Home | History | Annotate | Line # | Download | only in newfs_udf
newfs_udf.c revision 1.2
      1 /* $NetBSD: newfs_udf.c,v 1.2 2008/06/19 12:23:01 reinoud Exp $ */
      2 
      3 /*
      4  * Copyright (c) 2006, 2008 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 
     29 /*
     30  * TODO
     31  * - implement meta data partition formatting.
     32  * - implement support for a read-only companion partition?
     33  */
     34 
     35 #define _EXPOSE_MMC
     36 #if 0
     37 # define DEBUG
     38 #endif
     39 
     40 #include <stdio.h>
     41 #include <stdlib.h>
     42 #include <dirent.h>
     43 #include <inttypes.h>
     44 #include <stdint.h>
     45 #include <string.h>
     46 #include <errno.h>
     47 #include <fcntl.h>
     48 #include <unistd.h>
     49 #include <util.h>
     50 #include <fattr.h>
     51 #include <time.h>
     52 #include <assert.h>
     53 
     54 #include <sys/ioctl.h>
     55 #include <sys/stat.h>
     56 #include <sys/types.h>
     57 #include <sys/cdio.h>
     58 #include <sys/disklabel.h>
     59 #include <sys/dkio.h>
     60 #include <sys/param.h>
     61 #include <sys/queue.h>
     62 
     63 #include <fs/udf/ecma167-udf.h>
     64 #include <fs/udf/udf_mount.h>
     65 #include "udf_create.h"
     66 
     67 /* general settings */
     68 #define UDF_512_TRACK	0	/* NOT recommended */
     69 
     70 /* prototypes */
     71 int newfs_udf(int argc, char **argv);
     72 static void usage(void) __attribute__((__noreturn__));
     73 
     74 int udf_derive_format(int req_en, int req_dis, int force);
     75 int udf_proces_names(void);
     76 int udf_do_newfs(void);
     77 
     78 /* Identifying myself */
     79 #define APP_NAME		"*NetBSD newfs"
     80 #define APP_VERSION_MAIN	0
     81 #define APP_VERSION_SUB		2
     82 #define IMPL_NAME		"*NetBSD userland UDF"
     83 
     84 
     85 /* global variables describing disc and format requests */
     86 int	 fd;				/* device: file descriptor */
     87 char	*dev;				/* device: name		   */
     88 struct mmc_discinfo mmc_discinfo;	/* device: disc info	   */
     89 
     90 char	*format_str;			/* format: string representation */
     91 int	 format_flags;			/* format: attribute flags	 */
     92 int	 media_accesstype;		/* derived from current mmc cap  */
     93 int	 check_surface;			/* for rewritables               */
     94 
     95 int	 wrtrack_skew;
     96 
     97 
     98 /* shared structure between udf_create.c users */
     99 struct udf_create_context context;
    100 struct udf_disclayout     layout;
    101 
    102 
    103 /* queue for temporary storage of sectors to be written out */
    104 struct wrsect {
    105 	uint32_t  sectornr;
    106 	uint8_t	 *sector_data;
    107 	TAILQ_ENTRY(wrsect) next;
    108 };
    109 
    110 /* write queue and track blocking skew */
    111 TAILQ_HEAD(wrsect_list, wrsect) write_queue;
    112 
    113 
    114 /* --------------------------------------------------------------------- */
    115 
    116 /*
    117  * write queue implementation
    118  */
    119 
    120 static int
    121 udf_write_sector(void *sector, uint32_t location)
    122 {
    123 	struct wrsect *pos, *seekpos;
    124 
    125 
    126 	/* search location */
    127 	TAILQ_FOREACH_REVERSE(seekpos, &write_queue, wrsect_list, next) {
    128 		if (seekpos->sectornr <= location)
    129 			break;
    130 	}
    131 	if ((seekpos == NULL) || (seekpos->sectornr != location)) {
    132 		pos = calloc(1, sizeof(struct wrsect));
    133 		if (pos == NULL)
    134 			return ENOMEM;
    135 		/* allocate space for copy of sector data */
    136 		pos->sector_data = calloc(1, context.sector_size);
    137 		if (pos->sector_data == NULL)
    138 			return ENOMEM;
    139 		pos->sectornr = location;
    140 
    141 		if (seekpos) {
    142 			TAILQ_INSERT_AFTER(&write_queue, seekpos, pos, next);
    143 		} else {
    144 			TAILQ_INSERT_HEAD(&write_queue, pos, next);
    145 		}
    146 	} else {
    147 		pos = seekpos;
    148 	}
    149 	memcpy(pos->sector_data, sector, context.sector_size);
    150 
    151 	return 0;
    152 }
    153 
    154 
    155 /*
    156  * Now all write requests are queued in the TAILQ, write them out to the
    157  * disc/file image. Special care needs to be taken for devices that are only
    158  * strict overwritable i.e. only in packet size chunks
    159  *
    160  * XXX support for growing vnd?
    161  */
    162 
    163 static int
    164 writeout_write_queue(void)
    165 {
    166 	struct wrsect *pos;
    167 	uint64_t offset;
    168 	uint32_t line_len, line_offset;
    169 	uint32_t line_start, new_line_start, relpos;
    170 	uint32_t blockingnr;
    171 	uint8_t *linebuf, *adr;
    172 
    173 	blockingnr  = layout.blockingnr;
    174 	line_len    = blockingnr   * context.sector_size;
    175 	line_offset = wrtrack_skew * context.sector_size;
    176 
    177 	linebuf     = malloc(line_len);
    178 	if (linebuf == NULL)
    179 		return ENOMEM;
    180 
    181 	pos = TAILQ_FIRST(&write_queue);
    182 	bzero(linebuf, line_len);
    183 
    184 	/*
    185 	 * Always writing out in whole lines now; this is slightly wastefull
    186 	 * on logical overwrite volumes but it reduces complexity and the loss
    187 	 * is near zero compared to disc size.
    188 	 */
    189 	line_start = (pos->sectornr - wrtrack_skew) / blockingnr;
    190 	TAILQ_FOREACH(pos, &write_queue, next) {
    191 		new_line_start = (pos->sectornr - wrtrack_skew) / blockingnr;
    192 		if (new_line_start != line_start) {
    193 			/* write out */
    194 			offset = (uint64_t) line_start * line_len + line_offset;
    195 #ifdef DEBUG
    196 			printf("WRITEOUT %08"PRIu64" + %02d -- "
    197 				"[%08"PRIu64"..%08"PRIu64"]\n",
    198 				offset / context.sector_size, blockingnr,
    199 				offset / context.sector_size,
    200 				offset / context.sector_size + blockingnr-1);
    201 #endif
    202 			if (pwrite(fd, linebuf, line_len, offset) < 0) {
    203 				perror("Writing failed");
    204 				return errno;
    205 			}
    206 			line_start = new_line_start;
    207 			bzero(linebuf, line_len);
    208 		}
    209 
    210 		relpos = (pos->sectornr - wrtrack_skew) % blockingnr;
    211 		adr = linebuf + relpos * context.sector_size;
    212 		memcpy(adr, pos->sector_data, context.sector_size);
    213 	}
    214 	/* writeout last chunk */
    215 	offset = (uint64_t) line_start * line_len + line_offset;
    216 #ifdef DEBUG
    217 	printf("WRITEOUT %08"PRIu64" + %02d -- [%08"PRIu64"..%08"PRIu64"]\n",
    218 		offset / context.sector_size, blockingnr,
    219 		offset / context.sector_size,
    220 		offset / context.sector_size + blockingnr-1);
    221 #endif
    222 	if (pwrite(fd, linebuf, line_len, offset) < 0) {
    223 		perror("Writing failed");
    224 		return errno;
    225 	}
    226 
    227 	/* success */
    228 	return 0;
    229 }
    230 
    231 /* --------------------------------------------------------------------- */
    232 
    233 /*
    234  * mmc_discinfo and mmc_trackinfo readers modified from origional in udf main
    235  * code in sys/fs/udf/
    236  */
    237 
    238 #ifdef DEBUG
    239 static void
    240 udf_dump_discinfo(struct mmc_discinfo *di)
    241 {
    242 	char bits[128];
    243 
    244 	printf("Device/media info  :\n");
    245 	printf("\tMMC profile        0x%02x\n", di->mmc_profile);
    246 	printf("\tderived class      %d\n", di->mmc_class);
    247 	printf("\tsector size        %d\n", di->sector_size);
    248 	printf("\tdisc state         %d\n", di->disc_state);
    249 	printf("\tlast ses state     %d\n", di->last_session_state);
    250 	printf("\tbg format state    %d\n", di->bg_format_state);
    251 	printf("\tfrst track         %d\n", di->first_track);
    252 	printf("\tfst on last ses    %d\n", di->first_track_last_session);
    253 	printf("\tlst on last ses    %d\n", di->last_track_last_session);
    254 	printf("\tlink block penalty %d\n", di->link_block_penalty);
    255 	snprintb(bits, sizeof(bits), MMC_DFLAGS_FLAGBITS, (uint64_t) di->disc_flags);
    256 	printf("\tdisc flags         %s\n", bits);
    257 	printf("\tdisc id            %x\n", di->disc_id);
    258 	printf("\tdisc barcode       %"PRIx64"\n", di->disc_barcode);
    259 
    260 	printf("\tnum sessions       %d\n", di->num_sessions);
    261 	printf("\tnum tracks         %d\n", di->num_tracks);
    262 
    263 	snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cur);
    264 	printf("\tcapabilities cur   %s\n", bits);
    265 	snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cap);
    266 	printf("\tcapabilities cap   %s\n", bits);
    267 	printf("\n");
    268 	printf("\tlast_possible_lba  %d\n", di->last_possible_lba);
    269 	printf("\n");
    270 }
    271 #else
    272 #define udf_dump_discinfo(a);
    273 #endif
    274 
    275 /* --------------------------------------------------------------------- */
    276 
    277 static int
    278 udf_update_discinfo(struct mmc_discinfo *di)
    279 {
    280 	struct disklabel  disklab;
    281 	struct partition *dp;
    282 	struct stat st;
    283 	int partnr, error;
    284 
    285 	memset(di, 0, sizeof(struct mmc_discinfo));
    286 
    287 	/* check if we're on a MMC capable device, i.e. CD/DVD */
    288 	error = ioctl(fd, MMCGETDISCINFO, di);
    289 	if (error == 0)
    290 		return 0;
    291 
    292 	/*
    293 	 * disc partition support; note we can't use DIOCGPART in userland so
    294 	 * get disc label and use the stat info to get the partition number.
    295 	 */
    296 	if (ioctl(fd, DIOCGDINFO, &disklab) == -1) {
    297 		/* failed to get disclabel! */
    298 		perror("disklabel");
    299 		return errno;
    300 	}
    301 
    302 	/* get disk partition it refers to */
    303 	fstat(fd, &st);
    304 	partnr = DISKPART(st.st_rdev);
    305 	dp = &disklab.d_partitions[partnr];
    306 
    307 	/* set up a disc info profile for partitions */
    308 	di->mmc_profile		= 0x01;	/* disc type */
    309 	di->mmc_class		= MMC_CLASS_DISC;
    310 	di->disc_state		= MMC_STATE_CLOSED;
    311 	di->last_session_state	= MMC_STATE_CLOSED;
    312 	di->bg_format_state	= MMC_BGFSTATE_COMPLETED;
    313 	di->link_block_penalty	= 0;
    314 
    315 	di->mmc_cur     = MMC_CAP_RECORDABLE | MMC_CAP_REWRITABLE |
    316 		MMC_CAP_ZEROLINKBLK | MMC_CAP_HW_DEFECTFREE;
    317 	di->mmc_cap    = di->mmc_cur;
    318 	di->disc_flags = MMC_DFLAGS_UNRESTRICTED;
    319 
    320 	/* TODO problem with last_possible_lba on resizable VND; request */
    321 	if (dp->p_size == 0) {
    322 		perror("faulty disklabel partition returned, check label\n");
    323 		return EIO;
    324 	}
    325 	di->last_possible_lba = dp->p_size - 1;
    326 	di->sector_size       = disklab.d_secsize;
    327 
    328 	di->num_sessions = 1;
    329 	di->num_tracks   = 1;
    330 
    331 	di->first_track  = 1;
    332 	di->first_track_last_session = di->last_track_last_session = 1;
    333 
    334 	return 0;
    335 }
    336 
    337 
    338 static int
    339 udf_update_trackinfo(struct mmc_discinfo *di, struct mmc_trackinfo *ti)
    340 {
    341 	int error, class;
    342 
    343 	class = di->mmc_class;
    344 	if (class != MMC_CLASS_DISC) {
    345 		/* tracknr specified in struct ti */
    346 		error = ioctl(fd, MMCGETTRACKINFO, ti);
    347 		return error;
    348 	}
    349 
    350 	/* discs partition support */
    351 	if (ti->tracknr != 1)
    352 		return EIO;
    353 
    354 	/* create fake ti (TODO check for resized vnds) */
    355 	ti->sessionnr  = 1;
    356 
    357 	ti->track_mode = 0;	/* XXX */
    358 	ti->data_mode  = 0;	/* XXX */
    359 	ti->flags = MMC_TRACKINFO_LRA_VALID | MMC_TRACKINFO_NWA_VALID;
    360 
    361 	ti->track_start    = 0;
    362 	ti->packet_size    = 1;
    363 
    364 	/* TODO support for resizable vnd */
    365 	ti->track_size    = di->last_possible_lba;
    366 	ti->next_writable = di->last_possible_lba;
    367 	ti->last_recorded = ti->next_writable;
    368 	ti->free_blocks   = 0;
    369 
    370 	return 0;
    371 }
    372 
    373 
    374 static int
    375 udf_setup_writeparams(struct mmc_discinfo *di)
    376 {
    377 	struct mmc_writeparams mmc_writeparams;
    378 	int error;
    379 
    380 	if (di->mmc_class == MMC_CLASS_DISC)
    381 		return 0;
    382 
    383 	/*
    384 	 * only CD burning normally needs setting up, but other disc types
    385 	 * might need other settings to be made. The MMC framework will set up
    386 	 * the nessisary recording parameters according to the disc
    387 	 * characteristics read in. Modifications can be made in the discinfo
    388 	 * structure passed to change the nature of the disc.
    389 	 */
    390 	memset(&mmc_writeparams, 0, sizeof(struct mmc_writeparams));
    391 	mmc_writeparams.mmc_class  = di->mmc_class;
    392 	mmc_writeparams.mmc_cur    = di->mmc_cur;
    393 
    394 	/*
    395 	 * UDF dictates first track to determine track mode for the whole
    396 	 * disc. [UDF 1.50/6.10.1.1, UDF 1.50/6.10.2.1]
    397 	 * To prevent problems with a `reserved' track in front we start with
    398 	 * the 2nd track and if that is not valid, go for the 1st.
    399 	 */
    400 	mmc_writeparams.tracknr = 2;
    401 	mmc_writeparams.data_mode  = MMC_DATAMODE_DEFAULT;	/* XA disc */
    402 	mmc_writeparams.track_mode = MMC_TRACKMODE_DEFAULT;	/* data */
    403 
    404 	error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams);
    405 	if (error) {
    406 		mmc_writeparams.tracknr = 1;
    407 		error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams);
    408 	}
    409 	return error;
    410 }
    411 
    412 
    413 static void
    414 udf_synchronise_caches(void)
    415 {
    416 	struct mmc_op mmc_op;
    417 
    418 	bzero(&mmc_op, sizeof(struct mmc_op));
    419 	mmc_op.operation = MMC_OP_SYNCHRONISECACHE;
    420 
    421 	/* this device might not know this ioct, so just be ignorant */
    422 	(void) ioctl(fd, MMCOP, &mmc_op);
    423 }
    424 
    425 /* --------------------------------------------------------------------- */
    426 
    427 static int
    428 udf_write_dscr_phys(union dscrptr *dscr, uint32_t location,
    429 	uint32_t sects)
    430 {
    431 	uint32_t phys;
    432 	uint8_t *bpos;
    433 	int error, cnt;
    434 
    435 	dscr->tag.tag_loc = udf_rw32(location);
    436 	(void) udf_validate_tag_and_crc_sums(dscr);
    437 
    438 	for (cnt = 0; cnt < sects; cnt++) {
    439 		bpos  = (uint8_t *) dscr;
    440 		bpos += context.sector_size * cnt;
    441 
    442 		phys = location + cnt;
    443 		error = udf_write_sector(bpos, phys);
    444 		if (error)
    445 			return error;
    446 	}
    447 	return 0;
    448 }
    449 
    450 
    451 static int
    452 udf_write_dscr_virt(union dscrptr *dscr, uint32_t location, uint32_t vpart,
    453 	uint32_t sects)
    454 {
    455 	struct file_entry *fe;
    456 	struct extfile_entry *efe;
    457 	struct extattrhdr_desc *extattrhdr;
    458 	uint32_t phys;
    459 	uint8_t *bpos;
    460 	int error, cnt;
    461 
    462 	extattrhdr = NULL;
    463 	if (udf_rw16(dscr->tag.id) == TAGID_FENTRY) {
    464 		fe = (struct file_entry *) dscr;
    465 		if (udf_rw32(fe->l_ea) > 0)
    466 			extattrhdr = (struct extattrhdr_desc *) fe->data;
    467 	}
    468 	if (udf_rw16(dscr->tag.id) == TAGID_EXTFENTRY) {
    469 		efe = (struct extfile_entry *) dscr;
    470 		if (udf_rw32(efe->l_ea) > 0)
    471 			extattrhdr = (struct extattrhdr_desc *) efe->data;
    472 	}
    473 	if (extattrhdr) {
    474 		extattrhdr->tag.tag_loc = udf_rw32(location);
    475 		udf_validate_tag_and_crc_sums((union dscrptr *) extattrhdr);
    476 	}
    477 
    478 	dscr->tag.tag_loc = udf_rw32(location);
    479 	udf_validate_tag_and_crc_sums(dscr);
    480 
    481 	for (cnt = 0; cnt < sects; cnt++) {
    482 		bpos  = (uint8_t *) dscr;
    483 		bpos += context.sector_size * cnt;
    484 
    485 		/* NOTE linear mapping assumed in the ranges used */
    486 		/* XXX 1:1 translation */
    487 		phys = layout.part_start_lba + location + cnt;
    488 
    489 		error = udf_write_sector(bpos, phys);
    490 		if (error)
    491 			return error;
    492 	}
    493 	return 0;
    494 }
    495 
    496 /* --------------------------------------------------------------------- */
    497 
    498 /*
    499  * udf_derive_format derives the format_flags from the disc's mmc_discinfo.
    500  * The resulting flags uniquely define a disc format. Note there are at least
    501  * 7 distinct format types defined in UDF.
    502  */
    503 
    504 #define UDF_VERSION(a) \
    505 	(((a) == 0x100) || ((a) == 0x102) || ((a) == 0x150) || ((a) == 0x200) || \
    506 	 ((a) == 0x201) || ((a) == 0x250) || ((a) == 0x260))
    507 
    508 int
    509 udf_derive_format(int req_enable, int req_disable, int force)
    510 {
    511 	/* disc writability, formatted, appendable */
    512 	if ((mmc_discinfo.mmc_cur & MMC_CAP_RECORDABLE) == 0) {
    513 		(void)printf("Can't newfs readonly device\n");
    514 		return EROFS;
    515 	}
    516 	if (mmc_discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) {
    517 		/* sequentials need sessions appended */
    518 		if (mmc_discinfo.disc_state == MMC_STATE_CLOSED) {
    519 			(void)printf("Can't append session to a closed disc\n");
    520 			return EROFS;
    521 		}
    522 		if ((mmc_discinfo.disc_state != MMC_STATE_EMPTY) && !force) {
    523 			(void)printf("Disc not empty! Use -F to force "
    524 			    "initialisation\n");
    525 			return EROFS;
    526 		}
    527 	} else {
    528 		/* check if disc (being) formatted or has been started on */
    529 		if (mmc_discinfo.disc_state == MMC_STATE_EMPTY) {
    530 			(void)printf("Disc is not formatted\n");
    531 			return EROFS;
    532 		}
    533 	}
    534 
    535 	/* determine UDF format */
    536 	format_flags = 0;
    537 	if (mmc_discinfo.mmc_cur & MMC_CAP_REWRITABLE) {
    538 		/* all rewritable media */
    539 		format_flags |= FORMAT_REWRITABLE;
    540 		if (context.min_udf >= 0x0250) {
    541 			/* standard dictates meta as default */
    542 			format_flags |= FORMAT_META;
    543 		}
    544 
    545 		if ((mmc_discinfo.mmc_cur & MMC_CAP_HW_DEFECTFREE) == 0) {
    546 			/* sparables for defect management */
    547 			if (context.min_udf >= 0x150)
    548 				format_flags |= FORMAT_SPARABLE;
    549 		}
    550 	} else {
    551 		/* all once recordable media */
    552 		format_flags |= FORMAT_WRITEONCE;
    553 		if (mmc_discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) {
    554 			format_flags |= FORMAT_SEQUENTIAL;
    555 
    556 			if (mmc_discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE) {
    557 				/* logical overwritable */
    558 				format_flags |= FORMAT_LOW;
    559 			} else {
    560 				/* have to use VAT for overwriting */
    561 				format_flags |= FORMAT_VAT;
    562 			}
    563 		} else {
    564 			/* rare WORM devices, but BluRay has one, strat4096 */
    565 			format_flags |= FORMAT_WORM;
    566 		}
    567 	}
    568 
    569 	/* enable/disable requests */
    570 	if (req_disable & FORMAT_META) {
    571 		format_flags &= ~FORMAT_META;
    572 		req_disable  &= ~FORMAT_META;
    573 	}
    574 	if (req_disable || req_enable) {
    575 		(void)printf("Internal error\n");
    576 		(void)printf("\tunrecognised enable/disable req.\n");
    577 		return EIO;
    578 	}
    579 	if ((format_flags && FORMAT_VAT) && UDF_512_TRACK)
    580 		format_flags |= FORMAT_TRACK512;
    581 
    582 	/* determine partition/media access type */
    583 	media_accesstype = UDF_ACCESSTYPE_NOT_SPECIFIED;
    584 	if (mmc_discinfo.mmc_cur & MMC_CAP_REWRITABLE) {
    585 		media_accesstype = UDF_ACCESSTYPE_OVERWRITABLE;
    586 		if (mmc_discinfo.mmc_cur & MMC_CAP_ERASABLE)
    587 			media_accesstype = UDF_ACCESSTYPE_REWRITEABLE;
    588 	} else {
    589 		/* all once recordable media */
    590 		media_accesstype = UDF_ACCESSTYPE_WRITE_ONCE;
    591 	}
    592 	if (mmc_discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE)
    593 		media_accesstype = UDF_ACCESSTYPE_PSEUDO_OVERWITE;
    594 
    595 	/* adjust minimum version limits */
    596 	if (format_flags & FORMAT_VAT)
    597 		context.min_udf = MAX(context.min_udf, 0x0150);
    598 	if (format_flags & FORMAT_SPARABLE)
    599 		context.min_udf = MAX(context.min_udf, 0x0150);
    600 	if (format_flags & FORMAT_META)
    601 		context.min_udf = MAX(context.min_udf, 0x0250);
    602 	if (format_flags & FORMAT_LOW)
    603 		context.min_udf = MAX(context.min_udf, 0x0260);
    604 
    605 	/* adjust maximum version limits not to tease or break things */
    606 	if (!(format_flags & FORMAT_META) && (context.max_udf > 0x200))
    607 		context.max_udf = 0x201;
    608 
    609 	if ((format_flags & (FORMAT_VAT | FORMAT_SPARABLE)) == 0)
    610 		if (context.max_udf <= 0x150)
    611 			context.min_udf = 0x102;
    612 
    613 	/* limit Ecma 167 descriptor if possible/needed */
    614 	context.dscrver = 3;
    615 	if ((context.min_udf < 0x200) || (context.max_udf < 0x200)) {
    616 		context.dscrver = 2;
    617 		context.max_udf = 0x150;	/* last version < 0x200 */
    618 	}
    619 
    620 	/* is it possible ? */
    621 	if (context.min_udf > context.max_udf) {
    622 		(void)printf("Initialisation prohibited by specified maximum "
    623 		    "UDF version 0x%04x. Minimum version required 0x%04x\n",
    624 		    context.max_udf, context.min_udf);
    625 		return EPERM;
    626 	}
    627 
    628 	if (!UDF_VERSION(context.min_udf) || !UDF_VERSION(context.max_udf)) {
    629 		printf("Choose UDF version numbers from "
    630 			"0x102, 0x150, 0x200, 0x201, 0x250 and 0x260\n");
    631 		printf("Default version is 0x201\n");
    632 		return EPERM;
    633 	}
    634 
    635 	return 0;
    636 }
    637 
    638 #undef UDF_VERSION
    639 
    640 
    641 /* --------------------------------------------------------------------- */
    642 
    643 int
    644 udf_proces_names(void)
    645 {
    646 	uint32_t primary_nr;
    647 	uint64_t volset_nr;
    648 
    649 	if (context.logvol_name == NULL)
    650 		context.logvol_name = strdup("anonymous");
    651 	if (context.primary_name == NULL) {
    652 		if (mmc_discinfo.disc_flags & MMC_DFLAGS_DISCIDVALID) {
    653 			primary_nr = mmc_discinfo.disc_id;
    654 		} else {
    655 			primary_nr = (uint32_t) random();
    656 		}
    657 		context.primary_name = calloc(32, 1);
    658 		sprintf(context.primary_name, "%08"PRIx32, primary_nr);
    659 	}
    660 	if (context.volset_name == NULL) {
    661 		if (mmc_discinfo.disc_flags & MMC_DFLAGS_BARCODEVALID) {
    662 			volset_nr = mmc_discinfo.disc_barcode;
    663 		} else {
    664 			volset_nr  =  (uint32_t) random();
    665 			volset_nr |= ((uint64_t) random()) << 32;
    666 		}
    667 		context.volset_name = calloc(128,1);
    668 		sprintf(context.volset_name, "%016"PRIx64, volset_nr);
    669 	}
    670 	if (context.fileset_name == NULL)
    671 		context.fileset_name = strdup("anonymous");
    672 
    673 	/* check passed/created identifiers */
    674 	if (strlen(context.logvol_name)  > 128) {
    675 		(void)printf("Logical volume name too long\n");
    676 		return EINVAL;
    677 	}
    678 	if (strlen(context.primary_name) >  32) {
    679 		(void)printf("Primary volume name too long\n");
    680 		return EINVAL;
    681 	}
    682 	if (strlen(context.volset_name)  > 128) {
    683 		(void)printf("Volume set name too long\n");
    684 		return EINVAL;
    685 	}
    686 	if (strlen(context.fileset_name) > 32) {
    687 		(void)printf("Fileset name too long\n");
    688 		return EINVAL;
    689 	}
    690 
    691 	/* signal all OK */
    692 	return 0;
    693 }
    694 
    695 /* --------------------------------------------------------------------- */
    696 
    697 static int
    698 udf_prepare_disc(void)
    699 {
    700 	struct mmc_trackinfo ti;
    701 	struct mmc_op        op;
    702 	int tracknr, error;
    703 
    704 	/* If the last track is damaged, repair it */
    705 	ti.tracknr = mmc_discinfo.last_track_last_session;
    706 	error = udf_update_trackinfo(&mmc_discinfo, &ti);
    707 	if (error)
    708 		return error;
    709 
    710 	if (ti.flags & MMC_TRACKINFO_DAMAGED) {
    711 		/*
    712 		 * Need to repair last track before anything can be done.
    713 		 * this is an optional command, so ignore its error but report
    714 		 * warning.
    715 		 */
    716 		memset(&op, 0, sizeof(op));
    717 		op.operation   = MMC_OP_REPAIRTRACK;
    718 		op.mmc_profile = mmc_discinfo.mmc_profile;
    719 		op.tracknr     = ti.tracknr;
    720 		error = ioctl(fd, MMCOP, &op);
    721 
    722 		if (error)
    723 			(void)printf("Drive can't explicitly repair last "
    724 				"damaged track, but it might autorepair\n");
    725 	}
    726 	/* last track (if any) might not be damaged now, operations are ok now */
    727 
    728 	/* setup write parameters from discinfo */
    729 	error = udf_setup_writeparams(&mmc_discinfo);
    730 	if (error)
    731 		return error;
    732 
    733 	/* if the drive is not sequential, we're done */
    734 	if ((mmc_discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) == 0)
    735 		return 0;
    736 
    737 #ifdef notyet
    738 	/* if last track is not the reserved but an empty track, unreserve it */
    739 	if (ti.flags & MMC_TRACKINFO_BLANK) {
    740 		if (ti.flags & MMC_TRACKINFO_RESERVED == 0) {
    741 			memset(&op, 0, sizeof(op));
    742 			op.operation   = MMC_OP_UNRESERVETRACK;
    743 			op.mmc_profile = mmc_discinfo.mmc_profile;
    744 			op.tracknr     = ti.tracknr;
    745 			error = ioctl(fd, MMCOP, &op);
    746 			if (error)
    747 				return error;
    748 
    749 			/* update discinfo since it changed by the operation */
    750 			error = udf_update_discinfo(&mmc_discinfo);
    751 			if (error)
    752 				return error;
    753 		}
    754 	}
    755 #endif
    756 
    757 	/* close the last session if its still open */
    758 	if (mmc_discinfo.last_session_state == MMC_STATE_INCOMPLETE) {
    759 		printf("Closing last open session if present\n");
    760 		/* close all associated tracks */
    761 		tracknr = mmc_discinfo.first_track_last_session;
    762 		while (tracknr <= mmc_discinfo.last_track_last_session) {
    763 			ti.tracknr = tracknr;
    764 			error = udf_update_trackinfo(&mmc_discinfo, &ti);
    765 			if (error)
    766 				return error;
    767 			printf("\tClosing open track %d\n", tracknr);
    768 			memset(&op, 0, sizeof(op));
    769 			op.operation   = MMC_OP_CLOSETRACK;
    770 			op.mmc_profile = mmc_discinfo.mmc_profile;
    771 			op.tracknr     = tracknr;
    772 			error = ioctl(fd, MMCOP, &op);
    773 			if (error)
    774 				return error;
    775 			tracknr ++;
    776 		}
    777 		printf("Closing session\n");
    778 		memset(&op, 0, sizeof(op));
    779 		op.operation   = MMC_OP_CLOSESESSION;
    780 		op.mmc_profile = mmc_discinfo.mmc_profile;
    781 		op.sessionnr   = mmc_discinfo.num_sessions;
    782 		error = ioctl(fd, MMCOP, &op);
    783 		if (error)
    784 			return error;
    785 
    786 		/* update discinfo since it changed by the operations */
    787 		error = udf_update_discinfo(&mmc_discinfo);
    788 		if (error)
    789 			return error;
    790 	}
    791 
    792 	if (format_flags & FORMAT_TRACK512) {
    793 		/* get last track again */
    794 		ti.tracknr = mmc_discinfo.last_track_last_session;
    795 		error = udf_update_trackinfo(&mmc_discinfo, &ti);
    796 		if (error)
    797 			return error;
    798 
    799 		/* Split up the space at 512 for iso cd9660 hooking */
    800 		memset(&op, 0, sizeof(op));
    801 		op.operation   = MMC_OP_RESERVETRACK_NWA;	/* UPTO nwa */
    802 		op.mmc_profile = mmc_discinfo.mmc_profile;
    803 		op.extent      = 512;				/* size */
    804 		error = ioctl(fd, MMCOP, &op);
    805 		if (error)
    806 			return error;
    807 	}
    808 
    809 	return 0;
    810 }
    811 
    812 /* --------------------------------------------------------------------- */
    813 
    814 static int
    815 udf_surface_check(void)
    816 {
    817 	uint32_t loc, block_bytes;
    818 	uint32_t sector_size, blockingnr;
    819 	uint8_t *buffer;
    820 	int error, num_errors;
    821 	int bpos;
    822 
    823 	sector_size = context.sector_size;
    824 	blockingnr  = layout.blockingnr;
    825 
    826 	block_bytes = layout.blockingnr * sector_size;
    827 	if ((buffer = malloc(block_bytes)) == NULL)
    828 		return ENOMEM;
    829 
    830 	/* set all one to not kill Flash memory? */
    831 	for (bpos = 0; bpos < block_bytes; bpos++)
    832 		buffer[bpos] = 0x00;
    833 
    834 	printf("\nChecking disc surface : phase 1 - writing\n");
    835 	num_errors = 0;
    836 	loc = layout.first_lba;
    837 	while (loc <= layout.last_lba) {
    838 		/* write blockingnr sectors */
    839 		error = pwrite(fd, buffer, block_bytes, loc*sector_size);
    840 		printf("   %08d + %d (%02d %%)\r", loc, blockingnr,
    841 			(int)((100.0 * loc)/layout.last_lba));
    842 		fflush(stdout);
    843 		if (error == -1) {
    844 			/* block is bad */
    845 			printf("BAD block at %08d + %d         \n",
    846 				loc, layout.blockingnr);
    847 			if ((error = udf_register_bad_block(loc)))
    848 				return error;
    849 			num_errors ++;
    850 		}
    851 		loc += layout.blockingnr;
    852 	}
    853 
    854 	printf("\nChecking disc surface : phase 2 - reading\n");
    855 	num_errors = 0;
    856 	loc = layout.first_lba;
    857 	while (loc <= layout.last_lba) {
    858 		/* read blockingnr sectors */
    859 		error = pread(fd, buffer, block_bytes, loc*sector_size);
    860 		printf("   %08d + %d (%02d %%)\r", loc, blockingnr,
    861 			(int)((100.0 * loc)/layout.last_lba));
    862 		fflush(stdout);
    863 		if (error == -1) {
    864 			/* block is bad */
    865 			printf("BAD block at %08d + %d         \n",
    866 				loc, layout.blockingnr);
    867 			if ((error = udf_register_bad_block(loc)))
    868 				return error;
    869 			num_errors ++;
    870 		}
    871 		loc += layout.blockingnr;
    872 	}
    873 	printf("Scan complete : %d bad blocks found\n", num_errors);
    874 	free(buffer);
    875 
    876 	return 0;
    877 }
    878 
    879 /* --------------------------------------------------------------------- */
    880 
    881 static int
    882 udf_write_iso9660_vrs(void)
    883 {
    884 	struct vrs_desc *iso9660_vrs_desc;
    885 	uint32_t pos;
    886 	int error, cnt, dpos;
    887 
    888 	/* create ISO/Ecma-167 identification descriptors */
    889 	if ((iso9660_vrs_desc = calloc(1, context.sector_size)) == NULL)
    890 		return ENOMEM;
    891 
    892 	/*
    893 	 * All UDF formats should have their ISO/Ecma-167 descriptors written
    894 	 * except when not possible due to track reservation in the case of
    895 	 * VAT
    896 	 */
    897 	if ((format_flags & FORMAT_TRACK512) == 0) {
    898 		dpos = (2048 + context.sector_size - 1) / context.sector_size;
    899 
    900 		/* wipe at least 6 times 2048 byte `sectors' */
    901 		for (cnt = 0; cnt < 6 *dpos; cnt++) {
    902 			pos = layout.iso9660_vrs + cnt;
    903 			if ((error = udf_write_sector(iso9660_vrs_desc, pos)))
    904 				return error;
    905 		};
    906 
    907 		/* common VRS fields in all written out ISO descriptors */
    908 		iso9660_vrs_desc->struct_type = 0;
    909 		iso9660_vrs_desc->version     = 1;
    910 		pos = layout.iso9660_vrs;
    911 
    912 		/* BEA01, NSR[23], TEA01 */
    913 		memcpy(iso9660_vrs_desc->identifier, "BEA01", 5);
    914 		if ((error = udf_write_sector(iso9660_vrs_desc, pos)))
    915 			return error;
    916 		pos += dpos;
    917 
    918 		if (context.dscrver == 2)
    919 			memcpy(iso9660_vrs_desc->identifier, "NSR02", 5);
    920 		else
    921 			memcpy(iso9660_vrs_desc->identifier, "NSR03", 5);
    922 		;
    923 		if ((error = udf_write_sector(iso9660_vrs_desc, pos)))
    924 			return error;
    925 		pos += dpos;
    926 
    927 		memcpy(iso9660_vrs_desc->identifier, "TEA01", 5);
    928 		if ((error = udf_write_sector(iso9660_vrs_desc, pos)))
    929 			return error;
    930 	}
    931 
    932 	/* return success */
    933 	return 0;
    934 }
    935 
    936 
    937 /* --------------------------------------------------------------------- */
    938 
    939 /*
    940  * Main function that creates and writes out disc contents based on the
    941  * format_flags's that uniquely define the type of disc to create.
    942  */
    943 
    944 int
    945 udf_do_newfs(void)
    946 {
    947 	union dscrptr *zero_dscr;
    948 	union dscrptr *terminator_dscr;
    949 	union dscrptr *root_dscr;
    950 	union dscrptr *vat_dscr;
    951 	union dscrptr *dscr;
    952 	struct mmc_trackinfo ti;
    953 	uint32_t sparable_blocks;
    954 	uint32_t sector_size, blockingnr;
    955 	uint32_t cnt, loc, len;
    956 	int sectcopy;
    957 	int error, integrity_type;
    958 	int data_part, metadata_part;
    959 
    960 	/* init */
    961 	sector_size = mmc_discinfo.sector_size;
    962 
    963 	/* determine span/size */
    964 	ti.tracknr = mmc_discinfo.first_track_last_session;
    965 	error = udf_update_trackinfo(&mmc_discinfo, &ti);
    966 	if (error)
    967 		return error;
    968 
    969 	if (mmc_discinfo.sector_size < context.sector_size) {
    970 		fprintf(stderr, "Impossible to format: sectorsize too small\n");
    971 		return EIO;
    972 	}
    973 	context.sector_size = sector_size;
    974 
    975 	/* determine blockingnr */
    976 	blockingnr = ti.packet_size;
    977 	if (blockingnr <= 1) {
    978 		/* paranoia on blockingnr */
    979 		switch (mmc_discinfo.mmc_profile) {
    980 		case 0x09 : /* CD-R    */
    981 		case 0x0a : /* CD-RW   */
    982 			blockingnr = 32;	/* UDF requirement */
    983 			break;
    984 		case 0x11 : /* DVD-R (DL) */
    985 		case 0x1b : /* DVD+R      */
    986 		case 0x2b : /* DVD+R Dual layer */
    987 		case 0x13 : /* DVD-RW restricted overwrite */
    988 		case 0x14 : /* DVD-RW sequential */
    989 			blockingnr = 16;	/* SCSI definition */
    990 			break;
    991 		case 0x41 : /* BD-R Sequential recording (SRM) */
    992 		case 0x51 : /* HD DVD-R   */
    993 			blockingnr = 32;	/* SCSI definition */
    994 			break;
    995 		default:
    996 			break;
    997 		}
    998 
    999 	}
   1000 	if (blockingnr <= 0) {
   1001 		printf("Can't fixup blockingnumber for device "
   1002 			"type %d\n", mmc_discinfo.mmc_profile);
   1003 
   1004 		printf("Device is not returning valid blocking"
   1005 			" number and media type is unknown.\n");
   1006 
   1007 		return EINVAL;
   1008 	}
   1009 
   1010 	/* setup sector writeout queue's */
   1011 	TAILQ_INIT(&write_queue);
   1012 	wrtrack_skew = ti.track_start % blockingnr;
   1013 
   1014 	if (mmc_discinfo.mmc_class == MMC_CLASS_CD) {
   1015 		/* not too much for CD-RW, still 20Mb */
   1016 		sparable_blocks = 32;
   1017 	} else {
   1018 		/* take a value for DVD*RW mainly, BD is `defect free' */
   1019 		sparable_blocks = 512;
   1020 	}
   1021 
   1022 	/* get layout */
   1023 	error = udf_calculate_disc_layout(format_flags, context.min_udf,
   1024 		wrtrack_skew,
   1025 		ti.track_start, mmc_discinfo.last_possible_lba,
   1026 		sector_size, blockingnr, sparable_blocks);
   1027 
   1028 	/* cache partition for we need it often */
   1029 	data_part     = context.data_part;
   1030 	metadata_part = context.metadata_part;
   1031 
   1032 	/* Create sparing table descriptor if applicable */
   1033 	if (format_flags & FORMAT_SPARABLE) {
   1034 		if ((error = udf_create_sparing_tabled()))
   1035 			return error;
   1036 
   1037 		if (check_surface) {
   1038 			if ((error = udf_surface_check()))
   1039 				return error;
   1040 		}
   1041 	}
   1042 
   1043 	/* Create a generic terminator descriptor */
   1044 	terminator_dscr = calloc(1, sector_size);
   1045 	if (terminator_dscr == NULL)
   1046 		return ENOMEM;
   1047 	udf_create_terminator(terminator_dscr, 0);
   1048 
   1049 	/*
   1050 	 * Start with wipeout of VRS1 upto start of partition. This allows
   1051 	 * formatting for sequentials with the track reservation and it
   1052 	 * cleans old rubbish on rewritables. For sequentuals without the
   1053 	 * track reservation all is wiped from track start.
   1054 	 */
   1055 	if ((zero_dscr = calloc(1, context.sector_size)) == NULL)
   1056 		return ENOMEM;
   1057 
   1058 	loc = (format_flags & FORMAT_TRACK512) ? layout.vds1 : ti.track_start;
   1059 	for (; loc < layout.part_start_lba; loc++) {
   1060 		if ((error = udf_write_sector(zero_dscr, loc)))
   1061 			return error;
   1062 	}
   1063 
   1064 	/* Create anchors */
   1065 	for (cnt = 0; cnt < 3; cnt++) {
   1066 		if ((error = udf_create_anchor(cnt)))
   1067 			return error;
   1068 	}
   1069 
   1070 	/*
   1071 	 * Create the two Volume Descriptor Sets (VDS) each containing the
   1072 	 * following descriptors : primary volume, partition space,
   1073 	 * unallocated space, logical volume, implementation use and the
   1074 	 * terminator
   1075 	 */
   1076 
   1077 	/* start of volume recognision sequence building */
   1078 	context.vds_seq = 0;
   1079 
   1080 	/* Create primary volume descriptor */
   1081 	if ((error = udf_create_primaryd()))
   1082 		return error;
   1083 
   1084 	/* Create partition descriptor */
   1085 	if ((error = udf_create_partitiond(context.data_part, media_accesstype)))
   1086 		return error;
   1087 
   1088 	/* Create unallocated space descriptor */
   1089 	if ((error = udf_create_unalloc_spaced()))
   1090 		return error;
   1091 
   1092 	/* Create logical volume descriptor */
   1093 	if ((error = udf_create_logical_dscr(format_flags)))
   1094 		return error;
   1095 
   1096 	/* Create implementation use descriptor */
   1097 	/* TODO input of fields 1,2,3 and passing them */
   1098 	if ((error = udf_create_impvold(NULL, NULL, NULL)))
   1099 		return error;
   1100 
   1101 	/* write out what we've created so far */
   1102 
   1103 	/* writeout iso9660 vrs */
   1104 	if ((error = udf_write_iso9660_vrs()))
   1105 		return error;
   1106 
   1107 	/* Writeout anchors */
   1108 	for (cnt = 0; cnt < 3; cnt++) {
   1109 		dscr = (union dscrptr *) context.anchors[cnt];
   1110 		loc  = layout.anchors[cnt];
   1111 		if ((error = udf_write_dscr_phys(dscr, loc, 1)))
   1112 			return error;
   1113 
   1114 		/* sequential media has only one anchor */
   1115 		if (format_flags & FORMAT_SEQUENTIAL)
   1116 			break;
   1117 	}
   1118 
   1119 	/* write out main and secondary VRS */
   1120 	for (sectcopy = 1; sectcopy <= 2; sectcopy++) {
   1121 		loc = (sectcopy == 1) ? layout.vds1 : layout.vds2;
   1122 
   1123 		/* primary volume descriptor */
   1124 		dscr = (union dscrptr *) context.primary_vol;
   1125 		error = udf_write_dscr_phys(dscr, loc, 1);
   1126 		if (error)
   1127 			return error;
   1128 		loc++;
   1129 
   1130 		/* partition descriptor(s) */
   1131 		for (cnt = 0; cnt < UDF_PARTITIONS; cnt++) {
   1132 			dscr = (union dscrptr *) context.partitions[cnt];
   1133 			if (dscr) {
   1134 				error = udf_write_dscr_phys(dscr, loc, 1);
   1135 				if (error)
   1136 					return error;
   1137 				loc++;
   1138 			}
   1139 		}
   1140 
   1141 		/* unallocated space descriptor */
   1142 		dscr = (union dscrptr *) context.unallocated;
   1143 		error = udf_write_dscr_phys(dscr, loc, 1);
   1144 		if (error)
   1145 			return error;
   1146 		loc++;
   1147 
   1148 		/* logical volume descriptor */
   1149 		dscr = (union dscrptr *) context.logical_vol;
   1150 		error = udf_write_dscr_phys(dscr, loc, 1);
   1151 		if (error)
   1152 			return error;
   1153 		loc++;
   1154 
   1155 		/* implementation use descriptor */
   1156 		dscr = (union dscrptr *) context.implementation;
   1157 		error = udf_write_dscr_phys(dscr, loc, 1);
   1158 		if (error)
   1159 			return error;
   1160 		loc++;
   1161 
   1162 		/* terminator descriptor */
   1163 		error = udf_write_dscr_phys(terminator_dscr, loc, 1);
   1164 		if (error)
   1165 			return error;
   1166 		loc++;
   1167 	}
   1168 
   1169 	/* writeout the two sparable table descriptors (if needed) */
   1170 	if (format_flags & FORMAT_SPARABLE) {
   1171 		for (sectcopy = 1; sectcopy <= 2; sectcopy++) {
   1172 			loc  = (sectcopy == 1) ? layout.spt_1 : layout.spt_2;
   1173 			dscr = (union dscrptr *) context.sparing_table;
   1174 			len  = layout.sparing_table_dscr_lbas;
   1175 
   1176 			/* writeout */
   1177 			error = udf_write_dscr_phys(dscr, loc, len);
   1178 			if (error)
   1179 				return error;
   1180 		}
   1181 	}
   1182 
   1183 	/*
   1184 	 * Create unallocated space bitmap descriptor. Sequential recorded
   1185 	 * media report their own free/used space; no free/used space tables
   1186 	 * should be recorded for these.
   1187 	 */
   1188 	if ((format_flags & FORMAT_SEQUENTIAL) == 0) {
   1189 		error = udf_create_space_bitmap(
   1190 				&context.part_unalloc_bits[data_part]);
   1191 		/* TODO: freed space bitmap if applicable */
   1192 		/* mark allocated space bitmap itself */
   1193 		udf_mark_allocated(layout.unalloc_space, data_part,
   1194 			layout.bitmap_dscr_size);
   1195 	}
   1196 
   1197 	/* create logical volume integrity descriptor */
   1198 	context.num_files = 0;
   1199 	context.num_directories = 0;
   1200 	integrity_type = UDF_INTEGRITY_OPEN;
   1201 	if ((error = udf_create_lvintd(integrity_type)))
   1202 		return error;
   1203 
   1204 	/* create secondary descriptors for the fileset and rootdir */
   1205 
   1206 	/* create FSD */
   1207 	if ((error = udf_create_fsd()))
   1208 		return error;
   1209 	udf_mark_allocated(layout.fsd, metadata_part, 1);
   1210 
   1211 	/* create root directory */
   1212 	assert(context.unique_id == 0x10);
   1213 	context.unique_id = 0;
   1214 	if ((error = udf_create_new_rootdir(&root_dscr)))
   1215 		return error;
   1216 	udf_mark_allocated(layout.rootdir, metadata_part, 1);
   1217 
   1218 	/* writeout FSD + rootdir */
   1219 	dscr = (union dscrptr *) context.fileset_desc;
   1220 	error = udf_write_dscr_virt(dscr, layout.fsd, metadata_part, 1);
   1221 	if (error)
   1222 		return error;
   1223 
   1224 	error = udf_write_dscr_virt(root_dscr, layout.rootdir, metadata_part, 1);
   1225 	if (error)
   1226 		return error;
   1227 
   1228 	/* writeout initial open integrity sequence + terminator */
   1229 	loc = layout.lvis;
   1230 	dscr = (union dscrptr *) context.logvol_integrity;
   1231 	error = udf_write_dscr_phys(dscr, loc, 1);
   1232 	if (error)
   1233 		return error;
   1234 	loc++;
   1235 	error = udf_write_dscr_phys(terminator_dscr, loc, 1);
   1236 	if (error)
   1237 		return error;
   1238 
   1239 
   1240 	/* XXX the place to add more files */
   1241 
   1242 
   1243 	if ((format_flags & FORMAT_SEQUENTIAL) == 0) {
   1244 		/* update lvint and mark it closed */
   1245 		udf_update_lvintd(UDF_INTEGRITY_CLOSED);
   1246 
   1247 		/* overwrite initial terminator */
   1248 		loc = layout.lvis+1;
   1249 		dscr = (union dscrptr *) context.logvol_integrity;
   1250 		error = udf_write_dscr_phys(dscr, loc, 1);
   1251 		if (error)
   1252 			return error;
   1253 		loc++;
   1254 
   1255 		/* mark end of integrity desciptor sequence again */
   1256 		error = udf_write_dscr_phys(terminator_dscr, loc, 1);
   1257 		if (error)
   1258 			return error;
   1259 	}
   1260 
   1261 	/* write out unallocated space bitmap on non sequential media */
   1262 	if ((format_flags & FORMAT_SEQUENTIAL) == 0) {
   1263 		/* writeout */
   1264 		loc  = layout.unalloc_space;
   1265 		dscr = (union dscrptr *) (context.part_unalloc_bits[data_part]);
   1266 		len  = layout.bitmap_dscr_size;
   1267 		error = udf_write_dscr_virt(dscr, loc, metadata_part, len);
   1268 		if (error)
   1269 			return error;
   1270 	}
   1271 
   1272 	/* create a VAT and account for FSD+root */
   1273 	vat_dscr = NULL;
   1274 	if (format_flags & FORMAT_VAT) {
   1275 		/* update lvint to reflect the newest values (no writeout) */
   1276 		udf_update_lvintd(UDF_INTEGRITY_CLOSED);
   1277 
   1278 		error = udf_create_new_VAT(&vat_dscr);
   1279 		if (error)
   1280 			return error;
   1281 
   1282 		loc = layout.vat;
   1283 		error = udf_write_dscr_virt(vat_dscr, loc, metadata_part, 1);
   1284 		if (error)
   1285 			return error;
   1286 	}
   1287 
   1288 	/* write out sectors */
   1289 	if ((error = writeout_write_queue()))
   1290 		return error;
   1291 
   1292 	/* done */
   1293 	return 0;
   1294 }
   1295 
   1296 /* --------------------------------------------------------------------- */
   1297 
   1298 static void
   1299 usage(void)
   1300 {
   1301 	(void)fprintf(stderr, "Usage: %s [-c] [-F] [-L loglabel] "
   1302 	    "[-M] [-v min_udf] [-V max_udf] [-P discid] [-s size] "
   1303 	    "[-S setlabel] [-t gmtoff] special\n", getprogname());
   1304 	exit(EXIT_FAILURE);
   1305 }
   1306 
   1307 
   1308 int
   1309 main(int argc, char **argv)
   1310 {
   1311 	struct tm *tm;
   1312 	struct stat st;
   1313 	time_t now;
   1314 	char  scrap[255];
   1315 	int ch, req_enable, req_disable, force;
   1316 	int error;
   1317 
   1318 	setprogname(argv[0]);
   1319 
   1320 	/* initialise */
   1321 	format_str    = strdup("");
   1322 	req_enable    = req_disable = 0;
   1323 	format_flags  = FORMAT_INVALID;
   1324 	force         = 0;
   1325 	check_surface = 0;
   1326 
   1327 	srandom((unsigned long) time(NULL));
   1328 	udf_init_create_context();
   1329 	context.app_name  = APP_NAME;
   1330 	context.impl_name = IMPL_NAME;
   1331 	context.app_version_main = APP_VERSION_MAIN;
   1332 	context.app_version_sub  = APP_VERSION_SUB;
   1333 
   1334 	/* minimum and maximum UDF versions we advise */
   1335 	context.min_udf = 0x201;
   1336 	context.max_udf = 0x201;
   1337 
   1338 	/* use user's time zone as default */
   1339 	(void)time(&now);
   1340 	tm = localtime(&now);
   1341 	context.gmtoff = tm->tm_gmtoff;
   1342 
   1343 	/* process options */
   1344 	while ((ch = getopt(argc, argv, "cFL:MP:s:S:t:v:V:")) != -1) {
   1345 		switch (ch) {
   1346 		case 'c' :
   1347 			check_surface = 1;
   1348 			break;
   1349 		case 'F' :
   1350 			force = 1;
   1351 			break;
   1352 		case 'L' :
   1353 			if (context.logvol_name) free(context.logvol_name);
   1354 			context.logvol_name = strdup(optarg);
   1355 			break;
   1356 		case 'M' :
   1357 			req_disable |= FORMAT_META;
   1358 			break;
   1359 		case 'v' :
   1360 			context.min_udf = a_num(optarg, "min_udf");
   1361 			if (context.min_udf > context.max_udf)
   1362 				context.max_udf = context.min_udf;
   1363 			break;
   1364 		case 'V' :
   1365 			context.max_udf = a_num(optarg, "max_udf");
   1366 			if (context.min_udf > context.max_udf)
   1367 				context.min_udf = context.max_udf;
   1368 			break;
   1369 		case 'P' :
   1370 			context.primary_name = strdup(optarg);
   1371 			break;
   1372 		case 's' :
   1373 			/* TODO size argument; recordable emulation */
   1374 			break;
   1375 		case 'S' :
   1376 			if (context.volset_name) free(context.volset_name);
   1377 			context.volset_name = strdup(optarg);
   1378 			break;
   1379 		case 't' :
   1380 			/* time zone overide */
   1381 			context.gmtoff = a_num(optarg, "gmtoff");
   1382 			break;
   1383 		default  :
   1384 			usage();
   1385 			/* NOTREACHED */
   1386 		}
   1387 	}
   1388 
   1389 	if (optind + 1 != argc)
   1390 		usage();
   1391 
   1392 	/* get device and directory specifier */
   1393 	dev = argv[optind];
   1394 
   1395 	/* open device */
   1396 	if ((fd = open(dev, O_RDWR, 0)) == -1) {
   1397 		perror("can't open device");
   1398 		return EXIT_FAILURE;
   1399 	}
   1400 
   1401 	/* stat the device */
   1402 	if (fstat(fd, &st) != 0) {
   1403 		perror("can't stat the device");
   1404 		close(fd);
   1405 		return EXIT_FAILURE;
   1406 	}
   1407 
   1408 	/* Formatting can only be done on raw devices */
   1409 	if (!S_ISCHR(st.st_mode)) {
   1410 		printf("%s is not a raw device\n", dev);
   1411 		close(fd);
   1412 		return EXIT_FAILURE;
   1413 	}
   1414 
   1415 	/* just in case something went wrong, synchronise the drive's cache */
   1416 	udf_synchronise_caches();
   1417 
   1418 	/* get disc information */
   1419 	error = udf_update_discinfo(&mmc_discinfo);
   1420 	if (error) {
   1421 		perror("can't retrieve discinfo");
   1422 		close(fd);
   1423 		return EXIT_FAILURE;
   1424 	}
   1425 
   1426 	/* derive disc identifiers when not specified and check given */
   1427 	error = udf_proces_names();
   1428 	if (error) {
   1429 		/* error message has been printed */
   1430 		close(fd);
   1431 		return EXIT_FAILURE;
   1432 	}
   1433 
   1434 	/* derive newfs disc format from disc profile */
   1435 	error = udf_derive_format(req_enable, req_disable, force);
   1436 	if (error)  {
   1437 		/* error message has been printed */
   1438 		close(fd);
   1439 		return EXIT_FAILURE;
   1440 	}
   1441 
   1442 	udf_dump_discinfo(&mmc_discinfo);
   1443 	printf("Formatting disc compatible with UDF version %x to %x\n\n",
   1444 		context.min_udf, context.max_udf);
   1445 	(void)snprintb(scrap, sizeof(scrap), FORMAT_FLAGBITS,
   1446 	    (uint64_t) format_flags);
   1447 	printf("UDF properties  %s\n", scrap);
   1448 	printf("Volume set      `%s'\n", context.volset_name);
   1449 	printf("Primary volume  `%s`\n", context.primary_name);
   1450 	printf("Logical volume  `%s`\n", context.logvol_name);
   1451 	printf("\n");
   1452 
   1453 	/* prepare disc if nessisary (recordables mainly) */
   1454 	error = udf_prepare_disc();
   1455 	if (error) {
   1456 		perror("preparing disc failed");
   1457 		close(fd);
   1458 		return EXIT_FAILURE;
   1459 	};
   1460 
   1461 	/* set up administration */
   1462 	error = udf_do_newfs();
   1463 
   1464 	/* in any case, synchronise the drive's cache to prevent lockups */
   1465 	udf_synchronise_caches();
   1466 
   1467 	close(fd);
   1468 	if (error)
   1469 		return EXIT_FAILURE;
   1470 
   1471 	return EXIT_SUCCESS;
   1472 }
   1473 
   1474 /* --------------------------------------------------------------------- */
   1475 
   1476