GNU Linux-libre 5.4.257-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  *    http://www.ecma.ch/
15  *    http://www.iso.org/
16  *
17  * COPYRIGHT
18  *  This file is distributed under the terms of the GNU General Public
19  *  License (GPL). Copies of the GPL can be obtained from:
20  *    ftp://prep.ai.mit.edu/pub/gnu/GPL
21  *  Each contributing author retains all rights to their own work.
22  *
23  *  (C) 1998 Dave Boynton
24  *  (C) 1998-2004 Ben Fennema
25  *  (C) 2000 Stelias Computing Inc
26  *
27  * HISTORY
28  *
29  *  09/24/98 dgb  changed to allow compiling outside of kernel, and
30  *                added some debugging.
31  *  10/01/98 dgb  updated to allow (some) possibility of compiling w/2.0.34
32  *  10/16/98      attempting some multi-session support
33  *  10/17/98      added freespace count for "df"
34  *  11/11/98 gr   added novrs option
35  *  11/26/98 dgb  added fileset,anchor mount options
36  *  12/06/98 blf  really hosed things royally. vat/sparing support. sequenced
37  *                vol descs. rewrote option handling based on isofs
38  *  12/20/98      find the free space bitmap (if it exists)
39  */
40
41 #include "udfdecl.h"
42
43 #include <linux/blkdev.h>
44 #include <linux/slab.h>
45 #include <linux/kernel.h>
46 #include <linux/module.h>
47 #include <linux/parser.h>
48 #include <linux/stat.h>
49 #include <linux/cdrom.h>
50 #include <linux/nls.h>
51 #include <linux/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_ext.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 domainEntityIDSuffix *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 & (1 << 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 domainEntityIDSuffix *)ident->identSuffix;
785         if (suffix->flags & (1 << ENTITYIDSUFFIX_FLAGS_HARDWRITEPROTECT) ||
786             suffix->flags & (1 << ENTITYIDSUFFIX_FLAGS_SOFTWRITEPROTECT)) {
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 = -ENOMEM;
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;
1013         int size;
1014
1015         nr_groups = udf_compute_nr_groups(sb, index);
1016         size = sizeof(struct udf_bitmap) +
1017                 (sizeof(struct buffer_head *) * nr_groups);
1018
1019         if (size <= PAGE_SIZE)
1020                 bitmap = kzalloc(size, GFP_KERNEL);
1021         else
1022                 bitmap = vzalloc(size); /* TODO: get rid of vzalloc */
1023
1024         if (!bitmap)
1025                 return NULL;
1026
1027         bitmap->s_nr_groups = nr_groups;
1028         return bitmap;
1029 }
1030
1031 static int check_partition_desc(struct super_block *sb,
1032                                 struct partitionDesc *p,
1033                                 struct udf_part_map *map)
1034 {
1035         bool umap, utable, fmap, ftable;
1036         struct partitionHeaderDesc *phd;
1037
1038         switch (le32_to_cpu(p->accessType)) {
1039         case PD_ACCESS_TYPE_READ_ONLY:
1040         case PD_ACCESS_TYPE_WRITE_ONCE:
1041         case PD_ACCESS_TYPE_NONE:
1042                 goto force_ro;
1043         }
1044
1045         /* No Partition Header Descriptor? */
1046         if (strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR02) &&
1047             strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR03))
1048                 goto force_ro;
1049
1050         phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
1051         utable = phd->unallocSpaceTable.extLength;
1052         umap = phd->unallocSpaceBitmap.extLength;
1053         ftable = phd->freedSpaceTable.extLength;
1054         fmap = phd->freedSpaceBitmap.extLength;
1055
1056         /* No allocation info? */
1057         if (!utable && !umap && !ftable && !fmap)
1058                 goto force_ro;
1059
1060         /* We don't support blocks that require erasing before overwrite */
1061         if (ftable || fmap)
1062                 goto force_ro;
1063         /* UDF 2.60: 2.3.3 - no mixing of tables & bitmaps, no VAT. */
1064         if (utable && umap)
1065                 goto force_ro;
1066
1067         if (map->s_partition_type == UDF_VIRTUAL_MAP15 ||
1068             map->s_partition_type == UDF_VIRTUAL_MAP20)
1069                 goto force_ro;
1070
1071         return 0;
1072 force_ro:
1073         if (!sb_rdonly(sb))
1074                 return -EACCES;
1075         UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
1076         return 0;
1077 }
1078
1079 static int udf_fill_partdesc_info(struct super_block *sb,
1080                 struct partitionDesc *p, int p_index)
1081 {
1082         struct udf_part_map *map;
1083         struct udf_sb_info *sbi = UDF_SB(sb);
1084         struct partitionHeaderDesc *phd;
1085         int err;
1086
1087         map = &sbi->s_partmaps[p_index];
1088
1089         map->s_partition_len = le32_to_cpu(p->partitionLength); /* blocks */
1090         map->s_partition_root = le32_to_cpu(p->partitionStartingLocation);
1091
1092         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_READ_ONLY))
1093                 map->s_partition_flags |= UDF_PART_FLAG_READ_ONLY;
1094         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_WRITE_ONCE))
1095                 map->s_partition_flags |= UDF_PART_FLAG_WRITE_ONCE;
1096         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_REWRITABLE))
1097                 map->s_partition_flags |= UDF_PART_FLAG_REWRITABLE;
1098         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_OVERWRITABLE))
1099                 map->s_partition_flags |= UDF_PART_FLAG_OVERWRITABLE;
1100
1101         udf_debug("Partition (%d type %x) starts at physical %u, block length %u\n",
1102                   p_index, map->s_partition_type,
1103                   map->s_partition_root, map->s_partition_len);
1104
1105         err = check_partition_desc(sb, p, map);
1106         if (err)
1107                 return err;
1108
1109         /*
1110          * Skip loading allocation info it we cannot ever write to the fs.
1111          * This is a correctness thing as we may have decided to force ro mount
1112          * to avoid allocation info we don't support.
1113          */
1114         if (UDF_QUERY_FLAG(sb, UDF_FLAG_RW_INCOMPAT))
1115                 return 0;
1116
1117         phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
1118         if (phd->unallocSpaceTable.extLength) {
1119                 struct kernel_lb_addr loc = {
1120                         .logicalBlockNum = le32_to_cpu(
1121                                 phd->unallocSpaceTable.extPosition),
1122                         .partitionReferenceNum = p_index,
1123                 };
1124                 struct inode *inode;
1125
1126                 inode = udf_iget_special(sb, &loc);
1127                 if (IS_ERR(inode)) {
1128                         udf_debug("cannot load unallocSpaceTable (part %d)\n",
1129                                   p_index);
1130                         return PTR_ERR(inode);
1131                 }
1132                 map->s_uspace.s_table = inode;
1133                 map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_TABLE;
1134                 udf_debug("unallocSpaceTable (part %d) @ %lu\n",
1135                           p_index, map->s_uspace.s_table->i_ino);
1136         }
1137
1138         if (phd->unallocSpaceBitmap.extLength) {
1139                 struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index);
1140                 if (!bitmap)
1141                         return -ENOMEM;
1142                 map->s_uspace.s_bitmap = bitmap;
1143                 bitmap->s_extPosition = le32_to_cpu(
1144                                 phd->unallocSpaceBitmap.extPosition);
1145                 map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_BITMAP;
1146                 udf_debug("unallocSpaceBitmap (part %d) @ %u\n",
1147                           p_index, bitmap->s_extPosition);
1148         }
1149
1150         return 0;
1151 }
1152
1153 static void udf_find_vat_block(struct super_block *sb, int p_index,
1154                                int type1_index, sector_t start_block)
1155 {
1156         struct udf_sb_info *sbi = UDF_SB(sb);
1157         struct udf_part_map *map = &sbi->s_partmaps[p_index];
1158         sector_t vat_block;
1159         struct kernel_lb_addr ino;
1160         struct inode *inode;
1161
1162         /*
1163          * VAT file entry is in the last recorded block. Some broken disks have
1164          * it a few blocks before so try a bit harder...
1165          */
1166         ino.partitionReferenceNum = type1_index;
1167         for (vat_block = start_block;
1168              vat_block >= map->s_partition_root &&
1169              vat_block >= start_block - 3; vat_block--) {
1170                 ino.logicalBlockNum = vat_block - map->s_partition_root;
1171                 inode = udf_iget_special(sb, &ino);
1172                 if (!IS_ERR(inode)) {
1173                         sbi->s_vat_inode = inode;
1174                         break;
1175                 }
1176         }
1177 }
1178
1179 static int udf_load_vat(struct super_block *sb, int p_index, int type1_index)
1180 {
1181         struct udf_sb_info *sbi = UDF_SB(sb);
1182         struct udf_part_map *map = &sbi->s_partmaps[p_index];
1183         struct buffer_head *bh = NULL;
1184         struct udf_inode_info *vati;
1185         uint32_t pos;
1186         struct virtualAllocationTable20 *vat20;
1187         sector_t blocks = i_size_read(sb->s_bdev->bd_inode) >>
1188                           sb->s_blocksize_bits;
1189
1190         udf_find_vat_block(sb, p_index, type1_index, sbi->s_last_block);
1191         if (!sbi->s_vat_inode &&
1192             sbi->s_last_block != blocks - 1) {
1193                 pr_notice("Failed to read VAT inode from the last recorded block (%lu), retrying with the last block of the device (%lu).\n",
1194                           (unsigned long)sbi->s_last_block,
1195                           (unsigned long)blocks - 1);
1196                 udf_find_vat_block(sb, p_index, type1_index, blocks - 1);
1197         }
1198         if (!sbi->s_vat_inode)
1199                 return -EIO;
1200
1201         if (map->s_partition_type == UDF_VIRTUAL_MAP15) {
1202                 map->s_type_specific.s_virtual.s_start_offset = 0;
1203                 map->s_type_specific.s_virtual.s_num_entries =
1204                         (sbi->s_vat_inode->i_size - 36) >> 2;
1205         } else if (map->s_partition_type == UDF_VIRTUAL_MAP20) {
1206                 vati = UDF_I(sbi->s_vat_inode);
1207                 if (vati->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) {
1208                         pos = udf_block_map(sbi->s_vat_inode, 0);
1209                         bh = sb_bread(sb, pos);
1210                         if (!bh)
1211                                 return -EIO;
1212                         vat20 = (struct virtualAllocationTable20 *)bh->b_data;
1213                 } else {
1214                         vat20 = (struct virtualAllocationTable20 *)
1215                                                         vati->i_ext.i_data;
1216                 }
1217
1218                 map->s_type_specific.s_virtual.s_start_offset =
1219                         le16_to_cpu(vat20->lengthHeader);
1220                 map->s_type_specific.s_virtual.s_num_entries =
1221                         (sbi->s_vat_inode->i_size -
1222                                 map->s_type_specific.s_virtual.
1223                                         s_start_offset) >> 2;
1224                 brelse(bh);
1225         }
1226         return 0;
1227 }
1228
1229 /*
1230  * Load partition descriptor block
1231  *
1232  * Returns <0 on error, 0 on success, -EAGAIN is special - try next descriptor
1233  * sequence.
1234  */
1235 static int udf_load_partdesc(struct super_block *sb, sector_t block)
1236 {
1237         struct buffer_head *bh;
1238         struct partitionDesc *p;
1239         struct udf_part_map *map;
1240         struct udf_sb_info *sbi = UDF_SB(sb);
1241         int i, type1_idx;
1242         uint16_t partitionNumber;
1243         uint16_t ident;
1244         int ret;
1245
1246         bh = udf_read_tagged(sb, block, block, &ident);
1247         if (!bh)
1248                 return -EAGAIN;
1249         if (ident != TAG_IDENT_PD) {
1250                 ret = 0;
1251                 goto out_bh;
1252         }
1253
1254         p = (struct partitionDesc *)bh->b_data;
1255         partitionNumber = le16_to_cpu(p->partitionNumber);
1256
1257         /* First scan for TYPE1 and SPARABLE partitions */
1258         for (i = 0; i < sbi->s_partitions; i++) {
1259                 map = &sbi->s_partmaps[i];
1260                 udf_debug("Searching map: (%u == %u)\n",
1261                           map->s_partition_num, partitionNumber);
1262                 if (map->s_partition_num == partitionNumber &&
1263                     (map->s_partition_type == UDF_TYPE1_MAP15 ||
1264                      map->s_partition_type == UDF_SPARABLE_MAP15))
1265                         break;
1266         }
1267
1268         if (i >= sbi->s_partitions) {
1269                 udf_debug("Partition (%u) not found in partition map\n",
1270                           partitionNumber);
1271                 ret = 0;
1272                 goto out_bh;
1273         }
1274
1275         ret = udf_fill_partdesc_info(sb, p, i);
1276         if (ret < 0)
1277                 goto out_bh;
1278
1279         /*
1280          * Now rescan for VIRTUAL or METADATA partitions when SPARABLE and
1281          * PHYSICAL partitions are already set up
1282          */
1283         type1_idx = i;
1284         map = NULL; /* supress 'maybe used uninitialized' warning */
1285         for (i = 0; i < sbi->s_partitions; i++) {
1286                 map = &sbi->s_partmaps[i];
1287
1288                 if (map->s_partition_num == partitionNumber &&
1289                     (map->s_partition_type == UDF_VIRTUAL_MAP15 ||
1290                      map->s_partition_type == UDF_VIRTUAL_MAP20 ||
1291                      map->s_partition_type == UDF_METADATA_MAP25))
1292                         break;
1293         }
1294
1295         if (i >= sbi->s_partitions) {
1296                 ret = 0;
1297                 goto out_bh;
1298         }
1299
1300         ret = udf_fill_partdesc_info(sb, p, i);
1301         if (ret < 0)
1302                 goto out_bh;
1303
1304         if (map->s_partition_type == UDF_METADATA_MAP25) {
1305                 ret = udf_load_metadata_files(sb, i, type1_idx);
1306                 if (ret < 0) {
1307                         udf_err(sb, "error loading MetaData partition map %d\n",
1308                                 i);
1309                         goto out_bh;
1310                 }
1311         } else {
1312                 /*
1313                  * If we have a partition with virtual map, we don't handle
1314                  * writing to it (we overwrite blocks instead of relocating
1315                  * them).
1316                  */
1317                 if (!sb_rdonly(sb)) {
1318                         ret = -EACCES;
1319                         goto out_bh;
1320                 }
1321                 UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
1322                 ret = udf_load_vat(sb, i, type1_idx);
1323                 if (ret < 0)
1324                         goto out_bh;
1325         }
1326         ret = 0;
1327 out_bh:
1328         /* In case loading failed, we handle cleanup in udf_fill_super */
1329         brelse(bh);
1330         return ret;
1331 }
1332
1333 static int udf_load_sparable_map(struct super_block *sb,
1334                                  struct udf_part_map *map,
1335                                  struct sparablePartitionMap *spm)
1336 {
1337         uint32_t loc;
1338         uint16_t ident;
1339         struct sparingTable *st;
1340         struct udf_sparing_data *sdata = &map->s_type_specific.s_sparing;
1341         int i;
1342         struct buffer_head *bh;
1343
1344         map->s_partition_type = UDF_SPARABLE_MAP15;
1345         sdata->s_packet_len = le16_to_cpu(spm->packetLength);
1346         if (!is_power_of_2(sdata->s_packet_len)) {
1347                 udf_err(sb, "error loading logical volume descriptor: "
1348                         "Invalid packet length %u\n",
1349                         (unsigned)sdata->s_packet_len);
1350                 return -EIO;
1351         }
1352         if (spm->numSparingTables > 4) {
1353                 udf_err(sb, "error loading logical volume descriptor: "
1354                         "Too many sparing tables (%d)\n",
1355                         (int)spm->numSparingTables);
1356                 return -EIO;
1357         }
1358         if (le32_to_cpu(spm->sizeSparingTable) > sb->s_blocksize) {
1359                 udf_err(sb, "error loading logical volume descriptor: "
1360                         "Too big sparing table size (%u)\n",
1361                         le32_to_cpu(spm->sizeSparingTable));
1362                 return -EIO;
1363         }
1364
1365         for (i = 0; i < spm->numSparingTables; i++) {
1366                 loc = le32_to_cpu(spm->locSparingTable[i]);
1367                 bh = udf_read_tagged(sb, loc, loc, &ident);
1368                 if (!bh)
1369                         continue;
1370
1371                 st = (struct sparingTable *)bh->b_data;
1372                 if (ident != 0 ||
1373                     strncmp(st->sparingIdent.ident, UDF_ID_SPARING,
1374                             strlen(UDF_ID_SPARING)) ||
1375                     sizeof(*st) + le16_to_cpu(st->reallocationTableLen) >
1376                                                         sb->s_blocksize) {
1377                         brelse(bh);
1378                         continue;
1379                 }
1380
1381                 sdata->s_spar_map[i] = bh;
1382         }
1383         map->s_partition_func = udf_get_pblock_spar15;
1384         return 0;
1385 }
1386
1387 static int udf_load_logicalvol(struct super_block *sb, sector_t block,
1388                                struct kernel_lb_addr *fileset)
1389 {
1390         struct logicalVolDesc *lvd;
1391         int i, offset;
1392         uint8_t type;
1393         struct udf_sb_info *sbi = UDF_SB(sb);
1394         struct genericPartitionMap *gpm;
1395         uint16_t ident;
1396         struct buffer_head *bh;
1397         unsigned int table_len;
1398         int ret;
1399
1400         bh = udf_read_tagged(sb, block, block, &ident);
1401         if (!bh)
1402                 return -EAGAIN;
1403         BUG_ON(ident != TAG_IDENT_LVD);
1404         lvd = (struct logicalVolDesc *)bh->b_data;
1405         table_len = le32_to_cpu(lvd->mapTableLength);
1406         if (table_len > sb->s_blocksize - sizeof(*lvd)) {
1407                 udf_err(sb, "error loading logical volume descriptor: "
1408                         "Partition table too long (%u > %lu)\n", table_len,
1409                         sb->s_blocksize - sizeof(*lvd));
1410                 ret = -EIO;
1411                 goto out_bh;
1412         }
1413
1414         ret = udf_verify_domain_identifier(sb, &lvd->domainIdent,
1415                                            "logical volume");
1416         if (ret)
1417                 goto out_bh;
1418         ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
1419         if (ret)
1420                 goto out_bh;
1421
1422         for (i = 0, offset = 0;
1423              i < sbi->s_partitions && offset < table_len;
1424              i++, offset += gpm->partitionMapLength) {
1425                 struct udf_part_map *map = &sbi->s_partmaps[i];
1426                 gpm = (struct genericPartitionMap *)
1427                                 &(lvd->partitionMaps[offset]);
1428                 type = gpm->partitionMapType;
1429                 if (type == 1) {
1430                         struct genericPartitionMap1 *gpm1 =
1431                                 (struct genericPartitionMap1 *)gpm;
1432                         map->s_partition_type = UDF_TYPE1_MAP15;
1433                         map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
1434                         map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
1435                         map->s_partition_func = NULL;
1436                 } else if (type == 2) {
1437                         struct udfPartitionMap2 *upm2 =
1438                                                 (struct udfPartitionMap2 *)gpm;
1439                         if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
1440                                                 strlen(UDF_ID_VIRTUAL))) {
1441                                 u16 suf =
1442                                         le16_to_cpu(((__le16 *)upm2->partIdent.
1443                                                         identSuffix)[0]);
1444                                 if (suf < 0x0200) {
1445                                         map->s_partition_type =
1446                                                         UDF_VIRTUAL_MAP15;
1447                                         map->s_partition_func =
1448                                                         udf_get_pblock_virt15;
1449                                 } else {
1450                                         map->s_partition_type =
1451                                                         UDF_VIRTUAL_MAP20;
1452                                         map->s_partition_func =
1453                                                         udf_get_pblock_virt20;
1454                                 }
1455                         } else if (!strncmp(upm2->partIdent.ident,
1456                                                 UDF_ID_SPARABLE,
1457                                                 strlen(UDF_ID_SPARABLE))) {
1458                                 ret = udf_load_sparable_map(sb, map,
1459                                         (struct sparablePartitionMap *)gpm);
1460                                 if (ret < 0)
1461                                         goto out_bh;
1462                         } else if (!strncmp(upm2->partIdent.ident,
1463                                                 UDF_ID_METADATA,
1464                                                 strlen(UDF_ID_METADATA))) {
1465                                 struct udf_meta_data *mdata =
1466                                         &map->s_type_specific.s_metadata;
1467                                 struct metadataPartitionMap *mdm =
1468                                                 (struct metadataPartitionMap *)
1469                                                 &(lvd->partitionMaps[offset]);
1470                                 udf_debug("Parsing Logical vol part %d type %u  id=%s\n",
1471                                           i, type, UDF_ID_METADATA);
1472
1473                                 map->s_partition_type = UDF_METADATA_MAP25;
1474                                 map->s_partition_func = udf_get_pblock_meta25;
1475
1476                                 mdata->s_meta_file_loc   =
1477                                         le32_to_cpu(mdm->metadataFileLoc);
1478                                 mdata->s_mirror_file_loc =
1479                                         le32_to_cpu(mdm->metadataMirrorFileLoc);
1480                                 mdata->s_bitmap_file_loc =
1481                                         le32_to_cpu(mdm->metadataBitmapFileLoc);
1482                                 mdata->s_alloc_unit_size =
1483                                         le32_to_cpu(mdm->allocUnitSize);
1484                                 mdata->s_align_unit_size =
1485                                         le16_to_cpu(mdm->alignUnitSize);
1486                                 if (mdm->flags & 0x01)
1487                                         mdata->s_flags |= MF_DUPLICATE_MD;
1488
1489                                 udf_debug("Metadata Ident suffix=0x%x\n",
1490                                           le16_to_cpu(*(__le16 *)
1491                                                       mdm->partIdent.identSuffix));
1492                                 udf_debug("Metadata part num=%u\n",
1493                                           le16_to_cpu(mdm->partitionNum));
1494                                 udf_debug("Metadata part alloc unit size=%u\n",
1495                                           le32_to_cpu(mdm->allocUnitSize));
1496                                 udf_debug("Metadata file loc=%u\n",
1497                                           le32_to_cpu(mdm->metadataFileLoc));
1498                                 udf_debug("Mirror file loc=%u\n",
1499                                           le32_to_cpu(mdm->metadataMirrorFileLoc));
1500                                 udf_debug("Bitmap file loc=%u\n",
1501                                           le32_to_cpu(mdm->metadataBitmapFileLoc));
1502                                 udf_debug("Flags: %d %u\n",
1503                                           mdata->s_flags, mdm->flags);
1504                         } else {
1505                                 udf_debug("Unknown ident: %s\n",
1506                                           upm2->partIdent.ident);
1507                                 continue;
1508                         }
1509                         map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
1510                         map->s_partition_num = le16_to_cpu(upm2->partitionNum);
1511                 }
1512                 udf_debug("Partition (%d:%u) type %u on volume %u\n",
1513                           i, map->s_partition_num, type, map->s_volumeseqnum);
1514         }
1515
1516         if (fileset) {
1517                 struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
1518
1519                 *fileset = lelb_to_cpu(la->extLocation);
1520                 udf_debug("FileSet found in LogicalVolDesc at block=%u, partition=%u\n",
1521                           fileset->logicalBlockNum,
1522                           fileset->partitionReferenceNum);
1523         }
1524         if (lvd->integritySeqExt.extLength)
1525                 udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
1526         ret = 0;
1527
1528         if (!sbi->s_lvid_bh) {
1529                 /* We can't generate unique IDs without a valid LVID */
1530                 if (sb_rdonly(sb)) {
1531                         UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
1532                 } else {
1533                         udf_warn(sb, "Damaged or missing LVID, forcing "
1534                                      "readonly mount\n");
1535                         ret = -EACCES;
1536                 }
1537         }
1538 out_bh:
1539         brelse(bh);
1540         return ret;
1541 }
1542
1543 /*
1544  * Find the prevailing Logical Volume Integrity Descriptor.
1545  */
1546 static void udf_load_logicalvolint(struct super_block *sb, struct kernel_extent_ad loc)
1547 {
1548         struct buffer_head *bh, *final_bh;
1549         uint16_t ident;
1550         struct udf_sb_info *sbi = UDF_SB(sb);
1551         struct logicalVolIntegrityDesc *lvid;
1552         int indirections = 0;
1553         u32 parts, impuselen;
1554
1555         while (++indirections <= UDF_MAX_LVID_NESTING) {
1556                 final_bh = NULL;
1557                 while (loc.extLength > 0 &&
1558                         (bh = udf_read_tagged(sb, loc.extLocation,
1559                                         loc.extLocation, &ident))) {
1560                         if (ident != TAG_IDENT_LVID) {
1561                                 brelse(bh);
1562                                 break;
1563                         }
1564
1565                         brelse(final_bh);
1566                         final_bh = bh;
1567
1568                         loc.extLength -= sb->s_blocksize;
1569                         loc.extLocation++;
1570                 }
1571
1572                 if (!final_bh)
1573                         return;
1574
1575                 brelse(sbi->s_lvid_bh);
1576                 sbi->s_lvid_bh = final_bh;
1577
1578                 lvid = (struct logicalVolIntegrityDesc *)final_bh->b_data;
1579                 if (lvid->nextIntegrityExt.extLength == 0)
1580                         goto check;
1581
1582                 loc = leea_to_cpu(lvid->nextIntegrityExt);
1583         }
1584
1585         udf_warn(sb, "Too many LVID indirections (max %u), ignoring.\n",
1586                 UDF_MAX_LVID_NESTING);
1587 out_err:
1588         brelse(sbi->s_lvid_bh);
1589         sbi->s_lvid_bh = NULL;
1590         return;
1591 check:
1592         parts = le32_to_cpu(lvid->numOfPartitions);
1593         impuselen = le32_to_cpu(lvid->lengthOfImpUse);
1594         if (parts >= sb->s_blocksize || impuselen >= sb->s_blocksize ||
1595             sizeof(struct logicalVolIntegrityDesc) + impuselen +
1596             2 * parts * sizeof(u32) > sb->s_blocksize) {
1597                 udf_warn(sb, "Corrupted LVID (parts=%u, impuselen=%u), "
1598                          "ignoring.\n", parts, impuselen);
1599                 goto out_err;
1600         }
1601 }
1602
1603 /*
1604  * Step for reallocation of table of partition descriptor sequence numbers.
1605  * Must be power of 2.
1606  */
1607 #define PART_DESC_ALLOC_STEP 32
1608
1609 struct part_desc_seq_scan_data {
1610         struct udf_vds_record rec;
1611         u32 partnum;
1612 };
1613
1614 struct desc_seq_scan_data {
1615         struct udf_vds_record vds[VDS_POS_LENGTH];
1616         unsigned int size_part_descs;
1617         unsigned int num_part_descs;
1618         struct part_desc_seq_scan_data *part_descs_loc;
1619 };
1620
1621 static struct udf_vds_record *handle_partition_descriptor(
1622                                 struct buffer_head *bh,
1623                                 struct desc_seq_scan_data *data)
1624 {
1625         struct partitionDesc *desc = (struct partitionDesc *)bh->b_data;
1626         int partnum;
1627         int i;
1628
1629         partnum = le16_to_cpu(desc->partitionNumber);
1630         for (i = 0; i < data->num_part_descs; i++)
1631                 if (partnum == data->part_descs_loc[i].partnum)
1632                         return &(data->part_descs_loc[i].rec);
1633         if (data->num_part_descs >= data->size_part_descs) {
1634                 struct part_desc_seq_scan_data *new_loc;
1635                 unsigned int new_size = ALIGN(partnum, PART_DESC_ALLOC_STEP);
1636
1637                 new_loc = kcalloc(new_size, sizeof(*new_loc), GFP_KERNEL);
1638                 if (!new_loc)
1639                         return ERR_PTR(-ENOMEM);
1640                 memcpy(new_loc, data->part_descs_loc,
1641                        data->size_part_descs * sizeof(*new_loc));
1642                 kfree(data->part_descs_loc);
1643                 data->part_descs_loc = new_loc;
1644                 data->size_part_descs = new_size;
1645         }
1646         return &(data->part_descs_loc[data->num_part_descs++].rec);
1647 }
1648
1649
1650 static struct udf_vds_record *get_volume_descriptor_record(uint16_t ident,
1651                 struct buffer_head *bh, struct desc_seq_scan_data *data)
1652 {
1653         switch (ident) {
1654         case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
1655                 return &(data->vds[VDS_POS_PRIMARY_VOL_DESC]);
1656         case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
1657                 return &(data->vds[VDS_POS_IMP_USE_VOL_DESC]);
1658         case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
1659                 return &(data->vds[VDS_POS_LOGICAL_VOL_DESC]);
1660         case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
1661                 return &(data->vds[VDS_POS_UNALLOC_SPACE_DESC]);
1662         case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
1663                 return handle_partition_descriptor(bh, data);
1664         }
1665         return NULL;
1666 }
1667
1668 /*
1669  * Process a main/reserve volume descriptor sequence.
1670  *   @block             First block of first extent of the sequence.
1671  *   @lastblock         Lastblock of first extent of the sequence.
1672  *   @fileset           There we store extent containing root fileset
1673  *
1674  * Returns <0 on error, 0 on success. -EAGAIN is special - try next descriptor
1675  * sequence
1676  */
1677 static noinline int udf_process_sequence(
1678                 struct super_block *sb,
1679                 sector_t block, sector_t lastblock,
1680                 struct kernel_lb_addr *fileset)
1681 {
1682         struct buffer_head *bh = NULL;
1683         struct udf_vds_record *curr;
1684         struct generic_desc *gd;
1685         struct volDescPtr *vdp;
1686         bool done = false;
1687         uint32_t vdsn;
1688         uint16_t ident;
1689         int ret;
1690         unsigned int indirections = 0;
1691         struct desc_seq_scan_data data;
1692         unsigned int i;
1693
1694         memset(data.vds, 0, sizeof(struct udf_vds_record) * VDS_POS_LENGTH);
1695         data.size_part_descs = PART_DESC_ALLOC_STEP;
1696         data.num_part_descs = 0;
1697         data.part_descs_loc = kcalloc(data.size_part_descs,
1698                                       sizeof(*data.part_descs_loc),
1699                                       GFP_KERNEL);
1700         if (!data.part_descs_loc)
1701                 return -ENOMEM;
1702
1703         /*
1704          * Read the main descriptor sequence and find which descriptors
1705          * are in it.
1706          */
1707         for (; (!done && block <= lastblock); block++) {
1708                 bh = udf_read_tagged(sb, block, block, &ident);
1709                 if (!bh)
1710                         break;
1711
1712                 /* Process each descriptor (ISO 13346 3/8.3-8.4) */
1713                 gd = (struct generic_desc *)bh->b_data;
1714                 vdsn = le32_to_cpu(gd->volDescSeqNum);
1715                 switch (ident) {
1716                 case TAG_IDENT_VDP: /* ISO 13346 3/10.3 */
1717                         if (++indirections > UDF_MAX_TD_NESTING) {
1718                                 udf_err(sb, "too many Volume Descriptor "
1719                                         "Pointers (max %u supported)\n",
1720                                         UDF_MAX_TD_NESTING);
1721                                 brelse(bh);
1722                                 ret = -EIO;
1723                                 goto out;
1724                         }
1725
1726                         vdp = (struct volDescPtr *)bh->b_data;
1727                         block = le32_to_cpu(vdp->nextVolDescSeqExt.extLocation);
1728                         lastblock = le32_to_cpu(
1729                                 vdp->nextVolDescSeqExt.extLength) >>
1730                                 sb->s_blocksize_bits;
1731                         lastblock += block - 1;
1732                         /* For loop is going to increment 'block' again */
1733                         block--;
1734                         break;
1735                 case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
1736                 case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
1737                 case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
1738                 case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
1739                 case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
1740                         curr = get_volume_descriptor_record(ident, bh, &data);
1741                         if (IS_ERR(curr)) {
1742                                 brelse(bh);
1743                                 ret = PTR_ERR(curr);
1744                                 goto out;
1745                         }
1746                         /* Descriptor we don't care about? */
1747                         if (!curr)
1748                                 break;
1749                         if (vdsn >= curr->volDescSeqNum) {
1750                                 curr->volDescSeqNum = vdsn;
1751                                 curr->block = block;
1752                         }
1753                         break;
1754                 case TAG_IDENT_TD: /* ISO 13346 3/10.9 */
1755                         done = true;
1756                         break;
1757                 }
1758                 brelse(bh);
1759         }
1760         /*
1761          * Now read interesting descriptors again and process them
1762          * in a suitable order
1763          */
1764         if (!data.vds[VDS_POS_PRIMARY_VOL_DESC].block) {
1765                 udf_err(sb, "Primary Volume Descriptor not found!\n");
1766                 ret = -EAGAIN;
1767                 goto out;
1768         }
1769         ret = udf_load_pvoldesc(sb, data.vds[VDS_POS_PRIMARY_VOL_DESC].block);
1770         if (ret < 0)
1771                 goto out;
1772
1773         if (data.vds[VDS_POS_LOGICAL_VOL_DESC].block) {
1774                 ret = udf_load_logicalvol(sb,
1775                                 data.vds[VDS_POS_LOGICAL_VOL_DESC].block,
1776                                 fileset);
1777                 if (ret < 0)
1778                         goto out;
1779         }
1780
1781         /* Now handle prevailing Partition Descriptors */
1782         for (i = 0; i < data.num_part_descs; i++) {
1783                 ret = udf_load_partdesc(sb, data.part_descs_loc[i].rec.block);
1784                 if (ret < 0)
1785                         goto out;
1786         }
1787         ret = 0;
1788 out:
1789         kfree(data.part_descs_loc);
1790         return ret;
1791 }
1792
1793 /*
1794  * Load Volume Descriptor Sequence described by anchor in bh
1795  *
1796  * Returns <0 on error, 0 on success
1797  */
1798 static int udf_load_sequence(struct super_block *sb, struct buffer_head *bh,
1799                              struct kernel_lb_addr *fileset)
1800 {
1801         struct anchorVolDescPtr *anchor;
1802         sector_t main_s, main_e, reserve_s, reserve_e;
1803         int ret;
1804
1805         anchor = (struct anchorVolDescPtr *)bh->b_data;
1806
1807         /* Locate the main sequence */
1808         main_s = le32_to_cpu(anchor->mainVolDescSeqExt.extLocation);
1809         main_e = le32_to_cpu(anchor->mainVolDescSeqExt.extLength);
1810         main_e = main_e >> sb->s_blocksize_bits;
1811         main_e += main_s - 1;
1812
1813         /* Locate the reserve sequence */
1814         reserve_s = le32_to_cpu(anchor->reserveVolDescSeqExt.extLocation);
1815         reserve_e = le32_to_cpu(anchor->reserveVolDescSeqExt.extLength);
1816         reserve_e = reserve_e >> sb->s_blocksize_bits;
1817         reserve_e += reserve_s - 1;
1818
1819         /* Process the main & reserve sequences */
1820         /* responsible for finding the PartitionDesc(s) */
1821         ret = udf_process_sequence(sb, main_s, main_e, fileset);
1822         if (ret != -EAGAIN)
1823                 return ret;
1824         udf_sb_free_partitions(sb);
1825         ret = udf_process_sequence(sb, reserve_s, reserve_e, fileset);
1826         if (ret < 0) {
1827                 udf_sb_free_partitions(sb);
1828                 /* No sequence was OK, return -EIO */
1829                 if (ret == -EAGAIN)
1830                         ret = -EIO;
1831         }
1832         return ret;
1833 }
1834
1835 /*
1836  * Check whether there is an anchor block in the given block and
1837  * load Volume Descriptor Sequence if so.
1838  *
1839  * Returns <0 on error, 0 on success, -EAGAIN is special - try next anchor
1840  * block
1841  */
1842 static int udf_check_anchor_block(struct super_block *sb, sector_t block,
1843                                   struct kernel_lb_addr *fileset)
1844 {
1845         struct buffer_head *bh;
1846         uint16_t ident;
1847         int ret;
1848
1849         if (UDF_QUERY_FLAG(sb, UDF_FLAG_VARCONV) &&
1850             udf_fixed_to_variable(block) >=
1851             i_size_read(sb->s_bdev->bd_inode) >> sb->s_blocksize_bits)
1852                 return -EAGAIN;
1853
1854         bh = udf_read_tagged(sb, block, block, &ident);
1855         if (!bh)
1856                 return -EAGAIN;
1857         if (ident != TAG_IDENT_AVDP) {
1858                 brelse(bh);
1859                 return -EAGAIN;
1860         }
1861         ret = udf_load_sequence(sb, bh, fileset);
1862         brelse(bh);
1863         return ret;
1864 }
1865
1866 /*
1867  * Search for an anchor volume descriptor pointer.
1868  *
1869  * Returns < 0 on error, 0 on success. -EAGAIN is special - try next set
1870  * of anchors.
1871  */
1872 static int udf_scan_anchors(struct super_block *sb, sector_t *lastblock,
1873                             struct kernel_lb_addr *fileset)
1874 {
1875         sector_t last[6];
1876         int i;
1877         struct udf_sb_info *sbi = UDF_SB(sb);
1878         int last_count = 0;
1879         int ret;
1880
1881         /* First try user provided anchor */
1882         if (sbi->s_anchor) {
1883                 ret = udf_check_anchor_block(sb, sbi->s_anchor, fileset);
1884                 if (ret != -EAGAIN)
1885                         return ret;
1886         }
1887         /*
1888          * according to spec, anchor is in either:
1889          *     block 256
1890          *     lastblock-256
1891          *     lastblock
1892          *  however, if the disc isn't closed, it could be 512.
1893          */
1894         ret = udf_check_anchor_block(sb, sbi->s_session + 256, fileset);
1895         if (ret != -EAGAIN)
1896                 return ret;
1897         /*
1898          * The trouble is which block is the last one. Drives often misreport
1899          * this so we try various possibilities.
1900          */
1901         last[last_count++] = *lastblock;
1902         if (*lastblock >= 1)
1903                 last[last_count++] = *lastblock - 1;
1904         last[last_count++] = *lastblock + 1;
1905         if (*lastblock >= 2)
1906                 last[last_count++] = *lastblock - 2;
1907         if (*lastblock >= 150)
1908                 last[last_count++] = *lastblock - 150;
1909         if (*lastblock >= 152)
1910                 last[last_count++] = *lastblock - 152;
1911
1912         for (i = 0; i < last_count; i++) {
1913                 if (last[i] >= i_size_read(sb->s_bdev->bd_inode) >>
1914                                 sb->s_blocksize_bits)
1915                         continue;
1916                 ret = udf_check_anchor_block(sb, last[i], fileset);
1917                 if (ret != -EAGAIN) {
1918                         if (!ret)
1919                                 *lastblock = last[i];
1920                         return ret;
1921                 }
1922                 if (last[i] < 256)
1923                         continue;
1924                 ret = udf_check_anchor_block(sb, last[i] - 256, fileset);
1925                 if (ret != -EAGAIN) {
1926                         if (!ret)
1927                                 *lastblock = last[i];
1928                         return ret;
1929                 }
1930         }
1931
1932         /* Finally try block 512 in case media is open */
1933         return udf_check_anchor_block(sb, sbi->s_session + 512, fileset);
1934 }
1935
1936 /*
1937  * Find an anchor volume descriptor and load Volume Descriptor Sequence from
1938  * area specified by it. The function expects sbi->s_lastblock to be the last
1939  * block on the media.
1940  *
1941  * Return <0 on error, 0 if anchor found. -EAGAIN is special meaning anchor
1942  * was not found.
1943  */
1944 static int udf_find_anchor(struct super_block *sb,
1945                            struct kernel_lb_addr *fileset)
1946 {
1947         struct udf_sb_info *sbi = UDF_SB(sb);
1948         sector_t lastblock = sbi->s_last_block;
1949         int ret;
1950
1951         ret = udf_scan_anchors(sb, &lastblock, fileset);
1952         if (ret != -EAGAIN)
1953                 goto out;
1954
1955         /* No anchor found? Try VARCONV conversion of block numbers */
1956         UDF_SET_FLAG(sb, UDF_FLAG_VARCONV);
1957         lastblock = udf_variable_to_fixed(sbi->s_last_block);
1958         /* Firstly, we try to not convert number of the last block */
1959         ret = udf_scan_anchors(sb, &lastblock, fileset);
1960         if (ret != -EAGAIN)
1961                 goto out;
1962
1963         lastblock = sbi->s_last_block;
1964         /* Secondly, we try with converted number of the last block */
1965         ret = udf_scan_anchors(sb, &lastblock, fileset);
1966         if (ret < 0) {
1967                 /* VARCONV didn't help. Clear it. */
1968                 UDF_CLEAR_FLAG(sb, UDF_FLAG_VARCONV);
1969         }
1970 out:
1971         if (ret == 0)
1972                 sbi->s_last_block = lastblock;
1973         return ret;
1974 }
1975
1976 /*
1977  * Check Volume Structure Descriptor, find Anchor block and load Volume
1978  * Descriptor Sequence.
1979  *
1980  * Returns < 0 on error, 0 on success. -EAGAIN is special meaning anchor
1981  * block was not found.
1982  */
1983 static int udf_load_vrs(struct super_block *sb, struct udf_options *uopt,
1984                         int silent, struct kernel_lb_addr *fileset)
1985 {
1986         struct udf_sb_info *sbi = UDF_SB(sb);
1987         int nsr = 0;
1988         int ret;
1989
1990         if (!sb_set_blocksize(sb, uopt->blocksize)) {
1991                 if (!silent)
1992                         udf_warn(sb, "Bad block size\n");
1993                 return -EINVAL;
1994         }
1995         sbi->s_last_block = uopt->lastblock;
1996         if (!uopt->novrs) {
1997                 /* Check that it is NSR02 compliant */
1998                 nsr = udf_check_vsd(sb);
1999                 if (!nsr) {
2000                         if (!silent)
2001                                 udf_warn(sb, "No VRS found\n");
2002                         return -EINVAL;
2003                 }
2004                 if (nsr == -1)
2005                         udf_debug("Failed to read sector at offset %d. "
2006                                   "Assuming open disc. Skipping validity "
2007                                   "check\n", VSD_FIRST_SECTOR_OFFSET);
2008                 if (!sbi->s_last_block)
2009                         sbi->s_last_block = udf_get_last_block(sb);
2010         } else {
2011                 udf_debug("Validity check skipped because of novrs option\n");
2012         }
2013
2014         /* Look for anchor block and load Volume Descriptor Sequence */
2015         sbi->s_anchor = uopt->anchor;
2016         ret = udf_find_anchor(sb, fileset);
2017         if (ret < 0) {
2018                 if (!silent && ret == -EAGAIN)
2019                         udf_warn(sb, "No anchor found\n");
2020                 return ret;
2021         }
2022         return 0;
2023 }
2024
2025 static void udf_finalize_lvid(struct logicalVolIntegrityDesc *lvid)
2026 {
2027         struct timespec64 ts;
2028
2029         ktime_get_real_ts64(&ts);
2030         udf_time_to_disk_stamp(&lvid->recordingDateAndTime, ts);
2031         lvid->descTag.descCRC = cpu_to_le16(
2032                 crc_itu_t(0, (char *)lvid + sizeof(struct tag),
2033                         le16_to_cpu(lvid->descTag.descCRCLength)));
2034         lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag);
2035 }
2036
2037 static void udf_open_lvid(struct super_block *sb)
2038 {
2039         struct udf_sb_info *sbi = UDF_SB(sb);
2040         struct buffer_head *bh = sbi->s_lvid_bh;
2041         struct logicalVolIntegrityDesc *lvid;
2042         struct logicalVolIntegrityDescImpUse *lvidiu;
2043
2044         if (!bh)
2045                 return;
2046         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2047         lvidiu = udf_sb_lvidiu(sb);
2048         if (!lvidiu)
2049                 return;
2050
2051         mutex_lock(&sbi->s_alloc_mutex);
2052         lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
2053         lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
2054         if (le32_to_cpu(lvid->integrityType) == LVID_INTEGRITY_TYPE_CLOSE)
2055                 lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_OPEN);
2056         else
2057                 UDF_SET_FLAG(sb, UDF_FLAG_INCONSISTENT);
2058
2059         udf_finalize_lvid(lvid);
2060         mark_buffer_dirty(bh);
2061         sbi->s_lvid_dirty = 0;
2062         mutex_unlock(&sbi->s_alloc_mutex);
2063         /* Make opening of filesystem visible on the media immediately */
2064         sync_dirty_buffer(bh);
2065 }
2066
2067 static void udf_close_lvid(struct super_block *sb)
2068 {
2069         struct udf_sb_info *sbi = UDF_SB(sb);
2070         struct buffer_head *bh = sbi->s_lvid_bh;
2071         struct logicalVolIntegrityDesc *lvid;
2072         struct logicalVolIntegrityDescImpUse *lvidiu;
2073
2074         if (!bh)
2075                 return;
2076         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2077         lvidiu = udf_sb_lvidiu(sb);
2078         if (!lvidiu)
2079                 return;
2080
2081         mutex_lock(&sbi->s_alloc_mutex);
2082         lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
2083         lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
2084         if (UDF_MAX_WRITE_VERSION > le16_to_cpu(lvidiu->maxUDFWriteRev))
2085                 lvidiu->maxUDFWriteRev = cpu_to_le16(UDF_MAX_WRITE_VERSION);
2086         if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFReadRev))
2087                 lvidiu->minUDFReadRev = cpu_to_le16(sbi->s_udfrev);
2088         if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFWriteRev))
2089                 lvidiu->minUDFWriteRev = cpu_to_le16(sbi->s_udfrev);
2090         if (!UDF_QUERY_FLAG(sb, UDF_FLAG_INCONSISTENT))
2091                 lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_CLOSE);
2092
2093         /*
2094          * We set buffer uptodate unconditionally here to avoid spurious
2095          * warnings from mark_buffer_dirty() when previous EIO has marked
2096          * the buffer as !uptodate
2097          */
2098         set_buffer_uptodate(bh);
2099         udf_finalize_lvid(lvid);
2100         mark_buffer_dirty(bh);
2101         sbi->s_lvid_dirty = 0;
2102         mutex_unlock(&sbi->s_alloc_mutex);
2103         /* Make closing of filesystem visible on the media immediately */
2104         sync_dirty_buffer(bh);
2105 }
2106
2107 u64 lvid_get_unique_id(struct super_block *sb)
2108 {
2109         struct buffer_head *bh;
2110         struct udf_sb_info *sbi = UDF_SB(sb);
2111         struct logicalVolIntegrityDesc *lvid;
2112         struct logicalVolHeaderDesc *lvhd;
2113         u64 uniqueID;
2114         u64 ret;
2115
2116         bh = sbi->s_lvid_bh;
2117         if (!bh)
2118                 return 0;
2119
2120         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2121         lvhd = (struct logicalVolHeaderDesc *)lvid->logicalVolContentsUse;
2122
2123         mutex_lock(&sbi->s_alloc_mutex);
2124         ret = uniqueID = le64_to_cpu(lvhd->uniqueID);
2125         if (!(++uniqueID & 0xFFFFFFFF))
2126                 uniqueID += 16;
2127         lvhd->uniqueID = cpu_to_le64(uniqueID);
2128         udf_updated_lvid(sb);
2129         mutex_unlock(&sbi->s_alloc_mutex);
2130
2131         return ret;
2132 }
2133
2134 static int udf_fill_super(struct super_block *sb, void *options, int silent)
2135 {
2136         int ret = -EINVAL;
2137         struct inode *inode = NULL;
2138         struct udf_options uopt;
2139         struct kernel_lb_addr rootdir, fileset;
2140         struct udf_sb_info *sbi;
2141         bool lvid_open = false;
2142
2143         uopt.flags = (1 << UDF_FLAG_USE_AD_IN_ICB) | (1 << UDF_FLAG_STRICT);
2144         /* By default we'll use overflow[ug]id when UDF inode [ug]id == -1 */
2145         uopt.uid = make_kuid(current_user_ns(), overflowuid);
2146         uopt.gid = make_kgid(current_user_ns(), overflowgid);
2147         uopt.umask = 0;
2148         uopt.fmode = UDF_INVALID_MODE;
2149         uopt.dmode = UDF_INVALID_MODE;
2150         uopt.nls_map = NULL;
2151
2152         sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
2153         if (!sbi)
2154                 return -ENOMEM;
2155
2156         sb->s_fs_info = sbi;
2157
2158         mutex_init(&sbi->s_alloc_mutex);
2159
2160         if (!udf_parse_options((char *)options, &uopt, false))
2161                 goto parse_options_failure;
2162
2163         fileset.logicalBlockNum = 0xFFFFFFFF;
2164         fileset.partitionReferenceNum = 0xFFFF;
2165
2166         sbi->s_flags = uopt.flags;
2167         sbi->s_uid = uopt.uid;
2168         sbi->s_gid = uopt.gid;
2169         sbi->s_umask = uopt.umask;
2170         sbi->s_fmode = uopt.fmode;
2171         sbi->s_dmode = uopt.dmode;
2172         sbi->s_nls_map = uopt.nls_map;
2173         rwlock_init(&sbi->s_cred_lock);
2174
2175         if (uopt.session == 0xFFFFFFFF)
2176                 sbi->s_session = udf_get_last_session(sb);
2177         else
2178                 sbi->s_session = uopt.session;
2179
2180         udf_debug("Multi-session=%d\n", sbi->s_session);
2181
2182         /* Fill in the rest of the superblock */
2183         sb->s_op = &udf_sb_ops;
2184         sb->s_export_op = &udf_export_ops;
2185
2186         sb->s_magic = UDF_SUPER_MAGIC;
2187         sb->s_time_gran = 1000;
2188
2189         if (uopt.flags & (1 << UDF_FLAG_BLOCKSIZE_SET)) {
2190                 ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2191         } else {
2192                 uopt.blocksize = bdev_logical_block_size(sb->s_bdev);
2193                 while (uopt.blocksize <= 4096) {
2194                         ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2195                         if (ret < 0) {
2196                                 if (!silent && ret != -EACCES) {
2197                                         pr_notice("Scanning with blocksize %u failed\n",
2198                                                   uopt.blocksize);
2199                                 }
2200                                 brelse(sbi->s_lvid_bh);
2201                                 sbi->s_lvid_bh = NULL;
2202                                 /*
2203                                  * EACCES is special - we want to propagate to
2204                                  * upper layers that we cannot handle RW mount.
2205                                  */
2206                                 if (ret == -EACCES)
2207                                         break;
2208                         } else
2209                                 break;
2210
2211                         uopt.blocksize <<= 1;
2212                 }
2213         }
2214         if (ret < 0) {
2215                 if (ret == -EAGAIN) {
2216                         udf_warn(sb, "No partition found (1)\n");
2217                         ret = -EINVAL;
2218                 }
2219                 goto error_out;
2220         }
2221
2222         udf_debug("Lastblock=%u\n", sbi->s_last_block);
2223
2224         if (sbi->s_lvid_bh) {
2225                 struct logicalVolIntegrityDescImpUse *lvidiu =
2226                                                         udf_sb_lvidiu(sb);
2227                 uint16_t minUDFReadRev;
2228                 uint16_t minUDFWriteRev;
2229
2230                 if (!lvidiu) {
2231                         ret = -EINVAL;
2232                         goto error_out;
2233                 }
2234                 minUDFReadRev = le16_to_cpu(lvidiu->minUDFReadRev);
2235                 minUDFWriteRev = le16_to_cpu(lvidiu->minUDFWriteRev);
2236                 if (minUDFReadRev > UDF_MAX_READ_VERSION) {
2237                         udf_err(sb, "minUDFReadRev=%x (max is %x)\n",
2238                                 minUDFReadRev,
2239                                 UDF_MAX_READ_VERSION);
2240                         ret = -EINVAL;
2241                         goto error_out;
2242                 } else if (minUDFWriteRev > UDF_MAX_WRITE_VERSION) {
2243                         if (!sb_rdonly(sb)) {
2244                                 ret = -EACCES;
2245                                 goto error_out;
2246                         }
2247                         UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
2248                 }
2249
2250                 sbi->s_udfrev = minUDFWriteRev;
2251
2252                 if (minUDFReadRev >= UDF_VERS_USE_EXTENDED_FE)
2253                         UDF_SET_FLAG(sb, UDF_FLAG_USE_EXTENDED_FE);
2254                 if (minUDFReadRev >= UDF_VERS_USE_STREAMS)
2255                         UDF_SET_FLAG(sb, UDF_FLAG_USE_STREAMS);
2256         }
2257
2258         if (!sbi->s_partitions) {
2259                 udf_warn(sb, "No partition found (2)\n");
2260                 ret = -EINVAL;
2261                 goto error_out;
2262         }
2263
2264         if (sbi->s_partmaps[sbi->s_partition].s_partition_flags &
2265                         UDF_PART_FLAG_READ_ONLY) {
2266                 if (!sb_rdonly(sb)) {
2267                         ret = -EACCES;
2268                         goto error_out;
2269                 }
2270                 UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
2271         }
2272
2273         ret = udf_find_fileset(sb, &fileset, &rootdir);
2274         if (ret < 0) {
2275                 udf_warn(sb, "No fileset found\n");
2276                 goto error_out;
2277         }
2278
2279         if (!silent) {
2280                 struct timestamp ts;
2281                 udf_time_to_disk_stamp(&ts, sbi->s_record_time);
2282                 udf_info("Mounting volume '%s', timestamp %04u/%02u/%02u %02u:%02u (%x)\n",
2283                          sbi->s_volume_ident,
2284                          le16_to_cpu(ts.year), ts.month, ts.day,
2285                          ts.hour, ts.minute, le16_to_cpu(ts.typeAndTimezone));
2286         }
2287         if (!sb_rdonly(sb)) {
2288                 udf_open_lvid(sb);
2289                 lvid_open = true;
2290         }
2291
2292         /* Assign the root inode */
2293         /* assign inodes by physical block number */
2294         /* perhaps it's not extensible enough, but for now ... */
2295         inode = udf_iget(sb, &rootdir);
2296         if (IS_ERR(inode)) {
2297                 udf_err(sb, "Error in udf_iget, block=%u, partition=%u\n",
2298                        rootdir.logicalBlockNum, rootdir.partitionReferenceNum);
2299                 ret = PTR_ERR(inode);
2300                 goto error_out;
2301         }
2302
2303         /* Allocate a dentry for the root inode */
2304         sb->s_root = d_make_root(inode);
2305         if (!sb->s_root) {
2306                 udf_err(sb, "Couldn't allocate root dentry\n");
2307                 ret = -ENOMEM;
2308                 goto error_out;
2309         }
2310         sb->s_maxbytes = MAX_LFS_FILESIZE;
2311         sb->s_max_links = UDF_MAX_LINKS;
2312         return 0;
2313
2314 error_out:
2315         iput(sbi->s_vat_inode);
2316 parse_options_failure:
2317         unload_nls(uopt.nls_map);
2318         if (lvid_open)
2319                 udf_close_lvid(sb);
2320         brelse(sbi->s_lvid_bh);
2321         udf_sb_free_partitions(sb);
2322         kfree(sbi);
2323         sb->s_fs_info = NULL;
2324
2325         return ret;
2326 }
2327
2328 void _udf_err(struct super_block *sb, const char *function,
2329               const char *fmt, ...)
2330 {
2331         struct va_format vaf;
2332         va_list args;
2333
2334         va_start(args, fmt);
2335
2336         vaf.fmt = fmt;
2337         vaf.va = &args;
2338
2339         pr_err("error (device %s): %s: %pV", sb->s_id, function, &vaf);
2340
2341         va_end(args);
2342 }
2343
2344 void _udf_warn(struct super_block *sb, const char *function,
2345                const char *fmt, ...)
2346 {
2347         struct va_format vaf;
2348         va_list args;
2349
2350         va_start(args, fmt);
2351
2352         vaf.fmt = fmt;
2353         vaf.va = &args;
2354
2355         pr_warn("warning (device %s): %s: %pV", sb->s_id, function, &vaf);
2356
2357         va_end(args);
2358 }
2359
2360 static void udf_put_super(struct super_block *sb)
2361 {
2362         struct udf_sb_info *sbi;
2363
2364         sbi = UDF_SB(sb);
2365
2366         iput(sbi->s_vat_inode);
2367         unload_nls(sbi->s_nls_map);
2368         if (!sb_rdonly(sb))
2369                 udf_close_lvid(sb);
2370         brelse(sbi->s_lvid_bh);
2371         udf_sb_free_partitions(sb);
2372         mutex_destroy(&sbi->s_alloc_mutex);
2373         kfree(sb->s_fs_info);
2374         sb->s_fs_info = NULL;
2375 }
2376
2377 static int udf_sync_fs(struct super_block *sb, int wait)
2378 {
2379         struct udf_sb_info *sbi = UDF_SB(sb);
2380
2381         mutex_lock(&sbi->s_alloc_mutex);
2382         if (sbi->s_lvid_dirty) {
2383                 struct buffer_head *bh = sbi->s_lvid_bh;
2384                 struct logicalVolIntegrityDesc *lvid;
2385
2386                 lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2387                 udf_finalize_lvid(lvid);
2388
2389                 /*
2390                  * Blockdevice will be synced later so we don't have to submit
2391                  * the buffer for IO
2392                  */
2393                 mark_buffer_dirty(bh);
2394                 sbi->s_lvid_dirty = 0;
2395         }
2396         mutex_unlock(&sbi->s_alloc_mutex);
2397
2398         return 0;
2399 }
2400
2401 static int udf_statfs(struct dentry *dentry, struct kstatfs *buf)
2402 {
2403         struct super_block *sb = dentry->d_sb;
2404         struct udf_sb_info *sbi = UDF_SB(sb);
2405         struct logicalVolIntegrityDescImpUse *lvidiu;
2406         u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
2407
2408         lvidiu = udf_sb_lvidiu(sb);
2409         buf->f_type = UDF_SUPER_MAGIC;
2410         buf->f_bsize = sb->s_blocksize;
2411         buf->f_blocks = sbi->s_partmaps[sbi->s_partition].s_partition_len;
2412         buf->f_bfree = udf_count_free(sb);
2413         buf->f_bavail = buf->f_bfree;
2414         buf->f_files = (lvidiu != NULL ? (le32_to_cpu(lvidiu->numFiles) +
2415                                           le32_to_cpu(lvidiu->numDirs)) : 0)
2416                         + buf->f_bfree;
2417         buf->f_ffree = buf->f_bfree;
2418         buf->f_namelen = UDF_NAME_LEN;
2419         buf->f_fsid.val[0] = (u32)id;
2420         buf->f_fsid.val[1] = (u32)(id >> 32);
2421
2422         return 0;
2423 }
2424
2425 static unsigned int udf_count_free_bitmap(struct super_block *sb,
2426                                           struct udf_bitmap *bitmap)
2427 {
2428         struct buffer_head *bh = NULL;
2429         unsigned int accum = 0;
2430         int index;
2431         udf_pblk_t block = 0, newblock;
2432         struct kernel_lb_addr loc;
2433         uint32_t bytes;
2434         uint8_t *ptr;
2435         uint16_t ident;
2436         struct spaceBitmapDesc *bm;
2437
2438         loc.logicalBlockNum = bitmap->s_extPosition;
2439         loc.partitionReferenceNum = UDF_SB(sb)->s_partition;
2440         bh = udf_read_ptagged(sb, &loc, 0, &ident);
2441
2442         if (!bh) {
2443                 udf_err(sb, "udf_count_free failed\n");
2444                 goto out;
2445         } else if (ident != TAG_IDENT_SBD) {
2446                 brelse(bh);
2447                 udf_err(sb, "udf_count_free failed\n");
2448                 goto out;
2449         }
2450
2451         bm = (struct spaceBitmapDesc *)bh->b_data;
2452         bytes = le32_to_cpu(bm->numOfBytes);
2453         index = sizeof(struct spaceBitmapDesc); /* offset in first block only */
2454         ptr = (uint8_t *)bh->b_data;
2455
2456         while (bytes > 0) {
2457                 u32 cur_bytes = min_t(u32, bytes, sb->s_blocksize - index);
2458                 accum += bitmap_weight((const unsigned long *)(ptr + index),
2459                                         cur_bytes * 8);
2460                 bytes -= cur_bytes;
2461                 if (bytes) {
2462                         brelse(bh);
2463                         newblock = udf_get_lb_pblock(sb, &loc, ++block);
2464                         bh = udf_tread(sb, newblock);
2465                         if (!bh) {
2466                                 udf_debug("read failed\n");
2467                                 goto out;
2468                         }
2469                         index = 0;
2470                         ptr = (uint8_t *)bh->b_data;
2471                 }
2472         }
2473         brelse(bh);
2474 out:
2475         return accum;
2476 }
2477
2478 static unsigned int udf_count_free_table(struct super_block *sb,
2479                                          struct inode *table)
2480 {
2481         unsigned int accum = 0;
2482         uint32_t elen;
2483         struct kernel_lb_addr eloc;
2484         int8_t etype;
2485         struct extent_position epos;
2486
2487         mutex_lock(&UDF_SB(sb)->s_alloc_mutex);
2488         epos.block = UDF_I(table)->i_location;
2489         epos.offset = sizeof(struct unallocSpaceEntry);
2490         epos.bh = NULL;
2491
2492         while ((etype = udf_next_aext(table, &epos, &eloc, &elen, 1)) != -1)
2493                 accum += (elen >> table->i_sb->s_blocksize_bits);
2494
2495         brelse(epos.bh);
2496         mutex_unlock(&UDF_SB(sb)->s_alloc_mutex);
2497
2498         return accum;
2499 }
2500
2501 static unsigned int udf_count_free(struct super_block *sb)
2502 {
2503         unsigned int accum = 0;
2504         struct udf_sb_info *sbi = UDF_SB(sb);
2505         struct udf_part_map *map;
2506         unsigned int part = sbi->s_partition;
2507         int ptype = sbi->s_partmaps[part].s_partition_type;
2508
2509         if (ptype == UDF_METADATA_MAP25) {
2510                 part = sbi->s_partmaps[part].s_type_specific.s_metadata.
2511                                                         s_phys_partition_ref;
2512         } else if (ptype == UDF_VIRTUAL_MAP15 || ptype == UDF_VIRTUAL_MAP20) {
2513                 /*
2514                  * Filesystems with VAT are append-only and we cannot write to
2515                  * them. Let's just report 0 here.
2516                  */
2517                 return 0;
2518         }
2519
2520         if (sbi->s_lvid_bh) {
2521                 struct logicalVolIntegrityDesc *lvid =
2522                         (struct logicalVolIntegrityDesc *)
2523                         sbi->s_lvid_bh->b_data;
2524                 if (le32_to_cpu(lvid->numOfPartitions) > part) {
2525                         accum = le32_to_cpu(
2526                                         lvid->freeSpaceTable[part]);
2527                         if (accum == 0xFFFFFFFF)
2528                                 accum = 0;
2529                 }
2530         }
2531
2532         if (accum)
2533                 return accum;
2534
2535         map = &sbi->s_partmaps[part];
2536         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) {
2537                 accum += udf_count_free_bitmap(sb,
2538                                                map->s_uspace.s_bitmap);
2539         }
2540         if (accum)
2541                 return accum;
2542
2543         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) {
2544                 accum += udf_count_free_table(sb,
2545                                               map->s_uspace.s_table);
2546         }
2547         return accum;
2548 }
2549
2550 MODULE_AUTHOR("Ben Fennema");
2551 MODULE_DESCRIPTION("Universal Disk Format Filesystem");
2552 MODULE_LICENSE("GPL");
2553 module_init(init_udf_fs)
2554 module_exit(exit_udf_fs)