xref: /openbsd-src/usr.sbin/makefs/ffs.c (revision 505ee9ea3b177e2387d907a91ca7da069f3f14d8)
1 /*	$OpenBSD: ffs.c,v 1.32 2020/04/09 16:19:00 krw Exp $	*/
2 /*	$NetBSD: ffs.c,v 1.66 2015/12/21 00:58:08 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 2001 Wasabi Systems, Inc.
6  * All rights reserved.
7  *
8  * Written by Luke Mewburn for Wasabi Systems, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed for the NetBSD Project by
21  *      Wasabi Systems, Inc.
22  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
23  *    or promote products derived from this software without specific prior
24  *    written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 /*
39  * Copyright (c) 1982, 1986, 1989, 1993
40  *	The Regents of the University of California.  All rights reserved.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)ffs_alloc.c	8.19 (Berkeley) 7/13/95
67  */
68 
69 #include <sys/param.h>
70 #include <sys/disklabel.h>
71 
72 #include <assert.h>
73 #include <errno.h>
74 #include <fcntl.h>
75 #include <stdarg.h>
76 #include <stdio.h>
77 #include <stdint.h>
78 #include <stdlib.h>
79 #include <string.h>
80 #include <unistd.h>
81 
82 #include <ufs/ufs/dinode.h>
83 #include <ufs/ufs/dir.h>
84 #include <ufs/ffs/fs.h>
85 
86 #include "ffs/ufs_inode.h"
87 #include "ffs/ffs_extern.h"
88 
89 #include "makefs.h"
90 #include "ffs.h"
91 #include "ffs/newfs_extern.h"
92 
93 #undef DIP
94 #define DIP(dp, field) \
95 	((ffs_opts->version == 1) ? \
96 	(dp)->ffs1_din.di_##field : (dp)->ffs2_din.di_##field)
97 
98 /*
99  * Various file system defaults (cribbed from newfs(8)).
100  */
101 #define	DFL_FRAGSIZE		2048		/* fragment size */
102 #define	DFL_BLKSIZE		16384		/* block size */
103 #define	DFL_SECSIZE		512		/* sector size */
104 
105 
106 typedef struct {
107 	u_char		*buf;		/* buf for directory */
108 	doff_t		size;		/* full size of buf */
109 	doff_t		cur;		/* offset of current entry */
110 } dirbuf_t;
111 
112 
113 static	int	ffs_create_image(const char *, fsinfo_t *);
114 static	void	ffs_make_dirbuf(dirbuf_t *, const char *, fsnode *);
115 static	int	ffs_populate_dir(const char *, fsnode *, fsinfo_t *);
116 static	void	ffs_size_dir(fsnode *, fsinfo_t *);
117 static	void	ffs_validate(const char *, fsnode *, fsinfo_t *);
118 static	void	ffs_write_file(union dinode *, uint32_t, void *, fsinfo_t *);
119 static	void	ffs_write_inode(union dinode *, uint32_t, const fsinfo_t *);
120 static  void	*ffs_build_dinode1(struct ufs1_dinode *, dirbuf_t *, fsnode *,
121 				 fsnode *, fsinfo_t *);
122 static  void	*ffs_build_dinode2(struct ufs2_dinode *, dirbuf_t *, fsnode *,
123 				 fsnode *, fsinfo_t *);
124 
125 
126 
127 	/* publically visible functions */
128 void
129 ffs_prep_opts(fsinfo_t *fsopts)
130 {
131 	ffs_opt_t *ffs_opts = ecalloc(1, sizeof(*ffs_opts));
132 
133 	const option_t ffs_options[] = {
134 	    { "avgfilesize", &ffs_opts->avgfilesize, OPT_INT32, 1, INT_MAX },
135 	    { "avgfpdir", &ffs_opts->avgfpdir, OPT_INT32, 1, INT_MAX },
136 	    { "bsize", &ffs_opts->bsize, OPT_INT32, 1, INT_MAX },
137 	    { "density", &ffs_opts->density, OPT_INT32, 1, INT_MAX },
138 	    { "disklabel", NULL, OPT_STRBUF, 0, 0 },
139 	    { "extent", &ffs_opts->maxbsize, OPT_INT32, 1, INT_MAX },
140 	    { "fsize", &ffs_opts->fsize, OPT_INT32, 1, INT_MAX },
141 	    { "label", ffs_opts->label, OPT_STRARRAY, 1, MAXVOLLEN },
142 	    { "maxbpcg", &ffs_opts->maxblkspercg, OPT_INT32, 1, INT_MAX },
143 	    { "maxbpg", &ffs_opts->maxbpg, OPT_INT32, 1, INT_MAX },
144 	    { "minfree", &ffs_opts->minfree, OPT_INT32, 0, 99 },
145 	    { "optimization", NULL, OPT_STRBUF, 0, 0 },
146 	    { "version", &ffs_opts->version, OPT_INT32, 1, 2 },
147 	    { .name = NULL }
148 	};
149 
150 	ffs_opts->bsize = -1;
151 	ffs_opts->fsize = -1;
152 	ffs_opts->density = -1;
153 	ffs_opts->minfree = MINFREE;
154 	ffs_opts->optimization = FS_OPTSPACE;
155 	ffs_opts->maxbpg = -1;
156 	ffs_opts->avgfilesize = AVFILESIZ;
157 	ffs_opts->avgfpdir = AFPDIR;
158 	ffs_opts->version = 1;
159 	ffs_opts->lp = NULL;
160 	ffs_opts->pp = NULL;
161 
162 	fsopts->fs_specific = ffs_opts;
163 	fsopts->fs_options = copy_opts(ffs_options);
164 }
165 
166 void
167 ffs_cleanup_opts(fsinfo_t *fsopts)
168 {
169 	free(fsopts->fs_specific);
170 	free(fsopts->fs_options);
171 }
172 
173 int
174 ffs_parse_opts(const char *option, fsinfo_t *fsopts)
175 {
176 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
177 	option_t *ffs_options = fsopts->fs_options;
178 	char buf[1024];
179 
180 	int	rv;
181 
182 	assert(option != NULL);
183 	assert(fsopts != NULL);
184 	assert(ffs_opts != NULL);
185 
186 	rv = set_option(ffs_options, option, buf, sizeof(buf));
187 	if (rv == -1)
188 		return 0;
189 
190 	if (ffs_options[rv].name == NULL)
191 		abort();
192 
193 	if (strcmp(ffs_options[rv].name, "disklabel") == 0) {
194 		struct disklabel *dp;
195 
196 		dp = getdiskbyname(buf);
197 		if (dp == NULL)
198 			errx(1, "unknown disk type: %s", buf);
199 
200 		ffs_opts->lp = emalloc(sizeof(struct disklabel));
201 		*ffs_opts->lp = *dp;
202 	} else if (strcmp(ffs_options[rv].name, "optimization") == 0) {
203 		if (strcmp(buf, "time") == 0) {
204 			ffs_opts->optimization = FS_OPTTIME;
205 		} else if (strcmp(buf, "space") == 0) {
206 			ffs_opts->optimization = FS_OPTSPACE;
207 		} else {
208 			warnx("Invalid optimization `%s'", buf);
209 			return 0;
210 		}
211 	}
212 	return 1;
213 }
214 
215 
216 void
217 ffs_makefs(const char *image, const char *dir, fsnode *root, fsinfo_t *fsopts)
218 {
219 	struct fs	*superblock;
220 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
221 
222 	assert(image != NULL);
223 	assert(dir != NULL);
224 	assert(root != NULL);
225 	assert(fsopts != NULL);
226 
227 		/* validate tree and options */
228 	ffs_validate(dir, root, fsopts);
229 
230 	printf("Calculated size of `%s': %lld bytes, %lld inodes\n",
231 	    image, (long long)fsopts->size, (long long)fsopts->inodes);
232 
233 		/* create image */
234 	if (ffs_create_image(image, fsopts) == -1)
235 		errx(1, "Image file `%s' not created.", image);
236 
237 	fsopts->curinode = ROOTINO;
238 
239 		/* populate image */
240 	printf("Populating `%s'\n", image);
241 	if (! ffs_populate_dir(dir, root, fsopts))
242 		errx(1, "Image file `%s' not populated.", image);
243 
244 	bcleanup();
245 
246 		/* update various superblock parameters */
247 	superblock = fsopts->superblock;
248 	superblock->fs_fmod = 0;
249 	superblock->fs_ffs1_cstotal.cs_ndir   = superblock->fs_cstotal.cs_ndir;
250 	superblock->fs_ffs1_cstotal.cs_nbfree = superblock->fs_cstotal.cs_nbfree;
251 	superblock->fs_ffs1_cstotal.cs_nifree = superblock->fs_cstotal.cs_nifree;
252 	superblock->fs_ffs1_cstotal.cs_nffree = superblock->fs_cstotal.cs_nffree;
253 
254 		/* write out superblock; image is now complete */
255 	ffs_write_superblock(fsopts->superblock, fsopts);
256 
257 	if (ffs_opts->lp != NULL) {
258 		struct disklabel *lp = ffs_opts->lp;
259 		uint16_t *p, *end, sum = 0;
260 		ssize_t n;
261 		uint32_t bpg;
262 
263 		bpg = superblock->fs_fpg / superblock->fs_frag;
264 		while (bpg > UINT16_MAX)
265 			bpg >>= 1;
266 		ffs_opts->pp->p_cpg = bpg;
267 
268 		lp->d_magic = DISKMAGIC;
269 		lp->d_magic2 = DISKMAGIC;
270 		arc4random_buf(lp->d_uid, sizeof(lp->d_uid));
271 		lp->d_checksum = 0;
272 
273 		p = (uint16_t *)lp;
274 		end = (uint16_t *)&lp->d_partitions[lp->d_npartitions];
275 		while (p < end)
276 			sum ^= *p++;
277 		lp->d_checksum = sum;
278 
279 		n = pwrite(fsopts->fd, lp, sizeof(struct disklabel),
280 		    fsopts->offset + LABELSECTOR * DEV_BSIZE + LABELOFFSET);
281 		if (n == -1)
282 			err(1, "failed to write disklabel");
283 		else if (n < sizeof(struct disklabel))
284 			errx(1, "failed to write disklabel: short write");
285 	}
286 
287 	if (close(fsopts->fd) == -1)
288 		err(1, "Closing `%s'", image);
289 	fsopts->fd = -1;
290 	printf("Image `%s' complete\n", image);
291 }
292 
293 	/* end of public functions */
294 
295 
296 static void
297 ffs_validate(const char *dir, fsnode *root, fsinfo_t *fsopts)
298 {
299 	ffs_opt_t *ffs_opts = fsopts->fs_specific;
300 	struct disklabel *lp = ffs_opts->lp;
301 	struct partition *pp = NULL;
302 	int32_t	ncg = 1;
303 	int i;
304 
305 	assert(dir != NULL);
306 	assert(root != NULL);
307 	assert(fsopts != NULL);
308 	assert(ffs_opts != NULL);
309 
310 	if (lp != NULL) {
311 		for (i = 0; i < lp->d_npartitions; i++) {
312 			pp = &lp->d_partitions[i];
313 			if (pp->p_fstype == FS_BSDFFS &&
314 			    pp->p_offset * lp->d_secsize == fsopts->offset) {
315 				break;
316 			}
317 		}
318 		if (i == lp->d_npartitions)
319 			errx(1, "no matching partition found in the disklabel");
320 		ffs_opts->pp = pp;
321 
322 		if (pp->p_fragblock == 0)
323 			errx(1, "fragment size missing in disktab");
324 		if (fsopts->freeblocks != 0 || fsopts->freeblockpc != 0 ||
325 		    fsopts->freefiles != 0 || fsopts->freefilepc != 0 ||
326 		    fsopts->minsize != 0 || fsopts->maxsize != 0 ||
327 		    fsopts->sectorsize != -1 || fsopts->size != 0)
328 			errx(1, "-bfMmSs and disklabel are mutually exclusive");
329 		if (ffs_opts->fsize != -1 || ffs_opts->bsize != -1)
330 			errx(1, "b/fsize and disklabel are mutually exclusive");
331 
332 		fsopts->sectorsize = lp->d_secsize;
333 		fsopts->minsize = fsopts->maxsize =
334 		    DL_GETPSIZE(pp) * lp->d_secsize;
335 		ffs_opts->fsize = DISKLABELV1_FFS_FSIZE(pp->p_fragblock);
336 		ffs_opts->bsize = DISKLABELV1_FFS_BSIZE(pp->p_fragblock);
337 	}
338 
339 		/* set FFS defaults */
340 	if (fsopts->sectorsize == -1)
341 		fsopts->sectorsize = DFL_SECSIZE;
342 	if (ffs_opts->fsize == -1)
343 		ffs_opts->fsize = MAX(DFL_FRAGSIZE, fsopts->sectorsize);
344 	if (ffs_opts->bsize == -1)
345 		ffs_opts->bsize = MIN(DFL_BLKSIZE, 8 * ffs_opts->fsize);
346 				/* fsopts->density is set below */
347 	/* XXX ondisk32 */
348 	if (ffs_opts->maxbpg == -1)
349 		ffs_opts->maxbpg = ffs_opts->bsize / sizeof(int32_t);
350 
351 		/* calculate size of tree */
352 	ffs_size_dir(root, fsopts);
353 	fsopts->inodes += ROOTINO;		/* include first two inodes */
354 
355 		/* add requested slop */
356 	fsopts->size += fsopts->freeblocks;
357 	fsopts->inodes += fsopts->freefiles;
358 	if (fsopts->freefilepc > 0)
359 		fsopts->inodes =
360 		    fsopts->inodes * (100 + fsopts->freefilepc) / 100;
361 	if (fsopts->freeblockpc > 0)
362 		fsopts->size =
363 		    fsopts->size * (100 + fsopts->freeblockpc) / 100;
364 
365 		/* add space needed for superblocks */
366 	/*
367 	 * The old SBOFF (SBLOCK_UFS1) is used here because makefs is
368 	 * typically used for small filesystems where space matters.
369 	 * XXX make this an option.
370 	 */
371 	fsopts->size += (SBLOCK_UFS1 + SBLOCKSIZE) * ncg;
372 		/* add space needed to store inodes, x3 for blockmaps, etc */
373 	if (ffs_opts->version == 1)
374 		fsopts->size += ncg * sizeof(struct ufs1_dinode) *
375 		    roundup(fsopts->inodes / ncg,
376 			ffs_opts->bsize / sizeof(struct ufs1_dinode));
377 	else
378 		fsopts->size += ncg * sizeof(struct ufs2_dinode) *
379 		    roundup(fsopts->inodes / ncg,
380 			ffs_opts->bsize / sizeof(struct ufs2_dinode));
381 
382 		/* add minfree */
383 	if (ffs_opts->minfree > 0)
384 		fsopts->size =
385 		    fsopts->size * (100 + ffs_opts->minfree) / 100;
386 	/*
387 	 * XXX	any other fs slop to add, such as csum's, bitmaps, etc ??
388 	 */
389 
390 	if (fsopts->size < fsopts->minsize)	/* ensure meets minimum size */
391 		fsopts->size = fsopts->minsize;
392 
393 		/* round up to the next block */
394 	fsopts->size = roundup(fsopts->size, ffs_opts->bsize);
395 
396 		/* calculate density if necessary */
397 	if (ffs_opts->density == -1)
398 		ffs_opts->density = fsopts->size / fsopts->inodes + 1;
399 
400 		/* now check calculated sizes vs requested sizes */
401 	if (fsopts->maxsize > 0 && fsopts->size > fsopts->maxsize) {
402 		errx(1, "`%s' size of %lld is larger than the maxsize of %lld.",
403 		    dir, (long long)fsopts->size, (long long)fsopts->maxsize);
404 	}
405 }
406 
407 
408 static int
409 ffs_create_image(const char *image, fsinfo_t *fsopts)
410 {
411 	struct fs	*fs;
412 	char	*buf;
413 	int	i, bufsize;
414 	off_t	bufrem;
415 	time_t	tstamp;
416 	int	oflags = O_RDWR | O_CREAT;
417 
418 	assert (image != NULL);
419 	assert (fsopts != NULL);
420 
421 		/* create image */
422 	if (fsopts->offset == 0)
423 		oflags |= O_TRUNC;
424 	if ((fsopts->fd = open(image, oflags, 0666)) == -1) {
425 		warn("Can't open `%s' for writing", image);
426 		return (-1);
427 	}
428 
429 		/* zero image */
430 	bufsize = 8192;
431 	bufrem = fsopts->size;
432 
433 	if (fsopts->offset != 0)
434 		if (lseek(fsopts->fd, fsopts->offset, SEEK_SET) == -1) {
435 			warn("can't seek");
436 			return -1;
437 		}
438 
439 	if (bufrem > 0)
440 		buf = ecalloc(1, bufsize);
441 	while (bufrem > 0) {
442 		i = write(fsopts->fd, buf, MIN(bufsize, bufrem));
443 		if (i == -1) {
444 			warn("zeroing image, %lld bytes to go",
445 			    (long long)bufrem);
446 			free(buf);
447 			return (-1);
448 		}
449 		bufrem -= i;
450 	}
451 	free(buf);
452 
453 		/* make the file system */
454 	if (Tflag) {
455 		tstamp = stampts;
456 		srandom_deterministic(stampts);
457 	} else
458 		tstamp = start_time.tv_sec;
459 
460 	fs = ffs_mkfs(image, fsopts, tstamp);
461 	fsopts->superblock = (void *)fs;
462 
463 	if ((off_t)(fs->fs_cstotal.cs_nifree + ROOTINO) < fsopts->inodes) {
464 		warnx(
465 		"Image file `%s' has %lld free inodes; %lld are required.",
466 		    image,
467 		    (long long)(fs->fs_cstotal.cs_nifree + ROOTINO),
468 		    (long long)fsopts->inodes);
469 		return (-1);
470 	}
471 	return (fsopts->fd);
472 }
473 
474 
475 static void
476 ffs_size_dir(fsnode *root, fsinfo_t *fsopts)
477 {
478 	struct direct	tmpdir;
479 	fsnode *	node;
480 	int		curdirsize, this;
481 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
482 
483 	/* node may be NULL (empty directory) */
484 	assert(fsopts != NULL);
485 	assert(ffs_opts != NULL);
486 
487 #define	ADDDIRENT(e) do {						\
488 	tmpdir.d_namlen = strlen((e));					\
489 	this = DIRSIZ(NEWDIRFMT, &tmpdir);				\
490 	if (this + curdirsize > roundup(curdirsize, DIRBLKSIZ))	\
491 		curdirsize = roundup(curdirsize, DIRBLKSIZ);	\
492 	curdirsize += this;						\
493 } while (0);
494 
495 	/*
496 	 * XXX	this needs to take into account extra space consumed
497 	 *	by indirect blocks, etc.
498 	 */
499 #define	ADDSIZE(x) do {							\
500 	fsopts->size += roundup((x), ffs_opts->fsize);			\
501 } while (0);
502 
503 	curdirsize = 0;
504 	for (node = root; node != NULL; node = node->next) {
505 		ADDDIRENT(node->name);
506 		if (node == root) {			/* we're at "." */
507 			assert(strcmp(node->name, ".") == 0);
508 			ADDDIRENT("..");
509 		} else if ((node->inode->flags & FI_SIZED) == 0) {
510 				/* don't count duplicate names */
511 			node->inode->flags |= FI_SIZED;
512 			fsopts->inodes++;
513 			if (node->type == S_IFREG)
514 				ADDSIZE(node->inode->st.st_size);
515 			if (node->type == S_IFLNK) {
516 				size_t	slen;
517 
518 				slen = strlen(node->symlink) + 1;
519 				if (slen >= (ffs_opts->version == 1 ?
520 						MAXSYMLINKLEN_UFS1 :
521 						MAXSYMLINKLEN_UFS2))
522 					ADDSIZE(slen);
523 			}
524 		}
525 		if (node->type == S_IFDIR)
526 			ffs_size_dir(node->child, fsopts);
527 	}
528 	ADDSIZE(curdirsize);
529 }
530 
531 static void *
532 ffs_build_dinode1(struct ufs1_dinode *dinp, dirbuf_t *dbufp, fsnode *cur,
533 		 fsnode *root, fsinfo_t *fsopts)
534 {
535 	size_t slen;
536 	void *membuf;
537 
538 	memset(dinp, 0, sizeof(*dinp));
539 	dinp->di_mode = cur->inode->st.st_mode;
540 	dinp->di_nlink = cur->inode->nlink;
541 	dinp->di_size = cur->inode->st.st_size;
542 	dinp->di_flags = cur->inode->st.st_flags;
543 	dinp->di_gen = cur->inode->st.st_gen;
544 	dinp->di_uid = cur->inode->st.st_uid;
545 	dinp->di_gid = cur->inode->st.st_gid;
546 
547 	dinp->di_atime = cur->inode->st.st_atime;
548 	dinp->di_mtime = cur->inode->st.st_mtime;
549 	dinp->di_ctime = cur->inode->st.st_ctime;
550 	dinp->di_atimensec = cur->inode->st.st_atimensec;
551 	dinp->di_mtimensec = cur->inode->st.st_mtimensec;
552 	dinp->di_ctimensec = cur->inode->st.st_ctimensec;
553 		/* not set: di_db, di_ib, di_blocks, di_spare */
554 
555 	membuf = NULL;
556 	if (cur == root) {			/* "."; write dirbuf */
557 		membuf = dbufp->buf;
558 		dinp->di_size = dbufp->size;
559 	} else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) {
560 		dinp->di_size = 0;	/* a device */
561 		dinp->di_rdev = cur->inode->st.st_rdev;
562 	} else if (S_ISLNK(cur->type)) {	/* symlink */
563 		slen = strlen(cur->symlink);
564 		if (slen < MAXSYMLINKLEN_UFS1) {	/* short link */
565 			memcpy(dinp->di_db, cur->symlink, slen);
566 		} else
567 			membuf = cur->symlink;
568 		dinp->di_size = slen;
569 	}
570 	return membuf;
571 }
572 
573 static void *
574 ffs_build_dinode2(struct ufs2_dinode *dinp, dirbuf_t *dbufp, fsnode *cur,
575 		 fsnode *root, fsinfo_t *fsopts)
576 {
577 	size_t slen;
578 	void *membuf;
579 
580 	memset(dinp, 0, sizeof(*dinp));
581 	dinp->di_mode = cur->inode->st.st_mode;
582 	dinp->di_nlink = cur->inode->nlink;
583 	dinp->di_size = cur->inode->st.st_size;
584 	dinp->di_flags = cur->inode->st.st_flags;
585 	dinp->di_gen = cur->inode->st.st_gen;
586 	dinp->di_uid = cur->inode->st.st_uid;
587 	dinp->di_gid = cur->inode->st.st_gid;
588 
589 	dinp->di_atime = cur->inode->st.st_atime;
590 	dinp->di_mtime = cur->inode->st.st_mtime;
591 	dinp->di_ctime = cur->inode->st.st_ctime;
592 	dinp->di_atimensec = cur->inode->st.st_atimensec;
593 	dinp->di_mtimensec = cur->inode->st.st_mtimensec;
594 	dinp->di_ctimensec = cur->inode->st.st_ctimensec;
595 		/* not set: di_db, di_ib, di_blocks, di_spare */
596 
597 	membuf = NULL;
598 	if (cur == root) {			/* "."; write dirbuf */
599 		membuf = dbufp->buf;
600 		dinp->di_size = dbufp->size;
601 	} else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) {
602 		dinp->di_size = 0;	/* a device */
603 		dinp->di_rdev = cur->inode->st.st_rdev;
604 	} else if (S_ISLNK(cur->type)) {	/* symlink */
605 		slen = strlen(cur->symlink);
606 		if (slen < MAXSYMLINKLEN_UFS2) {	/* short link */
607 			memcpy(dinp->di_db, cur->symlink, slen);
608 		} else
609 			membuf = cur->symlink;
610 		dinp->di_size = slen;
611 	}
612 	return membuf;
613 }
614 
615 static int
616 ffs_populate_dir(const char *dir, fsnode *root, fsinfo_t *fsopts)
617 {
618 	fsnode		*cur;
619 	dirbuf_t	dirbuf;
620 	union dinode	din;
621 	void		*membuf;
622 	char		path[MAXPATHLEN + 1];
623 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
624 
625 	assert(dir != NULL);
626 	assert(root != NULL);
627 	assert(fsopts != NULL);
628 	assert(ffs_opts != NULL);
629 
630 	(void)memset(&dirbuf, 0, sizeof(dirbuf));
631 
632 		/*
633 		 * pass 1: allocate inode numbers, build directory `file'
634 		 */
635 	for (cur = root; cur != NULL; cur = cur->next) {
636 		if ((cur->inode->flags & FI_ALLOCATED) == 0) {
637 			cur->inode->flags |= FI_ALLOCATED;
638 			if (cur == root && cur->parent != NULL)
639 				cur->inode->ino = cur->parent->inode->ino;
640 			else {
641 				cur->inode->ino = fsopts->curinode;
642 				fsopts->curinode++;
643 			}
644 		}
645 		ffs_make_dirbuf(&dirbuf, cur->name, cur);
646 		if (cur == root) {		/* we're at "."; add ".." */
647 			ffs_make_dirbuf(&dirbuf, "..",
648 			    cur->parent == NULL ? cur : cur->parent->first);
649 			root->inode->nlink++;	/* count my parent's link */
650 		} else if (cur->child != NULL)
651 			root->inode->nlink++;	/* count my child's link */
652 
653 		/*
654 		 * XXX	possibly write file and long symlinks here,
655 		 *	ensuring that blocks get written before inodes?
656 		 *	otoh, this isn't a real filesystem, so who
657 		 *	cares about ordering? :-)
658 		 */
659 	}
660 
661 		/*
662 		 * pass 2: write out dirbuf, then non-directories at this level
663 		 */
664 	for (cur = root; cur != NULL; cur = cur->next) {
665 		if (cur->inode->flags & FI_WRITTEN)
666 			continue;		/* skip hard-linked entries */
667 		cur->inode->flags |= FI_WRITTEN;
668 
669 		if ((size_t)snprintf(path, sizeof(path), "%s/%s/%s", cur->root,
670 		    cur->path, cur->name) >= sizeof(path))
671 			errx(1, "Pathname too long.");
672 
673 		if (cur->child != NULL)
674 			continue;		/* child creates own inode */
675 
676 				/* build on-disk inode */
677 		if (ffs_opts->version == 1)
678 			membuf = ffs_build_dinode1(&din.ffs1_din, &dirbuf, cur,
679 			    root, fsopts);
680 		else
681 			membuf = ffs_build_dinode2(&din.ffs2_din, &dirbuf, cur,
682 			    root, fsopts);
683 
684 		if (membuf != NULL) {
685 			ffs_write_file(&din, cur->inode->ino, membuf, fsopts);
686 		} else if (S_ISREG(cur->type)) {
687 			ffs_write_file(&din, cur->inode->ino, path, fsopts);
688 		} else {
689 			assert (! S_ISDIR(cur->type));
690 			ffs_write_inode(&din, cur->inode->ino, fsopts);
691 		}
692 	}
693 
694 		/*
695 		 * pass 3: write out sub-directories
696 		 */
697 	for (cur = root; cur != NULL; cur = cur->next) {
698 		if (cur->child == NULL)
699 			continue;
700 		if ((size_t)snprintf(path, sizeof(path), "%s/%s", dir,
701 		    cur->name) >= sizeof(path))
702 			errx(1, "Pathname too long.");
703 		if (! ffs_populate_dir(path, cur->child, fsopts))
704 			return (0);
705 	}
706 
707 		/* cleanup */
708 	free(dirbuf.buf);
709 	return (1);
710 }
711 
712 
713 static void
714 ffs_write_file(union dinode *din, uint32_t ino, void *buf, fsinfo_t *fsopts)
715 {
716 	int	isfile, ffd;
717 	char	*fbuf, *p;
718 	off_t	bufleft, chunk, offset;
719 	ssize_t nread;
720 	struct inode	in;
721 	struct mkfsbuf *	bp;
722 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
723 	struct mkfsvnode vp = { fsopts, NULL };
724 
725 	assert (din != NULL);
726 	assert (buf != NULL);
727 	assert (fsopts != NULL);
728 	assert (ffs_opts != NULL);
729 
730 	isfile = S_ISREG(DIP(din, mode));
731 	fbuf = NULL;
732 	ffd = -1;
733 	p = NULL;
734 
735 	in.i_fs = (struct fs *)fsopts->superblock;
736 	in.i_devvp = &vp;
737 
738 	in.i_number = ino;
739 	in.i_size = DIP(din, size);
740 	if (ffs_opts->version == 1)
741 		memcpy(&in.i_din.ffs1_din, &din->ffs1_din,
742 		    sizeof(in.i_din.ffs1_din));
743 	else
744 		memcpy(&in.i_din.ffs2_din, &din->ffs2_din,
745 		    sizeof(in.i_din.ffs2_din));
746 
747 	if (DIP(din, size) == 0)
748 		goto write_inode_and_leave;		/* mmm, cheating */
749 
750 	if (isfile) {
751 		fbuf = emalloc(ffs_opts->bsize);
752 		if ((ffd = open((char *)buf, O_RDONLY, 0444)) == -1) {
753 			warn("Can't open `%s' for reading", (char *)buf);
754 			goto leave_ffs_write_file;
755 		}
756 	} else {
757 		p = buf;
758 	}
759 
760 	chunk = 0;
761 	for (bufleft = DIP(din, size); bufleft > 0; bufleft -= chunk) {
762 		chunk = MIN(bufleft, ffs_opts->bsize);
763 		if (!isfile)
764 			;
765 		else if ((nread = read(ffd, fbuf, chunk)) == -1)
766 			err(1, "Reading `%s', %lld bytes to go", (char *)buf,
767 			    (long long)bufleft);
768 		else if (nread != chunk)
769 			errx(1, "Reading `%s', %lld bytes to go, "
770 			    "read %zd bytes, expected %ju bytes, does "
771 			    "metalog size= attribute mismatch source size?",
772 			    (char *)buf, (long long)bufleft, nread,
773 			    (uintmax_t)chunk);
774 		else
775 			p = fbuf;
776 		offset = DIP(din, size) - bufleft;
777 	/*
778 	 * XXX	if holey support is desired, do the check here
779 	 *
780 	 * XXX	might need to write out last bit in fragroundup
781 	 *	sized chunk. however, ffs_balloc() handles this for us
782 	 */
783 		errno = ffs_balloc(&in, offset, chunk, &bp);
784  bad_ffs_write_file:
785 		if (errno != 0)
786 			err(1,
787 			    "Writing inode %d (%s), bytes %lld + %lld",
788 			    ino,
789 			    isfile ? (char *)buf :
790 			      inode_type(DIP(din, mode) & S_IFMT),
791 			    (long long)offset, (long long)chunk);
792 		memcpy(bp->b_data, p, chunk);
793 		errno = bwrite(bp);
794 		if (errno != 0)
795 			goto bad_ffs_write_file;
796 		if (!isfile)
797 			p += chunk;
798 	}
799 
800  write_inode_and_leave:
801 	ffs_write_inode(&in.i_din, in.i_number, fsopts);
802 
803  leave_ffs_write_file:
804 	free(fbuf);
805 	if (ffd != -1)
806 		close(ffd);
807 }
808 
809 
810 static void
811 ffs_make_dirbuf(dirbuf_t *dbuf, const char *name, fsnode *node)
812 {
813 	struct direct	de, *dp;
814 	uint16_t	llen;
815 	u_char		*newbuf;
816 
817 	assert (dbuf != NULL);
818 	assert (name != NULL);
819 	assert (node != NULL);
820 					/* create direct entry */
821 	(void)memset(&de, 0, sizeof(de));
822 	de.d_ino = node->inode->ino;
823 	de.d_type = IFTODT(node->type);
824 	de.d_namlen = (uint8_t)strlen(name);
825 	strlcpy(de.d_name, name, sizeof de.d_name);
826 	de.d_reclen = DIRSIZ(NEWDIRFMT, &de);
827 
828 	dp = (struct direct *)(dbuf->buf + dbuf->cur);
829 	llen = 0;
830 	if (dp != NULL)
831 		llen = DIRSIZ(NEWDIRFMT, dp);
832 
833 	if (de.d_reclen + dbuf->cur + llen > roundup(dbuf->size, DIRBLKSIZ)) {
834 		newbuf = erealloc(dbuf->buf, dbuf->size + DIRBLKSIZ);
835 		dbuf->buf = newbuf;
836 		dbuf->size += DIRBLKSIZ;
837 		memset(dbuf->buf + dbuf->size - DIRBLKSIZ, 0, DIRBLKSIZ);
838 		dbuf->cur = dbuf->size - DIRBLKSIZ;
839 	} else if (dp) {			/* shrink end of previous */
840 		dp->d_reclen = llen;
841 		dbuf->cur += llen;
842 	}
843 	dp = (struct direct *)(dbuf->buf + dbuf->cur);
844 	memcpy(dp, &de, de.d_reclen);
845 	dp->d_reclen = dbuf->size - dbuf->cur;
846 }
847 
848 /*
849  * cribbed from sys/ufs/ffs/ffs_alloc.c
850  */
851 static void
852 ffs_write_inode(union dinode *dp, uint32_t ino, const fsinfo_t *fsopts)
853 {
854 	char		*buf;
855 	struct ufs1_dinode *dp1;
856 	struct ufs2_dinode *dp2, *dip;
857 	struct cg	*cgp;
858 	struct fs	*fs;
859 	int		cg, cgino, i;
860 	daddr_t		d;
861 	char		sbbuf[FFS_MAXBSIZE];
862 	uint32_t	initediblk;
863 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
864 
865 	assert (dp != NULL);
866 	assert (ino > 0);
867 	assert (fsopts != NULL);
868 	assert (ffs_opts != NULL);
869 
870 	fs = (struct fs *)fsopts->superblock;
871 	cg = ino_to_cg(fs, ino);
872 	cgino = ino % fs->fs_ipg;
873 
874 	ffs_rdfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf,
875 	    fsopts);
876 	cgp = (struct cg *)sbbuf;
877 	if (!cg_chkmagic(cgp))
878 		errx(1, "ffs_write_inode: cg %d: bad magic number", cg);
879 
880 	assert (isclr(cg_inosused(cgp), cgino));
881 
882 	buf = emalloc(fs->fs_bsize);
883 	dp1 = (struct ufs1_dinode *)buf;
884 	dp2 = (struct ufs2_dinode *)buf;
885 
886 	if (fs->fs_cstotal.cs_nifree == 0)
887 		errx(1, "ffs_write_inode: fs out of inodes for ino %u",
888 		    ino);
889 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
890 		errx(1,
891 		    "ffs_write_inode: cg %d out of inodes for ino %u",
892 		    cg, ino);
893 	setbit(cg_inosused(cgp), cgino);
894 	cgp->cg_cs.cs_nifree -= 1;
895 	fs->fs_cstotal.cs_nifree--;
896 	fs->fs_cs(fs, cg).cs_nifree--;
897 	if (S_ISDIR(DIP(dp, mode))) {
898 		cgp->cg_cs.cs_ndir += 1;
899 		fs->fs_cstotal.cs_ndir++;
900 		fs->fs_cs(fs, cg).cs_ndir++;
901 	}
902 
903 	/*
904 	 * Initialize inode blocks on the fly for UFS2.
905 	 */
906 	initediblk = cgp->cg_initediblk;
907 	if (ffs_opts->version == 2 &&
908 	    (uint32_t)(cgino + INOPB(fs)) > initediblk &&
909 	    initediblk < cgp->cg_ffs2_niblk) {
910 		memset(buf, 0, fs->fs_bsize);
911 		dip = (struct ufs2_dinode *)buf;
912 		for (i = 0; i < INOPB(fs); i++) {
913 			dip->di_gen = random() / 2 + 1;
914 			dip++;
915 		}
916 		ffs_wtfs(fsbtodb(fs, ino_to_fsba(fs,
917 				  cg * fs->fs_ipg + initediblk)),
918 		    fs->fs_bsize, buf, fsopts);
919 		initediblk += INOPB(fs);
920 		cgp->cg_initediblk = initediblk;
921 	}
922 
923 
924 	ffs_wtfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf,
925 	    fsopts);
926 
927 					/* now write inode */
928 	d = fsbtodb(fs, ino_to_fsba(fs, ino));
929 	ffs_rdfs(d, fs->fs_bsize, buf, fsopts);
930 	if (ffs_opts->version == 1)
931 		dp1[ino_to_fsbo(fs, ino)] = dp->ffs1_din;
932 	else
933 		dp2[ino_to_fsbo(fs, ino)] = dp->ffs2_din;
934 	ffs_wtfs(d, fs->fs_bsize, buf, fsopts);
935 	free(buf);
936 }
937