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