xref: /freebsd/sbin/newfs/mkfs.c (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2002 Networks Associates Technology, Inc.
5  * All rights reserved.
6  *
7  * This software was developed for the FreeBSD Project by Marshall
8  * Kirk McKusick and Network Associates Laboratories, the Security
9  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
10  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
11  * research program.
12  *
13  * Copyright (c) 1980, 1989, 1993
14  *	The Regents of the University of California.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40 
41 #if 0
42 #ifndef lint
43 static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
44 #endif /* not lint */
45 #endif
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #define _WANT_P_OSREL
50 #include <sys/param.h>
51 #include <sys/disklabel.h>
52 #include <sys/file.h>
53 #include <sys/ioctl.h>
54 #include <sys/mman.h>
55 #include <sys/resource.h>
56 #include <sys/stat.h>
57 #include <sys/wait.h>
58 #include <err.h>
59 #include <grp.h>
60 #include <limits.h>
61 #include <signal.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <stdint.h>
65 #include <stdio.h>
66 #include <time.h>
67 #include <unistd.h>
68 #include <ufs/ufs/dinode.h>
69 #include <ufs/ufs/dir.h>
70 #include <ufs/ffs/fs.h>
71 #include "newfs.h"
72 
73 /*
74  * make file system for cylinder-group style file systems
75  */
76 #define UMASK		0755
77 #define POWEROF2(num)	(((num) & ((num) - 1)) == 0)
78 
79 /*
80  * The definition of "struct cg" used to contain an extra field at the end
81  * to represent the variable-length data that followed the fixed structure.
82  * This had the effect of artificially limiting the number of blocks that
83  * newfs would put in a CG, since newfs thought that the fixed-size header
84  * was bigger than it really was.  When we started validating that the CG
85  * header data actually fit into one fs block, the placeholder field caused
86  * a problem because it caused struct cg to be a different size depending on
87  * platform.  The placeholder field was later removed, but this caused a
88  * backward compatibility problem with older binaries that still thought
89  * struct cg was larger, and a new file system could fail validation if
90  * viewed by the older binaries.  To avoid this compatibility problem, we
91  * now artificially reduce the amount of space that the variable-length data
92  * can use such that new file systems will pass validation by older binaries.
93  */
94 #define CGSIZEFUDGE 8
95 
96 static struct	csum *fscs;
97 #define	sblock	disk.d_fs
98 #define	acg	disk.d_cg
99 
100 union dinode {
101 	struct ufs1_dinode dp1;
102 	struct ufs2_dinode dp2;
103 };
104 #define DIP(dp, field) \
105 	((sblock.fs_magic == FS_UFS1_MAGIC) ? \
106 	(dp)->dp1.field : (dp)->dp2.field)
107 
108 static caddr_t iobuf;
109 static long iobufsize;
110 static ufs2_daddr_t alloc(int size, int mode);
111 static int charsperline(void);
112 static void clrblock(struct fs *, unsigned char *, int);
113 static void fsinit(time_t);
114 static int ilog2(int);
115 static void initcg(int, time_t);
116 static int isblock(struct fs *, unsigned char *, int);
117 static void iput(union dinode *, ino_t);
118 static int makedir(struct direct *, int);
119 static void setblock(struct fs *, unsigned char *, int);
120 static void wtfs(ufs2_daddr_t, int, char *);
121 static u_int32_t newfs_random(void);
122 
123 void
124 mkfs(struct partition *pp, char *fsys)
125 {
126 	int fragsperinode, optimalfpg, origdensity, minfpg, lastminfpg;
127 	long i, j, csfrags;
128 	uint cg;
129 	time_t utime;
130 	quad_t sizepb;
131 	int width;
132 	ino_t maxinum;
133 	int minfragsperinode;	/* minimum ratio of frags to inodes */
134 	char tmpbuf[100];	/* XXX this will break in about 2,500 years */
135 	struct fsrecovery *fsr;
136 	char *fsrbuf;
137 	union {
138 		struct fs fdummy;
139 		char cdummy[SBLOCKSIZE];
140 	} dummy;
141 #define fsdummy dummy.fdummy
142 #define chdummy dummy.cdummy
143 
144 	/*
145 	 * Our blocks == sector size, and the version of UFS we are using is
146 	 * specified by Oflag.
147 	 */
148 	disk.d_bsize = sectorsize;
149 	disk.d_ufs = Oflag;
150 	if (Rflag)
151 		utime = 1000000000;
152 	else
153 		time(&utime);
154 	if ((sblock.fs_si = malloc(sizeof(struct fs_summary_info))) == NULL) {
155 		printf("Superblock summary info allocation failed.\n");
156 		exit(18);
157 	}
158 	sblock.fs_old_flags = FS_FLAGS_UPDATED;
159 	sblock.fs_flags = 0;
160 	if (Uflag)
161 		sblock.fs_flags |= FS_DOSOFTDEP;
162 	if (Lflag)
163 		strlcpy(sblock.fs_volname, volumelabel, MAXVOLLEN);
164 	if (Jflag)
165 		sblock.fs_flags |= FS_GJOURNAL;
166 	if (lflag)
167 		sblock.fs_flags |= FS_MULTILABEL;
168 	if (tflag)
169 		sblock.fs_flags |= FS_TRIM;
170 	/*
171 	 * Validate the given file system size.
172 	 * Verify that its last block can actually be accessed.
173 	 * Convert to file system fragment sized units.
174 	 */
175 	if (fssize <= 0) {
176 		printf("preposterous size %jd\n", (intmax_t)fssize);
177 		exit(13);
178 	}
179 	wtfs(fssize - (realsectorsize / DEV_BSIZE), realsectorsize,
180 	    (char *)&sblock);
181 	/*
182 	 * collect and verify the file system density info
183 	 */
184 	sblock.fs_avgfilesize = avgfilesize;
185 	sblock.fs_avgfpdir = avgfilesperdir;
186 	if (sblock.fs_avgfilesize <= 0)
187 		printf("illegal expected average file size %d\n",
188 		    sblock.fs_avgfilesize), exit(14);
189 	if (sblock.fs_avgfpdir <= 0)
190 		printf("illegal expected number of files per directory %d\n",
191 		    sblock.fs_avgfpdir), exit(15);
192 
193 restart:
194 	/*
195 	 * collect and verify the block and fragment sizes
196 	 */
197 	sblock.fs_bsize = bsize;
198 	sblock.fs_fsize = fsize;
199 	if (!POWEROF2(sblock.fs_bsize)) {
200 		printf("block size must be a power of 2, not %d\n",
201 		    sblock.fs_bsize);
202 		exit(16);
203 	}
204 	if (!POWEROF2(sblock.fs_fsize)) {
205 		printf("fragment size must be a power of 2, not %d\n",
206 		    sblock.fs_fsize);
207 		exit(17);
208 	}
209 	if (sblock.fs_fsize < sectorsize) {
210 		printf("increasing fragment size from %d to sector size (%d)\n",
211 		    sblock.fs_fsize, sectorsize);
212 		sblock.fs_fsize = sectorsize;
213 	}
214 	if (sblock.fs_bsize > MAXBSIZE) {
215 		printf("decreasing block size from %d to maximum (%d)\n",
216 		    sblock.fs_bsize, MAXBSIZE);
217 		sblock.fs_bsize = MAXBSIZE;
218 	}
219 	if (sblock.fs_bsize < MINBSIZE) {
220 		printf("increasing block size from %d to minimum (%d)\n",
221 		    sblock.fs_bsize, MINBSIZE);
222 		sblock.fs_bsize = MINBSIZE;
223 	}
224 	if (sblock.fs_fsize > MAXBSIZE) {
225 		printf("decreasing fragment size from %d to maximum (%d)\n",
226 		    sblock.fs_fsize, MAXBSIZE);
227 		sblock.fs_fsize = MAXBSIZE;
228 	}
229 	if (sblock.fs_bsize < sblock.fs_fsize) {
230 		printf("increasing block size from %d to fragment size (%d)\n",
231 		    sblock.fs_bsize, sblock.fs_fsize);
232 		sblock.fs_bsize = sblock.fs_fsize;
233 	}
234 	if (sblock.fs_fsize * MAXFRAG < sblock.fs_bsize) {
235 		printf(
236 		"increasing fragment size from %d to block size / %d (%d)\n",
237 		    sblock.fs_fsize, MAXFRAG, sblock.fs_bsize / MAXFRAG);
238 		sblock.fs_fsize = sblock.fs_bsize / MAXFRAG;
239 	}
240 	if (maxbsize == 0)
241 		maxbsize = bsize;
242 	if (maxbsize < bsize || !POWEROF2(maxbsize)) {
243 		sblock.fs_maxbsize = sblock.fs_bsize;
244 		printf("Extent size set to %d\n", sblock.fs_maxbsize);
245 	} else if (maxbsize > FS_MAXCONTIG * sblock.fs_bsize) {
246 		sblock.fs_maxbsize = FS_MAXCONTIG * sblock.fs_bsize;
247 		printf("Extent size reduced to %d\n", sblock.fs_maxbsize);
248 	} else {
249 		sblock.fs_maxbsize = maxbsize;
250 	}
251 	/*
252 	 * Maxcontig sets the default for the maximum number of blocks
253 	 * that may be allocated sequentially. With file system clustering
254 	 * it is possible to allocate contiguous blocks up to the maximum
255 	 * transfer size permitted by the controller or buffering.
256 	 */
257 	if (maxcontig == 0)
258 		maxcontig = MAX(1, MAXPHYS / bsize);
259 	sblock.fs_maxcontig = maxcontig;
260 	if (sblock.fs_maxcontig < sblock.fs_maxbsize / sblock.fs_bsize) {
261 		sblock.fs_maxcontig = sblock.fs_maxbsize / sblock.fs_bsize;
262 		printf("Maxcontig raised to %d\n", sblock.fs_maxbsize);
263 	}
264 	if (sblock.fs_maxcontig > 1)
265 		sblock.fs_contigsumsize = MIN(sblock.fs_maxcontig,FS_MAXCONTIG);
266 	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
267 	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
268 	sblock.fs_qbmask = ~sblock.fs_bmask;
269 	sblock.fs_qfmask = ~sblock.fs_fmask;
270 	sblock.fs_bshift = ilog2(sblock.fs_bsize);
271 	sblock.fs_fshift = ilog2(sblock.fs_fsize);
272 	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
273 	sblock.fs_fragshift = ilog2(sblock.fs_frag);
274 	if (sblock.fs_frag > MAXFRAG) {
275 		printf("fragment size %d is still too small (can't happen)\n",
276 		    sblock.fs_bsize / MAXFRAG);
277 		exit(21);
278 	}
279 	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / sectorsize);
280 	sblock.fs_size = fssize = dbtofsb(&sblock, fssize);
281 	sblock.fs_providersize = dbtofsb(&sblock, mediasize / sectorsize);
282 
283 	/*
284 	 * Before the filesystem is finally initialized, mark it
285 	 * as incompletely initialized.
286 	 */
287 	sblock.fs_magic = FS_BAD_MAGIC;
288 
289 	if (Oflag == 1) {
290 		sblock.fs_sblockloc = SBLOCK_UFS1;
291 		sblock.fs_sblockactualloc = SBLOCK_UFS1;
292 		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs1_daddr_t);
293 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
294 		sblock.fs_maxsymlinklen = ((UFS_NDADDR + UFS_NIADDR) *
295 		    sizeof(ufs1_daddr_t));
296 		sblock.fs_old_inodefmt = FS_44INODEFMT;
297 		sblock.fs_old_cgoffset = 0;
298 		sblock.fs_old_cgmask = 0xffffffff;
299 		sblock.fs_old_size = sblock.fs_size;
300 		sblock.fs_old_rotdelay = 0;
301 		sblock.fs_old_rps = 60;
302 		sblock.fs_old_nspf = sblock.fs_fsize / sectorsize;
303 		sblock.fs_old_cpg = 1;
304 		sblock.fs_old_interleave = 1;
305 		sblock.fs_old_trackskew = 0;
306 		sblock.fs_old_cpc = 0;
307 		sblock.fs_old_postblformat = 1;
308 		sblock.fs_old_nrpos = 1;
309 	} else {
310 		sblock.fs_sblockloc = SBLOCK_UFS2;
311 		sblock.fs_sblockactualloc = SBLOCK_UFS2;
312 		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs2_daddr_t);
313 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
314 		sblock.fs_maxsymlinklen = ((UFS_NDADDR + UFS_NIADDR) *
315 		    sizeof(ufs2_daddr_t));
316 	}
317 	sblock.fs_sblkno =
318 	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
319 		sblock.fs_frag);
320 	sblock.fs_cblkno = sblock.fs_sblkno +
321 	    roundup(howmany(SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag);
322 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
323 	sblock.fs_maxfilesize = sblock.fs_bsize * UFS_NDADDR - 1;
324 	for (sizepb = sblock.fs_bsize, i = 0; i < UFS_NIADDR; i++) {
325 		sizepb *= NINDIR(&sblock);
326 		sblock.fs_maxfilesize += sizepb;
327 	}
328 
329 	/*
330 	 * It's impossible to create a snapshot in case that fs_maxfilesize
331 	 * is smaller than the fssize.
332 	 */
333 	if (sblock.fs_maxfilesize < (u_quad_t)fssize) {
334 		warnx("WARNING: You will be unable to create snapshots on this "
335 		      "file system.  Correct by using a larger blocksize.");
336 	}
337 
338 	/*
339 	 * Calculate the number of blocks to put into each cylinder group.
340 	 *
341 	 * This algorithm selects the number of blocks per cylinder
342 	 * group. The first goal is to have at least enough data blocks
343 	 * in each cylinder group to meet the density requirement. Once
344 	 * this goal is achieved we try to expand to have at least
345 	 * MINCYLGRPS cylinder groups. Once this goal is achieved, we
346 	 * pack as many blocks into each cylinder group map as will fit.
347 	 *
348 	 * We start by calculating the smallest number of blocks that we
349 	 * can put into each cylinder group. If this is too big, we reduce
350 	 * the density until it fits.
351 	 */
352 retry:
353 	maxinum = (((int64_t)(1)) << 32) - INOPB(&sblock);
354 	minfragsperinode = 1 + fssize / maxinum;
355 	if (density == 0) {
356 		density = MAX(NFPI, minfragsperinode) * fsize;
357 	} else if (density < minfragsperinode * fsize) {
358 		origdensity = density;
359 		density = minfragsperinode * fsize;
360 		fprintf(stderr, "density increased from %d to %d\n",
361 		    origdensity, density);
362 	}
363 	origdensity = density;
364 	for (;;) {
365 		fragsperinode = MAX(numfrags(&sblock, density), 1);
366 		if (fragsperinode < minfragsperinode) {
367 			bsize <<= 1;
368 			fsize <<= 1;
369 			printf("Block size too small for a file system %s %d\n",
370 			     "of this size. Increasing blocksize to", bsize);
371 			goto restart;
372 		}
373 		minfpg = fragsperinode * INOPB(&sblock);
374 		if (minfpg > sblock.fs_size)
375 			minfpg = sblock.fs_size;
376 		sblock.fs_ipg = INOPB(&sblock);
377 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
378 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
379 		if (sblock.fs_fpg < minfpg)
380 			sblock.fs_fpg = minfpg;
381 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
382 		    INOPB(&sblock));
383 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
384 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
385 		if (sblock.fs_fpg < minfpg)
386 			sblock.fs_fpg = minfpg;
387 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
388 		    INOPB(&sblock));
389 		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize -
390 		    CGSIZEFUDGE)
391 			break;
392 		density -= sblock.fs_fsize;
393 	}
394 	if (density != origdensity)
395 		printf("density reduced from %d to %d\n", origdensity, density);
396 	/*
397 	 * Start packing more blocks into the cylinder group until
398 	 * it cannot grow any larger, the number of cylinder groups
399 	 * drops below MINCYLGRPS, or we reach the size requested.
400 	 * For UFS1 inodes per cylinder group are stored in an int16_t
401 	 * so fs_ipg is limited to 2^15 - 1.
402 	 */
403 	for ( ; sblock.fs_fpg < maxblkspercg; sblock.fs_fpg += sblock.fs_frag) {
404 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
405 		    INOPB(&sblock));
406 		if (Oflag > 1 || (Oflag == 1 && sblock.fs_ipg <= 0x7fff)) {
407 			if (sblock.fs_size / sblock.fs_fpg < MINCYLGRPS)
408 				break;
409 			if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize -
410 			    CGSIZEFUDGE)
411 				continue;
412 			if (CGSIZE(&sblock) == (unsigned long)sblock.fs_bsize -
413 			    CGSIZEFUDGE)
414 				break;
415 		}
416 		sblock.fs_fpg -= sblock.fs_frag;
417 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
418 		    INOPB(&sblock));
419 		break;
420 	}
421 	/*
422 	 * Check to be sure that the last cylinder group has enough blocks
423 	 * to be viable. If it is too small, reduce the number of blocks
424 	 * per cylinder group which will have the effect of moving more
425 	 * blocks into the last cylinder group.
426 	 */
427 	optimalfpg = sblock.fs_fpg;
428 	for (;;) {
429 		sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
430 		lastminfpg = roundup(sblock.fs_iblkno +
431 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
432 		if (sblock.fs_size < lastminfpg) {
433 			printf("Filesystem size %jd < minimum size of %d\n",
434 			    (intmax_t)sblock.fs_size, lastminfpg);
435 			exit(28);
436 		}
437 		if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
438 		    sblock.fs_size % sblock.fs_fpg == 0)
439 			break;
440 		sblock.fs_fpg -= sblock.fs_frag;
441 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
442 		    INOPB(&sblock));
443 	}
444 	if (optimalfpg != sblock.fs_fpg)
445 		printf("Reduced frags per cylinder group from %d to %d %s\n",
446 		   optimalfpg, sblock.fs_fpg, "to enlarge last cyl group");
447 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
448 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
449 	if (Oflag == 1) {
450 		sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
451 		sblock.fs_old_nsect = sblock.fs_old_spc;
452 		sblock.fs_old_npsect = sblock.fs_old_spc;
453 		sblock.fs_old_ncyl = sblock.fs_ncg;
454 	}
455 	/*
456 	 * fill in remaining fields of the super block
457 	 */
458 	sblock.fs_csaddr = cgdmin(&sblock, 0);
459 	sblock.fs_cssize =
460 	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
461 	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
462 	if (fscs == NULL)
463 		errx(31, "calloc failed");
464 	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
465 	if (sblock.fs_sbsize > SBLOCKSIZE)
466 		sblock.fs_sbsize = SBLOCKSIZE;
467 	if (sblock.fs_sbsize < realsectorsize)
468 		sblock.fs_sbsize = realsectorsize;
469 	sblock.fs_minfree = minfree;
470 	if (metaspace > 0 && metaspace < sblock.fs_fpg / 2)
471 		sblock.fs_metaspace = blknum(&sblock, metaspace);
472 	else if (metaspace != -1)
473 		/* reserve half of minfree for metadata blocks */
474 		sblock.fs_metaspace = blknum(&sblock,
475 		    (sblock.fs_fpg * minfree) / 200);
476 	if (maxbpg == 0)
477 		sblock.fs_maxbpg = MAXBLKPG(sblock.fs_bsize);
478 	else
479 		sblock.fs_maxbpg = maxbpg;
480 	sblock.fs_optim = opt;
481 	sblock.fs_cgrotor = 0;
482 	sblock.fs_pendingblocks = 0;
483 	sblock.fs_pendinginodes = 0;
484 	sblock.fs_fmod = 0;
485 	sblock.fs_ronly = 0;
486 	sblock.fs_state = 0;
487 	sblock.fs_clean = 1;
488 	sblock.fs_id[0] = (long)utime;
489 	sblock.fs_id[1] = newfs_random();
490 	sblock.fs_fsmnt[0] = '\0';
491 	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
492 	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
493 	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
494 	sblock.fs_cstotal.cs_nbfree =
495 	    fragstoblks(&sblock, sblock.fs_dsize) -
496 	    howmany(csfrags, sblock.fs_frag);
497 	sblock.fs_cstotal.cs_nffree =
498 	    fragnum(&sblock, sblock.fs_size) +
499 	    (fragnum(&sblock, csfrags) > 0 ?
500 	     sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
501 	sblock.fs_cstotal.cs_nifree =
502 	    sblock.fs_ncg * sblock.fs_ipg - UFS_ROOTINO;
503 	sblock.fs_cstotal.cs_ndir = 0;
504 	sblock.fs_dsize -= csfrags;
505 	sblock.fs_time = utime;
506 	if (Oflag == 1) {
507 		sblock.fs_old_time = utime;
508 		sblock.fs_old_dsize = sblock.fs_dsize;
509 		sblock.fs_old_csaddr = sblock.fs_csaddr;
510 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
511 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
512 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
513 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
514 	}
515 	/*
516 	 * Set flags for metadata that is being check-hashed.
517 	 *
518 	 * Metadata check hashes are not supported in the UFS version 1
519 	 * filesystem to keep it as small and simple as possible.
520 	 */
521 	if (Oflag > 1) {
522 		sblock.fs_flags |= FS_METACKHASH;
523 		if (getosreldate() >= P_OSREL_CK_CYLGRP)
524 			sblock.fs_metackhash |= CK_CYLGRP;
525 		if (getosreldate() >= P_OSREL_CK_SUPERBLOCK)
526 			sblock.fs_metackhash |= CK_SUPERBLOCK;
527 		if (getosreldate() >= P_OSREL_CK_INODE)
528 			sblock.fs_metackhash |= CK_INODE;
529 	}
530 
531 	/*
532 	 * Dump out summary information about file system.
533 	 */
534 #	define B2MBFACTOR (1 / (1024.0 * 1024.0))
535 	printf("%s: %.1fMB (%jd sectors) block size %d, fragment size %d\n",
536 	    fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
537 	    (intmax_t)fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize,
538 	    sblock.fs_fsize);
539 	printf("\tusing %d cylinder groups of %.2fMB, %d blks, %d inodes.\n",
540 	    sblock.fs_ncg, (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
541 	    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
542 	if (sblock.fs_flags & FS_DOSOFTDEP)
543 		printf("\twith soft updates\n");
544 #	undef B2MBFACTOR
545 
546 	if (Eflag && !Nflag) {
547 		printf("Erasing sectors [%jd...%jd]\n",
548 		    sblock.fs_sblockloc / disk.d_bsize,
549 		    fsbtodb(&sblock, sblock.fs_size) - 1);
550 		berase(&disk, sblock.fs_sblockloc / disk.d_bsize,
551 		    sblock.fs_size * sblock.fs_fsize - sblock.fs_sblockloc);
552 	}
553 	/*
554 	 * Wipe out old UFS1 superblock(s) if necessary.
555 	 */
556 	if (!Nflag && Oflag != 1 && realsectorsize <= SBLOCK_UFS1) {
557 		i = bread(&disk, part_ofs + SBLOCK_UFS1 / disk.d_bsize, chdummy,
558 		    SBLOCKSIZE);
559 		if (i == -1)
560 			err(1, "can't read old UFS1 superblock: %s",
561 			    disk.d_error);
562 
563 		if (fsdummy.fs_magic == FS_UFS1_MAGIC) {
564 			fsdummy.fs_magic = 0;
565 			bwrite(&disk, part_ofs + SBLOCK_UFS1 / disk.d_bsize,
566 			    chdummy, SBLOCKSIZE);
567 			for (cg = 0; cg < fsdummy.fs_ncg; cg++) {
568 				if (fsbtodb(&fsdummy, cgsblock(&fsdummy, cg)) >
569 				    fssize)
570 					break;
571 				bwrite(&disk, part_ofs + fsbtodb(&fsdummy,
572 				  cgsblock(&fsdummy, cg)), chdummy, SBLOCKSIZE);
573 			}
574 		}
575 	}
576 	/*
577 	 * Reference the summary information so it will also be written.
578 	 */
579 	sblock.fs_csp = fscs;
580 	if (!Nflag && sbwrite(&disk, 0) != 0)
581 		err(1, "sbwrite: %s", disk.d_error);
582 	if (Xflag == 1) {
583 		printf("** Exiting on Xflag 1\n");
584 		exit(0);
585 	}
586 	if (Xflag == 2)
587 		printf("** Leaving BAD MAGIC on Xflag 2\n");
588 	else
589 		sblock.fs_magic = (Oflag != 1) ? FS_UFS2_MAGIC : FS_UFS1_MAGIC;
590 
591 	/*
592 	 * Now build the cylinders group blocks and
593 	 * then print out indices of cylinder groups.
594 	 */
595 	printf("super-block backups (for fsck_ffs -b #) at:\n");
596 	i = 0;
597 	width = charsperline();
598 	/*
599 	 * Allocate space for two sets of inode blocks.
600 	 */
601 	iobufsize = 2 * sblock.fs_bsize;
602 	if ((iobuf = calloc(1, iobufsize)) == 0) {
603 		printf("Cannot allocate I/O buffer\n");
604 		exit(38);
605 	}
606 	/*
607 	 * Write out all the cylinder groups and backup superblocks.
608 	 */
609 	for (cg = 0; cg < sblock.fs_ncg; cg++) {
610 		if (!Nflag)
611 			initcg(cg, utime);
612 		j = snprintf(tmpbuf, sizeof(tmpbuf), " %jd%s",
613 		    (intmax_t)fsbtodb(&sblock, cgsblock(&sblock, cg)),
614 		    cg < (sblock.fs_ncg-1) ? "," : "");
615 		if (j < 0)
616 			tmpbuf[j = 0] = '\0';
617 		if (i + j >= width) {
618 			printf("\n");
619 			i = 0;
620 		}
621 		i += j;
622 		printf("%s", tmpbuf);
623 		fflush(stdout);
624 	}
625 	printf("\n");
626 	if (Nflag)
627 		exit(0);
628 	/*
629 	 * Now construct the initial file system,
630 	 * then write out the super-block.
631 	 */
632 	fsinit(utime);
633 	if (Oflag == 1) {
634 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
635 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
636 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
637 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
638 	}
639 	if (Xflag == 3) {
640 		printf("** Exiting on Xflag 3\n");
641 		exit(0);
642 	}
643 	if (sbwrite(&disk, 0) != 0)
644 		err(1, "sbwrite: %s", disk.d_error);
645 	/*
646 	 * For UFS1 filesystems with a blocksize of 64K, the first
647 	 * alternate superblock resides at the location used for
648 	 * the default UFS2 superblock. As there is a valid
649 	 * superblock at this location, the boot code will use
650 	 * it as its first choice. Thus we have to ensure that
651 	 * all of its statistcs on usage are correct.
652 	 */
653 	if (Oflag == 1 && sblock.fs_bsize == 65536)
654 		wtfs(fsbtodb(&sblock, cgsblock(&sblock, 0)),
655 		    sblock.fs_bsize, (char *)&sblock);
656 	/*
657 	 * Read the last sector of the boot block, replace the last
658 	 * 20 bytes with the recovery information, then write it back.
659 	 * The recovery information only works for UFS2 filesystems.
660 	 * For UFS1, zero out the area to ensure that an old UFS2
661 	 * recovery block is not accidentally found.
662 	 */
663 	if ((fsrbuf = malloc(realsectorsize)) == NULL || bread(&disk,
664 	    part_ofs + (SBLOCK_UFS2 - realsectorsize) / disk.d_bsize,
665 	    fsrbuf, realsectorsize) == -1)
666 		err(1, "can't read recovery area: %s", disk.d_error);
667 	fsr = (struct fsrecovery *)&fsrbuf[realsectorsize - sizeof *fsr];
668 	if (sblock.fs_magic != FS_UFS2_MAGIC) {
669 		memset(fsr, 0, sizeof *fsr);
670 	} else {
671 		fsr->fsr_magic = sblock.fs_magic;
672 		fsr->fsr_fpg = sblock.fs_fpg;
673 		fsr->fsr_fsbtodb = sblock.fs_fsbtodb;
674 		fsr->fsr_sblkno = sblock.fs_sblkno;
675 		fsr->fsr_ncg = sblock.fs_ncg;
676 	}
677 	wtfs((SBLOCK_UFS2 - realsectorsize) / disk.d_bsize,
678 	    realsectorsize, fsrbuf);
679 	free(fsrbuf);
680 	/*
681 	 * Update information about this partition in pack
682 	 * label, to that it may be updated on disk.
683 	 */
684 	if (pp != NULL) {
685 		pp->p_fstype = FS_BSDFFS;
686 		pp->p_fsize = sblock.fs_fsize;
687 		pp->p_frag = sblock.fs_frag;
688 		pp->p_cpg = sblock.fs_fpg;
689 	}
690 	/*
691 	 * This should NOT happen. If it does complain loudly and
692 	 * take evasive action.
693 	 */
694 	if ((int32_t)CGSIZE(&sblock) > sblock.fs_bsize) {
695 		printf("INTERNAL ERROR: ipg %d, fpg %d, contigsumsize %d, ",
696 		    sblock.fs_ipg, sblock.fs_fpg, sblock.fs_contigsumsize);
697 		printf("old_cpg %d, size_cg %zu, CGSIZE %zu\n",
698 		    sblock.fs_old_cpg, sizeof(struct cg), CGSIZE(&sblock));
699 		printf("Please file a FreeBSD bug report and include this "
700 		    "output\n");
701 		maxblkspercg = fragstoblks(&sblock, sblock.fs_fpg) - 1;
702 		density = 0;
703 		goto retry;
704 	}
705 }
706 
707 /*
708  * Initialize a cylinder group.
709  */
710 void
711 initcg(int cylno, time_t utime)
712 {
713 	long blkno, start;
714 	off_t savedactualloc;
715 	uint i, j, d, dlower, dupper;
716 	ufs2_daddr_t cbase, dmax;
717 	struct ufs1_dinode *dp1;
718 	struct ufs2_dinode *dp2;
719 	struct csum *cs;
720 
721 	/*
722 	 * Determine block bounds for cylinder group.
723 	 * Allow space for super block summary information in first
724 	 * cylinder group.
725 	 */
726 	cbase = cgbase(&sblock, cylno);
727 	dmax = cbase + sblock.fs_fpg;
728 	if (dmax > sblock.fs_size)
729 		dmax = sblock.fs_size;
730 	dlower = cgsblock(&sblock, cylno) - cbase;
731 	dupper = cgdmin(&sblock, cylno) - cbase;
732 	if (cylno == 0)
733 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
734 	cs = &fscs[cylno];
735 	memset(&acg, 0, sblock.fs_cgsize);
736 	acg.cg_time = utime;
737 	acg.cg_magic = CG_MAGIC;
738 	acg.cg_cgx = cylno;
739 	acg.cg_niblk = sblock.fs_ipg;
740 	acg.cg_initediblk = MIN(sblock.fs_ipg, 2 * INOPB(&sblock));
741 	acg.cg_ndblk = dmax - cbase;
742 	if (sblock.fs_contigsumsize > 0)
743 		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
744 	start = sizeof(acg);
745 	if (Oflag == 2) {
746 		acg.cg_iusedoff = start;
747 	} else {
748 		acg.cg_old_ncyl = sblock.fs_old_cpg;
749 		acg.cg_old_time = acg.cg_time;
750 		acg.cg_time = 0;
751 		acg.cg_old_niblk = acg.cg_niblk;
752 		acg.cg_niblk = 0;
753 		acg.cg_initediblk = 0;
754 		acg.cg_old_btotoff = start;
755 		acg.cg_old_boff = acg.cg_old_btotoff +
756 		    sblock.fs_old_cpg * sizeof(int32_t);
757 		acg.cg_iusedoff = acg.cg_old_boff +
758 		    sblock.fs_old_cpg * sizeof(u_int16_t);
759 	}
760 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
761 	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
762 	if (sblock.fs_contigsumsize > 0) {
763 		acg.cg_clustersumoff =
764 		    roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
765 		acg.cg_clustersumoff -= sizeof(u_int32_t);
766 		acg.cg_clusteroff = acg.cg_clustersumoff +
767 		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
768 		acg.cg_nextfreeoff = acg.cg_clusteroff +
769 		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
770 	}
771 	if (acg.cg_nextfreeoff > (unsigned)sblock.fs_cgsize) {
772 		printf("Panic: cylinder group too big by %d bytes\n",
773 		    acg.cg_nextfreeoff - (unsigned)sblock.fs_cgsize);
774 		exit(37);
775 	}
776 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
777 	if (cylno == 0)
778 		for (i = 0; i < (long)UFS_ROOTINO; i++) {
779 			setbit(cg_inosused(&acg), i);
780 			acg.cg_cs.cs_nifree--;
781 		}
782 	if (cylno > 0) {
783 		/*
784 		 * In cylno 0, beginning space is reserved
785 		 * for boot and super blocks.
786 		 */
787 		for (d = 0; d < dlower; d += sblock.fs_frag) {
788 			blkno = d / sblock.fs_frag;
789 			setblock(&sblock, cg_blksfree(&acg), blkno);
790 			if (sblock.fs_contigsumsize > 0)
791 				setbit(cg_clustersfree(&acg), blkno);
792 			acg.cg_cs.cs_nbfree++;
793 		}
794 	}
795 	if ((i = dupper % sblock.fs_frag)) {
796 		acg.cg_frsum[sblock.fs_frag - i]++;
797 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
798 			setbit(cg_blksfree(&acg), dupper);
799 			acg.cg_cs.cs_nffree++;
800 		}
801 	}
802 	for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
803 	     d += sblock.fs_frag) {
804 		blkno = d / sblock.fs_frag;
805 		setblock(&sblock, cg_blksfree(&acg), blkno);
806 		if (sblock.fs_contigsumsize > 0)
807 			setbit(cg_clustersfree(&acg), blkno);
808 		acg.cg_cs.cs_nbfree++;
809 	}
810 	if (d < acg.cg_ndblk) {
811 		acg.cg_frsum[acg.cg_ndblk - d]++;
812 		for (; d < acg.cg_ndblk; d++) {
813 			setbit(cg_blksfree(&acg), d);
814 			acg.cg_cs.cs_nffree++;
815 		}
816 	}
817 	if (sblock.fs_contigsumsize > 0) {
818 		int32_t *sump = cg_clustersum(&acg);
819 		u_char *mapp = cg_clustersfree(&acg);
820 		int map = *mapp++;
821 		int bit = 1;
822 		int run = 0;
823 
824 		for (i = 0; i < acg.cg_nclusterblks; i++) {
825 			if ((map & bit) != 0)
826 				run++;
827 			else if (run != 0) {
828 				if (run > sblock.fs_contigsumsize)
829 					run = sblock.fs_contigsumsize;
830 				sump[run]++;
831 				run = 0;
832 			}
833 			if ((i & (CHAR_BIT - 1)) != CHAR_BIT - 1)
834 				bit <<= 1;
835 			else {
836 				map = *mapp++;
837 				bit = 1;
838 			}
839 		}
840 		if (run != 0) {
841 			if (run > sblock.fs_contigsumsize)
842 				run = sblock.fs_contigsumsize;
843 			sump[run]++;
844 		}
845 	}
846 	*cs = acg.cg_cs;
847 	/*
848 	 * Write out the duplicate super block. Then write the cylinder
849 	 * group map and two blocks worth of inodes in a single write.
850 	 */
851 	savedactualloc = sblock.fs_sblockactualloc;
852 	sblock.fs_sblockactualloc =
853 	    dbtob(fsbtodb(&sblock, cgsblock(&sblock, cylno)));
854 	if (sbwrite(&disk, 0) != 0)
855 		err(1, "sbwrite: %s", disk.d_error);
856 	sblock.fs_sblockactualloc = savedactualloc;
857 	if (cgwrite(&disk) != 0)
858 		err(1, "initcg: cgwrite: %s", disk.d_error);
859 	start = 0;
860 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
861 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
862 	for (i = 0; i < acg.cg_initediblk; i++) {
863 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
864 			dp1->di_gen = newfs_random();
865 			dp1++;
866 		} else {
867 			dp2->di_gen = newfs_random();
868 			dp2++;
869 		}
870 	}
871 	wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno)), iobufsize, iobuf);
872 	/*
873 	 * For the old file system, we have to initialize all the inodes.
874 	 */
875 	if (Oflag == 1) {
876 		for (i = 2 * sblock.fs_frag;
877 		     i < sblock.fs_ipg / INOPF(&sblock);
878 		     i += sblock.fs_frag) {
879 			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
880 			for (j = 0; j < INOPB(&sblock); j++) {
881 				dp1->di_gen = newfs_random();
882 				dp1++;
883 			}
884 			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
885 			    sblock.fs_bsize, &iobuf[start]);
886 		}
887 	}
888 }
889 
890 /*
891  * initialize the file system
892  */
893 #define ROOTLINKCNT 3
894 
895 static struct direct root_dir[] = {
896 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
897 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
898 	{ UFS_ROOTINO + 1, sizeof(struct direct), DT_DIR, 5, ".snap" },
899 };
900 
901 #define SNAPLINKCNT 2
902 
903 static struct direct snap_dir[] = {
904 	{ UFS_ROOTINO + 1, sizeof(struct direct), DT_DIR, 1, "." },
905 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
906 };
907 
908 void
909 fsinit(time_t utime)
910 {
911 	union dinode node;
912 	struct group *grp;
913 	gid_t gid;
914 	int entries;
915 
916 	memset(&node, 0, sizeof node);
917 	if ((grp = getgrnam("operator")) != NULL) {
918 		gid = grp->gr_gid;
919 	} else {
920 		warnx("Cannot retrieve operator gid, using gid 0.");
921 		gid = 0;
922 	}
923 	entries = (nflag) ? ROOTLINKCNT - 1: ROOTLINKCNT;
924 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
925 		/*
926 		 * initialize the node
927 		 */
928 		node.dp1.di_atime = utime;
929 		node.dp1.di_mtime = utime;
930 		node.dp1.di_ctime = utime;
931 		/*
932 		 * create the root directory
933 		 */
934 		node.dp1.di_mode = IFDIR | UMASK;
935 		node.dp1.di_nlink = entries;
936 		node.dp1.di_size = makedir(root_dir, entries);
937 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
938 		node.dp1.di_blocks =
939 		    btodb(fragroundup(&sblock, node.dp1.di_size));
940 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize,
941 		    iobuf);
942 		iput(&node, UFS_ROOTINO);
943 		if (!nflag) {
944 			/*
945 			 * create the .snap directory
946 			 */
947 			node.dp1.di_mode |= 020;
948 			node.dp1.di_gid = gid;
949 			node.dp1.di_nlink = SNAPLINKCNT;
950 			node.dp1.di_size = makedir(snap_dir, SNAPLINKCNT);
951 				node.dp1.di_db[0] =
952 				    alloc(sblock.fs_fsize, node.dp1.di_mode);
953 			node.dp1.di_blocks =
954 			    btodb(fragroundup(&sblock, node.dp1.di_size));
955 			node.dp1.di_dirdepth = 1;
956 			wtfs(fsbtodb(&sblock, node.dp1.di_db[0]),
957 			    sblock.fs_fsize, iobuf);
958 			iput(&node, UFS_ROOTINO + 1);
959 		}
960 	} else {
961 		/*
962 		 * initialize the node
963 		 */
964 		node.dp2.di_atime = utime;
965 		node.dp2.di_mtime = utime;
966 		node.dp2.di_ctime = utime;
967 		node.dp2.di_birthtime = utime;
968 		/*
969 		 * create the root directory
970 		 */
971 		node.dp2.di_mode = IFDIR | UMASK;
972 		node.dp2.di_nlink = entries;
973 		node.dp2.di_size = makedir(root_dir, entries);
974 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
975 		node.dp2.di_blocks =
976 		    btodb(fragroundup(&sblock, node.dp2.di_size));
977 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize,
978 		    iobuf);
979 		iput(&node, UFS_ROOTINO);
980 		if (!nflag) {
981 			/*
982 			 * create the .snap directory
983 			 */
984 			node.dp2.di_mode |= 020;
985 			node.dp2.di_gid = gid;
986 			node.dp2.di_nlink = SNAPLINKCNT;
987 			node.dp2.di_size = makedir(snap_dir, SNAPLINKCNT);
988 				node.dp2.di_db[0] =
989 				    alloc(sblock.fs_fsize, node.dp2.di_mode);
990 			node.dp2.di_blocks =
991 			    btodb(fragroundup(&sblock, node.dp2.di_size));
992 			node.dp2.di_dirdepth = 1;
993 			wtfs(fsbtodb(&sblock, node.dp2.di_db[0]),
994 			    sblock.fs_fsize, iobuf);
995 			iput(&node, UFS_ROOTINO + 1);
996 		}
997 	}
998 }
999 
1000 /*
1001  * construct a set of directory entries in "iobuf".
1002  * return size of directory.
1003  */
1004 int
1005 makedir(struct direct *protodir, int entries)
1006 {
1007 	char *cp;
1008 	int i, spcleft;
1009 
1010 	spcleft = DIRBLKSIZ;
1011 	memset(iobuf, 0, DIRBLKSIZ);
1012 	for (cp = iobuf, i = 0; i < entries - 1; i++) {
1013 		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
1014 		memmove(cp, &protodir[i], protodir[i].d_reclen);
1015 		cp += protodir[i].d_reclen;
1016 		spcleft -= protodir[i].d_reclen;
1017 	}
1018 	protodir[i].d_reclen = spcleft;
1019 	memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
1020 	return (DIRBLKSIZ);
1021 }
1022 
1023 /*
1024  * allocate a block or frag
1025  */
1026 ufs2_daddr_t
1027 alloc(int size, int mode)
1028 {
1029 	int i, blkno, frag;
1030 	uint d;
1031 
1032 	bread(&disk, part_ofs + fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
1033 	    sblock.fs_cgsize);
1034 	if (acg.cg_magic != CG_MAGIC) {
1035 		printf("cg 0: bad magic number\n");
1036 		exit(38);
1037 	}
1038 	if (acg.cg_cs.cs_nbfree == 0) {
1039 		printf("first cylinder group ran out of space\n");
1040 		exit(39);
1041 	}
1042 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
1043 		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
1044 			goto goth;
1045 	printf("internal error: can't find block in cyl 0\n");
1046 	exit(40);
1047 goth:
1048 	blkno = fragstoblks(&sblock, d);
1049 	clrblock(&sblock, cg_blksfree(&acg), blkno);
1050 	if (sblock.fs_contigsumsize > 0)
1051 		clrbit(cg_clustersfree(&acg), blkno);
1052 	acg.cg_cs.cs_nbfree--;
1053 	sblock.fs_cstotal.cs_nbfree--;
1054 	fscs[0].cs_nbfree--;
1055 	if (mode & IFDIR) {
1056 		acg.cg_cs.cs_ndir++;
1057 		sblock.fs_cstotal.cs_ndir++;
1058 		fscs[0].cs_ndir++;
1059 	}
1060 	if (size != sblock.fs_bsize) {
1061 		frag = howmany(size, sblock.fs_fsize);
1062 		fscs[0].cs_nffree += sblock.fs_frag - frag;
1063 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
1064 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
1065 		acg.cg_frsum[sblock.fs_frag - frag]++;
1066 		for (i = frag; i < sblock.fs_frag; i++)
1067 			setbit(cg_blksfree(&acg), d + i);
1068 	}
1069 	if (cgwrite(&disk) != 0)
1070 		err(1, "alloc: cgwrite: %s", disk.d_error);
1071 	return ((ufs2_daddr_t)d);
1072 }
1073 
1074 /*
1075  * Allocate an inode on the disk
1076  */
1077 void
1078 iput(union dinode *ip, ino_t ino)
1079 {
1080 	union dinodep dp;
1081 
1082 	bread(&disk, part_ofs + fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
1083 	    sblock.fs_cgsize);
1084 	if (acg.cg_magic != CG_MAGIC) {
1085 		printf("cg 0: bad magic number\n");
1086 		exit(31);
1087 	}
1088 	acg.cg_cs.cs_nifree--;
1089 	setbit(cg_inosused(&acg), ino);
1090 	if (cgwrite(&disk) != 0)
1091 		err(1, "iput: cgwrite: %s", disk.d_error);
1092 	sblock.fs_cstotal.cs_nifree--;
1093 	fscs[0].cs_nifree--;
1094 	if (getinode(&disk, &dp, ino) == -1) {
1095 		printf("iput: %s\n", disk.d_error);
1096 		exit(32);
1097 	}
1098 	if (sblock.fs_magic == FS_UFS1_MAGIC)
1099 		*dp.dp1 = ip->dp1;
1100 	else
1101 		*dp.dp2 = ip->dp2;
1102 	putinode(&disk);
1103 }
1104 
1105 /*
1106  * possibly write to disk
1107  */
1108 static void
1109 wtfs(ufs2_daddr_t bno, int size, char *bf)
1110 {
1111 	if (Nflag)
1112 		return;
1113 	if (bwrite(&disk, part_ofs + bno, bf, size) < 0)
1114 		err(36, "wtfs: %d bytes at sector %jd", size, (intmax_t)bno);
1115 }
1116 
1117 /*
1118  * check if a block is available
1119  */
1120 static int
1121 isblock(struct fs *fs, unsigned char *cp, int h)
1122 {
1123 	unsigned char mask;
1124 
1125 	switch (fs->fs_frag) {
1126 	case 8:
1127 		return (cp[h] == 0xff);
1128 	case 4:
1129 		mask = 0x0f << ((h & 0x1) << 2);
1130 		return ((cp[h >> 1] & mask) == mask);
1131 	case 2:
1132 		mask = 0x03 << ((h & 0x3) << 1);
1133 		return ((cp[h >> 2] & mask) == mask);
1134 	case 1:
1135 		mask = 0x01 << (h & 0x7);
1136 		return ((cp[h >> 3] & mask) == mask);
1137 	default:
1138 		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
1139 		return (0);
1140 	}
1141 }
1142 
1143 /*
1144  * take a block out of the map
1145  */
1146 static void
1147 clrblock(struct fs *fs, unsigned char *cp, int h)
1148 {
1149 	switch ((fs)->fs_frag) {
1150 	case 8:
1151 		cp[h] = 0;
1152 		return;
1153 	case 4:
1154 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1155 		return;
1156 	case 2:
1157 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1158 		return;
1159 	case 1:
1160 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1161 		return;
1162 	default:
1163 		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
1164 		return;
1165 	}
1166 }
1167 
1168 /*
1169  * put a block into the map
1170  */
1171 static void
1172 setblock(struct fs *fs, unsigned char *cp, int h)
1173 {
1174 	switch (fs->fs_frag) {
1175 	case 8:
1176 		cp[h] = 0xff;
1177 		return;
1178 	case 4:
1179 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1180 		return;
1181 	case 2:
1182 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1183 		return;
1184 	case 1:
1185 		cp[h >> 3] |= (0x01 << (h & 0x7));
1186 		return;
1187 	default:
1188 		fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
1189 		return;
1190 	}
1191 }
1192 
1193 /*
1194  * Determine the number of characters in a
1195  * single line.
1196  */
1197 
1198 static int
1199 charsperline(void)
1200 {
1201 	int columns;
1202 	char *cp;
1203 	struct winsize ws;
1204 
1205 	columns = 0;
1206 	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1207 		columns = ws.ws_col;
1208 	if (columns == 0 && (cp = getenv("COLUMNS")))
1209 		columns = atoi(cp);
1210 	if (columns == 0)
1211 		columns = 80;	/* last resort */
1212 	return (columns);
1213 }
1214 
1215 static int
1216 ilog2(int val)
1217 {
1218 	u_int n;
1219 
1220 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
1221 		if (1 << n == val)
1222 			return (n);
1223 	errx(1, "ilog2: %d is not a power of 2\n", val);
1224 }
1225 
1226 /*
1227  * For the regression test, return predictable random values.
1228  * Otherwise use a true random number generator.
1229  */
1230 static u_int32_t
1231 newfs_random(void)
1232 {
1233 	static u_int32_t nextnum = 1;
1234 
1235 	if (Rflag)
1236 		return (nextnum++);
1237 	return (arc4random());
1238 }
1239