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