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