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