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