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