xref: /netbsd-src/usr.sbin/makefs/ffs.c (revision a536ee5124e62c9a0051a252f7833dc8f50f44c9)
1 /*	$NetBSD: ffs.c,v 1.48 2012/06/22 06:15:18 sjg Exp $	*/
2 
3 /*
4  * Copyright (c) 2001 Wasabi Systems, Inc.
5  * All rights reserved.
6  *
7  * Written by Luke Mewburn for Wasabi Systems, Inc.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed for the NetBSD Project by
20  *      Wasabi Systems, Inc.
21  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
22  *    or promote products derived from this software without specific prior
23  *    written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37 /*
38  * Copyright (c) 1982, 1986, 1989, 1993
39  *	The Regents of the University of California.  All rights reserved.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *	@(#)ffs_alloc.c	8.19 (Berkeley) 7/13/95
66  */
67 
68 #if HAVE_NBTOOL_CONFIG_H
69 #include "nbtool_config.h"
70 #endif
71 
72 #include <sys/cdefs.h>
73 #if defined(__RCSID) && !defined(__lint)
74 __RCSID("$NetBSD: ffs.c,v 1.48 2012/06/22 06:15:18 sjg Exp $");
75 #endif	/* !__lint */
76 
77 #include <sys/param.h>
78 
79 #if !HAVE_NBTOOL_CONFIG_H
80 #include <sys/mount.h>
81 #endif
82 
83 #include <assert.h>
84 #include <errno.h>
85 #include <fcntl.h>
86 #include <stdarg.h>
87 #include <stdio.h>
88 #include <stdlib.h>
89 #include <string.h>
90 #include <unistd.h>
91 
92 #include "makefs.h"
93 #include "ffs.h"
94 
95 #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS
96 #include <sys/statvfs.h>
97 #endif
98 
99 #include <ufs/ufs/dinode.h>
100 #include <ufs/ufs/dir.h>
101 #include <ufs/ffs/fs.h>
102 #include <ufs/ufs/ufs_bswap.h>
103 
104 #include "ffs/ufs_inode.h"
105 #include "ffs/newfs_extern.h"
106 #include "ffs/ffs_extern.h"
107 
108 #undef DIP
109 #define DIP(dp, field) \
110 	((ffs_opts->version == 1) ? \
111 	(dp)->ffs1_din.di_##field : (dp)->ffs2_din.di_##field)
112 
113 /*
114  * Various file system defaults (cribbed from newfs(8)).
115  */
116 #define	DFL_FRAGSIZE		1024		/* fragment size */
117 #define	DFL_BLKSIZE		8192		/* block size */
118 #define	DFL_SECSIZE		512		/* sector size */
119 #define	DFL_CYLSPERGROUP	65536		/* cylinders per group */
120 #define	DFL_FRAGSPERINODE	4		/* fragments per inode */
121 #define	DFL_ROTDELAY		0		/* rotational delay */
122 #define	DFL_NRPOS		1		/* rotational positions */
123 #define	DFL_RPM			3600		/* rpm of disk */
124 #define	DFL_NSECTORS		64		/* # of sectors */
125 #define	DFL_NTRACKS		16		/* # of tracks */
126 
127 
128 typedef struct {
129 	u_char		*buf;		/* buf for directory */
130 	doff_t		size;		/* full size of buf */
131 	doff_t		cur;		/* offset of current entry */
132 } dirbuf_t;
133 
134 
135 static	int	ffs_create_image(const char *, fsinfo_t *);
136 static	void	ffs_dump_fsinfo(fsinfo_t *);
137 static	void	ffs_dump_dirbuf(dirbuf_t *, const char *, int);
138 static	void	ffs_make_dirbuf(dirbuf_t *, const char *, fsnode *, int);
139 static	int	ffs_populate_dir(const char *, fsnode *, fsinfo_t *);
140 static	void	ffs_size_dir(fsnode *, fsinfo_t *);
141 static	void	ffs_validate(const char *, fsnode *, fsinfo_t *);
142 static	void	ffs_write_file(union dinode *, uint32_t, void *, fsinfo_t *);
143 static	void	ffs_write_inode(union dinode *, uint32_t, const fsinfo_t *);
144 static  void	*ffs_build_dinode1(struct ufs1_dinode *, dirbuf_t *, fsnode *,
145 				 fsnode *, fsinfo_t *);
146 static  void	*ffs_build_dinode2(struct ufs2_dinode *, dirbuf_t *, fsnode *,
147 				 fsnode *, fsinfo_t *);
148 
149 
150 
151 int	sectorsize;		/* XXX: for buf.c::getblk() */
152 
153 	/* publically visible functions */
154 
155 void
156 ffs_prep_opts(fsinfo_t *fsopts)
157 {
158 	ffs_opt_t *ffs_opts;
159 
160 	if ((ffs_opts = calloc(1, sizeof(ffs_opt_t))) == NULL)
161 		err(1, "Allocating memory for ffs_options");
162 
163 	fsopts->fs_specific = ffs_opts;
164 
165 	ffs_opts->bsize= -1;
166 	ffs_opts->fsize= -1;
167 	ffs_opts->cpg= -1;
168 	ffs_opts->density= -1;
169 	ffs_opts->minfree= -1;
170 	ffs_opts->optimization= -1;
171 	ffs_opts->maxcontig= -1;
172 	ffs_opts->maxbpg= -1;
173 	ffs_opts->avgfilesize= -1;
174 	ffs_opts->avgfpdir= -1;
175 	ffs_opts->version = 1;
176 }
177 
178 void
179 ffs_cleanup_opts(fsinfo_t *fsopts)
180 {
181 	if (fsopts->fs_specific)
182 		free(fsopts->fs_specific);
183 }
184 
185 int
186 ffs_parse_opts(const char *option, fsinfo_t *fsopts)
187 {
188 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
189 
190 	option_t ffs_options[] = {
191 		{ "bsize",	&ffs_opts->bsize,	1,	INT_MAX,
192 					"block size" },
193 		{ "fsize",	&ffs_opts->fsize,	1,	INT_MAX,
194 					"fragment size" },
195 		{ "density",	&ffs_opts->density,	1,	INT_MAX,
196 					"bytes per inode" },
197 		{ "minfree",	&ffs_opts->minfree,	0,	99,
198 					"minfree" },
199 		{ "maxbpf",	&ffs_opts->maxbpg,	1,	INT_MAX,
200 					"max blocks per file in a cg" },
201 		{ "avgfilesize", &ffs_opts->avgfilesize,1,	INT_MAX,
202 					"expected average file size" },
203 		{ "avgfpdir",	&ffs_opts->avgfpdir,	1,	INT_MAX,
204 					"expected # of files per directory" },
205 		{ "extent",	&ffs_opts->maxbsize,	1,	INT_MAX,
206 					"maximum # extent size" },
207 		{ "maxbpcg",	&ffs_opts->maxblkspercg,1,	INT_MAX,
208 					"max # of blocks per group" },
209 		{ "version",	&ffs_opts->version,	1,	2,
210 					"UFS version" },
211 		{ .name = NULL }
212 	};
213 
214 	char	*var, *val;
215 	int	rv;
216 
217 	assert(option != NULL);
218 	assert(fsopts != NULL);
219 	assert(ffs_opts != NULL);
220 
221 	if (debug & DEBUG_FS_PARSE_OPTS)
222 		printf("ffs_parse_opts: got `%s'\n", option);
223 
224 	if ((var = strdup(option)) == NULL)
225 		err(1, "Allocating memory for copy of option string");
226 	rv = 0;
227 
228 	if ((val = strchr(var, '=')) == NULL) {
229 		warnx("Option `%s' doesn't contain a value", var);
230 		goto leave_ffs_parse_opts;
231 	}
232 	*val++ = '\0';
233 
234 	if (strcmp(var, "optimization") == 0) {
235 		if (strcmp(val, "time") == 0) {
236 			ffs_opts->optimization = FS_OPTTIME;
237 		} else if (strcmp(val, "space") == 0) {
238 			ffs_opts->optimization = FS_OPTSPACE;
239 		} else {
240 			warnx("Invalid optimization `%s'", val);
241 			goto leave_ffs_parse_opts;
242 		}
243 		rv = 1;
244 	} else if (strcmp(var, "label") == 0) {
245 		strlcpy(ffs_opts->label, val, sizeof(ffs_opts->label));
246 		rv = 1;
247 	} else
248 		rv = set_option(ffs_options, var, val);
249 
250  leave_ffs_parse_opts:
251 	if (var)
252 		free(var);
253 	return (rv);
254 }
255 
256 
257 void
258 ffs_makefs(const char *image, const char *dir, fsnode *root, fsinfo_t *fsopts)
259 {
260 	struct fs	*superblock;
261 	struct timeval	start;
262 
263 	assert(image != NULL);
264 	assert(dir != NULL);
265 	assert(root != NULL);
266 	assert(fsopts != NULL);
267 
268 	if (debug & DEBUG_FS_MAKEFS)
269 		printf("ffs_makefs: image %s directory %s root %p\n",
270 		    image, dir, root);
271 
272 		/* validate tree and options */
273 	TIMER_START(start);
274 	ffs_validate(dir, root, fsopts);
275 	TIMER_RESULTS(start, "ffs_validate");
276 
277 	printf("Calculated size of `%s': %lld bytes, %lld inodes\n",
278 	    image, (long long)fsopts->size, (long long)fsopts->inodes);
279 
280 		/* create image */
281 	TIMER_START(start);
282 	if (ffs_create_image(image, fsopts) == -1)
283 		errx(1, "Image file `%s' not created.", image);
284 	TIMER_RESULTS(start, "ffs_create_image");
285 
286 	fsopts->curinode = ROOTINO;
287 
288 	if (debug & DEBUG_FS_MAKEFS)
289 		putchar('\n');
290 
291 		/* populate image */
292 	printf("Populating `%s'\n", image);
293 	TIMER_START(start);
294 	if (! ffs_populate_dir(dir, root, fsopts))
295 		errx(1, "Image file `%s' not populated.", image);
296 	TIMER_RESULTS(start, "ffs_populate_dir");
297 
298 		/* ensure no outstanding buffers remain */
299 	if (debug & DEBUG_FS_MAKEFS)
300 		bcleanup();
301 
302 		/* update various superblock parameters */
303 	superblock = fsopts->superblock;
304 	superblock->fs_fmod = 0;
305 	superblock->fs_old_cstotal.cs_ndir   = superblock->fs_cstotal.cs_ndir;
306 	superblock->fs_old_cstotal.cs_nbfree = superblock->fs_cstotal.cs_nbfree;
307 	superblock->fs_old_cstotal.cs_nifree = superblock->fs_cstotal.cs_nifree;
308 	superblock->fs_old_cstotal.cs_nffree = superblock->fs_cstotal.cs_nffree;
309 
310 		/* write out superblock; image is now complete */
311 	ffs_write_superblock(fsopts->superblock, fsopts);
312 	if (close(fsopts->fd) == -1)
313 		err(1, "Closing `%s'", image);
314 	fsopts->fd = -1;
315 	printf("Image `%s' complete\n", image);
316 }
317 
318 	/* end of public functions */
319 
320 
321 static void
322 ffs_validate(const char *dir, fsnode *root, fsinfo_t *fsopts)
323 {
324 	int32_t	ncg = 1;
325 #if notyet
326 	int32_t	spc, nspf, ncyl, fssize;
327 #endif
328 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
329 
330 	assert(dir != NULL);
331 	assert(root != NULL);
332 	assert(fsopts != NULL);
333 	assert(ffs_opts != NULL);
334 
335 	if (debug & DEBUG_FS_VALIDATE) {
336 		printf("ffs_validate: before defaults set:\n");
337 		ffs_dump_fsinfo(fsopts);
338 	}
339 
340 		/* set FFS defaults */
341 	if (fsopts->sectorsize == -1)
342 		fsopts->sectorsize = DFL_SECSIZE;
343 	if (ffs_opts->fsize == -1)
344 		ffs_opts->fsize = MAX(DFL_FRAGSIZE, fsopts->sectorsize);
345 	if (ffs_opts->bsize == -1)
346 		ffs_opts->bsize = MIN(DFL_BLKSIZE, 8 * ffs_opts->fsize);
347 	if (ffs_opts->cpg == -1)
348 		ffs_opts->cpg = DFL_CYLSPERGROUP;
349 	else
350 		ffs_opts->cpgflg = 1;
351 				/* fsopts->density is set below */
352 	if (ffs_opts->nsectors == -1)
353 		ffs_opts->nsectors = DFL_NSECTORS;
354 	if (ffs_opts->minfree == -1)
355 		ffs_opts->minfree = MINFREE;
356 	if (ffs_opts->optimization == -1)
357 		ffs_opts->optimization = DEFAULTOPT;
358 	if (ffs_opts->maxcontig == -1)
359 		ffs_opts->maxcontig =
360 		    MAX(1, MIN(MAXPHYS, FFS_MAXBSIZE) / ffs_opts->bsize);
361 	/* XXX ondisk32 */
362 	if (ffs_opts->maxbpg == -1)
363 		ffs_opts->maxbpg = ffs_opts->bsize / sizeof(int32_t);
364 	if (ffs_opts->avgfilesize == -1)
365 		ffs_opts->avgfilesize = AVFILESIZ;
366 	if (ffs_opts->avgfpdir == -1)
367 		ffs_opts->avgfpdir = AFPDIR;
368 
369 		/* calculate size of tree */
370 	ffs_size_dir(root, fsopts);
371 	fsopts->inodes += ROOTINO;		/* include first two inodes */
372 
373 	if (debug & DEBUG_FS_VALIDATE)
374 		printf("ffs_validate: size of tree: %lld bytes, %lld inodes\n",
375 		    (long long)fsopts->size, (long long)fsopts->inodes);
376 
377 		/* add requested slop */
378 	fsopts->size += fsopts->freeblocks;
379 	fsopts->inodes += fsopts->freefiles;
380 	if (fsopts->freefilepc > 0)
381 		fsopts->inodes =
382 		    fsopts->inodes * (100 + fsopts->freefilepc) / 100;
383 	if (fsopts->freeblockpc > 0)
384 		fsopts->size =
385 		    fsopts->size * (100 + fsopts->freeblockpc) / 100;
386 
387 		/* add space needed for superblocks */
388 	/*
389 	 * The old SBOFF (SBLOCK_UFS1) is used here because makefs is
390 	 * typically used for small filesystems where space matters.
391 	 * XXX make this an option.
392 	 */
393 	fsopts->size += (SBLOCK_UFS1 + SBLOCKSIZE) * ncg;
394 		/* add space needed to store inodes, x3 for blockmaps, etc */
395 	if (ffs_opts->version == 1)
396 		fsopts->size += ncg * DINODE1_SIZE *
397 		    roundup(fsopts->inodes / ncg,
398 			ffs_opts->bsize / DINODE1_SIZE);
399 	else
400 		fsopts->size += ncg * DINODE2_SIZE *
401 		    roundup(fsopts->inodes / ncg,
402 			ffs_opts->bsize / DINODE2_SIZE);
403 
404 		/* add minfree */
405 	if (ffs_opts->minfree > 0)
406 		fsopts->size =
407 		    fsopts->size * (100 + ffs_opts->minfree) / 100;
408 	/*
409 	 * XXX	any other fs slop to add, such as csum's, bitmaps, etc ??
410 	 */
411 
412 	if (fsopts->size < fsopts->minsize)	/* ensure meets minimum size */
413 		fsopts->size = fsopts->minsize;
414 
415 		/* round up to the next block */
416 	fsopts->size = roundup(fsopts->size, ffs_opts->bsize);
417 
418 		/* calculate density if necessary */
419 	if (ffs_opts->density == -1)
420 		ffs_opts->density = fsopts->size / fsopts->inodes + 1;
421 
422 	if (debug & DEBUG_FS_VALIDATE) {
423 		printf("ffs_validate: after defaults set:\n");
424 		ffs_dump_fsinfo(fsopts);
425 		printf("ffs_validate: dir %s; %lld bytes, %lld inodes\n",
426 		    dir, (long long)fsopts->size, (long long)fsopts->inodes);
427 	}
428 	sectorsize = fsopts->sectorsize;	/* XXX - see earlier */
429 
430 		/* now check calculated sizes vs requested sizes */
431 	if (fsopts->maxsize > 0 && fsopts->size > fsopts->maxsize) {
432 		errx(1, "`%s' size of %lld is larger than the maxsize of %lld.",
433 		    dir, (long long)fsopts->size, (long long)fsopts->maxsize);
434 	}
435 }
436 
437 
438 static void
439 ffs_dump_fsinfo(fsinfo_t *f)
440 {
441 
442 	ffs_opt_t	*fs = f->fs_specific;
443 
444 	printf("fsopts at %p\n", f);
445 
446 	printf("\tsize %lld, inodes %lld, curinode %u\n",
447 	    (long long)f->size, (long long)f->inodes, f->curinode);
448 
449 	printf("\tminsize %lld, maxsize %lld\n",
450 	    (long long)f->minsize, (long long)f->maxsize);
451 	printf("\tfree files %lld, freefile %% %d\n",
452 	    (long long)f->freefiles, f->freefilepc);
453 	printf("\tfree blocks %lld, freeblock %% %d\n",
454 	    (long long)f->freeblocks, f->freeblockpc);
455 	printf("\tneedswap %d, sectorsize %d\n", f->needswap, f->sectorsize);
456 
457 	printf("\tbsize %d, fsize %d, cpg %d, density %d\n",
458 	    fs->bsize, fs->fsize, fs->cpg, fs->density);
459 	printf("\tnsectors %d, rpm %d, minfree %d\n",
460 	    fs->nsectors, fs->rpm, fs->minfree);
461 	printf("\tmaxcontig %d, maxbpg %d\n",
462 	    fs->maxcontig, fs->maxbpg);
463 	printf("\toptimization %s\n",
464 	    fs->optimization == FS_OPTSPACE ? "space" : "time");
465 }
466 
467 
468 static int
469 ffs_create_image(const char *image, fsinfo_t *fsopts)
470 {
471 #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS
472 	struct statvfs	sfs;
473 #endif
474 	struct fs	*fs;
475 	char	*buf;
476 	int	i, bufsize;
477 	off_t	bufrem;
478 
479 	assert (image != NULL);
480 	assert (fsopts != NULL);
481 
482 		/* create image */
483 	if ((fsopts->fd = open(image, O_RDWR | O_CREAT | O_TRUNC, 0666))
484 	    == -1) {
485 		warn("Can't open `%s' for writing", image);
486 		return (-1);
487 	}
488 
489 		/* zero image */
490 #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS
491 	if (fstatvfs(fsopts->fd, &sfs) == -1) {
492 #endif
493 		bufsize = 8192;
494 #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS
495 		warn("can't fstatvfs `%s', using default %d byte chunk",
496 		    image, bufsize);
497 	} else
498 		bufsize = sfs.f_iosize;
499 #endif
500 	bufrem = fsopts->size;
501 
502 	if (fsopts->sparse) {
503 		if (ftruncate(fsopts->fd, bufrem) == -1) {
504 			printf ("ERROR in truncate. Sparse option disabled\n");
505 			fsopts->sparse = 0;
506 		} else {
507 			bufrem = 0; /* File truncated at bufrem. Remaining is 0 */
508 			buf = NULL;
509 		}
510 	}
511 
512 	if ((debug & DEBUG_FS_CREATE_IMAGE) && fsopts->sparse == 0)
513 		printf(
514 		    "zero-ing image `%s', %lld sectors, using %d byte chunks\n",
515 		    image, (long long)bufrem, bufsize);
516 	if ((bufrem > 0) && ((buf = calloc(1, bufsize)) == NULL)) {
517 		warn("Can't create buffer for sector");
518 		return (-1);
519 	}
520 	while (bufrem > 0) {
521 		i = write(fsopts->fd, buf, MIN(bufsize, bufrem));
522 		if (i == -1) {
523 			warn("zeroing image, %lld bytes to go",
524 			    (long long)bufrem);
525 			free(buf);
526 			return (-1);
527 		}
528 		bufrem -= i;
529 	}
530 	if (buf)
531 		free(buf);
532 
533 		/* make the file system */
534 	if (debug & DEBUG_FS_CREATE_IMAGE)
535 		printf("calling mkfs(\"%s\", ...)\n", image);
536 	fs = ffs_mkfs(image, fsopts);
537 	fsopts->superblock = (void *)fs;
538 	if (debug & DEBUG_FS_CREATE_IMAGE) {
539 		time_t t;
540 
541 		t = (time_t)((struct fs *)fsopts->superblock)->fs_time;
542 		printf("mkfs returned %p; fs_time %s",
543 		    fsopts->superblock, ctime(&t));
544 		printf("fs totals: nbfree %lld, nffree %lld, nifree %lld, ndir %lld\n",
545 		    (long long)fs->fs_cstotal.cs_nbfree,
546 		    (long long)fs->fs_cstotal.cs_nffree,
547 		    (long long)fs->fs_cstotal.cs_nifree,
548 		    (long long)fs->fs_cstotal.cs_ndir);
549 	}
550 
551 	if ((off_t)(fs->fs_cstotal.cs_nifree + ROOTINO) < fsopts->inodes) {
552 		warnx(
553 		"Image file `%s' has %lld free inodes; %lld are required.",
554 		    image,
555 		    (long long)(fs->fs_cstotal.cs_nifree + ROOTINO),
556 		    (long long)fsopts->inodes);
557 		return (-1);
558 	}
559 	return (fsopts->fd);
560 }
561 
562 
563 static void
564 ffs_size_dir(fsnode *root, fsinfo_t *fsopts)
565 {
566 	struct direct	tmpdir;
567 	fsnode *	node;
568 	int		curdirsize, this;
569 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
570 
571 	/* node may be NULL (empty directory) */
572 	assert(fsopts != NULL);
573 	assert(ffs_opts != NULL);
574 
575 	if (debug & DEBUG_FS_SIZE_DIR)
576 		printf("ffs_size_dir: entry: bytes %lld inodes %lld\n",
577 		    (long long)fsopts->size, (long long)fsopts->inodes);
578 
579 #define	ADDDIRENT(e) do {						\
580 	tmpdir.d_namlen = strlen((e));					\
581 	this = DIRSIZ(0, &tmpdir, 0);					\
582 	if (debug & DEBUG_FS_SIZE_DIR_ADD_DIRENT)			\
583 		printf("ADDDIRENT: was: %s (%d) this %d cur %d\n",	\
584 		    e, tmpdir.d_namlen, this, curdirsize);		\
585 	if (this + curdirsize > roundup(curdirsize, DIRBLKSIZ))		\
586 		curdirsize = roundup(curdirsize, DIRBLKSIZ);		\
587 	curdirsize += this;						\
588 	if (debug & DEBUG_FS_SIZE_DIR_ADD_DIRENT)			\
589 		printf("ADDDIRENT: now: %s (%d) this %d cur %d\n",	\
590 		    e, tmpdir.d_namlen, this, curdirsize);		\
591 } while (0);
592 
593 	/*
594 	 * XXX	this needs to take into account extra space consumed
595 	 *	by indirect blocks, etc.
596 	 */
597 #define	ADDSIZE(x) do {							\
598 	fsopts->size += roundup((x), ffs_opts->fsize);			\
599 } while (0);
600 
601 	curdirsize = 0;
602 	for (node = root; node != NULL; node = node->next) {
603 		ADDDIRENT(node->name);
604 		if (node == root) {			/* we're at "." */
605 			assert(strcmp(node->name, ".") == 0);
606 			ADDDIRENT("..");
607 		} else if ((node->inode->flags & FI_SIZED) == 0) {
608 				/* don't count duplicate names */
609 			node->inode->flags |= FI_SIZED;
610 			if (debug & DEBUG_FS_SIZE_DIR_NODE)
611 				printf("ffs_size_dir: `%s' size %lld\n",
612 				    node->name,
613 				    (long long)node->inode->st.st_size);
614 			fsopts->inodes++;
615 			if (node->type == S_IFREG)
616 				ADDSIZE(node->inode->st.st_size);
617 			if (node->type == S_IFLNK) {
618 				size_t	slen;
619 
620 				slen = strlen(node->symlink) + 1;
621 				if (slen >= (ffs_opts->version == 1 ?
622 						MAXSYMLINKLEN_UFS1 :
623 						MAXSYMLINKLEN_UFS2))
624 					ADDSIZE(slen);
625 			}
626 		}
627 		if (node->type == S_IFDIR)
628 			ffs_size_dir(node->child, fsopts);
629 	}
630 	ADDSIZE(curdirsize);
631 
632 	if (debug & DEBUG_FS_SIZE_DIR)
633 		printf("ffs_size_dir: exit: size %lld inodes %lld\n",
634 		    (long long)fsopts->size, (long long)fsopts->inodes);
635 }
636 
637 static void *
638 ffs_build_dinode1(struct ufs1_dinode *dinp, dirbuf_t *dbufp, fsnode *cur,
639 		 fsnode *root, fsinfo_t *fsopts)
640 {
641 	size_t slen;
642 	void *membuf;
643 
644 	memset(dinp, 0, sizeof(*dinp));
645 	dinp->di_mode = cur->inode->st.st_mode;
646 	dinp->di_nlink = cur->inode->nlink;
647 	dinp->di_size = cur->inode->st.st_size;
648 	dinp->di_atime = cur->inode->st.st_atime;
649 	dinp->di_mtime = cur->inode->st.st_mtime;
650 	dinp->di_ctime = cur->inode->st.st_ctime;
651 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
652 	dinp->di_atimensec = cur->inode->st.st_atimensec;
653 	dinp->di_mtimensec = cur->inode->st.st_mtimensec;
654 	dinp->di_ctimensec = cur->inode->st.st_ctimensec;
655 #endif
656 #if HAVE_STRUCT_STAT_ST_FLAGS
657 	dinp->di_flags = cur->inode->st.st_flags;
658 #endif
659 #if HAVE_STRUCT_STAT_ST_GEN
660 	dinp->di_gen = cur->inode->st.st_gen;
661 #endif
662 	dinp->di_uid = cur->inode->st.st_uid;
663 	dinp->di_gid = cur->inode->st.st_gid;
664 		/* not set: di_db, di_ib, di_blocks, di_spare */
665 
666 	membuf = NULL;
667 	if (cur == root) {			/* "."; write dirbuf */
668 		membuf = dbufp->buf;
669 		dinp->di_size = dbufp->size;
670 	} else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) {
671 		dinp->di_size = 0;	/* a device */
672 		dinp->di_rdev =
673 		    ufs_rw32(cur->inode->st.st_rdev, fsopts->needswap);
674 	} else if (S_ISLNK(cur->type)) {	/* symlink */
675 		slen = strlen(cur->symlink);
676 		if (slen < MAXSYMLINKLEN_UFS1) {	/* short link */
677 			memcpy(dinp->di_db, cur->symlink, slen);
678 		} else
679 			membuf = cur->symlink;
680 		dinp->di_size = slen;
681 	}
682 	return membuf;
683 }
684 
685 static void *
686 ffs_build_dinode2(struct ufs2_dinode *dinp, dirbuf_t *dbufp, fsnode *cur,
687 		 fsnode *root, fsinfo_t *fsopts)
688 {
689 	size_t slen;
690 	void *membuf;
691 
692 	memset(dinp, 0, sizeof(*dinp));
693 	dinp->di_mode = cur->inode->st.st_mode;
694 	dinp->di_nlink = cur->inode->nlink;
695 	dinp->di_size = cur->inode->st.st_size;
696 	dinp->di_atime = cur->inode->st.st_atime;
697 	dinp->di_mtime = cur->inode->st.st_mtime;
698 	dinp->di_ctime = cur->inode->st.st_ctime;
699 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
700 	dinp->di_atimensec = cur->inode->st.st_atimensec;
701 	dinp->di_mtimensec = cur->inode->st.st_mtimensec;
702 	dinp->di_ctimensec = cur->inode->st.st_ctimensec;
703 #endif
704 #if HAVE_STRUCT_STAT_ST_FLAGS
705 	dinp->di_flags = cur->inode->st.st_flags;
706 #endif
707 #if HAVE_STRUCT_STAT_ST_GEN
708 	dinp->di_gen = cur->inode->st.st_gen;
709 #endif
710 #if HAVE_STRUCT_STAT_BIRTHTIME
711 	dinp->di_birthtime = cur->inode->st.st_birthtime;
712 	dinp->di_birthnsec = cur->inode->st.st_birthtimensec;
713 #endif
714 	dinp->di_uid = cur->inode->st.st_uid;
715 	dinp->di_gid = cur->inode->st.st_gid;
716 		/* not set: di_db, di_ib, di_blocks, di_spare */
717 
718 	membuf = NULL;
719 	if (cur == root) {			/* "."; write dirbuf */
720 		membuf = dbufp->buf;
721 		dinp->di_size = dbufp->size;
722 	} else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) {
723 		dinp->di_size = 0;	/* a device */
724 		dinp->di_rdev =
725 		    ufs_rw64(cur->inode->st.st_rdev, fsopts->needswap);
726 	} else if (S_ISLNK(cur->type)) {	/* symlink */
727 		slen = strlen(cur->symlink);
728 		if (slen < MAXSYMLINKLEN_UFS2) {	/* short link */
729 			memcpy(dinp->di_db, cur->symlink, slen);
730 		} else
731 			membuf = cur->symlink;
732 		dinp->di_size = slen;
733 	}
734 	return membuf;
735 }
736 
737 static int
738 ffs_populate_dir(const char *dir, fsnode *root, fsinfo_t *fsopts)
739 {
740 	fsnode		*cur;
741 	dirbuf_t	dirbuf;
742 	union dinode	din;
743 	void		*membuf;
744 	char		path[MAXPATHLEN + 1];
745 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
746 
747 	assert(dir != NULL);
748 	assert(root != NULL);
749 	assert(fsopts != NULL);
750 	assert(ffs_opts != NULL);
751 
752 	(void)memset(&dirbuf, 0, sizeof(dirbuf));
753 
754 	if (debug & DEBUG_FS_POPULATE)
755 		printf("ffs_populate_dir: PASS 1  dir %s node %p\n", dir, root);
756 
757 		/*
758 		 * pass 1: allocate inode numbers, build directory `file'
759 		 */
760 	for (cur = root; cur != NULL; cur = cur->next) {
761 		if ((cur->inode->flags & FI_ALLOCATED) == 0) {
762 			cur->inode->flags |= FI_ALLOCATED;
763 			if (cur == root && cur->parent != NULL)
764 				cur->inode->ino = cur->parent->inode->ino;
765 			else {
766 				cur->inode->ino = fsopts->curinode;
767 				fsopts->curinode++;
768 			}
769 		}
770 		ffs_make_dirbuf(&dirbuf, cur->name, cur, fsopts->needswap);
771 		if (cur == root) {		/* we're at "."; add ".." */
772 			ffs_make_dirbuf(&dirbuf, "..",
773 			    cur->parent == NULL ? cur : cur->parent->first,
774 			    fsopts->needswap);
775 			root->inode->nlink++;	/* count my parent's link */
776 		} else if (cur->child != NULL)
777 			root->inode->nlink++;	/* count my child's link */
778 
779 		/*
780 		 * XXX	possibly write file and long symlinks here,
781 		 *	ensuring that blocks get written before inodes?
782 		 *	otoh, this isn't a real filesystem, so who
783 		 *	cares about ordering? :-)
784 		 */
785 	}
786 	if (debug & DEBUG_FS_POPULATE_DIRBUF)
787 		ffs_dump_dirbuf(&dirbuf, dir, fsopts->needswap);
788 
789 		/*
790 		 * pass 2: write out dirbuf, then non-directories at this level
791 		 */
792 	if (debug & DEBUG_FS_POPULATE)
793 		printf("ffs_populate_dir: PASS 2  dir %s\n", dir);
794 	for (cur = root; cur != NULL; cur = cur->next) {
795 		if (cur->inode->flags & FI_WRITTEN)
796 			continue;		/* skip hard-linked entries */
797 		cur->inode->flags |= FI_WRITTEN;
798 
799 		if ((size_t)snprintf(path, sizeof(path), "%s/%s/%s", cur->root,
800 		    cur->path, cur->name) >= sizeof(path))
801 			errx(1, "Pathname too long.");
802 
803 		if (cur->child != NULL)
804 			continue;		/* child creates own inode */
805 
806 				/* build on-disk inode */
807 		if (ffs_opts->version == 1)
808 			membuf = ffs_build_dinode1(&din.ffs1_din, &dirbuf, cur,
809 			    root, fsopts);
810 		else
811 			membuf = ffs_build_dinode2(&din.ffs2_din, &dirbuf, cur,
812 			    root, fsopts);
813 
814 		if (debug & DEBUG_FS_POPULATE_NODE) {
815 			printf("ffs_populate_dir: writing ino %d, %s",
816 			    cur->inode->ino, inode_type(cur->type));
817 			if (cur->inode->nlink > 1)
818 				printf(", nlink %d", cur->inode->nlink);
819 			putchar('\n');
820 		}
821 
822 		if (membuf != NULL) {
823 			ffs_write_file(&din, cur->inode->ino, membuf, fsopts);
824 		} else if (S_ISREG(cur->type)) {
825 			ffs_write_file(&din, cur->inode->ino, path, fsopts);
826 		} else {
827 			assert (! S_ISDIR(cur->type));
828 			ffs_write_inode(&din, cur->inode->ino, fsopts);
829 		}
830 	}
831 
832 		/*
833 		 * pass 3: write out sub-directories
834 		 */
835 	if (debug & DEBUG_FS_POPULATE)
836 		printf("ffs_populate_dir: PASS 3  dir %s\n", dir);
837 	for (cur = root; cur != NULL; cur = cur->next) {
838 		if (cur->child == NULL)
839 			continue;
840 		if ((size_t)snprintf(path, sizeof(path), "%s/%s", dir,
841 		    cur->name) >= sizeof(path))
842 			errx(1, "Pathname too long.");
843 		if (! ffs_populate_dir(path, cur->child, fsopts))
844 			return (0);
845 	}
846 
847 	if (debug & DEBUG_FS_POPULATE)
848 		printf("ffs_populate_dir: DONE dir %s\n", dir);
849 
850 		/* cleanup */
851 	if (dirbuf.buf != NULL)
852 		free(dirbuf.buf);
853 	return (1);
854 }
855 
856 
857 static void
858 ffs_write_file(union dinode *din, uint32_t ino, void *buf, fsinfo_t *fsopts)
859 {
860 	int 	isfile, ffd;
861 	char	*fbuf, *p;
862 	off_t	bufleft, chunk, offset;
863 	ssize_t nread;
864 	struct inode	in;
865 	struct buf *	bp;
866 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
867 
868 	assert (din != NULL);
869 	assert (buf != NULL);
870 	assert (fsopts != NULL);
871 	assert (ffs_opts != NULL);
872 
873 	isfile = S_ISREG(DIP(din, mode));
874 	fbuf = NULL;
875 	ffd = -1;
876 	p = NULL;
877 
878 	in.i_fs = (struct fs *)fsopts->superblock;
879 
880 	if (debug & DEBUG_FS_WRITE_FILE) {
881 		printf(
882 		    "ffs_write_file: ino %u, din %p, isfile %d, %s, size %lld",
883 		    ino, din, isfile, inode_type(DIP(din, mode) & S_IFMT),
884 		    (long long)DIP(din, size));
885 		if (isfile)
886 			printf(", file '%s'\n", (char *)buf);
887 		else
888 			printf(", buffer %p\n", buf);
889 	}
890 
891 	in.i_number = ino;
892 	in.i_size = DIP(din, size);
893 	if (ffs_opts->version == 1)
894 		memcpy(&in.i_din.ffs1_din, &din->ffs1_din,
895 		    sizeof(in.i_din.ffs1_din));
896 	else
897 		memcpy(&in.i_din.ffs2_din, &din->ffs2_din,
898 		    sizeof(in.i_din.ffs2_din));
899 	in.i_fd = fsopts->fd;
900 
901 	if (DIP(din, size) == 0)
902 		goto write_inode_and_leave;		/* mmm, cheating */
903 
904 	if (isfile) {
905 		if ((fbuf = malloc(ffs_opts->bsize)) == NULL)
906 			err(1, "Allocating memory for write buffer");
907 		if ((ffd = open((char *)buf, O_RDONLY, 0444)) == -1) {
908 			warn("Can't open `%s' for reading", (char *)buf);
909 			goto leave_ffs_write_file;
910 		}
911 	} else {
912 		p = buf;
913 	}
914 
915 	chunk = 0;
916 	for (bufleft = DIP(din, size); bufleft > 0; bufleft -= chunk) {
917 		chunk = MIN(bufleft, ffs_opts->bsize);
918 		if (!isfile)
919 			;
920 		else if ((nread = read(ffd, fbuf, chunk)) == -1)
921 			err(EXIT_FAILURE, "Reading `%s', %lld bytes to go",
922 			    (char *)buf, (long long)bufleft);
923 		else if (nread != chunk)
924 			errx(EXIT_FAILURE, "Reading `%s', %lld bytes to go, "
925 			    "read %zd bytes, expected %ju bytes, does "
926 			    "metalog size= attribute mismatch source size?",
927 			    (char *)buf, (long long)bufleft, nread,
928 			    (uintmax_t)chunk);
929 		else
930 			p = fbuf;
931 		offset = DIP(din, size) - bufleft;
932 		if (debug & DEBUG_FS_WRITE_FILE_BLOCK)
933 			printf(
934 		"ffs_write_file: write %p offset %lld size %lld left %lld\n",
935 			    p, (long long)offset,
936 			    (long long)chunk, (long long)bufleft);
937 	/*
938 	 * XXX	if holey support is desired, do the check here
939 	 *
940 	 * XXX	might need to write out last bit in fragroundup
941 	 *	sized chunk. however, ffs_balloc() handles this for us
942 	 */
943 		errno = ffs_balloc(&in, offset, chunk, &bp);
944  bad_ffs_write_file:
945 		if (errno != 0)
946 			err(1,
947 			    "Writing inode %d (%s), bytes %lld + %lld",
948 			    ino,
949 			    isfile ? (char *)buf :
950 			      inode_type(DIP(din, mode) & S_IFMT),
951 			    (long long)offset, (long long)chunk);
952 		memcpy(bp->b_data, p, chunk);
953 		errno = bwrite(bp);
954 		if (errno != 0)
955 			goto bad_ffs_write_file;
956 		brelse(bp);
957 		if (!isfile)
958 			p += chunk;
959 	}
960 
961  write_inode_and_leave:
962 	ffs_write_inode(&in.i_din, in.i_number, fsopts);
963 
964  leave_ffs_write_file:
965 	if (fbuf)
966 		free(fbuf);
967 	if (ffd != -1)
968 		close(ffd);
969 }
970 
971 
972 static void
973 ffs_dump_dirbuf(dirbuf_t *dbuf, const char *dir, int needswap)
974 {
975 	doff_t		i;
976 	struct direct	*de;
977 	uint16_t	reclen;
978 
979 	assert (dbuf != NULL);
980 	assert (dir != NULL);
981 	printf("ffs_dump_dirbuf: dir %s size %d cur %d\n",
982 	    dir, dbuf->size, dbuf->cur);
983 
984 	for (i = 0; i < dbuf->size; ) {
985 		de = (struct direct *)(dbuf->buf + i);
986 		reclen = ufs_rw16(de->d_reclen, needswap);
987 		printf(
988 	    " inode %4d %7s offset %4d reclen %3d namlen %3d name %s\n",
989 		    ufs_rw32(de->d_fileno, needswap),
990 		    inode_type(DTTOIF(de->d_type)), i, reclen,
991 		    de->d_namlen, de->d_name);
992 		i += reclen;
993 		assert(reclen > 0);
994 	}
995 }
996 
997 static void
998 ffs_make_dirbuf(dirbuf_t *dbuf, const char *name, fsnode *node, int needswap)
999 {
1000 	struct direct	de, *dp;
1001 	uint16_t	llen, reclen;
1002 	u_char		*newbuf;
1003 
1004 	assert (dbuf != NULL);
1005 	assert (name != NULL);
1006 	assert (node != NULL);
1007 					/* create direct entry */
1008 	(void)memset(&de, 0, sizeof(de));
1009 	de.d_fileno = ufs_rw32(node->inode->ino, needswap);
1010 	de.d_type = IFTODT(node->type);
1011 	de.d_namlen = (uint8_t)strlen(name);
1012 	strcpy(de.d_name, name);
1013 	reclen = DIRSIZ(0, &de, needswap);
1014 	de.d_reclen = ufs_rw16(reclen, needswap);
1015 
1016 	dp = (struct direct *)(dbuf->buf + dbuf->cur);
1017 	llen = 0;
1018 	if (dp != NULL)
1019 		llen = DIRSIZ(0, dp, needswap);
1020 
1021 	if (debug & DEBUG_FS_MAKE_DIRBUF)
1022 		printf(
1023 		    "ffs_make_dirbuf: dbuf siz %d cur %d lastlen %d\n"
1024 		    "  ino %d type %d reclen %d namlen %d name %.30s\n",
1025 		    dbuf->size, dbuf->cur, llen,
1026 		    ufs_rw32(de.d_fileno, needswap), de.d_type, reclen,
1027 		    de.d_namlen, de.d_name);
1028 
1029 	if (reclen + dbuf->cur + llen > roundup(dbuf->size, DIRBLKSIZ)) {
1030 		if (debug & DEBUG_FS_MAKE_DIRBUF)
1031 			printf("ffs_make_dirbuf: growing buf to %d\n",
1032 			    dbuf->size + DIRBLKSIZ);
1033 		if ((newbuf = realloc(dbuf->buf, dbuf->size + DIRBLKSIZ)) == NULL)
1034 			err(1, "Allocating memory for directory buffer");
1035 		dbuf->buf = newbuf;
1036 		dbuf->size += DIRBLKSIZ;
1037 		memset(dbuf->buf + dbuf->size - DIRBLKSIZ, 0, DIRBLKSIZ);
1038 		dbuf->cur = dbuf->size - DIRBLKSIZ;
1039 	} else if (dp) {			/* shrink end of previous */
1040 		dp->d_reclen = ufs_rw16(llen,needswap);
1041 		dbuf->cur += llen;
1042 	}
1043 	dp = (struct direct *)(dbuf->buf + dbuf->cur);
1044 	memcpy(dp, &de, reclen);
1045 	dp->d_reclen = ufs_rw16(dbuf->size - dbuf->cur, needswap);
1046 }
1047 
1048 /*
1049  * cribbed from sys/ufs/ffs/ffs_alloc.c
1050  */
1051 static void
1052 ffs_write_inode(union dinode *dp, uint32_t ino, const fsinfo_t *fsopts)
1053 {
1054 	char 		*buf;
1055 	struct ufs1_dinode *dp1;
1056 	struct ufs2_dinode *dp2, *dip;
1057 	struct cg	*cgp;
1058 	struct fs	*fs;
1059 	int		cg, cgino, i;
1060 	daddr_t		d;
1061 	char		sbbuf[FFS_MAXBSIZE];
1062 	uint32_t	initediblk;
1063 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
1064 
1065 	assert (dp != NULL);
1066 	assert (ino > 0);
1067 	assert (fsopts != NULL);
1068 	assert (ffs_opts != NULL);
1069 
1070 	fs = (struct fs *)fsopts->superblock;
1071 	cg = ino_to_cg(fs, ino);
1072 	cgino = ino % fs->fs_ipg;
1073 	if (debug & DEBUG_FS_WRITE_INODE)
1074 		printf("ffs_write_inode: din %p ino %u cg %d cgino %d\n",
1075 		    dp, ino, cg, cgino);
1076 
1077 	ffs_rdfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf,
1078 	    fsopts);
1079 	cgp = (struct cg *)sbbuf;
1080 	if (!cg_chkmagic(cgp, fsopts->needswap))
1081 		errx(1, "ffs_write_inode: cg %d: bad magic number", cg);
1082 
1083 	assert (isclr(cg_inosused(cgp, fsopts->needswap), cgino));
1084 
1085 	buf = malloc(fs->fs_bsize);
1086 	if (buf == NULL)
1087 		errx(1, "ffs_write_inode: cg %d: can't alloc inode block", cg);
1088 
1089 	dp1 = (struct ufs1_dinode *)buf;
1090 	dp2 = (struct ufs2_dinode *)buf;
1091 
1092 	if (fs->fs_cstotal.cs_nifree == 0)
1093 		errx(1, "ffs_write_inode: fs out of inodes for ino %u",
1094 		    ino);
1095 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1096 		errx(1,
1097 		    "ffs_write_inode: cg %d out of inodes for ino %u",
1098 		    cg, ino);
1099 	setbit(cg_inosused(cgp, fsopts->needswap), cgino);
1100 	ufs_add32(cgp->cg_cs.cs_nifree, -1, fsopts->needswap);
1101 	fs->fs_cstotal.cs_nifree--;
1102 	fs->fs_cs(fs, cg).cs_nifree--;
1103 	if (S_ISDIR(DIP(dp, mode))) {
1104 		ufs_add32(cgp->cg_cs.cs_ndir, 1, fsopts->needswap);
1105 		fs->fs_cstotal.cs_ndir++;
1106 		fs->fs_cs(fs, cg).cs_ndir++;
1107 	}
1108 
1109 	/*
1110 	 * Initialize inode blocks on the fly for UFS2.
1111 	 */
1112 	initediblk = ufs_rw32(cgp->cg_initediblk, fsopts->needswap);
1113 	if (ffs_opts->version == 2 &&
1114 	    (uint32_t)(cgino + INOPB(fs)) > initediblk &&
1115 	    initediblk < ufs_rw32(cgp->cg_niblk, fsopts->needswap)) {
1116 		memset(buf, 0, fs->fs_bsize);
1117 		dip = (struct ufs2_dinode *)buf;
1118 		srandom(time(NULL));
1119 		for (i = 0; i < INOPB(fs); i++) {
1120 			dip->di_gen = random() / 2 + 1;
1121 			dip++;
1122 		}
1123 		ffs_wtfs(fsbtodb(fs, ino_to_fsba(fs,
1124 				  cg * fs->fs_ipg + initediblk)),
1125 		    fs->fs_bsize, buf, fsopts);
1126 		initediblk += INOPB(fs);
1127 		cgp->cg_initediblk = ufs_rw32(initediblk, fsopts->needswap);
1128 	}
1129 
1130 
1131 	ffs_wtfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf,
1132 	    fsopts);
1133 
1134 					/* now write inode */
1135 	d = fsbtodb(fs, ino_to_fsba(fs, ino));
1136 	ffs_rdfs(d, fs->fs_bsize, buf, fsopts);
1137 	if (fsopts->needswap) {
1138 		if (ffs_opts->version == 1)
1139 			ffs_dinode1_swap(&dp->ffs1_din,
1140 			    &dp1[ino_to_fsbo(fs, ino)]);
1141 		else
1142 			ffs_dinode2_swap(&dp->ffs2_din,
1143 			    &dp2[ino_to_fsbo(fs, ino)]);
1144 	} else {
1145 		if (ffs_opts->version == 1)
1146 			dp1[ino_to_fsbo(fs, ino)] = dp->ffs1_din;
1147 		else
1148 			dp2[ino_to_fsbo(fs, ino)] = dp->ffs2_din;
1149 	}
1150 	ffs_wtfs(d, fs->fs_bsize, buf, fsopts);
1151 	free(buf);
1152 }
1153 
1154 void
1155 panic(const char *fmt, ...)
1156 {
1157 	va_list ap;
1158 
1159 	va_start(ap, fmt);
1160 	vwarnx(fmt, ap);
1161 	va_end(ap);
1162 	exit(1);
1163 }
1164