Home | History | Annotate | Line # | Download | only in newfs
mkfs.c revision 1.36
      1 /*	$NetBSD: mkfs.c,v 1.36 1999/05/14 22:36:50 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.36 1999/05/14 22:36:50 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 an 80 char line.
    605 	 */
    606 	printcolwidth = count_digits(
    607 			fsbtodb(&sblock, cgsblock(&sblock, sblock.fs_ncg -1)));
    608 	nprintcols = 80 / (printcolwidth + 2);
    609 	/*
    610 	 * Now build the cylinders group blocks and
    611 	 * then print out indices of cylinder groups.
    612 	 */
    613 	if (!mfs)
    614 		printf("super-block backups (for fsck -b #) at:");
    615 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
    616 		initcg(cylno, utime);
    617 		if (mfs)
    618 			continue;
    619 		if (cylno % nprintcols == 0)
    620 			printf("\n");
    621 		printf(" %*d,", printcolwidth,
    622 				fsbtodb(&sblock, cgsblock(&sblock, cylno)));
    623 		fflush(stdout);
    624 	}
    625 	if (!mfs)
    626 		printf("\n");
    627 	if (Nflag && !mfs)
    628 		exit(0);
    629 	/*
    630 	 * Now construct the initial file system,
    631 	 * then write out the super-block.
    632 	 */
    633 	fsinit(utime);
    634 	sblock.fs_time = utime;
    635 	memcpy(writebuf, &sblock, sbsize);
    636 	if (needswap)
    637 		ffs_sb_swap(&sblock, (struct fs*)writebuf, 1);
    638 	wtfs((int)SBOFF / sectorsize, sbsize, writebuf);
    639 	/*
    640 	 * Write out the duplicate super blocks
    641 	 */
    642 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
    643 		wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)),
    644 		    sbsize, writebuf);
    645 
    646 	/*
    647 	 * if we need to swap, create a buffer for the cylinder summaries
    648 	 * to get swapped to.
    649 	 */
    650 	if (needswap) {
    651 		if ((writebuf2=malloc(sblock.fs_cssize)) == NULL)
    652 			exit(12);
    653 		ffs_csum_swap(fscs, (struct csum*)writebuf2, sblock.fs_cssize);
    654 	} else
    655 		writebuf2 = (char *)fscs;
    656 
    657 	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
    658 		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
    659 			sblock.fs_cssize - i < sblock.fs_bsize ?
    660 			    sblock.fs_cssize - i : sblock.fs_bsize,
    661 			((char *)writebuf2) + i);
    662 	if (writebuf2 != (char *)fscs)
    663 		free(writebuf2);
    664 
    665 	/*
    666 	 * Update information about this partion in pack
    667 	 * label, to that it may be updated on disk.
    668 	 */
    669 	pp->p_fstype = FS_BSDFFS;
    670 	pp->p_fsize = sblock.fs_fsize;
    671 	pp->p_frag = sblock.fs_frag;
    672 	pp->p_cpg = sblock.fs_cpg;
    673 }
    674 
    675 /*
    676  * Initialize a cylinder group.
    677  */
    678 void
    679 initcg(cylno, utime)
    680 	int cylno;
    681 	time_t utime;
    682 {
    683 	daddr_t cbase, d, dlower, dupper, dmax, blkno;
    684 	int32_t i;
    685 	struct csum *cs;
    686 
    687 	/*
    688 	 * Determine block bounds for cylinder group.
    689 	 * Allow space for super block summary information in first
    690 	 * cylinder group.
    691 	 */
    692 	cbase = cgbase(&sblock, cylno);
    693 	dmax = cbase + sblock.fs_fpg;
    694 	if (dmax > sblock.fs_size)
    695 		dmax = sblock.fs_size;
    696 	dlower = cgsblock(&sblock, cylno) - cbase;
    697 	dupper = cgdmin(&sblock, cylno) - cbase;
    698 	if (cylno == 0)
    699 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
    700 	cs = fscs + cylno;
    701 	memset(&acg, 0, sblock.fs_cgsize);
    702 	acg.cg_time = utime;
    703 	acg.cg_magic = CG_MAGIC;
    704 	acg.cg_cgx = cylno;
    705 	if (cylno == sblock.fs_ncg - 1)
    706 		acg.cg_ncyl = sblock.fs_ncyl % sblock.fs_cpg;
    707 	else
    708 		acg.cg_ncyl = sblock.fs_cpg;
    709 	acg.cg_niblk = sblock.fs_ipg;
    710 	acg.cg_ndblk = dmax - cbase;
    711 	if (sblock.fs_contigsumsize > 0)
    712 		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
    713 	acg.cg_btotoff = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
    714 	acg.cg_boff = acg.cg_btotoff + sblock.fs_cpg * sizeof(int32_t);
    715 	acg.cg_iusedoff = acg.cg_boff +
    716 		sblock.fs_cpg * sblock.fs_nrpos * sizeof(int16_t);
    717 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, NBBY);
    718 	if (sblock.fs_contigsumsize <= 0) {
    719 		acg.cg_nextfreeoff = acg.cg_freeoff +
    720 		   howmany(sblock.fs_cpg * sblock.fs_spc / NSPF(&sblock), NBBY);
    721 	} else {
    722 		acg.cg_clustersumoff = acg.cg_freeoff + howmany
    723 		    (sblock.fs_cpg * sblock.fs_spc / NSPF(&sblock), NBBY) -
    724 		    sizeof(int32_t);
    725 		acg.cg_clustersumoff =
    726 		    roundup(acg.cg_clustersumoff, sizeof(int32_t));
    727 		acg.cg_clusteroff = acg.cg_clustersumoff +
    728 		    (sblock.fs_contigsumsize + 1) * sizeof(int32_t);
    729 		acg.cg_nextfreeoff = acg.cg_clusteroff + howmany
    730 		    (sblock.fs_cpg * sblock.fs_spc / NSPB(&sblock), NBBY);
    731 	}
    732 	if (acg.cg_nextfreeoff -
    733 	    (int32_t)(&acg.cg_firstfield) > sblock.fs_cgsize) {
    734 		printf("Panic: cylinder group too big\n");
    735 		exit(37);
    736 	}
    737 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
    738 	if (cylno == 0)
    739 		for (i = 0; i < ROOTINO; i++) {
    740 			setbit(cg_inosused(&acg, 0), i);
    741 			acg.cg_cs.cs_nifree--;
    742 		}
    743 	for (i = 0; i < sblock.fs_ipg / INOPF(&sblock); i += sblock.fs_frag)
    744 		wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
    745 		    sblock.fs_bsize, (char *)zino);
    746 	if (cylno > 0) {
    747 		/*
    748 		 * In cylno 0, beginning space is reserved
    749 		 * for boot and super blocks.
    750 		 */
    751 		for (d = 0; d < dlower; d += sblock.fs_frag) {
    752 			blkno = d / sblock.fs_frag;
    753 			setblock(&sblock, cg_blksfree(&acg, 0), blkno);
    754 			if (sblock.fs_contigsumsize > 0)
    755 				setbit(cg_clustersfree(&acg, 0), blkno);
    756 			acg.cg_cs.cs_nbfree++;
    757 			cg_blktot(&acg, 0)[cbtocylno(&sblock, d)]++;
    758 			cg_blks(&sblock, &acg, cbtocylno(&sblock, d), 0)
    759 			    [cbtorpos(&sblock, d)]++;
    760 		}
    761 		sblock.fs_dsize += dlower;
    762 	}
    763 	sblock.fs_dsize += acg.cg_ndblk - dupper;
    764 	if ((i = (dupper % sblock.fs_frag)) != 0) {
    765 		acg.cg_frsum[sblock.fs_frag - i]++;
    766 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
    767 			setbit(cg_blksfree(&acg, 0), dupper);
    768 			acg.cg_cs.cs_nffree++;
    769 		}
    770 	}
    771 	for (d = dupper; d + sblock.fs_frag <= dmax - cbase; ) {
    772 		blkno = d / sblock.fs_frag;
    773 		setblock(&sblock, cg_blksfree(&acg, 0), blkno);
    774 		if (sblock.fs_contigsumsize > 0)
    775 			setbit(cg_clustersfree(&acg, 0), blkno);
    776 		acg.cg_cs.cs_nbfree++;
    777 		cg_blktot(&acg, 0)[cbtocylno(&sblock, d)]++;
    778 		cg_blks(&sblock, &acg, cbtocylno(&sblock, d), 0)
    779 		    [cbtorpos(&sblock, d)]++;
    780 		d += sblock.fs_frag;
    781 	}
    782 	if (d < dmax - cbase) {
    783 		acg.cg_frsum[dmax - cbase - d]++;
    784 		for (; d < dmax - cbase; d++) {
    785 			setbit(cg_blksfree(&acg, 0), d);
    786 			acg.cg_cs.cs_nffree++;
    787 		}
    788 	}
    789 	if (sblock.fs_contigsumsize > 0) {
    790 		int32_t *sump = cg_clustersum(&acg, 0);
    791 		u_char *mapp = cg_clustersfree(&acg, 0);
    792 		int map = *mapp++;
    793 		int bit = 1;
    794 		int run = 0;
    795 
    796 		for (i = 0; i < acg.cg_nclusterblks; i++) {
    797 			if ((map & bit) != 0) {
    798 				run++;
    799 			} else if (run != 0) {
    800 				if (run > sblock.fs_contigsumsize)
    801 					run = sblock.fs_contigsumsize;
    802 				sump[run]++;
    803 				run = 0;
    804 			}
    805 			if ((i & (NBBY - 1)) != (NBBY - 1)) {
    806 				bit <<= 1;
    807 			} else {
    808 				map = *mapp++;
    809 				bit = 1;
    810 			}
    811 		}
    812 		if (run != 0) {
    813 			if (run > sblock.fs_contigsumsize)
    814 				run = sblock.fs_contigsumsize;
    815 			sump[run]++;
    816 		}
    817 	}
    818 	sblock.fs_cstotal.cs_ndir += acg.cg_cs.cs_ndir;
    819 	sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
    820 	sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
    821 	sblock.fs_cstotal.cs_nifree += acg.cg_cs.cs_nifree;
    822 	*cs = acg.cg_cs;
    823 	memcpy(writebuf, &acg, sblock.fs_bsize);
    824 	if (needswap)
    825 		swap_cg(&acg, (struct cg*)writebuf);
    826 	wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
    827 		sblock.fs_bsize, writebuf);
    828 }
    829 
    830 /*
    831  * initialize the file system
    832  */
    833 struct dinode node;
    834 
    835 #ifdef LOSTDIR
    836 #define PREDEFDIR 3
    837 #else
    838 #define PREDEFDIR 2
    839 #endif
    840 
    841 struct direct root_dir[] = {
    842 	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
    843 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
    844 #ifdef LOSTDIR
    845 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 10, "lost+found" },
    846 #endif
    847 };
    848 struct odirect {
    849 	u_int32_t d_ino;
    850 	u_int16_t d_reclen;
    851 	u_int16_t d_namlen;
    852 	u_char	d_name[MAXNAMLEN + 1];
    853 } oroot_dir[] = {
    854 	{ ROOTINO, sizeof(struct direct), 1, "." },
    855 	{ ROOTINO, sizeof(struct direct), 2, ".." },
    856 #ifdef LOSTDIR
    857 	{ LOSTFOUNDINO, sizeof(struct direct), 10, "lost+found" },
    858 #endif
    859 };
    860 #ifdef LOSTDIR
    861 struct direct lost_found_dir[] = {
    862 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 1, "." },
    863 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
    864 	{ 0, DIRBLKSIZ, 0, 0, 0 },
    865 };
    866 struct odirect olost_found_dir[] = {
    867 	{ LOSTFOUNDINO, sizeof(struct direct), 1, "." },
    868 	{ ROOTINO, sizeof(struct direct), 2, ".." },
    869 	{ 0, DIRBLKSIZ, 0, 0 },
    870 };
    871 #endif
    872 char buf[MAXBSIZE];
    873 static void copy_dir __P((struct direct *, struct direct *));
    874 
    875 void
    876 fsinit(utime)
    877 	time_t utime;
    878 {
    879 #ifdef LOSTDIR
    880 	int i;
    881 #endif
    882 
    883 	/*
    884 	 * initialize the node
    885 	 */
    886 	memset(&node, 0, sizeof(node));
    887 	node.di_atime = utime;
    888 	node.di_mtime = utime;
    889 	node.di_ctime = utime;
    890 
    891 #ifdef LOSTDIR
    892 	/*
    893 	 * create the lost+found directory
    894 	 */
    895 	if (Oflag) {
    896 		(void)makedir((struct direct *)olost_found_dir, 2);
    897 		for (i = DIRBLKSIZ; i < sblock.fs_bsize; i += DIRBLKSIZ)
    898 			copy_dir((struct direct*)&olost_found_dir[2],
    899 				(struct direct*)&buf[i]);
    900 	} else {
    901 		(void)makedir(lost_found_dir, 2);
    902 		for (i = DIRBLKSIZ; i < sblock.fs_bsize; i += DIRBLKSIZ)
    903 			copy_dir(&lost_found_dir[2], (struct direct*)&buf[i]);
    904 	}
    905 	node.di_mode = IFDIR | UMASK;
    906 	node.di_nlink = 2;
    907 	node.di_size = sblock.fs_bsize;
    908 	node.di_db[0] = alloc(node.di_size, node.di_mode);
    909 	node.di_blocks = btodb(fragroundup(&sblock, node.di_size));
    910 	node.di_uid = geteuid();
    911 	node.di_gid = getegid();
    912 	wtfs(fsbtodb(&sblock, node.di_db[0]), node.di_size, buf);
    913 	iput(&node, LOSTFOUNDINO);
    914 #endif
    915 	/*
    916 	 * create the root directory
    917 	 */
    918 	if (mfs)
    919 		node.di_mode = IFDIR | 01777;
    920 	else
    921 		node.di_mode = IFDIR | UMASK;
    922 	node.di_nlink = PREDEFDIR;
    923 	if (Oflag)
    924 		node.di_size = makedir((struct direct *)oroot_dir, PREDEFDIR);
    925 	else
    926 		node.di_size = makedir(root_dir, PREDEFDIR);
    927 	node.di_db[0] = alloc(sblock.fs_fsize, node.di_mode);
    928 	node.di_blocks = btodb(fragroundup(&sblock, node.di_size));
    929 	node.di_uid = geteuid();
    930 	node.di_gid = getegid();
    931 	wtfs(fsbtodb(&sblock, node.di_db[0]), sblock.fs_fsize, buf);
    932 	iput(&node, ROOTINO);
    933 }
    934 
    935 /*
    936  * construct a set of directory entries in "buf".
    937  * return size of directory.
    938  */
    939 int
    940 makedir(protodir, entries)
    941 	struct direct *protodir;
    942 	int entries;
    943 {
    944 	char *cp;
    945 	int i, spcleft;
    946 
    947 	spcleft = DIRBLKSIZ;
    948 	for (cp = buf, i = 0; i < entries - 1; i++) {
    949 		protodir[i].d_reclen = DIRSIZ(Oflag, &protodir[i], 0);
    950 		copy_dir(&protodir[i], (struct direct*)cp);
    951 		cp += protodir[i].d_reclen;
    952 		spcleft -= protodir[i].d_reclen;
    953 	}
    954 	protodir[i].d_reclen = spcleft;
    955 	copy_dir(&protodir[i], (struct direct*)cp);
    956 	return (DIRBLKSIZ);
    957 }
    958 
    959 /*
    960  * allocate a block or frag
    961  */
    962 daddr_t
    963 alloc(size, mode)
    964 	int size;
    965 	int mode;
    966 {
    967 	int i, frag;
    968 	daddr_t d, blkno;
    969 
    970 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
    971 	/* fs -> host byte order */
    972 	if (needswap)
    973 		swap_cg(&acg, &acg);
    974 	if (acg.cg_magic != CG_MAGIC) {
    975 		printf("cg 0: bad magic number\n");
    976 		return (0);
    977 	}
    978 	if (acg.cg_cs.cs_nbfree == 0) {
    979 		printf("first cylinder group ran out of space\n");
    980 		return (0);
    981 	}
    982 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
    983 		if (isblock(&sblock, cg_blksfree(&acg, 0), d / sblock.fs_frag))
    984 			goto goth;
    985 	printf("internal error: can't find block in cyl 0\n");
    986 	return (0);
    987 goth:
    988 	blkno = fragstoblks(&sblock, d);
    989 	clrblock(&sblock, cg_blksfree(&acg, 0), blkno);
    990 	if (sblock.fs_contigsumsize > 0)
    991 		clrbit(cg_clustersfree(&acg, 0), blkno);
    992 	acg.cg_cs.cs_nbfree--;
    993 	sblock.fs_cstotal.cs_nbfree--;
    994 	fscs[0].cs_nbfree--;
    995 	if (mode & IFDIR) {
    996 		acg.cg_cs.cs_ndir++;
    997 		sblock.fs_cstotal.cs_ndir++;
    998 		fscs[0].cs_ndir++;
    999 	}
   1000 	cg_blktot(&acg, 0)[cbtocylno(&sblock, d)]--;
   1001 	cg_blks(&sblock, &acg, cbtocylno(&sblock, d), 0)[cbtorpos(&sblock, d)]--;
   1002 	if (size != sblock.fs_bsize) {
   1003 		frag = howmany(size, sblock.fs_fsize);
   1004 		fscs[0].cs_nffree += sblock.fs_frag - frag;
   1005 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
   1006 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
   1007 		acg.cg_frsum[sblock.fs_frag - frag]++;
   1008 		for (i = frag; i < sblock.fs_frag; i++)
   1009 			setbit(cg_blksfree(&acg, 0), d + i);
   1010 	}
   1011 	/* host -> fs byte order */
   1012 	if (needswap)
   1013 		swap_cg(&acg, &acg);
   1014 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
   1015 	    (char *)&acg);
   1016 	return (d);
   1017 }
   1018 
   1019 /*
   1020  * Calculate number of inodes per group.
   1021  */
   1022 int32_t
   1023 calcipg(cpg, bpcg, usedbp)
   1024 	int32_t cpg;
   1025 	int32_t bpcg;
   1026 	off_t *usedbp;
   1027 {
   1028 	int i;
   1029 	int32_t ipg, new_ipg, ncg, ncyl;
   1030 	off_t usedb;
   1031 #if __GNUC__ /* XXX work around gcc 2.7.2 initialization bug */
   1032 	(void)&usedb;
   1033 #endif
   1034 
   1035 	/*
   1036 	 * Prepare to scale by fssize / (number of sectors in cylinder groups).
   1037 	 * Note that fssize is still in sectors, not filesystem blocks.
   1038 	 */
   1039 	ncyl = howmany(fssize, secpercyl);
   1040 	ncg = howmany(ncyl, cpg);
   1041 	/*
   1042 	 * Iterate a few times to allow for ipg depending on itself.
   1043 	 */
   1044 	ipg = 0;
   1045 	for (i = 0; i < 10; i++) {
   1046 		usedb = (sblock.fs_iblkno + ipg / INOPF(&sblock))
   1047 			* NSPF(&sblock) * (off_t)sectorsize;
   1048 		new_ipg = (cpg * (quad_t)bpcg - usedb) / density * fssize
   1049 			  / ncg / secpercyl / cpg;
   1050 		new_ipg = roundup(new_ipg, INOPB(&sblock));
   1051 		if (new_ipg == ipg)
   1052 			break;
   1053 		ipg = new_ipg;
   1054 	}
   1055 	*usedbp = usedb;
   1056 	return (ipg);
   1057 }
   1058 
   1059 /*
   1060  * Allocate an inode on the disk
   1061  */
   1062 static void
   1063 iput(ip, ino)
   1064 	struct dinode *ip;
   1065 	ino_t ino;
   1066 {
   1067 	struct dinode buf[MAXINOPB];
   1068 	daddr_t d;
   1069 	int c, i;
   1070 
   1071 	c = ino_to_cg(&sblock, ino);
   1072 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
   1073 	/* fs -> host byte order */
   1074 	if (needswap)
   1075 		swap_cg(&acg, &acg);
   1076 	if (acg.cg_magic != CG_MAGIC) {
   1077 		printf("cg 0: bad magic number\n");
   1078 		exit(31);
   1079 	}
   1080 	acg.cg_cs.cs_nifree--;
   1081 	setbit(cg_inosused(&acg, 0), ino);
   1082 	/* host -> fs byte order */
   1083 	if (needswap)
   1084 		swap_cg(&acg, &acg);
   1085 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
   1086 	    (char *)&acg);
   1087 	sblock.fs_cstotal.cs_nifree--;
   1088 	fscs[0].cs_nifree--;
   1089 	if (ino >= sblock.fs_ipg * sblock.fs_ncg) {
   1090 		printf("fsinit: inode value out of range (%d).\n", ino);
   1091 		exit(32);
   1092 	}
   1093 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
   1094 	rdfs(d, sblock.fs_bsize, buf);
   1095 	if (needswap) {
   1096 		ffs_dinode_swap(ip, &buf[ino_to_fsbo(&sblock, ino)]);
   1097 		/* ffs_dinode_swap() doesn't swap blocks addrs */
   1098 		for (i=0; i<NDADDR + NIADDR; i++)
   1099 			(&buf[ino_to_fsbo(&sblock, ino)])->di_db[i] =
   1100 				bswap32(ip->di_db[i]);
   1101 	} else
   1102 		buf[ino_to_fsbo(&sblock, ino)] = *ip;
   1103 	wtfs(d, sblock.fs_bsize, buf);
   1104 }
   1105 
   1106 /*
   1107  * Replace libc function with one suited to our needs.
   1108  */
   1109 void *
   1110 malloc(size)
   1111 	size_t size;
   1112 {
   1113 	char *base, *i;
   1114 	static u_long pgsz;
   1115 	struct rlimit rlp;
   1116 
   1117 	if (pgsz == 0) {
   1118 		base = sbrk(0);
   1119 		pgsz = getpagesize() - 1;
   1120 		i = (char *)((u_long)(base + pgsz) &~ pgsz);
   1121 		base = sbrk(i - base);
   1122 		if (getrlimit(RLIMIT_DATA, &rlp) < 0)
   1123 			perror("getrlimit");
   1124 		rlp.rlim_cur = rlp.rlim_max;
   1125 		if (setrlimit(RLIMIT_DATA, &rlp) < 0)
   1126 			perror("setrlimit");
   1127 		memleft = rlp.rlim_max - (u_long)base;
   1128 	}
   1129 	size = (size + pgsz) &~ pgsz;
   1130 	if (size > memleft)
   1131 		size = memleft;
   1132 	memleft -= size;
   1133 	if (size == 0)
   1134 		return (0);
   1135 	return ((caddr_t)sbrk(size));
   1136 }
   1137 
   1138 /*
   1139  * Replace libc function with one suited to our needs.
   1140  */
   1141 void *
   1142 realloc(ptr, size)
   1143 	void *ptr;
   1144 	size_t size;
   1145 {
   1146 	void *p;
   1147 
   1148 	if ((p = malloc(size)) == NULL)
   1149 		return (NULL);
   1150 	memmove(p, ptr, size);
   1151 	free(ptr);
   1152 	return (p);
   1153 }
   1154 
   1155 /*
   1156  * Replace libc function with one suited to our needs.
   1157  */
   1158 void *
   1159 calloc(size, numelm)
   1160 	size_t size, numelm;
   1161 {
   1162 	void *base;
   1163 
   1164 	size *= numelm;
   1165 	base = malloc(size);
   1166 	memset(base, 0, size);
   1167 	return (base);
   1168 }
   1169 
   1170 /*
   1171  * Replace libc function with one suited to our needs.
   1172  */
   1173 void
   1174 free(ptr)
   1175 	void *ptr;
   1176 {
   1177 
   1178 	/* do not worry about it for now */
   1179 }
   1180 
   1181 /*
   1182  * read a block from the file system
   1183  */
   1184 void
   1185 rdfs(bno, size, bf)
   1186 	daddr_t bno;
   1187 	int size;
   1188 	void *bf;
   1189 {
   1190 	int n;
   1191 	off_t offset;
   1192 
   1193 	if (mfs) {
   1194 		memmove(bf, membase + bno * sectorsize, size);
   1195 		return;
   1196 	}
   1197 	offset = bno;
   1198 	offset *= sectorsize;
   1199 	if (lseek(fsi, offset, SEEK_SET) < 0) {
   1200 		printf("seek error: %d\n", bno);
   1201 		perror("rdfs");
   1202 		exit(33);
   1203 	}
   1204 	n = read(fsi, bf, size);
   1205 	if (n != size) {
   1206 		printf("read error: %d\n", bno);
   1207 		perror("rdfs");
   1208 		exit(34);
   1209 	}
   1210 }
   1211 
   1212 /*
   1213  * write a block to the file system
   1214  */
   1215 void
   1216 wtfs(bno, size, bf)
   1217 	daddr_t bno;
   1218 	int size;
   1219 	void *bf;
   1220 {
   1221 	int n;
   1222 	off_t offset;
   1223 
   1224 	if (mfs) {
   1225 		memmove(membase + bno * sectorsize, bf, size);
   1226 		return;
   1227 	}
   1228 	if (Nflag)
   1229 		return;
   1230 	offset = bno;
   1231 	offset *= sectorsize;
   1232 	if (lseek(fso, offset, SEEK_SET) < 0) {
   1233 		printf("seek error: %d\n", bno);
   1234 		perror("wtfs");
   1235 		exit(35);
   1236 	}
   1237 	n = write(fso, bf, size);
   1238 	if (n != size) {
   1239 		printf("write error: %d\n", bno);
   1240 		perror("wtfs");
   1241 		exit(36);
   1242 	}
   1243 }
   1244 
   1245 /*
   1246  * check if a block is available
   1247  */
   1248 int
   1249 isblock(fs, cp, h)
   1250 	struct fs *fs;
   1251 	unsigned char *cp;
   1252 	int h;
   1253 {
   1254 	unsigned char mask;
   1255 
   1256 	switch (fs->fs_frag) {
   1257 	case 8:
   1258 		return (cp[h] == 0xff);
   1259 	case 4:
   1260 		mask = 0x0f << ((h & 0x1) << 2);
   1261 		return ((cp[h >> 1] & mask) == mask);
   1262 	case 2:
   1263 		mask = 0x03 << ((h & 0x3) << 1);
   1264 		return ((cp[h >> 2] & mask) == mask);
   1265 	case 1:
   1266 		mask = 0x01 << (h & 0x7);
   1267 		return ((cp[h >> 3] & mask) == mask);
   1268 	default:
   1269 #ifdef STANDALONE
   1270 		printf("isblock bad fs_frag %d\n", fs->fs_frag);
   1271 #else
   1272 		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
   1273 #endif
   1274 		return (0);
   1275 	}
   1276 }
   1277 
   1278 /*
   1279  * take a block out of the map
   1280  */
   1281 void
   1282 clrblock(fs, cp, h)
   1283 	struct fs *fs;
   1284 	unsigned char *cp;
   1285 	int h;
   1286 {
   1287 	switch ((fs)->fs_frag) {
   1288 	case 8:
   1289 		cp[h] = 0;
   1290 		return;
   1291 	case 4:
   1292 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
   1293 		return;
   1294 	case 2:
   1295 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
   1296 		return;
   1297 	case 1:
   1298 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
   1299 		return;
   1300 	default:
   1301 #ifdef STANDALONE
   1302 		printf("clrblock bad fs_frag %d\n", fs->fs_frag);
   1303 #else
   1304 		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
   1305 #endif
   1306 		return;
   1307 	}
   1308 }
   1309 
   1310 /*
   1311  * put a block into the map
   1312  */
   1313 void
   1314 setblock(fs, cp, h)
   1315 	struct fs *fs;
   1316 	unsigned char *cp;
   1317 	int h;
   1318 {
   1319 	switch (fs->fs_frag) {
   1320 	case 8:
   1321 		cp[h] = 0xff;
   1322 		return;
   1323 	case 4:
   1324 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
   1325 		return;
   1326 	case 2:
   1327 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
   1328 		return;
   1329 	case 1:
   1330 		cp[h >> 3] |= (0x01 << (h & 0x7));
   1331 		return;
   1332 	default:
   1333 #ifdef STANDALONE
   1334 		printf("setblock bad fs_frag %d\n", fs->fs_frag);
   1335 #else
   1336 		fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
   1337 #endif
   1338 		return;
   1339 	}
   1340 }
   1341 
   1342 /* swap byte order of cylinder group */
   1343 static void
   1344 swap_cg(o, n)
   1345 	struct cg *o, *n;
   1346 {
   1347 	int i, btotsize, fbsize;
   1348 	u_int32_t *n32, *o32;
   1349 	u_int16_t *n16, *o16;
   1350 
   1351 	n->cg_firstfield = bswap32(o->cg_firstfield);
   1352 	n->cg_magic = bswap32(o->cg_magic);
   1353 	n->cg_time = bswap32(o->cg_time);
   1354 	n->cg_cgx = bswap32(o->cg_cgx);
   1355 	n->cg_ncyl = bswap16(o->cg_ncyl);
   1356 	n->cg_niblk = bswap16(o->cg_niblk);
   1357 	n->cg_ndblk = bswap32(o->cg_ndblk);
   1358 	n->cg_cs.cs_ndir = bswap32(o->cg_cs.cs_ndir);
   1359 	n->cg_cs.cs_nbfree = bswap32(o->cg_cs.cs_nbfree);
   1360 	n->cg_cs.cs_nifree = bswap32(o->cg_cs.cs_nifree);
   1361 	n->cg_cs.cs_nffree = bswap32(o->cg_cs.cs_nffree);
   1362 	n->cg_rotor = bswap32(o->cg_rotor);
   1363 	n->cg_frotor = bswap32(o->cg_frotor);
   1364 	n->cg_irotor = bswap32(o->cg_irotor);
   1365 	n->cg_btotoff = bswap32(o->cg_btotoff);
   1366 	n->cg_boff = bswap32(o->cg_boff);
   1367 	n->cg_iusedoff = bswap32(o->cg_iusedoff);
   1368 	n->cg_freeoff = bswap32(o->cg_freeoff);
   1369 	n->cg_nextfreeoff = bswap32(o->cg_nextfreeoff);
   1370 	n->cg_clustersumoff = bswap32(o->cg_clustersumoff);
   1371 	n->cg_clusteroff = bswap32(o->cg_clusteroff);
   1372 	n->cg_nclusterblks = bswap32(o->cg_nclusterblks);
   1373 	for (i=0; i < MAXFRAG; i++)
   1374 		n->cg_frsum[i] = bswap32(o->cg_frsum[i]);
   1375 
   1376 	/* alays new format */
   1377 	if (n->cg_magic == CG_MAGIC) {
   1378 		btotsize = n->cg_boff - n->cg_btotoff;
   1379 		fbsize = n->cg_iusedoff - n->cg_boff;
   1380 		n32 = (u_int32_t*)((u_int8_t*)n + n->cg_btotoff);
   1381 		o32 = (u_int32_t*)((u_int8_t*)o + n->cg_btotoff);
   1382 		n16 = (u_int16_t*)((u_int8_t*)n + n->cg_boff);
   1383 		o16 = (u_int16_t*)((u_int8_t*)o + n->cg_boff);
   1384 	} else {
   1385 		btotsize = bswap32(n->cg_boff) - bswap32(n->cg_btotoff);
   1386 		fbsize = bswap32(n->cg_iusedoff) - bswap32(n->cg_boff);
   1387 		n32 = (u_int32_t*)((u_int8_t*)n + bswap32(n->cg_btotoff));
   1388 		o32 = (u_int32_t*)((u_int8_t*)o + bswap32(n->cg_btotoff));
   1389 		n16 = (u_int16_t*)((u_int8_t*)n + bswap32(n->cg_boff));
   1390 		o16 = (u_int16_t*)((u_int8_t*)o + bswap32(n->cg_boff));
   1391 	}
   1392 	for (i=0; i < btotsize / sizeof(u_int32_t); i++)
   1393 		n32[i] = bswap32(o32[i]);
   1394 
   1395 	for (i=0; i < fbsize/sizeof(u_int16_t); i++)
   1396 		n16[i] = bswap16(o16[i]);
   1397 
   1398 	if (n->cg_magic == CG_MAGIC) {
   1399 		n32 = (u_int32_t*)((u_int8_t*)n + n->cg_clustersumoff);
   1400 		o32 = (u_int32_t*)((u_int8_t*)o + n->cg_clustersumoff);
   1401 	} else {
   1402 		n32 = (u_int32_t*)((u_int8_t*)n + bswap32(n->cg_clustersumoff));
   1403 		o32 = (u_int32_t*)((u_int8_t*)o + bswap32(n->cg_clustersumoff));
   1404 	}
   1405 	for (i = 0; i < sblock.fs_contigsumsize + 1; i++)
   1406 		n32[i] = bswap32(o32[i]);
   1407 }
   1408 
   1409 /* copy a direntry to a buffer, in fs byte order */
   1410 static void
   1411 copy_dir(dir, dbuf)
   1412 	struct direct *dir;
   1413 	struct direct *dbuf;
   1414 {
   1415 	memcpy(dbuf, dir, DIRSIZ(Oflag, dir, 0));
   1416 	if (needswap) {
   1417 		dbuf->d_ino = bswap32(dir->d_ino);
   1418 		dbuf->d_reclen = bswap16(dir->d_reclen);
   1419 		if (Oflag)
   1420 			((struct odirect*)dbuf)->d_namlen =
   1421 				bswap16(((struct odirect*)dir)->d_namlen);
   1422 	}
   1423 }
   1424 
   1425 /* Determine how many digits are needed to print a given integer */
   1426 static int
   1427 count_digits(num)
   1428 	int num;
   1429 {
   1430 	int ndig;
   1431 
   1432 	for(ndig = 1; num > 9; num /=10, ndig++);
   1433 
   1434 	return (ndig);
   1435 }
   1436