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