mkfs.c revision 75377
131567Ssef/*
231899Ssef * Copyright (c) 1980, 1989, 1993
331899Ssef *	The Regents of the University of California.  All rights reserved.
431899Ssef *
531899Ssef * Redistribution and use in source and binary forms, with or without
631899Ssef * modification, are permitted provided that the following conditions
731899Ssef * are met:
831899Ssef * 1. Redistributions of source code must retain the above copyright
931899Ssef *    notice, this list of conditions and the following disclaimer.
1031899Ssef * 2. Redistributions in binary form must reproduce the above copyright
1131899Ssef *    notice, this list of conditions and the following disclaimer in the
1231899Ssef *    documentation and/or other materials provided with the distribution.
1331899Ssef * 3. All advertising materials mentioning features or use of this software
1431899Ssef *    must display the following acknowledgement:
1531899Ssef *	This product includes software developed by the University of
1631899Ssef *	California, Berkeley and its contributors.
1731899Ssef * 4. Neither the name of the University nor the names of its contributors
1831899Ssef *    may be used to endorse or promote products derived from this software
1931899Ssef *    without specific prior written permission.
2031899Ssef *
2131899Ssef * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2231899Ssef * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2331899Ssef * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2431899Ssef * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2531899Ssef * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2631899Ssef * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2731899Ssef * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2831899Ssef * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2931899Ssef * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3031899Ssef * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3131899Ssef * SUCH DAMAGE.
3232275Scharnier */
3332275Scharnier
3450477Speter#ifndef lint
3532275Scharnier#if 0
3632275Scharnierstatic char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
3731899Ssef#endif
3831567Ssefstatic const char rcsid[] =
3931567Ssef  "$FreeBSD: head/sbin/newfs/mkfs.c 75377 2001-04-10 08:38:59Z mckusick $";
4031567Ssef#endif /* not lint */
4131567Ssef
4231567Ssef#include <err.h>
4385301Sdes#include <signal.h>
4485301Sdes#include <string.h>
4585301Sdes#include <stdio.h>
4685301Sdes#include <unistd.h>
4732275Scharnier#include <sys/param.h>
4832275Scharnier#include <sys/time.h>
4932275Scharnier#include <sys/types.h>
5032275Scharnier#include <sys/wait.h>
5131567Ssef#include <sys/resource.h>
5231567Ssef#include <sys/stat.h>
5331567Ssef#include <ufs/ufs/dinode.h>
5431579Speter#include <ufs/ufs/dir.h>
5531567Ssef#include <ufs/ffs/fs.h>
56101282Smdodd#include <sys/disklabel.h>
5787703Smarkm#include <sys/file.h>
5831567Ssef#include <sys/mman.h>
5931567Ssef#include <sys/ioctl.h>
60101282Smdodd
61101282Smdodd#ifndef STANDALONE
6231567Ssef#include <stdlib.h>
6331567Ssef#else
6431567Ssefextern int atoi __P((char *));
6531567Ssefextern char * getenv __P((char *));
66100357Smarkm#endif
6732275Scharnier
6832275Scharnier#ifdef FSIRAND
6932275Scharnierextern long random __P((void));
70101289Smdoddextern void srandomdev __P((void));
71101289Smdodd#endif
7231567Ssef
7331567Ssef/*
7431567Ssef * make file system for cylinder-group style file systems
7538897Ssef */
7638897Ssef
7738897Ssef/*
7838897Ssef * We limit the size of the inode map to be no more than a
7931567Ssef * third of the cylinder group space, since we must leave at
8087703Smarkm * least an equal amount of space for the block map.
81101282Smdodd *
82101282Smdodd * N.B.: MAXIPG must be a multiple of INOPB(fs).
8331567Ssef */
8439908Ssef#define MAXIPG(fs)	roundup((fs)->fs_bsize * NBBY / 3, INOPB(fs))
8539908Ssef
8639908Ssef#define UMASK		0755
8739908Ssef#define MAXINOPB	(MAXBSIZE / sizeof(struct dinode))
8831567Ssef#define POWEROF2(num)	(((num) & ((num) - 1)) == 0)
8931580Speter
90101288Smdodd/*
9131567Ssef * variables set up by front end.
9239908Ssef */
9331567Ssefextern int	mfs;		/* run as the memory based filesystem */
9431567Ssefextern char	*mfs_mtpt;	/* mount point for mfs          */
9531567Ssefextern struct stat mfs_mtstat;	/* stat prior to mount          */
9631567Ssefextern int	Nflag;		/* run mkfs without writing file system */
9731567Ssefextern int	Oflag;		/* format as an 4.3BSD file system */
9831567Ssefextern int	Uflag;		/* enable soft updates for file system */
9931567Ssefextern int	fssize;		/* file system size */
10031567Ssefextern int	ntracks;	/* # tracks/cylinder */
10131567Ssefextern int	nsectors;	/* # sectors/track */
10231567Ssefextern int	nphyssectors;	/* # sectors/track including spares */
103101282Smdoddextern int	secpercyl;	/* sectors per cylinder */
10431567Ssefextern int	sectorsize;	/* bytes/sector */
10531567Ssefextern int	realsectorsize;	/* bytes/sector in hardware*/
10687703Smarkmextern int	rpm;		/* revolutions/minute of drive */
10731567Ssefextern int	interleave;	/* hardware sector interleave */
10831567Ssefextern int	trackskew;	/* sector 0 skew, per track */
109101282Smdoddextern int	fsize;		/* fragment size */
11031567Ssefextern int	bsize;		/* block size */
11187703Smarkmextern int	cpg;		/* cylinders/cylinder group */
11231567Ssefextern int	cpgflg;		/* cylinders/cylinder group flag was given */
11387703Smarkmextern int	minfree;	/* free space threshold */
11487703Smarkmextern int	opt;		/* optimization preference (space or time) */
11531580Speterextern int	density;	/* number of bytes per inode */
11631567Ssefextern int	maxcontig;	/* max contiguous blocks to allocate */
11731567Ssefextern int	rotdelay;	/* rotational delay between blocks */
11831567Ssefextern int	maxbpg;		/* maximum blocks per file in a cyl group */
11987703Smarkmextern int	nrpos;		/* # of distinguished rotational positions */
12031567Ssefextern int	bbsize;		/* boot block size */
12131567Ssefextern int	sbsize;		/* superblock size */
12290401Sdesextern int	avgfilesize;	/* expected average file size */
12338897Ssefextern int	avgfilesperdir;	/* expected number of files per directory */
12490401Sdesextern u_long	memleft;	/* virtual memory available */
12590401Sdesextern caddr_t	membase;	/* start address of memory based filesystem */
12638897Ssefextern char *	filename;
12731567Ssef
12831567Ssefunion {
12931567Ssef	struct fs fs;
13032275Scharnier	char pad[SBSIZE];
13131567Ssef} fsun;
13231567Ssef#define	sblock	fsun.fs
13331567Ssefstruct	csum *fscs;
13431567Ssef
13531567Ssefunion {
13631567Ssef	struct cg cg;
13731567Ssef	char pad[MAXBSIZE];
13832275Scharnier} cgun;
13938520Scracauer#define	acg	cgun.cg
140101282Smdodd
14131567Ssefstruct dinode zino[MAXBSIZE / sizeof(struct dinode)];
142101282Smdodd
143101282Smdoddint	fsi, fso;
144101282Smdodd#ifdef FSIRAND
145101282Smdoddint     randinit;
146101282Smdodd#endif
147101282Smdodddaddr_t	alloc();
148101282Smdoddlong	calcipg();
149101289Smdoddstatic int charsperline();
15031567Ssefvoid clrblock __P((struct fs *, unsigned char *, int));
15131567Ssefvoid fsinit __P((time_t));
152101282Smdoddvoid initcg __P((int, time_t));
15331567Ssefint isblock __P((struct fs *, unsigned char *, int));
154101283Smdoddvoid iput __P((struct dinode *, ino_t));
155101283Smdoddint makedir __P((struct direct *, int));
156101283Smdoddvoid rdfs __P((daddr_t, int, char *));
157101289Smdoddvoid setblock __P((struct fs *, unsigned char *, int));
158101289Smdoddvoid wtfs __P((daddr_t, int, char *));
159101289Smdoddvoid wtfsflush __P((void));
160101289Smdodd
161101289Smdodd#ifndef STANDALONE
162101289Smdoddvoid get_memleft __P((void));
163101285Smdoddvoid raise_data_limit __P((void));
164101285Smdodd#else
165101285Smdoddvoid free __P((char *));
166101285Smdoddchar * calloc __P((u_long, u_long));
167101285Smdoddcaddr_t malloc __P((u_long));
168101285Smdoddcaddr_t realloc __P((char *, u_long));
16931567Ssef#endif
17032275Scharnier
17131567Ssefint mfs_ppid = 0;
17231567Ssef
173101282Smdoddvoid
17431567Ssefmkfs(pp, fsys, fi, fo)
17531567Ssef	struct partition *pp;
17631567Ssef	char *fsys;
17731567Ssef	int fi, fo;
17831567Ssef{
17931567Ssef	register long i, mincpc, mincpg, inospercg;
18031567Ssef	long cylno, rpos, blk, j, warn = 0;
181101282Smdodd	long used, mincpgcnt, bpcg;
18231567Ssef	off_t usedb;
18331567Ssef	long mapcramped, inodecramped;
18432275Scharnier	long postblsize, rotblsize, totalsbsize;
185101282Smdodd	int status, fd;
18632275Scharnier	time_t utime;
18732275Scharnier	quad_t sizepb;
18832275Scharnier	void started();
18931567Ssef	int width;
19031567Ssef	char tmpbuf[100];	/* XXX this will break in about 2,500 years */
19131567Ssef
19231567Ssef#ifndef STANDALONE
19331567Ssef	time(&utime);
19431567Ssef#endif
19531567Ssef#ifdef FSIRAND
196101282Smdodd	if (!randinit) {
19731567Ssef		randinit = 1;
198101282Smdodd		srandomdev();
19931567Ssef	}
20031567Ssef#endif
20131567Ssef	if (mfs) {
20231567Ssef		mfs_ppid = getpid();
20331567Ssef		(void) signal(SIGUSR1, started);
20431567Ssef		if ((i = fork())) {
20531567Ssef			if (i == -1)
20631567Ssef				err(10, "mfs");
20731567Ssef			if (waitpid(i, &status, 0) != -1 && WIFEXITED(status))
20831567Ssef				exit(WEXITSTATUS(status));
20931567Ssef			exit(11);
21031567Ssef			/* NOTREACHED */
21131567Ssef		}
21231567Ssef#ifdef STANDALONE
21331567Ssef		(void)malloc(0);
214101283Smdodd#else
215101282Smdodd		raise_data_limit();
216101282Smdodd#endif
217101283Smdodd		if(filename) {
218101283Smdodd			unsigned char buf[BUFSIZ];
21955707Ssef			unsigned long l,l1;
22055707Ssef			fd = open(filename,O_RDWR|O_TRUNC|O_CREAT,0644);
22155707Ssef			if(fd < 0)
22231567Ssef				err(12, "%s", filename);
22331567Ssef			for(l=0;l< fssize * sectorsize;l += l1) {
224101282Smdodd				l1 = fssize * sectorsize;
22531567Ssef				if (BUFSIZ < l1)
22631567Ssef					l1 = BUFSIZ;
22731567Ssef				if (l1 != write(fd,buf,l1))
22831567Ssef					err(12, "%s", filename);
22931567Ssef			}
23031567Ssef			membase = mmap(
231101285Smdodd				0,
232101285Smdodd				fssize * sectorsize,
23331567Ssef				PROT_READ|PROT_WRITE,
23431567Ssef				MAP_SHARED,
23531567Ssef				fd,
23631567Ssef				0);
23732275Scharnier			if(membase == MAP_FAILED)
23831567Ssef				err(12, "mmap");
23931567Ssef			close(fd);
24031567Ssef		} else {
241101282Smdodd#ifndef STANDALONE
242101285Smdodd			get_memleft();
24331567Ssef#endif
24431567Ssef			if (fssize * sectorsize > (memleft - 131072))
245101285Smdodd				fssize = (memleft - 131072) / sectorsize;
24631567Ssef			if ((membase = malloc(fssize * sectorsize)) == NULL)
24731567Ssef				errx(13, "malloc failed");
24831567Ssef		}
24931567Ssef	}
25031567Ssef	fsi = fi;
25131567Ssef	fso = fo;
25231567Ssef	if (Oflag) {
25331567Ssef		sblock.fs_inodefmt = FS_42INODEFMT;
25431567Ssef		sblock.fs_maxsymlinklen = 0;
25531567Ssef	} else {
25631567Ssef		sblock.fs_inodefmt = FS_44INODEFMT;
257101283Smdodd		sblock.fs_maxsymlinklen = MAXSYMLINKLEN;
258101283Smdodd	}
259101283Smdodd	if (Uflag)
260101283Smdodd		sblock.fs_flags |= FS_DOSOFTDEP;
261101283Smdodd	/*
262101283Smdodd	 * Validate the given file system size.
263101283Smdodd	 * Verify that its last block can actually be accessed.
264101283Smdodd	 */
265101283Smdodd	if (fssize <= 0)
266101283Smdodd		printf("preposterous size %d\n", fssize), exit(13);
267101283Smdodd	wtfs(fssize - (realsectorsize / DEV_BSIZE), realsectorsize,
268101283Smdodd		 (char *)&sblock);
269101283Smdodd	/*
270101283Smdodd	 * collect and verify the sector and track info
271101283Smdodd	 */
272101283Smdodd	sblock.fs_nsect = nsectors;
273101283Smdodd	sblock.fs_ntrak = ntracks;
274101282Smdodd	if (sblock.fs_ntrak <= 0)
27531567Ssef		printf("preposterous ntrak %d\n", sblock.fs_ntrak), exit(14);
27631567Ssef	if (sblock.fs_nsect <= 0)
277101282Smdodd		printf("preposterous nsect %d\n", sblock.fs_nsect), exit(15);
27838520Scracauer	/*
27931567Ssef	 * collect and verify the filesystem density info
28031567Ssef	 */
281101282Smdodd	sblock.fs_avgfilesize = avgfilesize;
28231567Ssef	sblock.fs_avgfpdir = avgfilesperdir;
28331567Ssef	if (sblock.fs_avgfilesize <= 0)
284101282Smdodd		printf("illegal expected average file size %d\n",
28531567Ssef		    sblock.fs_avgfilesize), exit(14);
28631567Ssef	if (sblock.fs_avgfpdir <= 0)
28731567Ssef		printf("illegal expected number of files per directory %d\n",
288101282Smdodd		    sblock.fs_avgfpdir), exit(15);
28931567Ssef	/*
29031567Ssef	 * collect and verify the block and fragment sizes
29131567Ssef	 */
29255707Ssef	sblock.fs_bsize = bsize;
293101282Smdodd	sblock.fs_fsize = fsize;
29455707Ssef	if (!POWEROF2(sblock.fs_bsize)) {
29555707Ssef		printf("block size must be a power of 2, not %d\n",
29655707Ssef		    sblock.fs_bsize);
29755707Ssef		exit(16);
29831567Ssef	}
299101282Smdodd	if (!POWEROF2(sblock.fs_fsize)) {
30038520Scracauer		printf("fragment size must be a power of 2, not %d\n",
30138520Scracauer		    sblock.fs_fsize);
30238520Scracauer		exit(17);
30338520Scracauer	}
30438520Scracauer	if (sblock.fs_fsize < sectorsize) {
30538520Scracauer		printf("fragment size %d is too small, minimum is %d\n",
30631567Ssef		    sblock.fs_fsize, sectorsize);
30731567Ssef		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 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 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) > 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) > 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) > 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)
504			printf("Warning: ");
505		else if (!mapcramped && !inodecramped)
506			exit(26);
507		if (mapcramped && inodecramped)
508			printf("Block size and bytes per inode restrict");
509		else if (mapcramped)
510			printf("Block size restricts");
511		else
512			printf("Bytes per inode restrict");
513		printf(" cylinders per group to %d.\n", sblock.fs_cpg);
514		if (cpgflg)
515			exit(27);
516	}
517	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
518	/*
519	 * Now have size for file system and nsect and ntrak.
520	 * Determine number of cylinders and blocks in the file system.
521	 */
522	sblock.fs_size = fssize = dbtofsb(&sblock, fssize);
523	sblock.fs_ncyl = fssize * NSPF(&sblock) / sblock.fs_spc;
524	if (fssize * NSPF(&sblock) > sblock.fs_ncyl * sblock.fs_spc) {
525		sblock.fs_ncyl++;
526		warn = 1;
527	}
528	if (sblock.fs_ncyl < 1) {
529		printf("file systems must have at least one cylinder\n");
530		exit(28);
531	}
532	/*
533	 * Determine feasability/values of rotational layout tables.
534	 *
535	 * The size of the rotational layout tables is limited by the
536	 * size of the superblock, SBSIZE. The amount of space available
537	 * for tables is calculated as (SBSIZE - sizeof (struct fs)).
538	 * The size of these tables is inversely proportional to the block
539	 * size of the file system. The size increases if sectors per track
540	 * are not powers of two, because more cylinders must be described
541	 * by the tables before the rotational pattern repeats (fs_cpc).
542	 */
543	sblock.fs_interleave = interleave;
544	sblock.fs_trackskew = trackskew;
545	sblock.fs_npsect = nphyssectors;
546	sblock.fs_postblformat = FS_DYNAMICPOSTBLFMT;
547	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
548	if (sblock.fs_sbsize > SBSIZE)
549		sblock.fs_sbsize = SBSIZE;
550	if (sblock.fs_ntrak == 1) {
551		sblock.fs_cpc = 0;
552		goto next;
553	}
554	postblsize = sblock.fs_nrpos * sblock.fs_cpc * sizeof(int16_t);
555	rotblsize = sblock.fs_cpc * sblock.fs_spc / NSPB(&sblock);
556	totalsbsize = sizeof(struct fs) + rotblsize;
557	if (sblock.fs_nrpos == 8 && sblock.fs_cpc <= 16) {
558		/* use old static table space */
559		sblock.fs_postbloff = (char *)(&sblock.fs_opostbl[0][0]) -
560		    (char *)(&sblock.fs_firstfield);
561		sblock.fs_rotbloff = &sblock.fs_space[0] -
562		    (u_char *)(&sblock.fs_firstfield);
563	} else {
564		/* use dynamic table space */
565		sblock.fs_postbloff = &sblock.fs_space[0] -
566		    (u_char *)(&sblock.fs_firstfield);
567		sblock.fs_rotbloff = sblock.fs_postbloff + postblsize;
568		totalsbsize += postblsize;
569	}
570	if (totalsbsize > SBSIZE ||
571	    sblock.fs_nsect > (1 << NBBY) * NSPB(&sblock)) {
572		printf("%s %s %d %s %d.%s",
573		    "Warning: insufficient space in super block for\n",
574		    "rotational layout tables with nsect", sblock.fs_nsect,
575		    "and ntrak", sblock.fs_ntrak,
576		    "\nFile system performance may be impaired.\n");
577		sblock.fs_cpc = 0;
578		goto next;
579	}
580	sblock.fs_sbsize = fragroundup(&sblock, totalsbsize);
581	if (sblock.fs_sbsize > SBSIZE)
582		sblock.fs_sbsize = SBSIZE;
583	/*
584	 * calculate the available blocks for each rotational position
585	 */
586	for (cylno = 0; cylno < sblock.fs_cpc; cylno++)
587		for (rpos = 0; rpos < sblock.fs_nrpos; rpos++)
588			fs_postbl(&sblock, cylno)[rpos] = -1;
589	for (i = (rotblsize - 1) * sblock.fs_frag;
590	     i >= 0; i -= sblock.fs_frag) {
591		cylno = cbtocylno(&sblock, i);
592		rpos = cbtorpos(&sblock, i);
593		blk = fragstoblks(&sblock, i);
594		if (fs_postbl(&sblock, cylno)[rpos] == -1)
595			fs_rotbl(&sblock)[blk] = 0;
596		else
597			fs_rotbl(&sblock)[blk] =
598			    fs_postbl(&sblock, cylno)[rpos] - blk;
599		fs_postbl(&sblock, cylno)[rpos] = blk;
600	}
601next:
602	/*
603	 * Compute/validate number of cylinder groups.
604	 */
605	sblock.fs_ncg = sblock.fs_ncyl / sblock.fs_cpg;
606	if (sblock.fs_ncyl % sblock.fs_cpg)
607		sblock.fs_ncg++;
608	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
609	i = MIN(~sblock.fs_cgmask, sblock.fs_ncg - 1);
610	if (cgdmin(&sblock, i) - cgbase(&sblock, i) >= sblock.fs_fpg) {
611		printf("inode blocks/cyl group (%ld) >= data blocks (%ld)\n",
612		    cgdmin(&sblock, i) - cgbase(&sblock, i) / sblock.fs_frag,
613		    (long)(sblock.fs_fpg / sblock.fs_frag));
614		printf("number of cylinders per cylinder group (%d) %s.\n",
615		    sblock.fs_cpg, "must be increased");
616		exit(29);
617	}
618	j = sblock.fs_ncg - 1;
619	if ((i = fssize - j * sblock.fs_fpg) < sblock.fs_fpg &&
620	    cgdmin(&sblock, j) - cgbase(&sblock, j) > i) {
621		if (j == 0) {
622			printf("Filesystem must have at least %d sectors\n",
623			    NSPF(&sblock) *
624			    (cgdmin(&sblock, 0) + 3 * sblock.fs_frag));
625			exit(30);
626		}
627		printf(
628"Warning: inode blocks/cyl group (%ld) >= data blocks (%ld) in last\n",
629		    (cgdmin(&sblock, j) - cgbase(&sblock, j)) / sblock.fs_frag,
630		    i / sblock.fs_frag);
631		printf(
632"    cylinder group. This implies %ld sector(s) cannot be allocated.\n",
633		    i * NSPF(&sblock));
634		sblock.fs_ncg--;
635		sblock.fs_ncyl -= sblock.fs_ncyl % sblock.fs_cpg;
636		sblock.fs_size = fssize = sblock.fs_ncyl * sblock.fs_spc /
637		    NSPF(&sblock);
638		warn = 0;
639	}
640	if (warn && !mfs) {
641		printf("Warning: %d sector(s) in last cylinder unallocated\n",
642		    sblock.fs_spc -
643		    (fssize * NSPF(&sblock) - (sblock.fs_ncyl - 1)
644		    * sblock.fs_spc));
645	}
646	/*
647	 * fill in remaining fields of the super block
648	 */
649	sblock.fs_csaddr = cgdmin(&sblock, 0);
650	sblock.fs_cssize =
651	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
652	/*
653	 * The superblock fields 'fs_csmask' and 'fs_csshift' are no
654	 * longer used. However, we still initialise them so that the
655	 * filesystem remains compatible with old kernels.
656	 */
657	i = sblock.fs_bsize / sizeof(struct csum);
658	sblock.fs_csmask = ~(i - 1);
659	for (sblock.fs_csshift = 0; i > 1; i >>= 1)
660		sblock.fs_csshift++;
661	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
662	if (fscs == NULL)
663		errx(31, "calloc failed");
664	sblock.fs_magic = FS_MAGIC;
665	sblock.fs_rotdelay = rotdelay;
666	sblock.fs_minfree = minfree;
667	sblock.fs_maxcontig = maxcontig;
668	sblock.fs_maxbpg = maxbpg;
669	sblock.fs_rps = rpm / 60;
670	sblock.fs_optim = opt;
671	sblock.fs_cgrotor = 0;
672	sblock.fs_cstotal.cs_ndir = 0;
673	sblock.fs_cstotal.cs_nbfree = 0;
674	sblock.fs_cstotal.cs_nifree = 0;
675	sblock.fs_cstotal.cs_nffree = 0;
676	sblock.fs_fmod = 0;
677	sblock.fs_ronly = 0;
678	sblock.fs_clean = 1;
679#ifdef FSIRAND
680	sblock.fs_id[0] = (long)utime;
681	sblock.fs_id[1] = random();
682#endif
683
684	/*
685	 * Dump out summary information about file system.
686	 */
687	if (!mfs) {
688		printf("%s:\t%d sectors in %d %s of %d tracks, %d sectors\n",
689		    fsys, sblock.fs_size * NSPF(&sblock), sblock.fs_ncyl,
690		    "cylinders", sblock.fs_ntrak, sblock.fs_nsect);
691#define B2MBFACTOR (1 / (1024.0 * 1024.0))
692		printf(
693		    "\t%.1fMB in %d cyl groups (%d c/g, %.2fMB/g, %d i/g)%s\n",
694		    (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
695		    sblock.fs_ncg, sblock.fs_cpg,
696		    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
697		    sblock.fs_ipg,
698		    sblock.fs_flags & FS_DOSOFTDEP ? " SOFTUPDATES" : "");
699#undef B2MBFACTOR
700	}
701	/*
702	 * Now build the cylinders group blocks and
703	 * then print out indices of cylinder groups.
704	 */
705	if (!mfs)
706		printf("super-block backups (for fsck -b #) at:\n");
707	i = 0;
708	width = charsperline();
709	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
710		initcg(cylno, utime);
711		if (mfs)
712			continue;
713		j = sprintf(tmpbuf, " %ld%s",
714		    fsbtodb(&sblock, cgsblock(&sblock, cylno)),
715		    cylno < (sblock.fs_ncg-1) ? "," : "" );
716		if (i + j >= width) {
717			printf("\n");
718			i = 0;
719		}
720		i += j;
721		printf("%s", tmpbuf);
722		fflush(stdout);
723	}
724	if (!mfs)
725		printf("\n");
726	if (Nflag && !mfs)
727		exit(0);
728	/*
729	 * Now construct the initial file system,
730	 * then write out the super-block.
731	 */
732	fsinit(utime);
733	sblock.fs_time = utime;
734	wtfs((int)SBOFF / sectorsize, sbsize, (char *)&sblock);
735	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
736		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
737			sblock.fs_cssize - i < sblock.fs_bsize ?
738			    sblock.fs_cssize - i : sblock.fs_bsize,
739			((char *)fscs) + i);
740	/*
741	 * Write out the duplicate super blocks
742	 */
743	for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
744		wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)),
745		    sbsize, (char *)&sblock);
746	wtfsflush();
747	/*
748	 * Update information about this partion in pack
749	 * label, to that it may be updated on disk.
750	 */
751	pp->p_fstype = FS_BSDFFS;
752	pp->p_fsize = sblock.fs_fsize;
753	pp->p_frag = sblock.fs_frag;
754	pp->p_cpg = sblock.fs_cpg;
755	/*
756	 * Notify parent process of success.
757	 * Dissociate from session and tty.
758	 */
759	if (mfs) {
760		kill(mfs_ppid, SIGUSR1);
761		(void) setsid();
762		(void) close(0);
763		(void) close(1);
764		(void) close(2);
765		(void) chdir("/");
766	}
767}
768
769/*
770 * Initialize a cylinder group.
771 */
772void
773initcg(cylno, utime)
774	int cylno;
775	time_t utime;
776{
777	daddr_t cbase, d, dlower, dupper, dmax, blkno;
778	long i;
779	register struct csum *cs;
780#ifdef FSIRAND
781	long j;
782#endif
783
784	/*
785	 * Determine block bounds for cylinder group.
786	 * Allow space for super block summary information in first
787	 * cylinder group.
788	 */
789	cbase = cgbase(&sblock, cylno);
790	dmax = cbase + sblock.fs_fpg;
791	if (dmax > sblock.fs_size)
792		dmax = sblock.fs_size;
793	dlower = cgsblock(&sblock, cylno) - cbase;
794	dupper = cgdmin(&sblock, cylno) - cbase;
795	if (cylno == 0)
796		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
797	cs = fscs + cylno;
798	memset(&acg, 0, sblock.fs_cgsize);
799	acg.cg_time = utime;
800	acg.cg_magic = CG_MAGIC;
801	acg.cg_cgx = cylno;
802	if (cylno == sblock.fs_ncg - 1)
803		acg.cg_ncyl = sblock.fs_ncyl % sblock.fs_cpg;
804	else
805		acg.cg_ncyl = sblock.fs_cpg;
806	acg.cg_niblk = sblock.fs_ipg;
807	acg.cg_ndblk = dmax - cbase;
808	if (sblock.fs_contigsumsize > 0)
809		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
810	acg.cg_btotoff = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
811	acg.cg_boff = acg.cg_btotoff + sblock.fs_cpg * sizeof(int32_t);
812	acg.cg_iusedoff = acg.cg_boff +
813		sblock.fs_cpg * sblock.fs_nrpos * sizeof(u_int16_t);
814	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, NBBY);
815	if (sblock.fs_contigsumsize <= 0) {
816		acg.cg_nextfreeoff = acg.cg_freeoff +
817		   howmany(sblock.fs_cpg * sblock.fs_spc / NSPF(&sblock), NBBY);
818	} else {
819		acg.cg_clustersumoff = acg.cg_freeoff + howmany
820		    (sblock.fs_cpg * sblock.fs_spc / NSPF(&sblock), NBBY) -
821		    sizeof(u_int32_t);
822		acg.cg_clustersumoff =
823		    roundup(acg.cg_clustersumoff, sizeof(u_int32_t));
824		acg.cg_clusteroff = acg.cg_clustersumoff +
825		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
826		acg.cg_nextfreeoff = acg.cg_clusteroff + howmany
827		    (sblock.fs_cpg * sblock.fs_spc / NSPB(&sblock), NBBY);
828	}
829	if (acg.cg_nextfreeoff - (long)(&acg.cg_firstfield) > sblock.fs_cgsize) {
830		printf("Panic: cylinder group too big\n");
831		exit(37);
832	}
833	acg.cg_cs.cs_nifree += sblock.fs_ipg;
834	if (cylno == 0)
835		for (i = 0; i < ROOTINO; i++) {
836			setbit(cg_inosused(&acg), i);
837			acg.cg_cs.cs_nifree--;
838		}
839	for (i = 0; i < sblock.fs_ipg / INOPF(&sblock); i += sblock.fs_frag) {
840#ifdef FSIRAND
841		for (j = 0; j < sblock.fs_bsize / sizeof(struct dinode); j++)
842			zino[j].di_gen = random();
843#endif
844		wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
845		    sblock.fs_bsize, (char *)zino);
846	}
847	if (cylno > 0) {
848		/*
849		 * In cylno 0, beginning space is reserved
850		 * for boot and super blocks.
851		 */
852		for (d = 0; d < dlower; d += sblock.fs_frag) {
853			blkno = d / sblock.fs_frag;
854			setblock(&sblock, cg_blksfree(&acg), blkno);
855			if (sblock.fs_contigsumsize > 0)
856				setbit(cg_clustersfree(&acg), blkno);
857			acg.cg_cs.cs_nbfree++;
858			cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
859			cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
860			    [cbtorpos(&sblock, d)]++;
861		}
862		sblock.fs_dsize += dlower;
863	}
864	sblock.fs_dsize += acg.cg_ndblk - dupper;
865	if ((i = dupper % sblock.fs_frag)) {
866		acg.cg_frsum[sblock.fs_frag - i]++;
867		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
868			setbit(cg_blksfree(&acg), dupper);
869			acg.cg_cs.cs_nffree++;
870		}
871	}
872	for (d = dupper; d + sblock.fs_frag <= dmax - cbase; ) {
873		blkno = d / sblock.fs_frag;
874		setblock(&sblock, cg_blksfree(&acg), blkno);
875		if (sblock.fs_contigsumsize > 0)
876			setbit(cg_clustersfree(&acg), blkno);
877		acg.cg_cs.cs_nbfree++;
878		cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
879		cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
880		    [cbtorpos(&sblock, d)]++;
881		d += sblock.fs_frag;
882	}
883	if (d < dmax - cbase) {
884		acg.cg_frsum[dmax - cbase - d]++;
885		for (; d < dmax - cbase; d++) {
886			setbit(cg_blksfree(&acg), d);
887			acg.cg_cs.cs_nffree++;
888		}
889	}
890	if (sblock.fs_contigsumsize > 0) {
891		int32_t *sump = cg_clustersum(&acg);
892		u_char *mapp = cg_clustersfree(&acg);
893		int map = *mapp++;
894		int bit = 1;
895		int run = 0;
896
897		for (i = 0; i < acg.cg_nclusterblks; i++) {
898			if ((map & bit) != 0) {
899				run++;
900			} else if (run != 0) {
901				if (run > sblock.fs_contigsumsize)
902					run = sblock.fs_contigsumsize;
903				sump[run]++;
904				run = 0;
905			}
906			if ((i & (NBBY - 1)) != (NBBY - 1)) {
907				bit <<= 1;
908			} else {
909				map = *mapp++;
910				bit = 1;
911			}
912		}
913		if (run != 0) {
914			if (run > sblock.fs_contigsumsize)
915				run = sblock.fs_contigsumsize;
916			sump[run]++;
917		}
918	}
919	sblock.fs_cstotal.cs_ndir += acg.cg_cs.cs_ndir;
920	sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
921	sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
922	sblock.fs_cstotal.cs_nifree += acg.cg_cs.cs_nifree;
923	*cs = acg.cg_cs;
924	wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
925		sblock.fs_bsize, (char *)&acg);
926}
927
928/*
929 * initialize the file system
930 */
931struct dinode node;
932
933#ifdef LOSTDIR
934#define PREDEFDIR 3
935#else
936#define PREDEFDIR 2
937#endif
938
939struct direct root_dir[] = {
940	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
941	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
942#ifdef LOSTDIR
943	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 10, "lost+found" },
944#endif
945};
946struct odirect {
947	u_long	d_ino;
948	u_short	d_reclen;
949	u_short	d_namlen;
950	u_char	d_name[MAXNAMLEN + 1];
951} oroot_dir[] = {
952	{ ROOTINO, sizeof(struct direct), 1, "." },
953	{ ROOTINO, sizeof(struct direct), 2, ".." },
954#ifdef LOSTDIR
955	{ LOSTFOUNDINO, sizeof(struct direct), 10, "lost+found" },
956#endif
957};
958#ifdef LOSTDIR
959struct direct lost_found_dir[] = {
960	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 1, "." },
961	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
962	{ 0, DIRBLKSIZ, 0, 0, 0 },
963};
964struct odirect olost_found_dir[] = {
965	{ LOSTFOUNDINO, sizeof(struct direct), 1, "." },
966	{ ROOTINO, sizeof(struct direct), 2, ".." },
967	{ 0, DIRBLKSIZ, 0, 0 },
968};
969#endif
970char buf[MAXBSIZE];
971
972void
973fsinit(utime)
974	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		(void)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		(void)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 */
1031int
1032makedir(protodir, entries)
1033	register struct direct *protodir;
1034	int entries;
1035{
1036	char *cp;
1037	int i, spcleft;
1038
1039	spcleft = DIRBLKSIZ;
1040	for (cp = buf, i = 0; i < entries - 1; i++) {
1041		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
1042		memmove(cp, &protodir[i], protodir[i].d_reclen);
1043		cp += protodir[i].d_reclen;
1044		spcleft -= protodir[i].d_reclen;
1045	}
1046	protodir[i].d_reclen = spcleft;
1047	memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
1048	return (DIRBLKSIZ);
1049}
1050
1051/*
1052 * allocate a block or frag
1053 */
1054daddr_t
1055alloc(size, mode)
1056	int size;
1057	int mode;
1058{
1059	int i, frag;
1060	daddr_t d, blkno;
1061
1062	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1063	    (char *)&acg);
1064	if (acg.cg_magic != CG_MAGIC) {
1065		printf("cg 0: bad magic number\n");
1066		return (0);
1067	}
1068	if (acg.cg_cs.cs_nbfree == 0) {
1069		printf("first cylinder group ran out of space\n");
1070		return (0);
1071	}
1072	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
1073		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
1074			goto goth;
1075	printf("internal error: can't find block in cyl 0\n");
1076	return (0);
1077goth:
1078	blkno = fragstoblks(&sblock, d);
1079	clrblock(&sblock, cg_blksfree(&acg), blkno);
1080	if (sblock.fs_contigsumsize > 0)
1081		clrbit(cg_clustersfree(&acg), blkno);
1082	acg.cg_cs.cs_nbfree--;
1083	sblock.fs_cstotal.cs_nbfree--;
1084	fscs[0].cs_nbfree--;
1085	if (mode & IFDIR) {
1086		acg.cg_cs.cs_ndir++;
1087		sblock.fs_cstotal.cs_ndir++;
1088		fscs[0].cs_ndir++;
1089	}
1090	cg_blktot(&acg)[cbtocylno(&sblock, d)]--;
1091	cg_blks(&sblock, &acg, cbtocylno(&sblock, d))[cbtorpos(&sblock, d)]--;
1092	if (size != sblock.fs_bsize) {
1093		frag = howmany(size, sblock.fs_fsize);
1094		fscs[0].cs_nffree += sblock.fs_frag - frag;
1095		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
1096		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
1097		acg.cg_frsum[sblock.fs_frag - frag]++;
1098		for (i = frag; i < sblock.fs_frag; i++)
1099			setbit(cg_blksfree(&acg), d + i);
1100	}
1101	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1102	    (char *)&acg);
1103	return (d);
1104}
1105
1106/*
1107 * Calculate number of inodes per group.
1108 */
1109long
1110calcipg(cpg, bpcg, usedbp)
1111	long cpg;
1112	long bpcg;
1113	off_t *usedbp;
1114{
1115	int i;
1116	long ipg, new_ipg, ncg, ncyl;
1117	off_t usedb;
1118
1119	/*
1120	 * Prepare to scale by fssize / (number of sectors in cylinder groups).
1121	 * Note that fssize is still in sectors, not filesystem blocks.
1122	 */
1123	ncyl = howmany(fssize, (u_int)secpercyl);
1124	ncg = howmany(ncyl, cpg);
1125	/*
1126	 * Iterate a few times to allow for ipg depending on itself.
1127	 */
1128	ipg = 0;
1129	for (i = 0; i < 10; i++) {
1130		usedb = (sblock.fs_iblkno + ipg / INOPF(&sblock))
1131			* NSPF(&sblock) * (off_t)sectorsize;
1132		new_ipg = (cpg * (quad_t)bpcg - usedb) / density * fssize
1133			  / ncg / secpercyl / cpg;
1134		new_ipg = roundup(new_ipg, INOPB(&sblock));
1135		if (new_ipg == ipg)
1136			break;
1137		ipg = new_ipg;
1138	}
1139	*usedbp = usedb;
1140	return (ipg);
1141}
1142
1143/*
1144 * Allocate an inode on the disk
1145 */
1146void
1147iput(ip, ino)
1148	register struct dinode *ip;
1149	register ino_t ino;
1150{
1151	struct dinode buf[MAXINOPB];
1152	daddr_t d;
1153	int c;
1154
1155#ifdef FSIRAND
1156	ip->di_gen = random();
1157#endif
1158	c = ino_to_cg(&sblock, ino);
1159	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1160	    (char *)&acg);
1161	if (acg.cg_magic != CG_MAGIC) {
1162		printf("cg 0: bad magic number\n");
1163		exit(31);
1164	}
1165	acg.cg_cs.cs_nifree--;
1166	setbit(cg_inosused(&acg), ino);
1167	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1168	    (char *)&acg);
1169	sblock.fs_cstotal.cs_nifree--;
1170	fscs[0].cs_nifree--;
1171	if (ino >= sblock.fs_ipg * sblock.fs_ncg) {
1172		printf("fsinit: inode value out of range (%d).\n", ino);
1173		exit(32);
1174	}
1175	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
1176	rdfs(d, sblock.fs_bsize, (char *)buf);
1177	buf[ino_to_fsbo(&sblock, ino)] = *ip;
1178	wtfs(d, sblock.fs_bsize, (char *)buf);
1179}
1180
1181/*
1182 * Notify parent process that the filesystem has created itself successfully.
1183 *
1184 * We have to wait until the mount has actually completed!
1185 */
1186void
1187started()
1188{
1189	int retry = 100;	/* 10 seconds, 100ms */
1190
1191	while (mfs_ppid && retry) {
1192		struct stat st;
1193
1194		if (
1195		    stat(mfs_mtpt, &st) < 0 ||
1196		    st.st_dev != mfs_mtstat.st_dev
1197		) {
1198			break;
1199		}
1200		usleep(100*1000);
1201		--retry;
1202	}
1203	if (retry == 0) {
1204		fatal("mfs mount failed waiting for mount to go active");
1205	}
1206	exit(0);
1207}
1208
1209#ifdef STANDALONE
1210/*
1211 * Replace libc function with one suited to our needs.
1212 */
1213caddr_t
1214malloc(size)
1215	register u_long size;
1216{
1217	char *base, *i;
1218	static u_long pgsz;
1219	struct rlimit rlp;
1220
1221	if (pgsz == 0) {
1222		base = sbrk(0);
1223		pgsz = getpagesize() - 1;
1224		i = (char *)((u_long)(base + pgsz) &~ pgsz);
1225		base = sbrk(i - base);
1226		if (getrlimit(RLIMIT_DATA, &rlp) < 0)
1227			warn("getrlimit");
1228		rlp.rlim_cur = rlp.rlim_max;
1229		if (setrlimit(RLIMIT_DATA, &rlp) < 0)
1230			warn("setrlimit");
1231		memleft = rlp.rlim_max - (u_long)base;
1232	}
1233	size = (size + pgsz) &~ pgsz;
1234	if (size > memleft)
1235		size = memleft;
1236	memleft -= size;
1237	if (size == 0)
1238		return (0);
1239	return ((caddr_t)sbrk(size));
1240}
1241
1242/*
1243 * Replace libc function with one suited to our needs.
1244 */
1245caddr_t
1246realloc(ptr, size)
1247	char *ptr;
1248	u_long size;
1249{
1250	void *p;
1251
1252	if ((p = malloc(size)) == NULL)
1253		return (NULL);
1254	memmove(p, ptr, size);
1255	free(ptr);
1256	return (p);
1257}
1258
1259/*
1260 * Replace libc function with one suited to our needs.
1261 */
1262char *
1263calloc(size, numelm)
1264	u_long size, numelm;
1265{
1266	caddr_t base;
1267
1268	size *= numelm;
1269	if ((base = malloc(size)) == NULL)
1270		return (NULL);
1271	memset(base, 0, size);
1272	return (base);
1273}
1274
1275/*
1276 * Replace libc function with one suited to our needs.
1277 */
1278void
1279free(ptr)
1280	char *ptr;
1281{
1282
1283	/* do not worry about it for now */
1284}
1285
1286#else   /* !STANDALONE */
1287
1288void
1289raise_data_limit()
1290{
1291	struct rlimit rlp;
1292
1293	if (getrlimit(RLIMIT_DATA, &rlp) < 0)
1294		warn("getrlimit");
1295	rlp.rlim_cur = rlp.rlim_max;
1296	if (setrlimit(RLIMIT_DATA, &rlp) < 0)
1297		warn("setrlimit");
1298}
1299
1300#ifdef __ELF__
1301extern char *_etext;
1302#define etext _etext
1303#else
1304extern char *etext;
1305#endif
1306
1307void
1308get_memleft()
1309{
1310	static u_long pgsz;
1311	struct rlimit rlp;
1312	u_long freestart;
1313	u_long dstart;
1314	u_long memused;
1315
1316	pgsz = getpagesize() - 1;
1317	dstart = ((u_long)&etext) &~ pgsz;
1318	freestart = ((u_long)(sbrk(0) + pgsz) &~ pgsz);
1319	if (getrlimit(RLIMIT_DATA, &rlp) < 0)
1320		warn("getrlimit");
1321	memused = freestart - dstart;
1322	memleft = rlp.rlim_cur - memused;
1323}
1324#endif  /* STANDALONE */
1325
1326/*
1327 * read a block from the file system
1328 */
1329void
1330rdfs(bno, size, bf)
1331	daddr_t bno;
1332	int size;
1333	char *bf;
1334{
1335	int n;
1336
1337	wtfsflush();
1338	if (mfs) {
1339		memmove(bf, membase + bno * sectorsize, size);
1340		return;
1341	}
1342	if (lseek(fsi, (off_t)bno * sectorsize, 0) < 0) {
1343		printf("seek error: %ld\n", (long)bno);
1344		err(33, "rdfs");
1345	}
1346	n = read(fsi, bf, size);
1347	if (n != size) {
1348		printf("read error: %ld\n", (long)bno);
1349		err(34, "rdfs");
1350	}
1351}
1352
1353#define WCSIZE (128 * 1024)
1354daddr_t wc_sect;		/* units of sectorsize */
1355int wc_end;			/* bytes */
1356static char wc[WCSIZE];		/* bytes */
1357
1358/*
1359 * Flush dirty write behind buffer.
1360 */
1361void
1362wtfsflush()
1363{
1364	int n;
1365	if (wc_end) {
1366		if (lseek(fso, (off_t)wc_sect * sectorsize, SEEK_SET) < 0) {
1367			printf("seek error: %ld\n", (long)wc_sect);
1368			err(35, "wtfs - writecombine");
1369		}
1370		n = write(fso, wc, wc_end);
1371		if (n != wc_end) {
1372			printf("write error: %ld\n", (long)wc_sect);
1373			err(36, "wtfs - writecombine");
1374		}
1375		wc_end = 0;
1376	}
1377}
1378
1379/*
1380 * write a block to the file system
1381 */
1382void
1383wtfs(bno, size, bf)
1384	daddr_t bno;
1385	int size;
1386	char *bf;
1387{
1388	int n;
1389	int done;
1390
1391	if (mfs) {
1392		memmove(membase + bno * sectorsize, bf, size);
1393		return;
1394	}
1395	if (Nflag)
1396		return;
1397	done = 0;
1398	if (wc_end == 0 && size <= WCSIZE) {
1399		wc_sect = bno;
1400		bcopy(bf, wc, size);
1401		wc_end = size;
1402		if (wc_end < WCSIZE)
1403			return;
1404		done = 1;
1405	}
1406	if ((off_t)wc_sect * sectorsize + wc_end == (off_t)bno * sectorsize &&
1407	    wc_end + size <= WCSIZE) {
1408		bcopy(bf, wc + wc_end, size);
1409		wc_end += size;
1410		if (wc_end < WCSIZE)
1411			return;
1412		done = 1;
1413	}
1414	wtfsflush();
1415	if (done)
1416		return;
1417	if (lseek(fso, (off_t)bno * sectorsize, SEEK_SET) < 0) {
1418		printf("seek error: %ld\n", (long)bno);
1419		err(35, "wtfs");
1420	}
1421	n = write(fso, bf, size);
1422	if (n != size) {
1423		printf("write error: %ld\n", (long)bno);
1424		err(36, "wtfs");
1425	}
1426}
1427
1428/*
1429 * check if a block is available
1430 */
1431int
1432isblock(fs, cp, h)
1433	struct fs *fs;
1434	unsigned char *cp;
1435	int h;
1436{
1437	unsigned char mask;
1438
1439	switch (fs->fs_frag) {
1440	case 8:
1441		return (cp[h] == 0xff);
1442	case 4:
1443		mask = 0x0f << ((h & 0x1) << 2);
1444		return ((cp[h >> 1] & mask) == mask);
1445	case 2:
1446		mask = 0x03 << ((h & 0x3) << 1);
1447		return ((cp[h >> 2] & mask) == mask);
1448	case 1:
1449		mask = 0x01 << (h & 0x7);
1450		return ((cp[h >> 3] & mask) == mask);
1451	default:
1452#ifdef STANDALONE
1453		printf("isblock bad fs_frag %d\n", fs->fs_frag);
1454#else
1455		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
1456#endif
1457		return (0);
1458	}
1459}
1460
1461/*
1462 * take a block out of the map
1463 */
1464void
1465clrblock(fs, cp, h)
1466	struct fs *fs;
1467	unsigned char *cp;
1468	int h;
1469{
1470	switch ((fs)->fs_frag) {
1471	case 8:
1472		cp[h] = 0;
1473		return;
1474	case 4:
1475		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1476		return;
1477	case 2:
1478		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1479		return;
1480	case 1:
1481		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1482		return;
1483	default:
1484#ifdef STANDALONE
1485		printf("clrblock bad fs_frag %d\n", fs->fs_frag);
1486#else
1487		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
1488#endif
1489		return;
1490	}
1491}
1492
1493/*
1494 * put a block into the map
1495 */
1496void
1497setblock(fs, cp, h)
1498	struct fs *fs;
1499	unsigned char *cp;
1500	int h;
1501{
1502	switch (fs->fs_frag) {
1503	case 8:
1504		cp[h] = 0xff;
1505		return;
1506	case 4:
1507		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1508		return;
1509	case 2:
1510		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1511		return;
1512	case 1:
1513		cp[h >> 3] |= (0x01 << (h & 0x7));
1514		return;
1515	default:
1516#ifdef STANDALONE
1517		printf("setblock bad fs_frag %d\n", fs->fs_frag);
1518#else
1519		fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
1520#endif
1521		return;
1522	}
1523}
1524
1525/*
1526 * Determine the number of characters in a
1527 * single line.
1528 */
1529
1530static int
1531charsperline()
1532{
1533	int columns;
1534	char *cp;
1535	struct winsize ws;
1536
1537	columns = 0;
1538	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1539		columns = ws.ws_col;
1540	if (columns == 0 && (cp = getenv("COLUMNS")))
1541		columns = atoi(cp);
1542	if (columns == 0)
1543		columns = 80;	/* last resort */
1544	return columns;
1545}
1546