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