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