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