xref: /freebsd/sys/fs/udf/udf_vnops.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
1 /*-
2  * Copyright (c) 2001, 2002 Scott Long <scottl@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 /* udf_vnops.c */
30 /* Take care of the vnode side of things */
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/namei.h>
35 #include <sys/kernel.h>
36 #include <sys/malloc.h>
37 #include <sys/stat.h>
38 #include <sys/bio.h>
39 #include <sys/buf.h>
40 #include <sys/mount.h>
41 #include <sys/vnode.h>
42 #include <sys/dirent.h>
43 #include <sys/queue.h>
44 #include <sys/unistd.h>
45 
46 #include <vm/uma.h>
47 
48 #include <fs/udf/ecma167-udf.h>
49 #include <fs/udf/osta.h>
50 #include <fs/udf/udf.h>
51 
52 static int udf_access(struct vop_access_args *);
53 static int udf_getattr(struct vop_getattr_args *);
54 static int udf_ioctl(struct vop_ioctl_args *);
55 static int udf_pathconf(struct vop_pathconf_args *);
56 static int udf_read(struct vop_read_args *);
57 static int udf_readdir(struct vop_readdir_args *);
58 static int udf_readlink(struct vop_readlink_args *ap);
59 static int udf_strategy(struct vop_strategy_args *);
60 static int udf_bmap(struct vop_bmap_args *);
61 static int udf_lookup(struct vop_cachedlookup_args *);
62 static int udf_reclaim(struct vop_reclaim_args *);
63 static void udf_dumpblock(void *, int) __unused;
64 static int udf_readatoffset(struct udf_node *, int *, int, struct buf **, uint8_t **);
65 static int udf_bmap_internal(struct udf_node *, uint32_t, daddr_t *, uint32_t *);
66 
67 vop_t **udf_vnodeop_p;
68 static struct vnodeopv_entry_desc udf_vnodeop_entries[] = {
69 	{ &vop_default_desc,		(vop_t *) vop_defaultop },
70 	{ &vop_access_desc,		(vop_t *) udf_access },
71 	{ &vop_bmap_desc,		(vop_t *) udf_bmap },
72 	{ &vop_cachedlookup_desc,	(vop_t *) udf_lookup },
73 	{ &vop_getattr_desc,		(vop_t *) udf_getattr },
74 	{ &vop_ioctl_desc,		(vop_t *) udf_ioctl },
75 	{ &vop_lookup_desc,		(vop_t *) vfs_cache_lookup },
76 	{ &vop_pathconf_desc,		(vop_t *) udf_pathconf },
77 	{ &vop_read_desc,		(vop_t *) udf_read },
78 	{ &vop_readdir_desc,		(vop_t *) udf_readdir },
79 	{ &vop_readlink_desc,		(vop_t *) udf_readlink },
80 	{ &vop_reclaim_desc,		(vop_t *) udf_reclaim },
81 	{ &vop_strategy_desc,		(vop_t *) udf_strategy },
82 	{ NULL, NULL }
83 };
84 static struct vnodeopv_desc udf_vnodeop_opv_desc =
85 	{ &udf_vnodeop_p, udf_vnodeop_entries };
86 VNODEOP_SET(udf_vnodeop_opv_desc);
87 
88 MALLOC_DEFINE(M_UDFFID, "UDF FID", "UDF FileId structure");
89 MALLOC_DEFINE(M_UDFDS, "UDF DS", "UDF Dirstream structure");
90 
91 #define UDF_INVALID_BMAP	-1
92 
93 /* Look up a udf_node based on the ino_t passed in and return it's vnode */
94 int
95 udf_hashlookup(struct udf_mnt *udfmp, ino_t id, int flags, struct vnode **vpp)
96 {
97 	struct udf_node *node;
98 	struct udf_hash_lh *lh;
99 	int error;
100 
101 	*vpp = NULL;
102 
103 loop:
104 	mtx_lock(&udfmp->hash_mtx);
105 	lh = &udfmp->hashtbl[id % udfmp->hashsz];
106 	if (lh == NULL)
107 		return (ENOENT);
108 	LIST_FOREACH(node, lh, le) {
109 		if (node->hash_id == id) {
110 			VI_LOCK(node->i_vnode);
111 			mtx_unlock(&udfmp->hash_mtx);
112 			error = vget(node->i_vnode, flags | LK_INTERLOCK,
113 			    curthread);
114 			if (error == ENOENT)
115 				goto loop;
116 			if (error)
117 				return (error);
118 			*vpp = node->i_vnode;
119 			return (0);
120 		}
121 	}
122 
123 	mtx_unlock(&udfmp->hash_mtx);
124 	return (0);
125 }
126 
127 int
128 udf_hashins(struct udf_node *node)
129 {
130 	struct udf_mnt *udfmp;
131 	struct udf_hash_lh *lh;
132 
133 	udfmp = node->udfmp;
134 
135 	vn_lock(node->i_vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
136 	mtx_lock(&udfmp->hash_mtx);
137 	lh = &udfmp->hashtbl[node->hash_id % udfmp->hashsz];
138 	if (lh == NULL)
139 		LIST_INIT(lh);
140 	LIST_INSERT_HEAD(lh, node, le);
141 	mtx_unlock(&udfmp->hash_mtx);
142 
143 	return (0);
144 }
145 
146 int
147 udf_hashrem(struct udf_node *node)
148 {
149 	struct udf_mnt *udfmp;
150 	struct udf_hash_lh *lh;
151 
152 	udfmp = node->udfmp;
153 
154 	mtx_lock(&udfmp->hash_mtx);
155 	lh = &udfmp->hashtbl[node->hash_id % udfmp->hashsz];
156 	if (lh == NULL)
157 		panic("hash entry is NULL, node->hash_id= %d\n", node->hash_id);
158 	LIST_REMOVE(node, le);
159 	mtx_unlock(&udfmp->hash_mtx);
160 
161 	return (0);
162 }
163 
164 int
165 udf_allocv(struct mount *mp, struct vnode **vpp, struct thread *td)
166 {
167 	int error;
168 	struct vnode *vp;
169 
170 	error = getnewvnode("udf", mp, udf_vnodeop_p, &vp);
171 	if (error) {
172 		printf("udf_allocv: failed to allocate new vnode\n");
173 		return (error);
174 	}
175 
176 	*vpp = vp;
177 	return (0);
178 }
179 
180 /* Convert file entry permission (5 bits per owner/group/user) to a mode_t */
181 static mode_t
182 udf_permtomode(struct udf_node *node)
183 {
184 	uint32_t perm;
185 	uint32_t flags;
186 	mode_t mode;
187 
188 	perm = node->fentry->perm;
189 	flags = node->fentry->icbtag.flags;
190 
191 	mode = perm & UDF_FENTRY_PERM_USER_MASK;
192 	mode |= ((perm & UDF_FENTRY_PERM_GRP_MASK) >> 2);
193 	mode |= ((perm & UDF_FENTRY_PERM_OWNER_MASK) >> 4);
194 	mode |= ((flags & UDF_ICB_TAG_FLAGS_STICKY) << 4);
195 	mode |= ((flags & UDF_ICB_TAG_FLAGS_SETGID) << 6);
196 	mode |= ((flags & UDF_ICB_TAG_FLAGS_SETUID) << 8);
197 
198 	return (mode);
199 }
200 
201 static int
202 udf_access(struct vop_access_args *a)
203 {
204 	struct vnode *vp;
205 	struct udf_node *node;
206 	mode_t a_mode, mode;
207 
208 	vp = a->a_vp;
209 	node = VTON(vp);
210 	a_mode = a->a_mode;
211 
212 	if (a_mode & VWRITE) {
213 		switch (vp->v_type) {
214 		case VDIR:
215 		case VLNK:
216 		case VREG:
217 			return (EROFS);
218 			/* NOT REACHED */
219 		default:
220 			break;
221 		}
222 	}
223 
224 	mode = udf_permtomode(node);
225 
226 	return (vaccess(vp->v_type, mode, node->fentry->uid, node->fentry->gid,
227 	    a_mode, a->a_cred, NULL));
228 }
229 
230 static int mon_lens[2][12] = {
231 	{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
232 	{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
233 };
234 
235 static int
236 udf_isaleapyear(int year)
237 {
238 	int i;
239 
240 	i = (year % 4) ? 0 : 1;
241 	i &= (year % 100) ? 1 : 0;
242 	i |= (year % 400) ? 0 : 1;
243 
244 	return i;
245 }
246 
247 /*
248  * XXX This is just a rough hack.  Daylight savings isn't calculated and tv_nsec
249  * is ignored.
250  * Timezone calculation compliments of Julian Elischer <julian@elischer.org>.
251  */
252 static void
253 udf_timetotimespec(struct timestamp *time, struct timespec *t)
254 {
255 	int i, lpyear, daysinyear;
256 	union {
257 		uint16_t	u_tz_offset;
258 		int16_t		s_tz_offset;
259 	} tz;
260 
261 	t->tv_nsec = 0;
262 
263 	/* DirectCD seems to like using bogus year values */
264 	if (time->year < 1970) {
265 		t->tv_sec = 0;
266 		return;
267 	}
268 
269 	/* Calculate the time and day */
270 	t->tv_sec = time->second;
271 	t->tv_sec += time->minute * 60;
272 	t->tv_sec += time->hour * 3600;
273 	t->tv_sec += time->day * 3600 * 24;
274 
275 	/* Calclulate the month */
276 	lpyear = udf_isaleapyear(time->year);
277 	for (i = 1; i < time->month; i++)
278 		t->tv_sec += mon_lens[lpyear][i] * 3600 * 24;
279 
280 	/* Speed up the calculation */
281 	if (time->year > 1979)
282 		t->tv_sec += 315532800;
283 	if (time->year > 1989)
284 		t->tv_sec += 315619200;
285 	if (time->year > 1999)
286 		t->tv_sec += 315532800;
287 	for (i = 2000; i < time->year; i++) {
288 		daysinyear = udf_isaleapyear(i) + 365 ;
289 		t->tv_sec += daysinyear * 3600 * 24;
290 	}
291 
292 	/*
293 	 * Calculate the time zone.  The timezone is 12 bit signed 2's
294 	 * compliment, so we gotta do some extra magic to handle it right.
295 	 */
296 	tz.u_tz_offset = time->type_tz;
297 	tz.u_tz_offset &= 0x0fff;
298 	if (tz.u_tz_offset & 0x0800)
299 		tz.u_tz_offset |= 0xf000;	/* extend the sign to 16 bits */
300 	if ((time->type_tz & 0x1000) && (tz.s_tz_offset != -2047))
301 		t->tv_sec -= tz.s_tz_offset * 60;
302 
303 	return;
304 }
305 
306 static int
307 udf_getattr(struct vop_getattr_args *a)
308 {
309 	struct vnode *vp;
310 	struct udf_node *node;
311 	struct vattr *vap;
312 	struct file_entry *fentry;
313 	struct timespec ts;
314 
315 	ts.tv_sec = 0;
316 
317 	vp = a->a_vp;
318 	vap = a->a_vap;
319 	node = VTON(vp);
320 	fentry = node->fentry;
321 
322 	vap->va_fsid = dev2udev(node->i_dev);
323 	vap->va_fileid = node->hash_id;
324 	vap->va_mode = udf_permtomode(node);
325 	vap->va_nlink = fentry->link_cnt;
326 	/*
327 	 * XXX The spec says that -1 is valid for uid/gid and indicates an
328 	 * invalid uid/gid.  How should this be represented?
329 	 */
330 	vap->va_uid = (fentry->uid == -1) ? 0 : fentry->uid;
331 	vap->va_gid = (fentry->gid == -1) ? 0 : fentry->gid;
332 	udf_timetotimespec(&fentry->atime, &vap->va_atime);
333 	udf_timetotimespec(&fentry->mtime, &vap->va_mtime);
334 	vap->va_ctime = vap->va_mtime; /* XXX Stored as an Extended Attribute */
335 	vap->va_rdev = 0; /* XXX */
336 	if (vp->v_type & VDIR) {
337 		/*
338 		 * Directories that are recorded within their ICB will show
339 		 * as having 0 blocks recorded.  Since tradition dictates
340 		 * that directories consume at least one logical block,
341 		 * make it appear so.
342 		 */
343 		if (fentry->logblks_rec != 0) {
344 			vap->va_size = fentry->logblks_rec * node->udfmp->bsize;
345 		} else {
346 			vap->va_size = node->udfmp->bsize;
347 		}
348 	} else {
349 		vap->va_size = fentry->inf_len;
350 	}
351 	vap->va_flags = 0;
352 	vap->va_gen = 1;
353 	vap->va_blocksize = node->udfmp->bsize;
354 	vap->va_bytes = fentry->inf_len;
355 	vap->va_type = vp->v_type;
356 	vap->va_filerev = 0; /* XXX */
357 	return (0);
358 }
359 
360 /*
361  * File specific ioctls.  DeCSS candidate?
362  */
363 static int
364 udf_ioctl(struct vop_ioctl_args *a)
365 {
366 	printf("%s called\n", __FUNCTION__);
367 	return (ENOTTY);
368 }
369 
370 /*
371  * I'm not sure that this has much value in a read-only filesystem, but
372  * cd9660 has it too.
373  */
374 static int
375 udf_pathconf(struct vop_pathconf_args *a)
376 {
377 
378 	switch (a->a_name) {
379 	case _PC_LINK_MAX:
380 		*a->a_retval = 65535;
381 		return (0);
382 	case _PC_NAME_MAX:
383 		*a->a_retval = NAME_MAX;
384 		return (0);
385 	case _PC_PATH_MAX:
386 		*a->a_retval = PATH_MAX;
387 		return (0);
388 	case _PC_NO_TRUNC:
389 		*a->a_retval = 1;
390 		return (0);
391 	default:
392 		return (EINVAL);
393 	}
394 }
395 
396 static int
397 udf_read(struct vop_read_args *a)
398 {
399 	struct vnode *vp = a->a_vp;
400 	struct uio *uio = a->a_uio;
401 	struct udf_node *node = VTON(vp);
402 	struct buf *bp;
403 	uint8_t *data;
404 	int error = 0;
405 	int size, fsize, offset;
406 
407 	if (uio->uio_offset < 0)
408 		return (EINVAL);
409 
410 	fsize = node->fentry->inf_len;
411 
412 	while (uio->uio_offset < fsize && uio->uio_resid > 0) {
413 		offset = uio->uio_offset;
414 		size = uio->uio_resid;
415 		error = udf_readatoffset(node, &size, offset, &bp, &data);
416 		if (error)
417 			return (error);
418 		error = uiomove(data, size, uio);
419 		if (bp != NULL)
420 			brelse(bp);
421 		if (error)
422 			break;
423 	};
424 
425 	return (error);
426 }
427 
428 /* Convienience routine to dump a block in hex */
429 static void
430 udf_dumpblock(void *data, int len)
431 {
432 	int i, j;
433 
434 	for (i = 0; i < len; i++) {
435 		printf("\noffset= %d: ", i);
436 		for (j = 0; j < 8; j++) {
437 			if (i + j == len)
438 				break;
439 			printf("0x%02x ", (uint8_t)((uint8_t*)(data))[i + j]);
440 		}
441 		i += j - 1;
442 	}
443 	printf("\n");
444 }
445 
446 /*
447  * Call the OSTA routines to translate the name from a CS0 dstring to a
448  * 16-bit Unicode String.  Hooks need to be placed in here to translate from
449  * Unicode to the encoding that the kernel/user expects.  For now, compact
450  * the encoding to 8 bits if possible.  Return the length of the translated
451  * string.
452  * XXX This horribly pessimizes the 8bit case
453  */
454 static int
455 udf_transname(char *cs0string, char *destname, int len)
456 {
457 	unicode_t *transname;
458 	int i, unilen = 0;
459 
460 	/* allocate a buffer big enough to hold an 8->16 bit expansion */
461 	transname = uma_zalloc(udf_zone_trans, M_WAITOK);
462 
463 	if ((unilen = udf_UncompressUnicode(len, cs0string, transname)) == -1) {
464 		printf("udf: Unicode translation failed\n");
465 		uma_zfree(udf_zone_trans, transname);
466 		return 0;
467 	}
468 
469 	/* At this point, the name is in 16-bit Unicode.  Compact it down
470 	 * to 8-bit
471 	 */
472 	for (i = 0; i < unilen ; i++) {
473 		if (transname[i] & 0xff00) {
474 			destname[i] = '.';	/* Fudge the 16bit chars */
475 		} else {
476 			destname[i] = transname[i] & 0xff;
477 		}
478 	}
479 
480 	destname[unilen] = 0;
481 	uma_zfree(udf_zone_trans, transname);
482 
483 	return unilen;
484 }
485 
486 /*
487  * Compare a CS0 dstring with a name passed in from the VFS layer.  Return
488  * 0 on a successful match, nonzero therwise.  Unicode work may need to be done
489  * here also.
490  */
491 static int
492 udf_cmpname(char *cs0string, char *cmpname, int cs0len, int cmplen)
493 {
494 	char *transname;
495 	int error = 0;
496 
497 	/* This is overkill, but not worth creating a new zone */
498 	transname = uma_zalloc(udf_zone_trans, M_WAITOK);
499 
500 	cs0len = udf_transname(cs0string, transname, cs0len);
501 
502 	/* Easy check.  If they aren't the same length, they aren't equal */
503 	if ((cs0len == 0) || (cs0len != cmplen))
504 		error = -1;
505 	else
506 		error = bcmp(transname, cmpname, cmplen);
507 
508 	uma_zfree(udf_zone_trans, transname);
509 	return (error);
510 }
511 
512 struct udf_uiodir {
513 	struct dirent *dirent;
514 	u_long *cookies;
515 	int ncookies;
516 	int acookies;
517 	int eofflag;
518 };
519 
520 static int
521 udf_uiodir(struct udf_uiodir *uiodir, int de_size, struct uio *uio, long cookie)
522 {
523 	if (uiodir->cookies != NULL) {
524 		if (++uiodir->acookies > uiodir->ncookies) {
525 			uiodir->eofflag = 0;
526 			return (-1);
527 		}
528 		*uiodir->cookies++ = cookie;
529 	}
530 
531 	if (uio->uio_resid < de_size) {
532 		uiodir->eofflag = 0;
533 		return (-1);
534 	}
535 
536 	return (uiomove(uiodir->dirent, de_size, uio));
537 }
538 
539 static struct udf_dirstream *
540 udf_opendir(struct udf_node *node, int offset, int fsize, struct udf_mnt *udfmp)
541 {
542 	struct udf_dirstream *ds;
543 
544 	ds = uma_zalloc(udf_zone_ds, M_WAITOK | M_ZERO);
545 
546 	ds->node = node;
547 	ds->offset = offset;
548 	ds->udfmp = udfmp;
549 	ds->fsize = fsize;
550 
551 	return (ds);
552 }
553 
554 static struct fileid_desc *
555 udf_getfid(struct udf_dirstream *ds)
556 {
557 	struct fileid_desc *fid;
558 	int error, frag_size = 0, total_fid_size;
559 
560 	/* End of directory? */
561 	if (ds->offset + ds->off >= ds->fsize) {
562 		ds->error = 0;
563 		return (NULL);
564 	}
565 
566 	/* Grab the first extent of the directory */
567 	if (ds->off == 0) {
568 		ds->size = 0;
569 		error = udf_readatoffset(ds->node, &ds->size, ds->offset,
570 		    &ds->bp, &ds->data);
571 		if (error) {
572 			ds->error = error;
573 			return (NULL);
574 		}
575 	}
576 
577 	/*
578 	 * Clean up from a previous fragmented FID.
579 	 * XXX Is this the right place for this?
580 	 */
581 	if (ds->fid_fragment && ds->buf != NULL) {
582 		ds->fid_fragment = 0;
583 		FREE(ds->buf, M_UDFFID);
584 	}
585 
586 	fid = (struct fileid_desc*)&ds->data[ds->off];
587 
588 	/*
589 	 * Check to see if the fid is fragmented. The first test
590 	 * ensures that we don't wander off the end of the buffer
591 	 * looking for the l_iu and l_fi fields.
592 	 */
593 	if (ds->off + UDF_FID_SIZE > ds->size ||
594 	    ds->off + fid->l_iu + fid->l_fi + UDF_FID_SIZE > ds->size) {
595 
596 		/* Copy what we have of the fid into a buffer */
597 		frag_size = ds->size - ds->off;
598 		if (frag_size >= ds->udfmp->bsize) {
599 			printf("udf: invalid FID fragment\n");
600 			ds->error = EINVAL;
601 			return (NULL);
602 		}
603 
604 		/*
605 		 * File ID descriptors can only be at most one
606 		 * logical sector in size.
607 		 */
608 		MALLOC(ds->buf, uint8_t*, ds->udfmp->bsize, M_UDFFID,
609 		     M_WAITOK | M_ZERO);
610 		bcopy(fid, ds->buf, frag_size);
611 
612 		/* Reduce all of the casting magic */
613 		fid = (struct fileid_desc*)ds->buf;
614 
615 		if (ds->bp != NULL)
616 			brelse(ds->bp);
617 
618 		/* Fetch the next allocation */
619 		ds->offset += ds->size;
620 		ds->size = 0;
621 		error = udf_readatoffset(ds->node, &ds->size, ds->offset,
622 		    &ds->bp, &ds->data);
623 		if (error) {
624 			ds->error = error;
625 			return (NULL);
626 		}
627 
628 		/*
629 		 * If the fragment was so small that we didn't get
630 		 * the l_iu and l_fi fields, copy those in.
631 		 */
632 		if (frag_size < UDF_FID_SIZE)
633 			bcopy(ds->data, &ds->buf[frag_size],
634 			    UDF_FID_SIZE - frag_size);
635 
636 		/*
637 		 * Now that we have enough of the fid to work with,
638 		 * copy in the rest of the fid from the new
639 		 * allocation.
640 		 */
641 		total_fid_size = UDF_FID_SIZE + fid->l_iu + fid->l_fi;
642 		if (total_fid_size > ds->udfmp->bsize) {
643 			printf("udf: invalid FID\n");
644 			ds->error = EIO;
645 			return (NULL);
646 		}
647 		bcopy(ds->data, &ds->buf[frag_size],
648 		    total_fid_size - frag_size);
649 
650 		ds->fid_fragment = 1;
651 	} else {
652 		total_fid_size = fid->l_iu + fid->l_fi + UDF_FID_SIZE;
653 	}
654 
655 	/*
656 	 * Update the offset. Align on a 4 byte boundary because the
657 	 * UDF spec says so.
658 	 */
659 	ds->this_off = ds->off;
660 	if (!ds->fid_fragment) {
661 		ds->off += (total_fid_size + 3) & ~0x03;
662 	} else {
663 		ds->off = (total_fid_size - frag_size + 3) & ~0x03;
664 	}
665 
666 	return (fid);
667 }
668 
669 static void
670 udf_closedir(struct udf_dirstream *ds)
671 {
672 
673 	if (ds->bp != NULL)
674 		brelse(ds->bp);
675 
676 	if (ds->fid_fragment && ds->buf != NULL)
677 		FREE(ds->buf, M_UDFFID);
678 
679 	uma_zfree(udf_zone_ds, ds);
680 }
681 
682 static int
683 udf_readdir(struct vop_readdir_args *a)
684 {
685 	struct vnode *vp;
686 	struct uio *uio;
687 	struct dirent dir;
688 	struct udf_node *node;
689 	struct fileid_desc *fid;
690 	struct udf_uiodir uiodir;
691 	struct udf_dirstream *ds;
692 	u_long *cookies = NULL;
693 	int ncookies;
694 	int error = 0;
695 
696 	vp = a->a_vp;
697 	uio = a->a_uio;
698 	node = VTON(vp);
699 	uiodir.eofflag = 1;
700 
701 	if (a->a_ncookies != NULL) {
702 		/*
703 		 * Guess how many entries are needed.  If we run out, this
704 		 * function will be called again and thing will pick up were
705 		 * it left off.
706 		 */
707 		ncookies = uio->uio_resid / 8;
708 		MALLOC(cookies, u_long *, sizeof(u_long) * ncookies,
709 		    M_TEMP, M_WAITOK);
710 		if (cookies == NULL)
711 			return (ENOMEM);
712 		uiodir.ncookies = ncookies;
713 		uiodir.cookies = cookies;
714 		uiodir.acookies = 0;
715 	} else {
716 		uiodir.cookies = NULL;
717 	}
718 
719 	/*
720 	 * Iterate through the file id descriptors.  Give the parent dir
721 	 * entry special attention.
722 	 */
723 	ds = udf_opendir(node, uio->uio_offset, node->fentry->inf_len,
724 	    node->udfmp);
725 
726 	while ((fid = udf_getfid(ds)) != NULL) {
727 
728 		/* XXX Should we return an error on a bad fid? */
729 		if (udf_checktag(&fid->tag, TAGID_FID)) {
730 			printf("Invalid FID tag\n");
731 			udf_dumpblock(fid, UDF_FID_SIZE);
732 			error = EIO;
733 			break;
734 		}
735 
736 		/* Is this a deleted file? */
737 		if (fid->file_char & UDF_FILE_CHAR_DEL)
738 			continue;
739 
740 		if ((fid->l_fi == 0) && (fid->file_char & UDF_FILE_CHAR_PAR)) {
741 			/* Do up the '.' and '..' entries.  Dummy values are
742 			 * used for the cookies since the offset here is
743 			 * usually zero, and NFS doesn't like that value
744 			 */
745 			dir.d_fileno = node->hash_id;
746 			dir.d_type = DT_DIR;
747 			dir.d_name[0] = '.';
748 			dir.d_namlen = 1;
749 			dir.d_reclen = GENERIC_DIRSIZ(&dir);
750 			uiodir.dirent = &dir;
751 			error = udf_uiodir(&uiodir, dir.d_reclen, uio, 1);
752 			if (error)
753 				break;
754 
755 			dir.d_fileno = udf_getid(&fid->icb);
756 			dir.d_type = DT_DIR;
757 			dir.d_name[0] = '.';
758 			dir.d_name[1] = '.';
759 			dir.d_namlen = 2;
760 			dir.d_reclen = GENERIC_DIRSIZ(&dir);
761 			uiodir.dirent = &dir;
762 			error = udf_uiodir(&uiodir, dir.d_reclen, uio, 2);
763 		} else {
764 			dir.d_namlen = udf_transname(&fid->data[fid->l_iu],
765 			    &dir.d_name[0], fid->l_fi);
766 			dir.d_fileno = udf_getid(&fid->icb);
767 			dir.d_type = (fid->file_char & UDF_FILE_CHAR_DIR) ?
768 			    DT_DIR : DT_UNKNOWN;
769 			dir.d_reclen = GENERIC_DIRSIZ(&dir);
770 			uiodir.dirent = &dir;
771 			error = udf_uiodir(&uiodir, dir.d_reclen, uio,
772 			    ds->this_off);
773 		}
774 		if (error) {
775 			printf("uiomove returned %d\n", error);
776 			break;
777 		}
778 
779 	}
780 
781 	/* tell the calling layer whether we need to be called again */
782 	*a->a_eofflag = uiodir.eofflag;
783 	uio->uio_offset = ds->offset + ds->off;
784 
785 	if (!error)
786 		error = ds->error;
787 
788 	udf_closedir(ds);
789 
790 	if (a->a_ncookies != NULL) {
791 		if (error)
792 			FREE(cookies, M_TEMP);
793 		else {
794 			*a->a_ncookies = uiodir.acookies;
795 			*a->a_cookies = cookies;
796 		}
797 	}
798 
799 	return (error);
800 }
801 
802 /* Are there any implementations out there that do soft-links? */
803 static int
804 udf_readlink(struct vop_readlink_args *ap)
805 {
806 	printf("%s called\n", __FUNCTION__);
807 	return (EOPNOTSUPP);
808 }
809 
810 static int
811 udf_strategy(struct vop_strategy_args *a)
812 {
813 	struct buf *bp;
814 	struct vnode *vp;
815 	struct udf_node *node;
816 	int maxsize;
817 
818 	bp = a->a_bp;
819 	vp = bp->b_vp;
820 	node = VTON(vp);
821 
822 	KASSERT(a->a_vp == a->a_bp->b_vp, ("%s(%p != %p)",
823 	    __func__, a->a_vp, a->a_bp->b_vp));
824 	/* cd9660 has this test reversed, but it seems more logical this way */
825 	if (bp->b_blkno != bp->b_lblkno) {
826 		/*
827 		 * Files that are embedded in the fentry don't translate well
828 		 * to a block number.  Reject.
829 		 */
830 		if (udf_bmap_internal(node, bp->b_lblkno * node->udfmp->bsize,
831 		    &bp->b_lblkno, &maxsize)) {
832 			clrbuf(bp);
833 			bp->b_blkno = -1;
834 		}
835 	}
836 	if ((long)bp->b_blkno == -1) {
837 		bufdone(bp);
838 		return (0);
839 	}
840 	vp = node->i_devvp;
841 	bp->b_dev = vp->v_rdev;
842 	VOP_SPECSTRATEGY(vp, bp);
843 	return (0);
844 }
845 
846 static int
847 udf_bmap(struct vop_bmap_args *a)
848 {
849 	struct udf_node *node;
850 	uint32_t max_size;
851 	daddr_t lsector;
852 	int error;
853 
854 	node = VTON(a->a_vp);
855 
856 	if (a->a_vpp != NULL)
857 		*a->a_vpp = node->i_devvp;
858 	if (a->a_bnp == NULL)
859 		return (0);
860 	if (a->a_runb)
861 		*a->a_runb = 0;
862 
863 	error = udf_bmap_internal(node, a->a_bn * node->udfmp->bsize, &lsector,
864 	    &max_size);
865 	if (error)
866 		return (error);
867 
868 	/* Translate logical to physical sector number */
869 	*a->a_bnp = lsector << (node->udfmp->bshift - DEV_BSHIFT);
870 
871 	/* Punt on read-ahead for now */
872 	if (a->a_runp)
873 		*a->a_runp = 0;
874 
875 	return (0);
876 }
877 
878 /*
879  * The all powerful VOP_LOOKUP().
880  */
881 static int
882 udf_lookup(struct vop_cachedlookup_args *a)
883 {
884 	struct vnode *dvp;
885 	struct vnode *tdp = NULL;
886 	struct vnode **vpp = a->a_vpp;
887 	struct udf_node *node;
888 	struct udf_mnt *udfmp;
889 	struct fileid_desc *fid = NULL;
890 	struct udf_dirstream *ds;
891 	struct thread *td;
892 	u_long nameiop;
893 	u_long flags;
894 	char *nameptr;
895 	long namelen;
896 	ino_t id = 0;
897 	int offset, error = 0;
898 	int numdirpasses, fsize;
899 
900 	dvp = a->a_dvp;
901 	node = VTON(dvp);
902 	udfmp = node->udfmp;
903 	nameiop = a->a_cnp->cn_nameiop;
904 	flags = a->a_cnp->cn_flags;
905 	nameptr = a->a_cnp->cn_nameptr;
906 	namelen = a->a_cnp->cn_namelen;
907 	fsize = node->fentry->inf_len;
908 	td = a->a_cnp->cn_thread;
909 
910 	/*
911 	 * If this is a LOOKUP and we've already partially searched through
912 	 * the directory, pick up where we left off and flag that the
913 	 * directory may need to be searched twice.  For a full description,
914 	 * see /sys/isofs/cd9660/cd9660_lookup.c:cd9660_lookup()
915 	 */
916 	if (nameiop != LOOKUP || node->diroff == 0 || node->diroff > fsize) {
917 		offset = 0;
918 		numdirpasses = 1;
919 	} else {
920 		offset = node->diroff;
921 		numdirpasses = 2;
922 		nchstats.ncs_2passes++;
923 	}
924 
925 lookloop:
926 	ds = udf_opendir(node, offset, fsize, udfmp);
927 
928 	while ((fid = udf_getfid(ds)) != NULL) {
929 
930 		/* XXX Should we return an error on a bad fid? */
931 		if (udf_checktag(&fid->tag, TAGID_FID)) {
932 			printf("udf_lookup: Invalid tag\n");
933 			error = EIO;
934 			break;
935 		}
936 
937 		/* Is this a deleted file? */
938 		if (fid->file_char & UDF_FILE_CHAR_DEL)
939 			continue;
940 
941 		if ((fid->l_fi == 0) && (fid->file_char & UDF_FILE_CHAR_PAR)) {
942 			if (flags & ISDOTDOT) {
943 				id = udf_getid(&fid->icb);
944 				break;
945 			}
946 		} else {
947 			if (!(udf_cmpname(&fid->data[fid->l_iu],
948 			    nameptr, fid->l_fi, namelen))) {
949 				id = udf_getid(&fid->icb);
950 				break;
951 			}
952 		}
953 	}
954 
955 	if (!error)
956 		error = ds->error;
957 
958 	/* XXX Bail out here? */
959 	if (error) {
960 		udf_closedir(ds);
961 		return (error);
962 	}
963 
964 	/* Did we have a match? */
965 	if (id) {
966 		error = udf_vget(udfmp->im_mountp, id, LK_EXCLUSIVE, &tdp);
967 		if (!error) {
968 			/*
969 			 * Remember where this entry was if it's the final
970 			 * component.
971 			 */
972 			if ((flags & ISLASTCN) && nameiop == LOOKUP)
973 				node->diroff = ds->offset + ds->off;
974 			if (numdirpasses == 2)
975 				nchstats.ncs_pass2++;
976 			if (!(flags & LOCKPARENT) || !(flags & ISLASTCN)) {
977 				a->a_cnp->cn_flags |= PDIRUNLOCK;
978 				VOP_UNLOCK(dvp, 0, td);
979 			}
980 
981 			*vpp = tdp;
982 
983 			/* Put this entry in the cache */
984 			if (flags & MAKEENTRY)
985 				cache_enter(dvp, *vpp, a->a_cnp);
986 		}
987 	} else {
988 		/* Name wasn't found on this pass.  Do another pass? */
989 		if (numdirpasses == 2) {
990 			numdirpasses--;
991 			offset = 0;
992 			udf_closedir(ds);
993 			goto lookloop;
994 		}
995 
996 		/* Enter name into cache as non-existant */
997 		if (flags & MAKEENTRY)
998 			cache_enter(dvp, *vpp, a->a_cnp);
999 
1000 		if ((flags & ISLASTCN) &&
1001 		    (nameiop == CREATE || nameiop == RENAME)) {
1002 			error = EROFS;
1003 		} else {
1004 			error = ENOENT;
1005 		}
1006 	}
1007 
1008 	udf_closedir(ds);
1009 	return (error);
1010 }
1011 
1012 static int
1013 udf_reclaim(struct vop_reclaim_args *a)
1014 {
1015 	struct vnode *vp;
1016 	struct udf_node *unode;
1017 
1018 	vp = a->a_vp;
1019 	unode = VTON(vp);
1020 
1021 	cache_purge(vp);
1022 	if (unode != NULL) {
1023 		udf_hashrem(unode);
1024 		if (unode->i_devvp) {
1025 			vrele(unode->i_devvp);
1026 			unode->i_devvp = 0;
1027 		}
1028 
1029 		if (unode->fentry != NULL)
1030 			FREE(unode->fentry, M_UDFFENTRY);
1031 		uma_zfree(udf_zone_node, unode);
1032 		vp->v_data = NULL;
1033 	}
1034 
1035 	return (0);
1036 }
1037 
1038 /*
1039  * Read the block and then set the data pointer to correspond with the
1040  * offset passed in.  Only read in at most 'size' bytes, and then set 'size'
1041  * to the number of bytes pointed to.  If 'size' is zero, try to read in a
1042  * whole extent.
1043  * XXX 'size' is limited to the logical block size for now due to problems
1044  * with udf_read()
1045  */
1046 static int
1047 udf_readatoffset(struct udf_node *node, int *size, int offset, struct buf **bp, uint8_t **data)
1048 {
1049 	struct udf_mnt *udfmp;
1050 	struct file_entry *fentry = NULL;
1051 	struct buf *bp1;
1052 	uint32_t max_size;
1053 	daddr_t sector;
1054 	int error;
1055 
1056 	udfmp = node->udfmp;
1057 
1058 	error = udf_bmap_internal(node, offset, &sector, &max_size);
1059 	if (error == UDF_INVALID_BMAP) {
1060 		/*
1061 		 * This error means that the file *data* is stored in the
1062 		 * allocation descriptor field of the file entry.
1063 		 */
1064 		fentry = node->fentry;
1065 		*data = &fentry->data[fentry->l_ea];
1066 		*size = fentry->l_ad;
1067 		*bp = NULL;
1068 		return (0);
1069 	} else if (error != 0) {
1070 		return (error);
1071 	}
1072 
1073 	/* Adjust the size so that it is within range */
1074 	if (*size == 0 || *size > max_size)
1075 		*size = max_size;
1076 	*size = min(*size, MAXBSIZE);
1077 
1078 	if ((error = udf_readlblks(udfmp, sector, *size, bp))) {
1079 		printf("warning: udf_readlblks returned error %d\n", error);
1080 		return (error);
1081 	}
1082 
1083 	bp1 = *bp;
1084 	*data = (uint8_t *)&bp1->b_data[offset % udfmp->bsize];
1085 	return (0);
1086 }
1087 
1088 /*
1089  * Translate a file offset into a logical block and then into a physical
1090  * block.
1091  */
1092 static int
1093 udf_bmap_internal(struct udf_node *node, uint32_t offset, daddr_t *sector, uint32_t *max_size)
1094 {
1095 	struct udf_mnt *udfmp;
1096 	struct file_entry *fentry;
1097 	void *icb;
1098 	struct icb_tag *tag;
1099 	uint32_t icblen = 0;
1100 	daddr_t lsector;
1101 	int ad_offset, ad_num = 0;
1102 	int i, p_offset;
1103 
1104 	udfmp = node->udfmp;
1105 	fentry = node->fentry;
1106 	tag = &fentry->icbtag;
1107 
1108 	switch (tag->strat_type) {
1109 	case 4:
1110 		break;
1111 
1112 	case 4096:
1113 		printf("Cannot deal with strategy4096 yet!\n");
1114 		return (ENODEV);
1115 
1116 	default:
1117 		printf("Unknown strategy type %d\n", tag->strat_type);
1118 		return (ENODEV);
1119 	}
1120 
1121 	switch (tag->flags & 0x7) {
1122 	case 0:
1123 		/*
1124 		 * The allocation descriptor field is filled with short_ad's.
1125 		 * If the offset is beyond the current extent, look for the
1126 		 * next extent.
1127 		 */
1128 		do {
1129 			offset -= icblen;
1130 			ad_offset = sizeof(struct short_ad) * ad_num;
1131 			if (ad_offset > fentry->l_ad) {
1132 				printf("File offset out of bounds\n");
1133 				return (EINVAL);
1134 			}
1135 			icb = GETICB(long_ad, fentry, fentry->l_ea + ad_offset);
1136 			icblen = GETICBLEN(short_ad, icb);
1137 			ad_num++;
1138 		} while(offset >= icblen);
1139 
1140 		lsector = (offset  >> udfmp->bshift) +
1141 		    ((struct short_ad *)(icb))->pos;
1142 
1143 		*max_size = GETICBLEN(short_ad, icb);
1144 
1145 		break;
1146 	case 1:
1147 		/*
1148 		 * The allocation descriptor field is filled with long_ad's
1149 		 * If the offset is beyond the current extent, look for the
1150 		 * next extent.
1151 		 */
1152 		do {
1153 			offset -= icblen;
1154 			ad_offset = sizeof(struct long_ad) * ad_num;
1155 			if (ad_offset > fentry->l_ad) {
1156 				printf("File offset out of bounds\n");
1157 				return (EINVAL);
1158 			}
1159 			icb = GETICB(long_ad, fentry, fentry->l_ea + ad_offset);
1160 			icblen = GETICBLEN(long_ad, icb);
1161 			ad_num++;
1162 		} while(offset >= icblen);
1163 
1164 		lsector = (offset >> udfmp->bshift) +
1165 		    ((struct long_ad *)(icb))->loc.lb_num;
1166 
1167 		*max_size = GETICBLEN(long_ad, icb);
1168 
1169 		break;
1170 	case 3:
1171 		/*
1172 		 * This type means that the file *data* is stored in the
1173 		 * allocation descriptor field of the file entry.
1174 		 */
1175 		*max_size = 0;
1176 		*sector = node->hash_id + udfmp->part_start;
1177 
1178 		return (UDF_INVALID_BMAP);
1179 	case 2:
1180 		/* DirectCD does not use extended_ad's */
1181 	default:
1182 		printf("Unsupported allocation descriptor %d\n",
1183 		       tag->flags & 0x7);
1184 		return (ENODEV);
1185 	}
1186 
1187 	*sector = lsector + udfmp->part_start;
1188 
1189 	/*
1190 	 * Check the sparing table.  Each entry represents the beginning of
1191 	 * a packet.
1192 	 */
1193 	if (udfmp->s_table != NULL) {
1194 		for (i = 0; i< udfmp->s_table_entries; i++) {
1195 			p_offset = lsector - udfmp->s_table->entries[i].org;
1196 			if ((p_offset < udfmp->p_sectors) && (p_offset >= 0)) {
1197 				*sector = udfmp->s_table->entries[i].map +
1198 				    p_offset;
1199 				break;
1200 			}
1201 		}
1202 	}
1203 
1204 	return (0);
1205 }
1206