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