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