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