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