xref: /freebsd/sbin/newfs/mkfs.c (revision 63f9a4cb2684a303e3eb2ffed39c03a2e2b28ae0)
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 
742 	memset(&node, 0, sizeof node);
743 	if ((grp = getgrnam("operator")) == NULL)
744 		errx(35, "Cannot retrieve operator gid");
745 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
746 		/*
747 		 * initialize the node
748 		 */
749 		node.dp1.di_atime = utime;
750 		node.dp1.di_mtime = utime;
751 		node.dp1.di_ctime = utime;
752 		/*
753 		 * create the root directory
754 		 */
755 		node.dp1.di_mode = IFDIR | UMASK;
756 		node.dp1.di_nlink = ROOTLINKCNT;
757 		node.dp1.di_size = makedir(root_dir, ROOTLINKCNT);
758 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
759 		node.dp1.di_blocks =
760 		    btodb(fragroundup(&sblock, node.dp1.di_size));
761 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize,
762 		    iobuf);
763 		iput(&node, ROOTINO);
764 		/*
765 		 * create the .snap directory
766 		 */
767 		node.dp1.di_mode |= 020;
768 		node.dp1.di_gid = grp->gr_gid;
769 		node.dp1.di_nlink = SNAPLINKCNT;
770 		node.dp1.di_size = makedir(snap_dir, SNAPLINKCNT);
771 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
772 		node.dp1.di_blocks =
773 		    btodb(fragroundup(&sblock, node.dp1.di_size));
774 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize,
775 		    iobuf);
776 		iput(&node, ROOTINO + 1);
777 	} else {
778 		/*
779 		 * initialize the node
780 		 */
781 		node.dp2.di_atime = utime;
782 		node.dp2.di_mtime = utime;
783 		node.dp2.di_ctime = utime;
784 		node.dp2.di_birthtime = utime;
785 		/*
786 		 * create the root directory
787 		 */
788 		node.dp2.di_mode = IFDIR | UMASK;
789 		node.dp2.di_nlink = ROOTLINKCNT;
790 		node.dp2.di_size = makedir(root_dir, ROOTLINKCNT);
791 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
792 		node.dp2.di_blocks =
793 		    btodb(fragroundup(&sblock, node.dp2.di_size));
794 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize,
795 		    iobuf);
796 		iput(&node, ROOTINO);
797 		/*
798 		 * create the .snap directory
799 		 */
800 		node.dp2.di_mode |= 020;
801 		node.dp2.di_gid = grp->gr_gid;
802 		node.dp2.di_nlink = SNAPLINKCNT;
803 		node.dp2.di_size = makedir(snap_dir, SNAPLINKCNT);
804 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
805 		node.dp2.di_blocks =
806 		    btodb(fragroundup(&sblock, node.dp2.di_size));
807 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize,
808 		    iobuf);
809 		iput(&node, ROOTINO + 1);
810 	}
811 }
812 
813 /*
814  * construct a set of directory entries in "iobuf".
815  * return size of directory.
816  */
817 int
818 makedir(struct direct *protodir, int entries)
819 {
820 	char *cp;
821 	int i, spcleft;
822 
823 	spcleft = DIRBLKSIZ;
824 	memset(iobuf, 0, DIRBLKSIZ);
825 	for (cp = iobuf, i = 0; i < entries - 1; i++) {
826 		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
827 		memmove(cp, &protodir[i], protodir[i].d_reclen);
828 		cp += protodir[i].d_reclen;
829 		spcleft -= protodir[i].d_reclen;
830 	}
831 	protodir[i].d_reclen = spcleft;
832 	memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
833 	return (DIRBLKSIZ);
834 }
835 
836 /*
837  * allocate a block or frag
838  */
839 ufs2_daddr_t
840 alloc(int size, int mode)
841 {
842 	int i, d, blkno, frag;
843 
844 	bread(&disk, fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
845 	    sblock.fs_cgsize);
846 	if (acg.cg_magic != CG_MAGIC) {
847 		printf("cg 0: bad magic number\n");
848 		exit(38);
849 	}
850 	if (acg.cg_cs.cs_nbfree == 0) {
851 		printf("first cylinder group ran out of space\n");
852 		exit(39);
853 	}
854 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
855 		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
856 			goto goth;
857 	printf("internal error: can't find block in cyl 0\n");
858 	exit(40);
859 goth:
860 	blkno = fragstoblks(&sblock, d);
861 	clrblock(&sblock, cg_blksfree(&acg), blkno);
862 	if (sblock.fs_contigsumsize > 0)
863 		clrbit(cg_clustersfree(&acg), blkno);
864 	acg.cg_cs.cs_nbfree--;
865 	sblock.fs_cstotal.cs_nbfree--;
866 	fscs[0].cs_nbfree--;
867 	if (mode & IFDIR) {
868 		acg.cg_cs.cs_ndir++;
869 		sblock.fs_cstotal.cs_ndir++;
870 		fscs[0].cs_ndir++;
871 	}
872 	if (size != sblock.fs_bsize) {
873 		frag = howmany(size, sblock.fs_fsize);
874 		fscs[0].cs_nffree += sblock.fs_frag - frag;
875 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
876 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
877 		acg.cg_frsum[sblock.fs_frag - frag]++;
878 		for (i = frag; i < sblock.fs_frag; i++)
879 			setbit(cg_blksfree(&acg), d + i);
880 	}
881 	/* XXX cgwrite(&disk, 0)??? */
882 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
883 	    (char *)&acg);
884 	return ((ufs2_daddr_t)d);
885 }
886 
887 /*
888  * Allocate an inode on the disk
889  */
890 void
891 iput(union dinode *ip, ino_t ino)
892 {
893 	ufs2_daddr_t d;
894 	int c;
895 
896 	c = ino_to_cg(&sblock, ino);
897 	bread(&disk, fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
898 	    sblock.fs_cgsize);
899 	if (acg.cg_magic != CG_MAGIC) {
900 		printf("cg 0: bad magic number\n");
901 		exit(31);
902 	}
903 	acg.cg_cs.cs_nifree--;
904 	setbit(cg_inosused(&acg), ino);
905 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
906 	    (char *)&acg);
907 	sblock.fs_cstotal.cs_nifree--;
908 	fscs[0].cs_nifree--;
909 	if (ino >= (unsigned long)sblock.fs_ipg * sblock.fs_ncg) {
910 		printf("fsinit: inode value out of range (%d).\n", ino);
911 		exit(32);
912 	}
913 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
914 	bread(&disk, d, (char *)iobuf, sblock.fs_bsize);
915 	if (sblock.fs_magic == FS_UFS1_MAGIC)
916 		((struct ufs1_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
917 		    ip->dp1;
918 	else
919 		((struct ufs2_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
920 		    ip->dp2;
921 	wtfs(d, sblock.fs_bsize, (char *)iobuf);
922 }
923 
924 /*
925  * possibly write to disk
926  */
927 static void
928 wtfs(ufs2_daddr_t bno, int size, char *bf)
929 {
930 	if (Nflag)
931 		return;
932 	if (bwrite(&disk, bno, bf, size) < 0)
933 		err(36, "wtfs: %d bytes at sector %jd", size, (intmax_t)bno);
934 }
935 
936 /*
937  * check if a block is available
938  */
939 static int
940 isblock(struct fs *fs, unsigned char *cp, int h)
941 {
942 	unsigned char mask;
943 
944 	switch (fs->fs_frag) {
945 	case 8:
946 		return (cp[h] == 0xff);
947 	case 4:
948 		mask = 0x0f << ((h & 0x1) << 2);
949 		return ((cp[h >> 1] & mask) == mask);
950 	case 2:
951 		mask = 0x03 << ((h & 0x3) << 1);
952 		return ((cp[h >> 2] & mask) == mask);
953 	case 1:
954 		mask = 0x01 << (h & 0x7);
955 		return ((cp[h >> 3] & mask) == mask);
956 	default:
957 		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
958 		return (0);
959 	}
960 }
961 
962 /*
963  * take a block out of the map
964  */
965 static void
966 clrblock(struct fs *fs, unsigned char *cp, int h)
967 {
968 	switch ((fs)->fs_frag) {
969 	case 8:
970 		cp[h] = 0;
971 		return;
972 	case 4:
973 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
974 		return;
975 	case 2:
976 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
977 		return;
978 	case 1:
979 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
980 		return;
981 	default:
982 		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
983 		return;
984 	}
985 }
986 
987 /*
988  * put a block into the map
989  */
990 static void
991 setblock(struct fs *fs, unsigned char *cp, int h)
992 {
993 	switch (fs->fs_frag) {
994 	case 8:
995 		cp[h] = 0xff;
996 		return;
997 	case 4:
998 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
999 		return;
1000 	case 2:
1001 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1002 		return;
1003 	case 1:
1004 		cp[h >> 3] |= (0x01 << (h & 0x7));
1005 		return;
1006 	default:
1007 		fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
1008 		return;
1009 	}
1010 }
1011 
1012 /*
1013  * Determine the number of characters in a
1014  * single line.
1015  */
1016 
1017 static int
1018 charsperline(void)
1019 {
1020 	int columns;
1021 	char *cp;
1022 	struct winsize ws;
1023 
1024 	columns = 0;
1025 	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1026 		columns = ws.ws_col;
1027 	if (columns == 0 && (cp = getenv("COLUMNS")))
1028 		columns = atoi(cp);
1029 	if (columns == 0)
1030 		columns = 80;	/* last resort */
1031 	return (columns);
1032 }
1033 
1034 static int
1035 ilog2(int val)
1036 {
1037 	u_int n;
1038 
1039 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
1040 		if (1 << n == val)
1041 			return (n);
1042 	errx(1, "ilog2: %d is not a power of 2\n", val);
1043 }
1044 
1045 /*
1046  * For the regression test, return predictable random values.
1047  * Otherwise use a true random number generator.
1048  */
1049 static u_int32_t
1050 newfs_random(void)
1051 {
1052 	static int nextnum = 1;
1053 
1054 	if (Rflag)
1055 		return (nextnum++);
1056 	return (arc4random());
1057 }
1058