Home | History | Annotate | Line # | Download | only in newfs_udf
newfs_udf.c revision 1.20
      1 /* $NetBSD: newfs_udf.c,v 1.20 2020/04/05 15:25:40 joerg 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 
     29 /*
     30  * TODO
     31  * - implement metadata formatting for BD-R
     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 <time.h>
     51 #include <assert.h>
     52 #include <err.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 
     66 #include "mountprog.h"
     67 #include "udf_create.h"
     68 #include "udf_write.h"
     69 #include "newfs_udf.h"
     70 
     71 /* prototypes */
     72 int newfs_udf(int argc, char **argv);
     73 static void usage(void) __attribute__((__noreturn__));
     74 
     75 /* queue for temporary storage of sectors to be written out */
     76 struct wrsect {
     77 	uint64_t  sectornr;
     78 	uint8_t	 *sector_data;
     79 	TAILQ_ENTRY(wrsect) next;
     80 };
     81 
     82 /* write queue and track blocking skew */
     83 TAILQ_HEAD(wrsect_list, wrsect) write_queue;
     84 
     85 
     86 /* global variables describing disc and format requests */
     87 int	 fd;				/* device: file descriptor */
     88 char	*dev;				/* device: name		   */
     89 struct mmc_discinfo mmc_discinfo;	/* device: disc info	   */
     90 
     91 char	*format_str;			/* format: string representation */
     92 int	 format_flags;			/* format: attribute flags	 */
     93 int	 media_accesstype;		/* derived from current mmc cap  */
     94 int	 check_surface;			/* for rewritables               */
     95 int	 imagefile_secsize;		/* for files			 */
     96 int	 emul_packetsize;		/* for discs and files		 */
     97 
     98 int	 wrtrack_skew;
     99 int	 meta_perc = UDF_META_PERC;
    100 float	 meta_fract = (float) UDF_META_PERC / 100.0;
    101 
    102 
    103 /* --------------------------------------------------------------------- */
    104 
    105 /*
    106  * write queue implementation
    107  */
    108 
    109 int
    110 udf_write_sector(void *sector, uint64_t location)
    111 {
    112 	struct wrsect *pos, *seekpos;
    113 
    114 
    115 	/* search location */
    116 	TAILQ_FOREACH_REVERSE(seekpos, &write_queue, wrsect_list, next) {
    117 		if (seekpos->sectornr <= location)
    118 			break;
    119 	}
    120 	if ((seekpos == NULL) || (seekpos->sectornr != location)) {
    121 		pos = calloc(1, sizeof(struct wrsect));
    122 		if (pos == NULL)
    123 			return errno;
    124 		/* allocate space for copy of sector data */
    125 		pos->sector_data = calloc(1, context.sector_size);
    126 		if (pos->sector_data == NULL) {
    127 			free(pos);
    128 			return errno;
    129 		}
    130 		pos->sectornr = location;
    131 
    132 		if (seekpos) {
    133 			TAILQ_INSERT_AFTER(&write_queue, seekpos, pos, next);
    134 		} else {
    135 			TAILQ_INSERT_HEAD(&write_queue, pos, next);
    136 		}
    137 	} else {
    138 		pos = seekpos;
    139 	}
    140 	memcpy(pos->sector_data, sector, context.sector_size);
    141 
    142 	return 0;
    143 }
    144 
    145 
    146 /*
    147  * Now all write requests are queued in the TAILQ, write them out to the
    148  * disc/file image. Special care needs to be taken for devices that are only
    149  * strict overwritable i.e. only in packet size chunks
    150  *
    151  * XXX support for growing vnd?
    152  */
    153 
    154 int
    155 writeout_write_queue(void)
    156 {
    157 	struct wrsect *pos;
    158 	uint64_t offset;
    159 	uint64_t line_start, new_line_start;
    160 	uint32_t line_len, line_offset, relpos;
    161 	uint32_t blockingnr;
    162 	uint8_t *linebuf, *adr;
    163 
    164 	blockingnr  = layout.blockingnr;
    165 	line_len    = blockingnr   * context.sector_size;
    166 	line_offset = wrtrack_skew * context.sector_size;
    167 
    168 	linebuf     = malloc(line_len);
    169 	if (linebuf == NULL)
    170 		return ENOMEM;
    171 
    172 	pos = TAILQ_FIRST(&write_queue);
    173 	bzero(linebuf, line_len);
    174 
    175 	/*
    176 	 * Always writing out in whole lines now; this is slightly wastefull
    177 	 * on logical overwrite volumes but it reduces complexity and the loss
    178 	 * is near zero compared to disc size.
    179 	 */
    180 	line_start = (pos->sectornr - wrtrack_skew) / blockingnr;
    181 	TAILQ_FOREACH(pos, &write_queue, next) {
    182 		new_line_start = (pos->sectornr - wrtrack_skew) / blockingnr;
    183 		if (new_line_start != line_start) {
    184 			/* write out */
    185 			offset = (uint64_t) line_start * line_len + line_offset;
    186 #ifdef DEBUG
    187 			printf("WRITEOUT %08"PRIu64" + %02d -- "
    188 				"[%08"PRIu64"..%08"PRIu64"]\n",
    189 				offset / context.sector_size, blockingnr,
    190 				offset / context.sector_size,
    191 				offset / context.sector_size + blockingnr-1);
    192 #endif
    193 			if (pwrite(fd, linebuf, line_len, offset) < 0) {
    194 				perror("Writing failed");
    195 				return errno;
    196 			}
    197 			line_start = new_line_start;
    198 			bzero(linebuf, line_len);
    199 		}
    200 
    201 		relpos = (pos->sectornr - wrtrack_skew) % blockingnr;
    202 		adr = linebuf + relpos * context.sector_size;
    203 		memcpy(adr, pos->sector_data, context.sector_size);
    204 	}
    205 	/* writeout last chunk */
    206 	offset = (uint64_t) line_start * line_len + line_offset;
    207 #ifdef DEBUG
    208 	printf("WRITEOUT %08"PRIu64" + %02d -- [%08"PRIu64"..%08"PRIu64"]\n",
    209 		offset / context.sector_size, blockingnr,
    210 		offset / context.sector_size,
    211 		offset / context.sector_size + blockingnr-1);
    212 #endif
    213 	if (pwrite(fd, linebuf, line_len, offset) < 0) {
    214 		perror("Writing failed");
    215 		return errno;
    216 	}
    217 
    218 	/* success */
    219 	return 0;
    220 }
    221 
    222 /* --------------------------------------------------------------------- */
    223 
    224 /*
    225  * mmc_discinfo and mmc_trackinfo readers modified from origional in udf main
    226  * code in sys/fs/udf/
    227  */
    228 
    229 #ifdef DEBUG
    230 static void
    231 udf_dump_discinfo(struct mmc_discinfo *di)
    232 {
    233 	char bits[128];
    234 
    235 	printf("Device/media info  :\n");
    236 	printf("\tMMC profile        0x%02x\n", di->mmc_profile);
    237 	printf("\tderived class      %d\n", di->mmc_class);
    238 	printf("\tsector size        %d\n", di->sector_size);
    239 	printf("\tdisc state         %d\n", di->disc_state);
    240 	printf("\tlast ses state     %d\n", di->last_session_state);
    241 	printf("\tbg format state    %d\n", di->bg_format_state);
    242 	printf("\tfrst track         %d\n", di->first_track);
    243 	printf("\tfst on last ses    %d\n", di->first_track_last_session);
    244 	printf("\tlst on last ses    %d\n", di->last_track_last_session);
    245 	printf("\tlink block penalty %d\n", di->link_block_penalty);
    246 	snprintb(bits, sizeof(bits), MMC_DFLAGS_FLAGBITS, (uint64_t) di->disc_flags);
    247 	printf("\tdisc flags         %s\n", bits);
    248 	printf("\tdisc id            %x\n", di->disc_id);
    249 	printf("\tdisc barcode       %"PRIx64"\n", di->disc_barcode);
    250 
    251 	printf("\tnum sessions       %d\n", di->num_sessions);
    252 	printf("\tnum tracks         %d\n", di->num_tracks);
    253 
    254 	snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cur);
    255 	printf("\tcapabilities cur   %s\n", bits);
    256 	snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cap);
    257 	printf("\tcapabilities cap   %s\n", bits);
    258 	printf("\n");
    259 	printf("\tlast_possible_lba  %d\n", di->last_possible_lba);
    260 	printf("\n");
    261 }
    262 #else
    263 #define udf_dump_discinfo(a);
    264 #endif
    265 
    266 /* --------------------------------------------------------------------- */
    267 
    268 static int
    269 udf_update_discinfo(struct mmc_discinfo *di)
    270 {
    271 	struct stat st;
    272 	struct disklabel  disklab;
    273 	struct partition *dp;
    274 	off_t size, sectors, secsize;
    275 	int partnr, error;
    276 
    277 	memset(di, 0, sizeof(struct mmc_discinfo));
    278 
    279 	/* check if we're on a MMC capable device, i.e. CD/DVD */
    280 	error = ioctl(fd, MMCGETDISCINFO, di);
    281 	if (error == 0)
    282 		return 0;
    283 
    284 	/* (re)fstat the file */
    285 	fstat(fd, &st);
    286 
    287 	if (S_ISREG(st.st_mode)) {
    288 		/* file support; we pick the minimum sector size allowed */
    289 		size = st.st_size;
    290 		secsize = imagefile_secsize;
    291 		sectors = size / secsize;
    292 	} else {
    293 		/*
    294 		 * disc partition support; note we can't use DIOCGPART in
    295 		 * userland so get disc label and use the stat info to get the
    296 		 * partition number.
    297 		 */
    298 		if (ioctl(fd, DIOCGDINFO, &disklab) == -1) {
    299 			/* failed to get disclabel! */
    300 			perror("disklabel");
    301 			return errno;
    302 		}
    303 
    304 		/* get disk partition it refers to */
    305 		fstat(fd, &st);
    306 		partnr = DISKPART(st.st_rdev);
    307 		dp = &disklab.d_partitions[partnr];
    308 
    309 		/* TODO problem with last_possible_lba on resizable VND */
    310 		if (dp->p_size == 0) {
    311 			perror("faulty disklabel partition returned, "
    312 				"check label\n");
    313 			return EIO;
    314 		}
    315 
    316 		sectors = dp->p_size;
    317 		secsize = disklab.d_secsize;
    318 	}
    319 
    320 	/* set up a disc info profile for partitions */
    321 	di->mmc_profile		= 0x01;	/* disc type */
    322 	di->mmc_class		= MMC_CLASS_DISC;
    323 	di->disc_state		= MMC_STATE_CLOSED;
    324 	di->last_session_state	= MMC_STATE_CLOSED;
    325 	di->bg_format_state	= MMC_BGFSTATE_COMPLETED;
    326 	di->link_block_penalty	= 0;
    327 
    328 	di->mmc_cur     = MMC_CAP_RECORDABLE | MMC_CAP_REWRITABLE |
    329 		MMC_CAP_ZEROLINKBLK | MMC_CAP_HW_DEFECTFREE;
    330 	di->mmc_cap    = di->mmc_cur;
    331 	di->disc_flags = MMC_DFLAGS_UNRESTRICTED;
    332 
    333 	di->last_possible_lba = sectors - 1;
    334 	di->sector_size       = secsize;
    335 
    336 	di->num_sessions = 1;
    337 	di->num_tracks   = 1;
    338 
    339 	di->first_track  = 1;
    340 	di->first_track_last_session = di->last_track_last_session = 1;
    341 
    342 	return 0;
    343 }
    344 
    345 
    346 int
    347 udf_update_trackinfo(struct mmc_discinfo *di, struct mmc_trackinfo *ti)
    348 {
    349 	int error, class;
    350 
    351 	class = di->mmc_class;
    352 	if (class != MMC_CLASS_DISC) {
    353 		/* tracknr specified in struct ti */
    354 		error = ioctl(fd, MMCGETTRACKINFO, ti);
    355 		return error;
    356 	}
    357 
    358 	/* discs partition support */
    359 	if (ti->tracknr != 1)
    360 		return EIO;
    361 
    362 	/* create fake ti (TODO check for resized vnds) */
    363 	ti->sessionnr  = 1;
    364 
    365 	ti->track_mode = 0;	/* XXX */
    366 	ti->data_mode  = 0;	/* XXX */
    367 	ti->flags = MMC_TRACKINFO_LRA_VALID | MMC_TRACKINFO_NWA_VALID;
    368 
    369 	ti->track_start    = 0;
    370 	ti->packet_size    = emul_packetsize;
    371 
    372 	/* TODO support for resizable vnd */
    373 	ti->track_size    = di->last_possible_lba;
    374 	ti->next_writable = di->last_possible_lba;
    375 	ti->last_recorded = ti->next_writable;
    376 	ti->free_blocks   = 0;
    377 
    378 	return 0;
    379 }
    380 
    381 
    382 static int
    383 udf_setup_writeparams(struct mmc_discinfo *di)
    384 {
    385 	struct mmc_writeparams mmc_writeparams;
    386 	int error;
    387 
    388 	if (di->mmc_class == MMC_CLASS_DISC)
    389 		return 0;
    390 
    391 	/*
    392 	 * only CD burning normally needs setting up, but other disc types
    393 	 * might need other settings to be made. The MMC framework will set up
    394 	 * the nessisary recording parameters according to the disc
    395 	 * characteristics read in. Modifications can be made in the discinfo
    396 	 * structure passed to change the nature of the disc.
    397 	 */
    398 	memset(&mmc_writeparams, 0, sizeof(struct mmc_writeparams));
    399 	mmc_writeparams.mmc_class  = di->mmc_class;
    400 	mmc_writeparams.mmc_cur    = di->mmc_cur;
    401 
    402 	/*
    403 	 * UDF dictates first track to determine track mode for the whole
    404 	 * disc. [UDF 1.50/6.10.1.1, UDF 1.50/6.10.2.1]
    405 	 * To prevent problems with a `reserved' track in front we start with
    406 	 * the 2nd track and if that is not valid, go for the 1st.
    407 	 */
    408 	mmc_writeparams.tracknr = 2;
    409 	mmc_writeparams.data_mode  = MMC_DATAMODE_DEFAULT;	/* XA disc */
    410 	mmc_writeparams.track_mode = MMC_TRACKMODE_DEFAULT;	/* data */
    411 
    412 	error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams);
    413 	if (error) {
    414 		mmc_writeparams.tracknr = 1;
    415 		error = ioctl(fd, MMCSETUPWRITEPARAMS, &mmc_writeparams);
    416 	}
    417 	return error;
    418 }
    419 
    420 
    421 static void
    422 udf_synchronise_caches(void)
    423 {
    424 	struct mmc_op mmc_op;
    425 
    426 	bzero(&mmc_op, sizeof(struct mmc_op));
    427 	mmc_op.operation = MMC_OP_SYNCHRONISECACHE;
    428 
    429 	/* this device might not know this ioct, so just be ignorant */
    430 	(void) ioctl(fd, MMCOP, &mmc_op);
    431 }
    432 
    433 /* --------------------------------------------------------------------- */
    434 
    435 static int
    436 udf_prepare_disc(void)
    437 {
    438 	struct mmc_trackinfo ti;
    439 	struct mmc_op        op;
    440 	int tracknr, error;
    441 
    442 	/* If the last track is damaged, repair it */
    443 	ti.tracknr = mmc_discinfo.last_track_last_session;
    444 	error = udf_update_trackinfo(&mmc_discinfo, &ti);
    445 	if (error)
    446 		return error;
    447 
    448 	if (ti.flags & MMC_TRACKINFO_DAMAGED) {
    449 		/*
    450 		 * Need to repair last track before anything can be done.
    451 		 * this is an optional command, so ignore its error but report
    452 		 * warning.
    453 		 */
    454 		memset(&op, 0, sizeof(op));
    455 		op.operation   = MMC_OP_REPAIRTRACK;
    456 		op.mmc_profile = mmc_discinfo.mmc_profile;
    457 		op.tracknr     = ti.tracknr;
    458 		error = ioctl(fd, MMCOP, &op);
    459 
    460 		if (error)
    461 			(void)printf("Drive can't explicitly repair last "
    462 				"damaged track, but it might autorepair\n");
    463 	}
    464 	/* last track (if any) might not be damaged now, operations are ok now */
    465 
    466 	/* setup write parameters from discinfo */
    467 	error = udf_setup_writeparams(&mmc_discinfo);
    468 	if (error)
    469 		return error;
    470 
    471 	/* if the drive is not sequential, we're done */
    472 	if ((mmc_discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) == 0)
    473 		return 0;
    474 
    475 #ifdef notyet
    476 	/* if last track is not the reserved but an empty track, unreserve it */
    477 	if (ti.flags & MMC_TRACKINFO_BLANK) {
    478 		if (ti.flags & MMC_TRACKINFO_RESERVED == 0) {
    479 			memset(&op, 0, sizeof(op));
    480 			op.operation   = MMC_OP_UNRESERVETRACK;
    481 			op.mmc_profile = mmc_discinfo.mmc_profile;
    482 			op.tracknr     = ti.tracknr;
    483 			error = ioctl(fd, MMCOP, &op);
    484 			if (error)
    485 				return error;
    486 
    487 			/* update discinfo since it changed by the operation */
    488 			error = udf_update_discinfo(&mmc_discinfo);
    489 			if (error)
    490 				return error;
    491 		}
    492 	}
    493 #endif
    494 
    495 	/* close the last session if its still open */
    496 	if (mmc_discinfo.last_session_state == MMC_STATE_INCOMPLETE) {
    497 		printf("Closing last open session if present\n");
    498 		/* close all associated tracks */
    499 		tracknr = mmc_discinfo.first_track_last_session;
    500 		while (tracknr <= mmc_discinfo.last_track_last_session) {
    501 			ti.tracknr = tracknr;
    502 			error = udf_update_trackinfo(&mmc_discinfo, &ti);
    503 			if (error)
    504 				return error;
    505 			printf("\tClosing open track %d\n", tracknr);
    506 			memset(&op, 0, sizeof(op));
    507 			op.operation   = MMC_OP_CLOSETRACK;
    508 			op.mmc_profile = mmc_discinfo.mmc_profile;
    509 			op.tracknr     = tracknr;
    510 			error = ioctl(fd, MMCOP, &op);
    511 			if (error)
    512 				return error;
    513 			tracknr ++;
    514 		}
    515 		printf("Closing session\n");
    516 		memset(&op, 0, sizeof(op));
    517 		op.operation   = MMC_OP_CLOSESESSION;
    518 		op.mmc_profile = mmc_discinfo.mmc_profile;
    519 		op.sessionnr   = mmc_discinfo.num_sessions;
    520 		error = ioctl(fd, MMCOP, &op);
    521 		if (error)
    522 			return error;
    523 
    524 		/* update discinfo since it changed by the operations */
    525 		error = udf_update_discinfo(&mmc_discinfo);
    526 		if (error)
    527 			return error;
    528 	}
    529 
    530 	if (format_flags & FORMAT_TRACK512) {
    531 		/* get last track again */
    532 		ti.tracknr = mmc_discinfo.last_track_last_session;
    533 		error = udf_update_trackinfo(&mmc_discinfo, &ti);
    534 		if (error)
    535 			return error;
    536 
    537 		/* Split up the space at 512 for iso cd9660 hooking */
    538 		memset(&op, 0, sizeof(op));
    539 		op.operation   = MMC_OP_RESERVETRACK_NWA;	/* UPTO nwa */
    540 		op.mmc_profile = mmc_discinfo.mmc_profile;
    541 		op.extent      = 512;				/* size */
    542 		error = ioctl(fd, MMCOP, &op);
    543 		if (error)
    544 			return error;
    545 	}
    546 
    547 	return 0;
    548 }
    549 
    550 /* --------------------------------------------------------------------- */
    551 
    552 int
    553 udf_surface_check(void)
    554 {
    555 	uint32_t loc, block_bytes;
    556 	uint32_t sector_size, blockingnr, bpos;
    557 	uint8_t *buffer;
    558 	int error, num_errors;
    559 
    560 	sector_size = context.sector_size;
    561 	blockingnr  = layout.blockingnr;
    562 
    563 	block_bytes = layout.blockingnr * sector_size;
    564 	if ((buffer = malloc(block_bytes)) == NULL)
    565 		return ENOMEM;
    566 
    567 	/* set all one to not kill Flash memory? */
    568 	for (bpos = 0; bpos < block_bytes; bpos++)
    569 		buffer[bpos] = 0x00;
    570 
    571 	printf("\nChecking disc surface : phase 1 - writing\n");
    572 	num_errors = 0;
    573 	loc = layout.first_lba;
    574 	while (loc <= layout.last_lba) {
    575 		/* write blockingnr sectors */
    576 		error = pwrite(fd, buffer, block_bytes, loc*sector_size);
    577 		printf("   %08d + %d (%02d %%)\r", loc, blockingnr,
    578 			(int)((100.0 * loc)/layout.last_lba));
    579 		fflush(stdout);
    580 		if (error == -1) {
    581 			/* block is bad */
    582 			printf("BAD block at %08d + %d         \n",
    583 				loc, layout.blockingnr);
    584 			if ((error = udf_register_bad_block(loc))) {
    585 				free(buffer);
    586 				return error;
    587 			}
    588 			num_errors ++;
    589 		}
    590 		loc += layout.blockingnr;
    591 	}
    592 
    593 	printf("\nChecking disc surface : phase 2 - reading\n");
    594 	num_errors = 0;
    595 	loc = layout.first_lba;
    596 	while (loc <= layout.last_lba) {
    597 		/* read blockingnr sectors */
    598 		error = pread(fd, buffer, block_bytes, loc*sector_size);
    599 		printf("   %08d + %d (%02d %%)\r", loc, blockingnr,
    600 			(int)((100.0 * loc)/layout.last_lba));
    601 		fflush(stdout);
    602 		if (error == -1) {
    603 			/* block is bad */
    604 			printf("BAD block at %08d + %d         \n",
    605 				loc, layout.blockingnr);
    606 			if ((error = udf_register_bad_block(loc))) {
    607 				free(buffer);
    608 				return error;
    609 			}
    610 			num_errors ++;
    611 		}
    612 		loc += layout.blockingnr;
    613 	}
    614 	printf("Scan complete : %d bad blocks found\n", num_errors);
    615 	free(buffer);
    616 
    617 	return 0;
    618 }
    619 
    620 
    621 /* --------------------------------------------------------------------- */
    622 
    623 static int
    624 udf_do_newfs(void)
    625 {
    626 	int error;
    627 
    628 	error = udf_do_newfs_prefix();
    629 	if (error)
    630 		return error;
    631 	error = udf_do_rootdir();
    632 	if (error)
    633 		return error;
    634 	error = udf_do_newfs_postfix();
    635 
    636 	return error;
    637 }
    638 
    639 
    640 
    641 /* --------------------------------------------------------------------- */
    642 
    643 static void
    644 usage(void)
    645 {
    646 	(void)fprintf(stderr, "Usage: %s [-cFM] [-L loglabel] "
    647 	    "[-P discid] [-S sectorsize] [-s size] [-p perc] "
    648 	    "[-t gmtoff] [-v min_udf] [-V max_udf] special\n", getprogname());
    649 	exit(EXIT_FAILURE);
    650 }
    651 
    652 
    653 int
    654 main(int argc, char **argv)
    655 {
    656 	struct tm *tm;
    657 	struct stat st;
    658 	time_t now;
    659 	off_t setsize;
    660 	char  scrap[255], *colon;
    661 	int ch, req_enable, req_disable, force;
    662 	int error;
    663 
    664 	setprogname(argv[0]);
    665 
    666 	/* initialise */
    667 	format_str    = strdup("");
    668 	req_enable    = req_disable = 0;
    669 	format_flags  = FORMAT_INVALID;
    670 	force         = 0;
    671 	check_surface = 0;
    672 	setsize       = 0;
    673 	imagefile_secsize = 512;	/* minimum allowed sector size */
    674 	emul_packetsize   = 32;		/* reasonable default */
    675 
    676 	srandom((unsigned long) time(NULL));
    677 	udf_init_create_context();
    678 	context.app_name         = "*NetBSD newfs";
    679 	context.app_version_main = APP_VERSION_MAIN;
    680 	context.app_version_sub  = APP_VERSION_SUB;
    681 	context.impl_name        = IMPL_NAME;
    682 
    683 	/* minimum and maximum UDF versions we advise */
    684 	context.min_udf = 0x201;
    685 	context.max_udf = 0x201;
    686 
    687 	/* use user's time zone as default */
    688 	(void)time(&now);
    689 	tm = localtime(&now);
    690 	context.gmtoff = tm->tm_gmtoff;
    691 
    692 	/* process options */
    693 	while ((ch = getopt(argc, argv, "cFL:Mp:P:s:S:B:t:v:V:")) != -1) {
    694 		switch (ch) {
    695 		case 'c' :
    696 			check_surface = 1;
    697 			break;
    698 		case 'F' :
    699 			force = 1;
    700 			break;
    701 		case 'L' :
    702 			if (context.logvol_name) free(context.logvol_name);
    703 			context.logvol_name = strdup(optarg);
    704 			break;
    705 		case 'M' :
    706 			req_disable |= FORMAT_META;
    707 			break;
    708 		case 'p' :
    709 			meta_perc = a_num(optarg, "meta_perc");
    710 			/* limit to `sensible` values */
    711 			meta_perc = MIN(meta_perc, 99);
    712 			meta_perc = MAX(meta_perc, 1);
    713 			meta_fract = (float) meta_perc/100.0;
    714 			break;
    715 		case 'v' :
    716 			context.min_udf = a_udf_version(optarg, "min_udf");
    717 			if (context.min_udf > context.max_udf)
    718 				context.max_udf = context.min_udf;
    719 			break;
    720 		case 'V' :
    721 			context.max_udf = a_udf_version(optarg, "max_udf");
    722 			if (context.min_udf > context.max_udf)
    723 				context.min_udf = context.max_udf;
    724 			break;
    725 		case 'P' :
    726 			/* check if there is a ':' in the name */
    727 			if ((colon = strstr(optarg, ":"))) {
    728 				if (context.volset_name)
    729 					free(context.volset_name);
    730 				*colon = 0;
    731 				context.volset_name = strdup(optarg);
    732 				optarg = colon+1;
    733 			}
    734 			if (context.primary_name)
    735 				free(context.primary_name);
    736 			if ((strstr(optarg, ":"))) {
    737 				perror("primary name can't have ':' in its name");
    738 				return EXIT_FAILURE;
    739 			}
    740 			context.primary_name = strdup(optarg);
    741 			break;
    742 		case 's' :
    743 			/* support for files, set file size */
    744 			/* XXX support for formatting recordables on vnd/file? */
    745 			if (dehumanize_number(optarg, &setsize) < 0) {
    746 				perror("can't parse size argument");
    747 				return EXIT_FAILURE;
    748 			}
    749 			setsize = MAX(0, setsize);
    750 			break;
    751 		case 'S' :
    752 			imagefile_secsize = a_num(optarg, "secsize");
    753 			imagefile_secsize = MAX(512, imagefile_secsize);
    754 			break;
    755 		case 'B' :
    756 			emul_packetsize = a_num(optarg,
    757 				"blockingnr, packetsize");
    758 			emul_packetsize = MAX(emul_packetsize, 1);
    759 			emul_packetsize = MIN(emul_packetsize, 32);
    760 			break;
    761 		case 't' :
    762 			/* time zone overide */
    763 			context.gmtoff = a_num(optarg, "gmtoff");
    764 			break;
    765 		default  :
    766 			usage();
    767 			/* NOTREACHED */
    768 		}
    769 	}
    770 
    771 	if (optind + 1 != argc)
    772 		usage();
    773 
    774 	/* get device and directory specifier */
    775 	dev = argv[optind];
    776 
    777 	/* open device */
    778 	if ((fd = open(dev, O_RDWR, 0)) == -1) {
    779 		/* check if we need to create a file */
    780 		fd = open(dev, O_RDONLY, 0);
    781 		if (fd > 0) {
    782 			perror("device is there but can't be opened for read/write");
    783 			return EXIT_FAILURE;
    784 		}
    785 		if (!force) {
    786 			perror("can't open device");
    787 			return EXIT_FAILURE;
    788 		}
    789 		if (setsize == 0) {
    790 			perror("need to create image file but no size specified");
    791 			return EXIT_FAILURE;
    792 		}
    793 		/* need to create a file */
    794 		fd = open(dev, O_RDWR | O_CREAT | O_TRUNC, 0777);
    795 		if (fd == -1) {
    796 			perror("can't create image file");
    797 			return EXIT_FAILURE;
    798 		}
    799 	}
    800 
    801 	/* stat the device */
    802 	if (fstat(fd, &st) != 0) {
    803 		perror("can't stat the device");
    804 		close(fd);
    805 		return EXIT_FAILURE;
    806 	}
    807 
    808 	if (S_ISREG(st.st_mode)) {
    809 		if (setsize == 0)
    810 			setsize = st.st_size;
    811 		/* sanitise arguments */
    812 		imagefile_secsize &= ~511;
    813 		setsize &= ~(imagefile_secsize-1);
    814 
    815 		if (ftruncate(fd, setsize)) {
    816 			perror("can't resize file");
    817 			return EXIT_FAILURE;
    818 		}
    819 	}
    820 
    821 	/* formatting can only be done on raw devices */
    822 	if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode)) {
    823 		printf("%s is not a raw device\n", dev);
    824 		close(fd);
    825 		return EXIT_FAILURE;
    826 	}
    827 
    828 	/* just in case something went wrong, synchronise the drive's cache */
    829 	udf_synchronise_caches();
    830 
    831 	/* get 'disc' information */
    832 	error = udf_update_discinfo(&mmc_discinfo);
    833 	if (error) {
    834 		perror("can't retrieve discinfo");
    835 		close(fd);
    836 		return EXIT_FAILURE;
    837 	}
    838 
    839 	/* derive disc identifiers when not specified and check given */
    840 	error = udf_proces_names();
    841 	if (error) {
    842 		/* error message has been printed */
    843 		close(fd);
    844 		return EXIT_FAILURE;
    845 	}
    846 
    847 	/* derive newfs disc format from disc profile */
    848 	error = udf_derive_format(req_enable, req_disable, force);
    849 	if (error)  {
    850 		/* error message has been printed */
    851 		close(fd);
    852 		return EXIT_FAILURE;
    853 	}
    854 
    855 	udf_dump_discinfo(&mmc_discinfo);
    856 	printf("Formatting disc compatible with UDF version %x to %x\n\n",
    857 		context.min_udf, context.max_udf);
    858 	(void)snprintb(scrap, sizeof(scrap), FORMAT_FLAGBITS,
    859 	    (uint64_t) format_flags);
    860 	printf("UDF properties       %s\n", scrap);
    861 	printf("Volume set          `%s'\n", context.volset_name);
    862 	printf("Primary volume      `%s`\n", context.primary_name);
    863 	printf("Logical volume      `%s`\n", context.logvol_name);
    864 	if (format_flags & FORMAT_META)
    865 		printf("Metadata percentage  %d %%\n", meta_perc);
    866 	printf("\n");
    867 
    868 	/* prepare disc if nessisary (recordables mainly) */
    869 	error = udf_prepare_disc();
    870 	if (error) {
    871 		perror("preparing disc failed");
    872 		close(fd);
    873 		return EXIT_FAILURE;
    874 	};
    875 
    876 	/* setup sector writeout queue's */
    877 	TAILQ_INIT(&write_queue);
    878 
    879 	/* perform the newfs itself */
    880 	error = udf_do_newfs();
    881 	if (!error) {
    882 		/* write out sectors */
    883 		error = writeout_write_queue();
    884 	}
    885 
    886 	/* in any case, synchronise the drive's cache to prevent lockups */
    887 	udf_synchronise_caches();
    888 
    889 	close(fd);
    890 	if (error)
    891 		return EXIT_FAILURE;
    892 
    893 	return EXIT_SUCCESS;
    894 }
    895 
    896 /* --------------------------------------------------------------------- */
    897 
    898