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