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