xref: /freebsd-14.2/usr.sbin/makefs/ffs.c (revision 8e402178)
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
ffs_prep_opts(fsinfo_t * fsopts)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
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 		/* 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
ffs_validate(const char * dir,fsnode * root,fsinfo_t * fsopts)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 (fsopts->sectorsize != DFL_SECSIZE)
344 		warnx("sectorsize %d may produce nonfunctional image",
345 		    fsopts->sectorsize);
346 	if (ffs_opts->fsize == -1)
347 		ffs_opts->fsize = MAX(DFL_FRAGSIZE, fsopts->sectorsize);
348 	if (ffs_opts->bsize == -1)
349 		ffs_opts->bsize = MIN(DFL_BLKSIZE, 8 * ffs_opts->fsize);
350 	if (ffs_opts->cpg == -1)
351 		ffs_opts->cpg = DFL_CYLSPERGROUP;
352 	else
353 		ffs_opts->cpgflg = 1;
354 				/* fsopts->density is set below */
355 	if (ffs_opts->nsectors == -1)
356 		ffs_opts->nsectors = DFL_NSECTORS;
357 	if (ffs_opts->minfree == -1)
358 		ffs_opts->minfree = MINFREE;
359 	if (ffs_opts->optimization == -1)
360 		ffs_opts->optimization = DEFAULTOPT;
361 	if (ffs_opts->maxcontig == -1)
362 		ffs_opts->maxcontig =
363 		    MAX(1, MIN(MAXPHYS, FFS_MAXBSIZE) / ffs_opts->bsize);
364 	/* XXX ondisk32 */
365 	if (ffs_opts->maxbpg == -1)
366 		ffs_opts->maxbpg = ffs_opts->bsize / sizeof(int32_t);
367 	if (ffs_opts->avgfilesize == -1)
368 		ffs_opts->avgfilesize = AVFILESIZ;
369 	if (ffs_opts->avgfpdir == -1)
370 		ffs_opts->avgfpdir = AFPDIR;
371 
372 	if (fsopts->maxsize > 0 &&
373 	    roundup(fsopts->minsize, ffs_opts->bsize) > fsopts->maxsize)
374 		errx(1, "`%s' minsize of %lld rounded up to ffs bsize of %d "
375 		    "exceeds maxsize %lld.  Lower bsize, or round the minimum "
376 		    "and maximum sizes to bsize.", dir,
377 		    (long long)fsopts->minsize, ffs_opts->bsize,
378 		    (long long)fsopts->maxsize);
379 
380 		/* calculate size of tree */
381 	ffs_size_dir(root, fsopts);
382 	fsopts->inodes += UFS_ROOTINO;		/* include first two inodes */
383 
384 	if (debug & DEBUG_FS_VALIDATE)
385 		printf("ffs_validate: size of tree: %lld bytes, %lld inodes\n",
386 		    (long long)fsopts->size, (long long)fsopts->inodes);
387 
388 		/* add requested slop */
389 	fsopts->size += fsopts->freeblocks;
390 	fsopts->inodes += fsopts->freefiles;
391 	if (fsopts->freefilepc > 0)
392 		fsopts->inodes =
393 		    fsopts->inodes * (100 + fsopts->freefilepc) / 100;
394 	if (fsopts->freeblockpc > 0)
395 		fsopts->size =
396 		    fsopts->size * (100 + fsopts->freeblockpc) / 100;
397 
398 	/*
399 	 * Add space needed for superblock, cylblock and to store inodes.
400 	 * All of those segments are aligned to the block size.
401 	 * XXX: This has to match calculations done in ffs_mkfs.
402 	 */
403 	if (ffs_opts->version == 1) {
404 		fsopts->size +=
405 		    roundup(SBLOCK_UFS1 + SBLOCKSIZE, ffs_opts->bsize);
406 		fsopts->size += roundup(SBLOCKSIZE, ffs_opts->bsize);
407 		fsopts->size += ffs_opts->bsize;
408 		fsopts->size +=  DINODE1_SIZE *
409 		    roundup(fsopts->inodes, ffs_opts->bsize / DINODE1_SIZE);
410 	} else {
411 		fsopts->size +=
412 		    roundup(SBLOCK_UFS2 + SBLOCKSIZE, ffs_opts->bsize);
413 		fsopts->size += roundup(SBLOCKSIZE, ffs_opts->bsize);
414 		fsopts->size += ffs_opts->bsize;
415 		fsopts->size += DINODE2_SIZE *
416 		    roundup(fsopts->inodes, ffs_opts->bsize / DINODE2_SIZE);
417 	}
418 
419 		/* add minfree */
420 	if (ffs_opts->minfree > 0)
421 		fsopts->size =
422 		    fsopts->size * (100 + ffs_opts->minfree) / 100;
423 	/*
424 	 * XXX	any other fs slop to add, such as csum's, bitmaps, etc ??
425 	 */
426 
427 	if (fsopts->size < fsopts->minsize)	/* ensure meets minimum size */
428 		fsopts->size = fsopts->minsize;
429 
430 		/* round up to the next block */
431 	fsopts->size = roundup(fsopts->size, ffs_opts->bsize);
432 
433 		/* round up to requested block size, if any */
434 	if (fsopts->roundup > 0)
435 		fsopts->size = roundup(fsopts->size, fsopts->roundup);
436 
437 		/* calculate density to just fit inodes if no free space */
438 	if (ffs_opts->density == -1)
439 		ffs_opts->density = fsopts->size / fsopts->inodes + 1;
440 
441 	if (debug & DEBUG_FS_VALIDATE) {
442 		printf("ffs_validate: after defaults set:\n");
443 		ffs_dump_fsinfo(fsopts);
444 		printf("ffs_validate: dir %s; %lld bytes, %lld inodes\n",
445 		    dir, (long long)fsopts->size, (long long)fsopts->inodes);
446 	}
447 		/* now check calculated sizes vs requested sizes */
448 	if (fsopts->maxsize > 0 && fsopts->size > fsopts->maxsize) {
449 		errx(1, "`%s' size of %lld is larger than the maxsize of %lld.",
450 		    dir, (long long)fsopts->size, (long long)fsopts->maxsize);
451 	}
452 }
453 
454 
455 static void
ffs_dump_fsinfo(fsinfo_t * f)456 ffs_dump_fsinfo(fsinfo_t *f)
457 {
458 
459 	ffs_opt_t	*fs = f->fs_specific;
460 
461 	printf("fsopts at %p\n", f);
462 
463 	printf("\tsize %lld, inodes %lld, curinode %u\n",
464 	    (long long)f->size, (long long)f->inodes, f->curinode);
465 
466 	printf("\tminsize %lld, maxsize %lld\n",
467 	    (long long)f->minsize, (long long)f->maxsize);
468 	printf("\tfree files %lld, freefile %% %d\n",
469 	    (long long)f->freefiles, f->freefilepc);
470 	printf("\tfree blocks %lld, freeblock %% %d\n",
471 	    (long long)f->freeblocks, f->freeblockpc);
472 	printf("\tneedswap %d, sectorsize %d\n", f->needswap, f->sectorsize);
473 
474 	printf("\tbsize %d, fsize %d, cpg %d, density %d\n",
475 	    fs->bsize, fs->fsize, fs->cpg, fs->density);
476 	printf("\tnsectors %d, rpm %d, minfree %d\n",
477 	    fs->nsectors, fs->rpm, fs->minfree);
478 	printf("\tmaxcontig %d, maxbpg %d\n",
479 	    fs->maxcontig, fs->maxbpg);
480 	printf("\toptimization %s\n",
481 	    fs->optimization == FS_OPTSPACE ? "space" : "time");
482 }
483 
484 
485 static int
ffs_create_image(const char * image,fsinfo_t * fsopts)486 ffs_create_image(const char *image, fsinfo_t *fsopts)
487 {
488 #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS
489 	struct statvfs	sfs;
490 #endif
491 	struct fs	*fs;
492 	char	*buf;
493 	int	i, bufsize;
494 	off_t	bufrem;
495 	int	oflags = O_RDWR | O_CREAT;
496 	time_t	tstamp;
497 
498 	assert (image != NULL);
499 	assert (fsopts != NULL);
500 
501 		/* create image */
502 	if (fsopts->offset == 0)
503 		oflags |= O_TRUNC;
504 	if ((fsopts->fd = open(image, oflags, 0666)) == -1) {
505 		warn("Can't open `%s' for writing", image);
506 		return (-1);
507 	}
508 
509 		/* zero image */
510 #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS
511 	if (fstatvfs(fsopts->fd, &sfs) == -1) {
512 #endif
513 		bufsize = 8192;
514 #if HAVE_STRUCT_STATVFS_F_IOSIZE && HAVE_FSTATVFS
515 		warn("can't fstatvfs `%s', using default %d byte chunk",
516 		    image, bufsize);
517 	} else
518 		bufsize = sfs.f_iosize;
519 #endif
520 	bufrem = fsopts->size;
521 	if (fsopts->sparse) {
522 		if (ftruncate(fsopts->fd, bufrem) == -1) {
523 			warn("sparse option disabled.");
524 			fsopts->sparse = 0;
525 		}
526 	}
527 	if (fsopts->sparse) {
528 		/* File truncated at bufrem. Remaining is 0 */
529 		bufrem = 0;
530 		buf = NULL;
531 	} else {
532 		if (debug & DEBUG_FS_CREATE_IMAGE)
533 			printf("zero-ing image `%s', %lld sectors, "
534 			    "using %d byte chunks\n", image, (long long)bufrem,
535 			    bufsize);
536 		buf = ecalloc(1, bufsize);
537 	}
538 
539 	if (fsopts->offset != 0)
540 		if (lseek(fsopts->fd, fsopts->offset, SEEK_SET) == -1) {
541 			warn("can't seek");
542 			free(buf);
543 			return -1;
544 		}
545 
546 	while (bufrem > 0) {
547 		i = write(fsopts->fd, buf, MIN(bufsize, bufrem));
548 		if (i == -1) {
549 			warn("zeroing image, %lld bytes to go",
550 			    (long long)bufrem);
551 			free(buf);
552 			return (-1);
553 		}
554 		bufrem -= i;
555 	}
556 	if (buf)
557 		free(buf);
558 
559 		/* make the file system */
560 	if (debug & DEBUG_FS_CREATE_IMAGE)
561 		printf("calling mkfs(\"%s\", ...)\n", image);
562 
563 	if (stampst.st_ino != 0)
564 		tstamp = stampst.st_ctime;
565 	else
566 		tstamp = start_time.tv_sec;
567 
568 	srandom(tstamp);
569 
570 	fs = ffs_mkfs(image, fsopts, tstamp);
571 	fsopts->superblock = (void *)fs;
572 	if (debug & DEBUG_FS_CREATE_IMAGE) {
573 		time_t t;
574 
575 		t = (time_t)((struct fs *)fsopts->superblock)->fs_time;
576 		printf("mkfs returned %p; fs_time %s",
577 		    fsopts->superblock, ctime(&t));
578 		printf("fs totals: nbfree %lld, nffree %lld, nifree %lld, ndir %lld\n",
579 		    (long long)fs->fs_cstotal.cs_nbfree,
580 		    (long long)fs->fs_cstotal.cs_nffree,
581 		    (long long)fs->fs_cstotal.cs_nifree,
582 		    (long long)fs->fs_cstotal.cs_ndir);
583 	}
584 
585 	if (fs->fs_cstotal.cs_nifree + (off_t)UFS_ROOTINO < fsopts->inodes) {
586 		warnx(
587 		"Image file `%s' has %lld free inodes; %lld are required.",
588 		    image,
589 		    (long long)(fs->fs_cstotal.cs_nifree + UFS_ROOTINO),
590 		    (long long)fsopts->inodes);
591 		return (-1);
592 	}
593 	return (fsopts->fd);
594 }
595 
596 
597 static void
ffs_size_dir(fsnode * root,fsinfo_t * fsopts)598 ffs_size_dir(fsnode *root, fsinfo_t *fsopts)
599 {
600 	struct direct	tmpdir;
601 	fsnode *	node;
602 	int		curdirsize, this;
603 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
604 
605 	/* node may be NULL (empty directory) */
606 	assert(fsopts != NULL);
607 	assert(ffs_opts != NULL);
608 
609 	if (debug & DEBUG_FS_SIZE_DIR)
610 		printf("ffs_size_dir: entry: bytes %lld inodes %lld\n",
611 		    (long long)fsopts->size, (long long)fsopts->inodes);
612 
613 #define	ADDDIRENT(e) do {						\
614 	tmpdir.d_namlen = strlen((e));					\
615 	this = DIRSIZ_SWAP(0, &tmpdir, 0);					\
616 	if (debug & DEBUG_FS_SIZE_DIR_ADD_DIRENT)			\
617 		printf("ADDDIRENT: was: %s (%d) this %d cur %d\n",	\
618 		    e, tmpdir.d_namlen, this, curdirsize);		\
619 	if (this + curdirsize > roundup(curdirsize, DIRBLKSIZ))		\
620 		curdirsize = roundup(curdirsize, DIRBLKSIZ);		\
621 	curdirsize += this;						\
622 	if (debug & DEBUG_FS_SIZE_DIR_ADD_DIRENT)			\
623 		printf("ADDDIRENT: now: %s (%d) this %d cur %d\n",	\
624 		    e, tmpdir.d_namlen, this, curdirsize);		\
625 } while (0);
626 
627 #define	ADDSIZE(x) do {							\
628 	if ((size_t)(x) < UFS_NDADDR * (size_t)ffs_opts->bsize) {	\
629 		fsopts->size += roundup((x), ffs_opts->fsize);		\
630 	} else {							\
631 		/* Count space consumed by indirecttion blocks. */	\
632 		fsopts->size +=	ffs_opts->bsize *			\
633 		    (howmany((x), UFS_NDADDR * ffs_opts->bsize) - 1);	\
634 		/*							\
635 		 * If the file is big enough to use indirect blocks,	\
636 		 * we allocate bsize block for trailing data.		\
637 		 */							\
638 		fsopts->size += roundup((x), ffs_opts->bsize);		\
639 	}								\
640 } while (0);
641 
642 	curdirsize = 0;
643 	for (node = root; node != NULL; node = node->next) {
644 		ADDDIRENT(node->name);
645 		if (node == root) {			/* we're at "." */
646 			assert(strcmp(node->name, ".") == 0);
647 			ADDDIRENT("..");
648 		} else if ((node->inode->flags & FI_SIZED) == 0) {
649 				/* don't count duplicate names */
650 			node->inode->flags |= FI_SIZED;
651 			if (debug & DEBUG_FS_SIZE_DIR_NODE)
652 				printf("ffs_size_dir: `%s' size %lld\n",
653 				    node->name,
654 				    (long long)node->inode->st.st_size);
655 			fsopts->inodes++;
656 			if (node->type == S_IFREG)
657 				ADDSIZE(node->inode->st.st_size);
658 			if (node->type == S_IFLNK) {
659 				size_t slen;
660 
661 				slen = strlen(node->symlink) + 1;
662 				if (slen >= (ffs_opts->version == 1 ?
663 						UFS1_MAXSYMLINKLEN :
664 						UFS2_MAXSYMLINKLEN))
665 					ADDSIZE(slen);
666 			}
667 		}
668 		if (node->type == S_IFDIR)
669 			ffs_size_dir(node->child, fsopts);
670 	}
671 	ADDSIZE(curdirsize);
672 
673 	if (debug & DEBUG_FS_SIZE_DIR)
674 		printf("ffs_size_dir: exit: size %lld inodes %lld\n",
675 		    (long long)fsopts->size, (long long)fsopts->inodes);
676 }
677 
678 static void *
ffs_build_dinode1(struct ufs1_dinode * dinp,dirbuf_t * dbufp,fsnode * cur,fsnode * root,fsinfo_t * fsopts)679 ffs_build_dinode1(struct ufs1_dinode *dinp, dirbuf_t *dbufp, fsnode *cur,
680 		 fsnode *root, fsinfo_t *fsopts)
681 {
682 	size_t slen;
683 	void *membuf;
684 	struct stat *st = stampst.st_ino != 0 ? &stampst : &cur->inode->st;
685 
686 	memset(dinp, 0, sizeof(*dinp));
687 	dinp->di_mode = cur->inode->st.st_mode;
688 	dinp->di_nlink = cur->inode->nlink;
689 	dinp->di_size = cur->inode->st.st_size;
690 #if HAVE_STRUCT_STAT_ST_FLAGS
691 	dinp->di_flags = cur->inode->st.st_flags;
692 #endif
693 	dinp->di_gen = random();
694 	dinp->di_uid = cur->inode->st.st_uid;
695 	dinp->di_gid = cur->inode->st.st_gid;
696 
697 	dinp->di_atime = st->st_atime;
698 	dinp->di_mtime = st->st_mtime;
699 	dinp->di_ctime = st->st_ctime;
700 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
701 	dinp->di_atimensec = st->st_atimensec;
702 	dinp->di_mtimensec = st->st_mtimensec;
703 	dinp->di_ctimensec = st->st_ctimensec;
704 #endif
705 		/* not set: di_db, di_ib, di_blocks, di_spare */
706 
707 	membuf = NULL;
708 	if (cur == root) {			/* "."; write dirbuf */
709 		membuf = dbufp->buf;
710 		dinp->di_size = dbufp->size;
711 	} else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) {
712 		dinp->di_size = 0;	/* a device */
713 		dinp->di_rdev =
714 		    ufs_rw32(cur->inode->st.st_rdev, fsopts->needswap);
715 	} else if (S_ISLNK(cur->type)) {	/* symlink */
716 		slen = strlen(cur->symlink);
717 		if (slen < UFS1_MAXSYMLINKLEN) {	/* short link */
718 			memcpy(dinp->di_shortlink, cur->symlink, slen);
719 		} else
720 			membuf = cur->symlink;
721 		dinp->di_size = slen;
722 	}
723 	return membuf;
724 }
725 
726 static void *
ffs_build_dinode2(struct ufs2_dinode * dinp,dirbuf_t * dbufp,fsnode * cur,fsnode * root,fsinfo_t * fsopts)727 ffs_build_dinode2(struct ufs2_dinode *dinp, dirbuf_t *dbufp, fsnode *cur,
728 		 fsnode *root, fsinfo_t *fsopts)
729 {
730 	size_t slen;
731 	void *membuf;
732 	struct stat *st = stampst.st_ino != 0 ? &stampst : &cur->inode->st;
733 
734 	memset(dinp, 0, sizeof(*dinp));
735 	dinp->di_mode = cur->inode->st.st_mode;
736 	dinp->di_nlink = cur->inode->nlink;
737 	dinp->di_size = cur->inode->st.st_size;
738 #if HAVE_STRUCT_STAT_ST_FLAGS
739 	dinp->di_flags = cur->inode->st.st_flags;
740 #endif
741 	dinp->di_gen = random();
742 	dinp->di_uid = cur->inode->st.st_uid;
743 	dinp->di_gid = cur->inode->st.st_gid;
744 
745 	dinp->di_atime = st->st_atime;
746 	dinp->di_mtime = st->st_mtime;
747 	dinp->di_ctime = st->st_ctime;
748 #if HAVE_STRUCT_STAT_BIRTHTIME
749 	dinp->di_birthtime = st->st_birthtime;
750 #else
751 	dinp->di_birthtime = st->st_ctime;
752 #endif
753 #if HAVE_STRUCT_STAT_ST_MTIMENSEC
754 	dinp->di_atimensec = st->st_atimensec;
755 	dinp->di_mtimensec = st->st_mtimensec;
756 	dinp->di_ctimensec = st->st_ctimensec;
757 #if HAVE_STRUCT_STAT_BIRTHTIME
758 	dinp->di_birthnsec = st->st_birthtimensec;
759 #else
760 	dinp->di_birthnsec = st->st_ctimensec;
761 #endif
762 #endif
763 
764 		/* not set: di_db, di_ib, di_blocks, di_spare */
765 
766 	membuf = NULL;
767 	if (cur == root) {			/* "."; write dirbuf */
768 		membuf = dbufp->buf;
769 		dinp->di_size = dbufp->size;
770 	} else if (S_ISBLK(cur->type) || S_ISCHR(cur->type)) {
771 		dinp->di_size = 0;	/* a device */
772 		dinp->di_rdev =
773 		    ufs_rw64(cur->inode->st.st_rdev, fsopts->needswap);
774 	} else if (S_ISLNK(cur->type)) {	/* symlink */
775 		slen = strlen(cur->symlink);
776 		if (slen < UFS2_MAXSYMLINKLEN) {	/* short link */
777 			memcpy(dinp->di_shortlink, cur->symlink, slen);
778 		} else
779 			membuf = cur->symlink;
780 		dinp->di_size = slen;
781 	}
782 	return membuf;
783 }
784 
785 static int
ffs_populate_dir(const char * dir,fsnode * root,fsinfo_t * fsopts)786 ffs_populate_dir(const char *dir, fsnode *root, fsinfo_t *fsopts)
787 {
788 	fsnode		*cur;
789 	dirbuf_t	dirbuf;
790 	union dinode	din;
791 	void		*membuf;
792 	char		path[MAXPATHLEN + 1];
793 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
794 
795 	assert(dir != NULL);
796 	assert(root != NULL);
797 	assert(fsopts != NULL);
798 	assert(ffs_opts != NULL);
799 
800 	(void)memset(&dirbuf, 0, sizeof(dirbuf));
801 
802 	if (debug & DEBUG_FS_POPULATE)
803 		printf("ffs_populate_dir: PASS 1  dir %s node %p\n", dir, root);
804 
805 		/*
806 		 * pass 1: allocate inode numbers, build directory `file'
807 		 */
808 	for (cur = root; cur != NULL; cur = cur->next) {
809 		if ((cur->inode->flags & FI_ALLOCATED) == 0) {
810 			cur->inode->flags |= FI_ALLOCATED;
811 			if (cur == root && cur->parent != NULL)
812 				cur->inode->ino = cur->parent->inode->ino;
813 			else {
814 				cur->inode->ino = fsopts->curinode;
815 				fsopts->curinode++;
816 			}
817 		}
818 		ffs_make_dirbuf(&dirbuf, cur->name, cur, fsopts->needswap);
819 		if (cur == root) {		/* we're at "."; add ".." */
820 			ffs_make_dirbuf(&dirbuf, "..",
821 			    cur->parent == NULL ? cur : cur->parent->first,
822 			    fsopts->needswap);
823 			root->inode->nlink++;	/* count my parent's link */
824 		} else if (cur->child != NULL)
825 			root->inode->nlink++;	/* count my child's link */
826 
827 		/*
828 		 * XXX	possibly write file and long symlinks here,
829 		 *	ensuring that blocks get written before inodes?
830 		 *	otoh, this isn't a real filesystem, so who
831 		 *	cares about ordering? :-)
832 		 */
833 	}
834 	if (debug & DEBUG_FS_POPULATE_DIRBUF)
835 		ffs_dump_dirbuf(&dirbuf, dir, fsopts->needswap);
836 
837 		/*
838 		 * pass 2: write out dirbuf, then non-directories at this level
839 		 */
840 	if (debug & DEBUG_FS_POPULATE)
841 		printf("ffs_populate_dir: PASS 2  dir %s\n", dir);
842 	for (cur = root; cur != NULL; cur = cur->next) {
843 		if (cur->inode->flags & FI_WRITTEN)
844 			continue;		/* skip hard-linked entries */
845 		cur->inode->flags |= FI_WRITTEN;
846 
847 		if (cur->contents == NULL) {
848 			if (snprintf(path, sizeof(path), "%s/%s/%s", cur->root,
849 			    cur->path, cur->name) >= (int)sizeof(path))
850 				errx(1, "Pathname too long.");
851 		}
852 
853 		if (cur->child != NULL)
854 			continue;		/* child creates own inode */
855 
856 				/* build on-disk inode */
857 		if (ffs_opts->version == 1)
858 			membuf = ffs_build_dinode1(&din.ffs1_din, &dirbuf, cur,
859 			    root, fsopts);
860 		else
861 			membuf = ffs_build_dinode2(&din.ffs2_din, &dirbuf, cur,
862 			    root, fsopts);
863 
864 		if (debug & DEBUG_FS_POPULATE_NODE) {
865 			printf("ffs_populate_dir: writing ino %d, %s",
866 			    cur->inode->ino, inode_type(cur->type));
867 			if (cur->inode->nlink > 1)
868 				printf(", nlink %d", cur->inode->nlink);
869 			putchar('\n');
870 		}
871 
872 		if (membuf != NULL) {
873 			ffs_write_file(&din, cur->inode->ino, membuf, fsopts);
874 		} else if (S_ISREG(cur->type)) {
875 			ffs_write_file(&din, cur->inode->ino,
876 			    (cur->contents) ?  cur->contents : path, fsopts);
877 		} else {
878 			assert (! S_ISDIR(cur->type));
879 			ffs_write_inode(&din, cur->inode->ino, fsopts);
880 		}
881 	}
882 
883 		/*
884 		 * pass 3: write out sub-directories
885 		 */
886 	if (debug & DEBUG_FS_POPULATE)
887 		printf("ffs_populate_dir: PASS 3  dir %s\n", dir);
888 	for (cur = root; cur != NULL; cur = cur->next) {
889 		if (cur->child == NULL)
890 			continue;
891 		if ((size_t)snprintf(path, sizeof(path), "%s/%s", dir,
892 		    cur->name) >= sizeof(path))
893 			errx(1, "Pathname too long.");
894 		if (! ffs_populate_dir(path, cur->child, fsopts))
895 			return (0);
896 	}
897 
898 	if (debug & DEBUG_FS_POPULATE)
899 		printf("ffs_populate_dir: DONE dir %s\n", dir);
900 
901 		/* cleanup */
902 	if (dirbuf.buf != NULL)
903 		free(dirbuf.buf);
904 	return (1);
905 }
906 
907 
908 static void
ffs_write_file(union dinode * din,uint32_t ino,void * buf,fsinfo_t * fsopts)909 ffs_write_file(union dinode *din, uint32_t ino, void *buf, fsinfo_t *fsopts)
910 {
911 	int	isfile, ffd;
912 	char	*fbuf, *p;
913 	off_t	bufleft, chunk, offset;
914 	ssize_t nread;
915 	struct inode	in;
916 	struct m_buf *	bp;
917 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
918 	struct m_vnode vp = { fsopts, NULL };
919 
920 	assert (din != NULL);
921 	assert (buf != NULL);
922 	assert (fsopts != NULL);
923 	assert (ffs_opts != NULL);
924 
925 	isfile = S_ISREG(DIP(din, mode));
926 	fbuf = NULL;
927 	ffd = -1;
928 	p = NULL;
929 
930 	in.i_fs = (struct fs *)fsopts->superblock;
931 	in.i_devvp = (void *)&vp;
932 
933 	if (debug & DEBUG_FS_WRITE_FILE) {
934 		printf(
935 		    "ffs_write_file: ino %u, din %p, isfile %d, %s, size %lld",
936 		    ino, din, isfile, inode_type(DIP(din, mode) & S_IFMT),
937 		    (long long)DIP(din, size));
938 		if (isfile)
939 			printf(", file '%s'\n", (char *)buf);
940 		else
941 			printf(", buffer %p\n", buf);
942 	}
943 
944 	in.i_number = ino;
945 	in.i_size = DIP(din, size);
946 	if (ffs_opts->version == 1)
947 		memcpy(&in.i_din.ffs1_din, &din->ffs1_din,
948 		    sizeof(in.i_din.ffs1_din));
949 	else
950 		memcpy(&in.i_din.ffs2_din, &din->ffs2_din,
951 		    sizeof(in.i_din.ffs2_din));
952 
953 	if (DIP(din, size) == 0)
954 		goto write_inode_and_leave;		/* mmm, cheating */
955 
956 	if (isfile) {
957 		fbuf = emalloc(ffs_opts->bsize);
958 		if ((ffd = open((char *)buf, O_RDONLY)) == -1) {
959 			err(EXIT_FAILURE, "Can't open `%s' for reading", (char *)buf);
960 		}
961 	} else {
962 		p = buf;
963 	}
964 
965 	chunk = 0;
966 	for (bufleft = DIP(din, size); bufleft > 0; bufleft -= chunk) {
967 		chunk = MIN(bufleft, ffs_opts->bsize);
968 		if (!isfile)
969 			;
970 		else if ((nread = read(ffd, fbuf, chunk)) == -1)
971 			err(EXIT_FAILURE, "Reading `%s', %lld bytes to go",
972 			    (char *)buf, (long long)bufleft);
973 		else if (nread != chunk)
974 			errx(EXIT_FAILURE, "Reading `%s', %lld bytes to go, "
975 			    "read %zd bytes, expected %ju bytes, does "
976 			    "metalog size= attribute mismatch source size?",
977 			    (char *)buf, (long long)bufleft, nread,
978 			    (uintmax_t)chunk);
979 		else
980 			p = fbuf;
981 		offset = DIP(din, size) - bufleft;
982 		if (debug & DEBUG_FS_WRITE_FILE_BLOCK)
983 			printf(
984 		"ffs_write_file: write %p offset %lld size %lld left %lld\n",
985 			    p, (long long)offset,
986 			    (long long)chunk, (long long)bufleft);
987 	/*
988 	 * XXX	if holey support is desired, do the check here
989 	 *
990 	 * XXX	might need to write out last bit in fragroundup
991 	 *	sized chunk. however, ffs_balloc() handles this for us
992 	 */
993 		errno = ffs_balloc(&in, offset, chunk, &bp);
994  bad_ffs_write_file:
995 		if (errno != 0)
996 			err(1,
997 			    "Writing inode %d (%s), bytes %lld + %lld",
998 			    ino,
999 			    isfile ? (char *)buf :
1000 			      inode_type(DIP(din, mode) & S_IFMT),
1001 			    (long long)offset, (long long)chunk);
1002 		memcpy(bp->b_data, p, chunk);
1003 		errno = bwrite(bp);
1004 		if (errno != 0)
1005 			goto bad_ffs_write_file;
1006 		if (!isfile)
1007 			p += chunk;
1008 	}
1009 
1010  write_inode_and_leave:
1011 	ffs_write_inode(&in.i_din, in.i_number, fsopts);
1012 	if (fbuf)
1013 		free(fbuf);
1014 	if (ffd != -1)
1015 		close(ffd);
1016 }
1017 
1018 
1019 static void
ffs_dump_dirbuf(dirbuf_t * dbuf,const char * dir,int needswap)1020 ffs_dump_dirbuf(dirbuf_t *dbuf, const char *dir, int needswap)
1021 {
1022 	doff_t		i;
1023 	struct direct	*de;
1024 	uint16_t	reclen;
1025 
1026 	assert (dbuf != NULL);
1027 	assert (dir != NULL);
1028 	printf("ffs_dump_dirbuf: dir %s size %d cur %d\n",
1029 	    dir, dbuf->size, dbuf->cur);
1030 
1031 	for (i = 0; i < dbuf->size; ) {
1032 		de = (struct direct *)(dbuf->buf + i);
1033 		reclen = ufs_rw16(de->d_reclen, needswap);
1034 		printf(
1035 	    " inode %4d %7s offset %4d reclen %3d namlen %3d name %s\n",
1036 		    ufs_rw32(de->d_ino, needswap),
1037 		    inode_type(DTTOIF(de->d_type)), i, reclen,
1038 		    de->d_namlen, de->d_name);
1039 		i += reclen;
1040 		assert(reclen > 0);
1041 	}
1042 }
1043 
1044 static void
ffs_make_dirbuf(dirbuf_t * dbuf,const char * name,fsnode * node,int needswap)1045 ffs_make_dirbuf(dirbuf_t *dbuf, const char *name, fsnode *node, int needswap)
1046 {
1047 	struct direct	de, *dp;
1048 	uint16_t	llen, reclen;
1049 	u_char		*newbuf;
1050 
1051 	assert (dbuf != NULL);
1052 	assert (name != NULL);
1053 	assert (node != NULL);
1054 					/* create direct entry */
1055 	(void)memset(&de, 0, sizeof(de));
1056 	de.d_ino = ufs_rw32(node->inode->ino, needswap);
1057 	de.d_type = IFTODT(node->type);
1058 	de.d_namlen = (uint8_t)strlen(name);
1059 	strcpy(de.d_name, name);
1060 	reclen = DIRSIZ_SWAP(0, &de, needswap);
1061 	de.d_reclen = ufs_rw16(reclen, needswap);
1062 
1063 	dp = (struct direct *)(dbuf->buf + dbuf->cur);
1064 	llen = 0;
1065 	if (dp != NULL)
1066 		llen = DIRSIZ_SWAP(0, dp, needswap);
1067 
1068 	if (debug & DEBUG_FS_MAKE_DIRBUF)
1069 		printf(
1070 		    "ffs_make_dirbuf: dbuf siz %d cur %d lastlen %d\n"
1071 		    "  ino %d type %d reclen %d namlen %d name %.30s\n",
1072 		    dbuf->size, dbuf->cur, llen,
1073 		    ufs_rw32(de.d_ino, needswap), de.d_type, reclen,
1074 		    de.d_namlen, de.d_name);
1075 
1076 	if (reclen + dbuf->cur + llen > roundup(dbuf->size, DIRBLKSIZ)) {
1077 		if (debug & DEBUG_FS_MAKE_DIRBUF)
1078 			printf("ffs_make_dirbuf: growing buf to %d\n",
1079 			    dbuf->size + DIRBLKSIZ);
1080 		newbuf = erealloc(dbuf->buf, dbuf->size + DIRBLKSIZ);
1081 		dbuf->buf = newbuf;
1082 		dbuf->size += DIRBLKSIZ;
1083 		memset(dbuf->buf + dbuf->size - DIRBLKSIZ, 0, DIRBLKSIZ);
1084 		dbuf->cur = dbuf->size - DIRBLKSIZ;
1085 	} else if (dp) {			/* shrink end of previous */
1086 		dp->d_reclen = ufs_rw16(llen,needswap);
1087 		dbuf->cur += llen;
1088 	}
1089 	dp = (struct direct *)(dbuf->buf + dbuf->cur);
1090 	memcpy(dp, &de, reclen);
1091 	dp->d_reclen = ufs_rw16(dbuf->size - dbuf->cur, needswap);
1092 }
1093 
1094 /*
1095  * cribbed from sys/ufs/ffs/ffs_alloc.c
1096  */
1097 static void
ffs_write_inode(union dinode * dp,uint32_t ino,const fsinfo_t * fsopts)1098 ffs_write_inode(union dinode *dp, uint32_t ino, const fsinfo_t *fsopts)
1099 {
1100 	char		*buf;
1101 	struct ufs1_dinode *dp1;
1102 	struct ufs2_dinode *dp2, *dip;
1103 	struct cg	*cgp;
1104 	struct fs	*fs;
1105 	int		cg, cgino;
1106 	uint32_t	i;
1107 	daddr_t		d;
1108 	char		sbbuf[FFS_MAXBSIZE];
1109 	uint32_t	initediblk;
1110 	ffs_opt_t	*ffs_opts = fsopts->fs_specific;
1111 
1112 	assert (dp != NULL);
1113 	assert (ino > 0);
1114 	assert (fsopts != NULL);
1115 	assert (ffs_opts != NULL);
1116 
1117 	fs = (struct fs *)fsopts->superblock;
1118 	cg = ino_to_cg(fs, ino);
1119 	cgino = ino % fs->fs_ipg;
1120 	if (debug & DEBUG_FS_WRITE_INODE)
1121 		printf("ffs_write_inode: din %p ino %u cg %d cgino %d\n",
1122 		    dp, ino, cg, cgino);
1123 
1124 	ffs_rdfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf,
1125 	    fsopts);
1126 	cgp = (struct cg *)sbbuf;
1127 	if (!cg_chkmagic_swap(cgp, fsopts->needswap))
1128 		errx(1, "ffs_write_inode: cg %d: bad magic number", cg);
1129 
1130 	assert (isclr(cg_inosused_swap(cgp, fsopts->needswap), cgino));
1131 
1132 	buf = emalloc(fs->fs_bsize);
1133 	dp1 = (struct ufs1_dinode *)buf;
1134 	dp2 = (struct ufs2_dinode *)buf;
1135 
1136 	if (fs->fs_cstotal.cs_nifree == 0)
1137 		errx(1, "ffs_write_inode: fs out of inodes for ino %u",
1138 		    ino);
1139 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
1140 		errx(1,
1141 		    "ffs_write_inode: cg %d out of inodes for ino %u",
1142 		    cg, ino);
1143 	setbit(cg_inosused_swap(cgp, fsopts->needswap), cgino);
1144 	ufs_add32(cgp->cg_cs.cs_nifree, -1, fsopts->needswap);
1145 	fs->fs_cstotal.cs_nifree--;
1146 	fs->fs_cs(fs, cg).cs_nifree--;
1147 	if (S_ISDIR(DIP(dp, mode))) {
1148 		ufs_add32(cgp->cg_cs.cs_ndir, 1, fsopts->needswap);
1149 		fs->fs_cstotal.cs_ndir++;
1150 		fs->fs_cs(fs, cg).cs_ndir++;
1151 	}
1152 
1153 	/*
1154 	 * Initialize inode blocks on the fly for UFS2.
1155 	 */
1156 	initediblk = ufs_rw32(cgp->cg_initediblk, fsopts->needswap);
1157 	while (ffs_opts->version == 2 && cgino + INOPB(fs) > initediblk &&
1158 	    initediblk < ufs_rw32(cgp->cg_niblk, fsopts->needswap)) {
1159 		memset(buf, 0, fs->fs_bsize);
1160 		dip = (struct ufs2_dinode *)buf;
1161 		for (i = 0; i < INOPB(fs); i++) {
1162 			dip->di_gen = random();
1163 			dip++;
1164 		}
1165 		ffs_wtfs(fsbtodb(fs, ino_to_fsba(fs,
1166 				  cg * fs->fs_ipg + initediblk)),
1167 		    fs->fs_bsize, buf, fsopts);
1168 		initediblk += INOPB(fs);
1169 		cgp->cg_initediblk = ufs_rw32(initediblk, fsopts->needswap);
1170 	}
1171 
1172 
1173 	ffs_wtfs(fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize, &sbbuf,
1174 	    fsopts);
1175 
1176 					/* now write inode */
1177 	d = fsbtodb(fs, ino_to_fsba(fs, ino));
1178 	ffs_rdfs(d, fs->fs_bsize, buf, fsopts);
1179 	if (fsopts->needswap) {
1180 		if (ffs_opts->version == 1)
1181 			ffs_dinode1_swap(&dp->ffs1_din,
1182 			    &dp1[ino_to_fsbo(fs, ino)]);
1183 		else
1184 			ffs_dinode2_swap(&dp->ffs2_din,
1185 			    &dp2[ino_to_fsbo(fs, ino)]);
1186 	} else {
1187 		if (ffs_opts->version == 1)
1188 			dp1[ino_to_fsbo(fs, ino)] = dp->ffs1_din;
1189 		else
1190 			dp2[ino_to_fsbo(fs, ino)] = dp->ffs2_din;
1191 	}
1192 	ffs_wtfs(d, fs->fs_bsize, buf, fsopts);
1193 	free(buf);
1194 }
1195 
1196 void
panic(const char * fmt,...)1197 panic(const char *fmt, ...)
1198 {
1199 	va_list ap;
1200 
1201 	va_start(ap, fmt);
1202 	vwarnx(fmt, ap);
1203 	va_end(ap);
1204 	exit(1);
1205 }
1206