xref: /netbsd-src/sbin/newfs/mkfs.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: mkfs.c,v 1.127 2016/03/07 15:55:06 christos 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.127 2016/03/07 15:55:06 christos 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 		if (isappleufs) {
635 			struct appleufslabel appleufs;
636 			ffs_appleufs_set(&appleufs, appleufs_volname,
637 			    tv.tv_sec, 0);
638 			wtfs(APPLEUFS_LABEL_OFFSET/sectorsize,
639 			    APPLEUFS_LABEL_SIZE, &appleufs);
640 		} else if (APPLEUFS_LABEL_SIZE % sectorsize == 0) {
641 			struct appleufslabel appleufs;
642 			/* Look for & zap any existing valid apple ufs labels */
643 			rdfs(APPLEUFS_LABEL_OFFSET/sectorsize,
644 			    APPLEUFS_LABEL_SIZE, &appleufs);
645 			if (ffs_appleufs_validate(fsys, &appleufs, NULL) == 0) {
646 				memset(&appleufs, 0, sizeof(appleufs));
647 				wtfs(APPLEUFS_LABEL_OFFSET/sectorsize,
648 				    APPLEUFS_LABEL_SIZE, &appleufs);
649 			}
650 		}
651 	}
652 
653 	/*
654 	 * Make a copy of the superblock into the buffer that we will be
655 	 * writing out in each cylinder group.
656 	 */
657 	memcpy(iobuf, &sblock, sizeof sblock);
658 	if (needswap)
659 		ffs_sb_swap(&sblock, (struct fs *)iobuf);
660 	if ((sblock.fs_old_flags & FS_FLAGS_UPDATED) == 0)
661 		memset(iobuf + offsetof(struct fs, fs_old_postbl_start),
662 		    0xff, 256);
663 
664 	if (verbosity >= 3)
665 		printf("super-block backups (for fsck_ffs -b #) at:\n");
666 	/* If we are printing more than one line of numbers, line up columns */
667 	fld_width = verbosity < 4 ? 1 : snprintf(NULL, 0, "%" PRIu64,
668 		(uint64_t)FFS_FSBTODB(&sblock, cgsblock(&sblock, sblock.fs_ncg-1)));
669 	/* Get terminal width */
670 	if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) == 0)
671 		max_cols = winsize.ws_col;
672 	else
673 		max_cols = 80;
674 	if (Nflag && verbosity == 3)
675 		/* Leave space to add " ..." after one row of numbers */
676 		max_cols -= 4;
677 #define BASE 0x10000	/* For some fixed-point maths */
678 	col = 0;
679 	delta = verbosity > 2 ? 0 : max_cols * BASE / sblock.fs_ncg;
680 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
681 		fflush(stdout);
682 		initcg(cylno, &tv);
683 		if (verbosity < 2)
684 			continue;
685 		if (delta > 0) {
686 			if (Nflag)
687 				/* No point doing dots for -N */
688 				break;
689 			/* Print dots scaled to end near RH margin */
690 			for (col += delta; col > BASE; col -= BASE)
691 				printf(".");
692 			continue;
693 		}
694 		/* Print superblock numbers */
695 		len = printf("%s%*" PRIu64 ",", col ? " " : "", fld_width,
696 		    (uint64_t)FFS_FSBTODB(&sblock, cgsblock(&sblock, cylno)));
697 		col += len;
698 		if (col + len < max_cols)
699 			/* Next number fits */
700 			continue;
701 		/* Next number won't fit, need a newline */
702 		if (verbosity <= 3) {
703 			/* Print dots for subsequent cylinder groups */
704 			delta = sblock.fs_ncg - cylno - 1;
705 			if (delta != 0) {
706 				if (Nflag) {
707 					printf(" ...");
708 					break;
709 				}
710 				delta = max_cols * BASE / delta;
711 			}
712 		}
713 		col = 0;
714 		printf("\n");
715 	}
716 #undef BASE
717 	if (col > 0)
718 		printf("\n");
719 	if (Nflag)
720 		exit(0);
721 
722 	/*
723 	 * Now construct the initial file system,
724 	 */
725 	if (fsinit(&tv, mfsmode, mfsuid, mfsgid) == 0 && mfs)
726 		errx(1, "Error making filesystem");
727 	sblock.fs_time = tv.tv_sec;
728 	if (Oflag <= 1) {
729 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
730 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
731 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
732 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
733 	}
734 	/*
735 	 * Write out the super-block and zeros until the first cg info
736 	 */
737 	i = cgsblock(&sblock, 0) * sblock.fs_fsize - sblock.fs_sblockloc;
738 	if ((size_t)i < sizeof(sblock))
739 		errx(1, "No space for superblock");
740 	memcpy(iobuf, &sblock, sizeof(sblock));
741 	memset(iobuf + sizeof(sblock), 0, i - sizeof(sblock));
742 	if (needswap)
743 		ffs_sb_swap(&sblock, (struct fs *)iobuf);
744 	if ((sblock.fs_old_flags & FS_FLAGS_UPDATED) == 0)
745 		memset(iobuf + offsetof(struct fs, fs_old_postbl_start),
746 		    0xff, 256);
747 	wtfs(sblock.fs_sblockloc / sectorsize, i, iobuf);
748 
749 	/* Write out first and last cylinder summary sectors */
750 	if (needswap)
751 		ffs_csum_swap(fscs_0, fscs_0, sblock.fs_fsize);
752 	wtfs(FFS_FSBTODB(&sblock, sblock.fs_csaddr), sblock.fs_fsize, fscs_0);
753 
754 	if (fscs_next > fscs_reset) {
755 		if (needswap)
756 			ffs_csum_swap(fscs_reset, fscs_reset, sblock.fs_fsize);
757 		fs_csaddr++;
758 		wtfs(FFS_FSBTODB(&sblock, fs_csaddr), sblock.fs_fsize, fscs_reset);
759 	}
760 
761 	/* mfs doesn't need these permanently allocated */
762 	munmap(iobuf, iobuf_memsize);
763 	munmap(fscs_0, 2 * sblock.fs_fsize);
764 }
765 
766 /*
767  * Initialize a cylinder group.
768  */
769 void
770 initcg(int cylno, const struct timeval *tv)
771 {
772 	daddr_t cbase, dmax;
773 	int32_t i, d, dlower, dupper, blkno;
774 	uint32_t u;
775 	struct ufs1_dinode *dp1;
776 	struct ufs2_dinode *dp2;
777 	int start;
778 
779 	/*
780 	 * Determine block bounds for cylinder group.
781 	 * Allow space for super block summary information in first
782 	 * cylinder group.
783 	 */
784 	cbase = cgbase(&sblock, cylno);
785 	dmax = cbase + sblock.fs_fpg;
786 	if (dmax > sblock.fs_size)
787 		dmax = sblock.fs_size;
788 	dlower = cgsblock(&sblock, cylno) - cbase;
789 	dupper = cgdmin(&sblock, cylno) - cbase;
790 	if (cylno == 0) {
791 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
792 		if (dupper >= cgstart(&sblock, cylno + 1)) {
793 			printf("\rToo many cylinder groups to fit summary "
794 				"information into first cylinder group\n");
795 			fserr(40);
796 		}
797 	}
798 	memset(&acg, 0, sblock.fs_cgsize);
799 	acg.cg_magic = CG_MAGIC;
800 	acg.cg_cgx = cylno;
801 	acg.cg_ndblk = dmax - cbase;
802 	if (sblock.fs_contigsumsize > 0)
803 		acg.cg_nclusterblks = acg.cg_ndblk >> sblock.fs_fragshift;
804 	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
805 	if (Oflag == 2) {
806 		acg.cg_time = tv->tv_sec;
807 		acg.cg_niblk = sblock.fs_ipg;
808 		acg.cg_initediblk = sblock.fs_ipg < 2 * FFS_INOPB(&sblock) ?
809 		    sblock.fs_ipg : 2 * FFS_INOPB(&sblock);
810 		acg.cg_iusedoff = start;
811 	} else {
812 		acg.cg_old_ncyl = sblock.fs_old_cpg;
813 		if ((sblock.fs_old_flags & FS_FLAGS_UPDATED) == 0 &&
814 		    (cylno == sblock.fs_ncg - 1))
815 			acg.cg_old_ncyl =
816 			    sblock.fs_old_ncyl % sblock.fs_old_cpg;
817 		acg.cg_old_time = tv->tv_sec;
818 		acg.cg_old_niblk = sblock.fs_ipg;
819 		acg.cg_old_btotoff = start;
820 		acg.cg_old_boff = acg.cg_old_btotoff +
821 		    sblock.fs_old_cpg * sizeof(int32_t);
822 		acg.cg_iusedoff = acg.cg_old_boff +
823 		    sblock.fs_old_cpg * sizeof(u_int16_t);
824 	}
825 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
826 	if (sblock.fs_contigsumsize <= 0) {
827 		acg.cg_nextfreeoff = acg.cg_freeoff +
828 		   howmany(sblock.fs_fpg, CHAR_BIT);
829 	} else {
830 		acg.cg_clustersumoff = acg.cg_freeoff +
831 		    howmany(sblock.fs_fpg, CHAR_BIT) - sizeof(int32_t);
832 		if (isappleufs) {
833 			/* Apple PR2216969 gives rationale for this change.
834 			 * I believe they were mistaken, but we need to
835 			 * duplicate it for compatibility.  -- dbj@NetBSD.org
836 			 */
837 			acg.cg_clustersumoff += sizeof(int32_t);
838 		}
839 		acg.cg_clustersumoff =
840 		    roundup(acg.cg_clustersumoff, sizeof(int32_t));
841 		acg.cg_clusteroff = acg.cg_clustersumoff +
842 		    (sblock.fs_contigsumsize + 1) * sizeof(int32_t);
843 		acg.cg_nextfreeoff = acg.cg_clusteroff +
844 		    howmany(ffs_fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
845 	}
846 	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
847 		printf("Panic: cylinder group too big\n");
848 		fserr(37);
849 	}
850 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
851 	if (cylno == 0)
852 		for (u = 0; u < UFS_ROOTINO; u++) {
853 			setbit(cg_inosused(&acg, 0), u);
854 			acg.cg_cs.cs_nifree--;
855 		}
856 	if (cylno > 0) {
857 		/*
858 		 * In cylno 0, beginning space is reserved
859 		 * for boot and super blocks.
860 		 */
861 		for (d = 0, blkno = 0; d < dlower;) {
862 			setblock(&sblock, cg_blksfree(&acg, 0), blkno);
863 			if (sblock.fs_contigsumsize > 0)
864 				setbit(cg_clustersfree(&acg, 0), blkno);
865 			acg.cg_cs.cs_nbfree++;
866 			if (Oflag <= 1) {
867 				int cn = old_cbtocylno(&sblock, d);
868 				old_cg_blktot(&acg, 0)[cn]++;
869 				old_cg_blks(&sblock, &acg,
870 				    cn, 0)[old_cbtorpos(&sblock, d)]++;
871 			}
872 			d += sblock.fs_frag;
873 			blkno++;
874 		}
875 	}
876 	if ((i = (dupper & (sblock.fs_frag - 1))) != 0) {
877 		acg.cg_frsum[sblock.fs_frag - i]++;
878 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
879 			setbit(cg_blksfree(&acg, 0), dupper);
880 			acg.cg_cs.cs_nffree++;
881 		}
882 	}
883 	for (d = dupper, blkno = dupper >> sblock.fs_fragshift;
884 	     d + sblock.fs_frag <= acg.cg_ndblk; ) {
885 		setblock(&sblock, cg_blksfree(&acg, 0), blkno);
886 		if (sblock.fs_contigsumsize > 0)
887 			setbit(cg_clustersfree(&acg, 0), blkno);
888 		acg.cg_cs.cs_nbfree++;
889 		if (Oflag <= 1) {
890 			int cn = old_cbtocylno(&sblock, d);
891 			old_cg_blktot(&acg, 0)[cn]++;
892 			old_cg_blks(&sblock, &acg,
893 			    cn, 0)[old_cbtorpos(&sblock, d)]++;
894 		}
895 		d += sblock.fs_frag;
896 		blkno++;
897 	}
898 	if (d < acg.cg_ndblk) {
899 		acg.cg_frsum[acg.cg_ndblk - d]++;
900 		for (; d < acg.cg_ndblk; d++) {
901 			setbit(cg_blksfree(&acg, 0), d);
902 			acg.cg_cs.cs_nffree++;
903 		}
904 	}
905 	if (sblock.fs_contigsumsize > 0) {
906 		int32_t *sump = cg_clustersum(&acg, 0);
907 		u_char *mapp = cg_clustersfree(&acg, 0);
908 		int map = *mapp++;
909 		int bit = 1;
910 		int run = 0;
911 
912 		for (i = 0; i < acg.cg_nclusterblks; i++) {
913 			if ((map & bit) != 0) {
914 				run++;
915 			} else if (run != 0) {
916 				if (run > sblock.fs_contigsumsize)
917 					run = sblock.fs_contigsumsize;
918 				sump[run]++;
919 				run = 0;
920 			}
921 			if ((i & (CHAR_BIT - 1)) != (CHAR_BIT - 1)) {
922 				bit <<= 1;
923 			} else {
924 				map = *mapp++;
925 				bit = 1;
926 			}
927 		}
928 		if (run != 0) {
929 			if (run > sblock.fs_contigsumsize)
930 				run = sblock.fs_contigsumsize;
931 			sump[run]++;
932 		}
933 	}
934 	*fscs_next++ = acg.cg_cs;
935 	if (fscs_next == fscs_end) {
936 		/* write block of cylinder group summary info into cyl 0 */
937 		if (needswap)
938 			ffs_csum_swap(fscs_reset, fscs_reset, sblock.fs_fsize);
939 		fs_csaddr++;
940 		wtfs(FFS_FSBTODB(&sblock, fs_csaddr), sblock.fs_fsize, fscs_reset);
941 		fscs_next = fscs_reset;
942 		memset(fscs_next, 0, sblock.fs_fsize);
943 	}
944 	/*
945 	 * Write out the duplicate super block, the cylinder group map
946 	 * and two blocks worth of inodes in a single write.
947 	 */
948 	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
949 	memcpy(&iobuf[start], &acg, sblock.fs_cgsize);
950 	if (needswap)
951 		ffs_cg_swap(&acg, (struct cg*)&iobuf[start], &sblock);
952 	start += sblock.fs_bsize;
953 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
954 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
955 	for (i = MIN(sblock.fs_ipg, 2) * FFS_INOPB(&sblock); i != 0; i--) {
956 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
957 			/* No need to swap, it'll stay random */
958 			dp1->di_gen = arc4random() & INT32_MAX;
959 			dp1++;
960 		} else {
961 			dp2->di_gen = arc4random() & INT32_MAX;
962 			dp2++;
963 		}
964 	}
965 	wtfs(FFS_FSBTODB(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);
966 	/*
967 	 * For the old file system, we have to initialize all the inodes.
968 	 */
969 	if (sblock.fs_magic != FS_UFS1_MAGIC)
970 		return;
971 
972 	/* Write 'd' (usually 16 * fs_frag) file-system fragments at once */
973 	d = (iobuf_memsize - start) / sblock.fs_bsize * sblock.fs_frag;
974 	dupper = sblock.fs_ipg / FFS_INOPF(&sblock);
975 	for (i = 2 * sblock.fs_frag; i < dupper; i += d) {
976 		if (d > dupper - i)
977 			d = dupper - i;
978 		dp1 = (struct ufs1_dinode *)(&iobuf[start]);
979 		do
980 			dp1->di_gen = arc4random() & INT32_MAX;
981 		while ((char *)++dp1 < &iobuf[iobuf_memsize]);
982 		wtfs(FFS_FSBTODB(&sblock, cgimin(&sblock, cylno) + i),
983 		    d * sblock.fs_bsize / sblock.fs_frag, &iobuf[start]);
984 	}
985 }
986 
987 /*
988  * initialize the file system
989  */
990 
991 #ifdef LOSTDIR
992 #define	PREDEFDIR 3
993 #else
994 #define	PREDEFDIR 2
995 #endif
996 
997 struct direct root_dir[] = {
998 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
999 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
1000 #ifdef LOSTDIR
1001 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 10, "lost+found" },
1002 #endif
1003 };
1004 struct odirect {
1005 	u_int32_t d_ino;
1006 	u_int16_t d_reclen;
1007 	u_int16_t d_namlen;
1008 	u_char	d_name[FFS_MAXNAMLEN + 1];
1009 } oroot_dir[] = {
1010 	{ UFS_ROOTINO, sizeof(struct direct), 1, "." },
1011 	{ UFS_ROOTINO, sizeof(struct direct), 2, ".." },
1012 #ifdef LOSTDIR
1013 	{ LOSTFOUNDINO, sizeof(struct direct), 10, "lost+found" },
1014 #endif
1015 };
1016 #ifdef LOSTDIR
1017 struct direct lost_found_dir[] = {
1018 	{ LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 1, "." },
1019 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
1020 	{ 0, DIRBLKSIZ, 0, 0, 0 },
1021 };
1022 struct odirect olost_found_dir[] = {
1023 	{ LOSTFOUNDINO, sizeof(struct direct), 1, "." },
1024 	{ UFS_ROOTINO, sizeof(struct direct), 2, ".." },
1025 	{ 0, DIRBLKSIZ, 0, 0 },
1026 };
1027 #endif
1028 
1029 static void copy_dir(struct direct *, struct direct *);
1030 
1031 int
1032 fsinit(const struct timeval *tv, mode_t mfsmode, uid_t mfsuid, gid_t mfsgid)
1033 {
1034 	union dinode node;
1035 	union Buffer buf;
1036 	int i;
1037 	int qblocks = 0;
1038 	int qinos = 0;
1039 	uint8_t q2h_hash_shift;
1040 	uint16_t q2h_hash_mask;
1041 #ifdef LOSTDIR
1042 	int dirblksiz = DIRBLKSIZ;
1043 	if (isappleufs)
1044 		dirblksiz = APPLEUFS_DIRBLKSIZ;
1045 	int nextino = LOSTFOUNDINO+1;
1046 #else
1047 	int nextino = UFS_ROOTINO+1;
1048 #endif
1049 
1050 	/*
1051 	 * initialize the node
1052 	 */
1053 
1054 #ifdef LOSTDIR
1055 	/*
1056 	 * create the lost+found directory
1057 	 */
1058 	memset(&node, 0, sizeof(node));
1059 	if (Oflag == 0) {
1060 		(void)makedir(&buf, (struct direct *)olost_found_dir, 2);
1061 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
1062 			copy_dir((struct direct*)&olost_found_dir[2],
1063 				(struct direct*)&buf[i]);
1064 	} else {
1065 		(void)makedir(&buf, lost_found_dir, 2);
1066 		for (i = dirblksiz; i < sblock.fs_bsize; i += dirblksiz)
1067 			copy_dir(&lost_found_dir[2], (struct direct*)&buf[i]);
1068 	}
1069 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
1070 		node.dp1.di_atime = tv->tv_sec;
1071 		node.dp1.di_atimensec = tv->tv_usec * 1000;
1072 		node.dp1.di_mtime = tv->tv_sec;
1073 		node.dp1.di_mtimensec = tv->tv_usec * 1000;
1074 		node.dp1.di_ctime = tv->tv_sec;
1075 		node.dp1.di_ctimensec = tv->tv_usec * 1000;
1076 		node.dp1.di_mode = IFDIR | UMASK;
1077 		node.dp1.di_nlink = 2;
1078 		node.dp1.di_size = sblock.fs_bsize;
1079 		node.dp1.di_db[0] = alloc(node.dp1.di_size, node.dp1.di_mode);
1080 		if (node.dp1.di_db[0] == 0)
1081 			return (0);
1082 		node.dp1.di_blocks = btodb(ffs_fragroundup(&sblock,
1083 		    node.dp1.di_size));
1084 		qblocks += node.dp1.di_blocks;
1085 		node.dp1.di_uid = geteuid();
1086 		node.dp1.di_gid = getegid();
1087 		wtfs(FFS_FSBTODB(&sblock, node.dp1.di_db[0]), node.dp1.di_size,
1088 		    buf);
1089 	} else {
1090 		node.dp2.di_atime = tv->tv_sec;
1091 		node.dp2.di_atimensec = tv->tv_usec * 1000;
1092 		node.dp2.di_mtime = tv->tv_sec;
1093 		node.dp2.di_mtimensec = tv->tv_usec * 1000;
1094 		node.dp2.di_ctime = tv->tv_sec;
1095 		node.dp2.di_ctimensec = tv->tv_usec * 1000;
1096 		node.dp2.di_birthtime = tv->tv_sec;
1097 		node.dp2.di_birthnsec = tv->tv_usec * 1000;
1098 		node.dp2.di_mode = IFDIR | UMASK;
1099 		node.dp2.di_nlink = 2;
1100 		node.dp2.di_size = sblock.fs_bsize;
1101 		node.dp2.di_db[0] = alloc(node.dp2.di_size, node.dp2.di_mode);
1102 		if (node.dp2.di_db[0] == 0)
1103 			return (0);
1104 		node.dp2.di_blocks = btodb(ffs_fragroundup(&sblock,
1105 		    node.dp2.di_size));
1106 		qblocks += node.dp2.di_blocks;
1107 		node.dp2.di_uid = geteuid();
1108 		node.dp2.di_gid = getegid();
1109 		wtfs(FFS_FSBTODB(&sblock, node.dp2.di_db[0]), node.dp2.di_size,
1110 		    buf);
1111 	}
1112 	qinos++;
1113 	iput(&node, LOSTFOUNDINO);
1114 #endif
1115 	/*
1116 	 * create the root directory
1117 	 */
1118 	memset(&node, 0, sizeof(node));
1119 	if (Oflag <= 1) {
1120 		if (mfs) {
1121 			node.dp1.di_mode = IFDIR | mfsmode;
1122 			node.dp1.di_uid = mfsuid;
1123 			node.dp1.di_gid = mfsgid;
1124 		} else {
1125 			node.dp1.di_mode = IFDIR | UMASK;
1126 			node.dp1.di_uid = geteuid();
1127 			node.dp1.di_gid = getegid();
1128 		}
1129 		node.dp1.di_nlink = PREDEFDIR;
1130 		if (Oflag == 0)
1131 			node.dp1.di_size = makedir(&buf,
1132 			    (struct direct *)oroot_dir, PREDEFDIR);
1133 		else
1134 			node.dp1.di_size = makedir(&buf, root_dir, PREDEFDIR);
1135 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
1136 		if (node.dp1.di_db[0] == 0)
1137 			return (0);
1138 		node.dp1.di_blocks = btodb(ffs_fragroundup(&sblock,
1139 		    node.dp1.di_size));
1140 		qblocks += node.dp1.di_blocks;
1141 		wtfs(FFS_FSBTODB(&sblock, node.dp1.di_db[0]), sblock.fs_fsize, &buf);
1142 	} else {
1143 		if (mfs) {
1144 			node.dp2.di_mode = IFDIR | mfsmode;
1145 			node.dp2.di_uid = mfsuid;
1146 			node.dp2.di_gid = mfsgid;
1147 		} else {
1148 			node.dp2.di_mode = IFDIR | UMASK;
1149 			node.dp2.di_uid = geteuid();
1150 			node.dp2.di_gid = getegid();
1151 		}
1152 		node.dp2.di_atime = tv->tv_sec;
1153 		node.dp2.di_atimensec = tv->tv_usec * 1000;
1154 		node.dp2.di_mtime = tv->tv_sec;
1155 		node.dp2.di_mtimensec = tv->tv_usec * 1000;
1156 		node.dp2.di_ctime = tv->tv_sec;
1157 		node.dp2.di_ctimensec = tv->tv_usec * 1000;
1158 		node.dp2.di_birthtime = tv->tv_sec;
1159 		node.dp2.di_birthnsec = tv->tv_usec * 1000;
1160 		node.dp2.di_nlink = PREDEFDIR;
1161 		node.dp2.di_size = makedir(&buf, root_dir, PREDEFDIR);
1162 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
1163 		if (node.dp2.di_db[0] == 0)
1164 			return (0);
1165 		node.dp2.di_blocks = btodb(ffs_fragroundup(&sblock,
1166 		    node.dp2.di_size));
1167 		qblocks += node.dp2.di_blocks;
1168 		wtfs(FFS_FSBTODB(&sblock, node.dp2.di_db[0]), sblock.fs_fsize, &buf);
1169 	}
1170 	qinos++;
1171 	iput(&node, UFS_ROOTINO);
1172 	/*
1173 	 * compute the size of the hash table
1174 	 * We know the smallest block size is 4k, so we can use 2k
1175 	 * for the hash table; as an entry is 8 bytes we can store
1176 	 * 256 entries. So let start q2h_hash_shift at 8
1177 	 */
1178 	for (q2h_hash_shift = 8;
1179 	    q2h_hash_shift < 15;
1180 	    q2h_hash_shift++) {
1181 		if ((sizeof(uint64_t) << (q2h_hash_shift + 1)) +
1182 		    sizeof(struct quota2_header) > (u_int)sblock.fs_bsize)
1183 			break;
1184 	}
1185 	q2h_hash_mask = (1 << q2h_hash_shift) - 1;
1186 	for (i = 0; i < MAXQUOTAS; i++) {
1187 		struct quota2_header *q2h;
1188 		struct quota2_entry *q2e;
1189 		uint64_t offset;
1190 		uid_t uid = (i == USRQUOTA ? geteuid() : getegid());
1191 
1192 		if ((quotas & FS_Q2_DO_TYPE(i)) == 0)
1193 			continue;
1194 		quota2_create_blk0(sblock.fs_bsize, &buf, q2h_hash_shift,
1195 		    i, needswap);
1196 		/* grab an entry from header for root dir */
1197 		q2h = &buf.q2h;
1198 		offset = ufs_rw64(q2h->q2h_free, needswap);
1199 		q2e = (void *)((char *)&buf + offset);
1200 		q2h->q2h_free = q2e->q2e_next;
1201 		memcpy(q2e, &q2h->q2h_defentry, sizeof(*q2e));
1202 		q2e->q2e_uid = ufs_rw32(uid, needswap);
1203 		q2e->q2e_val[QL_BLOCK].q2v_cur = ufs_rw64(qblocks, needswap);
1204 		q2e->q2e_val[QL_FILE].q2v_cur = ufs_rw64(qinos, needswap);
1205 		/* add to the hash entry */
1206 		q2e->q2e_next = q2h->q2h_entries[uid & q2h_hash_mask];
1207 		q2h->q2h_entries[uid & q2h_hash_mask] =
1208 		    ufs_rw64(offset, needswap);
1209 
1210 		memset(&node, 0, sizeof(node));
1211 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
1212 			node.dp1.di_atime = tv->tv_sec;
1213 			node.dp1.di_atimensec = tv->tv_usec * 1000;
1214 			node.dp1.di_mtime = tv->tv_sec;
1215 			node.dp1.di_mtimensec = tv->tv_usec * 1000;
1216 			node.dp1.di_ctime = tv->tv_sec;
1217 			node.dp1.di_ctimensec = tv->tv_usec * 1000;
1218 			node.dp1.di_mode = IFREG;
1219 			node.dp1.di_nlink = 1;
1220 			node.dp1.di_size = sblock.fs_bsize;
1221 			node.dp1.di_db[0] =
1222 			    alloc(node.dp1.di_size, node.dp1.di_mode);
1223 			if (node.dp1.di_db[0] == 0)
1224 				return (0);
1225 			node.dp1.di_blocks = btodb(ffs_fragroundup(&sblock,
1226 			    node.dp1.di_size));
1227 			node.dp1.di_uid = geteuid();
1228 			node.dp1.di_gid = getegid();
1229 			wtfs(FFS_FSBTODB(&sblock, node.dp1.di_db[0]),
1230 			     node.dp1.di_size, &buf);
1231 		} else {
1232 			node.dp2.di_atime = tv->tv_sec;
1233 			node.dp2.di_atimensec = tv->tv_usec * 1000;
1234 			node.dp2.di_mtime = tv->tv_sec;
1235 			node.dp2.di_mtimensec = tv->tv_usec * 1000;
1236 			node.dp2.di_ctime = tv->tv_sec;
1237 			node.dp2.di_ctimensec = tv->tv_usec * 1000;
1238 			node.dp2.di_birthtime = tv->tv_sec;
1239 			node.dp2.di_birthnsec = tv->tv_usec * 1000;
1240 			node.dp2.di_mode = IFREG;
1241 			node.dp2.di_nlink = 1;
1242 			node.dp2.di_size = sblock.fs_bsize;
1243 			node.dp2.di_db[0] =
1244 			    alloc(node.dp2.di_size, node.dp2.di_mode);
1245 			if (node.dp2.di_db[0] == 0)
1246 				return (0);
1247 			node.dp2.di_blocks = btodb(ffs_fragroundup(&sblock,
1248 			    node.dp2.di_size));
1249 			node.dp2.di_uid = geteuid();
1250 			node.dp2.di_gid = getegid();
1251 			wtfs(FFS_FSBTODB(&sblock, node.dp2.di_db[0]),
1252 			    node.dp2.di_size, &buf);
1253 		}
1254 		iput(&node, nextino);
1255 		sblock.fs_quotafile[i] = nextino;
1256 		nextino++;
1257 	}
1258 	return (1);
1259 }
1260 
1261 /*
1262  * construct a set of directory entries in "buf".
1263  * return size of directory.
1264  */
1265 int
1266 makedir(union Buffer *buf, struct direct *protodir, int entries)
1267 {
1268 	char *cp;
1269 	int i, spcleft;
1270 	int dirblksiz = UFS_DIRBLKSIZ;
1271 	if (isappleufs)
1272 		dirblksiz = APPLEUFS_DIRBLKSIZ;
1273 
1274 	memset(buf, 0, dirblksiz);
1275 	spcleft = dirblksiz;
1276 	for (cp = buf->data, i = 0; i < entries - 1; i++) {
1277 		protodir[i].d_reclen = UFS_DIRSIZ(Oflag == 0, &protodir[i], 0);
1278 		copy_dir(&protodir[i], (struct direct*)cp);
1279 		cp += protodir[i].d_reclen;
1280 		spcleft -= protodir[i].d_reclen;
1281 	}
1282 	protodir[i].d_reclen = spcleft;
1283 	copy_dir(&protodir[i], (struct direct*)cp);
1284 	return (dirblksiz);
1285 }
1286 
1287 /*
1288  * allocate a block or frag
1289  */
1290 daddr_t
1291 alloc(int size, int mode)
1292 {
1293 	int i, frag;
1294 	daddr_t d, blkno;
1295 
1296 	rdfs(FFS_FSBTODB(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
1297 	/* fs -> host byte order */
1298 	if (needswap)
1299 		ffs_cg_swap(&acg, &acg, &sblock);
1300 	if (acg.cg_magic != CG_MAGIC) {
1301 		printf("cg 0: bad magic number\n");
1302 		return (0);
1303 	}
1304 	if (acg.cg_cs.cs_nbfree == 0) {
1305 		printf("first cylinder group ran out of space\n");
1306 		return (0);
1307 	}
1308 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
1309 		if (isblock(&sblock, cg_blksfree(&acg, 0),
1310 		    d >> sblock.fs_fragshift))
1311 			goto goth;
1312 	printf("internal error: can't find block in cyl 0\n");
1313 	return (0);
1314 goth:
1315 	blkno = ffs_fragstoblks(&sblock, d);
1316 	clrblock(&sblock, cg_blksfree(&acg, 0), blkno);
1317 	if (sblock.fs_contigsumsize > 0)
1318 		clrbit(cg_clustersfree(&acg, 0), blkno);
1319 	acg.cg_cs.cs_nbfree--;
1320 	sblock.fs_cstotal.cs_nbfree--;
1321 	fscs_0->cs_nbfree--;
1322 	if (mode & IFDIR) {
1323 		acg.cg_cs.cs_ndir++;
1324 		sblock.fs_cstotal.cs_ndir++;
1325 		fscs_0->cs_ndir++;
1326 	}
1327 	if (Oflag <= 1) {
1328 		int cn = old_cbtocylno(&sblock, d);
1329 		old_cg_blktot(&acg, 0)[cn]--;
1330 		old_cg_blks(&sblock, &acg,
1331 		    cn, 0)[old_cbtorpos(&sblock, d)]--;
1332 	}
1333 	if (size != sblock.fs_bsize) {
1334 		frag = howmany(size, sblock.fs_fsize);
1335 		fscs_0->cs_nffree += sblock.fs_frag - frag;
1336 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
1337 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
1338 		acg.cg_frsum[sblock.fs_frag - frag]++;
1339 		for (i = frag; i < sblock.fs_frag; i++)
1340 			setbit(cg_blksfree(&acg, 0), d + i);
1341 	}
1342 	/* host -> fs byte order */
1343 	if (needswap)
1344 		ffs_cg_swap(&acg, &acg, &sblock);
1345 	wtfs(FFS_FSBTODB(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
1346 	return (d);
1347 }
1348 
1349 /*
1350  * Allocate an inode on the disk
1351  */
1352 static void
1353 iput(union dinode *ip, ino_t ino)
1354 {
1355 	daddr_t d;
1356 	int i;
1357 	struct ufs1_dinode *dp1;
1358 	struct ufs2_dinode *dp2;
1359 
1360 	rdfs(FFS_FSBTODB(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
1361 	/* fs -> host byte order */
1362 	if (needswap)
1363 		ffs_cg_swap(&acg, &acg, &sblock);
1364 	if (acg.cg_magic != CG_MAGIC) {
1365 		printf("cg 0: bad magic number\n");
1366 		fserr(31);
1367 	}
1368 	acg.cg_cs.cs_nifree--;
1369 	setbit(cg_inosused(&acg, 0), ino);
1370 	/* host -> fs byte order */
1371 	if (needswap)
1372 		ffs_cg_swap(&acg, &acg, &sblock);
1373 	wtfs(FFS_FSBTODB(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize, &acg);
1374 	sblock.fs_cstotal.cs_nifree--;
1375 	fscs_0->cs_nifree--;
1376 	if (ino >= (ino_t)(sblock.fs_ipg * sblock.fs_ncg)) {
1377 		printf("fsinit: inode value out of range (%llu).\n",
1378 		    (unsigned long long)ino);
1379 		fserr(32);
1380 	}
1381 	d = FFS_FSBTODB(&sblock, ino_to_fsba(&sblock, ino));
1382 	rdfs(d, sblock.fs_bsize, (char *)iobuf);
1383 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
1384 		dp1 = (struct ufs1_dinode *)iobuf;
1385 		dp1 += ino_to_fsbo(&sblock, ino);
1386 		if (needswap) {
1387 			ffs_dinode1_swap(&ip->dp1, dp1);
1388 			/* ffs_dinode1_swap() doesn't swap blocks addrs */
1389 			for (i=0; i<UFS_NDADDR; i++)
1390 			    dp1->di_db[i] = bswap32(ip->dp1.di_db[i]);
1391 			for (i=0; i<UFS_NIADDR; i++)
1392 			    dp1->di_ib[i] = bswap32(ip->dp1.di_ib[i]);
1393 		} else
1394 			*dp1 = ip->dp1;
1395 		dp1->di_gen = arc4random() & INT32_MAX;
1396 	} else {
1397 		dp2 = (struct ufs2_dinode *)iobuf;
1398 		dp2 += ino_to_fsbo(&sblock, ino);
1399 		if (needswap) {
1400 			ffs_dinode2_swap(&ip->dp2, dp2);
1401 			for (i=0; i<UFS_NDADDR; i++)
1402 			    dp2->di_db[i] = bswap64(ip->dp2.di_db[i]);
1403 			for (i=0; i<UFS_NIADDR; i++)
1404 			    dp2->di_ib[i] = bswap64(ip->dp2.di_ib[i]);
1405 		} else
1406 			*dp2 = ip->dp2;
1407 		dp2->di_gen = arc4random() & INT32_MAX;
1408 	}
1409 	wtfs(d, sblock.fs_bsize, iobuf);
1410 }
1411 
1412 /*
1413  * read a block from the file system
1414  */
1415 void
1416 rdfs(daddr_t bno, int size, void *bf)
1417 {
1418 	int n;
1419 	off_t offset;
1420 
1421 #ifdef MFS
1422 	if (mfs) {
1423 		if (Nflag)
1424 			memset(bf, 0, size);
1425 		else
1426 			memmove(bf, membase + bno * sectorsize, size);
1427 		return;
1428 	}
1429 #endif
1430 	offset = bno;
1431 	n = pread(fsi, bf, size, offset * sectorsize);
1432 	if (n != size) {
1433 		printf("rdfs: read error for sector %lld: %s\n",
1434 		    (long long)bno, strerror(errno));
1435 		exit(34);
1436 	}
1437 }
1438 
1439 /*
1440  * write a block to the file system
1441  */
1442 void
1443 wtfs(daddr_t bno, int size, void *bf)
1444 {
1445 	int n;
1446 	off_t offset;
1447 
1448 	if (Nflag)
1449 		return;
1450 #ifdef MFS
1451 	if (mfs) {
1452 		memmove(membase + bno * sectorsize, bf, size);
1453 		return;
1454 	}
1455 #endif
1456 	offset = bno;
1457 	n = pwrite(fso, bf, size, offset * sectorsize);
1458 	if (n != size) {
1459 		printf("wtfs: write error for sector %lld: %s\n",
1460 		    (long long)bno, strerror(errno));
1461 		exit(36);
1462 	}
1463 }
1464 
1465 /*
1466  * check if a block is available
1467  */
1468 int
1469 isblock(struct fs *fs, unsigned char *cp, int h)
1470 {
1471 	unsigned char mask;
1472 
1473 	switch (fs->fs_fragshift) {
1474 	case 3:
1475 		return (cp[h] == 0xff);
1476 	case 2:
1477 		mask = 0x0f << ((h & 0x1) << 2);
1478 		return ((cp[h >> 1] & mask) == mask);
1479 	case 1:
1480 		mask = 0x03 << ((h & 0x3) << 1);
1481 		return ((cp[h >> 2] & mask) == mask);
1482 	case 0:
1483 		mask = 0x01 << (h & 0x7);
1484 		return ((cp[h >> 3] & mask) == mask);
1485 	default:
1486 #ifdef STANDALONE
1487 		printf("isblock bad fs_fragshift %d\n", fs->fs_fragshift);
1488 #else
1489 		fprintf(stderr, "isblock bad fs_fragshift %d\n",
1490 		    fs->fs_fragshift);
1491 #endif
1492 		return (0);
1493 	}
1494 }
1495 
1496 /*
1497  * take a block out of the map
1498  */
1499 void
1500 clrblock(struct fs *fs, unsigned char *cp, int h)
1501 {
1502 	switch ((fs)->fs_fragshift) {
1503 	case 3:
1504 		cp[h] = 0;
1505 		return;
1506 	case 2:
1507 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1508 		return;
1509 	case 1:
1510 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1511 		return;
1512 	case 0:
1513 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1514 		return;
1515 	default:
1516 #ifdef STANDALONE
1517 		printf("clrblock bad fs_fragshift %d\n", fs->fs_fragshift);
1518 #else
1519 		fprintf(stderr, "clrblock bad fs_fragshift %d\n",
1520 		    fs->fs_fragshift);
1521 #endif
1522 		return;
1523 	}
1524 }
1525 
1526 /*
1527  * put a block into the map
1528  */
1529 void
1530 setblock(struct fs *fs, unsigned char *cp, int h)
1531 {
1532 	switch (fs->fs_fragshift) {
1533 	case 3:
1534 		cp[h] = 0xff;
1535 		return;
1536 	case 2:
1537 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1538 		return;
1539 	case 1:
1540 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1541 		return;
1542 	case 0:
1543 		cp[h >> 3] |= (0x01 << (h & 0x7));
1544 		return;
1545 	default:
1546 #ifdef STANDALONE
1547 		printf("setblock bad fs_frag %d\n", fs->fs_fragshift);
1548 #else
1549 		fprintf(stderr, "setblock bad fs_fragshift %d\n",
1550 		    fs->fs_fragshift);
1551 #endif
1552 		return;
1553 	}
1554 }
1555 
1556 /* copy a direntry to a buffer, in fs byte order */
1557 static void
1558 copy_dir(struct direct *dir, struct direct *dbuf)
1559 {
1560 	memcpy(dbuf, dir, UFS_DIRSIZ(Oflag == 0, dir, 0));
1561 	if (needswap) {
1562 		dbuf->d_ino = bswap32(dir->d_ino);
1563 		dbuf->d_reclen = bswap16(dir->d_reclen);
1564 		if (Oflag == 0)
1565 			((struct odirect*)dbuf)->d_namlen =
1566 				bswap16(((struct odirect*)dir)->d_namlen);
1567 	}
1568 }
1569 
1570 static int
1571 ilog2(int val)
1572 {
1573 	u_int n;
1574 
1575 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
1576 		if (1 << n == val)
1577 			return (n);
1578 	errx(1, "ilog2: %d is not a power of 2", val);
1579 }
1580 
1581 static void
1582 zap_old_sblock(int sblkoff)
1583 {
1584 	static int cg0_data;
1585 	uint32_t oldfs[SBLOCKSIZE / 4];
1586 	static const struct fsm {
1587 		uint32_t	offset;
1588 		uint32_t	magic;
1589 		uint32_t	mask;
1590 	} fs_magics[] = {
1591 		{offsetof(struct fs, fs_magic)/4, FS_UFS1_MAGIC, ~0u},
1592 		{offsetof(struct fs, fs_magic)/4, FS_UFS2_MAGIC, ~0u},
1593 		{0, 0x70162, ~0u},		/* LFS_MAGIC */
1594 		{14, 0xef53, 0xffff},		/* EXT2FS (little) */
1595 		{14, 0xef530000, 0xffff0000},	/* EXT2FS (big) */
1596 		{.offset = ~0u},
1597 	};
1598 	const struct fsm *fsm;
1599 
1600 	if (Nflag)
1601 		return;
1602 
1603 	if (sblkoff == 0)	/* Why did UFS2 add support for this?  sigh. */
1604 		return;
1605 
1606 	if (cg0_data == 0)
1607 		/* For FFSv1 this could include all the inodes. */
1608 		cg0_data = cgsblock(&sblock, 0) * sblock.fs_fsize + iobufsize;
1609 
1610 	/* Ignore anything that is beyond our filesystem */
1611 	if ((sblkoff + SBLOCKSIZE)/sectorsize >= fssize)
1612 		return;
1613 	/* Zero anything inside our filesystem... */
1614 	if (sblkoff >= sblock.fs_sblockloc) {
1615 		/* ...unless we will write that area anyway */
1616 		if (sblkoff >= cg0_data)
1617 			wtfs(sblkoff / sectorsize,
1618 			    roundup(sizeof sblock, sectorsize), iobuf);
1619 		return;
1620 	}
1621 
1622 	/* The sector might contain boot code, so we must validate it */
1623 	rdfs(sblkoff/sectorsize, sizeof oldfs, &oldfs);
1624 	for (fsm = fs_magics; ; fsm++) {
1625 		uint32_t v;
1626 		if (fsm->mask == 0)
1627 			return;
1628 		v = oldfs[fsm->offset];
1629 		if ((v & fsm->mask) == fsm->magic ||
1630 		    (bswap32(v) & fsm->mask) == fsm->magic)
1631 			break;
1632 	}
1633 
1634 	/* Just zap the magic number */
1635 	oldfs[fsm->offset] = 0;
1636 	wtfs(sblkoff/sectorsize, sizeof oldfs, &oldfs);
1637 }
1638 
1639 
1640 #ifdef MFS
1641 /*
1642  * Internal version of malloc that trims the requested size if not enough
1643  * memory is available.
1644  */
1645 static void *
1646 mkfs_malloc(size_t size)
1647 {
1648 	u_long pgsz;
1649 	caddr_t *memory, *extra;
1650 	size_t exsize = 128 * 1024;
1651 
1652 	if (size == 0)
1653 		return (NULL);
1654 
1655 	pgsz = getpagesize() - 1;
1656 	size = (size + pgsz) &~ pgsz;
1657 
1658 	/* try to map requested size */
1659 	memory = mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
1660 	    -1, 0);
1661 	if (memory == MAP_FAILED)
1662 		return NULL;
1663 
1664 	/* try to map something extra */
1665 	extra = mmap(0, exsize, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
1666 	    -1, 0);
1667 	munmap(extra, exsize);
1668 
1669 	/* if extra memory couldn't be mapped, reduce original request accordingly */
1670 	if (extra == MAP_FAILED) {
1671 		munmap(memory, size);
1672 		size -= exsize;
1673 		memory = mmap(0, size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE,
1674 		    -1, 0);
1675 		if (memory == MAP_FAILED)
1676 			return NULL;
1677 	}
1678 
1679 	return memory;
1680 }
1681 #endif	/* MFS */
1682