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