Merge to Fedora kernel-2.6.18-1.2224_FC5 patched with stable patch-2.6.18.1-vs2.0...
[linux-2.6.git] / fs / dcache.c
1 /*
2  * fs/dcache.c
3  *
4  * Complete reimplementation
5  * (C) 1997 Thomas Schoebel-Theuer,
6  * with heavy changes by Linus Torvalds
7  */
8
9 /*
10  * Notes on the allocation strategy:
11  *
12  * The dcache is a master of the icache - whenever a dcache entry
13  * exists, the inode will always exist. "iput()" is done either when
14  * the dcache entry is deleted or garbage collected.
15  */
16
17 #include <linux/syscalls.h>
18 #include <linux/string.h>
19 #include <linux/mm.h>
20 #include <linux/fs.h>
21 #include <linux/fsnotify.h>
22 #include <linux/slab.h>
23 #include <linux/init.h>
24 #include <linux/smp_lock.h>
25 #include <linux/hash.h>
26 #include <linux/cache.h>
27 #include <linux/module.h>
28 #include <linux/mount.h>
29 #include <linux/file.h>
30 #include <asm/uaccess.h>
31 #include <linux/security.h>
32 #include <linux/seqlock.h>
33 #include <linux/swap.h>
34 #include <linux/bootmem.h>
35
36
37 int sysctl_vfs_cache_pressure __read_mostly = 100;
38 EXPORT_SYMBOL_GPL(sysctl_vfs_cache_pressure);
39
40  __cacheline_aligned_in_smp DEFINE_SPINLOCK(dcache_lock);
41 static __cacheline_aligned_in_smp DEFINE_SEQLOCK(rename_lock);
42
43 EXPORT_SYMBOL(dcache_lock);
44
45 static kmem_cache_t *dentry_cache __read_mostly;
46
47 #define DNAME_INLINE_LEN (sizeof(struct dentry)-offsetof(struct dentry,d_iname))
48
49 /*
50  * This is the single most critical data structure when it comes
51  * to the dcache: the hashtable for lookups. Somebody should try
52  * to make this good - I've just made it work.
53  *
54  * This hash-function tries to avoid losing too many bits of hash
55  * information, yet avoid using a prime hash-size or similar.
56  */
57 #define D_HASHBITS     d_hash_shift
58 #define D_HASHMASK     d_hash_mask
59
60 static unsigned int d_hash_mask __read_mostly;
61 static unsigned int d_hash_shift __read_mostly;
62 static struct hlist_head *dentry_hashtable __read_mostly;
63 static LIST_HEAD(dentry_unused);
64
65 /* Statistics gathering. */
66 struct dentry_stat_t dentry_stat = {
67         .age_limit = 45,
68 };
69
70 static void d_callback(struct rcu_head *head)
71 {
72         struct dentry * dentry = container_of(head, struct dentry, d_u.d_rcu);
73
74         if (dname_external(dentry))
75                 kfree(dentry->d_name.name);
76         kmem_cache_free(dentry_cache, dentry); 
77 }
78
79 /*
80  * no dcache_lock, please.  The caller must decrement dentry_stat.nr_dentry
81  * inside dcache_lock.
82  */
83 static void d_free(struct dentry *dentry)
84 {
85         if (dentry->d_op && dentry->d_op->d_release)
86                 dentry->d_op->d_release(dentry);
87         if (dentry->d_extra_attributes) {
88                 kfree(dentry->d_extra_attributes);
89                 dentry->d_extra_attributes = NULL;
90         }
91         call_rcu(&dentry->d_u.d_rcu, d_callback);
92 }
93
94 /*
95  * Release the dentry's inode, using the filesystem
96  * d_iput() operation if defined.
97  * Called with dcache_lock and per dentry lock held, drops both.
98  */
99 static void dentry_iput(struct dentry * dentry)
100 {
101         struct inode *inode = dentry->d_inode;
102         if (inode) {
103                 dentry->d_inode = NULL;
104                 list_del_init(&dentry->d_alias);
105                 spin_unlock(&dentry->d_lock);
106                 spin_unlock(&dcache_lock);
107                 if (!inode->i_nlink)
108                         fsnotify_inoderemove(inode);
109                 if (dentry->d_op && dentry->d_op->d_iput)
110                         dentry->d_op->d_iput(dentry, inode);
111                 else
112                         iput(inode);
113         } else {
114                 spin_unlock(&dentry->d_lock);
115                 spin_unlock(&dcache_lock);
116         }
117 }
118
119 /* 
120  * This is dput
121  *
122  * This is complicated by the fact that we do not want to put
123  * dentries that are no longer on any hash chain on the unused
124  * list: we'd much rather just get rid of them immediately.
125  *
126  * However, that implies that we have to traverse the dentry
127  * tree upwards to the parents which might _also_ now be
128  * scheduled for deletion (it may have been only waiting for
129  * its last child to go away).
130  *
131  * This tail recursion is done by hand as we don't want to depend
132  * on the compiler to always get this right (gcc generally doesn't).
133  * Real recursion would eat up our stack space.
134  */
135
136 /*
137  * dput - release a dentry
138  * @dentry: dentry to release 
139  *
140  * Release a dentry. This will drop the usage count and if appropriate
141  * call the dentry unlink method as well as removing it from the queues and
142  * releasing its resources. If the parent dentries were scheduled for release
143  * they too may now get deleted.
144  *
145  * no dcache lock, please.
146  */
147
148 void dput(struct dentry *dentry)
149 {
150         if (!dentry)
151                 return;
152
153 repeat:
154         if (atomic_read(&dentry->d_count) == 1)
155                 might_sleep();
156         if (!atomic_dec_and_lock(&dentry->d_count, &dcache_lock))
157                 return;
158
159         spin_lock(&dentry->d_lock);
160         if (atomic_read(&dentry->d_count)) {
161                 spin_unlock(&dentry->d_lock);
162                 spin_unlock(&dcache_lock);
163                 return;
164         }
165
166         /*
167          * AV: ->d_delete() is _NOT_ allowed to block now.
168          */
169         if (dentry->d_op && dentry->d_op->d_delete) {
170                 if (dentry->d_op->d_delete(dentry))
171                         goto unhash_it;
172         }
173         /* Unreachable? Get rid of it */
174         if (d_unhashed(dentry))
175                 goto kill_it;
176         if (list_empty(&dentry->d_lru)) {
177                 dentry->d_flags |= DCACHE_REFERENCED;
178                 list_add(&dentry->d_lru, &dentry_unused);
179                 dentry_stat.nr_unused++;
180         }
181         spin_unlock(&dentry->d_lock);
182         spin_unlock(&dcache_lock);
183         return;
184
185 unhash_it:
186         __d_drop(dentry);
187
188 kill_it: {
189                 struct dentry *parent;
190
191                 /* If dentry was on d_lru list
192                  * delete it from there
193                  */
194                 if (!list_empty(&dentry->d_lru)) {
195                         list_del(&dentry->d_lru);
196                         dentry_stat.nr_unused--;
197                 }
198                 list_del(&dentry->d_u.d_child);
199                 dentry_stat.nr_dentry--;        /* For d_free, below */
200                 /*drops the locks, at that point nobody can reach this dentry */
201                 dentry_iput(dentry);
202                 parent = dentry->d_parent;
203                 d_free(dentry);
204                 if (dentry == parent)
205                         return;
206                 dentry = parent;
207                 goto repeat;
208         }
209 }
210
211 /**
212  * d_invalidate - invalidate a dentry
213  * @dentry: dentry to invalidate
214  *
215  * Try to invalidate the dentry if it turns out to be
216  * possible. If there are other dentries that can be
217  * reached through this one we can't delete it and we
218  * return -EBUSY. On success we return 0.
219  *
220  * no dcache lock.
221  */
222  
223 int d_invalidate(struct dentry * dentry)
224 {
225         /*
226          * If it's already been dropped, return OK.
227          */
228         spin_lock(&dcache_lock);
229         if (d_unhashed(dentry)) {
230                 spin_unlock(&dcache_lock);
231                 return 0;
232         }
233         /*
234          * Check whether to do a partial shrink_dcache
235          * to get rid of unused child entries.
236          */
237         if (!list_empty(&dentry->d_subdirs)) {
238                 spin_unlock(&dcache_lock);
239                 shrink_dcache_parent(dentry);
240                 spin_lock(&dcache_lock);
241         }
242
243         /*
244          * Somebody else still using it?
245          *
246          * If it's a directory, we can't drop it
247          * for fear of somebody re-populating it
248          * with children (even though dropping it
249          * would make it unreachable from the root,
250          * we might still populate it if it was a
251          * working directory or similar).
252          */
253         spin_lock(&dentry->d_lock);
254         if (atomic_read(&dentry->d_count) > 1) {
255                 if (dentry->d_inode && S_ISDIR(dentry->d_inode->i_mode)) {
256                         spin_unlock(&dentry->d_lock);
257                         spin_unlock(&dcache_lock);
258                         return -EBUSY;
259                 }
260         }
261
262         __d_drop(dentry);
263         spin_unlock(&dentry->d_lock);
264         spin_unlock(&dcache_lock);
265         return 0;
266 }
267
268 /* This should be called _only_ with dcache_lock held */
269
270 static inline struct dentry * __dget_locked(struct dentry *dentry)
271 {
272         atomic_inc(&dentry->d_count);
273         if (!list_empty(&dentry->d_lru)) {
274                 dentry_stat.nr_unused--;
275                 list_del_init(&dentry->d_lru);
276         }
277         return dentry;
278 }
279
280 struct dentry * dget_locked(struct dentry *dentry)
281 {
282         return __dget_locked(dentry);
283 }
284
285 /**
286  * d_find_alias - grab a hashed alias of inode
287  * @inode: inode in question
288  * @want_discon:  flag, used by d_splice_alias, to request
289  *          that only a DISCONNECTED alias be returned.
290  *
291  * If inode has a hashed alias, or is a directory and has any alias,
292  * acquire the reference to alias and return it. Otherwise return NULL.
293  * Notice that if inode is a directory there can be only one alias and
294  * it can be unhashed only if it has no children, or if it is the root
295  * of a filesystem.
296  *
297  * If the inode has a DCACHE_DISCONNECTED alias, then prefer
298  * any other hashed alias over that one unless @want_discon is set,
299  * in which case only return a DCACHE_DISCONNECTED alias.
300  */
301
302 static struct dentry * __d_find_alias(struct inode *inode, int want_discon)
303 {
304         struct list_head *head, *next, *tmp;
305         struct dentry *alias, *discon_alias=NULL;
306
307         head = &inode->i_dentry;
308         next = inode->i_dentry.next;
309         while (next != head) {
310                 tmp = next;
311                 next = tmp->next;
312                 prefetch(next);
313                 alias = list_entry(tmp, struct dentry, d_alias);
314                 if (S_ISDIR(inode->i_mode) || !d_unhashed(alias)) {
315                         if (alias->d_flags & DCACHE_DISCONNECTED)
316                                 discon_alias = alias;
317                         else if (!want_discon) {
318                                 __dget_locked(alias);
319                                 return alias;
320                         }
321                 }
322         }
323         if (discon_alias)
324                 __dget_locked(discon_alias);
325         return discon_alias;
326 }
327
328 struct dentry * d_find_alias(struct inode *inode)
329 {
330         struct dentry *de = NULL;
331
332         if (!list_empty(&inode->i_dentry)) {
333                 spin_lock(&dcache_lock);
334                 de = __d_find_alias(inode, 0);
335                 spin_unlock(&dcache_lock);
336         }
337         return de;
338 }
339
340 /*
341  *      Try to kill dentries associated with this inode.
342  * WARNING: you must own a reference to inode.
343  */
344 void d_prune_aliases(struct inode *inode)
345 {
346         struct dentry *dentry;
347 restart:
348         spin_lock(&dcache_lock);
349         list_for_each_entry(dentry, &inode->i_dentry, d_alias) {
350                 spin_lock(&dentry->d_lock);
351                 if (!atomic_read(&dentry->d_count)) {
352                         __dget_locked(dentry);
353                         __d_drop(dentry);
354                         spin_unlock(&dentry->d_lock);
355                         spin_unlock(&dcache_lock);
356                         dput(dentry);
357                         goto restart;
358                 }
359                 spin_unlock(&dentry->d_lock);
360         }
361         spin_unlock(&dcache_lock);
362 }
363
364 /*
365  * Throw away a dentry - free the inode, dput the parent.  This requires that
366  * the LRU list has already been removed.
367  *
368  * Called with dcache_lock, drops it and then regains.
369  * Called with dentry->d_lock held, drops it.
370  */
371 static void prune_one_dentry(struct dentry * dentry)
372 {
373         struct dentry * parent;
374
375         __d_drop(dentry);
376         list_del(&dentry->d_u.d_child);
377         dentry_stat.nr_dentry--;        /* For d_free, below */
378         dentry_iput(dentry);
379         parent = dentry->d_parent;
380         d_free(dentry);
381         if (parent != dentry)
382                 dput(parent);
383         spin_lock(&dcache_lock);
384 }
385
386 /**
387  * prune_dcache - shrink the dcache
388  * @count: number of entries to try and free
389  * @sb: if given, ignore dentries for other superblocks
390  *         which are being unmounted.
391  *
392  * Shrink the dcache. This is done when we need
393  * more memory, or simply when we need to unmount
394  * something (at which point we need to unuse
395  * all dentries).
396  *
397  * This function may fail to free any resources if
398  * all the dentries are in use.
399  */
400  
401 static void prune_dcache(int count, struct super_block *sb)
402 {
403         spin_lock(&dcache_lock);
404         for (; count ; count--) {
405                 struct dentry *dentry;
406                 struct list_head *tmp;
407                 struct rw_semaphore *s_umount;
408
409                 cond_resched_lock(&dcache_lock);
410
411                 tmp = dentry_unused.prev;
412                 if (sb) {
413                         /* Try to find a dentry for this sb, but don't try
414                          * too hard, if they aren't near the tail they will
415                          * be moved down again soon
416                          */
417                         int skip = count;
418                         while (skip && tmp != &dentry_unused &&
419                             list_entry(tmp, struct dentry, d_lru)->d_sb != sb) {
420                                 skip--;
421                                 tmp = tmp->prev;
422                         }
423                 }
424                 if (tmp == &dentry_unused)
425                         break;
426                 list_del_init(tmp);
427                 prefetch(dentry_unused.prev);
428                 dentry_stat.nr_unused--;
429                 dentry = list_entry(tmp, struct dentry, d_lru);
430
431                 spin_lock(&dentry->d_lock);
432                 /*
433                  * We found an inuse dentry which was not removed from
434                  * dentry_unused because of laziness during lookup.  Do not free
435                  * it - just keep it off the dentry_unused list.
436                  */
437                 if (atomic_read(&dentry->d_count)) {
438                         spin_unlock(&dentry->d_lock);
439                         continue;
440                 }
441                 /* If the dentry was recently referenced, don't free it. */
442                 if (dentry->d_flags & DCACHE_REFERENCED) {
443                         dentry->d_flags &= ~DCACHE_REFERENCED;
444                         list_add(&dentry->d_lru, &dentry_unused);
445                         dentry_stat.nr_unused++;
446                         spin_unlock(&dentry->d_lock);
447                         continue;
448                 }
449                 /*
450                  * If the dentry is not DCACHED_REFERENCED, it is time
451                  * to remove it from the dcache, provided the super block is
452                  * NULL (which means we are trying to reclaim memory)
453                  * or this dentry belongs to the same super block that
454                  * we want to shrink.
455                  */
456                 /*
457                  * If this dentry is for "my" filesystem, then I can prune it
458                  * without taking the s_umount lock (I already hold it).
459                  */
460                 if (sb && dentry->d_sb == sb) {
461                         prune_one_dentry(dentry);
462                         continue;
463                 }
464                 /*
465                  * ...otherwise we need to be sure this filesystem isn't being
466                  * unmounted, otherwise we could race with
467                  * generic_shutdown_super(), and end up holding a reference to
468                  * an inode while the filesystem is unmounted.
469                  * So we try to get s_umount, and make sure s_root isn't NULL.
470                  * (Take a local copy of s_umount to avoid a use-after-free of
471                  * `dentry').
472                  */
473                 s_umount = &dentry->d_sb->s_umount;
474                 if (down_read_trylock(s_umount)) {
475                         if (dentry->d_sb->s_root != NULL) {
476                                 prune_one_dentry(dentry);
477                                 up_read(s_umount);
478                                 continue;
479                         }
480                         up_read(s_umount);
481                 }
482                 spin_unlock(&dentry->d_lock);
483                 /* Cannot remove the first dentry, and it isn't appropriate
484                  * to move it to the head of the list, so give up, and try
485                  * later
486                  */
487                 break;
488         }
489         spin_unlock(&dcache_lock);
490 }
491
492 /*
493  * Shrink the dcache for the specified super block.
494  * This allows us to unmount a device without disturbing
495  * the dcache for the other devices.
496  *
497  * This implementation makes just two traversals of the
498  * unused list.  On the first pass we move the selected
499  * dentries to the most recent end, and on the second
500  * pass we free them.  The second pass must restart after
501  * each dput(), but since the target dentries are all at
502  * the end, it's really just a single traversal.
503  */
504
505 /**
506  * shrink_dcache_sb - shrink dcache for a superblock
507  * @sb: superblock
508  *
509  * Shrink the dcache for the specified super block. This
510  * is used to free the dcache before unmounting a file
511  * system
512  */
513
514 void shrink_dcache_sb(struct super_block * sb)
515 {
516         struct list_head *tmp, *next;
517         struct dentry *dentry;
518
519         /*
520          * Pass one ... move the dentries for the specified
521          * superblock to the most recent end of the unused list.
522          */
523         spin_lock(&dcache_lock);
524         list_for_each_safe(tmp, next, &dentry_unused) {
525                 dentry = list_entry(tmp, struct dentry, d_lru);
526                 if (dentry->d_sb != sb)
527                         continue;
528                 list_move(tmp, &dentry_unused);
529         }
530
531         /*
532          * Pass two ... free the dentries for this superblock.
533          */
534 repeat:
535         list_for_each_safe(tmp, next, &dentry_unused) {
536                 dentry = list_entry(tmp, struct dentry, d_lru);
537                 if (dentry->d_sb != sb)
538                         continue;
539                 dentry_stat.nr_unused--;
540                 list_del_init(tmp);
541                 spin_lock(&dentry->d_lock);
542                 if (atomic_read(&dentry->d_count)) {
543                         spin_unlock(&dentry->d_lock);
544                         continue;
545                 }
546                 prune_one_dentry(dentry);
547                 cond_resched_lock(&dcache_lock);
548                 goto repeat;
549         }
550         spin_unlock(&dcache_lock);
551 }
552
553 /*
554  * destroy a single subtree of dentries for unmount
555  * - see the comments on shrink_dcache_for_umount() for a description of the
556  *   locking
557  */
558 static void shrink_dcache_for_umount_subtree(struct dentry *dentry)
559 {
560         struct dentry *parent;
561
562         BUG_ON(!IS_ROOT(dentry));
563
564         /* detach this root from the system */
565         spin_lock(&dcache_lock);
566         if (!list_empty(&dentry->d_lru)) {
567                 dentry_stat.nr_unused--;
568                 list_del_init(&dentry->d_lru);
569         }
570         __d_drop(dentry);
571         spin_unlock(&dcache_lock);
572
573         for (;;) {
574                 /* descend to the first leaf in the current subtree */
575                 while (!list_empty(&dentry->d_subdirs)) {
576                         struct dentry *loop;
577
578                         /* this is a branch with children - detach all of them
579                          * from the system in one go */
580                         spin_lock(&dcache_lock);
581                         list_for_each_entry(loop, &dentry->d_subdirs,
582                                             d_u.d_child) {
583                                 if (!list_empty(&loop->d_lru)) {
584                                         dentry_stat.nr_unused--;
585                                         list_del_init(&loop->d_lru);
586                                 }
587
588                                 __d_drop(loop);
589                                 cond_resched_lock(&dcache_lock);
590                         }
591                         spin_unlock(&dcache_lock);
592
593                         /* move to the first child */
594                         dentry = list_entry(dentry->d_subdirs.next,
595                                             struct dentry, d_u.d_child);
596                 }
597
598                 /* consume the dentries from this leaf up through its parents
599                  * until we find one with children or run out altogether */
600                 do {
601                         struct inode *inode;
602
603                         if (atomic_read(&dentry->d_count) != 0) {
604                                 printk(KERN_ERR
605                                        "BUG: Dentry %p{i=%lx,n=%s}"
606                                        " still in use (%d)"
607                                        " [unmount of %s %s]\n",
608                                        dentry,
609                                        dentry->d_inode ?
610                                        dentry->d_inode->i_ino : 0UL,
611                                        dentry->d_name.name,
612                                        atomic_read(&dentry->d_count),
613                                        dentry->d_sb->s_type->name,
614                                        dentry->d_sb->s_id);
615                                 BUG();
616                         }
617
618                         parent = dentry->d_parent;
619                         if (parent == dentry)
620                                 parent = NULL;
621                         else
622                                 atomic_dec(&parent->d_count);
623
624                         list_del(&dentry->d_u.d_child);
625                         dentry_stat.nr_dentry--;        /* For d_free, below */
626
627                         inode = dentry->d_inode;
628                         if (inode) {
629                                 dentry->d_inode = NULL;
630                                 list_del_init(&dentry->d_alias);
631                                 if (dentry->d_op && dentry->d_op->d_iput)
632                                         dentry->d_op->d_iput(dentry, inode);
633                                 else
634                                         iput(inode);
635                         }
636
637                         d_free(dentry);
638
639                         /* finished when we fall off the top of the tree,
640                          * otherwise we ascend to the parent and move to the
641                          * next sibling if there is one */
642                         if (!parent)
643                                 return;
644
645                         dentry = parent;
646
647                 } while (list_empty(&dentry->d_subdirs));
648
649                 dentry = list_entry(dentry->d_subdirs.next,
650                                     struct dentry, d_u.d_child);
651         }
652 }
653
654 /*
655  * destroy the dentries attached to a superblock on unmounting
656  * - we don't need to use dentry->d_lock, and only need dcache_lock when
657  *   removing the dentry from the system lists and hashes because:
658  *   - the superblock is detached from all mountings and open files, so the
659  *     dentry trees will not be rearranged by the VFS
660  *   - s_umount is write-locked, so the memory pressure shrinker will ignore
661  *     any dentries belonging to this superblock that it comes across
662  *   - the filesystem itself is no longer permitted to rearrange the dentries
663  *     in this superblock
664  */
665 void shrink_dcache_for_umount(struct super_block *sb)
666 {
667         struct dentry *dentry;
668
669         if (down_read_trylock(&sb->s_umount))
670                 BUG();
671
672         dentry = sb->s_root;
673         sb->s_root = NULL;
674         atomic_dec(&dentry->d_count);
675         shrink_dcache_for_umount_subtree(dentry);
676
677         while (!hlist_empty(&sb->s_anon)) {
678                 dentry = hlist_entry(sb->s_anon.first, struct dentry, d_hash);
679                 shrink_dcache_for_umount_subtree(dentry);
680         }
681 }
682
683 /*
684  * Search for at least 1 mount point in the dentry's subdirs.
685  * We descend to the next level whenever the d_subdirs
686  * list is non-empty and continue searching.
687  */
688  
689 /**
690  * have_submounts - check for mounts over a dentry
691  * @parent: dentry to check.
692  *
693  * Return true if the parent or its subdirectories contain
694  * a mount point
695  */
696  
697 int have_submounts(struct dentry *parent)
698 {
699         struct dentry *this_parent = parent;
700         struct list_head *next;
701
702         spin_lock(&dcache_lock);
703         if (d_mountpoint(parent))
704                 goto positive;
705 repeat:
706         next = this_parent->d_subdirs.next;
707 resume:
708         while (next != &this_parent->d_subdirs) {
709                 struct list_head *tmp = next;
710                 struct dentry *dentry = list_entry(tmp, struct dentry, d_u.d_child);
711                 next = tmp->next;
712                 /* Have we found a mount point ? */
713                 if (d_mountpoint(dentry))
714                         goto positive;
715                 if (!list_empty(&dentry->d_subdirs)) {
716                         this_parent = dentry;
717                         goto repeat;
718                 }
719         }
720         /*
721          * All done at this level ... ascend and resume the search.
722          */
723         if (this_parent != parent) {
724                 next = this_parent->d_u.d_child.next;
725                 this_parent = this_parent->d_parent;
726                 goto resume;
727         }
728         spin_unlock(&dcache_lock);
729         return 0; /* No mount points found in tree */
730 positive:
731         spin_unlock(&dcache_lock);
732         return 1;
733 }
734
735 /*
736  * Search the dentry child list for the specified parent,
737  * and move any unused dentries to the end of the unused
738  * list for prune_dcache(). We descend to the next level
739  * whenever the d_subdirs list is non-empty and continue
740  * searching.
741  *
742  * It returns zero iff there are no unused children,
743  * otherwise  it returns the number of children moved to
744  * the end of the unused list. This may not be the total
745  * number of unused children, because select_parent can
746  * drop the lock and return early due to latency
747  * constraints.
748  */
749 static int select_parent(struct dentry * parent)
750 {
751         struct dentry *this_parent = parent;
752         struct list_head *next;
753         int found = 0;
754
755         spin_lock(&dcache_lock);
756 repeat:
757         next = this_parent->d_subdirs.next;
758 resume:
759         while (next != &this_parent->d_subdirs) {
760                 struct list_head *tmp = next;
761                 struct dentry *dentry = list_entry(tmp, struct dentry, d_u.d_child);
762                 next = tmp->next;
763
764                 if (!list_empty(&dentry->d_lru)) {
765                         dentry_stat.nr_unused--;
766                         list_del_init(&dentry->d_lru);
767                 }
768                 /* 
769                  * move only zero ref count dentries to the end 
770                  * of the unused list for prune_dcache
771                  */
772                 if (!atomic_read(&dentry->d_count)) {
773                         list_add_tail(&dentry->d_lru, &dentry_unused);
774                         dentry_stat.nr_unused++;
775                         found++;
776                 }
777
778                 /*
779                  * We can return to the caller if we have found some (this
780                  * ensures forward progress). We'll be coming back to find
781                  * the rest.
782                  */
783                 if (found && need_resched())
784                         goto out;
785
786                 /*
787                  * Descend a level if the d_subdirs list is non-empty.
788                  */
789                 if (!list_empty(&dentry->d_subdirs)) {
790                         this_parent = dentry;
791                         goto repeat;
792                 }
793         }
794         /*
795          * All done at this level ... ascend and resume the search.
796          */
797         if (this_parent != parent) {
798                 next = this_parent->d_u.d_child.next;
799                 this_parent = this_parent->d_parent;
800                 goto resume;
801         }
802 out:
803         spin_unlock(&dcache_lock);
804         return found;
805 }
806
807 /**
808  * shrink_dcache_parent - prune dcache
809  * @parent: parent of entries to prune
810  *
811  * Prune the dcache to remove unused children of the parent dentry.
812  */
813  
814 void shrink_dcache_parent(struct dentry * parent)
815 {
816         int found;
817
818         while ((found = select_parent(parent)) != 0)
819                 prune_dcache(found, parent->d_sb);
820 }
821
822 /*
823  * Scan `nr' dentries and return the number which remain.
824  *
825  * We need to avoid reentering the filesystem if the caller is performing a
826  * GFP_NOFS allocation attempt.  One example deadlock is:
827  *
828  * ext2_new_block->getblk->GFP->shrink_dcache_memory->prune_dcache->
829  * prune_one_dentry->dput->dentry_iput->iput->inode->i_sb->s_op->put_inode->
830  * ext2_discard_prealloc->ext2_free_blocks->lock_super->DEADLOCK.
831  *
832  * In this case we return -1 to tell the caller that we baled.
833  */
834 static int shrink_dcache_memory(int nr, gfp_t gfp_mask)
835 {
836         if (nr) {
837                 if (!(gfp_mask & __GFP_FS))
838                         return -1;
839                 prune_dcache(nr, NULL);
840         }
841         return (dentry_stat.nr_unused / 100) * sysctl_vfs_cache_pressure;
842 }
843
844 /**
845  * d_alloc      -       allocate a dcache entry
846  * @parent: parent of entry to allocate
847  * @name: qstr of the name
848  *
849  * Allocates a dentry. It returns %NULL if there is insufficient memory
850  * available. On a success the dentry is returned. The name passed in is
851  * copied and the copy passed in may be reused after this call.
852  */
853  
854 struct dentry *d_alloc(struct dentry * parent, const struct qstr *name)
855 {
856         struct dentry *dentry;
857         char *dname;
858
859         dentry = kmem_cache_alloc(dentry_cache, GFP_KERNEL); 
860         if (!dentry)
861                 return NULL;
862
863         if (name->len > DNAME_INLINE_LEN-1) {
864                 dname = kmalloc(name->len + 1, GFP_KERNEL);
865                 if (!dname) {
866                         kmem_cache_free(dentry_cache, dentry); 
867                         return NULL;
868                 }
869         } else  {
870                 dname = dentry->d_iname;
871         }       
872         dentry->d_name.name = dname;
873
874         dentry->d_name.len = name->len;
875         dentry->d_name.hash = name->hash;
876         memcpy(dname, name->name, name->len);
877         dname[name->len] = 0;
878
879         atomic_set(&dentry->d_count, 1);
880         dentry->d_flags = DCACHE_UNHASHED;
881         spin_lock_init(&dentry->d_lock);
882         dentry->d_inode = NULL;
883         dentry->d_parent = NULL;
884         dentry->d_sb = NULL;
885         dentry->d_op = NULL;
886         dentry->d_fsdata = NULL;
887         dentry->d_extra_attributes = NULL;
888         dentry->d_mounted = 0;
889 #ifdef CONFIG_PROFILING
890         dentry->d_cookie = NULL;
891 #endif
892         INIT_HLIST_NODE(&dentry->d_hash);
893         INIT_LIST_HEAD(&dentry->d_lru);
894         INIT_LIST_HEAD(&dentry->d_subdirs);
895         INIT_LIST_HEAD(&dentry->d_alias);
896
897         if (parent) {
898                 dentry->d_parent = dget(parent);
899                 dentry->d_sb = parent->d_sb;
900         } else {
901                 INIT_LIST_HEAD(&dentry->d_u.d_child);
902         }
903
904         spin_lock(&dcache_lock);
905         if (parent)
906                 list_add(&dentry->d_u.d_child, &parent->d_subdirs);
907         dentry_stat.nr_dentry++;
908         spin_unlock(&dcache_lock);
909
910         return dentry;
911 }
912
913 struct dentry *d_alloc_name(struct dentry *parent, const char *name)
914 {
915         struct qstr q;
916
917         q.name = name;
918         q.len = strlen(name);
919         q.hash = full_name_hash(q.name, q.len);
920         return d_alloc(parent, &q);
921 }
922
923 /**
924  * d_instantiate - fill in inode information for a dentry
925  * @entry: dentry to complete
926  * @inode: inode to attach to this dentry
927  *
928  * Fill in inode information in the entry.
929  *
930  * This turns negative dentries into productive full members
931  * of society.
932  *
933  * NOTE! This assumes that the inode count has been incremented
934  * (or otherwise set) by the caller to indicate that it is now
935  * in use by the dcache.
936  */
937  
938 void d_instantiate(struct dentry *entry, struct inode * inode)
939 {
940         BUG_ON(!list_empty(&entry->d_alias));
941         spin_lock(&dcache_lock);
942         if (inode)
943                 list_add(&entry->d_alias, &inode->i_dentry);
944         entry->d_inode = inode;
945         fsnotify_d_instantiate(entry, inode);
946         spin_unlock(&dcache_lock);
947         security_d_instantiate(entry, inode);
948 }
949
950 /**
951  * d_instantiate_unique - instantiate a non-aliased dentry
952  * @entry: dentry to instantiate
953  * @inode: inode to attach to this dentry
954  *
955  * Fill in inode information in the entry. On success, it returns NULL.
956  * If an unhashed alias of "entry" already exists, then we return the
957  * aliased dentry instead and drop one reference to inode.
958  *
959  * Note that in order to avoid conflicts with rename() etc, the caller
960  * had better be holding the parent directory semaphore.
961  *
962  * This also assumes that the inode count has been incremented
963  * (or otherwise set) by the caller to indicate that it is now
964  * in use by the dcache.
965  */
966 static struct dentry *__d_instantiate_unique(struct dentry *entry,
967                                              struct inode *inode)
968 {
969         struct dentry *alias;
970         int len = entry->d_name.len;
971         const char *name = entry->d_name.name;
972         unsigned int hash = entry->d_name.hash;
973
974         if (!inode) {
975                 entry->d_inode = NULL;
976                 return NULL;
977         }
978
979         list_for_each_entry(alias, &inode->i_dentry, d_alias) {
980                 struct qstr *qstr = &alias->d_name;
981
982                 if (qstr->hash != hash)
983                         continue;
984                 if (alias->d_parent != entry->d_parent)
985                         continue;
986                 if (qstr->len != len)
987                         continue;
988                 if (memcmp(qstr->name, name, len))
989                         continue;
990                 dget_locked(alias);
991                 return alias;
992         }
993
994         list_add(&entry->d_alias, &inode->i_dentry);
995         entry->d_inode = inode;
996         fsnotify_d_instantiate(entry, inode);
997         return NULL;
998 }
999
1000 struct dentry *d_instantiate_unique(struct dentry *entry, struct inode *inode)
1001 {
1002         struct dentry *result;
1003
1004         BUG_ON(!list_empty(&entry->d_alias));
1005
1006         spin_lock(&dcache_lock);
1007         result = __d_instantiate_unique(entry, inode);
1008         spin_unlock(&dcache_lock);
1009
1010         if (!result) {
1011                 security_d_instantiate(entry, inode);
1012                 return NULL;
1013         }
1014
1015         BUG_ON(!d_unhashed(result));
1016         iput(inode);
1017         return result;
1018 }
1019
1020 EXPORT_SYMBOL(d_instantiate_unique);
1021
1022 /**
1023  * d_alloc_root - allocate root dentry
1024  * @root_inode: inode to allocate the root for
1025  *
1026  * Allocate a root ("/") dentry for the inode given. The inode is
1027  * instantiated and returned. %NULL is returned if there is insufficient
1028  * memory or the inode passed is %NULL.
1029  */
1030  
1031 struct dentry * d_alloc_root(struct inode * root_inode)
1032 {
1033         struct dentry *res = NULL;
1034
1035         if (root_inode) {
1036                 static const struct qstr name = { .name = "/", .len = 1 };
1037
1038                 res = d_alloc(NULL, &name);
1039                 if (res) {
1040                         res->d_sb = root_inode->i_sb;
1041                         res->d_parent = res;
1042                         d_instantiate(res, root_inode);
1043                 }
1044         }
1045         return res;
1046 }
1047
1048 static inline struct hlist_head *d_hash(struct dentry *parent,
1049                                         unsigned long hash)
1050 {
1051         hash += ((unsigned long) parent ^ GOLDEN_RATIO_PRIME) / L1_CACHE_BYTES;
1052         hash = hash ^ ((hash ^ GOLDEN_RATIO_PRIME) >> D_HASHBITS);
1053         return dentry_hashtable + (hash & D_HASHMASK);
1054 }
1055
1056 /**
1057  * d_alloc_anon - allocate an anonymous dentry
1058  * @inode: inode to allocate the dentry for
1059  *
1060  * This is similar to d_alloc_root.  It is used by filesystems when
1061  * creating a dentry for a given inode, often in the process of 
1062  * mapping a filehandle to a dentry.  The returned dentry may be
1063  * anonymous, or may have a full name (if the inode was already
1064  * in the cache).  The file system may need to make further
1065  * efforts to connect this dentry into the dcache properly.
1066  *
1067  * When called on a directory inode, we must ensure that
1068  * the inode only ever has one dentry.  If a dentry is
1069  * found, that is returned instead of allocating a new one.
1070  *
1071  * On successful return, the reference to the inode has been transferred
1072  * to the dentry.  If %NULL is returned (indicating kmalloc failure),
1073  * the reference on the inode has not been released.
1074  */
1075
1076 struct dentry * d_alloc_anon(struct inode *inode)
1077 {
1078         static const struct qstr anonstring = { .name = "" };
1079         struct dentry *tmp;
1080         struct dentry *res;
1081
1082         if ((res = d_find_alias(inode))) {
1083                 iput(inode);
1084                 return res;
1085         }
1086
1087         tmp = d_alloc(NULL, &anonstring);
1088         if (!tmp)
1089                 return NULL;
1090
1091         tmp->d_parent = tmp; /* make sure dput doesn't croak */
1092         
1093         spin_lock(&dcache_lock);
1094         res = __d_find_alias(inode, 0);
1095         if (!res) {
1096                 /* attach a disconnected dentry */
1097                 res = tmp;
1098                 tmp = NULL;
1099                 spin_lock(&res->d_lock);
1100                 res->d_sb = inode->i_sb;
1101                 res->d_parent = res;
1102                 res->d_inode = inode;
1103                 res->d_flags |= DCACHE_DISCONNECTED;
1104                 res->d_flags &= ~DCACHE_UNHASHED;
1105                 list_add(&res->d_alias, &inode->i_dentry);
1106                 hlist_add_head(&res->d_hash, &inode->i_sb->s_anon);
1107                 spin_unlock(&res->d_lock);
1108
1109                 inode = NULL; /* don't drop reference */
1110         }
1111         spin_unlock(&dcache_lock);
1112
1113         if (inode)
1114                 iput(inode);
1115         if (tmp)
1116                 dput(tmp);
1117         return res;
1118 }
1119
1120
1121 /**
1122  * d_splice_alias - splice a disconnected dentry into the tree if one exists
1123  * @inode:  the inode which may have a disconnected dentry
1124  * @dentry: a negative dentry which we want to point to the inode.
1125  *
1126  * If inode is a directory and has a 'disconnected' dentry (i.e. IS_ROOT and
1127  * DCACHE_DISCONNECTED), then d_move that in place of the given dentry
1128  * and return it, else simply d_add the inode to the dentry and return NULL.
1129  *
1130  * This is needed in the lookup routine of any filesystem that is exportable
1131  * (via knfsd) so that we can build dcache paths to directories effectively.
1132  *
1133  * If a dentry was found and moved, then it is returned.  Otherwise NULL
1134  * is returned.  This matches the expected return value of ->lookup.
1135  *
1136  */
1137 struct dentry *d_splice_alias(struct inode *inode, struct dentry *dentry)
1138 {
1139         struct dentry *new = NULL;
1140
1141         if (inode) {
1142                 spin_lock(&dcache_lock);
1143                 new = __d_find_alias(inode, 1);
1144                 if (new) {
1145                         BUG_ON(!(new->d_flags & DCACHE_DISCONNECTED));
1146                         fsnotify_d_instantiate(new, inode);
1147                         spin_unlock(&dcache_lock);
1148                         security_d_instantiate(new, inode);
1149                         d_rehash(dentry);
1150                         d_move(new, dentry);
1151                         iput(inode);
1152                 } else {
1153                         /* d_instantiate takes dcache_lock, so we do it by hand */
1154                         list_add(&dentry->d_alias, &inode->i_dentry);
1155                         dentry->d_inode = inode;
1156                         fsnotify_d_instantiate(dentry, inode);
1157                         spin_unlock(&dcache_lock);
1158                         security_d_instantiate(dentry, inode);
1159                         d_rehash(dentry);
1160                 }
1161         } else
1162                 d_add(dentry, inode);
1163         return new;
1164 }
1165
1166
1167 /**
1168  * d_lookup - search for a dentry
1169  * @parent: parent dentry
1170  * @name: qstr of name we wish to find
1171  *
1172  * Searches the children of the parent dentry for the name in question. If
1173  * the dentry is found its reference count is incremented and the dentry
1174  * is returned. The caller must use d_put to free the entry when it has
1175  * finished using it. %NULL is returned on failure.
1176  *
1177  * __d_lookup is dcache_lock free. The hash list is protected using RCU.
1178  * Memory barriers are used while updating and doing lockless traversal. 
1179  * To avoid races with d_move while rename is happening, d_lock is used.
1180  *
1181  * Overflows in memcmp(), while d_move, are avoided by keeping the length
1182  * and name pointer in one structure pointed by d_qstr.
1183  *
1184  * rcu_read_lock() and rcu_read_unlock() are used to disable preemption while
1185  * lookup is going on.
1186  *
1187  * dentry_unused list is not updated even if lookup finds the required dentry
1188  * in there. It is updated in places such as prune_dcache, shrink_dcache_sb,
1189  * select_parent and __dget_locked. This laziness saves lookup from dcache_lock
1190  * acquisition.
1191  *
1192  * d_lookup() is protected against the concurrent renames in some unrelated
1193  * directory using the seqlockt_t rename_lock.
1194  */
1195
1196 struct dentry * d_lookup(struct dentry * parent, struct qstr * name)
1197 {
1198         struct dentry * dentry = NULL;
1199         unsigned long seq;
1200
1201         do {
1202                 seq = read_seqbegin(&rename_lock);
1203                 dentry = __d_lookup(parent, name);
1204                 if (dentry)
1205                         break;
1206         } while (read_seqretry(&rename_lock, seq));
1207         return dentry;
1208 }
1209
1210 struct dentry * __d_lookup(struct dentry * parent, struct qstr * name)
1211 {
1212         unsigned int len = name->len;
1213         unsigned int hash = name->hash;
1214         const unsigned char *str = name->name;
1215         struct hlist_head *head = d_hash(parent,hash);
1216         struct dentry *found = NULL;
1217         struct hlist_node *node;
1218         struct dentry *dentry;
1219
1220         rcu_read_lock();
1221         
1222         hlist_for_each_entry_rcu(dentry, node, head, d_hash) {
1223                 struct qstr *qstr;
1224
1225                 if (dentry->d_name.hash != hash)
1226                         continue;
1227                 if (dentry->d_parent != parent)
1228                         continue;
1229
1230                 spin_lock(&dentry->d_lock);
1231
1232                 /*
1233                  * Recheck the dentry after taking the lock - d_move may have
1234                  * changed things.  Don't bother checking the hash because we're
1235                  * about to compare the whole name anyway.
1236                  */
1237                 if (dentry->d_parent != parent)
1238                         goto next;
1239
1240                 /*
1241                  * It is safe to compare names since d_move() cannot
1242                  * change the qstr (protected by d_lock).
1243                  */
1244                 qstr = &dentry->d_name;
1245                 if (parent->d_op && parent->d_op->d_compare) {
1246                         if (parent->d_op->d_compare(parent, qstr, name))
1247                                 goto next;
1248                 } else {
1249                         if (qstr->len != len)
1250                                 goto next;
1251                         if (memcmp(qstr->name, str, len))
1252                                 goto next;
1253                 }
1254
1255                 if (!d_unhashed(dentry)) {
1256                         atomic_inc(&dentry->d_count);
1257                         found = dentry;
1258                 }
1259                 spin_unlock(&dentry->d_lock);
1260                 break;
1261 next:
1262                 spin_unlock(&dentry->d_lock);
1263         }
1264         rcu_read_unlock();
1265
1266         return found;
1267 }
1268
1269 /**
1270  * d_hash_and_lookup - hash the qstr then search for a dentry
1271  * @dir: Directory to search in
1272  * @name: qstr of name we wish to find
1273  *
1274  * On hash failure or on lookup failure NULL is returned.
1275  */
1276 struct dentry *d_hash_and_lookup(struct dentry *dir, struct qstr *name)
1277 {
1278         struct dentry *dentry = NULL;
1279
1280         /*
1281          * Check for a fs-specific hash function. Note that we must
1282          * calculate the standard hash first, as the d_op->d_hash()
1283          * routine may choose to leave the hash value unchanged.
1284          */
1285         name->hash = full_name_hash(name->name, name->len);
1286         if (dir->d_op && dir->d_op->d_hash) {
1287                 if (dir->d_op->d_hash(dir, name) < 0)
1288                         goto out;
1289         }
1290         dentry = d_lookup(dir, name);
1291 out:
1292         return dentry;
1293 }
1294
1295 /**
1296  * d_validate - verify dentry provided from insecure source
1297  * @dentry: The dentry alleged to be valid child of @dparent
1298  * @dparent: The parent dentry (known to be valid)
1299  * @hash: Hash of the dentry
1300  * @len: Length of the name
1301  *
1302  * An insecure source has sent us a dentry, here we verify it and dget() it.
1303  * This is used by ncpfs in its readdir implementation.
1304  * Zero is returned in the dentry is invalid.
1305  */
1306  
1307 int d_validate(struct dentry *dentry, struct dentry *dparent)
1308 {
1309         struct hlist_head *base;
1310         struct hlist_node *lhp;
1311
1312         /* Check whether the ptr might be valid at all.. */
1313         if (!kmem_ptr_validate(dentry_cache, dentry))
1314                 goto out;
1315
1316         if (dentry->d_parent != dparent)
1317                 goto out;
1318
1319         spin_lock(&dcache_lock);
1320         base = d_hash(dparent, dentry->d_name.hash);
1321         hlist_for_each(lhp,base) { 
1322                 /* hlist_for_each_entry_rcu() not required for d_hash list
1323                  * as it is parsed under dcache_lock
1324                  */
1325                 if (dentry == hlist_entry(lhp, struct dentry, d_hash)) {
1326                         __dget_locked(dentry);
1327                         spin_unlock(&dcache_lock);
1328                         return 1;
1329                 }
1330         }
1331         spin_unlock(&dcache_lock);
1332 out:
1333         return 0;
1334 }
1335
1336 /*
1337  * When a file is deleted, we have two options:
1338  * - turn this dentry into a negative dentry
1339  * - unhash this dentry and free it.
1340  *
1341  * Usually, we want to just turn this into
1342  * a negative dentry, but if anybody else is
1343  * currently using the dentry or the inode
1344  * we can't do that and we fall back on removing
1345  * it from the hash queues and waiting for
1346  * it to be deleted later when it has no users
1347  */
1348  
1349 /**
1350  * d_delete - delete a dentry
1351  * @dentry: The dentry to delete
1352  *
1353  * Turn the dentry into a negative dentry if possible, otherwise
1354  * remove it from the hash queues so it can be deleted later
1355  */
1356  
1357 void d_delete(struct dentry * dentry)
1358 {
1359         int isdir = 0;
1360         /*
1361          * Are we the only user?
1362          */
1363         spin_lock(&dcache_lock);
1364         spin_lock(&dentry->d_lock);
1365         isdir = S_ISDIR(dentry->d_inode->i_mode);
1366         if (atomic_read(&dentry->d_count) == 1) {
1367                 dentry_iput(dentry);
1368                 fsnotify_nameremove(dentry, isdir);
1369
1370                 /* remove this and other inotify debug checks after 2.6.18 */
1371                 dentry->d_flags &= ~DCACHE_INOTIFY_PARENT_WATCHED;
1372                 return;
1373         }
1374
1375         if (!d_unhashed(dentry))
1376                 __d_drop(dentry);
1377
1378         spin_unlock(&dentry->d_lock);
1379         spin_unlock(&dcache_lock);
1380
1381         fsnotify_nameremove(dentry, isdir);
1382 }
1383
1384 static void __d_rehash(struct dentry * entry, struct hlist_head *list)
1385 {
1386
1387         entry->d_flags &= ~DCACHE_UNHASHED;
1388         hlist_add_head_rcu(&entry->d_hash, list);
1389 }
1390
1391 static void _d_rehash(struct dentry * entry)
1392 {
1393         __d_rehash(entry, d_hash(entry->d_parent, entry->d_name.hash));
1394 }
1395
1396 /**
1397  * d_rehash     - add an entry back to the hash
1398  * @entry: dentry to add to the hash
1399  *
1400  * Adds a dentry to the hash according to its name.
1401  */
1402  
1403 void d_rehash(struct dentry * entry)
1404 {
1405         spin_lock(&dcache_lock);
1406         spin_lock(&entry->d_lock);
1407         _d_rehash(entry);
1408         spin_unlock(&entry->d_lock);
1409         spin_unlock(&dcache_lock);
1410 }
1411
1412 #define do_switch(x,y) do { \
1413         __typeof__ (x) __tmp = x; \
1414         x = y; y = __tmp; } while (0)
1415
1416 /*
1417  * When switching names, the actual string doesn't strictly have to
1418  * be preserved in the target - because we're dropping the target
1419  * anyway. As such, we can just do a simple memcpy() to copy over
1420  * the new name before we switch.
1421  *
1422  * Note that we have to be a lot more careful about getting the hash
1423  * switched - we have to switch the hash value properly even if it
1424  * then no longer matches the actual (corrupted) string of the target.
1425  * The hash value has to match the hash queue that the dentry is on..
1426  */
1427 static void switch_names(struct dentry *dentry, struct dentry *target)
1428 {
1429         if (dname_external(target)) {
1430                 if (dname_external(dentry)) {
1431                         /*
1432                          * Both external: swap the pointers
1433                          */
1434                         do_switch(target->d_name.name, dentry->d_name.name);
1435                 } else {
1436                         /*
1437                          * dentry:internal, target:external.  Steal target's
1438                          * storage and make target internal.
1439                          */
1440                         dentry->d_name.name = target->d_name.name;
1441                         target->d_name.name = target->d_iname;
1442                 }
1443         } else {
1444                 if (dname_external(dentry)) {
1445                         /*
1446                          * dentry:external, target:internal.  Give dentry's
1447                          * storage to target and make dentry internal
1448                          */
1449                         memcpy(dentry->d_iname, target->d_name.name,
1450                                         target->d_name.len + 1);
1451                         target->d_name.name = dentry->d_name.name;
1452                         dentry->d_name.name = dentry->d_iname;
1453                 } else {
1454                         /*
1455                          * Both are internal.  Just copy target to dentry
1456                          */
1457                         memcpy(dentry->d_iname, target->d_name.name,
1458                                         target->d_name.len + 1);
1459                 }
1460         }
1461 }
1462
1463 /*
1464  * We cannibalize "target" when moving dentry on top of it,
1465  * because it's going to be thrown away anyway. We could be more
1466  * polite about it, though.
1467  *
1468  * This forceful removal will result in ugly /proc output if
1469  * somebody holds a file open that got deleted due to a rename.
1470  * We could be nicer about the deleted file, and let it show
1471  * up under the name it got deleted rather than the name that
1472  * deleted it.
1473  */
1474  
1475 /**
1476  * d_move - move a dentry
1477  * @dentry: entry to move
1478  * @target: new dentry
1479  *
1480  * Update the dcache to reflect the move of a file name. Negative
1481  * dcache entries should not be moved in this way.
1482  */
1483
1484 void d_move(struct dentry * dentry, struct dentry * target)
1485 {
1486         struct hlist_head *list;
1487
1488         if (!dentry->d_inode)
1489                 printk(KERN_WARNING "VFS: moving negative dcache entry\n");
1490
1491         spin_lock(&dcache_lock);
1492         write_seqlock(&rename_lock);
1493         /*
1494          * XXXX: do we really need to take target->d_lock?
1495          */
1496         if (target < dentry) {
1497                 spin_lock(&target->d_lock);
1498                 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
1499         } else {
1500                 spin_lock(&dentry->d_lock);
1501                 spin_lock_nested(&target->d_lock, DENTRY_D_LOCK_NESTED);
1502         }
1503
1504         /* Move the dentry to the target hash queue, if on different bucket */
1505         if (dentry->d_flags & DCACHE_UNHASHED)
1506                 goto already_unhashed;
1507
1508         hlist_del_rcu(&dentry->d_hash);
1509
1510 already_unhashed:
1511         list = d_hash(target->d_parent, target->d_name.hash);
1512         __d_rehash(dentry, list);
1513
1514         /* Unhash the target: dput() will then get rid of it */
1515         __d_drop(target);
1516
1517         /* flush any possible attributes */
1518         if (dentry->d_extra_attributes) {
1519                 kfree(dentry->d_extra_attributes);
1520                 dentry->d_extra_attributes = NULL;
1521         }
1522         if (target->d_extra_attributes) {
1523                 kfree(target->d_extra_attributes);
1524                 target->d_extra_attributes = NULL;
1525         }
1526
1527         list_del(&dentry->d_u.d_child);
1528         list_del(&target->d_u.d_child);
1529
1530         /* Switch the names.. */
1531         switch_names(dentry, target);
1532         do_switch(dentry->d_name.len, target->d_name.len);
1533         do_switch(dentry->d_name.hash, target->d_name.hash);
1534
1535         /* ... and switch the parents */
1536         if (IS_ROOT(dentry)) {
1537                 dentry->d_parent = target->d_parent;
1538                 target->d_parent = target;
1539                 INIT_LIST_HEAD(&target->d_u.d_child);
1540         } else {
1541                 do_switch(dentry->d_parent, target->d_parent);
1542
1543                 /* And add them back to the (new) parent lists */
1544                 list_add(&target->d_u.d_child, &target->d_parent->d_subdirs);
1545         }
1546
1547         list_add(&dentry->d_u.d_child, &dentry->d_parent->d_subdirs);
1548         spin_unlock(&target->d_lock);
1549         fsnotify_d_move(dentry);
1550         spin_unlock(&dentry->d_lock);
1551         write_sequnlock(&rename_lock);
1552         spin_unlock(&dcache_lock);
1553 }
1554
1555 /*
1556  * Prepare an anonymous dentry for life in the superblock's dentry tree as a
1557  * named dentry in place of the dentry to be replaced.
1558  */
1559 static void __d_materialise_dentry(struct dentry *dentry, struct dentry *anon)
1560 {
1561         struct dentry *dparent, *aparent;
1562
1563         switch_names(dentry, anon);
1564         do_switch(dentry->d_name.len, anon->d_name.len);
1565         do_switch(dentry->d_name.hash, anon->d_name.hash);
1566
1567         dparent = dentry->d_parent;
1568         aparent = anon->d_parent;
1569
1570         dentry->d_parent = (aparent == anon) ? dentry : aparent;
1571         list_del(&dentry->d_u.d_child);
1572         if (!IS_ROOT(dentry))
1573                 list_add(&dentry->d_u.d_child, &dentry->d_parent->d_subdirs);
1574         else
1575                 INIT_LIST_HEAD(&dentry->d_u.d_child);
1576
1577         anon->d_parent = (dparent == dentry) ? anon : dparent;
1578         list_del(&anon->d_u.d_child);
1579         if (!IS_ROOT(anon))
1580                 list_add(&anon->d_u.d_child, &anon->d_parent->d_subdirs);
1581         else
1582                 INIT_LIST_HEAD(&anon->d_u.d_child);
1583
1584         anon->d_flags &= ~DCACHE_DISCONNECTED;
1585 }
1586
1587 /**
1588  * d_materialise_unique - introduce an inode into the tree
1589  * @dentry: candidate dentry
1590  * @inode: inode to bind to the dentry, to which aliases may be attached
1591  *
1592  * Introduces an dentry into the tree, substituting an extant disconnected
1593  * root directory alias in its place if there is one
1594  */
1595 struct dentry *d_materialise_unique(struct dentry *dentry, struct inode *inode)
1596 {
1597         struct dentry *alias, *actual;
1598
1599         BUG_ON(!d_unhashed(dentry));
1600
1601         spin_lock(&dcache_lock);
1602
1603         if (!inode) {
1604                 actual = dentry;
1605                 dentry->d_inode = NULL;
1606                 goto found_lock;
1607         }
1608
1609         /* See if a disconnected directory already exists as an anonymous root
1610          * that we should splice into the tree instead */
1611         if (S_ISDIR(inode->i_mode) && (alias = __d_find_alias(inode, 1))) {
1612                 spin_lock(&alias->d_lock);
1613
1614                 /* Is this a mountpoint that we could splice into our tree? */
1615                 if (IS_ROOT(alias))
1616                         goto connect_mountpoint;
1617
1618                 if (alias->d_name.len == dentry->d_name.len &&
1619                     alias->d_parent == dentry->d_parent &&
1620                     memcmp(alias->d_name.name,
1621                            dentry->d_name.name,
1622                            dentry->d_name.len) == 0)
1623                         goto replace_with_alias;
1624
1625                 spin_unlock(&alias->d_lock);
1626
1627                 /* Doh! Seem to be aliasing directories for some reason... */
1628                 dput(alias);
1629         }
1630
1631         /* Add a unique reference */
1632         actual = __d_instantiate_unique(dentry, inode);
1633         if (!actual)
1634                 actual = dentry;
1635         else if (unlikely(!d_unhashed(actual)))
1636                 goto shouldnt_be_hashed;
1637
1638 found_lock:
1639         spin_lock(&actual->d_lock);
1640 found:
1641         _d_rehash(actual);
1642         spin_unlock(&actual->d_lock);
1643         spin_unlock(&dcache_lock);
1644
1645         if (actual == dentry) {
1646                 security_d_instantiate(dentry, inode);
1647                 return NULL;
1648         }
1649
1650         iput(inode);
1651         return actual;
1652
1653         /* Convert the anonymous/root alias into an ordinary dentry */
1654 connect_mountpoint:
1655         __d_materialise_dentry(dentry, alias);
1656
1657         /* Replace the candidate dentry with the alias in the tree */
1658 replace_with_alias:
1659         __d_drop(alias);
1660         actual = alias;
1661         goto found;
1662
1663 shouldnt_be_hashed:
1664         spin_unlock(&dcache_lock);
1665         BUG();
1666         goto shouldnt_be_hashed;
1667 }
1668
1669 /**
1670  * d_path - return the path of a dentry
1671  * @dentry: dentry to report
1672  * @vfsmnt: vfsmnt to which the dentry belongs
1673  * @root: root dentry
1674  * @rootmnt: vfsmnt to which the root dentry belongs
1675  * @buffer: buffer to return value in
1676  * @buflen: buffer length
1677  *
1678  * Convert a dentry into an ASCII path name. If the entry has been deleted
1679  * the string " (deleted)" is appended. Note that this is ambiguous.
1680  *
1681  * Returns the buffer or an error code if the path was too long.
1682  *
1683  * "buflen" should be positive. Caller holds the dcache_lock.
1684  */
1685 char * __d_path( struct dentry *dentry, struct vfsmount *vfsmnt,
1686                         struct dentry *root, struct vfsmount *rootmnt,
1687                         char *buffer, int buflen)
1688 {
1689         char * end = buffer+buflen;
1690         char * retval;
1691         int namelen;
1692
1693         *--end = '\0';
1694         buflen--;
1695         if (!IS_ROOT(dentry) && d_unhashed(dentry)) {
1696                 buflen -= 10;
1697                 end -= 10;
1698                 if (buflen < 0)
1699                         goto Elong;
1700                 memcpy(end, " (deleted)", 10);
1701         }
1702
1703         if (buflen < 1)
1704                 goto Elong;
1705         /* Get '/' right */
1706         retval = end-1;
1707         *retval = '/';
1708
1709         for (;;) {
1710                 struct dentry * parent;
1711
1712                 if (dentry == root && vfsmnt == rootmnt)
1713                         break;
1714                 if (dentry == vfsmnt->mnt_root || IS_ROOT(dentry)) {
1715                         /* Global root? */
1716                         spin_lock(&vfsmount_lock);
1717                         if (vfsmnt->mnt_parent == vfsmnt) {
1718                                 spin_unlock(&vfsmount_lock);
1719                                 goto global_root;
1720                         }
1721                         dentry = vfsmnt->mnt_mountpoint;
1722                         vfsmnt = vfsmnt->mnt_parent;
1723                         spin_unlock(&vfsmount_lock);
1724                         continue;
1725                 }
1726                 parent = dentry->d_parent;
1727                 prefetch(parent);
1728                 namelen = dentry->d_name.len;
1729                 buflen -= namelen + 1;
1730                 if (buflen < 0)
1731                         goto Elong;
1732                 end -= namelen;
1733                 memcpy(end, dentry->d_name.name, namelen);
1734                 *--end = '/';
1735                 retval = end;
1736                 dentry = parent;
1737         }
1738
1739         return retval;
1740
1741 global_root:
1742         namelen = dentry->d_name.len;
1743         buflen -= namelen;
1744         if (buflen < 0)
1745                 goto Elong;
1746         retval -= namelen-1;    /* hit the slash */
1747         memcpy(retval, dentry->d_name.name, namelen);
1748         return retval;
1749 Elong:
1750         return ERR_PTR(-ENAMETOOLONG);
1751 }
1752
1753 EXPORT_SYMBOL_GPL(__d_path);
1754
1755 /* write full pathname into buffer and return start of pathname */
1756 char * d_path(struct dentry *dentry, struct vfsmount *vfsmnt,
1757                                 char *buf, int buflen)
1758 {
1759         char *res;
1760         struct vfsmount *rootmnt;
1761         struct dentry *root;
1762
1763         read_lock(&current->fs->lock);
1764         rootmnt = mntget(current->fs->rootmnt);
1765         root = dget(current->fs->root);
1766         read_unlock(&current->fs->lock);
1767         spin_lock(&dcache_lock);
1768         res = __d_path(dentry, vfsmnt, root, rootmnt, buf, buflen);
1769         spin_unlock(&dcache_lock);
1770         dput(root);
1771         mntput(rootmnt);
1772         return res;
1773 }
1774
1775 /*
1776  * NOTE! The user-level library version returns a
1777  * character pointer. The kernel system call just
1778  * returns the length of the buffer filled (which
1779  * includes the ending '\0' character), or a negative
1780  * error value. So libc would do something like
1781  *
1782  *      char *getcwd(char * buf, size_t size)
1783  *      {
1784  *              int retval;
1785  *
1786  *              retval = sys_getcwd(buf, size);
1787  *              if (retval >= 0)
1788  *                      return buf;
1789  *              errno = -retval;
1790  *              return NULL;
1791  *      }
1792  */
1793 asmlinkage long sys_getcwd(char __user *buf, unsigned long size)
1794 {
1795         int error;
1796         struct vfsmount *pwdmnt, *rootmnt;
1797         struct dentry *pwd, *root;
1798         char *page = (char *) __get_free_page(GFP_USER);
1799
1800         if (!page)
1801                 return -ENOMEM;
1802
1803         read_lock(&current->fs->lock);
1804         pwdmnt = mntget(current->fs->pwdmnt);
1805         pwd = dget(current->fs->pwd);
1806         rootmnt = mntget(current->fs->rootmnt);
1807         root = dget(current->fs->root);
1808         read_unlock(&current->fs->lock);
1809
1810         error = -ENOENT;
1811         /* Has the current directory has been unlinked? */
1812         spin_lock(&dcache_lock);
1813         if (pwd->d_parent == pwd || !d_unhashed(pwd)) {
1814                 unsigned long len;
1815                 char * cwd;
1816
1817                 cwd = __d_path(pwd, pwdmnt, root, rootmnt, page, PAGE_SIZE);
1818                 spin_unlock(&dcache_lock);
1819
1820                 error = PTR_ERR(cwd);
1821                 if (IS_ERR(cwd))
1822                         goto out;
1823
1824                 error = -ERANGE;
1825                 len = PAGE_SIZE + page - cwd;
1826                 if (len <= size) {
1827                         error = len;
1828                         if (copy_to_user(buf, cwd, len))
1829                                 error = -EFAULT;
1830                 }
1831         } else
1832                 spin_unlock(&dcache_lock);
1833
1834 out:
1835         dput(pwd);
1836         mntput(pwdmnt);
1837         dput(root);
1838         mntput(rootmnt);
1839         free_page((unsigned long) page);
1840         return error;
1841 }
1842
1843 /*
1844  * Test whether new_dentry is a subdirectory of old_dentry.
1845  *
1846  * Trivially implemented using the dcache structure
1847  */
1848
1849 /**
1850  * is_subdir - is new dentry a subdirectory of old_dentry
1851  * @new_dentry: new dentry
1852  * @old_dentry: old dentry
1853  *
1854  * Returns 1 if new_dentry is a subdirectory of the parent (at any depth).
1855  * Returns 0 otherwise.
1856  * Caller must ensure that "new_dentry" is pinned before calling is_subdir()
1857  */
1858   
1859 int is_subdir(struct dentry * new_dentry, struct dentry * old_dentry)
1860 {
1861         int result;
1862         struct dentry * saved = new_dentry;
1863         unsigned long seq;
1864
1865         /* need rcu_readlock to protect against the d_parent trashing due to
1866          * d_move
1867          */
1868         rcu_read_lock();
1869         do {
1870                 /* for restarting inner loop in case of seq retry */
1871                 new_dentry = saved;
1872                 result = 0;
1873                 seq = read_seqbegin(&rename_lock);
1874                 for (;;) {
1875                         if (new_dentry != old_dentry) {
1876                                 struct dentry * parent = new_dentry->d_parent;
1877                                 if (parent == new_dentry)
1878                                         break;
1879                                 new_dentry = parent;
1880                                 continue;
1881                         }
1882                         result = 1;
1883                         break;
1884                 }
1885         } while (read_seqretry(&rename_lock, seq));
1886         rcu_read_unlock();
1887
1888         return result;
1889 }
1890
1891 void d_genocide(struct dentry *root)
1892 {
1893         struct dentry *this_parent = root;
1894         struct list_head *next;
1895
1896         spin_lock(&dcache_lock);
1897 repeat:
1898         next = this_parent->d_subdirs.next;
1899 resume:
1900         while (next != &this_parent->d_subdirs) {
1901                 struct list_head *tmp = next;
1902                 struct dentry *dentry = list_entry(tmp, struct dentry, d_u.d_child);
1903                 next = tmp->next;
1904                 if (d_unhashed(dentry)||!dentry->d_inode)
1905                         continue;
1906                 if (!list_empty(&dentry->d_subdirs)) {
1907                         this_parent = dentry;
1908                         goto repeat;
1909                 }
1910                 atomic_dec(&dentry->d_count);
1911         }
1912         if (this_parent != root) {
1913                 next = this_parent->d_u.d_child.next;
1914                 atomic_dec(&this_parent->d_count);
1915                 this_parent = this_parent->d_parent;
1916                 goto resume;
1917         }
1918         spin_unlock(&dcache_lock);
1919 }
1920
1921 /**
1922  * find_inode_number - check for dentry with name
1923  * @dir: directory to check
1924  * @name: Name to find.
1925  *
1926  * Check whether a dentry already exists for the given name,
1927  * and return the inode number if it has an inode. Otherwise
1928  * 0 is returned.
1929  *
1930  * This routine is used to post-process directory listings for
1931  * filesystems using synthetic inode numbers, and is necessary
1932  * to keep getcwd() working.
1933  */
1934  
1935 ino_t find_inode_number(struct dentry *dir, struct qstr *name)
1936 {
1937         struct dentry * dentry;
1938         ino_t ino = 0;
1939
1940         dentry = d_hash_and_lookup(dir, name);
1941         if (dentry) {
1942                 if (dentry->d_inode)
1943                         ino = dentry->d_inode->i_ino;
1944                 dput(dentry);
1945         }
1946         return ino;
1947 }
1948
1949 static __initdata unsigned long dhash_entries;
1950 static int __init set_dhash_entries(char *str)
1951 {
1952         if (!str)
1953                 return 0;
1954         dhash_entries = simple_strtoul(str, &str, 0);
1955         return 1;
1956 }
1957 __setup("dhash_entries=", set_dhash_entries);
1958
1959 static void __init dcache_init_early(void)
1960 {
1961         int loop;
1962
1963         /* If hashes are distributed across NUMA nodes, defer
1964          * hash allocation until vmalloc space is available.
1965          */
1966         if (hashdist)
1967                 return;
1968
1969         dentry_hashtable =
1970                 alloc_large_system_hash("Dentry cache",
1971                                         sizeof(struct hlist_head),
1972                                         dhash_entries,
1973                                         13,
1974                                         HASH_EARLY,
1975                                         &d_hash_shift,
1976                                         &d_hash_mask,
1977                                         0);
1978
1979         for (loop = 0; loop < (1 << d_hash_shift); loop++)
1980                 INIT_HLIST_HEAD(&dentry_hashtable[loop]);
1981 }
1982
1983 void flush_dentry_attributes (void)
1984 {
1985         struct hlist_node *tmp;
1986         struct dentry *dentry;
1987         int i;
1988
1989         spin_lock(&dcache_lock);
1990         for (i = 0; i <= d_hash_mask; i++)
1991                 hlist_for_each_entry(dentry, tmp, dentry_hashtable+i, d_hash) {
1992                         kfree(dentry->d_extra_attributes);
1993                         dentry->d_extra_attributes = NULL;
1994                 }
1995         spin_unlock(&dcache_lock);
1996 }
1997
1998 EXPORT_SYMBOL_GPL(flush_dentry_attributes);
1999
2000 static void __init dcache_init(unsigned long mempages)
2001 {
2002         int loop;
2003
2004         /* 
2005          * A constructor could be added for stable state like the lists,
2006          * but it is probably not worth it because of the cache nature
2007          * of the dcache. 
2008          */
2009         dentry_cache = kmem_cache_create("dentry_cache",
2010                                          sizeof(struct dentry),
2011                                          0,
2012                                          (SLAB_RECLAIM_ACCOUNT|SLAB_PANIC|
2013                                          SLAB_MEM_SPREAD),
2014                                          NULL, NULL);
2015         
2016         set_shrinker(DEFAULT_SEEKS, shrink_dcache_memory);
2017
2018         /* Hash may have been set up in dcache_init_early */
2019         if (!hashdist)
2020                 return;
2021
2022         dentry_hashtable =
2023                 alloc_large_system_hash("Dentry cache",
2024                                         sizeof(struct hlist_head),
2025                                         dhash_entries,
2026                                         13,
2027                                         0,
2028                                         &d_hash_shift,
2029                                         &d_hash_mask,
2030                                         0);
2031
2032         for (loop = 0; loop < (1 << d_hash_shift); loop++)
2033                 INIT_HLIST_HEAD(&dentry_hashtable[loop]);
2034 }
2035
2036 /* SLAB cache for __getname() consumers */
2037 kmem_cache_t *names_cachep __read_mostly;
2038
2039 /* SLAB cache for file structures */
2040 kmem_cache_t *filp_cachep __read_mostly;
2041
2042 EXPORT_SYMBOL(d_genocide);
2043
2044 extern void bdev_cache_init(void);
2045 extern void chrdev_init(void);
2046
2047 void __init vfs_caches_init_early(void)
2048 {
2049         dcache_init_early();
2050         inode_init_early();
2051 }
2052
2053 void __init vfs_caches_init(unsigned long mempages)
2054 {
2055         unsigned long reserve;
2056
2057         /* Base hash sizes on available memory, with a reserve equal to
2058            150% of current kernel size */
2059
2060         reserve = min((mempages - nr_free_pages()) * 3/2, mempages - 1);
2061         mempages -= reserve;
2062
2063         names_cachep = kmem_cache_create("names_cache", PATH_MAX, 0,
2064                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
2065
2066         filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0,
2067                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL, NULL);
2068
2069         dcache_init(mempages);
2070         inode_init(mempages);
2071         files_init(mempages);
2072         mnt_init(mempages);
2073         bdev_cache_init();
2074         chrdev_init();
2075 }
2076
2077 EXPORT_SYMBOL(d_alloc);
2078 EXPORT_SYMBOL(d_alloc_anon);
2079 EXPORT_SYMBOL(d_alloc_root);
2080 EXPORT_SYMBOL(d_delete);
2081 EXPORT_SYMBOL(d_find_alias);
2082 EXPORT_SYMBOL(d_instantiate);
2083 EXPORT_SYMBOL(d_invalidate);
2084 EXPORT_SYMBOL(d_lookup);
2085 EXPORT_SYMBOL(d_move);
2086 EXPORT_SYMBOL_GPL(d_materialise_unique);
2087 EXPORT_SYMBOL(d_path);
2088 EXPORT_SYMBOL(d_prune_aliases);
2089 EXPORT_SYMBOL(d_rehash);
2090 EXPORT_SYMBOL(d_splice_alias);
2091 EXPORT_SYMBOL(d_validate);
2092 EXPORT_SYMBOL(dget_locked);
2093 EXPORT_SYMBOL(dput);
2094 EXPORT_SYMBOL(find_inode_number);
2095 EXPORT_SYMBOL(have_submounts);
2096 EXPORT_SYMBOL(names_cachep);
2097 EXPORT_SYMBOL(shrink_dcache_parent);
2098 EXPORT_SYMBOL(shrink_dcache_sb);