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