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