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