xref: /freebsd/sbin/newfs/mkfs.c (revision 77a0943ded95b9e6438f7db70c4a28e4d93946d4)
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 	i = sblock.fs_bsize / sizeof(struct csum);
637 	sblock.fs_csmask = ~(i - 1);
638 	for (sblock.fs_csshift = 0; i > 1; i >>= 1)
639 		sblock.fs_csshift++;
640 	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
641 	if (fscs == NULL)
642 		errx(31, "calloc failed");
643 	sblock.fs_magic = FS_MAGIC;
644 	sblock.fs_rotdelay = rotdelay;
645 	sblock.fs_minfree = minfree;
646 	sblock.fs_maxcontig = maxcontig;
647 	sblock.fs_maxbpg = maxbpg;
648 	sblock.fs_rps = rpm / 60;
649 	sblock.fs_optim = opt;
650 	sblock.fs_cgrotor = 0;
651 	sblock.fs_cstotal.cs_ndir = 0;
652 	sblock.fs_cstotal.cs_nbfree = 0;
653 	sblock.fs_cstotal.cs_nifree = 0;
654 	sblock.fs_cstotal.cs_nffree = 0;
655 	sblock.fs_fmod = 0;
656 	sblock.fs_ronly = 0;
657 	sblock.fs_clean = 1;
658 #ifdef FSIRAND
659 	sblock.fs_id[0] = (long)utime;
660 	sblock.fs_id[1] = random();
661 #endif
662 
663 	/*
664 	 * Dump out summary information about file system.
665 	 */
666 	if (!mfs) {
667 		printf("%s:\t%d sectors in %d %s of %d tracks, %d sectors\n",
668 		    fsys, sblock.fs_size * NSPF(&sblock), sblock.fs_ncyl,
669 		    "cylinders", sblock.fs_ntrak, sblock.fs_nsect);
670 #define B2MBFACTOR (1 / (1024.0 * 1024.0))
671 		printf("\t%.1fMB in %d cyl groups (%d c/g, %.2fMB/g, %d i/g)\n",
672 		    (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
673 		    sblock.fs_ncg, sblock.fs_cpg,
674 		    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
675 		    sblock.fs_ipg);
676 #undef B2MBFACTOR
677 	}
678 	/*
679 	 * Now build the cylinders group blocks and
680 	 * then print out indices of cylinder groups.
681 	 */
682 	if (!mfs)
683 		printf("super-block backups (for fsck -b #) at:\n");
684 	i = 0;
685 	width = charsperline();
686 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
687 		initcg(cylno, utime);
688 		if (mfs)
689 			continue;
690 		j = sprintf(tmpbuf, " %ld%s",
691 		    fsbtodb(&sblock, cgsblock(&sblock, cylno)),
692 		    cylno < (sblock.fs_ncg-1) ? "," : "" );
693 		if (i + j >= width) {
694 			printf("\n");
695 			i = 0;
696 		}
697 		i += j;
698 		printf("%s", tmpbuf);
699 		fflush(stdout);
700 	}
701 	if (!mfs)
702 		printf("\n");
703 	if (Nflag && !mfs)
704 		exit(0);
705 	/*
706 	 * Now construct the initial file system,
707 	 * then write out the super-block.
708 	 */
709 	fsinit(utime);
710 	sblock.fs_time = utime;
711 	wtfs((int)SBOFF / sectorsize, sbsize, (char *)&sblock);
712 	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
713 		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
714 			sblock.fs_cssize - i < sblock.fs_bsize ?
715 			    sblock.fs_cssize - i : sblock.fs_bsize,
716 			((char *)fscs) + i);
717 	/*
718 	 * Write out the duplicate super blocks
719 	 */
720 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
721 		wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)),
722 		    sbsize, (char *)&sblock);
723 	wtfsflush();
724 	/*
725 	 * Update information about this partion in pack
726 	 * label, to that it may be updated on disk.
727 	 */
728 	pp->p_fstype = FS_BSDFFS;
729 	pp->p_fsize = sblock.fs_fsize;
730 	pp->p_frag = sblock.fs_frag;
731 	pp->p_cpg = sblock.fs_cpg;
732 	/*
733 	 * Notify parent process of success.
734 	 * Dissociate from session and tty.
735 	 */
736 	if (mfs) {
737 		kill(mfs_ppid, SIGUSR1);
738 		(void) setsid();
739 		(void) close(0);
740 		(void) close(1);
741 		(void) close(2);
742 		(void) chdir("/");
743 	}
744 }
745 
746 /*
747  * Initialize a cylinder group.
748  */
749 void
750 initcg(cylno, utime)
751 	int cylno;
752 	time_t utime;
753 {
754 	daddr_t cbase, d, dlower, dupper, dmax, blkno;
755 	long i;
756 	register struct csum *cs;
757 #ifdef FSIRAND
758 	long j;
759 #endif
760 
761 	/*
762 	 * Determine block bounds for cylinder group.
763 	 * Allow space for super block summary information in first
764 	 * cylinder group.
765 	 */
766 	cbase = cgbase(&sblock, cylno);
767 	dmax = cbase + sblock.fs_fpg;
768 	if (dmax > sblock.fs_size)
769 		dmax = sblock.fs_size;
770 	dlower = cgsblock(&sblock, cylno) - cbase;
771 	dupper = cgdmin(&sblock, cylno) - cbase;
772 	if (cylno == 0)
773 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
774 	cs = fscs + cylno;
775 	memset(&acg, 0, sblock.fs_cgsize);
776 	acg.cg_time = utime;
777 	acg.cg_magic = CG_MAGIC;
778 	acg.cg_cgx = cylno;
779 	if (cylno == sblock.fs_ncg - 1)
780 		acg.cg_ncyl = sblock.fs_ncyl % sblock.fs_cpg;
781 	else
782 		acg.cg_ncyl = sblock.fs_cpg;
783 	acg.cg_niblk = sblock.fs_ipg;
784 	acg.cg_ndblk = dmax - cbase;
785 	if (sblock.fs_contigsumsize > 0)
786 		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
787 	acg.cg_btotoff = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
788 	acg.cg_boff = acg.cg_btotoff + sblock.fs_cpg * sizeof(int32_t);
789 	acg.cg_iusedoff = acg.cg_boff +
790 		sblock.fs_cpg * sblock.fs_nrpos * sizeof(u_int16_t);
791 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, NBBY);
792 	if (sblock.fs_contigsumsize <= 0) {
793 		acg.cg_nextfreeoff = acg.cg_freeoff +
794 		   howmany(sblock.fs_cpg * sblock.fs_spc / NSPF(&sblock), NBBY);
795 	} else {
796 		acg.cg_clustersumoff = acg.cg_freeoff + howmany
797 		    (sblock.fs_cpg * sblock.fs_spc / NSPF(&sblock), NBBY) -
798 		    sizeof(u_int32_t);
799 		acg.cg_clustersumoff =
800 		    roundup(acg.cg_clustersumoff, sizeof(u_int32_t));
801 		acg.cg_clusteroff = acg.cg_clustersumoff +
802 		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
803 		acg.cg_nextfreeoff = acg.cg_clusteroff + howmany
804 		    (sblock.fs_cpg * sblock.fs_spc / NSPB(&sblock), NBBY);
805 	}
806 	if (acg.cg_nextfreeoff - (long)(&acg.cg_firstfield) > sblock.fs_cgsize) {
807 		printf("Panic: cylinder group too big\n");
808 		exit(37);
809 	}
810 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
811 	if (cylno == 0)
812 		for (i = 0; i < ROOTINO; i++) {
813 			setbit(cg_inosused(&acg), i);
814 			acg.cg_cs.cs_nifree--;
815 		}
816 	for (i = 0; i < sblock.fs_ipg / INOPF(&sblock); i += sblock.fs_frag) {
817 #ifdef FSIRAND
818 		for (j = 0; j < sblock.fs_bsize / sizeof(struct dinode); j++)
819 			zino[j].di_gen = random();
820 #endif
821 		wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
822 		    sblock.fs_bsize, (char *)zino);
823 	}
824 	if (cylno > 0) {
825 		/*
826 		 * In cylno 0, beginning space is reserved
827 		 * for boot and super blocks.
828 		 */
829 		for (d = 0; d < dlower; d += sblock.fs_frag) {
830 			blkno = d / sblock.fs_frag;
831 			setblock(&sblock, cg_blksfree(&acg), blkno);
832 			if (sblock.fs_contigsumsize > 0)
833 				setbit(cg_clustersfree(&acg), blkno);
834 			acg.cg_cs.cs_nbfree++;
835 			cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
836 			cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
837 			    [cbtorpos(&sblock, d)]++;
838 		}
839 		sblock.fs_dsize += dlower;
840 	}
841 	sblock.fs_dsize += acg.cg_ndblk - dupper;
842 	if ((i = dupper % sblock.fs_frag)) {
843 		acg.cg_frsum[sblock.fs_frag - i]++;
844 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
845 			setbit(cg_blksfree(&acg), dupper);
846 			acg.cg_cs.cs_nffree++;
847 		}
848 	}
849 	for (d = dupper; d + sblock.fs_frag <= dmax - cbase; ) {
850 		blkno = d / sblock.fs_frag;
851 		setblock(&sblock, cg_blksfree(&acg), blkno);
852 		if (sblock.fs_contigsumsize > 0)
853 			setbit(cg_clustersfree(&acg), blkno);
854 		acg.cg_cs.cs_nbfree++;
855 		cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
856 		cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
857 		    [cbtorpos(&sblock, d)]++;
858 		d += sblock.fs_frag;
859 	}
860 	if (d < dmax - cbase) {
861 		acg.cg_frsum[dmax - cbase - d]++;
862 		for (; d < dmax - cbase; d++) {
863 			setbit(cg_blksfree(&acg), d);
864 			acg.cg_cs.cs_nffree++;
865 		}
866 	}
867 	if (sblock.fs_contigsumsize > 0) {
868 		int32_t *sump = cg_clustersum(&acg);
869 		u_char *mapp = cg_clustersfree(&acg);
870 		int map = *mapp++;
871 		int bit = 1;
872 		int run = 0;
873 
874 		for (i = 0; i < acg.cg_nclusterblks; i++) {
875 			if ((map & bit) != 0) {
876 				run++;
877 			} else if (run != 0) {
878 				if (run > sblock.fs_contigsumsize)
879 					run = sblock.fs_contigsumsize;
880 				sump[run]++;
881 				run = 0;
882 			}
883 			if ((i & (NBBY - 1)) != (NBBY - 1)) {
884 				bit <<= 1;
885 			} else {
886 				map = *mapp++;
887 				bit = 1;
888 			}
889 		}
890 		if (run != 0) {
891 			if (run > sblock.fs_contigsumsize)
892 				run = sblock.fs_contigsumsize;
893 			sump[run]++;
894 		}
895 	}
896 	sblock.fs_cstotal.cs_ndir += acg.cg_cs.cs_ndir;
897 	sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
898 	sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
899 	sblock.fs_cstotal.cs_nifree += acg.cg_cs.cs_nifree;
900 	*cs = acg.cg_cs;
901 	wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
902 		sblock.fs_bsize, (char *)&acg);
903 }
904 
905 /*
906  * initialize the file system
907  */
908 struct dinode node;
909 
910 #ifdef LOSTDIR
911 #define PREDEFDIR 3
912 #else
913 #define PREDEFDIR 2
914 #endif
915 
916 struct direct root_dir[] = {
917 	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
918 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
919 #ifdef LOSTDIR
920 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 10, "lost+found" },
921 #endif
922 };
923 struct odirect {
924 	u_long	d_ino;
925 	u_short	d_reclen;
926 	u_short	d_namlen;
927 	u_char	d_name[MAXNAMLEN + 1];
928 } oroot_dir[] = {
929 	{ ROOTINO, sizeof(struct direct), 1, "." },
930 	{ ROOTINO, sizeof(struct direct), 2, ".." },
931 #ifdef LOSTDIR
932 	{ LOSTFOUNDINO, sizeof(struct direct), 10, "lost+found" },
933 #endif
934 };
935 #ifdef LOSTDIR
936 struct direct lost_found_dir[] = {
937 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 1, "." },
938 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
939 	{ 0, DIRBLKSIZ, 0, 0, 0 },
940 };
941 struct odirect olost_found_dir[] = {
942 	{ LOSTFOUNDINO, sizeof(struct direct), 1, "." },
943 	{ ROOTINO, sizeof(struct direct), 2, ".." },
944 	{ 0, DIRBLKSIZ, 0, 0 },
945 };
946 #endif
947 char buf[MAXBSIZE];
948 
949 void
950 fsinit(utime)
951 	time_t utime;
952 {
953 #ifdef LOSTDIR
954 	int i;
955 #endif
956 
957 	/*
958 	 * initialize the node
959 	 */
960 	node.di_atime = utime;
961 	node.di_mtime = utime;
962 	node.di_ctime = utime;
963 #ifdef LOSTDIR
964 	/*
965 	 * create the lost+found directory
966 	 */
967 	if (Oflag) {
968 		(void)makedir((struct direct *)olost_found_dir, 2);
969 		for (i = DIRBLKSIZ; i < sblock.fs_bsize; i += DIRBLKSIZ)
970 			memmove(&buf[i], &olost_found_dir[2],
971 			    DIRSIZ(0, &olost_found_dir[2]));
972 	} else {
973 		(void)makedir(lost_found_dir, 2);
974 		for (i = DIRBLKSIZ; i < sblock.fs_bsize; i += DIRBLKSIZ)
975 			memmove(&buf[i], &lost_found_dir[2],
976 			    DIRSIZ(0, &lost_found_dir[2]));
977 	}
978 	node.di_mode = IFDIR | UMASK;
979 	node.di_nlink = 2;
980 	node.di_size = sblock.fs_bsize;
981 	node.di_db[0] = alloc(node.di_size, node.di_mode);
982 	node.di_blocks = btodb(fragroundup(&sblock, node.di_size));
983 	wtfs(fsbtodb(&sblock, node.di_db[0]), node.di_size, buf);
984 	iput(&node, LOSTFOUNDINO);
985 #endif
986 	/*
987 	 * create the root directory
988 	 */
989 	if (mfs)
990 		node.di_mode = IFDIR | 01777;
991 	else
992 		node.di_mode = IFDIR | UMASK;
993 	node.di_nlink = PREDEFDIR;
994 	if (Oflag)
995 		node.di_size = makedir((struct direct *)oroot_dir, PREDEFDIR);
996 	else
997 		node.di_size = makedir(root_dir, PREDEFDIR);
998 	node.di_db[0] = alloc(sblock.fs_fsize, node.di_mode);
999 	node.di_blocks = btodb(fragroundup(&sblock, node.di_size));
1000 	wtfs(fsbtodb(&sblock, node.di_db[0]), sblock.fs_fsize, buf);
1001 	iput(&node, ROOTINO);
1002 }
1003 
1004 /*
1005  * construct a set of directory entries in "buf".
1006  * return size of directory.
1007  */
1008 int
1009 makedir(protodir, entries)
1010 	register struct direct *protodir;
1011 	int entries;
1012 {
1013 	char *cp;
1014 	int i, spcleft;
1015 
1016 	spcleft = DIRBLKSIZ;
1017 	for (cp = buf, i = 0; i < entries - 1; i++) {
1018 		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
1019 		memmove(cp, &protodir[i], protodir[i].d_reclen);
1020 		cp += protodir[i].d_reclen;
1021 		spcleft -= protodir[i].d_reclen;
1022 	}
1023 	protodir[i].d_reclen = spcleft;
1024 	memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
1025 	return (DIRBLKSIZ);
1026 }
1027 
1028 /*
1029  * allocate a block or frag
1030  */
1031 daddr_t
1032 alloc(size, mode)
1033 	int size;
1034 	int mode;
1035 {
1036 	int i, frag;
1037 	daddr_t d, blkno;
1038 
1039 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1040 	    (char *)&acg);
1041 	if (acg.cg_magic != CG_MAGIC) {
1042 		printf("cg 0: bad magic number\n");
1043 		return (0);
1044 	}
1045 	if (acg.cg_cs.cs_nbfree == 0) {
1046 		printf("first cylinder group ran out of space\n");
1047 		return (0);
1048 	}
1049 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
1050 		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
1051 			goto goth;
1052 	printf("internal error: can't find block in cyl 0\n");
1053 	return (0);
1054 goth:
1055 	blkno = fragstoblks(&sblock, d);
1056 	clrblock(&sblock, cg_blksfree(&acg), blkno);
1057 	if (sblock.fs_contigsumsize > 0)
1058 		clrbit(cg_clustersfree(&acg), blkno);
1059 	acg.cg_cs.cs_nbfree--;
1060 	sblock.fs_cstotal.cs_nbfree--;
1061 	fscs[0].cs_nbfree--;
1062 	if (mode & IFDIR) {
1063 		acg.cg_cs.cs_ndir++;
1064 		sblock.fs_cstotal.cs_ndir++;
1065 		fscs[0].cs_ndir++;
1066 	}
1067 	cg_blktot(&acg)[cbtocylno(&sblock, d)]--;
1068 	cg_blks(&sblock, &acg, cbtocylno(&sblock, d))[cbtorpos(&sblock, d)]--;
1069 	if (size != sblock.fs_bsize) {
1070 		frag = howmany(size, sblock.fs_fsize);
1071 		fscs[0].cs_nffree += sblock.fs_frag - frag;
1072 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
1073 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
1074 		acg.cg_frsum[sblock.fs_frag - frag]++;
1075 		for (i = frag; i < sblock.fs_frag; i++)
1076 			setbit(cg_blksfree(&acg), d + i);
1077 	}
1078 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1079 	    (char *)&acg);
1080 	return (d);
1081 }
1082 
1083 /*
1084  * Calculate number of inodes per group.
1085  */
1086 long
1087 calcipg(cpg, bpcg, usedbp)
1088 	long cpg;
1089 	long bpcg;
1090 	off_t *usedbp;
1091 {
1092 	int i;
1093 	long ipg, new_ipg, ncg, ncyl;
1094 	off_t usedb;
1095 
1096 	/*
1097 	 * Prepare to scale by fssize / (number of sectors in cylinder groups).
1098 	 * Note that fssize is still in sectors, not filesystem blocks.
1099 	 */
1100 	ncyl = howmany(fssize, (u_int)secpercyl);
1101 	ncg = howmany(ncyl, cpg);
1102 	/*
1103 	 * Iterate a few times to allow for ipg depending on itself.
1104 	 */
1105 	ipg = 0;
1106 	for (i = 0; i < 10; i++) {
1107 		usedb = (sblock.fs_iblkno + ipg / INOPF(&sblock))
1108 			* NSPF(&sblock) * (off_t)sectorsize;
1109 		new_ipg = (cpg * (quad_t)bpcg - usedb) / density * fssize
1110 			  / ncg / secpercyl / cpg;
1111 		new_ipg = roundup(new_ipg, INOPB(&sblock));
1112 		if (new_ipg == ipg)
1113 			break;
1114 		ipg = new_ipg;
1115 	}
1116 	*usedbp = usedb;
1117 	return (ipg);
1118 }
1119 
1120 /*
1121  * Allocate an inode on the disk
1122  */
1123 void
1124 iput(ip, ino)
1125 	register struct dinode *ip;
1126 	register ino_t ino;
1127 {
1128 	struct dinode buf[MAXINOPB];
1129 	daddr_t d;
1130 	int c;
1131 
1132 #ifdef FSIRAND
1133 	ip->di_gen = random();
1134 #endif
1135 	c = ino_to_cg(&sblock, ino);
1136 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1137 	    (char *)&acg);
1138 	if (acg.cg_magic != CG_MAGIC) {
1139 		printf("cg 0: bad magic number\n");
1140 		exit(31);
1141 	}
1142 	acg.cg_cs.cs_nifree--;
1143 	setbit(cg_inosused(&acg), ino);
1144 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1145 	    (char *)&acg);
1146 	sblock.fs_cstotal.cs_nifree--;
1147 	fscs[0].cs_nifree--;
1148 	if (ino >= sblock.fs_ipg * sblock.fs_ncg) {
1149 		printf("fsinit: inode value out of range (%d).\n", ino);
1150 		exit(32);
1151 	}
1152 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
1153 	rdfs(d, sblock.fs_bsize, (char *)buf);
1154 	buf[ino_to_fsbo(&sblock, ino)] = *ip;
1155 	wtfs(d, sblock.fs_bsize, (char *)buf);
1156 }
1157 
1158 /*
1159  * Notify parent process that the filesystem has created itself successfully.
1160  *
1161  * We have to wait until the mount has actually completed!
1162  */
1163 void
1164 started()
1165 {
1166 	int retry = 100;	/* 10 seconds, 100ms */
1167 
1168 	while (mfs_ppid && retry) {
1169 		struct stat st;
1170 
1171 		if (
1172 		    stat(mfs_mtpt, &st) < 0 ||
1173 		    st.st_dev != mfs_mtstat.st_dev
1174 		) {
1175 			break;
1176 		}
1177 		usleep(100*1000);
1178 		--retry;
1179 	}
1180 	if (retry == 0) {
1181 		fatal("mfs mount failed waiting for mount to go active");
1182 	}
1183 	exit(0);
1184 }
1185 
1186 #ifdef STANDALONE
1187 /*
1188  * Replace libc function with one suited to our needs.
1189  */
1190 caddr_t
1191 malloc(size)
1192 	register u_long size;
1193 {
1194 	char *base, *i;
1195 	static u_long pgsz;
1196 	struct rlimit rlp;
1197 
1198 	if (pgsz == 0) {
1199 		base = sbrk(0);
1200 		pgsz = getpagesize() - 1;
1201 		i = (char *)((u_long)(base + pgsz) &~ pgsz);
1202 		base = sbrk(i - base);
1203 		if (getrlimit(RLIMIT_DATA, &rlp) < 0)
1204 			warn("getrlimit");
1205 		rlp.rlim_cur = rlp.rlim_max;
1206 		if (setrlimit(RLIMIT_DATA, &rlp) < 0)
1207 			warn("setrlimit");
1208 		memleft = rlp.rlim_max - (u_long)base;
1209 	}
1210 	size = (size + pgsz) &~ pgsz;
1211 	if (size > memleft)
1212 		size = memleft;
1213 	memleft -= size;
1214 	if (size == 0)
1215 		return (0);
1216 	return ((caddr_t)sbrk(size));
1217 }
1218 
1219 /*
1220  * Replace libc function with one suited to our needs.
1221  */
1222 caddr_t
1223 realloc(ptr, size)
1224 	char *ptr;
1225 	u_long size;
1226 {
1227 	void *p;
1228 
1229 	if ((p = malloc(size)) == NULL)
1230 		return (NULL);
1231 	memmove(p, ptr, size);
1232 	free(ptr);
1233 	return (p);
1234 }
1235 
1236 /*
1237  * Replace libc function with one suited to our needs.
1238  */
1239 char *
1240 calloc(size, numelm)
1241 	u_long size, numelm;
1242 {
1243 	caddr_t base;
1244 
1245 	size *= numelm;
1246 	if ((base = malloc(size)) == NULL)
1247 		return (NULL);
1248 	memset(base, 0, size);
1249 	return (base);
1250 }
1251 
1252 /*
1253  * Replace libc function with one suited to our needs.
1254  */
1255 void
1256 free(ptr)
1257 	char *ptr;
1258 {
1259 
1260 	/* do not worry about it for now */
1261 }
1262 
1263 #else   /* !STANDALONE */
1264 
1265 void
1266 raise_data_limit()
1267 {
1268 	struct rlimit rlp;
1269 
1270 	if (getrlimit(RLIMIT_DATA, &rlp) < 0)
1271 		warn("getrlimit");
1272 	rlp.rlim_cur = rlp.rlim_max;
1273 	if (setrlimit(RLIMIT_DATA, &rlp) < 0)
1274 		warn("setrlimit");
1275 }
1276 
1277 #ifdef __ELF__
1278 extern char *_etext;
1279 #define etext _etext
1280 #else
1281 extern char *etext;
1282 #endif
1283 
1284 void
1285 get_memleft()
1286 {
1287 	static u_long pgsz;
1288 	struct rlimit rlp;
1289 	u_long freestart;
1290 	u_long dstart;
1291 	u_long memused;
1292 
1293 	pgsz = getpagesize() - 1;
1294 	dstart = ((u_long)&etext) &~ pgsz;
1295 	freestart = ((u_long)(sbrk(0) + pgsz) &~ pgsz);
1296 	if (getrlimit(RLIMIT_DATA, &rlp) < 0)
1297 		warn("getrlimit");
1298 	memused = freestart - dstart;
1299 	memleft = rlp.rlim_cur - memused;
1300 }
1301 #endif  /* STANDALONE */
1302 
1303 /*
1304  * read a block from the file system
1305  */
1306 void
1307 rdfs(bno, size, bf)
1308 	daddr_t bno;
1309 	int size;
1310 	char *bf;
1311 {
1312 	int n;
1313 
1314 	wtfsflush();
1315 	if (mfs) {
1316 		memmove(bf, membase + bno * sectorsize, size);
1317 		return;
1318 	}
1319 	if (lseek(fsi, (off_t)bno * sectorsize, 0) < 0) {
1320 		printf("seek error: %ld\n", (long)bno);
1321 		err(33, "rdfs");
1322 	}
1323 	n = read(fsi, bf, size);
1324 	if (n != size) {
1325 		printf("read error: %ld\n", (long)bno);
1326 		err(34, "rdfs");
1327 	}
1328 }
1329 
1330 #define WCSIZE (128 * 1024)
1331 daddr_t wc_sect;		/* units of sectorsize */
1332 int wc_end;			/* bytes */
1333 static char wc[WCSIZE];		/* bytes */
1334 
1335 /*
1336  * Flush dirty write behind buffer.
1337  */
1338 void
1339 wtfsflush()
1340 {
1341 	int n;
1342 	if (wc_end) {
1343 		if (lseek(fso, (off_t)wc_sect * sectorsize, SEEK_SET) < 0) {
1344 			printf("seek error: %ld\n", (long)wc_sect);
1345 			err(35, "wtfs - writecombine");
1346 		}
1347 		n = write(fso, wc, wc_end);
1348 		if (n != wc_end) {
1349 			printf("write error: %ld\n", (long)wc_sect);
1350 			err(36, "wtfs - writecombine");
1351 		}
1352 		wc_end = 0;
1353 	}
1354 }
1355 
1356 /*
1357  * write a block to the file system
1358  */
1359 void
1360 wtfs(bno, size, bf)
1361 	daddr_t bno;
1362 	int size;
1363 	char *bf;
1364 {
1365 	int n;
1366 	int done;
1367 
1368 	if (mfs) {
1369 		memmove(membase + bno * sectorsize, bf, size);
1370 		return;
1371 	}
1372 	if (Nflag)
1373 		return;
1374 	done = 0;
1375 	if (wc_end == 0 && size <= WCSIZE) {
1376 		wc_sect = bno;
1377 		bcopy(bf, wc, size);
1378 		wc_end = size;
1379 		if (wc_end < WCSIZE)
1380 			return;
1381 		done = 1;
1382 	}
1383 	if ((off_t)wc_sect * sectorsize + wc_end == (off_t)bno * sectorsize &&
1384 	    wc_end + size <= WCSIZE) {
1385 		bcopy(bf, wc + wc_end, size);
1386 		wc_end += size;
1387 		if (wc_end < WCSIZE)
1388 			return;
1389 		done = 1;
1390 	}
1391 	wtfsflush();
1392 	if (done)
1393 		return;
1394 	if (lseek(fso, (off_t)bno * sectorsize, SEEK_SET) < 0) {
1395 		printf("seek error: %ld\n", (long)bno);
1396 		err(35, "wtfs");
1397 	}
1398 	n = write(fso, bf, size);
1399 	if (n != size) {
1400 		printf("write error: %ld\n", (long)bno);
1401 		err(36, "wtfs");
1402 	}
1403 }
1404 
1405 /*
1406  * check if a block is available
1407  */
1408 int
1409 isblock(fs, cp, h)
1410 	struct fs *fs;
1411 	unsigned char *cp;
1412 	int h;
1413 {
1414 	unsigned char mask;
1415 
1416 	switch (fs->fs_frag) {
1417 	case 8:
1418 		return (cp[h] == 0xff);
1419 	case 4:
1420 		mask = 0x0f << ((h & 0x1) << 2);
1421 		return ((cp[h >> 1] & mask) == mask);
1422 	case 2:
1423 		mask = 0x03 << ((h & 0x3) << 1);
1424 		return ((cp[h >> 2] & mask) == mask);
1425 	case 1:
1426 		mask = 0x01 << (h & 0x7);
1427 		return ((cp[h >> 3] & mask) == mask);
1428 	default:
1429 #ifdef STANDALONE
1430 		printf("isblock bad fs_frag %d\n", fs->fs_frag);
1431 #else
1432 		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
1433 #endif
1434 		return (0);
1435 	}
1436 }
1437 
1438 /*
1439  * take a block out of the map
1440  */
1441 void
1442 clrblock(fs, cp, h)
1443 	struct fs *fs;
1444 	unsigned char *cp;
1445 	int h;
1446 {
1447 	switch ((fs)->fs_frag) {
1448 	case 8:
1449 		cp[h] = 0;
1450 		return;
1451 	case 4:
1452 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1453 		return;
1454 	case 2:
1455 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1456 		return;
1457 	case 1:
1458 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1459 		return;
1460 	default:
1461 #ifdef STANDALONE
1462 		printf("clrblock bad fs_frag %d\n", fs->fs_frag);
1463 #else
1464 		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
1465 #endif
1466 		return;
1467 	}
1468 }
1469 
1470 /*
1471  * put a block into the map
1472  */
1473 void
1474 setblock(fs, cp, h)
1475 	struct fs *fs;
1476 	unsigned char *cp;
1477 	int h;
1478 {
1479 	switch (fs->fs_frag) {
1480 	case 8:
1481 		cp[h] = 0xff;
1482 		return;
1483 	case 4:
1484 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1485 		return;
1486 	case 2:
1487 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1488 		return;
1489 	case 1:
1490 		cp[h >> 3] |= (0x01 << (h & 0x7));
1491 		return;
1492 	default:
1493 #ifdef STANDALONE
1494 		printf("setblock bad fs_frag %d\n", fs->fs_frag);
1495 #else
1496 		fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
1497 #endif
1498 		return;
1499 	}
1500 }
1501 
1502 /*
1503  * Determine the number of characters in a
1504  * single line.
1505  */
1506 
1507 static int
1508 charsperline()
1509 {
1510 	int columns;
1511 	char *cp;
1512 	struct winsize ws;
1513 
1514 	columns = 0;
1515 	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1516 		columns = ws.ws_col;
1517 	if (columns == 0 && (cp = getenv("COLUMNS")))
1518 		columns = atoi(cp);
1519 	if (columns == 0)
1520 		columns = 80;	/* last resort */
1521 	return columns;
1522 }
1523