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