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