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