xref: /linux/fs/overlayfs/super.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  * Copyright (C) 2011 Novell Inc.
5  */
6 
7 #include <uapi/linux/magic.h>
8 #include <linux/fs.h>
9 #include <linux/namei.h>
10 #include <linux/xattr.h>
11 #include <linux/mount.h>
12 #include <linux/parser.h>
13 #include <linux/module.h>
14 #include <linux/statfs.h>
15 #include <linux/seq_file.h>
16 #include <linux/posix_acl_xattr.h>
17 #include <linux/exportfs.h>
18 #include <linux/file.h>
19 #include <linux/fs_context.h>
20 #include <linux/fs_parser.h>
21 #include "overlayfs.h"
22 #include "params.h"
23 
24 MODULE_AUTHOR("Miklos Szeredi <miklos@szeredi.hu>");
25 MODULE_DESCRIPTION("Overlay filesystem");
26 MODULE_LICENSE("GPL");
27 
28 
29 struct ovl_dir_cache;
30 
31 static struct dentry *ovl_d_real(struct dentry *dentry, enum d_real_type type)
32 {
33 	struct dentry *upper, *lower;
34 	int err;
35 
36 	switch (type) {
37 	case D_REAL_DATA:
38 	case D_REAL_METADATA:
39 		break;
40 	default:
41 		goto bug;
42 	}
43 
44 	if (!d_is_reg(dentry)) {
45 		/* d_real_inode() is only relevant for regular files */
46 		return dentry;
47 	}
48 
49 	upper = ovl_dentry_upper(dentry);
50 	if (upper && (type == D_REAL_METADATA ||
51 		      ovl_has_upperdata(d_inode(dentry))))
52 		return upper;
53 
54 	if (type == D_REAL_METADATA) {
55 		lower = ovl_dentry_lower(dentry);
56 		goto real_lower;
57 	}
58 
59 	/*
60 	 * Best effort lazy lookup of lowerdata for D_REAL_DATA case to return
61 	 * the real lowerdata dentry.  The only current caller of d_real() with
62 	 * D_REAL_DATA is d_real_inode() from trace_uprobe and this caller is
63 	 * likely going to be followed reading from the file, before placing
64 	 * uprobes on offset within the file, so lowerdata should be available
65 	 * when setting the uprobe.
66 	 */
67 	err = ovl_verify_lowerdata(dentry);
68 	if (err)
69 		goto bug;
70 	lower = ovl_dentry_lowerdata(dentry);
71 	if (!lower)
72 		goto bug;
73 
74 real_lower:
75 	/* Handle recursion into stacked lower fs */
76 	return d_real(lower, type);
77 
78 bug:
79 	WARN(1, "%s(%pd4, %d): real dentry not found\n", __func__, dentry, type);
80 	return dentry;
81 }
82 
83 static int ovl_revalidate_real(struct dentry *d, unsigned int flags, bool weak)
84 {
85 	int ret = 1;
86 
87 	if (!d)
88 		return 1;
89 
90 	if (weak) {
91 		if (d->d_flags & DCACHE_OP_WEAK_REVALIDATE)
92 			ret =  d->d_op->d_weak_revalidate(d, flags);
93 	} else if (d->d_flags & DCACHE_OP_REVALIDATE) {
94 		struct dentry *parent;
95 		struct inode *dir;
96 		struct name_snapshot n;
97 
98 		if (flags & LOOKUP_RCU) {
99 			parent = READ_ONCE(d->d_parent);
100 			dir = d_inode_rcu(parent);
101 			if (!dir)
102 				return -ECHILD;
103 		} else {
104 			parent = dget_parent(d);
105 			dir = d_inode(parent);
106 		}
107 		/* In RCU walk the dentry name may go away at any time */
108 		if (!take_dentry_name_snapshot(&n, d))
109 			return -ECHILD;
110 		ret = d->d_op->d_revalidate(dir, &n.name, d, flags);
111 		release_dentry_name_snapshot(&n);
112 		if (!(flags & LOOKUP_RCU))
113 			dput(parent);
114 		if (!ret) {
115 			if (!(flags & LOOKUP_RCU))
116 				d_invalidate(d);
117 			ret = -ESTALE;
118 		}
119 	}
120 	return ret;
121 }
122 
123 static int ovl_dentry_revalidate_common(struct dentry *dentry,
124 					unsigned int flags, bool weak)
125 {
126 	struct ovl_entry *oe;
127 	struct ovl_path *lowerstack;
128 	struct inode *inode = d_inode_rcu(dentry);
129 	struct dentry *upper;
130 	unsigned int i;
131 	int ret = 1;
132 
133 	if (!inode) {
134 		/*
135 		 * Lookup of negative dentries will call ovl_dentry_init_flags()
136 		 * with NULL upperdentry and NULL oe, resulting in the
137 		 * DCACHE_OP*_REVALIDATE flags being cleared.  Hence the only
138 		 * way to get a negative inode is due to a race with dentry
139 		 * destruction.
140 		 */
141 		WARN_ON(!(flags & LOOKUP_RCU));
142 		return -ECHILD;
143 	}
144 
145 	oe = OVL_I_E(inode);
146 	lowerstack = ovl_lowerstack(oe);
147 	upper = ovl_i_dentry_upper(inode);
148 	if (upper)
149 		ret = ovl_revalidate_real(upper, flags, weak);
150 
151 	for (i = 0; ret > 0 && i < ovl_numlower(oe); i++)
152 		ret = ovl_revalidate_real(lowerstack[i].dentry, flags, weak);
153 
154 	return ret;
155 }
156 
157 static int ovl_dentry_revalidate(struct inode *dir, const struct qstr *name,
158 				 struct dentry *dentry, unsigned int flags)
159 {
160 	return ovl_dentry_revalidate_common(dentry, flags, false);
161 }
162 
163 static int ovl_dentry_weak_revalidate(struct dentry *dentry, unsigned int flags)
164 {
165 	return ovl_dentry_revalidate_common(dentry, flags, true);
166 }
167 
168 #ifdef CONFIG_LOCKDEP
169 static int ovl_dentry_init(struct dentry *dentry)
170 {
171 	static struct lock_class_key ovl_d_lock_key[OVL_MAX_NESTING];
172 	int depth = dentry->d_sb->s_stack_depth - 1;
173 
174 	if (WARN_ON_ONCE(depth < 0 || depth >= OVL_MAX_NESTING))
175 		depth = 0;
176 
177 	lockdep_set_class(dentry, &ovl_d_lock_key[depth]);
178 
179 	return 0;
180 }
181 #else
182 #define ovl_dentry_init NULL
183 #endif
184 
185 static const struct dentry_operations ovl_dentry_operations = {
186 	.d_real = ovl_d_real,
187 	.d_revalidate = ovl_dentry_revalidate,
188 	.d_weak_revalidate = ovl_dentry_weak_revalidate,
189 	.d_init = ovl_dentry_init,
190 };
191 
192 #if IS_ENABLED(CONFIG_UNICODE)
193 static const struct dentry_operations ovl_dentry_ci_operations = {
194 	.d_real = ovl_d_real,
195 	.d_revalidate = ovl_dentry_revalidate,
196 	.d_weak_revalidate = ovl_dentry_weak_revalidate,
197 	.d_hash = generic_ci_d_hash,
198 	.d_compare = generic_ci_d_compare,
199 	.d_init = ovl_dentry_init,
200 };
201 #endif
202 
203 static struct kmem_cache *ovl_inode_cachep;
204 
205 static struct inode *ovl_alloc_inode(struct super_block *sb)
206 {
207 	struct ovl_inode *oi = alloc_inode_sb(sb, ovl_inode_cachep, GFP_KERNEL);
208 
209 	if (!oi)
210 		return NULL;
211 
212 	oi->cache = NULL;
213 	oi->redirect = NULL;
214 	oi->version = 0;
215 	oi->flags = 0;
216 	oi->__upperdentry = NULL;
217 	oi->lowerdata_redirect = NULL;
218 	oi->oe = NULL;
219 	mutex_init(&oi->lock);
220 
221 	return &oi->vfs_inode;
222 }
223 
224 static void ovl_free_inode(struct inode *inode)
225 {
226 	struct ovl_inode *oi = OVL_I(inode);
227 
228 	kfree(oi->redirect);
229 	kfree(oi->oe);
230 	mutex_destroy(&oi->lock);
231 	kmem_cache_free(ovl_inode_cachep, oi);
232 }
233 
234 static void ovl_destroy_inode(struct inode *inode)
235 {
236 	struct ovl_inode *oi = OVL_I(inode);
237 
238 	dput(oi->__upperdentry);
239 	ovl_stack_put(ovl_lowerstack(oi->oe), ovl_numlower(oi->oe));
240 	if (S_ISDIR(inode->i_mode))
241 		ovl_dir_cache_free(inode);
242 	else
243 		kfree(oi->lowerdata_redirect);
244 }
245 
246 static void ovl_put_super(struct super_block *sb)
247 {
248 	struct ovl_fs *ofs = OVL_FS(sb);
249 
250 	if (ofs)
251 		ovl_free_fs(ofs);
252 }
253 
254 /* Sync real dirty inodes in upper filesystem (if it exists) */
255 static int ovl_sync_fs(struct super_block *sb, int wait)
256 {
257 	struct ovl_fs *ofs = OVL_FS(sb);
258 	struct super_block *upper_sb;
259 	int ret;
260 
261 	ret = ovl_sync_status(ofs);
262 
263 	if (ret < 0)
264 		return -EIO;
265 
266 	if (!ret)
267 		return ret;
268 
269 	/*
270 	 * Not called for sync(2) call or an emergency sync (SB_I_SKIP_SYNC).
271 	 * All the super blocks will be iterated, including upper_sb.
272 	 *
273 	 * If this is a syncfs(2) call, then we do need to call
274 	 * sync_filesystem() on upper_sb, but enough if we do it when being
275 	 * called with wait == 1.
276 	 */
277 	if (!wait)
278 		return 0;
279 
280 	upper_sb = ovl_upper_mnt(ofs)->mnt_sb;
281 
282 	down_read(&upper_sb->s_umount);
283 	ret = sync_filesystem(upper_sb);
284 	up_read(&upper_sb->s_umount);
285 
286 	return ret;
287 }
288 
289 /**
290  * ovl_statfs
291  * @dentry: The dentry to query
292  * @buf: The struct kstatfs to fill in with stats
293  *
294  * Get the filesystem statistics.  As writes always target the upper layer
295  * filesystem pass the statfs to the upper filesystem (if it exists)
296  */
297 static int ovl_statfs(struct dentry *dentry, struct kstatfs *buf)
298 {
299 	struct super_block *sb = dentry->d_sb;
300 	struct ovl_fs *ofs = OVL_FS(sb);
301 	struct dentry *root_dentry = sb->s_root;
302 	struct path path;
303 	int err;
304 
305 	ovl_path_real(root_dentry, &path);
306 
307 	err = vfs_statfs(&path, buf);
308 	if (!err) {
309 		buf->f_namelen = ofs->namelen;
310 		buf->f_type = OVERLAYFS_SUPER_MAGIC;
311 		if (ovl_has_fsid(ofs))
312 			buf->f_fsid = uuid_to_fsid(sb->s_uuid.b);
313 	}
314 
315 	return err;
316 }
317 
318 static const struct super_operations ovl_super_operations = {
319 	.alloc_inode	= ovl_alloc_inode,
320 	.free_inode	= ovl_free_inode,
321 	.destroy_inode	= ovl_destroy_inode,
322 	.drop_inode	= inode_just_drop,
323 	.put_super	= ovl_put_super,
324 	.sync_fs	= ovl_sync_fs,
325 	.statfs		= ovl_statfs,
326 	.show_options	= ovl_show_options,
327 };
328 
329 #define OVL_WORKDIR_NAME "work"
330 #define OVL_INDEXDIR_NAME "index"
331 
332 static struct dentry *ovl_workdir_create(struct ovl_fs *ofs,
333 					 const char *name, bool persist)
334 {
335 	struct inode *dir =  ofs->workbasedir->d_inode;
336 	struct vfsmount *mnt = ovl_upper_mnt(ofs);
337 	struct dentry *work;
338 	int err;
339 	bool retried = false;
340 
341 retry:
342 	work = ovl_start_creating_upper(ofs, ofs->workbasedir, &QSTR(name));
343 
344 	if (!IS_ERR(work)) {
345 		struct iattr attr = {
346 			.ia_valid = ATTR_MODE,
347 			.ia_mode = S_IFDIR | 0,
348 		};
349 
350 		if (work->d_inode) {
351 			end_creating_keep(work);
352 			if (persist)
353 				return work;
354 			err = -EEXIST;
355 			if (retried)
356 				goto out_dput;
357 			retried = true;
358 			err = ovl_workdir_cleanup(ofs, ofs->workbasedir, mnt, work, 0);
359 			dput(work);
360 			if (err == -EINVAL)
361 				return ERR_PTR(err);
362 
363 			goto retry;
364 		}
365 
366 		work = ovl_do_mkdir(ofs, dir, work, attr.ia_mode);
367 		end_creating_keep(work);
368 		err = PTR_ERR(work);
369 		if (IS_ERR(work))
370 			goto out_err;
371 
372 		/* Weird filesystem returning with hashed negative (kernfs)? */
373 		err = -EINVAL;
374 		if (d_really_is_negative(work))
375 			goto out_dput;
376 
377 		/*
378 		 * Try to remove POSIX ACL xattrs from workdir.  We are good if:
379 		 *
380 		 * a) success (there was a POSIX ACL xattr and was removed)
381 		 * b) -ENODATA (there was no POSIX ACL xattr)
382 		 * c) -EOPNOTSUPP (POSIX ACL xattrs are not supported)
383 		 *
384 		 * There are various other error values that could effectively
385 		 * mean that the xattr doesn't exist (e.g. -ERANGE is returned
386 		 * if the xattr name is too long), but the set of filesystems
387 		 * allowed as upper are limited to "normal" ones, where checking
388 		 * for the above two errors is sufficient.
389 		 */
390 		err = ovl_do_remove_acl(ofs, work, XATTR_NAME_POSIX_ACL_DEFAULT);
391 		if (err && err != -ENODATA && err != -EOPNOTSUPP)
392 			goto out_dput;
393 
394 		err = ovl_do_remove_acl(ofs, work, XATTR_NAME_POSIX_ACL_ACCESS);
395 		if (err && err != -ENODATA && err != -EOPNOTSUPP)
396 			goto out_dput;
397 
398 		/* Clear any inherited mode bits */
399 		inode_lock(work->d_inode);
400 		err = ovl_do_notify_change(ofs, work, &attr);
401 		inode_unlock(work->d_inode);
402 		if (err)
403 			goto out_dput;
404 	} else {
405 		err = PTR_ERR(work);
406 		goto out_err;
407 	}
408 	return work;
409 
410 out_dput:
411 	dput(work);
412 out_err:
413 	pr_warn("failed to create directory %s/%s (errno: %i); mounting read-only\n",
414 		ofs->config.workdir, name, -err);
415 	return NULL;
416 }
417 
418 static int ovl_check_namelen(const struct path *path, struct ovl_fs *ofs,
419 			     const char *name)
420 {
421 	struct kstatfs statfs;
422 	int err = vfs_statfs(path, &statfs);
423 
424 	if (err)
425 		pr_err("statfs failed on '%s'\n", name);
426 	else
427 		ofs->namelen = max(ofs->namelen, statfs.f_namelen);
428 
429 	return err;
430 }
431 
432 static int ovl_lower_dir(const char *name, const struct path *path,
433 			 struct ovl_fs *ofs, int *stack_depth)
434 {
435 	int fh_type;
436 	int err;
437 
438 	err = ovl_check_namelen(path, ofs, name);
439 	if (err)
440 		return err;
441 
442 	*stack_depth = max(*stack_depth, path->mnt->mnt_sb->s_stack_depth);
443 
444 	/*
445 	 * The inodes index feature and NFS export need to encode and decode
446 	 * file handles, so they require that all layers support them.
447 	 */
448 	fh_type = ovl_can_decode_fh(path->dentry->d_sb);
449 	if ((ofs->config.nfs_export ||
450 	     (ofs->config.index && ofs->config.upperdir)) && !fh_type) {
451 		ofs->config.index = false;
452 		ofs->config.nfs_export = false;
453 		pr_warn("fs on '%s' does not support file handles, falling back to index=off,nfs_export=off.\n",
454 			name);
455 	}
456 	ofs->nofh |= !fh_type;
457 	/*
458 	 * Decoding origin file handle is required for persistent st_ino.
459 	 * Without persistent st_ino, xino=auto falls back to xino=off.
460 	 */
461 	if (ofs->config.xino == OVL_XINO_AUTO &&
462 	    ofs->config.upperdir && !fh_type) {
463 		ofs->config.xino = OVL_XINO_OFF;
464 		pr_warn("fs on '%s' does not support file handles, falling back to xino=off.\n",
465 			name);
466 	}
467 
468 	/* Check if lower fs has 32bit inode numbers */
469 	if (fh_type != FILEID_INO32_GEN)
470 		ofs->xino_mode = -1;
471 
472 	return 0;
473 }
474 
475 /*
476  * Workdir should not be subdir of upperdir and vice versa, and
477  * they should not be the same.
478  */
479 static bool ovl_workdir_ok(struct dentry *workdir, struct dentry *upperdir)
480 {
481 	return !is_subdir(workdir, upperdir) && !is_subdir(upperdir, workdir);
482 }
483 
484 static int ovl_setup_trap(struct super_block *sb, struct dentry *dir,
485 			  struct inode **ptrap, const char *name)
486 {
487 	struct inode *trap;
488 	int err;
489 
490 	trap = ovl_get_trap_inode(sb, dir);
491 	err = PTR_ERR_OR_ZERO(trap);
492 	if (err) {
493 		if (err == -ELOOP)
494 			pr_err("conflicting %s path\n", name);
495 		return err;
496 	}
497 
498 	*ptrap = trap;
499 	return 0;
500 }
501 
502 /*
503  * Determine how we treat concurrent use of upperdir/workdir based on the
504  * index feature. This is papering over mount leaks of container runtimes,
505  * for example, an old overlay mount is leaked and now its upperdir is
506  * attempted to be used as a lower layer in a new overlay mount.
507  */
508 static int ovl_report_in_use(struct ovl_fs *ofs, const char *name)
509 {
510 	if (ofs->config.index) {
511 		pr_err("%s is in-use as upperdir/workdir of another mount, mount with '-o index=off' to override exclusive upperdir protection.\n",
512 		       name);
513 		return -EBUSY;
514 	} else {
515 		pr_warn("%s is in-use as upperdir/workdir of another mount, accessing files from both mounts will result in undefined behavior.\n",
516 			name);
517 		return 0;
518 	}
519 }
520 
521 /*
522  * clone_private_mount() checks CAP_SYS_ADMIN in current->cred.
523  * ovl_fill_super_creds() runs under the stashed creator cred, which
524  * override_creds may have dropped.
525  * The task that issued FSCONFIG_CMD_CREATE is still current->real_cred, so
526  * use that only for the clone. creator_cred stays in effect for every other
527  * backing-fs operation.
528  */
529 static struct vfsmount *ovl_clone_private_mount(const struct path *path)
530 {
531 	scoped_with_creds(current_real_cred())
532 		return clone_private_mount(path);
533 }
534 
535 static int ovl_get_upper(struct super_block *sb, struct ovl_fs *ofs,
536 			 struct ovl_layer *upper_layer,
537 			 const struct path *upperpath)
538 {
539 	struct vfsmount *upper_mnt;
540 	int err;
541 
542 	/* Upperdir path should not be r/o */
543 	if (__mnt_is_readonly(upperpath->mnt)) {
544 		pr_err("upper fs is r/o, try multi-lower layers mount\n");
545 		err = -EINVAL;
546 		goto out;
547 	}
548 
549 	err = ovl_check_namelen(upperpath, ofs, ofs->config.upperdir);
550 	if (err)
551 		goto out;
552 
553 	err = ovl_setup_trap(sb, upperpath->dentry, &upper_layer->trap,
554 			     "upperdir");
555 	if (err)
556 		goto out;
557 
558 	upper_mnt = ovl_clone_private_mount(upperpath);
559 	err = PTR_ERR(upper_mnt);
560 	if (IS_ERR(upper_mnt)) {
561 		pr_err("failed to clone upperpath\n");
562 		goto out;
563 	}
564 
565 	/* Don't inherit atime flags */
566 	upper_mnt->mnt_flags &= ~(MNT_NOATIME | MNT_NODIRATIME | MNT_RELATIME);
567 	upper_layer->mnt = upper_mnt;
568 	upper_layer->idx = 0;
569 	upper_layer->fsid = 0;
570 
571 	/*
572 	 * Inherit SB_NOSEC flag from upperdir.
573 	 *
574 	 * This optimization changes behavior when a security related attribute
575 	 * (suid/sgid/security.*) is changed on an underlying layer.  This is
576 	 * okay because we don't yet have guarantees in that case, but it will
577 	 * need careful treatment once we want to honour changes to underlying
578 	 * filesystems.
579 	 */
580 	if (upper_mnt->mnt_sb->s_flags & SB_NOSEC)
581 		sb->s_flags |= SB_NOSEC;
582 
583 	if (ovl_inuse_trylock(ovl_upper_mnt(ofs)->mnt_root)) {
584 		ofs->upperdir_locked = true;
585 	} else {
586 		err = ovl_report_in_use(ofs, "upperdir");
587 		if (err)
588 			goto out;
589 	}
590 
591 	err = 0;
592 out:
593 	return err;
594 }
595 
596 /*
597  * Returns 1 if RENAME_WHITEOUT is supported, 0 if not supported and
598  * negative values if error is encountered.
599  */
600 static int ovl_check_rename_whiteout(struct ovl_fs *ofs)
601 {
602 	struct dentry *workdir = ofs->workdir;
603 	struct dentry *temp;
604 	struct dentry *whiteout;
605 	struct name_snapshot name;
606 	struct renamedata rd = {};
607 	char name2[OVL_TEMPNAME_SIZE];
608 	int err;
609 
610 	temp = ovl_create_temp(ofs, workdir, OVL_CATTR(S_IFREG | 0));
611 	err = PTR_ERR(temp);
612 	if (IS_ERR(temp))
613 		return err;
614 
615 	rd.mnt_idmap = ovl_upper_mnt_idmap(ofs);
616 	rd.old_parent = workdir;
617 	rd.new_parent = workdir;
618 	rd.flags = RENAME_WHITEOUT;
619 	ovl_tempname(name2);
620 	err = start_renaming_dentry(&rd, 0, temp, &QSTR(name2));
621 	if (err) {
622 		dput(temp);
623 		return err;
624 	}
625 
626 	/* Name is inline and stable - using snapshot as a copy helper */
627 	take_dentry_name_snapshot(&name, temp);
628 	err = ovl_do_rename_rd(&rd);
629 	end_renaming(&rd);
630 	if (err) {
631 		if (err == -EINVAL)
632 			err = 0;
633 		goto cleanup_temp;
634 	}
635 
636 	whiteout = ovl_lookup_upper_unlocked(ofs, name.name.name,
637 					     workdir, name.name.len);
638 	err = PTR_ERR(whiteout);
639 	if (IS_ERR(whiteout))
640 		goto cleanup_temp;
641 
642 	err = ovl_upper_is_whiteout(ofs, whiteout);
643 
644 	/* Best effort cleanup of whiteout and temp file */
645 	if (err)
646 		ovl_cleanup(ofs, workdir, whiteout);
647 	dput(whiteout);
648 
649 cleanup_temp:
650 	ovl_cleanup(ofs, workdir, temp);
651 	release_dentry_name_snapshot(&name);
652 	dput(temp);
653 
654 	return err;
655 }
656 
657 static struct dentry *ovl_lookup_or_create(struct ovl_fs *ofs,
658 					   struct dentry *parent,
659 					   const char *name, bool is_dir)
660 {
661 	struct dentry *child;
662 
663 	child = ovl_start_creating_upper(ofs, parent, &QSTR(name));
664 	if (!IS_ERR(child)) {
665 		if (!child->d_inode) {
666 			child = ovl_create_real(ofs, parent, child,
667 						&QSTR(name),
668 						OVL_CATTR(is_dir ? S_IFDIR :
669 								   S_IFREG));
670 		} else if (is_dir && !d_can_lookup(child)) {
671 			end_creating(child);
672 			child = ERR_PTR(-ENOTDIR);
673 		}
674 		end_creating_keep(child);
675 	}
676 	dput(parent);
677 
678 	return child;
679 }
680 
681 /*
682  * Creates $workdir/work/incompat/volatile/dirty file if it is not already
683  * present.
684  */
685 static int ovl_create_volatile_dirty(struct ovl_fs *ofs)
686 {
687 	unsigned int ctr;
688 	struct dentry *d = dget(ofs->workbasedir);
689 	static const char *const volatile_path[] = {
690 		OVL_WORKDIR_NAME, "incompat", "volatile", "dirty"
691 	};
692 	const char *const *name = volatile_path;
693 
694 	for (ctr = ARRAY_SIZE(volatile_path); ctr; ctr--, name++) {
695 		d = ovl_lookup_or_create(ofs, d, *name, ctr > 1);
696 		if (IS_ERR(d))
697 			return PTR_ERR(d);
698 	}
699 	dput(d);
700 	return 0;
701 }
702 
703 static int ovl_make_workdir(struct super_block *sb, struct ovl_fs *ofs,
704 			    const struct path *workpath)
705 {
706 	struct vfsmount *mnt = ovl_upper_mnt(ofs);
707 	struct dentry *workdir;
708 	struct file *tmpfile;
709 	bool rename_whiteout;
710 	bool d_type;
711 	int fh_type;
712 	int err;
713 
714 	err = mnt_want_write(mnt);
715 	if (err)
716 		return err;
717 
718 	workdir = ovl_workdir_create(ofs, OVL_WORKDIR_NAME, false);
719 	err = PTR_ERR(workdir);
720 	if (IS_ERR_OR_NULL(workdir))
721 		goto out;
722 
723 	ofs->workdir = workdir;
724 
725 	err = ovl_setup_trap(sb, ofs->workdir, &ofs->workdir_trap, "workdir");
726 	if (err)
727 		goto out;
728 
729 	/*
730 	 * Upper should support d_type, else whiteouts are visible.  Given
731 	 * workdir and upper are on same fs, we can do iterate_dir() on
732 	 * workdir. This check requires successful creation of workdir in
733 	 * previous step.
734 	 */
735 	err = ovl_check_d_type_supported(workpath);
736 	if (err < 0)
737 		goto out;
738 
739 	d_type = err;
740 	if (!d_type)
741 		pr_warn("upper fs needs to support d_type.\n");
742 
743 	/* Check if upper/work fs supports O_TMPFILE */
744 	tmpfile = ovl_do_tmpfile(ofs, ofs->workdir, S_IFREG | 0);
745 	ofs->tmpfile = !IS_ERR(tmpfile);
746 	if (ofs->tmpfile)
747 		fput(tmpfile);
748 	else
749 		pr_warn("upper fs does not support tmpfile.\n");
750 
751 
752 	/* Check if upper/work fs supports RENAME_WHITEOUT */
753 	err = ovl_check_rename_whiteout(ofs);
754 	if (err < 0)
755 		goto out;
756 
757 	rename_whiteout = err;
758 	if (!rename_whiteout)
759 		pr_warn("upper fs does not support RENAME_WHITEOUT.\n");
760 
761 	/*
762 	 * Check if upper/work fs supports (trusted|user).overlay.* xattr
763 	 */
764 	err = ovl_setxattr(ofs, ofs->workdir, OVL_XATTR_OPAQUE, "0", 1);
765 	if (err) {
766 		pr_warn("failed to set xattr on upper\n");
767 		ofs->noxattr = true;
768 		if (ovl_redirect_follow(ofs)) {
769 			ofs->config.redirect_mode = OVL_REDIRECT_NOFOLLOW;
770 			pr_warn("...falling back to redirect_dir=nofollow.\n");
771 		}
772 		if (ofs->config.metacopy) {
773 			ofs->config.metacopy = false;
774 			pr_warn("...falling back to metacopy=off.\n");
775 		}
776 		if (ofs->config.index) {
777 			ofs->config.index = false;
778 			pr_warn("...falling back to index=off.\n");
779 		}
780 		if (ovl_has_fsid(ofs)) {
781 			ofs->config.uuid = OVL_UUID_NULL;
782 			pr_warn("...falling back to uuid=null.\n");
783 		}
784 		/*
785 		 * xattr support is required for persistent st_ino.
786 		 * Without persistent st_ino, xino=auto falls back to xino=off.
787 		 */
788 		if (ofs->config.xino == OVL_XINO_AUTO) {
789 			ofs->config.xino = OVL_XINO_OFF;
790 			pr_warn("...falling back to xino=off.\n");
791 		}
792 		if (err == -EPERM && !ofs->config.userxattr)
793 			pr_info("try mounting with 'userxattr' option\n");
794 		err = 0;
795 	} else {
796 		ovl_removexattr(ofs, ofs->workdir, OVL_XATTR_OPAQUE);
797 	}
798 
799 	/*
800 	 * We allowed sub-optimal upper fs configuration and don't want to break
801 	 * users over kernel upgrade, but we never allowed remote upper fs, so
802 	 * we can enforce strict requirements for remote upper fs.
803 	 */
804 	if (ovl_dentry_remote(ofs->workdir) &&
805 	    (!d_type || !rename_whiteout || ofs->noxattr)) {
806 		pr_err("upper fs missing required features.\n");
807 		err = -EINVAL;
808 		goto out;
809 	}
810 
811 	/*
812 	 * For volatile mount, create a incompat/volatile/dirty file to keep
813 	 * track of it.
814 	 */
815 	if (ovl_is_volatile(&ofs->config)) {
816 		err = ovl_create_volatile_dirty(ofs);
817 		if (err < 0) {
818 			pr_err("Failed to create volatile/dirty file.\n");
819 			goto out;
820 		}
821 	}
822 
823 	/* Check if upper/work fs supports file handles */
824 	fh_type = ovl_can_decode_fh(ofs->workdir->d_sb);
825 	if (ofs->config.index && !fh_type) {
826 		ofs->config.index = false;
827 		pr_warn("upper fs does not support file handles, falling back to index=off.\n");
828 	}
829 	ofs->nofh |= !fh_type;
830 
831 	/* Check if upper fs has 32bit inode numbers */
832 	if (fh_type != FILEID_INO32_GEN)
833 		ofs->xino_mode = -1;
834 
835 	/* NFS export of r/w mount depends on index */
836 	if (ofs->config.nfs_export && !ofs->config.index) {
837 		pr_warn("NFS export requires \"index=on\", falling back to nfs_export=off.\n");
838 		ofs->config.nfs_export = false;
839 	}
840 out:
841 	mnt_drop_write(mnt);
842 	return err;
843 }
844 
845 static int ovl_get_workdir(struct super_block *sb, struct ovl_fs *ofs,
846 			   const struct path *upperpath,
847 			   const struct path *workpath)
848 {
849 	int err;
850 
851 	err = -EINVAL;
852 	if (upperpath->mnt != workpath->mnt) {
853 		pr_err("workdir and upperdir must reside under the same mount\n");
854 		return err;
855 	}
856 	if (!ovl_workdir_ok(workpath->dentry, upperpath->dentry)) {
857 		pr_err("workdir and upperdir must be separate subtrees\n");
858 		return err;
859 	}
860 
861 	ofs->workbasedir = dget(workpath->dentry);
862 
863 	if (ovl_inuse_trylock(ofs->workbasedir)) {
864 		ofs->workdir_locked = true;
865 	} else {
866 		err = ovl_report_in_use(ofs, "workdir");
867 		if (err)
868 			return err;
869 	}
870 
871 	err = ovl_setup_trap(sb, ofs->workbasedir, &ofs->workbasedir_trap,
872 			     "workdir");
873 	if (err)
874 		return err;
875 
876 	return ovl_make_workdir(sb, ofs, workpath);
877 }
878 
879 static int ovl_get_indexdir(struct super_block *sb, struct ovl_fs *ofs,
880 			    struct ovl_entry *oe, const struct path *upperpath)
881 {
882 	struct vfsmount *mnt = ovl_upper_mnt(ofs);
883 	struct dentry *indexdir;
884 	struct dentry *origin = ovl_lowerstack(oe)->dentry;
885 	const struct ovl_fh *fh;
886 	int err;
887 
888 	fh = ovl_get_origin_fh(ofs, origin);
889 	if (IS_ERR(fh))
890 		return PTR_ERR(fh);
891 
892 	err = mnt_want_write(mnt);
893 	if (err)
894 		goto out_free_fh;
895 
896 	/* Verify lower root is upper root origin */
897 	err = ovl_verify_origin_fh(ofs, upperpath->dentry, fh, true);
898 	if (err) {
899 		pr_err("failed to verify upper root origin\n");
900 		goto out;
901 	}
902 
903 	/* index dir will act also as workdir */
904 	iput(ofs->workdir_trap);
905 	ofs->workdir_trap = NULL;
906 	dput(ofs->workdir);
907 	ofs->workdir = NULL;
908 	indexdir = ovl_workdir_create(ofs, OVL_INDEXDIR_NAME, true);
909 	if (IS_ERR(indexdir)) {
910 		err = PTR_ERR(indexdir);
911 	} else if (indexdir) {
912 		ofs->workdir = indexdir;
913 		err = ovl_setup_trap(sb, indexdir, &ofs->workdir_trap,
914 				     "indexdir");
915 		if (err)
916 			goto out;
917 
918 		/*
919 		 * Verify upper root is exclusively associated with index dir.
920 		 * Older kernels stored upper fh in ".overlay.origin"
921 		 * xattr. If that xattr exists, verify that it is a match to
922 		 * upper dir file handle. In any case, verify or set xattr
923 		 * ".overlay.upper" to indicate that index may have
924 		 * directory entries.
925 		 */
926 		if (ovl_check_origin_xattr(ofs, indexdir)) {
927 			err = ovl_verify_origin_xattr(ofs, indexdir,
928 						      OVL_XATTR_ORIGIN,
929 						      upperpath->dentry, true,
930 						      false);
931 			if (err)
932 				pr_err("failed to verify index dir 'origin' xattr\n");
933 		}
934 		err = ovl_verify_upper(ofs, indexdir, upperpath->dentry, true);
935 		if (err)
936 			pr_err("failed to verify index dir 'upper' xattr\n");
937 
938 		/* Cleanup bad/stale/orphan index entries */
939 		if (!err)
940 			err = ovl_indexdir_cleanup(ofs);
941 	}
942 	if (err || !indexdir)
943 		pr_warn("try deleting index dir or mounting with '-o index=off' to disable inodes index.\n");
944 
945 out:
946 	mnt_drop_write(mnt);
947 out_free_fh:
948 	kfree(fh);
949 	return err;
950 }
951 
952 static bool ovl_lower_uuid_ok(struct ovl_fs *ofs, const uuid_t *uuid)
953 {
954 	unsigned int i;
955 
956 	if (!ofs->config.nfs_export && !ovl_upper_mnt(ofs))
957 		return true;
958 
959 	/*
960 	 * We allow using single lower with null uuid for index and nfs_export
961 	 * for example to support those features with single lower squashfs.
962 	 * To avoid regressions in setups of overlay with re-formatted lower
963 	 * squashfs, do not allow decoding origin with lower null uuid unless
964 	 * user opted-in to one of the new features that require following the
965 	 * lower inode of non-dir upper.
966 	 */
967 	if (ovl_allow_offline_changes(ofs) && uuid_is_null(uuid))
968 		return false;
969 
970 	for (i = 0; i < ofs->numfs; i++) {
971 		/*
972 		 * We use uuid to associate an overlay lower file handle with a
973 		 * lower layer, so we can accept lower fs with null uuid as long
974 		 * as all lower layers with null uuid are on the same fs.
975 		 * if we detect multiple lower fs with the same uuid, we
976 		 * disable lower file handle decoding on all of them.
977 		 */
978 		if (ofs->fs[i].is_lower &&
979 		    ovl_uuid_match(ofs, ofs->fs[i].sb, uuid)) {
980 			ofs->fs[i].bad_uuid = true;
981 			return false;
982 		}
983 	}
984 	return true;
985 }
986 
987 /* Get a unique fsid for the layer */
988 static int ovl_get_fsid(struct ovl_fs *ofs, const struct path *path)
989 {
990 	struct super_block *sb = path->mnt->mnt_sb;
991 	const uuid_t *uuid = ovl_origin_uuid(ofs) ? &sb->s_uuid : &uuid_null;
992 	unsigned int i;
993 	dev_t dev;
994 	int err;
995 	bool bad_uuid = false;
996 	bool warn = false;
997 
998 	for (i = 0; i < ofs->numfs; i++) {
999 		if (ofs->fs[i].sb == sb)
1000 			return i;
1001 	}
1002 
1003 	if (!ovl_lower_uuid_ok(ofs, uuid)) {
1004 		bad_uuid = true;
1005 		if (ofs->config.xino == OVL_XINO_AUTO) {
1006 			ofs->config.xino = OVL_XINO_OFF;
1007 			warn = true;
1008 		}
1009 		if (ofs->config.index || ofs->config.nfs_export) {
1010 			ofs->config.index = false;
1011 			ofs->config.nfs_export = false;
1012 			warn = true;
1013 		}
1014 		if (warn) {
1015 			pr_warn("%s uuid in non-single lower fs '%pd2', falling back to xino=%s,index=off,nfs_export=off.\n",
1016 				uuid_is_null(uuid) ? "null" : "conflicting",
1017 				path->dentry, ovl_xino_mode(&ofs->config));
1018 		}
1019 	}
1020 
1021 	err = get_anon_bdev(&dev);
1022 	if (err) {
1023 		pr_err("failed to get anonymous bdev for lowerpath\n");
1024 		return err;
1025 	}
1026 
1027 	ofs->fs[ofs->numfs].sb = sb;
1028 	ofs->fs[ofs->numfs].pseudo_dev = dev;
1029 	ofs->fs[ofs->numfs].bad_uuid = bad_uuid;
1030 
1031 	return ofs->numfs++;
1032 }
1033 
1034 /*
1035  * The fsid after the last lower fsid is used for the data layers.
1036  * It is a "null fs" with a null sb, null uuid, and no pseudo dev.
1037  */
1038 static int ovl_get_data_fsid(struct ovl_fs *ofs)
1039 {
1040 	return ofs->numfs;
1041 }
1042 
1043 /*
1044  * Set the ovl sb encoding as the same one used by the first layer
1045  */
1046 static int ovl_set_encoding(struct super_block *sb, struct super_block *fs_sb)
1047 {
1048 	if (!sb_has_encoding(fs_sb))
1049 		return 0;
1050 
1051 #if IS_ENABLED(CONFIG_UNICODE)
1052 	if (sb_has_strict_encoding(fs_sb)) {
1053 		pr_err("strict encoding not supported\n");
1054 		return -EINVAL;
1055 	}
1056 
1057 	sb->s_encoding = fs_sb->s_encoding;
1058 	sb->s_encoding_flags = fs_sb->s_encoding_flags;
1059 #endif
1060 	return 0;
1061 }
1062 
1063 static int ovl_get_layers(struct super_block *sb, struct ovl_fs *ofs,
1064 			  struct ovl_fs_context *ctx, struct ovl_layer *layers)
1065 {
1066 	int err;
1067 	unsigned int i;
1068 	size_t nr_merged_lower;
1069 
1070 	ofs->fs = kzalloc_objs(struct ovl_sb, ctx->nr + 2);
1071 	if (ofs->fs == NULL)
1072 		return -ENOMEM;
1073 
1074 	/*
1075 	 * idx/fsid 0 are reserved for upper fs even with lower only overlay
1076 	 * and the last fsid is reserved for "null fs" of the data layers.
1077 	 */
1078 	ofs->numfs++;
1079 
1080 	/*
1081 	 * All lower layers that share the same fs as upper layer, use the same
1082 	 * pseudo_dev as upper layer.  Allocate fs[0].pseudo_dev even for lower
1083 	 * only overlay to simplify ovl_fs_free().
1084 	 * is_lower will be set if upper fs is shared with a lower layer.
1085 	 */
1086 	err = get_anon_bdev(&ofs->fs[0].pseudo_dev);
1087 	if (err) {
1088 		pr_err("failed to get anonymous bdev for upper fs\n");
1089 		return err;
1090 	}
1091 
1092 	if (ovl_upper_mnt(ofs)) {
1093 		ofs->fs[0].sb = ovl_upper_mnt(ofs)->mnt_sb;
1094 		ofs->fs[0].is_lower = false;
1095 
1096 		if (ofs->casefold) {
1097 			err = ovl_set_encoding(sb, ofs->fs[0].sb);
1098 			if (err)
1099 				return err;
1100 		}
1101 	}
1102 
1103 	nr_merged_lower = ctx->nr - ctx->nr_data;
1104 	for (i = 0; i < ctx->nr; i++) {
1105 		struct ovl_fs_context_layer *l = &ctx->lower[i];
1106 		struct vfsmount *mnt;
1107 		struct inode *trap;
1108 		int fsid;
1109 
1110 		if (i < nr_merged_lower)
1111 			fsid = ovl_get_fsid(ofs, &l->path);
1112 		else
1113 			fsid = ovl_get_data_fsid(ofs);
1114 		if (fsid < 0)
1115 			return fsid;
1116 
1117 		/*
1118 		 * Check if lower root conflicts with this overlay layers before
1119 		 * checking if it is in-use as upperdir/workdir of "another"
1120 		 * mount, because we do not bother to check in ovl_is_inuse() if
1121 		 * the upperdir/workdir is in fact in-use by our
1122 		 * upperdir/workdir.
1123 		 */
1124 		err = ovl_setup_trap(sb, l->path.dentry, &trap, "lowerdir");
1125 		if (err)
1126 			return err;
1127 
1128 		if (ovl_is_inuse(l->path.dentry)) {
1129 			err = ovl_report_in_use(ofs, "lowerdir");
1130 			if (err) {
1131 				iput(trap);
1132 				return err;
1133 			}
1134 		}
1135 
1136 		mnt = ovl_clone_private_mount(&l->path);
1137 		err = PTR_ERR(mnt);
1138 		if (IS_ERR(mnt)) {
1139 			pr_err("failed to clone lowerpath\n");
1140 			iput(trap);
1141 			return err;
1142 		}
1143 
1144 		/*
1145 		 * Make lower layers R/O.  That way fchmod/fchown on lower file
1146 		 * will fail instead of modifying lower fs.
1147 		 */
1148 		mnt->mnt_flags |= MNT_READONLY | MNT_NOATIME;
1149 
1150 		layers[ofs->numlayer].trap = trap;
1151 		layers[ofs->numlayer].mnt = mnt;
1152 		layers[ofs->numlayer].idx = ofs->numlayer;
1153 		layers[ofs->numlayer].fsid = fsid;
1154 		layers[ofs->numlayer].fs = &ofs->fs[fsid];
1155 		/* Store for printing lowerdir=... in ovl_show_options() */
1156 		ofs->config.lowerdirs[ofs->numlayer] = l->name;
1157 		l->name = NULL;
1158 		ofs->numlayer++;
1159 		ofs->fs[fsid].is_lower = true;
1160 
1161 		if (ofs->casefold) {
1162 			if (!ovl_upper_mnt(ofs) && !sb_has_encoding(sb)) {
1163 				err = ovl_set_encoding(sb, ofs->fs[fsid].sb);
1164 				if (err)
1165 					return err;
1166 			}
1167 
1168 			if (!sb_same_encoding(sb, mnt->mnt_sb)) {
1169 				pr_err("all layers must have the same encoding\n");
1170 				return -EINVAL;
1171 			}
1172 		}
1173 	}
1174 
1175 	/*
1176 	 * When all layers on same fs, overlay can use real inode numbers.
1177 	 * With mount option "xino=<on|auto>", mounter declares that there are
1178 	 * enough free high bits in underlying fs to hold the unique fsid.
1179 	 * If overlayfs does encounter underlying inodes using the high xino
1180 	 * bits reserved for fsid, it emits a warning and uses the original
1181 	 * inode number or a non persistent inode number allocated from a
1182 	 * dedicated range.
1183 	 */
1184 	if (ofs->numfs - !ovl_upper_mnt(ofs) == 1) {
1185 		if (ofs->config.xino == OVL_XINO_ON)
1186 			pr_info("\"xino=on\" is useless with all layers on same fs, ignore.\n");
1187 		ofs->xino_mode = 0;
1188 	} else if (ofs->config.xino == OVL_XINO_OFF) {
1189 		ofs->xino_mode = -1;
1190 	} else if (ofs->xino_mode < 0) {
1191 		/*
1192 		 * This is a roundup of number of bits needed for encoding
1193 		 * fsid, where fsid 0 is reserved for upper fs (even with
1194 		 * lower only overlay) +1 extra bit is reserved for the non
1195 		 * persistent inode number range that is used for resolving
1196 		 * xino lower bits overflow.
1197 		 */
1198 		BUILD_BUG_ON(ilog2(OVL_MAX_STACK) > 30);
1199 		ofs->xino_mode = ilog2(ofs->numfs - 1) + 2;
1200 	}
1201 
1202 	if (ofs->xino_mode > 0) {
1203 		pr_info("\"xino\" feature enabled using %d upper inode bits.\n",
1204 			ofs->xino_mode);
1205 	}
1206 
1207 	return 0;
1208 }
1209 
1210 static struct ovl_entry *ovl_get_lowerstack(struct super_block *sb,
1211 					    struct ovl_fs_context *ctx,
1212 					    struct ovl_fs *ofs,
1213 					    struct ovl_layer *layers)
1214 {
1215 	int err;
1216 	unsigned int i;
1217 	size_t nr_merged_lower;
1218 	struct ovl_entry *oe;
1219 	struct ovl_path *lowerstack;
1220 
1221 	struct ovl_fs_context_layer *l;
1222 
1223 	if (!ofs->config.upperdir && ctx->nr == 1) {
1224 		pr_err("at least 2 lowerdir are needed while upperdir nonexistent\n");
1225 		return ERR_PTR(-EINVAL);
1226 	}
1227 
1228 	if (ctx->nr == ctx->nr_data) {
1229 		pr_err("at least one non-data lowerdir is required\n");
1230 		return ERR_PTR(-EINVAL);
1231 	}
1232 
1233 	err = -EINVAL;
1234 	for (i = 0; i < ctx->nr; i++) {
1235 		l = &ctx->lower[i];
1236 
1237 		err = ovl_lower_dir(l->name, &l->path, ofs, &sb->s_stack_depth);
1238 		if (err)
1239 			return ERR_PTR(err);
1240 	}
1241 
1242 	err = -EINVAL;
1243 	sb->s_stack_depth++;
1244 	if (sb->s_stack_depth > FILESYSTEM_MAX_STACK_DEPTH) {
1245 		pr_err("maximum fs stacking depth exceeded\n");
1246 		return ERR_PTR(err);
1247 	}
1248 
1249 	err = ovl_get_layers(sb, ofs, ctx, layers);
1250 	if (err)
1251 		return ERR_PTR(err);
1252 
1253 	err = -ENOMEM;
1254 	/* Data-only layers are not merged in root directory */
1255 	nr_merged_lower = ctx->nr - ctx->nr_data;
1256 	oe = ovl_alloc_entry(nr_merged_lower);
1257 	if (!oe)
1258 		return ERR_PTR(err);
1259 
1260 	lowerstack = ovl_lowerstack(oe);
1261 	for (i = 0; i < nr_merged_lower; i++) {
1262 		l = &ctx->lower[i];
1263 		lowerstack[i].dentry = dget(l->path.dentry);
1264 		lowerstack[i].layer = &ofs->layers[i + 1];
1265 	}
1266 	ofs->numdatalayer = ctx->nr_data;
1267 
1268 	return oe;
1269 }
1270 
1271 /*
1272  * Check if this layer root is a descendant of:
1273  * - another layer of this overlayfs instance
1274  * - upper/work dir of any overlayfs instance
1275  */
1276 static int ovl_check_layer(struct super_block *sb, struct ovl_fs *ofs,
1277 			   struct dentry *dentry, const char *name,
1278 			   bool is_lower)
1279 {
1280 	struct dentry *next = dentry, *parent;
1281 	int err = 0;
1282 
1283 	if (!dentry)
1284 		return 0;
1285 
1286 	parent = dget_parent(next);
1287 
1288 	/* Walk back ancestors to root (inclusive) looking for traps */
1289 	while (!err && parent != next) {
1290 		if (is_lower && ovl_lookup_trap_inode(sb, parent)) {
1291 			err = -ELOOP;
1292 			pr_err("overlapping %s path\n", name);
1293 		} else if (ovl_is_inuse(parent)) {
1294 			err = ovl_report_in_use(ofs, name);
1295 		}
1296 		next = parent;
1297 		parent = dget_parent(next);
1298 		dput(next);
1299 	}
1300 
1301 	dput(parent);
1302 
1303 	return err;
1304 }
1305 
1306 /*
1307  * Check if any of the layers or work dirs overlap.
1308  */
1309 static int ovl_check_overlapping_layers(struct super_block *sb,
1310 					struct ovl_fs *ofs)
1311 {
1312 	int i, err;
1313 
1314 	if (ovl_upper_mnt(ofs)) {
1315 		err = ovl_check_layer(sb, ofs, ovl_upper_mnt(ofs)->mnt_root,
1316 				      "upperdir", false);
1317 		if (err)
1318 			return err;
1319 
1320 		/*
1321 		 * Checking workbasedir avoids hitting ovl_is_inuse(parent) of
1322 		 * this instance and covers overlapping work and index dirs,
1323 		 * unless work or index dir have been moved since created inside
1324 		 * workbasedir.  In that case, we already have their traps in
1325 		 * inode cache and we will catch that case on lookup.
1326 		 */
1327 		err = ovl_check_layer(sb, ofs, ofs->workbasedir, "workdir",
1328 				      false);
1329 		if (err)
1330 			return err;
1331 	}
1332 
1333 	for (i = 1; i < ofs->numlayer; i++) {
1334 		err = ovl_check_layer(sb, ofs,
1335 				      ofs->layers[i].mnt->mnt_root,
1336 				      "lowerdir", true);
1337 		if (err)
1338 			return err;
1339 	}
1340 
1341 	return 0;
1342 }
1343 
1344 static struct dentry *ovl_get_root(struct super_block *sb,
1345 				   struct dentry *upperdentry,
1346 				   struct ovl_entry *oe)
1347 {
1348 	struct dentry *root;
1349 	struct ovl_fs *ofs = OVL_FS(sb);
1350 	struct ovl_path *lowerpath = ovl_lowerstack(oe);
1351 	unsigned long ino = d_inode(lowerpath->dentry)->i_ino;
1352 	int fsid = lowerpath->layer->fsid;
1353 	struct ovl_inode_params oip = {
1354 		.upperdentry = upperdentry,
1355 		.oe = oe,
1356 	};
1357 
1358 	root = d_make_root(ovl_new_inode(sb, S_IFDIR, 0));
1359 	if (!root)
1360 		return NULL;
1361 
1362 	if (upperdentry) {
1363 		/* Root inode uses upper st_ino/i_ino */
1364 		ino = d_inode(upperdentry)->i_ino;
1365 		fsid = 0;
1366 		ovl_dentry_set_upper_alias(root);
1367 		if (ovl_is_impuredir(sb, upperdentry))
1368 			ovl_set_flag(OVL_IMPURE, d_inode(root));
1369 	}
1370 
1371 	/* Look for xwhiteouts marker except in the lowermost layer */
1372 	for (int i = 0; i < ovl_numlower(oe) - 1; i++, lowerpath++) {
1373 		struct path path = {
1374 			.mnt = lowerpath->layer->mnt,
1375 			.dentry = lowerpath->dentry,
1376 		};
1377 
1378 		/* overlay.opaque=x means xwhiteouts directory */
1379 		if (ovl_get_opaquedir_val(ofs, &path) == 'x') {
1380 			ovl_layer_set_xwhiteouts(ofs, lowerpath->layer);
1381 			ovl_dentry_set_xwhiteouts(root);
1382 		}
1383 	}
1384 
1385 	/* Root is always merge -> can have whiteouts */
1386 	ovl_set_flag(OVL_WHITEOUTS, d_inode(root));
1387 	ovl_dentry_set_flag(OVL_E_CONNECTED, root);
1388 	ovl_set_upperdata(d_inode(root));
1389 	ovl_inode_init(d_inode(root), &oip, ino, fsid);
1390 	ovl_dentry_init_flags(root, upperdentry, oe, DCACHE_OP_WEAK_REVALIDATE);
1391 	/* root keeps a reference of upperdentry */
1392 	dget(upperdentry);
1393 
1394 	return root;
1395 }
1396 
1397 static void ovl_set_d_op(struct super_block *sb)
1398 {
1399 #if IS_ENABLED(CONFIG_UNICODE)
1400 	struct ovl_fs *ofs = sb->s_fs_info;
1401 
1402 	if (ofs->casefold) {
1403 		set_default_d_op(sb, &ovl_dentry_ci_operations);
1404 		return;
1405 	}
1406 #endif
1407 	set_default_d_op(sb, &ovl_dentry_operations);
1408 }
1409 
1410 static int ovl_fill_super_creds(struct fs_context *fc, struct super_block *sb)
1411 {
1412 	struct ovl_fs *ofs = sb->s_fs_info;
1413 	struct cred *creator_cred = (struct cred *)ofs->creator_cred;
1414 	struct ovl_fs_context *ctx = fc->fs_private;
1415 	struct ovl_layer *layers;
1416 	struct ovl_entry *oe = NULL;
1417 	int err;
1418 
1419 	err = ovl_fs_params_verify(ctx, &ofs->config);
1420 	if (err)
1421 		return err;
1422 
1423 	err = -EINVAL;
1424 	if (ctx->nr == 0) {
1425 		if (!(fc->sb_flags & SB_SILENT))
1426 			pr_err("missing 'lowerdir'\n");
1427 		return err;
1428 	}
1429 
1430 	err = -ENOMEM;
1431 	layers = kzalloc_objs(struct ovl_layer, ctx->nr + 1);
1432 	if (!layers)
1433 		return err;
1434 
1435 	ofs->config.lowerdirs = kcalloc(ctx->nr + 1, sizeof(char *), GFP_KERNEL);
1436 	if (!ofs->config.lowerdirs) {
1437 		kfree(layers);
1438 		return err;
1439 	}
1440 	ofs->layers = layers;
1441 	/*
1442 	 * Layer 0 is reserved for upper even if there's no upper.
1443 	 * config.lowerdirs[0] is used for storing the user provided colon
1444 	 * separated lowerdir string.
1445 	 */
1446 	ofs->config.lowerdirs[0] = ctx->lowerdir_all;
1447 	ctx->lowerdir_all = NULL;
1448 	ofs->numlayer = 1;
1449 
1450 	sb->s_stack_depth = 0;
1451 	sb->s_maxbytes = MAX_LFS_FILESIZE;
1452 	atomic_long_set(&ofs->last_ino, 1);
1453 	/* Assume underlying fs uses 32bit inodes unless proven otherwise */
1454 	if (ofs->config.xino != OVL_XINO_OFF) {
1455 		ofs->xino_mode = BITS_PER_LONG - 32;
1456 		if (!ofs->xino_mode) {
1457 			pr_warn("xino not supported on 32bit kernel, falling back to xino=off.\n");
1458 			ofs->config.xino = OVL_XINO_OFF;
1459 		}
1460 	}
1461 
1462 	/* alloc/destroy_inode needed for setting up traps in inode cache */
1463 	sb->s_op = &ovl_super_operations;
1464 
1465 	if (ofs->config.upperdir) {
1466 		struct super_block *upper_sb;
1467 
1468 		err = -EINVAL;
1469 		if (!ofs->config.workdir) {
1470 			pr_err("missing 'workdir'\n");
1471 			return err;
1472 		}
1473 
1474 		err = ovl_get_upper(sb, ofs, &layers[0], &ctx->upper);
1475 		if (err)
1476 			return err;
1477 
1478 		upper_sb = ovl_upper_mnt(ofs)->mnt_sb;
1479 		if (!ovl_should_sync(ofs)) {
1480 			ofs->errseq = errseq_sample(&upper_sb->s_wb_err);
1481 			if (errseq_check(&upper_sb->s_wb_err, ofs->errseq)) {
1482 				err = -EIO;
1483 				pr_err("Cannot mount volatile when upperdir has an unseen error. Sync upperdir fs to clear state.\n");
1484 				return err;
1485 			}
1486 		}
1487 
1488 		err = ovl_get_workdir(sb, ofs, &ctx->upper, &ctx->work);
1489 		if (err)
1490 			return err;
1491 
1492 		if (!ofs->workdir)
1493 			sb->s_flags |= SB_RDONLY;
1494 
1495 		sb->s_stack_depth = upper_sb->s_stack_depth;
1496 		sb->s_time_gran = upper_sb->s_time_gran;
1497 	}
1498 	oe = ovl_get_lowerstack(sb, ctx, ofs, layers);
1499 	err = PTR_ERR(oe);
1500 	if (IS_ERR(oe))
1501 		return err;
1502 
1503 	/* If the upper fs is nonexistent, we mark overlayfs r/o too */
1504 	if (!ovl_upper_mnt(ofs))
1505 		sb->s_flags |= SB_RDONLY;
1506 
1507 	if (ovl_has_fsid(ofs) && ovl_upper_mnt(ofs)) {
1508 		/* Use per instance persistent uuid/fsid */
1509 		ovl_init_uuid_xattr(sb, ofs, &ctx->upper);
1510 	}
1511 
1512 	if (!ovl_force_readonly(ofs) && ofs->config.index) {
1513 		err = ovl_get_indexdir(sb, ofs, oe, &ctx->upper);
1514 		if (err)
1515 			goto out_free_oe;
1516 
1517 		/* Force r/o mount with no index dir */
1518 		if (!ofs->workdir)
1519 			sb->s_flags |= SB_RDONLY;
1520 	}
1521 
1522 	err = ovl_check_overlapping_layers(sb, ofs);
1523 	if (err)
1524 		goto out_free_oe;
1525 
1526 	/* Show index=off in /proc/mounts for forced r/o mount */
1527 	if (!ofs->workdir) {
1528 		ofs->config.index = false;
1529 		if (ovl_upper_mnt(ofs) && ofs->config.nfs_export) {
1530 			pr_warn("NFS export requires an index dir, falling back to nfs_export=off.\n");
1531 			ofs->config.nfs_export = false;
1532 		}
1533 	}
1534 
1535 	if (ofs->config.metacopy && ofs->config.nfs_export) {
1536 		pr_warn("NFS export is not supported with metadata only copy up, falling back to nfs_export=off.\n");
1537 		ofs->config.nfs_export = false;
1538 	}
1539 
1540 	/*
1541 	 * Support encoding decodable file handles with nfs_export=on
1542 	 * and encoding non-decodable file handles with nfs_export=off
1543 	 * if all layers support file handles.
1544 	 */
1545 	if (ofs->config.nfs_export)
1546 		sb->s_export_op = &ovl_export_operations;
1547 	else if (!ofs->nofh)
1548 		sb->s_export_op = &ovl_export_fid_operations;
1549 
1550 	/* Never override disk quota limits or use reserved space */
1551 	cap_lower(creator_cred->cap_effective, CAP_SYS_RESOURCE);
1552 
1553 	sb->s_magic = OVERLAYFS_SUPER_MAGIC;
1554 	sb->s_xattr = ovl_xattr_handlers(ofs);
1555 	sb->s_fs_info = ofs;
1556 #ifdef CONFIG_FS_POSIX_ACL
1557 	sb->s_flags |= SB_POSIXACL;
1558 #endif
1559 	sb->s_iflags |= SB_I_SKIP_SYNC;
1560 	/*
1561 	 * Ensure that umask handling is done by the filesystems used
1562 	 * for the the upper layer instead of overlayfs as that would
1563 	 * lead to unexpected results.
1564 	 */
1565 	sb->s_iflags |= SB_I_NOUMASK;
1566 	sb->s_iflags |= SB_I_EVM_HMAC_UNSUPPORTED;
1567 
1568 	err = -ENOMEM;
1569 	sb->s_root = ovl_get_root(sb, ctx->upper.dentry, oe);
1570 	if (!sb->s_root)
1571 		goto out_free_oe;
1572 
1573 	/*
1574 	 * The casefold flag of an empty layer root may have changed since the
1575 	 * mount options were parsed.  The root inode owns oe by now.
1576 	 */
1577 	if (!!IS_CASEFOLDED(d_inode(sb->s_root)) != ofs->casefold) {
1578 		pr_err("casefold flag of the root directory has changed\n");
1579 		dput(sb->s_root);
1580 		sb->s_root = NULL;
1581 		return -EINVAL;
1582 	}
1583 
1584 	return 0;
1585 
1586 out_free_oe:
1587 	ovl_free_entry(oe);
1588 	return err;
1589 }
1590 
1591 int ovl_fill_super(struct super_block *sb, struct fs_context *fc)
1592 {
1593 	struct ovl_fs *ofs = sb->s_fs_info;
1594 	int err;
1595 
1596 	err = -EINVAL;
1597 	/* The fscontext fd may have been passed to another user namespace. */
1598 	if (fc->user_ns != current_user_ns())
1599 		goto out_err;
1600 
1601 	ovl_set_d_op(sb);
1602 
1603 	if (!ofs->creator_cred) {
1604 		err = -ENOMEM;
1605 		ofs->creator_cred = prepare_creds();
1606 		if (!ofs->creator_cred)
1607 			goto out_err;
1608 	}
1609 
1610 	with_ovl_creds(sb)
1611 		err = ovl_fill_super_creds(fc, sb);
1612 
1613 out_err:
1614 	if (err) {
1615 		ovl_free_fs(ofs);
1616 		sb->s_fs_info = NULL;
1617 	}
1618 
1619 	return err;
1620 }
1621 
1622 struct file_system_type ovl_fs_type = {
1623 	.owner			= THIS_MODULE,
1624 	.name			= "overlay",
1625 	.init_fs_context	= ovl_init_fs_context,
1626 	.parameters		= ovl_parameter_spec,
1627 	.fs_flags		= FS_USERNS_MOUNT | FS_ALLOW_IDMAP,
1628 	.kill_sb		= kill_anon_super,
1629 };
1630 MODULE_ALIAS_FS("overlay");
1631 
1632 static void ovl_inode_init_once(void *foo)
1633 {
1634 	struct ovl_inode *oi = foo;
1635 
1636 	inode_init_once(&oi->vfs_inode);
1637 }
1638 
1639 static int __init ovl_init(void)
1640 {
1641 	int err;
1642 
1643 	ovl_inode_cachep = kmem_cache_create("ovl_inode",
1644 					     sizeof(struct ovl_inode), 0,
1645 					     (SLAB_RECLAIM_ACCOUNT|
1646 					      SLAB_ACCOUNT),
1647 					     ovl_inode_init_once);
1648 	if (ovl_inode_cachep == NULL)
1649 		return -ENOMEM;
1650 
1651 	err = register_filesystem(&ovl_fs_type);
1652 	if (!err)
1653 		return 0;
1654 
1655 	kmem_cache_destroy(ovl_inode_cachep);
1656 
1657 	return err;
1658 }
1659 
1660 static void __exit ovl_exit(void)
1661 {
1662 	unregister_filesystem(&ovl_fs_type);
1663 
1664 	/*
1665 	 * Make sure all delayed rcu free inodes are flushed before we
1666 	 * destroy cache.
1667 	 */
1668 	rcu_barrier();
1669 	kmem_cache_destroy(ovl_inode_cachep);
1670 }
1671 
1672 module_init(ovl_init);
1673 module_exit(ovl_exit);
1674