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