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