Home | History | Annotate | Line # | Download | only in newfs
mkfs.c revision 1.84
      1 /*	$NetBSD: mkfs.c,v 1.84 2003/10/29 08:14:13 lukem Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1980, 1989, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Copyright (c) 2002 Networks Associates Technology, Inc.
     34  * All rights reserved.
     35  *
     36  * This software was developed for the FreeBSD Project by Marshall
     37  * Kirk McKusick and Network Associates Laboratories, the Security
     38  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
     39  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
     40  * research program
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  */
     70 
     71 #include <sys/cdefs.h>
     72 #ifndef lint
     73 #if 0
     74 static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
     75 #else
     76 __RCSID("$NetBSD: mkfs.c,v 1.84 2003/10/29 08:14:13 lukem Exp $");
     77 #endif
     78 #endif /* not lint */
     79 
     80 #include <sys/param.h>
     81 #include <sys/mman.h>
     82 #include <sys/time.h>
     83 #include <sys/resource.h>
     84 #include <ufs/ufs/dinode.h>
     85 #include <ufs/ufs/dir.h>
     86 #include <ufs/ufs/ufs_bswap.h>
     87 #include <ufs/ffs/fs.h>
     88 #include <ufs/ffs/ffs_extern.h>
     89 #include <sys/disklabel.h>
     90 
     91 #include <err.h>
     92 #include <errno.h>
     93 #include <string.h>
     94 #include <unistd.h>
     95 #include <stdlib.h>
     96 #include <stddef.h>
     97 
     98 #ifndef STANDALONE
     99 #include <stdio.h>
    100 #endif
    101 
    102 #include "extern.h"
    103 
    104 union dinode {
    105 	struct ufs1_dinode dp1;
    106 	struct ufs2_dinode dp2;
    107 };
    108 
    109 static void initcg(int, const struct timeval *);
    110 static int fsinit(const struct timeval *, mode_t, uid_t, gid_t);
    111 static int makedir(struct direct *, int);
    112 static daddr_t alloc(int, int);
    113 static void iput(union dinode *, ino_t);
    114 static void rdfs(daddr_t, int, void *);
    115 static void wtfs(daddr_t, int, void *);
    116 static int isblock(struct fs *, unsigned char *, int);
    117 static void clrblock(struct fs *, unsigned char *, int);
    118 static void setblock(struct fs *, unsigned char *, int);
    119 static int ilog2(int);
    120 static void zap_old_sblock(int);
    121 #ifdef MFS
    122 static void calc_memfree(void);
    123 static void *mkfs_malloc(size_t size);
    124 #endif
    125 
    126 static int count_digits(uint64_t);
    127 
    128 /*
    129  * make file system for cylinder-group style file systems
    130  */
    131 #define	UMASK		0755
    132 #define	POWEROF2(num)	(((num) & ((num) - 1)) == 0)
    133 
    134 union {
    135 	struct fs fs;
    136 	char pad[SBLOCKSIZE];
    137 } fsun;
    138 #define	sblock	fsun.fs
    139 
    140 struct	csum *fscs_0;		/* first block of cylinder summaries */
    141 struct	csum *fscs_next;	/* place for next summary */
    142 struct	csum *fscs_end;		/* end of summary buffer */
    143 struct	csum *fscs_reset;	/* place for next summary after write */
    144 uint	fs_csaddr;		/* fragment number to write to */
    145 
    146 union {
    147 	struct cg cg;
    148 	char pad[MAXBSIZE];
    149 } cgun;
    150 #define	acg	cgun.cg
    151 
    152 #define DIP(dp, field) \
    153 	((sblock.fs_magic == FS_UFS1_MAGIC) ? \
    154 	(dp)->dp1.di_##field : (dp)->dp2.di_##field)
    155 
    156 char *iobuf;
    157 int iobufsize;
    158 
    159 int	fsi, fso;
    160 
    161 void
    162 mkfs(struct partition *pp, const char *fsys, int fi, int fo,
    163     mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
    164 {
    165 	uint fragsperinodeblk, ncg;
    166 	uint cgzero;
    167 	uint64_t inodeblks, cgall;
    168 	int32_t cylno, i, csfrags;
    169 	struct timeval tv;
    170 	long long sizepb;
    171 	int nprintcols, printcolwidth;
    172 
    173 #ifndef STANDALONE
    174 	gettimeofday(&tv, NULL);
    175 #endif
    176 #ifdef MFS
    177 	if (mfs) {
    178 		calc_memfree();
    179 		if (fssize * sectorsize > memleft)
    180 			fssize = memleft / sectorsize;
    181 		if ((membase = mkfs_malloc(fssize * sectorsize)) == 0)
    182 			exit(12);
    183 	}
    184 #endif
    185 	fsi = fi;
    186 	fso = fo;
    187 	if (Oflag == 0) {
    188 		sblock.fs_old_inodefmt = FS_42INODEFMT;
    189 		sblock.fs_maxsymlinklen = 0;
    190 		sblock.fs_old_flags = 0;
    191 	} else {
    192 		sblock.fs_old_inodefmt = FS_44INODEFMT;
    193 		sblock.fs_maxsymlinklen = (Oflag == 1 ? MAXSYMLINKLEN_UFS1 :
    194 		    MAXSYMLINKLEN_UFS2);
    195 		sblock.fs_old_flags = FS_FLAGS_UPDATED;
    196 		sblock.fs_flags = 0;
    197 	}
    198 
    199 	/*
    200 	 * collect and verify the filesystem density info
    201 	 */
    202 	sblock.fs_avgfilesize = avgfilesize;
    203 	sblock.fs_avgfpdir = avgfpdir;
    204 	if (sblock.fs_avgfilesize <= 0) {
    205 		printf("illegal expected average file size %d\n",
    206 		    sblock.fs_avgfilesize);
    207 		exit(14);
    208 	}
    209 	if (sblock.fs_avgfpdir <= 0) {
    210 		printf("illegal expected number of files per directory %d\n",
    211 		    sblock.fs_avgfpdir);
    212 		exit(15);
    213 	}
    214 	/*
    215 	 * collect and verify the block and fragment sizes
    216 	 */
    217 	sblock.fs_bsize = bsize;
    218 	sblock.fs_fsize = fsize;
    219 	if (!POWEROF2(sblock.fs_bsize)) {
    220 		printf("block size must be a power of 2, not %d\n",
    221 		    sblock.fs_bsize);
    222 		exit(16);
    223 	}
    224 	if (!POWEROF2(sblock.fs_fsize)) {
    225 		printf("fragment size must be a power of 2, not %d\n",
    226 		    sblock.fs_fsize);
    227 		exit(17);
    228 	}
    229 	if (sblock.fs_fsize < sectorsize) {
    230 		printf("fragment size %d is too small, minimum is %d\n",
    231 		    sblock.fs_fsize, sectorsize);
    232 		exit(18);
    233 	}
    234 	if (sblock.fs_bsize < MINBSIZE) {
    235 		printf("block size %d is too small, minimum is %d\n",
    236 		    sblock.fs_bsize, MINBSIZE);
    237 		exit(19);
    238 	}
    239 	if (sblock.fs_bsize > MAXBSIZE) {
    240 		printf("block size %d is too large, maximum is %d\n",
    241 		    sblock.fs_bsize, MAXBSIZE);
    242 		exit(19);
    243 	}
    244 	if (sblock.fs_bsize < sblock.fs_fsize) {
    245 		printf("block size (%d) cannot be smaller than fragment size (%d)\n",
    246 		    sblock.fs_bsize, sblock.fs_fsize);
    247 		exit(20);
    248 	}
    249 
    250 	if (maxbsize < bsize || !POWEROF2(maxbsize)) {
    251 		sblock.fs_maxbsize = sblock.fs_bsize;
    252 	} else if (sblock.fs_maxbsize > FS_MAXCONTIG * sblock.fs_bsize) {
    253 		sblock.fs_maxbsize = FS_MAXCONTIG * sblock.fs_bsize;
    254 	} else {
    255 		sblock.fs_maxbsize = maxbsize;
    256 	}
    257 	sblock.fs_maxcontig = maxcontig;
    258 	if (sblock.fs_maxcontig < sblock.fs_maxbsize / sblock.fs_bsize) {
    259 		sblock.fs_maxcontig = sblock.fs_maxbsize / sblock.fs_bsize;
    260 		printf("Maxcontig raised to %d\n", sblock.fs_maxbsize);
    261 	}
    262 	if (sblock.fs_maxcontig > 1)
    263 		sblock.fs_contigsumsize = MIN(sblock.fs_maxcontig,FS_MAXCONTIG);
    264 
    265 	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
    266 	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
    267 	sblock.fs_qbmask = ~sblock.fs_bmask;
    268 	sblock.fs_qfmask = ~sblock.fs_fmask;
    269 	for (sblock.fs_bshift = 0, i = sblock.fs_bsize; i > 1; i >>= 1)
    270 		sblock.fs_bshift++;
    271 	for (sblock.fs_fshift = 0, i = sblock.fs_fsize; i > 1; i >>= 1)
    272 		sblock.fs_fshift++;
    273 	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
    274 	for (sblock.fs_fragshift = 0, i = sblock.fs_frag; i > 1; i >>= 1)
    275 		sblock.fs_fragshift++;
    276 	if (sblock.fs_frag > MAXFRAG) {
    277 		printf("fragment size %d is too small, "
    278 			"minimum with block size %d is %d\n",
    279 		    sblock.fs_fsize, sblock.fs_bsize,
    280 		    sblock.fs_bsize / MAXFRAG);
    281 		exit(21);
    282 	}
    283 	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / sectorsize);
    284 	sblock.fs_size = dbtofsb(&sblock, fssize);
    285 	if (Oflag <= 1) {
    286 		if (sblock.fs_size >= 1ull << 31) {
    287 			printf("Too many fragments (0x%" PRIx64
    288 			    ") for a UFS1 filesystem\n", sblock.fs_size);
    289 			exit(22);
    290 		}
    291 		sblock.fs_magic = FS_UFS1_MAGIC;
    292 		sblock.fs_sblockloc = SBLOCK_UFS1;
    293 		sblock.fs_nindir = sblock.fs_bsize / sizeof(int32_t);
    294 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
    295 		sblock.fs_maxsymlinklen = ((NDADDR + NIADDR) *
    296 		    sizeof (int32_t));
    297 		sblock.fs_old_inodefmt = FS_44INODEFMT;
    298 		sblock.fs_old_cgoffset = 0;
    299 		sblock.fs_old_cgmask = 0xffffffff;
    300 		sblock.fs_old_size = sblock.fs_size;
    301 		sblock.fs_old_rotdelay = 0;
    302 		sblock.fs_old_rps = 60;
    303 		sblock.fs_old_nspf = sblock.fs_fsize / sectorsize;
    304 		sblock.fs_old_cpg = 1;
    305 		sblock.fs_old_interleave = 1;
    306 		sblock.fs_old_trackskew = 0;
    307 		sblock.fs_old_cpc = 0;
    308 		sblock.fs_old_postblformat = FS_DYNAMICPOSTBLFMT;
    309 		sblock.fs_old_nrpos = 1;
    310 	} else {
    311 		sblock.fs_magic = FS_UFS2_MAGIC;
    312 		sblock.fs_sblockloc = SBLOCK_UFS2;
    313 		sblock.fs_nindir = sblock.fs_bsize / sizeof(int64_t);
    314 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
    315 		sblock.fs_maxsymlinklen = ((NDADDR + NIADDR) *
    316 		    sizeof (int64_t));
    317 	}
    318 
    319 	sblock.fs_sblkno =
    320 	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
    321 		sblock.fs_frag);
    322 	sblock.fs_cblkno = (daddr_t)(sblock.fs_sblkno +
    323 	    roundup(howmany(SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag));
    324 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
    325 	sblock.fs_maxfilesize = sblock.fs_bsize * NDADDR - 1;
    326 	for (sizepb = sblock.fs_bsize, i = 0; i < NIADDR; i++) {
    327 		sizepb *= NINDIR(&sblock);
    328 		sblock.fs_maxfilesize += sizepb;
    329 	}
    330 
    331 	/*
    332 	 * Calculate the number of blocks to put into each cylinder group.
    333 	 *
    334 	 * The cylinder group size is limited because the data structure
    335 	 * must fit into a single block.
    336 	 * We try to have as few cylinder groups as possible, with a proviso
    337 	 * that we create at least MINCYLGRPS (==4) except for small
    338 	 * filesystems.
    339 	 *
    340 	 * This algorithm works out how many blocks of inodes would be
    341 	 * needed to fill the entire volume at the specified density.
    342 	 * It then looks at how big the 'cylinder block' would have to
    343 	 * be and, assuming that it is linearly related to the number
    344 	 * of inodes and blocks how many cylinder groups are needed to
    345 	 * keep the cylinder block below the filesystem block size.
    346 	 *
    347 	 * The cylinder groups are then all created with the average size.
    348 	 *
    349 	 * Space taken by the red tape on cylinder groups other than the
    350 	 * first is ignored.
    351 	 */
    352 
    353 	/* There must be space for 1 inode block and 2 data blocks */
    354 	if (sblock.fs_size < sblock.fs_iblkno + 3 * sblock.fs_frag) {
    355 		printf("Filesystem size %lld < minimum size of %d\n",
    356 		    (long long)sblock.fs_size, sblock.fs_iblkno + 3 * sblock.fs_frag);
    357 		exit(23);
    358 	}
    359 	if (num_inodes != 0)
    360 		inodeblks = howmany(num_inodes, INOPB(&sblock));
    361 	else {
    362 		/*
    363 		 * Calculate 'per inode block' so we can allocate less than
    364 		 * 1 fragment per inode - useful for /dev.
    365 		 */
    366 		fragsperinodeblk = MAX(numfrags(&sblock,
    367 					density * INOPB(&sblock)), 1);
    368 		inodeblks = (sblock.fs_size - sblock.fs_iblkno) /
    369 			(sblock.fs_frag + fragsperinodeblk);
    370 	}
    371 	if (inodeblks == 0)
    372 		inodeblks = 1;
    373 	/* Ensure that there are at least 2 data blocks (or we fail below) */
    374 	if (inodeblks > (sblock.fs_size - sblock.fs_iblkno)/sblock.fs_frag - 2)
    375 		inodeblks = (sblock.fs_size-sblock.fs_iblkno)/sblock.fs_frag-2;
    376 	/* Even UFS2 limits number of inodes to 2^31 (fs_ipg is int32_t) */
    377 	if (inodeblks * INOPB(&sblock) >= 1ull << 31)
    378 		inodeblks = ((1ull << 31) - NBBY) / INOPB(&sblock);
    379 	/*
    380 	 * See what would happen if we tried to use 1 cylinder group.
    381 	 * Assume space linear, so work out number of cylinder groups needed.
    382 	 * Subtract one from the allowed size to compensate for rounding
    383 	 * a number of bits up to a complete byte.
    384 	 */
    385 	cgzero = CGSIZE_IF(&sblock, 0, 0);
    386 	cgall = CGSIZE_IF(&sblock, inodeblks * INOPB(&sblock), sblock.fs_size);
    387 	ncg = howmany(cgall - cgzero, sblock.fs_bsize - cgzero - 1);
    388 	if (ncg < MINCYLGRPS) {
    389 		/*
    390 		 * We would like to allocate MINCLYGRPS cylinder groups,
    391 		 * but for small file sytems (especially ones with a lot
    392 		 * of inodes) this is not desirable (or possible).
    393 		 */
    394 		i = sblock.fs_size / 2 / (sblock.fs_iblkno +
    395 						inodeblks * sblock.fs_frag);
    396 		if (i > ncg)
    397 			ncg = i;
    398 		if (ncg > MINCYLGRPS)
    399 			ncg = MINCYLGRPS;
    400 		if (ncg > inodeblks)
    401 			ncg = inodeblks;
    402 	}
    403 	/*
    404 	 * Put an equal number of blocks in each cylinder group.
    405 	 * Round up so we don't have more fragments in the last CG than
    406 	 * the earlier ones (does that matter?), but kill a block if the
    407 	 * CGSIZE becomes too big (only happens if there are a lot of CGs).
    408 	 */
    409 	sblock.fs_fpg = roundup(howmany(sblock.fs_size, ncg), sblock.fs_frag);
    410 	i = CGSIZE_IF(&sblock, inodeblks * INOPB(&sblock) / ncg, sblock.fs_fpg);
    411 	if (i > sblock.fs_bsize)
    412 		sblock.fs_fpg -= (i - sblock.fs_bsize) * NBBY;
    413 	/* ... and recalculate how many cylinder groups we now need */
    414 	ncg = howmany(sblock.fs_size, sblock.fs_fpg);
    415 	inodeblks /= ncg;
    416 	if (inodeblks == 0)
    417 		inodeblks = 1;
    418 	sblock.fs_ipg = inodeblks * INOPB(&sblock);
    419 	/* Sanity check on our sums... */
    420 	if (CGSIZE(&sblock) > sblock.fs_bsize) {
    421 		printf("CGSIZE miscalculated %d > %d\n",
    422 		    (int)CGSIZE(&sblock), sblock.fs_bsize);
    423 		exit(24);
    424 	}
    425 	/* Check that the last cylinder group has enough space for the inodes */
    426 	i = sblock.fs_size - sblock.fs_fpg * (ncg - 1ull);
    427 	if (i < sblock.fs_iblkno + inodeblks * sblock.fs_frag) {
    428 		/*
    429 		 * Since we make all the cylinder groups the same size, the
    430 		 * last will only be small if there are a large number of
    431 		 * cylinder groups. If we pull even a fragment from each
    432 		 * of the other groups then the last CG will be overfull.
    433 		 * So we just kill the last CG.
    434 		 */
    435 		ncg--;
    436 		sblock.fs_size -= i;
    437 	}
    438 	sblock.fs_ncg = ncg;
    439 
    440 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
    441 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
    442 	if (Oflag <= 1) {
    443 		sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
    444 		sblock.fs_old_nsect = sblock.fs_old_spc;
    445 		sblock.fs_old_npsect = sblock.fs_old_spc;
    446 		sblock.fs_old_ncyl = sblock.fs_ncg;
    447 	}
    448 
    449 	/*
    450 	 * Cylinder group summary information for each cylinder is written
    451 	 * into the first cylinder group.
    452 	 * Write this fragment by fragment, but doing the first CG last
    453 	 * (after we've taken stuff off for the structure itself and the
    454 	 * root directory.
    455 	 */
    456 	sblock.fs_csaddr = cgdmin(&sblock, 0);
    457 	sblock.fs_cssize =
    458 	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
    459 	if (512 % sizeof *fscs_0)
    460 		errx(1, "cylinder group summary doesn't fit in sectors");
    461 	fscs_0 = calloc(1, 2 * sblock.fs_fsize);
    462 	if (fscs_0 == NULL)
    463 		exit(39);
    464 	fs_csaddr = sblock.fs_csaddr;
    465 	fscs_next = fscs_0;
    466 	fscs_end = (void *)((char *)fscs_0 + 2 * sblock.fs_fsize);
    467 	fscs_reset = (void *)((char *)fscs_0 + sblock.fs_fsize);
    468 	/*
    469 	 * fill in remaining fields of the super block
    470 	 */
    471 	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
    472 	if (sblock.fs_sbsize > SBLOCKSIZE)
    473 		sblock.fs_sbsize = SBLOCKSIZE;
    474 	sblock.fs_minfree = minfree;
    475 	sblock.fs_maxcontig = maxcontig;
    476 	sblock.fs_maxbpg = maxbpg;
    477 	sblock.fs_optim = opt;
    478 	sblock.fs_cgrotor = 0;
    479 	sblock.fs_pendingblocks = 0;
    480 	sblock.fs_pendinginodes = 0;
    481 	sblock.fs_cstotal.cs_ndir = 0;
    482 	sblock.fs_cstotal.cs_nbfree = 0;
    483 	sblock.fs_cstotal.cs_nifree = 0;
    484 	sblock.fs_cstotal.cs_nffree = 0;
    485 	sblock.fs_fmod = 0;
    486 	sblock.fs_ronly = 0;
    487 	sblock.fs_state = 0;
    488 	sblock.fs_clean = FS_ISCLEAN;
    489 	sblock.fs_ronly = 0;
    490 	sblock.fs_id[0] = (long)tv.tv_sec;	/* XXXfvdl huh? */
    491 	sblock.fs_id[1] = arc4random() & INT32_MAX;
    492 	sblock.fs_fsmnt[0] = '\0';
    493 	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
    494 	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
    495 	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
    496 	sblock.fs_cstotal.cs_nbfree =
    497 	    fragstoblks(&sblock, sblock.fs_dsize) -
    498 	    howmany(csfrags, sblock.fs_frag);
    499 	sblock.fs_cstotal.cs_nffree =
    500 	    fragnum(&sblock, sblock.fs_size) +
    501 	    (fragnum(&sblock, csfrags) > 0 ?
    502 	    sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
    503 	sblock.fs_cstotal.cs_nifree = sblock.fs_ncg * sblock.fs_ipg - ROOTINO;
    504 	sblock.fs_cstotal.cs_ndir = 0;
    505 	sblock.fs_dsize -= csfrags;
    506 	sblock.fs_time = tv.tv_sec;
    507 	if (Oflag <= 1) {
    508 		sblock.fs_old_time = tv.tv_sec;
    509 		sblock.fs_old_dsize = sblock.fs_dsize;
    510 		sblock.fs_old_csaddr = sblock.fs_csaddr;
    511 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
    512 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
    513 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
    514 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
    515 	}
    516 	/*
    517 	 * Dump out summary information about file system.
    518 	 */
    519 	if (!mfs) {
    520 #define	B2MBFACTOR (1 / (1024.0 * 1024.0))
    521 		printf("%s: %.1fMB (%lld sectors) block size %d, "
    522 		       "fragment size %d\n",
    523 		    fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
    524 		    (long long)fsbtodb(&sblock, sblock.fs_size),
    525 		    sblock.fs_bsize, sblock.fs_fsize);
    526 		printf("\tusing %d cylinder groups of %.2fMB, %d blks, "
    527 		       "%d inodes.\n",
    528 		    sblock.fs_ncg,
    529 		    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
    530 		    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
    531 #undef B2MBFACTOR
    532 	}
    533 	/*
    534 	 * Now determine how wide each column will be, and calculate how
    535 	 * many columns will fit in a 80 char line.
    536 	 */
    537 	printcolwidth = count_digits(
    538 			fsbtodb(&sblock, cgsblock(&sblock, sblock.fs_ncg -1)));
    539 	nprintcols = 80 / (printcolwidth + 2);
    540 
    541 	/*
    542 	 * allocate space for superblock, cylinder group map, and
    543 	 * two sets of inode blocks.
    544 	 */
    545 	if (sblock.fs_bsize < SBLOCKSIZE)
    546 		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
    547 	else
    548 		iobufsize = 4 * sblock.fs_bsize;
    549 	if ((iobuf = malloc(iobufsize)) == 0) {
    550 		printf("Cannot allocate I/O buffer\n");
    551 		exit(38);
    552 	}
    553 	memset(iobuf, 0, iobufsize);
    554 
    555 	/*
    556 	 * We now start writing to the filesystem
    557 	 */
    558 
    559 	/*
    560 	 * Validate the given file system size.
    561 	 * Verify that its last block can actually be accessed.
    562 	 * Convert to file system fragment sized units.
    563 	 */
    564 	if (fssize <= 0) {
    565 		printf("preposterous size %lld\n", (long long)fssize);
    566 		exit(13);
    567 	}
    568 	wtfs(fssize - 1, sectorsize, iobuf);
    569 
    570 	/*
    571 	 * Ensure there is nothing that looks like a filesystem
    572 	 * superbock anywhere other than where ours will be.
    573 	 * If fsck finds the wrong one all hell breaks loose!
    574 	 */
    575 	for (i = 0; ; i++) {
    576 		static const int sblocklist[] = SBLOCKSEARCH;
    577 		int sblkoff = sblocklist[i];
    578 		int sz;
    579 		if (sblkoff == -1)
    580 			break;
    581 		/* Remove main superblock */
    582 		zap_old_sblock(sblkoff);
    583 		/* and all possible locations for the first alternate */
    584 		sblkoff += SBLOCKSIZE;
    585 		for (sz = SBLOCKSIZE; sz <= 0x10000; sz <<= 1)
    586 			zap_old_sblock(roundup(sblkoff, sz));
    587 	}
    588 
    589 	if (isappleufs) {
    590 		struct appleufslabel appleufs;
    591 		ffs_appleufs_set(&appleufs, appleufs_volname, tv.tv_sec);
    592 		wtfs(APPLEUFS_LABEL_OFFSET/sectorsize, APPLEUFS_LABEL_SIZE,
    593 		    &appleufs);
    594 	}
    595 
    596 	/*
    597 	 * Make a copy of the superblock into the buffer that we will be
    598 	 * writing out in each cylinder group.
    599 	 */
    600 	memcpy(iobuf, &sblock, sizeof sblock);
    601 	if (needswap)
    602 		ffs_sb_swap(&sblock, (struct fs *)iobuf);
    603 
    604 	if (!mfs)
    605 		printf("super-block backups (for fsck -b #) at:");
    606 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
    607 		initcg(cylno, &tv);
    608 		if (mfs)
    609 			continue;
    610 		if (cylno % nprintcols == 0)
    611 			printf("\n");
    612 		printf(" %*lld,", printcolwidth,
    613 			(long long)fsbtodb(&sblock, cgsblock(&sblock, cylno)));
    614 		fflush(stdout);
    615 	}
    616 	if (!mfs)
    617 		printf("\n");
    618 	if (Nflag && !mfs)
    619 		exit(0);
    620 
    621 	/*
    622 	 * Now construct the initial file system,
    623 	 */
    624 	if (fsinit(&tv, mfsmode, mfsuid, mfsgid) == 0 && mfs)
    625 		errx(1, "Error making filesystem");
    626 	sblock.fs_time = tv.tv_sec;
    627 	if (Oflag <= 1) {
    628 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
    629 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
    630 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
    631 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
    632 	}
    633 	/*
    634 	 * Write out the super-block and zeros until the first cg info
    635 	 */
    636 	memset(iobuf, 0, iobufsize);
    637         memcpy(iobuf, &sblock, sizeof sblock);
    638 	if (needswap)
    639 		ffs_sb_swap(&sblock, (struct fs *)iobuf);
    640         wtfs(sblock.fs_sblockloc / sectorsize,
    641 	    cgsblock(&sblock, 0) * sblock.fs_fsize - sblock.fs_sblockloc,
    642 	    iobuf);
    643 
    644 	/* Write out first and last cylinder summary sectors */
    645 	if (needswap)
    646 		ffs_csum_swap(fscs_0, fscs_0, sblock.fs_fsize);
    647 	wtfs(fsbtodb(&sblock, sblock.fs_csaddr), sblock.fs_fsize, fscs_0);
    648 
    649 	if (fscs_next > fscs_reset) {
    650 		if (needswap)
    651 			ffs_csum_swap(fscs_reset, fscs_reset, sblock.fs_fsize);
    652 		fs_csaddr++;
    653 		wtfs(fsbtodb(&sblock, fs_csaddr), sblock.fs_fsize, fscs_reset);
    654 	}
    655 
    656 	/*
    657 	 * Update information about this partion in pack
    658 	 * label, to that it may be updated on disk.
    659 	 */
    660 	if (pp == NULL)
    661 		return;
    662 	if (isappleufs)
    663 		pp->p_fstype = FS_APPLEUFS;
    664 	else
    665 		pp->p_fstype = FS_BSDFFS;
    666 	pp->p_fsize = sblock.fs_fsize;
    667 	pp->p_frag = sblock.fs_frag;
    668 	pp->p_cpg = sblock.fs_fpg;
    669 }
    670 
    671 /*
    672  * Initialize a cylinder group.
    673  */
    674 void
    675 initcg(int cylno, const struct timeval *tv)
    676 {
    677 	daddr_t cbase, dmax;
    678 	int32_t i, j, d, dlower, dupper, blkno;
    679 	struct ufs1_dinode *dp1;
    680 	struct ufs2_dinode *dp2;
    681 	int start;
    682 
    683 	/*
    684 	 * Determine block bounds for cylinder group.
    685 	 * Allow space for super block summary information in first
    686 	 * cylinder group.
    687 	 */
    688 	cbase = cgbase(&sblock, cylno);
    689 	dmax = cbase + sblock.fs_fpg;
    690 	if (dmax > sblock.fs_size)
    691 		dmax = sblock.fs_size;
    692 	dlower = cgsblock(&sblock, cylno) - cbase;
    693 	dupper = cgdmin(&sblock, cylno) - cbase;
    694 	if (cylno == 0) {
    695 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
    696 		if (dupper >= cgstart(&sblock, cylno + 1)) {
    697 			printf("\rToo many cylinder groups to fit summary "
    698 				"information into first cylinder group\n");
    699 			exit(40);
    700 		}
    701 	}
    702 	memset(&acg, 0, sblock.fs_cgsize);
    703 	acg.cg_magic = CG_MAGIC;
    704 	acg.cg_cgx = cylno;
    705 	acg.cg_ndblk = dmax - cbase;
    706 	if (sblock.fs_contigsumsize > 0)
    707 		acg.cg_nclusterblks = acg.cg_ndblk >> sblock.fs_fragshift;
    708 	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
    709 	if (Oflag == 2) {
    710 		acg.cg_time = tv->tv_sec;
    711 		acg.cg_niblk = sblock.fs_ipg;
    712 		acg.cg_initediblk = sblock.fs_ipg < 2 * INOPB(&sblock) ?
    713 		    sblock.fs_ipg : 2 * INOPB(&sblock);
    714 		acg.cg_iusedoff = start;
    715 	} else {
    716 		acg.cg_old_ncyl = sblock.fs_old_cpg;
    717 		acg.cg_old_time = tv->tv_sec;
    718 		acg.cg_old_niblk = sblock.fs_ipg;
    719 		acg.cg_old_btotoff = start;
    720 		acg.cg_old_boff = acg.cg_old_btotoff +
    721 		    sblock.fs_old_cpg * sizeof(int32_t);
    722 		acg.cg_iusedoff = acg.cg_old_boff +
    723 		    sblock.fs_old_cpg * sizeof(u_int16_t);
    724 	}
    725 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
    726 	if (sblock.fs_contigsumsize <= 0) {
    727 		acg.cg_nextfreeoff = acg.cg_freeoff +
    728 		   howmany(sblock.fs_fpg, CHAR_BIT);
    729 	} else {
    730 		acg.cg_clustersumoff = acg.cg_freeoff +
    731 		    howmany(sblock.fs_fpg, CHAR_BIT) - sizeof(int32_t);
    732 		if (isappleufs) {
    733 			/* Apple PR2216969 gives rationale for this change.
    734 			 * I believe they were mistaken, but we need to
    735 			 * duplicate it for compatibility.  -- dbj (at) NetBSD.org
    736 			 */
    737 			acg.cg_clustersumoff += sizeof(int32_t);
    738 		}
    739 		acg.cg_clustersumoff =
    740 		    roundup(acg.cg_clustersumoff, sizeof(int32_t));
    741 		acg.cg_clusteroff = acg.cg_clustersumoff +
    742 		    (sblock.fs_contigsumsize + 1) * sizeof(int32_t);
    743 		acg.cg_nextfreeoff = acg.cg_clusteroff +
    744 		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
    745 	}
    746 	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
    747 		printf("Panic: cylinder group too big\n");
    748 		exit(37);
    749 	}
    750 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
    751 	if (cylno == 0)
    752 		for (i = 0; i < ROOTINO; i++) {
    753 			setbit(cg_inosused(&acg, 0), i);
    754 			acg.cg_cs.cs_nifree--;
    755 		}
    756 	if (cylno > 0) {
    757 		/*
    758 		 * In cylno 0, beginning space is reserved
    759 		 * for boot and super blocks.
    760 		 */
    761 		for (d = 0, blkno = 0; d < dlower;) {
    762 			setblock(&sblock, cg_blksfree(&acg, 0), blkno);
    763 			if (sblock.fs_contigsumsize > 0)
    764 				setbit(cg_clustersfree(&acg, 0), blkno);
    765 			acg.cg_cs.cs_nbfree++;
    766 			d += sblock.fs_frag;
    767 			blkno++;
    768 		}
    769 	}
    770 	if ((i = (dupper & (sblock.fs_frag - 1))) != 0) {
    771 		acg.cg_frsum[sblock.fs_frag - i]++;
    772 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
    773 			setbit(cg_blksfree(&acg, 0), dupper);
    774 			acg.cg_cs.cs_nffree++;
    775 		}
    776 	}
    777 	for (d = dupper, blkno = dupper >> sblock.fs_fragshift;
    778 	     d + sblock.fs_frag <= acg.cg_ndblk; ) {
    779 		setblock(&sblock, cg_blksfree(&acg, 0), blkno);
    780 		if (sblock.fs_contigsumsize > 0)
    781 			setbit(cg_clustersfree(&acg, 0), blkno);
    782 		acg.cg_cs.cs_nbfree++;
    783 		d += sblock.fs_frag;
    784 		blkno++;
    785 	}
    786 	if (d < acg.cg_ndblk) {
    787 		acg.cg_frsum[acg.cg_ndblk - d]++;
    788 		for (; d < acg.cg_ndblk; d++) {
    789 			setbit(cg_blksfree(&acg, 0), d);
    790 			acg.cg_cs.cs_nffree++;
    791 		}
    792 	}
    793 	if (sblock.fs_contigsumsize > 0) {
    794 		int32_t *sump = cg_clustersum(&acg, 0);
    795 		u_char *mapp = cg_clustersfree(&acg, 0);
    796 		int map = *mapp++;
    797 		int bit = 1;
    798 		int run = 0;
    799 
    800 		for (i = 0; i < acg.cg_nclusterblks; i++) {
    801 			if ((map & bit) != 0) {
    802 				run++;
    803 			} else if (run != 0) {
    804 				if (run > sblock.fs_contigsumsize)
    805 					run = sblock.fs_contigsumsize;
    806 				sump[run]++;
    807 				run = 0;
    808 			}
    809 			if ((i & (CHAR_BIT - 1)) != (CHAR_BIT - 1)) {
    810 				bit <<= 1;
    811 			} else {
    812 				map = *mapp++;
    813 				bit = 1;
    814 			}
    815 		}
    816 		if (run != 0) {
    817 			if (run > sblock.fs_contigsumsize)
    818 				run = sblock.fs_contigsumsize;
    819 			sump[run]++;
    820 		}
    821 	}
    822 	*fscs_next++ = acg.cg_cs;
    823 	if (fscs_next == fscs_end) {
    824 		if (needswap)
    825 			ffs_csum_swap(fscs_reset, fscs_reset, sblock.fs_fsize);
    826 		fs_csaddr++;
    827 		wtfs(fsbtodb(&sblock, fs_csaddr), sblock.fs_fsize, fscs_reset);
    828 		fscs_next = fscs_reset;
    829 		memset(fscs_next, 0, sblock.fs_fsize);
    830 	}
    831 	/*
    832 	 * Write out the duplicate super block, the cylinder group map
    833 	 * and two blocks worth of inodes in a single write.
    834 	 */
    835 	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
    836 	memcpy(&iobuf[start], &acg, sblock.fs_cgsize);
    837 	if (needswap)
    838 		ffs_cg_swap(&acg, (struct cg*)&iobuf[start], &sblock);
    839 	start += sblock.fs_bsize;
    840 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
    841 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
    842 	for (i = MIN(sblock.fs_ipg, 2) * INOPB(&sblock); i != 0; i--) {
    843 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
    844 			/* No need to swap, it'll stay random */
    845 			dp1->di_gen = arc4random() & INT32_MAX;
    846 			dp1++;
    847 		} else {
    848 			dp2->di_gen = arc4random() & INT32_MAX;
    849 			dp2++;
    850 		}
    851 	}
    852 	wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);
    853 	/*
    854 	 * For the old file system, we have to initialize all the inodes.
    855 	 */
    856 	if (Oflag <= 1) {
    857 		for (i = 2 * sblock.fs_frag;
    858 		     i < sblock.fs_ipg / INOPF(&sblock);
    859 		     i += sblock.fs_frag) {
    860 			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
    861 			for (j = 0; j < INOPB(&sblock); j++) {
    862 				dp1->di_gen = arc4random() & INT32_MAX;
    863 				dp1++;
    864 			}
    865 			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
    866 			    sblock.fs_bsize, &iobuf[start]);
    867 		}
    868 	}
    869 }
    870 
    871 /*
    872  * initialize the file system
    873  */
    874 
    875 #ifdef LOSTDIR
    876 #define	PREDEFDIR 3
    877 #else
    878 #define	PREDEFDIR 2
    879 #endif
    880 
    881 struct direct root_dir[] = {
    882 	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
    883 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
    884 #ifdef LOSTDIR
    885 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 10, "lost+found" },
    886 #endif
    887 };
    888 struct odirect {
    889 	u_int32_t d_ino;
    890 	u_int16_t d_reclen;
    891 	u_int16_t d_namlen;
    892 	u_char	d_name[MAXNAMLEN + 1];
    893 } oroot_dir[] = {
    894 	{ ROOTINO, sizeof(struct direct), 1, "." },
    895 	{ ROOTINO, sizeof(struct direct), 2, ".." },
    896 #ifdef LOSTDIR
    897 	{ LOSTFOUNDINO, sizeof(struct direct), 10, "lost+found" },
    898 #endif
    899 };
    900 #ifdef LOSTDIR
    901 struct direct lost_found_dir[] = {
    902 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 1, "." },
    903 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
    904 	{ 0, DIRBLKSIZ, 0, 0, 0 },
    905 };
    906 struct odirect olost_found_dir[] = {
    907 	{ LOSTFOUNDINO, sizeof(struct direct), 1, "." },
    908 	{ ROOTINO, sizeof(struct direct), 2, ".." },
    909 	{ 0, DIRBLKSIZ, 0, 0 },
    910 };
    911 #endif
    912 char buf[MAXBSIZE];
    913 static void copy_dir(struct direct *, struct direct *);
    914 
    915 int
    916 fsinit(const struct timeval *tv, mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
    917 {
    918 	union dinode node;
    919 #ifdef LOSTDIR
    920 	int i;
    921 	int dirblksiz = DIRBLKSIZ;
    922 	if (isappleufs)
    923 		dirblksiz = APPLEUFS_DIRBLKSIZ;
    924 #endif
    925 
    926 	/*
    927 	 * initialize the node
    928 	 */
    929 
    930 #ifdef LOSTDIR
    931 	/*
    932 	 * create the lost+found directory
    933 	 */
    934 	memset(&node, 0, sizeof(node));
    935 	if (Oflag == 0) {
    936 		(void)makedir((struct direct *)olost_found_dir, 2);
    937 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
    938 			copy_dir((struct direct*)&olost_found_dir[2],
    939 				(struct direct*)&buf[i]);
    940 	} else {
    941 		(void)makedir(lost_found_dir, 2);
    942 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
    943 			copy_dir(&lost_found_dir[2], (struct direct*)&buf[i]);
    944 	}
    945 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
    946 		node.dp1.di_atime = tv->tv_sec;
    947 		node.dp1.di_atimensec = tv->tv_usec * 1000;
    948 		node.dp1.di_mtime = tv->tv_sec;
    949 		node.dp1.di_mtimensec = tv->tv_usec * 1000;
    950 		node.dp1.di_ctime = tv->tv_sec;
    951 		node.dp1.di_ctimensec = tv->tv_usec * 1000;
    952 		node.dp1.di_mode = IFDIR | UMASK;
    953 		node.dp1.di_nlink = 2;
    954 		node.dp1.di_size = sblock.fs_bsize;
    955 		node.dp1.di_db[0] = alloc(node.dp1.di_size, node.dp1.di_mode);
    956 		if (node.dp1.di_db[0] == 0)
    957 			return (0);
    958 		node.dp1.di_blocks = btodb(fragroundup(&sblock,
    959 		    node.dp1.di_size));
    960 		node.dp1.di_uid = geteuid();
    961 		node.dp1.di_gid = getegid();
    962 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), node.dp1.di_size,
    963 		    buf);
    964 	} else {
    965 		node.dp2.di_atime = tv->tv_sec;
    966 		node.dp2.di_atimensec = tv->tv_usec * 1000;
    967 		node.dp2.di_mtime = tv->tv_sec;
    968 		node.dp2.di_mtimensec = tv->tv_usec * 1000;
    969 		node.dp2.di_ctime = tv->tv_sec;
    970 		node.dp2.di_ctimensec = tv->tv_usec * 1000;
    971 		node.dp2.di_birthtime = tv->tv_sec;
    972 		node.dp2.di_birthnsec = tv->tv_usec * 1000;
    973 		node.dp2.di_mode = IFDIR | UMASK;
    974 		node.dp2.di_nlink = 2;
    975 		node.dp2.di_size = sblock.fs_bsize;
    976 		node.dp2.di_db[0] = alloc(node.dp2.di_size, node.dp2.di_mode);
    977 		if (node.dp2.di_db[0] == 0)
    978 			return (0);
    979 		node.dp2.di_blocks = btodb(fragroundup(&sblock,
    980 		    node.dp2.di_size));
    981 		node.dp2.di_uid = geteuid();
    982 		node.dp2.di_gid = getegid();
    983 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), node.dp2.di_size,
    984 		    buf);
    985 	}
    986 	iput(&node, LOSTFOUNDINO);
    987 #endif
    988 	/*
    989 	 * create the root directory
    990 	 */
    991 	memset(&node, 0, sizeof(node));
    992 	if (Oflag <= 1) {
    993 		if (mfs) {
    994 			node.dp1.di_mode = IFDIR | mfsmode;
    995 			node.dp1.di_uid = mfsuid;
    996 			node.dp1.di_gid = mfsgid;
    997 		} else {
    998 			node.dp1.di_mode = IFDIR | UMASK;
    999 			node.dp1.di_uid = geteuid();
   1000 			node.dp1.di_gid = getegid();
   1001 		}
   1002 		node.dp1.di_nlink = PREDEFDIR;
   1003 		if (Oflag == 0)
   1004 			node.dp1.di_size = makedir((struct direct *)oroot_dir,
   1005 			    PREDEFDIR);
   1006 		else
   1007 			node.dp1.di_size = makedir(root_dir, PREDEFDIR);
   1008 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
   1009 		if (node.dp1.di_db[0] == 0)
   1010 			return (0);
   1011 		node.dp1.di_blocks = btodb(fragroundup(&sblock,
   1012 		    node.dp1.di_size));
   1013 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, buf);
   1014 	} else {
   1015 		if (mfs) {
   1016 			node.dp2.di_mode = IFDIR | mfsmode;
   1017 			node.dp2.di_uid = mfsuid;
   1018 			node.dp2.di_gid = mfsgid;
   1019 		} else {
   1020 			node.dp2.di_mode = IFDIR | UMASK;
   1021 			node.dp2.di_uid = geteuid();
   1022 			node.dp2.di_gid = getegid();
   1023 		}
   1024 		node.dp2.di_atime = tv->tv_sec;
   1025 		node.dp2.di_atimensec = tv->tv_usec * 1000;
   1026 		node.dp2.di_mtime = tv->tv_sec;
   1027 		node.dp2.di_mtimensec = tv->tv_usec * 1000;
   1028 		node.dp2.di_ctime = tv->tv_sec;
   1029 		node.dp2.di_ctimensec = tv->tv_usec * 1000;
   1030 		node.dp2.di_birthtime = tv->tv_sec;
   1031 		node.dp2.di_birthnsec = tv->tv_usec * 1000;
   1032 		node.dp2.di_nlink = PREDEFDIR;
   1033 		node.dp2.di_size = makedir(root_dir, PREDEFDIR);
   1034 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
   1035 		if (node.dp2.di_db[0] == 0)
   1036 			return (0);
   1037 		node.dp2.di_blocks = btodb(fragroundup(&sblock,
   1038 		    node.dp2.di_size));
   1039 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, buf);
   1040 	}
   1041 	iput(&node, ROOTINO);
   1042 	return (1);
   1043 }
   1044 
   1045 /*
   1046  * construct a set of directory entries in "buf".
   1047  * return size of directory.
   1048  */
   1049 int
   1050 makedir(struct direct *protodir, int entries)
   1051 {
   1052 	char *cp;
   1053 	int i, spcleft;
   1054 	int dirblksiz = DIRBLKSIZ;
   1055 	if (isappleufs)
   1056 		dirblksiz = APPLEUFS_DIRBLKSIZ;
   1057 
   1058 	memset(buf, 0, DIRBLKSIZ);
   1059 	spcleft = dirblksiz;
   1060 	for (cp = buf, i = 0; i < entries - 1; i++) {
   1061 		protodir[i].d_reclen = DIRSIZ(Oflag == 0, &protodir[i], 0);
   1062 		copy_dir(&protodir[i], (struct direct*)cp);
   1063 		cp += protodir[i].d_reclen;
   1064 		spcleft -= protodir[i].d_reclen;
   1065 	}
   1066 	protodir[i].d_reclen = spcleft;
   1067 	copy_dir(&protodir[i], (struct direct*)cp);
   1068 	return (dirblksiz);
   1069 }
   1070 
   1071 /*
   1072  * allocate a block or frag
   1073  */
   1074 daddr_t
   1075 alloc(int size, int mode)
   1076 {
   1077 	int i, frag;
   1078 	daddr_t d, blkno;
   1079 
   1080 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1081 	/* fs -> host byte order */
   1082 	if (needswap)
   1083 		ffs_cg_swap(&acg, &acg, &sblock);
   1084 	if (acg.cg_magic != CG_MAGIC) {
   1085 		printf("cg 0: bad magic number\n");
   1086 		return (0);
   1087 	}
   1088 	if (acg.cg_cs.cs_nbfree == 0) {
   1089 		printf("first cylinder group ran out of space\n");
   1090 		return (0);
   1091 	}
   1092 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
   1093 		if (isblock(&sblock, cg_blksfree(&acg, 0),
   1094 		    d >> sblock.fs_fragshift))
   1095 			goto goth;
   1096 	printf("internal error: can't find block in cyl 0\n");
   1097 	return (0);
   1098 goth:
   1099 	blkno = fragstoblks(&sblock, d);
   1100 	clrblock(&sblock, cg_blksfree(&acg, 0), blkno);
   1101 	if (sblock.fs_contigsumsize > 0)
   1102 		clrbit(cg_clustersfree(&acg, 0), blkno);
   1103 	acg.cg_cs.cs_nbfree--;
   1104 	sblock.fs_cstotal.cs_nbfree--;
   1105 	fscs_0->cs_nbfree--;
   1106 	if (mode & IFDIR) {
   1107 		acg.cg_cs.cs_ndir++;
   1108 		sblock.fs_cstotal.cs_ndir++;
   1109 		fscs_0->cs_ndir++;
   1110 	}
   1111 	if (size != sblock.fs_bsize) {
   1112 		frag = howmany(size, sblock.fs_fsize);
   1113 		fscs_0->cs_nffree += sblock.fs_frag - frag;
   1114 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
   1115 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
   1116 		acg.cg_frsum[sblock.fs_frag - frag]++;
   1117 		for (i = frag; i < sblock.fs_frag; i++)
   1118 			setbit(cg_blksfree(&acg, 0), d + i);
   1119 	}
   1120 	/* host -> fs byte order */
   1121 	if (needswap)
   1122 		ffs_cg_swap(&acg, &acg, &sblock);
   1123 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1124 	return (d);
   1125 }
   1126 
   1127 /*
   1128  * Allocate an inode on the disk
   1129  */
   1130 static void
   1131 iput(union dinode *ip, ino_t ino)
   1132 {
   1133 	daddr_t d;
   1134 	int c, i;
   1135 	struct ufs1_dinode *dp1;
   1136 	struct ufs2_dinode *dp2;
   1137 
   1138 	c = ino_to_cg(&sblock, ino);
   1139 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1140 	/* fs -> host byte order */
   1141 	if (needswap)
   1142 		ffs_cg_swap(&acg, &acg, &sblock);
   1143 	if (acg.cg_magic != CG_MAGIC) {
   1144 		printf("cg 0: bad magic number\n");
   1145 		exit(31);
   1146 	}
   1147 	acg.cg_cs.cs_nifree--;
   1148 	setbit(cg_inosused(&acg, 0), ino);
   1149 	/* host -> fs byte order */
   1150 	if (needswap)
   1151 		ffs_cg_swap(&acg, &acg, &sblock);
   1152 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1153 	sblock.fs_cstotal.cs_nifree--;
   1154 	fscs_0->cs_nifree--;
   1155 	if (ino >= sblock.fs_ipg * sblock.fs_ncg) {
   1156 		printf("fsinit: inode value out of range (%d).\n", ino);
   1157 		exit(32);
   1158 	}
   1159 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
   1160 	rdfs(d, sblock.fs_bsize, (char *)iobuf);
   1161 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
   1162 		dp1 = (struct ufs1_dinode *)iobuf;
   1163 		dp1 += ino_to_fsbo(&sblock, ino);
   1164 		if (needswap) {
   1165 			ffs_dinode1_swap(&ip->dp1, dp1);
   1166 			/* ffs_dinode1_swap() doesn't swap blocks addrs */
   1167 			for (i=0; i<NDADDR + NIADDR; i++)
   1168 			    dp1->di_db[i] = bswap32(ip->dp1.di_db[i]);
   1169 		} else
   1170 			*dp1 = ip->dp1;
   1171 		dp1->di_gen = arc4random() & INT32_MAX;
   1172 	} else {
   1173 		dp2 = (struct ufs2_dinode *)iobuf;
   1174 		dp2 += ino_to_fsbo(&sblock, ino);
   1175 		if (needswap) {
   1176 			ffs_dinode2_swap(&ip->dp2, dp2);
   1177 			for (i=0; i<NDADDR + NIADDR; i++)
   1178 			    dp2->di_db[i] = bswap32(ip->dp2.di_db[i]);
   1179 		} else
   1180 			*dp2 = ip->dp2;
   1181 		dp2->di_gen = arc4random() & INT32_MAX;
   1182 	}
   1183 	wtfs(d, sblock.fs_bsize, iobuf);
   1184 }
   1185 
   1186 /*
   1187  * read a block from the file system
   1188  */
   1189 void
   1190 rdfs(daddr_t bno, int size, void *bf)
   1191 {
   1192 	int n;
   1193 	off_t offset;
   1194 
   1195 #ifdef MFS
   1196 	if (mfs) {
   1197 		memmove(bf, membase + bno * sectorsize, size);
   1198 		return;
   1199 	}
   1200 #endif
   1201 	offset = bno;
   1202 	n = pread(fsi, bf, size, offset * sectorsize);
   1203 	if (n != size) {
   1204 		printf("rdfs: read error for sector %lld: %s\n",
   1205 		    (long long)bno, strerror(errno));
   1206 		exit(34);
   1207 	}
   1208 }
   1209 
   1210 /*
   1211  * write a block to the file system
   1212  */
   1213 void
   1214 wtfs(daddr_t bno, int size, void *bf)
   1215 {
   1216 	int n;
   1217 	off_t offset;
   1218 
   1219 #ifdef MFS
   1220 	if (mfs) {
   1221 		memmove(membase + bno * sectorsize, bf, size);
   1222 		return;
   1223 	}
   1224 #endif
   1225 	if (Nflag)
   1226 		return;
   1227 	offset = bno;
   1228 	n = pwrite(fso, bf, size, offset * sectorsize);
   1229 	if (n != size) {
   1230 		printf("wtfs: write error for sector %lld: %s\n",
   1231 		    (long long)bno, strerror(errno));
   1232 		exit(36);
   1233 	}
   1234 }
   1235 
   1236 /*
   1237  * check if a block is available
   1238  */
   1239 int
   1240 isblock(struct fs *fs, unsigned char *cp, int h)
   1241 {
   1242 	unsigned char mask;
   1243 
   1244 	switch (fs->fs_fragshift) {
   1245 	case 3:
   1246 		return (cp[h] == 0xff);
   1247 	case 2:
   1248 		mask = 0x0f << ((h & 0x1) << 2);
   1249 		return ((cp[h >> 1] & mask) == mask);
   1250 	case 1:
   1251 		mask = 0x03 << ((h & 0x3) << 1);
   1252 		return ((cp[h >> 2] & mask) == mask);
   1253 	case 0:
   1254 		mask = 0x01 << (h & 0x7);
   1255 		return ((cp[h >> 3] & mask) == mask);
   1256 	default:
   1257 #ifdef STANDALONE
   1258 		printf("isblock bad fs_fragshift %d\n", fs->fs_fragshift);
   1259 #else
   1260 		fprintf(stderr, "isblock bad fs_fragshift %d\n",
   1261 		    fs->fs_fragshift);
   1262 #endif
   1263 		return (0);
   1264 	}
   1265 }
   1266 
   1267 /*
   1268  * take a block out of the map
   1269  */
   1270 void
   1271 clrblock(struct fs *fs, unsigned char *cp, int h)
   1272 {
   1273 	switch ((fs)->fs_fragshift) {
   1274 	case 3:
   1275 		cp[h] = 0;
   1276 		return;
   1277 	case 2:
   1278 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
   1279 		return;
   1280 	case 1:
   1281 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
   1282 		return;
   1283 	case 0:
   1284 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
   1285 		return;
   1286 	default:
   1287 #ifdef STANDALONE
   1288 		printf("clrblock bad fs_fragshift %d\n", fs->fs_fragshift);
   1289 #else
   1290 		fprintf(stderr, "clrblock bad fs_fragshift %d\n",
   1291 		    fs->fs_fragshift);
   1292 #endif
   1293 		return;
   1294 	}
   1295 }
   1296 
   1297 /*
   1298  * put a block into the map
   1299  */
   1300 void
   1301 setblock(struct fs *fs, unsigned char *cp, int h)
   1302 {
   1303 	switch (fs->fs_fragshift) {
   1304 	case 3:
   1305 		cp[h] = 0xff;
   1306 		return;
   1307 	case 2:
   1308 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
   1309 		return;
   1310 	case 1:
   1311 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
   1312 		return;
   1313 	case 0:
   1314 		cp[h >> 3] |= (0x01 << (h & 0x7));
   1315 		return;
   1316 	default:
   1317 #ifdef STANDALONE
   1318 		printf("setblock bad fs_frag %d\n", fs->fs_fragshift);
   1319 #else
   1320 		fprintf(stderr, "setblock bad fs_fragshift %d\n",
   1321 		    fs->fs_fragshift);
   1322 #endif
   1323 		return;
   1324 	}
   1325 }
   1326 
   1327 /* copy a direntry to a buffer, in fs byte order */
   1328 static void
   1329 copy_dir(struct direct *dir, struct direct *dbuf)
   1330 {
   1331 	memcpy(dbuf, dir, DIRSIZ(Oflag == 0, dir, 0));
   1332 	if (needswap) {
   1333 		dbuf->d_ino = bswap32(dir->d_ino);
   1334 		dbuf->d_reclen = bswap16(dir->d_reclen);
   1335 		if (Oflag == 0)
   1336 			((struct odirect*)dbuf)->d_namlen =
   1337 				bswap16(((struct odirect*)dir)->d_namlen);
   1338 	}
   1339 }
   1340 
   1341 /* Determine how many digits are needed to print a given integer */
   1342 static int
   1343 count_digits(uint64_t num)
   1344 {
   1345 	int ndig;
   1346 
   1347 	for (ndig = 1; num > 9; num /= 10, ndig++);
   1348 
   1349 	return (ndig);
   1350 }
   1351 
   1352 static int
   1353 ilog2(int val)
   1354 {
   1355 	u_int n;
   1356 
   1357 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
   1358 		if (1 << n == val)
   1359 			return (n);
   1360 	errx(1, "ilog2: %d is not a power of 2\n", val);
   1361 }
   1362 
   1363 static void
   1364 zap_old_sblock(int sblkoff)
   1365 {
   1366 	static int cg0_data;
   1367 	uint32_t oldfs[SBLOCKSIZE / 4];
   1368 	static const struct fsm {
   1369 		uint32_t	offset;
   1370 		uint32_t	magic;
   1371 		uint32_t	mask;
   1372 	} fs_magics[] = {
   1373 		{offsetof(struct fs, fs_magic)/4, FS_UFS1_MAGIC, ~0u},
   1374 		{offsetof(struct fs, fs_magic)/4, FS_UFS2_MAGIC, ~0u},
   1375 		{0, 0x70162, ~0u},		/* LFS_MAGIC */
   1376 		{14, 0xef53, 0xffff},		/* EXT2FS (little) */
   1377 		{14, 0xef530000, 0xffff0000},	/* EXT2FS (big) */
   1378 		{~0u},
   1379 	};
   1380 	const struct fsm *fsm;
   1381 
   1382 	if (Nflag)
   1383 		return;
   1384 
   1385 	if (sblkoff == 0)	/* Why did UFS2 add support for this?  sigh. */
   1386 		return;
   1387 
   1388 	if (cg0_data == 0)
   1389 		/* For FFSv1 this could include all the inodes. */
   1390 		cg0_data = cgsblock(&sblock, 0) * sblock.fs_fsize + iobufsize;
   1391 
   1392 	/* Ignore anything that is beyond our filesystem */
   1393 	if ((sblkoff + SBLOCKSIZE)/sectorsize >= fssize)
   1394 		return;
   1395 	/* Zero anything inside our filesystem... */
   1396 	if (sblkoff >= sblock.fs_sblockloc) {
   1397 		/* ...unless we will write that area anyway */
   1398 		if (sblkoff >= cg0_data)
   1399 			wtfs(sblkoff / sectorsize,
   1400 			    roundup(sizeof sblock, sectorsize), iobuf);
   1401 		return;
   1402 	}
   1403 
   1404 	/* The sector might contain boot code, so we must validate it */
   1405 	rdfs(sblkoff/sectorsize, sizeof oldfs, &oldfs);
   1406 	for (fsm = fs_magics; ; fsm++) {
   1407 		uint32_t v;
   1408 		if (fsm->mask == 0)
   1409 			return;
   1410 		v = oldfs[fsm->offset];
   1411 		if ((v & fsm->mask) == fsm->magic ||
   1412 		    (bswap32(v) & fsm->mask) == fsm->magic)
   1413 			break;
   1414 	}
   1415 
   1416 	/* Just zap the magic number */
   1417 	oldfs[fsm->offset] = 0;
   1418 	wtfs(sblkoff/sectorsize, sizeof oldfs, &oldfs);
   1419 }
   1420 
   1421 
   1422 #ifdef MFS
   1423 /*
   1424  * XXX!
   1425  * Attempt to guess how much more space is available for process data.  The
   1426  * heuristic we use is
   1427  *
   1428  *	max_data_limit - (sbrk(0) - etext) - 128kB
   1429  *
   1430  * etext approximates that start address of the data segment, and the 128kB
   1431  * allows some slop for both segment gap between text and data, and for other
   1432  * (libc) malloc usage.
   1433  */
   1434 static void
   1435 calc_memfree(void)
   1436 {
   1437 	extern char etext;
   1438 	struct rlimit rlp;
   1439 	u_long base;
   1440 
   1441 	base = (u_long)sbrk(0) - (u_long)&etext;
   1442 	if (getrlimit(RLIMIT_DATA, &rlp) < 0)
   1443 		perror("getrlimit");
   1444 	rlp.rlim_cur = rlp.rlim_max;
   1445 	if (setrlimit(RLIMIT_DATA, &rlp) < 0)
   1446 		perror("setrlimit");
   1447 	memleft = rlp.rlim_max - base - (128 * 1024);
   1448 }
   1449 
   1450 /*
   1451  * Internal version of malloc that trims the requested size if not enough
   1452  * memory is available.
   1453  */
   1454 static void *
   1455 mkfs_malloc(size_t size)
   1456 {
   1457 	u_long pgsz;
   1458 
   1459 	if (size == 0)
   1460 		return (NULL);
   1461 	if (memleft == 0)
   1462 		calc_memfree();
   1463 
   1464 	pgsz = getpagesize() - 1;
   1465 	size = (size + pgsz) &~ pgsz;
   1466 	if (size > memleft)
   1467 		size = memleft;
   1468 	memleft -= size;
   1469 	return (mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
   1470 	    -1, 0));
   1471 }
   1472 #endif	/* MFS */
   1473