xref: /netbsd-src/sbin/newfs/mkfs.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: mkfs.c,v 1.128 2017/02/08 16:11:40 rin Exp $	*/
2 
3 /*
4  * Copyright (c) 1980, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 2002 Networks Associates Technology, Inc.
34  * All rights reserved.
35  *
36  * This software was developed for the FreeBSD Project by Marshall
37  * Kirk McKusick and Network Associates Laboratories, the Security
38  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
39  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
40  * research program
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed by the University of
53  *	California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 #include <sys/cdefs.h>
72 #ifndef lint
73 #if 0
74 static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
75 #else
76 __RCSID("$NetBSD: mkfs.c,v 1.128 2017/02/08 16:11:40 rin Exp $");
77 #endif
78 #endif /* not lint */
79 
80 #include <sys/param.h>
81 #include <sys/mman.h>
82 #include <sys/time.h>
83 #include <sys/resource.h>
84 #include <ufs/ufs/dinode.h>
85 #include <ufs/ufs/dir.h>
86 #include <ufs/ufs/ufs_bswap.h>
87 #include <ufs/ufs/quota2.h>
88 #include <ufs/ffs/fs.h>
89 #include <ufs/ffs/ffs_extern.h>
90 #include <sys/ioctl.h>
91 #include <sys/disklabel.h>
92 
93 #include <err.h>
94 #include <errno.h>
95 #include <string.h>
96 #include <unistd.h>
97 #include <stdlib.h>
98 #include <stddef.h>
99 
100 #ifndef STANDALONE
101 #include <stdio.h>
102 #endif
103 
104 #include "extern.h"
105 
106 union dinode {
107 	struct ufs1_dinode dp1;
108 	struct ufs2_dinode dp2;
109 };
110 
111 static void initcg(int, const struct timeval *);
112 static int fsinit(const struct timeval *, mode_t, uid_t, gid_t);
113 union Buffer;
114 static int makedir(union Buffer *, struct direct *, int);
115 static daddr_t alloc(int, int);
116 static void iput(union dinode *, ino_t);
117 static void rdfs(daddr_t, int, void *);
118 static void wtfs(daddr_t, int, void *);
119 static int isblock(struct fs *, unsigned char *, int);
120 static void clrblock(struct fs *, unsigned char *, int);
121 static void setblock(struct fs *, unsigned char *, int);
122 static int ilog2(int);
123 static void zap_old_sblock(int);
124 #ifdef MFS
125 static void *mkfs_malloc(size_t size);
126 #endif
127 
128 /*
129  * make file system for cylinder-group style file systems
130  */
131 #define	UMASK		0755
132 
133 union {
134 	struct fs fs;
135 	char data[SBLOCKSIZE];
136 } *fsun;
137 #define	sblock	fsun->fs
138 
139 union Buffer {
140 	struct quota2_header q2h;
141 	char data[MAXBSIZE];
142 };
143 
144 struct	csum *fscs_0;		/* first block of cylinder summaries */
145 struct	csum *fscs_next;	/* place for next summary */
146 struct	csum *fscs_end;		/* end of summary buffer */
147 struct	csum *fscs_reset;	/* place for next summary after write */
148 uint	fs_csaddr;		/* fragment number to write to */
149 
150 union {
151 	struct cg cg;
152 	char pad[MAXBSIZE];
153 } *cgun;
154 #define	acg	cgun->cg
155 
156 #define DIP(dp, field) \
157 	((sblock.fs_magic == FS_UFS1_MAGIC) ? \
158 	(dp)->dp1.di_##field : (dp)->dp2.di_##field)
159 
160 #define EXT2FS_SBOFF	1024	/* XXX: SBOFF in <ufs/ext2fs/ext2fs.h> */
161 
162 char *iobuf;
163 int iobufsize;			/* size to end of 2nd inode block */
164 int iobuf_memsize;		/* Actual buffer size */
165 
166 int	fsi, fso;
167 
168 static void
169 fserr(int num)
170 {
171 #ifdef GARBAGE
172 	extern int Gflag;
173 
174 	if (Gflag)
175 		return;
176 #endif
177 	exit(num);
178 }
179 
180 void
181 mkfs(const char *fsys, int fi, int fo,
182     mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
183 {
184 	uint fragsperinodeblk, ncg, u;
185 	uint cgzero;
186 	uint64_t inodeblks, cgall;
187 	int32_t cylno, i, csfrags;
188 	int inodes_per_cg;
189 	struct timeval tv;
190 	long long sizepb;
191 	int len, col, delta, fld_width, max_cols;
192 	struct winsize winsize;
193 
194 #ifndef STANDALONE
195 	gettimeofday(&tv, NULL);
196 #endif
197 #ifdef MFS
198 	if (mfs && !Nflag) {
199 		if ((membase = mkfs_malloc(fssize * sectorsize)) == NULL)
200 			exit(12);
201 	}
202 #endif
203 	if ((fsun = calloc(1, sizeof(*fsun))) == NULL)
204 		exit(12);
205 	if ((cgun = calloc(1, sizeof(*cgun))) == NULL)
206 		exit(12);
207 
208 	fsi = fi;
209 	fso = fo;
210 	if (Oflag == 0) {
211 		sblock.fs_old_inodefmt = FS_42INODEFMT;
212 		sblock.fs_maxsymlinklen = 0;
213 		sblock.fs_old_flags = 0;
214 	} else {
215 		sblock.fs_old_inodefmt = FS_44INODEFMT;
216 		sblock.fs_maxsymlinklen = (Oflag == 1 ? UFS1_MAXSYMLINKLEN :
217 		    UFS2_MAXSYMLINKLEN);
218 		sblock.fs_old_flags = FS_FLAGS_UPDATED;
219 		if (isappleufs)
220 			sblock.fs_old_flags = 0;
221 		sblock.fs_flags = 0;
222 	}
223 
224 	/*
225 	 * collect and verify the filesystem density info
226 	 */
227 	sblock.fs_avgfilesize = avgfilesize;
228 	sblock.fs_avgfpdir = avgfpdir;
229 	if (sblock.fs_avgfilesize <= 0) {
230 		printf("illegal expected average file size %d\n",
231 		    sblock.fs_avgfilesize);
232 		fserr(14);
233 	}
234 	if (sblock.fs_avgfpdir <= 0) {
235 		printf("illegal expected number of files per directory %d\n",
236 		    sblock.fs_avgfpdir);
237 		fserr(15);
238 	}
239 	/*
240 	 * collect and verify the block and fragment sizes
241 	 */
242 	sblock.fs_bsize = bsize;
243 	sblock.fs_fsize = fsize;
244 	if (!powerof2(sblock.fs_bsize)) {
245 		printf("block size must be a power of 2, not %d\n",
246 		    sblock.fs_bsize);
247 		fserr(16);
248 	}
249 	if (!powerof2(sblock.fs_fsize)) {
250 		printf("fragment size must be a power of 2, not %d\n",
251 		    sblock.fs_fsize);
252 		fserr(17);
253 	}
254 	if (sblock.fs_fsize < sectorsize) {
255 		printf("fragment size %d is too small, minimum is %d\n",
256 		    sblock.fs_fsize, sectorsize);
257 		fserr(18);
258 	}
259 	if (sblock.fs_bsize < MINBSIZE) {
260 		printf("block size %d is too small, minimum is %d\n",
261 		    sblock.fs_bsize, MINBSIZE);
262 		fserr(19);
263 	}
264 	if (sblock.fs_bsize > MAXBSIZE) {
265 		printf("block size %d is too large, maximum is %d\n",
266 		    sblock.fs_bsize, MAXBSIZE);
267 		fserr(19);
268 	}
269 	if (sblock.fs_bsize < sblock.fs_fsize) {
270 		printf("block size (%d) cannot be smaller than fragment size (%d)\n",
271 		    sblock.fs_bsize, sblock.fs_fsize);
272 		fserr(20);
273 	}
274 
275 	if (maxbsize < bsize || !powerof2(maxbsize)) {
276 		sblock.fs_maxbsize = sblock.fs_bsize;
277 	} else if (sblock.fs_maxbsize > FS_MAXCONTIG * sblock.fs_bsize) {
278 		sblock.fs_maxbsize = FS_MAXCONTIG * sblock.fs_bsize;
279 	} else {
280 		sblock.fs_maxbsize = maxbsize;
281 	}
282 	sblock.fs_maxcontig = maxcontig;
283 	if (sblock.fs_maxcontig < sblock.fs_maxbsize / sblock.fs_bsize) {
284 		sblock.fs_maxcontig = sblock.fs_maxbsize / sblock.fs_bsize;
285 		if (verbosity > 0)
286 			printf("Maxcontig raised to %d\n", sblock.fs_maxbsize);
287 	}
288 	if (sblock.fs_maxcontig > 1)
289 		sblock.fs_contigsumsize = MIN(sblock.fs_maxcontig,FS_MAXCONTIG);
290 
291 	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
292 	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
293 	sblock.fs_qbmask = ~sblock.fs_bmask;
294 	sblock.fs_qfmask = ~sblock.fs_fmask;
295 	for (sblock.fs_bshift = 0, i = sblock.fs_bsize; i > 1; i >>= 1)
296 		sblock.fs_bshift++;
297 	for (sblock.fs_fshift = 0, i = sblock.fs_fsize; i > 1; i >>= 1)
298 		sblock.fs_fshift++;
299 	sblock.fs_frag = ffs_numfrags(&sblock, sblock.fs_bsize);
300 	for (sblock.fs_fragshift = 0, i = sblock.fs_frag; i > 1; i >>= 1)
301 		sblock.fs_fragshift++;
302 	if (sblock.fs_frag > MAXFRAG) {
303 		printf("fragment size %d is too small, "
304 			"minimum with block size %d is %d\n",
305 		    sblock.fs_fsize, sblock.fs_bsize,
306 		    sblock.fs_bsize / MAXFRAG);
307 		fserr(21);
308 	}
309 	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / sectorsize);
310 	sblock.fs_size = FFS_DBTOFSB(&sblock, fssize);
311 	if (Oflag <= 1) {
312 		if ((uint64_t)sblock.fs_size >= 1ull << 31) {
313 			printf("Too many fragments (0x%" PRIx64
314 			    ") for a FFSv1 filesystem\n", sblock.fs_size);
315 			fserr(22);
316 		}
317 		sblock.fs_magic = FS_UFS1_MAGIC;
318 		sblock.fs_sblockloc = SBLOCK_UFS1;
319 		sblock.fs_nindir = sblock.fs_bsize / sizeof(int32_t);
320 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
321 		sblock.fs_old_cgoffset = 0;
322 		sblock.fs_old_cgmask = 0xffffffff;
323 		sblock.fs_old_size = sblock.fs_size;
324 		sblock.fs_old_rotdelay = 0;
325 		sblock.fs_old_rps = 60;
326 		sblock.fs_old_nspf = sblock.fs_fsize / sectorsize;
327 		sblock.fs_old_cpg = 1;
328 		sblock.fs_old_interleave = 1;
329 		sblock.fs_old_trackskew = 0;
330 		sblock.fs_old_cpc = 0;
331 		sblock.fs_old_postblformat = FS_DYNAMICPOSTBLFMT;
332 		sblock.fs_old_nrpos = 1;
333 	} else {
334 		sblock.fs_magic = FS_UFS2_MAGIC;
335 		sblock.fs_sblockloc = SBLOCK_UFS2;
336 		sblock.fs_nindir = sblock.fs_bsize / sizeof(int64_t);
337 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
338 	}
339 
340 	sblock.fs_sblkno =
341 	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
342 		sblock.fs_frag);
343 	sblock.fs_cblkno = (daddr_t)(sblock.fs_sblkno +
344 	    roundup(howmany(SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag));
345 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
346 	sblock.fs_maxfilesize = sblock.fs_bsize * UFS_NDADDR - 1;
347 	for (sizepb = sblock.fs_bsize, i = 0; i < UFS_NIADDR; i++) {
348 		sizepb *= FFS_NINDIR(&sblock);
349 		sblock.fs_maxfilesize += sizepb;
350 	}
351 
352 	/*
353 	 * Calculate the number of blocks to put into each cylinder group.
354 	 *
355 	 * The cylinder group size is limited because the data structure
356 	 * must fit into a single block.
357 	 * We try to have as few cylinder groups as possible, with a proviso
358 	 * that we create at least MINCYLGRPS (==4) except for small
359 	 * filesystems.
360 	 *
361 	 * This algorithm works out how many blocks of inodes would be
362 	 * needed to fill the entire volume at the specified density.
363 	 * It then looks at how big the 'cylinder block' would have to
364 	 * be and, assuming that it is linearly related to the number
365 	 * of inodes and blocks how many cylinder groups are needed to
366 	 * keep the cylinder block below the filesystem block size.
367 	 *
368 	 * The cylinder groups are then all created with the average size.
369 	 *
370 	 * Space taken by the red tape on cylinder groups other than the
371 	 * first is ignored.
372 	 */
373 
374 	/* There must be space for 1 inode block and 2 data blocks */
375 	if (sblock.fs_size < sblock.fs_iblkno + 3 * sblock.fs_frag) {
376 		printf("Filesystem size %lld < minimum size of %d\n",
377 		    (long long)sblock.fs_size, sblock.fs_iblkno + 3 * sblock.fs_frag);
378 		fserr(23);
379 	}
380 	if (num_inodes != 0)
381 		inodeblks = howmany(num_inodes, FFS_INOPB(&sblock));
382 	else {
383 		/*
384 		 * Calculate 'per inode block' so we can allocate less than
385 		 * 1 fragment per inode - useful for /dev.
386 		 */
387 		fragsperinodeblk = MAX(ffs_numfrags(&sblock,
388 					(uint64_t)density * FFS_INOPB(&sblock)), 1);
389 		inodeblks = (sblock.fs_size - sblock.fs_iblkno) /
390 			(sblock.fs_frag + fragsperinodeblk);
391 	}
392 	if (inodeblks == 0)
393 		inodeblks = 1;
394 	/* Ensure that there are at least 2 data blocks (or we fail below) */
395 	if (inodeblks > (uint64_t)(sblock.fs_size - sblock.fs_iblkno)/sblock.fs_frag - 2)
396 		inodeblks = (sblock.fs_size-sblock.fs_iblkno)/sblock.fs_frag-2;
397 	/* Even UFS2 limits number of inodes to 2^31 (fs_ipg is int32_t) */
398 	if (inodeblks * FFS_INOPB(&sblock) >= 1ull << 31)
399 		inodeblks = ((1ull << 31) - NBBY) / FFS_INOPB(&sblock);
400 	/*
401 	 * See what would happen if we tried to use 1 cylinder group.
402 	 * Assume space linear, so work out number of cylinder groups needed.
403 	 */
404 	cgzero = CGSIZE_IF(&sblock, 0, 0);
405 	cgall = CGSIZE_IF(&sblock, inodeblks * FFS_INOPB(&sblock), sblock.fs_size);
406 	ncg = howmany(cgall - cgzero, sblock.fs_bsize - cgzero);
407 	if (ncg < MINCYLGRPS) {
408 		/*
409 		 * We would like to allocate MINCLYGRPS cylinder groups,
410 		 * but for small file sytems (especially ones with a lot
411 		 * of inodes) this is not desirable (or possible).
412 		 */
413 		u = sblock.fs_size / 2 / (sblock.fs_iblkno +
414 						inodeblks * sblock.fs_frag);
415 		if (u > ncg)
416 			ncg = u;
417 		if (ncg > MINCYLGRPS)
418 			ncg = MINCYLGRPS;
419 		if (ncg > inodeblks)
420 			ncg = inodeblks;
421 	}
422 	/*
423 	 * Put an equal number of blocks in each cylinder group.
424 	 * Round up so we don't have more fragments in the last CG than
425 	 * the earlier ones (does that matter?), but kill a block if the
426 	 * CGSIZE becomes too big (only happens if there are a lot of CGs).
427 	 */
428 	sblock.fs_fpg = roundup(howmany(sblock.fs_size, ncg), sblock.fs_frag);
429 	/* Round up the fragments/group so the bitmap bytes are full */
430 	sblock.fs_fpg = roundup(sblock.fs_fpg, NBBY);
431 	inodes_per_cg = ((inodeblks - 1) / ncg + 1) * FFS_INOPB(&sblock);
432 
433 	i = CGSIZE_IF(&sblock, inodes_per_cg, sblock.fs_fpg);
434 	if (i > sblock.fs_bsize) {
435 		sblock.fs_fpg -= (i - sblock.fs_bsize) * NBBY;
436 		/* ... and recalculate how many cylinder groups we now need */
437 		ncg = howmany(sblock.fs_size, sblock.fs_fpg);
438 		inodes_per_cg = ((inodeblks - 1) / ncg + 1) * FFS_INOPB(&sblock);
439 	}
440 	sblock.fs_ipg = inodes_per_cg;
441 	/* Sanity check on our sums... */
442 	if ((int)CGSIZE(&sblock) > sblock.fs_bsize) {
443 		printf("CGSIZE miscalculated %d > %d\n",
444 		    (int)CGSIZE(&sblock), sblock.fs_bsize);
445 		fserr(24);
446 	}
447 
448 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / FFS_INOPF(&sblock);
449 	/* Check that the last cylinder group has enough space for the inodes */
450 	i = sblock.fs_size - sblock.fs_fpg * (ncg - 1ull);
451 	if (i < sblock.fs_dblkno) {
452 		/*
453 		 * Since we make all the cylinder groups the same size, the
454 		 * last will only be small if there are a large number of
455 		 * cylinder groups. If we pull even a fragment from each
456 		 * of the other groups then the last CG will be overfull.
457 		 * So we just kill the last CG.
458 		 */
459 		ncg--;
460 		sblock.fs_size -= i;
461 	}
462 	sblock.fs_ncg = ncg;
463 
464 	sblock.fs_cgsize = ffs_fragroundup(&sblock, CGSIZE(&sblock));
465 	if (Oflag <= 1) {
466 		sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
467 		sblock.fs_old_nsect = sblock.fs_old_spc;
468 		sblock.fs_old_npsect = sblock.fs_old_spc;
469 		sblock.fs_old_ncyl = sblock.fs_ncg;
470 	}
471 
472 	/*
473 	 * Cylinder group summary information for each cylinder is written
474 	 * into the first cylinder group.
475 	 * Write this fragment by fragment, but doing the first CG last
476 	 * (after we've taken stuff off for the structure itself and the
477 	 * root directory.
478 	 */
479 	sblock.fs_csaddr = cgdmin(&sblock, 0);
480 	sblock.fs_cssize =
481 	    ffs_fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
482 	if (512 % sizeof *fscs_0)
483 		errx(1, "cylinder group summary doesn't fit in sectors");
484 	fscs_0 = mmap(0, 2 * sblock.fs_fsize, PROT_READ|PROT_WRITE,
485 			MAP_ANON|MAP_PRIVATE, -1, 0);
486 	if (fscs_0 == MAP_FAILED)
487 		exit(39);
488 	memset(fscs_0, 0, 2 * sblock.fs_fsize);
489 	fs_csaddr = sblock.fs_csaddr;
490 	fscs_next = fscs_0;
491 	fscs_end = (void *)((char *)fscs_0 + 2 * sblock.fs_fsize);
492 	fscs_reset = (void *)((char *)fscs_0 + sblock.fs_fsize);
493 	/*
494 	 * fill in remaining fields of the super block
495 	 */
496 	sblock.fs_sbsize = ffs_fragroundup(&sblock, sizeof(struct fs));
497 	if (sblock.fs_sbsize > SBLOCKSIZE)
498 		sblock.fs_sbsize = SBLOCKSIZE;
499 	sblock.fs_minfree = minfree;
500 	sblock.fs_maxcontig = maxcontig;
501 	sblock.fs_maxbpg = maxbpg;
502 	sblock.fs_optim = opt;
503 	sblock.fs_cgrotor = 0;
504 	sblock.fs_pendingblocks = 0;
505 	sblock.fs_pendinginodes = 0;
506 	sblock.fs_cstotal.cs_ndir = 0;
507 	sblock.fs_cstotal.cs_nbfree = 0;
508 	sblock.fs_cstotal.cs_nifree = 0;
509 	sblock.fs_cstotal.cs_nffree = 0;
510 	sblock.fs_fmod = 0;
511 	sblock.fs_ronly = 0;
512 	sblock.fs_state = 0;
513 	sblock.fs_clean = FS_ISCLEAN;
514 	sblock.fs_ronly = 0;
515 	sblock.fs_id[0] = (long)tv.tv_sec;	/* XXXfvdl huh? */
516 	sblock.fs_id[1] = arc4random() & INT32_MAX;
517 	sblock.fs_fsmnt[0] = '\0';
518 	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
519 	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
520 	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
521 	sblock.fs_cstotal.cs_nbfree =
522 	    ffs_fragstoblks(&sblock, sblock.fs_dsize) -
523 	    howmany(csfrags, sblock.fs_frag);
524 	sblock.fs_cstotal.cs_nffree =
525 	    ffs_fragnum(&sblock, sblock.fs_size) +
526 	    (ffs_fragnum(&sblock, csfrags) > 0 ?
527 	    sblock.fs_frag - ffs_fragnum(&sblock, csfrags) : 0);
528 	sblock.fs_cstotal.cs_nifree = sblock.fs_ncg * sblock.fs_ipg - UFS_ROOTINO;
529 	sblock.fs_cstotal.cs_ndir = 0;
530 	sblock.fs_dsize -= csfrags;
531 	sblock.fs_time = tv.tv_sec;
532 	if (Oflag <= 1) {
533 		sblock.fs_old_time = tv.tv_sec;
534 		sblock.fs_old_dsize = sblock.fs_dsize;
535 		sblock.fs_old_csaddr = sblock.fs_csaddr;
536 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
537 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
538 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
539 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
540 	}
541 	/* add quota data in superblock */
542 	if (quotas) {
543 		sblock.fs_flags |= FS_DOQUOTA2;
544 		sblock.fs_quota_magic = Q2_HEAD_MAGIC;
545 		sblock.fs_quota_flags = quotas;
546 	}
547 	/*
548 	 * Dump out summary information about file system.
549 	 */
550 	if (verbosity > 0) {
551 #define	B2MBFACTOR (1 / (1024.0 * 1024.0))
552 		printf("%s: %.1fMB (%lld sectors) block size %d, "
553 		       "fragment size %d\n",
554 		    fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
555 		    (long long)FFS_FSBTODB(&sblock, sblock.fs_size),
556 		    sblock.fs_bsize, sblock.fs_fsize);
557 		printf("\tusing %d cylinder groups of %.2fMB, %d blks, "
558 		       "%d inodes.\n",
559 		    sblock.fs_ncg,
560 		    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
561 		    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
562 #undef B2MBFACTOR
563 	}
564 
565 	/*
566 	 * allocate space for superblock, cylinder group map, and
567 	 * two sets of inode blocks.
568 	 */
569 	if (sblock.fs_bsize < SBLOCKSIZE)
570 		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
571 	else
572 		iobufsize = 4 * sblock.fs_bsize;
573 	iobuf_memsize = iobufsize;
574 	if (!mfs && sblock.fs_magic == FS_UFS1_MAGIC) {
575 		/* A larger buffer so we can write multiple inode blks */
576 		iobuf_memsize += 14 * sblock.fs_bsize;
577 	}
578 	for (;;) {
579 		iobuf = mmap(0, iobuf_memsize, PROT_READ|PROT_WRITE,
580 				MAP_ANON|MAP_PRIVATE, -1, 0);
581 		if (iobuf != MAP_FAILED)
582 			break;
583 		if (iobuf_memsize != iobufsize) {
584 			/* Try again with the smaller size */
585 			iobuf_memsize = iobufsize;
586 			continue;
587 		}
588 		printf("Cannot allocate I/O buffer\n");
589 		exit(38);
590 	}
591 	memset(iobuf, 0, iobuf_memsize);
592 
593 	/*
594 	 * We now start writing to the filesystem
595 	 */
596 
597 	if (!Nflag) {
598 		/*
599 		 * Validate the given file system size.
600 		 * Verify that its last block can actually be accessed.
601 		 * Convert to file system fragment sized units.
602 		 */
603 		if (fssize <= 0) {
604 			printf("preposterous size %lld\n", (long long)fssize);
605 			fserr(13);
606 		}
607 		wtfs(fssize - 1, sectorsize, iobuf);
608 
609 		/*
610 		 * Ensure there is nothing that looks like a filesystem
611 		 * superbock anywhere other than where ours will be.
612 		 * If fsck finds the wrong one all hell breaks loose!
613 		 */
614 		for (i = 0; ; i++) {
615 			static const int sblocklist[] = SBLOCKSEARCH;
616 			int sblkoff = sblocklist[i];
617 			int sz;
618 			if (sblkoff == -1)
619 				break;
620 			/* Remove main superblock */
621 			zap_old_sblock(sblkoff);
622 			/* and all possible locations for the first alternate */
623 			sblkoff += SBLOCKSIZE;
624 			for (sz = SBLOCKSIZE; sz <= 0x10000; sz <<= 1)
625 				zap_old_sblock(roundup(sblkoff, sz));
626 		}
627 		/*
628 		 * Also zap possible Ext2fs magic leftover to prevent
629 		 * kernel vfs_mountroot() and bootloaders from mis-recognizing
630 		 * this file system as Ext2fs.
631 		 */
632 		zap_old_sblock(EXT2FS_SBOFF);
633 
634 #ifndef NO_APPLE_UFS
635 		if (isappleufs) {
636 			struct appleufslabel appleufs;
637 			ffs_appleufs_set(&appleufs, appleufs_volname,
638 			    tv.tv_sec, 0);
639 			wtfs(APPLEUFS_LABEL_OFFSET/sectorsize,
640 			    APPLEUFS_LABEL_SIZE, &appleufs);
641 		} else if (APPLEUFS_LABEL_SIZE % sectorsize == 0) {
642 			struct appleufslabel appleufs;
643 			/* Look for & zap any existing valid apple ufs labels */
644 			rdfs(APPLEUFS_LABEL_OFFSET/sectorsize,
645 			    APPLEUFS_LABEL_SIZE, &appleufs);
646 			if (ffs_appleufs_validate(fsys, &appleufs, NULL) == 0) {
647 				memset(&appleufs, 0, sizeof(appleufs));
648 				wtfs(APPLEUFS_LABEL_OFFSET/sectorsize,
649 				    APPLEUFS_LABEL_SIZE, &appleufs);
650 			}
651 		}
652 #endif
653 	}
654 
655 	/*
656 	 * Make a copy of the superblock into the buffer that we will be
657 	 * writing out in each cylinder group.
658 	 */
659 	memcpy(iobuf, &sblock, sizeof sblock);
660 	if (needswap)
661 		ffs_sb_swap(&sblock, (struct fs *)iobuf);
662 	if ((sblock.fs_old_flags & FS_FLAGS_UPDATED) == 0)
663 		memset(iobuf + offsetof(struct fs, fs_old_postbl_start),
664 		    0xff, 256);
665 
666 	if (verbosity >= 3)
667 		printf("super-block backups (for fsck_ffs -b #) at:\n");
668 	/* If we are printing more than one line of numbers, line up columns */
669 	fld_width = verbosity < 4 ? 1 : snprintf(NULL, 0, "%" PRIu64,
670 		(uint64_t)FFS_FSBTODB(&sblock, cgsblock(&sblock, sblock.fs_ncg-1)));
671 	/* Get terminal width */
672 	if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) == 0)
673 		max_cols = winsize.ws_col;
674 	else
675 		max_cols = 80;
676 	if (Nflag && verbosity == 3)
677 		/* Leave space to add " ..." after one row of numbers */
678 		max_cols -= 4;
679 #define BASE 0x10000	/* For some fixed-point maths */
680 	col = 0;
681 	delta = verbosity > 2 ? 0 : max_cols * BASE / sblock.fs_ncg;
682 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
683 		fflush(stdout);
684 		initcg(cylno, &tv);
685 		if (verbosity < 2)
686 			continue;
687 		if (delta > 0) {
688 			if (Nflag)
689 				/* No point doing dots for -N */
690 				break;
691 			/* Print dots scaled to end near RH margin */
692 			for (col += delta; col > BASE; col -= BASE)
693 				printf(".");
694 			continue;
695 		}
696 		/* Print superblock numbers */
697 		len = printf("%s%*" PRIu64 ",", col ? " " : "", fld_width,
698 		    (uint64_t)FFS_FSBTODB(&sblock, cgsblock(&sblock, cylno)));
699 		col += len;
700 		if (col + len < max_cols)
701 			/* Next number fits */
702 			continue;
703 		/* Next number won't fit, need a newline */
704 		if (verbosity <= 3) {
705 			/* Print dots for subsequent cylinder groups */
706 			delta = sblock.fs_ncg - cylno - 1;
707 			if (delta != 0) {
708 				if (Nflag) {
709 					printf(" ...");
710 					break;
711 				}
712 				delta = max_cols * BASE / delta;
713 			}
714 		}
715 		col = 0;
716 		printf("\n");
717 	}
718 #undef BASE
719 	if (col > 0)
720 		printf("\n");
721 	if (Nflag)
722 		exit(0);
723 
724 	/*
725 	 * Now construct the initial file system,
726 	 */
727 	if (fsinit(&tv, mfsmode, mfsuid, mfsgid) == 0 && mfs)
728 		errx(1, "Error making filesystem");
729 	sblock.fs_time = tv.tv_sec;
730 	if (Oflag <= 1) {
731 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
732 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
733 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
734 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
735 	}
736 	/*
737 	 * Write out the super-block and zeros until the first cg info
738 	 */
739 	i = cgsblock(&sblock, 0) * sblock.fs_fsize - sblock.fs_sblockloc;
740 	if ((size_t)i < sizeof(sblock))
741 		errx(1, "No space for superblock");
742 	memcpy(iobuf, &sblock, sizeof(sblock));
743 	memset(iobuf + sizeof(sblock), 0, i - sizeof(sblock));
744 	if (needswap)
745 		ffs_sb_swap(&sblock, (struct fs *)iobuf);
746 	if ((sblock.fs_old_flags & FS_FLAGS_UPDATED) == 0)
747 		memset(iobuf + offsetof(struct fs, fs_old_postbl_start),
748 		    0xff, 256);
749 	wtfs(sblock.fs_sblockloc / sectorsize, i, iobuf);
750 
751 	/* Write out first and last cylinder summary sectors */
752 	if (needswap)
753 		ffs_csum_swap(fscs_0, fscs_0, sblock.fs_fsize);
754 	wtfs(FFS_FSBTODB(&sblock, sblock.fs_csaddr), sblock.fs_fsize, fscs_0);
755 
756 	if (fscs_next > fscs_reset) {
757 		if (needswap)
758 			ffs_csum_swap(fscs_reset, fscs_reset, sblock.fs_fsize);
759 		fs_csaddr++;
760 		wtfs(FFS_FSBTODB(&sblock, fs_csaddr), sblock.fs_fsize, fscs_reset);
761 	}
762 
763 	/* mfs doesn't need these permanently allocated */
764 	munmap(iobuf, iobuf_memsize);
765 	munmap(fscs_0, 2 * sblock.fs_fsize);
766 }
767 
768 /*
769  * Initialize a cylinder group.
770  */
771 void
772 initcg(int cylno, const struct timeval *tv)
773 {
774 	daddr_t cbase, dmax;
775 	int32_t i, d, dlower, dupper, blkno;
776 	uint32_t u;
777 	struct ufs1_dinode *dp1;
778 	struct ufs2_dinode *dp2;
779 	int start;
780 
781 	/*
782 	 * Determine block bounds for cylinder group.
783 	 * Allow space for super block summary information in first
784 	 * cylinder group.
785 	 */
786 	cbase = cgbase(&sblock, cylno);
787 	dmax = cbase + sblock.fs_fpg;
788 	if (dmax > sblock.fs_size)
789 		dmax = sblock.fs_size;
790 	dlower = cgsblock(&sblock, cylno) - cbase;
791 	dupper = cgdmin(&sblock, cylno) - cbase;
792 	if (cylno == 0) {
793 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
794 		if (dupper >= cgstart(&sblock, cylno + 1)) {
795 			printf("\rToo many cylinder groups to fit summary "
796 				"information into first cylinder group\n");
797 			fserr(40);
798 		}
799 	}
800 	memset(&acg, 0, sblock.fs_cgsize);
801 	acg.cg_magic = CG_MAGIC;
802 	acg.cg_cgx = cylno;
803 	acg.cg_ndblk = dmax - cbase;
804 	if (sblock.fs_contigsumsize > 0)
805 		acg.cg_nclusterblks = acg.cg_ndblk >> sblock.fs_fragshift;
806 	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
807 	if (Oflag == 2) {
808 		acg.cg_time = tv->tv_sec;
809 		acg.cg_niblk = sblock.fs_ipg;
810 		acg.cg_initediblk = sblock.fs_ipg < 2 * FFS_INOPB(&sblock) ?
811 		    sblock.fs_ipg : 2 * FFS_INOPB(&sblock);
812 		acg.cg_iusedoff = start;
813 	} else {
814 		acg.cg_old_ncyl = sblock.fs_old_cpg;
815 		if ((sblock.fs_old_flags & FS_FLAGS_UPDATED) == 0 &&
816 		    (cylno == sblock.fs_ncg - 1))
817 			acg.cg_old_ncyl =
818 			    sblock.fs_old_ncyl % sblock.fs_old_cpg;
819 		acg.cg_old_time = tv->tv_sec;
820 		acg.cg_old_niblk = sblock.fs_ipg;
821 		acg.cg_old_btotoff = start;
822 		acg.cg_old_boff = acg.cg_old_btotoff +
823 		    sblock.fs_old_cpg * sizeof(int32_t);
824 		acg.cg_iusedoff = acg.cg_old_boff +
825 		    sblock.fs_old_cpg * sizeof(u_int16_t);
826 	}
827 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
828 	if (sblock.fs_contigsumsize <= 0) {
829 		acg.cg_nextfreeoff = acg.cg_freeoff +
830 		   howmany(sblock.fs_fpg, CHAR_BIT);
831 	} else {
832 		acg.cg_clustersumoff = acg.cg_freeoff +
833 		    howmany(sblock.fs_fpg, CHAR_BIT) - sizeof(int32_t);
834 		if (isappleufs) {
835 			/* Apple PR2216969 gives rationale for this change.
836 			 * I believe they were mistaken, but we need to
837 			 * duplicate it for compatibility.  -- dbj@NetBSD.org
838 			 */
839 			acg.cg_clustersumoff += sizeof(int32_t);
840 		}
841 		acg.cg_clustersumoff =
842 		    roundup(acg.cg_clustersumoff, sizeof(int32_t));
843 		acg.cg_clusteroff = acg.cg_clustersumoff +
844 		    (sblock.fs_contigsumsize + 1) * sizeof(int32_t);
845 		acg.cg_nextfreeoff = acg.cg_clusteroff +
846 		    howmany(ffs_fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
847 	}
848 	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
849 		printf("Panic: cylinder group too big\n");
850 		fserr(37);
851 	}
852 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
853 	if (cylno == 0)
854 		for (u = 0; u < UFS_ROOTINO; u++) {
855 			setbit(cg_inosused(&acg, 0), u);
856 			acg.cg_cs.cs_nifree--;
857 		}
858 	if (cylno > 0) {
859 		/*
860 		 * In cylno 0, beginning space is reserved
861 		 * for boot and super blocks.
862 		 */
863 		for (d = 0, blkno = 0; d < dlower;) {
864 			setblock(&sblock, cg_blksfree(&acg, 0), blkno);
865 			if (sblock.fs_contigsumsize > 0)
866 				setbit(cg_clustersfree(&acg, 0), blkno);
867 			acg.cg_cs.cs_nbfree++;
868 			if (Oflag <= 1) {
869 				int cn = old_cbtocylno(&sblock, d);
870 				old_cg_blktot(&acg, 0)[cn]++;
871 				old_cg_blks(&sblock, &acg,
872 				    cn, 0)[old_cbtorpos(&sblock, d)]++;
873 			}
874 			d += sblock.fs_frag;
875 			blkno++;
876 		}
877 	}
878 	if ((i = (dupper & (sblock.fs_frag - 1))) != 0) {
879 		acg.cg_frsum[sblock.fs_frag - i]++;
880 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
881 			setbit(cg_blksfree(&acg, 0), dupper);
882 			acg.cg_cs.cs_nffree++;
883 		}
884 	}
885 	for (d = dupper, blkno = dupper >> sblock.fs_fragshift;
886 	     d + sblock.fs_frag <= acg.cg_ndblk; ) {
887 		setblock(&sblock, cg_blksfree(&acg, 0), blkno);
888 		if (sblock.fs_contigsumsize > 0)
889 			setbit(cg_clustersfree(&acg, 0), blkno);
890 		acg.cg_cs.cs_nbfree++;
891 		if (Oflag <= 1) {
892 			int cn = old_cbtocylno(&sblock, d);
893 			old_cg_blktot(&acg, 0)[cn]++;
894 			old_cg_blks(&sblock, &acg,
895 			    cn, 0)[old_cbtorpos(&sblock, d)]++;
896 		}
897 		d += sblock.fs_frag;
898 		blkno++;
899 	}
900 	if (d < acg.cg_ndblk) {
901 		acg.cg_frsum[acg.cg_ndblk - d]++;
902 		for (; d < acg.cg_ndblk; d++) {
903 			setbit(cg_blksfree(&acg, 0), d);
904 			acg.cg_cs.cs_nffree++;
905 		}
906 	}
907 	if (sblock.fs_contigsumsize > 0) {
908 		int32_t *sump = cg_clustersum(&acg, 0);
909 		u_char *mapp = cg_clustersfree(&acg, 0);
910 		int map = *mapp++;
911 		int bit = 1;
912 		int run = 0;
913 
914 		for (i = 0; i < acg.cg_nclusterblks; i++) {
915 			if ((map & bit) != 0) {
916 				run++;
917 			} else if (run != 0) {
918 				if (run > sblock.fs_contigsumsize)
919 					run = sblock.fs_contigsumsize;
920 				sump[run]++;
921 				run = 0;
922 			}
923 			if ((i & (CHAR_BIT - 1)) != (CHAR_BIT - 1)) {
924 				bit <<= 1;
925 			} else {
926 				map = *mapp++;
927 				bit = 1;
928 			}
929 		}
930 		if (run != 0) {
931 			if (run > sblock.fs_contigsumsize)
932 				run = sblock.fs_contigsumsize;
933 			sump[run]++;
934 		}
935 	}
936 	*fscs_next++ = acg.cg_cs;
937 	if (fscs_next == fscs_end) {
938 		/* write block of cylinder group summary info into cyl 0 */
939 		if (needswap)
940 			ffs_csum_swap(fscs_reset, fscs_reset, sblock.fs_fsize);
941 		fs_csaddr++;
942 		wtfs(FFS_FSBTODB(&sblock, fs_csaddr), sblock.fs_fsize, fscs_reset);
943 		fscs_next = fscs_reset;
944 		memset(fscs_next, 0, sblock.fs_fsize);
945 	}
946 	/*
947 	 * Write out the duplicate super block, the cylinder group map
948 	 * and two blocks worth of inodes in a single write.
949 	 */
950 	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
951 	memcpy(&iobuf[start], &acg, sblock.fs_cgsize);
952 	if (needswap)
953 		ffs_cg_swap(&acg, (struct cg*)&iobuf[start], &sblock);
954 	start += sblock.fs_bsize;
955 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
956 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
957 	for (i = MIN(sblock.fs_ipg, 2) * FFS_INOPB(&sblock); i != 0; i--) {
958 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
959 			/* No need to swap, it'll stay random */
960 			dp1->di_gen = arc4random() & INT32_MAX;
961 			dp1++;
962 		} else {
963 			dp2->di_gen = arc4random() & INT32_MAX;
964 			dp2++;
965 		}
966 	}
967 	wtfs(FFS_FSBTODB(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);
968 	/*
969 	 * For the old file system, we have to initialize all the inodes.
970 	 */
971 	if (sblock.fs_magic != FS_UFS1_MAGIC)
972 		return;
973 
974 	/* Write 'd' (usually 16 * fs_frag) file-system fragments at once */
975 	d = (iobuf_memsize - start) / sblock.fs_bsize * sblock.fs_frag;
976 	dupper = sblock.fs_ipg / FFS_INOPF(&sblock);
977 	for (i = 2 * sblock.fs_frag; i < dupper; i += d) {
978 		if (d > dupper - i)
979 			d = dupper - i;
980 		dp1 = (struct ufs1_dinode *)(&iobuf[start]);
981 		do
982 			dp1->di_gen = arc4random() & INT32_MAX;
983 		while ((char *)++dp1 < &iobuf[iobuf_memsize]);
984 		wtfs(FFS_FSBTODB(&sblock, cgimin(&sblock, cylno) + i),
985 		    d * sblock.fs_bsize / sblock.fs_frag, &iobuf[start]);
986 	}
987 }
988 
989 /*
990  * initialize the file system
991  */
992 
993 #ifdef LOSTDIR
994 #define	PREDEFDIR 3
995 #else
996 #define	PREDEFDIR 2
997 #endif
998 
999 struct direct root_dir[] = {
1000 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
1001 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
1002 #ifdef LOSTDIR
1003 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 10, "lost+found" },
1004 #endif
1005 };
1006 struct odirect {
1007 	u_int32_t d_ino;
1008 	u_int16_t d_reclen;
1009 	u_int16_t d_namlen;
1010 	u_char	d_name[FFS_MAXNAMLEN + 1];
1011 } oroot_dir[] = {
1012 	{ UFS_ROOTINO, sizeof(struct direct), 1, "." },
1013 	{ UFS_ROOTINO, sizeof(struct direct), 2, ".." },
1014 #ifdef LOSTDIR
1015 	{ LOSTFOUNDINO, sizeof(struct direct), 10, "lost+found" },
1016 #endif
1017 };
1018 #ifdef LOSTDIR
1019 struct direct lost_found_dir[] = {
1020 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 1, "." },
1021 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
1022 	{ 0, DIRBLKSIZ, 0, 0, 0 },
1023 };
1024 struct odirect olost_found_dir[] = {
1025 	{ LOSTFOUNDINO, sizeof(struct direct), 1, "." },
1026 	{ UFS_ROOTINO, sizeof(struct direct), 2, ".." },
1027 	{ 0, DIRBLKSIZ, 0, 0 },
1028 };
1029 #endif
1030 
1031 static void copy_dir(struct direct *, struct direct *);
1032 
1033 int
1034 fsinit(const struct timeval *tv, mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
1035 {
1036 	union dinode node;
1037 	union Buffer buf;
1038 	int i;
1039 	int qblocks = 0;
1040 	int qinos = 0;
1041 	uint8_t q2h_hash_shift;
1042 	uint16_t q2h_hash_mask;
1043 #ifdef LOSTDIR
1044 	int dirblksiz = DIRBLKSIZ;
1045 	if (isappleufs)
1046 		dirblksiz = APPLEUFS_DIRBLKSIZ;
1047 	int nextino = LOSTFOUNDINO+1;
1048 #else
1049 	int nextino = UFS_ROOTINO+1;
1050 #endif
1051 
1052 	/*
1053 	 * initialize the node
1054 	 */
1055 
1056 #ifdef LOSTDIR
1057 	/*
1058 	 * create the lost+found directory
1059 	 */
1060 	memset(&node, 0, sizeof(node));
1061 	if (Oflag == 0) {
1062 		(void)makedir(&buf, (struct direct *)olost_found_dir, 2);
1063 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
1064 			copy_dir((struct direct*)&olost_found_dir[2],
1065 				(struct direct*)&buf[i]);
1066 	} else {
1067 		(void)makedir(&buf, lost_found_dir, 2);
1068 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
1069 			copy_dir(&lost_found_dir[2], (struct direct*)&buf[i]);
1070 	}
1071 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
1072 		node.dp1.di_atime = tv->tv_sec;
1073 		node.dp1.di_atimensec = tv->tv_usec * 1000;
1074 		node.dp1.di_mtime = tv->tv_sec;
1075 		node.dp1.di_mtimensec = tv->tv_usec * 1000;
1076 		node.dp1.di_ctime = tv->tv_sec;
1077 		node.dp1.di_ctimensec = tv->tv_usec * 1000;
1078 		node.dp1.di_mode = IFDIR | UMASK;
1079 		node.dp1.di_nlink = 2;
1080 		node.dp1.di_size = sblock.fs_bsize;
1081 		node.dp1.di_db[0] = alloc(node.dp1.di_size, node.dp1.di_mode);
1082 		if (node.dp1.di_db[0] == 0)
1083 			return (0);
1084 		node.dp1.di_blocks = btodb(ffs_fragroundup(&sblock,
1085 		    node.dp1.di_size));
1086 		qblocks += node.dp1.di_blocks;
1087 		node.dp1.di_uid = geteuid();
1088 		node.dp1.di_gid = getegid();
1089 		wtfs(FFS_FSBTODB(&sblock, node.dp1.di_db[0]), node.dp1.di_size,
1090 		    buf);
1091 	} else {
1092 		node.dp2.di_atime = tv->tv_sec;
1093 		node.dp2.di_atimensec = tv->tv_usec * 1000;
1094 		node.dp2.di_mtime = tv->tv_sec;
1095 		node.dp2.di_mtimensec = tv->tv_usec * 1000;
1096 		node.dp2.di_ctime = tv->tv_sec;
1097 		node.dp2.di_ctimensec = tv->tv_usec * 1000;
1098 		node.dp2.di_birthtime = tv->tv_sec;
1099 		node.dp2.di_birthnsec = tv->tv_usec * 1000;
1100 		node.dp2.di_mode = IFDIR | UMASK;
1101 		node.dp2.di_nlink = 2;
1102 		node.dp2.di_size = sblock.fs_bsize;
1103 		node.dp2.di_db[0] = alloc(node.dp2.di_size, node.dp2.di_mode);
1104 		if (node.dp2.di_db[0] == 0)
1105 			return (0);
1106 		node.dp2.di_blocks = btodb(ffs_fragroundup(&sblock,
1107 		    node.dp2.di_size));
1108 		qblocks += node.dp2.di_blocks;
1109 		node.dp2.di_uid = geteuid();
1110 		node.dp2.di_gid = getegid();
1111 		wtfs(FFS_FSBTODB(&sblock, node.dp2.di_db[0]), node.dp2.di_size,
1112 		    buf);
1113 	}
1114 	qinos++;
1115 	iput(&node, LOSTFOUNDINO);
1116 #endif
1117 	/*
1118 	 * create the root directory
1119 	 */
1120 	memset(&node, 0, sizeof(node));
1121 	if (Oflag <= 1) {
1122 		if (mfs) {
1123 			node.dp1.di_mode = IFDIR | mfsmode;
1124 			node.dp1.di_uid = mfsuid;
1125 			node.dp1.di_gid = mfsgid;
1126 		} else {
1127 			node.dp1.di_mode = IFDIR | UMASK;
1128 			node.dp1.di_uid = geteuid();
1129 			node.dp1.di_gid = getegid();
1130 		}
1131 		node.dp1.di_nlink = PREDEFDIR;
1132 		if (Oflag == 0)
1133 			node.dp1.di_size = makedir(&buf,
1134 			    (struct direct *)oroot_dir, PREDEFDIR);
1135 		else
1136 			node.dp1.di_size = makedir(&buf, root_dir, PREDEFDIR);
1137 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
1138 		if (node.dp1.di_db[0] == 0)
1139 			return (0);
1140 		node.dp1.di_blocks = btodb(ffs_fragroundup(&sblock,
1141 		    node.dp1.di_size));
1142 		qblocks += node.dp1.di_blocks;
1143 		wtfs(FFS_FSBTODB(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, &buf);
1144 	} else {
1145 		if (mfs) {
1146 			node.dp2.di_mode = IFDIR | mfsmode;
1147 			node.dp2.di_uid = mfsuid;
1148 			node.dp2.di_gid = mfsgid;
1149 		} else {
1150 			node.dp2.di_mode = IFDIR | UMASK;
1151 			node.dp2.di_uid = geteuid();
1152 			node.dp2.di_gid = getegid();
1153 		}
1154 		node.dp2.di_atime = tv->tv_sec;
1155 		node.dp2.di_atimensec = tv->tv_usec * 1000;
1156 		node.dp2.di_mtime = tv->tv_sec;
1157 		node.dp2.di_mtimensec = tv->tv_usec * 1000;
1158 		node.dp2.di_ctime = tv->tv_sec;
1159 		node.dp2.di_ctimensec = tv->tv_usec * 1000;
1160 		node.dp2.di_birthtime = tv->tv_sec;
1161 		node.dp2.di_birthnsec = tv->tv_usec * 1000;
1162 		node.dp2.di_nlink = PREDEFDIR;
1163 		node.dp2.di_size = makedir(&buf, root_dir, PREDEFDIR);
1164 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
1165 		if (node.dp2.di_db[0] == 0)
1166 			return (0);
1167 		node.dp2.di_blocks = btodb(ffs_fragroundup(&sblock,
1168 		    node.dp2.di_size));
1169 		qblocks += node.dp2.di_blocks;
1170 		wtfs(FFS_FSBTODB(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, &buf);
1171 	}
1172 	qinos++;
1173 	iput(&node, UFS_ROOTINO);
1174 	/*
1175 	 * compute the size of the hash table
1176 	 * We know the smallest block size is 4k, so we can use 2k
1177 	 * for the hash table; as an entry is 8 bytes we can store
1178 	 * 256 entries. So let start q2h_hash_shift at 8
1179 	 */
1180 	for (q2h_hash_shift = 8;
1181 	    q2h_hash_shift < 15;
1182 	    q2h_hash_shift++) {
1183 		if ((sizeof(uint64_t) << (q2h_hash_shift + 1)) +
1184 		    sizeof(struct quota2_header) > (u_int)sblock.fs_bsize)
1185 			break;
1186 	}
1187 	q2h_hash_mask = (1 << q2h_hash_shift) - 1;
1188 	for (i = 0; i < MAXQUOTAS; i++) {
1189 		struct quota2_header *q2h;
1190 		struct quota2_entry *q2e;
1191 		uint64_t offset;
1192 		uid_t uid = (i == USRQUOTA ? geteuid() : getegid());
1193 
1194 		if ((quotas & FS_Q2_DO_TYPE(i)) == 0)
1195 			continue;
1196 		quota2_create_blk0(sblock.fs_bsize, &buf, q2h_hash_shift,
1197 		    i, needswap);
1198 		/* grab an entry from header for root dir */
1199 		q2h = &buf.q2h;
1200 		offset = ufs_rw64(q2h->q2h_free, needswap);
1201 		q2e = (void *)((char *)&buf + offset);
1202 		q2h->q2h_free = q2e->q2e_next;
1203 		memcpy(q2e, &q2h->q2h_defentry, sizeof(*q2e));
1204 		q2e->q2e_uid = ufs_rw32(uid, needswap);
1205 		q2e->q2e_val[QL_BLOCK].q2v_cur = ufs_rw64(qblocks, needswap);
1206 		q2e->q2e_val[QL_FILE].q2v_cur = ufs_rw64(qinos, needswap);
1207 		/* add to the hash entry */
1208 		q2e->q2e_next = q2h->q2h_entries[uid & q2h_hash_mask];
1209 		q2h->q2h_entries[uid & q2h_hash_mask] =
1210 		    ufs_rw64(offset, needswap);
1211 
1212 		memset(&node, 0, sizeof(node));
1213 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
1214 			node.dp1.di_atime = tv->tv_sec;
1215 			node.dp1.di_atimensec = tv->tv_usec * 1000;
1216 			node.dp1.di_mtime = tv->tv_sec;
1217 			node.dp1.di_mtimensec = tv->tv_usec * 1000;
1218 			node.dp1.di_ctime = tv->tv_sec;
1219 			node.dp1.di_ctimensec = tv->tv_usec * 1000;
1220 			node.dp1.di_mode = IFREG;
1221 			node.dp1.di_nlink = 1;
1222 			node.dp1.di_size = sblock.fs_bsize;
1223 			node.dp1.di_db[0] =
1224 			    alloc(node.dp1.di_size, node.dp1.di_mode);
1225 			if (node.dp1.di_db[0] == 0)
1226 				return (0);
1227 			node.dp1.di_blocks = btodb(ffs_fragroundup(&sblock,
1228 			    node.dp1.di_size));
1229 			node.dp1.di_uid = geteuid();
1230 			node.dp1.di_gid = getegid();
1231 			wtfs(FFS_FSBTODB(&sblock, node.dp1.di_db[0]),
1232 			     node.dp1.di_size, &buf);
1233 		} else {
1234 			node.dp2.di_atime = tv->tv_sec;
1235 			node.dp2.di_atimensec = tv->tv_usec * 1000;
1236 			node.dp2.di_mtime = tv->tv_sec;
1237 			node.dp2.di_mtimensec = tv->tv_usec * 1000;
1238 			node.dp2.di_ctime = tv->tv_sec;
1239 			node.dp2.di_ctimensec = tv->tv_usec * 1000;
1240 			node.dp2.di_birthtime = tv->tv_sec;
1241 			node.dp2.di_birthnsec = tv->tv_usec * 1000;
1242 			node.dp2.di_mode = IFREG;
1243 			node.dp2.di_nlink = 1;
1244 			node.dp2.di_size = sblock.fs_bsize;
1245 			node.dp2.di_db[0] =
1246 			    alloc(node.dp2.di_size, node.dp2.di_mode);
1247 			if (node.dp2.di_db[0] == 0)
1248 				return (0);
1249 			node.dp2.di_blocks = btodb(ffs_fragroundup(&sblock,
1250 			    node.dp2.di_size));
1251 			node.dp2.di_uid = geteuid();
1252 			node.dp2.di_gid = getegid();
1253 			wtfs(FFS_FSBTODB(&sblock, node.dp2.di_db[0]),
1254 			    node.dp2.di_size, &buf);
1255 		}
1256 		iput(&node, nextino);
1257 		sblock.fs_quotafile[i] = nextino;
1258 		nextino++;
1259 	}
1260 	return (1);
1261 }
1262 
1263 /*
1264  * construct a set of directory entries in "buf".
1265  * return size of directory.
1266  */
1267 int
1268 makedir(union Buffer *buf, struct direct *protodir, int entries)
1269 {
1270 	char *cp;
1271 	int i, spcleft;
1272 	int dirblksiz = UFS_DIRBLKSIZ;
1273 	if (isappleufs)
1274 		dirblksiz = APPLEUFS_DIRBLKSIZ;
1275 
1276 	memset(buf, 0, dirblksiz);
1277 	spcleft = dirblksiz;
1278 	for (cp = buf->data, i = 0; i < entries - 1; i++) {
1279 		protodir[i].d_reclen = UFS_DIRSIZ(Oflag == 0, &protodir[i], 0);
1280 		copy_dir(&protodir[i], (struct direct*)cp);
1281 		cp += protodir[i].d_reclen;
1282 		spcleft -= protodir[i].d_reclen;
1283 	}
1284 	protodir[i].d_reclen = spcleft;
1285 	copy_dir(&protodir[i], (struct direct*)cp);
1286 	return (dirblksiz);
1287 }
1288 
1289 /*
1290  * allocate a block or frag
1291  */
1292 daddr_t
1293 alloc(int size, int mode)
1294 {
1295 	int i, frag;
1296 	daddr_t d, blkno;
1297 
1298 	rdfs(FFS_FSBTODB(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
1299 	/* fs -> host byte order */
1300 	if (needswap)
1301 		ffs_cg_swap(&acg, &acg, &sblock);
1302 	if (acg.cg_magic != CG_MAGIC) {
1303 		printf("cg 0: bad magic number\n");
1304 		return (0);
1305 	}
1306 	if (acg.cg_cs.cs_nbfree == 0) {
1307 		printf("first cylinder group ran out of space\n");
1308 		return (0);
1309 	}
1310 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
1311 		if (isblock(&sblock, cg_blksfree(&acg, 0),
1312 		    d >> sblock.fs_fragshift))
1313 			goto goth;
1314 	printf("internal error: can't find block in cyl 0\n");
1315 	return (0);
1316 goth:
1317 	blkno = ffs_fragstoblks(&sblock, d);
1318 	clrblock(&sblock, cg_blksfree(&acg, 0), blkno);
1319 	if (sblock.fs_contigsumsize > 0)
1320 		clrbit(cg_clustersfree(&acg, 0), blkno);
1321 	acg.cg_cs.cs_nbfree--;
1322 	sblock.fs_cstotal.cs_nbfree--;
1323 	fscs_0->cs_nbfree--;
1324 	if (mode & IFDIR) {
1325 		acg.cg_cs.cs_ndir++;
1326 		sblock.fs_cstotal.cs_ndir++;
1327 		fscs_0->cs_ndir++;
1328 	}
1329 	if (Oflag <= 1) {
1330 		int cn = old_cbtocylno(&sblock, d);
1331 		old_cg_blktot(&acg, 0)[cn]--;
1332 		old_cg_blks(&sblock, &acg,
1333 		    cn, 0)[old_cbtorpos(&sblock, d)]--;
1334 	}
1335 	if (size != sblock.fs_bsize) {
1336 		frag = howmany(size, sblock.fs_fsize);
1337 		fscs_0->cs_nffree += sblock.fs_frag - frag;
1338 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
1339 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
1340 		acg.cg_frsum[sblock.fs_frag - frag]++;
1341 		for (i = frag; i < sblock.fs_frag; i++)
1342 			setbit(cg_blksfree(&acg, 0), d + i);
1343 	}
1344 	/* host -> fs byte order */
1345 	if (needswap)
1346 		ffs_cg_swap(&acg, &acg, &sblock);
1347 	wtfs(FFS_FSBTODB(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
1348 	return (d);
1349 }
1350 
1351 /*
1352  * Allocate an inode on the disk
1353  */
1354 static void
1355 iput(union dinode *ip, ino_t ino)
1356 {
1357 	daddr_t d;
1358 	int i;
1359 	struct ufs1_dinode *dp1;
1360 	struct ufs2_dinode *dp2;
1361 
1362 	rdfs(FFS_FSBTODB(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
1363 	/* fs -> host byte order */
1364 	if (needswap)
1365 		ffs_cg_swap(&acg, &acg, &sblock);
1366 	if (acg.cg_magic != CG_MAGIC) {
1367 		printf("cg 0: bad magic number\n");
1368 		fserr(31);
1369 	}
1370 	acg.cg_cs.cs_nifree--;
1371 	setbit(cg_inosused(&acg, 0), ino);
1372 	/* host -> fs byte order */
1373 	if (needswap)
1374 		ffs_cg_swap(&acg, &acg, &sblock);
1375 	wtfs(FFS_FSBTODB(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
1376 	sblock.fs_cstotal.cs_nifree--;
1377 	fscs_0->cs_nifree--;
1378 	if (ino >= (ino_t)(sblock.fs_ipg * sblock.fs_ncg)) {
1379 		printf("fsinit: inode value out of range (%llu).\n",
1380 		    (unsigned long long)ino);
1381 		fserr(32);
1382 	}
1383 	d = FFS_FSBTODB(&sblock, ino_to_fsba(&sblock, ino));
1384 	rdfs(d, sblock.fs_bsize, (char *)iobuf);
1385 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
1386 		dp1 = (struct ufs1_dinode *)iobuf;
1387 		dp1 += ino_to_fsbo(&sblock, ino);
1388 		if (needswap) {
1389 			ffs_dinode1_swap(&ip->dp1, dp1);
1390 			/* ffs_dinode1_swap() doesn't swap blocks addrs */
1391 			for (i=0; i<UFS_NDADDR; i++)
1392 			    dp1->di_db[i] = bswap32(ip->dp1.di_db[i]);
1393 			for (i=0; i<UFS_NIADDR; i++)
1394 			    dp1->di_ib[i] = bswap32(ip->dp1.di_ib[i]);
1395 		} else
1396 			*dp1 = ip->dp1;
1397 		dp1->di_gen = arc4random() & INT32_MAX;
1398 	} else {
1399 		dp2 = (struct ufs2_dinode *)iobuf;
1400 		dp2 += ino_to_fsbo(&sblock, ino);
1401 		if (needswap) {
1402 			ffs_dinode2_swap(&ip->dp2, dp2);
1403 			for (i=0; i<UFS_NDADDR; i++)
1404 			    dp2->di_db[i] = bswap64(ip->dp2.di_db[i]);
1405 			for (i=0; i<UFS_NIADDR; i++)
1406 			    dp2->di_ib[i] = bswap64(ip->dp2.di_ib[i]);
1407 		} else
1408 			*dp2 = ip->dp2;
1409 		dp2->di_gen = arc4random() & INT32_MAX;
1410 	}
1411 	wtfs(d, sblock.fs_bsize, iobuf);
1412 }
1413 
1414 /*
1415  * read a block from the file system
1416  */
1417 void
1418 rdfs(daddr_t bno, int size, void *bf)
1419 {
1420 	int n;
1421 	off_t offset;
1422 
1423 #ifdef MFS
1424 	if (mfs) {
1425 		if (Nflag)
1426 			memset(bf, 0, size);
1427 		else
1428 			memmove(bf, membase + bno * sectorsize, size);
1429 		return;
1430 	}
1431 #endif
1432 	offset = bno;
1433 	n = pread(fsi, bf, size, offset * sectorsize);
1434 	if (n != size) {
1435 		printf("rdfs: read error for sector %lld: %s\n",
1436 		    (long long)bno, strerror(errno));
1437 		exit(34);
1438 	}
1439 }
1440 
1441 /*
1442  * write a block to the file system
1443  */
1444 void
1445 wtfs(daddr_t bno, int size, void *bf)
1446 {
1447 	int n;
1448 	off_t offset;
1449 
1450 	if (Nflag)
1451 		return;
1452 #ifdef MFS
1453 	if (mfs) {
1454 		memmove(membase + bno * sectorsize, bf, size);
1455 		return;
1456 	}
1457 #endif
1458 	offset = bno;
1459 	n = pwrite(fso, bf, size, offset * sectorsize);
1460 	if (n != size) {
1461 		printf("wtfs: write error for sector %lld: %s\n",
1462 		    (long long)bno, strerror(errno));
1463 		exit(36);
1464 	}
1465 }
1466 
1467 /*
1468  * check if a block is available
1469  */
1470 int
1471 isblock(struct fs *fs, unsigned char *cp, int h)
1472 {
1473 	unsigned char mask;
1474 
1475 	switch (fs->fs_fragshift) {
1476 	case 3:
1477 		return (cp[h] == 0xff);
1478 	case 2:
1479 		mask = 0x0f << ((h & 0x1) << 2);
1480 		return ((cp[h >> 1] & mask) == mask);
1481 	case 1:
1482 		mask = 0x03 << ((h & 0x3) << 1);
1483 		return ((cp[h >> 2] & mask) == mask);
1484 	case 0:
1485 		mask = 0x01 << (h & 0x7);
1486 		return ((cp[h >> 3] & mask) == mask);
1487 	default:
1488 #ifdef STANDALONE
1489 		printf("isblock bad fs_fragshift %d\n", fs->fs_fragshift);
1490 #else
1491 		fprintf(stderr, "isblock bad fs_fragshift %d\n",
1492 		    fs->fs_fragshift);
1493 #endif
1494 		return (0);
1495 	}
1496 }
1497 
1498 /*
1499  * take a block out of the map
1500  */
1501 void
1502 clrblock(struct fs *fs, unsigned char *cp, int h)
1503 {
1504 	switch ((fs)->fs_fragshift) {
1505 	case 3:
1506 		cp[h] = 0;
1507 		return;
1508 	case 2:
1509 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1510 		return;
1511 	case 1:
1512 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1513 		return;
1514 	case 0:
1515 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1516 		return;
1517 	default:
1518 #ifdef STANDALONE
1519 		printf("clrblock bad fs_fragshift %d\n", fs->fs_fragshift);
1520 #else
1521 		fprintf(stderr, "clrblock bad fs_fragshift %d\n",
1522 		    fs->fs_fragshift);
1523 #endif
1524 		return;
1525 	}
1526 }
1527 
1528 /*
1529  * put a block into the map
1530  */
1531 void
1532 setblock(struct fs *fs, unsigned char *cp, int h)
1533 {
1534 	switch (fs->fs_fragshift) {
1535 	case 3:
1536 		cp[h] = 0xff;
1537 		return;
1538 	case 2:
1539 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1540 		return;
1541 	case 1:
1542 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1543 		return;
1544 	case 0:
1545 		cp[h >> 3] |= (0x01 << (h & 0x7));
1546 		return;
1547 	default:
1548 #ifdef STANDALONE
1549 		printf("setblock bad fs_frag %d\n", fs->fs_fragshift);
1550 #else
1551 		fprintf(stderr, "setblock bad fs_fragshift %d\n",
1552 		    fs->fs_fragshift);
1553 #endif
1554 		return;
1555 	}
1556 }
1557 
1558 /* copy a direntry to a buffer, in fs byte order */
1559 static void
1560 copy_dir(struct direct *dir, struct direct *dbuf)
1561 {
1562 	memcpy(dbuf, dir, UFS_DIRSIZ(Oflag == 0, dir, 0));
1563 	if (needswap) {
1564 		dbuf->d_ino = bswap32(dir->d_ino);
1565 		dbuf->d_reclen = bswap16(dir->d_reclen);
1566 		if (Oflag == 0)
1567 			((struct odirect*)dbuf)->d_namlen =
1568 				bswap16(((struct odirect*)dir)->d_namlen);
1569 	}
1570 }
1571 
1572 static int
1573 ilog2(int val)
1574 {
1575 	u_int n;
1576 
1577 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
1578 		if (1 << n == val)
1579 			return (n);
1580 	errx(1, "ilog2: %d is not a power of 2", val);
1581 }
1582 
1583 static void
1584 zap_old_sblock(int sblkoff)
1585 {
1586 	static int cg0_data;
1587 	uint32_t oldfs[SBLOCKSIZE / 4];
1588 	static const struct fsm {
1589 		uint32_t	offset;
1590 		uint32_t	magic;
1591 		uint32_t	mask;
1592 	} fs_magics[] = {
1593 		{offsetof(struct fs, fs_magic)/4, FS_UFS1_MAGIC, ~0u},
1594 		{offsetof(struct fs, fs_magic)/4, FS_UFS2_MAGIC, ~0u},
1595 		{0, 0x70162, ~0u},		/* LFS_MAGIC */
1596 		{14, 0xef53, 0xffff},		/* EXT2FS (little) */
1597 		{14, 0xef530000, 0xffff0000},	/* EXT2FS (big) */
1598 		{.offset = ~0u},
1599 	};
1600 	const struct fsm *fsm;
1601 
1602 	if (Nflag)
1603 		return;
1604 
1605 	if (sblkoff == 0)	/* Why did UFS2 add support for this?  sigh. */
1606 		return;
1607 
1608 	if (cg0_data == 0)
1609 		/* For FFSv1 this could include all the inodes. */
1610 		cg0_data = cgsblock(&sblock, 0) * sblock.fs_fsize + iobufsize;
1611 
1612 	/* Ignore anything that is beyond our filesystem */
1613 	if ((sblkoff + SBLOCKSIZE)/sectorsize >= fssize)
1614 		return;
1615 	/* Zero anything inside our filesystem... */
1616 	if (sblkoff >= sblock.fs_sblockloc) {
1617 		/* ...unless we will write that area anyway */
1618 		if (sblkoff >= cg0_data)
1619 			wtfs(sblkoff / sectorsize,
1620 			    roundup(sizeof sblock, sectorsize), iobuf);
1621 		return;
1622 	}
1623 
1624 	/* The sector might contain boot code, so we must validate it */
1625 	rdfs(sblkoff/sectorsize, sizeof oldfs, &oldfs);
1626 	for (fsm = fs_magics; ; fsm++) {
1627 		uint32_t v;
1628 		if (fsm->mask == 0)
1629 			return;
1630 		v = oldfs[fsm->offset];
1631 		if ((v & fsm->mask) == fsm->magic ||
1632 		    (bswap32(v) & fsm->mask) == fsm->magic)
1633 			break;
1634 	}
1635 
1636 	/* Just zap the magic number */
1637 	oldfs[fsm->offset] = 0;
1638 	wtfs(sblkoff/sectorsize, sizeof oldfs, &oldfs);
1639 }
1640 
1641 
1642 #ifdef MFS
1643 /*
1644  * Internal version of malloc that trims the requested size if not enough
1645  * memory is available.
1646  */
1647 static void *
1648 mkfs_malloc(size_t size)
1649 {
1650 	u_long pgsz;
1651 	caddr_t *memory, *extra;
1652 	size_t exsize = 128 * 1024;
1653 
1654 	if (size == 0)
1655 		return (NULL);
1656 
1657 	pgsz = getpagesize() - 1;
1658 	size = (size + pgsz) &~ pgsz;
1659 
1660 	/* try to map requested size */
1661 	memory = mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
1662 	    -1, 0);
1663 	if (memory == MAP_FAILED)
1664 		return NULL;
1665 
1666 	/* try to map something extra */
1667 	extra = mmap(0, exsize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
1668 	    -1, 0);
1669 	munmap(extra, exsize);
1670 
1671 	/* if extra memory couldn't be mapped, reduce original request accordingly */
1672 	if (extra == MAP_FAILED) {
1673 		munmap(memory, size);
1674 		size -= exsize;
1675 		memory = mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
1676 		    -1, 0);
1677 		if (memory == MAP_FAILED)
1678 			return NULL;
1679 	}
1680 
1681 	return memory;
1682 }
1683 #endif	/* MFS */
1684