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