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