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