]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sbin/growfs/growfs.c
MFC of 203763, 203764, 203768, 203769, 203770, 203782, and 203784.
[FreeBSD/stable/8.git] / sbin / growfs / growfs.c
1 /*
2  * Copyright (c) 2000 Christoph Herrmann, Thomas-Henning von Kamptz
3  * Copyright (c) 1980, 1989, 1993 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Christoph Herrmann and Thomas-Henning von Kamptz, Munich and Frankfurt.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgment:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors, as well as Christoph
21  *      Herrmann and Thomas-Henning von Kamptz.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * $TSHeader: src/sbin/growfs/growfs.c,v 1.5 2000/12/12 19:31:00 tomsoft Exp $
39  *
40  */
41
42 #ifndef lint
43 static const char copyright[] =
44 "@(#) Copyright (c) 2000 Christoph Herrmann, Thomas-Henning von Kamptz\n\
45 Copyright (c) 1980, 1989, 1993 The Regents of the University of California.\n\
46 All rights reserved.\n";
47 #endif /* not lint */
48
49 #include <sys/cdefs.h>
50 __FBSDID("$FreeBSD$");
51
52 /* ********************************************************** INCLUDES ***** */
53 #include <sys/param.h>
54 #include <sys/disklabel.h>
55 #include <sys/ioctl.h>
56 #include <sys/stat.h>
57 #include <sys/disk.h>
58
59 #include <stdio.h>
60 #include <paths.h>
61 #include <ctype.h>
62 #include <err.h>
63 #include <fcntl.h>
64 #include <limits.h>
65 #include <stdlib.h>
66 #include <stdint.h>
67 #include <string.h>
68 #include <time.h>
69 #include <unistd.h>
70 #include <ufs/ufs/dinode.h>
71 #include <ufs/ffs/fs.h>
72
73 #include "debug.h"
74
75 /* *************************************************** GLOBALS & TYPES ***** */
76 #ifdef FS_DEBUG
77 int     _dbg_lvl_ = (DL_INFO);  /* DL_TRC */
78 #endif /* FS_DEBUG */
79
80 static union {
81         struct fs       fs;
82         char    pad[SBLOCKSIZE];
83 } fsun1, fsun2;
84 #define sblock  fsun1.fs        /* the new superblock */
85 #define osblock fsun2.fs        /* the old superblock */
86
87 /*
88  * Possible superblock locations ordered from most to least likely.
89  */
90 static int sblock_try[] = SBLOCKSEARCH;
91 static ufs2_daddr_t sblockloc;
92
93 static union {
94         struct cg       cg;
95         char    pad[MAXBSIZE];
96 } cgun1, cgun2;
97 #define acg     cgun1.cg        /* a cylinder cgroup (new) */
98 #define aocg    cgun2.cg        /* an old cylinder group */
99
100 static char     ablk[MAXBSIZE]; /* a block */
101
102 static struct csum      *fscs;  /* cylinder summary */
103
104 union dinode {
105         struct ufs1_dinode dp1;
106         struct ufs2_dinode dp2;
107 };
108 #define DIP(dp, field) \
109         ((sblock.fs_magic == FS_UFS1_MAGIC) ? \
110         (uint32_t)(dp)->dp1.field : (dp)->dp2.field)
111 #define DIP_SET(dp, field, val) do { \
112         if (sblock.fs_magic == FS_UFS1_MAGIC) \
113                 (dp)->dp1.field = (val); \
114         else \
115                 (dp)->dp2.field = (val); \
116         } while (0)
117 static ufs2_daddr_t     inoblk;                 /* inode block address */
118 static char             inobuf[MAXBSIZE];       /* inode block */
119 ino_t                   maxino;                 /* last valid inode */
120 static int              unlabeled;     /* unlabeled partition, e.g. vinum volume etc. */
121
122 /*
123  * An array of elements of type struct gfs_bpp describes all blocks to
124  * be relocated in order to free the space needed for the cylinder group
125  * summary for all cylinder groups located in the first cylinder group.
126  */
127 struct gfs_bpp {
128         ufs2_daddr_t    old;            /* old block number */
129         ufs2_daddr_t    new;            /* new block number */
130 #define GFS_FL_FIRST    1
131 #define GFS_FL_LAST     2
132         unsigned int    flags;  /* special handling required */
133         int     found;          /* how many references were updated */
134 };
135
136 /* ******************************************************** PROTOTYPES ***** */
137 static void     growfs(int, int, unsigned int);
138 static void     rdfs(ufs2_daddr_t, size_t, void *, int);
139 static void     wtfs(ufs2_daddr_t, size_t, void *, int, unsigned int);
140 static ufs2_daddr_t alloc(void);
141 static int      charsperline(void);
142 static void     usage(void);
143 static int      isblock(struct fs *, unsigned char *, int);
144 static void     clrblock(struct fs *, unsigned char *, int);
145 static void     setblock(struct fs *, unsigned char *, int);
146 static void     initcg(int, time_t, int, unsigned int);
147 static void     updjcg(int, time_t, int, int, unsigned int);
148 static void     updcsloc(time_t, int, int, unsigned int);
149 static struct disklabel *get_disklabel(int);
150 static void     return_disklabel(int, struct disklabel *, unsigned int);
151 static union dinode *ginode(ino_t, int, int);
152 static void     frag_adjust(ufs2_daddr_t, int);
153 static int      cond_bl_upd(ufs2_daddr_t *, struct gfs_bpp *, int, int,
154                     unsigned int);
155 static void     updclst(int);
156 static void     updrefs(int, ino_t, struct gfs_bpp *, int, int, unsigned int);
157 static void     indirchk(ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t, ufs_lbn_t,
158                     struct gfs_bpp *, int, int, unsigned int);
159 static void     get_dev_size(int, int *);
160
161 /* ************************************************************ growfs ***** */
162 /*
163  * Here we actually start growing the file system. We basically read the
164  * cylinder summary from the first cylinder group as we want to update
165  * this on the fly during our various operations. First we handle the
166  * changes in the former last cylinder group. Afterwards we create all new
167  * cylinder groups.  Now we handle the cylinder group containing the
168  * cylinder summary which might result in a relocation of the whole
169  * structure.  In the end we write back the updated cylinder summary, the
170  * new superblock, and slightly patched versions of the super block
171  * copies.
172  */
173 static void
174 growfs(int fsi, int fso, unsigned int Nflag)
175 {
176         DBG_FUNC("growfs")
177         time_t  utime;
178         uint    cylno;
179         int     i, j, width;
180         char    tmpbuf[100];
181 #ifdef FSIRAND
182         static int      randinit=0;
183
184         DBG_ENTER;
185
186         if (!randinit) {
187                 randinit = 1;
188                 srandomdev();
189         }
190 #else /* not FSIRAND */
191
192         DBG_ENTER;
193
194 #endif /* FSIRAND */
195         time(&utime);
196
197         /*
198          * Get the cylinder summary into the memory.
199          */
200         fscs = (struct csum *)calloc((size_t)1, (size_t)sblock.fs_cssize);
201         if(fscs == NULL) {
202                 errx(1, "calloc failed");
203         }
204         for (i = 0; i < osblock.fs_cssize; i += osblock.fs_bsize) {
205                 rdfs(fsbtodb(&osblock, osblock.fs_csaddr +
206                     numfrags(&osblock, i)), (size_t)MIN(osblock.fs_cssize - i,
207                     osblock.fs_bsize), (void *)(((char *)fscs)+i), fsi);
208         }
209
210 #ifdef FS_DEBUG
211 {
212         struct csum     *dbg_csp;
213         int     dbg_csc;
214         char    dbg_line[80];
215
216         dbg_csp=fscs;
217         for(dbg_csc=0; dbg_csc<osblock.fs_ncg; dbg_csc++) {
218                 snprintf(dbg_line, sizeof(dbg_line),
219                     "%d. old csum in old location", dbg_csc);
220                 DBG_DUMP_CSUM(&osblock,
221                     dbg_line,
222                     dbg_csp++);
223         }
224 }
225 #endif /* FS_DEBUG */
226         DBG_PRINT0("fscs read\n");
227
228         /*
229          * Do all needed changes in the former last cylinder group.
230          */
231         updjcg(osblock.fs_ncg-1, utime, fsi, fso, Nflag);
232
233         /*
234          * Dump out summary information about file system.
235          */
236 #       define B2MBFACTOR (1 / (1024.0 * 1024.0))
237         printf("growfs: %.1fMB (%jd sectors) block size %d, fragment size %d\n",
238             (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
239             (intmax_t)fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize,
240             sblock.fs_fsize);
241         printf("\tusing %d cylinder groups of %.2fMB, %d blks, %d inodes.\n",
242             sblock.fs_ncg, (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
243             sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
244         if (sblock.fs_flags & FS_DOSOFTDEP)
245                 printf("\twith soft updates\n");
246 #       undef B2MBFACTOR
247
248         /*
249          * Now build the cylinders group blocks and
250          * then print out indices of cylinder groups.
251          */
252         printf("super-block backups (for fsck -b #) at:\n");
253         i = 0;
254         width = charsperline();
255
256         /*
257          * Iterate for only the new cylinder groups.
258          */
259         for (cylno = osblock.fs_ncg; cylno < sblock.fs_ncg; cylno++) {
260                 initcg(cylno, utime, fso, Nflag);
261                 j = sprintf(tmpbuf, " %jd%s",
262                     (intmax_t)fsbtodb(&sblock, cgsblock(&sblock, cylno)),
263                     cylno < (sblock.fs_ncg-1) ? "," : "" );
264                 if (i + j >= width) {
265                         printf("\n");
266                         i = 0;
267                 }
268                 i += j;
269                 printf("%s", tmpbuf);
270                 fflush(stdout);
271         }
272         printf("\n");
273
274         /*
275          * Do all needed changes in the first cylinder group.
276          * allocate blocks in new location
277          */
278         updcsloc(utime, fsi, fso, Nflag);
279
280         /*
281          * Now write the cylinder summary back to disk.
282          */
283         for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize) {
284                 wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
285                     (size_t)MIN(sblock.fs_cssize - i, sblock.fs_bsize),
286                     (void *)(((char *)fscs) + i), fso, Nflag);
287         }
288         DBG_PRINT0("fscs written\n");
289
290 #ifdef FS_DEBUG
291 {
292         struct csum     *dbg_csp;
293         int     dbg_csc;
294         char    dbg_line[80];
295
296         dbg_csp=fscs;
297         for(dbg_csc=0; dbg_csc<sblock.fs_ncg; dbg_csc++) {
298                 snprintf(dbg_line, sizeof(dbg_line),
299                     "%d. new csum in new location", dbg_csc);
300                 DBG_DUMP_CSUM(&sblock,
301                     dbg_line,
302                     dbg_csp++);
303         }
304 }
305 #endif /* FS_DEBUG */
306
307         /*
308          * Now write the new superblock back to disk.
309          */
310         sblock.fs_time = utime;
311         wtfs(sblockloc, (size_t)SBLOCKSIZE, (void *)&sblock, fso, Nflag);
312         DBG_PRINT0("sblock written\n");
313         DBG_DUMP_FS(&sblock,
314             "new initial sblock");
315
316         /*
317          * Clean up the dynamic fields in our superblock copies.
318          */
319         sblock.fs_fmod = 0;
320         sblock.fs_clean = 1;
321         sblock.fs_ronly = 0;
322         sblock.fs_cgrotor = 0;
323         sblock.fs_state = 0;
324         memset((void *)&sblock.fs_fsmnt, 0, sizeof(sblock.fs_fsmnt));
325         sblock.fs_flags &= FS_DOSOFTDEP;
326
327         /*
328          * XXX
329          * The following fields are currently distributed from the superblock
330          * to the copies:
331          *     fs_minfree
332          *     fs_rotdelay
333          *     fs_maxcontig
334          *     fs_maxbpg
335          *     fs_minfree,
336          *     fs_optim
337          *     fs_flags regarding SOFTPDATES
338          *
339          * We probably should rather change the summary for the cylinder group
340          * statistics here to the value of what would be in there, if the file
341          * system were created initially with the new size. Therefor we still
342          * need to find an easy way of calculating that.
343          * Possibly we can try to read the first superblock copy and apply the
344          * "diffed" stats between the old and new superblock by still copying
345          * certain parameters onto that.
346          */
347
348         /*
349          * Write out the duplicate super blocks.
350          */
351         for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
352                 wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)),
353                     (size_t)SBLOCKSIZE, (void *)&sblock, fso, Nflag);
354         }
355         DBG_PRINT0("sblock copies written\n");
356         DBG_DUMP_FS(&sblock,
357             "new other sblocks");
358
359         DBG_LEAVE;
360         return;
361 }
362
363 /* ************************************************************ initcg ***** */
364 /*
365  * This creates a new cylinder group structure, for more details please see
366  * the source of newfs(8), as this function is taken over almost unchanged.
367  * As this is never called for the first cylinder group, the special
368  * provisions for that case are removed here.
369  */
370 static void
371 initcg(int cylno, time_t utime, int fso, unsigned int Nflag)
372 {
373         DBG_FUNC("initcg")
374         static void *iobuf;
375         long blkno, start;
376         ufs2_daddr_t i, cbase, dmax;
377         struct ufs1_dinode *dp1;
378         struct csum *cs;
379         uint d, dupper, dlower;
380
381         if (iobuf == NULL && (iobuf = malloc(sblock.fs_bsize)) == NULL) {
382                 errx(37, "panic: cannot allocate I/O buffer");
383         }
384         /*
385          * Determine block bounds for cylinder group.
386          * Allow space for super block summary information in first
387          * cylinder group.
388          */
389         cbase = cgbase(&sblock, cylno);
390         dmax = cbase + sblock.fs_fpg;
391         if (dmax > sblock.fs_size)
392                 dmax = sblock.fs_size;
393         dlower = cgsblock(&sblock, cylno) - cbase;
394         dupper = cgdmin(&sblock, cylno) - cbase;
395         if (cylno == 0) /* XXX fscs may be relocated */
396                 dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
397         cs = &fscs[cylno];
398         memset(&acg, 0, sblock.fs_cgsize);
399         acg.cg_time = utime;
400         acg.cg_magic = CG_MAGIC;
401         acg.cg_cgx = cylno;
402         acg.cg_niblk = sblock.fs_ipg;
403         acg.cg_initediblk = sblock.fs_ipg;
404         acg.cg_ndblk = dmax - cbase;
405         if (sblock.fs_contigsumsize > 0)
406                 acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
407         start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
408         if (sblock.fs_magic == FS_UFS2_MAGIC) {
409                 acg.cg_iusedoff = start;
410         } else {
411                 acg.cg_old_ncyl = sblock.fs_old_cpg;
412                 acg.cg_old_time = acg.cg_time;
413                 acg.cg_time = 0;
414                 acg.cg_old_niblk = acg.cg_niblk;
415                 acg.cg_niblk = 0;
416                 acg.cg_initediblk = 0;
417                 acg.cg_old_btotoff = start;
418                 acg.cg_old_boff = acg.cg_old_btotoff +
419                     sblock.fs_old_cpg * sizeof(int32_t);
420                 acg.cg_iusedoff = acg.cg_old_boff +
421                     sblock.fs_old_cpg * sizeof(u_int16_t);
422         }
423         acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
424         acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
425         if (sblock.fs_contigsumsize > 0) {
426                 acg.cg_clustersumoff =
427                     roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
428                 acg.cg_clustersumoff -= sizeof(u_int32_t);
429                 acg.cg_clusteroff = acg.cg_clustersumoff +
430                     (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
431                 acg.cg_nextfreeoff = acg.cg_clusteroff +
432                     howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
433         }
434         if (acg.cg_nextfreeoff > (unsigned)sblock.fs_cgsize) {
435                 /*
436                  * This should never happen as we would have had that panic
437                  * already on file system creation
438                  */
439                 errx(37, "panic: cylinder group too big");
440         }
441         acg.cg_cs.cs_nifree += sblock.fs_ipg;
442         if (cylno == 0)
443                 for (i = 0; i < ROOTINO; i++) {
444                         setbit(cg_inosused(&acg), i);
445                         acg.cg_cs.cs_nifree--;
446                 }
447         /*
448          * XXX Newfs writes out two blocks of initialized inodes
449          *     unconditionally.  Should we check here to make sure that they
450          *     were actually written?
451          */
452         if (sblock.fs_magic == FS_UFS1_MAGIC) {
453                 bzero(iobuf, sblock.fs_bsize);
454                 for (i = 2 * sblock.fs_frag; i < sblock.fs_ipg / INOPF(&sblock);
455                      i += sblock.fs_frag) {
456                         dp1 = (struct ufs1_dinode *)iobuf;
457 #ifdef FSIRAND
458                         for (j = 0; j < INOPB(&sblock); j++) {
459                                 dp1->di_gen = random();
460                                 dp1++;
461                         }
462 #endif
463                         wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
464                             sblock.fs_bsize, iobuf, fso, Nflag);
465                 }
466         }
467         if (cylno > 0) {
468                 /*
469                  * In cylno 0, beginning space is reserved
470                  * for boot and super blocks.
471                  */
472                 for (d = 0; d < dlower; d += sblock.fs_frag) {
473                         blkno = d / sblock.fs_frag;
474                         setblock(&sblock, cg_blksfree(&acg), blkno);
475                         if (sblock.fs_contigsumsize > 0)
476                                 setbit(cg_clustersfree(&acg), blkno);
477                         acg.cg_cs.cs_nbfree++;
478                 }
479                 sblock.fs_dsize += dlower;
480         }
481         sblock.fs_dsize += acg.cg_ndblk - dupper;
482         if ((i = dupper % sblock.fs_frag)) {
483                 acg.cg_frsum[sblock.fs_frag - i]++;
484                 for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
485                         setbit(cg_blksfree(&acg), dupper);
486                         acg.cg_cs.cs_nffree++;
487                 }
488         }
489         for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
490              d += sblock.fs_frag) {
491                 blkno = d / sblock.fs_frag;
492                 setblock(&sblock, cg_blksfree(&acg), blkno);
493                 if (sblock.fs_contigsumsize > 0)
494                         setbit(cg_clustersfree(&acg), blkno);
495                 acg.cg_cs.cs_nbfree++;
496         }
497         if (d < acg.cg_ndblk) {
498                 acg.cg_frsum[acg.cg_ndblk - d]++;
499                 for (; d < acg.cg_ndblk; d++) {
500                         setbit(cg_blksfree(&acg), d);
501                         acg.cg_cs.cs_nffree++;
502                 }
503         }
504         if (sblock.fs_contigsumsize > 0) {
505                 int32_t *sump = cg_clustersum(&acg);
506                 u_char *mapp = cg_clustersfree(&acg);
507                 int map = *mapp++;
508                 int bit = 1;
509                 int run = 0;
510
511                 for (i = 0; i < acg.cg_nclusterblks; i++) {
512                         if ((map & bit) != 0)
513                                 run++;
514                         else if (run != 0) {
515                                 if (run > sblock.fs_contigsumsize)
516                                         run = sblock.fs_contigsumsize;
517                                 sump[run]++;
518                                 run = 0;
519                         }
520                         if ((i & (CHAR_BIT - 1)) != CHAR_BIT - 1)
521                                 bit <<= 1;
522                         else {
523                                 map = *mapp++;
524                                 bit = 1;
525                         }
526                 }
527                 if (run != 0) {
528                         if (run > sblock.fs_contigsumsize)
529                                 run = sblock.fs_contigsumsize;
530                         sump[run]++;
531                 }
532         }
533         sblock.fs_cstotal.cs_ndir += acg.cg_cs.cs_ndir;
534         sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
535         sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
536         sblock.fs_cstotal.cs_nifree += acg.cg_cs.cs_nifree;
537         *cs = acg.cg_cs;
538         wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
539                 sblock.fs_bsize, (char *)&acg, fso, Nflag);
540         DBG_DUMP_CG(&sblock,
541             "new cg",
542             &acg);
543
544         DBG_LEAVE;
545         return;
546 }
547
548 /* ******************************************************* frag_adjust ***** */
549 /*
550  * Here we add or subtract (sign +1/-1) the available fragments in a given
551  * block to or from the fragment statistics. By subtracting before and adding
552  * after an operation on the free frag map we can easy update the fragment
553  * statistic, which seems to be otherwise a rather complex operation.
554  */
555 static void
556 frag_adjust(ufs2_daddr_t frag, int sign)
557 {
558         DBG_FUNC("frag_adjust")
559         int fragsize;
560         int f;
561
562         DBG_ENTER;
563
564         fragsize=0;
565         /*
566          * Here frag only needs to point to any fragment in the block we want
567          * to examine.
568          */
569         for(f=rounddown(frag, sblock.fs_frag);
570             f<roundup(frag+1, sblock.fs_frag);
571             f++) {
572                 /*
573                  * Count contiguous free fragments.
574                  */
575                 if(isset(cg_blksfree(&acg), f)) {
576                         fragsize++;
577                 } else {
578                         if(fragsize && fragsize<sblock.fs_frag) {
579                                 /*
580                                  * We found something in between.
581                                  */
582                                 acg.cg_frsum[fragsize]+=sign;
583                                 DBG_PRINT2("frag_adjust [%d]+=%d\n",
584                                     fragsize,
585                                     sign);
586                         }
587                         fragsize=0;
588                 }
589         }
590         if(fragsize && fragsize<sblock.fs_frag) {
591                 /*
592                  * We found something.
593                  */
594                 acg.cg_frsum[fragsize]+=sign;
595                 DBG_PRINT2("frag_adjust [%d]+=%d\n",
596                     fragsize,
597                     sign);
598         }
599         DBG_PRINT2("frag_adjust [[%d]]+=%d\n",
600             fragsize,
601             sign);
602
603         DBG_LEAVE;
604         return;
605 }
606
607 /* ******************************************************* cond_bl_upd ***** */
608 /*
609  * Here we conditionally update a pointer to a fragment. We check for all
610  * relocated blocks if any of its fragments is referenced by the current
611  * field, and update the pointer to the respective fragment in our new
612  * block.  If we find a reference we write back the block immediately,
613  * as there is no easy way for our general block reading engine to figure
614  * out if a write back operation is needed.
615  */
616 static int
617 cond_bl_upd(ufs2_daddr_t *block, struct gfs_bpp *field, int fsi, int fso,
618     unsigned int Nflag)
619 {
620         DBG_FUNC("cond_bl_upd")
621         struct gfs_bpp *f;
622         ufs2_daddr_t src, dst;
623         int fragnum;
624         void *ibuf;
625
626         DBG_ENTER;
627
628         for (f = field; f->old != 0; f++) {
629                 src = *block;
630                 if (fragstoblks(&sblock, src) != f->old)
631                         continue;
632                 /*
633                  * The fragment is part of the block, so update.
634                  */
635                 dst = blkstofrags(&sblock, f->new);
636                 fragnum = fragnum(&sblock, src);
637                 *block = dst + fragnum;
638                 f->found++;
639                 DBG_PRINT3("scg (%jd->%jd)[%d] reference updated\n",
640                     (intmax_t)f->old,
641                     (intmax_t)f->new,
642                     fragnum);
643
644                 /*
645                  * Copy the block back immediately.
646                  *
647                  * XXX  If src is is from an indirect block we have
648                  *      to implement copy on write here in case of
649                  *      active snapshots.
650                  */
651                 ibuf = malloc(sblock.fs_bsize);
652                 if (!ibuf)
653                         errx(1, "malloc failed");
654                 src -= fragnum;
655                 rdfs(fsbtodb(&sblock, src), (size_t)sblock.fs_bsize, ibuf, fsi);
656                 wtfs(dst, (size_t)sblock.fs_bsize, ibuf, fso, Nflag);
657                 free(ibuf);
658                 /*
659                  * The same block can't be found again in this loop.
660                  */
661                 return (1);
662         }
663
664         DBG_LEAVE;
665         return (0);
666 }
667
668 /* ************************************************************ updjcg ***** */
669 /*
670  * Here we do all needed work for the former last cylinder group. It has to be
671  * changed in any case, even if the file system ended exactly on the end of
672  * this group, as there is some slightly inconsistent handling of the number
673  * of cylinders in the cylinder group. We start again by reading the cylinder
674  * group from disk. If the last block was not fully available, we first handle
675  * the missing fragments, then we handle all new full blocks in that file
676  * system and finally we handle the new last fragmented block in the file
677  * system.  We again have to handle the fragment statistics rotational layout
678  * tables and cluster summary during all those operations.
679  */
680 static void
681 updjcg(int cylno, time_t utime, int fsi, int fso, unsigned int Nflag)
682 {
683         DBG_FUNC("updjcg")
684         ufs2_daddr_t    cbase, dmax, dupper;
685         struct csum     *cs;
686         int     i,k;
687         int     j=0;
688
689         DBG_ENTER;
690
691         /*
692          * Read the former last (joining) cylinder group from disk, and make
693          * a copy.
694          */
695         rdfs(fsbtodb(&osblock, cgtod(&osblock, cylno)),
696             (size_t)osblock.fs_cgsize, (void *)&aocg, fsi);
697         DBG_PRINT0("jcg read\n");
698         DBG_DUMP_CG(&sblock,
699             "old joining cg",
700             &aocg);
701
702         memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
703
704         /*
705          * If the cylinder group had already its new final size almost
706          * nothing is to be done ... except:
707          * For some reason the value of cg_ncyl in the last cylinder group has
708          * to be zero instead of fs_cpg. As this is now no longer the last
709          * cylinder group we have to change that value now to fs_cpg.
710          */
711
712         if(cgbase(&osblock, cylno+1) == osblock.fs_size) {
713                 if (sblock.fs_magic == FS_UFS1_MAGIC)
714                         acg.cg_old_ncyl=sblock.fs_old_cpg;
715
716                 wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
717                     (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
718                 DBG_PRINT0("jcg written\n");
719                 DBG_DUMP_CG(&sblock,
720                     "new joining cg",
721                     &acg);
722
723                 DBG_LEAVE;
724                 return;
725         }
726
727         /*
728          * Set up some variables needed later.
729          */
730         cbase = cgbase(&sblock, cylno);
731         dmax = cbase + sblock.fs_fpg;
732         if (dmax > sblock.fs_size)
733                 dmax = sblock.fs_size;
734         dupper = cgdmin(&sblock, cylno) - cbase;
735         if (cylno == 0) { /* XXX fscs may be relocated */
736                 dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
737         }
738
739         /*
740          * Set pointer to the cylinder summary for our cylinder group.
741          */
742         cs = fscs + cylno;
743
744         /*
745          * Touch the cylinder group, update all fields in the cylinder group as
746          * needed, update the free space in the superblock.
747          */
748         acg.cg_time = utime;
749         if ((unsigned)cylno == sblock.fs_ncg - 1) {
750                 /*
751                  * This is still the last cylinder group.
752                  */
753                 if (sblock.fs_magic == FS_UFS1_MAGIC)
754                         acg.cg_old_ncyl =
755                             sblock.fs_old_ncyl % sblock.fs_old_cpg;
756         } else {
757                 acg.cg_old_ncyl = sblock.fs_old_cpg;
758         }
759         DBG_PRINT2("jcg dbg: %d %u",
760             cylno,
761             sblock.fs_ncg);
762 #ifdef FS_DEBUG
763         if (sblock.fs_magic == FS_UFS1_MAGIC)
764                 DBG_PRINT2("%d %u",
765                     acg.cg_old_ncyl,
766                     sblock.fs_old_cpg);
767 #endif
768         DBG_PRINT0("\n");
769         acg.cg_ndblk = dmax - cbase;
770         sblock.fs_dsize += acg.cg_ndblk-aocg.cg_ndblk;
771         if (sblock.fs_contigsumsize > 0) {
772                 acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
773         }
774
775         /*
776          * Now we have to update the free fragment bitmap for our new free
777          * space.  There again we have to handle the fragmentation and also
778          * the rotational layout tables and the cluster summary.  This is
779          * also done per fragment for the first new block if the old file
780          * system end was not on a block boundary, per fragment for the new
781          * last block if the new file system end is not on a block boundary,
782          * and per block for all space in between.
783          *
784          * Handle the first new block here if it was partially available
785          * before.
786          */
787         if(osblock.fs_size % sblock.fs_frag) {
788                 if(roundup(osblock.fs_size, sblock.fs_frag)<=sblock.fs_size) {
789                         /*
790                          * The new space is enough to fill at least this
791                          * block
792                          */
793                         j=0;
794                         for(i=roundup(osblock.fs_size-cbase, sblock.fs_frag)-1;
795                             i>=osblock.fs_size-cbase;
796                             i--) {
797                                 setbit(cg_blksfree(&acg), i);
798                                 acg.cg_cs.cs_nffree++;
799                                 j++;
800                         }
801
802                         /*
803                          * Check if the fragment just created could join an
804                          * already existing fragment at the former end of the
805                          * file system.
806                          */
807                         if(isblock(&sblock, cg_blksfree(&acg),
808                             ((osblock.fs_size - cgbase(&sblock, cylno))/
809                             sblock.fs_frag))) {
810                                 /*
811                                  * The block is now completely available.
812                                  */
813                                 DBG_PRINT0("block was\n");
814                                 acg.cg_frsum[osblock.fs_size%sblock.fs_frag]--;
815                                 acg.cg_cs.cs_nbfree++;
816                                 acg.cg_cs.cs_nffree-=sblock.fs_frag;
817                                 k=rounddown(osblock.fs_size-cbase,
818                                     sblock.fs_frag);
819                                 updclst((osblock.fs_size-cbase)/sblock.fs_frag);
820                         } else {
821                                 /*
822                                  * Lets rejoin a possible partially growed
823                                  * fragment.
824                                  */
825                                 k=0;
826                                 while(isset(cg_blksfree(&acg), i) &&
827                                     (i>=rounddown(osblock.fs_size-cbase,
828                                     sblock.fs_frag))) {
829                                         i--;
830                                         k++;
831                                 }
832                                 if(k) {
833                                         acg.cg_frsum[k]--;
834                                 }
835                                 acg.cg_frsum[k+j]++;
836                         }
837                 } else {
838                         /*
839                          * We only grow by some fragments within this last
840                          * block.
841                          */
842                         for(i=sblock.fs_size-cbase-1;
843                                 i>=osblock.fs_size-cbase;
844                                 i--) {
845                                 setbit(cg_blksfree(&acg), i);
846                                 acg.cg_cs.cs_nffree++;
847                                 j++;
848                         }
849                         /*
850                          * Lets rejoin a possible partially growed fragment.
851                          */
852                         k=0;
853                         while(isset(cg_blksfree(&acg), i) &&
854                             (i>=rounddown(osblock.fs_size-cbase,
855                             sblock.fs_frag))) {
856                                 i--;
857                                 k++;
858                         }
859                         if(k) {
860                                 acg.cg_frsum[k]--;
861                         }
862                         acg.cg_frsum[k+j]++;
863                 }
864         }
865
866         /*
867          * Handle all new complete blocks here.
868          */
869         for(i=roundup(osblock.fs_size-cbase, sblock.fs_frag);
870             i+sblock.fs_frag<=dmax-cbase;       /* XXX <= or only < ? */
871             i+=sblock.fs_frag) {
872                 j = i / sblock.fs_frag;
873                 setblock(&sblock, cg_blksfree(&acg), j);
874                 updclst(j);
875                 acg.cg_cs.cs_nbfree++;
876         }
877
878         /*
879          * Handle the last new block if there are stll some new fragments left.
880          * Here we don't have to bother about the cluster summary or the even
881          * the rotational layout table.
882          */
883         if (i < (dmax - cbase)) {
884                 acg.cg_frsum[dmax - cbase - i]++;
885                 for (; i < dmax - cbase; i++) {
886                         setbit(cg_blksfree(&acg), i);
887                         acg.cg_cs.cs_nffree++;
888                 }
889         }
890
891         sblock.fs_cstotal.cs_nffree +=
892             (acg.cg_cs.cs_nffree - aocg.cg_cs.cs_nffree);
893         sblock.fs_cstotal.cs_nbfree +=
894             (acg.cg_cs.cs_nbfree - aocg.cg_cs.cs_nbfree);
895         /*
896          * The following statistics are not changed here:
897          *     sblock.fs_cstotal.cs_ndir
898          *     sblock.fs_cstotal.cs_nifree
899          * As the statistics for this cylinder group are ready, copy it to
900          * the summary information array.
901          */
902         *cs = acg.cg_cs;
903
904         /*
905          * Write the updated "joining" cylinder group back to disk.
906          */
907         wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)), (size_t)sblock.fs_cgsize,
908             (void *)&acg, fso, Nflag);
909         DBG_PRINT0("jcg written\n");
910         DBG_DUMP_CG(&sblock,
911             "new joining cg",
912             &acg);
913
914         DBG_LEAVE;
915         return;
916 }
917
918 /* ********************************************************** updcsloc ***** */
919 /*
920  * Here we update the location of the cylinder summary. We have two possible
921  * ways of growing the cylinder summary.
922  * (1)  We can try to grow the summary in the current location, and relocate
923  *      possibly used blocks within the current cylinder group.
924  * (2)  Alternatively we can relocate the whole cylinder summary to the first
925  *      new completely empty cylinder group. Once the cylinder summary is no
926  *      longer in the beginning of the first cylinder group you should never
927  *      use a version of fsck which is not aware of the possibility to have
928  *      this structure in a non standard place.
929  * Option (1) is considered to be less intrusive to the structure of the file-
930  * system. So we try to stick to that whenever possible. If there is not enough
931  * space in the cylinder group containing the cylinder summary we have to use
932  * method (2). In case of active snapshots in the file system we probably can
933  * completely avoid implementing copy on write if we stick to method (2) only.
934  */
935 static void
936 updcsloc(time_t utime, int fsi, int fso, unsigned int Nflag)
937 {
938         DBG_FUNC("updcsloc")
939         struct csum     *cs;
940         int     ocscg, ncscg;
941         int     blocks;
942         ufs2_daddr_t    cbase, dupper, odupper, d, f, g;
943         int     ind, inc;
944         uint    cylno;
945         struct gfs_bpp  *bp;
946         int     i, l;
947         int     lcs=0;
948         int     block;
949
950         DBG_ENTER;
951
952         if(howmany(sblock.fs_cssize, sblock.fs_fsize) ==
953             howmany(osblock.fs_cssize, osblock.fs_fsize)) {
954                 /*
955                  * No new fragment needed.
956                  */
957                 DBG_LEAVE;
958                 return;
959         }
960         ocscg=dtog(&osblock, osblock.fs_csaddr);
961         cs=fscs+ocscg;
962         blocks = 1+howmany(sblock.fs_cssize, sblock.fs_bsize)-
963             howmany(osblock.fs_cssize, osblock.fs_bsize);
964
965         /*
966          * Read original cylinder group from disk, and make a copy.
967          * XXX  If Nflag is set in some very rare cases we now miss
968          *      some changes done in updjcg by reading the unmodified
969          *      block from disk.
970          */
971         rdfs(fsbtodb(&osblock, cgtod(&osblock, ocscg)),
972             (size_t)osblock.fs_cgsize, (void *)&aocg, fsi);
973         DBG_PRINT0("oscg read\n");
974         DBG_DUMP_CG(&sblock,
975             "old summary cg",
976             &aocg);
977
978         memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
979
980         /*
981          * Touch the cylinder group, set up local variables needed later
982          * and update the superblock.
983          */
984         acg.cg_time = utime;
985
986         /*
987          * XXX  In the case of having active snapshots we may need much more
988          *      blocks for the copy on write. We need each block twice, and
989          *      also up to 8*3 blocks for indirect blocks for all possible
990          *      references.
991          */
992         if(/*((int)sblock.fs_time&0x3)>0||*/ cs->cs_nbfree < blocks) {
993                 /*
994                  * There is not enough space in the old cylinder group to
995                  * relocate all blocks as needed, so we relocate the whole
996                  * cylinder group summary to a new group. We try to use the
997                  * first complete new cylinder group just created. Within the
998                  * cylinder group we align the area immediately after the
999                  * cylinder group information location in order to be as
1000                  * close as possible to the original implementation of ffs.
1001                  *
1002                  * First we have to make sure we'll find enough space in the
1003                  * new cylinder group. If not, then we currently give up.
1004                  * We start with freeing everything which was used by the
1005                  * fragments of the old cylinder summary in the current group.
1006                  * Now we write back the group meta data, read in the needed
1007                  * meta data from the new cylinder group, and start allocating
1008                  * within that group. Here we can assume, the group to be
1009                  * completely empty. Which makes the handling of fragments and
1010                  * clusters a lot easier.
1011                  */
1012                 DBG_TRC;
1013                 if(sblock.fs_ncg-osblock.fs_ncg < 2) {
1014                         errx(2, "panic: not enough space");
1015                 }
1016
1017                 /*
1018                  * Point "d" to the first fragment not used by the cylinder
1019                  * summary.
1020                  */
1021                 d=osblock.fs_csaddr+(osblock.fs_cssize/osblock.fs_fsize);
1022
1023                 /*
1024                  * Set up last cluster size ("lcs") already here. Calculate
1025                  * the size for the trailing cluster just behind where "d"
1026                  * points to.
1027                  */
1028                 if(sblock.fs_contigsumsize > 0) {
1029                         for(block=howmany(d%sblock.fs_fpg, sblock.fs_frag),
1030                             lcs=0; lcs<sblock.fs_contigsumsize;
1031                             block++, lcs++) {
1032                                 if(isclr(cg_clustersfree(&acg), block)){
1033                                         break;
1034                                 }
1035                         }
1036                 }
1037
1038                 /*
1039                  * Point "d" to the last frag used by the cylinder summary.
1040                  */
1041                 d--;
1042
1043                 DBG_PRINT1("d=%jd\n",
1044                     (intmax_t)d);
1045                 if((d+1)%sblock.fs_frag) {
1046                         /*
1047                          * The end of the cylinder summary is not a complete
1048                          * block.
1049                          */
1050                         DBG_TRC;
1051                         frag_adjust(d%sblock.fs_fpg, -1);
1052                         for(; (d+1)%sblock.fs_frag; d--) {
1053                                 DBG_PRINT1("d=%jd\n",
1054                                     (intmax_t)d);
1055                                 setbit(cg_blksfree(&acg), d%sblock.fs_fpg);
1056                                 acg.cg_cs.cs_nffree++;
1057                                 sblock.fs_cstotal.cs_nffree++;
1058                         }
1059                         /*
1060                          * Point "d" to the last fragment of the last
1061                          * (incomplete) block of the cylinder summary.
1062                          */
1063                         d++;
1064                         frag_adjust(d%sblock.fs_fpg, 1);
1065
1066                         if(isblock(&sblock, cg_blksfree(&acg),
1067                             (d%sblock.fs_fpg)/sblock.fs_frag)) {
1068                                 DBG_PRINT1("d=%jd\n", (intmax_t)d);
1069                                 acg.cg_cs.cs_nffree-=sblock.fs_frag;
1070                                 acg.cg_cs.cs_nbfree++;
1071                                 sblock.fs_cstotal.cs_nffree-=sblock.fs_frag;
1072                                 sblock.fs_cstotal.cs_nbfree++;
1073                                 if(sblock.fs_contigsumsize > 0) {
1074                                         setbit(cg_clustersfree(&acg),
1075                                             (d%sblock.fs_fpg)/sblock.fs_frag);
1076                                         if(lcs < sblock.fs_contigsumsize) {
1077                                                 if(lcs) {
1078                                                         cg_clustersum(&acg)
1079                                                             [lcs]--;
1080                                                 }
1081                                                 lcs++;
1082                                                 cg_clustersum(&acg)[lcs]++;
1083                                         }
1084                                 }
1085                         }
1086                         /*
1087                          * Point "d" to the first fragment of the block before
1088                          * the last incomplete block.
1089                          */
1090                         d--;
1091                 }
1092
1093                 DBG_PRINT1("d=%jd\n", (intmax_t)d);
1094                 for(d=rounddown(d, sblock.fs_frag); d >= osblock.fs_csaddr;
1095                     d-=sblock.fs_frag) {
1096                         DBG_TRC;
1097                         DBG_PRINT1("d=%jd\n", (intmax_t)d);
1098                         setblock(&sblock, cg_blksfree(&acg),
1099                             (d%sblock.fs_fpg)/sblock.fs_frag);
1100                         acg.cg_cs.cs_nbfree++;
1101                         sblock.fs_cstotal.cs_nbfree++;
1102                         if(sblock.fs_contigsumsize > 0) {
1103                                 setbit(cg_clustersfree(&acg),
1104                                     (d%sblock.fs_fpg)/sblock.fs_frag);
1105                                 /*
1106                                  * The last cluster size is already set up.
1107                                  */
1108                                 if(lcs < sblock.fs_contigsumsize) {
1109                                         if(lcs) {
1110                                                 cg_clustersum(&acg)[lcs]--;
1111                                         }
1112                                         lcs++;
1113                                         cg_clustersum(&acg)[lcs]++;
1114                                 }
1115                         }
1116                 }
1117                 *cs = acg.cg_cs;
1118
1119                 /*
1120                  * Now write the former cylinder group containing the cylinder
1121                  * summary back to disk.
1122                  */
1123                 wtfs(fsbtodb(&sblock, cgtod(&sblock, ocscg)),
1124                     (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
1125                 DBG_PRINT0("oscg written\n");
1126                 DBG_DUMP_CG(&sblock,
1127                     "old summary cg",
1128                     &acg);
1129
1130                 /*
1131                  * Find the beginning of the new cylinder group containing the
1132                  * cylinder summary.
1133                  */
1134                 sblock.fs_csaddr=cgdmin(&sblock, osblock.fs_ncg);
1135                 ncscg=dtog(&sblock, sblock.fs_csaddr);
1136                 cs=fscs+ncscg;
1137
1138
1139                 /*
1140                  * If Nflag is specified, we would now read random data instead
1141                  * of an empty cg structure from disk. So we can't simulate that
1142                  * part for now.
1143                  */
1144                 if(Nflag) {
1145                         DBG_PRINT0("nscg update skipped\n");
1146                         DBG_LEAVE;
1147                         return;
1148                 }
1149
1150                 /*
1151                  * Read the future cylinder group containing the cylinder
1152                  * summary from disk, and make a copy.
1153                  */
1154                 rdfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
1155                     (size_t)sblock.fs_cgsize, (void *)&aocg, fsi);
1156                 DBG_PRINT0("nscg read\n");
1157                 DBG_DUMP_CG(&sblock,
1158                     "new summary cg",
1159                     &aocg);
1160
1161                 memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
1162
1163                 /*
1164                  * Allocate all complete blocks used by the new cylinder
1165                  * summary.
1166                  */
1167                 for(d=sblock.fs_csaddr; d+sblock.fs_frag <=
1168                     sblock.fs_csaddr+(sblock.fs_cssize/sblock.fs_fsize);
1169                     d+=sblock.fs_frag) {
1170                         clrblock(&sblock, cg_blksfree(&acg),
1171                             (d%sblock.fs_fpg)/sblock.fs_frag);
1172                         acg.cg_cs.cs_nbfree--;
1173                         sblock.fs_cstotal.cs_nbfree--;
1174                         if(sblock.fs_contigsumsize > 0) {
1175                                 clrbit(cg_clustersfree(&acg),
1176                                     (d%sblock.fs_fpg)/sblock.fs_frag);
1177                         }
1178                 }
1179
1180                 /*
1181                  * Allocate all fragments used by the cylinder summary in the
1182                  * last block.
1183                  */
1184                 if(d<sblock.fs_csaddr+(sblock.fs_cssize/sblock.fs_fsize)) {
1185                         for(; d-sblock.fs_csaddr<
1186                             sblock.fs_cssize/sblock.fs_fsize;
1187                             d++) {
1188                                 clrbit(cg_blksfree(&acg), d%sblock.fs_fpg);
1189                                 acg.cg_cs.cs_nffree--;
1190                                 sblock.fs_cstotal.cs_nffree--;
1191                         }
1192                         acg.cg_cs.cs_nbfree--;
1193                         acg.cg_cs.cs_nffree+=sblock.fs_frag;
1194                         sblock.fs_cstotal.cs_nbfree--;
1195                         sblock.fs_cstotal.cs_nffree+=sblock.fs_frag;
1196                         if(sblock.fs_contigsumsize > 0) {
1197                                 clrbit(cg_clustersfree(&acg),
1198                                     (d%sblock.fs_fpg)/sblock.fs_frag);
1199                         }
1200
1201                         frag_adjust(d%sblock.fs_fpg, +1);
1202                 }
1203                 /*
1204                  * XXX  Handle the cluster statistics here in the case this
1205                  *      cylinder group is now almost full, and the remaining
1206                  *      space is less then the maximum cluster size. This is
1207                  *      probably not needed, as you would hardly find a file
1208                  *      system which has only MAXCSBUFS+FS_MAXCONTIG of free
1209                  *      space right behind the cylinder group information in
1210                  *      any new cylinder group.
1211                  */
1212
1213                 /*
1214                  * Update our statistics in the cylinder summary.
1215                  */
1216                 *cs = acg.cg_cs;
1217
1218                 /*
1219                  * Write the new cylinder group containing the cylinder summary
1220                  * back to disk.
1221                  */
1222                 wtfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
1223                     (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
1224                 DBG_PRINT0("nscg written\n");
1225                 DBG_DUMP_CG(&sblock,
1226                     "new summary cg",
1227                     &acg);
1228
1229                 DBG_LEAVE;
1230                 return;
1231         }
1232         /*
1233          * We have got enough of space in the current cylinder group, so we
1234          * can relocate just a few blocks, and let the summary information
1235          * grow in place where it is right now.
1236          */
1237         DBG_TRC;
1238
1239         cbase = cgbase(&osblock, ocscg);        /* old and new are equal */
1240         dupper = sblock.fs_csaddr - cbase +
1241             howmany(sblock.fs_cssize, sblock.fs_fsize);
1242         odupper = osblock.fs_csaddr - cbase +
1243             howmany(osblock.fs_cssize, osblock.fs_fsize);
1244
1245         sblock.fs_dsize -= dupper-odupper;
1246
1247         /*
1248          * Allocate the space for the array of blocks to be relocated.
1249          */
1250         bp=(struct gfs_bpp *)malloc(((dupper-odupper)/sblock.fs_frag+2)*
1251             sizeof(struct gfs_bpp));
1252         if(bp == NULL) {
1253                 errx(1, "malloc failed");
1254         }
1255         memset((char *)bp, 0, ((dupper-odupper)/sblock.fs_frag+2)*
1256             sizeof(struct gfs_bpp));
1257
1258         /*
1259          * Lock all new frags needed for the cylinder group summary. This is
1260          * done per fragment in the first and last block of the new required
1261          * area, and per block for all other blocks.
1262          *
1263          * Handle the first new block here (but only if some fragments where
1264          * already used for the cylinder summary).
1265          */
1266         ind=0;
1267         frag_adjust(odupper, -1);
1268         for(d=odupper; ((d<dupper)&&(d%sblock.fs_frag)); d++) {
1269                 DBG_PRINT1("scg first frag check loop d=%jd\n",
1270                     (intmax_t)d);
1271                 if(isclr(cg_blksfree(&acg), d)) {
1272                         if (!ind) {
1273                                 bp[ind].old=d/sblock.fs_frag;
1274                                 bp[ind].flags|=GFS_FL_FIRST;
1275                                 if(roundup(d, sblock.fs_frag) >= dupper) {
1276                                         bp[ind].flags|=GFS_FL_LAST;
1277                                 }
1278                                 ind++;
1279                         }
1280                 } else {
1281                         clrbit(cg_blksfree(&acg), d);
1282                         acg.cg_cs.cs_nffree--;
1283                         sblock.fs_cstotal.cs_nffree--;
1284                 }
1285                 /*
1286                  * No cluster handling is needed here, as there was at least
1287                  * one fragment in use by the cylinder summary in the old
1288                  * file system.
1289                  * No block-free counter handling here as this block was not
1290                  * a free block.
1291                  */
1292         }
1293         frag_adjust(odupper, 1);
1294
1295         /*
1296          * Handle all needed complete blocks here.
1297          */
1298         for(; d+sblock.fs_frag<=dupper; d+=sblock.fs_frag) {
1299                 DBG_PRINT1("scg block check loop d=%jd\n",
1300                     (intmax_t)d);
1301                 if(!isblock(&sblock, cg_blksfree(&acg), d/sblock.fs_frag)) {
1302                         for(f=d; f<d+sblock.fs_frag; f++) {
1303                                 if(isset(cg_blksfree(&aocg), f)) {
1304                                         acg.cg_cs.cs_nffree--;
1305                                         sblock.fs_cstotal.cs_nffree--;
1306                                 }
1307                         }
1308                         clrblock(&sblock, cg_blksfree(&acg), d/sblock.fs_frag);
1309                         bp[ind].old=d/sblock.fs_frag;
1310                         ind++;
1311                 } else {
1312                         clrblock(&sblock, cg_blksfree(&acg), d/sblock.fs_frag);
1313                         acg.cg_cs.cs_nbfree--;
1314                         sblock.fs_cstotal.cs_nbfree--;
1315                         if(sblock.fs_contigsumsize > 0) {
1316                                 clrbit(cg_clustersfree(&acg), d/sblock.fs_frag);
1317                                 for(lcs=0, l=(d/sblock.fs_frag)+1;
1318                                     lcs<sblock.fs_contigsumsize;
1319                                     l++, lcs++ ) {
1320                                         if(isclr(cg_clustersfree(&acg),l)){
1321                                                 break;
1322                                         }
1323                                 }
1324                                 if(lcs < sblock.fs_contigsumsize) {
1325                                         cg_clustersum(&acg)[lcs+1]--;
1326                                         if(lcs) {
1327                                                 cg_clustersum(&acg)[lcs]++;
1328                                         }
1329                                 }
1330                         }
1331                 }
1332                 /*
1333                  * No fragment counter handling is needed here, as this finally
1334                  * doesn't change after the relocation.
1335                  */
1336         }
1337
1338         /*
1339          * Handle all fragments needed in the last new affected block.
1340          */
1341         if(d<dupper) {
1342                 frag_adjust(dupper-1, -1);
1343
1344                 if(isblock(&sblock, cg_blksfree(&acg), d/sblock.fs_frag)) {
1345                         acg.cg_cs.cs_nbfree--;
1346                         sblock.fs_cstotal.cs_nbfree--;
1347                         acg.cg_cs.cs_nffree+=sblock.fs_frag;
1348                         sblock.fs_cstotal.cs_nffree+=sblock.fs_frag;
1349                         if(sblock.fs_contigsumsize > 0) {
1350                                 clrbit(cg_clustersfree(&acg), d/sblock.fs_frag);
1351                                 for(lcs=0, l=(d/sblock.fs_frag)+1;
1352                                     lcs<sblock.fs_contigsumsize;
1353                                     l++, lcs++ ) {
1354                                         if(isclr(cg_clustersfree(&acg),l)){
1355                                                 break;
1356                                         }
1357                                 }
1358                                 if(lcs < sblock.fs_contigsumsize) {
1359                                         cg_clustersum(&acg)[lcs+1]--;
1360                                         if(lcs) {
1361                                                 cg_clustersum(&acg)[lcs]++;
1362                                         }
1363                                 }
1364                         }
1365                 }
1366
1367                 for(; d<dupper; d++) {
1368                         DBG_PRINT1("scg second frag check loop d=%jd\n",
1369                             (intmax_t)d);
1370                         if(isclr(cg_blksfree(&acg), d)) {
1371                                 bp[ind].old=d/sblock.fs_frag;
1372                                 bp[ind].flags|=GFS_FL_LAST;
1373                         } else {
1374                                 clrbit(cg_blksfree(&acg), d);
1375                                 acg.cg_cs.cs_nffree--;
1376                                 sblock.fs_cstotal.cs_nffree--;
1377                         }
1378                 }
1379                 if(bp[ind].flags & GFS_FL_LAST) { /* we have to advance here */
1380                         ind++;
1381                 }
1382                 frag_adjust(dupper-1, 1);
1383         }
1384
1385         /*
1386          * If we found a block to relocate just do so.
1387          */
1388         if(ind) {
1389                 for(i=0; i<ind; i++) {
1390                         if(!bp[i].old) { /* no more blocks listed */
1391                                 /*
1392                                  * XXX  A relative blocknumber should not be
1393                                  *      zero, which is not explicitly
1394                                  *      guaranteed by our code.
1395                                  */
1396                                 break;
1397                         }
1398                         /*
1399                          * Allocate a complete block in the same (current)
1400                          * cylinder group.
1401                          */
1402                         bp[i].new=alloc()/sblock.fs_frag;
1403
1404                         /*
1405                          * There is no frag_adjust() needed for the new block
1406                          * as it will have no fragments yet :-).
1407                          */
1408                         for(f=bp[i].old*sblock.fs_frag,
1409                             g=bp[i].new*sblock.fs_frag;
1410                             f<(bp[i].old+1)*sblock.fs_frag;
1411                             f++, g++) {
1412                                 if(isset(cg_blksfree(&aocg), f)) {
1413                                         setbit(cg_blksfree(&acg), g);
1414                                         acg.cg_cs.cs_nffree++;
1415                                         sblock.fs_cstotal.cs_nffree++;
1416                                 }
1417                         }
1418
1419                         /*
1420                          * Special handling is required if this was the first
1421                          * block. We have to consider the fragments which were
1422                          * used by the cylinder summary in the original block
1423                          * which re to be free in the copy of our block.  We
1424                          * have to be careful if this first block happens to
1425                          * be also the last block to be relocated.
1426                          */
1427                         if(bp[i].flags & GFS_FL_FIRST) {
1428                                 for(f=bp[i].old*sblock.fs_frag,
1429                                     g=bp[i].new*sblock.fs_frag;
1430                                     f<odupper;
1431                                     f++, g++) {
1432                                         setbit(cg_blksfree(&acg), g);
1433                                         acg.cg_cs.cs_nffree++;
1434                                         sblock.fs_cstotal.cs_nffree++;
1435                                 }
1436                                 if(!(bp[i].flags & GFS_FL_LAST)) {
1437                                         frag_adjust(bp[i].new*sblock.fs_frag,1);
1438                                 }
1439                         }
1440
1441                         /*
1442                          * Special handling is required if this is the last
1443                          * block to be relocated.
1444                          */
1445                         if(bp[i].flags & GFS_FL_LAST) {
1446                                 frag_adjust(bp[i].new*sblock.fs_frag, 1);
1447                                 frag_adjust(bp[i].old*sblock.fs_frag, -1);
1448                                 for(f=dupper;
1449                                     f<roundup(dupper, sblock.fs_frag);
1450                                     f++) {
1451                                         if(isclr(cg_blksfree(&acg), f)) {
1452                                                 setbit(cg_blksfree(&acg), f);
1453                                                 acg.cg_cs.cs_nffree++;
1454                                                 sblock.fs_cstotal.cs_nffree++;
1455                                         }
1456                                 }
1457                                 frag_adjust(bp[i].old*sblock.fs_frag, 1);
1458                         }
1459
1460                         /*
1461                          * !!! Attach the cylindergroup offset here.
1462                          */
1463                         bp[i].old+=cbase/sblock.fs_frag;
1464                         bp[i].new+=cbase/sblock.fs_frag;
1465
1466                         /*
1467                          * Copy the content of the block.
1468                          */
1469                         /*
1470                          * XXX  Here we will have to implement a copy on write
1471                          *      in the case we have any active snapshots.
1472                          */
1473                         rdfs(fsbtodb(&sblock, bp[i].old*sblock.fs_frag),
1474                             (size_t)sblock.fs_bsize, (void *)&ablk, fsi);
1475                         wtfs(fsbtodb(&sblock, bp[i].new*sblock.fs_frag),
1476                             (size_t)sblock.fs_bsize, (void *)&ablk, fso, Nflag);
1477                         DBG_DUMP_HEX(&sblock,
1478                             "copied full block",
1479                             (unsigned char *)&ablk);
1480
1481                         DBG_PRINT2("scg (%jd->%jd) block relocated\n",
1482                             (intmax_t)bp[i].old,
1483                             (intmax_t)bp[i].new);
1484                 }
1485
1486                 /*
1487                  * Now we have to update all references to any fragment which
1488                  * belongs to any block relocated. We iterate now over all
1489                  * cylinder groups, within those over all non zero length
1490                  * inodes.
1491                  */
1492                 for(cylno=0; cylno<osblock.fs_ncg; cylno++) {
1493                         DBG_PRINT1("scg doing cg (%d)\n",
1494                             cylno);
1495                         for(inc=osblock.fs_ipg-1 ; inc>0 ; inc--) {
1496                                 updrefs(cylno, (ino_t)inc, bp, fsi, fso, Nflag);
1497                         }
1498                 }
1499
1500                 /*
1501                  * All inodes are checked, now make sure the number of
1502                  * references found make sense.
1503                  */
1504                 for(i=0; i<ind; i++) {
1505                         if(!bp[i].found || (bp[i].found>sblock.fs_frag)) {
1506                                 warnx("error: %jd refs found for block %jd.",
1507                                     (intmax_t)bp[i].found, (intmax_t)bp[i].old);
1508                         }
1509
1510                 }
1511         }
1512         /*
1513          * The following statistics are not changed here:
1514          *     sblock.fs_cstotal.cs_ndir
1515          *     sblock.fs_cstotal.cs_nifree
1516          * The following statistics were already updated on the fly:
1517          *     sblock.fs_cstotal.cs_nffree
1518          *     sblock.fs_cstotal.cs_nbfree
1519          * As the statistics for this cylinder group are ready, copy it to
1520          * the summary information array.
1521          */
1522
1523         *cs = acg.cg_cs;
1524
1525         /*
1526          * Write summary cylinder group back to disk.
1527          */
1528         wtfs(fsbtodb(&sblock, cgtod(&sblock, ocscg)), (size_t)sblock.fs_cgsize,
1529             (void *)&acg, fso, Nflag);
1530         DBG_PRINT0("scg written\n");
1531         DBG_DUMP_CG(&sblock,
1532             "new summary cg",
1533             &acg);
1534
1535         DBG_LEAVE;
1536         return;
1537 }
1538
1539 /* ************************************************************** rdfs ***** */
1540 /*
1541  * Here we read some block(s) from disk.
1542  */
1543 static void
1544 rdfs(ufs2_daddr_t bno, size_t size, void *bf, int fsi)
1545 {
1546         DBG_FUNC("rdfs")
1547         ssize_t n;
1548
1549         DBG_ENTER;
1550
1551         if (bno < 0) {
1552                 err(32, "rdfs: attempting to read negative block number");
1553         }
1554         if (lseek(fsi, (off_t)bno * DEV_BSIZE, 0) < 0) {
1555                 err(33, "rdfs: seek error: %jd", (intmax_t)bno);
1556         }
1557         n = read(fsi, bf, size);
1558         if (n != (ssize_t)size) {
1559                 err(34, "rdfs: read error: %jd", (intmax_t)bno);
1560         }
1561
1562         DBG_LEAVE;
1563         return;
1564 }
1565
1566 /* ************************************************************** wtfs ***** */
1567 /*
1568  * Here we write some block(s) to disk.
1569  */
1570 static void
1571 wtfs(ufs2_daddr_t bno, size_t size, void *bf, int fso, unsigned int Nflag)
1572 {
1573         DBG_FUNC("wtfs")
1574         ssize_t n;
1575
1576         DBG_ENTER;
1577
1578         if (Nflag) {
1579                 DBG_LEAVE;
1580                 return;
1581         }
1582         if (lseek(fso, (off_t)bno * DEV_BSIZE, SEEK_SET) < 0) {
1583                 err(35, "wtfs: seek error: %ld", (long)bno);
1584         }
1585         n = write(fso, bf, size);
1586         if (n != (ssize_t)size) {
1587                 err(36, "wtfs: write error: %ld", (long)bno);
1588         }
1589
1590         DBG_LEAVE;
1591         return;
1592 }
1593
1594 /* ************************************************************* alloc ***** */
1595 /*
1596  * Here we allocate a free block in the current cylinder group. It is assumed,
1597  * that acg contains the current cylinder group. As we may take a block from
1598  * somewhere in the file system we have to handle cluster summary here.
1599  */
1600 static ufs2_daddr_t
1601 alloc(void)
1602 {
1603         DBG_FUNC("alloc")
1604         ufs2_daddr_t    d, blkno;
1605         int     lcs1, lcs2;
1606         int     l;
1607         int     csmin, csmax;
1608         int     dlower, dupper, dmax;
1609
1610         DBG_ENTER;
1611
1612         if (acg.cg_magic != CG_MAGIC) {
1613                 warnx("acg: bad magic number");
1614                 DBG_LEAVE;
1615                 return (0);
1616         }
1617         if (acg.cg_cs.cs_nbfree == 0) {
1618                 warnx("error: cylinder group ran out of space");
1619                 DBG_LEAVE;
1620                 return (0);
1621         }
1622         /*
1623          * We start seeking for free blocks only from the space available after
1624          * the end of the new grown cylinder summary. Otherwise we allocate a
1625          * block here which we have to relocate a couple of seconds later again
1626          * again, and we are not prepared to to this anyway.
1627          */
1628         blkno=-1;
1629         dlower=cgsblock(&sblock, acg.cg_cgx)-cgbase(&sblock, acg.cg_cgx);
1630         dupper=cgdmin(&sblock, acg.cg_cgx)-cgbase(&sblock, acg.cg_cgx);
1631         dmax=cgbase(&sblock, acg.cg_cgx)+sblock.fs_fpg;
1632         if (dmax > sblock.fs_size) {
1633                 dmax = sblock.fs_size;
1634         }
1635         dmax-=cgbase(&sblock, acg.cg_cgx); /* retransform into cg */
1636         csmin=sblock.fs_csaddr-cgbase(&sblock, acg.cg_cgx);
1637         csmax=csmin+howmany(sblock.fs_cssize, sblock.fs_fsize);
1638         DBG_PRINT3("seek range: dl=%d, du=%d, dm=%d\n",
1639             dlower,
1640             dupper,
1641             dmax);
1642         DBG_PRINT2("range cont: csmin=%d, csmax=%d\n",
1643             csmin,
1644             csmax);
1645
1646         for(d=0; (d<dlower && blkno==-1); d+=sblock.fs_frag) {
1647                 if(d>=csmin && d<=csmax) {
1648                         continue;
1649                 }
1650                 if(isblock(&sblock, cg_blksfree(&acg), fragstoblks(&sblock,
1651                     d))) {
1652                         blkno = fragstoblks(&sblock, d);/* Yeah found a block */
1653                         break;
1654                 }
1655         }
1656         for(d=dupper; (d<dmax && blkno==-1); d+=sblock.fs_frag) {
1657                 if(d>=csmin && d<=csmax) {
1658                         continue;
1659                 }
1660                 if(isblock(&sblock, cg_blksfree(&acg), fragstoblks(&sblock,
1661                     d))) {
1662                         blkno = fragstoblks(&sblock, d);/* Yeah found a block */
1663                         break;
1664                 }
1665         }
1666         if(blkno==-1) {
1667                 warnx("internal error: couldn't find promised block in cg");
1668                 DBG_LEAVE;
1669                 return (0);
1670         }
1671
1672         /*
1673          * This is needed if the block was found already in the first loop.
1674          */
1675         d=blkstofrags(&sblock, blkno);
1676
1677         clrblock(&sblock, cg_blksfree(&acg), blkno);
1678         if (sblock.fs_contigsumsize > 0) {
1679                 /*
1680                  * Handle the cluster allocation bitmap.
1681                  */
1682                 clrbit(cg_clustersfree(&acg), blkno);
1683                 /*
1684                  * We possibly have split a cluster here, so we have to do
1685                  * recalculate the sizes of the remaining cluster halves now,
1686                  * and use them for updating the cluster summary information.
1687                  *
1688                  * Lets start with the blocks before our allocated block ...
1689                  */
1690                 for(lcs1=0, l=blkno-1; lcs1<sblock.fs_contigsumsize;
1691                     l--, lcs1++ ) {
1692                         if(isclr(cg_clustersfree(&acg),l)){
1693                                 break;
1694                         }
1695                 }
1696                 /*
1697                  * ... and continue with the blocks right after our allocated
1698                  * block.
1699                  */
1700                 for(lcs2=0, l=blkno+1; lcs2<sblock.fs_contigsumsize;
1701                     l++, lcs2++ ) {
1702                         if(isclr(cg_clustersfree(&acg),l)){
1703                                 break;
1704                         }
1705                 }
1706
1707                 /*
1708                  * Now update all counters.
1709                  */
1710                 cg_clustersum(&acg)[MIN(lcs1+lcs2+1,sblock.fs_contigsumsize)]--;
1711                 if(lcs1) {
1712                         cg_clustersum(&acg)[lcs1]++;
1713                 }
1714                 if(lcs2) {
1715                         cg_clustersum(&acg)[lcs2]++;
1716                 }
1717         }
1718         /*
1719          * Update all statistics based on blocks.
1720          */
1721         acg.cg_cs.cs_nbfree--;
1722         sblock.fs_cstotal.cs_nbfree--;
1723
1724         DBG_LEAVE;
1725         return (d);
1726 }
1727
1728 /* *********************************************************** isblock ***** */
1729 /*
1730  * Here we check if all frags of a block are free. For more details again
1731  * please see the source of newfs(8), as this function is taken over almost
1732  * unchanged.
1733  */
1734 static int
1735 isblock(struct fs *fs, unsigned char *cp, int h)
1736 {
1737         DBG_FUNC("isblock")
1738         unsigned char   mask;
1739
1740         DBG_ENTER;
1741
1742         switch (fs->fs_frag) {
1743         case 8:
1744                 DBG_LEAVE;
1745                 return (cp[h] == 0xff);
1746         case 4:
1747                 mask = 0x0f << ((h & 0x1) << 2);
1748                 DBG_LEAVE;
1749                 return ((cp[h >> 1] & mask) == mask);
1750         case 2:
1751                 mask = 0x03 << ((h & 0x3) << 1);
1752                 DBG_LEAVE;
1753                 return ((cp[h >> 2] & mask) == mask);
1754         case 1:
1755                 mask = 0x01 << (h & 0x7);
1756                 DBG_LEAVE;
1757                 return ((cp[h >> 3] & mask) == mask);
1758         default:
1759                 fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
1760                 DBG_LEAVE;
1761                 return (0);
1762         }
1763 }
1764
1765 /* ********************************************************** clrblock ***** */
1766 /*
1767  * Here we allocate a complete block in the block map. For more details again
1768  * please see the source of newfs(8), as this function is taken over almost
1769  * unchanged.
1770  */
1771 static void
1772 clrblock(struct fs *fs, unsigned char *cp, int h)
1773 {
1774         DBG_FUNC("clrblock")
1775
1776         DBG_ENTER;
1777
1778         switch ((fs)->fs_frag) {
1779         case 8:
1780                 cp[h] = 0;
1781                 break;
1782         case 4:
1783                 cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1784                 break;
1785         case 2:
1786                 cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1787                 break;
1788         case 1:
1789                 cp[h >> 3] &= ~(0x01 << (h & 0x7));
1790                 break;
1791         default:
1792                 warnx("clrblock bad fs_frag %d", fs->fs_frag);
1793                 break;
1794         }
1795
1796         DBG_LEAVE;
1797         return;
1798 }
1799
1800 /* ********************************************************** setblock ***** */
1801 /*
1802  * Here we free a complete block in the free block map. For more details again
1803  * please see the source of newfs(8), as this function is taken over almost
1804  * unchanged.
1805  */
1806 static void
1807 setblock(struct fs *fs, unsigned char *cp, int h)
1808 {
1809         DBG_FUNC("setblock")
1810
1811         DBG_ENTER;
1812
1813         switch (fs->fs_frag) {
1814         case 8:
1815                 cp[h] = 0xff;
1816                 break;
1817         case 4:
1818                 cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1819                 break;
1820         case 2:
1821                 cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1822                 break;
1823         case 1:
1824                 cp[h >> 3] |= (0x01 << (h & 0x7));
1825                 break;
1826         default:
1827                 warnx("setblock bad fs_frag %d", fs->fs_frag);
1828                 break;
1829         }
1830
1831         DBG_LEAVE;
1832         return;
1833 }
1834
1835 /* ************************************************************ ginode ***** */
1836 /*
1837  * This function provides access to an individual inode. We find out in which
1838  * block the requested inode is located, read it from disk if needed, and
1839  * return the pointer into that block. We maintain a cache of one block to
1840  * not read the same block again and again if we iterate linearly over all
1841  * inodes.
1842  */
1843 static union dinode *
1844 ginode(ino_t inumber, int fsi, int cg)
1845 {
1846         DBG_FUNC("ginode")
1847         static ino_t    startinum = 0;  /* first inode in cached block */
1848
1849         DBG_ENTER;
1850
1851         /*
1852          * The inumber passed in is relative to the cg, so use it here to see
1853          * if the inode has been allocated yet.
1854          */
1855         if (isclr(cg_inosused(&aocg), inumber)) {
1856                 DBG_LEAVE;
1857                 return NULL;
1858         }
1859         /*
1860          * Now make the inumber relative to the entire inode space so it can
1861          * be sanity checked.
1862          */
1863         inumber += (cg * sblock.fs_ipg);
1864         if (inumber < ROOTINO) {
1865                 DBG_LEAVE;
1866                 return NULL;
1867         }
1868         if (inumber > maxino)
1869                 errx(8, "bad inode number %d to ginode", inumber);
1870         if (startinum == 0 ||
1871             inumber < startinum || inumber >= startinum + INOPB(&sblock)) {
1872                 inoblk = fsbtodb(&sblock, ino_to_fsba(&sblock, inumber));
1873                 rdfs(inoblk, (size_t)sblock.fs_bsize, inobuf, fsi);
1874                 startinum = (inumber / INOPB(&sblock)) * INOPB(&sblock);
1875         }
1876         DBG_LEAVE;
1877         if (sblock.fs_magic == FS_UFS1_MAGIC)
1878                 return (union dinode *)((uintptr_t)inobuf +
1879                     (inumber % INOPB(&sblock)) * sizeof(struct ufs1_dinode));
1880         return (union dinode *)((uintptr_t)inobuf +
1881             (inumber % INOPB(&sblock)) * sizeof(struct ufs2_dinode));
1882 }
1883
1884 /* ****************************************************** charsperline ***** */
1885 /*
1886  * Figure out how many lines our current terminal has. For more details again
1887  * please see the source of newfs(8), as this function is taken over almost
1888  * unchanged.
1889  */
1890 static int
1891 charsperline(void)
1892 {
1893         DBG_FUNC("charsperline")
1894         int     columns;
1895         char    *cp;
1896         struct winsize  ws;
1897
1898         DBG_ENTER;
1899
1900         columns = 0;
1901         if (ioctl(0, TIOCGWINSZ, &ws) != -1) {
1902                 columns = ws.ws_col;
1903         }
1904         if (columns == 0 && (cp = getenv("COLUMNS"))) {
1905                 columns = atoi(cp);
1906         }
1907         if (columns == 0) {
1908                 columns = 80;   /* last resort */
1909         }
1910
1911         DBG_LEAVE;
1912         return columns;
1913 }
1914
1915 /* ****************************************************** get_dev_size ***** */
1916 /*
1917  * Get the size of the partition if we can't figure it out from the disklabel,
1918  * e.g. from vinum volumes.
1919  */
1920 static void
1921 get_dev_size(int fd, int *size)
1922 {
1923    int sectorsize;
1924    off_t mediasize;
1925
1926    if (ioctl(fd, DIOCGSECTORSIZE, &sectorsize) == -1)
1927         err(1,"DIOCGSECTORSIZE");
1928    if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) == -1)
1929         err(1,"DIOCGMEDIASIZE");
1930
1931    if (sectorsize <= 0)
1932        errx(1, "bogus sectorsize: %d", sectorsize);
1933
1934    *size = mediasize / sectorsize;
1935 }
1936
1937 /* ************************************************************** main ***** */
1938 /*
1939  * growfs(8)  is a utility which allows to increase the size of an existing
1940  * ufs file system. Currently this can only be done on unmounted file system.
1941  * It recognizes some command line options to specify the new desired size,
1942  * and it does some basic checkings. The old file system size is determined
1943  * and after some more checks like we can really access the new last block
1944  * on the disk etc. we calculate the new parameters for the superblock. After
1945  * having done this we just call growfs() which will do the work.  Before
1946  * we finish the only thing left is to update the disklabel.
1947  * We still have to provide support for snapshots. Therefore we first have to
1948  * understand what data structures are always replicated in the snapshot on
1949  * creation, for all other blocks we touch during our procedure, we have to
1950  * keep the old blocks unchanged somewhere available for the snapshots. If we
1951  * are lucky, then we only have to handle our blocks to be relocated in that
1952  * way.
1953  * Also we have to consider in what order we actually update the critical
1954  * data structures of the file system to make sure, that in case of a disaster
1955  * fsck(8) is still able to restore any lost data.
1956  * The foreseen last step then will be to provide for growing even mounted
1957  * file systems. There we have to extend the mount() system call to provide
1958  * userland access to the file system locking facility.
1959  */
1960 int
1961 main(int argc, char **argv)
1962 {
1963         DBG_FUNC("main")
1964         char    *device, *special, *cp;
1965         int     ch;
1966         unsigned int    size=0;
1967         size_t  len;
1968         unsigned int    Nflag=0;
1969         int     ExpertFlag=0;
1970         struct stat     st;
1971         struct disklabel        *lp;
1972         struct partition        *pp;
1973         int     i,fsi,fso;
1974     u_int32_t p_size;
1975         char    reply[5];
1976 #ifdef FSMAXSNAP
1977         int     j;
1978 #endif /* FSMAXSNAP */
1979
1980         DBG_ENTER;
1981
1982         while((ch=getopt(argc, argv, "Ns:vy")) != -1) {
1983                 switch(ch) {
1984                 case 'N':
1985                         Nflag=1;
1986                         break;
1987                 case 's':
1988                         size=(size_t)atol(optarg);
1989                         if(size<1) {
1990                                 usage();
1991                         }
1992                         break;
1993                 case 'v': /* for compatibility to newfs */
1994                         break;
1995                 case 'y':
1996                         ExpertFlag=1;
1997                         break;
1998                 case '?':
1999                         /* FALLTHROUGH */
2000                 default:
2001                         usage();
2002                 }
2003         }
2004         argc -= optind;
2005         argv += optind;
2006
2007         if(argc != 1) {
2008                 usage();
2009         }
2010         device=*argv;
2011
2012         /*
2013          * Now try to guess the (raw)device name.
2014          */
2015         if (0 == strrchr(device, '/')) {
2016                 /*
2017                  * No path prefix was given, so try in that order:
2018                  *     /dev/r%s
2019                  *     /dev/%s
2020                  *     /dev/vinum/r%s
2021                  *     /dev/vinum/%s.
2022                  *
2023                  * FreeBSD now doesn't distinguish between raw and block
2024                  * devices any longer, but it should still work this way.
2025                  */
2026                 len=strlen(device)+strlen(_PATH_DEV)+2+strlen("vinum/");
2027                 special=(char *)malloc(len);
2028                 if(special == NULL) {
2029                         errx(1, "malloc failed");
2030                 }
2031                 snprintf(special, len, "%sr%s", _PATH_DEV, device);
2032                 if (stat(special, &st) == -1) {
2033                         snprintf(special, len, "%s%s", _PATH_DEV, device);
2034                         if (stat(special, &st) == -1) {
2035                                 snprintf(special, len, "%svinum/r%s",
2036                                     _PATH_DEV, device);
2037                                 if (stat(special, &st) == -1) {
2038                                         /* For now this is the 'last resort' */
2039                                         snprintf(special, len, "%svinum/%s",
2040                                             _PATH_DEV, device);
2041                                 }
2042                         }
2043                 }
2044                 device = special;
2045         }
2046
2047         /*
2048          * Try to access our devices for writing ...
2049          */
2050         if (Nflag) {
2051                 fso = -1;
2052         } else {
2053                 fso = open(device, O_WRONLY);
2054                 if (fso < 0) {
2055                         err(1, "%s", device);
2056                 }
2057         }
2058
2059         /*
2060          * ... and reading.
2061          */
2062         fsi = open(device, O_RDONLY);
2063         if (fsi < 0) {
2064                 err(1, "%s", device);
2065         }
2066
2067         /*
2068          * Try to read a label and guess the slice if not specified. This
2069          * code should guess the right thing and avoid to bother the user
2070          * with the task of specifying the option -v on vinum volumes.
2071          */
2072         cp=device+strlen(device)-1;
2073         lp = get_disklabel(fsi);
2074         pp = NULL;
2075     if (lp != NULL) {
2076         if (isdigit(*cp)) {
2077             pp = &lp->d_partitions[2];
2078         } else if (*cp>='a' && *cp<='h') {
2079             pp = &lp->d_partitions[*cp - 'a'];
2080         } else {
2081             errx(1, "unknown device");
2082         }
2083         p_size = pp->p_size;
2084     } else {
2085         get_dev_size(fsi, &p_size);
2086     }
2087
2088         /*
2089          * Check if that partition is suitable for growing a file system.
2090          */
2091         if (p_size < 1) {
2092                 errx(1, "partition is unavailable");
2093         }
2094
2095         /*
2096          * Read the current superblock, and take a backup.
2097          */
2098         for (i = 0; sblock_try[i] != -1; i++) {
2099                 sblockloc = sblock_try[i] / DEV_BSIZE;
2100                 rdfs(sblockloc, (size_t)SBLOCKSIZE, (void *)&(osblock), fsi);
2101                 if ((osblock.fs_magic == FS_UFS1_MAGIC ||
2102                      (osblock.fs_magic == FS_UFS2_MAGIC &&
2103                       osblock.fs_sblockloc == sblock_try[i])) &&
2104                     osblock.fs_bsize <= MAXBSIZE &&
2105                     osblock.fs_bsize >= (int32_t) sizeof(struct fs))
2106                         break;
2107         }
2108         if (sblock_try[i] == -1) {
2109                 errx(1, "superblock not recognized");
2110         }
2111         memcpy((void *)&fsun1, (void *)&fsun2, sizeof(fsun2));
2112         maxino = sblock.fs_ncg * sblock.fs_ipg;
2113
2114         DBG_OPEN("/tmp/growfs.debug"); /* already here we need a superblock */
2115         DBG_DUMP_FS(&sblock,
2116             "old sblock");
2117
2118         /*
2119          * Determine size to grow to. Default to the full size specified in
2120          * the disk label.
2121          */
2122         sblock.fs_size = dbtofsb(&osblock, p_size);
2123         if (size != 0) {
2124                 if (size > p_size){
2125                         errx(1, "there is not enough space (%d < %d)",
2126                             p_size, size);
2127                 }
2128                 sblock.fs_size = dbtofsb(&osblock, size);
2129         }
2130
2131         /*
2132          * Are we really growing ?
2133          */
2134         if(osblock.fs_size >= sblock.fs_size) {
2135                 errx(1, "we are not growing (%jd->%jd)",
2136                     (intmax_t)osblock.fs_size, (intmax_t)sblock.fs_size);
2137         }
2138
2139
2140 #ifdef FSMAXSNAP
2141         /*
2142          * Check if we find an active snapshot.
2143          */
2144         if(ExpertFlag == 0) {
2145                 for(j=0; j<FSMAXSNAP; j++) {
2146                         if(sblock.fs_snapinum[j]) {
2147                                 errx(1, "active snapshot found in file system\n"
2148                                     "   please remove all snapshots before "
2149                                     "using growfs");
2150                         }
2151                         if(!sblock.fs_snapinum[j]) { /* list is dense */
2152                                 break;
2153                         }
2154                 }
2155         }
2156 #endif
2157
2158         if (ExpertFlag == 0 && Nflag == 0) {
2159                 printf("We strongly recommend you to make a backup "
2160                     "before growing the Filesystem\n\n"
2161                     " Did you backup your data (Yes/No) ? ");
2162                 fgets(reply, (int)sizeof(reply), stdin);
2163                 if (strcmp(reply, "Yes\n")){
2164                         printf("\n Nothing done \n");
2165                         exit (0);
2166                 }
2167         }
2168
2169         printf("new file systemsize is: %jd frags\n", (intmax_t)sblock.fs_size);
2170
2171         /*
2172          * Try to access our new last block in the file system. Even if we
2173          * later on realize we have to abort our operation, on that block
2174          * there should be no data, so we can't destroy something yet.
2175          */
2176         wtfs((ufs2_daddr_t)p_size-1, (size_t)DEV_BSIZE, (void *)&sblock,
2177             fso, Nflag);
2178
2179         /*
2180          * Now calculate new superblock values and check for reasonable
2181          * bound for new file system size:
2182          *     fs_size:    is derived from label or user input
2183          *     fs_dsize:   should get updated in the routines creating or
2184          *                 updating the cylinder groups on the fly
2185          *     fs_cstotal: should get updated in the routines creating or
2186          *                 updating the cylinder groups
2187          */
2188
2189         /*
2190          * Update the number of cylinders and cylinder groups in the file system.
2191          */
2192         if (sblock.fs_magic == FS_UFS1_MAGIC) {
2193                 sblock.fs_old_ncyl =
2194                     sblock.fs_size * sblock.fs_old_nspf / sblock.fs_old_spc;
2195                 if (sblock.fs_size * sblock.fs_old_nspf >
2196                     sblock.fs_old_ncyl * sblock.fs_old_spc)
2197                         sblock.fs_old_ncyl++;
2198         }
2199         sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
2200         maxino = sblock.fs_ncg * sblock.fs_ipg;
2201
2202         if (sblock.fs_size % sblock.fs_fpg != 0 &&
2203             sblock.fs_size % sblock.fs_fpg < cgdmin(&sblock, sblock.fs_ncg)) {
2204                 /*
2205                  * The space in the new last cylinder group is too small,
2206                  * so revert back.
2207                  */
2208                 sblock.fs_ncg--;
2209                 if (sblock.fs_magic == FS_UFS1_MAGIC)
2210                         sblock.fs_old_ncyl = sblock.fs_ncg * sblock.fs_old_cpg;
2211                 printf("Warning: %jd sector(s) cannot be allocated.\n",
2212                     (intmax_t)fsbtodb(&sblock, sblock.fs_size % sblock.fs_fpg));
2213                 sblock.fs_size = sblock.fs_ncg * sblock.fs_fpg;
2214         }
2215
2216         /*
2217          * Update the space for the cylinder group summary information in the
2218          * respective cylinder group data area.
2219          */
2220         sblock.fs_cssize =
2221             fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
2222
2223         if(osblock.fs_size >= sblock.fs_size) {
2224                 errx(1, "not enough new space");
2225         }
2226
2227         DBG_PRINT0("sblock calculated\n");
2228
2229         /*
2230          * Ok, everything prepared, so now let's do the tricks.
2231          */
2232         growfs(fsi, fso, Nflag);
2233
2234         /*
2235          * Update the disk label.
2236          */
2237     if (!unlabeled) {
2238         pp->p_fsize = sblock.fs_fsize;
2239         pp->p_frag = sblock.fs_frag;
2240         pp->p_cpg = sblock.fs_fpg;
2241
2242         return_disklabel(fso, lp, Nflag);
2243         DBG_PRINT0("label rewritten\n");
2244     }
2245
2246         close(fsi);
2247         if(fso>-1) close(fso);
2248
2249         DBG_CLOSE;
2250
2251         DBG_LEAVE;
2252         return 0;
2253 }
2254
2255 /* ************************************************** return_disklabel ***** */
2256 /*
2257  * Write the updated disklabel back to disk.
2258  */
2259 static void
2260 return_disklabel(int fd, struct disklabel *lp, unsigned int Nflag)
2261 {
2262         DBG_FUNC("return_disklabel")
2263         u_short sum;
2264         u_short *ptr;
2265
2266         DBG_ENTER;
2267
2268         if(!lp) {
2269                 DBG_LEAVE;
2270                 return;
2271         }
2272         if(!Nflag) {
2273                 lp->d_checksum=0;
2274                 sum = 0;
2275                 ptr=(u_short *)lp;
2276
2277                 /*
2278                  * recalculate checksum
2279                  */
2280                 while(ptr < (u_short *)&lp->d_partitions[lp->d_npartitions]) {
2281                         sum ^= *ptr++;
2282                 }
2283                 lp->d_checksum=sum;
2284
2285                 if (ioctl(fd, DIOCWDINFO, (char *)lp) < 0) {
2286                         errx(1, "DIOCWDINFO failed");
2287                 }
2288         }
2289         free(lp);
2290
2291         DBG_LEAVE;
2292         return ;
2293 }
2294
2295 /* ***************************************************** get_disklabel ***** */
2296 /*
2297  * Read the disklabel from disk.
2298  */
2299 static struct disklabel *
2300 get_disklabel(int fd)
2301 {
2302         DBG_FUNC("get_disklabel")
2303         static struct   disklabel *lab;
2304
2305         DBG_ENTER;
2306
2307         lab=(struct disklabel *)malloc(sizeof(struct disklabel));
2308         if (!lab)
2309                 errx(1, "malloc failed");
2310
2311     if (!ioctl(fd, DIOCGDINFO, (char *)lab))
2312         return (lab);
2313
2314     unlabeled++;
2315
2316         DBG_LEAVE;
2317         return (NULL);
2318 }
2319
2320
2321 /* ************************************************************* usage ***** */
2322 /*
2323  * Dump a line of usage.
2324  */
2325 static void
2326 usage(void)
2327 {
2328         DBG_FUNC("usage")
2329
2330         DBG_ENTER;
2331
2332         fprintf(stderr, "usage: growfs [-Ny] [-s size] special\n");
2333
2334         DBG_LEAVE;
2335         exit(1);
2336 }
2337
2338 /* *********************************************************** updclst ***** */
2339 /*
2340  * This updates most parameters and the bitmap related to cluster. We have to
2341  * assume that sblock, osblock, acg are set up.
2342  */
2343 static void
2344 updclst(int block)
2345 {
2346         DBG_FUNC("updclst")
2347         static int      lcs=0;
2348
2349         DBG_ENTER;
2350
2351         if(sblock.fs_contigsumsize < 1) { /* no clustering */
2352                 return;
2353         }
2354         /*
2355          * update cluster allocation map
2356          */
2357         setbit(cg_clustersfree(&acg), block);
2358
2359         /*
2360          * update cluster summary table
2361          */
2362         if(!lcs) {
2363                 /*
2364                  * calculate size for the trailing cluster
2365                  */
2366                 for(block--; lcs<sblock.fs_contigsumsize; block--, lcs++ ) {
2367                         if(isclr(cg_clustersfree(&acg), block)){
2368                                 break;
2369                         }
2370                 }
2371         }
2372         if(lcs < sblock.fs_contigsumsize) {
2373                 if(lcs) {
2374                         cg_clustersum(&acg)[lcs]--;
2375                 }
2376                 lcs++;
2377                 cg_clustersum(&acg)[lcs]++;
2378         }
2379
2380         DBG_LEAVE;
2381         return;
2382 }
2383
2384 /* *********************************************************** updrefs ***** */
2385 /*
2386  * This updates all references to relocated blocks for the given inode.  The
2387  * inode is given as number within the cylinder group, and the number of the
2388  * cylinder group.
2389  */
2390 static void
2391 updrefs(int cg, ino_t in, struct gfs_bpp *bp, int fsi, int fso, unsigned int
2392     Nflag)
2393 {
2394         DBG_FUNC("updrefs")
2395         ufs_lbn_t       len, lbn, numblks;
2396         ufs2_daddr_t    iptr, blksperindir;
2397         union dinode    *ino;
2398         int             i, mode, inodeupdated;
2399
2400         DBG_ENTER;
2401
2402         ino = ginode(in, fsi, cg);
2403         if (ino == NULL) {
2404                 DBG_LEAVE;
2405                 return;
2406         }
2407         mode = DIP(ino, di_mode) & IFMT;
2408         if (mode != IFDIR && mode != IFREG && mode != IFLNK) {
2409                 DBG_LEAVE;
2410                 return; /* only check DIR, FILE, LINK */
2411         }
2412         if (mode == IFLNK && 
2413             DIP(ino, di_size) < (u_int64_t) sblock.fs_maxsymlinklen) {
2414                 DBG_LEAVE;
2415                 return; /* skip short symlinks */
2416         }
2417         numblks = howmany(DIP(ino, di_size), sblock.fs_bsize);
2418         if (numblks == 0) {
2419                 DBG_LEAVE;
2420                 return; /* skip empty file */
2421         }
2422         if (DIP(ino, di_blocks) == 0) {
2423                 DBG_LEAVE;
2424                 return; /* skip empty swiss cheesy file or old fastlink */
2425         }
2426         DBG_PRINT2("scg checking inode (%d in %d)\n",
2427             in,
2428             cg);
2429
2430         /*
2431          * Check all the blocks.
2432          */
2433         inodeupdated = 0;
2434         len = numblks < NDADDR ? numblks : NDADDR;
2435         for (i = 0; i < len; i++) {
2436                 iptr = DIP(ino, di_db[i]);
2437                 if (iptr == 0)
2438                         continue;
2439                 if (cond_bl_upd(&iptr, bp, fsi, fso, Nflag)) {
2440                         DIP_SET(ino, di_db[i], iptr);
2441                         inodeupdated++;
2442                 }
2443         }
2444         DBG_PRINT0("~~scg direct blocks checked\n");
2445
2446         blksperindir = 1;
2447         len = numblks - NDADDR;
2448         lbn = NDADDR;
2449         for (i = 0; len > 0 && i < NIADDR; i++) {
2450                 iptr = DIP(ino, di_ib[i]);
2451                 if (iptr == 0)
2452                         continue;
2453                 if (cond_bl_upd(&iptr, bp, fsi, fso, Nflag)) {
2454                         DIP_SET(ino, di_ib[i], iptr);
2455                         inodeupdated++;
2456                 }
2457                 indirchk(blksperindir, lbn, iptr, numblks, bp, fsi, fso, Nflag);
2458                 blksperindir *= NINDIR(&sblock);
2459                 lbn += blksperindir;
2460                 len -= blksperindir;
2461                 DBG_PRINT1("scg indirect_%d blocks checked\n", i + 1);
2462         }
2463         if (inodeupdated)
2464                 wtfs(inoblk, sblock.fs_bsize, inobuf, fso, Nflag);
2465
2466         DBG_LEAVE;
2467         return;
2468 }
2469
2470 /*
2471  * Recursively check all the indirect blocks.
2472  */
2473 static void
2474 indirchk(ufs_lbn_t blksperindir, ufs_lbn_t lbn, ufs2_daddr_t blkno,
2475     ufs_lbn_t lastlbn, struct gfs_bpp *bp, int fsi, int fso, unsigned int Nflag)
2476 {
2477         DBG_FUNC("indirchk")
2478         void *ibuf;
2479         int i, last;
2480         ufs2_daddr_t iptr;
2481
2482         DBG_ENTER;
2483
2484         /* read in the indirect block. */
2485         ibuf = malloc(sblock.fs_bsize);
2486         if (!ibuf)
2487                 errx(1, "malloc failed");
2488         rdfs(fsbtodb(&sblock, blkno), (size_t)sblock.fs_bsize, ibuf, fsi);
2489         last = howmany(lastlbn - lbn, blksperindir) < NINDIR(&sblock) ?
2490             howmany(lastlbn - lbn, blksperindir) : NINDIR(&sblock);
2491         for (i = 0; i < last; i++) {
2492                 if (sblock.fs_magic == FS_UFS1_MAGIC)
2493                         iptr = ((ufs1_daddr_t *)ibuf)[i];
2494                 else
2495                         iptr = ((ufs2_daddr_t *)ibuf)[i];
2496                 if (iptr == 0)
2497                         continue;
2498                 if (cond_bl_upd(&iptr, bp, fsi, fso, Nflag)) {
2499                         if (sblock.fs_magic == FS_UFS1_MAGIC)
2500                                 ((ufs1_daddr_t *)ibuf)[i] = iptr;
2501                         else
2502                                 ((ufs2_daddr_t *)ibuf)[i] = iptr;
2503                 }
2504                 if (blksperindir == 1)
2505                         continue;
2506                 indirchk(blksperindir / NINDIR(&sblock), lbn + blksperindir * i,
2507                     iptr, lastlbn, bp, fsi, fso, Nflag);
2508         }
2509         free(ibuf);
2510
2511         DBG_LEAVE;
2512         return;
2513 }