xref: /linux/fs/namespace.c (revision 804382d59b81b331735d37a18149ea0d36d5936a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/fs/namespace.c
4  *
5  * (C) Copyright Al Viro 2000, 2001
6  *
7  * Based on code from fs/super.c, copyright Linus Torvalds and others.
8  * Heavily rewritten.
9  */
10 
11 #include <linux/syscalls.h>
12 #include <linux/export.h>
13 #include <linux/capability.h>
14 #include <linux/mnt_namespace.h>
15 #include <linux/user_namespace.h>
16 #include <linux/namei.h>
17 #include <linux/security.h>
18 #include <linux/cred.h>
19 #include <linux/idr.h>
20 #include <linux/init.h>		/* init_rootfs */
21 #include <linux/fs_struct.h>	/* get_fs_root et.al. */
22 #include <linux/fsnotify.h>	/* fsnotify_vfsmount_delete */
23 #include <linux/file.h>
24 #include <linux/uaccess.h>
25 #include <linux/proc_ns.h>
26 #include <linux/magic.h>
27 #include <linux/memblock.h>
28 #include <linux/proc_fs.h>
29 #include <linux/task_work.h>
30 #include <linux/sched/task.h>
31 #include <uapi/linux/mount.h>
32 #include <linux/fs_context.h>
33 #include <linux/shmem_fs.h>
34 #include <linux/mnt_idmapping.h>
35 #include <linux/pidfs.h>
36 
37 #include "pnode.h"
38 #include "internal.h"
39 
40 /* Maximum number of mounts in a mount namespace */
41 static unsigned int sysctl_mount_max __read_mostly = 100000;
42 
43 static unsigned int m_hash_mask __ro_after_init;
44 static unsigned int m_hash_shift __ro_after_init;
45 static unsigned int mp_hash_mask __ro_after_init;
46 static unsigned int mp_hash_shift __ro_after_init;
47 
48 static __initdata unsigned long mhash_entries;
49 static int __init set_mhash_entries(char *str)
50 {
51 	if (!str)
52 		return 0;
53 	mhash_entries = simple_strtoul(str, &str, 0);
54 	return 1;
55 }
56 __setup("mhash_entries=", set_mhash_entries);
57 
58 static __initdata unsigned long mphash_entries;
59 static int __init set_mphash_entries(char *str)
60 {
61 	if (!str)
62 		return 0;
63 	mphash_entries = simple_strtoul(str, &str, 0);
64 	return 1;
65 }
66 __setup("mphash_entries=", set_mphash_entries);
67 
68 static u64 event;
69 static DEFINE_XARRAY_FLAGS(mnt_id_xa, XA_FLAGS_ALLOC);
70 static DEFINE_IDA(mnt_group_ida);
71 
72 /* Don't allow confusion with old 32bit mount ID */
73 #define MNT_UNIQUE_ID_OFFSET (1ULL << 31)
74 static u64 mnt_id_ctr = MNT_UNIQUE_ID_OFFSET;
75 
76 static struct hlist_head *mount_hashtable __ro_after_init;
77 static struct hlist_head *mountpoint_hashtable __ro_after_init;
78 static struct kmem_cache *mnt_cache __ro_after_init;
79 static DECLARE_RWSEM(namespace_sem);
80 static HLIST_HEAD(unmounted);	/* protected by namespace_sem */
81 static LIST_HEAD(ex_mountpoints); /* protected by namespace_sem */
82 static DEFINE_SEQLOCK(mnt_ns_tree_lock);
83 
84 #ifdef CONFIG_FSNOTIFY
85 LIST_HEAD(notify_list); /* protected by namespace_sem */
86 #endif
87 static struct rb_root mnt_ns_tree = RB_ROOT; /* protected by mnt_ns_tree_lock */
88 static LIST_HEAD(mnt_ns_list); /* protected by mnt_ns_tree_lock */
89 
90 enum mount_kattr_flags_t {
91 	MOUNT_KATTR_RECURSE		= (1 << 0),
92 	MOUNT_KATTR_IDMAP_REPLACE	= (1 << 1),
93 };
94 
95 struct mount_kattr {
96 	unsigned int attr_set;
97 	unsigned int attr_clr;
98 	unsigned int propagation;
99 	unsigned int lookup_flags;
100 	enum mount_kattr_flags_t kflags;
101 	struct user_namespace *mnt_userns;
102 	struct mnt_idmap *mnt_idmap;
103 };
104 
105 /* /sys/fs */
106 struct kobject *fs_kobj __ro_after_init;
107 EXPORT_SYMBOL_GPL(fs_kobj);
108 
109 /*
110  * vfsmount lock may be taken for read to prevent changes to the
111  * vfsmount hash, ie. during mountpoint lookups or walking back
112  * up the tree.
113  *
114  * It should be taken for write in all cases where the vfsmount
115  * tree or hash is modified or when a vfsmount structure is modified.
116  */
117 __cacheline_aligned_in_smp DEFINE_SEQLOCK(mount_lock);
118 
119 static inline struct mnt_namespace *node_to_mnt_ns(const struct rb_node *node)
120 {
121 	if (!node)
122 		return NULL;
123 	return rb_entry(node, struct mnt_namespace, mnt_ns_tree_node);
124 }
125 
126 static int mnt_ns_cmp(struct rb_node *a, const struct rb_node *b)
127 {
128 	struct mnt_namespace *ns_a = node_to_mnt_ns(a);
129 	struct mnt_namespace *ns_b = node_to_mnt_ns(b);
130 	u64 seq_a = ns_a->seq;
131 	u64 seq_b = ns_b->seq;
132 
133 	if (seq_a < seq_b)
134 		return -1;
135 	if (seq_a > seq_b)
136 		return 1;
137 	return 0;
138 }
139 
140 static inline void mnt_ns_tree_write_lock(void)
141 {
142 	write_seqlock(&mnt_ns_tree_lock);
143 }
144 
145 static inline void mnt_ns_tree_write_unlock(void)
146 {
147 	write_sequnlock(&mnt_ns_tree_lock);
148 }
149 
150 static void mnt_ns_tree_add(struct mnt_namespace *ns)
151 {
152 	struct rb_node *node, *prev;
153 
154 	mnt_ns_tree_write_lock();
155 	node = rb_find_add_rcu(&ns->mnt_ns_tree_node, &mnt_ns_tree, mnt_ns_cmp);
156 	/*
157 	 * If there's no previous entry simply add it after the
158 	 * head and if there is add it after the previous entry.
159 	 */
160 	prev = rb_prev(&ns->mnt_ns_tree_node);
161 	if (!prev)
162 		list_add_rcu(&ns->mnt_ns_list, &mnt_ns_list);
163 	else
164 		list_add_rcu(&ns->mnt_ns_list, &node_to_mnt_ns(prev)->mnt_ns_list);
165 	mnt_ns_tree_write_unlock();
166 
167 	WARN_ON_ONCE(node);
168 }
169 
170 static void mnt_ns_release(struct mnt_namespace *ns)
171 {
172 	/* keep alive for {list,stat}mount() */
173 	if (refcount_dec_and_test(&ns->passive)) {
174 		fsnotify_mntns_delete(ns);
175 		put_user_ns(ns->user_ns);
176 		kfree(ns);
177 	}
178 }
179 DEFINE_FREE(mnt_ns_release, struct mnt_namespace *, if (_T) mnt_ns_release(_T))
180 
181 static void mnt_ns_release_rcu(struct rcu_head *rcu)
182 {
183 	mnt_ns_release(container_of(rcu, struct mnt_namespace, mnt_ns_rcu));
184 }
185 
186 static void mnt_ns_tree_remove(struct mnt_namespace *ns)
187 {
188 	/* remove from global mount namespace list */
189 	if (!is_anon_ns(ns)) {
190 		mnt_ns_tree_write_lock();
191 		rb_erase(&ns->mnt_ns_tree_node, &mnt_ns_tree);
192 		list_bidir_del_rcu(&ns->mnt_ns_list);
193 		mnt_ns_tree_write_unlock();
194 	}
195 
196 	call_rcu(&ns->mnt_ns_rcu, mnt_ns_release_rcu);
197 }
198 
199 static int mnt_ns_find(const void *key, const struct rb_node *node)
200 {
201 	const u64 mnt_ns_id = *(u64 *)key;
202 	const struct mnt_namespace *ns = node_to_mnt_ns(node);
203 
204 	if (mnt_ns_id < ns->seq)
205 		return -1;
206 	if (mnt_ns_id > ns->seq)
207 		return 1;
208 	return 0;
209 }
210 
211 /*
212  * Lookup a mount namespace by id and take a passive reference count. Taking a
213  * passive reference means the mount namespace can be emptied if e.g., the last
214  * task holding an active reference exits. To access the mounts of the
215  * namespace the @namespace_sem must first be acquired. If the namespace has
216  * already shut down before acquiring @namespace_sem, {list,stat}mount() will
217  * see that the mount rbtree of the namespace is empty.
218  *
219  * Note the lookup is lockless protected by a sequence counter. We only
220  * need to guard against false negatives as false positives aren't
221  * possible. So if we didn't find a mount namespace and the sequence
222  * counter has changed we need to retry. If the sequence counter is
223  * still the same we know the search actually failed.
224  */
225 static struct mnt_namespace *lookup_mnt_ns(u64 mnt_ns_id)
226 {
227 	struct mnt_namespace *ns;
228 	struct rb_node *node;
229 	unsigned int seq;
230 
231 	guard(rcu)();
232 	do {
233 		seq = read_seqbegin(&mnt_ns_tree_lock);
234 		node = rb_find_rcu(&mnt_ns_id, &mnt_ns_tree, mnt_ns_find);
235 		if (node)
236 			break;
237 	} while (read_seqretry(&mnt_ns_tree_lock, seq));
238 
239 	if (!node)
240 		return NULL;
241 
242 	/*
243 	 * The last reference count is put with RCU delay so we can
244 	 * unconditonally acquire a reference here.
245 	 */
246 	ns = node_to_mnt_ns(node);
247 	refcount_inc(&ns->passive);
248 	return ns;
249 }
250 
251 static inline void lock_mount_hash(void)
252 {
253 	write_seqlock(&mount_lock);
254 }
255 
256 static inline void unlock_mount_hash(void)
257 {
258 	write_sequnlock(&mount_lock);
259 }
260 
261 static inline struct hlist_head *m_hash(struct vfsmount *mnt, struct dentry *dentry)
262 {
263 	unsigned long tmp = ((unsigned long)mnt / L1_CACHE_BYTES);
264 	tmp += ((unsigned long)dentry / L1_CACHE_BYTES);
265 	tmp = tmp + (tmp >> m_hash_shift);
266 	return &mount_hashtable[tmp & m_hash_mask];
267 }
268 
269 static inline struct hlist_head *mp_hash(struct dentry *dentry)
270 {
271 	unsigned long tmp = ((unsigned long)dentry / L1_CACHE_BYTES);
272 	tmp = tmp + (tmp >> mp_hash_shift);
273 	return &mountpoint_hashtable[tmp & mp_hash_mask];
274 }
275 
276 static int mnt_alloc_id(struct mount *mnt)
277 {
278 	int res;
279 
280 	xa_lock(&mnt_id_xa);
281 	res = __xa_alloc(&mnt_id_xa, &mnt->mnt_id, mnt, XA_LIMIT(1, INT_MAX), GFP_KERNEL);
282 	if (!res)
283 		mnt->mnt_id_unique = ++mnt_id_ctr;
284 	xa_unlock(&mnt_id_xa);
285 	return res;
286 }
287 
288 static void mnt_free_id(struct mount *mnt)
289 {
290 	xa_erase(&mnt_id_xa, mnt->mnt_id);
291 }
292 
293 /*
294  * Allocate a new peer group ID
295  */
296 static int mnt_alloc_group_id(struct mount *mnt)
297 {
298 	int res = ida_alloc_min(&mnt_group_ida, 1, GFP_KERNEL);
299 
300 	if (res < 0)
301 		return res;
302 	mnt->mnt_group_id = res;
303 	return 0;
304 }
305 
306 /*
307  * Release a peer group ID
308  */
309 void mnt_release_group_id(struct mount *mnt)
310 {
311 	ida_free(&mnt_group_ida, mnt->mnt_group_id);
312 	mnt->mnt_group_id = 0;
313 }
314 
315 /*
316  * vfsmount lock must be held for read
317  */
318 static inline void mnt_add_count(struct mount *mnt, int n)
319 {
320 #ifdef CONFIG_SMP
321 	this_cpu_add(mnt->mnt_pcp->mnt_count, n);
322 #else
323 	preempt_disable();
324 	mnt->mnt_count += n;
325 	preempt_enable();
326 #endif
327 }
328 
329 /*
330  * vfsmount lock must be held for write
331  */
332 int mnt_get_count(struct mount *mnt)
333 {
334 #ifdef CONFIG_SMP
335 	int count = 0;
336 	int cpu;
337 
338 	for_each_possible_cpu(cpu) {
339 		count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_count;
340 	}
341 
342 	return count;
343 #else
344 	return mnt->mnt_count;
345 #endif
346 }
347 
348 static struct mount *alloc_vfsmnt(const char *name)
349 {
350 	struct mount *mnt = kmem_cache_zalloc(mnt_cache, GFP_KERNEL);
351 	if (mnt) {
352 		int err;
353 
354 		err = mnt_alloc_id(mnt);
355 		if (err)
356 			goto out_free_cache;
357 
358 		if (name) {
359 			mnt->mnt_devname = kstrdup_const(name,
360 							 GFP_KERNEL_ACCOUNT);
361 			if (!mnt->mnt_devname)
362 				goto out_free_id;
363 		}
364 
365 #ifdef CONFIG_SMP
366 		mnt->mnt_pcp = alloc_percpu(struct mnt_pcp);
367 		if (!mnt->mnt_pcp)
368 			goto out_free_devname;
369 
370 		this_cpu_add(mnt->mnt_pcp->mnt_count, 1);
371 #else
372 		mnt->mnt_count = 1;
373 		mnt->mnt_writers = 0;
374 #endif
375 
376 		INIT_HLIST_NODE(&mnt->mnt_hash);
377 		INIT_LIST_HEAD(&mnt->mnt_child);
378 		INIT_LIST_HEAD(&mnt->mnt_mounts);
379 		INIT_LIST_HEAD(&mnt->mnt_list);
380 		INIT_LIST_HEAD(&mnt->mnt_expire);
381 		INIT_LIST_HEAD(&mnt->mnt_share);
382 		INIT_LIST_HEAD(&mnt->mnt_slave_list);
383 		INIT_LIST_HEAD(&mnt->mnt_slave);
384 		INIT_HLIST_NODE(&mnt->mnt_mp_list);
385 		INIT_LIST_HEAD(&mnt->mnt_umounting);
386 		INIT_HLIST_HEAD(&mnt->mnt_stuck_children);
387 		RB_CLEAR_NODE(&mnt->mnt_node);
388 		mnt->mnt.mnt_idmap = &nop_mnt_idmap;
389 	}
390 	return mnt;
391 
392 #ifdef CONFIG_SMP
393 out_free_devname:
394 	kfree_const(mnt->mnt_devname);
395 #endif
396 out_free_id:
397 	mnt_free_id(mnt);
398 out_free_cache:
399 	kmem_cache_free(mnt_cache, mnt);
400 	return NULL;
401 }
402 
403 /*
404  * Most r/o checks on a fs are for operations that take
405  * discrete amounts of time, like a write() or unlink().
406  * We must keep track of when those operations start
407  * (for permission checks) and when they end, so that
408  * we can determine when writes are able to occur to
409  * a filesystem.
410  */
411 /*
412  * __mnt_is_readonly: check whether a mount is read-only
413  * @mnt: the mount to check for its write status
414  *
415  * This shouldn't be used directly ouside of the VFS.
416  * It does not guarantee that the filesystem will stay
417  * r/w, just that it is right *now*.  This can not and
418  * should not be used in place of IS_RDONLY(inode).
419  * mnt_want/drop_write() will _keep_ the filesystem
420  * r/w.
421  */
422 bool __mnt_is_readonly(struct vfsmount *mnt)
423 {
424 	return (mnt->mnt_flags & MNT_READONLY) || sb_rdonly(mnt->mnt_sb);
425 }
426 EXPORT_SYMBOL_GPL(__mnt_is_readonly);
427 
428 static inline void mnt_inc_writers(struct mount *mnt)
429 {
430 #ifdef CONFIG_SMP
431 	this_cpu_inc(mnt->mnt_pcp->mnt_writers);
432 #else
433 	mnt->mnt_writers++;
434 #endif
435 }
436 
437 static inline void mnt_dec_writers(struct mount *mnt)
438 {
439 #ifdef CONFIG_SMP
440 	this_cpu_dec(mnt->mnt_pcp->mnt_writers);
441 #else
442 	mnt->mnt_writers--;
443 #endif
444 }
445 
446 static unsigned int mnt_get_writers(struct mount *mnt)
447 {
448 #ifdef CONFIG_SMP
449 	unsigned int count = 0;
450 	int cpu;
451 
452 	for_each_possible_cpu(cpu) {
453 		count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_writers;
454 	}
455 
456 	return count;
457 #else
458 	return mnt->mnt_writers;
459 #endif
460 }
461 
462 static int mnt_is_readonly(struct vfsmount *mnt)
463 {
464 	if (READ_ONCE(mnt->mnt_sb->s_readonly_remount))
465 		return 1;
466 	/*
467 	 * The barrier pairs with the barrier in sb_start_ro_state_change()
468 	 * making sure if we don't see s_readonly_remount set yet, we also will
469 	 * not see any superblock / mount flag changes done by remount.
470 	 * It also pairs with the barrier in sb_end_ro_state_change()
471 	 * assuring that if we see s_readonly_remount already cleared, we will
472 	 * see the values of superblock / mount flags updated by remount.
473 	 */
474 	smp_rmb();
475 	return __mnt_is_readonly(mnt);
476 }
477 
478 /*
479  * Most r/o & frozen checks on a fs are for operations that take discrete
480  * amounts of time, like a write() or unlink().  We must keep track of when
481  * those operations start (for permission checks) and when they end, so that we
482  * can determine when writes are able to occur to a filesystem.
483  */
484 /**
485  * mnt_get_write_access - get write access to a mount without freeze protection
486  * @m: the mount on which to take a write
487  *
488  * This tells the low-level filesystem that a write is about to be performed to
489  * it, and makes sure that writes are allowed (mnt it read-write) before
490  * returning success. This operation does not protect against filesystem being
491  * frozen. When the write operation is finished, mnt_put_write_access() must be
492  * called. This is effectively a refcount.
493  */
494 int mnt_get_write_access(struct vfsmount *m)
495 {
496 	struct mount *mnt = real_mount(m);
497 	int ret = 0;
498 
499 	preempt_disable();
500 	mnt_inc_writers(mnt);
501 	/*
502 	 * The store to mnt_inc_writers must be visible before we pass
503 	 * MNT_WRITE_HOLD loop below, so that the slowpath can see our
504 	 * incremented count after it has set MNT_WRITE_HOLD.
505 	 */
506 	smp_mb();
507 	might_lock(&mount_lock.lock);
508 	while (READ_ONCE(mnt->mnt.mnt_flags) & MNT_WRITE_HOLD) {
509 		if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
510 			cpu_relax();
511 		} else {
512 			/*
513 			 * This prevents priority inversion, if the task
514 			 * setting MNT_WRITE_HOLD got preempted on a remote
515 			 * CPU, and it prevents life lock if the task setting
516 			 * MNT_WRITE_HOLD has a lower priority and is bound to
517 			 * the same CPU as the task that is spinning here.
518 			 */
519 			preempt_enable();
520 			lock_mount_hash();
521 			unlock_mount_hash();
522 			preempt_disable();
523 		}
524 	}
525 	/*
526 	 * The barrier pairs with the barrier sb_start_ro_state_change() making
527 	 * sure that if we see MNT_WRITE_HOLD cleared, we will also see
528 	 * s_readonly_remount set (or even SB_RDONLY / MNT_READONLY flags) in
529 	 * mnt_is_readonly() and bail in case we are racing with remount
530 	 * read-only.
531 	 */
532 	smp_rmb();
533 	if (mnt_is_readonly(m)) {
534 		mnt_dec_writers(mnt);
535 		ret = -EROFS;
536 	}
537 	preempt_enable();
538 
539 	return ret;
540 }
541 EXPORT_SYMBOL_GPL(mnt_get_write_access);
542 
543 /**
544  * mnt_want_write - get write access to a mount
545  * @m: the mount on which to take a write
546  *
547  * This tells the low-level filesystem that a write is about to be performed to
548  * it, and makes sure that writes are allowed (mount is read-write, filesystem
549  * is not frozen) before returning success.  When the write operation is
550  * finished, mnt_drop_write() must be called.  This is effectively a refcount.
551  */
552 int mnt_want_write(struct vfsmount *m)
553 {
554 	int ret;
555 
556 	sb_start_write(m->mnt_sb);
557 	ret = mnt_get_write_access(m);
558 	if (ret)
559 		sb_end_write(m->mnt_sb);
560 	return ret;
561 }
562 EXPORT_SYMBOL_GPL(mnt_want_write);
563 
564 /**
565  * mnt_get_write_access_file - get write access to a file's mount
566  * @file: the file who's mount on which to take a write
567  *
568  * This is like mnt_get_write_access, but if @file is already open for write it
569  * skips incrementing mnt_writers (since the open file already has a reference)
570  * and instead only does the check for emergency r/o remounts.  This must be
571  * paired with mnt_put_write_access_file.
572  */
573 int mnt_get_write_access_file(struct file *file)
574 {
575 	if (file->f_mode & FMODE_WRITER) {
576 		/*
577 		 * Superblock may have become readonly while there are still
578 		 * writable fd's, e.g. due to a fs error with errors=remount-ro
579 		 */
580 		if (__mnt_is_readonly(file->f_path.mnt))
581 			return -EROFS;
582 		return 0;
583 	}
584 	return mnt_get_write_access(file->f_path.mnt);
585 }
586 
587 /**
588  * mnt_want_write_file - get write access to a file's mount
589  * @file: the file who's mount on which to take a write
590  *
591  * This is like mnt_want_write, but if the file is already open for writing it
592  * skips incrementing mnt_writers (since the open file already has a reference)
593  * and instead only does the freeze protection and the check for emergency r/o
594  * remounts.  This must be paired with mnt_drop_write_file.
595  */
596 int mnt_want_write_file(struct file *file)
597 {
598 	int ret;
599 
600 	sb_start_write(file_inode(file)->i_sb);
601 	ret = mnt_get_write_access_file(file);
602 	if (ret)
603 		sb_end_write(file_inode(file)->i_sb);
604 	return ret;
605 }
606 EXPORT_SYMBOL_GPL(mnt_want_write_file);
607 
608 /**
609  * mnt_put_write_access - give up write access to a mount
610  * @mnt: the mount on which to give up write access
611  *
612  * Tells the low-level filesystem that we are done
613  * performing writes to it.  Must be matched with
614  * mnt_get_write_access() call above.
615  */
616 void mnt_put_write_access(struct vfsmount *mnt)
617 {
618 	preempt_disable();
619 	mnt_dec_writers(real_mount(mnt));
620 	preempt_enable();
621 }
622 EXPORT_SYMBOL_GPL(mnt_put_write_access);
623 
624 /**
625  * mnt_drop_write - give up write access to a mount
626  * @mnt: the mount on which to give up write access
627  *
628  * Tells the low-level filesystem that we are done performing writes to it and
629  * also allows filesystem to be frozen again.  Must be matched with
630  * mnt_want_write() call above.
631  */
632 void mnt_drop_write(struct vfsmount *mnt)
633 {
634 	mnt_put_write_access(mnt);
635 	sb_end_write(mnt->mnt_sb);
636 }
637 EXPORT_SYMBOL_GPL(mnt_drop_write);
638 
639 void mnt_put_write_access_file(struct file *file)
640 {
641 	if (!(file->f_mode & FMODE_WRITER))
642 		mnt_put_write_access(file->f_path.mnt);
643 }
644 
645 void mnt_drop_write_file(struct file *file)
646 {
647 	mnt_put_write_access_file(file);
648 	sb_end_write(file_inode(file)->i_sb);
649 }
650 EXPORT_SYMBOL(mnt_drop_write_file);
651 
652 /**
653  * mnt_hold_writers - prevent write access to the given mount
654  * @mnt: mnt to prevent write access to
655  *
656  * Prevents write access to @mnt if there are no active writers for @mnt.
657  * This function needs to be called and return successfully before changing
658  * properties of @mnt that need to remain stable for callers with write access
659  * to @mnt.
660  *
661  * After this functions has been called successfully callers must pair it with
662  * a call to mnt_unhold_writers() in order to stop preventing write access to
663  * @mnt.
664  *
665  * Context: This function expects lock_mount_hash() to be held serializing
666  *          setting MNT_WRITE_HOLD.
667  * Return: On success 0 is returned.
668  *	   On error, -EBUSY is returned.
669  */
670 static inline int mnt_hold_writers(struct mount *mnt)
671 {
672 	mnt->mnt.mnt_flags |= MNT_WRITE_HOLD;
673 	/*
674 	 * After storing MNT_WRITE_HOLD, we'll read the counters. This store
675 	 * should be visible before we do.
676 	 */
677 	smp_mb();
678 
679 	/*
680 	 * With writers on hold, if this value is zero, then there are
681 	 * definitely no active writers (although held writers may subsequently
682 	 * increment the count, they'll have to wait, and decrement it after
683 	 * seeing MNT_READONLY).
684 	 *
685 	 * It is OK to have counter incremented on one CPU and decremented on
686 	 * another: the sum will add up correctly. The danger would be when we
687 	 * sum up each counter, if we read a counter before it is incremented,
688 	 * but then read another CPU's count which it has been subsequently
689 	 * decremented from -- we would see more decrements than we should.
690 	 * MNT_WRITE_HOLD protects against this scenario, because
691 	 * mnt_want_write first increments count, then smp_mb, then spins on
692 	 * MNT_WRITE_HOLD, so it can't be decremented by another CPU while
693 	 * we're counting up here.
694 	 */
695 	if (mnt_get_writers(mnt) > 0)
696 		return -EBUSY;
697 
698 	return 0;
699 }
700 
701 /**
702  * mnt_unhold_writers - stop preventing write access to the given mount
703  * @mnt: mnt to stop preventing write access to
704  *
705  * Stop preventing write access to @mnt allowing callers to gain write access
706  * to @mnt again.
707  *
708  * This function can only be called after a successful call to
709  * mnt_hold_writers().
710  *
711  * Context: This function expects lock_mount_hash() to be held.
712  */
713 static inline void mnt_unhold_writers(struct mount *mnt)
714 {
715 	/*
716 	 * MNT_READONLY must become visible before ~MNT_WRITE_HOLD, so writers
717 	 * that become unheld will see MNT_READONLY.
718 	 */
719 	smp_wmb();
720 	mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD;
721 }
722 
723 static int mnt_make_readonly(struct mount *mnt)
724 {
725 	int ret;
726 
727 	ret = mnt_hold_writers(mnt);
728 	if (!ret)
729 		mnt->mnt.mnt_flags |= MNT_READONLY;
730 	mnt_unhold_writers(mnt);
731 	return ret;
732 }
733 
734 int sb_prepare_remount_readonly(struct super_block *sb)
735 {
736 	struct mount *mnt;
737 	int err = 0;
738 
739 	/* Racy optimization.  Recheck the counter under MNT_WRITE_HOLD */
740 	if (atomic_long_read(&sb->s_remove_count))
741 		return -EBUSY;
742 
743 	lock_mount_hash();
744 	list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) {
745 		if (!(mnt->mnt.mnt_flags & MNT_READONLY)) {
746 			err = mnt_hold_writers(mnt);
747 			if (err)
748 				break;
749 		}
750 	}
751 	if (!err && atomic_long_read(&sb->s_remove_count))
752 		err = -EBUSY;
753 
754 	if (!err)
755 		sb_start_ro_state_change(sb);
756 	list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) {
757 		if (mnt->mnt.mnt_flags & MNT_WRITE_HOLD)
758 			mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD;
759 	}
760 	unlock_mount_hash();
761 
762 	return err;
763 }
764 
765 static void free_vfsmnt(struct mount *mnt)
766 {
767 	mnt_idmap_put(mnt_idmap(&mnt->mnt));
768 	kfree_const(mnt->mnt_devname);
769 #ifdef CONFIG_SMP
770 	free_percpu(mnt->mnt_pcp);
771 #endif
772 	kmem_cache_free(mnt_cache, mnt);
773 }
774 
775 static void delayed_free_vfsmnt(struct rcu_head *head)
776 {
777 	free_vfsmnt(container_of(head, struct mount, mnt_rcu));
778 }
779 
780 /* call under rcu_read_lock */
781 int __legitimize_mnt(struct vfsmount *bastard, unsigned seq)
782 {
783 	struct mount *mnt;
784 	if (read_seqretry(&mount_lock, seq))
785 		return 1;
786 	if (bastard == NULL)
787 		return 0;
788 	mnt = real_mount(bastard);
789 	mnt_add_count(mnt, 1);
790 	smp_mb();			// see mntput_no_expire()
791 	if (likely(!read_seqretry(&mount_lock, seq)))
792 		return 0;
793 	if (bastard->mnt_flags & MNT_SYNC_UMOUNT) {
794 		mnt_add_count(mnt, -1);
795 		return 1;
796 	}
797 	lock_mount_hash();
798 	if (unlikely(bastard->mnt_flags & MNT_DOOMED)) {
799 		mnt_add_count(mnt, -1);
800 		unlock_mount_hash();
801 		return 1;
802 	}
803 	unlock_mount_hash();
804 	/* caller will mntput() */
805 	return -1;
806 }
807 
808 /* call under rcu_read_lock */
809 static bool legitimize_mnt(struct vfsmount *bastard, unsigned seq)
810 {
811 	int res = __legitimize_mnt(bastard, seq);
812 	if (likely(!res))
813 		return true;
814 	if (unlikely(res < 0)) {
815 		rcu_read_unlock();
816 		mntput(bastard);
817 		rcu_read_lock();
818 	}
819 	return false;
820 }
821 
822 /**
823  * __lookup_mnt - find first child mount
824  * @mnt:	parent mount
825  * @dentry:	mountpoint
826  *
827  * If @mnt has a child mount @c mounted @dentry find and return it.
828  *
829  * Note that the child mount @c need not be unique. There are cases
830  * where shadow mounts are created. For example, during mount
831  * propagation when a source mount @mnt whose root got overmounted by a
832  * mount @o after path lookup but before @namespace_sem could be
833  * acquired gets copied and propagated. So @mnt gets copied including
834  * @o. When @mnt is propagated to a destination mount @d that already
835  * has another mount @n mounted at the same mountpoint then the source
836  * mount @mnt will be tucked beneath @n, i.e., @n will be mounted on
837  * @mnt and @mnt mounted on @d. Now both @n and @o are mounted at @mnt
838  * on @dentry.
839  *
840  * Return: The first child of @mnt mounted @dentry or NULL.
841  */
842 struct mount *__lookup_mnt(struct vfsmount *mnt, struct dentry *dentry)
843 {
844 	struct hlist_head *head = m_hash(mnt, dentry);
845 	struct mount *p;
846 
847 	hlist_for_each_entry_rcu(p, head, mnt_hash)
848 		if (&p->mnt_parent->mnt == mnt && p->mnt_mountpoint == dentry)
849 			return p;
850 	return NULL;
851 }
852 
853 /*
854  * lookup_mnt - Return the first child mount mounted at path
855  *
856  * "First" means first mounted chronologically.  If you create the
857  * following mounts:
858  *
859  * mount /dev/sda1 /mnt
860  * mount /dev/sda2 /mnt
861  * mount /dev/sda3 /mnt
862  *
863  * Then lookup_mnt() on the base /mnt dentry in the root mount will
864  * return successively the root dentry and vfsmount of /dev/sda1, then
865  * /dev/sda2, then /dev/sda3, then NULL.
866  *
867  * lookup_mnt takes a reference to the found vfsmount.
868  */
869 struct vfsmount *lookup_mnt(const struct path *path)
870 {
871 	struct mount *child_mnt;
872 	struct vfsmount *m;
873 	unsigned seq;
874 
875 	rcu_read_lock();
876 	do {
877 		seq = read_seqbegin(&mount_lock);
878 		child_mnt = __lookup_mnt(path->mnt, path->dentry);
879 		m = child_mnt ? &child_mnt->mnt : NULL;
880 	} while (!legitimize_mnt(m, seq));
881 	rcu_read_unlock();
882 	return m;
883 }
884 
885 /*
886  * __is_local_mountpoint - Test to see if dentry is a mountpoint in the
887  *                         current mount namespace.
888  *
889  * The common case is dentries are not mountpoints at all and that
890  * test is handled inline.  For the slow case when we are actually
891  * dealing with a mountpoint of some kind, walk through all of the
892  * mounts in the current mount namespace and test to see if the dentry
893  * is a mountpoint.
894  *
895  * The mount_hashtable is not usable in the context because we
896  * need to identify all mounts that may be in the current mount
897  * namespace not just a mount that happens to have some specified
898  * parent mount.
899  */
900 bool __is_local_mountpoint(struct dentry *dentry)
901 {
902 	struct mnt_namespace *ns = current->nsproxy->mnt_ns;
903 	struct mount *mnt, *n;
904 	bool is_covered = false;
905 
906 	down_read(&namespace_sem);
907 	rbtree_postorder_for_each_entry_safe(mnt, n, &ns->mounts, mnt_node) {
908 		is_covered = (mnt->mnt_mountpoint == dentry);
909 		if (is_covered)
910 			break;
911 	}
912 	up_read(&namespace_sem);
913 
914 	return is_covered;
915 }
916 
917 static struct mountpoint *lookup_mountpoint(struct dentry *dentry)
918 {
919 	struct hlist_head *chain = mp_hash(dentry);
920 	struct mountpoint *mp;
921 
922 	hlist_for_each_entry(mp, chain, m_hash) {
923 		if (mp->m_dentry == dentry) {
924 			mp->m_count++;
925 			return mp;
926 		}
927 	}
928 	return NULL;
929 }
930 
931 static struct mountpoint *get_mountpoint(struct dentry *dentry)
932 {
933 	struct mountpoint *mp, *new = NULL;
934 	int ret;
935 
936 	if (d_mountpoint(dentry)) {
937 		/* might be worth a WARN_ON() */
938 		if (d_unlinked(dentry))
939 			return ERR_PTR(-ENOENT);
940 mountpoint:
941 		read_seqlock_excl(&mount_lock);
942 		mp = lookup_mountpoint(dentry);
943 		read_sequnlock_excl(&mount_lock);
944 		if (mp)
945 			goto done;
946 	}
947 
948 	if (!new)
949 		new = kmalloc(sizeof(struct mountpoint), GFP_KERNEL);
950 	if (!new)
951 		return ERR_PTR(-ENOMEM);
952 
953 
954 	/* Exactly one processes may set d_mounted */
955 	ret = d_set_mounted(dentry);
956 
957 	/* Someone else set d_mounted? */
958 	if (ret == -EBUSY)
959 		goto mountpoint;
960 
961 	/* The dentry is not available as a mountpoint? */
962 	mp = ERR_PTR(ret);
963 	if (ret)
964 		goto done;
965 
966 	/* Add the new mountpoint to the hash table */
967 	read_seqlock_excl(&mount_lock);
968 	new->m_dentry = dget(dentry);
969 	new->m_count = 1;
970 	hlist_add_head(&new->m_hash, mp_hash(dentry));
971 	INIT_HLIST_HEAD(&new->m_list);
972 	read_sequnlock_excl(&mount_lock);
973 
974 	mp = new;
975 	new = NULL;
976 done:
977 	kfree(new);
978 	return mp;
979 }
980 
981 /*
982  * vfsmount lock must be held.  Additionally, the caller is responsible
983  * for serializing calls for given disposal list.
984  */
985 static void __put_mountpoint(struct mountpoint *mp, struct list_head *list)
986 {
987 	if (!--mp->m_count) {
988 		struct dentry *dentry = mp->m_dentry;
989 		BUG_ON(!hlist_empty(&mp->m_list));
990 		spin_lock(&dentry->d_lock);
991 		dentry->d_flags &= ~DCACHE_MOUNTED;
992 		spin_unlock(&dentry->d_lock);
993 		dput_to_list(dentry, list);
994 		hlist_del(&mp->m_hash);
995 		kfree(mp);
996 	}
997 }
998 
999 /* called with namespace_lock and vfsmount lock */
1000 static void put_mountpoint(struct mountpoint *mp)
1001 {
1002 	__put_mountpoint(mp, &ex_mountpoints);
1003 }
1004 
1005 static inline int check_mnt(struct mount *mnt)
1006 {
1007 	return mnt->mnt_ns == current->nsproxy->mnt_ns;
1008 }
1009 
1010 /*
1011  * vfsmount lock must be held for write
1012  */
1013 static void touch_mnt_namespace(struct mnt_namespace *ns)
1014 {
1015 	if (ns) {
1016 		ns->event = ++event;
1017 		wake_up_interruptible(&ns->poll);
1018 	}
1019 }
1020 
1021 /*
1022  * vfsmount lock must be held for write
1023  */
1024 static void __touch_mnt_namespace(struct mnt_namespace *ns)
1025 {
1026 	if (ns && ns->event != event) {
1027 		ns->event = event;
1028 		wake_up_interruptible(&ns->poll);
1029 	}
1030 }
1031 
1032 /*
1033  * vfsmount lock must be held for write
1034  */
1035 static struct mountpoint *unhash_mnt(struct mount *mnt)
1036 {
1037 	struct mountpoint *mp;
1038 	mnt->mnt_parent = mnt;
1039 	mnt->mnt_mountpoint = mnt->mnt.mnt_root;
1040 	list_del_init(&mnt->mnt_child);
1041 	hlist_del_init_rcu(&mnt->mnt_hash);
1042 	hlist_del_init(&mnt->mnt_mp_list);
1043 	mp = mnt->mnt_mp;
1044 	mnt->mnt_mp = NULL;
1045 	return mp;
1046 }
1047 
1048 /*
1049  * vfsmount lock must be held for write
1050  */
1051 static void umount_mnt(struct mount *mnt)
1052 {
1053 	put_mountpoint(unhash_mnt(mnt));
1054 }
1055 
1056 /*
1057  * vfsmount lock must be held for write
1058  */
1059 void mnt_set_mountpoint(struct mount *mnt,
1060 			struct mountpoint *mp,
1061 			struct mount *child_mnt)
1062 {
1063 	mp->m_count++;
1064 	mnt_add_count(mnt, 1);	/* essentially, that's mntget */
1065 	child_mnt->mnt_mountpoint = mp->m_dentry;
1066 	child_mnt->mnt_parent = mnt;
1067 	child_mnt->mnt_mp = mp;
1068 	hlist_add_head(&child_mnt->mnt_mp_list, &mp->m_list);
1069 }
1070 
1071 /**
1072  * mnt_set_mountpoint_beneath - mount a mount beneath another one
1073  *
1074  * @new_parent: the source mount
1075  * @top_mnt:    the mount beneath which @new_parent is mounted
1076  * @new_mp:     the new mountpoint of @top_mnt on @new_parent
1077  *
1078  * Remove @top_mnt from its current mountpoint @top_mnt->mnt_mp and
1079  * parent @top_mnt->mnt_parent and mount it on top of @new_parent at
1080  * @new_mp. And mount @new_parent on the old parent and old
1081  * mountpoint of @top_mnt.
1082  *
1083  * Context: This function expects namespace_lock() and lock_mount_hash()
1084  *          to have been acquired in that order.
1085  */
1086 static void mnt_set_mountpoint_beneath(struct mount *new_parent,
1087 				       struct mount *top_mnt,
1088 				       struct mountpoint *new_mp)
1089 {
1090 	struct mount *old_top_parent = top_mnt->mnt_parent;
1091 	struct mountpoint *old_top_mp = top_mnt->mnt_mp;
1092 
1093 	mnt_set_mountpoint(old_top_parent, old_top_mp, new_parent);
1094 	mnt_change_mountpoint(new_parent, new_mp, top_mnt);
1095 }
1096 
1097 
1098 static void __attach_mnt(struct mount *mnt, struct mount *parent)
1099 {
1100 	hlist_add_head_rcu(&mnt->mnt_hash,
1101 			   m_hash(&parent->mnt, mnt->mnt_mountpoint));
1102 	list_add_tail(&mnt->mnt_child, &parent->mnt_mounts);
1103 }
1104 
1105 /**
1106  * attach_mnt - mount a mount, attach to @mount_hashtable and parent's
1107  *              list of child mounts
1108  * @parent:  the parent
1109  * @mnt:     the new mount
1110  * @mp:      the new mountpoint
1111  * @beneath: whether to mount @mnt beneath or on top of @parent
1112  *
1113  * If @beneath is false, mount @mnt at @mp on @parent. Then attach @mnt
1114  * to @parent's child mount list and to @mount_hashtable.
1115  *
1116  * If @beneath is true, remove @mnt from its current parent and
1117  * mountpoint and mount it on @mp on @parent, and mount @parent on the
1118  * old parent and old mountpoint of @mnt. Finally, attach @parent to
1119  * @mnt_hashtable and @parent->mnt_parent->mnt_mounts.
1120  *
1121  * Note, when __attach_mnt() is called @mnt->mnt_parent already points
1122  * to the correct parent.
1123  *
1124  * Context: This function expects namespace_lock() and lock_mount_hash()
1125  *          to have been acquired in that order.
1126  */
1127 static void attach_mnt(struct mount *mnt, struct mount *parent,
1128 		       struct mountpoint *mp, bool beneath)
1129 {
1130 	if (beneath)
1131 		mnt_set_mountpoint_beneath(mnt, parent, mp);
1132 	else
1133 		mnt_set_mountpoint(parent, mp, mnt);
1134 	/*
1135 	 * Note, @mnt->mnt_parent has to be used. If @mnt was mounted
1136 	 * beneath @parent then @mnt will need to be attached to
1137 	 * @parent's old parent, not @parent. IOW, @mnt->mnt_parent
1138 	 * isn't the same mount as @parent.
1139 	 */
1140 	__attach_mnt(mnt, mnt->mnt_parent);
1141 }
1142 
1143 void mnt_change_mountpoint(struct mount *parent, struct mountpoint *mp, struct mount *mnt)
1144 {
1145 	struct mountpoint *old_mp = mnt->mnt_mp;
1146 	struct mount *old_parent = mnt->mnt_parent;
1147 
1148 	list_del_init(&mnt->mnt_child);
1149 	hlist_del_init(&mnt->mnt_mp_list);
1150 	hlist_del_init_rcu(&mnt->mnt_hash);
1151 
1152 	attach_mnt(mnt, parent, mp, false);
1153 
1154 	put_mountpoint(old_mp);
1155 	mnt_add_count(old_parent, -1);
1156 }
1157 
1158 static inline struct mount *node_to_mount(struct rb_node *node)
1159 {
1160 	return node ? rb_entry(node, struct mount, mnt_node) : NULL;
1161 }
1162 
1163 static void mnt_add_to_ns(struct mnt_namespace *ns, struct mount *mnt)
1164 {
1165 	struct rb_node **link = &ns->mounts.rb_node;
1166 	struct rb_node *parent = NULL;
1167 	bool mnt_first_node = true, mnt_last_node = true;
1168 
1169 	WARN_ON(mnt_ns_attached(mnt));
1170 	mnt->mnt_ns = ns;
1171 	while (*link) {
1172 		parent = *link;
1173 		if (mnt->mnt_id_unique < node_to_mount(parent)->mnt_id_unique) {
1174 			link = &parent->rb_left;
1175 			mnt_last_node = false;
1176 		} else {
1177 			link = &parent->rb_right;
1178 			mnt_first_node = false;
1179 		}
1180 	}
1181 
1182 	if (mnt_last_node)
1183 		ns->mnt_last_node = &mnt->mnt_node;
1184 	if (mnt_first_node)
1185 		ns->mnt_first_node = &mnt->mnt_node;
1186 	rb_link_node(&mnt->mnt_node, parent, link);
1187 	rb_insert_color(&mnt->mnt_node, &ns->mounts);
1188 
1189 	mnt_notify_add(mnt);
1190 }
1191 
1192 /*
1193  * vfsmount lock must be held for write
1194  */
1195 static void commit_tree(struct mount *mnt)
1196 {
1197 	struct mount *parent = mnt->mnt_parent;
1198 	struct mount *m;
1199 	LIST_HEAD(head);
1200 	struct mnt_namespace *n = parent->mnt_ns;
1201 
1202 	BUG_ON(parent == mnt);
1203 
1204 	list_add_tail(&head, &mnt->mnt_list);
1205 	while (!list_empty(&head)) {
1206 		m = list_first_entry(&head, typeof(*m), mnt_list);
1207 		list_del(&m->mnt_list);
1208 
1209 		mnt_add_to_ns(n, m);
1210 	}
1211 	n->nr_mounts += n->pending_mounts;
1212 	n->pending_mounts = 0;
1213 
1214 	__attach_mnt(mnt, parent);
1215 	touch_mnt_namespace(n);
1216 }
1217 
1218 static struct mount *next_mnt(struct mount *p, struct mount *root)
1219 {
1220 	struct list_head *next = p->mnt_mounts.next;
1221 	if (next == &p->mnt_mounts) {
1222 		while (1) {
1223 			if (p == root)
1224 				return NULL;
1225 			next = p->mnt_child.next;
1226 			if (next != &p->mnt_parent->mnt_mounts)
1227 				break;
1228 			p = p->mnt_parent;
1229 		}
1230 	}
1231 	return list_entry(next, struct mount, mnt_child);
1232 }
1233 
1234 static struct mount *skip_mnt_tree(struct mount *p)
1235 {
1236 	struct list_head *prev = p->mnt_mounts.prev;
1237 	while (prev != &p->mnt_mounts) {
1238 		p = list_entry(prev, struct mount, mnt_child);
1239 		prev = p->mnt_mounts.prev;
1240 	}
1241 	return p;
1242 }
1243 
1244 /**
1245  * vfs_create_mount - Create a mount for a configured superblock
1246  * @fc: The configuration context with the superblock attached
1247  *
1248  * Create a mount to an already configured superblock.  If necessary, the
1249  * caller should invoke vfs_get_tree() before calling this.
1250  *
1251  * Note that this does not attach the mount to anything.
1252  */
1253 struct vfsmount *vfs_create_mount(struct fs_context *fc)
1254 {
1255 	struct mount *mnt;
1256 
1257 	if (!fc->root)
1258 		return ERR_PTR(-EINVAL);
1259 
1260 	mnt = alloc_vfsmnt(fc->source ?: "none");
1261 	if (!mnt)
1262 		return ERR_PTR(-ENOMEM);
1263 
1264 	if (fc->sb_flags & SB_KERNMOUNT)
1265 		mnt->mnt.mnt_flags = MNT_INTERNAL;
1266 
1267 	atomic_inc(&fc->root->d_sb->s_active);
1268 	mnt->mnt.mnt_sb		= fc->root->d_sb;
1269 	mnt->mnt.mnt_root	= dget(fc->root);
1270 	mnt->mnt_mountpoint	= mnt->mnt.mnt_root;
1271 	mnt->mnt_parent		= mnt;
1272 
1273 	lock_mount_hash();
1274 	list_add_tail(&mnt->mnt_instance, &mnt->mnt.mnt_sb->s_mounts);
1275 	unlock_mount_hash();
1276 	return &mnt->mnt;
1277 }
1278 EXPORT_SYMBOL(vfs_create_mount);
1279 
1280 struct vfsmount *fc_mount(struct fs_context *fc)
1281 {
1282 	int err = vfs_get_tree(fc);
1283 	if (!err) {
1284 		up_write(&fc->root->d_sb->s_umount);
1285 		return vfs_create_mount(fc);
1286 	}
1287 	return ERR_PTR(err);
1288 }
1289 EXPORT_SYMBOL(fc_mount);
1290 
1291 struct vfsmount *vfs_kern_mount(struct file_system_type *type,
1292 				int flags, const char *name,
1293 				void *data)
1294 {
1295 	struct fs_context *fc;
1296 	struct vfsmount *mnt;
1297 	int ret = 0;
1298 
1299 	if (!type)
1300 		return ERR_PTR(-EINVAL);
1301 
1302 	fc = fs_context_for_mount(type, flags);
1303 	if (IS_ERR(fc))
1304 		return ERR_CAST(fc);
1305 
1306 	if (name)
1307 		ret = vfs_parse_fs_string(fc, "source",
1308 					  name, strlen(name));
1309 	if (!ret)
1310 		ret = parse_monolithic_mount_data(fc, data);
1311 	if (!ret)
1312 		mnt = fc_mount(fc);
1313 	else
1314 		mnt = ERR_PTR(ret);
1315 
1316 	put_fs_context(fc);
1317 	return mnt;
1318 }
1319 EXPORT_SYMBOL_GPL(vfs_kern_mount);
1320 
1321 struct vfsmount *
1322 vfs_submount(const struct dentry *mountpoint, struct file_system_type *type,
1323 	     const char *name, void *data)
1324 {
1325 	/* Until it is worked out how to pass the user namespace
1326 	 * through from the parent mount to the submount don't support
1327 	 * unprivileged mounts with submounts.
1328 	 */
1329 	if (mountpoint->d_sb->s_user_ns != &init_user_ns)
1330 		return ERR_PTR(-EPERM);
1331 
1332 	return vfs_kern_mount(type, SB_SUBMOUNT, name, data);
1333 }
1334 EXPORT_SYMBOL_GPL(vfs_submount);
1335 
1336 static struct mount *clone_mnt(struct mount *old, struct dentry *root,
1337 					int flag)
1338 {
1339 	struct super_block *sb = old->mnt.mnt_sb;
1340 	struct mount *mnt;
1341 	int err;
1342 
1343 	mnt = alloc_vfsmnt(old->mnt_devname);
1344 	if (!mnt)
1345 		return ERR_PTR(-ENOMEM);
1346 
1347 	if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))
1348 		mnt->mnt_group_id = 0; /* not a peer of original */
1349 	else
1350 		mnt->mnt_group_id = old->mnt_group_id;
1351 
1352 	if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
1353 		err = mnt_alloc_group_id(mnt);
1354 		if (err)
1355 			goto out_free;
1356 	}
1357 
1358 	mnt->mnt.mnt_flags = old->mnt.mnt_flags;
1359 	mnt->mnt.mnt_flags &= ~(MNT_WRITE_HOLD|MNT_MARKED|MNT_INTERNAL);
1360 
1361 	atomic_inc(&sb->s_active);
1362 	mnt->mnt.mnt_idmap = mnt_idmap_get(mnt_idmap(&old->mnt));
1363 
1364 	mnt->mnt.mnt_sb = sb;
1365 	mnt->mnt.mnt_root = dget(root);
1366 	mnt->mnt_mountpoint = mnt->mnt.mnt_root;
1367 	mnt->mnt_parent = mnt;
1368 	lock_mount_hash();
1369 	list_add_tail(&mnt->mnt_instance, &sb->s_mounts);
1370 	unlock_mount_hash();
1371 
1372 	if ((flag & CL_SLAVE) ||
1373 	    ((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {
1374 		list_add(&mnt->mnt_slave, &old->mnt_slave_list);
1375 		mnt->mnt_master = old;
1376 		CLEAR_MNT_SHARED(mnt);
1377 	} else if (!(flag & CL_PRIVATE)) {
1378 		if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))
1379 			list_add(&mnt->mnt_share, &old->mnt_share);
1380 		if (IS_MNT_SLAVE(old))
1381 			list_add(&mnt->mnt_slave, &old->mnt_slave);
1382 		mnt->mnt_master = old->mnt_master;
1383 	} else {
1384 		CLEAR_MNT_SHARED(mnt);
1385 	}
1386 	if (flag & CL_MAKE_SHARED)
1387 		set_mnt_shared(mnt);
1388 
1389 	/* stick the duplicate mount on the same expiry list
1390 	 * as the original if that was on one */
1391 	if (flag & CL_EXPIRE) {
1392 		if (!list_empty(&old->mnt_expire))
1393 			list_add(&mnt->mnt_expire, &old->mnt_expire);
1394 	}
1395 
1396 	return mnt;
1397 
1398  out_free:
1399 	mnt_free_id(mnt);
1400 	free_vfsmnt(mnt);
1401 	return ERR_PTR(err);
1402 }
1403 
1404 static void cleanup_mnt(struct mount *mnt)
1405 {
1406 	struct hlist_node *p;
1407 	struct mount *m;
1408 	/*
1409 	 * The warning here probably indicates that somebody messed
1410 	 * up a mnt_want/drop_write() pair.  If this happens, the
1411 	 * filesystem was probably unable to make r/w->r/o transitions.
1412 	 * The locking used to deal with mnt_count decrement provides barriers,
1413 	 * so mnt_get_writers() below is safe.
1414 	 */
1415 	WARN_ON(mnt_get_writers(mnt));
1416 	if (unlikely(mnt->mnt_pins.first))
1417 		mnt_pin_kill(mnt);
1418 	hlist_for_each_entry_safe(m, p, &mnt->mnt_stuck_children, mnt_umount) {
1419 		hlist_del(&m->mnt_umount);
1420 		mntput(&m->mnt);
1421 	}
1422 	fsnotify_vfsmount_delete(&mnt->mnt);
1423 	dput(mnt->mnt.mnt_root);
1424 	deactivate_super(mnt->mnt.mnt_sb);
1425 	mnt_free_id(mnt);
1426 	call_rcu(&mnt->mnt_rcu, delayed_free_vfsmnt);
1427 }
1428 
1429 static void __cleanup_mnt(struct rcu_head *head)
1430 {
1431 	cleanup_mnt(container_of(head, struct mount, mnt_rcu));
1432 }
1433 
1434 static LLIST_HEAD(delayed_mntput_list);
1435 static void delayed_mntput(struct work_struct *unused)
1436 {
1437 	struct llist_node *node = llist_del_all(&delayed_mntput_list);
1438 	struct mount *m, *t;
1439 
1440 	llist_for_each_entry_safe(m, t, node, mnt_llist)
1441 		cleanup_mnt(m);
1442 }
1443 static DECLARE_DELAYED_WORK(delayed_mntput_work, delayed_mntput);
1444 
1445 static void mntput_no_expire(struct mount *mnt)
1446 {
1447 	LIST_HEAD(list);
1448 	int count;
1449 
1450 	rcu_read_lock();
1451 	if (likely(READ_ONCE(mnt->mnt_ns))) {
1452 		/*
1453 		 * Since we don't do lock_mount_hash() here,
1454 		 * ->mnt_ns can change under us.  However, if it's
1455 		 * non-NULL, then there's a reference that won't
1456 		 * be dropped until after an RCU delay done after
1457 		 * turning ->mnt_ns NULL.  So if we observe it
1458 		 * non-NULL under rcu_read_lock(), the reference
1459 		 * we are dropping is not the final one.
1460 		 */
1461 		mnt_add_count(mnt, -1);
1462 		rcu_read_unlock();
1463 		return;
1464 	}
1465 	lock_mount_hash();
1466 	/*
1467 	 * make sure that if __legitimize_mnt() has not seen us grab
1468 	 * mount_lock, we'll see their refcount increment here.
1469 	 */
1470 	smp_mb();
1471 	mnt_add_count(mnt, -1);
1472 	count = mnt_get_count(mnt);
1473 	if (count != 0) {
1474 		WARN_ON(count < 0);
1475 		rcu_read_unlock();
1476 		unlock_mount_hash();
1477 		return;
1478 	}
1479 	if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) {
1480 		rcu_read_unlock();
1481 		unlock_mount_hash();
1482 		return;
1483 	}
1484 	mnt->mnt.mnt_flags |= MNT_DOOMED;
1485 	rcu_read_unlock();
1486 
1487 	list_del(&mnt->mnt_instance);
1488 
1489 	if (unlikely(!list_empty(&mnt->mnt_mounts))) {
1490 		struct mount *p, *tmp;
1491 		list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts,  mnt_child) {
1492 			__put_mountpoint(unhash_mnt(p), &list);
1493 			hlist_add_head(&p->mnt_umount, &mnt->mnt_stuck_children);
1494 		}
1495 	}
1496 	unlock_mount_hash();
1497 	shrink_dentry_list(&list);
1498 
1499 	if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) {
1500 		struct task_struct *task = current;
1501 		if (likely(!(task->flags & PF_KTHREAD))) {
1502 			init_task_work(&mnt->mnt_rcu, __cleanup_mnt);
1503 			if (!task_work_add(task, &mnt->mnt_rcu, TWA_RESUME))
1504 				return;
1505 		}
1506 		if (llist_add(&mnt->mnt_llist, &delayed_mntput_list))
1507 			schedule_delayed_work(&delayed_mntput_work, 1);
1508 		return;
1509 	}
1510 	cleanup_mnt(mnt);
1511 }
1512 
1513 void mntput(struct vfsmount *mnt)
1514 {
1515 	if (mnt) {
1516 		struct mount *m = real_mount(mnt);
1517 		/* avoid cacheline pingpong */
1518 		if (unlikely(m->mnt_expiry_mark))
1519 			WRITE_ONCE(m->mnt_expiry_mark, 0);
1520 		mntput_no_expire(m);
1521 	}
1522 }
1523 EXPORT_SYMBOL(mntput);
1524 
1525 struct vfsmount *mntget(struct vfsmount *mnt)
1526 {
1527 	if (mnt)
1528 		mnt_add_count(real_mount(mnt), 1);
1529 	return mnt;
1530 }
1531 EXPORT_SYMBOL(mntget);
1532 
1533 /*
1534  * Make a mount point inaccessible to new lookups.
1535  * Because there may still be current users, the caller MUST WAIT
1536  * for an RCU grace period before destroying the mount point.
1537  */
1538 void mnt_make_shortterm(struct vfsmount *mnt)
1539 {
1540 	if (mnt)
1541 		real_mount(mnt)->mnt_ns = NULL;
1542 }
1543 
1544 /**
1545  * path_is_mountpoint() - Check if path is a mount in the current namespace.
1546  * @path: path to check
1547  *
1548  *  d_mountpoint() can only be used reliably to establish if a dentry is
1549  *  not mounted in any namespace and that common case is handled inline.
1550  *  d_mountpoint() isn't aware of the possibility there may be multiple
1551  *  mounts using a given dentry in a different namespace. This function
1552  *  checks if the passed in path is a mountpoint rather than the dentry
1553  *  alone.
1554  */
1555 bool path_is_mountpoint(const struct path *path)
1556 {
1557 	unsigned seq;
1558 	bool res;
1559 
1560 	if (!d_mountpoint(path->dentry))
1561 		return false;
1562 
1563 	rcu_read_lock();
1564 	do {
1565 		seq = read_seqbegin(&mount_lock);
1566 		res = __path_is_mountpoint(path);
1567 	} while (read_seqretry(&mount_lock, seq));
1568 	rcu_read_unlock();
1569 
1570 	return res;
1571 }
1572 EXPORT_SYMBOL(path_is_mountpoint);
1573 
1574 struct vfsmount *mnt_clone_internal(const struct path *path)
1575 {
1576 	struct mount *p;
1577 	p = clone_mnt(real_mount(path->mnt), path->dentry, CL_PRIVATE);
1578 	if (IS_ERR(p))
1579 		return ERR_CAST(p);
1580 	p->mnt.mnt_flags |= MNT_INTERNAL;
1581 	return &p->mnt;
1582 }
1583 
1584 /*
1585  * Returns the mount which either has the specified mnt_id, or has the next
1586  * smallest id afer the specified one.
1587  */
1588 static struct mount *mnt_find_id_at(struct mnt_namespace *ns, u64 mnt_id)
1589 {
1590 	struct rb_node *node = ns->mounts.rb_node;
1591 	struct mount *ret = NULL;
1592 
1593 	while (node) {
1594 		struct mount *m = node_to_mount(node);
1595 
1596 		if (mnt_id <= m->mnt_id_unique) {
1597 			ret = node_to_mount(node);
1598 			if (mnt_id == m->mnt_id_unique)
1599 				break;
1600 			node = node->rb_left;
1601 		} else {
1602 			node = node->rb_right;
1603 		}
1604 	}
1605 	return ret;
1606 }
1607 
1608 /*
1609  * Returns the mount which either has the specified mnt_id, or has the next
1610  * greater id before the specified one.
1611  */
1612 static struct mount *mnt_find_id_at_reverse(struct mnt_namespace *ns, u64 mnt_id)
1613 {
1614 	struct rb_node *node = ns->mounts.rb_node;
1615 	struct mount *ret = NULL;
1616 
1617 	while (node) {
1618 		struct mount *m = node_to_mount(node);
1619 
1620 		if (mnt_id >= m->mnt_id_unique) {
1621 			ret = node_to_mount(node);
1622 			if (mnt_id == m->mnt_id_unique)
1623 				break;
1624 			node = node->rb_right;
1625 		} else {
1626 			node = node->rb_left;
1627 		}
1628 	}
1629 	return ret;
1630 }
1631 
1632 #ifdef CONFIG_PROC_FS
1633 
1634 /* iterator; we want it to have access to namespace_sem, thus here... */
1635 static void *m_start(struct seq_file *m, loff_t *pos)
1636 {
1637 	struct proc_mounts *p = m->private;
1638 
1639 	down_read(&namespace_sem);
1640 
1641 	return mnt_find_id_at(p->ns, *pos);
1642 }
1643 
1644 static void *m_next(struct seq_file *m, void *v, loff_t *pos)
1645 {
1646 	struct mount *next = NULL, *mnt = v;
1647 	struct rb_node *node = rb_next(&mnt->mnt_node);
1648 
1649 	++*pos;
1650 	if (node) {
1651 		next = node_to_mount(node);
1652 		*pos = next->mnt_id_unique;
1653 	}
1654 	return next;
1655 }
1656 
1657 static void m_stop(struct seq_file *m, void *v)
1658 {
1659 	up_read(&namespace_sem);
1660 }
1661 
1662 static int m_show(struct seq_file *m, void *v)
1663 {
1664 	struct proc_mounts *p = m->private;
1665 	struct mount *r = v;
1666 	return p->show(m, &r->mnt);
1667 }
1668 
1669 const struct seq_operations mounts_op = {
1670 	.start	= m_start,
1671 	.next	= m_next,
1672 	.stop	= m_stop,
1673 	.show	= m_show,
1674 };
1675 
1676 #endif  /* CONFIG_PROC_FS */
1677 
1678 /**
1679  * may_umount_tree - check if a mount tree is busy
1680  * @m: root of mount tree
1681  *
1682  * This is called to check if a tree of mounts has any
1683  * open files, pwds, chroots or sub mounts that are
1684  * busy.
1685  */
1686 int may_umount_tree(struct vfsmount *m)
1687 {
1688 	struct mount *mnt = real_mount(m);
1689 	int actual_refs = 0;
1690 	int minimum_refs = 0;
1691 	struct mount *p;
1692 	BUG_ON(!m);
1693 
1694 	/* write lock needed for mnt_get_count */
1695 	lock_mount_hash();
1696 	for (p = mnt; p; p = next_mnt(p, mnt)) {
1697 		actual_refs += mnt_get_count(p);
1698 		minimum_refs += 2;
1699 	}
1700 	unlock_mount_hash();
1701 
1702 	if (actual_refs > minimum_refs)
1703 		return 0;
1704 
1705 	return 1;
1706 }
1707 
1708 EXPORT_SYMBOL(may_umount_tree);
1709 
1710 /**
1711  * may_umount - check if a mount point is busy
1712  * @mnt: root of mount
1713  *
1714  * This is called to check if a mount point has any
1715  * open files, pwds, chroots or sub mounts. If the
1716  * mount has sub mounts this will return busy
1717  * regardless of whether the sub mounts are busy.
1718  *
1719  * Doesn't take quota and stuff into account. IOW, in some cases it will
1720  * give false negatives. The main reason why it's here is that we need
1721  * a non-destructive way to look for easily umountable filesystems.
1722  */
1723 int may_umount(struct vfsmount *mnt)
1724 {
1725 	int ret = 1;
1726 	down_read(&namespace_sem);
1727 	lock_mount_hash();
1728 	if (propagate_mount_busy(real_mount(mnt), 2))
1729 		ret = 0;
1730 	unlock_mount_hash();
1731 	up_read(&namespace_sem);
1732 	return ret;
1733 }
1734 
1735 EXPORT_SYMBOL(may_umount);
1736 
1737 #ifdef CONFIG_FSNOTIFY
1738 static void mnt_notify(struct mount *p)
1739 {
1740 	if (!p->prev_ns && p->mnt_ns) {
1741 		fsnotify_mnt_attach(p->mnt_ns, &p->mnt);
1742 	} else if (p->prev_ns && !p->mnt_ns) {
1743 		fsnotify_mnt_detach(p->prev_ns, &p->mnt);
1744 	} else if (p->prev_ns == p->mnt_ns) {
1745 		fsnotify_mnt_move(p->mnt_ns, &p->mnt);
1746 	} else {
1747 		fsnotify_mnt_detach(p->prev_ns, &p->mnt);
1748 		fsnotify_mnt_attach(p->mnt_ns, &p->mnt);
1749 	}
1750 	p->prev_ns = p->mnt_ns;
1751 }
1752 
1753 static void notify_mnt_list(void)
1754 {
1755 	struct mount *m, *tmp;
1756 	/*
1757 	 * Notify about mounts that were added/reparented/detached/remain
1758 	 * connected after unmount.
1759 	 */
1760 	list_for_each_entry_safe(m, tmp, &notify_list, to_notify) {
1761 		mnt_notify(m);
1762 		list_del_init(&m->to_notify);
1763 	}
1764 }
1765 
1766 static bool need_notify_mnt_list(void)
1767 {
1768 	return !list_empty(&notify_list);
1769 }
1770 #else
1771 static void notify_mnt_list(void)
1772 {
1773 }
1774 
1775 static bool need_notify_mnt_list(void)
1776 {
1777 	return false;
1778 }
1779 #endif
1780 
1781 static void namespace_unlock(void)
1782 {
1783 	struct hlist_head head;
1784 	struct hlist_node *p;
1785 	struct mount *m;
1786 	LIST_HEAD(list);
1787 
1788 	hlist_move_list(&unmounted, &head);
1789 	list_splice_init(&ex_mountpoints, &list);
1790 
1791 	if (need_notify_mnt_list()) {
1792 		/*
1793 		 * No point blocking out concurrent readers while notifications
1794 		 * are sent. This will also allow statmount()/listmount() to run
1795 		 * concurrently.
1796 		 */
1797 		downgrade_write(&namespace_sem);
1798 		notify_mnt_list();
1799 		up_read(&namespace_sem);
1800 	} else {
1801 		up_write(&namespace_sem);
1802 	}
1803 
1804 	shrink_dentry_list(&list);
1805 
1806 	if (likely(hlist_empty(&head)))
1807 		return;
1808 
1809 	synchronize_rcu_expedited();
1810 
1811 	hlist_for_each_entry_safe(m, p, &head, mnt_umount) {
1812 		hlist_del(&m->mnt_umount);
1813 		mntput(&m->mnt);
1814 	}
1815 }
1816 
1817 static inline void namespace_lock(void)
1818 {
1819 	down_write(&namespace_sem);
1820 }
1821 
1822 enum umount_tree_flags {
1823 	UMOUNT_SYNC = 1,
1824 	UMOUNT_PROPAGATE = 2,
1825 	UMOUNT_CONNECTED = 4,
1826 };
1827 
1828 static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)
1829 {
1830 	/* Leaving mounts connected is only valid for lazy umounts */
1831 	if (how & UMOUNT_SYNC)
1832 		return true;
1833 
1834 	/* A mount without a parent has nothing to be connected to */
1835 	if (!mnt_has_parent(mnt))
1836 		return true;
1837 
1838 	/* Because the reference counting rules change when mounts are
1839 	 * unmounted and connected, umounted mounts may not be
1840 	 * connected to mounted mounts.
1841 	 */
1842 	if (!(mnt->mnt_parent->mnt.mnt_flags & MNT_UMOUNT))
1843 		return true;
1844 
1845 	/* Has it been requested that the mount remain connected? */
1846 	if (how & UMOUNT_CONNECTED)
1847 		return false;
1848 
1849 	/* Is the mount locked such that it needs to remain connected? */
1850 	if (IS_MNT_LOCKED(mnt))
1851 		return false;
1852 
1853 	/* By default disconnect the mount */
1854 	return true;
1855 }
1856 
1857 /*
1858  * mount_lock must be held
1859  * namespace_sem must be held for write
1860  */
1861 static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
1862 {
1863 	LIST_HEAD(tmp_list);
1864 	struct mount *p;
1865 
1866 	if (how & UMOUNT_PROPAGATE)
1867 		propagate_mount_unlock(mnt);
1868 
1869 	/* Gather the mounts to umount */
1870 	for (p = mnt; p; p = next_mnt(p, mnt)) {
1871 		p->mnt.mnt_flags |= MNT_UMOUNT;
1872 		if (mnt_ns_attached(p))
1873 			move_from_ns(p, &tmp_list);
1874 		else
1875 			list_move(&p->mnt_list, &tmp_list);
1876 	}
1877 
1878 	/* Hide the mounts from mnt_mounts */
1879 	list_for_each_entry(p, &tmp_list, mnt_list) {
1880 		list_del_init(&p->mnt_child);
1881 	}
1882 
1883 	/* Add propagated mounts to the tmp_list */
1884 	if (how & UMOUNT_PROPAGATE)
1885 		propagate_umount(&tmp_list);
1886 
1887 	while (!list_empty(&tmp_list)) {
1888 		struct mnt_namespace *ns;
1889 		bool disconnect;
1890 		p = list_first_entry(&tmp_list, struct mount, mnt_list);
1891 		list_del_init(&p->mnt_expire);
1892 		list_del_init(&p->mnt_list);
1893 		ns = p->mnt_ns;
1894 		if (ns) {
1895 			ns->nr_mounts--;
1896 			__touch_mnt_namespace(ns);
1897 		}
1898 		p->mnt_ns = NULL;
1899 		if (how & UMOUNT_SYNC)
1900 			p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
1901 
1902 		disconnect = disconnect_mount(p, how);
1903 		if (mnt_has_parent(p)) {
1904 			mnt_add_count(p->mnt_parent, -1);
1905 			if (!disconnect) {
1906 				/* Don't forget about p */
1907 				list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
1908 			} else {
1909 				umount_mnt(p);
1910 			}
1911 		}
1912 		change_mnt_propagation(p, MS_PRIVATE);
1913 		if (disconnect)
1914 			hlist_add_head(&p->mnt_umount, &unmounted);
1915 
1916 		/*
1917 		 * At this point p->mnt_ns is NULL, notification will be queued
1918 		 * only if
1919 		 *
1920 		 *  - p->prev_ns is non-NULL *and*
1921 		 *  - p->prev_ns->n_fsnotify_marks is non-NULL
1922 		 *
1923 		 * This will preclude queuing the mount if this is a cleanup
1924 		 * after a failed copy_tree() or destruction of an anonymous
1925 		 * namespace, etc.
1926 		 */
1927 		mnt_notify_add(p);
1928 	}
1929 }
1930 
1931 static void shrink_submounts(struct mount *mnt);
1932 
1933 static int do_umount_root(struct super_block *sb)
1934 {
1935 	int ret = 0;
1936 
1937 	down_write(&sb->s_umount);
1938 	if (!sb_rdonly(sb)) {
1939 		struct fs_context *fc;
1940 
1941 		fc = fs_context_for_reconfigure(sb->s_root, SB_RDONLY,
1942 						SB_RDONLY);
1943 		if (IS_ERR(fc)) {
1944 			ret = PTR_ERR(fc);
1945 		} else {
1946 			ret = parse_monolithic_mount_data(fc, NULL);
1947 			if (!ret)
1948 				ret = reconfigure_super(fc);
1949 			put_fs_context(fc);
1950 		}
1951 	}
1952 	up_write(&sb->s_umount);
1953 	return ret;
1954 }
1955 
1956 static int do_umount(struct mount *mnt, int flags)
1957 {
1958 	struct super_block *sb = mnt->mnt.mnt_sb;
1959 	int retval;
1960 
1961 	retval = security_sb_umount(&mnt->mnt, flags);
1962 	if (retval)
1963 		return retval;
1964 
1965 	/*
1966 	 * Allow userspace to request a mountpoint be expired rather than
1967 	 * unmounting unconditionally. Unmount only happens if:
1968 	 *  (1) the mark is already set (the mark is cleared by mntput())
1969 	 *  (2) the usage count == 1 [parent vfsmount] + 1 [sys_umount]
1970 	 */
1971 	if (flags & MNT_EXPIRE) {
1972 		if (&mnt->mnt == current->fs->root.mnt ||
1973 		    flags & (MNT_FORCE | MNT_DETACH))
1974 			return -EINVAL;
1975 
1976 		/*
1977 		 * probably don't strictly need the lock here if we examined
1978 		 * all race cases, but it's a slowpath.
1979 		 */
1980 		lock_mount_hash();
1981 		if (mnt_get_count(mnt) != 2) {
1982 			unlock_mount_hash();
1983 			return -EBUSY;
1984 		}
1985 		unlock_mount_hash();
1986 
1987 		if (!xchg(&mnt->mnt_expiry_mark, 1))
1988 			return -EAGAIN;
1989 	}
1990 
1991 	/*
1992 	 * If we may have to abort operations to get out of this
1993 	 * mount, and they will themselves hold resources we must
1994 	 * allow the fs to do things. In the Unix tradition of
1995 	 * 'Gee thats tricky lets do it in userspace' the umount_begin
1996 	 * might fail to complete on the first run through as other tasks
1997 	 * must return, and the like. Thats for the mount program to worry
1998 	 * about for the moment.
1999 	 */
2000 
2001 	if (flags & MNT_FORCE && sb->s_op->umount_begin) {
2002 		sb->s_op->umount_begin(sb);
2003 	}
2004 
2005 	/*
2006 	 * No sense to grab the lock for this test, but test itself looks
2007 	 * somewhat bogus. Suggestions for better replacement?
2008 	 * Ho-hum... In principle, we might treat that as umount + switch
2009 	 * to rootfs. GC would eventually take care of the old vfsmount.
2010 	 * Actually it makes sense, especially if rootfs would contain a
2011 	 * /reboot - static binary that would close all descriptors and
2012 	 * call reboot(9). Then init(8) could umount root and exec /reboot.
2013 	 */
2014 	if (&mnt->mnt == current->fs->root.mnt && !(flags & MNT_DETACH)) {
2015 		/*
2016 		 * Special case for "unmounting" root ...
2017 		 * we just try to remount it readonly.
2018 		 */
2019 		if (!ns_capable(sb->s_user_ns, CAP_SYS_ADMIN))
2020 			return -EPERM;
2021 		return do_umount_root(sb);
2022 	}
2023 
2024 	namespace_lock();
2025 	lock_mount_hash();
2026 
2027 	/* Recheck MNT_LOCKED with the locks held */
2028 	retval = -EINVAL;
2029 	if (mnt->mnt.mnt_flags & MNT_LOCKED)
2030 		goto out;
2031 
2032 	event++;
2033 	if (flags & MNT_DETACH) {
2034 		if (mnt_ns_attached(mnt) || !list_empty(&mnt->mnt_list))
2035 			umount_tree(mnt, UMOUNT_PROPAGATE);
2036 		retval = 0;
2037 	} else {
2038 		shrink_submounts(mnt);
2039 		retval = -EBUSY;
2040 		if (!propagate_mount_busy(mnt, 2)) {
2041 			if (mnt_ns_attached(mnt) || !list_empty(&mnt->mnt_list))
2042 				umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
2043 			retval = 0;
2044 		}
2045 	}
2046 out:
2047 	unlock_mount_hash();
2048 	namespace_unlock();
2049 	return retval;
2050 }
2051 
2052 /*
2053  * __detach_mounts - lazily unmount all mounts on the specified dentry
2054  *
2055  * During unlink, rmdir, and d_drop it is possible to loose the path
2056  * to an existing mountpoint, and wind up leaking the mount.
2057  * detach_mounts allows lazily unmounting those mounts instead of
2058  * leaking them.
2059  *
2060  * The caller may hold dentry->d_inode->i_mutex.
2061  */
2062 void __detach_mounts(struct dentry *dentry)
2063 {
2064 	struct mountpoint *mp;
2065 	struct mount *mnt;
2066 
2067 	namespace_lock();
2068 	lock_mount_hash();
2069 	mp = lookup_mountpoint(dentry);
2070 	if (!mp)
2071 		goto out_unlock;
2072 
2073 	event++;
2074 	while (!hlist_empty(&mp->m_list)) {
2075 		mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
2076 		if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
2077 			umount_mnt(mnt);
2078 			hlist_add_head(&mnt->mnt_umount, &unmounted);
2079 		}
2080 		else umount_tree(mnt, UMOUNT_CONNECTED);
2081 	}
2082 	put_mountpoint(mp);
2083 out_unlock:
2084 	unlock_mount_hash();
2085 	namespace_unlock();
2086 }
2087 
2088 /*
2089  * Is the caller allowed to modify his namespace?
2090  */
2091 bool may_mount(void)
2092 {
2093 	return ns_capable(current->nsproxy->mnt_ns->user_ns, CAP_SYS_ADMIN);
2094 }
2095 
2096 static void warn_mandlock(void)
2097 {
2098 	pr_warn_once("=======================================================\n"
2099 		     "WARNING: The mand mount option has been deprecated and\n"
2100 		     "         and is ignored by this kernel. Remove the mand\n"
2101 		     "         option from the mount to silence this warning.\n"
2102 		     "=======================================================\n");
2103 }
2104 
2105 static int can_umount(const struct path *path, int flags)
2106 {
2107 	struct mount *mnt = real_mount(path->mnt);
2108 	struct super_block *sb = path->dentry->d_sb;
2109 
2110 	if (!may_mount())
2111 		return -EPERM;
2112 	if (!path_mounted(path))
2113 		return -EINVAL;
2114 	if (!check_mnt(mnt))
2115 		return -EINVAL;
2116 	if (mnt->mnt.mnt_flags & MNT_LOCKED) /* Check optimistically */
2117 		return -EINVAL;
2118 	if (flags & MNT_FORCE && !ns_capable(sb->s_user_ns, CAP_SYS_ADMIN))
2119 		return -EPERM;
2120 	return 0;
2121 }
2122 
2123 // caller is responsible for flags being sane
2124 int path_umount(struct path *path, int flags)
2125 {
2126 	struct mount *mnt = real_mount(path->mnt);
2127 	int ret;
2128 
2129 	ret = can_umount(path, flags);
2130 	if (!ret)
2131 		ret = do_umount(mnt, flags);
2132 
2133 	/* we mustn't call path_put() as that would clear mnt_expiry_mark */
2134 	dput(path->dentry);
2135 	mntput_no_expire(mnt);
2136 	return ret;
2137 }
2138 
2139 static int ksys_umount(char __user *name, int flags)
2140 {
2141 	int lookup_flags = LOOKUP_MOUNTPOINT;
2142 	struct path path;
2143 	int ret;
2144 
2145 	// basic validity checks done first
2146 	if (flags & ~(MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW))
2147 		return -EINVAL;
2148 
2149 	if (!(flags & UMOUNT_NOFOLLOW))
2150 		lookup_flags |= LOOKUP_FOLLOW;
2151 	ret = user_path_at(AT_FDCWD, name, lookup_flags, &path);
2152 	if (ret)
2153 		return ret;
2154 	return path_umount(&path, flags);
2155 }
2156 
2157 SYSCALL_DEFINE2(umount, char __user *, name, int, flags)
2158 {
2159 	return ksys_umount(name, flags);
2160 }
2161 
2162 #ifdef __ARCH_WANT_SYS_OLDUMOUNT
2163 
2164 /*
2165  *	The 2.0 compatible umount. No flags.
2166  */
2167 SYSCALL_DEFINE1(oldumount, char __user *, name)
2168 {
2169 	return ksys_umount(name, 0);
2170 }
2171 
2172 #endif
2173 
2174 static bool is_mnt_ns_file(struct dentry *dentry)
2175 {
2176 	struct ns_common *ns;
2177 
2178 	/* Is this a proxy for a mount namespace? */
2179 	if (dentry->d_op != &ns_dentry_operations)
2180 		return false;
2181 
2182 	ns = d_inode(dentry)->i_private;
2183 
2184 	return ns->ops == &mntns_operations;
2185 }
2186 
2187 struct ns_common *from_mnt_ns(struct mnt_namespace *mnt)
2188 {
2189 	return &mnt->ns;
2190 }
2191 
2192 struct mnt_namespace *get_sequential_mnt_ns(struct mnt_namespace *mntns, bool previous)
2193 {
2194 	guard(rcu)();
2195 
2196 	for (;;) {
2197 		struct list_head *list;
2198 
2199 		if (previous)
2200 			list = rcu_dereference(list_bidir_prev_rcu(&mntns->mnt_ns_list));
2201 		else
2202 			list = rcu_dereference(list_next_rcu(&mntns->mnt_ns_list));
2203 		if (list_is_head(list, &mnt_ns_list))
2204 			return ERR_PTR(-ENOENT);
2205 
2206 		mntns = list_entry_rcu(list, struct mnt_namespace, mnt_ns_list);
2207 
2208 		/*
2209 		 * The last passive reference count is put with RCU
2210 		 * delay so accessing the mount namespace is not just
2211 		 * safe but all relevant members are still valid.
2212 		 */
2213 		if (!ns_capable_noaudit(mntns->user_ns, CAP_SYS_ADMIN))
2214 			continue;
2215 
2216 		/*
2217 		 * We need an active reference count as we're persisting
2218 		 * the mount namespace and it might already be on its
2219 		 * deathbed.
2220 		 */
2221 		if (!refcount_inc_not_zero(&mntns->ns.count))
2222 			continue;
2223 
2224 		return mntns;
2225 	}
2226 }
2227 
2228 struct mnt_namespace *mnt_ns_from_dentry(struct dentry *dentry)
2229 {
2230 	if (!is_mnt_ns_file(dentry))
2231 		return NULL;
2232 
2233 	return to_mnt_ns(get_proc_ns(dentry->d_inode));
2234 }
2235 
2236 static bool mnt_ns_loop(struct dentry *dentry)
2237 {
2238 	/* Could bind mounting the mount namespace inode cause a
2239 	 * mount namespace loop?
2240 	 */
2241 	struct mnt_namespace *mnt_ns = mnt_ns_from_dentry(dentry);
2242 
2243 	if (!mnt_ns)
2244 		return false;
2245 
2246 	return current->nsproxy->mnt_ns->seq >= mnt_ns->seq;
2247 }
2248 
2249 struct mount *copy_tree(struct mount *src_root, struct dentry *dentry,
2250 					int flag)
2251 {
2252 	struct mount *res, *src_parent, *src_root_child, *src_mnt,
2253 		*dst_parent, *dst_mnt;
2254 
2255 	if (!(flag & CL_COPY_UNBINDABLE) && IS_MNT_UNBINDABLE(src_root))
2256 		return ERR_PTR(-EINVAL);
2257 
2258 	if (!(flag & CL_COPY_MNT_NS_FILE) && is_mnt_ns_file(dentry))
2259 		return ERR_PTR(-EINVAL);
2260 
2261 	res = dst_mnt = clone_mnt(src_root, dentry, flag);
2262 	if (IS_ERR(dst_mnt))
2263 		return dst_mnt;
2264 
2265 	src_parent = src_root;
2266 	dst_mnt->mnt_mountpoint = src_root->mnt_mountpoint;
2267 
2268 	list_for_each_entry(src_root_child, &src_root->mnt_mounts, mnt_child) {
2269 		if (!is_subdir(src_root_child->mnt_mountpoint, dentry))
2270 			continue;
2271 
2272 		for (src_mnt = src_root_child; src_mnt;
2273 		    src_mnt = next_mnt(src_mnt, src_root_child)) {
2274 			if (!(flag & CL_COPY_UNBINDABLE) &&
2275 			    IS_MNT_UNBINDABLE(src_mnt)) {
2276 				if (src_mnt->mnt.mnt_flags & MNT_LOCKED) {
2277 					/* Both unbindable and locked. */
2278 					dst_mnt = ERR_PTR(-EPERM);
2279 					goto out;
2280 				} else {
2281 					src_mnt = skip_mnt_tree(src_mnt);
2282 					continue;
2283 				}
2284 			}
2285 			if (!(flag & CL_COPY_MNT_NS_FILE) &&
2286 			    is_mnt_ns_file(src_mnt->mnt.mnt_root)) {
2287 				src_mnt = skip_mnt_tree(src_mnt);
2288 				continue;
2289 			}
2290 			while (src_parent != src_mnt->mnt_parent) {
2291 				src_parent = src_parent->mnt_parent;
2292 				dst_mnt = dst_mnt->mnt_parent;
2293 			}
2294 
2295 			src_parent = src_mnt;
2296 			dst_parent = dst_mnt;
2297 			dst_mnt = clone_mnt(src_mnt, src_mnt->mnt.mnt_root, flag);
2298 			if (IS_ERR(dst_mnt))
2299 				goto out;
2300 			lock_mount_hash();
2301 			list_add_tail(&dst_mnt->mnt_list, &res->mnt_list);
2302 			attach_mnt(dst_mnt, dst_parent, src_parent->mnt_mp, false);
2303 			unlock_mount_hash();
2304 		}
2305 	}
2306 	return res;
2307 
2308 out:
2309 	if (res) {
2310 		lock_mount_hash();
2311 		umount_tree(res, UMOUNT_SYNC);
2312 		unlock_mount_hash();
2313 	}
2314 	return dst_mnt;
2315 }
2316 
2317 /* Caller should check returned pointer for errors */
2318 
2319 struct vfsmount *collect_mounts(const struct path *path)
2320 {
2321 	struct mount *tree;
2322 	namespace_lock();
2323 	if (!check_mnt(real_mount(path->mnt)))
2324 		tree = ERR_PTR(-EINVAL);
2325 	else
2326 		tree = copy_tree(real_mount(path->mnt), path->dentry,
2327 				 CL_COPY_ALL | CL_PRIVATE);
2328 	namespace_unlock();
2329 	if (IS_ERR(tree))
2330 		return ERR_CAST(tree);
2331 	return &tree->mnt;
2332 }
2333 
2334 static void free_mnt_ns(struct mnt_namespace *);
2335 static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *, bool);
2336 
2337 void dissolve_on_fput(struct vfsmount *mnt)
2338 {
2339 	struct mnt_namespace *ns;
2340 	namespace_lock();
2341 	lock_mount_hash();
2342 	ns = real_mount(mnt)->mnt_ns;
2343 	if (ns) {
2344 		if (is_anon_ns(ns))
2345 			umount_tree(real_mount(mnt), UMOUNT_CONNECTED);
2346 		else
2347 			ns = NULL;
2348 	}
2349 	unlock_mount_hash();
2350 	namespace_unlock();
2351 	if (ns)
2352 		free_mnt_ns(ns);
2353 }
2354 
2355 void drop_collected_mounts(struct vfsmount *mnt)
2356 {
2357 	namespace_lock();
2358 	lock_mount_hash();
2359 	umount_tree(real_mount(mnt), 0);
2360 	unlock_mount_hash();
2361 	namespace_unlock();
2362 }
2363 
2364 bool has_locked_children(struct mount *mnt, struct dentry *dentry)
2365 {
2366 	struct mount *child;
2367 
2368 	list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
2369 		if (!is_subdir(child->mnt_mountpoint, dentry))
2370 			continue;
2371 
2372 		if (child->mnt.mnt_flags & MNT_LOCKED)
2373 			return true;
2374 	}
2375 	return false;
2376 }
2377 
2378 /*
2379  * Check that there aren't references to earlier/same mount namespaces in the
2380  * specified subtree.  Such references can act as pins for mount namespaces
2381  * that aren't checked by the mount-cycle checking code, thereby allowing
2382  * cycles to be made.
2383  */
2384 static bool check_for_nsfs_mounts(struct mount *subtree)
2385 {
2386 	struct mount *p;
2387 	bool ret = false;
2388 
2389 	lock_mount_hash();
2390 	for (p = subtree; p; p = next_mnt(p, subtree))
2391 		if (mnt_ns_loop(p->mnt.mnt_root))
2392 			goto out;
2393 
2394 	ret = true;
2395 out:
2396 	unlock_mount_hash();
2397 	return ret;
2398 }
2399 
2400 /**
2401  * clone_private_mount - create a private clone of a path
2402  * @path: path to clone
2403  *
2404  * This creates a new vfsmount, which will be the clone of @path.  The new mount
2405  * will not be attached anywhere in the namespace and will be private (i.e.
2406  * changes to the originating mount won't be propagated into this).
2407  *
2408  * This assumes caller has called or done the equivalent of may_mount().
2409  *
2410  * Release with mntput().
2411  */
2412 struct vfsmount *clone_private_mount(const struct path *path)
2413 {
2414 	struct mount *old_mnt = real_mount(path->mnt);
2415 	struct mount *new_mnt;
2416 
2417 	scoped_guard(rwsem_read, &namespace_sem)
2418 	if (IS_MNT_UNBINDABLE(old_mnt))
2419 		return ERR_PTR(-EINVAL);
2420 
2421 	if (mnt_has_parent(old_mnt)) {
2422 		if (!check_mnt(old_mnt))
2423 			return ERR_PTR(-EINVAL);
2424 	} else {
2425 		if (!is_mounted(&old_mnt->mnt))
2426 			return ERR_PTR(-EINVAL);
2427 
2428 		/* Make sure this isn't something purely kernel internal. */
2429 		if (!is_anon_ns(old_mnt->mnt_ns))
2430 			return ERR_PTR(-EINVAL);
2431 
2432 		/* Make sure we don't create mount namespace loops. */
2433 		if (!check_for_nsfs_mounts(old_mnt))
2434 			return ERR_PTR(-EINVAL);
2435 	}
2436 
2437 	if (has_locked_children(old_mnt, path->dentry))
2438 		return ERR_PTR(-EINVAL);
2439 
2440 	new_mnt = clone_mnt(old_mnt, path->dentry, CL_PRIVATE);
2441 	if (IS_ERR(new_mnt))
2442 		return ERR_PTR(-EINVAL);
2443 
2444 	/* Longterm mount to be removed by kern_unmount*() */
2445 	new_mnt->mnt_ns = MNT_NS_INTERNAL;
2446 	return &new_mnt->mnt;
2447 }
2448 EXPORT_SYMBOL_GPL(clone_private_mount);
2449 
2450 int iterate_mounts(int (*f)(struct vfsmount *, void *), void *arg,
2451 		   struct vfsmount *root)
2452 {
2453 	struct mount *mnt;
2454 	int res = f(root, arg);
2455 	if (res)
2456 		return res;
2457 	list_for_each_entry(mnt, &real_mount(root)->mnt_list, mnt_list) {
2458 		res = f(&mnt->mnt, arg);
2459 		if (res)
2460 			return res;
2461 	}
2462 	return 0;
2463 }
2464 
2465 static void lock_mnt_tree(struct mount *mnt)
2466 {
2467 	struct mount *p;
2468 
2469 	for (p = mnt; p; p = next_mnt(p, mnt)) {
2470 		int flags = p->mnt.mnt_flags;
2471 		/* Don't allow unprivileged users to change mount flags */
2472 		flags |= MNT_LOCK_ATIME;
2473 
2474 		if (flags & MNT_READONLY)
2475 			flags |= MNT_LOCK_READONLY;
2476 
2477 		if (flags & MNT_NODEV)
2478 			flags |= MNT_LOCK_NODEV;
2479 
2480 		if (flags & MNT_NOSUID)
2481 			flags |= MNT_LOCK_NOSUID;
2482 
2483 		if (flags & MNT_NOEXEC)
2484 			flags |= MNT_LOCK_NOEXEC;
2485 		/* Don't allow unprivileged users to reveal what is under a mount */
2486 		if (list_empty(&p->mnt_expire))
2487 			flags |= MNT_LOCKED;
2488 		p->mnt.mnt_flags = flags;
2489 	}
2490 }
2491 
2492 static void cleanup_group_ids(struct mount *mnt, struct mount *end)
2493 {
2494 	struct mount *p;
2495 
2496 	for (p = mnt; p != end; p = next_mnt(p, mnt)) {
2497 		if (p->mnt_group_id && !IS_MNT_SHARED(p))
2498 			mnt_release_group_id(p);
2499 	}
2500 }
2501 
2502 static int invent_group_ids(struct mount *mnt, bool recurse)
2503 {
2504 	struct mount *p;
2505 
2506 	for (p = mnt; p; p = recurse ? next_mnt(p, mnt) : NULL) {
2507 		if (!p->mnt_group_id && !IS_MNT_SHARED(p)) {
2508 			int err = mnt_alloc_group_id(p);
2509 			if (err) {
2510 				cleanup_group_ids(mnt, p);
2511 				return err;
2512 			}
2513 		}
2514 	}
2515 
2516 	return 0;
2517 }
2518 
2519 int count_mounts(struct mnt_namespace *ns, struct mount *mnt)
2520 {
2521 	unsigned int max = READ_ONCE(sysctl_mount_max);
2522 	unsigned int mounts = 0;
2523 	struct mount *p;
2524 
2525 	if (ns->nr_mounts >= max)
2526 		return -ENOSPC;
2527 	max -= ns->nr_mounts;
2528 	if (ns->pending_mounts >= max)
2529 		return -ENOSPC;
2530 	max -= ns->pending_mounts;
2531 
2532 	for (p = mnt; p; p = next_mnt(p, mnt))
2533 		mounts++;
2534 
2535 	if (mounts > max)
2536 		return -ENOSPC;
2537 
2538 	ns->pending_mounts += mounts;
2539 	return 0;
2540 }
2541 
2542 enum mnt_tree_flags_t {
2543 	MNT_TREE_MOVE = BIT(0),
2544 	MNT_TREE_BENEATH = BIT(1),
2545 };
2546 
2547 /**
2548  * attach_recursive_mnt - attach a source mount tree
2549  * @source_mnt: mount tree to be attached
2550  * @top_mnt:    mount that @source_mnt will be mounted on or mounted beneath
2551  * @dest_mp:    the mountpoint @source_mnt will be mounted at
2552  * @flags:      modify how @source_mnt is supposed to be attached
2553  *
2554  *  NOTE: in the table below explains the semantics when a source mount
2555  *  of a given type is attached to a destination mount of a given type.
2556  * ---------------------------------------------------------------------------
2557  * |         BIND MOUNT OPERATION                                            |
2558  * |**************************************************************************
2559  * | source-->| shared        |       private  |       slave    | unbindable |
2560  * | dest     |               |                |                |            |
2561  * |   |      |               |                |                |            |
2562  * |   v      |               |                |                |            |
2563  * |**************************************************************************
2564  * |  shared  | shared (++)   |     shared (+) |     shared(+++)|  invalid   |
2565  * |          |               |                |                |            |
2566  * |non-shared| shared (+)    |      private   |      slave (*) |  invalid   |
2567  * ***************************************************************************
2568  * A bind operation clones the source mount and mounts the clone on the
2569  * destination mount.
2570  *
2571  * (++)  the cloned mount is propagated to all the mounts in the propagation
2572  * 	 tree of the destination mount and the cloned mount is added to
2573  * 	 the peer group of the source mount.
2574  * (+)   the cloned mount is created under the destination mount and is marked
2575  *       as shared. The cloned mount is added to the peer group of the source
2576  *       mount.
2577  * (+++) the mount is propagated to all the mounts in the propagation tree
2578  *       of the destination mount and the cloned mount is made slave
2579  *       of the same master as that of the source mount. The cloned mount
2580  *       is marked as 'shared and slave'.
2581  * (*)   the cloned mount is made a slave of the same master as that of the
2582  * 	 source mount.
2583  *
2584  * ---------------------------------------------------------------------------
2585  * |         		MOVE MOUNT OPERATION                                 |
2586  * |**************************************************************************
2587  * | source-->| shared        |       private  |       slave    | unbindable |
2588  * | dest     |               |                |                |            |
2589  * |   |      |               |                |                |            |
2590  * |   v      |               |                |                |            |
2591  * |**************************************************************************
2592  * |  shared  | shared (+)    |     shared (+) |    shared(+++) |  invalid   |
2593  * |          |               |                |                |            |
2594  * |non-shared| shared (+*)   |      private   |    slave (*)   | unbindable |
2595  * ***************************************************************************
2596  *
2597  * (+)  the mount is moved to the destination. And is then propagated to
2598  * 	all the mounts in the propagation tree of the destination mount.
2599  * (+*)  the mount is moved to the destination.
2600  * (+++)  the mount is moved to the destination and is then propagated to
2601  * 	all the mounts belonging to the destination mount's propagation tree.
2602  * 	the mount is marked as 'shared and slave'.
2603  * (*)	the mount continues to be a slave at the new location.
2604  *
2605  * if the source mount is a tree, the operations explained above is
2606  * applied to each mount in the tree.
2607  * Must be called without spinlocks held, since this function can sleep
2608  * in allocations.
2609  *
2610  * Context: The function expects namespace_lock() to be held.
2611  * Return: If @source_mnt was successfully attached 0 is returned.
2612  *         Otherwise a negative error code is returned.
2613  */
2614 static int attach_recursive_mnt(struct mount *source_mnt,
2615 				struct mount *top_mnt,
2616 				struct mountpoint *dest_mp,
2617 				enum mnt_tree_flags_t flags)
2618 {
2619 	struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;
2620 	HLIST_HEAD(tree_list);
2621 	struct mnt_namespace *ns = top_mnt->mnt_ns;
2622 	struct mountpoint *smp;
2623 	struct mount *child, *dest_mnt, *p;
2624 	struct hlist_node *n;
2625 	int err = 0;
2626 	bool moving = flags & MNT_TREE_MOVE, beneath = flags & MNT_TREE_BENEATH;
2627 
2628 	/*
2629 	 * Preallocate a mountpoint in case the new mounts need to be
2630 	 * mounted beneath mounts on the same mountpoint.
2631 	 */
2632 	smp = get_mountpoint(source_mnt->mnt.mnt_root);
2633 	if (IS_ERR(smp))
2634 		return PTR_ERR(smp);
2635 
2636 	/* Is there space to add these mounts to the mount namespace? */
2637 	if (!moving) {
2638 		err = count_mounts(ns, source_mnt);
2639 		if (err)
2640 			goto out;
2641 	}
2642 
2643 	if (beneath)
2644 		dest_mnt = top_mnt->mnt_parent;
2645 	else
2646 		dest_mnt = top_mnt;
2647 
2648 	if (IS_MNT_SHARED(dest_mnt)) {
2649 		err = invent_group_ids(source_mnt, true);
2650 		if (err)
2651 			goto out;
2652 		err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list);
2653 	}
2654 	lock_mount_hash();
2655 	if (err)
2656 		goto out_cleanup_ids;
2657 
2658 	if (IS_MNT_SHARED(dest_mnt)) {
2659 		for (p = source_mnt; p; p = next_mnt(p, source_mnt))
2660 			set_mnt_shared(p);
2661 	}
2662 
2663 	if (moving) {
2664 		if (beneath)
2665 			dest_mp = smp;
2666 		unhash_mnt(source_mnt);
2667 		attach_mnt(source_mnt, top_mnt, dest_mp, beneath);
2668 		mnt_notify_add(source_mnt);
2669 		touch_mnt_namespace(source_mnt->mnt_ns);
2670 	} else {
2671 		if (source_mnt->mnt_ns) {
2672 			LIST_HEAD(head);
2673 
2674 			/* move from anon - the caller will destroy */
2675 			for (p = source_mnt; p; p = next_mnt(p, source_mnt))
2676 				move_from_ns(p, &head);
2677 			list_del_init(&head);
2678 		}
2679 		if (beneath)
2680 			mnt_set_mountpoint_beneath(source_mnt, top_mnt, smp);
2681 		else
2682 			mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt);
2683 		commit_tree(source_mnt);
2684 	}
2685 
2686 	hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) {
2687 		struct mount *q;
2688 		hlist_del_init(&child->mnt_hash);
2689 		q = __lookup_mnt(&child->mnt_parent->mnt,
2690 				 child->mnt_mountpoint);
2691 		if (q)
2692 			mnt_change_mountpoint(child, smp, q);
2693 		/* Notice when we are propagating across user namespaces */
2694 		if (child->mnt_parent->mnt_ns->user_ns != user_ns)
2695 			lock_mnt_tree(child);
2696 		child->mnt.mnt_flags &= ~MNT_LOCKED;
2697 		commit_tree(child);
2698 	}
2699 	put_mountpoint(smp);
2700 	unlock_mount_hash();
2701 
2702 	return 0;
2703 
2704  out_cleanup_ids:
2705 	while (!hlist_empty(&tree_list)) {
2706 		child = hlist_entry(tree_list.first, struct mount, mnt_hash);
2707 		child->mnt_parent->mnt_ns->pending_mounts = 0;
2708 		umount_tree(child, UMOUNT_SYNC);
2709 	}
2710 	unlock_mount_hash();
2711 	cleanup_group_ids(source_mnt, NULL);
2712  out:
2713 	ns->pending_mounts = 0;
2714 
2715 	read_seqlock_excl(&mount_lock);
2716 	put_mountpoint(smp);
2717 	read_sequnlock_excl(&mount_lock);
2718 
2719 	return err;
2720 }
2721 
2722 /**
2723  * do_lock_mount - lock mount and mountpoint
2724  * @path:    target path
2725  * @beneath: whether the intention is to mount beneath @path
2726  *
2727  * Follow the mount stack on @path until the top mount @mnt is found. If
2728  * the initial @path->{mnt,dentry} is a mountpoint lookup the first
2729  * mount stacked on top of it. Then simply follow @{mnt,mnt->mnt_root}
2730  * until nothing is stacked on top of it anymore.
2731  *
2732  * Acquire the inode_lock() on the top mount's ->mnt_root to protect
2733  * against concurrent removal of the new mountpoint from another mount
2734  * namespace.
2735  *
2736  * If @beneath is requested, acquire inode_lock() on @mnt's mountpoint
2737  * @mp on @mnt->mnt_parent must be acquired. This protects against a
2738  * concurrent unlink of @mp->mnt_dentry from another mount namespace
2739  * where @mnt doesn't have a child mount mounted @mp. A concurrent
2740  * removal of @mnt->mnt_root doesn't matter as nothing will be mounted
2741  * on top of it for @beneath.
2742  *
2743  * In addition, @beneath needs to make sure that @mnt hasn't been
2744  * unmounted or moved from its current mountpoint in between dropping
2745  * @mount_lock and acquiring @namespace_sem. For the !@beneath case @mnt
2746  * being unmounted would be detected later by e.g., calling
2747  * check_mnt(mnt) in the function it's called from. For the @beneath
2748  * case however, it's useful to detect it directly in do_lock_mount().
2749  * If @mnt hasn't been unmounted then @mnt->mnt_mountpoint still points
2750  * to @mnt->mnt_mp->m_dentry. But if @mnt has been unmounted it will
2751  * point to @mnt->mnt_root and @mnt->mnt_mp will be NULL.
2752  *
2753  * Return: Either the target mountpoint on the top mount or the top
2754  *         mount's mountpoint.
2755  */
2756 static struct mountpoint *do_lock_mount(struct path *path, bool beneath)
2757 {
2758 	struct vfsmount *mnt = path->mnt;
2759 	struct dentry *dentry;
2760 	struct mountpoint *mp = ERR_PTR(-ENOENT);
2761 
2762 	for (;;) {
2763 		struct mount *m;
2764 
2765 		if (beneath) {
2766 			m = real_mount(mnt);
2767 			read_seqlock_excl(&mount_lock);
2768 			dentry = dget(m->mnt_mountpoint);
2769 			read_sequnlock_excl(&mount_lock);
2770 		} else {
2771 			dentry = path->dentry;
2772 		}
2773 
2774 		inode_lock(dentry->d_inode);
2775 		if (unlikely(cant_mount(dentry))) {
2776 			inode_unlock(dentry->d_inode);
2777 			goto out;
2778 		}
2779 
2780 		namespace_lock();
2781 
2782 		if (beneath && (!is_mounted(mnt) || m->mnt_mountpoint != dentry)) {
2783 			namespace_unlock();
2784 			inode_unlock(dentry->d_inode);
2785 			goto out;
2786 		}
2787 
2788 		mnt = lookup_mnt(path);
2789 		if (likely(!mnt))
2790 			break;
2791 
2792 		namespace_unlock();
2793 		inode_unlock(dentry->d_inode);
2794 		if (beneath)
2795 			dput(dentry);
2796 		path_put(path);
2797 		path->mnt = mnt;
2798 		path->dentry = dget(mnt->mnt_root);
2799 	}
2800 
2801 	mp = get_mountpoint(dentry);
2802 	if (IS_ERR(mp)) {
2803 		namespace_unlock();
2804 		inode_unlock(dentry->d_inode);
2805 	}
2806 
2807 out:
2808 	if (beneath)
2809 		dput(dentry);
2810 
2811 	return mp;
2812 }
2813 
2814 static inline struct mountpoint *lock_mount(struct path *path)
2815 {
2816 	return do_lock_mount(path, false);
2817 }
2818 
2819 static void unlock_mount(struct mountpoint *where)
2820 {
2821 	struct dentry *dentry = where->m_dentry;
2822 
2823 	read_seqlock_excl(&mount_lock);
2824 	put_mountpoint(where);
2825 	read_sequnlock_excl(&mount_lock);
2826 
2827 	namespace_unlock();
2828 	inode_unlock(dentry->d_inode);
2829 }
2830 
2831 static int graft_tree(struct mount *mnt, struct mount *p, struct mountpoint *mp)
2832 {
2833 	if (mnt->mnt.mnt_sb->s_flags & SB_NOUSER)
2834 		return -EINVAL;
2835 
2836 	if (d_is_dir(mp->m_dentry) !=
2837 	      d_is_dir(mnt->mnt.mnt_root))
2838 		return -ENOTDIR;
2839 
2840 	return attach_recursive_mnt(mnt, p, mp, 0);
2841 }
2842 
2843 /*
2844  * Sanity check the flags to change_mnt_propagation.
2845  */
2846 
2847 static int flags_to_propagation_type(int ms_flags)
2848 {
2849 	int type = ms_flags & ~(MS_REC | MS_SILENT);
2850 
2851 	/* Fail if any non-propagation flags are set */
2852 	if (type & ~(MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
2853 		return 0;
2854 	/* Only one propagation flag should be set */
2855 	if (!is_power_of_2(type))
2856 		return 0;
2857 	return type;
2858 }
2859 
2860 /*
2861  * recursively change the type of the mountpoint.
2862  */
2863 static int do_change_type(struct path *path, int ms_flags)
2864 {
2865 	struct mount *m;
2866 	struct mount *mnt = real_mount(path->mnt);
2867 	int recurse = ms_flags & MS_REC;
2868 	int type;
2869 	int err = 0;
2870 
2871 	if (!path_mounted(path))
2872 		return -EINVAL;
2873 
2874 	type = flags_to_propagation_type(ms_flags);
2875 	if (!type)
2876 		return -EINVAL;
2877 
2878 	namespace_lock();
2879 	if (type == MS_SHARED) {
2880 		err = invent_group_ids(mnt, recurse);
2881 		if (err)
2882 			goto out_unlock;
2883 	}
2884 
2885 	lock_mount_hash();
2886 	for (m = mnt; m; m = (recurse ? next_mnt(m, mnt) : NULL))
2887 		change_mnt_propagation(m, type);
2888 	unlock_mount_hash();
2889 
2890  out_unlock:
2891 	namespace_unlock();
2892 	return err;
2893 }
2894 
2895 static struct mount *__do_loopback(struct path *old_path, int recurse)
2896 {
2897 	struct mount *mnt = ERR_PTR(-EINVAL), *old = real_mount(old_path->mnt);
2898 
2899 	if (IS_MNT_UNBINDABLE(old))
2900 		return mnt;
2901 
2902 	if (!check_mnt(old)) {
2903 		const struct dentry_operations *d_op = old_path->dentry->d_op;
2904 
2905 		if (d_op != &ns_dentry_operations &&
2906 		    d_op != &pidfs_dentry_operations)
2907 			return mnt;
2908 	}
2909 
2910 	if (!recurse && has_locked_children(old, old_path->dentry))
2911 		return mnt;
2912 
2913 	if (recurse)
2914 		mnt = copy_tree(old, old_path->dentry, CL_COPY_MNT_NS_FILE);
2915 	else
2916 		mnt = clone_mnt(old, old_path->dentry, 0);
2917 
2918 	if (!IS_ERR(mnt))
2919 		mnt->mnt.mnt_flags &= ~MNT_LOCKED;
2920 
2921 	return mnt;
2922 }
2923 
2924 /*
2925  * do loopback mount.
2926  */
2927 static int do_loopback(struct path *path, const char *old_name,
2928 				int recurse)
2929 {
2930 	struct path old_path;
2931 	struct mount *mnt = NULL, *parent;
2932 	struct mountpoint *mp;
2933 	int err;
2934 	if (!old_name || !*old_name)
2935 		return -EINVAL;
2936 	err = kern_path(old_name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &old_path);
2937 	if (err)
2938 		return err;
2939 
2940 	err = -EINVAL;
2941 	if (mnt_ns_loop(old_path.dentry))
2942 		goto out;
2943 
2944 	mp = lock_mount(path);
2945 	if (IS_ERR(mp)) {
2946 		err = PTR_ERR(mp);
2947 		goto out;
2948 	}
2949 
2950 	parent = real_mount(path->mnt);
2951 	if (!check_mnt(parent))
2952 		goto out2;
2953 
2954 	mnt = __do_loopback(&old_path, recurse);
2955 	if (IS_ERR(mnt)) {
2956 		err = PTR_ERR(mnt);
2957 		goto out2;
2958 	}
2959 
2960 	err = graft_tree(mnt, parent, mp);
2961 	if (err) {
2962 		lock_mount_hash();
2963 		umount_tree(mnt, UMOUNT_SYNC);
2964 		unlock_mount_hash();
2965 	}
2966 out2:
2967 	unlock_mount(mp);
2968 out:
2969 	path_put(&old_path);
2970 	return err;
2971 }
2972 
2973 static struct file *open_detached_copy(struct path *path, bool recursive)
2974 {
2975 	struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;
2976 	struct mnt_namespace *ns = alloc_mnt_ns(user_ns, true);
2977 	struct mount *mnt, *p;
2978 	struct file *file;
2979 
2980 	if (IS_ERR(ns))
2981 		return ERR_CAST(ns);
2982 
2983 	namespace_lock();
2984 	mnt = __do_loopback(path, recursive);
2985 	if (IS_ERR(mnt)) {
2986 		namespace_unlock();
2987 		free_mnt_ns(ns);
2988 		return ERR_CAST(mnt);
2989 	}
2990 
2991 	lock_mount_hash();
2992 	for (p = mnt; p; p = next_mnt(p, mnt)) {
2993 		mnt_add_to_ns(ns, p);
2994 		ns->nr_mounts++;
2995 	}
2996 	ns->root = mnt;
2997 	mntget(&mnt->mnt);
2998 	unlock_mount_hash();
2999 	namespace_unlock();
3000 
3001 	mntput(path->mnt);
3002 	path->mnt = &mnt->mnt;
3003 	file = dentry_open(path, O_PATH, current_cred());
3004 	if (IS_ERR(file))
3005 		dissolve_on_fput(path->mnt);
3006 	else
3007 		file->f_mode |= FMODE_NEED_UNMOUNT;
3008 	return file;
3009 }
3010 
3011 static struct file *vfs_open_tree(int dfd, const char __user *filename, unsigned int flags)
3012 {
3013 	int ret;
3014 	struct path path __free(path_put) = {};
3015 	int lookup_flags = LOOKUP_AUTOMOUNT | LOOKUP_FOLLOW;
3016 	bool detached = flags & OPEN_TREE_CLONE;
3017 
3018 	BUILD_BUG_ON(OPEN_TREE_CLOEXEC != O_CLOEXEC);
3019 
3020 	if (flags & ~(AT_EMPTY_PATH | AT_NO_AUTOMOUNT | AT_RECURSIVE |
3021 		      AT_SYMLINK_NOFOLLOW | OPEN_TREE_CLONE |
3022 		      OPEN_TREE_CLOEXEC))
3023 		return ERR_PTR(-EINVAL);
3024 
3025 	if ((flags & (AT_RECURSIVE | OPEN_TREE_CLONE)) == AT_RECURSIVE)
3026 		return ERR_PTR(-EINVAL);
3027 
3028 	if (flags & AT_NO_AUTOMOUNT)
3029 		lookup_flags &= ~LOOKUP_AUTOMOUNT;
3030 	if (flags & AT_SYMLINK_NOFOLLOW)
3031 		lookup_flags &= ~LOOKUP_FOLLOW;
3032 	if (flags & AT_EMPTY_PATH)
3033 		lookup_flags |= LOOKUP_EMPTY;
3034 
3035 	if (detached && !may_mount())
3036 		return ERR_PTR(-EPERM);
3037 
3038 	ret = user_path_at(dfd, filename, lookup_flags, &path);
3039 	if (unlikely(ret))
3040 		return ERR_PTR(ret);
3041 
3042 	if (detached)
3043 		return open_detached_copy(&path, flags & AT_RECURSIVE);
3044 
3045 	return dentry_open(&path, O_PATH, current_cred());
3046 }
3047 
3048 SYSCALL_DEFINE3(open_tree, int, dfd, const char __user *, filename, unsigned, flags)
3049 {
3050 	int fd;
3051 	struct file *file __free(fput) = NULL;
3052 
3053 	file = vfs_open_tree(dfd, filename, flags);
3054 	if (IS_ERR(file))
3055 		return PTR_ERR(file);
3056 
3057 	fd = get_unused_fd_flags(flags & O_CLOEXEC);
3058 	if (fd < 0)
3059 		return fd;
3060 
3061 	fd_install(fd, no_free_ptr(file));
3062 	return fd;
3063 }
3064 
3065 /*
3066  * Don't allow locked mount flags to be cleared.
3067  *
3068  * No locks need to be held here while testing the various MNT_LOCK
3069  * flags because those flags can never be cleared once they are set.
3070  */
3071 static bool can_change_locked_flags(struct mount *mnt, unsigned int mnt_flags)
3072 {
3073 	unsigned int fl = mnt->mnt.mnt_flags;
3074 
3075 	if ((fl & MNT_LOCK_READONLY) &&
3076 	    !(mnt_flags & MNT_READONLY))
3077 		return false;
3078 
3079 	if ((fl & MNT_LOCK_NODEV) &&
3080 	    !(mnt_flags & MNT_NODEV))
3081 		return false;
3082 
3083 	if ((fl & MNT_LOCK_NOSUID) &&
3084 	    !(mnt_flags & MNT_NOSUID))
3085 		return false;
3086 
3087 	if ((fl & MNT_LOCK_NOEXEC) &&
3088 	    !(mnt_flags & MNT_NOEXEC))
3089 		return false;
3090 
3091 	if ((fl & MNT_LOCK_ATIME) &&
3092 	    ((fl & MNT_ATIME_MASK) != (mnt_flags & MNT_ATIME_MASK)))
3093 		return false;
3094 
3095 	return true;
3096 }
3097 
3098 static int change_mount_ro_state(struct mount *mnt, unsigned int mnt_flags)
3099 {
3100 	bool readonly_request = (mnt_flags & MNT_READONLY);
3101 
3102 	if (readonly_request == __mnt_is_readonly(&mnt->mnt))
3103 		return 0;
3104 
3105 	if (readonly_request)
3106 		return mnt_make_readonly(mnt);
3107 
3108 	mnt->mnt.mnt_flags &= ~MNT_READONLY;
3109 	return 0;
3110 }
3111 
3112 static void set_mount_attributes(struct mount *mnt, unsigned int mnt_flags)
3113 {
3114 	mnt_flags |= mnt->mnt.mnt_flags & ~MNT_USER_SETTABLE_MASK;
3115 	mnt->mnt.mnt_flags = mnt_flags;
3116 	touch_mnt_namespace(mnt->mnt_ns);
3117 }
3118 
3119 static void mnt_warn_timestamp_expiry(struct path *mountpoint, struct vfsmount *mnt)
3120 {
3121 	struct super_block *sb = mnt->mnt_sb;
3122 
3123 	if (!__mnt_is_readonly(mnt) &&
3124 	   (!(sb->s_iflags & SB_I_TS_EXPIRY_WARNED)) &&
3125 	   (ktime_get_real_seconds() + TIME_UPTIME_SEC_MAX > sb->s_time_max)) {
3126 		char *buf, *mntpath;
3127 
3128 		buf = (char *)__get_free_page(GFP_KERNEL);
3129 		if (buf)
3130 			mntpath = d_path(mountpoint, buf, PAGE_SIZE);
3131 		else
3132 			mntpath = ERR_PTR(-ENOMEM);
3133 		if (IS_ERR(mntpath))
3134 			mntpath = "(unknown)";
3135 
3136 		pr_warn("%s filesystem being %s at %s supports timestamps until %ptTd (0x%llx)\n",
3137 			sb->s_type->name,
3138 			is_mounted(mnt) ? "remounted" : "mounted",
3139 			mntpath, &sb->s_time_max,
3140 			(unsigned long long)sb->s_time_max);
3141 
3142 		sb->s_iflags |= SB_I_TS_EXPIRY_WARNED;
3143 		if (buf)
3144 			free_page((unsigned long)buf);
3145 	}
3146 }
3147 
3148 /*
3149  * Handle reconfiguration of the mountpoint only without alteration of the
3150  * superblock it refers to.  This is triggered by specifying MS_REMOUNT|MS_BIND
3151  * to mount(2).
3152  */
3153 static int do_reconfigure_mnt(struct path *path, unsigned int mnt_flags)
3154 {
3155 	struct super_block *sb = path->mnt->mnt_sb;
3156 	struct mount *mnt = real_mount(path->mnt);
3157 	int ret;
3158 
3159 	if (!check_mnt(mnt))
3160 		return -EINVAL;
3161 
3162 	if (!path_mounted(path))
3163 		return -EINVAL;
3164 
3165 	if (!can_change_locked_flags(mnt, mnt_flags))
3166 		return -EPERM;
3167 
3168 	/*
3169 	 * We're only checking whether the superblock is read-only not
3170 	 * changing it, so only take down_read(&sb->s_umount).
3171 	 */
3172 	down_read(&sb->s_umount);
3173 	lock_mount_hash();
3174 	ret = change_mount_ro_state(mnt, mnt_flags);
3175 	if (ret == 0)
3176 		set_mount_attributes(mnt, mnt_flags);
3177 	unlock_mount_hash();
3178 	up_read(&sb->s_umount);
3179 
3180 	mnt_warn_timestamp_expiry(path, &mnt->mnt);
3181 
3182 	return ret;
3183 }
3184 
3185 /*
3186  * change filesystem flags. dir should be a physical root of filesystem.
3187  * If you've mounted a non-root directory somewhere and want to do remount
3188  * on it - tough luck.
3189  */
3190 static int do_remount(struct path *path, int ms_flags, int sb_flags,
3191 		      int mnt_flags, void *data)
3192 {
3193 	int err;
3194 	struct super_block *sb = path->mnt->mnt_sb;
3195 	struct mount *mnt = real_mount(path->mnt);
3196 	struct fs_context *fc;
3197 
3198 	if (!check_mnt(mnt))
3199 		return -EINVAL;
3200 
3201 	if (!path_mounted(path))
3202 		return -EINVAL;
3203 
3204 	if (!can_change_locked_flags(mnt, mnt_flags))
3205 		return -EPERM;
3206 
3207 	fc = fs_context_for_reconfigure(path->dentry, sb_flags, MS_RMT_MASK);
3208 	if (IS_ERR(fc))
3209 		return PTR_ERR(fc);
3210 
3211 	/*
3212 	 * Indicate to the filesystem that the remount request is coming
3213 	 * from the legacy mount system call.
3214 	 */
3215 	fc->oldapi = true;
3216 
3217 	err = parse_monolithic_mount_data(fc, data);
3218 	if (!err) {
3219 		down_write(&sb->s_umount);
3220 		err = -EPERM;
3221 		if (ns_capable(sb->s_user_ns, CAP_SYS_ADMIN)) {
3222 			err = reconfigure_super(fc);
3223 			if (!err) {
3224 				lock_mount_hash();
3225 				set_mount_attributes(mnt, mnt_flags);
3226 				unlock_mount_hash();
3227 			}
3228 		}
3229 		up_write(&sb->s_umount);
3230 	}
3231 
3232 	mnt_warn_timestamp_expiry(path, &mnt->mnt);
3233 
3234 	put_fs_context(fc);
3235 	return err;
3236 }
3237 
3238 static inline int tree_contains_unbindable(struct mount *mnt)
3239 {
3240 	struct mount *p;
3241 	for (p = mnt; p; p = next_mnt(p, mnt)) {
3242 		if (IS_MNT_UNBINDABLE(p))
3243 			return 1;
3244 	}
3245 	return 0;
3246 }
3247 
3248 static int do_set_group(struct path *from_path, struct path *to_path)
3249 {
3250 	struct mount *from, *to;
3251 	int err;
3252 
3253 	from = real_mount(from_path->mnt);
3254 	to = real_mount(to_path->mnt);
3255 
3256 	namespace_lock();
3257 
3258 	err = -EINVAL;
3259 	/* To and From must be mounted */
3260 	if (!is_mounted(&from->mnt))
3261 		goto out;
3262 	if (!is_mounted(&to->mnt))
3263 		goto out;
3264 
3265 	err = -EPERM;
3266 	/* We should be allowed to modify mount namespaces of both mounts */
3267 	if (!ns_capable(from->mnt_ns->user_ns, CAP_SYS_ADMIN))
3268 		goto out;
3269 	if (!ns_capable(to->mnt_ns->user_ns, CAP_SYS_ADMIN))
3270 		goto out;
3271 
3272 	err = -EINVAL;
3273 	/* To and From paths should be mount roots */
3274 	if (!path_mounted(from_path))
3275 		goto out;
3276 	if (!path_mounted(to_path))
3277 		goto out;
3278 
3279 	/* Setting sharing groups is only allowed across same superblock */
3280 	if (from->mnt.mnt_sb != to->mnt.mnt_sb)
3281 		goto out;
3282 
3283 	/* From mount root should be wider than To mount root */
3284 	if (!is_subdir(to->mnt.mnt_root, from->mnt.mnt_root))
3285 		goto out;
3286 
3287 	/* From mount should not have locked children in place of To's root */
3288 	if (has_locked_children(from, to->mnt.mnt_root))
3289 		goto out;
3290 
3291 	/* Setting sharing groups is only allowed on private mounts */
3292 	if (IS_MNT_SHARED(to) || IS_MNT_SLAVE(to))
3293 		goto out;
3294 
3295 	/* From should not be private */
3296 	if (!IS_MNT_SHARED(from) && !IS_MNT_SLAVE(from))
3297 		goto out;
3298 
3299 	if (IS_MNT_SLAVE(from)) {
3300 		struct mount *m = from->mnt_master;
3301 
3302 		list_add(&to->mnt_slave, &m->mnt_slave_list);
3303 		to->mnt_master = m;
3304 	}
3305 
3306 	if (IS_MNT_SHARED(from)) {
3307 		to->mnt_group_id = from->mnt_group_id;
3308 		list_add(&to->mnt_share, &from->mnt_share);
3309 		lock_mount_hash();
3310 		set_mnt_shared(to);
3311 		unlock_mount_hash();
3312 	}
3313 
3314 	err = 0;
3315 out:
3316 	namespace_unlock();
3317 	return err;
3318 }
3319 
3320 /**
3321  * path_overmounted - check if path is overmounted
3322  * @path: path to check
3323  *
3324  * Check if path is overmounted, i.e., if there's a mount on top of
3325  * @path->mnt with @path->dentry as mountpoint.
3326  *
3327  * Context: This function expects namespace_lock() to be held.
3328  * Return: If path is overmounted true is returned, false if not.
3329  */
3330 static inline bool path_overmounted(const struct path *path)
3331 {
3332 	rcu_read_lock();
3333 	if (unlikely(__lookup_mnt(path->mnt, path->dentry))) {
3334 		rcu_read_unlock();
3335 		return true;
3336 	}
3337 	rcu_read_unlock();
3338 	return false;
3339 }
3340 
3341 /**
3342  * can_move_mount_beneath - check that we can mount beneath the top mount
3343  * @from: mount to mount beneath
3344  * @to:   mount under which to mount
3345  * @mp:   mountpoint of @to
3346  *
3347  * - Make sure that @to->dentry is actually the root of a mount under
3348  *   which we can mount another mount.
3349  * - Make sure that nothing can be mounted beneath the caller's current
3350  *   root or the rootfs of the namespace.
3351  * - Make sure that the caller can unmount the topmost mount ensuring
3352  *   that the caller could reveal the underlying mountpoint.
3353  * - Ensure that nothing has been mounted on top of @from before we
3354  *   grabbed @namespace_sem to avoid creating pointless shadow mounts.
3355  * - Prevent mounting beneath a mount if the propagation relationship
3356  *   between the source mount, parent mount, and top mount would lead to
3357  *   nonsensical mount trees.
3358  *
3359  * Context: This function expects namespace_lock() to be held.
3360  * Return: On success 0, and on error a negative error code is returned.
3361  */
3362 static int can_move_mount_beneath(const struct path *from,
3363 				  const struct path *to,
3364 				  const struct mountpoint *mp)
3365 {
3366 	struct mount *mnt_from = real_mount(from->mnt),
3367 		     *mnt_to = real_mount(to->mnt),
3368 		     *parent_mnt_to = mnt_to->mnt_parent;
3369 
3370 	if (!mnt_has_parent(mnt_to))
3371 		return -EINVAL;
3372 
3373 	if (!path_mounted(to))
3374 		return -EINVAL;
3375 
3376 	if (IS_MNT_LOCKED(mnt_to))
3377 		return -EINVAL;
3378 
3379 	/* Avoid creating shadow mounts during mount propagation. */
3380 	if (path_overmounted(from))
3381 		return -EINVAL;
3382 
3383 	/*
3384 	 * Mounting beneath the rootfs only makes sense when the
3385 	 * semantics of pivot_root(".", ".") are used.
3386 	 */
3387 	if (&mnt_to->mnt == current->fs->root.mnt)
3388 		return -EINVAL;
3389 	if (parent_mnt_to == current->nsproxy->mnt_ns->root)
3390 		return -EINVAL;
3391 
3392 	for (struct mount *p = mnt_from; mnt_has_parent(p); p = p->mnt_parent)
3393 		if (p == mnt_to)
3394 			return -EINVAL;
3395 
3396 	/*
3397 	 * If the parent mount propagates to the child mount this would
3398 	 * mean mounting @mnt_from on @mnt_to->mnt_parent and then
3399 	 * propagating a copy @c of @mnt_from on top of @mnt_to. This
3400 	 * defeats the whole purpose of mounting beneath another mount.
3401 	 */
3402 	if (propagation_would_overmount(parent_mnt_to, mnt_to, mp))
3403 		return -EINVAL;
3404 
3405 	/*
3406 	 * If @mnt_to->mnt_parent propagates to @mnt_from this would
3407 	 * mean propagating a copy @c of @mnt_from on top of @mnt_from.
3408 	 * Afterwards @mnt_from would be mounted on top of
3409 	 * @mnt_to->mnt_parent and @mnt_to would be unmounted from
3410 	 * @mnt->mnt_parent and remounted on @mnt_from. But since @c is
3411 	 * already mounted on @mnt_from, @mnt_to would ultimately be
3412 	 * remounted on top of @c. Afterwards, @mnt_from would be
3413 	 * covered by a copy @c of @mnt_from and @c would be covered by
3414 	 * @mnt_from itself. This defeats the whole purpose of mounting
3415 	 * @mnt_from beneath @mnt_to.
3416 	 */
3417 	if (propagation_would_overmount(parent_mnt_to, mnt_from, mp))
3418 		return -EINVAL;
3419 
3420 	return 0;
3421 }
3422 
3423 static int do_move_mount(struct path *old_path, struct path *new_path,
3424 			 bool beneath)
3425 {
3426 	struct mnt_namespace *ns;
3427 	struct mount *p;
3428 	struct mount *old;
3429 	struct mount *parent;
3430 	struct mountpoint *mp, *old_mp;
3431 	int err;
3432 	bool attached;
3433 	enum mnt_tree_flags_t flags = 0;
3434 
3435 	mp = do_lock_mount(new_path, beneath);
3436 	if (IS_ERR(mp))
3437 		return PTR_ERR(mp);
3438 
3439 	old = real_mount(old_path->mnt);
3440 	p = real_mount(new_path->mnt);
3441 	parent = old->mnt_parent;
3442 	attached = mnt_has_parent(old);
3443 	if (attached)
3444 		flags |= MNT_TREE_MOVE;
3445 	old_mp = old->mnt_mp;
3446 	ns = old->mnt_ns;
3447 
3448 	err = -EINVAL;
3449 	/* The mountpoint must be in our namespace. */
3450 	if (!check_mnt(p))
3451 		goto out;
3452 
3453 	/* The thing moved must be mounted... */
3454 	if (!is_mounted(&old->mnt))
3455 		goto out;
3456 
3457 	/* ... and either ours or the root of anon namespace */
3458 	if (!(attached ? check_mnt(old) : is_anon_ns(ns)))
3459 		goto out;
3460 
3461 	if (old->mnt.mnt_flags & MNT_LOCKED)
3462 		goto out;
3463 
3464 	if (!path_mounted(old_path))
3465 		goto out;
3466 
3467 	if (d_is_dir(new_path->dentry) !=
3468 	    d_is_dir(old_path->dentry))
3469 		goto out;
3470 	/*
3471 	 * Don't move a mount residing in a shared parent.
3472 	 */
3473 	if (attached && IS_MNT_SHARED(parent))
3474 		goto out;
3475 
3476 	if (beneath) {
3477 		err = can_move_mount_beneath(old_path, new_path, mp);
3478 		if (err)
3479 			goto out;
3480 
3481 		err = -EINVAL;
3482 		p = p->mnt_parent;
3483 		flags |= MNT_TREE_BENEATH;
3484 	}
3485 
3486 	/*
3487 	 * Don't move a mount tree containing unbindable mounts to a destination
3488 	 * mount which is shared.
3489 	 */
3490 	if (IS_MNT_SHARED(p) && tree_contains_unbindable(old))
3491 		goto out;
3492 	err = -ELOOP;
3493 	if (!check_for_nsfs_mounts(old))
3494 		goto out;
3495 	for (; mnt_has_parent(p); p = p->mnt_parent)
3496 		if (p == old)
3497 			goto out;
3498 
3499 	err = attach_recursive_mnt(old, real_mount(new_path->mnt), mp, flags);
3500 	if (err)
3501 		goto out;
3502 
3503 	/* if the mount is moved, it should no longer be expire
3504 	 * automatically */
3505 	list_del_init(&old->mnt_expire);
3506 	if (attached)
3507 		put_mountpoint(old_mp);
3508 out:
3509 	unlock_mount(mp);
3510 	if (!err) {
3511 		if (attached)
3512 			mntput_no_expire(parent);
3513 		else
3514 			free_mnt_ns(ns);
3515 	}
3516 	return err;
3517 }
3518 
3519 static int do_move_mount_old(struct path *path, const char *old_name)
3520 {
3521 	struct path old_path;
3522 	int err;
3523 
3524 	if (!old_name || !*old_name)
3525 		return -EINVAL;
3526 
3527 	err = kern_path(old_name, LOOKUP_FOLLOW, &old_path);
3528 	if (err)
3529 		return err;
3530 
3531 	err = do_move_mount(&old_path, path, false);
3532 	path_put(&old_path);
3533 	return err;
3534 }
3535 
3536 /*
3537  * add a mount into a namespace's mount tree
3538  */
3539 static int do_add_mount(struct mount *newmnt, struct mountpoint *mp,
3540 			const struct path *path, int mnt_flags)
3541 {
3542 	struct mount *parent = real_mount(path->mnt);
3543 
3544 	mnt_flags &= ~MNT_INTERNAL_FLAGS;
3545 
3546 	if (unlikely(!check_mnt(parent))) {
3547 		/* that's acceptable only for automounts done in private ns */
3548 		if (!(mnt_flags & MNT_SHRINKABLE))
3549 			return -EINVAL;
3550 		/* ... and for those we'd better have mountpoint still alive */
3551 		if (!parent->mnt_ns)
3552 			return -EINVAL;
3553 	}
3554 
3555 	/* Refuse the same filesystem on the same mount point */
3556 	if (path->mnt->mnt_sb == newmnt->mnt.mnt_sb && path_mounted(path))
3557 		return -EBUSY;
3558 
3559 	if (d_is_symlink(newmnt->mnt.mnt_root))
3560 		return -EINVAL;
3561 
3562 	newmnt->mnt.mnt_flags = mnt_flags;
3563 	return graft_tree(newmnt, parent, mp);
3564 }
3565 
3566 static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags);
3567 
3568 /*
3569  * Create a new mount using a superblock configuration and request it
3570  * be added to the namespace tree.
3571  */
3572 static int do_new_mount_fc(struct fs_context *fc, struct path *mountpoint,
3573 			   unsigned int mnt_flags)
3574 {
3575 	struct vfsmount *mnt;
3576 	struct mountpoint *mp;
3577 	struct super_block *sb = fc->root->d_sb;
3578 	int error;
3579 
3580 	error = security_sb_kern_mount(sb);
3581 	if (!error && mount_too_revealing(sb, &mnt_flags))
3582 		error = -EPERM;
3583 
3584 	if (unlikely(error)) {
3585 		fc_drop_locked(fc);
3586 		return error;
3587 	}
3588 
3589 	up_write(&sb->s_umount);
3590 
3591 	mnt = vfs_create_mount(fc);
3592 	if (IS_ERR(mnt))
3593 		return PTR_ERR(mnt);
3594 
3595 	mnt_warn_timestamp_expiry(mountpoint, mnt);
3596 
3597 	mp = lock_mount(mountpoint);
3598 	if (IS_ERR(mp)) {
3599 		mntput(mnt);
3600 		return PTR_ERR(mp);
3601 	}
3602 	error = do_add_mount(real_mount(mnt), mp, mountpoint, mnt_flags);
3603 	unlock_mount(mp);
3604 	if (error < 0)
3605 		mntput(mnt);
3606 	return error;
3607 }
3608 
3609 /*
3610  * create a new mount for userspace and request it to be added into the
3611  * namespace's tree
3612  */
3613 static int do_new_mount(struct path *path, const char *fstype, int sb_flags,
3614 			int mnt_flags, const char *name, void *data)
3615 {
3616 	struct file_system_type *type;
3617 	struct fs_context *fc;
3618 	const char *subtype = NULL;
3619 	int err = 0;
3620 
3621 	if (!fstype)
3622 		return -EINVAL;
3623 
3624 	type = get_fs_type(fstype);
3625 	if (!type)
3626 		return -ENODEV;
3627 
3628 	if (type->fs_flags & FS_HAS_SUBTYPE) {
3629 		subtype = strchr(fstype, '.');
3630 		if (subtype) {
3631 			subtype++;
3632 			if (!*subtype) {
3633 				put_filesystem(type);
3634 				return -EINVAL;
3635 			}
3636 		}
3637 	}
3638 
3639 	fc = fs_context_for_mount(type, sb_flags);
3640 	put_filesystem(type);
3641 	if (IS_ERR(fc))
3642 		return PTR_ERR(fc);
3643 
3644 	/*
3645 	 * Indicate to the filesystem that the mount request is coming
3646 	 * from the legacy mount system call.
3647 	 */
3648 	fc->oldapi = true;
3649 
3650 	if (subtype)
3651 		err = vfs_parse_fs_string(fc, "subtype",
3652 					  subtype, strlen(subtype));
3653 	if (!err && name)
3654 		err = vfs_parse_fs_string(fc, "source", name, strlen(name));
3655 	if (!err)
3656 		err = parse_monolithic_mount_data(fc, data);
3657 	if (!err && !mount_capable(fc))
3658 		err = -EPERM;
3659 	if (!err)
3660 		err = vfs_get_tree(fc);
3661 	if (!err)
3662 		err = do_new_mount_fc(fc, path, mnt_flags);
3663 
3664 	put_fs_context(fc);
3665 	return err;
3666 }
3667 
3668 int finish_automount(struct vfsmount *m, const struct path *path)
3669 {
3670 	struct dentry *dentry = path->dentry;
3671 	struct mountpoint *mp;
3672 	struct mount *mnt;
3673 	int err;
3674 
3675 	if (!m)
3676 		return 0;
3677 	if (IS_ERR(m))
3678 		return PTR_ERR(m);
3679 
3680 	mnt = real_mount(m);
3681 	/* The new mount record should have at least 2 refs to prevent it being
3682 	 * expired before we get a chance to add it
3683 	 */
3684 	BUG_ON(mnt_get_count(mnt) < 2);
3685 
3686 	if (m->mnt_sb == path->mnt->mnt_sb &&
3687 	    m->mnt_root == dentry) {
3688 		err = -ELOOP;
3689 		goto discard;
3690 	}
3691 
3692 	/*
3693 	 * we don't want to use lock_mount() - in this case finding something
3694 	 * that overmounts our mountpoint to be means "quitely drop what we've
3695 	 * got", not "try to mount it on top".
3696 	 */
3697 	inode_lock(dentry->d_inode);
3698 	namespace_lock();
3699 	if (unlikely(cant_mount(dentry))) {
3700 		err = -ENOENT;
3701 		goto discard_locked;
3702 	}
3703 	if (path_overmounted(path)) {
3704 		err = 0;
3705 		goto discard_locked;
3706 	}
3707 	mp = get_mountpoint(dentry);
3708 	if (IS_ERR(mp)) {
3709 		err = PTR_ERR(mp);
3710 		goto discard_locked;
3711 	}
3712 
3713 	err = do_add_mount(mnt, mp, path, path->mnt->mnt_flags | MNT_SHRINKABLE);
3714 	unlock_mount(mp);
3715 	if (unlikely(err))
3716 		goto discard;
3717 	mntput(m);
3718 	return 0;
3719 
3720 discard_locked:
3721 	namespace_unlock();
3722 	inode_unlock(dentry->d_inode);
3723 discard:
3724 	/* remove m from any expiration list it may be on */
3725 	if (!list_empty(&mnt->mnt_expire)) {
3726 		namespace_lock();
3727 		list_del_init(&mnt->mnt_expire);
3728 		namespace_unlock();
3729 	}
3730 	mntput(m);
3731 	mntput(m);
3732 	return err;
3733 }
3734 
3735 /**
3736  * mnt_set_expiry - Put a mount on an expiration list
3737  * @mnt: The mount to list.
3738  * @expiry_list: The list to add the mount to.
3739  */
3740 void mnt_set_expiry(struct vfsmount *mnt, struct list_head *expiry_list)
3741 {
3742 	namespace_lock();
3743 
3744 	list_add_tail(&real_mount(mnt)->mnt_expire, expiry_list);
3745 
3746 	namespace_unlock();
3747 }
3748 EXPORT_SYMBOL(mnt_set_expiry);
3749 
3750 /*
3751  * process a list of expirable mountpoints with the intent of discarding any
3752  * mountpoints that aren't in use and haven't been touched since last we came
3753  * here
3754  */
3755 void mark_mounts_for_expiry(struct list_head *mounts)
3756 {
3757 	struct mount *mnt, *next;
3758 	LIST_HEAD(graveyard);
3759 
3760 	if (list_empty(mounts))
3761 		return;
3762 
3763 	namespace_lock();
3764 	lock_mount_hash();
3765 
3766 	/* extract from the expiration list every vfsmount that matches the
3767 	 * following criteria:
3768 	 * - only referenced by its parent vfsmount
3769 	 * - still marked for expiry (marked on the last call here; marks are
3770 	 *   cleared by mntput())
3771 	 */
3772 	list_for_each_entry_safe(mnt, next, mounts, mnt_expire) {
3773 		if (!xchg(&mnt->mnt_expiry_mark, 1) ||
3774 			propagate_mount_busy(mnt, 1))
3775 			continue;
3776 		list_move(&mnt->mnt_expire, &graveyard);
3777 	}
3778 	while (!list_empty(&graveyard)) {
3779 		mnt = list_first_entry(&graveyard, struct mount, mnt_expire);
3780 		touch_mnt_namespace(mnt->mnt_ns);
3781 		umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
3782 	}
3783 	unlock_mount_hash();
3784 	namespace_unlock();
3785 }
3786 
3787 EXPORT_SYMBOL_GPL(mark_mounts_for_expiry);
3788 
3789 /*
3790  * Ripoff of 'select_parent()'
3791  *
3792  * search the list of submounts for a given mountpoint, and move any
3793  * shrinkable submounts to the 'graveyard' list.
3794  */
3795 static int select_submounts(struct mount *parent, struct list_head *graveyard)
3796 {
3797 	struct mount *this_parent = parent;
3798 	struct list_head *next;
3799 	int found = 0;
3800 
3801 repeat:
3802 	next = this_parent->mnt_mounts.next;
3803 resume:
3804 	while (next != &this_parent->mnt_mounts) {
3805 		struct list_head *tmp = next;
3806 		struct mount *mnt = list_entry(tmp, struct mount, mnt_child);
3807 
3808 		next = tmp->next;
3809 		if (!(mnt->mnt.mnt_flags & MNT_SHRINKABLE))
3810 			continue;
3811 		/*
3812 		 * Descend a level if the d_mounts list is non-empty.
3813 		 */
3814 		if (!list_empty(&mnt->mnt_mounts)) {
3815 			this_parent = mnt;
3816 			goto repeat;
3817 		}
3818 
3819 		if (!propagate_mount_busy(mnt, 1)) {
3820 			list_move_tail(&mnt->mnt_expire, graveyard);
3821 			found++;
3822 		}
3823 	}
3824 	/*
3825 	 * All done at this level ... ascend and resume the search
3826 	 */
3827 	if (this_parent != parent) {
3828 		next = this_parent->mnt_child.next;
3829 		this_parent = this_parent->mnt_parent;
3830 		goto resume;
3831 	}
3832 	return found;
3833 }
3834 
3835 /*
3836  * process a list of expirable mountpoints with the intent of discarding any
3837  * submounts of a specific parent mountpoint
3838  *
3839  * mount_lock must be held for write
3840  */
3841 static void shrink_submounts(struct mount *mnt)
3842 {
3843 	LIST_HEAD(graveyard);
3844 	struct mount *m;
3845 
3846 	/* extract submounts of 'mountpoint' from the expiration list */
3847 	while (select_submounts(mnt, &graveyard)) {
3848 		while (!list_empty(&graveyard)) {
3849 			m = list_first_entry(&graveyard, struct mount,
3850 						mnt_expire);
3851 			touch_mnt_namespace(m->mnt_ns);
3852 			umount_tree(m, UMOUNT_PROPAGATE|UMOUNT_SYNC);
3853 		}
3854 	}
3855 }
3856 
3857 static void *copy_mount_options(const void __user * data)
3858 {
3859 	char *copy;
3860 	unsigned left, offset;
3861 
3862 	if (!data)
3863 		return NULL;
3864 
3865 	copy = kmalloc(PAGE_SIZE, GFP_KERNEL);
3866 	if (!copy)
3867 		return ERR_PTR(-ENOMEM);
3868 
3869 	left = copy_from_user(copy, data, PAGE_SIZE);
3870 
3871 	/*
3872 	 * Not all architectures have an exact copy_from_user(). Resort to
3873 	 * byte at a time.
3874 	 */
3875 	offset = PAGE_SIZE - left;
3876 	while (left) {
3877 		char c;
3878 		if (get_user(c, (const char __user *)data + offset))
3879 			break;
3880 		copy[offset] = c;
3881 		left--;
3882 		offset++;
3883 	}
3884 
3885 	if (left == PAGE_SIZE) {
3886 		kfree(copy);
3887 		return ERR_PTR(-EFAULT);
3888 	}
3889 
3890 	return copy;
3891 }
3892 
3893 static char *copy_mount_string(const void __user *data)
3894 {
3895 	return data ? strndup_user(data, PATH_MAX) : NULL;
3896 }
3897 
3898 /*
3899  * Flags is a 32-bit value that allows up to 31 non-fs dependent flags to
3900  * be given to the mount() call (ie: read-only, no-dev, no-suid etc).
3901  *
3902  * data is a (void *) that can point to any structure up to
3903  * PAGE_SIZE-1 bytes, which can contain arbitrary fs-dependent
3904  * information (or be NULL).
3905  *
3906  * Pre-0.97 versions of mount() didn't have a flags word.
3907  * When the flags word was introduced its top half was required
3908  * to have the magic value 0xC0ED, and this remained so until 2.4.0-test9.
3909  * Therefore, if this magic number is present, it carries no information
3910  * and must be discarded.
3911  */
3912 int path_mount(const char *dev_name, struct path *path,
3913 		const char *type_page, unsigned long flags, void *data_page)
3914 {
3915 	unsigned int mnt_flags = 0, sb_flags;
3916 	int ret;
3917 
3918 	/* Discard magic */
3919 	if ((flags & MS_MGC_MSK) == MS_MGC_VAL)
3920 		flags &= ~MS_MGC_MSK;
3921 
3922 	/* Basic sanity checks */
3923 	if (data_page)
3924 		((char *)data_page)[PAGE_SIZE - 1] = 0;
3925 
3926 	if (flags & MS_NOUSER)
3927 		return -EINVAL;
3928 
3929 	ret = security_sb_mount(dev_name, path, type_page, flags, data_page);
3930 	if (ret)
3931 		return ret;
3932 	if (!may_mount())
3933 		return -EPERM;
3934 	if (flags & SB_MANDLOCK)
3935 		warn_mandlock();
3936 
3937 	/* Default to relatime unless overriden */
3938 	if (!(flags & MS_NOATIME))
3939 		mnt_flags |= MNT_RELATIME;
3940 
3941 	/* Separate the per-mountpoint flags */
3942 	if (flags & MS_NOSUID)
3943 		mnt_flags |= MNT_NOSUID;
3944 	if (flags & MS_NODEV)
3945 		mnt_flags |= MNT_NODEV;
3946 	if (flags & MS_NOEXEC)
3947 		mnt_flags |= MNT_NOEXEC;
3948 	if (flags & MS_NOATIME)
3949 		mnt_flags |= MNT_NOATIME;
3950 	if (flags & MS_NODIRATIME)
3951 		mnt_flags |= MNT_NODIRATIME;
3952 	if (flags & MS_STRICTATIME)
3953 		mnt_flags &= ~(MNT_RELATIME | MNT_NOATIME);
3954 	if (flags & MS_RDONLY)
3955 		mnt_flags |= MNT_READONLY;
3956 	if (flags & MS_NOSYMFOLLOW)
3957 		mnt_flags |= MNT_NOSYMFOLLOW;
3958 
3959 	/* The default atime for remount is preservation */
3960 	if ((flags & MS_REMOUNT) &&
3961 	    ((flags & (MS_NOATIME | MS_NODIRATIME | MS_RELATIME |
3962 		       MS_STRICTATIME)) == 0)) {
3963 		mnt_flags &= ~MNT_ATIME_MASK;
3964 		mnt_flags |= path->mnt->mnt_flags & MNT_ATIME_MASK;
3965 	}
3966 
3967 	sb_flags = flags & (SB_RDONLY |
3968 			    SB_SYNCHRONOUS |
3969 			    SB_MANDLOCK |
3970 			    SB_DIRSYNC |
3971 			    SB_SILENT |
3972 			    SB_POSIXACL |
3973 			    SB_LAZYTIME |
3974 			    SB_I_VERSION);
3975 
3976 	if ((flags & (MS_REMOUNT | MS_BIND)) == (MS_REMOUNT | MS_BIND))
3977 		return do_reconfigure_mnt(path, mnt_flags);
3978 	if (flags & MS_REMOUNT)
3979 		return do_remount(path, flags, sb_flags, mnt_flags, data_page);
3980 	if (flags & MS_BIND)
3981 		return do_loopback(path, dev_name, flags & MS_REC);
3982 	if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE))
3983 		return do_change_type(path, flags);
3984 	if (flags & MS_MOVE)
3985 		return do_move_mount_old(path, dev_name);
3986 
3987 	return do_new_mount(path, type_page, sb_flags, mnt_flags, dev_name,
3988 			    data_page);
3989 }
3990 
3991 int do_mount(const char *dev_name, const char __user *dir_name,
3992 		const char *type_page, unsigned long flags, void *data_page)
3993 {
3994 	struct path path;
3995 	int ret;
3996 
3997 	ret = user_path_at(AT_FDCWD, dir_name, LOOKUP_FOLLOW, &path);
3998 	if (ret)
3999 		return ret;
4000 	ret = path_mount(dev_name, &path, type_page, flags, data_page);
4001 	path_put(&path);
4002 	return ret;
4003 }
4004 
4005 static struct ucounts *inc_mnt_namespaces(struct user_namespace *ns)
4006 {
4007 	return inc_ucount(ns, current_euid(), UCOUNT_MNT_NAMESPACES);
4008 }
4009 
4010 static void dec_mnt_namespaces(struct ucounts *ucounts)
4011 {
4012 	dec_ucount(ucounts, UCOUNT_MNT_NAMESPACES);
4013 }
4014 
4015 static void free_mnt_ns(struct mnt_namespace *ns)
4016 {
4017 	if (!is_anon_ns(ns))
4018 		ns_free_inum(&ns->ns);
4019 	dec_mnt_namespaces(ns->ucounts);
4020 	mnt_ns_tree_remove(ns);
4021 }
4022 
4023 /*
4024  * Assign a sequence number so we can detect when we attempt to bind
4025  * mount a reference to an older mount namespace into the current
4026  * mount namespace, preventing reference counting loops.  A 64bit
4027  * number incrementing at 10Ghz will take 12,427 years to wrap which
4028  * is effectively never, so we can ignore the possibility.
4029  */
4030 static atomic64_t mnt_ns_seq = ATOMIC64_INIT(1);
4031 
4032 static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns, bool anon)
4033 {
4034 	struct mnt_namespace *new_ns;
4035 	struct ucounts *ucounts;
4036 	int ret;
4037 
4038 	ucounts = inc_mnt_namespaces(user_ns);
4039 	if (!ucounts)
4040 		return ERR_PTR(-ENOSPC);
4041 
4042 	new_ns = kzalloc(sizeof(struct mnt_namespace), GFP_KERNEL_ACCOUNT);
4043 	if (!new_ns) {
4044 		dec_mnt_namespaces(ucounts);
4045 		return ERR_PTR(-ENOMEM);
4046 	}
4047 	if (!anon) {
4048 		ret = ns_alloc_inum(&new_ns->ns);
4049 		if (ret) {
4050 			kfree(new_ns);
4051 			dec_mnt_namespaces(ucounts);
4052 			return ERR_PTR(ret);
4053 		}
4054 	}
4055 	new_ns->ns.ops = &mntns_operations;
4056 	if (!anon)
4057 		new_ns->seq = atomic64_inc_return(&mnt_ns_seq);
4058 	refcount_set(&new_ns->ns.count, 1);
4059 	refcount_set(&new_ns->passive, 1);
4060 	new_ns->mounts = RB_ROOT;
4061 	INIT_LIST_HEAD(&new_ns->mnt_ns_list);
4062 	RB_CLEAR_NODE(&new_ns->mnt_ns_tree_node);
4063 	init_waitqueue_head(&new_ns->poll);
4064 	new_ns->user_ns = get_user_ns(user_ns);
4065 	new_ns->ucounts = ucounts;
4066 	return new_ns;
4067 }
4068 
4069 __latent_entropy
4070 struct mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns,
4071 		struct user_namespace *user_ns, struct fs_struct *new_fs)
4072 {
4073 	struct mnt_namespace *new_ns;
4074 	struct vfsmount *rootmnt = NULL, *pwdmnt = NULL;
4075 	struct mount *p, *q;
4076 	struct mount *old;
4077 	struct mount *new;
4078 	int copy_flags;
4079 
4080 	BUG_ON(!ns);
4081 
4082 	if (likely(!(flags & CLONE_NEWNS))) {
4083 		get_mnt_ns(ns);
4084 		return ns;
4085 	}
4086 
4087 	old = ns->root;
4088 
4089 	new_ns = alloc_mnt_ns(user_ns, false);
4090 	if (IS_ERR(new_ns))
4091 		return new_ns;
4092 
4093 	namespace_lock();
4094 	/* First pass: copy the tree topology */
4095 	copy_flags = CL_COPY_UNBINDABLE | CL_EXPIRE;
4096 	if (user_ns != ns->user_ns)
4097 		copy_flags |= CL_SHARED_TO_SLAVE;
4098 	new = copy_tree(old, old->mnt.mnt_root, copy_flags);
4099 	if (IS_ERR(new)) {
4100 		namespace_unlock();
4101 		ns_free_inum(&new_ns->ns);
4102 		dec_mnt_namespaces(new_ns->ucounts);
4103 		mnt_ns_release(new_ns);
4104 		return ERR_CAST(new);
4105 	}
4106 	if (user_ns != ns->user_ns) {
4107 		lock_mount_hash();
4108 		lock_mnt_tree(new);
4109 		unlock_mount_hash();
4110 	}
4111 	new_ns->root = new;
4112 
4113 	/*
4114 	 * Second pass: switch the tsk->fs->* elements and mark new vfsmounts
4115 	 * as belonging to new namespace.  We have already acquired a private
4116 	 * fs_struct, so tsk->fs->lock is not needed.
4117 	 */
4118 	p = old;
4119 	q = new;
4120 	while (p) {
4121 		mnt_add_to_ns(new_ns, q);
4122 		new_ns->nr_mounts++;
4123 		if (new_fs) {
4124 			if (&p->mnt == new_fs->root.mnt) {
4125 				new_fs->root.mnt = mntget(&q->mnt);
4126 				rootmnt = &p->mnt;
4127 			}
4128 			if (&p->mnt == new_fs->pwd.mnt) {
4129 				new_fs->pwd.mnt = mntget(&q->mnt);
4130 				pwdmnt = &p->mnt;
4131 			}
4132 		}
4133 		p = next_mnt(p, old);
4134 		q = next_mnt(q, new);
4135 		if (!q)
4136 			break;
4137 		// an mntns binding we'd skipped?
4138 		while (p->mnt.mnt_root != q->mnt.mnt_root)
4139 			p = next_mnt(skip_mnt_tree(p), old);
4140 	}
4141 	namespace_unlock();
4142 
4143 	if (rootmnt)
4144 		mntput(rootmnt);
4145 	if (pwdmnt)
4146 		mntput(pwdmnt);
4147 
4148 	mnt_ns_tree_add(new_ns);
4149 	return new_ns;
4150 }
4151 
4152 struct dentry *mount_subtree(struct vfsmount *m, const char *name)
4153 {
4154 	struct mount *mnt = real_mount(m);
4155 	struct mnt_namespace *ns;
4156 	struct super_block *s;
4157 	struct path path;
4158 	int err;
4159 
4160 	ns = alloc_mnt_ns(&init_user_ns, true);
4161 	if (IS_ERR(ns)) {
4162 		mntput(m);
4163 		return ERR_CAST(ns);
4164 	}
4165 	ns->root = mnt;
4166 	ns->nr_mounts++;
4167 	mnt_add_to_ns(ns, mnt);
4168 
4169 	err = vfs_path_lookup(m->mnt_root, m,
4170 			name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &path);
4171 
4172 	put_mnt_ns(ns);
4173 
4174 	if (err)
4175 		return ERR_PTR(err);
4176 
4177 	/* trade a vfsmount reference for active sb one */
4178 	s = path.mnt->mnt_sb;
4179 	atomic_inc(&s->s_active);
4180 	mntput(path.mnt);
4181 	/* lock the sucker */
4182 	down_write(&s->s_umount);
4183 	/* ... and return the root of (sub)tree on it */
4184 	return path.dentry;
4185 }
4186 EXPORT_SYMBOL(mount_subtree);
4187 
4188 SYSCALL_DEFINE5(mount, char __user *, dev_name, char __user *, dir_name,
4189 		char __user *, type, unsigned long, flags, void __user *, data)
4190 {
4191 	int ret;
4192 	char *kernel_type;
4193 	char *kernel_dev;
4194 	void *options;
4195 
4196 	kernel_type = copy_mount_string(type);
4197 	ret = PTR_ERR(kernel_type);
4198 	if (IS_ERR(kernel_type))
4199 		goto out_type;
4200 
4201 	kernel_dev = copy_mount_string(dev_name);
4202 	ret = PTR_ERR(kernel_dev);
4203 	if (IS_ERR(kernel_dev))
4204 		goto out_dev;
4205 
4206 	options = copy_mount_options(data);
4207 	ret = PTR_ERR(options);
4208 	if (IS_ERR(options))
4209 		goto out_data;
4210 
4211 	ret = do_mount(kernel_dev, dir_name, kernel_type, flags, options);
4212 
4213 	kfree(options);
4214 out_data:
4215 	kfree(kernel_dev);
4216 out_dev:
4217 	kfree(kernel_type);
4218 out_type:
4219 	return ret;
4220 }
4221 
4222 #define FSMOUNT_VALID_FLAGS                                                    \
4223 	(MOUNT_ATTR_RDONLY | MOUNT_ATTR_NOSUID | MOUNT_ATTR_NODEV |            \
4224 	 MOUNT_ATTR_NOEXEC | MOUNT_ATTR__ATIME | MOUNT_ATTR_NODIRATIME |       \
4225 	 MOUNT_ATTR_NOSYMFOLLOW)
4226 
4227 #define MOUNT_SETATTR_VALID_FLAGS (FSMOUNT_VALID_FLAGS | MOUNT_ATTR_IDMAP)
4228 
4229 #define MOUNT_SETATTR_PROPAGATION_FLAGS \
4230 	(MS_UNBINDABLE | MS_PRIVATE | MS_SLAVE | MS_SHARED)
4231 
4232 static unsigned int attr_flags_to_mnt_flags(u64 attr_flags)
4233 {
4234 	unsigned int mnt_flags = 0;
4235 
4236 	if (attr_flags & MOUNT_ATTR_RDONLY)
4237 		mnt_flags |= MNT_READONLY;
4238 	if (attr_flags & MOUNT_ATTR_NOSUID)
4239 		mnt_flags |= MNT_NOSUID;
4240 	if (attr_flags & MOUNT_ATTR_NODEV)
4241 		mnt_flags |= MNT_NODEV;
4242 	if (attr_flags & MOUNT_ATTR_NOEXEC)
4243 		mnt_flags |= MNT_NOEXEC;
4244 	if (attr_flags & MOUNT_ATTR_NODIRATIME)
4245 		mnt_flags |= MNT_NODIRATIME;
4246 	if (attr_flags & MOUNT_ATTR_NOSYMFOLLOW)
4247 		mnt_flags |= MNT_NOSYMFOLLOW;
4248 
4249 	return mnt_flags;
4250 }
4251 
4252 /*
4253  * Create a kernel mount representation for a new, prepared superblock
4254  * (specified by fs_fd) and attach to an open_tree-like file descriptor.
4255  */
4256 SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
4257 		unsigned int, attr_flags)
4258 {
4259 	struct mnt_namespace *ns;
4260 	struct fs_context *fc;
4261 	struct file *file;
4262 	struct path newmount;
4263 	struct mount *mnt;
4264 	unsigned int mnt_flags = 0;
4265 	long ret;
4266 
4267 	if (!may_mount())
4268 		return -EPERM;
4269 
4270 	if ((flags & ~(FSMOUNT_CLOEXEC)) != 0)
4271 		return -EINVAL;
4272 
4273 	if (attr_flags & ~FSMOUNT_VALID_FLAGS)
4274 		return -EINVAL;
4275 
4276 	mnt_flags = attr_flags_to_mnt_flags(attr_flags);
4277 
4278 	switch (attr_flags & MOUNT_ATTR__ATIME) {
4279 	case MOUNT_ATTR_STRICTATIME:
4280 		break;
4281 	case MOUNT_ATTR_NOATIME:
4282 		mnt_flags |= MNT_NOATIME;
4283 		break;
4284 	case MOUNT_ATTR_RELATIME:
4285 		mnt_flags |= MNT_RELATIME;
4286 		break;
4287 	default:
4288 		return -EINVAL;
4289 	}
4290 
4291 	CLASS(fd, f)(fs_fd);
4292 	if (fd_empty(f))
4293 		return -EBADF;
4294 
4295 	if (fd_file(f)->f_op != &fscontext_fops)
4296 		return -EINVAL;
4297 
4298 	fc = fd_file(f)->private_data;
4299 
4300 	ret = mutex_lock_interruptible(&fc->uapi_mutex);
4301 	if (ret < 0)
4302 		return ret;
4303 
4304 	/* There must be a valid superblock or we can't mount it */
4305 	ret = -EINVAL;
4306 	if (!fc->root)
4307 		goto err_unlock;
4308 
4309 	ret = -EPERM;
4310 	if (mount_too_revealing(fc->root->d_sb, &mnt_flags)) {
4311 		pr_warn("VFS: Mount too revealing\n");
4312 		goto err_unlock;
4313 	}
4314 
4315 	ret = -EBUSY;
4316 	if (fc->phase != FS_CONTEXT_AWAITING_MOUNT)
4317 		goto err_unlock;
4318 
4319 	if (fc->sb_flags & SB_MANDLOCK)
4320 		warn_mandlock();
4321 
4322 	newmount.mnt = vfs_create_mount(fc);
4323 	if (IS_ERR(newmount.mnt)) {
4324 		ret = PTR_ERR(newmount.mnt);
4325 		goto err_unlock;
4326 	}
4327 	newmount.dentry = dget(fc->root);
4328 	newmount.mnt->mnt_flags = mnt_flags;
4329 
4330 	/* We've done the mount bit - now move the file context into more or
4331 	 * less the same state as if we'd done an fspick().  We don't want to
4332 	 * do any memory allocation or anything like that at this point as we
4333 	 * don't want to have to handle any errors incurred.
4334 	 */
4335 	vfs_clean_context(fc);
4336 
4337 	ns = alloc_mnt_ns(current->nsproxy->mnt_ns->user_ns, true);
4338 	if (IS_ERR(ns)) {
4339 		ret = PTR_ERR(ns);
4340 		goto err_path;
4341 	}
4342 	mnt = real_mount(newmount.mnt);
4343 	ns->root = mnt;
4344 	ns->nr_mounts = 1;
4345 	mnt_add_to_ns(ns, mnt);
4346 	mntget(newmount.mnt);
4347 
4348 	/* Attach to an apparent O_PATH fd with a note that we need to unmount
4349 	 * it, not just simply put it.
4350 	 */
4351 	file = dentry_open(&newmount, O_PATH, fc->cred);
4352 	if (IS_ERR(file)) {
4353 		dissolve_on_fput(newmount.mnt);
4354 		ret = PTR_ERR(file);
4355 		goto err_path;
4356 	}
4357 	file->f_mode |= FMODE_NEED_UNMOUNT;
4358 
4359 	ret = get_unused_fd_flags((flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0);
4360 	if (ret >= 0)
4361 		fd_install(ret, file);
4362 	else
4363 		fput(file);
4364 
4365 err_path:
4366 	path_put(&newmount);
4367 err_unlock:
4368 	mutex_unlock(&fc->uapi_mutex);
4369 	return ret;
4370 }
4371 
4372 /*
4373  * Move a mount from one place to another.  In combination with
4374  * fsopen()/fsmount() this is used to install a new mount and in combination
4375  * with open_tree(OPEN_TREE_CLONE [| AT_RECURSIVE]) it can be used to copy
4376  * a mount subtree.
4377  *
4378  * Note the flags value is a combination of MOVE_MOUNT_* flags.
4379  */
4380 SYSCALL_DEFINE5(move_mount,
4381 		int, from_dfd, const char __user *, from_pathname,
4382 		int, to_dfd, const char __user *, to_pathname,
4383 		unsigned int, flags)
4384 {
4385 	struct path from_path, to_path;
4386 	unsigned int lflags;
4387 	int ret = 0;
4388 
4389 	if (!may_mount())
4390 		return -EPERM;
4391 
4392 	if (flags & ~MOVE_MOUNT__MASK)
4393 		return -EINVAL;
4394 
4395 	if ((flags & (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP)) ==
4396 	    (MOVE_MOUNT_BENEATH | MOVE_MOUNT_SET_GROUP))
4397 		return -EINVAL;
4398 
4399 	/* If someone gives a pathname, they aren't permitted to move
4400 	 * from an fd that requires unmount as we can't get at the flag
4401 	 * to clear it afterwards.
4402 	 */
4403 	lflags = 0;
4404 	if (flags & MOVE_MOUNT_F_SYMLINKS)	lflags |= LOOKUP_FOLLOW;
4405 	if (flags & MOVE_MOUNT_F_AUTOMOUNTS)	lflags |= LOOKUP_AUTOMOUNT;
4406 	if (flags & MOVE_MOUNT_F_EMPTY_PATH)	lflags |= LOOKUP_EMPTY;
4407 
4408 	ret = user_path_at(from_dfd, from_pathname, lflags, &from_path);
4409 	if (ret < 0)
4410 		return ret;
4411 
4412 	lflags = 0;
4413 	if (flags & MOVE_MOUNT_T_SYMLINKS)	lflags |= LOOKUP_FOLLOW;
4414 	if (flags & MOVE_MOUNT_T_AUTOMOUNTS)	lflags |= LOOKUP_AUTOMOUNT;
4415 	if (flags & MOVE_MOUNT_T_EMPTY_PATH)	lflags |= LOOKUP_EMPTY;
4416 
4417 	ret = user_path_at(to_dfd, to_pathname, lflags, &to_path);
4418 	if (ret < 0)
4419 		goto out_from;
4420 
4421 	ret = security_move_mount(&from_path, &to_path);
4422 	if (ret < 0)
4423 		goto out_to;
4424 
4425 	if (flags & MOVE_MOUNT_SET_GROUP)
4426 		ret = do_set_group(&from_path, &to_path);
4427 	else
4428 		ret = do_move_mount(&from_path, &to_path,
4429 				    (flags & MOVE_MOUNT_BENEATH));
4430 
4431 out_to:
4432 	path_put(&to_path);
4433 out_from:
4434 	path_put(&from_path);
4435 	return ret;
4436 }
4437 
4438 /*
4439  * Return true if path is reachable from root
4440  *
4441  * namespace_sem or mount_lock is held
4442  */
4443 bool is_path_reachable(struct mount *mnt, struct dentry *dentry,
4444 			 const struct path *root)
4445 {
4446 	while (&mnt->mnt != root->mnt && mnt_has_parent(mnt)) {
4447 		dentry = mnt->mnt_mountpoint;
4448 		mnt = mnt->mnt_parent;
4449 	}
4450 	return &mnt->mnt == root->mnt && is_subdir(dentry, root->dentry);
4451 }
4452 
4453 bool path_is_under(const struct path *path1, const struct path *path2)
4454 {
4455 	bool res;
4456 	read_seqlock_excl(&mount_lock);
4457 	res = is_path_reachable(real_mount(path1->mnt), path1->dentry, path2);
4458 	read_sequnlock_excl(&mount_lock);
4459 	return res;
4460 }
4461 EXPORT_SYMBOL(path_is_under);
4462 
4463 /*
4464  * pivot_root Semantics:
4465  * Moves the root file system of the current process to the directory put_old,
4466  * makes new_root as the new root file system of the current process, and sets
4467  * root/cwd of all processes which had them on the current root to new_root.
4468  *
4469  * Restrictions:
4470  * The new_root and put_old must be directories, and  must not be on the
4471  * same file  system as the current process root. The put_old  must  be
4472  * underneath new_root,  i.e. adding a non-zero number of /.. to the string
4473  * pointed to by put_old must yield the same directory as new_root. No other
4474  * file system may be mounted on put_old. After all, new_root is a mountpoint.
4475  *
4476  * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem.
4477  * See Documentation/filesystems/ramfs-rootfs-initramfs.rst for alternatives
4478  * in this situation.
4479  *
4480  * Notes:
4481  *  - we don't move root/cwd if they are not at the root (reason: if something
4482  *    cared enough to change them, it's probably wrong to force them elsewhere)
4483  *  - it's okay to pick a root that isn't the root of a file system, e.g.
4484  *    /nfs/my_root where /nfs is the mount point. It must be a mountpoint,
4485  *    though, so you may need to say mount --bind /nfs/my_root /nfs/my_root
4486  *    first.
4487  */
4488 SYSCALL_DEFINE2(pivot_root, const char __user *, new_root,
4489 		const char __user *, put_old)
4490 {
4491 	struct path new, old, root;
4492 	struct mount *new_mnt, *root_mnt, *old_mnt, *root_parent, *ex_parent;
4493 	struct mountpoint *old_mp, *root_mp;
4494 	int error;
4495 
4496 	if (!may_mount())
4497 		return -EPERM;
4498 
4499 	error = user_path_at(AT_FDCWD, new_root,
4500 			     LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &new);
4501 	if (error)
4502 		goto out0;
4503 
4504 	error = user_path_at(AT_FDCWD, put_old,
4505 			     LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &old);
4506 	if (error)
4507 		goto out1;
4508 
4509 	error = security_sb_pivotroot(&old, &new);
4510 	if (error)
4511 		goto out2;
4512 
4513 	get_fs_root(current->fs, &root);
4514 	old_mp = lock_mount(&old);
4515 	error = PTR_ERR(old_mp);
4516 	if (IS_ERR(old_mp))
4517 		goto out3;
4518 
4519 	error = -EINVAL;
4520 	new_mnt = real_mount(new.mnt);
4521 	root_mnt = real_mount(root.mnt);
4522 	old_mnt = real_mount(old.mnt);
4523 	ex_parent = new_mnt->mnt_parent;
4524 	root_parent = root_mnt->mnt_parent;
4525 	if (IS_MNT_SHARED(old_mnt) ||
4526 		IS_MNT_SHARED(ex_parent) ||
4527 		IS_MNT_SHARED(root_parent))
4528 		goto out4;
4529 	if (!check_mnt(root_mnt) || !check_mnt(new_mnt))
4530 		goto out4;
4531 	if (new_mnt->mnt.mnt_flags & MNT_LOCKED)
4532 		goto out4;
4533 	error = -ENOENT;
4534 	if (d_unlinked(new.dentry))
4535 		goto out4;
4536 	error = -EBUSY;
4537 	if (new_mnt == root_mnt || old_mnt == root_mnt)
4538 		goto out4; /* loop, on the same file system  */
4539 	error = -EINVAL;
4540 	if (!path_mounted(&root))
4541 		goto out4; /* not a mountpoint */
4542 	if (!mnt_has_parent(root_mnt))
4543 		goto out4; /* not attached */
4544 	if (!path_mounted(&new))
4545 		goto out4; /* not a mountpoint */
4546 	if (!mnt_has_parent(new_mnt))
4547 		goto out4; /* not attached */
4548 	/* make sure we can reach put_old from new_root */
4549 	if (!is_path_reachable(old_mnt, old.dentry, &new))
4550 		goto out4;
4551 	/* make certain new is below the root */
4552 	if (!is_path_reachable(new_mnt, new.dentry, &root))
4553 		goto out4;
4554 	lock_mount_hash();
4555 	umount_mnt(new_mnt);
4556 	root_mp = unhash_mnt(root_mnt);  /* we'll need its mountpoint */
4557 	if (root_mnt->mnt.mnt_flags & MNT_LOCKED) {
4558 		new_mnt->mnt.mnt_flags |= MNT_LOCKED;
4559 		root_mnt->mnt.mnt_flags &= ~MNT_LOCKED;
4560 	}
4561 	/* mount old root on put_old */
4562 	attach_mnt(root_mnt, old_mnt, old_mp, false);
4563 	/* mount new_root on / */
4564 	attach_mnt(new_mnt, root_parent, root_mp, false);
4565 	mnt_add_count(root_parent, -1);
4566 	touch_mnt_namespace(current->nsproxy->mnt_ns);
4567 	/* A moved mount should not expire automatically */
4568 	list_del_init(&new_mnt->mnt_expire);
4569 	put_mountpoint(root_mp);
4570 	unlock_mount_hash();
4571 	mnt_notify_add(root_mnt);
4572 	mnt_notify_add(new_mnt);
4573 	chroot_fs_refs(&root, &new);
4574 	error = 0;
4575 out4:
4576 	unlock_mount(old_mp);
4577 	if (!error)
4578 		mntput_no_expire(ex_parent);
4579 out3:
4580 	path_put(&root);
4581 out2:
4582 	path_put(&old);
4583 out1:
4584 	path_put(&new);
4585 out0:
4586 	return error;
4587 }
4588 
4589 static unsigned int recalc_flags(struct mount_kattr *kattr, struct mount *mnt)
4590 {
4591 	unsigned int flags = mnt->mnt.mnt_flags;
4592 
4593 	/*  flags to clear */
4594 	flags &= ~kattr->attr_clr;
4595 	/* flags to raise */
4596 	flags |= kattr->attr_set;
4597 
4598 	return flags;
4599 }
4600 
4601 static int can_idmap_mount(const struct mount_kattr *kattr, struct mount *mnt)
4602 {
4603 	struct vfsmount *m = &mnt->mnt;
4604 	struct user_namespace *fs_userns = m->mnt_sb->s_user_ns;
4605 
4606 	if (!kattr->mnt_idmap)
4607 		return 0;
4608 
4609 	/*
4610 	 * Creating an idmapped mount with the filesystem wide idmapping
4611 	 * doesn't make sense so block that. We don't allow mushy semantics.
4612 	 */
4613 	if (kattr->mnt_userns == m->mnt_sb->s_user_ns)
4614 		return -EINVAL;
4615 
4616 	/*
4617 	 * We only allow an mount to change it's idmapping if it has
4618 	 * never been accessible to userspace.
4619 	 */
4620 	if (!(kattr->kflags & MOUNT_KATTR_IDMAP_REPLACE) && is_idmapped_mnt(m))
4621 		return -EPERM;
4622 
4623 	/* The underlying filesystem doesn't support idmapped mounts yet. */
4624 	if (!(m->mnt_sb->s_type->fs_flags & FS_ALLOW_IDMAP))
4625 		return -EINVAL;
4626 
4627 	/* The filesystem has turned off idmapped mounts. */
4628 	if (m->mnt_sb->s_iflags & SB_I_NOIDMAP)
4629 		return -EINVAL;
4630 
4631 	/* We're not controlling the superblock. */
4632 	if (!ns_capable(fs_userns, CAP_SYS_ADMIN))
4633 		return -EPERM;
4634 
4635 	/* Mount has already been visible in the filesystem hierarchy. */
4636 	if (!is_anon_ns(mnt->mnt_ns))
4637 		return -EINVAL;
4638 
4639 	return 0;
4640 }
4641 
4642 /**
4643  * mnt_allow_writers() - check whether the attribute change allows writers
4644  * @kattr: the new mount attributes
4645  * @mnt: the mount to which @kattr will be applied
4646  *
4647  * Check whether thew new mount attributes in @kattr allow concurrent writers.
4648  *
4649  * Return: true if writers need to be held, false if not
4650  */
4651 static inline bool mnt_allow_writers(const struct mount_kattr *kattr,
4652 				     const struct mount *mnt)
4653 {
4654 	return (!(kattr->attr_set & MNT_READONLY) ||
4655 		(mnt->mnt.mnt_flags & MNT_READONLY)) &&
4656 	       !kattr->mnt_idmap;
4657 }
4658 
4659 static int mount_setattr_prepare(struct mount_kattr *kattr, struct mount *mnt)
4660 {
4661 	struct mount *m;
4662 	int err;
4663 
4664 	for (m = mnt; m; m = next_mnt(m, mnt)) {
4665 		if (!can_change_locked_flags(m, recalc_flags(kattr, m))) {
4666 			err = -EPERM;
4667 			break;
4668 		}
4669 
4670 		err = can_idmap_mount(kattr, m);
4671 		if (err)
4672 			break;
4673 
4674 		if (!mnt_allow_writers(kattr, m)) {
4675 			err = mnt_hold_writers(m);
4676 			if (err)
4677 				break;
4678 		}
4679 
4680 		if (!(kattr->kflags & MOUNT_KATTR_RECURSE))
4681 			return 0;
4682 	}
4683 
4684 	if (err) {
4685 		struct mount *p;
4686 
4687 		/*
4688 		 * If we had to call mnt_hold_writers() MNT_WRITE_HOLD will
4689 		 * be set in @mnt_flags. The loop unsets MNT_WRITE_HOLD for all
4690 		 * mounts and needs to take care to include the first mount.
4691 		 */
4692 		for (p = mnt; p; p = next_mnt(p, mnt)) {
4693 			/* If we had to hold writers unblock them. */
4694 			if (p->mnt.mnt_flags & MNT_WRITE_HOLD)
4695 				mnt_unhold_writers(p);
4696 
4697 			/*
4698 			 * We're done once the first mount we changed got
4699 			 * MNT_WRITE_HOLD unset.
4700 			 */
4701 			if (p == m)
4702 				break;
4703 		}
4704 	}
4705 	return err;
4706 }
4707 
4708 static void do_idmap_mount(const struct mount_kattr *kattr, struct mount *mnt)
4709 {
4710 	struct mnt_idmap *old_idmap;
4711 
4712 	if (!kattr->mnt_idmap)
4713 		return;
4714 
4715 	old_idmap = mnt_idmap(&mnt->mnt);
4716 
4717 	/* Pairs with smp_load_acquire() in mnt_idmap(). */
4718 	smp_store_release(&mnt->mnt.mnt_idmap, mnt_idmap_get(kattr->mnt_idmap));
4719 	mnt_idmap_put(old_idmap);
4720 }
4721 
4722 static void mount_setattr_commit(struct mount_kattr *kattr, struct mount *mnt)
4723 {
4724 	struct mount *m;
4725 
4726 	for (m = mnt; m; m = next_mnt(m, mnt)) {
4727 		unsigned int flags;
4728 
4729 		do_idmap_mount(kattr, m);
4730 		flags = recalc_flags(kattr, m);
4731 		WRITE_ONCE(m->mnt.mnt_flags, flags);
4732 
4733 		/* If we had to hold writers unblock them. */
4734 		if (m->mnt.mnt_flags & MNT_WRITE_HOLD)
4735 			mnt_unhold_writers(m);
4736 
4737 		if (kattr->propagation)
4738 			change_mnt_propagation(m, kattr->propagation);
4739 		if (!(kattr->kflags & MOUNT_KATTR_RECURSE))
4740 			break;
4741 	}
4742 	touch_mnt_namespace(mnt->mnt_ns);
4743 }
4744 
4745 static int do_mount_setattr(struct path *path, struct mount_kattr *kattr)
4746 {
4747 	struct mount *mnt = real_mount(path->mnt);
4748 	int err = 0;
4749 
4750 	if (!path_mounted(path))
4751 		return -EINVAL;
4752 
4753 	if (kattr->mnt_userns) {
4754 		struct mnt_idmap *mnt_idmap;
4755 
4756 		mnt_idmap = alloc_mnt_idmap(kattr->mnt_userns);
4757 		if (IS_ERR(mnt_idmap))
4758 			return PTR_ERR(mnt_idmap);
4759 		kattr->mnt_idmap = mnt_idmap;
4760 	}
4761 
4762 	if (kattr->propagation) {
4763 		/*
4764 		 * Only take namespace_lock() if we're actually changing
4765 		 * propagation.
4766 		 */
4767 		namespace_lock();
4768 		if (kattr->propagation == MS_SHARED) {
4769 			err = invent_group_ids(mnt, kattr->kflags & MOUNT_KATTR_RECURSE);
4770 			if (err) {
4771 				namespace_unlock();
4772 				return err;
4773 			}
4774 		}
4775 	}
4776 
4777 	err = -EINVAL;
4778 	lock_mount_hash();
4779 
4780 	/* Ensure that this isn't anything purely vfs internal. */
4781 	if (!is_mounted(&mnt->mnt))
4782 		goto out;
4783 
4784 	/*
4785 	 * If this is an attached mount make sure it's located in the callers
4786 	 * mount namespace. If it's not don't let the caller interact with it.
4787 	 *
4788 	 * If this mount doesn't have a parent it's most often simply a
4789 	 * detached mount with an anonymous mount namespace. IOW, something
4790 	 * that's simply not attached yet. But there are apparently also users
4791 	 * that do change mount properties on the rootfs itself. That obviously
4792 	 * neither has a parent nor is it a detached mount so we cannot
4793 	 * unconditionally check for detached mounts.
4794 	 */
4795 	if ((mnt_has_parent(mnt) || !is_anon_ns(mnt->mnt_ns)) && !check_mnt(mnt))
4796 		goto out;
4797 
4798 	/*
4799 	 * First, we get the mount tree in a shape where we can change mount
4800 	 * properties without failure. If we succeeded to do so we commit all
4801 	 * changes and if we failed we clean up.
4802 	 */
4803 	err = mount_setattr_prepare(kattr, mnt);
4804 	if (!err)
4805 		mount_setattr_commit(kattr, mnt);
4806 
4807 out:
4808 	unlock_mount_hash();
4809 
4810 	if (kattr->propagation) {
4811 		if (err)
4812 			cleanup_group_ids(mnt, NULL);
4813 		namespace_unlock();
4814 	}
4815 
4816 	return err;
4817 }
4818 
4819 static int build_mount_idmapped(const struct mount_attr *attr, size_t usize,
4820 				struct mount_kattr *kattr)
4821 {
4822 	struct ns_common *ns;
4823 	struct user_namespace *mnt_userns;
4824 
4825 	if (!((attr->attr_set | attr->attr_clr) & MOUNT_ATTR_IDMAP))
4826 		return 0;
4827 
4828 	if (attr->attr_clr & MOUNT_ATTR_IDMAP) {
4829 		/*
4830 		 * We can only remove an idmapping if it's never been
4831 		 * exposed to userspace.
4832 		 */
4833 		if (!(kattr->kflags & MOUNT_KATTR_IDMAP_REPLACE))
4834 			return -EINVAL;
4835 
4836 		/*
4837 		 * Removal of idmappings is equivalent to setting
4838 		 * nop_mnt_idmap.
4839 		 */
4840 		if (!(attr->attr_set & MOUNT_ATTR_IDMAP)) {
4841 			kattr->mnt_idmap = &nop_mnt_idmap;
4842 			return 0;
4843 		}
4844 	}
4845 
4846 	if (attr->userns_fd > INT_MAX)
4847 		return -EINVAL;
4848 
4849 	CLASS(fd, f)(attr->userns_fd);
4850 	if (fd_empty(f))
4851 		return -EBADF;
4852 
4853 	if (!proc_ns_file(fd_file(f)))
4854 		return -EINVAL;
4855 
4856 	ns = get_proc_ns(file_inode(fd_file(f)));
4857 	if (ns->ops->type != CLONE_NEWUSER)
4858 		return -EINVAL;
4859 
4860 	/*
4861 	 * The initial idmapping cannot be used to create an idmapped
4862 	 * mount. We use the initial idmapping as an indicator of a mount
4863 	 * that is not idmapped. It can simply be passed into helpers that
4864 	 * are aware of idmapped mounts as a convenient shortcut. A user
4865 	 * can just create a dedicated identity mapping to achieve the same
4866 	 * result.
4867 	 */
4868 	mnt_userns = container_of(ns, struct user_namespace, ns);
4869 	if (mnt_userns == &init_user_ns)
4870 		return -EPERM;
4871 
4872 	/* We're not controlling the target namespace. */
4873 	if (!ns_capable(mnt_userns, CAP_SYS_ADMIN))
4874 		return -EPERM;
4875 
4876 	kattr->mnt_userns = get_user_ns(mnt_userns);
4877 	return 0;
4878 }
4879 
4880 static int build_mount_kattr(const struct mount_attr *attr, size_t usize,
4881 			     struct mount_kattr *kattr)
4882 {
4883 	if (attr->propagation & ~MOUNT_SETATTR_PROPAGATION_FLAGS)
4884 		return -EINVAL;
4885 	if (hweight32(attr->propagation & MOUNT_SETATTR_PROPAGATION_FLAGS) > 1)
4886 		return -EINVAL;
4887 	kattr->propagation = attr->propagation;
4888 
4889 	if ((attr->attr_set | attr->attr_clr) & ~MOUNT_SETATTR_VALID_FLAGS)
4890 		return -EINVAL;
4891 
4892 	kattr->attr_set = attr_flags_to_mnt_flags(attr->attr_set);
4893 	kattr->attr_clr = attr_flags_to_mnt_flags(attr->attr_clr);
4894 
4895 	/*
4896 	 * Since the MOUNT_ATTR_<atime> values are an enum, not a bitmap,
4897 	 * users wanting to transition to a different atime setting cannot
4898 	 * simply specify the atime setting in @attr_set, but must also
4899 	 * specify MOUNT_ATTR__ATIME in the @attr_clr field.
4900 	 * So ensure that MOUNT_ATTR__ATIME can't be partially set in
4901 	 * @attr_clr and that @attr_set can't have any atime bits set if
4902 	 * MOUNT_ATTR__ATIME isn't set in @attr_clr.
4903 	 */
4904 	if (attr->attr_clr & MOUNT_ATTR__ATIME) {
4905 		if ((attr->attr_clr & MOUNT_ATTR__ATIME) != MOUNT_ATTR__ATIME)
4906 			return -EINVAL;
4907 
4908 		/*
4909 		 * Clear all previous time settings as they are mutually
4910 		 * exclusive.
4911 		 */
4912 		kattr->attr_clr |= MNT_RELATIME | MNT_NOATIME;
4913 		switch (attr->attr_set & MOUNT_ATTR__ATIME) {
4914 		case MOUNT_ATTR_RELATIME:
4915 			kattr->attr_set |= MNT_RELATIME;
4916 			break;
4917 		case MOUNT_ATTR_NOATIME:
4918 			kattr->attr_set |= MNT_NOATIME;
4919 			break;
4920 		case MOUNT_ATTR_STRICTATIME:
4921 			break;
4922 		default:
4923 			return -EINVAL;
4924 		}
4925 	} else {
4926 		if (attr->attr_set & MOUNT_ATTR__ATIME)
4927 			return -EINVAL;
4928 	}
4929 
4930 	return build_mount_idmapped(attr, usize, kattr);
4931 }
4932 
4933 static void finish_mount_kattr(struct mount_kattr *kattr)
4934 {
4935 	if (kattr->mnt_userns) {
4936 		put_user_ns(kattr->mnt_userns);
4937 		kattr->mnt_userns = NULL;
4938 	}
4939 
4940 	if (kattr->mnt_idmap)
4941 		mnt_idmap_put(kattr->mnt_idmap);
4942 }
4943 
4944 static int copy_mount_setattr(struct mount_attr __user *uattr, size_t usize,
4945 			      struct mount_kattr *kattr)
4946 {
4947 	int ret;
4948 	struct mount_attr attr;
4949 
4950 	BUILD_BUG_ON(sizeof(struct mount_attr) != MOUNT_ATTR_SIZE_VER0);
4951 
4952 	if (unlikely(usize > PAGE_SIZE))
4953 		return -E2BIG;
4954 	if (unlikely(usize < MOUNT_ATTR_SIZE_VER0))
4955 		return -EINVAL;
4956 
4957 	if (!may_mount())
4958 		return -EPERM;
4959 
4960 	ret = copy_struct_from_user(&attr, sizeof(attr), uattr, usize);
4961 	if (ret)
4962 		return ret;
4963 
4964 	/* Don't bother walking through the mounts if this is a nop. */
4965 	if (attr.attr_set == 0 &&
4966 	    attr.attr_clr == 0 &&
4967 	    attr.propagation == 0)
4968 		return 0;
4969 
4970 	return build_mount_kattr(&attr, usize, kattr);
4971 }
4972 
4973 SYSCALL_DEFINE5(mount_setattr, int, dfd, const char __user *, path,
4974 		unsigned int, flags, struct mount_attr __user *, uattr,
4975 		size_t, usize)
4976 {
4977 	int err;
4978 	struct path target;
4979 	struct mount_kattr kattr;
4980 	unsigned int lookup_flags = LOOKUP_AUTOMOUNT | LOOKUP_FOLLOW;
4981 
4982 	if (flags & ~(AT_EMPTY_PATH |
4983 		      AT_RECURSIVE |
4984 		      AT_SYMLINK_NOFOLLOW |
4985 		      AT_NO_AUTOMOUNT))
4986 		return -EINVAL;
4987 
4988 	if (flags & AT_NO_AUTOMOUNT)
4989 		lookup_flags &= ~LOOKUP_AUTOMOUNT;
4990 	if (flags & AT_SYMLINK_NOFOLLOW)
4991 		lookup_flags &= ~LOOKUP_FOLLOW;
4992 	if (flags & AT_EMPTY_PATH)
4993 		lookup_flags |= LOOKUP_EMPTY;
4994 
4995 	kattr = (struct mount_kattr) {
4996 		.lookup_flags	= lookup_flags,
4997 	};
4998 
4999 	if (flags & AT_RECURSIVE)
5000 		kattr.kflags |= MOUNT_KATTR_RECURSE;
5001 
5002 	err = copy_mount_setattr(uattr, usize, &kattr);
5003 	if (err)
5004 		return err;
5005 
5006 	err = user_path_at(dfd, path, kattr.lookup_flags, &target);
5007 	if (!err) {
5008 		err = do_mount_setattr(&target, &kattr);
5009 		path_put(&target);
5010 	}
5011 	finish_mount_kattr(&kattr);
5012 	return err;
5013 }
5014 
5015 SYSCALL_DEFINE5(open_tree_attr, int, dfd, const char __user *, filename,
5016 		unsigned, flags, struct mount_attr __user *, uattr,
5017 		size_t, usize)
5018 {
5019 	struct file __free(fput) *file = NULL;
5020 	int fd;
5021 
5022 	if (!uattr && usize)
5023 		return -EINVAL;
5024 
5025 	file = vfs_open_tree(dfd, filename, flags);
5026 	if (IS_ERR(file))
5027 		return PTR_ERR(file);
5028 
5029 	if (uattr) {
5030 		int ret;
5031 		struct mount_kattr kattr = {};
5032 
5033 		kattr.kflags = MOUNT_KATTR_IDMAP_REPLACE;
5034 		if (flags & AT_RECURSIVE)
5035 			kattr.kflags |= MOUNT_KATTR_RECURSE;
5036 
5037 		ret = copy_mount_setattr(uattr, usize, &kattr);
5038 		if (ret)
5039 			return ret;
5040 
5041 		ret = do_mount_setattr(&file->f_path, &kattr);
5042 		if (ret)
5043 			return ret;
5044 
5045 		finish_mount_kattr(&kattr);
5046 	}
5047 
5048 	fd = get_unused_fd_flags(flags & O_CLOEXEC);
5049 	if (fd < 0)
5050 		return fd;
5051 
5052 	fd_install(fd, no_free_ptr(file));
5053 	return fd;
5054 }
5055 
5056 int show_path(struct seq_file *m, struct dentry *root)
5057 {
5058 	if (root->d_sb->s_op->show_path)
5059 		return root->d_sb->s_op->show_path(m, root);
5060 
5061 	seq_dentry(m, root, " \t\n\\");
5062 	return 0;
5063 }
5064 
5065 static struct vfsmount *lookup_mnt_in_ns(u64 id, struct mnt_namespace *ns)
5066 {
5067 	struct mount *mnt = mnt_find_id_at(ns, id);
5068 
5069 	if (!mnt || mnt->mnt_id_unique != id)
5070 		return NULL;
5071 
5072 	return &mnt->mnt;
5073 }
5074 
5075 struct kstatmount {
5076 	struct statmount __user *buf;
5077 	size_t bufsize;
5078 	struct vfsmount *mnt;
5079 	struct mnt_idmap *idmap;
5080 	u64 mask;
5081 	struct path root;
5082 	struct statmount sm;
5083 	struct seq_file seq;
5084 };
5085 
5086 static u64 mnt_to_attr_flags(struct vfsmount *mnt)
5087 {
5088 	unsigned int mnt_flags = READ_ONCE(mnt->mnt_flags);
5089 	u64 attr_flags = 0;
5090 
5091 	if (mnt_flags & MNT_READONLY)
5092 		attr_flags |= MOUNT_ATTR_RDONLY;
5093 	if (mnt_flags & MNT_NOSUID)
5094 		attr_flags |= MOUNT_ATTR_NOSUID;
5095 	if (mnt_flags & MNT_NODEV)
5096 		attr_flags |= MOUNT_ATTR_NODEV;
5097 	if (mnt_flags & MNT_NOEXEC)
5098 		attr_flags |= MOUNT_ATTR_NOEXEC;
5099 	if (mnt_flags & MNT_NODIRATIME)
5100 		attr_flags |= MOUNT_ATTR_NODIRATIME;
5101 	if (mnt_flags & MNT_NOSYMFOLLOW)
5102 		attr_flags |= MOUNT_ATTR_NOSYMFOLLOW;
5103 
5104 	if (mnt_flags & MNT_NOATIME)
5105 		attr_flags |= MOUNT_ATTR_NOATIME;
5106 	else if (mnt_flags & MNT_RELATIME)
5107 		attr_flags |= MOUNT_ATTR_RELATIME;
5108 	else
5109 		attr_flags |= MOUNT_ATTR_STRICTATIME;
5110 
5111 	if (is_idmapped_mnt(mnt))
5112 		attr_flags |= MOUNT_ATTR_IDMAP;
5113 
5114 	return attr_flags;
5115 }
5116 
5117 static u64 mnt_to_propagation_flags(struct mount *m)
5118 {
5119 	u64 propagation = 0;
5120 
5121 	if (IS_MNT_SHARED(m))
5122 		propagation |= MS_SHARED;
5123 	if (IS_MNT_SLAVE(m))
5124 		propagation |= MS_SLAVE;
5125 	if (IS_MNT_UNBINDABLE(m))
5126 		propagation |= MS_UNBINDABLE;
5127 	if (!propagation)
5128 		propagation |= MS_PRIVATE;
5129 
5130 	return propagation;
5131 }
5132 
5133 static void statmount_sb_basic(struct kstatmount *s)
5134 {
5135 	struct super_block *sb = s->mnt->mnt_sb;
5136 
5137 	s->sm.mask |= STATMOUNT_SB_BASIC;
5138 	s->sm.sb_dev_major = MAJOR(sb->s_dev);
5139 	s->sm.sb_dev_minor = MINOR(sb->s_dev);
5140 	s->sm.sb_magic = sb->s_magic;
5141 	s->sm.sb_flags = sb->s_flags & (SB_RDONLY|SB_SYNCHRONOUS|SB_DIRSYNC|SB_LAZYTIME);
5142 }
5143 
5144 static void statmount_mnt_basic(struct kstatmount *s)
5145 {
5146 	struct mount *m = real_mount(s->mnt);
5147 
5148 	s->sm.mask |= STATMOUNT_MNT_BASIC;
5149 	s->sm.mnt_id = m->mnt_id_unique;
5150 	s->sm.mnt_parent_id = m->mnt_parent->mnt_id_unique;
5151 	s->sm.mnt_id_old = m->mnt_id;
5152 	s->sm.mnt_parent_id_old = m->mnt_parent->mnt_id;
5153 	s->sm.mnt_attr = mnt_to_attr_flags(&m->mnt);
5154 	s->sm.mnt_propagation = mnt_to_propagation_flags(m);
5155 	s->sm.mnt_peer_group = IS_MNT_SHARED(m) ? m->mnt_group_id : 0;
5156 	s->sm.mnt_master = IS_MNT_SLAVE(m) ? m->mnt_master->mnt_group_id : 0;
5157 }
5158 
5159 static void statmount_propagate_from(struct kstatmount *s)
5160 {
5161 	struct mount *m = real_mount(s->mnt);
5162 
5163 	s->sm.mask |= STATMOUNT_PROPAGATE_FROM;
5164 	if (IS_MNT_SLAVE(m))
5165 		s->sm.propagate_from = get_dominating_id(m, &current->fs->root);
5166 }
5167 
5168 static int statmount_mnt_root(struct kstatmount *s, struct seq_file *seq)
5169 {
5170 	int ret;
5171 	size_t start = seq->count;
5172 
5173 	ret = show_path(seq, s->mnt->mnt_root);
5174 	if (ret)
5175 		return ret;
5176 
5177 	if (unlikely(seq_has_overflowed(seq)))
5178 		return -EAGAIN;
5179 
5180 	/*
5181          * Unescape the result. It would be better if supplied string was not
5182          * escaped in the first place, but that's a pretty invasive change.
5183          */
5184 	seq->buf[seq->count] = '\0';
5185 	seq->count = start;
5186 	seq_commit(seq, string_unescape_inplace(seq->buf + start, UNESCAPE_OCTAL));
5187 	return 0;
5188 }
5189 
5190 static int statmount_mnt_point(struct kstatmount *s, struct seq_file *seq)
5191 {
5192 	struct vfsmount *mnt = s->mnt;
5193 	struct path mnt_path = { .dentry = mnt->mnt_root, .mnt = mnt };
5194 	int err;
5195 
5196 	err = seq_path_root(seq, &mnt_path, &s->root, "");
5197 	return err == SEQ_SKIP ? 0 : err;
5198 }
5199 
5200 static int statmount_fs_type(struct kstatmount *s, struct seq_file *seq)
5201 {
5202 	struct super_block *sb = s->mnt->mnt_sb;
5203 
5204 	seq_puts(seq, sb->s_type->name);
5205 	return 0;
5206 }
5207 
5208 static void statmount_fs_subtype(struct kstatmount *s, struct seq_file *seq)
5209 {
5210 	struct super_block *sb = s->mnt->mnt_sb;
5211 
5212 	if (sb->s_subtype)
5213 		seq_puts(seq, sb->s_subtype);
5214 }
5215 
5216 static int statmount_sb_source(struct kstatmount *s, struct seq_file *seq)
5217 {
5218 	struct super_block *sb = s->mnt->mnt_sb;
5219 	struct mount *r = real_mount(s->mnt);
5220 
5221 	if (sb->s_op->show_devname) {
5222 		size_t start = seq->count;
5223 		int ret;
5224 
5225 		ret = sb->s_op->show_devname(seq, s->mnt->mnt_root);
5226 		if (ret)
5227 			return ret;
5228 
5229 		if (unlikely(seq_has_overflowed(seq)))
5230 			return -EAGAIN;
5231 
5232 		/* Unescape the result */
5233 		seq->buf[seq->count] = '\0';
5234 		seq->count = start;
5235 		seq_commit(seq, string_unescape_inplace(seq->buf + start, UNESCAPE_OCTAL));
5236 	} else if (r->mnt_devname) {
5237 		seq_puts(seq, r->mnt_devname);
5238 	}
5239 	return 0;
5240 }
5241 
5242 static void statmount_mnt_ns_id(struct kstatmount *s, struct mnt_namespace *ns)
5243 {
5244 	s->sm.mask |= STATMOUNT_MNT_NS_ID;
5245 	s->sm.mnt_ns_id = ns->seq;
5246 }
5247 
5248 static int statmount_mnt_opts(struct kstatmount *s, struct seq_file *seq)
5249 {
5250 	struct vfsmount *mnt = s->mnt;
5251 	struct super_block *sb = mnt->mnt_sb;
5252 	size_t start = seq->count;
5253 	int err;
5254 
5255 	err = security_sb_show_options(seq, sb);
5256 	if (err)
5257 		return err;
5258 
5259 	if (sb->s_op->show_options) {
5260 		err = sb->s_op->show_options(seq, mnt->mnt_root);
5261 		if (err)
5262 			return err;
5263 	}
5264 
5265 	if (unlikely(seq_has_overflowed(seq)))
5266 		return -EAGAIN;
5267 
5268 	if (seq->count == start)
5269 		return 0;
5270 
5271 	/* skip leading comma */
5272 	memmove(seq->buf + start, seq->buf + start + 1,
5273 		seq->count - start - 1);
5274 	seq->count--;
5275 
5276 	return 0;
5277 }
5278 
5279 static inline int statmount_opt_process(struct seq_file *seq, size_t start)
5280 {
5281 	char *buf_end, *opt_end, *src, *dst;
5282 	int count = 0;
5283 
5284 	if (unlikely(seq_has_overflowed(seq)))
5285 		return -EAGAIN;
5286 
5287 	buf_end = seq->buf + seq->count;
5288 	dst = seq->buf + start;
5289 	src = dst + 1;	/* skip initial comma */
5290 
5291 	if (src >= buf_end) {
5292 		seq->count = start;
5293 		return 0;
5294 	}
5295 
5296 	*buf_end = '\0';
5297 	for (; src < buf_end; src = opt_end + 1) {
5298 		opt_end = strchrnul(src, ',');
5299 		*opt_end = '\0';
5300 		dst += string_unescape(src, dst, 0, UNESCAPE_OCTAL) + 1;
5301 		if (WARN_ON_ONCE(++count == INT_MAX))
5302 			return -EOVERFLOW;
5303 	}
5304 	seq->count = dst - 1 - seq->buf;
5305 	return count;
5306 }
5307 
5308 static int statmount_opt_array(struct kstatmount *s, struct seq_file *seq)
5309 {
5310 	struct vfsmount *mnt = s->mnt;
5311 	struct super_block *sb = mnt->mnt_sb;
5312 	size_t start = seq->count;
5313 	int err;
5314 
5315 	if (!sb->s_op->show_options)
5316 		return 0;
5317 
5318 	err = sb->s_op->show_options(seq, mnt->mnt_root);
5319 	if (err)
5320 		return err;
5321 
5322 	err = statmount_opt_process(seq, start);
5323 	if (err < 0)
5324 		return err;
5325 
5326 	s->sm.opt_num = err;
5327 	return 0;
5328 }
5329 
5330 static int statmount_opt_sec_array(struct kstatmount *s, struct seq_file *seq)
5331 {
5332 	struct vfsmount *mnt = s->mnt;
5333 	struct super_block *sb = mnt->mnt_sb;
5334 	size_t start = seq->count;
5335 	int err;
5336 
5337 	err = security_sb_show_options(seq, sb);
5338 	if (err)
5339 		return err;
5340 
5341 	err = statmount_opt_process(seq, start);
5342 	if (err < 0)
5343 		return err;
5344 
5345 	s->sm.opt_sec_num = err;
5346 	return 0;
5347 }
5348 
5349 static inline int statmount_mnt_uidmap(struct kstatmount *s, struct seq_file *seq)
5350 {
5351 	int ret;
5352 
5353 	ret = statmount_mnt_idmap(s->idmap, seq, true);
5354 	if (ret < 0)
5355 		return ret;
5356 
5357 	s->sm.mnt_uidmap_num = ret;
5358 	/*
5359 	 * Always raise STATMOUNT_MNT_UIDMAP even if there are no valid
5360 	 * mappings. This allows userspace to distinguish between a
5361 	 * non-idmapped mount and an idmapped mount where none of the
5362 	 * individual mappings are valid in the caller's idmapping.
5363 	 */
5364 	if (is_valid_mnt_idmap(s->idmap))
5365 		s->sm.mask |= STATMOUNT_MNT_UIDMAP;
5366 	return 0;
5367 }
5368 
5369 static inline int statmount_mnt_gidmap(struct kstatmount *s, struct seq_file *seq)
5370 {
5371 	int ret;
5372 
5373 	ret = statmount_mnt_idmap(s->idmap, seq, false);
5374 	if (ret < 0)
5375 		return ret;
5376 
5377 	s->sm.mnt_gidmap_num = ret;
5378 	/*
5379 	 * Always raise STATMOUNT_MNT_GIDMAP even if there are no valid
5380 	 * mappings. This allows userspace to distinguish between a
5381 	 * non-idmapped mount and an idmapped mount where none of the
5382 	 * individual mappings are valid in the caller's idmapping.
5383 	 */
5384 	if (is_valid_mnt_idmap(s->idmap))
5385 		s->sm.mask |= STATMOUNT_MNT_GIDMAP;
5386 	return 0;
5387 }
5388 
5389 static int statmount_string(struct kstatmount *s, u64 flag)
5390 {
5391 	int ret = 0;
5392 	size_t kbufsize;
5393 	struct seq_file *seq = &s->seq;
5394 	struct statmount *sm = &s->sm;
5395 	u32 start, *offp;
5396 
5397 	/* Reserve an empty string at the beginning for any unset offsets */
5398 	if (!seq->count)
5399 		seq_putc(seq, 0);
5400 
5401 	start = seq->count;
5402 
5403 	switch (flag) {
5404 	case STATMOUNT_FS_TYPE:
5405 		offp = &sm->fs_type;
5406 		ret = statmount_fs_type(s, seq);
5407 		break;
5408 	case STATMOUNT_MNT_ROOT:
5409 		offp = &sm->mnt_root;
5410 		ret = statmount_mnt_root(s, seq);
5411 		break;
5412 	case STATMOUNT_MNT_POINT:
5413 		offp = &sm->mnt_point;
5414 		ret = statmount_mnt_point(s, seq);
5415 		break;
5416 	case STATMOUNT_MNT_OPTS:
5417 		offp = &sm->mnt_opts;
5418 		ret = statmount_mnt_opts(s, seq);
5419 		break;
5420 	case STATMOUNT_OPT_ARRAY:
5421 		offp = &sm->opt_array;
5422 		ret = statmount_opt_array(s, seq);
5423 		break;
5424 	case STATMOUNT_OPT_SEC_ARRAY:
5425 		offp = &sm->opt_sec_array;
5426 		ret = statmount_opt_sec_array(s, seq);
5427 		break;
5428 	case STATMOUNT_FS_SUBTYPE:
5429 		offp = &sm->fs_subtype;
5430 		statmount_fs_subtype(s, seq);
5431 		break;
5432 	case STATMOUNT_SB_SOURCE:
5433 		offp = &sm->sb_source;
5434 		ret = statmount_sb_source(s, seq);
5435 		break;
5436 	case STATMOUNT_MNT_UIDMAP:
5437 		sm->mnt_uidmap = start;
5438 		ret = statmount_mnt_uidmap(s, seq);
5439 		break;
5440 	case STATMOUNT_MNT_GIDMAP:
5441 		sm->mnt_gidmap = start;
5442 		ret = statmount_mnt_gidmap(s, seq);
5443 		break;
5444 	default:
5445 		WARN_ON_ONCE(true);
5446 		return -EINVAL;
5447 	}
5448 
5449 	/*
5450 	 * If nothing was emitted, return to avoid setting the flag
5451 	 * and terminating the buffer.
5452 	 */
5453 	if (seq->count == start)
5454 		return ret;
5455 	if (unlikely(check_add_overflow(sizeof(*sm), seq->count, &kbufsize)))
5456 		return -EOVERFLOW;
5457 	if (kbufsize >= s->bufsize)
5458 		return -EOVERFLOW;
5459 
5460 	/* signal a retry */
5461 	if (unlikely(seq_has_overflowed(seq)))
5462 		return -EAGAIN;
5463 
5464 	if (ret)
5465 		return ret;
5466 
5467 	seq->buf[seq->count++] = '\0';
5468 	sm->mask |= flag;
5469 	*offp = start;
5470 	return 0;
5471 }
5472 
5473 static int copy_statmount_to_user(struct kstatmount *s)
5474 {
5475 	struct statmount *sm = &s->sm;
5476 	struct seq_file *seq = &s->seq;
5477 	char __user *str = ((char __user *)s->buf) + sizeof(*sm);
5478 	size_t copysize = min_t(size_t, s->bufsize, sizeof(*sm));
5479 
5480 	if (seq->count && copy_to_user(str, seq->buf, seq->count))
5481 		return -EFAULT;
5482 
5483 	/* Return the number of bytes copied to the buffer */
5484 	sm->size = copysize + seq->count;
5485 	if (copy_to_user(s->buf, sm, copysize))
5486 		return -EFAULT;
5487 
5488 	return 0;
5489 }
5490 
5491 static struct mount *listmnt_next(struct mount *curr, bool reverse)
5492 {
5493 	struct rb_node *node;
5494 
5495 	if (reverse)
5496 		node = rb_prev(&curr->mnt_node);
5497 	else
5498 		node = rb_next(&curr->mnt_node);
5499 
5500 	return node_to_mount(node);
5501 }
5502 
5503 static int grab_requested_root(struct mnt_namespace *ns, struct path *root)
5504 {
5505 	struct mount *first, *child;
5506 
5507 	rwsem_assert_held(&namespace_sem);
5508 
5509 	/* We're looking at our own ns, just use get_fs_root. */
5510 	if (ns == current->nsproxy->mnt_ns) {
5511 		get_fs_root(current->fs, root);
5512 		return 0;
5513 	}
5514 
5515 	/*
5516 	 * We have to find the first mount in our ns and use that, however it
5517 	 * may not exist, so handle that properly.
5518 	 */
5519 	if (RB_EMPTY_ROOT(&ns->mounts))
5520 		return -ENOENT;
5521 
5522 	first = child = ns->root;
5523 	for (;;) {
5524 		child = listmnt_next(child, false);
5525 		if (!child)
5526 			return -ENOENT;
5527 		if (child->mnt_parent == first)
5528 			break;
5529 	}
5530 
5531 	root->mnt = mntget(&child->mnt);
5532 	root->dentry = dget(root->mnt->mnt_root);
5533 	return 0;
5534 }
5535 
5536 /* This must be updated whenever a new flag is added */
5537 #define STATMOUNT_SUPPORTED (STATMOUNT_SB_BASIC | \
5538 			     STATMOUNT_MNT_BASIC | \
5539 			     STATMOUNT_PROPAGATE_FROM | \
5540 			     STATMOUNT_MNT_ROOT | \
5541 			     STATMOUNT_MNT_POINT | \
5542 			     STATMOUNT_FS_TYPE | \
5543 			     STATMOUNT_MNT_NS_ID | \
5544 			     STATMOUNT_MNT_OPTS | \
5545 			     STATMOUNT_FS_SUBTYPE | \
5546 			     STATMOUNT_SB_SOURCE | \
5547 			     STATMOUNT_OPT_ARRAY | \
5548 			     STATMOUNT_OPT_SEC_ARRAY | \
5549 			     STATMOUNT_SUPPORTED_MASK)
5550 
5551 static int do_statmount(struct kstatmount *s, u64 mnt_id, u64 mnt_ns_id,
5552 			struct mnt_namespace *ns)
5553 {
5554 	struct path root __free(path_put) = {};
5555 	struct mount *m;
5556 	int err;
5557 
5558 	/* Has the namespace already been emptied? */
5559 	if (mnt_ns_id && RB_EMPTY_ROOT(&ns->mounts))
5560 		return -ENOENT;
5561 
5562 	s->mnt = lookup_mnt_in_ns(mnt_id, ns);
5563 	if (!s->mnt)
5564 		return -ENOENT;
5565 
5566 	err = grab_requested_root(ns, &root);
5567 	if (err)
5568 		return err;
5569 
5570 	/*
5571 	 * Don't trigger audit denials. We just want to determine what
5572 	 * mounts to show users.
5573 	 */
5574 	m = real_mount(s->mnt);
5575 	if (!is_path_reachable(m, m->mnt.mnt_root, &root) &&
5576 	    !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN))
5577 		return -EPERM;
5578 
5579 	err = security_sb_statfs(s->mnt->mnt_root);
5580 	if (err)
5581 		return err;
5582 
5583 	s->root = root;
5584 	s->idmap = mnt_idmap(s->mnt);
5585 	if (s->mask & STATMOUNT_SB_BASIC)
5586 		statmount_sb_basic(s);
5587 
5588 	if (s->mask & STATMOUNT_MNT_BASIC)
5589 		statmount_mnt_basic(s);
5590 
5591 	if (s->mask & STATMOUNT_PROPAGATE_FROM)
5592 		statmount_propagate_from(s);
5593 
5594 	if (s->mask & STATMOUNT_FS_TYPE)
5595 		err = statmount_string(s, STATMOUNT_FS_TYPE);
5596 
5597 	if (!err && s->mask & STATMOUNT_MNT_ROOT)
5598 		err = statmount_string(s, STATMOUNT_MNT_ROOT);
5599 
5600 	if (!err && s->mask & STATMOUNT_MNT_POINT)
5601 		err = statmount_string(s, STATMOUNT_MNT_POINT);
5602 
5603 	if (!err && s->mask & STATMOUNT_MNT_OPTS)
5604 		err = statmount_string(s, STATMOUNT_MNT_OPTS);
5605 
5606 	if (!err && s->mask & STATMOUNT_OPT_ARRAY)
5607 		err = statmount_string(s, STATMOUNT_OPT_ARRAY);
5608 
5609 	if (!err && s->mask & STATMOUNT_OPT_SEC_ARRAY)
5610 		err = statmount_string(s, STATMOUNT_OPT_SEC_ARRAY);
5611 
5612 	if (!err && s->mask & STATMOUNT_FS_SUBTYPE)
5613 		err = statmount_string(s, STATMOUNT_FS_SUBTYPE);
5614 
5615 	if (!err && s->mask & STATMOUNT_SB_SOURCE)
5616 		err = statmount_string(s, STATMOUNT_SB_SOURCE);
5617 
5618 	if (!err && s->mask & STATMOUNT_MNT_UIDMAP)
5619 		err = statmount_string(s, STATMOUNT_MNT_UIDMAP);
5620 
5621 	if (!err && s->mask & STATMOUNT_MNT_GIDMAP)
5622 		err = statmount_string(s, STATMOUNT_MNT_GIDMAP);
5623 
5624 	if (!err && s->mask & STATMOUNT_MNT_NS_ID)
5625 		statmount_mnt_ns_id(s, ns);
5626 
5627 	if (!err && s->mask & STATMOUNT_SUPPORTED_MASK) {
5628 		s->sm.mask |= STATMOUNT_SUPPORTED_MASK;
5629 		s->sm.supported_mask = STATMOUNT_SUPPORTED;
5630 	}
5631 
5632 	if (err)
5633 		return err;
5634 
5635 	/* Are there bits in the return mask not present in STATMOUNT_SUPPORTED? */
5636 	WARN_ON_ONCE(~STATMOUNT_SUPPORTED & s->sm.mask);
5637 
5638 	return 0;
5639 }
5640 
5641 static inline bool retry_statmount(const long ret, size_t *seq_size)
5642 {
5643 	if (likely(ret != -EAGAIN))
5644 		return false;
5645 	if (unlikely(check_mul_overflow(*seq_size, 2, seq_size)))
5646 		return false;
5647 	if (unlikely(*seq_size > MAX_RW_COUNT))
5648 		return false;
5649 	return true;
5650 }
5651 
5652 #define STATMOUNT_STRING_REQ (STATMOUNT_MNT_ROOT | STATMOUNT_MNT_POINT | \
5653 			      STATMOUNT_FS_TYPE | STATMOUNT_MNT_OPTS | \
5654 			      STATMOUNT_FS_SUBTYPE | STATMOUNT_SB_SOURCE | \
5655 			      STATMOUNT_OPT_ARRAY | STATMOUNT_OPT_SEC_ARRAY | \
5656 			      STATMOUNT_MNT_UIDMAP | STATMOUNT_MNT_GIDMAP)
5657 
5658 static int prepare_kstatmount(struct kstatmount *ks, struct mnt_id_req *kreq,
5659 			      struct statmount __user *buf, size_t bufsize,
5660 			      size_t seq_size)
5661 {
5662 	if (!access_ok(buf, bufsize))
5663 		return -EFAULT;
5664 
5665 	memset(ks, 0, sizeof(*ks));
5666 	ks->mask = kreq->param;
5667 	ks->buf = buf;
5668 	ks->bufsize = bufsize;
5669 
5670 	if (ks->mask & STATMOUNT_STRING_REQ) {
5671 		if (bufsize == sizeof(ks->sm))
5672 			return -EOVERFLOW;
5673 
5674 		ks->seq.buf = kvmalloc(seq_size, GFP_KERNEL_ACCOUNT);
5675 		if (!ks->seq.buf)
5676 			return -ENOMEM;
5677 
5678 		ks->seq.size = seq_size;
5679 	}
5680 
5681 	return 0;
5682 }
5683 
5684 static int copy_mnt_id_req(const struct mnt_id_req __user *req,
5685 			   struct mnt_id_req *kreq)
5686 {
5687 	int ret;
5688 	size_t usize;
5689 
5690 	BUILD_BUG_ON(sizeof(struct mnt_id_req) != MNT_ID_REQ_SIZE_VER1);
5691 
5692 	ret = get_user(usize, &req->size);
5693 	if (ret)
5694 		return -EFAULT;
5695 	if (unlikely(usize > PAGE_SIZE))
5696 		return -E2BIG;
5697 	if (unlikely(usize < MNT_ID_REQ_SIZE_VER0))
5698 		return -EINVAL;
5699 	memset(kreq, 0, sizeof(*kreq));
5700 	ret = copy_struct_from_user(kreq, sizeof(*kreq), req, usize);
5701 	if (ret)
5702 		return ret;
5703 	if (kreq->spare != 0)
5704 		return -EINVAL;
5705 	/* The first valid unique mount id is MNT_UNIQUE_ID_OFFSET + 1. */
5706 	if (kreq->mnt_id <= MNT_UNIQUE_ID_OFFSET)
5707 		return -EINVAL;
5708 	return 0;
5709 }
5710 
5711 /*
5712  * If the user requested a specific mount namespace id, look that up and return
5713  * that, or if not simply grab a passive reference on our mount namespace and
5714  * return that.
5715  */
5716 static struct mnt_namespace *grab_requested_mnt_ns(const struct mnt_id_req *kreq)
5717 {
5718 	struct mnt_namespace *mnt_ns;
5719 
5720 	if (kreq->mnt_ns_id && kreq->spare)
5721 		return ERR_PTR(-EINVAL);
5722 
5723 	if (kreq->mnt_ns_id)
5724 		return lookup_mnt_ns(kreq->mnt_ns_id);
5725 
5726 	if (kreq->spare) {
5727 		struct ns_common *ns;
5728 
5729 		CLASS(fd, f)(kreq->spare);
5730 		if (fd_empty(f))
5731 			return ERR_PTR(-EBADF);
5732 
5733 		if (!proc_ns_file(fd_file(f)))
5734 			return ERR_PTR(-EINVAL);
5735 
5736 		ns = get_proc_ns(file_inode(fd_file(f)));
5737 		if (ns->ops->type != CLONE_NEWNS)
5738 			return ERR_PTR(-EINVAL);
5739 
5740 		mnt_ns = to_mnt_ns(ns);
5741 	} else {
5742 		mnt_ns = current->nsproxy->mnt_ns;
5743 	}
5744 
5745 	refcount_inc(&mnt_ns->passive);
5746 	return mnt_ns;
5747 }
5748 
5749 SYSCALL_DEFINE4(statmount, const struct mnt_id_req __user *, req,
5750 		struct statmount __user *, buf, size_t, bufsize,
5751 		unsigned int, flags)
5752 {
5753 	struct mnt_namespace *ns __free(mnt_ns_release) = NULL;
5754 	struct kstatmount *ks __free(kfree) = NULL;
5755 	struct mnt_id_req kreq;
5756 	/* We currently support retrieval of 3 strings. */
5757 	size_t seq_size = 3 * PATH_MAX;
5758 	int ret;
5759 
5760 	if (flags)
5761 		return -EINVAL;
5762 
5763 	ret = copy_mnt_id_req(req, &kreq);
5764 	if (ret)
5765 		return ret;
5766 
5767 	ns = grab_requested_mnt_ns(&kreq);
5768 	if (!ns)
5769 		return -ENOENT;
5770 
5771 	if (kreq.mnt_ns_id && (ns != current->nsproxy->mnt_ns) &&
5772 	    !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN))
5773 		return -ENOENT;
5774 
5775 	ks = kmalloc(sizeof(*ks), GFP_KERNEL_ACCOUNT);
5776 	if (!ks)
5777 		return -ENOMEM;
5778 
5779 retry:
5780 	ret = prepare_kstatmount(ks, &kreq, buf, bufsize, seq_size);
5781 	if (ret)
5782 		return ret;
5783 
5784 	scoped_guard(rwsem_read, &namespace_sem)
5785 		ret = do_statmount(ks, kreq.mnt_id, kreq.mnt_ns_id, ns);
5786 
5787 	if (!ret)
5788 		ret = copy_statmount_to_user(ks);
5789 	kvfree(ks->seq.buf);
5790 	if (retry_statmount(ret, &seq_size))
5791 		goto retry;
5792 	return ret;
5793 }
5794 
5795 static ssize_t do_listmount(struct mnt_namespace *ns, u64 mnt_parent_id,
5796 			    u64 last_mnt_id, u64 *mnt_ids, size_t nr_mnt_ids,
5797 			    bool reverse)
5798 {
5799 	struct path root __free(path_put) = {};
5800 	struct path orig;
5801 	struct mount *r, *first;
5802 	ssize_t ret;
5803 
5804 	rwsem_assert_held(&namespace_sem);
5805 
5806 	ret = grab_requested_root(ns, &root);
5807 	if (ret)
5808 		return ret;
5809 
5810 	if (mnt_parent_id == LSMT_ROOT) {
5811 		orig = root;
5812 	} else {
5813 		orig.mnt = lookup_mnt_in_ns(mnt_parent_id, ns);
5814 		if (!orig.mnt)
5815 			return -ENOENT;
5816 		orig.dentry = orig.mnt->mnt_root;
5817 	}
5818 
5819 	/*
5820 	 * Don't trigger audit denials. We just want to determine what
5821 	 * mounts to show users.
5822 	 */
5823 	if (!is_path_reachable(real_mount(orig.mnt), orig.dentry, &root) &&
5824 	    !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN))
5825 		return -EPERM;
5826 
5827 	ret = security_sb_statfs(orig.dentry);
5828 	if (ret)
5829 		return ret;
5830 
5831 	if (!last_mnt_id) {
5832 		if (reverse)
5833 			first = node_to_mount(ns->mnt_last_node);
5834 		else
5835 			first = node_to_mount(ns->mnt_first_node);
5836 	} else {
5837 		if (reverse)
5838 			first = mnt_find_id_at_reverse(ns, last_mnt_id - 1);
5839 		else
5840 			first = mnt_find_id_at(ns, last_mnt_id + 1);
5841 	}
5842 
5843 	for (ret = 0, r = first; r && nr_mnt_ids; r = listmnt_next(r, reverse)) {
5844 		if (r->mnt_id_unique == mnt_parent_id)
5845 			continue;
5846 		if (!is_path_reachable(r, r->mnt.mnt_root, &orig))
5847 			continue;
5848 		*mnt_ids = r->mnt_id_unique;
5849 		mnt_ids++;
5850 		nr_mnt_ids--;
5851 		ret++;
5852 	}
5853 	return ret;
5854 }
5855 
5856 SYSCALL_DEFINE4(listmount, const struct mnt_id_req __user *, req,
5857 		u64 __user *, mnt_ids, size_t, nr_mnt_ids, unsigned int, flags)
5858 {
5859 	u64 *kmnt_ids __free(kvfree) = NULL;
5860 	const size_t maxcount = 1000000;
5861 	struct mnt_namespace *ns __free(mnt_ns_release) = NULL;
5862 	struct mnt_id_req kreq;
5863 	u64 last_mnt_id;
5864 	ssize_t ret;
5865 
5866 	if (flags & ~LISTMOUNT_REVERSE)
5867 		return -EINVAL;
5868 
5869 	/*
5870 	 * If the mount namespace really has more than 1 million mounts the
5871 	 * caller must iterate over the mount namespace (and reconsider their
5872 	 * system design...).
5873 	 */
5874 	if (unlikely(nr_mnt_ids > maxcount))
5875 		return -EOVERFLOW;
5876 
5877 	if (!access_ok(mnt_ids, nr_mnt_ids * sizeof(*mnt_ids)))
5878 		return -EFAULT;
5879 
5880 	ret = copy_mnt_id_req(req, &kreq);
5881 	if (ret)
5882 		return ret;
5883 
5884 	last_mnt_id = kreq.param;
5885 	/* The first valid unique mount id is MNT_UNIQUE_ID_OFFSET + 1. */
5886 	if (last_mnt_id != 0 && last_mnt_id <= MNT_UNIQUE_ID_OFFSET)
5887 		return -EINVAL;
5888 
5889 	kmnt_ids = kvmalloc_array(nr_mnt_ids, sizeof(*kmnt_ids),
5890 				  GFP_KERNEL_ACCOUNT);
5891 	if (!kmnt_ids)
5892 		return -ENOMEM;
5893 
5894 	ns = grab_requested_mnt_ns(&kreq);
5895 	if (!ns)
5896 		return -ENOENT;
5897 
5898 	if (kreq.mnt_ns_id && (ns != current->nsproxy->mnt_ns) &&
5899 	    !ns_capable_noaudit(ns->user_ns, CAP_SYS_ADMIN))
5900 		return -ENOENT;
5901 
5902 	scoped_guard(rwsem_read, &namespace_sem)
5903 		ret = do_listmount(ns, kreq.mnt_id, last_mnt_id, kmnt_ids,
5904 				   nr_mnt_ids, (flags & LISTMOUNT_REVERSE));
5905 	if (ret <= 0)
5906 		return ret;
5907 
5908 	if (copy_to_user(mnt_ids, kmnt_ids, ret * sizeof(*mnt_ids)))
5909 		return -EFAULT;
5910 
5911 	return ret;
5912 }
5913 
5914 static void __init init_mount_tree(void)
5915 {
5916 	struct vfsmount *mnt;
5917 	struct mount *m;
5918 	struct mnt_namespace *ns;
5919 	struct path root;
5920 
5921 	mnt = vfs_kern_mount(&rootfs_fs_type, 0, "rootfs", NULL);
5922 	if (IS_ERR(mnt))
5923 		panic("Can't create rootfs");
5924 
5925 	ns = alloc_mnt_ns(&init_user_ns, false);
5926 	if (IS_ERR(ns))
5927 		panic("Can't allocate initial namespace");
5928 	m = real_mount(mnt);
5929 	ns->root = m;
5930 	ns->nr_mounts = 1;
5931 	mnt_add_to_ns(ns, m);
5932 	init_task.nsproxy->mnt_ns = ns;
5933 	get_mnt_ns(ns);
5934 
5935 	root.mnt = mnt;
5936 	root.dentry = mnt->mnt_root;
5937 	mnt->mnt_flags |= MNT_LOCKED;
5938 
5939 	set_fs_pwd(current->fs, &root);
5940 	set_fs_root(current->fs, &root);
5941 
5942 	mnt_ns_tree_add(ns);
5943 }
5944 
5945 void __init mnt_init(void)
5946 {
5947 	int err;
5948 
5949 	mnt_cache = kmem_cache_create("mnt_cache", sizeof(struct mount),
5950 			0, SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, NULL);
5951 
5952 	mount_hashtable = alloc_large_system_hash("Mount-cache",
5953 				sizeof(struct hlist_head),
5954 				mhash_entries, 19,
5955 				HASH_ZERO,
5956 				&m_hash_shift, &m_hash_mask, 0, 0);
5957 	mountpoint_hashtable = alloc_large_system_hash("Mountpoint-cache",
5958 				sizeof(struct hlist_head),
5959 				mphash_entries, 19,
5960 				HASH_ZERO,
5961 				&mp_hash_shift, &mp_hash_mask, 0, 0);
5962 
5963 	if (!mount_hashtable || !mountpoint_hashtable)
5964 		panic("Failed to allocate mount hash table\n");
5965 
5966 	kernfs_init();
5967 
5968 	err = sysfs_init();
5969 	if (err)
5970 		printk(KERN_WARNING "%s: sysfs_init error: %d\n",
5971 			__func__, err);
5972 	fs_kobj = kobject_create_and_add("fs", NULL);
5973 	if (!fs_kobj)
5974 		printk(KERN_WARNING "%s: kobj create error\n", __func__);
5975 	shmem_init();
5976 	init_rootfs();
5977 	init_mount_tree();
5978 }
5979 
5980 void put_mnt_ns(struct mnt_namespace *ns)
5981 {
5982 	if (!refcount_dec_and_test(&ns->ns.count))
5983 		return;
5984 	drop_collected_mounts(&ns->root->mnt);
5985 	free_mnt_ns(ns);
5986 }
5987 
5988 struct vfsmount *kern_mount(struct file_system_type *type)
5989 {
5990 	struct vfsmount *mnt;
5991 	mnt = vfs_kern_mount(type, SB_KERNMOUNT, type->name, NULL);
5992 	if (!IS_ERR(mnt)) {
5993 		/*
5994 		 * it is a longterm mount, don't release mnt until
5995 		 * we unmount before file sys is unregistered
5996 		*/
5997 		real_mount(mnt)->mnt_ns = MNT_NS_INTERNAL;
5998 	}
5999 	return mnt;
6000 }
6001 EXPORT_SYMBOL_GPL(kern_mount);
6002 
6003 void kern_unmount(struct vfsmount *mnt)
6004 {
6005 	/* release long term mount so mount point can be released */
6006 	if (!IS_ERR(mnt)) {
6007 		mnt_make_shortterm(mnt);
6008 		synchronize_rcu();	/* yecchhh... */
6009 		mntput(mnt);
6010 	}
6011 }
6012 EXPORT_SYMBOL(kern_unmount);
6013 
6014 void kern_unmount_array(struct vfsmount *mnt[], unsigned int num)
6015 {
6016 	unsigned int i;
6017 
6018 	for (i = 0; i < num; i++)
6019 		mnt_make_shortterm(mnt[i]);
6020 	synchronize_rcu_expedited();
6021 	for (i = 0; i < num; i++)
6022 		mntput(mnt[i]);
6023 }
6024 EXPORT_SYMBOL(kern_unmount_array);
6025 
6026 bool our_mnt(struct vfsmount *mnt)
6027 {
6028 	return check_mnt(real_mount(mnt));
6029 }
6030 
6031 bool current_chrooted(void)
6032 {
6033 	/* Does the current process have a non-standard root */
6034 	struct path ns_root;
6035 	struct path fs_root;
6036 	bool chrooted;
6037 
6038 	/* Find the namespace root */
6039 	ns_root.mnt = &current->nsproxy->mnt_ns->root->mnt;
6040 	ns_root.dentry = ns_root.mnt->mnt_root;
6041 	path_get(&ns_root);
6042 	while (d_mountpoint(ns_root.dentry) && follow_down_one(&ns_root))
6043 		;
6044 
6045 	get_fs_root(current->fs, &fs_root);
6046 
6047 	chrooted = !path_equal(&fs_root, &ns_root);
6048 
6049 	path_put(&fs_root);
6050 	path_put(&ns_root);
6051 
6052 	return chrooted;
6053 }
6054 
6055 static bool mnt_already_visible(struct mnt_namespace *ns,
6056 				const struct super_block *sb,
6057 				int *new_mnt_flags)
6058 {
6059 	int new_flags = *new_mnt_flags;
6060 	struct mount *mnt, *n;
6061 	bool visible = false;
6062 
6063 	down_read(&namespace_sem);
6064 	rbtree_postorder_for_each_entry_safe(mnt, n, &ns->mounts, mnt_node) {
6065 		struct mount *child;
6066 		int mnt_flags;
6067 
6068 		if (mnt->mnt.mnt_sb->s_type != sb->s_type)
6069 			continue;
6070 
6071 		/* This mount is not fully visible if it's root directory
6072 		 * is not the root directory of the filesystem.
6073 		 */
6074 		if (mnt->mnt.mnt_root != mnt->mnt.mnt_sb->s_root)
6075 			continue;
6076 
6077 		/* A local view of the mount flags */
6078 		mnt_flags = mnt->mnt.mnt_flags;
6079 
6080 		/* Don't miss readonly hidden in the superblock flags */
6081 		if (sb_rdonly(mnt->mnt.mnt_sb))
6082 			mnt_flags |= MNT_LOCK_READONLY;
6083 
6084 		/* Verify the mount flags are equal to or more permissive
6085 		 * than the proposed new mount.
6086 		 */
6087 		if ((mnt_flags & MNT_LOCK_READONLY) &&
6088 		    !(new_flags & MNT_READONLY))
6089 			continue;
6090 		if ((mnt_flags & MNT_LOCK_ATIME) &&
6091 		    ((mnt_flags & MNT_ATIME_MASK) != (new_flags & MNT_ATIME_MASK)))
6092 			continue;
6093 
6094 		/* This mount is not fully visible if there are any
6095 		 * locked child mounts that cover anything except for
6096 		 * empty directories.
6097 		 */
6098 		list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
6099 			struct inode *inode = child->mnt_mountpoint->d_inode;
6100 			/* Only worry about locked mounts */
6101 			if (!(child->mnt.mnt_flags & MNT_LOCKED))
6102 				continue;
6103 			/* Is the directory permanently empty? */
6104 			if (!is_empty_dir_inode(inode))
6105 				goto next;
6106 		}
6107 		/* Preserve the locked attributes */
6108 		*new_mnt_flags |= mnt_flags & (MNT_LOCK_READONLY | \
6109 					       MNT_LOCK_ATIME);
6110 		visible = true;
6111 		goto found;
6112 	next:	;
6113 	}
6114 found:
6115 	up_read(&namespace_sem);
6116 	return visible;
6117 }
6118 
6119 static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags)
6120 {
6121 	const unsigned long required_iflags = SB_I_NOEXEC | SB_I_NODEV;
6122 	struct mnt_namespace *ns = current->nsproxy->mnt_ns;
6123 	unsigned long s_iflags;
6124 
6125 	if (ns->user_ns == &init_user_ns)
6126 		return false;
6127 
6128 	/* Can this filesystem be too revealing? */
6129 	s_iflags = sb->s_iflags;
6130 	if (!(s_iflags & SB_I_USERNS_VISIBLE))
6131 		return false;
6132 
6133 	if ((s_iflags & required_iflags) != required_iflags) {
6134 		WARN_ONCE(1, "Expected s_iflags to contain 0x%lx\n",
6135 			  required_iflags);
6136 		return true;
6137 	}
6138 
6139 	return !mnt_already_visible(ns, sb, new_mnt_flags);
6140 }
6141 
6142 bool mnt_may_suid(struct vfsmount *mnt)
6143 {
6144 	/*
6145 	 * Foreign mounts (accessed via fchdir or through /proc
6146 	 * symlinks) are always treated as if they are nosuid.  This
6147 	 * prevents namespaces from trusting potentially unsafe
6148 	 * suid/sgid bits, file caps, or security labels that originate
6149 	 * in other namespaces.
6150 	 */
6151 	return !(mnt->mnt_flags & MNT_NOSUID) && check_mnt(real_mount(mnt)) &&
6152 	       current_in_userns(mnt->mnt_sb->s_user_ns);
6153 }
6154 
6155 static struct ns_common *mntns_get(struct task_struct *task)
6156 {
6157 	struct ns_common *ns = NULL;
6158 	struct nsproxy *nsproxy;
6159 
6160 	task_lock(task);
6161 	nsproxy = task->nsproxy;
6162 	if (nsproxy) {
6163 		ns = &nsproxy->mnt_ns->ns;
6164 		get_mnt_ns(to_mnt_ns(ns));
6165 	}
6166 	task_unlock(task);
6167 
6168 	return ns;
6169 }
6170 
6171 static void mntns_put(struct ns_common *ns)
6172 {
6173 	put_mnt_ns(to_mnt_ns(ns));
6174 }
6175 
6176 static int mntns_install(struct nsset *nsset, struct ns_common *ns)
6177 {
6178 	struct nsproxy *nsproxy = nsset->nsproxy;
6179 	struct fs_struct *fs = nsset->fs;
6180 	struct mnt_namespace *mnt_ns = to_mnt_ns(ns), *old_mnt_ns;
6181 	struct user_namespace *user_ns = nsset->cred->user_ns;
6182 	struct path root;
6183 	int err;
6184 
6185 	if (!ns_capable(mnt_ns->user_ns, CAP_SYS_ADMIN) ||
6186 	    !ns_capable(user_ns, CAP_SYS_CHROOT) ||
6187 	    !ns_capable(user_ns, CAP_SYS_ADMIN))
6188 		return -EPERM;
6189 
6190 	if (is_anon_ns(mnt_ns))
6191 		return -EINVAL;
6192 
6193 	if (fs->users != 1)
6194 		return -EINVAL;
6195 
6196 	get_mnt_ns(mnt_ns);
6197 	old_mnt_ns = nsproxy->mnt_ns;
6198 	nsproxy->mnt_ns = mnt_ns;
6199 
6200 	/* Find the root */
6201 	err = vfs_path_lookup(mnt_ns->root->mnt.mnt_root, &mnt_ns->root->mnt,
6202 				"/", LOOKUP_DOWN, &root);
6203 	if (err) {
6204 		/* revert to old namespace */
6205 		nsproxy->mnt_ns = old_mnt_ns;
6206 		put_mnt_ns(mnt_ns);
6207 		return err;
6208 	}
6209 
6210 	put_mnt_ns(old_mnt_ns);
6211 
6212 	/* Update the pwd and root */
6213 	set_fs_pwd(fs, &root);
6214 	set_fs_root(fs, &root);
6215 
6216 	path_put(&root);
6217 	return 0;
6218 }
6219 
6220 static struct user_namespace *mntns_owner(struct ns_common *ns)
6221 {
6222 	return to_mnt_ns(ns)->user_ns;
6223 }
6224 
6225 const struct proc_ns_operations mntns_operations = {
6226 	.name		= "mnt",
6227 	.type		= CLONE_NEWNS,
6228 	.get		= mntns_get,
6229 	.put		= mntns_put,
6230 	.install	= mntns_install,
6231 	.owner		= mntns_owner,
6232 };
6233 
6234 #ifdef CONFIG_SYSCTL
6235 static const struct ctl_table fs_namespace_sysctls[] = {
6236 	{
6237 		.procname	= "mount-max",
6238 		.data		= &sysctl_mount_max,
6239 		.maxlen		= sizeof(unsigned int),
6240 		.mode		= 0644,
6241 		.proc_handler	= proc_dointvec_minmax,
6242 		.extra1		= SYSCTL_ONE,
6243 	},
6244 };
6245 
6246 static int __init init_fs_namespace_sysctls(void)
6247 {
6248 	register_sysctl_init("fs", fs_namespace_sysctls);
6249 	return 0;
6250 }
6251 fs_initcall(init_fs_namespace_sysctls);
6252 
6253 #endif /* CONFIG_SYSCTL */
6254