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