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