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