ffs.c revision 186334
1185222Ssam/*	$NetBSD: ffs.c,v 1.30 2004/06/24 22:30:13 lukem Exp $	*/
2185222Ssam
3185222Ssam/*
4185222Ssam * Copyright (c) 2001 Wasabi Systems, Inc.
5185222Ssam * All rights reserved.
6185222Ssam *
7185222Ssam * Written by Luke Mewburn for Wasabi Systems, Inc.
8185222Ssam *
9185222Ssam * Redistribution and use in source and binary forms, with or without
10185222Ssam * modification, are permitted provided that the following conditions
11185222Ssam * are met:
12185222Ssam * 1. Redistributions of source code must retain the above copyright
13185222Ssam *    notice, this list of conditions and the following disclaimer.
14185222Ssam * 2. Redistributions in binary form must reproduce the above copyright
15185222Ssam *    notice, this list of conditions and the following disclaimer in the
16185222Ssam *    documentation and/or other materials provided with the distribution.
17185222Ssam * 3. All advertising materials mentioning features or use of this software
18185222Ssam *    must display the following acknowledgement:
19185222Ssam *      This product includes software developed for the NetBSD Project by
20185222Ssam *      Wasabi Systems, Inc.
21185222Ssam * 4. The name of Wasabi Systems, Inc. may not be used to endorse
22185222Ssam *    or promote products derived from this software without specific prior
23185222Ssam *    written permission.
24185222Ssam *
25185222Ssam * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
26185222Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27185222Ssam * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28185222Ssam * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
29185222Ssam * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30185222Ssam * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31185222Ssam * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32185222Ssam * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33185222Ssam * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34185222Ssam * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35185222Ssam * POSSIBILITY OF SUCH DAMAGE.
36185222Ssam */
37185222Ssam/*
38185222Ssam * Copyright (c) 1982, 1986, 1989, 1993
39185222Ssam *	The Regents of the University of California.  All rights reserved.
40185222Ssam *
41185222Ssam * Redistribution and use in source and binary forms, with or without
42185222Ssam * modification, are permitted provided that the following conditions
43185222Ssam * are met:
44185222Ssam * 1. Redistributions of source code must retain the above copyright
45185222Ssam *    notice, this list of conditions and the following disclaimer.
46185222Ssam * 2. Redistributions in binary form must reproduce the above copyright
47185222Ssam *    notice, this list of conditions and the following disclaimer in the
48185222Ssam *    documentation and/or other materials provided with the distribution.
49185222Ssam * 3. Neither the name of the University nor the names of its contributors
50185222Ssam *    may be used to endorse or promote products derived from this software
51185222Ssam *    without specific prior written permission.
52185222Ssam *
53185222Ssam * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54185222Ssam * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55185222Ssam * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56185222Ssam * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57185222Ssam * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58185222Ssam * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59185222Ssam * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60185222Ssam * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61185222Ssam * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62185222Ssam * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63185222Ssam * SUCH DAMAGE.
64185222Ssam *
65185222Ssam *	@(#)ffs_alloc.c	8.19 (Berkeley) 7/13/95
66185222Ssam */
67185222Ssam
68185222Ssam#include <sys/cdefs.h>
69186334Ssam__FBSDID("$FreeBSD: projects/makefs/ffs.c 186334 2008-12-19 18:45:43Z sam $");
70185222Ssam
71185222Ssam#include <sys/param.h>
72185222Ssam
73185222Ssam#include <sys/mount.h>
74185222Ssam
75185222Ssam#include <assert.h>
76185222Ssam#include <errno.h>
77185222Ssam#include <fcntl.h>
78185222Ssam#include <stdarg.h>
79185222Ssam#include <stdio.h>
80185222Ssam#include <stdlib.h>
81185222Ssam#include <string.h>
82185222Ssam#include <unistd.h>
83185222Ssam
84185222Ssam#include "makefs.h"
85185222Ssam
86185222Ssam#include <ufs/ufs/dinode.h>
87185222Ssam#include <ufs/ufs/dir.h>
88185222Ssam#include <ufs/ffs/fs.h>
89185222Ssam
90186261Ssam#include "ffs/ufs_bswap.h"
91185222Ssam#include "ffs/ufs_inode.h"
92185222Ssam#include "ffs/newfs_extern.h"
93185222Ssam#include "ffs/ffs_extern.h"
94185222Ssam
95185222Ssam#undef DIP
96185222Ssam#define DIP(dp, field) \
97185222Ssam	((fsopts->version == 1) ? \
98185222Ssam	(dp)->ffs1_din.di_##field : (dp)->ffs2_din.di_##field)
99185222Ssam
100185222Ssam/*
101185222Ssam * Various file system defaults (cribbed from newfs(8)).
102185222Ssam */
103185222Ssam#define	DFL_FRAGSIZE		1024		/* fragment size */
104185222Ssam#define	DFL_BLKSIZE		8192		/* block size */
105185222Ssam#define	DFL_SECSIZE		512		/* sector size */
106185222Ssam#define	DFL_CYLSPERGROUP	65536		/* cylinders per group */
107185222Ssam#define	DFL_FRAGSPERINODE	4		/* fragments per inode */
108185222Ssam#define	DFL_ROTDELAY		0		/* rotational delay */
109185222Ssam#define	DFL_NRPOS		1		/* rotational positions */
110185222Ssam#define	DFL_RPM			3600		/* rpm of disk */
111185222Ssam#define	DFL_NSECTORS		64		/* # of sectors */
112185222Ssam#define	DFL_NTRACKS		16		/* # of tracks */
113185222Ssam
114185222Ssam
115185222Ssamtypedef struct {
116185222Ssam	u_char		*buf;		/* buf for directory */
117185222Ssam	doff_t		size;		/* full size of buf */
118185222Ssam	doff_t		cur;		/* offset of current entry */
119185222Ssam} dirbuf_t;
120185222Ssam
121185222Ssam
122185222Ssamstatic	int	ffs_create_image(const char *, fsinfo_t *);
123185222Ssamstatic	void	ffs_dump_fsinfo(fsinfo_t *);
124185222Ssamstatic	void	ffs_dump_dirbuf(dirbuf_t *, const char *, int);
125185222Ssamstatic	void	ffs_make_dirbuf(dirbuf_t *, const char *, fsnode *, int);
126185222Ssamstatic	int	ffs_populate_dir(const char *, fsnode *, fsinfo_t *);
127185222Ssamstatic	void	ffs_size_dir(fsnode *, fsinfo_t *);
128185222Ssamstatic	void	ffs_validate(const char *, fsnode *, fsinfo_t *);
129185222Ssamstatic	void	ffs_write_file(union dinode *, uint32_t, void *, fsinfo_t *);
130185222Ssamstatic	void	ffs_write_inode(union dinode *, uint32_t, const fsinfo_t *);
131185222Ssamstatic  void	*ffs_build_dinode1(struct ufs1_dinode *, dirbuf_t *, fsnode *,
132185222Ssam				 fsnode *, fsinfo_t *);
133185222Ssamstatic  void	*ffs_build_dinode2(struct ufs2_dinode *, dirbuf_t *, fsnode *,
134185222Ssam				 fsnode *, fsinfo_t *);
135185222Ssam
136185222Ssam
137185222Ssam
138185222Ssamint	sectorsize;		/* XXX: for buf.c::getblk() */
139185222Ssam
140185222Ssam	/* publically visible functions */
141185222Ssam
142185222Ssamint
143185222Ssamffs_parse_opts(const char *option, fsinfo_t *fsopts)
144185222Ssam{
145185222Ssam	option_t ffs_options[] = {
146185222Ssam		{ "bsize",	&fsopts->bsize,		1,	INT_MAX,
147185222Ssam					"block size" },
148185222Ssam		{ "fsize",	&fsopts->fsize,		1,	INT_MAX,
149185222Ssam					"fragment size" },
150185222Ssam		{ "density",	&fsopts->density,	1,	INT_MAX,
151185222Ssam					"bytes per inode" },
152185222Ssam		{ "minfree",	&fsopts->minfree,	0,	99,
153185222Ssam					"minfree" },
154185222Ssam		{ "maxbpf",	&fsopts->maxbpg,	1,	INT_MAX,
155185222Ssam					"max blocks per file in a cg" },
156185222Ssam		{ "avgfilesize", &fsopts->avgfilesize,	1,	INT_MAX,
157185222Ssam					"expected average file size" },
158185222Ssam		{ "avgfpdir",	&fsopts->avgfpdir,	1,	INT_MAX,
159185222Ssam					"expected # of files per directory" },
160185222Ssam		{ "extent",	&fsopts->maxbsize,	1,	INT_MAX,
161185222Ssam					"maximum # extent size" },
162185222Ssam		{ "maxbpcg",	&fsopts->maxblkspercg,	1,	INT_MAX,
163185222Ssam					"max # of blocks per group" },
164185222Ssam		{ "version",	&fsopts->version,	1,	2,
165185222Ssam					"UFS version" },
166185222Ssam		{ NULL }
167185222Ssam	};
168185222Ssam
169185222Ssam	char	*var, *val;
170185222Ssam	int	rv;
171185222Ssam
172185222Ssam	(void)&ffs_options;
173185222Ssam	assert(option != NULL);
174185222Ssam	assert(fsopts != NULL);
175185222Ssam
176185222Ssam	if (debug & DEBUG_FS_PARSE_OPTS)
177185222Ssam		printf("ffs_parse_opts: got `%s'\n", option);
178185222Ssam
179185222Ssam	if ((var = strdup(option)) == NULL)
180185222Ssam		err(1, "Allocating memory for copy of option string");
181185222Ssam	rv = 0;
182185222Ssam
183185222Ssam	if ((val = strchr(var, '=')) == NULL) {
184185222Ssam		warnx("Option `%s' doesn't contain a value", var);
185185222Ssam		goto leave_ffs_parse_opts;
186185222Ssam	}
187185222Ssam	*val++ = '\0';
188185222Ssam
189185222Ssam	if (strcmp(var, "optimization") == 0) {
190185222Ssam		if (strcmp(val, "time") == 0) {
191185222Ssam			fsopts->optimization = FS_OPTTIME;
192185222Ssam		} else if (strcmp(val, "space") == 0) {
193185222Ssam			fsopts->optimization = FS_OPTSPACE;
194185222Ssam		} else {
195185222Ssam			warnx("Invalid optimization `%s'", val);
196185222Ssam			goto leave_ffs_parse_opts;
197185222Ssam		}
198185222Ssam		rv = 1;
199185222Ssam	} else
200185222Ssam		rv = set_option(ffs_options, var, val);
201185222Ssam
202185222Ssam leave_ffs_parse_opts:
203185222Ssam	if (var)
204185222Ssam		free(var);
205185222Ssam	return (rv);
206185222Ssam}
207185222Ssam
208185222Ssam
209185222Ssamvoid
210185222Ssamffs_makefs(const char *image, const char *dir, fsnode *root, fsinfo_t *fsopts)
211185222Ssam{
212185222Ssam	struct fs	*superblock;
213185222Ssam	struct timeval	start;
214185222Ssam
215185222Ssam	assert(image != NULL);
216185222Ssam	assert(dir != NULL);
217185222Ssam	assert(root != NULL);
218185222Ssam	assert(fsopts != NULL);
219185222Ssam
220185222Ssam	if (debug & DEBUG_FS_MAKEFS)
221185222Ssam		printf("ffs_makefs: image %s directory %s root %p\n",
222185222Ssam		    image, dir, root);
223185222Ssam
224185222Ssam		/* validate tree and options */
225185222Ssam	TIMER_START(start);
226185222Ssam	ffs_validate(dir, root, fsopts);
227185222Ssam	TIMER_RESULTS(start, "ffs_validate");
228185222Ssam
229185222Ssam	printf("Calculated size of `%s': %lld bytes, %lld inodes\n",
230185222Ssam	    image, (long long)fsopts->size, (long long)fsopts->inodes);
231185222Ssam
232185222Ssam		/* create image */
233185222Ssam	TIMER_START(start);
234185222Ssam	if (ffs_create_image(image, fsopts) == -1)
235185222Ssam		errx(1, "Image file `%s' not created.", image);
236185222Ssam	TIMER_RESULTS(start, "ffs_create_image");
237185222Ssam
238185222Ssam	fsopts->curinode = ROOTINO;
239185222Ssam
240185222Ssam	if (debug & DEBUG_FS_MAKEFS)
241185222Ssam		putchar('\n');
242185222Ssam
243185222Ssam		/* populate image */
244185222Ssam	printf("Populating `%s'\n", image);
245185222Ssam	TIMER_START(start);
246185222Ssam	if (! ffs_populate_dir(dir, root, fsopts))
247185222Ssam		errx(1, "Image file `%s' not populated.", image);
248185222Ssam	TIMER_RESULTS(start, "ffs_populate_dir");
249185222Ssam
250185222Ssam		/* ensure no outstanding buffers remain */
251185222Ssam	if (debug & DEBUG_FS_MAKEFS)
252185222Ssam		bcleanup();
253185222Ssam
254185222Ssam		/* update various superblock parameters */
255185222Ssam	superblock = fsopts->superblock;
256185222Ssam	superblock->fs_fmod = 0;
257185222Ssam	superblock->fs_old_cstotal.cs_ndir   = superblock->fs_cstotal.cs_ndir;
258185222Ssam	superblock->fs_old_cstotal.cs_nbfree = superblock->fs_cstotal.cs_nbfree;
259185222Ssam	superblock->fs_old_cstotal.cs_nifree = superblock->fs_cstotal.cs_nifree;
260185222Ssam	superblock->fs_old_cstotal.cs_nffree = superblock->fs_cstotal.cs_nffree;
261185222Ssam
262185222Ssam		/* write out superblock; image is now complete */
263185222Ssam	ffs_write_superblock(fsopts->superblock, fsopts);
264185222Ssam	if (close(fsopts->fd) == -1)
265185222Ssam		err(1, "Closing `%s'", image);
266185222Ssam	fsopts->fd = -1;
267185222Ssam	printf("Image `%s' complete\n", image);
268185222Ssam}
269185222Ssam
270185222Ssam	/* end of public functions */
271185222Ssam
272185222Ssam
273185222Ssamstatic void
274185222Ssamffs_validate(const char *dir, fsnode *root, fsinfo_t *fsopts)
275185222Ssam{
276185222Ssam	int32_t	ncg = 1;
277185222Ssam#if notyet
278185222Ssam	int32_t	spc, nspf, ncyl, fssize;
279185222Ssam#endif
280186265Ssam	off_t size;
281185222Ssam
282185222Ssam	assert(dir != NULL);
283185222Ssam	assert(root != NULL);
284185222Ssam	assert(fsopts != NULL);
285185222Ssam
286185222Ssam	if (debug & DEBUG_FS_VALIDATE) {
287185222Ssam		printf("ffs_validate: before defaults set:\n");
288185222Ssam		ffs_dump_fsinfo(fsopts);
289185222Ssam	}
290185222Ssam
291185222Ssam		/* set FFS defaults */
292185222Ssam	if (fsopts->sectorsize == -1)
293185222Ssam		fsopts->sectorsize = DFL_SECSIZE;
294185222Ssam	if (fsopts->fsize == -1)
295185222Ssam		fsopts->fsize = MAX(DFL_FRAGSIZE, fsopts->sectorsize);
296185222Ssam	if (fsopts->bsize == -1)
297185222Ssam		fsopts->bsize = MIN(DFL_BLKSIZE, 8 * fsopts->fsize);
298185222Ssam	if (fsopts->cpg == -1)
299185222Ssam		fsopts->cpg = DFL_CYLSPERGROUP;
300185222Ssam	else
301185222Ssam		fsopts->cpgflg = 1;
302185222Ssam				/* fsopts->density is set below */
303185222Ssam	if (fsopts->nsectors == -1)
304185222Ssam		fsopts->nsectors = DFL_NSECTORS;
305185222Ssam	if (fsopts->minfree == -1)
306185222Ssam		fsopts->minfree = MINFREE;
307185222Ssam	if (fsopts->optimization == -1)
308185222Ssam		fsopts->optimization = DEFAULTOPT;
309185222Ssam	if (fsopts->maxcontig == -1)
310185222Ssam		fsopts->maxcontig =
311185222Ssam		    MAX(1, MIN(MAXPHYS, FFS_MAXBSIZE) / fsopts->bsize);
312185222Ssam	/* XXX ondisk32 */
313185222Ssam	if (fsopts->maxbpg == -1)
314185222Ssam		fsopts->maxbpg = fsopts->bsize / sizeof(int32_t);
315185222Ssam	if (fsopts->avgfilesize == -1)
316185222Ssam		fsopts->avgfilesize = AVFILESIZ;
317185222Ssam	if (fsopts->avgfpdir == -1)
318185222Ssam		fsopts->avgfpdir = AFPDIR;
319185222Ssam
320185222Ssam		/* calculate size of tree */
321185222Ssam	ffs_size_dir(root, fsopts);
322185222Ssam	fsopts->inodes += ROOTINO;		/* include first two inodes */
323185222Ssam
324185222Ssam	if (debug & DEBUG_FS_VALIDATE)
325185222Ssam		printf("ffs_validate: size of tree: %lld bytes, %lld inodes\n",
326185222Ssam		    (long long)fsopts->size, (long long)fsopts->inodes);
327185222Ssam
328185222Ssam		/* add requested slop */
329185222Ssam	fsopts->size += fsopts->freeblocks;
330185222Ssam	fsopts->inodes += fsopts->freefiles;
331185222Ssam	if (fsopts->freefilepc > 0)
332185222Ssam		fsopts->inodes =
333185222Ssam		    fsopts->inodes * (100 + fsopts->freefilepc) / 100;
334185222Ssam	if (fsopts->freeblockpc > 0)
335185222Ssam		fsopts->size =
336185222Ssam		    fsopts->size * (100 + fsopts->freeblockpc) / 100;
337185222Ssam
338185222Ssam		/* add space needed for superblocks */
339185222Ssam	/*
340185222Ssam	 * The old SBOFF (SBLOCK_UFS1) is used here because makefs is
341185222Ssam	 * typically used for small filesystems where space matters.
342185222Ssam	 * XXX make this an option.
343185222Ssam	 */
344185222Ssam	fsopts->size += (SBLOCK_UFS1 + SBLOCKSIZE) * ncg;
345185222Ssam		/* add space needed to store inodes, x3 for blockmaps, etc */
346185222Ssam	if (fsopts->version == 1)
347185222Ssam		fsopts->size += ncg * DINODE1_SIZE *
348185222Ssam		    roundup(fsopts->inodes / ncg, fsopts->bsize / DINODE1_SIZE);
349185222Ssam	else
350185222Ssam		fsopts->size += ncg * DINODE2_SIZE *
351185222Ssam		    roundup(fsopts->inodes / ncg, fsopts->bsize / DINODE2_SIZE);
352185222Ssam
353185222Ssam		/* add minfree */
354185222Ssam	if (fsopts->minfree > 0)
355185222Ssam		fsopts->size =
356185222Ssam		    fsopts->size * (100 + fsopts->minfree) / 100;
357185222Ssam	/*
358185222Ssam	 * XXX	any other fs slop to add, such as csum's, bitmaps, etc ??
359185222Ssam	 */
360185222Ssam
361185222Ssam	if (fsopts->size < fsopts->minsize)	/* ensure meets minimum size */
362185222Ssam		fsopts->size = fsopts->minsize;
363185222Ssam
364185222Ssam		/* round up to the next block */
365186265Ssam	size = roundup(fsopts->size, fsopts->bsize);
366185222Ssam
367186265Ssam		/* now check calculated sizes vs requested sizes */
368186265Ssam	if (fsopts->maxsize > 0 && size > fsopts->maxsize) {
369186272Ssam		if (debug & DEBUG_FS_VALIDATE) {
370186272Ssam			printf("%s: `%s' size of %lld is larger than the "
371186272Ssam			    "maxsize of %lld; rounding down to %lld.",
372186272Ssam			    __func__, dir, (long long)size,
373186272Ssam			    (long long)fsopts->maxsize,
374186272Ssam			    rounddown(fsopts->size, fsopts->bsize));
375186272Ssam		}
376186265Ssam		size = rounddown(fsopts->size, fsopts->bsize);
377186265Ssam	}
378186265Ssam	fsopts->size = size;
379186265Ssam
380185222Ssam		/* calculate density if necessary */
381185222Ssam	if (fsopts->density == -1)
382185222Ssam		fsopts->density = fsopts->size / fsopts->inodes + 1;
383185222Ssam
384185222Ssam	if (debug & DEBUG_FS_VALIDATE) {
385185222Ssam		printf("ffs_validate: after defaults set:\n");
386185222Ssam		ffs_dump_fsinfo(fsopts);
387185222Ssam		printf("ffs_validate: dir %s; %lld bytes, %lld inodes\n",
388185222Ssam		    dir, (long long)fsopts->size, (long long)fsopts->inodes);
389185222Ssam	}
390185222Ssam	sectorsize = fsopts->sectorsize;	/* XXX - see earlier */
391185222Ssam}
392185222Ssam
393185222Ssam
394185222Ssamstatic void
395185222Ssamffs_dump_fsinfo(fsinfo_t *f)
396185222Ssam{
397185222Ssam
398185222Ssam	printf("fsopts at %p\n", f);
399185222Ssam
400185222Ssam	printf("\tsize %lld, inodes %lld, curinode %u\n",
401185222Ssam	    (long long)f->size, (long long)f->inodes, f->curinode);
402185222Ssam
403185222Ssam	printf("\tminsize %lld, maxsize %lld\n",
404185222Ssam	    (long long)f->minsize, (long long)f->maxsize);
405185222Ssam	printf("\tfree files %lld, freefile %% %d\n",
406185222Ssam	    (long long)f->freefiles, f->freefilepc);
407185222Ssam	printf("\tfree blocks %lld, freeblock %% %d\n",
408185222Ssam	    (long long)f->freeblocks, f->freeblockpc);
409185222Ssam	printf("\tneedswap %d, sectorsize %d\n", f->needswap, f->sectorsize);
410185222Ssam
411185222Ssam	printf("\tbsize %d, fsize %d, cpg %d, density %d\n",
412185222Ssam	    f->bsize, f->fsize, f->cpg, f->density);
413185222Ssam	printf("\tnsectors %d, rpm %d, minfree %d\n",
414185222Ssam	    f->nsectors, f->rpm, f->minfree);
415185222Ssam	printf("\tmaxcontig %d, maxbpg %d\n",
416185222Ssam	    f->maxcontig, f->maxbpg);
417185222Ssam	printf("\toptimization %s\n",
418185222Ssam	    f->optimization == FS_OPTSPACE ? "space" : "time");
419185222Ssam}
420185222Ssam
421185222Ssam
422185222Ssamstatic int
423185222Ssamffs_create_image(const char *image, fsinfo_t *fsopts)
424185222Ssam{
425185222Ssam#if HAVE_STRUCT_STATVFS_F_IOSIZE
426185222Ssam	struct statvfs	sfs;
427185222Ssam#endif
428185222Ssam	struct fs	*fs;
429185222Ssam	char	*buf;
430185222Ssam	int	i, bufsize;
431185222Ssam	off_t	bufrem;
432185222Ssam
433185222Ssam	assert (image != NULL);
434185222Ssam	assert (fsopts != NULL);
435185222Ssam
436185222Ssam		/* create image */
437185222Ssam	if ((fsopts->fd = open(image, O_RDWR | O_CREAT | O_TRUNC, 0777))
438185222Ssam	    == -1) {
439185222Ssam		warn("Can't open `%s' for writing", image);
440185222Ssam		return (-1);
441185222Ssam	}
442185222Ssam
443185222Ssam		/* zero image */
444185222Ssam#if HAVE_STRUCT_STATVFS_F_IOSIZE
445185222Ssam	if (fstatvfs(fsopts->fd, &sfs) == -1) {
446185222Ssam#endif
447185222Ssam		bufsize = 8192;
448185222Ssam#if HAVE_STRUCT_STATVFS_F_IOSIZE
449185222Ssam		warn("can't fstatvfs `%s', using default %d byte chunk",
450185222Ssam		    image, bufsize);
451185222Ssam	} else
452185222Ssam		bufsize = sfs.f_iosize;
453185222Ssam#endif
454185222Ssam	bufrem = fsopts->size;
455185222Ssam	if (debug & DEBUG_FS_CREATE_IMAGE)
456185222Ssam		printf(
457185222Ssam		    "zero-ing image `%s', %lld sectors, using %d byte chunks\n",
458185222Ssam		    image, (long long)bufrem, bufsize);
459185222Ssam	if ((buf = calloc(1, bufsize)) == NULL) {
460185222Ssam		warn("Can't create buffer for sector");
461185222Ssam		return (-1);
462185222Ssam	}
463185222Ssam	while (bufrem > 0) {
464185222Ssam		i = write(fsopts->fd, buf, MIN(bufsize, bufrem));
465185222Ssam		if (i == -1) {
466185222Ssam			warn("zeroing image, %lld bytes to go",
467185222Ssam			    (long long)bufrem);
468185222Ssam			return (-1);
469185222Ssam		}
470185222Ssam		bufrem -= i;
471185222Ssam	}
472185222Ssam
473185222Ssam		/* make the file system */
474185222Ssam	if (debug & DEBUG_FS_CREATE_IMAGE)
475185222Ssam		printf("calling mkfs(\"%s\", ...)\n", image);
476185222Ssam	fs = ffs_mkfs(image, fsopts);
477185222Ssam	fsopts->superblock = (void *)fs;
478185222Ssam	if (debug & DEBUG_FS_CREATE_IMAGE) {
479185222Ssam		time_t t;
480185222Ssam
481185222Ssam		t = (time_t)((struct fs *)fsopts->superblock)->fs_time;
482185222Ssam		printf("mkfs returned %p; fs_time %s",
483185222Ssam		    fsopts->superblock, ctime(&t));
484185222Ssam		printf("fs totals: nbfree %lld, nffree %lld, nifree %lld, ndir %lld\n",
485185222Ssam		    (long long)fs->fs_cstotal.cs_nbfree,
486185222Ssam		    (long long)fs->fs_cstotal.cs_nffree,
487185222Ssam		    (long long)fs->fs_cstotal.cs_nifree,
488185222Ssam		    (long long)fs->fs_cstotal.cs_ndir);
489185222Ssam	}
490185222Ssam
491185222Ssam	if (fs->fs_cstotal.cs_nifree + ROOTINO < fsopts->inodes) {
492185222Ssam		warnx(
493185222Ssam		"Image file `%s' has %lld free inodes; %lld are required.",
494185222Ssam		    image,
495185222Ssam		    (long long)fs->fs_cstotal.cs_nifree + ROOTINO,
496185222Ssam		    (long long)fsopts->inodes);
497185222Ssam		return (-1);
498185222Ssam	}
499185222Ssam	return (fsopts->fd);
500185222Ssam}
501185222Ssam
502185222Ssam
503185222Ssamstatic void
504185222Ssamffs_size_dir(fsnode *root, fsinfo_t *fsopts)
505185222Ssam{
506185222Ssam	struct direct	tmpdir;
507185222Ssam	fsnode *	node;
508185222Ssam	int		curdirsize, this;
509185222Ssam
510185222Ssam	/* node may be NULL (empty directory) */
511185222Ssam	assert(fsopts != NULL);
512185222Ssam
513185222Ssam	if (debug & DEBUG_FS_SIZE_DIR)
514185222Ssam		printf("ffs_size_dir: entry: bytes %lld inodes %lld\n",
515185222Ssam		    (long long)fsopts->size, (long long)fsopts->inodes);
516185222Ssam
517185222Ssam#define	ADDDIRENT(e) do {						\
518185222Ssam	tmpdir.d_namlen = strlen((e));					\
519186261Ssam	this = DIRSIZ_SWAP(0, &tmpdir, 0);				\
520185222Ssam	if (debug & DEBUG_FS_SIZE_DIR_ADD_DIRENT)			\
521185222Ssam		printf("ADDDIRENT: was: %s (%d) this %d cur %d\n",	\
522185222Ssam		    e, tmpdir.d_namlen, this, curdirsize);		\
523185222Ssam	if (this + curdirsize > roundup(curdirsize, DIRBLKSIZ))		\
524185222Ssam		curdirsize = roundup(curdirsize, DIRBLKSIZ);		\
525185222Ssam	curdirsize += this;						\
526185222Ssam	if (debug & DEBUG_FS_SIZE_DIR_ADD_DIRENT)			\
527185222Ssam		printf("ADDDIRENT: now: %s (%d) this %d cur %d\n",	\
528185222Ssam		    e, tmpdir.d_namlen, this, curdirsize);		\
529185222Ssam} while (0);
530185222Ssam
531185222Ssam	/*
532185222Ssam	 * XXX	this needs to take into account extra space consumed
533185222Ssam	 *	by indirect blocks, etc.
534185222Ssam	 */
535185222Ssam#define	ADDSIZE(x) do {							\
536185222Ssam	fsopts->size += roundup((x), fsopts->fsize);			\
537185222Ssam} while (0);
538185222Ssam
539185222Ssam	curdirsize = 0;
540185222Ssam	for (node = root; node != NULL; node = node->next) {
541185222Ssam		ADDDIRENT(node->name);
542185222Ssam		if (FSNODE_EXCLUDE_P(fsopts, node))
543185222Ssam			continue;
544185222Ssam		if (node == root) {			/* we're at "." */
545185222Ssam			assert(strcmp(node->name, ".") == 0);
546185222Ssam			ADDDIRENT("..");
547185222Ssam		} else if ((node->inode->flags & FI_SIZED) == 0) {
548185222Ssam				/* don't count duplicate names */
549185222Ssam			node->inode->flags |= FI_SIZED;
550185222Ssam			if (debug & DEBUG_FS_SIZE_DIR_NODE)
551185222Ssam				printf("ffs_size_dir: `%s' size %lld\n",
552185222Ssam				    node->name,
553185222Ssam				    (long long)node->inode->st.st_size);
554185222Ssam			fsopts->inodes++;
555185222Ssam			if (node->type == S_IFREG)
556185222Ssam				ADDSIZE(node->inode->st.st_size);
557185222Ssam			if (node->type == S_IFLNK) {
558185222Ssam				int	slen;
559185222Ssam
560185222Ssam				slen = strlen(node->symlink) + 1;
561185222Ssam				if (slen >= (fsopts->version == 1 ?
562185222Ssam						MAXSYMLINKLEN_UFS1 :
563185222Ssam						MAXSYMLINKLEN_UFS2))
564185222Ssam					ADDSIZE(slen);
565185222Ssam			}
566185222Ssam		}
567185222Ssam		if (node->type == S_IFDIR)
568185222Ssam			ffs_size_dir(node->child, fsopts);
569185222Ssam	}
570185222Ssam	ADDSIZE(curdirsize);
571185222Ssam
572185222Ssam	if (debug & DEBUG_FS_SIZE_DIR)
573185222Ssam		printf("ffs_size_dir: exit: size %lld inodes %lld\n",
574185222Ssam		    (long long)fsopts->size, (long long)fsopts->inodes);
575185222Ssam}
576185222Ssam
577185222Ssamstatic void *
578185222Ssamffs_build_dinode1(struct ufs1_dinode *dinp, dirbuf_t *dbufp, fsnode *cur,
579185222Ssam		 fsnode *root, fsinfo_t *fsopts)
580185222Ssam{
581185222Ssam	int slen;
582185222Ssam	void *membuf;
583185222Ssam
584185222Ssam	memset(dinp, 0, sizeof(*dinp));
585185222Ssam	dinp->di_mode = cur->inode->st.st_mode;
586185222Ssam	dinp->di_nlink = cur->inode->nlink;
587185222Ssam	dinp->di_size = cur->inode->st.st_size;
588185222Ssam	dinp->di_atime = cur->inode->st.st_atime;
589185222Ssam	dinp->di_mtime = cur->inode->st.st_mtime;
590185222Ssam	dinp->di_ctime = cur->inode->st.st_ctime;
591185222Ssam#if HAVE_STRUCT_STAT_ST_MTIMENSEC
592185222Ssam	dinp->di_atimensec = cur->inode->st.st_atimensec;
593185222Ssam	dinp->di_mtimensec = cur->inode->st.st_mtimensec;
594185222Ssam	dinp->di_ctimensec = cur->inode->st.st_ctimensec;
595185222Ssam#endif
596185222Ssam#if HAVE_STRUCT_STAT_ST_FLAGS
597185222Ssam	dinp->di_flags = cur->inode->st.st_flags;
598185222Ssam#endif
599185222Ssam#if HAVE_STRUCT_STAT_ST_GEN
600185222Ssam	dinp->di_gen = cur->inode->st.st_gen;
601185222Ssam#endif
602185222Ssam	dinp->di_uid = cur->inode->st.st_uid;
603185222Ssam	dinp->di_gid = cur->inode->st.st_gid;
604185222Ssam		/* not set: di_db, di_ib, di_blocks, di_spare */
605185222Ssam
606185222Ssam	membuf = NULL;
607185222Ssam	if (cur == root) {			/* "."; write dirbuf */
608185222Ssam		membuf = dbufp->buf;
609185222Ssam		dinp->di_size = dbufp->size;
610185222Ssam	} else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) {
611185222Ssam		dinp->di_size = 0;	/* a device */
612185222Ssam		dinp->di_rdev =
613185222Ssam		    ufs_rw32(cur->inode->st.st_rdev, fsopts->needswap);
614185222Ssam	} else if (S_ISLNK(cur->type)) {	/* symlink */
615185222Ssam		slen = strlen(cur->symlink);
616185222Ssam		if (slen < MAXSYMLINKLEN_UFS1) {	/* short link */
617185222Ssam			memcpy(dinp->di_db, cur->symlink, slen);
618185222Ssam		} else
619185222Ssam			membuf = cur->symlink;
620185222Ssam		dinp->di_size = slen;
621185222Ssam	}
622185222Ssam	return membuf;
623185222Ssam}
624185222Ssam
625185222Ssamstatic void *
626185222Ssamffs_build_dinode2(struct ufs2_dinode *dinp, dirbuf_t *dbufp, fsnode *cur,
627185222Ssam		 fsnode *root, fsinfo_t *fsopts)
628185222Ssam{
629185222Ssam	int slen;
630185222Ssam	void *membuf;
631185222Ssam
632185222Ssam	memset(dinp, 0, sizeof(*dinp));
633185222Ssam	dinp->di_mode = cur->inode->st.st_mode;
634185222Ssam	dinp->di_nlink = cur->inode->nlink;
635185222Ssam	dinp->di_size = cur->inode->st.st_size;
636185222Ssam	dinp->di_atime = cur->inode->st.st_atime;
637185222Ssam	dinp->di_mtime = cur->inode->st.st_mtime;
638185222Ssam	dinp->di_ctime = cur->inode->st.st_ctime;
639185222Ssam#if HAVE_STRUCT_STAT_ST_MTIMENSEC
640185222Ssam	dinp->di_atimensec = cur->inode->st.st_atimensec;
641185222Ssam	dinp->di_mtimensec = cur->inode->st.st_mtimensec;
642185222Ssam	dinp->di_ctimensec = cur->inode->st.st_ctimensec;
643185222Ssam#endif
644185222Ssam#if HAVE_STRUCT_STAT_ST_FLAGS
645185222Ssam	dinp->di_flags = cur->inode->st.st_flags;
646185222Ssam#endif
647185222Ssam#if HAVE_STRUCT_STAT_ST_GEN
648185222Ssam	dinp->di_gen = cur->inode->st.st_gen;
649185222Ssam#endif
650185222Ssam#if HAVE_STRUCT_STAT_BIRTHTIME
651185222Ssam	dinp->di_birthtime = cur->inode->st.st_birthtime;
652185222Ssam	dinp->di_birthnsec = cur->inode->st.st_birthtimensec;
653185222Ssam#endif
654185222Ssam	dinp->di_uid = cur->inode->st.st_uid;
655185222Ssam	dinp->di_gid = cur->inode->st.st_gid;
656185222Ssam		/* not set: di_db, di_ib, di_blocks, di_spare */
657185222Ssam
658185222Ssam	membuf = NULL;
659185222Ssam	if (cur == root) {			/* "."; write dirbuf */
660185222Ssam		membuf = dbufp->buf;
661185222Ssam		dinp->di_size = dbufp->size;
662185222Ssam	} else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) {
663185222Ssam		dinp->di_size = 0;	/* a device */
664185222Ssam		dinp->di_rdev =
665185222Ssam		    ufs_rw64(cur->inode->st.st_rdev, fsopts->needswap);
666185222Ssam	} else if (S_ISLNK(cur->type)) {	/* symlink */
667185222Ssam		slen = strlen(cur->symlink);
668185222Ssam		if (slen < MAXSYMLINKLEN_UFS2) {	/* short link */
669185222Ssam			memcpy(dinp->di_db, cur->symlink, slen);
670185222Ssam		} else
671185222Ssam			membuf = cur->symlink;
672185222Ssam		dinp->di_size = slen;
673185222Ssam	}
674185222Ssam	return membuf;
675185222Ssam}
676185222Ssam
677185222Ssamstatic int
678185222Ssamffs_populate_dir(const char *dir, fsnode *root, fsinfo_t *fsopts)
679185222Ssam{
680185222Ssam	fsnode		*cur;
681185222Ssam	dirbuf_t	dirbuf;
682185222Ssam	union dinode	din;
683185222Ssam	void		*membuf;
684185222Ssam	char		path[MAXPATHLEN + 1];
685185222Ssam
686185222Ssam	assert(dir != NULL);
687185222Ssam	assert(root != NULL);
688185222Ssam	assert(fsopts != NULL);
689185222Ssam
690185222Ssam	(void)memset(&dirbuf, 0, sizeof(dirbuf));
691185222Ssam
692185222Ssam	if (debug & DEBUG_FS_POPULATE)
693185222Ssam		printf("ffs_populate_dir: PASS 1  dir %s node %p\n", dir, root);
694185222Ssam
695185222Ssam		/*
696185222Ssam		 * pass 1: allocate inode numbers, build directory `file'
697185222Ssam		 */
698185222Ssam	for (cur = root; cur != NULL; cur = cur->next) {
699185222Ssam		if (FSNODE_EXCLUDE_P(fsopts, cur))
700185222Ssam			continue;
701185222Ssam		if ((cur->inode->flags & FI_ALLOCATED) == 0) {
702185222Ssam			cur->inode->flags |= FI_ALLOCATED;
703185222Ssam			if (cur == root && cur->parent != NULL)
704185222Ssam				cur->inode->ino = cur->parent->inode->ino;
705185222Ssam			else {
706185222Ssam				cur->inode->ino = fsopts->curinode;
707185222Ssam				fsopts->curinode++;
708185222Ssam			}
709185222Ssam		}
710185222Ssam		ffs_make_dirbuf(&dirbuf, cur->name, cur, fsopts->needswap);
711185222Ssam		if (cur == root) {		/* we're at "."; add ".." */
712185222Ssam			ffs_make_dirbuf(&dirbuf, "..",
713185222Ssam			    cur->parent == NULL ? cur : cur->parent->first,
714185222Ssam			    fsopts->needswap);
715185222Ssam			root->inode->nlink++;	/* count my parent's link */
716185222Ssam		} else if (cur->child != NULL)
717185222Ssam			root->inode->nlink++;	/* count my child's link */
718185222Ssam
719185222Ssam		/*
720185222Ssam		 * XXX	possibly write file and long symlinks here,
721185222Ssam		 *	ensuring that blocks get written before inodes?
722185222Ssam		 *	otoh, this isn't a real filesystem, so who
723185222Ssam		 *	cares about ordering? :-)
724185222Ssam		 */
725185222Ssam	}
726185222Ssam	if (debug & DEBUG_FS_POPULATE_DIRBUF)
727185222Ssam		ffs_dump_dirbuf(&dirbuf, dir, fsopts->needswap);
728185222Ssam
729185222Ssam		/*
730185222Ssam		 * pass 2: write out dirbuf, then non-directories at this level
731185222Ssam		 */
732185222Ssam	if (debug & DEBUG_FS_POPULATE)
733185222Ssam		printf("ffs_populate_dir: PASS 2  dir %s\n", dir);
734185222Ssam	for (cur = root; cur != NULL; cur = cur->next) {
735185222Ssam		if (FSNODE_EXCLUDE_P(fsopts, cur))
736185222Ssam			continue;
737185222Ssam		if (cur->inode->flags & FI_WRITTEN)
738185222Ssam			continue;		/* skip hard-linked entries */
739185222Ssam		cur->inode->flags |= FI_WRITTEN;
740185222Ssam
741185222Ssam		if (snprintf(path, sizeof(path), "%s/%s", dir, cur->name)
742185222Ssam		    >= sizeof(path))
743185222Ssam			errx(1, "Pathname too long.");
744185222Ssam
745185222Ssam		if (cur->child != NULL)
746185222Ssam			continue;		/* child creates own inode */
747185222Ssam
748185222Ssam				/* build on-disk inode */
749185222Ssam		if (fsopts->version == 1)
750185222Ssam			membuf = ffs_build_dinode1(&din.ffs1_din, &dirbuf, cur,
751185222Ssam			    root, fsopts);
752185222Ssam		else
753185222Ssam			membuf = ffs_build_dinode2(&din.ffs2_din, &dirbuf, cur,
754185222Ssam			    root, fsopts);
755185222Ssam
756185222Ssam		if (debug & DEBUG_FS_POPULATE_NODE) {
757185222Ssam			printf("ffs_populate_dir: writing ino %d, %s",
758185222Ssam			    cur->inode->ino, inode_type(cur->type));
759185222Ssam			if (cur->inode->nlink > 1)
760185222Ssam				printf(", nlink %d", cur->inode->nlink);
761185222Ssam			putchar('\n');
762185222Ssam		}
763185222Ssam
764185222Ssam		if (membuf != NULL) {
765185222Ssam			ffs_write_file(&din, cur->inode->ino, membuf, fsopts);
766185222Ssam		} else if (S_ISREG(cur->type)) {
767185222Ssam			ffs_write_file(&din, cur->inode->ino, path, fsopts);
768185222Ssam		} else {
769185222Ssam			assert (! S_ISDIR(cur->type));
770185222Ssam			ffs_write_inode(&din, cur->inode->ino, fsopts);
771185222Ssam		}
772185222Ssam	}
773185222Ssam
774185222Ssam		/*
775185222Ssam		 * pass 3: write out sub-directories
776185222Ssam		 */
777185222Ssam	if (debug & DEBUG_FS_POPULATE)
778185222Ssam		printf("ffs_populate_dir: PASS 3  dir %s\n", dir);
779185222Ssam	for (cur = root; cur != NULL; cur = cur->next) {
780185222Ssam		if (FSNODE_EXCLUDE_P(fsopts, cur))
781185222Ssam			continue;
782185222Ssam		if (cur->child == NULL)
783185222Ssam			continue;
784185222Ssam		if (snprintf(path, sizeof(path), "%s/%s", dir, cur->name)
785185222Ssam		    >= sizeof(path))
786185222Ssam			errx(1, "Pathname too long.");
787185222Ssam		if (! ffs_populate_dir(path, cur->child, fsopts))
788185222Ssam			return (0);
789185222Ssam	}
790185222Ssam
791185222Ssam	if (debug & DEBUG_FS_POPULATE)
792185222Ssam		printf("ffs_populate_dir: DONE dir %s\n", dir);
793185222Ssam
794185222Ssam		/* cleanup */
795185222Ssam	if (dirbuf.buf != NULL)
796185222Ssam		free(dirbuf.buf);
797185222Ssam	return (1);
798185222Ssam}
799185222Ssam
800185222Ssam
801185222Ssamstatic void
802185222Ssamffs_write_file(union dinode *din, uint32_t ino, void *buf, fsinfo_t *fsopts)
803185222Ssam{
804185222Ssam	int 	isfile, ffd;
805185222Ssam	char	*fbuf, *p;
806185222Ssam	off_t	bufleft, chunk, offset;
807185222Ssam	struct inode	in;
808185222Ssam	struct buf *	bp;
809185222Ssam
810185222Ssam	assert (din != NULL);
811185222Ssam	assert (buf != NULL);
812185222Ssam	assert (fsopts != NULL);
813185222Ssam
814185222Ssam	isfile = S_ISREG(DIP(din, mode));
815185222Ssam	fbuf = NULL;
816185222Ssam	ffd = -1;
817185222Ssam
818185222Ssam	in.i_fs = (struct fs *)fsopts->superblock;
819185222Ssam
820185222Ssam	if (debug & DEBUG_FS_WRITE_FILE) {
821185222Ssam		printf(
822185222Ssam		    "ffs_write_file: ino %u, din %p, isfile %d, %s, size %lld",
823185222Ssam		    ino, din, isfile, inode_type(DIP(din, mode) & S_IFMT),
824185222Ssam		    (long long)DIP(din, size));
825185222Ssam		if (isfile)
826185222Ssam			printf(", file '%s'\n", (char *)buf);
827185222Ssam		else
828185222Ssam			printf(", buffer %p\n", buf);
829185222Ssam	}
830185222Ssam
831185222Ssam	in.i_number = ino;
832185222Ssam	in.i_size = DIP(din, size);
833185222Ssam	if (fsopts->version == 1)
834185222Ssam		memcpy(&in.i_din.ffs1_din, &din->ffs1_din,
835185222Ssam		    sizeof(in.i_din.ffs1_din));
836185222Ssam	else
837185222Ssam		memcpy(&in.i_din.ffs2_din, &din->ffs2_din,
838185222Ssam		    sizeof(in.i_din.ffs2_din));
839185222Ssam	in.i_fd = fsopts->fd;
840185222Ssam
841185222Ssam	if (DIP(din, size) == 0)
842185222Ssam		goto write_inode_and_leave;		/* mmm, cheating */
843185222Ssam
844185222Ssam	if (isfile) {
845185222Ssam		if ((fbuf = malloc(fsopts->bsize)) == NULL)
846185222Ssam			err(1, "Allocating memory for write buffer");
847185222Ssam		if ((ffd = open((char *)buf, O_RDONLY, 0444)) == -1) {
848185222Ssam			warn("Can't open `%s' for reading", (char *)buf);
849185222Ssam			goto leave_ffs_write_file;
850185222Ssam		}
851185222Ssam	} else {
852185222Ssam		p = buf;
853185222Ssam	}
854185222Ssam
855185222Ssam	chunk = 0;
856185222Ssam	for (bufleft = DIP(din, size); bufleft > 0; bufleft -= chunk) {
857185222Ssam		chunk = MIN(bufleft, fsopts->bsize);
858185222Ssam		if (isfile) {
859185222Ssam			if (read(ffd, fbuf, chunk) != chunk)
860185222Ssam				err(1, "Reading `%s', %lld bytes to go",
861185222Ssam				    (char *)buf, (long long)bufleft);
862185222Ssam			p = fbuf;
863185222Ssam		}
864185222Ssam		offset = DIP(din, size) - bufleft;
865185222Ssam		if (debug & DEBUG_FS_WRITE_FILE_BLOCK)
866185222Ssam			printf(
867185222Ssam		"ffs_write_file: write %p offset %lld size %lld left %lld\n",
868185222Ssam			    p, (long long)offset,
869185222Ssam			    (long long)chunk, (long long)bufleft);
870185222Ssam	/*
871185222Ssam	 * XXX	if holey support is desired, do the check here
872185222Ssam	 *
873185222Ssam	 * XXX	might need to write out last bit in fragroundup
874185222Ssam	 *	sized chunk. however, ffs_balloc() handles this for us
875185222Ssam	 */
876185222Ssam		errno = ffs_balloc(&in, offset, chunk, &bp);
877185222Ssam bad_ffs_write_file:
878185222Ssam		if (errno != 0)
879185222Ssam			err(1,
880185222Ssam			    "Writing inode %d (%s), bytes %lld + %lld",
881185222Ssam			    ino,
882185222Ssam			    isfile ? (char *)buf :
883185222Ssam			      inode_type(DIP(din, mode) & S_IFMT),
884185222Ssam			    (long long)offset, (long long)chunk);
885185222Ssam		memcpy(bp->b_data, p, chunk);
886185222Ssam		errno = bwrite(bp);
887185222Ssam		if (errno != 0)
888185222Ssam			goto bad_ffs_write_file;
889185222Ssam		brelse(bp);
890185222Ssam		if (!isfile)
891185222Ssam			p += chunk;
892185222Ssam	}
893185222Ssam
894185222Ssam write_inode_and_leave:
895185222Ssam	ffs_write_inode(&in.i_din, in.i_number, fsopts);
896185222Ssam
897185222Ssam leave_ffs_write_file:
898185222Ssam	if (fbuf)
899185222Ssam		free(fbuf);
900185222Ssam	if (ffd != -1)
901185222Ssam		close(ffd);
902185222Ssam}
903185222Ssam
904185222Ssam
905185222Ssamstatic void
906185222Ssamffs_dump_dirbuf(dirbuf_t *dbuf, const char *dir, int needswap)
907185222Ssam{
908185222Ssam	doff_t		i;
909185222Ssam	struct direct	*de;
910185222Ssam	uint16_t	reclen;
911185222Ssam
912185222Ssam	assert (dbuf != NULL);
913185222Ssam	assert (dir != NULL);
914185222Ssam	printf("ffs_dump_dirbuf: dir %s size %d cur %d\n",
915185222Ssam	    dir, dbuf->size, dbuf->cur);
916185222Ssam
917185222Ssam	for (i = 0; i < dbuf->size; ) {
918185222Ssam		de = (struct direct *)(dbuf->buf + i);
919185222Ssam		reclen = ufs_rw16(de->d_reclen, needswap);
920185222Ssam		printf(
921185222Ssam	    " inode %4d %7s offset %4d reclen %3d namlen %3d name %s\n",
922185222Ssam		    ufs_rw32(de->d_ino, needswap),
923185222Ssam		    inode_type(DTTOIF(de->d_type)), i, reclen,
924185222Ssam		    de->d_namlen, de->d_name);
925185222Ssam		i += reclen;
926185222Ssam		assert(reclen > 0);
927185222Ssam	}
928185222Ssam}
929185222Ssam
930185222Ssamstatic void
931185222Ssamffs_make_dirbuf(dirbuf_t *dbuf, const char *name, fsnode *node, int needswap)
932185222Ssam{
933185222Ssam	struct direct	de, *dp;
934185222Ssam	uint16_t	llen, reclen;
935185222Ssam	char		*newbuf;
936185222Ssam
937185222Ssam	assert (dbuf != NULL);
938185222Ssam	assert (name != NULL);
939185222Ssam	assert (node != NULL);
940185222Ssam					/* create direct entry */
941185222Ssam	(void)memset(&de, 0, sizeof(de));
942185222Ssam	de.d_ino = ufs_rw32(node->inode->ino, needswap);
943185222Ssam	de.d_type = IFTODT(node->type);
944185222Ssam	de.d_namlen = (uint8_t)strlen(name);
945185222Ssam	strcpy(de.d_name, name);
946186261Ssam	reclen = DIRSIZ_SWAP(0, &de, needswap);
947185222Ssam	de.d_reclen = ufs_rw16(reclen, needswap);
948185222Ssam
949185222Ssam	dp = (struct direct *)(dbuf->buf + dbuf->cur);
950185222Ssam	llen = 0;
951185222Ssam	if (dp != NULL)
952186261Ssam		llen = DIRSIZ_SWAP(0, dp, needswap);
953185222Ssam
954185222Ssam	if (debug & DEBUG_FS_MAKE_DIRBUF)
955185222Ssam		printf(
956185222Ssam		    "ffs_make_dirbuf: dbuf siz %d cur %d lastlen %d\n"
957185222Ssam		    "  ino %d type %d reclen %d namlen %d name %.30s\n",
958185222Ssam		    dbuf->size, dbuf->cur, llen,
959185222Ssam		    ufs_rw32(de.d_ino, needswap), de.d_type, reclen,
960185222Ssam		    de.d_namlen, de.d_name);
961185222Ssam
962185222Ssam	if (reclen + dbuf->cur + llen > roundup(dbuf->size, DIRBLKSIZ)) {
963185222Ssam		if (debug & DEBUG_FS_MAKE_DIRBUF)
964185222Ssam			printf("ffs_make_dirbuf: growing buf to %d\n",
965185222Ssam			    dbuf->size + DIRBLKSIZ);
966185222Ssam		if ((newbuf = realloc(dbuf->buf, dbuf->size + DIRBLKSIZ)) == NULL)
967185222Ssam			err(1, "Allocating memory for directory buffer");
968185222Ssam		dbuf->buf = newbuf;
969185222Ssam		dbuf->size += DIRBLKSIZ;
970185222Ssam		memset(dbuf->buf + dbuf->size - DIRBLKSIZ, 0, DIRBLKSIZ);
971185222Ssam		dbuf->cur = dbuf->size - DIRBLKSIZ;
972185222Ssam	} else {				/* shrink end of previous */
973185222Ssam		dp->d_reclen = ufs_rw16(llen,needswap);
974185222Ssam		dbuf->cur += llen;
975185222Ssam	}
976185222Ssam	dp = (struct direct *)(dbuf->buf + dbuf->cur);
977185222Ssam	memcpy(dp, &de, reclen);
978185222Ssam	dp->d_reclen = ufs_rw16(dbuf->size - dbuf->cur, needswap);
979185222Ssam}
980185222Ssam
981185222Ssam/*
982185222Ssam * cribbed from sys/ufs/ffs/ffs_alloc.c
983185222Ssam */
984185222Ssamstatic void
985185222Ssamffs_write_inode(union dinode *dp, uint32_t ino, const fsinfo_t *fsopts)
986185222Ssam{
987185222Ssam	char 		*buf;
988185222Ssam	struct ufs1_dinode *dp1;
989185222Ssam	struct ufs2_dinode *dp2, *dip;
990185222Ssam	struct cg	*cgp;
991185222Ssam	struct fs	*fs;
992185222Ssam	int		cg, cgino, i;
993185222Ssam	daddr_t		d;
994185222Ssam	char		sbbuf[FFS_MAXBSIZE];
995185222Ssam	int32_t		initediblk;
996185222Ssam
997185222Ssam	assert (dp != NULL);
998185222Ssam	assert (ino > 0);
999185222Ssam	assert (fsopts != NULL);
1000185222Ssam
1001185222Ssam	fs = (struct fs *)fsopts->superblock;
1002185222Ssam	cg = ino_to_cg(fs, ino);
1003185222Ssam	cgino = ino % fs->fs_ipg;
1004185222Ssam	if (debug & DEBUG_FS_WRITE_INODE)
1005185222Ssam		printf("ffs_write_inode: din %p ino %u cg %d cgino %d\n",
1006185222Ssam		    dp, ino, cg, cgino);
1007185222Ssam
1008185222Ssam	ffs_rdfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf,
1009185222Ssam	    fsopts);
1010185222Ssam	cgp = (struct cg *)sbbuf;
1011186261Ssam	if (!cg_chkmagic_swap(cgp, fsopts->needswap))
1012185222Ssam		errx(1, "ffs_write_inode: cg %d: bad magic number", cg);
1013185222Ssam
1014186261Ssam	assert (isclr(cg_inosused_swap(cgp, fsopts->needswap), cgino));
1015185222Ssam
1016185222Ssam	buf = malloc(fs->fs_bsize);
1017185222Ssam	if (buf == NULL)
1018185222Ssam		errx(1, "ffs_write_inode: cg %d: can't alloc inode block", cg);
1019185222Ssam
1020185222Ssam	dp1 = (struct ufs1_dinode *)buf;
1021185222Ssam	dp2 = (struct ufs2_dinode *)buf;
1022185222Ssam
1023185222Ssam	if (fs->fs_cstotal.cs_nifree == 0)
1024185222Ssam		errx(1, "ffs_write_inode: fs out of inodes for ino %u",
1025185222Ssam		    ino);
1026185222Ssam	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1027185222Ssam		errx(1,
1028185222Ssam		    "ffs_write_inode: cg %d out of inodes for ino %u",
1029185222Ssam		    cg, ino);
1030186261Ssam	setbit(cg_inosused_swap(cgp, fsopts->needswap), cgino);
1031185222Ssam	ufs_add32(cgp->cg_cs.cs_nifree, -1, fsopts->needswap);
1032185222Ssam	fs->fs_cstotal.cs_nifree--;
1033185222Ssam	fs->fs_cs(fs, cg).cs_nifree--;
1034185222Ssam	if (S_ISDIR(DIP(dp, mode))) {
1035185222Ssam		ufs_add32(cgp->cg_cs.cs_ndir, 1, fsopts->needswap);
1036185222Ssam		fs->fs_cstotal.cs_ndir++;
1037185222Ssam		fs->fs_cs(fs, cg).cs_ndir++;
1038185222Ssam	}
1039185222Ssam
1040185222Ssam	/*
1041185222Ssam	 * Initialize inode blocks on the fly for UFS2.
1042185222Ssam	 */
1043185222Ssam	initediblk = ufs_rw32(cgp->cg_initediblk, fsopts->needswap);
1044185222Ssam	if (fsopts->version == 2 && cgino + INOPB(fs) > initediblk &&
1045185222Ssam	    initediblk < ufs_rw32(cgp->cg_niblk, fsopts->needswap)) {
1046185222Ssam		memset(buf, 0, fs->fs_bsize);
1047185222Ssam		dip = (struct ufs2_dinode *)buf;
1048185222Ssam		srandom(time(NULL));
1049185222Ssam		for (i = 0; i < INOPB(fs); i++) {
1050185222Ssam			dip->di_gen = random() / 2 + 1;
1051185222Ssam			dip++;
1052185222Ssam		}
1053185222Ssam		ffs_wtfs(fsbtodb(fs, ino_to_fsba(fs,
1054185222Ssam				  cg * fs->fs_ipg + initediblk)),
1055185222Ssam		    fs->fs_bsize, buf, fsopts);
1056185222Ssam		initediblk += INOPB(fs);
1057185222Ssam		cgp->cg_initediblk = ufs_rw32(initediblk, fsopts->needswap);
1058185222Ssam	}
1059185222Ssam
1060185222Ssam
1061185222Ssam	ffs_wtfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf,
1062185222Ssam	    fsopts);
1063185222Ssam
1064185222Ssam					/* now write inode */
1065185222Ssam	d = fsbtodb(fs, ino_to_fsba(fs, ino));
1066185222Ssam	ffs_rdfs(d, fs->fs_bsize, buf, fsopts);
1067185222Ssam	if (fsopts->needswap) {
1068185222Ssam		if (fsopts->version == 1)
1069185222Ssam			ffs_dinode1_swap(&dp->ffs1_din,
1070185222Ssam			    &dp1[ino_to_fsbo(fs, ino)]);
1071185222Ssam		else
1072185222Ssam			ffs_dinode2_swap(&dp->ffs2_din,
1073185222Ssam			    &dp2[ino_to_fsbo(fs, ino)]);
1074185222Ssam	} else {
1075185222Ssam		if (fsopts->version == 1)
1076185222Ssam			dp1[ino_to_fsbo(fs, ino)] = dp->ffs1_din;
1077185222Ssam		else
1078185222Ssam			dp2[ino_to_fsbo(fs, ino)] = dp->ffs2_din;
1079185222Ssam	}
1080185222Ssam	ffs_wtfs(d, fs->fs_bsize, buf, fsopts);
1081185222Ssam	free(buf);
1082185222Ssam}
1083185222Ssam
1084185222Ssamvoid
1085185222Ssampanic(const char *fmt, ...)
1086185222Ssam{
1087185222Ssam	va_list ap;
1088185222Ssam
1089185222Ssam	va_start(ap, fmt);
1090185222Ssam	vwarnx(fmt, ap);
1091185222Ssam	va_end(ap);
1092185222Ssam	exit(1);
1093185222Ssam}
1094