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