/*
 * Copyright (c) 2002 Juli Mallett.  All rights reserved.
 *
 * This software was written by Juli Mallett <jmallett@FreeBSD.org> for the
 * FreeBSD project.  Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that the following
 * conditions are met:
 *
 * 1. Redistribution of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistribution in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>

#include <sys/param.h>
#include <sys/mount.h>
#include <sys/disklabel.h>
#include <sys/stat.h>

#include <ufsmount.h>
#include <dinode.h>
#include <fs.h>

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <libufs.h>


#define FS_UFS2_CIGAM 0x19015419 /* byte-reversed UFS2 magic number */


static int superblocks[] = SBLOCKSEARCH;


static void sbswapen(struct fs *fs)
{
	int i;
	fs->fs_firstfield             = (int32_t)bswap_32(fs->fs_firstfield);
	fs->fs_unused_1               = (int32_t)bswap_32(fs->fs_unused_1);
	fs->fs_sblkno                 = (int32_t)bswap_32(fs->fs_sblkno);
	fs->fs_cblkno                 = (int32_t)bswap_32(fs->fs_cblkno);
	fs->fs_iblkno                 = (int32_t)bswap_32(fs->fs_iblkno);
	fs->fs_dblkno                 = (int32_t)bswap_32(fs->fs_dblkno);
	fs->fs_old_cgoffset           = (int32_t)bswap_32(fs->fs_old_cgoffset);
	fs->fs_old_cgmask             = (int32_t)bswap_32(fs->fs_old_cgmask);
	fs->fs_old_time               = (int32_t)bswap_32(fs->fs_old_time);
	fs->fs_old_size               = (int32_t)bswap_32(fs->fs_old_size);
	fs->fs_old_dsize              = (int32_t)bswap_32(fs->fs_old_dsize);
	fs->fs_ncg                    = (int32_t)bswap_32(fs->fs_ncg);
	fs->fs_bsize                  = (int32_t)bswap_32(fs->fs_bsize);
	fs->fs_fsize                  = (int32_t)bswap_32(fs->fs_fsize);
	fs->fs_frag                   = (int32_t)bswap_32(fs->fs_frag);
	fs->fs_minfree                = (int32_t)bswap_32(fs->fs_minfree);
	fs->fs_old_rotdelay           = (int32_t)bswap_32(fs->fs_old_rotdelay);
	fs->fs_old_rps                = (int32_t)bswap_32(fs->fs_old_rps);
	fs->fs_bmask                  = (int32_t)bswap_32(fs->fs_bmask);
	fs->fs_fmask                  = (int32_t)bswap_32(fs->fs_fmask);
	fs->fs_bshift                 = (int32_t)bswap_32(fs->fs_bshift);
	fs->fs_fshift                 = (int32_t)bswap_32(fs->fs_fshift);
	fs->fs_maxcontig              = (int32_t)bswap_32(fs->fs_maxcontig);
	fs->fs_maxbpg                 = (int32_t)bswap_32(fs->fs_maxbpg);
	fs->fs_fragshift              = (int32_t)bswap_32(fs->fs_fragshift);
	fs->fs_fsbtodb                = (int32_t)bswap_32(fs->fs_fsbtodb);
	fs->fs_sbsize                 = (int32_t)bswap_32(fs->fs_sbsize);
	for (i = 0; i < 2; i++)
	  fs->fs_spare1[i]            = (int32_t)bswap_32(fs->fs_spare1[i]);
	fs->fs_nindir                 = (int32_t)bswap_32(fs->fs_nindir);
  fs->fs_inopb                  = (int32_t)bswap_32(fs->fs_inopb);
  fs->fs_old_nspf               = (int32_t)bswap_32(fs->fs_old_nspf);
  fs->fs_optim                  = (int32_t)bswap_32(fs->fs_optim);
  fs->fs_old_npsect             = (int32_t)bswap_32(fs->fs_old_npsect);
  fs->fs_old_interleave         = (int32_t)bswap_32(fs->fs_old_interleave);
  fs->fs_old_trackskew          = (int32_t)bswap_32(fs->fs_old_trackskew);
  for (i = 0; i < 2; i++)
	  fs->fs_id[i]                = (int32_t)bswap_32(fs->fs_id[i]);
  fs->fs_old_csaddr             = (int32_t)bswap_32(fs->fs_old_csaddr);
  fs->fs_cssize                 = (int32_t)bswap_32(fs->fs_cssize);
  fs->fs_cgsize                 = (int32_t)bswap_32(fs->fs_cgsize);
  fs->fs_spare2                 = (int32_t)bswap_32(fs->fs_spare2);
  fs->fs_old_nsect              = (int32_t)bswap_32(fs->fs_old_nsect);
  fs->fs_old_spc                = (int32_t)bswap_32(fs->fs_old_spc);
  fs->fs_old_ncyl               = (int32_t)bswap_32(fs->fs_old_ncyl);
  fs->fs_old_cpg                = (int32_t)bswap_32(fs->fs_old_cpg);
  fs->fs_ipg                    = (int32_t)bswap_32(fs->fs_ipg);
  fs->fs_fpg                    = (int32_t)bswap_32(fs->fs_fpg);
  fs->fs_old_cstotal.cs_ndir    = (int32_t)bswap_32(fs->fs_old_cstotal.cs_ndir);
  fs->fs_old_cstotal.cs_nbfree  = (int32_t)bswap_32(fs->fs_old_cstotal.cs_nbfree);
  fs->fs_old_cstotal.cs_nifree  = (int32_t)bswap_32(fs->fs_old_cstotal.cs_nifree);
  fs->fs_old_cstotal.cs_nffree  = (int32_t)bswap_32(fs->fs_old_cstotal.cs_nffree);
  fs->fs_swuid                  = (uint64_t)bswap_64(fs->fs_swuid);
  fs->fs_pad                    = (int32_t)bswap_32(fs->fs_pad);
  fs->fs_cgrotor                = (int32_t)bswap_32(fs->fs_cgrotor);
  fs->fs_old_cpc                = (int32_t)bswap_32(fs->fs_old_cpc);
  fs->fs_maxbsize               = (int32_t)bswap_32(fs->fs_maxbsize);
  fs->fs_unrefs                 = (int64_t)bswap_64(fs->fs_sblockloc);
	for (i = 0; i < 16; i++)
	  fs->fs_sparecon64[i]        = (int64_t)bswap_64(fs->fs_sparecon64[i]);
	fs->fs_sblockloc              = (int64_t)bswap_64(fs->fs_sblockloc);
	fs->fs_cstotal.cs_ndir        = (int64_t)bswap_64(fs->fs_cstotal.cs_ndir);
	fs->fs_cstotal.cs_nbfree      = (int64_t)bswap_64(fs->fs_cstotal.cs_nbfree);
	fs->fs_cstotal.cs_nifree      = (int64_t)bswap_64(fs->fs_cstotal.cs_nifree);
	fs->fs_cstotal.cs_nffree      = (int64_t)bswap_64(fs->fs_cstotal.cs_nffree);
	fs->fs_cstotal.cs_numclusters = (int64_t)bswap_64(fs->fs_cstotal.cs_numclusters);
	for (i = 0; i < 3; i++)
	  fs->fs_cstotal.cs_spare[i]  = (int64_t)bswap_64(fs->fs_cstotal.cs_spare[i]);
  fs->fs_time                   = (ufs_time_t)bswap_64(fs->fs_time);
  fs->fs_size                   = (int64_t)bswap_64(fs->fs_size);
  fs->fs_dsize                  = (int64_t)bswap_64(fs->fs_dsize);
  fs->fs_csaddr                 = (ufs2_daddr_t)bswap_64(fs->fs_csaddr);
  fs->fs_pendingblocks          = (int64_t)bswap_64(fs->fs_pendingblocks);
  fs->fs_pendinginodes          = (int32_t)bswap_32(fs->fs_pendinginodes);
  for (i = 0; i < FSMAXSNAP; i++)
	  fs->fs_snapinum[i]          = (int32_t)bswap_32(fs->fs_snapinum[i]);
  fs->fs_avgfilesize            = (int32_t)bswap_32(fs->fs_avgfilesize);
  fs->fs_avgfpdir               = (int32_t)bswap_32(fs->fs_avgfpdir);
  fs->fs_save_cgsize            = (int32_t)bswap_32(fs->fs_save_cgsize);
  for (i = 0; i < 26; i++)
	  fs->fs_sparecon32[i]        = (int32_t)bswap_32(fs->fs_sparecon32[i]);
  fs->fs_flags                  = (int32_t)bswap_32(fs->fs_flags);
  fs->fs_contigsumsize          = (int32_t)bswap_32(fs->fs_contigsumsize);
  fs->fs_maxsymlinklen          = (int32_t)bswap_32(fs->fs_maxsymlinklen);
  fs->fs_old_inodefmt           = (int32_t)bswap_32(fs->fs_old_inodefmt);
  fs->fs_maxfilesize            = (uint64_t)bswap_64(fs->fs_maxfilesize);
  fs->fs_qbmask                 = (int64_t)bswap_64(fs->fs_qbmask);
  fs->fs_qfmask                 = (int64_t)bswap_64(fs->fs_qfmask);
  fs->fs_state                  = (int32_t)bswap_32(fs->fs_state);
  fs->fs_old_postblformat       = (int32_t)bswap_32(fs->fs_old_postblformat);
  fs->fs_old_nrpos              = (int32_t)bswap_32(fs->fs_old_nrpos);
  for (i = 0; i < 2; i++)
	  fs->fs_spare5[i]            = (int32_t)bswap_32(fs->fs_spare5[i]);
  fs->fs_magic                  = (int32_t)bswap_32(fs->fs_magic);
}

int
sbread(struct uufsd *disk)
{
	struct fs *fs;
	int sb, superblock;

	ERROR(disk, NULL);

	fs = &disk->d_fs;
	superblock = superblocks[0];

	for (sb = 0; (superblock = superblocks[sb]) != -1; sb++) {
		if (bread(disk, superblock, disk->d_sb, SBLOCKSIZE) == -1) {
			ERROR(disk, "non-existent or truncated superblock");
			return (-1);
		}
		if (fs->fs_magic == FS_UFS2_CIGAM) {
			sbswapen(fs);
			disk->d_is_BE = 1;
		}
		if (fs->fs_magic == FS_UFS1_MAGIC)
			disk->d_ufs = 1;
		if (fs->fs_magic == FS_UFS2_MAGIC &&
		    fs->fs_sblockloc == superblock)
			disk->d_ufs = 2;
		if (fs->fs_bsize <= MAXBSIZE &&
		    (size_t)fs->fs_bsize >= sizeof(*fs)) {
			if (disk->d_ufs)
				break;
		}
		disk->d_ufs = 0;
	}
	if (superblock == -1 || disk->d_ufs == 0) {
		/*
		 * Other error cases will result in errno being set, here we
		 * must set it to indicate no superblock could be found with
		 * which to associate this disk/filesystem.
		 */
		ERROR(disk, "no usable known superblock found");
		errno = ENOENT;
		return (-1);
	}
	disk->d_bsize = fs->fs_fsize / fsbtodb(fs, 1);
	disk->d_sblock = superblock / disk->d_bsize;
	return (0);
}

int
sbwrite(struct uufsd *disk, int all)
{
	struct fs *fs;
	int i;

	ERROR(disk, NULL);

	fs = &disk->d_fs;

	if (!disk->d_sblock) {
		disk->d_sblock = disk->d_fs.fs_sblockloc / disk->d_bsize;
	}
	
	if (disk->d_is_BE)
	  sbswapen(fs);

	if (bwrite(disk, disk->d_sblock, fs, SBLOCKSIZE) == -1) {
		ERROR(disk, "failed to write superblock");
		return (-1);
	}
	if (all) {
		for (i = 0; i < fs->fs_ncg; i++)
			if (bwrite(disk, fsbtodb(fs, cgsblock(fs, i)),
			    fs, SBLOCKSIZE) == -1) {
				ERROR(disk, "failed to update a superblock");
				return (-1);
			}
	}
	return (0);
}
