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