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