kernfs: s/sysfs/kernfs/ in constants
[platform/adaptation/renesas_rcar/renesas_kernel.git] / fs / kernfs / dir.c
1 /*
2  * fs/kernfs/dir.c - kernfs directory implementation
3  *
4  * Copyright (c) 2001-3 Patrick Mochel
5  * Copyright (c) 2007 SUSE Linux Products GmbH
6  * Copyright (c) 2007, 2013 Tejun Heo <tj@kernel.org>
7  *
8  * This file is released under the GPLv2.
9  */
10
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_MUTEX(sysfs_mutex);
21
22 #define rb_to_kn(X) rb_entry((X), struct kernfs_node, rb)
23
24 /**
25  *      sysfs_name_hash
26  *      @name: Null terminated string to hash
27  *      @ns:   Namespace tag to hash
28  *
29  *      Returns 31 bit hash of ns + name (so it fits in an off_t )
30  */
31 static unsigned int sysfs_name_hash(const char *name, const void *ns)
32 {
33         unsigned long hash = init_name_hash();
34         unsigned int len = strlen(name);
35         while (len--)
36                 hash = partial_name_hash(*name++, hash);
37         hash = (end_name_hash(hash) ^ hash_ptr((void *)ns, 31));
38         hash &= 0x7fffffffU;
39         /* Reserve hash numbers 0, 1 and INT_MAX for magic directory entries */
40         if (hash < 1)
41                 hash += 2;
42         if (hash >= INT_MAX)
43                 hash = INT_MAX - 1;
44         return hash;
45 }
46
47 static int sysfs_name_compare(unsigned int hash, const char *name,
48                               const void *ns, const struct kernfs_node *kn)
49 {
50         if (hash != kn->hash)
51                 return hash - kn->hash;
52         if (ns != kn->ns)
53                 return ns - kn->ns;
54         return strcmp(name, kn->name);
55 }
56
57 static int sysfs_sd_compare(const struct kernfs_node *left,
58                             const struct kernfs_node *right)
59 {
60         return sysfs_name_compare(left->hash, left->name, left->ns, right);
61 }
62
63 /**
64  *      sysfs_link_sibling - link kernfs_node into sibling rbtree
65  *      @kn: kernfs_node of interest
66  *
67  *      Link @kn into its sibling rbtree which starts from
68  *      @kn->parent->dir.children.
69  *
70  *      Locking:
71  *      mutex_lock(sysfs_mutex)
72  *
73  *      RETURNS:
74  *      0 on susccess -EEXIST on failure.
75  */
76 static int sysfs_link_sibling(struct kernfs_node *kn)
77 {
78         struct rb_node **node = &kn->parent->dir.children.rb_node;
79         struct rb_node *parent = NULL;
80
81         if (kernfs_type(kn) == KERNFS_DIR)
82                 kn->parent->dir.subdirs++;
83
84         while (*node) {
85                 struct kernfs_node *pos;
86                 int result;
87
88                 pos = rb_to_kn(*node);
89                 parent = *node;
90                 result = sysfs_sd_compare(kn, pos);
91                 if (result < 0)
92                         node = &pos->rb.rb_left;
93                 else if (result > 0)
94                         node = &pos->rb.rb_right;
95                 else
96                         return -EEXIST;
97         }
98         /* add new node and rebalance the tree */
99         rb_link_node(&kn->rb, parent, node);
100         rb_insert_color(&kn->rb, &kn->parent->dir.children);
101         return 0;
102 }
103
104 /**
105  *      sysfs_unlink_sibling - unlink kernfs_node from sibling rbtree
106  *      @kn: kernfs_node of interest
107  *
108  *      Unlink @kn from its sibling rbtree which starts from
109  *      kn->parent->dir.children.
110  *
111  *      Locking:
112  *      mutex_lock(sysfs_mutex)
113  */
114 static void sysfs_unlink_sibling(struct kernfs_node *kn)
115 {
116         if (kernfs_type(kn) == KERNFS_DIR)
117                 kn->parent->dir.subdirs--;
118
119         rb_erase(&kn->rb, &kn->parent->dir.children);
120 }
121
122 /**
123  *      sysfs_get_active - get an active reference to kernfs_node
124  *      @kn: kernfs_node to get an active reference to
125  *
126  *      Get an active reference of @kn.  This function is noop if @kn
127  *      is NULL.
128  *
129  *      RETURNS:
130  *      Pointer to @kn on success, NULL on failure.
131  */
132 struct kernfs_node *sysfs_get_active(struct kernfs_node *kn)
133 {
134         if (unlikely(!kn))
135                 return NULL;
136
137         if (!atomic_inc_unless_negative(&kn->active))
138                 return NULL;
139
140         if (kn->flags & KERNFS_LOCKDEP)
141                 rwsem_acquire_read(&kn->dep_map, 0, 1, _RET_IP_);
142         return kn;
143 }
144
145 /**
146  *      sysfs_put_active - put an active reference to kernfs_node
147  *      @kn: kernfs_node to put an active reference to
148  *
149  *      Put an active reference to @kn.  This function is noop if @kn
150  *      is NULL.
151  */
152 void sysfs_put_active(struct kernfs_node *kn)
153 {
154         int v;
155
156         if (unlikely(!kn))
157                 return;
158
159         if (kn->flags & KERNFS_LOCKDEP)
160                 rwsem_release(&kn->dep_map, 1, _RET_IP_);
161         v = atomic_dec_return(&kn->active);
162         if (likely(v != KN_DEACTIVATED_BIAS))
163                 return;
164
165         /*
166          * atomic_dec_return() is a mb(), we'll always see the updated
167          * kn->u.completion.
168          */
169         complete(kn->u.completion);
170 }
171
172 /**
173  *      sysfs_deactivate - deactivate kernfs_node
174  *      @kn: kernfs_node to deactivate
175  *
176  *      Deny new active references and drain existing ones.
177  */
178 static void sysfs_deactivate(struct kernfs_node *kn)
179 {
180         DECLARE_COMPLETION_ONSTACK(wait);
181         int v;
182
183         BUG_ON(!(kn->flags & KERNFS_REMOVED));
184
185         if (!(kernfs_type(kn) & KERNFS_ACTIVE_REF))
186                 return;
187
188         kn->u.completion = (void *)&wait;
189
190         rwsem_acquire(&kn->dep_map, 0, 0, _RET_IP_);
191         /* atomic_add_return() is a mb(), put_active() will always see
192          * the updated kn->u.completion.
193          */
194         v = atomic_add_return(KN_DEACTIVATED_BIAS, &kn->active);
195
196         if (v != KN_DEACTIVATED_BIAS) {
197                 lock_contended(&kn->dep_map, _RET_IP_);
198                 wait_for_completion(&wait);
199         }
200
201         lock_acquired(&kn->dep_map, _RET_IP_);
202         rwsem_release(&kn->dep_map, 1, _RET_IP_);
203 }
204
205 /**
206  * kernfs_get - get a reference count on a kernfs_node
207  * @kn: the target kernfs_node
208  */
209 void kernfs_get(struct kernfs_node *kn)
210 {
211         if (kn) {
212                 WARN_ON(!atomic_read(&kn->count));
213                 atomic_inc(&kn->count);
214         }
215 }
216 EXPORT_SYMBOL_GPL(kernfs_get);
217
218 /**
219  * kernfs_put - put a reference count on a kernfs_node
220  * @kn: the target kernfs_node
221  *
222  * Put a reference count of @kn and destroy it if it reached zero.
223  */
224 void kernfs_put(struct kernfs_node *kn)
225 {
226         struct kernfs_node *parent;
227         struct kernfs_root *root;
228
229         if (!kn || !atomic_dec_and_test(&kn->count))
230                 return;
231         root = kernfs_root(kn);
232  repeat:
233         /* Moving/renaming is always done while holding reference.
234          * kn->parent won't change beneath us.
235          */
236         parent = kn->parent;
237
238         WARN(!(kn->flags & KERNFS_REMOVED),
239                 "sysfs: free using entry: %s/%s\n",
240                 parent ? parent->name : "", kn->name);
241
242         if (kernfs_type(kn) == KERNFS_LINK)
243                 kernfs_put(kn->symlink.target_kn);
244         if (kernfs_type(kn) & KERNFS_COPY_NAME)
245                 kfree(kn->name);
246         if (kn->iattr) {
247                 if (kn->iattr->ia_secdata)
248                         security_release_secctx(kn->iattr->ia_secdata,
249                                                 kn->iattr->ia_secdata_len);
250                 simple_xattrs_free(&kn->iattr->xattrs);
251         }
252         kfree(kn->iattr);
253         ida_simple_remove(&root->ino_ida, kn->ino);
254         kmem_cache_free(sysfs_dir_cachep, kn);
255
256         kn = parent;
257         if (kn) {
258                 if (atomic_dec_and_test(&kn->count))
259                         goto repeat;
260         } else {
261                 /* just released the root kn, free @root too */
262                 ida_destroy(&root->ino_ida);
263                 kfree(root);
264         }
265 }
266 EXPORT_SYMBOL_GPL(kernfs_put);
267
268 static int sysfs_dentry_delete(const struct dentry *dentry)
269 {
270         struct kernfs_node *kn = dentry->d_fsdata;
271         return !(kn && !(kn->flags & KERNFS_REMOVED));
272 }
273
274 static int sysfs_dentry_revalidate(struct dentry *dentry, unsigned int flags)
275 {
276         struct kernfs_node *kn;
277
278         if (flags & LOOKUP_RCU)
279                 return -ECHILD;
280
281         kn = dentry->d_fsdata;
282         mutex_lock(&sysfs_mutex);
283
284         /* The sysfs dirent has been deleted */
285         if (kn->flags & KERNFS_REMOVED)
286                 goto out_bad;
287
288         /* The sysfs dirent has been moved? */
289         if (dentry->d_parent->d_fsdata != kn->parent)
290                 goto out_bad;
291
292         /* The sysfs dirent has been renamed */
293         if (strcmp(dentry->d_name.name, kn->name) != 0)
294                 goto out_bad;
295
296         /* The sysfs dirent has been moved to a different namespace */
297         if (kn->parent && kernfs_ns_enabled(kn->parent) &&
298             kernfs_info(dentry->d_sb)->ns != kn->ns)
299                 goto out_bad;
300
301         mutex_unlock(&sysfs_mutex);
302 out_valid:
303         return 1;
304 out_bad:
305         /* Remove the dentry from the dcache hashes.
306          * If this is a deleted dentry we use d_drop instead of d_delete
307          * so sysfs doesn't need to cope with negative dentries.
308          *
309          * If this is a dentry that has simply been renamed we
310          * use d_drop to remove it from the dcache lookup on its
311          * old parent.  If this dentry persists later when a lookup
312          * is performed at its new name the dentry will be readded
313          * to the dcache hashes.
314          */
315         mutex_unlock(&sysfs_mutex);
316
317         /* If we have submounts we must allow the vfs caches
318          * to lie about the state of the filesystem to prevent
319          * leaks and other nasty things.
320          */
321         if (check_submounts_and_drop(dentry) != 0)
322                 goto out_valid;
323
324         return 0;
325 }
326
327 static void sysfs_dentry_release(struct dentry *dentry)
328 {
329         kernfs_put(dentry->d_fsdata);
330 }
331
332 const struct dentry_operations sysfs_dentry_ops = {
333         .d_revalidate   = sysfs_dentry_revalidate,
334         .d_delete       = sysfs_dentry_delete,
335         .d_release      = sysfs_dentry_release,
336 };
337
338 struct kernfs_node *sysfs_new_dirent(struct kernfs_root *root,
339                                      const char *name, umode_t mode, int type)
340 {
341         char *dup_name = NULL;
342         struct kernfs_node *kn;
343         int ret;
344
345         if (type & KERNFS_COPY_NAME) {
346                 name = dup_name = kstrdup(name, GFP_KERNEL);
347                 if (!name)
348                         return NULL;
349         }
350
351         kn = kmem_cache_zalloc(sysfs_dir_cachep, GFP_KERNEL);
352         if (!kn)
353                 goto err_out1;
354
355         ret = ida_simple_get(&root->ino_ida, 1, 0, GFP_KERNEL);
356         if (ret < 0)
357                 goto err_out2;
358         kn->ino = ret;
359
360         atomic_set(&kn->count, 1);
361         atomic_set(&kn->active, 0);
362
363         kn->name = name;
364         kn->mode = mode;
365         kn->flags = type | KERNFS_REMOVED;
366
367         return kn;
368
369  err_out2:
370         kmem_cache_free(sysfs_dir_cachep, kn);
371  err_out1:
372         kfree(dup_name);
373         return NULL;
374 }
375
376 /**
377  *      sysfs_addrm_start - prepare for kernfs_node add/remove
378  *      @acxt: pointer to kernfs_addrm_cxt to be used
379  *
380  *      This function is called when the caller is about to add or remove
381  *      kernfs_node.  This function acquires sysfs_mutex.  @acxt is used to
382  *      keep and pass context to other addrm functions.
383  *
384  *      LOCKING:
385  *      Kernel thread context (may sleep).  sysfs_mutex is locked on
386  *      return.
387  */
388 void sysfs_addrm_start(struct kernfs_addrm_cxt *acxt)
389         __acquires(sysfs_mutex)
390 {
391         memset(acxt, 0, sizeof(*acxt));
392
393         mutex_lock(&sysfs_mutex);
394 }
395
396 /**
397  *      sysfs_add_one - add kernfs_node to parent without warning
398  *      @acxt: addrm context to use
399  *      @kn: kernfs_node to be added
400  *      @parent: the parent kernfs_node to add @kn to
401  *
402  *      Get @parent and set @kn->parent to it and increment nlink of the
403  *      parent inode if @kn is a directory and link into the children list
404  *      of the parent.
405  *
406  *      This function should be called between calls to
407  *      sysfs_addrm_start() and sysfs_addrm_finish() and should be
408  *      passed the same @acxt as passed to sysfs_addrm_start().
409  *
410  *      LOCKING:
411  *      Determined by sysfs_addrm_start().
412  *
413  *      RETURNS:
414  *      0 on success, -EEXIST if entry with the given name already
415  *      exists.
416  */
417 int sysfs_add_one(struct kernfs_addrm_cxt *acxt, struct kernfs_node *kn,
418                   struct kernfs_node *parent)
419 {
420         bool has_ns = kernfs_ns_enabled(parent);
421         struct kernfs_iattrs *ps_iattr;
422         int ret;
423
424         if (has_ns != (bool)kn->ns) {
425                 WARN(1, KERN_WARNING "sysfs: ns %s in '%s' for '%s'\n",
426                      has_ns ? "required" : "invalid", parent->name, kn->name);
427                 return -EINVAL;
428         }
429
430         if (kernfs_type(parent) != KERNFS_DIR)
431                 return -EINVAL;
432
433         kn->hash = sysfs_name_hash(kn->name, kn->ns);
434         kn->parent = parent;
435         kernfs_get(parent);
436
437         ret = sysfs_link_sibling(kn);
438         if (ret)
439                 return ret;
440
441         /* Update timestamps on the parent */
442         ps_iattr = parent->iattr;
443         if (ps_iattr) {
444                 struct iattr *ps_iattrs = &ps_iattr->ia_iattr;
445                 ps_iattrs->ia_ctime = ps_iattrs->ia_mtime = CURRENT_TIME;
446         }
447
448         /* Mark the entry added into directory tree */
449         kn->flags &= ~KERNFS_REMOVED;
450
451         return 0;
452 }
453
454 /**
455  *      sysfs_remove_one - remove kernfs_node from parent
456  *      @acxt: addrm context to use
457  *      @kn: kernfs_node to be removed
458  *
459  *      Mark @kn removed and drop nlink of parent inode if @kn is a
460  *      directory.  @kn is unlinked from the children list.
461  *
462  *      This function should be called between calls to
463  *      sysfs_addrm_start() and sysfs_addrm_finish() and should be
464  *      passed the same @acxt as passed to sysfs_addrm_start().
465  *
466  *      LOCKING:
467  *      Determined by sysfs_addrm_start().
468  */
469 static void sysfs_remove_one(struct kernfs_addrm_cxt *acxt,
470                              struct kernfs_node *kn)
471 {
472         struct kernfs_iattrs *ps_iattr;
473
474         /*
475          * Removal can be called multiple times on the same node.  Only the
476          * first invocation is effective and puts the base ref.
477          */
478         if (kn->flags & KERNFS_REMOVED)
479                 return;
480
481         if (kn->parent) {
482                 sysfs_unlink_sibling(kn);
483
484                 /* Update timestamps on the parent */
485                 ps_iattr = kn->parent->iattr;
486                 if (ps_iattr) {
487                         ps_iattr->ia_iattr.ia_ctime = CURRENT_TIME;
488                         ps_iattr->ia_iattr.ia_mtime = CURRENT_TIME;
489                 }
490         }
491
492         kn->flags |= KERNFS_REMOVED;
493         kn->u.removed_list = acxt->removed;
494         acxt->removed = kn;
495 }
496
497 /**
498  *      sysfs_addrm_finish - finish up kernfs_node add/remove
499  *      @acxt: addrm context to finish up
500  *
501  *      Finish up kernfs_node add/remove.  Resources acquired by
502  *      sysfs_addrm_start() are released and removed kernfs_nodes are
503  *      cleaned up.
504  *
505  *      LOCKING:
506  *      sysfs_mutex is released.
507  */
508 void sysfs_addrm_finish(struct kernfs_addrm_cxt *acxt)
509         __releases(sysfs_mutex)
510 {
511         /* release resources acquired by sysfs_addrm_start() */
512         mutex_unlock(&sysfs_mutex);
513
514         /* kill removed kernfs_nodes */
515         while (acxt->removed) {
516                 struct kernfs_node *kn = acxt->removed;
517
518                 acxt->removed = kn->u.removed_list;
519
520                 sysfs_deactivate(kn);
521                 sysfs_unmap_bin_file(kn);
522                 kernfs_put(kn);
523         }
524 }
525
526 /**
527  * kernfs_find_ns - find kernfs_node with the given name
528  * @parent: kernfs_node to search under
529  * @name: name to look for
530  * @ns: the namespace tag to use
531  *
532  * Look for kernfs_node with name @name under @parent.  Returns pointer to
533  * the found kernfs_node on success, %NULL on failure.
534  */
535 static struct kernfs_node *kernfs_find_ns(struct kernfs_node *parent,
536                                           const unsigned char *name,
537                                           const void *ns)
538 {
539         struct rb_node *node = parent->dir.children.rb_node;
540         bool has_ns = kernfs_ns_enabled(parent);
541         unsigned int hash;
542
543         lockdep_assert_held(&sysfs_mutex);
544
545         if (has_ns != (bool)ns) {
546                 WARN(1, KERN_WARNING "sysfs: ns %s in '%s' for '%s'\n",
547                      has_ns ? "required" : "invalid", parent->name, name);
548                 return NULL;
549         }
550
551         hash = sysfs_name_hash(name, ns);
552         while (node) {
553                 struct kernfs_node *kn;
554                 int result;
555
556                 kn = rb_to_kn(node);
557                 result = sysfs_name_compare(hash, name, ns, kn);
558                 if (result < 0)
559                         node = node->rb_left;
560                 else if (result > 0)
561                         node = node->rb_right;
562                 else
563                         return kn;
564         }
565         return NULL;
566 }
567
568 /**
569  * kernfs_find_and_get_ns - find and get kernfs_node with the given name
570  * @parent: kernfs_node to search under
571  * @name: name to look for
572  * @ns: the namespace tag to use
573  *
574  * Look for kernfs_node with name @name under @parent and get a reference
575  * if found.  This function may sleep and returns pointer to the found
576  * kernfs_node on success, %NULL on failure.
577  */
578 struct kernfs_node *kernfs_find_and_get_ns(struct kernfs_node *parent,
579                                            const char *name, const void *ns)
580 {
581         struct kernfs_node *kn;
582
583         mutex_lock(&sysfs_mutex);
584         kn = kernfs_find_ns(parent, name, ns);
585         kernfs_get(kn);
586         mutex_unlock(&sysfs_mutex);
587
588         return kn;
589 }
590 EXPORT_SYMBOL_GPL(kernfs_find_and_get_ns);
591
592 /**
593  * kernfs_create_root - create a new kernfs hierarchy
594  * @priv: opaque data associated with the new directory
595  *
596  * Returns the root of the new hierarchy on success, ERR_PTR() value on
597  * failure.
598  */
599 struct kernfs_root *kernfs_create_root(void *priv)
600 {
601         struct kernfs_root *root;
602         struct kernfs_node *kn;
603
604         root = kzalloc(sizeof(*root), GFP_KERNEL);
605         if (!root)
606                 return ERR_PTR(-ENOMEM);
607
608         ida_init(&root->ino_ida);
609
610         kn = sysfs_new_dirent(root, "", S_IFDIR | S_IRUGO | S_IXUGO, KERNFS_DIR);
611         if (!kn) {
612                 ida_destroy(&root->ino_ida);
613                 kfree(root);
614                 return ERR_PTR(-ENOMEM);
615         }
616
617         kn->flags &= ~KERNFS_REMOVED;
618         kn->priv = priv;
619         kn->dir.root = root;
620
621         root->kn = kn;
622
623         return root;
624 }
625
626 /**
627  * kernfs_destroy_root - destroy a kernfs hierarchy
628  * @root: root of the hierarchy to destroy
629  *
630  * Destroy the hierarchy anchored at @root by removing all existing
631  * directories and destroying @root.
632  */
633 void kernfs_destroy_root(struct kernfs_root *root)
634 {
635         kernfs_remove(root->kn);        /* will also free @root */
636 }
637
638 /**
639  * kernfs_create_dir_ns - create a directory
640  * @parent: parent in which to create a new directory
641  * @name: name of the new directory
642  * @priv: opaque data associated with the new directory
643  * @ns: optional namespace tag of the directory
644  *
645  * Returns the created node on success, ERR_PTR() value on failure.
646  */
647 struct kernfs_node *kernfs_create_dir_ns(struct kernfs_node *parent,
648                                          const char *name, void *priv,
649                                          const void *ns)
650 {
651         umode_t mode = S_IFDIR | S_IRWXU | S_IRUGO | S_IXUGO;
652         struct kernfs_addrm_cxt acxt;
653         struct kernfs_node *kn;
654         int rc;
655
656         /* allocate */
657         kn = sysfs_new_dirent(kernfs_root(parent), name, mode, KERNFS_DIR);
658         if (!kn)
659                 return ERR_PTR(-ENOMEM);
660
661         kn->dir.root = parent->dir.root;
662         kn->ns = ns;
663         kn->priv = priv;
664
665         /* link in */
666         sysfs_addrm_start(&acxt);
667         rc = sysfs_add_one(&acxt, kn, parent);
668         sysfs_addrm_finish(&acxt);
669
670         if (!rc)
671                 return kn;
672
673         kernfs_put(kn);
674         return ERR_PTR(rc);
675 }
676
677 static struct dentry *sysfs_lookup(struct inode *dir, struct dentry *dentry,
678                                    unsigned int flags)
679 {
680         struct dentry *ret = NULL;
681         struct kernfs_node *parent = dentry->d_parent->d_fsdata;
682         struct kernfs_node *kn;
683         struct inode *inode;
684         const void *ns = NULL;
685
686         mutex_lock(&sysfs_mutex);
687
688         if (kernfs_ns_enabled(parent))
689                 ns = kernfs_info(dir->i_sb)->ns;
690
691         kn = kernfs_find_ns(parent, dentry->d_name.name, ns);
692
693         /* no such entry */
694         if (!kn) {
695                 ret = ERR_PTR(-ENOENT);
696                 goto out_unlock;
697         }
698         kernfs_get(kn);
699         dentry->d_fsdata = kn;
700
701         /* attach dentry and inode */
702         inode = sysfs_get_inode(dir->i_sb, kn);
703         if (!inode) {
704                 ret = ERR_PTR(-ENOMEM);
705                 goto out_unlock;
706         }
707
708         /* instantiate and hash dentry */
709         ret = d_materialise_unique(dentry, inode);
710  out_unlock:
711         mutex_unlock(&sysfs_mutex);
712         return ret;
713 }
714
715 const struct inode_operations sysfs_dir_inode_operations = {
716         .lookup         = sysfs_lookup,
717         .permission     = sysfs_permission,
718         .setattr        = sysfs_setattr,
719         .getattr        = sysfs_getattr,
720         .setxattr       = sysfs_setxattr,
721         .removexattr    = sysfs_removexattr,
722         .getxattr       = sysfs_getxattr,
723         .listxattr      = sysfs_listxattr,
724 };
725
726 static struct kernfs_node *sysfs_leftmost_descendant(struct kernfs_node *pos)
727 {
728         struct kernfs_node *last;
729
730         while (true) {
731                 struct rb_node *rbn;
732
733                 last = pos;
734
735                 if (kernfs_type(pos) != KERNFS_DIR)
736                         break;
737
738                 rbn = rb_first(&pos->dir.children);
739                 if (!rbn)
740                         break;
741
742                 pos = rb_to_kn(rbn);
743         }
744
745         return last;
746 }
747
748 /**
749  * sysfs_next_descendant_post - find the next descendant for post-order walk
750  * @pos: the current position (%NULL to initiate traversal)
751  * @root: kernfs_node whose descendants to walk
752  *
753  * Find the next descendant to visit for post-order traversal of @root's
754  * descendants.  @root is included in the iteration and the last node to be
755  * visited.
756  */
757 static struct kernfs_node *sysfs_next_descendant_post(struct kernfs_node *pos,
758                                                       struct kernfs_node *root)
759 {
760         struct rb_node *rbn;
761
762         lockdep_assert_held(&sysfs_mutex);
763
764         /* if first iteration, visit leftmost descendant which may be root */
765         if (!pos)
766                 return sysfs_leftmost_descendant(root);
767
768         /* if we visited @root, we're done */
769         if (pos == root)
770                 return NULL;
771
772         /* if there's an unvisited sibling, visit its leftmost descendant */
773         rbn = rb_next(&pos->rb);
774         if (rbn)
775                 return sysfs_leftmost_descendant(rb_to_kn(rbn));
776
777         /* no sibling left, visit parent */
778         return pos->parent;
779 }
780
781 static void __kernfs_remove(struct kernfs_addrm_cxt *acxt,
782                             struct kernfs_node *kn)
783 {
784         struct kernfs_node *pos, *next;
785
786         if (!kn)
787                 return;
788
789         pr_debug("sysfs %s: removing\n", kn->name);
790
791         next = NULL;
792         do {
793                 pos = next;
794                 next = sysfs_next_descendant_post(pos, kn);
795                 if (pos)
796                         sysfs_remove_one(acxt, pos);
797         } while (next);
798 }
799
800 /**
801  * kernfs_remove - remove a kernfs_node recursively
802  * @kn: the kernfs_node to remove
803  *
804  * Remove @kn along with all its subdirectories and files.
805  */
806 void kernfs_remove(struct kernfs_node *kn)
807 {
808         struct kernfs_addrm_cxt acxt;
809
810         sysfs_addrm_start(&acxt);
811         __kernfs_remove(&acxt, kn);
812         sysfs_addrm_finish(&acxt);
813 }
814
815 /**
816  * kernfs_remove_by_name_ns - find a kernfs_node by name and remove it
817  * @parent: parent of the target
818  * @name: name of the kernfs_node to remove
819  * @ns: namespace tag of the kernfs_node to remove
820  *
821  * Look for the kernfs_node with @name and @ns under @parent and remove it.
822  * Returns 0 on success, -ENOENT if such entry doesn't exist.
823  */
824 int kernfs_remove_by_name_ns(struct kernfs_node *parent, const char *name,
825                              const void *ns)
826 {
827         struct kernfs_addrm_cxt acxt;
828         struct kernfs_node *kn;
829
830         if (!parent) {
831                 WARN(1, KERN_WARNING "sysfs: can not remove '%s', no directory\n",
832                         name);
833                 return -ENOENT;
834         }
835
836         sysfs_addrm_start(&acxt);
837
838         kn = kernfs_find_ns(parent, name, ns);
839         if (kn)
840                 __kernfs_remove(&acxt, kn);
841
842         sysfs_addrm_finish(&acxt);
843
844         if (kn)
845                 return 0;
846         else
847                 return -ENOENT;
848 }
849
850 /**
851  * kernfs_rename_ns - move and rename a kernfs_node
852  * @kn: target node
853  * @new_parent: new parent to put @sd under
854  * @new_name: new name
855  * @new_ns: new namespace tag
856  */
857 int kernfs_rename_ns(struct kernfs_node *kn, struct kernfs_node *new_parent,
858                      const char *new_name, const void *new_ns)
859 {
860         int error;
861
862         mutex_lock(&sysfs_mutex);
863
864         error = 0;
865         if ((kn->parent == new_parent) && (kn->ns == new_ns) &&
866             (strcmp(kn->name, new_name) == 0))
867                 goto out;       /* nothing to rename */
868
869         error = -EEXIST;
870         if (kernfs_find_ns(new_parent, new_name, new_ns))
871                 goto out;
872
873         /* rename kernfs_node */
874         if (strcmp(kn->name, new_name) != 0) {
875                 error = -ENOMEM;
876                 new_name = kstrdup(new_name, GFP_KERNEL);
877                 if (!new_name)
878                         goto out;
879
880                 kfree(kn->name);
881                 kn->name = new_name;
882         }
883
884         /*
885          * Move to the appropriate place in the appropriate directories rbtree.
886          */
887         sysfs_unlink_sibling(kn);
888         kernfs_get(new_parent);
889         kernfs_put(kn->parent);
890         kn->ns = new_ns;
891         kn->hash = sysfs_name_hash(kn->name, kn->ns);
892         kn->parent = new_parent;
893         sysfs_link_sibling(kn);
894
895         error = 0;
896  out:
897         mutex_unlock(&sysfs_mutex);
898         return error;
899 }
900
901 /* Relationship between s_mode and the DT_xxx types */
902 static inline unsigned char dt_type(struct kernfs_node *kn)
903 {
904         return (kn->mode >> 12) & 15;
905 }
906
907 static int sysfs_dir_release(struct inode *inode, struct file *filp)
908 {
909         kernfs_put(filp->private_data);
910         return 0;
911 }
912
913 static struct kernfs_node *sysfs_dir_pos(const void *ns,
914         struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos)
915 {
916         if (pos) {
917                 int valid = !(pos->flags & KERNFS_REMOVED) &&
918                         pos->parent == parent && hash == pos->hash;
919                 kernfs_put(pos);
920                 if (!valid)
921                         pos = NULL;
922         }
923         if (!pos && (hash > 1) && (hash < INT_MAX)) {
924                 struct rb_node *node = parent->dir.children.rb_node;
925                 while (node) {
926                         pos = rb_to_kn(node);
927
928                         if (hash < pos->hash)
929                                 node = node->rb_left;
930                         else if (hash > pos->hash)
931                                 node = node->rb_right;
932                         else
933                                 break;
934                 }
935         }
936         /* Skip over entries in the wrong namespace */
937         while (pos && pos->ns != ns) {
938                 struct rb_node *node = rb_next(&pos->rb);
939                 if (!node)
940                         pos = NULL;
941                 else
942                         pos = rb_to_kn(node);
943         }
944         return pos;
945 }
946
947 static struct kernfs_node *sysfs_dir_next_pos(const void *ns,
948         struct kernfs_node *parent, ino_t ino, struct kernfs_node *pos)
949 {
950         pos = sysfs_dir_pos(ns, parent, ino, pos);
951         if (pos)
952                 do {
953                         struct rb_node *node = rb_next(&pos->rb);
954                         if (!node)
955                                 pos = NULL;
956                         else
957                                 pos = rb_to_kn(node);
958                 } while (pos && pos->ns != ns);
959         return pos;
960 }
961
962 static int sysfs_readdir(struct file *file, struct dir_context *ctx)
963 {
964         struct dentry *dentry = file->f_path.dentry;
965         struct kernfs_node *parent = dentry->d_fsdata;
966         struct kernfs_node *pos = file->private_data;
967         const void *ns = NULL;
968
969         if (!dir_emit_dots(file, ctx))
970                 return 0;
971         mutex_lock(&sysfs_mutex);
972
973         if (kernfs_ns_enabled(parent))
974                 ns = kernfs_info(dentry->d_sb)->ns;
975
976         for (pos = sysfs_dir_pos(ns, parent, ctx->pos, pos);
977              pos;
978              pos = sysfs_dir_next_pos(ns, parent, ctx->pos, pos)) {
979                 const char *name = pos->name;
980                 unsigned int type = dt_type(pos);
981                 int len = strlen(name);
982                 ino_t ino = pos->ino;
983
984                 ctx->pos = pos->hash;
985                 file->private_data = pos;
986                 kernfs_get(pos);
987
988                 mutex_unlock(&sysfs_mutex);
989                 if (!dir_emit(ctx, name, len, ino, type))
990                         return 0;
991                 mutex_lock(&sysfs_mutex);
992         }
993         mutex_unlock(&sysfs_mutex);
994         file->private_data = NULL;
995         ctx->pos = INT_MAX;
996         return 0;
997 }
998
999 static loff_t sysfs_dir_llseek(struct file *file, loff_t offset, int whence)
1000 {
1001         struct inode *inode = file_inode(file);
1002         loff_t ret;
1003
1004         mutex_lock(&inode->i_mutex);
1005         ret = generic_file_llseek(file, offset, whence);
1006         mutex_unlock(&inode->i_mutex);
1007
1008         return ret;
1009 }
1010
1011 const struct file_operations sysfs_dir_operations = {
1012         .read           = generic_read_dir,
1013         .iterate        = sysfs_readdir,
1014         .release        = sysfs_dir_release,
1015         .llseek         = sysfs_dir_llseek,
1016 };