Home | History | Annotate | Line # | Download | only in udf
udf_subr.c revision 1.44.6.3
      1 /* $NetBSD: udf_subr.c,v 1.44.6.3 2008/09/28 10:40:51 mjf Exp $ */
      2 
      3 /*
      4  * Copyright (c) 2006, 2008 Reinoud Zandijk
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  *
     27  */
     28 
     29 
     30 #include <sys/cdefs.h>
     31 #ifndef lint
     32 __KERNEL_RCSID(0, "$NetBSD: udf_subr.c,v 1.44.6.3 2008/09/28 10:40:51 mjf Exp $");
     33 #endif /* not lint */
     34 
     35 
     36 #if defined(_KERNEL_OPT)
     37 #include "opt_quota.h"
     38 #include "opt_compat_netbsd.h"
     39 #endif
     40 
     41 #include <sys/param.h>
     42 #include <sys/systm.h>
     43 #include <sys/sysctl.h>
     44 #include <sys/namei.h>
     45 #include <sys/proc.h>
     46 #include <sys/kernel.h>
     47 #include <sys/vnode.h>
     48 #include <miscfs/genfs/genfs_node.h>
     49 #include <sys/mount.h>
     50 #include <sys/buf.h>
     51 #include <sys/file.h>
     52 #include <sys/device.h>
     53 #include <sys/disklabel.h>
     54 #include <sys/ioctl.h>
     55 #include <sys/malloc.h>
     56 #include <sys/dirent.h>
     57 #include <sys/stat.h>
     58 #include <sys/conf.h>
     59 #include <sys/kauth.h>
     60 #include <fs/unicode.h>
     61 #include <dev/clock_subr.h>
     62 
     63 #include <fs/udf/ecma167-udf.h>
     64 #include <fs/udf/udf_mount.h>
     65 
     66 #include "udf.h"
     67 #include "udf_subr.h"
     68 #include "udf_bswap.h"
     69 
     70 
     71 #define VTOI(vnode) ((struct udf_node *) (vnode)->v_data)
     72 
     73 #define UDF_SET_SYSTEMFILE(vp) \
     74 	/* XXXAD Is the vnode locked? */	\
     75 	(vp)->v_vflag |= VV_SYSTEM;		\
     76 	vref(vp);			\
     77 	vput(vp);			\
     78 
     79 extern int syncer_maxdelay;     /* maximum delay time */
     80 extern int (**udf_vnodeop_p)(void *);
     81 
     82 /* --------------------------------------------------------------------- */
     83 
     84 //#ifdef DEBUG
     85 #if 1
     86 
     87 #if 0
     88 static void
     89 udf_dumpblob(boid *blob, uint32_t dlen)
     90 {
     91 	int i, j;
     92 
     93 	printf("blob = %p\n", blob);
     94 	printf("dump of %d bytes\n", dlen);
     95 
     96 	for (i = 0; i < dlen; i+ = 16) {
     97 		printf("%04x ", i);
     98 		for (j = 0; j < 16; j++) {
     99 			if (i+j < dlen) {
    100 				printf("%02x ", blob[i+j]);
    101 			} else {
    102 				printf("   ");
    103 			}
    104 		}
    105 		for (j = 0; j < 16; j++) {
    106 			if (i+j < dlen) {
    107 				if (blob[i+j]>32 && blob[i+j]! = 127) {
    108 					printf("%c", blob[i+j]);
    109 				} else {
    110 					printf(".");
    111 				}
    112 			}
    113 		}
    114 		printf("\n");
    115 	}
    116 	printf("\n");
    117 	Debugger();
    118 }
    119 #endif
    120 
    121 static void
    122 udf_dump_discinfo(struct udf_mount *ump)
    123 {
    124 	char   bits[128];
    125 	struct mmc_discinfo *di = &ump->discinfo;
    126 
    127 	if ((udf_verbose & UDF_DEBUG_VOLUMES) == 0)
    128 		return;
    129 
    130 	printf("Device/media info  :\n");
    131 	printf("\tMMC profile        0x%02x\n", di->mmc_profile);
    132 	printf("\tderived class      %d\n", di->mmc_class);
    133 	printf("\tsector size        %d\n", di->sector_size);
    134 	printf("\tdisc state         %d\n", di->disc_state);
    135 	printf("\tlast ses state     %d\n", di->last_session_state);
    136 	printf("\tbg format state    %d\n", di->bg_format_state);
    137 	printf("\tfrst track         %d\n", di->first_track);
    138 	printf("\tfst on last ses    %d\n", di->first_track_last_session);
    139 	printf("\tlst on last ses    %d\n", di->last_track_last_session);
    140 	printf("\tlink block penalty %d\n", di->link_block_penalty);
    141 	bitmask_snprintf(di->disc_flags, MMC_DFLAGS_FLAGBITS, bits,
    142 		sizeof(bits));
    143 	printf("\tdisc flags         %s\n", bits);
    144 	printf("\tdisc id            %x\n", di->disc_id);
    145 	printf("\tdisc barcode       %"PRIx64"\n", di->disc_barcode);
    146 
    147 	printf("\tnum sessions       %d\n", di->num_sessions);
    148 	printf("\tnum tracks         %d\n", di->num_tracks);
    149 
    150 	bitmask_snprintf(di->mmc_cur, MMC_CAP_FLAGBITS, bits, sizeof(bits));
    151 	printf("\tcapabilities cur   %s\n", bits);
    152 	bitmask_snprintf(di->mmc_cap, MMC_CAP_FLAGBITS, bits, sizeof(bits));
    153 	printf("\tcapabilities cap   %s\n", bits);
    154 }
    155 #else
    156 #define udf_dump_discinfo(a);
    157 #endif
    158 
    159 
    160 /* --------------------------------------------------------------------- */
    161 
    162 /* not called often */
    163 int
    164 udf_update_discinfo(struct udf_mount *ump)
    165 {
    166 	struct vnode *devvp = ump->devvp;
    167 	struct partinfo dpart;
    168 	struct mmc_discinfo *di;
    169 	int error;
    170 
    171 	DPRINTF(VOLUMES, ("read/update disc info\n"));
    172 	di = &ump->discinfo;
    173 	memset(di, 0, sizeof(struct mmc_discinfo));
    174 
    175 	/* check if we're on a MMC capable device, i.e. CD/DVD */
    176 	error = VOP_IOCTL(devvp, MMCGETDISCINFO, di, FKIOCTL, NOCRED);
    177 	if (error == 0) {
    178 		udf_dump_discinfo(ump);
    179 		return 0;
    180 	}
    181 
    182 	/* disc partition support */
    183 	error = VOP_IOCTL(devvp, DIOCGPART, &dpart, FREAD, NOCRED);
    184 	if (error)
    185 		return ENODEV;
    186 
    187 	/* set up a disc info profile for partitions */
    188 	di->mmc_profile		= 0x01;	/* disc type */
    189 	di->mmc_class		= MMC_CLASS_DISC;
    190 	di->disc_state		= MMC_STATE_CLOSED;
    191 	di->last_session_state	= MMC_STATE_CLOSED;
    192 	di->bg_format_state	= MMC_BGFSTATE_COMPLETED;
    193 	di->link_block_penalty	= 0;
    194 
    195 	di->mmc_cur     = MMC_CAP_RECORDABLE | MMC_CAP_REWRITABLE |
    196 		MMC_CAP_ZEROLINKBLK | MMC_CAP_HW_DEFECTFREE;
    197 	di->mmc_cap    = di->mmc_cur;
    198 	di->disc_flags = MMC_DFLAGS_UNRESTRICTED;
    199 
    200 	/* TODO problem with last_possible_lba on resizable VND; request */
    201 	di->last_possible_lba = dpart.part->p_size;
    202 	di->sector_size       = dpart.disklab->d_secsize;
    203 
    204 	di->num_sessions = 1;
    205 	di->num_tracks   = 1;
    206 
    207 	di->first_track  = 1;
    208 	di->first_track_last_session = di->last_track_last_session = 1;
    209 
    210 	udf_dump_discinfo(ump);
    211 	return 0;
    212 }
    213 
    214 
    215 int
    216 udf_update_trackinfo(struct udf_mount *ump, struct mmc_trackinfo *ti)
    217 {
    218 	struct vnode *devvp = ump->devvp;
    219 	struct mmc_discinfo *di = &ump->discinfo;
    220 	int error, class;
    221 
    222 	DPRINTF(VOLUMES, ("read track info\n"));
    223 
    224 	class = di->mmc_class;
    225 	if (class != MMC_CLASS_DISC) {
    226 		/* tracknr specified in struct ti */
    227 		error = VOP_IOCTL(devvp, MMCGETTRACKINFO, ti, FKIOCTL, NOCRED);
    228 		return error;
    229 	}
    230 
    231 	/* disc partition support */
    232 	if (ti->tracknr != 1)
    233 		return EIO;
    234 
    235 	/* create fake ti (TODO check for resized vnds) */
    236 	ti->sessionnr  = 1;
    237 
    238 	ti->track_mode = 0;	/* XXX */
    239 	ti->data_mode  = 0;	/* XXX */
    240 	ti->flags = MMC_TRACKINFO_LRA_VALID | MMC_TRACKINFO_NWA_VALID;
    241 
    242 	ti->track_start    = 0;
    243 	ti->packet_size    = 1;
    244 
    245 	/* TODO support for resizable vnd */
    246 	ti->track_size    = di->last_possible_lba;
    247 	ti->next_writable = di->last_possible_lba;
    248 	ti->last_recorded = ti->next_writable;
    249 	ti->free_blocks   = 0;
    250 
    251 	return 0;
    252 }
    253 
    254 
    255 int
    256 udf_setup_writeparams(struct udf_mount *ump)
    257 {
    258 	struct mmc_writeparams mmc_writeparams;
    259 	int error;
    260 
    261 	if (ump->discinfo.mmc_class == MMC_CLASS_DISC)
    262 		return 0;
    263 
    264 	/*
    265 	 * only CD burning normally needs setting up, but other disc types
    266 	 * might need other settings to be made. The MMC framework will set up
    267 	 * the nessisary recording parameters according to the disc
    268 	 * characteristics read in. Modifications can be made in the discinfo
    269 	 * structure passed to change the nature of the disc.
    270 	 */
    271 
    272 	memset(&mmc_writeparams, 0, sizeof(struct mmc_writeparams));
    273 	mmc_writeparams.mmc_class  = ump->discinfo.mmc_class;
    274 	mmc_writeparams.mmc_cur    = ump->discinfo.mmc_cur;
    275 
    276 	/*
    277 	 * UDF dictates first track to determine track mode for the whole
    278 	 * disc. [UDF 1.50/6.10.1.1, UDF 1.50/6.10.2.1]
    279 	 * To prevent problems with a `reserved' track in front we start with
    280 	 * the 2nd track and if that is not valid, go for the 1st.
    281 	 */
    282 	mmc_writeparams.tracknr = 2;
    283 	mmc_writeparams.data_mode  = MMC_DATAMODE_DEFAULT;	/* XA disc */
    284 	mmc_writeparams.track_mode = MMC_TRACKMODE_DEFAULT;	/* data */
    285 
    286 	error = VOP_IOCTL(ump->devvp, MMCSETUPWRITEPARAMS, &mmc_writeparams,
    287 			FKIOCTL, NOCRED);
    288 	if (error) {
    289 		mmc_writeparams.tracknr = 1;
    290 		error = VOP_IOCTL(ump->devvp, MMCSETUPWRITEPARAMS,
    291 				&mmc_writeparams, FKIOCTL, NOCRED);
    292 	}
    293 	return error;
    294 }
    295 
    296 
    297 int
    298 udf_synchronise_caches(struct udf_mount *ump)
    299 {
    300 	struct mmc_op mmc_op;
    301 
    302 	DPRINTF(CALL, ("udf_synchronise_caches()\n"));
    303 
    304 	if (ump->vfs_mountp->mnt_flag & MNT_RDONLY)
    305 		return 0;
    306 
    307 	/* discs are done now */
    308 	if (ump->discinfo.mmc_class == MMC_CLASS_DISC)
    309 		return 0;
    310 
    311 	bzero(&mmc_op, sizeof(struct mmc_op));
    312 	mmc_op.operation = MMC_OP_SYNCHRONISECACHE;
    313 
    314 	/* ignore return code */
    315 	(void) VOP_IOCTL(ump->devvp, MMCOP, &mmc_op, FKIOCTL, NOCRED);
    316 
    317 	return 0;
    318 }
    319 
    320 /* --------------------------------------------------------------------- */
    321 
    322 /* track/session searching for mounting */
    323 int
    324 udf_search_tracks(struct udf_mount *ump, struct udf_args *args,
    325 		  int *first_tracknr, int *last_tracknr)
    326 {
    327 	struct mmc_trackinfo trackinfo;
    328 	uint32_t tracknr, start_track, num_tracks;
    329 	int error;
    330 
    331 	/* if negative, sessionnr is relative to last session */
    332 	if (args->sessionnr < 0) {
    333 		args->sessionnr += ump->discinfo.num_sessions;
    334 	}
    335 
    336 	/* sanity */
    337 	if (args->sessionnr < 0)
    338 		args->sessionnr = 0;
    339 	if (args->sessionnr > ump->discinfo.num_sessions)
    340 		args->sessionnr = ump->discinfo.num_sessions;
    341 
    342 	/* search the tracks for this session, zero session nr indicates last */
    343 	if (args->sessionnr == 0)
    344 		args->sessionnr = ump->discinfo.num_sessions;
    345 	if (ump->discinfo.last_session_state == MMC_STATE_EMPTY)
    346 		args->sessionnr--;
    347 
    348 	/* sanity again */
    349 	if (args->sessionnr < 0)
    350 		args->sessionnr = 0;
    351 
    352 	/* search the first and last track of the specified session */
    353 	num_tracks  = ump->discinfo.num_tracks;
    354 	start_track = ump->discinfo.first_track;
    355 
    356 	/* search for first track of this session */
    357 	for (tracknr = start_track; tracknr <= num_tracks; tracknr++) {
    358 		/* get track info */
    359 		trackinfo.tracknr = tracknr;
    360 		error = udf_update_trackinfo(ump, &trackinfo);
    361 		if (error)
    362 			return error;
    363 
    364 		if (trackinfo.sessionnr == args->sessionnr)
    365 			break;
    366 	}
    367 	*first_tracknr = tracknr;
    368 
    369 	/* search for last track of this session */
    370 	for (;tracknr <= num_tracks; tracknr++) {
    371 		/* get track info */
    372 		trackinfo.tracknr = tracknr;
    373 		error = udf_update_trackinfo(ump, &trackinfo);
    374 		if (error || (trackinfo.sessionnr != args->sessionnr)) {
    375 			tracknr--;
    376 			break;
    377 		}
    378 	}
    379 	if (tracknr > num_tracks)
    380 		tracknr--;
    381 
    382 	*last_tracknr = tracknr;
    383 
    384 	if (*last_tracknr < *first_tracknr) {
    385 		printf( "udf_search_tracks: sanity check on drive+disc failed, "
    386 			"drive returned garbage\n");
    387 		return EINVAL;
    388 	}
    389 
    390 	assert(*last_tracknr >= *first_tracknr);
    391 	return 0;
    392 }
    393 
    394 
    395 /*
    396  * NOTE: this is the only routine in this file that directly peeks into the
    397  * metadata file but since its at a larval state of the mount it can't hurt.
    398  *
    399  * XXX candidate for udf_allocation.c
    400  * XXX clean me up!, change to new node reading code.
    401  */
    402 
    403 static void
    404 udf_check_track_metadata_overlap(struct udf_mount *ump,
    405 	struct mmc_trackinfo *trackinfo)
    406 {
    407 	struct part_desc *part;
    408 	struct file_entry      *fe;
    409 	struct extfile_entry   *efe;
    410 	struct short_ad        *s_ad;
    411 	struct long_ad         *l_ad;
    412 	uint32_t track_start, track_end;
    413 	uint32_t phys_part_start, phys_part_end, part_start, part_end;
    414 	uint32_t sector_size, len, alloclen, plb_num;
    415 	uint8_t *pos;
    416 	int addr_type, icblen, icbflags, flags;
    417 
    418 	/* get our track extents */
    419 	track_start = trackinfo->track_start;
    420 	track_end   = track_start + trackinfo->track_size;
    421 
    422 	/* get our base partition extent */
    423 	KASSERT(ump->node_part == ump->fids_part);
    424 	part = ump->partitions[ump->node_part];
    425 	phys_part_start = udf_rw32(part->start_loc);
    426 	phys_part_end   = phys_part_start + udf_rw32(part->part_len);
    427 
    428 	/* no use if its outside the physical partition */
    429 	if ((phys_part_start >= track_end) || (phys_part_end < track_start))
    430 		return;
    431 
    432 	/*
    433 	 * now follow all extents in the fe/efe to see if they refer to this
    434 	 * track
    435 	 */
    436 
    437 	sector_size = ump->discinfo.sector_size;
    438 
    439 	/* XXX should we claim exclusive access to the metafile ? */
    440 	/* TODO: move to new node read code */
    441 	fe  = ump->metadata_node->fe;
    442 	efe = ump->metadata_node->efe;
    443 	if (fe) {
    444 		alloclen = udf_rw32(fe->l_ad);
    445 		pos      = &fe->data[0] + udf_rw32(fe->l_ea);
    446 		icbflags = udf_rw16(fe->icbtag.flags);
    447 	} else {
    448 		assert(efe);
    449 		alloclen = udf_rw32(efe->l_ad);
    450 		pos      = &efe->data[0] + udf_rw32(efe->l_ea);
    451 		icbflags = udf_rw16(efe->icbtag.flags);
    452 	}
    453 	addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK;
    454 
    455 	while (alloclen) {
    456 		if (addr_type == UDF_ICB_SHORT_ALLOC) {
    457 			icblen = sizeof(struct short_ad);
    458 			s_ad   = (struct short_ad *) pos;
    459 			len        = udf_rw32(s_ad->len);
    460 			plb_num    = udf_rw32(s_ad->lb_num);
    461 		} else {
    462 			/* should not be present, but why not */
    463 			icblen = sizeof(struct long_ad);
    464 			l_ad   = (struct long_ad *) pos;
    465 			len        = udf_rw32(l_ad->len);
    466 			plb_num    = udf_rw32(l_ad->loc.lb_num);
    467 			/* pvpart_num = udf_rw16(l_ad->loc.part_num); */
    468 		}
    469 		/* process extent */
    470 		flags   = UDF_EXT_FLAGS(len);
    471 		len     = UDF_EXT_LEN(len);
    472 
    473 		part_start = phys_part_start + plb_num;
    474 		part_end   = part_start + (len / sector_size);
    475 
    476 		if ((part_start >= track_start) && (part_end <= track_end)) {
    477 			/* extent is enclosed within this track */
    478 			ump->metadata_track = *trackinfo;
    479 			return;
    480 		}
    481 
    482 		pos        += icblen;
    483 		alloclen   -= icblen;
    484 	}
    485 }
    486 
    487 
    488 int
    489 udf_search_writing_tracks(struct udf_mount *ump)
    490 {
    491 	struct mmc_trackinfo trackinfo;
    492 	struct part_desc *part;
    493 	uint32_t tracknr, start_track, num_tracks;
    494 	uint32_t track_start, track_end, part_start, part_end;
    495 	int node_alloc, error;
    496 
    497 	/*
    498 	 * in the CD/(HD)DVD/BD recordable device model a few tracks within
    499 	 * the last session might be open but in the UDF device model at most
    500 	 * three tracks can be open: a reserved track for delayed ISO VRS
    501 	 * writing, a data track and a metadata track. We search here for the
    502 	 * data track and the metadata track. Note that the reserved track is
    503 	 * troublesome but can be detected by its small size of < 512 sectors.
    504 	 */
    505 
    506 	num_tracks  = ump->discinfo.num_tracks;
    507 	start_track = ump->discinfo.first_track;
    508 
    509 	/* fetch info on first and possibly only track */
    510 	trackinfo.tracknr = start_track;
    511 	error = udf_update_trackinfo(ump, &trackinfo);
    512 	if (error)
    513 		return error;
    514 
    515 	/* copy results to our mount point */
    516 	ump->data_track     = trackinfo;
    517 	ump->metadata_track = trackinfo;
    518 
    519 	/* if not sequential, we're done */
    520 	if (num_tracks == 1)
    521 		return 0;
    522 
    523 	for (tracknr = start_track;tracknr <= num_tracks; tracknr++) {
    524 		/* get track info */
    525 		trackinfo.tracknr = tracknr;
    526 		error = udf_update_trackinfo(ump, &trackinfo);
    527 		if (error)
    528 			return error;
    529 
    530 		if ((trackinfo.flags & MMC_TRACKINFO_NWA_VALID) == 0)
    531 			continue;
    532 
    533 		track_start = trackinfo.track_start;
    534 		track_end   = track_start + trackinfo.track_size;
    535 
    536 		/* check for overlap on data partition */
    537 		part = ump->partitions[ump->data_part];
    538 		part_start = udf_rw32(part->start_loc);
    539 		part_end   = part_start + udf_rw32(part->part_len);
    540 		if ((part_start < track_end) && (part_end > track_start)) {
    541 			ump->data_track = trackinfo;
    542 			/* TODO check if UDF partition data_part is writable */
    543 		}
    544 
    545 		/* check for overlap on metadata partition */
    546 		node_alloc = ump->vtop_alloc[ump->node_part];
    547 		if ((node_alloc == UDF_ALLOC_METASEQUENTIAL) ||
    548 		    (node_alloc == UDF_ALLOC_METABITMAP)) {
    549 			udf_check_track_metadata_overlap(ump, &trackinfo);
    550 		} else {
    551 			ump->metadata_track = trackinfo;
    552 		}
    553 	}
    554 
    555 	if ((ump->data_track.flags & MMC_TRACKINFO_NWA_VALID) == 0)
    556 		return EROFS;
    557 
    558 	if ((ump->metadata_track.flags & MMC_TRACKINFO_NWA_VALID) == 0)
    559 		return EROFS;
    560 
    561 	return 0;
    562 }
    563 
    564 /* --------------------------------------------------------------------- */
    565 
    566 /*
    567  * Check if the blob starts with a good UDF tag. Tags are protected by a
    568  * checksum over the reader except one byte at position 4 that is the checksum
    569  * itself.
    570  */
    571 
    572 int
    573 udf_check_tag(void *blob)
    574 {
    575 	struct desc_tag *tag = blob;
    576 	uint8_t *pos, sum, cnt;
    577 
    578 	/* check TAG header checksum */
    579 	pos = (uint8_t *) tag;
    580 	sum = 0;
    581 
    582 	for(cnt = 0; cnt < 16; cnt++) {
    583 		if (cnt != 4)
    584 			sum += *pos;
    585 		pos++;
    586 	}
    587 	if (sum != tag->cksum) {
    588 		/* bad tag header checksum; this is not a valid tag */
    589 		return EINVAL;
    590 	}
    591 
    592 	return 0;
    593 }
    594 
    595 
    596 /*
    597  * check tag payload will check descriptor CRC as specified.
    598  * If the descriptor is too long, it will return EIO otherwise EINVAL.
    599  */
    600 
    601 int
    602 udf_check_tag_payload(void *blob, uint32_t max_length)
    603 {
    604 	struct desc_tag *tag = blob;
    605 	uint16_t crc, crc_len;
    606 
    607 	crc_len = udf_rw16(tag->desc_crc_len);
    608 
    609 	/* check payload CRC if applicable */
    610 	if (crc_len == 0)
    611 		return 0;
    612 
    613 	if (crc_len > max_length)
    614 		return EIO;
    615 
    616 	crc = udf_cksum(((uint8_t *) tag) + UDF_DESC_TAG_LENGTH, crc_len);
    617 	if (crc != udf_rw16(tag->desc_crc)) {
    618 		/* bad payload CRC; this is a broken tag */
    619 		return EINVAL;
    620 	}
    621 
    622 	return 0;
    623 }
    624 
    625 
    626 void
    627 udf_validate_tag_sum(void *blob)
    628 {
    629 	struct desc_tag *tag = blob;
    630 	uint8_t *pos, sum, cnt;
    631 
    632 	/* calculate TAG header checksum */
    633 	pos = (uint8_t *) tag;
    634 	sum = 0;
    635 
    636 	for(cnt = 0; cnt < 16; cnt++) {
    637 		if (cnt != 4) sum += *pos;
    638 		pos++;
    639 	}
    640 	tag->cksum = sum;	/* 8 bit */
    641 }
    642 
    643 
    644 /* assumes sector number of descriptor to be saved already present */
    645 void
    646 udf_validate_tag_and_crc_sums(void *blob)
    647 {
    648 	struct desc_tag *tag  = blob;
    649 	uint8_t         *btag = (uint8_t *) tag;
    650 	uint16_t crc, crc_len;
    651 
    652 	crc_len = udf_rw16(tag->desc_crc_len);
    653 
    654 	/* check payload CRC if applicable */
    655 	if (crc_len > 0) {
    656 		crc = udf_cksum(btag + UDF_DESC_TAG_LENGTH, crc_len);
    657 		tag->desc_crc = udf_rw16(crc);
    658 	}
    659 
    660 	/* calculate TAG header checksum */
    661 	udf_validate_tag_sum(blob);
    662 }
    663 
    664 /* --------------------------------------------------------------------- */
    665 
    666 /*
    667  * XXX note the different semantics from udfclient: for FIDs it still rounds
    668  * up to sectors. Use udf_fidsize() for a correct length.
    669  */
    670 
    671 int
    672 udf_tagsize(union dscrptr *dscr, uint32_t lb_size)
    673 {
    674 	uint32_t size, tag_id, num_lb, elmsz;
    675 
    676 	tag_id = udf_rw16(dscr->tag.id);
    677 
    678 	switch (tag_id) {
    679 	case TAGID_LOGVOL :
    680 		size  = sizeof(struct logvol_desc) - 1;
    681 		size += udf_rw32(dscr->lvd.mt_l);
    682 		break;
    683 	case TAGID_UNALLOC_SPACE :
    684 		elmsz = sizeof(struct extent_ad);
    685 		size  = sizeof(struct unalloc_sp_desc) - elmsz;
    686 		size += udf_rw32(dscr->usd.alloc_desc_num) * elmsz;
    687 		break;
    688 	case TAGID_FID :
    689 		size = UDF_FID_SIZE + dscr->fid.l_fi + udf_rw16(dscr->fid.l_iu);
    690 		size = (size + 3) & ~3;
    691 		break;
    692 	case TAGID_LOGVOL_INTEGRITY :
    693 		size  = sizeof(struct logvol_int_desc) - sizeof(uint32_t);
    694 		size += udf_rw32(dscr->lvid.l_iu);
    695 		size += (2 * udf_rw32(dscr->lvid.num_part) * sizeof(uint32_t));
    696 		break;
    697 	case TAGID_SPACE_BITMAP :
    698 		size  = sizeof(struct space_bitmap_desc) - 1;
    699 		size += udf_rw32(dscr->sbd.num_bytes);
    700 		break;
    701 	case TAGID_SPARING_TABLE :
    702 		elmsz = sizeof(struct spare_map_entry);
    703 		size  = sizeof(struct udf_sparing_table) - elmsz;
    704 		size += udf_rw16(dscr->spt.rt_l) * elmsz;
    705 		break;
    706 	case TAGID_FENTRY :
    707 		size  = sizeof(struct file_entry);
    708 		size += udf_rw32(dscr->fe.l_ea) + udf_rw32(dscr->fe.l_ad)-1;
    709 		break;
    710 	case TAGID_EXTFENTRY :
    711 		size  = sizeof(struct extfile_entry);
    712 		size += udf_rw32(dscr->efe.l_ea) + udf_rw32(dscr->efe.l_ad)-1;
    713 		break;
    714 	case TAGID_FSD :
    715 		size  = sizeof(struct fileset_desc);
    716 		break;
    717 	default :
    718 		size = sizeof(union dscrptr);
    719 		break;
    720 	}
    721 
    722 	if ((size == 0) || (lb_size == 0))
    723 		return 0;
    724 
    725 	if (lb_size == 1)
    726 		return size;
    727 
    728 	/* round up in sectors */
    729 	num_lb = (size + lb_size -1) / lb_size;
    730 	return num_lb * lb_size;
    731 }
    732 
    733 
    734 int
    735 udf_fidsize(struct fileid_desc *fid)
    736 {
    737 	uint32_t size;
    738 
    739 	if (udf_rw16(fid->tag.id) != TAGID_FID)
    740 		panic("got udf_fidsize on non FID\n");
    741 
    742 	size = UDF_FID_SIZE + fid->l_fi + udf_rw16(fid->l_iu);
    743 	size = (size + 3) & ~3;
    744 
    745 	return size;
    746 }
    747 
    748 /* --------------------------------------------------------------------- */
    749 
    750 void
    751 udf_lock_node(struct udf_node *udf_node, int flag, char const *fname, const int lineno)
    752 {
    753 	int ret;
    754 
    755 	mutex_enter(&udf_node->node_mutex);
    756 	/* wait until free */
    757 	while (udf_node->i_flags & IN_LOCKED) {
    758 		ret = cv_timedwait(&udf_node->node_lock, &udf_node->node_mutex, hz/8);
    759 		/* TODO check if we should return error; abort */
    760 		if (ret == EWOULDBLOCK) {
    761 			DPRINTF(LOCKING, ( "udf_lock_node: udf_node %p would block "
    762 				"wanted at %s:%d, previously locked at %s:%d\n",
    763 				udf_node, fname, lineno,
    764 				udf_node->lock_fname, udf_node->lock_lineno));
    765 		}
    766 	}
    767 	/* grab */
    768 	udf_node->i_flags |= IN_LOCKED | flag;
    769 	/* debug */
    770 	udf_node->lock_fname  = fname;
    771 	udf_node->lock_lineno = lineno;
    772 
    773 	mutex_exit(&udf_node->node_mutex);
    774 }
    775 
    776 
    777 void
    778 udf_unlock_node(struct udf_node *udf_node, int flag)
    779 {
    780 	mutex_enter(&udf_node->node_mutex);
    781 	udf_node->i_flags &= ~(IN_LOCKED | flag);
    782 	cv_broadcast(&udf_node->node_lock);
    783 	mutex_exit(&udf_node->node_mutex);
    784 }
    785 
    786 
    787 /* --------------------------------------------------------------------- */
    788 
    789 static int
    790 udf_read_anchor(struct udf_mount *ump, uint32_t sector, struct anchor_vdp **dst)
    791 {
    792 	int error;
    793 
    794 	error = udf_read_phys_dscr(ump, sector, M_UDFVOLD,
    795 			(union dscrptr **) dst);
    796 	if (!error) {
    797 		/* blank terminator blocks are not allowed here */
    798 		if (*dst == NULL)
    799 			return ENOENT;
    800 		if (udf_rw16((*dst)->tag.id) != TAGID_ANCHOR) {
    801 			error = ENOENT;
    802 			free(*dst, M_UDFVOLD);
    803 			*dst = NULL;
    804 			DPRINTF(VOLUMES, ("Not an anchor\n"));
    805 		}
    806 	}
    807 
    808 	return error;
    809 }
    810 
    811 
    812 int
    813 udf_read_anchors(struct udf_mount *ump)
    814 {
    815 	struct udf_args *args = &ump->mount_args;
    816 	struct mmc_trackinfo first_track;
    817 	struct mmc_trackinfo second_track;
    818 	struct mmc_trackinfo last_track;
    819 	struct anchor_vdp **anchorsp;
    820 	uint32_t track_start;
    821 	uint32_t track_end;
    822 	uint32_t positions[4];
    823 	int first_tracknr, last_tracknr;
    824 	int error, anch, ok, first_anchor;
    825 
    826 	/* search the first and last track of the specified session */
    827 	error = udf_search_tracks(ump, args, &first_tracknr, &last_tracknr);
    828 	if (!error) {
    829 		first_track.tracknr = first_tracknr;
    830 		error = udf_update_trackinfo(ump, &first_track);
    831 	}
    832 	if (!error) {
    833 		last_track.tracknr = last_tracknr;
    834 		error = udf_update_trackinfo(ump, &last_track);
    835 	}
    836 	if ((!error) && (first_tracknr != last_tracknr)) {
    837 		second_track.tracknr = first_tracknr+1;
    838 		error = udf_update_trackinfo(ump, &second_track);
    839 	}
    840 	if (error) {
    841 		printf("UDF mount: reading disc geometry failed\n");
    842 		return 0;
    843 	}
    844 
    845 	track_start = first_track.track_start;
    846 
    847 	/* `end' is not as straitforward as start. */
    848 	track_end =   last_track.track_start
    849 		    + last_track.track_size - last_track.free_blocks - 1;
    850 
    851 	if (ump->discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) {
    852 		/* end of track is not straitforward here */
    853 		if (last_track.flags & MMC_TRACKINFO_LRA_VALID)
    854 			track_end = last_track.last_recorded;
    855 		else if (last_track.flags & MMC_TRACKINFO_NWA_VALID)
    856 			track_end = last_track.next_writable
    857 				    - ump->discinfo.link_block_penalty;
    858 	}
    859 
    860 	/* its no use reading a blank track */
    861 	first_anchor = 0;
    862 	if (first_track.flags & MMC_TRACKINFO_BLANK)
    863 		first_anchor = 1;
    864 
    865 	/* get our packet size */
    866 	ump->packet_size = first_track.packet_size;
    867 	if (first_track.flags & MMC_TRACKINFO_BLANK)
    868 		ump->packet_size = second_track.packet_size;
    869 
    870 	if (ump->packet_size <= 1) {
    871 		/* take max, but not bigger than 64 */
    872 		ump->packet_size = MAXPHYS / ump->discinfo.sector_size;
    873 		ump->packet_size = MIN(ump->packet_size, 64);
    874 	}
    875 	KASSERT(ump->packet_size >= 1);
    876 
    877 	/* read anchors start+256, start+512, end-256, end */
    878 	positions[0] = track_start+256;
    879 	positions[1] =   track_end-256;
    880 	positions[2] =   track_end;
    881 	positions[3] = track_start+512;	/* [UDF 2.60/6.11.2] */
    882 	/* XXX shouldn't +512 be prefered above +256 for compat with Roxio CD */
    883 
    884 	ok = 0;
    885 	anchorsp = ump->anchors;
    886 	for (anch = first_anchor; anch < 4; anch++) {
    887 		DPRINTF(VOLUMES, ("Read anchor %d at sector %d\n", anch,
    888 		    positions[anch]));
    889 		error = udf_read_anchor(ump, positions[anch], anchorsp);
    890 		if (!error) {
    891 			anchorsp++;
    892 			ok++;
    893 		}
    894 	}
    895 
    896 	/* VATs are only recorded on sequential media, but initialise */
    897 	ump->first_possible_vat_location = track_start + 2;
    898 	ump->last_possible_vat_location  = track_end + last_track.packet_size;
    899 
    900 	return ok;
    901 }
    902 
    903 /* --------------------------------------------------------------------- */
    904 
    905 /* we dont try to be smart; we just record the parts */
    906 #define UDF_UPDATE_DSCR(name, dscr) \
    907 	if (name) \
    908 		free(name, M_UDFVOLD); \
    909 	name = dscr;
    910 
    911 static int
    912 udf_process_vds_descriptor(struct udf_mount *ump, union dscrptr *dscr)
    913 {
    914 	struct part_desc *part;
    915 	uint16_t phys_part, raw_phys_part;
    916 
    917 	DPRINTF(VOLUMES, ("\tprocessing VDS descr %d\n",
    918 	    udf_rw16(dscr->tag.id)));
    919 	switch (udf_rw16(dscr->tag.id)) {
    920 	case TAGID_PRI_VOL :		/* primary partition		*/
    921 		UDF_UPDATE_DSCR(ump->primary_vol, &dscr->pvd);
    922 		break;
    923 	case TAGID_LOGVOL :		/* logical volume		*/
    924 		UDF_UPDATE_DSCR(ump->logical_vol, &dscr->lvd);
    925 		break;
    926 	case TAGID_UNALLOC_SPACE :	/* unallocated space		*/
    927 		UDF_UPDATE_DSCR(ump->unallocated, &dscr->usd);
    928 		break;
    929 	case TAGID_IMP_VOL :		/* implementation		*/
    930 		/* XXX do we care about multiple impl. descr ? */
    931 		UDF_UPDATE_DSCR(ump->implementation, &dscr->ivd);
    932 		break;
    933 	case TAGID_PARTITION :		/* physical partition		*/
    934 		/* not much use if its not allocated */
    935 		if ((udf_rw16(dscr->pd.flags) & UDF_PART_FLAG_ALLOCATED) == 0) {
    936 			free(dscr, M_UDFVOLD);
    937 			break;
    938 		}
    939 
    940 		/*
    941 		 * BUGALERT: some rogue implementations use random physical
    942 		 * partion numbers to break other implementations so lookup
    943 		 * the number.
    944 		 */
    945 		raw_phys_part = udf_rw16(dscr->pd.part_num);
    946 		for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) {
    947 			part = ump->partitions[phys_part];
    948 			if (part == NULL)
    949 				break;
    950 			if (udf_rw16(part->part_num) == raw_phys_part)
    951 				break;
    952 		}
    953 		if (phys_part == UDF_PARTITIONS) {
    954 			free(dscr, M_UDFVOLD);
    955 			return EINVAL;
    956 		}
    957 
    958 		UDF_UPDATE_DSCR(ump->partitions[phys_part], &dscr->pd);
    959 		break;
    960 	case TAGID_VOL :		/* volume space extender; rare	*/
    961 		DPRINTF(VOLUMES, ("VDS extender ignored\n"));
    962 		free(dscr, M_UDFVOLD);
    963 		break;
    964 	default :
    965 		DPRINTF(VOLUMES, ("Unhandled VDS type %d\n",
    966 		    udf_rw16(dscr->tag.id)));
    967 		free(dscr, M_UDFVOLD);
    968 	}
    969 
    970 	return 0;
    971 }
    972 #undef UDF_UPDATE_DSCR
    973 
    974 /* --------------------------------------------------------------------- */
    975 
    976 static int
    977 udf_read_vds_extent(struct udf_mount *ump, uint32_t loc, uint32_t len)
    978 {
    979 	union dscrptr *dscr;
    980 	uint32_t sector_size, dscr_size;
    981 	int error;
    982 
    983 	sector_size = ump->discinfo.sector_size;
    984 
    985 	/* loc is sectornr, len is in bytes */
    986 	error = EIO;
    987 	while (len) {
    988 		error = udf_read_phys_dscr(ump, loc, M_UDFVOLD, &dscr);
    989 		if (error)
    990 			return error;
    991 
    992 		/* blank block is a terminator */
    993 		if (dscr == NULL)
    994 			return 0;
    995 
    996 		/* TERM descriptor is a terminator */
    997 		if (udf_rw16(dscr->tag.id) == TAGID_TERM) {
    998 			free(dscr, M_UDFVOLD);
    999 			return 0;
   1000 		}
   1001 
   1002 		/* process all others */
   1003 		dscr_size = udf_tagsize(dscr, sector_size);
   1004 		error = udf_process_vds_descriptor(ump, dscr);
   1005 		if (error) {
   1006 			free(dscr, M_UDFVOLD);
   1007 			break;
   1008 		}
   1009 		assert((dscr_size % sector_size) == 0);
   1010 
   1011 		len -= dscr_size;
   1012 		loc += dscr_size / sector_size;
   1013 	}
   1014 
   1015 	return error;
   1016 }
   1017 
   1018 
   1019 int
   1020 udf_read_vds_space(struct udf_mount *ump)
   1021 {
   1022 	/* struct udf_args *args = &ump->mount_args; */
   1023 	struct anchor_vdp *anchor, *anchor2;
   1024 	size_t size;
   1025 	uint32_t main_loc, main_len;
   1026 	uint32_t reserve_loc, reserve_len;
   1027 	int error;
   1028 
   1029 	/*
   1030 	 * read in VDS space provided by the anchors; if one descriptor read
   1031 	 * fails, try the mirror sector.
   1032 	 *
   1033 	 * check if 2nd anchor is different from 1st; if so, go for 2nd. This
   1034 	 * avoids the `compatibility features' of DirectCD that may confuse
   1035 	 * stuff completely.
   1036 	 */
   1037 
   1038 	anchor  = ump->anchors[0];
   1039 	anchor2 = ump->anchors[1];
   1040 	assert(anchor);
   1041 
   1042 	if (anchor2) {
   1043 		size = sizeof(struct extent_ad);
   1044 		if (memcmp(&anchor->main_vds_ex, &anchor2->main_vds_ex, size))
   1045 			anchor = anchor2;
   1046 		/* reserve is specified to be a literal copy of main */
   1047 	}
   1048 
   1049 	main_loc    = udf_rw32(anchor->main_vds_ex.loc);
   1050 	main_len    = udf_rw32(anchor->main_vds_ex.len);
   1051 
   1052 	reserve_loc = udf_rw32(anchor->reserve_vds_ex.loc);
   1053 	reserve_len = udf_rw32(anchor->reserve_vds_ex.len);
   1054 
   1055 	error = udf_read_vds_extent(ump, main_loc, main_len);
   1056 	if (error) {
   1057 		printf("UDF mount: reading in reserve VDS extent\n");
   1058 		error = udf_read_vds_extent(ump, reserve_loc, reserve_len);
   1059 	}
   1060 
   1061 	return error;
   1062 }
   1063 
   1064 /* --------------------------------------------------------------------- */
   1065 
   1066 /*
   1067  * Read in the logical volume integrity sequence pointed to by our logical
   1068  * volume descriptor. Its a sequence that can be extended using fields in the
   1069  * integrity descriptor itself. On sequential media only one is found, on
   1070  * rewritable media a sequence of descriptors can be found as a form of
   1071  * history keeping and on non sequential write-once media the chain is vital
   1072  * to allow more and more descriptors to be written. The last descriptor
   1073  * written in an extent needs to claim space for a new extent.
   1074  */
   1075 
   1076 static int
   1077 udf_retrieve_lvint(struct udf_mount *ump)
   1078 {
   1079 	union dscrptr *dscr;
   1080 	struct logvol_int_desc *lvint;
   1081 	struct udf_lvintq *trace;
   1082 	uint32_t lb_size, lbnum, len;
   1083 	int dscr_type, error, trace_len;
   1084 
   1085 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   1086 	len     = udf_rw32(ump->logical_vol->integrity_seq_loc.len);
   1087 	lbnum   = udf_rw32(ump->logical_vol->integrity_seq_loc.loc);
   1088 
   1089 	/* clean trace */
   1090 	memset(ump->lvint_trace, 0,
   1091 	    UDF_LVDINT_SEGMENTS * sizeof(struct udf_lvintq));
   1092 
   1093 	trace_len    = 0;
   1094 	trace        = ump->lvint_trace;
   1095 	trace->start = lbnum;
   1096 	trace->end   = lbnum + len/lb_size;
   1097 	trace->pos   = 0;
   1098 	trace->wpos  = 0;
   1099 
   1100 	lvint = NULL;
   1101 	dscr  = NULL;
   1102 	error = 0;
   1103 	while (len) {
   1104 		trace->pos  = lbnum - trace->start;
   1105 		trace->wpos = trace->pos + 1;
   1106 
   1107 		/* read in our integrity descriptor */
   1108 		error = udf_read_phys_dscr(ump, lbnum, M_UDFVOLD, &dscr);
   1109 		if (!error) {
   1110 			if (dscr == NULL) {
   1111 				trace->wpos = trace->pos;
   1112 				break;		/* empty terminates */
   1113 			}
   1114 			dscr_type = udf_rw16(dscr->tag.id);
   1115 			if (dscr_type == TAGID_TERM) {
   1116 				trace->wpos = trace->pos;
   1117 				break;		/* clean terminator */
   1118 			}
   1119 			if (dscr_type != TAGID_LOGVOL_INTEGRITY) {
   1120 				/* fatal... corrupt disc */
   1121 				error = ENOENT;
   1122 				break;
   1123 			}
   1124 			if (lvint)
   1125 				free(lvint, M_UDFVOLD);
   1126 			lvint = &dscr->lvid;
   1127 			dscr = NULL;
   1128 		} /* else hope for the best... maybe the next is ok */
   1129 
   1130 		DPRINTFIF(VOLUMES, lvint, ("logvol integrity read, state %s\n",
   1131 		    udf_rw32(lvint->integrity_type) ? "CLOSED" : "OPEN"));
   1132 
   1133 		/* proceed sequential */
   1134 		lbnum += 1;
   1135 		len    -= lb_size;
   1136 
   1137 		/* are we linking to a new piece? */
   1138 		if (dscr && lvint->next_extent.len) {
   1139 			len    = udf_rw32(lvint->next_extent.len);
   1140 			lbnum = udf_rw32(lvint->next_extent.loc);
   1141 
   1142 			if (trace_len >= UDF_LVDINT_SEGMENTS-1) {
   1143 				/* IEK! segment link full... */
   1144 				DPRINTF(VOLUMES, ("lvdint segments full\n"));
   1145 				error = EINVAL;
   1146 			} else {
   1147 				trace++;
   1148 				trace_len++;
   1149 
   1150 				trace->start = lbnum;
   1151 				trace->end   = lbnum + len/lb_size;
   1152 				trace->pos   = 0;
   1153 				trace->wpos  = 0;
   1154 			}
   1155 		}
   1156 	}
   1157 
   1158 	/* clean up the mess, esp. when there is an error */
   1159 	if (dscr)
   1160 		free(dscr, M_UDFVOLD);
   1161 
   1162 	if (error && lvint) {
   1163 		free(lvint, M_UDFVOLD);
   1164 		lvint = NULL;
   1165 	}
   1166 
   1167 	if (!lvint)
   1168 		error = ENOENT;
   1169 
   1170 	ump->logvol_integrity = lvint;
   1171 	return error;
   1172 }
   1173 
   1174 
   1175 static int
   1176 udf_loose_lvint_history(struct udf_mount *ump)
   1177 {
   1178 	union dscrptr **bufs, *dscr, *last_dscr;
   1179 	struct udf_lvintq *trace, *in_trace, *out_trace;
   1180 	struct logvol_int_desc *lvint;
   1181 	uint32_t in_ext, in_pos, in_len;
   1182 	uint32_t out_ext, out_wpos, out_len;
   1183 	uint32_t lb_size, packet_size, lb_num;
   1184 	uint32_t len, start;
   1185 	int ext, minext, extlen, cnt, cpy_len, dscr_type;
   1186 	int losing;
   1187 	int error;
   1188 
   1189 	DPRINTF(VOLUMES, ("need to lose some lvint history\n"));
   1190 
   1191 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   1192 	packet_size = ump->data_track.packet_size;	/* XXX data track */
   1193 
   1194 	/* search smallest extent */
   1195 	trace = &ump->lvint_trace[0];
   1196 	minext = trace->end - trace->start;
   1197 	for (ext = 1; ext < UDF_LVDINT_SEGMENTS; ext++) {
   1198 		trace = &ump->lvint_trace[ext];
   1199 		extlen = trace->end - trace->start;
   1200 		if (extlen == 0)
   1201 			break;
   1202 		minext = MIN(minext, extlen);
   1203 	}
   1204 	losing = MIN(minext, UDF_LVINT_LOSSAGE);
   1205 	/* no sense wiping all */
   1206 	if (losing == minext)
   1207 		losing--;
   1208 
   1209 	DPRINTF(VOLUMES, ("\tlosing %d entries\n", losing));
   1210 
   1211 	/* get buffer for pieces */
   1212 	bufs = malloc(UDF_LVDINT_SEGMENTS * sizeof(void *), M_TEMP, M_WAITOK);
   1213 
   1214 	in_ext    = 0;
   1215 	in_pos    = losing;
   1216 	in_trace  = &ump->lvint_trace[in_ext];
   1217 	in_len    = in_trace->end - in_trace->start;
   1218 	out_ext   = 0;
   1219 	out_wpos  = 0;
   1220 	out_trace = &ump->lvint_trace[out_ext];
   1221 	out_len   = out_trace->end - out_trace->start;
   1222 
   1223 	last_dscr = NULL;
   1224 	for(;;) {
   1225 		out_trace->pos  = out_wpos;
   1226 		out_trace->wpos = out_trace->pos;
   1227 		if (in_pos >= in_len) {
   1228 			in_ext++;
   1229 			in_pos = 0;
   1230 			in_trace = &ump->lvint_trace[in_ext];
   1231 			in_len   = in_trace->end - in_trace->start;
   1232 		}
   1233 		if (out_wpos >= out_len) {
   1234 			out_ext++;
   1235 			out_wpos = 0;
   1236 			out_trace = &ump->lvint_trace[out_ext];
   1237 			out_len   = out_trace->end - out_trace->start;
   1238 		}
   1239 		/* copy overlap contents */
   1240 		cpy_len = MIN(in_len - in_pos, out_len - out_wpos);
   1241 		cpy_len = MIN(cpy_len, in_len - in_trace->pos);
   1242 		if (cpy_len == 0)
   1243 			break;
   1244 
   1245 		/* copy */
   1246 		DPRINTF(VOLUMES, ("\treading %d lvid descriptors\n", cpy_len));
   1247 		for (cnt = 0; cnt < cpy_len; cnt++) {
   1248 			/* read in our integrity descriptor */
   1249 			lb_num = in_trace->start + in_pos + cnt;
   1250 			error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD,
   1251 				&dscr);
   1252 			if (error) {
   1253 				/* copy last one */
   1254 				dscr = last_dscr;
   1255 			}
   1256 			bufs[cnt] = dscr;
   1257 			if (!error) {
   1258 				if (dscr == NULL) {
   1259 					out_trace->pos  = out_wpos + cnt;
   1260 					out_trace->wpos = out_trace->pos;
   1261 					break;		/* empty terminates */
   1262 				}
   1263 				dscr_type = udf_rw16(dscr->tag.id);
   1264 				if (dscr_type == TAGID_TERM) {
   1265 					out_trace->pos  = out_wpos + cnt;
   1266 					out_trace->wpos = out_trace->pos;
   1267 					break;		/* clean terminator */
   1268 				}
   1269 				if (dscr_type != TAGID_LOGVOL_INTEGRITY) {
   1270 					panic(  "UDF integrity sequence "
   1271 						"corrupted while mounted!\n");
   1272 				}
   1273 				last_dscr = dscr;
   1274 			}
   1275 		}
   1276 
   1277 		/* patch up if first entry was on error */
   1278 		if (bufs[0] == NULL) {
   1279 			for (cnt = 0; cnt < cpy_len; cnt++)
   1280 				if (bufs[cnt] != NULL)
   1281 					break;
   1282 			last_dscr = bufs[cnt];
   1283 			for (; cnt > 0; cnt--) {
   1284 				bufs[cnt] = last_dscr;
   1285 			}
   1286 		}
   1287 
   1288 		/* glue + write out */
   1289 		DPRINTF(VOLUMES, ("\twriting %d lvid descriptors\n", cpy_len));
   1290 		for (cnt = 0; cnt < cpy_len; cnt++) {
   1291 			lb_num = out_trace->start + out_wpos + cnt;
   1292 			lvint  = &bufs[cnt]->lvid;
   1293 
   1294 			/* set continuation */
   1295 			len = 0;
   1296 			start = 0;
   1297 			if (out_wpos + cnt == out_len) {
   1298 				/* get continuation */
   1299 				trace = &ump->lvint_trace[out_ext+1];
   1300 				len   = trace->end - trace->start;
   1301 				start = trace->start;
   1302 			}
   1303 			lvint->next_extent.len = udf_rw32(len);
   1304 			lvint->next_extent.loc = udf_rw32(start);
   1305 
   1306 			lb_num = trace->start + trace->wpos;
   1307 			error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR,
   1308 				bufs[cnt], lb_num, lb_num);
   1309 			DPRINTFIF(VOLUMES, error,
   1310 				("error writing lvint lb_num\n"));
   1311 		}
   1312 
   1313 		/* free non repeating descriptors */
   1314 		last_dscr = NULL;
   1315 		for (cnt = 0; cnt < cpy_len; cnt++) {
   1316 			if (bufs[cnt] != last_dscr)
   1317 				free(bufs[cnt], M_UDFVOLD);
   1318 			last_dscr = bufs[cnt];
   1319 		}
   1320 
   1321 		/* advance */
   1322 		in_pos   += cpy_len;
   1323 		out_wpos += cpy_len;
   1324 	}
   1325 
   1326 	free(bufs, M_TEMP);
   1327 
   1328 	return 0;
   1329 }
   1330 
   1331 
   1332 static int
   1333 udf_writeout_lvint(struct udf_mount *ump, int lvflag)
   1334 {
   1335 	struct udf_lvintq *trace;
   1336 	struct timeval  now_v;
   1337 	struct timespec now_s;
   1338 	uint32_t sector;
   1339 	int logvol_integrity;
   1340 	int space, error;
   1341 
   1342 	DPRINTF(VOLUMES, ("writing out logvol integrity descriptor\n"));
   1343 
   1344 again:
   1345 	/* get free space in last chunk */
   1346 	trace = ump->lvint_trace;
   1347 	while (trace->wpos > (trace->end - trace->start)) {
   1348 		DPRINTF(VOLUMES, ("skip : start = %d, end = %d, pos = %d, "
   1349 				  "wpos = %d\n", trace->start, trace->end,
   1350 				  trace->pos, trace->wpos));
   1351 		trace++;
   1352 	}
   1353 
   1354 	/* check if there is space to append */
   1355 	space = (trace->end - trace->start) - trace->wpos;
   1356 	DPRINTF(VOLUMES, ("write start = %d, end = %d, pos = %d, wpos = %d, "
   1357 			  "space = %d\n", trace->start, trace->end, trace->pos,
   1358 			  trace->wpos, space));
   1359 
   1360 	/* get state */
   1361 	logvol_integrity = udf_rw32(ump->logvol_integrity->integrity_type);
   1362 	if (logvol_integrity == UDF_INTEGRITY_CLOSED) {
   1363 		if ((space < 3) && (lvflag & UDF_APPENDONLY_LVINT)) {
   1364 			/* don't allow this logvol to be opened */
   1365 			/* TODO extent LVINT space if possible */
   1366 			return EROFS;
   1367 		}
   1368 	}
   1369 
   1370 	if (space < 1) {
   1371 		if (lvflag & UDF_APPENDONLY_LVINT)
   1372 			return EROFS;
   1373 		/* loose history by re-writing extents */
   1374 		error = udf_loose_lvint_history(ump);
   1375 		if (error)
   1376 			return error;
   1377 		goto again;
   1378 	}
   1379 
   1380 	/* update our integrity descriptor to identify us and timestamp it */
   1381 	DPRINTF(VOLUMES, ("updating integrity descriptor\n"));
   1382 	microtime(&now_v);
   1383 	TIMEVAL_TO_TIMESPEC(&now_v, &now_s);
   1384 	udf_timespec_to_timestamp(&now_s, &ump->logvol_integrity->time);
   1385 	udf_set_regid(&ump->logvol_info->impl_id, IMPL_NAME);
   1386 	udf_add_impl_regid(ump, &ump->logvol_info->impl_id);
   1387 
   1388 	/* writeout integrity descriptor */
   1389 	sector = trace->start + trace->wpos;
   1390 	error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR,
   1391 			(union dscrptr *) ump->logvol_integrity,
   1392 			sector, sector);
   1393 	DPRINTF(VOLUMES, ("writeout lvint : error = %d\n", error));
   1394 	if (error)
   1395 		return error;
   1396 
   1397 	/* advance write position */
   1398 	trace->wpos++; space--;
   1399 	if (space >= 1) {
   1400 		/* append terminator */
   1401 		sector = trace->start + trace->wpos;
   1402 		error = udf_write_terminator(ump, sector);
   1403 
   1404 		DPRINTF(VOLUMES, ("write terminator : error = %d\n", error));
   1405 	}
   1406 
   1407 	space = (trace->end - trace->start) - trace->wpos;
   1408 	DPRINTF(VOLUMES, ("write start = %d, end = %d, pos = %d, wpos = %d, "
   1409 		"space = %d\n", trace->start, trace->end, trace->pos,
   1410 		trace->wpos, space));
   1411 	DPRINTF(VOLUMES, ("finished writing out logvol integrity descriptor "
   1412 		"successfull\n"));
   1413 
   1414 	return error;
   1415 }
   1416 
   1417 /* --------------------------------------------------------------------- */
   1418 
   1419 static int
   1420 udf_read_physical_partition_spacetables(struct udf_mount *ump)
   1421 {
   1422 	union dscrptr        *dscr;
   1423 	/* struct udf_args *args = &ump->mount_args; */
   1424 	struct part_desc     *partd;
   1425 	struct part_hdr_desc *parthdr;
   1426 	struct udf_bitmap    *bitmap;
   1427 	uint32_t phys_part;
   1428 	uint32_t lb_num, len;
   1429 	int error, dscr_type;
   1430 
   1431 	/* unallocated space map */
   1432 	for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) {
   1433 		partd = ump->partitions[phys_part];
   1434 		if (partd == NULL)
   1435 			continue;
   1436 		parthdr = &partd->_impl_use.part_hdr;
   1437 
   1438 		lb_num  = udf_rw32(partd->start_loc);
   1439 		lb_num += udf_rw32(parthdr->unalloc_space_bitmap.lb_num);
   1440 		len     = udf_rw32(parthdr->unalloc_space_bitmap.len);
   1441 		if (len == 0)
   1442 			continue;
   1443 
   1444 		DPRINTF(VOLUMES, ("Read unalloc. space bitmap %d\n", lb_num));
   1445 		error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD, &dscr);
   1446 		if (!error && dscr) {
   1447 			/* analyse */
   1448 			dscr_type = udf_rw16(dscr->tag.id);
   1449 			if (dscr_type == TAGID_SPACE_BITMAP) {
   1450 				DPRINTF(VOLUMES, ("Accepting space bitmap\n"));
   1451 				ump->part_unalloc_dscr[phys_part] = &dscr->sbd;
   1452 
   1453 				/* fill in ump->part_unalloc_bits */
   1454 				bitmap = &ump->part_unalloc_bits[phys_part];
   1455 				bitmap->blob  = (uint8_t *) dscr;
   1456 				bitmap->bits  = dscr->sbd.data;
   1457 				bitmap->max_offset = udf_rw32(dscr->sbd.num_bits);
   1458 				bitmap->pages = NULL;	/* TODO */
   1459 				bitmap->data_pos     = 0;
   1460 				bitmap->metadata_pos = 0;
   1461 			} else {
   1462 				free(dscr, M_UDFVOLD);
   1463 
   1464 				printf( "UDF mount: error reading unallocated "
   1465 					"space bitmap\n");
   1466 				return EROFS;
   1467 			}
   1468 		} else {
   1469 			/* blank not allowed */
   1470 			printf("UDF mount: blank unallocated space bitmap\n");
   1471 			return EROFS;
   1472 		}
   1473 	}
   1474 
   1475 	/* unallocated space table (not supported) */
   1476 	for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) {
   1477 		partd = ump->partitions[phys_part];
   1478 		if (partd == NULL)
   1479 			continue;
   1480 		parthdr = &partd->_impl_use.part_hdr;
   1481 
   1482 		len     = udf_rw32(parthdr->unalloc_space_table.len);
   1483 		if (len) {
   1484 			printf("UDF mount: space tables not supported\n");
   1485 			return EROFS;
   1486 		}
   1487 	}
   1488 
   1489 	/* freed space map */
   1490 	for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) {
   1491 		partd = ump->partitions[phys_part];
   1492 		if (partd == NULL)
   1493 			continue;
   1494 		parthdr = &partd->_impl_use.part_hdr;
   1495 
   1496 		/* freed space map */
   1497 		lb_num  = udf_rw32(partd->start_loc);
   1498 		lb_num += udf_rw32(parthdr->freed_space_bitmap.lb_num);
   1499 		len     = udf_rw32(parthdr->freed_space_bitmap.len);
   1500 		if (len == 0)
   1501 			continue;
   1502 
   1503 		DPRINTF(VOLUMES, ("Read unalloc. space bitmap %d\n", lb_num));
   1504 		error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD, &dscr);
   1505 		if (!error && dscr) {
   1506 			/* analyse */
   1507 			dscr_type = udf_rw16(dscr->tag.id);
   1508 			if (dscr_type == TAGID_SPACE_BITMAP) {
   1509 				DPRINTF(VOLUMES, ("Accepting space bitmap\n"));
   1510 				ump->part_freed_dscr[phys_part] = &dscr->sbd;
   1511 
   1512 				/* fill in ump->part_freed_bits */
   1513 				bitmap = &ump->part_unalloc_bits[phys_part];
   1514 				bitmap->blob  = (uint8_t *) dscr;
   1515 				bitmap->bits  = dscr->sbd.data;
   1516 				bitmap->max_offset = udf_rw32(dscr->sbd.num_bits);
   1517 				bitmap->pages = NULL;	/* TODO */
   1518 				bitmap->data_pos     = 0;
   1519 				bitmap->metadata_pos = 0;
   1520 			} else {
   1521 				free(dscr, M_UDFVOLD);
   1522 
   1523 				printf( "UDF mount: error reading freed  "
   1524 					"space bitmap\n");
   1525 				return EROFS;
   1526 			}
   1527 		} else {
   1528 			/* blank not allowed */
   1529 			printf("UDF mount: blank freed space bitmap\n");
   1530 			return EROFS;
   1531 		}
   1532 	}
   1533 
   1534 	/* freed space table (not supported) */
   1535 	for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) {
   1536 		partd = ump->partitions[phys_part];
   1537 		if (partd == NULL)
   1538 			continue;
   1539 		parthdr = &partd->_impl_use.part_hdr;
   1540 
   1541 		len     = udf_rw32(parthdr->freed_space_table.len);
   1542 		if (len) {
   1543 			printf("UDF mount: space tables not supported\n");
   1544 			return EROFS;
   1545 		}
   1546 	}
   1547 
   1548 	return 0;
   1549 }
   1550 
   1551 
   1552 /* TODO implement async writeout */
   1553 int
   1554 udf_write_physical_partition_spacetables(struct udf_mount *ump, int waitfor)
   1555 {
   1556 	union dscrptr        *dscr;
   1557 	/* struct udf_args *args = &ump->mount_args; */
   1558 	struct part_desc     *partd;
   1559 	struct part_hdr_desc *parthdr;
   1560 	uint32_t phys_part;
   1561 	uint32_t lb_num, len, ptov;
   1562 	int error_all, error;
   1563 
   1564 	error_all = 0;
   1565 	/* unallocated space map */
   1566 	for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) {
   1567 		partd = ump->partitions[phys_part];
   1568 		if (partd == NULL)
   1569 			continue;
   1570 		parthdr = &partd->_impl_use.part_hdr;
   1571 
   1572 		ptov   = udf_rw32(partd->start_loc);
   1573 		lb_num = udf_rw32(parthdr->unalloc_space_bitmap.lb_num);
   1574 		len    = udf_rw32(parthdr->unalloc_space_bitmap.len);
   1575 		if (len == 0)
   1576 			continue;
   1577 
   1578 		DPRINTF(VOLUMES, ("Write unalloc. space bitmap %d\n",
   1579 			lb_num + ptov));
   1580 		dscr = (union dscrptr *) ump->part_unalloc_dscr[phys_part];
   1581 		error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR,
   1582 				(union dscrptr *) dscr,
   1583 				ptov + lb_num, lb_num);
   1584 		if (error) {
   1585 			DPRINTF(VOLUMES, ("\tfailed!! (error %d)\n", error));
   1586 			error_all = error;
   1587 		}
   1588 	}
   1589 
   1590 	/* freed space map */
   1591 	for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) {
   1592 		partd = ump->partitions[phys_part];
   1593 		if (partd == NULL)
   1594 			continue;
   1595 		parthdr = &partd->_impl_use.part_hdr;
   1596 
   1597 		/* freed space map */
   1598 		ptov   = udf_rw32(partd->start_loc);
   1599 		lb_num = udf_rw32(parthdr->freed_space_bitmap.lb_num);
   1600 		len    = udf_rw32(parthdr->freed_space_bitmap.len);
   1601 		if (len == 0)
   1602 			continue;
   1603 
   1604 		DPRINTF(VOLUMES, ("Write freed space bitmap %d\n",
   1605 			lb_num + ptov));
   1606 		dscr = (union dscrptr *) ump->part_freed_dscr[phys_part];
   1607 		error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR,
   1608 				(union dscrptr *) dscr,
   1609 				ptov + lb_num, lb_num);
   1610 		if (error) {
   1611 			DPRINTF(VOLUMES, ("\tfailed!! (error %d)\n", error));
   1612 			error_all = error;
   1613 		}
   1614 	}
   1615 
   1616 	return error_all;
   1617 }
   1618 
   1619 
   1620 static int
   1621 udf_read_metadata_partition_spacetable(struct udf_mount *ump)
   1622 {
   1623 	struct udf_node	     *bitmap_node;
   1624 	union dscrptr        *dscr;
   1625 	struct udf_bitmap    *bitmap;
   1626 	uint64_t inflen;
   1627 	int error, dscr_type;
   1628 
   1629 	bitmap_node = ump->metadatabitmap_node;
   1630 
   1631 	/* only read in when metadata bitmap node is read in */
   1632 	if (bitmap_node == NULL)
   1633 		return 0;
   1634 
   1635 	if (bitmap_node->fe) {
   1636 		inflen = udf_rw64(bitmap_node->fe->inf_len);
   1637 	} else {
   1638 		KASSERT(bitmap_node->efe);
   1639 		inflen = udf_rw64(bitmap_node->efe->inf_len);
   1640 	}
   1641 
   1642 	DPRINTF(VOLUMES, ("Reading metadata space bitmap for "
   1643 		"%"PRIu64" bytes\n", inflen));
   1644 
   1645 	/* allocate space for bitmap */
   1646 	dscr = malloc(inflen, M_UDFVOLD, M_CANFAIL | M_WAITOK);
   1647 	if (!dscr)
   1648 		return ENOMEM;
   1649 
   1650 	/* set vnode type to regular file or we can't read from it! */
   1651 	bitmap_node->vnode->v_type = VREG;
   1652 
   1653 	/* read in complete metadata bitmap file */
   1654 	error = vn_rdwr(UIO_READ, bitmap_node->vnode,
   1655 			dscr,
   1656 			inflen, 0,
   1657 			UIO_SYSSPACE,
   1658 			IO_SYNC | IO_NODELOCKED | IO_ALTSEMANTICS, FSCRED,
   1659 			NULL, NULL);
   1660 	if (error) {
   1661 		DPRINTF(VOLUMES, ("Error reading metadata space bitmap\n"));
   1662 		goto errorout;
   1663 	}
   1664 
   1665 	/* analyse */
   1666 	dscr_type = udf_rw16(dscr->tag.id);
   1667 	if (dscr_type == TAGID_SPACE_BITMAP) {
   1668 		DPRINTF(VOLUMES, ("Accepting metadata space bitmap\n"));
   1669 		ump->metadata_unalloc_dscr = &dscr->sbd;
   1670 
   1671 		/* fill in bitmap bits */
   1672 		bitmap = &ump->metadata_unalloc_bits;
   1673 		bitmap->blob  = (uint8_t *) dscr;
   1674 		bitmap->bits  = dscr->sbd.data;
   1675 		bitmap->max_offset = udf_rw32(dscr->sbd.num_bits);
   1676 		bitmap->pages = NULL;	/* TODO */
   1677 		bitmap->data_pos     = 0;
   1678 		bitmap->metadata_pos = 0;
   1679 	} else {
   1680 		DPRINTF(VOLUMES, ("No valid bitmap found!\n"));
   1681 		goto errorout;
   1682 	}
   1683 
   1684 	return 0;
   1685 
   1686 errorout:
   1687 	free(dscr, M_UDFVOLD);
   1688 	printf( "UDF mount: error reading unallocated "
   1689 		"space bitmap for metadata partition\n");
   1690 	return EROFS;
   1691 }
   1692 
   1693 
   1694 int
   1695 udf_write_metadata_partition_spacetable(struct udf_mount *ump, int waitfor)
   1696 {
   1697 	struct udf_node	     *bitmap_node;
   1698 	union dscrptr        *dscr;
   1699 	uint64_t inflen, new_inflen;
   1700 	int dummy, error;
   1701 
   1702 	bitmap_node = ump->metadatabitmap_node;
   1703 
   1704 	/* only write out when metadata bitmap node is known */
   1705 	if (bitmap_node == NULL)
   1706 		return 0;
   1707 
   1708 	if (bitmap_node->fe) {
   1709 		inflen = udf_rw64(bitmap_node->fe->inf_len);
   1710 	} else {
   1711 		KASSERT(bitmap_node->efe);
   1712 		inflen = udf_rw64(bitmap_node->efe->inf_len);
   1713 	}
   1714 
   1715 	/* reduce length to zero */
   1716 	dscr = (union dscrptr *) ump->metadata_unalloc_dscr;
   1717 	new_inflen = udf_tagsize(dscr, 1);
   1718 
   1719 	DPRINTF(VOLUMES, ("Resize and write out metadata space bitmap from "
   1720 		"%"PRIu64" to %"PRIu64" bytes\n", inflen, new_inflen));
   1721 
   1722 	error = udf_resize_node(bitmap_node, new_inflen, &dummy);
   1723 	if (error)
   1724 		printf("Error resizing metadata space bitmap\n");
   1725 
   1726 	error = vn_rdwr(UIO_WRITE, bitmap_node->vnode,
   1727 			dscr,
   1728 			new_inflen, 0,
   1729 			UIO_SYSSPACE,
   1730 			IO_NODELOCKED | IO_ALTSEMANTICS, FSCRED,
   1731 			NULL, NULL);
   1732 
   1733 	bitmap_node->i_flags |= IN_MODIFIED;
   1734 	vflushbuf(bitmap_node->vnode, 1 /* sync */);
   1735 
   1736 	error = VOP_FSYNC(bitmap_node->vnode,
   1737 			FSCRED, FSYNC_WAIT, 0, 0);
   1738 
   1739 	if (error)
   1740 		printf( "Error writing out metadata partition unalloced "
   1741 			"space bitmap!\n");
   1742 
   1743 	return error;
   1744 }
   1745 
   1746 
   1747 /* --------------------------------------------------------------------- */
   1748 
   1749 /*
   1750  * Checks if ump's vds information is correct and complete
   1751  */
   1752 
   1753 int
   1754 udf_process_vds(struct udf_mount *ump) {
   1755 	union udf_pmap *mapping;
   1756 	/* struct udf_args *args = &ump->mount_args; */
   1757 	struct logvol_int_desc *lvint;
   1758 	struct udf_logvol_info *lvinfo;
   1759 	struct part_desc *part;
   1760 	uint32_t n_pm, mt_l;
   1761 	uint8_t *pmap_pos;
   1762 	char *domain_name, *map_name;
   1763 	const char *check_name;
   1764 	char bits[128];
   1765 	int pmap_stype, pmap_size;
   1766 	int pmap_type, log_part, phys_part, raw_phys_part, maps_on;
   1767 	int n_phys, n_virt, n_spar, n_meta;
   1768 	int len, error;
   1769 
   1770 	if (ump == NULL)
   1771 		return ENOENT;
   1772 
   1773 	/* we need at least an anchor (trivial, but for safety) */
   1774 	if (ump->anchors[0] == NULL)
   1775 		return EINVAL;
   1776 
   1777 	/* we need at least one primary and one logical volume descriptor */
   1778 	if ((ump->primary_vol == NULL) || (ump->logical_vol) == NULL)
   1779 		return EINVAL;
   1780 
   1781 	/* we need at least one partition descriptor */
   1782 	if (ump->partitions[0] == NULL)
   1783 		return EINVAL;
   1784 
   1785 	/* check logical volume sector size verses device sector size */
   1786 	if (udf_rw32(ump->logical_vol->lb_size) != ump->discinfo.sector_size) {
   1787 		printf("UDF mount: format violation, lb_size != sector size\n");
   1788 		return EINVAL;
   1789 	}
   1790 
   1791 	/* check domain name */
   1792 	domain_name = ump->logical_vol->domain_id.id;
   1793 	if (strncmp(domain_name, "*OSTA UDF Compliant", 20)) {
   1794 		printf("mount_udf: disc not OSTA UDF Compliant, aborting\n");
   1795 		return EINVAL;
   1796 	}
   1797 
   1798 	/* retrieve logical volume integrity sequence */
   1799 	error = udf_retrieve_lvint(ump);
   1800 
   1801 	/*
   1802 	 * We need at least one logvol integrity descriptor recorded.  Note
   1803 	 * that its OK to have an open logical volume integrity here. The VAT
   1804 	 * will close/update the integrity.
   1805 	 */
   1806 	if (ump->logvol_integrity == NULL)
   1807 		return EINVAL;
   1808 
   1809 	/* process derived structures */
   1810 	n_pm   = udf_rw32(ump->logical_vol->n_pm);   /* num partmaps         */
   1811 	lvint  = ump->logvol_integrity;
   1812 	lvinfo = (struct udf_logvol_info *) (&lvint->tables[2 * n_pm]);
   1813 	ump->logvol_info = lvinfo;
   1814 
   1815 	/* TODO check udf versions? */
   1816 
   1817 	/*
   1818 	 * check logvol mappings: effective virt->log partmap translation
   1819 	 * check and recording of the mapping results. Saves expensive
   1820 	 * strncmp() in tight places.
   1821 	 */
   1822 	DPRINTF(VOLUMES, ("checking logvol mappings\n"));
   1823 	n_pm = udf_rw32(ump->logical_vol->n_pm);   /* num partmaps         */
   1824 	mt_l = udf_rw32(ump->logical_vol->mt_l);   /* partmaps data length */
   1825 	pmap_pos =  ump->logical_vol->maps;
   1826 
   1827 	if (n_pm > UDF_PMAPS) {
   1828 		printf("UDF mount: too many mappings\n");
   1829 		return EINVAL;
   1830 	}
   1831 
   1832 	/* count types and set partition numbers */
   1833 	ump->data_part = ump->node_part = ump->fids_part = 0;
   1834 	n_phys = n_virt = n_spar = n_meta = 0;
   1835 	for (log_part = 0; log_part < n_pm; log_part++) {
   1836 		mapping = (union udf_pmap *) pmap_pos;
   1837 		pmap_stype = pmap_pos[0];
   1838 		pmap_size  = pmap_pos[1];
   1839 		switch (pmap_stype) {
   1840 		case 1:	/* physical mapping */
   1841 			/* volseq    = udf_rw16(mapping->pm1.vol_seq_num); */
   1842 			raw_phys_part = udf_rw16(mapping->pm1.part_num);
   1843 			pmap_type = UDF_VTOP_TYPE_PHYS;
   1844 			n_phys++;
   1845 			ump->data_part = log_part;
   1846 			ump->node_part = log_part;
   1847 			ump->fids_part = log_part;
   1848 			break;
   1849 		case 2: /* virtual/sparable/meta mapping */
   1850 			map_name  = mapping->pm2.part_id.id;
   1851 			/* volseq  = udf_rw16(mapping->pm2.vol_seq_num); */
   1852 			raw_phys_part = udf_rw16(mapping->pm2.part_num);
   1853 			pmap_type = UDF_VTOP_TYPE_UNKNOWN;
   1854 			len = UDF_REGID_ID_SIZE;
   1855 
   1856 			check_name = "*UDF Virtual Partition";
   1857 			if (strncmp(map_name, check_name, len) == 0) {
   1858 				pmap_type = UDF_VTOP_TYPE_VIRT;
   1859 				n_virt++;
   1860 				ump->node_part = log_part;
   1861 				break;
   1862 			}
   1863 			check_name = "*UDF Sparable Partition";
   1864 			if (strncmp(map_name, check_name, len) == 0) {
   1865 				pmap_type = UDF_VTOP_TYPE_SPARABLE;
   1866 				n_spar++;
   1867 				ump->data_part = log_part;
   1868 				ump->node_part = log_part;
   1869 				ump->fids_part = log_part;
   1870 				break;
   1871 			}
   1872 			check_name = "*UDF Metadata Partition";
   1873 			if (strncmp(map_name, check_name, len) == 0) {
   1874 				pmap_type = UDF_VTOP_TYPE_META;
   1875 				n_meta++;
   1876 				ump->node_part = log_part;
   1877 				ump->fids_part = log_part;
   1878 				break;
   1879 			}
   1880 			break;
   1881 		default:
   1882 			return EINVAL;
   1883 		}
   1884 
   1885 		/*
   1886 		 * BUGALERT: some rogue implementations use random physical
   1887 		 * partion numbers to break other implementations so lookup
   1888 		 * the number.
   1889 		 */
   1890 		for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) {
   1891 			part = ump->partitions[phys_part];
   1892 			if (part == NULL)
   1893 				continue;
   1894 			if (udf_rw16(part->part_num) == raw_phys_part)
   1895 				break;
   1896 		}
   1897 
   1898 		DPRINTF(VOLUMES, ("\t%d -> %d(%d) type %d\n", log_part,
   1899 		    raw_phys_part, phys_part, pmap_type));
   1900 
   1901 		if (phys_part == UDF_PARTITIONS)
   1902 			return EINVAL;
   1903 		if (pmap_type == UDF_VTOP_TYPE_UNKNOWN)
   1904 			return EINVAL;
   1905 
   1906 		ump->vtop   [log_part] = phys_part;
   1907 		ump->vtop_tp[log_part] = pmap_type;
   1908 
   1909 		pmap_pos += pmap_size;
   1910 	}
   1911 	/* not winning the beauty contest */
   1912 	ump->vtop_tp[UDF_VTOP_RAWPART] = UDF_VTOP_TYPE_RAW;
   1913 
   1914 	/* test some basic UDF assertions/requirements */
   1915 	if ((n_virt > 1) || (n_spar > 1) || (n_meta > 1))
   1916 		return EINVAL;
   1917 
   1918 	if (n_virt) {
   1919 		if ((n_phys == 0) || n_spar || n_meta)
   1920 			return EINVAL;
   1921 	}
   1922 	if (n_spar + n_phys == 0)
   1923 		return EINVAL;
   1924 
   1925 	/* select allocation type for each logical partition */
   1926 	for (log_part = 0; log_part < n_pm; log_part++) {
   1927 		maps_on = ump->vtop[log_part];
   1928 		switch (ump->vtop_tp[log_part]) {
   1929 		case UDF_VTOP_TYPE_PHYS :
   1930 			assert(maps_on == log_part);
   1931 			ump->vtop_alloc[log_part] = UDF_ALLOC_SPACEMAP;
   1932 			break;
   1933 		case UDF_VTOP_TYPE_VIRT :
   1934 			ump->vtop_alloc[log_part] = UDF_ALLOC_VAT;
   1935 			ump->vtop_alloc[maps_on]  = UDF_ALLOC_SEQUENTIAL;
   1936 			break;
   1937 		case UDF_VTOP_TYPE_SPARABLE :
   1938 			assert(maps_on == log_part);
   1939 			ump->vtop_alloc[log_part] = UDF_ALLOC_SPACEMAP;
   1940 			break;
   1941 		case UDF_VTOP_TYPE_META :
   1942 			ump->vtop_alloc[log_part] = UDF_ALLOC_METABITMAP;
   1943 			if (ump->discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE) {
   1944 				/* special case for UDF 2.60 */
   1945 				ump->vtop_alloc[log_part] = UDF_ALLOC_METASEQUENTIAL;
   1946 				ump->vtop_alloc[maps_on]  = UDF_ALLOC_SEQUENTIAL;
   1947 			}
   1948 			break;
   1949 		default:
   1950 			panic("bad alloction type in udf's ump->vtop\n");
   1951 		}
   1952 	}
   1953 
   1954 	/* determine logical volume open/closure actions */
   1955 	if (n_virt) {
   1956 		ump->lvopen  = 0;
   1957 		if (ump->discinfo.last_session_state == MMC_STATE_CLOSED)
   1958 			ump->lvopen |= UDF_OPEN_SESSION ;
   1959 		ump->lvclose = UDF_WRITE_VAT;
   1960 		if (ump->mount_args.udfmflags & UDFMNT_CLOSESESSION)
   1961 			ump->lvclose |= UDF_CLOSE_SESSION;
   1962 	} else {
   1963 		/* `normal' rewritable or non sequential media */
   1964 		ump->lvopen  = UDF_WRITE_LVINT;
   1965 		ump->lvclose = UDF_WRITE_LVINT;
   1966 		if ((ump->discinfo.mmc_cur & MMC_CAP_REWRITABLE) == 0)
   1967 			ump->lvopen  |= UDF_APPENDONLY_LVINT;
   1968 	}
   1969 
   1970 	/*
   1971 	 * Determine sheduler error behaviour. For virtual partions, update
   1972 	 * the trackinfo; for sparable partitions replace a whole block on the
   1973 	 * sparable table. Allways requeue.
   1974 	 */
   1975 	ump->lvreadwrite = 0;
   1976 	if (n_virt)
   1977 		ump->lvreadwrite = UDF_UPDATE_TRACKINFO;
   1978 	if (n_spar)
   1979 		ump->lvreadwrite = UDF_REMAP_BLOCK;
   1980 
   1981 	/*
   1982 	 * Select our sheduler
   1983 	 */
   1984 	ump->strategy = &udf_strat_rmw;
   1985 	if (n_virt || (ump->discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE))
   1986 		ump->strategy = &udf_strat_sequential;
   1987 	if ((ump->discinfo.mmc_class == MMC_CLASS_DISC) ||
   1988 		(ump->discinfo.mmc_class == MMC_CLASS_UNKN))
   1989 			ump->strategy = &udf_strat_direct;
   1990 	if (n_spar)
   1991 		ump->strategy = &udf_strat_rmw;
   1992 
   1993 	/* print results */
   1994 	DPRINTF(VOLUMES, ("\tdata partition    %d\n", ump->data_part));
   1995 	DPRINTF(VOLUMES, ("\t\talloc scheme %d\n", ump->vtop_alloc[ump->data_part]));
   1996 	DPRINTF(VOLUMES, ("\tnode partition    %d\n", ump->node_part));
   1997 	DPRINTF(VOLUMES, ("\t\talloc scheme %d\n", ump->vtop_alloc[ump->node_part]));
   1998 	DPRINTF(VOLUMES, ("\tfids partition    %d\n", ump->fids_part));
   1999 	DPRINTF(VOLUMES, ("\t\talloc scheme %d\n", ump->vtop_alloc[ump->fids_part]));
   2000 
   2001 	bitmask_snprintf(ump->lvopen,  UDFLOGVOL_BITS, bits, sizeof(bits));
   2002 	DPRINTF(VOLUMES, ("\tactions on logvol open  %s\n", bits));
   2003 	bitmask_snprintf(ump->lvclose, UDFLOGVOL_BITS, bits, sizeof(bits));
   2004 	DPRINTF(VOLUMES, ("\tactions on logvol close %s\n", bits));
   2005 	bitmask_snprintf(ump->lvreadwrite, UDFONERROR_BITS, bits, sizeof(bits));
   2006 	DPRINTF(VOLUMES, ("\tactions on logvol errors %s\n", bits));
   2007 
   2008 	DPRINTF(VOLUMES, ("\tselected sheduler `%s`\n",
   2009 		(ump->strategy == &udf_strat_direct) ? "Direct" :
   2010 		(ump->strategy == &udf_strat_sequential) ? "Sequential" :
   2011 		(ump->strategy == &udf_strat_rmw) ? "RMW" : "UNKNOWN!"));
   2012 
   2013 	/* signal its OK for now */
   2014 	return 0;
   2015 }
   2016 
   2017 /* --------------------------------------------------------------------- */
   2018 
   2019 /*
   2020  * Update logical volume name in all structures that keep a record of it. We
   2021  * use memmove since each of them might be specified as a source.
   2022  *
   2023  * Note that it doesn't update the VAT structure!
   2024  */
   2025 
   2026 static void
   2027 udf_update_logvolname(struct udf_mount *ump, char *logvol_id)
   2028 {
   2029 	struct logvol_desc     *lvd = NULL;
   2030 	struct fileset_desc    *fsd = NULL;
   2031 	struct udf_lv_info     *lvi = NULL;
   2032 
   2033 	DPRINTF(VOLUMES, ("Updating logical volume name\n"));
   2034 	lvd = ump->logical_vol;
   2035 	fsd = ump->fileset_desc;
   2036 	if (ump->implementation)
   2037 		lvi = &ump->implementation->_impl_use.lv_info;
   2038 
   2039 	/* logvol's id might be specified as origional so use memmove here */
   2040 	memmove(lvd->logvol_id, logvol_id, 128);
   2041 	if (fsd)
   2042 		memmove(fsd->logvol_id, logvol_id, 128);
   2043 	if (lvi)
   2044 		memmove(lvi->logvol_id, logvol_id, 128);
   2045 }
   2046 
   2047 /* --------------------------------------------------------------------- */
   2048 
   2049 void
   2050 udf_inittag(struct udf_mount *ump, struct desc_tag *tag, int tagid,
   2051 	uint32_t sector)
   2052 {
   2053 	assert(ump->logical_vol);
   2054 
   2055 	tag->id 		= udf_rw16(tagid);
   2056 	tag->descriptor_ver	= ump->logical_vol->tag.descriptor_ver;
   2057 	tag->cksum		= 0;
   2058 	tag->reserved		= 0;
   2059 	tag->serial_num		= ump->logical_vol->tag.serial_num;
   2060 	tag->tag_loc            = udf_rw32(sector);
   2061 }
   2062 
   2063 
   2064 uint64_t
   2065 udf_advance_uniqueid(struct udf_mount *ump)
   2066 {
   2067 	uint64_t unique_id;
   2068 
   2069 	mutex_enter(&ump->logvol_mutex);
   2070 	unique_id = udf_rw64(ump->logvol_integrity->lvint_next_unique_id);
   2071 	if (unique_id < 0x10)
   2072 		unique_id = 0x10;
   2073 	ump->logvol_integrity->lvint_next_unique_id = udf_rw64(unique_id + 1);
   2074 	mutex_exit(&ump->logvol_mutex);
   2075 
   2076 	return unique_id;
   2077 }
   2078 
   2079 
   2080 static void
   2081 udf_adjust_filecount(struct udf_node *udf_node, int sign)
   2082 {
   2083 	struct udf_mount *ump = udf_node->ump;
   2084 	uint32_t num_dirs, num_files;
   2085 	int udf_file_type;
   2086 
   2087 	/* get file type */
   2088 	if (udf_node->fe) {
   2089 		udf_file_type = udf_node->fe->icbtag.file_type;
   2090 	} else {
   2091 		udf_file_type = udf_node->efe->icbtag.file_type;
   2092 	}
   2093 
   2094 	/* adjust file count */
   2095 	mutex_enter(&ump->allocate_mutex);
   2096 	if (udf_file_type == UDF_ICB_FILETYPE_DIRECTORY) {
   2097 		num_dirs = udf_rw32(ump->logvol_info->num_directories);
   2098 		ump->logvol_info->num_directories =
   2099 			udf_rw32((num_dirs + sign));
   2100 	} else {
   2101 		num_files = udf_rw32(ump->logvol_info->num_files);
   2102 		ump->logvol_info->num_files =
   2103 			udf_rw32((num_files + sign));
   2104 	}
   2105 	mutex_exit(&ump->allocate_mutex);
   2106 }
   2107 
   2108 
   2109 void
   2110 udf_osta_charset(struct charspec *charspec)
   2111 {
   2112 	bzero(charspec, sizeof(struct charspec));
   2113 	charspec->type = 0;
   2114 	strcpy((char *) charspec->inf, "OSTA Compressed Unicode");
   2115 }
   2116 
   2117 
   2118 /* first call udf_set_regid and then the suffix */
   2119 void
   2120 udf_set_regid(struct regid *regid, char const *name)
   2121 {
   2122 	bzero(regid, sizeof(struct regid));
   2123 	regid->flags    = 0;		/* not dirty and not protected */
   2124 	strcpy((char *) regid->id, name);
   2125 }
   2126 
   2127 
   2128 void
   2129 udf_add_domain_regid(struct udf_mount *ump, struct regid *regid)
   2130 {
   2131 	uint16_t *ver;
   2132 
   2133 	ver  = (uint16_t *) regid->id_suffix;
   2134 	*ver = ump->logvol_info->min_udf_readver;
   2135 }
   2136 
   2137 
   2138 void
   2139 udf_add_udf_regid(struct udf_mount *ump, struct regid *regid)
   2140 {
   2141 	uint16_t *ver;
   2142 
   2143 	ver  = (uint16_t *) regid->id_suffix;
   2144 	*ver = ump->logvol_info->min_udf_readver;
   2145 
   2146 	regid->id_suffix[2] = 4;	/* unix */
   2147 	regid->id_suffix[3] = 8;	/* NetBSD */
   2148 }
   2149 
   2150 
   2151 void
   2152 udf_add_impl_regid(struct udf_mount *ump, struct regid *regid)
   2153 {
   2154 	regid->id_suffix[0] = 4;	/* unix */
   2155 	regid->id_suffix[1] = 8;	/* NetBSD */
   2156 }
   2157 
   2158 
   2159 void
   2160 udf_add_app_regid(struct udf_mount *ump, struct regid *regid)
   2161 {
   2162 	regid->id_suffix[0] = APP_VERSION_MAIN;
   2163 	regid->id_suffix[1] = APP_VERSION_SUB;
   2164 }
   2165 
   2166 static int
   2167 udf_create_parentfid(struct udf_mount *ump, struct fileid_desc *fid,
   2168 	struct long_ad *parent, uint64_t unique_id)
   2169 {
   2170 	/* the size of an empty FID is 38 but needs to be a multiple of 4 */
   2171 	int fidsize = 40;
   2172 
   2173 	udf_inittag(ump, &fid->tag, TAGID_FID, udf_rw32(parent->loc.lb_num));
   2174 	fid->file_version_num = udf_rw16(1);	/* UDF 2.3.4.1 */
   2175 	fid->file_char = UDF_FILE_CHAR_DIR | UDF_FILE_CHAR_PAR;
   2176 	fid->icb = *parent;
   2177 	fid->icb.longad_uniqueid = udf_rw32((uint32_t) unique_id);
   2178 	fid->tag.desc_crc_len = fidsize - UDF_DESC_TAG_LENGTH;
   2179 	(void) udf_validate_tag_and_crc_sums((union dscrptr *) fid);
   2180 
   2181 	return fidsize;
   2182 }
   2183 
   2184 /* --------------------------------------------------------------------- */
   2185 
   2186 /*
   2187  * Extended attribute support. UDF knows of 3 places for extended attributes:
   2188  *
   2189  * (a) inside the file's (e)fe in the length of the extended attribute area
   2190  * before the allocation descriptors/filedata
   2191  *
   2192  * (b) in a file referenced by (e)fe->ext_attr_icb and
   2193  *
   2194  * (c) in the e(fe)'s associated stream directory that can hold various
   2195  * sub-files. In the stream directory a few fixed named subfiles are reserved
   2196  * for NT/Unix ACL's and OS/2 attributes.
   2197  *
   2198  * NOTE: Extended attributes are read randomly but allways written
   2199  * *atomicaly*. For ACL's this interface is propably different but not known
   2200  * to me yet.
   2201  *
   2202  * Order of extended attributes in a space :
   2203  *   ECMA 167 EAs
   2204  *   Non block aligned Implementation Use EAs
   2205  *   Block aligned Implementation Use EAs
   2206  *   Application Use EAs
   2207  */
   2208 
   2209 static int
   2210 udf_impl_extattr_check(struct impl_extattr_entry *implext)
   2211 {
   2212 	uint16_t   *spos;
   2213 
   2214 	if (strncmp(implext->imp_id.id, "*UDF", 4) == 0) {
   2215 		/* checksum valid? */
   2216 		DPRINTF(EXTATTR, ("checking UDF impl. attr checksum\n"));
   2217 		spos = (uint16_t *) implext->data;
   2218 		if (udf_rw16(*spos) != udf_ea_cksum((uint8_t *) implext))
   2219 			return EINVAL;
   2220 	}
   2221 	return 0;
   2222 }
   2223 
   2224 static void
   2225 udf_calc_impl_extattr_checksum(struct impl_extattr_entry *implext)
   2226 {
   2227 	uint16_t   *spos;
   2228 
   2229 	if (strncmp(implext->imp_id.id, "*UDF", 4) == 0) {
   2230 		/* set checksum */
   2231 		spos = (uint16_t *) implext->data;
   2232 		*spos = udf_rw16(udf_ea_cksum((uint8_t *) implext));
   2233 	}
   2234 }
   2235 
   2236 
   2237 int
   2238 udf_extattr_search_intern(struct udf_node *node,
   2239 	uint32_t sattr, char const *sattrname,
   2240 	uint32_t *offsetp, uint32_t *lengthp)
   2241 {
   2242 	struct extattrhdr_desc    *eahdr;
   2243 	struct extattr_entry      *attrhdr;
   2244 	struct impl_extattr_entry *implext;
   2245 	uint32_t    offset, a_l, sector_size;
   2246 	 int32_t    l_ea;
   2247 	uint8_t    *pos;
   2248 	int         error;
   2249 
   2250 	/* get mountpoint */
   2251 	sector_size = node->ump->discinfo.sector_size;
   2252 
   2253 	/* get information from fe/efe */
   2254 	if (node->fe) {
   2255 		l_ea  = udf_rw32(node->fe->l_ea);
   2256 		eahdr = (struct extattrhdr_desc *) node->fe->data;
   2257 	} else {
   2258 		assert(node->efe);
   2259 		l_ea  = udf_rw32(node->efe->l_ea);
   2260 		eahdr = (struct extattrhdr_desc *) node->efe->data;
   2261 	}
   2262 
   2263 	/* something recorded here? */
   2264 	if (l_ea == 0)
   2265 		return ENOENT;
   2266 
   2267 	/* check extended attribute tag; what to do if it fails? */
   2268 	error = udf_check_tag(eahdr);
   2269 	if (error)
   2270 		return EINVAL;
   2271 	if (udf_rw16(eahdr->tag.id) != TAGID_EXTATTR_HDR)
   2272 		return EINVAL;
   2273 	error = udf_check_tag_payload(eahdr, sizeof(struct extattrhdr_desc));
   2274 	if (error)
   2275 		return EINVAL;
   2276 
   2277 	DPRINTF(EXTATTR, ("Found %d bytes of extended attributes\n", l_ea));
   2278 
   2279 	/* looking for Ecma-167 attributes? */
   2280 	offset = sizeof(struct extattrhdr_desc);
   2281 
   2282 	/* looking for either implemenation use or application use */
   2283 	if (sattr == 2048) {				/* [4/48.10.8] */
   2284 		offset = udf_rw32(eahdr->impl_attr_loc);
   2285 		if (offset == UDF_IMPL_ATTR_LOC_NOT_PRESENT)
   2286 			return ENOENT;
   2287 	}
   2288 	if (sattr == 65536) {				/* [4/48.10.9] */
   2289 		offset = udf_rw32(eahdr->appl_attr_loc);
   2290 		if (offset == UDF_APPL_ATTR_LOC_NOT_PRESENT)
   2291 			return ENOENT;
   2292 	}
   2293 
   2294 	/* paranoia check offset and l_ea */
   2295 	if (l_ea + offset >= sector_size - sizeof(struct extattr_entry))
   2296 		return EINVAL;
   2297 
   2298 	DPRINTF(EXTATTR, ("Starting at offset %d\n", offset));
   2299 
   2300 	/* find our extended attribute  */
   2301 	l_ea -= offset;
   2302 	pos = (uint8_t *) eahdr + offset;
   2303 
   2304 	while (l_ea >= sizeof(struct extattr_entry)) {
   2305 		DPRINTF(EXTATTR, ("%d extended attr bytes left\n", l_ea));
   2306 		attrhdr = (struct extattr_entry *) pos;
   2307 		implext = (struct impl_extattr_entry *) pos;
   2308 
   2309 		/* get complete attribute length and check for roque values */
   2310 		a_l = udf_rw32(attrhdr->a_l);
   2311 		DPRINTF(EXTATTR, ("attribute %d:%d, len %d/%d\n",
   2312 				udf_rw32(attrhdr->type),
   2313 				attrhdr->subtype, a_l, l_ea));
   2314 		if ((a_l == 0) || (a_l > l_ea))
   2315 			return EINVAL;
   2316 
   2317 		if (attrhdr->type != sattr)
   2318 			goto next_attribute;
   2319 
   2320 		/* we might have found it! */
   2321 		if (attrhdr->type < 2048) {	/* Ecma-167 attribute */
   2322 			*offsetp = offset;
   2323 			*lengthp = a_l;
   2324 			return 0;		/* success */
   2325 		}
   2326 
   2327 		/*
   2328 		 * Implementation use and application use extended attributes
   2329 		 * have a name to identify. They share the same structure only
   2330 		 * UDF implementation use extended attributes have a checksum
   2331 		 * we need to check
   2332 		 */
   2333 
   2334 		DPRINTF(EXTATTR, ("named attribute %s\n", implext->imp_id.id));
   2335 		if (strcmp(implext->imp_id.id, sattrname) == 0) {
   2336 			/* we have found our appl/implementation attribute */
   2337 			*offsetp = offset;
   2338 			*lengthp = a_l;
   2339 			return 0;		/* success */
   2340 		}
   2341 
   2342 next_attribute:
   2343 		/* next attribute */
   2344 		pos    += a_l;
   2345 		l_ea   -= a_l;
   2346 		offset += a_l;
   2347 	}
   2348 	/* not found */
   2349 	return ENOENT;
   2350 }
   2351 
   2352 
   2353 static void
   2354 udf_extattr_insert_internal(struct udf_mount *ump, union dscrptr *dscr,
   2355 	struct extattr_entry *extattr)
   2356 {
   2357 	struct file_entry      *fe;
   2358 	struct extfile_entry   *efe;
   2359 	struct extattrhdr_desc *extattrhdr;
   2360 	struct impl_extattr_entry *implext;
   2361 	uint32_t impl_attr_loc, appl_attr_loc, l_ea, a_l, exthdr_len;
   2362 	uint32_t *l_eap, l_ad;
   2363 	uint16_t *spos;
   2364 	uint8_t *bpos, *data;
   2365 
   2366 	if (udf_rw16(dscr->tag.id) == TAGID_FENTRY) {
   2367 		fe    = &dscr->fe;
   2368 		data  = fe->data;
   2369 		l_eap = &fe->l_ea;
   2370 		l_ad  = udf_rw32(fe->l_ad);
   2371 	} else if (udf_rw16(dscr->tag.id) == TAGID_EXTFENTRY) {
   2372 		efe   = &dscr->efe;
   2373 		data  = efe->data;
   2374 		l_eap = &efe->l_ea;
   2375 		l_ad  = udf_rw32(efe->l_ad);
   2376 	} else {
   2377 		panic("Bad tag passed to udf_extattr_insert_internal");
   2378 	}
   2379 
   2380 	/* can't append already written to file descriptors yet */
   2381 	assert(l_ad == 0);
   2382 
   2383 	/* should have a header! */
   2384 	extattrhdr = (struct extattrhdr_desc *) data;
   2385 	l_ea = udf_rw32(*l_eap);
   2386 	if (l_ea == 0) {
   2387 		/* create empty extended attribute header */
   2388 		exthdr_len = sizeof(struct extattrhdr_desc);
   2389 
   2390 		udf_inittag(ump, &extattrhdr->tag, TAGID_EXTATTR_HDR,
   2391 			/* loc */ 0);
   2392 		extattrhdr->impl_attr_loc = udf_rw32(exthdr_len);
   2393 		extattrhdr->appl_attr_loc = udf_rw32(exthdr_len);
   2394 		extattrhdr->tag.desc_crc_len = udf_rw16(8);
   2395 
   2396 		/* record extended attribute header length */
   2397 		l_ea = exthdr_len;
   2398 		*l_eap = udf_rw32(l_ea);
   2399 	}
   2400 
   2401 	/* extract locations */
   2402 	impl_attr_loc = udf_rw32(extattrhdr->impl_attr_loc);
   2403 	appl_attr_loc = udf_rw32(extattrhdr->appl_attr_loc);
   2404 	if (impl_attr_loc == UDF_IMPL_ATTR_LOC_NOT_PRESENT)
   2405 		impl_attr_loc = l_ea;
   2406 	if (appl_attr_loc == UDF_IMPL_ATTR_LOC_NOT_PRESENT)
   2407 		appl_attr_loc = l_ea;
   2408 
   2409 	/* Ecma 167 EAs */
   2410 	if (udf_rw32(extattr->type) < 2048) {
   2411 		assert(impl_attr_loc == l_ea);
   2412 		assert(appl_attr_loc == l_ea);
   2413 	}
   2414 
   2415 	/* implementation use extended attributes */
   2416 	if (udf_rw32(extattr->type) == 2048) {
   2417 		assert(appl_attr_loc == l_ea);
   2418 
   2419 		/* calculate and write extended attribute header checksum */
   2420 		implext = (struct impl_extattr_entry *) extattr;
   2421 		assert(udf_rw32(implext->iu_l) == 4);	/* [UDF 3.3.4.5] */
   2422 		spos = (uint16_t *) implext->data;
   2423 		*spos = udf_rw16(udf_ea_cksum((uint8_t *) implext));
   2424 	}
   2425 
   2426 	/* application use extended attributes */
   2427 	assert(udf_rw32(extattr->type) != 65536);
   2428 	assert(appl_attr_loc == l_ea);
   2429 
   2430 	/* append the attribute at the end of the current space */
   2431 	bpos = data + udf_rw32(*l_eap);
   2432 	a_l  = udf_rw32(extattr->a_l);
   2433 
   2434 	/* update impl. attribute locations */
   2435 	if (udf_rw32(extattr->type) < 2048) {
   2436 		impl_attr_loc = l_ea + a_l;
   2437 		appl_attr_loc = l_ea + a_l;
   2438 	}
   2439 	if (udf_rw32(extattr->type) == 2048) {
   2440 		appl_attr_loc = l_ea + a_l;
   2441 	}
   2442 
   2443 	/* copy and advance */
   2444 	memcpy(bpos, extattr, a_l);
   2445 	l_ea += a_l;
   2446 	*l_eap = udf_rw32(l_ea);
   2447 
   2448 	/* do the `dance` again backwards */
   2449 	if (udf_rw16(ump->logical_vol->tag.descriptor_ver) != 2) {
   2450 		if (impl_attr_loc == l_ea)
   2451 			impl_attr_loc = UDF_IMPL_ATTR_LOC_NOT_PRESENT;
   2452 		if (appl_attr_loc == l_ea)
   2453 			appl_attr_loc = UDF_APPL_ATTR_LOC_NOT_PRESENT;
   2454 	}
   2455 
   2456 	/* store offsets */
   2457 	extattrhdr->impl_attr_loc = udf_rw32(impl_attr_loc);
   2458 	extattrhdr->appl_attr_loc = udf_rw32(appl_attr_loc);
   2459 }
   2460 
   2461 
   2462 /* --------------------------------------------------------------------- */
   2463 
   2464 static int
   2465 udf_update_lvid_from_vat_extattr(struct udf_node *vat_node)
   2466 {
   2467 	struct udf_mount       *ump;
   2468 	struct udf_logvol_info *lvinfo;
   2469 	struct impl_extattr_entry     *implext;
   2470 	struct vatlvext_extattr_entry  lvext;
   2471 	const char *extstr = "*UDF VAT LVExtension";
   2472 	uint64_t    vat_uniqueid;
   2473 	uint32_t    offset, a_l;
   2474 	uint8_t    *ea_start, *lvextpos;
   2475 	int         error;
   2476 
   2477 	/* get mountpoint and lvinfo */
   2478 	ump    = vat_node->ump;
   2479 	lvinfo = ump->logvol_info;
   2480 
   2481 	/* get information from fe/efe */
   2482 	if (vat_node->fe) {
   2483 		vat_uniqueid = udf_rw64(vat_node->fe->unique_id);
   2484 		ea_start     = vat_node->fe->data;
   2485 	} else {
   2486 		vat_uniqueid = udf_rw64(vat_node->efe->unique_id);
   2487 		ea_start     = vat_node->efe->data;
   2488 	}
   2489 
   2490 	error = udf_extattr_search_intern(vat_node, 2048, extstr, &offset, &a_l);
   2491 	if (error)
   2492 		return error;
   2493 
   2494 	implext = (struct impl_extattr_entry *) (ea_start + offset);
   2495 	error = udf_impl_extattr_check(implext);
   2496 	if (error)
   2497 		return error;
   2498 
   2499 	/* paranoia */
   2500 	if (a_l != sizeof(*implext) -1 + udf_rw32(implext->iu_l) + sizeof(lvext)) {
   2501 		DPRINTF(VOLUMES, ("VAT LVExtension size doesn't compute\n"));
   2502 		return EINVAL;
   2503 	}
   2504 
   2505 	/*
   2506 	 * we have found our "VAT LVExtension attribute. BUT due to a
   2507 	 * bug in the specification it might not be word aligned so
   2508 	 * copy first to avoid panics on some machines (!!)
   2509 	 */
   2510 	DPRINTF(VOLUMES, ("Found VAT LVExtension attr\n"));
   2511 	lvextpos = implext->data + udf_rw32(implext->iu_l);
   2512 	memcpy(&lvext, lvextpos, sizeof(lvext));
   2513 
   2514 	/* check if it was updated the last time */
   2515 	if (udf_rw64(lvext.unique_id_chk) == vat_uniqueid) {
   2516 		lvinfo->num_files       = lvext.num_files;
   2517 		lvinfo->num_directories = lvext.num_directories;
   2518 		udf_update_logvolname(ump, lvext.logvol_id);
   2519 	} else {
   2520 		DPRINTF(VOLUMES, ("VAT LVExtension out of date\n"));
   2521 		/* replace VAT LVExt by free space EA */
   2522 		memset(implext->imp_id.id, 0, UDF_REGID_ID_SIZE);
   2523 		strcpy(implext->imp_id.id, "*UDF FreeEASpace");
   2524 		udf_calc_impl_extattr_checksum(implext);
   2525 	}
   2526 
   2527 	return 0;
   2528 }
   2529 
   2530 
   2531 static int
   2532 udf_update_vat_extattr_from_lvid(struct udf_node *vat_node)
   2533 {
   2534 	struct udf_mount       *ump;
   2535 	struct udf_logvol_info *lvinfo;
   2536 	struct impl_extattr_entry     *implext;
   2537 	struct vatlvext_extattr_entry  lvext;
   2538 	const char *extstr = "*UDF VAT LVExtension";
   2539 	uint64_t    vat_uniqueid;
   2540 	uint32_t    offset, a_l;
   2541 	uint8_t    *ea_start, *lvextpos;
   2542 	int         error;
   2543 
   2544 	/* get mountpoint and lvinfo */
   2545 	ump    = vat_node->ump;
   2546 	lvinfo = ump->logvol_info;
   2547 
   2548 	/* get information from fe/efe */
   2549 	if (vat_node->fe) {
   2550 		vat_uniqueid = udf_rw64(vat_node->fe->unique_id);
   2551 		ea_start     = vat_node->fe->data;
   2552 	} else {
   2553 		vat_uniqueid = udf_rw64(vat_node->efe->unique_id);
   2554 		ea_start     = vat_node->efe->data;
   2555 	}
   2556 
   2557 	error = udf_extattr_search_intern(vat_node, 2048, extstr, &offset, &a_l);
   2558 	if (error)
   2559 		return error;
   2560 	/* found, it existed */
   2561 
   2562 	/* paranoia */
   2563 	implext = (struct impl_extattr_entry *) (ea_start + offset);
   2564 	error = udf_impl_extattr_check(implext);
   2565 	if (error) {
   2566 		DPRINTF(VOLUMES, ("VAT LVExtension bad on update\n"));
   2567 		return error;
   2568 	}
   2569 	/* it is correct */
   2570 
   2571 	/*
   2572 	 * we have found our "VAT LVExtension attribute. BUT due to a
   2573 	 * bug in the specification it might not be word aligned so
   2574 	 * copy first to avoid panics on some machines (!!)
   2575 	 */
   2576 	DPRINTF(VOLUMES, ("Updating VAT LVExtension attr\n"));
   2577 	lvextpos = implext->data + udf_rw32(implext->iu_l);
   2578 
   2579 	lvext.unique_id_chk   = vat_uniqueid;
   2580 	lvext.num_files       = lvinfo->num_files;
   2581 	lvext.num_directories = lvinfo->num_directories;
   2582 	memmove(lvext.logvol_id, ump->logical_vol->logvol_id, 128);
   2583 
   2584 	memcpy(lvextpos, &lvext, sizeof(lvext));
   2585 
   2586 	return 0;
   2587 }
   2588 
   2589 /* --------------------------------------------------------------------- */
   2590 
   2591 int
   2592 udf_vat_read(struct udf_node *vat_node, uint8_t *blob, int size, uint32_t offset)
   2593 {
   2594 	struct udf_mount *ump = vat_node->ump;
   2595 
   2596 	if (offset + size > ump->vat_offset + ump->vat_entries * 4)
   2597 		return EINVAL;
   2598 
   2599 	memcpy(blob, ump->vat_table + offset, size);
   2600 	return 0;
   2601 }
   2602 
   2603 int
   2604 udf_vat_write(struct udf_node *vat_node, uint8_t *blob, int size, uint32_t offset)
   2605 {
   2606 	struct udf_mount *ump = vat_node->ump;
   2607 	uint32_t offset_high;
   2608 	uint8_t *new_vat_table;
   2609 
   2610 	/* extent VAT allocation if needed */
   2611 	offset_high = offset + size;
   2612 	if (offset_high >= ump->vat_table_alloc_len) {
   2613 		/* realloc */
   2614 		new_vat_table = realloc(ump->vat_table,
   2615 			ump->vat_table_alloc_len + UDF_VAT_CHUNKSIZE,
   2616 			M_UDFVOLD, M_WAITOK | M_CANFAIL);
   2617 		if (!new_vat_table) {
   2618 			printf("udf_vat_write: can't extent VAT, out of mem\n");
   2619 			return ENOMEM;
   2620 		}
   2621 		ump->vat_table = new_vat_table;
   2622 		ump->vat_table_alloc_len += UDF_VAT_CHUNKSIZE;
   2623 	}
   2624 	ump->vat_table_len = MAX(ump->vat_table_len, offset_high);
   2625 
   2626 	memcpy(ump->vat_table + offset, blob, size);
   2627 	return 0;
   2628 }
   2629 
   2630 /* --------------------------------------------------------------------- */
   2631 
   2632 /* TODO support previous VAT location writeout */
   2633 static int
   2634 udf_update_vat_descriptor(struct udf_mount *ump)
   2635 {
   2636 	struct udf_node *vat_node = ump->vat_node;
   2637 	struct udf_logvol_info *lvinfo = ump->logvol_info;
   2638 	struct icb_tag *icbtag;
   2639 	struct udf_oldvat_tail *oldvat_tl;
   2640 	struct udf_vat *vat;
   2641 	uint64_t unique_id;
   2642 	uint32_t lb_size;
   2643 	uint8_t *raw_vat;
   2644 	int filetype, error;
   2645 
   2646 	KASSERT(vat_node);
   2647 	KASSERT(lvinfo);
   2648 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   2649 
   2650 	/* get our new unique_id */
   2651 	unique_id = udf_advance_uniqueid(ump);
   2652 
   2653 	/* get information from fe/efe */
   2654 	if (vat_node->fe) {
   2655 		icbtag    = &vat_node->fe->icbtag;
   2656 		vat_node->fe->unique_id = udf_rw64(unique_id);
   2657 	} else {
   2658 		icbtag = &vat_node->efe->icbtag;
   2659 		vat_node->efe->unique_id = udf_rw64(unique_id);
   2660 	}
   2661 
   2662 	/* Check icb filetype! it has to be 0 or UDF_ICB_FILETYPE_VAT */
   2663 	filetype = icbtag->file_type;
   2664 	KASSERT((filetype == 0) || (filetype == UDF_ICB_FILETYPE_VAT));
   2665 
   2666 	/* allocate piece to process head or tail of VAT file */
   2667 	raw_vat = malloc(lb_size, M_TEMP, M_WAITOK);
   2668 
   2669 	if (filetype == 0) {
   2670 		/*
   2671 		 * Update "*UDF VAT LVExtension" extended attribute from the
   2672 		 * lvint if present.
   2673 		 */
   2674 		udf_update_vat_extattr_from_lvid(vat_node);
   2675 
   2676 		/* setup identifying regid */
   2677 		oldvat_tl = (struct udf_oldvat_tail *) raw_vat;
   2678 		memset(oldvat_tl, 0, sizeof(struct udf_oldvat_tail));
   2679 
   2680 		udf_set_regid(&oldvat_tl->id, "*UDF Virtual Alloc Tbl");
   2681 		udf_add_udf_regid(ump, &oldvat_tl->id);
   2682 		oldvat_tl->prev_vat = udf_rw32(0xffffffff);
   2683 
   2684 		/* write out new tail of virtual allocation table file */
   2685 		error = udf_vat_write(vat_node, raw_vat,
   2686 			sizeof(struct udf_oldvat_tail), ump->vat_entries * 4);
   2687 	} else {
   2688 		/* compose the VAT2 header */
   2689 		vat = (struct udf_vat *) raw_vat;
   2690 		memset(vat, 0, sizeof(struct udf_vat));
   2691 
   2692 		vat->header_len       = udf_rw16(152);	/* as per spec */
   2693 		vat->impl_use_len     = udf_rw16(0);
   2694 		memmove(vat->logvol_id, ump->logical_vol->logvol_id, 128);
   2695 		vat->prev_vat         = udf_rw32(0xffffffff);
   2696 		vat->num_files        = lvinfo->num_files;
   2697 		vat->num_directories  = lvinfo->num_directories;
   2698 		vat->min_udf_readver  = lvinfo->min_udf_readver;
   2699 		vat->min_udf_writever = lvinfo->min_udf_writever;
   2700 		vat->max_udf_writever = lvinfo->max_udf_writever;
   2701 
   2702 		error = udf_vat_write(vat_node, raw_vat,
   2703 			sizeof(struct udf_vat), 0);
   2704 	}
   2705 	free(raw_vat, M_TEMP);
   2706 
   2707 	return error;	/* success! */
   2708 }
   2709 
   2710 
   2711 int
   2712 udf_writeout_vat(struct udf_mount *ump)
   2713 {
   2714 	struct udf_node *vat_node = ump->vat_node;
   2715 	uint32_t vat_length;
   2716 	int error;
   2717 
   2718 	KASSERT(vat_node);
   2719 
   2720 	DPRINTF(CALL, ("udf_writeout_vat\n"));
   2721 
   2722 	mutex_enter(&ump->allocate_mutex);
   2723 	udf_update_vat_descriptor(ump);
   2724 
   2725 	/* write out the VAT contents ; TODO intelligent writing */
   2726 	vat_length = ump->vat_table_len;
   2727 	error = vn_rdwr(UIO_WRITE, vat_node->vnode,
   2728 		ump->vat_table, ump->vat_table_len, 0,
   2729 		UIO_SYSSPACE, IO_NODELOCKED, FSCRED, NULL, NULL);
   2730 	if (error) {
   2731 		printf("udf_writeout_vat: failed to write out VAT contents\n");
   2732 		goto out;
   2733 	}
   2734 
   2735 	mutex_exit(&ump->allocate_mutex);
   2736 
   2737 	vflushbuf(ump->vat_node->vnode, 1 /* sync */);
   2738 	error = VOP_FSYNC(ump->vat_node->vnode,
   2739 			FSCRED, FSYNC_WAIT, 0, 0);
   2740 	if (error)
   2741 		printf("udf_writeout_vat: error writing VAT node!\n");
   2742 out:
   2743 
   2744 	return error;
   2745 }
   2746 
   2747 /* --------------------------------------------------------------------- */
   2748 
   2749 /*
   2750  * Read in relevant pieces of VAT file and check if its indeed a VAT file
   2751  * descriptor. If OK, read in complete VAT file.
   2752  */
   2753 
   2754 static int
   2755 udf_check_for_vat(struct udf_node *vat_node)
   2756 {
   2757 	struct udf_mount *ump;
   2758 	struct icb_tag   *icbtag;
   2759 	struct timestamp *mtime;
   2760 	struct udf_vat   *vat;
   2761 	struct udf_oldvat_tail *oldvat_tl;
   2762 	struct udf_logvol_info *lvinfo;
   2763 	uint64_t  unique_id;
   2764 	uint32_t  vat_length;
   2765 	uint32_t  vat_offset, vat_entries, vat_table_alloc_len;
   2766 	uint32_t  sector_size;
   2767 	uint32_t *raw_vat;
   2768 	uint8_t  *vat_table;
   2769 	char     *regid_name;
   2770 	int filetype;
   2771 	int error;
   2772 
   2773 	/* vat_length is really 64 bits though impossible */
   2774 
   2775 	DPRINTF(VOLUMES, ("Checking for VAT\n"));
   2776 	if (!vat_node)
   2777 		return ENOENT;
   2778 
   2779 	/* get mount info */
   2780 	ump = vat_node->ump;
   2781 	sector_size = udf_rw32(ump->logical_vol->lb_size);
   2782 
   2783 	/* check assertions */
   2784 	assert(vat_node->fe || vat_node->efe);
   2785 	assert(ump->logvol_integrity);
   2786 
   2787 	/* set vnode type to regular file or we can't read from it! */
   2788 	vat_node->vnode->v_type = VREG;
   2789 
   2790 	/* get information from fe/efe */
   2791 	if (vat_node->fe) {
   2792 		vat_length = udf_rw64(vat_node->fe->inf_len);
   2793 		icbtag    = &vat_node->fe->icbtag;
   2794 		mtime     = &vat_node->fe->mtime;
   2795 		unique_id = udf_rw64(vat_node->fe->unique_id);
   2796 	} else {
   2797 		vat_length = udf_rw64(vat_node->efe->inf_len);
   2798 		icbtag = &vat_node->efe->icbtag;
   2799 		mtime  = &vat_node->efe->mtime;
   2800 		unique_id = udf_rw64(vat_node->efe->unique_id);
   2801 	}
   2802 
   2803 	/* Check icb filetype! it has to be 0 or UDF_ICB_FILETYPE_VAT */
   2804 	filetype = icbtag->file_type;
   2805 	if ((filetype != 0) && (filetype != UDF_ICB_FILETYPE_VAT))
   2806 		return ENOENT;
   2807 
   2808 	DPRINTF(VOLUMES, ("\tPossible VAT length %d\n", vat_length));
   2809 
   2810 	vat_table_alloc_len =
   2811 		((vat_length + UDF_VAT_CHUNKSIZE-1) / UDF_VAT_CHUNKSIZE)
   2812 			* UDF_VAT_CHUNKSIZE;
   2813 
   2814 	vat_table = malloc(vat_table_alloc_len, M_UDFVOLD,
   2815 		M_CANFAIL | M_WAITOK);
   2816 	if (vat_table == NULL) {
   2817 		printf("allocation of %d bytes failed for VAT\n",
   2818 			vat_table_alloc_len);
   2819 		return ENOMEM;
   2820 	}
   2821 
   2822 	/* allocate piece to read in head or tail of VAT file */
   2823 	raw_vat = malloc(sector_size, M_TEMP, M_WAITOK);
   2824 
   2825 	/*
   2826 	 * check contents of the file if its the old 1.50 VAT table format.
   2827 	 * Its notoriously broken and allthough some implementations support an
   2828 	 * extention as defined in the UDF 1.50 errata document, its doubtfull
   2829 	 * to be useable since a lot of implementations don't maintain it.
   2830 	 */
   2831 	lvinfo = ump->logvol_info;
   2832 
   2833 	if (filetype == 0) {
   2834 		/* definition */
   2835 		vat_offset  = 0;
   2836 		vat_entries = (vat_length-36)/4;
   2837 
   2838 		/* read in tail of virtual allocation table file */
   2839 		error = vn_rdwr(UIO_READ, vat_node->vnode,
   2840 				(uint8_t *) raw_vat,
   2841 				sizeof(struct udf_oldvat_tail),
   2842 				vat_entries * 4,
   2843 				UIO_SYSSPACE, IO_SYNC | IO_NODELOCKED, FSCRED,
   2844 				NULL, NULL);
   2845 		if (error)
   2846 			goto out;
   2847 
   2848 		/* check 1.50 VAT */
   2849 		oldvat_tl = (struct udf_oldvat_tail *) raw_vat;
   2850 		regid_name = (char *) oldvat_tl->id.id;
   2851 		error = strncmp(regid_name, "*UDF Virtual Alloc Tbl", 22);
   2852 		if (error) {
   2853 			DPRINTF(VOLUMES, ("VAT format 1.50 rejected\n"));
   2854 			error = ENOENT;
   2855 			goto out;
   2856 		}
   2857 
   2858 		/*
   2859 		 * update LVID from "*UDF VAT LVExtension" extended attribute
   2860 		 * if present.
   2861 		 */
   2862 		udf_update_lvid_from_vat_extattr(vat_node);
   2863 	} else {
   2864 		/* read in head of virtual allocation table file */
   2865 		error = vn_rdwr(UIO_READ, vat_node->vnode,
   2866 				(uint8_t *) raw_vat,
   2867 				sizeof(struct udf_vat), 0,
   2868 				UIO_SYSSPACE, IO_SYNC | IO_NODELOCKED, FSCRED,
   2869 				NULL, NULL);
   2870 		if (error)
   2871 			goto out;
   2872 
   2873 		/* definition */
   2874 		vat = (struct udf_vat *) raw_vat;
   2875 		vat_offset  = vat->header_len;
   2876 		vat_entries = (vat_length - vat_offset)/4;
   2877 
   2878 		assert(lvinfo);
   2879 		lvinfo->num_files        = vat->num_files;
   2880 		lvinfo->num_directories  = vat->num_directories;
   2881 		lvinfo->min_udf_readver  = vat->min_udf_readver;
   2882 		lvinfo->min_udf_writever = vat->min_udf_writever;
   2883 		lvinfo->max_udf_writever = vat->max_udf_writever;
   2884 
   2885 		udf_update_logvolname(ump, vat->logvol_id);
   2886 	}
   2887 
   2888 	/* read in complete VAT file */
   2889 	error = vn_rdwr(UIO_READ, vat_node->vnode,
   2890 			vat_table,
   2891 			vat_length, 0,
   2892 			UIO_SYSSPACE, IO_SYNC | IO_NODELOCKED, FSCRED,
   2893 			NULL, NULL);
   2894 	if (error)
   2895 		printf("read in of complete VAT file failed (error %d)\n",
   2896 			error);
   2897 	if (error)
   2898 		goto out;
   2899 
   2900 	DPRINTF(VOLUMES, ("VAT format accepted, marking it closed\n"));
   2901 	ump->logvol_integrity->lvint_next_unique_id = unique_id;
   2902 	ump->logvol_integrity->integrity_type = udf_rw32(UDF_INTEGRITY_CLOSED);
   2903 	ump->logvol_integrity->time           = *mtime;
   2904 
   2905 	ump->vat_table_len = vat_length;
   2906 	ump->vat_table_alloc_len = vat_table_alloc_len;
   2907 	ump->vat_table   = vat_table;
   2908 	ump->vat_offset  = vat_offset;
   2909 	ump->vat_entries = vat_entries;
   2910 	ump->vat_last_free_lb = 0;		/* start at beginning */
   2911 
   2912 out:
   2913 	if (error) {
   2914 		if (vat_table)
   2915 			free(vat_table, M_UDFVOLD);
   2916 	}
   2917 	free(raw_vat, M_TEMP);
   2918 
   2919 	return error;
   2920 }
   2921 
   2922 /* --------------------------------------------------------------------- */
   2923 
   2924 static int
   2925 udf_search_vat(struct udf_mount *ump, union udf_pmap *mapping)
   2926 {
   2927 	struct udf_node *vat_node;
   2928 	struct long_ad	 icb_loc;
   2929 	uint32_t early_vat_loc, late_vat_loc, vat_loc;
   2930 	int error;
   2931 
   2932 	/* mapping info not needed */
   2933 	mapping = mapping;
   2934 
   2935 	vat_loc = ump->last_possible_vat_location;
   2936 	early_vat_loc = vat_loc - 256;	/* 8 blocks of 32 sectors */
   2937 
   2938 	DPRINTF(VOLUMES, ("1) last possible %d, early_vat_loc %d \n",
   2939 		vat_loc, early_vat_loc));
   2940 	early_vat_loc = MAX(early_vat_loc, ump->first_possible_vat_location);
   2941 	late_vat_loc  = vat_loc + 1024;
   2942 
   2943 	DPRINTF(VOLUMES, ("2) last possible %d, early_vat_loc %d \n",
   2944 		vat_loc, early_vat_loc));
   2945 
   2946 	/* start looking from the end of the range */
   2947 	do {
   2948 		DPRINTF(VOLUMES, ("Checking for VAT at sector %d\n", vat_loc));
   2949 		icb_loc.loc.part_num = udf_rw16(UDF_VTOP_RAWPART);
   2950 		icb_loc.loc.lb_num   = udf_rw32(vat_loc);
   2951 
   2952 		error = udf_get_node(ump, &icb_loc, &vat_node);
   2953 		if (!error) {
   2954 			error = udf_check_for_vat(vat_node);
   2955 			DPRINTFIF(VOLUMES, !error,
   2956 				("VAT accepted at %d\n", vat_loc));
   2957 			if (!error)
   2958 				break;
   2959 		}
   2960 		if (vat_node) {
   2961 			vput(vat_node->vnode);
   2962 			vat_node = NULL;
   2963 		}
   2964 		vat_loc--;	/* walk backwards */
   2965 	} while (vat_loc >= early_vat_loc);
   2966 
   2967 	/* keep our VAT node around */
   2968 	if (vat_node) {
   2969 		UDF_SET_SYSTEMFILE(vat_node->vnode);
   2970 		ump->vat_node = vat_node;
   2971 	}
   2972 
   2973 	return error;
   2974 }
   2975 
   2976 /* --------------------------------------------------------------------- */
   2977 
   2978 static int
   2979 udf_read_sparables(struct udf_mount *ump, union udf_pmap *mapping)
   2980 {
   2981 	union dscrptr *dscr;
   2982 	struct part_map_spare *pms = &mapping->pms;
   2983 	uint32_t lb_num;
   2984 	int spar, error;
   2985 
   2986 	/*
   2987 	 * The partition mapping passed on to us specifies the information we
   2988 	 * need to locate and initialise the sparable partition mapping
   2989 	 * information we need.
   2990 	 */
   2991 
   2992 	DPRINTF(VOLUMES, ("Read sparable table\n"));
   2993 	ump->sparable_packet_size = udf_rw16(pms->packet_len);
   2994 	KASSERT(ump->sparable_packet_size >= ump->packet_size);	/* XXX */
   2995 
   2996 	for (spar = 0; spar < pms->n_st; spar++) {
   2997 		lb_num = pms->st_loc[spar];
   2998 		DPRINTF(VOLUMES, ("Checking for sparing table %d\n", lb_num));
   2999 		error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD, &dscr);
   3000 		if (!error && dscr) {
   3001 			if (udf_rw16(dscr->tag.id) == TAGID_SPARING_TABLE) {
   3002 				if (ump->sparing_table)
   3003 					free(ump->sparing_table, M_UDFVOLD);
   3004 				ump->sparing_table = &dscr->spt;
   3005 				dscr = NULL;
   3006 				DPRINTF(VOLUMES,
   3007 				    ("Sparing table accepted (%d entries)\n",
   3008 				     udf_rw16(ump->sparing_table->rt_l)));
   3009 				break;	/* we're done */
   3010 			}
   3011 		}
   3012 		if (dscr)
   3013 			free(dscr, M_UDFVOLD);
   3014 	}
   3015 
   3016 	if (ump->sparing_table)
   3017 		return 0;
   3018 
   3019 	return ENOENT;
   3020 }
   3021 
   3022 /* --------------------------------------------------------------------- */
   3023 
   3024 static int
   3025 udf_read_metadata_nodes(struct udf_mount *ump, union udf_pmap *mapping)
   3026 {
   3027 	struct part_map_meta *pmm = &mapping->pmm;
   3028 	struct long_ad	 icb_loc;
   3029 	struct vnode *vp;
   3030 	int error;
   3031 
   3032 	DPRINTF(VOLUMES, ("Reading in Metadata files\n"));
   3033 	icb_loc.loc.part_num = pmm->part_num;
   3034 	icb_loc.loc.lb_num   = pmm->meta_file_lbn;
   3035 	DPRINTF(VOLUMES, ("Metadata file\n"));
   3036 	error = udf_get_node(ump, &icb_loc, &ump->metadata_node);
   3037 	if (ump->metadata_node) {
   3038 		vp = ump->metadata_node->vnode;
   3039 		UDF_SET_SYSTEMFILE(vp);
   3040 	}
   3041 
   3042 	icb_loc.loc.lb_num   = pmm->meta_mirror_file_lbn;
   3043 	if (icb_loc.loc.lb_num != -1) {
   3044 		DPRINTF(VOLUMES, ("Metadata copy file\n"));
   3045 		error = udf_get_node(ump, &icb_loc, &ump->metadatamirror_node);
   3046 		if (ump->metadatamirror_node) {
   3047 			vp = ump->metadatamirror_node->vnode;
   3048 			UDF_SET_SYSTEMFILE(vp);
   3049 		}
   3050 	}
   3051 
   3052 	icb_loc.loc.lb_num   = pmm->meta_bitmap_file_lbn;
   3053 	if (icb_loc.loc.lb_num != -1) {
   3054 		DPRINTF(VOLUMES, ("Metadata bitmap file\n"));
   3055 		error = udf_get_node(ump, &icb_loc, &ump->metadatabitmap_node);
   3056 		if (ump->metadatabitmap_node) {
   3057 			vp = ump->metadatabitmap_node->vnode;
   3058 			UDF_SET_SYSTEMFILE(vp);
   3059 		}
   3060 	}
   3061 
   3062 	/* if we're mounting read-only we relax the requirements */
   3063 	if (ump->vfs_mountp->mnt_flag & MNT_RDONLY) {
   3064 		error = EFAULT;
   3065 		if (ump->metadata_node)
   3066 			error = 0;
   3067 		if ((ump->metadata_node == NULL) && (ump->metadatamirror_node)) {
   3068 			printf( "udf mount: Metadata file not readable, "
   3069 				"substituting Metadata copy file\n");
   3070 			ump->metadata_node = ump->metadatamirror_node;
   3071 			ump->metadatamirror_node = NULL;
   3072 			error = 0;
   3073 		}
   3074 	} else {
   3075 		/* mounting read/write */
   3076 		/* XXX DISABLED! metadata writing is not working yet XXX */
   3077 		if (error)
   3078 			error = EROFS;
   3079 	}
   3080 	DPRINTFIF(VOLUMES, error, ("udf mount: failed to read "
   3081 				   "metadata files\n"));
   3082 	return error;
   3083 }
   3084 
   3085 /* --------------------------------------------------------------------- */
   3086 
   3087 int
   3088 udf_read_vds_tables(struct udf_mount *ump)
   3089 {
   3090 	union udf_pmap *mapping;
   3091 	/* struct udf_args *args = &ump->mount_args; */
   3092 	uint32_t n_pm, mt_l;
   3093 	uint32_t log_part;
   3094 	uint8_t *pmap_pos;
   3095 	int pmap_size;
   3096 	int error;
   3097 
   3098 	/* Iterate (again) over the part mappings for locations   */
   3099 	n_pm = udf_rw32(ump->logical_vol->n_pm);   /* num partmaps         */
   3100 	mt_l = udf_rw32(ump->logical_vol->mt_l);   /* partmaps data length */
   3101 	pmap_pos =  ump->logical_vol->maps;
   3102 
   3103 	for (log_part = 0; log_part < n_pm; log_part++) {
   3104 		mapping = (union udf_pmap *) pmap_pos;
   3105 		switch (ump->vtop_tp[log_part]) {
   3106 		case UDF_VTOP_TYPE_PHYS :
   3107 			/* nothing */
   3108 			break;
   3109 		case UDF_VTOP_TYPE_VIRT :
   3110 			/* search and load VAT */
   3111 			error = udf_search_vat(ump, mapping);
   3112 			if (error)
   3113 				return ENOENT;
   3114 			break;
   3115 		case UDF_VTOP_TYPE_SPARABLE :
   3116 			/* load one of the sparable tables */
   3117 			error = udf_read_sparables(ump, mapping);
   3118 			if (error)
   3119 				return ENOENT;
   3120 			break;
   3121 		case UDF_VTOP_TYPE_META :
   3122 			/* load the associated file descriptors */
   3123 			error = udf_read_metadata_nodes(ump, mapping);
   3124 			if (error)
   3125 				return ENOENT;
   3126 			break;
   3127 		default:
   3128 			break;
   3129 		}
   3130 		pmap_size  = pmap_pos[1];
   3131 		pmap_pos  += pmap_size;
   3132 	}
   3133 
   3134 	/* read in and check unallocated and free space info if writing */
   3135 	if ((ump->vfs_mountp->mnt_flag & MNT_RDONLY) == 0) {
   3136 		error = udf_read_physical_partition_spacetables(ump);
   3137 		if (error)
   3138 			return error;
   3139 
   3140 		/* also read in metadata partion spacebitmap if defined */
   3141 		error = udf_read_metadata_partition_spacetable(ump);
   3142 			return error;
   3143 	}
   3144 
   3145 	return 0;
   3146 }
   3147 
   3148 /* --------------------------------------------------------------------- */
   3149 
   3150 int
   3151 udf_read_rootdirs(struct udf_mount *ump)
   3152 {
   3153 	union dscrptr *dscr;
   3154 	/* struct udf_args *args = &ump->mount_args; */
   3155 	struct udf_node *rootdir_node, *streamdir_node;
   3156 	struct long_ad  fsd_loc, *dir_loc;
   3157 	uint32_t lb_num, dummy;
   3158 	uint32_t fsd_len;
   3159 	int dscr_type;
   3160 	int error;
   3161 
   3162 	/* TODO implement FSD reading in separate function like integrity? */
   3163 	/* get fileset descriptor sequence */
   3164 	fsd_loc = ump->logical_vol->lv_fsd_loc;
   3165 	fsd_len = udf_rw32(fsd_loc.len);
   3166 
   3167 	dscr  = NULL;
   3168 	error = 0;
   3169 	while (fsd_len || error) {
   3170 		DPRINTF(VOLUMES, ("fsd_len = %d\n", fsd_len));
   3171 		/* translate fsd_loc to lb_num */
   3172 		error = udf_translate_vtop(ump, &fsd_loc, &lb_num, &dummy);
   3173 		if (error)
   3174 			break;
   3175 		DPRINTF(VOLUMES, ("Reading FSD at lb %d\n", lb_num));
   3176 		error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD, &dscr);
   3177 		/* end markers */
   3178 		if (error || (dscr == NULL))
   3179 			break;
   3180 
   3181 		/* analyse */
   3182 		dscr_type = udf_rw16(dscr->tag.id);
   3183 		if (dscr_type == TAGID_TERM)
   3184 			break;
   3185 		if (dscr_type != TAGID_FSD) {
   3186 			free(dscr, M_UDFVOLD);
   3187 			return ENOENT;
   3188 		}
   3189 
   3190 		/*
   3191 		 * TODO check for multiple fileset descriptors; its only
   3192 		 * picking the last now. Also check for FSD
   3193 		 * correctness/interpretability
   3194 		 */
   3195 
   3196 		/* update */
   3197 		if (ump->fileset_desc) {
   3198 			free(ump->fileset_desc, M_UDFVOLD);
   3199 		}
   3200 		ump->fileset_desc = &dscr->fsd;
   3201 		dscr = NULL;
   3202 
   3203 		/* continue to the next fsd */
   3204 		fsd_len -= ump->discinfo.sector_size;
   3205 		fsd_loc.loc.lb_num = udf_rw32(udf_rw32(fsd_loc.loc.lb_num)+1);
   3206 
   3207 		/* follow up to fsd->next_ex (long_ad) if its not null */
   3208 		if (udf_rw32(ump->fileset_desc->next_ex.len)) {
   3209 			DPRINTF(VOLUMES, ("follow up FSD extent\n"));
   3210 			fsd_loc = ump->fileset_desc->next_ex;
   3211 			fsd_len = udf_rw32(ump->fileset_desc->next_ex.len);
   3212 		}
   3213 	}
   3214 	if (dscr)
   3215 		free(dscr, M_UDFVOLD);
   3216 
   3217 	/* there has to be one */
   3218 	if (ump->fileset_desc == NULL)
   3219 		return ENOENT;
   3220 
   3221 	DPRINTF(VOLUMES, ("FSD read in fine\n"));
   3222 	DPRINTF(VOLUMES, ("Updating fsd logical volume id\n"));
   3223 	udf_update_logvolname(ump, ump->logical_vol->logvol_id);
   3224 
   3225 	/*
   3226 	 * Now the FSD is known, read in the rootdirectory and if one exists,
   3227 	 * the system stream dir. Some files in the system streamdir are not
   3228 	 * wanted in this implementation since they are not maintained. If
   3229 	 * writing is enabled we'll delete these files if they exist.
   3230 	 */
   3231 
   3232 	rootdir_node = streamdir_node = NULL;
   3233 	dir_loc = NULL;
   3234 
   3235 	/* try to read in the rootdir */
   3236 	dir_loc = &ump->fileset_desc->rootdir_icb;
   3237 	error = udf_get_node(ump, dir_loc, &rootdir_node);
   3238 	if (error)
   3239 		return ENOENT;
   3240 
   3241 	/* aparently it read in fine */
   3242 
   3243 	/*
   3244 	 * Try the system stream directory; not very likely in the ones we
   3245 	 * test, but for completeness.
   3246 	 */
   3247 	dir_loc = &ump->fileset_desc->streamdir_icb;
   3248 	if (udf_rw32(dir_loc->len)) {
   3249 		printf("udf_read_rootdirs: streamdir defined ");
   3250 		error = udf_get_node(ump, dir_loc, &streamdir_node);
   3251 		if (error) {
   3252 			printf("but error in streamdir reading\n");
   3253 		} else {
   3254 			printf("but ignored\n");
   3255 			/*
   3256 			 * TODO process streamdir `baddies' i.e. files we dont
   3257 			 * want if R/W
   3258 			 */
   3259 		}
   3260 	}
   3261 
   3262 	DPRINTF(VOLUMES, ("Rootdir(s) read in fine\n"));
   3263 
   3264 	/* release the vnodes again; they'll be auto-recycled later */
   3265 	if (streamdir_node) {
   3266 		vput(streamdir_node->vnode);
   3267 	}
   3268 	if (rootdir_node) {
   3269 		vput(rootdir_node->vnode);
   3270 	}
   3271 
   3272 	return 0;
   3273 }
   3274 
   3275 /* --------------------------------------------------------------------- */
   3276 
   3277 /* To make absolutely sure we are NOT returning zero, add one :) */
   3278 
   3279 long
   3280 udf_calchash(struct long_ad *icbptr)
   3281 {
   3282 	/* ought to be enough since each mountpoint has its own chain */
   3283 	return udf_rw32(icbptr->loc.lb_num) + 1;
   3284 }
   3285 
   3286 
   3287 static struct udf_node *
   3288 udf_hash_lookup(struct udf_mount *ump, struct long_ad *icbptr)
   3289 {
   3290 	struct udf_node *node;
   3291 	struct vnode *vp;
   3292 	uint32_t hashline;
   3293 
   3294 loop:
   3295 	mutex_enter(&ump->ihash_lock);
   3296 
   3297 	hashline = udf_calchash(icbptr) & UDF_INODE_HASHMASK;
   3298 	LIST_FOREACH(node, &ump->udf_nodes[hashline], hashchain) {
   3299 		assert(node);
   3300 		if (node->loc.loc.lb_num   == icbptr->loc.lb_num &&
   3301 		    node->loc.loc.part_num == icbptr->loc.part_num) {
   3302 			vp = node->vnode;
   3303 			assert(vp);
   3304 			mutex_enter(&vp->v_interlock);
   3305 			mutex_exit(&ump->ihash_lock);
   3306 			if (vget(vp, LK_EXCLUSIVE | LK_INTERLOCK))
   3307 				goto loop;
   3308 			return node;
   3309 		}
   3310 	}
   3311 	mutex_exit(&ump->ihash_lock);
   3312 
   3313 	return NULL;
   3314 }
   3315 
   3316 
   3317 static void
   3318 udf_sorted_list_insert(struct udf_node *node)
   3319 {
   3320 	struct udf_mount *ump;
   3321 	struct udf_node  *s_node, *last_node;
   3322 	uint32_t loc, s_loc;
   3323 
   3324 	ump = node->ump;
   3325 	last_node = NULL;	/* XXX gcc */
   3326 
   3327 	if (LIST_EMPTY(&ump->sorted_udf_nodes)) {
   3328 		LIST_INSERT_HEAD(&ump->sorted_udf_nodes, node, sortchain);
   3329 		return;
   3330 	}
   3331 
   3332 	/*
   3333 	 * We sort on logical block number here and not on physical block
   3334 	 * number here. Ideally we should go for the physical block nr to get
   3335 	 * better sync performance though this sort will ensure that packets
   3336 	 * won't get spit up unnessisarily.
   3337 	 */
   3338 
   3339 	loc = udf_rw32(node->loc.loc.lb_num);
   3340 	LIST_FOREACH(s_node, &ump->sorted_udf_nodes, sortchain) {
   3341 		s_loc = udf_rw32(s_node->loc.loc.lb_num);
   3342 		if (s_loc > loc) {
   3343 			LIST_INSERT_BEFORE(s_node, node, sortchain);
   3344 			return;
   3345 		}
   3346 		last_node = s_node;
   3347 	}
   3348 	LIST_INSERT_AFTER(last_node, node, sortchain);
   3349 }
   3350 
   3351 
   3352 static void
   3353 udf_register_node(struct udf_node *node)
   3354 {
   3355 	struct udf_mount *ump;
   3356 	struct udf_node *chk;
   3357 	uint32_t hashline;
   3358 
   3359 	ump = node->ump;
   3360 	mutex_enter(&ump->ihash_lock);
   3361 
   3362 	/* add to our hash table */
   3363 	hashline = udf_calchash(&node->loc) & UDF_INODE_HASHMASK;
   3364 #ifdef DEBUG
   3365 	LIST_FOREACH(chk, &ump->udf_nodes[hashline], hashchain) {
   3366 		assert(chk);
   3367 		if (chk->loc.loc.lb_num   == node->loc.loc.lb_num &&
   3368 		    chk->loc.loc.part_num == node->loc.loc.part_num)
   3369 			panic("Double node entered\n");
   3370 	}
   3371 #else
   3372 	chk = NULL;
   3373 #endif
   3374 	LIST_INSERT_HEAD(&ump->udf_nodes[hashline], node, hashchain);
   3375 
   3376 	/* add to our sorted list */
   3377 	udf_sorted_list_insert(node);
   3378 
   3379 	mutex_exit(&ump->ihash_lock);
   3380 }
   3381 
   3382 
   3383 static void
   3384 udf_deregister_node(struct udf_node *node)
   3385 {
   3386 	struct udf_mount *ump;
   3387 
   3388 	ump = node->ump;
   3389 	mutex_enter(&ump->ihash_lock);
   3390 
   3391 	/* from hash and sorted list */
   3392 	LIST_REMOVE(node, hashchain);
   3393 	LIST_REMOVE(node, sortchain);
   3394 
   3395 	mutex_exit(&ump->ihash_lock);
   3396 }
   3397 
   3398 /* --------------------------------------------------------------------- */
   3399 
   3400 int
   3401 udf_open_logvol(struct udf_mount *ump)
   3402 {
   3403 	int logvol_integrity;
   3404 	int error;
   3405 
   3406 	/* already/still open? */
   3407 	logvol_integrity = udf_rw32(ump->logvol_integrity->integrity_type);
   3408 	if (logvol_integrity == UDF_INTEGRITY_OPEN)
   3409 		return 0;
   3410 
   3411 	/* can we open it ? */
   3412 	if (ump->vfs_mountp->mnt_flag & MNT_RDONLY)
   3413 		return EROFS;
   3414 
   3415 	/* setup write parameters */
   3416 	DPRINTF(VOLUMES, ("Setting up write parameters\n"));
   3417 	if ((error = udf_setup_writeparams(ump)) != 0)
   3418 		return error;
   3419 
   3420 	/* determine data and metadata tracks (most likely same) */
   3421 	error = udf_search_writing_tracks(ump);
   3422 	if (error) {
   3423 		/* most likely lack of space */
   3424 		printf("udf_open_logvol: error searching writing tracks\n");
   3425 		return EROFS;
   3426 	}
   3427 
   3428 	/* writeout/update lvint on disc or only in memory */
   3429 	DPRINTF(VOLUMES, ("Opening logical volume\n"));
   3430 	if (ump->lvopen & UDF_OPEN_SESSION) {
   3431 		/* TODO implement writeout of VRS + VDS */
   3432 		printf( "udf_open_logvol:Opening a closed session not yet "
   3433 			"implemented\n");
   3434 		return EROFS;
   3435 
   3436 		/* determine data and metadata tracks again */
   3437 		error = udf_search_writing_tracks(ump);
   3438 	}
   3439 
   3440 	/* mark it open */
   3441 	ump->logvol_integrity->integrity_type = udf_rw32(UDF_INTEGRITY_OPEN);
   3442 
   3443 	/* do we need to write it out? */
   3444 	if (ump->lvopen & UDF_WRITE_LVINT) {
   3445 		error = udf_writeout_lvint(ump, ump->lvopen);
   3446 		/* if we couldn't write it mark it closed again */
   3447 		if (error) {
   3448 			ump->logvol_integrity->integrity_type =
   3449 						udf_rw32(UDF_INTEGRITY_CLOSED);
   3450 			return error;
   3451 		}
   3452 	}
   3453 
   3454 	return 0;
   3455 }
   3456 
   3457 
   3458 int
   3459 udf_close_logvol(struct udf_mount *ump, int mntflags)
   3460 {
   3461 	int logvol_integrity;
   3462 	int error = 0, error1 = 0, error2 = 0;
   3463 	int n;
   3464 
   3465 	/* already/still closed? */
   3466 	logvol_integrity = udf_rw32(ump->logvol_integrity->integrity_type);
   3467 	if (logvol_integrity == UDF_INTEGRITY_CLOSED)
   3468 		return 0;
   3469 
   3470 	/* writeout/update lvint or write out VAT */
   3471 	DPRINTF(VOLUMES, ("Closing logical volume\n"));
   3472 	if (ump->lvclose & UDF_WRITE_VAT) {
   3473 		DPRINTF(VOLUMES, ("lvclose & UDF_WRITE_VAT\n"));
   3474 
   3475 		/* write out the VAT node */
   3476 		DPRINTF(VOLUMES, ("writeout vat_node\n"));
   3477 		udf_writeout_vat(ump);
   3478 
   3479 		vflushbuf(ump->vat_node->vnode, 1 /* sync */);
   3480 		for (n = 0; n < 16; n++) {
   3481 			ump->vat_node->i_flags |= IN_MODIFIED;
   3482 			error = VOP_FSYNC(ump->vat_node->vnode,
   3483 					FSCRED, FSYNC_WAIT, 0, 0);
   3484 		}
   3485 		if (error) {
   3486 			printf("udf_close_logvol: writeout of VAT failed\n");
   3487 			return error;
   3488 		}
   3489 	}
   3490 
   3491 	if (ump->lvclose & UDF_WRITE_PART_BITMAPS) {
   3492 		/* sync writeout metadata spacetable if existing */
   3493 		error1 = udf_write_metadata_partition_spacetable(ump, true);
   3494 		if (error1)
   3495 			printf( "udf_close_logvol: writeout of metadata space "
   3496 				"bitmap failed\n");
   3497 
   3498 		/* sync writeout partition spacetables */
   3499 		error2 = udf_write_physical_partition_spacetables(ump, true);
   3500 		if (error2)
   3501 			printf( "udf_close_logvol: writeout of space tables "
   3502 				"failed\n");
   3503 
   3504 		if (error1 || error2)
   3505 			return (error1 | error2);
   3506 
   3507 		ump->lvclose &= ~UDF_WRITE_PART_BITMAPS;
   3508 	}
   3509 
   3510 	if (ump->lvclose & UDF_CLOSE_SESSION) {
   3511 		printf("TODO: Closing a session is not yet implemented\n");
   3512 		return EROFS;
   3513 		ump->lvopen |= UDF_OPEN_SESSION;
   3514 	}
   3515 
   3516 	/* mark it closed */
   3517 	ump->logvol_integrity->integrity_type = udf_rw32(UDF_INTEGRITY_CLOSED);
   3518 
   3519 	/* do we need to write out the logical volume integrity */
   3520 	if (ump->lvclose & UDF_WRITE_LVINT)
   3521 		error = udf_writeout_lvint(ump, ump->lvopen);
   3522 	if (error) {
   3523 		/* HELP now what? mark it open again for now */
   3524 		ump->logvol_integrity->integrity_type =
   3525 			udf_rw32(UDF_INTEGRITY_OPEN);
   3526 		return error;
   3527 	}
   3528 
   3529 	(void) udf_synchronise_caches(ump);
   3530 
   3531 	return 0;
   3532 }
   3533 
   3534 /* --------------------------------------------------------------------- */
   3535 
   3536 /*
   3537  * Genfs interfacing
   3538  *
   3539  * static const struct genfs_ops udf_genfsops = {
   3540  * 	.gop_size = genfs_size,
   3541  * 		size of transfers
   3542  * 	.gop_alloc = udf_gop_alloc,
   3543  * 		allocate len bytes at offset
   3544  * 	.gop_write = genfs_gop_write,
   3545  * 		putpages interface code
   3546  * 	.gop_markupdate = udf_gop_markupdate,
   3547  * 		set update/modify flags etc.
   3548  * }
   3549  */
   3550 
   3551 /*
   3552  * Genfs interface. These four functions are the only ones defined though not
   3553  * documented... great....
   3554  */
   3555 
   3556 /*
   3557  * Callback from genfs to allocate len bytes at offset off; only called when
   3558  * filling up gaps in the allocation.
   3559  */
   3560 /* XXX should we check if there is space enough in udf_gop_alloc? */
   3561 static int
   3562 udf_gop_alloc(struct vnode *vp, off_t off,
   3563     off_t len, int flags, kauth_cred_t cred)
   3564 {
   3565 #if 0
   3566 	struct udf_node *udf_node = VTOI(vp);
   3567 	struct udf_mount *ump = udf_node->ump;
   3568 	uint32_t lb_size, num_lb;
   3569 #endif
   3570 
   3571 	DPRINTF(NOTIMPL, ("udf_gop_alloc not implemented\n"));
   3572 	DPRINTF(ALLOC, ("udf_gop_alloc called for %"PRIu64" bytes\n", len));
   3573 
   3574 	return 0;
   3575 }
   3576 
   3577 
   3578 /*
   3579  * callback from genfs to update our flags
   3580  */
   3581 static void
   3582 udf_gop_markupdate(struct vnode *vp, int flags)
   3583 {
   3584 	struct udf_node *udf_node = VTOI(vp);
   3585 	u_long mask = 0;
   3586 
   3587 	if ((flags & GOP_UPDATE_ACCESSED) != 0) {
   3588 		mask = IN_ACCESS;
   3589 	}
   3590 	if ((flags & GOP_UPDATE_MODIFIED) != 0) {
   3591 		if (vp->v_type == VREG) {
   3592 			mask |= IN_CHANGE | IN_UPDATE;
   3593 		} else {
   3594 			mask |= IN_MODIFY;
   3595 		}
   3596 	}
   3597 	if (mask) {
   3598 		udf_node->i_flags |= mask;
   3599 	}
   3600 }
   3601 
   3602 
   3603 static const struct genfs_ops udf_genfsops = {
   3604 	.gop_size = genfs_size,
   3605 	.gop_alloc = udf_gop_alloc,
   3606 	.gop_write = genfs_gop_write_rwmap,
   3607 	.gop_markupdate = udf_gop_markupdate,
   3608 };
   3609 
   3610 
   3611 /* --------------------------------------------------------------------- */
   3612 
   3613 int
   3614 udf_write_terminator(struct udf_mount *ump, uint32_t sector)
   3615 {
   3616 	union dscrptr *dscr;
   3617 	int error;
   3618 
   3619 	dscr = malloc(ump->discinfo.sector_size, M_TEMP, M_WAITOK);
   3620 	bzero(dscr, ump->discinfo.sector_size);
   3621 	udf_inittag(ump, &dscr->tag, TAGID_TERM, sector);
   3622 
   3623 	/* CRC length for an anchor is 512 - tag length; defined in Ecma 167 */
   3624 	dscr->tag.desc_crc_len = udf_rw16(512-UDF_DESC_TAG_LENGTH);
   3625 	(void) udf_validate_tag_and_crc_sums(dscr);
   3626 
   3627 	error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR,
   3628 			dscr, sector, sector);
   3629 
   3630 	free(dscr, M_TEMP);
   3631 
   3632 	return error;
   3633 }
   3634 
   3635 
   3636 /* --------------------------------------------------------------------- */
   3637 
   3638 /* UDF<->unix converters */
   3639 
   3640 /* --------------------------------------------------------------------- */
   3641 
   3642 static mode_t
   3643 udf_perm_to_unix_mode(uint32_t perm)
   3644 {
   3645 	mode_t mode;
   3646 
   3647 	mode  = ((perm & UDF_FENTRY_PERM_USER_MASK)      );
   3648 	mode |= ((perm & UDF_FENTRY_PERM_GRP_MASK  ) >> 2);
   3649 	mode |= ((perm & UDF_FENTRY_PERM_OWNER_MASK) >> 4);
   3650 
   3651 	return mode;
   3652 }
   3653 
   3654 /* --------------------------------------------------------------------- */
   3655 
   3656 static uint32_t
   3657 unix_mode_to_udf_perm(mode_t mode)
   3658 {
   3659 	uint32_t perm;
   3660 
   3661 	perm  = ((mode & S_IRWXO)     );
   3662 	perm |= ((mode & S_IRWXG) << 2);
   3663 	perm |= ((mode & S_IRWXU) << 4);
   3664 	perm |= ((mode & S_IWOTH) << 3);
   3665 	perm |= ((mode & S_IWGRP) << 5);
   3666 	perm |= ((mode & S_IWUSR) << 7);
   3667 
   3668 	return perm;
   3669 }
   3670 
   3671 /* --------------------------------------------------------------------- */
   3672 
   3673 static uint32_t
   3674 udf_icb_to_unix_filetype(uint32_t icbftype)
   3675 {
   3676 	switch (icbftype) {
   3677 	case UDF_ICB_FILETYPE_DIRECTORY :
   3678 	case UDF_ICB_FILETYPE_STREAMDIR :
   3679 		return S_IFDIR;
   3680 	case UDF_ICB_FILETYPE_FIFO :
   3681 		return S_IFIFO;
   3682 	case UDF_ICB_FILETYPE_CHARDEVICE :
   3683 		return S_IFCHR;
   3684 	case UDF_ICB_FILETYPE_BLOCKDEVICE :
   3685 		return S_IFBLK;
   3686 	case UDF_ICB_FILETYPE_RANDOMACCESS :
   3687 	case UDF_ICB_FILETYPE_REALTIME :
   3688 		return S_IFREG;
   3689 	case UDF_ICB_FILETYPE_SYMLINK :
   3690 		return S_IFLNK;
   3691 	case UDF_ICB_FILETYPE_SOCKET :
   3692 		return S_IFSOCK;
   3693 	}
   3694 	/* no idea what this is */
   3695 	return 0;
   3696 }
   3697 
   3698 /* --------------------------------------------------------------------- */
   3699 
   3700 void
   3701 udf_to_unix_name(char *result, int result_len, char *id, int len,
   3702 	struct charspec *chsp)
   3703 {
   3704 	uint16_t   *raw_name, *unix_name;
   3705 	uint16_t   *inchp, ch;
   3706 	uint8_t	   *outchp;
   3707 	const char *osta_id = "OSTA Compressed Unicode";
   3708 	int         ucode_chars, nice_uchars, is_osta_typ0, nout;
   3709 
   3710 	raw_name = malloc(2048 * sizeof(uint16_t), M_UDFTEMP, M_WAITOK);
   3711 	unix_name = raw_name + 1024;			/* split space in half */
   3712 	assert(sizeof(char) == sizeof(uint8_t));
   3713 	outchp = (uint8_t *) result;
   3714 
   3715 	is_osta_typ0  = (chsp->type == 0);
   3716 	is_osta_typ0 &= (strcmp((char *) chsp->inf, osta_id) == 0);
   3717 	if (is_osta_typ0) {
   3718 		/* TODO clean up */
   3719 		*raw_name = *unix_name = 0;
   3720 		ucode_chars = udf_UncompressUnicode(len, (uint8_t *) id, raw_name);
   3721 		ucode_chars = MIN(ucode_chars, UnicodeLength((unicode_t *) raw_name));
   3722 		nice_uchars = UDFTransName(unix_name, raw_name, ucode_chars);
   3723 		/* output UTF8 */
   3724 		for (inchp = unix_name; nice_uchars>0; inchp++, nice_uchars--) {
   3725 			ch = *inchp;
   3726 			nout = wput_utf8(outchp, result_len, ch);
   3727 			outchp += nout; result_len -= nout;
   3728 			if (!ch) break;
   3729 		}
   3730 		*outchp++ = 0;
   3731 	} else {
   3732 		/* assume 8bit char length byte latin-1 */
   3733 		assert(*id == 8);
   3734 		assert(strlen((char *) (id+1)) <= MAXNAMLEN);
   3735 		strncpy((char *) result, (char *) (id+1), strlen((char *) (id+1)));
   3736 	}
   3737 	free(raw_name, M_UDFTEMP);
   3738 }
   3739 
   3740 /* --------------------------------------------------------------------- */
   3741 
   3742 void
   3743 unix_to_udf_name(char *result, uint8_t *result_len, char const *name, int name_len,
   3744 	struct charspec *chsp)
   3745 {
   3746 	uint16_t   *raw_name;
   3747 	uint16_t   *outchp;
   3748 	const char *inchp;
   3749 	const char *osta_id = "OSTA Compressed Unicode";
   3750 	int         udf_chars, is_osta_typ0, bits;
   3751 	size_t      cnt;
   3752 
   3753 	/* allocate temporary unicode-16 buffer */
   3754 	raw_name = malloc(1024, M_UDFTEMP, M_WAITOK);
   3755 
   3756 	/* convert utf8 to unicode-16 */
   3757 	*raw_name = 0;
   3758 	inchp  = name;
   3759 	outchp = raw_name;
   3760 	bits = 8;
   3761 	for (cnt = name_len, udf_chars = 0; cnt;) {
   3762 /*###3490 [cc] warning: passing argument 2 of 'wget_utf8' from incompatible pointer type%%%*/
   3763 		*outchp = wget_utf8(&inchp, &cnt);
   3764 		if (*outchp > 0xff)
   3765 			bits=16;
   3766 		outchp++;
   3767 		udf_chars++;
   3768 	}
   3769 	/* null terminate just in case */
   3770 	*outchp++ = 0;
   3771 
   3772 	is_osta_typ0  = (chsp->type == 0);
   3773 	is_osta_typ0 &= (strcmp((char *) chsp->inf, osta_id) == 0);
   3774 	if (is_osta_typ0) {
   3775 		udf_chars = udf_CompressUnicode(udf_chars, bits,
   3776 				(unicode_t *) raw_name,
   3777 				(byte *) result);
   3778 	} else {
   3779 		printf("unix to udf name: no CHSP0 ?\n");
   3780 		/* XXX assume 8bit char length byte latin-1 */
   3781 		*result++ = 8; udf_chars = 1;
   3782 		strncpy(result, name + 1, name_len);
   3783 		udf_chars += name_len;
   3784 	}
   3785 	*result_len = udf_chars;
   3786 	free(raw_name, M_UDFTEMP);
   3787 }
   3788 
   3789 /* --------------------------------------------------------------------- */
   3790 
   3791 void
   3792 udf_timestamp_to_timespec(struct udf_mount *ump,
   3793 			  struct timestamp *timestamp,
   3794 			  struct timespec  *timespec)
   3795 {
   3796 	struct clock_ymdhms ymdhms;
   3797 	uint32_t usecs, secs, nsecs;
   3798 	uint16_t tz;
   3799 
   3800 	/* fill in ymdhms structure from timestamp */
   3801 	memset(&ymdhms, 0, sizeof(ymdhms));
   3802 	ymdhms.dt_year = udf_rw16(timestamp->year);
   3803 	ymdhms.dt_mon  = timestamp->month;
   3804 	ymdhms.dt_day  = timestamp->day;
   3805 	ymdhms.dt_wday = 0; /* ? */
   3806 	ymdhms.dt_hour = timestamp->hour;
   3807 	ymdhms.dt_min  = timestamp->minute;
   3808 	ymdhms.dt_sec  = timestamp->second;
   3809 
   3810 	secs = clock_ymdhms_to_secs(&ymdhms);
   3811 	usecs = timestamp->usec +
   3812 		100*timestamp->hund_usec + 10000*timestamp->centisec;
   3813 	nsecs = usecs * 1000;
   3814 
   3815 	/*
   3816 	 * Calculate the time zone.  The timezone is 12 bit signed 2's
   3817 	 * compliment, so we gotta do some extra magic to handle it right.
   3818 	 */
   3819 	tz  = udf_rw16(timestamp->type_tz);
   3820 	tz &= 0x0fff;			/* only lower 12 bits are significant */
   3821 	if (tz & 0x0800)		/* sign extention */
   3822 		tz |= 0xf000;
   3823 
   3824 	/* TODO check timezone conversion */
   3825 	/* check if we are specified a timezone to convert */
   3826 	if (udf_rw16(timestamp->type_tz) & 0x1000) {
   3827 		if ((int16_t) tz != -2047)
   3828 			secs -= (int16_t) tz * 60;
   3829 	} else {
   3830 		secs -= ump->mount_args.gmtoff;
   3831 	}
   3832 
   3833 	timespec->tv_sec  = secs;
   3834 	timespec->tv_nsec = nsecs;
   3835 }
   3836 
   3837 
   3838 void
   3839 udf_timespec_to_timestamp(struct timespec *timespec, struct timestamp *timestamp)
   3840 {
   3841 	struct clock_ymdhms ymdhms;
   3842 	uint32_t husec, usec, csec;
   3843 
   3844 	(void) clock_secs_to_ymdhms(timespec->tv_sec, &ymdhms);
   3845 
   3846 	usec   = timespec->tv_nsec / 1000;
   3847 	husec  =  usec / 100;
   3848 	usec  -= husec * 100;				/* only 0-99 in usec  */
   3849 	csec   = husec / 100;				/* only 0-99 in csec  */
   3850 	husec -=  csec * 100;				/* only 0-99 in husec */
   3851 
   3852 	/* set method 1 for CUT/GMT */
   3853 	timestamp->type_tz	= udf_rw16((1<<12) + 0);
   3854 	timestamp->year		= udf_rw16(ymdhms.dt_year);
   3855 	timestamp->month	= ymdhms.dt_mon;
   3856 	timestamp->day		= ymdhms.dt_day;
   3857 	timestamp->hour		= ymdhms.dt_hour;
   3858 	timestamp->minute	= ymdhms.dt_min;
   3859 	timestamp->second	= ymdhms.dt_sec;
   3860 	timestamp->centisec	= csec;
   3861 	timestamp->hund_usec	= husec;
   3862 	timestamp->usec		= usec;
   3863 }
   3864 
   3865 /* --------------------------------------------------------------------- */
   3866 
   3867 /*
   3868  * Attribute and filetypes converters with get/set pairs
   3869  */
   3870 
   3871 uint32_t
   3872 udf_getaccessmode(struct udf_node *udf_node)
   3873 {
   3874 	struct file_entry     *fe = udf_node->fe;;
   3875 	struct extfile_entry *efe = udf_node->efe;
   3876 	uint32_t udf_perm, icbftype;
   3877 	uint32_t mode, ftype;
   3878 	uint16_t icbflags;
   3879 
   3880 	UDF_LOCK_NODE(udf_node, 0);
   3881 	if (fe) {
   3882 		udf_perm = udf_rw32(fe->perm);
   3883 		icbftype = fe->icbtag.file_type;
   3884 		icbflags = udf_rw16(fe->icbtag.flags);
   3885 	} else {
   3886 		assert(udf_node->efe);
   3887 		udf_perm = udf_rw32(efe->perm);
   3888 		icbftype = efe->icbtag.file_type;
   3889 		icbflags = udf_rw16(efe->icbtag.flags);
   3890 	}
   3891 
   3892 	mode  = udf_perm_to_unix_mode(udf_perm);
   3893 	ftype = udf_icb_to_unix_filetype(icbftype);
   3894 
   3895 	/* set suid, sgid, sticky from flags in fe/efe */
   3896 	if (icbflags & UDF_ICB_TAG_FLAGS_SETUID)
   3897 		mode |= S_ISUID;
   3898 	if (icbflags & UDF_ICB_TAG_FLAGS_SETGID)
   3899 		mode |= S_ISGID;
   3900 	if (icbflags & UDF_ICB_TAG_FLAGS_STICKY)
   3901 		mode |= S_ISVTX;
   3902 
   3903 	UDF_UNLOCK_NODE(udf_node, 0);
   3904 
   3905 	return mode | ftype;
   3906 }
   3907 
   3908 
   3909 void
   3910 udf_setaccessmode(struct udf_node *udf_node, mode_t mode)
   3911 {
   3912 	struct file_entry    *fe  = udf_node->fe;
   3913 	struct extfile_entry *efe = udf_node->efe;
   3914 	uint32_t udf_perm;
   3915 	uint16_t icbflags;
   3916 
   3917 	UDF_LOCK_NODE(udf_node, 0);
   3918 	udf_perm = unix_mode_to_udf_perm(mode & ALLPERMS);
   3919 	if (fe) {
   3920 		icbflags = udf_rw16(fe->icbtag.flags);
   3921 	} else {
   3922 		icbflags = udf_rw16(efe->icbtag.flags);
   3923 	}
   3924 
   3925 	icbflags &= ~UDF_ICB_TAG_FLAGS_SETUID;
   3926 	icbflags &= ~UDF_ICB_TAG_FLAGS_SETGID;
   3927 	icbflags &= ~UDF_ICB_TAG_FLAGS_STICKY;
   3928 	if (mode & S_ISUID)
   3929 		icbflags |= UDF_ICB_TAG_FLAGS_SETUID;
   3930 	if (mode & S_ISGID)
   3931 		icbflags |= UDF_ICB_TAG_FLAGS_SETGID;
   3932 	if (mode & S_ISVTX)
   3933 		icbflags |= UDF_ICB_TAG_FLAGS_STICKY;
   3934 
   3935 	if (fe) {
   3936 		fe->perm  = udf_rw32(udf_perm);
   3937 		fe->icbtag.flags  = udf_rw16(icbflags);
   3938 	} else {
   3939 		efe->perm = udf_rw32(udf_perm);
   3940 		efe->icbtag.flags = udf_rw16(icbflags);
   3941 	}
   3942 
   3943 	UDF_UNLOCK_NODE(udf_node, 0);
   3944 }
   3945 
   3946 
   3947 void
   3948 udf_getownership(struct udf_node *udf_node, uid_t *uidp, gid_t *gidp)
   3949 {
   3950 	struct udf_mount     *ump = udf_node->ump;
   3951 	struct file_entry    *fe  = udf_node->fe;
   3952 	struct extfile_entry *efe = udf_node->efe;
   3953 	uid_t uid;
   3954 	gid_t gid;
   3955 
   3956 	UDF_LOCK_NODE(udf_node, 0);
   3957 	if (fe) {
   3958 		uid = (uid_t)udf_rw32(fe->uid);
   3959 		gid = (gid_t)udf_rw32(fe->gid);
   3960 	} else {
   3961 		assert(udf_node->efe);
   3962 		uid = (uid_t)udf_rw32(efe->uid);
   3963 		gid = (gid_t)udf_rw32(efe->gid);
   3964 	}
   3965 
   3966 	/* do the uid/gid translation game */
   3967 	if ((uid == (uid_t) -1) && (gid == (gid_t) -1)) {
   3968 		uid = ump->mount_args.anon_uid;
   3969 		gid = ump->mount_args.anon_gid;
   3970 	}
   3971 	*uidp = uid;
   3972 	*gidp = gid;
   3973 
   3974 	UDF_UNLOCK_NODE(udf_node, 0);
   3975 }
   3976 
   3977 
   3978 void
   3979 udf_setownership(struct udf_node *udf_node, uid_t uid, gid_t gid)
   3980 {
   3981 	struct udf_mount     *ump = udf_node->ump;
   3982 	struct file_entry    *fe  = udf_node->fe;
   3983 	struct extfile_entry *efe = udf_node->efe;
   3984 	uid_t nobody_uid;
   3985 	gid_t nobody_gid;
   3986 
   3987 	UDF_LOCK_NODE(udf_node, 0);
   3988 
   3989 	/* do the uid/gid translation game */
   3990 	nobody_uid = ump->mount_args.nobody_uid;
   3991 	nobody_gid = ump->mount_args.nobody_gid;
   3992 	if ((uid == nobody_uid) && (gid == nobody_gid)) {
   3993 		uid = (uid_t) -1;
   3994 		gid = (gid_t) -1;
   3995 	}
   3996 
   3997 	if (fe) {
   3998 		fe->uid  = udf_rw32((uint32_t) uid);
   3999 		fe->gid  = udf_rw32((uint32_t) gid);
   4000 	} else {
   4001 		efe->uid = udf_rw32((uint32_t) uid);
   4002 		efe->gid = udf_rw32((uint32_t) gid);
   4003 	}
   4004 
   4005 	UDF_UNLOCK_NODE(udf_node, 0);
   4006 }
   4007 
   4008 
   4009 /* --------------------------------------------------------------------- */
   4010 
   4011 /*
   4012  * UDF dirhash implementation
   4013  */
   4014 
   4015 static uint32_t
   4016 udf_dirhash_hash(const char *str, int namelen)
   4017 {
   4018 	uint32_t hash = 5381;
   4019         int i, c;
   4020 
   4021 	for (i = 0; i < namelen; i++) {
   4022 		c = *str++;
   4023 		hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
   4024 	}
   4025         return hash;
   4026 }
   4027 
   4028 
   4029 static void
   4030 udf_dirhash_purge(struct udf_dirhash *dirh)
   4031 {
   4032 	struct udf_dirhash_entry *dirh_e;
   4033 	uint32_t hashline;
   4034 
   4035 	if (dirh == NULL)
   4036 		return;
   4037 
   4038 	if (dirh->size == 0)
   4039 		return;
   4040 
   4041 	for (hashline = 0; hashline < UDF_DIRHASH_HASHSIZE; hashline++) {
   4042 		dirh_e = LIST_FIRST(&dirh->entries[hashline]);
   4043 		while (dirh_e) {
   4044 			LIST_REMOVE(dirh_e, next);
   4045 			pool_put(&udf_dirhash_entry_pool, dirh_e);
   4046 			dirh_e = LIST_FIRST(&dirh->entries[hashline]);
   4047 		}
   4048 	}
   4049 	dirh_e = LIST_FIRST(&dirh->free_entries);
   4050 
   4051 	while (dirh_e) {
   4052 		LIST_REMOVE(dirh_e, next);
   4053 		pool_put(&udf_dirhash_entry_pool, dirh_e);
   4054 		dirh_e = LIST_FIRST(&dirh->entries[hashline]);
   4055 	}
   4056 
   4057 	dirh->flags &= ~UDF_DIRH_COMPLETE;
   4058 	dirh->flags |=  UDF_DIRH_PURGED;
   4059 
   4060 	udf_dirhashsize -= dirh->size;
   4061 	dirh->size = 0;
   4062 }
   4063 
   4064 
   4065 static void
   4066 udf_dirhash_destroy(struct udf_dirhash **dirhp)
   4067 {
   4068 	struct udf_dirhash *dirh = *dirhp;
   4069 
   4070 	if (dirh == NULL)
   4071 		return;
   4072 
   4073 	mutex_enter(&udf_dirhashmutex);
   4074 
   4075 	udf_dirhash_purge(dirh);
   4076 	TAILQ_REMOVE(&udf_dirhash_queue, dirh, next);
   4077 	pool_put(&udf_dirhash_pool, dirh);
   4078 
   4079 	*dirhp = NULL;
   4080 
   4081 	mutex_exit(&udf_dirhashmutex);
   4082 }
   4083 
   4084 
   4085 static void
   4086 udf_dirhash_get(struct udf_dirhash **dirhp)
   4087 {
   4088 	struct udf_dirhash *dirh;
   4089 	uint32_t hashline;
   4090 
   4091 	mutex_enter(&udf_dirhashmutex);
   4092 
   4093 	dirh = *dirhp;
   4094 	if (*dirhp == NULL) {
   4095 		dirh = pool_get(&udf_dirhash_pool, PR_WAITOK);
   4096 		*dirhp = dirh;
   4097 		memset(dirh, 0, sizeof(struct udf_dirhash));
   4098 		for (hashline = 0; hashline < UDF_DIRHASH_HASHSIZE; hashline++)
   4099 			LIST_INIT(&dirh->entries[hashline]);
   4100 		dirh->size   = 0;
   4101 		dirh->refcnt = 0;
   4102 		dirh->flags  = 0;
   4103 	} else {
   4104 		TAILQ_REMOVE(&udf_dirhash_queue, dirh, next);
   4105 	}
   4106 
   4107 	dirh->refcnt++;
   4108 	TAILQ_INSERT_HEAD(&udf_dirhash_queue, dirh, next);
   4109 
   4110 	mutex_exit(&udf_dirhashmutex);
   4111 }
   4112 
   4113 
   4114 static void
   4115 udf_dirhash_put(struct udf_dirhash *dirh)
   4116 {
   4117 	mutex_enter(&udf_dirhashmutex);
   4118 	dirh->refcnt--;
   4119 	mutex_exit(&udf_dirhashmutex);
   4120 }
   4121 
   4122 
   4123 static void
   4124 udf_dirhash_enter(struct udf_node *dir_node, struct fileid_desc *fid,
   4125 	struct dirent *dirent, uint64_t offset, uint32_t fid_size, int new)
   4126 {
   4127 	struct udf_dirhash *dirh, *del_dirh, *prev_dirh;
   4128 	struct udf_dirhash_entry *dirh_e;
   4129 	uint32_t hashvalue, hashline;
   4130 	int entrysize;
   4131 
   4132 	/* make sure we have a dirhash to work on */
   4133 	dirh = dir_node->dir_hash;
   4134 	KASSERT(dirh);
   4135 	KASSERT(dirh->refcnt > 0);
   4136 
   4137 	/* are we trying to re-enter an entry? */
   4138 	if (!new && (dirh->flags & UDF_DIRH_COMPLETE))
   4139 		return;
   4140 
   4141 	/* calculate our hash */
   4142 	hashvalue = udf_dirhash_hash(dirent->d_name, dirent->d_namlen);
   4143 	hashline  = hashvalue & UDF_DIRHASH_HASHMASK;
   4144 
   4145 	/* lookup and insert entry if not there yet */
   4146 	LIST_FOREACH(dirh_e, &dirh->entries[hashline], next) {
   4147 		/* check for hash collision */
   4148 		if (dirh_e->hashvalue != hashvalue)
   4149 			continue;
   4150 		if (dirh_e->offset != offset)
   4151 			continue;
   4152 		/* got it already */
   4153 		KASSERT(dirh_e->d_namlen == dirent->d_namlen);
   4154 		KASSERT(dirh_e->fid_size == fid_size);
   4155 		return;
   4156 	}
   4157 
   4158 	DPRINTF(DIRHASH, ("dirhash enter %"PRIu64", %d, %d for `%*.*s`\n",
   4159 		offset, fid_size, dirent->d_namlen,
   4160 		dirent->d_namlen, dirent->d_namlen, dirent->d_name));
   4161 
   4162 	/* check if entry is in free space list */
   4163 	LIST_FOREACH(dirh_e, &dirh->free_entries, next) {
   4164 		if (dirh_e->offset == offset) {
   4165 			DPRINTF(DIRHASH, ("\tremoving free entry\n"));
   4166 			LIST_REMOVE(dirh_e, next);
   4167 			break;
   4168 		}
   4169 	}
   4170 
   4171 	/* ensure we are not passing the dirhash limit */
   4172 	entrysize = sizeof(struct udf_dirhash_entry);
   4173 	if (udf_dirhashsize + entrysize > udf_maxdirhashsize) {
   4174 		del_dirh = TAILQ_LAST(&udf_dirhash_queue, _udf_dirhash);
   4175 		KASSERT(del_dirh);
   4176 		while (udf_dirhashsize + entrysize > udf_maxdirhashsize) {
   4177 			/* no use trying to delete myself */
   4178 			if (del_dirh == dirh)
   4179 				break;
   4180 			prev_dirh = TAILQ_PREV(del_dirh, _udf_dirhash, next);
   4181 			if (del_dirh->refcnt == 0)
   4182 				udf_dirhash_purge(del_dirh);
   4183 			del_dirh = prev_dirh;
   4184 		}
   4185 	}
   4186 
   4187 	/* add to the hashline */
   4188 	dirh_e = pool_get(&udf_dirhash_entry_pool, PR_WAITOK);
   4189 	memset(dirh_e, 0, sizeof(struct udf_dirhash_entry));
   4190 
   4191 	dirh_e->hashvalue = hashvalue;
   4192 	dirh_e->offset    = offset;
   4193 	dirh_e->d_namlen  = dirent->d_namlen;
   4194 	dirh_e->fid_size  = fid_size;
   4195 
   4196 	dirh->size      += sizeof(struct udf_dirhash_entry);
   4197 	udf_dirhashsize += sizeof(struct udf_dirhash_entry);
   4198 	LIST_INSERT_HEAD(&dirh->entries[hashline], dirh_e, next);
   4199 }
   4200 
   4201 
   4202 static void
   4203 udf_dirhash_enter_freed(struct udf_node *dir_node, uint64_t offset,
   4204 	uint32_t fid_size)
   4205 {
   4206 	struct udf_dirhash *dirh;
   4207 	struct udf_dirhash_entry *dirh_e;
   4208 
   4209 	/* make sure we have a dirhash to work on */
   4210 	dirh = dir_node->dir_hash;
   4211 	KASSERT(dirh);
   4212 	KASSERT(dirh->refcnt > 0);
   4213 
   4214 #ifdef DEBUG
   4215 	/* check for double entry of free space */
   4216 	LIST_FOREACH(dirh_e, &dirh->free_entries, next)
   4217 		KASSERT(dirh_e->offset != offset);
   4218 #endif
   4219 
   4220 	DPRINTF(DIRHASH, ("dirhash enter FREED %"PRIu64", %d\n",
   4221 		offset, fid_size));
   4222 	dirh_e = pool_get(&udf_dirhash_entry_pool, PR_WAITOK);
   4223 	memset(dirh_e, 0, sizeof(struct udf_dirhash_entry));
   4224 
   4225 	dirh_e->hashvalue = 0;		/* not relevant */
   4226 	dirh_e->offset    = offset;
   4227 	dirh_e->d_namlen  = 0;		/* not relevant */
   4228 	dirh_e->fid_size  = fid_size;
   4229 
   4230 	/* XXX it might be preferable to append them at the tail */
   4231 	LIST_INSERT_HEAD(&dirh->free_entries, dirh_e, next);
   4232 	dirh->size      += sizeof(struct udf_dirhash_entry);
   4233 	udf_dirhashsize += sizeof(struct udf_dirhash_entry);
   4234 }
   4235 
   4236 
   4237 static void
   4238 udf_dirhash_remove(struct udf_node *dir_node, struct dirent *dirent,
   4239 	uint64_t offset, uint32_t fid_size)
   4240 {
   4241 	struct udf_dirhash *dirh;
   4242 	struct udf_dirhash_entry *dirh_e;
   4243 	uint32_t hashvalue, hashline;
   4244 
   4245 	DPRINTF(DIRHASH, ("dirhash remove %"PRIu64", %d for `%*.*s`\n",
   4246 		offset, fid_size,
   4247 		dirent->d_namlen, dirent->d_namlen, dirent->d_name));
   4248 
   4249 	/* make sure we have a dirhash to work on */
   4250 	dirh = dir_node->dir_hash;
   4251 	KASSERT(dirh);
   4252 	KASSERT(dirh->refcnt > 0);
   4253 
   4254 	/* calculate our hash */
   4255 	hashvalue = udf_dirhash_hash(dirent->d_name, dirent->d_namlen);
   4256 	hashline  = hashvalue & UDF_DIRHASH_HASHMASK;
   4257 
   4258 	/* lookup entry */
   4259 	LIST_FOREACH(dirh_e, &dirh->entries[hashline], next) {
   4260 		/* check for hash collision */
   4261 		if (dirh_e->hashvalue != hashvalue)
   4262 			continue;
   4263 		if (dirh_e->offset != offset)
   4264 			continue;
   4265 
   4266 		/* got it! */
   4267 		KASSERT(dirh_e->d_namlen == dirent->d_namlen);
   4268 		KASSERT(dirh_e->fid_size == fid_size);
   4269 		LIST_REMOVE(dirh_e, next);
   4270 		dirh->size      -= sizeof(struct udf_dirhash_entry);
   4271 		udf_dirhashsize -= sizeof(struct udf_dirhash_entry);
   4272 
   4273 		udf_dirhash_enter_freed(dir_node, offset, fid_size);
   4274 		return;
   4275 	}
   4276 
   4277 	/* not found! */
   4278 	panic("dirhash_remove couldn't find entry in hash table\n");
   4279 }
   4280 
   4281 
   4282 /* BUGALERT: don't use result longer than needed, never past the node lock */
   4283 /* call with NULL *result initially and it will return nonzero if again */
   4284 static int
   4285 udf_dirhash_lookup(struct udf_node *dir_node, const char *d_name, int d_namlen,
   4286 	struct udf_dirhash_entry **result)
   4287 {
   4288 	struct udf_dirhash *dirh;
   4289 	struct udf_dirhash_entry *dirh_e;
   4290 	uint32_t hashvalue, hashline;
   4291 
   4292 	KASSERT(VOP_ISLOCKED(dir_node->vnode));
   4293 
   4294 	/* make sure we have a dirhash to work on */
   4295 	dirh = dir_node->dir_hash;
   4296 	KASSERT(dirh);
   4297 	KASSERT(dirh->refcnt > 0);
   4298 
   4299 	/* start where we were */
   4300 	if (*result) {
   4301 		KASSERT(dir_node->dir_hash);
   4302 		dirh_e = *result;
   4303 
   4304 		/* retrieve information to avoid recalculation and advance */
   4305 		hashvalue = dirh_e->hashvalue;
   4306 		dirh_e = LIST_NEXT(*result, next);
   4307 	} else {
   4308 		/* calculate our hash and lookup all entries in hashline */
   4309 		hashvalue = udf_dirhash_hash(d_name, d_namlen);
   4310 		hashline  = hashvalue & UDF_DIRHASH_HASHMASK;
   4311 		dirh_e = LIST_FIRST(&dirh->entries[hashline]);
   4312 	}
   4313 
   4314 	for (; dirh_e; dirh_e = LIST_NEXT(dirh_e, next)) {
   4315 		/* check for hash collision */
   4316 		if (dirh_e->hashvalue != hashvalue)
   4317 			continue;
   4318 		if (dirh_e->d_namlen != d_namlen)
   4319 			continue;
   4320 		/* might have an entry in the cache */
   4321 		*result = dirh_e;
   4322 		return 1;
   4323 	}
   4324 
   4325 	*result = NULL;
   4326 	return 0;
   4327 }
   4328 
   4329 
   4330 /* BUGALERT: don't use result longer than needed, never past the node lock */
   4331 /* call with NULL *result initially and it will return nonzero if again */
   4332 static int
   4333 udf_dirhash_lookup_freed(struct udf_node *dir_node, uint32_t min_fidsize,
   4334 	struct udf_dirhash_entry **result)
   4335 {
   4336 	struct udf_dirhash *dirh;
   4337 	struct udf_dirhash_entry *dirh_e;
   4338 
   4339 	KASSERT(VOP_ISLOCKED(dir_node->vnode));
   4340 
   4341 	/* make sure we have a dirhash to work on */
   4342 	dirh = dir_node->dir_hash;
   4343 	KASSERT(dirh);
   4344 	KASSERT(dirh->refcnt > 0);
   4345 
   4346 	/* start where we were */
   4347 	if (*result) {
   4348 		KASSERT(dir_node->dir_hash);
   4349 		dirh_e = LIST_NEXT(*result, next);
   4350 	} else {
   4351 		/* lookup all entries that match */
   4352 		dirh_e = LIST_FIRST(&dirh->free_entries);
   4353 	}
   4354 
   4355 	for (; dirh_e; dirh_e = LIST_NEXT(dirh_e, next)) {
   4356 		/* check for minimum size */
   4357 		if (dirh_e->fid_size < min_fidsize)
   4358 			continue;
   4359 		/* might be a candidate */
   4360 		*result = dirh_e;
   4361 		return 1;
   4362 	}
   4363 
   4364 	*result = NULL;
   4365 	return 0;
   4366 }
   4367 
   4368 
   4369 static int
   4370 udf_dirhash_fill(struct udf_node *dir_node)
   4371 {
   4372 	struct vnode *dvp = dir_node->vnode;
   4373 	struct udf_dirhash *dirh;
   4374 	struct file_entry    *fe  = dir_node->fe;
   4375 	struct extfile_entry *efe = dir_node->efe;
   4376 	struct fileid_desc *fid;
   4377 	struct dirent *dirent;
   4378 	uint64_t file_size, pre_diroffset, diroffset;
   4379 	uint32_t lb_size;
   4380 	int error;
   4381 
   4382 	/* make sure we have a dirhash to work on */
   4383 	dirh = dir_node->dir_hash;
   4384 	KASSERT(dirh);
   4385 	KASSERT(dirh->refcnt > 0);
   4386 
   4387 	if (dirh->flags & UDF_DIRH_BROKEN)
   4388 		return EIO;
   4389 	if (dirh->flags & UDF_DIRH_COMPLETE)
   4390 		return 0;
   4391 
   4392 	/* make sure we have a clean dirhash to add to */
   4393 	udf_dirhash_purge(dirh);
   4394 
   4395 	/* get directory filesize */
   4396 	if (fe) {
   4397 		file_size = udf_rw64(fe->inf_len);
   4398 	} else {
   4399 		assert(efe);
   4400 		file_size = udf_rw64(efe->inf_len);
   4401 	}
   4402 
   4403 	/* allocate temporary space for fid */
   4404 	lb_size = udf_rw32(dir_node->ump->logical_vol->lb_size);
   4405 	fid = malloc(lb_size, M_UDFTEMP, M_WAITOK);
   4406 
   4407 	/* allocate temporary space for dirent */
   4408 	dirent = malloc(sizeof(struct dirent), M_UDFTEMP, M_WAITOK);
   4409 
   4410 	error = 0;
   4411 	diroffset = 0;
   4412 	while (diroffset < file_size) {
   4413 		/* transfer a new fid/dirent */
   4414 		pre_diroffset = diroffset;
   4415 		error = udf_read_fid_stream(dvp, &diroffset, fid, dirent);
   4416 		if (error) {
   4417 			/* TODO what to do? continue but not add? */
   4418 			dirh->flags |= UDF_DIRH_BROKEN;
   4419 			udf_dirhash_purge(dirh);
   4420 			break;
   4421 		}
   4422 
   4423 		if ((fid->file_char & UDF_FILE_CHAR_DEL)) {
   4424 			/* register deleted extent for reuse */
   4425 			udf_dirhash_enter_freed(dir_node, pre_diroffset,
   4426 				udf_fidsize(fid));
   4427 		} else {
   4428 			/* append to the dirhash */
   4429 			udf_dirhash_enter(dir_node, fid, dirent, pre_diroffset,
   4430 				udf_fidsize(fid), 0);
   4431 		}
   4432 	}
   4433 	dirh->flags |= UDF_DIRH_COMPLETE;
   4434 
   4435 	free(fid, M_UDFTEMP);
   4436 	free(dirent, M_UDFTEMP);
   4437 
   4438 	return error;
   4439 }
   4440 
   4441 
   4442 /* --------------------------------------------------------------------- */
   4443 
   4444 /*
   4445  * Directory read and manipulation functions.
   4446  *
   4447  * Note that if the file is found, the cached diroffset position *before* the
   4448  * advance is remembered. Thus if the same filename is lookup again just after
   4449  * this lookup its immediately found.
   4450  */
   4451 
   4452 int
   4453 udf_lookup_name_in_dir(struct vnode *vp, const char *name, int namelen,
   4454        struct long_ad *icb_loc, int *found)
   4455 {
   4456 	struct udf_node  *dir_node = VTOI(vp);
   4457 	struct udf_dirhash_entry *dirh_ep;
   4458 	struct fileid_desc *fid;
   4459 	struct dirent *dirent;
   4460 	uint64_t diroffset;
   4461 	uint32_t lb_size;
   4462 	int hit, error;
   4463 
   4464 	/* set default return */
   4465 	*found = 0;
   4466 
   4467 	/* get our dirhash and make sure its read in */
   4468 	udf_dirhash_get(&dir_node->dir_hash);
   4469 	error = udf_dirhash_fill(dir_node);
   4470 	if (error) {
   4471 		udf_dirhash_put(dir_node->dir_hash);
   4472 		return error;
   4473 	}
   4474 
   4475 	/* allocate temporary space for fid */
   4476 	lb_size = udf_rw32(dir_node->ump->logical_vol->lb_size);
   4477 	fid     = malloc(lb_size, M_UDFTEMP, M_WAITOK);
   4478 	dirent  = malloc(sizeof(struct dirent), M_UDFTEMP, M_WAITOK);
   4479 
   4480 	DPRINTF(DIRHASH, ("dirhash_lookup looking for `%*.*s`\n",
   4481 		namelen, namelen, name));
   4482 
   4483 	/* search our dirhash hits */
   4484 	memset(icb_loc, 0, sizeof(*icb_loc));
   4485 	dirh_ep = NULL;
   4486 	for (;;) {
   4487 		hit = udf_dirhash_lookup(dir_node, name, namelen, &dirh_ep);
   4488 		/* if no hit, abort the search */
   4489 		if (!hit)
   4490 			break;
   4491 
   4492 		/* check this hit */
   4493 		diroffset = dirh_ep->offset;
   4494 
   4495 		/* transfer a new fid/dirent */
   4496 		error = udf_read_fid_stream(vp, &diroffset, fid, dirent);
   4497 		if (error)
   4498 			break;
   4499 
   4500 		DPRINTF(DIRHASH, ("dirhash_lookup\tchecking `%*.*s`\n",
   4501 			dirent->d_namlen, dirent->d_namlen, dirent->d_name));
   4502 
   4503 		/* see if its our entry */
   4504 		KASSERT(dirent->d_namlen == namelen);
   4505 		if (strncmp(dirent->d_name, name, namelen) == 0) {
   4506 			*found = 1;
   4507 			*icb_loc = fid->icb;
   4508 			break;
   4509 		}
   4510 	}
   4511 	free(fid, M_UDFTEMP);
   4512 	free(dirent, M_UDFTEMP);
   4513 
   4514 	udf_dirhash_put(dir_node->dir_hash);
   4515 
   4516 	return error;
   4517 }
   4518 
   4519 /* --------------------------------------------------------------------- */
   4520 
   4521 static int
   4522 udf_create_new_fe(struct udf_mount *ump, struct file_entry *fe, int file_type,
   4523 	struct long_ad *node_icb, struct long_ad *parent_icb,
   4524 	uint64_t parent_unique_id)
   4525 {
   4526 	struct timespec now;
   4527 	struct icb_tag *icb;
   4528 	struct filetimes_extattr_entry *ft_extattr;
   4529 	uint64_t unique_id;
   4530 	uint32_t fidsize, lb_num;
   4531 	uint8_t *bpos;
   4532 	int crclen, attrlen;
   4533 
   4534 	lb_num = udf_rw32(node_icb->loc.lb_num);
   4535 	udf_inittag(ump, &fe->tag, TAGID_FENTRY, lb_num);
   4536 	icb = &fe->icbtag;
   4537 
   4538 	/*
   4539 	 * Always use strategy type 4 unless on WORM wich we don't support
   4540 	 * (yet). Fill in defaults and set for internal allocation of data.
   4541 	 */
   4542 	icb->strat_type      = udf_rw16(4);
   4543 	icb->max_num_entries = udf_rw16(1);
   4544 	icb->file_type       = file_type;	/* 8 bit */
   4545 	icb->flags           = udf_rw16(UDF_ICB_INTERN_ALLOC);
   4546 
   4547 	fe->perm     = udf_rw32(0x7fff);	/* all is allowed   */
   4548 	fe->link_cnt = udf_rw16(0);		/* explicit setting */
   4549 
   4550 	fe->ckpoint  = udf_rw32(1);		/* user supplied file version */
   4551 
   4552 	vfs_timestamp(&now);
   4553 	udf_timespec_to_timestamp(&now, &fe->atime);
   4554 	udf_timespec_to_timestamp(&now, &fe->attrtime);
   4555 	udf_timespec_to_timestamp(&now, &fe->mtime);
   4556 
   4557 	udf_set_regid(&fe->imp_id, IMPL_NAME);
   4558 	udf_add_impl_regid(ump, &fe->imp_id);
   4559 
   4560 	unique_id = udf_advance_uniqueid(ump);
   4561 	fe->unique_id = udf_rw64(unique_id);
   4562 	fe->l_ea = udf_rw32(0);
   4563 
   4564 	/* create extended attribute to record our creation time */
   4565 	attrlen = UDF_FILETIMES_ATTR_SIZE(1);
   4566 	ft_extattr = malloc(attrlen, M_UDFTEMP, M_WAITOK);
   4567 	memset(ft_extattr, 0, attrlen);
   4568 	ft_extattr->hdr.type = udf_rw32(UDF_FILETIMES_ATTR_NO);
   4569 	ft_extattr->hdr.subtype = 1;	/* [4/48.10.5] */
   4570 	ft_extattr->hdr.a_l = udf_rw32(UDF_FILETIMES_ATTR_SIZE(1));
   4571 	ft_extattr->d_l     = udf_rw32(UDF_TIMESTAMP_SIZE); /* one item */
   4572 	ft_extattr->existence = UDF_FILETIMES_FILE_CREATION;
   4573 	udf_timespec_to_timestamp(&now, &ft_extattr->times[0]);
   4574 
   4575 	udf_extattr_insert_internal(ump, (union dscrptr *) fe,
   4576 		(struct extattr_entry *) ft_extattr);
   4577 	free(ft_extattr, M_UDFTEMP);
   4578 
   4579 	/* if its a directory, create '..' */
   4580 	bpos = (uint8_t *) fe->data + udf_rw32(fe->l_ea);
   4581 	fidsize = 0;
   4582 	if (file_type == UDF_ICB_FILETYPE_DIRECTORY) {
   4583 		fidsize = udf_create_parentfid(ump,
   4584 			(struct fileid_desc *) bpos, parent_icb,
   4585 			parent_unique_id);
   4586 	}
   4587 
   4588 	/* record fidlength information */
   4589 	fe->inf_len = udf_rw64(fidsize);
   4590 	fe->l_ad    = udf_rw32(fidsize);
   4591 	fe->logblks_rec = udf_rw64(0);		/* intern */
   4592 
   4593 	crclen  = sizeof(struct file_entry) - 1 - UDF_DESC_TAG_LENGTH;
   4594 	crclen += udf_rw32(fe->l_ea) + fidsize;
   4595 	fe->tag.desc_crc_len = udf_rw16(crclen);
   4596 
   4597 	(void) udf_validate_tag_and_crc_sums((union dscrptr *) fe);
   4598 
   4599 	return fidsize;
   4600 }
   4601 
   4602 /* --------------------------------------------------------------------- */
   4603 
   4604 static int
   4605 udf_create_new_efe(struct udf_mount *ump, struct extfile_entry *efe,
   4606 	int file_type, struct long_ad *node_icb, struct long_ad *parent_icb,
   4607 	uint64_t parent_unique_id)
   4608 {
   4609 	struct timespec now;
   4610 	struct icb_tag *icb;
   4611 	uint64_t unique_id;
   4612 	uint32_t fidsize, lb_num;
   4613 	uint8_t *bpos;
   4614 	int crclen;
   4615 
   4616 	lb_num = udf_rw32(node_icb->loc.lb_num);
   4617 	udf_inittag(ump, &efe->tag, TAGID_EXTFENTRY, lb_num);
   4618 	icb = &efe->icbtag;
   4619 
   4620 	/*
   4621 	 * Always use strategy type 4 unless on WORM wich we don't support
   4622 	 * (yet). Fill in defaults and set for internal allocation of data.
   4623 	 */
   4624 	icb->strat_type      = udf_rw16(4);
   4625 	icb->max_num_entries = udf_rw16(1);
   4626 	icb->file_type       = file_type;	/* 8 bit */
   4627 	icb->flags           = udf_rw16(UDF_ICB_INTERN_ALLOC);
   4628 
   4629 	efe->perm     = udf_rw32(0x7fff);	/* all is allowed   */
   4630 	efe->link_cnt = udf_rw16(0);		/* explicit setting */
   4631 
   4632 	efe->ckpoint  = udf_rw32(1);		/* user supplied file version */
   4633 
   4634 	vfs_timestamp(&now);
   4635 	udf_timespec_to_timestamp(&now, &efe->ctime);
   4636 	udf_timespec_to_timestamp(&now, &efe->atime);
   4637 	udf_timespec_to_timestamp(&now, &efe->attrtime);
   4638 	udf_timespec_to_timestamp(&now, &efe->mtime);
   4639 
   4640 	udf_set_regid(&efe->imp_id, IMPL_NAME);
   4641 	udf_add_impl_regid(ump, &efe->imp_id);
   4642 
   4643 	unique_id = udf_advance_uniqueid(ump);
   4644 	efe->unique_id = udf_rw64(unique_id);
   4645 	efe->l_ea = udf_rw32(0);
   4646 
   4647 	/* if its a directory, create '..' */
   4648 	bpos = (uint8_t *) efe->data + udf_rw32(efe->l_ea);
   4649 	fidsize = 0;
   4650 	if (file_type == UDF_ICB_FILETYPE_DIRECTORY) {
   4651 		fidsize = udf_create_parentfid(ump,
   4652 			(struct fileid_desc *) bpos, parent_icb,
   4653 			parent_unique_id);
   4654 	}
   4655 
   4656 	/* record fidlength information */
   4657 	efe->obj_size = udf_rw64(fidsize);
   4658 	efe->inf_len  = udf_rw64(fidsize);
   4659 	efe->l_ad     = udf_rw32(fidsize);
   4660 	efe->logblks_rec = udf_rw64(0);		/* intern */
   4661 
   4662 	crclen  = sizeof(struct extfile_entry) - 1 - UDF_DESC_TAG_LENGTH;
   4663 	crclen += udf_rw32(efe->l_ea) + fidsize;
   4664 	efe->tag.desc_crc_len = udf_rw16(crclen);
   4665 
   4666 	(void) udf_validate_tag_and_crc_sums((union dscrptr *) efe);
   4667 
   4668 	return fidsize;
   4669 }
   4670 
   4671 /* --------------------------------------------------------------------- */
   4672 
   4673 int
   4674 udf_dir_detach(struct udf_mount *ump, struct udf_node *dir_node,
   4675 	struct udf_node *udf_node, struct componentname *cnp)
   4676 {
   4677 	struct vnode *dvp = dir_node->vnode;
   4678 	struct udf_dirhash_entry *dirh_ep;
   4679 	struct file_entry    *fe  = dir_node->fe;
   4680 	struct extfile_entry *efe = dir_node->efe;
   4681 	struct fileid_desc *fid;
   4682 	struct dirent *dirent;
   4683 	uint64_t file_size, diroffset;
   4684 	uint32_t lb_size, fidsize;
   4685 	int found, error;
   4686 	char const *name  = cnp->cn_nameptr;
   4687 	int namelen = cnp->cn_namelen;
   4688 	int hit, refcnt;
   4689 
   4690 	/* get our dirhash and make sure its read in */
   4691 	udf_dirhash_get(&dir_node->dir_hash);
   4692 	error = udf_dirhash_fill(dir_node);
   4693 	if (error) {
   4694 		udf_dirhash_put(dir_node->dir_hash);
   4695 		return error;
   4696 	}
   4697 
   4698 	/* get directory filesize */
   4699 	if (fe) {
   4700 		file_size = udf_rw64(fe->inf_len);
   4701 	} else {
   4702 		assert(efe);
   4703 		file_size = udf_rw64(efe->inf_len);
   4704 	}
   4705 
   4706 	/* allocate temporary space for fid */
   4707 	lb_size = udf_rw32(dir_node->ump->logical_vol->lb_size);
   4708 	fid     = malloc(lb_size, M_UDFTEMP, M_WAITOK);
   4709 	dirent  = malloc(sizeof(struct dirent), M_UDFTEMP, M_WAITOK);
   4710 
   4711 	/* search our dirhash hits */
   4712 	found = 0;
   4713 	dirh_ep = NULL;
   4714 	for (;;) {
   4715 		hit = udf_dirhash_lookup(dir_node, name, namelen, &dirh_ep);
   4716 		/* if no hit, abort the search */
   4717 		if (!hit)
   4718 			break;
   4719 
   4720 		/* check this hit */
   4721 		diroffset = dirh_ep->offset;
   4722 
   4723 		/* transfer a new fid/dirent */
   4724 		error = udf_read_fid_stream(dvp, &diroffset, fid, dirent);
   4725 		if (error)
   4726 			break;
   4727 
   4728 		/* see if its our entry */
   4729 		KASSERT(dirent->d_namlen == namelen);
   4730 		if (strncmp(dirent->d_name, name, namelen) == 0) {
   4731 			found = 1;
   4732 			break;
   4733 		}
   4734 	}
   4735 
   4736 	if (!found)
   4737 		error = ENOENT;
   4738 	if (error)
   4739 		goto error_out;
   4740 
   4741 	/* mark deleted */
   4742 	fid->file_char |= UDF_FILE_CHAR_DEL;
   4743 #ifdef UDF_COMPLETE_DELETE
   4744 	memset(&fid->icb, 0, sizeof(fid->icb));
   4745 #endif
   4746 	(void) udf_validate_tag_and_crc_sums((union dscrptr *) fid);
   4747 
   4748 	/* get size of fid and compensate for the read_fid_stream advance */
   4749 	fidsize = udf_fidsize(fid);
   4750 	diroffset -= fidsize;
   4751 
   4752 	/* write out */
   4753 	error = vn_rdwr(UIO_WRITE, dir_node->vnode,
   4754 			fid, fidsize, diroffset,
   4755 			UIO_SYSSPACE, IO_ALTSEMANTICS | IO_NODELOCKED,
   4756 			FSCRED, NULL, NULL);
   4757 	if (error)
   4758 		goto error_out;
   4759 
   4760 	/* get reference count of attached node */
   4761 	if (udf_node->fe) {
   4762 		refcnt = udf_rw16(udf_node->fe->link_cnt);
   4763 	} else {
   4764 		KASSERT(udf_node->efe);
   4765 		refcnt = udf_rw16(udf_node->efe->link_cnt);
   4766 	}
   4767 #ifdef UDF_COMPLETE_DELETE
   4768 	/* substract reference counter in attached node */
   4769 	refcnt -= 1;
   4770 	if (udf_node->fe) {
   4771 		udf_node->fe->link_cnt = udf_rw16(refcnt);
   4772 	} else {
   4773 		udf_node->efe->link_cnt = udf_rw16(refcnt);
   4774 	}
   4775 
   4776 	/* prevent writeout when refcnt == 0 */
   4777 	if (refcnt == 0)
   4778 		udf_node->i_flags |= IN_DELETED;
   4779 
   4780 	if (fid->file_char & UDF_FILE_CHAR_DIR) {
   4781 		int drefcnt;
   4782 
   4783 		/* substract reference counter in directory node */
   4784 		/* note subtract 2 (?) for its was also backreferenced */
   4785 		if (dir_node->fe) {
   4786 			drefcnt  = udf_rw16(dir_node->fe->link_cnt);
   4787 			drefcnt -= 1;
   4788 			dir_node->fe->link_cnt = udf_rw16(drefcnt);
   4789 		} else {
   4790 			KASSERT(dir_node->efe);
   4791 			drefcnt  = udf_rw16(dir_node->efe->link_cnt);
   4792 			drefcnt -= 1;
   4793 			dir_node->efe->link_cnt = udf_rw16(drefcnt);
   4794 		}
   4795 	}
   4796 
   4797 	udf_node->i_flags |= IN_MODIFIED;
   4798 	dir_node->i_flags |= IN_MODIFIED;
   4799 #endif
   4800 	/* if it is/was a hardlink adjust the file count */
   4801 	if (refcnt > 0)
   4802 		udf_adjust_filecount(udf_node, -1);
   4803 
   4804 	/* remove from the dirhash */
   4805 	udf_dirhash_remove(dir_node, dirent, diroffset,
   4806 		udf_fidsize(fid));
   4807 
   4808 error_out:
   4809 	free(fid, M_UDFTEMP);
   4810 	free(dirent, M_UDFTEMP);
   4811 
   4812 	udf_dirhash_put(dir_node->dir_hash);
   4813 
   4814 	return error;
   4815 }
   4816 
   4817 /* --------------------------------------------------------------------- */
   4818 
   4819 /*
   4820  * We are not allowed to split the fid tag itself over an logical block so
   4821  * check the space remaining in the logical block.
   4822  *
   4823  * We try to select the smallest candidate for recycling or when none is
   4824  * found, append a new one at the end of the directory.
   4825  */
   4826 
   4827 int
   4828 udf_dir_attach(struct udf_mount *ump, struct udf_node *dir_node,
   4829 	struct udf_node *udf_node, struct vattr *vap, struct componentname *cnp)
   4830 {
   4831 	struct vnode *dvp = dir_node->vnode;
   4832 	struct udf_dirhash_entry *dirh_ep;
   4833 	struct fileid_desc   *fid;
   4834 	struct icb_tag       *icbtag;
   4835 	struct charspec osta_charspec;
   4836 	struct dirent   dirent;
   4837 	uint64_t unique_id, dir_size, diroffset;
   4838 	uint64_t fid_pos, end_fid_pos, chosen_fid_pos;
   4839 	uint32_t chosen_size, chosen_size_diff;
   4840 	int lb_size, lb_rest, fidsize, this_fidsize, size_diff;
   4841 	int file_char, refcnt, icbflags, addr_type, hit, error;
   4842 
   4843 	/* get our dirhash and make sure its read in */
   4844 	udf_dirhash_get(&dir_node->dir_hash);
   4845 	error = udf_dirhash_fill(dir_node);
   4846 	if (error) {
   4847 		udf_dirhash_put(dir_node->dir_hash);
   4848 		return error;
   4849 	}
   4850 
   4851 	/* get info */
   4852 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   4853 	udf_osta_charset(&osta_charspec);
   4854 
   4855 	if (dir_node->fe) {
   4856 		dir_size = udf_rw64(dir_node->fe->inf_len);
   4857 		icbtag   = &dir_node->fe->icbtag;
   4858 	} else {
   4859 		dir_size = udf_rw64(dir_node->efe->inf_len);
   4860 		icbtag   = &dir_node->efe->icbtag;
   4861 	}
   4862 
   4863 	icbflags   = udf_rw16(icbtag->flags);
   4864 	addr_type  = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK;
   4865 
   4866 	if (udf_node->fe) {
   4867 		unique_id = udf_rw64(udf_node->fe->unique_id);
   4868 		refcnt    = udf_rw16(udf_node->fe->link_cnt);
   4869 	} else {
   4870 		unique_id = udf_rw64(udf_node->efe->unique_id);
   4871 		refcnt    = udf_rw16(udf_node->efe->link_cnt);
   4872 	}
   4873 
   4874 	if (refcnt > 0) {
   4875 		unique_id = udf_advance_uniqueid(ump);
   4876 		udf_adjust_filecount(udf_node, 1);
   4877 	}
   4878 
   4879 	/* determine file characteristics */
   4880 	file_char = 0;	/* visible non deleted file and not stream metadata */
   4881 	if (vap->va_type == VDIR)
   4882 		file_char = UDF_FILE_CHAR_DIR;
   4883 
   4884 	/* malloc scrap buffer */
   4885 	fid = malloc(lb_size, M_TEMP, M_WAITOK);
   4886 	bzero(fid, lb_size);
   4887 
   4888 	/* calculate _minimum_ fid size */
   4889 	unix_to_udf_name((char *) fid->data, &fid->l_fi,
   4890 		cnp->cn_nameptr, cnp->cn_namelen, &osta_charspec);
   4891 	fidsize = UDF_FID_SIZE + fid->l_fi;
   4892 	fidsize = (fidsize + 3) & ~3;		/* multiple of 4 */
   4893 
   4894 	/* find position that will fit the FID */
   4895 	chosen_fid_pos   = dir_size;
   4896 	chosen_size      = 0;
   4897 	chosen_size_diff = UINT_MAX;
   4898 
   4899 	/* shut up gcc */
   4900 	dirent.d_namlen = 0;
   4901 
   4902 	/* search our dirhash hits */
   4903 	error = 0;
   4904 	dirh_ep = NULL;
   4905 	for (;;) {
   4906 		hit = udf_dirhash_lookup_freed(dir_node, fidsize, &dirh_ep);
   4907 		/* if no hit, abort the search */
   4908 		if (!hit)
   4909 			break;
   4910 
   4911 		/* check this hit for size */
   4912 		this_fidsize = dirh_ep->fid_size;
   4913 
   4914 		/* check this hit */
   4915 		fid_pos     = dirh_ep->offset;
   4916 		end_fid_pos = fid_pos + this_fidsize;
   4917 		size_diff   = this_fidsize - fidsize;
   4918 		lb_rest = lb_size - (end_fid_pos % lb_size);
   4919 
   4920 #ifndef UDF_COMPLETE_DELETE
   4921 		/* transfer a new fid/dirent */
   4922 		error = udf_read_fid_stream(vp, &fid_pos, fid, dirent);
   4923 		if (error)
   4924 			goto error_out;
   4925 
   4926 		/* only reuse entries that are wiped */
   4927 		/* check if the len + loc are marked zero */
   4928 		if (udf_rw32(fid->icb.len != 0))
   4929 			continue;
   4930 		if (udf_rw32(fid->icb.loc.lb_num) != 0)
   4931 			continue;
   4932 		if (udf_rw16(fid->icb.loc.part_num != 0))
   4933 			continue;
   4934 #endif	/* UDF_COMPLETE_DELETE */
   4935 
   4936 		/* select if not splitting the tag and its smaller */
   4937 		if ((size_diff >= 0)  &&
   4938 			(size_diff < chosen_size_diff) &&
   4939 			(lb_rest >= sizeof(struct desc_tag)))
   4940 		{
   4941 			/* UDF 2.3.4.2+3 specifies rules for iu size */
   4942 			if ((size_diff == 0) || (size_diff >= 32)) {
   4943 				chosen_fid_pos   = fid_pos;
   4944 				chosen_size      = this_fidsize;
   4945 				chosen_size_diff = size_diff;
   4946 			}
   4947 		}
   4948 	}
   4949 
   4950 
   4951 	/* extend directory if no other candidate found */
   4952 	if (chosen_size == 0) {
   4953 		chosen_fid_pos   = dir_size;
   4954 		chosen_size      = fidsize;
   4955 		chosen_size_diff = 0;
   4956 
   4957 		/* special case UDF 2.00+ 2.3.4.4, no splitting up fid tag */
   4958 		if (addr_type == UDF_ICB_INTERN_ALLOC) {
   4959 			/* pre-grow directory to see if we're to switch */
   4960 			udf_grow_node(dir_node, dir_size + chosen_size);
   4961 
   4962 			icbflags   = udf_rw16(icbtag->flags);
   4963 			addr_type  = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK;
   4964 		}
   4965 
   4966 		/* make sure the next fid desc_tag won't be splitted */
   4967 		if (addr_type != UDF_ICB_INTERN_ALLOC) {
   4968 			end_fid_pos = chosen_fid_pos + chosen_size;
   4969 			lb_rest = lb_size - (end_fid_pos % lb_size);
   4970 
   4971 			/* pad with implementation use regid if needed */
   4972 			if (lb_rest < sizeof(struct desc_tag))
   4973 				chosen_size += 32;
   4974 		}
   4975 	}
   4976 	chosen_size_diff = chosen_size - fidsize;
   4977 	diroffset = chosen_fid_pos + chosen_size;
   4978 
   4979 	/* populate the FID */
   4980 	memset(fid, 0, lb_size);
   4981 	udf_inittag(ump, &fid->tag, TAGID_FID, 0);
   4982 	fid->file_version_num    = udf_rw16(1);	/* UDF 2.3.4.1 */
   4983 	fid->file_char           = file_char;
   4984 	fid->icb                 = udf_node->loc;
   4985 	fid->icb.longad_uniqueid = udf_rw32((uint32_t) unique_id);
   4986 	fid->l_iu                = udf_rw16(0);
   4987 
   4988 	if (chosen_size > fidsize) {
   4989 		/* insert implementation-use regid to space it correctly */
   4990 		fid->l_iu = udf_rw16(chosen_size_diff);
   4991 
   4992 		/* set implementation use */
   4993 		udf_set_regid((struct regid *) fid->data, IMPL_NAME);
   4994 		udf_add_impl_regid(ump, (struct regid *) fid->data);
   4995 	}
   4996 
   4997 	/* fill in name */
   4998 	unix_to_udf_name((char *) fid->data + udf_rw16(fid->l_iu),
   4999 		&fid->l_fi, cnp->cn_nameptr, cnp->cn_namelen, &osta_charspec);
   5000 
   5001 	fid->tag.desc_crc_len = chosen_size - UDF_DESC_TAG_LENGTH;
   5002 	(void) udf_validate_tag_and_crc_sums((union dscrptr *) fid);
   5003 
   5004 	/* writeout FID/update parent directory */
   5005 	error = vn_rdwr(UIO_WRITE, dvp,
   5006 			fid, chosen_size, chosen_fid_pos,
   5007 			UIO_SYSSPACE, IO_ALTSEMANTICS | IO_NODELOCKED,
   5008 			FSCRED, NULL, NULL);
   5009 
   5010 	if (error)
   5011 		goto error_out;
   5012 
   5013 	/* add reference counter in attached node */
   5014 	if (udf_node->fe) {
   5015 		refcnt = udf_rw16(udf_node->fe->link_cnt);
   5016 		udf_node->fe->link_cnt = udf_rw16(refcnt+1);
   5017 	} else {
   5018 		KASSERT(udf_node->efe);
   5019 		refcnt = udf_rw16(udf_node->efe->link_cnt);
   5020 		udf_node->efe->link_cnt = udf_rw16(refcnt+1);
   5021 	}
   5022 
   5023 	/* mark not deleted if it was... just in case, but do warn */
   5024 	if (udf_node->i_flags & IN_DELETED) {
   5025 		printf("udf: warning, marking a file undeleted\n");
   5026 		udf_node->i_flags &= ~IN_DELETED;
   5027 	}
   5028 
   5029 	if (file_char & UDF_FILE_CHAR_DIR) {
   5030 		/* add reference counter in directory node for '..' */
   5031 		if (dir_node->fe) {
   5032 			refcnt = udf_rw16(dir_node->fe->link_cnt);
   5033 			refcnt++;
   5034 			dir_node->fe->link_cnt = udf_rw16(refcnt);
   5035 		} else {
   5036 			KASSERT(dir_node->efe);
   5037 			refcnt = udf_rw16(dir_node->efe->link_cnt);
   5038 			refcnt++;
   5039 			dir_node->efe->link_cnt = udf_rw16(refcnt);
   5040 		}
   5041 	}
   5042 
   5043 	/* append to the dirhash */
   5044 	dirent.d_namlen = cnp->cn_namelen;
   5045 	memcpy(dirent.d_name, cnp->cn_nameptr, cnp->cn_namelen);
   5046 	udf_dirhash_enter(dir_node, fid, &dirent, chosen_fid_pos,
   5047 		udf_fidsize(fid), 1);
   5048 
   5049 	/* note updates */
   5050 	udf_node->i_flags |= IN_CHANGE | IN_MODIFY; /* | IN_CREATE? */
   5051 	/* VN_KNOTE(udf_node,  ...) */
   5052 	udf_update(udf_node->vnode, NULL, NULL, NULL, 0);
   5053 
   5054 error_out:
   5055 	free(fid, M_TEMP);
   5056 
   5057 	udf_dirhash_put(dir_node->dir_hash);
   5058 
   5059 	return error;
   5060 }
   5061 
   5062 /* --------------------------------------------------------------------- */
   5063 
   5064 /*
   5065  * Each node can have an attached streamdir node though not recursively. These
   5066  * are otherwise known as named substreams/named extended attributes that have
   5067  * no size limitations.
   5068  *
   5069  * `Normal' extended attributes are indicated with a number and are recorded
   5070  * in either the fe/efe descriptor itself for small descriptors or recorded in
   5071  * the attached extended attribute file. Since these spaces can get
   5072  * fragmented, care ought to be taken.
   5073  *
   5074  * Since the size of the space reserved for allocation descriptors is limited,
   5075  * there is a mechanim provided for extending this space; this is done by a
   5076  * special extent to allow schrinking of the allocations without breaking the
   5077  * linkage to the allocation extent descriptor.
   5078  */
   5079 
   5080 int
   5081 udf_get_node(struct udf_mount *ump, struct long_ad *node_icb_loc,
   5082 	     struct udf_node **udf_noderes)
   5083 {
   5084 	union dscrptr   *dscr;
   5085 	struct udf_node *udf_node;
   5086 	struct vnode    *nvp;
   5087 	struct long_ad   icb_loc, last_fe_icb_loc;
   5088 	uint64_t file_size;
   5089 	uint32_t lb_size, sector, dummy;
   5090 	uint8_t  *file_data;
   5091 	int udf_file_type, dscr_type, strat, strat4096, needs_indirect;
   5092 	int slot, eof, error;
   5093 
   5094 	DPRINTF(NODE, ("udf_get_node called\n"));
   5095 	*udf_noderes = udf_node = NULL;
   5096 
   5097 	/* lock to disallow simultanious creation of same udf_node */
   5098 	mutex_enter(&ump->get_node_lock);
   5099 
   5100 	DPRINTF(NODE, ("\tlookup in hash table\n"));
   5101 	/* lookup in hash table */
   5102 	assert(ump);
   5103 	assert(node_icb_loc);
   5104 	udf_node = udf_hash_lookup(ump, node_icb_loc);
   5105 	if (udf_node) {
   5106 		DPRINTF(NODE, ("\tgot it from the hash!\n"));
   5107 		/* vnode is returned locked */
   5108 		*udf_noderes = udf_node;
   5109 		mutex_exit(&ump->get_node_lock);
   5110 		return 0;
   5111 	}
   5112 
   5113 	/* garbage check: translate udf_node_icb_loc to sectornr */
   5114 	error = udf_translate_vtop(ump, node_icb_loc, &sector, &dummy);
   5115 	if (error) {
   5116 		/* no use, this will fail anyway */
   5117 		mutex_exit(&ump->get_node_lock);
   5118 		return EINVAL;
   5119 	}
   5120 
   5121 	/* build udf_node (do initialise!) */
   5122 	udf_node = pool_get(&udf_node_pool, PR_WAITOK);
   5123 	memset(udf_node, 0, sizeof(struct udf_node));
   5124 
   5125 	DPRINTF(NODE, ("\tget new vnode\n"));
   5126 	/* give it a vnode */
   5127 	error = getnewvnode(VT_UDF, ump->vfs_mountp, udf_vnodeop_p, &nvp);
   5128         if (error) {
   5129 		pool_put(&udf_node_pool, udf_node);
   5130 		mutex_exit(&ump->get_node_lock);
   5131 		return error;
   5132 	}
   5133 
   5134 	/* always return locked vnode */
   5135 	if ((error = vn_lock(nvp, LK_EXCLUSIVE | LK_RETRY))) {
   5136 		/* recycle vnode and unlock; simultanious will fail too */
   5137 		ungetnewvnode(nvp);
   5138 		mutex_exit(&ump->get_node_lock);
   5139 		return error;
   5140 	}
   5141 
   5142 	/* initialise crosslinks, note location of fe/efe for hashing */
   5143 	udf_node->ump    =  ump;
   5144 	udf_node->vnode  =  nvp;
   5145 	nvp->v_data      =  udf_node;
   5146 	udf_node->loc    = *node_icb_loc;
   5147 	udf_node->lockf  =  0;
   5148 	mutex_init(&udf_node->node_mutex, MUTEX_DEFAULT, IPL_NONE);
   5149 	cv_init(&udf_node->node_lock, "udf_nlk");
   5150 	genfs_node_init(nvp, &udf_genfsops);	/* inititise genfs */
   5151 	udf_node->outstanding_bufs = 0;
   5152 	udf_node->outstanding_nodedscr = 0;
   5153 
   5154 	/* insert into the hash lookup */
   5155 	udf_register_node(udf_node);
   5156 
   5157 	/* safe to unlock, the entry is in the hash table, vnode is locked */
   5158 	mutex_exit(&ump->get_node_lock);
   5159 
   5160 	icb_loc = *node_icb_loc;
   5161 	needs_indirect = 0;
   5162 	strat4096 = 0;
   5163 	udf_file_type = UDF_ICB_FILETYPE_UNKNOWN;
   5164 	file_size = 0;
   5165 	file_data = NULL;
   5166 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   5167 
   5168 	DPRINTF(NODE, ("\tstart reading descriptors\n"));
   5169 	do {
   5170 		/* try to read in fe/efe */
   5171 		error = udf_read_logvol_dscr(ump, &icb_loc, &dscr);
   5172 
   5173 		/* blank sector marks end of sequence, check this */
   5174 		if ((dscr == NULL) &&  (!strat4096))
   5175 			error = ENOENT;
   5176 
   5177 		/* break if read error or blank sector */
   5178 		if (error || (dscr == NULL))
   5179 			break;
   5180 
   5181 		/* process descriptor based on the descriptor type */
   5182 		dscr_type = udf_rw16(dscr->tag.id);
   5183 		DPRINTF(NODE, ("\tread descriptor %d\n", dscr_type));
   5184 
   5185 		/* if dealing with an indirect entry, follow the link */
   5186 		if (dscr_type == TAGID_INDIRECTENTRY) {
   5187 			needs_indirect = 0;
   5188 			udf_free_logvol_dscr(ump, &icb_loc, dscr);
   5189 			icb_loc = dscr->inde.indirect_icb;
   5190 			continue;
   5191 		}
   5192 
   5193 		/* only file entries and extended file entries allowed here */
   5194 		if ((dscr_type != TAGID_FENTRY) &&
   5195 		    (dscr_type != TAGID_EXTFENTRY)) {
   5196 			udf_free_logvol_dscr(ump, &icb_loc, dscr);
   5197 			error = ENOENT;
   5198 			break;
   5199 		}
   5200 
   5201 		KASSERT(udf_tagsize(dscr, lb_size) == lb_size);
   5202 
   5203 		/* choose this one */
   5204 		last_fe_icb_loc = icb_loc;
   5205 
   5206 		/* record and process/update (ext)fentry */
   5207 		file_data = NULL;
   5208 		if (dscr_type == TAGID_FENTRY) {
   5209 			if (udf_node->fe)
   5210 				udf_free_logvol_dscr(ump, &last_fe_icb_loc,
   5211 					udf_node->fe);
   5212 			udf_node->fe  = &dscr->fe;
   5213 			strat = udf_rw16(udf_node->fe->icbtag.strat_type);
   5214 			udf_file_type = udf_node->fe->icbtag.file_type;
   5215 			file_size = udf_rw64(udf_node->fe->inf_len);
   5216 			file_data = udf_node->fe->data;
   5217 		} else {
   5218 			if (udf_node->efe)
   5219 				udf_free_logvol_dscr(ump, &last_fe_icb_loc,
   5220 					udf_node->efe);
   5221 			udf_node->efe = &dscr->efe;
   5222 			strat = udf_rw16(udf_node->efe->icbtag.strat_type);
   5223 			udf_file_type = udf_node->efe->icbtag.file_type;
   5224 			file_size = udf_rw64(udf_node->efe->inf_len);
   5225 			file_data = udf_node->efe->data;
   5226 		}
   5227 
   5228 		/* check recording strategy (structure) */
   5229 
   5230 		/*
   5231 		 * Strategy 4096 is a daisy linked chain terminating with an
   5232 		 * unrecorded sector or a TERM descriptor. The next
   5233 		 * descriptor is to be found in the sector that follows the
   5234 		 * current sector.
   5235 		 */
   5236 		if (strat == 4096) {
   5237 			strat4096 = 1;
   5238 			needs_indirect = 1;
   5239 
   5240 			icb_loc.loc.lb_num = udf_rw32(icb_loc.loc.lb_num) + 1;
   5241 		}
   5242 
   5243 		/*
   5244 		 * Strategy 4 is the normal strategy and terminates, but if
   5245 		 * we're in strategy 4096, we can't have strategy 4 mixed in
   5246 		 */
   5247 
   5248 		if (strat == 4) {
   5249 			if (strat4096) {
   5250 				error = EINVAL;
   5251 				break;
   5252 			}
   5253 			break;		/* done */
   5254 		}
   5255 	} while (!error);
   5256 
   5257 	/* first round of cleanup code */
   5258 	if (error) {
   5259 		DPRINTF(NODE, ("\tnode fe/efe failed!\n"));
   5260 		/* recycle udf_node */
   5261 		udf_dispose_node(udf_node);
   5262 
   5263 		vlockmgr(nvp->v_vnlock, LK_RELEASE);
   5264 		nvp->v_data = NULL;
   5265 		ungetnewvnode(nvp);
   5266 
   5267 		return EINVAL;		/* error code ok? */
   5268 	}
   5269 	DPRINTF(NODE, ("\tnode fe/efe read in fine\n"));
   5270 
   5271 	/* assert no references to dscr anymore beyong this point */
   5272 	assert((udf_node->fe) || (udf_node->efe));
   5273 	dscr = NULL;
   5274 
   5275 	/*
   5276 	 * Remember where to record an updated version of the descriptor. If
   5277 	 * there is a sequence of indirect entries, icb_loc will have been
   5278 	 * updated. Its the write disipline to allocate new space and to make
   5279 	 * sure the chain is maintained.
   5280 	 *
   5281 	 * `needs_indirect' flags if the next location is to be filled with
   5282 	 * with an indirect entry.
   5283 	 */
   5284 	udf_node->write_loc = icb_loc;
   5285 	udf_node->needs_indirect = needs_indirect;
   5286 
   5287 	/*
   5288 	 * Go trough all allocations extents of this descriptor and when
   5289 	 * encountering a redirect read in the allocation extension. These are
   5290 	 * daisy-chained.
   5291 	 */
   5292 	UDF_LOCK_NODE(udf_node, 0);
   5293 	udf_node->num_extensions = 0;
   5294 
   5295 	error   = 0;
   5296 	slot    = 0;
   5297 	for (;;) {
   5298 		udf_get_adslot(udf_node, slot, &icb_loc, &eof);
   5299 		DPRINTF(ADWLK, ("slot %d, eof = %d, flags = %d, len = %d, "
   5300 			"lb_num = %d, part = %d\n", slot, eof,
   5301 			UDF_EXT_FLAGS(udf_rw32(icb_loc.len)),
   5302 			UDF_EXT_LEN(udf_rw32(icb_loc.len)),
   5303 			udf_rw32(icb_loc.loc.lb_num),
   5304 			udf_rw16(icb_loc.loc.part_num)));
   5305 		if (eof)
   5306 			break;
   5307 		slot++;
   5308 
   5309 		if (UDF_EXT_FLAGS(udf_rw32(icb_loc.len)) != UDF_EXT_REDIRECT)
   5310 			continue;
   5311 
   5312 		DPRINTF(NODE, ("\tgot redirect extent\n"));
   5313 		if (udf_node->num_extensions >= UDF_MAX_ALLOC_EXTENTS) {
   5314 			DPRINTF(ALLOC, ("udf_get_node: implementation limit, "
   5315 					"too many allocation extensions on "
   5316 					"udf_node\n"));
   5317 			error = EINVAL;
   5318 			break;
   5319 		}
   5320 
   5321 		/* length can only be *one* lb : UDF 2.50/2.3.7.1 */
   5322 		if (UDF_EXT_LEN(udf_rw32(icb_loc.len)) != lb_size) {
   5323 			DPRINTF(ALLOC, ("udf_get_node: bad allocation "
   5324 					"extension size in udf_node\n"));
   5325 			error = EINVAL;
   5326 			break;
   5327 		}
   5328 
   5329 		DPRINTF(NODE, ("read allocation extent at lb_num %d\n",
   5330 			UDF_EXT_LEN(udf_rw32(icb_loc.loc.lb_num))));
   5331 		/* load in allocation extent */
   5332 		error = udf_read_logvol_dscr(ump, &icb_loc, &dscr);
   5333 		if (error || (dscr == NULL))
   5334 			break;
   5335 
   5336 		/* process read-in descriptor */
   5337 		dscr_type = udf_rw16(dscr->tag.id);
   5338 
   5339 		if (dscr_type != TAGID_ALLOCEXTENT) {
   5340 			udf_free_logvol_dscr(ump, &icb_loc, dscr);
   5341 			error = ENOENT;
   5342 			break;
   5343 		}
   5344 
   5345 		DPRINTF(NODE, ("\trecording redirect extent\n"));
   5346 		udf_node->ext[udf_node->num_extensions] = &dscr->aee;
   5347 		udf_node->ext_loc[udf_node->num_extensions] = icb_loc;
   5348 
   5349 		udf_node->num_extensions++;
   5350 
   5351 	} /* while */
   5352 	UDF_UNLOCK_NODE(udf_node, 0);
   5353 
   5354 	/* second round of cleanup code */
   5355 	if (error) {
   5356 		/* recycle udf_node */
   5357 		udf_dispose_node(udf_node);
   5358 
   5359 		vlockmgr(nvp->v_vnlock, LK_RELEASE);
   5360 		nvp->v_data = NULL;
   5361 		ungetnewvnode(nvp);
   5362 
   5363 		return EINVAL;		/* error code ok? */
   5364 	}
   5365 
   5366 	DPRINTF(NODE, ("\tnode read in fine\n"));
   5367 
   5368 	/*
   5369 	 * Translate UDF filetypes into vnode types.
   5370 	 *
   5371 	 * Systemfiles like the meta main and mirror files are not treated as
   5372 	 * normal files, so we type them as having no type. UDF dictates that
   5373 	 * they are not allowed to be visible.
   5374 	 */
   5375 
   5376 	switch (udf_file_type) {
   5377 	case UDF_ICB_FILETYPE_DIRECTORY :
   5378 	case UDF_ICB_FILETYPE_STREAMDIR :
   5379 		nvp->v_type = VDIR;
   5380 		break;
   5381 	case UDF_ICB_FILETYPE_BLOCKDEVICE :
   5382 		nvp->v_type = VBLK;
   5383 		break;
   5384 	case UDF_ICB_FILETYPE_CHARDEVICE :
   5385 		nvp->v_type = VCHR;
   5386 		break;
   5387 	case UDF_ICB_FILETYPE_SOCKET :
   5388 		nvp->v_type = VSOCK;
   5389 		break;
   5390 	case UDF_ICB_FILETYPE_FIFO :
   5391 		nvp->v_type = VFIFO;
   5392 		break;
   5393 	case UDF_ICB_FILETYPE_SYMLINK :
   5394 		nvp->v_type = VLNK;
   5395 		break;
   5396 	case UDF_ICB_FILETYPE_VAT :
   5397 	case UDF_ICB_FILETYPE_META_MAIN :
   5398 	case UDF_ICB_FILETYPE_META_MIRROR :
   5399 		nvp->v_type = VNON;
   5400 		break;
   5401 	case UDF_ICB_FILETYPE_RANDOMACCESS :
   5402 	case UDF_ICB_FILETYPE_REALTIME :
   5403 		nvp->v_type = VREG;
   5404 		break;
   5405 	default:
   5406 		/* YIKES, something else */
   5407 		nvp->v_type = VNON;
   5408 	}
   5409 
   5410 	/* TODO specfs, fifofs etc etc. vnops setting */
   5411 
   5412 	/* don't forget to set vnode's v_size */
   5413 	uvm_vnp_setsize(nvp, file_size);
   5414 
   5415 	/* TODO ext attr and streamdir udf_nodes */
   5416 
   5417 	*udf_noderes = udf_node;
   5418 
   5419 	return 0;
   5420 }
   5421 
   5422 /* --------------------------------------------------------------------- */
   5423 
   5424 int
   5425 udf_writeout_node(struct udf_node *udf_node, int waitfor)
   5426 {
   5427 	union dscrptr *dscr;
   5428 	struct long_ad *loc;
   5429 	int extnr, flags, error;
   5430 
   5431 	DPRINTF(NODE, ("udf_writeout_node called\n"));
   5432 
   5433 	KASSERT(udf_node->outstanding_bufs == 0);
   5434 	KASSERT(udf_node->outstanding_nodedscr == 0);
   5435 
   5436 	KASSERT(LIST_EMPTY(&udf_node->vnode->v_dirtyblkhd));
   5437 
   5438 	if (udf_node->i_flags & IN_DELETED) {
   5439 		DPRINTF(NODE, ("\tnode deleted; not writing out\n"));
   5440 		return 0;
   5441 	}
   5442 
   5443 	/* lock node */
   5444 	flags = waitfor ? 0 : IN_CALLBACK_ULK;
   5445 	UDF_LOCK_NODE(udf_node, flags);
   5446 
   5447 	/* at least one descriptor writeout */
   5448 	udf_node->outstanding_nodedscr = 1;
   5449 
   5450 	/* we're going to write out the descriptor so clear the flags */
   5451 	udf_node->i_flags &= ~(IN_MODIFIED | IN_ACCESSED);
   5452 
   5453 	/* if we were rebuild, write out the allocation extents */
   5454 	if (udf_node->i_flags & IN_NODE_REBUILD) {
   5455 		/* mark outstanding node descriptors and issue them */
   5456 		udf_node->outstanding_nodedscr += udf_node->num_extensions;
   5457 		for (extnr = 0; extnr < udf_node->num_extensions; extnr++) {
   5458 			loc = &udf_node->ext_loc[extnr];
   5459 			dscr = (union dscrptr *) udf_node->ext[extnr];
   5460 			error = udf_write_logvol_dscr(udf_node, dscr, loc, 0);
   5461 			if (error)
   5462 				return error;
   5463 		}
   5464 		/* mark allocation extents written out */
   5465 		udf_node->i_flags &= ~(IN_NODE_REBUILD);
   5466 	}
   5467 
   5468 	if (udf_node->fe) {
   5469 		KASSERT(udf_node->efe == NULL);
   5470 		dscr = (union dscrptr *) udf_node->fe;
   5471 	} else {
   5472 		KASSERT(udf_node->efe);
   5473 		KASSERT(udf_node->fe == NULL);
   5474 		dscr = (union dscrptr *) udf_node->efe;
   5475 	}
   5476 	KASSERT(dscr);
   5477 
   5478 	loc = &udf_node->write_loc;
   5479 	error = udf_write_logvol_dscr(udf_node, dscr, loc, waitfor);
   5480 	return error;
   5481 }
   5482 
   5483 /* --------------------------------------------------------------------- */
   5484 
   5485 int
   5486 udf_dispose_node(struct udf_node *udf_node)
   5487 {
   5488 	struct vnode *vp;
   5489 	int extnr;
   5490 
   5491 	DPRINTF(NODE, ("udf_dispose_node called on node %p\n", udf_node));
   5492 	if (!udf_node) {
   5493 		DPRINTF(NODE, ("UDF: Dispose node on node NULL, ignoring\n"));
   5494 		return 0;
   5495 	}
   5496 
   5497 	vp  = udf_node->vnode;
   5498 #ifdef DIAGNOSTIC
   5499 	if (vp->v_numoutput)
   5500 		panic("disposing UDF node with pending I/O's, udf_node = %p, "
   5501 				"v_numoutput = %d", udf_node, vp->v_numoutput);
   5502 #endif
   5503 
   5504 	/* wait until out of sync (just in case we happen to stumble over one */
   5505 	KASSERT(!mutex_owned(&mntvnode_lock));
   5506 	mutex_enter(&mntvnode_lock);
   5507 	while (udf_node->i_flags & IN_SYNCED) {
   5508 		cv_timedwait(&udf_node->ump->dirtynodes_cv, &mntvnode_lock,
   5509 			hz/16);
   5510 	}
   5511 	mutex_exit(&mntvnode_lock);
   5512 
   5513 	/* TODO extended attributes and streamdir */
   5514 
   5515 	/* remove dirhash if present */
   5516 	udf_dirhash_destroy(&udf_node->dir_hash);
   5517 
   5518 	/* remove from our hash lookup table */
   5519 	udf_deregister_node(udf_node);
   5520 
   5521 	/* destroy our lock */
   5522 	mutex_destroy(&udf_node->node_mutex);
   5523 	cv_destroy(&udf_node->node_lock);
   5524 
   5525 	/* dissociate our udf_node from the vnode */
   5526 	genfs_node_destroy(udf_node->vnode);
   5527 	vp->v_data = NULL;
   5528 
   5529 	/* free associated memory and the node itself */
   5530 	for (extnr = 0; extnr < udf_node->num_extensions; extnr++) {
   5531 		udf_free_logvol_dscr(udf_node->ump, &udf_node->ext_loc[extnr],
   5532 			udf_node->ext[extnr]);
   5533 		udf_node->ext[extnr] = (void *) 0xdeadcccc;
   5534 	}
   5535 
   5536 	if (udf_node->fe)
   5537 		udf_free_logvol_dscr(udf_node->ump, &udf_node->loc,
   5538 			udf_node->fe);
   5539 	if (udf_node->efe)
   5540 		udf_free_logvol_dscr(udf_node->ump, &udf_node->loc,
   5541 			udf_node->efe);
   5542 
   5543 	udf_node->fe  = (void *) 0xdeadaaaa;
   5544 	udf_node->efe = (void *) 0xdeadbbbb;
   5545 	udf_node->ump = (void *) 0xdeadbeef;
   5546 	pool_put(&udf_node_pool, udf_node);
   5547 
   5548 	return 0;
   5549 }
   5550 
   5551 
   5552 
   5553 /*
   5554  * create a new node using the specified vnodeops, vap and cnp but with the
   5555  * udf_file_type. This allows special files to be created. Use with care.
   5556  */
   5557 
   5558 static int
   5559 udf_create_node_raw(struct vnode *dvp, struct vnode **vpp, int udf_file_type,
   5560 	int (**vnodeops)(void *), struct vattr *vap, struct componentname *cnp)
   5561 {
   5562 	union dscrptr *dscr;
   5563 	struct udf_node *dir_node = VTOI(dvp);;
   5564 	struct udf_node *udf_node;
   5565 	struct udf_mount *ump = dir_node->ump;
   5566 	struct vnode *nvp;
   5567 	struct long_ad node_icb_loc;
   5568 	uint64_t parent_unique_id;
   5569 	uint64_t lmapping;
   5570 	uint32_t lb_size, lb_num;
   5571 	uint16_t vpart_num;
   5572 	uid_t uid;
   5573 	gid_t gid, parent_gid;
   5574 	int fid_size, error;
   5575 
   5576 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   5577 	*vpp = NULL;
   5578 
   5579 	/* allocate vnode */
   5580 	error = getnewvnode(VT_UDF, ump->vfs_mountp, vnodeops, &nvp);
   5581         if (error)
   5582 		return error;
   5583 
   5584 	/* lock node */
   5585 	error = vn_lock(nvp, LK_EXCLUSIVE | LK_RETRY);
   5586 	if (error) {
   5587 		nvp->v_data = NULL;
   5588 		ungetnewvnode(nvp);
   5589 		return error;
   5590 	}
   5591 
   5592 	/* get disc allocation for one logical block */
   5593 	vpart_num = ump->node_part;
   5594 	error = udf_pre_allocate_space(ump, UDF_C_NODE, 1,
   5595 			vpart_num, &lmapping);
   5596 	lb_num = lmapping;
   5597 	if (error) {
   5598 		vlockmgr(nvp->v_vnlock, LK_RELEASE);
   5599 		ungetnewvnode(nvp);
   5600 		return error;
   5601 	}
   5602 
   5603 	/* initialise pointer to location */
   5604 	memset(&node_icb_loc, 0, sizeof(struct long_ad));
   5605 	node_icb_loc.len = lb_size;
   5606 	node_icb_loc.loc.lb_num   = udf_rw32(lb_num);
   5607 	node_icb_loc.loc.part_num = udf_rw16(vpart_num);
   5608 
   5609 	/* build udf_node (do initialise!) */
   5610 	udf_node = pool_get(&udf_node_pool, PR_WAITOK);
   5611 	memset(udf_node, 0, sizeof(struct udf_node));
   5612 
   5613 	/* initialise crosslinks, note location of fe/efe for hashing */
   5614 	/* bugalert: synchronise with udf_get_node() */
   5615 	udf_node->ump       = ump;
   5616 	udf_node->vnode     = nvp;
   5617 	nvp->v_data         = udf_node;
   5618 	udf_node->loc       = node_icb_loc;
   5619 	udf_node->write_loc = node_icb_loc;
   5620 	udf_node->lockf     = 0;
   5621 	mutex_init(&udf_node->node_mutex, MUTEX_DEFAULT, IPL_NONE);
   5622 	cv_init(&udf_node->node_lock, "udf_nlk");
   5623 	udf_node->outstanding_bufs = 0;
   5624 	udf_node->outstanding_nodedscr = 0;
   5625 
   5626 	/* initialise genfs */
   5627 	genfs_node_init(nvp, &udf_genfsops);
   5628 
   5629 	/* insert into the hash lookup */
   5630 	udf_register_node(udf_node);
   5631 
   5632 	/* get parent's unique ID for refering '..' if its a directory */
   5633 	if (dir_node->fe) {
   5634 		parent_unique_id = udf_rw64(dir_node->fe->unique_id);
   5635 		parent_gid       = (gid_t) udf_rw32(dir_node->fe->gid);
   5636 	} else {
   5637 		parent_unique_id = udf_rw64(dir_node->efe->unique_id);
   5638 		parent_gid       = (gid_t) udf_rw32(dir_node->efe->gid);
   5639 	}
   5640 
   5641 	/* get descriptor */
   5642 	udf_create_logvol_dscr(ump, udf_node, &node_icb_loc, &dscr);
   5643 
   5644 	/* choose a fe or an efe for it */
   5645 	if (ump->logical_vol->tag.descriptor_ver == 2) {
   5646 		udf_node->fe = &dscr->fe;
   5647 		fid_size = udf_create_new_fe(ump, udf_node->fe,
   5648 			udf_file_type, &udf_node->loc,
   5649 			&dir_node->loc, parent_unique_id);
   5650 		/* TODO add extended attribute for creation time */
   5651 	} else {
   5652 		udf_node->efe = &dscr->efe;
   5653 		fid_size = udf_create_new_efe(ump, udf_node->efe,
   5654 			udf_file_type, &udf_node->loc,
   5655 			&dir_node->loc, parent_unique_id);
   5656 	}
   5657 	KASSERT(dscr->tag.tag_loc == udf_node->loc.loc.lb_num);
   5658 
   5659 	/* update vnode's size and type */
   5660 	nvp->v_type = vap->va_type;
   5661 	uvm_vnp_setsize(nvp, fid_size);
   5662 
   5663 	/* set access mode */
   5664 	udf_setaccessmode(udf_node, vap->va_mode);
   5665 
   5666 	/* set ownership */
   5667 	uid = kauth_cred_geteuid(cnp->cn_cred);
   5668 	gid = parent_gid;
   5669 	udf_setownership(udf_node, uid, gid);
   5670 
   5671 	error = udf_dir_attach(ump, dir_node, udf_node, vap, cnp);
   5672 	if (error) {
   5673 		/* free disc allocation for node */
   5674 		udf_free_allocated_space(ump, lb_num, vpart_num, 1);
   5675 
   5676 		/* recycle udf_node */
   5677 		udf_dispose_node(udf_node);
   5678 		vput(nvp);
   5679 
   5680 		*vpp = NULL;
   5681 		return error;
   5682 	}
   5683 
   5684 	/* adjust file count */
   5685 	udf_adjust_filecount(udf_node, 1);
   5686 
   5687 	/* return result */
   5688 	*vpp = nvp;
   5689 
   5690 	return 0;
   5691 }
   5692 
   5693 
   5694 int
   5695 udf_create_node(struct vnode *dvp, struct vnode **vpp, struct vattr *vap,
   5696 	struct componentname *cnp)
   5697 {
   5698 	int (**vnodeops)(void *);
   5699 	int udf_file_type;
   5700 
   5701 	DPRINTF(NODE, ("udf_create_node called\n"));
   5702 
   5703 	/* what type are we creating ? */
   5704 	vnodeops = udf_vnodeop_p;
   5705 	/* start with a default */
   5706 	udf_file_type = UDF_ICB_FILETYPE_RANDOMACCESS;
   5707 
   5708 	*vpp = NULL;
   5709 
   5710 	switch (vap->va_type) {
   5711 	case VREG :
   5712 		udf_file_type = UDF_ICB_FILETYPE_RANDOMACCESS;
   5713 		break;
   5714 	case VDIR :
   5715 		udf_file_type = UDF_ICB_FILETYPE_DIRECTORY;
   5716 		break;
   5717 	case VLNK :
   5718 		udf_file_type = UDF_ICB_FILETYPE_SYMLINK;
   5719 		break;
   5720 	case VBLK :
   5721 		udf_file_type = UDF_ICB_FILETYPE_BLOCKDEVICE;
   5722 		/* specfs */
   5723 		return ENOTSUP;
   5724 		break;
   5725 	case VCHR :
   5726 		udf_file_type = UDF_ICB_FILETYPE_CHARDEVICE;
   5727 		/* specfs */
   5728 		return ENOTSUP;
   5729 		break;
   5730 	case VFIFO :
   5731 		udf_file_type = UDF_ICB_FILETYPE_FIFO;
   5732 		/* specfs */
   5733 		return ENOTSUP;
   5734 		break;
   5735 	case VSOCK :
   5736 		udf_file_type = UDF_ICB_FILETYPE_SOCKET;
   5737 		/* specfs */
   5738 		return ENOTSUP;
   5739 		break;
   5740 	case VNON :
   5741 	case VBAD :
   5742 	default :
   5743 		/* nothing; can we even create these? */
   5744 		return EINVAL;
   5745 	}
   5746 
   5747 	return udf_create_node_raw(dvp, vpp, udf_file_type, vnodeops, vap, cnp);
   5748 }
   5749 
   5750 /* --------------------------------------------------------------------- */
   5751 
   5752 static void
   5753 udf_free_descriptor_space(struct udf_node *udf_node, struct long_ad *loc, void *mem)
   5754 {
   5755 	struct udf_mount *ump = udf_node->ump;
   5756 	uint32_t lb_size, lb_num, len, num_lb;
   5757 	uint16_t vpart_num;
   5758 
   5759 	/* is there really one? */
   5760 	if (mem == NULL)
   5761 		return;
   5762 
   5763 	/* got a descriptor here */
   5764 	len       = UDF_EXT_LEN(udf_rw32(loc->len));
   5765 	lb_num    = udf_rw32(loc->loc.lb_num);
   5766 	vpart_num = udf_rw16(loc->loc.part_num);
   5767 
   5768 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   5769 	num_lb = (len + lb_size -1) / lb_size;
   5770 
   5771 	udf_free_allocated_space(ump, lb_num, vpart_num, num_lb);
   5772 }
   5773 
   5774 void
   5775 udf_delete_node(struct udf_node *udf_node)
   5776 {
   5777 	void *dscr;
   5778 	struct udf_mount *ump;
   5779 	struct long_ad *loc;
   5780 	int extnr, lvint, dummy;
   5781 
   5782 	ump = udf_node->ump;
   5783 
   5784 	/* paranoia check on integrity; should be open!; we could panic */
   5785 	lvint = udf_rw32(udf_node->ump->logvol_integrity->integrity_type);
   5786 	if (lvint == UDF_INTEGRITY_CLOSED)
   5787 		printf("\tIntegrity was CLOSED!\n");
   5788 
   5789 	/* whatever the node type, change its size to zero */
   5790 	(void) udf_resize_node(udf_node, 0, &dummy);
   5791 
   5792 	/* force it to be `clean'; no use writing it out */
   5793 	udf_node->i_flags &= ~(IN_MODIFIED | IN_ACCESSED | IN_ACCESS |
   5794 		IN_CHANGE | IN_UPDATE | IN_MODIFY);
   5795 
   5796 	/* adjust file count */
   5797 	udf_adjust_filecount(udf_node, -1);
   5798 
   5799 	/*
   5800 	 * Free its allocated descriptors; memory will be released when
   5801 	 * vop_reclaim() is called.
   5802 	 */
   5803 	loc = &udf_node->loc;
   5804 
   5805 	dscr = udf_node->fe;
   5806 	udf_free_descriptor_space(udf_node, loc, dscr);
   5807 	dscr = udf_node->efe;
   5808 	udf_free_descriptor_space(udf_node, loc, dscr);
   5809 
   5810 	for (extnr = 0; extnr < UDF_MAX_ALLOC_EXTENTS; extnr++) {
   5811 		dscr =  udf_node->ext[extnr];
   5812 		loc  = &udf_node->ext_loc[extnr];
   5813 		udf_free_descriptor_space(udf_node, loc, dscr);
   5814 	}
   5815 }
   5816 
   5817 /* --------------------------------------------------------------------- */
   5818 
   5819 /* set new filesize; node but be LOCKED on entry and is locked on exit */
   5820 int
   5821 udf_resize_node(struct udf_node *udf_node, uint64_t new_size, int *extended)
   5822 {
   5823 	struct file_entry    *fe  = udf_node->fe;
   5824 	struct extfile_entry *efe = udf_node->efe;
   5825 	uint64_t file_size;
   5826 	int error;
   5827 
   5828 	if (fe) {
   5829 		file_size  = udf_rw64(fe->inf_len);
   5830 	} else {
   5831 		assert(udf_node->efe);
   5832 		file_size  = udf_rw64(efe->inf_len);
   5833 	}
   5834 
   5835 	DPRINTF(ATTR, ("\tchanging file length from %"PRIu64" to %"PRIu64"\n",
   5836 			file_size, new_size));
   5837 
   5838 	/* if not changing, we're done */
   5839 	if (file_size == new_size)
   5840 		return 0;
   5841 
   5842 	*extended = (new_size > file_size);
   5843 	if (*extended) {
   5844 		error = udf_grow_node(udf_node, new_size);
   5845 	} else {
   5846 		error = udf_shrink_node(udf_node, new_size);
   5847 	}
   5848 
   5849 	return error;
   5850 }
   5851 
   5852 
   5853 /* --------------------------------------------------------------------- */
   5854 
   5855 void
   5856 udf_itimes(struct udf_node *udf_node, struct timespec *acc,
   5857 	struct timespec *mod, struct timespec *birth)
   5858 {
   5859 	struct timespec now;
   5860 	struct file_entry    *fe;
   5861 	struct extfile_entry *efe;
   5862 	struct filetimes_extattr_entry *ft_extattr;
   5863 	struct timestamp *atime, *mtime, *attrtime, *ctime;
   5864 	struct timestamp  fe_ctime;
   5865 	struct timespec   cur_birth;
   5866 	uint32_t offset, a_l;
   5867 	uint8_t *filedata;
   5868 	int error;
   5869 
   5870 	/* protect against rogue values */
   5871 	if (!udf_node)
   5872 		return;
   5873 
   5874 	fe  = udf_node->fe;
   5875 	efe = udf_node->efe;
   5876 
   5877 	if (!(udf_node->i_flags & (IN_ACCESS|IN_CHANGE|IN_UPDATE|IN_MODIFY)))
   5878 		return;
   5879 
   5880 	/* get descriptor information */
   5881 	if (fe) {
   5882 		atime    = &fe->atime;
   5883 		mtime    = &fe->mtime;
   5884 		attrtime = &fe->attrtime;
   5885 		filedata = fe->data;
   5886 
   5887 		/* initial save dummy setting */
   5888 		ctime    = &fe_ctime;
   5889 
   5890 		/* check our extended attribute if present */
   5891 		error = udf_extattr_search_intern(udf_node,
   5892 			UDF_FILETIMES_ATTR_NO, "", &offset, &a_l);
   5893 		if (!error) {
   5894 			ft_extattr = (struct filetimes_extattr_entry *)
   5895 				(filedata + offset);
   5896 			if (ft_extattr->existence & UDF_FILETIMES_FILE_CREATION)
   5897 				ctime = &ft_extattr->times[0];
   5898 		}
   5899 		/* TODO create the extended attribute if not found ? */
   5900 	} else {
   5901 		assert(udf_node->efe);
   5902 		atime    = &efe->atime;
   5903 		mtime    = &efe->mtime;
   5904 		attrtime = &efe->attrtime;
   5905 		ctime    = &efe->ctime;
   5906 	}
   5907 
   5908 	vfs_timestamp(&now);
   5909 
   5910 	/* set access time */
   5911 	if (udf_node->i_flags & IN_ACCESS) {
   5912 		if (acc == NULL)
   5913 			acc = &now;
   5914 		udf_timespec_to_timestamp(acc, atime);
   5915 	}
   5916 
   5917 	/* set modification time */
   5918 	if (udf_node->i_flags & (IN_UPDATE | IN_MODIFY)) {
   5919 		if (mod == NULL)
   5920 			mod = &now;
   5921 		udf_timespec_to_timestamp(mod, mtime);
   5922 
   5923 		/* ensure birthtime is older than set modification! */
   5924 		udf_timestamp_to_timespec(udf_node->ump, ctime, &cur_birth);
   5925 		if ((cur_birth.tv_sec > mod->tv_sec) ||
   5926 			  ((cur_birth.tv_sec == mod->tv_sec) &&
   5927 			     (cur_birth.tv_nsec > mod->tv_nsec))) {
   5928 			udf_timespec_to_timestamp(mod, ctime);
   5929 		}
   5930 	}
   5931 
   5932 	/* update birthtime if specified */
   5933 	/* XXX we asume here that given birthtime is older than mod */
   5934 	if (birth && (birth->tv_sec != VNOVAL)) {
   5935 		udf_timespec_to_timestamp(birth, ctime);
   5936 	}
   5937 
   5938 	/* set change time */
   5939 	if (udf_node->i_flags & (IN_CHANGE | IN_MODIFY))
   5940 		udf_timespec_to_timestamp(&now, attrtime);
   5941 
   5942 	/* notify updates to the node itself */
   5943 	if (udf_node->i_flags & (IN_ACCESS | IN_MODIFY))
   5944 		udf_node->i_flags |= IN_ACCESSED;
   5945 	if (udf_node->i_flags & (IN_UPDATE | IN_CHANGE))
   5946 		udf_node->i_flags |= IN_MODIFIED;
   5947 
   5948 	/* clear modification flags */
   5949 	udf_node->i_flags &= ~(IN_ACCESS | IN_CHANGE | IN_UPDATE | IN_MODIFY);
   5950 }
   5951 
   5952 /* --------------------------------------------------------------------- */
   5953 
   5954 int
   5955 udf_update(struct vnode *vp, struct timespec *acc,
   5956 	struct timespec *mod, struct timespec *birth, int updflags)
   5957 {
   5958 	union dscrptr *dscrptr;
   5959 	struct udf_node  *udf_node = VTOI(vp);
   5960 	struct udf_mount *ump = udf_node->ump;
   5961 	struct regid     *impl_id;
   5962 	int mnt_async = (vp->v_mount->mnt_flag & MNT_ASYNC);
   5963 	int waitfor, flags;
   5964 
   5965 #ifdef DEBUG
   5966 	char bits[128];
   5967 	DPRINTF(CALL, ("udf_update(node, %p, %p, %p, %d)\n", acc, mod, birth,
   5968 		updflags));
   5969 	bitmask_snprintf(udf_node->i_flags, IN_FLAGBITS, bits, sizeof(bits));
   5970 	DPRINTF(CALL, ("\tnode flags %s\n", bits));
   5971 	DPRINTF(CALL, ("\t\tmnt_async = %d\n", mnt_async));
   5972 #endif
   5973 
   5974 	/* set our times */
   5975 	udf_itimes(udf_node, acc, mod, birth);
   5976 
   5977 	/* set our implementation id */
   5978 	if (udf_node->fe) {
   5979 		dscrptr = (union dscrptr *) udf_node->fe;
   5980 		impl_id = &udf_node->fe->imp_id;
   5981 	} else {
   5982 		dscrptr = (union dscrptr *) udf_node->efe;
   5983 		impl_id = &udf_node->efe->imp_id;
   5984 	}
   5985 
   5986 	/* set our ID */
   5987 	udf_set_regid(impl_id, IMPL_NAME);
   5988 	udf_add_impl_regid(ump, impl_id);
   5989 
   5990 	/* update our crc! on RMW we are not allowed to change a thing */
   5991 	udf_validate_tag_and_crc_sums(dscrptr);
   5992 
   5993 	/* if called when mounted readonly, never write back */
   5994 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
   5995 		return 0;
   5996 
   5997 	/* check if the node is dirty 'enough'*/
   5998 	if (updflags & UPDATE_CLOSE) {
   5999 		flags = udf_node->i_flags & (IN_MODIFIED | IN_ACCESSED);
   6000 	} else {
   6001 		flags = udf_node->i_flags & IN_MODIFIED;
   6002 	}
   6003 	if (flags == 0)
   6004 		return 0;
   6005 
   6006 	/* determine if we need to write sync or async */
   6007 	waitfor = 0;
   6008 	if ((flags & IN_MODIFIED) && (mnt_async == 0)) {
   6009 		/* sync mounted */
   6010 		waitfor = updflags & UPDATE_WAIT;
   6011 		if (updflags & UPDATE_DIROP)
   6012 			waitfor |= UPDATE_WAIT;
   6013 	}
   6014 	if (waitfor)
   6015 		return VOP_FSYNC(vp, FSCRED, FSYNC_WAIT, 0,0);
   6016 
   6017 	return 0;
   6018 }
   6019 
   6020 
   6021 /* --------------------------------------------------------------------- */
   6022 
   6023 
   6024 /*
   6025  * Read one fid and process it into a dirent and advance to the next (*fid)
   6026  * has to be allocated a logical block in size, (*dirent) struct dirent length
   6027  */
   6028 
   6029 int
   6030 udf_read_fid_stream(struct vnode *vp, uint64_t *offset,
   6031 		    struct fileid_desc *fid, struct dirent *dirent)
   6032 {
   6033 	struct udf_node  *dir_node = VTOI(vp);
   6034 	struct udf_mount *ump = dir_node->ump;
   6035 	struct file_entry    *fe  = dir_node->fe;
   6036 	struct extfile_entry *efe = dir_node->efe;
   6037 	uint32_t      fid_size, lb_size;
   6038 	uint64_t      file_size;
   6039 	char         *fid_name;
   6040 	int           enough, error;
   6041 
   6042 	assert(fid);
   6043 	assert(dirent);
   6044 	assert(dir_node);
   6045 	assert(offset);
   6046 	assert(*offset != 1);
   6047 
   6048 	DPRINTF(FIDS, ("read_fid_stream called at offset %"PRIu64"\n", *offset));
   6049 	/* check if we're past the end of the directory */
   6050 	if (fe) {
   6051 		file_size = udf_rw64(fe->inf_len);
   6052 	} else {
   6053 		assert(dir_node->efe);
   6054 		file_size = udf_rw64(efe->inf_len);
   6055 	}
   6056 	if (*offset >= file_size)
   6057 		return EINVAL;
   6058 
   6059 	/* get maximum length of FID descriptor */
   6060 	lb_size = udf_rw32(ump->logical_vol->lb_size);
   6061 
   6062 	/* initialise return values */
   6063 	fid_size = 0;
   6064 	memset(dirent, 0, sizeof(struct dirent));
   6065 	memset(fid, 0, lb_size);
   6066 
   6067 	enough  = (file_size - (*offset) >= UDF_FID_SIZE);
   6068 	if (!enough) {
   6069 		/* short dir ... */
   6070 		return EIO;
   6071 	}
   6072 
   6073 	error = vn_rdwr(UIO_READ, vp,
   6074 			fid, MIN(file_size - (*offset), lb_size), *offset,
   6075 			UIO_SYSSPACE, IO_ALTSEMANTICS | IO_NODELOCKED, FSCRED,
   6076 			NULL, NULL);
   6077 	if (error)
   6078 		return error;
   6079 
   6080 	DPRINTF(FIDS, ("\tfid piece read in fine\n"));
   6081 	/*
   6082 	 * Check if we got a whole descriptor.
   6083 	 * TODO Try to `resync' directory stream when something is very wrong.
   6084 	 */
   6085 
   6086 	/* check if our FID header is OK */
   6087 	error = udf_check_tag(fid);
   6088 	if (error) {
   6089 		goto brokendir;
   6090 	}
   6091 	DPRINTF(FIDS, ("\ttag check ok\n"));
   6092 
   6093 	if (udf_rw16(fid->tag.id) != TAGID_FID) {
   6094 		error = EIO;
   6095 		goto brokendir;
   6096 	}
   6097 	DPRINTF(FIDS, ("\ttag checked ok: got TAGID_FID\n"));
   6098 
   6099 	/* check for length */
   6100 	fid_size = udf_fidsize(fid);
   6101 	enough = (file_size - (*offset) >= fid_size);
   6102 	if (!enough) {
   6103 		error = EIO;
   6104 		goto brokendir;
   6105 	}
   6106 	DPRINTF(FIDS, ("\tthe complete fid is read in\n"));
   6107 
   6108 	/* check FID contents */
   6109 	error = udf_check_tag_payload((union dscrptr *) fid, lb_size);
   6110 brokendir:
   6111 	if (error) {
   6112 		/* note that is sometimes a bit quick to report */
   6113 		printf("BROKEN DIRECTORY ENTRY\n");
   6114 		/* RESYNC? */
   6115 		/* TODO: use udf_resync_fid_stream */
   6116 		return EIO;
   6117 	}
   6118 	DPRINTF(FIDS, ("\tpayload checked ok\n"));
   6119 
   6120 	/* we got a whole and valid descriptor! */
   6121 	DPRINTF(FIDS, ("\tinterpret FID\n"));
   6122 
   6123 	/* create resulting dirent structure */
   6124 	fid_name = (char *) fid->data + udf_rw16(fid->l_iu);
   6125 	udf_to_unix_name(dirent->d_name, MAXNAMLEN,
   6126 		fid_name, fid->l_fi, &ump->logical_vol->desc_charset);
   6127 
   6128 	/* '..' has no name, so provide one */
   6129 	if (fid->file_char & UDF_FILE_CHAR_PAR)
   6130 		strcpy(dirent->d_name, "..");
   6131 
   6132 	dirent->d_fileno = udf_calchash(&fid->icb);	/* inode hash XXX */
   6133 	dirent->d_namlen = strlen(dirent->d_name);
   6134 	dirent->d_reclen = _DIRENT_SIZE(dirent);
   6135 
   6136 	/*
   6137 	 * Note that its not worth trying to go for the filetypes now... its
   6138 	 * too expensive too
   6139 	 */
   6140 	dirent->d_type = DT_UNKNOWN;
   6141 
   6142 	/* initial guess for filetype we can make */
   6143 	if (fid->file_char & UDF_FILE_CHAR_DIR)
   6144 		dirent->d_type = DT_DIR;
   6145 
   6146 	/* advance */
   6147 	*offset += fid_size;
   6148 
   6149 	return error;
   6150 }
   6151 
   6152 
   6153 /* --------------------------------------------------------------------- */
   6154 
   6155 static void
   6156 udf_sync_pass(struct udf_mount *ump, kauth_cred_t cred, int waitfor,
   6157 	int pass, int *ndirty)
   6158 {
   6159 	struct udf_node *udf_node, *n_udf_node;
   6160 	struct vnode *vp;
   6161 	int vdirty, error;
   6162 	int on_type, on_flags, on_vnode;
   6163 
   6164 derailed:
   6165 	KASSERT(mutex_owned(&mntvnode_lock));
   6166 
   6167 	DPRINTF(SYNC, ("sync_pass %d\n", pass));
   6168 	udf_node = LIST_FIRST(&ump->sorted_udf_nodes);
   6169 	for (;udf_node; udf_node = n_udf_node) {
   6170 		DPRINTF(SYNC, ("."));
   6171 
   6172 		udf_node->i_flags &= ~IN_SYNCED;
   6173 		vp = udf_node->vnode;
   6174 
   6175 		mutex_enter(&vp->v_interlock);
   6176 		n_udf_node = LIST_NEXT(udf_node, sortchain);
   6177 		if (n_udf_node)
   6178 			n_udf_node->i_flags |= IN_SYNCED;
   6179 
   6180 		/* system nodes are not synced this way */
   6181 		if (vp->v_vflag & VV_SYSTEM) {
   6182 			mutex_exit(&vp->v_interlock);
   6183 			continue;
   6184 		}
   6185 
   6186 		/* check if its dirty enough to even try */
   6187 		on_type  = (waitfor == MNT_LAZY || vp->v_type == VNON);
   6188 		on_flags = ((udf_node->i_flags &
   6189 			(IN_ACCESSED | IN_UPDATE | IN_MODIFIED)) == 0);
   6190 		on_vnode = LIST_EMPTY(&vp->v_dirtyblkhd)
   6191 			&& UVM_OBJ_IS_CLEAN(&vp->v_uobj);
   6192 		if (on_type || (on_flags || on_vnode)) { /* XXX */
   6193 			/* not dirty (enough?) */
   6194 			mutex_exit(&vp->v_interlock);
   6195 			continue;
   6196 		}
   6197 
   6198 		mutex_exit(&mntvnode_lock);
   6199 		error = vget(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_INTERLOCK);
   6200 		if (error) {
   6201 			mutex_enter(&mntvnode_lock);
   6202 			if (error == ENOENT)
   6203 				goto derailed;
   6204 			*ndirty += 1;
   6205 			continue;
   6206 		}
   6207 
   6208 		switch (pass) {
   6209 		case 1:
   6210 			VOP_FSYNC(vp, cred, 0 | FSYNC_DATAONLY,0,0);
   6211 			break;
   6212 		case 2:
   6213 			vdirty = vp->v_numoutput;
   6214 			if (vp->v_tag == VT_UDF)
   6215 				vdirty += udf_node->outstanding_bufs +
   6216 					udf_node->outstanding_nodedscr;
   6217 			if (vdirty == 0)
   6218 				VOP_FSYNC(vp, cred, 0,0,0);
   6219 			*ndirty += vdirty;
   6220 			break;
   6221 		case 3:
   6222 			vdirty = vp->v_numoutput;
   6223 			if (vp->v_tag == VT_UDF)
   6224 				vdirty += udf_node->outstanding_bufs +
   6225 					udf_node->outstanding_nodedscr;
   6226 			*ndirty += vdirty;
   6227 			break;
   6228 		}
   6229 
   6230 		vput(vp);
   6231 		mutex_enter(&mntvnode_lock);
   6232 	}
   6233 	DPRINTF(SYNC, ("END sync_pass %d\n", pass));
   6234 }
   6235 
   6236 
   6237 void
   6238 udf_do_sync(struct udf_mount *ump, kauth_cred_t cred, int waitfor)
   6239 {
   6240 	int dummy, ndirty;
   6241 
   6242 	mutex_enter(&mntvnode_lock);
   6243 recount:
   6244 	dummy = 0;
   6245 	DPRINTF(CALL, ("issue VOP_FSYNC(DATA only) on all nodes\n"));
   6246 	DPRINTF(SYNC, ("issue VOP_FSYNC(DATA only) on all nodes\n"));
   6247 	udf_sync_pass(ump, cred, waitfor, 1, &dummy);
   6248 
   6249 	DPRINTF(CALL, ("issue VOP_FSYNC(COMPLETE) on all finished nodes\n"));
   6250 	DPRINTF(SYNC, ("issue VOP_FSYNC(COMPLETE) on all finished nodes\n"));
   6251 	udf_sync_pass(ump, cred, waitfor, 2, &dummy);
   6252 
   6253 	if (waitfor == MNT_WAIT) {
   6254 		ndirty = ump->devvp->v_numoutput;
   6255 		DPRINTF(NODE, ("counting pending blocks: on devvp %d\n",
   6256 			ndirty));
   6257 		udf_sync_pass(ump, cred, waitfor, 3, &ndirty);
   6258 		DPRINTF(NODE, ("counted num dirty pending blocks %d\n",
   6259 			ndirty));
   6260 
   6261 		if (ndirty) {
   6262 			/* 1/4 second wait */
   6263 			cv_timedwait(&ump->dirtynodes_cv, &mntvnode_lock,
   6264 				hz/4);
   6265 			goto recount;
   6266 		}
   6267 	}
   6268 
   6269 	mutex_exit(&mntvnode_lock);
   6270 }
   6271 
   6272 /* --------------------------------------------------------------------- */
   6273 
   6274 /*
   6275  * Read and write file extent in/from the buffer.
   6276  *
   6277  * The splitup of the extent into seperate request-buffers is to minimise
   6278  * copying around as much as possible.
   6279  *
   6280  * block based file reading and writing
   6281  */
   6282 
   6283 static int
   6284 udf_read_internal(struct udf_node *node, uint8_t *blob)
   6285 {
   6286 	struct udf_mount *ump;
   6287 	struct file_entry     *fe = node->fe;
   6288 	struct extfile_entry *efe = node->efe;
   6289 	uint64_t inflen;
   6290 	uint32_t sector_size;
   6291 	uint8_t  *pos;
   6292 	int icbflags, addr_type;
   6293 
   6294 	/* get extent and do some paranoia checks */
   6295 	ump = node->ump;
   6296 	sector_size = ump->discinfo.sector_size;
   6297 
   6298 	if (fe) {
   6299 		inflen   = udf_rw64(fe->inf_len);
   6300 		pos      = &fe->data[0] + udf_rw32(fe->l_ea);
   6301 		icbflags = udf_rw16(fe->icbtag.flags);
   6302 	} else {
   6303 		assert(node->efe);
   6304 		inflen   = udf_rw64(efe->inf_len);
   6305 		pos      = &efe->data[0] + udf_rw32(efe->l_ea);
   6306 		icbflags = udf_rw16(efe->icbtag.flags);
   6307 	}
   6308 	addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK;
   6309 
   6310 	assert(addr_type == UDF_ICB_INTERN_ALLOC);
   6311 	assert(inflen < sector_size);
   6312 
   6313 	/* copy out info */
   6314 	memset(blob, 0, sector_size);
   6315 	memcpy(blob, pos, inflen);
   6316 
   6317 	return 0;
   6318 }
   6319 
   6320 
   6321 static int
   6322 udf_write_internal(struct udf_node *node, uint8_t *blob)
   6323 {
   6324 	struct udf_mount *ump;
   6325 	struct file_entry     *fe = node->fe;
   6326 	struct extfile_entry *efe = node->efe;
   6327 	uint64_t inflen;
   6328 	uint32_t sector_size;
   6329 	uint8_t  *pos;
   6330 	int icbflags, addr_type;
   6331 
   6332 	/* get extent and do some paranoia checks */
   6333 	ump = node->ump;
   6334 	sector_size = ump->discinfo.sector_size;
   6335 
   6336 	if (fe) {
   6337 		inflen   = udf_rw64(fe->inf_len);
   6338 		pos      = &fe->data[0] + udf_rw32(fe->l_ea);
   6339 		icbflags = udf_rw16(fe->icbtag.flags);
   6340 	} else {
   6341 		assert(node->efe);
   6342 		inflen   = udf_rw64(efe->inf_len);
   6343 		pos      = &efe->data[0] + udf_rw32(efe->l_ea);
   6344 		icbflags = udf_rw16(efe->icbtag.flags);
   6345 	}
   6346 	addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK;
   6347 
   6348 	assert(addr_type == UDF_ICB_INTERN_ALLOC);
   6349 	assert(inflen < sector_size);
   6350 
   6351 	/* copy in blob */
   6352 	/* memset(pos, 0, inflen); */
   6353 	memcpy(pos, blob, inflen);
   6354 
   6355 	return 0;
   6356 }
   6357 
   6358 
   6359 void
   6360 udf_read_filebuf(struct udf_node *udf_node, struct buf *buf)
   6361 {
   6362 	struct buf *nestbuf;
   6363 	struct udf_mount *ump = udf_node->ump;
   6364 	uint64_t   *mapping;
   6365 	uint64_t    run_start;
   6366 	uint32_t    sector_size;
   6367 	uint32_t    buf_offset, sector, rbuflen, rblk;
   6368 	uint32_t    from, lblkno;
   6369 	uint32_t    sectors;
   6370 	uint8_t    *buf_pos;
   6371 	int error, run_length, isdir, what;
   6372 
   6373 	sector_size = udf_node->ump->discinfo.sector_size;
   6374 
   6375 	from    = buf->b_blkno;
   6376 	sectors = buf->b_bcount / sector_size;
   6377 
   6378 	isdir   = (udf_node->vnode->v_type == VDIR);
   6379 	what    = isdir ? UDF_C_FIDS : UDF_C_USERDATA;
   6380 
   6381 	/* assure we have enough translation slots */
   6382 	KASSERT(buf->b_bcount / sector_size <= UDF_MAX_MAPPINGS);
   6383 	KASSERT(MAXPHYS / sector_size <= UDF_MAX_MAPPINGS);
   6384 
   6385 	if (sectors > UDF_MAX_MAPPINGS) {
   6386 		printf("udf_read_filebuf: implementation limit on bufsize\n");
   6387 		buf->b_error  = EIO;
   6388 		biodone(buf);
   6389 		return;
   6390 	}
   6391 
   6392 	mapping = malloc(sizeof(*mapping) * UDF_MAX_MAPPINGS, M_TEMP, M_WAITOK);
   6393 
   6394 	error = 0;
   6395 	DPRINTF(READ, ("\ttranslate %d-%d\n", from, sectors));
   6396 	error = udf_translate_file_extent(udf_node, from, sectors, mapping);
   6397 	if (error) {
   6398 		buf->b_error  = error;
   6399 		biodone(buf);
   6400 		goto out;
   6401 	}
   6402 	DPRINTF(READ, ("\ttranslate extent went OK\n"));
   6403 
   6404 	/* pre-check if its an internal */
   6405 	if (*mapping == UDF_TRANS_INTERN) {
   6406 		error = udf_read_internal(udf_node, (uint8_t *) buf->b_data);
   6407 		if (error)
   6408 			buf->b_error  = error;
   6409 		biodone(buf);
   6410 		goto out;
   6411 	}
   6412 	DPRINTF(READ, ("\tnot intern\n"));
   6413 
   6414 #ifdef DEBUG
   6415 	if (udf_verbose & UDF_DEBUG_TRANSLATE) {
   6416 		printf("Returned translation table:\n");
   6417 		for (sector = 0; sector < sectors; sector++) {
   6418 			printf("%d : %"PRIu64"\n", sector, mapping[sector]);
   6419 		}
   6420 	}
   6421 #endif
   6422 
   6423 	/* request read-in of data from disc sheduler */
   6424 	buf->b_resid = buf->b_bcount;
   6425 	for (sector = 0; sector < sectors; sector++) {
   6426 		buf_offset = sector * sector_size;
   6427 		buf_pos    = (uint8_t *) buf->b_data + buf_offset;
   6428 		DPRINTF(READ, ("\tprocessing rel sector %d\n", sector));
   6429 
   6430 		/* check if its zero or unmapped to stop reading */
   6431 		switch (mapping[sector]) {
   6432 		case UDF_TRANS_UNMAPPED:
   6433 		case UDF_TRANS_ZERO:
   6434 			/* copy zero sector TODO runlength like below */
   6435 			memset(buf_pos, 0, sector_size);
   6436 			DPRINTF(READ, ("\treturning zero sector\n"));
   6437 			nestiobuf_done(buf, sector_size, 0);
   6438 			break;
   6439 		default :
   6440 			DPRINTF(READ, ("\tread sector "
   6441 			    "%"PRIu64"\n", mapping[sector]));
   6442 
   6443 			lblkno = from + sector;
   6444 			run_start  = mapping[sector];
   6445 			run_length = 1;
   6446 			while (sector < sectors-1) {
   6447 				if (mapping[sector+1] != mapping[sector]+1)
   6448 					break;
   6449 				run_length++;
   6450 				sector++;
   6451 			}
   6452 
   6453 			/*
   6454 			 * nest an iobuf and mark it for async reading. Since
   6455 			 * we're using nested buffers, they can't be cached by
   6456 			 * design.
   6457 			 */
   6458 			rbuflen = run_length * sector_size;
   6459 			rblk    = run_start  * (sector_size/DEV_BSIZE);
   6460 
   6461 			nestbuf = getiobuf(NULL, true);
   6462 			nestiobuf_setup(buf, nestbuf, buf_offset, rbuflen);
   6463 			/* nestbuf is B_ASYNC */
   6464 
   6465 			/* identify this nestbuf */
   6466 			nestbuf->b_lblkno   = lblkno;
   6467 			assert(nestbuf->b_vp == udf_node->vnode);
   6468 
   6469 			/* CD shedules on raw blkno */
   6470 			nestbuf->b_blkno      = rblk;
   6471 			nestbuf->b_proc       = NULL;
   6472 			nestbuf->b_rawblkno   = rblk;
   6473 			nestbuf->b_udf_c_type = what;
   6474 
   6475 			udf_discstrat_queuebuf(ump, nestbuf);
   6476 		}
   6477 	}
   6478 out:
   6479 	/* if we're synchronously reading, wait for the completion */
   6480 	if ((buf->b_flags & B_ASYNC) == 0)
   6481 		biowait(buf);
   6482 
   6483 	DPRINTF(READ, ("\tend of read_filebuf\n"));
   6484 	free(mapping, M_TEMP);
   6485 	return;
   6486 }
   6487 
   6488 
   6489 void
   6490 udf_write_filebuf(struct udf_node *udf_node, struct buf *buf)
   6491 {
   6492 	struct buf *nestbuf;
   6493 	struct udf_mount *ump = udf_node->ump;
   6494 	uint64_t   *mapping;
   6495 	uint64_t    run_start;
   6496 	uint32_t    lb_size;
   6497 	uint32_t    buf_offset, lb_num, rbuflen, rblk;
   6498 	uint32_t    from, lblkno;
   6499 	uint32_t    num_lb;
   6500 	uint8_t    *buf_pos;
   6501 	int error, run_length, isdir, what, s;
   6502 
   6503 	lb_size = udf_rw32(udf_node->ump->logical_vol->lb_size);
   6504 
   6505 	from   = buf->b_blkno;
   6506 	num_lb = buf->b_bcount / lb_size;
   6507 
   6508 	isdir  = (udf_node->vnode->v_type == VDIR);
   6509 	what   = isdir ? UDF_C_FIDS : UDF_C_USERDATA;
   6510 
   6511 	if (udf_node == ump->metadatabitmap_node)
   6512 		what = UDF_C_METADATA_SBM;
   6513 
   6514 	/* assure we have enough translation slots */
   6515 	KASSERT(buf->b_bcount / lb_size <= UDF_MAX_MAPPINGS);
   6516 	KASSERT(MAXPHYS / lb_size <= UDF_MAX_MAPPINGS);
   6517 
   6518 	if (num_lb > UDF_MAX_MAPPINGS) {
   6519 		printf("udf_write_filebuf: implementation limit on bufsize\n");
   6520 		buf->b_error  = EIO;
   6521 		biodone(buf);
   6522 		return;
   6523 	}
   6524 
   6525 	mapping = malloc(sizeof(*mapping) * UDF_MAX_MAPPINGS, M_TEMP, M_WAITOK);
   6526 
   6527 	error = 0;
   6528 	DPRINTF(WRITE, ("\ttranslate %d-%d\n", from, num_lb));
   6529 	error = udf_translate_file_extent(udf_node, from, num_lb, mapping);
   6530 	if (error) {
   6531 		buf->b_error  = error;
   6532 		biodone(buf);
   6533 		goto out;
   6534 	}
   6535 	DPRINTF(WRITE, ("\ttranslate extent went OK\n"));
   6536 
   6537 	/* if its internally mapped, we can write it in the descriptor itself */
   6538 	if (*mapping == UDF_TRANS_INTERN) {
   6539 		/* TODO paranoia check if we ARE going to have enough space */
   6540 		error = udf_write_internal(udf_node, (uint8_t *) buf->b_data);
   6541 		if (error)
   6542 			buf->b_error  = error;
   6543 		biodone(buf);
   6544 		goto out;
   6545 	}
   6546 	DPRINTF(WRITE, ("\tnot intern\n"));
   6547 
   6548 	/* request write out of data to disc sheduler */
   6549 	buf->b_resid = buf->b_bcount;
   6550 	for (lb_num = 0; lb_num < num_lb; lb_num++) {
   6551 		buf_offset = lb_num * lb_size;
   6552 		buf_pos    = (uint8_t *) buf->b_data + buf_offset;
   6553 		DPRINTF(WRITE, ("\tprocessing rel lb_num %d\n", lb_num));
   6554 
   6555 		/*
   6556 		 * Mappings are not that important here. Just before we write
   6557 		 * the lb_num we late-allocate them when needed and update the
   6558 		 * mapping in the udf_node.
   6559 		 */
   6560 
   6561 		/* XXX why not ignore the mapping altogether ? */
   6562 		/* TODO estimate here how much will be late-allocated */
   6563 		DPRINTF(WRITE, ("\twrite lb_num "
   6564 		    "%"PRIu64, mapping[lb_num]));
   6565 
   6566 		lblkno = from + lb_num;
   6567 		run_start  = mapping[lb_num];
   6568 		run_length = 1;
   6569 		while (lb_num < num_lb-1) {
   6570 			if (mapping[lb_num+1] != mapping[lb_num]+1)
   6571 				if (mapping[lb_num+1] != mapping[lb_num])
   6572 					break;
   6573 			run_length++;
   6574 			lb_num++;
   6575 		}
   6576 		DPRINTF(WRITE, ("+ %d\n", run_length));
   6577 
   6578 		/* nest an iobuf on the master buffer for the extent */
   6579 		rbuflen = run_length * lb_size;
   6580 		rblk = run_start * (lb_size/DEV_BSIZE);
   6581 
   6582 #if 0
   6583 		/* if its zero or unmapped, our blknr gets -1 for unmapped */
   6584 		switch (mapping[lb_num]) {
   6585 		case UDF_TRANS_UNMAPPED:
   6586 		case UDF_TRANS_ZERO:
   6587 			rblk = -1;
   6588 			break;
   6589 		default:
   6590 			rblk = run_start * (lb_size/DEV_BSIZE);
   6591 			break;
   6592 		}
   6593 #endif
   6594 
   6595 		nestbuf = getiobuf(NULL, true);
   6596 		nestiobuf_setup(buf, nestbuf, buf_offset, rbuflen);
   6597 		/* nestbuf is B_ASYNC */
   6598 
   6599 		/* identify this nestbuf */
   6600 		nestbuf->b_lblkno   = lblkno;
   6601 		KASSERT(nestbuf->b_vp == udf_node->vnode);
   6602 
   6603 		/* CD shedules on raw blkno */
   6604 		nestbuf->b_blkno      = rblk;
   6605 		nestbuf->b_proc       = NULL;
   6606 		nestbuf->b_rawblkno   = rblk;
   6607 		nestbuf->b_udf_c_type = what;
   6608 
   6609 		/* increment our outstanding bufs counter */
   6610 		s = splbio();
   6611 			udf_node->outstanding_bufs++;
   6612 		splx(s);
   6613 
   6614 		udf_discstrat_queuebuf(ump, nestbuf);
   6615 	}
   6616 out:
   6617 	/* if we're synchronously writing, wait for the completion */
   6618 	if ((buf->b_flags & B_ASYNC) == 0)
   6619 		biowait(buf);
   6620 
   6621 	DPRINTF(WRITE, ("\tend of write_filebuf\n"));
   6622 	free(mapping, M_TEMP);
   6623 	return;
   6624 }
   6625 
   6626 /* --------------------------------------------------------------------- */
   6627 
   6628 
   6629