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