xref: /linux/fs/overlayfs/super.c (revision 720f40c05b2785406121da0151543751204f2953)
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, size_t nr_data)
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_lower(ofs)) {
769 			ofs->config.redirect_mode =
770 				ovl_redirect_follow_mode(false, nr_data);
771 			pr_warn("...falling back to redirect_dir=%s.\n",
772 				ovl_redirect_mode(&ofs->config));
773 		}
774 		if (ofs->config.metacopy) {
775 			ofs->config.metacopy = false;
776 			pr_warn("...falling back to metacopy=off.\n");
777 		}
778 		if (ofs->config.index) {
779 			ofs->config.index = false;
780 			pr_warn("...falling back to index=off.\n");
781 		}
782 		if (ovl_has_fsid(ofs)) {
783 			ofs->config.uuid = OVL_UUID_NULL;
784 			pr_warn("...falling back to uuid=null.\n");
785 		}
786 		/*
787 		 * xattr support is required for persistent st_ino.
788 		 * Without persistent st_ino, xino=auto falls back to xino=off.
789 		 */
790 		if (ofs->config.xino == OVL_XINO_AUTO) {
791 			ofs->config.xino = OVL_XINO_OFF;
792 			pr_warn("...falling back to xino=off.\n");
793 		}
794 		if (err == -EPERM && !ofs->config.userxattr)
795 			pr_info("try mounting with 'userxattr' option\n");
796 		err = 0;
797 	} else {
798 		ovl_removexattr(ofs, ofs->workdir, OVL_XATTR_OPAQUE);
799 	}
800 
801 	/*
802 	 * We allowed sub-optimal upper fs configuration and don't want to break
803 	 * users over kernel upgrade, but we never allowed remote upper fs, so
804 	 * we can enforce strict requirements for remote upper fs.
805 	 */
806 	if (ovl_dentry_remote(ofs->workdir) &&
807 	    (!d_type || !rename_whiteout || ofs->noxattr)) {
808 		pr_err("upper fs missing required features.\n");
809 		err = -EINVAL;
810 		goto out;
811 	}
812 
813 	/*
814 	 * For volatile mount, create a incompat/volatile/dirty file to keep
815 	 * track of it.
816 	 */
817 	if (ovl_is_volatile(&ofs->config)) {
818 		err = ovl_create_volatile_dirty(ofs);
819 		if (err < 0) {
820 			pr_err("Failed to create volatile/dirty file.\n");
821 			goto out;
822 		}
823 	}
824 
825 	/* Check if upper/work fs supports file handles */
826 	fh_type = ovl_can_decode_fh(ofs->workdir->d_sb);
827 	if (ofs->config.index && !fh_type) {
828 		ofs->config.index = false;
829 		pr_warn("upper fs does not support file handles, falling back to index=off.\n");
830 	}
831 	ofs->nofh |= !fh_type;
832 
833 	/* Check if upper fs has 32bit inode numbers */
834 	if (fh_type != FILEID_INO32_GEN)
835 		ofs->xino_mode = -1;
836 
837 	/* NFS export of r/w mount depends on index */
838 	if (ofs->config.nfs_export && !ofs->config.index) {
839 		pr_warn("NFS export requires \"index=on\", falling back to nfs_export=off.\n");
840 		ofs->config.nfs_export = false;
841 	}
842 out:
843 	mnt_drop_write(mnt);
844 	return err;
845 }
846 
847 static int ovl_get_workdir(struct super_block *sb, struct ovl_fs *ofs,
848 			   const struct path *upperpath,
849 			   const struct path *workpath, size_t nr_data)
850 {
851 	int err;
852 
853 	err = -EINVAL;
854 	if (upperpath->mnt != workpath->mnt) {
855 		pr_err("workdir and upperdir must reside under the same mount\n");
856 		return err;
857 	}
858 	if (!ovl_workdir_ok(workpath->dentry, upperpath->dentry)) {
859 		pr_err("workdir and upperdir must be separate subtrees\n");
860 		return err;
861 	}
862 
863 	ofs->workbasedir = dget(workpath->dentry);
864 
865 	if (ovl_inuse_trylock(ofs->workbasedir)) {
866 		ofs->workdir_locked = true;
867 	} else {
868 		err = ovl_report_in_use(ofs, "workdir");
869 		if (err)
870 			return err;
871 	}
872 
873 	err = ovl_setup_trap(sb, ofs->workbasedir, &ofs->workbasedir_trap,
874 			     "workdir");
875 	if (err)
876 		return err;
877 
878 	return ovl_make_workdir(sb, ofs, workpath, nr_data);
879 }
880 
881 static int ovl_get_indexdir(struct super_block *sb, struct ovl_fs *ofs,
882 			    struct ovl_entry *oe, const struct path *upperpath)
883 {
884 	struct vfsmount *mnt = ovl_upper_mnt(ofs);
885 	struct dentry *indexdir;
886 	struct dentry *origin = ovl_lowerstack(oe)->dentry;
887 	const struct ovl_fh *fh;
888 	int err;
889 
890 	fh = ovl_get_origin_fh(ofs, origin);
891 	if (IS_ERR(fh))
892 		return PTR_ERR(fh);
893 
894 	err = mnt_want_write(mnt);
895 	if (err)
896 		goto out_free_fh;
897 
898 	/* Verify lower root is upper root origin */
899 	err = ovl_verify_origin_fh(ofs, upperpath->dentry, fh, true);
900 	if (err) {
901 		pr_err("failed to verify upper root origin\n");
902 		goto out;
903 	}
904 
905 	/* index dir will act also as workdir */
906 	iput(ofs->workdir_trap);
907 	ofs->workdir_trap = NULL;
908 	dput(ofs->workdir);
909 	ofs->workdir = NULL;
910 	indexdir = ovl_workdir_create(ofs, OVL_INDEXDIR_NAME, true);
911 	if (IS_ERR(indexdir)) {
912 		err = PTR_ERR(indexdir);
913 	} else if (indexdir) {
914 		ofs->workdir = indexdir;
915 		err = ovl_setup_trap(sb, indexdir, &ofs->workdir_trap,
916 				     "indexdir");
917 		if (err)
918 			goto out;
919 
920 		/*
921 		 * Verify upper root is exclusively associated with index dir.
922 		 * Older kernels stored upper fh in ".overlay.origin"
923 		 * xattr. If that xattr exists, verify that it is a match to
924 		 * upper dir file handle. In any case, verify or set xattr
925 		 * ".overlay.upper" to indicate that index may have
926 		 * directory entries.
927 		 */
928 		if (ovl_check_origin_xattr(ofs, indexdir)) {
929 			err = ovl_verify_origin_xattr(ofs, indexdir,
930 						      OVL_XATTR_ORIGIN,
931 						      upperpath->dentry, true,
932 						      false);
933 			if (err)
934 				pr_err("failed to verify index dir 'origin' xattr\n");
935 		}
936 		err = ovl_verify_upper(ofs, indexdir, upperpath->dentry, true);
937 		if (err)
938 			pr_err("failed to verify index dir 'upper' xattr\n");
939 
940 		/* Cleanup bad/stale/orphan index entries */
941 		if (!err)
942 			err = ovl_indexdir_cleanup(ofs);
943 	}
944 	if (err || !indexdir)
945 		pr_warn("try deleting index dir or mounting with '-o index=off' to disable inodes index.\n");
946 
947 out:
948 	mnt_drop_write(mnt);
949 out_free_fh:
950 	kfree(fh);
951 	return err;
952 }
953 
954 static bool ovl_lower_uuid_ok(struct ovl_fs *ofs, const uuid_t *uuid)
955 {
956 	unsigned int i;
957 
958 	if (!ofs->config.nfs_export && !ovl_upper_mnt(ofs))
959 		return true;
960 
961 	/*
962 	 * We allow using single lower with null uuid for index and nfs_export
963 	 * for example to support those features with single lower squashfs.
964 	 * To avoid regressions in setups of overlay with re-formatted lower
965 	 * squashfs, do not allow decoding origin with lower null uuid unless
966 	 * user opted-in to one of the new features that require following the
967 	 * lower inode of non-dir upper.
968 	 */
969 	if (ovl_allow_offline_changes(ofs) && uuid_is_null(uuid))
970 		return false;
971 
972 	for (i = 0; i < ofs->numfs; i++) {
973 		/*
974 		 * We use uuid to associate an overlay lower file handle with a
975 		 * lower layer, so we can accept lower fs with null uuid as long
976 		 * as all lower layers with null uuid are on the same fs.
977 		 * if we detect multiple lower fs with the same uuid, we
978 		 * disable lower file handle decoding on all of them.
979 		 */
980 		if (ofs->fs[i].is_lower &&
981 		    ovl_uuid_match(ofs, ofs->fs[i].sb, uuid)) {
982 			ofs->fs[i].bad_uuid = true;
983 			return false;
984 		}
985 	}
986 	return true;
987 }
988 
989 /* Get a unique fsid for the layer */
990 static int ovl_get_fsid(struct ovl_fs *ofs, const struct path *path)
991 {
992 	struct super_block *sb = path->mnt->mnt_sb;
993 	const uuid_t *uuid = ovl_origin_uuid(ofs) ? &sb->s_uuid : &uuid_null;
994 	unsigned int i;
995 	dev_t dev;
996 	int err;
997 	bool bad_uuid = false;
998 	bool warn = false;
999 
1000 	for (i = 0; i < ofs->numfs; i++) {
1001 		if (ofs->fs[i].sb == sb)
1002 			return i;
1003 	}
1004 
1005 	if (!ovl_lower_uuid_ok(ofs, uuid)) {
1006 		bad_uuid = true;
1007 		if (ofs->config.xino == OVL_XINO_AUTO) {
1008 			ofs->config.xino = OVL_XINO_OFF;
1009 			warn = true;
1010 		}
1011 		if (ofs->config.index || ofs->config.nfs_export) {
1012 			ofs->config.index = false;
1013 			ofs->config.nfs_export = false;
1014 			warn = true;
1015 		}
1016 		if (warn) {
1017 			pr_warn("%s uuid in non-single lower fs '%pd2', falling back to xino=%s,index=off,nfs_export=off.\n",
1018 				uuid_is_null(uuid) ? "null" : "conflicting",
1019 				path->dentry, ovl_xino_mode(&ofs->config));
1020 		}
1021 	}
1022 
1023 	err = get_anon_bdev(&dev);
1024 	if (err) {
1025 		pr_err("failed to get anonymous bdev for lowerpath\n");
1026 		return err;
1027 	}
1028 
1029 	ofs->fs[ofs->numfs].sb = sb;
1030 	ofs->fs[ofs->numfs].pseudo_dev = dev;
1031 	ofs->fs[ofs->numfs].bad_uuid = bad_uuid;
1032 
1033 	return ofs->numfs++;
1034 }
1035 
1036 /*
1037  * The fsid after the last lower fsid is used for the data layers.
1038  * It is a "null fs" with a null sb, null uuid, and no pseudo dev.
1039  */
1040 static int ovl_get_data_fsid(struct ovl_fs *ofs)
1041 {
1042 	return ofs->numfs;
1043 }
1044 
1045 /*
1046  * Set the ovl sb encoding as the same one used by the first layer
1047  */
1048 static int ovl_set_encoding(struct super_block *sb, struct super_block *fs_sb)
1049 {
1050 	if (!sb_has_encoding(fs_sb))
1051 		return 0;
1052 
1053 #if IS_ENABLED(CONFIG_UNICODE)
1054 	if (sb_has_strict_encoding(fs_sb)) {
1055 		pr_err("strict encoding not supported\n");
1056 		return -EINVAL;
1057 	}
1058 
1059 	sb->s_encoding = fs_sb->s_encoding;
1060 	sb->s_encoding_flags = fs_sb->s_encoding_flags;
1061 #endif
1062 	return 0;
1063 }
1064 
1065 static int ovl_get_layers(struct super_block *sb, struct ovl_fs *ofs,
1066 			  struct ovl_fs_context *ctx, struct ovl_layer *layers)
1067 {
1068 	int err;
1069 	unsigned int i;
1070 	size_t nr_merged_lower;
1071 
1072 	ofs->fs = kzalloc_objs(struct ovl_sb, ctx->nr + 2);
1073 	if (ofs->fs == NULL)
1074 		return -ENOMEM;
1075 
1076 	/*
1077 	 * idx/fsid 0 are reserved for upper fs even with lower only overlay
1078 	 * and the last fsid is reserved for "null fs" of the data layers.
1079 	 */
1080 	ofs->numfs++;
1081 
1082 	/*
1083 	 * All lower layers that share the same fs as upper layer, use the same
1084 	 * pseudo_dev as upper layer.  Allocate fs[0].pseudo_dev even for lower
1085 	 * only overlay to simplify ovl_fs_free().
1086 	 * is_lower will be set if upper fs is shared with a lower layer.
1087 	 */
1088 	err = get_anon_bdev(&ofs->fs[0].pseudo_dev);
1089 	if (err) {
1090 		pr_err("failed to get anonymous bdev for upper fs\n");
1091 		return err;
1092 	}
1093 
1094 	if (ovl_upper_mnt(ofs)) {
1095 		ofs->fs[0].sb = ovl_upper_mnt(ofs)->mnt_sb;
1096 		ofs->fs[0].is_lower = false;
1097 
1098 		if (ofs->casefold) {
1099 			err = ovl_set_encoding(sb, ofs->fs[0].sb);
1100 			if (err)
1101 				return err;
1102 		}
1103 	}
1104 
1105 	nr_merged_lower = ctx->nr - ctx->nr_data;
1106 	for (i = 0; i < ctx->nr; i++) {
1107 		struct ovl_fs_context_layer *l = &ctx->lower[i];
1108 		struct vfsmount *mnt;
1109 		struct inode *trap;
1110 		int fsid;
1111 
1112 		if (i < nr_merged_lower)
1113 			fsid = ovl_get_fsid(ofs, &l->path);
1114 		else
1115 			fsid = ovl_get_data_fsid(ofs);
1116 		if (fsid < 0)
1117 			return fsid;
1118 
1119 		/*
1120 		 * Check if lower root conflicts with this overlay layers before
1121 		 * checking if it is in-use as upperdir/workdir of "another"
1122 		 * mount, because we do not bother to check in ovl_is_inuse() if
1123 		 * the upperdir/workdir is in fact in-use by our
1124 		 * upperdir/workdir.
1125 		 */
1126 		err = ovl_setup_trap(sb, l->path.dentry, &trap, "lowerdir");
1127 		if (err)
1128 			return err;
1129 
1130 		if (ovl_is_inuse(l->path.dentry)) {
1131 			err = ovl_report_in_use(ofs, "lowerdir");
1132 			if (err) {
1133 				iput(trap);
1134 				return err;
1135 			}
1136 		}
1137 
1138 		mnt = ovl_clone_private_mount(&l->path);
1139 		err = PTR_ERR(mnt);
1140 		if (IS_ERR(mnt)) {
1141 			pr_err("failed to clone lowerpath\n");
1142 			iput(trap);
1143 			return err;
1144 		}
1145 
1146 		/*
1147 		 * Lower file handles identify the lower fs, but not the layer,
1148 		 * so with different idmaps on the same lower fs, index and
1149 		 * nfs_export may decode a file handle through a layer with the
1150 		 * wrong idmap.  Following copy up origin without index is only
1151 		 * used for st_ino, which does not depend on the idmap.
1152 		 */
1153 		if (i < nr_merged_lower &&
1154 		    (ofs->config.index || ofs->config.nfs_export)) {
1155 			const struct mnt_idmap *idmap = mnt_idmap(mnt);
1156 			struct ovl_sb *fs = &ofs->fs[fsid];
1157 
1158 			if (!fs->lower_idmap) {
1159 				fs->lower_idmap = idmap;
1160 			} else if (fs->lower_idmap != idmap) {
1161 				pr_err("lower layer '%pd2' conflicts with idmap of another lower layer on the same fs, mount with '-o index=off,nfs_export=off' to override.\n",
1162 				       l->path.dentry);
1163 				iput(trap);
1164 				kern_unmount(mnt);
1165 				return -EINVAL;
1166 			}
1167 		}
1168 
1169 		/*
1170 		 * Make lower layers R/O.  That way fchmod/fchown on lower file
1171 		 * will fail instead of modifying lower fs.
1172 		 */
1173 		mnt->mnt_flags |= MNT_READONLY | MNT_NOATIME;
1174 
1175 		layers[ofs->numlayer].trap = trap;
1176 		layers[ofs->numlayer].mnt = mnt;
1177 		layers[ofs->numlayer].idx = ofs->numlayer;
1178 		layers[ofs->numlayer].fsid = fsid;
1179 		layers[ofs->numlayer].fs = &ofs->fs[fsid];
1180 		/* Store for printing lowerdir=... in ovl_show_options() */
1181 		ofs->config.lowerdirs[ofs->numlayer] = l->name;
1182 		l->name = NULL;
1183 		ofs->numlayer++;
1184 		ofs->fs[fsid].is_lower = true;
1185 
1186 		if (ofs->casefold) {
1187 			if (!ovl_upper_mnt(ofs) && !sb_has_encoding(sb)) {
1188 				err = ovl_set_encoding(sb, ofs->fs[fsid].sb);
1189 				if (err)
1190 					return err;
1191 			}
1192 
1193 			if (!sb_same_encoding(sb, mnt->mnt_sb)) {
1194 				pr_err("all layers must have the same encoding\n");
1195 				return -EINVAL;
1196 			}
1197 		}
1198 	}
1199 
1200 	/*
1201 	 * When all layers on same fs, overlay can use real inode numbers.
1202 	 * With mount option "xino=<on|auto>", mounter declares that there are
1203 	 * enough free high bits in underlying fs to hold the unique fsid.
1204 	 * If overlayfs does encounter underlying inodes using the high xino
1205 	 * bits reserved for fsid, it emits a warning and uses the original
1206 	 * inode number or a non persistent inode number allocated from a
1207 	 * dedicated range.
1208 	 */
1209 	if (ofs->numfs - !ovl_upper_mnt(ofs) == 1) {
1210 		if (ofs->config.xino == OVL_XINO_ON)
1211 			pr_info("\"xino=on\" is useless with all layers on same fs, ignore.\n");
1212 		ofs->xino_mode = 0;
1213 	} else if (ofs->config.xino == OVL_XINO_OFF) {
1214 		ofs->xino_mode = -1;
1215 	} else if (ofs->xino_mode < 0) {
1216 		/*
1217 		 * This is a roundup of number of bits needed for encoding
1218 		 * fsid, where fsid 0 is reserved for upper fs (even with
1219 		 * lower only overlay) +1 extra bit is reserved for the non
1220 		 * persistent inode number range that is used for resolving
1221 		 * xino lower bits overflow.
1222 		 */
1223 		BUILD_BUG_ON(ilog2(OVL_MAX_STACK) > 30);
1224 		ofs->xino_mode = ilog2(ofs->numfs - 1) + 2;
1225 	}
1226 
1227 	if (ofs->xino_mode > 0) {
1228 		pr_info("\"xino\" feature enabled using %d upper inode bits.\n",
1229 			ofs->xino_mode);
1230 	}
1231 
1232 	return 0;
1233 }
1234 
1235 static struct ovl_entry *ovl_get_lowerstack(struct super_block *sb,
1236 					    struct ovl_fs_context *ctx,
1237 					    struct ovl_fs *ofs,
1238 					    struct ovl_layer *layers)
1239 {
1240 	int err;
1241 	unsigned int i;
1242 	size_t nr_merged_lower;
1243 	struct ovl_entry *oe;
1244 	struct ovl_path *lowerstack;
1245 
1246 	struct ovl_fs_context_layer *l;
1247 
1248 	if (!ofs->config.upperdir && ctx->nr == 1) {
1249 		pr_err("at least 2 lowerdir are needed while upperdir nonexistent\n");
1250 		return ERR_PTR(-EINVAL);
1251 	}
1252 
1253 	if (ctx->nr == ctx->nr_data) {
1254 		pr_err("at least one non-data lowerdir is required\n");
1255 		return ERR_PTR(-EINVAL);
1256 	}
1257 
1258 	err = -EINVAL;
1259 	for (i = 0; i < ctx->nr; i++) {
1260 		l = &ctx->lower[i];
1261 
1262 		err = ovl_lower_dir(l->name, &l->path, ofs, &sb->s_stack_depth);
1263 		if (err)
1264 			return ERR_PTR(err);
1265 	}
1266 
1267 	err = -EINVAL;
1268 	sb->s_stack_depth++;
1269 	if (sb->s_stack_depth > FILESYSTEM_MAX_STACK_DEPTH) {
1270 		pr_err("maximum fs stacking depth exceeded\n");
1271 		return ERR_PTR(err);
1272 	}
1273 
1274 	err = ovl_get_layers(sb, ofs, ctx, layers);
1275 	if (err)
1276 		return ERR_PTR(err);
1277 
1278 	err = -ENOMEM;
1279 	/* Data-only layers are not merged in root directory */
1280 	nr_merged_lower = ctx->nr - ctx->nr_data;
1281 	oe = ovl_alloc_entry(nr_merged_lower);
1282 	if (!oe)
1283 		return ERR_PTR(err);
1284 
1285 	lowerstack = ovl_lowerstack(oe);
1286 	for (i = 0; i < nr_merged_lower; i++) {
1287 		l = &ctx->lower[i];
1288 		lowerstack[i].dentry = dget(l->path.dentry);
1289 		lowerstack[i].layer = &ofs->layers[i + 1];
1290 	}
1291 	ofs->numdatalayer = ctx->nr_data;
1292 
1293 	return oe;
1294 }
1295 
1296 /*
1297  * Check if this layer root is a descendant of:
1298  * - another layer of this overlayfs instance
1299  * - upper/work dir of any overlayfs instance
1300  */
1301 static int ovl_check_layer(struct super_block *sb, struct ovl_fs *ofs,
1302 			   struct dentry *dentry, const char *name,
1303 			   bool is_lower)
1304 {
1305 	struct dentry *next = dentry, *parent;
1306 	int err = 0;
1307 
1308 	if (!dentry)
1309 		return 0;
1310 
1311 	parent = dget_parent(next);
1312 
1313 	/* Walk back ancestors to root (inclusive) looking for traps */
1314 	while (!err && parent != next) {
1315 		if (is_lower && ovl_lookup_trap_inode(sb, parent)) {
1316 			err = -ELOOP;
1317 			pr_err("overlapping %s path\n", name);
1318 		} else if (ovl_is_inuse(parent)) {
1319 			err = ovl_report_in_use(ofs, name);
1320 		}
1321 		next = parent;
1322 		parent = dget_parent(next);
1323 		dput(next);
1324 	}
1325 
1326 	dput(parent);
1327 
1328 	return err;
1329 }
1330 
1331 /*
1332  * Check if any of the layers or work dirs overlap.
1333  */
1334 static int ovl_check_overlapping_layers(struct super_block *sb,
1335 					struct ovl_fs *ofs)
1336 {
1337 	int i, err;
1338 
1339 	if (ovl_upper_mnt(ofs)) {
1340 		err = ovl_check_layer(sb, ofs, ovl_upper_mnt(ofs)->mnt_root,
1341 				      "upperdir", false);
1342 		if (err)
1343 			return err;
1344 
1345 		/*
1346 		 * Checking workbasedir avoids hitting ovl_is_inuse(parent) of
1347 		 * this instance and covers overlapping work and index dirs,
1348 		 * unless work or index dir have been moved since created inside
1349 		 * workbasedir.  In that case, we already have their traps in
1350 		 * inode cache and we will catch that case on lookup.
1351 		 */
1352 		err = ovl_check_layer(sb, ofs, ofs->workbasedir, "workdir",
1353 				      false);
1354 		if (err)
1355 			return err;
1356 	}
1357 
1358 	for (i = 1; i < ofs->numlayer; i++) {
1359 		err = ovl_check_layer(sb, ofs,
1360 				      ofs->layers[i].mnt->mnt_root,
1361 				      "lowerdir", true);
1362 		if (err)
1363 			return err;
1364 	}
1365 
1366 	return 0;
1367 }
1368 
1369 static struct dentry *ovl_get_root(struct super_block *sb,
1370 				   struct dentry *upperdentry,
1371 				   struct ovl_entry *oe)
1372 {
1373 	struct dentry *root;
1374 	struct ovl_fs *ofs = OVL_FS(sb);
1375 	struct ovl_path *lowerpath = ovl_lowerstack(oe);
1376 	unsigned long ino = d_inode(lowerpath->dentry)->i_ino;
1377 	int fsid = lowerpath->layer->fsid;
1378 	struct ovl_inode_params oip = {
1379 		.upperdentry = upperdentry,
1380 		.oe = oe,
1381 	};
1382 
1383 	root = d_make_root(ovl_new_inode(sb, S_IFDIR, 0));
1384 	if (!root)
1385 		return NULL;
1386 
1387 	if (upperdentry) {
1388 		/* Root inode uses upper st_ino/i_ino */
1389 		ino = d_inode(upperdentry)->i_ino;
1390 		fsid = 0;
1391 		ovl_dentry_set_upper_alias(root);
1392 		if (ovl_is_impuredir(sb, upperdentry))
1393 			ovl_set_flag(OVL_IMPURE, d_inode(root));
1394 	}
1395 
1396 	/* Look for xwhiteouts marker except in the lowermost layer */
1397 	for (int i = 0; i < ovl_numlower(oe) - 1; i++, lowerpath++) {
1398 		struct path path = {
1399 			.mnt = lowerpath->layer->mnt,
1400 			.dentry = lowerpath->dentry,
1401 		};
1402 
1403 		/* overlay.opaque=x means xwhiteouts directory */
1404 		if (ovl_get_opaquedir_val(ofs, &path) == 'x') {
1405 			ovl_layer_set_xwhiteouts(ofs, lowerpath->layer);
1406 			ovl_dentry_set_xwhiteouts(root);
1407 		}
1408 	}
1409 
1410 	/* Root is always merge -> can have whiteouts */
1411 	ovl_set_flag(OVL_WHITEOUTS, d_inode(root));
1412 	ovl_dentry_set_flag(OVL_E_CONNECTED, root);
1413 	ovl_set_upperdata(d_inode(root));
1414 	ovl_inode_init(d_inode(root), &oip, ino, fsid);
1415 	ovl_dentry_init_flags(root, upperdentry, oe, DCACHE_OP_WEAK_REVALIDATE);
1416 	/* root keeps a reference of upperdentry */
1417 	dget(upperdentry);
1418 
1419 	return root;
1420 }
1421 
1422 static void ovl_set_d_op(struct super_block *sb)
1423 {
1424 #if IS_ENABLED(CONFIG_UNICODE)
1425 	struct ovl_fs *ofs = sb->s_fs_info;
1426 
1427 	if (ofs->casefold) {
1428 		set_default_d_op(sb, &ovl_dentry_ci_operations);
1429 		return;
1430 	}
1431 #endif
1432 	set_default_d_op(sb, &ovl_dentry_operations);
1433 }
1434 
1435 static int ovl_fill_super_creds(struct fs_context *fc, struct super_block *sb)
1436 {
1437 	struct ovl_fs *ofs = sb->s_fs_info;
1438 	struct cred *creator_cred = (struct cred *)ofs->creator_cred;
1439 	struct ovl_fs_context *ctx = fc->fs_private;
1440 	struct ovl_layer *layers;
1441 	struct ovl_entry *oe = NULL;
1442 	int err;
1443 
1444 	err = ovl_fs_params_verify(ctx, &ofs->config);
1445 	if (err)
1446 		return err;
1447 
1448 	err = -EINVAL;
1449 	if (ctx->nr == 0) {
1450 		if (!(fc->sb_flags & SB_SILENT))
1451 			pr_err("missing 'lowerdir'\n");
1452 		return err;
1453 	}
1454 
1455 	err = -ENOMEM;
1456 	layers = kzalloc_objs(struct ovl_layer, ctx->nr + 1);
1457 	if (!layers)
1458 		return err;
1459 
1460 	ofs->config.lowerdirs = kcalloc(ctx->nr + 1, sizeof(char *), GFP_KERNEL);
1461 	if (!ofs->config.lowerdirs) {
1462 		kfree(layers);
1463 		return err;
1464 	}
1465 	ofs->layers = layers;
1466 	/*
1467 	 * Layer 0 is reserved for upper even if there's no upper.
1468 	 * config.lowerdirs[0] is used for storing the user provided colon
1469 	 * separated lowerdir string.
1470 	 */
1471 	ofs->config.lowerdirs[0] = ctx->lowerdir_all;
1472 	ctx->lowerdir_all = NULL;
1473 	ofs->numlayer = 1;
1474 
1475 	sb->s_stack_depth = 0;
1476 	sb->s_maxbytes = MAX_LFS_FILESIZE;
1477 	atomic_long_set(&ofs->last_ino, 1);
1478 	/* Assume underlying fs uses 32bit inodes unless proven otherwise */
1479 	if (ofs->config.xino != OVL_XINO_OFF) {
1480 		ofs->xino_mode = BITS_PER_LONG - 32;
1481 		if (!ofs->xino_mode) {
1482 			pr_warn("xino not supported on 32bit kernel, falling back to xino=off.\n");
1483 			ofs->config.xino = OVL_XINO_OFF;
1484 		}
1485 	}
1486 
1487 	/* alloc/destroy_inode needed for setting up traps in inode cache */
1488 	sb->s_op = &ovl_super_operations;
1489 
1490 	if (ofs->config.upperdir) {
1491 		struct super_block *upper_sb;
1492 
1493 		err = -EINVAL;
1494 		if (!ofs->config.workdir) {
1495 			pr_err("missing 'workdir'\n");
1496 			return err;
1497 		}
1498 
1499 		err = ovl_get_upper(sb, ofs, &layers[0], &ctx->upper);
1500 		if (err)
1501 			return err;
1502 
1503 		upper_sb = ovl_upper_mnt(ofs)->mnt_sb;
1504 		if (!ovl_should_sync(ofs)) {
1505 			ofs->errseq = errseq_sample(&upper_sb->s_wb_err);
1506 			if (errseq_check(&upper_sb->s_wb_err, ofs->errseq)) {
1507 				err = -EIO;
1508 				pr_err("Cannot mount volatile when upperdir has an unseen error. Sync upperdir fs to clear state.\n");
1509 				return err;
1510 			}
1511 		}
1512 
1513 		err = ovl_get_workdir(sb, ofs, &ctx->upper, &ctx->work,
1514 				      ctx->nr_data);
1515 		if (err)
1516 			return err;
1517 
1518 		if (!ofs->workdir)
1519 			sb->s_flags |= SB_RDONLY;
1520 
1521 		sb->s_stack_depth = upper_sb->s_stack_depth;
1522 		sb->s_time_gran = upper_sb->s_time_gran;
1523 	}
1524 	oe = ovl_get_lowerstack(sb, ctx, ofs, layers);
1525 	err = PTR_ERR(oe);
1526 	if (IS_ERR(oe))
1527 		return err;
1528 
1529 	/* If the upper fs is nonexistent, we mark overlayfs r/o too */
1530 	if (!ovl_upper_mnt(ofs))
1531 		sb->s_flags |= SB_RDONLY;
1532 
1533 	if (ovl_has_fsid(ofs) && ovl_upper_mnt(ofs)) {
1534 		/* Use per instance persistent uuid/fsid */
1535 		ovl_init_uuid_xattr(sb, ofs, &ctx->upper);
1536 	}
1537 
1538 	if (!ovl_force_readonly(ofs) && ofs->config.index) {
1539 		err = ovl_get_indexdir(sb, ofs, oe, &ctx->upper);
1540 		if (err)
1541 			goto out_free_oe;
1542 
1543 		/* Force r/o mount with no index dir */
1544 		if (!ofs->workdir)
1545 			sb->s_flags |= SB_RDONLY;
1546 	}
1547 
1548 	err = ovl_check_overlapping_layers(sb, ofs);
1549 	if (err)
1550 		goto out_free_oe;
1551 
1552 	/* Show index=off in /proc/mounts for forced r/o mount */
1553 	if (!ofs->workdir) {
1554 		ofs->config.index = false;
1555 		if (ovl_upper_mnt(ofs) && ofs->config.nfs_export) {
1556 			pr_warn("NFS export requires an index dir, falling back to nfs_export=off.\n");
1557 			ofs->config.nfs_export = false;
1558 		}
1559 	}
1560 
1561 	if (ofs->config.metacopy && ofs->config.nfs_export) {
1562 		pr_warn("NFS export is not supported with metadata only copy up, falling back to nfs_export=off.\n");
1563 		ofs->config.nfs_export = false;
1564 	}
1565 
1566 	/*
1567 	 * Support encoding decodable file handles with nfs_export=on
1568 	 * and encoding non-decodable file handles with nfs_export=off
1569 	 * if all layers support file handles.
1570 	 */
1571 	if (ofs->config.nfs_export)
1572 		sb->s_export_op = &ovl_export_operations;
1573 	else if (!ofs->nofh)
1574 		sb->s_export_op = &ovl_export_fid_operations;
1575 
1576 	/* Never override disk quota limits or use reserved space */
1577 	cap_lower(creator_cred->cap_effective, CAP_SYS_RESOURCE);
1578 
1579 	sb->s_magic = OVERLAYFS_SUPER_MAGIC;
1580 	sb->s_xattr = ovl_xattr_handlers(ofs);
1581 	sb->s_fs_info = ofs;
1582 #ifdef CONFIG_FS_POSIX_ACL
1583 	sb->s_flags |= SB_POSIXACL;
1584 #endif
1585 	sb->s_iflags |= SB_I_SKIP_SYNC;
1586 	/*
1587 	 * Ensure that umask handling is done by the filesystems used
1588 	 * for the the upper layer instead of overlayfs as that would
1589 	 * lead to unexpected results.
1590 	 */
1591 	sb->s_iflags |= SB_I_NOUMASK;
1592 	sb->s_iflags |= SB_I_EVM_HMAC_UNSUPPORTED;
1593 
1594 	err = -ENOMEM;
1595 	sb->s_root = ovl_get_root(sb, ctx->upper.dentry, oe);
1596 	if (!sb->s_root)
1597 		goto out_free_oe;
1598 
1599 	/*
1600 	 * The casefold flag of an empty layer root may have changed since the
1601 	 * mount options were parsed.  The root inode owns oe by now.
1602 	 */
1603 	if (!!IS_CASEFOLDED(d_inode(sb->s_root)) != ofs->casefold) {
1604 		pr_err("casefold flag of the root directory has changed\n");
1605 		dput(sb->s_root);
1606 		sb->s_root = NULL;
1607 		return -EINVAL;
1608 	}
1609 
1610 	return 0;
1611 
1612 out_free_oe:
1613 	ovl_free_entry(oe);
1614 	return err;
1615 }
1616 
1617 int ovl_fill_super(struct super_block *sb, struct fs_context *fc)
1618 {
1619 	struct ovl_fs *ofs = sb->s_fs_info;
1620 	int err;
1621 
1622 	err = -EINVAL;
1623 	/* The fscontext fd may have been passed to another user namespace. */
1624 	if (fc->user_ns != current_user_ns())
1625 		goto out_err;
1626 
1627 	ovl_set_d_op(sb);
1628 
1629 	if (!ofs->creator_cred) {
1630 		err = -ENOMEM;
1631 		ofs->creator_cred = prepare_creds();
1632 		if (!ofs->creator_cred)
1633 			goto out_err;
1634 	}
1635 
1636 	with_ovl_creds(sb)
1637 		err = ovl_fill_super_creds(fc, sb);
1638 
1639 out_err:
1640 	if (err) {
1641 		ovl_free_fs(ofs);
1642 		sb->s_fs_info = NULL;
1643 	}
1644 
1645 	return err;
1646 }
1647 
1648 static void ovl_kill_sb(struct super_block *sb)
1649 {
1650 	struct ovl_fs *ofs = OVL_FS(sb);
1651 
1652 	/* Nothing can modify them now, do not hold them across the sync */
1653 	if (ofs)
1654 		ovl_inuse_unlock_all(ofs);
1655 	kill_anon_super(sb);
1656 }
1657 
1658 struct file_system_type ovl_fs_type = {
1659 	.owner			= THIS_MODULE,
1660 	.name			= "overlay",
1661 	.init_fs_context	= ovl_init_fs_context,
1662 	.parameters		= ovl_parameter_spec,
1663 	.fs_flags		= FS_USERNS_MOUNT | FS_ALLOW_IDMAP,
1664 	.kill_sb		= ovl_kill_sb,
1665 };
1666 MODULE_ALIAS_FS("overlay");
1667 
1668 static void ovl_inode_init_once(void *foo)
1669 {
1670 	struct ovl_inode *oi = foo;
1671 
1672 	inode_init_once(&oi->vfs_inode);
1673 }
1674 
1675 static int __init ovl_init(void)
1676 {
1677 	int err;
1678 
1679 	ovl_inode_cachep = kmem_cache_create("ovl_inode",
1680 					     sizeof(struct ovl_inode), 0,
1681 					     (SLAB_RECLAIM_ACCOUNT|
1682 					      SLAB_ACCOUNT),
1683 					     ovl_inode_init_once);
1684 	if (ovl_inode_cachep == NULL)
1685 		return -ENOMEM;
1686 
1687 	err = register_filesystem(&ovl_fs_type);
1688 	if (!err)
1689 		return 0;
1690 
1691 	kmem_cache_destroy(ovl_inode_cachep);
1692 
1693 	return err;
1694 }
1695 
1696 static void __exit ovl_exit(void)
1697 {
1698 	unregister_filesystem(&ovl_fs_type);
1699 
1700 	/*
1701 	 * Make sure all delayed rcu free inodes are flushed before we
1702 	 * destroy cache.
1703 	 */
1704 	rcu_barrier();
1705 	kmem_cache_destroy(ovl_inode_cachep);
1706 }
1707 
1708 module_init(ovl_init);
1709 module_exit(ovl_exit);
1710