xref: /freebsd/sbin/newfs/mkfs.c (revision 7773002178c8dbc52b44e4d705f07706409af8e4)
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_UFS2_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 
453 	/*
454 	 * Now build the cylinders group blocks and
455 	 * then print out indices of cylinder groups.
456 	 */
457 	printf("super-block backups (for fsck -b #) at:\n");
458 	i = 0;
459 	width = charsperline();
460 	/*
461 	 * allocate space for superblock, cylinder group map, and
462 	 * two sets of inode blocks.
463 	 */
464 	if (sblock.fs_bsize < SBLOCKSIZE)
465 		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
466 	else
467 		iobufsize = 4 * sblock.fs_bsize;
468 	if ((iobuf = malloc(iobufsize)) == 0) {
469 		printf("Cannot allocate I/O buffer\n");
470 		exit(38);
471 	}
472 	bzero(iobuf, iobufsize);
473 	/*
474 	 * Make a copy of the superblock into the buffer that we will be
475 	 * writing out in each cylinder group.
476 	 */
477 	bcopy((char *)&sblock, iobuf, SBLOCKSIZE);
478 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
479 		initcg(cylno, utime);
480 		j = snprintf(tmpbuf, sizeof(tmpbuf), " %jd%s",
481 		    (intmax_t)fsbtodb(&sblock, cgsblock(&sblock, cylno)),
482 		    cylno < (sblock.fs_ncg-1) ? "," : "");
483 		if (j < 0)
484 			tmpbuf[j = 0] = '\0';
485 		if (i + j >= width) {
486 			printf("\n");
487 			i = 0;
488 		}
489 		i += j;
490 		printf("%s", tmpbuf);
491 		fflush(stdout);
492 	}
493 	printf("\n");
494 	if (Nflag)
495 		exit(0);
496 	/*
497 	 * Now construct the initial file system,
498 	 * then write out the super-block.
499 	 */
500 	fsinit(utime);
501 	if (Oflag == 1) {
502 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
503 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
504 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
505 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
506 	}
507 	if (!Nflag)
508 		sbwrite(&disk, 0);
509 	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
510 		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
511 			sblock.fs_cssize - i < sblock.fs_bsize ?
512 			sblock.fs_cssize - i : sblock.fs_bsize,
513 			((char *)fscs) + i);
514 	/*
515 	 * Update information about this partion in pack
516 	 * label, to that it may be updated on disk.
517 	 */
518 	if (pp != NULL) {
519 		pp->p_fstype = FS_BSDFFS;
520 		pp->p_fsize = sblock.fs_fsize;
521 		pp->p_frag = sblock.fs_frag;
522 		pp->p_cpg = sblock.fs_fpg;
523 	}
524 }
525 
526 /*
527  * Initialize a cylinder group.
528  */
529 void
530 initcg(int cylno, time_t utime)
531 {
532 	long i, j, d, dlower, dupper, blkno, start;
533 	ufs2_daddr_t cbase, dmax;
534 	struct ufs1_dinode *dp1;
535 	struct ufs2_dinode *dp2;
536 	struct csum *cs;
537 
538 	/*
539 	 * Determine block bounds for cylinder group.
540 	 * Allow space for super block summary information in first
541 	 * cylinder group.
542 	 */
543 	cbase = cgbase(&sblock, cylno);
544 	dmax = cbase + sblock.fs_fpg;
545 	if (dmax > sblock.fs_size)
546 		dmax = sblock.fs_size;
547 	dlower = cgsblock(&sblock, cylno) - cbase;
548 	dupper = cgdmin(&sblock, cylno) - cbase;
549 	if (cylno == 0)
550 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
551 	cs = &fscs[cylno];
552 	memset(&acg, 0, sblock.fs_cgsize);
553 	acg.cg_time = utime;
554 	acg.cg_magic = CG_MAGIC;
555 	acg.cg_cgx = cylno;
556 	acg.cg_niblk = sblock.fs_ipg;
557 	acg.cg_initediblk = sblock.fs_ipg < 2 * INOPB(&sblock) ?
558 	    sblock.fs_ipg : 2 * INOPB(&sblock);
559 	acg.cg_ndblk = dmax - cbase;
560 	if (sblock.fs_contigsumsize > 0)
561 		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
562 	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
563 	if (Oflag == 2) {
564 		acg.cg_iusedoff = start;
565 	} else {
566 		acg.cg_old_ncyl = sblock.fs_old_cpg;
567 		acg.cg_old_time = acg.cg_time;
568 		acg.cg_time = 0;
569 		acg.cg_old_niblk = acg.cg_niblk;
570 		acg.cg_niblk = 0;
571 		acg.cg_initediblk = 0;
572 		acg.cg_old_btotoff = start;
573 		acg.cg_old_boff = acg.cg_old_btotoff +
574 		    sblock.fs_old_cpg * sizeof(int32_t);
575 		acg.cg_iusedoff = acg.cg_old_boff +
576 		    sblock.fs_old_cpg * sizeof(u_int16_t);
577 	}
578 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
579 	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
580 	if (sblock.fs_contigsumsize > 0) {
581 		acg.cg_clustersumoff =
582 		    roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
583 		acg.cg_clustersumoff -= sizeof(u_int32_t);
584 		acg.cg_clusteroff = acg.cg_clustersumoff +
585 		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
586 		acg.cg_nextfreeoff = acg.cg_clusteroff +
587 		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
588 	}
589 	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
590 		printf("Panic: cylinder group too big\n");
591 		exit(37);
592 	}
593 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
594 	if (cylno == 0)
595 		for (i = 0; i < (long)ROOTINO; i++) {
596 			setbit(cg_inosused(&acg), i);
597 			acg.cg_cs.cs_nifree--;
598 		}
599 	if (cylno > 0) {
600 		/*
601 		 * In cylno 0, beginning space is reserved
602 		 * for boot and super blocks.
603 		 */
604 		for (d = 0; d < dlower; d += sblock.fs_frag) {
605 			blkno = d / sblock.fs_frag;
606 			setblock(&sblock, cg_blksfree(&acg), blkno);
607 			if (sblock.fs_contigsumsize > 0)
608 				setbit(cg_clustersfree(&acg), blkno);
609 			acg.cg_cs.cs_nbfree++;
610 		}
611 	}
612 	if ((i = dupper % sblock.fs_frag)) {
613 		acg.cg_frsum[sblock.fs_frag - i]++;
614 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
615 			setbit(cg_blksfree(&acg), dupper);
616 			acg.cg_cs.cs_nffree++;
617 		}
618 	}
619 	for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
620 	     d += sblock.fs_frag) {
621 		blkno = d / sblock.fs_frag;
622 		setblock(&sblock, cg_blksfree(&acg), blkno);
623 		if (sblock.fs_contigsumsize > 0)
624 			setbit(cg_clustersfree(&acg), blkno);
625 		acg.cg_cs.cs_nbfree++;
626 	}
627 	if (d < acg.cg_ndblk) {
628 		acg.cg_frsum[acg.cg_ndblk - d]++;
629 		for (; d < acg.cg_ndblk; d++) {
630 			setbit(cg_blksfree(&acg), d);
631 			acg.cg_cs.cs_nffree++;
632 		}
633 	}
634 	if (sblock.fs_contigsumsize > 0) {
635 		int32_t *sump = cg_clustersum(&acg);
636 		u_char *mapp = cg_clustersfree(&acg);
637 		int map = *mapp++;
638 		int bit = 1;
639 		int run = 0;
640 
641 		for (i = 0; i < acg.cg_nclusterblks; i++) {
642 			if ((map & bit) != 0)
643 				run++;
644 			else if (run != 0) {
645 				if (run > sblock.fs_contigsumsize)
646 					run = sblock.fs_contigsumsize;
647 				sump[run]++;
648 				run = 0;
649 			}
650 			if ((i & (CHAR_BIT - 1)) != CHAR_BIT - 1)
651 				bit <<= 1;
652 			else {
653 				map = *mapp++;
654 				bit = 1;
655 			}
656 		}
657 		if (run != 0) {
658 			if (run > sblock.fs_contigsumsize)
659 				run = sblock.fs_contigsumsize;
660 			sump[run]++;
661 		}
662 	}
663 	*cs = acg.cg_cs;
664 	/*
665 	 * Write out the duplicate super block, the cylinder group map
666 	 * and two blocks worth of inodes in a single write.
667 	 */
668 	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
669 	bcopy((char *)&acg, &iobuf[start], sblock.fs_cgsize);
670 	start += sblock.fs_bsize;
671 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
672 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
673 	for (i = 0; i < acg.cg_initediblk; i++) {
674 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
675 			dp1->di_gen = newfs_random();
676 			dp1++;
677 		} else {
678 			dp2->di_gen = newfs_random();
679 			dp2++;
680 		}
681 	}
682 	wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);
683 	/*
684 	 * For the old file system, we have to initialize all the inodes.
685 	 */
686 	if (Oflag == 1) {
687 		for (i = 2 * sblock.fs_frag;
688 		     i < sblock.fs_ipg / INOPF(&sblock);
689 		     i += sblock.fs_frag) {
690 			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
691 			for (j = 0; j < INOPB(&sblock); j++) {
692 				dp1->di_gen = newfs_random();
693 				dp1++;
694 			}
695 			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
696 			    sblock.fs_bsize, &iobuf[start]);
697 		}
698 	}
699 }
700 
701 /*
702  * initialize the file system
703  */
704 #define ROOTLINKCNT 3
705 
706 struct direct root_dir[] = {
707 	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
708 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
709 	{ ROOTINO + 1, sizeof(struct direct), DT_DIR, 5, ".snap" },
710 };
711 
712 #define SNAPLINKCNT 2
713 
714 struct direct snap_dir[] = {
715 	{ ROOTINO + 1, sizeof(struct direct), DT_DIR, 1, "." },
716 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
717 };
718 
719 void
720 fsinit(time_t utime)
721 {
722 	union dinode node;
723 	struct group *grp;
724 
725 	memset(&node, 0, sizeof node);
726 	if ((grp = getgrnam("operator")) == NULL)
727 		errx(35, "Cannot retrieve operator gid");
728 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
729 		/*
730 		 * initialize the node
731 		 */
732 		node.dp1.di_atime = utime;
733 		node.dp1.di_mtime = utime;
734 		node.dp1.di_ctime = utime;
735 		/*
736 		 * create the root directory
737 		 */
738 		node.dp1.di_mode = IFDIR | UMASK;
739 		node.dp1.di_nlink = ROOTLINKCNT;
740 		node.dp1.di_size = makedir(root_dir, ROOTLINKCNT);
741 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
742 		node.dp1.di_blocks =
743 		    btodb(fragroundup(&sblock, node.dp1.di_size));
744 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize,
745 		    iobuf);
746 		iput(&node, ROOTINO);
747 		/*
748 		 * create the .snap directory
749 		 */
750 		node.dp1.di_mode |= 020;
751 		node.dp1.di_gid = grp->gr_gid;
752 		node.dp1.di_nlink = SNAPLINKCNT;
753 		node.dp1.di_size = makedir(snap_dir, SNAPLINKCNT);
754 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
755 		node.dp1.di_blocks =
756 		    btodb(fragroundup(&sblock, node.dp1.di_size));
757 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize,
758 		    iobuf);
759 		iput(&node, ROOTINO + 1);
760 	} else {
761 		/*
762 		 * initialize the node
763 		 */
764 		node.dp2.di_atime = utime;
765 		node.dp2.di_mtime = utime;
766 		node.dp2.di_ctime = utime;
767 		node.dp2.di_birthtime = utime;
768 		/*
769 		 * create the root directory
770 		 */
771 		node.dp2.di_mode = IFDIR | UMASK;
772 		node.dp2.di_nlink = ROOTLINKCNT;
773 		node.dp2.di_size = makedir(root_dir, ROOTLINKCNT);
774 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
775 		node.dp2.di_blocks =
776 		    btodb(fragroundup(&sblock, node.dp2.di_size));
777 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize,
778 		    iobuf);
779 		iput(&node, ROOTINO);
780 		/*
781 		 * create the .snap directory
782 		 */
783 		node.dp2.di_mode |= 020;
784 		node.dp2.di_gid = grp->gr_gid;
785 		node.dp2.di_nlink = SNAPLINKCNT;
786 		node.dp2.di_size = makedir(snap_dir, SNAPLINKCNT);
787 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
788 		node.dp2.di_blocks =
789 		    btodb(fragroundup(&sblock, node.dp2.di_size));
790 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize,
791 		    iobuf);
792 		iput(&node, ROOTINO + 1);
793 	}
794 }
795 
796 /*
797  * construct a set of directory entries in "iobuf".
798  * return size of directory.
799  */
800 int
801 makedir(struct direct *protodir, int entries)
802 {
803 	char *cp;
804 	int i, spcleft;
805 
806 	spcleft = DIRBLKSIZ;
807 	memset(iobuf, 0, DIRBLKSIZ);
808 	for (cp = iobuf, i = 0; i < entries - 1; i++) {
809 		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
810 		memmove(cp, &protodir[i], protodir[i].d_reclen);
811 		cp += protodir[i].d_reclen;
812 		spcleft -= protodir[i].d_reclen;
813 	}
814 	protodir[i].d_reclen = spcleft;
815 	memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
816 	return (DIRBLKSIZ);
817 }
818 
819 /*
820  * allocate a block or frag
821  */
822 ufs2_daddr_t
823 alloc(int size, int mode)
824 {
825 	int i, d, blkno, frag;
826 
827 	bread(&disk, fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
828 	    sblock.fs_cgsize);
829 	if (acg.cg_magic != CG_MAGIC) {
830 		printf("cg 0: bad magic number\n");
831 		exit(38);
832 	}
833 	if (acg.cg_cs.cs_nbfree == 0) {
834 		printf("first cylinder group ran out of space\n");
835 		exit(39);
836 	}
837 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
838 		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
839 			goto goth;
840 	printf("internal error: can't find block in cyl 0\n");
841 	exit(40);
842 goth:
843 	blkno = fragstoblks(&sblock, d);
844 	clrblock(&sblock, cg_blksfree(&acg), blkno);
845 	if (sblock.fs_contigsumsize > 0)
846 		clrbit(cg_clustersfree(&acg), blkno);
847 	acg.cg_cs.cs_nbfree--;
848 	sblock.fs_cstotal.cs_nbfree--;
849 	fscs[0].cs_nbfree--;
850 	if (mode & IFDIR) {
851 		acg.cg_cs.cs_ndir++;
852 		sblock.fs_cstotal.cs_ndir++;
853 		fscs[0].cs_ndir++;
854 	}
855 	if (size != sblock.fs_bsize) {
856 		frag = howmany(size, sblock.fs_fsize);
857 		fscs[0].cs_nffree += sblock.fs_frag - frag;
858 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
859 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
860 		acg.cg_frsum[sblock.fs_frag - frag]++;
861 		for (i = frag; i < sblock.fs_frag; i++)
862 			setbit(cg_blksfree(&acg), d + i);
863 	}
864 	/* XXX cgwrite(&disk, 0)??? */
865 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
866 	    (char *)&acg);
867 	return ((ufs2_daddr_t)d);
868 }
869 
870 /*
871  * Allocate an inode on the disk
872  */
873 void
874 iput(union dinode *ip, ino_t ino)
875 {
876 	ufs2_daddr_t d;
877 	int c;
878 
879 	c = ino_to_cg(&sblock, ino);
880 	bread(&disk, fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
881 	    sblock.fs_cgsize);
882 	if (acg.cg_magic != CG_MAGIC) {
883 		printf("cg 0: bad magic number\n");
884 		exit(31);
885 	}
886 	acg.cg_cs.cs_nifree--;
887 	setbit(cg_inosused(&acg), ino);
888 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
889 	    (char *)&acg);
890 	sblock.fs_cstotal.cs_nifree--;
891 	fscs[0].cs_nifree--;
892 	if (ino >= (unsigned long)sblock.fs_ipg * sblock.fs_ncg) {
893 		printf("fsinit: inode value out of range (%d).\n", ino);
894 		exit(32);
895 	}
896 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
897 	bread(&disk, d, (char *)iobuf, sblock.fs_bsize);
898 	if (sblock.fs_magic == FS_UFS1_MAGIC)
899 		((struct ufs1_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
900 		    ip->dp1;
901 	else
902 		((struct ufs2_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
903 		    ip->dp2;
904 	wtfs(d, sblock.fs_bsize, (char *)iobuf);
905 }
906 
907 /*
908  * possibly write to disk
909  */
910 static void
911 wtfs(ufs2_daddr_t bno, int size, char *bf)
912 {
913 	if (Nflag)
914 		return;
915 	if (bwrite(&disk, bno, bf, size) < 0)
916 		err(36, "wtfs: %d bytes at sector %jd", size, (intmax_t)bno);
917 }
918 
919 /*
920  * check if a block is available
921  */
922 static int
923 isblock(struct fs *fs, unsigned char *cp, int h)
924 {
925 	unsigned char mask;
926 
927 	switch (fs->fs_frag) {
928 	case 8:
929 		return (cp[h] == 0xff);
930 	case 4:
931 		mask = 0x0f << ((h & 0x1) << 2);
932 		return ((cp[h >> 1] & mask) == mask);
933 	case 2:
934 		mask = 0x03 << ((h & 0x3) << 1);
935 		return ((cp[h >> 2] & mask) == mask);
936 	case 1:
937 		mask = 0x01 << (h & 0x7);
938 		return ((cp[h >> 3] & mask) == mask);
939 	default:
940 		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
941 		return (0);
942 	}
943 }
944 
945 /*
946  * take a block out of the map
947  */
948 static void
949 clrblock(struct fs *fs, unsigned char *cp, int h)
950 {
951 	switch ((fs)->fs_frag) {
952 	case 8:
953 		cp[h] = 0;
954 		return;
955 	case 4:
956 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
957 		return;
958 	case 2:
959 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
960 		return;
961 	case 1:
962 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
963 		return;
964 	default:
965 		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
966 		return;
967 	}
968 }
969 
970 /*
971  * put a block into the map
972  */
973 static void
974 setblock(struct fs *fs, unsigned char *cp, int h)
975 {
976 	switch (fs->fs_frag) {
977 	case 8:
978 		cp[h] = 0xff;
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, "setblock bad fs_frag %d\n", fs->fs_frag);
991 		return;
992 	}
993 }
994 
995 /*
996  * Determine the number of characters in a
997  * single line.
998  */
999 
1000 static int
1001 charsperline(void)
1002 {
1003 	int columns;
1004 	char *cp;
1005 	struct winsize ws;
1006 
1007 	columns = 0;
1008 	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1009 		columns = ws.ws_col;
1010 	if (columns == 0 && (cp = getenv("COLUMNS")))
1011 		columns = atoi(cp);
1012 	if (columns == 0)
1013 		columns = 80;	/* last resort */
1014 	return (columns);
1015 }
1016 
1017 static int
1018 ilog2(int val)
1019 {
1020 	u_int n;
1021 
1022 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
1023 		if (1 << n == val)
1024 			return (n);
1025 	errx(1, "ilog2: %d is not a power of 2\n", val);
1026 }
1027 
1028 /*
1029  * For the regression test, return predictable random values.
1030  * Otherwise use a true random number generator.
1031  */
1032 static u_int32_t
1033 newfs_random(void)
1034 {
1035 	static int nextnum = 1;
1036 
1037 	if (Rflag)
1038 		return (nextnum++);
1039 	return (arc4random());
1040 }
1041