xref: /linux/fs/kernfs/dir.c (revision c8db08110cbeff12a1f3990a31730936b092f62b)
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  *
502  * Drain existing usages and nuke all existing mmaps of @kn.  Multiple
503  * removers may invoke this function concurrently on @kn and all will
504  * return after draining is complete.
505  */
506 static void kernfs_drain(struct kernfs_node *kn)
507 	__releases(&kernfs_root(kn)->kernfs_rwsem)
508 	__acquires(&kernfs_root(kn)->kernfs_rwsem)
509 {
510 	struct kernfs_root *root = kernfs_root(kn);
511 
512 	lockdep_assert_held_write(&root->kernfs_rwsem);
513 	WARN_ON_ONCE(kernfs_active(kn));
514 
515 	/*
516 	 * Skip draining if already fully drained. This avoids draining and its
517 	 * lockdep annotations for nodes which have never been activated
518 	 * allowing embedding kernfs_remove() in create error paths without
519 	 * worrying about draining.
520 	 */
521 	if (atomic_read(&kn->active) == KN_DEACTIVATED_BIAS &&
522 	    !kernfs_should_drain_open_files(kn))
523 		return;
524 
525 	up_write(&root->kernfs_rwsem);
526 
527 	if (kernfs_lockdep(kn)) {
528 		rwsem_acquire(&kn->dep_map, 0, 0, _RET_IP_);
529 		if (atomic_read(&kn->active) != KN_DEACTIVATED_BIAS)
530 			lock_contended(&kn->dep_map, _RET_IP_);
531 	}
532 
533 	wait_event(root->deactivate_waitq,
534 		   atomic_read(&kn->active) == KN_DEACTIVATED_BIAS);
535 
536 	if (kernfs_lockdep(kn)) {
537 		lock_acquired(&kn->dep_map, _RET_IP_);
538 		rwsem_release(&kn->dep_map, _RET_IP_);
539 	}
540 
541 	if (kernfs_should_drain_open_files(kn))
542 		kernfs_drain_open_files(kn);
543 
544 	down_write(&root->kernfs_rwsem);
545 }
546 
547 /**
548  * kernfs_get - get a reference count on a kernfs_node
549  * @kn: the target kernfs_node
550  */
551 void kernfs_get(struct kernfs_node *kn)
552 {
553 	if (kn) {
554 		WARN_ON(!atomic_read(&kn->count));
555 		atomic_inc(&kn->count);
556 	}
557 }
558 EXPORT_SYMBOL_GPL(kernfs_get);
559 
560 static void kernfs_free_rcu(struct rcu_head *rcu)
561 {
562 	struct kernfs_node *kn = container_of(rcu, struct kernfs_node, rcu);
563 
564 	/* If the whole node goes away, then name can't be used outside */
565 	kfree_const(rcu_access_pointer(kn->name));
566 
567 	if (kn->iattr)
568 		kmem_cache_free(kernfs_iattrs_cache, kn->iattr);
569 
570 	kmem_cache_free(kernfs_node_cache, kn);
571 }
572 
573 /**
574  * kernfs_put - put a reference count on a kernfs_node
575  * @kn: the target kernfs_node
576  *
577  * Put a reference count of @kn and destroy it if it reached zero.
578  */
579 void kernfs_put(struct kernfs_node *kn)
580 {
581 	struct kernfs_node *parent;
582 	struct kernfs_root *root;
583 
584 	if (!kn || !atomic_dec_and_test(&kn->count))
585 		return;
586 	root = kernfs_root(kn);
587  repeat:
588 	/*
589 	 * Moving/renaming is always done while holding reference.
590 	 * kn->parent won't change beneath us.
591 	 */
592 	parent = kernfs_parent(kn);
593 
594 	WARN_ONCE(atomic_read(&kn->active) != KN_DEACTIVATED_BIAS,
595 		  "kernfs_put: %s/%s: released with incorrect active_ref %d\n",
596 		  parent ? rcu_dereference(parent->name) : "",
597 		  rcu_dereference(kn->name), atomic_read(&kn->active));
598 
599 	if (kernfs_type(kn) == KERNFS_LINK)
600 		kernfs_put(kn->symlink.target_kn);
601 
602 	if (kn->iattr && kn->iattr->xattrs) {
603 		simple_xattrs_free(kn->iattr->xattrs, NULL);
604 		kfree(kn->iattr->xattrs);
605 		kn->iattr->xattrs = NULL;
606 	}
607 
608 	spin_lock(&root->kernfs_idr_lock);
609 	idr_remove(&root->ino_idr, (u32)kernfs_ino(kn));
610 	spin_unlock(&root->kernfs_idr_lock);
611 
612 	call_rcu(&kn->rcu, kernfs_free_rcu);
613 
614 	kn = parent;
615 	if (kn) {
616 		if (atomic_dec_and_test(&kn->count))
617 			goto repeat;
618 	} else {
619 		/* just released the root kn, free @root too */
620 		idr_destroy(&root->ino_idr);
621 		kfree_rcu(root, rcu);
622 	}
623 }
624 EXPORT_SYMBOL_GPL(kernfs_put);
625 
626 /**
627  * kernfs_node_from_dentry - determine kernfs_node associated with a dentry
628  * @dentry: the dentry in question
629  *
630  * Return: the kernfs_node associated with @dentry.  If @dentry is not a
631  * kernfs one, %NULL is returned.
632  *
633  * While the returned kernfs_node will stay accessible as long as @dentry
634  * is accessible, the returned node can be in any state and the caller is
635  * fully responsible for determining what's accessible.
636  */
637 struct kernfs_node *kernfs_node_from_dentry(struct dentry *dentry)
638 {
639 	if (dentry->d_sb->s_op == &kernfs_sops)
640 		return kernfs_dentry_node(dentry);
641 	return NULL;
642 }
643 
644 static struct kernfs_node *__kernfs_new_node(struct kernfs_root *root,
645 					     struct kernfs_node *parent,
646 					     const char *name, umode_t mode,
647 					     kuid_t uid, kgid_t gid,
648 					     unsigned flags)
649 {
650 	struct kernfs_node *kn;
651 	u32 id_highbits;
652 	int ret;
653 
654 	name = kstrdup_const(name, GFP_KERNEL);
655 	if (!name)
656 		return NULL;
657 
658 	kn = kmem_cache_zalloc(kernfs_node_cache, GFP_KERNEL);
659 	if (!kn)
660 		goto err_out1;
661 
662 	idr_preload(GFP_KERNEL);
663 	spin_lock(&root->kernfs_idr_lock);
664 	ret = idr_alloc_cyclic(&root->ino_idr, kn, 1, 0, GFP_ATOMIC);
665 	if (ret >= 0 && ret < root->last_id_lowbits)
666 		root->id_highbits++;
667 	id_highbits = root->id_highbits;
668 	root->last_id_lowbits = ret;
669 	spin_unlock(&root->kernfs_idr_lock);
670 	idr_preload_end();
671 	if (ret < 0)
672 		goto err_out2;
673 
674 	kn->id = (u64)id_highbits << 32 | ret;
675 
676 	atomic_set(&kn->count, 1);
677 	atomic_set(&kn->active, KN_DEACTIVATED_BIAS);
678 	RB_CLEAR_NODE(&kn->rb);
679 
680 	rcu_assign_pointer(kn->name, name);
681 	kn->mode = mode;
682 	kn->flags = flags;
683 
684 	if (!uid_eq(uid, GLOBAL_ROOT_UID) || !gid_eq(gid, GLOBAL_ROOT_GID)) {
685 		struct iattr iattr = {
686 			.ia_valid = ATTR_UID | ATTR_GID,
687 			.ia_uid = uid,
688 			.ia_gid = gid,
689 		};
690 
691 		ret = __kernfs_setattr(kn, &iattr);
692 		if (ret < 0)
693 			goto err_out3;
694 	}
695 
696 	if (parent) {
697 		ret = security_kernfs_init_security(parent, kn);
698 		if (ret)
699 			goto err_out4;
700 	}
701 
702 	return kn;
703 
704  err_out4:
705 	if (kn->iattr) {
706 		if (kn->iattr->xattrs) {
707 			simple_xattrs_free(kn->iattr->xattrs, NULL);
708 			kfree(kn->iattr->xattrs);
709 		}
710 		kmem_cache_free(kernfs_iattrs_cache, kn->iattr);
711 	}
712  err_out3:
713 	spin_lock(&root->kernfs_idr_lock);
714 	idr_remove(&root->ino_idr, (u32)kernfs_ino(kn));
715 	spin_unlock(&root->kernfs_idr_lock);
716  err_out2:
717 	kmem_cache_free(kernfs_node_cache, kn);
718  err_out1:
719 	kfree_const(name);
720 	return NULL;
721 }
722 
723 struct kernfs_node *kernfs_new_node(struct kernfs_node *parent,
724 				    const char *name, umode_t mode,
725 				    kuid_t uid, kgid_t gid,
726 				    unsigned flags)
727 {
728 	struct kernfs_node *kn;
729 
730 	if (parent->mode & S_ISGID) {
731 		/* this code block imitates inode_init_owner() for
732 		 * kernfs
733 		 */
734 
735 		if (parent->iattr)
736 			gid = parent->iattr->ia_gid;
737 
738 		if (flags & KERNFS_DIR)
739 			mode |= S_ISGID;
740 	}
741 
742 	kn = __kernfs_new_node(kernfs_root(parent), parent,
743 			       name, mode, uid, gid, flags);
744 	if (kn) {
745 		kernfs_get(parent);
746 		rcu_assign_pointer(kn->__parent, parent);
747 	}
748 	return kn;
749 }
750 
751 /*
752  * kernfs_find_and_get_node_by_id - get kernfs_node from node id
753  * @root: the kernfs root
754  * @id: the target node id
755  *
756  * @id's lower 32bits encode ino and upper gen.  If the gen portion is
757  * zero, all generations are matched.
758  *
759  * Return: %NULL on failure,
760  * otherwise a kernfs node with reference counter incremented.
761  */
762 struct kernfs_node *kernfs_find_and_get_node_by_id(struct kernfs_root *root,
763 						   u64 id)
764 {
765 	struct kernfs_node *kn;
766 	ino_t ino = kernfs_id_ino(id);
767 	u32 gen = kernfs_id_gen(id);
768 
769 	rcu_read_lock();
770 
771 	kn = idr_find(&root->ino_idr, (u32)ino);
772 	if (!kn)
773 		goto err_unlock;
774 
775 	if (sizeof(ino_t) >= sizeof(u64)) {
776 		/* we looked up with the low 32bits, compare the whole */
777 		if (kernfs_ino(kn) != ino)
778 			goto err_unlock;
779 	} else {
780 		/* 0 matches all generations */
781 		if (unlikely(gen && kernfs_gen(kn) != gen))
782 			goto err_unlock;
783 	}
784 
785 	/*
786 	 * We should fail if @kn has never been activated and guarantee success
787 	 * if the caller knows that @kn is active. Both can be achieved by
788 	 * __kernfs_active() which tests @kn->active without kernfs_rwsem.
789 	 */
790 	if (unlikely(!__kernfs_active(kn) || !atomic_inc_not_zero(&kn->count)))
791 		goto err_unlock;
792 
793 	rcu_read_unlock();
794 	return kn;
795 err_unlock:
796 	rcu_read_unlock();
797 	return NULL;
798 }
799 
800 /**
801  *	kernfs_add_one - add kernfs_node to parent without warning
802  *	@kn: kernfs_node to be added
803  *
804  *	The caller must already have initialized @kn->parent.  This
805  *	function increments nlink of the parent's inode if @kn is a
806  *	directory and link into the children list of the parent.
807  *
808  *	Return:
809  *	%0 on success, -EEXIST if entry with the given name already
810  *	exists.
811  */
812 int kernfs_add_one(struct kernfs_node *kn)
813 {
814 	struct kernfs_root *root = kernfs_root(kn);
815 	struct kernfs_iattrs *ps_iattr;
816 	struct kernfs_node *parent;
817 	bool has_ns;
818 	int ret;
819 
820 	down_write(&root->kernfs_rwsem);
821 	parent = kernfs_parent(kn);
822 
823 	ret = -EINVAL;
824 	has_ns = kernfs_ns_enabled(parent);
825 	if (WARN(has_ns != (bool)kn->ns, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n",
826 		 has_ns ? "required" : "invalid",
827 		 kernfs_rcu_name(parent), kernfs_rcu_name(kn)))
828 		goto out_unlock;
829 
830 	if (kernfs_type(parent) != KERNFS_DIR)
831 		goto out_unlock;
832 
833 	ret = -ENOENT;
834 	if (parent->flags & (KERNFS_REMOVING | KERNFS_EMPTY_DIR))
835 		goto out_unlock;
836 
837 	kn->hash = kernfs_name_hash(kernfs_rcu_name(kn), kn->ns);
838 
839 	ret = kernfs_link_sibling(kn);
840 	if (ret)
841 		goto out_unlock;
842 
843 	/* Update timestamps on the parent */
844 	down_write(&root->kernfs_iattr_rwsem);
845 
846 	ps_iattr = parent->iattr;
847 	if (ps_iattr) {
848 		ktime_get_real_ts64(&ps_iattr->ia_ctime);
849 		ps_iattr->ia_mtime = ps_iattr->ia_ctime;
850 	}
851 
852 	up_write(&root->kernfs_iattr_rwsem);
853 	up_write(&root->kernfs_rwsem);
854 
855 	/*
856 	 * Activate the new node unless CREATE_DEACTIVATED is requested.
857 	 * If not activated here, the kernfs user is responsible for
858 	 * activating the node with kernfs_activate().  A node which hasn't
859 	 * been activated is not visible to userland and its removal won't
860 	 * trigger deactivation.
861 	 */
862 	if (!(kernfs_root(kn)->flags & KERNFS_ROOT_CREATE_DEACTIVATED))
863 		kernfs_activate(kn);
864 	return 0;
865 
866 out_unlock:
867 	up_write(&root->kernfs_rwsem);
868 	return ret;
869 }
870 
871 /**
872  * kernfs_find_ns - find kernfs_node with the given name
873  * @parent: kernfs_node to search under
874  * @name: name to look for
875  * @ns: the namespace tag to use
876  *
877  * Look for kernfs_node with name @name under @parent.
878  *
879  * Return: pointer to the found kernfs_node on success, %NULL on failure.
880  */
881 static struct kernfs_node *kernfs_find_ns(struct kernfs_node *parent,
882 					  const unsigned char *name,
883 					  const struct ns_common *ns)
884 {
885 	struct rb_node *node = parent->dir.children.rb_node;
886 	bool has_ns = kernfs_ns_enabled(parent);
887 	unsigned int hash;
888 
889 	lockdep_assert_held(&kernfs_root(parent)->kernfs_rwsem);
890 
891 	if (has_ns != (bool)ns) {
892 		WARN(1, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n",
893 		     has_ns ? "required" : "invalid", kernfs_rcu_name(parent), name);
894 		return NULL;
895 	}
896 
897 	hash = kernfs_name_hash(name, ns);
898 	while (node) {
899 		struct kernfs_node *kn;
900 		int result;
901 
902 		kn = rb_to_kn(node);
903 		result = kernfs_name_compare(hash, name, ns, kn);
904 		if (result < 0)
905 			node = node->rb_left;
906 		else if (result > 0)
907 			node = node->rb_right;
908 		else
909 			return kn;
910 	}
911 	return NULL;
912 }
913 
914 static struct kernfs_node *kernfs_walk_ns(struct kernfs_node *parent,
915 					  const unsigned char *path,
916 					  const struct ns_common *ns)
917 {
918 	ssize_t len;
919 	char *p, *name;
920 
921 	lockdep_assert_held_read(&kernfs_root(parent)->kernfs_rwsem);
922 
923 	spin_lock_irq(&kernfs_pr_cont_lock);
924 
925 	len = strscpy(kernfs_pr_cont_buf, path, sizeof(kernfs_pr_cont_buf));
926 
927 	if (len < 0) {
928 		spin_unlock_irq(&kernfs_pr_cont_lock);
929 		return NULL;
930 	}
931 
932 	p = kernfs_pr_cont_buf;
933 
934 	while ((name = strsep(&p, "/")) && parent) {
935 		if (*name == '\0')
936 			continue;
937 		parent = kernfs_find_ns(parent, name, ns);
938 	}
939 
940 	spin_unlock_irq(&kernfs_pr_cont_lock);
941 
942 	return parent;
943 }
944 
945 /**
946  * kernfs_find_and_get_ns - find and get kernfs_node with the given name
947  * @parent: kernfs_node to search under
948  * @name: name to look for
949  * @ns: the namespace tag to use
950  *
951  * Look for kernfs_node with name @name under @parent and get a reference
952  * if found.  This function may sleep.
953  *
954  * Return: pointer to the found kernfs_node on success, %NULL on failure.
955  */
956 struct kernfs_node *kernfs_find_and_get_ns(struct kernfs_node *parent,
957 					   const char *name,
958 					   const struct ns_common *ns)
959 {
960 	struct kernfs_node *kn;
961 	struct kernfs_root *root = kernfs_root(parent);
962 
963 	down_read(&root->kernfs_rwsem);
964 	kn = kernfs_find_ns(parent, name, ns);
965 	kernfs_get(kn);
966 	up_read(&root->kernfs_rwsem);
967 
968 	return kn;
969 }
970 EXPORT_SYMBOL_GPL(kernfs_find_and_get_ns);
971 
972 /**
973  * kernfs_walk_and_get_ns - find and get kernfs_node with the given path
974  * @parent: kernfs_node to search under
975  * @path: path to look for
976  * @ns: the namespace tag to use
977  *
978  * Look for kernfs_node with path @path under @parent and get a reference
979  * if found.  This function may sleep.
980  *
981  * Return: pointer to the found kernfs_node on success, %NULL on failure.
982  */
983 struct kernfs_node *kernfs_walk_and_get_ns(struct kernfs_node *parent,
984 					   const char *path,
985 					   const struct ns_common *ns)
986 {
987 	struct kernfs_node *kn;
988 	struct kernfs_root *root = kernfs_root(parent);
989 
990 	down_read(&root->kernfs_rwsem);
991 	kn = kernfs_walk_ns(parent, path, ns);
992 	kernfs_get(kn);
993 	up_read(&root->kernfs_rwsem);
994 
995 	return kn;
996 }
997 
998 unsigned int kernfs_root_flags(struct kernfs_node *kn)
999 {
1000 	return kernfs_root(kn)->flags;
1001 }
1002 
1003 /**
1004  * kernfs_create_root - create a new kernfs hierarchy
1005  * @scops: optional syscall operations for the hierarchy
1006  * @flags: KERNFS_ROOT_* flags
1007  * @priv: opaque data associated with the new directory
1008  *
1009  * Return: the root of the new hierarchy on success, ERR_PTR() value on
1010  * failure.
1011  */
1012 struct kernfs_root *kernfs_create_root(struct kernfs_syscall_ops *scops,
1013 				       unsigned int flags, void *priv)
1014 {
1015 	struct kernfs_root *root;
1016 	struct kernfs_node *kn;
1017 
1018 	root = kzalloc_obj(*root);
1019 	if (!root)
1020 		return ERR_PTR(-ENOMEM);
1021 
1022 	idr_init(&root->ino_idr);
1023 	spin_lock_init(&root->kernfs_idr_lock);
1024 	init_rwsem(&root->kernfs_rwsem);
1025 	init_rwsem(&root->kernfs_iattr_rwsem);
1026 	init_rwsem(&root->kernfs_supers_rwsem);
1027 	INIT_LIST_HEAD(&root->supers);
1028 	rwlock_init(&root->kernfs_rename_lock);
1029 
1030 	/*
1031 	 * On 64bit ino setups, id is ino.  On 32bit, low 32bits are ino.
1032 	 * High bits generation.  The starting value for both ino and
1033 	 * genenration is 1.  Initialize upper 32bit allocation
1034 	 * accordingly.
1035 	 */
1036 	if (sizeof(ino_t) >= sizeof(u64))
1037 		root->id_highbits = 0;
1038 	else
1039 		root->id_highbits = 1;
1040 
1041 	kn = __kernfs_new_node(root, NULL, "", S_IFDIR | S_IRUGO | S_IXUGO,
1042 			       GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
1043 			       KERNFS_DIR);
1044 	if (!kn) {
1045 		idr_destroy(&root->ino_idr);
1046 		kfree(root);
1047 		return ERR_PTR(-ENOMEM);
1048 	}
1049 
1050 	kn->priv = priv;
1051 	kn->dir.root = root;
1052 
1053 	root->syscall_ops = scops;
1054 	root->flags = flags;
1055 	root->kn = kn;
1056 	init_waitqueue_head(&root->deactivate_waitq);
1057 
1058 	if (!(root->flags & KERNFS_ROOT_CREATE_DEACTIVATED))
1059 		kernfs_activate(kn);
1060 
1061 	return root;
1062 }
1063 
1064 /**
1065  * kernfs_destroy_root - destroy a kernfs hierarchy
1066  * @root: root of the hierarchy to destroy
1067  *
1068  * Destroy the hierarchy anchored at @root by removing all existing
1069  * directories and destroying @root.
1070  */
1071 void kernfs_destroy_root(struct kernfs_root *root)
1072 {
1073 	/*
1074 	 *  kernfs_remove holds kernfs_rwsem from the root so the root
1075 	 *  shouldn't be freed during the operation.
1076 	 */
1077 	kernfs_get(root->kn);
1078 	kernfs_remove(root->kn);
1079 	kernfs_put(root->kn); /* will also free @root */
1080 }
1081 
1082 /**
1083  * kernfs_root_to_node - return the kernfs_node associated with a kernfs_root
1084  * @root: root to use to lookup
1085  *
1086  * Return: @root's kernfs_node
1087  */
1088 struct kernfs_node *kernfs_root_to_node(struct kernfs_root *root)
1089 {
1090 	return root->kn;
1091 }
1092 
1093 /**
1094  * kernfs_create_dir_ns - create a directory
1095  * @parent: parent in which to create a new directory
1096  * @name: name of the new directory
1097  * @mode: mode of the new directory
1098  * @uid: uid of the new directory
1099  * @gid: gid of the new directory
1100  * @priv: opaque data associated with the new directory
1101  * @ns: optional namespace tag of the directory
1102  *
1103  * Return: the created node on success, ERR_PTR() value on failure.
1104  */
1105 struct kernfs_node *kernfs_create_dir_ns(struct kernfs_node *parent,
1106 					 const char *name, umode_t mode,
1107 					 kuid_t uid, kgid_t gid,
1108 					 void *priv,
1109 					 const struct ns_common *ns)
1110 {
1111 	struct kernfs_node *kn;
1112 	int rc;
1113 
1114 	/* allocate */
1115 	kn = kernfs_new_node(parent, name, mode | S_IFDIR,
1116 			     uid, gid, KERNFS_DIR);
1117 	if (!kn)
1118 		return ERR_PTR(-ENOMEM);
1119 
1120 	kn->dir.root = parent->dir.root;
1121 	kn->ns = ns;
1122 	kn->priv = priv;
1123 
1124 	/* link in */
1125 	rc = kernfs_add_one(kn);
1126 	if (!rc)
1127 		return kn;
1128 
1129 	kernfs_put(kn);
1130 	return ERR_PTR(rc);
1131 }
1132 
1133 /**
1134  * kernfs_create_empty_dir - create an always empty directory
1135  * @parent: parent in which to create a new directory
1136  * @name: name of the new directory
1137  *
1138  * Return: the created node on success, ERR_PTR() value on failure.
1139  */
1140 struct kernfs_node *kernfs_create_empty_dir(struct kernfs_node *parent,
1141 					    const char *name)
1142 {
1143 	struct kernfs_node *kn;
1144 	int rc;
1145 
1146 	/* allocate */
1147 	kn = kernfs_new_node(parent, name, S_IRUGO|S_IXUGO|S_IFDIR,
1148 			     GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, KERNFS_DIR);
1149 	if (!kn)
1150 		return ERR_PTR(-ENOMEM);
1151 
1152 	kn->flags |= KERNFS_EMPTY_DIR;
1153 	kn->dir.root = parent->dir.root;
1154 	kn->ns = NULL;
1155 	kn->priv = NULL;
1156 
1157 	/* link in */
1158 	rc = kernfs_add_one(kn);
1159 	if (!rc)
1160 		return kn;
1161 
1162 	kernfs_put(kn);
1163 	return ERR_PTR(rc);
1164 }
1165 
1166 static int kernfs_dop_revalidate(struct inode *dir, const struct qstr *name,
1167 				 struct dentry *dentry, unsigned int flags)
1168 {
1169 	struct kernfs_node *kn, *parent;
1170 	struct kernfs_root *root;
1171 
1172 	if (flags & LOOKUP_RCU)
1173 		return -ECHILD;
1174 
1175 	/* Negative hashed dentry? */
1176 	if (d_really_is_negative(dentry)) {
1177 		/* If the kernfs parent node has changed discard and
1178 		 * proceed to ->lookup.
1179 		 *
1180 		 * There's nothing special needed here when getting the
1181 		 * dentry parent, even if a concurrent rename is in
1182 		 * progress. That's because the dentry is negative so
1183 		 * it can only be the target of the rename and it will
1184 		 * be doing a d_move() not a replace. Consequently the
1185 		 * dentry d_parent won't change over the d_move().
1186 		 *
1187 		 * Also kernfs negative dentries transitioning from
1188 		 * negative to positive during revalidate won't happen
1189 		 * because they are invalidated on containing directory
1190 		 * changes and the lookup re-done so that a new positive
1191 		 * dentry can be properly created.
1192 		 */
1193 		root = kernfs_root_from_sb(dentry->d_sb);
1194 		down_read(&root->kernfs_rwsem);
1195 		parent = kernfs_dentry_node(dentry->d_parent);
1196 		if (parent) {
1197 			if (kernfs_dir_changed(parent, dentry)) {
1198 				up_read(&root->kernfs_rwsem);
1199 				return 0;
1200 			}
1201 		}
1202 		up_read(&root->kernfs_rwsem);
1203 
1204 		/* The kernfs parent node hasn't changed, leave the
1205 		 * dentry negative and return success.
1206 		 */
1207 		return 1;
1208 	}
1209 
1210 	kn = kernfs_dentry_node(dentry);
1211 	root = kernfs_root(kn);
1212 	down_read(&root->kernfs_rwsem);
1213 
1214 	/* The kernfs node has been deactivated */
1215 	if (!kernfs_active(kn))
1216 		goto out_bad;
1217 
1218 	parent = kernfs_parent(kn);
1219 	/* The kernfs node has been moved? */
1220 	if (kernfs_dentry_node(dentry->d_parent) != parent)
1221 		goto out_bad;
1222 
1223 	/* The kernfs node has been renamed */
1224 	if (strcmp(dentry->d_name.name, kernfs_rcu_name(kn)) != 0)
1225 		goto out_bad;
1226 
1227 	/* The kernfs node has been moved to a different namespace */
1228 	if (parent && kernfs_ns_enabled(parent) &&
1229 	    kernfs_ns_id(kernfs_info(dentry->d_sb)->ns) != kernfs_ns_id(kn->ns))
1230 		goto out_bad;
1231 
1232 	up_read(&root->kernfs_rwsem);
1233 	return 1;
1234 out_bad:
1235 	up_read(&root->kernfs_rwsem);
1236 	return 0;
1237 }
1238 
1239 const struct dentry_operations kernfs_dops = {
1240 	.d_revalidate	= kernfs_dop_revalidate,
1241 };
1242 
1243 static struct dentry *kernfs_iop_lookup(struct inode *dir,
1244 					struct dentry *dentry,
1245 					unsigned int flags)
1246 {
1247 	struct kernfs_node *parent = dir->i_private;
1248 	struct kernfs_node *kn;
1249 	struct kernfs_root *root;
1250 	struct inode *inode = NULL;
1251 	const struct ns_common *ns = NULL;
1252 
1253 	root = kernfs_root(parent);
1254 	down_read(&root->kernfs_rwsem);
1255 	if (kernfs_ns_enabled(parent))
1256 		ns = kernfs_info(dir->i_sb)->ns;
1257 
1258 	kn = kernfs_find_ns(parent, dentry->d_name.name, ns);
1259 	/* attach dentry and inode */
1260 	if (kn) {
1261 		/* Inactive nodes are invisible to the VFS so don't
1262 		 * create a negative.
1263 		 */
1264 		if (!kernfs_active(kn)) {
1265 			up_read(&root->kernfs_rwsem);
1266 			return NULL;
1267 		}
1268 		inode = kernfs_get_inode(dir->i_sb, kn);
1269 		if (!inode)
1270 			inode = ERR_PTR(-ENOMEM);
1271 	}
1272 	/*
1273 	 * Needed for negative dentry validation.
1274 	 * The negative dentry can be created in kernfs_iop_lookup()
1275 	 * or transforms from positive dentry in dentry_unlink_inode()
1276 	 * called from vfs_rmdir().
1277 	 */
1278 	if (!IS_ERR(inode))
1279 		kernfs_set_rev(parent, dentry);
1280 	up_read(&root->kernfs_rwsem);
1281 
1282 	/* instantiate and hash (possibly negative) dentry */
1283 	return d_splice_alias(inode, dentry);
1284 }
1285 
1286 static struct dentry *kernfs_iop_mkdir(struct mnt_idmap *idmap,
1287 				       struct inode *dir, struct dentry *dentry,
1288 				       umode_t mode)
1289 {
1290 	struct kernfs_node *parent = dir->i_private;
1291 	struct kernfs_syscall_ops *scops = kernfs_root(parent)->syscall_ops;
1292 	int ret;
1293 
1294 	if (!scops || !scops->mkdir)
1295 		return ERR_PTR(-EPERM);
1296 
1297 	if (!kernfs_get_active(parent))
1298 		return ERR_PTR(-ENODEV);
1299 
1300 	ret = scops->mkdir(parent, dentry->d_name.name, mode);
1301 
1302 	kernfs_put_active(parent);
1303 	return ERR_PTR(ret);
1304 }
1305 
1306 static int kernfs_iop_rmdir(struct inode *dir, struct dentry *dentry)
1307 {
1308 	struct kernfs_node *kn  = kernfs_dentry_node(dentry);
1309 	struct kernfs_syscall_ops *scops = kernfs_root(kn)->syscall_ops;
1310 	int ret;
1311 
1312 	if (!scops || !scops->rmdir)
1313 		return -EPERM;
1314 
1315 	if (!kernfs_get_active(kn))
1316 		return -ENODEV;
1317 
1318 	ret = scops->rmdir(kn);
1319 
1320 	kernfs_put_active(kn);
1321 	return ret;
1322 }
1323 
1324 static int kernfs_iop_rename(struct mnt_idmap *idmap,
1325 			     struct inode *old_dir, struct dentry *old_dentry,
1326 			     struct inode *new_dir, struct dentry *new_dentry,
1327 			     unsigned int flags)
1328 {
1329 	struct kernfs_node *kn = kernfs_dentry_node(old_dentry);
1330 	struct kernfs_node *new_parent = new_dir->i_private;
1331 	struct kernfs_syscall_ops *scops = kernfs_root(kn)->syscall_ops;
1332 	int ret;
1333 
1334 	if (flags)
1335 		return -EINVAL;
1336 
1337 	if (!scops || !scops->rename)
1338 		return -EPERM;
1339 
1340 	if (!kernfs_get_active(kn))
1341 		return -ENODEV;
1342 
1343 	if (!kernfs_get_active(new_parent)) {
1344 		kernfs_put_active(kn);
1345 		return -ENODEV;
1346 	}
1347 
1348 	ret = scops->rename(kn, new_parent, new_dentry->d_name.name);
1349 
1350 	kernfs_put_active(new_parent);
1351 	kernfs_put_active(kn);
1352 	return ret;
1353 }
1354 
1355 const struct inode_operations kernfs_dir_iops = {
1356 	.lookup		= kernfs_iop_lookup,
1357 	.permission	= kernfs_iop_permission,
1358 	.setattr	= kernfs_iop_setattr,
1359 	.getattr	= kernfs_iop_getattr,
1360 	.listxattr	= kernfs_iop_listxattr,
1361 
1362 	.mkdir		= kernfs_iop_mkdir,
1363 	.rmdir		= kernfs_iop_rmdir,
1364 	.rename		= kernfs_iop_rename,
1365 };
1366 
1367 static struct kernfs_node *kernfs_leftmost_descendant(struct kernfs_node *pos)
1368 {
1369 	struct kernfs_node *last;
1370 
1371 	while (true) {
1372 		struct rb_node *rbn;
1373 
1374 		last = pos;
1375 
1376 		if (kernfs_type(pos) != KERNFS_DIR)
1377 			break;
1378 
1379 		rbn = rb_first(&pos->dir.children);
1380 		if (!rbn)
1381 			break;
1382 
1383 		pos = rb_to_kn(rbn);
1384 	}
1385 
1386 	return last;
1387 }
1388 
1389 /**
1390  * kernfs_next_descendant_post - find the next descendant for post-order walk
1391  * @pos: the current position (%NULL to initiate traversal)
1392  * @root: kernfs_node whose descendants to walk
1393  *
1394  * Find the next descendant to visit for post-order traversal of @root's
1395  * descendants.  @root is included in the iteration and the last node to be
1396  * visited.
1397  *
1398  * Return: the next descendant to visit or %NULL when done.
1399  */
1400 static struct kernfs_node *kernfs_next_descendant_post(struct kernfs_node *pos,
1401 						       struct kernfs_node *root)
1402 {
1403 	struct rb_node *rbn;
1404 
1405 	lockdep_assert_held_write(&kernfs_root(root)->kernfs_rwsem);
1406 
1407 	/* if first iteration, visit leftmost descendant which may be root */
1408 	if (!pos)
1409 		return kernfs_leftmost_descendant(root);
1410 
1411 	/* if we visited @root, we're done */
1412 	if (pos == root)
1413 		return NULL;
1414 
1415 	/* if there's an unvisited sibling, visit its leftmost descendant */
1416 	rbn = rb_next(&pos->rb);
1417 	if (rbn)
1418 		return kernfs_leftmost_descendant(rb_to_kn(rbn));
1419 
1420 	/* no sibling left, visit parent */
1421 	return kernfs_parent(pos);
1422 }
1423 
1424 static void kernfs_activate_one(struct kernfs_node *kn)
1425 {
1426 	lockdep_assert_held_write(&kernfs_root(kn)->kernfs_rwsem);
1427 
1428 	kn->flags |= KERNFS_ACTIVATED;
1429 
1430 	if (kernfs_active(kn) || (kn->flags & (KERNFS_HIDDEN | KERNFS_REMOVING)))
1431 		return;
1432 
1433 	WARN_ON_ONCE(rcu_access_pointer(kn->__parent) && RB_EMPTY_NODE(&kn->rb));
1434 	WARN_ON_ONCE(atomic_read(&kn->active) != KN_DEACTIVATED_BIAS);
1435 
1436 	atomic_sub(KN_DEACTIVATED_BIAS, &kn->active);
1437 }
1438 
1439 /**
1440  * kernfs_activate - activate a node which started deactivated
1441  * @kn: kernfs_node whose subtree is to be activated
1442  *
1443  * If the root has KERNFS_ROOT_CREATE_DEACTIVATED set, a newly created node
1444  * needs to be explicitly activated.  A node which hasn't been activated
1445  * isn't visible to userland and deactivation is skipped during its
1446  * removal.  This is useful to construct atomic init sequences where
1447  * creation of multiple nodes should either succeed or fail atomically.
1448  *
1449  * The caller is responsible for ensuring that this function is not called
1450  * after kernfs_remove*() is invoked on @kn.
1451  */
1452 void kernfs_activate(struct kernfs_node *kn)
1453 {
1454 	struct kernfs_node *pos;
1455 	struct kernfs_root *root = kernfs_root(kn);
1456 
1457 	down_write(&root->kernfs_rwsem);
1458 
1459 	pos = NULL;
1460 	while ((pos = kernfs_next_descendant_post(pos, kn)))
1461 		kernfs_activate_one(pos);
1462 
1463 	up_write(&root->kernfs_rwsem);
1464 }
1465 
1466 /**
1467  * kernfs_show - show or hide a node
1468  * @kn: kernfs_node to show or hide
1469  * @show: whether to show or hide
1470  *
1471  * If @show is %false, @kn is marked hidden and deactivated. A hidden node is
1472  * ignored in future activaitons. If %true, the mark is removed and activation
1473  * state is restored. This function won't implicitly activate a new node in a
1474  * %KERNFS_ROOT_CREATE_DEACTIVATED root which hasn't been activated yet.
1475  *
1476  * To avoid recursion complexities, directories aren't supported for now.
1477  */
1478 void kernfs_show(struct kernfs_node *kn, bool show)
1479 {
1480 	struct kernfs_root *root = kernfs_root(kn);
1481 
1482 	if (WARN_ON_ONCE(kernfs_type(kn) == KERNFS_DIR))
1483 		return;
1484 
1485 	down_write(&root->kernfs_rwsem);
1486 
1487 	if (show) {
1488 		kn->flags &= ~KERNFS_HIDDEN;
1489 		if (kn->flags & KERNFS_ACTIVATED)
1490 			kernfs_activate_one(kn);
1491 	} else {
1492 		kn->flags |= KERNFS_HIDDEN;
1493 		if (kernfs_active(kn))
1494 			atomic_add(KN_DEACTIVATED_BIAS, &kn->active);
1495 		kernfs_drain(kn);
1496 	}
1497 
1498 	up_write(&root->kernfs_rwsem);
1499 }
1500 
1501 static void __kernfs_remove(struct kernfs_node *kn)
1502 {
1503 	struct kernfs_node *pos, *parent;
1504 
1505 	/* Short-circuit if non-root @kn has already finished removal. */
1506 	if (!kn)
1507 		return;
1508 
1509 	lockdep_assert_held_write(&kernfs_root(kn)->kernfs_rwsem);
1510 
1511 	/*
1512 	 * This is for kernfs_remove_self() which plays with active ref
1513 	 * after removal.
1514 	 */
1515 	if (kernfs_parent(kn) && RB_EMPTY_NODE(&kn->rb))
1516 		return;
1517 
1518 	pr_debug("kernfs %s: removing\n", kernfs_rcu_name(kn));
1519 
1520 	/* prevent new usage by marking all nodes removing and deactivating */
1521 	pos = NULL;
1522 	while ((pos = kernfs_next_descendant_post(pos, kn))) {
1523 		pos->flags |= KERNFS_REMOVING;
1524 		if (kernfs_active(pos))
1525 			atomic_add(KN_DEACTIVATED_BIAS, &pos->active);
1526 	}
1527 
1528 	/* deactivate and unlink the subtree node-by-node */
1529 	do {
1530 		pos = kernfs_leftmost_descendant(kn);
1531 
1532 		/*
1533 		 * kernfs_drain() may drop kernfs_rwsem temporarily and @pos's
1534 		 * base ref could have been put by someone else by the time
1535 		 * the function returns.  Make sure it doesn't go away
1536 		 * underneath us.
1537 		 */
1538 		kernfs_get(pos);
1539 
1540 		kernfs_drain(pos);
1541 		parent = kernfs_parent(pos);
1542 		/*
1543 		 * kernfs_unlink_sibling() succeeds once per node.  Use it
1544 		 * to decide who's responsible for cleanups.
1545 		 */
1546 		if (!parent || kernfs_unlink_sibling(pos)) {
1547 			struct kernfs_iattrs *ps_iattr =
1548 				parent ? parent->iattr : NULL;
1549 
1550 			/* update timestamps on the parent */
1551 			down_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
1552 
1553 			if (ps_iattr) {
1554 				ktime_get_real_ts64(&ps_iattr->ia_ctime);
1555 				ps_iattr->ia_mtime = ps_iattr->ia_ctime;
1556 			}
1557 
1558 			up_write(&kernfs_root(kn)->kernfs_iattr_rwsem);
1559 			kernfs_put(pos);
1560 		}
1561 
1562 		kernfs_put(pos);
1563 	} while (pos != kn);
1564 }
1565 
1566 /**
1567  * kernfs_remove - remove a kernfs_node recursively
1568  * @kn: the kernfs_node to remove
1569  *
1570  * Remove @kn along with all its subdirectories and files.
1571  */
1572 void kernfs_remove(struct kernfs_node *kn)
1573 {
1574 	struct kernfs_root *root;
1575 
1576 	if (!kn)
1577 		return;
1578 
1579 	root = kernfs_root(kn);
1580 
1581 	down_write(&root->kernfs_rwsem);
1582 	__kernfs_remove(kn);
1583 	up_write(&root->kernfs_rwsem);
1584 }
1585 
1586 /**
1587  * kernfs_break_active_protection - break out of active protection
1588  * @kn: the self kernfs_node
1589  *
1590  * The caller must be running off of a kernfs operation which is invoked
1591  * with an active reference - e.g. one of kernfs_ops.  Each invocation of
1592  * this function must also be matched with an invocation of
1593  * kernfs_unbreak_active_protection().
1594  *
1595  * This function releases the active reference of @kn the caller is
1596  * holding.  Once this function is called, @kn may be removed at any point
1597  * and the caller is solely responsible for ensuring that the objects it
1598  * dereferences are accessible.
1599  */
1600 void kernfs_break_active_protection(struct kernfs_node *kn)
1601 {
1602 	/*
1603 	 * Take out ourself out of the active ref dependency chain.  If
1604 	 * we're called without an active ref, lockdep will complain.
1605 	 */
1606 	kernfs_put_active(kn);
1607 }
1608 
1609 /**
1610  * kernfs_unbreak_active_protection - undo kernfs_break_active_protection()
1611  * @kn: the self kernfs_node
1612  *
1613  * If kernfs_break_active_protection() was called, this function must be
1614  * invoked before finishing the kernfs operation.  Note that while this
1615  * function restores the active reference, it doesn't and can't actually
1616  * restore the active protection - @kn may already or be in the process of
1617  * being drained and removed.  Once kernfs_break_active_protection() is
1618  * invoked, that protection is irreversibly gone for the kernfs operation
1619  * instance.
1620  *
1621  * While this function may be called at any point after
1622  * kernfs_break_active_protection() is invoked, its most useful location
1623  * would be right before the enclosing kernfs operation returns.
1624  */
1625 void kernfs_unbreak_active_protection(struct kernfs_node *kn)
1626 {
1627 	/*
1628 	 * @kn->active could be in any state; however, the increment we do
1629 	 * here will be undone as soon as the enclosing kernfs operation
1630 	 * finishes and this temporary bump can't break anything.  If @kn
1631 	 * is alive, nothing changes.  If @kn is being deactivated, the
1632 	 * soon-to-follow put will either finish deactivation or restore
1633 	 * deactivated state.  If @kn is already removed, the temporary
1634 	 * bump is guaranteed to be gone before @kn is released.
1635 	 */
1636 	atomic_inc(&kn->active);
1637 	if (kernfs_lockdep(kn))
1638 		rwsem_acquire(&kn->dep_map, 0, 1, _RET_IP_);
1639 }
1640 
1641 /**
1642  * kernfs_remove_self - remove a kernfs_node from its own method
1643  * @kn: the self kernfs_node to remove
1644  *
1645  * The caller must be running off of a kernfs operation which is invoked
1646  * with an active reference - e.g. one of kernfs_ops.  This can be used to
1647  * implement a file operation which deletes itself.
1648  *
1649  * For example, the "delete" file for a sysfs device directory can be
1650  * implemented by invoking kernfs_remove_self() on the "delete" file
1651  * itself.  This function breaks the circular dependency of trying to
1652  * deactivate self while holding an active ref itself.  It isn't necessary
1653  * to modify the usual removal path to use kernfs_remove_self().  The
1654  * "delete" implementation can simply invoke kernfs_remove_self() on self
1655  * before proceeding with the usual removal path.  kernfs will ignore later
1656  * kernfs_remove() on self.
1657  *
1658  * kernfs_remove_self() can be called multiple times concurrently on the
1659  * same kernfs_node.  Only the first one actually performs removal and
1660  * returns %true.  All others will wait until the kernfs operation which
1661  * won self-removal finishes and return %false.  Note that the losers wait
1662  * for the completion of not only the winning kernfs_remove_self() but also
1663  * the whole kernfs_ops which won the arbitration.  This can be used to
1664  * guarantee, for example, all concurrent writes to a "delete" file to
1665  * finish only after the whole operation is complete.
1666  *
1667  * Return: %true if @kn is removed by this call, otherwise %false.
1668  */
1669 bool kernfs_remove_self(struct kernfs_node *kn)
1670 {
1671 	bool ret;
1672 	struct kernfs_root *root = kernfs_root(kn);
1673 
1674 	down_write(&root->kernfs_rwsem);
1675 	kernfs_break_active_protection(kn);
1676 
1677 	/*
1678 	 * SUICIDAL is used to arbitrate among competing invocations.  Only
1679 	 * the first one will actually perform removal.  When the removal
1680 	 * is complete, SUICIDED is set and the active ref is restored
1681 	 * while kernfs_rwsem for held exclusive.  The ones which lost
1682 	 * arbitration waits for SUICIDED && drained which can happen only
1683 	 * after the enclosing kernfs operation which executed the winning
1684 	 * instance of kernfs_remove_self() finished.
1685 	 */
1686 	if (!(kn->flags & KERNFS_SUICIDAL)) {
1687 		kn->flags |= KERNFS_SUICIDAL;
1688 		__kernfs_remove(kn);
1689 		kn->flags |= KERNFS_SUICIDED;
1690 		ret = true;
1691 	} else {
1692 		wait_queue_head_t *waitq = &kernfs_root(kn)->deactivate_waitq;
1693 		DEFINE_WAIT(wait);
1694 
1695 		while (true) {
1696 			prepare_to_wait(waitq, &wait, TASK_UNINTERRUPTIBLE);
1697 
1698 			if ((kn->flags & KERNFS_SUICIDED) &&
1699 			    atomic_read(&kn->active) == KN_DEACTIVATED_BIAS)
1700 				break;
1701 
1702 			up_write(&root->kernfs_rwsem);
1703 			schedule();
1704 			down_write(&root->kernfs_rwsem);
1705 		}
1706 		finish_wait(waitq, &wait);
1707 		WARN_ON_ONCE(!RB_EMPTY_NODE(&kn->rb));
1708 		ret = false;
1709 	}
1710 
1711 	/*
1712 	 * This must be done while kernfs_rwsem held exclusive; otherwise,
1713 	 * waiting for SUICIDED && deactivated could finish prematurely.
1714 	 */
1715 	kernfs_unbreak_active_protection(kn);
1716 
1717 	up_write(&root->kernfs_rwsem);
1718 	return ret;
1719 }
1720 
1721 /**
1722  * kernfs_remove_by_name_ns - find a kernfs_node by name and remove it
1723  * @parent: parent of the target
1724  * @name: name of the kernfs_node to remove
1725  * @ns: namespace tag of the kernfs_node to remove
1726  *
1727  * Look for the kernfs_node with @name and @ns under @parent and remove it.
1728  *
1729  * Return: %0 on success, -ENOENT if such entry doesn't exist.
1730  */
1731 int kernfs_remove_by_name_ns(struct kernfs_node *parent, const char *name,
1732 			     const struct ns_common *ns)
1733 {
1734 	struct kernfs_node *kn;
1735 	struct kernfs_root *root;
1736 
1737 	if (!parent) {
1738 		WARN(1, KERN_WARNING "kernfs: can not remove '%s', no directory\n",
1739 			name);
1740 		return -ENOENT;
1741 	}
1742 
1743 	root = kernfs_root(parent);
1744 	down_write(&root->kernfs_rwsem);
1745 
1746 	kn = kernfs_find_ns(parent, name, ns);
1747 	if (kn) {
1748 		kernfs_get(kn);
1749 		__kernfs_remove(kn);
1750 		kernfs_put(kn);
1751 	}
1752 
1753 	up_write(&root->kernfs_rwsem);
1754 
1755 	if (kn)
1756 		return 0;
1757 	else
1758 		return -ENOENT;
1759 }
1760 
1761 /**
1762  * kernfs_rename_ns - move and rename a kernfs_node
1763  * @kn: target node
1764  * @new_parent: new parent to put @sd under
1765  * @new_name: new name
1766  * @new_ns: new namespace tag
1767  *
1768  * Return: %0 on success, -errno on failure.
1769  */
1770 int kernfs_rename_ns(struct kernfs_node *kn, struct kernfs_node *new_parent,
1771 		     const char *new_name, const struct ns_common *new_ns)
1772 {
1773 	struct kernfs_node *old_parent;
1774 	struct kernfs_root *root;
1775 	const char *old_name;
1776 	int error;
1777 
1778 	/* can't move or rename root */
1779 	if (!rcu_access_pointer(kn->__parent))
1780 		return -EINVAL;
1781 
1782 	root = kernfs_root(kn);
1783 	down_write(&root->kernfs_rwsem);
1784 
1785 	error = -ENOENT;
1786 	if (!kernfs_active(kn) || !kernfs_active(new_parent) ||
1787 	    (new_parent->flags & KERNFS_EMPTY_DIR))
1788 		goto out;
1789 
1790 	old_parent = kernfs_parent(kn);
1791 	if (root->flags & KERNFS_ROOT_INVARIANT_PARENT) {
1792 		error = -EINVAL;
1793 		if (WARN_ON_ONCE(old_parent != new_parent))
1794 			goto out;
1795 	}
1796 
1797 	error = 0;
1798 	old_name = kernfs_rcu_name(kn);
1799 	if (!new_name)
1800 		new_name = old_name;
1801 	if ((old_parent == new_parent) &&
1802 	    (kernfs_ns_id(kn->ns) == kernfs_ns_id(new_ns)) &&
1803 	    (strcmp(old_name, new_name) == 0))
1804 		goto out;	/* nothing to rename */
1805 
1806 	error = -EEXIST;
1807 	if (kernfs_find_ns(new_parent, new_name, new_ns))
1808 		goto out;
1809 
1810 	/* rename kernfs_node */
1811 	if (strcmp(old_name, new_name) != 0) {
1812 		error = -ENOMEM;
1813 		new_name = kstrdup_const(new_name, GFP_KERNEL);
1814 		if (!new_name)
1815 			goto out;
1816 	} else {
1817 		new_name = NULL;
1818 	}
1819 
1820 	/*
1821 	 * Move to the appropriate place in the appropriate directories rbtree.
1822 	 */
1823 	kernfs_unlink_sibling(kn);
1824 
1825 	/* rename_lock protects ->parent accessors */
1826 	if (old_parent != new_parent) {
1827 		kernfs_get(new_parent);
1828 		write_lock_irq(&root->kernfs_rename_lock);
1829 
1830 		rcu_assign_pointer(kn->__parent, new_parent);
1831 
1832 		kn->ns = new_ns;
1833 		if (new_name)
1834 			rcu_assign_pointer(kn->name, new_name);
1835 
1836 		write_unlock_irq(&root->kernfs_rename_lock);
1837 		kernfs_put(old_parent);
1838 	} else {
1839 		/* name assignment is RCU protected, parent is the same */
1840 		kn->ns = new_ns;
1841 		if (new_name)
1842 			rcu_assign_pointer(kn->name, new_name);
1843 	}
1844 
1845 	kn->hash = kernfs_name_hash(new_name ?: old_name, kn->ns);
1846 	kernfs_link_sibling(kn);
1847 
1848 	if (new_name && !is_kernel_rodata((unsigned long)old_name))
1849 		kfree_rcu_mightsleep(old_name);
1850 
1851 	error = 0;
1852  out:
1853 	up_write(&root->kernfs_rwsem);
1854 	return error;
1855 }
1856 
1857 static int kernfs_dir_fop_release(struct inode *inode, struct file *filp)
1858 {
1859 	kernfs_put(filp->private_data);
1860 	return 0;
1861 }
1862 
1863 static struct kernfs_node *kernfs_dir_pos(const struct ns_common *ns,
1864 	struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos)
1865 {
1866 	if (pos) {
1867 		int valid = kernfs_active(pos) &&
1868 			rcu_access_pointer(pos->__parent) == parent &&
1869 			hash == pos->hash;
1870 		kernfs_put(pos);
1871 		if (!valid)
1872 			pos = NULL;
1873 	}
1874 	if (!pos && (hash > 1) && (hash < INT_MAX)) {
1875 		struct rb_node *node = parent->dir.children.rb_node;
1876 		u64 ns_id = kernfs_ns_id(ns);
1877 		while (node) {
1878 			pos = rb_to_kn(node);
1879 
1880 			if (hash < pos->hash)
1881 				node = node->rb_left;
1882 			else if (hash > pos->hash)
1883 				node = node->rb_right;
1884 			else if (ns_id < kernfs_ns_id(pos->ns))
1885 				node = node->rb_left;
1886 			else if (ns_id > kernfs_ns_id(pos->ns))
1887 				node = node->rb_right;
1888 			else
1889 				break;
1890 		}
1891 	}
1892 	/* Skip over entries which are dying/dead or in the wrong namespace */
1893 	while (pos && (!kernfs_active(pos) ||
1894 		       kernfs_ns_id(pos->ns) != kernfs_ns_id(ns))) {
1895 		struct rb_node *node = rb_next(&pos->rb);
1896 		if (!node)
1897 			pos = NULL;
1898 		else
1899 			pos = rb_to_kn(node);
1900 	}
1901 	return pos;
1902 }
1903 
1904 static struct kernfs_node *kernfs_dir_next_pos(const struct ns_common *ns,
1905 	struct kernfs_node *parent, ino_t ino, struct kernfs_node *pos)
1906 {
1907 	pos = kernfs_dir_pos(ns, parent, ino, pos);
1908 	if (pos) {
1909 		do {
1910 			struct rb_node *node = rb_next(&pos->rb);
1911 			if (!node)
1912 				pos = NULL;
1913 			else
1914 				pos = rb_to_kn(node);
1915 		} while (pos && (!kernfs_active(pos) ||
1916 			kernfs_ns_id(pos->ns) != kernfs_ns_id(ns)));
1917 	}
1918 	return pos;
1919 }
1920 
1921 static int kernfs_fop_readdir(struct file *file, struct dir_context *ctx)
1922 {
1923 	struct dentry *dentry = file->f_path.dentry;
1924 	struct kernfs_node *parent = kernfs_dentry_node(dentry);
1925 	struct kernfs_node *pos = file->private_data;
1926 	struct kernfs_root *root;
1927 	const struct ns_common *ns = NULL;
1928 
1929 	if (!dir_emit_dots(file, ctx))
1930 		return 0;
1931 
1932 	root = kernfs_root(parent);
1933 	down_read(&root->kernfs_rwsem);
1934 
1935 	if (kernfs_ns_enabled(parent))
1936 		ns = kernfs_info(dentry->d_sb)->ns;
1937 
1938 	for (pos = kernfs_dir_pos(ns, parent, ctx->pos, pos);
1939 	     pos;
1940 	     pos = kernfs_dir_next_pos(ns, parent, ctx->pos, pos)) {
1941 		const char *name = kernfs_rcu_name(pos);
1942 		unsigned int type = fs_umode_to_dtype(pos->mode);
1943 		int len = strlen(name);
1944 		ino_t ino = kernfs_ino(pos);
1945 
1946 		ctx->pos = pos->hash;
1947 		file->private_data = pos;
1948 		kernfs_get(pos);
1949 
1950 		if (!dir_emit(ctx, name, len, ino, type)) {
1951 			up_read(&root->kernfs_rwsem);
1952 			return 0;
1953 		}
1954 	}
1955 	up_read(&root->kernfs_rwsem);
1956 	file->private_data = NULL;
1957 	ctx->pos = INT_MAX;
1958 	return 0;
1959 }
1960 
1961 const struct file_operations kernfs_dir_fops = {
1962 	.read		= generic_read_dir,
1963 	.iterate_shared	= kernfs_fop_readdir,
1964 	.release	= kernfs_dir_fop_release,
1965 	.llseek		= generic_file_llseek,
1966 };
1967