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