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