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