resize_ffs.c revision 1.38.6.2 1 /* $NetBSD: resize_ffs.c,v 1.38.6.2 2016/09/10 06:36: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.2 2016/09/10 06:36: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 int base; /* Disk address of cg base */
466 int dlow; /* Size of pre-cg data area */
467 int dhigh; /* Offset of post-inode data area, from base */
468 int 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 = &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 for (i = 0; i < dlow; i += newsb->fs_frag) {
569 old_cg_blktot(cg, 0)[old_cbtocylno(newsb, i)]++;
570 old_cg_blks(newsb, cg,
571 old_cbtocylno(newsb, i),
572 0)[old_cbtorpos(newsb, i)]++;
573 }
574
575 /* Deal with a partial block at the beginning of the post-inode area.
576 * I'm not convinced this can happen - I think the inodes are always
577 * block-aligned and always an integral number of blocks - but it's
578 * cheap to do the right thing just in case. */
579 if (dhigh % newsb->fs_frag) {
580 n = newsb->fs_frag - (dhigh % newsb->fs_frag);
581 cg->cg_frsum[n]++;
582 cg->cg_cs.cs_nffree += n;
583 dhigh += n;
584 }
585 n = (dmax - dhigh) / newsb->fs_frag;
586 /* We have n full-size blocks in the post-inode data area. */
587 if (n > 0) {
588 cg->cg_cs.cs_nbfree += n;
589 if (newsb->fs_contigsumsize > 0) {
590 i = dhigh / newsb->fs_frag;
591 set_bits(cg_clustersfree(cg, 0), i, n);
592 cg_clustersum(cg, 0)[(n > newsb->fs_contigsumsize) ?
593 newsb->fs_contigsumsize : n]++;
594 }
595 if (is_ufs2 == 0)
596 for (i = n; i > 0; i--) {
597 old_cg_blktot(cg, 0)[old_cbtocylno(newsb,
598 dhigh)]++;
599 old_cg_blks(newsb, cg,
600 old_cbtocylno(newsb, dhigh),
601 0)[old_cbtorpos(newsb,
602 dhigh)]++;
603 dhigh += newsb->fs_frag;
604 }
605 }
606 if (is_ufs2 == 0) {
607 /* Deal with any leftover frag at the end of the cg. */
608 i = dmax - dhigh;
609 if (i) {
610 cg->cg_frsum[i]++;
611 cg->cg_cs.cs_nffree += i;
612 }
613 }
614 /* Update the csum info. */
615 csums[cgn] = cg->cg_cs;
616 newsb->fs_cstotal.cs_nffree += cg->cg_cs.cs_nffree;
617 newsb->fs_cstotal.cs_nbfree += cg->cg_cs.cs_nbfree;
618 newsb->fs_cstotal.cs_nifree += cg->cg_cs.cs_nifree;
619 if (is_ufs2) {
620 /* Write out the cleared inodes. */
621 writeat(FFS_FSBTODB(newsb, cgimin(newsb, cgn)), zinodes2,
622 cg->cg_initediblk * sizeof(*zinodes2));
623 } else {
624 /* Write out the cleared inodes. */
625 writeat(FFS_FSBTODB(newsb, cgimin(newsb, cgn)), zinodes1,
626 newsb->fs_ipg * sizeof(*zinodes1));
627 }
628 /* Dirty the cg. */
629 cgflags[cgn] |= CGF_DIRTY;
630 }
631 /*
632 * Find free space, at least nfrags consecutive frags of it. Pays no
633 * attention to block boundaries, but refuses to straddle cg
634 * boundaries, even if the disk blocks involved are in fact
635 * consecutive. Return value is the frag number of the first frag of
636 * the block, or -1 if no space was found. Uses newsb for sb values,
637 * and assumes the cgs[] structures correctly describe the area to be
638 * searched.
639 *
640 * XXX is there a bug lurking in the ignoring of block boundaries by
641 * the routine used by fragmove() in evict_data()? Can an end-of-file
642 * frag legally straddle a block boundary? If not, this should be
643 * cloned and fixed to stop at block boundaries for that use. The
644 * current one may still be needed for csum info motion, in case that
645 * takes up more than a whole block (is the csum info allowed to begin
646 * partway through a block and continue into the following block?).
647 *
648 * If we wrap off the end of the file system back to the beginning, we
649 * can end up searching the end of the file system twice. I ignore
650 * this inefficiency, since if that happens we're going to croak with
651 * a no-space error anyway, so it happens at most once.
652 */
653 static int
654 find_freespace(unsigned int nfrags)
655 {
656 static int hand = 0; /* hand rotates through all frags in the fs */
657 int cgsize; /* size of the cg hand currently points into */
658 int cgn; /* number of cg hand currently points into */
659 int fwc; /* frag-within-cg number of frag hand points
660 * to */
661 unsigned int run; /* length of run of free frags seen so far */
662 int secondpass; /* have we wrapped from end of fs to
663 * beginning? */
664 unsigned char *bits; /* cg_blksfree()[] for cg hand points into */
665
666 cgn = dtog(newsb, hand);
667 fwc = dtogd(newsb, hand);
668 secondpass = (hand == 0);
669 run = 0;
670 bits = cg_blksfree(cgs[cgn], 0);
671 cgsize = cgs[cgn]->cg_ndblk;
672 while (1) {
673 if (bit_is_set(bits, fwc)) {
674 run++;
675 if (run >= nfrags)
676 return (hand + 1 - run);
677 } else {
678 run = 0;
679 }
680 hand++;
681 fwc++;
682 if (fwc >= cgsize) {
683 fwc = 0;
684 cgn++;
685 if (cgn >= newsb->fs_ncg) {
686 hand = 0;
687 if (secondpass)
688 return (-1);
689 secondpass = 1;
690 cgn = 0;
691 }
692 bits = cg_blksfree(cgs[cgn], 0);
693 cgsize = cgs[cgn]->cg_ndblk;
694 run = 0;
695 }
696 }
697 }
698 /*
699 * Find a free block of disk space. Finds an entire block of frags,
700 * all of which are free. Return value is the frag number of the
701 * first frag of the block, or -1 if no space was found. Uses newsb
702 * for sb values, and assumes the cgs[] structures correctly describe
703 * the area to be searched.
704 *
705 * See find_freespace(), above, for remarks about hand wrapping around.
706 */
707 static int
708 find_freeblock(void)
709 {
710 static int hand = 0; /* hand rotates through all frags in fs */
711 int cgn; /* cg number of cg hand points into */
712 int fwc; /* frag-within-cg number of frag hand points
713 * to */
714 int cgsize; /* size of cg hand points into */
715 int secondpass; /* have we wrapped from end to beginning? */
716 unsigned char *bits; /* cg_blksfree()[] for cg hand points into */
717
718 cgn = dtog(newsb, hand);
719 fwc = dtogd(newsb, hand);
720 secondpass = (hand == 0);
721 bits = cg_blksfree(cgs[cgn], 0);
722 cgsize = ffs_blknum(newsb, cgs[cgn]->cg_ndblk);
723 while (1) {
724 if (blk_is_set(bits, fwc, newsb->fs_frag))
725 return (hand);
726 fwc += newsb->fs_frag;
727 hand += newsb->fs_frag;
728 if (fwc >= cgsize) {
729 fwc = 0;
730 cgn++;
731 if (cgn >= newsb->fs_ncg) {
732 hand = 0;
733 if (secondpass)
734 return (-1);
735 secondpass = 1;
736 cgn = 0;
737 }
738 bits = cg_blksfree(cgs[cgn], 0);
739 cgsize = ffs_blknum(newsb, cgs[cgn]->cg_ndblk);
740 }
741 }
742 }
743 /*
744 * Find a free inode, returning its inumber or -1 if none was found.
745 * Uses newsb for sb values, and assumes the cgs[] structures
746 * correctly describe the area to be searched.
747 *
748 * See find_freespace(), above, for remarks about hand wrapping around.
749 */
750 static int
751 find_freeinode(void)
752 {
753 static int hand = 0; /* hand rotates through all inodes in fs */
754 int cgn; /* cg number of cg hand points into */
755 int iwc; /* inode-within-cg number of inode hand points
756 * to */
757 int secondpass; /* have we wrapped from end to beginning? */
758 unsigned char *bits; /* cg_inosused()[] for cg hand points into */
759
760 cgn = hand / newsb->fs_ipg;
761 iwc = hand % newsb->fs_ipg;
762 secondpass = (hand == 0);
763 bits = cg_inosused(cgs[cgn], 0);
764 while (1) {
765 if (bit_is_clr(bits, iwc))
766 return (hand);
767 hand++;
768 iwc++;
769 if (iwc >= newsb->fs_ipg) {
770 iwc = 0;
771 cgn++;
772 if (cgn >= newsb->fs_ncg) {
773 hand = 0;
774 if (secondpass)
775 return (-1);
776 secondpass = 1;
777 cgn = 0;
778 }
779 bits = cg_inosused(cgs[cgn], 0);
780 }
781 }
782 }
783 /*
784 * Mark a frag as free. Sets the frag's bit in the cg_blksfree bitmap
785 * for the appropriate cg, and marks the cg as dirty.
786 */
787 static void
788 free_frag(int fno)
789 {
790 int cgn;
791
792 cgn = dtog(newsb, fno);
793 set_bits(cg_blksfree(cgs[cgn], 0), dtogd(newsb, fno), 1);
794 cgflags[cgn] |= CGF_DIRTY | CGF_BLKMAPS;
795 }
796 /*
797 * Allocate a frag. Clears the frag's bit in the cg_blksfree bitmap
798 * for the appropriate cg, and marks the cg as dirty.
799 */
800 static void
801 alloc_frag(int fno)
802 {
803 int cgn;
804
805 cgn = dtog(newsb, fno);
806 clr_bits(cg_blksfree(cgs[cgn], 0), dtogd(newsb, fno), 1);
807 cgflags[cgn] |= CGF_DIRTY | CGF_BLKMAPS;
808 }
809 /*
810 * Fix up the csum array. If shrinking, this involves freeing zero or
811 * more frags; if growing, it involves allocating them, or if the
812 * frags being grown into aren't free, finding space elsewhere for the
813 * csum info. (If the number of occupied frags doesn't change,
814 * nothing happens here.)
815 */
816 static void
817 csum_fixup(void)
818 {
819 int nold; /* # frags in old csum info */
820 int ntot; /* # frags in new csum info */
821 int nnew; /* ntot-nold */
822 int newloc; /* new location for csum info, if necessary */
823 int i; /* generic loop index */
824 int j; /* generic loop index */
825 int f; /* "from" frag number, if moving */
826 int t; /* "to" frag number, if moving */
827 int cgn; /* cg number, used when shrinking */
828
829 ntot = howmany(newsb->fs_cssize, newsb->fs_fsize);
830 nold = howmany(oldsb->fs_cssize, newsb->fs_fsize);
831 nnew = ntot - nold;
832 /* First, if there's no change in frag counts, it's easy. */
833 if (nnew == 0)
834 return;
835 /* Next, if we're shrinking, it's almost as easy. Just free up any
836 * frags in the old area we no longer need. */
837 if (nnew < 0) {
838 for ((i = newsb->fs_csaddr + ntot - 1), (j = nnew);
839 j < 0;
840 i--, j++) {
841 free_frag(i);
842 }
843 return;
844 }
845 /* We must be growing. Check to see that the new csum area fits
846 * within the file system. I think this can never happen, since for
847 * the csum area to grow, we must be adding at least one cg, so the
848 * old csum area can't be this close to the end of the new file system.
849 * But it's a cheap check. */
850 /* XXX what if csum info is at end of cg and grows into next cg, what
851 * if it spills over onto the next cg's backup superblock? Can this
852 * happen? */
853 if (newsb->fs_csaddr + ntot <= newsb->fs_size) {
854 /* Okay, it fits - now, see if the space we want is free. */
855 for ((i = newsb->fs_csaddr + nold), (j = nnew);
856 j > 0;
857 i++, j--) {
858 cgn = dtog(newsb, i);
859 if (bit_is_clr(cg_blksfree(cgs[cgn], 0),
860 dtogd(newsb, i)))
861 break;
862 }
863 if (j <= 0) {
864 /* Win win - all the frags we want are free. Allocate
865 * 'em and we're all done. */
866 for ((i = newsb->fs_csaddr + ntot - nnew),
867 (j = nnew); j > 0; i++, j--) {
868 alloc_frag(i);
869 }
870 return;
871 }
872 }
873 /* We have to move the csum info, sigh. Look for new space, free old
874 * space, and allocate new. Update fs_csaddr. We don't copy anything
875 * on disk at this point; the csum info will be written to the
876 * then-current fs_csaddr as part of the final flush. */
877 newloc = find_freespace(ntot);
878 if (newloc < 0)
879 errx(EXIT_FAILURE, "Sorry, no space available for new csums");
880 for (i = 0, f = newsb->fs_csaddr, t = newloc; i < ntot; i++, f++, t++) {
881 if (i < nold) {
882 free_frag(f);
883 }
884 alloc_frag(t);
885 }
886 newsb->fs_csaddr = newloc;
887 }
888 /*
889 * Recompute newsb->fs_dsize. Just scans all cgs, adding the number of
890 * data blocks in that cg to the total.
891 */
892 static void
893 recompute_fs_dsize(void)
894 {
895 int i;
896
897 newsb->fs_dsize = 0;
898 for (i = 0; i < newsb->fs_ncg; i++) {
899 int dlow; /* size of before-sb data area */
900 int dhigh; /* offset of post-inode data area */
901 int dmax; /* total size of cg */
902 int base; /* base of cg, since cgsblock() etc add it in */
903 base = cgbase(newsb, i);
904 dlow = cgsblock(newsb, i) - base;
905 dhigh = cgdmin(newsb, i) - base;
906 dmax = newsb->fs_size - base;
907 if (dmax > newsb->fs_fpg)
908 dmax = newsb->fs_fpg;
909 newsb->fs_dsize += dlow + dmax - dhigh;
910 }
911 /* Space in cg 0 before cgsblock is boot area, not free space! */
912 newsb->fs_dsize -= cgsblock(newsb, 0) - cgbase(newsb, 0);
913 /* And of course the csum info takes up space. */
914 newsb->fs_dsize -= howmany(newsb->fs_cssize, newsb->fs_fsize);
915 }
916 /*
917 * Return the current time. We call this and assign, rather than
918 * calling time() directly, as insulation against OSes where fs_time
919 * is not a time_t.
920 */
921 static time_t
922 timestamp(void)
923 {
924 time_t t;
925
926 time(&t);
927 return (t);
928 }
929
930 /*
931 * Calculate new filesystem geometry
932 * return 0 if geometry actually changed
933 */
934 static int
935 makegeometry(int chatter)
936 {
937
938 /* Update the size. */
939 newsb->fs_size = FFS_DBTOFSB(newsb, newsize);
940 if (is_ufs2)
941 newsb->fs_ncg = howmany(newsb->fs_size, newsb->fs_fpg);
942 else {
943 /* Update fs_old_ncyl and fs_ncg. */
944 newsb->fs_old_ncyl = howmany(newsb->fs_size * NSPF(newsb),
945 newsb->fs_old_spc);
946 newsb->fs_ncg = howmany(newsb->fs_old_ncyl, newsb->fs_old_cpg);
947 }
948
949 /* Does the last cg end before the end of its inode area? There is no
950 * reason why this couldn't be handled, but it would complicate a lot
951 * of code (in all file system code - fsck, kernel, etc) because of the
952 * potential partial inode area, and the gain in space would be
953 * minimal, at most the pre-sb data area. */
954 if (cgdmin(newsb, newsb->fs_ncg - 1) > newsb->fs_size) {
955 newsb->fs_ncg--;
956 if (is_ufs2)
957 newsb->fs_size = newsb->fs_ncg * newsb->fs_fpg;
958 else {
959 newsb->fs_old_ncyl = newsb->fs_ncg * newsb->fs_old_cpg;
960 newsb->fs_size = (newsb->fs_old_ncyl *
961 newsb->fs_old_spc) / NSPF(newsb);
962 }
963 if (chatter || verbose) {
964 printf("Warning: last cylinder group is too small;\n");
965 printf(" dropping it. New size = %lu.\n",
966 (unsigned long int) FFS_FSBTODB(newsb, newsb->fs_size));
967 }
968 }
969
970 /* Did we actually not grow? (This can happen if newsize is less than
971 * a frag larger than the old size - unlikely, but no excuse to
972 * misbehave if it happens.) */
973 if (newsb->fs_size == oldsb->fs_size)
974 return 1;
975
976 return 0;
977 }
978
979
980 /*
981 * Grow the file system.
982 */
983 static void
984 grow(void)
985 {
986 int i;
987
988 if (makegeometry(1)) {
989 printf("New fs size %"PRIu64" = old fs size %"PRIu64
990 ", not growing.\n", newsb->fs_size, oldsb->fs_size);
991 return;
992 }
993
994 if (verbose) {
995 printf("Growing fs from %"PRIu64" blocks to %"PRIu64
996 " blocks.\n", oldsb->fs_size, newsb->fs_size);
997 }
998
999 /* Update the timestamp. */
1000 newsb->fs_time = timestamp();
1001 /* Allocate and clear the new-inode area, in case we add any cgs. */
1002 if (is_ufs2) {
1003 zinodes2 = alloconce(newsb->fs_ipg * sizeof(*zinodes2),
1004 "zeroed inodes");
1005 memset(zinodes2, 0, newsb->fs_ipg * sizeof(*zinodes2));
1006 } else {
1007 zinodes1 = alloconce(newsb->fs_ipg * sizeof(*zinodes1),
1008 "zeroed inodes");
1009 memset(zinodes1, 0, newsb->fs_ipg * sizeof(*zinodes1));
1010 }
1011
1012 /* Check that the new last sector (frag, actually) is writable. Since
1013 * it's at least one frag larger than it used to be, we know we aren't
1014 * overwriting anything important by this. (The choice of sbbuf as
1015 * what to write is irrelevant; it's just something handy that's known
1016 * to be at least one frag in size.) */
1017 writeat(FFS_FSBTODB(newsb,newsb->fs_size - 1), &sbbuf, newsb->fs_fsize);
1018
1019 /* Find out how big the csum area is, and realloc csums if bigger. */
1020 newsb->fs_cssize = ffs_fragroundup(newsb,
1021 newsb->fs_ncg * sizeof(struct csum));
1022 if (newsb->fs_cssize > oldsb->fs_cssize)
1023 csums = nfrealloc(csums, newsb->fs_cssize, "new cg summary");
1024 /* If we're adding any cgs, realloc structures and set up the new
1025 cgs. */
1026 if (newsb->fs_ncg > oldsb->fs_ncg) {
1027 char *cgp;
1028 cgs = nfrealloc(cgs, newsb->fs_ncg * sizeof(*cgs),
1029 "cg pointers");
1030 cgflags = nfrealloc(cgflags, newsb->fs_ncg, "cg flags");
1031 memset(cgflags + oldsb->fs_ncg, 0,
1032 newsb->fs_ncg - oldsb->fs_ncg);
1033 cgp = alloconce((newsb->fs_ncg - oldsb->fs_ncg) * cgblksz,
1034 "cgs");
1035 for (i = oldsb->fs_ncg; i < newsb->fs_ncg; i++) {
1036 cgs[i] = (struct cg *) cgp;
1037 progress_bar(special, "grow cg",
1038 i - oldsb->fs_ncg, newsb->fs_ncg - oldsb->fs_ncg);
1039 initcg(i);
1040 cgp += cgblksz;
1041 }
1042 cgs[oldsb->fs_ncg - 1]->cg_old_ncyl = oldsb->fs_old_cpg;
1043 cgflags[oldsb->fs_ncg - 1] |= CGF_DIRTY;
1044 }
1045 /* If the old fs ended partway through a cg, we have to update the old
1046 * last cg (though possibly not to a full cg!). */
1047 if (oldsb->fs_size % oldsb->fs_fpg) {
1048 struct cg *cg;
1049 int newcgsize;
1050 int prevcgtop;
1051 int oldcgsize;
1052 cg = cgs[oldsb->fs_ncg - 1];
1053 cgflags[oldsb->fs_ncg - 1] |= CGF_DIRTY | CGF_BLKMAPS;
1054 prevcgtop = oldsb->fs_fpg * (oldsb->fs_ncg - 1);
1055 newcgsize = newsb->fs_size - prevcgtop;
1056 if (newcgsize > newsb->fs_fpg)
1057 newcgsize = newsb->fs_fpg;
1058 oldcgsize = oldsb->fs_size % oldsb->fs_fpg;
1059 set_bits(cg_blksfree(cg, 0), oldcgsize, newcgsize - oldcgsize);
1060 cg->cg_old_ncyl = oldsb->fs_old_cpg;
1061 cg->cg_ndblk = newcgsize;
1062 }
1063 /* Fix up the csum info, if necessary. */
1064 csum_fixup();
1065 /* Make fs_dsize match the new reality. */
1066 recompute_fs_dsize();
1067
1068 progress_done();
1069 }
1070 /*
1071 * Call (*fn)() for each inode, passing the inode and its inumber. The
1072 * number of cylinder groups is pased in, so this can be used to map
1073 * over either the old or the new file system's set of inodes.
1074 */
1075 static void
1076 map_inodes(void (*fn) (union dinode * di, unsigned int, void *arg),
1077 int ncg, void *cbarg) {
1078 int i;
1079 int ni;
1080
1081 ni = oldsb->fs_ipg * ncg;
1082 for (i = 0; i < ni; i++)
1083 (*fn) (inodes + i, i, cbarg);
1084 }
1085 /* Values for the third argument to the map function for
1086 * map_inode_data_blocks. MDB_DATA indicates the block is contains
1087 * file data; MDB_INDIR_PRE and MDB_INDIR_POST indicate that it's an
1088 * indirect block. The MDB_INDIR_PRE call is made before the indirect
1089 * block pointers are followed and the pointed-to blocks scanned,
1090 * MDB_INDIR_POST after.
1091 */
1092 #define MDB_DATA 1
1093 #define MDB_INDIR_PRE 2
1094 #define MDB_INDIR_POST 3
1095
1096 typedef void (*mark_callback_t) (off_t blocknum, unsigned int nfrags,
1097 unsigned int blksize, int opcode);
1098
1099 /* Helper function - handles a data block. Calls the callback
1100 * function and returns number of bytes occupied in file (actually,
1101 * rounded up to a frag boundary). The name is historical. */
1102 static int
1103 markblk(mark_callback_t fn, union dinode * di, off_t bn, off_t o)
1104 {
1105 int sz;
1106 int nb;
1107 off_t filesize;
1108
1109 filesize = DIP(di,di_size);
1110 if (o >= filesize)
1111 return (0);
1112 sz = dblksize(newsb, di, ffs_lblkno(newsb, o), filesize);
1113 nb = (sz > filesize - o) ? filesize - o : sz;
1114 if (bn)
1115 (*fn) (bn, ffs_numfrags(newsb, sz), nb, MDB_DATA);
1116 return (sz);
1117 }
1118 /* Helper function - handles an indirect block. Makes the
1119 * MDB_INDIR_PRE callback for the indirect block, loops over the
1120 * pointers and recurses, and makes the MDB_INDIR_POST callback.
1121 * Returns the number of bytes occupied in file, as does markblk().
1122 * For the sake of update_for_data_move(), we read the indirect block
1123 * _after_ making the _PRE callback. The name is historical. */
1124 static int
1125 markiblk(mark_callback_t fn, union dinode * di, off_t bn, off_t o, int lev)
1126 {
1127 int i;
1128 int j;
1129 unsigned k;
1130 int tot;
1131 static int32_t indirblk1[howmany(MAXBSIZE, sizeof(int32_t))];
1132 static int32_t indirblk2[howmany(MAXBSIZE, sizeof(int32_t))];
1133 static int32_t indirblk3[howmany(MAXBSIZE, sizeof(int32_t))];
1134 static int32_t *indirblks[3] = {
1135 &indirblk1[0], &indirblk2[0], &indirblk3[0]
1136 };
1137
1138 if (lev < 0)
1139 return (markblk(fn, di, bn, o));
1140 if (bn == 0) {
1141 for (i = newsb->fs_bsize;
1142 lev >= 0;
1143 i *= FFS_NINDIR(newsb), lev--);
1144 return (i);
1145 }
1146 (*fn) (bn, newsb->fs_frag, newsb->fs_bsize, MDB_INDIR_PRE);
1147 readat(FFS_FSBTODB(newsb, bn), indirblks[lev], newsb->fs_bsize);
1148 if (needswap)
1149 for (k = 0; k < howmany(MAXBSIZE, sizeof(int32_t)); k++)
1150 indirblks[lev][k] = bswap32(indirblks[lev][k]);
1151 tot = 0;
1152 for (i = 0; i < FFS_NINDIR(newsb); i++) {
1153 j = markiblk(fn, di, indirblks[lev][i], o, lev - 1);
1154 if (j == 0)
1155 break;
1156 o += j;
1157 tot += j;
1158 }
1159 (*fn) (bn, newsb->fs_frag, newsb->fs_bsize, MDB_INDIR_POST);
1160 return (tot);
1161 }
1162
1163
1164 /*
1165 * Call (*fn)() for each data block for an inode. This routine assumes
1166 * the inode is known to be of a type that has data blocks (file,
1167 * directory, or non-fast symlink). The called function is:
1168 *
1169 * (*fn)(unsigned int blkno, unsigned int nf, unsigned int nb, int op)
1170 *
1171 * where blkno is the frag number, nf is the number of frags starting
1172 * at blkno (always <= fs_frag), nb is the number of bytes that belong
1173 * to the file (usually nf*fs_frag, often less for the last block/frag
1174 * of a file).
1175 */
1176 static void
1177 map_inode_data_blocks(union dinode * di, mark_callback_t fn)
1178 {
1179 off_t o; /* offset within inode */
1180 int inc; /* increment for o - maybe should be off_t? */
1181 int b; /* index within di_db[] and di_ib[] arrays */
1182
1183 /* Scan the direct blocks... */
1184 o = 0;
1185 for (b = 0; b < UFS_NDADDR; b++) {
1186 inc = markblk(fn, di, DIP(di,di_db[b]), o);
1187 if (inc == 0)
1188 break;
1189 o += inc;
1190 }
1191 /* ...and the indirect blocks. */
1192 if (inc) {
1193 for (b = 0; b < UFS_NIADDR; b++) {
1194 inc = markiblk(fn, di, DIP(di,di_ib[b]), o, b);
1195 if (inc == 0)
1196 return;
1197 o += inc;
1198 }
1199 }
1200 }
1201
1202 static void
1203 dblk_callback(union dinode * di, unsigned int inum, void *arg)
1204 {
1205 mark_callback_t fn;
1206 off_t filesize;
1207
1208 filesize = DIP(di,di_size);
1209 fn = (mark_callback_t) arg;
1210 switch (DIP(di,di_mode) & IFMT) {
1211 case IFLNK:
1212 if (filesize <= newsb->fs_maxsymlinklen) {
1213 break;
1214 }
1215 /* FALLTHROUGH */
1216 case IFDIR:
1217 case IFREG:
1218 map_inode_data_blocks(di, fn);
1219 break;
1220 }
1221 }
1222 /*
1223 * Make a callback call, a la map_inode_data_blocks, for all data
1224 * blocks in the entire fs. This is used only once, in
1225 * update_for_data_move, but it's out at top level because the complex
1226 * downward-funarg nesting that would otherwise result seems to give
1227 * gcc gastric distress.
1228 */
1229 static void
1230 map_data_blocks(mark_callback_t fn, int ncg)
1231 {
1232 map_inodes(&dblk_callback, ncg, (void *) fn);
1233 }
1234 /*
1235 * Initialize the blkmove array.
1236 */
1237 static void
1238 blkmove_init(void)
1239 {
1240 int i;
1241
1242 blkmove = alloconce(oldsb->fs_size * sizeof(*blkmove), "blkmove");
1243 for (i = 0; i < oldsb->fs_size; i++)
1244 blkmove[i] = i;
1245 }
1246 /*
1247 * Load the inodes off disk. Allocates the structures and initializes
1248 * them - the inodes from disk, the flags to zero.
1249 */
1250 static void
1251 loadinodes(void)
1252 {
1253 int imax, ino, i, j;
1254 struct ufs1_dinode *dp1 = NULL;
1255 struct ufs2_dinode *dp2 = NULL;
1256
1257 /* read inodes one fs block at a time and copy them */
1258
1259 inodes = alloconce(oldsb->fs_ncg * oldsb->fs_ipg *
1260 sizeof(union dinode), "inodes");
1261 iflags = alloconce(oldsb->fs_ncg * oldsb->fs_ipg, "inode flags");
1262 memset(iflags, 0, oldsb->fs_ncg * oldsb->fs_ipg);
1263
1264 ibuf = nfmalloc(oldsb->fs_bsize,"inode block buf");
1265 if (is_ufs2)
1266 dp2 = (struct ufs2_dinode *)ibuf;
1267 else
1268 dp1 = (struct ufs1_dinode *)ibuf;
1269
1270 for (ino = 0,imax = oldsb->fs_ipg * oldsb->fs_ncg; ino < imax; ) {
1271 readat(FFS_FSBTODB(oldsb, ino_to_fsba(oldsb, ino)), ibuf,
1272 oldsb->fs_bsize);
1273
1274 for (i = 0; i < oldsb->fs_inopb; i++) {
1275 if (is_ufs2) {
1276 if (needswap) {
1277 ffs_dinode2_swap(&(dp2[i]), &(dp2[i]));
1278 for (j = 0; j < UFS_NDADDR + UFS_NIADDR; j++)
1279 dp2[i].di_db[j] =
1280 bswap32(dp2[i].di_db[j]);
1281 }
1282 memcpy(&inodes[ino].dp2, &dp2[i],
1283 sizeof(inodes[ino].dp2));
1284 } else {
1285 if (needswap) {
1286 ffs_dinode1_swap(&(dp1[i]), &(dp1[i]));
1287 for (j = 0; j < UFS_NDADDR + UFS_NIADDR; j++)
1288 dp1[i].di_db[j] =
1289 bswap32(dp1[i].di_db[j]);
1290 }
1291 memcpy(&inodes[ino].dp1, &dp1[i],
1292 sizeof(inodes[ino].dp1));
1293 }
1294 if (++ino > imax)
1295 errx(EXIT_FAILURE,
1296 "Exceeded number of inodes");
1297 }
1298
1299 }
1300 }
1301 /*
1302 * Report a file-system-too-full problem.
1303 */
1304 __dead static void
1305 toofull(void)
1306 {
1307 errx(EXIT_FAILURE, "Sorry, would run out of data blocks");
1308 }
1309 /*
1310 * Record a desire to move "n" frags from "from" to "to".
1311 */
1312 static void
1313 mark_move(unsigned int from, unsigned int to, unsigned int n)
1314 {
1315 for (; n > 0; n--)
1316 blkmove[from++] = to++;
1317 }
1318 /* Helper function - evict n frags, starting with start (cg-relative).
1319 * The free bitmap is scanned, unallocated frags are ignored, and
1320 * each block of consecutive allocated frags is moved as a unit.
1321 */
1322 static void
1323 fragmove(struct cg * cg, int base, unsigned int start, unsigned int n)
1324 {
1325 unsigned int i;
1326 int run;
1327
1328 run = 0;
1329 for (i = 0; i <= n; i++) {
1330 if ((i < n) && bit_is_clr(cg_blksfree(cg, 0), start + i)) {
1331 run++;
1332 } else {
1333 if (run > 0) {
1334 int off;
1335 off = find_freespace(run);
1336 if (off < 0)
1337 toofull();
1338 mark_move(base + start + i - run, off, run);
1339 set_bits(cg_blksfree(cg, 0), start + i - run,
1340 run);
1341 clr_bits(cg_blksfree(cgs[dtog(oldsb, off)], 0),
1342 dtogd(oldsb, off), run);
1343 }
1344 run = 0;
1345 }
1346 }
1347 }
1348 /*
1349 * Evict all data blocks from the given cg, starting at minfrag (based
1350 * at the beginning of the cg), for length nfrag. The eviction is
1351 * assumed to be entirely data-area; this should not be called with a
1352 * range overlapping the metadata structures in the cg. It also
1353 * assumes minfrag points into the given cg; it will misbehave if this
1354 * is not true.
1355 *
1356 * See the comment header on find_freespace() for one possible bug
1357 * lurking here.
1358 */
1359 static void
1360 evict_data(struct cg * cg, unsigned int minfrag, int nfrag)
1361 {
1362 int base; /* base of cg (in frags from beginning of fs) */
1363
1364 base = cgbase(oldsb, cg->cg_cgx);
1365 /* Does the boundary fall in the middle of a block? To avoid
1366 * breaking between frags allocated as consecutive, we always
1367 * evict the whole block in this case, though one could argue
1368 * we should check to see if the frag before or after the
1369 * break is unallocated. */
1370 if (minfrag % oldsb->fs_frag) {
1371 int n;
1372 n = minfrag % oldsb->fs_frag;
1373 minfrag -= n;
1374 nfrag += n;
1375 }
1376 /* Do whole blocks. If a block is wholly free, skip it; if
1377 * wholly allocated, move it in toto. If neither, call
1378 * fragmove() to move the frags to new locations. */
1379 while (nfrag >= oldsb->fs_frag) {
1380 if (!blk_is_set(cg_blksfree(cg, 0), minfrag, oldsb->fs_frag)) {
1381 if (blk_is_clr(cg_blksfree(cg, 0), minfrag,
1382 oldsb->fs_frag)) {
1383 int off;
1384 off = find_freeblock();
1385 if (off < 0)
1386 toofull();
1387 mark_move(base + minfrag, off, oldsb->fs_frag);
1388 set_bits(cg_blksfree(cg, 0), minfrag,
1389 oldsb->fs_frag);
1390 clr_bits(cg_blksfree(cgs[dtog(oldsb, off)], 0),
1391 dtogd(oldsb, off), oldsb->fs_frag);
1392 } else {
1393 fragmove(cg, base, minfrag, oldsb->fs_frag);
1394 }
1395 }
1396 minfrag += oldsb->fs_frag;
1397 nfrag -= oldsb->fs_frag;
1398 }
1399 /* Clean up any sub-block amount left over. */
1400 if (nfrag) {
1401 fragmove(cg, base, minfrag, nfrag);
1402 }
1403 }
1404 /*
1405 * Move all data blocks according to blkmove. We have to be careful,
1406 * because we may be updating indirect blocks that will themselves be
1407 * getting moved, or inode int32_t arrays that point to indirect
1408 * blocks that will be moved. We call this before
1409 * update_for_data_move, and update_for_data_move does inodes first,
1410 * then indirect blocks in preorder, so as to make sure that the
1411 * file system is self-consistent at all points, for better crash
1412 * tolerance. (We can get away with this only because all the writes
1413 * done by perform_data_move() are writing into space that's not used
1414 * by the old file system.) If we crash, some things may point to the
1415 * old data and some to the new, but both copies are the same. The
1416 * only wrong things should be csum info and free bitmaps, which fsck
1417 * is entirely capable of cleaning up.
1418 *
1419 * Since blkmove_init() initializes all blocks to move to their current
1420 * locations, we can have two blocks marked as wanting to move to the
1421 * same location, but only two and only when one of them is the one
1422 * that was already there. So if blkmove[i]==i, we ignore that entry
1423 * entirely - for unallocated blocks, we don't want it (and may be
1424 * putting something else there), and for allocated blocks, we don't
1425 * want to copy it anywhere.
1426 */
1427 static void
1428 perform_data_move(void)
1429 {
1430 int i;
1431 int run;
1432 int maxrun;
1433 char buf[65536];
1434
1435 maxrun = sizeof(buf) / newsb->fs_fsize;
1436 run = 0;
1437 for (i = 0; i < oldsb->fs_size; i++) {
1438 if ((blkmove[i] == (unsigned)i /*XXX cast*/) ||
1439 (run >= maxrun) ||
1440 ((run > 0) &&
1441 (blkmove[i] != blkmove[i - 1] + 1))) {
1442 if (run > 0) {
1443 readat(FFS_FSBTODB(oldsb, i - run), &buf[0],
1444 run << oldsb->fs_fshift);
1445 writeat(FFS_FSBTODB(oldsb, blkmove[i - run]),
1446 &buf[0], run << oldsb->fs_fshift);
1447 }
1448 run = 0;
1449 }
1450 if (blkmove[i] != (unsigned)i /*XXX cast*/)
1451 run++;
1452 }
1453 if (run > 0) {
1454 readat(FFS_FSBTODB(oldsb, i - run), &buf[0],
1455 run << oldsb->fs_fshift);
1456 writeat(FFS_FSBTODB(oldsb, blkmove[i - run]), &buf[0],
1457 run << oldsb->fs_fshift);
1458 }
1459 }
1460 /*
1461 * This modifies an array of int32_t, according to blkmove. This is
1462 * used to update inode block arrays and indirect blocks to point to
1463 * the new locations of data blocks.
1464 *
1465 * Return value is the number of int32_ts that needed updating; in
1466 * particular, the return value is zero iff nothing was modified.
1467 */
1468 static int
1469 movemap_blocks(int32_t * vec, int n)
1470 {
1471 int rv;
1472
1473 rv = 0;
1474 for (; n > 0; n--, vec++) {
1475 if (blkmove[*vec] != (unsigned)*vec /*XXX cast*/) {
1476 *vec = blkmove[*vec];
1477 rv++;
1478 }
1479 }
1480 return (rv);
1481 }
1482 static void
1483 moveblocks_callback(union dinode * di, unsigned int inum, void *arg)
1484 {
1485 int32_t *dblkptr, *iblkptr;
1486
1487 switch (DIP(di,di_mode) & IFMT) {
1488 case IFLNK:
1489 if ((off_t)DIP(di,di_size) <= oldsb->fs_maxsymlinklen) {
1490 break;
1491 }
1492 /* FALLTHROUGH */
1493 case IFDIR:
1494 case IFREG:
1495 if (is_ufs2) {
1496 /* XXX these are not int32_t and this is WRONG! */
1497 dblkptr = (void *) &(di->dp2.di_db[0]);
1498 iblkptr = (void *) &(di->dp2.di_ib[0]);
1499 } else {
1500 dblkptr = &(di->dp1.di_db[0]);
1501 iblkptr = &(di->dp1.di_ib[0]);
1502 }
1503 /*
1504 * Don't || these two calls; we need their
1505 * side-effects.
1506 */
1507 if (movemap_blocks(dblkptr, UFS_NDADDR)) {
1508 iflags[inum] |= IF_DIRTY;
1509 }
1510 if (movemap_blocks(iblkptr, UFS_NIADDR)) {
1511 iflags[inum] |= IF_DIRTY;
1512 }
1513 break;
1514 }
1515 }
1516
1517 static void
1518 moveindir_callback(off_t off, unsigned int nfrag, unsigned int nbytes,
1519 int kind)
1520 {
1521 unsigned int i;
1522
1523 if (kind == MDB_INDIR_PRE) {
1524 int32_t blk[howmany(MAXBSIZE, sizeof(int32_t))];
1525 readat(FFS_FSBTODB(oldsb, off), &blk[0], oldsb->fs_bsize);
1526 if (needswap)
1527 for (i = 0; i < howmany(MAXBSIZE, sizeof(int32_t)); i++)
1528 blk[i] = bswap32(blk[i]);
1529 if (movemap_blocks(&blk[0], FFS_NINDIR(oldsb))) {
1530 if (needswap)
1531 for (i = 0; i < howmany(MAXBSIZE,
1532 sizeof(int32_t)); i++)
1533 blk[i] = bswap32(blk[i]);
1534 writeat(FFS_FSBTODB(oldsb, off), &blk[0], oldsb->fs_bsize);
1535 }
1536 }
1537 }
1538 /*
1539 * Update all inode data arrays and indirect blocks to point to the new
1540 * locations of data blocks. See the comment header on
1541 * perform_data_move for some ordering considerations.
1542 */
1543 static void
1544 update_for_data_move(void)
1545 {
1546 map_inodes(&moveblocks_callback, oldsb->fs_ncg, NULL);
1547 map_data_blocks(&moveindir_callback, oldsb->fs_ncg);
1548 }
1549 /*
1550 * Initialize the inomove array.
1551 */
1552 static void
1553 inomove_init(void)
1554 {
1555 int i;
1556
1557 inomove = alloconce(oldsb->fs_ipg * oldsb->fs_ncg * sizeof(*inomove),
1558 "inomove");
1559 for (i = (oldsb->fs_ipg * oldsb->fs_ncg) - 1; i >= 0; i--)
1560 inomove[i] = i;
1561 }
1562 /*
1563 * Flush all dirtied inodes to disk. Scans the inode flags array; for
1564 * each dirty inode, it sets the BDIRTY bit on the first inode in the
1565 * block containing the dirty inode. Then it scans by blocks, and for
1566 * each marked block, writes it.
1567 */
1568 static void
1569 flush_inodes(void)
1570 {
1571 int i, j, k, na, ni, m;
1572 struct ufs1_dinode *dp1 = NULL;
1573 struct ufs2_dinode *dp2 = NULL;
1574
1575 na = UFS_NDADDR + UFS_NIADDR;
1576 ni = newsb->fs_ipg * newsb->fs_ncg;
1577 m = FFS_INOPB(newsb) - 1;
1578 for (i = 0; i < ni; i++) {
1579 if (iflags[i] & IF_DIRTY) {
1580 iflags[i & ~m] |= IF_BDIRTY;
1581 }
1582 }
1583 m++;
1584
1585 if (is_ufs2)
1586 dp2 = (struct ufs2_dinode *)ibuf;
1587 else
1588 dp1 = (struct ufs1_dinode *)ibuf;
1589
1590 for (i = 0; i < ni; i += m) {
1591 if (iflags[i] & IF_BDIRTY) {
1592 if (is_ufs2)
1593 for (j = 0; j < m; j++) {
1594 dp2[j] = inodes[i + j].dp2;
1595 if (needswap) {
1596 for (k = 0; k < na; k++)
1597 dp2[j].di_db[k]=
1598 bswap32(dp2[j].di_db[k]);
1599 ffs_dinode2_swap(&dp2[j],
1600 &dp2[j]);
1601 }
1602 }
1603 else
1604 for (j = 0; j < m; j++) {
1605 dp1[j] = inodes[i + j].dp1;
1606 if (needswap) {
1607 for (k = 0; k < na; k++)
1608 dp1[j].di_db[k]=
1609 bswap32(dp1[j].di_db[k]);
1610 ffs_dinode1_swap(&dp1[j],
1611 &dp1[j]);
1612 }
1613 }
1614
1615 writeat(FFS_FSBTODB(newsb, ino_to_fsba(newsb, i)),
1616 ibuf, newsb->fs_bsize);
1617 }
1618 }
1619 }
1620 /*
1621 * Evict all inodes from the specified cg. shrink() already checked
1622 * that there were enough free inodes, so the no-free-inodes check is
1623 * a can't-happen. If it does trip, the file system should be in good
1624 * enough shape for fsck to fix; see the comment on perform_data_move
1625 * for the considerations in question.
1626 */
1627 static void
1628 evict_inodes(struct cg * cg)
1629 {
1630 int inum;
1631 int i;
1632 int fi;
1633
1634 inum = newsb->fs_ipg * cg->cg_cgx;
1635 for (i = 0; i < newsb->fs_ipg; i++, inum++) {
1636 if (DIP(inodes + inum,di_mode) != 0) {
1637 fi = find_freeinode();
1638 if (fi < 0)
1639 errx(EXIT_FAILURE, "Sorry, inodes evaporated - "
1640 "file system probably needs fsck");
1641 inomove[inum] = fi;
1642 clr_bits(cg_inosused(cg, 0), i, 1);
1643 set_bits(cg_inosused(cgs[ino_to_cg(newsb, fi)], 0),
1644 fi % newsb->fs_ipg, 1);
1645 }
1646 }
1647 }
1648 /*
1649 * Move inodes from old locations to new. Does not actually write
1650 * anything to disk; just copies in-core and sets dirty bits.
1651 *
1652 * We have to be careful here for reasons similar to those mentioned in
1653 * the comment header on perform_data_move, above: for the sake of
1654 * crash tolerance, we want to make sure everything is present at both
1655 * old and new locations before we update pointers. So we call this
1656 * first, then flush_inodes() to get them out on disk, then update
1657 * directories to match.
1658 */
1659 static void
1660 perform_inode_move(void)
1661 {
1662 unsigned int i;
1663 unsigned int ni;
1664
1665 ni = oldsb->fs_ipg * oldsb->fs_ncg;
1666 for (i = 0; i < ni; i++) {
1667 if (inomove[i] != i) {
1668 inodes[inomove[i]] = inodes[i];
1669 iflags[inomove[i]] = iflags[i] | IF_DIRTY;
1670 }
1671 }
1672 }
1673 /*
1674 * Update the directory contained in the nb bytes at buf, to point to
1675 * inodes' new locations.
1676 */
1677 static int
1678 update_dirents(char *buf, int nb)
1679 {
1680 int rv;
1681 #define d ((struct direct *)buf)
1682 #define s32(x) (needswap?bswap32((x)):(x))
1683 #define s16(x) (needswap?bswap16((x)):(x))
1684
1685 rv = 0;
1686 while (nb > 0) {
1687 if (inomove[s32(d->d_ino)] != s32(d->d_ino)) {
1688 rv++;
1689 d->d_ino = s32(inomove[s32(d->d_ino)]);
1690 }
1691 nb -= s16(d->d_reclen);
1692 buf += s16(d->d_reclen);
1693 }
1694 return (rv);
1695 #undef d
1696 #undef s32
1697 #undef s16
1698 }
1699 /*
1700 * Callback function for map_inode_data_blocks, for updating a
1701 * directory to point to new inode locations.
1702 */
1703 static void
1704 update_dir_data(off_t bn, unsigned int size, unsigned int nb, int kind)
1705 {
1706 if (kind == MDB_DATA) {
1707 union {
1708 struct direct d;
1709 char ch[MAXBSIZE];
1710 } buf;
1711 readat(FFS_FSBTODB(oldsb, bn), &buf, size << oldsb->fs_fshift);
1712 if (update_dirents((char *) &buf, nb)) {
1713 writeat(FFS_FSBTODB(oldsb, bn), &buf,
1714 size << oldsb->fs_fshift);
1715 }
1716 }
1717 }
1718 static void
1719 dirmove_callback(union dinode * di, unsigned int inum, void *arg)
1720 {
1721 switch (DIP(di,di_mode) & IFMT) {
1722 case IFDIR:
1723 map_inode_data_blocks(di, &update_dir_data);
1724 break;
1725 }
1726 }
1727 /*
1728 * Update directory entries to point to new inode locations.
1729 */
1730 static void
1731 update_for_inode_move(void)
1732 {
1733 map_inodes(&dirmove_callback, newsb->fs_ncg, NULL);
1734 }
1735 /*
1736 * Shrink the file system.
1737 */
1738 static void
1739 shrink(void)
1740 {
1741 int i;
1742
1743 if (makegeometry(1)) {
1744 printf("New fs size %"PRIu64" = old fs size %"PRIu64
1745 ", not shrinking.\n", newsb->fs_size, oldsb->fs_size);
1746 return;
1747 }
1748
1749 /* Let's make sure we're not being shrunk into oblivion. */
1750 if (newsb->fs_ncg < 1)
1751 errx(EXIT_FAILURE, "Size too small - file system would "
1752 "have no cylinders");
1753
1754 if (verbose) {
1755 printf("Shrinking fs from %"PRIu64" blocks to %"PRIu64
1756 " blocks.\n", oldsb->fs_size, newsb->fs_size);
1757 }
1758
1759 /* Load the inodes off disk - we'll need 'em. */
1760 loadinodes();
1761
1762 /* Update the timestamp. */
1763 newsb->fs_time = timestamp();
1764
1765 /* Initialize for block motion. */
1766 blkmove_init();
1767 /* Update csum size, then fix up for the new size */
1768 newsb->fs_cssize = ffs_fragroundup(newsb,
1769 newsb->fs_ncg * sizeof(struct csum));
1770 csum_fixup();
1771 /* Evict data from any cgs being wholly eliminated */
1772 for (i = newsb->fs_ncg; i < oldsb->fs_ncg; i++) {
1773 int base;
1774 int dlow;
1775 int dhigh;
1776 int dmax;
1777 base = cgbase(oldsb, i);
1778 dlow = cgsblock(oldsb, i) - base;
1779 dhigh = cgdmin(oldsb, i) - base;
1780 dmax = oldsb->fs_size - base;
1781 if (dmax > cgs[i]->cg_ndblk)
1782 dmax = cgs[i]->cg_ndblk;
1783 evict_data(cgs[i], 0, dlow);
1784 evict_data(cgs[i], dhigh, dmax - dhigh);
1785 newsb->fs_cstotal.cs_ndir -= cgs[i]->cg_cs.cs_ndir;
1786 newsb->fs_cstotal.cs_nifree -= cgs[i]->cg_cs.cs_nifree;
1787 newsb->fs_cstotal.cs_nffree -= cgs[i]->cg_cs.cs_nffree;
1788 newsb->fs_cstotal.cs_nbfree -= cgs[i]->cg_cs.cs_nbfree;
1789 }
1790 /* Update the new last cg. */
1791 cgs[newsb->fs_ncg - 1]->cg_ndblk = newsb->fs_size -
1792 ((newsb->fs_ncg - 1) * newsb->fs_fpg);
1793 /* Is the new last cg partial? If so, evict any data from the part
1794 * being shrunken away. */
1795 if (newsb->fs_size % newsb->fs_fpg) {
1796 struct cg *cg;
1797 int oldcgsize;
1798 int newcgsize;
1799 cg = cgs[newsb->fs_ncg - 1];
1800 newcgsize = newsb->fs_size % newsb->fs_fpg;
1801 oldcgsize = oldsb->fs_size - ((newsb->fs_ncg - 1) &
1802 oldsb->fs_fpg);
1803 if (oldcgsize > oldsb->fs_fpg)
1804 oldcgsize = oldsb->fs_fpg;
1805 evict_data(cg, newcgsize, oldcgsize - newcgsize);
1806 clr_bits(cg_blksfree(cg, 0), newcgsize, oldcgsize - newcgsize);
1807 }
1808 /* Find out whether we would run out of inodes. (Note we
1809 * haven't actually done anything to the file system yet; all
1810 * those evict_data calls just update blkmove.) */
1811 {
1812 int slop;
1813 slop = 0;
1814 for (i = 0; i < newsb->fs_ncg; i++)
1815 slop += cgs[i]->cg_cs.cs_nifree;
1816 for (; i < oldsb->fs_ncg; i++)
1817 slop -= oldsb->fs_ipg - cgs[i]->cg_cs.cs_nifree;
1818 if (slop < 0)
1819 errx(EXIT_FAILURE, "Sorry, would run out of inodes");
1820 }
1821 /* Copy data, then update pointers to data. See the comment
1822 * header on perform_data_move for ordering considerations. */
1823 perform_data_move();
1824 update_for_data_move();
1825 /* Now do inodes. Initialize, evict, move, update - see the
1826 * comment header on perform_inode_move. */
1827 inomove_init();
1828 for (i = newsb->fs_ncg; i < oldsb->fs_ncg; i++)
1829 evict_inodes(cgs[i]);
1830 perform_inode_move();
1831 flush_inodes();
1832 update_for_inode_move();
1833 /* Recompute all the bitmaps; most of them probably need it anyway,
1834 * the rest are just paranoia and not wanting to have to bother
1835 * keeping track of exactly which ones require it. */
1836 for (i = 0; i < newsb->fs_ncg; i++)
1837 cgflags[i] |= CGF_DIRTY | CGF_BLKMAPS | CGF_INOMAPS;
1838 /* Update the cg_old_ncyl value for the last cylinder. */
1839 if ((newsb->fs_old_flags & FS_FLAGS_UPDATED) == 0)
1840 cgs[newsb->fs_ncg - 1]->cg_old_ncyl =
1841 newsb->fs_old_ncyl % newsb->fs_old_cpg;
1842 /* Make fs_dsize match the new reality. */
1843 recompute_fs_dsize();
1844 }
1845 /*
1846 * Recompute the block totals, block cluster summaries, and rotational
1847 * position summaries, for a given cg (specified by number), based on
1848 * its free-frag bitmap (cg_blksfree()[]).
1849 */
1850 static void
1851 rescan_blkmaps(int cgn)
1852 {
1853 struct cg *cg;
1854 int f;
1855 int b;
1856 int blkfree;
1857 int blkrun;
1858 int fragrun;
1859 int fwb;
1860
1861 cg = cgs[cgn];
1862 /* Subtract off the current totals from the sb's summary info */
1863 newsb->fs_cstotal.cs_nffree -= cg->cg_cs.cs_nffree;
1864 newsb->fs_cstotal.cs_nbfree -= cg->cg_cs.cs_nbfree;
1865 /* Clear counters and bitmaps. */
1866 cg->cg_cs.cs_nffree = 0;
1867 cg->cg_cs.cs_nbfree = 0;
1868 memset(&cg->cg_frsum[0], 0, MAXFRAG * sizeof(cg->cg_frsum[0]));
1869 memset(&old_cg_blktot(cg, 0)[0], 0,
1870 newsb->fs_old_cpg * sizeof(old_cg_blktot(cg, 0)[0]));
1871 memset(&old_cg_blks(newsb, cg, 0, 0)[0], 0,
1872 newsb->fs_old_cpg * newsb->fs_old_nrpos *
1873 sizeof(old_cg_blks(newsb, cg, 0, 0)[0]));
1874 if (newsb->fs_contigsumsize > 0) {
1875 cg->cg_nclusterblks = cg->cg_ndblk / newsb->fs_frag;
1876 memset(&cg_clustersum(cg, 0)[1], 0,
1877 newsb->fs_contigsumsize *
1878 sizeof(cg_clustersum(cg, 0)[1]));
1879 if (is_ufs2)
1880 memset(&cg_clustersfree(cg, 0)[0], 0,
1881 howmany(newsb->fs_fpg / NSPB(newsb), NBBY));
1882 else
1883 memset(&cg_clustersfree(cg, 0)[0], 0,
1884 howmany((newsb->fs_old_cpg * newsb->fs_old_spc) /
1885 NSPB(newsb), NBBY));
1886 }
1887 /* Scan the free-frag bitmap. Runs of free frags are kept
1888 * track of with fragrun, and recorded into cg_frsum[] and
1889 * cg_cs.cs_nffree; on each block boundary, entire free blocks
1890 * are recorded as well. */
1891 blkfree = 1;
1892 blkrun = 0;
1893 fragrun = 0;
1894 f = 0;
1895 b = 0;
1896 fwb = 0;
1897 while (f < cg->cg_ndblk) {
1898 if (bit_is_set(cg_blksfree(cg, 0), f)) {
1899 fragrun++;
1900 } else {
1901 blkfree = 0;
1902 if (fragrun > 0) {
1903 cg->cg_frsum[fragrun]++;
1904 cg->cg_cs.cs_nffree += fragrun;
1905 }
1906 fragrun = 0;
1907 }
1908 f++;
1909 fwb++;
1910 if (fwb >= newsb->fs_frag) {
1911 if (blkfree) {
1912 cg->cg_cs.cs_nbfree++;
1913 if (newsb->fs_contigsumsize > 0)
1914 set_bits(cg_clustersfree(cg, 0), b, 1);
1915 if (is_ufs2 == 0) {
1916 old_cg_blktot(cg, 0)[
1917 old_cbtocylno(newsb,
1918 f - newsb->fs_frag)]++;
1919 old_cg_blks(newsb, cg,
1920 old_cbtocylno(newsb,
1921 f - newsb->fs_frag),
1922 0)[old_cbtorpos(newsb,
1923 f - newsb->fs_frag)]++;
1924 }
1925 blkrun++;
1926 } else {
1927 if (fragrun > 0) {
1928 cg->cg_frsum[fragrun]++;
1929 cg->cg_cs.cs_nffree += fragrun;
1930 }
1931 if (newsb->fs_contigsumsize > 0) {
1932 if (blkrun > 0) {
1933 cg_clustersum(cg, 0)[(blkrun
1934 > newsb->fs_contigsumsize)
1935 ? newsb->fs_contigsumsize
1936 : blkrun]++;
1937 }
1938 }
1939 blkrun = 0;
1940 }
1941 fwb = 0;
1942 b++;
1943 blkfree = 1;
1944 fragrun = 0;
1945 }
1946 }
1947 if (fragrun > 0) {
1948 cg->cg_frsum[fragrun]++;
1949 cg->cg_cs.cs_nffree += fragrun;
1950 }
1951 if ((blkrun > 0) && (newsb->fs_contigsumsize > 0)) {
1952 cg_clustersum(cg, 0)[(blkrun > newsb->fs_contigsumsize) ?
1953 newsb->fs_contigsumsize : blkrun]++;
1954 }
1955 /*
1956 * Put the updated summary info back into csums, and add it
1957 * back into the sb's summary info. Then mark the cg dirty.
1958 */
1959 csums[cgn] = cg->cg_cs;
1960 newsb->fs_cstotal.cs_nffree += cg->cg_cs.cs_nffree;
1961 newsb->fs_cstotal.cs_nbfree += cg->cg_cs.cs_nbfree;
1962 cgflags[cgn] |= CGF_DIRTY;
1963 }
1964 /*
1965 * Recompute the cg_inosused()[] bitmap, and the cs_nifree and cs_ndir
1966 * values, for a cg, based on the in-core inodes for that cg.
1967 */
1968 static void
1969 rescan_inomaps(int cgn)
1970 {
1971 struct cg *cg;
1972 int inum;
1973 int iwc;
1974
1975 cg = cgs[cgn];
1976 newsb->fs_cstotal.cs_ndir -= cg->cg_cs.cs_ndir;
1977 newsb->fs_cstotal.cs_nifree -= cg->cg_cs.cs_nifree;
1978 cg->cg_cs.cs_ndir = 0;
1979 cg->cg_cs.cs_nifree = 0;
1980 memset(&cg_inosused(cg, 0)[0], 0, howmany(newsb->fs_ipg, NBBY));
1981 inum = cgn * newsb->fs_ipg;
1982 if (cgn == 0) {
1983 set_bits(cg_inosused(cg, 0), 0, 2);
1984 iwc = 2;
1985 inum += 2;
1986 } else {
1987 iwc = 0;
1988 }
1989 for (; iwc < newsb->fs_ipg; iwc++, inum++) {
1990 switch (DIP(inodes + inum, di_mode) & IFMT) {
1991 case 0:
1992 cg->cg_cs.cs_nifree++;
1993 break;
1994 case IFDIR:
1995 cg->cg_cs.cs_ndir++;
1996 /* FALLTHROUGH */
1997 default:
1998 set_bits(cg_inosused(cg, 0), iwc, 1);
1999 break;
2000 }
2001 }
2002 csums[cgn] = cg->cg_cs;
2003 newsb->fs_cstotal.cs_ndir += cg->cg_cs.cs_ndir;
2004 newsb->fs_cstotal.cs_nifree += cg->cg_cs.cs_nifree;
2005 cgflags[cgn] |= CGF_DIRTY;
2006 }
2007 /*
2008 * Flush cgs to disk, recomputing anything they're marked as needing.
2009 */
2010 static void
2011 flush_cgs(void)
2012 {
2013 int i;
2014
2015 for (i = 0; i < newsb->fs_ncg; i++) {
2016 progress_bar(special, "flush cg",
2017 i, newsb->fs_ncg - 1);
2018 if (cgflags[i] & CGF_BLKMAPS) {
2019 rescan_blkmaps(i);
2020 }
2021 if (cgflags[i] & CGF_INOMAPS) {
2022 rescan_inomaps(i);
2023 }
2024 if (cgflags[i] & CGF_DIRTY) {
2025 cgs[i]->cg_rotor = 0;
2026 cgs[i]->cg_frotor = 0;
2027 cgs[i]->cg_irotor = 0;
2028 if (needswap)
2029 ffs_cg_swap(cgs[i],cgs[i],newsb);
2030 writeat(FFS_FSBTODB(newsb, cgtod(newsb, i)), cgs[i],
2031 cgblksz);
2032 }
2033 }
2034 if (needswap)
2035 ffs_csum_swap(csums,csums,newsb->fs_cssize);
2036 writeat(FFS_FSBTODB(newsb, newsb->fs_csaddr), csums, newsb->fs_cssize);
2037
2038 progress_done();
2039 }
2040 /*
2041 * Write the superblock, both to the main superblock and to each cg's
2042 * alternative superblock.
2043 */
2044 static void
2045 write_sbs(void)
2046 {
2047 int i;
2048
2049 if (newsb->fs_magic == FS_UFS1_MAGIC &&
2050 (newsb->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
2051 newsb->fs_old_time = newsb->fs_time;
2052 newsb->fs_old_size = newsb->fs_size;
2053 /* we don't update fs_csaddr */
2054 newsb->fs_old_dsize = newsb->fs_dsize;
2055 newsb->fs_old_cstotal.cs_ndir = newsb->fs_cstotal.cs_ndir;
2056 newsb->fs_old_cstotal.cs_nbfree = newsb->fs_cstotal.cs_nbfree;
2057 newsb->fs_old_cstotal.cs_nifree = newsb->fs_cstotal.cs_nifree;
2058 newsb->fs_old_cstotal.cs_nffree = newsb->fs_cstotal.cs_nffree;
2059 /* fill fs_old_postbl_start with 256 bytes of 0xff? */
2060 }
2061 /* copy newsb back to oldsb, so we can use it for offsets if
2062 newsb has been swapped for writing to disk */
2063 memcpy(oldsb, newsb, SBLOCKSIZE);
2064 if (needswap)
2065 ffs_sb_swap(newsb,newsb);
2066 writeat(where / DEV_BSIZE, newsb, SBLOCKSIZE);
2067 for (i = 0; i < oldsb->fs_ncg; i++) {
2068 progress_bar(special, "write sb",
2069 i, oldsb->fs_ncg - 1);
2070 writeat(FFS_FSBTODB(oldsb, cgsblock(oldsb, i)), newsb, SBLOCKSIZE);
2071 }
2072
2073 progress_done();
2074 }
2075
2076 /*
2077 * Check to see wether new size changes the filesystem
2078 * return exit code
2079 */
2080 static int
2081 checkonly(void)
2082 {
2083 if (makegeometry(0)) {
2084 if (verbose) {
2085 printf("Wouldn't change: already %" PRId64
2086 " blocks\n", (int64_t)oldsb->fs_size);
2087 }
2088 return 1;
2089 }
2090
2091 if (verbose) {
2092 printf("Would change: newsize: %" PRId64 " oldsize: %"
2093 PRId64 " fsdb: %" PRId64 "\n", FFS_DBTOFSB(oldsb, newsize),
2094 (int64_t)oldsb->fs_size,
2095 (int64_t)oldsb->fs_fsbtodb);
2096 }
2097 return 0;
2098 }
2099
2100 static off_t
2101 get_dev_size(char *dev_name)
2102 {
2103 struct dkwedge_info dkw;
2104 struct partition *pp;
2105 struct disklabel lp;
2106 struct stat st;
2107 size_t ptn;
2108
2109 /* Get info about partition/wedge */
2110 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1)
2111 return dkw.dkw_size;
2112 if (ioctl(fd, DIOCGDINFO, &lp) != -1) {
2113 ptn = strchr(dev_name, '\0')[-1] - 'a';
2114 if (ptn >= lp.d_npartitions)
2115 return 0;
2116 pp = &lp.d_partitions[ptn];
2117 return pp->p_size;
2118 }
2119 if (fstat(fd, &st) != -1 && S_ISREG(st.st_mode))
2120 return st.st_size / DEV_BSIZE;
2121
2122 return 0;
2123 }
2124
2125 /*
2126 * main().
2127 */
2128 int
2129 main(int argc, char **argv)
2130 {
2131 int ch;
2132 int CheckOnlyFlag;
2133 int ExpertFlag;
2134 int SFlag;
2135 size_t i;
2136
2137 char reply[5];
2138
2139 newsize = 0;
2140 ExpertFlag = 0;
2141 SFlag = 0;
2142 CheckOnlyFlag = 0;
2143
2144 while ((ch = getopt(argc, argv, "cps:vy")) != -1) {
2145 switch (ch) {
2146 case 'c':
2147 CheckOnlyFlag = 1;
2148 break;
2149 case 'p':
2150 progress = 1;
2151 break;
2152 case 's':
2153 SFlag = 1;
2154 newsize = strtoll(optarg, NULL, 10);
2155 if(newsize < 1) {
2156 usage();
2157 }
2158 break;
2159 case 'v':
2160 verbose = 1;
2161 break;
2162 case 'y':
2163 ExpertFlag = 1;
2164 break;
2165 case '?':
2166 /* FALLTHROUGH */
2167 default:
2168 usage();
2169 }
2170 }
2171 argc -= optind;
2172 argv += optind;
2173
2174 if (argc != 1) {
2175 usage();
2176 }
2177
2178 special = *argv;
2179
2180 if (ExpertFlag == 0 && CheckOnlyFlag == 0) {
2181 printf("It's required to manually run fsck on file system "
2182 "before you can resize it\n\n"
2183 " Did you run fsck on your disk (Yes/No) ? ");
2184 fgets(reply, (int)sizeof(reply), stdin);
2185 if (strcasecmp(reply, "Yes\n")) {
2186 printf("\n Nothing done \n");
2187 exit(EXIT_SUCCESS);
2188 }
2189 }
2190
2191 fd = open(special, O_RDWR, 0);
2192 if (fd < 0)
2193 err(EXIT_FAILURE, "Can't open `%s'", special);
2194 checksmallio();
2195
2196 if (SFlag == 0) {
2197 newsize = get_dev_size(special);
2198 if (newsize == 0)
2199 err(EXIT_FAILURE,
2200 "Can't resize file system, newsize not known.");
2201 }
2202
2203 oldsb = (struct fs *) & sbbuf;
2204 newsb = (struct fs *) (SBLOCKSIZE + (char *) &sbbuf);
2205 for (where = search[i = 0]; search[i] != -1; where = search[++i]) {
2206 readat(where / DEV_BSIZE, oldsb, SBLOCKSIZE);
2207 switch (oldsb->fs_magic) {
2208 case FS_UFS2_MAGIC:
2209 is_ufs2 = 1;
2210 /* FALLTHROUGH */
2211 case FS_UFS1_MAGIC:
2212 needswap = 0;
2213 break;
2214 case FS_UFS2_MAGIC_SWAPPED:
2215 is_ufs2 = 1;
2216 /* FALLTHROUGH */
2217 case FS_UFS1_MAGIC_SWAPPED:
2218 needswap = 1;
2219 break;
2220 default:
2221 continue;
2222 }
2223 if (!is_ufs2 && where == SBLOCK_UFS2)
2224 continue;
2225 break;
2226 }
2227 if (where == (off_t)-1)
2228 errx(EXIT_FAILURE, "Bad magic number");
2229 if (needswap)
2230 ffs_sb_swap(oldsb,oldsb);
2231 if (oldsb->fs_magic == FS_UFS1_MAGIC &&
2232 (oldsb->fs_old_flags & FS_FLAGS_UPDATED) == 0) {
2233 oldsb->fs_csaddr = oldsb->fs_old_csaddr;
2234 oldsb->fs_size = oldsb->fs_old_size;
2235 oldsb->fs_dsize = oldsb->fs_old_dsize;
2236 oldsb->fs_cstotal.cs_ndir = oldsb->fs_old_cstotal.cs_ndir;
2237 oldsb->fs_cstotal.cs_nbfree = oldsb->fs_old_cstotal.cs_nbfree;
2238 oldsb->fs_cstotal.cs_nifree = oldsb->fs_old_cstotal.cs_nifree;
2239 oldsb->fs_cstotal.cs_nffree = oldsb->fs_old_cstotal.cs_nffree;
2240 /* any others? */
2241 printf("Resizing with ffsv1 superblock\n");
2242 }
2243
2244 oldsb->fs_qbmask = ~(int64_t) oldsb->fs_bmask;
2245 oldsb->fs_qfmask = ~(int64_t) oldsb->fs_fmask;
2246 if (oldsb->fs_ipg % FFS_INOPB(oldsb))
2247 errx(EXIT_FAILURE, "ipg[%d] %% FFS_INOPB[%d] != 0",
2248 (int) oldsb->fs_ipg, (int) FFS_INOPB(oldsb));
2249 /* The superblock is bigger than struct fs (there are trailing
2250 * tables, of non-fixed size); make sure we copy the whole
2251 * thing. SBLOCKSIZE may be an over-estimate, but we do this
2252 * just once, so being generous is cheap. */
2253 memcpy(newsb, oldsb, SBLOCKSIZE);
2254
2255 if (progress) {
2256 progress_ttywidth(0);
2257 signal(SIGWINCH, progress_ttywidth);
2258 }
2259
2260 loadcgs();
2261
2262 if (progress && !CheckOnlyFlag) {
2263 progress_switch(progress);
2264 progress_init();
2265 }
2266
2267 if (newsize > FFS_FSBTODB(oldsb, oldsb->fs_size)) {
2268 if (CheckOnlyFlag)
2269 exit(checkonly());
2270 grow();
2271 } else if (newsize < FFS_FSBTODB(oldsb, oldsb->fs_size)) {
2272 if (is_ufs2)
2273 errx(EXIT_FAILURE,"shrinking not supported for ufs2");
2274 if (CheckOnlyFlag)
2275 exit(checkonly());
2276 shrink();
2277 } else {
2278 if (CheckOnlyFlag)
2279 exit(checkonly());
2280 if (verbose)
2281 printf("No change requested: already %" PRId64
2282 " blocks\n", (int64_t)oldsb->fs_size);
2283 }
2284
2285 flush_cgs();
2286 write_sbs();
2287 if (isplainfile())
2288 ftruncate(fd,newsize * DEV_BSIZE);
2289 return 0;
2290 }
2291
2292 static void
2293 usage(void)
2294 {
2295
2296 (void)fprintf(stderr, "usage: %s [-cvy] [-s size] special\n",
2297 getprogname());
2298 exit(EXIT_FAILURE);
2299 }
2300