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