GNU Linux-libre 5.10.217-gnu1
[releases.git] / fs / udf / super.c
1 /*
2  * super.c
3  *
4  * PURPOSE
5  *  Super block routines for the OSTA-UDF(tm) filesystem.
6  *
7  * DESCRIPTION
8  *  OSTA-UDF(tm) = Optical Storage Technology Association
9  *  Universal Disk Format.
10  *
11  *  This code is based on version 2.00 of the UDF specification,
12  *  and revision 3 of the ECMA 167 standard [equivalent to ISO 13346].
13  *    http://www.osta.org/
14  *    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 = kmem_cache_alloc(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
460         uopt->novrs = 0;
461         uopt->session = 0xFFFFFFFF;
462         uopt->lastblock = 0;
463         uopt->anchor = 0;
464
465         if (!options)
466                 return 1;
467
468         while ((p = strsep(&options, ",")) != NULL) {
469                 substring_t args[MAX_OPT_ARGS];
470                 int token;
471                 unsigned n;
472                 if (!*p)
473                         continue;
474
475                 token = match_token(p, tokens, args);
476                 switch (token) {
477                 case Opt_novrs:
478                         uopt->novrs = 1;
479                         break;
480                 case Opt_bs:
481                         if (match_int(&args[0], &option))
482                                 return 0;
483                         n = option;
484                         if (n != 512 && n != 1024 && n != 2048 && n != 4096)
485                                 return 0;
486                         uopt->blocksize = n;
487                         uopt->flags |= (1 << UDF_FLAG_BLOCKSIZE_SET);
488                         break;
489                 case Opt_unhide:
490                         uopt->flags |= (1 << UDF_FLAG_UNHIDE);
491                         break;
492                 case Opt_undelete:
493                         uopt->flags |= (1 << UDF_FLAG_UNDELETE);
494                         break;
495                 case Opt_noadinicb:
496                         uopt->flags &= ~(1 << UDF_FLAG_USE_AD_IN_ICB);
497                         break;
498                 case Opt_adinicb:
499                         uopt->flags |= (1 << UDF_FLAG_USE_AD_IN_ICB);
500                         break;
501                 case Opt_shortad:
502                         uopt->flags |= (1 << UDF_FLAG_USE_SHORT_AD);
503                         break;
504                 case Opt_longad:
505                         uopt->flags &= ~(1 << UDF_FLAG_USE_SHORT_AD);
506                         break;
507                 case Opt_gid:
508                         if (match_int(args, &option))
509                                 return 0;
510                         uopt->gid = make_kgid(current_user_ns(), option);
511                         if (!gid_valid(uopt->gid))
512                                 return 0;
513                         uopt->flags |= (1 << UDF_FLAG_GID_SET);
514                         break;
515                 case Opt_uid:
516                         if (match_int(args, &option))
517                                 return 0;
518                         uopt->uid = make_kuid(current_user_ns(), option);
519                         if (!uid_valid(uopt->uid))
520                                 return 0;
521                         uopt->flags |= (1 << UDF_FLAG_UID_SET);
522                         break;
523                 case Opt_umask:
524                         if (match_octal(args, &option))
525                                 return 0;
526                         uopt->umask = option;
527                         break;
528                 case Opt_nostrict:
529                         uopt->flags &= ~(1 << UDF_FLAG_STRICT);
530                         break;
531                 case Opt_session:
532                         if (match_int(args, &option))
533                                 return 0;
534                         uopt->session = option;
535                         if (!remount)
536                                 uopt->flags |= (1 << UDF_FLAG_SESSION_SET);
537                         break;
538                 case Opt_lastblock:
539                         if (match_int(args, &option))
540                                 return 0;
541                         uopt->lastblock = option;
542                         if (!remount)
543                                 uopt->flags |= (1 << UDF_FLAG_LASTBLOCK_SET);
544                         break;
545                 case Opt_anchor:
546                         if (match_int(args, &option))
547                                 return 0;
548                         uopt->anchor = option;
549                         break;
550                 case Opt_volume:
551                 case Opt_partition:
552                 case Opt_fileset:
553                 case Opt_rootdir:
554                         /* Ignored (never implemented properly) */
555                         break;
556                 case Opt_utf8:
557                         if (!remount) {
558                                 unload_nls(uopt->nls_map);
559                                 uopt->nls_map = NULL;
560                         }
561                         break;
562                 case Opt_iocharset:
563                         if (!remount) {
564                                 unload_nls(uopt->nls_map);
565                                 uopt->nls_map = NULL;
566                         }
567                         /* When nls_map is not loaded then UTF-8 is used */
568                         if (!remount && strcmp(args[0].from, "utf8") != 0) {
569                                 uopt->nls_map = load_nls(args[0].from);
570                                 if (!uopt->nls_map) {
571                                         pr_err("iocharset %s not found\n",
572                                                 args[0].from);
573                                         return 0;
574                                 }
575                         }
576                         break;
577                 case Opt_uforget:
578                         uopt->flags |= (1 << UDF_FLAG_UID_FORGET);
579                         break;
580                 case Opt_uignore:
581                 case Opt_gignore:
582                         /* These options are superseeded by uid=<number> */
583                         break;
584                 case Opt_gforget:
585                         uopt->flags |= (1 << UDF_FLAG_GID_FORGET);
586                         break;
587                 case Opt_fmode:
588                         if (match_octal(args, &option))
589                                 return 0;
590                         uopt->fmode = option & 0777;
591                         break;
592                 case Opt_dmode:
593                         if (match_octal(args, &option))
594                                 return 0;
595                         uopt->dmode = option & 0777;
596                         break;
597                 default:
598                         pr_err("bad mount option \"%s\" or missing value\n", p);
599                         return 0;
600                 }
601         }
602         return 1;
603 }
604
605 static int udf_remount_fs(struct super_block *sb, int *flags, char *options)
606 {
607         struct udf_options uopt;
608         struct udf_sb_info *sbi = UDF_SB(sb);
609         int error = 0;
610
611         if (!(*flags & SB_RDONLY) && UDF_QUERY_FLAG(sb, UDF_FLAG_RW_INCOMPAT))
612                 return -EACCES;
613
614         sync_filesystem(sb);
615
616         uopt.flags = sbi->s_flags;
617         uopt.uid   = sbi->s_uid;
618         uopt.gid   = sbi->s_gid;
619         uopt.umask = sbi->s_umask;
620         uopt.fmode = sbi->s_fmode;
621         uopt.dmode = sbi->s_dmode;
622         uopt.nls_map = NULL;
623
624         if (!udf_parse_options(options, &uopt, true))
625                 return -EINVAL;
626
627         write_lock(&sbi->s_cred_lock);
628         sbi->s_flags = uopt.flags;
629         sbi->s_uid   = uopt.uid;
630         sbi->s_gid   = uopt.gid;
631         sbi->s_umask = uopt.umask;
632         sbi->s_fmode = uopt.fmode;
633         sbi->s_dmode = uopt.dmode;
634         write_unlock(&sbi->s_cred_lock);
635
636         if ((bool)(*flags & SB_RDONLY) == sb_rdonly(sb))
637                 goto out_unlock;
638
639         if (*flags & SB_RDONLY)
640                 udf_close_lvid(sb);
641         else
642                 udf_open_lvid(sb);
643
644 out_unlock:
645         return error;
646 }
647
648 /*
649  * Check VSD descriptor. Returns -1 in case we are at the end of volume
650  * recognition area, 0 if the descriptor is valid but non-interesting, 1 if
651  * we found one of NSR descriptors we are looking for.
652  */
653 static int identify_vsd(const struct volStructDesc *vsd)
654 {
655         int ret = 0;
656
657         if (!memcmp(vsd->stdIdent, VSD_STD_ID_CD001, VSD_STD_ID_LEN)) {
658                 switch (vsd->structType) {
659                 case 0:
660                         udf_debug("ISO9660 Boot Record found\n");
661                         break;
662                 case 1:
663                         udf_debug("ISO9660 Primary Volume Descriptor found\n");
664                         break;
665                 case 2:
666                         udf_debug("ISO9660 Supplementary Volume Descriptor found\n");
667                         break;
668                 case 3:
669                         udf_debug("ISO9660 Volume Partition Descriptor found\n");
670                         break;
671                 case 255:
672                         udf_debug("ISO9660 Volume Descriptor Set Terminator found\n");
673                         break;
674                 default:
675                         udf_debug("ISO9660 VRS (%u) found\n", vsd->structType);
676                         break;
677                 }
678         } else if (!memcmp(vsd->stdIdent, VSD_STD_ID_BEA01, VSD_STD_ID_LEN))
679                 ; /* ret = 0 */
680         else if (!memcmp(vsd->stdIdent, VSD_STD_ID_NSR02, VSD_STD_ID_LEN))
681                 ret = 1;
682         else if (!memcmp(vsd->stdIdent, VSD_STD_ID_NSR03, VSD_STD_ID_LEN))
683                 ret = 1;
684         else if (!memcmp(vsd->stdIdent, VSD_STD_ID_BOOT2, VSD_STD_ID_LEN))
685                 ; /* ret = 0 */
686         else if (!memcmp(vsd->stdIdent, VSD_STD_ID_CDW02, VSD_STD_ID_LEN))
687                 ; /* ret = 0 */
688         else {
689                 /* TEA01 or invalid id : end of volume recognition area */
690                 ret = -1;
691         }
692
693         return ret;
694 }
695
696 /*
697  * Check Volume Structure Descriptors (ECMA 167 2/9.1)
698  * We also check any "CD-ROM Volume Descriptor Set" (ECMA 167 2/8.3.1)
699  * @return   1 if NSR02 or NSR03 found,
700  *          -1 if first sector read error, 0 otherwise
701  */
702 static int udf_check_vsd(struct super_block *sb)
703 {
704         struct volStructDesc *vsd = NULL;
705         loff_t sector = VSD_FIRST_SECTOR_OFFSET;
706         int sectorsize;
707         struct buffer_head *bh = NULL;
708         int nsr = 0;
709         struct udf_sb_info *sbi;
710         loff_t session_offset;
711
712         sbi = UDF_SB(sb);
713         if (sb->s_blocksize < sizeof(struct volStructDesc))
714                 sectorsize = sizeof(struct volStructDesc);
715         else
716                 sectorsize = sb->s_blocksize;
717
718         session_offset = (loff_t)sbi->s_session << sb->s_blocksize_bits;
719         sector += session_offset;
720
721         udf_debug("Starting at sector %u (%lu byte sectors)\n",
722                   (unsigned int)(sector >> sb->s_blocksize_bits),
723                   sb->s_blocksize);
724         /* Process the sequence (if applicable). The hard limit on the sector
725          * offset is arbitrary, hopefully large enough so that all valid UDF
726          * filesystems will be recognised. There is no mention of an upper
727          * bound to the size of the volume recognition area in the standard.
728          *  The limit will prevent the code to read all the sectors of a
729          * specially crafted image (like a bluray disc full of CD001 sectors),
730          * potentially causing minutes or even hours of uninterruptible I/O
731          * activity. This actually happened with uninitialised SSD partitions
732          * (all 0xFF) before the check for the limit and all valid IDs were
733          * added */
734         for (; !nsr && sector < VSD_MAX_SECTOR_OFFSET; sector += sectorsize) {
735                 /* Read a block */
736                 bh = udf_tread(sb, sector >> sb->s_blocksize_bits);
737                 if (!bh)
738                         break;
739
740                 vsd = (struct volStructDesc *)(bh->b_data +
741                                               (sector & (sb->s_blocksize - 1)));
742                 nsr = identify_vsd(vsd);
743                 /* Found NSR or end? */
744                 if (nsr) {
745                         brelse(bh);
746                         break;
747                 }
748                 /*
749                  * Special handling for improperly formatted VRS (e.g., Win10)
750                  * where components are separated by 2048 bytes even though
751                  * sectors are 4K
752                  */
753                 if (sb->s_blocksize == 4096) {
754                         nsr = identify_vsd(vsd + 1);
755                         /* Ignore unknown IDs... */
756                         if (nsr < 0)
757                                 nsr = 0;
758                 }
759                 brelse(bh);
760         }
761
762         if (nsr > 0)
763                 return 1;
764         else if (!bh && sector - session_offset == VSD_FIRST_SECTOR_OFFSET)
765                 return -1;
766         else
767                 return 0;
768 }
769
770 static int udf_verify_domain_identifier(struct super_block *sb,
771                                         struct regid *ident, char *dname)
772 {
773         struct domainIdentSuffix *suffix;
774
775         if (memcmp(ident->ident, UDF_ID_COMPLIANT, strlen(UDF_ID_COMPLIANT))) {
776                 udf_warn(sb, "Not OSTA UDF compliant %s descriptor.\n", dname);
777                 goto force_ro;
778         }
779         if (ident->flags & ENTITYID_FLAGS_DIRTY) {
780                 udf_warn(sb, "Possibly not OSTA UDF compliant %s descriptor.\n",
781                          dname);
782                 goto force_ro;
783         }
784         suffix = (struct domainIdentSuffix *)ident->identSuffix;
785         if ((suffix->domainFlags & DOMAIN_FLAGS_HARD_WRITE_PROTECT) ||
786             (suffix->domainFlags & DOMAIN_FLAGS_SOFT_WRITE_PROTECT)) {
787                 if (!sb_rdonly(sb)) {
788                         udf_warn(sb, "Descriptor for %s marked write protected."
789                                  " Forcing read only mount.\n", dname);
790                 }
791                 goto force_ro;
792         }
793         return 0;
794
795 force_ro:
796         if (!sb_rdonly(sb))
797                 return -EACCES;
798         UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
799         return 0;
800 }
801
802 static int udf_load_fileset(struct super_block *sb, struct fileSetDesc *fset,
803                             struct kernel_lb_addr *root)
804 {
805         int ret;
806
807         ret = udf_verify_domain_identifier(sb, &fset->domainIdent, "file set");
808         if (ret < 0)
809                 return ret;
810
811         *root = lelb_to_cpu(fset->rootDirectoryICB.extLocation);
812         UDF_SB(sb)->s_serial_number = le16_to_cpu(fset->descTag.tagSerialNum);
813
814         udf_debug("Rootdir at block=%u, partition=%u\n",
815                   root->logicalBlockNum, root->partitionReferenceNum);
816         return 0;
817 }
818
819 static int udf_find_fileset(struct super_block *sb,
820                             struct kernel_lb_addr *fileset,
821                             struct kernel_lb_addr *root)
822 {
823         struct buffer_head *bh = NULL;
824         uint16_t ident;
825         int ret;
826
827         if (fileset->logicalBlockNum == 0xFFFFFFFF &&
828             fileset->partitionReferenceNum == 0xFFFF)
829                 return -EINVAL;
830
831         bh = udf_read_ptagged(sb, fileset, 0, &ident);
832         if (!bh)
833                 return -EIO;
834         if (ident != TAG_IDENT_FSD) {
835                 brelse(bh);
836                 return -EINVAL;
837         }
838
839         udf_debug("Fileset at block=%u, partition=%u\n",
840                   fileset->logicalBlockNum, fileset->partitionReferenceNum);
841
842         UDF_SB(sb)->s_partition = fileset->partitionReferenceNum;
843         ret = udf_load_fileset(sb, (struct fileSetDesc *)bh->b_data, root);
844         brelse(bh);
845         return ret;
846 }
847
848 /*
849  * Load primary Volume Descriptor Sequence
850  *
851  * Return <0 on error, 0 on success. -EAGAIN is special meaning next sequence
852  * should be tried.
853  */
854 static int udf_load_pvoldesc(struct super_block *sb, sector_t block)
855 {
856         struct primaryVolDesc *pvoldesc;
857         uint8_t *outstr;
858         struct buffer_head *bh;
859         uint16_t ident;
860         int ret;
861         struct timestamp *ts;
862
863         outstr = kmalloc(128, GFP_NOFS);
864         if (!outstr)
865                 return -ENOMEM;
866
867         bh = udf_read_tagged(sb, block, block, &ident);
868         if (!bh) {
869                 ret = -EAGAIN;
870                 goto out2;
871         }
872
873         if (ident != TAG_IDENT_PVD) {
874                 ret = -EIO;
875                 goto out_bh;
876         }
877
878         pvoldesc = (struct primaryVolDesc *)bh->b_data;
879
880         udf_disk_stamp_to_time(&UDF_SB(sb)->s_record_time,
881                               pvoldesc->recordingDateAndTime);
882         ts = &pvoldesc->recordingDateAndTime;
883         udf_debug("recording time %04u/%02u/%02u %02u:%02u (%x)\n",
884                   le16_to_cpu(ts->year), ts->month, ts->day, ts->hour,
885                   ts->minute, le16_to_cpu(ts->typeAndTimezone));
886
887         ret = udf_dstrCS0toChar(sb, outstr, 31, pvoldesc->volIdent, 32);
888         if (ret < 0) {
889                 strcpy(UDF_SB(sb)->s_volume_ident, "InvalidName");
890                 pr_warn("incorrect volume identification, setting to "
891                         "'InvalidName'\n");
892         } else {
893                 strncpy(UDF_SB(sb)->s_volume_ident, outstr, ret);
894         }
895         udf_debug("volIdent[] = '%s'\n", UDF_SB(sb)->s_volume_ident);
896
897         ret = udf_dstrCS0toChar(sb, outstr, 127, pvoldesc->volSetIdent, 128);
898         if (ret < 0) {
899                 ret = 0;
900                 goto out_bh;
901         }
902         outstr[ret] = 0;
903         udf_debug("volSetIdent[] = '%s'\n", outstr);
904
905         ret = 0;
906 out_bh:
907         brelse(bh);
908 out2:
909         kfree(outstr);
910         return ret;
911 }
912
913 struct inode *udf_find_metadata_inode_efe(struct super_block *sb,
914                                         u32 meta_file_loc, u32 partition_ref)
915 {
916         struct kernel_lb_addr addr;
917         struct inode *metadata_fe;
918
919         addr.logicalBlockNum = meta_file_loc;
920         addr.partitionReferenceNum = partition_ref;
921
922         metadata_fe = udf_iget_special(sb, &addr);
923
924         if (IS_ERR(metadata_fe)) {
925                 udf_warn(sb, "metadata inode efe not found\n");
926                 return metadata_fe;
927         }
928         if (UDF_I(metadata_fe)->i_alloc_type != ICBTAG_FLAG_AD_SHORT) {
929                 udf_warn(sb, "metadata inode efe does not have short allocation descriptors!\n");
930                 iput(metadata_fe);
931                 return ERR_PTR(-EIO);
932         }
933
934         return metadata_fe;
935 }
936
937 static int udf_load_metadata_files(struct super_block *sb, int partition,
938                                    int type1_index)
939 {
940         struct udf_sb_info *sbi = UDF_SB(sb);
941         struct udf_part_map *map;
942         struct udf_meta_data *mdata;
943         struct kernel_lb_addr addr;
944         struct inode *fe;
945
946         map = &sbi->s_partmaps[partition];
947         mdata = &map->s_type_specific.s_metadata;
948         mdata->s_phys_partition_ref = type1_index;
949
950         /* metadata address */
951         udf_debug("Metadata file location: block = %u part = %u\n",
952                   mdata->s_meta_file_loc, mdata->s_phys_partition_ref);
953
954         fe = udf_find_metadata_inode_efe(sb, mdata->s_meta_file_loc,
955                                          mdata->s_phys_partition_ref);
956         if (IS_ERR(fe)) {
957                 /* mirror file entry */
958                 udf_debug("Mirror metadata file location: block = %u part = %u\n",
959                           mdata->s_mirror_file_loc, mdata->s_phys_partition_ref);
960
961                 fe = udf_find_metadata_inode_efe(sb, mdata->s_mirror_file_loc,
962                                                  mdata->s_phys_partition_ref);
963
964                 if (IS_ERR(fe)) {
965                         udf_err(sb, "Both metadata and mirror metadata inode efe can not found\n");
966                         return PTR_ERR(fe);
967                 }
968                 mdata->s_mirror_fe = fe;
969         } else
970                 mdata->s_metadata_fe = fe;
971
972
973         /*
974          * bitmap file entry
975          * Note:
976          * Load only if bitmap file location differs from 0xFFFFFFFF (DCN-5102)
977         */
978         if (mdata->s_bitmap_file_loc != 0xFFFFFFFF) {
979                 addr.logicalBlockNum = mdata->s_bitmap_file_loc;
980                 addr.partitionReferenceNum = mdata->s_phys_partition_ref;
981
982                 udf_debug("Bitmap file location: block = %u part = %u\n",
983                           addr.logicalBlockNum, addr.partitionReferenceNum);
984
985                 fe = udf_iget_special(sb, &addr);
986                 if (IS_ERR(fe)) {
987                         if (sb_rdonly(sb))
988                                 udf_warn(sb, "bitmap inode efe not found but it's ok since the disc is mounted read-only\n");
989                         else {
990                                 udf_err(sb, "bitmap inode efe not found and attempted read-write mount\n");
991                                 return PTR_ERR(fe);
992                         }
993                 } else
994                         mdata->s_bitmap_fe = fe;
995         }
996
997         udf_debug("udf_load_metadata_files Ok\n");
998         return 0;
999 }
1000
1001 int udf_compute_nr_groups(struct super_block *sb, u32 partition)
1002 {
1003         struct udf_part_map *map = &UDF_SB(sb)->s_partmaps[partition];
1004         return DIV_ROUND_UP(map->s_partition_len +
1005                             (sizeof(struct spaceBitmapDesc) << 3),
1006                             sb->s_blocksize * 8);
1007 }
1008
1009 static struct udf_bitmap *udf_sb_alloc_bitmap(struct super_block *sb, u32 index)
1010 {
1011         struct udf_bitmap *bitmap;
1012         int nr_groups = udf_compute_nr_groups(sb, index);
1013
1014         bitmap = kvzalloc(struct_size(bitmap, s_block_bitmap, nr_groups),
1015                           GFP_KERNEL);
1016         if (!bitmap)
1017                 return NULL;
1018
1019         bitmap->s_nr_groups = nr_groups;
1020         return bitmap;
1021 }
1022
1023 static int check_partition_desc(struct super_block *sb,
1024                                 struct partitionDesc *p,
1025                                 struct udf_part_map *map)
1026 {
1027         bool umap, utable, fmap, ftable;
1028         struct partitionHeaderDesc *phd;
1029
1030         switch (le32_to_cpu(p->accessType)) {
1031         case PD_ACCESS_TYPE_READ_ONLY:
1032         case PD_ACCESS_TYPE_WRITE_ONCE:
1033         case PD_ACCESS_TYPE_NONE:
1034                 goto force_ro;
1035         }
1036
1037         /* No Partition Header Descriptor? */
1038         if (strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR02) &&
1039             strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR03))
1040                 goto force_ro;
1041
1042         phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
1043         utable = phd->unallocSpaceTable.extLength;
1044         umap = phd->unallocSpaceBitmap.extLength;
1045         ftable = phd->freedSpaceTable.extLength;
1046         fmap = phd->freedSpaceBitmap.extLength;
1047
1048         /* No allocation info? */
1049         if (!utable && !umap && !ftable && !fmap)
1050                 goto force_ro;
1051
1052         /* We don't support blocks that require erasing before overwrite */
1053         if (ftable || fmap)
1054                 goto force_ro;
1055         /* UDF 2.60: 2.3.3 - no mixing of tables & bitmaps, no VAT. */
1056         if (utable && umap)
1057                 goto force_ro;
1058
1059         if (map->s_partition_type == UDF_VIRTUAL_MAP15 ||
1060             map->s_partition_type == UDF_VIRTUAL_MAP20 ||
1061             map->s_partition_type == UDF_METADATA_MAP25)
1062                 goto force_ro;
1063
1064         return 0;
1065 force_ro:
1066         if (!sb_rdonly(sb))
1067                 return -EACCES;
1068         UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
1069         return 0;
1070 }
1071
1072 static int udf_fill_partdesc_info(struct super_block *sb,
1073                 struct partitionDesc *p, int p_index)
1074 {
1075         struct udf_part_map *map;
1076         struct udf_sb_info *sbi = UDF_SB(sb);
1077         struct partitionHeaderDesc *phd;
1078         int err;
1079
1080         map = &sbi->s_partmaps[p_index];
1081
1082         map->s_partition_len = le32_to_cpu(p->partitionLength); /* blocks */
1083         map->s_partition_root = le32_to_cpu(p->partitionStartingLocation);
1084
1085         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_READ_ONLY))
1086                 map->s_partition_flags |= UDF_PART_FLAG_READ_ONLY;
1087         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_WRITE_ONCE))
1088                 map->s_partition_flags |= UDF_PART_FLAG_WRITE_ONCE;
1089         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_REWRITABLE))
1090                 map->s_partition_flags |= UDF_PART_FLAG_REWRITABLE;
1091         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_OVERWRITABLE))
1092                 map->s_partition_flags |= UDF_PART_FLAG_OVERWRITABLE;
1093
1094         udf_debug("Partition (%d type %x) starts at physical %u, block length %u\n",
1095                   p_index, map->s_partition_type,
1096                   map->s_partition_root, map->s_partition_len);
1097
1098         err = check_partition_desc(sb, p, map);
1099         if (err)
1100                 return err;
1101
1102         /*
1103          * Skip loading allocation info it we cannot ever write to the fs.
1104          * This is a correctness thing as we may have decided to force ro mount
1105          * to avoid allocation info we don't support.
1106          */
1107         if (UDF_QUERY_FLAG(sb, UDF_FLAG_RW_INCOMPAT))
1108                 return 0;
1109
1110         phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
1111         if (phd->unallocSpaceTable.extLength) {
1112                 struct kernel_lb_addr loc = {
1113                         .logicalBlockNum = le32_to_cpu(
1114                                 phd->unallocSpaceTable.extPosition),
1115                         .partitionReferenceNum = p_index,
1116                 };
1117                 struct inode *inode;
1118
1119                 inode = udf_iget_special(sb, &loc);
1120                 if (IS_ERR(inode)) {
1121                         udf_debug("cannot load unallocSpaceTable (part %d)\n",
1122                                   p_index);
1123                         return PTR_ERR(inode);
1124                 }
1125                 map->s_uspace.s_table = inode;
1126                 map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_TABLE;
1127                 udf_debug("unallocSpaceTable (part %d) @ %lu\n",
1128                           p_index, map->s_uspace.s_table->i_ino);
1129         }
1130
1131         if (phd->unallocSpaceBitmap.extLength) {
1132                 struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index);
1133                 if (!bitmap)
1134                         return -ENOMEM;
1135                 map->s_uspace.s_bitmap = bitmap;
1136                 bitmap->s_extPosition = le32_to_cpu(
1137                                 phd->unallocSpaceBitmap.extPosition);
1138                 map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_BITMAP;
1139                 udf_debug("unallocSpaceBitmap (part %d) @ %u\n",
1140                           p_index, bitmap->s_extPosition);
1141         }
1142
1143         return 0;
1144 }
1145
1146 static void udf_find_vat_block(struct super_block *sb, int p_index,
1147                                int type1_index, sector_t start_block)
1148 {
1149         struct udf_sb_info *sbi = UDF_SB(sb);
1150         struct udf_part_map *map = &sbi->s_partmaps[p_index];
1151         sector_t vat_block;
1152         struct kernel_lb_addr ino;
1153         struct inode *inode;
1154
1155         /*
1156          * VAT file entry is in the last recorded block. Some broken disks have
1157          * it a few blocks before so try a bit harder...
1158          */
1159         ino.partitionReferenceNum = type1_index;
1160         for (vat_block = start_block;
1161              vat_block >= map->s_partition_root &&
1162              vat_block >= start_block - 3; vat_block--) {
1163                 ino.logicalBlockNum = vat_block - map->s_partition_root;
1164                 inode = udf_iget_special(sb, &ino);
1165                 if (!IS_ERR(inode)) {
1166                         sbi->s_vat_inode = inode;
1167                         break;
1168                 }
1169         }
1170 }
1171
1172 static int udf_load_vat(struct super_block *sb, int p_index, int type1_index)
1173 {
1174         struct udf_sb_info *sbi = UDF_SB(sb);
1175         struct udf_part_map *map = &sbi->s_partmaps[p_index];
1176         struct buffer_head *bh = NULL;
1177         struct udf_inode_info *vati;
1178         uint32_t pos;
1179         struct virtualAllocationTable20 *vat20;
1180         sector_t blocks = i_size_read(sb->s_bdev->bd_inode) >>
1181                           sb->s_blocksize_bits;
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) >=
1844             i_size_read(sb->s_bdev->bd_inode) >> sb->s_blocksize_bits)
1845                 return -EAGAIN;
1846
1847         bh = udf_read_tagged(sb, block, block, &ident);
1848         if (!bh)
1849                 return -EAGAIN;
1850         if (ident != TAG_IDENT_AVDP) {
1851                 brelse(bh);
1852                 return -EAGAIN;
1853         }
1854         ret = udf_load_sequence(sb, bh, fileset);
1855         brelse(bh);
1856         return ret;
1857 }
1858
1859 /*
1860  * Search for an anchor volume descriptor pointer.
1861  *
1862  * Returns < 0 on error, 0 on success. -EAGAIN is special - try next set
1863  * of anchors.
1864  */
1865 static int udf_scan_anchors(struct super_block *sb, sector_t *lastblock,
1866                             struct kernel_lb_addr *fileset)
1867 {
1868         sector_t last[6];
1869         int i;
1870         struct udf_sb_info *sbi = UDF_SB(sb);
1871         int last_count = 0;
1872         int ret;
1873
1874         /* First try user provided anchor */
1875         if (sbi->s_anchor) {
1876                 ret = udf_check_anchor_block(sb, sbi->s_anchor, fileset);
1877                 if (ret != -EAGAIN)
1878                         return ret;
1879         }
1880         /*
1881          * according to spec, anchor is in either:
1882          *     block 256
1883          *     lastblock-256
1884          *     lastblock
1885          *  however, if the disc isn't closed, it could be 512.
1886          */
1887         ret = udf_check_anchor_block(sb, sbi->s_session + 256, fileset);
1888         if (ret != -EAGAIN)
1889                 return ret;
1890         /*
1891          * The trouble is which block is the last one. Drives often misreport
1892          * this so we try various possibilities.
1893          */
1894         last[last_count++] = *lastblock;
1895         if (*lastblock >= 1)
1896                 last[last_count++] = *lastblock - 1;
1897         last[last_count++] = *lastblock + 1;
1898         if (*lastblock >= 2)
1899                 last[last_count++] = *lastblock - 2;
1900         if (*lastblock >= 150)
1901                 last[last_count++] = *lastblock - 150;
1902         if (*lastblock >= 152)
1903                 last[last_count++] = *lastblock - 152;
1904
1905         for (i = 0; i < last_count; i++) {
1906                 if (last[i] >= i_size_read(sb->s_bdev->bd_inode) >>
1907                                 sb->s_blocksize_bits)
1908                         continue;
1909                 ret = udf_check_anchor_block(sb, last[i], fileset);
1910                 if (ret != -EAGAIN) {
1911                         if (!ret)
1912                                 *lastblock = last[i];
1913                         return ret;
1914                 }
1915                 if (last[i] < 256)
1916                         continue;
1917                 ret = udf_check_anchor_block(sb, last[i] - 256, fileset);
1918                 if (ret != -EAGAIN) {
1919                         if (!ret)
1920                                 *lastblock = last[i];
1921                         return ret;
1922                 }
1923         }
1924
1925         /* Finally try block 512 in case media is open */
1926         return udf_check_anchor_block(sb, sbi->s_session + 512, fileset);
1927 }
1928
1929 /*
1930  * Find an anchor volume descriptor and load Volume Descriptor Sequence from
1931  * area specified by it. The function expects sbi->s_lastblock to be the last
1932  * block on the media.
1933  *
1934  * Return <0 on error, 0 if anchor found. -EAGAIN is special meaning anchor
1935  * was not found.
1936  */
1937 static int udf_find_anchor(struct super_block *sb,
1938                            struct kernel_lb_addr *fileset)
1939 {
1940         struct udf_sb_info *sbi = UDF_SB(sb);
1941         sector_t lastblock = sbi->s_last_block;
1942         int ret;
1943
1944         ret = udf_scan_anchors(sb, &lastblock, fileset);
1945         if (ret != -EAGAIN)
1946                 goto out;
1947
1948         /* No anchor found? Try VARCONV conversion of block numbers */
1949         UDF_SET_FLAG(sb, UDF_FLAG_VARCONV);
1950         lastblock = udf_variable_to_fixed(sbi->s_last_block);
1951         /* Firstly, we try to not convert number of the last block */
1952         ret = udf_scan_anchors(sb, &lastblock, fileset);
1953         if (ret != -EAGAIN)
1954                 goto out;
1955
1956         lastblock = sbi->s_last_block;
1957         /* Secondly, we try with converted number of the last block */
1958         ret = udf_scan_anchors(sb, &lastblock, fileset);
1959         if (ret < 0) {
1960                 /* VARCONV didn't help. Clear it. */
1961                 UDF_CLEAR_FLAG(sb, UDF_FLAG_VARCONV);
1962         }
1963 out:
1964         if (ret == 0)
1965                 sbi->s_last_block = lastblock;
1966         return ret;
1967 }
1968
1969 /*
1970  * Check Volume Structure Descriptor, find Anchor block and load Volume
1971  * Descriptor Sequence.
1972  *
1973  * Returns < 0 on error, 0 on success. -EAGAIN is special meaning anchor
1974  * block was not found.
1975  */
1976 static int udf_load_vrs(struct super_block *sb, struct udf_options *uopt,
1977                         int silent, struct kernel_lb_addr *fileset)
1978 {
1979         struct udf_sb_info *sbi = UDF_SB(sb);
1980         int nsr = 0;
1981         int ret;
1982
1983         if (!sb_set_blocksize(sb, uopt->blocksize)) {
1984                 if (!silent)
1985                         udf_warn(sb, "Bad block size\n");
1986                 return -EINVAL;
1987         }
1988         sbi->s_last_block = uopt->lastblock;
1989         if (!uopt->novrs) {
1990                 /* Check that it is NSR02 compliant */
1991                 nsr = udf_check_vsd(sb);
1992                 if (!nsr) {
1993                         if (!silent)
1994                                 udf_warn(sb, "No VRS found\n");
1995                         return -EINVAL;
1996                 }
1997                 if (nsr == -1)
1998                         udf_debug("Failed to read sector at offset %d. "
1999                                   "Assuming open disc. Skipping validity "
2000                                   "check\n", VSD_FIRST_SECTOR_OFFSET);
2001                 if (!sbi->s_last_block)
2002                         sbi->s_last_block = udf_get_last_block(sb);
2003         } else {
2004                 udf_debug("Validity check skipped because of novrs option\n");
2005         }
2006
2007         /* Look for anchor block and load Volume Descriptor Sequence */
2008         sbi->s_anchor = uopt->anchor;
2009         ret = udf_find_anchor(sb, fileset);
2010         if (ret < 0) {
2011                 if (!silent && ret == -EAGAIN)
2012                         udf_warn(sb, "No anchor found\n");
2013                 return ret;
2014         }
2015         return 0;
2016 }
2017
2018 static void udf_finalize_lvid(struct logicalVolIntegrityDesc *lvid)
2019 {
2020         struct timespec64 ts;
2021
2022         ktime_get_real_ts64(&ts);
2023         udf_time_to_disk_stamp(&lvid->recordingDateAndTime, ts);
2024         lvid->descTag.descCRC = cpu_to_le16(
2025                 crc_itu_t(0, (char *)lvid + sizeof(struct tag),
2026                         le16_to_cpu(lvid->descTag.descCRCLength)));
2027         lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag);
2028 }
2029
2030 static void udf_open_lvid(struct super_block *sb)
2031 {
2032         struct udf_sb_info *sbi = UDF_SB(sb);
2033         struct buffer_head *bh = sbi->s_lvid_bh;
2034         struct logicalVolIntegrityDesc *lvid;
2035         struct logicalVolIntegrityDescImpUse *lvidiu;
2036
2037         if (!bh)
2038                 return;
2039         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2040         lvidiu = udf_sb_lvidiu(sb);
2041         if (!lvidiu)
2042                 return;
2043
2044         mutex_lock(&sbi->s_alloc_mutex);
2045         lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
2046         lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
2047         if (le32_to_cpu(lvid->integrityType) == LVID_INTEGRITY_TYPE_CLOSE)
2048                 lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_OPEN);
2049         else
2050                 UDF_SET_FLAG(sb, UDF_FLAG_INCONSISTENT);
2051
2052         udf_finalize_lvid(lvid);
2053         mark_buffer_dirty(bh);
2054         sbi->s_lvid_dirty = 0;
2055         mutex_unlock(&sbi->s_alloc_mutex);
2056         /* Make opening of filesystem visible on the media immediately */
2057         sync_dirty_buffer(bh);
2058 }
2059
2060 static void udf_close_lvid(struct super_block *sb)
2061 {
2062         struct udf_sb_info *sbi = UDF_SB(sb);
2063         struct buffer_head *bh = sbi->s_lvid_bh;
2064         struct logicalVolIntegrityDesc *lvid;
2065         struct logicalVolIntegrityDescImpUse *lvidiu;
2066
2067         if (!bh)
2068                 return;
2069         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2070         lvidiu = udf_sb_lvidiu(sb);
2071         if (!lvidiu)
2072                 return;
2073
2074         mutex_lock(&sbi->s_alloc_mutex);
2075         lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
2076         lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
2077         if (UDF_MAX_WRITE_VERSION > le16_to_cpu(lvidiu->maxUDFWriteRev))
2078                 lvidiu->maxUDFWriteRev = cpu_to_le16(UDF_MAX_WRITE_VERSION);
2079         if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFReadRev))
2080                 lvidiu->minUDFReadRev = cpu_to_le16(sbi->s_udfrev);
2081         if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFWriteRev))
2082                 lvidiu->minUDFWriteRev = cpu_to_le16(sbi->s_udfrev);
2083         if (!UDF_QUERY_FLAG(sb, UDF_FLAG_INCONSISTENT))
2084                 lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_CLOSE);
2085
2086         /*
2087          * We set buffer uptodate unconditionally here to avoid spurious
2088          * warnings from mark_buffer_dirty() when previous EIO has marked
2089          * the buffer as !uptodate
2090          */
2091         set_buffer_uptodate(bh);
2092         udf_finalize_lvid(lvid);
2093         mark_buffer_dirty(bh);
2094         sbi->s_lvid_dirty = 0;
2095         mutex_unlock(&sbi->s_alloc_mutex);
2096         /* Make closing of filesystem visible on the media immediately */
2097         sync_dirty_buffer(bh);
2098 }
2099
2100 u64 lvid_get_unique_id(struct super_block *sb)
2101 {
2102         struct buffer_head *bh;
2103         struct udf_sb_info *sbi = UDF_SB(sb);
2104         struct logicalVolIntegrityDesc *lvid;
2105         struct logicalVolHeaderDesc *lvhd;
2106         u64 uniqueID;
2107         u64 ret;
2108
2109         bh = sbi->s_lvid_bh;
2110         if (!bh)
2111                 return 0;
2112
2113         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2114         lvhd = (struct logicalVolHeaderDesc *)lvid->logicalVolContentsUse;
2115
2116         mutex_lock(&sbi->s_alloc_mutex);
2117         ret = uniqueID = le64_to_cpu(lvhd->uniqueID);
2118         if (!(++uniqueID & 0xFFFFFFFF))
2119                 uniqueID += 16;
2120         lvhd->uniqueID = cpu_to_le64(uniqueID);
2121         udf_updated_lvid(sb);
2122         mutex_unlock(&sbi->s_alloc_mutex);
2123
2124         return ret;
2125 }
2126
2127 static int udf_fill_super(struct super_block *sb, void *options, int silent)
2128 {
2129         int ret = -EINVAL;
2130         struct inode *inode = NULL;
2131         struct udf_options uopt;
2132         struct kernel_lb_addr rootdir, fileset;
2133         struct udf_sb_info *sbi;
2134         bool lvid_open = false;
2135
2136         uopt.flags = (1 << UDF_FLAG_USE_AD_IN_ICB) | (1 << UDF_FLAG_STRICT);
2137         /* By default we'll use overflow[ug]id when UDF inode [ug]id == -1 */
2138         uopt.uid = make_kuid(current_user_ns(), overflowuid);
2139         uopt.gid = make_kgid(current_user_ns(), overflowgid);
2140         uopt.umask = 0;
2141         uopt.fmode = UDF_INVALID_MODE;
2142         uopt.dmode = UDF_INVALID_MODE;
2143         uopt.nls_map = NULL;
2144
2145         sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
2146         if (!sbi)
2147                 return -ENOMEM;
2148
2149         sb->s_fs_info = sbi;
2150
2151         mutex_init(&sbi->s_alloc_mutex);
2152
2153         if (!udf_parse_options((char *)options, &uopt, false))
2154                 goto parse_options_failure;
2155
2156         fileset.logicalBlockNum = 0xFFFFFFFF;
2157         fileset.partitionReferenceNum = 0xFFFF;
2158
2159         sbi->s_flags = uopt.flags;
2160         sbi->s_uid = uopt.uid;
2161         sbi->s_gid = uopt.gid;
2162         sbi->s_umask = uopt.umask;
2163         sbi->s_fmode = uopt.fmode;
2164         sbi->s_dmode = uopt.dmode;
2165         sbi->s_nls_map = uopt.nls_map;
2166         rwlock_init(&sbi->s_cred_lock);
2167
2168         if (uopt.session == 0xFFFFFFFF)
2169                 sbi->s_session = udf_get_last_session(sb);
2170         else
2171                 sbi->s_session = uopt.session;
2172
2173         udf_debug("Multi-session=%d\n", sbi->s_session);
2174
2175         /* Fill in the rest of the superblock */
2176         sb->s_op = &udf_sb_ops;
2177         sb->s_export_op = &udf_export_ops;
2178
2179         sb->s_magic = UDF_SUPER_MAGIC;
2180         sb->s_time_gran = 1000;
2181
2182         if (uopt.flags & (1 << UDF_FLAG_BLOCKSIZE_SET)) {
2183                 ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2184         } else {
2185                 uopt.blocksize = bdev_logical_block_size(sb->s_bdev);
2186                 while (uopt.blocksize <= 4096) {
2187                         ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2188                         if (ret < 0) {
2189                                 if (!silent && ret != -EACCES) {
2190                                         pr_notice("Scanning with blocksize %u failed\n",
2191                                                   uopt.blocksize);
2192                                 }
2193                                 brelse(sbi->s_lvid_bh);
2194                                 sbi->s_lvid_bh = NULL;
2195                                 /*
2196                                  * EACCES is special - we want to propagate to
2197                                  * upper layers that we cannot handle RW mount.
2198                                  */
2199                                 if (ret == -EACCES)
2200                                         break;
2201                         } else
2202                                 break;
2203
2204                         uopt.blocksize <<= 1;
2205                 }
2206         }
2207         if (ret < 0) {
2208                 if (ret == -EAGAIN) {
2209                         udf_warn(sb, "No partition found (1)\n");
2210                         ret = -EINVAL;
2211                 }
2212                 goto error_out;
2213         }
2214
2215         udf_debug("Lastblock=%u\n", sbi->s_last_block);
2216
2217         if (sbi->s_lvid_bh) {
2218                 struct logicalVolIntegrityDescImpUse *lvidiu =
2219                                                         udf_sb_lvidiu(sb);
2220                 uint16_t minUDFReadRev;
2221                 uint16_t minUDFWriteRev;
2222
2223                 if (!lvidiu) {
2224                         ret = -EINVAL;
2225                         goto error_out;
2226                 }
2227                 minUDFReadRev = le16_to_cpu(lvidiu->minUDFReadRev);
2228                 minUDFWriteRev = le16_to_cpu(lvidiu->minUDFWriteRev);
2229                 if (minUDFReadRev > UDF_MAX_READ_VERSION) {
2230                         udf_err(sb, "minUDFReadRev=%x (max is %x)\n",
2231                                 minUDFReadRev,
2232                                 UDF_MAX_READ_VERSION);
2233                         ret = -EINVAL;
2234                         goto error_out;
2235                 } else if (minUDFWriteRev > UDF_MAX_WRITE_VERSION) {
2236                         if (!sb_rdonly(sb)) {
2237                                 ret = -EACCES;
2238                                 goto error_out;
2239                         }
2240                         UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
2241                 }
2242
2243                 sbi->s_udfrev = minUDFWriteRev;
2244
2245                 if (minUDFReadRev >= UDF_VERS_USE_EXTENDED_FE)
2246                         UDF_SET_FLAG(sb, UDF_FLAG_USE_EXTENDED_FE);
2247                 if (minUDFReadRev >= UDF_VERS_USE_STREAMS)
2248                         UDF_SET_FLAG(sb, UDF_FLAG_USE_STREAMS);
2249         }
2250
2251         if (!sbi->s_partitions) {
2252                 udf_warn(sb, "No partition found (2)\n");
2253                 ret = -EINVAL;
2254                 goto error_out;
2255         }
2256
2257         if (sbi->s_partmaps[sbi->s_partition].s_partition_flags &
2258                         UDF_PART_FLAG_READ_ONLY) {
2259                 if (!sb_rdonly(sb)) {
2260                         ret = -EACCES;
2261                         goto error_out;
2262                 }
2263                 UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
2264         }
2265
2266         ret = udf_find_fileset(sb, &fileset, &rootdir);
2267         if (ret < 0) {
2268                 udf_warn(sb, "No fileset found\n");
2269                 goto error_out;
2270         }
2271
2272         if (!silent) {
2273                 struct timestamp ts;
2274                 udf_time_to_disk_stamp(&ts, sbi->s_record_time);
2275                 udf_info("Mounting volume '%s', timestamp %04u/%02u/%02u %02u:%02u (%x)\n",
2276                          sbi->s_volume_ident,
2277                          le16_to_cpu(ts.year), ts.month, ts.day,
2278                          ts.hour, ts.minute, le16_to_cpu(ts.typeAndTimezone));
2279         }
2280         if (!sb_rdonly(sb)) {
2281                 udf_open_lvid(sb);
2282                 lvid_open = true;
2283         }
2284
2285         /* Assign the root inode */
2286         /* assign inodes by physical block number */
2287         /* perhaps it's not extensible enough, but for now ... */
2288         inode = udf_iget(sb, &rootdir);
2289         if (IS_ERR(inode)) {
2290                 udf_err(sb, "Error in udf_iget, block=%u, partition=%u\n",
2291                        rootdir.logicalBlockNum, rootdir.partitionReferenceNum);
2292                 ret = PTR_ERR(inode);
2293                 goto error_out;
2294         }
2295
2296         /* Allocate a dentry for the root inode */
2297         sb->s_root = d_make_root(inode);
2298         if (!sb->s_root) {
2299                 udf_err(sb, "Couldn't allocate root dentry\n");
2300                 ret = -ENOMEM;
2301                 goto error_out;
2302         }
2303         sb->s_maxbytes = MAX_LFS_FILESIZE;
2304         sb->s_max_links = UDF_MAX_LINKS;
2305         return 0;
2306
2307 error_out:
2308         iput(sbi->s_vat_inode);
2309 parse_options_failure:
2310         unload_nls(uopt.nls_map);
2311         if (lvid_open)
2312                 udf_close_lvid(sb);
2313         brelse(sbi->s_lvid_bh);
2314         udf_sb_free_partitions(sb);
2315         kfree(sbi);
2316         sb->s_fs_info = NULL;
2317
2318         return ret;
2319 }
2320
2321 void _udf_err(struct super_block *sb, const char *function,
2322               const char *fmt, ...)
2323 {
2324         struct va_format vaf;
2325         va_list args;
2326
2327         va_start(args, fmt);
2328
2329         vaf.fmt = fmt;
2330         vaf.va = &args;
2331
2332         pr_err("error (device %s): %s: %pV", sb->s_id, function, &vaf);
2333
2334         va_end(args);
2335 }
2336
2337 void _udf_warn(struct super_block *sb, const char *function,
2338                const char *fmt, ...)
2339 {
2340         struct va_format vaf;
2341         va_list args;
2342
2343         va_start(args, fmt);
2344
2345         vaf.fmt = fmt;
2346         vaf.va = &args;
2347
2348         pr_warn("warning (device %s): %s: %pV", sb->s_id, function, &vaf);
2349
2350         va_end(args);
2351 }
2352
2353 static void udf_put_super(struct super_block *sb)
2354 {
2355         struct udf_sb_info *sbi;
2356
2357         sbi = UDF_SB(sb);
2358
2359         iput(sbi->s_vat_inode);
2360         unload_nls(sbi->s_nls_map);
2361         if (!sb_rdonly(sb))
2362                 udf_close_lvid(sb);
2363         brelse(sbi->s_lvid_bh);
2364         udf_sb_free_partitions(sb);
2365         mutex_destroy(&sbi->s_alloc_mutex);
2366         kfree(sb->s_fs_info);
2367         sb->s_fs_info = NULL;
2368 }
2369
2370 static int udf_sync_fs(struct super_block *sb, int wait)
2371 {
2372         struct udf_sb_info *sbi = UDF_SB(sb);
2373
2374         mutex_lock(&sbi->s_alloc_mutex);
2375         if (sbi->s_lvid_dirty) {
2376                 struct buffer_head *bh = sbi->s_lvid_bh;
2377                 struct logicalVolIntegrityDesc *lvid;
2378
2379                 lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2380                 udf_finalize_lvid(lvid);
2381
2382                 /*
2383                  * Blockdevice will be synced later so we don't have to submit
2384                  * the buffer for IO
2385                  */
2386                 mark_buffer_dirty(bh);
2387                 sbi->s_lvid_dirty = 0;
2388         }
2389         mutex_unlock(&sbi->s_alloc_mutex);
2390
2391         return 0;
2392 }
2393
2394 static int udf_statfs(struct dentry *dentry, struct kstatfs *buf)
2395 {
2396         struct super_block *sb = dentry->d_sb;
2397         struct udf_sb_info *sbi = UDF_SB(sb);
2398         struct logicalVolIntegrityDescImpUse *lvidiu;
2399         u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
2400
2401         lvidiu = udf_sb_lvidiu(sb);
2402         buf->f_type = UDF_SUPER_MAGIC;
2403         buf->f_bsize = sb->s_blocksize;
2404         buf->f_blocks = sbi->s_partmaps[sbi->s_partition].s_partition_len;
2405         buf->f_bfree = udf_count_free(sb);
2406         buf->f_bavail = buf->f_bfree;
2407         /*
2408          * Let's pretend each free block is also a free 'inode' since UDF does
2409          * not have separate preallocated table of inodes.
2410          */
2411         buf->f_files = (lvidiu != NULL ? (le32_to_cpu(lvidiu->numFiles) +
2412                                           le32_to_cpu(lvidiu->numDirs)) : 0)
2413                         + buf->f_bfree;
2414         buf->f_ffree = buf->f_bfree;
2415         buf->f_namelen = UDF_NAME_LEN;
2416         buf->f_fsid = u64_to_fsid(id);
2417
2418         return 0;
2419 }
2420
2421 static unsigned int udf_count_free_bitmap(struct super_block *sb,
2422                                           struct udf_bitmap *bitmap)
2423 {
2424         struct buffer_head *bh = NULL;
2425         unsigned int accum = 0;
2426         int index;
2427         udf_pblk_t block = 0, newblock;
2428         struct kernel_lb_addr loc;
2429         uint32_t bytes;
2430         uint8_t *ptr;
2431         uint16_t ident;
2432         struct spaceBitmapDesc *bm;
2433
2434         loc.logicalBlockNum = bitmap->s_extPosition;
2435         loc.partitionReferenceNum = UDF_SB(sb)->s_partition;
2436         bh = udf_read_ptagged(sb, &loc, 0, &ident);
2437
2438         if (!bh) {
2439                 udf_err(sb, "udf_count_free failed\n");
2440                 goto out;
2441         } else if (ident != TAG_IDENT_SBD) {
2442                 brelse(bh);
2443                 udf_err(sb, "udf_count_free failed\n");
2444                 goto out;
2445         }
2446
2447         bm = (struct spaceBitmapDesc *)bh->b_data;
2448         bytes = le32_to_cpu(bm->numOfBytes);
2449         index = sizeof(struct spaceBitmapDesc); /* offset in first block only */
2450         ptr = (uint8_t *)bh->b_data;
2451
2452         while (bytes > 0) {
2453                 u32 cur_bytes = min_t(u32, bytes, sb->s_blocksize - index);
2454                 accum += bitmap_weight((const unsigned long *)(ptr + index),
2455                                         cur_bytes * 8);
2456                 bytes -= cur_bytes;
2457                 if (bytes) {
2458                         brelse(bh);
2459                         newblock = udf_get_lb_pblock(sb, &loc, ++block);
2460                         bh = udf_tread(sb, newblock);
2461                         if (!bh) {
2462                                 udf_debug("read failed\n");
2463                                 goto out;
2464                         }
2465                         index = 0;
2466                         ptr = (uint8_t *)bh->b_data;
2467                 }
2468         }
2469         brelse(bh);
2470 out:
2471         return accum;
2472 }
2473
2474 static unsigned int udf_count_free_table(struct super_block *sb,
2475                                          struct inode *table)
2476 {
2477         unsigned int accum = 0;
2478         uint32_t elen;
2479         struct kernel_lb_addr eloc;
2480         int8_t etype;
2481         struct extent_position epos;
2482
2483         mutex_lock(&UDF_SB(sb)->s_alloc_mutex);
2484         epos.block = UDF_I(table)->i_location;
2485         epos.offset = sizeof(struct unallocSpaceEntry);
2486         epos.bh = NULL;
2487
2488         while ((etype = udf_next_aext(table, &epos, &eloc, &elen, 1)) != -1)
2489                 accum += (elen >> table->i_sb->s_blocksize_bits);
2490
2491         brelse(epos.bh);
2492         mutex_unlock(&UDF_SB(sb)->s_alloc_mutex);
2493
2494         return accum;
2495 }
2496
2497 static unsigned int udf_count_free(struct super_block *sb)
2498 {
2499         unsigned int accum = 0;
2500         struct udf_sb_info *sbi = UDF_SB(sb);
2501         struct udf_part_map *map;
2502         unsigned int part = sbi->s_partition;
2503         int ptype = sbi->s_partmaps[part].s_partition_type;
2504
2505         if (ptype == UDF_METADATA_MAP25) {
2506                 part = sbi->s_partmaps[part].s_type_specific.s_metadata.
2507                                                         s_phys_partition_ref;
2508         } else if (ptype == UDF_VIRTUAL_MAP15 || ptype == UDF_VIRTUAL_MAP20) {
2509                 /*
2510                  * Filesystems with VAT are append-only and we cannot write to
2511                  * them. Let's just report 0 here.
2512                  */
2513                 return 0;
2514         }
2515
2516         if (sbi->s_lvid_bh) {
2517                 struct logicalVolIntegrityDesc *lvid =
2518                         (struct logicalVolIntegrityDesc *)
2519                         sbi->s_lvid_bh->b_data;
2520                 if (le32_to_cpu(lvid->numOfPartitions) > part) {
2521                         accum = le32_to_cpu(
2522                                         lvid->freeSpaceTable[part]);
2523                         if (accum == 0xFFFFFFFF)
2524                                 accum = 0;
2525                 }
2526         }
2527
2528         if (accum)
2529                 return accum;
2530
2531         map = &sbi->s_partmaps[part];
2532         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) {
2533                 accum += udf_count_free_bitmap(sb,
2534                                                map->s_uspace.s_bitmap);
2535         }
2536         if (accum)
2537                 return accum;
2538
2539         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) {
2540                 accum += udf_count_free_table(sb,
2541                                               map->s_uspace.s_table);
2542         }
2543         return accum;
2544 }
2545
2546 MODULE_AUTHOR("Ben Fennema");
2547 MODULE_DESCRIPTION("Universal Disk Format Filesystem");
2548 MODULE_LICENSE("GPL");
2549 module_init(init_udf_fs)
2550 module_exit(exit_udf_fs)