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