xref: /netbsd-src/usr.sbin/makefs/udf.c (revision a1f170f5375dc1d5da7dfc6c367ab7b02b595668)
1 /* $NetBSD: udf.c,v 1.8 2013/08/06 12:19:34 reinoud Exp $ */
2 
3 /*
4  * Copyright (c) 2006, 2008, 2013 Reinoud Zandijk
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  */
28 #if HAVE_NBTOOL_CONFIG_H
29 #include "nbtool_config.h"
30 #endif
31 
32 #include <sys/cdefs.h>
33 __RCSID("$NetBSD: udf.c,v 1.8 2013/08/06 12:19:34 reinoud Exp $");
34 
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <time.h>
40 #include <assert.h>
41 #include <err.h>
42 #include <unistd.h>
43 #include <fcntl.h>
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/stat.h>
47 #include <util.h>
48 
49 #if !HAVE_NBTOOL_CONFIG_H
50 #define _EXPOSE_MMC
51 #include <sys/cdio.h>
52 #else
53 #include "udf/cdio_mmc_structs.h"
54 #endif
55 
56 #include "makefs.h"
57 #include "udf_create.h"
58 #include "udf_write.h"
59 #include "newfs_udf.h"
60 
61 
62 /*
63  * Note: due to the setup of the newfs code, the current state of the program
64  * and its options are helt in a few global variables. The FS specific parts
65  * are in a global `context' structure.
66  */
67 
68 /* global variables describing disc and format requests */
69 int	 fd;				/* device: file descriptor */
70 char	*dev;				/* device: name		   */
71 struct mmc_discinfo mmc_discinfo;	/* device: disc info	   */
72 
73 char	*format_str;			/* format: string representation */
74 int	 format_flags;			/* format: attribute flags	 */
75 int	 media_accesstype;		/* derived from current mmc cap  */
76 int	 check_surface;			/* for rewritables               */
77 int	 imagefile_secsize;		/* for files			 */
78 
79 int	 display_progressbar;
80 
81 int	 wrtrack_skew;
82 float	 meta_fract = (float) UDF_META_PERC / 100.0;
83 
84 int	 mmc_profile;			/* emulated profile */
85 int	 req_enable, req_disable;
86 
87 
88 /* --------------------------------------------------------------------- */
89 
90 int
91 udf_write_sector(void *sector, uint32_t location)
92 {
93 	uint64_t wpos;
94 	ssize_t ret;
95 
96 	wpos = (uint64_t) location * context.sector_size;
97 	ret = pwrite(fd, sector, context.sector_size, wpos);
98 	if (ret == -1)
99 		return errno;
100 	if (ret < context.sector_size)
101 		return EIO;
102 	return 0;
103 }
104 
105 
106 /* not implemented for files */
107 int
108 udf_surface_check(void)
109 {
110 	return 0;
111 }
112 
113 
114 /*
115  * mmc_discinfo and mmc_trackinfo readers modified from origional in udf main
116  * code in sys/fs/udf/
117  */
118 
119 #ifdef DEBUG
120 static void
121 udf_dump_discinfo(struct mmc_discinfo *di)
122 {
123 	char bits[128];
124 
125 	printf("Device/media info  :\n");
126 	printf("\tMMC profile        0x%02x\n", di->mmc_profile);
127 	printf("\tderived class      %d\n", di->mmc_class);
128 	printf("\tsector size        %d\n", di->sector_size);
129 	printf("\tdisc state         %d\n", di->disc_state);
130 	printf("\tlast ses state     %d\n", di->last_session_state);
131 	printf("\tbg format state    %d\n", di->bg_format_state);
132 	printf("\tfrst track         %d\n", di->first_track);
133 	printf("\tfst on last ses    %d\n", di->first_track_last_session);
134 	printf("\tlst on last ses    %d\n", di->last_track_last_session);
135 	printf("\tlink block penalty %d\n", di->link_block_penalty);
136 	snprintb(bits, sizeof(bits), MMC_DFLAGS_FLAGBITS,
137 			(uint64_t) di->disc_flags);
138 	printf("\tdisc flags         %s\n", bits);
139 	printf("\tdisc id            %x\n", di->disc_id);
140 	printf("\tdisc barcode       %"PRIx64"\n", di->disc_barcode);
141 
142 	printf("\tnum sessions       %d\n", di->num_sessions);
143 	printf("\tnum tracks         %d\n", di->num_tracks);
144 
145 	snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cur);
146 	printf("\tcapabilities cur   %s\n", bits);
147 	snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cap);
148 	printf("\tcapabilities cap   %s\n", bits);
149 	printf("\n");
150 	printf("\tlast_possible_lba  %d\n", di->last_possible_lba);
151 	printf("\n");
152 }
153 #else
154 #define udf_dump_discinfo(a);
155 #endif
156 
157 /* --------------------------------------------------------------------- */
158 
159 static int
160 udf_emulate_discinfo(fsinfo_t *fsopts, struct mmc_discinfo *di,
161 		int mmc_emuprofile)
162 {
163 	off_t sectors;
164 
165 	memset(di, 0, sizeof(*di));
166 
167 	/* file support */
168 	if ((mmc_emuprofile != 0x01) && (fsopts->sectorsize != 2048))
169 		warnx("cd/dvd/bd sectorsize is not set to default 2048");
170 
171 	sectors = fsopts->size / fsopts->sectorsize;
172 
173 	/* commons */
174 	di->mmc_profile		= mmc_emuprofile;
175 	di->disc_state		= MMC_STATE_CLOSED;
176 	di->last_session_state	= MMC_STATE_CLOSED;
177 	di->bg_format_state	= MMC_BGFSTATE_COMPLETED;
178 	di->link_block_penalty	= 0;
179 
180 	di->disc_flags = MMC_DFLAGS_UNRESTRICTED;
181 
182 	di->last_possible_lba = sectors - 1;
183 	di->sector_size       = fsopts->sectorsize;
184 
185 	di->num_sessions = 1;
186 	di->num_tracks   = 1;
187 
188 	di->first_track  = 1;
189 	di->first_track_last_session = di->last_track_last_session = 1;
190 
191 	di->mmc_cur = MMC_CAP_RECORDABLE | MMC_CAP_ZEROLINKBLK;
192 	switch (mmc_emuprofile) {
193 	case 0x00:	/* unknown, treat as CDROM */
194 	case 0x08:	/* CDROM */
195 	case 0x10:	/* DVDROM */
196 	case 0x40:	/* BDROM */
197 		req_enable |= FORMAT_READONLY;
198 		/* FALLTROUGH */
199 	case 0x01:	/* disc */
200 		/* set up a disc info profile for partitions/files */
201 		di->mmc_class	= MMC_CLASS_DISC;
202 		di->mmc_cur    |= MMC_CAP_REWRITABLE | MMC_CAP_HW_DEFECTFREE;
203 		break;
204 	case 0x09:	/* CD-R */
205 		di->mmc_class	= MMC_CLASS_CD;
206 		di->mmc_cur    |= MMC_CAP_SEQUENTIAL;
207 		di->disc_state  = MMC_STATE_EMPTY;
208 		break;
209 	case 0x0a:	/* CD-RW + CD-MRW (regretably) */
210 		di->mmc_class	= MMC_CLASS_CD;
211 		di->mmc_cur    |= MMC_CAP_REWRITABLE;
212 		break;
213 	case 0x13:	/* DVD-RW */
214 		di->mmc_class	= MMC_CLASS_DVD;
215 		di->mmc_cur    |= MMC_CAP_REWRITABLE;
216 		break;
217 	case 0x11:	/* DVD-R */
218 	case 0x14:	/* DVD-RW sequential */
219 	case 0x1b:	/* DVD+R */
220 	case 0x2b:	/* DVD+R DL */
221 	case 0x51:	/* HD DVD-R */
222 		di->mmc_class	= MMC_CLASS_DVD;
223 		di->mmc_cur    |= MMC_CAP_SEQUENTIAL;
224 		di->disc_state  = MMC_STATE_EMPTY;
225 		break;
226 	case 0x41:	/* BD-R */
227 		di->mmc_class   = MMC_CLASS_BD;
228 		di->mmc_cur    |= MMC_CAP_SEQUENTIAL | MMC_CAP_HW_DEFECTFREE;
229 		di->disc_state  = MMC_STATE_EMPTY;
230 		break;
231 	case 0x43:	/* BD-RE */
232 		di->mmc_class   = MMC_CLASS_BD;
233 		di->mmc_cur    |= MMC_CAP_REWRITABLE | MMC_CAP_HW_DEFECTFREE;
234 		break;
235 	default:
236 		err(EINVAL, "makefs_udf: unknown or unimplemented device type");
237 		return EINVAL;
238 	}
239 	di->mmc_cap    = di->mmc_cur;
240 
241 	udf_dump_discinfo(di);
242 	return 0;
243 }
244 
245 
246 int
247 udf_update_trackinfo(struct mmc_discinfo *di, struct mmc_trackinfo *ti)
248 {
249 	/* discs partition support */
250 	if (ti->tracknr != 1)
251 		return EIO;
252 
253 	/* create fake ti */
254 	ti->sessionnr  = 1;
255 
256 	ti->track_mode = 0;	/* XXX */
257 	ti->data_mode  = 0;	/* XXX */
258 	ti->flags = MMC_TRACKINFO_LRA_VALID | MMC_TRACKINFO_NWA_VALID;
259 
260 	ti->track_start    = 0;
261 	ti->packet_size    = 32;	/* take sensible default */
262 
263 	ti->track_size    = di->last_possible_lba;
264 	ti->next_writable = di->last_possible_lba;
265 	ti->last_recorded = ti->next_writable;
266 	ti->free_blocks   = 0;
267 
268 	return 0;
269 }
270 
271 #define OPT_STR(letter, name, desc)  \
272 	{ letter, name, NULL, OPT_STRBUF, 0, 0, desc }
273 
274 #define OPT_NUM(letter, name, field, min, max, desc) \
275 	{ letter, name, &diskStructure->field, \
276 	  sizeof(diskStructure->field) == 8 ? OPT_INT64 : \
277 	  (sizeof(diskStructure->field) == 4 ? OPT_INT32 : \
278 	  (sizeof(diskStructure->field) == 2 ? OPT_INT16 : OPT_INT8)), \
279 	  min, max, desc }
280 
281 #define OPT_BOOL(letter, name, field, desc) \
282 	OPT_NUM(letter, name, field, 0, 1, desc)
283 
284 void
285 udf_prep_opts(fsinfo_t *fsopts)
286 {
287 	struct tm *tm;
288 	time_t now;
289 
290 	const option_t udf_options[] = {
291 		OPT_STR('T', "disctype", "disc type (cdrom,dvdrom,bdrom,"
292 			"dvdram,bdre,disk,cdr,dvdr,bdr,cdrw,dvdrw)"),
293 		OPT_STR('L', "loglabel", "\"logical volume name\""),
294 		OPT_STR('P', "discid",   "[\"volset name\"':']"
295 			"\"physical volume name\""),
296 		{ .name = NULL }
297 	};
298 
299 	/* initialise */
300 	format_str    = strdup("");
301 	req_enable    = req_disable = 0;
302 	format_flags  = FORMAT_INVALID;
303 	fsopts->sectorsize = 512;	/* minimum allowed sector size */
304 
305 	srandom((unsigned long) time(NULL));
306 
307 	mmc_profile = 0x01;		/* 'disc'/file */
308 
309 	udf_init_create_context();
310 	context.app_name  = APP_NAME;
311 	context.impl_name = IMPL_NAME;
312 	context.app_version_main = APP_VERSION_MAIN;
313 	context.app_version_sub  = APP_VERSION_SUB;
314 
315 	/* minimum and maximum UDF versions we advise */
316 	context.min_udf = 0x102;
317 	context.max_udf = 0x201;
318 
319 	/* use user's time zone as default */
320 	(void)time(&now);
321 	tm = localtime(&now);
322 	context.gmtoff = tm->tm_gmtoff;
323 
324 	/* return info */
325 	fsopts->fs_specific = NULL;
326 	fsopts->fs_options = copy_opts(udf_options);
327 }
328 
329 
330 void
331 udf_cleanup_opts(fsinfo_t *fsopts)
332 {
333 	free(fsopts->fs_options);
334 }
335 
336 
337 #define CDRSIZE    ((uint64_t)   700*1024*1024)	/* small approx */
338 #define CDRWSIZE   ((uint64_t)   576*1024*1024)	/* small approx */
339 #define DVDRSIZE   ((uint64_t)  4488*1024*1024)	/* small approx */
340 #define DVDRAMSIZE ((uint64_t)  4330*1024*1024)	/* small approx with spare */
341 #define DVDRWSIZE  ((uint64_t)  4482*1024*1024)	/* small approx */
342 #define BDRSIZE    ((uint64_t) 23866*1024*1024)	/* small approx */
343 #define BDRESIZE   ((uint64_t) 23098*1024*1024)	/* small approx */
344 
345 int
346 udf_parse_opts(const char *option, fsinfo_t *fsopts)
347 {
348 	option_t *udf_options = fsopts->fs_options;
349 	uint64_t stdsize;
350 	uint32_t set_sectorsize;
351 	const char *name, *desc;
352 	char buffer[1024], *buf, *colon;
353 	int i;
354 
355 	assert(option != NULL);
356 
357 	if (debug & DEBUG_FS_PARSE_OPTS)
358 		printf("udf_parse_opts: got `%s'\n", option);
359 
360 	i = set_option(udf_options, option, buffer, sizeof(buffer));
361 	if (i == -1)
362 		return 0;
363 
364 	if (udf_options[i].name == NULL)
365 		abort();
366 
367 	set_sectorsize = 0;
368 	stdsize = 0;
369 
370 	buf = buffer;
371 	name = udf_options[i].name;
372 	desc = udf_options[i].desc;
373 	switch (udf_options[i].letter) {
374 	case 'T':
375 		if (strcmp(buf, "cdrom") == 0) {
376 			mmc_profile = 0x00;
377 		} else if (strcmp(buf, "dvdrom") == 0) {
378 			mmc_profile = 0x10;
379 		} else if (strcmp(buf, "bdrom") == 0) {
380 			mmc_profile = 0x40;
381 		} else if (strcmp(buf, "dvdram") == 0) {
382 			mmc_profile = 0x12;
383 			stdsize = DVDRAMSIZE;
384 		} else if (strcmp(buf, "bdre") == 0) {
385 			mmc_profile = 0x43;
386 			stdsize = BDRESIZE;
387 		} else if (strcmp(buf, "disk") == 0) {
388 			mmc_profile = 0x01;
389 		} else if (strcmp(buf, "cdr") == 0) {
390 			mmc_profile = 0x09;
391 			stdsize = CDRSIZE;
392 		} else if (strcmp(buf, "dvdr") == 0) {
393 			mmc_profile = 0x1b;
394 			stdsize = DVDRSIZE;
395 		} else if (strcmp(buf, "bdr") == 0) {
396 			mmc_profile = 0x41;
397 			stdsize = BDRSIZE;
398 		} else if (strcmp(buf, "cdrw") == 0) {
399 			mmc_profile = 0x0a;
400 			stdsize = CDRWSIZE;
401 		} else if (strcmp(buf, "dvdrw") == 0) {
402 			mmc_profile = 0x13;
403 			stdsize = DVDRWSIZE;
404 		} else {
405 			errx(EINVAL, "Unknown or unimplemented disc format");
406 			return 0;
407 		}
408 		if (mmc_profile != 0x01)
409 			set_sectorsize = 2048;
410 		break;
411 	case 'L':
412 		if (context.logvol_name) free(context.logvol_name);
413 		context.logvol_name = strdup(buf);
414 		break;
415 	case 'P':
416 		if ((colon = strstr(buf, ":"))) {
417 			if (context.volset_name)
418 				free(context.volset_name);
419 			*colon = 0;
420 			context.volset_name = strdup(buf);
421 			buf = colon+1;
422 		}
423 		if (context.primary_name)
424 			free(context.primary_name);
425 		if ((strstr(buf, ":"))) {
426 			perror("primary name can't have ':' in its name");
427 			return 0;
428 		}
429 		context.primary_name = strdup(buf);
430 		break;
431 	}
432 	if (set_sectorsize)
433 		fsopts->sectorsize = set_sectorsize;
434 	if (stdsize)
435 		fsopts->size = stdsize;
436 	return 1;
437 }
438 
439 /* --------------------------------------------------------------------- */
440 
441 struct udf_stats {
442 	uint32_t nfiles;
443 	uint32_t ndirs;
444 	uint32_t ndescr;
445 	uint32_t nmetadatablocks;
446 	uint32_t ndatablocks;
447 };
448 
449 
450 /* node reference administration */
451 static void
452 udf_inc_link(union dscrptr *dscr)
453 {
454 	struct file_entry *fe;
455 	struct extfile_entry *efe;
456 
457 	if (udf_rw16(dscr->tag.id) == TAGID_FENTRY) {
458 		fe        = &dscr->fe;
459 		fe->link_cnt = udf_rw16(udf_rw16(fe->link_cnt) + 1);
460 	} else if (udf_rw16(dscr->tag.id) == TAGID_EXTFENTRY) {
461 		efe       = &dscr->efe;
462 		efe->link_cnt = udf_rw16(udf_rw16(efe->link_cnt) + 1);
463 	} else {
464 		errx(1, "Bad tag passed to udf_inc_link");
465 	}
466 }
467 
468 
469 static void
470 udf_set_link_cnt(union dscrptr *dscr, int num)
471 {
472 	struct file_entry *fe;
473 	struct extfile_entry *efe;
474 
475 	if (udf_rw16(dscr->tag.id) == TAGID_FENTRY) {
476 		fe        = &dscr->fe;
477 		fe->link_cnt = udf_rw16(num);
478 	} else if (udf_rw16(dscr->tag.id) == TAGID_EXTFENTRY) {
479 		efe       = &dscr->efe;
480 		efe->link_cnt = udf_rw16(num);
481 	} else {
482 		errx(1, "Bad tag passed to udf_set_link_cnt");
483 	}
484 }
485 
486 
487 static uint32_t
488 udf_datablocks(off_t sz)
489 {
490 	/* predictor if it can be written inside the node */
491 	if (sz < context.sector_size - UDF_EXTFENTRY_SIZE - 16)
492 		return 0;
493 
494 	return UDF_ROUNDUP(sz, context.sector_size) / context.sector_size;
495 }
496 
497 
498 static void
499 udf_prepare_fids(struct long_ad *dir_icb, struct long_ad *dirdata_icb,
500 		uint8_t *dirdata, uint32_t dirdata_size)
501 {
502 	struct fileid_desc *fid;
503 	struct long_ad     *icb;
504 	uint32_t fidsize, offset;
505 	uint32_t location;
506 
507 	if (udf_datablocks(dirdata_size) == 0) {
508 		/* going internal */
509 		icb = dir_icb;
510 	} else {
511 		/* external blocks to write to */
512 		icb = dirdata_icb;
513 	}
514 
515 	for (offset = 0; offset < dirdata_size; offset += fidsize) {
516 		/* for each FID: */
517 		fid = (struct fileid_desc *) (dirdata + offset);
518 		assert(udf_rw16(fid->tag.id) == TAGID_FID);
519 
520 		location  = udf_rw32(icb->loc.lb_num);
521 		location += offset / context.sector_size;
522 
523 		fid->tag.tag_loc = udf_rw32(location);
524 		udf_validate_tag_and_crc_sums((union dscrptr *) fid);
525 
526 		fidsize = udf_fidsize(fid);
527 	}
528 }
529 
530 static int
531 udf_file_inject_blob(union dscrptr *dscr,  uint8_t *blob, size_t size)
532 {
533 	struct icb_tag *icb;
534 	struct file_entry *fe;
535 	struct extfile_entry *efe;
536 	uint64_t inf_len, obj_size;
537 	uint32_t l_ea, l_ad;
538 	uint32_t free_space, desc_size;
539 	uint16_t crclen;
540 	uint8_t *data, *pos;
541 
542 	fe = NULL;
543 	efe = NULL;
544 	if (udf_rw16(dscr->tag.id) == TAGID_FENTRY) {
545 		fe        = &dscr->fe;
546 		data      = fe->data;
547 		l_ea      = udf_rw32(fe->l_ea);
548 		l_ad      = udf_rw32(fe->l_ad);
549 		icb       = &fe->icbtag;
550 		inf_len   = udf_rw64(fe->inf_len);
551 		obj_size  = 0;
552 		desc_size = sizeof(struct file_entry);
553 	} else if (udf_rw16(dscr->tag.id) == TAGID_EXTFENTRY) {
554 		efe       = &dscr->efe;
555 		data      = efe->data;
556 		l_ea      = udf_rw32(efe->l_ea);
557 		l_ad      = udf_rw32(efe->l_ad);
558 		icb       = &efe->icbtag;
559 		inf_len   = udf_rw64(efe->inf_len);
560 		obj_size  = udf_rw64(efe->obj_size);
561 		desc_size = sizeof(struct extfile_entry);
562 	} else {
563 		errx(1, "Bad tag passed to udf_file_inject_blob");
564 	}
565 	crclen = udf_rw16(dscr->tag.desc_crc_len);
566 
567 	/* calculate free space */
568 	free_space = context.sector_size - (l_ea + l_ad) - desc_size;
569 	if (udf_datablocks(size)) {
570 		assert(free_space < size);
571 		return 1;
572 	}
573 
574 	/* going internal */
575 	assert(l_ad == 0);
576 	assert((udf_rw16(icb->flags) & UDF_ICB_TAG_FLAGS_ALLOC_MASK) ==
577 			UDF_ICB_INTERN_ALLOC);
578 
579 	// assert(free_space >= size);
580 	pos = data + l_ea + l_ad;
581 	memcpy(pos, blob, size);
582 	l_ad   += size;
583 	crclen += size;
584 
585 	inf_len  += size;
586 	obj_size += size;
587 
588 	if (fe) {
589 		fe->l_ad = udf_rw32(l_ad);
590 		fe->inf_len = udf_rw64(inf_len);
591 	} else if (efe) {
592 		efe->l_ad = udf_rw32(l_ad);
593 		efe->inf_len  = udf_rw64(inf_len);
594 		efe->obj_size = udf_rw64(inf_len);
595 	}
596 
597 	/* make sure the header sums stays correct */
598 	dscr->tag.desc_crc_len = udf_rw16(crclen);
599 	udf_validate_tag_and_crc_sums(dscr);
600 
601 	return 0;
602 }
603 
604 
605 /* XXX no sparse file support */
606 static void
607 udf_append_file_mapping(union dscrptr *dscr, struct long_ad *piece)
608 {
609 	struct icb_tag *icb;
610 	struct file_entry *fe;
611 	struct extfile_entry *efe;
612 	struct long_ad *last_long, last_piece;
613 	struct short_ad *last_short, new_short;
614 	uint64_t inf_len, obj_size, logblks_rec;
615 	uint32_t l_ea, l_ad, size;
616 	uint32_t last_lb_num, piece_lb_num;
617 	uint32_t last_len, piece_len, last_flags;
618 	uint32_t rest_len, merge_len, last_end;
619 	uint16_t last_part_num, piece_part_num;
620 	uint16_t crclen, cur_alloc;
621 	uint8_t *data, *pos;
622 	const int short_len = sizeof(struct short_ad);
623 	const int long_len  = sizeof(struct long_ad);
624 	const int sector_size = context.sector_size;
625 	const int use_shorts = (context.data_part == context.metadata_part);
626 	uint64_t max_len = UDF_ROUNDDOWN(UDF_EXT_MAXLEN, sector_size);
627 
628 	if (udf_rw16(dscr->tag.id) == TAGID_FENTRY) {
629 		fe          = &dscr->fe;
630 		data        =    fe->data;
631 		l_ea        = fe->l_ea;
632 		l_ad        = udf_rw32(fe->l_ad);
633 		icb         = &fe->icbtag;
634 		inf_len     = udf_rw64(fe->inf_len);
635 		logblks_rec = udf_rw64(fe->logblks_rec);
636 		obj_size = 0;
637 	} else if (udf_rw16(dscr->tag.id) == TAGID_EXTFENTRY) {
638 		efe         = &dscr->efe;
639 		data        = efe->data;
640 		l_ea        = efe->l_ea;
641 		l_ad        = udf_rw32(efe->l_ad);
642 		icb         = &efe->icbtag;
643 		inf_len     = udf_rw64(efe->inf_len);
644 		obj_size    = udf_rw64(efe->obj_size);
645 		logblks_rec = udf_rw64(efe->logblks_rec);
646 	} else {
647 		errx(1, "Bad tag passed to udf_file_append_blob");
648 	}
649 	crclen = udf_rw16(dscr->tag.desc_crc_len);
650 
651 	pos = data + l_ea;
652 	cur_alloc = udf_rw16(icb->flags);
653 	size = UDF_EXT_LEN(udf_rw32(piece->len));
654 
655 	/* extract last entry as a long_ad */
656 	memset(&last_piece, 0, sizeof(last_piece));
657 	last_len      = 0;
658 	last_lb_num   = 0;
659 	last_part_num = 0;
660 	if (l_ad != 0) {
661 		if (use_shorts) {
662 			assert(cur_alloc == UDF_ICB_SHORT_ALLOC);
663 			pos += l_ad - short_len;
664 			last_short   = (struct short_ad *) pos;
665 			last_lb_num  = udf_rw32(last_short->lb_num);
666 			last_part_num = udf_rw16(piece->loc.part_num);
667 			last_len     = UDF_EXT_LEN(udf_rw32(last_short->len));
668 			last_flags   = UDF_EXT_FLAGS(udf_rw32(last_short->len));
669 		} else {
670 			assert(cur_alloc == UDF_ICB_LONG_ALLOC);
671 			pos += l_ad - long_len;
672 			last_long    = (struct long_ad *) pos;
673 			last_lb_num  = udf_rw32(last_long->loc.lb_num);
674 			last_part_num = udf_rw16(last_long->loc.part_num);
675 			last_len     = UDF_EXT_LEN(udf_rw32(last_long->len));
676 			last_flags   = UDF_EXT_FLAGS(udf_rw32(last_long->len));
677 		}
678 	}
679 
680 	piece_len      = UDF_EXT_LEN(udf_rw32(piece->len));
681 	piece_lb_num   = udf_rw32(piece->loc.lb_num);
682 	piece_part_num = udf_rw16(piece->loc.part_num);
683 
684 	/* try merging */
685 	rest_len  = max_len - last_len;
686 
687 	merge_len = MIN(udf_rw32(piece->len), rest_len);
688 	last_end  = last_lb_num + (last_len / sector_size);
689 
690 	if ((piece_lb_num == last_end) && (last_part_num == piece_part_num)) {
691 		/* we can merge */
692 		last_len  += merge_len;
693 		piece_len -= merge_len;
694 
695 		/* write back merge result */
696 		if (use_shorts) {
697 			last_short->len = udf_rw32(last_len | last_flags);
698 		} else {
699 			last_long->len  = udf_rw32(last_len | last_flags);
700 		}
701 		piece_lb_num += merge_len / sector_size;
702 	}
703 
704 	if (piece_len) {
705 		/* append new entry */
706 		pos = data + l_ea + l_ad;
707 		if (use_shorts) {
708 			icb->flags = udf_rw16(UDF_ICB_SHORT_ALLOC);
709 			memset(&new_short, 0, short_len);
710 			new_short.len    = udf_rw32(piece_len);
711 			new_short.lb_num = udf_rw32(piece_lb_num);
712 			memcpy(pos, &new_short, short_len);
713 			l_ad += short_len;
714 			crclen += short_len;
715 		} else {
716 			icb->flags = udf_rw16(UDF_ICB_LONG_ALLOC);
717 			piece->len        = udf_rw32(piece_len);
718 			piece->loc.lb_num = udf_rw32(piece_lb_num);
719 			memcpy(pos, piece, long_len);
720 			l_ad += long_len;
721 			crclen += long_len;
722 		}
723 	}
724 	piece->len = udf_rw32(0);
725 
726 	inf_len  += size;
727 	obj_size += size;
728 	logblks_rec += UDF_ROUNDUP(size, sector_size) / sector_size;
729 
730 	dscr->tag.desc_crc_len = udf_rw16(crclen);
731 	if (udf_rw16(dscr->tag.id) == TAGID_FENTRY) {
732 		fe->l_ad = udf_rw32(l_ad);
733 		fe->inf_len = udf_rw64(inf_len);
734 		fe->logblks_rec = udf_rw64(logblks_rec);
735 	} else if (udf_rw16(dscr->tag.id) == TAGID_EXTFENTRY) {
736 		efe->l_ad = udf_rw32(l_ad);
737 		efe->inf_len  = udf_rw64(inf_len);
738 		efe->obj_size = udf_rw64(inf_len);
739 		efe->logblks_rec = udf_rw64(logblks_rec);
740 	}
741 }
742 
743 
744 static int
745 udf_append_file_contents(union dscrptr *dscr, struct long_ad *data_icb,
746 		uint8_t *fdata, size_t flen)
747 {
748 	struct long_ad icb;
749 	uint32_t location;
750 	uint32_t phys;
751 	uint16_t vpart;
752 	uint8_t *bpos;
753 	int cnt, sects;
754 	int error;
755 
756 	if (udf_file_inject_blob(dscr, fdata, flen) == 0)
757 		return 0;
758 
759 	/* has to be appended in mappings */
760 	icb = *data_icb;
761 	icb.len = udf_rw32(flen);
762 	while (udf_rw32(icb.len) > 0)
763 		udf_append_file_mapping(dscr, &icb);
764 	udf_validate_tag_and_crc_sums(dscr);
765 
766 	/* write out data piece */
767 	vpart    = udf_rw16(data_icb->loc.part_num);
768 	location = udf_rw32(data_icb->loc.lb_num);
769 	sects    = udf_datablocks(flen);
770 	for (cnt = 0; cnt < sects; cnt++) {
771 		bpos = fdata + cnt*context.sector_size;
772 		phys = context.vtop_offset[vpart] + location + cnt;
773 		error = udf_write_sector(bpos, phys);
774 		if (error)
775 			return error;
776 	}
777 	return 0;
778 }
779 
780 
781 static int
782 udf_create_new_file(struct stat *st, union dscrptr **dscr,
783 	int filetype, struct long_ad *icb)
784 {
785 	struct file_entry *fe;
786 	struct extfile_entry *efe;
787 	int error;
788 
789 	fe = NULL;
790 	efe = NULL;
791 	if (context.dscrver == 2) {
792 		error = udf_create_new_fe(&fe, filetype, st);
793 		if (error)
794 			errx(error, "can't create fe");
795 		*dscr = (union dscrptr *) fe;
796 		icb->longad_uniqueid = fe->unique_id;
797 	} else {
798 		error = udf_create_new_efe(&efe, filetype, st);
799 		if (error)
800 			errx(error, "can't create fe");
801 		*dscr = (union dscrptr *) efe;
802 		icb->longad_uniqueid = efe->unique_id;
803 	}
804 
805 	return 0;
806 }
807 
808 
809 static void
810 udf_estimate_walk(fsinfo_t *fsopts,
811 		fsnode *root, char *dir, struct udf_stats *stats)
812 {
813 	struct fileid_desc *fid;
814 	struct long_ad dummy_ref;
815 	fsnode *cur;
816 	fsinode *fnode;
817 	size_t pathlen = strlen(dir);
818 	char *mydir = dir + pathlen;
819 	off_t sz;
820 	uint32_t nblk, ddoff;
821 	uint32_t softlink_len;
822 	uint8_t *softlink_buf;
823 	int nentries;
824 	int error;
825 
826 	stats->ndirs++;
827 
828 	/*
829 	 * Count number of directory entries and count directory size; needed
830 	 * for the reservation of enough space for the directory. Pity we
831 	 * don't keep the FIDs we created. If it turns out to be a issue we
832 	 * can cache it later.
833 	 */
834 	fid = (struct fileid_desc *) malloc(context.sector_size);
835 	assert(fid);
836 
837 	ddoff = 40;	/* '..' entry */
838 	for (cur = root, nentries = 0; cur != NULL; cur = cur->next) {
839 		switch (cur->type & S_IFMT) {
840 		default:
841 			/* what kind of nodes? */
842 			break;
843 		case S_IFCHR:
844 		case S_IFBLK:
845 			/* not supported yet */
846 			continue;
847 		case S_IFDIR:
848 			if (strcmp(cur->name, ".") == 0)
849 				continue;
850 		case S_IFLNK:
851 		case S_IFREG:
852 			/* create dummy FID to see how long name will become */
853 			udf_create_fid(ddoff, fid, cur->name, 0, &dummy_ref);
854 
855 			nentries++;
856 			ddoff += udf_fidsize(fid);
857 		}
858 	}
859 	sz = ddoff;
860 
861 	root->inode->st.st_size = sz;	/* max now */
862 	root->inode->flags |= FI_SIZED;
863 
864 	nblk = udf_datablocks(sz);
865 	stats->nmetadatablocks += nblk;
866 
867 	/* for each entry in the directory, there needs to be a (E)FE */
868 	stats->nmetadatablocks += nentries + 1;
869 
870 	/* recurse */
871 	for (cur = root; cur != NULL; cur = cur->next) {
872 		switch (cur->type & S_IFMT) {
873 		default:
874 			/* what kind of nodes? */
875 			break;
876 		case S_IFCHR:
877 		case S_IFBLK:
878 			/* not supported yet */
879 			// stats->nfiles++;
880 			break;
881 		case S_IFDIR:
882 			if (strcmp(cur->name, ".") == 0)
883 				continue;
884 			/* empty dir? */
885 			if (!cur->child)
886 				break;
887 			mydir[0] = '/';
888 			strncpy(&mydir[1], cur->name, MAXPATHLEN - pathlen);
889 			udf_estimate_walk(fsopts, cur->child, dir, stats);
890 			mydir[0] = '\0';
891 			break;
892 		case S_IFREG:
893 			fnode = cur->inode;
894 			/* don't double-count hard-links */
895 			if (!(fnode->flags & FI_SIZED)) {
896 				sz = fnode->st.st_size;
897 				nblk = udf_datablocks(sz);
898 				stats->ndatablocks += nblk;
899 				/* ... */
900 				fnode->flags |= FI_SIZED;
901 			}
902 			stats->nfiles++;
903 			break;
904 		case S_IFLNK:
905 			/* softlink */
906 			fnode = cur->inode;
907 			/* don't double-count hard-links */
908 			if (!(fnode->flags & FI_SIZED)) {
909 				error = udf_encode_symlink(&softlink_buf,
910 						&softlink_len, cur->symlink);
911 				if (error) {
912 					printf("SOFTLINK error %d\n", error);
913 					break;
914 				}
915 				nblk = udf_datablocks(softlink_len);
916 				stats->ndatablocks += nblk;
917 				fnode->flags |= FI_SIZED;
918 
919 				free(softlink_buf);
920 			}
921 			stats->nfiles++;
922 			break;
923 		}
924 	}
925 }
926 
927 
928 #define UDF_MAX_CHUNK_SIZE (4*1024*1024)
929 static int
930 udf_copy_file(struct stat *st, char *path, fsnode *cur, struct fileid_desc *fid,
931 	struct long_ad *icb)
932 {
933 	union dscrptr *dscr;
934 	struct long_ad data_icb;
935 	fsinode *fnode;
936 	size_t sz, chunk, rd;
937 	uint8_t *data;
938 	int nblk;
939 	int i, f;
940 	int error;
941 
942 	fnode = cur->inode;
943 
944 	f = open(path, O_RDONLY);
945 	if (f < 0) {
946 		warn("Can't open file %s for reading", cur->name);
947 		return errno;
948 	}
949 
950 	/* claim disc space for the (e)fe descriptor for this file */
951 	udf_metadata_alloc(1, icb);
952 	udf_create_new_file(st, &dscr, UDF_ICB_FILETYPE_RANDOMACCESS, icb);
953 
954 	sz = fnode->st.st_size;
955 
956 	chunk = MIN(sz, UDF_MAX_CHUNK_SIZE);
957 	data = malloc(MAX(chunk, context.sector_size));
958 	assert(data);
959 
960 	printf("  ");
961 	i = 0;
962 	error = 0;
963 	while (chunk) {
964 		rd = read(f, data, chunk);
965 		if (rd != chunk) {
966 			warn("Short read of file %s\n", cur->name);
967 			error = errno;
968 			break;
969 		}
970 		printf("\b%c", "\\|/-"[i++ % 4]); fflush(stdout);fflush(stderr);
971 
972 		nblk = udf_datablocks(chunk);
973 		if (nblk > 0)
974 			udf_data_alloc(nblk, &data_icb);
975 		udf_append_file_contents(dscr, &data_icb, data, chunk);
976 
977 		sz -= chunk;
978 		chunk = MIN(sz, UDF_MAX_CHUNK_SIZE);
979 	}
980 	printf("\b \n");
981 	close(f);
982 	free(data);
983 
984 	/* write out dscr (e)fe */
985 	udf_set_link_cnt(dscr, fnode->nlink);
986 	udf_write_dscr_virt(dscr, udf_rw32(icb->loc.lb_num),
987 		udf_rw16(icb->loc.part_num), 1);
988 	free(dscr);
989 
990 	/* remember our location for hardlinks */
991 	cur->inode->fsuse = malloc(sizeof(struct long_ad));
992 	memcpy(cur->inode->fsuse, icb, sizeof(struct long_ad));
993 
994 	return error;
995 }
996 
997 
998 static int
999 udf_populate_walk(fsinfo_t *fsopts, fsnode *root, char *dir,
1000 		struct long_ad *parent_icb, struct long_ad *dir_icb)
1001 {
1002 	union dscrptr *dir_dscr, *dscr;
1003 	struct fileid_desc *fid;
1004 	struct long_ad icb, data_icb, dirdata_icb;
1005 	fsnode *cur;
1006 	fsinode *fnode;
1007 	size_t pathlen = strlen(dir);
1008 	size_t dirlen;
1009 	char *mydir = dir + pathlen;
1010 	uint32_t nblk, ddoff;
1011 	uint32_t softlink_len;
1012 	uint8_t *softlink_buf;
1013 	uint8_t *dirdata;
1014 	int error, ret, retval;
1015 
1016 	/* claim disc space for the (e)fe descriptor for this dir */
1017 	udf_metadata_alloc(1, dir_icb);
1018 
1019 	/* create new e(fe) */
1020 	udf_create_new_file(&root->inode->st, &dir_dscr,
1021 		UDF_ICB_FILETYPE_DIRECTORY, dir_icb);
1022 
1023 	/* claim space for the directory contents */
1024 	dirlen = root->inode->st.st_size;
1025 	nblk = udf_datablocks(dirlen);
1026 	if (nblk > 0) {
1027 		/* claim disc space for the dir contents */
1028 		udf_data_alloc(nblk, &dirdata_icb);
1029 	}
1030 
1031 	/* allocate memory for the directory contents */
1032 	nblk++;
1033 	dirdata = malloc(nblk * context.sector_size);
1034 	assert(dirdata);
1035 	memset(dirdata, 0, nblk * context.sector_size);
1036 
1037 	/* create and append '..' */
1038 	fid = (struct fileid_desc *) dirdata;
1039 	ddoff = udf_create_parentfid(fid, parent_icb);
1040 
1041 	/* for '..' */
1042 	udf_inc_link(dir_dscr);
1043 
1044 	/* recurse */
1045 	retval = 0;
1046 	for (cur = root; cur != NULL; cur = cur->next) {
1047 		mydir[0] = '/';
1048 		strncpy(&mydir[1], cur->name, MAXPATHLEN - pathlen);
1049 
1050 		fid = (struct fileid_desc *) (dirdata + ddoff);
1051 		switch (cur->type & S_IFMT) {
1052 		default:
1053 			/* what kind of nodes? */
1054 			retval = 2;
1055 			break;
1056 		case S_IFCHR:
1057 		case S_IFBLK:
1058 			/* not supported */
1059 			retval = 2;
1060 			warnx("device node %s not supported", dir);
1061 			break;
1062 		case S_IFDIR:
1063 			/* not an empty dir? */
1064 			if (strcmp(cur->name, ".") == 0)
1065 				break;
1066 			assert(cur->child);
1067 			if (cur->child) {
1068 				ret = udf_populate_walk(fsopts, cur->child,
1069 					dir, dir_icb, &icb);
1070 				if (ret)
1071 					retval = 2;
1072 			}
1073 			udf_create_fid(ddoff, fid, cur->name,
1074 					UDF_FILE_CHAR_DIR, &icb);
1075 			udf_inc_link(dir_dscr);
1076 			ddoff += udf_fidsize(fid);
1077 			break;
1078 		case S_IFREG:
1079 			fnode = cur->inode;
1080 			/* don't re-copy hard-links */
1081 			if (!(fnode->flags & FI_WRITTEN)) {
1082 				printf("%s", dir);
1083 				error = udf_copy_file(&fnode->st, dir, cur,
1084 					fid, &icb);
1085 				if (!error) {
1086 					fnode->flags |= FI_WRITTEN;
1087 					udf_create_fid(ddoff, fid, cur->name,
1088 						0, &icb);
1089 					ddoff += udf_fidsize(fid);
1090 				} else {
1091 					retval = 2;
1092 				}
1093 			} else {
1094 				/* hardlink! */
1095 				printf("%s (hardlink)\n", dir);
1096 				udf_create_fid(ddoff, fid, cur->name,
1097 					0, (struct long_ad *) (fnode->fsuse));
1098 				ddoff += udf_fidsize(fid);
1099 			}
1100 			fnode->nlink--;
1101 			if (fnode->nlink == 0)
1102 				free(fnode->fsuse);
1103 			break;
1104 		case S_IFLNK:
1105 			/* softlink */
1106 			fnode = cur->inode;
1107 			printf("%s -> %s\n", dir, cur->symlink);
1108 			error = udf_encode_symlink(&softlink_buf,
1109 					&softlink_len, cur->symlink);
1110 			if (error) {
1111 				printf("SOFTLINK error %d\n", error);
1112 				retval = 2;
1113 				break;
1114 			}
1115 
1116 			udf_metadata_alloc(1, &icb);
1117 			udf_create_new_file(&fnode->st, &dscr,
1118 				UDF_ICB_FILETYPE_SYMLINK, &icb);
1119 
1120 			nblk = udf_datablocks(softlink_len);
1121 			if (nblk > 0)
1122 				udf_data_alloc(nblk, &data_icb);
1123 			udf_append_file_contents(dscr, &data_icb,
1124 					softlink_buf, softlink_len);
1125 
1126 			/* write out dscr (e)fe */
1127 			udf_inc_link(dscr);
1128 			udf_write_dscr_virt(dscr, udf_rw32(icb.loc.lb_num),
1129 				udf_rw16(icb.loc.part_num), 1);
1130 
1131 			free(dscr);
1132 			free(softlink_buf);
1133 
1134 			udf_create_fid(ddoff, fid, cur->name, 0, &icb);
1135 			ddoff += udf_fidsize(fid);
1136 			break;
1137 		}
1138 		mydir[0] = '\0';
1139 	}
1140 
1141 	/* writeout directory contents */
1142 	dirlen = ddoff;	/* XXX might bite back */
1143 
1144 	udf_prepare_fids(dir_icb, &dirdata_icb, dirdata, dirlen);
1145 	udf_append_file_contents(dir_dscr, &dirdata_icb, dirdata, dirlen);
1146 
1147 	/* write out dir_dscr (e)fe */
1148 	udf_write_dscr_virt(dir_dscr, udf_rw32(dir_icb->loc.lb_num),
1149 			udf_rw16(dir_icb->loc.part_num), 1);
1150 
1151 	free(dirdata);
1152 	free(dir_dscr);
1153 	return retval;
1154 }
1155 
1156 
1157 static int
1158 udf_populate(const char *dir, fsnode *root, fsinfo_t *fsopts,
1159 		struct udf_stats *stats)
1160 {
1161 	struct long_ad rooticb;
1162 	static char path[MAXPATHLEN+1];
1163 	int error;
1164 
1165 	/* make sure the root gets the rootdir entry */
1166 	context.metadata_alloc_pos = layout.rootdir;
1167 	context.data_alloc_pos = layout.rootdir;
1168 
1169 	strncpy(path, dir, sizeof(path));
1170 	error = udf_populate_walk(fsopts, root, path, &rooticb, &rooticb);
1171 
1172 	return error;
1173 }
1174 
1175 
1176 static void
1177 udf_enumerate_and_estimate(const char *dir, fsnode *root, fsinfo_t *fsopts,
1178 		struct udf_stats *stats)
1179 {
1180 	char path[MAXPATHLEN + 1];
1181 	off_t proposed_size;
1182 	uint32_t n, nblk;
1183 
1184 	strncpy(path, dir, sizeof(path));
1185 
1186 	/* calculate strict minimal size */
1187 	udf_estimate_walk(fsopts, root, path, stats);
1188 	printf("ndirs            %d\n", stats->ndirs);
1189 	printf("nfiles           %d\n", stats->nfiles);
1190 	printf("ndata_blocks     %d\n", stats->ndatablocks);
1191 	printf("nmetadata_blocks %d\n", stats->nmetadatablocks);
1192 	printf("\n");
1193 
1194 	/* adjust for options : free file nodes */
1195 	if (fsopts->freefiles) {
1196 		/* be mercifull and reserve more for the FID */
1197 		stats->nmetadatablocks += fsopts->freefiles * 1.5;
1198 	} else if ((n = fsopts->freefilepc)) {
1199 		stats->nmetadatablocks += (stats->nmetadatablocks*n) / (100-n);
1200 	}
1201 
1202 	/* adjust for options : free data blocks */
1203 	if (fsopts->freeblocks) {
1204 		stats->ndatablocks += fsopts->freeblocks;
1205 	} else if ((n = fsopts->freeblockpc)) {
1206 		stats->ndatablocks += (stats->ndatablocks * n) / (100-n);
1207 	}
1208 
1209 	/* rough predictor of minimum disc size */
1210 	nblk  = stats->ndatablocks + stats->nmetadatablocks;
1211 	nblk = (double) nblk * (1.0 + 1.0/8.0);		/* free space map    */
1212 	nblk += 256;					/* pre-volume space  */
1213 	nblk += 256;					/* post-volume space */
1214 	nblk += 64;					/* safeguard	     */
1215 
1216 	/* try to honour minimum size */
1217 	n = fsopts->minsize / fsopts->sectorsize;
1218 	if (nblk < n) {
1219 		stats->ndatablocks += (n - nblk);
1220 		nblk += n - nblk;
1221 	}
1222 	proposed_size = (off_t) nblk * fsopts->sectorsize;
1223 	/* sanity size */
1224 	if (proposed_size < 512*1024)
1225 		proposed_size = 512*1024;
1226 
1227 	if (fsopts->size) {
1228 		if (fsopts->size < proposed_size)
1229 			err(EINVAL, "makefs_udf: won't fit on disc!");
1230 	} else {
1231 		fsopts->size = proposed_size;
1232 	}
1233 
1234 	fsopts->inodes = stats->nfiles + stats->ndirs;
1235 }
1236 
1237 
1238 void
1239 udf_makefs(const char *image, const char *dir, fsnode *root, fsinfo_t *fsopts)
1240 {
1241 	struct udf_stats stats;
1242 	uint64_t truncate_len;
1243 	int error;
1244 
1245 	/* determine format */
1246 	udf_emulate_discinfo(fsopts, &mmc_discinfo, mmc_profile);
1247 	printf("req_enable %d, req_disable %d\n", req_enable, req_disable);
1248 
1249 	context.sector_size = fsopts->sectorsize;
1250 	error = udf_derive_format(req_enable, req_disable, false);
1251 	if (error)
1252 		err(EINVAL, "makefs_udf: can't determine format");
1253 
1254 	/* names */
1255 	error = udf_proces_names();
1256 	if (error)
1257 		err(EINVAL, "makefs_udf: bad names given");
1258 
1259 	/* set return value to 1 indicating error */
1260 	error = 1;
1261 
1262 	/* estimate the amount of space needed */
1263 	memset(&stats, 0, sizeof(stats));
1264 	udf_enumerate_and_estimate(dir, root, fsopts, &stats);
1265 
1266 	printf("Calculated size of `%s': %lld bytes, %ld inodes\n",
1267 	    image, (long long)fsopts->size, (long)fsopts->inodes);
1268 
1269 	/* create file image */
1270 	if ((fd = open(image, O_RDWR | O_CREAT | O_TRUNC, 0666)) == -1) {
1271 		err(EXIT_FAILURE, "%s", image);
1272 	}
1273 	if (lseek(fd, fsopts->size - 1, SEEK_SET) == -1) {
1274 		goto err_exit;
1275 	}
1276 	if (write(fd, &fd, 1) != 1) {
1277 		goto err_exit;
1278 	}
1279 	if (lseek(fd, 0, SEEK_SET) == -1) {
1280 		goto err_exit;
1281 	}
1282 	fsopts->fd = fd;
1283 
1284 	/* calculate metadata percentage */
1285 	meta_fract = fsopts->size / (stats.nmetadatablocks*fsopts->sectorsize);
1286 	meta_fract = ((int) ((meta_fract + 0.005)*100.0)) / 100;
1287 
1288 	/* update mmc info but now with correct size */
1289 	udf_emulate_discinfo(fsopts, &mmc_discinfo, mmc_profile);
1290 
1291 	udf_do_newfs_prefix();
1292 
1293 	/* update context */
1294 	context.unique_id = 0;
1295 
1296 	/* XXX are the next two needed? or should be re-count them? */
1297 	context.num_files = stats.nfiles;
1298 	context.num_directories = stats.ndirs;
1299 
1300 	error = udf_populate(dir, root, fsopts, &stats);
1301 
1302 	udf_do_newfs_postfix();
1303 
1304 	if (format_flags & FORMAT_VAT) {
1305 		truncate_len = context.vtop_offset[context.data_part] +
1306 			context.data_alloc_pos;
1307 		truncate_len *= context.sector_size;
1308 
1309 		printf("\nTruncing the disc-image to allow for VAT\n");
1310 		printf("Free space left on this volume approx. "
1311 			"%"PRIu64" KiB, %"PRIu64" MiB\n",
1312 			(fsopts->size - truncate_len)/1024,
1313 			(fsopts->size - truncate_len)/1024/1024);
1314 		ftruncate(fd, truncate_len);
1315 	}
1316 
1317 	if (error) {
1318 		error = 2;	/* some files couldn't be added */
1319 		goto err_exit;
1320 	}
1321 
1322 	close(fd);
1323 	return;
1324 
1325 err_exit:
1326 	close(fd);
1327 	if (error == 2) {
1328 		errx(error, "Not all files could be added");
1329 	} else {
1330 		errx(error, "creation of %s failed", image);
1331 	}
1332 }
1333 
1334