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