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