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