Home | History | Annotate | Line # | Download | only in newfs
mkfs.c revision 1.67
      1 /*	$NetBSD: mkfs.c,v 1.67 2003/02/14 16:21:49 grant 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. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 #if 0
     39 static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
     40 #else
     41 __RCSID("$NetBSD: mkfs.c,v 1.67 2003/02/14 16:21:49 grant Exp $");
     42 #endif
     43 #endif /* not lint */
     44 
     45 #include <sys/param.h>
     46 #include <sys/mman.h>
     47 #include <sys/time.h>
     48 #include <sys/resource.h>
     49 #include <ufs/ufs/dinode.h>
     50 #include <ufs/ufs/dir.h>
     51 #include <ufs/ufs/ufs_bswap.h>
     52 #include <ufs/ffs/fs.h>
     53 #include <ufs/ffs/ffs_extern.h>
     54 #include <sys/disklabel.h>
     55 
     56 #include <err.h>
     57 #include <errno.h>
     58 #include <string.h>
     59 #include <unistd.h>
     60 #include <stdlib.h>
     61 
     62 #ifndef STANDALONE
     63 #include <stdio.h>
     64 #endif
     65 
     66 #include "extern.h"
     67 
     68 static void initcg(int, time_t);
     69 static int fsinit(time_t, mode_t, uid_t, gid_t);
     70 static int makedir(struct direct *, int);
     71 static daddr_t alloc(int, int);
     72 static void iput(struct dinode *, ino_t);
     73 static void rdfs(daddr_t, int, void *);
     74 static void wtfs(daddr_t, int, void *);
     75 static int isblock(struct fs *, unsigned char *, int);
     76 static void clrblock(struct fs *, unsigned char *, int);
     77 static void setblock(struct fs *, unsigned char *, int);
     78 static int32_t calcipg(int32_t, int32_t, off_t *);
     79 static void swap_cg(struct cg *, struct cg *);
     80 #ifdef MFS
     81 static void calc_memfree(void);
     82 static void *mkfs_malloc(size_t size);
     83 #endif
     84 
     85 static int count_digits(int);
     86 
     87 /*
     88  * make file system for cylinder-group style file systems
     89  */
     90 
     91 /*
     92  * We limit the size of the inode map to be no more than a
     93  * third of the cylinder group space, since we must leave at
     94  * least an equal amount of space for the block map.
     95  *
     96  * N.B.: MAXIPG must be a multiple of INOPB(fs).
     97  */
     98 #define	MAXIPG(fs)	roundup((fs)->fs_bsize * NBBY / 3, INOPB(fs))
     99 
    100 #define	UMASK		0755
    101 #define	MAXINOPB	(MAXBSIZE / DINODE_SIZE)
    102 #define	POWEROF2(num)	(((num) & ((num) - 1)) == 0)
    103 
    104 union {
    105 	struct fs fs;
    106 	char pad[SBSIZE];
    107 } fsun;
    108 #define	sblock	fsun.fs
    109 struct	csum *fscs;
    110 
    111 union {
    112 	struct cg cg;
    113 	char pad[MAXBSIZE];
    114 } cgun;
    115 #define	acg	cgun.cg
    116 
    117 struct dinode zino[MAXBSIZE / DINODE_SIZE];
    118 
    119 char writebuf[MAXBSIZE];
    120 
    121 int	fsi, fso;
    122 
    123 void
    124 mkfs(struct partition *pp, const char *fsys, int fi, int fo,
    125     mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
    126 {
    127 	int32_t i, mincpc, mincpg, inospercg;
    128 	int32_t cylno, rpos, blk, j, warning = 0;
    129 	int32_t used, mincpgcnt, bpcg;
    130 	off_t usedb;
    131 	int32_t mapcramped, inodecramped;
    132 	int32_t postblsize, rotblsize, totalsbsize;
    133 	time_t utime;
    134 	long long sizepb;
    135 	char *writebuf2;		/* dynamic buffer */
    136 	int nprintcols, printcolwidth;
    137 
    138 #ifndef STANDALONE
    139 	time(&utime);
    140 #endif
    141 #ifdef MFS
    142 	if (mfs) {
    143 		calc_memfree();
    144 		if (fssize * sectorsize > memleft)
    145 			fssize = memleft / sectorsize;
    146 		if ((membase = mkfs_malloc(fssize * sectorsize)) == 0)
    147 			exit(12);
    148 	}
    149 #endif
    150 	fsi = fi;
    151 	fso = fo;
    152 	if (Oflag) {
    153 		sblock.fs_inodefmt = FS_42INODEFMT;
    154 		sblock.fs_maxsymlinklen = 0;
    155 	} else {
    156 		sblock.fs_inodefmt = FS_44INODEFMT;
    157 		sblock.fs_maxsymlinklen = MAXSYMLINKLEN;
    158 	}
    159 	/*
    160 	 * Validate the given file system size.
    161 	 * Verify that its last block can actually be accessed.
    162 	 */
    163 	if (fssize <= 0)
    164 		printf("preposterous size %d\n", fssize), exit(13);
    165 	wtfs(fssize - 1, sectorsize, (char *)&sblock);
    166 
    167 	if (isappleufs) {
    168 		struct appleufslabel appleufs;
    169 		ffs_appleufs_set(&appleufs,appleufs_volname,utime);
    170 		wtfs(APPLEUFS_LABEL_OFFSET/sectorsize,APPLEUFS_LABEL_SIZE,&appleufs);
    171 	}
    172 
    173 	/*
    174 	 * collect and verify the sector and track info
    175 	 */
    176 	sblock.fs_nsect = nsectors;
    177 	sblock.fs_ntrak = ntracks;
    178 	if (sblock.fs_ntrak <= 0)
    179 		printf("preposterous ntrak %d\n", sblock.fs_ntrak), exit(14);
    180 	if (sblock.fs_nsect <= 0)
    181 		printf("preposterous nsect %d\n", sblock.fs_nsect), exit(15);
    182 	/*
    183 	 * collect and verify the filesystem density info
    184 	 */
    185 	sblock.fs_avgfilesize = avgfilesize;
    186 	sblock.fs_avgfpdir = avgfpdir;
    187 	if (sblock.fs_avgfilesize <= 0)
    188 		printf("illegal expected average file size %d\n",
    189 		    sblock.fs_avgfilesize), exit(14);
    190 	if (sblock.fs_avgfpdir <= 0)
    191 		printf("illegal expected number of files per directory %d\n",
    192 		    sblock.fs_avgfpdir), exit(15);
    193 	/*
    194 	 * collect and verify the block and fragment sizes
    195 	 */
    196 	sblock.fs_bsize = bsize;
    197 	sblock.fs_fsize = fsize;
    198 	if (!POWEROF2(sblock.fs_bsize)) {
    199 		printf("block size must be a power of 2, not %d\n",
    200 		    sblock.fs_bsize);
    201 		exit(16);
    202 	}
    203 	if (!POWEROF2(sblock.fs_fsize)) {
    204 		printf("fragment size must be a power of 2, not %d\n",
    205 		    sblock.fs_fsize);
    206 		exit(17);
    207 	}
    208 	if (sblock.fs_fsize < sectorsize) {
    209 		printf("fragment size %d is too small, minimum is %d\n",
    210 		    sblock.fs_fsize, sectorsize);
    211 		exit(18);
    212 	}
    213 	if (sblock.fs_bsize < MINBSIZE) {
    214 		printf("block size %d is too small, minimum is %d\n",
    215 		    sblock.fs_bsize, MINBSIZE);
    216 		exit(19);
    217 	}
    218 	if (sblock.fs_bsize > MAXBSIZE) {
    219 		printf("block size %d is too large, maximum is %d\n",
    220 		    sblock.fs_bsize, MAXBSIZE);
    221 		exit(19);
    222 	}
    223 	if (sblock.fs_bsize < sblock.fs_fsize) {
    224 		printf("block size (%d) cannot be smaller than fragment size (%d)\n",
    225 		    sblock.fs_bsize, sblock.fs_fsize);
    226 		exit(20);
    227 	}
    228 	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
    229 	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
    230 	sblock.fs_qbmask = ~sblock.fs_bmask;
    231 	sblock.fs_qfmask = ~sblock.fs_fmask;
    232 	for (sblock.fs_bshift = 0, i = sblock.fs_bsize; i > 1; i >>= 1)
    233 		sblock.fs_bshift++;
    234 	for (sblock.fs_fshift = 0, i = sblock.fs_fsize; i > 1; i >>= 1)
    235 		sblock.fs_fshift++;
    236 	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
    237 	for (sblock.fs_fragshift = 0, i = sblock.fs_frag; i > 1; i >>= 1)
    238 		sblock.fs_fragshift++;
    239 	if (sblock.fs_frag > MAXFRAG) {
    240 		printf("fragment size %d is too small, "
    241 			"minimum with block size %d is %d\n",
    242 		    sblock.fs_fsize, sblock.fs_bsize,
    243 		    sblock.fs_bsize / MAXFRAG);
    244 		exit(21);
    245 	}
    246 	sblock.fs_nrpos = nrpos;
    247 	/* XXX ondisk32 */
    248 	sblock.fs_nindir = sblock.fs_bsize / sizeof(int32_t);
    249 	sblock.fs_inopb = sblock.fs_bsize / DINODE_SIZE;
    250 	sblock.fs_nspf = sblock.fs_fsize / sectorsize;
    251 	for (sblock.fs_fsbtodb = 0, i = NSPF(&sblock); i > 1; i >>= 1)
    252 		sblock.fs_fsbtodb++;
    253 	sblock.fs_sblkno =
    254 	    roundup(howmany(bbsize + sbsize, sblock.fs_fsize), sblock.fs_frag);
    255 	sblock.fs_cblkno = (daddr_t)(sblock.fs_sblkno +
    256 	    roundup(howmany(sbsize, sblock.fs_fsize), sblock.fs_frag));
    257 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
    258 	sblock.fs_cgoffset = roundup(
    259 	    howmany(sblock.fs_nsect, NSPF(&sblock)), sblock.fs_frag);
    260 	for (sblock.fs_cgmask = 0xffffffff, i = sblock.fs_ntrak; i > 1; i >>= 1)
    261 		sblock.fs_cgmask <<= 1;
    262 	if (!POWEROF2(sblock.fs_ntrak))
    263 		sblock.fs_cgmask <<= 1;
    264 	sblock.fs_maxfilesize = sblock.fs_bsize * NDADDR - 1;
    265 	for (sizepb = sblock.fs_bsize, i = 0; i < NIADDR; i++) {
    266 		sizepb *= NINDIR(&sblock);
    267 		sblock.fs_maxfilesize += sizepb;
    268 	}
    269 	/*
    270 	 * Validate specified/determined secpercyl
    271 	 * and calculate minimum cylinders per group.
    272 	 */
    273 	sblock.fs_spc = secpercyl;
    274 	for (sblock.fs_cpc = NSPB(&sblock), i = sblock.fs_spc;
    275 	     sblock.fs_cpc > 1 && (i & 1) == 0;
    276 	     sblock.fs_cpc >>= 1, i >>= 1)
    277 		/* void */;
    278 	mincpc = sblock.fs_cpc;
    279 	bpcg = sblock.fs_spc * sectorsize;
    280 	inospercg = roundup(bpcg / DINODE_SIZE, INOPB(&sblock));
    281 	if (inospercg > MAXIPG(&sblock))
    282 		inospercg = MAXIPG(&sblock);
    283 	used = (sblock.fs_iblkno + inospercg / INOPF(&sblock)) * NSPF(&sblock);
    284 	mincpgcnt = howmany(sblock.fs_cgoffset * (~sblock.fs_cgmask) + used,
    285 	    sblock.fs_spc);
    286 	mincpg = roundup(mincpgcnt, mincpc);
    287 	/*
    288 	 * Ensure that cylinder group with mincpg has enough space
    289 	 * for block maps.
    290 	 */
    291 	sblock.fs_cpg = mincpg;
    292 	sblock.fs_ipg = inospercg;
    293 	if (maxcontig > 1)
    294 		sblock.fs_contigsumsize = MIN(maxcontig, FS_MAXCONTIG);
    295 	mapcramped = 0;
    296 	while (CGSIZE(&sblock) > sblock.fs_bsize) {
    297 		mapcramped = 1;
    298 		if (sblock.fs_bsize < MAXBSIZE) {
    299 			sblock.fs_bsize <<= 1;
    300 			if ((i & 1) == 0) {
    301 				i >>= 1;
    302 			} else {
    303 				sblock.fs_cpc <<= 1;
    304 				mincpc <<= 1;
    305 				mincpg = roundup(mincpgcnt, mincpc);
    306 				sblock.fs_cpg = mincpg;
    307 			}
    308 			sblock.fs_frag <<= 1;
    309 			sblock.fs_fragshift += 1;
    310 			if (sblock.fs_frag <= MAXFRAG)
    311 				continue;
    312 		}
    313 		if (sblock.fs_fsize == sblock.fs_bsize) {
    314 			printf("There is no block size that");
    315 			printf(" can support this disk\n");
    316 			exit(22);
    317 		}
    318 		sblock.fs_frag >>= 1;
    319 		sblock.fs_fragshift -= 1;
    320 		sblock.fs_fsize <<= 1;
    321 		sblock.fs_nspf <<= 1;
    322 	}
    323 	/*
    324 	 * Ensure that cylinder group with mincpg has enough space for inodes.
    325 	 */
    326 	inodecramped = 0;
    327 	inospercg = calcipg(mincpg, bpcg, &usedb);
    328 	sblock.fs_ipg = inospercg;
    329 	while (inospercg > MAXIPG(&sblock)) {
    330 		inodecramped = 1;
    331 		if (mincpc == 1 || sblock.fs_frag == 1 ||
    332 		    sblock.fs_bsize == MINBSIZE)
    333 			break;
    334 		printf("With a block size of %d %s %d\n", sblock.fs_bsize,
    335 		       "minimum bytes per inode is",
    336 		       (int)((mincpg * (off_t)bpcg - usedb)
    337 			     / MAXIPG(&sblock) + 1));
    338 		sblock.fs_bsize >>= 1;
    339 		sblock.fs_frag >>= 1;
    340 		sblock.fs_fragshift -= 1;
    341 		mincpc >>= 1;
    342 		sblock.fs_cpg = roundup(mincpgcnt, mincpc);
    343 		if (CGSIZE(&sblock) > sblock.fs_bsize) {
    344 			sblock.fs_bsize <<= 1;
    345 			break;
    346 		}
    347 		mincpg = sblock.fs_cpg;
    348 		inospercg = calcipg(mincpg, bpcg, &usedb);
    349 		sblock.fs_ipg = inospercg;
    350 	}
    351 	if (inodecramped) {
    352 		if (inospercg > MAXIPG(&sblock)) {
    353 			printf("Minimum bytes per inode is %d\n",
    354 			       (int)((mincpg * (off_t)bpcg - usedb)
    355 				     / MAXIPG(&sblock) + 1));
    356 		} else if (!mapcramped) {
    357 			printf("With %d bytes per inode, ", density);
    358 			printf("minimum cylinders per group is %d\n", mincpg);
    359 		}
    360 	}
    361 	if (mapcramped) {
    362 		printf("With %d sectors per cylinder, ", sblock.fs_spc);
    363 		printf("minimum cylinders per group is %d\n", mincpg);
    364 	}
    365 	if (inodecramped || mapcramped) {
    366 		if (sblock.fs_bsize != bsize)
    367 			printf("%s to be changed from %d to %d\n",
    368 			    "This requires the block size",
    369 			    bsize, sblock.fs_bsize);
    370 		if (sblock.fs_fsize != fsize)
    371 			printf("\t%s to be changed from %d to %d\n",
    372 			    "and the fragment size",
    373 			    fsize, sblock.fs_fsize);
    374 		exit(23);
    375 	}
    376 	/*
    377 	 * Calculate the number of cylinders per group
    378 	 */
    379 	sblock.fs_cpg = cpg;
    380 	if (sblock.fs_cpg % mincpc != 0) {
    381 		printf("%s groups must have a multiple of %d cylinders\n",
    382 			cpgflg ? "Cylinder" : "Warning: cylinder", mincpc);
    383 		sblock.fs_cpg = roundup(sblock.fs_cpg, mincpc);
    384 		if (!cpgflg)
    385 			cpg = sblock.fs_cpg;
    386 	}
    387 	/*
    388 	 * Must ensure there is enough space for inodes.
    389 	 */
    390 	sblock.fs_ipg = calcipg(sblock.fs_cpg, bpcg, &usedb);
    391 	while (sblock.fs_ipg > MAXIPG(&sblock)) {
    392 		inodecramped = 1;
    393 		sblock.fs_cpg -= mincpc;
    394 		sblock.fs_ipg = calcipg(sblock.fs_cpg, bpcg, &usedb);
    395 	}
    396 	/*
    397 	 * Must ensure there is enough space to hold block map.
    398 	 */
    399 	while (CGSIZE(&sblock) > sblock.fs_bsize) {
    400 		mapcramped = 1;
    401 		sblock.fs_cpg -= mincpc;
    402 		sblock.fs_ipg = calcipg(sblock.fs_cpg, bpcg, &usedb);
    403 	}
    404 	sblock.fs_fpg = (sblock.fs_cpg * sblock.fs_spc) / NSPF(&sblock);
    405 	if ((sblock.fs_cpg * sblock.fs_spc) % NSPB(&sblock) != 0) {
    406 		printf("panic (fs_cpg * fs_spc) %% NSPF != 0");
    407 		exit(24);
    408 	}
    409 	if (sblock.fs_cpg < mincpg) {
    410 		printf("cylinder groups must have at least %d cylinders\n",
    411 			mincpg);
    412 		exit(25);
    413 	} else if (sblock.fs_cpg != cpg && cpgflg) {
    414 		if (!mapcramped && !inodecramped)
    415 			exit(26);
    416 		if (mapcramped && inodecramped)
    417 			printf("Block size and bytes per inode restrict");
    418 		else if (mapcramped)
    419 			printf("Block size restricts");
    420 		else
    421 			printf("Bytes per inode restrict");
    422 		printf(" cylinders per group to %d.\n", sblock.fs_cpg);
    423 		exit(27);
    424 	}
    425 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
    426 	/*
    427 	 * Now have size for file system and nsect and ntrak.
    428 	 * Determine number of cylinders and blocks in the file system.
    429 	 */
    430 	sblock.fs_size = fssize = dbtofsb(&sblock, fssize);
    431 	sblock.fs_ncyl = fssize * NSPF(&sblock) / sblock.fs_spc;
    432 	if (fssize * NSPF(&sblock) > sblock.fs_ncyl * sblock.fs_spc) {
    433 		sblock.fs_ncyl++;
    434 		warning = 1;
    435 	}
    436 	if (sblock.fs_ncyl < 1) {
    437 		printf("file systems must have at least one cylinder\n");
    438 		exit(28);
    439 	}
    440 	/*
    441 	 * Determine feasability/values of rotational layout tables.
    442 	 *
    443 	 * The size of the rotational layout tables is limited by the
    444 	 * size of the superblock, SBSIZE. The amount of space available
    445 	 * for tables is calculated as (SBSIZE - sizeof (struct fs)).
    446 	 * The size of these tables is inversely proportional to the block
    447 	 * size of the file system. The size increases if sectors per track
    448 	 * are not powers of two, because more cylinders must be described
    449 	 * by the tables before the rotational pattern repeats (fs_cpc).
    450 	 */
    451 	sblock.fs_interleave = interleave;
    452 	sblock.fs_trackskew = trackskew;
    453 	sblock.fs_npsect = nphyssectors;
    454 	sblock.fs_postblformat = FS_DYNAMICPOSTBLFMT;
    455 	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
    456 	if (sblock.fs_ntrak == 1) {
    457 		sblock.fs_cpc = 0;
    458 		goto next;
    459 	}
    460 	postblsize = sblock.fs_nrpos * sblock.fs_cpc * sizeof(int16_t);
    461 	rotblsize = sblock.fs_cpc * sblock.fs_spc / NSPB(&sblock);
    462 	totalsbsize = sizeof(struct fs) + rotblsize;
    463 	if (sblock.fs_nrpos == 8 && sblock.fs_cpc <= 16) {
    464 		/* use old static table space */
    465 		sblock.fs_postbloff = (char *)(&sblock.fs_opostbl[0][0]) -
    466 		    (char *)(&sblock.fs_firstfield);
    467 		sblock.fs_rotbloff = &sblock.fs_space[0] -
    468 		    (u_char *)(&sblock.fs_firstfield);
    469 	} else {
    470 		/* use dynamic table space */
    471 		sblock.fs_postbloff = &sblock.fs_space[0] -
    472 		    (u_char *)(&sblock.fs_firstfield);
    473 		sblock.fs_rotbloff = sblock.fs_postbloff + postblsize;
    474 		totalsbsize += postblsize;
    475 	}
    476 	if (totalsbsize > SBSIZE ||
    477 	    sblock.fs_nsect > (1 << NBBY) * NSPB(&sblock)) {
    478 		printf("%s %s %d %s %d.%s",
    479 		    "Warning: insufficient space in super block for\n",
    480 		    "rotational layout tables with nsect", sblock.fs_nsect,
    481 		    "and ntrak", sblock.fs_ntrak,
    482 		    "\nFile system performance may be impaired.\n");
    483 		sblock.fs_cpc = 0;
    484 		goto next;
    485 	}
    486 	sblock.fs_sbsize = fragroundup(&sblock, totalsbsize);
    487 	/*
    488 	 * calculate the available blocks for each rotational position
    489 	 */
    490 	for (cylno = 0; cylno < sblock.fs_cpc; cylno++)
    491 		for (rpos = 0; rpos < sblock.fs_nrpos; rpos++)
    492 			fs_postbl(&sblock, cylno)[rpos] = -1;
    493 	for (i = (rotblsize - 1) << sblock.fs_fragshift;
    494 	     i >= 0; i -= sblock.fs_frag) {
    495 		cylno = cbtocylno(&sblock, i);
    496 		rpos = cbtorpos(&sblock, i);
    497 		blk = fragstoblks(&sblock, i);
    498 		if (fs_postbl(&sblock, cylno)[rpos] == -1)
    499 			fs_rotbl(&sblock)[blk] = 0;
    500 		else
    501 			fs_rotbl(&sblock)[blk] = fs_postbl(&sblock, cylno)[rpos] - blk;
    502 		fs_postbl(&sblock, cylno)[rpos] = blk;
    503 	}
    504 next:
    505 	/*
    506 	 * Compute/validate number of cylinder groups.
    507 	 */
    508 	sblock.fs_ncg = sblock.fs_ncyl / sblock.fs_cpg;
    509 	if (sblock.fs_ncyl % sblock.fs_cpg)
    510 		sblock.fs_ncg++;
    511 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
    512 	i = MIN(~sblock.fs_cgmask, sblock.fs_ncg - 1);
    513 	if (cgdmin(&sblock, i) - cgbase(&sblock, i) >= sblock.fs_fpg) {
    514 		printf("inode blocks/cyl group (%lld) >= data blocks (%lld)\n",
    515 		    (long long)cgdmin(&sblock, i) -
    516 		    (long long)(cgbase(&sblock, i) >> sblock.fs_fragshift),
    517 		    (long long)(sblock.fs_fpg >> sblock.fs_fragshift));
    518 		printf("number of cylinders per cylinder group (%d) %s.\n",
    519 		    sblock.fs_cpg, "must be increased");
    520 		exit(29);
    521 	}
    522 	j = sblock.fs_ncg - 1;
    523 	if ((i = fssize - j * sblock.fs_fpg) < sblock.fs_fpg &&
    524 	    cgdmin(&sblock, j) - cgbase(&sblock, j) > i) {
    525 		if (j == 0) {
    526 			printf("File system must have at least %lld sectors\n",
    527 			    (long long)(NSPF(&sblock) *
    528 			    (cgdmin(&sblock, 0) + (3 << sblock.fs_fragshift))));
    529 			exit(30);
    530 		}
    531 		printf("Warning: inode blocks/cyl group (%lld) >= "
    532 			"data blocks (%d) in last\n",
    533 		    (long long)(cgdmin(&sblock, j) -
    534 		     cgbase(&sblock, j)) >> sblock.fs_fragshift,
    535 		    i >> sblock.fs_fragshift);
    536 		printf("    cylinder group. This implies %d sector(s) "
    537 			"cannot be allocated.\n",
    538 		    i * NSPF(&sblock));
    539 		sblock.fs_ncg--;
    540 		sblock.fs_ncyl -= sblock.fs_ncyl % sblock.fs_cpg;
    541 		sblock.fs_size = fssize = sblock.fs_ncyl * sblock.fs_spc /
    542 		    NSPF(&sblock);
    543 		warning = 0;
    544 	}
    545 	if (warning && !mfs) {
    546 		printf("Warning: %d sector(s) in last cylinder unallocated\n",
    547 		    sblock.fs_spc -
    548 		    (fssize * NSPF(&sblock) - (sblock.fs_ncyl - 1)
    549 		    * sblock.fs_spc));
    550 	}
    551 	/*
    552 	 * fill in remaining fields of the super block
    553 	 */
    554 	sblock.fs_csaddr = cgdmin(&sblock, 0);
    555 	sblock.fs_cssize =
    556 	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
    557 	/*
    558 	 * The superblock fields 'fs_csmask' and 'fs_csshift' are no
    559 	 * longer used. However, we still initialise them so that the
    560 	 * filesystem remains compatible with old kernels.
    561 	 */
    562 	i = sblock.fs_bsize / sizeof(struct csum);
    563 	sblock.fs_csmask = ~(i - 1);
    564 	for (sblock.fs_csshift = 0; i > 1; i >>= 1)
    565 		sblock.fs_csshift++;
    566 	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
    567 	if (fscs == NULL)
    568 		exit(39);
    569 	sblock.fs_magic = FS_MAGIC;
    570 	sblock.fs_rotdelay = rotdelay;
    571 	sblock.fs_minfree = minfree;
    572 	sblock.fs_maxcontig = maxcontig;
    573 	sblock.fs_maxbpg = maxbpg;
    574 	sblock.fs_rps = rpm / 60;
    575 	sblock.fs_optim = opt;
    576 	sblock.fs_cgrotor = 0;
    577 	sblock.fs_cstotal.cs_ndir = 0;
    578 	sblock.fs_cstotal.cs_nbfree = 0;
    579 	sblock.fs_cstotal.cs_nifree = 0;
    580 	sblock.fs_cstotal.cs_nffree = 0;
    581 	sblock.fs_fmod = 0;
    582 	sblock.fs_clean = FS_ISCLEAN;
    583 	sblock.fs_ronly = 0;
    584 	/*
    585 	 * Dump out summary information about file system.
    586 	 */
    587 	if (!mfs) {
    588 		printf("%s:\t%d sectors in %d %s of %d tracks, %d sectors\n",
    589 		    fsys, sblock.fs_size * NSPF(&sblock), sblock.fs_ncyl,
    590 		    "cylinders", sblock.fs_ntrak, sblock.fs_nsect);
    591 #define	B2MBFACTOR (1 / (1024.0 * 1024.0))
    592 		printf("\t%.1fMB in %d cyl groups (%d c/g, %.2fMB/g, %d i/g)\n",
    593 		    (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
    594 		    sblock.fs_ncg, sblock.fs_cpg,
    595 		    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
    596 		    sblock.fs_ipg);
    597 #undef B2MBFACTOR
    598 	}
    599 	/*
    600 	 * Now determine how wide each column will be, and calculate how
    601 	 * many columns will fit in a 76 char line. 76 is the width of the
    602 	 * subwindows in sysinst.
    603 	 */
    604 	printcolwidth = count_digits(
    605 			fsbtodb(&sblock, cgsblock(&sblock, sblock.fs_ncg -1)));
    606 	nprintcols = 76 / (printcolwidth + 2);
    607 	/*
    608 	 * Now build the cylinders group blocks and
    609 	 * then print out indices of cylinder groups.
    610 	 */
    611 	if (!mfs)
    612 		printf("super-block backups (for fsck -b #) at:");
    613 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
    614 		initcg(cylno, utime);
    615 		if (mfs)
    616 			continue;
    617 		if (cylno % nprintcols == 0)
    618 			printf("\n");
    619 		printf(" %*lld,", printcolwidth,
    620 			(long long)fsbtodb(&sblock, cgsblock(&sblock, cylno)));
    621 		fflush(stdout);
    622 	}
    623 	if (!mfs)
    624 		printf("\n");
    625 	if (Nflag && !mfs)
    626 		exit(0);
    627 	/*
    628 	 * Now construct the initial file system,
    629 	 * then write out the super-block.
    630 	 */
    631 	if (fsinit(utime, mfsmode, mfsuid, mfsgid) == 0 && mfs)
    632 		errx(1, "Error making filesystem");
    633 	sblock.fs_time = utime;
    634 	memcpy(writebuf, &sblock, sbsize);
    635 	if (needswap)
    636 		ffs_sb_swap(&sblock, (struct fs*)writebuf);
    637 	wtfs((int)SBOFF / sectorsize, sbsize, writebuf);
    638 	/*
    639 	 * Write out the duplicate super blocks
    640 	 */
    641 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
    642 		wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)),
    643 		    sbsize, writebuf);
    644 
    645 	/*
    646 	 * if we need to swap, create a buffer for the cylinder summaries
    647 	 * to get swapped to.
    648 	 */
    649 	if (needswap) {
    650 		if ((writebuf2 = malloc(sblock.fs_cssize)) == NULL)
    651 			exit(12);
    652 		ffs_csum_swap(fscs, (struct csum*)writebuf2, sblock.fs_cssize);
    653 	} else
    654 		writebuf2 = (char *)fscs;
    655 
    656 	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
    657 		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
    658 			sblock.fs_cssize - i < sblock.fs_bsize ?
    659 			    sblock.fs_cssize - i : sblock.fs_bsize,
    660 			((char *)writebuf2) + i);
    661 	if (writebuf2 != (char *)fscs)
    662 		free(writebuf2);
    663 
    664 	/*
    665 	 * Update information about this partion in pack
    666 	 * label, to that it may be updated on disk.
    667 	 */
    668 	if (isappleufs)
    669 		pp->p_fstype = FS_APPLEUFS;
    670 	else
    671 		pp->p_fstype = FS_BSDFFS;
    672 	pp->p_fsize = sblock.fs_fsize;
    673 	pp->p_frag = sblock.fs_frag;
    674 	pp->p_cpg = sblock.fs_cpg;
    675 }
    676 
    677 /*
    678  * Initialize a cylinder group.
    679  */
    680 void
    681 initcg(int cylno, time_t utime)
    682 {
    683 	daddr_t cbase, d, dlower, dupper, dmax, blkno;
    684 	int32_t i;
    685 	struct csum *cs;
    686 	int cn;
    687 
    688 	/*
    689 	 * Determine block bounds for cylinder group.
    690 	 * Allow space for super block summary information in first
    691 	 * cylinder group.
    692 	 */
    693 	cbase = cgbase(&sblock, cylno);
    694 	dmax = cbase + sblock.fs_fpg;
    695 	if (dmax > sblock.fs_size)
    696 		dmax = sblock.fs_size;
    697 	dlower = cgsblock(&sblock, cylno) - cbase;
    698 	dupper = cgdmin(&sblock, cylno) - cbase;
    699 	if (cylno == 0)
    700 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
    701 	cs = fscs + cylno;
    702 	memset(&acg, 0, sblock.fs_cgsize);
    703 	acg.cg_time = utime;
    704 	acg.cg_magic = CG_MAGIC;
    705 	acg.cg_cgx = cylno;
    706 	if (cylno == sblock.fs_ncg - 1)
    707 		acg.cg_ncyl = sblock.fs_ncyl % sblock.fs_cpg;
    708 	else
    709 		acg.cg_ncyl = sblock.fs_cpg;
    710 	acg.cg_niblk = sblock.fs_ipg;
    711 	acg.cg_ndblk = dmax - cbase;
    712 	if (sblock.fs_contigsumsize > 0)
    713 		acg.cg_nclusterblks = acg.cg_ndblk >> sblock.fs_fragshift;
    714 	acg.cg_btotoff = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
    715 	acg.cg_boff = acg.cg_btotoff + sblock.fs_cpg * sizeof(int32_t);
    716 	acg.cg_iusedoff = acg.cg_boff +
    717 		sblock.fs_cpg * sblock.fs_nrpos * sizeof(int16_t);
    718 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, NBBY);
    719 	if (sblock.fs_contigsumsize <= 0) {
    720 		acg.cg_nextfreeoff = acg.cg_freeoff +
    721 		   howmany(sblock.fs_fpg, NBBY);
    722 	} else {
    723 		acg.cg_clustersumoff = acg.cg_freeoff +
    724 		    howmany(sblock.fs_fpg, NBBY) - sizeof(int32_t);
    725 		if (isappleufs) {
    726 			/* Apple PR2216969 gives rationale for this change.
    727 			 * I believe they were mistaken, but we need to
    728 			 * duplicate it for compatibility.  -- dbj (at) NetBSD.org
    729 			 */
    730 			acg.cg_clustersumoff += sizeof(int32_t);
    731 		}
    732 		acg.cg_clustersumoff =
    733 		    roundup(acg.cg_clustersumoff, sizeof(int32_t));
    734 		acg.cg_clusteroff = acg.cg_clustersumoff +
    735 		    (sblock.fs_contigsumsize + 1) * sizeof(int32_t);
    736 		acg.cg_nextfreeoff = acg.cg_clusteroff +
    737 		    howmany(fragstoblks(&sblock, sblock.fs_fpg), NBBY);
    738 	}
    739 	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
    740 		printf("Panic: cylinder group too big\n");
    741 		exit(37);
    742 	}
    743 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
    744 	if (cylno == 0)
    745 		for (i = 0; i < ROOTINO; i++) {
    746 			setbit(cg_inosused(&acg, 0), i);
    747 			acg.cg_cs.cs_nifree--;
    748 		}
    749 	for (i = 0; i < sblock.fs_ipg / INOPF(&sblock); i += sblock.fs_frag)
    750 		wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
    751 		    sblock.fs_bsize, (char *)zino);
    752 	if (cylno > 0) {
    753 		/*
    754 		 * In cylno 0, beginning space is reserved
    755 		 * for boot and super blocks.
    756 		 */
    757 		for (d = 0, blkno = 0; d < dlower; ) {
    758 			setblock(&sblock, cg_blksfree(&acg, 0), blkno);
    759 			if (sblock.fs_contigsumsize > 0)
    760 				setbit(cg_clustersfree(&acg, 0), blkno);
    761 			acg.cg_cs.cs_nbfree++;
    762 			cn = cbtocylno(&sblock, d);
    763 			cg_blktot(&acg, 0)[cn]++;
    764 			cg_blks(&sblock, &acg, cn, 0)[cbtorpos(&sblock, d)]++;
    765 			d += sblock.fs_frag;
    766 			blkno++;
    767 		}
    768 		sblock.fs_dsize += dlower;
    769 	}
    770 	sblock.fs_dsize += acg.cg_ndblk - dupper;
    771 	if ((i = (dupper & (sblock.fs_frag - 1))) != 0) {
    772 		acg.cg_frsum[sblock.fs_frag - i]++;
    773 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
    774 			setbit(cg_blksfree(&acg, 0), dupper);
    775 			acg.cg_cs.cs_nffree++;
    776 		}
    777 	}
    778 	for (d = dupper, blkno = dupper >> sblock.fs_fragshift;
    779 	     d + sblock.fs_frag <= dmax - cbase; ) {
    780 		setblock(&sblock, cg_blksfree(&acg, 0), blkno);
    781 		if (sblock.fs_contigsumsize > 0)
    782 			setbit(cg_clustersfree(&acg, 0), blkno);
    783 		acg.cg_cs.cs_nbfree++;
    784 		cn = cbtocylno(&sblock, d);
    785 		cg_blktot(&acg, 0)[cn]++;
    786 		cg_blks(&sblock, &acg, cn, 0)[cbtorpos(&sblock, d)]++;
    787 		d += sblock.fs_frag;
    788 		blkno++;
    789 	}
    790 	if (d < dmax - cbase) {
    791 		acg.cg_frsum[dmax - cbase - d]++;
    792 		for (; d < dmax - cbase; d++) {
    793 			setbit(cg_blksfree(&acg, 0), d);
    794 			acg.cg_cs.cs_nffree++;
    795 		}
    796 	}
    797 	if (sblock.fs_contigsumsize > 0) {
    798 		int32_t *sump = cg_clustersum(&acg, 0);
    799 		u_char *mapp = cg_clustersfree(&acg, 0);
    800 		int map = *mapp++;
    801 		int bit = 1;
    802 		int run = 0;
    803 
    804 		for (i = 0; i < acg.cg_nclusterblks; i++) {
    805 			if ((map & bit) != 0) {
    806 				run++;
    807 			} else if (run != 0) {
    808 				if (run > sblock.fs_contigsumsize)
    809 					run = sblock.fs_contigsumsize;
    810 				sump[run]++;
    811 				run = 0;
    812 			}
    813 			if ((i & (NBBY - 1)) != (NBBY - 1)) {
    814 				bit <<= 1;
    815 			} else {
    816 				map = *mapp++;
    817 				bit = 1;
    818 			}
    819 		}
    820 		if (run != 0) {
    821 			if (run > sblock.fs_contigsumsize)
    822 				run = sblock.fs_contigsumsize;
    823 			sump[run]++;
    824 		}
    825 	}
    826 	sblock.fs_cstotal.cs_ndir += acg.cg_cs.cs_ndir;
    827 	sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
    828 	sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
    829 	sblock.fs_cstotal.cs_nifree += acg.cg_cs.cs_nifree;
    830 	*cs = acg.cg_cs;
    831 	memcpy(writebuf, &acg, sblock.fs_bsize);
    832 	if (needswap)
    833 		swap_cg(&acg, (struct cg*)writebuf);
    834 	wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
    835 		sblock.fs_bsize, writebuf);
    836 }
    837 
    838 /*
    839  * initialize the file system
    840  */
    841 struct dinode node;
    842 
    843 #ifdef LOSTDIR
    844 #define	PREDEFDIR 3
    845 #else
    846 #define	PREDEFDIR 2
    847 #endif
    848 
    849 struct direct root_dir[] = {
    850 	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
    851 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
    852 #ifdef LOSTDIR
    853 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 10, "lost+found" },
    854 #endif
    855 };
    856 struct odirect {
    857 	u_int32_t d_ino;
    858 	u_int16_t d_reclen;
    859 	u_int16_t d_namlen;
    860 	u_char	d_name[MAXNAMLEN + 1];
    861 } oroot_dir[] = {
    862 	{ ROOTINO, sizeof(struct direct), 1, "." },
    863 	{ ROOTINO, sizeof(struct direct), 2, ".." },
    864 #ifdef LOSTDIR
    865 	{ LOSTFOUNDINO, sizeof(struct direct), 10, "lost+found" },
    866 #endif
    867 };
    868 #ifdef LOSTDIR
    869 struct direct lost_found_dir[] = {
    870 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 1, "." },
    871 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
    872 	{ 0, DIRBLKSIZ, 0, 0, 0 },
    873 };
    874 struct odirect olost_found_dir[] = {
    875 	{ LOSTFOUNDINO, sizeof(struct direct), 1, "." },
    876 	{ ROOTINO, sizeof(struct direct), 2, ".." },
    877 	{ 0, DIRBLKSIZ, 0, 0 },
    878 };
    879 #endif
    880 char buf[MAXBSIZE];
    881 static void copy_dir(struct direct *, struct direct *);
    882 
    883 int
    884 fsinit(time_t utime, mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
    885 {
    886 #ifdef LOSTDIR
    887 	int i;
    888 	int dirblksiz = DIRBLKSIZ;
    889 	if (isappleufs)
    890 		dirblksiz = APPLEUFS_DIRBLKSIZ;
    891 #endif
    892 
    893 	/*
    894 	 * initialize the node
    895 	 */
    896 	memset(&node, 0, sizeof(node));
    897 	node.di_atime = utime;
    898 	node.di_mtime = utime;
    899 	node.di_ctime = utime;
    900 
    901 #ifdef LOSTDIR
    902 	/*
    903 	 * create the lost+found directory
    904 	 */
    905 	if (Oflag) {
    906 		(void)makedir((struct direct *)olost_found_dir, 2);
    907 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
    908 			copy_dir((struct direct*)&olost_found_dir[2],
    909 				(struct direct*)&buf[i]);
    910 	} else {
    911 		(void)makedir(lost_found_dir, 2);
    912 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
    913 			copy_dir(&lost_found_dir[2], (struct direct*)&buf[i]);
    914 	}
    915 	node.di_mode = IFDIR | UMASK;
    916 	node.di_nlink = 2;
    917 	node.di_size = sblock.fs_bsize;
    918 	node.di_db[0] = alloc(node.di_size, node.di_mode);
    919 	node.di_blocks = btodb(fragroundup(&sblock, node.di_size));
    920 	node.di_uid = geteuid();
    921 	node.di_gid = getegid();
    922 	wtfs(fsbtodb(&sblock, node.di_db[0]), node.di_size, buf);
    923 	iput(&node, LOSTFOUNDINO);
    924 #endif
    925 	/*
    926 	 * create the root directory
    927 	 */
    928 	if (mfs) {
    929 		node.di_mode = IFDIR | mfsmode;
    930 		node.di_uid = mfsuid;
    931 		node.di_gid = mfsgid;
    932 	} else {
    933 		node.di_mode = IFDIR | UMASK;
    934 		node.di_uid = geteuid();
    935 		node.di_gid = getegid();
    936 	}
    937 	node.di_nlink = PREDEFDIR;
    938 	if (Oflag)
    939 		node.di_size = makedir((struct direct *)oroot_dir, PREDEFDIR);
    940 	else
    941 		node.di_size = makedir(root_dir, PREDEFDIR);
    942 	node.di_db[0] = alloc(sblock.fs_fsize, node.di_mode);
    943 	if (node.di_db[0] == 0)
    944 		return (0);
    945 	node.di_blocks = btodb(fragroundup(&sblock, node.di_size));
    946 	wtfs(fsbtodb(&sblock, node.di_db[0]), sblock.fs_fsize, buf);
    947 	iput(&node, ROOTINO);
    948 	return (1);
    949 }
    950 
    951 /*
    952  * construct a set of directory entries in "buf".
    953  * return size of directory.
    954  */
    955 int
    956 makedir(struct direct *protodir, int entries)
    957 {
    958 	char *cp;
    959 	int i, spcleft;
    960 	int dirblksiz = DIRBLKSIZ;
    961 	if (isappleufs)
    962 		dirblksiz = APPLEUFS_DIRBLKSIZ;
    963 
    964 	spcleft = dirblksiz;
    965 	for (cp = buf, i = 0; i < entries - 1; i++) {
    966 		protodir[i].d_reclen = DIRSIZ(Oflag, &protodir[i], 0);
    967 		copy_dir(&protodir[i], (struct direct*)cp);
    968 		cp += protodir[i].d_reclen;
    969 		spcleft -= protodir[i].d_reclen;
    970 	}
    971 	protodir[i].d_reclen = spcleft;
    972 	copy_dir(&protodir[i], (struct direct*)cp);
    973 	return (dirblksiz);
    974 }
    975 
    976 /*
    977  * allocate a block or frag
    978  */
    979 daddr_t
    980 alloc(int size, int mode)
    981 {
    982 	int i, frag;
    983 	daddr_t d, blkno;
    984 
    985 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
    986 	/* fs -> host byte order */
    987 	if (needswap)
    988 		swap_cg(&acg, &acg);
    989 	if (acg.cg_magic != CG_MAGIC) {
    990 		printf("cg 0: bad magic number\n");
    991 		return (0);
    992 	}
    993 	if (acg.cg_cs.cs_nbfree == 0) {
    994 		printf("first cylinder group ran out of space\n");
    995 		return (0);
    996 	}
    997 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
    998 		if (isblock(&sblock, cg_blksfree(&acg, 0),
    999 		    d >> sblock.fs_fragshift))
   1000 			goto goth;
   1001 	printf("internal error: can't find block in cyl 0\n");
   1002 	return (0);
   1003 goth:
   1004 	blkno = fragstoblks(&sblock, d);
   1005 	clrblock(&sblock, cg_blksfree(&acg, 0), blkno);
   1006 	if (sblock.fs_contigsumsize > 0)
   1007 		clrbit(cg_clustersfree(&acg, 0), blkno);
   1008 	acg.cg_cs.cs_nbfree--;
   1009 	sblock.fs_cstotal.cs_nbfree--;
   1010 	fscs[0].cs_nbfree--;
   1011 	if (mode & IFDIR) {
   1012 		acg.cg_cs.cs_ndir++;
   1013 		sblock.fs_cstotal.cs_ndir++;
   1014 		fscs[0].cs_ndir++;
   1015 	}
   1016 	cg_blktot(&acg, 0)[cbtocylno(&sblock, d)]--;
   1017 	cg_blks(&sblock, &acg, cbtocylno(&sblock, d), 0)[cbtorpos(&sblock, d)]--;
   1018 	if (size != sblock.fs_bsize) {
   1019 		frag = howmany(size, sblock.fs_fsize);
   1020 		fscs[0].cs_nffree += sblock.fs_frag - frag;
   1021 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
   1022 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
   1023 		acg.cg_frsum[sblock.fs_frag - frag]++;
   1024 		for (i = frag; i < sblock.fs_frag; i++)
   1025 			setbit(cg_blksfree(&acg, 0), d + i);
   1026 	}
   1027 	/* host -> fs byte order */
   1028 	if (needswap)
   1029 		swap_cg(&acg, &acg);
   1030 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
   1031 	    (char *)&acg);
   1032 	return (d);
   1033 }
   1034 
   1035 /*
   1036  * Calculate number of inodes per group.
   1037  */
   1038 int32_t
   1039 calcipg(int32_t cylpg, int32_t bpcg, off_t *usedbp)
   1040 {
   1041 	int i;
   1042 	int32_t ipg, new_ipg, ncg, ncyl;
   1043 	off_t usedb;
   1044 
   1045 	/*
   1046 	 * Prepare to scale by fssize / (number of sectors in cylinder groups).
   1047 	 * Note that fssize is still in sectors, not file system blocks.
   1048 	 */
   1049 	ncyl = howmany(fssize, secpercyl);
   1050 	ncg = howmany(ncyl, cylpg);
   1051 	/*
   1052 	 * Iterate a few times to allow for ipg depending on itself.
   1053 	 */
   1054 	ipg = 0;
   1055 	for (i = 0; i < 10; i++) {
   1056 		usedb = (sblock.fs_iblkno + ipg / INOPF(&sblock))
   1057 			* NSPF(&sblock) * (off_t)sectorsize;
   1058 		new_ipg = (cylpg * (long long)bpcg - usedb) /
   1059 		    (long long)density * fssize / (ncg * secpercyl * cylpg);
   1060 		if (new_ipg <= 0)
   1061 			new_ipg = 1;		/* ensure ipg > 0 */
   1062 		new_ipg = roundup(new_ipg, INOPB(&sblock));
   1063 		if (new_ipg == ipg)
   1064 			break;
   1065 		ipg = new_ipg;
   1066 	}
   1067 	*usedbp = usedb;
   1068 	return (ipg);
   1069 }
   1070 
   1071 /*
   1072  * Allocate an inode on the disk
   1073  */
   1074 static void
   1075 iput(struct dinode *ip, ino_t ino)
   1076 {
   1077 	struct dinode ibuf[MAXINOPB];
   1078 	daddr_t d;
   1079 	int c, i;
   1080 
   1081 	c = ino_to_cg(&sblock, ino);
   1082 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1083 	/* fs -> host byte order */
   1084 	if (needswap)
   1085 		swap_cg(&acg, &acg);
   1086 	if (acg.cg_magic != CG_MAGIC) {
   1087 		printf("cg 0: bad magic number\n");
   1088 		exit(31);
   1089 	}
   1090 	acg.cg_cs.cs_nifree--;
   1091 	setbit(cg_inosused(&acg, 0), ino);
   1092 	/* host -> fs byte order */
   1093 	if (needswap)
   1094 		swap_cg(&acg, &acg);
   1095 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
   1096 	    (char *)&acg);
   1097 	sblock.fs_cstotal.cs_nifree--;
   1098 	fscs[0].cs_nifree--;
   1099 	if (ino >= sblock.fs_ipg * sblock.fs_ncg) {
   1100 		printf("fsinit: inode value out of range (%d).\n", ino);
   1101 		exit(32);
   1102 	}
   1103 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
   1104 	rdfs(d, sblock.fs_bsize, ibuf);
   1105 	if (needswap) {
   1106 		ffs_dinode_swap(ip, &ibuf[ino_to_fsbo(&sblock, ino)]);
   1107 		/* ffs_dinode_swap() doesn't swap blocks addrs */
   1108 		for (i=0; i<NDADDR + NIADDR; i++)
   1109 			(&ibuf[ino_to_fsbo(&sblock, ino)])->di_db[i] =
   1110 				bswap32(ip->di_db[i]);
   1111 	} else
   1112 		ibuf[ino_to_fsbo(&sblock, ino)] = *ip;
   1113 	wtfs(d, sblock.fs_bsize, ibuf);
   1114 }
   1115 
   1116 /*
   1117  * read a block from the file system
   1118  */
   1119 void
   1120 rdfs(daddr_t bno, int size, void *bf)
   1121 {
   1122 	int n;
   1123 	off_t offset;
   1124 
   1125 #ifdef MFS
   1126 	if (mfs) {
   1127 		memmove(bf, membase + bno * sectorsize, size);
   1128 		return;
   1129 	}
   1130 #endif
   1131 	offset = bno;
   1132 	offset *= sectorsize;
   1133 	if (lseek(fsi, offset, SEEK_SET) < 0) {
   1134 		printf("rdfs: seek error for sector %lld: %s\n",
   1135 		    (long long)bno, strerror(errno));
   1136 		exit(33);
   1137 	}
   1138 	n = read(fsi, bf, size);
   1139 	if (n != size) {
   1140 		printf("rdfs: read error for sector %lld: %s\n",
   1141 		    (long long)bno, strerror(errno));
   1142 		exit(34);
   1143 	}
   1144 }
   1145 
   1146 /*
   1147  * write a block to the file system
   1148  */
   1149 void
   1150 wtfs(daddr_t bno, int size, void *bf)
   1151 {
   1152 	int n;
   1153 	off_t offset;
   1154 
   1155 #ifdef MFS
   1156 	if (mfs) {
   1157 		memmove(membase + bno * sectorsize, bf, size);
   1158 		return;
   1159 	}
   1160 #endif
   1161 	if (Nflag)
   1162 		return;
   1163 	offset = bno;
   1164 	offset *= sectorsize;
   1165 	if (lseek(fso, offset, SEEK_SET) < 0) {
   1166 		printf("wtfs: seek error for sector %lld: %s\n",
   1167 		    (long long)bno, strerror(errno));
   1168 		exit(35);
   1169 	}
   1170 	n = write(fso, bf, size);
   1171 	if (n != size) {
   1172 		printf("wtfs: write error for sector %lld: %s\n",
   1173 		    (long long)bno, strerror(errno));
   1174 		exit(36);
   1175 	}
   1176 }
   1177 
   1178 /*
   1179  * check if a block is available
   1180  */
   1181 int
   1182 isblock(struct fs *fs, unsigned char *cp, int h)
   1183 {
   1184 	unsigned char mask;
   1185 
   1186 	switch (fs->fs_fragshift) {
   1187 	case 3:
   1188 		return (cp[h] == 0xff);
   1189 	case 2:
   1190 		mask = 0x0f << ((h & 0x1) << 2);
   1191 		return ((cp[h >> 1] & mask) == mask);
   1192 	case 1:
   1193 		mask = 0x03 << ((h & 0x3) << 1);
   1194 		return ((cp[h >> 2] & mask) == mask);
   1195 	case 0:
   1196 		mask = 0x01 << (h & 0x7);
   1197 		return ((cp[h >> 3] & mask) == mask);
   1198 	default:
   1199 #ifdef STANDALONE
   1200 		printf("isblock bad fs_fragshift %d\n", fs->fs_fragshift);
   1201 #else
   1202 		fprintf(stderr, "isblock bad fs_fragshift %d\n",
   1203 		    fs->fs_fragshift);
   1204 #endif
   1205 		return (0);
   1206 	}
   1207 }
   1208 
   1209 /*
   1210  * take a block out of the map
   1211  */
   1212 void
   1213 clrblock(struct fs *fs, unsigned char *cp, int h)
   1214 {
   1215 	switch ((fs)->fs_fragshift) {
   1216 	case 3:
   1217 		cp[h] = 0;
   1218 		return;
   1219 	case 2:
   1220 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
   1221 		return;
   1222 	case 1:
   1223 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
   1224 		return;
   1225 	case 0:
   1226 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
   1227 		return;
   1228 	default:
   1229 #ifdef STANDALONE
   1230 		printf("clrblock bad fs_fragshift %d\n", fs->fs_fragshift);
   1231 #else
   1232 		fprintf(stderr, "clrblock bad fs_fragshift %d\n",
   1233 		    fs->fs_fragshift);
   1234 #endif
   1235 		return;
   1236 	}
   1237 }
   1238 
   1239 /*
   1240  * put a block into the map
   1241  */
   1242 void
   1243 setblock(struct fs *fs, unsigned char *cp, int h)
   1244 {
   1245 	switch (fs->fs_fragshift) {
   1246 	case 3:
   1247 		cp[h] = 0xff;
   1248 		return;
   1249 	case 2:
   1250 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
   1251 		return;
   1252 	case 1:
   1253 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
   1254 		return;
   1255 	case 0:
   1256 		cp[h >> 3] |= (0x01 << (h & 0x7));
   1257 		return;
   1258 	default:
   1259 #ifdef STANDALONE
   1260 		printf("setblock bad fs_frag %d\n", fs->fs_fragshift);
   1261 #else
   1262 		fprintf(stderr, "setblock bad fs_fragshift %d\n",
   1263 		    fs->fs_fragshift);
   1264 #endif
   1265 		return;
   1266 	}
   1267 }
   1268 
   1269 /* swap byte order of cylinder group */
   1270 static void
   1271 swap_cg(struct cg *o, struct cg *n)
   1272 {
   1273 	int i, btotsize, fbsize;
   1274 	u_int32_t *n32, *o32;
   1275 	u_int16_t *n16, *o16;
   1276 
   1277 	n->cg_firstfield = bswap32(o->cg_firstfield);
   1278 	n->cg_magic = bswap32(o->cg_magic);
   1279 	n->cg_time = bswap32(o->cg_time);
   1280 	n->cg_cgx = bswap32(o->cg_cgx);
   1281 	n->cg_ncyl = bswap16(o->cg_ncyl);
   1282 	n->cg_niblk = bswap16(o->cg_niblk);
   1283 	n->cg_ndblk = bswap32(o->cg_ndblk);
   1284 	n->cg_cs.cs_ndir = bswap32(o->cg_cs.cs_ndir);
   1285 	n->cg_cs.cs_nbfree = bswap32(o->cg_cs.cs_nbfree);
   1286 	n->cg_cs.cs_nifree = bswap32(o->cg_cs.cs_nifree);
   1287 	n->cg_cs.cs_nffree = bswap32(o->cg_cs.cs_nffree);
   1288 	n->cg_rotor = bswap32(o->cg_rotor);
   1289 	n->cg_frotor = bswap32(o->cg_frotor);
   1290 	n->cg_irotor = bswap32(o->cg_irotor);
   1291 	n->cg_btotoff = bswap32(o->cg_btotoff);
   1292 	n->cg_boff = bswap32(o->cg_boff);
   1293 	n->cg_iusedoff = bswap32(o->cg_iusedoff);
   1294 	n->cg_freeoff = bswap32(o->cg_freeoff);
   1295 	n->cg_nextfreeoff = bswap32(o->cg_nextfreeoff);
   1296 	n->cg_clustersumoff = bswap32(o->cg_clustersumoff);
   1297 	n->cg_clusteroff = bswap32(o->cg_clusteroff);
   1298 	n->cg_nclusterblks = bswap32(o->cg_nclusterblks);
   1299 	for (i=0; i < MAXFRAG; i++)
   1300 		n->cg_frsum[i] = bswap32(o->cg_frsum[i]);
   1301 
   1302 	/* alays new format */
   1303 	if (n->cg_magic == CG_MAGIC) {
   1304 		btotsize = n->cg_boff - n->cg_btotoff;
   1305 		fbsize = n->cg_iusedoff - n->cg_boff;
   1306 		n32 = (u_int32_t*)((u_int8_t*)n + n->cg_btotoff);
   1307 		o32 = (u_int32_t*)((u_int8_t*)o + n->cg_btotoff);
   1308 		n16 = (u_int16_t*)((u_int8_t*)n + n->cg_boff);
   1309 		o16 = (u_int16_t*)((u_int8_t*)o + n->cg_boff);
   1310 	} else {
   1311 		btotsize = bswap32(n->cg_boff) - bswap32(n->cg_btotoff);
   1312 		fbsize = bswap32(n->cg_iusedoff) - bswap32(n->cg_boff);
   1313 		n32 = (u_int32_t*)((u_int8_t*)n + bswap32(n->cg_btotoff));
   1314 		o32 = (u_int32_t*)((u_int8_t*)o + bswap32(n->cg_btotoff));
   1315 		n16 = (u_int16_t*)((u_int8_t*)n + bswap32(n->cg_boff));
   1316 		o16 = (u_int16_t*)((u_int8_t*)o + bswap32(n->cg_boff));
   1317 	}
   1318 	for (i=0; i < btotsize / sizeof(u_int32_t); i++)
   1319 		n32[i] = bswap32(o32[i]);
   1320 
   1321 	for (i=0; i < fbsize/sizeof(u_int16_t); i++)
   1322 		n16[i] = bswap16(o16[i]);
   1323 
   1324 	if (n->cg_magic == CG_MAGIC) {
   1325 		n32 = (u_int32_t*)((u_int8_t*)n + n->cg_clustersumoff);
   1326 		o32 = (u_int32_t*)((u_int8_t*)o + n->cg_clustersumoff);
   1327 	} else {
   1328 		n32 = (u_int32_t*)((u_int8_t*)n + bswap32(n->cg_clustersumoff));
   1329 		o32 = (u_int32_t*)((u_int8_t*)o + bswap32(n->cg_clustersumoff));
   1330 	}
   1331 	for (i = 1; i < sblock.fs_contigsumsize + 1; i++)
   1332 		n32[i] = bswap32(o32[i]);
   1333 }
   1334 
   1335 /* copy a direntry to a buffer, in fs byte order */
   1336 static void
   1337 copy_dir(struct direct *dir, struct direct *dbuf)
   1338 {
   1339 	memcpy(dbuf, dir, DIRSIZ(Oflag, dir, 0));
   1340 	if (needswap) {
   1341 		dbuf->d_ino = bswap32(dir->d_ino);
   1342 		dbuf->d_reclen = bswap16(dir->d_reclen);
   1343 		if (Oflag)
   1344 			((struct odirect*)dbuf)->d_namlen =
   1345 				bswap16(((struct odirect*)dir)->d_namlen);
   1346 	}
   1347 }
   1348 
   1349 /* Determine how many digits are needed to print a given integer */
   1350 static int
   1351 count_digits(int num)
   1352 {
   1353 	int ndig;
   1354 
   1355 	for(ndig = 1; num > 9; num /=10, ndig++);
   1356 
   1357 	return (ndig);
   1358 }
   1359 
   1360 #ifdef MFS
   1361 /*
   1362  * XXX!
   1363  * Attempt to guess how much more space is available for process data.  The
   1364  * heuristic we use is
   1365  *
   1366  *	max_data_limit - (sbrk(0) - etext) - 128kB
   1367  *
   1368  * etext approximates that start address of the data segment, and the 128kB
   1369  * allows some slop for both segment gap between text and data, and for other
   1370  * (libc) malloc usage.
   1371  */
   1372 static void
   1373 calc_memfree(void)
   1374 {
   1375 	extern char etext;
   1376 	struct rlimit rlp;
   1377 	u_long base;
   1378 
   1379 	base = (u_long)sbrk(0) - (u_long)&etext;
   1380 	if (getrlimit(RLIMIT_DATA, &rlp) < 0)
   1381 		perror("getrlimit");
   1382 	rlp.rlim_cur = rlp.rlim_max;
   1383 	if (setrlimit(RLIMIT_DATA, &rlp) < 0)
   1384 		perror("setrlimit");
   1385 	memleft = rlp.rlim_max - base - (128 * 1024);
   1386 }
   1387 
   1388 /*
   1389  * Internal version of malloc that trims the requested size if not enough
   1390  * memory is available.
   1391  */
   1392 static void *
   1393 mkfs_malloc(size_t size)
   1394 {
   1395 	u_long pgsz;
   1396 
   1397 	if (size == 0)
   1398 		return (NULL);
   1399 	if (memleft == 0)
   1400 		calc_memfree();
   1401 
   1402 	pgsz = getpagesize() - 1;
   1403 	size = (size + pgsz) &~ pgsz;
   1404 	if (size > memleft)
   1405 		size = memleft;
   1406 	memleft -= size;
   1407 	return (mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
   1408 	    -1, 0));
   1409 }
   1410 #endif	/* MFS */
   1411