Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/rkuo/linux...
[linux-2.6-block.git] / fs / udf / super.c
1 /*
2  * super.c
3  *
4  * PURPOSE
5  *  Super block routines for the OSTA-UDF(tm) filesystem.
6  *
7  * DESCRIPTION
8  *  OSTA-UDF(tm) = Optical Storage Technology Association
9  *  Universal Disk Format.
10  *
11  *  This code is based on version 2.00 of the UDF specification,
12  *  and revision 3 of the ECMA 167 standard [equivalent to ISO 13346].
13  *    http://www.osta.org/
14  *    http://www.ecma.ch/
15  *    http://www.iso.org/
16  *
17  * COPYRIGHT
18  *  This file is distributed under the terms of the GNU General Public
19  *  License (GPL). Copies of the GPL can be obtained from:
20  *    ftp://prep.ai.mit.edu/pub/gnu/GPL
21  *  Each contributing author retains all rights to their own work.
22  *
23  *  (C) 1998 Dave Boynton
24  *  (C) 1998-2004 Ben Fennema
25  *  (C) 2000 Stelias Computing Inc
26  *
27  * HISTORY
28  *
29  *  09/24/98 dgb  changed to allow compiling outside of kernel, and
30  *                added some debugging.
31  *  10/01/98 dgb  updated to allow (some) possibility of compiling w/2.0.34
32  *  10/16/98      attempting some multi-session support
33  *  10/17/98      added freespace count for "df"
34  *  11/11/98 gr   added novrs option
35  *  11/26/98 dgb  added fileset,anchor mount options
36  *  12/06/98 blf  really hosed things royally. vat/sparing support. sequenced
37  *                vol descs. rewrote option handling based on isofs
38  *  12/20/98      find the free space bitmap (if it exists)
39  */
40
41 #include "udfdecl.h"
42
43 #include <linux/blkdev.h>
44 #include <linux/slab.h>
45 #include <linux/kernel.h>
46 #include <linux/module.h>
47 #include <linux/parser.h>
48 #include <linux/stat.h>
49 #include <linux/cdrom.h>
50 #include <linux/nls.h>
51 #include <linux/buffer_head.h>
52 #include <linux/vfs.h>
53 #include <linux/vmalloc.h>
54 #include <linux/errno.h>
55 #include <linux/mount.h>
56 #include <linux/seq_file.h>
57 #include <linux/bitmap.h>
58 #include <linux/crc-itu-t.h>
59 #include <linux/log2.h>
60 #include <asm/byteorder.h>
61
62 #include "udf_sb.h"
63 #include "udf_i.h"
64
65 #include <linux/init.h>
66 #include <asm/uaccess.h>
67
68 #define VDS_POS_PRIMARY_VOL_DESC        0
69 #define VDS_POS_UNALLOC_SPACE_DESC      1
70 #define VDS_POS_LOGICAL_VOL_DESC        2
71 #define VDS_POS_PARTITION_DESC          3
72 #define VDS_POS_IMP_USE_VOL_DESC        4
73 #define VDS_POS_VOL_DESC_PTR            5
74 #define VDS_POS_TERMINATING_DESC        6
75 #define VDS_POS_LENGTH                  7
76
77 #define UDF_DEFAULT_BLOCKSIZE 2048
78
79 #define VSD_FIRST_SECTOR_OFFSET         32768
80 #define VSD_MAX_SECTOR_OFFSET           0x800000
81
82 enum { UDF_MAX_LINKS = 0xffff };
83
84 /* These are the "meat" - everything else is stuffing */
85 static int udf_fill_super(struct super_block *, void *, int);
86 static void udf_put_super(struct super_block *);
87 static int udf_sync_fs(struct super_block *, int);
88 static int udf_remount_fs(struct super_block *, int *, char *);
89 static void udf_load_logicalvolint(struct super_block *, struct kernel_extent_ad);
90 static int udf_find_fileset(struct super_block *, struct kernel_lb_addr *,
91                             struct kernel_lb_addr *);
92 static void udf_load_fileset(struct super_block *, struct buffer_head *,
93                              struct kernel_lb_addr *);
94 static void udf_open_lvid(struct super_block *);
95 static void udf_close_lvid(struct super_block *);
96 static unsigned int udf_count_free(struct super_block *);
97 static int udf_statfs(struct dentry *, struct kstatfs *);
98 static int udf_show_options(struct seq_file *, struct dentry *);
99
100 struct logicalVolIntegrityDescImpUse *udf_sb_lvidiu(struct super_block *sb)
101 {
102         struct logicalVolIntegrityDesc *lvid;
103         unsigned int partnum;
104         unsigned int offset;
105
106         if (!UDF_SB(sb)->s_lvid_bh)
107                 return NULL;
108         lvid = (struct logicalVolIntegrityDesc *)UDF_SB(sb)->s_lvid_bh->b_data;
109         partnum = le32_to_cpu(lvid->numOfPartitions);
110         if ((sb->s_blocksize - sizeof(struct logicalVolIntegrityDescImpUse) -
111              offsetof(struct logicalVolIntegrityDesc, impUse)) /
112              (2 * sizeof(uint32_t)) < partnum) {
113                 udf_err(sb, "Logical volume integrity descriptor corrupted "
114                         "(numOfPartitions = %u)!\n", partnum);
115                 return NULL;
116         }
117         /* The offset is to skip freeSpaceTable and sizeTable arrays */
118         offset = partnum * 2 * sizeof(uint32_t);
119         return (struct logicalVolIntegrityDescImpUse *)&(lvid->impUse[offset]);
120 }
121
122 /* UDF filesystem type */
123 static struct dentry *udf_mount(struct file_system_type *fs_type,
124                       int flags, const char *dev_name, void *data)
125 {
126         return mount_bdev(fs_type, flags, dev_name, data, udf_fill_super);
127 }
128
129 static struct file_system_type udf_fstype = {
130         .owner          = THIS_MODULE,
131         .name           = "udf",
132         .mount          = udf_mount,
133         .kill_sb        = kill_block_super,
134         .fs_flags       = FS_REQUIRES_DEV,
135 };
136 MODULE_ALIAS_FS("udf");
137
138 static struct kmem_cache *udf_inode_cachep;
139
140 static struct inode *udf_alloc_inode(struct super_block *sb)
141 {
142         struct udf_inode_info *ei;
143         ei = kmem_cache_alloc(udf_inode_cachep, GFP_KERNEL);
144         if (!ei)
145                 return NULL;
146
147         ei->i_unique = 0;
148         ei->i_lenExtents = 0;
149         ei->i_next_alloc_block = 0;
150         ei->i_next_alloc_goal = 0;
151         ei->i_strat4096 = 0;
152         init_rwsem(&ei->i_data_sem);
153         ei->cached_extent.lstart = -1;
154         spin_lock_init(&ei->i_extent_cache_lock);
155
156         return &ei->vfs_inode;
157 }
158
159 static void udf_i_callback(struct rcu_head *head)
160 {
161         struct inode *inode = container_of(head, struct inode, i_rcu);
162         kmem_cache_free(udf_inode_cachep, UDF_I(inode));
163 }
164
165 static void udf_destroy_inode(struct inode *inode)
166 {
167         call_rcu(&inode->i_rcu, udf_i_callback);
168 }
169
170 static void init_once(void *foo)
171 {
172         struct udf_inode_info *ei = (struct udf_inode_info *)foo;
173
174         ei->i_ext.i_data = NULL;
175         inode_init_once(&ei->vfs_inode);
176 }
177
178 static int init_inodecache(void)
179 {
180         udf_inode_cachep = kmem_cache_create("udf_inode_cache",
181                                              sizeof(struct udf_inode_info),
182                                              0, (SLAB_RECLAIM_ACCOUNT |
183                                                  SLAB_MEM_SPREAD),
184                                              init_once);
185         if (!udf_inode_cachep)
186                 return -ENOMEM;
187         return 0;
188 }
189
190 static void destroy_inodecache(void)
191 {
192         /*
193          * Make sure all delayed rcu free inodes are flushed before we
194          * destroy cache.
195          */
196         rcu_barrier();
197         kmem_cache_destroy(udf_inode_cachep);
198 }
199
200 /* Superblock operations */
201 static const struct super_operations udf_sb_ops = {
202         .alloc_inode    = udf_alloc_inode,
203         .destroy_inode  = udf_destroy_inode,
204         .write_inode    = udf_write_inode,
205         .evict_inode    = udf_evict_inode,
206         .put_super      = udf_put_super,
207         .sync_fs        = udf_sync_fs,
208         .statfs         = udf_statfs,
209         .remount_fs     = udf_remount_fs,
210         .show_options   = udf_show_options,
211 };
212
213 struct udf_options {
214         unsigned char novrs;
215         unsigned int blocksize;
216         unsigned int session;
217         unsigned int lastblock;
218         unsigned int anchor;
219         unsigned int volume;
220         unsigned short partition;
221         unsigned int fileset;
222         unsigned int rootdir;
223         unsigned int flags;
224         umode_t umask;
225         kgid_t gid;
226         kuid_t uid;
227         umode_t fmode;
228         umode_t dmode;
229         struct nls_table *nls_map;
230 };
231
232 static int __init init_udf_fs(void)
233 {
234         int err;
235
236         err = init_inodecache();
237         if (err)
238                 goto out1;
239         err = register_filesystem(&udf_fstype);
240         if (err)
241                 goto out;
242
243         return 0;
244
245 out:
246         destroy_inodecache();
247
248 out1:
249         return err;
250 }
251
252 static void __exit exit_udf_fs(void)
253 {
254         unregister_filesystem(&udf_fstype);
255         destroy_inodecache();
256 }
257
258 module_init(init_udf_fs)
259 module_exit(exit_udf_fs)
260
261 static int udf_sb_alloc_partition_maps(struct super_block *sb, u32 count)
262 {
263         struct udf_sb_info *sbi = UDF_SB(sb);
264
265         sbi->s_partmaps = kcalloc(count, sizeof(struct udf_part_map),
266                                   GFP_KERNEL);
267         if (!sbi->s_partmaps) {
268                 udf_err(sb, "Unable to allocate space for %d partition maps\n",
269                         count);
270                 sbi->s_partitions = 0;
271                 return -ENOMEM;
272         }
273
274         sbi->s_partitions = count;
275         return 0;
276 }
277
278 static void udf_sb_free_bitmap(struct udf_bitmap *bitmap)
279 {
280         int i;
281         int nr_groups = bitmap->s_nr_groups;
282         int size = sizeof(struct udf_bitmap) + (sizeof(struct buffer_head *) *
283                                                 nr_groups);
284
285         for (i = 0; i < nr_groups; i++)
286                 if (bitmap->s_block_bitmap[i])
287                         brelse(bitmap->s_block_bitmap[i]);
288
289         if (size <= PAGE_SIZE)
290                 kfree(bitmap);
291         else
292                 vfree(bitmap);
293 }
294
295 static void udf_free_partition(struct udf_part_map *map)
296 {
297         int i;
298         struct udf_meta_data *mdata;
299
300         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE)
301                 iput(map->s_uspace.s_table);
302         if (map->s_partition_flags & UDF_PART_FLAG_FREED_TABLE)
303                 iput(map->s_fspace.s_table);
304         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP)
305                 udf_sb_free_bitmap(map->s_uspace.s_bitmap);
306         if (map->s_partition_flags & UDF_PART_FLAG_FREED_BITMAP)
307                 udf_sb_free_bitmap(map->s_fspace.s_bitmap);
308         if (map->s_partition_type == UDF_SPARABLE_MAP15)
309                 for (i = 0; i < 4; i++)
310                         brelse(map->s_type_specific.s_sparing.s_spar_map[i]);
311         else if (map->s_partition_type == UDF_METADATA_MAP25) {
312                 mdata = &map->s_type_specific.s_metadata;
313                 iput(mdata->s_metadata_fe);
314                 mdata->s_metadata_fe = NULL;
315
316                 iput(mdata->s_mirror_fe);
317                 mdata->s_mirror_fe = NULL;
318
319                 iput(mdata->s_bitmap_fe);
320                 mdata->s_bitmap_fe = NULL;
321         }
322 }
323
324 static void udf_sb_free_partitions(struct super_block *sb)
325 {
326         struct udf_sb_info *sbi = UDF_SB(sb);
327         int i;
328         if (sbi->s_partmaps == NULL)
329                 return;
330         for (i = 0; i < sbi->s_partitions; i++)
331                 udf_free_partition(&sbi->s_partmaps[i]);
332         kfree(sbi->s_partmaps);
333         sbi->s_partmaps = NULL;
334 }
335
336 static int udf_show_options(struct seq_file *seq, struct dentry *root)
337 {
338         struct super_block *sb = root->d_sb;
339         struct udf_sb_info *sbi = UDF_SB(sb);
340
341         if (!UDF_QUERY_FLAG(sb, UDF_FLAG_STRICT))
342                 seq_puts(seq, ",nostrict");
343         if (UDF_QUERY_FLAG(sb, UDF_FLAG_BLOCKSIZE_SET))
344                 seq_printf(seq, ",bs=%lu", sb->s_blocksize);
345         if (UDF_QUERY_FLAG(sb, UDF_FLAG_UNHIDE))
346                 seq_puts(seq, ",unhide");
347         if (UDF_QUERY_FLAG(sb, UDF_FLAG_UNDELETE))
348                 seq_puts(seq, ",undelete");
349         if (!UDF_QUERY_FLAG(sb, UDF_FLAG_USE_AD_IN_ICB))
350                 seq_puts(seq, ",noadinicb");
351         if (UDF_QUERY_FLAG(sb, UDF_FLAG_USE_SHORT_AD))
352                 seq_puts(seq, ",shortad");
353         if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_FORGET))
354                 seq_puts(seq, ",uid=forget");
355         if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_IGNORE))
356                 seq_puts(seq, ",uid=ignore");
357         if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_FORGET))
358                 seq_puts(seq, ",gid=forget");
359         if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_IGNORE))
360                 seq_puts(seq, ",gid=ignore");
361         if (UDF_QUERY_FLAG(sb, UDF_FLAG_UID_SET))
362                 seq_printf(seq, ",uid=%u", from_kuid(&init_user_ns, sbi->s_uid));
363         if (UDF_QUERY_FLAG(sb, UDF_FLAG_GID_SET))
364                 seq_printf(seq, ",gid=%u", from_kgid(&init_user_ns, sbi->s_gid));
365         if (sbi->s_umask != 0)
366                 seq_printf(seq, ",umask=%ho", sbi->s_umask);
367         if (sbi->s_fmode != UDF_INVALID_MODE)
368                 seq_printf(seq, ",mode=%ho", sbi->s_fmode);
369         if (sbi->s_dmode != UDF_INVALID_MODE)
370                 seq_printf(seq, ",dmode=%ho", sbi->s_dmode);
371         if (UDF_QUERY_FLAG(sb, UDF_FLAG_SESSION_SET))
372                 seq_printf(seq, ",session=%u", sbi->s_session);
373         if (UDF_QUERY_FLAG(sb, UDF_FLAG_LASTBLOCK_SET))
374                 seq_printf(seq, ",lastblock=%u", sbi->s_last_block);
375         if (sbi->s_anchor != 0)
376                 seq_printf(seq, ",anchor=%u", sbi->s_anchor);
377         /*
378          * volume, partition, fileset and rootdir seem to be ignored
379          * currently
380          */
381         if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8))
382                 seq_puts(seq, ",utf8");
383         if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP) && sbi->s_nls_map)
384                 seq_printf(seq, ",iocharset=%s", sbi->s_nls_map->charset);
385
386         return 0;
387 }
388
389 /*
390  * udf_parse_options
391  *
392  * PURPOSE
393  *      Parse mount options.
394  *
395  * DESCRIPTION
396  *      The following mount options are supported:
397  *
398  *      gid=            Set the default group.
399  *      umask=          Set the default umask.
400  *      mode=           Set the default file permissions.
401  *      dmode=          Set the default directory permissions.
402  *      uid=            Set the default user.
403  *      bs=             Set the block size.
404  *      unhide          Show otherwise hidden files.
405  *      undelete        Show deleted files in lists.
406  *      adinicb         Embed data in the inode (default)
407  *      noadinicb       Don't embed data in the inode
408  *      shortad         Use short ad's
409  *      longad          Use long ad's (default)
410  *      nostrict        Unset strict conformance
411  *      iocharset=      Set the NLS character set
412  *
413  *      The remaining are for debugging and disaster recovery:
414  *
415  *      novrs           Skip volume sequence recognition
416  *
417  *      The following expect a offset from 0.
418  *
419  *      session=        Set the CDROM session (default= last session)
420  *      anchor=         Override standard anchor location. (default= 256)
421  *      volume=         Override the VolumeDesc location. (unused)
422  *      partition=      Override the PartitionDesc location. (unused)
423  *      lastblock=      Set the last block of the filesystem/
424  *
425  *      The following expect a offset from the partition root.
426  *
427  *      fileset=        Override the fileset block location. (unused)
428  *      rootdir=        Override the root directory location. (unused)
429  *              WARNING: overriding the rootdir to a non-directory may
430  *              yield highly unpredictable results.
431  *
432  * PRE-CONDITIONS
433  *      options         Pointer to mount options string.
434  *      uopts           Pointer to mount options variable.
435  *
436  * POST-CONDITIONS
437  *      <return>        1       Mount options parsed okay.
438  *      <return>        0       Error parsing mount options.
439  *
440  * HISTORY
441  *      July 1, 1997 - Andrew E. Mileski
442  *      Written, tested, and released.
443  */
444
445 enum {
446         Opt_novrs, Opt_nostrict, Opt_bs, Opt_unhide, Opt_undelete,
447         Opt_noadinicb, Opt_adinicb, Opt_shortad, Opt_longad,
448         Opt_gid, Opt_uid, Opt_umask, Opt_session, Opt_lastblock,
449         Opt_anchor, Opt_volume, Opt_partition, Opt_fileset,
450         Opt_rootdir, Opt_utf8, Opt_iocharset,
451         Opt_err, Opt_uforget, Opt_uignore, Opt_gforget, Opt_gignore,
452         Opt_fmode, Opt_dmode
453 };
454
455 static const match_table_t tokens = {
456         {Opt_novrs,     "novrs"},
457         {Opt_nostrict,  "nostrict"},
458         {Opt_bs,        "bs=%u"},
459         {Opt_unhide,    "unhide"},
460         {Opt_undelete,  "undelete"},
461         {Opt_noadinicb, "noadinicb"},
462         {Opt_adinicb,   "adinicb"},
463         {Opt_shortad,   "shortad"},
464         {Opt_longad,    "longad"},
465         {Opt_uforget,   "uid=forget"},
466         {Opt_uignore,   "uid=ignore"},
467         {Opt_gforget,   "gid=forget"},
468         {Opt_gignore,   "gid=ignore"},
469         {Opt_gid,       "gid=%u"},
470         {Opt_uid,       "uid=%u"},
471         {Opt_umask,     "umask=%o"},
472         {Opt_session,   "session=%u"},
473         {Opt_lastblock, "lastblock=%u"},
474         {Opt_anchor,    "anchor=%u"},
475         {Opt_volume,    "volume=%u"},
476         {Opt_partition, "partition=%u"},
477         {Opt_fileset,   "fileset=%u"},
478         {Opt_rootdir,   "rootdir=%u"},
479         {Opt_utf8,      "utf8"},
480         {Opt_iocharset, "iocharset=%s"},
481         {Opt_fmode,     "mode=%o"},
482         {Opt_dmode,     "dmode=%o"},
483         {Opt_err,       NULL}
484 };
485
486 static int udf_parse_options(char *options, struct udf_options *uopt,
487                              bool remount)
488 {
489         char *p;
490         int option;
491
492         uopt->novrs = 0;
493         uopt->partition = 0xFFFF;
494         uopt->session = 0xFFFFFFFF;
495         uopt->lastblock = 0;
496         uopt->anchor = 0;
497         uopt->volume = 0xFFFFFFFF;
498         uopt->rootdir = 0xFFFFFFFF;
499         uopt->fileset = 0xFFFFFFFF;
500         uopt->nls_map = NULL;
501
502         if (!options)
503                 return 1;
504
505         while ((p = strsep(&options, ",")) != NULL) {
506                 substring_t args[MAX_OPT_ARGS];
507                 int token;
508                 if (!*p)
509                         continue;
510
511                 token = match_token(p, tokens, args);
512                 switch (token) {
513                 case Opt_novrs:
514                         uopt->novrs = 1;
515                         break;
516                 case Opt_bs:
517                         if (match_int(&args[0], &option))
518                                 return 0;
519                         uopt->blocksize = option;
520                         uopt->flags |= (1 << UDF_FLAG_BLOCKSIZE_SET);
521                         break;
522                 case Opt_unhide:
523                         uopt->flags |= (1 << UDF_FLAG_UNHIDE);
524                         break;
525                 case Opt_undelete:
526                         uopt->flags |= (1 << UDF_FLAG_UNDELETE);
527                         break;
528                 case Opt_noadinicb:
529                         uopt->flags &= ~(1 << UDF_FLAG_USE_AD_IN_ICB);
530                         break;
531                 case Opt_adinicb:
532                         uopt->flags |= (1 << UDF_FLAG_USE_AD_IN_ICB);
533                         break;
534                 case Opt_shortad:
535                         uopt->flags |= (1 << UDF_FLAG_USE_SHORT_AD);
536                         break;
537                 case Opt_longad:
538                         uopt->flags &= ~(1 << UDF_FLAG_USE_SHORT_AD);
539                         break;
540                 case Opt_gid:
541                         if (match_int(args, &option))
542                                 return 0;
543                         uopt->gid = make_kgid(current_user_ns(), option);
544                         if (!gid_valid(uopt->gid))
545                                 return 0;
546                         uopt->flags |= (1 << UDF_FLAG_GID_SET);
547                         break;
548                 case Opt_uid:
549                         if (match_int(args, &option))
550                                 return 0;
551                         uopt->uid = make_kuid(current_user_ns(), option);
552                         if (!uid_valid(uopt->uid))
553                                 return 0;
554                         uopt->flags |= (1 << UDF_FLAG_UID_SET);
555                         break;
556                 case Opt_umask:
557                         if (match_octal(args, &option))
558                                 return 0;
559                         uopt->umask = option;
560                         break;
561                 case Opt_nostrict:
562                         uopt->flags &= ~(1 << UDF_FLAG_STRICT);
563                         break;
564                 case Opt_session:
565                         if (match_int(args, &option))
566                                 return 0;
567                         uopt->session = option;
568                         if (!remount)
569                                 uopt->flags |= (1 << UDF_FLAG_SESSION_SET);
570                         break;
571                 case Opt_lastblock:
572                         if (match_int(args, &option))
573                                 return 0;
574                         uopt->lastblock = option;
575                         if (!remount)
576                                 uopt->flags |= (1 << UDF_FLAG_LASTBLOCK_SET);
577                         break;
578                 case Opt_anchor:
579                         if (match_int(args, &option))
580                                 return 0;
581                         uopt->anchor = option;
582                         break;
583                 case Opt_volume:
584                         if (match_int(args, &option))
585                                 return 0;
586                         uopt->volume = option;
587                         break;
588                 case Opt_partition:
589                         if (match_int(args, &option))
590                                 return 0;
591                         uopt->partition = option;
592                         break;
593                 case Opt_fileset:
594                         if (match_int(args, &option))
595                                 return 0;
596                         uopt->fileset = option;
597                         break;
598                 case Opt_rootdir:
599                         if (match_int(args, &option))
600                                 return 0;
601                         uopt->rootdir = option;
602                         break;
603                 case Opt_utf8:
604                         uopt->flags |= (1 << UDF_FLAG_UTF8);
605                         break;
606 #ifdef CONFIG_UDF_NLS
607                 case Opt_iocharset:
608                         uopt->nls_map = load_nls(args[0].from);
609                         uopt->flags |= (1 << UDF_FLAG_NLS_MAP);
610                         break;
611 #endif
612                 case Opt_uignore:
613                         uopt->flags |= (1 << UDF_FLAG_UID_IGNORE);
614                         break;
615                 case Opt_uforget:
616                         uopt->flags |= (1 << UDF_FLAG_UID_FORGET);
617                         break;
618                 case Opt_gignore:
619                         uopt->flags |= (1 << UDF_FLAG_GID_IGNORE);
620                         break;
621                 case Opt_gforget:
622                         uopt->flags |= (1 << UDF_FLAG_GID_FORGET);
623                         break;
624                 case Opt_fmode:
625                         if (match_octal(args, &option))
626                                 return 0;
627                         uopt->fmode = option & 0777;
628                         break;
629                 case Opt_dmode:
630                         if (match_octal(args, &option))
631                                 return 0;
632                         uopt->dmode = option & 0777;
633                         break;
634                 default:
635                         pr_err("bad mount option \"%s\" or missing value\n", p);
636                         return 0;
637                 }
638         }
639         return 1;
640 }
641
642 static int udf_remount_fs(struct super_block *sb, int *flags, char *options)
643 {
644         struct udf_options uopt;
645         struct udf_sb_info *sbi = UDF_SB(sb);
646         int error = 0;
647         struct logicalVolIntegrityDescImpUse *lvidiu = udf_sb_lvidiu(sb);
648
649         sync_filesystem(sb);
650         if (lvidiu) {
651                 int write_rev = le16_to_cpu(lvidiu->minUDFWriteRev);
652                 if (write_rev > UDF_MAX_WRITE_VERSION && !(*flags & MS_RDONLY))
653                         return -EACCES;
654         }
655
656         uopt.flags = sbi->s_flags;
657         uopt.uid   = sbi->s_uid;
658         uopt.gid   = sbi->s_gid;
659         uopt.umask = sbi->s_umask;
660         uopt.fmode = sbi->s_fmode;
661         uopt.dmode = sbi->s_dmode;
662
663         if (!udf_parse_options(options, &uopt, true))
664                 return -EINVAL;
665
666         write_lock(&sbi->s_cred_lock);
667         sbi->s_flags = uopt.flags;
668         sbi->s_uid   = uopt.uid;
669         sbi->s_gid   = uopt.gid;
670         sbi->s_umask = uopt.umask;
671         sbi->s_fmode = uopt.fmode;
672         sbi->s_dmode = uopt.dmode;
673         write_unlock(&sbi->s_cred_lock);
674
675         if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY))
676                 goto out_unlock;
677
678         if (*flags & MS_RDONLY)
679                 udf_close_lvid(sb);
680         else
681                 udf_open_lvid(sb);
682
683 out_unlock:
684         return error;
685 }
686
687 /* Check Volume Structure Descriptors (ECMA 167 2/9.1) */
688 /* We also check any "CD-ROM Volume Descriptor Set" (ECMA 167 2/8.3.1) */
689 static loff_t udf_check_vsd(struct super_block *sb)
690 {
691         struct volStructDesc *vsd = NULL;
692         loff_t sector = VSD_FIRST_SECTOR_OFFSET;
693         int sectorsize;
694         struct buffer_head *bh = NULL;
695         int nsr02 = 0;
696         int nsr03 = 0;
697         struct udf_sb_info *sbi;
698
699         sbi = UDF_SB(sb);
700         if (sb->s_blocksize < sizeof(struct volStructDesc))
701                 sectorsize = sizeof(struct volStructDesc);
702         else
703                 sectorsize = sb->s_blocksize;
704
705         sector += (sbi->s_session << sb->s_blocksize_bits);
706
707         udf_debug("Starting at sector %u (%ld byte sectors)\n",
708                   (unsigned int)(sector >> sb->s_blocksize_bits),
709                   sb->s_blocksize);
710         /* Process the sequence (if applicable). The hard limit on the sector
711          * offset is arbitrary, hopefully large enough so that all valid UDF
712          * filesystems will be recognised. There is no mention of an upper
713          * bound to the size of the volume recognition area in the standard.
714          *  The limit will prevent the code to read all the sectors of a
715          * specially crafted image (like a bluray disc full of CD001 sectors),
716          * potentially causing minutes or even hours of uninterruptible I/O
717          * activity. This actually happened with uninitialised SSD partitions
718          * (all 0xFF) before the check for the limit and all valid IDs were
719          * added */
720         for (; !nsr02 && !nsr03 && sector < VSD_MAX_SECTOR_OFFSET;
721              sector += sectorsize) {
722                 /* Read a block */
723                 bh = udf_tread(sb, sector >> sb->s_blocksize_bits);
724                 if (!bh)
725                         break;
726
727                 /* Look for ISO  descriptors */
728                 vsd = (struct volStructDesc *)(bh->b_data +
729                                               (sector & (sb->s_blocksize - 1)));
730
731                 if (!strncmp(vsd->stdIdent, VSD_STD_ID_CD001,
732                                     VSD_STD_ID_LEN)) {
733                         switch (vsd->structType) {
734                         case 0:
735                                 udf_debug("ISO9660 Boot Record found\n");
736                                 break;
737                         case 1:
738                                 udf_debug("ISO9660 Primary Volume Descriptor found\n");
739                                 break;
740                         case 2:
741                                 udf_debug("ISO9660 Supplementary Volume Descriptor found\n");
742                                 break;
743                         case 3:
744                                 udf_debug("ISO9660 Volume Partition Descriptor found\n");
745                                 break;
746                         case 255:
747                                 udf_debug("ISO9660 Volume Descriptor Set Terminator found\n");
748                                 break;
749                         default:
750                                 udf_debug("ISO9660 VRS (%u) found\n",
751                                           vsd->structType);
752                                 break;
753                         }
754                 } else if (!strncmp(vsd->stdIdent, VSD_STD_ID_BEA01,
755                                     VSD_STD_ID_LEN))
756                         ; /* nothing */
757                 else if (!strncmp(vsd->stdIdent, VSD_STD_ID_TEA01,
758                                     VSD_STD_ID_LEN)) {
759                         brelse(bh);
760                         break;
761                 } else if (!strncmp(vsd->stdIdent, VSD_STD_ID_NSR02,
762                                     VSD_STD_ID_LEN))
763                         nsr02 = sector;
764                 else if (!strncmp(vsd->stdIdent, VSD_STD_ID_NSR03,
765                                     VSD_STD_ID_LEN))
766                         nsr03 = sector;
767                 else if (!strncmp(vsd->stdIdent, VSD_STD_ID_BOOT2,
768                                     VSD_STD_ID_LEN))
769                         ; /* nothing */
770                 else if (!strncmp(vsd->stdIdent, VSD_STD_ID_CDW02,
771                                     VSD_STD_ID_LEN))
772                         ; /* nothing */
773                 else {
774                         /* invalid id : end of volume recognition area */
775                         brelse(bh);
776                         break;
777                 }
778                 brelse(bh);
779         }
780
781         if (nsr03)
782                 return nsr03;
783         else if (nsr02)
784                 return nsr02;
785         else if (!bh && sector - (sbi->s_session << sb->s_blocksize_bits) ==
786                         VSD_FIRST_SECTOR_OFFSET)
787                 return -1;
788         else
789                 return 0;
790 }
791
792 static int udf_find_fileset(struct super_block *sb,
793                             struct kernel_lb_addr *fileset,
794                             struct kernel_lb_addr *root)
795 {
796         struct buffer_head *bh = NULL;
797         long lastblock;
798         uint16_t ident;
799         struct udf_sb_info *sbi;
800
801         if (fileset->logicalBlockNum != 0xFFFFFFFF ||
802             fileset->partitionReferenceNum != 0xFFFF) {
803                 bh = udf_read_ptagged(sb, fileset, 0, &ident);
804
805                 if (!bh) {
806                         return 1;
807                 } else if (ident != TAG_IDENT_FSD) {
808                         brelse(bh);
809                         return 1;
810                 }
811
812         }
813
814         sbi = UDF_SB(sb);
815         if (!bh) {
816                 /* Search backwards through the partitions */
817                 struct kernel_lb_addr newfileset;
818
819 /* --> cvg: FIXME - is it reasonable? */
820                 return 1;
821
822                 for (newfileset.partitionReferenceNum = sbi->s_partitions - 1;
823                      (newfileset.partitionReferenceNum != 0xFFFF &&
824                       fileset->logicalBlockNum == 0xFFFFFFFF &&
825                       fileset->partitionReferenceNum == 0xFFFF);
826                      newfileset.partitionReferenceNum--) {
827                         lastblock = sbi->s_partmaps
828                                         [newfileset.partitionReferenceNum]
829                                                 .s_partition_len;
830                         newfileset.logicalBlockNum = 0;
831
832                         do {
833                                 bh = udf_read_ptagged(sb, &newfileset, 0,
834                                                       &ident);
835                                 if (!bh) {
836                                         newfileset.logicalBlockNum++;
837                                         continue;
838                                 }
839
840                                 switch (ident) {
841                                 case TAG_IDENT_SBD:
842                                 {
843                                         struct spaceBitmapDesc *sp;
844                                         sp = (struct spaceBitmapDesc *)
845                                                                 bh->b_data;
846                                         newfileset.logicalBlockNum += 1 +
847                                                 ((le32_to_cpu(sp->numOfBytes) +
848                                                   sizeof(struct spaceBitmapDesc)
849                                                   - 1) >> sb->s_blocksize_bits);
850                                         brelse(bh);
851                                         break;
852                                 }
853                                 case TAG_IDENT_FSD:
854                                         *fileset = newfileset;
855                                         break;
856                                 default:
857                                         newfileset.logicalBlockNum++;
858                                         brelse(bh);
859                                         bh = NULL;
860                                         break;
861                                 }
862                         } while (newfileset.logicalBlockNum < lastblock &&
863                                  fileset->logicalBlockNum == 0xFFFFFFFF &&
864                                  fileset->partitionReferenceNum == 0xFFFF);
865                 }
866         }
867
868         if ((fileset->logicalBlockNum != 0xFFFFFFFF ||
869              fileset->partitionReferenceNum != 0xFFFF) && bh) {
870                 udf_debug("Fileset at block=%d, partition=%d\n",
871                           fileset->logicalBlockNum,
872                           fileset->partitionReferenceNum);
873
874                 sbi->s_partition = fileset->partitionReferenceNum;
875                 udf_load_fileset(sb, bh, root);
876                 brelse(bh);
877                 return 0;
878         }
879         return 1;
880 }
881
882 /*
883  * Load primary Volume Descriptor Sequence
884  *
885  * Return <0 on error, 0 on success. -EAGAIN is special meaning next sequence
886  * should be tried.
887  */
888 static int udf_load_pvoldesc(struct super_block *sb, sector_t block)
889 {
890         struct primaryVolDesc *pvoldesc;
891         struct ustr *instr, *outstr;
892         struct buffer_head *bh;
893         uint16_t ident;
894         int ret = -ENOMEM;
895
896         instr = kmalloc(sizeof(struct ustr), GFP_NOFS);
897         if (!instr)
898                 return -ENOMEM;
899
900         outstr = kmalloc(sizeof(struct ustr), GFP_NOFS);
901         if (!outstr)
902                 goto out1;
903
904         bh = udf_read_tagged(sb, block, block, &ident);
905         if (!bh) {
906                 ret = -EAGAIN;
907                 goto out2;
908         }
909
910         if (ident != TAG_IDENT_PVD) {
911                 ret = -EIO;
912                 goto out_bh;
913         }
914
915         pvoldesc = (struct primaryVolDesc *)bh->b_data;
916
917         if (udf_disk_stamp_to_time(&UDF_SB(sb)->s_record_time,
918                               pvoldesc->recordingDateAndTime)) {
919 #ifdef UDFFS_DEBUG
920                 struct timestamp *ts = &pvoldesc->recordingDateAndTime;
921                 udf_debug("recording time %04u/%02u/%02u %02u:%02u (%x)\n",
922                           le16_to_cpu(ts->year), ts->month, ts->day, ts->hour,
923                           ts->minute, le16_to_cpu(ts->typeAndTimezone));
924 #endif
925         }
926
927         if (!udf_build_ustr(instr, pvoldesc->volIdent, 32))
928                 if (udf_CS0toUTF8(outstr, instr)) {
929                         strncpy(UDF_SB(sb)->s_volume_ident, outstr->u_name,
930                                 outstr->u_len > 31 ? 31 : outstr->u_len);
931                         udf_debug("volIdent[] = '%s'\n",
932                                   UDF_SB(sb)->s_volume_ident);
933                 }
934
935         if (!udf_build_ustr(instr, pvoldesc->volSetIdent, 128))
936                 if (udf_CS0toUTF8(outstr, instr))
937                         udf_debug("volSetIdent[] = '%s'\n", outstr->u_name);
938
939         ret = 0;
940 out_bh:
941         brelse(bh);
942 out2:
943         kfree(outstr);
944 out1:
945         kfree(instr);
946         return ret;
947 }
948
949 struct inode *udf_find_metadata_inode_efe(struct super_block *sb,
950                                         u32 meta_file_loc, u32 partition_num)
951 {
952         struct kernel_lb_addr addr;
953         struct inode *metadata_fe;
954
955         addr.logicalBlockNum = meta_file_loc;
956         addr.partitionReferenceNum = partition_num;
957
958         metadata_fe = udf_iget(sb, &addr);
959
960         if (metadata_fe == NULL)
961                 udf_warn(sb, "metadata inode efe not found\n");
962         else if (UDF_I(metadata_fe)->i_alloc_type != ICBTAG_FLAG_AD_SHORT) {
963                 udf_warn(sb, "metadata inode efe does not have short allocation descriptors!\n");
964                 iput(metadata_fe);
965                 metadata_fe = NULL;
966         }
967
968         return metadata_fe;
969 }
970
971 static int udf_load_metadata_files(struct super_block *sb, int partition)
972 {
973         struct udf_sb_info *sbi = UDF_SB(sb);
974         struct udf_part_map *map;
975         struct udf_meta_data *mdata;
976         struct kernel_lb_addr addr;
977
978         map = &sbi->s_partmaps[partition];
979         mdata = &map->s_type_specific.s_metadata;
980
981         /* metadata address */
982         udf_debug("Metadata file location: block = %d part = %d\n",
983                   mdata->s_meta_file_loc, map->s_partition_num);
984
985         mdata->s_metadata_fe = udf_find_metadata_inode_efe(sb,
986                 mdata->s_meta_file_loc, map->s_partition_num);
987
988         if (mdata->s_metadata_fe == NULL) {
989                 /* mirror file entry */
990                 udf_debug("Mirror metadata file location: block = %d part = %d\n",
991                           mdata->s_mirror_file_loc, map->s_partition_num);
992
993                 mdata->s_mirror_fe = udf_find_metadata_inode_efe(sb,
994                         mdata->s_mirror_file_loc, map->s_partition_num);
995
996                 if (mdata->s_mirror_fe == NULL) {
997                         udf_err(sb, "Both metadata and mirror metadata inode efe can not found\n");
998                         return -EIO;
999                 }
1000         }
1001
1002         /*
1003          * bitmap file entry
1004          * Note:
1005          * Load only if bitmap file location differs from 0xFFFFFFFF (DCN-5102)
1006         */
1007         if (mdata->s_bitmap_file_loc != 0xFFFFFFFF) {
1008                 addr.logicalBlockNum = mdata->s_bitmap_file_loc;
1009                 addr.partitionReferenceNum = map->s_partition_num;
1010
1011                 udf_debug("Bitmap file location: block = %d part = %d\n",
1012                           addr.logicalBlockNum, addr.partitionReferenceNum);
1013
1014                 mdata->s_bitmap_fe = udf_iget(sb, &addr);
1015                 if (mdata->s_bitmap_fe == NULL) {
1016                         if (sb->s_flags & MS_RDONLY)
1017                                 udf_warn(sb, "bitmap inode efe not found but it's ok since the disc is mounted read-only\n");
1018                         else {
1019                                 udf_err(sb, "bitmap inode efe not found and attempted read-write mount\n");
1020                                 return -EIO;
1021                         }
1022                 }
1023         }
1024
1025         udf_debug("udf_load_metadata_files Ok\n");
1026         return 0;
1027 }
1028
1029 static void udf_load_fileset(struct super_block *sb, struct buffer_head *bh,
1030                              struct kernel_lb_addr *root)
1031 {
1032         struct fileSetDesc *fset;
1033
1034         fset = (struct fileSetDesc *)bh->b_data;
1035
1036         *root = lelb_to_cpu(fset->rootDirectoryICB.extLocation);
1037
1038         UDF_SB(sb)->s_serial_number = le16_to_cpu(fset->descTag.tagSerialNum);
1039
1040         udf_debug("Rootdir at block=%d, partition=%d\n",
1041                   root->logicalBlockNum, root->partitionReferenceNum);
1042 }
1043
1044 int udf_compute_nr_groups(struct super_block *sb, u32 partition)
1045 {
1046         struct udf_part_map *map = &UDF_SB(sb)->s_partmaps[partition];
1047         return DIV_ROUND_UP(map->s_partition_len +
1048                             (sizeof(struct spaceBitmapDesc) << 3),
1049                             sb->s_blocksize * 8);
1050 }
1051
1052 static struct udf_bitmap *udf_sb_alloc_bitmap(struct super_block *sb, u32 index)
1053 {
1054         struct udf_bitmap *bitmap;
1055         int nr_groups;
1056         int size;
1057
1058         nr_groups = udf_compute_nr_groups(sb, index);
1059         size = sizeof(struct udf_bitmap) +
1060                 (sizeof(struct buffer_head *) * nr_groups);
1061
1062         if (size <= PAGE_SIZE)
1063                 bitmap = kzalloc(size, GFP_KERNEL);
1064         else
1065                 bitmap = vzalloc(size); /* TODO: get rid of vzalloc */
1066
1067         if (bitmap == NULL)
1068                 return NULL;
1069
1070         bitmap->s_nr_groups = nr_groups;
1071         return bitmap;
1072 }
1073
1074 static int udf_fill_partdesc_info(struct super_block *sb,
1075                 struct partitionDesc *p, int p_index)
1076 {
1077         struct udf_part_map *map;
1078         struct udf_sb_info *sbi = UDF_SB(sb);
1079         struct partitionHeaderDesc *phd;
1080
1081         map = &sbi->s_partmaps[p_index];
1082
1083         map->s_partition_len = le32_to_cpu(p->partitionLength); /* blocks */
1084         map->s_partition_root = le32_to_cpu(p->partitionStartingLocation);
1085
1086         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_READ_ONLY))
1087                 map->s_partition_flags |= UDF_PART_FLAG_READ_ONLY;
1088         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_WRITE_ONCE))
1089                 map->s_partition_flags |= UDF_PART_FLAG_WRITE_ONCE;
1090         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_REWRITABLE))
1091                 map->s_partition_flags |= UDF_PART_FLAG_REWRITABLE;
1092         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_OVERWRITABLE))
1093                 map->s_partition_flags |= UDF_PART_FLAG_OVERWRITABLE;
1094
1095         udf_debug("Partition (%d type %x) starts at physical %d, block length %d\n",
1096                   p_index, map->s_partition_type,
1097                   map->s_partition_root, map->s_partition_len);
1098
1099         if (strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR02) &&
1100             strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR03))
1101                 return 0;
1102
1103         phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
1104         if (phd->unallocSpaceTable.extLength) {
1105                 struct kernel_lb_addr loc = {
1106                         .logicalBlockNum = le32_to_cpu(
1107                                 phd->unallocSpaceTable.extPosition),
1108                         .partitionReferenceNum = p_index,
1109                 };
1110
1111                 map->s_uspace.s_table = udf_iget(sb, &loc);
1112                 if (!map->s_uspace.s_table) {
1113                         udf_debug("cannot load unallocSpaceTable (part %d)\n",
1114                                   p_index);
1115                         return -EIO;
1116                 }
1117                 map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_TABLE;
1118                 udf_debug("unallocSpaceTable (part %d) @ %ld\n",
1119                           p_index, map->s_uspace.s_table->i_ino);
1120         }
1121
1122         if (phd->unallocSpaceBitmap.extLength) {
1123                 struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index);
1124                 if (!bitmap)
1125                         return -ENOMEM;
1126                 map->s_uspace.s_bitmap = bitmap;
1127                 bitmap->s_extPosition = le32_to_cpu(
1128                                 phd->unallocSpaceBitmap.extPosition);
1129                 map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_BITMAP;
1130                 udf_debug("unallocSpaceBitmap (part %d) @ %d\n",
1131                           p_index, bitmap->s_extPosition);
1132         }
1133
1134         if (phd->partitionIntegrityTable.extLength)
1135                 udf_debug("partitionIntegrityTable (part %d)\n", p_index);
1136
1137         if (phd->freedSpaceTable.extLength) {
1138                 struct kernel_lb_addr loc = {
1139                         .logicalBlockNum = le32_to_cpu(
1140                                 phd->freedSpaceTable.extPosition),
1141                         .partitionReferenceNum = p_index,
1142                 };
1143
1144                 map->s_fspace.s_table = udf_iget(sb, &loc);
1145                 if (!map->s_fspace.s_table) {
1146                         udf_debug("cannot load freedSpaceTable (part %d)\n",
1147                                   p_index);
1148                         return -EIO;
1149                 }
1150
1151                 map->s_partition_flags |= UDF_PART_FLAG_FREED_TABLE;
1152                 udf_debug("freedSpaceTable (part %d) @ %ld\n",
1153                           p_index, map->s_fspace.s_table->i_ino);
1154         }
1155
1156         if (phd->freedSpaceBitmap.extLength) {
1157                 struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index);
1158                 if (!bitmap)
1159                         return -ENOMEM;
1160                 map->s_fspace.s_bitmap = bitmap;
1161                 bitmap->s_extPosition = le32_to_cpu(
1162                                 phd->freedSpaceBitmap.extPosition);
1163                 map->s_partition_flags |= UDF_PART_FLAG_FREED_BITMAP;
1164                 udf_debug("freedSpaceBitmap (part %d) @ %d\n",
1165                           p_index, bitmap->s_extPosition);
1166         }
1167         return 0;
1168 }
1169
1170 static void udf_find_vat_block(struct super_block *sb, int p_index,
1171                                int type1_index, sector_t start_block)
1172 {
1173         struct udf_sb_info *sbi = UDF_SB(sb);
1174         struct udf_part_map *map = &sbi->s_partmaps[p_index];
1175         sector_t vat_block;
1176         struct kernel_lb_addr ino;
1177
1178         /*
1179          * VAT file entry is in the last recorded block. Some broken disks have
1180          * it a few blocks before so try a bit harder...
1181          */
1182         ino.partitionReferenceNum = type1_index;
1183         for (vat_block = start_block;
1184              vat_block >= map->s_partition_root &&
1185              vat_block >= start_block - 3 &&
1186              !sbi->s_vat_inode; vat_block--) {
1187                 ino.logicalBlockNum = vat_block - map->s_partition_root;
1188                 sbi->s_vat_inode = udf_iget(sb, &ino);
1189         }
1190 }
1191
1192 static int udf_load_vat(struct super_block *sb, int p_index, int type1_index)
1193 {
1194         struct udf_sb_info *sbi = UDF_SB(sb);
1195         struct udf_part_map *map = &sbi->s_partmaps[p_index];
1196         struct buffer_head *bh = NULL;
1197         struct udf_inode_info *vati;
1198         uint32_t pos;
1199         struct virtualAllocationTable20 *vat20;
1200         sector_t blocks = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
1201
1202         udf_find_vat_block(sb, p_index, type1_index, sbi->s_last_block);
1203         if (!sbi->s_vat_inode &&
1204             sbi->s_last_block != blocks - 1) {
1205                 pr_notice("Failed to read VAT inode from the last recorded block (%lu), retrying with the last block of the device (%lu).\n",
1206                           (unsigned long)sbi->s_last_block,
1207                           (unsigned long)blocks - 1);
1208                 udf_find_vat_block(sb, p_index, type1_index, blocks - 1);
1209         }
1210         if (!sbi->s_vat_inode)
1211                 return -EIO;
1212
1213         if (map->s_partition_type == UDF_VIRTUAL_MAP15) {
1214                 map->s_type_specific.s_virtual.s_start_offset = 0;
1215                 map->s_type_specific.s_virtual.s_num_entries =
1216                         (sbi->s_vat_inode->i_size - 36) >> 2;
1217         } else if (map->s_partition_type == UDF_VIRTUAL_MAP20) {
1218                 vati = UDF_I(sbi->s_vat_inode);
1219                 if (vati->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) {
1220                         pos = udf_block_map(sbi->s_vat_inode, 0);
1221                         bh = sb_bread(sb, pos);
1222                         if (!bh)
1223                                 return -EIO;
1224                         vat20 = (struct virtualAllocationTable20 *)bh->b_data;
1225                 } else {
1226                         vat20 = (struct virtualAllocationTable20 *)
1227                                                         vati->i_ext.i_data;
1228                 }
1229
1230                 map->s_type_specific.s_virtual.s_start_offset =
1231                         le16_to_cpu(vat20->lengthHeader);
1232                 map->s_type_specific.s_virtual.s_num_entries =
1233                         (sbi->s_vat_inode->i_size -
1234                                 map->s_type_specific.s_virtual.
1235                                         s_start_offset) >> 2;
1236                 brelse(bh);
1237         }
1238         return 0;
1239 }
1240
1241 /*
1242  * Load partition descriptor block
1243  *
1244  * Returns <0 on error, 0 on success, -EAGAIN is special - try next descriptor
1245  * sequence.
1246  */
1247 static int udf_load_partdesc(struct super_block *sb, sector_t block)
1248 {
1249         struct buffer_head *bh;
1250         struct partitionDesc *p;
1251         struct udf_part_map *map;
1252         struct udf_sb_info *sbi = UDF_SB(sb);
1253         int i, type1_idx;
1254         uint16_t partitionNumber;
1255         uint16_t ident;
1256         int ret;
1257
1258         bh = udf_read_tagged(sb, block, block, &ident);
1259         if (!bh)
1260                 return -EAGAIN;
1261         if (ident != TAG_IDENT_PD) {
1262                 ret = 0;
1263                 goto out_bh;
1264         }
1265
1266         p = (struct partitionDesc *)bh->b_data;
1267         partitionNumber = le16_to_cpu(p->partitionNumber);
1268
1269         /* First scan for TYPE1, SPARABLE and METADATA partitions */
1270         for (i = 0; i < sbi->s_partitions; i++) {
1271                 map = &sbi->s_partmaps[i];
1272                 udf_debug("Searching map: (%d == %d)\n",
1273                           map->s_partition_num, partitionNumber);
1274                 if (map->s_partition_num == partitionNumber &&
1275                     (map->s_partition_type == UDF_TYPE1_MAP15 ||
1276                      map->s_partition_type == UDF_SPARABLE_MAP15))
1277                         break;
1278         }
1279
1280         if (i >= sbi->s_partitions) {
1281                 udf_debug("Partition (%d) not found in partition map\n",
1282                           partitionNumber);
1283                 ret = 0;
1284                 goto out_bh;
1285         }
1286
1287         ret = udf_fill_partdesc_info(sb, p, i);
1288         if (ret < 0)
1289                 goto out_bh;
1290
1291         /*
1292          * Now rescan for VIRTUAL or METADATA partitions when SPARABLE and
1293          * PHYSICAL partitions are already set up
1294          */
1295         type1_idx = i;
1296 #ifdef UDFFS_DEBUG
1297         map = NULL; /* supress 'maybe used uninitialized' warning */
1298 #endif
1299         for (i = 0; i < sbi->s_partitions; i++) {
1300                 map = &sbi->s_partmaps[i];
1301
1302                 if (map->s_partition_num == partitionNumber &&
1303                     (map->s_partition_type == UDF_VIRTUAL_MAP15 ||
1304                      map->s_partition_type == UDF_VIRTUAL_MAP20 ||
1305                      map->s_partition_type == UDF_METADATA_MAP25))
1306                         break;
1307         }
1308
1309         if (i >= sbi->s_partitions) {
1310                 ret = 0;
1311                 goto out_bh;
1312         }
1313
1314         ret = udf_fill_partdesc_info(sb, p, i);
1315         if (ret < 0)
1316                 goto out_bh;
1317
1318         if (map->s_partition_type == UDF_METADATA_MAP25) {
1319                 ret = udf_load_metadata_files(sb, i);
1320                 if (ret < 0) {
1321                         udf_err(sb, "error loading MetaData partition map %d\n",
1322                                 i);
1323                         goto out_bh;
1324                 }
1325         } else {
1326                 /*
1327                  * If we have a partition with virtual map, we don't handle
1328                  * writing to it (we overwrite blocks instead of relocating
1329                  * them).
1330                  */
1331                 if (!(sb->s_flags & MS_RDONLY)) {
1332                         ret = -EACCES;
1333                         goto out_bh;
1334                 }
1335                 ret = udf_load_vat(sb, i, type1_idx);
1336                 if (ret < 0)
1337                         goto out_bh;
1338         }
1339         ret = 0;
1340 out_bh:
1341         /* In case loading failed, we handle cleanup in udf_fill_super */
1342         brelse(bh);
1343         return ret;
1344 }
1345
1346 static int udf_load_sparable_map(struct super_block *sb,
1347                                  struct udf_part_map *map,
1348                                  struct sparablePartitionMap *spm)
1349 {
1350         uint32_t loc;
1351         uint16_t ident;
1352         struct sparingTable *st;
1353         struct udf_sparing_data *sdata = &map->s_type_specific.s_sparing;
1354         int i;
1355         struct buffer_head *bh;
1356
1357         map->s_partition_type = UDF_SPARABLE_MAP15;
1358         sdata->s_packet_len = le16_to_cpu(spm->packetLength);
1359         if (!is_power_of_2(sdata->s_packet_len)) {
1360                 udf_err(sb, "error loading logical volume descriptor: "
1361                         "Invalid packet length %u\n",
1362                         (unsigned)sdata->s_packet_len);
1363                 return -EIO;
1364         }
1365         if (spm->numSparingTables > 4) {
1366                 udf_err(sb, "error loading logical volume descriptor: "
1367                         "Too many sparing tables (%d)\n",
1368                         (int)spm->numSparingTables);
1369                 return -EIO;
1370         }
1371
1372         for (i = 0; i < spm->numSparingTables; i++) {
1373                 loc = le32_to_cpu(spm->locSparingTable[i]);
1374                 bh = udf_read_tagged(sb, loc, loc, &ident);
1375                 if (!bh)
1376                         continue;
1377
1378                 st = (struct sparingTable *)bh->b_data;
1379                 if (ident != 0 ||
1380                     strncmp(st->sparingIdent.ident, UDF_ID_SPARING,
1381                             strlen(UDF_ID_SPARING)) ||
1382                     sizeof(*st) + le16_to_cpu(st->reallocationTableLen) >
1383                                                         sb->s_blocksize) {
1384                         brelse(bh);
1385                         continue;
1386                 }
1387
1388                 sdata->s_spar_map[i] = bh;
1389         }
1390         map->s_partition_func = udf_get_pblock_spar15;
1391         return 0;
1392 }
1393
1394 static int udf_load_logicalvol(struct super_block *sb, sector_t block,
1395                                struct kernel_lb_addr *fileset)
1396 {
1397         struct logicalVolDesc *lvd;
1398         int i, offset;
1399         uint8_t type;
1400         struct udf_sb_info *sbi = UDF_SB(sb);
1401         struct genericPartitionMap *gpm;
1402         uint16_t ident;
1403         struct buffer_head *bh;
1404         unsigned int table_len;
1405         int ret;
1406
1407         bh = udf_read_tagged(sb, block, block, &ident);
1408         if (!bh)
1409                 return -EAGAIN;
1410         BUG_ON(ident != TAG_IDENT_LVD);
1411         lvd = (struct logicalVolDesc *)bh->b_data;
1412         table_len = le32_to_cpu(lvd->mapTableLength);
1413         if (table_len > sb->s_blocksize - sizeof(*lvd)) {
1414                 udf_err(sb, "error loading logical volume descriptor: "
1415                         "Partition table too long (%u > %lu)\n", table_len,
1416                         sb->s_blocksize - sizeof(*lvd));
1417                 ret = -EIO;
1418                 goto out_bh;
1419         }
1420
1421         ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
1422         if (ret)
1423                 goto out_bh;
1424
1425         for (i = 0, offset = 0;
1426              i < sbi->s_partitions && offset < table_len;
1427              i++, offset += gpm->partitionMapLength) {
1428                 struct udf_part_map *map = &sbi->s_partmaps[i];
1429                 gpm = (struct genericPartitionMap *)
1430                                 &(lvd->partitionMaps[offset]);
1431                 type = gpm->partitionMapType;
1432                 if (type == 1) {
1433                         struct genericPartitionMap1 *gpm1 =
1434                                 (struct genericPartitionMap1 *)gpm;
1435                         map->s_partition_type = UDF_TYPE1_MAP15;
1436                         map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
1437                         map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
1438                         map->s_partition_func = NULL;
1439                 } else if (type == 2) {
1440                         struct udfPartitionMap2 *upm2 =
1441                                                 (struct udfPartitionMap2 *)gpm;
1442                         if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
1443                                                 strlen(UDF_ID_VIRTUAL))) {
1444                                 u16 suf =
1445                                         le16_to_cpu(((__le16 *)upm2->partIdent.
1446                                                         identSuffix)[0]);
1447                                 if (suf < 0x0200) {
1448                                         map->s_partition_type =
1449                                                         UDF_VIRTUAL_MAP15;
1450                                         map->s_partition_func =
1451                                                         udf_get_pblock_virt15;
1452                                 } else {
1453                                         map->s_partition_type =
1454                                                         UDF_VIRTUAL_MAP20;
1455                                         map->s_partition_func =
1456                                                         udf_get_pblock_virt20;
1457                                 }
1458                         } else if (!strncmp(upm2->partIdent.ident,
1459                                                 UDF_ID_SPARABLE,
1460                                                 strlen(UDF_ID_SPARABLE))) {
1461                                 ret = udf_load_sparable_map(sb, map,
1462                                         (struct sparablePartitionMap *)gpm);
1463                                 if (ret < 0)
1464                                         goto out_bh;
1465                         } else if (!strncmp(upm2->partIdent.ident,
1466                                                 UDF_ID_METADATA,
1467                                                 strlen(UDF_ID_METADATA))) {
1468                                 struct udf_meta_data *mdata =
1469                                         &map->s_type_specific.s_metadata;
1470                                 struct metadataPartitionMap *mdm =
1471                                                 (struct metadataPartitionMap *)
1472                                                 &(lvd->partitionMaps[offset]);
1473                                 udf_debug("Parsing Logical vol part %d type %d  id=%s\n",
1474                                           i, type, UDF_ID_METADATA);
1475
1476                                 map->s_partition_type = UDF_METADATA_MAP25;
1477                                 map->s_partition_func = udf_get_pblock_meta25;
1478
1479                                 mdata->s_meta_file_loc   =
1480                                         le32_to_cpu(mdm->metadataFileLoc);
1481                                 mdata->s_mirror_file_loc =
1482                                         le32_to_cpu(mdm->metadataMirrorFileLoc);
1483                                 mdata->s_bitmap_file_loc =
1484                                         le32_to_cpu(mdm->metadataBitmapFileLoc);
1485                                 mdata->s_alloc_unit_size =
1486                                         le32_to_cpu(mdm->allocUnitSize);
1487                                 mdata->s_align_unit_size =
1488                                         le16_to_cpu(mdm->alignUnitSize);
1489                                 if (mdm->flags & 0x01)
1490                                         mdata->s_flags |= MF_DUPLICATE_MD;
1491
1492                                 udf_debug("Metadata Ident suffix=0x%x\n",
1493                                           le16_to_cpu(*(__le16 *)
1494                                                       mdm->partIdent.identSuffix));
1495                                 udf_debug("Metadata part num=%d\n",
1496                                           le16_to_cpu(mdm->partitionNum));
1497                                 udf_debug("Metadata part alloc unit size=%d\n",
1498                                           le32_to_cpu(mdm->allocUnitSize));
1499                                 udf_debug("Metadata file loc=%d\n",
1500                                           le32_to_cpu(mdm->metadataFileLoc));
1501                                 udf_debug("Mirror file loc=%d\n",
1502                                           le32_to_cpu(mdm->metadataMirrorFileLoc));
1503                                 udf_debug("Bitmap file loc=%d\n",
1504                                           le32_to_cpu(mdm->metadataBitmapFileLoc));
1505                                 udf_debug("Flags: %d %d\n",
1506                                           mdata->s_flags, mdm->flags);
1507                         } else {
1508                                 udf_debug("Unknown ident: %s\n",
1509                                           upm2->partIdent.ident);
1510                                 continue;
1511                         }
1512                         map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
1513                         map->s_partition_num = le16_to_cpu(upm2->partitionNum);
1514                 }
1515                 udf_debug("Partition (%d:%d) type %d on volume %d\n",
1516                           i, map->s_partition_num, type, map->s_volumeseqnum);
1517         }
1518
1519         if (fileset) {
1520                 struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
1521
1522                 *fileset = lelb_to_cpu(la->extLocation);
1523                 udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
1524                           fileset->logicalBlockNum,
1525                           fileset->partitionReferenceNum);
1526         }
1527         if (lvd->integritySeqExt.extLength)
1528                 udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
1529         ret = 0;
1530 out_bh:
1531         brelse(bh);
1532         return ret;
1533 }
1534
1535 /*
1536  * udf_load_logicalvolint
1537  *
1538  */
1539 static void udf_load_logicalvolint(struct super_block *sb, struct kernel_extent_ad loc)
1540 {
1541         struct buffer_head *bh = NULL;
1542         uint16_t ident;
1543         struct udf_sb_info *sbi = UDF_SB(sb);
1544         struct logicalVolIntegrityDesc *lvid;
1545
1546         while (loc.extLength > 0 &&
1547                (bh = udf_read_tagged(sb, loc.extLocation,
1548                                      loc.extLocation, &ident)) &&
1549                ident == TAG_IDENT_LVID) {
1550                 sbi->s_lvid_bh = bh;
1551                 lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
1552
1553                 if (lvid->nextIntegrityExt.extLength)
1554                         udf_load_logicalvolint(sb,
1555                                 leea_to_cpu(lvid->nextIntegrityExt));
1556
1557                 if (sbi->s_lvid_bh != bh)
1558                         brelse(bh);
1559                 loc.extLength -= sb->s_blocksize;
1560                 loc.extLocation++;
1561         }
1562         if (sbi->s_lvid_bh != bh)
1563                 brelse(bh);
1564 }
1565
1566 /*
1567  * Process a main/reserve volume descriptor sequence.
1568  *   @block             First block of first extent of the sequence.
1569  *   @lastblock         Lastblock of first extent of the sequence.
1570  *   @fileset           There we store extent containing root fileset
1571  *
1572  * Returns <0 on error, 0 on success. -EAGAIN is special - try next descriptor
1573  * sequence
1574  */
1575 static noinline int udf_process_sequence(
1576                 struct super_block *sb,
1577                 sector_t block, sector_t lastblock,
1578                 struct kernel_lb_addr *fileset)
1579 {
1580         struct buffer_head *bh = NULL;
1581         struct udf_vds_record vds[VDS_POS_LENGTH];
1582         struct udf_vds_record *curr;
1583         struct generic_desc *gd;
1584         struct volDescPtr *vdp;
1585         int done = 0;
1586         uint32_t vdsn;
1587         uint16_t ident;
1588         long next_s = 0, next_e = 0;
1589         int ret;
1590
1591         memset(vds, 0, sizeof(struct udf_vds_record) * VDS_POS_LENGTH);
1592
1593         /*
1594          * Read the main descriptor sequence and find which descriptors
1595          * are in it.
1596          */
1597         for (; (!done && block <= lastblock); block++) {
1598
1599                 bh = udf_read_tagged(sb, block, block, &ident);
1600                 if (!bh) {
1601                         udf_err(sb,
1602                                 "Block %llu of volume descriptor sequence is corrupted or we could not read it\n",
1603                                 (unsigned long long)block);
1604                         return -EAGAIN;
1605                 }
1606
1607                 /* Process each descriptor (ISO 13346 3/8.3-8.4) */
1608                 gd = (struct generic_desc *)bh->b_data;
1609                 vdsn = le32_to_cpu(gd->volDescSeqNum);
1610                 switch (ident) {
1611                 case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
1612                         curr = &vds[VDS_POS_PRIMARY_VOL_DESC];
1613                         if (vdsn >= curr->volDescSeqNum) {
1614                                 curr->volDescSeqNum = vdsn;
1615                                 curr->block = block;
1616                         }
1617                         break;
1618                 case TAG_IDENT_VDP: /* ISO 13346 3/10.3 */
1619                         curr = &vds[VDS_POS_VOL_DESC_PTR];
1620                         if (vdsn >= curr->volDescSeqNum) {
1621                                 curr->volDescSeqNum = vdsn;
1622                                 curr->block = block;
1623
1624                                 vdp = (struct volDescPtr *)bh->b_data;
1625                                 next_s = le32_to_cpu(
1626                                         vdp->nextVolDescSeqExt.extLocation);
1627                                 next_e = le32_to_cpu(
1628                                         vdp->nextVolDescSeqExt.extLength);
1629                                 next_e = next_e >> sb->s_blocksize_bits;
1630                                 next_e += next_s;
1631                         }
1632                         break;
1633                 case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
1634                         curr = &vds[VDS_POS_IMP_USE_VOL_DESC];
1635                         if (vdsn >= curr->volDescSeqNum) {
1636                                 curr->volDescSeqNum = vdsn;
1637                                 curr->block = block;
1638                         }
1639                         break;
1640                 case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
1641                         curr = &vds[VDS_POS_PARTITION_DESC];
1642                         if (!curr->block)
1643                                 curr->block = block;
1644                         break;
1645                 case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
1646                         curr = &vds[VDS_POS_LOGICAL_VOL_DESC];
1647                         if (vdsn >= curr->volDescSeqNum) {
1648                                 curr->volDescSeqNum = vdsn;
1649                                 curr->block = block;
1650                         }
1651                         break;
1652                 case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
1653                         curr = &vds[VDS_POS_UNALLOC_SPACE_DESC];
1654                         if (vdsn >= curr->volDescSeqNum) {
1655                                 curr->volDescSeqNum = vdsn;
1656                                 curr->block = block;
1657                         }
1658                         break;
1659                 case TAG_IDENT_TD: /* ISO 13346 3/10.9 */
1660                         vds[VDS_POS_TERMINATING_DESC].block = block;
1661                         if (next_e) {
1662                                 block = next_s;
1663                                 lastblock = next_e;
1664                                 next_s = next_e = 0;
1665                         } else
1666                                 done = 1;
1667                         break;
1668                 }
1669                 brelse(bh);
1670         }
1671         /*
1672          * Now read interesting descriptors again and process them
1673          * in a suitable order
1674          */
1675         if (!vds[VDS_POS_PRIMARY_VOL_DESC].block) {
1676                 udf_err(sb, "Primary Volume Descriptor not found!\n");
1677                 return -EAGAIN;
1678         }
1679         ret = udf_load_pvoldesc(sb, vds[VDS_POS_PRIMARY_VOL_DESC].block);
1680         if (ret < 0)
1681                 return ret;
1682
1683         if (vds[VDS_POS_LOGICAL_VOL_DESC].block) {
1684                 ret = udf_load_logicalvol(sb,
1685                                           vds[VDS_POS_LOGICAL_VOL_DESC].block,
1686                                           fileset);
1687                 if (ret < 0)
1688                         return ret;
1689         }
1690
1691         if (vds[VDS_POS_PARTITION_DESC].block) {
1692                 /*
1693                  * We rescan the whole descriptor sequence to find
1694                  * partition descriptor blocks and process them.
1695                  */
1696                 for (block = vds[VDS_POS_PARTITION_DESC].block;
1697                      block < vds[VDS_POS_TERMINATING_DESC].block;
1698                      block++) {
1699                         ret = udf_load_partdesc(sb, block);
1700                         if (ret < 0)
1701                                 return ret;
1702                 }
1703         }
1704
1705         return 0;
1706 }
1707
1708 /*
1709  * Load Volume Descriptor Sequence described by anchor in bh
1710  *
1711  * Returns <0 on error, 0 on success
1712  */
1713 static int udf_load_sequence(struct super_block *sb, struct buffer_head *bh,
1714                              struct kernel_lb_addr *fileset)
1715 {
1716         struct anchorVolDescPtr *anchor;
1717         sector_t main_s, main_e, reserve_s, reserve_e;
1718         int ret;
1719
1720         anchor = (struct anchorVolDescPtr *)bh->b_data;
1721
1722         /* Locate the main sequence */
1723         main_s = le32_to_cpu(anchor->mainVolDescSeqExt.extLocation);
1724         main_e = le32_to_cpu(anchor->mainVolDescSeqExt.extLength);
1725         main_e = main_e >> sb->s_blocksize_bits;
1726         main_e += main_s;
1727
1728         /* Locate the reserve sequence */
1729         reserve_s = le32_to_cpu(anchor->reserveVolDescSeqExt.extLocation);
1730         reserve_e = le32_to_cpu(anchor->reserveVolDescSeqExt.extLength);
1731         reserve_e = reserve_e >> sb->s_blocksize_bits;
1732         reserve_e += reserve_s;
1733
1734         /* Process the main & reserve sequences */
1735         /* responsible for finding the PartitionDesc(s) */
1736         ret = udf_process_sequence(sb, main_s, main_e, fileset);
1737         if (ret != -EAGAIN)
1738                 return ret;
1739         udf_sb_free_partitions(sb);
1740         ret = udf_process_sequence(sb, reserve_s, reserve_e, fileset);
1741         if (ret < 0) {
1742                 udf_sb_free_partitions(sb);
1743                 /* No sequence was OK, return -EIO */
1744                 if (ret == -EAGAIN)
1745                         ret = -EIO;
1746         }
1747         return ret;
1748 }
1749
1750 /*
1751  * Check whether there is an anchor block in the given block and
1752  * load Volume Descriptor Sequence if so.
1753  *
1754  * Returns <0 on error, 0 on success, -EAGAIN is special - try next anchor
1755  * block
1756  */
1757 static int udf_check_anchor_block(struct super_block *sb, sector_t block,
1758                                   struct kernel_lb_addr *fileset)
1759 {
1760         struct buffer_head *bh;
1761         uint16_t ident;
1762         int ret;
1763
1764         if (UDF_QUERY_FLAG(sb, UDF_FLAG_VARCONV) &&
1765             udf_fixed_to_variable(block) >=
1766             sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits)
1767                 return -EAGAIN;
1768
1769         bh = udf_read_tagged(sb, block, block, &ident);
1770         if (!bh)
1771                 return -EAGAIN;
1772         if (ident != TAG_IDENT_AVDP) {
1773                 brelse(bh);
1774                 return -EAGAIN;
1775         }
1776         ret = udf_load_sequence(sb, bh, fileset);
1777         brelse(bh);
1778         return ret;
1779 }
1780
1781 /*
1782  * Search for an anchor volume descriptor pointer.
1783  *
1784  * Returns < 0 on error, 0 on success. -EAGAIN is special - try next set
1785  * of anchors.
1786  */
1787 static int udf_scan_anchors(struct super_block *sb, sector_t *lastblock,
1788                             struct kernel_lb_addr *fileset)
1789 {
1790         sector_t last[6];
1791         int i;
1792         struct udf_sb_info *sbi = UDF_SB(sb);
1793         int last_count = 0;
1794         int ret;
1795
1796         /* First try user provided anchor */
1797         if (sbi->s_anchor) {
1798                 ret = udf_check_anchor_block(sb, sbi->s_anchor, fileset);
1799                 if (ret != -EAGAIN)
1800                         return ret;
1801         }
1802         /*
1803          * according to spec, anchor is in either:
1804          *     block 256
1805          *     lastblock-256
1806          *     lastblock
1807          *  however, if the disc isn't closed, it could be 512.
1808          */
1809         ret = udf_check_anchor_block(sb, sbi->s_session + 256, fileset);
1810         if (ret != -EAGAIN)
1811                 return ret;
1812         /*
1813          * The trouble is which block is the last one. Drives often misreport
1814          * this so we try various possibilities.
1815          */
1816         last[last_count++] = *lastblock;
1817         if (*lastblock >= 1)
1818                 last[last_count++] = *lastblock - 1;
1819         last[last_count++] = *lastblock + 1;
1820         if (*lastblock >= 2)
1821                 last[last_count++] = *lastblock - 2;
1822         if (*lastblock >= 150)
1823                 last[last_count++] = *lastblock - 150;
1824         if (*lastblock >= 152)
1825                 last[last_count++] = *lastblock - 152;
1826
1827         for (i = 0; i < last_count; i++) {
1828                 if (last[i] >= sb->s_bdev->bd_inode->i_size >>
1829                                 sb->s_blocksize_bits)
1830                         continue;
1831                 ret = udf_check_anchor_block(sb, last[i], fileset);
1832                 if (ret != -EAGAIN) {
1833                         if (!ret)
1834                                 *lastblock = last[i];
1835                         return ret;
1836                 }
1837                 if (last[i] < 256)
1838                         continue;
1839                 ret = udf_check_anchor_block(sb, last[i] - 256, fileset);
1840                 if (ret != -EAGAIN) {
1841                         if (!ret)
1842                                 *lastblock = last[i];
1843                         return ret;
1844                 }
1845         }
1846
1847         /* Finally try block 512 in case media is open */
1848         return udf_check_anchor_block(sb, sbi->s_session + 512, fileset);
1849 }
1850
1851 /*
1852  * Find an anchor volume descriptor and load Volume Descriptor Sequence from
1853  * area specified by it. The function expects sbi->s_lastblock to be the last
1854  * block on the media.
1855  *
1856  * Return <0 on error, 0 if anchor found. -EAGAIN is special meaning anchor
1857  * was not found.
1858  */
1859 static int udf_find_anchor(struct super_block *sb,
1860                            struct kernel_lb_addr *fileset)
1861 {
1862         struct udf_sb_info *sbi = UDF_SB(sb);
1863         sector_t lastblock = sbi->s_last_block;
1864         int ret;
1865
1866         ret = udf_scan_anchors(sb, &lastblock, fileset);
1867         if (ret != -EAGAIN)
1868                 goto out;
1869
1870         /* No anchor found? Try VARCONV conversion of block numbers */
1871         UDF_SET_FLAG(sb, UDF_FLAG_VARCONV);
1872         lastblock = udf_variable_to_fixed(sbi->s_last_block);
1873         /* Firstly, we try to not convert number of the last block */
1874         ret = udf_scan_anchors(sb, &lastblock, fileset);
1875         if (ret != -EAGAIN)
1876                 goto out;
1877
1878         lastblock = sbi->s_last_block;
1879         /* Secondly, we try with converted number of the last block */
1880         ret = udf_scan_anchors(sb, &lastblock, fileset);
1881         if (ret < 0) {
1882                 /* VARCONV didn't help. Clear it. */
1883                 UDF_CLEAR_FLAG(sb, UDF_FLAG_VARCONV);
1884         }
1885 out:
1886         if (ret == 0)
1887                 sbi->s_last_block = lastblock;
1888         return ret;
1889 }
1890
1891 /*
1892  * Check Volume Structure Descriptor, find Anchor block and load Volume
1893  * Descriptor Sequence.
1894  *
1895  * Returns < 0 on error, 0 on success. -EAGAIN is special meaning anchor
1896  * block was not found.
1897  */
1898 static int udf_load_vrs(struct super_block *sb, struct udf_options *uopt,
1899                         int silent, struct kernel_lb_addr *fileset)
1900 {
1901         struct udf_sb_info *sbi = UDF_SB(sb);
1902         loff_t nsr_off;
1903         int ret;
1904
1905         if (!sb_set_blocksize(sb, uopt->blocksize)) {
1906                 if (!silent)
1907                         udf_warn(sb, "Bad block size\n");
1908                 return -EINVAL;
1909         }
1910         sbi->s_last_block = uopt->lastblock;
1911         if (!uopt->novrs) {
1912                 /* Check that it is NSR02 compliant */
1913                 nsr_off = udf_check_vsd(sb);
1914                 if (!nsr_off) {
1915                         if (!silent)
1916                                 udf_warn(sb, "No VRS found\n");
1917                         return 0;
1918                 }
1919                 if (nsr_off == -1)
1920                         udf_debug("Failed to read sector at offset %d. "
1921                                   "Assuming open disc. Skipping validity "
1922                                   "check\n", VSD_FIRST_SECTOR_OFFSET);
1923                 if (!sbi->s_last_block)
1924                         sbi->s_last_block = udf_get_last_block(sb);
1925         } else {
1926                 udf_debug("Validity check skipped because of novrs option\n");
1927         }
1928
1929         /* Look for anchor block and load Volume Descriptor Sequence */
1930         sbi->s_anchor = uopt->anchor;
1931         ret = udf_find_anchor(sb, fileset);
1932         if (ret < 0) {
1933                 if (!silent && ret == -EAGAIN)
1934                         udf_warn(sb, "No anchor found\n");
1935                 return ret;
1936         }
1937         return 0;
1938 }
1939
1940 static void udf_open_lvid(struct super_block *sb)
1941 {
1942         struct udf_sb_info *sbi = UDF_SB(sb);
1943         struct buffer_head *bh = sbi->s_lvid_bh;
1944         struct logicalVolIntegrityDesc *lvid;
1945         struct logicalVolIntegrityDescImpUse *lvidiu;
1946
1947         if (!bh)
1948                 return;
1949         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
1950         lvidiu = udf_sb_lvidiu(sb);
1951         if (!lvidiu)
1952                 return;
1953
1954         mutex_lock(&sbi->s_alloc_mutex);
1955         lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
1956         lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
1957         udf_time_to_disk_stamp(&lvid->recordingDateAndTime,
1958                                 CURRENT_TIME);
1959         lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_OPEN);
1960
1961         lvid->descTag.descCRC = cpu_to_le16(
1962                 crc_itu_t(0, (char *)lvid + sizeof(struct tag),
1963                         le16_to_cpu(lvid->descTag.descCRCLength)));
1964
1965         lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag);
1966         mark_buffer_dirty(bh);
1967         sbi->s_lvid_dirty = 0;
1968         mutex_unlock(&sbi->s_alloc_mutex);
1969         /* Make opening of filesystem visible on the media immediately */
1970         sync_dirty_buffer(bh);
1971 }
1972
1973 static void udf_close_lvid(struct super_block *sb)
1974 {
1975         struct udf_sb_info *sbi = UDF_SB(sb);
1976         struct buffer_head *bh = sbi->s_lvid_bh;
1977         struct logicalVolIntegrityDesc *lvid;
1978         struct logicalVolIntegrityDescImpUse *lvidiu;
1979
1980         if (!bh)
1981                 return;
1982         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
1983         lvidiu = udf_sb_lvidiu(sb);
1984         if (!lvidiu)
1985                 return;
1986
1987         mutex_lock(&sbi->s_alloc_mutex);
1988         lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
1989         lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
1990         udf_time_to_disk_stamp(&lvid->recordingDateAndTime, CURRENT_TIME);
1991         if (UDF_MAX_WRITE_VERSION > le16_to_cpu(lvidiu->maxUDFWriteRev))
1992                 lvidiu->maxUDFWriteRev = cpu_to_le16(UDF_MAX_WRITE_VERSION);
1993         if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFReadRev))
1994                 lvidiu->minUDFReadRev = cpu_to_le16(sbi->s_udfrev);
1995         if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFWriteRev))
1996                 lvidiu->minUDFWriteRev = cpu_to_le16(sbi->s_udfrev);
1997         lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_CLOSE);
1998
1999         lvid->descTag.descCRC = cpu_to_le16(
2000                         crc_itu_t(0, (char *)lvid + sizeof(struct tag),
2001                                 le16_to_cpu(lvid->descTag.descCRCLength)));
2002
2003         lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag);
2004         /*
2005          * We set buffer uptodate unconditionally here to avoid spurious
2006          * warnings from mark_buffer_dirty() when previous EIO has marked
2007          * the buffer as !uptodate
2008          */
2009         set_buffer_uptodate(bh);
2010         mark_buffer_dirty(bh);
2011         sbi->s_lvid_dirty = 0;
2012         mutex_unlock(&sbi->s_alloc_mutex);
2013         /* Make closing of filesystem visible on the media immediately */
2014         sync_dirty_buffer(bh);
2015 }
2016
2017 u64 lvid_get_unique_id(struct super_block *sb)
2018 {
2019         struct buffer_head *bh;
2020         struct udf_sb_info *sbi = UDF_SB(sb);
2021         struct logicalVolIntegrityDesc *lvid;
2022         struct logicalVolHeaderDesc *lvhd;
2023         u64 uniqueID;
2024         u64 ret;
2025
2026         bh = sbi->s_lvid_bh;
2027         if (!bh)
2028                 return 0;
2029
2030         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2031         lvhd = (struct logicalVolHeaderDesc *)lvid->logicalVolContentsUse;
2032
2033         mutex_lock(&sbi->s_alloc_mutex);
2034         ret = uniqueID = le64_to_cpu(lvhd->uniqueID);
2035         if (!(++uniqueID & 0xFFFFFFFF))
2036                 uniqueID += 16;
2037         lvhd->uniqueID = cpu_to_le64(uniqueID);
2038         mutex_unlock(&sbi->s_alloc_mutex);
2039         mark_buffer_dirty(bh);
2040
2041         return ret;
2042 }
2043
2044 static int udf_fill_super(struct super_block *sb, void *options, int silent)
2045 {
2046         int ret = -EINVAL;
2047         struct inode *inode = NULL;
2048         struct udf_options uopt;
2049         struct kernel_lb_addr rootdir, fileset;
2050         struct udf_sb_info *sbi;
2051
2052         uopt.flags = (1 << UDF_FLAG_USE_AD_IN_ICB) | (1 << UDF_FLAG_STRICT);
2053         uopt.uid = INVALID_UID;
2054         uopt.gid = INVALID_GID;
2055         uopt.umask = 0;
2056         uopt.fmode = UDF_INVALID_MODE;
2057         uopt.dmode = UDF_INVALID_MODE;
2058
2059         sbi = kzalloc(sizeof(struct udf_sb_info), GFP_KERNEL);
2060         if (!sbi)
2061                 return -ENOMEM;
2062
2063         sb->s_fs_info = sbi;
2064
2065         mutex_init(&sbi->s_alloc_mutex);
2066
2067         if (!udf_parse_options((char *)options, &uopt, false))
2068                 goto error_out;
2069
2070         if (uopt.flags & (1 << UDF_FLAG_UTF8) &&
2071             uopt.flags & (1 << UDF_FLAG_NLS_MAP)) {
2072                 udf_err(sb, "utf8 cannot be combined with iocharset\n");
2073                 goto error_out;
2074         }
2075 #ifdef CONFIG_UDF_NLS
2076         if ((uopt.flags & (1 << UDF_FLAG_NLS_MAP)) && !uopt.nls_map) {
2077                 uopt.nls_map = load_nls_default();
2078                 if (!uopt.nls_map)
2079                         uopt.flags &= ~(1 << UDF_FLAG_NLS_MAP);
2080                 else
2081                         udf_debug("Using default NLS map\n");
2082         }
2083 #endif
2084         if (!(uopt.flags & (1 << UDF_FLAG_NLS_MAP)))
2085                 uopt.flags |= (1 << UDF_FLAG_UTF8);
2086
2087         fileset.logicalBlockNum = 0xFFFFFFFF;
2088         fileset.partitionReferenceNum = 0xFFFF;
2089
2090         sbi->s_flags = uopt.flags;
2091         sbi->s_uid = uopt.uid;
2092         sbi->s_gid = uopt.gid;
2093         sbi->s_umask = uopt.umask;
2094         sbi->s_fmode = uopt.fmode;
2095         sbi->s_dmode = uopt.dmode;
2096         sbi->s_nls_map = uopt.nls_map;
2097         rwlock_init(&sbi->s_cred_lock);
2098
2099         if (uopt.session == 0xFFFFFFFF)
2100                 sbi->s_session = udf_get_last_session(sb);
2101         else
2102                 sbi->s_session = uopt.session;
2103
2104         udf_debug("Multi-session=%d\n", sbi->s_session);
2105
2106         /* Fill in the rest of the superblock */
2107         sb->s_op = &udf_sb_ops;
2108         sb->s_export_op = &udf_export_ops;
2109
2110         sb->s_magic = UDF_SUPER_MAGIC;
2111         sb->s_time_gran = 1000;
2112
2113         if (uopt.flags & (1 << UDF_FLAG_BLOCKSIZE_SET)) {
2114                 ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2115         } else {
2116                 uopt.blocksize = bdev_logical_block_size(sb->s_bdev);
2117                 ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2118                 if (ret == -EAGAIN && uopt.blocksize != UDF_DEFAULT_BLOCKSIZE) {
2119                         if (!silent)
2120                                 pr_notice("Rescanning with blocksize %d\n",
2121                                           UDF_DEFAULT_BLOCKSIZE);
2122                         brelse(sbi->s_lvid_bh);
2123                         sbi->s_lvid_bh = NULL;
2124                         uopt.blocksize = UDF_DEFAULT_BLOCKSIZE;
2125                         ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2126                 }
2127         }
2128         if (ret < 0) {
2129                 if (ret == -EAGAIN) {
2130                         udf_warn(sb, "No partition found (1)\n");
2131                         ret = -EINVAL;
2132                 }
2133                 goto error_out;
2134         }
2135
2136         udf_debug("Lastblock=%d\n", sbi->s_last_block);
2137
2138         if (sbi->s_lvid_bh) {
2139                 struct logicalVolIntegrityDescImpUse *lvidiu =
2140                                                         udf_sb_lvidiu(sb);
2141                 uint16_t minUDFReadRev;
2142                 uint16_t minUDFWriteRev;
2143
2144                 if (!lvidiu) {
2145                         ret = -EINVAL;
2146                         goto error_out;
2147                 }
2148                 minUDFReadRev = le16_to_cpu(lvidiu->minUDFReadRev);
2149                 minUDFWriteRev = le16_to_cpu(lvidiu->minUDFWriteRev);
2150                 if (minUDFReadRev > UDF_MAX_READ_VERSION) {
2151                         udf_err(sb, "minUDFReadRev=%x (max is %x)\n",
2152                                 minUDFReadRev,
2153                                 UDF_MAX_READ_VERSION);
2154                         ret = -EINVAL;
2155                         goto error_out;
2156                 } else if (minUDFWriteRev > UDF_MAX_WRITE_VERSION &&
2157                            !(sb->s_flags & MS_RDONLY)) {
2158                         ret = -EACCES;
2159                         goto error_out;
2160                 }
2161
2162                 sbi->s_udfrev = minUDFWriteRev;
2163
2164                 if (minUDFReadRev >= UDF_VERS_USE_EXTENDED_FE)
2165                         UDF_SET_FLAG(sb, UDF_FLAG_USE_EXTENDED_FE);
2166                 if (minUDFReadRev >= UDF_VERS_USE_STREAMS)
2167                         UDF_SET_FLAG(sb, UDF_FLAG_USE_STREAMS);
2168         }
2169
2170         if (!sbi->s_partitions) {
2171                 udf_warn(sb, "No partition found (2)\n");
2172                 ret = -EINVAL;
2173                 goto error_out;
2174         }
2175
2176         if (sbi->s_partmaps[sbi->s_partition].s_partition_flags &
2177                         UDF_PART_FLAG_READ_ONLY &&
2178             !(sb->s_flags & MS_RDONLY)) {
2179                 ret = -EACCES;
2180                 goto error_out;
2181         }
2182
2183         if (udf_find_fileset(sb, &fileset, &rootdir)) {
2184                 udf_warn(sb, "No fileset found\n");
2185                 ret = -EINVAL;
2186                 goto error_out;
2187         }
2188
2189         if (!silent) {
2190                 struct timestamp ts;
2191                 udf_time_to_disk_stamp(&ts, sbi->s_record_time);
2192                 udf_info("Mounting volume '%s', timestamp %04u/%02u/%02u %02u:%02u (%x)\n",
2193                          sbi->s_volume_ident,
2194                          le16_to_cpu(ts.year), ts.month, ts.day,
2195                          ts.hour, ts.minute, le16_to_cpu(ts.typeAndTimezone));
2196         }
2197         if (!(sb->s_flags & MS_RDONLY))
2198                 udf_open_lvid(sb);
2199
2200         /* Assign the root inode */
2201         /* assign inodes by physical block number */
2202         /* perhaps it's not extensible enough, but for now ... */
2203         inode = udf_iget(sb, &rootdir);
2204         if (!inode) {
2205                 udf_err(sb, "Error in udf_iget, block=%d, partition=%d\n",
2206                        rootdir.logicalBlockNum, rootdir.partitionReferenceNum);
2207                 ret = -EIO;
2208                 goto error_out;
2209         }
2210
2211         /* Allocate a dentry for the root inode */
2212         sb->s_root = d_make_root(inode);
2213         if (!sb->s_root) {
2214                 udf_err(sb, "Couldn't allocate root dentry\n");
2215                 ret = -ENOMEM;
2216                 goto error_out;
2217         }
2218         sb->s_maxbytes = MAX_LFS_FILESIZE;
2219         sb->s_max_links = UDF_MAX_LINKS;
2220         return 0;
2221
2222 error_out:
2223         if (sbi->s_vat_inode)
2224                 iput(sbi->s_vat_inode);
2225 #ifdef CONFIG_UDF_NLS
2226         if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP))
2227                 unload_nls(sbi->s_nls_map);
2228 #endif
2229         if (!(sb->s_flags & MS_RDONLY))
2230                 udf_close_lvid(sb);
2231         brelse(sbi->s_lvid_bh);
2232         udf_sb_free_partitions(sb);
2233         kfree(sbi);
2234         sb->s_fs_info = NULL;
2235
2236         return ret;
2237 }
2238
2239 void _udf_err(struct super_block *sb, const char *function,
2240               const char *fmt, ...)
2241 {
2242         struct va_format vaf;
2243         va_list args;
2244
2245         va_start(args, fmt);
2246
2247         vaf.fmt = fmt;
2248         vaf.va = &args;
2249
2250         pr_err("error (device %s): %s: %pV", sb->s_id, function, &vaf);
2251
2252         va_end(args);
2253 }
2254
2255 void _udf_warn(struct super_block *sb, const char *function,
2256                const char *fmt, ...)
2257 {
2258         struct va_format vaf;
2259         va_list args;
2260
2261         va_start(args, fmt);
2262
2263         vaf.fmt = fmt;
2264         vaf.va = &args;
2265
2266         pr_warn("warning (device %s): %s: %pV", sb->s_id, function, &vaf);
2267
2268         va_end(args);
2269 }
2270
2271 static void udf_put_super(struct super_block *sb)
2272 {
2273         struct udf_sb_info *sbi;
2274
2275         sbi = UDF_SB(sb);
2276
2277         if (sbi->s_vat_inode)
2278                 iput(sbi->s_vat_inode);
2279 #ifdef CONFIG_UDF_NLS
2280         if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP))
2281                 unload_nls(sbi->s_nls_map);
2282 #endif
2283         if (!(sb->s_flags & MS_RDONLY))
2284                 udf_close_lvid(sb);
2285         brelse(sbi->s_lvid_bh);
2286         udf_sb_free_partitions(sb);
2287         kfree(sb->s_fs_info);
2288         sb->s_fs_info = NULL;
2289 }
2290
2291 static int udf_sync_fs(struct super_block *sb, int wait)
2292 {
2293         struct udf_sb_info *sbi = UDF_SB(sb);
2294
2295         mutex_lock(&sbi->s_alloc_mutex);
2296         if (sbi->s_lvid_dirty) {
2297                 /*
2298                  * Blockdevice will be synced later so we don't have to submit
2299                  * the buffer for IO
2300                  */
2301                 mark_buffer_dirty(sbi->s_lvid_bh);
2302                 sbi->s_lvid_dirty = 0;
2303         }
2304         mutex_unlock(&sbi->s_alloc_mutex);
2305
2306         return 0;
2307 }
2308
2309 static int udf_statfs(struct dentry *dentry, struct kstatfs *buf)
2310 {
2311         struct super_block *sb = dentry->d_sb;
2312         struct udf_sb_info *sbi = UDF_SB(sb);
2313         struct logicalVolIntegrityDescImpUse *lvidiu;
2314         u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
2315
2316         lvidiu = udf_sb_lvidiu(sb);
2317         buf->f_type = UDF_SUPER_MAGIC;
2318         buf->f_bsize = sb->s_blocksize;
2319         buf->f_blocks = sbi->s_partmaps[sbi->s_partition].s_partition_len;
2320         buf->f_bfree = udf_count_free(sb);
2321         buf->f_bavail = buf->f_bfree;
2322         buf->f_files = (lvidiu != NULL ? (le32_to_cpu(lvidiu->numFiles) +
2323                                           le32_to_cpu(lvidiu->numDirs)) : 0)
2324                         + buf->f_bfree;
2325         buf->f_ffree = buf->f_bfree;
2326         buf->f_namelen = UDF_NAME_LEN - 2;
2327         buf->f_fsid.val[0] = (u32)id;
2328         buf->f_fsid.val[1] = (u32)(id >> 32);
2329
2330         return 0;
2331 }
2332
2333 static unsigned int udf_count_free_bitmap(struct super_block *sb,
2334                                           struct udf_bitmap *bitmap)
2335 {
2336         struct buffer_head *bh = NULL;
2337         unsigned int accum = 0;
2338         int index;
2339         int block = 0, newblock;
2340         struct kernel_lb_addr loc;
2341         uint32_t bytes;
2342         uint8_t *ptr;
2343         uint16_t ident;
2344         struct spaceBitmapDesc *bm;
2345
2346         loc.logicalBlockNum = bitmap->s_extPosition;
2347         loc.partitionReferenceNum = UDF_SB(sb)->s_partition;
2348         bh = udf_read_ptagged(sb, &loc, 0, &ident);
2349
2350         if (!bh) {
2351                 udf_err(sb, "udf_count_free failed\n");
2352                 goto out;
2353         } else if (ident != TAG_IDENT_SBD) {
2354                 brelse(bh);
2355                 udf_err(sb, "udf_count_free failed\n");
2356                 goto out;
2357         }
2358
2359         bm = (struct spaceBitmapDesc *)bh->b_data;
2360         bytes = le32_to_cpu(bm->numOfBytes);
2361         index = sizeof(struct spaceBitmapDesc); /* offset in first block only */
2362         ptr = (uint8_t *)bh->b_data;
2363
2364         while (bytes > 0) {
2365                 u32 cur_bytes = min_t(u32, bytes, sb->s_blocksize - index);
2366                 accum += bitmap_weight((const unsigned long *)(ptr + index),
2367                                         cur_bytes * 8);
2368                 bytes -= cur_bytes;
2369                 if (bytes) {
2370                         brelse(bh);
2371                         newblock = udf_get_lb_pblock(sb, &loc, ++block);
2372                         bh = udf_tread(sb, newblock);
2373                         if (!bh) {
2374                                 udf_debug("read failed\n");
2375                                 goto out;
2376                         }
2377                         index = 0;
2378                         ptr = (uint8_t *)bh->b_data;
2379                 }
2380         }
2381         brelse(bh);
2382 out:
2383         return accum;
2384 }
2385
2386 static unsigned int udf_count_free_table(struct super_block *sb,
2387                                          struct inode *table)
2388 {
2389         unsigned int accum = 0;
2390         uint32_t elen;
2391         struct kernel_lb_addr eloc;
2392         int8_t etype;
2393         struct extent_position epos;
2394
2395         mutex_lock(&UDF_SB(sb)->s_alloc_mutex);
2396         epos.block = UDF_I(table)->i_location;
2397         epos.offset = sizeof(struct unallocSpaceEntry);
2398         epos.bh = NULL;
2399
2400         while ((etype = udf_next_aext(table, &epos, &eloc, &elen, 1)) != -1)
2401                 accum += (elen >> table->i_sb->s_blocksize_bits);
2402
2403         brelse(epos.bh);
2404         mutex_unlock(&UDF_SB(sb)->s_alloc_mutex);
2405
2406         return accum;
2407 }
2408
2409 static unsigned int udf_count_free(struct super_block *sb)
2410 {
2411         unsigned int accum = 0;
2412         struct udf_sb_info *sbi;
2413         struct udf_part_map *map;
2414
2415         sbi = UDF_SB(sb);
2416         if (sbi->s_lvid_bh) {
2417                 struct logicalVolIntegrityDesc *lvid =
2418                         (struct logicalVolIntegrityDesc *)
2419                         sbi->s_lvid_bh->b_data;
2420                 if (le32_to_cpu(lvid->numOfPartitions) > sbi->s_partition) {
2421                         accum = le32_to_cpu(
2422                                         lvid->freeSpaceTable[sbi->s_partition]);
2423                         if (accum == 0xFFFFFFFF)
2424                                 accum = 0;
2425                 }
2426         }
2427
2428         if (accum)
2429                 return accum;
2430
2431         map = &sbi->s_partmaps[sbi->s_partition];
2432         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) {
2433                 accum += udf_count_free_bitmap(sb,
2434                                                map->s_uspace.s_bitmap);
2435         }
2436         if (map->s_partition_flags & UDF_PART_FLAG_FREED_BITMAP) {
2437                 accum += udf_count_free_bitmap(sb,
2438                                                map->s_fspace.s_bitmap);
2439         }
2440         if (accum)
2441                 return accum;
2442
2443         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) {
2444                 accum += udf_count_free_table(sb,
2445                                               map->s_uspace.s_table);
2446         }
2447         if (map->s_partition_flags & UDF_PART_FLAG_FREED_TABLE) {
2448                 accum += udf_count_free_table(sb,
2449                                               map->s_fspace.s_table);
2450         }
2451
2452         return accum;
2453 }