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