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