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