xref: /freebsd-14-stable/sbin/newfs/mkfs.c (revision 5572827428bb54e5a22aa81c8c8826d033205406)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2002 Networks Associates Technology, Inc.
5  * All rights reserved.
6  *
7  * This software was developed for the FreeBSD Project by Marshall
8  * Kirk McKusick and Network Associates Laboratories, the Security
9  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
10  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
11  * research program.
12  *
13  * Copyright (c) 1980, 1989, 1993
14  *	The Regents of the University of California.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40 
41 #if 0
42 #ifndef lint
43 static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
44 #endif /* not lint */
45 #endif
46 #include <sys/cdefs.h>
47 #define _WANT_P_OSREL
48 #include <sys/param.h>
49 #include <sys/disklabel.h>
50 #include <sys/file.h>
51 #include <sys/ioctl.h>
52 #include <sys/mman.h>
53 #include <sys/resource.h>
54 #include <sys/stat.h>
55 #include <sys/wait.h>
56 #include <err.h>
57 #include <grp.h>
58 #include <limits.h>
59 #include <signal.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <stdint.h>
63 #include <stdio.h>
64 #include <time.h>
65 #include <unistd.h>
66 #include <ufs/ufs/dinode.h>
67 #include <ufs/ufs/dir.h>
68 #include <ufs/ffs/fs.h>
69 #include "newfs.h"
70 
71 /*
72  * make file system for cylinder-group style file systems
73  */
74 #define UMASK		0755
75 #define POWEROF2(num)	(((num) & ((num) - 1)) == 0)
76 
77 /*
78  * The definition of "struct cg" used to contain an extra field at the end
79  * to represent the variable-length data that followed the fixed structure.
80  * This had the effect of artificially limiting the number of blocks that
81  * newfs would put in a CG, since newfs thought that the fixed-size header
82  * was bigger than it really was.  When we started validating that the CG
83  * header data actually fit into one fs block, the placeholder field caused
84  * a problem because it caused struct cg to be a different size depending on
85  * platform.  The placeholder field was later removed, but this caused a
86  * backward compatibility problem with older binaries that still thought
87  * struct cg was larger, and a new file system could fail validation if
88  * viewed by the older binaries.  To avoid this compatibility problem, we
89  * now artificially reduce the amount of space that the variable-length data
90  * can use such that new file systems will pass validation by older binaries.
91  */
92 #define CGSIZEFUDGE 8
93 
94 static struct	csum *fscs;
95 #define	sblock	disk.d_fs
96 #define	acg	disk.d_cg
97 
98 #define DIP(dp, field) \
99 	((sblock.fs_magic == FS_UFS1_MAGIC) ? \
100 	(dp)->dp1.field : (dp)->dp2.field)
101 
102 static caddr_t iobuf;
103 static long iobufsize;
104 static ufs2_daddr_t alloc(int size, int mode);
105 static int charsperline(void);
106 static void clrblock(struct fs *, unsigned char *, int);
107 static void fsinit(time_t);
108 static int ilog2(int);
109 static void initcg(int, time_t);
110 static int isblock(struct fs *, unsigned char *, int);
111 static void iput(union dinode *, ino_t);
112 static int makedir(struct direct *, int);
113 static void setblock(struct fs *, unsigned char *, int);
114 static void wtfs(ufs2_daddr_t, int, char *);
115 static u_int32_t newfs_random(void);
116 
117 void
mkfs(struct partition * pp,char * fsys)118 mkfs(struct partition *pp, char *fsys)
119 {
120 	int fragsperinode, optimalfpg, origdensity, minfpg, lastminfpg;
121 	long i, j, csfrags;
122 	uint cg;
123 	time_t utime;
124 	quad_t sizepb;
125 	int width;
126 	ino_t maxinum;
127 	int minfragsperinode;	/* minimum ratio of frags to inodes */
128 	char tmpbuf[100];	/* XXX this will break in about 2,500 years */
129 	struct fsrecovery *fsr;
130 	char *fsrbuf;
131 	union {
132 		struct fs fdummy;
133 		char cdummy[SBLOCKSIZE];
134 	} dummy;
135 #define fsdummy dummy.fdummy
136 #define chdummy dummy.cdummy
137 
138 	/*
139 	 * Our blocks == sector size, and the version of UFS we are using is
140 	 * specified by Oflag.
141 	 */
142 	disk.d_bsize = sectorsize;
143 	disk.d_ufs = Oflag;
144 	if (Rflag)
145 		utime = 1000000000;
146 	else
147 		time(&utime);
148 	if ((sblock.fs_si = malloc(sizeof(struct fs_summary_info))) == NULL) {
149 		printf("Superblock summary info allocation failed.\n");
150 		exit(18);
151 	}
152 	sblock.fs_old_flags = FS_FLAGS_UPDATED;
153 	sblock.fs_flags = 0;
154 	if (Uflag)
155 		sblock.fs_flags |= FS_DOSOFTDEP;
156 	if (Lflag)
157 		strlcpy(sblock.fs_volname, volumelabel, MAXVOLLEN);
158 	if (Jflag)
159 		sblock.fs_flags |= FS_GJOURNAL;
160 	if (lflag)
161 		sblock.fs_flags |= FS_MULTILABEL;
162 	if (tflag)
163 		sblock.fs_flags |= FS_TRIM;
164 	/*
165 	 * Validate the given file system size.
166 	 * Verify that its last block can actually be accessed.
167 	 * Convert to file system fragment sized units.
168 	 */
169 	if (fssize <= 0) {
170 		printf("preposterous size %jd\n", (intmax_t)fssize);
171 		exit(13);
172 	}
173 	wtfs(fssize - (realsectorsize / DEV_BSIZE), realsectorsize,
174 	    (char *)&sblock);
175 	/*
176 	 * collect and verify the file system density info
177 	 */
178 	sblock.fs_avgfilesize = avgfilesize;
179 	sblock.fs_avgfpdir = avgfilesperdir;
180 	if (sblock.fs_avgfilesize <= 0)
181 		printf("illegal expected average file size %d\n",
182 		    sblock.fs_avgfilesize), exit(14);
183 	if (sblock.fs_avgfpdir <= 0)
184 		printf("illegal expected number of files per directory %d\n",
185 		    sblock.fs_avgfpdir), exit(15);
186 
187 restart:
188 	/*
189 	 * collect and verify the block and fragment sizes
190 	 */
191 	sblock.fs_bsize = bsize;
192 	sblock.fs_fsize = fsize;
193 	if (!POWEROF2(sblock.fs_bsize)) {
194 		printf("block size must be a power of 2, not %d\n",
195 		    sblock.fs_bsize);
196 		exit(16);
197 	}
198 	if (!POWEROF2(sblock.fs_fsize)) {
199 		printf("fragment size must be a power of 2, not %d\n",
200 		    sblock.fs_fsize);
201 		exit(17);
202 	}
203 	if (sblock.fs_fsize < sectorsize) {
204 		printf("increasing fragment size from %d to sector size (%d)\n",
205 		    sblock.fs_fsize, sectorsize);
206 		sblock.fs_fsize = sectorsize;
207 	}
208 	if (sblock.fs_bsize > MAXBSIZE) {
209 		printf("decreasing block size from %d to maximum (%d)\n",
210 		    sblock.fs_bsize, MAXBSIZE);
211 		sblock.fs_bsize = MAXBSIZE;
212 	}
213 	if (sblock.fs_bsize < MINBSIZE) {
214 		printf("increasing block size from %d to minimum (%d)\n",
215 		    sblock.fs_bsize, MINBSIZE);
216 		sblock.fs_bsize = MINBSIZE;
217 	}
218 	if (sblock.fs_fsize > MAXBSIZE) {
219 		printf("decreasing fragment size from %d to maximum (%d)\n",
220 		    sblock.fs_fsize, MAXBSIZE);
221 		sblock.fs_fsize = MAXBSIZE;
222 	}
223 	if (sblock.fs_bsize < sblock.fs_fsize) {
224 		printf("increasing block size from %d to fragment size (%d)\n",
225 		    sblock.fs_bsize, sblock.fs_fsize);
226 		sblock.fs_bsize = sblock.fs_fsize;
227 	}
228 	if (sblock.fs_fsize * MAXFRAG < sblock.fs_bsize) {
229 		printf(
230 		"increasing fragment size from %d to block size / %d (%d)\n",
231 		    sblock.fs_fsize, MAXFRAG, sblock.fs_bsize / MAXFRAG);
232 		sblock.fs_fsize = sblock.fs_bsize / MAXFRAG;
233 	}
234 	if (maxbsize == 0)
235 		maxbsize = bsize;
236 	if (maxbsize < bsize || !POWEROF2(maxbsize)) {
237 		sblock.fs_maxbsize = sblock.fs_bsize;
238 		printf("Extent size set to %d\n", sblock.fs_maxbsize);
239 	} else if (maxbsize > FS_MAXCONTIG * sblock.fs_bsize) {
240 		sblock.fs_maxbsize = FS_MAXCONTIG * sblock.fs_bsize;
241 		printf("Extent size reduced to %d\n", sblock.fs_maxbsize);
242 	} else {
243 		sblock.fs_maxbsize = maxbsize;
244 	}
245 	/*
246 	 * Maxcontig sets the default for the maximum number of blocks
247 	 * that may be allocated sequentially. With file system clustering
248 	 * it is possible to allocate contiguous blocks up to the maximum
249 	 * transfer size permitted by the controller or buffering.
250 	 */
251 	if (maxcontig == 0)
252 		maxcontig = MAX(1, MAXPHYS / bsize);
253 	sblock.fs_maxcontig = maxcontig;
254 	if (sblock.fs_maxcontig < sblock.fs_maxbsize / sblock.fs_bsize) {
255 		sblock.fs_maxcontig = sblock.fs_maxbsize / sblock.fs_bsize;
256 		printf("Maxcontig raised to %d\n", sblock.fs_maxbsize);
257 	}
258 	if (sblock.fs_maxcontig > 1)
259 		sblock.fs_contigsumsize = MIN(sblock.fs_maxcontig,FS_MAXCONTIG);
260 	sblock.fs_bmask = ~(sblock.fs_bsize - 1);
261 	sblock.fs_fmask = ~(sblock.fs_fsize - 1);
262 	sblock.fs_qbmask = ~sblock.fs_bmask;
263 	sblock.fs_qfmask = ~sblock.fs_fmask;
264 	sblock.fs_bshift = ilog2(sblock.fs_bsize);
265 	sblock.fs_fshift = ilog2(sblock.fs_fsize);
266 	sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
267 	sblock.fs_fragshift = ilog2(sblock.fs_frag);
268 	if (sblock.fs_frag > MAXFRAG) {
269 		printf("fragment size %d is still too small (can't happen)\n",
270 		    sblock.fs_bsize / MAXFRAG);
271 		exit(21);
272 	}
273 	sblock.fs_fsbtodb = ilog2(sblock.fs_fsize / sectorsize);
274 	sblock.fs_size = fssize = dbtofsb(&sblock, fssize);
275 	sblock.fs_providersize = dbtofsb(&sblock, mediasize / sectorsize);
276 
277 	/*
278 	 * Before the filesystem is finally initialized, mark it
279 	 * as incompletely initialized.
280 	 */
281 	sblock.fs_magic = FS_BAD_MAGIC;
282 
283 	if (Oflag == 1) {
284 		sblock.fs_sblockloc = SBLOCK_UFS1;
285 		sblock.fs_sblockactualloc = SBLOCK_UFS1;
286 		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs1_daddr_t);
287 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
288 		sblock.fs_maxsymlinklen = ((UFS_NDADDR + UFS_NIADDR) *
289 		    sizeof(ufs1_daddr_t));
290 		sblock.fs_old_inodefmt = FS_44INODEFMT;
291 		sblock.fs_old_cgoffset = 0;
292 		sblock.fs_old_cgmask = 0xffffffff;
293 		sblock.fs_old_size = sblock.fs_size;
294 		sblock.fs_old_rotdelay = 0;
295 		sblock.fs_old_rps = 60;
296 		sblock.fs_old_nspf = sblock.fs_fsize / sectorsize;
297 		sblock.fs_old_cpg = 1;
298 		sblock.fs_old_interleave = 1;
299 		sblock.fs_old_trackskew = 0;
300 		sblock.fs_old_cpc = 0;
301 		sblock.fs_old_postblformat = 1;
302 		sblock.fs_old_nrpos = 1;
303 	} else {
304 		sblock.fs_sblockloc = SBLOCK_UFS2;
305 		sblock.fs_sblockactualloc = SBLOCK_UFS2;
306 		sblock.fs_nindir = sblock.fs_bsize / sizeof(ufs2_daddr_t);
307 		sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs2_dinode);
308 		sblock.fs_maxsymlinklen = ((UFS_NDADDR + UFS_NIADDR) *
309 		    sizeof(ufs2_daddr_t));
310 	}
311 	sblock.fs_sblkno =
312 	    roundup(howmany(sblock.fs_sblockloc + SBLOCKSIZE, sblock.fs_fsize),
313 		sblock.fs_frag);
314 	sblock.fs_cblkno = sblock.fs_sblkno +
315 	    roundup(howmany(SBLOCKSIZE, sblock.fs_fsize), sblock.fs_frag);
316 	sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
317 	sblock.fs_maxfilesize = sblock.fs_bsize * UFS_NDADDR - 1;
318 	for (sizepb = sblock.fs_bsize, i = 0; i < UFS_NIADDR; i++) {
319 		sizepb *= NINDIR(&sblock);
320 		sblock.fs_maxfilesize += sizepb;
321 	}
322 
323 	/*
324 	 * It's impossible to create a snapshot in case that fs_maxfilesize
325 	 * is smaller than the fssize.
326 	 */
327 	if (sblock.fs_maxfilesize < (u_quad_t)fssize) {
328 		warnx("WARNING: You will be unable to create snapshots on this "
329 		      "file system.  Correct by using a larger blocksize.");
330 	}
331 
332 	/*
333 	 * Calculate the number of blocks to put into each cylinder group.
334 	 *
335 	 * This algorithm selects the number of blocks per cylinder
336 	 * group. The first goal is to have at least enough data blocks
337 	 * in each cylinder group to meet the density requirement. Once
338 	 * this goal is achieved we try to expand to have at least
339 	 * MINCYLGRPS cylinder groups. Once this goal is achieved, we
340 	 * pack as many blocks into each cylinder group map as will fit.
341 	 *
342 	 * We start by calculating the smallest number of blocks that we
343 	 * can put into each cylinder group. If this is too big, we reduce
344 	 * the density until it fits.
345 	 */
346 retry:
347 	maxinum = (((int64_t)(1)) << 32) - INOPB(&sblock);
348 	minfragsperinode = 1 + fssize / maxinum;
349 	if (density == 0) {
350 		density = MAX(NFPI, minfragsperinode) * fsize;
351 	} else if (density < minfragsperinode * fsize) {
352 		origdensity = density;
353 		density = minfragsperinode * fsize;
354 		fprintf(stderr, "density increased from %d to %d\n",
355 		    origdensity, density);
356 	}
357 	origdensity = density;
358 	for (;;) {
359 		fragsperinode = MAX(numfrags(&sblock, density), 1);
360 		if (fragsperinode < minfragsperinode) {
361 			bsize <<= 1;
362 			fsize <<= 1;
363 			printf("Block size too small for a file system %s %d\n",
364 			     "of this size. Increasing blocksize to", bsize);
365 			goto restart;
366 		}
367 		minfpg = fragsperinode * INOPB(&sblock);
368 		if (minfpg > sblock.fs_size)
369 			minfpg = sblock.fs_size;
370 		sblock.fs_ipg = INOPB(&sblock);
371 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
372 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
373 		if (sblock.fs_fpg < minfpg)
374 			sblock.fs_fpg = minfpg;
375 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
376 		    INOPB(&sblock));
377 		sblock.fs_fpg = roundup(sblock.fs_iblkno +
378 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
379 		if (sblock.fs_fpg < minfpg)
380 			sblock.fs_fpg = minfpg;
381 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
382 		    INOPB(&sblock));
383 		if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize -
384 		    CGSIZEFUDGE)
385 			break;
386 		density -= sblock.fs_fsize;
387 	}
388 	if (density != origdensity)
389 		printf("density reduced from %d to %d\n", origdensity, density);
390 	/*
391 	 * Start packing more blocks into the cylinder group until
392 	 * it cannot grow any larger, the number of cylinder groups
393 	 * drops below MINCYLGRPS, or we reach the size requested.
394 	 * For UFS1 inodes per cylinder group are stored in an int16_t
395 	 * so fs_ipg is limited to 2^15 - 1.
396 	 */
397 	for ( ; sblock.fs_fpg < maxblkspercg; sblock.fs_fpg += sblock.fs_frag) {
398 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
399 		    INOPB(&sblock));
400 		if (Oflag > 1 || (Oflag == 1 && sblock.fs_ipg <= 0x7fff)) {
401 			if (sblock.fs_size / sblock.fs_fpg < MINCYLGRPS)
402 				break;
403 			if (CGSIZE(&sblock) < (unsigned long)sblock.fs_bsize -
404 			    CGSIZEFUDGE)
405 				continue;
406 			if (CGSIZE(&sblock) == (unsigned long)sblock.fs_bsize -
407 			    CGSIZEFUDGE)
408 				break;
409 		}
410 		sblock.fs_fpg -= sblock.fs_frag;
411 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
412 		    INOPB(&sblock));
413 		break;
414 	}
415 	/*
416 	 * Check to be sure that the last cylinder group has enough blocks
417 	 * to be viable. If it is too small, reduce the number of blocks
418 	 * per cylinder group which will have the effect of moving more
419 	 * blocks into the last cylinder group.
420 	 */
421 	optimalfpg = sblock.fs_fpg;
422 	for (;;) {
423 		sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
424 		lastminfpg = roundup(sblock.fs_iblkno +
425 		    sblock.fs_ipg / INOPF(&sblock), sblock.fs_frag);
426 		if (sblock.fs_size < lastminfpg) {
427 			printf("Filesystem size %jd < minimum size of %d\n",
428 			    (intmax_t)sblock.fs_size, lastminfpg);
429 			exit(28);
430 		}
431 		if (sblock.fs_size % sblock.fs_fpg >= lastminfpg ||
432 		    sblock.fs_size % sblock.fs_fpg == 0)
433 			break;
434 		sblock.fs_fpg -= sblock.fs_frag;
435 		sblock.fs_ipg = roundup(howmany(sblock.fs_fpg, fragsperinode),
436 		    INOPB(&sblock));
437 	}
438 	if (optimalfpg != sblock.fs_fpg)
439 		printf("Reduced frags per cylinder group from %d to %d %s\n",
440 		   optimalfpg, sblock.fs_fpg, "to enlarge last cyl group");
441 	sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
442 	sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
443 	if (Oflag == 1) {
444 		sblock.fs_old_spc = sblock.fs_fpg * sblock.fs_old_nspf;
445 		sblock.fs_old_nsect = sblock.fs_old_spc;
446 		sblock.fs_old_npsect = sblock.fs_old_spc;
447 		sblock.fs_old_ncyl = sblock.fs_ncg;
448 	}
449 	/*
450 	 * fill in remaining fields of the super block
451 	 */
452 	sblock.fs_csaddr = cgdmin(&sblock, 0);
453 	sblock.fs_cssize =
454 	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
455 	fscs = (struct csum *)calloc(1, sblock.fs_cssize);
456 	if (fscs == NULL)
457 		errx(31, "calloc failed");
458 	sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
459 	if (sblock.fs_sbsize > SBLOCKSIZE)
460 		sblock.fs_sbsize = SBLOCKSIZE;
461 	if (sblock.fs_sbsize < realsectorsize)
462 		sblock.fs_sbsize = realsectorsize;
463 	sblock.fs_minfree = minfree;
464 	if (metaspace > 0 && metaspace < sblock.fs_fpg / 2)
465 		sblock.fs_metaspace = blknum(&sblock, metaspace);
466 	else if (metaspace != -1)
467 		/* reserve half of minfree for metadata blocks */
468 		sblock.fs_metaspace = blknum(&sblock,
469 		    (sblock.fs_fpg * minfree) / 200);
470 	if (maxbpg == 0)
471 		sblock.fs_maxbpg = MAXBLKPG(sblock.fs_bsize);
472 	else
473 		sblock.fs_maxbpg = maxbpg;
474 	sblock.fs_optim = opt;
475 	sblock.fs_cgrotor = 0;
476 	sblock.fs_pendingblocks = 0;
477 	sblock.fs_pendinginodes = 0;
478 	sblock.fs_fmod = 0;
479 	sblock.fs_ronly = 0;
480 	sblock.fs_state = 0;
481 	sblock.fs_clean = 1;
482 	sblock.fs_id[0] = (long)utime;
483 	sblock.fs_id[1] = newfs_random();
484 	sblock.fs_fsmnt[0] = '\0';
485 	csfrags = howmany(sblock.fs_cssize, sblock.fs_fsize);
486 	sblock.fs_dsize = sblock.fs_size - sblock.fs_sblkno -
487 	    sblock.fs_ncg * (sblock.fs_dblkno - sblock.fs_sblkno);
488 	sblock.fs_cstotal.cs_nbfree =
489 	    fragstoblks(&sblock, sblock.fs_dsize) -
490 	    howmany(csfrags, sblock.fs_frag);
491 	sblock.fs_cstotal.cs_nffree =
492 	    fragnum(&sblock, sblock.fs_size) +
493 	    (fragnum(&sblock, csfrags) > 0 ?
494 	     sblock.fs_frag - fragnum(&sblock, csfrags) : 0);
495 	sblock.fs_cstotal.cs_nifree =
496 	    sblock.fs_ncg * sblock.fs_ipg - UFS_ROOTINO;
497 	sblock.fs_cstotal.cs_ndir = 0;
498 	sblock.fs_dsize -= csfrags;
499 	sblock.fs_time = utime;
500 	if (Oflag == 1) {
501 		sblock.fs_old_time = utime;
502 		sblock.fs_old_dsize = sblock.fs_dsize;
503 		sblock.fs_old_csaddr = sblock.fs_csaddr;
504 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
505 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
506 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
507 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
508 	}
509 	/*
510 	 * Set flags for metadata that is being check-hashed.
511 	 *
512 	 * Metadata check hashes are not supported in the UFS version 1
513 	 * filesystem to keep it as small and simple as possible.
514 	 */
515 	if (Oflag > 1) {
516 		sblock.fs_flags |= FS_METACKHASH;
517 		if (getosreldate() >= P_OSREL_CK_CYLGRP)
518 			sblock.fs_metackhash |= CK_CYLGRP;
519 		if (getosreldate() >= P_OSREL_CK_SUPERBLOCK)
520 			sblock.fs_metackhash |= CK_SUPERBLOCK;
521 		if (getosreldate() >= P_OSREL_CK_INODE)
522 			sblock.fs_metackhash |= CK_INODE;
523 	}
524 
525 	/*
526 	 * Dump out summary information about file system.
527 	 */
528 #	define B2MBFACTOR (1 / (1024.0 * 1024.0))
529 	printf("%s: %.1fMB (%jd sectors) block size %d, fragment size %d\n",
530 	    fsys, (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
531 	    (intmax_t)fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize,
532 	    sblock.fs_fsize);
533 	printf("\tusing %d cylinder groups of %.2fMB, %d blks, %d inodes.\n",
534 	    sblock.fs_ncg, (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
535 	    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
536 	if (sblock.fs_flags & FS_DOSOFTDEP)
537 		printf("\twith soft updates\n");
538 #	undef B2MBFACTOR
539 
540 	if (Eflag && !Nflag) {
541 		printf("Erasing sectors [%jd...%jd]\n",
542 		    sblock.fs_sblockloc / disk.d_bsize,
543 		    fsbtodb(&sblock, sblock.fs_size) - 1);
544 		berase(&disk, sblock.fs_sblockloc / disk.d_bsize,
545 		    sblock.fs_size * sblock.fs_fsize - sblock.fs_sblockloc);
546 	}
547 	/*
548 	 * Wipe out old UFS1 superblock(s) if necessary.
549 	 */
550 	if (!Nflag && Oflag != 1 && realsectorsize <= SBLOCK_UFS1) {
551 		i = bread(&disk, part_ofs + SBLOCK_UFS1 / disk.d_bsize, chdummy,
552 		    SBLOCKSIZE);
553 		if (i == -1)
554 			err(1, "can't read old UFS1 superblock: %s",
555 			    disk.d_error);
556 
557 		if (fsdummy.fs_magic == FS_UFS1_MAGIC) {
558 			fsdummy.fs_magic = 0;
559 			bwrite(&disk, part_ofs + SBLOCK_UFS1 / disk.d_bsize,
560 			    chdummy, SBLOCKSIZE);
561 			for (cg = 0; cg < fsdummy.fs_ncg; cg++) {
562 				if (fsbtodb(&fsdummy, cgsblock(&fsdummy, cg)) >
563 				    fssize)
564 					break;
565 				bwrite(&disk, part_ofs + fsbtodb(&fsdummy,
566 				  cgsblock(&fsdummy, cg)), chdummy, SBLOCKSIZE);
567 			}
568 		}
569 	}
570 	/*
571 	 * Reference the summary information so it will also be written.
572 	 */
573 	sblock.fs_csp = fscs;
574 	if (!Nflag && sbwrite(&disk, 0) != 0)
575 		err(1, "sbwrite: %s", disk.d_error);
576 	if (Xflag == 1) {
577 		printf("** Exiting on Xflag 1\n");
578 		exit(0);
579 	}
580 	if (Xflag == 2)
581 		printf("** Leaving BAD MAGIC on Xflag 2\n");
582 	else
583 		sblock.fs_magic = (Oflag != 1) ? FS_UFS2_MAGIC : FS_UFS1_MAGIC;
584 
585 	/*
586 	 * Now build the cylinders group blocks and
587 	 * then print out indices of cylinder groups.
588 	 */
589 	printf("super-block backups (for fsck_ffs -b #) at:\n");
590 	i = 0;
591 	width = charsperline();
592 	/*
593 	 * Allocate space for two sets of inode blocks.
594 	 */
595 	iobufsize = 2 * sblock.fs_bsize;
596 	if ((iobuf = calloc(1, iobufsize)) == 0) {
597 		printf("Cannot allocate I/O buffer\n");
598 		exit(38);
599 	}
600 	/*
601 	 * Write out all the cylinder groups and backup superblocks.
602 	 */
603 	for (cg = 0; cg < sblock.fs_ncg; cg++) {
604 		if (!Nflag)
605 			initcg(cg, utime);
606 		j = snprintf(tmpbuf, sizeof(tmpbuf), " %jd%s",
607 		    (intmax_t)fsbtodb(&sblock, cgsblock(&sblock, cg)),
608 		    cg < (sblock.fs_ncg-1) ? "," : "");
609 		if (j < 0)
610 			tmpbuf[j = 0] = '\0';
611 		if (i + j >= width) {
612 			printf("\n");
613 			i = 0;
614 		}
615 		i += j;
616 		printf("%s", tmpbuf);
617 		fflush(stdout);
618 	}
619 	printf("\n");
620 	if (Nflag)
621 		exit(0);
622 	/*
623 	 * Now construct the initial file system,
624 	 * then write out the super-block.
625 	 */
626 	fsinit(utime);
627 	if (Oflag == 1) {
628 		sblock.fs_old_cstotal.cs_ndir = sblock.fs_cstotal.cs_ndir;
629 		sblock.fs_old_cstotal.cs_nbfree = sblock.fs_cstotal.cs_nbfree;
630 		sblock.fs_old_cstotal.cs_nifree = sblock.fs_cstotal.cs_nifree;
631 		sblock.fs_old_cstotal.cs_nffree = sblock.fs_cstotal.cs_nffree;
632 	}
633 	if (Xflag == 3) {
634 		printf("** Exiting on Xflag 3\n");
635 		exit(0);
636 	}
637 	if (sbwrite(&disk, 0) != 0)
638 		err(1, "sbwrite: %s", disk.d_error);
639 	/*
640 	 * For UFS1 filesystems with a blocksize of 64K, the first
641 	 * alternate superblock resides at the location used for
642 	 * the default UFS2 superblock. As there is a valid
643 	 * superblock at this location, the boot code will use
644 	 * it as its first choice. Thus we have to ensure that
645 	 * all of its statistcs on usage are correct.
646 	 */
647 	if (Oflag == 1 && sblock.fs_bsize == 65536)
648 		wtfs(fsbtodb(&sblock, cgsblock(&sblock, 0)),
649 		    sblock.fs_bsize, (char *)&sblock);
650 	/*
651 	 * Read the last sector of the boot block, replace the last
652 	 * 20 bytes with the recovery information, then write it back.
653 	 * The recovery information only works for UFS2 filesystems.
654 	 * For UFS1, zero out the area to ensure that an old UFS2
655 	 * recovery block is not accidentally found.
656 	 */
657 	if ((fsrbuf = malloc(realsectorsize)) == NULL || bread(&disk,
658 	    part_ofs + (SBLOCK_UFS2 - realsectorsize) / disk.d_bsize,
659 	    fsrbuf, realsectorsize) == -1)
660 		err(1, "can't read recovery area: %s", disk.d_error);
661 	fsr = (struct fsrecovery *)&fsrbuf[realsectorsize - sizeof *fsr];
662 	if (sblock.fs_magic != FS_UFS2_MAGIC) {
663 		memset(fsr, 0, sizeof *fsr);
664 	} else {
665 		fsr->fsr_magic = sblock.fs_magic;
666 		fsr->fsr_fpg = sblock.fs_fpg;
667 		fsr->fsr_fsbtodb = sblock.fs_fsbtodb;
668 		fsr->fsr_sblkno = sblock.fs_sblkno;
669 		fsr->fsr_ncg = sblock.fs_ncg;
670 	}
671 	wtfs((SBLOCK_UFS2 - realsectorsize) / disk.d_bsize,
672 	    realsectorsize, fsrbuf);
673 	free(fsrbuf);
674 	/*
675 	 * Update information about this partition in pack
676 	 * label, to that it may be updated on disk.
677 	 */
678 	if (pp != NULL) {
679 		pp->p_fstype = FS_BSDFFS;
680 		pp->p_fsize = sblock.fs_fsize;
681 		pp->p_frag = sblock.fs_frag;
682 		pp->p_cpg = sblock.fs_fpg;
683 	}
684 	/*
685 	 * This should NOT happen. If it does complain loudly and
686 	 * take evasive action.
687 	 */
688 	if ((int32_t)CGSIZE(&sblock) > sblock.fs_bsize) {
689 		printf("INTERNAL ERROR: ipg %d, fpg %d, contigsumsize %d, ",
690 		    sblock.fs_ipg, sblock.fs_fpg, sblock.fs_contigsumsize);
691 		printf("old_cpg %d, size_cg %zu, CGSIZE %zu\n",
692 		    sblock.fs_old_cpg, sizeof(struct cg), CGSIZE(&sblock));
693 		printf("Please file a FreeBSD bug report and include this "
694 		    "output\n");
695 		maxblkspercg = fragstoblks(&sblock, sblock.fs_fpg) - 1;
696 		density = 0;
697 		goto retry;
698 	}
699 }
700 
701 /*
702  * Initialize a cylinder group.
703  */
704 void
initcg(int cylno,time_t utime)705 initcg(int cylno, time_t utime)
706 {
707 	long blkno, start;
708 	off_t savedactualloc;
709 	uint i, j, d, dlower, dupper;
710 	ufs2_daddr_t cbase, dmax;
711 	struct ufs1_dinode *dp1;
712 	struct ufs2_dinode *dp2;
713 	struct csum *cs;
714 
715 	/*
716 	 * Determine block bounds for cylinder group.
717 	 * Allow space for super block summary information in first
718 	 * cylinder group.
719 	 */
720 	cbase = cgbase(&sblock, cylno);
721 	dmax = cbase + sblock.fs_fpg;
722 	if (dmax > sblock.fs_size)
723 		dmax = sblock.fs_size;
724 	dlower = cgsblock(&sblock, cylno) - cbase;
725 	dupper = cgdmin(&sblock, cylno) - cbase;
726 	if (cylno == 0)
727 		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
728 	cs = &fscs[cylno];
729 	memset(&acg, 0, sblock.fs_cgsize);
730 	acg.cg_time = utime;
731 	acg.cg_magic = CG_MAGIC;
732 	acg.cg_cgx = cylno;
733 	acg.cg_niblk = sblock.fs_ipg;
734 	acg.cg_initediblk = MIN(sblock.fs_ipg, 2 * INOPB(&sblock));
735 	acg.cg_ndblk = dmax - cbase;
736 	if (sblock.fs_contigsumsize > 0)
737 		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
738 	start = sizeof(acg);
739 	if (Oflag == 2) {
740 		acg.cg_iusedoff = start;
741 	} else {
742 		acg.cg_old_ncyl = sblock.fs_old_cpg;
743 		acg.cg_old_time = acg.cg_time;
744 		acg.cg_time = 0;
745 		acg.cg_old_niblk = acg.cg_niblk;
746 		acg.cg_niblk = 0;
747 		acg.cg_initediblk = 0;
748 		acg.cg_old_btotoff = start;
749 		acg.cg_old_boff = acg.cg_old_btotoff +
750 		    sblock.fs_old_cpg * sizeof(int32_t);
751 		acg.cg_iusedoff = acg.cg_old_boff +
752 		    sblock.fs_old_cpg * sizeof(u_int16_t);
753 	}
754 	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
755 	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
756 	if (sblock.fs_contigsumsize > 0) {
757 		acg.cg_clustersumoff =
758 		    roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
759 		acg.cg_clustersumoff -= sizeof(u_int32_t);
760 		acg.cg_clusteroff = acg.cg_clustersumoff +
761 		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
762 		acg.cg_nextfreeoff = acg.cg_clusteroff +
763 		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
764 	}
765 	if (acg.cg_nextfreeoff > (unsigned)sblock.fs_cgsize) {
766 		printf("Panic: cylinder group too big by %d bytes\n",
767 		    acg.cg_nextfreeoff - (unsigned)sblock.fs_cgsize);
768 		exit(37);
769 	}
770 	acg.cg_cs.cs_nifree += sblock.fs_ipg;
771 	if (cylno == 0)
772 		for (i = 0; i < (long)UFS_ROOTINO; i++) {
773 			setbit(cg_inosused(&acg), i);
774 			acg.cg_cs.cs_nifree--;
775 		}
776 	if (cylno > 0) {
777 		/*
778 		 * In cylno 0, beginning space is reserved
779 		 * for boot and super blocks.
780 		 */
781 		for (d = 0; d < dlower; d += sblock.fs_frag) {
782 			blkno = d / sblock.fs_frag;
783 			setblock(&sblock, cg_blksfree(&acg), blkno);
784 			if (sblock.fs_contigsumsize > 0)
785 				setbit(cg_clustersfree(&acg), blkno);
786 			acg.cg_cs.cs_nbfree++;
787 		}
788 	}
789 	if ((i = dupper % sblock.fs_frag)) {
790 		acg.cg_frsum[sblock.fs_frag - i]++;
791 		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
792 			setbit(cg_blksfree(&acg), dupper);
793 			acg.cg_cs.cs_nffree++;
794 		}
795 	}
796 	for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
797 	     d += sblock.fs_frag) {
798 		blkno = d / sblock.fs_frag;
799 		setblock(&sblock, cg_blksfree(&acg), blkno);
800 		if (sblock.fs_contigsumsize > 0)
801 			setbit(cg_clustersfree(&acg), blkno);
802 		acg.cg_cs.cs_nbfree++;
803 	}
804 	if (d < acg.cg_ndblk) {
805 		acg.cg_frsum[acg.cg_ndblk - d]++;
806 		for (; d < acg.cg_ndblk; d++) {
807 			setbit(cg_blksfree(&acg), d);
808 			acg.cg_cs.cs_nffree++;
809 		}
810 	}
811 	if (sblock.fs_contigsumsize > 0) {
812 		int32_t *sump = cg_clustersum(&acg);
813 		u_char *mapp = cg_clustersfree(&acg);
814 		int map = *mapp++;
815 		int bit = 1;
816 		int run = 0;
817 
818 		for (i = 0; i < acg.cg_nclusterblks; i++) {
819 			if ((map & bit) != 0)
820 				run++;
821 			else if (run != 0) {
822 				if (run > sblock.fs_contigsumsize)
823 					run = sblock.fs_contigsumsize;
824 				sump[run]++;
825 				run = 0;
826 			}
827 			if ((i & (CHAR_BIT - 1)) != CHAR_BIT - 1)
828 				bit <<= 1;
829 			else {
830 				map = *mapp++;
831 				bit = 1;
832 			}
833 		}
834 		if (run != 0) {
835 			if (run > sblock.fs_contigsumsize)
836 				run = sblock.fs_contigsumsize;
837 			sump[run]++;
838 		}
839 	}
840 	*cs = acg.cg_cs;
841 	/*
842 	 * Write out the duplicate super block. Then write the cylinder
843 	 * group map and two blocks worth of inodes in a single write.
844 	 */
845 	savedactualloc = sblock.fs_sblockactualloc;
846 	sblock.fs_sblockactualloc =
847 	    dbtob(fsbtodb(&sblock, cgsblock(&sblock, cylno)));
848 	if (sbwrite(&disk, 0) != 0)
849 		err(1, "sbwrite: %s", disk.d_error);
850 	sblock.fs_sblockactualloc = savedactualloc;
851 	if (cgwrite(&disk) != 0)
852 		err(1, "initcg: cgwrite: %s", disk.d_error);
853 	start = 0;
854 	dp1 = (struct ufs1_dinode *)(&iobuf[start]);
855 	dp2 = (struct ufs2_dinode *)(&iobuf[start]);
856 	for (i = 0; i < acg.cg_initediblk; i++) {
857 		if (sblock.fs_magic == FS_UFS1_MAGIC) {
858 			dp1->di_gen = newfs_random();
859 			dp1++;
860 		} else {
861 			dp2->di_gen = newfs_random();
862 			dp2++;
863 		}
864 	}
865 	wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno)), iobufsize, iobuf);
866 	/*
867 	 * For the old file system, we have to initialize all the inodes.
868 	 */
869 	if (Oflag == 1) {
870 		for (i = 2 * sblock.fs_frag;
871 		     i < sblock.fs_ipg / INOPF(&sblock);
872 		     i += sblock.fs_frag) {
873 			dp1 = (struct ufs1_dinode *)(&iobuf[start]);
874 			for (j = 0; j < INOPB(&sblock); j++) {
875 				dp1->di_gen = newfs_random();
876 				dp1++;
877 			}
878 			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
879 			    sblock.fs_bsize, &iobuf[start]);
880 		}
881 	}
882 }
883 
884 /*
885  * initialize the file system
886  */
887 #define ROOTLINKCNT 3
888 
889 static struct direct root_dir[] = {
890 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
891 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
892 	{ UFS_ROOTINO + 1, sizeof(struct direct), DT_DIR, 5, ".snap" },
893 };
894 
895 #define SNAPLINKCNT 2
896 
897 static struct direct snap_dir[] = {
898 	{ UFS_ROOTINO + 1, sizeof(struct direct), DT_DIR, 1, "." },
899 	{ UFS_ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
900 };
901 
902 void
fsinit(time_t utime)903 fsinit(time_t utime)
904 {
905 	union dinode node;
906 	struct group *grp;
907 	gid_t gid;
908 	int entries;
909 
910 	memset(&node, 0, sizeof node);
911 	if ((grp = getgrnam("operator")) != NULL) {
912 		gid = grp->gr_gid;
913 	} else {
914 		warnx("Cannot retrieve operator gid, using gid 0.");
915 		gid = 0;
916 	}
917 	entries = (nflag) ? ROOTLINKCNT - 1: ROOTLINKCNT;
918 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
919 		/*
920 		 * initialize the node
921 		 */
922 		node.dp1.di_atime = utime;
923 		node.dp1.di_mtime = utime;
924 		node.dp1.di_ctime = utime;
925 		/*
926 		 * create the root directory
927 		 */
928 		node.dp1.di_mode = IFDIR | UMASK;
929 		node.dp1.di_nlink = entries;
930 		node.dp1.di_size = makedir(root_dir, entries);
931 		node.dp1.di_db[0] = alloc(sblock.fs_fsize, node.dp1.di_mode);
932 		node.dp1.di_blocks =
933 		    btodb(fragroundup(&sblock, node.dp1.di_size));
934 		wtfs(fsbtodb(&sblock, node.dp1.di_db[0]), sblock.fs_fsize,
935 		    iobuf);
936 		iput(&node, UFS_ROOTINO);
937 		if (!nflag) {
938 			/*
939 			 * create the .snap directory
940 			 */
941 			node.dp1.di_mode |= 020;
942 			node.dp1.di_gid = gid;
943 			node.dp1.di_nlink = SNAPLINKCNT;
944 			node.dp1.di_size = makedir(snap_dir, SNAPLINKCNT);
945 				node.dp1.di_db[0] =
946 				    alloc(sblock.fs_fsize, node.dp1.di_mode);
947 			node.dp1.di_blocks =
948 			    btodb(fragroundup(&sblock, node.dp1.di_size));
949 			node.dp1.di_dirdepth = 1;
950 			wtfs(fsbtodb(&sblock, node.dp1.di_db[0]),
951 			    sblock.fs_fsize, iobuf);
952 			iput(&node, UFS_ROOTINO + 1);
953 		}
954 	} else {
955 		/*
956 		 * initialize the node
957 		 */
958 		node.dp2.di_atime = utime;
959 		node.dp2.di_mtime = utime;
960 		node.dp2.di_ctime = utime;
961 		node.dp2.di_birthtime = utime;
962 		/*
963 		 * create the root directory
964 		 */
965 		node.dp2.di_mode = IFDIR | UMASK;
966 		node.dp2.di_nlink = entries;
967 		node.dp2.di_size = makedir(root_dir, entries);
968 		node.dp2.di_db[0] = alloc(sblock.fs_fsize, node.dp2.di_mode);
969 		node.dp2.di_blocks =
970 		    btodb(fragroundup(&sblock, node.dp2.di_size));
971 		wtfs(fsbtodb(&sblock, node.dp2.di_db[0]), sblock.fs_fsize,
972 		    iobuf);
973 		iput(&node, UFS_ROOTINO);
974 		if (!nflag) {
975 			/*
976 			 * create the .snap directory
977 			 */
978 			node.dp2.di_mode |= 020;
979 			node.dp2.di_gid = gid;
980 			node.dp2.di_nlink = SNAPLINKCNT;
981 			node.dp2.di_size = makedir(snap_dir, SNAPLINKCNT);
982 				node.dp2.di_db[0] =
983 				    alloc(sblock.fs_fsize, node.dp2.di_mode);
984 			node.dp2.di_blocks =
985 			    btodb(fragroundup(&sblock, node.dp2.di_size));
986 			node.dp2.di_dirdepth = 1;
987 			wtfs(fsbtodb(&sblock, node.dp2.di_db[0]),
988 			    sblock.fs_fsize, iobuf);
989 			iput(&node, UFS_ROOTINO + 1);
990 		}
991 	}
992 }
993 
994 /*
995  * construct a set of directory entries in "iobuf".
996  * return size of directory.
997  */
998 int
makedir(struct direct * protodir,int entries)999 makedir(struct direct *protodir, int entries)
1000 {
1001 	char *cp;
1002 	int i, spcleft;
1003 
1004 	spcleft = DIRBLKSIZ;
1005 	memset(iobuf, 0, DIRBLKSIZ);
1006 	for (cp = iobuf, i = 0; i < entries - 1; i++) {
1007 		protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
1008 		memmove(cp, &protodir[i], protodir[i].d_reclen);
1009 		cp += protodir[i].d_reclen;
1010 		spcleft -= protodir[i].d_reclen;
1011 	}
1012 	protodir[i].d_reclen = spcleft;
1013 	memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
1014 	return (DIRBLKSIZ);
1015 }
1016 
1017 /*
1018  * allocate a block or frag
1019  */
1020 ufs2_daddr_t
alloc(int size,int mode)1021 alloc(int size, int mode)
1022 {
1023 	int i, blkno, frag;
1024 	uint d;
1025 
1026 	bread(&disk, part_ofs + fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
1027 	    sblock.fs_cgsize);
1028 	if (acg.cg_magic != CG_MAGIC) {
1029 		printf("cg 0: bad magic number\n");
1030 		exit(38);
1031 	}
1032 	if (acg.cg_cs.cs_nbfree == 0) {
1033 		printf("first cylinder group ran out of space\n");
1034 		exit(39);
1035 	}
1036 	for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
1037 		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
1038 			goto goth;
1039 	printf("internal error: can't find block in cyl 0\n");
1040 	exit(40);
1041 goth:
1042 	blkno = fragstoblks(&sblock, d);
1043 	clrblock(&sblock, cg_blksfree(&acg), blkno);
1044 	if (sblock.fs_contigsumsize > 0)
1045 		clrbit(cg_clustersfree(&acg), blkno);
1046 	acg.cg_cs.cs_nbfree--;
1047 	sblock.fs_cstotal.cs_nbfree--;
1048 	fscs[0].cs_nbfree--;
1049 	if (mode & IFDIR) {
1050 		acg.cg_cs.cs_ndir++;
1051 		sblock.fs_cstotal.cs_ndir++;
1052 		fscs[0].cs_ndir++;
1053 	}
1054 	if (size != sblock.fs_bsize) {
1055 		frag = howmany(size, sblock.fs_fsize);
1056 		fscs[0].cs_nffree += sblock.fs_frag - frag;
1057 		sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
1058 		acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
1059 		acg.cg_frsum[sblock.fs_frag - frag]++;
1060 		for (i = frag; i < sblock.fs_frag; i++)
1061 			setbit(cg_blksfree(&acg), d + i);
1062 	}
1063 	if (cgwrite(&disk) != 0)
1064 		err(1, "alloc: cgwrite: %s", disk.d_error);
1065 	return ((ufs2_daddr_t)d);
1066 }
1067 
1068 /*
1069  * Allocate an inode on the disk
1070  */
1071 void
iput(union dinode * ip,ino_t ino)1072 iput(union dinode *ip, ino_t ino)
1073 {
1074 	union dinodep dp;
1075 
1076 	bread(&disk, part_ofs + fsbtodb(&sblock, cgtod(&sblock, 0)), (char *)&acg,
1077 	    sblock.fs_cgsize);
1078 	if (acg.cg_magic != CG_MAGIC) {
1079 		printf("cg 0: bad magic number\n");
1080 		exit(31);
1081 	}
1082 	acg.cg_cs.cs_nifree--;
1083 	setbit(cg_inosused(&acg), ino);
1084 	if (cgwrite(&disk) != 0)
1085 		err(1, "iput: cgwrite: %s", disk.d_error);
1086 	sblock.fs_cstotal.cs_nifree--;
1087 	fscs[0].cs_nifree--;
1088 	if (getinode(&disk, &dp, ino) == -1) {
1089 		printf("iput: %s\n", disk.d_error);
1090 		exit(32);
1091 	}
1092 	if (sblock.fs_magic == FS_UFS1_MAGIC)
1093 		*dp.dp1 = ip->dp1;
1094 	else
1095 		*dp.dp2 = ip->dp2;
1096 	putinode(&disk);
1097 }
1098 
1099 /*
1100  * possibly write to disk
1101  */
1102 static void
wtfs(ufs2_daddr_t bno,int size,char * bf)1103 wtfs(ufs2_daddr_t bno, int size, char *bf)
1104 {
1105 	if (Nflag)
1106 		return;
1107 	if (bwrite(&disk, part_ofs + bno, bf, size) < 0)
1108 		err(36, "wtfs: %d bytes at sector %jd", size, (intmax_t)bno);
1109 }
1110 
1111 /*
1112  * check if a block is available
1113  */
1114 static int
isblock(struct fs * fs,unsigned char * cp,int h)1115 isblock(struct fs *fs, unsigned char *cp, int h)
1116 {
1117 	unsigned char mask;
1118 
1119 	switch (fs->fs_frag) {
1120 	case 8:
1121 		return (cp[h] == 0xff);
1122 	case 4:
1123 		mask = 0x0f << ((h & 0x1) << 2);
1124 		return ((cp[h >> 1] & mask) == mask);
1125 	case 2:
1126 		mask = 0x03 << ((h & 0x3) << 1);
1127 		return ((cp[h >> 2] & mask) == mask);
1128 	case 1:
1129 		mask = 0x01 << (h & 0x7);
1130 		return ((cp[h >> 3] & mask) == mask);
1131 	default:
1132 		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
1133 		return (0);
1134 	}
1135 }
1136 
1137 /*
1138  * take a block out of the map
1139  */
1140 static void
clrblock(struct fs * fs,unsigned char * cp,int h)1141 clrblock(struct fs *fs, unsigned char *cp, int h)
1142 {
1143 	switch ((fs)->fs_frag) {
1144 	case 8:
1145 		cp[h] = 0;
1146 		return;
1147 	case 4:
1148 		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1149 		return;
1150 	case 2:
1151 		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1152 		return;
1153 	case 1:
1154 		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1155 		return;
1156 	default:
1157 		fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
1158 		return;
1159 	}
1160 }
1161 
1162 /*
1163  * put a block into the map
1164  */
1165 static void
setblock(struct fs * fs,unsigned char * cp,int h)1166 setblock(struct fs *fs, unsigned char *cp, int h)
1167 {
1168 	switch (fs->fs_frag) {
1169 	case 8:
1170 		cp[h] = 0xff;
1171 		return;
1172 	case 4:
1173 		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1174 		return;
1175 	case 2:
1176 		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1177 		return;
1178 	case 1:
1179 		cp[h >> 3] |= (0x01 << (h & 0x7));
1180 		return;
1181 	default:
1182 		fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
1183 		return;
1184 	}
1185 }
1186 
1187 /*
1188  * Determine the number of characters in a
1189  * single line.
1190  */
1191 
1192 static int
charsperline(void)1193 charsperline(void)
1194 {
1195 	int columns;
1196 	char *cp;
1197 	struct winsize ws;
1198 
1199 	columns = 0;
1200 	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1201 		columns = ws.ws_col;
1202 	if (columns == 0 && (cp = getenv("COLUMNS")))
1203 		columns = atoi(cp);
1204 	if (columns == 0)
1205 		columns = 80;	/* last resort */
1206 	return (columns);
1207 }
1208 
1209 static int
ilog2(int val)1210 ilog2(int val)
1211 {
1212 	u_int n;
1213 
1214 	for (n = 0; n < sizeof(n) * CHAR_BIT; n++)
1215 		if (1 << n == val)
1216 			return (n);
1217 	errx(1, "ilog2: %d is not a power of 2\n", val);
1218 }
1219 
1220 /*
1221  * For the regression test, return predictable random values.
1222  * Otherwise use a true random number generator.
1223  */
1224 static u_int32_t
newfs_random(void)1225 newfs_random(void)
1226 {
1227 	static u_int32_t nextnum = 1;
1228 
1229 	if (Rflag)
1230 		return (nextnum++);
1231 	return (arc4random());
1232 }
1233