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