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