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