mkfs.c revision 118493
1/*
2 * Copyright (c) 2002 Networks Associates Technology, Inc.
3 * All rights reserved.
4 *
5 * This software was developed for the FreeBSD Project by Marshall
6 * Kirk McKusick and Network Associates Laboratories, the Security
7 * Research Division of Network Associates, Inc. under DARPA/SPAWAR
8 * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
9 * research program.
10 *
11 * Copyright (c) 1980, 1989, 1993
12 *	The Regents of the University of California.  All rights reserved.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 *    notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 *    notice, this list of conditions and the following disclaimer in the
21 *    documentation and/or other materials provided with the distribution.
22 * 3. All advertising materials mentioning features or use of this software
23 *    must display the following acknowledgement:
24 *	This product includes software developed by the University of
25 *	California, Berkeley and its contributors.
26 * 4. 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#if 0
44#ifndef lint
45static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
46#endif /* not lint */
47#endif
48#include <sys/cdefs.h>
49__FBSDID("$FreeBSD: head/sbin/newfs/mkfs.c 118493 2003-08-05 13:35:17Z yar $");
50
51#include <err.h>
52#include <limits.h>
53#include <signal.h>
54#include <stdlib.h>
55#include <string.h>
56#include <stdint.h>
57#include <stdio.h>
58#include <unistd.h>
59#include <sys/param.h>
60#include <sys/time.h>
61#include <sys/types.h>
62#include <sys/wait.h>
63#include <sys/resource.h>
64#include <sys/stat.h>
65#include <ufs/ufs/dinode.h>
66#include <ufs/ufs/dir.h>
67#include <ufs/ffs/fs.h>
68#include <sys/disklabel.h>
69#include <sys/file.h>
70#include <sys/mman.h>
71#include <sys/ioctl.h>
72#include "newfs.h"
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
80static struct	csum *fscs;
81#define	sblock	disk.d_fs
82#define	acg	disk.d_cg
83
84union dinode {
85	struct ufs1_dinode dp1;
86	struct ufs2_dinode dp2;
87};
88#define DIP(dp, field) \
89	((sblock.fs_magic == FS_UFS1_MAGIC) ? \
90	(dp)->dp1.field : (dp)->dp2.field)
91
92static caddr_t iobuf;
93static long iobufsize;
94static ufs2_daddr_t alloc(int size, int mode);
95static int charsperline(void);
96static void clrblock(struct fs *, unsigned char *, int);
97static void fsinit(time_t);
98static int ilog2(int);
99static void initcg(int, time_t);
100static int isblock(struct fs *, unsigned char *, int);
101static void iput(union dinode *, ino_t);
102static int makedir(struct direct *, int);
103static void setblock(struct fs *, unsigned char *, int);
104static void wtfs(ufs2_daddr_t, int, char *);
105static u_int32_t newfs_random(void);
106
107void
108mkfs(struct partition *pp, char *fsys)
109{
110	int fragsperinode, optimalfpg, origdensity, minfpg, lastminfpg;
111	long i, j, cylno, csfrags;
112	time_t utime;
113	quad_t sizepb;
114	int width;
115	char tmpbuf[100];	/* XXX this will break in about 2,500 years */
116	union {
117		struct fs fdummy;
118		char cdummy[SBLOCKSIZE];
119	} dummy;
120#define fsdummy dummy.fdummy
121#define chdummy dummy.cdummy
122
123	/*
124	 * Our blocks == sector size, and the version of UFS we are using is
125	 * specified by Oflag.
126	 */
127	disk.d_bsize = sectorsize;
128	disk.d_ufs = Oflag;
129	if (Rflag) {
130		utime = 1000000000;
131	} else {
132		time(&utime);
133		arc4random_stir();
134	}
135	sblock.fs_old_flags = FS_FLAGS_UPDATED;
136	sblock.fs_flags = 0;
137	if (Uflag)
138		sblock.fs_flags |= FS_DOSOFTDEP;
139	if (Lflag)
140		strlcpy(sblock.fs_volname, volumelabel, MAXVOLLEN);
141	/*
142	 * Validate the given file system size.
143	 * Verify that its last block can actually be accessed.
144	 * Convert to file system fragment sized units.
145	 */
146	if (fssize <= 0) {
147		printf("preposterous size %jd\n", (intmax_t)fssize);
148		exit(13);
149	}
150	wtfs(fssize - (realsectorsize / DEV_BSIZE), realsectorsize,
151	    (char *)&sblock);
152	/*
153	 * collect and verify the file system density info
154	 */
155	sblock.fs_avgfilesize = avgfilesize;
156	sblock.fs_avgfpdir = avgfilesperdir;
157	if (sblock.fs_avgfilesize <= 0)
158		printf("illegal expected average file size %d\n",
159		    sblock.fs_avgfilesize), exit(14);
160	if (sblock.fs_avgfpdir <= 0)
161		printf("illegal expected number of files per directory %d\n",
162		    sblock.fs_avgfpdir), exit(15);
163	/*
164	 * collect and verify the block and fragment sizes
165	 */
166	sblock.fs_bsize = bsize;
167	sblock.fs_fsize = fsize;
168	if (!POWEROF2(sblock.fs_bsize)) {
169		printf("block size must be a power of 2, not %d\n",
170		    sblock.fs_bsize);
171		exit(16);
172	}
173	if (!POWEROF2(sblock.fs_fsize)) {
174		printf("fragment size must be a power of 2, not %d\n",
175		    sblock.fs_fsize);
176		exit(17);
177	}
178	if (sblock.fs_fsize < sectorsize) {
179		printf("increasing fragment size from %d to sector size (%d)\n",
180		    sblock.fs_fsize, sectorsize);
181		sblock.fs_fsize = sectorsize;
182	}
183	if (sblock.fs_bsize > MAXBSIZE) {
184		printf("decreasing block size from %d to maximum (%d)\n",
185		    sblock.fs_bsize, MAXBSIZE);
186		sblock.fs_bsize = MAXBSIZE;
187	}
188	if (sblock.fs_bsize < MINBSIZE) {
189		printf("increasing block size from %d to minimum (%d)\n",
190		    sblock.fs_bsize, MINBSIZE);
191		sblock.fs_bsize = MINBSIZE;
192	}
193	if (sblock.fs_fsize > MAXBSIZE) {
194		printf("decreasing fragment size from %d to maximum (%d)\n",
195		    sblock.fs_fsize, MAXBSIZE);
196		sblock.fs_fsize = MAXBSIZE;
197	}
198	if (sblock.fs_bsize < sblock.fs_fsize) {
199		printf("increasing block size from %d to fragment size (%d)\n",
200		    sblock.fs_bsize, sblock.fs_fsize);
201		sblock.fs_bsize = sblock.fs_fsize;
202	}
203	if (sblock.fs_fsize * MAXFRAG < sblock.fs_bsize) {
204		printf(
205		"increasing fragment size from %d to block size / %d (%d)\n",
206		    sblock.fs_fsize, MAXFRAG, sblock.fs_bsize / MAXFRAG);
207		sblock.fs_fsize = sblock.fs_bsize / MAXFRAG;
208	}
209	if (maxbsize < bsize || !POWEROF2(maxbsize)) {
210		sblock.fs_maxbsize = sblock.fs_bsize;
211		printf("Extent size set to %d\n", sblock.fs_maxbsize);
212	} else if (sblock.fs_maxbsize > FS_MAXCONTIG * sblock.fs_bsize) {
213		sblock.fs_maxbsize = FS_MAXCONTIG * sblock.fs_bsize;
214		printf("Extent size reduced to %d\n", sblock.fs_maxbsize);
215	} else {
216		sblock.fs_maxbsize = maxbsize;
217	}
218	sblock.fs_maxcontig = maxcontig;
219	if (sblock.fs_maxcontig < sblock.fs_maxbsize / sblock.fs_bsize) {
220		sblock.fs_maxcontig = sblock.fs_maxbsize / sblock.fs_bsize;
221		printf("Maxcontig raised to %d\n", sblock.fs_maxbsize);
222	}
223	if (sblock.fs_maxcontig > 1)
224		sblock.fs_contigsumsize = MIN(sblock.fs_maxcontig,FS_MAXCONTIG);
225	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
226	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
227	sblock.fs_qbmask = ~sblock.fs_bmask;
228	sblock.fs_qfmask = ~sblock.fs_fmask;
229	sblock.fs_bshift = ilog2(sblock.fs_bsize);
230	sblock.fs_fshift = ilog2(sblock.fs_fsize);
231	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
232	sblock.fs_fragshift = ilog2(sblock.fs_frag);
233	if (sblock.fs_frag > MAXFRAG) {
234		printf("fragment size %d is still too small (can't happen)\n",
235		    sblock.fs_bsize / MAXFRAG);
236		exit(21);
237	}
238	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / sectorsize);
239	sblock.fs_size = fssize = dbtofsb(&sblock, fssize);
240	if (Oflag == 1) {
241		sblock.fs_magic = FS_UFS1_MAGIC;
242		sblock.fs_sblockloc = SBLOCK_UFS1;
243		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs1_daddr_t);
244		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
245		sblock.fs_maxsymlinklen = ((NDADDR + NIADDR) *
246		    sizeof(ufs1_daddr_t));
247		sblock.fs_old_inodefmt = FS_44INODEFMT;
248		sblock.fs_old_cgoffset = 0;
249		sblock.fs_old_cgmask = 0xffffffff;
250		sblock.fs_old_size = sblock.fs_size;
251		sblock.fs_old_rotdelay = 0;
252		sblock.fs_old_rps = 60;
253		sblock.fs_old_nspf = sblock.fs_fsize / sectorsize;
254		sblock.fs_old_cpg = 1;
255		sblock.fs_old_interleave = 1;
256		sblock.fs_old_trackskew = 0;
257		sblock.fs_old_cpc = 0;
258		sblock.fs_old_postblformat = 1;
259		sblock.fs_old_nrpos = 1;
260	} else {
261		sblock.fs_magic = FS_UFS2_MAGIC;
262		sblock.fs_sblockloc = SBLOCK_UFS2;
263		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs2_daddr_t);
264		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
265		sblock.fs_maxsymlinklen = ((NDADDR + NIADDR) *
266		    sizeof(ufs2_daddr_t));
267	}
268	sblock.fs_sblkno =
269	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
270		sblock.fs_frag);
271	sblock.fs_cblkno = sblock.fs_sblkno +
272	    roundup(howmany(SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag);
273	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
274	sblock.fs_maxfilesize = sblock.fs_bsize * NDADDR - 1;
275	for (sizepb = sblock.fs_bsize, i = 0; i < NIADDR; i++) {
276		sizepb *= NINDIR(&sblock);
277		sblock.fs_maxfilesize += sizepb;
278	}
279	/*
280	 * Calculate the number of blocks to put into each cylinder group.
281	 *
282	 * This algorithm selects the number of blocks per cylinder
283	 * group. The first goal is to have at least enough data blocks
284	 * in each cylinder group to meet the density requirement. Once
285	 * this goal is achieved we try to expand to have at least
286	 * MINCYLGRPS cylinder groups. Once this goal is achieved, we
287	 * pack as many blocks into each cylinder group map as will fit.
288	 *
289	 * We start by calculating the smallest number of blocks that we
290	 * can put into each cylinder group. If this is too big, we reduce
291	 * the density until it fits.
292	 */
293	origdensity = density;
294	for (;;) {
295		fragsperinode = MAX(numfrags(&sblock, density), 1);
296		minfpg = fragsperinode * INOPB(&sblock);
297		if (minfpg > sblock.fs_size)
298			minfpg = sblock.fs_size;
299		sblock.fs_ipg = INOPB(&sblock);
300		sblock.fs_fpg = roundup(sblock.fs_iblkno +
301		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
302		if (sblock.fs_fpg < minfpg)
303			sblock.fs_fpg = minfpg;
304		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
305		    INOPB(&sblock));
306		sblock.fs_fpg = roundup(sblock.fs_iblkno +
307		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
308		if (sblock.fs_fpg < minfpg)
309			sblock.fs_fpg = minfpg;
310		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
311		    INOPB(&sblock));
312		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
313			break;
314		density -= sblock.fs_fsize;
315	}
316	if (density != origdensity)
317		printf("density reduced from %d to %d\n", origdensity, density);
318	/*
319	 * Start packing more blocks into the cylinder group until
320	 * it cannot grow any larger, the number of cylinder groups
321	 * drops below MINCYLGRPS, or we reach the size requested.
322	 */
323	for ( ; sblock.fs_fpg < maxblkspercg; sblock.fs_fpg += sblock.fs_frag) {
324		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
325		    INOPB(&sblock));
326		if (sblock.fs_size / sblock.fs_fpg < MINCYLGRPS)
327			break;
328		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize)
329			continue;
330		if (CGSIZE(&sblock) == (unsigned long)sblock.fs_bsize)
331			break;
332		sblock.fs_fpg -= sblock.fs_frag;
333		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
334		    INOPB(&sblock));
335		break;
336	}
337	/*
338	 * Check to be sure that the last cylinder group has enough blocks
339	 * to be viable. If it is too small, reduce the number of blocks
340	 * per cylinder group which will have the effect of moving more
341	 * blocks into the last cylinder group.
342	 */
343	optimalfpg = sblock.fs_fpg;
344	for (;;) {
345		sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
346		lastminfpg = roundup(sblock.fs_iblkno +
347		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
348		if (sblock.fs_size < lastminfpg) {
349			printf("Filesystem size %jd < minimum size of %d\n",
350			    (intmax_t)sblock.fs_size, lastminfpg);
351			exit(28);
352		}
353		if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
354		    sblock.fs_size % sblock.fs_fpg == 0)
355			break;
356		sblock.fs_fpg -= sblock.fs_frag;
357		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
358		    INOPB(&sblock));
359	}
360	if (optimalfpg != sblock.fs_fpg)
361		printf("Reduced frags per cylinder group from %d to %d %s\n",
362		   optimalfpg, sblock.fs_fpg, "to enlarge last cyl group");
363	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
364	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
365	if (Oflag == 1) {
366		sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
367		sblock.fs_old_nsect = sblock.fs_old_spc;
368		sblock.fs_old_npsect = sblock.fs_old_spc;
369		sblock.fs_old_ncyl = sblock.fs_ncg;
370	}
371	/*
372	 * fill in remaining fields of the super block
373	 */
374	sblock.fs_csaddr = cgdmin(&sblock, 0);
375	sblock.fs_cssize =
376	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
377	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
378	if (fscs == NULL)
379		errx(31, "calloc failed");
380	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
381	if (sblock.fs_sbsize > SBLOCKSIZE)
382		sblock.fs_sbsize = SBLOCKSIZE;
383	sblock.fs_minfree = minfree;
384	sblock.fs_maxbpg = maxbpg;
385	sblock.fs_optim = opt;
386	sblock.fs_cgrotor = 0;
387	sblock.fs_pendingblocks = 0;
388	sblock.fs_pendinginodes = 0;
389	sblock.fs_fmod = 0;
390	sblock.fs_ronly = 0;
391	sblock.fs_state = 0;
392	sblock.fs_clean = 1;
393	sblock.fs_id[0] = (long)utime;
394	sblock.fs_id[1] = newfs_random();
395	sblock.fs_fsmnt[0] = '\0';
396	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
397	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
398	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
399	sblock.fs_cstotal.cs_nbfree =
400	    fragstoblks(&sblock, sblock.fs_dsize) -
401	    howmany(csfrags, sblock.fs_frag);
402	sblock.fs_cstotal.cs_nffree =
403	    fragnum(&sblock, sblock.fs_size) +
404	    (fragnum(&sblock, csfrags) > 0 ?
405	     sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
406	sblock.fs_cstotal.cs_nifree = sblock.fs_ncg * sblock.fs_ipg - ROOTINO;
407	sblock.fs_cstotal.cs_ndir = 0;
408	sblock.fs_dsize -= csfrags;
409	sblock.fs_time = utime;
410	if (Oflag == 1) {
411		sblock.fs_old_time = utime;
412		sblock.fs_old_dsize = sblock.fs_dsize;
413		sblock.fs_old_csaddr = sblock.fs_csaddr;
414		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
415		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
416		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
417		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
418	}
419
420	/*
421	 * Dump out summary information about file system.
422	 */
423#	define B2MBFACTOR (1 / (1024.0 * 1024.0))
424	printf("%s: %.1fMB (%jd sectors) block size %d, fragment size %d\n",
425	    fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
426	    (intmax_t)fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize,
427	    sblock.fs_fsize);
428	printf("\tusing %d cylinder groups of %.2fMB, %d blks, %d inodes.\n",
429	    sblock.fs_ncg, (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
430	    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
431	if (sblock.fs_flags & FS_DOSOFTDEP)
432		printf("\twith soft updates\n");
433#	undef B2MBFACTOR
434
435	/*
436	 * Wipe out old UFS1 superblock(s) if necessary.
437	 */
438	if (!Nflag && Oflag != 1) {
439		i = bread(&disk, SBLOCK_UFS1 / disk.d_bsize, chdummy, SBLOCKSIZE);
440		if (i == -1)
441			err(1, "can't read old UFS1 superblock: %s", disk.d_error);
442
443		if (fsdummy.fs_magic == FS_UFS1_MAGIC) {
444			fsdummy.fs_magic = 0;
445			bwrite(&disk, SBLOCK_UFS1 / disk.d_bsize, chdummy, SBLOCKSIZE);
446			for (i = 0; i < fsdummy.fs_ncg; i++)
447				bwrite(&disk, fsbtodb(&fsdummy, cgsblock(&fsdummy, i)),
448	                    chdummy, SBLOCKSIZE);
449		}
450	}
451
452	/*
453	 * Now build the cylinders group blocks and
454	 * then print out indices of cylinder groups.
455	 */
456	printf("super-block backups (for fsck -b #) at:\n");
457	i = 0;
458	width = charsperline();
459	/*
460	 * allocate space for superblock, cylinder group map, and
461	 * two sets of inode blocks.
462	 */
463	if (sblock.fs_bsize < SBLOCKSIZE)
464		iobufsize = SBLOCKSIZE + 3 * sblock.fs_bsize;
465	else
466		iobufsize = 4 * sblock.fs_bsize;
467	if ((iobuf = malloc(iobufsize)) == 0) {
468		printf("Cannot allocate I/O buffer\n");
469		exit(38);
470	}
471	bzero(iobuf, iobufsize);
472	/*
473	 * Make a copy of the superblock into the buffer that we will be
474	 * writing out in each cylinder group.
475	 */
476	bcopy((char *)&sblock, iobuf, SBLOCKSIZE);
477	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
478		initcg(cylno, utime);
479		j = snprintf(tmpbuf, sizeof(tmpbuf), " %jd%s",
480		    (intmax_t)fsbtodb(&sblock, cgsblock(&sblock, cylno)),
481		    cylno < (sblock.fs_ncg-1) ? "," : "");
482		if (j < 0)
483			tmpbuf[j = 0] = '\0';
484		if (i + j >= width) {
485			printf("\n");
486			i = 0;
487		}
488		i += j;
489		printf("%s", tmpbuf);
490		fflush(stdout);
491	}
492	printf("\n");
493	if (Nflag)
494		exit(0);
495	/*
496	 * Now construct the initial file system,
497	 * then write out the super-block.
498	 */
499	fsinit(utime);
500	if (Oflag == 1) {
501		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
502		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
503		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
504		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
505	}
506	if (!Nflag)
507		sbwrite(&disk, 0);
508	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
509		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
510			sblock.fs_cssize - i < sblock.fs_bsize ?
511			sblock.fs_cssize - i : sblock.fs_bsize,
512			((char *)fscs) + i);
513	/*
514	 * Update information about this partion in pack
515	 * label, to that it may be updated on disk.
516	 */
517	if (pp != NULL) {
518		pp->p_fstype = FS_BSDFFS;
519		pp->p_fsize = sblock.fs_fsize;
520		pp->p_frag = sblock.fs_frag;
521		pp->p_cpg = sblock.fs_fpg;
522	}
523}
524
525/*
526 * Initialize a cylinder group.
527 */
528void
529initcg(int cylno, time_t utime)
530{
531	long i, j, d, dlower, dupper, blkno, start;
532	ufs2_daddr_t cbase, dmax;
533	struct ufs1_dinode *dp1;
534	struct ufs2_dinode *dp2;
535	struct csum *cs;
536
537	/*
538	 * Determine block bounds for cylinder group.
539	 * Allow space for super block summary information in first
540	 * cylinder group.
541	 */
542	cbase = cgbase(&sblock, cylno);
543	dmax = cbase + sblock.fs_fpg;
544	if (dmax > sblock.fs_size)
545		dmax = sblock.fs_size;
546	dlower = cgsblock(&sblock, cylno) - cbase;
547	dupper = cgdmin(&sblock, cylno) - cbase;
548	if (cylno == 0)
549		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
550	cs = &fscs[cylno];
551	memset(&acg, 0, sblock.fs_cgsize);
552	acg.cg_time = utime;
553	acg.cg_magic = CG_MAGIC;
554	acg.cg_cgx = cylno;
555	acg.cg_niblk = sblock.fs_ipg;
556	acg.cg_initediblk = sblock.fs_ipg < 2 * INOPB(&sblock) ?
557	    sblock.fs_ipg : 2 * INOPB(&sblock);
558	acg.cg_ndblk = dmax - cbase;
559	if (sblock.fs_contigsumsize > 0)
560		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
561	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
562	if (Oflag == 2) {
563		acg.cg_iusedoff = start;
564	} else {
565		acg.cg_old_ncyl = sblock.fs_old_cpg;
566		acg.cg_old_time = acg.cg_time;
567		acg.cg_time = 0;
568		acg.cg_old_niblk = acg.cg_niblk;
569		acg.cg_niblk = 0;
570		acg.cg_initediblk = 0;
571		acg.cg_old_btotoff = start;
572		acg.cg_old_boff = acg.cg_old_btotoff +
573		    sblock.fs_old_cpg * sizeof(int32_t);
574		acg.cg_iusedoff = acg.cg_old_boff +
575		    sblock.fs_old_cpg * sizeof(u_int16_t);
576	}
577	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
578	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
579	if (sblock.fs_contigsumsize > 0) {
580		acg.cg_clustersumoff =
581		    roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
582		acg.cg_clustersumoff -= sizeof(u_int32_t);
583		acg.cg_clusteroff = acg.cg_clustersumoff +
584		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
585		acg.cg_nextfreeoff = acg.cg_clusteroff +
586		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
587	}
588	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
589		printf("Panic: cylinder group too big\n");
590		exit(37);
591	}
592	acg.cg_cs.cs_nifree += sblock.fs_ipg;
593	if (cylno == 0)
594		for (i = 0; i < (long)ROOTINO; i++) {
595			setbit(cg_inosused(&acg), i);
596			acg.cg_cs.cs_nifree--;
597		}
598	if (cylno > 0) {
599		/*
600		 * In cylno 0, beginning space is reserved
601		 * for boot and super blocks.
602		 */
603		for (d = 0; d < dlower; d += sblock.fs_frag) {
604			blkno = d / sblock.fs_frag;
605			setblock(&sblock, cg_blksfree(&acg), blkno);
606			if (sblock.fs_contigsumsize > 0)
607				setbit(cg_clustersfree(&acg), blkno);
608			acg.cg_cs.cs_nbfree++;
609		}
610	}
611	if ((i = dupper % sblock.fs_frag)) {
612		acg.cg_frsum[sblock.fs_frag - i]++;
613		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
614			setbit(cg_blksfree(&acg), dupper);
615			acg.cg_cs.cs_nffree++;
616		}
617	}
618	for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
619	     d += sblock.fs_frag) {
620		blkno = d / sblock.fs_frag;
621		setblock(&sblock, cg_blksfree(&acg), blkno);
622		if (sblock.fs_contigsumsize > 0)
623			setbit(cg_clustersfree(&acg), blkno);
624		acg.cg_cs.cs_nbfree++;
625	}
626	if (d < acg.cg_ndblk) {
627		acg.cg_frsum[acg.cg_ndblk - d]++;
628		for (; d < acg.cg_ndblk; d++) {
629			setbit(cg_blksfree(&acg), d);
630			acg.cg_cs.cs_nffree++;
631		}
632	}
633	if (sblock.fs_contigsumsize > 0) {
634		int32_t *sump = cg_clustersum(&acg);
635		u_char *mapp = cg_clustersfree(&acg);
636		int map = *mapp++;
637		int bit = 1;
638		int run = 0;
639
640		for (i = 0; i < acg.cg_nclusterblks; i++) {
641			if ((map & bit) != 0)
642				run++;
643			else if (run != 0) {
644				if (run > sblock.fs_contigsumsize)
645					run = sblock.fs_contigsumsize;
646				sump[run]++;
647				run = 0;
648			}
649			if ((i & (CHAR_BIT - 1)) != CHAR_BIT - 1)
650				bit <<= 1;
651			else {
652				map = *mapp++;
653				bit = 1;
654			}
655		}
656		if (run != 0) {
657			if (run > sblock.fs_contigsumsize)
658				run = sblock.fs_contigsumsize;
659			sump[run]++;
660		}
661	}
662	*cs = acg.cg_cs;
663	/*
664	 * Write out the duplicate super block, the cylinder group map
665	 * and two blocks worth of inodes in a single write.
666	 */
667	start = sblock.fs_bsize > SBLOCKSIZE ? sblock.fs_bsize : SBLOCKSIZE;
668	bcopy((char *)&acg, &iobuf[start], sblock.fs_cgsize);
669	start += sblock.fs_bsize;
670	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
671	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
672	for (i = 0; i < acg.cg_initediblk; i++) {
673		if (sblock.fs_magic == FS_UFS1_MAGIC) {
674			dp1->di_gen = newfs_random();
675			dp1++;
676		} else {
677			dp2->di_gen = newfs_random();
678			dp2++;
679		}
680	}
681	wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)), iobufsize, iobuf);
682	/*
683	 * For the old file system, we have to initialize all the inodes.
684	 */
685	if (Oflag == 1) {
686		for (i = 2 * sblock.fs_frag;
687		     i < sblock.fs_ipg / INOPF(&sblock);
688		     i += sblock.fs_frag) {
689			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
690			for (j = 0; j < INOPB(&sblock); j++) {
691				dp1->di_gen = newfs_random();
692				dp1++;
693			}
694			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
695			    sblock.fs_bsize, &iobuf[start]);
696		}
697	}
698}
699
700/*
701 * initialize the file system
702 */
703#define PREDEFDIR 2
704
705struct direct root_dir[] = {
706	{ ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
707	{ ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
708};
709
710void
711fsinit(time_t utime)
712{
713	union dinode node;
714
715	memset(&node, 0, sizeof node);
716	if (sblock.fs_magic == FS_UFS1_MAGIC) {
717		/*
718		 * initialize the node
719		 */
720		node.dp1.di_atime = utime;
721		node.dp1.di_mtime = utime;
722		node.dp1.di_ctime = utime;
723		/*
724		 * create the root directory
725		 */
726		node.dp1.di_mode = IFDIR | UMASK;
727		node.dp1.di_nlink = PREDEFDIR;
728		node.dp1.di_size = makedir(root_dir, PREDEFDIR);
729		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
730		node.dp1.di_blocks =
731		    btodb(fragroundup(&sblock, node.dp1.di_size));
732		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize,
733		    iobuf);
734	} else {
735		/*
736		 * initialize the node
737		 */
738		node.dp2.di_atime = utime;
739		node.dp2.di_mtime = utime;
740		node.dp2.di_ctime = utime;
741		node.dp2.di_birthtime = utime;
742		/*
743		 * create the root directory
744		 */
745		node.dp2.di_mode = IFDIR | UMASK;
746		node.dp2.di_nlink = PREDEFDIR;
747		node.dp2.di_size = makedir(root_dir, PREDEFDIR);
748		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
749		node.dp2.di_blocks =
750		    btodb(fragroundup(&sblock, node.dp2.di_size));
751		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize,
752		    iobuf);
753	}
754	iput(&node, ROOTINO);
755}
756
757/*
758 * construct a set of directory entries in "iobuf".
759 * return size of directory.
760 */
761int
762makedir(struct direct *protodir, int entries)
763{
764	char *cp;
765	int i, spcleft;
766
767	spcleft = DIRBLKSIZ;
768	memset(iobuf, 0, DIRBLKSIZ);
769	for (cp = iobuf, i = 0; i < entries - 1; i++) {
770		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
771		memmove(cp, &protodir[i], protodir[i].d_reclen);
772		cp += protodir[i].d_reclen;
773		spcleft -= protodir[i].d_reclen;
774	}
775	protodir[i].d_reclen = spcleft;
776	memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
777	return (DIRBLKSIZ);
778}
779
780/*
781 * allocate a block or frag
782 */
783ufs2_daddr_t
784alloc(int size, int mode)
785{
786	int i, d, blkno, frag;
787
788	bread(&disk, fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
789	    sblock.fs_cgsize);
790	if (acg.cg_magic != CG_MAGIC) {
791		printf("cg 0: bad magic number\n");
792		exit(38);
793	}
794	if (acg.cg_cs.cs_nbfree == 0) {
795		printf("first cylinder group ran out of space\n");
796		exit(39);
797	}
798	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
799		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
800			goto goth;
801	printf("internal error: can't find block in cyl 0\n");
802	exit(40);
803goth:
804	blkno = fragstoblks(&sblock, d);
805	clrblock(&sblock, cg_blksfree(&acg), blkno);
806	if (sblock.fs_contigsumsize > 0)
807		clrbit(cg_clustersfree(&acg), blkno);
808	acg.cg_cs.cs_nbfree--;
809	sblock.fs_cstotal.cs_nbfree--;
810	fscs[0].cs_nbfree--;
811	if (mode & IFDIR) {
812		acg.cg_cs.cs_ndir++;
813		sblock.fs_cstotal.cs_ndir++;
814		fscs[0].cs_ndir++;
815	}
816	if (size != sblock.fs_bsize) {
817		frag = howmany(size, sblock.fs_fsize);
818		fscs[0].cs_nffree += sblock.fs_frag - frag;
819		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
820		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
821		acg.cg_frsum[sblock.fs_frag - frag]++;
822		for (i = frag; i < sblock.fs_frag; i++)
823			setbit(cg_blksfree(&acg), d + i);
824	}
825	/* XXX cgwrite(&disk, 0)??? */
826	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
827	    (char *)&acg);
828	return ((ufs2_daddr_t)d);
829}
830
831/*
832 * Allocate an inode on the disk
833 */
834void
835iput(union dinode *ip, ino_t ino)
836{
837	ufs2_daddr_t d;
838	int c;
839
840	c = ino_to_cg(&sblock, ino);
841	bread(&disk, fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
842	    sblock.fs_cgsize);
843	if (acg.cg_magic != CG_MAGIC) {
844		printf("cg 0: bad magic number\n");
845		exit(31);
846	}
847	acg.cg_cs.cs_nifree--;
848	setbit(cg_inosused(&acg), ino);
849	wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
850	    (char *)&acg);
851	sblock.fs_cstotal.cs_nifree--;
852	fscs[0].cs_nifree--;
853	if (ino >= (unsigned long)sblock.fs_ipg * sblock.fs_ncg) {
854		printf("fsinit: inode value out of range (%d).\n", ino);
855		exit(32);
856	}
857	d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
858	bread(&disk, d, (char *)iobuf, sblock.fs_bsize);
859	if (sblock.fs_magic == FS_UFS1_MAGIC)
860		((struct ufs1_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
861		    ip->dp1;
862	else
863		((struct ufs2_dinode *)iobuf)[ino_to_fsbo(&sblock, ino)] =
864		    ip->dp2;
865	wtfs(d, sblock.fs_bsize, (char *)iobuf);
866}
867
868/*
869 * possibly write to disk
870 */
871static void
872wtfs(ufs2_daddr_t bno, int size, char *bf)
873{
874	if (Nflag)
875		return;
876	if (bwrite(&disk, bno, bf, size) < 0)
877		err(36, "wtfs: %d bytes at sector %jd", size, (intmax_t)bno);
878}
879
880/*
881 * check if a block is available
882 */
883static int
884isblock(struct fs *fs, unsigned char *cp, int h)
885{
886	unsigned char mask;
887
888	switch (fs->fs_frag) {
889	case 8:
890		return (cp[h] == 0xff);
891	case 4:
892		mask = 0x0f << ((h & 0x1) << 2);
893		return ((cp[h >> 1] & mask) == mask);
894	case 2:
895		mask = 0x03 << ((h & 0x3) << 1);
896		return ((cp[h >> 2] & mask) == mask);
897	case 1:
898		mask = 0x01 << (h & 0x7);
899		return ((cp[h >> 3] & mask) == mask);
900	default:
901		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
902		return (0);
903	}
904}
905
906/*
907 * take a block out of the map
908 */
909static void
910clrblock(struct fs *fs, unsigned char *cp, int h)
911{
912	switch ((fs)->fs_frag) {
913	case 8:
914		cp[h] = 0;
915		return;
916	case 4:
917		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
918		return;
919	case 2:
920		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
921		return;
922	case 1:
923		cp[h >> 3] &= ~(0x01 << (h & 0x7));
924		return;
925	default:
926		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
927		return;
928	}
929}
930
931/*
932 * put a block into the map
933 */
934static void
935setblock(struct fs *fs, unsigned char *cp, int h)
936{
937	switch (fs->fs_frag) {
938	case 8:
939		cp[h] = 0xff;
940		return;
941	case 4:
942		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
943		return;
944	case 2:
945		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
946		return;
947	case 1:
948		cp[h >> 3] |= (0x01 << (h & 0x7));
949		return;
950	default:
951		fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
952		return;
953	}
954}
955
956/*
957 * Determine the number of characters in a
958 * single line.
959 */
960
961static int
962charsperline(void)
963{
964	int columns;
965	char *cp;
966	struct winsize ws;
967
968	columns = 0;
969	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
970		columns = ws.ws_col;
971	if (columns == 0 && (cp = getenv("COLUMNS")))
972		columns = atoi(cp);
973	if (columns == 0)
974		columns = 80;	/* last resort */
975	return (columns);
976}
977
978static int
979ilog2(int val)
980{
981	u_int n;
982
983	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
984		if (1 << n == val)
985			return (n);
986	errx(1, "ilog2: %d is not a power of 2\n", val);
987}
988
989/*
990 * For the regression test, return predictable random values.
991 * Otherwise use a true random number generator.
992 */
993static u_int32_t
994newfs_random(void)
995{
996	static int nextnum = 1;
997
998	if (Rflag)
999		return (nextnum++);
1000	return (arc4random());
1001}
1002