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