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