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