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