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