xref: /openbsd/sbin/newfs/mkfs.c (revision 4bdff4be)
1 /*	$OpenBSD: mkfs.c,v 1.102 2024/01/09 03:16:00 guenther Exp $	*/
2 /*	$NetBSD: mkfs.c,v 1.25 1995/06/18 21:35:38 cgd Exp $	*/
3 
4 /*
5  * Copyright (c) 2002 Networks Associates Technology, Inc.
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Marshall
9  * Kirk McKusick and Network Associates Laboratories, the Security
10  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
11  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
12  * research program.
13  *
14  * Copyright (c) 1980, 1989, 1993
15  *	The Regents of the University of California.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  * 3. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  */
41 
42 #include <sys/param.h>	/* MAXBSIZE DEV_BSIZE roundup btodb setbit */
43 #include <sys/signal.h>
44 #include <sys/time.h>
45 #include <sys/disklabel.h>
46 #include <sys/ioctl.h>
47 #include <sys/mman.h>
48 #include <sys/resource.h>
49 #include <sys/sysctl.h>
50 
51 #include <ufs/ufs/dinode.h>
52 #include <ufs/ufs/dir.h>
53 #include <ufs/ffs/fs.h>
54 
55 #include <err.h>
56 #include <string.h>
57 #include <stdlib.h>
58 #include <stdint.h>
59 #include <unistd.h>
60 #include <limits.h>
61 
62 #ifndef STANDALONE
63 #include <stdio.h>
64 #include <errno.h>
65 #endif
66 
67 #define MINIMUM(a, b)	(((a) < (b)) ? (a) : (b))
68 #define MAXIMUM(a, b)	(((a) > (b)) ? (a) : (b))
69 
70 /*
71  * Default directory umask.
72  */
73 #define UMASK		0755
74 
75 #define POWEROF2(num)	(((num) & ((num) - 1)) == 0)
76 
77 /*
78  * 'Standard' bad FFS magic.
79  */
80 #define FS_BAD_MAGIC	0x19960408
81 
82 /*
83  * The minimum number of cylinder groups that should be created.
84  */
85 #define MINCYLGRPS	4
86 
87 /*
88  * variables set up by front end.
89  */
90 extern int	mfs;		/* run as the memory based filesystem */
91 extern int	Nflag;		/* run mkfs without writing file system */
92 extern int	Oflag;		/* format as an 4.3BSD file system */
93 extern daddr_t fssize;		/* file system size in 512-byte blocks. */
94 extern long long	sectorsize;	/* bytes/sector */
95 extern int	fsize;		/* fragment size */
96 extern int	bsize;		/* block size */
97 extern int	maxfrgspercg;	/* maximum fragments per cylinder group */
98 extern int	minfree;	/* free space threshold */
99 extern int	opt;		/* optimization preference (space or time) */
100 extern int	density;	/* number of bytes per inode */
101 extern int	maxbpg;		/* maximum blocks per file in a cyl group */
102 extern int	avgfilesize;	/* expected average file size */
103 extern int	avgfilesperdir;	/* expected number of files per directory */
104 extern int	quiet;		/* quiet flag */
105 extern caddr_t	membase;	/* start address of memory based filesystem */
106 
107 union fs_u {
108 	struct fs fs;
109 	char pad[SBSIZE];
110 } *fsun;
111 #define sblock	fsun->fs
112 
113 struct	csum *fscs;
114 
115 union cg_u {
116 	struct cg cg;
117 	char pad[MAXBSIZE];
118 } *cgun;
119 #define acg	cgun->cg
120 
121 union dinode {
122 	struct ufs1_dinode dp1;
123 	struct ufs2_dinode dp2;
124 };
125 
126 int	fsi, fso;
127 
128 static caddr_t iobuf;
129 static long iobufsize;
130 
131 daddr_t	alloc(int, int);
132 static int	charsperline(void);
133 static int	ilog2(int);
134 void		initcg(u_int, time_t);
135 void		wtfs(daddr_t, int, void *);
136 int		fsinit1(time_t, mode_t, uid_t, gid_t);
137 int		fsinit2(time_t, mode_t, uid_t, gid_t);
138 int		makedir(struct direct *, int);
139 void		iput(union dinode *, ino_t);
140 void		setblock(struct fs *, unsigned char *, int);
141 void		clrblock(struct fs *, unsigned char *, int);
142 int		isblock(struct fs *, unsigned char *, int);
143 void		rdfs(daddr_t, int, void *);
144 void		mkfs(struct partition *, char *, int, int,
145 		    mode_t, uid_t, gid_t);
146 static		void checksz(void);
147 
148 #ifndef STANDALONE
149 volatile sig_atomic_t cur_cylno;
150 volatile const char *cur_fsys;
151 void	siginfo(int sig);
152 
153 void
154 siginfo(int sig)
155 {
156 	int save_errno = errno;
157 
158 	dprintf(STDERR_FILENO, "%s: initializing cg %ld/%d\n",
159 	    cur_fsys, (long)cur_cylno, sblock.fs_ncg);
160 	errno = save_errno;
161 }
162 #endif
163 
164 void
165 mkfs(struct partition *pp, char *fsys, int fi, int fo, mode_t mfsmode,
166     uid_t mfsuid, gid_t mfsgid)
167 {
168 	time_t utime;
169 	quad_t sizepb;
170 	int i, j, width, origdensity, fragsperinode, minfpg, optimalfpg;
171 	int lastminfpg, mincylgrps;
172 	uint32_t bpg;
173 	long csfrags;
174 	u_int cg;
175 	char tmpbuf[100];	/* XXX this will break in about 2,500 years */
176 
177 	if ((fsun = calloc(1, sizeof (union fs_u))) == NULL ||
178 	    (cgun = calloc(1, sizeof (union cg_u))) == NULL)
179 		err(1, "calloc");
180 
181 #ifndef STANDALONE
182 	time(&utime);
183 #endif
184 	if (mfs) {
185 		size_t sz;
186 		if (fssize > SIZE_MAX / DEV_BSIZE) {
187 			errno = ENOMEM;
188 			err(12, "mmap");
189 		}
190 		sz = (size_t)fssize * DEV_BSIZE;
191 		membase = mmap(NULL, sz, PROT_READ|PROT_WRITE,
192 		    MAP_ANON|MAP_PRIVATE, -1, (off_t)0);
193 		if (membase == MAP_FAILED)
194 			err(12, "mmap");
195 		madvise(membase, sz, MADV_RANDOM);
196 	}
197 	fsi = fi;
198 	fso = fo;
199 	/*
200 	 * Validate the given file system size.
201 	 * Verify that its last block can actually be accessed.
202 	 */
203 	if (Oflag <= 1 && fssize > INT_MAX)
204 		errx(13, "preposterous size %lld, max is %d", (long long)fssize,
205 		    INT_MAX);
206 	if (Oflag == 2 && fssize > MAXDISKSIZE)
207 		errx(13, "preposterous size %lld, max is %lld",
208 		    (long long)fssize, MAXDISKSIZE);
209 
210 	wtfs(fssize - (sectorsize / DEV_BSIZE), sectorsize, (char *)&sblock);
211 
212 	sblock.fs_postblformat = FS_DYNAMICPOSTBLFMT;
213 	sblock.fs_avgfilesize = avgfilesize;
214 	sblock.fs_avgfpdir = avgfilesperdir;
215 
216 	/*
217 	 * Collect and verify the block and fragment sizes.
218 	 */
219 	if (!POWEROF2(bsize)) {
220 		errx(16, "block size must be a power of 2, not %d", bsize);
221 	}
222 	if (!POWEROF2(fsize)) {
223 		errx(17, "fragment size must be a power of 2, not %d",
224 		     fsize);
225 	}
226 	if (fsize < sectorsize) {
227 		errx(18, "fragment size %d is too small, minimum is %lld",
228 		     fsize, sectorsize);
229 	}
230 	if (bsize < MINBSIZE) {
231 		errx(19, "block size %d is too small, minimum is %d",
232 		     bsize, MINBSIZE);
233 	}
234 	if (bsize > MAXBSIZE) {
235 		errx(19, "block size %d is too large, maximum is %d",
236 		     bsize, MAXBSIZE);
237 	}
238 	if (bsize < fsize) {
239 		errx(20, "block size (%d) cannot be smaller than fragment size (%d)",
240 		     bsize, fsize);
241 	}
242 	sblock.fs_bsize = bsize;
243 	sblock.fs_fsize = fsize;
244 
245 	/*
246 	 * Calculate the superblock bitmasks and shifts.
247 	 */
248 	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
249 	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
250 	sblock.fs_qbmask = ~sblock.fs_bmask;
251 	sblock.fs_qfmask = ~sblock.fs_fmask;
252 	sblock.fs_bshift = ilog2(sblock.fs_bsize);
253 	sblock.fs_fshift = ilog2(sblock.fs_fsize);
254 	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
255 	if (sblock.fs_frag > MAXFRAG) {
256 		errx(21, "fragment size %d is too small, minimum with block "
257 		    "size %d is %d", sblock.fs_fsize, sblock.fs_bsize,
258 		    sblock.fs_bsize / MAXFRAG);
259 	}
260 	sblock.fs_fragshift = ilog2(sblock.fs_frag);
261 	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / DEV_BSIZE);
262 	sblock.fs_size = dbtofsb(&sblock, fssize);
263 	sblock.fs_nspf = sblock.fs_fsize / DEV_BSIZE;
264 	sblock.fs_maxcontig = 1;
265 	sblock.fs_nrpos = 1;
266 	sblock.fs_cpg = 1;
267 
268 	/*
269 	 * Before the file system is fully initialized, mark it as invalid.
270 	 */
271 	sblock.fs_magic = FS_BAD_MAGIC;
272 
273 	/*
274 	 * Set the remaining superblock fields.  Note that for FFS1, media
275 	 * geometry fields are set to fake values.  This is for compatibility
276 	 * with really ancient kernels that might still inspect these values.
277 	 */
278 	if (Oflag <= 1) {
279 		sblock.fs_sblockloc = SBLOCK_UFS1;
280 		sblock.fs_nindir = sblock.fs_bsize / sizeof(int32_t);
281 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
282 		sblock.fs_maxsymlinklen = MAXSYMLINKLEN_UFS1;
283 		sblock.fs_inodefmt = FS_44INODEFMT;
284 		sblock.fs_cgoffset = 0;
285 		sblock.fs_cgmask = 0xffffffff;
286 		sblock.fs_ffs1_size = sblock.fs_size;
287 		sblock.fs_rotdelay = 0;
288 		sblock.fs_rps = 60;
289 		sblock.fs_interleave = 1;
290 		sblock.fs_trackskew = 0;
291 		sblock.fs_cpc = 0;
292 	} else {
293 		sblock.fs_inodefmt = FS_44INODEFMT;
294 		sblock.fs_sblockloc = SBLOCK_UFS2;
295 		sblock.fs_nindir = sblock.fs_bsize / sizeof(int64_t);
296 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
297 		sblock.fs_maxsymlinklen = MAXSYMLINKLEN_UFS2;
298 	}
299 	sblock.fs_sblkno =
300 	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
301 		sblock.fs_frag);
302 	sblock.fs_cblkno = (int32_t)(sblock.fs_sblkno +
303 	    roundup(howmany(SBSIZE, sblock.fs_fsize), sblock.fs_frag));
304 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
305 	sblock.fs_maxfilesize = sblock.fs_bsize * NDADDR - 1;
306 	for (sizepb = sblock.fs_bsize, i = 0; i < NIADDR; i++) {
307 		sizepb *= NINDIR(&sblock);
308 		sblock.fs_maxfilesize += sizepb;
309 	}
310 #ifdef notyet
311 	/*
312 	 * It is impossible to create a snapshot in case fs_maxfilesize is
313 	 * smaller than fssize.
314 	 */
315 	if (sblock.fs_maxfilesize < (u_quad_t)fssize)
316 		warnx("WARNING: You will be unable to create snapshots on this "
317 		    "file system. Correct by using a larger blocksize.");
318 #endif
319 	/*
320 	 * Calculate the number of blocks to put into each cylinder group. The
321 	 * first goal is to have at least enough data blocks in each cylinder
322 	 * group to meet the density requirement. Once this goal is achieved
323 	 * we try to expand to have at least mincylgrps cylinder groups. Once
324 	 * this goal is achieved, we pack as many blocks into each cylinder
325 	 * group map as will fit.
326 	 *
327 	 * We start by calculating the smallest number of blocks that we can
328 	 * put into each cylinder group. If this is too big, we reduce the
329 	 * density until it fits.
330 	 */
331 	origdensity = density;
332 	for (;;) {
333 		fragsperinode = MAXIMUM(numfrags(&sblock, density), 1);
334 
335 		minfpg = fragsperinode * INOPB(&sblock);
336 		if (minfpg > sblock.fs_size)
337 			minfpg = sblock.fs_size;
338 
339 		sblock.fs_ipg = INOPB(&sblock);
340 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
341 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
342 		if (sblock.fs_fpg < minfpg)
343 			sblock.fs_fpg = minfpg;
344 
345 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
346 		    INOPB(&sblock));
347 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
348 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
349 		if (sblock.fs_fpg < minfpg)
350 			sblock.fs_fpg = minfpg;
351 
352 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
353 		    INOPB(&sblock));
354 
355 		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
356 			break;
357 
358 		density -= sblock.fs_fsize;
359 	}
360 	if (density != origdensity)
361 		warnx("density reduced from %d to %d bytes per inode",
362 		    origdensity, density);
363 
364 	/*
365 	 * Use a lower value for mincylgrps if the user specified a large
366 	 * number of blocks per cylinder group.  This is needed for, e.g. the
367 	 * install media which needs to pack 2 files very tightly.
368 	 */
369 	mincylgrps = MINCYLGRPS;
370 	if (maxfrgspercg != INT_MAX) {
371 		i = sblock.fs_size / maxfrgspercg;
372 		if (i < MINCYLGRPS)
373 			mincylgrps = i <= 0 ? 1 : i;
374 	}
375 
376 	/*
377 	 * Start packing more blocks into the cylinder group until it cannot
378 	 * grow any larger, the number of cylinder groups drops below
379 	 * mincylgrps, or we reach the requested size.
380 	 */
381 	for (;;) {
382 		sblock.fs_fpg += sblock.fs_frag;
383 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
384 		    INOPB(&sblock));
385 
386 		if (sblock.fs_fpg > maxfrgspercg ||
387 		    sblock.fs_size / sblock.fs_fpg < mincylgrps ||
388 		    CGSIZE(&sblock) > (unsigned long)sblock.fs_bsize)
389 			break;
390 	}
391 	sblock.fs_fpg -= sblock.fs_frag;
392 	sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
393 	    INOPB(&sblock));
394 	if (sblock.fs_fpg > maxfrgspercg)
395 		warnx("can't honour -c: minimum is %d", sblock.fs_fpg);
396 
397 	/*
398 	 * Check to be sure that the last cylinder group has enough blocks to
399 	 * be viable. If it is too small, reduce the number of blocks per
400 	 * cylinder group which will have the effect of moving more blocks into
401 	 * the last cylinder group.
402 	 */
403 	optimalfpg = sblock.fs_fpg;
404 	for (;;) {
405 		sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
406 		lastminfpg = roundup(sblock.fs_iblkno +
407 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
408 		if (sblock.fs_size < lastminfpg)
409 			errx(28, "file system size %jd < minimum size of %d "
410 			    "fragments", (intmax_t)sblock.fs_size, lastminfpg);
411 
412 		if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
413 		    sblock.fs_size % sblock.fs_fpg == 0)
414 			break;
415 
416 		sblock.fs_fpg -= sblock.fs_frag;
417 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
418 		    INOPB(&sblock));
419 	}
420 
421 	if (optimalfpg != sblock.fs_fpg)
422 		warnx("reduced number of fragments per cylinder group from %d"
423 		    " to %d to enlarge last cylinder group", optimalfpg,
424 		    sblock.fs_fpg);
425 
426 	if ((ino_t)sblock.fs_ipg * sblock.fs_ncg >  UINT_MAX)
427 		errx(42, "more than 2^32 inodes, increase density, block or "
428 		    "fragment size");
429 
430 	/*
431 	 * Back to filling superblock fields.
432 	 */
433 	if (Oflag <= 1) {
434 		sblock.fs_spc = sblock.fs_fpg * sblock.fs_nspf;
435 		sblock.fs_nsect = sblock.fs_spc;
436 		sblock.fs_npsect = sblock.fs_spc;
437 		sblock.fs_ncyl = sblock.fs_ncg;
438 	}
439 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
440 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
441 	sblock.fs_csaddr = cgdmin(&sblock, 0);
442 	sblock.fs_cssize =
443 	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
444 
445 	fscs = calloc(1, sblock.fs_cssize);
446 	if (fscs == NULL)
447 		errx(31, "calloc failed");
448 
449 	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
450 	if (sblock.fs_sbsize > SBLOCKSIZE)
451 		sblock.fs_sbsize = SBLOCKSIZE;
452 
453 	sblock.fs_minfree = minfree;
454 	sblock.fs_maxbpg = maxbpg;
455 	sblock.fs_optim = opt;
456 	sblock.fs_cgrotor = 0;
457 	sblock.fs_pendingblocks = 0;
458 	sblock.fs_pendinginodes = 0;
459 	sblock.fs_fmod = 0;
460 	sblock.fs_ronly = 0;
461 	sblock.fs_state = 0;
462 	sblock.fs_clean = 1;
463 	sblock.fs_id[0] = (u_int32_t)utime;
464 	sblock.fs_id[1] = (u_int32_t)arc4random();
465 	sblock.fs_fsmnt[0] = '\0';
466 
467 	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
468 	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
469 	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
470 
471 	sblock.fs_cstotal.cs_nbfree = fragstoblks(&sblock, sblock.fs_dsize) -
472 	    howmany(csfrags, sblock.fs_frag);
473 	sblock.fs_cstotal.cs_nffree = fragnum(&sblock, sblock.fs_size) +
474 	    (fragnum(&sblock, csfrags) > 0 ?
475 	    sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
476 	sblock.fs_cstotal.cs_nifree = sblock.fs_ncg * sblock.fs_ipg - ROOTINO;
477 	sblock.fs_cstotal.cs_ndir = 0;
478 
479 	sblock.fs_dsize -= csfrags;
480 	sblock.fs_time = utime;
481 
482 	if (Oflag <= 1) {
483 		sblock.fs_ffs1_time = sblock.fs_time;
484 		sblock.fs_ffs1_dsize = sblock.fs_dsize;
485 		sblock.fs_ffs1_csaddr = sblock.fs_csaddr;
486 		sblock.fs_ffs1_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
487 		sblock.fs_ffs1_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
488 		sblock.fs_ffs1_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
489 		sblock.fs_ffs1_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
490 	}
491 
492 	/*
493 	 * Dump out summary information about file system.
494 	 */
495 	if (!mfs) {
496 #define B2MBFACTOR (1 / (1024.0 * 1024.0))
497 		printf("%s: %.1fMB in %jd sectors of %lld bytes\n", fsys,
498 		    (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
499 		    (intmax_t)fsbtodb(&sblock, sblock.fs_size) /
500 		    (sectorsize / DEV_BSIZE), sectorsize);
501 		printf("%u cylinder groups of %.2fMB, %d blocks, %u"
502 		    " inodes each\n", sblock.fs_ncg,
503 		    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
504 		    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
505 #undef B2MBFACTOR
506 		checksz();
507 	}
508 
509 	/*
510 	 * Wipe out old FFS1 superblock if necessary.
511 	 */
512 	if (Oflag >= 2) {
513 		union fs_u *fsun1;
514 		struct fs *fs1;
515 
516 		fsun1 = calloc(1, sizeof(union fs_u));
517 		if (fsun1 == NULL)
518 			err(39, "calloc");
519 		fs1 = &fsun1->fs;
520 		rdfs(SBLOCK_UFS1 / DEV_BSIZE, SBSIZE, (char *)fs1);
521 		if (fs1->fs_magic == FS_UFS1_MAGIC) {
522 			fs1->fs_magic = FS_BAD_MAGIC;
523 			wtfs(SBLOCK_UFS1 / DEV_BSIZE, SBSIZE, (char *)fs1);
524 		}
525 		free(fsun1);
526 	}
527 
528 	wtfs((int)sblock.fs_sblockloc / DEV_BSIZE, SBSIZE, (char *)&sblock);
529 	sblock.fs_magic = (Oflag <= 1) ? FS_UFS1_MAGIC : FS_UFS2_MAGIC;
530 
531 	/*
532 	 * Now build the cylinders group blocks and
533 	 * then print out indices of cylinder groups.
534 	 */
535 	if (!quiet)
536 		printf("super-block backups (for fsck -b #) at:\n");
537 #ifndef STANDALONE
538 	else if (!mfs && isatty(STDIN_FILENO)) {
539 		signal(SIGINFO, siginfo);
540 		cur_fsys = fsys;
541 	}
542 #endif
543 	i = 0;
544 	width = charsperline();
545 	/*
546 	* Allocate space for superblock, cylinder group map, and two sets of
547 	* inode blocks.
548 	*/
549 	if (sblock.fs_bsize < SBLOCKSIZE)
550 		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
551 	else
552 		iobufsize = 4 * sblock.fs_bsize;
553 	if ((iobuf = malloc(iobufsize)) == NULL)
554 		errx(38, "cannot allocate I/O buffer");
555 	bzero(iobuf, iobufsize);
556 	/*
557 	 * Make a copy of the superblock into the buffer that we will be
558 	 * writing out in each cylinder group.
559 	 */
560 	bcopy((char *)&sblock, iobuf, SBLOCKSIZE);
561 	for (cg = 0; cg < sblock.fs_ncg; cg++) {
562 		cur_cylno = (sig_atomic_t)cg;
563 		initcg(cg, utime);
564 		if (quiet)
565 			continue;
566 		j = snprintf(tmpbuf, sizeof tmpbuf, " %lld,",
567 		    (long long)fsbtodb(&sblock, cgsblock(&sblock, cg)));
568 		if (j >= sizeof tmpbuf)
569 			j = sizeof tmpbuf - 1;
570 		if (j < 0 || i+j >= width) {
571 			printf("\n");
572 			i = 0;
573 		}
574 		i += j;
575 		printf("%s", tmpbuf);
576 		fflush(stdout);
577 	}
578 	if (!quiet)
579 		printf("\n");
580 	if (Nflag && !mfs)
581 		exit(0);
582 	/*
583 	 * Now construct the initial file system, then write out the superblock.
584 	 */
585 	if (Oflag <= 1) {
586 		if (fsinit1(utime, mfsmode, mfsuid, mfsgid))
587 			errx(32, "fsinit1 failed");
588 		sblock.fs_ffs1_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
589 		sblock.fs_ffs1_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
590 		sblock.fs_ffs1_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
591 		sblock.fs_ffs1_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
592 	} else {
593 		if (fsinit2(utime, mfsmode, mfsuid, mfsgid))
594 			errx(32, "fsinit2 failed");
595 	}
596 
597 	wtfs((int)sblock.fs_sblockloc / DEV_BSIZE, SBSIZE, (char *)&sblock);
598 
599 	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
600 		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
601 		    sblock.fs_cssize - i < sblock.fs_bsize ?
602 		    sblock.fs_cssize - i : sblock.fs_bsize,
603 		    ((char *)fscs) + i);
604 
605 	/*
606 	 * Update information about this partition in pack label, to that it may
607 	 * be updated on disk.
608 	 */
609 	pp->p_fstype = FS_BSDFFS;
610 	pp->p_fragblock =
611 	    DISKLABELV1_FFS_FRAGBLOCK(sblock.fs_fsize, sblock.fs_frag);
612 	bpg = sblock.fs_fpg / sblock.fs_frag;
613 	while (bpg > USHRT_MAX)
614 		bpg >>= 1;
615 	pp->p_cpg = bpg;
616 }
617 
618 /*
619  * Initialize a cylinder group.
620  */
621 void
622 initcg(u_int cg, time_t utime)
623 {
624 	u_int i, j, d, dlower, dupper, blkno, start;
625 	daddr_t cbase, dmax;
626 	struct ufs1_dinode *dp1;
627 	struct ufs2_dinode *dp2;
628 	struct csum *cs;
629 
630 	/*
631 	 * Determine block bounds for cylinder group.  Allow space for
632 	 * super block summary information in first cylinder group.
633 	 */
634 	cbase = cgbase(&sblock, cg);
635 	dmax = cbase + sblock.fs_fpg;
636 	if (dmax > sblock.fs_size)
637 		dmax = sblock.fs_size;
638 	if (fsbtodb(&sblock, cgsblock(&sblock, cg)) + iobufsize / DEV_BSIZE
639 	    > fssize)
640 		errx(40, "inode table does not fit in cylinder group");
641 
642 	dlower = cgsblock(&sblock, cg) - cbase;
643 	dupper = cgdmin(&sblock, cg) - cbase;
644 	if (cg == 0)
645 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
646 	cs = &fscs[cg];
647 	memset(&acg, 0, sblock.fs_cgsize);
648 	acg.cg_ffs2_time = utime;
649 	acg.cg_magic = CG_MAGIC;
650 	acg.cg_cgx = cg;
651 	acg.cg_ffs2_niblk = sblock.fs_ipg;
652 	acg.cg_initediblk = MINIMUM(sblock.fs_ipg, 2 * INOPB(&sblock));
653 	acg.cg_ndblk = dmax - cbase;
654 
655 	start = sizeof(struct cg);
656 	if (Oflag <= 1) {
657 		/* Hack to maintain compatibility with old fsck. */
658 		if (cg == sblock.fs_ncg - 1)
659 			acg.cg_ncyl = 0;
660 		else
661 			acg.cg_ncyl = sblock.fs_cpg;
662 		acg.cg_time = acg.cg_ffs2_time;
663 		acg.cg_ffs2_time = 0;
664 		acg.cg_niblk = acg.cg_ffs2_niblk;
665 		acg.cg_ffs2_niblk = 0;
666 		acg.cg_initediblk = 0;
667 		acg.cg_btotoff = start;
668 		acg.cg_boff = acg.cg_btotoff + sblock.fs_cpg * sizeof(int32_t);
669 		acg.cg_iusedoff = acg.cg_boff +
670 		    sblock.fs_cpg * sizeof(u_int16_t);
671 	} else {
672 		acg.cg_iusedoff = start;
673 	}
674 
675 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
676 	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
677 	if (acg.cg_nextfreeoff > sblock.fs_cgsize)
678 		errx(37, "panic: cylinder group too big: %u > %d",
679 		    acg.cg_nextfreeoff, sblock.fs_cgsize);
680 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
681 	if (cg == 0) {
682 		for (i = 0; i < ROOTINO; i++) {
683 			setbit(cg_inosused(&acg), i);
684 			acg.cg_cs.cs_nifree--;
685 		}
686 	}
687 	if (cg > 0) {
688 		/*
689 		 * In cg 0, space is reserved for boot and super blocks.
690 		 */
691 		for (d = 0; d < dlower; d += sblock.fs_frag) {
692 			blkno = d / sblock.fs_frag;
693 			setblock(&sblock, cg_blksfree(&acg), blkno);
694 			acg.cg_cs.cs_nbfree++;
695 			if (Oflag <= 1) {
696 				cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
697 				cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
698 				    [cbtorpos(&sblock, d)]++;
699 			}
700 		}
701 	}
702 	if ((i = dupper % sblock.fs_frag)) {
703 		acg.cg_frsum[sblock.fs_frag - i]++;
704 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
705 			setbit(cg_blksfree(&acg), dupper);
706 			acg.cg_cs.cs_nffree++;
707 		}
708 	}
709 	for (d = dupper;
710 	    d + sblock.fs_frag <= acg.cg_ndblk;
711 	    d += sblock.fs_frag) {
712 		blkno = d / sblock.fs_frag;
713 		setblock(&sblock, cg_blksfree(&acg), blkno);
714 		acg.cg_cs.cs_nbfree++;
715 		if (Oflag <= 1) {
716 			cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
717 			cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
718 			    [cbtorpos(&sblock, d)]++;
719 		}
720 	}
721 	if (d < acg.cg_ndblk) {
722 		acg.cg_frsum[acg.cg_ndblk - d]++;
723 		for (; d < acg.cg_ndblk; d++) {
724 			setbit(cg_blksfree(&acg), d);
725 			acg.cg_cs.cs_nffree++;
726 		}
727 	}
728 	*cs = acg.cg_cs;
729 
730 	/*
731 	 * Write out the duplicate superblock, the cylinder group map
732 	 * and two blocks worth of inodes in a single write.
733 	 */
734 	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
735 
736 	if (cg == 0 && acg.cg_cs.cs_nbfree == 0)
737 		errx(42, "cg 0: summary info is too large to fit");
738 
739 	bcopy((char *)&acg, &iobuf[start], sblock.fs_cgsize);
740 	start += sblock.fs_bsize;
741 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
742 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
743 	for (i = MINIMUM(sblock.fs_ipg, 2 * INOPB(&sblock)); i != 0; i--) {
744 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
745 			dp1->di_gen = arc4random();
746 			dp1++;
747 		} else {
748 			dp2->di_gen = arc4random();
749 			dp2++;
750 		}
751 	}
752 	wtfs(fsbtodb(&sblock, cgsblock(&sblock, cg)), iobufsize, iobuf);
753 
754 	if (Oflag <= 1) {
755 		/* Initialize inodes for FFS1. */
756 		for (i = 2 * sblock.fs_frag;
757 		    i < sblock.fs_ipg / INOPF(&sblock);
758 		    i += sblock.fs_frag) {
759 			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
760 			for (j = 0; j < INOPB(&sblock); j++) {
761 				dp1->di_gen = arc4random();
762 				dp1++;
763 			}
764 			wtfs(fsbtodb(&sblock, cgimin(&sblock, cg) + i),
765 			    sblock.fs_bsize, &iobuf[start]);
766 		}
767 	}
768 }
769 
770 #define PREDEFDIR 2
771 
772 struct direct root_dir[] = {
773 	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
774 	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
775 };
776 
777 int
778 fsinit1(time_t utime, mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
779 {
780 	union dinode node;
781 
782 	/*
783 	 * Initialize the node
784 	 */
785 	memset(&node, 0, sizeof(node));
786 	node.dp1.di_atime = utime;
787 	node.dp1.di_mtime = utime;
788 	node.dp1.di_ctime = utime;
789 
790 	/*
791 	 * Create the root directory.
792 	 */
793 	if (mfs) {
794 		node.dp1.di_mode = IFDIR | mfsmode;
795 		node.dp1.di_uid = mfsuid;
796 		node.dp1.di_gid = mfsgid;
797 	} else {
798 		node.dp1.di_mode = IFDIR | UMASK;
799 		node.dp1.di_uid = geteuid();
800 		node.dp1.di_gid = getegid();
801 	}
802 	node.dp1.di_nlink = PREDEFDIR;
803 	node.dp1.di_size = makedir(root_dir, PREDEFDIR);
804 	node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
805 	if (node.dp1.di_db[0] == 0)
806 		return (1);
807 
808 	node.dp1.di_blocks = btodb(fragroundup(&sblock, node.dp1.di_size));
809 
810 	wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, iobuf);
811 	iput(&node, ROOTINO);
812 
813 #ifdef notyet
814 	/*
815 	* Create the .snap directory.
816 	*/
817 	node.dp1.di_mode |= 020;
818 	node.dp1.di_gid = gid;
819 	node.dp1.di_nlink = SNAPLINKCNT;
820 	node.dp1.di_size = makedir(snap_dir, SNAPLINKCNT);
821 
822 	node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
823 	if (node.dp1.di_db[0] == 0)
824 		return (1);
825 
826 	node.dp1.di_blocks = btodb(fragroundup(&sblock, node.dp1.di_size));
827 
828 	wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, iobuf);
829 	iput(&node, ROOTINO + 1);
830 #endif
831 	return (0);
832 }
833 
834 int
835 fsinit2(time_t utime, mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
836 {
837 	union dinode node;
838 
839 	/*
840 	 * Initialize the node.
841 	 */
842 	memset(&node, 0, sizeof(node));
843 	node.dp2.di_atime = utime;
844 	node.dp2.di_mtime = utime;
845 	node.dp2.di_ctime = utime;
846 
847 	/*
848 	 * Create the root directory.
849 	 */
850 	if (mfs) {
851 		node.dp2.di_mode = IFDIR | mfsmode;
852 		node.dp2.di_uid = mfsuid;
853 		node.dp2.di_gid = mfsgid;
854 	} else {
855 		node.dp2.di_mode = IFDIR | UMASK;
856 		node.dp2.di_uid = geteuid();
857 		node.dp2.di_gid = getegid();
858 	}
859 	node.dp2.di_nlink = PREDEFDIR;
860 	node.dp2.di_size = makedir(root_dir, PREDEFDIR);
861 
862 	node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
863 	if (node.dp2.di_db[0] == 0)
864 		return (1);
865 
866 	node.dp2.di_blocks = btodb(fragroundup(&sblock, node.dp2.di_size));
867 
868 	wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, iobuf);
869 	iput(&node, ROOTINO);
870 
871 #ifdef notyet
872 	/*
873 	 * Create the .snap directory.
874 	 */
875 	node.dp2.di_mode |= 020;
876 	node.dp2.di_gid = gid;
877 	node.dp2.di_nlink = SNAPLINKCNT;
878 	node.dp2.di_size = makedir(snap_dir, SNAPLINKCNT);
879 
880 	node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
881 	if (node.dp2.di_db[0] == 0)
882 		return (1);
883 
884 	node.dp2.di_blocks = btodb(fragroundup(&sblock, node.dp2.di_size));
885 
886 	wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, iobuf);
887 	iput(&node, ROOTINO + 1);
888 #endif
889 	return (0);
890 }
891 
892 /*
893  * construct a set of directory entries in "buf".
894  * return size of directory.
895  */
896 int
897 makedir(struct direct *protodir, int entries)
898 {
899 	char *cp;
900 	int i, spcleft;
901 
902 	spcleft = DIRBLKSIZ;
903 	for (cp = iobuf, i = 0; i < entries - 1; i++) {
904 		protodir[i].d_reclen = DIRSIZ(&protodir[i]);
905 		memcpy(cp, &protodir[i], protodir[i].d_reclen);
906 		cp += protodir[i].d_reclen;
907 		spcleft -= protodir[i].d_reclen;
908 	}
909 	protodir[i].d_reclen = spcleft;
910 	memcpy(cp, &protodir[i], DIRSIZ(&protodir[i]));
911 	return (DIRBLKSIZ);
912 }
913 
914 /*
915  * allocate a block or frag
916  */
917 daddr_t
918 alloc(int size, int mode)
919 {
920 	int i, frag;
921 	daddr_t d, blkno;
922 
923 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
924 	    (char *)&acg);
925 	if (acg.cg_magic != CG_MAGIC) {
926 		warnx("cg 0: bad magic number");
927 		return (0);
928 	}
929 	if (acg.cg_cs.cs_nbfree == 0) {
930 		warnx("first cylinder group ran out of space");
931 		return (0);
932 	}
933 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
934 		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
935 			goto goth;
936 	warnx("internal error: can't find block in cyl 0");
937 	return (0);
938 goth:
939 	blkno = fragstoblks(&sblock, d);
940 	clrblock(&sblock, cg_blksfree(&acg), blkno);
941 	acg.cg_cs.cs_nbfree--;
942 	sblock.fs_cstotal.cs_nbfree--;
943 	fscs[0].cs_nbfree--;
944 	if (mode & IFDIR) {
945 		acg.cg_cs.cs_ndir++;
946 		sblock.fs_cstotal.cs_ndir++;
947 		fscs[0].cs_ndir++;
948 	}
949 	if (Oflag <= 1) {
950 		cg_blktot(&acg)[cbtocylno(&sblock, d)]--;
951 		cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
952 		    [cbtorpos(&sblock, d)]--;
953 	}
954 	if (size != sblock.fs_bsize) {
955 		frag = howmany(size, sblock.fs_fsize);
956 		fscs[0].cs_nffree += sblock.fs_frag - frag;
957 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
958 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
959 		acg.cg_frsum[sblock.fs_frag - frag]++;
960 		for (i = frag; i < sblock.fs_frag; i++)
961 			setbit(cg_blksfree(&acg), d + i);
962 	}
963 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
964 	    (char *)&acg);
965 	return (d);
966 }
967 
968 /*
969  * Allocate an inode on the disk
970  */
971 void
972 iput(union dinode *ip, ino_t ino)
973 {
974 	daddr_t d;
975 
976 	if (Oflag <= 1)
977 		ip->dp1.di_gen = arc4random();
978 	else
979 		ip->dp2.di_gen = arc4random();
980 
981 	rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
982 	    (char *)&acg);
983 	if (acg.cg_magic != CG_MAGIC)
984 		errx(41, "cg 0: bad magic number");
985 
986 	acg.cg_cs.cs_nifree--;
987 	setbit(cg_inosused(&acg), ino);
988 
989 	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
990 	    (char *)&acg);
991 
992 	sblock.fs_cstotal.cs_nifree--;
993 	fscs[0].cs_nifree--;
994 	if (ino >= sblock.fs_ipg * sblock.fs_ncg)
995 		errx(32, "fsinit: inode value %llu out of range",
996 		    (unsigned long long)ino);
997 	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
998 	rdfs(d, sblock.fs_bsize, iobuf);
999 
1000 	if (Oflag <= 1)
1001 		((struct ufs1_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
1002 		    ip->dp1;
1003 	else
1004 		((struct ufs2_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
1005 		    ip->dp2;
1006 
1007 	wtfs(d, sblock.fs_bsize, iobuf);
1008 }
1009 
1010 /*
1011  * read a block from the file system
1012  */
1013 void
1014 rdfs(daddr_t bno, int size, void *bf)
1015 {
1016 	int n;
1017 
1018 	if (mfs) {
1019 		memcpy(bf, membase + bno * DEV_BSIZE, size);
1020 		return;
1021 	}
1022 	n = pread(fsi, bf, size, (off_t)bno * DEV_BSIZE);
1023 	if (n != size) {
1024 		err(34, "rdfs: read error on block %lld", (long long)bno);
1025 	}
1026 }
1027 
1028 /*
1029  * write a block to the file system
1030  */
1031 void
1032 wtfs(daddr_t bno, int size, void *bf)
1033 {
1034 	int n;
1035 
1036 	if (mfs) {
1037 		memcpy(membase + bno * DEV_BSIZE, bf, size);
1038 		return;
1039 	}
1040 	if (Nflag)
1041 		return;
1042 	n = pwrite(fso, bf, size, (off_t)bno * DEV_BSIZE);
1043 	if (n != size) {
1044 		err(36, "wtfs: write error on block %lld", (long long)bno);
1045 	}
1046 }
1047 
1048 /*
1049  * check if a block is available
1050  */
1051 int
1052 isblock(struct fs *fs, unsigned char *cp, int h)
1053 {
1054 	unsigned char mask;
1055 
1056 	switch (fs->fs_frag) {
1057 	case 8:
1058 		return (cp[h] == 0xff);
1059 	case 4:
1060 		mask = 0x0f << ((h & 0x1) << 2);
1061 		return ((cp[h >> 1] & mask) == mask);
1062 	case 2:
1063 		mask = 0x03 << ((h & 0x3) << 1);
1064 		return ((cp[h >> 2] & mask) == mask);
1065 	case 1:
1066 		mask = 0x01 << (h & 0x7);
1067 		return ((cp[h >> 3] & mask) == mask);
1068 	default:
1069 #ifdef STANDALONE
1070 		printf("isblock bad fs_frag %d\n", fs->fs_frag);
1071 #else
1072 		warnx("isblock bad fs_frag %d", fs->fs_frag);
1073 #endif
1074 		return (0);
1075 	}
1076 }
1077 
1078 /*
1079  * take a block out of the map
1080  */
1081 void
1082 clrblock(struct fs *fs, unsigned char *cp, int h)
1083 {
1084 	switch ((fs)->fs_frag) {
1085 	case 8:
1086 		cp[h] = 0;
1087 		return;
1088 	case 4:
1089 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1090 		return;
1091 	case 2:
1092 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1093 		return;
1094 	case 1:
1095 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1096 		return;
1097 	default:
1098 #ifdef STANDALONE
1099 		printf("clrblock bad fs_frag %d\n", fs->fs_frag);
1100 #else
1101 		warnx("clrblock bad fs_frag %d", fs->fs_frag);
1102 #endif
1103 		return;
1104 	}
1105 }
1106 
1107 /*
1108  * put a block into the map
1109  */
1110 void
1111 setblock(struct fs *fs, unsigned char *cp, int h)
1112 {
1113 	switch (fs->fs_frag) {
1114 	case 8:
1115 		cp[h] = 0xff;
1116 		return;
1117 	case 4:
1118 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1119 		return;
1120 	case 2:
1121 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1122 		return;
1123 	case 1:
1124 		cp[h >> 3] |= (0x01 << (h & 0x7));
1125 		return;
1126 	default:
1127 #ifdef STANDALONE
1128 		printf("setblock bad fs_frag %d\n", fs->fs_frag);
1129 #else
1130 		warnx("setblock bad fs_frag %d", fs->fs_frag);
1131 #endif
1132 		return;
1133 	}
1134 }
1135 
1136 /*
1137  * Determine the number of characters in a
1138  * single line.
1139  */
1140 static int
1141 charsperline(void)
1142 {
1143 	int columns;
1144 	char *cp;
1145 	struct winsize ws;
1146 
1147 	columns = 0;
1148 	if ((cp = getenv("COLUMNS")) != NULL)
1149 		columns = strtonum(cp, 1, INT_MAX, NULL);
1150 	if (columns == 0 && ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 &&
1151 	    ws.ws_col > 0)
1152 		columns = ws.ws_col;
1153 	if (columns == 0)
1154 		columns = 80;
1155 
1156 	return columns;
1157 }
1158 
1159 static int
1160 ilog2(int val)
1161 {
1162 	int n;
1163 
1164 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
1165 		if (1 << n == val)
1166 			return (n);
1167 
1168 	errx(1, "ilog2: %d is not a power of 2\n", val);
1169 }
1170 
1171 struct inoinfo {
1172         struct  inoinfo *i_nexthash;    /* next entry in hash chain */
1173         struct  inoinfo *i_child, *i_sibling, *i_parentp;
1174         size_t  i_isize;                /* size of inode */
1175         ino_t   i_number;               /* inode number of this entry */
1176         ino_t   i_parent;               /* inode number of parent */
1177 
1178         ino_t   i_dotdot;               /* inode number of `..' */
1179         u_int   i_numblks;              /* size of block array in bytes */
1180         daddr_t i_blks[1];              /* actually longer */
1181 };
1182 
1183 static void
1184 checksz(void)
1185 {
1186 	unsigned long long allocate, maxino, maxfsblock, ndir, bound;
1187 	extern int64_t physmem;
1188 	struct rlimit datasz;
1189 
1190 	if (getrlimit(RLIMIT_DATA, &datasz) != 0)
1191 		err(1, "can't get rlimit");
1192 
1193 	bound = MINIMUM(datasz.rlim_max, physmem);
1194 
1195 	allocate = 0;
1196 	maxino = sblock.fs_ncg * (unsigned long long)sblock.fs_ipg;
1197 	maxfsblock = sblock.fs_size;
1198 	ndir = maxino / avgfilesperdir;
1199 
1200 	allocate += roundup(howmany(maxfsblock, NBBY), sizeof(int16_t));
1201 	allocate += (maxino + 1) * 3;
1202 	allocate += sblock.fs_ncg * sizeof(long);
1203 	allocate += (MAXIMUM(ndir, 128) + 10) * sizeof(struct inoinfo);
1204 	allocate += MAXIMUM(ndir, 128) * sizeof(struct inoinfo);
1205 
1206 	if (allocate > bound)
1207 		warnx("warning: fsck_ffs will need %lluMB; "
1208 		    "min(ulimit -dH,physmem) is %lluMB",
1209 		    allocate / (1024ULL * 1024ULL),
1210 		    bound / (1024ULL * 1024ULL));
1211 }
1212