]> asedeno.scripts.mit.edu Git - linux.git/blob - fs/udf/super.c
Merge tag 'rtc-5.2' of git://git.kernel.org/pub/scm/linux/kernel/git/abelloni/linux
[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                                 uopt->nls_map = load_nls(args[0].from);
570                                 uopt->flags |= (1 << UDF_FLAG_NLS_MAP);
571                         }
572                         break;
573                 case Opt_uforget:
574                         uopt->flags |= (1 << UDF_FLAG_UID_FORGET);
575                         break;
576                 case Opt_uignore:
577                 case Opt_gignore:
578                         /* These options are superseeded by uid=<number> */
579                         break;
580                 case Opt_gforget:
581                         uopt->flags |= (1 << UDF_FLAG_GID_FORGET);
582                         break;
583                 case Opt_fmode:
584                         if (match_octal(args, &option))
585                                 return 0;
586                         uopt->fmode = option & 0777;
587                         break;
588                 case Opt_dmode:
589                         if (match_octal(args, &option))
590                                 return 0;
591                         uopt->dmode = option & 0777;
592                         break;
593                 default:
594                         pr_err("bad mount option \"%s\" or missing value\n", p);
595                         return 0;
596                 }
597         }
598         return 1;
599 }
600
601 static int udf_remount_fs(struct super_block *sb, int *flags, char *options)
602 {
603         struct udf_options uopt;
604         struct udf_sb_info *sbi = UDF_SB(sb);
605         int error = 0;
606
607         if (!(*flags & SB_RDONLY) && UDF_QUERY_FLAG(sb, UDF_FLAG_RW_INCOMPAT))
608                 return -EACCES;
609
610         sync_filesystem(sb);
611
612         uopt.flags = sbi->s_flags;
613         uopt.uid   = sbi->s_uid;
614         uopt.gid   = sbi->s_gid;
615         uopt.umask = sbi->s_umask;
616         uopt.fmode = sbi->s_fmode;
617         uopt.dmode = sbi->s_dmode;
618         uopt.nls_map = NULL;
619
620         if (!udf_parse_options(options, &uopt, true))
621                 return -EINVAL;
622
623         write_lock(&sbi->s_cred_lock);
624         sbi->s_flags = uopt.flags;
625         sbi->s_uid   = uopt.uid;
626         sbi->s_gid   = uopt.gid;
627         sbi->s_umask = uopt.umask;
628         sbi->s_fmode = uopt.fmode;
629         sbi->s_dmode = uopt.dmode;
630         write_unlock(&sbi->s_cred_lock);
631
632         if ((bool)(*flags & SB_RDONLY) == sb_rdonly(sb))
633                 goto out_unlock;
634
635         if (*flags & SB_RDONLY)
636                 udf_close_lvid(sb);
637         else
638                 udf_open_lvid(sb);
639
640 out_unlock:
641         return error;
642 }
643
644 /* Check Volume Structure Descriptors (ECMA 167 2/9.1) */
645 /* We also check any "CD-ROM Volume Descriptor Set" (ECMA 167 2/8.3.1) */
646 static loff_t udf_check_vsd(struct super_block *sb)
647 {
648         struct volStructDesc *vsd = NULL;
649         loff_t sector = VSD_FIRST_SECTOR_OFFSET;
650         int sectorsize;
651         struct buffer_head *bh = NULL;
652         int nsr02 = 0;
653         int nsr03 = 0;
654         struct udf_sb_info *sbi;
655
656         sbi = UDF_SB(sb);
657         if (sb->s_blocksize < sizeof(struct volStructDesc))
658                 sectorsize = sizeof(struct volStructDesc);
659         else
660                 sectorsize = sb->s_blocksize;
661
662         sector += (((loff_t)sbi->s_session) << sb->s_blocksize_bits);
663
664         udf_debug("Starting at sector %u (%lu byte sectors)\n",
665                   (unsigned int)(sector >> sb->s_blocksize_bits),
666                   sb->s_blocksize);
667         /* Process the sequence (if applicable). The hard limit on the sector
668          * offset is arbitrary, hopefully large enough so that all valid UDF
669          * filesystems will be recognised. There is no mention of an upper
670          * bound to the size of the volume recognition area in the standard.
671          *  The limit will prevent the code to read all the sectors of a
672          * specially crafted image (like a bluray disc full of CD001 sectors),
673          * potentially causing minutes or even hours of uninterruptible I/O
674          * activity. This actually happened with uninitialised SSD partitions
675          * (all 0xFF) before the check for the limit and all valid IDs were
676          * added */
677         for (; !nsr02 && !nsr03 && sector < VSD_MAX_SECTOR_OFFSET;
678              sector += sectorsize) {
679                 /* Read a block */
680                 bh = udf_tread(sb, sector >> sb->s_blocksize_bits);
681                 if (!bh)
682                         break;
683
684                 /* Look for ISO  descriptors */
685                 vsd = (struct volStructDesc *)(bh->b_data +
686                                               (sector & (sb->s_blocksize - 1)));
687
688                 if (!strncmp(vsd->stdIdent, VSD_STD_ID_CD001,
689                                     VSD_STD_ID_LEN)) {
690                         switch (vsd->structType) {
691                         case 0:
692                                 udf_debug("ISO9660 Boot Record found\n");
693                                 break;
694                         case 1:
695                                 udf_debug("ISO9660 Primary Volume Descriptor found\n");
696                                 break;
697                         case 2:
698                                 udf_debug("ISO9660 Supplementary Volume Descriptor found\n");
699                                 break;
700                         case 3:
701                                 udf_debug("ISO9660 Volume Partition Descriptor found\n");
702                                 break;
703                         case 255:
704                                 udf_debug("ISO9660 Volume Descriptor Set Terminator found\n");
705                                 break;
706                         default:
707                                 udf_debug("ISO9660 VRS (%u) found\n",
708                                           vsd->structType);
709                                 break;
710                         }
711                 } else if (!strncmp(vsd->stdIdent, VSD_STD_ID_BEA01,
712                                     VSD_STD_ID_LEN))
713                         ; /* nothing */
714                 else if (!strncmp(vsd->stdIdent, VSD_STD_ID_TEA01,
715                                     VSD_STD_ID_LEN)) {
716                         brelse(bh);
717                         break;
718                 } else if (!strncmp(vsd->stdIdent, VSD_STD_ID_NSR02,
719                                     VSD_STD_ID_LEN))
720                         nsr02 = sector;
721                 else if (!strncmp(vsd->stdIdent, VSD_STD_ID_NSR03,
722                                     VSD_STD_ID_LEN))
723                         nsr03 = sector;
724                 else if (!strncmp(vsd->stdIdent, VSD_STD_ID_BOOT2,
725                                     VSD_STD_ID_LEN))
726                         ; /* nothing */
727                 else if (!strncmp(vsd->stdIdent, VSD_STD_ID_CDW02,
728                                     VSD_STD_ID_LEN))
729                         ; /* nothing */
730                 else {
731                         /* invalid id : end of volume recognition area */
732                         brelse(bh);
733                         break;
734                 }
735                 brelse(bh);
736         }
737
738         if (nsr03)
739                 return nsr03;
740         else if (nsr02)
741                 return nsr02;
742         else if (!bh && sector - (sbi->s_session << sb->s_blocksize_bits) ==
743                         VSD_FIRST_SECTOR_OFFSET)
744                 return -1;
745         else
746                 return 0;
747 }
748
749 static int udf_find_fileset(struct super_block *sb,
750                             struct kernel_lb_addr *fileset,
751                             struct kernel_lb_addr *root)
752 {
753         struct buffer_head *bh = NULL;
754         uint16_t ident;
755
756         if (fileset->logicalBlockNum != 0xFFFFFFFF ||
757             fileset->partitionReferenceNum != 0xFFFF) {
758                 bh = udf_read_ptagged(sb, fileset, 0, &ident);
759
760                 if (!bh) {
761                         return 1;
762                 } else if (ident != TAG_IDENT_FSD) {
763                         brelse(bh);
764                         return 1;
765                 }
766
767                 udf_debug("Fileset at block=%u, partition=%u\n",
768                           fileset->logicalBlockNum,
769                           fileset->partitionReferenceNum);
770
771                 UDF_SB(sb)->s_partition = fileset->partitionReferenceNum;
772                 udf_load_fileset(sb, bh, root);
773                 brelse(bh);
774                 return 0;
775         }
776         return 1;
777 }
778
779 /*
780  * Load primary Volume Descriptor Sequence
781  *
782  * Return <0 on error, 0 on success. -EAGAIN is special meaning next sequence
783  * should be tried.
784  */
785 static int udf_load_pvoldesc(struct super_block *sb, sector_t block)
786 {
787         struct primaryVolDesc *pvoldesc;
788         uint8_t *outstr;
789         struct buffer_head *bh;
790         uint16_t ident;
791         int ret = -ENOMEM;
792 #ifdef UDFFS_DEBUG
793         struct timestamp *ts;
794 #endif
795
796         outstr = kmalloc(128, GFP_NOFS);
797         if (!outstr)
798                 return -ENOMEM;
799
800         bh = udf_read_tagged(sb, block, block, &ident);
801         if (!bh) {
802                 ret = -EAGAIN;
803                 goto out2;
804         }
805
806         if (ident != TAG_IDENT_PVD) {
807                 ret = -EIO;
808                 goto out_bh;
809         }
810
811         pvoldesc = (struct primaryVolDesc *)bh->b_data;
812
813         udf_disk_stamp_to_time(&UDF_SB(sb)->s_record_time,
814                               pvoldesc->recordingDateAndTime);
815 #ifdef UDFFS_DEBUG
816         ts = &pvoldesc->recordingDateAndTime;
817         udf_debug("recording time %04u/%02u/%02u %02u:%02u (%x)\n",
818                   le16_to_cpu(ts->year), ts->month, ts->day, ts->hour,
819                   ts->minute, le16_to_cpu(ts->typeAndTimezone));
820 #endif
821
822
823         ret = udf_dstrCS0toChar(sb, outstr, 31, pvoldesc->volIdent, 32);
824         if (ret < 0) {
825                 strcpy(UDF_SB(sb)->s_volume_ident, "InvalidName");
826                 pr_warn("incorrect volume identification, setting to "
827                         "'InvalidName'\n");
828         } else {
829                 strncpy(UDF_SB(sb)->s_volume_ident, outstr, ret);
830         }
831         udf_debug("volIdent[] = '%s'\n", UDF_SB(sb)->s_volume_ident);
832
833         ret = udf_dstrCS0toChar(sb, outstr, 127, pvoldesc->volSetIdent, 128);
834         if (ret < 0) {
835                 ret = 0;
836                 goto out_bh;
837         }
838         outstr[ret] = 0;
839         udf_debug("volSetIdent[] = '%s'\n", outstr);
840
841         ret = 0;
842 out_bh:
843         brelse(bh);
844 out2:
845         kfree(outstr);
846         return ret;
847 }
848
849 struct inode *udf_find_metadata_inode_efe(struct super_block *sb,
850                                         u32 meta_file_loc, u32 partition_ref)
851 {
852         struct kernel_lb_addr addr;
853         struct inode *metadata_fe;
854
855         addr.logicalBlockNum = meta_file_loc;
856         addr.partitionReferenceNum = partition_ref;
857
858         metadata_fe = udf_iget_special(sb, &addr);
859
860         if (IS_ERR(metadata_fe)) {
861                 udf_warn(sb, "metadata inode efe not found\n");
862                 return metadata_fe;
863         }
864         if (UDF_I(metadata_fe)->i_alloc_type != ICBTAG_FLAG_AD_SHORT) {
865                 udf_warn(sb, "metadata inode efe does not have short allocation descriptors!\n");
866                 iput(metadata_fe);
867                 return ERR_PTR(-EIO);
868         }
869
870         return metadata_fe;
871 }
872
873 static int udf_load_metadata_files(struct super_block *sb, int partition,
874                                    int type1_index)
875 {
876         struct udf_sb_info *sbi = UDF_SB(sb);
877         struct udf_part_map *map;
878         struct udf_meta_data *mdata;
879         struct kernel_lb_addr addr;
880         struct inode *fe;
881
882         map = &sbi->s_partmaps[partition];
883         mdata = &map->s_type_specific.s_metadata;
884         mdata->s_phys_partition_ref = type1_index;
885
886         /* metadata address */
887         udf_debug("Metadata file location: block = %u part = %u\n",
888                   mdata->s_meta_file_loc, mdata->s_phys_partition_ref);
889
890         fe = udf_find_metadata_inode_efe(sb, mdata->s_meta_file_loc,
891                                          mdata->s_phys_partition_ref);
892         if (IS_ERR(fe)) {
893                 /* mirror file entry */
894                 udf_debug("Mirror metadata file location: block = %u part = %u\n",
895                           mdata->s_mirror_file_loc, mdata->s_phys_partition_ref);
896
897                 fe = udf_find_metadata_inode_efe(sb, mdata->s_mirror_file_loc,
898                                                  mdata->s_phys_partition_ref);
899
900                 if (IS_ERR(fe)) {
901                         udf_err(sb, "Both metadata and mirror metadata inode efe can not found\n");
902                         return PTR_ERR(fe);
903                 }
904                 mdata->s_mirror_fe = fe;
905         } else
906                 mdata->s_metadata_fe = fe;
907
908
909         /*
910          * bitmap file entry
911          * Note:
912          * Load only if bitmap file location differs from 0xFFFFFFFF (DCN-5102)
913         */
914         if (mdata->s_bitmap_file_loc != 0xFFFFFFFF) {
915                 addr.logicalBlockNum = mdata->s_bitmap_file_loc;
916                 addr.partitionReferenceNum = mdata->s_phys_partition_ref;
917
918                 udf_debug("Bitmap file location: block = %u part = %u\n",
919                           addr.logicalBlockNum, addr.partitionReferenceNum);
920
921                 fe = udf_iget_special(sb, &addr);
922                 if (IS_ERR(fe)) {
923                         if (sb_rdonly(sb))
924                                 udf_warn(sb, "bitmap inode efe not found but it's ok since the disc is mounted read-only\n");
925                         else {
926                                 udf_err(sb, "bitmap inode efe not found and attempted read-write mount\n");
927                                 return PTR_ERR(fe);
928                         }
929                 } else
930                         mdata->s_bitmap_fe = fe;
931         }
932
933         udf_debug("udf_load_metadata_files Ok\n");
934         return 0;
935 }
936
937 static void udf_load_fileset(struct super_block *sb, struct buffer_head *bh,
938                              struct kernel_lb_addr *root)
939 {
940         struct fileSetDesc *fset;
941
942         fset = (struct fileSetDesc *)bh->b_data;
943
944         *root = lelb_to_cpu(fset->rootDirectoryICB.extLocation);
945
946         UDF_SB(sb)->s_serial_number = le16_to_cpu(fset->descTag.tagSerialNum);
947
948         udf_debug("Rootdir at block=%u, partition=%u\n",
949                   root->logicalBlockNum, root->partitionReferenceNum);
950 }
951
952 int udf_compute_nr_groups(struct super_block *sb, u32 partition)
953 {
954         struct udf_part_map *map = &UDF_SB(sb)->s_partmaps[partition];
955         return DIV_ROUND_UP(map->s_partition_len +
956                             (sizeof(struct spaceBitmapDesc) << 3),
957                             sb->s_blocksize * 8);
958 }
959
960 static struct udf_bitmap *udf_sb_alloc_bitmap(struct super_block *sb, u32 index)
961 {
962         struct udf_bitmap *bitmap;
963         int nr_groups;
964         int size;
965
966         nr_groups = udf_compute_nr_groups(sb, index);
967         size = sizeof(struct udf_bitmap) +
968                 (sizeof(struct buffer_head *) * nr_groups);
969
970         if (size <= PAGE_SIZE)
971                 bitmap = kzalloc(size, GFP_KERNEL);
972         else
973                 bitmap = vzalloc(size); /* TODO: get rid of vzalloc */
974
975         if (!bitmap)
976                 return NULL;
977
978         bitmap->s_nr_groups = nr_groups;
979         return bitmap;
980 }
981
982 static int check_partition_desc(struct super_block *sb,
983                                 struct partitionDesc *p,
984                                 struct udf_part_map *map)
985 {
986         bool umap, utable, fmap, ftable;
987         struct partitionHeaderDesc *phd;
988
989         switch (le32_to_cpu(p->accessType)) {
990         case PD_ACCESS_TYPE_READ_ONLY:
991         case PD_ACCESS_TYPE_WRITE_ONCE:
992         case PD_ACCESS_TYPE_REWRITABLE:
993         case PD_ACCESS_TYPE_NONE:
994                 goto force_ro;
995         }
996
997         /* No Partition Header Descriptor? */
998         if (strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR02) &&
999             strcmp(p->partitionContents.ident, PD_PARTITION_CONTENTS_NSR03))
1000                 goto force_ro;
1001
1002         phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
1003         utable = phd->unallocSpaceTable.extLength;
1004         umap = phd->unallocSpaceBitmap.extLength;
1005         ftable = phd->freedSpaceTable.extLength;
1006         fmap = phd->freedSpaceBitmap.extLength;
1007
1008         /* No allocation info? */
1009         if (!utable && !umap && !ftable && !fmap)
1010                 goto force_ro;
1011
1012         /* We don't support blocks that require erasing before overwrite */
1013         if (ftable || fmap)
1014                 goto force_ro;
1015         /* UDF 2.60: 2.3.3 - no mixing of tables & bitmaps, no VAT. */
1016         if (utable && umap)
1017                 goto force_ro;
1018
1019         if (map->s_partition_type == UDF_VIRTUAL_MAP15 ||
1020             map->s_partition_type == UDF_VIRTUAL_MAP20)
1021                 goto force_ro;
1022
1023         return 0;
1024 force_ro:
1025         if (!sb_rdonly(sb))
1026                 return -EACCES;
1027         UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
1028         return 0;
1029 }
1030
1031 static int udf_fill_partdesc_info(struct super_block *sb,
1032                 struct partitionDesc *p, int p_index)
1033 {
1034         struct udf_part_map *map;
1035         struct udf_sb_info *sbi = UDF_SB(sb);
1036         struct partitionHeaderDesc *phd;
1037         int err;
1038
1039         map = &sbi->s_partmaps[p_index];
1040
1041         map->s_partition_len = le32_to_cpu(p->partitionLength); /* blocks */
1042         map->s_partition_root = le32_to_cpu(p->partitionStartingLocation);
1043
1044         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_READ_ONLY))
1045                 map->s_partition_flags |= UDF_PART_FLAG_READ_ONLY;
1046         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_WRITE_ONCE))
1047                 map->s_partition_flags |= UDF_PART_FLAG_WRITE_ONCE;
1048         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_REWRITABLE))
1049                 map->s_partition_flags |= UDF_PART_FLAG_REWRITABLE;
1050         if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_OVERWRITABLE))
1051                 map->s_partition_flags |= UDF_PART_FLAG_OVERWRITABLE;
1052
1053         udf_debug("Partition (%d type %x) starts at physical %u, block length %u\n",
1054                   p_index, map->s_partition_type,
1055                   map->s_partition_root, map->s_partition_len);
1056
1057         err = check_partition_desc(sb, p, map);
1058         if (err)
1059                 return err;
1060
1061         /*
1062          * Skip loading allocation info it we cannot ever write to the fs.
1063          * This is a correctness thing as we may have decided to force ro mount
1064          * to avoid allocation info we don't support.
1065          */
1066         if (UDF_QUERY_FLAG(sb, UDF_FLAG_RW_INCOMPAT))
1067                 return 0;
1068
1069         phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
1070         if (phd->unallocSpaceTable.extLength) {
1071                 struct kernel_lb_addr loc = {
1072                         .logicalBlockNum = le32_to_cpu(
1073                                 phd->unallocSpaceTable.extPosition),
1074                         .partitionReferenceNum = p_index,
1075                 };
1076                 struct inode *inode;
1077
1078                 inode = udf_iget_special(sb, &loc);
1079                 if (IS_ERR(inode)) {
1080                         udf_debug("cannot load unallocSpaceTable (part %d)\n",
1081                                   p_index);
1082                         return PTR_ERR(inode);
1083                 }
1084                 map->s_uspace.s_table = inode;
1085                 map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_TABLE;
1086                 udf_debug("unallocSpaceTable (part %d) @ %lu\n",
1087                           p_index, map->s_uspace.s_table->i_ino);
1088         }
1089
1090         if (phd->unallocSpaceBitmap.extLength) {
1091                 struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index);
1092                 if (!bitmap)
1093                         return -ENOMEM;
1094                 map->s_uspace.s_bitmap = bitmap;
1095                 bitmap->s_extPosition = le32_to_cpu(
1096                                 phd->unallocSpaceBitmap.extPosition);
1097                 map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_BITMAP;
1098                 udf_debug("unallocSpaceBitmap (part %d) @ %u\n",
1099                           p_index, bitmap->s_extPosition);
1100         }
1101
1102         return 0;
1103 }
1104
1105 static void udf_find_vat_block(struct super_block *sb, int p_index,
1106                                int type1_index, sector_t start_block)
1107 {
1108         struct udf_sb_info *sbi = UDF_SB(sb);
1109         struct udf_part_map *map = &sbi->s_partmaps[p_index];
1110         sector_t vat_block;
1111         struct kernel_lb_addr ino;
1112         struct inode *inode;
1113
1114         /*
1115          * VAT file entry is in the last recorded block. Some broken disks have
1116          * it a few blocks before so try a bit harder...
1117          */
1118         ino.partitionReferenceNum = type1_index;
1119         for (vat_block = start_block;
1120              vat_block >= map->s_partition_root &&
1121              vat_block >= start_block - 3; vat_block--) {
1122                 ino.logicalBlockNum = vat_block - map->s_partition_root;
1123                 inode = udf_iget_special(sb, &ino);
1124                 if (!IS_ERR(inode)) {
1125                         sbi->s_vat_inode = inode;
1126                         break;
1127                 }
1128         }
1129 }
1130
1131 static int udf_load_vat(struct super_block *sb, int p_index, int type1_index)
1132 {
1133         struct udf_sb_info *sbi = UDF_SB(sb);
1134         struct udf_part_map *map = &sbi->s_partmaps[p_index];
1135         struct buffer_head *bh = NULL;
1136         struct udf_inode_info *vati;
1137         uint32_t pos;
1138         struct virtualAllocationTable20 *vat20;
1139         sector_t blocks = i_size_read(sb->s_bdev->bd_inode) >>
1140                           sb->s_blocksize_bits;
1141
1142         udf_find_vat_block(sb, p_index, type1_index, sbi->s_last_block);
1143         if (!sbi->s_vat_inode &&
1144             sbi->s_last_block != blocks - 1) {
1145                 pr_notice("Failed to read VAT inode from the last recorded block (%lu), retrying with the last block of the device (%lu).\n",
1146                           (unsigned long)sbi->s_last_block,
1147                           (unsigned long)blocks - 1);
1148                 udf_find_vat_block(sb, p_index, type1_index, blocks - 1);
1149         }
1150         if (!sbi->s_vat_inode)
1151                 return -EIO;
1152
1153         if (map->s_partition_type == UDF_VIRTUAL_MAP15) {
1154                 map->s_type_specific.s_virtual.s_start_offset = 0;
1155                 map->s_type_specific.s_virtual.s_num_entries =
1156                         (sbi->s_vat_inode->i_size - 36) >> 2;
1157         } else if (map->s_partition_type == UDF_VIRTUAL_MAP20) {
1158                 vati = UDF_I(sbi->s_vat_inode);
1159                 if (vati->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) {
1160                         pos = udf_block_map(sbi->s_vat_inode, 0);
1161                         bh = sb_bread(sb, pos);
1162                         if (!bh)
1163                                 return -EIO;
1164                         vat20 = (struct virtualAllocationTable20 *)bh->b_data;
1165                 } else {
1166                         vat20 = (struct virtualAllocationTable20 *)
1167                                                         vati->i_ext.i_data;
1168                 }
1169
1170                 map->s_type_specific.s_virtual.s_start_offset =
1171                         le16_to_cpu(vat20->lengthHeader);
1172                 map->s_type_specific.s_virtual.s_num_entries =
1173                         (sbi->s_vat_inode->i_size -
1174                                 map->s_type_specific.s_virtual.
1175                                         s_start_offset) >> 2;
1176                 brelse(bh);
1177         }
1178         return 0;
1179 }
1180
1181 /*
1182  * Load partition descriptor block
1183  *
1184  * Returns <0 on error, 0 on success, -EAGAIN is special - try next descriptor
1185  * sequence.
1186  */
1187 static int udf_load_partdesc(struct super_block *sb, sector_t block)
1188 {
1189         struct buffer_head *bh;
1190         struct partitionDesc *p;
1191         struct udf_part_map *map;
1192         struct udf_sb_info *sbi = UDF_SB(sb);
1193         int i, type1_idx;
1194         uint16_t partitionNumber;
1195         uint16_t ident;
1196         int ret;
1197
1198         bh = udf_read_tagged(sb, block, block, &ident);
1199         if (!bh)
1200                 return -EAGAIN;
1201         if (ident != TAG_IDENT_PD) {
1202                 ret = 0;
1203                 goto out_bh;
1204         }
1205
1206         p = (struct partitionDesc *)bh->b_data;
1207         partitionNumber = le16_to_cpu(p->partitionNumber);
1208
1209         /* First scan for TYPE1 and SPARABLE partitions */
1210         for (i = 0; i < sbi->s_partitions; i++) {
1211                 map = &sbi->s_partmaps[i];
1212                 udf_debug("Searching map: (%u == %u)\n",
1213                           map->s_partition_num, partitionNumber);
1214                 if (map->s_partition_num == partitionNumber &&
1215                     (map->s_partition_type == UDF_TYPE1_MAP15 ||
1216                      map->s_partition_type == UDF_SPARABLE_MAP15))
1217                         break;
1218         }
1219
1220         if (i >= sbi->s_partitions) {
1221                 udf_debug("Partition (%u) not found in partition map\n",
1222                           partitionNumber);
1223                 ret = 0;
1224                 goto out_bh;
1225         }
1226
1227         ret = udf_fill_partdesc_info(sb, p, i);
1228         if (ret < 0)
1229                 goto out_bh;
1230
1231         /*
1232          * Now rescan for VIRTUAL or METADATA partitions when SPARABLE and
1233          * PHYSICAL partitions are already set up
1234          */
1235         type1_idx = i;
1236 #ifdef UDFFS_DEBUG
1237         map = NULL; /* supress 'maybe used uninitialized' warning */
1238 #endif
1239         for (i = 0; i < sbi->s_partitions; i++) {
1240                 map = &sbi->s_partmaps[i];
1241
1242                 if (map->s_partition_num == partitionNumber &&
1243                     (map->s_partition_type == UDF_VIRTUAL_MAP15 ||
1244                      map->s_partition_type == UDF_VIRTUAL_MAP20 ||
1245                      map->s_partition_type == UDF_METADATA_MAP25))
1246                         break;
1247         }
1248
1249         if (i >= sbi->s_partitions) {
1250                 ret = 0;
1251                 goto out_bh;
1252         }
1253
1254         ret = udf_fill_partdesc_info(sb, p, i);
1255         if (ret < 0)
1256                 goto out_bh;
1257
1258         if (map->s_partition_type == UDF_METADATA_MAP25) {
1259                 ret = udf_load_metadata_files(sb, i, type1_idx);
1260                 if (ret < 0) {
1261                         udf_err(sb, "error loading MetaData partition map %d\n",
1262                                 i);
1263                         goto out_bh;
1264                 }
1265         } else {
1266                 /*
1267                  * If we have a partition with virtual map, we don't handle
1268                  * writing to it (we overwrite blocks instead of relocating
1269                  * them).
1270                  */
1271                 if (!sb_rdonly(sb)) {
1272                         ret = -EACCES;
1273                         goto out_bh;
1274                 }
1275                 UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
1276                 ret = udf_load_vat(sb, i, type1_idx);
1277                 if (ret < 0)
1278                         goto out_bh;
1279         }
1280         ret = 0;
1281 out_bh:
1282         /* In case loading failed, we handle cleanup in udf_fill_super */
1283         brelse(bh);
1284         return ret;
1285 }
1286
1287 static int udf_load_sparable_map(struct super_block *sb,
1288                                  struct udf_part_map *map,
1289                                  struct sparablePartitionMap *spm)
1290 {
1291         uint32_t loc;
1292         uint16_t ident;
1293         struct sparingTable *st;
1294         struct udf_sparing_data *sdata = &map->s_type_specific.s_sparing;
1295         int i;
1296         struct buffer_head *bh;
1297
1298         map->s_partition_type = UDF_SPARABLE_MAP15;
1299         sdata->s_packet_len = le16_to_cpu(spm->packetLength);
1300         if (!is_power_of_2(sdata->s_packet_len)) {
1301                 udf_err(sb, "error loading logical volume descriptor: "
1302                         "Invalid packet length %u\n",
1303                         (unsigned)sdata->s_packet_len);
1304                 return -EIO;
1305         }
1306         if (spm->numSparingTables > 4) {
1307                 udf_err(sb, "error loading logical volume descriptor: "
1308                         "Too many sparing tables (%d)\n",
1309                         (int)spm->numSparingTables);
1310                 return -EIO;
1311         }
1312
1313         for (i = 0; i < spm->numSparingTables; i++) {
1314                 loc = le32_to_cpu(spm->locSparingTable[i]);
1315                 bh = udf_read_tagged(sb, loc, loc, &ident);
1316                 if (!bh)
1317                         continue;
1318
1319                 st = (struct sparingTable *)bh->b_data;
1320                 if (ident != 0 ||
1321                     strncmp(st->sparingIdent.ident, UDF_ID_SPARING,
1322                             strlen(UDF_ID_SPARING)) ||
1323                     sizeof(*st) + le16_to_cpu(st->reallocationTableLen) >
1324                                                         sb->s_blocksize) {
1325                         brelse(bh);
1326                         continue;
1327                 }
1328
1329                 sdata->s_spar_map[i] = bh;
1330         }
1331         map->s_partition_func = udf_get_pblock_spar15;
1332         return 0;
1333 }
1334
1335 static int udf_load_logicalvol(struct super_block *sb, sector_t block,
1336                                struct kernel_lb_addr *fileset)
1337 {
1338         struct logicalVolDesc *lvd;
1339         int i, offset;
1340         uint8_t type;
1341         struct udf_sb_info *sbi = UDF_SB(sb);
1342         struct genericPartitionMap *gpm;
1343         uint16_t ident;
1344         struct buffer_head *bh;
1345         unsigned int table_len;
1346         int ret;
1347
1348         bh = udf_read_tagged(sb, block, block, &ident);
1349         if (!bh)
1350                 return -EAGAIN;
1351         BUG_ON(ident != TAG_IDENT_LVD);
1352         lvd = (struct logicalVolDesc *)bh->b_data;
1353         table_len = le32_to_cpu(lvd->mapTableLength);
1354         if (table_len > sb->s_blocksize - sizeof(*lvd)) {
1355                 udf_err(sb, "error loading logical volume descriptor: "
1356                         "Partition table too long (%u > %lu)\n", table_len,
1357                         sb->s_blocksize - sizeof(*lvd));
1358                 ret = -EIO;
1359                 goto out_bh;
1360         }
1361
1362         ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
1363         if (ret)
1364                 goto out_bh;
1365
1366         for (i = 0, offset = 0;
1367              i < sbi->s_partitions && offset < table_len;
1368              i++, offset += gpm->partitionMapLength) {
1369                 struct udf_part_map *map = &sbi->s_partmaps[i];
1370                 gpm = (struct genericPartitionMap *)
1371                                 &(lvd->partitionMaps[offset]);
1372                 type = gpm->partitionMapType;
1373                 if (type == 1) {
1374                         struct genericPartitionMap1 *gpm1 =
1375                                 (struct genericPartitionMap1 *)gpm;
1376                         map->s_partition_type = UDF_TYPE1_MAP15;
1377                         map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
1378                         map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
1379                         map->s_partition_func = NULL;
1380                 } else if (type == 2) {
1381                         struct udfPartitionMap2 *upm2 =
1382                                                 (struct udfPartitionMap2 *)gpm;
1383                         if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
1384                                                 strlen(UDF_ID_VIRTUAL))) {
1385                                 u16 suf =
1386                                         le16_to_cpu(((__le16 *)upm2->partIdent.
1387                                                         identSuffix)[0]);
1388                                 if (suf < 0x0200) {
1389                                         map->s_partition_type =
1390                                                         UDF_VIRTUAL_MAP15;
1391                                         map->s_partition_func =
1392                                                         udf_get_pblock_virt15;
1393                                 } else {
1394                                         map->s_partition_type =
1395                                                         UDF_VIRTUAL_MAP20;
1396                                         map->s_partition_func =
1397                                                         udf_get_pblock_virt20;
1398                                 }
1399                         } else if (!strncmp(upm2->partIdent.ident,
1400                                                 UDF_ID_SPARABLE,
1401                                                 strlen(UDF_ID_SPARABLE))) {
1402                                 ret = udf_load_sparable_map(sb, map,
1403                                         (struct sparablePartitionMap *)gpm);
1404                                 if (ret < 0)
1405                                         goto out_bh;
1406                         } else if (!strncmp(upm2->partIdent.ident,
1407                                                 UDF_ID_METADATA,
1408                                                 strlen(UDF_ID_METADATA))) {
1409                                 struct udf_meta_data *mdata =
1410                                         &map->s_type_specific.s_metadata;
1411                                 struct metadataPartitionMap *mdm =
1412                                                 (struct metadataPartitionMap *)
1413                                                 &(lvd->partitionMaps[offset]);
1414                                 udf_debug("Parsing Logical vol part %d type %u  id=%s\n",
1415                                           i, type, UDF_ID_METADATA);
1416
1417                                 map->s_partition_type = UDF_METADATA_MAP25;
1418                                 map->s_partition_func = udf_get_pblock_meta25;
1419
1420                                 mdata->s_meta_file_loc   =
1421                                         le32_to_cpu(mdm->metadataFileLoc);
1422                                 mdata->s_mirror_file_loc =
1423                                         le32_to_cpu(mdm->metadataMirrorFileLoc);
1424                                 mdata->s_bitmap_file_loc =
1425                                         le32_to_cpu(mdm->metadataBitmapFileLoc);
1426                                 mdata->s_alloc_unit_size =
1427                                         le32_to_cpu(mdm->allocUnitSize);
1428                                 mdata->s_align_unit_size =
1429                                         le16_to_cpu(mdm->alignUnitSize);
1430                                 if (mdm->flags & 0x01)
1431                                         mdata->s_flags |= MF_DUPLICATE_MD;
1432
1433                                 udf_debug("Metadata Ident suffix=0x%x\n",
1434                                           le16_to_cpu(*(__le16 *)
1435                                                       mdm->partIdent.identSuffix));
1436                                 udf_debug("Metadata part num=%u\n",
1437                                           le16_to_cpu(mdm->partitionNum));
1438                                 udf_debug("Metadata part alloc unit size=%u\n",
1439                                           le32_to_cpu(mdm->allocUnitSize));
1440                                 udf_debug("Metadata file loc=%u\n",
1441                                           le32_to_cpu(mdm->metadataFileLoc));
1442                                 udf_debug("Mirror file loc=%u\n",
1443                                           le32_to_cpu(mdm->metadataMirrorFileLoc));
1444                                 udf_debug("Bitmap file loc=%u\n",
1445                                           le32_to_cpu(mdm->metadataBitmapFileLoc));
1446                                 udf_debug("Flags: %d %u\n",
1447                                           mdata->s_flags, mdm->flags);
1448                         } else {
1449                                 udf_debug("Unknown ident: %s\n",
1450                                           upm2->partIdent.ident);
1451                                 continue;
1452                         }
1453                         map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
1454                         map->s_partition_num = le16_to_cpu(upm2->partitionNum);
1455                 }
1456                 udf_debug("Partition (%d:%u) type %u on volume %u\n",
1457                           i, map->s_partition_num, type, map->s_volumeseqnum);
1458         }
1459
1460         if (fileset) {
1461                 struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
1462
1463                 *fileset = lelb_to_cpu(la->extLocation);
1464                 udf_debug("FileSet found in LogicalVolDesc at block=%u, partition=%u\n",
1465                           fileset->logicalBlockNum,
1466                           fileset->partitionReferenceNum);
1467         }
1468         if (lvd->integritySeqExt.extLength)
1469                 udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
1470         ret = 0;
1471
1472         if (!sbi->s_lvid_bh) {
1473                 /* We can't generate unique IDs without a valid LVID */
1474                 if (sb_rdonly(sb)) {
1475                         UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
1476                 } else {
1477                         udf_warn(sb, "Damaged or missing LVID, forcing "
1478                                      "readonly mount\n");
1479                         ret = -EACCES;
1480                 }
1481         }
1482 out_bh:
1483         brelse(bh);
1484         return ret;
1485 }
1486
1487 /*
1488  * Find the prevailing Logical Volume Integrity Descriptor.
1489  */
1490 static void udf_load_logicalvolint(struct super_block *sb, struct kernel_extent_ad loc)
1491 {
1492         struct buffer_head *bh, *final_bh;
1493         uint16_t ident;
1494         struct udf_sb_info *sbi = UDF_SB(sb);
1495         struct logicalVolIntegrityDesc *lvid;
1496         int indirections = 0;
1497
1498         while (++indirections <= UDF_MAX_LVID_NESTING) {
1499                 final_bh = NULL;
1500                 while (loc.extLength > 0 &&
1501                         (bh = udf_read_tagged(sb, loc.extLocation,
1502                                         loc.extLocation, &ident))) {
1503                         if (ident != TAG_IDENT_LVID) {
1504                                 brelse(bh);
1505                                 break;
1506                         }
1507
1508                         brelse(final_bh);
1509                         final_bh = bh;
1510
1511                         loc.extLength -= sb->s_blocksize;
1512                         loc.extLocation++;
1513                 }
1514
1515                 if (!final_bh)
1516                         return;
1517
1518                 brelse(sbi->s_lvid_bh);
1519                 sbi->s_lvid_bh = final_bh;
1520
1521                 lvid = (struct logicalVolIntegrityDesc *)final_bh->b_data;
1522                 if (lvid->nextIntegrityExt.extLength == 0)
1523                         return;
1524
1525                 loc = leea_to_cpu(lvid->nextIntegrityExt);
1526         }
1527
1528         udf_warn(sb, "Too many LVID indirections (max %u), ignoring.\n",
1529                 UDF_MAX_LVID_NESTING);
1530         brelse(sbi->s_lvid_bh);
1531         sbi->s_lvid_bh = NULL;
1532 }
1533
1534 /*
1535  * Step for reallocation of table of partition descriptor sequence numbers.
1536  * Must be power of 2.
1537  */
1538 #define PART_DESC_ALLOC_STEP 32
1539
1540 struct part_desc_seq_scan_data {
1541         struct udf_vds_record rec;
1542         u32 partnum;
1543 };
1544
1545 struct desc_seq_scan_data {
1546         struct udf_vds_record vds[VDS_POS_LENGTH];
1547         unsigned int size_part_descs;
1548         unsigned int num_part_descs;
1549         struct part_desc_seq_scan_data *part_descs_loc;
1550 };
1551
1552 static struct udf_vds_record *handle_partition_descriptor(
1553                                 struct buffer_head *bh,
1554                                 struct desc_seq_scan_data *data)
1555 {
1556         struct partitionDesc *desc = (struct partitionDesc *)bh->b_data;
1557         int partnum;
1558         int i;
1559
1560         partnum = le16_to_cpu(desc->partitionNumber);
1561         for (i = 0; i < data->num_part_descs; i++)
1562                 if (partnum == data->part_descs_loc[i].partnum)
1563                         return &(data->part_descs_loc[i].rec);
1564         if (data->num_part_descs >= data->size_part_descs) {
1565                 struct part_desc_seq_scan_data *new_loc;
1566                 unsigned int new_size = ALIGN(partnum, PART_DESC_ALLOC_STEP);
1567
1568                 new_loc = kcalloc(new_size, sizeof(*new_loc), GFP_KERNEL);
1569                 if (!new_loc)
1570                         return ERR_PTR(-ENOMEM);
1571                 memcpy(new_loc, data->part_descs_loc,
1572                        data->size_part_descs * sizeof(*new_loc));
1573                 kfree(data->part_descs_loc);
1574                 data->part_descs_loc = new_loc;
1575                 data->size_part_descs = new_size;
1576         }
1577         return &(data->part_descs_loc[data->num_part_descs++].rec);
1578 }
1579
1580
1581 static struct udf_vds_record *get_volume_descriptor_record(uint16_t ident,
1582                 struct buffer_head *bh, struct desc_seq_scan_data *data)
1583 {
1584         switch (ident) {
1585         case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
1586                 return &(data->vds[VDS_POS_PRIMARY_VOL_DESC]);
1587         case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
1588                 return &(data->vds[VDS_POS_IMP_USE_VOL_DESC]);
1589         case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
1590                 return &(data->vds[VDS_POS_LOGICAL_VOL_DESC]);
1591         case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
1592                 return &(data->vds[VDS_POS_UNALLOC_SPACE_DESC]);
1593         case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
1594                 return handle_partition_descriptor(bh, data);
1595         }
1596         return NULL;
1597 }
1598
1599 /*
1600  * Process a main/reserve volume descriptor sequence.
1601  *   @block             First block of first extent of the sequence.
1602  *   @lastblock         Lastblock of first extent of the sequence.
1603  *   @fileset           There we store extent containing root fileset
1604  *
1605  * Returns <0 on error, 0 on success. -EAGAIN is special - try next descriptor
1606  * sequence
1607  */
1608 static noinline int udf_process_sequence(
1609                 struct super_block *sb,
1610                 sector_t block, sector_t lastblock,
1611                 struct kernel_lb_addr *fileset)
1612 {
1613         struct buffer_head *bh = NULL;
1614         struct udf_vds_record *curr;
1615         struct generic_desc *gd;
1616         struct volDescPtr *vdp;
1617         bool done = false;
1618         uint32_t vdsn;
1619         uint16_t ident;
1620         int ret;
1621         unsigned int indirections = 0;
1622         struct desc_seq_scan_data data;
1623         unsigned int i;
1624
1625         memset(data.vds, 0, sizeof(struct udf_vds_record) * VDS_POS_LENGTH);
1626         data.size_part_descs = PART_DESC_ALLOC_STEP;
1627         data.num_part_descs = 0;
1628         data.part_descs_loc = kcalloc(data.size_part_descs,
1629                                       sizeof(*data.part_descs_loc),
1630                                       GFP_KERNEL);
1631         if (!data.part_descs_loc)
1632                 return -ENOMEM;
1633
1634         /*
1635          * Read the main descriptor sequence and find which descriptors
1636          * are in it.
1637          */
1638         for (; (!done && block <= lastblock); block++) {
1639                 bh = udf_read_tagged(sb, block, block, &ident);
1640                 if (!bh)
1641                         break;
1642
1643                 /* Process each descriptor (ISO 13346 3/8.3-8.4) */
1644                 gd = (struct generic_desc *)bh->b_data;
1645                 vdsn = le32_to_cpu(gd->volDescSeqNum);
1646                 switch (ident) {
1647                 case TAG_IDENT_VDP: /* ISO 13346 3/10.3 */
1648                         if (++indirections > UDF_MAX_TD_NESTING) {
1649                                 udf_err(sb, "too many Volume Descriptor "
1650                                         "Pointers (max %u supported)\n",
1651                                         UDF_MAX_TD_NESTING);
1652                                 brelse(bh);
1653                                 return -EIO;
1654                         }
1655
1656                         vdp = (struct volDescPtr *)bh->b_data;
1657                         block = le32_to_cpu(vdp->nextVolDescSeqExt.extLocation);
1658                         lastblock = le32_to_cpu(
1659                                 vdp->nextVolDescSeqExt.extLength) >>
1660                                 sb->s_blocksize_bits;
1661                         lastblock += block - 1;
1662                         /* For loop is going to increment 'block' again */
1663                         block--;
1664                         break;
1665                 case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
1666                 case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
1667                 case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
1668                 case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
1669                 case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
1670                         curr = get_volume_descriptor_record(ident, bh, &data);
1671                         if (IS_ERR(curr)) {
1672                                 brelse(bh);
1673                                 return PTR_ERR(curr);
1674                         }
1675                         /* Descriptor we don't care about? */
1676                         if (!curr)
1677                                 break;
1678                         if (vdsn >= curr->volDescSeqNum) {
1679                                 curr->volDescSeqNum = vdsn;
1680                                 curr->block = block;
1681                         }
1682                         break;
1683                 case TAG_IDENT_TD: /* ISO 13346 3/10.9 */
1684                         done = true;
1685                         break;
1686                 }
1687                 brelse(bh);
1688         }
1689         /*
1690          * Now read interesting descriptors again and process them
1691          * in a suitable order
1692          */
1693         if (!data.vds[VDS_POS_PRIMARY_VOL_DESC].block) {
1694                 udf_err(sb, "Primary Volume Descriptor not found!\n");
1695                 return -EAGAIN;
1696         }
1697         ret = udf_load_pvoldesc(sb, data.vds[VDS_POS_PRIMARY_VOL_DESC].block);
1698         if (ret < 0)
1699                 return ret;
1700
1701         if (data.vds[VDS_POS_LOGICAL_VOL_DESC].block) {
1702                 ret = udf_load_logicalvol(sb,
1703                                 data.vds[VDS_POS_LOGICAL_VOL_DESC].block,
1704                                 fileset);
1705                 if (ret < 0)
1706                         return ret;
1707         }
1708
1709         /* Now handle prevailing Partition Descriptors */
1710         for (i = 0; i < data.num_part_descs; i++) {
1711                 ret = udf_load_partdesc(sb, data.part_descs_loc[i].rec.block);
1712                 if (ret < 0)
1713                         return ret;
1714         }
1715
1716         return 0;
1717 }
1718
1719 /*
1720  * Load Volume Descriptor Sequence described by anchor in bh
1721  *
1722  * Returns <0 on error, 0 on success
1723  */
1724 static int udf_load_sequence(struct super_block *sb, struct buffer_head *bh,
1725                              struct kernel_lb_addr *fileset)
1726 {
1727         struct anchorVolDescPtr *anchor;
1728         sector_t main_s, main_e, reserve_s, reserve_e;
1729         int ret;
1730
1731         anchor = (struct anchorVolDescPtr *)bh->b_data;
1732
1733         /* Locate the main sequence */
1734         main_s = le32_to_cpu(anchor->mainVolDescSeqExt.extLocation);
1735         main_e = le32_to_cpu(anchor->mainVolDescSeqExt.extLength);
1736         main_e = main_e >> sb->s_blocksize_bits;
1737         main_e += main_s - 1;
1738
1739         /* Locate the reserve sequence */
1740         reserve_s = le32_to_cpu(anchor->reserveVolDescSeqExt.extLocation);
1741         reserve_e = le32_to_cpu(anchor->reserveVolDescSeqExt.extLength);
1742         reserve_e = reserve_e >> sb->s_blocksize_bits;
1743         reserve_e += reserve_s - 1;
1744
1745         /* Process the main & reserve sequences */
1746         /* responsible for finding the PartitionDesc(s) */
1747         ret = udf_process_sequence(sb, main_s, main_e, fileset);
1748         if (ret != -EAGAIN)
1749                 return ret;
1750         udf_sb_free_partitions(sb);
1751         ret = udf_process_sequence(sb, reserve_s, reserve_e, fileset);
1752         if (ret < 0) {
1753                 udf_sb_free_partitions(sb);
1754                 /* No sequence was OK, return -EIO */
1755                 if (ret == -EAGAIN)
1756                         ret = -EIO;
1757         }
1758         return ret;
1759 }
1760
1761 /*
1762  * Check whether there is an anchor block in the given block and
1763  * load Volume Descriptor Sequence if so.
1764  *
1765  * Returns <0 on error, 0 on success, -EAGAIN is special - try next anchor
1766  * block
1767  */
1768 static int udf_check_anchor_block(struct super_block *sb, sector_t block,
1769                                   struct kernel_lb_addr *fileset)
1770 {
1771         struct buffer_head *bh;
1772         uint16_t ident;
1773         int ret;
1774
1775         if (UDF_QUERY_FLAG(sb, UDF_FLAG_VARCONV) &&
1776             udf_fixed_to_variable(block) >=
1777             i_size_read(sb->s_bdev->bd_inode) >> sb->s_blocksize_bits)
1778                 return -EAGAIN;
1779
1780         bh = udf_read_tagged(sb, block, block, &ident);
1781         if (!bh)
1782                 return -EAGAIN;
1783         if (ident != TAG_IDENT_AVDP) {
1784                 brelse(bh);
1785                 return -EAGAIN;
1786         }
1787         ret = udf_load_sequence(sb, bh, fileset);
1788         brelse(bh);
1789         return ret;
1790 }
1791
1792 /*
1793  * Search for an anchor volume descriptor pointer.
1794  *
1795  * Returns < 0 on error, 0 on success. -EAGAIN is special - try next set
1796  * of anchors.
1797  */
1798 static int udf_scan_anchors(struct super_block *sb, sector_t *lastblock,
1799                             struct kernel_lb_addr *fileset)
1800 {
1801         sector_t last[6];
1802         int i;
1803         struct udf_sb_info *sbi = UDF_SB(sb);
1804         int last_count = 0;
1805         int ret;
1806
1807         /* First try user provided anchor */
1808         if (sbi->s_anchor) {
1809                 ret = udf_check_anchor_block(sb, sbi->s_anchor, fileset);
1810                 if (ret != -EAGAIN)
1811                         return ret;
1812         }
1813         /*
1814          * according to spec, anchor is in either:
1815          *     block 256
1816          *     lastblock-256
1817          *     lastblock
1818          *  however, if the disc isn't closed, it could be 512.
1819          */
1820         ret = udf_check_anchor_block(sb, sbi->s_session + 256, fileset);
1821         if (ret != -EAGAIN)
1822                 return ret;
1823         /*
1824          * The trouble is which block is the last one. Drives often misreport
1825          * this so we try various possibilities.
1826          */
1827         last[last_count++] = *lastblock;
1828         if (*lastblock >= 1)
1829                 last[last_count++] = *lastblock - 1;
1830         last[last_count++] = *lastblock + 1;
1831         if (*lastblock >= 2)
1832                 last[last_count++] = *lastblock - 2;
1833         if (*lastblock >= 150)
1834                 last[last_count++] = *lastblock - 150;
1835         if (*lastblock >= 152)
1836                 last[last_count++] = *lastblock - 152;
1837
1838         for (i = 0; i < last_count; i++) {
1839                 if (last[i] >= i_size_read(sb->s_bdev->bd_inode) >>
1840                                 sb->s_blocksize_bits)
1841                         continue;
1842                 ret = udf_check_anchor_block(sb, last[i], fileset);
1843                 if (ret != -EAGAIN) {
1844                         if (!ret)
1845                                 *lastblock = last[i];
1846                         return ret;
1847                 }
1848                 if (last[i] < 256)
1849                         continue;
1850                 ret = udf_check_anchor_block(sb, last[i] - 256, fileset);
1851                 if (ret != -EAGAIN) {
1852                         if (!ret)
1853                                 *lastblock = last[i];
1854                         return ret;
1855                 }
1856         }
1857
1858         /* Finally try block 512 in case media is open */
1859         return udf_check_anchor_block(sb, sbi->s_session + 512, fileset);
1860 }
1861
1862 /*
1863  * Find an anchor volume descriptor and load Volume Descriptor Sequence from
1864  * area specified by it. The function expects sbi->s_lastblock to be the last
1865  * block on the media.
1866  *
1867  * Return <0 on error, 0 if anchor found. -EAGAIN is special meaning anchor
1868  * was not found.
1869  */
1870 static int udf_find_anchor(struct super_block *sb,
1871                            struct kernel_lb_addr *fileset)
1872 {
1873         struct udf_sb_info *sbi = UDF_SB(sb);
1874         sector_t lastblock = sbi->s_last_block;
1875         int ret;
1876
1877         ret = udf_scan_anchors(sb, &lastblock, fileset);
1878         if (ret != -EAGAIN)
1879                 goto out;
1880
1881         /* No anchor found? Try VARCONV conversion of block numbers */
1882         UDF_SET_FLAG(sb, UDF_FLAG_VARCONV);
1883         lastblock = udf_variable_to_fixed(sbi->s_last_block);
1884         /* Firstly, we try to not convert number of the last block */
1885         ret = udf_scan_anchors(sb, &lastblock, fileset);
1886         if (ret != -EAGAIN)
1887                 goto out;
1888
1889         lastblock = sbi->s_last_block;
1890         /* Secondly, we try with converted number of the last block */
1891         ret = udf_scan_anchors(sb, &lastblock, fileset);
1892         if (ret < 0) {
1893                 /* VARCONV didn't help. Clear it. */
1894                 UDF_CLEAR_FLAG(sb, UDF_FLAG_VARCONV);
1895         }
1896 out:
1897         if (ret == 0)
1898                 sbi->s_last_block = lastblock;
1899         return ret;
1900 }
1901
1902 /*
1903  * Check Volume Structure Descriptor, find Anchor block and load Volume
1904  * Descriptor Sequence.
1905  *
1906  * Returns < 0 on error, 0 on success. -EAGAIN is special meaning anchor
1907  * block was not found.
1908  */
1909 static int udf_load_vrs(struct super_block *sb, struct udf_options *uopt,
1910                         int silent, struct kernel_lb_addr *fileset)
1911 {
1912         struct udf_sb_info *sbi = UDF_SB(sb);
1913         loff_t nsr_off;
1914         int ret;
1915
1916         if (!sb_set_blocksize(sb, uopt->blocksize)) {
1917                 if (!silent)
1918                         udf_warn(sb, "Bad block size\n");
1919                 return -EINVAL;
1920         }
1921         sbi->s_last_block = uopt->lastblock;
1922         if (!uopt->novrs) {
1923                 /* Check that it is NSR02 compliant */
1924                 nsr_off = udf_check_vsd(sb);
1925                 if (!nsr_off) {
1926                         if (!silent)
1927                                 udf_warn(sb, "No VRS found\n");
1928                         return -EINVAL;
1929                 }
1930                 if (nsr_off == -1)
1931                         udf_debug("Failed to read sector at offset %d. "
1932                                   "Assuming open disc. Skipping validity "
1933                                   "check\n", VSD_FIRST_SECTOR_OFFSET);
1934                 if (!sbi->s_last_block)
1935                         sbi->s_last_block = udf_get_last_block(sb);
1936         } else {
1937                 udf_debug("Validity check skipped because of novrs option\n");
1938         }
1939
1940         /* Look for anchor block and load Volume Descriptor Sequence */
1941         sbi->s_anchor = uopt->anchor;
1942         ret = udf_find_anchor(sb, fileset);
1943         if (ret < 0) {
1944                 if (!silent && ret == -EAGAIN)
1945                         udf_warn(sb, "No anchor found\n");
1946                 return ret;
1947         }
1948         return 0;
1949 }
1950
1951 static void udf_finalize_lvid(struct logicalVolIntegrityDesc *lvid)
1952 {
1953         struct timespec64 ts;
1954
1955         ktime_get_real_ts64(&ts);
1956         udf_time_to_disk_stamp(&lvid->recordingDateAndTime, ts);
1957         lvid->descTag.descCRC = cpu_to_le16(
1958                 crc_itu_t(0, (char *)lvid + sizeof(struct tag),
1959                         le16_to_cpu(lvid->descTag.descCRCLength)));
1960         lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag);
1961 }
1962
1963 static void udf_open_lvid(struct super_block *sb)
1964 {
1965         struct udf_sb_info *sbi = UDF_SB(sb);
1966         struct buffer_head *bh = sbi->s_lvid_bh;
1967         struct logicalVolIntegrityDesc *lvid;
1968         struct logicalVolIntegrityDescImpUse *lvidiu;
1969
1970         if (!bh)
1971                 return;
1972         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
1973         lvidiu = udf_sb_lvidiu(sb);
1974         if (!lvidiu)
1975                 return;
1976
1977         mutex_lock(&sbi->s_alloc_mutex);
1978         lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
1979         lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
1980         if (le32_to_cpu(lvid->integrityType) == LVID_INTEGRITY_TYPE_CLOSE)
1981                 lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_OPEN);
1982         else
1983                 UDF_SET_FLAG(sb, UDF_FLAG_INCONSISTENT);
1984
1985         udf_finalize_lvid(lvid);
1986         mark_buffer_dirty(bh);
1987         sbi->s_lvid_dirty = 0;
1988         mutex_unlock(&sbi->s_alloc_mutex);
1989         /* Make opening of filesystem visible on the media immediately */
1990         sync_dirty_buffer(bh);
1991 }
1992
1993 static void udf_close_lvid(struct super_block *sb)
1994 {
1995         struct udf_sb_info *sbi = UDF_SB(sb);
1996         struct buffer_head *bh = sbi->s_lvid_bh;
1997         struct logicalVolIntegrityDesc *lvid;
1998         struct logicalVolIntegrityDescImpUse *lvidiu;
1999
2000         if (!bh)
2001                 return;
2002         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2003         lvidiu = udf_sb_lvidiu(sb);
2004         if (!lvidiu)
2005                 return;
2006
2007         mutex_lock(&sbi->s_alloc_mutex);
2008         lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
2009         lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
2010         if (UDF_MAX_WRITE_VERSION > le16_to_cpu(lvidiu->maxUDFWriteRev))
2011                 lvidiu->maxUDFWriteRev = cpu_to_le16(UDF_MAX_WRITE_VERSION);
2012         if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFReadRev))
2013                 lvidiu->minUDFReadRev = cpu_to_le16(sbi->s_udfrev);
2014         if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFWriteRev))
2015                 lvidiu->minUDFWriteRev = cpu_to_le16(sbi->s_udfrev);
2016         if (!UDF_QUERY_FLAG(sb, UDF_FLAG_INCONSISTENT))
2017                 lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_CLOSE);
2018
2019         /*
2020          * We set buffer uptodate unconditionally here to avoid spurious
2021          * warnings from mark_buffer_dirty() when previous EIO has marked
2022          * the buffer as !uptodate
2023          */
2024         set_buffer_uptodate(bh);
2025         udf_finalize_lvid(lvid);
2026         mark_buffer_dirty(bh);
2027         sbi->s_lvid_dirty = 0;
2028         mutex_unlock(&sbi->s_alloc_mutex);
2029         /* Make closing of filesystem visible on the media immediately */
2030         sync_dirty_buffer(bh);
2031 }
2032
2033 u64 lvid_get_unique_id(struct super_block *sb)
2034 {
2035         struct buffer_head *bh;
2036         struct udf_sb_info *sbi = UDF_SB(sb);
2037         struct logicalVolIntegrityDesc *lvid;
2038         struct logicalVolHeaderDesc *lvhd;
2039         u64 uniqueID;
2040         u64 ret;
2041
2042         bh = sbi->s_lvid_bh;
2043         if (!bh)
2044                 return 0;
2045
2046         lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2047         lvhd = (struct logicalVolHeaderDesc *)lvid->logicalVolContentsUse;
2048
2049         mutex_lock(&sbi->s_alloc_mutex);
2050         ret = uniqueID = le64_to_cpu(lvhd->uniqueID);
2051         if (!(++uniqueID & 0xFFFFFFFF))
2052                 uniqueID += 16;
2053         lvhd->uniqueID = cpu_to_le64(uniqueID);
2054         udf_updated_lvid(sb);
2055         mutex_unlock(&sbi->s_alloc_mutex);
2056
2057         return ret;
2058 }
2059
2060 static int udf_fill_super(struct super_block *sb, void *options, int silent)
2061 {
2062         int ret = -EINVAL;
2063         struct inode *inode = NULL;
2064         struct udf_options uopt;
2065         struct kernel_lb_addr rootdir, fileset;
2066         struct udf_sb_info *sbi;
2067         bool lvid_open = false;
2068
2069         uopt.flags = (1 << UDF_FLAG_USE_AD_IN_ICB) | (1 << UDF_FLAG_STRICT);
2070         /* By default we'll use overflow[ug]id when UDF inode [ug]id == -1 */
2071         uopt.uid = make_kuid(current_user_ns(), overflowuid);
2072         uopt.gid = make_kgid(current_user_ns(), overflowgid);
2073         uopt.umask = 0;
2074         uopt.fmode = UDF_INVALID_MODE;
2075         uopt.dmode = UDF_INVALID_MODE;
2076         uopt.nls_map = NULL;
2077
2078         sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
2079         if (!sbi)
2080                 return -ENOMEM;
2081
2082         sb->s_fs_info = sbi;
2083
2084         mutex_init(&sbi->s_alloc_mutex);
2085
2086         if (!udf_parse_options((char *)options, &uopt, false))
2087                 goto parse_options_failure;
2088
2089         if (uopt.flags & (1 << UDF_FLAG_UTF8) &&
2090             uopt.flags & (1 << UDF_FLAG_NLS_MAP)) {
2091                 udf_err(sb, "utf8 cannot be combined with iocharset\n");
2092                 goto parse_options_failure;
2093         }
2094         if ((uopt.flags & (1 << UDF_FLAG_NLS_MAP)) && !uopt.nls_map) {
2095                 uopt.nls_map = load_nls_default();
2096                 if (!uopt.nls_map)
2097                         uopt.flags &= ~(1 << UDF_FLAG_NLS_MAP);
2098                 else
2099                         udf_debug("Using default NLS map\n");
2100         }
2101         if (!(uopt.flags & (1 << UDF_FLAG_NLS_MAP)))
2102                 uopt.flags |= (1 << UDF_FLAG_UTF8);
2103
2104         fileset.logicalBlockNum = 0xFFFFFFFF;
2105         fileset.partitionReferenceNum = 0xFFFF;
2106
2107         sbi->s_flags = uopt.flags;
2108         sbi->s_uid = uopt.uid;
2109         sbi->s_gid = uopt.gid;
2110         sbi->s_umask = uopt.umask;
2111         sbi->s_fmode = uopt.fmode;
2112         sbi->s_dmode = uopt.dmode;
2113         sbi->s_nls_map = uopt.nls_map;
2114         rwlock_init(&sbi->s_cred_lock);
2115
2116         if (uopt.session == 0xFFFFFFFF)
2117                 sbi->s_session = udf_get_last_session(sb);
2118         else
2119                 sbi->s_session = uopt.session;
2120
2121         udf_debug("Multi-session=%d\n", sbi->s_session);
2122
2123         /* Fill in the rest of the superblock */
2124         sb->s_op = &udf_sb_ops;
2125         sb->s_export_op = &udf_export_ops;
2126
2127         sb->s_magic = UDF_SUPER_MAGIC;
2128         sb->s_time_gran = 1000;
2129
2130         if (uopt.flags & (1 << UDF_FLAG_BLOCKSIZE_SET)) {
2131                 ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2132         } else {
2133                 uopt.blocksize = bdev_logical_block_size(sb->s_bdev);
2134                 while (uopt.blocksize <= 4096) {
2135                         ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2136                         if (ret < 0) {
2137                                 if (!silent && ret != -EACCES) {
2138                                         pr_notice("Scanning with blocksize %u failed\n",
2139                                                   uopt.blocksize);
2140                                 }
2141                                 brelse(sbi->s_lvid_bh);
2142                                 sbi->s_lvid_bh = NULL;
2143                                 /*
2144                                  * EACCES is special - we want to propagate to
2145                                  * upper layers that we cannot handle RW mount.
2146                                  */
2147                                 if (ret == -EACCES)
2148                                         break;
2149                         } else
2150                                 break;
2151
2152                         uopt.blocksize <<= 1;
2153                 }
2154         }
2155         if (ret < 0) {
2156                 if (ret == -EAGAIN) {
2157                         udf_warn(sb, "No partition found (1)\n");
2158                         ret = -EINVAL;
2159                 }
2160                 goto error_out;
2161         }
2162
2163         udf_debug("Lastblock=%u\n", sbi->s_last_block);
2164
2165         if (sbi->s_lvid_bh) {
2166                 struct logicalVolIntegrityDescImpUse *lvidiu =
2167                                                         udf_sb_lvidiu(sb);
2168                 uint16_t minUDFReadRev;
2169                 uint16_t minUDFWriteRev;
2170
2171                 if (!lvidiu) {
2172                         ret = -EINVAL;
2173                         goto error_out;
2174                 }
2175                 minUDFReadRev = le16_to_cpu(lvidiu->minUDFReadRev);
2176                 minUDFWriteRev = le16_to_cpu(lvidiu->minUDFWriteRev);
2177                 if (minUDFReadRev > UDF_MAX_READ_VERSION) {
2178                         udf_err(sb, "minUDFReadRev=%x (max is %x)\n",
2179                                 minUDFReadRev,
2180                                 UDF_MAX_READ_VERSION);
2181                         ret = -EINVAL;
2182                         goto error_out;
2183                 } else if (minUDFWriteRev > UDF_MAX_WRITE_VERSION) {
2184                         if (!sb_rdonly(sb)) {
2185                                 ret = -EACCES;
2186                                 goto error_out;
2187                         }
2188                         UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
2189                 }
2190
2191                 sbi->s_udfrev = minUDFWriteRev;
2192
2193                 if (minUDFReadRev >= UDF_VERS_USE_EXTENDED_FE)
2194                         UDF_SET_FLAG(sb, UDF_FLAG_USE_EXTENDED_FE);
2195                 if (minUDFReadRev >= UDF_VERS_USE_STREAMS)
2196                         UDF_SET_FLAG(sb, UDF_FLAG_USE_STREAMS);
2197         }
2198
2199         if (!sbi->s_partitions) {
2200                 udf_warn(sb, "No partition found (2)\n");
2201                 ret = -EINVAL;
2202                 goto error_out;
2203         }
2204
2205         if (sbi->s_partmaps[sbi->s_partition].s_partition_flags &
2206                         UDF_PART_FLAG_READ_ONLY) {
2207                 if (!sb_rdonly(sb)) {
2208                         ret = -EACCES;
2209                         goto error_out;
2210                 }
2211                 UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
2212         }
2213
2214         if (udf_find_fileset(sb, &fileset, &rootdir)) {
2215                 udf_warn(sb, "No fileset found\n");
2216                 ret = -EINVAL;
2217                 goto error_out;
2218         }
2219
2220         if (!silent) {
2221                 struct timestamp ts;
2222                 udf_time_to_disk_stamp(&ts, sbi->s_record_time);
2223                 udf_info("Mounting volume '%s', timestamp %04u/%02u/%02u %02u:%02u (%x)\n",
2224                          sbi->s_volume_ident,
2225                          le16_to_cpu(ts.year), ts.month, ts.day,
2226                          ts.hour, ts.minute, le16_to_cpu(ts.typeAndTimezone));
2227         }
2228         if (!sb_rdonly(sb)) {
2229                 udf_open_lvid(sb);
2230                 lvid_open = true;
2231         }
2232
2233         /* Assign the root inode */
2234         /* assign inodes by physical block number */
2235         /* perhaps it's not extensible enough, but for now ... */
2236         inode = udf_iget(sb, &rootdir);
2237         if (IS_ERR(inode)) {
2238                 udf_err(sb, "Error in udf_iget, block=%u, partition=%u\n",
2239                        rootdir.logicalBlockNum, rootdir.partitionReferenceNum);
2240                 ret = PTR_ERR(inode);
2241                 goto error_out;
2242         }
2243
2244         /* Allocate a dentry for the root inode */
2245         sb->s_root = d_make_root(inode);
2246         if (!sb->s_root) {
2247                 udf_err(sb, "Couldn't allocate root dentry\n");
2248                 ret = -ENOMEM;
2249                 goto error_out;
2250         }
2251         sb->s_maxbytes = MAX_LFS_FILESIZE;
2252         sb->s_max_links = UDF_MAX_LINKS;
2253         return 0;
2254
2255 error_out:
2256         iput(sbi->s_vat_inode);
2257 parse_options_failure:
2258         if (uopt.nls_map)
2259                 unload_nls(uopt.nls_map);
2260         if (lvid_open)
2261                 udf_close_lvid(sb);
2262         brelse(sbi->s_lvid_bh);
2263         udf_sb_free_partitions(sb);
2264         kfree(sbi);
2265         sb->s_fs_info = NULL;
2266
2267         return ret;
2268 }
2269
2270 void _udf_err(struct super_block *sb, const char *function,
2271               const char *fmt, ...)
2272 {
2273         struct va_format vaf;
2274         va_list args;
2275
2276         va_start(args, fmt);
2277
2278         vaf.fmt = fmt;
2279         vaf.va = &args;
2280
2281         pr_err("error (device %s): %s: %pV", sb->s_id, function, &vaf);
2282
2283         va_end(args);
2284 }
2285
2286 void _udf_warn(struct super_block *sb, const char *function,
2287                const char *fmt, ...)
2288 {
2289         struct va_format vaf;
2290         va_list args;
2291
2292         va_start(args, fmt);
2293
2294         vaf.fmt = fmt;
2295         vaf.va = &args;
2296
2297         pr_warn("warning (device %s): %s: %pV", sb->s_id, function, &vaf);
2298
2299         va_end(args);
2300 }
2301
2302 static void udf_put_super(struct super_block *sb)
2303 {
2304         struct udf_sb_info *sbi;
2305
2306         sbi = UDF_SB(sb);
2307
2308         iput(sbi->s_vat_inode);
2309         if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP))
2310                 unload_nls(sbi->s_nls_map);
2311         if (!sb_rdonly(sb))
2312                 udf_close_lvid(sb);
2313         brelse(sbi->s_lvid_bh);
2314         udf_sb_free_partitions(sb);
2315         mutex_destroy(&sbi->s_alloc_mutex);
2316         kfree(sb->s_fs_info);
2317         sb->s_fs_info = NULL;
2318 }
2319
2320 static int udf_sync_fs(struct super_block *sb, int wait)
2321 {
2322         struct udf_sb_info *sbi = UDF_SB(sb);
2323
2324         mutex_lock(&sbi->s_alloc_mutex);
2325         if (sbi->s_lvid_dirty) {
2326                 struct buffer_head *bh = sbi->s_lvid_bh;
2327                 struct logicalVolIntegrityDesc *lvid;
2328
2329                 lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2330                 udf_finalize_lvid(lvid);
2331
2332                 /*
2333                  * Blockdevice will be synced later so we don't have to submit
2334                  * the buffer for IO
2335                  */
2336                 mark_buffer_dirty(bh);
2337                 sbi->s_lvid_dirty = 0;
2338         }
2339         mutex_unlock(&sbi->s_alloc_mutex);
2340
2341         return 0;
2342 }
2343
2344 static int udf_statfs(struct dentry *dentry, struct kstatfs *buf)
2345 {
2346         struct super_block *sb = dentry->d_sb;
2347         struct udf_sb_info *sbi = UDF_SB(sb);
2348         struct logicalVolIntegrityDescImpUse *lvidiu;
2349         u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
2350
2351         lvidiu = udf_sb_lvidiu(sb);
2352         buf->f_type = UDF_SUPER_MAGIC;
2353         buf->f_bsize = sb->s_blocksize;
2354         buf->f_blocks = sbi->s_partmaps[sbi->s_partition].s_partition_len;
2355         buf->f_bfree = udf_count_free(sb);
2356         buf->f_bavail = buf->f_bfree;
2357         buf->f_files = (lvidiu != NULL ? (le32_to_cpu(lvidiu->numFiles) +
2358                                           le32_to_cpu(lvidiu->numDirs)) : 0)
2359                         + buf->f_bfree;
2360         buf->f_ffree = buf->f_bfree;
2361         buf->f_namelen = UDF_NAME_LEN;
2362         buf->f_fsid.val[0] = (u32)id;
2363         buf->f_fsid.val[1] = (u32)(id >> 32);
2364
2365         return 0;
2366 }
2367
2368 static unsigned int udf_count_free_bitmap(struct super_block *sb,
2369                                           struct udf_bitmap *bitmap)
2370 {
2371         struct buffer_head *bh = NULL;
2372         unsigned int accum = 0;
2373         int index;
2374         udf_pblk_t block = 0, newblock;
2375         struct kernel_lb_addr loc;
2376         uint32_t bytes;
2377         uint8_t *ptr;
2378         uint16_t ident;
2379         struct spaceBitmapDesc *bm;
2380
2381         loc.logicalBlockNum = bitmap->s_extPosition;
2382         loc.partitionReferenceNum = UDF_SB(sb)->s_partition;
2383         bh = udf_read_ptagged(sb, &loc, 0, &ident);
2384
2385         if (!bh) {
2386                 udf_err(sb, "udf_count_free failed\n");
2387                 goto out;
2388         } else if (ident != TAG_IDENT_SBD) {
2389                 brelse(bh);
2390                 udf_err(sb, "udf_count_free failed\n");
2391                 goto out;
2392         }
2393
2394         bm = (struct spaceBitmapDesc *)bh->b_data;
2395         bytes = le32_to_cpu(bm->numOfBytes);
2396         index = sizeof(struct spaceBitmapDesc); /* offset in first block only */
2397         ptr = (uint8_t *)bh->b_data;
2398
2399         while (bytes > 0) {
2400                 u32 cur_bytes = min_t(u32, bytes, sb->s_blocksize - index);
2401                 accum += bitmap_weight((const unsigned long *)(ptr + index),
2402                                         cur_bytes * 8);
2403                 bytes -= cur_bytes;
2404                 if (bytes) {
2405                         brelse(bh);
2406                         newblock = udf_get_lb_pblock(sb, &loc, ++block);
2407                         bh = udf_tread(sb, newblock);
2408                         if (!bh) {
2409                                 udf_debug("read failed\n");
2410                                 goto out;
2411                         }
2412                         index = 0;
2413                         ptr = (uint8_t *)bh->b_data;
2414                 }
2415         }
2416         brelse(bh);
2417 out:
2418         return accum;
2419 }
2420
2421 static unsigned int udf_count_free_table(struct super_block *sb,
2422                                          struct inode *table)
2423 {
2424         unsigned int accum = 0;
2425         uint32_t elen;
2426         struct kernel_lb_addr eloc;
2427         int8_t etype;
2428         struct extent_position epos;
2429
2430         mutex_lock(&UDF_SB(sb)->s_alloc_mutex);
2431         epos.block = UDF_I(table)->i_location;
2432         epos.offset = sizeof(struct unallocSpaceEntry);
2433         epos.bh = NULL;
2434
2435         while ((etype = udf_next_aext(table, &epos, &eloc, &elen, 1)) != -1)
2436                 accum += (elen >> table->i_sb->s_blocksize_bits);
2437
2438         brelse(epos.bh);
2439         mutex_unlock(&UDF_SB(sb)->s_alloc_mutex);
2440
2441         return accum;
2442 }
2443
2444 static unsigned int udf_count_free(struct super_block *sb)
2445 {
2446         unsigned int accum = 0;
2447         struct udf_sb_info *sbi;
2448         struct udf_part_map *map;
2449
2450         sbi = UDF_SB(sb);
2451         if (sbi->s_lvid_bh) {
2452                 struct logicalVolIntegrityDesc *lvid =
2453                         (struct logicalVolIntegrityDesc *)
2454                         sbi->s_lvid_bh->b_data;
2455                 if (le32_to_cpu(lvid->numOfPartitions) > sbi->s_partition) {
2456                         accum = le32_to_cpu(
2457                                         lvid->freeSpaceTable[sbi->s_partition]);
2458                         if (accum == 0xFFFFFFFF)
2459                                 accum = 0;
2460                 }
2461         }
2462
2463         if (accum)
2464                 return accum;
2465
2466         map = &sbi->s_partmaps[sbi->s_partition];
2467         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) {
2468                 accum += udf_count_free_bitmap(sb,
2469                                                map->s_uspace.s_bitmap);
2470         }
2471         if (accum)
2472                 return accum;
2473
2474         if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) {
2475                 accum += udf_count_free_table(sb,
2476                                               map->s_uspace.s_table);
2477         }
2478         return accum;
2479 }
2480
2481 MODULE_AUTHOR("Ben Fennema");
2482 MODULE_DESCRIPTION("Universal Disk Format Filesystem");
2483 MODULE_LICENSE("GPL");
2484 module_init(init_udf_fs)
2485 module_exit(exit_udf_fs)