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