xref: /dragonfly/usr.sbin/makefs/ffs/mkfs.c (revision d9d30518)
1 /*	$NetBSD: mkfs.c,v 1.22 2011/10/09 22:30:13 christos Exp $	*/
2 
3 /*-
4  * SPDX-License-Identifier: BSD-3-Clause
5  *
6  * Copyright (c) 2002 Networks Associates Technology, Inc.
7  * All rights reserved.
8  *
9  * This software was developed for the FreeBSD Project by Marshall
10  * Kirk McKusick and Network Associates Laboratories, the Security
11  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
12  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
13  * research program
14  *
15  * Copyright (c) 1980, 1989, 1993
16  *	The Regents of the University of California.  All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  * $FreeBSD: head/usr.sbin/makefs/ffs/mkfs.c 326025 2017-11-20 19:49:47Z pfg $
43  */
44 
45 #include <sys/param.h>
46 #include <sys/time.h>
47 #include <sys/resource.h>
48 
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53 #include <errno.h>
54 #include <util.h>
55 
56 #include "makefs.h"
57 #include "ffs.h"
58 
59 #include <vfs/ufs/dinode.h>
60 #include <vfs/ufs/fs.h>
61 
62 #include "ffs/ufs_bswap.h"
63 #include "ffs/ufs_inode.h"
64 #include "ffs/ffs_extern.h"
65 #include "ffs/newfs_extern.h"
66 
67 #ifndef BBSIZE
68 #define	BBSIZE	8192			/* size of boot area, with label */
69 #endif
70 
71 static void initcg(uint32_t, time_t, const fsinfo_t *);
72 static int ilog2(int);
73 
74 static int count_digits(int);
75 
76 /*
77  * make file system for cylinder-group style file systems
78  */
79 #define	UMASK		0755
80 
81 static union {
82 	struct fs fs;
83 	char pad[SBLOCKSIZE];
84 } fsun;
85 #define	sblock	fsun.fs
86 
87 static union {
88 	struct cg cg;
89 	char pad[FFS_MAXBSIZE];
90 } cgun;
91 #define	acg	cgun.cg
92 
93 static char *iobuf;
94 static int iobufsize;
95 
96 static char writebuf[FFS_MAXBSIZE];
97 
98 static int     Oflag;	   /* format as an 4.3BSD file system */
99 static int64_t fssize;	   /* file system size */
100 static int     sectorsize;	   /* bytes/sector */
101 static int     fsize;	   /* fragment size */
102 static int     bsize;	   /* block size */
103 #ifndef __DragonFly__
104 static int     maxbsize;   /* maximum clustering */
105 #endif
106 static int     maxblkspercg;
107 static int     minfree;	   /* free space threshold */
108 static int     opt;		   /* optimization preference (space or time) */
109 static int     density;	   /* number of bytes per inode */
110 static int     maxcontig;	   /* max contiguous blocks to allocate */
111 static int     maxbpg;	   /* maximum blocks per file in a cyl group */
112 static int     bbsize;	   /* boot block size */
113 static int     sbsize;	   /* superblock size */
114 static int     avgfilesize;	   /* expected average file size */
115 static int     avgfpdir;	   /* expected number of files per directory */
116 
117 struct fs *
118 ffs_mkfs(const char *fsys, const fsinfo_t *fsopts, time_t tstamp)
119 {
120 	int fragsperinode, optimalfpg, origdensity, mindensity;
121 	int minfpg, lastminfpg;
122 	int32_t csfrags;
123 	uint32_t i, cylno;
124 	long long sizepb;
125 	ino_t maxinum;
126 	int minfragsperinode;   /* minimum ratio of frags to inodes */
127 	void *space;
128 	int size;
129 	int nprintcols, printcolwidth;
130 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
131 
132 	Oflag =		ffs_opts->version;
133 	fssize =        fsopts->size / fsopts->sectorsize;
134 	sectorsize =    fsopts->sectorsize;
135 	fsize =         ffs_opts->fsize;
136 	bsize =         ffs_opts->bsize;
137 #ifndef __DragonFly__
138 	maxbsize =      ffs_opts->maxbsize;
139 #endif
140 	maxblkspercg =  ffs_opts->maxblkspercg;
141 	minfree =       ffs_opts->minfree;
142 	opt =           ffs_opts->optimization;
143 	density =       ffs_opts->density;
144 	maxcontig =     ffs_opts->maxcontig;
145 	maxbpg =        ffs_opts->maxbpg;
146 	avgfilesize =   ffs_opts->avgfilesize;
147 	avgfpdir =      ffs_opts->avgfpdir;
148 	bbsize =        BBSIZE;
149 	sbsize =        SBLOCKSIZE;
150 
151 	strlcpy((char *)sblock.fs_volname, ffs_opts->label,
152 	    sizeof(sblock.fs_volname));
153 
154 #ifndef __DragonFly__ /* XXX dead code */
155 	if (Oflag == 0) {
156 		sblock.fs_old_inodefmt = FS_42INODEFMT;
157 		sblock.fs_maxsymlinklen = 0;
158 		sblock.fs_old_flags = 0;
159 	} else
160 #endif
161 	{
162 		sblock.fs_old_inodefmt = FS_44INODEFMT;
163 #ifndef __DragonFly__ /* XXX UFS2 */
164 		sblock.fs_maxsymlinklen = (Oflag == 1 ? UFS1_MAXSYMLINKLEN :
165 		    UFS2_MAXSYMLINKLEN);
166 #else
167 		sblock.fs_maxsymlinklen = UFS1_MAXSYMLINKLEN;
168 #endif
169 #ifndef __DragonFly__
170 		sblock.fs_old_flags = FS_FLAGS_UPDATED;
171 #endif
172 		sblock.fs_flags = 0;
173 	}
174 	/*
175 	 * Validate the given file system size.
176 	 * Verify that its last block can actually be accessed.
177 	 * Convert to file system fragment sized units.
178 	 */
179 	if (fssize <= 0) {
180 		printf("preposterous size %lld\n", (long long)fssize);
181 		exit(13);
182 	}
183 	ffs_wtfs(fssize - 1, sectorsize, (char *)&sblock, fsopts);
184 
185 	/*
186 	 * collect and verify the filesystem density info
187 	 */
188 	sblock.fs_avgfilesize = avgfilesize;
189 	sblock.fs_avgfpdir = avgfpdir;
190 	if (sblock.fs_avgfilesize <= 0)
191 		printf("illegal expected average file size %d\n",
192 		    sblock.fs_avgfilesize), exit(14);
193 	if (sblock.fs_avgfpdir <= 0)
194 		printf("illegal expected number of files per directory %d\n",
195 		    sblock.fs_avgfpdir), exit(15);
196 	/*
197 	 * collect and verify the block and fragment sizes
198 	 */
199 	sblock.fs_bsize = bsize;
200 	sblock.fs_fsize = fsize;
201 	if (!powerof2(sblock.fs_bsize)) {
202 		printf("block size must be a power of 2, not %d\n",
203 		    sblock.fs_bsize);
204 		exit(16);
205 	}
206 	if (!powerof2(sblock.fs_fsize)) {
207 		printf("fragment size must be a power of 2, not %d\n",
208 		    sblock.fs_fsize);
209 		exit(17);
210 	}
211 	if (sblock.fs_fsize < sectorsize) {
212 		printf("fragment size %d is too small, minimum is %d\n",
213 		    sblock.fs_fsize, sectorsize);
214 		exit(18);
215 	}
216 	if (sblock.fs_bsize < MINBSIZE) {
217 		printf("block size %d is too small, minimum is %d\n",
218 		    sblock.fs_bsize, MINBSIZE);
219 		exit(19);
220 	}
221 	if (sblock.fs_bsize > FFS_MAXBSIZE) {
222 		printf("block size %d is too large, maximum is %d\n",
223 		    sblock.fs_bsize, FFS_MAXBSIZE);
224 		exit(19);
225 	}
226 	if (sblock.fs_bsize < sblock.fs_fsize) {
227 		printf("block size (%d) cannot be smaller than fragment size (%d)\n",
228 		    sblock.fs_bsize, sblock.fs_fsize);
229 		exit(20);
230 	}
231 
232 #ifndef __DragonFly__
233 	if (maxbsize < bsize || !powerof2(maxbsize)) {
234 		sblock.fs_maxbsize = sblock.fs_bsize;
235 		printf("Extent size set to %d\n", sblock.fs_maxbsize);
236 	} else if (sblock.fs_maxbsize > FS_MAXCONTIG * sblock.fs_bsize) {
237 		sblock.fs_maxbsize = FS_MAXCONTIG * sblock.fs_bsize;
238 		printf("Extent size reduced to %d\n", sblock.fs_maxbsize);
239 	} else {
240 		sblock.fs_maxbsize = maxbsize;
241 	}
242 #endif
243 	sblock.fs_maxcontig = maxcontig;
244 #ifndef __DragonFly__
245 	if (sblock.fs_maxcontig < sblock.fs_maxbsize / sblock.fs_bsize) {
246 		sblock.fs_maxcontig = sblock.fs_maxbsize / sblock.fs_bsize;
247 		printf("Maxcontig raised to %d\n", sblock.fs_maxbsize);
248 	}
249 #endif
250 
251 	if (sblock.fs_maxcontig > 1)
252 		sblock.fs_contigsumsize = MIN(sblock.fs_maxcontig,FS_MAXCONTIG);
253 
254 	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
255 	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
256 	sblock.fs_qbmask = ~sblock.fs_bmask;
257 	sblock.fs_qfmask = ~sblock.fs_fmask;
258 	for (sblock.fs_bshift = 0, i = sblock.fs_bsize; i > 1; i >>= 1)
259 		sblock.fs_bshift++;
260 	for (sblock.fs_fshift = 0, i = sblock.fs_fsize; i > 1; i >>= 1)
261 		sblock.fs_fshift++;
262 	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
263 	for (sblock.fs_fragshift = 0, i = sblock.fs_frag; i > 1; i >>= 1)
264 		sblock.fs_fragshift++;
265 	if (sblock.fs_frag > MAXFRAG) {
266 		printf("fragment size %d is too small, "
267 			"minimum with block size %d is %d\n",
268 		    sblock.fs_fsize, sblock.fs_bsize,
269 		    sblock.fs_bsize / MAXFRAG);
270 		exit(21);
271 	}
272 	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / sectorsize);
273 #ifndef __DragonFly__
274 	sblock.fs_size = sblock.fs_providersize = fssize =
275 	    dbtofsb(&sblock, fssize);
276 #else
277 	sblock.fs_size = fssize = dbtofsb(&sblock, fssize);
278 #endif
279 
280 	if (Oflag <= 1) {
281 		sblock.fs_magic = FS_UFS1_MAGIC;
282 #ifndef __DragonFly__
283 		sblock.fs_sblockloc = SBLOCK_UFS1;
284 #endif
285 		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs1_daddr_t);
286 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
287 		sblock.fs_maxsymlinklen = ((UFS_NDADDR + UFS_NIADDR) *
288 		    sizeof (ufs1_daddr_t));
289 		sblock.fs_old_inodefmt = FS_44INODEFMT;
290 		sblock.fs_old_cgoffset = 0;
291 		sblock.fs_old_cgmask = 0xffffffff;
292 #ifndef __DragonFly__
293 		sblock.fs_old_size = sblock.fs_size;
294 #endif
295 		sblock.fs_old_rotdelay = 0;
296 		sblock.fs_old_rps = 60;
297 		sblock.fs_old_nspf = sblock.fs_fsize / sectorsize;
298 		sblock.fs_old_cpg = 1;
299 		sblock.fs_old_interleave = 1;
300 		sblock.fs_old_trackskew = 0;
301 		sblock.fs_old_cpc = 0;
302 		sblock.fs_old_postblformat = 1;
303 		sblock.fs_old_nrpos = 1;
304 #ifdef __DragonFly__	/* softupdates support */
305 		if (ffs_opts->softupdates == 1)
306 			sblock.fs_flags |= FS_DOSOFTDEP;
307 #else	/* XXX UFS2 */
308 	} else {
309 		sblock.fs_magic = FS_UFS2_MAGIC;
310 		sblock.fs_sblockloc = SBLOCK_UFS2;
311 		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs2_daddr_t);
312 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
313 		sblock.fs_maxsymlinklen = ((UFS_NDADDR + UFS_NIADDR) *
314 		    sizeof (ufs2_daddr_t));
315 		if (ffs_opts->softupdates == 1)
316 			sblock.fs_flags |= FS_DOSOFTDEP;
317 #endif
318 	}
319 
320 	sblock.fs_sblkno =
321 #ifndef __DragonFly__
322 	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
323 #else
324 	    roundup(howmany(8192 + SBLOCKSIZE, sblock.fs_fsize),
325 #endif
326 		sblock.fs_frag);
327 	sblock.fs_cblkno = (makefs_daddr_t)(sblock.fs_sblkno +
328 	    roundup(howmany(SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag));
329 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
330 	sblock.fs_maxfilesize = sblock.fs_bsize * UFS_NDADDR - 1;
331 	for (sizepb = sblock.fs_bsize, i = 0; i < UFS_NIADDR; i++) {
332 		sizepb *= NINDIR(&sblock);
333 		sblock.fs_maxfilesize += sizepb;
334 	}
335 
336 	/*
337 	 * Calculate the number of blocks to put into each cylinder group.
338 	 *
339 	 * This algorithm selects the number of blocks per cylinder
340 	 * group. The first goal is to have at least enough data blocks
341 	 * in each cylinder group to meet the density requirement. Once
342 	 * this goal is achieved we try to expand to have at least
343 	 * 1 cylinder group. Once this goal is achieved, we pack as
344 	 * many blocks into each cylinder group map as will fit.
345 	 *
346 	 * We start by calculating the smallest number of blocks that we
347 	 * can put into each cylinder group. If this is too big, we reduce
348 	 * the density until it fits.
349 	 */
350 	maxinum = (((int64_t)(1)) << 32) - INOPB(&sblock);
351 	minfragsperinode = 1 + fssize / maxinum;
352 	mindensity = minfragsperinode * fsize;
353 	if (density == 0)
354 		density = MAX(2, minfragsperinode) * fsize;
355 	if (density < mindensity) {
356 		origdensity = density;
357 		density = mindensity;
358 		fprintf(stderr, "density increased from %d to %d\n",
359 		    origdensity, density);
360 	}
361 	origdensity = density;
362 	if (!ffs_opts->min_inodes)
363 		density = MIN(density, MAX(2, minfragsperinode) * fsize);
364 	for (;;) {
365 		fragsperinode = MAX(numfrags(&sblock, density), 1);
366 		minfpg = fragsperinode * INOPB(&sblock);
367 		if (minfpg > sblock.fs_size)
368 			minfpg = sblock.fs_size;
369 		sblock.fs_ipg = INOPB(&sblock);
370 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
371 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
372 		if (sblock.fs_fpg < minfpg)
373 			sblock.fs_fpg = minfpg;
374 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
375 		    INOPB(&sblock));
376 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
377 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
378 		if (sblock.fs_fpg < minfpg)
379 			sblock.fs_fpg = minfpg;
380 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
381 		    INOPB(&sblock));
382 #ifndef __DragonFly__
383 		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
384 			break;
385 #else
386 		if (FBSD_CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
387 			break;
388 #endif
389 		density -= sblock.fs_fsize;
390 	}
391 	if (density != origdensity)
392 		printf("density reduced from %d to %d\n", origdensity, density);
393 
394 	if (maxblkspercg <= 0 || maxblkspercg >= fssize)
395 		maxblkspercg = fssize - 1;
396 	/*
397 	 * Start packing more blocks into the cylinder group until
398 	 * it cannot grow any larger, the number of cylinder groups
399 	 * drops below 1, or we reach the size requested.
400 	 */
401 	for ( ; sblock.fs_fpg < maxblkspercg; sblock.fs_fpg += sblock.fs_frag) {
402 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
403 		    INOPB(&sblock));
404 		if (sblock.fs_size / sblock.fs_fpg < 1)
405 			break;
406 #ifndef __DragonFly__
407 		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
408 			continue;
409 		if (CGSIZE(&sblock) == (unsigned long)sblock.fs_bsize)
410 			break;
411 #else
412 		if (FBSD_CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
413 			continue;
414 		if (FBSD_CGSIZE(&sblock) == (unsigned long)sblock.fs_bsize)
415 			break;
416 #endif
417 		sblock.fs_fpg -= sblock.fs_frag;
418 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
419 		    INOPB(&sblock));
420 		break;
421 	}
422 	/*
423 	 * Check to be sure that the last cylinder group has enough blocks
424 	 * to be viable. If it is too small, reduce the number of blocks
425 	 * per cylinder group which will have the effect of moving more
426 	 * blocks into the last cylinder group.
427 	 */
428 	optimalfpg = sblock.fs_fpg;
429 	for (;;) {
430 		sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
431 		lastminfpg = roundup(sblock.fs_iblkno +
432 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
433 		if (sblock.fs_size < lastminfpg) {
434 			printf("Filesystem size %lld < minimum size of %d\n",
435 			    (long long)sblock.fs_size, lastminfpg);
436 			exit(28);
437 		}
438 		if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
439 		    sblock.fs_size % sblock.fs_fpg == 0)
440 			break;
441 		sblock.fs_fpg -= sblock.fs_frag;
442 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
443 		    INOPB(&sblock));
444 	}
445 	if (optimalfpg != sblock.fs_fpg)
446 		printf("Reduced frags per cylinder group from %d to %d %s\n",
447 		   optimalfpg, sblock.fs_fpg, "to enlarge last cyl group");
448 #ifndef __DragonFly__
449 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
450 #else
451 	sblock.fs_cgsize = fragroundup(&sblock, FBSD_CGSIZE(&sblock));
452 #endif
453 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
454 	if (Oflag <= 1) {
455 		sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
456 		sblock.fs_old_nsect = sblock.fs_old_spc;
457 		sblock.fs_old_npsect = sblock.fs_old_spc;
458 		sblock.fs_old_ncyl = sblock.fs_ncg;
459 	}
460 
461 	/*
462 	 * fill in remaining fields of the super block
463 	 */
464 	sblock.fs_csaddr = cgdmin(&sblock, 0);
465 	sblock.fs_cssize =
466 	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
467 
468 	/*
469 	 * Setup memory for temporary in-core cylgroup summaries.
470 	 * Cribbed from ffs_mountfs().
471 	 */
472 	size = sblock.fs_cssize;
473 	if (sblock.fs_contigsumsize > 0)
474 		size += sblock.fs_ncg * sizeof(int32_t);
475 	space = ecalloc(1, size);
476 	sblock.fs_csp = space;
477 	space = (char *)space + sblock.fs_cssize;
478 	if (sblock.fs_contigsumsize > 0) {
479 		int32_t *lp;
480 
481 		sblock.fs_maxcluster = lp = space;
482 		for (i = 0; i < sblock.fs_ncg; i++)
483 		*lp++ = sblock.fs_contigsumsize;
484 	}
485 
486 	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
487 	if (sblock.fs_sbsize > SBLOCKSIZE)
488 		sblock.fs_sbsize = SBLOCKSIZE;
489 	sblock.fs_minfree = minfree;
490 	sblock.fs_maxcontig = maxcontig;
491 	sblock.fs_maxbpg = maxbpg;
492 	sblock.fs_optim = opt;
493 	sblock.fs_cgrotor = 0;
494 	sblock.fs_pendingblocks = 0;
495 	sblock.fs_pendinginodes = 0;
496 	sblock.fs_cstotal.cs_ndir = 0;
497 	sblock.fs_cstotal.cs_nbfree = 0;
498 	sblock.fs_cstotal.cs_nifree = 0;
499 	sblock.fs_cstotal.cs_nffree = 0;
500 	sblock.fs_fmod = 0;
501 	sblock.fs_ronly = 0;
502 	sblock.fs_state = 0;
503 	sblock.fs_clean = FS_ISCLEAN;
504 	sblock.fs_ronly = 0;
505 	sblock.fs_id[0] = tstamp;
506 	sblock.fs_id[1] = random();
507 	sblock.fs_fsmnt[0] = '\0';
508 	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
509 	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
510 	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
511 	sblock.fs_cstotal.cs_nbfree =
512 	    fragstoblks(&sblock, sblock.fs_dsize) -
513 	    howmany(csfrags, sblock.fs_frag);
514 	sblock.fs_cstotal.cs_nffree =
515 	    fragnum(&sblock, sblock.fs_size) +
516 	    (fragnum(&sblock, csfrags) > 0 ?
517 	    sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
518 	sblock.fs_cstotal.cs_nifree =
519 	    sblock.fs_ncg * sblock.fs_ipg - UFS_ROOTINO;
520 	sblock.fs_cstotal.cs_ndir = 0;
521 	sblock.fs_dsize -= csfrags;
522 	sblock.fs_time = tstamp;
523 #ifndef __DragonFly__
524 	if (Oflag <= 1) {
525 		sblock.fs_old_time = tstamp;
526 		sblock.fs_old_dsize = sblock.fs_dsize;
527 		sblock.fs_old_csaddr = sblock.fs_csaddr;
528 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
529 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
530 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
531 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
532 	}
533 #endif
534 	/*
535 	 * Dump out summary information about file system.
536 	 */
537 #define	B2MBFACTOR (1 / (1024.0 * 1024.0))
538 	printf("%s: %.1fMB (%lld sectors) block size %d, "
539 	       "fragment size %d\n",
540 	    fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
541 	    (long long)fsbtodb(&sblock, sblock.fs_size),
542 	    sblock.fs_bsize, sblock.fs_fsize);
543 	printf("\tusing %d cylinder groups of %.2fMB, %d blks, "
544 	       "%d inodes.\n",
545 	    sblock.fs_ncg,
546 	    (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
547 	    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
548 #undef B2MBFACTOR
549 	/*
550 	 * Now determine how wide each column will be, and calculate how
551 	 * many columns will fit in a 76 char line. 76 is the width of the
552 	 * subwindows in sysinst.
553 	 */
554 	printcolwidth = count_digits(
555 			fsbtodb(&sblock, cgsblock(&sblock, sblock.fs_ncg -1)));
556 	nprintcols = 76 / (printcolwidth + 2);
557 
558 	/*
559 	 * allocate space for superblock, cylinder group map, and
560 	 * two sets of inode blocks.
561 	 */
562 	if (sblock.fs_bsize < SBLOCKSIZE)
563 		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
564 	else
565 		iobufsize = 4 * sblock.fs_bsize;
566 	iobuf = ecalloc(1, iobufsize);
567 	/*
568 	 * Make a copy of the superblock into the buffer that we will be
569 	 * writing out in each cylinder group.
570 	 */
571 	memcpy(writebuf, &sblock, sbsize);
572 	if (fsopts->needswap)
573 		ffs_sb_swap(&sblock, (struct fs*)writebuf);
574 	memcpy(iobuf, writebuf, SBLOCKSIZE);
575 
576 	printf("super-block backups (for fsck -b #) at:");
577 	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
578 		initcg(cylno, tstamp, fsopts);
579 		if (cylno % nprintcols == 0)
580 			printf("\n");
581 		printf(" %*lld,", printcolwidth,
582 			(long long)fsbtodb(&sblock, cgsblock(&sblock, cylno)));
583 		fflush(stdout);
584 	}
585 	printf("\n");
586 
587 	/*
588 	 * Now construct the initial file system,
589 	 * then write out the super-block.
590 	 */
591 	sblock.fs_time = tstamp;
592 #ifndef __DragonFly__
593 	if (Oflag <= 1) {
594 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
595 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
596 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
597 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
598 	}
599 #endif
600 	if (fsopts->needswap)
601 		sblock.fs_flags |= FS_SWAPPED;
602 	ffs_write_superblock(&sblock, fsopts);
603 	return (&sblock);
604 }
605 
606 /*
607  * Write out the superblock and its duplicates,
608  * and the cylinder group summaries
609  */
610 void
611 ffs_write_superblock(struct fs *fs, const fsinfo_t *fsopts)
612 {
613 	int size, blks, i, saveflag;
614 	uint32_t cylno;
615 	void *space;
616 	char *wrbuf;
617 
618 	saveflag = fs->fs_flags & FS_INTERNAL;
619 	fs->fs_flags &= ~FS_INTERNAL;
620 
621         memcpy(writebuf, &sblock, sbsize);
622 	if (fsopts->needswap)
623 		ffs_sb_swap(fs, (struct fs*)writebuf);
624 #ifndef __DragonFly__
625 	ffs_wtfs(fs->fs_sblockloc / sectorsize, sbsize, writebuf, fsopts);
626 #else
627 	ffs_wtfs(8192 / sectorsize, sbsize, writebuf, fsopts);
628 #endif
629 
630 	/* Write out the duplicate super blocks */
631 	for (cylno = 0; cylno < fs->fs_ncg; cylno++)
632 		ffs_wtfs(fsbtodb(fs, cgsblock(fs, cylno)),
633 		    sbsize, writebuf, fsopts);
634 
635 	/* Write out the cylinder group summaries */
636 	size = fs->fs_cssize;
637 	blks = howmany(size, fs->fs_fsize);
638 	space = (void *)fs->fs_csp;
639 	wrbuf = emalloc(size);
640 	for (i = 0; i < blks; i+= fs->fs_frag) {
641 		size = fs->fs_bsize;
642 		if (i + fs->fs_frag > blks)
643 			size = (blks - i) * fs->fs_fsize;
644 		if (fsopts->needswap)
645 			ffs_csum_swap((struct csum *)space,
646 			    (struct csum *)wrbuf, size);
647 		else
648 			memcpy(wrbuf, space, (u_int)size);
649 		ffs_wtfs(fsbtodb(fs, fs->fs_csaddr + i), size, wrbuf, fsopts);
650 		space = (char *)space + size;
651 	}
652 	free(wrbuf);
653 	fs->fs_flags |= saveflag;
654 }
655 
656 /*
657  * Initialize a cylinder group.
658  */
659 static void
660 initcg(uint32_t cylno, time_t utime, const fsinfo_t *fsopts)
661 {
662 	makefs_daddr_t cbase, dmax;
663 	int32_t blkno;
664 	uint32_t i, j, d, dlower, dupper;
665 	struct ufs1_dinode *dp1;
666 #ifndef __DragonFly__ /* XXX UFS2 */
667 	struct ufs2_dinode *dp2;
668 #endif
669 	int start;
670 
671 	/*
672 	 * Determine block bounds for cylinder group.
673 	 * Allow space for super block summary information in first
674 	 * cylinder group.
675 	 */
676 	cbase = cgbase(&sblock, cylno);
677 	dmax = cbase + sblock.fs_fpg;
678 	if (dmax > sblock.fs_size)
679 		dmax = sblock.fs_size;
680 	dlower = cgsblock(&sblock, cylno) - cbase;
681 	dupper = cgdmin(&sblock, cylno) - cbase;
682 	if (cylno == 0)
683 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
684 	memset(&acg, 0, sblock.fs_cgsize);
685 	acg.cg_time = utime;
686 	acg.cg_magic = CG_MAGIC;
687 	acg.cg_cgx = cylno;
688 	acg.cg_niblk = sblock.fs_ipg;
689 #ifndef __DragonFly__ /* XXX UFS2 */
690 	acg.cg_initediblk = MIN(sblock.fs_ipg, 2 * INOPB(&sblock));
691 #endif
692 	acg.cg_ndblk = dmax - cbase;
693 	if (sblock.fs_contigsumsize > 0)
694 		acg.cg_nclusterblks = acg.cg_ndblk >> sblock.fs_fragshift;
695 	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
696 #ifndef __DragonFly__ /* XXX UFS2 */
697 	if (Oflag == 2) {
698 		acg.cg_iusedoff = start;
699 	} else
700 #endif
701 	{
702 		if (cylno == sblock.fs_ncg - 1)
703 #ifndef __DragonFly__
704 			acg.cg_old_ncyl = howmany(acg.cg_ndblk,
705 			    sblock.fs_fpg / sblock.fs_old_cpg);
706 #else
707 			acg.cg_ncyl = sblock.fs_ncyl % sblock.fs_cpg;
708 #endif
709 		else
710 			acg.cg_old_ncyl = sblock.fs_old_cpg;
711 #ifndef __DragonFly__
712 		acg.cg_old_time = acg.cg_time;
713 		acg.cg_time = 0;
714 		acg.cg_old_niblk = acg.cg_niblk;
715 		acg.cg_niblk = 0;
716 		acg.cg_initediblk = 0;
717 #endif
718 		acg.cg_old_btotoff = start;
719 		acg.cg_old_boff = acg.cg_old_btotoff +
720 		    sblock.fs_old_cpg * sizeof(int32_t);
721 		acg.cg_iusedoff = acg.cg_old_boff +
722 		    sblock.fs_old_cpg * sizeof(u_int16_t);
723 	}
724 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
725 	if (sblock.fs_contigsumsize <= 0) {
726 		acg.cg_nextfreeoff = acg.cg_freeoff +
727 		   howmany(sblock.fs_fpg, CHAR_BIT);
728 	} else {
729 		acg.cg_clustersumoff = acg.cg_freeoff +
730 		    howmany(sblock.fs_fpg, CHAR_BIT) - sizeof(int32_t);
731 		acg.cg_clustersumoff =
732 		    roundup(acg.cg_clustersumoff, sizeof(int32_t));
733 		acg.cg_clusteroff = acg.cg_clustersumoff +
734 		    (sblock.fs_contigsumsize + 1) * sizeof(int32_t);
735 		acg.cg_nextfreeoff = acg.cg_clusteroff +
736 		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
737 	}
738 	if (acg.cg_nextfreeoff > (uint32_t)sblock.fs_cgsize) {
739 		printf("Panic: cylinder group too big\n");
740 		exit(37);
741 	}
742 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
743 	if (cylno == 0)
744 		for (i = 0; i < UFS_ROOTINO; i++) {
745 			setbit(cg_inosused_swap(&acg, 0), i);
746 			acg.cg_cs.cs_nifree--;
747 		}
748 	if (cylno > 0) {
749 		/*
750 		 * In cylno 0, beginning space is reserved
751 		 * for boot and super blocks.
752 		 */
753 		for (d = 0, blkno = 0; d < dlower;) {
754 			ffs_setblock(&sblock, cg_blksfree_swap(&acg, 0), blkno);
755 			if (sblock.fs_contigsumsize > 0)
756 				setbit(cg_clustersfree_swap(&acg, 0), blkno);
757 			acg.cg_cs.cs_nbfree++;
758 #ifdef __DragonFly__ /* XXX swildner: our fsck checks these */
759 			cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
760 			cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
761 			    [cbtorpos(&sblock, d)]++;
762 #endif
763 			d += sblock.fs_frag;
764 			blkno++;
765 		}
766 	}
767 	if ((i = (dupper & (sblock.fs_frag - 1))) != 0) {
768 		acg.cg_frsum[sblock.fs_frag - i]++;
769 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
770 			setbit(cg_blksfree_swap(&acg, 0), dupper);
771 			acg.cg_cs.cs_nffree++;
772 		}
773 	}
774 	for (d = dupper, blkno = dupper >> sblock.fs_fragshift;
775 	     d + sblock.fs_frag <= acg.cg_ndblk; ) {
776 		ffs_setblock(&sblock, cg_blksfree_swap(&acg, 0), blkno);
777 		if (sblock.fs_contigsumsize > 0)
778 			setbit(cg_clustersfree_swap(&acg, 0), blkno);
779 		acg.cg_cs.cs_nbfree++;
780 #ifdef __DragonFly__ /* XXX swildner: our fsck checks these */
781 		cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
782 		cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
783 		    [cbtorpos(&sblock, d)]++;
784 #endif
785 		d += sblock.fs_frag;
786 		blkno++;
787 	}
788 	if (d < acg.cg_ndblk) {
789 		acg.cg_frsum[acg.cg_ndblk - d]++;
790 		for (; d < acg.cg_ndblk; d++) {
791 			setbit(cg_blksfree_swap(&acg, 0), d);
792 			acg.cg_cs.cs_nffree++;
793 		}
794 	}
795 	if (sblock.fs_contigsumsize > 0) {
796 		int32_t *sump = cg_clustersum_swap(&acg, 0);
797 		u_char *mapp = cg_clustersfree_swap(&acg, 0);
798 		int map = *mapp++;
799 		int bit = 1;
800 		int run = 0;
801 
802 		for (i = 0; i < acg.cg_nclusterblks; i++) {
803 			if ((map & bit) != 0) {
804 				run++;
805 			} else if (run != 0) {
806 				if (run > sblock.fs_contigsumsize)
807 					run = sblock.fs_contigsumsize;
808 				sump[run]++;
809 				run = 0;
810 			}
811 			if ((i & (CHAR_BIT - 1)) != (CHAR_BIT - 1)) {
812 				bit <<= 1;
813 			} else {
814 				map = *mapp++;
815 				bit = 1;
816 			}
817 		}
818 		if (run != 0) {
819 			if (run > sblock.fs_contigsumsize)
820 				run = sblock.fs_contigsumsize;
821 			sump[run]++;
822 		}
823 	}
824 	sblock.fs_cs(&sblock, cylno) = acg.cg_cs;
825 	/*
826 	 * Write out the duplicate super block, the cylinder group map
827 	 * and two blocks worth of inodes in a single write.
828 	 */
829 	start = MAX(sblock.fs_bsize, SBLOCKSIZE);
830 	memcpy(&iobuf[start], &acg, sblock.fs_cgsize);
831 	if (fsopts->needswap)
832 		ffs_cg_swap(&acg, (struct cg*)&iobuf[start], &sblock);
833 	start += sblock.fs_bsize;
834 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
835 #ifndef __DragonFly__ /* XXX UFS2 */
836 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
837 	for (i = 0; i < acg.cg_initediblk; i++) {
838 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
839 			/* No need to swap, it'll stay random */
840 			dp1->di_gen = random();
841 			dp1++;
842 		} else {
843 			dp2->di_gen = random();
844 			dp2++;
845 		}
846 	}
847 #endif
848 	ffs_wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf,
849 	    fsopts);
850 	/*
851 	 * For the old file system, we have to initialize all the inodes.
852 	 */
853 	if (Oflag <= 1) {
854 		for (i = 2 * sblock.fs_frag;
855 		     i < sblock.fs_ipg / INOPF(&sblock);
856 		     i += sblock.fs_frag) {
857 			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
858 			for (j = 0; j < INOPB(&sblock); j++) {
859 				dp1->di_gen = random();
860 				dp1++;
861 			}
862 			ffs_wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
863 			    sblock.fs_bsize, &iobuf[start], fsopts);
864 		}
865 	}
866 }
867 
868 /*
869  * read a block from the file system
870  */
871 void
872 ffs_rdfs(makefs_daddr_t bno, int size, void *bf, const fsinfo_t *fsopts)
873 {
874 	int n;
875 	off_t offset;
876 
877 	offset = (off_t)bno * fsopts->sectorsize + fsopts->offset;
878 	if (lseek(fsopts->fd, offset, SEEK_SET) < 0)
879 		err(1, "%s: seek error for sector %lld", __func__,
880 		    (long long)bno);
881 	n = read(fsopts->fd, bf, size);
882 	if (n == -1) {
883 		abort();
884 		err(1, "%s: read error bno %lld size %d", __func__,
885 		    (long long)bno, size);
886 	}
887 	else if (n != size)
888 		errx(1, "%s: read error for sector %lld", __func__,
889 		    (long long)bno);
890 }
891 
892 /*
893  * write a block to the file system
894  */
895 void
896 ffs_wtfs(makefs_daddr_t bno, int size, void *bf, const fsinfo_t *fsopts)
897 {
898 	int n;
899 	off_t offset;
900 
901 	offset = (off_t)bno * fsopts->sectorsize + fsopts->offset;
902 	if (lseek(fsopts->fd, offset, SEEK_SET) < 0)
903 		err(1, "%s: seek error for sector %lld", __func__,
904 		    (long long)bno);
905 	n = write(fsopts->fd, bf, size);
906 	if (n == -1)
907 		err(1, "%s: write error for sector %lld", __func__,
908 		    (long long)bno);
909 	else if (n != size)
910 		errx(1, "%s: write error for sector %lld", __func__,
911 		    (long long)bno);
912 }
913 
914 
915 /* Determine how many digits are needed to print a given integer */
916 static int
917 count_digits(int num)
918 {
919 	int ndig;
920 
921 	for(ndig = 1; num > 9; num /=10, ndig++);
922 
923 	return (ndig);
924 }
925 
926 static int
927 ilog2(int val)
928 {
929 	u_int n;
930 
931 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
932 		if (1 << n == val)
933 			return (n);
934 	errx(1, "%s: %d is not a power of 2", __func__, val);
935 }
936