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