Home | History | Annotate | Line # | Download | only in udf
udf_subr.c revision 1.30
      1 /* $NetBSD: udf_subr.c,v 1.30 2007/01/17 12:49:01 reinoud Exp $ */
      2 
      3 /*
      4  * Copyright (c) 2006 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  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *          This product includes software developed for the
     18  *          NetBSD Project.  See http://www.NetBSD.org/ for
     19  *          information about NetBSD.
     20  * 4. The name of the author may not be used to endorse or promote products
     21  *    derived from this software without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     33  *
     34  */
     35 
     36 
     37 #include <sys/cdefs.h>
     38 #ifndef lint
     39 __RCSID("$NetBSD: udf_subr.c,v 1.30 2007/01/17 12:49:01 reinoud Exp $");
     40 #endif /* not lint */
     41 
     42 
     43 #if defined(_KERNEL_OPT)
     44 #include "opt_quota.h"
     45 #include "opt_compat_netbsd.h"
     46 #endif
     47 
     48 #include <sys/param.h>
     49 #include <sys/systm.h>
     50 #include <sys/sysctl.h>
     51 #include <sys/namei.h>
     52 #include <sys/proc.h>
     53 #include <sys/kernel.h>
     54 #include <sys/vnode.h>
     55 #include <miscfs/genfs/genfs_node.h>
     56 #include <sys/mount.h>
     57 #include <sys/buf.h>
     58 #include <sys/file.h>
     59 #include <sys/device.h>
     60 #include <sys/disklabel.h>
     61 #include <sys/ioctl.h>
     62 #include <sys/malloc.h>
     63 #include <sys/dirent.h>
     64 #include <sys/stat.h>
     65 #include <sys/conf.h>
     66 #include <sys/kauth.h>
     67 #include <dev/clock_subr.h>
     68 
     69 #include <fs/udf/ecma167-udf.h>
     70 #include <fs/udf/udf_mount.h>
     71 
     72 #include "udf.h"
     73 #include "udf_subr.h"
     74 #include "udf_bswap.h"
     75 
     76 
     77 #define VTOI(vnode) ((struct udf_node *) vnode->v_data)
     78 
     79 
     80 /* predefines */
     81 
     82 
     83 #if 0
     84 {
     85 	int i, j, dlen;
     86 	uint8_t *blob;
     87 
     88 	blob = (uint8_t *) fid;
     89 	dlen = file_size - (*offset);
     90 
     91 	printf("blob = %p\n", blob);
     92 	printf("dump of %d bytes\n", dlen);
     93 
     94 	for (i = 0; i < dlen; i+ = 16) {
     95 		printf("%04x ", i);
     96 		for (j = 0; j < 16; j++) {
     97 			if (i+j < dlen) {
     98 				printf("%02x ", blob[i+j]);
     99 			} else {
    100 				printf("   ");
    101 			}
    102 		}
    103 		for (j = 0; j < 16; j++) {
    104 			if (i+j < dlen) {
    105 				if (blob[i+j]>32 && blob[i+j]! = 127) {
    106 					printf("%c", blob[i+j]);
    107 				} else {
    108 					printf(".");
    109 				}
    110 			}
    111 		}
    112 		printf("\n");
    113 	}
    114 	printf("\n");
    115 }
    116 Debugger();
    117 #endif
    118 
    119 
    120 /* --------------------------------------------------------------------- */
    121 
    122 /* STUB */
    123 
    124 static int
    125 udf_bread(struct udf_mount *ump, uint32_t sector, struct buf **bpp)
    126 {
    127 	int sector_size = ump->discinfo.sector_size;
    128 	int blks = sector_size / DEV_BSIZE;
    129 
    130 	/* NOTE bread() checks if block is in cache or not */
    131 	return bread(ump->devvp, sector*blks, sector_size, NOCRED, bpp);
    132 }
    133 
    134 
    135 /* --------------------------------------------------------------------- */
    136 
    137 /*
    138  * Check if the blob starts with a good UDF tag. Tags are protected by a
    139  * checksum over the reader except one byte at position 4 that is the checksum
    140  * itself.
    141  */
    142 
    143 int
    144 udf_check_tag(void *blob)
    145 {
    146 	struct desc_tag *tag = blob;
    147 	uint8_t *pos, sum, cnt;
    148 
    149 	/* check TAG header checksum */
    150 	pos = (uint8_t *) tag;
    151 	sum = 0;
    152 
    153 	for(cnt = 0; cnt < 16; cnt++) {
    154 		if (cnt != 4)
    155 			sum += *pos;
    156 		pos++;
    157 	}
    158 	if (sum != tag->cksum) {
    159 		/* bad tag header checksum; this is not a valid tag */
    160 		return EINVAL;
    161 	}
    162 
    163 	return 0;
    164 }
    165 
    166 /* --------------------------------------------------------------------- */
    167 
    168 /*
    169  * check tag payload will check descriptor CRC as specified.
    170  * If the descriptor is too short, it will return EIO otherwise EINVAL.
    171  */
    172 
    173 int
    174 udf_check_tag_payload(void *blob, uint32_t max_length)
    175 {
    176 	struct desc_tag *tag = blob;
    177 	uint16_t crc, crc_len;
    178 
    179 	crc_len = udf_rw16(tag->desc_crc_len);
    180 
    181 	/* check payload CRC if applicable */
    182 	if (crc_len == 0)
    183 		return 0;
    184 
    185 	if (crc_len > max_length)
    186 		return EIO;
    187 
    188 	crc = udf_cksum(((uint8_t *) tag) + UDF_DESC_TAG_LENGTH, crc_len);
    189 	if (crc != udf_rw16(tag->desc_crc)) {
    190 		/* bad payload CRC; this is a broken tag */
    191 		return EINVAL;
    192 	}
    193 
    194 	return 0;
    195 }
    196 
    197 /* --------------------------------------------------------------------- */
    198 
    199 int
    200 udf_validate_tag_sum(void *blob)
    201 {
    202 	struct desc_tag *tag = blob;
    203 	uint8_t *pos, sum, cnt;
    204 
    205 	/* calculate TAG header checksum */
    206 	pos = (uint8_t *) tag;
    207 	sum = 0;
    208 
    209 	for(cnt = 0; cnt < 16; cnt++) {
    210 		if (cnt != 4) sum += *pos;
    211 		pos++;
    212 	}
    213 	tag->cksum = sum;	/* 8 bit */
    214 
    215 	return 0;
    216 }
    217 
    218 /* --------------------------------------------------------------------- */
    219 
    220 /* assumes sector number of descriptor to be saved already present */
    221 
    222 int
    223 udf_validate_tag_and_crc_sums(void *blob)
    224 {
    225 	struct desc_tag *tag  = blob;
    226 	uint8_t         *btag = (uint8_t *) tag;
    227 	uint16_t crc, crc_len;
    228 
    229 	crc_len = udf_rw16(tag->desc_crc_len);
    230 
    231 	/* check payload CRC if applicable */
    232 	if (crc_len > 0) {
    233 		crc = udf_cksum(btag + UDF_DESC_TAG_LENGTH, crc_len);
    234 		tag->desc_crc = udf_rw16(crc);
    235 	}
    236 
    237 	/* calculate TAG header checksum */
    238 	return udf_validate_tag_sum(blob);
    239 }
    240 
    241 /* --------------------------------------------------------------------- */
    242 
    243 /*
    244  * XXX note the different semantics from udfclient: for FIDs it still rounds
    245  * up to sectors. Use udf_fidsize() for a correct length.
    246  */
    247 
    248 int
    249 udf_tagsize(union dscrptr *dscr, uint32_t udf_sector_size)
    250 {
    251 	uint32_t size, tag_id, num_secs, elmsz;
    252 
    253 	tag_id = udf_rw16(dscr->tag.id);
    254 
    255 	switch (tag_id) {
    256 	case TAGID_LOGVOL :
    257 		size  = sizeof(struct logvol_desc) - 1;
    258 		size += udf_rw32(dscr->lvd.mt_l);
    259 		break;
    260 	case TAGID_UNALLOC_SPACE :
    261 		elmsz = sizeof(struct extent_ad);
    262 		size  = sizeof(struct unalloc_sp_desc) - elmsz;
    263 		size += udf_rw32(dscr->usd.alloc_desc_num) * elmsz;
    264 		break;
    265 	case TAGID_FID :
    266 		size = UDF_FID_SIZE + dscr->fid.l_fi + udf_rw16(dscr->fid.l_iu);
    267 		size = (size + 3) & ~3;
    268 		break;
    269 	case TAGID_LOGVOL_INTEGRITY :
    270 		size  = sizeof(struct logvol_int_desc) - sizeof(uint32_t);
    271 		size += udf_rw32(dscr->lvid.l_iu);
    272 		size += (2 * udf_rw32(dscr->lvid.num_part) * sizeof(uint32_t));
    273 		break;
    274 	case TAGID_SPACE_BITMAP :
    275 		size  = sizeof(struct space_bitmap_desc) - 1;
    276 		size += udf_rw32(dscr->sbd.num_bytes);
    277 		break;
    278 	case TAGID_SPARING_TABLE :
    279 		elmsz = sizeof(struct spare_map_entry);
    280 		size  = sizeof(struct udf_sparing_table) - elmsz;
    281 		size += udf_rw16(dscr->spt.rt_l) * elmsz;
    282 		break;
    283 	case TAGID_FENTRY :
    284 		size  = sizeof(struct file_entry);
    285 		size += udf_rw32(dscr->fe.l_ea) + udf_rw32(dscr->fe.l_ad)-1;
    286 		break;
    287 	case TAGID_EXTFENTRY :
    288 		size  = sizeof(struct extfile_entry);
    289 		size += udf_rw32(dscr->efe.l_ea) + udf_rw32(dscr->efe.l_ad)-1;
    290 		break;
    291 	case TAGID_FSD :
    292 		size  = sizeof(struct fileset_desc);
    293 		break;
    294 	default :
    295 		size = sizeof(union dscrptr);
    296 		break;
    297 	}
    298 
    299 	if ((size == 0) || (udf_sector_size == 0)) return 0;
    300 
    301 	/* round up in sectors */
    302 	num_secs = (size + udf_sector_size -1) / udf_sector_size;
    303 	return num_secs * udf_sector_size;
    304 }
    305 
    306 
    307 static int
    308 udf_fidsize(struct fileid_desc *fid, uint32_t udf_sector_size)
    309 {
    310 	uint32_t size;
    311 
    312 	if (udf_rw16(fid->tag.id) != TAGID_FID)
    313 		panic("got udf_fidsize on non FID\n");
    314 
    315 	size = UDF_FID_SIZE + fid->l_fi + udf_rw16(fid->l_iu);
    316 	size = (size + 3) & ~3;
    317 
    318 	return size;
    319 }
    320 
    321 /* --------------------------------------------------------------------- */
    322 
    323 /*
    324  * Problem with read_descriptor are long descriptors spanning more than one
    325  * sector. Luckily long descriptors can't be in `logical space'.
    326  *
    327  * Size of allocated piece is returned in multiple of sector size due to
    328  * udf_calc_udf_malloc_size().
    329  */
    330 
    331 int
    332 udf_read_descriptor(struct udf_mount *ump, uint32_t sector,
    333 		    struct malloc_type *mtype, union dscrptr **dstp)
    334 {
    335 	union dscrptr *src, *dst;
    336 	struct buf *bp;
    337 	uint8_t *pos;
    338 	int blks, blk, dscrlen;
    339 	int i, error, sector_size;
    340 
    341 	sector_size = ump->discinfo.sector_size;
    342 
    343 	*dstp = dst = NULL;
    344 	dscrlen = sector_size;
    345 
    346 	/* read initial piece */
    347 	error = udf_bread(ump, sector, &bp);
    348 	DPRINTFIF(DESCRIPTOR, error, ("read error (%d)\n", error));
    349 
    350 	if (!error) {
    351 		/* check if its a valid tag */
    352 		error = udf_check_tag(bp->b_data);
    353 		if (error) {
    354 			/* check if its an empty block */
    355 			pos = bp->b_data;
    356 			for (i = 0; i < sector_size; i++, pos++) {
    357 				if (*pos) break;
    358 			}
    359 			if (i == sector_size) {
    360 				/* return no error but with no dscrptr */
    361 				/* dispose first block */
    362 				brelse(bp);
    363 				return 0;
    364 			}
    365 		}
    366 	}
    367 	DPRINTFIF(DESCRIPTOR, error, ("bad tag checksum\n"));
    368 	if (!error) {
    369 		src = (union dscrptr *) bp->b_data;
    370 		dscrlen = udf_tagsize(src, sector_size);
    371 		dst = malloc(dscrlen, mtype, M_WAITOK);
    372 		memcpy(dst, src, sector_size);
    373 	}
    374 	/* dispose first block */
    375 	bp->b_flags |= B_AGE;
    376 	brelse(bp);
    377 
    378 	if (!error && (dscrlen > sector_size)) {
    379 		DPRINTF(DESCRIPTOR, ("multi block descriptor read\n"));
    380 		/*
    381 		 * Read the rest of descriptor. Since it is only used at mount
    382 		 * time its overdone to define and use a specific udf_breadn
    383 		 * for this alone.
    384 		 */
    385 		blks = (dscrlen + sector_size -1) / sector_size;
    386 		for (blk = 1; blk < blks; blk++) {
    387 			error = udf_bread(ump, sector + blk, &bp);
    388 			if (error) {
    389 				brelse(bp);
    390 				break;
    391 			}
    392 			pos = (uint8_t *) dst + blk*sector_size;
    393 			memcpy(pos, bp->b_data, sector_size);
    394 
    395 			/* dispose block */
    396 			bp->b_flags |= B_AGE;
    397 			brelse(bp);
    398 		}
    399 		DPRINTFIF(DESCRIPTOR, error, ("read error on multi (%d)\n",
    400 		    error));
    401 	}
    402 	if (!error) {
    403 		error = udf_check_tag_payload(dst, dscrlen);
    404 		DPRINTFIF(DESCRIPTOR, error, ("bad payload check sum\n"));
    405 	}
    406 	if (error && dst) {
    407 		free(dst, mtype);
    408 		dst = NULL;
    409 	}
    410 	*dstp = dst;
    411 
    412 	return error;
    413 }
    414 
    415 /* --------------------------------------------------------------------- */
    416 #ifdef DEBUG
    417 static void
    418 udf_dump_discinfo(struct udf_mount *ump)
    419 {
    420 	char   bits[128];
    421 	struct mmc_discinfo *di = &ump->discinfo;
    422 
    423 	if ((udf_verbose & UDF_DEBUG_VOLUMES) == 0)
    424 		return;
    425 
    426 	printf("Device/media info  :\n");
    427 	printf("\tMMC profile        0x%02x\n", di->mmc_profile);
    428 	printf("\tderived class      %d\n", di->mmc_class);
    429 	printf("\tsector size        %d\n", di->sector_size);
    430 	printf("\tdisc state         %d\n", di->disc_state);
    431 	printf("\tlast ses state     %d\n", di->last_session_state);
    432 	printf("\tbg format state    %d\n", di->bg_format_state);
    433 	printf("\tfrst track         %d\n", di->first_track);
    434 	printf("\tfst on last ses    %d\n", di->first_track_last_session);
    435 	printf("\tlst on last ses    %d\n", di->last_track_last_session);
    436 	printf("\tlink block penalty %d\n", di->link_block_penalty);
    437 	bitmask_snprintf(di->disc_flags, MMC_DFLAGS_FLAGBITS, bits,
    438 		sizeof(bits));
    439 	printf("\tdisc flags         %s\n", bits);
    440 	printf("\tdisc id            %x\n", di->disc_id);
    441 	printf("\tdisc barcode       %"PRIx64"\n", di->disc_barcode);
    442 
    443 	printf("\tnum sessions       %d\n", di->num_sessions);
    444 	printf("\tnum tracks         %d\n", di->num_tracks);
    445 
    446 	bitmask_snprintf(di->mmc_cur, MMC_CAP_FLAGBITS, bits, sizeof(bits));
    447 	printf("\tcapabilities cur   %s\n", bits);
    448 	bitmask_snprintf(di->mmc_cap, MMC_CAP_FLAGBITS, bits, sizeof(bits));
    449 	printf("\tcapabilities cap   %s\n", bits);
    450 }
    451 #else
    452 #define udf_dump_discinfo(a);
    453 #endif
    454 
    455 /* not called often */
    456 int
    457 udf_update_discinfo(struct udf_mount *ump)
    458 {
    459 	struct vnode *devvp = ump->devvp;
    460 	struct partinfo dpart;
    461 	struct mmc_discinfo *di;
    462 	int error;
    463 
    464 	DPRINTF(VOLUMES, ("read/update disc info\n"));
    465 	di = &ump->discinfo;
    466 	memset(di, 0, sizeof(struct mmc_discinfo));
    467 
    468 	/* check if we're on a MMC capable device, i.e. CD/DVD */
    469 	error = VOP_IOCTL(devvp, MMCGETDISCINFO, di, FKIOCTL, NOCRED, NULL);
    470 	if (error == 0) {
    471 		udf_dump_discinfo(ump);
    472 		return 0;
    473 	}
    474 
    475 	/* disc partition support */
    476 	error = VOP_IOCTL(devvp, DIOCGPART, &dpart, FREAD, NOCRED, NULL);
    477 	if (error)
    478 		return ENODEV;
    479 
    480 	/* set up a disc info profile for partitions */
    481 	di->mmc_profile		= 0x01;	/* disc type */
    482 	di->mmc_class		= MMC_CLASS_DISC;
    483 	di->disc_state		= MMC_STATE_CLOSED;
    484 	di->last_session_state	= MMC_STATE_CLOSED;
    485 	di->bg_format_state	= MMC_BGFSTATE_COMPLETED;
    486 	di->link_block_penalty	= 0;
    487 
    488 	di->mmc_cur     = MMC_CAP_RECORDABLE | MMC_CAP_REWRITABLE |
    489 		MMC_CAP_ZEROLINKBLK | MMC_CAP_HW_DEFECTFREE;
    490 	di->mmc_cap    = di->mmc_cur;
    491 	di->disc_flags = MMC_DFLAGS_UNRESTRICTED;
    492 
    493 	/* TODO problem with last_possible_lba on resizable VND; request */
    494 	di->last_possible_lba = dpart.part->p_size;
    495 	di->sector_size       = dpart.disklab->d_secsize;
    496 	di->blockingnr        = 1;
    497 
    498 	di->num_sessions = 1;
    499 	di->num_tracks   = 1;
    500 
    501 	di->first_track  = 1;
    502 	di->first_track_last_session = di->last_track_last_session = 1;
    503 
    504 	udf_dump_discinfo(ump);
    505 	return 0;
    506 }
    507 
    508 /* --------------------------------------------------------------------- */
    509 
    510 int
    511 udf_update_trackinfo(struct udf_mount *ump, struct mmc_trackinfo *ti)
    512 {
    513 	struct vnode *devvp = ump->devvp;
    514 	struct mmc_discinfo *di = &ump->discinfo;
    515 	int error, class;
    516 
    517 	DPRINTF(VOLUMES, ("read track info\n"));
    518 
    519 	class = di->mmc_class;
    520 	if (class != MMC_CLASS_DISC) {
    521 		/* tracknr specified in struct ti */
    522 		error = VOP_IOCTL(devvp, MMCGETTRACKINFO, ti, FKIOCTL,
    523 			NOCRED, NULL);
    524 		return error;
    525 	}
    526 
    527 	/* disc partition support */
    528 	if (ti->tracknr != 1)
    529 		return EIO;
    530 
    531 	/* create fake ti (TODO check for resized vnds) */
    532 	ti->sessionnr  = 1;
    533 
    534 	ti->track_mode = 0;	/* XXX */
    535 	ti->data_mode  = 0;	/* XXX */
    536 	ti->flags = MMC_TRACKINFO_LRA_VALID | MMC_TRACKINFO_NWA_VALID;
    537 
    538 	ti->track_start    = 0;
    539 	ti->packet_size    = 1;
    540 
    541 	/* TODO support for resizable vnd */
    542 	ti->track_size    = di->last_possible_lba;
    543 	ti->next_writable = di->last_possible_lba;
    544 	ti->last_recorded = ti->next_writable;
    545 	ti->free_blocks   = 0;
    546 
    547 	return 0;
    548 }
    549 
    550 /* --------------------------------------------------------------------- */
    551 
    552 /* track/session searching for mounting */
    553 
    554 static int
    555 udf_search_tracks(struct udf_mount *ump, struct udf_args *args,
    556 		  int *first_tracknr, int *last_tracknr)
    557 {
    558 	struct mmc_trackinfo trackinfo;
    559 	uint32_t tracknr, start_track, num_tracks;
    560 	int error;
    561 
    562 	/* if negative, sessionnr is relative to last session */
    563 	if (args->sessionnr < 0) {
    564 		args->sessionnr += ump->discinfo.num_sessions;
    565 		/* sanity */
    566 		if (args->sessionnr < 0)
    567 			args->sessionnr = 0;
    568 	}
    569 
    570 	/* sanity */
    571 	if (args->sessionnr > ump->discinfo.num_sessions)
    572 		args->sessionnr = ump->discinfo.num_sessions;
    573 
    574 	/* search the tracks for this session, zero session nr indicates last */
    575 	if (args->sessionnr == 0) {
    576 		args->sessionnr = ump->discinfo.num_sessions;
    577 		if (ump->discinfo.last_session_state == MMC_STATE_EMPTY) {
    578 			args->sessionnr--;
    579 		}
    580 	}
    581 
    582 	/* search the first and last track of the specified session */
    583 	num_tracks  = ump->discinfo.num_tracks;
    584 	start_track = ump->discinfo.first_track;
    585 
    586 	/* search for first track of this session */
    587 	for (tracknr = start_track; tracknr <= num_tracks; tracknr++) {
    588 		/* get track info */
    589 		trackinfo.tracknr = tracknr;
    590 		error = udf_update_trackinfo(ump, &trackinfo);
    591 		if (error)
    592 			return error;
    593 
    594 		if (trackinfo.sessionnr == args->sessionnr)
    595 			break;
    596 	}
    597 	*first_tracknr = tracknr;
    598 
    599 	/* search for last track of this session */
    600 	for (;tracknr <= num_tracks; tracknr++) {
    601 		/* get track info */
    602 		trackinfo.tracknr = tracknr;
    603 		error = udf_update_trackinfo(ump, &trackinfo);
    604 		if (error || (trackinfo.sessionnr != args->sessionnr)) {
    605 			tracknr--;
    606 			break;
    607 		}
    608 	}
    609 	if (tracknr > num_tracks)
    610 		tracknr--;
    611 
    612 	*last_tracknr = tracknr;
    613 
    614 	assert(*last_tracknr >= *first_tracknr);
    615 	return 0;
    616 }
    617 
    618 /* --------------------------------------------------------------------- */
    619 
    620 static int
    621 udf_read_anchor(struct udf_mount *ump, uint32_t sector, struct anchor_vdp **dst)
    622 {
    623 	int error;
    624 
    625 	error = udf_read_descriptor(ump, sector, M_UDFVOLD,
    626 			(union dscrptr **) dst);
    627 	if (!error) {
    628 		/* blank terminator blocks are not allowed here */
    629 		if (*dst == NULL)
    630 			return ENOENT;
    631 		if (udf_rw16((*dst)->tag.id) != TAGID_ANCHOR) {
    632 			error = ENOENT;
    633 			free(*dst, M_UDFVOLD);
    634 			*dst = NULL;
    635 			DPRINTF(VOLUMES, ("Not an anchor\n"));
    636 		}
    637 	}
    638 
    639 	return error;
    640 }
    641 
    642 
    643 int
    644 udf_read_anchors(struct udf_mount *ump, struct udf_args *args)
    645 {
    646 	struct mmc_trackinfo first_track;
    647 	struct mmc_trackinfo last_track;
    648 	struct anchor_vdp **anchorsp;
    649 	uint32_t track_start;
    650 	uint32_t track_end;
    651 	uint32_t positions[4];
    652 	int first_tracknr, last_tracknr;
    653 	int error, anch, ok, first_anchor;
    654 
    655 	/* search the first and last track of the specified session */
    656 	error = udf_search_tracks(ump, args, &first_tracknr, &last_tracknr);
    657 	if (!error) {
    658 		first_track.tracknr = first_tracknr;
    659 		error = udf_update_trackinfo(ump, &first_track);
    660 	}
    661 	if (!error) {
    662 		last_track.tracknr = last_tracknr;
    663 		error = udf_update_trackinfo(ump, &last_track);
    664 	}
    665 	if (error) {
    666 		printf("UDF mount: reading disc geometry failed\n");
    667 		return 0;
    668 	}
    669 
    670 	track_start = first_track.track_start;
    671 
    672 	/* `end' is not as straitforward as start. */
    673 	track_end =   last_track.track_start
    674 		    + last_track.track_size - last_track.free_blocks - 1;
    675 
    676 	if (ump->discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) {
    677 		/* end of track is not straitforward here */
    678 		if (last_track.flags & MMC_TRACKINFO_LRA_VALID)
    679 			track_end = last_track.last_recorded;
    680 		else if (last_track.flags & MMC_TRACKINFO_NWA_VALID)
    681 			track_end = last_track.next_writable
    682 				    - ump->discinfo.link_block_penalty;
    683 	}
    684 
    685 	/* its no use reading a blank track */
    686 	first_anchor = 0;
    687 	if (first_track.flags & MMC_TRACKINFO_BLANK)
    688 		first_anchor = 1;
    689 
    690 	/* read anchors start+256, start+512, end-256, end */
    691 	positions[0] = track_start+256;
    692 	positions[1] =   track_end-256;
    693 	positions[2] =   track_end;
    694 	positions[3] = track_start+512;	/* [UDF 2.60/6.11.2] */
    695 	/* XXX shouldn't +512 be prefered above +256 for compat with Roxio CD */
    696 
    697 	ok = 0;
    698 	anchorsp = ump->anchors;
    699 	for (anch = first_anchor; anch < 4; anch++) {
    700 		DPRINTF(VOLUMES, ("Read anchor %d at sector %d\n", anch,
    701 		    positions[anch]));
    702 		error = udf_read_anchor(ump, positions[anch], anchorsp);
    703 		if (!error) {
    704 			anchorsp++;
    705 			ok++;
    706 		}
    707 	}
    708 
    709 	/* VATs are only recorded on sequential media, but initialise */
    710 	ump->first_possible_vat_location = track_start + 256 + 1;
    711 	ump->last_possible_vat_location  = track_end
    712 		+ ump->discinfo.blockingnr;
    713 
    714 	return ok;
    715 }
    716 
    717 /* --------------------------------------------------------------------- */
    718 
    719 /* we dont try to be smart; we just record the parts */
    720 #define UDF_UPDATE_DSCR(name, dscr) \
    721 	if (name) \
    722 		free(name, M_UDFVOLD); \
    723 	name = dscr;
    724 
    725 static int
    726 udf_process_vds_descriptor(struct udf_mount *ump, union dscrptr *dscr)
    727 {
    728 	uint16_t partnr;
    729 
    730 	DPRINTF(VOLUMES, ("\tprocessing VDS descr %d\n",
    731 	    udf_rw16(dscr->tag.id)));
    732 	switch (udf_rw16(dscr->tag.id)) {
    733 	case TAGID_PRI_VOL :		/* primary partition		*/
    734 		UDF_UPDATE_DSCR(ump->primary_vol, &dscr->pvd);
    735 		break;
    736 	case TAGID_LOGVOL :		/* logical volume		*/
    737 		UDF_UPDATE_DSCR(ump->logical_vol, &dscr->lvd);
    738 		break;
    739 	case TAGID_UNALLOC_SPACE :	/* unallocated space		*/
    740 		UDF_UPDATE_DSCR(ump->unallocated, &dscr->usd);
    741 		break;
    742 	case TAGID_IMP_VOL :		/* implementation		*/
    743 		/* XXX do we care about multiple impl. descr ? */
    744 		UDF_UPDATE_DSCR(ump->implementation, &dscr->ivd);
    745 		break;
    746 	case TAGID_PARTITION :		/* physical partition		*/
    747 		/* not much use if its not allocated */
    748 		if ((udf_rw16(dscr->pd.flags) & UDF_PART_FLAG_ALLOCATED) == 0) {
    749 			free(dscr, M_UDFVOLD);
    750 			break;
    751 		}
    752 
    753 		/* check partnr boundaries */
    754 		partnr = udf_rw16(dscr->pd.part_num);
    755 		if (partnr >= UDF_PARTITIONS) {
    756 			free(dscr, M_UDFVOLD);
    757 			return EINVAL;
    758 		}
    759 
    760 		UDF_UPDATE_DSCR(ump->partitions[partnr], &dscr->pd);
    761 		break;
    762 	case TAGID_VOL :		/* volume space extender; rare	*/
    763 		DPRINTF(VOLUMES, ("VDS extender ignored\n"));
    764 		free(dscr, M_UDFVOLD);
    765 		break;
    766 	default :
    767 		DPRINTF(VOLUMES, ("Unhandled VDS type %d\n",
    768 		    udf_rw16(dscr->tag.id)));
    769 		free(dscr, M_UDFVOLD);
    770 	}
    771 
    772 	return 0;
    773 }
    774 #undef UDF_UPDATE_DSCR
    775 
    776 /* --------------------------------------------------------------------- */
    777 
    778 static int
    779 udf_read_vds_extent(struct udf_mount *ump, uint32_t loc, uint32_t len)
    780 {
    781 	union dscrptr *dscr;
    782 	uint32_t sector_size, dscr_size;
    783 	int error;
    784 
    785 	sector_size = ump->discinfo.sector_size;
    786 
    787 	/* loc is sectornr, len is in bytes */
    788 	error = EIO;
    789 	while (len) {
    790 		error = udf_read_descriptor(ump, loc, M_UDFVOLD, &dscr);
    791 		if (error)
    792 			return error;
    793 
    794 		/* blank block is a terminator */
    795 		if (dscr == NULL)
    796 			return 0;
    797 
    798 		/* TERM descriptor is a terminator */
    799 		if (udf_rw16(dscr->tag.id) == TAGID_TERM) {
    800 			free(dscr, M_UDFVOLD);
    801 			return 0;
    802 		}
    803 
    804 		/* process all others */
    805 		dscr_size = udf_tagsize(dscr, sector_size);
    806 		error = udf_process_vds_descriptor(ump, dscr);
    807 		if (error) {
    808 			free(dscr, M_UDFVOLD);
    809 			break;
    810 		}
    811 		assert((dscr_size % sector_size) == 0);
    812 
    813 		len -= dscr_size;
    814 		loc += dscr_size / sector_size;
    815 	}
    816 
    817 	return error;
    818 }
    819 
    820 
    821 int
    822 udf_read_vds_space(struct udf_mount *ump)
    823 {
    824 	struct anchor_vdp *anchor, *anchor2;
    825 	size_t size;
    826 	uint32_t main_loc, main_len;
    827 	uint32_t reserve_loc, reserve_len;
    828 	int error;
    829 
    830 	/*
    831 	 * read in VDS space provided by the anchors; if one descriptor read
    832 	 * fails, try the mirror sector.
    833 	 *
    834 	 * check if 2nd anchor is different from 1st; if so, go for 2nd. This
    835 	 * avoids the `compatibility features' of DirectCD that may confuse
    836 	 * stuff completely.
    837 	 */
    838 
    839 	anchor  = ump->anchors[0];
    840 	anchor2 = ump->anchors[1];
    841 	assert(anchor);
    842 
    843 	if (anchor2) {
    844 		size = sizeof(struct extent_ad);
    845 		if (memcmp(&anchor->main_vds_ex, &anchor2->main_vds_ex, size))
    846 			anchor = anchor2;
    847 		/* reserve is specified to be a literal copy of main */
    848 	}
    849 
    850 	main_loc    = udf_rw32(anchor->main_vds_ex.loc);
    851 	main_len    = udf_rw32(anchor->main_vds_ex.len);
    852 
    853 	reserve_loc = udf_rw32(anchor->reserve_vds_ex.loc);
    854 	reserve_len = udf_rw32(anchor->reserve_vds_ex.len);
    855 
    856 	error = udf_read_vds_extent(ump, main_loc, main_len);
    857 	if (error) {
    858 		printf("UDF mount: reading in reserve VDS extent\n");
    859 		error = udf_read_vds_extent(ump, reserve_loc, reserve_len);
    860 	}
    861 
    862 	return error;
    863 }
    864 
    865 /* --------------------------------------------------------------------- */
    866 
    867 /*
    868  * Read in the logical volume integrity sequence pointed to by our logical
    869  * volume descriptor. Its a sequence that can be extended using fields in the
    870  * integrity descriptor itself. On sequential media only one is found, on
    871  * rewritable media a sequence of descriptors can be found as a form of
    872  * history keeping and on non sequential write-once media the chain is vital
    873  * to allow more and more descriptors to be written. The last descriptor
    874  * written in an extent needs to claim space for a new extent.
    875  */
    876 
    877 static int
    878 udf_retrieve_lvint(struct udf_mount *ump, struct logvol_int_desc **lvintp)
    879 {
    880 	union dscrptr *dscr;
    881 	struct logvol_int_desc *lvint;
    882 	uint32_t sector_size, sector, len;
    883 	int dscr_type, error;
    884 
    885 	sector_size = ump->discinfo.sector_size;
    886 	len    = udf_rw32(ump->logical_vol->integrity_seq_loc.len);
    887 	sector = udf_rw32(ump->logical_vol->integrity_seq_loc.loc);
    888 
    889 	lvint = NULL;
    890 	dscr  = NULL;
    891 	error = 0;
    892 	while (len) {
    893 		/* read in our integrity descriptor */
    894 		error = udf_read_descriptor(ump, sector, M_UDFVOLD, &dscr);
    895 		if (!error) {
    896 			if (dscr == NULL)
    897 				break;		/* empty terminates */
    898 			dscr_type = udf_rw16(dscr->tag.id);
    899 			if (dscr_type == TAGID_TERM) {
    900 				break;		/* clean terminator */
    901 			}
    902 			if (dscr_type != TAGID_LOGVOL_INTEGRITY) {
    903 				/* fatal... corrupt disc */
    904 				error = ENOENT;
    905 				break;
    906 			}
    907 			if (lvint)
    908 				free(lvint, M_UDFVOLD);
    909 			lvint = &dscr->lvid;
    910 			dscr = NULL;
    911 		} /* else hope for the best... maybe the next is ok */
    912 
    913 		DPRINTFIF(VOLUMES, lvint, ("logvol integrity read, state %s\n",
    914 		    udf_rw32(lvint->integrity_type) ? "CLOSED" : "OPEN"));
    915 
    916 		/* proceed sequential */
    917 		sector += 1;
    918 		len    -= sector_size;
    919 
    920 		/* are we linking to a new piece? */
    921 		if (lvint->next_extent.len) {
    922 			len    = udf_rw32(lvint->next_extent.len);
    923 			sector = udf_rw32(lvint->next_extent.loc);
    924 		}
    925 	}
    926 
    927 	/* clean up the mess, esp. when there is an error */
    928 	if (dscr)
    929 		free(dscr, M_UDFVOLD);
    930 
    931 	if (error && lvint) {
    932 		free(lvint, M_UDFVOLD);
    933 		lvint = NULL;
    934 	}
    935 
    936 	if (!lvint)
    937 		error = ENOENT;
    938 
    939 	*lvintp = lvint;
    940 	return error;
    941 }
    942 
    943 /* --------------------------------------------------------------------- */
    944 
    945 /*
    946  * Checks if ump's vds information is correct and complete
    947  */
    948 
    949 int
    950 udf_process_vds(struct udf_mount *ump, struct udf_args *args)
    951 {
    952 	union udf_pmap *mapping;
    953 	struct logvol_int_desc *lvint;
    954 	struct udf_logvol_info *lvinfo;
    955 	uint32_t n_pm, mt_l;
    956 	uint8_t *pmap_pos;
    957 	char *domain_name, *map_name;
    958 	const char *check_name;
    959 	int pmap_stype, pmap_size;
    960 	int pmap_type, log_part, phys_part;
    961 	int n_phys, n_virt, n_spar, n_meta;
    962 	int len, error;
    963 
    964 	if (ump == NULL)
    965 		return ENOENT;
    966 
    967 	/* we need at least an anchor (trivial, but for safety) */
    968 	if (ump->anchors[0] == NULL)
    969 		return EINVAL;
    970 
    971 	/* we need at least one primary and one logical volume descriptor */
    972 	if ((ump->primary_vol == NULL) || (ump->logical_vol) == NULL)
    973 		return EINVAL;
    974 
    975 	/* we need at least one partition descriptor */
    976 	if (ump->partitions[0] == NULL)
    977 		return EINVAL;
    978 
    979 	/* check logical volume sector size verses device sector size */
    980 	if (udf_rw32(ump->logical_vol->lb_size) != ump->discinfo.sector_size) {
    981 		printf("UDF mount: format violation, lb_size != sector size\n");
    982 		return EINVAL;
    983 	}
    984 
    985 	domain_name = ump->logical_vol->domain_id.id;
    986 	if (strncmp(domain_name, "*OSTA UDF Compliant", 20)) {
    987 		printf("mount_udf: disc not OSTA UDF Compliant, aborting\n");
    988 		return EINVAL;
    989 	}
    990 
    991 	/* retrieve logical volume integrity sequence */
    992 	error = udf_retrieve_lvint(ump, &ump->logvol_integrity);
    993 
    994 	/*
    995 	 * We need at least one logvol integrity descriptor recorded.  Note
    996 	 * that its OK to have an open logical volume integrity here. The VAT
    997 	 * will close/update the integrity.
    998 	 */
    999 	if (ump->logvol_integrity == NULL)
   1000 		return EINVAL;
   1001 
   1002 	/* process derived structures */
   1003 	n_pm   = udf_rw32(ump->logical_vol->n_pm);   /* num partmaps         */
   1004 	lvint  = ump->logvol_integrity;
   1005 	lvinfo = (struct udf_logvol_info *) (&lvint->tables[2 * n_pm]);
   1006 	ump->logvol_info = lvinfo;
   1007 
   1008 	/* TODO check udf versions? */
   1009 
   1010 	/*
   1011 	 * check logvol mappings: effective virt->log partmap translation
   1012 	 * check and recording of the mapping results. Saves expensive
   1013 	 * strncmp() in tight places.
   1014 	 */
   1015 	DPRINTF(VOLUMES, ("checking logvol mappings\n"));
   1016 	n_pm = udf_rw32(ump->logical_vol->n_pm);   /* num partmaps         */
   1017 	mt_l = udf_rw32(ump->logical_vol->mt_l);   /* partmaps data length */
   1018 	pmap_pos =  ump->logical_vol->maps;
   1019 
   1020 	if (n_pm > UDF_PMAPS) {
   1021 		printf("UDF mount: too many mappings\n");
   1022 		return EINVAL;
   1023 	}
   1024 
   1025 	n_phys = n_virt = n_spar = n_meta = 0;
   1026 	for (log_part = 0; log_part < n_pm; log_part++) {
   1027 		mapping = (union udf_pmap *) pmap_pos;
   1028 		pmap_stype = pmap_pos[0];
   1029 		pmap_size  = pmap_pos[1];
   1030 		switch (pmap_stype) {
   1031 		case 1:	/* physical mapping */
   1032 			/* volseq    = udf_rw16(mapping->pm1.vol_seq_num); */
   1033 			phys_part = udf_rw16(mapping->pm1.part_num);
   1034 			pmap_type = UDF_VTOP_TYPE_PHYS;
   1035 			n_phys++;
   1036 			break;
   1037 		case 2: /* virtual/sparable/meta mapping */
   1038 			map_name  = mapping->pm2.part_id.id;
   1039 			/* volseq  = udf_rw16(mapping->pm2.vol_seq_num); */
   1040 			phys_part = udf_rw16(mapping->pm2.part_num);
   1041 			pmap_type = UDF_VTOP_TYPE_UNKNOWN;
   1042 			len = UDF_REGID_ID_SIZE;
   1043 
   1044 			check_name = "*UDF Virtual Partition";
   1045 			if (strncmp(map_name, check_name, len) == 0) {
   1046 				pmap_type = UDF_VTOP_TYPE_VIRT;
   1047 				n_virt++;
   1048 				break;
   1049 			}
   1050 			check_name = "*UDF Sparable Partition";
   1051 			if (strncmp(map_name, check_name, len) == 0) {
   1052 				pmap_type = UDF_VTOP_TYPE_SPARABLE;
   1053 				n_spar++;
   1054 				break;
   1055 			}
   1056 			check_name = "*UDF Metadata Partition";
   1057 			if (strncmp(map_name, check_name, len) == 0) {
   1058 				pmap_type = UDF_VTOP_TYPE_META;
   1059 				n_meta++;
   1060 				break;
   1061 			}
   1062 			break;
   1063 		default:
   1064 			return EINVAL;
   1065 		}
   1066 
   1067 		DPRINTF(VOLUMES, ("\t%d -> %d type %d\n", log_part, phys_part,
   1068 		    pmap_type));
   1069 		if (pmap_type == UDF_VTOP_TYPE_UNKNOWN)
   1070 			return EINVAL;
   1071 
   1072 		ump->vtop   [log_part] = phys_part;
   1073 		ump->vtop_tp[log_part] = pmap_type;
   1074 
   1075 		pmap_pos += pmap_size;
   1076 	}
   1077 	/* not winning the beauty contest */
   1078 	ump->vtop_tp[UDF_VTOP_RAWPART] = UDF_VTOP_TYPE_RAW;
   1079 
   1080 	/* test some basic UDF assertions/requirements */
   1081 	if ((n_virt > 1) || (n_spar > 1) || (n_meta > 1))
   1082 		return EINVAL;
   1083 
   1084 	if (n_virt) {
   1085 		if ((n_phys == 0) || n_spar || n_meta)
   1086 			return EINVAL;
   1087 	}
   1088 	if (n_spar + n_phys == 0)
   1089 		return EINVAL;
   1090 
   1091 	/* vat's can only be on a sequential media */
   1092 	ump->data_alloc = UDF_ALLOC_SPACEMAP;
   1093 	if (n_virt)
   1094 		ump->data_alloc = UDF_ALLOC_SEQUENTIAL;
   1095 
   1096 	ump->meta_alloc = UDF_ALLOC_SPACEMAP;
   1097 	if (n_virt)
   1098 		ump->meta_alloc = UDF_ALLOC_VAT;
   1099 	if (n_meta)
   1100 		ump->meta_alloc = UDF_ALLOC_METABITMAP;
   1101 
   1102 	/* special cases for pseudo-overwrite */
   1103 	if (ump->discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE) {
   1104 		ump->data_alloc = UDF_ALLOC_SEQUENTIAL;
   1105 		if (n_meta) {
   1106 			ump->meta_alloc = UDF_ALLOC_METASEQUENTIAL;
   1107 		} else {
   1108 			ump->meta_alloc = UDF_ALLOC_RELAXEDSEQUENTIAL;
   1109 		}
   1110 	}
   1111 
   1112 	DPRINTF(VOLUMES, ("\tdata alloc scheme %d, meta alloc scheme %d\n",
   1113 	    ump->data_alloc, ump->meta_alloc));
   1114 	/* TODO determine partitions to write data and metadata ? */
   1115 
   1116 	/* signal its OK for now */
   1117 	return 0;
   1118 }
   1119 
   1120 /* --------------------------------------------------------------------- */
   1121 
   1122 /*
   1123  * Read in complete VAT file and check if its indeed a VAT file descriptor
   1124  */
   1125 
   1126 static int
   1127 udf_check_for_vat(struct udf_node *vat_node)
   1128 {
   1129 	struct udf_mount *ump;
   1130 	struct icb_tag   *icbtag;
   1131 	struct timestamp *mtime;
   1132 	struct regid     *regid;
   1133 	struct udf_vat   *vat;
   1134 	struct udf_logvol_info *lvinfo;
   1135 	uint32_t  vat_length, alloc_length;
   1136 	uint32_t  vat_offset, vat_entries;
   1137 	uint32_t  sector_size;
   1138 	uint32_t  sectors;
   1139 	uint32_t *raw_vat;
   1140 	char     *regid_name;
   1141 	int filetype;
   1142 	int error;
   1143 
   1144 	/* vat_length is really 64 bits though impossible */
   1145 
   1146 	DPRINTF(VOLUMES, ("Checking for VAT\n"));
   1147 	if (!vat_node)
   1148 		return ENOENT;
   1149 
   1150 	/* get mount info */
   1151 	ump = vat_node->ump;
   1152 
   1153 	/* check assertions */
   1154 	assert(vat_node->fe || vat_node->efe);
   1155 	assert(ump->logvol_integrity);
   1156 
   1157 	/* get information from fe/efe */
   1158 	if (vat_node->fe) {
   1159 		vat_length = udf_rw64(vat_node->fe->inf_len);
   1160 		icbtag = &vat_node->fe->icbtag;
   1161 		mtime  = &vat_node->fe->mtime;
   1162 	} else {
   1163 		vat_length = udf_rw64(vat_node->efe->inf_len);
   1164 		icbtag = &vat_node->efe->icbtag;
   1165 		mtime  = &vat_node->efe->mtime;
   1166 	}
   1167 
   1168 	/* Check icb filetype! it has to be 0 or UDF_ICB_FILETYPE_VAT */
   1169 	filetype = icbtag->file_type;
   1170 	if ((filetype != 0) && (filetype != UDF_ICB_FILETYPE_VAT))
   1171 		return ENOENT;
   1172 
   1173 	DPRINTF(VOLUMES, ("\tPossible VAT length %d\n", vat_length));
   1174 	/* place a sanity check on the length; currently 1Mb in size */
   1175 	if (vat_length > 1*1024*1024)
   1176 		return ENOENT;
   1177 
   1178 	/* get sector size */
   1179 	sector_size = vat_node->ump->discinfo.sector_size;
   1180 
   1181 	/* calculate how many sectors to read in and how much to allocate */
   1182 	sectors = (vat_length + sector_size -1) / sector_size;
   1183 	alloc_length = (sectors + 2) * sector_size;
   1184 
   1185 	/* try to allocate the space */
   1186 	ump->vat_table_alloc_length = alloc_length;
   1187 	ump->vat_table = malloc(alloc_length, M_UDFVOLD, M_CANFAIL | M_WAITOK);
   1188 	if (!ump->vat_table)
   1189 		return ENOMEM;		/* impossible to allocate */
   1190 	DPRINTF(VOLUMES, ("\talloced fine\n"));
   1191 
   1192 	/* read it in! */
   1193 	raw_vat = (uint32_t *) ump->vat_table;
   1194 	error = udf_read_file_extent(vat_node, 0, sectors, (uint8_t *) raw_vat);
   1195 	if (error) {
   1196 		DPRINTF(VOLUMES, ("\tread failed : %d\n", error));
   1197 		/* not completely readable... :( bomb out */
   1198 		free(ump->vat_table, M_UDFVOLD);
   1199 		ump->vat_table = NULL;
   1200 		return error;
   1201 	}
   1202 	DPRINTF(VOLUMES, ("VAT read in fine!\n"));
   1203 
   1204 	/*
   1205 	 * check contents of the file if its the old 1.50 VAT table format.
   1206 	 * Its notoriously broken and allthough some implementations support an
   1207 	 * extention as defined in the UDF 1.50 errata document, its doubtfull
   1208 	 * to be useable since a lot of implementations don't maintain it.
   1209 	 */
   1210 	lvinfo = ump->logvol_info;
   1211 
   1212 	if (filetype == 0) {
   1213 		/* definition */
   1214 		vat_offset  = 0;
   1215 		vat_entries = (vat_length-36)/4;
   1216 
   1217 		/* check 1.50 VAT */
   1218 		regid = (struct regid *) (raw_vat + vat_entries);
   1219 		regid_name = (char *) regid->id;
   1220 		error = strncmp(regid_name, "*UDF Virtual Alloc Tbl", 22);
   1221 		if (error) {
   1222 			DPRINTF(VOLUMES, ("VAT format 1.50 rejected\n"));
   1223 			free(ump->vat_table, M_UDFVOLD);
   1224 			ump->vat_table = NULL;
   1225 			return ENOENT;
   1226 		}
   1227 		/* TODO update LVID from "*UDF VAT LVExtension" ext. attr. */
   1228 	} else {
   1229 		vat = (struct udf_vat *) raw_vat;
   1230 
   1231 		/* definition */
   1232 		vat_offset  = vat->header_len;
   1233 		vat_entries = (vat_length - vat_offset)/4;
   1234 
   1235 		assert(lvinfo);
   1236 		lvinfo->num_files        = vat->num_files;
   1237 		lvinfo->num_directories  = vat->num_directories;
   1238 		lvinfo->min_udf_readver  = vat->min_udf_readver;
   1239 		lvinfo->min_udf_writever = vat->min_udf_writever;
   1240 		lvinfo->max_udf_writever = vat->max_udf_writever;
   1241 	}
   1242 
   1243 	ump->vat_offset  = vat_offset;
   1244 	ump->vat_entries = vat_entries;
   1245 
   1246 	DPRINTF(VOLUMES, ("VAT format accepted, marking it closed\n"));
   1247 	ump->logvol_integrity->integrity_type = udf_rw32(UDF_INTEGRITY_CLOSED);
   1248 	ump->logvol_integrity->time           = *mtime;
   1249 
   1250 	return 0;	/* success! */
   1251 }
   1252 
   1253 /* --------------------------------------------------------------------- */
   1254 
   1255 static int
   1256 udf_search_vat(struct udf_mount *ump, union udf_pmap *mapping)
   1257 {
   1258 	struct udf_node *vat_node;
   1259 	struct long_ad	 icb_loc;
   1260 	uint32_t early_vat_loc, late_vat_loc, vat_loc;
   1261 	int error;
   1262 
   1263 	/* mapping info not needed */
   1264 	mapping = mapping;
   1265 
   1266 	vat_loc = ump->last_possible_vat_location;
   1267 	early_vat_loc = vat_loc - 2 * ump->discinfo.blockingnr;
   1268 	early_vat_loc = MAX(early_vat_loc, ump->first_possible_vat_location);
   1269 	late_vat_loc  = vat_loc + 1024;
   1270 
   1271 	/* TODO first search last sector? */
   1272 	do {
   1273 		DPRINTF(VOLUMES, ("Checking for VAT at sector %d\n", vat_loc));
   1274 		icb_loc.loc.part_num = udf_rw16(UDF_VTOP_RAWPART);
   1275 		icb_loc.loc.lb_num   = udf_rw32(vat_loc);
   1276 
   1277 		error = udf_get_node(ump, &icb_loc, &vat_node);
   1278 		if (!error) error = udf_check_for_vat(vat_node);
   1279 		if (!error) break;
   1280 		if (vat_node) {
   1281 			vput(vat_node->vnode);
   1282 			udf_dispose_node(vat_node);
   1283 		}
   1284 		vat_loc--;	/* walk backwards */
   1285 	} while (vat_loc >= early_vat_loc);
   1286 
   1287 	/* we don't need our VAT node anymore */
   1288 	if (vat_node) {
   1289 		vput(vat_node->vnode);
   1290 		udf_dispose_node(vat_node);
   1291 	}
   1292 
   1293 	return error;
   1294 }
   1295 
   1296 /* --------------------------------------------------------------------- */
   1297 
   1298 static int
   1299 udf_read_sparables(struct udf_mount *ump, union udf_pmap *mapping)
   1300 {
   1301 	union dscrptr *dscr;
   1302 	struct part_map_spare *pms = &mapping->pms;
   1303 	uint32_t lb_num;
   1304 	int spar, error;
   1305 
   1306 	/*
   1307 	 * The partition mapping passed on to us specifies the information we
   1308 	 * need to locate and initialise the sparable partition mapping
   1309 	 * information we need.
   1310 	 */
   1311 
   1312 	DPRINTF(VOLUMES, ("Read sparable table\n"));
   1313 	ump->sparable_packet_len = udf_rw16(pms->packet_len);
   1314 	for (spar = 0; spar < pms->n_st; spar++) {
   1315 		lb_num = pms->st_loc[spar];
   1316 		DPRINTF(VOLUMES, ("Checking for sparing table %d\n", lb_num));
   1317 		error = udf_read_descriptor(ump, lb_num, M_UDFVOLD, &dscr);
   1318 		if (!error && dscr) {
   1319 			if (udf_rw16(dscr->tag.id) == TAGID_SPARING_TABLE) {
   1320 				if (ump->sparing_table)
   1321 					free(ump->sparing_table, M_UDFVOLD);
   1322 				ump->sparing_table = &dscr->spt;
   1323 				dscr = NULL;
   1324 				DPRINTF(VOLUMES,
   1325 				    ("Sparing table accepted (%d entries)\n",
   1326 				     udf_rw16(ump->sparing_table->rt_l)));
   1327 				break;	/* we're done */
   1328 			}
   1329 		}
   1330 		if (dscr)
   1331 			free(dscr, M_UDFVOLD);
   1332 	}
   1333 
   1334 	if (ump->sparing_table)
   1335 		return 0;
   1336 
   1337 	return ENOENT;
   1338 }
   1339 
   1340 /* --------------------------------------------------------------------- */
   1341 
   1342 #define UDF_SET_SYSTEMFILE(vp) \
   1343 	simple_lock(&(vp)->v_interlock);	\
   1344 	(vp)->v_flag |= VSYSTEM;		\
   1345 	simple_unlock(&(vp)->v_interlock);\
   1346 	vref(vp);			\
   1347 	vput(vp);			\
   1348 
   1349 static int
   1350 udf_read_metadata_files(struct udf_mount *ump, union udf_pmap *mapping)
   1351 {
   1352 	struct part_map_meta *pmm = &mapping->pmm;
   1353 	struct long_ad	 icb_loc;
   1354 	struct vnode *vp;
   1355 	int error;
   1356 
   1357 	DPRINTF(VOLUMES, ("Reading in Metadata files\n"));
   1358 	icb_loc.loc.part_num = pmm->part_num;
   1359 	icb_loc.loc.lb_num   = pmm->meta_file_lbn;
   1360 	DPRINTF(VOLUMES, ("Metadata file\n"));
   1361 	error = udf_get_node(ump, &icb_loc, &ump->metadata_file);
   1362 	if (ump->metadata_file) {
   1363 		vp = ump->metadata_file->vnode;
   1364 		UDF_SET_SYSTEMFILE(vp);
   1365 	}
   1366 
   1367 	icb_loc.loc.lb_num   = pmm->meta_mirror_file_lbn;
   1368 	if (icb_loc.loc.lb_num != -1) {
   1369 		DPRINTF(VOLUMES, ("Metadata copy file\n"));
   1370 		error = udf_get_node(ump, &icb_loc, &ump->metadatamirror_file);
   1371 		if (ump->metadatamirror_file) {
   1372 			vp = ump->metadatamirror_file->vnode;
   1373 			UDF_SET_SYSTEMFILE(vp);
   1374 		}
   1375 	}
   1376 
   1377 	icb_loc.loc.lb_num   = pmm->meta_bitmap_file_lbn;
   1378 	if (icb_loc.loc.lb_num != -1) {
   1379 		DPRINTF(VOLUMES, ("Metadata bitmap file\n"));
   1380 		error = udf_get_node(ump, &icb_loc, &ump->metadatabitmap_file);
   1381 		if (ump->metadatabitmap_file) {
   1382 			vp = ump->metadatabitmap_file->vnode;
   1383 			UDF_SET_SYSTEMFILE(vp);
   1384 		}
   1385 	}
   1386 
   1387 	/* if we're mounting read-only we relax the requirements */
   1388 	if (ump->vfs_mountp->mnt_flag & MNT_RDONLY) {
   1389 		error = EFAULT;
   1390 		if (ump->metadata_file)
   1391 			error = 0;
   1392 		if ((ump->metadata_file == NULL) && (ump->metadatamirror_file)) {
   1393 			printf( "udf mount: Metadata file not readable, "
   1394 				"substituting Metadata copy file\n");
   1395 			ump->metadata_file = ump->metadatamirror_file;
   1396 			ump->metadatamirror_file = NULL;
   1397 			error = 0;
   1398 		}
   1399 	} else {
   1400 		/* mounting read/write */
   1401 		DPRINTF(VOLUMES, ("udf mount: read only file system\n"));
   1402 		error = EROFS;
   1403 	}
   1404 	DPRINTFIF(VOLUMES, error, ("udf mount: failed to read "
   1405 				   "metadata files\n"));
   1406 	return error;
   1407 }
   1408 #undef UDF_SET_SYSTEMFILE
   1409 
   1410 /* --------------------------------------------------------------------- */
   1411 
   1412 int
   1413 udf_read_vds_tables(struct udf_mount *ump, struct udf_args *args)
   1414 {
   1415 	union udf_pmap *mapping;
   1416 	uint32_t n_pm, mt_l;
   1417 	uint32_t log_part;
   1418 	uint8_t *pmap_pos;
   1419 	int pmap_size;
   1420 	int error;
   1421 
   1422 	/* We have to iterate again over the part mappings for locations   */
   1423 	n_pm = udf_rw32(ump->logical_vol->n_pm);   /* num partmaps         */
   1424 	mt_l = udf_rw32(ump->logical_vol->mt_l);   /* partmaps data length */
   1425 	pmap_pos =  ump->logical_vol->maps;
   1426 
   1427 	for (log_part = 0; log_part < n_pm; log_part++) {
   1428 		mapping = (union udf_pmap *) pmap_pos;
   1429 		switch (ump->vtop_tp[log_part]) {
   1430 		case UDF_VTOP_TYPE_PHYS :
   1431 			/* nothing */
   1432 			break;
   1433 		case UDF_VTOP_TYPE_VIRT :
   1434 			/* search and load VAT */
   1435 			error = udf_search_vat(ump, mapping);
   1436 			if (error)
   1437 				return ENOENT;
   1438 			break;
   1439 		case UDF_VTOP_TYPE_SPARABLE :
   1440 			/* load one of the sparable tables */
   1441 			error = udf_read_sparables(ump, mapping);
   1442 			if (error)
   1443 				return ENOENT;
   1444 			break;
   1445 		case UDF_VTOP_TYPE_META :
   1446 			/* load the associated file descriptors */
   1447 			error = udf_read_metadata_files(ump, mapping);
   1448 			if (error)
   1449 				return ENOENT;
   1450 			break;
   1451 		default:
   1452 			break;
   1453 		}
   1454 		pmap_size  = pmap_pos[1];
   1455 		pmap_pos  += pmap_size;
   1456 	}
   1457 
   1458 	return 0;
   1459 }
   1460 
   1461 /* --------------------------------------------------------------------- */
   1462 
   1463 int
   1464 udf_read_rootdirs(struct udf_mount *ump, struct udf_args *args)
   1465 {
   1466 	struct udf_node *rootdir_node, *streamdir_node;
   1467 	union dscrptr *dscr;
   1468 	struct long_ad  fsd_loc, *dir_loc;
   1469 	uint32_t lb_num, dummy;
   1470 	uint32_t fsd_len;
   1471 	int dscr_type;
   1472 	int error;
   1473 
   1474 	/* TODO implement FSD reading in separate function like integrity? */
   1475 	/* get fileset descriptor sequence */
   1476 	fsd_loc = ump->logical_vol->lv_fsd_loc;
   1477 	fsd_len = udf_rw32(fsd_loc.len);
   1478 
   1479 	dscr  = NULL;
   1480 	error = 0;
   1481 	while (fsd_len || error) {
   1482 		DPRINTF(VOLUMES, ("fsd_len = %d\n", fsd_len));
   1483 		/* translate fsd_loc to lb_num */
   1484 		error = udf_translate_vtop(ump, &fsd_loc, &lb_num, &dummy);
   1485 		if (error)
   1486 			break;
   1487 		DPRINTF(VOLUMES, ("Reading FSD at lb %d\n", lb_num));
   1488 		error = udf_read_descriptor(ump, lb_num, M_UDFVOLD, &dscr);
   1489 		/* end markers */
   1490 		if (error || (dscr == NULL))
   1491 			break;
   1492 
   1493 		/* analyse */
   1494 		dscr_type = udf_rw16(dscr->tag.id);
   1495 		if (dscr_type == TAGID_TERM)
   1496 			break;
   1497 		if (dscr_type != TAGID_FSD) {
   1498 			free(dscr, M_UDFVOLD);
   1499 			return ENOENT;
   1500 		}
   1501 
   1502 		/*
   1503 		 * TODO check for multiple fileset descriptors; its only
   1504 		 * picking the last now. Also check for FSD
   1505 		 * correctness/interpretability
   1506 		 */
   1507 
   1508 		/* update */
   1509 		if (ump->fileset_desc) {
   1510 			free(ump->fileset_desc, M_UDFVOLD);
   1511 		}
   1512 		ump->fileset_desc = &dscr->fsd;
   1513 		dscr = NULL;
   1514 
   1515 		/* continue to the next fsd */
   1516 		fsd_len -= ump->discinfo.sector_size;
   1517 		fsd_loc.loc.lb_num = udf_rw32(udf_rw32(fsd_loc.loc.lb_num)+1);
   1518 
   1519 		/* follow up to fsd->next_ex (long_ad) if its not null */
   1520 		if (udf_rw32(ump->fileset_desc->next_ex.len)) {
   1521 			DPRINTF(VOLUMES, ("follow up FSD extent\n"));
   1522 			fsd_loc = ump->fileset_desc->next_ex;
   1523 			fsd_len = udf_rw32(ump->fileset_desc->next_ex.len);
   1524 		}
   1525 	}
   1526 	if (dscr)
   1527 		free(dscr, M_UDFVOLD);
   1528 
   1529 	/* there has to be one */
   1530 	if (ump->fileset_desc == NULL)
   1531 		return ENOENT;
   1532 
   1533 	DPRINTF(VOLUMES, ("FSD read in fine\n"));
   1534 
   1535 	/*
   1536 	 * Now the FSD is known, read in the rootdirectory and if one exists,
   1537 	 * the system stream dir. Some files in the system streamdir are not
   1538 	 * wanted in this implementation since they are not maintained. If
   1539 	 * writing is enabled we'll delete these files if they exist.
   1540 	 */
   1541 
   1542 	rootdir_node = streamdir_node = NULL;
   1543 	dir_loc = NULL;
   1544 
   1545 	/* try to read in the rootdir */
   1546 	dir_loc = &ump->fileset_desc->rootdir_icb;
   1547 	error = udf_get_node(ump, dir_loc, &rootdir_node);
   1548 	if (error)
   1549 		return ENOENT;
   1550 
   1551 	/* aparently it read in fine */
   1552 
   1553 	/*
   1554 	 * Try the system stream directory; not very likely in the ones we
   1555 	 * test, but for completeness.
   1556 	 */
   1557 	dir_loc = &ump->fileset_desc->streamdir_icb;
   1558 	if (udf_rw32(dir_loc->len)) {
   1559 		error = udf_get_node(ump, dir_loc, &streamdir_node);
   1560 		if (error)
   1561 			printf("udf mount: streamdir defined but ignored\n");
   1562 		if (!error) {
   1563 			/*
   1564 			 * TODO process streamdir `baddies' i.e. files we dont
   1565 			 * want if R/W
   1566 			 */
   1567 		}
   1568 	}
   1569 
   1570 	DPRINTF(VOLUMES, ("Rootdir(s) read in fine\n"));
   1571 
   1572 	/* release the vnodes again; they'll be auto-recycled later */
   1573 	if (streamdir_node) {
   1574 		vput(streamdir_node->vnode);
   1575 	}
   1576 	if (rootdir_node) {
   1577 		vput(rootdir_node->vnode);
   1578 	}
   1579 
   1580 	return 0;
   1581 }
   1582 
   1583 /* --------------------------------------------------------------------- */
   1584 
   1585 int
   1586 udf_translate_vtop(struct udf_mount *ump, struct long_ad *icb_loc,
   1587 		   uint32_t *lb_numres, uint32_t *extres)
   1588 {
   1589 	struct part_desc       *pdesc;
   1590 	struct spare_map_entry *sme;
   1591 	struct file_entry      *fe;
   1592 	struct extfile_entry   *efe;
   1593 	struct short_ad        *s_ad;
   1594 	struct long_ad         *l_ad;
   1595 	uint64_t  cur_offset;
   1596 	uint32_t *trans;
   1597 	uint32_t  lb_num, plb_num, lb_rel, lb_packet;
   1598 	uint32_t  sector_size, len, alloclen;
   1599 	uint8_t *pos;
   1600 	int rel, vpart, part, addr_type, icblen, icbflags, flags;
   1601 
   1602 	assert(ump && icb_loc && lb_numres);
   1603 
   1604 	vpart  = udf_rw16(icb_loc->loc.part_num);
   1605 	lb_num = udf_rw32(icb_loc->loc.lb_num);
   1606 	if (vpart < 0 || vpart > UDF_VTOP_RAWPART)
   1607 		return EINVAL;
   1608 
   1609 	part = ump->vtop[vpart];
   1610 	pdesc = ump->partitions[part];
   1611 
   1612 	switch (ump->vtop_tp[vpart]) {
   1613 	case UDF_VTOP_TYPE_RAW :
   1614 		/* 1:1 to the end of the device */
   1615 		*lb_numres = lb_num;
   1616 		*extres = INT_MAX;
   1617 		return 0;
   1618 	case UDF_VTOP_TYPE_PHYS :
   1619 		/* transform into its disc logical block */
   1620 		if (lb_num > udf_rw32(pdesc->part_len))
   1621 			return EINVAL;
   1622 		*lb_numres = lb_num + udf_rw32(pdesc->start_loc);
   1623 
   1624 		/* extent from here to the end of the partition */
   1625 		*extres = udf_rw32(pdesc->part_len) - lb_num;
   1626 		return 0;
   1627 	case UDF_VTOP_TYPE_VIRT :
   1628 		/* only maps one sector, lookup in VAT */
   1629 		if (lb_num >= ump->vat_entries)		/* XXX > or >= ? */
   1630 			return EINVAL;
   1631 
   1632 		/* lookup in virtual allocation table */
   1633 		trans  = (uint32_t *) (ump->vat_table + ump->vat_offset);
   1634 		lb_num = udf_rw32(trans[lb_num]);
   1635 
   1636 		/* transform into its disc logical block */
   1637 		if (lb_num > udf_rw32(pdesc->part_len))
   1638 			return EINVAL;
   1639 		*lb_numres = lb_num + udf_rw32(pdesc->start_loc);
   1640 
   1641 		/* just one logical block */
   1642 		*extres = 1;
   1643 		return 0;
   1644 	case UDF_VTOP_TYPE_SPARABLE :
   1645 		/* check if the packet containing the lb_num is remapped */
   1646 		lb_packet = lb_num / ump->sparable_packet_len;
   1647 		lb_rel    = lb_num % ump->sparable_packet_len;
   1648 
   1649 		for (rel = 0; rel < udf_rw16(ump->sparing_table->rt_l); rel++) {
   1650 			sme = &ump->sparing_table->entries[rel];
   1651 			if (lb_packet == udf_rw32(sme->org)) {
   1652 				/* NOTE maps to absolute disc logical block! */
   1653 				*lb_numres = udf_rw32(sme->map) + lb_rel;
   1654 				*extres    = ump->sparable_packet_len - lb_rel;
   1655 				return 0;
   1656 			}
   1657 		}
   1658 
   1659 		/* transform into its disc logical block */
   1660 		if (lb_num > udf_rw32(pdesc->part_len))
   1661 			return EINVAL;
   1662 		*lb_numres = lb_num + udf_rw32(pdesc->start_loc);
   1663 
   1664 		/* rest of block */
   1665 		*extres = ump->sparable_packet_len - lb_rel;
   1666 		return 0;
   1667 	case UDF_VTOP_TYPE_META :
   1668 		/* we have to look into the file's allocation descriptors */
   1669 		/* free after udf_translate_file_extent() */
   1670 		/* XXX sector size or lb_size? */
   1671 		sector_size = ump->discinfo.sector_size;
   1672 		/* XXX should we claim exclusive access to the metafile ? */
   1673 		fe  = ump->metadata_file->fe;
   1674 		efe = ump->metadata_file->efe;
   1675 		if (fe) {
   1676 			alloclen = udf_rw32(fe->l_ad);
   1677 			pos      = &fe->data[0] + udf_rw32(fe->l_ea);
   1678 			icbflags = udf_rw16(fe->icbtag.flags);
   1679 		} else {
   1680 			assert(efe);
   1681 			alloclen = udf_rw32(efe->l_ad);
   1682 			pos      = &efe->data[0] + udf_rw32(efe->l_ea);
   1683 			icbflags = udf_rw16(efe->icbtag.flags);
   1684 		}
   1685 		addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK;
   1686 
   1687 		cur_offset = 0;
   1688 		while (alloclen) {
   1689 			if (addr_type == UDF_ICB_SHORT_ALLOC) {
   1690 				icblen = sizeof(struct short_ad);
   1691 				s_ad   = (struct short_ad *) pos;
   1692 				len        = udf_rw32(s_ad->len);
   1693 				plb_num    = udf_rw32(s_ad->lb_num);
   1694 			} else {
   1695 				/* should not be present, but why not */
   1696 				icblen = sizeof(struct long_ad);
   1697 				l_ad   = (struct long_ad *) pos;
   1698 				len        = udf_rw32(l_ad->len);
   1699 				plb_num    = udf_rw32(l_ad->loc.lb_num);
   1700 				/* pvpart_num = udf_rw16(l_ad->loc.part_num); */
   1701 			}
   1702 			/* process extent */
   1703 			flags   = UDF_EXT_FLAGS(len);
   1704 			len     = UDF_EXT_LEN(len);
   1705 
   1706 			if (cur_offset + len > lb_num * sector_size) {
   1707 				if (flags != UDF_EXT_ALLOCATED)
   1708 					return EINVAL;
   1709 				lb_rel = lb_num - cur_offset / sector_size;
   1710 				/* remainder of this extent */
   1711 				*lb_numres = plb_num + lb_rel +
   1712 					udf_rw32(pdesc->start_loc);
   1713 				*extres = (len / sector_size) - lb_rel;
   1714 				return 0;
   1715 			}
   1716 			cur_offset += len;
   1717 			pos        += icblen;
   1718 			alloclen   -= icblen;
   1719 		}
   1720 		/* not found */
   1721 		DPRINTF(TRANSLATE, ("Metadata partition translation failed\n"));
   1722 		return EINVAL;
   1723 	default:
   1724 		printf("UDF vtop translation scheme %d unimplemented yet\n",
   1725 			ump->vtop_tp[vpart]);
   1726 	}
   1727 
   1728 	return EINVAL;
   1729 }
   1730 
   1731 /* --------------------------------------------------------------------- */
   1732 
   1733 /* To make absolutely sure we are NOT returning zero, add one :) */
   1734 
   1735 long
   1736 udf_calchash(struct long_ad *icbptr)
   1737 {
   1738 	/* ought to be enough since each mountpoint has its own chain */
   1739 	return udf_rw32(icbptr->loc.lb_num) + 1;
   1740 }
   1741 
   1742 /* --------------------------------------------------------------------- */
   1743 
   1744 static struct udf_node *
   1745 udf_hashget(struct udf_mount *ump, struct long_ad *icbptr)
   1746 {
   1747 	struct udf_node *unp;
   1748 	struct vnode *vp;
   1749 	uint32_t hashline;
   1750 
   1751 loop:
   1752 	simple_lock(&ump->ihash_slock);
   1753 
   1754 	hashline = udf_calchash(icbptr) & UDF_INODE_HASHMASK;
   1755 	LIST_FOREACH(unp, &ump->udf_nodes[hashline], hashchain) {
   1756 		assert(unp);
   1757 		if (unp->loc.loc.lb_num   == icbptr->loc.lb_num &&
   1758 		    unp->loc.loc.part_num == icbptr->loc.part_num) {
   1759 			vp = unp->vnode;
   1760 			assert(vp);
   1761 			simple_lock(&vp->v_interlock);
   1762 			simple_unlock(&ump->ihash_slock);
   1763 			if (vget(vp, LK_EXCLUSIVE | LK_INTERLOCK))
   1764 				goto loop;
   1765 			return unp;
   1766 		}
   1767 	}
   1768 	simple_unlock(&ump->ihash_slock);
   1769 
   1770 	return NULL;
   1771 }
   1772 
   1773 /* --------------------------------------------------------------------- */
   1774 
   1775 static void
   1776 udf_hashins(struct udf_node *unp)
   1777 {
   1778 	struct udf_mount *ump;
   1779 	uint32_t hashline;
   1780 
   1781 	ump = unp->ump;
   1782 	simple_lock(&ump->ihash_slock);
   1783 
   1784 	hashline = udf_calchash(&unp->loc) & UDF_INODE_HASHMASK;
   1785 	LIST_INSERT_HEAD(&ump->udf_nodes[hashline], unp, hashchain);
   1786 
   1787 	simple_unlock(&ump->ihash_slock);
   1788 }
   1789 
   1790 /* --------------------------------------------------------------------- */
   1791 
   1792 static void
   1793 udf_hashrem(struct udf_node *unp)
   1794 {
   1795 	struct udf_mount *ump;
   1796 
   1797 	ump = unp->ump;
   1798 	simple_lock(&ump->ihash_slock);
   1799 
   1800 	LIST_REMOVE(unp, hashchain);
   1801 
   1802 	simple_unlock(&ump->ihash_slock);
   1803 }
   1804 
   1805 /* --------------------------------------------------------------------- */
   1806 
   1807 int
   1808 udf_dispose_locked_node(struct udf_node *node)
   1809 {
   1810 	if (!node)
   1811 		return 0;
   1812 	if (node->vnode)
   1813 		VOP_UNLOCK(node->vnode, 0);
   1814 	return udf_dispose_node(node);
   1815 }
   1816 
   1817 /* --------------------------------------------------------------------- */
   1818 
   1819 int
   1820 udf_dispose_node(struct udf_node *node)
   1821 {
   1822 	struct vnode *vp;
   1823 
   1824 	DPRINTF(NODE, ("udf_dispose_node called on node %p\n", node));
   1825 	if (!node) {
   1826 		DPRINTF(NODE, ("UDF: Dispose node on node NULL, ignoring\n"));
   1827 		return 0;
   1828 	}
   1829 
   1830 	vp  = node->vnode;
   1831 
   1832 	/* TODO extended attributes and streamdir */
   1833 
   1834 	/* remove from our hash lookup table */
   1835 	udf_hashrem(node);
   1836 
   1837 	/* dissociate our udf_node from the vnode */
   1838 	vp->v_data = NULL;
   1839 
   1840 	/* free associated memory and the node itself */
   1841 	if (node->fe)
   1842 		pool_put(node->ump->desc_pool, node->fe);
   1843 	if (node->efe)
   1844 		pool_put(node->ump->desc_pool, node->efe);
   1845 	pool_put(&udf_node_pool, node);
   1846 
   1847 	return 0;
   1848 }
   1849 
   1850 /* --------------------------------------------------------------------- */
   1851 
   1852 /*
   1853  * Genfs interfacing
   1854  *
   1855  * static const struct genfs_ops udffs_genfsops = {
   1856  * 	.gop_size = genfs_size,
   1857  * 		size of transfers
   1858  * 	.gop_alloc = udf_gop_alloc,
   1859  * 		unknown
   1860  * 	.gop_write = genfs_gop_write,
   1861  * 		putpages interface code
   1862  * 	.gop_markupdate = udf_gop_markupdate,
   1863  * 		set update/modify flags etc.
   1864  * }
   1865  */
   1866 
   1867 /*
   1868  * Genfs interface. These four functions are the only ones defined though not
   1869  * documented... great.... why is chosen for the `.' initialisers i dont know
   1870  * but other filingsystems seem to use it this way.
   1871  */
   1872 
   1873 static int
   1874 udf_gop_alloc(struct vnode *vp, off_t off,
   1875     off_t len, int flags, kauth_cred_t cred)
   1876 {
   1877 	return 0;
   1878 }
   1879 
   1880 
   1881 static void
   1882 udf_gop_markupdate(struct vnode *vp, int flags)
   1883 {
   1884 	struct udf_node *udf_node = VTOI(vp);
   1885 	u_long mask;
   1886 
   1887 	udf_node = udf_node;	/* shut up gcc */
   1888 
   1889 	mask = 0;
   1890 #ifdef notyet
   1891 	if ((flags & GOP_UPDATE_ACCESSED) != 0) {
   1892 		mask = UDF_SET_ACCESS;
   1893 	}
   1894 	if ((flags & GOP_UPDATE_MODIFIED) != 0) {
   1895 		mask |= UDF_SET_UPDATE;
   1896 	}
   1897 	if (mask) {
   1898 		udf_node->update_flag |= mask;
   1899 	}
   1900 #endif
   1901 	/* msdosfs doesn't do it, but shouldn't we update the times here? */
   1902 }
   1903 
   1904 
   1905 static const struct genfs_ops udf_genfsops = {
   1906 	.gop_size = genfs_size,
   1907 	.gop_alloc = udf_gop_alloc,
   1908 	.gop_write = genfs_gop_write,
   1909 	.gop_markupdate = udf_gop_markupdate,
   1910 };
   1911 
   1912 /* --------------------------------------------------------------------- */
   1913 
   1914 /*
   1915  * Each node can have an attached streamdir node though not
   1916  * recursively. These are otherwise known as named substreams/named
   1917  * extended attributes that have no size limitations.
   1918  *
   1919  * `Normal' extended attributes are indicated with a number and are recorded
   1920  * in either the fe/efe descriptor itself for small descriptors or recorded in
   1921  * the attached extended attribute file. Since this file can get fragmented,
   1922  * care ought to be taken.
   1923  */
   1924 
   1925 int
   1926 udf_get_node(struct udf_mount *ump, struct long_ad *node_icb_loc,
   1927 	     struct udf_node **noderes)
   1928 {
   1929 	union dscrptr   *dscr, *tmpdscr;
   1930 	struct udf_node *node;
   1931 	struct vnode    *nvp;
   1932 	struct long_ad   icb_loc;
   1933 	extern int (**udf_vnodeop_p)(void *);
   1934 	uint64_t file_size;
   1935 	uint32_t lb_size, sector, dummy;
   1936 	int udf_file_type, dscr_type, strat, strat4096, needs_indirect;
   1937 	int error;
   1938 
   1939 	DPRINTF(NODE, ("udf_get_node called\n"));
   1940 	*noderes = node = NULL;
   1941 
   1942 	/* lock to disallow simultanious creation of same node */
   1943 	lockmgr(&ump->get_node_lock, LK_EXCLUSIVE, NULL);
   1944 
   1945 	DPRINTF(NODE, ("\tlookup in hash table\n"));
   1946 	/* lookup in hash table */
   1947 	assert(ump);
   1948 	assert(node_icb_loc);
   1949 	node = udf_hashget(ump, node_icb_loc);
   1950 	if (node) {
   1951 		DPRINTF(NODE, ("\tgot it from the hash!\n"));
   1952 		/* vnode is returned locked */
   1953 		*noderes = node;
   1954 		lockmgr(&ump->get_node_lock, LK_RELEASE, NULL);
   1955 		return 0;
   1956 	}
   1957 
   1958 	/* garbage check: translate node_icb_loc to sectornr */
   1959 	error = udf_translate_vtop(ump, node_icb_loc, &sector, &dummy);
   1960 	if (error) {
   1961 		/* no use, this will fail anyway */
   1962 		lockmgr(&ump->get_node_lock, LK_RELEASE, NULL);
   1963 		return EINVAL;
   1964 	}
   1965 
   1966 	/* build node (do initialise!) */
   1967 	node = pool_get(&udf_node_pool, PR_WAITOK);
   1968 	memset(node, 0, sizeof(struct udf_node));
   1969 
   1970 	DPRINTF(NODE, ("\tget new vnode\n"));
   1971 	/* give it a vnode */
   1972 	error = getnewvnode(VT_UDF, ump->vfs_mountp, udf_vnodeop_p, &nvp);
   1973         if (error) {
   1974 		pool_put(&udf_node_pool, node);
   1975 		lockmgr(&ump->get_node_lock, LK_RELEASE, NULL);
   1976 		return error;
   1977 	}
   1978 
   1979 	/* allways return locked vnode */
   1980 	if ((error = vn_lock(nvp, LK_EXCLUSIVE | LK_RETRY))) {
   1981 		/* recycle vnode and unlock; simultanious will fail too */
   1982 		ungetnewvnode(nvp);
   1983 		lockmgr(&ump->get_node_lock, LK_RELEASE, NULL);
   1984 		return error;
   1985 	}
   1986 
   1987 	/* initialise crosslinks, note location of fe/efe for hashing */
   1988 	node->ump    =  ump;
   1989 	node->vnode  =  nvp;
   1990 	nvp->v_data  =  node;
   1991 	node->loc    = *node_icb_loc;
   1992 	node->lockf  =  0;
   1993 
   1994 	/* insert into the hash lookup */
   1995 	udf_hashins(node);
   1996 
   1997 	/* safe to unlock, the entry is in the hash table, vnode is locked */
   1998 	lockmgr(&ump->get_node_lock, LK_RELEASE, NULL);
   1999 
   2000 	icb_loc = *node_icb_loc;
   2001 	needs_indirect = 0;
   2002 	strat4096 = 0;
   2003 	udf_file_type = UDF_ICB_FILETYPE_UNKNOWN;
   2004 	file_size = 0;
   2005 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   2006 
   2007 	do {
   2008 		error = udf_translate_vtop(ump, &icb_loc, &sector, &dummy);
   2009 		if (error)
   2010 			break;
   2011 
   2012 		/* try to read in fe/efe */
   2013 		error = udf_read_descriptor(ump, sector, M_UDFTEMP, &tmpdscr);
   2014 
   2015 		/* blank sector marks end of sequence, check this */
   2016 		if ((tmpdscr == NULL) &&  (!strat4096))
   2017 			error = ENOENT;
   2018 
   2019 		/* break if read error or blank sector */
   2020 		if (error || (tmpdscr == NULL))
   2021 			break;
   2022 
   2023 		/* process descriptor based on the descriptor type */
   2024 		dscr_type = udf_rw16(tmpdscr->tag.id);
   2025 
   2026 		/* if dealing with an indirect entry, follow the link */
   2027 		if (dscr_type == TAGID_INDIRECT_ENTRY) {
   2028 			needs_indirect = 0;
   2029 			icb_loc = tmpdscr->inde.indirect_icb;
   2030 			free(tmpdscr, M_UDFTEMP);
   2031 			continue;
   2032 		}
   2033 
   2034 		/* only file entries and extended file entries allowed here */
   2035 		if ((dscr_type != TAGID_FENTRY) &&
   2036 		    (dscr_type != TAGID_EXTFENTRY)) {
   2037 			free(tmpdscr, M_UDFTEMP);
   2038 			error = ENOENT;
   2039 			break;
   2040 		}
   2041 
   2042 		/* get descriptor space from our pool */
   2043 		KASSERT(udf_tagsize(tmpdscr, lb_size) == lb_size);
   2044 
   2045 		dscr = pool_get(ump->desc_pool, PR_WAITOK);
   2046 		memcpy(dscr, tmpdscr, lb_size);
   2047 		free(tmpdscr, M_UDFTEMP);
   2048 
   2049 		/* record and process/update (ext)fentry */
   2050 		if (dscr_type == TAGID_FENTRY) {
   2051 			if (node->fe)
   2052 				pool_put(ump->desc_pool, node->fe);
   2053 			node->fe  = &dscr->fe;
   2054 			strat = udf_rw16(node->fe->icbtag.strat_type);
   2055 			udf_file_type = node->fe->icbtag.file_type;
   2056 			file_size = udf_rw64(node->fe->inf_len);
   2057 		} else {
   2058 			if (node->efe)
   2059 				pool_put(ump->desc_pool, node->efe);
   2060 			node->efe = &dscr->efe;
   2061 			strat = udf_rw16(node->efe->icbtag.strat_type);
   2062 			udf_file_type = node->efe->icbtag.file_type;
   2063 			file_size = udf_rw64(node->efe->inf_len);
   2064 		}
   2065 
   2066 		/* check recording strategy (structure) */
   2067 
   2068 		/*
   2069 		 * Strategy 4096 is a daisy linked chain terminating with an
   2070 		 * unrecorded sector or a TERM descriptor. The next
   2071 		 * descriptor is to be found in the sector that follows the
   2072 		 * current sector.
   2073 		 */
   2074 		if (strat == 4096) {
   2075 			strat4096 = 1;
   2076 			needs_indirect = 1;
   2077 
   2078 			icb_loc.loc.lb_num = udf_rw32(icb_loc.loc.lb_num) + 1;
   2079 		}
   2080 
   2081 		/*
   2082 		 * Strategy 4 is the normal strategy and terminates, but if
   2083 		 * we're in strategy 4096, we can't have strategy 4 mixed in
   2084 		 */
   2085 
   2086 		if (strat == 4) {
   2087 			if (strat4096) {
   2088 				error = EINVAL;
   2089 				break;
   2090 			}
   2091 			break;		/* done */
   2092 		}
   2093 	} while (!error);
   2094 
   2095 	if (error) {
   2096 		/* recycle udf_node */
   2097 		udf_dispose_node(node);
   2098 
   2099 		/* recycle vnode */
   2100 		nvp->v_data = NULL;
   2101 		ungetnewvnode(nvp);
   2102 
   2103 		return EINVAL;		/* error code ok? */
   2104 	}
   2105 
   2106 	/* post process and initialise node */
   2107 
   2108 	/* assert no references to dscr anymore beyong this point */
   2109 	assert((node->fe) || (node->efe));
   2110 	dscr = NULL;
   2111 
   2112 	/*
   2113 	 * Record where to record an updated version of the descriptor. If
   2114 	 * there is a sequence of indirect entries, icb_loc will have been
   2115 	 * updated. Its the write disipline to allocate new space and to make
   2116 	 * sure the chain is maintained.
   2117 	 *
   2118 	 * `needs_indirect' flags if the next location is to be filled with
   2119 	 * with an indirect entry.
   2120 	 */
   2121 	node->next_loc = icb_loc;
   2122 	node->needs_indirect = needs_indirect;
   2123 
   2124 	/*
   2125 	 * Translate UDF filetypes into vnode types.
   2126 	 *
   2127 	 * Systemfiles like the meta main and mirror files are not treated as
   2128 	 * normal files, so we type them as having no type. UDF dictates that
   2129 	 * they are not allowed to be visible.
   2130 	 */
   2131 
   2132 	/* TODO specfs, fifofs etc etc. vnops setting */
   2133 	switch (udf_file_type) {
   2134 	case UDF_ICB_FILETYPE_DIRECTORY :
   2135 	case UDF_ICB_FILETYPE_STREAMDIR :
   2136 		nvp->v_type = VDIR;
   2137 		break;
   2138 	case UDF_ICB_FILETYPE_BLOCKDEVICE :
   2139 		nvp->v_type = VBLK;
   2140 		break;
   2141 	case UDF_ICB_FILETYPE_CHARDEVICE :
   2142 		nvp->v_type = VCHR;
   2143 		break;
   2144 	case UDF_ICB_FILETYPE_SYMLINK :
   2145 		nvp->v_type = VLNK;
   2146 		break;
   2147 	case UDF_ICB_FILETYPE_VAT :
   2148 	case UDF_ICB_FILETYPE_META_MAIN :
   2149 	case UDF_ICB_FILETYPE_META_MIRROR :
   2150 		nvp->v_type = VNON;
   2151 		break;
   2152 	case UDF_ICB_FILETYPE_RANDOMACCESS :
   2153 	case UDF_ICB_FILETYPE_REALTIME :
   2154 		nvp->v_type = VREG;
   2155 		break;
   2156 	default:
   2157 		/* YIKES, either a block/char device, fifo or something else */
   2158 		nvp->v_type = VNON;
   2159 	}
   2160 
   2161 	/* initialise genfs */
   2162 	genfs_node_init(nvp, &udf_genfsops);
   2163 
   2164 	/* don't forget to set vnode's v_size */
   2165 	nvp->v_size = file_size;
   2166 
   2167 	/* TODO ext attr and streamdir nodes */
   2168 
   2169 	*noderes = node;
   2170 
   2171 	return 0;
   2172 }
   2173 
   2174 /* --------------------------------------------------------------------- */
   2175 
   2176 /* UDF<->unix converters */
   2177 
   2178 /* --------------------------------------------------------------------- */
   2179 
   2180 static mode_t
   2181 udf_perm_to_unix_mode(uint32_t perm)
   2182 {
   2183 	mode_t mode;
   2184 
   2185 	mode  = ((perm & UDF_FENTRY_PERM_USER_MASK)      );
   2186 	mode |= ((perm & UDF_FENTRY_PERM_GRP_MASK  ) >> 2);
   2187 	mode |= ((perm & UDF_FENTRY_PERM_OWNER_MASK) >> 4);
   2188 
   2189 	return mode;
   2190 }
   2191 
   2192 /* --------------------------------------------------------------------- */
   2193 
   2194 #ifdef notyet
   2195 static uint32_t
   2196 unix_mode_to_udf_perm(mode_t mode)
   2197 {
   2198 	uint32_t perm;
   2199 
   2200 	perm  = ((mode & S_IRWXO)     );
   2201 	perm |= ((mode & S_IRWXG) << 2);
   2202 	perm |= ((mode & S_IRWXU) << 4);
   2203 	perm |= ((mode & S_IWOTH) << 3);
   2204 	perm |= ((mode & S_IWGRP) << 5);
   2205 	perm |= ((mode & S_IWUSR) << 7);
   2206 
   2207 	return perm;
   2208 }
   2209 #endif
   2210 
   2211 /* --------------------------------------------------------------------- */
   2212 
   2213 static uint32_t
   2214 udf_icb_to_unix_filetype(uint32_t icbftype)
   2215 {
   2216 	switch (icbftype) {
   2217 	case UDF_ICB_FILETYPE_DIRECTORY :
   2218 	case UDF_ICB_FILETYPE_STREAMDIR :
   2219 		return S_IFDIR;
   2220 	case UDF_ICB_FILETYPE_FIFO :
   2221 		return S_IFIFO;
   2222 	case UDF_ICB_FILETYPE_CHARDEVICE :
   2223 		return S_IFCHR;
   2224 	case UDF_ICB_FILETYPE_BLOCKDEVICE :
   2225 		return S_IFBLK;
   2226 	case UDF_ICB_FILETYPE_RANDOMACCESS :
   2227 	case UDF_ICB_FILETYPE_REALTIME :
   2228 		return S_IFREG;
   2229 	case UDF_ICB_FILETYPE_SYMLINK :
   2230 		return S_IFLNK;
   2231 	case UDF_ICB_FILETYPE_SOCKET :
   2232 		return S_IFSOCK;
   2233 	}
   2234 	/* no idea what this is */
   2235 	return 0;
   2236 }
   2237 
   2238 /* --------------------------------------------------------------------- */
   2239 
   2240 /* TODO KNF-ify */
   2241 
   2242 void
   2243 udf_to_unix_name(char *result, char *id, int len, struct charspec *chsp)
   2244 {
   2245 	uint16_t *raw_name, *unix_name;
   2246 	uint16_t *inchp, ch;
   2247 	uint8_t	 *outchp;
   2248 	int       ucode_chars, nice_uchars;
   2249 
   2250 	raw_name = malloc(2048 * sizeof(uint16_t), M_UDFTEMP, M_WAITOK);
   2251 	unix_name = raw_name + 1024;			/* split space in half */
   2252 	assert(sizeof(char) == sizeof(uint8_t));
   2253 	outchp = (uint8_t *) result;
   2254 	if ((chsp->type == 0) && (strcmp((char*) chsp->inf, "OSTA Compressed Unicode") == 0)) {
   2255 		*raw_name = *unix_name = 0;
   2256 		ucode_chars = udf_UncompressUnicode(len, (uint8_t *) id, raw_name);
   2257 		ucode_chars = MIN(ucode_chars, UnicodeLength((unicode_t *) raw_name));
   2258 		nice_uchars = UDFTransName(unix_name, raw_name, ucode_chars);
   2259 		for (inchp = unix_name; nice_uchars>0; inchp++, nice_uchars--) {
   2260 			ch = *inchp;
   2261 			/* XXX sloppy unicode -> latin */
   2262 			*outchp++ = ch & 255;
   2263 			if (!ch) break;
   2264 		}
   2265 		*outchp++ = 0;
   2266 	} else {
   2267 		/* assume 8bit char length byte latin-1 */
   2268 		assert(*id == 8);
   2269 		strncpy((char *) result, (char *) (id+1), strlen((char *) (id+1)));
   2270 	}
   2271 	free(raw_name, M_UDFTEMP);
   2272 }
   2273 
   2274 /* --------------------------------------------------------------------- */
   2275 
   2276 /* TODO KNF-ify */
   2277 
   2278 void
   2279 unix_to_udf_name(char *result, char *name,
   2280 		 uint8_t *result_len, struct charspec *chsp)
   2281 {
   2282 	uint16_t *raw_name;
   2283 	int       udf_chars, name_len;
   2284 	char     *inchp;
   2285 	uint16_t *outchp;
   2286 
   2287 	raw_name = malloc(1024, M_UDFTEMP, M_WAITOK);
   2288 	/* convert latin-1 or whatever to unicode-16 */
   2289 	*raw_name = 0;
   2290 	name_len  = 0;
   2291 	inchp  = name;
   2292 	outchp = raw_name;
   2293 	while (*inchp) {
   2294 		*outchp++ = (uint16_t) (*inchp++);
   2295 		name_len++;
   2296 	}
   2297 
   2298 	if ((chsp->type == 0) && (strcmp((char *) chsp->inf, "OSTA Compressed Unicode") == 0)) {
   2299 		udf_chars = udf_CompressUnicode(name_len, 8, (unicode_t *) raw_name, (byte *) result);
   2300 	} else {
   2301 		/* XXX assume 8bit char length byte latin-1 */
   2302 		*result++ = 8; udf_chars = 1;
   2303 		strncpy(result, name + 1, strlen(name+1));
   2304 		udf_chars += strlen(name);
   2305 	}
   2306 	*result_len = udf_chars;
   2307 	free(raw_name, M_UDFTEMP);
   2308 }
   2309 
   2310 /* --------------------------------------------------------------------- */
   2311 
   2312 void
   2313 udf_timestamp_to_timespec(struct udf_mount *ump,
   2314 			  struct timestamp *timestamp,
   2315 			  struct timespec  *timespec)
   2316 {
   2317 	struct clock_ymdhms ymdhms;
   2318 	uint32_t usecs, secs, nsecs;
   2319 	uint16_t tz;
   2320 
   2321 	/* fill in ymdhms structure from timestamp */
   2322 	memset(&ymdhms, 0, sizeof(ymdhms));
   2323 	ymdhms.dt_year = udf_rw16(timestamp->year);
   2324 	ymdhms.dt_mon  = timestamp->month;
   2325 	ymdhms.dt_day  = timestamp->day;
   2326 	ymdhms.dt_wday = 0; /* ? */
   2327 	ymdhms.dt_hour = timestamp->hour;
   2328 	ymdhms.dt_min  = timestamp->minute;
   2329 	ymdhms.dt_sec  = timestamp->second;
   2330 
   2331 	secs = clock_ymdhms_to_secs(&ymdhms);
   2332 	usecs = timestamp->usec +
   2333 		100*timestamp->hund_usec + 10000*timestamp->centisec;
   2334 	nsecs = usecs * 1000;
   2335 
   2336 	/*
   2337 	 * Calculate the time zone.  The timezone is 12 bit signed 2's
   2338 	 * compliment, so we gotta do some extra magic to handle it right.
   2339 	 */
   2340 	tz  = udf_rw16(timestamp->type_tz);
   2341 	tz &= 0x0fff;			/* only lower 12 bits are significant */
   2342 	if (tz & 0x0800)		/* sign extention */
   2343 		tz |= 0xf000;
   2344 
   2345 	/* TODO check timezone conversion */
   2346 	/* check if we are specified a timezone to convert */
   2347 	if (udf_rw16(timestamp->type_tz) & 0x1000) {
   2348 		if ((int16_t) tz != -2047)
   2349 			secs -= (int16_t) tz * 60;
   2350 	} else {
   2351 		secs -= ump->mount_args.gmtoff;
   2352 	}
   2353 
   2354 	timespec->tv_sec  = secs;
   2355 	timespec->tv_nsec = nsecs;
   2356 }
   2357 
   2358 /* --------------------------------------------------------------------- */
   2359 
   2360 /*
   2361  * Attribute and filetypes converters with get/set pairs
   2362  */
   2363 
   2364 uint32_t
   2365 udf_getaccessmode(struct udf_node *udf_node)
   2366 {
   2367 	struct file_entry *fe;
   2368 	struct extfile_entry *efe;
   2369 	uint32_t udf_perm, icbftype;
   2370 	uint32_t mode, ftype;
   2371 	uint16_t icbflags;
   2372 
   2373 	if (udf_node->fe) {
   2374 		fe = udf_node->fe;
   2375 		udf_perm = udf_rw32(fe->perm);
   2376 		icbftype = fe->icbtag.file_type;
   2377 		icbflags = udf_rw16(fe->icbtag.flags);
   2378 	} else {
   2379 		assert(udf_node->efe);
   2380 		efe = udf_node->efe;
   2381 		udf_perm = udf_rw32(efe->perm);
   2382 		icbftype = efe->icbtag.file_type;
   2383 		icbflags = udf_rw16(efe->icbtag.flags);
   2384 	}
   2385 
   2386 	mode  = udf_perm_to_unix_mode(udf_perm);
   2387 	ftype = udf_icb_to_unix_filetype(icbftype);
   2388 
   2389 	/* set suid, sgid, sticky from flags in fe/efe */
   2390 	if (icbflags & UDF_ICB_TAG_FLAGS_SETUID)
   2391 		mode |= S_ISUID;
   2392 	if (icbflags & UDF_ICB_TAG_FLAGS_SETGID)
   2393 		mode |= S_ISGID;
   2394 	if (icbflags & UDF_ICB_TAG_FLAGS_STICKY)
   2395 		mode |= S_ISVTX;
   2396 
   2397 	return mode | ftype;
   2398 }
   2399 
   2400 /* --------------------------------------------------------------------- */
   2401 
   2402 /*
   2403  * Directory read and manipulation functions
   2404  */
   2405 
   2406 int
   2407 udf_lookup_name_in_dir(struct vnode *vp, const char *name, int namelen,
   2408 		       struct long_ad *icb_loc)
   2409 {
   2410 	struct udf_node  *dir_node = VTOI(vp);
   2411 	struct file_entry    *fe;
   2412 	struct extfile_entry *efe;
   2413 	struct fileid_desc *fid;
   2414 	struct dirent dirent;
   2415 	uint64_t file_size, diroffset;
   2416 	uint32_t lb_size;
   2417 	int found, error;
   2418 
   2419 	/* get directory filesize */
   2420 	if (dir_node->fe) {
   2421 		fe = dir_node->fe;
   2422 		file_size = udf_rw64(fe->inf_len);
   2423 	} else {
   2424 		assert(dir_node->efe);
   2425 		efe = dir_node->efe;
   2426 		file_size = udf_rw64(efe->inf_len);
   2427 	}
   2428 
   2429 	/* allocate temporary space for fid */
   2430 	lb_size = udf_rw32(dir_node->ump->logical_vol->lb_size);
   2431 	fid = malloc(lb_size, M_TEMP, M_WAITOK);
   2432 
   2433 	found = 0;
   2434 	diroffset = dir_node->last_diroffset;
   2435 	while (!found) {
   2436 		/* if not found in this track, turn trough zero */
   2437 		if (diroffset >= file_size)
   2438 			diroffset = 0;
   2439 
   2440 		/* transfer a new fid/dirent */
   2441 		error = udf_read_fid_stream(vp, &diroffset, fid, &dirent);
   2442 		if (error)
   2443 			break;
   2444 
   2445 		/* skip deleted entries */
   2446 		if ((fid->file_char & UDF_FILE_CHAR_DEL) == 0) {
   2447 			if ((strlen(dirent.d_name) == namelen) &&
   2448 			    (strncmp(dirent.d_name, name, namelen) == 0)) {
   2449 				found = 1;
   2450 				*icb_loc = fid->icb;
   2451 			}
   2452 		}
   2453 
   2454 		if (diroffset == dir_node->last_diroffset) {
   2455 			/* we have cycled */
   2456 			break;
   2457 		}
   2458 	}
   2459 	free(fid, M_TEMP);
   2460 	dir_node->last_diroffset = diroffset;
   2461 
   2462 	return found;
   2463 }
   2464 
   2465 /* --------------------------------------------------------------------- */
   2466 
   2467 /*
   2468  * Read one fid and process it into a dirent and advance to the next (*fid)
   2469  * has to be allocated a logical block in size, (*dirent) struct dirent length
   2470  */
   2471 
   2472 int
   2473 udf_read_fid_stream(struct vnode *vp, uint64_t *offset,
   2474 		    struct fileid_desc *fid, struct dirent *dirent)
   2475 {
   2476 	struct udf_node  *dir_node = VTOI(vp);
   2477 	struct udf_mount *ump = dir_node->ump;
   2478 	struct file_entry    *fe;
   2479 	struct extfile_entry *efe;
   2480 	struct uio    dir_uio;
   2481 	struct iovec  dir_iovec;
   2482 	uint32_t      entry_length, lb_size;
   2483 	uint64_t      file_size;
   2484 	char         *fid_name;
   2485 	int           enough, error;
   2486 
   2487 	assert(fid);
   2488 	assert(dirent);
   2489 	assert(dir_node);
   2490 	assert(offset);
   2491 	assert(*offset != 1);
   2492 
   2493 	DPRINTF(FIDS, ("read_fid_stream called\n"));
   2494 	/* check if we're past the end of the directory */
   2495 	if (dir_node->fe) {
   2496 		fe = dir_node->fe;
   2497 		file_size = udf_rw64(fe->inf_len);
   2498 	} else {
   2499 		assert(dir_node->efe);
   2500 		efe = dir_node->efe;
   2501 		file_size = udf_rw64(efe->inf_len);
   2502 	}
   2503 	if (*offset >= file_size)
   2504 		return EINVAL;
   2505 
   2506 	/* get maximum length of FID descriptor */
   2507 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   2508 
   2509 	/* initialise return values */
   2510 	entry_length = 0;
   2511 	memset(dirent, 0, sizeof(struct dirent));
   2512 	memset(fid, 0, lb_size);
   2513 
   2514 	/* TODO use vn_rdwr instead of creating our own uio */
   2515 	/* read part of the directory */
   2516 	memset(&dir_uio, 0, sizeof(struct uio));
   2517 	dir_uio.uio_rw     = UIO_READ;	/* read into this space */
   2518 	dir_uio.uio_iovcnt = 1;
   2519 	dir_uio.uio_iov    = &dir_iovec;
   2520 	UIO_SETUP_SYSSPACE(&dir_uio);
   2521 	dir_iovec.iov_base = fid;
   2522 	dir_iovec.iov_len  = lb_size;
   2523 	dir_uio.uio_offset = *offset;
   2524 
   2525 	/* limit length of read in piece */
   2526 	dir_uio.uio_resid  = MIN(file_size - (*offset), lb_size);
   2527 
   2528 	/* read the part into the fid space */
   2529 	error = VOP_READ(vp, &dir_uio, IO_ALTSEMANTICS, NOCRED);
   2530 	if (error)
   2531 		return error;
   2532 
   2533 	/*
   2534 	 * Check if we got a whole descriptor.
   2535 	 * XXX Try to `resync' directory stream when something is very wrong.
   2536 	 *
   2537 	 */
   2538 	enough = (dir_uio.uio_offset - (*offset) >= UDF_FID_SIZE);
   2539 	if (!enough) {
   2540 		/* short dir ... */
   2541 		return EIO;
   2542 	}
   2543 
   2544 	/* check if our FID header is OK */
   2545 	error = udf_check_tag(fid);
   2546 	DPRINTFIF(FIDS, error, ("read fids: tag check failed\n"));
   2547 	if (!error) {
   2548 		if (udf_rw16(fid->tag.id) != TAGID_FID)
   2549 			error = ENOENT;
   2550 	}
   2551 	DPRINTFIF(FIDS, !error, ("\ttag checked ok: got TAGID_FID\n"));
   2552 
   2553 	/* check for length */
   2554 	if (!error) {
   2555 		entry_length = udf_fidsize(fid, lb_size);
   2556 		enough = (dir_uio.uio_offset - (*offset) >= entry_length);
   2557 	}
   2558 	DPRINTFIF(FIDS, !error, ("\tentry_length = %d, enough = %s\n",
   2559 	    entry_length, enough?"yes":"no"));
   2560 
   2561 	if (!enough) {
   2562 		/* short dir ... bomb out */
   2563 		return EIO;
   2564 	}
   2565 
   2566 	/* check FID contents */
   2567 	if (!error) {
   2568 		error = udf_check_tag_payload((union dscrptr *) fid, lb_size);
   2569 		DPRINTF(FIDS, ("\tpayload checked ok\n"));
   2570 	}
   2571 	if (error) {
   2572 		/* note that is sometimes a bit quick to report */
   2573 		printf("BROKEN DIRECTORY ENTRY\n");
   2574 		/* RESYNC? */
   2575 		/* TODO: use udf_resync_fid_stream */
   2576 		return EIO;
   2577 	}
   2578 	DPRINTF(FIDS, ("\tinterpret FID\n"));
   2579 
   2580 	/* we got a whole and valid descriptor! */
   2581 
   2582 	/* create resulting dirent structure */
   2583 	fid_name = (char *) fid->data + udf_rw16(fid->l_iu);
   2584 	udf_to_unix_name(dirent->d_name,
   2585 		fid_name, fid->l_fi, &ump->logical_vol->desc_charset);
   2586 
   2587 	/* '..' has no name, so provide one */
   2588 	if (fid->file_char & UDF_FILE_CHAR_PAR)
   2589 		strcpy(dirent->d_name, "..");
   2590 
   2591 	dirent->d_fileno = udf_calchash(&fid->icb);	/* inode hash XXX */
   2592 	dirent->d_namlen = strlen(dirent->d_name);
   2593 	dirent->d_reclen = _DIRENT_SIZE(dirent);
   2594 
   2595 	/*
   2596 	 * Note that its not worth trying to go for the filetypes now... its
   2597 	 * too expensive too
   2598 	 */
   2599 	dirent->d_type = DT_UNKNOWN;
   2600 
   2601 	/* initial guess for filetype we can make */
   2602 	if (fid->file_char & UDF_FILE_CHAR_DIR)
   2603 		dirent->d_type = DT_DIR;
   2604 
   2605 	/* advance */
   2606 	*offset += entry_length;
   2607 
   2608 	return error;
   2609 }
   2610 
   2611 /* --------------------------------------------------------------------- */
   2612 
   2613 /*
   2614  * block based file reading and writing
   2615  */
   2616 
   2617 static int
   2618 udf_read_internal(struct udf_node *node, uint8_t *blob)
   2619 {
   2620 	struct udf_mount *ump;
   2621 	struct file_entry *fe;
   2622 	struct extfile_entry *efe;
   2623 	uint64_t inflen;
   2624 	uint32_t sector_size;
   2625 	uint8_t  *pos;
   2626 	int icbflags, addr_type;
   2627 
   2628 	/* shut up gcc */
   2629 	inflen = addr_type = icbflags = 0;
   2630 	pos = NULL;
   2631 
   2632 	/* get extent and do some paranoia checks */
   2633 	ump = node->ump;
   2634 	sector_size = ump->discinfo.sector_size;
   2635 
   2636 	fe  = node->fe;
   2637 	efe = node->efe;
   2638 	if (fe) {
   2639 		inflen   = udf_rw64(fe->inf_len);
   2640 		pos      = &fe->data[0] + udf_rw32(fe->l_ea);
   2641 		icbflags = udf_rw16(fe->icbtag.flags);
   2642 	}
   2643 	if (efe) {
   2644 		inflen   = udf_rw64(efe->inf_len);
   2645 		pos      = &efe->data[0] + udf_rw32(efe->l_ea);
   2646 		icbflags = udf_rw16(efe->icbtag.flags);
   2647 	}
   2648 	addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK;
   2649 
   2650 	assert(addr_type == UDF_ICB_INTERN_ALLOC);
   2651 	assert(inflen < sector_size);
   2652 
   2653 	/* copy out info */
   2654 	memset(blob, 0, sector_size);
   2655 	memcpy(blob, pos, inflen);
   2656 
   2657 	return 0;
   2658 }
   2659 
   2660 /* --------------------------------------------------------------------- */
   2661 
   2662 /*
   2663  * Read file extent reads an extent specified in sectors from the file. It is
   2664  * sector based; i.e. no `fancy' offsets.
   2665  */
   2666 
   2667 int
   2668 udf_read_file_extent(struct udf_node *node,
   2669 		     uint32_t from, uint32_t sectors,
   2670 		     uint8_t *blob)
   2671 {
   2672 	struct buf buf;
   2673 	uint32_t sector_size;
   2674 
   2675 	BUF_INIT(&buf);
   2676 
   2677 	sector_size = node->ump->discinfo.sector_size;
   2678 
   2679 	buf.b_bufsize = sectors * sector_size;
   2680 	buf.b_data    = blob;
   2681 	buf.b_bcount  = buf.b_bufsize;
   2682 	buf.b_resid   = buf.b_bcount;
   2683 	buf.b_flags   = B_BUSY | B_READ;
   2684 	buf.b_vp      = node->vnode;
   2685 	buf.b_proc    = NULL;
   2686 
   2687 	buf.b_blkno  = from;
   2688 	buf.b_lblkno = 0;
   2689 	BIO_SETPRIO(&buf, BPRIO_TIMELIMITED);
   2690 
   2691 	udf_read_filebuf(node, &buf);
   2692 	return biowait(&buf);
   2693 }
   2694 
   2695 
   2696 /* --------------------------------------------------------------------- */
   2697 
   2698 /*
   2699  * Read file extent in the buffer.
   2700  *
   2701  * The splitup of the extent into separate request-buffers is to minimise
   2702  * copying around as much as possible.
   2703  */
   2704 
   2705 
   2706 /* maximum of 128 translations (!) (64 kb in 512 byte sectors) */
   2707 #define FILEBUFSECT 128
   2708 
   2709 void
   2710 udf_read_filebuf(struct udf_node *node, struct buf *buf)
   2711 {
   2712 	struct buf *nestbuf;
   2713 	uint64_t   *mapping;
   2714 	uint64_t    run_start;
   2715 	uint32_t    sector_size;
   2716 	uint32_t    buf_offset, sector, rbuflen, rblk;
   2717 	uint8_t    *buf_pos;
   2718 	int error, run_length;
   2719 
   2720 	uint32_t  from;
   2721 	uint32_t  sectors;
   2722 
   2723 	sector_size = node->ump->discinfo.sector_size;
   2724 
   2725 	from    = buf->b_blkno;
   2726 	sectors = buf->b_bcount / sector_size;
   2727 
   2728 	/* assure we have enough translation slots */
   2729 	KASSERT(buf->b_bcount / sector_size <= FILEBUFSECT);
   2730 	KASSERT(MAXPHYS / sector_size <= FILEBUFSECT);
   2731 
   2732 	if (sectors > FILEBUFSECT) {
   2733 		printf("udf_read_filebuf: implementation limit on bufsize\n");
   2734 		buf->b_error  = EIO;
   2735 		buf->b_flags |= B_ERROR;
   2736 		biodone(buf);
   2737 		return;
   2738 	}
   2739 
   2740 	mapping = malloc(sizeof(*mapping) * FILEBUFSECT, M_TEMP, M_WAITOK);
   2741 
   2742 	error = 0;
   2743 	DPRINTF(READ, ("\ttranslate %d-%d\n", from, sectors));
   2744 	error = udf_translate_file_extent(node, from, sectors, mapping);
   2745 	if (error) {
   2746 		buf->b_error  = error;
   2747 		buf->b_flags |= B_ERROR;
   2748 		biodone(buf);
   2749 		goto out;
   2750 	}
   2751 	DPRINTF(READ, ("\ttranslate extent went OK\n"));
   2752 
   2753 	/* pre-check if internal or parts are zero */
   2754 	if (*mapping == UDF_TRANS_INTERN) {
   2755 		error = udf_read_internal(node, (uint8_t *) buf->b_data);
   2756 		if (error) {
   2757 			buf->b_error  = error;
   2758 			buf->b_flags |= B_ERROR;
   2759 		}
   2760 		biodone(buf);
   2761 		goto out;
   2762 	}
   2763 	DPRINTF(READ, ("\tnot intern\n"));
   2764 
   2765 	/* request read-in of data from disc scheduler */
   2766 	buf->b_resid = buf->b_bcount;
   2767 	for (sector = 0; sector < sectors; sector++) {
   2768 		buf_offset = sector * sector_size;
   2769 		buf_pos    = (uint8_t *) buf->b_data + buf_offset;
   2770 		DPRINTF(READ, ("\tprocessing rel sector %d\n", sector));
   2771 
   2772 		switch (mapping[sector]) {
   2773 		case UDF_TRANS_UNMAPPED:
   2774 		case UDF_TRANS_ZERO:
   2775 			/* copy zero sector */
   2776 			memset(buf_pos, 0, sector_size);
   2777 			DPRINTF(READ, ("\treturning zero sector\n"));
   2778 			nestiobuf_done(buf, sector_size, 0);
   2779 			break;
   2780 		default :
   2781 			DPRINTF(READ, ("\tread sector "
   2782 			    "%"PRIu64"\n", mapping[sector]));
   2783 
   2784 			run_start  = mapping[sector];
   2785 			run_length = 1;
   2786 			while (sector < sectors-1) {
   2787 				if (mapping[sector+1] != mapping[sector]+1)
   2788 					break;
   2789 				run_length++;
   2790 				sector++;
   2791 			}
   2792 
   2793 			/*
   2794 			 * nest an iobuf and mark it for async reading. Since
   2795 			 * we're using nested buffers, they can't be cached by
   2796 			 * design.
   2797 			 */
   2798 			rbuflen = run_length * sector_size;
   2799 			rblk    = run_start  * (sector_size/DEV_BSIZE);
   2800 
   2801 			nestbuf = getiobuf();
   2802 			nestiobuf_setup(buf, nestbuf, buf_offset, rbuflen);
   2803 			/* nestbuf is B_ASYNC */
   2804 
   2805 			/* CD schedules on raw blkno */
   2806 			nestbuf->b_blkno    = rblk;
   2807 			nestbuf->b_proc     = NULL;
   2808 			nestbuf->b_cylinder = 0;
   2809 			nestbuf->b_rawblkno = rblk;
   2810 			VOP_STRATEGY(node->ump->devvp, nestbuf);
   2811 		}
   2812 	}
   2813 out:
   2814 	DPRINTF(READ, ("\tend of read_filebuf\n"));
   2815 	free(mapping, M_TEMP);
   2816 	return;
   2817 }
   2818 #undef FILEBUFSECT
   2819 
   2820 
   2821 /* --------------------------------------------------------------------- */
   2822 
   2823 /*
   2824  * Translate an extent (in sectors) into sector numbers; used for read and
   2825  * write operations. DOESNT't check extents.
   2826  */
   2827 
   2828 int
   2829 udf_translate_file_extent(struct udf_node *node,
   2830 		          uint32_t from, uint32_t pages,
   2831 			  uint64_t *map)
   2832 {
   2833 	struct udf_mount *ump;
   2834 	struct file_entry *fe;
   2835 	struct extfile_entry *efe;
   2836 	struct short_ad *s_ad;
   2837 	struct long_ad  *l_ad, t_ad;
   2838 	uint64_t transsec;
   2839 	uint32_t sector_size, transsec32;
   2840 	uint32_t overlap, translen;
   2841 	uint32_t vpart_num, lb_num, len, alloclen;
   2842 	uint8_t *pos;
   2843 	int error, flags, addr_type, icblen, icbflags;
   2844 
   2845 	if (!node)
   2846 		return ENOENT;
   2847 
   2848 	/* shut up gcc */
   2849 	alloclen = addr_type = icbflags = 0;
   2850 	pos = NULL;
   2851 
   2852 	/* do the work */
   2853 	ump = node->ump;
   2854 	sector_size = ump->discinfo.sector_size;
   2855 	fe  = node->fe;
   2856 	efe = node->efe;
   2857 	if (fe) {
   2858 		alloclen = udf_rw32(fe->l_ad);
   2859 		pos      = &fe->data[0] + udf_rw32(fe->l_ea);
   2860 		icbflags = udf_rw16(fe->icbtag.flags);
   2861 	}
   2862 	if (efe) {
   2863 		alloclen = udf_rw32(efe->l_ad);
   2864 		pos      = &efe->data[0] + udf_rw32(efe->l_ea);
   2865 		icbflags = udf_rw16(efe->icbtag.flags);
   2866 	}
   2867 	addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK;
   2868 
   2869 	DPRINTF(TRANSLATE, ("udf trans: alloc_len = %d, addr_type %d, "
   2870 	    "fe %p, efe %p\n", alloclen, addr_type, fe, efe));
   2871 
   2872 	vpart_num = udf_rw16(node->loc.loc.part_num);
   2873 	lb_num = len = icblen = 0;	/* shut up gcc */
   2874 	while (pages && alloclen) {
   2875 		DPRINTF(TRANSLATE, ("\taddr_type %d\n", addr_type));
   2876 		switch (addr_type) {
   2877 		case UDF_ICB_INTERN_ALLOC :
   2878 			/* TODO check extents? */
   2879 			*map = UDF_TRANS_INTERN;
   2880 			return 0;
   2881 		case UDF_ICB_SHORT_ALLOC :
   2882 			icblen = sizeof(struct short_ad);
   2883 			s_ad   = (struct short_ad *) pos;
   2884 			len       = udf_rw32(s_ad->len);
   2885 			lb_num    = udf_rw32(s_ad->lb_num);
   2886 			break;
   2887 		case UDF_ICB_LONG_ALLOC  :
   2888 			icblen = sizeof(struct long_ad);
   2889 			l_ad   = (struct long_ad *) pos;
   2890 			len       = udf_rw32(l_ad->len);
   2891 			lb_num    = udf_rw32(l_ad->loc.lb_num);
   2892 			vpart_num = udf_rw16(l_ad->loc.part_num);
   2893 			DPRINTFIF(TRANSLATE,
   2894 			    (l_ad->impl.im_used.flags &
   2895 			     UDF_ADIMP_FLAGS_EXTENT_ERASED),
   2896 			    ("UDF: got an `extent erased' flag in long_ad\n"));
   2897 			break;
   2898 		default:
   2899 			/* can't be here */
   2900 			return EINVAL;	/* for sure */
   2901 		}
   2902 
   2903 		/* process extent */
   2904 		flags   = UDF_EXT_FLAGS(len);
   2905 		len     = UDF_EXT_LEN(len);
   2906 
   2907 		overlap = (len + sector_size -1) / sector_size;
   2908 		if (from) {
   2909 			if (from > overlap) {
   2910 				from -= overlap;
   2911 				overlap = 0;
   2912 			} else {
   2913 				lb_num  += from;	/* advance in extent */
   2914 				overlap -= from;
   2915 				from = 0;
   2916 			}
   2917 		}
   2918 
   2919 		overlap = MIN(overlap, pages);
   2920 		while (overlap) {
   2921 			switch (flags) {
   2922 			case UDF_EXT_REDIRECT :
   2923 				/* no support for allocation extentions yet */
   2924 				/* TODO support for allocation extention */
   2925 				return ENOENT;
   2926 			case UDF_EXT_FREED :
   2927 			case UDF_EXT_FREE :
   2928 				transsec = UDF_TRANS_ZERO;
   2929 				translen = overlap;
   2930 				while (overlap && pages && translen) {
   2931 					*map++ = transsec;
   2932 					lb_num++;
   2933 					overlap--; pages--; translen--;
   2934 				}
   2935 				break;
   2936 			case UDF_EXT_ALLOCATED :
   2937 				t_ad.loc.lb_num   = udf_rw32(lb_num);
   2938 				t_ad.loc.part_num = udf_rw16(vpart_num);
   2939 				error = udf_translate_vtop(ump,
   2940 						&t_ad, &transsec32, &translen);
   2941 				transsec = transsec32;
   2942 				if (error)
   2943 					return error;
   2944 				while (overlap && pages && translen) {
   2945 					*map++ = transsec;
   2946 					lb_num++; transsec++;
   2947 					overlap--; pages--; translen--;
   2948 				}
   2949 				break;
   2950 			}
   2951 		}
   2952 		pos      += icblen;
   2953 		alloclen -= icblen;
   2954 	}
   2955 	return 0;
   2956 }
   2957 
   2958 /* --------------------------------------------------------------------- */
   2959 
   2960