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