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