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