xref: /freebsd/sbin/newfs/mkfs.c (revision 6af83ee0d2941d18880b6aaa2b4facd1d30c6106)
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
41 static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
42 #endif /* not lint */
43 #endif
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
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 
77 static struct	csum *fscs;
78 #define	sblock	disk.d_fs
79 #define	acg	disk.d_cg
80 
81 union 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 
89 static caddr_t iobuf;
90 static long iobufsize;
91 static ufs2_daddr_t alloc(int size, int mode);
92 static int charsperline(void);
93 static void clrblock(struct fs *, unsigned char *, int);
94 static void fsinit(time_t);
95 static int ilog2(int);
96 static void initcg(int, time_t);
97 static int isblock(struct fs *, unsigned char *, int);
98 static void iput(union dinode *, ino_t);
99 static int makedir(struct direct *, int);
100 static void setblock(struct fs *, unsigned char *, int);
101 static void wtfs(ufs2_daddr_t, int, char *);
102 static u_int32_t newfs_random(void);
103 
104 void
105 mkfs(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 
240 	/*
241 	 * Before the filesystem is finally initialized, mark it
242 	 * as incompletely initialized.
243 	 */
244 	sblock.fs_magic = FS_BAD_MAGIC;
245 
246 	if (Oflag == 1) {
247 		sblock.fs_sblockloc = SBLOCK_UFS1;
248 		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs1_daddr_t);
249 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
250 		sblock.fs_maxsymlinklen = ((NDADDR + NIADDR) *
251 		    sizeof(ufs1_daddr_t));
252 		sblock.fs_old_inodefmt = FS_44INODEFMT;
253 		sblock.fs_old_cgoffset = 0;
254 		sblock.fs_old_cgmask = 0xffffffff;
255 		sblock.fs_old_size = sblock.fs_size;
256 		sblock.fs_old_rotdelay = 0;
257 		sblock.fs_old_rps = 60;
258 		sblock.fs_old_nspf = sblock.fs_fsize / sectorsize;
259 		sblock.fs_old_cpg = 1;
260 		sblock.fs_old_interleave = 1;
261 		sblock.fs_old_trackskew = 0;
262 		sblock.fs_old_cpc = 0;
263 		sblock.fs_old_postblformat = 1;
264 		sblock.fs_old_nrpos = 1;
265 	} else {
266 		sblock.fs_sblockloc = SBLOCK_UFS2;
267 		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs2_daddr_t);
268 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
269 		sblock.fs_maxsymlinklen = ((NDADDR + NIADDR) *
270 		    sizeof(ufs2_daddr_t));
271 	}
272 	sblock.fs_sblkno =
273 	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
274 		sblock.fs_frag);
275 	sblock.fs_cblkno = sblock.fs_sblkno +
276 	    roundup(howmany(SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag);
277 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
278 	sblock.fs_maxfilesize = sblock.fs_bsize * NDADDR - 1;
279 	for (sizepb = sblock.fs_bsize, i = 0; i < NIADDR; i++) {
280 		sizepb *= NINDIR(&sblock);
281 		sblock.fs_maxfilesize += sizepb;
282 	}
283 	/*
284 	 * Calculate the number of blocks to put into each cylinder group.
285 	 *
286 	 * This algorithm selects the number of blocks per cylinder
287 	 * group. The first goal is to have at least enough data blocks
288 	 * in each cylinder group to meet the density requirement. Once
289 	 * this goal is achieved we try to expand to have at least
290 	 * MINCYLGRPS cylinder groups. Once this goal is achieved, we
291 	 * pack as many blocks into each cylinder group map as will fit.
292 	 *
293 	 * We start by calculating the smallest number of blocks that we
294 	 * can put into each cylinder group. If this is too big, we reduce
295 	 * the density until it fits.
296 	 */
297 	origdensity = density;
298 	for (;;) {
299 		fragsperinode = MAX(numfrags(&sblock, density), 1);
300 		minfpg = fragsperinode * INOPB(&sblock);
301 		if (minfpg > sblock.fs_size)
302 			minfpg = sblock.fs_size;
303 		sblock.fs_ipg = INOPB(&sblock);
304 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
305 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
306 		if (sblock.fs_fpg < minfpg)
307 			sblock.fs_fpg = minfpg;
308 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
309 		    INOPB(&sblock));
310 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
311 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
312 		if (sblock.fs_fpg < minfpg)
313 			sblock.fs_fpg = minfpg;
314 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
315 		    INOPB(&sblock));
316 		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
317 			break;
318 		density -= sblock.fs_fsize;
319 	}
320 	if (density != origdensity)
321 		printf("density reduced from %d to %d\n", origdensity, density);
322 	/*
323 	 * Start packing more blocks into the cylinder group until
324 	 * it cannot grow any larger, the number of cylinder groups
325 	 * drops below MINCYLGRPS, or we reach the size requested.
326 	 */
327 	for ( ; sblock.fs_fpg < maxblkspercg; sblock.fs_fpg += sblock.fs_frag) {
328 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
329 		    INOPB(&sblock));
330 		if (sblock.fs_size / sblock.fs_fpg < MINCYLGRPS)
331 			break;
332 		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
333 			continue;
334 		if (CGSIZE(&sblock) == (unsigned long)sblock.fs_bsize)
335 			break;
336 		sblock.fs_fpg -= sblock.fs_frag;
337 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
338 		    INOPB(&sblock));
339 		break;
340 	}
341 	/*
342 	 * Check to be sure that the last cylinder group has enough blocks
343 	 * to be viable. If it is too small, reduce the number of blocks
344 	 * per cylinder group which will have the effect of moving more
345 	 * blocks into the last cylinder group.
346 	 */
347 	optimalfpg = sblock.fs_fpg;
348 	for (;;) {
349 		sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
350 		lastminfpg = roundup(sblock.fs_iblkno +
351 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
352 		if (sblock.fs_size < lastminfpg) {
353 			printf("Filesystem size %jd < minimum size of %d\n",
354 			    (intmax_t)sblock.fs_size, lastminfpg);
355 			exit(28);
356 		}
357 		if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
358 		    sblock.fs_size % sblock.fs_fpg == 0)
359 			break;
360 		sblock.fs_fpg -= sblock.fs_frag;
361 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
362 		    INOPB(&sblock));
363 	}
364 	if (optimalfpg != sblock.fs_fpg)
365 		printf("Reduced frags per cylinder group from %d to %d %s\n",
366 		   optimalfpg, sblock.fs_fpg, "to enlarge last cyl group");
367 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
368 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
369 	if (Oflag == 1) {
370 		sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
371 		sblock.fs_old_nsect = sblock.fs_old_spc;
372 		sblock.fs_old_npsect = sblock.fs_old_spc;
373 		sblock.fs_old_ncyl = sblock.fs_ncg;
374 	}
375 	/*
376 	 * fill in remaining fields of the super block
377 	 */
378 	sblock.fs_csaddr = cgdmin(&sblock, 0);
379 	sblock.fs_cssize =
380 	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
381 	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
382 	if (fscs == NULL)
383 		errx(31, "calloc failed");
384 	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
385 	if (sblock.fs_sbsize > SBLOCKSIZE)
386 		sblock.fs_sbsize = SBLOCKSIZE;
387 	sblock.fs_minfree = minfree;
388 	sblock.fs_maxbpg = maxbpg;
389 	sblock.fs_optim = opt;
390 	sblock.fs_cgrotor = 0;
391 	sblock.fs_pendingblocks = 0;
392 	sblock.fs_pendinginodes = 0;
393 	sblock.fs_fmod = 0;
394 	sblock.fs_ronly = 0;
395 	sblock.fs_state = 0;
396 	sblock.fs_clean = 1;
397 	sblock.fs_id[0] = (long)utime;
398 	sblock.fs_id[1] = newfs_random();
399 	sblock.fs_fsmnt[0] = '\0';
400 	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
401 	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
402 	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
403 	sblock.fs_cstotal.cs_nbfree =
404 	    fragstoblks(&sblock, sblock.fs_dsize) -
405 	    howmany(csfrags, sblock.fs_frag);
406 	sblock.fs_cstotal.cs_nffree =
407 	    fragnum(&sblock, sblock.fs_size) +
408 	    (fragnum(&sblock, csfrags) > 0 ?
409 	     sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
410 	sblock.fs_cstotal.cs_nifree = sblock.fs_ncg * sblock.fs_ipg - ROOTINO;
411 	sblock.fs_cstotal.cs_ndir = 0;
412 	sblock.fs_dsize -= csfrags;
413 	sblock.fs_time = utime;
414 	if (Oflag == 1) {
415 		sblock.fs_old_time = utime;
416 		sblock.fs_old_dsize = sblock.fs_dsize;
417 		sblock.fs_old_csaddr = sblock.fs_csaddr;
418 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
419 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
420 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
421 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
422 	}
423 
424 	/*
425 	 * Dump out summary information about file system.
426 	 */
427 #	define B2MBFACTOR (1 / (1024.0 * 1024.0))
428 	printf("%s: %.1fMB (%jd sectors) block size %d, fragment size %d\n",
429 	    fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
430 	    (intmax_t)fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize,
431 	    sblock.fs_fsize);
432 	printf("\tusing %d cylinder groups of %.2fMB, %d blks, %d inodes.\n",
433 	    sblock.fs_ncg, (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
434 	    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
435 	if (sblock.fs_flags & FS_DOSOFTDEP)
436 		printf("\twith soft updates\n");
437 #	undef B2MBFACTOR
438 
439 	/*
440 	 * Wipe out old UFS1 superblock(s) if necessary.
441 	 */
442 	if (!Nflag && Oflag != 1) {
443 		i = bread(&disk, SBLOCK_UFS1 / disk.d_bsize, chdummy, SBLOCKSIZE);
444 		if (i == -1)
445 			err(1, "can't read old UFS1 superblock: %s", disk.d_error);
446 
447 		if (fsdummy.fs_magic == FS_UFS1_MAGIC) {
448 			fsdummy.fs_magic = 0;
449 			bwrite(&disk, SBLOCK_UFS1 / disk.d_bsize, chdummy, SBLOCKSIZE);
450 			for (i = 0; i < fsdummy.fs_ncg; i++)
451 				bwrite(&disk, fsbtodb(&fsdummy, cgsblock(&fsdummy, i)),
452 	                    chdummy, SBLOCKSIZE);
453 		}
454 	}
455 	if (!Nflag)
456 		sbwrite(&disk, 0);
457 	if (Eflag == 1) {
458 		printf("** Exiting on Eflag 1\n");
459 		exit(0);
460 	}
461 	if (Eflag == 2)
462 		printf("** Leaving BAD MAGIC on Eflag 2\n");
463 	else
464 		sblock.fs_magic = (Oflag != 1) ? FS_UFS2_MAGIC : FS_UFS1_MAGIC;
465 
466 	/*
467 	 * Now build the cylinders group blocks and
468 	 * then print out indices of cylinder groups.
469 	 */
470 	printf("super-block backups (for fsck -b #) at:\n");
471 	i = 0;
472 	width = charsperline();
473 	/*
474 	 * allocate space for superblock, cylinder group map, and
475 	 * two sets of inode blocks.
476 	 */
477 	if (sblock.fs_bsize < SBLOCKSIZE)
478 		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
479 	else
480 		iobufsize = 4 * sblock.fs_bsize;
481 	if ((iobuf = malloc(iobufsize)) == 0) {
482 		printf("Cannot allocate I/O buffer\n");
483 		exit(38);
484 	}
485 	bzero(iobuf, iobufsize);
486 	/*
487 	 * Make a copy of the superblock into the buffer that we will be
488 	 * writing out in each cylinder group.
489 	 */
490 	bcopy((char *)&sblock, iobuf, SBLOCKSIZE);
491 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
492 		initcg(cylno, utime);
493 		j = snprintf(tmpbuf, sizeof(tmpbuf), " %jd%s",
494 		    (intmax_t)fsbtodb(&sblock, cgsblock(&sblock, cylno)),
495 		    cylno < (sblock.fs_ncg-1) ? "," : "");
496 		if (j < 0)
497 			tmpbuf[j = 0] = '\0';
498 		if (i + j >= width) {
499 			printf("\n");
500 			i = 0;
501 		}
502 		i += j;
503 		printf("%s", tmpbuf);
504 		fflush(stdout);
505 	}
506 	printf("\n");
507 	if (Nflag)
508 		exit(0);
509 	/*
510 	 * Now construct the initial file system,
511 	 * then write out the super-block.
512 	 */
513 	fsinit(utime);
514 	if (Oflag == 1) {
515 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
516 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
517 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
518 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
519 	}
520 	if (Eflag == 3) {
521 		printf("** Exiting on Eflag 3\n");
522 		exit(0);
523 	}
524 	if (!Nflag)
525 		sbwrite(&disk, 0);
526 	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
527 		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
528 			sblock.fs_cssize - i < sblock.fs_bsize ?
529 			sblock.fs_cssize - i : sblock.fs_bsize,
530 			((char *)fscs) + i);
531 	/*
532 	 * Update information about this partion in pack
533 	 * label, to that it may be updated on disk.
534 	 */
535 	if (pp != NULL) {
536 		pp->p_fstype = FS_BSDFFS;
537 		pp->p_fsize = sblock.fs_fsize;
538 		pp->p_frag = sblock.fs_frag;
539 		pp->p_cpg = sblock.fs_fpg;
540 	}
541 }
542 
543 /*
544  * Initialize a cylinder group.
545  */
546 void
547 initcg(int cylno, time_t utime)
548 {
549 	long i, j, d, dlower, dupper, blkno, start;
550 	ufs2_daddr_t cbase, dmax;
551 	struct ufs1_dinode *dp1;
552 	struct ufs2_dinode *dp2;
553 	struct csum *cs;
554 
555 	/*
556 	 * Determine block bounds for cylinder group.
557 	 * Allow space for super block summary information in first
558 	 * cylinder group.
559 	 */
560 	cbase = cgbase(&sblock, cylno);
561 	dmax = cbase + sblock.fs_fpg;
562 	if (dmax > sblock.fs_size)
563 		dmax = sblock.fs_size;
564 	dlower = cgsblock(&sblock, cylno) - cbase;
565 	dupper = cgdmin(&sblock, cylno) - cbase;
566 	if (cylno == 0)
567 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
568 	cs = &fscs[cylno];
569 	memset(&acg, 0, sblock.fs_cgsize);
570 	acg.cg_time = utime;
571 	acg.cg_magic = CG_MAGIC;
572 	acg.cg_cgx = cylno;
573 	acg.cg_niblk = sblock.fs_ipg;
574 	acg.cg_initediblk = sblock.fs_ipg < 2 * INOPB(&sblock) ?
575 	    sblock.fs_ipg : 2 * INOPB(&sblock);
576 	acg.cg_ndblk = dmax - cbase;
577 	if (sblock.fs_contigsumsize > 0)
578 		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
579 	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
580 	if (Oflag == 2) {
581 		acg.cg_iusedoff = start;
582 	} else {
583 		acg.cg_old_ncyl = sblock.fs_old_cpg;
584 		acg.cg_old_time = acg.cg_time;
585 		acg.cg_time = 0;
586 		acg.cg_old_niblk = acg.cg_niblk;
587 		acg.cg_niblk = 0;
588 		acg.cg_initediblk = 0;
589 		acg.cg_old_btotoff = start;
590 		acg.cg_old_boff = acg.cg_old_btotoff +
591 		    sblock.fs_old_cpg * sizeof(int32_t);
592 		acg.cg_iusedoff = acg.cg_old_boff +
593 		    sblock.fs_old_cpg * sizeof(u_int16_t);
594 	}
595 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
596 	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
597 	if (sblock.fs_contigsumsize > 0) {
598 		acg.cg_clustersumoff =
599 		    roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
600 		acg.cg_clustersumoff -= sizeof(u_int32_t);
601 		acg.cg_clusteroff = acg.cg_clustersumoff +
602 		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
603 		acg.cg_nextfreeoff = acg.cg_clusteroff +
604 		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
605 	}
606 	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
607 		printf("Panic: cylinder group too big\n");
608 		exit(37);
609 	}
610 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
611 	if (cylno == 0)
612 		for (i = 0; i < (long)ROOTINO; i++) {
613 			setbit(cg_inosused(&acg), i);
614 			acg.cg_cs.cs_nifree--;
615 		}
616 	if (cylno > 0) {
617 		/*
618 		 * In cylno 0, beginning space is reserved
619 		 * for boot and super blocks.
620 		 */
621 		for (d = 0; d < dlower; d += sblock.fs_frag) {
622 			blkno = d / sblock.fs_frag;
623 			setblock(&sblock, cg_blksfree(&acg), blkno);
624 			if (sblock.fs_contigsumsize > 0)
625 				setbit(cg_clustersfree(&acg), blkno);
626 			acg.cg_cs.cs_nbfree++;
627 		}
628 	}
629 	if ((i = dupper % sblock.fs_frag)) {
630 		acg.cg_frsum[sblock.fs_frag - i]++;
631 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
632 			setbit(cg_blksfree(&acg), dupper);
633 			acg.cg_cs.cs_nffree++;
634 		}
635 	}
636 	for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
637 	     d += sblock.fs_frag) {
638 		blkno = d / sblock.fs_frag;
639 		setblock(&sblock, cg_blksfree(&acg), blkno);
640 		if (sblock.fs_contigsumsize > 0)
641 			setbit(cg_clustersfree(&acg), blkno);
642 		acg.cg_cs.cs_nbfree++;
643 	}
644 	if (d < acg.cg_ndblk) {
645 		acg.cg_frsum[acg.cg_ndblk - d]++;
646 		for (; d < acg.cg_ndblk; d++) {
647 			setbit(cg_blksfree(&acg), d);
648 			acg.cg_cs.cs_nffree++;
649 		}
650 	}
651 	if (sblock.fs_contigsumsize > 0) {
652 		int32_t *sump = cg_clustersum(&acg);
653 		u_char *mapp = cg_clustersfree(&acg);
654 		int map = *mapp++;
655 		int bit = 1;
656 		int run = 0;
657 
658 		for (i = 0; i < acg.cg_nclusterblks; i++) {
659 			if ((map & bit) != 0)
660 				run++;
661 			else if (run != 0) {
662 				if (run > sblock.fs_contigsumsize)
663 					run = sblock.fs_contigsumsize;
664 				sump[run]++;
665 				run = 0;
666 			}
667 			if ((i & (CHAR_BIT - 1)) != CHAR_BIT - 1)
668 				bit <<= 1;
669 			else {
670 				map = *mapp++;
671 				bit = 1;
672 			}
673 		}
674 		if (run != 0) {
675 			if (run > sblock.fs_contigsumsize)
676 				run = sblock.fs_contigsumsize;
677 			sump[run]++;
678 		}
679 	}
680 	*cs = acg.cg_cs;
681 	/*
682 	 * Write out the duplicate super block, the cylinder group map
683 	 * and two blocks worth of inodes in a single write.
684 	 */
685 	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
686 	bcopy((char *)&acg, &iobuf[start], sblock.fs_cgsize);
687 	start += sblock.fs_bsize;
688 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
689 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
690 	for (i = 0; i < acg.cg_initediblk; i++) {
691 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
692 			dp1->di_gen = newfs_random();
693 			dp1++;
694 		} else {
695 			dp2->di_gen = newfs_random();
696 			dp2++;
697 		}
698 	}
699 	wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);
700 	/*
701 	 * For the old file system, we have to initialize all the inodes.
702 	 */
703 	if (Oflag == 1) {
704 		for (i = 2 * sblock.fs_frag;
705 		     i < sblock.fs_ipg / INOPF(&sblock);
706 		     i += sblock.fs_frag) {
707 			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
708 			for (j = 0; j < INOPB(&sblock); j++) {
709 				dp1->di_gen = newfs_random();
710 				dp1++;
711 			}
712 			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
713 			    sblock.fs_bsize, &iobuf[start]);
714 		}
715 	}
716 }
717 
718 /*
719  * initialize the file system
720  */
721 #define ROOTLINKCNT 3
722 
723 struct direct root_dir[] = {
724 	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
725 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
726 	{ ROOTINO + 1, sizeof(struct direct), DT_DIR, 5, ".snap" },
727 };
728 
729 #define SNAPLINKCNT 2
730 
731 struct direct snap_dir[] = {
732 	{ ROOTINO + 1, sizeof(struct direct), DT_DIR, 1, "." },
733 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
734 };
735 
736 void
737 fsinit(time_t utime)
738 {
739 	union dinode node;
740 	struct group *grp;
741 	int entries;
742 
743 	memset(&node, 0, sizeof node);
744 	if ((grp = getgrnam("operator")) == NULL)
745 		errx(35, "Cannot retrieve operator gid");
746 	entries = (nflag) ? ROOTLINKCNT - 1: ROOTLINKCNT;
747 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
748 		/*
749 		 * initialize the node
750 		 */
751 		node.dp1.di_atime = utime;
752 		node.dp1.di_mtime = utime;
753 		node.dp1.di_ctime = utime;
754 		/*
755 		 * create the root directory
756 		 */
757 		node.dp1.di_mode = IFDIR | UMASK;
758 		node.dp1.di_nlink = entries;
759 		node.dp1.di_size = makedir(root_dir, entries);
760 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
761 		node.dp1.di_blocks =
762 		    btodb(fragroundup(&sblock, node.dp1.di_size));
763 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize,
764 		    iobuf);
765 		iput(&node, ROOTINO);
766 		if (!nflag) {
767 			/*
768 			 * create the .snap directory
769 			 */
770 			node.dp1.di_mode |= 020;
771 			node.dp1.di_gid = grp->gr_gid;
772 			node.dp1.di_nlink = SNAPLINKCNT;
773 			node.dp1.di_size = makedir(snap_dir, SNAPLINKCNT);
774 				node.dp1.di_db[0] =
775 				    alloc(sblock.fs_fsize, node.dp1.di_mode);
776 			node.dp1.di_blocks =
777 			    btodb(fragroundup(&sblock, node.dp1.di_size));
778 				wtfs(fsbtodb(&sblock, node.dp1.di_db[0]),
779 				    sblock.fs_fsize, iobuf);
780 			iput(&node, ROOTINO + 1);
781 		}
782 	} else {
783 		/*
784 		 * initialize the node
785 		 */
786 		node.dp2.di_atime = utime;
787 		node.dp2.di_mtime = utime;
788 		node.dp2.di_ctime = utime;
789 		node.dp2.di_birthtime = utime;
790 		/*
791 		 * create the root directory
792 		 */
793 		node.dp2.di_mode = IFDIR | UMASK;
794 		node.dp2.di_nlink = entries;
795 		node.dp2.di_size = makedir(root_dir, entries);
796 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
797 		node.dp2.di_blocks =
798 		    btodb(fragroundup(&sblock, node.dp2.di_size));
799 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize,
800 		    iobuf);
801 		iput(&node, ROOTINO);
802 		if (!nflag) {
803 			/*
804 			 * create the .snap directory
805 			 */
806 			node.dp2.di_mode |= 020;
807 			node.dp2.di_gid = grp->gr_gid;
808 			node.dp2.di_nlink = SNAPLINKCNT;
809 			node.dp2.di_size = makedir(snap_dir, SNAPLINKCNT);
810 				node.dp2.di_db[0] =
811 				    alloc(sblock.fs_fsize, node.dp2.di_mode);
812 			node.dp2.di_blocks =
813 			    btodb(fragroundup(&sblock, node.dp2.di_size));
814 				wtfs(fsbtodb(&sblock, node.dp2.di_db[0]),
815 				    sblock.fs_fsize, iobuf);
816 			iput(&node, ROOTINO + 1);
817 		}
818 	}
819 }
820 
821 /*
822  * construct a set of directory entries in "iobuf".
823  * return size of directory.
824  */
825 int
826 makedir(struct direct *protodir, int entries)
827 {
828 	char *cp;
829 	int i, spcleft;
830 
831 	spcleft = DIRBLKSIZ;
832 	memset(iobuf, 0, DIRBLKSIZ);
833 	for (cp = iobuf, i = 0; i < entries - 1; i++) {
834 		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
835 		memmove(cp, &protodir[i], protodir[i].d_reclen);
836 		cp += protodir[i].d_reclen;
837 		spcleft -= protodir[i].d_reclen;
838 	}
839 	protodir[i].d_reclen = spcleft;
840 	memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
841 	return (DIRBLKSIZ);
842 }
843 
844 /*
845  * allocate a block or frag
846  */
847 ufs2_daddr_t
848 alloc(int size, int mode)
849 {
850 	int i, d, blkno, frag;
851 
852 	bread(&disk, fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
853 	    sblock.fs_cgsize);
854 	if (acg.cg_magic != CG_MAGIC) {
855 		printf("cg 0: bad magic number\n");
856 		exit(38);
857 	}
858 	if (acg.cg_cs.cs_nbfree == 0) {
859 		printf("first cylinder group ran out of space\n");
860 		exit(39);
861 	}
862 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
863 		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
864 			goto goth;
865 	printf("internal error: can't find block in cyl 0\n");
866 	exit(40);
867 goth:
868 	blkno = fragstoblks(&sblock, d);
869 	clrblock(&sblock, cg_blksfree(&acg), blkno);
870 	if (sblock.fs_contigsumsize > 0)
871 		clrbit(cg_clustersfree(&acg), blkno);
872 	acg.cg_cs.cs_nbfree--;
873 	sblock.fs_cstotal.cs_nbfree--;
874 	fscs[0].cs_nbfree--;
875 	if (mode & IFDIR) {
876 		acg.cg_cs.cs_ndir++;
877 		sblock.fs_cstotal.cs_ndir++;
878 		fscs[0].cs_ndir++;
879 	}
880 	if (size != sblock.fs_bsize) {
881 		frag = howmany(size, sblock.fs_fsize);
882 		fscs[0].cs_nffree += sblock.fs_frag - frag;
883 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
884 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
885 		acg.cg_frsum[sblock.fs_frag - frag]++;
886 		for (i = frag; i < sblock.fs_frag; i++)
887 			setbit(cg_blksfree(&acg), d + i);
888 	}
889 	/* XXX cgwrite(&disk, 0)??? */
890 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
891 	    (char *)&acg);
892 	return ((ufs2_daddr_t)d);
893 }
894 
895 /*
896  * Allocate an inode on the disk
897  */
898 void
899 iput(union dinode *ip, ino_t ino)
900 {
901 	ufs2_daddr_t d;
902 	int c;
903 
904 	c = ino_to_cg(&sblock, ino);
905 	bread(&disk, fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
906 	    sblock.fs_cgsize);
907 	if (acg.cg_magic != CG_MAGIC) {
908 		printf("cg 0: bad magic number\n");
909 		exit(31);
910 	}
911 	acg.cg_cs.cs_nifree--;
912 	setbit(cg_inosused(&acg), ino);
913 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
914 	    (char *)&acg);
915 	sblock.fs_cstotal.cs_nifree--;
916 	fscs[0].cs_nifree--;
917 	if (ino >= (unsigned long)sblock.fs_ipg * sblock.fs_ncg) {
918 		printf("fsinit: inode value out of range (%d).\n", ino);
919 		exit(32);
920 	}
921 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
922 	bread(&disk, d, (char *)iobuf, sblock.fs_bsize);
923 	if (sblock.fs_magic == FS_UFS1_MAGIC)
924 		((struct ufs1_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
925 		    ip->dp1;
926 	else
927 		((struct ufs2_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
928 		    ip->dp2;
929 	wtfs(d, sblock.fs_bsize, (char *)iobuf);
930 }
931 
932 /*
933  * possibly write to disk
934  */
935 static void
936 wtfs(ufs2_daddr_t bno, int size, char *bf)
937 {
938 	if (Nflag)
939 		return;
940 	if (bwrite(&disk, bno, bf, size) < 0)
941 		err(36, "wtfs: %d bytes at sector %jd", size, (intmax_t)bno);
942 }
943 
944 /*
945  * check if a block is available
946  */
947 static int
948 isblock(struct fs *fs, unsigned char *cp, int h)
949 {
950 	unsigned char mask;
951 
952 	switch (fs->fs_frag) {
953 	case 8:
954 		return (cp[h] == 0xff);
955 	case 4:
956 		mask = 0x0f << ((h & 0x1) << 2);
957 		return ((cp[h >> 1] & mask) == mask);
958 	case 2:
959 		mask = 0x03 << ((h & 0x3) << 1);
960 		return ((cp[h >> 2] & mask) == mask);
961 	case 1:
962 		mask = 0x01 << (h & 0x7);
963 		return ((cp[h >> 3] & mask) == mask);
964 	default:
965 		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
966 		return (0);
967 	}
968 }
969 
970 /*
971  * take a block out of the map
972  */
973 static void
974 clrblock(struct fs *fs, unsigned char *cp, int h)
975 {
976 	switch ((fs)->fs_frag) {
977 	case 8:
978 		cp[h] = 0;
979 		return;
980 	case 4:
981 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
982 		return;
983 	case 2:
984 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
985 		return;
986 	case 1:
987 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
988 		return;
989 	default:
990 		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
991 		return;
992 	}
993 }
994 
995 /*
996  * put a block into the map
997  */
998 static void
999 setblock(struct fs *fs, unsigned char *cp, int h)
1000 {
1001 	switch (fs->fs_frag) {
1002 	case 8:
1003 		cp[h] = 0xff;
1004 		return;
1005 	case 4:
1006 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1007 		return;
1008 	case 2:
1009 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1010 		return;
1011 	case 1:
1012 		cp[h >> 3] |= (0x01 << (h & 0x7));
1013 		return;
1014 	default:
1015 		fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
1016 		return;
1017 	}
1018 }
1019 
1020 /*
1021  * Determine the number of characters in a
1022  * single line.
1023  */
1024 
1025 static int
1026 charsperline(void)
1027 {
1028 	int columns;
1029 	char *cp;
1030 	struct winsize ws;
1031 
1032 	columns = 0;
1033 	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1034 		columns = ws.ws_col;
1035 	if (columns == 0 && (cp = getenv("COLUMNS")))
1036 		columns = atoi(cp);
1037 	if (columns == 0)
1038 		columns = 80;	/* last resort */
1039 	return (columns);
1040 }
1041 
1042 static int
1043 ilog2(int val)
1044 {
1045 	u_int n;
1046 
1047 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
1048 		if (1 << n == val)
1049 			return (n);
1050 	errx(1, "ilog2: %d is not a power of 2\n", val);
1051 }
1052 
1053 /*
1054  * For the regression test, return predictable random values.
1055  * Otherwise use a true random number generator.
1056  */
1057 static u_int32_t
1058 newfs_random(void)
1059 {
1060 	static int nextnum = 1;
1061 
1062 	if (Rflag)
1063 		return (nextnum++);
1064 	return (arc4random());
1065 }
1066