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