xref: /linux/fs/kernfs/dir.c (revision bb29b957eaaa15be33243550d9ee576c2d601669)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * fs/kernfs/dir.c - kernfs directory implementation
4  *
5  * Copyright (c) 2001-3 Patrick Mochel
6  * Copyright (c) 2007 SUSE Linux Products GmbH
7  * Copyright (c) 2007, 2013 Tejun Heo <tj@kernel.org>
8  */
9 
10 #include <linux/sched.h>
11 #include <linux/fs.h>
12 #include <linux/namei.h>
13 #include <linux/idr.h>
14 #include <linux/slab.h>
15 #include <linux/security.h>
16 #include <linux/hash.h>
17 #include <linux/ns_common.h>
18 
19 #include "kernfs-internal.h"
20 
21 /*
22  * Don't use rename_lock to piggy back on pr_cont_buf. We don't want to
23  * call pr_cont() while holding rename_lock. Because sometimes pr_cont()
24  * will perform wakeups when releasing console_sem. Holding rename_lock
25  * will introduce deadlock if the scheduler reads the kernfs_name in the
26  * wakeup path.
27  */
28 static DEFINE_SPINLOCK(kernfs_pr_cont_lock);
29 static char kernfs_pr_cont_buf[PATH_MAX];	/* protected by pr_cont_lock */
30 
31 #define rb_to_kn(X) rb_entry((X), struct kernfs_node, rb)
32 
33 static void kernfs_activate_one(struct kernfs_node *kn);
34 
35 static bool __kernfs_active(struct kernfs_node *kn)
36 {
37 	return atomic_read(&kn->active) >= 0;
38 }
39 
40 static bool kernfs_active(struct kernfs_node *kn)
41 {
42 	lockdep_assert_held(&kernfs_root(kn)->kernfs_rwsem);
43 	return __kernfs_active(kn);
44 }
45 
46 static bool kernfs_lockdep(struct kernfs_node *kn)
47 {
48 #ifdef CONFIG_DEBUG_LOCK_ALLOC
49 	return kn->flags & KERNFS_LOCKDEP;
50 #else
51 	return false;
52 #endif
53 }
54 
55 /* kernfs_node_depth - compute depth from @from to @to */
56 static size_t kernfs_depth(struct kernfs_node *from, struct kernfs_node *to)
57 {
58 	size_t depth = 0;
59 
60 	while (rcu_dereference(to->__parent) && to != from) {
61 		depth++;
62 		to = rcu_dereference(to->__parent);
63 	}
64 	return depth;
65 }
66 
67 static struct kernfs_node *kernfs_common_ancestor(struct kernfs_node *a,
68 						  struct kernfs_node *b)
69 {
70 	size_t da, db;
71 	struct kernfs_root *ra = kernfs_root(a), *rb = kernfs_root(b);
72 
73 	if (ra != rb)
74 		return NULL;
75 
76 	da = kernfs_depth(ra->kn, a);
77 	db = kernfs_depth(rb->kn, b);
78 
79 	while (da > db) {
80 		a = rcu_dereference(a->__parent);
81 		da--;
82 	}
83 	while (db > da) {
84 		b = rcu_dereference(b->__parent);
85 		db--;
86 	}
87 
88 	/* worst case b and a will be the same at root */
89 	while (b != a) {
90 		b = rcu_dereference(b->__parent);
91 		a = rcu_dereference(a->__parent);
92 	}
93 
94 	return a;
95 }
96 
97 /**
98  * kernfs_path_from_node_locked - find a pseudo-absolute path to @kn_to,
99  * where kn_from is treated as root of the path.
100  * @kn_from: kernfs node which should be treated as root for the path
101  * @kn_to: kernfs node to which path is needed
102  * @buf: buffer to copy the path into
103  * @buflen: size of @buf
104  *
105  * We need to handle couple of scenarios here:
106  * [1] when @kn_from is an ancestor of @kn_to at some level
107  * kn_from: /n1/n2/n3
108  * kn_to:   /n1/n2/n3/n4/n5
109  * result:  /n4/n5
110  *
111  * [2] when @kn_from is on a different hierarchy and we need to find common
112  * ancestor between @kn_from and @kn_to.
113  * kn_from: /n1/n2/n3/n4
114  * kn_to:   /n1/n2/n5
115  * result:  /../../n5
116  * OR
117  * kn_from: /n1/n2/n3/n4/n5   [depth=5]
118  * kn_to:   /n1/n2/n3         [depth=3]
119  * result:  /../..
120  *
121  * [3] when @kn_to is %NULL result will be "(null)"
122  *
123  * Return: the length of the constructed path.  If the path would have been
124  * greater than @buflen, @buf contains the truncated path with the trailing
125  * '\0'.  On error, -errno is returned.
126  */
127 static int kernfs_path_from_node_locked(struct kernfs_node *kn_to,
128 					struct kernfs_node *kn_from,
129 					char *buf, size_t buflen)
130 {
131 	struct kernfs_node *kn, *common;
132 	const char parent_str[] = "/..";
133 	size_t depth_from, depth_to, len = 0;
134 	ssize_t copied;
135 	int i, j;
136 
137 	if (!kn_to)
138 		return strscpy(buf, "(null)", buflen);
139 
140 	if (!kn_from)
141 		kn_from = kernfs_root(kn_to)->kn;
142 
143 	if (kn_from == kn_to)
144 		return strscpy(buf, "/", buflen);
145 
146 	common = kernfs_common_ancestor(kn_from, kn_to);
147 	if (WARN_ON(!common))
148 		return -EINVAL;
149 
150 	depth_to = kernfs_depth(common, kn_to);
151 	depth_from = kernfs_depth(common, kn_from);
152 
153 	buf[0] = '\0';
154 
155 	for (i = 0; i < depth_from; i++) {
156 		copied = strscpy(buf + len, parent_str, buflen - len);
157 		if (copied < 0)
158 			return copied;
159 		len += copied;
160 	}
161 
162 	/* Calculate how many bytes we need for the rest */
163 	for (i = depth_to - 1; i >= 0; i--) {
164 		const char *name;
165 
166 		for (kn = kn_to, j = 0; j < i; j++)
167 			kn = rcu_dereference(kn->__parent);
168 
169 		name = rcu_dereference(kn->name);
170 		len += scnprintf(buf + len, buflen - len, "/%s", name);
171 	}
172 
173 	return len;
174 }
175 
176 /**
177  * kernfs_name - obtain the name of a given node
178  * @kn: kernfs_node of interest
179  * @buf: buffer to copy @kn's name into
180  * @buflen: size of @buf
181  *
182  * Copies the name of @kn into @buf of @buflen bytes.  The behavior is
183  * similar to strscpy().
184  *
185  * Fills buffer with "(null)" if @kn is %NULL.
186  *
187  * Return: the resulting length of @buf. If @buf isn't long enough,
188  * it's filled up to @buflen-1 and nul terminated, and returns -E2BIG.
189  *
190  * This function can be called from any context.
191  */
192 int kernfs_name(struct kernfs_node *kn, char *buf, size_t buflen)
193 {
194 	struct kernfs_node *kn_parent;
195 
196 	if (!kn)
197 		return strscpy(buf, "(null)", buflen);
198 
199 	guard(rcu)();
200 	/*
201 	 * KERNFS_ROOT_INVARIANT_PARENT is ignored here. The name is RCU freed and
202 	 * the parent is either existing or not.
203 	 */
204 	kn_parent = rcu_dereference(kn->__parent);
205 	return strscpy(buf, kn_parent ? rcu_dereference(kn->name) : "/", buflen);
206 }
207 
208 /**
209  * kernfs_path_from_node - build path of node @to relative to @from.
210  * @from: parent kernfs_node relative to which we need to build the path
211  * @to: kernfs_node of interest
212  * @buf: buffer to copy @to's path into
213  * @buflen: size of @buf
214  *
215  * Builds @to's path relative to @from in @buf. @from and @to must
216  * be on the same kernfs-root. If @from is not parent of @to, then a relative
217  * path (which includes '..'s) as needed to reach from @from to @to is
218  * returned.
219  *
220  * Return: the length of the constructed path.  If the path would have been
221  * greater than @buflen, @buf contains the truncated path with the trailing
222  * '\0'.  On error, -errno is returned.
223  */
224 int kernfs_path_from_node(struct kernfs_node *to, struct kernfs_node *from,
225 			  char *buf, size_t buflen)
226 {
227 	struct kernfs_root *root;
228 
229 	guard(rcu)();
230 	if (to) {
231 		root = kernfs_root(to);
232 		if (!(root->flags & KERNFS_ROOT_INVARIANT_PARENT)) {
233 			guard(read_lock_irqsave)(&root->kernfs_rename_lock);
234 			return kernfs_path_from_node_locked(to, from, buf, buflen);
235 		}
236 	}
237 	return kernfs_path_from_node_locked(to, from, buf, buflen);
238 }
239 EXPORT_SYMBOL_GPL(kernfs_path_from_node);
240 
241 /**
242  * pr_cont_kernfs_name - pr_cont name of a kernfs_node
243  * @kn: kernfs_node of interest
244  *
245  * This function can be called from any context.
246  */
247 void pr_cont_kernfs_name(struct kernfs_node *kn)
248 {
249 	unsigned long flags;
250 
251 	spin_lock_irqsave(&kernfs_pr_cont_lock, flags);
252 
253 	kernfs_name(kn, kernfs_pr_cont_buf, sizeof(kernfs_pr_cont_buf));
254 	pr_cont("%s", kernfs_pr_cont_buf);
255 
256 	spin_unlock_irqrestore(&kernfs_pr_cont_lock, flags);
257 }
258 
259 /**
260  * pr_cont_kernfs_path - pr_cont path of a kernfs_node
261  * @kn: kernfs_node of interest
262  *
263  * This function can be called from any context.
264  */
265 void pr_cont_kernfs_path(struct kernfs_node *kn)
266 {
267 	unsigned long flags;
268 	int sz;
269 
270 	spin_lock_irqsave(&kernfs_pr_cont_lock, flags);
271 
272 	sz = kernfs_path_from_node(kn, NULL, kernfs_pr_cont_buf,
273 				   sizeof(kernfs_pr_cont_buf));
274 	if (sz < 0) {
275 		if (sz == -E2BIG)
276 			pr_cont("(name too long)");
277 		else
278 			pr_cont("(error)");
279 		goto out;
280 	}
281 
282 	pr_cont("%s", kernfs_pr_cont_buf);
283 
284 out:
285 	spin_unlock_irqrestore(&kernfs_pr_cont_lock, flags);
286 }
287 
288 /**
289  * kernfs_get_parent - determine the parent node and pin it
290  * @kn: kernfs_node of interest
291  *
292  * Determines @kn's parent, pins and returns it.  This function can be
293  * called from any context.
294  *
295  * Return: parent node of @kn
296  */
297 struct kernfs_node *kernfs_get_parent(struct kernfs_node *kn)
298 {
299 	struct kernfs_node *parent;
300 	struct kernfs_root *root;
301 	unsigned long flags;
302 
303 	root = kernfs_root(kn);
304 	read_lock_irqsave(&root->kernfs_rename_lock, flags);
305 	parent = kernfs_parent(kn);
306 	kernfs_get(parent);
307 	read_unlock_irqrestore(&root->kernfs_rename_lock, flags);
308 
309 	return parent;
310 }
311 
312 /*
313  * kernfs_ns_id - return the namespace id for a given namespace
314  * @ns: namespace tag (may be NULL)
315  *
316  * Use the 64-bit namespace id instead of raw pointers for hashing
317  * and comparison to avoid leaking kernel addresses to userspace.
318  */
319 static u64 kernfs_ns_id(const struct ns_common *ns)
320 {
321 	return ns ? ns->ns_id : 0;
322 }
323 
324 /**
325  *	kernfs_name_hash - calculate hash of @ns + @name
326  *	@name: Null terminated string to hash
327  *	@ns:   Namespace tag to hash
328  *
329  *	Return: 31-bit hash of ns + name (so it fits in an off_t)
330  */
331 static unsigned int kernfs_name_hash(const char *name,
332 				     const struct ns_common *ns)
333 {
334 	unsigned long hash = init_name_hash(kernfs_ns_id(ns));
335 
336 	while (*name)
337 		hash = partial_name_hash(*name++, hash);
338 	hash = end_name_hash(hash);
339 	hash &= 0x7fffffffU;
340 	/* Reserve hash numbers 0, 1 and INT_MAX for magic directory entries */
341 	if (hash < 2)
342 		hash += 2;
343 	if (hash >= INT_MAX)
344 		hash = INT_MAX - 1;
345 	return hash;
346 }
347 
348 static int kernfs_name_compare(unsigned int hash, const char *name,
349 			       const struct ns_common *ns, const struct kernfs_node *kn)
350 {
351 	u64 ns_id = kernfs_ns_id(ns);
352 	u64 kn_ns_id = kernfs_ns_id(kn->ns);
353 
354 	if (hash < kn->hash)
355 		return -1;
356 	if (hash > kn->hash)
357 		return 1;
358 	if (ns_id < kn_ns_id)
359 		return -1;
360 	if (ns_id > kn_ns_id)
361 		return 1;
362 	return strcmp(name, kernfs_rcu_name(kn));
363 }
364 
365 static int kernfs_sd_compare(const struct kernfs_node *left,
366 			     const struct kernfs_node *right)
367 {
368 	return kernfs_name_compare(left->hash, kernfs_rcu_name(left), left->ns, right);
369 }
370 
371 /**
372  *	kernfs_link_sibling - link kernfs_node into sibling rbtree
373  *	@kn: kernfs_node of interest
374  *
375  *	Link @kn into its sibling rbtree which starts from
376  *	@kn->parent->dir.children.
377  *
378  *	Locking:
379  *	kernfs_rwsem held exclusive
380  *
381  *	Return:
382  *	%0 on success, -EEXIST on failure.
383  */
384 static int kernfs_link_sibling(struct kernfs_node *kn)
385 {
386 	struct rb_node *parent = NULL;
387 	struct kernfs_node *kn_parent;
388 	struct rb_node **node;
389 
390 	kn_parent = kernfs_parent(kn);
391 	node = &kn_parent->dir.children.rb_node;
392 
393 	while (*node) {
394 		struct kernfs_node *pos;
395 		int result;
396 
397 		pos = rb_to_kn(*node);
398 		parent = *node;
399 		result = kernfs_sd_compare(kn, pos);
400 		if (result < 0)
401 			node = &pos->rb.rb_left;
402 		else if (result > 0)
403 			node = &pos->rb.rb_right;
404 		else
405 			return -EEXIST;
406 	}
407 
408 	/* add new node and rebalance the tree */
409 	rb_link_node(&kn->rb, parent, node);
410 	rb_insert_color(&kn->rb, &kn_parent->dir.children);
411 
412 	/* successfully added, account subdir number */
413 	down_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
414 	if (kernfs_type(kn) == KERNFS_DIR)
415 		kn_parent->dir.subdirs++;
416 	kernfs_inc_rev(kn_parent);
417 	up_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
418 
419 	return 0;
420 }
421 
422 /**
423  *	kernfs_unlink_sibling - unlink kernfs_node from sibling rbtree
424  *	@kn: kernfs_node of interest
425  *
426  *	Try to unlink @kn from its sibling rbtree which starts from
427  *	kn->parent->dir.children.
428  *
429  *	Return: %true if @kn was actually removed,
430  *	%false if @kn wasn't on the rbtree.
431  *
432  *	Locking:
433  *	kernfs_rwsem held exclusive
434  */
435 static bool kernfs_unlink_sibling(struct kernfs_node *kn)
436 {
437 	struct kernfs_node *kn_parent;
438 
439 	if (RB_EMPTY_NODE(&kn->rb))
440 		return false;
441 
442 	kn_parent = kernfs_parent(kn);
443 	down_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
444 	if (kernfs_type(kn) == KERNFS_DIR)
445 		kn_parent->dir.subdirs--;
446 	kernfs_inc_rev(kn_parent);
447 	up_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
448 
449 	rb_erase(&kn->rb, &kn_parent->dir.children);
450 	RB_CLEAR_NODE(&kn->rb);
451 	return true;
452 }
453 
454 /**
455  *	kernfs_get_active - get an active reference to kernfs_node
456  *	@kn: kernfs_node to get an active reference to
457  *
458  *	Get an active reference of @kn.  This function is noop if @kn
459  *	is %NULL.
460  *
461  *	Return:
462  *	Pointer to @kn on success, %NULL on failure.
463  */
464 struct kernfs_node *kernfs_get_active(struct kernfs_node *kn)
465 {
466 	if (unlikely(!kn))
467 		return NULL;
468 
469 	if (!atomic_inc_unless_negative(&kn->active))
470 		return NULL;
471 
472 	if (kernfs_lockdep(kn))
473 		rwsem_acquire_read(&kn->dep_map, 0, 1, _RET_IP_);
474 	return kn;
475 }
476 
477 /**
478  *	kernfs_put_active - put an active reference to kernfs_node
479  *	@kn: kernfs_node to put an active reference to
480  *
481  *	Put an active reference to @kn.  This function is noop if @kn
482  *	is %NULL.
483  */
484 void kernfs_put_active(struct kernfs_node *kn)
485 {
486 	int v;
487 
488 	if (unlikely(!kn))
489 		return;
490 
491 	if (kernfs_lockdep(kn))
492 		rwsem_release(&kn->dep_map, _RET_IP_);
493 	v = atomic_dec_return(&kn->active);
494 	if (likely(v != KN_DEACTIVATED_BIAS))
495 		return;
496 
497 	wake_up_all(&kernfs_root(kn)->deactivate_waitq);
498 }
499 
500 /**
501  * kernfs_drain - drain kernfs_node
502  * @kn: kernfs_node to drain
503  * @drop_supers: Set to true if this function is called with the
504  *               kernfs_supers_rwsem locked.
505  *
506  * Drain existing usages and nuke all existing mmaps of @kn.  Multiple
507  * removers may invoke this function concurrently on @kn and all will
508  * return after draining is complete.
509  */
510 static void kernfs_drain(struct kernfs_node *kn, bool drop_supers)
511 	__releases(&kernfs_root(kn)->kernfs_rwsem)
512 	__acquires(&kernfs_root(kn)->kernfs_rwsem)
513 {
514 	struct kernfs_root *root = kernfs_root(kn);
515 
516 	lockdep_assert_held_write(&root->kernfs_rwsem);
517 	WARN_ON_ONCE(kernfs_active(kn));
518 
519 	/*
520 	 * Skip draining if already fully drained. This avoids draining and its
521 	 * lockdep annotations for nodes which have never been activated
522 	 * allowing embedding kernfs_remove() in create error paths without
523 	 * worrying about draining.
524 	 */
525 	if (atomic_read(&kn->active) == KN_DEACTIVATED_BIAS &&
526 	    !kernfs_should_drain_open_files(kn))
527 		return;
528 
529 	up_write(&root->kernfs_rwsem);
530 	if (drop_supers)
531 		up_read(&root->kernfs_supers_rwsem);
532 
533 	if (kernfs_lockdep(kn)) {
534 		rwsem_acquire(&kn->dep_map, 0, 0, _RET_IP_);
535 		if (atomic_read(&kn->active) != KN_DEACTIVATED_BIAS)
536 			lock_contended(&kn->dep_map, _RET_IP_);
537 	}
538 
539 	wait_event(root->deactivate_waitq,
540 		   atomic_read(&kn->active) == KN_DEACTIVATED_BIAS);
541 
542 	if (kernfs_lockdep(kn)) {
543 		lock_acquired(&kn->dep_map, _RET_IP_);
544 		rwsem_release(&kn->dep_map, _RET_IP_);
545 	}
546 
547 	if (kernfs_should_drain_open_files(kn))
548 		kernfs_drain_open_files(kn);
549 
550 	if (drop_supers)
551 		down_read(&root->kernfs_supers_rwsem);
552 	down_write(&root->kernfs_rwsem);
553 }
554 
555 /**
556  * kernfs_get - get a reference count on a kernfs_node
557  * @kn: the target kernfs_node
558  */
559 void kernfs_get(struct kernfs_node *kn)
560 {
561 	if (kn) {
562 		WARN_ON(!atomic_read(&kn->count));
563 		atomic_inc(&kn->count);
564 	}
565 }
566 EXPORT_SYMBOL_GPL(kernfs_get);
567 
568 static void kernfs_free_rcu(struct rcu_head *rcu)
569 {
570 	struct kernfs_node *kn = container_of(rcu, struct kernfs_node, rcu);
571 
572 	/* If the whole node goes away, then name can't be used outside */
573 	kfree_const(rcu_access_pointer(kn->name));
574 
575 	if (kn->iattr)
576 		kmem_cache_free(kernfs_iattrs_cache, kn->iattr);
577 
578 	kmem_cache_free(kernfs_node_cache, kn);
579 }
580 
581 /**
582  * kernfs_put - put a reference count on a kernfs_node
583  * @kn: the target kernfs_node
584  *
585  * Put a reference count of @kn and destroy it if it reached zero.
586  */
587 void kernfs_put(struct kernfs_node *kn)
588 {
589 	struct kernfs_node *parent;
590 	struct kernfs_root *root;
591 
592 	if (!kn || !atomic_dec_and_test(&kn->count))
593 		return;
594 	root = kernfs_root(kn);
595  repeat:
596 	/*
597 	 * Moving/renaming is always done while holding reference.
598 	 * kn->parent won't change beneath us.
599 	 */
600 	parent = kernfs_parent(kn);
601 
602 	if (atomic_read(&kn->active) != KN_DEACTIVATED_BIAS) {
603 		guard(rcu)();
604 		WARN_ONCE(1,
605 			  "kernfs_put: %s/%s: released with incorrect active_ref %d\n",
606 			  parent ? rcu_dereference(parent->name) : "",
607 			  rcu_dereference(kn->name), atomic_read(&kn->active));
608 	}
609 
610 	if (kernfs_type(kn) == KERNFS_LINK)
611 		kernfs_put(kn->symlink.target_kn);
612 
613 	if (kn->iattr)
614 		simple_xattrs_free(&root->xa_cache, &kn->iattr->xattrs, NULL);
615 
616 	spin_lock(&root->kernfs_idr_lock);
617 	idr_remove(&root->ino_idr, (u32)kernfs_ino(kn));
618 	spin_unlock(&root->kernfs_idr_lock);
619 
620 	call_rcu(&kn->rcu, kernfs_free_rcu);
621 
622 	kn = parent;
623 	if (kn) {
624 		if (atomic_dec_and_test(&kn->count))
625 			goto repeat;
626 	} else {
627 		/* just released the root kn, free @root too */
628 		idr_destroy(&root->ino_idr);
629 		simple_xattr_cache_cleanup(&root->xa_cache);
630 		kfree_rcu(root, rcu);
631 	}
632 }
633 EXPORT_SYMBOL_GPL(kernfs_put);
634 
635 /**
636  * kernfs_node_from_dentry - determine kernfs_node associated with a dentry
637  * @dentry: the dentry in question
638  *
639  * Return: the kernfs_node associated with @dentry.  If @dentry is not a
640  * kernfs one, %NULL is returned.
641  *
642  * While the returned kernfs_node will stay accessible as long as @dentry
643  * is accessible, the returned node can be in any state and the caller is
644  * fully responsible for determining what's accessible.
645  */
646 struct kernfs_node *kernfs_node_from_dentry(struct dentry *dentry)
647 {
648 	if (dentry->d_sb->s_op == &kernfs_sops)
649 		return kernfs_dentry_node(dentry);
650 	return NULL;
651 }
652 
653 static struct kernfs_node *__kernfs_new_node(struct kernfs_root *root,
654 					     struct kernfs_node *parent,
655 					     const char *name, umode_t mode,
656 					     kuid_t uid, kgid_t gid,
657 					     unsigned flags)
658 {
659 	struct kernfs_node *kn;
660 	u32 id_highbits;
661 	int ret;
662 
663 	name = kstrdup_const(name, GFP_KERNEL);
664 	if (!name)
665 		return NULL;
666 
667 	kn = kmem_cache_zalloc(kernfs_node_cache, GFP_KERNEL);
668 	if (!kn)
669 		goto err_out1;
670 
671 	idr_preload(GFP_KERNEL);
672 	spin_lock(&root->kernfs_idr_lock);
673 	ret = idr_alloc_cyclic(&root->ino_idr, kn, 1, 0, GFP_ATOMIC);
674 	if (ret >= 0 && ret < root->last_id_lowbits)
675 		root->id_highbits++;
676 	id_highbits = root->id_highbits;
677 	root->last_id_lowbits = ret;
678 	spin_unlock(&root->kernfs_idr_lock);
679 	idr_preload_end();
680 	if (ret < 0)
681 		goto err_out2;
682 
683 	kn->id = (u64)id_highbits << 32 | ret;
684 
685 	atomic_set(&kn->count, 1);
686 	atomic_set(&kn->active, KN_DEACTIVATED_BIAS);
687 	RB_CLEAR_NODE(&kn->rb);
688 
689 	rcu_assign_pointer(kn->name, name);
690 	kn->mode = mode;
691 	kn->flags = flags;
692 
693 	if (!uid_eq(uid, GLOBAL_ROOT_UID) || !gid_eq(gid, GLOBAL_ROOT_GID)) {
694 		struct iattr iattr = {
695 			.ia_valid = ATTR_UID | ATTR_GID,
696 			.ia_uid = uid,
697 			.ia_gid = gid,
698 		};
699 
700 		ret = __kernfs_setattr(kn, &iattr);
701 		if (ret < 0)
702 			goto err_out3;
703 	}
704 
705 	if (parent) {
706 		kernfs_get(parent);
707 		rcu_assign_pointer(kn->__parent, parent);
708 
709 		ret = security_kernfs_init_security(parent, kn);
710 		if (ret)
711 			goto err_out4;
712 	}
713 
714 	return kn;
715 
716  err_out4:
717 	RCU_INIT_POINTER(kn->__parent, NULL);
718 	kernfs_put(parent);
719 	if (kn->iattr) {
720 		simple_xattrs_free(&root->xa_cache, &kn->iattr->xattrs, NULL);
721 		kmem_cache_free(kernfs_iattrs_cache, kn->iattr);
722 	}
723  err_out3:
724 	spin_lock(&root->kernfs_idr_lock);
725 	idr_remove(&root->ino_idr, (u32)kernfs_ino(kn));
726 	spin_unlock(&root->kernfs_idr_lock);
727  err_out2:
728 	kmem_cache_free(kernfs_node_cache, kn);
729  err_out1:
730 	kfree_const(name);
731 	return NULL;
732 }
733 
734 struct kernfs_node *kernfs_new_node(struct kernfs_node *parent,
735 				    const char *name, umode_t mode,
736 				    kuid_t uid, kgid_t gid,
737 				    unsigned flags)
738 {
739 	struct kernfs_node *kn;
740 
741 	/*
742 	 * The mode and the gid below are read unlocked on purpose: they feed
743 	 * a node that does not exist yet, so nothing orders a racing chmod or
744 	 * chown against this creation.
745 	 */
746 	if (READ_ONCE(parent->mode) & S_ISGID) {
747 		/* this code block imitates inode_init_owner() for
748 		 * kernfs
749 		 */
750 		struct kernfs_iattrs *attrs = READ_ONCE(parent->iattr);
751 
752 		if (attrs)
753 			gid = READ_ONCE(attrs->ia_gid);
754 
755 		if (flags & KERNFS_DIR)
756 			mode |= S_ISGID;
757 	}
758 
759 	kn = __kernfs_new_node(kernfs_root(parent), parent,
760 			       name, mode, uid, gid, flags);
761 	return kn;
762 }
763 
764 /*
765  * kernfs_find_and_get_node_by_id - get kernfs_node from node id
766  * @root: the kernfs root
767  * @id: the target node id
768  *
769  * @id's lower 32bits encode ino and upper gen.  If the gen portion is
770  * zero, all generations are matched.
771  *
772  * Return: %NULL on failure,
773  * otherwise a kernfs node with reference counter incremented.
774  */
775 struct kernfs_node *kernfs_find_and_get_node_by_id(struct kernfs_root *root,
776 						   u64 id)
777 {
778 	struct kernfs_node *kn;
779 	ino_t ino = kernfs_id_ino(id);
780 	u32 gen = kernfs_id_gen(id);
781 
782 	rcu_read_lock();
783 
784 	kn = idr_find(&root->ino_idr, (u32)ino);
785 	if (!kn)
786 		goto err_unlock;
787 
788 	if (sizeof(ino_t) >= sizeof(u64)) {
789 		/* we looked up with the low 32bits, compare the whole */
790 		if (kernfs_ino(kn) != ino)
791 			goto err_unlock;
792 	} else {
793 		/* 0 matches all generations */
794 		if (unlikely(gen && kernfs_gen(kn) != gen))
795 			goto err_unlock;
796 	}
797 
798 	/*
799 	 * We should fail if @kn has never been activated and guarantee success
800 	 * if the caller knows that @kn is active. Both can be achieved by
801 	 * __kernfs_active() which tests @kn->active without kernfs_rwsem.
802 	 */
803 	if (unlikely(!__kernfs_active(kn) || !atomic_inc_not_zero(&kn->count)))
804 		goto err_unlock;
805 
806 	rcu_read_unlock();
807 	return kn;
808 err_unlock:
809 	rcu_read_unlock();
810 	return NULL;
811 }
812 
813 /**
814  *	kernfs_add_one - add kernfs_node to parent without warning
815  *	@kn: kernfs_node to be added
816  *
817  *	The caller must already have initialized @kn->parent.  This
818  *	function increments nlink of the parent's inode if @kn is a
819  *	directory and link into the children list of the parent.
820  *
821  *	Return:
822  *	%0 on success, -EEXIST if entry with the given name already
823  *	exists.
824  */
825 int kernfs_add_one(struct kernfs_node *kn)
826 {
827 	struct kernfs_root *root = kernfs_root(kn);
828 	struct kernfs_iattrs *ps_iattr;
829 	struct kernfs_node *parent;
830 	bool has_ns;
831 	int ret;
832 
833 	down_write(&root->kernfs_rwsem);
834 	parent = kernfs_parent(kn);
835 
836 	ret = -EINVAL;
837 	has_ns = kernfs_ns_enabled(parent);
838 	if (WARN(has_ns != (bool)kn->ns, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n",
839 		 has_ns ? "required" : "invalid",
840 		 kernfs_rcu_name(parent), kernfs_rcu_name(kn)))
841 		goto out_unlock;
842 
843 	if (kernfs_type(parent) != KERNFS_DIR)
844 		goto out_unlock;
845 
846 	ret = -ENOENT;
847 	if (parent->flags & (KERNFS_REMOVING | KERNFS_EMPTY_DIR))
848 		goto out_unlock;
849 
850 	kn->hash = kernfs_name_hash(kernfs_rcu_name(kn), kn->ns);
851 
852 	ret = kernfs_link_sibling(kn);
853 	if (ret)
854 		goto out_unlock;
855 
856 	/* Update timestamps on the parent */
857 	down_write(&root->kernfs_iattr_rwsem);
858 
859 	ps_iattr = parent->iattr;
860 	if (ps_iattr) {
861 		ktime_get_real_ts64(&ps_iattr->ia_ctime);
862 		ps_iattr->ia_mtime = ps_iattr->ia_ctime;
863 	}
864 
865 	up_write(&root->kernfs_iattr_rwsem);
866 
867 	/*
868 	 * Activate the new node unless CREATE_DEACTIVATED is requested.
869 	 * If not activated here, the kernfs user is responsible for
870 	 * activating the node with kernfs_activate().  A node which hasn't
871 	 * been activated is not visible to userland and its removal won't
872 	 * trigger deactivation.
873 	 *
874 	 * @kn has no children yet, so kernfs_activate() would walk only @kn.
875 	 * Do it here rather than dropping the write lock and taking it again
876 	 * for every new node.
877 	 */
878 	if (!(root->flags & KERNFS_ROOT_CREATE_DEACTIVATED))
879 		kernfs_activate_one(kn);
880 
881 	up_write(&root->kernfs_rwsem);
882 	return 0;
883 
884 out_unlock:
885 	up_write(&root->kernfs_rwsem);
886 	return ret;
887 }
888 
889 /**
890  * kernfs_find_ns - find kernfs_node with the given name
891  * @parent: kernfs_node to search under
892  * @name: name to look for
893  * @ns: the namespace tag to use
894  *
895  * Look for kernfs_node with name @name under @parent.
896  *
897  * Return: pointer to the found kernfs_node on success, %NULL on failure.
898  */
899 static struct kernfs_node *kernfs_find_ns(struct kernfs_node *parent,
900 					  const unsigned char *name,
901 					  const struct ns_common *ns)
902 {
903 	struct rb_node *node = parent->dir.children.rb_node;
904 	bool has_ns = kernfs_ns_enabled(parent);
905 	unsigned int hash;
906 
907 	lockdep_assert_held(&kernfs_root(parent)->kernfs_rwsem);
908 
909 	if (has_ns != (bool)ns) {
910 		WARN(1, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n",
911 		     has_ns ? "required" : "invalid", kernfs_rcu_name(parent), name);
912 		return NULL;
913 	}
914 
915 	hash = kernfs_name_hash(name, ns);
916 	while (node) {
917 		struct kernfs_node *kn;
918 		int result;
919 
920 		kn = rb_to_kn(node);
921 		result = kernfs_name_compare(hash, name, ns, kn);
922 		if (result < 0)
923 			node = node->rb_left;
924 		else if (result > 0)
925 			node = node->rb_right;
926 		else
927 			return kn;
928 	}
929 	return NULL;
930 }
931 
932 static struct kernfs_node *kernfs_walk_ns(struct kernfs_node *parent,
933 					  const unsigned char *path,
934 					  const struct ns_common *ns)
935 {
936 	ssize_t len;
937 	char *p, *name;
938 
939 	lockdep_assert_held_read(&kernfs_root(parent)->kernfs_rwsem);
940 
941 	spin_lock_irq(&kernfs_pr_cont_lock);
942 
943 	len = strscpy(kernfs_pr_cont_buf, path, sizeof(kernfs_pr_cont_buf));
944 
945 	if (len < 0) {
946 		spin_unlock_irq(&kernfs_pr_cont_lock);
947 		return NULL;
948 	}
949 
950 	p = kernfs_pr_cont_buf;
951 
952 	while ((name = strsep(&p, "/")) && parent) {
953 		if (*name == '\0')
954 			continue;
955 		parent = kernfs_find_ns(parent, name, ns);
956 	}
957 
958 	spin_unlock_irq(&kernfs_pr_cont_lock);
959 
960 	return parent;
961 }
962 
963 /**
964  * kernfs_find_and_get_ns - find and get kernfs_node with the given name
965  * @parent: kernfs_node to search under
966  * @name: name to look for
967  * @ns: the namespace tag to use
968  *
969  * Look for kernfs_node with name @name under @parent and get a reference
970  * if found.  This function may sleep.
971  *
972  * Return: pointer to the found kernfs_node on success, %NULL on failure.
973  */
974 struct kernfs_node *kernfs_find_and_get_ns(struct kernfs_node *parent,
975 					   const char *name,
976 					   const struct ns_common *ns)
977 {
978 	struct kernfs_node *kn;
979 	struct kernfs_root *root = kernfs_root(parent);
980 
981 	down_read(&root->kernfs_rwsem);
982 	kn = kernfs_find_ns(parent, name, ns);
983 	kernfs_get(kn);
984 	up_read(&root->kernfs_rwsem);
985 
986 	return kn;
987 }
988 EXPORT_SYMBOL_GPL(kernfs_find_and_get_ns);
989 
990 /**
991  * kernfs_walk_and_get_ns - find and get kernfs_node with the given path
992  * @parent: kernfs_node to search under
993  * @path: path to look for
994  * @ns: the namespace tag to use
995  *
996  * Look for kernfs_node with path @path under @parent and get a reference
997  * if found.  This function may sleep.
998  *
999  * Return: pointer to the found kernfs_node on success, %NULL on failure.
1000  */
1001 struct kernfs_node *kernfs_walk_and_get_ns(struct kernfs_node *parent,
1002 					   const char *path,
1003 					   const struct ns_common *ns)
1004 {
1005 	struct kernfs_node *kn;
1006 	struct kernfs_root *root = kernfs_root(parent);
1007 
1008 	down_read(&root->kernfs_rwsem);
1009 	kn = kernfs_walk_ns(parent, path, ns);
1010 	kernfs_get(kn);
1011 	up_read(&root->kernfs_rwsem);
1012 
1013 	return kn;
1014 }
1015 
1016 unsigned int kernfs_root_flags(struct kernfs_node *kn)
1017 {
1018 	return kernfs_root(kn)->flags;
1019 }
1020 
1021 /**
1022  * kernfs_create_root - create a new kernfs hierarchy
1023  * @scops: optional syscall operations for the hierarchy
1024  * @flags: KERNFS_ROOT_* flags
1025  * @priv: opaque data associated with the new directory
1026  *
1027  * Return: the root of the new hierarchy on success, ERR_PTR() value on
1028  * failure.
1029  */
1030 struct kernfs_root *kernfs_create_root(struct kernfs_syscall_ops *scops,
1031 				       unsigned int flags, void *priv)
1032 {
1033 	struct kernfs_root *root;
1034 	struct kernfs_node *kn;
1035 
1036 	root = kzalloc_obj(*root);
1037 	if (!root)
1038 		return ERR_PTR(-ENOMEM);
1039 
1040 	idr_init(&root->ino_idr);
1041 	spin_lock_init(&root->kernfs_idr_lock);
1042 	init_rwsem(&root->kernfs_rwsem);
1043 	init_rwsem(&root->kernfs_iattr_rwsem);
1044 	init_rwsem(&root->kernfs_supers_rwsem);
1045 	INIT_LIST_HEAD(&root->supers);
1046 	rwlock_init(&root->kernfs_rename_lock);
1047 
1048 	/*
1049 	 * On 64bit ino setups, id is ino.  On 32bit, low 32bits are ino.
1050 	 * High bits generation.  The starting value for both ino and
1051 	 * genenration is 1.  Initialize upper 32bit allocation
1052 	 * accordingly.
1053 	 */
1054 	if (sizeof(ino_t) >= sizeof(u64))
1055 		root->id_highbits = 0;
1056 	else
1057 		root->id_highbits = 1;
1058 
1059 	kn = __kernfs_new_node(root, NULL, "", S_IFDIR | S_IRUGO | S_IXUGO,
1060 			       GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
1061 			       KERNFS_DIR);
1062 	if (!kn) {
1063 		idr_destroy(&root->ino_idr);
1064 		kfree(root);
1065 		return ERR_PTR(-ENOMEM);
1066 	}
1067 
1068 	kn->priv = priv;
1069 	kn->dir.root = root;
1070 
1071 	root->syscall_ops = scops;
1072 	root->flags = flags;
1073 	root->kn = kn;
1074 	init_waitqueue_head(&root->deactivate_waitq);
1075 
1076 	if (!(root->flags & KERNFS_ROOT_CREATE_DEACTIVATED))
1077 		kernfs_activate(kn);
1078 
1079 	return root;
1080 }
1081 
1082 /**
1083  * kernfs_destroy_root - destroy a kernfs hierarchy
1084  * @root: root of the hierarchy to destroy
1085  *
1086  * Destroy the hierarchy anchored at @root by removing all existing
1087  * directories and destroying @root.
1088  */
1089 void kernfs_destroy_root(struct kernfs_root *root)
1090 {
1091 	/*
1092 	 *  kernfs_remove holds kernfs_rwsem from the root so the root
1093 	 *  shouldn't be freed during the operation.
1094 	 */
1095 	kernfs_get(root->kn);
1096 	kernfs_remove(root->kn);
1097 	kernfs_put(root->kn); /* will also free @root */
1098 }
1099 
1100 /**
1101  * kernfs_root_to_node - return the kernfs_node associated with a kernfs_root
1102  * @root: root to use to lookup
1103  *
1104  * Return: @root's kernfs_node
1105  */
1106 struct kernfs_node *kernfs_root_to_node(struct kernfs_root *root)
1107 {
1108 	return root->kn;
1109 }
1110 
1111 /**
1112  * kernfs_create_dir_ns - create a directory
1113  * @parent: parent in which to create a new directory
1114  * @name: name of the new directory
1115  * @mode: mode of the new directory
1116  * @uid: uid of the new directory
1117  * @gid: gid of the new directory
1118  * @priv: opaque data associated with the new directory
1119  * @ns: optional namespace tag of the directory
1120  *
1121  * Return: the created node on success, ERR_PTR() value on failure.
1122  */
1123 struct kernfs_node *kernfs_create_dir_ns(struct kernfs_node *parent,
1124 					 const char *name, umode_t mode,
1125 					 kuid_t uid, kgid_t gid,
1126 					 void *priv,
1127 					 const struct ns_common *ns)
1128 {
1129 	struct kernfs_node *kn;
1130 	int rc;
1131 
1132 	/* allocate */
1133 	kn = kernfs_new_node(parent, name, mode | S_IFDIR,
1134 			     uid, gid, KERNFS_DIR);
1135 	if (!kn)
1136 		return ERR_PTR(-ENOMEM);
1137 
1138 	kn->dir.root = parent->dir.root;
1139 	kn->ns = ns;
1140 	kn->priv = priv;
1141 
1142 	/* link in */
1143 	rc = kernfs_add_one(kn);
1144 	if (!rc)
1145 		return kn;
1146 
1147 	kernfs_put(kn);
1148 	return ERR_PTR(rc);
1149 }
1150 
1151 /**
1152  * kernfs_create_empty_dir - create an always empty directory
1153  * @parent: parent in which to create a new directory
1154  * @name: name of the new directory
1155  *
1156  * Return: the created node on success, ERR_PTR() value on failure.
1157  */
1158 struct kernfs_node *kernfs_create_empty_dir(struct kernfs_node *parent,
1159 					    const char *name)
1160 {
1161 	struct kernfs_node *kn;
1162 	int rc;
1163 
1164 	/* allocate */
1165 	kn = kernfs_new_node(parent, name, S_IRUGO|S_IXUGO|S_IFDIR,
1166 			     GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, KERNFS_DIR);
1167 	if (!kn)
1168 		return ERR_PTR(-ENOMEM);
1169 
1170 	kn->flags |= KERNFS_EMPTY_DIR;
1171 	kn->dir.root = parent->dir.root;
1172 	kn->ns = NULL;
1173 	kn->priv = NULL;
1174 
1175 	/* link in */
1176 	rc = kernfs_add_one(kn);
1177 	if (!rc)
1178 		return kn;
1179 
1180 	kernfs_put(kn);
1181 	return ERR_PTR(rc);
1182 }
1183 
1184 static int kernfs_dop_revalidate(struct inode *dir, const struct qstr *name,
1185 				 struct dentry *dentry, unsigned int flags)
1186 {
1187 	struct kernfs_node *parent = dir->i_private;
1188 	struct kernfs_node *kn;
1189 	const char *kn_name;
1190 
1191 	if (flags & LOOKUP_RCU)
1192 		return -ECHILD;
1193 
1194 	/* Negative hashed dentry? */
1195 	if (d_really_is_negative(dentry)) {
1196 		/*
1197 		 * If the kernfs parent node has changed discard and proceed to
1198 		 * ->lookup.
1199 		 *
1200 		 * Also kernfs negative dentries transitioning from
1201 		 * negative to positive during revalidate won't happen
1202 		 * because they are invalidated on containing directory
1203 		 * changes and the lookup re-done so that a new positive
1204 		 * dentry can be properly created.
1205 		 */
1206 		return !kernfs_dir_changed(parent, dentry);
1207 	}
1208 
1209 	kn = kernfs_dentry_node(dentry);
1210 
1211 	guard(rcu)();
1212 
1213 	/* The kernfs node has been deactivated */
1214 	if (!__kernfs_active(kn))
1215 		return 0;
1216 
1217 	/* The kernfs node has been moved? */
1218 	if (kernfs_parent(kn) != parent)
1219 		return 0;
1220 
1221 	/* The kernfs node has been renamed */
1222 	kn_name = kernfs_rcu_name(kn);
1223 	if (name->len != strlen(kn_name) ||
1224 	    memcmp(name->name, kn_name, name->len))
1225 		return 0;
1226 
1227 	/*
1228 	 * The kernfs node has been moved to a different namespace.
1229 	 *
1230 	 * KERNFS_NS is set by kernfs_enable_ns() while @parent still has no
1231 	 * children, so it cannot change while a child of @parent is being
1232 	 * revalidated. The other bits in that word, KERNFS_ACTIVATED and
1233 	 * KERNFS_REMOVING, are updated under kernfs_rwsem and are not read
1234 	 * here, so racing with them is intentional and harmless.
1235 	 */
1236 	if (data_race(kernfs_ns_enabled(parent)) &&
1237 	    kernfs_info(dir->i_sb)->ns != READ_ONCE(kn->ns))
1238 		return 0;
1239 
1240 	return 1;
1241 }
1242 
1243 const struct dentry_operations kernfs_dops = {
1244 	.d_revalidate	= kernfs_dop_revalidate,
1245 };
1246 
1247 static struct dentry *kernfs_iop_lookup(struct inode *dir,
1248 					struct dentry *dentry,
1249 					unsigned int flags)
1250 {
1251 	struct kernfs_node *parent = dir->i_private;
1252 	struct kernfs_node *kn;
1253 	struct kernfs_root *root;
1254 	struct inode *inode = NULL;
1255 	const struct ns_common *ns = NULL;
1256 
1257 	root = kernfs_root(parent);
1258 	down_read(&root->kernfs_rwsem);
1259 	if (kernfs_ns_enabled(parent))
1260 		ns = kernfs_info(dir->i_sb)->ns;
1261 
1262 	kn = kernfs_find_ns(parent, dentry->d_name.name, ns);
1263 	/* attach dentry and inode */
1264 	if (kn) {
1265 		/* Inactive nodes are invisible to the VFS so don't
1266 		 * create a negative.
1267 		 */
1268 		if (!kernfs_active(kn)) {
1269 			up_read(&root->kernfs_rwsem);
1270 			return NULL;
1271 		}
1272 		inode = kernfs_get_inode(dir->i_sb, kn);
1273 		if (!inode)
1274 			inode = ERR_PTR(-ENOMEM);
1275 	}
1276 	/*
1277 	 * Needed for negative dentry validation.
1278 	 * The negative dentry can be created in kernfs_iop_lookup()
1279 	 * or transforms from positive dentry in dentry_unlink_inode()
1280 	 * called from vfs_rmdir().
1281 	 */
1282 	if (!IS_ERR(inode))
1283 		kernfs_set_rev(parent, dentry);
1284 	up_read(&root->kernfs_rwsem);
1285 
1286 	/* instantiate and hash (possibly negative) dentry */
1287 	return d_splice_alias(inode, dentry);
1288 }
1289 
1290 static struct dentry *kernfs_iop_mkdir(const struct mnt_idmap *idmap,
1291 				       struct inode *dir, struct dentry *dentry,
1292 				       umode_t mode)
1293 {
1294 	struct kernfs_node *parent = dir->i_private;
1295 	struct kernfs_syscall_ops *scops = kernfs_root(parent)->syscall_ops;
1296 	int ret;
1297 
1298 	if (!scops || !scops->mkdir)
1299 		return ERR_PTR(-EPERM);
1300 
1301 	if (!kernfs_get_active(parent))
1302 		return ERR_PTR(-ENODEV);
1303 
1304 	ret = scops->mkdir(parent, dentry->d_name.name, mode);
1305 
1306 	kernfs_put_active(parent);
1307 	return ERR_PTR(ret);
1308 }
1309 
1310 static int kernfs_iop_rmdir(struct inode *dir, struct dentry *dentry)
1311 {
1312 	struct kernfs_node *kn  = kernfs_dentry_node(dentry);
1313 	struct kernfs_syscall_ops *scops = kernfs_root(kn)->syscall_ops;
1314 	int ret;
1315 
1316 	if (!scops || !scops->rmdir)
1317 		return -EPERM;
1318 
1319 	if (!kernfs_get_active(kn))
1320 		return -ENODEV;
1321 
1322 	ret = scops->rmdir(kn);
1323 
1324 	kernfs_put_active(kn);
1325 	return ret;
1326 }
1327 
1328 static int kernfs_iop_rename(const struct mnt_idmap *idmap,
1329 			     struct inode *old_dir, struct dentry *old_dentry,
1330 			     struct inode *new_dir, struct dentry *new_dentry,
1331 			     unsigned int flags)
1332 {
1333 	struct kernfs_node *kn = kernfs_dentry_node(old_dentry);
1334 	struct kernfs_node *new_parent = new_dir->i_private;
1335 	struct kernfs_syscall_ops *scops = kernfs_root(kn)->syscall_ops;
1336 	int ret;
1337 
1338 	if (flags)
1339 		return -EINVAL;
1340 
1341 	if (!scops || !scops->rename)
1342 		return -EPERM;
1343 
1344 	if (!kernfs_get_active(kn))
1345 		return -ENODEV;
1346 
1347 	if (!kernfs_get_active(new_parent)) {
1348 		kernfs_put_active(kn);
1349 		return -ENODEV;
1350 	}
1351 
1352 	ret = scops->rename(kn, new_parent, new_dentry->d_name.name);
1353 
1354 	kernfs_put_active(new_parent);
1355 	kernfs_put_active(kn);
1356 	return ret;
1357 }
1358 
1359 const struct inode_operations kernfs_dir_iops = {
1360 	.lookup		= kernfs_iop_lookup,
1361 	.permission	= kernfs_iop_permission,
1362 	.setattr	= kernfs_iop_setattr,
1363 	.getattr	= kernfs_iop_getattr,
1364 	.listxattr	= kernfs_iop_listxattr,
1365 
1366 	.mkdir		= kernfs_iop_mkdir,
1367 	.rmdir		= kernfs_iop_rmdir,
1368 	.rename		= kernfs_iop_rename,
1369 };
1370 
1371 static struct kernfs_node *kernfs_leftmost_descendant(struct kernfs_node *pos)
1372 {
1373 	struct kernfs_node *last;
1374 
1375 	while (true) {
1376 		struct rb_node *rbn;
1377 
1378 		last = pos;
1379 
1380 		if (kernfs_type(pos) != KERNFS_DIR)
1381 			break;
1382 
1383 		rbn = rb_first(&pos->dir.children);
1384 		if (!rbn)
1385 			break;
1386 
1387 		pos = rb_to_kn(rbn);
1388 	}
1389 
1390 	return last;
1391 }
1392 
1393 /**
1394  * kernfs_next_descendant_post - find the next descendant for post-order walk
1395  * @pos: the current position (%NULL to initiate traversal)
1396  * @root: kernfs_node whose descendants to walk
1397  *
1398  * Find the next descendant to visit for post-order traversal of @root's
1399  * descendants.  @root is included in the iteration and the last node to be
1400  * visited.
1401  *
1402  * Return: the next descendant to visit or %NULL when done.
1403  */
1404 static struct kernfs_node *kernfs_next_descendant_post(struct kernfs_node *pos,
1405 						       struct kernfs_node *root)
1406 {
1407 	struct rb_node *rbn;
1408 
1409 	lockdep_assert_held_write(&kernfs_root(root)->kernfs_rwsem);
1410 
1411 	/* if first iteration, visit leftmost descendant which may be root */
1412 	if (!pos)
1413 		return kernfs_leftmost_descendant(root);
1414 
1415 	/* if we visited @root, we're done */
1416 	if (pos == root)
1417 		return NULL;
1418 
1419 	/* if there's an unvisited sibling, visit its leftmost descendant */
1420 	rbn = rb_next(&pos->rb);
1421 	if (rbn)
1422 		return kernfs_leftmost_descendant(rb_to_kn(rbn));
1423 
1424 	/* no sibling left, visit parent */
1425 	return kernfs_parent(pos);
1426 }
1427 
1428 static void kernfs_activate_one(struct kernfs_node *kn)
1429 {
1430 	lockdep_assert_held_write(&kernfs_root(kn)->kernfs_rwsem);
1431 
1432 	kn->flags |= KERNFS_ACTIVATED;
1433 
1434 	if (kernfs_active(kn) || (kn->flags & (KERNFS_HIDDEN | KERNFS_REMOVING)))
1435 		return;
1436 
1437 	WARN_ON_ONCE(rcu_access_pointer(kn->__parent) && RB_EMPTY_NODE(&kn->rb));
1438 	WARN_ON_ONCE(atomic_read(&kn->active) != KN_DEACTIVATED_BIAS);
1439 
1440 	atomic_sub(KN_DEACTIVATED_BIAS, &kn->active);
1441 }
1442 
1443 /**
1444  * kernfs_activate - activate a node which started deactivated
1445  * @kn: kernfs_node whose subtree is to be activated
1446  *
1447  * If the root has KERNFS_ROOT_CREATE_DEACTIVATED set, a newly created node
1448  * needs to be explicitly activated.  A node which hasn't been activated
1449  * isn't visible to userland and deactivation is skipped during its
1450  * removal.  This is useful to construct atomic init sequences where
1451  * creation of multiple nodes should either succeed or fail atomically.
1452  *
1453  * The caller is responsible for ensuring that this function is not called
1454  * after kernfs_remove*() is invoked on @kn.
1455  */
1456 void kernfs_activate(struct kernfs_node *kn)
1457 {
1458 	struct kernfs_node *pos;
1459 	struct kernfs_root *root = kernfs_root(kn);
1460 
1461 	down_write(&root->kernfs_rwsem);
1462 
1463 	pos = NULL;
1464 	while ((pos = kernfs_next_descendant_post(pos, kn)))
1465 		kernfs_activate_one(pos);
1466 
1467 	up_write(&root->kernfs_rwsem);
1468 }
1469 
1470 /**
1471  * kernfs_show - show or hide a node
1472  * @kn: kernfs_node to show or hide
1473  * @show: whether to show or hide
1474  *
1475  * If @show is %false, @kn is marked hidden and deactivated. A hidden node is
1476  * ignored in future activaitons. If %true, the mark is removed and activation
1477  * state is restored. This function won't implicitly activate a new node in a
1478  * %KERNFS_ROOT_CREATE_DEACTIVATED root which hasn't been activated yet.
1479  *
1480  * To avoid recursion complexities, directories aren't supported for now.
1481  */
1482 void kernfs_show(struct kernfs_node *kn, bool show)
1483 {
1484 	struct kernfs_root *root = kernfs_root(kn);
1485 
1486 	if (WARN_ON_ONCE(kernfs_type(kn) == KERNFS_DIR))
1487 		return;
1488 
1489 	down_write(&root->kernfs_rwsem);
1490 
1491 	if (show) {
1492 		kn->flags &= ~KERNFS_HIDDEN;
1493 		if (kn->flags & KERNFS_ACTIVATED)
1494 			kernfs_activate_one(kn);
1495 	} else {
1496 		kn->flags |= KERNFS_HIDDEN;
1497 		if (kernfs_active(kn))
1498 			atomic_add(KN_DEACTIVATED_BIAS, &kn->active);
1499 		kernfs_drain(kn, false);
1500 	}
1501 
1502 	up_write(&root->kernfs_rwsem);
1503 }
1504 
1505 /*
1506  * This function enables VFS to send fsnotify events for deletions.
1507  * There is gap in this implementation for certain file removals due their
1508  * unique nature in kernfs. Directory removals that trigger file removals occur
1509  * through vfs_rmdir, which shrinks the dcache and emits fsnotify events after
1510  * the rmdir operation; there is no issue here. However kernfs writes to
1511  * particular files (e.g. cgroup.subtree_control) can also cause file removal,
1512  * but vfs_write does not attempt to emit fsnotify events after the write
1513  * operation, even if i_nlink counts are 0. As a usecase for monitoring this
1514  * category of file removals is not known, they are left without having
1515  * IN_DELETE or IN_DELETE_SELF events generated.
1516  * Fanotify recursive monitoring also does not work for kernfs nodes that do not
1517  * have inodes attached, as they are created on-demand in kernfs.
1518  */
1519 static void kernfs_clear_inode_nlink(struct kernfs_node *kn)
1520 {
1521 	struct kernfs_root *root = kernfs_root(kn);
1522 	struct kernfs_super_info *info;
1523 
1524 	lockdep_assert_held_read(&root->kernfs_supers_rwsem);
1525 
1526 	list_for_each_entry(info, &root->supers, node) {
1527 		struct inode *inode = ilookup(info->sb, kernfs_ino(kn));
1528 
1529 		if (inode) {
1530 			clear_nlink(inode);
1531 			iput(inode);
1532 		}
1533 	}
1534 }
1535 
1536 static void __kernfs_remove(struct kernfs_node *kn)
1537 {
1538 	struct kernfs_node *pos, *parent;
1539 
1540 	/* Short-circuit if non-root @kn has already finished removal. */
1541 	if (!kn)
1542 		return;
1543 
1544 	lockdep_assert_held_read(&kernfs_root(kn)->kernfs_supers_rwsem);
1545 	lockdep_assert_held_write(&kernfs_root(kn)->kernfs_rwsem);
1546 
1547 	/*
1548 	 * This is for kernfs_remove_self() which plays with active ref
1549 	 * after removal.
1550 	 */
1551 	if (kernfs_parent(kn) && RB_EMPTY_NODE(&kn->rb))
1552 		return;
1553 
1554 	pr_debug("kernfs %s: removing\n", kernfs_rcu_name(kn));
1555 
1556 	/* prevent new usage by marking all nodes removing and deactivating */
1557 	down_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
1558 	pos = NULL;
1559 	while ((pos = kernfs_next_descendant_post(pos, kn))) {
1560 		pos->flags |= KERNFS_REMOVING;
1561 		if (kernfs_active(pos))
1562 			atomic_add(KN_DEACTIVATED_BIAS, &pos->active);
1563 	}
1564 	up_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
1565 
1566 	/* deactivate and unlink the subtree node-by-node */
1567 	do {
1568 		pos = kernfs_leftmost_descendant(kn);
1569 
1570 		/*
1571 		 * kernfs_drain() may drop kernfs_rwsem temporarily and @pos's
1572 		 * base ref could have been put by someone else by the time
1573 		 * the function returns.  Make sure it doesn't go away
1574 		 * underneath us.
1575 		 */
1576 		kernfs_get(pos);
1577 
1578 		kernfs_drain(pos, true);
1579 		parent = kernfs_parent(pos);
1580 		/*
1581 		 * kernfs_unlink_sibling() succeeds once per node.  Use it
1582 		 * to decide who's responsible for cleanups.
1583 		 */
1584 		if (!parent || kernfs_unlink_sibling(pos)) {
1585 			struct kernfs_iattrs *ps_iattr =
1586 				parent ? parent->iattr : NULL;
1587 
1588 			down_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
1589 
1590 			kernfs_clear_inode_nlink(pos);
1591 
1592 			/* update timestamps on the parent */
1593 			if (ps_iattr) {
1594 				ktime_get_real_ts64(&ps_iattr->ia_ctime);
1595 				ps_iattr->ia_mtime = ps_iattr->ia_ctime;
1596 			}
1597 
1598 			up_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
1599 			kernfs_put(pos);
1600 		}
1601 
1602 		kernfs_put(pos);
1603 	} while (pos != kn);
1604 }
1605 
1606 /**
1607  * kernfs_remove - remove a kernfs_node recursively
1608  * @kn: the kernfs_node to remove
1609  *
1610  * Remove @kn along with all its subdirectories and files.
1611  */
1612 void kernfs_remove(struct kernfs_node *kn)
1613 {
1614 	struct kernfs_root *root;
1615 
1616 	if (!kn)
1617 		return;
1618 
1619 	root = kernfs_root(kn);
1620 
1621 	down_read(&root->kernfs_supers_rwsem);
1622 	down_write(&root->kernfs_rwsem);
1623 	__kernfs_remove(kn);
1624 	up_write(&root->kernfs_rwsem);
1625 	up_read(&root->kernfs_supers_rwsem);
1626 }
1627 
1628 /**
1629  * kernfs_break_active_protection - break out of active protection
1630  * @kn: the self kernfs_node
1631  *
1632  * The caller must be running off of a kernfs operation which is invoked
1633  * with an active reference - e.g. one of kernfs_ops.  Each invocation of
1634  * this function must also be matched with an invocation of
1635  * kernfs_unbreak_active_protection().
1636  *
1637  * This function releases the active reference of @kn the caller is
1638  * holding.  Once this function is called, @kn may be removed at any point
1639  * and the caller is solely responsible for ensuring that the objects it
1640  * dereferences are accessible.
1641  */
1642 void kernfs_break_active_protection(struct kernfs_node *kn)
1643 {
1644 	/*
1645 	 * Take out ourself out of the active ref dependency chain.  If
1646 	 * we're called without an active ref, lockdep will complain.
1647 	 */
1648 	kernfs_put_active(kn);
1649 }
1650 
1651 /**
1652  * kernfs_unbreak_active_protection - undo kernfs_break_active_protection()
1653  * @kn: the self kernfs_node
1654  *
1655  * If kernfs_break_active_protection() was called, this function must be
1656  * invoked before finishing the kernfs operation.  Note that while this
1657  * function restores the active reference, it doesn't and can't actually
1658  * restore the active protection - @kn may already or be in the process of
1659  * being drained and removed.  Once kernfs_break_active_protection() is
1660  * invoked, that protection is irreversibly gone for the kernfs operation
1661  * instance.
1662  *
1663  * While this function may be called at any point after
1664  * kernfs_break_active_protection() is invoked, its most useful location
1665  * would be right before the enclosing kernfs operation returns.
1666  */
1667 void kernfs_unbreak_active_protection(struct kernfs_node *kn)
1668 {
1669 	/*
1670 	 * @kn->active could be in any state; however, the increment we do
1671 	 * here will be undone as soon as the enclosing kernfs operation
1672 	 * finishes and this temporary bump can't break anything.  If @kn
1673 	 * is alive, nothing changes.  If @kn is being deactivated, the
1674 	 * soon-to-follow put will either finish deactivation or restore
1675 	 * deactivated state.  If @kn is already removed, the temporary
1676 	 * bump is guaranteed to be gone before @kn is released.
1677 	 */
1678 	atomic_inc(&kn->active);
1679 	if (kernfs_lockdep(kn))
1680 		rwsem_acquire(&kn->dep_map, 0, 1, _RET_IP_);
1681 }
1682 
1683 /**
1684  * kernfs_remove_self - remove a kernfs_node from its own method
1685  * @kn: the self kernfs_node to remove
1686  *
1687  * The caller must be running off of a kernfs operation which is invoked
1688  * with an active reference - e.g. one of kernfs_ops.  This can be used to
1689  * implement a file operation which deletes itself.
1690  *
1691  * For example, the "delete" file for a sysfs device directory can be
1692  * implemented by invoking kernfs_remove_self() on the "delete" file
1693  * itself.  This function breaks the circular dependency of trying to
1694  * deactivate self while holding an active ref itself.  It isn't necessary
1695  * to modify the usual removal path to use kernfs_remove_self().  The
1696  * "delete" implementation can simply invoke kernfs_remove_self() on self
1697  * before proceeding with the usual removal path.  kernfs will ignore later
1698  * kernfs_remove() on self.
1699  *
1700  * kernfs_remove_self() can be called multiple times concurrently on the
1701  * same kernfs_node.  Only the first one actually performs removal and
1702  * returns %true.  All others will wait until the kernfs operation which
1703  * won self-removal finishes and return %false.  Note that the losers wait
1704  * for the completion of not only the winning kernfs_remove_self() but also
1705  * the whole kernfs_ops which won the arbitration.  This can be used to
1706  * guarantee, for example, all concurrent writes to a "delete" file to
1707  * finish only after the whole operation is complete.
1708  *
1709  * Return: %true if @kn is removed by this call, otherwise %false.
1710  */
1711 bool kernfs_remove_self(struct kernfs_node *kn)
1712 {
1713 	bool ret;
1714 	struct kernfs_root *root = kernfs_root(kn);
1715 
1716 	down_read(&root->kernfs_supers_rwsem);
1717 	down_write(&root->kernfs_rwsem);
1718 	kernfs_break_active_protection(kn);
1719 
1720 	/*
1721 	 * SUICIDAL is used to arbitrate among competing invocations.  Only
1722 	 * the first one will actually perform removal.  When the removal
1723 	 * is complete, SUICIDED is set and the active ref is restored
1724 	 * while kernfs_rwsem for held exclusive.  The ones which lost
1725 	 * arbitration waits for SUICIDED && drained which can happen only
1726 	 * after the enclosing kernfs operation which executed the winning
1727 	 * instance of kernfs_remove_self() finished.
1728 	 */
1729 	if (!(kn->flags & KERNFS_SUICIDAL)) {
1730 		kn->flags |= KERNFS_SUICIDAL;
1731 		__kernfs_remove(kn);
1732 		kn->flags |= KERNFS_SUICIDED;
1733 		ret = true;
1734 	} else {
1735 		wait_queue_head_t *waitq = &kernfs_root(kn)->deactivate_waitq;
1736 		DEFINE_WAIT(wait);
1737 
1738 		while (true) {
1739 			prepare_to_wait(waitq, &wait, TASK_UNINTERRUPTIBLE);
1740 
1741 			if ((kn->flags & KERNFS_SUICIDED) &&
1742 			    atomic_read(&kn->active) == KN_DEACTIVATED_BIAS)
1743 				break;
1744 
1745 			up_write(&root->kernfs_rwsem);
1746 			up_read(&root->kernfs_supers_rwsem);
1747 			schedule();
1748 			down_read(&root->kernfs_supers_rwsem);
1749 			down_write(&root->kernfs_rwsem);
1750 		}
1751 		finish_wait(waitq, &wait);
1752 		WARN_ON_ONCE(!RB_EMPTY_NODE(&kn->rb));
1753 		ret = false;
1754 	}
1755 
1756 	/*
1757 	 * This must be done while kernfs_rwsem held exclusive; otherwise,
1758 	 * waiting for SUICIDED && deactivated could finish prematurely.
1759 	 */
1760 	kernfs_unbreak_active_protection(kn);
1761 
1762 	up_write(&root->kernfs_rwsem);
1763 	up_read(&root->kernfs_supers_rwsem);
1764 	return ret;
1765 }
1766 
1767 /**
1768  * kernfs_remove_by_name_ns - find a kernfs_node by name and remove it
1769  * @parent: parent of the target
1770  * @name: name of the kernfs_node to remove
1771  * @ns: namespace tag of the kernfs_node to remove
1772  *
1773  * Look for the kernfs_node with @name and @ns under @parent and remove it.
1774  *
1775  * Return: %0 on success, -ENOENT if such entry doesn't exist.
1776  */
1777 int kernfs_remove_by_name_ns(struct kernfs_node *parent, const char *name,
1778 			     const struct ns_common *ns)
1779 {
1780 	struct kernfs_node *kn;
1781 	struct kernfs_root *root;
1782 
1783 	if (!parent) {
1784 		WARN(1, KERN_WARNING "kernfs: can not remove '%s', no directory\n",
1785 			name);
1786 		return -ENOENT;
1787 	}
1788 
1789 	root = kernfs_root(parent);
1790 	down_read(&root->kernfs_supers_rwsem);
1791 	down_write(&root->kernfs_rwsem);
1792 
1793 	kn = kernfs_find_ns(parent, name, ns);
1794 	if (kn) {
1795 		kernfs_get(kn);
1796 		__kernfs_remove(kn);
1797 		kernfs_put(kn);
1798 	}
1799 
1800 	up_write(&root->kernfs_rwsem);
1801 	up_read(&root->kernfs_supers_rwsem);
1802 
1803 	if (kn)
1804 		return 0;
1805 	else
1806 		return -ENOENT;
1807 }
1808 
1809 /**
1810  * kernfs_rename_ns - move and rename a kernfs_node
1811  * @kn: target node
1812  * @new_parent: new parent to put @sd under
1813  * @new_name: new name
1814  * @new_ns: new namespace tag
1815  *
1816  * Return: %0 on success, -errno on failure.
1817  */
1818 int kernfs_rename_ns(struct kernfs_node *kn, struct kernfs_node *new_parent,
1819 		     const char *new_name, const struct ns_common *new_ns)
1820 {
1821 	struct kernfs_node *old_parent;
1822 	const char *dup_name = NULL;
1823 	const char *put_name = NULL;
1824 	struct kernfs_root *root;
1825 	const char *old_name;
1826 	bool reparent;
1827 	int error;
1828 
1829 	/* can't move or rename root */
1830 	if (!rcu_access_pointer(kn->__parent))
1831 		return -EINVAL;
1832 
1833 	if (new_name)
1834 		dup_name = kstrdup_const(new_name, GFP_KERNEL);
1835 
1836 	root = kernfs_root(kn);
1837 	down_write(&root->kernfs_rwsem);
1838 
1839 	error = -ENOENT;
1840 	if (!kernfs_active(kn) || !kernfs_active(new_parent) ||
1841 	    (new_parent->flags & KERNFS_EMPTY_DIR))
1842 		goto out;
1843 
1844 	old_parent = kernfs_parent(kn);
1845 	if (root->flags & KERNFS_ROOT_INVARIANT_PARENT) {
1846 		error = -EINVAL;
1847 		if (WARN_ON_ONCE(old_parent != new_parent))
1848 			goto out;
1849 	}
1850 
1851 	error = 0;
1852 	old_name = kernfs_rcu_name(kn);
1853 	if (!new_name)
1854 		new_name = old_name;
1855 	if ((old_parent == new_parent) &&
1856 	    (kernfs_ns_id(kn->ns) == kernfs_ns_id(new_ns)) &&
1857 	    (strcmp(old_name, new_name) == 0))
1858 		goto out;	/* nothing to rename */
1859 
1860 	error = -EEXIST;
1861 	if (kernfs_find_ns(new_parent, new_name, new_ns))
1862 		goto out;
1863 
1864 	/* rename kernfs_node */
1865 	if (strcmp(old_name, new_name) != 0) {
1866 		error = -ENOMEM;
1867 		if (!dup_name)
1868 			goto out;
1869 		new_name = dup_name;
1870 		dup_name = NULL;
1871 	} else {
1872 		new_name = NULL;
1873 	}
1874 
1875 	/*
1876 	 * Move to the appropriate place in the appropriate directories rbtree.
1877 	 */
1878 	kernfs_unlink_sibling(kn);
1879 
1880 	reparent = old_parent != new_parent;
1881 	if (reparent)
1882 		kernfs_get(new_parent);
1883 
1884 	/*
1885 	 * kernfs_rename_lock protects ->__parent, ->ns and ->name, so take it
1886 	 * even when the parent does not change.
1887 	 */
1888 	write_lock_irq(&root->kernfs_rename_lock);
1889 
1890 	if (reparent)
1891 		rcu_assign_pointer(kn->__parent, new_parent);
1892 	WRITE_ONCE(kn->ns, new_ns);
1893 	if (new_name)
1894 		rcu_assign_pointer(kn->name, new_name);
1895 
1896 	write_unlock_irq(&root->kernfs_rename_lock);
1897 
1898 	if (reparent)
1899 		kernfs_put(old_parent);
1900 
1901 	kn->hash = kernfs_name_hash(new_name ?: old_name, kn->ns);
1902 	kernfs_link_sibling(kn);
1903 
1904 	if (new_name && !is_kernel_rodata((unsigned long)old_name))
1905 		put_name = old_name;
1906 
1907 	error = 0;
1908  out:
1909 	up_write(&root->kernfs_rwsem);
1910 	kfree_const(dup_name);
1911 	if (put_name)
1912 		kfree_rcu_mightsleep(put_name);
1913 	return error;
1914 }
1915 
1916 static int kernfs_dir_fop_release(struct inode *inode, struct file *filp)
1917 {
1918 	kernfs_put(filp->private_data);
1919 	return 0;
1920 }
1921 
1922 /*
1923  * Find where a listing left off.  @resumed says whether @pos is still that
1924  * entry; if not, the search falls back to @hash, keyed by @name if given.
1925  */
1926 static struct kernfs_node *kernfs_dir_pos(const struct ns_common *ns,
1927 	struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos,
1928 	const char *name, bool *resumed)
1929 {
1930 	if (resumed)
1931 		*resumed = false;
1932 	if (pos) {
1933 		/*
1934 		 * A rename keeps the hash if the new name hashes the same, so
1935 		 * check @name too.  Otherwise the caller would step over the
1936 		 * entry now sitting where @pos used to be.
1937 		 */
1938 		int valid = kernfs_active(pos) &&
1939 			rcu_access_pointer(pos->__parent) == parent &&
1940 			hash == pos->hash &&
1941 			(!name || !strcmp(name, kernfs_rcu_name(pos)));
1942 		kernfs_put(pos);
1943 		if (!valid)
1944 			pos = NULL;
1945 		else if (resumed)
1946 			*resumed = true;
1947 	}
1948 	if (!pos && (hash > 1) && (hash < INT_MAX)) {
1949 		struct rb_node *node = parent->dir.children.rb_node;
1950 
1951 		/*
1952 		 * Keep a node only on the way left, so the search ends on the
1953 		 * first entry after the key.  An empty @name sorts before all
1954 		 * entries sharing the hash, so it lands on the first of them.
1955 		 */
1956 		while (node) {
1957 			struct kernfs_node *kn = rb_to_kn(node);
1958 
1959 			if (kernfs_name_compare(hash, name ?: "", ns, kn) < 0) {
1960 				pos = kn;
1961 				node = node->rb_left;
1962 			} else {
1963 				node = node->rb_right;
1964 			}
1965 		}
1966 	}
1967 	/* Skip over entries which are dying/dead or in the wrong namespace */
1968 	while (pos && (!kernfs_active(pos) ||
1969 		       kernfs_ns_id(pos->ns) != kernfs_ns_id(ns))) {
1970 		struct rb_node *node = rb_next(&pos->rb);
1971 		if (!node)
1972 			pos = NULL;
1973 		else
1974 			pos = rb_to_kn(node);
1975 	}
1976 	return pos;
1977 }
1978 
1979 static struct kernfs_node *kernfs_dir_next_pos(const struct ns_common *ns,
1980 	struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos,
1981 	const char *name)
1982 {
1983 	bool resumed;
1984 
1985 	pos = kernfs_dir_pos(ns, parent, hash, pos, name, &resumed);
1986 	/* Step over @pos only if it survived; @name finds the spot if not. */
1987 	if (pos && resumed) {
1988 		do {
1989 			struct rb_node *node = rb_next(&pos->rb);
1990 			if (!node)
1991 				pos = NULL;
1992 			else
1993 				pos = rb_to_kn(node);
1994 		} while (pos && (!kernfs_active(pos) ||
1995 			kernfs_ns_id(pos->ns) != kernfs_ns_id(ns)));
1996 	}
1997 	return pos;
1998 }
1999 
2000 static int kernfs_fop_readdir(struct file *file, struct dir_context *ctx)
2001 {
2002 	struct dentry *dentry = file->f_path.dentry;
2003 	struct kernfs_node *parent = kernfs_dentry_node(dentry);
2004 	struct kernfs_node *pos = file->private_data;
2005 	char *name __free(kfree) = NULL;
2006 	struct kernfs_root *root;
2007 	const struct ns_common *ns = NULL;
2008 
2009 	if (!dir_emit_dots(file, ctx))
2010 		return 0;
2011 
2012 	/*
2013 	 * One buffer for the call, holding the name of the entry the listing
2014 	 * is on.  PATH_MAX: kernfs bounds no single name.
2015 	 */
2016 	name = kmalloc(PATH_MAX, GFP_KERNEL);
2017 	if (!name)
2018 		return -ENOMEM;
2019 
2020 	root = kernfs_root(parent);
2021 	down_read(&root->kernfs_rwsem);
2022 
2023 	if (kernfs_ns_enabled(parent))
2024 		ns = kernfs_info(dentry->d_sb)->ns;
2025 
2026 	for (pos = kernfs_dir_pos(ns, parent, ctx->pos, pos, NULL, NULL);
2027 	     pos;
2028 	     pos = kernfs_dir_next_pos(ns, parent, ctx->pos, pos, name)) {
2029 		unsigned int type = fs_umode_to_dtype(pos->mode);
2030 		ino_t ino = kernfs_ino(pos);
2031 		int len;
2032 
2033 		/*
2034 		 * The copy is also the resume key, so a truncated name would
2035 		 * resume here again.  getname() caps a path, so only an
2036 		 * in-kernel caller can get here; end the listing instead.
2037 		 */
2038 		len = strscpy(name, kernfs_rcu_name(pos), PATH_MAX);
2039 		if (WARN_ON_ONCE(len < 0))
2040 			break;
2041 
2042 		ctx->pos = pos->hash;
2043 		file->private_data = pos;
2044 		kernfs_get(pos);
2045 
2046 		/*
2047 		 * dir_emit() can fault, so run it unlocked.  @pos is pinned
2048 		 * above and kernfs_dir_pos() rechecks it on the way back.
2049 		 */
2050 		up_read(&root->kernfs_rwsem);
2051 		if (!dir_emit(ctx, name, len, ino, type))
2052 			return 0;
2053 		down_read(&root->kernfs_rwsem);
2054 	}
2055 	up_read(&root->kernfs_rwsem);
2056 	file->private_data = NULL;
2057 	ctx->pos = INT_MAX;
2058 	return 0;
2059 }
2060 
2061 const struct file_operations kernfs_dir_fops = {
2062 	.read		= generic_read_dir,
2063 	.iterate_shared	= kernfs_fop_readdir,
2064 	.release	= kernfs_dir_fop_release,
2065 	.llseek		= generic_file_llseek,
2066 };
2067