OSDN Git Service

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