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