Home | History | Annotate | Line # | Download | only in resize_ffs
      1 /*	$NetBSD: resize_ffs.c,v 1.58 2023/01/07 19:41:30 chs Exp $	*/
      2 /* From sources sent on February 17, 2003 */
      3 /*-
      4  * As its sole author, I explicitly place this code in the public
      5  *  domain.  Anyone may use it for any purpose (though I would
      6  *  appreciate credit where it is due).
      7  *
      8  *					der Mouse
      9  *
     10  *			       mouse (at) rodents.montreal.qc.ca
     11  *		     7D C8 61 52 5D E7 2D 39  4E F1 31 3E E8 B3 27 4B
     12  */
     13 /*
     14  * resize_ffs:
     15  *
     16  * Resize a file system.  Is capable of both growing and shrinking.
     17  *
     18  * Usage: resize_ffs [-s newsize] [-y] file_system
     19  *
     20  * Example: resize_ffs -s 29574 /dev/rsd1e
     21  *
     22  * newsize is in DEV_BSIZE units (ie, disk sectors, usually 512 bytes
     23  *  each).
     24  *
     25  * Note: this currently requires gcc to build, since it is written
     26  *  depending on gcc-specific features, notably nested function
     27  *  definitions (which in at least a few cases depend on the lexical
     28  *  scoping gcc provides, so they can't be trivially moved outside).
     29  *
     30  * Many thanks go to John Kohl <jtk (at) NetBSD.org> for finding bugs: the
     31  *  one responsible for the "realloccgblk: can't find blk in cyl"
     32  *  problem and a more minor one which left fs_dsize wrong when
     33  *  shrinking.  (These actually indicate bugs in fsck too - it should
     34  *  have caught and fixed them.)
     35  *
     36  */
     37 
     38 #include <sys/cdefs.h>
     39 __RCSID("$NetBSD: resize_ffs.c,v 1.58 2023/01/07 19:41:30 chs Exp $");
     40 
     41 #include <sys/disk.h>
     42 #include <sys/disklabel.h>
     43 #include <sys/dkio.h>
     44 #include <sys/ioctl.h>
     45 #include <sys/stat.h>
     46 #include <sys/mman.h>
     47 #include <sys/param.h>		/* MAXFRAG */
     48 #include <ufs/ffs/fs.h>
     49 #include <ufs/ffs/ffs_extern.h>
     50 #include <ufs/ufs/dir.h>
     51 #include <ufs/ufs/dinode.h>
     52 #include <ufs/ufs/ufs_bswap.h>	/* ufs_rw32 */
     53 
     54 #include <err.h>
     55 #include <errno.h>
     56 #include <fcntl.h>
     57 #include <stdio.h>
     58 #include <stdlib.h>
     59 #include <strings.h>
     60 #include <unistd.h>
     61 #include <util.h>
     62 
     63 #include "progress.h"
     64 
     65 /* new size of file system, in sectors */
     66 static int64_t newsize;
     67 
     68 /* fd open onto disk device or file */
     69 static int fd;
     70 
     71 /* disk device or file path */
     72 const char *special;
     73 
     74 /* must we break up big I/O operations - see checksmallio() */
     75 static int smallio;
     76 
     77 /* size of a cg, in bytes, rounded up to a frag boundary */
     78 static int cgblksz;
     79 
     80 /* possible superblock localtions */
     81 static int search[] = SBLOCKSEARCH;
     82 /* location of the superblock */
     83 static off_t where;
     84 
     85 /* Superblocks. */
     86 static struct fs *oldsb;	/* before we started */
     87 static struct fs *newsb;	/* copy to work with */
     88 /* Buffer to hold the above.  Make sure it's aligned correctly. */
     89 static char sbbuf[2 * SBLOCKSIZE]
     90 	__attribute__((__aligned__(__alignof__(struct fs))));
     91 
     92 union dinode {
     93 	struct ufs1_dinode dp1;
     94 	struct ufs2_dinode dp2;
     95 };
     96 #define DIP(dp, field)							      \
     97 	((is_ufs2) ?							      \
     98 	    (dp)->dp2.field : (dp)->dp1.field)
     99 
    100 #define DIP_ASSIGN(dp, field, value)					      \
    101 	do {								      \
    102 		if (is_ufs2)						      \
    103 			(dp)->dp2.field = (value);			      \
    104 		else							      \
    105 			(dp)->dp1.field = (value);			      \
    106 	} while (0)
    107 
    108 /* a cg's worth of brand new squeaky-clean inodes */
    109 static struct ufs1_dinode *zinodes1;
    110 static struct ufs2_dinode *zinodes2;
    111 
    112 /* pointers to the in-core cgs, read off disk and possibly modified */
    113 static struct cg **cgs;
    114 
    115 /* pointer to csum array - the stuff pointed to on-disk by fs_csaddr */
    116 static struct csum *csums;
    117 
    118 /* per-cg flags, indexed by cg number */
    119 static unsigned char *cgflags;
    120 #define CGF_DIRTY   0x01	/* needs to be written to disk */
    121 #define CGF_BLKMAPS 0x02	/* block bitmaps need rebuilding */
    122 #define CGF_INOMAPS 0x04	/* inode bitmaps need rebuilding */
    123 
    124 /* when shrinking, these two arrays record how we want blocks to move.	 */
    125 /*  if blkmove[i] is j, the frag that started out as frag #i should end	 */
    126 /*  up as frag #j.  inomove[i]=j means, similarly, that the inode that	 */
    127 /*  started out as inode i should end up as inode j.			 */
    128 static unsigned int *blkmove;
    129 static unsigned int *inomove;
    130 
    131 /* in-core copies of all inodes in the fs, indexed by inumber */
    132 union dinode *inodes;
    133 
    134 void *ibuf;	/* ptr to fs block-sized buffer for reading/writing inodes */
    135 
    136 /* byteswapped inodes */
    137 union dinode *sinodes;
    138 
    139 /* per-inode flags, indexed by inumber */
    140 static unsigned char *iflags;
    141 #define IF_DIRTY  0x01		/* needs to be written to disk */
    142 #define IF_BDIRTY 0x02		/* like DIRTY, but is set on first inode in a
    143 				 * block of inodes, and applies to the whole
    144 				 * block. */
    145 
    146 /* resize_ffs works directly on dinodes, adapt blksize() */
    147 #define dblksize(fs, dip, lbn, filesize) \
    148 	(((lbn) >= UFS_NDADDR || (uint64_t)(filesize) >= ffs_lblktosize(fs, (lbn) + 1)) \
    149 	    ? (fs)->fs_bsize						       \
    150 	    : (ffs_fragroundup(fs, ffs_blkoff(fs, (filesize)))))
    151 
    152 
    153 /*
    154  * Number of disk sectors per block/fragment
    155  */
    156 #define NSPB(fs)	(FFS_FSBTODB((fs),1) << (fs)->fs_fragshift)
    157 #define NSPF(fs)	(FFS_FSBTODB((fs),1))
    158 
    159 /* global flags */
    160 int is_ufs2 = 0;
    161 int needswap = 0;
    162 int verbose = 0;
    163 int progress = 0;
    164 
    165 static void usage(void) __dead;
    166 
    167 /*
    168  * See if we need to break up large I/O operations.  This should never
    169  *  be needed, but under at least one <version,platform> combination,
    170  *  large enough disk transfers to the raw device hang.  So if we're
    171  *  talking to a character special device, play it safe; in this case,
    172  *  readat() and writeat() break everything up into pieces no larger
    173  *  than 8K, doing multiple syscalls for larger operations.
    174  */
    175 static void
    176 checksmallio(void)
    177 {
    178 	struct stat stb;
    179 
    180 	fstat(fd, &stb);
    181 	smallio = ((stb.st_mode & S_IFMT) == S_IFCHR);
    182 }
    183 
    184 static int
    185 isplainfile(void)
    186 {
    187 	struct stat stb;
    188 
    189 	fstat(fd, &stb);
    190 	return S_ISREG(stb.st_mode);
    191 }
    192 /*
    193  * Read size bytes starting at blkno into buf.  blkno is in DEV_BSIZE
    194  *  units, ie, after FFS_FSBTODB(); size is in bytes.
    195  */
    196 static void
    197 readat(off_t blkno, void *buf, int size)
    198 {
    199 	/* Seek to the correct place. */
    200 	if (lseek(fd, blkno * DEV_BSIZE, L_SET) < 0)
    201 		err(EXIT_FAILURE, "lseek failed");
    202 
    203 	/* See if we have to break up the transfer... */
    204 	if (smallio) {
    205 		char *bp;	/* pointer into buf */
    206 		int left;	/* bytes left to go */
    207 		int n;		/* number to do this time around */
    208 		int rv;		/* syscall return value */
    209 		bp = buf;
    210 		left = size;
    211 		while (left > 0) {
    212 			n = (left > 8192) ? 8192 : left;
    213 			rv = read(fd, bp, n);
    214 			if (rv < 0)
    215 				err(EXIT_FAILURE, "read failed");
    216 			if (rv != n)
    217 				errx(EXIT_FAILURE,
    218 				    "read: wanted %d, got %d", n, rv);
    219 			bp += n;
    220 			left -= n;
    221 		}
    222 	} else {
    223 		int rv;
    224 		rv = read(fd, buf, size);
    225 		if (rv < 0)
    226 			err(EXIT_FAILURE, "read failed");
    227 		if (rv != size)
    228 			errx(EXIT_FAILURE, "read: wanted %d, got %d",
    229 			    size, rv);
    230 	}
    231 }
    232 /*
    233  * Write size bytes from buf starting at blkno.  blkno is in DEV_BSIZE
    234  *  units, ie, after FFS_FSBTODB(); size is in bytes.
    235  */
    236 static void
    237 writeat(off_t blkno, const void *buf, int size)
    238 {
    239 	/* Seek to the correct place. */
    240 	if (lseek(fd, blkno * DEV_BSIZE, L_SET) < 0)
    241 		err(EXIT_FAILURE, "lseek failed");
    242 	/* See if we have to break up the transfer... */
    243 	if (smallio) {
    244 		const char *bp;	/* pointer into buf */
    245 		int left;	/* bytes left to go */
    246 		int n;		/* number to do this time around */
    247 		int rv;		/* syscall return value */
    248 		bp = buf;
    249 		left = size;
    250 		while (left > 0) {
    251 			n = (left > 8192) ? 8192 : left;
    252 			rv = write(fd, bp, n);
    253 			if (rv < 0)
    254 				err(EXIT_FAILURE, "write failed");
    255 			if (rv != n)
    256 				errx(EXIT_FAILURE,
    257 				    "write: wanted %d, got %d", n, rv);
    258 			bp += n;
    259 			left -= n;
    260 		}
    261 	} else {
    262 		int rv;
    263 		rv = write(fd, buf, size);
    264 		if (rv < 0)
    265 			err(EXIT_FAILURE, "write failed");
    266 		if (rv != size)
    267 			errx(EXIT_FAILURE,
    268 			    "write: wanted %d, got %d", size, rv);
    269 	}
    270 }
    271 /*
    272  * Never-fail versions of malloc() and realloc(), and an allocation
    273  *  routine (which also never fails) for allocating memory that will
    274  *  never be freed until exit.
    275  */
    276 
    277 /*
    278  * Never-fail malloc.
    279  */
    280 static void *
    281 nfmalloc(size_t nb, const char *tag)
    282 {
    283 	void *rv;
    284 
    285 	rv = malloc(nb);
    286 	if (rv)
    287 		return (rv);
    288 	err(EXIT_FAILURE, "Can't allocate %lu bytes for %s",
    289 	    (unsigned long int) nb, tag);
    290 }
    291 /*
    292  * Never-fail realloc.
    293  */
    294 static void *
    295 nfrealloc(void *blk, size_t nb, const char *tag)
    296 {
    297 	void *rv;
    298 
    299 	rv = realloc(blk, nb);
    300 	if (rv)
    301 		return (rv);
    302 	err(EXIT_FAILURE, "Can't re-allocate %lu bytes for %s",
    303 	    (unsigned long int) nb, tag);
    304 }
    305 /*
    306  * Allocate memory that will never be freed or reallocated.  Arguably
    307  *  this routine should handle small allocations by chopping up pages,
    308  *  but that's not worth the bother; it's not called more than a
    309  *  handful of times per run, and if the allocations are that small the
    310  *  waste in giving each one its own page is ignorable.
    311  */
    312 static void *
    313 alloconce(size_t nb, const char *tag)
    314 {
    315 	void *rv;
    316 
    317 	rv = mmap(0, nb, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
    318 	if (rv != MAP_FAILED)
    319 		return (rv);
    320 	err(EXIT_FAILURE, "Can't map %lu bytes for %s",
    321 	    (unsigned long int) nb, tag);
    322 }
    323 /*
    324  * Load the cgs and csums off disk.  Also allocates the space to load
    325  *  them into and initializes the per-cg flags.
    326  */
    327 static void
    328 loadcgs(void)
    329 {
    330 	uint32_t cg;
    331 	char *cgp;
    332 
    333 	cgblksz = roundup(oldsb->fs_cgsize, oldsb->fs_fsize);
    334 	cgs = nfmalloc(oldsb->fs_ncg * sizeof(*cgs), "cg pointers");
    335 	cgp = alloconce(oldsb->fs_ncg * cgblksz, "cgs");
    336 	cgflags = nfmalloc(oldsb->fs_ncg, "cg flags");
    337 	csums = nfmalloc(oldsb->fs_cssize, "cg summary");
    338 	for (cg = 0; cg < oldsb->fs_ncg; cg++) {
    339 		cgs[cg] = (struct cg *) cgp;
    340 		readat(FFS_FSBTODB(oldsb, cgtod(oldsb, cg)), cgp, cgblksz);
    341 		if (needswap)
    342 			ffs_cg_swap(cgs[cg],cgs[cg],oldsb);
    343 		cgflags[cg] = 0;
    344 		cgp += cgblksz;
    345 	}
    346 	readat(FFS_FSBTODB(oldsb, oldsb->fs_csaddr), csums, oldsb->fs_cssize);
    347 	if (needswap)
    348 		ffs_csum_swap(csums,csums,oldsb->fs_cssize);
    349 }
    350 /*
    351  * Set n bits, starting with bit #base, in the bitmap pointed to by
    352  *  bitvec (which is assumed to be large enough to include bits base
    353  *  through base+n-1).
    354  */
    355 static void
    356 set_bits(unsigned char *bitvec, unsigned int base, unsigned int n)
    357 {
    358 	if (n < 1)
    359 		return;		/* nothing to do */
    360 	if (base & 7) {		/* partial byte at beginning */
    361 		if (n <= 8 - (base & 7)) {	/* entirely within one byte */
    362 			bitvec[base >> 3] |= (~((~0U) << n)) << (base & 7);
    363 			return;
    364 		}
    365 		bitvec[base >> 3] |= (~0U) << (base & 7);
    366 		n -= 8 - (base & 7);
    367 		base = (base & ~7) + 8;
    368 	}
    369 	if (n >= 8) {		/* do full bytes */
    370 		memset(bitvec + (base >> 3), 0xff, n >> 3);
    371 		base += n & ~7;
    372 		n &= 7;
    373 	}
    374 	if (n) {		/* partial byte at end */
    375 		bitvec[base >> 3] |= ~((~0U) << n);
    376 	}
    377 }
    378 /*
    379  * Clear n bits, starting with bit #base, in the bitmap pointed to by
    380  *  bitvec (which is assumed to be large enough to include bits base
    381  *  through base+n-1).  Code parallels set_bits().
    382  */
    383 static void
    384 clr_bits(unsigned char *bitvec, int base, int n)
    385 {
    386 	if (n < 1)
    387 		return;
    388 	if (base & 7) {
    389 		if (n <= 8 - (base & 7)) {
    390 			bitvec[base >> 3] &= ~((~((~0U) << n)) << (base & 7));
    391 			return;
    392 		}
    393 		bitvec[base >> 3] &= ~((~0U) << (base & 7));
    394 		n -= 8 - (base & 7);
    395 		base = (base & ~7) + 8;
    396 	}
    397 	if (n >= 8) {
    398 		memset(bitvec + (base >> 3), 0, n >> 3);
    399 		base += n & ~7;
    400 		n &= 7;
    401 	}
    402 	if (n) {
    403 		bitvec[base >> 3] &= (~0U) << n;
    404 	}
    405 }
    406 /*
    407  * Test whether bit #bit is set in the bitmap pointed to by bitvec.
    408  */
    409 static int
    410 bit_is_set(unsigned char *bitvec, int bit)
    411 {
    412 	return (bitvec[bit >> 3] & (1 << (bit & 7)));
    413 }
    414 /*
    415  * Test whether bit #bit is clear in the bitmap pointed to by bitvec.
    416  */
    417 static int
    418 bit_is_clr(unsigned char *bitvec, int bit)
    419 {
    420 	return (!bit_is_set(bitvec, bit));
    421 }
    422 /*
    423  * Test whether a whole block of bits is set in a bitmap.  This is
    424  *  designed for testing (aligned) disk blocks in a bit-per-frag
    425  *  bitmap; it has assumptions wired into it based on that, essentially
    426  *  that the entire block fits into a single byte.  This returns true
    427  *  iff _all_ the bits are set; it is not just the complement of
    428  *  blk_is_clr on the same arguments (unless blkfrags==1).
    429  */
    430 static int
    431 blk_is_set(unsigned char *bitvec, int blkbase, int blkfrags)
    432 {
    433 	unsigned int mask;
    434 
    435 	mask = (~((~0U) << blkfrags)) << (blkbase & 7);
    436 	return ((bitvec[blkbase >> 3] & mask) == mask);
    437 }
    438 /*
    439  * Test whether a whole block of bits is clear in a bitmap.  See
    440  *  blk_is_set (above) for assumptions.  This returns true iff _all_
    441  *  the bits are clear; it is not just the complement of blk_is_set on
    442  *  the same arguments (unless blkfrags==1).
    443  */
    444 static int
    445 blk_is_clr(unsigned char *bitvec, int blkbase, int blkfrags)
    446 {
    447 	unsigned int mask;
    448 
    449 	mask = (~((~0U) << blkfrags)) << (blkbase & 7);
    450 	return ((bitvec[blkbase >> 3] & mask) == 0);
    451 }
    452 /*
    453  * Initialize a new cg.  Called when growing.  Assumes memory has been
    454  *  allocated but not otherwise set up.  This code sets the fields of
    455  *  the cg, initializes the bitmaps (and cluster summaries, if
    456  *  applicable), updates both per-cylinder summary info and the global
    457  *  summary info in newsb; it also writes out new inodes for the cg.
    458  *
    459  * This code knows it can never be called for cg 0, which makes it a
    460  *  bit simpler than it would otherwise be.
    461  */
    462 static void
    463 initcg(uint32_t cgn)
    464 {
    465 	struct cg *cg;		/* The in-core cg, of course */
    466 	int64_t base;		/* Disk address of cg base */
    467 	int64_t dlow;		/* Size of pre-cg data area */
    468 	int64_t dhigh;		/* Offset of post-inode data area, from base */
    469 	int64_t dmax;		/* Offset of end of post-inode data area */
    470 	int i;			/* Generic loop index */
    471 	int n;			/* Generic count */
    472 	int start;		/* start of cg maps */
    473 
    474 	cg = cgs[cgn];
    475 	/* Place the data areas */
    476 	base = cgbase(newsb, cgn);
    477 	dlow = cgsblock(newsb, cgn) - base;
    478 	dhigh = cgdmin(newsb, cgn) - base;
    479 	dmax = newsb->fs_size - base;
    480 	if (dmax > newsb->fs_fpg)
    481 		dmax = newsb->fs_fpg;
    482 	start = (unsigned char *)&cg->cg_space[0] - (unsigned char *) cg;
    483 	/*
    484          * Clear out the cg - assumes all-0-bytes is the correct way
    485          * to initialize fields we don't otherwise touch, which is
    486          * perhaps not the right thing to do, but it's what fsck and
    487          * mkfs do.
    488          */
    489 	memset(cg, 0, newsb->fs_cgsize);
    490 	if (newsb->fs_old_flags & FS_FLAGS_UPDATED)
    491 		cg->cg_time = newsb->fs_time;
    492 	cg->cg_magic = CG_MAGIC;
    493 	cg->cg_cgx = cgn;
    494 	cg->cg_niblk = newsb->fs_ipg;
    495 	cg->cg_ndblk = dmax;
    496 
    497 	if (is_ufs2) {
    498 		cg->cg_time = newsb->fs_time;
    499 		cg->cg_initediblk = newsb->fs_ipg < 2 * FFS_INOPB(newsb) ?
    500 		    newsb->fs_ipg : 2 * FFS_INOPB(newsb);
    501 		cg->cg_iusedoff = start;
    502 	} else {
    503 		cg->cg_old_time = newsb->fs_time;
    504 		cg->cg_old_niblk = cg->cg_niblk;
    505 		cg->cg_niblk = 0;
    506 		cg->cg_initediblk = 0;
    507 
    508 
    509 		cg->cg_old_ncyl = newsb->fs_old_cpg;
    510 		/* Update the cg_old_ncyl value for the last cylinder. */
    511 		if (cgn == newsb->fs_ncg - 1) {
    512 			if ((newsb->fs_old_flags & FS_FLAGS_UPDATED) == 0)
    513 				cg->cg_old_ncyl = newsb->fs_old_ncyl %
    514 				    newsb->fs_old_cpg;
    515 		}
    516 
    517 		/* Set up the bitmap pointers.  We have to be careful
    518 		 * to lay out the cg _exactly_ the way mkfs and fsck
    519 		 * do it, since fsck compares the _entire_ cg against
    520 		 * a recomputed cg, and whines if there is any
    521 		 * mismatch, including the bitmap offsets. */
    522 		/* XXX update this comment when fsck is fixed */
    523 		cg->cg_old_btotoff = start;
    524 		cg->cg_old_boff = cg->cg_old_btotoff
    525 		    + (newsb->fs_old_cpg * sizeof(int32_t));
    526 		cg->cg_iusedoff = cg->cg_old_boff +
    527 		    (newsb->fs_old_cpg * newsb->fs_old_nrpos * sizeof(int16_t));
    528 	}
    529 	cg->cg_freeoff = cg->cg_iusedoff + howmany(newsb->fs_ipg, NBBY);
    530 	if (newsb->fs_contigsumsize > 0) {
    531 		cg->cg_nclusterblks = cg->cg_ndblk / newsb->fs_frag;
    532 		cg->cg_clustersumoff = cg->cg_freeoff +
    533 		    howmany(newsb->fs_fpg, NBBY) - sizeof(int32_t);
    534 		cg->cg_clustersumoff =
    535 		    roundup(cg->cg_clustersumoff, sizeof(int32_t));
    536 		cg->cg_clusteroff = cg->cg_clustersumoff +
    537 		    ((newsb->fs_contigsumsize + 1) * sizeof(int32_t));
    538 		cg->cg_nextfreeoff = cg->cg_clusteroff +
    539 		    howmany(ffs_fragstoblks(newsb,newsb->fs_fpg), NBBY);
    540 		n = dlow / newsb->fs_frag;
    541 		if (n > 0) {
    542 			set_bits(cg_clustersfree(cg, 0), 0, n);
    543 			cg_clustersum(cg, 0)[(n > newsb->fs_contigsumsize) ?
    544 			    newsb->fs_contigsumsize : n]++;
    545 		}
    546 	} else {
    547 		cg->cg_nextfreeoff = cg->cg_freeoff +
    548 		    howmany(newsb->fs_fpg, NBBY);
    549 	}
    550 	/* Mark the data areas as free; everything else is marked busy by the
    551 	 * memset() up at the top. */
    552 	set_bits(cg_blksfree(cg, 0), 0, dlow);
    553 	set_bits(cg_blksfree(cg, 0), dhigh, dmax - dhigh);
    554 	/* Initialize summary info */
    555 	cg->cg_cs.cs_ndir = 0;
    556 	cg->cg_cs.cs_nifree = newsb->fs_ipg;
    557 	cg->cg_cs.cs_nbfree = dlow / newsb->fs_frag;
    558 	cg->cg_cs.cs_nffree = 0;
    559 
    560 	/* This is the simplest way of doing this; we perhaps could
    561 	 * compute the correct cg_blktot()[] and cg_blks()[] values
    562 	 * other ways, but it would be complicated and hardly seems
    563 	 * worth the effort.  (The reason there isn't
    564 	 * frag-at-beginning and frag-at-end code here, like the code
    565 	 * below for the post-inode data area, is that the pre-sb data
    566 	 * area always starts at 0, and thus is block-aligned, and
    567 	 * always ends at the sb, which is block-aligned.) */
    568 	if ((newsb->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
    569 		int64_t di;
    570 
    571 		for (di = 0; di < dlow; di += newsb->fs_frag) {
    572 			old_cg_blktot(cg, 0)[old_cbtocylno(newsb, di)]++;
    573 			old_cg_blks(newsb, cg,
    574 			    old_cbtocylno(newsb, di),
    575 			    0)[old_cbtorpos(newsb, di)]++;
    576 		}
    577 	}
    578 
    579 	/* Deal with a partial block at the beginning of the post-inode area.
    580 	 * I'm not convinced this can happen - I think the inodes are always
    581 	 * block-aligned and always an integral number of blocks - but it's
    582 	 * cheap to do the right thing just in case. */
    583 	if (dhigh % newsb->fs_frag) {
    584 		n = newsb->fs_frag - (dhigh % newsb->fs_frag);
    585 		cg->cg_frsum[n]++;
    586 		cg->cg_cs.cs_nffree += n;
    587 		dhigh += n;
    588 	}
    589 	n = (dmax - dhigh) / newsb->fs_frag;
    590 	/* We have n full-size blocks in the post-inode data area. */
    591 	if (n > 0) {
    592 		cg->cg_cs.cs_nbfree += n;
    593 		if (newsb->fs_contigsumsize > 0) {
    594 			i = dhigh / newsb->fs_frag;
    595 			set_bits(cg_clustersfree(cg, 0), i, n);
    596 			cg_clustersum(cg, 0)[(n > newsb->fs_contigsumsize) ?
    597 			    newsb->fs_contigsumsize : n]++;
    598 		}
    599 		for (i = n; i > 0; i--) {
    600 			if (is_ufs2 == 0) {
    601 				old_cg_blktot(cg, 0)[old_cbtocylno(newsb,
    602 					    dhigh)]++;
    603 				old_cg_blks(newsb, cg,
    604 				    old_cbtocylno(newsb, dhigh),
    605 				    0)[old_cbtorpos(newsb,
    606 					    dhigh)]++;
    607 			}
    608 			dhigh += newsb->fs_frag;
    609 		}
    610 	}
    611 	/* Deal with any leftover frag at the end of the cg. */
    612 	i = dmax - dhigh;
    613 	if (i) {
    614 		cg->cg_frsum[i]++;
    615 		cg->cg_cs.cs_nffree += i;
    616 	}
    617 	/* Update the csum info. */
    618 	csums[cgn] = cg->cg_cs;
    619 	newsb->fs_cstotal.cs_nffree += cg->cg_cs.cs_nffree;
    620 	newsb->fs_cstotal.cs_nbfree += cg->cg_cs.cs_nbfree;
    621 	newsb->fs_cstotal.cs_nifree += cg->cg_cs.cs_nifree;
    622 	if (is_ufs2) {
    623 		/* Write out the cleared inodes. */
    624 		writeat(FFS_FSBTODB(newsb, cgimin(newsb, cgn)), zinodes2,
    625 		    cg->cg_initediblk * sizeof(*zinodes2));
    626 	} else {
    627 		/* Write out the cleared inodes. */
    628 		writeat(FFS_FSBTODB(newsb, cgimin(newsb, cgn)), zinodes1,
    629 		    newsb->fs_ipg * sizeof(*zinodes1));
    630 	}
    631 	/* Dirty the cg. */
    632 	cgflags[cgn] |= CGF_DIRTY;
    633 }
    634 /*
    635  * Find free space, at least nfrags consecutive frags of it.  Pays no
    636  *  attention to block boundaries, but refuses to straddle cg
    637  *  boundaries, even if the disk blocks involved are in fact
    638  *  consecutive.  Return value is the frag number of the first frag of
    639  *  the block, or -1 if no space was found.  Uses newsb for sb values,
    640  *  and assumes the cgs[] structures correctly describe the area to be
    641  *  searched.
    642  *
    643  * XXX is there a bug lurking in the ignoring of block boundaries by
    644  *  the routine used by fragmove() in evict_data()?  Can an end-of-file
    645  *  frag legally straddle a block boundary?  If not, this should be
    646  *  cloned and fixed to stop at block boundaries for that use.  The
    647  *  current one may still be needed for csum info motion, in case that
    648  *  takes up more than a whole block (is the csum info allowed to begin
    649  *  partway through a block and continue into the following block?).
    650  *
    651  * If we wrap off the end of the file system back to the beginning, we
    652  *  can end up searching the end of the file system twice.  I ignore
    653  *  this inefficiency, since if that happens we're going to croak with
    654  *  a no-space error anyway, so it happens at most once.
    655  */
    656 static int
    657 find_freespace(unsigned int nfrags)
    658 {
    659 	static int hand = 0;	/* hand rotates through all frags in the fs */
    660 	int cgsize;		/* size of the cg hand currently points into */
    661 	uint32_t cgn;		/* number of cg hand currently points into */
    662 	int fwc;		/* frag-within-cg number of frag hand points
    663 				 * to */
    664 	unsigned int run;	/* length of run of free frags seen so far */
    665 	int secondpass;		/* have we wrapped from end of fs to
    666 				 * beginning? */
    667 	unsigned char *bits;	/* cg_blksfree()[] for cg hand points into */
    668 
    669 	cgn = dtog(newsb, hand);
    670 	fwc = dtogd(newsb, hand);
    671 	secondpass = (hand == 0);
    672 	run = 0;
    673 	bits = cg_blksfree(cgs[cgn], 0);
    674 	cgsize = cgs[cgn]->cg_ndblk;
    675 	while (1) {
    676 		if (bit_is_set(bits, fwc)) {
    677 			run++;
    678 			if (run >= nfrags)
    679 				return (hand + 1 - run);
    680 		} else {
    681 			run = 0;
    682 		}
    683 		hand++;
    684 		fwc++;
    685 		if (fwc >= cgsize) {
    686 			fwc = 0;
    687 			cgn++;
    688 			if (cgn >= newsb->fs_ncg) {
    689 				hand = 0;
    690 				if (secondpass)
    691 					return (-1);
    692 				secondpass = 1;
    693 				cgn = 0;
    694 			}
    695 			bits = cg_blksfree(cgs[cgn], 0);
    696 			cgsize = cgs[cgn]->cg_ndblk;
    697 			run = 0;
    698 		}
    699 	}
    700 }
    701 /*
    702  * Find a free block of disk space.  Finds an entire block of frags,
    703  *  all of which are free.  Return value is the frag number of the
    704  *  first frag of the block, or -1 if no space was found.  Uses newsb
    705  *  for sb values, and assumes the cgs[] structures correctly describe
    706  *  the area to be searched.
    707  *
    708  * See find_freespace(), above, for remarks about hand wrapping around.
    709  */
    710 static int
    711 find_freeblock(void)
    712 {
    713 	static int hand = 0;	/* hand rotates through all frags in fs */
    714 	uint32_t cgn;		/* cg number of cg hand points into */
    715 	int fwc;		/* frag-within-cg number of frag hand points
    716 				 * to */
    717 	int cgsize;		/* size of cg hand points into */
    718 	int secondpass;		/* have we wrapped from end to beginning? */
    719 	unsigned char *bits;	/* cg_blksfree()[] for cg hand points into */
    720 
    721 	cgn = dtog(newsb, hand);
    722 	fwc = dtogd(newsb, hand);
    723 	secondpass = (hand == 0);
    724 	bits = cg_blksfree(cgs[cgn], 0);
    725 	cgsize = ffs_blknum(newsb, cgs[cgn]->cg_ndblk);
    726 	while (1) {
    727 		if (blk_is_set(bits, fwc, newsb->fs_frag))
    728 			return (hand);
    729 		fwc += newsb->fs_frag;
    730 		hand += newsb->fs_frag;
    731 		if (fwc >= cgsize) {
    732 			fwc = 0;
    733 			cgn++;
    734 			if (cgn >= newsb->fs_ncg) {
    735 				hand = 0;
    736 				if (secondpass)
    737 					return (-1);
    738 				secondpass = 1;
    739 				cgn = 0;
    740 			}
    741 			bits = cg_blksfree(cgs[cgn], 0);
    742 			cgsize = ffs_blknum(newsb, cgs[cgn]->cg_ndblk);
    743 		}
    744 	}
    745 }
    746 /*
    747  * Find a free inode, returning its inumber or -1 if none was found.
    748  *  Uses newsb for sb values, and assumes the cgs[] structures
    749  *  correctly describe the area to be searched.
    750  *
    751  * See find_freespace(), above, for remarks about hand wrapping around.
    752  */
    753 static int
    754 find_freeinode(void)
    755 {
    756 	static int hand = 0;	/* hand rotates through all inodes in fs */
    757 	uint32_t cgn;		/* cg number of cg hand points into */
    758 	uint32_t iwc;		/* inode-within-cg number of inode hand points
    759 				 * to */
    760 	int secondpass;		/* have we wrapped from end to beginning? */
    761 	unsigned char *bits;	/* cg_inosused()[] for cg hand points into */
    762 
    763 	cgn = hand / newsb->fs_ipg;
    764 	iwc = hand % newsb->fs_ipg;
    765 	secondpass = (hand == 0);
    766 	bits = cg_inosused(cgs[cgn], 0);
    767 	while (1) {
    768 		if (bit_is_clr(bits, iwc))
    769 			return (hand);
    770 		hand++;
    771 		iwc++;
    772 		if (iwc >= newsb->fs_ipg) {
    773 			iwc = 0;
    774 			cgn++;
    775 			if (cgn >= newsb->fs_ncg) {
    776 				hand = 0;
    777 				if (secondpass)
    778 					return (-1);
    779 				secondpass = 1;
    780 				cgn = 0;
    781 			}
    782 			bits = cg_inosused(cgs[cgn], 0);
    783 		}
    784 	}
    785 }
    786 /*
    787  * Mark a frag as free.  Sets the frag's bit in the cg_blksfree bitmap
    788  *  for the appropriate cg, and marks the cg as dirty.
    789  */
    790 static void
    791 free_frag(int fno)
    792 {
    793 	int cgn;
    794 
    795 	cgn = dtog(newsb, fno);
    796 	set_bits(cg_blksfree(cgs[cgn], 0), dtogd(newsb, fno), 1);
    797 	cgflags[cgn] |= CGF_DIRTY | CGF_BLKMAPS;
    798 }
    799 /*
    800  * Allocate a frag.  Clears the frag's bit in the cg_blksfree bitmap
    801  *  for the appropriate cg, and marks the cg as dirty.
    802  */
    803 static void
    804 alloc_frag(int fno)
    805 {
    806 	int cgn;
    807 
    808 	cgn = dtog(newsb, fno);
    809 	clr_bits(cg_blksfree(cgs[cgn], 0), dtogd(newsb, fno), 1);
    810 	cgflags[cgn] |= CGF_DIRTY | CGF_BLKMAPS;
    811 }
    812 /*
    813  * Fix up the csum array.  If shrinking, this involves freeing zero or
    814  *  more frags; if growing, it involves allocating them, or if the
    815  *  frags being grown into aren't free, finding space elsewhere for the
    816  *  csum info.  (If the number of occupied frags doesn't change,
    817  *  nothing happens here.)
    818  */
    819 static void
    820 csum_fixup(void)
    821 {
    822 	int nold;		/* # frags in old csum info */
    823 	int ntot;		/* # frags in new csum info */
    824 	int nnew;		/* ntot-nold */
    825 	int newloc;		/* new location for csum info, if necessary */
    826 	int i;			/* generic loop index */
    827 	int j;			/* generic loop index */
    828 	int f;			/* "from" frag number, if moving */
    829 	int t;			/* "to" frag number, if moving */
    830 	int cgn;		/* cg number, used when shrinking */
    831 
    832 	ntot = howmany(newsb->fs_cssize, newsb->fs_fsize);
    833 	nold = howmany(oldsb->fs_cssize, newsb->fs_fsize);
    834 	nnew = ntot - nold;
    835 	/* First, if there's no change in frag counts, it's easy. */
    836 	if (nnew == 0)
    837 		return;
    838 	/* Next, if we're shrinking, it's almost as easy.  Just free up any
    839 	 * frags in the old area we no longer need. */
    840 	if (nnew < 0) {
    841 		for ((i = newsb->fs_csaddr + ntot - 1), (j = nnew);
    842 		    j < 0;
    843 		    i--, j++) {
    844 			free_frag(i);
    845 		}
    846 		return;
    847 	}
    848 	/* We must be growing.  Check to see that the new csum area fits
    849 	 * within the file system.  I think this can never happen, since for
    850 	 * the csum area to grow, we must be adding at least one cg, so the
    851 	 * old csum area can't be this close to the end of the new file system.
    852 	 * But it's a cheap check. */
    853 	/* XXX what if csum info is at end of cg and grows into next cg, what
    854 	 * if it spills over onto the next cg's backup superblock?  Can this
    855 	 * happen? */
    856 	if (newsb->fs_csaddr + ntot <= newsb->fs_size) {
    857 		/* Okay, it fits - now,  see if the space we want is free. */
    858 		for ((i = newsb->fs_csaddr + nold), (j = nnew);
    859 		    j > 0;
    860 		    i++, j--) {
    861 			cgn = dtog(newsb, i);
    862 			if (bit_is_clr(cg_blksfree(cgs[cgn], 0),
    863 				dtogd(newsb, i)))
    864 				break;
    865 		}
    866 		if (j <= 0) {
    867 			/* Win win - all the frags we want are free. Allocate
    868 			 * 'em and we're all done.  */
    869 			for ((i = newsb->fs_csaddr + ntot - nnew),
    870 				 (j = nnew); j > 0; i++, j--) {
    871 				alloc_frag(i);
    872 			}
    873 			return;
    874 		}
    875 	}
    876 	/* We have to move the csum info, sigh.  Look for new space, free old
    877 	 * space, and allocate new.  Update fs_csaddr.  We don't copy anything
    878 	 * on disk at this point; the csum info will be written to the
    879 	 * then-current fs_csaddr as part of the final flush. */
    880 	newloc = find_freespace(ntot);
    881 	if (newloc < 0)
    882 		errx(EXIT_FAILURE, "Sorry, no space available for new csums");
    883 	for (i = 0, f = newsb->fs_csaddr, t = newloc; i < ntot; i++, f++, t++) {
    884 		if (i < nold) {
    885 			free_frag(f);
    886 		}
    887 		alloc_frag(t);
    888 	}
    889 	newsb->fs_csaddr = newloc;
    890 }
    891 /*
    892  * Recompute newsb->fs_dsize.  Just scans all cgs, adding the number of
    893  *  data blocks in that cg to the total.
    894  */
    895 static void
    896 recompute_fs_dsize(void)
    897 {
    898 	uint32_t i;
    899 
    900 	newsb->fs_dsize = 0;
    901 	for (i = 0; i < newsb->fs_ncg; i++) {
    902 		int64_t dlow;	/* size of before-sb data area */
    903 		int64_t dhigh;	/* offset of post-inode data area */
    904 		int64_t dmax;	/* total size of cg */
    905 		int64_t base;	/* base of cg, since cgsblock() etc add it in */
    906 		base = cgbase(newsb, i);
    907 		dlow = cgsblock(newsb, i) - base;
    908 		dhigh = cgdmin(newsb, i) - base;
    909 		dmax = newsb->fs_size - base;
    910 		if (dmax > newsb->fs_fpg)
    911 			dmax = newsb->fs_fpg;
    912 		newsb->fs_dsize += dlow + dmax - dhigh;
    913 	}
    914 	/* Space in cg 0 before cgsblock is boot area, not free space! */
    915 	newsb->fs_dsize -= cgsblock(newsb, 0) - cgbase(newsb, 0);
    916 	/* And of course the csum info takes up space. */
    917 	newsb->fs_dsize -= howmany(newsb->fs_cssize, newsb->fs_fsize);
    918 }
    919 /*
    920  * Return the current time.  We call this and assign, rather than
    921  *  calling time() directly, as insulation against OSes where fs_time
    922  *  is not a time_t.
    923  */
    924 static time_t
    925 timestamp(void)
    926 {
    927 	time_t t;
    928 
    929 	time(&t);
    930 	return (t);
    931 }
    932 
    933 /*
    934  * Calculate new filesystem geometry
    935  *  return 0 if geometry actually changed
    936  */
    937 static int
    938 makegeometry(int chatter)
    939 {
    940 
    941 	/* Update the size. */
    942 	newsb->fs_size = FFS_DBTOFSB(newsb, newsize);
    943 	if (is_ufs2)
    944 		newsb->fs_ncg = howmany(newsb->fs_size, newsb->fs_fpg);
    945 	else {
    946 		/* Update fs_old_ncyl and fs_ncg. */
    947 		newsb->fs_old_ncyl = howmany(newsb->fs_size * NSPF(newsb),
    948 		    newsb->fs_old_spc);
    949 		newsb->fs_ncg = howmany(newsb->fs_old_ncyl, newsb->fs_old_cpg);
    950 	}
    951 
    952 	/* Does the last cg end before the end of its inode area? There is no
    953 	 * reason why this couldn't be handled, but it would complicate a lot
    954 	 * of code (in all file system code - fsck, kernel, etc) because of the
    955 	 * potential partial inode area, and the gain in space would be
    956 	 * minimal, at most the pre-sb data area. */
    957 	if (cgdmin(newsb, newsb->fs_ncg - 1) > newsb->fs_size) {
    958 		newsb->fs_ncg--;
    959 		if (is_ufs2)
    960 			newsb->fs_size = newsb->fs_ncg * newsb->fs_fpg;
    961 		else {
    962 			newsb->fs_old_ncyl = newsb->fs_ncg * newsb->fs_old_cpg;
    963 			newsb->fs_size = (newsb->fs_old_ncyl *
    964 				newsb->fs_old_spc) / NSPF(newsb);
    965 		}
    966 		if (chatter || verbose) {
    967 			printf("Warning: last cylinder group is too small;\n");
    968 			printf("    dropping it.  New size = %lu.\n",
    969 			(unsigned long int) FFS_FSBTODB(newsb, newsb->fs_size));
    970 		}
    971 	}
    972 
    973 	/* Did we actually not grow?  (This can happen if newsize is less than
    974 	 * a frag larger than the old size - unlikely, but no excuse to
    975 	 * misbehave if it happens.) */
    976 	if (newsb->fs_size == oldsb->fs_size)
    977 		return 1;
    978 
    979 	return 0;
    980 }
    981 
    982 
    983 /*
    984  * Grow the file system.
    985  */
    986 static void
    987 grow(void)
    988 {
    989 	uint32_t i;
    990 
    991 	if (makegeometry(1)) {
    992 		printf("New fs size %"PRIu64" = old fs size %"PRIu64
    993 		    ", not growing.\n", newsb->fs_size, oldsb->fs_size);
    994 		return;
    995 	}
    996 
    997 	if (verbose) {
    998 		printf("Growing fs from %"PRIu64" blocks to %"PRIu64
    999 		    " blocks.\n", oldsb->fs_size, newsb->fs_size);
   1000 	}
   1001 
   1002 	/* Update the timestamp. */
   1003 	newsb->fs_time = timestamp();
   1004 	/* Allocate and clear the new-inode area, in case we add any cgs. */
   1005 	if (is_ufs2) {
   1006 		zinodes2 = alloconce(newsb->fs_ipg * sizeof(*zinodes2),
   1007 			"zeroed inodes");
   1008 		memset(zinodes2, 0, newsb->fs_ipg * sizeof(*zinodes2));
   1009 	} else {
   1010 		zinodes1 = alloconce(newsb->fs_ipg * sizeof(*zinodes1),
   1011 			"zeroed inodes");
   1012 		memset(zinodes1, 0, newsb->fs_ipg * sizeof(*zinodes1));
   1013 	}
   1014 
   1015 	/* Check that the new last sector (frag, actually) is writable.  Since
   1016 	 * it's at least one frag larger than it used to be, we know we aren't
   1017 	 * overwriting anything important by this.  (The choice of sbbuf as
   1018 	 * what to write is irrelevant; it's just something handy that's known
   1019 	 * to be at least one frag in size.) */
   1020 	writeat(FFS_FSBTODB(newsb,newsb->fs_size - 1), &sbbuf, newsb->fs_fsize);
   1021 
   1022 	/* Find out how big the csum area is, and realloc csums if bigger. */
   1023 	newsb->fs_cssize = ffs_fragroundup(newsb,
   1024 	    newsb->fs_ncg * sizeof(struct csum));
   1025 	if (newsb->fs_cssize > oldsb->fs_cssize)
   1026 		csums = nfrealloc(csums, newsb->fs_cssize, "new cg summary");
   1027 	/* If we're adding any cgs, realloc structures and set up the new
   1028 	   cgs. */
   1029 	if (newsb->fs_ncg > oldsb->fs_ncg) {
   1030 		char *cgp;
   1031 		cgs = nfrealloc(cgs, newsb->fs_ncg * sizeof(*cgs),
   1032                                 "cg pointers");
   1033 		cgflags = nfrealloc(cgflags, newsb->fs_ncg, "cg flags");
   1034 		memset(cgflags + oldsb->fs_ncg, 0,
   1035 		    newsb->fs_ncg - oldsb->fs_ncg);
   1036 		cgp = alloconce((newsb->fs_ncg - oldsb->fs_ncg) * cgblksz,
   1037                                 "cgs");
   1038 		for (i = oldsb->fs_ncg; i < newsb->fs_ncg; i++) {
   1039 			cgs[i] = (struct cg *) cgp;
   1040 			progress_bar(special, "grow cg",
   1041 			    i - oldsb->fs_ncg, newsb->fs_ncg - oldsb->fs_ncg);
   1042 			initcg(i);
   1043 			cgp += cgblksz;
   1044 		}
   1045 		cgs[oldsb->fs_ncg - 1]->cg_old_ncyl = oldsb->fs_old_cpg;
   1046 		cgflags[oldsb->fs_ncg - 1] |= CGF_DIRTY;
   1047 	}
   1048 	/* If the old fs ended partway through a cg, we have to update the old
   1049 	 * last cg (though possibly not to a full cg!). */
   1050 	if (oldsb->fs_size % oldsb->fs_fpg) {
   1051 		struct cg *cg;
   1052 		int64_t newcgsize;
   1053 		int64_t prevcgtop;
   1054 		int64_t oldcgsize;
   1055 		cg = cgs[oldsb->fs_ncg - 1];
   1056 		cgflags[oldsb->fs_ncg - 1] |= CGF_DIRTY | CGF_BLKMAPS;
   1057 		prevcgtop = oldsb->fs_fpg * (oldsb->fs_ncg - 1);
   1058 		newcgsize = newsb->fs_size - prevcgtop;
   1059 		if (newcgsize > newsb->fs_fpg)
   1060 			newcgsize = newsb->fs_fpg;
   1061 		oldcgsize = oldsb->fs_size % oldsb->fs_fpg;
   1062 		set_bits(cg_blksfree(cg, 0), oldcgsize, newcgsize - oldcgsize);
   1063 		cg->cg_old_ncyl = oldsb->fs_old_cpg;
   1064 		cg->cg_ndblk = newcgsize;
   1065 	}
   1066 	/* Fix up the csum info, if necessary. */
   1067 	csum_fixup();
   1068 	/* Make fs_dsize match the new reality. */
   1069 	recompute_fs_dsize();
   1070 
   1071 	progress_done();
   1072 }
   1073 /*
   1074  * Call (*fn)() for each inode, passing the inode and its inumber.  The
   1075  *  number of cylinder groups is passed in, so this can be used to map
   1076  *  over either the old or the new file system's set of inodes.
   1077  */
   1078 static void
   1079 map_inodes(void (*fn) (union dinode * di, unsigned int, void *arg),
   1080 	   int ncg, void *cbarg) {
   1081 	int i;
   1082 	int ni;
   1083 
   1084 	ni = oldsb->fs_ipg * ncg;
   1085 	for (i = 0; i < ni; i++)
   1086 		(*fn) (inodes + i, i, cbarg);
   1087 }
   1088 /* Values for the third argument to the map function for
   1089  * map_inode_data_blocks.  MDB_DATA indicates the block is contains
   1090  * file data; MDB_INDIR_PRE and MDB_INDIR_POST indicate that it's an
   1091  * indirect block.  The MDB_INDIR_PRE call is made before the indirect
   1092  * block pointers are followed and the pointed-to blocks scanned,
   1093  * MDB_INDIR_POST after.
   1094  */
   1095 #define MDB_DATA       1
   1096 #define MDB_INDIR_PRE  2
   1097 #define MDB_INDIR_POST 3
   1098 
   1099 typedef void (*mark_callback_t) (off_t blocknum, unsigned int nfrags,
   1100 				 unsigned int blksize, int opcode);
   1101 
   1102 /* Helper function - handles a data block.  Calls the callback
   1103  * function and returns number of bytes occupied in file (actually,
   1104  * rounded up to a frag boundary).  The name is historical.  */
   1105 static int
   1106 markblk(mark_callback_t fn, union dinode * di, off_t bn, off_t o)
   1107 {
   1108 	int sz;
   1109 	int nb;
   1110 	off_t filesize;
   1111 
   1112 	filesize = DIP(di,di_size);
   1113 	if (o >= filesize)
   1114 		return (0);
   1115 	sz = dblksize(newsb, di, ffs_lblkno(newsb, o), filesize);
   1116 	nb = (sz > filesize - o) ? filesize - o : sz;
   1117 	if (bn)
   1118 		(*fn) (bn, ffs_numfrags(newsb, sz), nb, MDB_DATA);
   1119 	return (sz);
   1120 }
   1121 /* Helper function - handles an indirect block.  Makes the
   1122  * MDB_INDIR_PRE callback for the indirect block, loops over the
   1123  * pointers and recurses, and makes the MDB_INDIR_POST callback.
   1124  * Returns the number of bytes occupied in file, as does markblk().
   1125  * For the sake of update_for_data_move(), we read the indirect block
   1126  * _after_ making the _PRE callback.  The name is historical.  */
   1127 static off_t
   1128 markiblk(mark_callback_t fn, union dinode * di, off_t bn, off_t o, int lev)
   1129 {
   1130 	int i;
   1131 	unsigned k;
   1132 	off_t j, tot;
   1133 	static int32_t indirblk1[howmany(MAXBSIZE, sizeof(int32_t))];
   1134 	static int32_t indirblk2[howmany(MAXBSIZE, sizeof(int32_t))];
   1135 	static int32_t indirblk3[howmany(MAXBSIZE, sizeof(int32_t))];
   1136 	static int32_t *indirblks[3] = {
   1137 		&indirblk1[0], &indirblk2[0], &indirblk3[0]
   1138 	};
   1139 
   1140 	if (lev < 0)
   1141 		return (markblk(fn, di, bn, o));
   1142 	if (bn == 0) {
   1143 		for (j = newsb->fs_bsize;
   1144 		    lev >= 0;
   1145 		    j *= FFS_NINDIR(newsb), lev--);
   1146 		return (j);
   1147 	}
   1148 	(*fn) (bn, newsb->fs_frag, newsb->fs_bsize, MDB_INDIR_PRE);
   1149 	readat(FFS_FSBTODB(newsb, bn), indirblks[lev], newsb->fs_bsize);
   1150 	if (needswap)
   1151 		for (k = 0; k < howmany(MAXBSIZE, sizeof(int32_t)); k++)
   1152 			indirblks[lev][k] = bswap32(indirblks[lev][k]);
   1153 	tot = 0;
   1154 	for (i = 0; i < FFS_NINDIR(newsb); i++) {
   1155 		j = markiblk(fn, di, indirblks[lev][i], o, lev - 1);
   1156 		if (j == 0)
   1157 			break;
   1158 		o += j;
   1159 		tot += j;
   1160 	}
   1161 	(*fn) (bn, newsb->fs_frag, newsb->fs_bsize, MDB_INDIR_POST);
   1162 	return (tot);
   1163 }
   1164 
   1165 
   1166 /*
   1167  * Call (*fn)() for each data block for an inode.  This routine assumes
   1168  *  the inode is known to be of a type that has data blocks (file,
   1169  *  directory, or non-fast symlink).  The called function is:
   1170  *
   1171  * (*fn)(unsigned int blkno, unsigned int nf, unsigned int nb, int op)
   1172  *
   1173  *  where blkno is the frag number, nf is the number of frags starting
   1174  *  at blkno (always <= fs_frag), nb is the number of bytes that belong
   1175  *  to the file (usually nf*fs_frag, often less for the last block/frag
   1176  *  of a file).
   1177  */
   1178 static void
   1179 map_inode_data_blocks(union dinode * di, mark_callback_t fn)
   1180 {
   1181 	off_t o;		/* offset within  inode */
   1182 	off_t inc;		/* increment for o */
   1183 	int b;			/* index within di_db[] and di_ib[] arrays */
   1184 
   1185 	/* Scan the direct blocks... */
   1186 	o = 0;
   1187 	for (b = 0; b < UFS_NDADDR; b++) {
   1188 		inc = markblk(fn, di, DIP(di,di_db[b]), o);
   1189 		if (inc == 0)
   1190 			break;
   1191 		o += inc;
   1192 	}
   1193 	/* ...and the indirect blocks. */
   1194 	if (inc) {
   1195 		for (b = 0; b < UFS_NIADDR; b++) {
   1196 			inc = markiblk(fn, di, DIP(di,di_ib[b]), o, b);
   1197 			if (inc == 0)
   1198 				return;
   1199 			o += inc;
   1200 		}
   1201 	}
   1202 }
   1203 
   1204 static void
   1205 dblk_callback(union dinode * di, unsigned int inum, void *arg)
   1206 {
   1207 	mark_callback_t fn;
   1208 	off_t filesize;
   1209 
   1210 	filesize = DIP(di,di_size);
   1211 	fn = (mark_callback_t) arg;
   1212 	switch (DIP(di,di_mode) & IFMT) {
   1213 	case IFLNK:
   1214 		if (filesize <= newsb->fs_maxsymlinklen) {
   1215 			break;
   1216 		}
   1217 		/* FALLTHROUGH */
   1218 	case IFDIR:
   1219 	case IFREG:
   1220 		map_inode_data_blocks(di, fn);
   1221 		break;
   1222 	}
   1223 }
   1224 /*
   1225  * Make a callback call, a la map_inode_data_blocks, for all data
   1226  *  blocks in the entire fs.  This is used only once, in
   1227  *  update_for_data_move, but it's out at top level because the complex
   1228  *  downward-funarg nesting that would otherwise result seems to give
   1229  *  gcc gastric distress.
   1230  */
   1231 static void
   1232 map_data_blocks(mark_callback_t fn, int ncg)
   1233 {
   1234 	map_inodes(&dblk_callback, ncg, (void *) fn);
   1235 }
   1236 /*
   1237  * Initialize the blkmove array.
   1238  */
   1239 static void
   1240 blkmove_init(void)
   1241 {
   1242 	int i;
   1243 
   1244 	blkmove = alloconce(oldsb->fs_size * sizeof(*blkmove), "blkmove");
   1245 	for (i = 0; i < oldsb->fs_size; i++)
   1246 		blkmove[i] = i;
   1247 }
   1248 /*
   1249  * Load the inodes off disk.  Allocates the structures and initializes
   1250  *  them - the inodes from disk, the flags to zero.
   1251  */
   1252 static void
   1253 loadinodes(void)
   1254 {
   1255 	int imax, ino, j;
   1256 	uint32_t i;
   1257 	struct ufs1_dinode *dp1 = NULL;
   1258 	struct ufs2_dinode *dp2 = NULL;
   1259 
   1260 	/* read inodes one fs block at a time and copy them */
   1261 
   1262 	inodes = alloconce(oldsb->fs_ncg * oldsb->fs_ipg *
   1263 	    sizeof(union dinode), "inodes");
   1264 	iflags = alloconce(oldsb->fs_ncg * oldsb->fs_ipg, "inode flags");
   1265 	memset(iflags, 0, oldsb->fs_ncg * oldsb->fs_ipg);
   1266 
   1267 	ibuf = nfmalloc(oldsb->fs_bsize,"inode block buf");
   1268 	if (is_ufs2)
   1269 		dp2 = (struct ufs2_dinode *)ibuf;
   1270 	else
   1271 		dp1 = (struct ufs1_dinode *)ibuf;
   1272 
   1273 	for (ino = 0,imax = oldsb->fs_ipg * oldsb->fs_ncg; ino < imax; ) {
   1274 		readat(FFS_FSBTODB(oldsb, ino_to_fsba(oldsb, ino)), ibuf,
   1275 		    oldsb->fs_bsize);
   1276 
   1277 		for (i = 0; i < oldsb->fs_inopb; i++) {
   1278 			if (is_ufs2) {
   1279 				if (needswap) {
   1280 					ffs_dinode2_swap(&(dp2[i]), &(dp2[i]));
   1281 					for (j = 0; j < UFS_NDADDR; j++)
   1282 						dp2[i].di_db[j] =
   1283 						    bswap32(dp2[i].di_db[j]);
   1284 					for (j = 0; j < UFS_NIADDR; j++)
   1285 						dp2[i].di_ib[j] =
   1286 						    bswap32(dp2[i].di_ib[j]);
   1287 				}
   1288 				memcpy(&inodes[ino].dp2, &dp2[i],
   1289 				    sizeof(inodes[ino].dp2));
   1290 			} else {
   1291 				if (needswap) {
   1292 					ffs_dinode1_swap(&(dp1[i]), &(dp1[i]));
   1293 					for (j = 0; j < UFS_NDADDR; j++)
   1294 						dp1[i].di_db[j] =
   1295 						    bswap32(dp1[i].di_db[j]);
   1296 					for (j = 0; j < UFS_NIADDR; j++)
   1297 						dp1[i].di_ib[j] =
   1298 						    bswap32(dp1[i].di_ib[j]);
   1299 				}
   1300 				memcpy(&inodes[ino].dp1, &dp1[i],
   1301 				    sizeof(inodes[ino].dp1));
   1302 			}
   1303 			    if (++ino > imax)
   1304 				    errx(EXIT_FAILURE,
   1305 					"Exceeded number of inodes");
   1306 		}
   1307 
   1308 	}
   1309 }
   1310 /*
   1311  * Report a file-system-too-full problem.
   1312  */
   1313 __dead static void
   1314 toofull(void)
   1315 {
   1316 	errx(EXIT_FAILURE, "Sorry, would run out of data blocks");
   1317 }
   1318 /*
   1319  * Record a desire to move "n" frags from "from" to "to".
   1320  */
   1321 static void
   1322 mark_move(unsigned int from, unsigned int to, unsigned int n)
   1323 {
   1324 	for (; n > 0; n--)
   1325 		blkmove[from++] = to++;
   1326 }
   1327 /* Helper function - evict n frags, starting with start (cg-relative).
   1328  * The free bitmap is scanned, unallocated frags are ignored, and
   1329  * each block of consecutive allocated frags is moved as a unit.
   1330  */
   1331 static void
   1332 fragmove(struct cg * cg, int64_t base, unsigned int start, unsigned int n)
   1333 {
   1334 	unsigned int i;
   1335 	int run;
   1336 
   1337 	run = 0;
   1338 	for (i = 0; i <= n; i++) {
   1339 		if ((i < n) && bit_is_clr(cg_blksfree(cg, 0), start + i)) {
   1340 			run++;
   1341 		} else {
   1342 			if (run > 0) {
   1343 				int off;
   1344 				off = find_freespace(run);
   1345 				if (off < 0)
   1346 					toofull();
   1347 				mark_move(base + start + i - run, off, run);
   1348 				set_bits(cg_blksfree(cg, 0), start + i - run,
   1349 				    run);
   1350 				clr_bits(cg_blksfree(cgs[dtog(oldsb, off)], 0),
   1351 				    dtogd(oldsb, off), run);
   1352 			}
   1353 			run = 0;
   1354 		}
   1355 	}
   1356 }
   1357 /*
   1358  * Evict all data blocks from the given cg, starting at minfrag (based
   1359  *  at the beginning of the cg), for length nfrag.  The eviction is
   1360  *  assumed to be entirely data-area; this should not be called with a
   1361  *  range overlapping the metadata structures in the cg.  It also
   1362  *  assumes minfrag points into the given cg; it will misbehave if this
   1363  *  is not true.
   1364  *
   1365  * See the comment header on find_freespace() for one possible bug
   1366  *  lurking here.
   1367  */
   1368 static void
   1369 evict_data(struct cg * cg, unsigned int minfrag, int nfrag)
   1370 {
   1371 	int64_t base;	/* base of cg (in frags from beginning of fs) */
   1372 
   1373 	base = cgbase(oldsb, cg->cg_cgx);
   1374 	/* Does the boundary fall in the middle of a block?  To avoid
   1375 	 * breaking between frags allocated as consecutive, we always
   1376 	 * evict the whole block in this case, though one could argue
   1377 	 * we should check to see if the frag before or after the
   1378 	 * break is unallocated. */
   1379 	if (minfrag % oldsb->fs_frag) {
   1380 		int n;
   1381 		n = minfrag % oldsb->fs_frag;
   1382 		minfrag -= n;
   1383 		nfrag += n;
   1384 	}
   1385 	/* Do whole blocks.  If a block is wholly free, skip it; if
   1386 	 * wholly allocated, move it in toto.  If neither, call
   1387 	 * fragmove() to move the frags to new locations. */
   1388 	while (nfrag >= oldsb->fs_frag) {
   1389 		if (!blk_is_set(cg_blksfree(cg, 0), minfrag, oldsb->fs_frag)) {
   1390 			if (blk_is_clr(cg_blksfree(cg, 0), minfrag,
   1391 				oldsb->fs_frag)) {
   1392 				int off;
   1393 				off = find_freeblock();
   1394 				if (off < 0)
   1395 					toofull();
   1396 				mark_move(base + minfrag, off, oldsb->fs_frag);
   1397 				set_bits(cg_blksfree(cg, 0), minfrag,
   1398 				    oldsb->fs_frag);
   1399 				clr_bits(cg_blksfree(cgs[dtog(oldsb, off)], 0),
   1400 				    dtogd(oldsb, off), oldsb->fs_frag);
   1401 			} else {
   1402 				fragmove(cg, base, minfrag, oldsb->fs_frag);
   1403 			}
   1404 		}
   1405 		minfrag += oldsb->fs_frag;
   1406 		nfrag -= oldsb->fs_frag;
   1407 	}
   1408 	/* Clean up any sub-block amount left over. */
   1409 	if (nfrag) {
   1410 		fragmove(cg, base, minfrag, nfrag);
   1411 	}
   1412 }
   1413 /*
   1414  * Move all data blocks according to blkmove.  We have to be careful,
   1415  *  because we may be updating indirect blocks that will themselves be
   1416  *  getting moved, or inode int32_t arrays that point to indirect
   1417  *  blocks that will be moved.  We call this before
   1418  *  update_for_data_move, and update_for_data_move does inodes first,
   1419  *  then indirect blocks in preorder, so as to make sure that the
   1420  *  file system is self-consistent at all points, for better crash
   1421  *  tolerance.  (We can get away with this only because all the writes
   1422  *  done by perform_data_move() are writing into space that's not used
   1423  *  by the old file system.)  If we crash, some things may point to the
   1424  *  old data and some to the new, but both copies are the same.  The
   1425  *  only wrong things should be csum info and free bitmaps, which fsck
   1426  *  is entirely capable of cleaning up.
   1427  *
   1428  * Since blkmove_init() initializes all blocks to move to their current
   1429  *  locations, we can have two blocks marked as wanting to move to the
   1430  *  same location, but only two and only when one of them is the one
   1431  *  that was already there.  So if blkmove[i]==i, we ignore that entry
   1432  *  entirely - for unallocated blocks, we don't want it (and may be
   1433  *  putting something else there), and for allocated blocks, we don't
   1434  *  want to copy it anywhere.
   1435  */
   1436 static void
   1437 perform_data_move(void)
   1438 {
   1439 	int i;
   1440 	int run;
   1441 	int maxrun;
   1442 	char buf[65536];
   1443 
   1444 	maxrun = sizeof(buf) / newsb->fs_fsize;
   1445 	run = 0;
   1446 	for (i = 0; i < oldsb->fs_size; i++) {
   1447 		if ((blkmove[i] == (unsigned)i /*XXX cast*/) ||
   1448 		    (run >= maxrun) ||
   1449 		    ((run > 0) &&
   1450 			(blkmove[i] != blkmove[i - 1] + 1))) {
   1451 			if (run > 0) {
   1452 				readat(FFS_FSBTODB(oldsb, i - run), &buf[0],
   1453 				    run << oldsb->fs_fshift);
   1454 				writeat(FFS_FSBTODB(oldsb, blkmove[i - run]),
   1455 				    &buf[0], run << oldsb->fs_fshift);
   1456 			}
   1457 			run = 0;
   1458 		}
   1459 		if (blkmove[i] != (unsigned)i /*XXX cast*/)
   1460 			run++;
   1461 	}
   1462 	if (run > 0) {
   1463 		readat(FFS_FSBTODB(oldsb, i - run), &buf[0],
   1464 		    run << oldsb->fs_fshift);
   1465 		writeat(FFS_FSBTODB(oldsb, blkmove[i - run]), &buf[0],
   1466 		    run << oldsb->fs_fshift);
   1467 	}
   1468 }
   1469 /*
   1470  * This modifies an array of int32_t, according to blkmove.  This is
   1471  *  used to update inode block arrays and indirect blocks to point to
   1472  *  the new locations of data blocks.
   1473  *
   1474  * Return value is the number of int32_ts that needed updating; in
   1475  *  particular, the return value is zero iff nothing was modified.
   1476  */
   1477 static int
   1478 movemap_blocks(int32_t * vec, int n)
   1479 {
   1480 	int rv;
   1481 
   1482 	rv = 0;
   1483 	for (; n > 0; n--, vec++) {
   1484 		if (blkmove[*vec] != (unsigned)*vec /*XXX cast*/) {
   1485 			*vec = blkmove[*vec];
   1486 			rv++;
   1487 		}
   1488 	}
   1489 	return (rv);
   1490 }
   1491 static void
   1492 moveblocks_callback(union dinode * di, unsigned int inum, void *arg)
   1493 {
   1494 	int32_t *dblkptr, *iblkptr;
   1495 
   1496 	switch (DIP(di,di_mode) & IFMT) {
   1497 	case IFLNK:
   1498 		if ((off_t)DIP(di,di_size) <= oldsb->fs_maxsymlinklen) {
   1499 			break;
   1500 		}
   1501 		/* FALLTHROUGH */
   1502 	case IFDIR:
   1503 	case IFREG:
   1504 		if (is_ufs2) {
   1505 			/* XXX these are not int32_t and this is WRONG! */
   1506 			dblkptr = (void *) &(di->dp2.di_db[0]);
   1507 			iblkptr = (void *) &(di->dp2.di_ib[0]);
   1508 		} else {
   1509 			dblkptr = &(di->dp1.di_db[0]);
   1510 			iblkptr = &(di->dp1.di_ib[0]);
   1511 		}
   1512 		/*
   1513 		 * Don't || these two calls; we need their
   1514 		 * side-effects.
   1515 		 */
   1516 		if (movemap_blocks(dblkptr, UFS_NDADDR)) {
   1517 			iflags[inum] |= IF_DIRTY;
   1518 		}
   1519 		if (movemap_blocks(iblkptr, UFS_NIADDR)) {
   1520 			iflags[inum] |= IF_DIRTY;
   1521 		}
   1522 		break;
   1523 	}
   1524 }
   1525 
   1526 static void
   1527 moveindir_callback(off_t off, unsigned int nfrag, unsigned int nbytes,
   1528 		   int kind)
   1529 {
   1530 	unsigned int i;
   1531 
   1532 	if (kind == MDB_INDIR_PRE) {
   1533 		int32_t blk[howmany(MAXBSIZE, sizeof(int32_t))];
   1534 		readat(FFS_FSBTODB(oldsb, off), &blk[0], oldsb->fs_bsize);
   1535 		if (needswap)
   1536 			for (i = 0; i < howmany(MAXBSIZE, sizeof(int32_t)); i++)
   1537 				blk[i] = bswap32(blk[i]);
   1538 		if (movemap_blocks(&blk[0], FFS_NINDIR(oldsb))) {
   1539 			if (needswap)
   1540 				for (i = 0; i < howmany(MAXBSIZE,
   1541 					sizeof(int32_t)); i++)
   1542 					blk[i] = bswap32(blk[i]);
   1543 			writeat(FFS_FSBTODB(oldsb, off), &blk[0], oldsb->fs_bsize);
   1544 		}
   1545 	}
   1546 }
   1547 /*
   1548  * Update all inode data arrays and indirect blocks to point to the new
   1549  *  locations of data blocks.  See the comment header on
   1550  *  perform_data_move for some ordering considerations.
   1551  */
   1552 static void
   1553 update_for_data_move(void)
   1554 {
   1555 	map_inodes(&moveblocks_callback, oldsb->fs_ncg, NULL);
   1556 	map_data_blocks(&moveindir_callback, oldsb->fs_ncg);
   1557 }
   1558 /*
   1559  * Initialize the inomove array.
   1560  */
   1561 static void
   1562 inomove_init(void)
   1563 {
   1564 	int i;
   1565 
   1566 	inomove = alloconce(oldsb->fs_ipg * oldsb->fs_ncg * sizeof(*inomove),
   1567                             "inomove");
   1568 	for (i = (oldsb->fs_ipg * oldsb->fs_ncg) - 1; i >= 0; i--)
   1569 		inomove[i] = i;
   1570 }
   1571 /*
   1572  * Flush all dirtied inodes to disk.  Scans the inode flags array; for
   1573  *  each dirty inode, it sets the BDIRTY bit on the first inode in the
   1574  *  block containing the dirty inode.  Then it scans by blocks, and for
   1575  *  each marked block, writes it.
   1576  */
   1577 static void
   1578 flush_inodes(void)
   1579 {
   1580 	int i, j, k, ni, m;
   1581 	struct ufs1_dinode *dp1 = NULL;
   1582 	struct ufs2_dinode *dp2 = NULL;
   1583 
   1584 	ni = newsb->fs_ipg * newsb->fs_ncg;
   1585 	m = FFS_INOPB(newsb) - 1;
   1586 	for (i = 0; i < ni; i++) {
   1587 		if (iflags[i] & IF_DIRTY) {
   1588 			iflags[i & ~m] |= IF_BDIRTY;
   1589 		}
   1590 	}
   1591 	m++;
   1592 
   1593 	if (is_ufs2)
   1594 		dp2 = (struct ufs2_dinode *)ibuf;
   1595 	else
   1596 		dp1 = (struct ufs1_dinode *)ibuf;
   1597 
   1598 	for (i = 0; i < ni; i += m) {
   1599 		if ((iflags[i] & IF_BDIRTY) == 0)
   1600 			continue;
   1601 		if (is_ufs2)
   1602 			for (j = 0; j < m; j++) {
   1603 				dp2[j] = inodes[i + j].dp2;
   1604 				if (needswap) {
   1605 					for (k = 0; k < UFS_NDADDR; k++)
   1606 						dp2[j].di_db[k] =
   1607 						    bswap32(dp2[j].di_db[k]);
   1608 					for (k = 0; k < UFS_NIADDR; k++)
   1609 						dp2[j].di_ib[k] =
   1610 						    bswap32(dp2[j].di_ib[k]);
   1611 					ffs_dinode2_swap(&dp2[j],
   1612 					    &dp2[j]);
   1613 				}
   1614 			}
   1615 		else
   1616 			for (j = 0; j < m; j++) {
   1617 				dp1[j] = inodes[i + j].dp1;
   1618 				if (needswap) {
   1619 					for (k = 0; k < UFS_NDADDR; k++)
   1620 						dp1[j].di_db[k]=
   1621 						    bswap32(dp1[j].di_db[k]);
   1622 					for (k = 0; k < UFS_NIADDR; k++)
   1623 						dp1[j].di_ib[k]=
   1624 						    bswap32(dp1[j].di_ib[k]);
   1625 					ffs_dinode1_swap(&dp1[j],
   1626 					    &dp1[j]);
   1627 				}
   1628 			}
   1629 
   1630 		writeat(FFS_FSBTODB(newsb, ino_to_fsba(newsb, i)),
   1631 		    ibuf, newsb->fs_bsize);
   1632 	}
   1633 }
   1634 /*
   1635  * Evict all inodes from the specified cg.  shrink() already checked
   1636  *  that there were enough free inodes, so the no-free-inodes check is
   1637  *  a can't-happen.  If it does trip, the file system should be in good
   1638  *  enough shape for fsck to fix; see the comment on perform_data_move
   1639  *  for the considerations in question.
   1640  */
   1641 static void
   1642 evict_inodes(struct cg * cg)
   1643 {
   1644 	int inum;
   1645 	int fi;
   1646 	uint32_t i;
   1647 
   1648 	inum = newsb->fs_ipg * cg->cg_cgx;
   1649 	for (i = 0; i < newsb->fs_ipg; i++, inum++) {
   1650 		if (DIP(inodes + inum,di_mode) != 0) {
   1651 			fi = find_freeinode();
   1652 			if (fi < 0)
   1653 				errx(EXIT_FAILURE, "Sorry, inodes evaporated - "
   1654 				    "file system probably needs fsck");
   1655 			inomove[inum] = fi;
   1656 			clr_bits(cg_inosused(cg, 0), i, 1);
   1657 			set_bits(cg_inosused(cgs[ino_to_cg(newsb, fi)], 0),
   1658 			    fi % newsb->fs_ipg, 1);
   1659 		}
   1660 	}
   1661 }
   1662 /*
   1663  * Move inodes from old locations to new.  Does not actually write
   1664  *  anything to disk; just copies in-core and sets dirty bits.
   1665  *
   1666  * We have to be careful here for reasons similar to those mentioned in
   1667  *  the comment header on perform_data_move, above: for the sake of
   1668  *  crash tolerance, we want to make sure everything is present at both
   1669  *  old and new locations before we update pointers.  So we call this
   1670  *  first, then flush_inodes() to get them out on disk, then update
   1671  *  directories to match.
   1672  */
   1673 static void
   1674 perform_inode_move(void)
   1675 {
   1676 	unsigned int i;
   1677 	unsigned int ni;
   1678 
   1679 	ni = oldsb->fs_ipg * oldsb->fs_ncg;
   1680 	for (i = 0; i < ni; i++) {
   1681 		if (inomove[i] != i) {
   1682 			inodes[inomove[i]] = inodes[i];
   1683 			iflags[inomove[i]] = iflags[i] | IF_DIRTY;
   1684 		}
   1685 	}
   1686 }
   1687 /*
   1688  * Update the directory contained in the nb bytes at buf, to point to
   1689  *  inodes' new locations.
   1690  */
   1691 static int
   1692 update_dirents(char *buf, int nb)
   1693 {
   1694 	int rv;
   1695 #define d ((struct direct *)buf)
   1696 #define s32(x) (needswap?bswap32((x)):(x))
   1697 #define s16(x) (needswap?bswap16((x)):(x))
   1698 
   1699 	rv = 0;
   1700 	while (nb > 0) {
   1701 		if (inomove[s32(d->d_ino)] != s32(d->d_ino)) {
   1702 			rv++;
   1703 			d->d_ino = s32(inomove[s32(d->d_ino)]);
   1704 		}
   1705 		nb -= s16(d->d_reclen);
   1706 		buf += s16(d->d_reclen);
   1707 	}
   1708 	return (rv);
   1709 #undef d
   1710 #undef s32
   1711 #undef s16
   1712 }
   1713 /*
   1714  * Callback function for map_inode_data_blocks, for updating a
   1715  *  directory to point to new inode locations.
   1716  */
   1717 static void
   1718 update_dir_data(off_t bn, unsigned int size, unsigned int nb, int kind)
   1719 {
   1720 	if (kind == MDB_DATA) {
   1721 		union {
   1722 			struct direct d;
   1723 			char ch[MAXBSIZE];
   1724 		}     buf;
   1725 		readat(FFS_FSBTODB(oldsb, bn), &buf, size << oldsb->fs_fshift);
   1726 		if (update_dirents((char *) &buf, nb)) {
   1727 			writeat(FFS_FSBTODB(oldsb, bn), &buf,
   1728 			    size << oldsb->fs_fshift);
   1729 		}
   1730 	}
   1731 }
   1732 static void
   1733 dirmove_callback(union dinode * di, unsigned int inum, void *arg)
   1734 {
   1735 	switch (DIP(di,di_mode) & IFMT) {
   1736 	case IFDIR:
   1737 		map_inode_data_blocks(di, &update_dir_data);
   1738 		break;
   1739 	}
   1740 }
   1741 /*
   1742  * Update directory entries to point to new inode locations.
   1743  */
   1744 static void
   1745 update_for_inode_move(void)
   1746 {
   1747 	map_inodes(&dirmove_callback, newsb->fs_ncg, NULL);
   1748 }
   1749 /*
   1750  * Shrink the file system.
   1751  */
   1752 static void
   1753 shrink(void)
   1754 {
   1755 	uint32_t i;
   1756 
   1757 	if (makegeometry(1)) {
   1758 		printf("New fs size %"PRIu64" = old fs size %"PRIu64
   1759 		    ", not shrinking.\n", newsb->fs_size, oldsb->fs_size);
   1760 		return;
   1761 	}
   1762 
   1763 	/* Let's make sure we're not being shrunk into oblivion. */
   1764 	if (newsb->fs_ncg < 1)
   1765 		errx(EXIT_FAILURE, "Size too small - file system would "
   1766 		    "have no cylinders");
   1767 
   1768 	if (verbose) {
   1769 		printf("Shrinking fs from %"PRIu64" blocks to %"PRIu64
   1770 		    " blocks.\n", oldsb->fs_size, newsb->fs_size);
   1771 	}
   1772 
   1773 	/* Load the inodes off disk - we'll need 'em. */
   1774 	loadinodes();
   1775 
   1776 	/* Update the timestamp. */
   1777 	newsb->fs_time = timestamp();
   1778 
   1779 	/* Initialize for block motion. */
   1780 	blkmove_init();
   1781 	/* Update csum size, then fix up for the new size */
   1782 	newsb->fs_cssize = ffs_fragroundup(newsb,
   1783 	    newsb->fs_ncg * sizeof(struct csum));
   1784 	csum_fixup();
   1785 	/* Evict data from any cgs being wholly eliminated */
   1786 	for (i = newsb->fs_ncg; i < oldsb->fs_ncg; i++) {
   1787 		int64_t base;
   1788 		int64_t dlow;
   1789 		int64_t dhigh;
   1790 		int64_t dmax;
   1791 		base = cgbase(oldsb, i);
   1792 		dlow = cgsblock(oldsb, i) - base;
   1793 		dhigh = cgdmin(oldsb, i) - base;
   1794 		dmax = oldsb->fs_size - base;
   1795 		if (dmax > cgs[i]->cg_ndblk)
   1796 			dmax = cgs[i]->cg_ndblk;
   1797 		evict_data(cgs[i], 0, dlow);
   1798 		evict_data(cgs[i], dhigh, dmax - dhigh);
   1799 		newsb->fs_cstotal.cs_ndir -= cgs[i]->cg_cs.cs_ndir;
   1800 		newsb->fs_cstotal.cs_nifree -= cgs[i]->cg_cs.cs_nifree;
   1801 		newsb->fs_cstotal.cs_nffree -= cgs[i]->cg_cs.cs_nffree;
   1802 		newsb->fs_cstotal.cs_nbfree -= cgs[i]->cg_cs.cs_nbfree;
   1803 	}
   1804 	/* Update the new last cg. */
   1805 	cgs[newsb->fs_ncg - 1]->cg_ndblk = newsb->fs_size -
   1806 	    ((newsb->fs_ncg - 1) * newsb->fs_fpg);
   1807 	/* Is the new last cg partial?  If so, evict any data from the part
   1808 	 * being shrunken away. */
   1809 	if (newsb->fs_size % newsb->fs_fpg) {
   1810 		struct cg *cg;
   1811 		int oldcgsize;
   1812 		int newcgsize;
   1813 		cg = cgs[newsb->fs_ncg - 1];
   1814 		newcgsize = newsb->fs_size % newsb->fs_fpg;
   1815 		oldcgsize = oldsb->fs_size - ((newsb->fs_ncg - 1) &
   1816 		    oldsb->fs_fpg);
   1817 		if (oldcgsize > oldsb->fs_fpg)
   1818 			oldcgsize = oldsb->fs_fpg;
   1819 		evict_data(cg, newcgsize, oldcgsize - newcgsize);
   1820 		clr_bits(cg_blksfree(cg, 0), newcgsize, oldcgsize - newcgsize);
   1821 	}
   1822 	/* Find out whether we would run out of inodes.  (Note we
   1823 	 * haven't actually done anything to the file system yet; all
   1824 	 * those evict_data calls just update blkmove.) */
   1825 	{
   1826 		int slop;
   1827 		slop = 0;
   1828 		for (i = 0; i < newsb->fs_ncg; i++)
   1829 			slop += cgs[i]->cg_cs.cs_nifree;
   1830 		for (; i < oldsb->fs_ncg; i++)
   1831 			slop -= oldsb->fs_ipg - cgs[i]->cg_cs.cs_nifree;
   1832 		if (slop < 0)
   1833 			errx(EXIT_FAILURE, "Sorry, would run out of inodes");
   1834 	}
   1835 	/* Copy data, then update pointers to data.  See the comment
   1836 	 * header on perform_data_move for ordering considerations. */
   1837 	perform_data_move();
   1838 	update_for_data_move();
   1839 	/* Now do inodes.  Initialize, evict, move, update - see the
   1840 	 * comment header on perform_inode_move. */
   1841 	inomove_init();
   1842 	for (i = newsb->fs_ncg; i < oldsb->fs_ncg; i++)
   1843 		evict_inodes(cgs[i]);
   1844 	perform_inode_move();
   1845 	flush_inodes();
   1846 	update_for_inode_move();
   1847 	/* Recompute all the bitmaps; most of them probably need it anyway,
   1848 	 * the rest are just paranoia and not wanting to have to bother
   1849 	 * keeping track of exactly which ones require it. */
   1850 	for (i = 0; i < newsb->fs_ncg; i++)
   1851 		cgflags[i] |= CGF_DIRTY | CGF_BLKMAPS | CGF_INOMAPS;
   1852 	/* Update the cg_old_ncyl value for the last cylinder. */
   1853 	if ((newsb->fs_old_flags & FS_FLAGS_UPDATED) == 0)
   1854 		cgs[newsb->fs_ncg - 1]->cg_old_ncyl =
   1855 		    newsb->fs_old_ncyl % newsb->fs_old_cpg;
   1856 	/* Make fs_dsize match the new reality. */
   1857 	recompute_fs_dsize();
   1858 }
   1859 /*
   1860  * Recompute the block totals, block cluster summaries, and rotational
   1861  *  position summaries, for a given cg (specified by number), based on
   1862  *  its free-frag bitmap (cg_blksfree()[]).
   1863  */
   1864 static void
   1865 rescan_blkmaps(int cgn)
   1866 {
   1867 	struct cg *cg;
   1868 	uint32_t f;
   1869 	int b;
   1870 	int blkfree;
   1871 	int blkrun;
   1872 	int fragrun;
   1873 	int fwb;
   1874 
   1875 	cg = cgs[cgn];
   1876 	/* Subtract off the current totals from the sb's summary info */
   1877 	newsb->fs_cstotal.cs_nffree -= cg->cg_cs.cs_nffree;
   1878 	newsb->fs_cstotal.cs_nbfree -= cg->cg_cs.cs_nbfree;
   1879 	/* Clear counters and bitmaps. */
   1880 	cg->cg_cs.cs_nffree = 0;
   1881 	cg->cg_cs.cs_nbfree = 0;
   1882 	memset(&cg->cg_frsum[0], 0, MAXFRAG * sizeof(cg->cg_frsum[0]));
   1883 	memset(&old_cg_blktot(cg, 0)[0], 0,
   1884 	    newsb->fs_old_cpg * sizeof(old_cg_blktot(cg, 0)[0]));
   1885 	memset(&old_cg_blks(newsb, cg, 0, 0)[0], 0,
   1886 	    newsb->fs_old_cpg * newsb->fs_old_nrpos *
   1887 	    sizeof(old_cg_blks(newsb, cg, 0, 0)[0]));
   1888 	if (newsb->fs_contigsumsize > 0) {
   1889 		cg->cg_nclusterblks = cg->cg_ndblk / newsb->fs_frag;
   1890 		memset(&cg_clustersum(cg, 0)[1], 0,
   1891 		    newsb->fs_contigsumsize *
   1892 		    sizeof(cg_clustersum(cg, 0)[1]));
   1893 		if (is_ufs2)
   1894 			memset(&cg_clustersfree(cg, 0)[0], 0,
   1895 			    howmany(newsb->fs_fpg / NSPB(newsb), NBBY));
   1896 		else
   1897 			memset(&cg_clustersfree(cg, 0)[0], 0,
   1898 			    howmany((newsb->fs_old_cpg * newsb->fs_old_spc) /
   1899 				NSPB(newsb), NBBY));
   1900 	}
   1901 	/* Scan the free-frag bitmap.  Runs of free frags are kept
   1902 	 * track of with fragrun, and recorded into cg_frsum[] and
   1903 	 * cg_cs.cs_nffree; on each block boundary, entire free blocks
   1904 	 * are recorded as well. */
   1905 	blkfree = 1;
   1906 	blkrun = 0;
   1907 	fragrun = 0;
   1908 	f = 0;
   1909 	b = 0;
   1910 	fwb = 0;
   1911 	while (f < cg->cg_ndblk) {
   1912 		if (bit_is_set(cg_blksfree(cg, 0), f)) {
   1913 			fragrun++;
   1914 		} else {
   1915 			blkfree = 0;
   1916 			if (fragrun > 0) {
   1917 				cg->cg_frsum[fragrun]++;
   1918 				cg->cg_cs.cs_nffree += fragrun;
   1919 			}
   1920 			fragrun = 0;
   1921 		}
   1922 		f++;
   1923 		fwb++;
   1924 		if (fwb >= newsb->fs_frag) {
   1925 			if (blkfree) {
   1926 				cg->cg_cs.cs_nbfree++;
   1927 				if (newsb->fs_contigsumsize > 0)
   1928 					set_bits(cg_clustersfree(cg, 0), b, 1);
   1929 				if (is_ufs2 == 0) {
   1930 					old_cg_blktot(cg, 0)[
   1931 						old_cbtocylno(newsb,
   1932 						    f - newsb->fs_frag)]++;
   1933 					old_cg_blks(newsb, cg,
   1934 					    old_cbtocylno(newsb,
   1935 						f - newsb->fs_frag),
   1936 					    0)[old_cbtorpos(newsb,
   1937 						    f - newsb->fs_frag)]++;
   1938 				}
   1939 				blkrun++;
   1940 			} else {
   1941 				if (fragrun > 0) {
   1942 					cg->cg_frsum[fragrun]++;
   1943 					cg->cg_cs.cs_nffree += fragrun;
   1944 				}
   1945 				if (newsb->fs_contigsumsize > 0) {
   1946 					if (blkrun > 0) {
   1947 						cg_clustersum(cg, 0)[(blkrun
   1948 						    > newsb->fs_contigsumsize)
   1949 						    ? newsb->fs_contigsumsize
   1950 						    : blkrun]++;
   1951 					}
   1952 				}
   1953 				blkrun = 0;
   1954 			}
   1955 			fwb = 0;
   1956 			b++;
   1957 			blkfree = 1;
   1958 			fragrun = 0;
   1959 		}
   1960 	}
   1961 	if (fragrun > 0) {
   1962 		cg->cg_frsum[fragrun]++;
   1963 		cg->cg_cs.cs_nffree += fragrun;
   1964 	}
   1965 	if ((blkrun > 0) && (newsb->fs_contigsumsize > 0)) {
   1966 		cg_clustersum(cg, 0)[(blkrun > newsb->fs_contigsumsize) ?
   1967 		    newsb->fs_contigsumsize : blkrun]++;
   1968 	}
   1969 	/*
   1970          * Put the updated summary info back into csums, and add it
   1971          * back into the sb's summary info.  Then mark the cg dirty.
   1972          */
   1973 	csums[cgn] = cg->cg_cs;
   1974 	newsb->fs_cstotal.cs_nffree += cg->cg_cs.cs_nffree;
   1975 	newsb->fs_cstotal.cs_nbfree += cg->cg_cs.cs_nbfree;
   1976 	cgflags[cgn] |= CGF_DIRTY;
   1977 }
   1978 /*
   1979  * Recompute the cg_inosused()[] bitmap, and the cs_nifree and cs_ndir
   1980  *  values, for a cg, based on the in-core inodes for that cg.
   1981  */
   1982 static void
   1983 rescan_inomaps(int cgn)
   1984 {
   1985 	struct cg *cg;
   1986 	int inum;
   1987 	uint32_t iwc;
   1988 
   1989 	cg = cgs[cgn];
   1990 	newsb->fs_cstotal.cs_ndir -= cg->cg_cs.cs_ndir;
   1991 	newsb->fs_cstotal.cs_nifree -= cg->cg_cs.cs_nifree;
   1992 	cg->cg_cs.cs_ndir = 0;
   1993 	cg->cg_cs.cs_nifree = 0;
   1994 	memset(&cg_inosused(cg, 0)[0], 0, howmany(newsb->fs_ipg, NBBY));
   1995 	inum = cgn * newsb->fs_ipg;
   1996 	if (cgn == 0) {
   1997 		set_bits(cg_inosused(cg, 0), 0, 2);
   1998 		iwc = 2;
   1999 		inum += 2;
   2000 	} else {
   2001 		iwc = 0;
   2002 	}
   2003 	for (; iwc < newsb->fs_ipg; iwc++, inum++) {
   2004 		switch (DIP(inodes + inum, di_mode) & IFMT) {
   2005 		case 0:
   2006 			cg->cg_cs.cs_nifree++;
   2007 			break;
   2008 		case IFDIR:
   2009 			cg->cg_cs.cs_ndir++;
   2010 			/* FALLTHROUGH */
   2011 		default:
   2012 			set_bits(cg_inosused(cg, 0), iwc, 1);
   2013 			break;
   2014 		}
   2015 	}
   2016 	csums[cgn] = cg->cg_cs;
   2017 	newsb->fs_cstotal.cs_ndir += cg->cg_cs.cs_ndir;
   2018 	newsb->fs_cstotal.cs_nifree += cg->cg_cs.cs_nifree;
   2019 	cgflags[cgn] |= CGF_DIRTY;
   2020 }
   2021 /*
   2022  * Flush cgs to disk, recomputing anything they're marked as needing.
   2023  */
   2024 static void
   2025 flush_cgs(void)
   2026 {
   2027 	uint32_t i;
   2028 
   2029 	for (i = 0; i < newsb->fs_ncg; i++) {
   2030 		progress_bar(special, "flush cg",
   2031 		    i, newsb->fs_ncg - 1);
   2032 		if (cgflags[i] & CGF_BLKMAPS) {
   2033 			rescan_blkmaps(i);
   2034 		}
   2035 		if (cgflags[i] & CGF_INOMAPS) {
   2036 			rescan_inomaps(i);
   2037 		}
   2038 		if (cgflags[i] & CGF_DIRTY) {
   2039 			cgs[i]->cg_rotor = 0;
   2040 			cgs[i]->cg_frotor = 0;
   2041 			cgs[i]->cg_irotor = 0;
   2042 			if (needswap)
   2043 				ffs_cg_swap(cgs[i],cgs[i],newsb);
   2044 			writeat(FFS_FSBTODB(newsb, cgtod(newsb, i)), cgs[i],
   2045 			    cgblksz);
   2046 		}
   2047 	}
   2048 	if (needswap)
   2049 		ffs_csum_swap(csums,csums,newsb->fs_cssize);
   2050 	writeat(FFS_FSBTODB(newsb, newsb->fs_csaddr), csums, newsb->fs_cssize);
   2051 
   2052 	progress_done();
   2053 }
   2054 /*
   2055  * Write the superblock, both to the main superblock and to each cg's
   2056  *  alternative superblock.
   2057  */
   2058 static void
   2059 write_sbs(void)
   2060 {
   2061 	uint32_t i;
   2062 
   2063 	if (newsb->fs_magic == FS_UFS1_MAGIC &&
   2064 	    (newsb->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
   2065 		newsb->fs_old_time = newsb->fs_time;
   2066 	    	newsb->fs_old_size = newsb->fs_size;
   2067 	    	/* we don't update fs_csaddr */
   2068 	    	newsb->fs_old_dsize = newsb->fs_dsize;
   2069 		newsb->fs_old_cstotal.cs_ndir = newsb->fs_cstotal.cs_ndir;
   2070 		newsb->fs_old_cstotal.cs_nbfree = newsb->fs_cstotal.cs_nbfree;
   2071 		newsb->fs_old_cstotal.cs_nifree = newsb->fs_cstotal.cs_nifree;
   2072 		newsb->fs_old_cstotal.cs_nffree = newsb->fs_cstotal.cs_nffree;
   2073 		/* fill fs_old_postbl_start with 256 bytes of 0xff? */
   2074 	}
   2075 	/* copy newsb back to oldsb, so we can use it for offsets if
   2076 	   newsb has been swapped for writing to disk */
   2077 	memcpy(oldsb, newsb, SBLOCKSIZE);
   2078 	if (needswap)
   2079 		ffs_sb_swap(newsb,newsb);
   2080 	writeat(where /  DEV_BSIZE, newsb, SBLOCKSIZE);
   2081 	for (i = 0; i < oldsb->fs_ncg; i++) {
   2082 		progress_bar(special, "write sb",
   2083 		    i, oldsb->fs_ncg - 1);
   2084 		writeat(FFS_FSBTODB(oldsb, cgsblock(oldsb, i)), newsb, SBLOCKSIZE);
   2085 	}
   2086 
   2087 	progress_done();
   2088 }
   2089 
   2090 /*
   2091  * Check to see whether new size changes the filesystem
   2092  *  return exit code
   2093  */
   2094 static int
   2095 checkonly(void)
   2096 {
   2097 	if (makegeometry(0)) {
   2098 		if (verbose) {
   2099 			printf("Wouldn't change: already %" PRId64
   2100 			    " blocks\n", (int64_t)oldsb->fs_size);
   2101 		}
   2102 		return 1;
   2103 	}
   2104 
   2105 	if (verbose) {
   2106 		printf("Would change: newsize: %" PRId64 " oldsize: %"
   2107 		    PRId64 " fsdb: %" PRId64 "\n", FFS_DBTOFSB(oldsb, newsize),
   2108 		    (int64_t)oldsb->fs_size,
   2109 		    (int64_t)oldsb->fs_fsbtodb);
   2110 	}
   2111 	return 0;
   2112 }
   2113 
   2114 static off_t
   2115 get_dev_size(const char *dev_name)
   2116 {
   2117 	struct dkwedge_info dkw;
   2118 	struct partition *pp;
   2119 	struct disklabel lp;
   2120 	struct stat st;
   2121 	size_t ptn;
   2122 
   2123 	/* Get info about partition/wedge */
   2124 	if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1)
   2125 		return dkw.dkw_size;
   2126 	if (ioctl(fd, DIOCGDINFO, &lp) != -1) {
   2127 		ptn = strchr(dev_name, '\0')[-1] - 'a';
   2128 		if (ptn >= lp.d_npartitions)
   2129 			return 0;
   2130 		pp = &lp.d_partitions[ptn];
   2131 		return pp->p_size;
   2132 	}
   2133 	if (fstat(fd, &st) != -1 && S_ISREG(st.st_mode))
   2134 		return st.st_size / DEV_BSIZE;
   2135 
   2136 	return 0;
   2137 }
   2138 
   2139 /*
   2140  * main().
   2141  */
   2142 int
   2143 main(int argc, char **argv)
   2144 {
   2145 	int ch;
   2146 	int CheckOnlyFlag;
   2147 	int ExpertFlag;
   2148 	int SFlag;
   2149 	size_t i;
   2150 	char specname[MAXPATHLEN];
   2151 	char rawname[MAXPATHLEN];
   2152 	const char *raw;
   2153 
   2154 	char reply[5];
   2155 
   2156 	newsize = 0;
   2157 	ExpertFlag = 0;
   2158 	SFlag = 0;
   2159         CheckOnlyFlag = 0;
   2160 
   2161 	while ((ch = getopt(argc, argv, "cps:vy")) != -1) {
   2162 		switch (ch) {
   2163                 case 'c':
   2164 			CheckOnlyFlag = 1;
   2165 			break;
   2166 		case 'p':
   2167 			progress = 1;
   2168 			break;
   2169 		case 's':
   2170 			SFlag = 1;
   2171 			newsize = strtoll(optarg, NULL, 10);
   2172 			if(newsize < 1) {
   2173 				usage();
   2174 			}
   2175 			break;
   2176 		case 'v':
   2177 			verbose = 1;
   2178 			break;
   2179 		case 'y':
   2180 			ExpertFlag = 1;
   2181 			break;
   2182 		case '?':
   2183 			/* FALLTHROUGH */
   2184 		default:
   2185 			usage();
   2186 		}
   2187 	}
   2188 	argc -= optind;
   2189 	argv += optind;
   2190 
   2191 	if (argc != 1) {
   2192 		usage();
   2193 	}
   2194 
   2195 	special = getfsspecname(specname, sizeof(specname), argv[0]);
   2196 	if (special == NULL)
   2197 		err(EXIT_FAILURE, "%s: %s", argv[0], specname);
   2198 	raw = getdiskrawname(rawname, sizeof(rawname), special);
   2199 	if (raw != NULL)
   2200 		special = raw;
   2201 
   2202 	if (ExpertFlag == 0 && CheckOnlyFlag == 0) {
   2203 		printf("It's required to manually run fsck on file system "
   2204 		    "before you can resize it\n\n"
   2205 		    " Did you run fsck on your disk (Yes/No) ? ");
   2206 		fgets(reply, (int)sizeof(reply), stdin);
   2207 		if (strcasecmp(reply, "Yes\n")) {
   2208 			printf("\n Nothing done \n");
   2209 			exit(EXIT_SUCCESS);
   2210 		}
   2211 	}
   2212 
   2213 	fd = open(special, O_RDWR, 0);
   2214 	if (fd < 0)
   2215 		err(EXIT_FAILURE, "Can't open `%s'", special);
   2216 	checksmallio();
   2217 
   2218 	if (SFlag == 0) {
   2219 		newsize = get_dev_size(special);
   2220 		if (newsize == 0)
   2221 			err(EXIT_FAILURE,
   2222 			    "Can't resize file system, newsize not known.");
   2223 	}
   2224 
   2225 	oldsb = (struct fs *) & sbbuf;
   2226 	newsb = (struct fs *) (SBLOCKSIZE + (char *) &sbbuf);
   2227 	for (where = search[i = 0]; search[i] != -1; where = search[++i]) {
   2228 		readat(where / DEV_BSIZE, oldsb, SBLOCKSIZE);
   2229 		switch (oldsb->fs_magic) {
   2230 		case FS_UFS2_MAGIC:
   2231 		case FS_UFS2EA_MAGIC:
   2232 			is_ufs2 = 1;
   2233 			/* FALLTHROUGH */
   2234 		case FS_UFS1_MAGIC:
   2235 			needswap = 0;
   2236 			break;
   2237 		case FS_UFS2_MAGIC_SWAPPED:
   2238 		case FS_UFS2EA_MAGIC_SWAPPED:
   2239  			is_ufs2 = 1;
   2240 			/* FALLTHROUGH */
   2241 		case FS_UFS1_MAGIC_SWAPPED:
   2242 			needswap = 1;
   2243 			break;
   2244 		default:
   2245 			continue;
   2246 		}
   2247 		if (!is_ufs2 && where == SBLOCK_UFS2)
   2248 			continue;
   2249 		break;
   2250 	}
   2251 	if (where == (off_t)-1)
   2252 		errx(EXIT_FAILURE, "Bad magic number");
   2253 	if (needswap)
   2254 		ffs_sb_swap(oldsb,oldsb);
   2255 	if (oldsb->fs_magic == FS_UFS1_MAGIC &&
   2256 	    (oldsb->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
   2257 		oldsb->fs_csaddr = oldsb->fs_old_csaddr;
   2258 		oldsb->fs_size = oldsb->fs_old_size;
   2259 		oldsb->fs_dsize = oldsb->fs_old_dsize;
   2260 		oldsb->fs_cstotal.cs_ndir = oldsb->fs_old_cstotal.cs_ndir;
   2261 		oldsb->fs_cstotal.cs_nbfree = oldsb->fs_old_cstotal.cs_nbfree;
   2262 		oldsb->fs_cstotal.cs_nifree = oldsb->fs_old_cstotal.cs_nifree;
   2263 		oldsb->fs_cstotal.cs_nffree = oldsb->fs_old_cstotal.cs_nffree;
   2264 		/* any others? */
   2265 		printf("Resizing with ffsv1 superblock\n");
   2266 	}
   2267 
   2268 	oldsb->fs_qbmask = ~(int64_t) oldsb->fs_bmask;
   2269 	oldsb->fs_qfmask = ~(int64_t) oldsb->fs_fmask;
   2270 	if (oldsb->fs_ipg % FFS_INOPB(oldsb))
   2271 		errx(EXIT_FAILURE, "ipg[%d] %% FFS_INOPB[%d] != 0",
   2272 		    (int) oldsb->fs_ipg, (int) FFS_INOPB(oldsb));
   2273 	/* The superblock is bigger than struct fs (there are trailing
   2274 	 * tables, of non-fixed size); make sure we copy the whole
   2275 	 * thing.  SBLOCKSIZE may be an over-estimate, but we do this
   2276 	 * just once, so being generous is cheap. */
   2277 	memcpy(newsb, oldsb, SBLOCKSIZE);
   2278 
   2279 	if (progress) {
   2280 		progress_ttywidth(0);
   2281 		signal(SIGWINCH, progress_ttywidth);
   2282 	}
   2283 
   2284 	loadcgs();
   2285 
   2286 	if (progress && !CheckOnlyFlag) {
   2287 		progress_switch(progress);
   2288 		progress_init();
   2289 	}
   2290 
   2291 	if (newsize > FFS_FSBTODB(oldsb, oldsb->fs_size)) {
   2292 		if (CheckOnlyFlag)
   2293 			exit(checkonly());
   2294 		grow();
   2295 	} else if (newsize < FFS_FSBTODB(oldsb, oldsb->fs_size)) {
   2296 		if (is_ufs2)
   2297 			errx(EXIT_FAILURE,"shrinking not supported for ufs2");
   2298 		if (CheckOnlyFlag)
   2299 			exit(checkonly());
   2300 		shrink();
   2301 	} else {
   2302 		if (CheckOnlyFlag)
   2303 			exit(checkonly());
   2304 		if (verbose)
   2305 			printf("No change requested: already %" PRId64
   2306 			    " blocks\n", (int64_t)oldsb->fs_size);
   2307 	}
   2308 
   2309 	flush_cgs();
   2310 	write_sbs();
   2311 	if (isplainfile())
   2312 		ftruncate(fd,newsize * DEV_BSIZE);
   2313 	return 0;
   2314 }
   2315 
   2316 static void
   2317 usage(void)
   2318 {
   2319 
   2320 	(void)fprintf(stderr, "usage: %s [-cpvy] [-s size] special\n",
   2321 	    getprogname());
   2322 	exit(EXIT_FAILURE);
   2323 }
   2324