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