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