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