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