]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/makefs/ffs/mkfs.c
Merge bmake-20210110
[FreeBSD/FreeBSD.git] / usr.sbin / makefs / ffs / mkfs.c
1 /*      $NetBSD: mkfs.c,v 1.22 2011/10/09 22:30:13 christos Exp $       */
2
3 /*-
4  * SPDX-License-Identifier: BSD-3-Clause
5  *
6  * Copyright (c) 2002 Networks Associates Technology, Inc.
7  * All rights reserved.
8  *
9  * This software was developed for the FreeBSD Project by Marshall
10  * Kirk McKusick and Network Associates Laboratories, the Security
11  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
12  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
13  * research program
14  *
15  * Copyright (c) 1980, 1989, 1993
16  *      The Regents of the University of California.  All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  */
42
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45
46 #include <sys/param.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <errno.h>
55 #include <util.h>
56
57 #include "makefs.h"
58 #include "ffs.h"
59
60 #include <ufs/ufs/dinode.h>
61 #include <ufs/ffs/fs.h>
62
63 #include "ffs/ufs_bswap.h"
64 #include "ffs/ufs_inode.h"
65 #include "ffs/ffs_extern.h"
66 #include "ffs/newfs_extern.h"
67
68 #ifndef BBSIZE
69 #define BBSIZE  8192                    /* size of boot area, with label */
70 #endif
71
72 static void initcg(uint32_t, time_t, const fsinfo_t *);
73 static int ilog2(int);
74
75 static int count_digits(int);
76
77 /*
78  * make file system for cylinder-group style file systems
79  */
80 #define UMASK           0755
81 #define POWEROF2(num)   (((num) & ((num) - 1)) == 0)
82
83 static union {
84         struct fs fs;
85         char pad[SBLOCKSIZE];
86 } fsun;
87 #define sblock  fsun.fs
88
89 static union {
90         struct cg cg;
91         char pad[FFS_MAXBSIZE];
92 } cgun;
93 #define acg     cgun.cg
94
95 static char *iobuf;
96 static int iobufsize;
97
98 static char writebuf[FFS_MAXBSIZE];
99
100 static int     Oflag;      /* format as an 4.3BSD file system */
101 static int64_t fssize;     /* file system size */
102 static int     sectorsize;         /* bytes/sector */
103 static int     fsize;      /* fragment size */
104 static int     bsize;      /* block size */
105 static int     maxbsize;   /* maximum clustering */
106 static int     maxblkspercg;
107 static int     minfree;    /* free space threshold */
108 static int     opt;                /* optimization preference (space or time) */
109 static int     density;    /* number of bytes per inode */
110 static int     maxcontig;          /* max contiguous blocks to allocate */
111 static int     maxbpg;     /* maximum blocks per file in a cyl group */
112 static int     bbsize;     /* boot block size */
113 static int     sbsize;     /* superblock size */
114 static int     avgfilesize;        /* expected average file size */
115 static int     avgfpdir;           /* expected number of files per directory */
116
117 struct fs *
118 ffs_mkfs(const char *fsys, const fsinfo_t *fsopts, time_t tstamp)
119 {
120         int fragsperinode, optimalfpg, origdensity, minfpg, lastminfpg;
121         int32_t csfrags;
122         uint32_t i, cylno;
123         long long sizepb;
124         void *space;
125         int size;
126         int nprintcols, printcolwidth;
127         ffs_opt_t       *ffs_opts = fsopts->fs_specific;
128
129         Oflag =         ffs_opts->version;
130         fssize =        fsopts->size / fsopts->sectorsize;
131         sectorsize =    fsopts->sectorsize;
132         fsize =         ffs_opts->fsize;
133         bsize =         ffs_opts->bsize;
134         maxbsize =      ffs_opts->maxbsize;
135         maxblkspercg =  ffs_opts->maxblkspercg;
136         minfree =       ffs_opts->minfree;
137         opt =           ffs_opts->optimization;
138         density =       ffs_opts->density;
139         maxcontig =     ffs_opts->maxcontig;
140         maxbpg =        ffs_opts->maxbpg;
141         avgfilesize =   ffs_opts->avgfilesize;
142         avgfpdir =      ffs_opts->avgfpdir;
143         bbsize =        BBSIZE;
144         sbsize =        SBLOCKSIZE;
145
146         strlcpy((char *)sblock.fs_volname, ffs_opts->label,
147             sizeof(sblock.fs_volname));
148
149         if (Oflag == 0) {
150                 sblock.fs_old_inodefmt = FS_42INODEFMT;
151                 sblock.fs_maxsymlinklen = 0;
152                 sblock.fs_old_flags = 0;
153         } else {
154                 sblock.fs_old_inodefmt = FS_44INODEFMT;
155                 sblock.fs_maxsymlinklen = (Oflag == 1 ? UFS1_MAXSYMLINKLEN :
156                     UFS2_MAXSYMLINKLEN);
157                 sblock.fs_old_flags = FS_FLAGS_UPDATED;
158                 sblock.fs_flags = 0;
159         }
160         /*
161          * Validate the given file system size.
162          * Verify that its last block can actually be accessed.
163          * Convert to file system fragment sized units.
164          */
165         if (fssize <= 0) {
166                 printf("preposterous size %lld\n", (long long)fssize);
167                 exit(13);
168         }
169         ffs_wtfs(fssize - 1, sectorsize, (char *)&sblock, fsopts);
170
171         /*
172          * collect and verify the filesystem density info
173          */
174         sblock.fs_avgfilesize = avgfilesize;
175         sblock.fs_avgfpdir = avgfpdir;
176         if (sblock.fs_avgfilesize <= 0)
177                 printf("illegal expected average file size %d\n",
178                     sblock.fs_avgfilesize), exit(14);
179         if (sblock.fs_avgfpdir <= 0)
180                 printf("illegal expected number of files per directory %d\n",
181                     sblock.fs_avgfpdir), exit(15);
182         /*
183          * collect and verify the block and fragment sizes
184          */
185         sblock.fs_bsize = bsize;
186         sblock.fs_fsize = fsize;
187         if (!POWEROF2(sblock.fs_bsize)) {
188                 printf("block size must be a power of 2, not %d\n",
189                     sblock.fs_bsize);
190                 exit(16);
191         }
192         if (!POWEROF2(sblock.fs_fsize)) {
193                 printf("fragment size must be a power of 2, not %d\n",
194                     sblock.fs_fsize);
195                 exit(17);
196         }
197         if (sblock.fs_fsize < sectorsize) {
198                 printf("fragment size %d is too small, minimum is %d\n",
199                     sblock.fs_fsize, sectorsize);
200                 exit(18);
201         }
202         if (sblock.fs_bsize < MINBSIZE) {
203                 printf("block size %d is too small, minimum is %d\n",
204                     sblock.fs_bsize, MINBSIZE);
205                 exit(19);
206         }
207         if (sblock.fs_bsize > FFS_MAXBSIZE) {
208                 printf("block size %d is too large, maximum is %d\n",
209                     sblock.fs_bsize, FFS_MAXBSIZE);
210                 exit(19);
211         }
212         if (sblock.fs_bsize < sblock.fs_fsize) {
213                 printf("block size (%d) cannot be smaller than fragment size (%d)\n",
214                     sblock.fs_bsize, sblock.fs_fsize);
215                 exit(20);
216         }
217
218         if (maxbsize < bsize || !POWEROF2(maxbsize)) {
219                 sblock.fs_maxbsize = sblock.fs_bsize;
220                 printf("Extent size set to %d\n", sblock.fs_maxbsize);
221         } else if (sblock.fs_maxbsize > FS_MAXCONTIG * sblock.fs_bsize) {
222                 sblock.fs_maxbsize = FS_MAXCONTIG * sblock.fs_bsize;
223                 printf("Extent size reduced to %d\n", sblock.fs_maxbsize);
224         } else {
225                 sblock.fs_maxbsize = maxbsize;
226         }
227         sblock.fs_maxcontig = maxcontig;
228         if (sblock.fs_maxcontig < sblock.fs_maxbsize / sblock.fs_bsize) {
229                 sblock.fs_maxcontig = sblock.fs_maxbsize / sblock.fs_bsize;
230                 printf("Maxcontig raised to %d\n", sblock.fs_maxbsize);
231         }
232
233         if (sblock.fs_maxcontig > 1)
234                 sblock.fs_contigsumsize = MIN(sblock.fs_maxcontig,FS_MAXCONTIG);
235
236         sblock.fs_bmask = ~(sblock.fs_bsize - 1);
237         sblock.fs_fmask = ~(sblock.fs_fsize - 1);
238         sblock.fs_qbmask = ~sblock.fs_bmask;
239         sblock.fs_qfmask = ~sblock.fs_fmask;
240         for (sblock.fs_bshift = 0, i = sblock.fs_bsize; i > 1; i >>= 1)
241                 sblock.fs_bshift++;
242         for (sblock.fs_fshift = 0, i = sblock.fs_fsize; i > 1; i >>= 1)
243                 sblock.fs_fshift++;
244         sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
245         for (sblock.fs_fragshift = 0, i = sblock.fs_frag; i > 1; i >>= 1)
246                 sblock.fs_fragshift++;
247         if (sblock.fs_frag > MAXFRAG) {
248                 printf("fragment size %d is too small, "
249                         "minimum with block size %d is %d\n",
250                     sblock.fs_fsize, sblock.fs_bsize,
251                     sblock.fs_bsize / MAXFRAG);
252                 exit(21);
253         }
254         sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / sectorsize);
255         sblock.fs_size = sblock.fs_providersize = fssize =
256             dbtofsb(&sblock, fssize);
257
258         if (Oflag <= 1) {
259                 sblock.fs_magic = FS_UFS1_MAGIC;
260                 sblock.fs_sblockloc = SBLOCK_UFS1;
261                 sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs1_daddr_t);
262                 sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
263                 sblock.fs_maxsymlinklen = ((UFS_NDADDR + UFS_NIADDR) *
264                     sizeof (ufs1_daddr_t));
265                 sblock.fs_old_inodefmt = FS_44INODEFMT;
266                 sblock.fs_old_cgoffset = 0;
267                 sblock.fs_old_cgmask = 0xffffffff;
268                 sblock.fs_old_size = sblock.fs_size;
269                 sblock.fs_old_rotdelay = 0;
270                 sblock.fs_old_rps = 60;
271                 sblock.fs_old_nspf = sblock.fs_fsize / sectorsize;
272                 sblock.fs_old_cpg = 1;
273                 sblock.fs_old_interleave = 1;
274                 sblock.fs_old_trackskew = 0;
275                 sblock.fs_old_cpc = 0;
276                 sblock.fs_old_postblformat = 1;
277                 sblock.fs_old_nrpos = 1;
278         } else {
279                 sblock.fs_magic = FS_UFS2_MAGIC;
280                 sblock.fs_sblockloc = SBLOCK_UFS2;
281                 sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs2_daddr_t);
282                 sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
283                 sblock.fs_maxsymlinklen = ((UFS_NDADDR + UFS_NIADDR) *
284                     sizeof (ufs2_daddr_t));
285                 if (ffs_opts->softupdates == 1)
286                         sblock.fs_flags |= FS_DOSOFTDEP;
287         }
288
289         sblock.fs_sblkno =
290             roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
291                 sblock.fs_frag);
292         sblock.fs_cblkno = (daddr_t)(sblock.fs_sblkno +
293             roundup(howmany(SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag));
294         sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
295         sblock.fs_maxfilesize = sblock.fs_bsize * UFS_NDADDR - 1;
296         for (sizepb = sblock.fs_bsize, i = 0; i < UFS_NIADDR; i++) {
297                 sizepb *= NINDIR(&sblock);
298                 sblock.fs_maxfilesize += sizepb;
299         }
300
301         /*
302          * Calculate the number of blocks to put into each cylinder group.
303          *
304          * This algorithm selects the number of blocks per cylinder
305          * group. The first goal is to have at least enough data blocks
306          * in each cylinder group to meet the density requirement. Once
307          * this goal is achieved we try to expand to have at least
308          * 1 cylinder group. Once this goal is achieved, we pack as
309          * many blocks into each cylinder group map as will fit.
310          *
311          * We start by calculating the smallest number of blocks that we
312          * can put into each cylinder group. If this is too big, we reduce
313          * the density until it fits.
314          */
315         origdensity = density;
316         for (;;) {
317                 fragsperinode = MAX(numfrags(&sblock, density), 1);
318                 minfpg = fragsperinode * INOPB(&sblock);
319                 if (minfpg > sblock.fs_size)
320                         minfpg = sblock.fs_size;
321                 sblock.fs_ipg = INOPB(&sblock);
322                 sblock.fs_fpg = roundup(sblock.fs_iblkno +
323                     sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
324                 if (sblock.fs_fpg < minfpg)
325                         sblock.fs_fpg = minfpg;
326                 sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
327                     INOPB(&sblock));
328                 sblock.fs_fpg = roundup(sblock.fs_iblkno +
329                     sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
330                 if (sblock.fs_fpg < minfpg)
331                         sblock.fs_fpg = minfpg;
332                 sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
333                     INOPB(&sblock));
334                 if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
335                         break;
336                 density -= sblock.fs_fsize;
337         }
338         if (density != origdensity)
339                 printf("density reduced from %d to %d\n", origdensity, density);
340
341         if (maxblkspercg <= 0 || maxblkspercg >= fssize)
342                 maxblkspercg = fssize - 1;
343         /*
344          * Start packing more blocks into the cylinder group until
345          * it cannot grow any larger, the number of cylinder groups
346          * drops below 1, or we reach the size requested.
347          */
348         for ( ; sblock.fs_fpg < maxblkspercg; sblock.fs_fpg += sblock.fs_frag) {
349                 sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
350                     INOPB(&sblock));
351                 if (sblock.fs_size / sblock.fs_fpg < 1)
352                         break;
353                 if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
354                         continue;
355                 if (CGSIZE(&sblock) == (unsigned long)sblock.fs_bsize)
356                         break;
357                 sblock.fs_fpg -= sblock.fs_frag;
358                 sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
359                     INOPB(&sblock));
360                 break;
361         }
362         /*
363          * Check to be sure that the last cylinder group has enough blocks
364          * to be viable. If it is too small, reduce the number of blocks
365          * per cylinder group which will have the effect of moving more
366          * blocks into the last cylinder group.
367          */
368         optimalfpg = sblock.fs_fpg;
369         for (;;) {
370                 sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
371                 lastminfpg = roundup(sblock.fs_iblkno +
372                     sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
373                 if (sblock.fs_size < lastminfpg) {
374                         printf("Filesystem size %lld < minimum size of %d\n",
375                             (long long)sblock.fs_size, lastminfpg);
376                         exit(28);
377                 }
378                 if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
379                     sblock.fs_size % sblock.fs_fpg == 0)
380                         break;
381                 sblock.fs_fpg -= sblock.fs_frag;
382                 sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
383                     INOPB(&sblock));
384         }
385         if (optimalfpg != sblock.fs_fpg)
386                 printf("Reduced frags per cylinder group from %d to %d %s\n",
387                    optimalfpg, sblock.fs_fpg, "to enlarge last cyl group");
388         sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
389         sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
390         if (Oflag <= 1) {
391                 sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
392                 sblock.fs_old_nsect = sblock.fs_old_spc;
393                 sblock.fs_old_npsect = sblock.fs_old_spc;
394                 sblock.fs_old_ncyl = sblock.fs_ncg;
395         }
396
397         /*
398          * fill in remaining fields of the super block
399          */
400         sblock.fs_csaddr = cgdmin(&sblock, 0);
401         sblock.fs_cssize =
402             fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
403
404         /*
405          * Setup memory for temporary in-core cylgroup summaries.
406          * Cribbed from ffs_mountfs().
407          */
408         size = sblock.fs_cssize;
409         if (sblock.fs_contigsumsize > 0)
410                 size += sblock.fs_ncg * sizeof(int32_t);
411         space = ecalloc(1, size);
412         sblock.fs_si = ecalloc(1, sizeof(struct fs_summary_info));
413         sblock.fs_csp = space;
414         space = (char *)space + sblock.fs_cssize;
415         if (sblock.fs_contigsumsize > 0) {
416                 int32_t *lp;
417
418                 sblock.fs_maxcluster = lp = space;
419                 for (i = 0; i < sblock.fs_ncg; i++)
420                 *lp++ = sblock.fs_contigsumsize;
421         }
422
423         sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
424         if (sblock.fs_sbsize > SBLOCKSIZE)
425                 sblock.fs_sbsize = SBLOCKSIZE;
426         sblock.fs_minfree = minfree;
427         sblock.fs_maxcontig = maxcontig;
428         sblock.fs_maxbpg = maxbpg;
429         sblock.fs_optim = opt;
430         sblock.fs_cgrotor = 0;
431         sblock.fs_pendingblocks = 0;
432         sblock.fs_pendinginodes = 0;
433         sblock.fs_cstotal.cs_ndir = 0;
434         sblock.fs_cstotal.cs_nbfree = 0;
435         sblock.fs_cstotal.cs_nifree = 0;
436         sblock.fs_cstotal.cs_nffree = 0;
437         sblock.fs_fmod = 0;
438         sblock.fs_ronly = 0;
439         sblock.fs_state = 0;
440         sblock.fs_clean = FS_ISCLEAN;
441         sblock.fs_ronly = 0;
442         sblock.fs_id[0] = tstamp;
443         sblock.fs_id[1] = random();
444         sblock.fs_fsmnt[0] = '\0';
445         csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
446         sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
447             sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
448         sblock.fs_cstotal.cs_nbfree =
449             fragstoblks(&sblock, sblock.fs_dsize) -
450             howmany(csfrags, sblock.fs_frag);
451         sblock.fs_cstotal.cs_nffree =
452             fragnum(&sblock, sblock.fs_size) +
453             (fragnum(&sblock, csfrags) > 0 ?
454             sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
455         sblock.fs_cstotal.cs_nifree =
456             sblock.fs_ncg * sblock.fs_ipg - UFS_ROOTINO;
457         sblock.fs_cstotal.cs_ndir = 0;
458         sblock.fs_dsize -= csfrags;
459         sblock.fs_time = tstamp;
460         if (Oflag <= 1) {
461                 sblock.fs_old_time = tstamp;
462                 sblock.fs_old_dsize = sblock.fs_dsize;
463                 sblock.fs_old_csaddr = sblock.fs_csaddr;
464                 sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
465                 sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
466                 sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
467                 sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
468         }
469         /*
470          * Dump out summary information about file system.
471          */
472 #define B2MBFACTOR (1 / (1024.0 * 1024.0))
473         printf("%s: %.1fMB (%lld sectors) block size %d, "
474                "fragment size %d\n",
475             fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
476             (long long)fsbtodb(&sblock, sblock.fs_size),
477             sblock.fs_bsize, sblock.fs_fsize);
478         printf("\tusing %d cylinder groups of %.2fMB, %d blks, "
479                "%d inodes.\n",
480             sblock.fs_ncg,
481             (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
482             sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
483 #undef B2MBFACTOR
484         /*
485          * Now determine how wide each column will be, and calculate how
486          * many columns will fit in a 76 char line. 76 is the width of the
487          * subwindows in sysinst.
488          */
489         printcolwidth = count_digits(
490                         fsbtodb(&sblock, cgsblock(&sblock, sblock.fs_ncg -1)));
491         nprintcols = 76 / (printcolwidth + 2);
492
493         /*
494          * allocate space for superblock, cylinder group map, and
495          * two sets of inode blocks.
496          */
497         if (sblock.fs_bsize < SBLOCKSIZE)
498                 iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
499         else
500                 iobufsize = 4 * sblock.fs_bsize;
501         iobuf = ecalloc(1, iobufsize);
502         /*
503          * Make a copy of the superblock into the buffer that we will be
504          * writing out in each cylinder group.
505          */
506         memcpy(writebuf, &sblock, sbsize);
507         if (fsopts->needswap)
508                 ffs_sb_swap(&sblock, (struct fs*)writebuf);
509         memcpy(iobuf, writebuf, SBLOCKSIZE);
510
511         printf("super-block backups (for fsck -b #) at:");
512         for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
513                 initcg(cylno, tstamp, fsopts);
514                 if (cylno % nprintcols == 0)
515                         printf("\n");
516                 printf(" %*lld,", printcolwidth,
517                         (long long)fsbtodb(&sblock, cgsblock(&sblock, cylno)));
518                 fflush(stdout);
519         }
520         printf("\n");
521
522         /*
523          * Now construct the initial file system,
524          * then write out the super-block.
525          */
526         sblock.fs_time = tstamp;
527         if (Oflag <= 1) {
528                 sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
529                 sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
530                 sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
531                 sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
532         }
533         if (fsopts->needswap)
534                 sblock.fs_flags |= FS_SWAPPED;
535         ffs_write_superblock(&sblock, fsopts);
536         return (&sblock);
537 }
538
539 /*
540  * Write out the superblock and its duplicates,
541  * and the cylinder group summaries
542  */
543 void
544 ffs_write_superblock(struct fs *fs, const fsinfo_t *fsopts)
545 {
546         int size, blks, i, saveflag;
547         uint32_t cylno;
548         void *space;
549         char *wrbuf;
550
551         saveflag = fs->fs_flags & FS_INTERNAL;
552         fs->fs_flags &= ~FS_INTERNAL;
553
554         memcpy(writebuf, &sblock, sbsize);
555         if (fsopts->needswap)
556                 ffs_sb_swap(fs, (struct fs*)writebuf);
557         ffs_wtfs(fs->fs_sblockloc / sectorsize, sbsize, writebuf, fsopts);
558
559         /* Write out the duplicate super blocks */
560         for (cylno = 0; cylno < fs->fs_ncg; cylno++)
561                 ffs_wtfs(fsbtodb(fs, cgsblock(fs, cylno)),
562                     sbsize, writebuf, fsopts);
563
564         /* Write out the cylinder group summaries */
565         size = fs->fs_cssize;
566         blks = howmany(size, fs->fs_fsize);
567         space = (void *)fs->fs_csp;
568         wrbuf = emalloc(size);
569         for (i = 0; i < blks; i+= fs->fs_frag) {
570                 size = fs->fs_bsize;
571                 if (i + fs->fs_frag > blks)
572                         size = (blks - i) * fs->fs_fsize;
573                 if (fsopts->needswap)
574                         ffs_csum_swap((struct csum *)space,
575                             (struct csum *)wrbuf, size);
576                 else
577                         memcpy(wrbuf, space, (u_int)size);
578                 ffs_wtfs(fsbtodb(fs, fs->fs_csaddr + i), size, wrbuf, fsopts);
579                 space = (char *)space + size;
580         }
581         free(wrbuf);
582         fs->fs_flags |= saveflag;
583 }
584
585 /*
586  * Initialize a cylinder group.
587  */
588 static void
589 initcg(uint32_t cylno, time_t utime, const fsinfo_t *fsopts)
590 {
591         daddr_t cbase, dmax;
592         int32_t blkno;
593         uint32_t i, j, d, dlower, dupper;
594         struct ufs1_dinode *dp1;
595         struct ufs2_dinode *dp2;
596         int start;
597
598         /*
599          * Determine block bounds for cylinder group.
600          * Allow space for super block summary information in first
601          * cylinder group.
602          */
603         cbase = cgbase(&sblock, cylno);
604         dmax = cbase + sblock.fs_fpg;
605         if (dmax > sblock.fs_size)
606                 dmax = sblock.fs_size;
607         dlower = cgsblock(&sblock, cylno) - cbase;
608         dupper = cgdmin(&sblock, cylno) - cbase;
609         if (cylno == 0)
610                 dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
611         memset(&acg, 0, sblock.fs_cgsize);
612         acg.cg_time = utime;
613         acg.cg_magic = CG_MAGIC;
614         acg.cg_cgx = cylno;
615         acg.cg_niblk = sblock.fs_ipg;
616         acg.cg_initediblk = MIN(sblock.fs_ipg, 2 * INOPB(&sblock));
617         acg.cg_ndblk = dmax - cbase;
618         if (sblock.fs_contigsumsize > 0)
619                 acg.cg_nclusterblks = acg.cg_ndblk >> sblock.fs_fragshift;
620         start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
621         if (Oflag == 2) {
622                 acg.cg_iusedoff = start;
623         } else {
624                 if (cylno == sblock.fs_ncg - 1)
625                         acg.cg_old_ncyl = howmany(acg.cg_ndblk,
626                             sblock.fs_fpg / sblock.fs_old_cpg);
627                 else
628                         acg.cg_old_ncyl = sblock.fs_old_cpg;
629                 acg.cg_old_time = acg.cg_time;
630                 acg.cg_time = 0;
631                 acg.cg_old_niblk = acg.cg_niblk;
632                 acg.cg_niblk = 0;
633                 acg.cg_initediblk = 0;
634                 acg.cg_old_btotoff = start;
635                 acg.cg_old_boff = acg.cg_old_btotoff +
636                     sblock.fs_old_cpg * sizeof(int32_t);
637                 acg.cg_iusedoff = acg.cg_old_boff +
638                     sblock.fs_old_cpg * sizeof(u_int16_t);
639         }
640         acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
641         if (sblock.fs_contigsumsize <= 0) {
642                 acg.cg_nextfreeoff = acg.cg_freeoff +
643                    howmany(sblock.fs_fpg, CHAR_BIT);
644         } else {
645                 acg.cg_clustersumoff = acg.cg_freeoff +
646                     howmany(sblock.fs_fpg, CHAR_BIT) - sizeof(int32_t);
647                 acg.cg_clustersumoff =
648                     roundup(acg.cg_clustersumoff, sizeof(int32_t));
649                 acg.cg_clusteroff = acg.cg_clustersumoff +
650                     (sblock.fs_contigsumsize + 1) * sizeof(int32_t);
651                 acg.cg_nextfreeoff = acg.cg_clusteroff +
652                     howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
653         }
654         if (acg.cg_nextfreeoff > (uint32_t)sblock.fs_cgsize) {
655                 printf("Panic: cylinder group too big\n");
656                 exit(37);
657         }
658         acg.cg_cs.cs_nifree += sblock.fs_ipg;
659         if (cylno == 0)
660                 for (i = 0; i < UFS_ROOTINO; i++) {
661                         setbit(cg_inosused_swap(&acg, 0), i);
662                         acg.cg_cs.cs_nifree--;
663                 }
664         if (cylno > 0) {
665                 /*
666                  * In cylno 0, beginning space is reserved
667                  * for boot and super blocks.
668                  */
669                 for (d = 0, blkno = 0; d < dlower;) {
670                         ffs_setblock(&sblock, cg_blksfree_swap(&acg, 0), blkno);
671                         if (sblock.fs_contigsumsize > 0)
672                                 setbit(cg_clustersfree_swap(&acg, 0), blkno);
673                         acg.cg_cs.cs_nbfree++;
674                         d += sblock.fs_frag;
675                         blkno++;
676                 }
677         }
678         if ((i = (dupper & (sblock.fs_frag - 1))) != 0) {
679                 acg.cg_frsum[sblock.fs_frag - i]++;
680                 for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
681                         setbit(cg_blksfree_swap(&acg, 0), dupper);
682                         acg.cg_cs.cs_nffree++;
683                 }
684         }
685         for (d = dupper, blkno = dupper >> sblock.fs_fragshift;
686              d + sblock.fs_frag <= acg.cg_ndblk; ) {
687                 ffs_setblock(&sblock, cg_blksfree_swap(&acg, 0), blkno);
688                 if (sblock.fs_contigsumsize > 0)
689                         setbit(cg_clustersfree_swap(&acg, 0), blkno);
690                 acg.cg_cs.cs_nbfree++;
691                 d += sblock.fs_frag;
692                 blkno++;
693         }
694         if (d < acg.cg_ndblk) {
695                 acg.cg_frsum[acg.cg_ndblk - d]++;
696                 for (; d < acg.cg_ndblk; d++) {
697                         setbit(cg_blksfree_swap(&acg, 0), d);
698                         acg.cg_cs.cs_nffree++;
699                 }
700         }
701         if (sblock.fs_contigsumsize > 0) {
702                 int32_t *sump = cg_clustersum_swap(&acg, 0);
703                 u_char *mapp = cg_clustersfree_swap(&acg, 0);
704                 int map = *mapp++;
705                 int bit = 1;
706                 int run = 0;
707
708                 for (i = 0; i < acg.cg_nclusterblks; i++) {
709                         if ((map & bit) != 0) {
710                                 run++;
711                         } else if (run != 0) {
712                                 if (run > sblock.fs_contigsumsize)
713                                         run = sblock.fs_contigsumsize;
714                                 sump[run]++;
715                                 run = 0;
716                         }
717                         if ((i & (CHAR_BIT - 1)) != (CHAR_BIT - 1)) {
718                                 bit <<= 1;
719                         } else {
720                                 map = *mapp++;
721                                 bit = 1;
722                         }
723                 }
724                 if (run != 0) {
725                         if (run > sblock.fs_contigsumsize)
726                                 run = sblock.fs_contigsumsize;
727                         sump[run]++;
728                 }
729         }
730         sblock.fs_cs(&sblock, cylno) = acg.cg_cs;
731         /*
732          * Write out the duplicate super block, the cylinder group map
733          * and two blocks worth of inodes in a single write.
734          */
735         start = MAX(sblock.fs_bsize, SBLOCKSIZE);
736         memcpy(&iobuf[start], &acg, sblock.fs_cgsize);
737         if (fsopts->needswap)
738                 ffs_cg_swap(&acg, (struct cg*)&iobuf[start], &sblock);
739         start += sblock.fs_bsize;
740         dp1 = (struct ufs1_dinode *)(&iobuf[start]);
741         dp2 = (struct ufs2_dinode *)(&iobuf[start]);
742         for (i = 0; i < acg.cg_initediblk; i++) {
743                 if (sblock.fs_magic == FS_UFS1_MAGIC) {
744                         /* No need to swap, it'll stay random */
745                         dp1->di_gen = random();
746                         dp1++;
747                 } else {
748                         dp2->di_gen = random();
749                         dp2++;
750                 }
751         }
752         ffs_wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf,
753             fsopts);
754         /*
755          * For the old file system, we have to initialize all the inodes.
756          */
757         if (Oflag <= 1) {
758                 for (i = 2 * sblock.fs_frag;
759                      i < sblock.fs_ipg / INOPF(&sblock);
760                      i += sblock.fs_frag) {
761                         dp1 = (struct ufs1_dinode *)(&iobuf[start]);
762                         for (j = 0; j < INOPB(&sblock); j++) {
763                                 dp1->di_gen = random();
764                                 dp1++;
765                         }
766                         ffs_wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
767                             sblock.fs_bsize, &iobuf[start], fsopts);
768                 }
769         }
770 }
771
772 /*
773  * read a block from the file system
774  */
775 void
776 ffs_rdfs(daddr_t bno, int size, void *bf, const fsinfo_t *fsopts)
777 {
778         int n;
779         off_t offset;
780
781         offset = bno * fsopts->sectorsize + fsopts->offset;
782         if (lseek(fsopts->fd, offset, SEEK_SET) < 0)
783                 err(1, "%s: seek error for sector %lld", __func__,
784                     (long long)bno);
785         n = read(fsopts->fd, bf, size);
786         if (n == -1) {
787                 abort();
788                 err(1, "%s: read error bno %lld size %d", __func__,
789                     (long long)bno, size);
790         }
791         else if (n != size)
792                 errx(1, "%s: read error for sector %lld", __func__,
793                     (long long)bno);
794 }
795
796 /*
797  * write a block to the file system
798  */
799 void
800 ffs_wtfs(daddr_t bno, int size, void *bf, const fsinfo_t *fsopts)
801 {
802         int n;
803         off_t offset;
804
805         offset = bno * fsopts->sectorsize + fsopts->offset;
806         if (lseek(fsopts->fd, offset, SEEK_SET) < 0)
807                 err(1, "%s: seek error for sector %lld", __func__,
808                     (long long)bno);
809         n = write(fsopts->fd, bf, size);
810         if (n == -1)
811                 err(1, "%s: write error for sector %lld", __func__,
812                     (long long)bno);
813         else if (n != size)
814                 errx(1, "%s: write error for sector %lld", __func__,
815                     (long long)bno);
816 }
817
818
819 /* Determine how many digits are needed to print a given integer */
820 static int
821 count_digits(int num)
822 {
823         int ndig;
824
825         for(ndig = 1; num > 9; num /=10, ndig++);
826
827         return (ndig);
828 }
829
830 static int
831 ilog2(int val)
832 {
833         u_int n;
834
835         for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
836                 if (1 << n == val)
837                         return (n);
838         errx(1, "%s: %d is not a power of 2", __func__, val);
839 }