Home | History | Annotate | Line # | Download | only in newfs
mkfs.c revision 1.80
      1 /*	$NetBSD: mkfs.c,v 1.80 2003/09/10 17:25:14 dsl 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.80 2003/09/10 17:25:14 dsl 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 	/*
    360 	 * Calculate 'per inode block' so we can allocate less than 1 fragment
    361 	 * per inode - useful for /dev.
    362 	 */
    363 	fragsperinodeblk = MAX(numfrags(&sblock, density * INOPB(&sblock)), 1);
    364 	inodeblks = (sblock.fs_size - sblock.fs_iblkno - 2 * sblock.fs_frag) /
    365 		(sblock.fs_frag + fragsperinodeblk);
    366 	if (inodeblks == 0)
    367 		inodeblks = 1;
    368 	/* Even UFS2 limits number of inodes to 2^31 (fs_ipg is int32_t) */
    369 	if (inodeblks * INOPB(&sblock) >= 1ull << 31)
    370 		inodeblks = ((1ull << 31) - NBBY) / INOPB(&sblock);
    371 	/*
    372 	 * See what would happen if we tried to use 1 cylinder group.
    373 	 * Assume space linear, so work out number of cylinder groups needed.
    374 	 * Subtract one from the allowed size to compensate for rounding
    375 	 * a number of bits up to a complete byte.
    376 	 */
    377 	cgzero = CGSIZE_IF(&sblock, 0, 0);
    378 	cgall = CGSIZE_IF(&sblock, inodeblks * INOPB(&sblock), sblock.fs_size);
    379 	ncg = howmany(cgall - cgzero, sblock.fs_bsize - cgzero - 1);
    380 	if (ncg < MINCYLGRPS) {
    381 		/*
    382 		 * We would like to allocate MINCLYGRPS cylinder groups,
    383 		 * but for small file sytems (especially ones with a lot
    384 		 * of inodes) this is not desirable (or possible).
    385 		 */
    386 		i = sblock.fs_size / 2 / (sblock.fs_iblkno +
    387 						inodeblks * sblock.fs_frag);
    388 		if (i > ncg)
    389 			ncg = i;
    390 		if (ncg > MINCYLGRPS)
    391 			ncg = MINCYLGRPS;
    392 		if (ncg > inodeblks)
    393 			ncg = inodeblks;
    394 	}
    395 	/*
    396 	 * Put an equal number of blocks in each cylinder group.
    397 	 * Round up so we don't have more fragments in the last CG than
    398 	 * the earlier ones (does that matter?), but kill a block if the
    399 	 * CGSIZE becomes too big (only happens if there are a lot of CGs).
    400 	 */
    401 	sblock.fs_fpg = roundup(howmany(sblock.fs_size, ncg), sblock.fs_frag);
    402 	i = CGSIZE_IF(&sblock, inodeblks * INOPB(&sblock) / ncg, sblock.fs_fpg);
    403 	if (i > sblock.fs_bsize)
    404 		sblock.fs_fpg -= (i - sblock.fs_bsize) * NBBY;
    405 	/* ... and recalculate how many cylinder groups we now need */
    406 	ncg = howmany(sblock.fs_size, sblock.fs_fpg);
    407 	inodeblks /= ncg;
    408 	if (inodeblks == 0)
    409 		inodeblks = 1;
    410 	sblock.fs_ipg = inodeblks * INOPB(&sblock);
    411 	/* Sanity check on our sums... */
    412 	if (CGSIZE(&sblock) > sblock.fs_bsize) {
    413 		printf("CGSIZE miscalculated %d > %d\n",
    414 		    (int)CGSIZE(&sblock), sblock.fs_bsize);
    415 		exit(24);
    416 	}
    417 	/* Check that the last cylinder group has enough space for the inodes */
    418 	i = sblock.fs_size - sblock.fs_fpg * (ncg - 1ull);
    419 	if (i < sblock.fs_iblkno + inodeblks * sblock.fs_frag) {
    420 		/*
    421 		 * Since we make all the cylinder groups the same size, the
    422 		 * last will only be small if there are a large number of
    423 		 * cylinder groups. If we pull even a fragment from each
    424 		 * of the other groups then the last CG will be overfull.
    425 		 * So we just kill the last CG.
    426 		 */
    427 		ncg--;
    428 		sblock.fs_size -= i;
    429 	}
    430 	sblock.fs_ncg = ncg;
    431 
    432 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
    433 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
    434 	if (Oflag <= 1) {
    435 		sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
    436 		sblock.fs_old_nsect = sblock.fs_old_spc;
    437 		sblock.fs_old_npsect = sblock.fs_old_spc;
    438 		sblock.fs_old_ncyl = sblock.fs_ncg;
    439 	}
    440 
    441 	/*
    442 	 * Cylinder group summary information for each cylinder is written
    443 	 * into the first cylinder group.
    444 	 * Write this fragment by fragment, but doing the first CG last
    445 	 * (after we've taken stuff off for the structure itself and the
    446 	 * root directory.
    447 	 */
    448 	sblock.fs_csaddr = cgdmin(&sblock, 0);
    449 	sblock.fs_cssize =
    450 	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
    451 	if (512 % sizeof *fscs_0)
    452 		errx(1, "cylinder group summary doesn't fit in sectors");
    453 	fscs_0 = calloc(1, 2 * sblock.fs_fsize);
    454 	if (fscs_0 == NULL)
    455 		exit(39);
    456 	fs_csaddr = sblock.fs_csaddr;
    457 	fscs_next = fscs_0;
    458 	fscs_end = (void *)((char *)fscs_0 + 2 * sblock.fs_fsize);
    459 	fscs_reset = (void *)((char *)fscs_0 + sblock.fs_fsize);
    460 	/*
    461 	 * fill in remaining fields of the super block
    462 	 */
    463 	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
    464 	if (sblock.fs_sbsize > SBLOCKSIZE)
    465 		sblock.fs_sbsize = SBLOCKSIZE;
    466 	sblock.fs_minfree = minfree;
    467 	sblock.fs_maxcontig = maxcontig;
    468 	sblock.fs_maxbpg = maxbpg;
    469 	sblock.fs_optim = opt;
    470 	sblock.fs_cgrotor = 0;
    471 	sblock.fs_pendingblocks = 0;
    472 	sblock.fs_pendinginodes = 0;
    473 	sblock.fs_cstotal.cs_ndir = 0;
    474 	sblock.fs_cstotal.cs_nbfree = 0;
    475 	sblock.fs_cstotal.cs_nifree = 0;
    476 	sblock.fs_cstotal.cs_nffree = 0;
    477 	sblock.fs_fmod = 0;
    478 	sblock.fs_ronly = 0;
    479 	sblock.fs_state = 0;
    480 	sblock.fs_clean = FS_ISCLEAN;
    481 	sblock.fs_ronly = 0;
    482 	sblock.fs_id[0] = (long)tv.tv_sec;	/* XXXfvdl huh? */
    483 	sblock.fs_id[1] = arc4random() & INT32_MAX;
    484 	sblock.fs_fsmnt[0] = '\0';
    485 	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
    486 	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
    487 	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
    488 	sblock.fs_cstotal.cs_nbfree =
    489 	    fragstoblks(&sblock, sblock.fs_dsize) -
    490 	    howmany(csfrags, sblock.fs_frag);
    491 	sblock.fs_cstotal.cs_nffree =
    492 	    fragnum(&sblock, sblock.fs_size) +
    493 	    (fragnum(&sblock, csfrags) > 0 ?
    494 	    sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
    495 	sblock.fs_cstotal.cs_nifree = sblock.fs_ncg * sblock.fs_ipg - ROOTINO;
    496 	sblock.fs_cstotal.cs_ndir = 0;
    497 	sblock.fs_dsize -= csfrags;
    498 	sblock.fs_time = tv.tv_sec;
    499 	if (Oflag <= 1) {
    500 		sblock.fs_old_time = tv.tv_sec;
    501 		sblock.fs_old_dsize = sblock.fs_dsize;
    502 		sblock.fs_old_csaddr = sblock.fs_csaddr;
    503 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
    504 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
    505 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
    506 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
    507 	}
    508 	/*
    509 	 * Dump out summary information about file system.
    510 	 */
    511 	if (!mfs) {
    512 #define	B2MBFACTOR (1 / (1024.0 * 1024.0))
    513 		printf("%s: %.1fMB (%lld sectors) block size %d, "
    514 		       "fragment size %d\n",
    515 		    fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
    516 		    (long long)fsbtodb(&sblock, sblock.fs_size),
    517 		    sblock.fs_bsize, sblock.fs_fsize);
    518 		printf("\tusing %d cylinder groups of %.2fMB, %d blks, "
    519 		       "%d inodes.\n",
    520 		    sblock.fs_ncg,
    521 		    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
    522 		    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
    523 #undef B2MBFACTOR
    524 	}
    525 	/*
    526 	 * Now determine how wide each column will be, and calculate how
    527 	 * many columns will fit in a 80 char line.
    528 	 */
    529 	printcolwidth = count_digits(
    530 			fsbtodb(&sblock, cgsblock(&sblock, sblock.fs_ncg -1)));
    531 	nprintcols = 80 / (printcolwidth + 2);
    532 
    533 	/*
    534 	 * allocate space for superblock, cylinder group map, and
    535 	 * two sets of inode blocks.
    536 	 */
    537 	if (sblock.fs_bsize < SBLOCKSIZE)
    538 		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
    539 	else
    540 		iobufsize = 4 * sblock.fs_bsize;
    541 	if ((iobuf = malloc(iobufsize)) == 0) {
    542 		printf("Cannot allocate I/O buffer\n");
    543 		exit(38);
    544 	}
    545 	memset(iobuf, 0, iobufsize);
    546 
    547 	/*
    548 	 * We now start writing to the filesystem
    549 	 */
    550 
    551 	/*
    552 	 * Validate the given file system size.
    553 	 * Verify that its last block can actually be accessed.
    554 	 * Convert to file system fragment sized units.
    555 	 */
    556 	if (fssize <= 0) {
    557 		printf("preposterous size %lld\n", (long long)fssize);
    558 		exit(13);
    559 	}
    560 	wtfs(fssize - 1, sectorsize, iobuf);
    561 
    562 	/*
    563 	 * Ensure there is nothing that looks like a filesystem
    564 	 * superbock anywhere other than where ours will be.
    565 	 * If fsck finds the wrong one all hell breaks loose!
    566 	 */
    567 	for (i = 0; ; i++) {
    568 		static const int sblocklist[] = SBLOCKSEARCH;
    569 		int sblkoff = sblocklist[i];
    570 		int sz;
    571 		if (sblkoff == -1)
    572 			break;
    573 		/* Remove main superblock */
    574 		zap_old_sblock(sblkoff);
    575 		/* and all possible locations for the first alternate */
    576 		sblkoff += SBLOCKSIZE;
    577 		for (sz = SBLOCKSIZE; sz <= 0x10000; sz <<= 1)
    578 			zap_old_sblock(roundup(sblkoff, sz));
    579 	}
    580 
    581 	if (isappleufs) {
    582 		struct appleufslabel appleufs;
    583 		ffs_appleufs_set(&appleufs, appleufs_volname, tv.tv_sec);
    584 		wtfs(APPLEUFS_LABEL_OFFSET/sectorsize, APPLEUFS_LABEL_SIZE,
    585 		    &appleufs);
    586 	}
    587 
    588 	/*
    589 	 * Make a copy of the superblock into the buffer that we will be
    590 	 * writing out in each cylinder group.
    591 	 */
    592 	memcpy(iobuf, &sblock, sizeof sblock);
    593 	if (needswap)
    594 		ffs_sb_swap(&sblock, (struct fs *)iobuf);
    595 
    596 	if (!mfs)
    597 		printf("super-block backups (for fsck -b #) at:");
    598 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
    599 		initcg(cylno, &tv);
    600 		if (mfs)
    601 			continue;
    602 		if (cylno % nprintcols == 0)
    603 			printf("\n");
    604 		printf(" %*lld,", printcolwidth,
    605 			(long long)fsbtodb(&sblock, cgsblock(&sblock, cylno)));
    606 		fflush(stdout);
    607 	}
    608 	if (!mfs)
    609 		printf("\n");
    610 	if (Nflag && !mfs)
    611 		exit(0);
    612 
    613 	/*
    614 	 * Now construct the initial file system,
    615 	 */
    616 	if (fsinit(&tv, mfsmode, mfsuid, mfsgid) == 0 && mfs)
    617 		errx(1, "Error making filesystem");
    618 	sblock.fs_time = tv.tv_sec;
    619 	if (Oflag <= 1) {
    620 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
    621 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
    622 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
    623 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
    624 	}
    625 	/*
    626 	 * Write out the super-block and zeros until the first cg info
    627 	 */
    628 	memset(iobuf, 0, iobufsize);
    629         memcpy(iobuf, &sblock, sizeof sblock);
    630 	if (needswap)
    631 		ffs_sb_swap(&sblock, (struct fs *)iobuf);
    632         wtfs(sblock.fs_sblockloc / sectorsize,
    633 	    cgsblock(&sblock, 0) * sblock.fs_fsize - sblock.fs_sblockloc,
    634 	    iobuf);
    635 
    636 	/* Write out first and last cylinder summary sectors */
    637 	if (needswap)
    638 		ffs_csum_swap(fscs_0, fscs_0, sblock.fs_fsize);
    639 	wtfs(fsbtodb(&sblock, sblock.fs_csaddr), sblock.fs_fsize, fscs_0);
    640 
    641 	if (fscs_next > fscs_reset) {
    642 		if (needswap)
    643 			ffs_csum_swap(fscs_reset, fscs_reset, sblock.fs_fsize);
    644 		fs_csaddr++;
    645 		wtfs(fsbtodb(&sblock, fs_csaddr), sblock.fs_fsize, fscs_reset);
    646 	}
    647 
    648 	/*
    649 	 * Update information about this partion in pack
    650 	 * label, to that it may be updated on disk.
    651 	 */
    652 	if (isappleufs)
    653 		pp->p_fstype = FS_APPLEUFS;
    654 	else
    655 		pp->p_fstype = FS_BSDFFS;
    656 	pp->p_fsize = sblock.fs_fsize;
    657 	pp->p_frag = sblock.fs_frag;
    658 	pp->p_cpg = sblock.fs_fpg;
    659 }
    660 
    661 /*
    662  * Initialize a cylinder group.
    663  */
    664 void
    665 initcg(int cylno, const struct timeval *tv)
    666 {
    667 	daddr_t cbase, dmax;
    668 	int32_t i, j, d, dlower, dupper, blkno;
    669 	struct ufs1_dinode *dp1;
    670 	struct ufs2_dinode *dp2;
    671 	int start;
    672 
    673 	/*
    674 	 * Determine block bounds for cylinder group.
    675 	 * Allow space for super block summary information in first
    676 	 * cylinder group.
    677 	 */
    678 	cbase = cgbase(&sblock, cylno);
    679 	dmax = cbase + sblock.fs_fpg;
    680 	if (dmax > sblock.fs_size)
    681 		dmax = sblock.fs_size;
    682 	dlower = cgsblock(&sblock, cylno) - cbase;
    683 	dupper = cgdmin(&sblock, cylno) - cbase;
    684 	if (cylno == 0) {
    685 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
    686 		if (dupper >= cgstart(&sblock, cylno + 1)) {
    687 			printf("\rToo many cylinder groups to fit summary "
    688 				"information into first cylinder group\n");
    689 			exit(40);
    690 		}
    691 	}
    692 	memset(&acg, 0, sblock.fs_cgsize);
    693 	acg.cg_magic = CG_MAGIC;
    694 	acg.cg_cgx = cylno;
    695 	acg.cg_ndblk = dmax - cbase;
    696 	if (sblock.fs_contigsumsize > 0)
    697 		acg.cg_nclusterblks = acg.cg_ndblk >> sblock.fs_fragshift;
    698 	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
    699 	if (Oflag == 2) {
    700 		acg.cg_time = tv->tv_sec;
    701 		acg.cg_niblk = sblock.fs_ipg;
    702 		acg.cg_initediblk = sblock.fs_ipg < 2 * INOPB(&sblock) ?
    703 		    sblock.fs_ipg : 2 * INOPB(&sblock);
    704 		acg.cg_iusedoff = start;
    705 	} else {
    706 		acg.cg_old_ncyl = sblock.fs_old_cpg;
    707 		acg.cg_old_time = tv->tv_sec;
    708 		acg.cg_old_niblk = sblock.fs_ipg;
    709 		acg.cg_old_btotoff = start;
    710 		acg.cg_old_boff = acg.cg_old_btotoff +
    711 		    sblock.fs_old_cpg * sizeof(int32_t);
    712 		acg.cg_iusedoff = acg.cg_old_boff +
    713 		    sblock.fs_old_cpg * sizeof(u_int16_t);
    714 	}
    715 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
    716 	if (sblock.fs_contigsumsize <= 0) {
    717 		acg.cg_nextfreeoff = acg.cg_freeoff +
    718 		   howmany(sblock.fs_fpg, CHAR_BIT);
    719 	} else {
    720 		acg.cg_clustersumoff = acg.cg_freeoff +
    721 		    howmany(sblock.fs_fpg, CHAR_BIT) - sizeof(int32_t);
    722 		if (isappleufs) {
    723 			/* Apple PR2216969 gives rationale for this change.
    724 			 * I believe they were mistaken, but we need to
    725 			 * duplicate it for compatibility.  -- dbj (at) NetBSD.org
    726 			 */
    727 			acg.cg_clustersumoff += sizeof(int32_t);
    728 		}
    729 		acg.cg_clustersumoff =
    730 		    roundup(acg.cg_clustersumoff, sizeof(int32_t));
    731 		acg.cg_clusteroff = acg.cg_clustersumoff +
    732 		    (sblock.fs_contigsumsize + 1) * sizeof(int32_t);
    733 		acg.cg_nextfreeoff = acg.cg_clusteroff +
    734 		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
    735 	}
    736 	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
    737 		printf("Panic: cylinder group too big\n");
    738 		exit(37);
    739 	}
    740 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
    741 	if (cylno == 0)
    742 		for (i = 0; i < ROOTINO; i++) {
    743 			setbit(cg_inosused(&acg, 0), i);
    744 			acg.cg_cs.cs_nifree--;
    745 		}
    746 	if (cylno > 0) {
    747 		/*
    748 		 * In cylno 0, beginning space is reserved
    749 		 * for boot and super blocks.
    750 		 */
    751 		for (d = 0, blkno = 0; d < dlower;) {
    752 			setblock(&sblock, cg_blksfree(&acg, 0), blkno);
    753 			if (sblock.fs_contigsumsize > 0)
    754 				setbit(cg_clustersfree(&acg, 0), blkno);
    755 			acg.cg_cs.cs_nbfree++;
    756 			d += sblock.fs_frag;
    757 			blkno++;
    758 		}
    759 	}
    760 	if ((i = (dupper & (sblock.fs_frag - 1))) != 0) {
    761 		acg.cg_frsum[sblock.fs_frag - i]++;
    762 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
    763 			setbit(cg_blksfree(&acg, 0), dupper);
    764 			acg.cg_cs.cs_nffree++;
    765 		}
    766 	}
    767 	for (d = dupper, blkno = dupper >> sblock.fs_fragshift;
    768 	     d + sblock.fs_frag <= acg.cg_ndblk; ) {
    769 		setblock(&sblock, cg_blksfree(&acg, 0), blkno);
    770 		if (sblock.fs_contigsumsize > 0)
    771 			setbit(cg_clustersfree(&acg, 0), blkno);
    772 		acg.cg_cs.cs_nbfree++;
    773 		d += sblock.fs_frag;
    774 		blkno++;
    775 	}
    776 	if (d < acg.cg_ndblk) {
    777 		acg.cg_frsum[acg.cg_ndblk - d]++;
    778 		for (; d < acg.cg_ndblk; d++) {
    779 			setbit(cg_blksfree(&acg, 0), d);
    780 			acg.cg_cs.cs_nffree++;
    781 		}
    782 	}
    783 	if (sblock.fs_contigsumsize > 0) {
    784 		int32_t *sump = cg_clustersum(&acg, 0);
    785 		u_char *mapp = cg_clustersfree(&acg, 0);
    786 		int map = *mapp++;
    787 		int bit = 1;
    788 		int run = 0;
    789 
    790 		for (i = 0; i < acg.cg_nclusterblks; i++) {
    791 			if ((map & bit) != 0) {
    792 				run++;
    793 			} else if (run != 0) {
    794 				if (run > sblock.fs_contigsumsize)
    795 					run = sblock.fs_contigsumsize;
    796 				sump[run]++;
    797 				run = 0;
    798 			}
    799 			if ((i & (CHAR_BIT - 1)) != (CHAR_BIT - 1)) {
    800 				bit <<= 1;
    801 			} else {
    802 				map = *mapp++;
    803 				bit = 1;
    804 			}
    805 		}
    806 		if (run != 0) {
    807 			if (run > sblock.fs_contigsumsize)
    808 				run = sblock.fs_contigsumsize;
    809 			sump[run]++;
    810 		}
    811 	}
    812 	*fscs_next++ = acg.cg_cs;
    813 	if (fscs_next == fscs_end) {
    814 		if (needswap)
    815 			ffs_csum_swap(fscs_reset, fscs_reset, sblock.fs_fsize);
    816 		fs_csaddr++;
    817 		wtfs(fsbtodb(&sblock, fs_csaddr), sblock.fs_fsize, fscs_reset);
    818 		fscs_next = fscs_reset;
    819 		memset(fscs_next, 0, sblock.fs_fsize);
    820 	}
    821 	/*
    822 	 * Write out the duplicate super block, the cylinder group map
    823 	 * and two blocks worth of inodes in a single write.
    824 	 */
    825 	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
    826 	memcpy(&iobuf[start], &acg, sblock.fs_cgsize);
    827 	if (needswap)
    828 		ffs_cg_swap(&acg, (struct cg*)&iobuf[start], &sblock);
    829 	start += sblock.fs_bsize;
    830 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
    831 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
    832 	for (i = MIN(sblock.fs_ipg, 2) * INOPB(&sblock); i != 0; i--) {
    833 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
    834 			/* No need to swap, it'll stay random */
    835 			dp1->di_gen = arc4random() & INT32_MAX;
    836 			dp1++;
    837 		} else {
    838 			dp2->di_gen = arc4random() & INT32_MAX;
    839 			dp2++;
    840 		}
    841 	}
    842 	wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);
    843 	/*
    844 	 * For the old file system, we have to initialize all the inodes.
    845 	 */
    846 	if (Oflag <= 1) {
    847 		for (i = 2 * sblock.fs_frag;
    848 		     i < sblock.fs_ipg / INOPF(&sblock);
    849 		     i += sblock.fs_frag) {
    850 			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
    851 			for (j = 0; j < INOPB(&sblock); j++) {
    852 				dp1->di_gen = arc4random() & INT32_MAX;
    853 				dp1++;
    854 			}
    855 			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
    856 			    sblock.fs_bsize, &iobuf[start]);
    857 		}
    858 	}
    859 }
    860 
    861 /*
    862  * initialize the file system
    863  */
    864 
    865 #ifdef LOSTDIR
    866 #define	PREDEFDIR 3
    867 #else
    868 #define	PREDEFDIR 2
    869 #endif
    870 
    871 struct direct root_dir[] = {
    872 	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
    873 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
    874 #ifdef LOSTDIR
    875 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 10, "lost+found" },
    876 #endif
    877 };
    878 struct odirect {
    879 	u_int32_t d_ino;
    880 	u_int16_t d_reclen;
    881 	u_int16_t d_namlen;
    882 	u_char	d_name[MAXNAMLEN + 1];
    883 } oroot_dir[] = {
    884 	{ ROOTINO, sizeof(struct direct), 1, "." },
    885 	{ ROOTINO, sizeof(struct direct), 2, ".." },
    886 #ifdef LOSTDIR
    887 	{ LOSTFOUNDINO, sizeof(struct direct), 10, "lost+found" },
    888 #endif
    889 };
    890 #ifdef LOSTDIR
    891 struct direct lost_found_dir[] = {
    892 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 1, "." },
    893 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
    894 	{ 0, DIRBLKSIZ, 0, 0, 0 },
    895 };
    896 struct odirect olost_found_dir[] = {
    897 	{ LOSTFOUNDINO, sizeof(struct direct), 1, "." },
    898 	{ ROOTINO, sizeof(struct direct), 2, ".." },
    899 	{ 0, DIRBLKSIZ, 0, 0 },
    900 };
    901 #endif
    902 char buf[MAXBSIZE];
    903 static void copy_dir(struct direct *, struct direct *);
    904 
    905 int
    906 fsinit(const struct timeval *tv, mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
    907 {
    908 	union dinode node;
    909 #ifdef LOSTDIR
    910 	int i;
    911 	int dirblksiz = DIRBLKSIZ;
    912 	if (isappleufs)
    913 		dirblksiz = APPLEUFS_DIRBLKSIZ;
    914 #endif
    915 
    916 	/*
    917 	 * initialize the node
    918 	 */
    919 
    920 #ifdef LOSTDIR
    921 	/*
    922 	 * create the lost+found directory
    923 	 */
    924 	memset(&node, 0, sizeof(node));
    925 	if (Oflag == 0) {
    926 		(void)makedir((struct direct *)olost_found_dir, 2);
    927 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
    928 			copy_dir((struct direct*)&olost_found_dir[2],
    929 				(struct direct*)&buf[i]);
    930 	} else {
    931 		(void)makedir(lost_found_dir, 2);
    932 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
    933 			copy_dir(&lost_found_dir[2], (struct direct*)&buf[i]);
    934 	}
    935 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
    936 		node.dp1.di_atime = tv->tv_sec;
    937 		node.dp1.di_atimensec = tv->tv_usec * 1000;
    938 		node.dp1.di_mtime = tv->tv_sec;
    939 		node.dp1.di_mtimensec = tv->tv_usec * 1000;
    940 		node.dp1.di_ctime = tv->tv_sec;
    941 		node.dp1.di_ctimensec = tv->tv_usec * 1000;
    942 		node.dp1.di_mode = IFDIR | UMASK;
    943 		node.dp1.di_nlink = 2;
    944 		node.dp1.di_size = sblock.fs_bsize;
    945 		node.dp1.di_db[0] = alloc(node.dp1.di_size, node.dp1.di_mode);
    946 		if (node.dp1.di_db[0] == 0)
    947 			return (0);
    948 		node.dp1.di_blocks = btodb(fragroundup(&sblock,
    949 		    node.dp1.di_size));
    950 		node.dp1.di_uid = geteuid();
    951 		node.dp1.di_gid = getegid();
    952 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), node.dp1.di_size,
    953 		    buf);
    954 	} else {
    955 		node.dp2.di_atime = tv->tv_sec;
    956 		node.dp2.di_atimensec = tv->tv_usec * 1000;
    957 		node.dp2.di_mtime = tv->tv_sec;
    958 		node.dp2.di_mtimensec = tv->tv_usec * 1000;
    959 		node.dp2.di_ctime = tv->tv_sec;
    960 		node.dp2.di_ctimensec = tv->tv_usec * 1000;
    961 		node.dp2.di_birthtime = tv->tv_sec;
    962 		node.dp2.di_birthnsec = tv->tv_usec * 1000;
    963 		node.dp2.di_mode = IFDIR | UMASK;
    964 		node.dp2.di_nlink = 2;
    965 		node.dp2.di_size = sblock.fs_bsize;
    966 		node.dp2.di_db[0] = alloc(node.dp2.di_size, node.dp2.di_mode);
    967 		if (node.dp2.di_db[0] == 0)
    968 			return (0);
    969 		node.dp2.di_blocks = btodb(fragroundup(&sblock,
    970 		    node.dp2.di_size));
    971 		node.dp2.di_uid = geteuid();
    972 		node.dp2.di_gid = getegid();
    973 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), node.dp2.di_size,
    974 		    buf);
    975 	}
    976 	iput(&node, LOSTFOUNDINO);
    977 #endif
    978 	/*
    979 	 * create the root directory
    980 	 */
    981 	memset(&node, 0, sizeof(node));
    982 	if (Oflag <= 1) {
    983 		if (mfs) {
    984 			node.dp1.di_mode = IFDIR | mfsmode;
    985 			node.dp1.di_uid = mfsuid;
    986 			node.dp1.di_gid = mfsgid;
    987 		} else {
    988 			node.dp1.di_mode = IFDIR | UMASK;
    989 			node.dp1.di_uid = geteuid();
    990 			node.dp1.di_gid = getegid();
    991 		}
    992 		node.dp1.di_nlink = PREDEFDIR;
    993 		if (Oflag == 0)
    994 			node.dp1.di_size = makedir((struct direct *)oroot_dir,
    995 			    PREDEFDIR);
    996 		else
    997 			node.dp1.di_size = makedir(root_dir, PREDEFDIR);
    998 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
    999 		if (node.dp1.di_db[0] == 0)
   1000 			return (0);
   1001 		node.dp1.di_blocks = btodb(fragroundup(&sblock,
   1002 		    node.dp1.di_size));
   1003 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, buf);
   1004 	} else {
   1005 		if (mfs) {
   1006 			node.dp2.di_mode = IFDIR | mfsmode;
   1007 			node.dp2.di_uid = mfsuid;
   1008 			node.dp2.di_gid = mfsgid;
   1009 		} else {
   1010 			node.dp2.di_mode = IFDIR | UMASK;
   1011 			node.dp2.di_uid = geteuid();
   1012 			node.dp2.di_gid = getegid();
   1013 		}
   1014 		node.dp2.di_atime = tv->tv_sec;
   1015 		node.dp2.di_atimensec = tv->tv_usec * 1000;
   1016 		node.dp2.di_mtime = tv->tv_sec;
   1017 		node.dp2.di_mtimensec = tv->tv_usec * 1000;
   1018 		node.dp2.di_ctime = tv->tv_sec;
   1019 		node.dp2.di_ctimensec = tv->tv_usec * 1000;
   1020 		node.dp2.di_birthtime = tv->tv_sec;
   1021 		node.dp2.di_birthnsec = tv->tv_usec * 1000;
   1022 		node.dp2.di_nlink = PREDEFDIR;
   1023 		node.dp2.di_size = makedir(root_dir, PREDEFDIR);
   1024 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
   1025 		if (node.dp2.di_db[0] == 0)
   1026 			return (0);
   1027 		node.dp2.di_blocks = btodb(fragroundup(&sblock,
   1028 		    node.dp2.di_size));
   1029 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, buf);
   1030 	}
   1031 	iput(&node, ROOTINO);
   1032 	return (1);
   1033 }
   1034 
   1035 /*
   1036  * construct a set of directory entries in "buf".
   1037  * return size of directory.
   1038  */
   1039 int
   1040 makedir(struct direct *protodir, int entries)
   1041 {
   1042 	char *cp;
   1043 	int i, spcleft;
   1044 	int dirblksiz = DIRBLKSIZ;
   1045 	if (isappleufs)
   1046 		dirblksiz = APPLEUFS_DIRBLKSIZ;
   1047 
   1048 	memset(buf, 0, DIRBLKSIZ);
   1049 	spcleft = dirblksiz;
   1050 	for (cp = buf, i = 0; i < entries - 1; i++) {
   1051 		protodir[i].d_reclen = DIRSIZ(Oflag == 0, &protodir[i], 0);
   1052 		copy_dir(&protodir[i], (struct direct*)cp);
   1053 		cp += protodir[i].d_reclen;
   1054 		spcleft -= protodir[i].d_reclen;
   1055 	}
   1056 	protodir[i].d_reclen = spcleft;
   1057 	copy_dir(&protodir[i], (struct direct*)cp);
   1058 	return (dirblksiz);
   1059 }
   1060 
   1061 /*
   1062  * allocate a block or frag
   1063  */
   1064 daddr_t
   1065 alloc(int size, int mode)
   1066 {
   1067 	int i, frag;
   1068 	daddr_t d, blkno;
   1069 
   1070 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1071 	/* fs -> host byte order */
   1072 	if (needswap)
   1073 		ffs_cg_swap(&acg, &acg, &sblock);
   1074 	if (acg.cg_magic != CG_MAGIC) {
   1075 		printf("cg 0: bad magic number\n");
   1076 		return (0);
   1077 	}
   1078 	if (acg.cg_cs.cs_nbfree == 0) {
   1079 		printf("first cylinder group ran out of space\n");
   1080 		return (0);
   1081 	}
   1082 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
   1083 		if (isblock(&sblock, cg_blksfree(&acg, 0),
   1084 		    d >> sblock.fs_fragshift))
   1085 			goto goth;
   1086 	printf("internal error: can't find block in cyl 0\n");
   1087 	return (0);
   1088 goth:
   1089 	blkno = fragstoblks(&sblock, d);
   1090 	clrblock(&sblock, cg_blksfree(&acg, 0), blkno);
   1091 	if (sblock.fs_contigsumsize > 0)
   1092 		clrbit(cg_clustersfree(&acg, 0), blkno);
   1093 	acg.cg_cs.cs_nbfree--;
   1094 	sblock.fs_cstotal.cs_nbfree--;
   1095 	fscs_0->cs_nbfree--;
   1096 	if (mode & IFDIR) {
   1097 		acg.cg_cs.cs_ndir++;
   1098 		sblock.fs_cstotal.cs_ndir++;
   1099 		fscs_0->cs_ndir++;
   1100 	}
   1101 	if (size != sblock.fs_bsize) {
   1102 		frag = howmany(size, sblock.fs_fsize);
   1103 		fscs_0->cs_nffree += sblock.fs_frag - frag;
   1104 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
   1105 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
   1106 		acg.cg_frsum[sblock.fs_frag - frag]++;
   1107 		for (i = frag; i < sblock.fs_frag; i++)
   1108 			setbit(cg_blksfree(&acg, 0), d + i);
   1109 	}
   1110 	/* host -> fs byte order */
   1111 	if (needswap)
   1112 		ffs_cg_swap(&acg, &acg, &sblock);
   1113 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1114 	return (d);
   1115 }
   1116 
   1117 /*
   1118  * Allocate an inode on the disk
   1119  */
   1120 static void
   1121 iput(union dinode *ip, ino_t ino)
   1122 {
   1123 	daddr_t d;
   1124 	int c, i;
   1125 	struct ufs1_dinode *dp1;
   1126 	struct ufs2_dinode *dp2;
   1127 
   1128 	c = ino_to_cg(&sblock, ino);
   1129 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1130 	/* fs -> host byte order */
   1131 	if (needswap)
   1132 		ffs_cg_swap(&acg, &acg, &sblock);
   1133 	if (acg.cg_magic != CG_MAGIC) {
   1134 		printf("cg 0: bad magic number\n");
   1135 		exit(31);
   1136 	}
   1137 	acg.cg_cs.cs_nifree--;
   1138 	setbit(cg_inosused(&acg, 0), ino);
   1139 	/* host -> fs byte order */
   1140 	if (needswap)
   1141 		ffs_cg_swap(&acg, &acg, &sblock);
   1142 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1143 	sblock.fs_cstotal.cs_nifree--;
   1144 	fscs_0->cs_nifree--;
   1145 	if (ino >= sblock.fs_ipg * sblock.fs_ncg) {
   1146 		printf("fsinit: inode value out of range (%d).\n", ino);
   1147 		exit(32);
   1148 	}
   1149 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
   1150 	rdfs(d, sblock.fs_bsize, (char *)iobuf);
   1151 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
   1152 		dp1 = (struct ufs1_dinode *)iobuf;
   1153 		dp1 += ino_to_fsbo(&sblock, ino);
   1154 		if (needswap) {
   1155 			ffs_dinode1_swap(&ip->dp1, dp1);
   1156 			/* ffs_dinode1_swap() doesn't swap blocks addrs */
   1157 			for (i=0; i<NDADDR + NIADDR; i++)
   1158 			    dp1->di_db[i] = bswap32(ip->dp1.di_db[i]);
   1159 		} else
   1160 			*dp1 = ip->dp1;
   1161 		dp1->di_gen = arc4random() & INT32_MAX;
   1162 	} else {
   1163 		dp2 = (struct ufs2_dinode *)iobuf;
   1164 		dp2 += ino_to_fsbo(&sblock, ino);
   1165 		if (needswap) {
   1166 			ffs_dinode2_swap(&ip->dp2, dp2);
   1167 			for (i=0; i<NDADDR + NIADDR; i++)
   1168 			    dp2->di_db[i] = bswap32(ip->dp2.di_db[i]);
   1169 		} else
   1170 			*dp2 = ip->dp2;
   1171 		dp2->di_gen = arc4random() & INT32_MAX;
   1172 	}
   1173 	wtfs(d, sblock.fs_bsize, iobuf);
   1174 }
   1175 
   1176 /*
   1177  * read a block from the file system
   1178  */
   1179 void
   1180 rdfs(daddr_t bno, int size, void *bf)
   1181 {
   1182 	int n;
   1183 	off_t offset;
   1184 
   1185 #ifdef MFS
   1186 	if (mfs) {
   1187 		memmove(bf, membase + bno * sectorsize, size);
   1188 		return;
   1189 	}
   1190 #endif
   1191 	offset = bno;
   1192 	n = pread(fsi, bf, size, offset * sectorsize);
   1193 	if (n != size) {
   1194 		printf("rdfs: read error for sector %lld: %s\n",
   1195 		    (long long)bno, strerror(errno));
   1196 		exit(34);
   1197 	}
   1198 }
   1199 
   1200 /*
   1201  * write a block to the file system
   1202  */
   1203 void
   1204 wtfs(daddr_t bno, int size, void *bf)
   1205 {
   1206 	int n;
   1207 	off_t offset;
   1208 
   1209 #ifdef MFS
   1210 	if (mfs) {
   1211 		memmove(membase + bno * sectorsize, bf, size);
   1212 		return;
   1213 	}
   1214 #endif
   1215 	if (Nflag)
   1216 		return;
   1217 	offset = bno;
   1218 	n = pwrite(fso, bf, size, offset * sectorsize);
   1219 	if (n != size) {
   1220 		printf("wtfs: write error for sector %lld: %s\n",
   1221 		    (long long)bno, strerror(errno));
   1222 		exit(36);
   1223 	}
   1224 }
   1225 
   1226 /*
   1227  * check if a block is available
   1228  */
   1229 int
   1230 isblock(struct fs *fs, unsigned char *cp, int h)
   1231 {
   1232 	unsigned char mask;
   1233 
   1234 	switch (fs->fs_fragshift) {
   1235 	case 3:
   1236 		return (cp[h] == 0xff);
   1237 	case 2:
   1238 		mask = 0x0f << ((h & 0x1) << 2);
   1239 		return ((cp[h >> 1] & mask) == mask);
   1240 	case 1:
   1241 		mask = 0x03 << ((h & 0x3) << 1);
   1242 		return ((cp[h >> 2] & mask) == mask);
   1243 	case 0:
   1244 		mask = 0x01 << (h & 0x7);
   1245 		return ((cp[h >> 3] & mask) == mask);
   1246 	default:
   1247 #ifdef STANDALONE
   1248 		printf("isblock bad fs_fragshift %d\n", fs->fs_fragshift);
   1249 #else
   1250 		fprintf(stderr, "isblock bad fs_fragshift %d\n",
   1251 		    fs->fs_fragshift);
   1252 #endif
   1253 		return (0);
   1254 	}
   1255 }
   1256 
   1257 /*
   1258  * take a block out of the map
   1259  */
   1260 void
   1261 clrblock(struct fs *fs, unsigned char *cp, int h)
   1262 {
   1263 	switch ((fs)->fs_fragshift) {
   1264 	case 3:
   1265 		cp[h] = 0;
   1266 		return;
   1267 	case 2:
   1268 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
   1269 		return;
   1270 	case 1:
   1271 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
   1272 		return;
   1273 	case 0:
   1274 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
   1275 		return;
   1276 	default:
   1277 #ifdef STANDALONE
   1278 		printf("clrblock bad fs_fragshift %d\n", fs->fs_fragshift);
   1279 #else
   1280 		fprintf(stderr, "clrblock bad fs_fragshift %d\n",
   1281 		    fs->fs_fragshift);
   1282 #endif
   1283 		return;
   1284 	}
   1285 }
   1286 
   1287 /*
   1288  * put a block into the map
   1289  */
   1290 void
   1291 setblock(struct fs *fs, unsigned char *cp, int h)
   1292 {
   1293 	switch (fs->fs_fragshift) {
   1294 	case 3:
   1295 		cp[h] = 0xff;
   1296 		return;
   1297 	case 2:
   1298 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
   1299 		return;
   1300 	case 1:
   1301 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
   1302 		return;
   1303 	case 0:
   1304 		cp[h >> 3] |= (0x01 << (h & 0x7));
   1305 		return;
   1306 	default:
   1307 #ifdef STANDALONE
   1308 		printf("setblock bad fs_frag %d\n", fs->fs_fragshift);
   1309 #else
   1310 		fprintf(stderr, "setblock bad fs_fragshift %d\n",
   1311 		    fs->fs_fragshift);
   1312 #endif
   1313 		return;
   1314 	}
   1315 }
   1316 
   1317 /* copy a direntry to a buffer, in fs byte order */
   1318 static void
   1319 copy_dir(struct direct *dir, struct direct *dbuf)
   1320 {
   1321 	memcpy(dbuf, dir, DIRSIZ(Oflag == 0, dir, 0));
   1322 	if (needswap) {
   1323 		dbuf->d_ino = bswap32(dir->d_ino);
   1324 		dbuf->d_reclen = bswap16(dir->d_reclen);
   1325 		if (Oflag == 0)
   1326 			((struct odirect*)dbuf)->d_namlen =
   1327 				bswap16(((struct odirect*)dir)->d_namlen);
   1328 	}
   1329 }
   1330 
   1331 /* Determine how many digits are needed to print a given integer */
   1332 static int
   1333 count_digits(uint64_t num)
   1334 {
   1335 	int ndig;
   1336 
   1337 	for (ndig = 1; num > 9; num /= 10, ndig++);
   1338 
   1339 	return (ndig);
   1340 }
   1341 
   1342 static int
   1343 ilog2(int val)
   1344 {
   1345 	u_int n;
   1346 
   1347 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
   1348 		if (1 << n == val)
   1349 			return (n);
   1350 	errx(1, "ilog2: %d is not a power of 2\n", val);
   1351 }
   1352 
   1353 static void
   1354 zap_old_sblock(int sblkoff)
   1355 {
   1356 	static int cg0_data;
   1357 	uint32_t oldfs[SBLOCKSIZE / 4];
   1358 	static const struct fsm {
   1359 		uint32_t	offset;
   1360 		uint32_t	magic;
   1361 		uint32_t	mask;
   1362 	} fs_magics[] = {
   1363 		{offsetof(struct fs, fs_magic)/4, FS_UFS1_MAGIC, ~0u},
   1364 		{offsetof(struct fs, fs_magic)/4, FS_UFS2_MAGIC, ~0u},
   1365 		{0, 0x70162, ~0u},		/* LFS_MAGIC */
   1366 		{14, 0xef53, 0xffff},		/* EXT2FS (little) */
   1367 		{14, 0xef530000, 0xffff0000},	/* EXT2FS (big) */
   1368 		{~0u},
   1369 	};
   1370 	const struct fsm *fsm;
   1371 
   1372 	if (cg0_data == 0)
   1373 		/* For FFSv1 this could include all the inodes. */
   1374 		cg0_data = cgsblock(&sblock, 0) * sblock.fs_fsize + iobufsize;
   1375 
   1376 	/* Ignore anything that is beyond our filesystem */
   1377 	if ((sblkoff + SBLOCKSIZE)/sectorsize >= fssize)
   1378 		return;
   1379 	/* Zero anything inside our filesystem... */
   1380 	if (sblkoff >= sblock.fs_sblockloc) {
   1381 		/* ...unless we will write that area anyway */
   1382 		if (sblkoff >= cg0_data)
   1383 			wtfs(sblkoff/sectorsize, sizeof sblock, iobuf);
   1384 		return;
   1385 	}
   1386 
   1387 	/* The sector might contain boot code, so we must validate it */
   1388 	rdfs(sblkoff/sectorsize, sizeof oldfs, &oldfs);
   1389 	for (fsm = fs_magics; ; fsm++) {
   1390 		uint32_t v;
   1391 		if (fsm->mask == 0)
   1392 			return;
   1393 		v = oldfs[fsm->offset];
   1394 		if ((v & fsm->mask) == fsm->magic ||
   1395 		    (bswap32(v) & fsm->mask) == fsm->magic)
   1396 			break;
   1397 	}
   1398 
   1399 	/* Just zap the magic number */
   1400 	oldfs[fsm->offset] = 0;
   1401 	wtfs(sblkoff/sectorsize, sizeof oldfs, &oldfs);
   1402 }
   1403 
   1404 
   1405 #ifdef MFS
   1406 /*
   1407  * XXX!
   1408  * Attempt to guess how much more space is available for process data.  The
   1409  * heuristic we use is
   1410  *
   1411  *	max_data_limit - (sbrk(0) - etext) - 128kB
   1412  *
   1413  * etext approximates that start address of the data segment, and the 128kB
   1414  * allows some slop for both segment gap between text and data, and for other
   1415  * (libc) malloc usage.
   1416  */
   1417 static void
   1418 calc_memfree(void)
   1419 {
   1420 	extern char etext;
   1421 	struct rlimit rlp;
   1422 	u_long base;
   1423 
   1424 	base = (u_long)sbrk(0) - (u_long)&etext;
   1425 	if (getrlimit(RLIMIT_DATA, &rlp) < 0)
   1426 		perror("getrlimit");
   1427 	rlp.rlim_cur = rlp.rlim_max;
   1428 	if (setrlimit(RLIMIT_DATA, &rlp) < 0)
   1429 		perror("setrlimit");
   1430 	memleft = rlp.rlim_max - base - (128 * 1024);
   1431 }
   1432 
   1433 /*
   1434  * Internal version of malloc that trims the requested size if not enough
   1435  * memory is available.
   1436  */
   1437 static void *
   1438 mkfs_malloc(size_t size)
   1439 {
   1440 	u_long pgsz;
   1441 
   1442 	if (size == 0)
   1443 		return (NULL);
   1444 	if (memleft == 0)
   1445 		calc_memfree();
   1446 
   1447 	pgsz = getpagesize() - 1;
   1448 	size = (size + pgsz) &~ pgsz;
   1449 	if (size > memleft)
   1450 		size = memleft;
   1451 	memleft -= size;
   1452 	return (mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
   1453 	    -1, 0));
   1454 }
   1455 #endif	/* MFS */
   1456