xref: /openbmc/linux/fs/udf/super.c (revision 80d0624d)
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 	int err;
1084 
1085 	map = &sbi->s_partmaps[p_index];
1086 
1087 	map->s_partition_len = le32_to_cpu(p->partitionLength); /* blocks */
1088 	map->s_partition_root = le32_to_cpu(p->partitionStartingLocation);
1089 
1090 	if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_READ_ONLY))
1091 		map->s_partition_flags |= UDF_PART_FLAG_READ_ONLY;
1092 	if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_WRITE_ONCE))
1093 		map->s_partition_flags |= UDF_PART_FLAG_WRITE_ONCE;
1094 	if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_REWRITABLE))
1095 		map->s_partition_flags |= UDF_PART_FLAG_REWRITABLE;
1096 	if (p->accessType == cpu_to_le32(PD_ACCESS_TYPE_OVERWRITABLE))
1097 		map->s_partition_flags |= UDF_PART_FLAG_OVERWRITABLE;
1098 
1099 	udf_debug("Partition (%d type %x) starts at physical %u, block length %u\n",
1100 		  p_index, map->s_partition_type,
1101 		  map->s_partition_root, map->s_partition_len);
1102 
1103 	err = check_partition_desc(sb, p, map);
1104 	if (err)
1105 		return err;
1106 
1107 	/*
1108 	 * Skip loading allocation info it we cannot ever write to the fs.
1109 	 * This is a correctness thing as we may have decided to force ro mount
1110 	 * to avoid allocation info we don't support.
1111 	 */
1112 	if (UDF_QUERY_FLAG(sb, UDF_FLAG_RW_INCOMPAT))
1113 		return 0;
1114 
1115 	phd = (struct partitionHeaderDesc *)p->partitionContentsUse;
1116 	if (phd->unallocSpaceTable.extLength) {
1117 		struct kernel_lb_addr loc = {
1118 			.logicalBlockNum = le32_to_cpu(
1119 				phd->unallocSpaceTable.extPosition),
1120 			.partitionReferenceNum = p_index,
1121 		};
1122 		struct inode *inode;
1123 
1124 		inode = udf_iget_special(sb, &loc);
1125 		if (IS_ERR(inode)) {
1126 			udf_debug("cannot load unallocSpaceTable (part %d)\n",
1127 				  p_index);
1128 			return PTR_ERR(inode);
1129 		}
1130 		map->s_uspace.s_table = inode;
1131 		map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_TABLE;
1132 		udf_debug("unallocSpaceTable (part %d) @ %lu\n",
1133 			  p_index, map->s_uspace.s_table->i_ino);
1134 	}
1135 
1136 	if (phd->unallocSpaceBitmap.extLength) {
1137 		struct udf_bitmap *bitmap = udf_sb_alloc_bitmap(sb, p_index);
1138 		if (!bitmap)
1139 			return -ENOMEM;
1140 		map->s_uspace.s_bitmap = bitmap;
1141 		bitmap->s_extPosition = le32_to_cpu(
1142 				phd->unallocSpaceBitmap.extPosition);
1143 		map->s_partition_flags |= UDF_PART_FLAG_UNALLOC_BITMAP;
1144 		udf_debug("unallocSpaceBitmap (part %d) @ %u\n",
1145 			  p_index, bitmap->s_extPosition);
1146 	}
1147 
1148 	return 0;
1149 }
1150 
1151 static void udf_find_vat_block(struct super_block *sb, int p_index,
1152 			       int type1_index, sector_t start_block)
1153 {
1154 	struct udf_sb_info *sbi = UDF_SB(sb);
1155 	struct udf_part_map *map = &sbi->s_partmaps[p_index];
1156 	sector_t vat_block;
1157 	struct kernel_lb_addr ino;
1158 	struct inode *inode;
1159 
1160 	/*
1161 	 * VAT file entry is in the last recorded block. Some broken disks have
1162 	 * it a few blocks before so try a bit harder...
1163 	 */
1164 	ino.partitionReferenceNum = type1_index;
1165 	for (vat_block = start_block;
1166 	     vat_block >= map->s_partition_root &&
1167 	     vat_block >= start_block - 3; vat_block--) {
1168 		ino.logicalBlockNum = vat_block - map->s_partition_root;
1169 		inode = udf_iget_special(sb, &ino);
1170 		if (!IS_ERR(inode)) {
1171 			sbi->s_vat_inode = inode;
1172 			break;
1173 		}
1174 	}
1175 }
1176 
1177 static int udf_load_vat(struct super_block *sb, int p_index, int type1_index)
1178 {
1179 	struct udf_sb_info *sbi = UDF_SB(sb);
1180 	struct udf_part_map *map = &sbi->s_partmaps[p_index];
1181 	struct buffer_head *bh = NULL;
1182 	struct udf_inode_info *vati;
1183 	struct virtualAllocationTable20 *vat20;
1184 	sector_t blocks = sb_bdev_nr_blocks(sb);
1185 
1186 	udf_find_vat_block(sb, p_index, type1_index, sbi->s_last_block);
1187 	if (!sbi->s_vat_inode &&
1188 	    sbi->s_last_block != blocks - 1) {
1189 		pr_notice("Failed to read VAT inode from the last recorded block (%lu), retrying with the last block of the device (%lu).\n",
1190 			  (unsigned long)sbi->s_last_block,
1191 			  (unsigned long)blocks - 1);
1192 		udf_find_vat_block(sb, p_index, type1_index, blocks - 1);
1193 	}
1194 	if (!sbi->s_vat_inode)
1195 		return -EIO;
1196 
1197 	if (map->s_partition_type == UDF_VIRTUAL_MAP15) {
1198 		map->s_type_specific.s_virtual.s_start_offset = 0;
1199 		map->s_type_specific.s_virtual.s_num_entries =
1200 			(sbi->s_vat_inode->i_size - 36) >> 2;
1201 	} else if (map->s_partition_type == UDF_VIRTUAL_MAP20) {
1202 		vati = UDF_I(sbi->s_vat_inode);
1203 		if (vati->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) {
1204 			int err = 0;
1205 
1206 			bh = udf_bread(sbi->s_vat_inode, 0, 0, &err);
1207 			if (!bh) {
1208 				if (!err)
1209 					err = -EFSCORRUPTED;
1210 				return err;
1211 			}
1212 			vat20 = (struct virtualAllocationTable20 *)bh->b_data;
1213 		} else {
1214 			vat20 = (struct virtualAllocationTable20 *)
1215 							vati->i_data;
1216 		}
1217 
1218 		map->s_type_specific.s_virtual.s_start_offset =
1219 			le16_to_cpu(vat20->lengthHeader);
1220 		map->s_type_specific.s_virtual.s_num_entries =
1221 			(sbi->s_vat_inode->i_size -
1222 				map->s_type_specific.s_virtual.
1223 					s_start_offset) >> 2;
1224 		brelse(bh);
1225 	}
1226 	return 0;
1227 }
1228 
1229 /*
1230  * Load partition descriptor block
1231  *
1232  * Returns <0 on error, 0 on success, -EAGAIN is special - try next descriptor
1233  * sequence.
1234  */
1235 static int udf_load_partdesc(struct super_block *sb, sector_t block)
1236 {
1237 	struct buffer_head *bh;
1238 	struct partitionDesc *p;
1239 	struct udf_part_map *map;
1240 	struct udf_sb_info *sbi = UDF_SB(sb);
1241 	int i, type1_idx;
1242 	uint16_t partitionNumber;
1243 	uint16_t ident;
1244 	int ret;
1245 
1246 	bh = udf_read_tagged(sb, block, block, &ident);
1247 	if (!bh)
1248 		return -EAGAIN;
1249 	if (ident != TAG_IDENT_PD) {
1250 		ret = 0;
1251 		goto out_bh;
1252 	}
1253 
1254 	p = (struct partitionDesc *)bh->b_data;
1255 	partitionNumber = le16_to_cpu(p->partitionNumber);
1256 
1257 	/* First scan for TYPE1 and SPARABLE partitions */
1258 	for (i = 0; i < sbi->s_partitions; i++) {
1259 		map = &sbi->s_partmaps[i];
1260 		udf_debug("Searching map: (%u == %u)\n",
1261 			  map->s_partition_num, partitionNumber);
1262 		if (map->s_partition_num == partitionNumber &&
1263 		    (map->s_partition_type == UDF_TYPE1_MAP15 ||
1264 		     map->s_partition_type == UDF_SPARABLE_MAP15))
1265 			break;
1266 	}
1267 
1268 	if (i >= sbi->s_partitions) {
1269 		udf_debug("Partition (%u) not found in partition map\n",
1270 			  partitionNumber);
1271 		ret = 0;
1272 		goto out_bh;
1273 	}
1274 
1275 	ret = udf_fill_partdesc_info(sb, p, i);
1276 	if (ret < 0)
1277 		goto out_bh;
1278 
1279 	/*
1280 	 * Now rescan for VIRTUAL or METADATA partitions when SPARABLE and
1281 	 * PHYSICAL partitions are already set up
1282 	 */
1283 	type1_idx = i;
1284 	map = NULL; /* supress 'maybe used uninitialized' warning */
1285 	for (i = 0; i < sbi->s_partitions; i++) {
1286 		map = &sbi->s_partmaps[i];
1287 
1288 		if (map->s_partition_num == partitionNumber &&
1289 		    (map->s_partition_type == UDF_VIRTUAL_MAP15 ||
1290 		     map->s_partition_type == UDF_VIRTUAL_MAP20 ||
1291 		     map->s_partition_type == UDF_METADATA_MAP25))
1292 			break;
1293 	}
1294 
1295 	if (i >= sbi->s_partitions) {
1296 		ret = 0;
1297 		goto out_bh;
1298 	}
1299 
1300 	ret = udf_fill_partdesc_info(sb, p, i);
1301 	if (ret < 0)
1302 		goto out_bh;
1303 
1304 	if (map->s_partition_type == UDF_METADATA_MAP25) {
1305 		ret = udf_load_metadata_files(sb, i, type1_idx);
1306 		if (ret < 0) {
1307 			udf_err(sb, "error loading MetaData partition map %d\n",
1308 				i);
1309 			goto out_bh;
1310 		}
1311 	} else {
1312 		/*
1313 		 * If we have a partition with virtual map, we don't handle
1314 		 * writing to it (we overwrite blocks instead of relocating
1315 		 * them).
1316 		 */
1317 		if (!sb_rdonly(sb)) {
1318 			ret = -EACCES;
1319 			goto out_bh;
1320 		}
1321 		UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
1322 		ret = udf_load_vat(sb, i, type1_idx);
1323 		if (ret < 0)
1324 			goto out_bh;
1325 	}
1326 	ret = 0;
1327 out_bh:
1328 	/* In case loading failed, we handle cleanup in udf_fill_super */
1329 	brelse(bh);
1330 	return ret;
1331 }
1332 
1333 static int udf_load_sparable_map(struct super_block *sb,
1334 				 struct udf_part_map *map,
1335 				 struct sparablePartitionMap *spm)
1336 {
1337 	uint32_t loc;
1338 	uint16_t ident;
1339 	struct sparingTable *st;
1340 	struct udf_sparing_data *sdata = &map->s_type_specific.s_sparing;
1341 	int i;
1342 	struct buffer_head *bh;
1343 
1344 	map->s_partition_type = UDF_SPARABLE_MAP15;
1345 	sdata->s_packet_len = le16_to_cpu(spm->packetLength);
1346 	if (!is_power_of_2(sdata->s_packet_len)) {
1347 		udf_err(sb, "error loading logical volume descriptor: "
1348 			"Invalid packet length %u\n",
1349 			(unsigned)sdata->s_packet_len);
1350 		return -EIO;
1351 	}
1352 	if (spm->numSparingTables > 4) {
1353 		udf_err(sb, "error loading logical volume descriptor: "
1354 			"Too many sparing tables (%d)\n",
1355 			(int)spm->numSparingTables);
1356 		return -EIO;
1357 	}
1358 	if (le32_to_cpu(spm->sizeSparingTable) > sb->s_blocksize) {
1359 		udf_err(sb, "error loading logical volume descriptor: "
1360 			"Too big sparing table size (%u)\n",
1361 			le32_to_cpu(spm->sizeSparingTable));
1362 		return -EIO;
1363 	}
1364 
1365 	for (i = 0; i < spm->numSparingTables; i++) {
1366 		loc = le32_to_cpu(spm->locSparingTable[i]);
1367 		bh = udf_read_tagged(sb, loc, loc, &ident);
1368 		if (!bh)
1369 			continue;
1370 
1371 		st = (struct sparingTable *)bh->b_data;
1372 		if (ident != 0 ||
1373 		    strncmp(st->sparingIdent.ident, UDF_ID_SPARING,
1374 			    strlen(UDF_ID_SPARING)) ||
1375 		    sizeof(*st) + le16_to_cpu(st->reallocationTableLen) >
1376 							sb->s_blocksize) {
1377 			brelse(bh);
1378 			continue;
1379 		}
1380 
1381 		sdata->s_spar_map[i] = bh;
1382 	}
1383 	map->s_partition_func = udf_get_pblock_spar15;
1384 	return 0;
1385 }
1386 
1387 static int udf_load_logicalvol(struct super_block *sb, sector_t block,
1388 			       struct kernel_lb_addr *fileset)
1389 {
1390 	struct logicalVolDesc *lvd;
1391 	int i, offset;
1392 	uint8_t type;
1393 	struct udf_sb_info *sbi = UDF_SB(sb);
1394 	struct genericPartitionMap *gpm;
1395 	uint16_t ident;
1396 	struct buffer_head *bh;
1397 	unsigned int table_len;
1398 	int ret;
1399 
1400 	bh = udf_read_tagged(sb, block, block, &ident);
1401 	if (!bh)
1402 		return -EAGAIN;
1403 	BUG_ON(ident != TAG_IDENT_LVD);
1404 	lvd = (struct logicalVolDesc *)bh->b_data;
1405 	table_len = le32_to_cpu(lvd->mapTableLength);
1406 	if (table_len > sb->s_blocksize - sizeof(*lvd)) {
1407 		udf_err(sb, "error loading logical volume descriptor: "
1408 			"Partition table too long (%u > %lu)\n", table_len,
1409 			sb->s_blocksize - sizeof(*lvd));
1410 		ret = -EIO;
1411 		goto out_bh;
1412 	}
1413 
1414 	ret = udf_verify_domain_identifier(sb, &lvd->domainIdent,
1415 					   "logical volume");
1416 	if (ret)
1417 		goto out_bh;
1418 	ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
1419 	if (ret)
1420 		goto out_bh;
1421 
1422 	for (i = 0, offset = 0;
1423 	     i < sbi->s_partitions && offset < table_len;
1424 	     i++, offset += gpm->partitionMapLength) {
1425 		struct udf_part_map *map = &sbi->s_partmaps[i];
1426 		gpm = (struct genericPartitionMap *)
1427 				&(lvd->partitionMaps[offset]);
1428 		type = gpm->partitionMapType;
1429 		if (type == 1) {
1430 			struct genericPartitionMap1 *gpm1 =
1431 				(struct genericPartitionMap1 *)gpm;
1432 			map->s_partition_type = UDF_TYPE1_MAP15;
1433 			map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
1434 			map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
1435 			map->s_partition_func = NULL;
1436 		} else if (type == 2) {
1437 			struct udfPartitionMap2 *upm2 =
1438 						(struct udfPartitionMap2 *)gpm;
1439 			if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
1440 						strlen(UDF_ID_VIRTUAL))) {
1441 				u16 suf =
1442 					le16_to_cpu(((__le16 *)upm2->partIdent.
1443 							identSuffix)[0]);
1444 				if (suf < 0x0200) {
1445 					map->s_partition_type =
1446 							UDF_VIRTUAL_MAP15;
1447 					map->s_partition_func =
1448 							udf_get_pblock_virt15;
1449 				} else {
1450 					map->s_partition_type =
1451 							UDF_VIRTUAL_MAP20;
1452 					map->s_partition_func =
1453 							udf_get_pblock_virt20;
1454 				}
1455 			} else if (!strncmp(upm2->partIdent.ident,
1456 						UDF_ID_SPARABLE,
1457 						strlen(UDF_ID_SPARABLE))) {
1458 				ret = udf_load_sparable_map(sb, map,
1459 					(struct sparablePartitionMap *)gpm);
1460 				if (ret < 0)
1461 					goto out_bh;
1462 			} else if (!strncmp(upm2->partIdent.ident,
1463 						UDF_ID_METADATA,
1464 						strlen(UDF_ID_METADATA))) {
1465 				struct udf_meta_data *mdata =
1466 					&map->s_type_specific.s_metadata;
1467 				struct metadataPartitionMap *mdm =
1468 						(struct metadataPartitionMap *)
1469 						&(lvd->partitionMaps[offset]);
1470 				udf_debug("Parsing Logical vol part %d type %u  id=%s\n",
1471 					  i, type, UDF_ID_METADATA);
1472 
1473 				map->s_partition_type = UDF_METADATA_MAP25;
1474 				map->s_partition_func = udf_get_pblock_meta25;
1475 
1476 				mdata->s_meta_file_loc   =
1477 					le32_to_cpu(mdm->metadataFileLoc);
1478 				mdata->s_mirror_file_loc =
1479 					le32_to_cpu(mdm->metadataMirrorFileLoc);
1480 				mdata->s_bitmap_file_loc =
1481 					le32_to_cpu(mdm->metadataBitmapFileLoc);
1482 				mdata->s_alloc_unit_size =
1483 					le32_to_cpu(mdm->allocUnitSize);
1484 				mdata->s_align_unit_size =
1485 					le16_to_cpu(mdm->alignUnitSize);
1486 				if (mdm->flags & 0x01)
1487 					mdata->s_flags |= MF_DUPLICATE_MD;
1488 
1489 				udf_debug("Metadata Ident suffix=0x%x\n",
1490 					  le16_to_cpu(*(__le16 *)
1491 						      mdm->partIdent.identSuffix));
1492 				udf_debug("Metadata part num=%u\n",
1493 					  le16_to_cpu(mdm->partitionNum));
1494 				udf_debug("Metadata part alloc unit size=%u\n",
1495 					  le32_to_cpu(mdm->allocUnitSize));
1496 				udf_debug("Metadata file loc=%u\n",
1497 					  le32_to_cpu(mdm->metadataFileLoc));
1498 				udf_debug("Mirror file loc=%u\n",
1499 					  le32_to_cpu(mdm->metadataMirrorFileLoc));
1500 				udf_debug("Bitmap file loc=%u\n",
1501 					  le32_to_cpu(mdm->metadataBitmapFileLoc));
1502 				udf_debug("Flags: %d %u\n",
1503 					  mdata->s_flags, mdm->flags);
1504 			} else {
1505 				udf_debug("Unknown ident: %s\n",
1506 					  upm2->partIdent.ident);
1507 				continue;
1508 			}
1509 			map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
1510 			map->s_partition_num = le16_to_cpu(upm2->partitionNum);
1511 		}
1512 		udf_debug("Partition (%d:%u) type %u on volume %u\n",
1513 			  i, map->s_partition_num, type, map->s_volumeseqnum);
1514 	}
1515 
1516 	if (fileset) {
1517 		struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
1518 
1519 		*fileset = lelb_to_cpu(la->extLocation);
1520 		udf_debug("FileSet found in LogicalVolDesc at block=%u, partition=%u\n",
1521 			  fileset->logicalBlockNum,
1522 			  fileset->partitionReferenceNum);
1523 	}
1524 	if (lvd->integritySeqExt.extLength)
1525 		udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
1526 	ret = 0;
1527 
1528 	if (!sbi->s_lvid_bh) {
1529 		/* We can't generate unique IDs without a valid LVID */
1530 		if (sb_rdonly(sb)) {
1531 			UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
1532 		} else {
1533 			udf_warn(sb, "Damaged or missing LVID, forcing "
1534 				     "readonly mount\n");
1535 			ret = -EACCES;
1536 		}
1537 	}
1538 out_bh:
1539 	brelse(bh);
1540 	return ret;
1541 }
1542 
1543 /*
1544  * Find the prevailing Logical Volume Integrity Descriptor.
1545  */
1546 static void udf_load_logicalvolint(struct super_block *sb, struct kernel_extent_ad loc)
1547 {
1548 	struct buffer_head *bh, *final_bh;
1549 	uint16_t ident;
1550 	struct udf_sb_info *sbi = UDF_SB(sb);
1551 	struct logicalVolIntegrityDesc *lvid;
1552 	int indirections = 0;
1553 	u32 parts, impuselen;
1554 
1555 	while (++indirections <= UDF_MAX_LVID_NESTING) {
1556 		final_bh = NULL;
1557 		while (loc.extLength > 0 &&
1558 			(bh = udf_read_tagged(sb, loc.extLocation,
1559 					loc.extLocation, &ident))) {
1560 			if (ident != TAG_IDENT_LVID) {
1561 				brelse(bh);
1562 				break;
1563 			}
1564 
1565 			brelse(final_bh);
1566 			final_bh = bh;
1567 
1568 			loc.extLength -= sb->s_blocksize;
1569 			loc.extLocation++;
1570 		}
1571 
1572 		if (!final_bh)
1573 			return;
1574 
1575 		brelse(sbi->s_lvid_bh);
1576 		sbi->s_lvid_bh = final_bh;
1577 
1578 		lvid = (struct logicalVolIntegrityDesc *)final_bh->b_data;
1579 		if (lvid->nextIntegrityExt.extLength == 0)
1580 			goto check;
1581 
1582 		loc = leea_to_cpu(lvid->nextIntegrityExt);
1583 	}
1584 
1585 	udf_warn(sb, "Too many LVID indirections (max %u), ignoring.\n",
1586 		UDF_MAX_LVID_NESTING);
1587 out_err:
1588 	brelse(sbi->s_lvid_bh);
1589 	sbi->s_lvid_bh = NULL;
1590 	return;
1591 check:
1592 	parts = le32_to_cpu(lvid->numOfPartitions);
1593 	impuselen = le32_to_cpu(lvid->lengthOfImpUse);
1594 	if (parts >= sb->s_blocksize || impuselen >= sb->s_blocksize ||
1595 	    sizeof(struct logicalVolIntegrityDesc) + impuselen +
1596 	    2 * parts * sizeof(u32) > sb->s_blocksize) {
1597 		udf_warn(sb, "Corrupted LVID (parts=%u, impuselen=%u), "
1598 			 "ignoring.\n", parts, impuselen);
1599 		goto out_err;
1600 	}
1601 }
1602 
1603 /*
1604  * Step for reallocation of table of partition descriptor sequence numbers.
1605  * Must be power of 2.
1606  */
1607 #define PART_DESC_ALLOC_STEP 32
1608 
1609 struct part_desc_seq_scan_data {
1610 	struct udf_vds_record rec;
1611 	u32 partnum;
1612 };
1613 
1614 struct desc_seq_scan_data {
1615 	struct udf_vds_record vds[VDS_POS_LENGTH];
1616 	unsigned int size_part_descs;
1617 	unsigned int num_part_descs;
1618 	struct part_desc_seq_scan_data *part_descs_loc;
1619 };
1620 
1621 static struct udf_vds_record *handle_partition_descriptor(
1622 				struct buffer_head *bh,
1623 				struct desc_seq_scan_data *data)
1624 {
1625 	struct partitionDesc *desc = (struct partitionDesc *)bh->b_data;
1626 	int partnum;
1627 	int i;
1628 
1629 	partnum = le16_to_cpu(desc->partitionNumber);
1630 	for (i = 0; i < data->num_part_descs; i++)
1631 		if (partnum == data->part_descs_loc[i].partnum)
1632 			return &(data->part_descs_loc[i].rec);
1633 	if (data->num_part_descs >= data->size_part_descs) {
1634 		struct part_desc_seq_scan_data *new_loc;
1635 		unsigned int new_size = ALIGN(partnum, PART_DESC_ALLOC_STEP);
1636 
1637 		new_loc = kcalloc(new_size, sizeof(*new_loc), GFP_KERNEL);
1638 		if (!new_loc)
1639 			return ERR_PTR(-ENOMEM);
1640 		memcpy(new_loc, data->part_descs_loc,
1641 		       data->size_part_descs * sizeof(*new_loc));
1642 		kfree(data->part_descs_loc);
1643 		data->part_descs_loc = new_loc;
1644 		data->size_part_descs = new_size;
1645 	}
1646 	return &(data->part_descs_loc[data->num_part_descs++].rec);
1647 }
1648 
1649 
1650 static struct udf_vds_record *get_volume_descriptor_record(uint16_t ident,
1651 		struct buffer_head *bh, struct desc_seq_scan_data *data)
1652 {
1653 	switch (ident) {
1654 	case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
1655 		return &(data->vds[VDS_POS_PRIMARY_VOL_DESC]);
1656 	case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
1657 		return &(data->vds[VDS_POS_IMP_USE_VOL_DESC]);
1658 	case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
1659 		return &(data->vds[VDS_POS_LOGICAL_VOL_DESC]);
1660 	case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
1661 		return &(data->vds[VDS_POS_UNALLOC_SPACE_DESC]);
1662 	case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
1663 		return handle_partition_descriptor(bh, data);
1664 	}
1665 	return NULL;
1666 }
1667 
1668 /*
1669  * Process a main/reserve volume descriptor sequence.
1670  *   @block		First block of first extent of the sequence.
1671  *   @lastblock		Lastblock of first extent of the sequence.
1672  *   @fileset		There we store extent containing root fileset
1673  *
1674  * Returns <0 on error, 0 on success. -EAGAIN is special - try next descriptor
1675  * sequence
1676  */
1677 static noinline int udf_process_sequence(
1678 		struct super_block *sb,
1679 		sector_t block, sector_t lastblock,
1680 		struct kernel_lb_addr *fileset)
1681 {
1682 	struct buffer_head *bh = NULL;
1683 	struct udf_vds_record *curr;
1684 	struct generic_desc *gd;
1685 	struct volDescPtr *vdp;
1686 	bool done = false;
1687 	uint32_t vdsn;
1688 	uint16_t ident;
1689 	int ret;
1690 	unsigned int indirections = 0;
1691 	struct desc_seq_scan_data data;
1692 	unsigned int i;
1693 
1694 	memset(data.vds, 0, sizeof(struct udf_vds_record) * VDS_POS_LENGTH);
1695 	data.size_part_descs = PART_DESC_ALLOC_STEP;
1696 	data.num_part_descs = 0;
1697 	data.part_descs_loc = kcalloc(data.size_part_descs,
1698 				      sizeof(*data.part_descs_loc),
1699 				      GFP_KERNEL);
1700 	if (!data.part_descs_loc)
1701 		return -ENOMEM;
1702 
1703 	/*
1704 	 * Read the main descriptor sequence and find which descriptors
1705 	 * are in it.
1706 	 */
1707 	for (; (!done && block <= lastblock); block++) {
1708 		bh = udf_read_tagged(sb, block, block, &ident);
1709 		if (!bh)
1710 			break;
1711 
1712 		/* Process each descriptor (ISO 13346 3/8.3-8.4) */
1713 		gd = (struct generic_desc *)bh->b_data;
1714 		vdsn = le32_to_cpu(gd->volDescSeqNum);
1715 		switch (ident) {
1716 		case TAG_IDENT_VDP: /* ISO 13346 3/10.3 */
1717 			if (++indirections > UDF_MAX_TD_NESTING) {
1718 				udf_err(sb, "too many Volume Descriptor "
1719 					"Pointers (max %u supported)\n",
1720 					UDF_MAX_TD_NESTING);
1721 				brelse(bh);
1722 				ret = -EIO;
1723 				goto out;
1724 			}
1725 
1726 			vdp = (struct volDescPtr *)bh->b_data;
1727 			block = le32_to_cpu(vdp->nextVolDescSeqExt.extLocation);
1728 			lastblock = le32_to_cpu(
1729 				vdp->nextVolDescSeqExt.extLength) >>
1730 				sb->s_blocksize_bits;
1731 			lastblock += block - 1;
1732 			/* For loop is going to increment 'block' again */
1733 			block--;
1734 			break;
1735 		case TAG_IDENT_PVD: /* ISO 13346 3/10.1 */
1736 		case TAG_IDENT_IUVD: /* ISO 13346 3/10.4 */
1737 		case TAG_IDENT_LVD: /* ISO 13346 3/10.6 */
1738 		case TAG_IDENT_USD: /* ISO 13346 3/10.8 */
1739 		case TAG_IDENT_PD: /* ISO 13346 3/10.5 */
1740 			curr = get_volume_descriptor_record(ident, bh, &data);
1741 			if (IS_ERR(curr)) {
1742 				brelse(bh);
1743 				ret = PTR_ERR(curr);
1744 				goto out;
1745 			}
1746 			/* Descriptor we don't care about? */
1747 			if (!curr)
1748 				break;
1749 			if (vdsn >= curr->volDescSeqNum) {
1750 				curr->volDescSeqNum = vdsn;
1751 				curr->block = block;
1752 			}
1753 			break;
1754 		case TAG_IDENT_TD: /* ISO 13346 3/10.9 */
1755 			done = true;
1756 			break;
1757 		}
1758 		brelse(bh);
1759 	}
1760 	/*
1761 	 * Now read interesting descriptors again and process them
1762 	 * in a suitable order
1763 	 */
1764 	if (!data.vds[VDS_POS_PRIMARY_VOL_DESC].block) {
1765 		udf_err(sb, "Primary Volume Descriptor not found!\n");
1766 		ret = -EAGAIN;
1767 		goto out;
1768 	}
1769 	ret = udf_load_pvoldesc(sb, data.vds[VDS_POS_PRIMARY_VOL_DESC].block);
1770 	if (ret < 0)
1771 		goto out;
1772 
1773 	if (data.vds[VDS_POS_LOGICAL_VOL_DESC].block) {
1774 		ret = udf_load_logicalvol(sb,
1775 				data.vds[VDS_POS_LOGICAL_VOL_DESC].block,
1776 				fileset);
1777 		if (ret < 0)
1778 			goto out;
1779 	}
1780 
1781 	/* Now handle prevailing Partition Descriptors */
1782 	for (i = 0; i < data.num_part_descs; i++) {
1783 		ret = udf_load_partdesc(sb, data.part_descs_loc[i].rec.block);
1784 		if (ret < 0)
1785 			goto out;
1786 	}
1787 	ret = 0;
1788 out:
1789 	kfree(data.part_descs_loc);
1790 	return ret;
1791 }
1792 
1793 /*
1794  * Load Volume Descriptor Sequence described by anchor in bh
1795  *
1796  * Returns <0 on error, 0 on success
1797  */
1798 static int udf_load_sequence(struct super_block *sb, struct buffer_head *bh,
1799 			     struct kernel_lb_addr *fileset)
1800 {
1801 	struct anchorVolDescPtr *anchor;
1802 	sector_t main_s, main_e, reserve_s, reserve_e;
1803 	int ret;
1804 
1805 	anchor = (struct anchorVolDescPtr *)bh->b_data;
1806 
1807 	/* Locate the main sequence */
1808 	main_s = le32_to_cpu(anchor->mainVolDescSeqExt.extLocation);
1809 	main_e = le32_to_cpu(anchor->mainVolDescSeqExt.extLength);
1810 	main_e = main_e >> sb->s_blocksize_bits;
1811 	main_e += main_s - 1;
1812 
1813 	/* Locate the reserve sequence */
1814 	reserve_s = le32_to_cpu(anchor->reserveVolDescSeqExt.extLocation);
1815 	reserve_e = le32_to_cpu(anchor->reserveVolDescSeqExt.extLength);
1816 	reserve_e = reserve_e >> sb->s_blocksize_bits;
1817 	reserve_e += reserve_s - 1;
1818 
1819 	/* Process the main & reserve sequences */
1820 	/* responsible for finding the PartitionDesc(s) */
1821 	ret = udf_process_sequence(sb, main_s, main_e, fileset);
1822 	if (ret != -EAGAIN)
1823 		return ret;
1824 	udf_sb_free_partitions(sb);
1825 	ret = udf_process_sequence(sb, reserve_s, reserve_e, fileset);
1826 	if (ret < 0) {
1827 		udf_sb_free_partitions(sb);
1828 		/* No sequence was OK, return -EIO */
1829 		if (ret == -EAGAIN)
1830 			ret = -EIO;
1831 	}
1832 	return ret;
1833 }
1834 
1835 /*
1836  * Check whether there is an anchor block in the given block and
1837  * load Volume Descriptor Sequence if so.
1838  *
1839  * Returns <0 on error, 0 on success, -EAGAIN is special - try next anchor
1840  * block
1841  */
1842 static int udf_check_anchor_block(struct super_block *sb, sector_t block,
1843 				  struct kernel_lb_addr *fileset)
1844 {
1845 	struct buffer_head *bh;
1846 	uint16_t ident;
1847 	int ret;
1848 
1849 	bh = udf_read_tagged(sb, block, block, &ident);
1850 	if (!bh)
1851 		return -EAGAIN;
1852 	if (ident != TAG_IDENT_AVDP) {
1853 		brelse(bh);
1854 		return -EAGAIN;
1855 	}
1856 	ret = udf_load_sequence(sb, bh, fileset);
1857 	brelse(bh);
1858 	return ret;
1859 }
1860 
1861 /*
1862  * Search for an anchor volume descriptor pointer.
1863  *
1864  * Returns < 0 on error, 0 on success. -EAGAIN is special - try next set
1865  * of anchors.
1866  */
1867 static int udf_scan_anchors(struct super_block *sb, udf_pblk_t *lastblock,
1868 			    struct kernel_lb_addr *fileset)
1869 {
1870 	udf_pblk_t last[6];
1871 	int i;
1872 	struct udf_sb_info *sbi = UDF_SB(sb);
1873 	int last_count = 0;
1874 	int ret;
1875 
1876 	/* First try user provided anchor */
1877 	if (sbi->s_anchor) {
1878 		ret = udf_check_anchor_block(sb, sbi->s_anchor, fileset);
1879 		if (ret != -EAGAIN)
1880 			return ret;
1881 	}
1882 	/*
1883 	 * according to spec, anchor is in either:
1884 	 *     block 256
1885 	 *     lastblock-256
1886 	 *     lastblock
1887 	 *  however, if the disc isn't closed, it could be 512.
1888 	 */
1889 	ret = udf_check_anchor_block(sb, sbi->s_session + 256, fileset);
1890 	if (ret != -EAGAIN)
1891 		return ret;
1892 	/*
1893 	 * The trouble is which block is the last one. Drives often misreport
1894 	 * this so we try various possibilities.
1895 	 */
1896 	last[last_count++] = *lastblock;
1897 	if (*lastblock >= 1)
1898 		last[last_count++] = *lastblock - 1;
1899 	last[last_count++] = *lastblock + 1;
1900 	if (*lastblock >= 2)
1901 		last[last_count++] = *lastblock - 2;
1902 	if (*lastblock >= 150)
1903 		last[last_count++] = *lastblock - 150;
1904 	if (*lastblock >= 152)
1905 		last[last_count++] = *lastblock - 152;
1906 
1907 	for (i = 0; i < last_count; i++) {
1908 		if (last[i] >= sb_bdev_nr_blocks(sb))
1909 			continue;
1910 		ret = udf_check_anchor_block(sb, last[i], fileset);
1911 		if (ret != -EAGAIN) {
1912 			if (!ret)
1913 				*lastblock = last[i];
1914 			return ret;
1915 		}
1916 		if (last[i] < 256)
1917 			continue;
1918 		ret = udf_check_anchor_block(sb, last[i] - 256, fileset);
1919 		if (ret != -EAGAIN) {
1920 			if (!ret)
1921 				*lastblock = last[i];
1922 			return ret;
1923 		}
1924 	}
1925 
1926 	/* Finally try block 512 in case media is open */
1927 	return udf_check_anchor_block(sb, sbi->s_session + 512, fileset);
1928 }
1929 
1930 /*
1931  * Check Volume Structure Descriptor, find Anchor block and load Volume
1932  * Descriptor Sequence.
1933  *
1934  * Returns < 0 on error, 0 on success. -EAGAIN is special meaning anchor
1935  * block was not found.
1936  */
1937 static int udf_load_vrs(struct super_block *sb, struct udf_options *uopt,
1938 			int silent, struct kernel_lb_addr *fileset)
1939 {
1940 	struct udf_sb_info *sbi = UDF_SB(sb);
1941 	int nsr = 0;
1942 	int ret;
1943 
1944 	if (!sb_set_blocksize(sb, uopt->blocksize)) {
1945 		if (!silent)
1946 			udf_warn(sb, "Bad block size\n");
1947 		return -EINVAL;
1948 	}
1949 	sbi->s_last_block = uopt->lastblock;
1950 	if (!uopt->novrs) {
1951 		/* Check that it is NSR02 compliant */
1952 		nsr = udf_check_vsd(sb);
1953 		if (!nsr) {
1954 			if (!silent)
1955 				udf_warn(sb, "No VRS found\n");
1956 			return -EINVAL;
1957 		}
1958 		if (nsr == -1)
1959 			udf_debug("Failed to read sector at offset %d. "
1960 				  "Assuming open disc. Skipping validity "
1961 				  "check\n", VSD_FIRST_SECTOR_OFFSET);
1962 		if (!sbi->s_last_block)
1963 			sbi->s_last_block = udf_get_last_block(sb);
1964 	} else {
1965 		udf_debug("Validity check skipped because of novrs option\n");
1966 	}
1967 
1968 	/* Look for anchor block and load Volume Descriptor Sequence */
1969 	sbi->s_anchor = uopt->anchor;
1970 	ret = udf_scan_anchors(sb, &sbi->s_last_block, fileset);
1971 	if (ret < 0) {
1972 		if (!silent && ret == -EAGAIN)
1973 			udf_warn(sb, "No anchor found\n");
1974 		return ret;
1975 	}
1976 	return 0;
1977 }
1978 
1979 static void udf_finalize_lvid(struct logicalVolIntegrityDesc *lvid)
1980 {
1981 	struct timespec64 ts;
1982 
1983 	ktime_get_real_ts64(&ts);
1984 	udf_time_to_disk_stamp(&lvid->recordingDateAndTime, ts);
1985 	lvid->descTag.descCRC = cpu_to_le16(
1986 		crc_itu_t(0, (char *)lvid + sizeof(struct tag),
1987 			le16_to_cpu(lvid->descTag.descCRCLength)));
1988 	lvid->descTag.tagChecksum = udf_tag_checksum(&lvid->descTag);
1989 }
1990 
1991 static void udf_open_lvid(struct super_block *sb)
1992 {
1993 	struct udf_sb_info *sbi = UDF_SB(sb);
1994 	struct buffer_head *bh = sbi->s_lvid_bh;
1995 	struct logicalVolIntegrityDesc *lvid;
1996 	struct logicalVolIntegrityDescImpUse *lvidiu;
1997 
1998 	if (!bh)
1999 		return;
2000 	lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2001 	lvidiu = udf_sb_lvidiu(sb);
2002 	if (!lvidiu)
2003 		return;
2004 
2005 	mutex_lock(&sbi->s_alloc_mutex);
2006 	lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
2007 	lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
2008 	if (le32_to_cpu(lvid->integrityType) == LVID_INTEGRITY_TYPE_CLOSE)
2009 		lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_OPEN);
2010 	else
2011 		UDF_SET_FLAG(sb, UDF_FLAG_INCONSISTENT);
2012 
2013 	udf_finalize_lvid(lvid);
2014 	mark_buffer_dirty(bh);
2015 	sbi->s_lvid_dirty = 0;
2016 	mutex_unlock(&sbi->s_alloc_mutex);
2017 	/* Make opening of filesystem visible on the media immediately */
2018 	sync_dirty_buffer(bh);
2019 }
2020 
2021 static void udf_close_lvid(struct super_block *sb)
2022 {
2023 	struct udf_sb_info *sbi = UDF_SB(sb);
2024 	struct buffer_head *bh = sbi->s_lvid_bh;
2025 	struct logicalVolIntegrityDesc *lvid;
2026 	struct logicalVolIntegrityDescImpUse *lvidiu;
2027 
2028 	if (!bh)
2029 		return;
2030 	lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2031 	lvidiu = udf_sb_lvidiu(sb);
2032 	if (!lvidiu)
2033 		return;
2034 
2035 	mutex_lock(&sbi->s_alloc_mutex);
2036 	lvidiu->impIdent.identSuffix[0] = UDF_OS_CLASS_UNIX;
2037 	lvidiu->impIdent.identSuffix[1] = UDF_OS_ID_LINUX;
2038 	if (UDF_MAX_WRITE_VERSION > le16_to_cpu(lvidiu->maxUDFWriteRev))
2039 		lvidiu->maxUDFWriteRev = cpu_to_le16(UDF_MAX_WRITE_VERSION);
2040 	if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFReadRev))
2041 		lvidiu->minUDFReadRev = cpu_to_le16(sbi->s_udfrev);
2042 	if (sbi->s_udfrev > le16_to_cpu(lvidiu->minUDFWriteRev))
2043 		lvidiu->minUDFWriteRev = cpu_to_le16(sbi->s_udfrev);
2044 	if (!UDF_QUERY_FLAG(sb, UDF_FLAG_INCONSISTENT))
2045 		lvid->integrityType = cpu_to_le32(LVID_INTEGRITY_TYPE_CLOSE);
2046 
2047 	/*
2048 	 * We set buffer uptodate unconditionally here to avoid spurious
2049 	 * warnings from mark_buffer_dirty() when previous EIO has marked
2050 	 * the buffer as !uptodate
2051 	 */
2052 	set_buffer_uptodate(bh);
2053 	udf_finalize_lvid(lvid);
2054 	mark_buffer_dirty(bh);
2055 	sbi->s_lvid_dirty = 0;
2056 	mutex_unlock(&sbi->s_alloc_mutex);
2057 	/* Make closing of filesystem visible on the media immediately */
2058 	sync_dirty_buffer(bh);
2059 }
2060 
2061 u64 lvid_get_unique_id(struct super_block *sb)
2062 {
2063 	struct buffer_head *bh;
2064 	struct udf_sb_info *sbi = UDF_SB(sb);
2065 	struct logicalVolIntegrityDesc *lvid;
2066 	struct logicalVolHeaderDesc *lvhd;
2067 	u64 uniqueID;
2068 	u64 ret;
2069 
2070 	bh = sbi->s_lvid_bh;
2071 	if (!bh)
2072 		return 0;
2073 
2074 	lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2075 	lvhd = (struct logicalVolHeaderDesc *)lvid->logicalVolContentsUse;
2076 
2077 	mutex_lock(&sbi->s_alloc_mutex);
2078 	ret = uniqueID = le64_to_cpu(lvhd->uniqueID);
2079 	if (!(++uniqueID & 0xFFFFFFFF))
2080 		uniqueID += 16;
2081 	lvhd->uniqueID = cpu_to_le64(uniqueID);
2082 	udf_updated_lvid(sb);
2083 	mutex_unlock(&sbi->s_alloc_mutex);
2084 
2085 	return ret;
2086 }
2087 
2088 static int udf_fill_super(struct super_block *sb, void *options, int silent)
2089 {
2090 	int ret = -EINVAL;
2091 	struct inode *inode = NULL;
2092 	struct udf_options uopt;
2093 	struct kernel_lb_addr rootdir, fileset;
2094 	struct udf_sb_info *sbi;
2095 	bool lvid_open = false;
2096 
2097 	uopt.flags = (1 << UDF_FLAG_USE_AD_IN_ICB) | (1 << UDF_FLAG_STRICT);
2098 	/* By default we'll use overflow[ug]id when UDF inode [ug]id == -1 */
2099 	uopt.uid = make_kuid(current_user_ns(), overflowuid);
2100 	uopt.gid = make_kgid(current_user_ns(), overflowgid);
2101 	uopt.umask = 0;
2102 	uopt.fmode = UDF_INVALID_MODE;
2103 	uopt.dmode = UDF_INVALID_MODE;
2104 	uopt.nls_map = NULL;
2105 
2106 	sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
2107 	if (!sbi)
2108 		return -ENOMEM;
2109 
2110 	sb->s_fs_info = sbi;
2111 
2112 	mutex_init(&sbi->s_alloc_mutex);
2113 
2114 	if (!udf_parse_options((char *)options, &uopt, false))
2115 		goto parse_options_failure;
2116 
2117 	fileset.logicalBlockNum = 0xFFFFFFFF;
2118 	fileset.partitionReferenceNum = 0xFFFF;
2119 
2120 	sbi->s_flags = uopt.flags;
2121 	sbi->s_uid = uopt.uid;
2122 	sbi->s_gid = uopt.gid;
2123 	sbi->s_umask = uopt.umask;
2124 	sbi->s_fmode = uopt.fmode;
2125 	sbi->s_dmode = uopt.dmode;
2126 	sbi->s_nls_map = uopt.nls_map;
2127 	rwlock_init(&sbi->s_cred_lock);
2128 
2129 	if (uopt.session == 0xFFFFFFFF)
2130 		sbi->s_session = udf_get_last_session(sb);
2131 	else
2132 		sbi->s_session = uopt.session;
2133 
2134 	udf_debug("Multi-session=%d\n", sbi->s_session);
2135 
2136 	/* Fill in the rest of the superblock */
2137 	sb->s_op = &udf_sb_ops;
2138 	sb->s_export_op = &udf_export_ops;
2139 
2140 	sb->s_magic = UDF_SUPER_MAGIC;
2141 	sb->s_time_gran = 1000;
2142 
2143 	if (uopt.flags & (1 << UDF_FLAG_BLOCKSIZE_SET)) {
2144 		ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2145 	} else {
2146 		uopt.blocksize = bdev_logical_block_size(sb->s_bdev);
2147 		while (uopt.blocksize <= 4096) {
2148 			ret = udf_load_vrs(sb, &uopt, silent, &fileset);
2149 			if (ret < 0) {
2150 				if (!silent && ret != -EACCES) {
2151 					pr_notice("Scanning with blocksize %u failed\n",
2152 						  uopt.blocksize);
2153 				}
2154 				brelse(sbi->s_lvid_bh);
2155 				sbi->s_lvid_bh = NULL;
2156 				/*
2157 				 * EACCES is special - we want to propagate to
2158 				 * upper layers that we cannot handle RW mount.
2159 				 */
2160 				if (ret == -EACCES)
2161 					break;
2162 			} else
2163 				break;
2164 
2165 			uopt.blocksize <<= 1;
2166 		}
2167 	}
2168 	if (ret < 0) {
2169 		if (ret == -EAGAIN) {
2170 			udf_warn(sb, "No partition found (1)\n");
2171 			ret = -EINVAL;
2172 		}
2173 		goto error_out;
2174 	}
2175 
2176 	udf_debug("Lastblock=%u\n", sbi->s_last_block);
2177 
2178 	if (sbi->s_lvid_bh) {
2179 		struct logicalVolIntegrityDescImpUse *lvidiu =
2180 							udf_sb_lvidiu(sb);
2181 		uint16_t minUDFReadRev;
2182 		uint16_t minUDFWriteRev;
2183 
2184 		if (!lvidiu) {
2185 			ret = -EINVAL;
2186 			goto error_out;
2187 		}
2188 		minUDFReadRev = le16_to_cpu(lvidiu->minUDFReadRev);
2189 		minUDFWriteRev = le16_to_cpu(lvidiu->minUDFWriteRev);
2190 		if (minUDFReadRev > UDF_MAX_READ_VERSION) {
2191 			udf_err(sb, "minUDFReadRev=%x (max is %x)\n",
2192 				minUDFReadRev,
2193 				UDF_MAX_READ_VERSION);
2194 			ret = -EINVAL;
2195 			goto error_out;
2196 		} else if (minUDFWriteRev > UDF_MAX_WRITE_VERSION) {
2197 			if (!sb_rdonly(sb)) {
2198 				ret = -EACCES;
2199 				goto error_out;
2200 			}
2201 			UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
2202 		}
2203 
2204 		sbi->s_udfrev = minUDFWriteRev;
2205 
2206 		if (minUDFReadRev >= UDF_VERS_USE_EXTENDED_FE)
2207 			UDF_SET_FLAG(sb, UDF_FLAG_USE_EXTENDED_FE);
2208 		if (minUDFReadRev >= UDF_VERS_USE_STREAMS)
2209 			UDF_SET_FLAG(sb, UDF_FLAG_USE_STREAMS);
2210 	}
2211 
2212 	if (!sbi->s_partitions) {
2213 		udf_warn(sb, "No partition found (2)\n");
2214 		ret = -EINVAL;
2215 		goto error_out;
2216 	}
2217 
2218 	if (sbi->s_partmaps[sbi->s_partition].s_partition_flags &
2219 			UDF_PART_FLAG_READ_ONLY) {
2220 		if (!sb_rdonly(sb)) {
2221 			ret = -EACCES;
2222 			goto error_out;
2223 		}
2224 		UDF_SET_FLAG(sb, UDF_FLAG_RW_INCOMPAT);
2225 	}
2226 
2227 	ret = udf_find_fileset(sb, &fileset, &rootdir);
2228 	if (ret < 0) {
2229 		udf_warn(sb, "No fileset found\n");
2230 		goto error_out;
2231 	}
2232 
2233 	if (!silent) {
2234 		struct timestamp ts;
2235 		udf_time_to_disk_stamp(&ts, sbi->s_record_time);
2236 		udf_info("Mounting volume '%s', timestamp %04u/%02u/%02u %02u:%02u (%x)\n",
2237 			 sbi->s_volume_ident,
2238 			 le16_to_cpu(ts.year), ts.month, ts.day,
2239 			 ts.hour, ts.minute, le16_to_cpu(ts.typeAndTimezone));
2240 	}
2241 	if (!sb_rdonly(sb)) {
2242 		udf_open_lvid(sb);
2243 		lvid_open = true;
2244 	}
2245 
2246 	/* Assign the root inode */
2247 	/* assign inodes by physical block number */
2248 	/* perhaps it's not extensible enough, but for now ... */
2249 	inode = udf_iget(sb, &rootdir);
2250 	if (IS_ERR(inode)) {
2251 		udf_err(sb, "Error in udf_iget, block=%u, partition=%u\n",
2252 		       rootdir.logicalBlockNum, rootdir.partitionReferenceNum);
2253 		ret = PTR_ERR(inode);
2254 		goto error_out;
2255 	}
2256 
2257 	/* Allocate a dentry for the root inode */
2258 	sb->s_root = d_make_root(inode);
2259 	if (!sb->s_root) {
2260 		udf_err(sb, "Couldn't allocate root dentry\n");
2261 		ret = -ENOMEM;
2262 		goto error_out;
2263 	}
2264 	sb->s_maxbytes = UDF_MAX_FILESIZE;
2265 	sb->s_max_links = UDF_MAX_LINKS;
2266 	return 0;
2267 
2268 error_out:
2269 	iput(sbi->s_vat_inode);
2270 parse_options_failure:
2271 	unload_nls(uopt.nls_map);
2272 	if (lvid_open)
2273 		udf_close_lvid(sb);
2274 	brelse(sbi->s_lvid_bh);
2275 	udf_sb_free_partitions(sb);
2276 	kfree(sbi);
2277 	sb->s_fs_info = NULL;
2278 
2279 	return ret;
2280 }
2281 
2282 void _udf_err(struct super_block *sb, const char *function,
2283 	      const char *fmt, ...)
2284 {
2285 	struct va_format vaf;
2286 	va_list args;
2287 
2288 	va_start(args, fmt);
2289 
2290 	vaf.fmt = fmt;
2291 	vaf.va = &args;
2292 
2293 	pr_err("error (device %s): %s: %pV", sb->s_id, function, &vaf);
2294 
2295 	va_end(args);
2296 }
2297 
2298 void _udf_warn(struct super_block *sb, const char *function,
2299 	       const char *fmt, ...)
2300 {
2301 	struct va_format vaf;
2302 	va_list args;
2303 
2304 	va_start(args, fmt);
2305 
2306 	vaf.fmt = fmt;
2307 	vaf.va = &args;
2308 
2309 	pr_warn("warning (device %s): %s: %pV", sb->s_id, function, &vaf);
2310 
2311 	va_end(args);
2312 }
2313 
2314 static void udf_put_super(struct super_block *sb)
2315 {
2316 	struct udf_sb_info *sbi;
2317 
2318 	sbi = UDF_SB(sb);
2319 
2320 	iput(sbi->s_vat_inode);
2321 	unload_nls(sbi->s_nls_map);
2322 	if (!sb_rdonly(sb))
2323 		udf_close_lvid(sb);
2324 	brelse(sbi->s_lvid_bh);
2325 	udf_sb_free_partitions(sb);
2326 	mutex_destroy(&sbi->s_alloc_mutex);
2327 	kfree(sb->s_fs_info);
2328 	sb->s_fs_info = NULL;
2329 }
2330 
2331 static int udf_sync_fs(struct super_block *sb, int wait)
2332 {
2333 	struct udf_sb_info *sbi = UDF_SB(sb);
2334 
2335 	mutex_lock(&sbi->s_alloc_mutex);
2336 	if (sbi->s_lvid_dirty) {
2337 		struct buffer_head *bh = sbi->s_lvid_bh;
2338 		struct logicalVolIntegrityDesc *lvid;
2339 
2340 		lvid = (struct logicalVolIntegrityDesc *)bh->b_data;
2341 		udf_finalize_lvid(lvid);
2342 
2343 		/*
2344 		 * Blockdevice will be synced later so we don't have to submit
2345 		 * the buffer for IO
2346 		 */
2347 		mark_buffer_dirty(bh);
2348 		sbi->s_lvid_dirty = 0;
2349 	}
2350 	mutex_unlock(&sbi->s_alloc_mutex);
2351 
2352 	return 0;
2353 }
2354 
2355 static int udf_statfs(struct dentry *dentry, struct kstatfs *buf)
2356 {
2357 	struct super_block *sb = dentry->d_sb;
2358 	struct udf_sb_info *sbi = UDF_SB(sb);
2359 	struct logicalVolIntegrityDescImpUse *lvidiu;
2360 	u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
2361 
2362 	lvidiu = udf_sb_lvidiu(sb);
2363 	buf->f_type = UDF_SUPER_MAGIC;
2364 	buf->f_bsize = sb->s_blocksize;
2365 	buf->f_blocks = sbi->s_partmaps[sbi->s_partition].s_partition_len;
2366 	buf->f_bfree = udf_count_free(sb);
2367 	buf->f_bavail = buf->f_bfree;
2368 	/*
2369 	 * Let's pretend each free block is also a free 'inode' since UDF does
2370 	 * not have separate preallocated table of inodes.
2371 	 */
2372 	buf->f_files = (lvidiu != NULL ? (le32_to_cpu(lvidiu->numFiles) +
2373 					  le32_to_cpu(lvidiu->numDirs)) : 0)
2374 			+ buf->f_bfree;
2375 	buf->f_ffree = buf->f_bfree;
2376 	buf->f_namelen = UDF_NAME_LEN;
2377 	buf->f_fsid = u64_to_fsid(id);
2378 
2379 	return 0;
2380 }
2381 
2382 static unsigned int udf_count_free_bitmap(struct super_block *sb,
2383 					  struct udf_bitmap *bitmap)
2384 {
2385 	struct buffer_head *bh = NULL;
2386 	unsigned int accum = 0;
2387 	int index;
2388 	udf_pblk_t block = 0, newblock;
2389 	struct kernel_lb_addr loc;
2390 	uint32_t bytes;
2391 	uint8_t *ptr;
2392 	uint16_t ident;
2393 	struct spaceBitmapDesc *bm;
2394 
2395 	loc.logicalBlockNum = bitmap->s_extPosition;
2396 	loc.partitionReferenceNum = UDF_SB(sb)->s_partition;
2397 	bh = udf_read_ptagged(sb, &loc, 0, &ident);
2398 
2399 	if (!bh) {
2400 		udf_err(sb, "udf_count_free failed\n");
2401 		goto out;
2402 	} else if (ident != TAG_IDENT_SBD) {
2403 		brelse(bh);
2404 		udf_err(sb, "udf_count_free failed\n");
2405 		goto out;
2406 	}
2407 
2408 	bm = (struct spaceBitmapDesc *)bh->b_data;
2409 	bytes = le32_to_cpu(bm->numOfBytes);
2410 	index = sizeof(struct spaceBitmapDesc); /* offset in first block only */
2411 	ptr = (uint8_t *)bh->b_data;
2412 
2413 	while (bytes > 0) {
2414 		u32 cur_bytes = min_t(u32, bytes, sb->s_blocksize - index);
2415 		accum += bitmap_weight((const unsigned long *)(ptr + index),
2416 					cur_bytes * 8);
2417 		bytes -= cur_bytes;
2418 		if (bytes) {
2419 			brelse(bh);
2420 			newblock = udf_get_lb_pblock(sb, &loc, ++block);
2421 			bh = sb_bread(sb, newblock);
2422 			if (!bh) {
2423 				udf_debug("read failed\n");
2424 				goto out;
2425 			}
2426 			index = 0;
2427 			ptr = (uint8_t *)bh->b_data;
2428 		}
2429 	}
2430 	brelse(bh);
2431 out:
2432 	return accum;
2433 }
2434 
2435 static unsigned int udf_count_free_table(struct super_block *sb,
2436 					 struct inode *table)
2437 {
2438 	unsigned int accum = 0;
2439 	uint32_t elen;
2440 	struct kernel_lb_addr eloc;
2441 	struct extent_position epos;
2442 
2443 	mutex_lock(&UDF_SB(sb)->s_alloc_mutex);
2444 	epos.block = UDF_I(table)->i_location;
2445 	epos.offset = sizeof(struct unallocSpaceEntry);
2446 	epos.bh = NULL;
2447 
2448 	while (udf_next_aext(table, &epos, &eloc, &elen, 1) != -1)
2449 		accum += (elen >> table->i_sb->s_blocksize_bits);
2450 
2451 	brelse(epos.bh);
2452 	mutex_unlock(&UDF_SB(sb)->s_alloc_mutex);
2453 
2454 	return accum;
2455 }
2456 
2457 static unsigned int udf_count_free(struct super_block *sb)
2458 {
2459 	unsigned int accum = 0;
2460 	struct udf_sb_info *sbi = UDF_SB(sb);
2461 	struct udf_part_map *map;
2462 	unsigned int part = sbi->s_partition;
2463 	int ptype = sbi->s_partmaps[part].s_partition_type;
2464 
2465 	if (ptype == UDF_METADATA_MAP25) {
2466 		part = sbi->s_partmaps[part].s_type_specific.s_metadata.
2467 							s_phys_partition_ref;
2468 	} else if (ptype == UDF_VIRTUAL_MAP15 || ptype == UDF_VIRTUAL_MAP20) {
2469 		/*
2470 		 * Filesystems with VAT are append-only and we cannot write to
2471  		 * them. Let's just report 0 here.
2472 		 */
2473 		return 0;
2474 	}
2475 
2476 	if (sbi->s_lvid_bh) {
2477 		struct logicalVolIntegrityDesc *lvid =
2478 			(struct logicalVolIntegrityDesc *)
2479 			sbi->s_lvid_bh->b_data;
2480 		if (le32_to_cpu(lvid->numOfPartitions) > part) {
2481 			accum = le32_to_cpu(
2482 					lvid->freeSpaceTable[part]);
2483 			if (accum == 0xFFFFFFFF)
2484 				accum = 0;
2485 		}
2486 	}
2487 
2488 	if (accum)
2489 		return accum;
2490 
2491 	map = &sbi->s_partmaps[part];
2492 	if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_BITMAP) {
2493 		accum += udf_count_free_bitmap(sb,
2494 					       map->s_uspace.s_bitmap);
2495 	}
2496 	if (accum)
2497 		return accum;
2498 
2499 	if (map->s_partition_flags & UDF_PART_FLAG_UNALLOC_TABLE) {
2500 		accum += udf_count_free_table(sb,
2501 					      map->s_uspace.s_table);
2502 	}
2503 	return accum;
2504 }
2505 
2506 MODULE_AUTHOR("Ben Fennema");
2507 MODULE_DESCRIPTION("Universal Disk Format Filesystem");
2508 MODULE_LICENSE("GPL");
2509 module_init(init_udf_fs)
2510 module_exit(exit_udf_fs)
2511