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