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