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