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