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