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