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