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