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