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