mkfs.c revision 98649
1/*
2 * Copyright (c) 2002 Networks Associates Technology, Inc.
3 * All rights reserved.
4 *
5 * This software was developed for the FreeBSD Project by Marshall
6 * Kirk McKusick and Network Associates Laboratories, the Security
7 * Research Division of Network Associates, Inc. under DARPA/SPAWAR
8 * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
9 * research program
10 *
11 * Copyright (c) 1982, 1989, 1993
12 *	The Regents of the University of California.  All rights reserved.
13 * (c) UNIX System Laboratories, Inc.
14 * Copyright (c) 1980, 1989, 1993
15 *	The Regents of the University of California.  All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 *    notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 *    notice, this list of conditions and the following disclaimer in the
24 *    documentation and/or other materials provided with the distribution.
25 * 3. All advertising materials mentioning features or use of this software
26 *    must display the following acknowledgement:
27 *	This product includes software developed by the University of
28 *	California, Berkeley and its contributors.
29 * 4. Neither the name of the University nor the names of its contributors
30 *    may be used to endorse or promote products derived from this software
31 *    without specific prior written permission.
32 *
33 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 * SUCH DAMAGE.
44 */
45
46#ifndef lint
47#if 0
48static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
49#endif
50static const char rcsid[] =
51  "$FreeBSD: head/sbin/newfs/mkfs.c 98649 2002-06-22 22:44:09Z mckusick $";
52#endif /* not lint */
53
54#include <err.h>
55#include <signal.h>
56#include <stdlib.h>
57#include <string.h>
58#include <stdio.h>
59#include <unistd.h>
60#include <sys/param.h>
61#include <sys/time.h>
62#include <sys/types.h>
63#include <sys/wait.h>
64#include <sys/resource.h>
65#include <sys/stat.h>
66#include <ufs/ufs/dinode.h>
67#include <ufs/ufs/dir.h>
68#include <ufs/ffs/fs.h>
69#include <sys/disklabel.h>
70#include <sys/file.h>
71#include <sys/mman.h>
72#include <sys/ioctl.h>
73#include "newfs.h"
74
75/*
76 * make filesystem for cylinder-group style filesystems
77 */
78#define UMASK		0755
79#define POWEROF2(num)	(((num) & ((num) - 1)) == 0)
80
81static union {
82	struct fs fs;
83	char pad[SBLOCKSIZE];
84} fsun;
85#define	sblock	fsun.fs
86static struct	csum *fscs;
87
88static union {
89	struct cg cg;
90	char pad[MAXBSIZE];
91} cgun;
92#define	acg	cgun.cg
93
94union dinode {
95	struct ufs1_dinode dp1;
96	struct ufs2_dinode dp2;
97};
98#define DIP(dp, field) \
99	((sblock.fs_magic == FS_UFS1_MAGIC) ? \
100	(dp)->dp1.field : (dp)->dp2.field)
101
102static int randinit;
103static caddr_t iobuf;
104static long iobufsize;
105static ufs2_daddr_t alloc(int size, int mode);
106static int charsperline(void);
107static void clrblock(struct fs *, unsigned char *, int);
108static void fsinit(time_t);
109static int ilog2(int);
110static void initcg(int, time_t);
111static int isblock(struct fs *, unsigned char *, int);
112static void iput(union dinode *, ino_t);
113static int makedir(struct direct *, int);
114static void rdfs(ufs2_daddr_t, int, char *);
115static void setblock(struct fs *, unsigned char *, int);
116static void wtfs(ufs2_daddr_t, int, char *);
117static void wtfsflush(void);
118
119void
120mkfs(struct partition *pp, char *fsys)
121{
122	int fragsperinode, optimalfpg, origdensity, minfpg, lastminfpg;
123	long i, j, cylno, csfrags;
124	time_t utime;
125	quad_t sizepb;
126	int width;
127	char tmpbuf[100];	/* XXX this will break in about 2,500 years */
128
129	if (Rflag)
130		utime = 1000000000;
131	else
132		time(&utime);
133	if (!Rflag && !randinit) {
134		randinit = 1;
135		srandomdev();
136	}
137	/*
138	 * allocate space for superblock, cylinder group map, and
139	 * two sets of inode blocks.
140	 */
141	if (bsize < SBLOCKSIZE)
142		iobufsize = SBLOCKSIZE + 3 * bsize;
143	else
144		iobufsize = 4 * bsize;
145	if ((iobuf = malloc(iobufsize)) == 0) {
146		printf("Cannot allocate I/O buffer\n");
147		exit(38);
148	}
149	bzero(iobuf, iobufsize);
150	sblock.fs_flags = 0;
151	if (Uflag)
152		sblock.fs_flags |= FS_DOSOFTDEP;
153	/*
154	 * Validate the given filesystem size.
155	 * Verify that its last block can actually be accessed.
156	 * Convert to filesystem fragment sized units.
157	 */
158	if (fssize <= 0) {
159		printf("preposterous size %qd\n", fssize);
160		exit(13);
161	}
162	wtfs(fssize - (realsectorsize / DEV_BSIZE), realsectorsize,
163	    (char *)&sblock);
164	/*
165	 * collect and verify the filesystem density info
166	 */
167	sblock.fs_avgfilesize = avgfilesize;
168	sblock.fs_avgfpdir = avgfilesperdir;
169	if (sblock.fs_avgfilesize <= 0)
170		printf("illegal expected average file size %d\n",
171		    sblock.fs_avgfilesize), exit(14);
172	if (sblock.fs_avgfpdir <= 0)
173		printf("illegal expected number of files per directory %d\n",
174		    sblock.fs_avgfpdir), exit(15);
175	/*
176	 * collect and verify the block and fragment sizes
177	 */
178	sblock.fs_bsize = bsize;
179	sblock.fs_fsize = fsize;
180	if (!POWEROF2(sblock.fs_bsize)) {
181		printf("block size must be a power of 2, not %d\n",
182		    sblock.fs_bsize);
183		exit(16);
184	}
185	if (!POWEROF2(sblock.fs_fsize)) {
186		printf("fragment size must be a power of 2, not %d\n",
187		    sblock.fs_fsize);
188		exit(17);
189	}
190	if (sblock.fs_fsize < sectorsize) {
191		printf("increasing fragment size from %d to sector size (%d)\n",
192		    sblock.fs_fsize, sectorsize);
193		sblock.fs_fsize = sectorsize;
194	}
195	if (sblock.fs_bsize < MINBSIZE) {
196		printf("increasing block size from %d to minimum (%d)\n",
197		    sblock.fs_bsize, MINBSIZE);
198		sblock.fs_bsize = MINBSIZE;
199	}
200	if (sblock.fs_bsize < sblock.fs_fsize) {
201		printf("increasing block size from %d to fragment size (%d)\n",
202		    sblock.fs_bsize, sblock.fs_fsize);
203		sblock.fs_bsize = sblock.fs_fsize;
204	}
205	if (sblock.fs_fsize * MAXFRAG < sblock.fs_bsize) {
206		printf(
207		"increasing fragment size from %d to block size / %d (%d)\n",
208		    sblock.fs_fsize, MAXFRAG, sblock.fs_bsize / MAXFRAG);
209		sblock.fs_fsize = sblock.fs_bsize / MAXFRAG;
210	}
211	if (maxbsize < bsize || !POWEROF2(maxbsize)) {
212		sblock.fs_maxbsize = sblock.fs_bsize;
213		printf("Extent size set to %d\n", sblock.fs_maxbsize);
214	} else if (sblock.fs_maxbsize > FS_MAXCONTIG * sblock.fs_bsize) {
215		sblock.fs_maxbsize = FS_MAXCONTIG * sblock.fs_bsize;
216		printf("Extent size reduced to %d\n", sblock.fs_maxbsize);
217	} else {
218		sblock.fs_maxbsize = maxbsize;
219	}
220	sblock.fs_maxcontig = maxcontig;
221	if (sblock.fs_maxcontig < sblock.fs_maxbsize / sblock.fs_bsize) {
222		sblock.fs_maxcontig = sblock.fs_maxbsize / sblock.fs_bsize;
223		printf("Maxcontig raised to %d\n", sblock.fs_maxbsize);
224	}
225	if (sblock.fs_maxcontig > 1)
226		sblock.fs_contigsumsize = MIN(sblock.fs_maxcontig,FS_MAXCONTIG);
227	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
228	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
229	sblock.fs_qbmask = ~sblock.fs_bmask;
230	sblock.fs_qfmask = ~sblock.fs_fmask;
231	sblock.fs_bshift = ilog2(sblock.fs_bsize);
232	sblock.fs_fshift = ilog2(sblock.fs_fsize);
233	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
234	sblock.fs_fragshift = ilog2(sblock.fs_frag);
235	if (sblock.fs_frag > MAXFRAG) {
236		printf("fragment size %d is still too small (can't happen)\n",
237		    sblock.fs_bsize / MAXFRAG);
238		exit(21);
239	}
240	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / sectorsize);
241	sblock.fs_size = fssize = dbtofsb(&sblock, fssize);
242	if (Oflag == 1) {
243		sblock.fs_magic = FS_UFS1_MAGIC;
244		sblock.fs_sblockloc = numfrags(&sblock, SBLOCK_UFS1);
245		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs1_daddr_t);
246		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
247		sblock.fs_maxsymlinklen = ((NDADDR + NIADDR) *
248		    sizeof(ufs1_daddr_t));
249		sblock.fs_old_inodefmt = FS_44INODEFMT;
250		sblock.fs_old_cgoffset = 0;
251		sblock.fs_old_cgmask = 0xffffffff;
252		sblock.fs_old_size = sblock.fs_size;
253		sblock.fs_old_rotdelay = 0;
254		sblock.fs_old_rps = 60;
255		sblock.fs_old_nspf = sblock.fs_fsize / sectorsize;
256		sblock.fs_old_cpg = 1;
257		sblock.fs_old_interleave = 1;
258		sblock.fs_old_trackskew = 0;
259		sblock.fs_old_cpc = 0;
260		sblock.fs_old_postblformat = 1;
261		sblock.fs_old_nrpos = 1;
262	} else {
263		sblock.fs_magic = FS_UFS2_MAGIC;
264		sblock.fs_sblockloc = numfrags(&sblock, SBLOCK_UFS2);
265		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs2_daddr_t);
266		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
267		sblock.fs_maxsymlinklen = ((NDADDR + NIADDR) *
268		    sizeof(ufs2_daddr_t));
269	}
270	sblock.fs_sblkno =
271	    roundup(howmany(lfragtosize(&sblock, sblock.fs_sblockloc) +
272		SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag);
273	sblock.fs_cblkno = sblock.fs_sblkno +
274	    roundup(howmany(SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag);
275	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
276	sblock.fs_maxfilesize = sblock.fs_bsize * NDADDR - 1;
277	for (sizepb = sblock.fs_bsize, i = 0; i < NIADDR; i++) {
278		sizepb *= NINDIR(&sblock);
279		sblock.fs_maxfilesize += sizepb;
280	}
281	/*
282	 * Calculate the number of blocks to put into each cylinder group.
283	 *
284	 * This algorithm selects the number of blocks per cylinder
285	 * group. The first goal is to have at least enough data blocks
286	 * in each cylinder group to meet the density requirement. Once
287	 * this goal is achieved we try to expand to have at least
288	 * MINCYLGRPS cylinder groups. Once this goal is achieved, we
289	 * pack as many blocks into each cylinder group map as will fit.
290	 *
291	 * We start by calculating the smallest number of blocks that we
292	 * can put into each cylinder group. If this is too big, we reduce
293	 * the density until it fits.
294	 */
295	origdensity = density;
296	for (;;) {
297		fragsperinode = numfrags(&sblock, density);
298		minfpg = fragsperinode * INOPB(&sblock);
299		if (minfpg > sblock.fs_size)
300			minfpg = sblock.fs_size;
301		sblock.fs_ipg = INOPB(&sblock);
302		sblock.fs_fpg = roundup(sblock.fs_iblkno +
303		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
304		if (sblock.fs_fpg < minfpg)
305			sblock.fs_fpg = minfpg;
306		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
307		    INOPB(&sblock));
308		sblock.fs_fpg = roundup(sblock.fs_iblkno +
309		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
310		if (sblock.fs_fpg < minfpg)
311			sblock.fs_fpg = minfpg;
312		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
313		    INOPB(&sblock));
314		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
315			break;
316		density -= sblock.fs_fsize;
317	}
318	if (density != origdensity)
319		printf("density reduced from %d to %d\n", origdensity, density);
320	/*
321	 * Start packing more blocks into the cylinder group until
322	 * it cannot grow any larger, the number of cylinder groups
323	 * drops below MINCYLGRPS, or we reach the size requested.
324	 */
325	for ( ; sblock.fs_fpg < maxblkspercg; sblock.fs_fpg += sblock.fs_frag) {
326		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
327		    INOPB(&sblock));
328		if (sblock.fs_size / sblock.fs_fpg < MINCYLGRPS)
329			break;
330		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
331			continue;
332		if (CGSIZE(&sblock) == (unsigned long)sblock.fs_bsize)
333			break;
334		sblock.fs_fpg -= sblock.fs_frag;
335		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
336		    INOPB(&sblock));
337		break;
338	}
339	/*
340	 * Check to be sure that the last cylinder group has enough blocks
341	 * to be viable. If it is too small, reduce the number of blocks
342	 * per cylinder group which will have the effect of moving more
343	 * blocks into the last cylinder group.
344	 */
345	optimalfpg = sblock.fs_fpg;
346	for (;;) {
347		sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
348		lastminfpg = roundup(sblock.fs_iblkno +
349		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
350		if (sblock.fs_size < lastminfpg) {
351			printf("Filesystem size %qd < minimum size of %d\n",
352				sblock.fs_size, lastminfpg);
353			exit(28);
354		}
355		if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
356		    sblock.fs_size % sblock.fs_fpg == 0)
357			break;
358		sblock.fs_fpg -= sblock.fs_frag;
359		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
360		    INOPB(&sblock));
361	}
362	if (optimalfpg != sblock.fs_fpg)
363		printf("Reduced frags per cylinder group from %d to %d %s\n",
364		   optimalfpg, sblock.fs_fpg, "to enlarge last cyl group");
365	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
366	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
367	if (Oflag == 1) {
368		sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
369		sblock.fs_old_nsect = sblock.fs_old_spc;
370		sblock.fs_old_npsect = sblock.fs_old_spc;
371		sblock.fs_old_ncyl = sblock.fs_ncg;
372	}
373	/*
374	 * fill in remaining fields of the super block
375	 */
376	sblock.fs_csaddr = cgdmin(&sblock, 0);
377	sblock.fs_cssize =
378	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
379	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
380	if (fscs == NULL)
381		errx(31, "calloc failed");
382	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
383	sblock.fs_minfree = minfree;
384	sblock.fs_maxbpg = maxbpg;
385	sblock.fs_optim = opt;
386	sblock.fs_cgrotor = 0;
387	sblock.fs_pendingblocks = 0;
388	sblock.fs_pendinginodes = 0;
389	sblock.fs_fmod = 0;
390	sblock.fs_ronly = 0;
391	sblock.fs_state = 0;
392	sblock.fs_clean = 1;
393	sblock.fs_id[0] = (long)utime;
394	sblock.fs_id[1] = random();
395	sblock.fs_fsmnt[0] = '\0';
396	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
397	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
398	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
399	sblock.fs_cstotal.cs_nbfree =
400	    fragstoblks(&sblock, sblock.fs_dsize) -
401	    howmany(csfrags, sblock.fs_frag);
402	sblock.fs_cstotal.cs_nffree =
403	    fragnum(&sblock, sblock.fs_size) +
404	    (csfrags > 0 ? sblock.fs_frag - csfrags : 0);
405	sblock.fs_cstotal.cs_nifree = sblock.fs_ncg * sblock.fs_ipg - ROOTINO;
406	sblock.fs_cstotal.cs_ndir = 0;
407	sblock.fs_dsize -= csfrags;
408	sblock.fs_time = utime;
409	if (Oflag == 1) {
410		sblock.fs_old_time = utime;
411		sblock.fs_old_dsize = sblock.fs_dsize;
412		sblock.fs_old_csaddr = sblock.fs_csaddr;
413		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
414		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
415		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
416		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
417	}
418
419	/*
420	 * Dump out summary information about filesystem.
421	 */
422#	define B2MBFACTOR (1 / (1024.0 * 1024.0))
423	printf("%s: %.1fMB (%qd sectors) block size %d, fragment size %d\n",
424	    fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
425	    fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize, sblock.fs_fsize);
426	printf("\tusing %d cylinder groups of %.2fMB, %d blks, %d inodes.\n",
427	    sblock.fs_ncg, (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
428	    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
429	if (sblock.fs_flags & FS_DOSOFTDEP)
430		printf("\twith soft updates\n");
431#	undef B2MBFACTOR
432	/*
433	 * Now build the cylinders group blocks and
434	 * then print out indices of cylinder groups.
435	 */
436	printf("super-block backups (for fsck -b #) at:\n");
437	i = 0;
438	width = charsperline();
439	/*
440	 * Make a copy of the superblock into the buffer that we will be
441	 * writing out in each cylinder group.
442	 */
443	bcopy((char *)&sblock, iobuf, SBLOCKSIZE);
444	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
445		initcg(cylno, utime);
446		j = snprintf(tmpbuf, sizeof(tmpbuf), " %qd%s",
447		    fsbtodb(&sblock, cgsblock(&sblock, cylno)),
448		    cylno < (sblock.fs_ncg-1) ? "," : "");
449		if (j < 0)
450			tmpbuf[j = 0] = '\0';
451		if (i + j >= width) {
452			printf("\n");
453			i = 0;
454		}
455		i += j;
456		printf("%s", tmpbuf);
457		fflush(stdout);
458	}
459	printf("\n");
460	if (Nflag)
461		exit(0);
462	/*
463	 * Now construct the initial filesystem,
464	 * then write out the super-block.
465	 */
466	fsinit(utime);
467	if (Oflag == 1) {
468		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
469		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
470		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
471		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
472	}
473	wtfs(lfragtosize(&sblock, sblock.fs_sblockloc) / sectorsize,
474	    SBLOCKSIZE, (char *)&sblock);
475	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
476		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
477			sblock.fs_cssize - i < sblock.fs_bsize ?
478			sblock.fs_cssize - i : sblock.fs_bsize,
479			((char *)fscs) + i);
480	wtfsflush();
481	/*
482	 * Update information about this partion in pack
483	 * label, to that it may be updated on disk.
484	 */
485	if (pp != NULL) {
486		pp->p_fstype = FS_BSDFFS;
487		pp->p_fsize = sblock.fs_fsize;
488		pp->p_frag = sblock.fs_frag;
489		pp->p_cpg = sblock.fs_fpg;
490	}
491}
492
493/*
494 * Initialize a cylinder group.
495 */
496void
497initcg(int cylno, time_t utime)
498{
499	long i, j, d, dlower, dupper, blkno, start;
500	ufs2_daddr_t cbase, dmax;
501	struct ufs1_dinode *dp1;
502	struct ufs2_dinode *dp2;
503	struct csum *cs;
504
505	/*
506	 * Determine block bounds for cylinder group.
507	 * Allow space for super block summary information in first
508	 * cylinder group.
509	 */
510	cbase = cgbase(&sblock, cylno);
511	dmax = cbase + sblock.fs_fpg;
512	if (dmax > sblock.fs_size)
513		dmax = sblock.fs_size;
514	dlower = cgsblock(&sblock, cylno) - cbase;
515	dupper = cgdmin(&sblock, cylno) - cbase;
516	if (cylno == 0)
517		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
518	cs = &fscs[cylno];
519	memset(&acg, 0, sblock.fs_cgsize);
520	acg.cg_time = utime;
521	acg.cg_magic = CG_MAGIC;
522	acg.cg_cgx = cylno;
523	acg.cg_niblk = sblock.fs_ipg;
524	acg.cg_initediblk = sblock.fs_ipg < 2 * INOPB(&sblock) ?
525	    sblock.fs_ipg : 2 * INOPB(&sblock);
526	acg.cg_ndblk = dmax - cbase;
527	if (sblock.fs_contigsumsize > 0)
528		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
529	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
530	if (Oflag == 2) {
531		acg.cg_iusedoff = start;
532	} else {
533		acg.cg_old_ncyl = sblock.fs_old_cpg;
534		acg.cg_old_time = acg.cg_time;
535		acg.cg_time = 0;
536		acg.cg_old_niblk = acg.cg_niblk;
537		acg.cg_niblk = 0;
538		acg.cg_initediblk = 0;
539		acg.cg_old_btotoff = start;
540		acg.cg_old_boff = acg.cg_old_btotoff +
541		    sblock.fs_old_cpg * sizeof(int32_t);
542		acg.cg_iusedoff = acg.cg_old_boff +
543		    sblock.fs_old_cpg * sizeof(u_int16_t);
544	}
545	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, NBBY);
546	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, NBBY);
547	if (sblock.fs_contigsumsize > 0) {
548		acg.cg_clustersumoff =
549		    roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
550		acg.cg_clustersumoff -= sizeof(u_int32_t);
551		acg.cg_clusteroff = acg.cg_clustersumoff +
552		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
553		acg.cg_nextfreeoff = acg.cg_clusteroff +
554		    howmany(fragstoblks(&sblock, sblock.fs_fpg), NBBY);
555	}
556	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
557		printf("Panic: cylinder group too big\n");
558		exit(37);
559	}
560	acg.cg_cs.cs_nifree += sblock.fs_ipg;
561	if (cylno == 0)
562		for (i = 0; i < (long)ROOTINO; i++) {
563			setbit(cg_inosused(&acg), i);
564			acg.cg_cs.cs_nifree--;
565		}
566	if (cylno > 0) {
567		/*
568		 * In cylno 0, beginning space is reserved
569		 * for boot and super blocks.
570		 */
571		for (d = 0; d < dlower; d += sblock.fs_frag) {
572			blkno = d / sblock.fs_frag;
573			setblock(&sblock, cg_blksfree(&acg), blkno);
574			if (sblock.fs_contigsumsize > 0)
575				setbit(cg_clustersfree(&acg), blkno);
576			acg.cg_cs.cs_nbfree++;
577		}
578	}
579	if ((i = dupper % sblock.fs_frag)) {
580		acg.cg_frsum[sblock.fs_frag - i]++;
581		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
582			setbit(cg_blksfree(&acg), dupper);
583			acg.cg_cs.cs_nffree++;
584		}
585	}
586	for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
587	     d += sblock.fs_frag) {
588		blkno = d / sblock.fs_frag;
589		setblock(&sblock, cg_blksfree(&acg), blkno);
590		if (sblock.fs_contigsumsize > 0)
591			setbit(cg_clustersfree(&acg), blkno);
592		acg.cg_cs.cs_nbfree++;
593	}
594	if (d < acg.cg_ndblk) {
595		acg.cg_frsum[acg.cg_ndblk - d]++;
596		for (; d < acg.cg_ndblk; d++) {
597			setbit(cg_blksfree(&acg), d);
598			acg.cg_cs.cs_nffree++;
599		}
600	}
601	if (sblock.fs_contigsumsize > 0) {
602		int32_t *sump = cg_clustersum(&acg);
603		u_char *mapp = cg_clustersfree(&acg);
604		int map = *mapp++;
605		int bit = 1;
606		int run = 0;
607
608		for (i = 0; i < acg.cg_nclusterblks; i++) {
609			if ((map & bit) != 0)
610				run++;
611			else if (run != 0) {
612				if (run > sblock.fs_contigsumsize)
613					run = sblock.fs_contigsumsize;
614				sump[run]++;
615				run = 0;
616			}
617			if ((i & (NBBY - 1)) != NBBY - 1)
618				bit <<= 1;
619			else {
620				map = *mapp++;
621				bit = 1;
622			}
623		}
624		if (run != 0) {
625			if (run > sblock.fs_contigsumsize)
626				run = sblock.fs_contigsumsize;
627			sump[run]++;
628		}
629	}
630	*cs = acg.cg_cs;
631	/*
632	 * Write out the duplicate super block, the cylinder group map
633	 * and two blocks worth of inodes in a single write.
634	 */
635	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
636	bcopy((char *)&acg, &iobuf[start], sblock.fs_cgsize);
637	start += sblock.fs_bsize;
638	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
639	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
640	for (i = 0; i < acg.cg_initediblk; i++) {
641		if (sblock.fs_magic == FS_UFS1_MAGIC) {
642			dp1->di_gen = random();
643			dp1++;
644		} else {
645			dp2->di_gen = random();
646			dp2++;
647		}
648	}
649	wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);
650	/*
651	 * For the old filesystem, we have to initialize all the inodes.
652	 */
653	if (Oflag == 1) {
654		for (i = 2 * sblock.fs_frag;
655		     i < sblock.fs_ipg / INOPF(&sblock);
656		     i += sblock.fs_frag) {
657			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
658			for (j = 0; j < INOPB(&sblock); j++) {
659				dp1->di_gen = random();
660				dp1++;
661			}
662			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
663			    sblock.fs_bsize, &iobuf[start]);
664		}
665	}
666}
667
668/*
669 * initialize the filesystem
670 */
671#define PREDEFDIR 2
672
673struct direct root_dir[] = {
674	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
675	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
676};
677
678void
679fsinit(time_t utime)
680{
681	union dinode node;
682
683	memset(&node, 0, sizeof node);
684	if (sblock.fs_magic == FS_UFS1_MAGIC) {
685		/*
686		 * initialize the node
687		 */
688		node.dp1.di_atime = utime;
689		node.dp1.di_mtime = utime;
690		node.dp1.di_ctime = utime;
691		/*
692		 * create the root directory
693		 */
694		node.dp1.di_mode = IFDIR | UMASK;
695		node.dp1.di_nlink = PREDEFDIR;
696		node.dp1.di_size = makedir(root_dir, PREDEFDIR);
697		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
698		node.dp1.di_blocks =
699		    btodb(fragroundup(&sblock, node.dp1.di_size));
700		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize,
701		    iobuf);
702	} else {
703		/*
704		 * initialize the node
705		 */
706		node.dp2.di_atime = utime;
707		node.dp2.di_mtime = utime;
708		node.dp2.di_ctime = utime;
709		node.dp2.di_createtime = utime;
710		/*
711		 * create the root directory
712		 */
713		node.dp2.di_mode = IFDIR | UMASK;
714		node.dp2.di_nlink = PREDEFDIR;
715		node.dp2.di_size = makedir(root_dir, PREDEFDIR);
716		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
717		node.dp2.di_blocks =
718		    btodb(fragroundup(&sblock, node.dp2.di_size));
719		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize,
720		    iobuf);
721	}
722	iput(&node, ROOTINO);
723}
724
725/*
726 * construct a set of directory entries in "iobuf".
727 * return size of directory.
728 */
729int
730makedir(struct direct *protodir, int entries)
731{
732	char *cp;
733	int i, spcleft;
734
735	spcleft = DIRBLKSIZ;
736	memset(iobuf, 0, DIRBLKSIZ);
737	for (cp = iobuf, i = 0; i < entries - 1; i++) {
738		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
739		memmove(cp, &protodir[i], protodir[i].d_reclen);
740		cp += protodir[i].d_reclen;
741		spcleft -= protodir[i].d_reclen;
742	}
743	protodir[i].d_reclen = spcleft;
744	memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
745	return (DIRBLKSIZ);
746}
747
748/*
749 * allocate a block or frag
750 */
751ufs2_daddr_t
752alloc(int size, int mode)
753{
754	int i, d, blkno, frag;
755
756	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
757	    (char *)&acg);
758	if (acg.cg_magic != CG_MAGIC) {
759		printf("cg 0: bad magic number\n");
760		return (0);
761	}
762	if (acg.cg_cs.cs_nbfree == 0) {
763		printf("first cylinder group ran out of space\n");
764		return (0);
765	}
766	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
767		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
768			goto goth;
769	printf("internal error: can't find block in cyl 0\n");
770	return (0);
771goth:
772	blkno = fragstoblks(&sblock, d);
773	clrblock(&sblock, cg_blksfree(&acg), blkno);
774	if (sblock.fs_contigsumsize > 0)
775		clrbit(cg_clustersfree(&acg), blkno);
776	acg.cg_cs.cs_nbfree--;
777	sblock.fs_cstotal.cs_nbfree--;
778	fscs[0].cs_nbfree--;
779	if (mode & IFDIR) {
780		acg.cg_cs.cs_ndir++;
781		sblock.fs_cstotal.cs_ndir++;
782		fscs[0].cs_ndir++;
783	}
784	if (size != sblock.fs_bsize) {
785		frag = howmany(size, sblock.fs_fsize);
786		fscs[0].cs_nffree += sblock.fs_frag - frag;
787		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
788		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
789		acg.cg_frsum[sblock.fs_frag - frag]++;
790		for (i = frag; i < sblock.fs_frag; i++)
791			setbit(cg_blksfree(&acg), d + i);
792	}
793	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
794	    (char *)&acg);
795	return ((ufs2_daddr_t)d);
796}
797
798/*
799 * Allocate an inode on the disk
800 */
801void
802iput(union dinode *ip, ino_t ino)
803{
804	ufs2_daddr_t d;
805	int c;
806
807	c = ino_to_cg(&sblock, ino);
808	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
809	    (char *)&acg);
810	if (acg.cg_magic != CG_MAGIC) {
811		printf("cg 0: bad magic number\n");
812		exit(31);
813	}
814	acg.cg_cs.cs_nifree--;
815	setbit(cg_inosused(&acg), ino);
816	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
817	    (char *)&acg);
818	sblock.fs_cstotal.cs_nifree--;
819	fscs[0].cs_nifree--;
820	if (ino >= (unsigned long)sblock.fs_ipg * sblock.fs_ncg) {
821		printf("fsinit: inode value out of range (%d).\n", ino);
822		exit(32);
823	}
824	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
825	rdfs(d, sblock.fs_bsize, (char *)iobuf);
826	if (sblock.fs_magic == FS_UFS1_MAGIC)
827		((struct ufs1_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
828		    ip->dp1;
829	else
830		((struct ufs2_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
831		    ip->dp2;
832	wtfs(d, sblock.fs_bsize, (char *)iobuf);
833}
834
835/*
836 * read a block from the filesystem
837 */
838void
839rdfs(ufs2_daddr_t bno, int size, char *bf)
840{
841	int n;
842
843	wtfsflush();
844	if (lseek(fso, (off_t)bno * sectorsize, 0) < 0) {
845		printf("seek error: %ld\n", (long)bno);
846		err(33, "rdfs");
847	}
848	n = read(fso, bf, size);
849	if (n != size) {
850		printf("read error: %ld\n", (long)bno);
851		err(34, "rdfs");
852	}
853}
854
855#define WCSIZE (128 * 1024)
856ufs2_daddr_t wc_sect;		/* units of sectorsize */
857int wc_end;			/* bytes */
858static char wc[WCSIZE];		/* bytes */
859
860/*
861 * Flush dirty write behind buffer.
862 */
863static void
864wtfsflush()
865{
866	int n;
867	if (wc_end) {
868		if (lseek(fso, (off_t)wc_sect * sectorsize, SEEK_SET) < 0) {
869			printf("seek error: %ld\n", (long)wc_sect);
870			err(35, "wtfs - writecombine");
871		}
872		n = write(fso, wc, wc_end);
873		if (n != wc_end) {
874			printf("write error: %ld\n", (long)wc_sect);
875			err(36, "wtfs - writecombine");
876		}
877		wc_end = 0;
878	}
879}
880
881/*
882 * write a block to the filesystem
883 */
884static void
885wtfs(ufs2_daddr_t bno, int size, char *bf)
886{
887	int done, n;
888
889	if (Nflag)
890		return;
891	done = 0;
892	if (wc_end == 0 && size <= WCSIZE) {
893		wc_sect = bno;
894		bcopy(bf, wc, size);
895		wc_end = size;
896		if (wc_end < WCSIZE)
897			return;
898		done = 1;
899	}
900	if ((off_t)wc_sect * sectorsize + wc_end == (off_t)bno * sectorsize &&
901	    wc_end + size <= WCSIZE) {
902		bcopy(bf, wc + wc_end, size);
903		wc_end += size;
904		if (wc_end < WCSIZE)
905			return;
906		done = 1;
907	}
908	wtfsflush();
909	if (done)
910		return;
911	if (lseek(fso, (off_t)bno * sectorsize, SEEK_SET) < 0) {
912		printf("seek error: %ld\n", (long)bno);
913		err(35, "wtfs");
914	}
915	n = write(fso, bf, size);
916	if (n != size) {
917		printf("write error: %ld\n", (long)bno);
918		err(36, "wtfs");
919	}
920}
921
922/*
923 * check if a block is available
924 */
925static int
926isblock(struct fs *fs, unsigned char *cp, int h)
927{
928	unsigned char mask;
929
930	switch (fs->fs_frag) {
931	case 8:
932		return (cp[h] == 0xff);
933	case 4:
934		mask = 0x0f << ((h & 0x1) << 2);
935		return ((cp[h >> 1] & mask) == mask);
936	case 2:
937		mask = 0x03 << ((h & 0x3) << 1);
938		return ((cp[h >> 2] & mask) == mask);
939	case 1:
940		mask = 0x01 << (h & 0x7);
941		return ((cp[h >> 3] & mask) == mask);
942	default:
943		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
944		return (0);
945	}
946}
947
948/*
949 * take a block out of the map
950 */
951static void
952clrblock(struct fs *fs, unsigned char *cp, int h)
953{
954	switch ((fs)->fs_frag) {
955	case 8:
956		cp[h] = 0;
957		return;
958	case 4:
959		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
960		return;
961	case 2:
962		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
963		return;
964	case 1:
965		cp[h >> 3] &= ~(0x01 << (h & 0x7));
966		return;
967	default:
968		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
969		return;
970	}
971}
972
973/*
974 * put a block into the map
975 */
976static void
977setblock(struct fs *fs, unsigned char *cp, int h)
978{
979	switch (fs->fs_frag) {
980	case 8:
981		cp[h] = 0xff;
982		return;
983	case 4:
984		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
985		return;
986	case 2:
987		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
988		return;
989	case 1:
990		cp[h >> 3] |= (0x01 << (h & 0x7));
991		return;
992	default:
993		fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
994		return;
995	}
996}
997
998/*
999 * Determine the number of characters in a
1000 * single line.
1001 */
1002
1003static int
1004charsperline(void)
1005{
1006	int columns;
1007	char *cp;
1008	struct winsize ws;
1009
1010	columns = 0;
1011	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1012		columns = ws.ws_col;
1013	if (columns == 0 && (cp = getenv("COLUMNS")))
1014		columns = atoi(cp);
1015	if (columns == 0)
1016		columns = 80;	/* last resort */
1017	return (columns);
1018}
1019
1020static int
1021ilog2(int val)
1022{
1023	u_int n;
1024
1025	for (n = 0; n < sizeof(n) * NBBY; n++)
1026		if (1 << n == val)
1027			return (n);
1028	errx(1, "ilog2: %d is not a power of 2\n", val);
1029}
1030