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