]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/growfs/growfs.c
Add UPDATING entries and bump version.
[FreeBSD/FreeBSD.git] / sbin / growfs / growfs.c
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1980, 1989, 1993 The Regents of the University of California.
5  * Copyright (c) 2000 Christoph Herrmann, Thomas-Henning von Kamptz
6  * Copyright (c) 2012 The FreeBSD Foundation
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Christoph Herrmann and Thomas-Henning von Kamptz, Munich and Frankfurt.
11  *
12  * Portions of this software were developed by Edward Tomasz Napierala
13  * under sponsorship from the FreeBSD Foundation.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. All advertising materials mentioning features or use of this software
24  *    must display the following acknowledgment:
25  *      This product includes software developed by the University of
26  *      California, Berkeley and its contributors, as well as Christoph
27  *      Herrmann and Thomas-Henning von Kamptz.
28  * 4. Neither the name of the University nor the names of its contributors
29  *    may be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42  * SUCH DAMAGE.
43  *
44  * $TSHeader: src/sbin/growfs/growfs.c,v 1.5 2000/12/12 19:31:00 tomsoft Exp $
45  *
46  */
47
48 #ifndef lint
49 static const char copyright[] =
50 "@(#) Copyright (c) 2000 Christoph Herrmann, Thomas-Henning von Kamptz\n\
51 Copyright (c) 1980, 1989, 1993 The Regents of the University of California.\n\
52 All rights reserved.\n";
53 #endif /* not lint */
54
55 #include <sys/cdefs.h>
56 __FBSDID("$FreeBSD$");
57
58 #include <sys/param.h>
59 #include <sys/ioctl.h>
60 #include <sys/stat.h>
61 #include <sys/disk.h>
62 #include <sys/ucred.h>
63 #include <sys/mount.h>
64
65 #include <stdio.h>
66 #include <paths.h>
67 #include <ctype.h>
68 #include <err.h>
69 #include <errno.h>
70 #include <fcntl.h>
71 #include <fstab.h>
72 #include <inttypes.h>
73 #include <limits.h>
74 #include <mntopts.h>
75 #include <paths.h>
76 #include <stdlib.h>
77 #include <stdint.h>
78 #include <string.h>
79 #include <time.h>
80 #include <unistd.h>
81 #include <ufs/ufs/dinode.h>
82 #include <ufs/ffs/fs.h>
83 #include <libutil.h>
84 #include <libufs.h>
85
86 #include "debug.h"
87
88 #ifdef FS_DEBUG
89 int     _dbg_lvl_ = (DL_INFO);  /* DL_TRC */
90 #endif /* FS_DEBUG */
91
92 static union {
93         struct fs       fs;
94         char            pad[SBLOCKSIZE];
95 } fsun1, fsun2;
96 #define sblock  fsun1.fs        /* the new superblock */
97 #define osblock fsun2.fs        /* the old superblock */
98
99 static union {
100         struct cg       cg;
101         char            pad[MAXBSIZE];
102 } cgun1, cgun2;
103 #define acg     cgun1.cg        /* a cylinder cgroup (new) */
104 #define aocg    cgun2.cg        /* an old cylinder group */
105
106 static struct csum      *fscs;  /* cylinder summary */
107
108 static void     growfs(int, int, unsigned int);
109 static void     rdfs(ufs2_daddr_t, size_t, void *, int);
110 static void     wtfs(ufs2_daddr_t, size_t, void *, int, unsigned int);
111 static int      charsperline(void);
112 static void     usage(void);
113 static int      isblock(struct fs *, unsigned char *, int);
114 static void     clrblock(struct fs *, unsigned char *, int);
115 static void     setblock(struct fs *, unsigned char *, int);
116 static void     initcg(int, time_t, int, unsigned int);
117 static void     updjcg(int, time_t, int, int, unsigned int);
118 static void     updcsloc(time_t, int, int, unsigned int);
119 static void     frag_adjust(ufs2_daddr_t, int);
120 static void     updclst(int);
121 static void     mount_reload(const struct statfs *stfs);
122 static void     cgckhash(struct cg *);
123
124 /*
125  * Here we actually start growing the file system. We basically read the
126  * cylinder summary from the first cylinder group as we want to update
127  * this on the fly during our various operations. First we handle the
128  * changes in the former last cylinder group. Afterwards we create all new
129  * cylinder groups.  Now we handle the cylinder group containing the
130  * cylinder summary which might result in a relocation of the whole
131  * structure.  In the end we write back the updated cylinder summary, the
132  * new superblock, and slightly patched versions of the super block
133  * copies.
134  */
135 static void
136 growfs(int fsi, int fso, unsigned int Nflag)
137 {
138         DBG_FUNC("growfs")
139         time_t modtime;
140         uint cylno;
141         int i, j, width;
142         char tmpbuf[100];
143
144         DBG_ENTER;
145
146         time(&modtime);
147
148         /*
149          * Get the cylinder summary into the memory.
150          */
151         fscs = (struct csum *)calloc((size_t)1, (size_t)sblock.fs_cssize);
152         if (fscs == NULL)
153                 errx(1, "calloc failed");
154         memcpy(fscs, osblock.fs_csp, osblock.fs_cssize);
155         free(osblock.fs_csp);
156         osblock.fs_csp = NULL;
157         sblock.fs_csp = fscs;
158
159 #ifdef FS_DEBUG
160         {
161                 struct csum *dbg_csp;
162                 u_int32_t dbg_csc;
163                 char dbg_line[80];
164
165                 dbg_csp = fscs;
166
167                 for (dbg_csc = 0; dbg_csc < osblock.fs_ncg; dbg_csc++) {
168                         snprintf(dbg_line, sizeof(dbg_line),
169                             "%d. old csum in old location", dbg_csc);
170                         DBG_DUMP_CSUM(&osblock, dbg_line, dbg_csp++);
171                 }
172         }
173 #endif /* FS_DEBUG */
174         DBG_PRINT0("fscs read\n");
175
176         /*
177          * Do all needed changes in the former last cylinder group.
178          */
179         updjcg(osblock.fs_ncg - 1, modtime, fsi, fso, Nflag);
180
181         /*
182          * Dump out summary information about file system.
183          */
184 #ifdef FS_DEBUG
185 #define B2MBFACTOR (1 / (1024.0 * 1024.0))
186         printf("growfs: %.1fMB (%jd sectors) block size %d, fragment size %d\n",
187             (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
188             (intmax_t)fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize,
189             sblock.fs_fsize);
190         printf("\tusing %d cylinder groups of %.2fMB, %d blks, %d inodes.\n",
191             sblock.fs_ncg, (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
192             sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
193         if (sblock.fs_flags & FS_DOSOFTDEP)
194                 printf("\twith soft updates\n");
195 #undef B2MBFACTOR
196 #endif /* FS_DEBUG */
197
198         /*
199          * Now build the cylinders group blocks and
200          * then print out indices of cylinder groups.
201          */
202         printf("super-block backups (for fsck_ffs -b #) at:\n");
203         i = 0;
204         width = charsperline();
205
206         /*
207          * Iterate for only the new cylinder groups.
208          */
209         for (cylno = osblock.fs_ncg; cylno < sblock.fs_ncg; cylno++) {
210                 initcg(cylno, modtime, fso, Nflag);
211                 j = sprintf(tmpbuf, " %jd%s",
212                     (intmax_t)fsbtodb(&sblock, cgsblock(&sblock, cylno)),
213                     cylno < (sblock.fs_ncg - 1) ? "," : "" );
214                 if (i + j >= width) {
215                         printf("\n");
216                         i = 0;
217                 }
218                 i += j;
219                 printf("%s", tmpbuf);
220                 fflush(stdout);
221         }
222         printf("\n");
223
224         /*
225          * Do all needed changes in the first cylinder group.
226          * allocate blocks in new location
227          */
228         updcsloc(modtime, fsi, fso, Nflag);
229
230         /*
231          * Clean up the dynamic fields in our superblock.
232          * 
233          * XXX
234          * The following fields are currently distributed from the superblock
235          * to the copies:
236          *     fs_minfree
237          *     fs_rotdelay
238          *     fs_maxcontig
239          *     fs_maxbpg
240          *     fs_minfree,
241          *     fs_optim
242          *     fs_flags
243          *
244          * We probably should rather change the summary for the cylinder group
245          * statistics here to the value of what would be in there, if the file
246          * system were created initially with the new size. Therefor we still
247          * need to find an easy way of calculating that.
248          * Possibly we can try to read the first superblock copy and apply the
249          * "diffed" stats between the old and new superblock by still copying
250          * certain parameters onto that.
251          */
252         sblock.fs_time = modtime;
253         sblock.fs_fmod = 0;
254         sblock.fs_clean = 1;
255         sblock.fs_ronly = 0;
256         sblock.fs_cgrotor = 0;
257         sblock.fs_state = 0;
258         memset((void *)&sblock.fs_fsmnt, 0, sizeof(sblock.fs_fsmnt));
259
260         /*
261          * Now write the new superblock, its summary information,
262          * and all the alternates back to disk.
263          */
264         if (!Nflag && sbput(fso, &sblock, sblock.fs_ncg) != 0)
265                 errc(2, EIO, "could not write updated superblock");
266         DBG_PRINT0("fscs written\n");
267
268 #ifdef FS_DEBUG
269         {
270                 struct csum     *dbg_csp;
271                 u_int32_t       dbg_csc;
272                 char    dbg_line[80];
273
274                 dbg_csp = fscs;
275                 for (dbg_csc = 0; dbg_csc < sblock.fs_ncg; dbg_csc++) {
276                         snprintf(dbg_line, sizeof(dbg_line),
277                             "%d. new csum in new location", dbg_csc);
278                         DBG_DUMP_CSUM(&sblock, dbg_line, dbg_csp++);
279                 }
280         }
281 #endif /* FS_DEBUG */
282
283         DBG_PRINT0("sblock written\n");
284         DBG_DUMP_FS(&sblock, "new initial sblock");
285
286         DBG_PRINT0("sblock copies written\n");
287         DBG_DUMP_FS(&sblock, "new other sblocks");
288
289         DBG_LEAVE;
290         return;
291 }
292
293 /*
294  * This creates a new cylinder group structure, for more details please see
295  * the source of newfs(8), as this function is taken over almost unchanged.
296  * As this is never called for the first cylinder group, the special
297  * provisions for that case are removed here.
298  */
299 static void
300 initcg(int cylno, time_t modtime, int fso, unsigned int Nflag)
301 {
302         DBG_FUNC("initcg")
303         static caddr_t iobuf;
304         long blkno, start;
305         ino_t ino;
306         ufs2_daddr_t i, cbase, dmax;
307         struct ufs1_dinode *dp1;
308         struct csum *cs;
309         uint j, d, dupper, dlower;
310
311         if (iobuf == NULL && (iobuf = malloc(sblock.fs_bsize * 3)) == NULL)
312                 errx(37, "panic: cannot allocate I/O buffer");
313
314         /*
315          * Determine block bounds for cylinder group.
316          * Allow space for super block summary information in first
317          * cylinder group.
318          */
319         cbase = cgbase(&sblock, cylno);
320         dmax = cbase + sblock.fs_fpg;
321         if (dmax > sblock.fs_size)
322                 dmax = sblock.fs_size;
323         dlower = cgsblock(&sblock, cylno) - cbase;
324         dupper = cgdmin(&sblock, cylno) - cbase;
325         if (cylno == 0) /* XXX fscs may be relocated */
326                 dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
327         cs = &fscs[cylno];
328         memset(&acg, 0, sblock.fs_cgsize);
329         acg.cg_time = modtime;
330         acg.cg_magic = CG_MAGIC;
331         acg.cg_cgx = cylno;
332         acg.cg_niblk = sblock.fs_ipg;
333         acg.cg_initediblk = MIN(sblock.fs_ipg, 2 * INOPB(&sblock));
334         acg.cg_ndblk = dmax - cbase;
335         if (sblock.fs_contigsumsize > 0)
336                 acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
337         start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
338         if (sblock.fs_magic == FS_UFS2_MAGIC) {
339                 acg.cg_iusedoff = start;
340         } else {
341                 acg.cg_old_ncyl = sblock.fs_old_cpg;
342                 acg.cg_old_time = acg.cg_time;
343                 acg.cg_time = 0;
344                 acg.cg_old_niblk = acg.cg_niblk;
345                 acg.cg_niblk = 0;
346                 acg.cg_initediblk = 0;
347                 acg.cg_old_btotoff = start;
348                 acg.cg_old_boff = acg.cg_old_btotoff +
349                     sblock.fs_old_cpg * sizeof(int32_t);
350                 acg.cg_iusedoff = acg.cg_old_boff +
351                     sblock.fs_old_cpg * sizeof(u_int16_t);
352         }
353         acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
354         acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
355         if (sblock.fs_contigsumsize > 0) {
356                 acg.cg_clustersumoff =
357                     roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
358                 acg.cg_clustersumoff -= sizeof(u_int32_t);
359                 acg.cg_clusteroff = acg.cg_clustersumoff +
360                     (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
361                 acg.cg_nextfreeoff = acg.cg_clusteroff +
362                     howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
363         }
364         if (acg.cg_nextfreeoff > (unsigned)sblock.fs_cgsize) {
365                 /*
366                  * This should never happen as we would have had that panic
367                  * already on file system creation
368                  */
369                 errx(37, "panic: cylinder group too big");
370         }
371         acg.cg_cs.cs_nifree += sblock.fs_ipg;
372         if (cylno == 0)
373                 for (ino = 0; ino < UFS_ROOTINO; ino++) {
374                         setbit(cg_inosused(&acg), ino);
375                         acg.cg_cs.cs_nifree--;
376                 }
377         /*
378          * For the old file system, we have to initialize all the inodes.
379          */
380         if (sblock.fs_magic == FS_UFS1_MAGIC) {
381                 bzero(iobuf, sblock.fs_bsize);
382                 for (i = 0; i < sblock.fs_ipg / INOPF(&sblock);
383                     i += sblock.fs_frag) {
384                         dp1 = (struct ufs1_dinode *)(void *)iobuf;
385                         for (j = 0; j < INOPB(&sblock); j++) {
386                                 dp1->di_gen = arc4random();
387                                 dp1++;
388                         }
389                         wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
390                             sblock.fs_bsize, iobuf, fso, Nflag);
391                 }
392         }
393         if (cylno > 0) {
394                 /*
395                  * In cylno 0, beginning space is reserved
396                  * for boot and super blocks.
397                  */
398                 for (d = 0; d < dlower; d += sblock.fs_frag) {
399                         blkno = d / sblock.fs_frag;
400                         setblock(&sblock, cg_blksfree(&acg), blkno);
401                         if (sblock.fs_contigsumsize > 0)
402                                 setbit(cg_clustersfree(&acg), blkno);
403                         acg.cg_cs.cs_nbfree++;
404                 }
405                 sblock.fs_dsize += dlower;
406         }
407         sblock.fs_dsize += acg.cg_ndblk - dupper;
408         if ((i = dupper % sblock.fs_frag)) {
409                 acg.cg_frsum[sblock.fs_frag - i]++;
410                 for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
411                         setbit(cg_blksfree(&acg), dupper);
412                         acg.cg_cs.cs_nffree++;
413                 }
414         }
415         for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
416             d += sblock.fs_frag) {
417                 blkno = d / sblock.fs_frag;
418                 setblock(&sblock, cg_blksfree(&acg), blkno);
419                 if (sblock.fs_contigsumsize > 0)
420                         setbit(cg_clustersfree(&acg), blkno);
421                 acg.cg_cs.cs_nbfree++;
422         }
423         if (d < acg.cg_ndblk) {
424                 acg.cg_frsum[acg.cg_ndblk - d]++;
425                 for (; d < acg.cg_ndblk; d++) {
426                         setbit(cg_blksfree(&acg), d);
427                         acg.cg_cs.cs_nffree++;
428                 }
429         }
430         if (sblock.fs_contigsumsize > 0) {
431                 int32_t *sump = cg_clustersum(&acg);
432                 u_char *mapp = cg_clustersfree(&acg);
433                 int map = *mapp++;
434                 int bit = 1;
435                 int run = 0;
436
437                 for (i = 0; i < acg.cg_nclusterblks; i++) {
438                         if ((map & bit) != 0)
439                                 run++;
440                         else if (run != 0) {
441                                 if (run > sblock.fs_contigsumsize)
442                                         run = sblock.fs_contigsumsize;
443                                 sump[run]++;
444                                 run = 0;
445                         }
446                         if ((i & (CHAR_BIT - 1)) != CHAR_BIT - 1)
447                                 bit <<= 1;
448                         else {
449                                 map = *mapp++;
450                                 bit = 1;
451                         }
452                 }
453                 if (run != 0) {
454                         if (run > sblock.fs_contigsumsize)
455                                 run = sblock.fs_contigsumsize;
456                         sump[run]++;
457                 }
458         }
459         sblock.fs_cstotal.cs_ndir += acg.cg_cs.cs_ndir;
460         sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
461         sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
462         sblock.fs_cstotal.cs_nifree += acg.cg_cs.cs_nifree;
463         *cs = acg.cg_cs;
464
465         cgckhash(&acg);
466         memcpy(iobuf, &acg, sblock.fs_cgsize);
467         memset(iobuf + sblock.fs_cgsize, '\0',
468             sblock.fs_bsize * 3 - sblock.fs_cgsize);
469
470         wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
471             sblock.fs_bsize * 3, iobuf, fso, Nflag);
472         DBG_DUMP_CG(&sblock, "new cg", &acg);
473
474         DBG_LEAVE;
475         return;
476 }
477
478 /*
479  * Here we add or subtract (sign +1/-1) the available fragments in a given
480  * block to or from the fragment statistics. By subtracting before and adding
481  * after an operation on the free frag map we can easy update the fragment
482  * statistic, which seems to be otherwise a rather complex operation.
483  */
484 static void
485 frag_adjust(ufs2_daddr_t frag, int sign)
486 {
487         DBG_FUNC("frag_adjust")
488         int fragsize;
489         int f;
490
491         DBG_ENTER;
492
493         fragsize = 0;
494         /*
495          * Here frag only needs to point to any fragment in the block we want
496          * to examine.
497          */
498         for (f = rounddown(frag, sblock.fs_frag);
499             f < roundup(frag + 1, sblock.fs_frag); f++) {
500                 /*
501                  * Count contiguous free fragments.
502                  */
503                 if (isset(cg_blksfree(&acg), f)) {
504                         fragsize++;
505                 } else {
506                         if (fragsize && fragsize < sblock.fs_frag) {
507                                 /*
508                                  * We found something in between.
509                                  */
510                                 acg.cg_frsum[fragsize] += sign;
511                                 DBG_PRINT2("frag_adjust [%d]+=%d\n",
512                                     fragsize, sign);
513                         }
514                         fragsize = 0;
515                 }
516         }
517         if (fragsize && fragsize < sblock.fs_frag) {
518                 /*
519                  * We found something.
520                  */
521                 acg.cg_frsum[fragsize] += sign;
522                 DBG_PRINT2("frag_adjust [%d]+=%d\n", fragsize, sign);
523         }
524         DBG_PRINT2("frag_adjust [[%d]]+=%d\n", fragsize, sign);
525
526         DBG_LEAVE;
527         return;
528 }
529
530 /*
531  * Here we do all needed work for the former last cylinder group. It has to be
532  * changed in any case, even if the file system ended exactly on the end of
533  * this group, as there is some slightly inconsistent handling of the number
534  * of cylinders in the cylinder group. We start again by reading the cylinder
535  * group from disk. If the last block was not fully available, we first handle
536  * the missing fragments, then we handle all new full blocks in that file
537  * system and finally we handle the new last fragmented block in the file
538  * system.  We again have to handle the fragment statistics rotational layout
539  * tables and cluster summary during all those operations.
540  */
541 static void
542 updjcg(int cylno, time_t modtime, int fsi, int fso, unsigned int Nflag)
543 {
544         DBG_FUNC("updjcg")
545         ufs2_daddr_t cbase, dmax, dupper;
546         struct csum *cs;
547         int i, k;
548         int j = 0;
549
550         DBG_ENTER;
551
552         /*
553          * Read the former last (joining) cylinder group from disk, and make
554          * a copy.
555          */
556         rdfs(fsbtodb(&osblock, cgtod(&osblock, cylno)),
557             (size_t)osblock.fs_cgsize, (void *)&aocg, fsi);
558         DBG_PRINT0("jcg read\n");
559         DBG_DUMP_CG(&sblock, "old joining cg", &aocg);
560
561         memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
562
563         /*
564          * If the cylinder group had already its new final size almost
565          * nothing is to be done ... except:
566          * For some reason the value of cg_ncyl in the last cylinder group has
567          * to be zero instead of fs_cpg. As this is now no longer the last
568          * cylinder group we have to change that value now to fs_cpg.
569          */
570
571         if (cgbase(&osblock, cylno + 1) == osblock.fs_size) {
572                 if (sblock.fs_magic == FS_UFS1_MAGIC)
573                         acg.cg_old_ncyl = sblock.fs_old_cpg;
574
575                 cgckhash(&acg);
576                 wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
577                     (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
578                 DBG_PRINT0("jcg written\n");
579                 DBG_DUMP_CG(&sblock, "new joining cg", &acg);
580
581                 DBG_LEAVE;
582                 return;
583         }
584
585         /*
586          * Set up some variables needed later.
587          */
588         cbase = cgbase(&sblock, cylno);
589         dmax = cbase + sblock.fs_fpg;
590         if (dmax > sblock.fs_size)
591                 dmax = sblock.fs_size;
592         dupper = cgdmin(&sblock, cylno) - cbase;
593         if (cylno == 0) /* XXX fscs may be relocated */
594                 dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
595
596         /*
597          * Set pointer to the cylinder summary for our cylinder group.
598          */
599         cs = fscs + cylno;
600
601         /*
602          * Touch the cylinder group, update all fields in the cylinder group as
603          * needed, update the free space in the superblock.
604          */
605         acg.cg_time = modtime;
606         if ((unsigned)cylno == sblock.fs_ncg - 1) {
607                 /*
608                  * This is still the last cylinder group.
609                  */
610                 if (sblock.fs_magic == FS_UFS1_MAGIC)
611                         acg.cg_old_ncyl =
612                             sblock.fs_old_ncyl % sblock.fs_old_cpg;
613         } else {
614                 acg.cg_old_ncyl = sblock.fs_old_cpg;
615         }
616         DBG_PRINT2("jcg dbg: %d %u", cylno, sblock.fs_ncg);
617 #ifdef FS_DEBUG
618         if (sblock.fs_magic == FS_UFS1_MAGIC)
619                 DBG_PRINT2("%d %u", acg.cg_old_ncyl, sblock.fs_old_cpg);
620 #endif
621         DBG_PRINT0("\n");
622         acg.cg_ndblk = dmax - cbase;
623         sblock.fs_dsize += acg.cg_ndblk - aocg.cg_ndblk;
624         if (sblock.fs_contigsumsize > 0)
625                 acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
626
627         /*
628          * Now we have to update the free fragment bitmap for our new free
629          * space.  There again we have to handle the fragmentation and also
630          * the rotational layout tables and the cluster summary.  This is
631          * also done per fragment for the first new block if the old file
632          * system end was not on a block boundary, per fragment for the new
633          * last block if the new file system end is not on a block boundary,
634          * and per block for all space in between.
635          *
636          * Handle the first new block here if it was partially available
637          * before.
638          */
639         if (osblock.fs_size % sblock.fs_frag) {
640                 if (roundup(osblock.fs_size, sblock.fs_frag) <=
641                     sblock.fs_size) {
642                         /*
643                          * The new space is enough to fill at least this
644                          * block
645                          */
646                         j = 0;
647                         for (i = roundup(osblock.fs_size - cbase,
648                             sblock.fs_frag) - 1; i >= osblock.fs_size - cbase;
649                             i--) {
650                                 setbit(cg_blksfree(&acg), i);
651                                 acg.cg_cs.cs_nffree++;
652                                 j++;
653                         }
654
655                         /*
656                          * Check if the fragment just created could join an
657                          * already existing fragment at the former end of the
658                          * file system.
659                          */
660                         if (isblock(&sblock, cg_blksfree(&acg),
661                             ((osblock.fs_size - cgbase(&sblock, cylno)) /
662                              sblock.fs_frag))) {
663                                 /*
664                                  * The block is now completely available.
665                                  */
666                                 DBG_PRINT0("block was\n");
667                                 acg.cg_frsum[osblock.fs_size % sblock.fs_frag]--;
668                                 acg.cg_cs.cs_nbfree++;
669                                 acg.cg_cs.cs_nffree -= sblock.fs_frag;
670                                 k = rounddown(osblock.fs_size - cbase,
671                                     sblock.fs_frag);
672                                 updclst((osblock.fs_size - cbase) /
673                                     sblock.fs_frag);
674                         } else {
675                                 /*
676                                  * Lets rejoin a possible partially growed
677                                  * fragment.
678                                  */
679                                 k = 0;
680                                 while (isset(cg_blksfree(&acg), i) &&
681                                     (i >= rounddown(osblock.fs_size - cbase,
682                                     sblock.fs_frag))) {
683                                         i--;
684                                         k++;
685                                 }
686                                 if (k)
687                                         acg.cg_frsum[k]--;
688                                 acg.cg_frsum[k + j]++;
689                         }
690                 } else {
691                         /*
692                          * We only grow by some fragments within this last
693                          * block.
694                          */
695                         for (i = sblock.fs_size - cbase - 1;
696                             i >= osblock.fs_size - cbase; i--) {
697                                 setbit(cg_blksfree(&acg), i);
698                                 acg.cg_cs.cs_nffree++;
699                                 j++;
700                         }
701                         /*
702                          * Lets rejoin a possible partially growed fragment.
703                          */
704                         k = 0;
705                         while (isset(cg_blksfree(&acg), i) &&
706                             (i >= rounddown(osblock.fs_size - cbase,
707                             sblock.fs_frag))) {
708                                 i--;
709                                 k++;
710                         }
711                         if (k)
712                                 acg.cg_frsum[k]--;
713                         acg.cg_frsum[k + j]++;
714                 }
715         }
716
717         /*
718          * Handle all new complete blocks here.
719          */
720         for (i = roundup(osblock.fs_size - cbase, sblock.fs_frag);
721             i + sblock.fs_frag <= dmax - cbase; /* XXX <= or only < ? */
722             i += sblock.fs_frag) {
723                 j = i / sblock.fs_frag;
724                 setblock(&sblock, cg_blksfree(&acg), j);
725                 updclst(j);
726                 acg.cg_cs.cs_nbfree++;
727         }
728
729         /*
730          * Handle the last new block if there are stll some new fragments left.
731          * Here we don't have to bother about the cluster summary or the even
732          * the rotational layout table.
733          */
734         if (i < (dmax - cbase)) {
735                 acg.cg_frsum[dmax - cbase - i]++;
736                 for (; i < dmax - cbase; i++) {
737                         setbit(cg_blksfree(&acg), i);
738                         acg.cg_cs.cs_nffree++;
739                 }
740         }
741
742         sblock.fs_cstotal.cs_nffree +=
743             (acg.cg_cs.cs_nffree - aocg.cg_cs.cs_nffree);
744         sblock.fs_cstotal.cs_nbfree +=
745             (acg.cg_cs.cs_nbfree - aocg.cg_cs.cs_nbfree);
746         /*
747          * The following statistics are not changed here:
748          *     sblock.fs_cstotal.cs_ndir
749          *     sblock.fs_cstotal.cs_nifree
750          * As the statistics for this cylinder group are ready, copy it to
751          * the summary information array.
752          */
753         *cs = acg.cg_cs;
754
755         /*
756          * Write the updated "joining" cylinder group back to disk.
757          */
758         cgckhash(&acg);
759         wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)), (size_t)sblock.fs_cgsize,
760             (void *)&acg, fso, Nflag);
761         DBG_PRINT0("jcg written\n");
762         DBG_DUMP_CG(&sblock, "new joining cg", &acg);
763
764         DBG_LEAVE;
765         return;
766 }
767
768 /*
769  * Here we update the location of the cylinder summary. We have two possible
770  * ways of growing the cylinder summary:
771  * (1)  We can try to grow the summary in the current location, and relocate
772  *      possibly used blocks within the current cylinder group.
773  * (2)  Alternatively we can relocate the whole cylinder summary to the first
774  *      new completely empty cylinder group. Once the cylinder summary is no
775  *      longer in the beginning of the first cylinder group you should never
776  *      use a version of fsck which is not aware of the possibility to have
777  *      this structure in a non standard place.
778  * Option (2) is considered to be less intrusive to the structure of the file-
779  * system, so that's the one being used.
780  */
781 static void
782 updcsloc(time_t modtime, int fsi, int fso, unsigned int Nflag)
783 {
784         DBG_FUNC("updcsloc")
785         struct csum *cs;
786         int ocscg, ncscg;
787         ufs2_daddr_t d;
788         int lcs = 0;
789         int block;
790
791         DBG_ENTER;
792
793         if (howmany(sblock.fs_cssize, sblock.fs_fsize) ==
794             howmany(osblock.fs_cssize, osblock.fs_fsize)) {
795                 /*
796                  * No new fragment needed.
797                  */
798                 DBG_LEAVE;
799                 return;
800         }
801         ocscg = dtog(&osblock, osblock.fs_csaddr);
802         cs = fscs + ocscg;
803
804         /*
805          * Read original cylinder group from disk, and make a copy.
806          * XXX  If Nflag is set in some very rare cases we now miss
807          *      some changes done in updjcg by reading the unmodified
808          *      block from disk.
809          */
810         rdfs(fsbtodb(&osblock, cgtod(&osblock, ocscg)),
811             (size_t)osblock.fs_cgsize, (void *)&aocg, fsi);
812         DBG_PRINT0("oscg read\n");
813         DBG_DUMP_CG(&sblock, "old summary cg", &aocg);
814
815         memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
816
817         /*
818          * Touch the cylinder group, set up local variables needed later
819          * and update the superblock.
820          */
821         acg.cg_time = modtime;
822
823         /*
824          * XXX  In the case of having active snapshots we may need much more
825          *      blocks for the copy on write. We need each block twice, and
826          *      also up to 8*3 blocks for indirect blocks for all possible
827          *      references.
828          */
829         /*
830          * There is not enough space in the old cylinder group to
831          * relocate all blocks as needed, so we relocate the whole
832          * cylinder group summary to a new group. We try to use the
833          * first complete new cylinder group just created. Within the
834          * cylinder group we align the area immediately after the
835          * cylinder group information location in order to be as
836          * close as possible to the original implementation of ffs.
837          *
838          * First we have to make sure we'll find enough space in the
839          * new cylinder group. If not, then we currently give up.
840          * We start with freeing everything which was used by the
841          * fragments of the old cylinder summary in the current group.
842          * Now we write back the group meta data, read in the needed
843          * meta data from the new cylinder group, and start allocating
844          * within that group. Here we can assume, the group to be
845          * completely empty. Which makes the handling of fragments and
846          * clusters a lot easier.
847          */
848         DBG_TRC;
849         if (sblock.fs_ncg - osblock.fs_ncg < 2)
850                 errx(2, "panic: not enough space");
851
852         /*
853          * Point "d" to the first fragment not used by the cylinder
854          * summary.
855          */
856         d = osblock.fs_csaddr + (osblock.fs_cssize / osblock.fs_fsize);
857
858         /*
859          * Set up last cluster size ("lcs") already here. Calculate
860          * the size for the trailing cluster just behind where "d"
861          * points to.
862          */
863         if (sblock.fs_contigsumsize > 0) {
864                 for (block = howmany(d % sblock.fs_fpg, sblock.fs_frag),
865                     lcs = 0; lcs < sblock.fs_contigsumsize; block++, lcs++) {
866                         if (isclr(cg_clustersfree(&acg), block))
867                                 break;
868                 }
869         }
870
871         /*
872          * Point "d" to the last frag used by the cylinder summary.
873          */
874         d--;
875
876         DBG_PRINT1("d=%jd\n", (intmax_t)d);
877         if ((d + 1) % sblock.fs_frag) {
878                 /*
879                  * The end of the cylinder summary is not a complete
880                  * block.
881                  */
882                 DBG_TRC;
883                 frag_adjust(d % sblock.fs_fpg, -1);
884                 for (; (d + 1) % sblock.fs_frag; d--) {
885                         DBG_PRINT1("d=%jd\n", (intmax_t)d);
886                         setbit(cg_blksfree(&acg), d % sblock.fs_fpg);
887                         acg.cg_cs.cs_nffree++;
888                         sblock.fs_cstotal.cs_nffree++;
889                 }
890                 /*
891                  * Point "d" to the last fragment of the last
892                  * (incomplete) block of the cylinder summary.
893                  */
894                 d++;
895                 frag_adjust(d % sblock.fs_fpg, 1);
896
897                 if (isblock(&sblock, cg_blksfree(&acg),
898                     (d % sblock.fs_fpg) / sblock.fs_frag)) {
899                         DBG_PRINT1("d=%jd\n", (intmax_t)d);
900                         acg.cg_cs.cs_nffree -= sblock.fs_frag;
901                         acg.cg_cs.cs_nbfree++;
902                         sblock.fs_cstotal.cs_nffree -= sblock.fs_frag;
903                         sblock.fs_cstotal.cs_nbfree++;
904                         if (sblock.fs_contigsumsize > 0) {
905                                 setbit(cg_clustersfree(&acg),
906                                     (d % sblock.fs_fpg) / sblock.fs_frag);
907                                 if (lcs < sblock.fs_contigsumsize) {
908                                         if (lcs)
909                                                 cg_clustersum(&acg)[lcs]--;
910                                         lcs++;
911                                         cg_clustersum(&acg)[lcs]++;
912                                 }
913                         }
914                 }
915                 /*
916                  * Point "d" to the first fragment of the block before
917                  * the last incomplete block.
918                  */
919                 d--;
920         }
921
922         DBG_PRINT1("d=%jd\n", (intmax_t)d);
923         for (d = rounddown(d, sblock.fs_frag); d >= osblock.fs_csaddr;
924             d -= sblock.fs_frag) {
925                 DBG_TRC;
926                 DBG_PRINT1("d=%jd\n", (intmax_t)d);
927                 setblock(&sblock, cg_blksfree(&acg),
928                     (d % sblock.fs_fpg) / sblock.fs_frag);
929                 acg.cg_cs.cs_nbfree++;
930                 sblock.fs_cstotal.cs_nbfree++;
931                 if (sblock.fs_contigsumsize > 0) {
932                         setbit(cg_clustersfree(&acg),
933                             (d % sblock.fs_fpg) / sblock.fs_frag);
934                         /*
935                          * The last cluster size is already set up.
936                          */
937                         if (lcs < sblock.fs_contigsumsize) {
938                                 if (lcs)
939                                         cg_clustersum(&acg)[lcs]--;
940                                 lcs++;
941                                 cg_clustersum(&acg)[lcs]++;
942                         }
943                 }
944         }
945         *cs = acg.cg_cs;
946
947         /*
948          * Now write the former cylinder group containing the cylinder
949          * summary back to disk.
950          */
951         cgckhash(&acg);
952         wtfs(fsbtodb(&sblock, cgtod(&sblock, ocscg)),
953             (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
954         DBG_PRINT0("oscg written\n");
955         DBG_DUMP_CG(&sblock, "old summary cg", &acg);
956
957         /*
958          * Find the beginning of the new cylinder group containing the
959          * cylinder summary.
960          */
961         sblock.fs_csaddr = cgdmin(&sblock, osblock.fs_ncg);
962         ncscg = dtog(&sblock, sblock.fs_csaddr);
963         cs = fscs + ncscg;
964
965         /*
966          * If Nflag is specified, we would now read random data instead
967          * of an empty cg structure from disk. So we can't simulate that
968          * part for now.
969          */
970         if (Nflag) {
971                 DBG_PRINT0("nscg update skipped\n");
972                 DBG_LEAVE;
973                 return;
974         }
975
976         /*
977          * Read the future cylinder group containing the cylinder
978          * summary from disk, and make a copy.
979          */
980         rdfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
981             (size_t)sblock.fs_cgsize, (void *)&aocg, fsi);
982         DBG_PRINT0("nscg read\n");
983         DBG_DUMP_CG(&sblock, "new summary cg", &aocg);
984
985         memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
986
987         /*
988          * Allocate all complete blocks used by the new cylinder
989          * summary.
990          */
991         for (d = sblock.fs_csaddr; d + sblock.fs_frag <=
992             sblock.fs_csaddr + (sblock.fs_cssize / sblock.fs_fsize);
993             d += sblock.fs_frag) {
994                 clrblock(&sblock, cg_blksfree(&acg),
995                     (d % sblock.fs_fpg) / sblock.fs_frag);
996                 acg.cg_cs.cs_nbfree--;
997                 sblock.fs_cstotal.cs_nbfree--;
998                 if (sblock.fs_contigsumsize > 0) {
999                         clrbit(cg_clustersfree(&acg),
1000                             (d % sblock.fs_fpg) / sblock.fs_frag);
1001                 }
1002         }
1003
1004         /*
1005          * Allocate all fragments used by the cylinder summary in the
1006          * last block.
1007          */
1008         if (d < sblock.fs_csaddr + (sblock.fs_cssize / sblock.fs_fsize)) {
1009                 for (; d - sblock.fs_csaddr <
1010                     sblock.fs_cssize/sblock.fs_fsize; d++) {
1011                         clrbit(cg_blksfree(&acg), d % sblock.fs_fpg);
1012                         acg.cg_cs.cs_nffree--;
1013                         sblock.fs_cstotal.cs_nffree--;
1014                 }
1015                 acg.cg_cs.cs_nbfree--;
1016                 acg.cg_cs.cs_nffree += sblock.fs_frag;
1017                 sblock.fs_cstotal.cs_nbfree--;
1018                 sblock.fs_cstotal.cs_nffree += sblock.fs_frag;
1019                 if (sblock.fs_contigsumsize > 0)
1020                         clrbit(cg_clustersfree(&acg),
1021                             (d % sblock.fs_fpg) / sblock.fs_frag);
1022
1023                 frag_adjust(d % sblock.fs_fpg, 1);
1024         }
1025         /*
1026          * XXX  Handle the cluster statistics here in the case this
1027          *      cylinder group is now almost full, and the remaining
1028          *      space is less then the maximum cluster size. This is
1029          *      probably not needed, as you would hardly find a file
1030          *      system which has only MAXCSBUFS+FS_MAXCONTIG of free
1031          *      space right behind the cylinder group information in
1032          *      any new cylinder group.
1033          */
1034
1035         /*
1036          * Update our statistics in the cylinder summary.
1037          */
1038         *cs = acg.cg_cs;
1039
1040         /*
1041          * Write the new cylinder group containing the cylinder summary
1042          * back to disk.
1043          */
1044         cgckhash(&acg);
1045         wtfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
1046             (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
1047         DBG_PRINT0("nscg written\n");
1048         DBG_DUMP_CG(&sblock, "new summary cg", &acg);
1049
1050         DBG_LEAVE;
1051         return;
1052 }
1053
1054 /*
1055  * Here we read some block(s) from disk.
1056  */
1057 static void
1058 rdfs(ufs2_daddr_t bno, size_t size, void *bf, int fsi)
1059 {
1060         DBG_FUNC("rdfs")
1061         ssize_t n;
1062
1063         DBG_ENTER;
1064
1065         if (bno < 0)
1066                 err(32, "rdfs: attempting to read negative block number");
1067         if (lseek(fsi, (off_t)bno * DEV_BSIZE, 0) < 0)
1068                 err(33, "rdfs: seek error: %jd", (intmax_t)bno);
1069         n = read(fsi, bf, size);
1070         if (n != (ssize_t)size)
1071                 err(34, "rdfs: read error: %jd", (intmax_t)bno);
1072
1073         DBG_LEAVE;
1074         return;
1075 }
1076
1077 /*
1078  * Here we write some block(s) to disk.
1079  */
1080 static void
1081 wtfs(ufs2_daddr_t bno, size_t size, void *bf, int fso, unsigned int Nflag)
1082 {
1083         DBG_FUNC("wtfs")
1084         ssize_t n;
1085
1086         DBG_ENTER;
1087
1088         if (Nflag) {
1089                 DBG_LEAVE;
1090                 return;
1091         }
1092         if (lseek(fso, (off_t)bno * DEV_BSIZE, SEEK_SET) < 0)
1093                 err(35, "wtfs: seek error: %ld", (long)bno);
1094         n = write(fso, bf, size);
1095         if (n != (ssize_t)size)
1096                 err(36, "wtfs: write error: %ld", (long)bno);
1097
1098         DBG_LEAVE;
1099         return;
1100 }
1101
1102 /*
1103  * Here we check if all frags of a block are free. For more details again
1104  * please see the source of newfs(8), as this function is taken over almost
1105  * unchanged.
1106  */
1107 static int
1108 isblock(struct fs *fs, unsigned char *cp, int h)
1109 {
1110         DBG_FUNC("isblock")
1111         unsigned char mask;
1112
1113         DBG_ENTER;
1114
1115         switch (fs->fs_frag) {
1116         case 8:
1117                 DBG_LEAVE;
1118                 return (cp[h] == 0xff);
1119         case 4:
1120                 mask = 0x0f << ((h & 0x1) << 2);
1121                 DBG_LEAVE;
1122                 return ((cp[h >> 1] & mask) == mask);
1123         case 2:
1124                 mask = 0x03 << ((h & 0x3) << 1);
1125                 DBG_LEAVE;
1126                 return ((cp[h >> 2] & mask) == mask);
1127         case 1:
1128                 mask = 0x01 << (h & 0x7);
1129                 DBG_LEAVE;
1130                 return ((cp[h >> 3] & mask) == mask);
1131         default:
1132                 fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
1133                 DBG_LEAVE;
1134                 return (0);
1135         }
1136 }
1137
1138 /*
1139  * Here we allocate a complete block in the block map. For more details again
1140  * please see the source of newfs(8), as this function is taken over almost
1141  * unchanged.
1142  */
1143 static void
1144 clrblock(struct fs *fs, unsigned char *cp, int h)
1145 {
1146         DBG_FUNC("clrblock")
1147
1148         DBG_ENTER;
1149
1150         switch ((fs)->fs_frag) {
1151         case 8:
1152                 cp[h] = 0;
1153                 break;
1154         case 4:
1155                 cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1156                 break;
1157         case 2:
1158                 cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1159                 break;
1160         case 1:
1161                 cp[h >> 3] &= ~(0x01 << (h & 0x7));
1162                 break;
1163         default:
1164                 warnx("clrblock bad fs_frag %d", fs->fs_frag);
1165                 break;
1166         }
1167
1168         DBG_LEAVE;
1169         return;
1170 }
1171
1172 /*
1173  * Here we free a complete block in the free block map. For more details again
1174  * please see the source of newfs(8), as this function is taken over almost
1175  * unchanged.
1176  */
1177 static void
1178 setblock(struct fs *fs, unsigned char *cp, int h)
1179 {
1180         DBG_FUNC("setblock")
1181
1182         DBG_ENTER;
1183
1184         switch (fs->fs_frag) {
1185         case 8:
1186                 cp[h] = 0xff;
1187                 break;
1188         case 4:
1189                 cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1190                 break;
1191         case 2:
1192                 cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1193                 break;
1194         case 1:
1195                 cp[h >> 3] |= (0x01 << (h & 0x7));
1196                 break;
1197         default:
1198                 warnx("setblock bad fs_frag %d", fs->fs_frag);
1199                 break;
1200         }
1201
1202         DBG_LEAVE;
1203         return;
1204 }
1205
1206 /*
1207  * Figure out how many lines our current terminal has. For more details again
1208  * please see the source of newfs(8), as this function is taken over almost
1209  * unchanged.
1210  */
1211 static int
1212 charsperline(void)
1213 {
1214         DBG_FUNC("charsperline")
1215         int columns;
1216         char *cp;
1217         struct winsize ws;
1218
1219         DBG_ENTER;
1220
1221         columns = 0;
1222         if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1223                 columns = ws.ws_col;
1224         if (columns == 0 && (cp = getenv("COLUMNS")))
1225                 columns = atoi(cp);
1226         if (columns == 0)
1227                 columns = 80;   /* last resort */
1228
1229         DBG_LEAVE;
1230         return (columns);
1231 }
1232
1233 static int
1234 is_dev(const char *name)
1235 {
1236         struct stat devstat;
1237
1238         if (stat(name, &devstat) != 0)
1239                 return (0);
1240         if (!S_ISCHR(devstat.st_mode))
1241                 return (0);
1242         return (1);
1243 }
1244
1245 /*
1246  * Return mountpoint on which the device is currently mounted.
1247  */ 
1248 static const struct statfs *
1249 dev_to_statfs(const char *dev)
1250 {
1251         struct stat devstat, mntdevstat;
1252         struct statfs *mntbuf, *statfsp;
1253         char device[MAXPATHLEN];
1254         char *mntdevname;
1255         int i, mntsize;
1256
1257         /*
1258          * First check the mounted filesystems.
1259          */
1260         if (stat(dev, &devstat) != 0)
1261                 return (NULL);
1262         if (!S_ISCHR(devstat.st_mode) && !S_ISBLK(devstat.st_mode))
1263                 return (NULL);
1264
1265         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
1266         for (i = 0; i < mntsize; i++) {
1267                 statfsp = &mntbuf[i];
1268                 mntdevname = statfsp->f_mntfromname;
1269                 if (*mntdevname != '/') {
1270                         strcpy(device, _PATH_DEV);
1271                         strcat(device, mntdevname);
1272                         mntdevname = device;
1273                 }
1274                 if (stat(mntdevname, &mntdevstat) == 0 &&
1275                     mntdevstat.st_rdev == devstat.st_rdev)
1276                         return (statfsp);
1277         }
1278
1279         return (NULL);
1280 }
1281
1282 static const char *
1283 mountpoint_to_dev(const char *mountpoint)
1284 {
1285         struct statfs *mntbuf, *statfsp;
1286         struct fstab *fs;
1287         int i, mntsize;
1288
1289         /*
1290          * First check the mounted filesystems.
1291          */
1292         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
1293         for (i = 0; i < mntsize; i++) {
1294                 statfsp = &mntbuf[i];
1295
1296                 if (strcmp(statfsp->f_mntonname, mountpoint) == 0)
1297                         return (statfsp->f_mntfromname);
1298         }
1299
1300         /*
1301          * Check the fstab.
1302          */
1303         fs = getfsfile(mountpoint);
1304         if (fs != NULL)
1305                 return (fs->fs_spec);
1306
1307         return (NULL);
1308 }
1309
1310 static const char *
1311 getdev(const char *name)
1312 {
1313         static char device[MAXPATHLEN];
1314         const char *cp, *dev;
1315
1316         if (is_dev(name))
1317                 return (name);
1318
1319         cp = strrchr(name, '/');
1320         if (cp == NULL) {
1321                 snprintf(device, sizeof(device), "%s%s", _PATH_DEV, name);
1322                 if (is_dev(device))
1323                         return (device);
1324         }
1325
1326         dev = mountpoint_to_dev(name);
1327         if (dev != NULL && is_dev(dev))
1328                 return (dev);
1329
1330         return (NULL);
1331 }
1332
1333 /*
1334  * growfs(8) is a utility which allows to increase the size of an existing
1335  * ufs file system. Currently this can only be done on unmounted file system.
1336  * It recognizes some command line options to specify the new desired size,
1337  * and it does some basic checkings. The old file system size is determined
1338  * and after some more checks like we can really access the new last block
1339  * on the disk etc. we calculate the new parameters for the superblock. After
1340  * having done this we just call growfs() which will do the work.
1341  * We still have to provide support for snapshots. Therefore we first have to
1342  * understand what data structures are always replicated in the snapshot on
1343  * creation, for all other blocks we touch during our procedure, we have to
1344  * keep the old blocks unchanged somewhere available for the snapshots. If we
1345  * are lucky, then we only have to handle our blocks to be relocated in that
1346  * way.
1347  * Also we have to consider in what order we actually update the critical
1348  * data structures of the file system to make sure, that in case of a disaster
1349  * fsck(8) is still able to restore any lost data.
1350  * The foreseen last step then will be to provide for growing even mounted
1351  * file systems. There we have to extend the mount() system call to provide
1352  * userland access to the file system locking facility.
1353  */
1354 int
1355 main(int argc, char **argv)
1356 {
1357         DBG_FUNC("main")
1358         struct fs *fs;
1359         const char *device;
1360         const struct statfs *statfsp;
1361         uint64_t size = 0;
1362         off_t mediasize;
1363         int error, j, fsi, fso, ch, ret, Nflag = 0, yflag = 0;
1364         char *p, reply[5], oldsizebuf[6], newsizebuf[6];
1365         void *testbuf;
1366
1367         DBG_ENTER;
1368
1369         while ((ch = getopt(argc, argv, "Ns:vy")) != -1) {
1370                 switch(ch) {
1371                 case 'N':
1372                         Nflag = 1;
1373                         break;
1374                 case 's':
1375                         size = (off_t)strtoumax(optarg, &p, 0);
1376                         if (p == NULL || *p == '\0')
1377                                 size *= DEV_BSIZE;
1378                         else if (*p == 'b' || *p == 'B')
1379                                 ; /* do nothing */
1380                         else if (*p == 'k' || *p == 'K')
1381                                 size <<= 10;
1382                         else if (*p == 'm' || *p == 'M')
1383                                 size <<= 20;
1384                         else if (*p == 'g' || *p == 'G')
1385                                 size <<= 30;
1386                         else if (*p == 't' || *p == 'T') {
1387                                 size <<= 30;
1388                                 size <<= 10;
1389                         } else
1390                                 errx(1, "unknown suffix on -s argument");
1391                         break;
1392                 case 'v': /* for compatibility to newfs */
1393                         break;
1394                 case 'y':
1395                         yflag = 1;
1396                         break;
1397                 case '?':
1398                         /* FALLTHROUGH */
1399                 default:
1400                         usage();
1401                 }
1402         }
1403         argc -= optind;
1404         argv += optind;
1405
1406         if (argc != 1)
1407                 usage();
1408
1409         /*
1410          * Now try to guess the device name.
1411          */
1412         device = getdev(*argv);
1413         if (device == NULL)
1414                 errx(1, "cannot find special device for %s", *argv);
1415
1416         statfsp = dev_to_statfs(device);
1417
1418         fsi = open(device, O_RDONLY);
1419         if (fsi < 0)
1420                 err(1, "%s", device);
1421
1422         /*
1423          * Try to guess the slice size if not specified.
1424          */
1425         if (ioctl(fsi, DIOCGMEDIASIZE, &mediasize) == -1)
1426                 err(1,"DIOCGMEDIASIZE");
1427
1428         /*
1429          * Check if that partition is suitable for growing a file system.
1430          */
1431         if (mediasize < 1)
1432                 errx(1, "partition is unavailable");
1433
1434         /*
1435          * Read the current superblock, and take a backup.
1436          */
1437         if ((ret = sbget(fsi, &fs, -1)) != 0) {
1438                 switch (ret) {
1439                 case ENOENT:
1440                         errx(1, "superblock not recognized");
1441                 default:
1442                         errc(1, ret, "unable to read superblock");
1443                 }
1444         }
1445         /*
1446          * Check for filesystem that was unclean at mount time.
1447          */
1448         if ((fs->fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) != 0)
1449                 errx(1, "%s is not clean - run fsck.\n", *argv);
1450         memcpy(&osblock, fs, fs->fs_sbsize);
1451         free(fs);
1452         memcpy((void *)&fsun1, (void *)&fsun2, osblock.fs_sbsize);
1453
1454         DBG_OPEN("/tmp/growfs.debug"); /* already here we need a superblock */
1455         DBG_DUMP_FS(&sblock, "old sblock");
1456
1457         /*
1458          * Determine size to grow to. Default to the device size.
1459          */
1460         if (size == 0)
1461                 size = mediasize;
1462         else {
1463                 if (size > (uint64_t)mediasize) {
1464                         humanize_number(oldsizebuf, sizeof(oldsizebuf), size,
1465                             "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1466                         humanize_number(newsizebuf, sizeof(newsizebuf),
1467                             mediasize,
1468                             "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1469
1470                         errx(1, "requested size %s is larger "
1471                             "than the available %s", oldsizebuf, newsizebuf);
1472                 }
1473         }
1474
1475         /*
1476          * Make sure the new size is a multiple of fs_fsize; /dev/ufssuspend
1477          * only supports fragment-aligned IO requests.
1478          */
1479         size -= size % osblock.fs_fsize;
1480
1481         if (size <= (uint64_t)(osblock.fs_size * osblock.fs_fsize)) {
1482                 humanize_number(oldsizebuf, sizeof(oldsizebuf),
1483                     osblock.fs_size * osblock.fs_fsize,
1484                     "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1485                 humanize_number(newsizebuf, sizeof(newsizebuf), size,
1486                     "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1487
1488                 errx(1, "requested size %s is not larger than the current "
1489                    "filesystem size %s", newsizebuf, oldsizebuf);
1490         }
1491
1492         sblock.fs_size = dbtofsb(&osblock, size / DEV_BSIZE);
1493         sblock.fs_providersize = dbtofsb(&osblock, mediasize / DEV_BSIZE);
1494
1495         /*
1496          * Are we really growing?
1497          */
1498         if (osblock.fs_size >= sblock.fs_size) {
1499                 errx(1, "we are not growing (%jd->%jd)",
1500                     (intmax_t)osblock.fs_size, (intmax_t)sblock.fs_size);
1501         }
1502
1503         /*
1504          * Check if we find an active snapshot.
1505          */
1506         if (yflag == 0) {
1507                 for (j = 0; j < FSMAXSNAP; j++) {
1508                         if (sblock.fs_snapinum[j]) {
1509                                 errx(1, "active snapshot found in file system; "
1510                                     "please remove all snapshots before "
1511                                     "using growfs");
1512                         }
1513                         if (!sblock.fs_snapinum[j]) /* list is dense */
1514                                 break;
1515                 }
1516         }
1517
1518         if (yflag == 0 && Nflag == 0) {
1519                 if (statfsp != NULL && (statfsp->f_flags & MNT_RDONLY) == 0)
1520                         printf("Device is mounted read-write; resizing will "
1521                             "result in temporary write suspension for %s.\n",
1522                             statfsp->f_mntonname);
1523                 printf("It's strongly recommended to make a backup "
1524                     "before growing the file system.\n"
1525                     "OK to grow filesystem on %s", device);
1526                 if (statfsp != NULL)
1527                         printf(", mounted on %s,", statfsp->f_mntonname);
1528                 humanize_number(oldsizebuf, sizeof(oldsizebuf),
1529                     osblock.fs_size * osblock.fs_fsize,
1530                     "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1531                 humanize_number(newsizebuf, sizeof(newsizebuf),
1532                     sblock.fs_size * sblock.fs_fsize,
1533                     "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1534                 printf(" from %s to %s? [yes/no] ", oldsizebuf, newsizebuf);
1535                 fflush(stdout);
1536                 fgets(reply, (int)sizeof(reply), stdin);
1537                 if (strcasecmp(reply, "yes\n")){
1538                         printf("Response other than \"yes\"; aborting\n");
1539                         exit(0);
1540                 }
1541         }
1542
1543         /*
1544          * Try to access our device for writing.  If it's not mounted,
1545          * or mounted read-only, simply open it; otherwise, use UFS
1546          * suspension mechanism.
1547          */
1548         if (Nflag) {
1549                 fso = -1;
1550         } else {
1551                 if (statfsp != NULL && (statfsp->f_flags & MNT_RDONLY) == 0) {
1552                         fso = open(_PATH_UFSSUSPEND, O_RDWR);
1553                         if (fso == -1)
1554                                 err(1, "unable to open %s", _PATH_UFSSUSPEND);
1555                         error = ioctl(fso, UFSSUSPEND, &statfsp->f_fsid);
1556                         if (error != 0)
1557                                 err(1, "UFSSUSPEND");
1558                 } else {
1559                         fso = open(device, O_WRONLY);
1560                         if (fso < 0)
1561                                 err(1, "%s", device);
1562                 }
1563         }
1564
1565         /*
1566          * Try to access our new last block in the file system.
1567          */
1568         testbuf = malloc(sblock.fs_fsize);
1569         if (testbuf == NULL)
1570                 err(1, "malloc");
1571         rdfs((ufs2_daddr_t)((size - sblock.fs_fsize) / DEV_BSIZE),
1572             sblock.fs_fsize, testbuf, fsi);
1573         wtfs((ufs2_daddr_t)((size - sblock.fs_fsize) / DEV_BSIZE),
1574             sblock.fs_fsize, testbuf, fso, Nflag);
1575         free(testbuf);
1576
1577         /*
1578          * Now calculate new superblock values and check for reasonable
1579          * bound for new file system size:
1580          *     fs_size:    is derived from user input
1581          *     fs_dsize:   should get updated in the routines creating or
1582          *                 updating the cylinder groups on the fly
1583          *     fs_cstotal: should get updated in the routines creating or
1584          *                 updating the cylinder groups
1585          */
1586
1587         /*
1588          * Update the number of cylinders and cylinder groups in the file system.
1589          */
1590         if (sblock.fs_magic == FS_UFS1_MAGIC) {
1591                 sblock.fs_old_ncyl =
1592                     sblock.fs_size * sblock.fs_old_nspf / sblock.fs_old_spc;
1593                 if (sblock.fs_size * sblock.fs_old_nspf >
1594                     sblock.fs_old_ncyl * sblock.fs_old_spc)
1595                         sblock.fs_old_ncyl++;
1596         }
1597         sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
1598
1599         /*
1600          * Allocate last cylinder group only if there is enough room
1601          * for at least one data block.
1602          */
1603         if (sblock.fs_size % sblock.fs_fpg != 0 &&
1604             sblock.fs_size <= cgdmin(&sblock, sblock.fs_ncg - 1)) {
1605                 humanize_number(oldsizebuf, sizeof(oldsizebuf),
1606                     (sblock.fs_size % sblock.fs_fpg) * sblock.fs_fsize,
1607                     "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1608                 warnx("no room to allocate last cylinder group; "
1609                     "leaving %s unused", oldsizebuf);
1610                 sblock.fs_ncg--;
1611                 if (sblock.fs_magic == FS_UFS1_MAGIC)
1612                         sblock.fs_old_ncyl = sblock.fs_ncg * sblock.fs_old_cpg;
1613                 sblock.fs_size = sblock.fs_ncg * sblock.fs_fpg;
1614         }
1615
1616         /*
1617          * Update the space for the cylinder group summary information in the
1618          * respective cylinder group data area.
1619          */
1620         sblock.fs_cssize =
1621             fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
1622
1623         if (osblock.fs_size >= sblock.fs_size)
1624                 errx(1, "not enough new space");
1625
1626         DBG_PRINT0("sblock calculated\n");
1627
1628         /*
1629          * Ok, everything prepared, so now let's do the tricks.
1630          */
1631         growfs(fsi, fso, Nflag);
1632
1633         close(fsi);
1634         if (fso > -1) {
1635                 if (statfsp != NULL && (statfsp->f_flags & MNT_RDONLY) == 0) {
1636                         error = ioctl(fso, UFSRESUME);
1637                         if (error != 0)
1638                                 err(1, "UFSRESUME");
1639                 }
1640                 error = close(fso);
1641                 if (error != 0)
1642                         err(1, "close");
1643                 if (statfsp != NULL && (statfsp->f_flags & MNT_RDONLY) != 0)
1644                         mount_reload(statfsp);
1645         }
1646
1647         DBG_CLOSE;
1648
1649         DBG_LEAVE;
1650         return (0);
1651 }
1652
1653 /*
1654  * Dump a line of usage.
1655  */
1656 static void
1657 usage(void)
1658 {
1659         DBG_FUNC("usage")
1660
1661         DBG_ENTER;
1662
1663         fprintf(stderr, "usage: growfs [-Ny] [-s size] special | filesystem\n");
1664
1665         DBG_LEAVE;
1666         exit(1);
1667 }
1668
1669 /*
1670  * This updates most parameters and the bitmap related to cluster. We have to
1671  * assume that sblock, osblock, acg are set up.
1672  */
1673 static void
1674 updclst(int block)
1675 {
1676         DBG_FUNC("updclst")
1677         static int lcs = 0;
1678
1679         DBG_ENTER;
1680
1681         if (sblock.fs_contigsumsize < 1) /* no clustering */
1682                 return;
1683         /*
1684          * update cluster allocation map
1685          */
1686         setbit(cg_clustersfree(&acg), block);
1687
1688         /*
1689          * update cluster summary table
1690          */
1691         if (!lcs) {
1692                 /*
1693                  * calculate size for the trailing cluster
1694                  */
1695                 for (block--; lcs < sblock.fs_contigsumsize; block--, lcs++ ) {
1696                         if (isclr(cg_clustersfree(&acg), block))
1697                                 break;
1698                 }
1699         }
1700         if (lcs < sblock.fs_contigsumsize) {
1701                 if (lcs)
1702                         cg_clustersum(&acg)[lcs]--;
1703                 lcs++;
1704                 cg_clustersum(&acg)[lcs]++;
1705         }
1706
1707         DBG_LEAVE;
1708         return;
1709 }
1710
1711 static void
1712 mount_reload(const struct statfs *stfs)
1713 {
1714         char errmsg[255];
1715         struct iovec *iov;
1716         int iovlen;
1717
1718         iov = NULL;
1719         iovlen = 0;
1720         *errmsg = '\0';
1721         build_iovec(&iov, &iovlen, "fstype", __DECONST(char *, "ffs"), 4);
1722         build_iovec(&iov, &iovlen, "fspath", __DECONST(char *, stfs->f_mntonname), (size_t)-1);
1723         build_iovec(&iov, &iovlen, "errmsg", errmsg, sizeof(errmsg));
1724         build_iovec(&iov, &iovlen, "update", NULL, 0);
1725         build_iovec(&iov, &iovlen, "reload", NULL, 0);
1726
1727         if (nmount(iov, iovlen, stfs->f_flags) < 0) {
1728                 errmsg[sizeof(errmsg) - 1] = '\0';
1729                 err(9, "%s: cannot reload filesystem%s%s", stfs->f_mntonname,
1730                     *errmsg != '\0' ? ": " : "", errmsg);
1731         }
1732 }
1733
1734 /*
1735  * Calculate the check-hash of the cylinder group.
1736  */
1737 static void
1738 cgckhash(struct cg *cgp)
1739 {
1740
1741         if ((sblock.fs_metackhash & CK_CYLGRP) == 0)
1742                 return;
1743         cgp->cg_ckhash = 0;
1744         cgp->cg_ckhash = calculate_crc32c(~0L, (void *)cgp, sblock.fs_cgsize);
1745 }