xref: /netbsd-src/sbin/resize_ffs/resize_ffs.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: resize_ffs.c,v 1.46 2016/03/17 01:41:54 christos 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.46 2016/03/17 01:41:54 christos 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; j++)
1266 						dp2[i].di_db[j] =
1267 						    bswap32(dp2[i].di_db[j]);
1268 					for (j = 0; j < UFS_NIADDR; j++)
1269 						dp2[i].di_ib[j] =
1270 						    bswap32(dp2[i].di_ib[j]);
1271 				}
1272 				memcpy(&inodes[ino].dp2, &dp2[i],
1273 				    sizeof(inodes[ino].dp2));
1274 			} else {
1275 				if (needswap) {
1276 					ffs_dinode1_swap(&(dp1[i]), &(dp1[i]));
1277 					for (j = 0; j < UFS_NDADDR; j++)
1278 						dp1[i].di_db[j] =
1279 						    bswap32(dp1[i].di_db[j]);
1280 					for (j = 0; j < UFS_NIADDR; j++)
1281 						dp1[i].di_ib[j] =
1282 						    bswap32(dp1[i].di_ib[j]);
1283 				}
1284 				memcpy(&inodes[ino].dp1, &dp1[i],
1285 				    sizeof(inodes[ino].dp1));
1286 			}
1287 			    if (++ino > imax)
1288 				    errx(EXIT_FAILURE,
1289 					"Exceeded number of inodes");
1290 		}
1291 
1292 	}
1293 }
1294 /*
1295  * Report a file-system-too-full problem.
1296  */
1297 __dead static void
1298 toofull(void)
1299 {
1300 	errx(EXIT_FAILURE, "Sorry, would run out of data blocks");
1301 }
1302 /*
1303  * Record a desire to move "n" frags from "from" to "to".
1304  */
1305 static void
1306 mark_move(unsigned int from, unsigned int to, unsigned int n)
1307 {
1308 	for (; n > 0; n--)
1309 		blkmove[from++] = to++;
1310 }
1311 /* Helper function - evict n frags, starting with start (cg-relative).
1312  * The free bitmap is scanned, unallocated frags are ignored, and
1313  * each block of consecutive allocated frags is moved as a unit.
1314  */
1315 static void
1316 fragmove(struct cg * cg, int base, unsigned int start, unsigned int n)
1317 {
1318 	unsigned int i;
1319 	int run;
1320 
1321 	run = 0;
1322 	for (i = 0; i <= n; i++) {
1323 		if ((i < n) && bit_is_clr(cg_blksfree(cg, 0), start + i)) {
1324 			run++;
1325 		} else {
1326 			if (run > 0) {
1327 				int off;
1328 				off = find_freespace(run);
1329 				if (off < 0)
1330 					toofull();
1331 				mark_move(base + start + i - run, off, run);
1332 				set_bits(cg_blksfree(cg, 0), start + i - run,
1333 				    run);
1334 				clr_bits(cg_blksfree(cgs[dtog(oldsb, off)], 0),
1335 				    dtogd(oldsb, off), run);
1336 			}
1337 			run = 0;
1338 		}
1339 	}
1340 }
1341 /*
1342  * Evict all data blocks from the given cg, starting at minfrag (based
1343  *  at the beginning of the cg), for length nfrag.  The eviction is
1344  *  assumed to be entirely data-area; this should not be called with a
1345  *  range overlapping the metadata structures in the cg.  It also
1346  *  assumes minfrag points into the given cg; it will misbehave if this
1347  *  is not true.
1348  *
1349  * See the comment header on find_freespace() for one possible bug
1350  *  lurking here.
1351  */
1352 static void
1353 evict_data(struct cg * cg, unsigned int minfrag, int nfrag)
1354 {
1355 	int base;	/* base of cg (in frags from beginning of fs) */
1356 
1357 	base = cgbase(oldsb, cg->cg_cgx);
1358 	/* Does the boundary fall in the middle of a block?  To avoid
1359 	 * breaking between frags allocated as consecutive, we always
1360 	 * evict the whole block in this case, though one could argue
1361 	 * we should check to see if the frag before or after the
1362 	 * break is unallocated. */
1363 	if (minfrag % oldsb->fs_frag) {
1364 		int n;
1365 		n = minfrag % oldsb->fs_frag;
1366 		minfrag -= n;
1367 		nfrag += n;
1368 	}
1369 	/* Do whole blocks.  If a block is wholly free, skip it; if
1370 	 * wholly allocated, move it in toto.  If neither, call
1371 	 * fragmove() to move the frags to new locations. */
1372 	while (nfrag >= oldsb->fs_frag) {
1373 		if (!blk_is_set(cg_blksfree(cg, 0), minfrag, oldsb->fs_frag)) {
1374 			if (blk_is_clr(cg_blksfree(cg, 0), minfrag,
1375 				oldsb->fs_frag)) {
1376 				int off;
1377 				off = find_freeblock();
1378 				if (off < 0)
1379 					toofull();
1380 				mark_move(base + minfrag, off, oldsb->fs_frag);
1381 				set_bits(cg_blksfree(cg, 0), minfrag,
1382 				    oldsb->fs_frag);
1383 				clr_bits(cg_blksfree(cgs[dtog(oldsb, off)], 0),
1384 				    dtogd(oldsb, off), oldsb->fs_frag);
1385 			} else {
1386 				fragmove(cg, base, minfrag, oldsb->fs_frag);
1387 			}
1388 		}
1389 		minfrag += oldsb->fs_frag;
1390 		nfrag -= oldsb->fs_frag;
1391 	}
1392 	/* Clean up any sub-block amount left over. */
1393 	if (nfrag) {
1394 		fragmove(cg, base, minfrag, nfrag);
1395 	}
1396 }
1397 /*
1398  * Move all data blocks according to blkmove.  We have to be careful,
1399  *  because we may be updating indirect blocks that will themselves be
1400  *  getting moved, or inode int32_t arrays that point to indirect
1401  *  blocks that will be moved.  We call this before
1402  *  update_for_data_move, and update_for_data_move does inodes first,
1403  *  then indirect blocks in preorder, so as to make sure that the
1404  *  file system is self-consistent at all points, for better crash
1405  *  tolerance.  (We can get away with this only because all the writes
1406  *  done by perform_data_move() are writing into space that's not used
1407  *  by the old file system.)  If we crash, some things may point to the
1408  *  old data and some to the new, but both copies are the same.  The
1409  *  only wrong things should be csum info and free bitmaps, which fsck
1410  *  is entirely capable of cleaning up.
1411  *
1412  * Since blkmove_init() initializes all blocks to move to their current
1413  *  locations, we can have two blocks marked as wanting to move to the
1414  *  same location, but only two and only when one of them is the one
1415  *  that was already there.  So if blkmove[i]==i, we ignore that entry
1416  *  entirely - for unallocated blocks, we don't want it (and may be
1417  *  putting something else there), and for allocated blocks, we don't
1418  *  want to copy it anywhere.
1419  */
1420 static void
1421 perform_data_move(void)
1422 {
1423 	int i;
1424 	int run;
1425 	int maxrun;
1426 	char buf[65536];
1427 
1428 	maxrun = sizeof(buf) / newsb->fs_fsize;
1429 	run = 0;
1430 	for (i = 0; i < oldsb->fs_size; i++) {
1431 		if ((blkmove[i] == (unsigned)i /*XXX cast*/) ||
1432 		    (run >= maxrun) ||
1433 		    ((run > 0) &&
1434 			(blkmove[i] != blkmove[i - 1] + 1))) {
1435 			if (run > 0) {
1436 				readat(FFS_FSBTODB(oldsb, i - run), &buf[0],
1437 				    run << oldsb->fs_fshift);
1438 				writeat(FFS_FSBTODB(oldsb, blkmove[i - run]),
1439 				    &buf[0], run << oldsb->fs_fshift);
1440 			}
1441 			run = 0;
1442 		}
1443 		if (blkmove[i] != (unsigned)i /*XXX cast*/)
1444 			run++;
1445 	}
1446 	if (run > 0) {
1447 		readat(FFS_FSBTODB(oldsb, i - run), &buf[0],
1448 		    run << oldsb->fs_fshift);
1449 		writeat(FFS_FSBTODB(oldsb, blkmove[i - run]), &buf[0],
1450 		    run << oldsb->fs_fshift);
1451 	}
1452 }
1453 /*
1454  * This modifies an array of int32_t, according to blkmove.  This is
1455  *  used to update inode block arrays and indirect blocks to point to
1456  *  the new locations of data blocks.
1457  *
1458  * Return value is the number of int32_ts that needed updating; in
1459  *  particular, the return value is zero iff nothing was modified.
1460  */
1461 static int
1462 movemap_blocks(int32_t * vec, int n)
1463 {
1464 	int rv;
1465 
1466 	rv = 0;
1467 	for (; n > 0; n--, vec++) {
1468 		if (blkmove[*vec] != (unsigned)*vec /*XXX cast*/) {
1469 			*vec = blkmove[*vec];
1470 			rv++;
1471 		}
1472 	}
1473 	return (rv);
1474 }
1475 static void
1476 moveblocks_callback(union dinode * di, unsigned int inum, void *arg)
1477 {
1478 	int32_t *dblkptr, *iblkptr;
1479 
1480 	switch (DIP(di,di_mode) & IFMT) {
1481 	case IFLNK:
1482 		if ((off_t)DIP(di,di_size) <= oldsb->fs_maxsymlinklen) {
1483 			break;
1484 		}
1485 		/* FALLTHROUGH */
1486 	case IFDIR:
1487 	case IFREG:
1488 		if (is_ufs2) {
1489 			/* XXX these are not int32_t and this is WRONG! */
1490 			dblkptr = (void *) &(di->dp2.di_db[0]);
1491 			iblkptr = (void *) &(di->dp2.di_ib[0]);
1492 		} else {
1493 			dblkptr = &(di->dp1.di_db[0]);
1494 			iblkptr = &(di->dp1.di_ib[0]);
1495 		}
1496 		/*
1497 		 * Don't || these two calls; we need their
1498 		 * side-effects.
1499 		 */
1500 		if (movemap_blocks(dblkptr, UFS_NDADDR)) {
1501 			iflags[inum] |= IF_DIRTY;
1502 		}
1503 		if (movemap_blocks(iblkptr, UFS_NIADDR)) {
1504 			iflags[inum] |= IF_DIRTY;
1505 		}
1506 		break;
1507 	}
1508 }
1509 
1510 static void
1511 moveindir_callback(off_t off, unsigned int nfrag, unsigned int nbytes,
1512 		   int kind)
1513 {
1514 	unsigned int i;
1515 
1516 	if (kind == MDB_INDIR_PRE) {
1517 		int32_t blk[howmany(MAXBSIZE, sizeof(int32_t))];
1518 		readat(FFS_FSBTODB(oldsb, off), &blk[0], oldsb->fs_bsize);
1519 		if (needswap)
1520 			for (i = 0; i < howmany(MAXBSIZE, sizeof(int32_t)); i++)
1521 				blk[i] = bswap32(blk[i]);
1522 		if (movemap_blocks(&blk[0], FFS_NINDIR(oldsb))) {
1523 			if (needswap)
1524 				for (i = 0; i < howmany(MAXBSIZE,
1525 					sizeof(int32_t)); i++)
1526 					blk[i] = bswap32(blk[i]);
1527 			writeat(FFS_FSBTODB(oldsb, off), &blk[0], oldsb->fs_bsize);
1528 		}
1529 	}
1530 }
1531 /*
1532  * Update all inode data arrays and indirect blocks to point to the new
1533  *  locations of data blocks.  See the comment header on
1534  *  perform_data_move for some ordering considerations.
1535  */
1536 static void
1537 update_for_data_move(void)
1538 {
1539 	map_inodes(&moveblocks_callback, oldsb->fs_ncg, NULL);
1540 	map_data_blocks(&moveindir_callback, oldsb->fs_ncg);
1541 }
1542 /*
1543  * Initialize the inomove array.
1544  */
1545 static void
1546 inomove_init(void)
1547 {
1548 	int i;
1549 
1550 	inomove = alloconce(oldsb->fs_ipg * oldsb->fs_ncg * sizeof(*inomove),
1551                             "inomove");
1552 	for (i = (oldsb->fs_ipg * oldsb->fs_ncg) - 1; i >= 0; i--)
1553 		inomove[i] = i;
1554 }
1555 /*
1556  * Flush all dirtied inodes to disk.  Scans the inode flags array; for
1557  *  each dirty inode, it sets the BDIRTY bit on the first inode in the
1558  *  block containing the dirty inode.  Then it scans by blocks, and for
1559  *  each marked block, writes it.
1560  */
1561 static void
1562 flush_inodes(void)
1563 {
1564 	int i, j, k, ni, m;
1565 	struct ufs1_dinode *dp1 = NULL;
1566 	struct ufs2_dinode *dp2 = NULL;
1567 
1568 	ni = newsb->fs_ipg * newsb->fs_ncg;
1569 	m = FFS_INOPB(newsb) - 1;
1570 	for (i = 0; i < ni; i++) {
1571 		if (iflags[i] & IF_DIRTY) {
1572 			iflags[i & ~m] |= IF_BDIRTY;
1573 		}
1574 	}
1575 	m++;
1576 
1577 	if (is_ufs2)
1578 		dp2 = (struct ufs2_dinode *)ibuf;
1579 	else
1580 		dp1 = (struct ufs1_dinode *)ibuf;
1581 
1582 	for (i = 0; i < ni; i += m) {
1583 		if ((iflags[i] & IF_BDIRTY) == 0)
1584 			continue;
1585 		if (is_ufs2)
1586 			for (j = 0; j < m; j++) {
1587 				dp2[j] = inodes[i + j].dp2;
1588 				if (needswap) {
1589 					for (k = 0; k < UFS_NDADDR; k++)
1590 						dp2[j].di_db[k] =
1591 						    bswap32(dp2[j].di_db[k]);
1592 					for (k = 0; k < UFS_NIADDR; k++)
1593 						dp2[j].di_ib[k] =
1594 						    bswap32(dp2[j].di_ib[k]);
1595 					ffs_dinode2_swap(&dp2[j],
1596 					    &dp2[j]);
1597 				}
1598 			}
1599 		else
1600 			for (j = 0; j < m; j++) {
1601 				dp1[j] = inodes[i + j].dp1;
1602 				if (needswap) {
1603 					for (k = 0; k < UFS_NDADDR; k++)
1604 						dp1[j].di_db[k]=
1605 						    bswap32(dp1[j].di_db[k]);
1606 					for (k = 0; k < UFS_NIADDR; k++)
1607 						dp1[j].di_ib[k]=
1608 						    bswap32(dp1[j].di_ib[k]);
1609 					ffs_dinode1_swap(&dp1[j],
1610 					    &dp1[j]);
1611 				}
1612 			}
1613 
1614 		writeat(FFS_FSBTODB(newsb, ino_to_fsba(newsb, i)),
1615 		    ibuf, newsb->fs_bsize);
1616 	}
1617 }
1618 /*
1619  * Evict all inodes from the specified cg.  shrink() already checked
1620  *  that there were enough free inodes, so the no-free-inodes check is
1621  *  a can't-happen.  If it does trip, the file system should be in good
1622  *  enough shape for fsck to fix; see the comment on perform_data_move
1623  *  for the considerations in question.
1624  */
1625 static void
1626 evict_inodes(struct cg * cg)
1627 {
1628 	int inum;
1629 	int i;
1630 	int fi;
1631 
1632 	inum = newsb->fs_ipg * cg->cg_cgx;
1633 	for (i = 0; i < newsb->fs_ipg; i++, inum++) {
1634 		if (DIP(inodes + inum,di_mode) != 0) {
1635 			fi = find_freeinode();
1636 			if (fi < 0)
1637 				errx(EXIT_FAILURE, "Sorry, inodes evaporated - "
1638 				    "file system probably needs fsck");
1639 			inomove[inum] = fi;
1640 			clr_bits(cg_inosused(cg, 0), i, 1);
1641 			set_bits(cg_inosused(cgs[ino_to_cg(newsb, fi)], 0),
1642 			    fi % newsb->fs_ipg, 1);
1643 		}
1644 	}
1645 }
1646 /*
1647  * Move inodes from old locations to new.  Does not actually write
1648  *  anything to disk; just copies in-core and sets dirty bits.
1649  *
1650  * We have to be careful here for reasons similar to those mentioned in
1651  *  the comment header on perform_data_move, above: for the sake of
1652  *  crash tolerance, we want to make sure everything is present at both
1653  *  old and new locations before we update pointers.  So we call this
1654  *  first, then flush_inodes() to get them out on disk, then update
1655  *  directories to match.
1656  */
1657 static void
1658 perform_inode_move(void)
1659 {
1660 	unsigned int i;
1661 	unsigned int ni;
1662 
1663 	ni = oldsb->fs_ipg * oldsb->fs_ncg;
1664 	for (i = 0; i < ni; i++) {
1665 		if (inomove[i] != i) {
1666 			inodes[inomove[i]] = inodes[i];
1667 			iflags[inomove[i]] = iflags[i] | IF_DIRTY;
1668 		}
1669 	}
1670 }
1671 /*
1672  * Update the directory contained in the nb bytes at buf, to point to
1673  *  inodes' new locations.
1674  */
1675 static int
1676 update_dirents(char *buf, int nb)
1677 {
1678 	int rv;
1679 #define d ((struct direct *)buf)
1680 #define s32(x) (needswap?bswap32((x)):(x))
1681 #define s16(x) (needswap?bswap16((x)):(x))
1682 
1683 	rv = 0;
1684 	while (nb > 0) {
1685 		if (inomove[s32(d->d_ino)] != s32(d->d_ino)) {
1686 			rv++;
1687 			d->d_ino = s32(inomove[s32(d->d_ino)]);
1688 		}
1689 		nb -= s16(d->d_reclen);
1690 		buf += s16(d->d_reclen);
1691 	}
1692 	return (rv);
1693 #undef d
1694 #undef s32
1695 #undef s16
1696 }
1697 /*
1698  * Callback function for map_inode_data_blocks, for updating a
1699  *  directory to point to new inode locations.
1700  */
1701 static void
1702 update_dir_data(off_t bn, unsigned int size, unsigned int nb, int kind)
1703 {
1704 	if (kind == MDB_DATA) {
1705 		union {
1706 			struct direct d;
1707 			char ch[MAXBSIZE];
1708 		}     buf;
1709 		readat(FFS_FSBTODB(oldsb, bn), &buf, size << oldsb->fs_fshift);
1710 		if (update_dirents((char *) &buf, nb)) {
1711 			writeat(FFS_FSBTODB(oldsb, bn), &buf,
1712 			    size << oldsb->fs_fshift);
1713 		}
1714 	}
1715 }
1716 static void
1717 dirmove_callback(union dinode * di, unsigned int inum, void *arg)
1718 {
1719 	switch (DIP(di,di_mode) & IFMT) {
1720 	case IFDIR:
1721 		map_inode_data_blocks(di, &update_dir_data);
1722 		break;
1723 	}
1724 }
1725 /*
1726  * Update directory entries to point to new inode locations.
1727  */
1728 static void
1729 update_for_inode_move(void)
1730 {
1731 	map_inodes(&dirmove_callback, newsb->fs_ncg, NULL);
1732 }
1733 /*
1734  * Shrink the file system.
1735  */
1736 static void
1737 shrink(void)
1738 {
1739 	int i;
1740 
1741 	if (makegeometry(1)) {
1742 		printf("New fs size %"PRIu64" = old fs size %"PRIu64
1743 		    ", not shrinking.\n", newsb->fs_size, oldsb->fs_size);
1744 		return;
1745 	}
1746 
1747 	/* Let's make sure we're not being shrunk into oblivion. */
1748 	if (newsb->fs_ncg < 1)
1749 		errx(EXIT_FAILURE, "Size too small - file system would "
1750 		    "have no cylinders");
1751 
1752 	if (verbose) {
1753 		printf("Shrinking fs from %"PRIu64" blocks to %"PRIu64
1754 		    " blocks.\n", oldsb->fs_size, newsb->fs_size);
1755 	}
1756 
1757 	/* Load the inodes off disk - we'll need 'em. */
1758 	loadinodes();
1759 
1760 	/* Update the timestamp. */
1761 	newsb->fs_time = timestamp();
1762 
1763 	/* Initialize for block motion. */
1764 	blkmove_init();
1765 	/* Update csum size, then fix up for the new size */
1766 	newsb->fs_cssize = ffs_fragroundup(newsb,
1767 	    newsb->fs_ncg * sizeof(struct csum));
1768 	csum_fixup();
1769 	/* Evict data from any cgs being wholly eliminated */
1770 	for (i = newsb->fs_ncg; i < oldsb->fs_ncg; i++) {
1771 		int base;
1772 		int dlow;
1773 		int dhigh;
1774 		int dmax;
1775 		base = cgbase(oldsb, i);
1776 		dlow = cgsblock(oldsb, i) - base;
1777 		dhigh = cgdmin(oldsb, i) - base;
1778 		dmax = oldsb->fs_size - base;
1779 		if (dmax > cgs[i]->cg_ndblk)
1780 			dmax = cgs[i]->cg_ndblk;
1781 		evict_data(cgs[i], 0, dlow);
1782 		evict_data(cgs[i], dhigh, dmax - dhigh);
1783 		newsb->fs_cstotal.cs_ndir -= cgs[i]->cg_cs.cs_ndir;
1784 		newsb->fs_cstotal.cs_nifree -= cgs[i]->cg_cs.cs_nifree;
1785 		newsb->fs_cstotal.cs_nffree -= cgs[i]->cg_cs.cs_nffree;
1786 		newsb->fs_cstotal.cs_nbfree -= cgs[i]->cg_cs.cs_nbfree;
1787 	}
1788 	/* Update the new last cg. */
1789 	cgs[newsb->fs_ncg - 1]->cg_ndblk = newsb->fs_size -
1790 	    ((newsb->fs_ncg - 1) * newsb->fs_fpg);
1791 	/* Is the new last cg partial?  If so, evict any data from the part
1792 	 * being shrunken away. */
1793 	if (newsb->fs_size % newsb->fs_fpg) {
1794 		struct cg *cg;
1795 		int oldcgsize;
1796 		int newcgsize;
1797 		cg = cgs[newsb->fs_ncg - 1];
1798 		newcgsize = newsb->fs_size % newsb->fs_fpg;
1799 		oldcgsize = oldsb->fs_size - ((newsb->fs_ncg - 1) &
1800 		    oldsb->fs_fpg);
1801 		if (oldcgsize > oldsb->fs_fpg)
1802 			oldcgsize = oldsb->fs_fpg;
1803 		evict_data(cg, newcgsize, oldcgsize - newcgsize);
1804 		clr_bits(cg_blksfree(cg, 0), newcgsize, oldcgsize - newcgsize);
1805 	}
1806 	/* Find out whether we would run out of inodes.  (Note we
1807 	 * haven't actually done anything to the file system yet; all
1808 	 * those evict_data calls just update blkmove.) */
1809 	{
1810 		int slop;
1811 		slop = 0;
1812 		for (i = 0; i < newsb->fs_ncg; i++)
1813 			slop += cgs[i]->cg_cs.cs_nifree;
1814 		for (; i < oldsb->fs_ncg; i++)
1815 			slop -= oldsb->fs_ipg - cgs[i]->cg_cs.cs_nifree;
1816 		if (slop < 0)
1817 			errx(EXIT_FAILURE, "Sorry, would run out of inodes");
1818 	}
1819 	/* Copy data, then update pointers to data.  See the comment
1820 	 * header on perform_data_move for ordering considerations. */
1821 	perform_data_move();
1822 	update_for_data_move();
1823 	/* Now do inodes.  Initialize, evict, move, update - see the
1824 	 * comment header on perform_inode_move. */
1825 	inomove_init();
1826 	for (i = newsb->fs_ncg; i < oldsb->fs_ncg; i++)
1827 		evict_inodes(cgs[i]);
1828 	perform_inode_move();
1829 	flush_inodes();
1830 	update_for_inode_move();
1831 	/* Recompute all the bitmaps; most of them probably need it anyway,
1832 	 * the rest are just paranoia and not wanting to have to bother
1833 	 * keeping track of exactly which ones require it. */
1834 	for (i = 0; i < newsb->fs_ncg; i++)
1835 		cgflags[i] |= CGF_DIRTY | CGF_BLKMAPS | CGF_INOMAPS;
1836 	/* Update the cg_old_ncyl value for the last cylinder. */
1837 	if ((newsb->fs_old_flags & FS_FLAGS_UPDATED) == 0)
1838 		cgs[newsb->fs_ncg - 1]->cg_old_ncyl =
1839 		    newsb->fs_old_ncyl % newsb->fs_old_cpg;
1840 	/* Make fs_dsize match the new reality. */
1841 	recompute_fs_dsize();
1842 }
1843 /*
1844  * Recompute the block totals, block cluster summaries, and rotational
1845  *  position summaries, for a given cg (specified by number), based on
1846  *  its free-frag bitmap (cg_blksfree()[]).
1847  */
1848 static void
1849 rescan_blkmaps(int cgn)
1850 {
1851 	struct cg *cg;
1852 	int f;
1853 	int b;
1854 	int blkfree;
1855 	int blkrun;
1856 	int fragrun;
1857 	int fwb;
1858 
1859 	cg = cgs[cgn];
1860 	/* Subtract off the current totals from the sb's summary info */
1861 	newsb->fs_cstotal.cs_nffree -= cg->cg_cs.cs_nffree;
1862 	newsb->fs_cstotal.cs_nbfree -= cg->cg_cs.cs_nbfree;
1863 	/* Clear counters and bitmaps. */
1864 	cg->cg_cs.cs_nffree = 0;
1865 	cg->cg_cs.cs_nbfree = 0;
1866 	memset(&cg->cg_frsum[0], 0, MAXFRAG * sizeof(cg->cg_frsum[0]));
1867 	memset(&old_cg_blktot(cg, 0)[0], 0,
1868 	    newsb->fs_old_cpg * sizeof(old_cg_blktot(cg, 0)[0]));
1869 	memset(&old_cg_blks(newsb, cg, 0, 0)[0], 0,
1870 	    newsb->fs_old_cpg * newsb->fs_old_nrpos *
1871 	    sizeof(old_cg_blks(newsb, cg, 0, 0)[0]));
1872 	if (newsb->fs_contigsumsize > 0) {
1873 		cg->cg_nclusterblks = cg->cg_ndblk / newsb->fs_frag;
1874 		memset(&cg_clustersum(cg, 0)[1], 0,
1875 		    newsb->fs_contigsumsize *
1876 		    sizeof(cg_clustersum(cg, 0)[1]));
1877 		if (is_ufs2)
1878 			memset(&cg_clustersfree(cg, 0)[0], 0,
1879 			    howmany(newsb->fs_fpg / NSPB(newsb), NBBY));
1880 		else
1881 			memset(&cg_clustersfree(cg, 0)[0], 0,
1882 			    howmany((newsb->fs_old_cpg * newsb->fs_old_spc) /
1883 				NSPB(newsb), NBBY));
1884 	}
1885 	/* Scan the free-frag bitmap.  Runs of free frags are kept
1886 	 * track of with fragrun, and recorded into cg_frsum[] and
1887 	 * cg_cs.cs_nffree; on each block boundary, entire free blocks
1888 	 * are recorded as well. */
1889 	blkfree = 1;
1890 	blkrun = 0;
1891 	fragrun = 0;
1892 	f = 0;
1893 	b = 0;
1894 	fwb = 0;
1895 	while (f < cg->cg_ndblk) {
1896 		if (bit_is_set(cg_blksfree(cg, 0), f)) {
1897 			fragrun++;
1898 		} else {
1899 			blkfree = 0;
1900 			if (fragrun > 0) {
1901 				cg->cg_frsum[fragrun]++;
1902 				cg->cg_cs.cs_nffree += fragrun;
1903 			}
1904 			fragrun = 0;
1905 		}
1906 		f++;
1907 		fwb++;
1908 		if (fwb >= newsb->fs_frag) {
1909 			if (blkfree) {
1910 				cg->cg_cs.cs_nbfree++;
1911 				if (newsb->fs_contigsumsize > 0)
1912 					set_bits(cg_clustersfree(cg, 0), b, 1);
1913 				if (is_ufs2 == 0) {
1914 					old_cg_blktot(cg, 0)[
1915 						old_cbtocylno(newsb,
1916 						    f - newsb->fs_frag)]++;
1917 					old_cg_blks(newsb, cg,
1918 					    old_cbtocylno(newsb,
1919 						f - newsb->fs_frag),
1920 					    0)[old_cbtorpos(newsb,
1921 						    f - newsb->fs_frag)]++;
1922 				}
1923 				blkrun++;
1924 			} else {
1925 				if (fragrun > 0) {
1926 					cg->cg_frsum[fragrun]++;
1927 					cg->cg_cs.cs_nffree += fragrun;
1928 				}
1929 				if (newsb->fs_contigsumsize > 0) {
1930 					if (blkrun > 0) {
1931 						cg_clustersum(cg, 0)[(blkrun
1932 						    > newsb->fs_contigsumsize)
1933 						    ? newsb->fs_contigsumsize
1934 						    : blkrun]++;
1935 					}
1936 				}
1937 				blkrun = 0;
1938 			}
1939 			fwb = 0;
1940 			b++;
1941 			blkfree = 1;
1942 			fragrun = 0;
1943 		}
1944 	}
1945 	if (fragrun > 0) {
1946 		cg->cg_frsum[fragrun]++;
1947 		cg->cg_cs.cs_nffree += fragrun;
1948 	}
1949 	if ((blkrun > 0) && (newsb->fs_contigsumsize > 0)) {
1950 		cg_clustersum(cg, 0)[(blkrun > newsb->fs_contigsumsize) ?
1951 		    newsb->fs_contigsumsize : blkrun]++;
1952 	}
1953 	/*
1954          * Put the updated summary info back into csums, and add it
1955          * back into the sb's summary info.  Then mark the cg dirty.
1956          */
1957 	csums[cgn] = cg->cg_cs;
1958 	newsb->fs_cstotal.cs_nffree += cg->cg_cs.cs_nffree;
1959 	newsb->fs_cstotal.cs_nbfree += cg->cg_cs.cs_nbfree;
1960 	cgflags[cgn] |= CGF_DIRTY;
1961 }
1962 /*
1963  * Recompute the cg_inosused()[] bitmap, and the cs_nifree and cs_ndir
1964  *  values, for a cg, based on the in-core inodes for that cg.
1965  */
1966 static void
1967 rescan_inomaps(int cgn)
1968 {
1969 	struct cg *cg;
1970 	int inum;
1971 	int iwc;
1972 
1973 	cg = cgs[cgn];
1974 	newsb->fs_cstotal.cs_ndir -= cg->cg_cs.cs_ndir;
1975 	newsb->fs_cstotal.cs_nifree -= cg->cg_cs.cs_nifree;
1976 	cg->cg_cs.cs_ndir = 0;
1977 	cg->cg_cs.cs_nifree = 0;
1978 	memset(&cg_inosused(cg, 0)[0], 0, howmany(newsb->fs_ipg, NBBY));
1979 	inum = cgn * newsb->fs_ipg;
1980 	if (cgn == 0) {
1981 		set_bits(cg_inosused(cg, 0), 0, 2);
1982 		iwc = 2;
1983 		inum += 2;
1984 	} else {
1985 		iwc = 0;
1986 	}
1987 	for (; iwc < newsb->fs_ipg; iwc++, inum++) {
1988 		switch (DIP(inodes + inum, di_mode) & IFMT) {
1989 		case 0:
1990 			cg->cg_cs.cs_nifree++;
1991 			break;
1992 		case IFDIR:
1993 			cg->cg_cs.cs_ndir++;
1994 			/* FALLTHROUGH */
1995 		default:
1996 			set_bits(cg_inosused(cg, 0), iwc, 1);
1997 			break;
1998 		}
1999 	}
2000 	csums[cgn] = cg->cg_cs;
2001 	newsb->fs_cstotal.cs_ndir += cg->cg_cs.cs_ndir;
2002 	newsb->fs_cstotal.cs_nifree += cg->cg_cs.cs_nifree;
2003 	cgflags[cgn] |= CGF_DIRTY;
2004 }
2005 /*
2006  * Flush cgs to disk, recomputing anything they're marked as needing.
2007  */
2008 static void
2009 flush_cgs(void)
2010 {
2011 	int i;
2012 
2013 	for (i = 0; i < newsb->fs_ncg; i++) {
2014 		progress_bar(special, "flush cg",
2015 		    i, newsb->fs_ncg - 1);
2016 		if (cgflags[i] & CGF_BLKMAPS) {
2017 			rescan_blkmaps(i);
2018 		}
2019 		if (cgflags[i] & CGF_INOMAPS) {
2020 			rescan_inomaps(i);
2021 		}
2022 		if (cgflags[i] & CGF_DIRTY) {
2023 			cgs[i]->cg_rotor = 0;
2024 			cgs[i]->cg_frotor = 0;
2025 			cgs[i]->cg_irotor = 0;
2026 			if (needswap)
2027 				ffs_cg_swap(cgs[i],cgs[i],newsb);
2028 			writeat(FFS_FSBTODB(newsb, cgtod(newsb, i)), cgs[i],
2029 			    cgblksz);
2030 		}
2031 	}
2032 	if (needswap)
2033 		ffs_csum_swap(csums,csums,newsb->fs_cssize);
2034 	writeat(FFS_FSBTODB(newsb, newsb->fs_csaddr), csums, newsb->fs_cssize);
2035 
2036 	progress_done();
2037 }
2038 /*
2039  * Write the superblock, both to the main superblock and to each cg's
2040  *  alternative superblock.
2041  */
2042 static void
2043 write_sbs(void)
2044 {
2045 	int i;
2046 
2047 	if (newsb->fs_magic == FS_UFS1_MAGIC &&
2048 	    (newsb->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
2049 		newsb->fs_old_time = newsb->fs_time;
2050 	    	newsb->fs_old_size = newsb->fs_size;
2051 	    	/* we don't update fs_csaddr */
2052 	    	newsb->fs_old_dsize = newsb->fs_dsize;
2053 		newsb->fs_old_cstotal.cs_ndir = newsb->fs_cstotal.cs_ndir;
2054 		newsb->fs_old_cstotal.cs_nbfree = newsb->fs_cstotal.cs_nbfree;
2055 		newsb->fs_old_cstotal.cs_nifree = newsb->fs_cstotal.cs_nifree;
2056 		newsb->fs_old_cstotal.cs_nffree = newsb->fs_cstotal.cs_nffree;
2057 		/* fill fs_old_postbl_start with 256 bytes of 0xff? */
2058 	}
2059 	/* copy newsb back to oldsb, so we can use it for offsets if
2060 	   newsb has been swapped for writing to disk */
2061 	memcpy(oldsb, newsb, SBLOCKSIZE);
2062 	if (needswap)
2063 		ffs_sb_swap(newsb,newsb);
2064 	writeat(where /  DEV_BSIZE, newsb, SBLOCKSIZE);
2065 	for (i = 0; i < oldsb->fs_ncg; i++) {
2066 		progress_bar(special, "write sb",
2067 		    i, oldsb->fs_ncg - 1);
2068 		writeat(FFS_FSBTODB(oldsb, cgsblock(oldsb, i)), newsb, SBLOCKSIZE);
2069 	}
2070 
2071 	progress_done();
2072 }
2073 
2074 /*
2075  * Check to see wether new size changes the filesystem
2076  *  return exit code
2077  */
2078 static int
2079 checkonly(void)
2080 {
2081 	if (makegeometry(0)) {
2082 		if (verbose) {
2083 			printf("Wouldn't change: already %" PRId64
2084 			    " blocks\n", (int64_t)oldsb->fs_size);
2085 		}
2086 		return 1;
2087 	}
2088 
2089 	if (verbose) {
2090 		printf("Would change: newsize: %" PRId64 " oldsize: %"
2091 		    PRId64 " fsdb: %" PRId64 "\n", FFS_DBTOFSB(oldsb, newsize),
2092 		    (int64_t)oldsb->fs_size,
2093 		    (int64_t)oldsb->fs_fsbtodb);
2094 	}
2095 	return 0;
2096 }
2097 
2098 static off_t
2099 get_dev_size(char *dev_name)
2100 {
2101 	struct dkwedge_info dkw;
2102 	struct partition *pp;
2103 	struct disklabel lp;
2104 	struct stat st;
2105 	size_t ptn;
2106 
2107 	/* Get info about partition/wedge */
2108 	if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1)
2109 		return dkw.dkw_size;
2110 	if (ioctl(fd, DIOCGDINFO, &lp) != -1) {
2111 		ptn = strchr(dev_name, '\0')[-1] - 'a';
2112 		if (ptn >= lp.d_npartitions)
2113 			return 0;
2114 		pp = &lp.d_partitions[ptn];
2115 		return pp->p_size;
2116 	}
2117 	if (fstat(fd, &st) != -1 && S_ISREG(st.st_mode))
2118 		return st.st_size / DEV_BSIZE;
2119 
2120 	return 0;
2121 }
2122 
2123 /*
2124  * main().
2125  */
2126 int
2127 main(int argc, char **argv)
2128 {
2129 	int ch;
2130 	int CheckOnlyFlag;
2131 	int ExpertFlag;
2132 	int SFlag;
2133 	size_t i;
2134 
2135 	char reply[5];
2136 
2137 	newsize = 0;
2138 	ExpertFlag = 0;
2139 	SFlag = 0;
2140         CheckOnlyFlag = 0;
2141 
2142 	while ((ch = getopt(argc, argv, "cps:vy")) != -1) {
2143 		switch (ch) {
2144                 case 'c':
2145 			CheckOnlyFlag = 1;
2146 			break;
2147 		case 'p':
2148 			progress = 1;
2149 			break;
2150 		case 's':
2151 			SFlag = 1;
2152 			newsize = strtoll(optarg, NULL, 10);
2153 			if(newsize < 1) {
2154 				usage();
2155 			}
2156 			break;
2157 		case 'v':
2158 			verbose = 1;
2159 			break;
2160 		case 'y':
2161 			ExpertFlag = 1;
2162 			break;
2163 		case '?':
2164 			/* FALLTHROUGH */
2165 		default:
2166 			usage();
2167 		}
2168 	}
2169 	argc -= optind;
2170 	argv += optind;
2171 
2172 	if (argc != 1) {
2173 		usage();
2174 	}
2175 
2176 	special = *argv;
2177 
2178 	if (ExpertFlag == 0 && CheckOnlyFlag == 0) {
2179 		printf("It's required to manually run fsck on file system "
2180 		    "before you can resize it\n\n"
2181 		    " Did you run fsck on your disk (Yes/No) ? ");
2182 		fgets(reply, (int)sizeof(reply), stdin);
2183 		if (strcasecmp(reply, "Yes\n")) {
2184 			printf("\n Nothing done \n");
2185 			exit(EXIT_SUCCESS);
2186 		}
2187 	}
2188 
2189 	fd = open(special, O_RDWR, 0);
2190 	if (fd < 0)
2191 		err(EXIT_FAILURE, "Can't open `%s'", special);
2192 	checksmallio();
2193 
2194 	if (SFlag == 0) {
2195 		newsize = get_dev_size(special);
2196 		if (newsize == 0)
2197 			err(EXIT_FAILURE,
2198 			    "Can't resize file system, newsize not known.");
2199 	}
2200 
2201 	oldsb = (struct fs *) & sbbuf;
2202 	newsb = (struct fs *) (SBLOCKSIZE + (char *) &sbbuf);
2203 	for (where = search[i = 0]; search[i] != -1; where = search[++i]) {
2204 		readat(where / DEV_BSIZE, oldsb, SBLOCKSIZE);
2205 		switch (oldsb->fs_magic) {
2206 		case FS_UFS2_MAGIC:
2207 			is_ufs2 = 1;
2208 			/* FALLTHROUGH */
2209 		case FS_UFS1_MAGIC:
2210 			needswap = 0;
2211 			break;
2212 		case FS_UFS2_MAGIC_SWAPPED:
2213  			is_ufs2 = 1;
2214 			/* FALLTHROUGH */
2215 		case FS_UFS1_MAGIC_SWAPPED:
2216 			needswap = 1;
2217 			break;
2218 		default:
2219 			continue;
2220 		}
2221 		if (!is_ufs2 && where == SBLOCK_UFS2)
2222 			continue;
2223 		break;
2224 	}
2225 	if (where == (off_t)-1)
2226 		errx(EXIT_FAILURE, "Bad magic number");
2227 	if (needswap)
2228 		ffs_sb_swap(oldsb,oldsb);
2229 	if (oldsb->fs_magic == FS_UFS1_MAGIC &&
2230 	    (oldsb->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
2231 		oldsb->fs_csaddr = oldsb->fs_old_csaddr;
2232 		oldsb->fs_size = oldsb->fs_old_size;
2233 		oldsb->fs_dsize = oldsb->fs_old_dsize;
2234 		oldsb->fs_cstotal.cs_ndir = oldsb->fs_old_cstotal.cs_ndir;
2235 		oldsb->fs_cstotal.cs_nbfree = oldsb->fs_old_cstotal.cs_nbfree;
2236 		oldsb->fs_cstotal.cs_nifree = oldsb->fs_old_cstotal.cs_nifree;
2237 		oldsb->fs_cstotal.cs_nffree = oldsb->fs_old_cstotal.cs_nffree;
2238 		/* any others? */
2239 		printf("Resizing with ffsv1 superblock\n");
2240 	}
2241 
2242 	oldsb->fs_qbmask = ~(int64_t) oldsb->fs_bmask;
2243 	oldsb->fs_qfmask = ~(int64_t) oldsb->fs_fmask;
2244 	if (oldsb->fs_ipg % FFS_INOPB(oldsb))
2245 		errx(EXIT_FAILURE, "ipg[%d] %% FFS_INOPB[%d] != 0",
2246 		    (int) oldsb->fs_ipg, (int) FFS_INOPB(oldsb));
2247 	/* The superblock is bigger than struct fs (there are trailing
2248 	 * tables, of non-fixed size); make sure we copy the whole
2249 	 * thing.  SBLOCKSIZE may be an over-estimate, but we do this
2250 	 * just once, so being generous is cheap. */
2251 	memcpy(newsb, oldsb, SBLOCKSIZE);
2252 
2253 	if (progress) {
2254 		progress_ttywidth(0);
2255 		signal(SIGWINCH, progress_ttywidth);
2256 	}
2257 
2258 	loadcgs();
2259 
2260 	if (progress && !CheckOnlyFlag) {
2261 		progress_switch(progress);
2262 		progress_init();
2263 	}
2264 
2265 	if (newsize > FFS_FSBTODB(oldsb, oldsb->fs_size)) {
2266 		if (CheckOnlyFlag)
2267 			exit(checkonly());
2268 		grow();
2269 	} else if (newsize < FFS_FSBTODB(oldsb, oldsb->fs_size)) {
2270 		if (is_ufs2)
2271 			errx(EXIT_FAILURE,"shrinking not supported for ufs2");
2272 		if (CheckOnlyFlag)
2273 			exit(checkonly());
2274 		shrink();
2275 	} else {
2276 		if (CheckOnlyFlag)
2277 			exit(checkonly());
2278 		if (verbose)
2279 			printf("No change requested: already %" PRId64
2280 			    " blocks\n", (int64_t)oldsb->fs_size);
2281 	}
2282 
2283 	flush_cgs();
2284 	write_sbs();
2285 	if (isplainfile())
2286 		ftruncate(fd,newsize * DEV_BSIZE);
2287 	return 0;
2288 }
2289 
2290 static void
2291 usage(void)
2292 {
2293 
2294 	(void)fprintf(stderr, "usage: %s [-cvy] [-s size] special\n",
2295 	    getprogname());
2296 	exit(EXIT_FAILURE);
2297 }
2298