]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/udf/udf_vnops.c
zfs: merge openzfs/zfs@feff9dfed
[FreeBSD/FreeBSD.git] / sys / fs / udf / udf_vnops.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001, 2002 Scott Long <scottl@freebsd.org>
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 AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30
31 /* udf_vnops.c */
32 /* Take care of the vnode side of things */
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/namei.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/stat.h>
40 #include <sys/bio.h>
41 #include <sys/conf.h>
42 #include <sys/buf.h>
43 #include <sys/iconv.h>
44 #include <sys/mount.h>
45 #include <sys/vnode.h>
46 #include <sys/dirent.h>
47 #include <sys/queue.h>
48 #include <sys/unistd.h>
49 #include <sys/endian.h>
50
51 #include <vm/uma.h>
52
53 #include <fs/udf/ecma167-udf.h>
54 #include <fs/udf/osta.h>
55 #include <fs/udf/udf.h>
56 #include <fs/udf/udf_mount.h>
57
58 extern struct iconv_functions *udf_iconv;
59
60 static vop_access_t     udf_access;
61 static vop_getattr_t    udf_getattr;
62 static vop_open_t       udf_open;
63 static vop_ioctl_t      udf_ioctl;
64 static vop_pathconf_t   udf_pathconf;
65 static vop_print_t      udf_print;
66 static vop_read_t       udf_read;
67 static vop_readdir_t    udf_readdir;
68 static vop_readlink_t   udf_readlink;
69 static vop_setattr_t    udf_setattr;
70 static vop_strategy_t   udf_strategy;
71 static vop_bmap_t       udf_bmap;
72 static vop_cachedlookup_t       udf_lookup;
73 static vop_reclaim_t    udf_reclaim;
74 static vop_vptofh_t     udf_vptofh;
75 static int udf_readatoffset(struct udf_node *node, int *size, off_t offset,
76     struct buf **bp, uint8_t **data);
77 static int udf_bmap_internal(struct udf_node *node, off_t offset,
78     daddr_t *sector, uint32_t *max_size);
79
80 static struct vop_vector udf_vnodeops = {
81         .vop_default =          &default_vnodeops,
82
83         .vop_access =           udf_access,
84         .vop_bmap =             udf_bmap,
85         .vop_cachedlookup =     udf_lookup,
86         .vop_getattr =          udf_getattr,
87         .vop_ioctl =            udf_ioctl,
88         .vop_lookup =           vfs_cache_lookup,
89         .vop_open =             udf_open,
90         .vop_pathconf =         udf_pathconf,
91         .vop_print =            udf_print,
92         .vop_read =             udf_read,
93         .vop_readdir =          udf_readdir,
94         .vop_readlink =         udf_readlink,
95         .vop_reclaim =          udf_reclaim,
96         .vop_setattr =          udf_setattr,
97         .vop_strategy =         udf_strategy,
98         .vop_vptofh =           udf_vptofh,
99 };
100 VFS_VOP_VECTOR_REGISTER(udf_vnodeops);
101
102 struct vop_vector udf_fifoops = {
103         .vop_default =          &fifo_specops,
104         .vop_access =           udf_access,
105         .vop_getattr =          udf_getattr,
106         .vop_pathconf =         udf_pathconf,
107         .vop_print =            udf_print,
108         .vop_reclaim =          udf_reclaim,
109         .vop_setattr =          udf_setattr,
110         .vop_vptofh =           udf_vptofh,
111 };
112 VFS_VOP_VECTOR_REGISTER(udf_fifoops);
113
114 static MALLOC_DEFINE(M_UDFFID, "udf_fid", "UDF FileId structure");
115 static MALLOC_DEFINE(M_UDFDS, "udf_ds", "UDF Dirstream structure");
116
117 #define UDF_INVALID_BMAP        -1
118
119 int
120 udf_allocv(struct mount *mp, struct vnode **vpp, struct thread *td)
121 {
122         int error;
123         struct vnode *vp;
124
125         error = getnewvnode("udf", mp, &udf_vnodeops, &vp);
126         if (error) {
127                 printf("udf_allocv: failed to allocate new vnode\n");
128                 return (error);
129         }
130
131         *vpp = vp;
132         return (0);
133 }
134
135 /* Convert file entry permission (5 bits per owner/group/user) to a mode_t */
136 static mode_t
137 udf_permtomode(struct udf_node *node)
138 {
139         uint32_t perm;
140         uint16_t flags;
141         mode_t mode;
142
143         perm = le32toh(node->fentry->perm);
144         flags = le16toh(node->fentry->icbtag.flags);
145
146         mode = perm & UDF_FENTRY_PERM_USER_MASK;
147         mode |= ((perm & UDF_FENTRY_PERM_GRP_MASK) >> 2);
148         mode |= ((perm & UDF_FENTRY_PERM_OWNER_MASK) >> 4);
149         mode |= ((flags & UDF_ICB_TAG_FLAGS_STICKY) << 4);
150         mode |= ((flags & UDF_ICB_TAG_FLAGS_SETGID) << 6);
151         mode |= ((flags & UDF_ICB_TAG_FLAGS_SETUID) << 8);
152
153         return (mode);
154 }
155
156 static int
157 udf_access(struct vop_access_args *a)
158 {
159         struct vnode *vp;
160         struct udf_node *node;
161         accmode_t accmode;
162         mode_t mode;
163
164         vp = a->a_vp;
165         node = VTON(vp);
166         accmode = a->a_accmode;
167
168         if (accmode & VWRITE) {
169                 switch (vp->v_type) {
170                 case VDIR:
171                 case VLNK:
172                 case VREG:
173                         return (EROFS);
174                         /* NOT REACHED */
175                 default:
176                         break;
177                 }
178         }
179
180         mode = udf_permtomode(node);
181
182         return (vaccess(vp->v_type, mode, node->fentry->uid, node->fentry->gid,
183             accmode, a->a_cred));
184 }
185
186 static int
187 udf_open(struct vop_open_args *ap) {
188         struct udf_node *np = VTON(ap->a_vp);
189         off_t fsize;
190
191         fsize = le64toh(np->fentry->inf_len);
192         vnode_create_vobject(ap->a_vp, fsize, ap->a_td);
193         return 0;
194 }
195
196 static const int mon_lens[2][12] = {
197         {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
198         {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
199 };
200
201 static int
202 udf_isaleapyear(int year)
203 {
204         int i;
205
206         i = (year % 4) ? 0 : 1;
207         i &= (year % 100) ? 1 : 0;
208         i |= (year % 400) ? 0 : 1;
209
210         return i;
211 }
212
213 /*
214  * Timezone calculation compliments of Julian Elischer <julian@elischer.org>.
215  */
216 static void
217 udf_timetotimespec(struct timestamp *time, struct timespec *t)
218 {
219         int i, lpyear, daysinyear, year, startyear;
220         union {
221                 uint16_t        u_tz_offset;
222                 int16_t         s_tz_offset;
223         } tz;
224
225         /*
226          * DirectCD seems to like using bogus year values.
227          * Don't trust time->month as it will be used for an array index.
228          */
229         year = le16toh(time->year);
230         if (year < 1970 || time->month < 1 || time->month > 12) {
231                 t->tv_sec = 0;
232                 t->tv_nsec = 0;
233                 return;
234         }
235
236         /* Calculate the time and day */
237         t->tv_sec = time->second;
238         t->tv_sec += time->minute * 60;
239         t->tv_sec += time->hour * 3600;
240         t->tv_sec += (time->day - 1) * 3600 * 24;
241
242         /* Calculate the month */
243         lpyear = udf_isaleapyear(year);
244         t->tv_sec += mon_lens[lpyear][time->month - 1] * 3600 * 24;
245
246         /* Speed up the calculation */
247         startyear = 1970;
248         if (year > 2009) {
249                 t->tv_sec += 1262304000;
250                 startyear += 40;
251         } else if (year > 1999) {
252                 t->tv_sec += 946684800;
253                 startyear += 30;
254         } else if (year > 1989) {
255                 t->tv_sec += 631152000;
256                 startyear += 20;
257         } else if (year > 1979) {
258                 t->tv_sec += 315532800;
259                 startyear += 10;
260         }
261
262         daysinyear = (year - startyear) * 365;
263         for (i = startyear; i < year; i++)
264                 daysinyear += udf_isaleapyear(i);
265         t->tv_sec += daysinyear * 3600 * 24;
266
267         /* Calculate microseconds */
268         t->tv_nsec = time->centisec * 10000 + time->hund_usec * 100 +
269             time->usec;
270
271         /*
272          * Calculate the time zone.  The timezone is 12 bit signed 2's
273          * complement, so we gotta do some extra magic to handle it right.
274          */
275         tz.u_tz_offset = le16toh(time->type_tz);
276         tz.u_tz_offset &= 0x0fff;
277         if (tz.u_tz_offset & 0x0800)
278                 tz.u_tz_offset |= 0xf000;       /* extend the sign to 16 bits */
279         if ((le16toh(time->type_tz) & 0x1000) && (tz.s_tz_offset != -2047))
280                 t->tv_sec -= tz.s_tz_offset * 60;
281
282         return;
283 }
284
285 static int
286 udf_getattr(struct vop_getattr_args *a)
287 {
288         struct vnode *vp;
289         struct udf_node *node;
290         struct vattr *vap;
291         struct file_entry *fentry;
292
293         vp = a->a_vp;
294         vap = a->a_vap;
295         node = VTON(vp);
296         fentry = node->fentry;
297
298         vap->va_fsid = dev2udev(node->udfmp->im_dev);
299         vap->va_fileid = node->hash_id;
300         vap->va_mode = udf_permtomode(node);
301         vap->va_nlink = le16toh(fentry->link_cnt);
302         /*
303          * XXX The spec says that -1 is valid for uid/gid and indicates an
304          * invalid uid/gid.  How should this be represented?
305          */
306         vap->va_uid = (le32toh(fentry->uid) == -1) ? 0 : le32toh(fentry->uid);
307         vap->va_gid = (le32toh(fentry->gid) == -1) ? 0 : le32toh(fentry->gid);
308         udf_timetotimespec(&fentry->atime, &vap->va_atime);
309         udf_timetotimespec(&fentry->mtime, &vap->va_mtime);
310         vap->va_ctime = vap->va_mtime; /* XXX Stored as an Extended Attribute */
311         vap->va_rdev = NODEV;
312         if (vp->v_type & VDIR) {
313                 /*
314                  * Directories that are recorded within their ICB will show
315                  * as having 0 blocks recorded.  Since tradition dictates
316                  * that directories consume at least one logical block,
317                  * make it appear so.
318                  */
319                 if (fentry->logblks_rec != 0) {
320                         vap->va_size =
321                             le64toh(fentry->logblks_rec) * node->udfmp->bsize;
322                 } else {
323                         vap->va_size = node->udfmp->bsize;
324                 }
325         } else {
326                 vap->va_size = le64toh(fentry->inf_len);
327         }
328         vap->va_flags = 0;
329         vap->va_gen = 1;
330         vap->va_blocksize = node->udfmp->bsize;
331         vap->va_bytes = le64toh(fentry->inf_len);
332         vap->va_type = vp->v_type;
333         vap->va_filerev = 0; /* XXX */
334         return (0);
335 }
336
337 static int
338 udf_setattr(struct vop_setattr_args *a)
339 {
340         struct vnode *vp;
341         struct vattr *vap;
342
343         vp = a->a_vp;
344         vap = a->a_vap;
345         if (vap->va_flags != (u_long)VNOVAL || vap->va_uid != (uid_t)VNOVAL ||
346             vap->va_gid != (gid_t)VNOVAL || vap->va_atime.tv_sec != VNOVAL ||
347             vap->va_mtime.tv_sec != VNOVAL || vap->va_mode != (mode_t)VNOVAL)
348                 return (EROFS);
349         if (vap->va_size != (u_quad_t)VNOVAL) {
350                 switch (vp->v_type) {
351                 case VDIR:
352                         return (EISDIR);
353                 case VLNK:
354                 case VREG:
355                         return (EROFS);
356                 case VCHR:
357                 case VBLK:
358                 case VSOCK:
359                 case VFIFO:
360                 case VNON:
361                 case VBAD:
362                 case VMARKER:
363                         return (0);
364                 }
365         }
366         return (0);
367 }
368
369 /*
370  * File specific ioctls.
371  */
372 static int
373 udf_ioctl(struct vop_ioctl_args *a)
374 {
375         printf("%s called\n", __func__);
376         return (ENOTTY);
377 }
378
379 /*
380  * I'm not sure that this has much value in a read-only filesystem, but
381  * cd9660 has it too.
382  */
383 static int
384 udf_pathconf(struct vop_pathconf_args *a)
385 {
386
387         switch (a->a_name) {
388         case _PC_FILESIZEBITS:
389                 *a->a_retval = 64;
390                 return (0);
391         case _PC_LINK_MAX:
392                 *a->a_retval = 65535;
393                 return (0);
394         case _PC_NAME_MAX:
395                 *a->a_retval = NAME_MAX;
396                 return (0);
397         case _PC_SYMLINK_MAX:
398                 *a->a_retval = MAXPATHLEN;
399                 return (0);
400         case _PC_NO_TRUNC:
401                 *a->a_retval = 1;
402                 return (0);
403         case _PC_PIPE_BUF:
404                 if (a->a_vp->v_type == VDIR || a->a_vp->v_type == VFIFO) {
405                         *a->a_retval = PIPE_BUF;
406                         return (0);
407                 }
408                 return (EINVAL);
409         default:
410                 return (vop_stdpathconf(a));
411         }
412 }
413
414 static int
415 udf_print(struct vop_print_args *ap)
416 {
417         struct vnode *vp = ap->a_vp;
418         struct udf_node *node = VTON(vp);
419
420         printf("    ino %lu, on dev %s", (u_long)node->hash_id,
421             devtoname(node->udfmp->im_dev));
422         if (vp->v_type == VFIFO)
423                 fifo_printinfo(vp);
424         printf("\n");
425         return (0);
426 }
427
428 #define lblkno(udfmp, loc)      ((loc) >> (udfmp)->bshift)
429 #define blkoff(udfmp, loc)      ((loc) & (udfmp)->bmask)
430 #define lblktosize(udfmp, blk)  ((blk) << (udfmp)->bshift)
431
432 static inline int
433 is_data_in_fentry(const struct udf_node *node)
434 {
435         const struct file_entry *fentry = node->fentry;
436
437         return ((le16toh(fentry->icbtag.flags) & 0x7) == 3);
438 }
439
440 static int
441 udf_read(struct vop_read_args *ap)
442 {
443         struct vnode *vp = ap->a_vp;
444         struct uio *uio = ap->a_uio;
445         struct udf_node *node = VTON(vp);
446         struct udf_mnt *udfmp;
447         struct file_entry *fentry;
448         struct buf *bp;
449         uint8_t *data;
450         daddr_t lbn, rablock;
451         off_t diff, fsize;
452         ssize_t n;
453         int error = 0;
454         long size, on;
455
456         if (uio->uio_resid == 0)
457                 return (0);
458         if (uio->uio_offset < 0)
459                 return (EINVAL);
460
461         if (is_data_in_fentry(node)) {
462                 fentry = node->fentry;
463                 data = &fentry->data[le32toh(fentry->l_ea)];
464                 fsize = le32toh(fentry->l_ad);
465
466                 n = uio->uio_resid;
467                 diff = fsize - uio->uio_offset;
468                 if (diff <= 0)
469                         return (0);
470                 if (diff < n)
471                         n = diff;
472                 error = uiomove(data + uio->uio_offset, (int)n, uio);
473                 return (error);
474         }
475
476         fsize = le64toh(node->fentry->inf_len);
477         udfmp = node->udfmp;
478         do {
479                 lbn = lblkno(udfmp, uio->uio_offset);
480                 on = blkoff(udfmp, uio->uio_offset);
481                 n = min((u_int)(udfmp->bsize - on),
482                         uio->uio_resid);
483                 diff = fsize - uio->uio_offset;
484                 if (diff <= 0)
485                         return (0);
486                 if (diff < n)
487                         n = diff;
488                 size = udfmp->bsize;
489                 rablock = lbn + 1;
490                 if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERR) == 0) {
491                         if (lblktosize(udfmp, rablock) < fsize) {
492                                 error = cluster_read(vp, fsize, lbn, size,
493                                     NOCRED, uio->uio_resid,
494                                     (ap->a_ioflag >> 16), 0, &bp);
495                         } else {
496                                 error = bread(vp, lbn, size, NOCRED, &bp);
497                         }
498                 } else {
499                         error = bread(vp, lbn, size, NOCRED, &bp);
500                 }
501                 if (error != 0) {
502                         brelse(bp);
503                         return (error);
504                 }
505                 n = min(n, size - bp->b_resid);
506
507                 error = uiomove(bp->b_data + on, (int)n, uio);
508                 brelse(bp);
509         } while (error == 0 && uio->uio_resid > 0 && n != 0);
510         return (error);
511 }
512
513 /*
514  * Call the OSTA routines to translate the name from a CS0 dstring to a
515  * 16-bit Unicode String.  Hooks need to be placed in here to translate from
516  * Unicode to the encoding that the kernel/user expects.  Return the length
517  * of the translated string.
518  */
519 static int
520 udf_transname(char *cs0string, char *destname, int len, struct udf_mnt *udfmp)
521 {
522         unicode_t *transname;
523         char *unibuf, *unip;
524         int i, destlen;
525         ssize_t unilen = 0;
526         size_t destleft = MAXNAMLEN;
527
528         /* Convert 16-bit Unicode to destname */
529         if (udfmp->im_flags & UDFMNT_KICONV && udf_iconv) {
530                 /* allocate a buffer big enough to hold an 8->16 bit expansion */
531                 unibuf = uma_zalloc(udf_zone_trans, M_WAITOK);
532                 unip = unibuf;
533                 if ((unilen = (ssize_t)udf_UncompressUnicodeByte(len, cs0string, unibuf)) == -1) {
534                         printf("udf: Unicode translation failed\n");
535                         uma_zfree(udf_zone_trans, unibuf);
536                         return 0;
537                 }
538
539                 while (unilen > 0 && destleft > 0) {
540                         udf_iconv->conv(udfmp->im_d2l, __DECONST(const char **,
541                             &unibuf), (size_t *)&unilen, (char **)&destname,
542                             &destleft);
543                         /* Unconverted character found */
544                         if (unilen > 0 && destleft > 0) {
545                                 *destname++ = '?';
546                                 destleft--;
547                                 unibuf += 2;
548                                 unilen -= 2;
549                         }
550                 }
551                 uma_zfree(udf_zone_trans, unip);
552                 *destname = '\0';
553                 destlen = MAXNAMLEN - (int)destleft;
554         } else {
555                 /* allocate a buffer big enough to hold an 8->16 bit expansion */
556                 transname = uma_zalloc(udf_zone_trans, M_WAITOK);
557
558                 if ((unilen = (ssize_t)udf_UncompressUnicode(len, cs0string, transname)) == -1) {
559                         printf("udf: Unicode translation failed\n");
560                         uma_zfree(udf_zone_trans, transname);
561                         return 0;
562                 }
563
564                 for (i = 0; i < unilen ; i++) {
565                         if (transname[i] & 0xff00) {
566                                 destname[i] = '.';      /* Fudge the 16bit chars */
567                         } else {
568                                 destname[i] = transname[i] & 0xff;
569                         }
570                 }
571                 uma_zfree(udf_zone_trans, transname);
572                 destname[unilen] = 0;
573                 destlen = (int)unilen;
574         }
575
576         return (destlen);
577 }
578
579 /*
580  * Compare a CS0 dstring with a name passed in from the VFS layer.  Return
581  * 0 on a successful match, nonzero otherwise.  Unicode work may need to be done
582  * here also.
583  */
584 static int
585 udf_cmpname(char *cs0string, char *cmpname, int cs0len, int cmplen, struct udf_mnt *udfmp)
586 {
587         char *transname;
588         int error = 0;
589
590         /* This is overkill, but not worth creating a new zone */
591         transname = uma_zalloc(udf_zone_trans, M_WAITOK);
592
593         cs0len = udf_transname(cs0string, transname, cs0len, udfmp);
594
595         /* Easy check.  If they aren't the same length, they aren't equal */
596         if ((cs0len == 0) || (cs0len != cmplen))
597                 error = -1;
598         else
599                 error = bcmp(transname, cmpname, cmplen);
600
601         uma_zfree(udf_zone_trans, transname);
602         return (error);
603 }
604
605 struct udf_uiodir {
606         struct dirent *dirent;
607         uint64_t *cookies;
608         int ncookies;
609         int acookies;
610         int eofflag;
611 };
612
613 static int
614 udf_uiodir(struct udf_uiodir *uiodir, int de_size, struct uio *uio, long cookie)
615 {
616         if (uiodir->cookies != NULL) {
617                 if (++uiodir->acookies > uiodir->ncookies) {
618                         uiodir->eofflag = 0;
619                         return (-1);
620                 }
621                 *uiodir->cookies++ = cookie;
622         }
623
624         if (uio->uio_resid < de_size) {
625                 uiodir->eofflag = 0;
626                 return (-1);
627         }
628
629         return (uiomove(uiodir->dirent, de_size, uio));
630 }
631
632 static struct udf_dirstream *
633 udf_opendir(struct udf_node *node, int offset, int fsize, struct udf_mnt *udfmp)
634 {
635         struct udf_dirstream *ds;
636
637         ds = uma_zalloc(udf_zone_ds, M_WAITOK | M_ZERO);
638
639         ds->node = node;
640         ds->offset = offset;
641         ds->udfmp = udfmp;
642         ds->fsize = fsize;
643
644         return (ds);
645 }
646
647 static struct fileid_desc *
648 udf_getfid(struct udf_dirstream *ds)
649 {
650         struct fileid_desc *fid;
651         int error, frag_size = 0, total_fid_size;
652
653         /* End of directory? */
654         if (ds->offset + ds->off >= ds->fsize) {
655                 ds->error = 0;
656                 return (NULL);
657         }
658
659         /* Grab the first extent of the directory */
660         if (ds->off == 0) {
661                 ds->size = 0;
662                 error = udf_readatoffset(ds->node, &ds->size, ds->offset,
663                     &ds->bp, &ds->data);
664                 if (error) {
665                         ds->error = error;
666                         if (ds->bp != NULL)
667                                 brelse(ds->bp);
668                         return (NULL);
669                 }
670         }
671
672         /*
673          * Clean up from a previous fragmented FID.
674          * XXX Is this the right place for this?
675          */
676         if (ds->fid_fragment && ds->buf != NULL) {
677                 ds->fid_fragment = 0;
678                 free(ds->buf, M_UDFFID);
679         }
680
681         fid = (struct fileid_desc*)&ds->data[ds->off];
682
683         /*
684          * Check to see if the fid is fragmented. The first test
685          * ensures that we don't wander off the end of the buffer
686          * looking for the l_iu and l_fi fields.
687          */
688         if (ds->off + UDF_FID_SIZE > ds->size ||
689             ds->off + le16toh(fid->l_iu) + fid->l_fi + UDF_FID_SIZE > ds->size){
690                 /* Copy what we have of the fid into a buffer */
691                 frag_size = ds->size - ds->off;
692                 if (frag_size >= ds->udfmp->bsize) {
693                         printf("udf: invalid FID fragment\n");
694                         ds->error = EINVAL;
695                         return (NULL);
696                 }
697
698                 /*
699                  * File ID descriptors can only be at most one
700                  * logical sector in size.
701                  */
702                 ds->buf = malloc(ds->udfmp->bsize, M_UDFFID,
703                      M_WAITOK | M_ZERO);
704                 bcopy(fid, ds->buf, frag_size);
705
706                 /* Reduce all of the casting magic */
707                 fid = (struct fileid_desc*)ds->buf;
708
709                 if (ds->bp != NULL)
710                         brelse(ds->bp);
711
712                 /* Fetch the next allocation */
713                 ds->offset += ds->size;
714                 ds->size = 0;
715                 error = udf_readatoffset(ds->node, &ds->size, ds->offset,
716                     &ds->bp, &ds->data);
717                 if (error) {
718                         ds->error = error;
719                         return (NULL);
720                 }
721
722                 /*
723                  * If the fragment was so small that we didn't get
724                  * the l_iu and l_fi fields, copy those in.
725                  */
726                 if (frag_size < UDF_FID_SIZE)
727                         bcopy(ds->data, &ds->buf[frag_size],
728                             UDF_FID_SIZE - frag_size);
729
730                 /*
731                  * Now that we have enough of the fid to work with,
732                  * copy in the rest of the fid from the new
733                  * allocation.
734                  */
735                 total_fid_size = UDF_FID_SIZE + le16toh(fid->l_iu) + fid->l_fi;
736                 if (total_fid_size > ds->udfmp->bsize) {
737                         printf("udf: invalid FID\n");
738                         ds->error = EIO;
739                         return (NULL);
740                 }
741                 bcopy(ds->data, &ds->buf[frag_size],
742                     total_fid_size - frag_size);
743
744                 ds->fid_fragment = 1;
745         } else {
746                 total_fid_size = le16toh(fid->l_iu) + fid->l_fi + UDF_FID_SIZE;
747         }
748
749         /*
750          * Update the offset. Align on a 4 byte boundary because the
751          * UDF spec says so.
752          */
753         ds->this_off = ds->offset + ds->off;
754         if (!ds->fid_fragment) {
755                 ds->off += (total_fid_size + 3) & ~0x03;
756         } else {
757                 ds->off = (total_fid_size - frag_size + 3) & ~0x03;
758         }
759
760         return (fid);
761 }
762
763 static void
764 udf_closedir(struct udf_dirstream *ds)
765 {
766
767         if (ds->bp != NULL)
768                 brelse(ds->bp);
769
770         if (ds->fid_fragment && ds->buf != NULL)
771                 free(ds->buf, M_UDFFID);
772
773         uma_zfree(udf_zone_ds, ds);
774 }
775
776 static int
777 udf_readdir(struct vop_readdir_args *a)
778 {
779         struct vnode *vp;
780         struct uio *uio;
781         struct dirent dir;
782         struct udf_node *node;
783         struct udf_mnt *udfmp;
784         struct fileid_desc *fid;
785         struct udf_uiodir uiodir;
786         struct udf_dirstream *ds;
787         uint64_t *cookies = NULL;
788         int ncookies;
789         int error = 0;
790
791         vp = a->a_vp;
792         uio = a->a_uio;
793         node = VTON(vp);
794         udfmp = node->udfmp;
795         uiodir.eofflag = 1;
796
797         if (a->a_ncookies != NULL) {
798                 /*
799                  * Guess how many entries are needed.  If we run out, this
800                  * function will be called again and thing will pick up were
801                  * it left off.
802                  */
803                 ncookies = uio->uio_resid / 8;
804                 cookies = malloc(sizeof(*cookies) * ncookies, M_TEMP, M_WAITOK);
805                 if (cookies == NULL)
806                         return (ENOMEM);
807                 uiodir.ncookies = ncookies;
808                 uiodir.cookies = cookies;
809                 uiodir.acookies = 0;
810         } else {
811                 uiodir.cookies = NULL;
812         }
813
814         /*
815          * Iterate through the file id descriptors.  Give the parent dir
816          * entry special attention.
817          */
818         ds = udf_opendir(node, uio->uio_offset, le64toh(node->fentry->inf_len),
819             node->udfmp);
820
821         while ((fid = udf_getfid(ds)) != NULL) {
822                 /* XXX Should we return an error on a bad fid? */
823                 if (udf_checktag(&fid->tag, TAGID_FID)) {
824                         printf("Invalid FID tag\n");
825                         hexdump(fid, UDF_FID_SIZE, NULL, 0);
826                         error = EIO;
827                         break;
828                 }
829
830                 /* Is this a deleted file? */
831                 if (fid->file_char & UDF_FILE_CHAR_DEL)
832                         continue;
833
834                 if ((fid->l_fi == 0) && (fid->file_char & UDF_FILE_CHAR_PAR)) {
835                         /* Do up the '.' and '..' entries.  Dummy values are
836                          * used for the cookies since the offset here is
837                          * usually zero, and NFS doesn't like that value
838                          */
839                         dir.d_fileno = node->hash_id;
840                         dir.d_type = DT_DIR;
841                         dir.d_name[0] = '.';
842                         dir.d_namlen = 1;
843                         dir.d_reclen = GENERIC_DIRSIZ(&dir);
844                         dir.d_off = 1;
845                         dirent_terminate(&dir);
846                         uiodir.dirent = &dir;
847                         error = udf_uiodir(&uiodir, dir.d_reclen, uio, 1);
848                         if (error)
849                                 break;
850
851                         dir.d_fileno = udf_getid(&fid->icb);
852                         dir.d_type = DT_DIR;
853                         dir.d_name[0] = '.';
854                         dir.d_name[1] = '.';
855                         dir.d_namlen = 2;
856                         dir.d_reclen = GENERIC_DIRSIZ(&dir);
857                         dir.d_off = 2;
858                         dirent_terminate(&dir);
859                         uiodir.dirent = &dir;
860                         error = udf_uiodir(&uiodir, dir.d_reclen, uio, 2);
861                 } else {
862                         dir.d_namlen = udf_transname(&fid->data[fid->l_iu],
863                             &dir.d_name[0], fid->l_fi, udfmp);
864                         dir.d_fileno = udf_getid(&fid->icb);
865                         dir.d_type = (fid->file_char & UDF_FILE_CHAR_DIR) ?
866                             DT_DIR : DT_UNKNOWN;
867                         dir.d_reclen = GENERIC_DIRSIZ(&dir);
868                         dir.d_off = ds->this_off;
869                         dirent_terminate(&dir);
870                         uiodir.dirent = &dir;
871                         error = udf_uiodir(&uiodir, dir.d_reclen, uio,
872                             ds->this_off);
873                 }
874                 if (error)
875                         break;
876                 uio->uio_offset = ds->offset + ds->off;
877         }
878
879         /* tell the calling layer whether we need to be called again */
880         *a->a_eofflag = uiodir.eofflag;
881
882         if (error < 0)
883                 error = 0;
884         if (!error)
885                 error = ds->error;
886
887         udf_closedir(ds);
888
889         if (a->a_ncookies != NULL) {
890                 if (error)
891                         free(cookies, M_TEMP);
892                 else {
893                         *a->a_ncookies = uiodir.acookies;
894                         *a->a_cookies = cookies;
895                 }
896         }
897
898         return (error);
899 }
900
901 static int
902 udf_readlink(struct vop_readlink_args *ap)
903 {
904         struct path_component *pc, *end;
905         struct vnode *vp;
906         struct uio uio;
907         struct iovec iov[1];
908         struct udf_node *node;
909         void *buf;
910         char *cp;
911         int error, len, root;
912
913         /*
914          * A symbolic link in UDF is a list of variable-length path
915          * component structures.  We build a pathname in the caller's
916          * uio by traversing this list.
917          */
918         vp = ap->a_vp;
919         node = VTON(vp);
920         len = le64toh(node->fentry->inf_len);
921         buf = malloc(len, M_DEVBUF, M_WAITOK);
922         iov[0].iov_len = len;
923         iov[0].iov_base = buf;
924         uio.uio_iov = iov;
925         uio.uio_iovcnt = 1;
926         uio.uio_offset = 0;
927         uio.uio_resid = iov[0].iov_len;
928         uio.uio_segflg = UIO_SYSSPACE;
929         uio.uio_rw = UIO_READ;
930         uio.uio_td = curthread;
931         error = VOP_READ(vp, &uio, 0, ap->a_cred);
932         if (error)
933                 goto error;
934
935         pc = buf;
936         end = (void *)((char *)buf + len);
937         root = 0;
938         while (pc < end) {
939                 switch (pc->type) {
940                 case UDF_PATH_ROOT:
941                         /* Only allow this at the beginning of a path. */
942                         if ((void *)pc != buf) {
943                                 error = EINVAL;
944                                 goto error;
945                         }
946                         cp = "/";
947                         len = 1;
948                         root = 1;
949                         break;
950                 case UDF_PATH_DOT:
951                         cp = ".";
952                         len = 1;
953                         break;
954                 case UDF_PATH_DOTDOT:
955                         cp = "..";
956                         len = 2;
957                         break;
958                 case UDF_PATH_PATH:
959                         if (pc->length == 0) {
960                                 error = EINVAL;
961                                 goto error;
962                         }
963                         /*
964                          * XXX: We only support CS8 which appears to map
965                          * to ASCII directly.
966                          */
967                         switch (pc->identifier[0]) {
968                         case 8:
969                                 cp = pc->identifier + 1;
970                                 len = pc->length - 1;
971                                 break;
972                         default:
973                                 error = EOPNOTSUPP;
974                                 goto error;
975                         }
976                         break;
977                 default:
978                         error = EINVAL;
979                         goto error;
980                 }
981
982                 /*
983                  * If this is not the first component, insert a path
984                  * separator.
985                  */
986                 if (pc != buf) {
987                         /* If we started with root we already have a "/". */
988                         if (root)
989                                 goto skipslash;
990                         root = 0;
991                         if (ap->a_uio->uio_resid < 1) {
992                                 error = ENAMETOOLONG;
993                                 goto error;
994                         }
995                         error = uiomove("/", 1, ap->a_uio);
996                         if (error)
997                                 break;
998                 }
999         skipslash:
1000
1001                 /* Append string at 'cp' of length 'len' to our path. */
1002                 if (len > ap->a_uio->uio_resid) {
1003                         error = ENAMETOOLONG;
1004                         goto error;
1005                 }
1006                 error = uiomove(cp, len, ap->a_uio);
1007                 if (error)
1008                         break;
1009
1010                 /* Advance to next component. */
1011                 pc = (void *)((char *)pc + 4 + pc->length);
1012         }
1013 error:
1014         free(buf, M_DEVBUF);
1015         return (error);
1016 }
1017
1018 static int
1019 udf_strategy(struct vop_strategy_args *a)
1020 {
1021         struct buf *bp;
1022         struct vnode *vp;
1023         struct udf_node *node;
1024         struct bufobj *bo;
1025         off_t offset;
1026         uint32_t maxsize;
1027         daddr_t sector;
1028         int error;
1029
1030         bp = a->a_bp;
1031         vp = a->a_vp;
1032         node = VTON(vp);
1033
1034         if (bp->b_blkno == bp->b_lblkno) {
1035                 offset = lblktosize(node->udfmp, bp->b_lblkno);
1036                 error = udf_bmap_internal(node, offset, &sector, &maxsize);
1037                 if (error) {
1038                         clrbuf(bp);
1039                         bp->b_blkno = -1;
1040                         bufdone(bp);
1041                         return (0);
1042                 }
1043                 /* bmap gives sector numbers, bio works with device blocks */
1044                 bp->b_blkno = sector << (node->udfmp->bshift - DEV_BSHIFT);
1045         }
1046         bo = node->udfmp->im_bo;
1047         bp->b_iooffset = dbtob(bp->b_blkno);
1048         BO_STRATEGY(bo, bp);
1049         return (0);
1050 }
1051
1052 static int
1053 udf_bmap(struct vop_bmap_args *a)
1054 {
1055         struct udf_node *node;
1056         uint32_t max_size;
1057         daddr_t lsector;
1058         int nblk;
1059         int error;
1060
1061         node = VTON(a->a_vp);
1062
1063         if (a->a_bop != NULL)
1064                 *a->a_bop = &node->udfmp->im_devvp->v_bufobj;
1065         if (a->a_bnp == NULL)
1066                 return (0);
1067         if (a->a_runb)
1068                 *a->a_runb = 0;
1069
1070         /*
1071          * UDF_INVALID_BMAP means data embedded into fentry, this is an internal
1072          * error that should not be propagated to calling code.
1073          * Most obvious mapping for this error is EOPNOTSUPP as we can not truly
1074          * translate block numbers in this case.
1075          * Incidentally, this return code will make vnode pager to use VOP_READ
1076          * to get data for mmap-ed pages and udf_read knows how to do the right
1077          * thing for this kind of files.
1078          */
1079         error = udf_bmap_internal(node, a->a_bn << node->udfmp->bshift,
1080             &lsector, &max_size);
1081         if (error == UDF_INVALID_BMAP)
1082                 return (EOPNOTSUPP);
1083         if (error)
1084                 return (error);
1085
1086         /* Translate logical to physical sector number */
1087         *a->a_bnp = lsector << (node->udfmp->bshift - DEV_BSHIFT);
1088
1089         /*
1090          * Determine maximum number of readahead blocks following the
1091          * requested block.
1092          */
1093         if (a->a_runp) {
1094                 nblk = (max_size >> node->udfmp->bshift) - 1;
1095                 if (nblk <= 0)
1096                         *a->a_runp = 0;
1097                 else if (nblk >= (MAXBSIZE >> node->udfmp->bshift))
1098                         *a->a_runp = (MAXBSIZE >> node->udfmp->bshift) - 1;
1099                 else
1100                         *a->a_runp = nblk;
1101         }
1102
1103         if (a->a_runb) {
1104                 *a->a_runb = 0;
1105         }
1106
1107         return (0);
1108 }
1109
1110 /*
1111  * The all powerful VOP_LOOKUP().
1112  */
1113 static int
1114 udf_lookup(struct vop_cachedlookup_args *a)
1115 {
1116         struct vnode *dvp;
1117         struct vnode *tdp = NULL;
1118         struct vnode **vpp = a->a_vpp;
1119         struct udf_node *node;
1120         struct udf_mnt *udfmp;
1121         struct fileid_desc *fid = NULL;
1122         struct udf_dirstream *ds;
1123         u_long nameiop;
1124         u_long flags;
1125         char *nameptr;
1126         long namelen;
1127         ino_t id = 0;
1128         int offset, error = 0;
1129         int fsize, lkflags, ltype, numdirpasses;
1130
1131         dvp = a->a_dvp;
1132         node = VTON(dvp);
1133         udfmp = node->udfmp;
1134         nameiop = a->a_cnp->cn_nameiop;
1135         flags = a->a_cnp->cn_flags;
1136         lkflags = a->a_cnp->cn_lkflags;
1137         nameptr = a->a_cnp->cn_nameptr;
1138         namelen = a->a_cnp->cn_namelen;
1139         fsize = le64toh(node->fentry->inf_len);
1140
1141         /*
1142          * If this is a LOOKUP and we've already partially searched through
1143          * the directory, pick up where we left off and flag that the
1144          * directory may need to be searched twice.  For a full description,
1145          * see /sys/fs/cd9660/cd9660_lookup.c:cd9660_lookup()
1146          */
1147         if (nameiop != LOOKUP || node->diroff == 0 || node->diroff > fsize) {
1148                 offset = 0;
1149                 numdirpasses = 1;
1150         } else {
1151                 offset = node->diroff;
1152                 numdirpasses = 2;
1153                 nchstats.ncs_2passes++;
1154         }
1155
1156 lookloop:
1157         ds = udf_opendir(node, offset, fsize, udfmp);
1158
1159         while ((fid = udf_getfid(ds)) != NULL) {
1160                 /* XXX Should we return an error on a bad fid? */
1161                 if (udf_checktag(&fid->tag, TAGID_FID)) {
1162                         printf("udf_lookup: Invalid tag\n");
1163                         error = EIO;
1164                         break;
1165                 }
1166
1167                 /* Is this a deleted file? */
1168                 if (fid->file_char & UDF_FILE_CHAR_DEL)
1169                         continue;
1170
1171                 if ((fid->l_fi == 0) && (fid->file_char & UDF_FILE_CHAR_PAR)) {
1172                         if (flags & ISDOTDOT) {
1173                                 id = udf_getid(&fid->icb);
1174                                 break;
1175                         }
1176                 } else {
1177                         if (!(udf_cmpname(&fid->data[fid->l_iu],
1178                             nameptr, fid->l_fi, namelen, udfmp))) {
1179                                 id = udf_getid(&fid->icb);
1180                                 break;
1181                         }
1182                 }
1183         }
1184
1185         if (!error)
1186                 error = ds->error;
1187
1188         /* XXX Bail out here? */
1189         if (error) {
1190                 udf_closedir(ds);
1191                 return (error);
1192         }
1193
1194         /* Did we have a match? */
1195         if (id) {
1196                 /*
1197                  * Remember where this entry was if it's the final
1198                  * component.
1199                  */
1200                 if ((flags & ISLASTCN) && nameiop == LOOKUP)
1201                         node->diroff = ds->offset + ds->off;
1202                 if (numdirpasses == 2)
1203                         nchstats.ncs_pass2++;
1204                 udf_closedir(ds);
1205
1206                 if (flags & ISDOTDOT) {
1207                         error = vn_vget_ino(dvp, id, lkflags, &tdp);
1208                 } else if (node->hash_id == id) {
1209                         VREF(dvp);      /* we want ourself, ie "." */
1210                         /*
1211                          * When we lookup "." we still can be asked to lock it
1212                          * differently.
1213                          */
1214                         ltype = lkflags & LK_TYPE_MASK;
1215                         if (ltype != VOP_ISLOCKED(dvp)) {
1216                                 if (ltype == LK_EXCLUSIVE)
1217                                         vn_lock(dvp, LK_UPGRADE | LK_RETRY);
1218                                 else /* if (ltype == LK_SHARED) */
1219                                         vn_lock(dvp, LK_DOWNGRADE | LK_RETRY);
1220                         }
1221                         tdp = dvp;
1222                 } else
1223                         error = udf_vget(udfmp->im_mountp, id, lkflags, &tdp);
1224                 if (!error) {
1225                         *vpp = tdp;
1226                         /* Put this entry in the cache */
1227                         if (flags & MAKEENTRY)
1228                                 cache_enter(dvp, *vpp, a->a_cnp);
1229                 }
1230         } else {
1231                 /* Name wasn't found on this pass.  Do another pass? */
1232                 if (numdirpasses == 2) {
1233                         numdirpasses--;
1234                         offset = 0;
1235                         udf_closedir(ds);
1236                         goto lookloop;
1237                 }
1238                 udf_closedir(ds);
1239
1240                 /* Enter name into cache as non-existant */
1241                 if (flags & MAKEENTRY)
1242                         cache_enter(dvp, *vpp, a->a_cnp);
1243
1244                 if ((flags & ISLASTCN) &&
1245                     (nameiop == CREATE || nameiop == RENAME)) {
1246                         error = EROFS;
1247                 } else {
1248                         error = ENOENT;
1249                 }
1250         }
1251
1252         return (error);
1253 }
1254
1255 static int
1256 udf_reclaim(struct vop_reclaim_args *a)
1257 {
1258         struct vnode *vp;
1259         struct udf_node *unode;
1260
1261         vp = a->a_vp;
1262         unode = VTON(vp);
1263
1264         if (unode != NULL) {
1265                 vfs_hash_remove(vp);
1266
1267                 if (unode->fentry != NULL)
1268                         free(unode->fentry, M_UDFFENTRY);
1269                 uma_zfree(udf_zone_node, unode);
1270                 vp->v_data = NULL;
1271         }
1272
1273         return (0);
1274 }
1275
1276 static int
1277 udf_vptofh(struct vop_vptofh_args *a)
1278 {
1279         struct udf_node *node;
1280         struct ifid *ifhp;
1281
1282         node = VTON(a->a_vp);
1283         ifhp = (struct ifid *)a->a_fhp;
1284         ifhp->ifid_len = sizeof(struct ifid);
1285         ifhp->ifid_ino = node->hash_id;
1286
1287         return (0);
1288 }
1289
1290 /*
1291  * Read the block and then set the data pointer to correspond with the
1292  * offset passed in.  Only read in at most 'size' bytes, and then set 'size'
1293  * to the number of bytes pointed to.  If 'size' is zero, try to read in a
1294  * whole extent.
1295  *
1296  * Note that *bp may be assigned error or not.
1297  *
1298  */
1299 static int
1300 udf_readatoffset(struct udf_node *node, int *size, off_t offset,
1301     struct buf **bp, uint8_t **data)
1302 {
1303         struct udf_mnt *udfmp = node->udfmp;
1304         struct vnode *vp = node->i_vnode;
1305         struct file_entry *fentry;
1306         struct buf *bp1;
1307         uint32_t max_size;
1308         daddr_t sector;
1309         off_t off;
1310         int adj_size;
1311         int error;
1312
1313         /*
1314          * This call is made *not* only to detect UDF_INVALID_BMAP case,
1315          * max_size is used as an ad-hoc read-ahead hint for "normal" case.
1316          */
1317         error = udf_bmap_internal(node, offset, &sector, &max_size);
1318         if (error == UDF_INVALID_BMAP) {
1319                 /*
1320                  * This error means that the file *data* is stored in the
1321                  * allocation descriptor field of the file entry.
1322                  */
1323                 fentry = node->fentry;
1324                 *data = &fentry->data[le32toh(fentry->l_ea)];
1325                 *size = le32toh(fentry->l_ad);
1326                 if (offset >= *size)
1327                         *size = 0;
1328                 else {
1329                         *data += offset;
1330                         *size -= offset;
1331                 }
1332                 return (0);
1333         } else if (error != 0) {
1334                 return (error);
1335         }
1336
1337         /* Adjust the size so that it is within range */
1338         if (*size == 0 || *size > max_size)
1339                 *size = max_size;
1340
1341         /*
1342          * Because we will read starting at block boundary, we need to adjust
1343          * how much we need to read so that all promised data is in.
1344          * Also, we can't promise to read more than MAXBSIZE bytes starting
1345          * from block boundary, so adjust what we promise too.
1346          */
1347         off = blkoff(udfmp, offset);
1348         *size = min(*size, MAXBSIZE - off);
1349         adj_size = (*size + off + udfmp->bmask) & ~udfmp->bmask;
1350         *bp = NULL;
1351         if ((error = bread(vp, lblkno(udfmp, offset), adj_size, NOCRED, bp))) {
1352                 printf("warning: udf_readlblks returned error %d\n", error);
1353                 /* note: *bp may be non-NULL */
1354                 return (error);
1355         }
1356
1357         bp1 = *bp;
1358         *data = (uint8_t *)&bp1->b_data[offset & udfmp->bmask];
1359         return (0);
1360 }
1361
1362 /*
1363  * Translate a file offset into a logical block and then into a physical
1364  * block.
1365  * max_size - maximum number of bytes that can be read starting from given
1366  * offset, rather than beginning of calculated sector number
1367  */
1368 static int
1369 udf_bmap_internal(struct udf_node *node, off_t offset, daddr_t *sector,
1370     uint32_t *max_size)
1371 {
1372         struct udf_mnt *udfmp;
1373         struct file_entry *fentry;
1374         void *icb;
1375         struct icb_tag *tag;
1376         uint32_t icblen = 0;
1377         daddr_t lsector;
1378         int ad_offset, ad_num = 0;
1379         int i, p_offset;
1380
1381         udfmp = node->udfmp;
1382         fentry = node->fentry;
1383         tag = &fentry->icbtag;
1384
1385         switch (le16toh(tag->strat_type)) {
1386         case 4:
1387                 break;
1388
1389         case 4096:
1390                 printf("Cannot deal with strategy4096 yet!\n");
1391                 return (ENODEV);
1392
1393         default:
1394                 printf("Unknown strategy type %d\n", tag->strat_type);
1395                 return (ENODEV);
1396         }
1397
1398         switch (le16toh(tag->flags) & 0x7) {
1399         case 0:
1400                 /*
1401                  * The allocation descriptor field is filled with short_ad's.
1402                  * If the offset is beyond the current extent, look for the
1403                  * next extent.
1404                  */
1405                 do {
1406                         offset -= icblen;
1407                         ad_offset = sizeof(struct short_ad) * ad_num;
1408                         if (ad_offset > le32toh(fentry->l_ad)) {
1409                                 printf("File offset out of bounds\n");
1410                                 return (EINVAL);
1411                         }
1412                         icb = GETICB(short_ad, fentry,
1413                             le32toh(fentry->l_ea) + ad_offset);
1414                         icblen = GETICBLEN(short_ad, icb);
1415                         ad_num++;
1416                 } while(offset >= icblen);
1417
1418                 lsector = (offset  >> udfmp->bshift) +
1419                     le32toh(((struct short_ad *)(icb))->pos);
1420
1421                 *max_size = icblen - offset;
1422
1423                 break;
1424         case 1:
1425                 /*
1426                  * The allocation descriptor field is filled with long_ad's
1427                  * If the offset is beyond the current extent, look for the
1428                  * next extent.
1429                  */
1430                 do {
1431                         offset -= icblen;
1432                         ad_offset = sizeof(struct long_ad) * ad_num;
1433                         if (ad_offset > le32toh(fentry->l_ad)) {
1434                                 printf("File offset out of bounds\n");
1435                                 return (EINVAL);
1436                         }
1437                         icb = GETICB(long_ad, fentry,
1438                             le32toh(fentry->l_ea) + ad_offset);
1439                         icblen = GETICBLEN(long_ad, icb);
1440                         ad_num++;
1441                 } while(offset >= icblen);
1442
1443                 lsector = (offset >> udfmp->bshift) +
1444                     le32toh(((struct long_ad *)(icb))->loc.lb_num);
1445
1446                 *max_size = icblen - offset;
1447
1448                 break;
1449         case 3:
1450                 /*
1451                  * This type means that the file *data* is stored in the
1452                  * allocation descriptor field of the file entry.
1453                  */
1454                 *max_size = 0;
1455                 *sector = node->hash_id + udfmp->part_start;
1456
1457                 return (UDF_INVALID_BMAP);
1458         case 2:
1459                 /* DirectCD does not use extended_ad's */
1460         default:
1461                 printf("Unsupported allocation descriptor %d\n",
1462                        tag->flags & 0x7);
1463                 return (ENODEV);
1464         }
1465
1466         *sector = lsector + udfmp->part_start;
1467
1468         /*
1469          * Check the sparing table.  Each entry represents the beginning of
1470          * a packet.
1471          */
1472         if (udfmp->s_table != NULL) {
1473                 for (i = 0; i< udfmp->s_table_entries; i++) {
1474                         p_offset =
1475                             lsector - le32toh(udfmp->s_table->entries[i].org);
1476                         if ((p_offset < udfmp->p_sectors) && (p_offset >= 0)) {
1477                                 *sector =
1478                                    le32toh(udfmp->s_table->entries[i].map) +
1479                                     p_offset;
1480                                 break;
1481                         }
1482                 }
1483         }
1484
1485         return (0);
1486 }