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