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