]> Pileus Git - ~andy/linux/blob - fs/kernfs/dir.c
510b5062ef302184736503ec076d9ffafdb136aa
[~andy/linux] / 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(kernfs_mutex);
21
22 #define rb_to_kn(X) rb_entry((X), struct kernfs_node, rb)
23
24 /**
25  *      kernfs_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 kernfs_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 kernfs_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 kernfs_sd_compare(const struct kernfs_node *left,
58                              const struct kernfs_node *right)
59 {
60         return kernfs_name_compare(left->hash, left->name, left->ns, right);
61 }
62
63 /**
64  *      kernfs_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(kernfs_mutex)
72  *
73  *      RETURNS:
74  *      0 on susccess -EEXIST on failure.
75  */
76 static int kernfs_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 = kernfs_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  *      kernfs_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(kernfs_mutex)
113  */
114 static void kernfs_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  *      kernfs_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 *kernfs_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  *      kernfs_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 kernfs_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  *      kernfs_deactivate - deactivate kernfs_node
174  *      @kn: kernfs_node to deactivate
175  *
176  *      Deny new active references and drain existing ones.
177  */
178 static void kernfs_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), "kernfs: free using entry: %s/%s\n",
239              parent ? parent->name : "", kn->name);
240
241         if (kernfs_type(kn) == KERNFS_LINK)
242                 kernfs_put(kn->symlink.target_kn);
243         if (!(kn->flags & KERNFS_STATIC_NAME))
244                 kfree(kn->name);
245         if (kn->iattr) {
246                 if (kn->iattr->ia_secdata)
247                         security_release_secctx(kn->iattr->ia_secdata,
248                                                 kn->iattr->ia_secdata_len);
249                 simple_xattrs_free(&kn->iattr->xattrs);
250         }
251         kfree(kn->iattr);
252         ida_simple_remove(&root->ino_ida, kn->ino);
253         kmem_cache_free(kernfs_node_cache, kn);
254
255         kn = parent;
256         if (kn) {
257                 if (atomic_dec_and_test(&kn->count))
258                         goto repeat;
259         } else {
260                 /* just released the root kn, free @root too */
261                 ida_destroy(&root->ino_ida);
262                 kfree(root);
263         }
264 }
265 EXPORT_SYMBOL_GPL(kernfs_put);
266
267 static int kernfs_dop_revalidate(struct dentry *dentry, unsigned int flags)
268 {
269         struct kernfs_node *kn;
270
271         if (flags & LOOKUP_RCU)
272                 return -ECHILD;
273
274         /* Always perform fresh lookup for negatives */
275         if (!dentry->d_inode)
276                 goto out_bad_unlocked;
277
278         kn = dentry->d_fsdata;
279         mutex_lock(&kernfs_mutex);
280
281         /* The kernfs node has been deleted */
282         if (kn->flags & KERNFS_REMOVED)
283                 goto out_bad;
284
285         /* The kernfs node has been moved? */
286         if (dentry->d_parent->d_fsdata != kn->parent)
287                 goto out_bad;
288
289         /* The kernfs node has been renamed */
290         if (strcmp(dentry->d_name.name, kn->name) != 0)
291                 goto out_bad;
292
293         /* The kernfs node has been moved to a different namespace */
294         if (kn->parent && kernfs_ns_enabled(kn->parent) &&
295             kernfs_info(dentry->d_sb)->ns != kn->ns)
296                 goto out_bad;
297
298         mutex_unlock(&kernfs_mutex);
299 out_valid:
300         return 1;
301 out_bad:
302         mutex_unlock(&kernfs_mutex);
303 out_bad_unlocked:
304         /*
305          * @dentry doesn't match the underlying kernfs node, drop the
306          * dentry and force lookup.  If we have submounts we must allow the
307          * vfs caches to lie about the state of the filesystem to prevent
308          * leaks and other nasty things, so use check_submounts_and_drop()
309          * instead of d_drop().
310          */
311         if (check_submounts_and_drop(dentry) != 0)
312                 goto out_valid;
313
314         return 0;
315 }
316
317 static void kernfs_dop_release(struct dentry *dentry)
318 {
319         kernfs_put(dentry->d_fsdata);
320 }
321
322 const struct dentry_operations kernfs_dops = {
323         .d_revalidate   = kernfs_dop_revalidate,
324         .d_release      = kernfs_dop_release,
325 };
326
327 struct kernfs_node *kernfs_new_node(struct kernfs_root *root, const char *name,
328                                     umode_t mode, unsigned flags)
329 {
330         char *dup_name = NULL;
331         struct kernfs_node *kn;
332         int ret;
333
334         if (!(flags & KERNFS_STATIC_NAME)) {
335                 name = dup_name = kstrdup(name, GFP_KERNEL);
336                 if (!name)
337                         return NULL;
338         }
339
340         kn = kmem_cache_zalloc(kernfs_node_cache, GFP_KERNEL);
341         if (!kn)
342                 goto err_out1;
343
344         ret = ida_simple_get(&root->ino_ida, 1, 0, GFP_KERNEL);
345         if (ret < 0)
346                 goto err_out2;
347         kn->ino = ret;
348
349         atomic_set(&kn->count, 1);
350         atomic_set(&kn->active, 0);
351
352         kn->name = name;
353         kn->mode = mode;
354         kn->flags = flags | KERNFS_REMOVED;
355
356         return kn;
357
358  err_out2:
359         kmem_cache_free(kernfs_node_cache, kn);
360  err_out1:
361         kfree(dup_name);
362         return NULL;
363 }
364
365 /**
366  *      kernfs_addrm_start - prepare for kernfs_node add/remove
367  *      @acxt: pointer to kernfs_addrm_cxt to be used
368  *
369  *      This function is called when the caller is about to add or remove
370  *      kernfs_node.  This function acquires kernfs_mutex.  @acxt is used
371  *      to keep and pass context to other addrm functions.
372  *
373  *      LOCKING:
374  *      Kernel thread context (may sleep).  kernfs_mutex is locked on
375  *      return.
376  */
377 void kernfs_addrm_start(struct kernfs_addrm_cxt *acxt)
378         __acquires(kernfs_mutex)
379 {
380         memset(acxt, 0, sizeof(*acxt));
381
382         mutex_lock(&kernfs_mutex);
383 }
384
385 /**
386  *      kernfs_add_one - add kernfs_node to parent without warning
387  *      @acxt: addrm context to use
388  *      @kn: kernfs_node to be added
389  *      @parent: the parent kernfs_node to add @kn to
390  *
391  *      Get @parent and set @kn->parent to it and increment nlink of the
392  *      parent inode if @kn is a directory and link into the children list
393  *      of the parent.
394  *
395  *      This function should be called between calls to
396  *      kernfs_addrm_start() and kernfs_addrm_finish() and should be passed
397  *      the same @acxt as passed to kernfs_addrm_start().
398  *
399  *      LOCKING:
400  *      Determined by kernfs_addrm_start().
401  *
402  *      RETURNS:
403  *      0 on success, -EEXIST if entry with the given name already
404  *      exists.
405  */
406 int kernfs_add_one(struct kernfs_addrm_cxt *acxt, struct kernfs_node *kn,
407                   struct kernfs_node *parent)
408 {
409         bool has_ns = kernfs_ns_enabled(parent);
410         struct kernfs_iattrs *ps_iattr;
411         int ret;
412
413         if (has_ns != (bool)kn->ns) {
414                 WARN(1, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n",
415                      has_ns ? "required" : "invalid", parent->name, kn->name);
416                 return -EINVAL;
417         }
418
419         if (kernfs_type(parent) != KERNFS_DIR)
420                 return -EINVAL;
421
422         if (parent->flags & KERNFS_REMOVED)
423                 return -ENOENT;
424
425         kn->hash = kernfs_name_hash(kn->name, kn->ns);
426         kn->parent = parent;
427         kernfs_get(parent);
428
429         ret = kernfs_link_sibling(kn);
430         if (ret)
431                 return ret;
432
433         /* Update timestamps on the parent */
434         ps_iattr = parent->iattr;
435         if (ps_iattr) {
436                 struct iattr *ps_iattrs = &ps_iattr->ia_iattr;
437                 ps_iattrs->ia_ctime = ps_iattrs->ia_mtime = CURRENT_TIME;
438         }
439
440         /* Mark the entry added into directory tree */
441         kn->flags &= ~KERNFS_REMOVED;
442
443         return 0;
444 }
445
446 /**
447  *      kernfs_remove_one - remove kernfs_node from parent
448  *      @acxt: addrm context to use
449  *      @kn: kernfs_node to be removed
450  *
451  *      Mark @kn removed and drop nlink of parent inode if @kn is a
452  *      directory.  @kn is unlinked from the children list.
453  *
454  *      This function should be called between calls to
455  *      kernfs_addrm_start() and kernfs_addrm_finish() and should be
456  *      passed the same @acxt as passed to kernfs_addrm_start().
457  *
458  *      LOCKING:
459  *      Determined by kernfs_addrm_start().
460  */
461 static void kernfs_remove_one(struct kernfs_addrm_cxt *acxt,
462                               struct kernfs_node *kn)
463 {
464         struct kernfs_iattrs *ps_iattr;
465
466         /*
467          * Removal can be called multiple times on the same node.  Only the
468          * first invocation is effective and puts the base ref.
469          */
470         if (kn->flags & KERNFS_REMOVED)
471                 return;
472
473         if (kn->parent) {
474                 kernfs_unlink_sibling(kn);
475
476                 /* Update timestamps on the parent */
477                 ps_iattr = kn->parent->iattr;
478                 if (ps_iattr) {
479                         ps_iattr->ia_iattr.ia_ctime = CURRENT_TIME;
480                         ps_iattr->ia_iattr.ia_mtime = CURRENT_TIME;
481                 }
482         }
483
484         kn->flags |= KERNFS_REMOVED;
485         kn->u.removed_list = acxt->removed;
486         acxt->removed = kn;
487 }
488
489 /**
490  *      kernfs_addrm_finish - finish up kernfs_node add/remove
491  *      @acxt: addrm context to finish up
492  *
493  *      Finish up kernfs_node add/remove.  Resources acquired by
494  *      kernfs_addrm_start() are released and removed kernfs_nodes are
495  *      cleaned up.
496  *
497  *      LOCKING:
498  *      kernfs_mutex is released.
499  */
500 void kernfs_addrm_finish(struct kernfs_addrm_cxt *acxt)
501         __releases(kernfs_mutex)
502 {
503         /* release resources acquired by kernfs_addrm_start() */
504         mutex_unlock(&kernfs_mutex);
505
506         /* kill removed kernfs_nodes */
507         while (acxt->removed) {
508                 struct kernfs_node *kn = acxt->removed;
509
510                 acxt->removed = kn->u.removed_list;
511
512                 kernfs_deactivate(kn);
513                 kernfs_unmap_bin_file(kn);
514                 kernfs_put(kn);
515         }
516 }
517
518 /**
519  * kernfs_find_ns - find kernfs_node with the given name
520  * @parent: kernfs_node to search under
521  * @name: name to look for
522  * @ns: the namespace tag to use
523  *
524  * Look for kernfs_node with name @name under @parent.  Returns pointer to
525  * the found kernfs_node on success, %NULL on failure.
526  */
527 static struct kernfs_node *kernfs_find_ns(struct kernfs_node *parent,
528                                           const unsigned char *name,
529                                           const void *ns)
530 {
531         struct rb_node *node = parent->dir.children.rb_node;
532         bool has_ns = kernfs_ns_enabled(parent);
533         unsigned int hash;
534
535         lockdep_assert_held(&kernfs_mutex);
536
537         if (has_ns != (bool)ns) {
538                 WARN(1, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n",
539                      has_ns ? "required" : "invalid", parent->name, name);
540                 return NULL;
541         }
542
543         hash = kernfs_name_hash(name, ns);
544         while (node) {
545                 struct kernfs_node *kn;
546                 int result;
547
548                 kn = rb_to_kn(node);
549                 result = kernfs_name_compare(hash, name, ns, kn);
550                 if (result < 0)
551                         node = node->rb_left;
552                 else if (result > 0)
553                         node = node->rb_right;
554                 else
555                         return kn;
556         }
557         return NULL;
558 }
559
560 /**
561  * kernfs_find_and_get_ns - find and get kernfs_node with the given name
562  * @parent: kernfs_node to search under
563  * @name: name to look for
564  * @ns: the namespace tag to use
565  *
566  * Look for kernfs_node with name @name under @parent and get a reference
567  * if found.  This function may sleep and returns pointer to the found
568  * kernfs_node on success, %NULL on failure.
569  */
570 struct kernfs_node *kernfs_find_and_get_ns(struct kernfs_node *parent,
571                                            const char *name, const void *ns)
572 {
573         struct kernfs_node *kn;
574
575         mutex_lock(&kernfs_mutex);
576         kn = kernfs_find_ns(parent, name, ns);
577         kernfs_get(kn);
578         mutex_unlock(&kernfs_mutex);
579
580         return kn;
581 }
582 EXPORT_SYMBOL_GPL(kernfs_find_and_get_ns);
583
584 /**
585  * kernfs_create_root - create a new kernfs hierarchy
586  * @kdops: optional directory syscall operations for the hierarchy
587  * @priv: opaque data associated with the new directory
588  *
589  * Returns the root of the new hierarchy on success, ERR_PTR() value on
590  * failure.
591  */
592 struct kernfs_root *kernfs_create_root(struct kernfs_dir_ops *kdops, void *priv)
593 {
594         struct kernfs_root *root;
595         struct kernfs_node *kn;
596
597         root = kzalloc(sizeof(*root), GFP_KERNEL);
598         if (!root)
599                 return ERR_PTR(-ENOMEM);
600
601         ida_init(&root->ino_ida);
602
603         kn = kernfs_new_node(root, "", S_IFDIR | S_IRUGO | S_IXUGO, KERNFS_DIR);
604         if (!kn) {
605                 ida_destroy(&root->ino_ida);
606                 kfree(root);
607                 return ERR_PTR(-ENOMEM);
608         }
609
610         kn->flags &= ~KERNFS_REMOVED;
611         kn->priv = priv;
612         kn->dir.root = root;
613
614         root->dir_ops = kdops;
615         root->kn = kn;
616
617         return root;
618 }
619
620 /**
621  * kernfs_destroy_root - destroy a kernfs hierarchy
622  * @root: root of the hierarchy to destroy
623  *
624  * Destroy the hierarchy anchored at @root by removing all existing
625  * directories and destroying @root.
626  */
627 void kernfs_destroy_root(struct kernfs_root *root)
628 {
629         kernfs_remove(root->kn);        /* will also free @root */
630 }
631
632 /**
633  * kernfs_create_dir_ns - create a directory
634  * @parent: parent in which to create a new directory
635  * @name: name of the new directory
636  * @mode: mode of the new directory
637  * @priv: opaque data associated with the new directory
638  * @ns: optional namespace tag of the directory
639  *
640  * Returns the created node on success, ERR_PTR() value on failure.
641  */
642 struct kernfs_node *kernfs_create_dir_ns(struct kernfs_node *parent,
643                                          const char *name, umode_t mode,
644                                          void *priv, const void *ns)
645 {
646         struct kernfs_addrm_cxt acxt;
647         struct kernfs_node *kn;
648         int rc;
649
650         /* allocate */
651         kn = kernfs_new_node(kernfs_root(parent), name, mode | S_IFDIR,
652                              KERNFS_DIR);
653         if (!kn)
654                 return ERR_PTR(-ENOMEM);
655
656         kn->dir.root = parent->dir.root;
657         kn->ns = ns;
658         kn->priv = priv;
659
660         /* link in */
661         kernfs_addrm_start(&acxt);
662         rc = kernfs_add_one(&acxt, kn, parent);
663         kernfs_addrm_finish(&acxt);
664
665         if (!rc)
666                 return kn;
667
668         kernfs_put(kn);
669         return ERR_PTR(rc);
670 }
671
672 static struct dentry *kernfs_iop_lookup(struct inode *dir,
673                                         struct dentry *dentry,
674                                         unsigned int flags)
675 {
676         struct dentry *ret;
677         struct kernfs_node *parent = dentry->d_parent->d_fsdata;
678         struct kernfs_node *kn;
679         struct inode *inode;
680         const void *ns = NULL;
681
682         mutex_lock(&kernfs_mutex);
683
684         if (kernfs_ns_enabled(parent))
685                 ns = kernfs_info(dir->i_sb)->ns;
686
687         kn = kernfs_find_ns(parent, dentry->d_name.name, ns);
688
689         /* no such entry */
690         if (!kn) {
691                 ret = NULL;
692                 goto out_unlock;
693         }
694         kernfs_get(kn);
695         dentry->d_fsdata = kn;
696
697         /* attach dentry and inode */
698         inode = kernfs_get_inode(dir->i_sb, kn);
699         if (!inode) {
700                 ret = ERR_PTR(-ENOMEM);
701                 goto out_unlock;
702         }
703
704         /* instantiate and hash dentry */
705         ret = d_materialise_unique(dentry, inode);
706  out_unlock:
707         mutex_unlock(&kernfs_mutex);
708         return ret;
709 }
710
711 static int kernfs_iop_mkdir(struct inode *dir, struct dentry *dentry,
712                             umode_t mode)
713 {
714         struct kernfs_node *parent = dir->i_private;
715         struct kernfs_dir_ops *kdops = kernfs_root(parent)->dir_ops;
716
717         if (!kdops || !kdops->mkdir)
718                 return -EPERM;
719
720         return kdops->mkdir(parent, dentry->d_name.name, mode);
721 }
722
723 static int kernfs_iop_rmdir(struct inode *dir, struct dentry *dentry)
724 {
725         struct kernfs_node *kn  = dentry->d_fsdata;
726         struct kernfs_dir_ops *kdops = kernfs_root(kn)->dir_ops;
727
728         if (!kdops || !kdops->rmdir)
729                 return -EPERM;
730
731         return kdops->rmdir(kn);
732 }
733
734 static int kernfs_iop_rename(struct inode *old_dir, struct dentry *old_dentry,
735                              struct inode *new_dir, struct dentry *new_dentry)
736 {
737         struct kernfs_node *kn  = old_dentry->d_fsdata;
738         struct kernfs_node *new_parent = new_dir->i_private;
739         struct kernfs_dir_ops *kdops = kernfs_root(kn)->dir_ops;
740
741         if (!kdops || !kdops->rename)
742                 return -EPERM;
743
744         return kdops->rename(kn, new_parent, new_dentry->d_name.name);
745 }
746
747 const struct inode_operations kernfs_dir_iops = {
748         .lookup         = kernfs_iop_lookup,
749         .permission     = kernfs_iop_permission,
750         .setattr        = kernfs_iop_setattr,
751         .getattr        = kernfs_iop_getattr,
752         .setxattr       = kernfs_iop_setxattr,
753         .removexattr    = kernfs_iop_removexattr,
754         .getxattr       = kernfs_iop_getxattr,
755         .listxattr      = kernfs_iop_listxattr,
756
757         .mkdir          = kernfs_iop_mkdir,
758         .rmdir          = kernfs_iop_rmdir,
759         .rename         = kernfs_iop_rename,
760 };
761
762 static struct kernfs_node *kernfs_leftmost_descendant(struct kernfs_node *pos)
763 {
764         struct kernfs_node *last;
765
766         while (true) {
767                 struct rb_node *rbn;
768
769                 last = pos;
770
771                 if (kernfs_type(pos) != KERNFS_DIR)
772                         break;
773
774                 rbn = rb_first(&pos->dir.children);
775                 if (!rbn)
776                         break;
777
778                 pos = rb_to_kn(rbn);
779         }
780
781         return last;
782 }
783
784 /**
785  * kernfs_next_descendant_post - find the next descendant for post-order walk
786  * @pos: the current position (%NULL to initiate traversal)
787  * @root: kernfs_node whose descendants to walk
788  *
789  * Find the next descendant to visit for post-order traversal of @root's
790  * descendants.  @root is included in the iteration and the last node to be
791  * visited.
792  */
793 static struct kernfs_node *kernfs_next_descendant_post(struct kernfs_node *pos,
794                                                        struct kernfs_node *root)
795 {
796         struct rb_node *rbn;
797
798         lockdep_assert_held(&kernfs_mutex);
799
800         /* if first iteration, visit leftmost descendant which may be root */
801         if (!pos)
802                 return kernfs_leftmost_descendant(root);
803
804         /* if we visited @root, we're done */
805         if (pos == root)
806                 return NULL;
807
808         /* if there's an unvisited sibling, visit its leftmost descendant */
809         rbn = rb_next(&pos->rb);
810         if (rbn)
811                 return kernfs_leftmost_descendant(rb_to_kn(rbn));
812
813         /* no sibling left, visit parent */
814         return pos->parent;
815 }
816
817 static void __kernfs_remove(struct kernfs_addrm_cxt *acxt,
818                             struct kernfs_node *kn)
819 {
820         struct kernfs_node *pos, *next;
821
822         if (!kn)
823                 return;
824
825         pr_debug("kernfs %s: removing\n", kn->name);
826
827         next = NULL;
828         do {
829                 pos = next;
830                 next = kernfs_next_descendant_post(pos, kn);
831                 if (pos)
832                         kernfs_remove_one(acxt, pos);
833         } while (next);
834 }
835
836 /**
837  * kernfs_remove - remove a kernfs_node recursively
838  * @kn: the kernfs_node to remove
839  *
840  * Remove @kn along with all its subdirectories and files.
841  */
842 void kernfs_remove(struct kernfs_node *kn)
843 {
844         struct kernfs_addrm_cxt acxt;
845
846         kernfs_addrm_start(&acxt);
847         __kernfs_remove(&acxt, kn);
848         kernfs_addrm_finish(&acxt);
849 }
850
851 /**
852  * kernfs_remove_by_name_ns - find a kernfs_node by name and remove it
853  * @parent: parent of the target
854  * @name: name of the kernfs_node to remove
855  * @ns: namespace tag of the kernfs_node to remove
856  *
857  * Look for the kernfs_node with @name and @ns under @parent and remove it.
858  * Returns 0 on success, -ENOENT if such entry doesn't exist.
859  */
860 int kernfs_remove_by_name_ns(struct kernfs_node *parent, const char *name,
861                              const void *ns)
862 {
863         struct kernfs_addrm_cxt acxt;
864         struct kernfs_node *kn;
865
866         if (!parent) {
867                 WARN(1, KERN_WARNING "kernfs: can not remove '%s', no directory\n",
868                         name);
869                 return -ENOENT;
870         }
871
872         kernfs_addrm_start(&acxt);
873
874         kn = kernfs_find_ns(parent, name, ns);
875         if (kn)
876                 __kernfs_remove(&acxt, kn);
877
878         kernfs_addrm_finish(&acxt);
879
880         if (kn)
881                 return 0;
882         else
883                 return -ENOENT;
884 }
885
886 /**
887  * kernfs_rename_ns - move and rename a kernfs_node
888  * @kn: target node
889  * @new_parent: new parent to put @sd under
890  * @new_name: new name
891  * @new_ns: new namespace tag
892  */
893 int kernfs_rename_ns(struct kernfs_node *kn, struct kernfs_node *new_parent,
894                      const char *new_name, const void *new_ns)
895 {
896         int error;
897
898         mutex_lock(&kernfs_mutex);
899
900         error = -ENOENT;
901         if ((kn->flags | new_parent->flags) & KERNFS_REMOVED)
902                 goto out;
903
904         error = 0;
905         if ((kn->parent == new_parent) && (kn->ns == new_ns) &&
906             (strcmp(kn->name, new_name) == 0))
907                 goto out;       /* nothing to rename */
908
909         error = -EEXIST;
910         if (kernfs_find_ns(new_parent, new_name, new_ns))
911                 goto out;
912
913         /* rename kernfs_node */
914         if (strcmp(kn->name, new_name) != 0) {
915                 error = -ENOMEM;
916                 new_name = kstrdup(new_name, GFP_KERNEL);
917                 if (!new_name)
918                         goto out;
919
920                 if (kn->flags & KERNFS_STATIC_NAME)
921                         kn->flags &= ~KERNFS_STATIC_NAME;
922                 else
923                         kfree(kn->name);
924
925                 kn->name = new_name;
926         }
927
928         /*
929          * Move to the appropriate place in the appropriate directories rbtree.
930          */
931         kernfs_unlink_sibling(kn);
932         kernfs_get(new_parent);
933         kernfs_put(kn->parent);
934         kn->ns = new_ns;
935         kn->hash = kernfs_name_hash(kn->name, kn->ns);
936         kn->parent = new_parent;
937         kernfs_link_sibling(kn);
938
939         error = 0;
940  out:
941         mutex_unlock(&kernfs_mutex);
942         return error;
943 }
944
945 /* Relationship between s_mode and the DT_xxx types */
946 static inline unsigned char dt_type(struct kernfs_node *kn)
947 {
948         return (kn->mode >> 12) & 15;
949 }
950
951 static int kernfs_dir_fop_release(struct inode *inode, struct file *filp)
952 {
953         kernfs_put(filp->private_data);
954         return 0;
955 }
956
957 static struct kernfs_node *kernfs_dir_pos(const void *ns,
958         struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos)
959 {
960         if (pos) {
961                 int valid = !(pos->flags & KERNFS_REMOVED) &&
962                         pos->parent == parent && hash == pos->hash;
963                 kernfs_put(pos);
964                 if (!valid)
965                         pos = NULL;
966         }
967         if (!pos && (hash > 1) && (hash < INT_MAX)) {
968                 struct rb_node *node = parent->dir.children.rb_node;
969                 while (node) {
970                         pos = rb_to_kn(node);
971
972                         if (hash < pos->hash)
973                                 node = node->rb_left;
974                         else if (hash > pos->hash)
975                                 node = node->rb_right;
976                         else
977                                 break;
978                 }
979         }
980         /* Skip over entries in the wrong namespace */
981         while (pos && pos->ns != ns) {
982                 struct rb_node *node = rb_next(&pos->rb);
983                 if (!node)
984                         pos = NULL;
985                 else
986                         pos = rb_to_kn(node);
987         }
988         return pos;
989 }
990
991 static struct kernfs_node *kernfs_dir_next_pos(const void *ns,
992         struct kernfs_node *parent, ino_t ino, struct kernfs_node *pos)
993 {
994         pos = kernfs_dir_pos(ns, parent, ino, pos);
995         if (pos)
996                 do {
997                         struct rb_node *node = rb_next(&pos->rb);
998                         if (!node)
999                                 pos = NULL;
1000                         else
1001                                 pos = rb_to_kn(node);
1002                 } while (pos && pos->ns != ns);
1003         return pos;
1004 }
1005
1006 static int kernfs_fop_readdir(struct file *file, struct dir_context *ctx)
1007 {
1008         struct dentry *dentry = file->f_path.dentry;
1009         struct kernfs_node *parent = dentry->d_fsdata;
1010         struct kernfs_node *pos = file->private_data;
1011         const void *ns = NULL;
1012
1013         if (!dir_emit_dots(file, ctx))
1014                 return 0;
1015         mutex_lock(&kernfs_mutex);
1016
1017         if (kernfs_ns_enabled(parent))
1018                 ns = kernfs_info(dentry->d_sb)->ns;
1019
1020         for (pos = kernfs_dir_pos(ns, parent, ctx->pos, pos);
1021              pos;
1022              pos = kernfs_dir_next_pos(ns, parent, ctx->pos, pos)) {
1023                 const char *name = pos->name;
1024                 unsigned int type = dt_type(pos);
1025                 int len = strlen(name);
1026                 ino_t ino = pos->ino;
1027
1028                 ctx->pos = pos->hash;
1029                 file->private_data = pos;
1030                 kernfs_get(pos);
1031
1032                 mutex_unlock(&kernfs_mutex);
1033                 if (!dir_emit(ctx, name, len, ino, type))
1034                         return 0;
1035                 mutex_lock(&kernfs_mutex);
1036         }
1037         mutex_unlock(&kernfs_mutex);
1038         file->private_data = NULL;
1039         ctx->pos = INT_MAX;
1040         return 0;
1041 }
1042
1043 static loff_t kernfs_dir_fop_llseek(struct file *file, loff_t offset,
1044                                     int whence)
1045 {
1046         struct inode *inode = file_inode(file);
1047         loff_t ret;
1048
1049         mutex_lock(&inode->i_mutex);
1050         ret = generic_file_llseek(file, offset, whence);
1051         mutex_unlock(&inode->i_mutex);
1052
1053         return ret;
1054 }
1055
1056 const struct file_operations kernfs_dir_fops = {
1057         .read           = generic_read_dir,
1058         .iterate        = kernfs_fop_readdir,
1059         .release        = kernfs_dir_fop_release,
1060         .llseek         = kernfs_dir_fop_llseek,
1061 };