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