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