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