fs: dcache scale d_unhashed
[linux-flexiantxendom0-natty.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/hash.h>
25 #include <linux/cache.h>
26 #include <linux/module.h>
27 #include <linux/mount.h>
28 #include <linux/file.h>
29 #include <asm/uaccess.h>
30 #include <linux/security.h>
31 #include <linux/seqlock.h>
32 #include <linux/swap.h>
33 #include <linux/bootmem.h>
34 #include <linux/fs_struct.h>
35 #include <linux/hardirq.h>
36 #include "internal.h"
37
38 /*
39  * Usage:
40  * dcache_hash_lock protects:
41  *   - the dcache hash table, s_anon lists
42  * dcache_lru_lock protects:
43  *   - the dcache lru lists and counters
44  * d_lock protects:
45  *   - d_flags
46  *   - d_name
47  *   - d_lru
48  *   - d_count
49  *   - d_unhashed()
50  *
51  * Ordering:
52  * dcache_lock
53  *   dentry->d_lock
54  *     dcache_lru_lock
55  *     dcache_hash_lock
56  *
57  * If there is an ancestor relationship:
58  * dentry->d_parent->...->d_parent->d_lock
59  *   ...
60  *     dentry->d_parent->d_lock
61  *       dentry->d_lock
62  *
63  * If no ancestor relationship:
64  * if (dentry1 < dentry2)
65  *   dentry1->d_lock
66  *     dentry2->d_lock
67  */
68 int sysctl_vfs_cache_pressure __read_mostly = 100;
69 EXPORT_SYMBOL_GPL(sysctl_vfs_cache_pressure);
70
71 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(dcache_hash_lock);
72 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(dcache_lru_lock);
73 __cacheline_aligned_in_smp DEFINE_SPINLOCK(dcache_lock);
74 __cacheline_aligned_in_smp DEFINE_SEQLOCK(rename_lock);
75
76 EXPORT_SYMBOL(dcache_lock);
77
78 static struct kmem_cache *dentry_cache __read_mostly;
79
80 #define DNAME_INLINE_LEN (sizeof(struct dentry)-offsetof(struct dentry,d_iname))
81
82 /*
83  * This is the single most critical data structure when it comes
84  * to the dcache: the hashtable for lookups. Somebody should try
85  * to make this good - I've just made it work.
86  *
87  * This hash-function tries to avoid losing too many bits of hash
88  * information, yet avoid using a prime hash-size or similar.
89  */
90 #define D_HASHBITS     d_hash_shift
91 #define D_HASHMASK     d_hash_mask
92
93 static unsigned int d_hash_mask __read_mostly;
94 static unsigned int d_hash_shift __read_mostly;
95 static struct hlist_head *dentry_hashtable __read_mostly;
96
97 /* Statistics gathering. */
98 struct dentry_stat_t dentry_stat = {
99         .age_limit = 45,
100 };
101
102 static DEFINE_PER_CPU(unsigned int, nr_dentry);
103
104 #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS)
105 static int get_nr_dentry(void)
106 {
107         int i;
108         int sum = 0;
109         for_each_possible_cpu(i)
110                 sum += per_cpu(nr_dentry, i);
111         return sum < 0 ? 0 : sum;
112 }
113
114 int proc_nr_dentry(ctl_table *table, int write, void __user *buffer,
115                    size_t *lenp, loff_t *ppos)
116 {
117         dentry_stat.nr_dentry = get_nr_dentry();
118         return proc_dointvec(table, write, buffer, lenp, ppos);
119 }
120 #endif
121
122 static void __d_free(struct rcu_head *head)
123 {
124         struct dentry *dentry = container_of(head, struct dentry, d_u.d_rcu);
125
126         WARN_ON(!list_empty(&dentry->d_alias));
127         if (dname_external(dentry))
128                 kfree(dentry->d_name.name);
129         kmem_cache_free(dentry_cache, dentry); 
130 }
131
132 /*
133  * no dcache_lock, please.
134  */
135 static void d_free(struct dentry *dentry)
136 {
137         BUG_ON(dentry->d_count);
138         this_cpu_dec(nr_dentry);
139         if (dentry->d_op && dentry->d_op->d_release)
140                 dentry->d_op->d_release(dentry);
141
142         /* if dentry was never inserted into hash, immediate free is OK */
143         if (hlist_unhashed(&dentry->d_hash))
144                 __d_free(&dentry->d_u.d_rcu);
145         else
146                 call_rcu(&dentry->d_u.d_rcu, __d_free);
147 }
148
149 /*
150  * Release the dentry's inode, using the filesystem
151  * d_iput() operation if defined.
152  */
153 static void dentry_iput(struct dentry * dentry)
154         __releases(dentry->d_lock)
155         __releases(dcache_lock)
156 {
157         struct inode *inode = dentry->d_inode;
158         if (inode) {
159                 dentry->d_inode = NULL;
160                 list_del_init(&dentry->d_alias);
161                 spin_unlock(&dentry->d_lock);
162                 spin_unlock(&dcache_lock);
163                 if (!inode->i_nlink)
164                         fsnotify_inoderemove(inode);
165                 if (dentry->d_op && dentry->d_op->d_iput)
166                         dentry->d_op->d_iput(dentry, inode);
167                 else
168                         iput(inode);
169         } else {
170                 spin_unlock(&dentry->d_lock);
171                 spin_unlock(&dcache_lock);
172         }
173 }
174
175 /*
176  * dentry_lru_(add|del|move_tail) must be called with d_lock held.
177  */
178 static void dentry_lru_add(struct dentry *dentry)
179 {
180         if (list_empty(&dentry->d_lru)) {
181                 spin_lock(&dcache_lru_lock);
182                 list_add(&dentry->d_lru, &dentry->d_sb->s_dentry_lru);
183                 dentry->d_sb->s_nr_dentry_unused++;
184                 dentry_stat.nr_unused++;
185                 spin_unlock(&dcache_lru_lock);
186         }
187 }
188
189 static void __dentry_lru_del(struct dentry *dentry)
190 {
191         list_del_init(&dentry->d_lru);
192         dentry->d_sb->s_nr_dentry_unused--;
193         dentry_stat.nr_unused--;
194 }
195
196 static void dentry_lru_del(struct dentry *dentry)
197 {
198         if (!list_empty(&dentry->d_lru)) {
199                 spin_lock(&dcache_lru_lock);
200                 __dentry_lru_del(dentry);
201                 spin_unlock(&dcache_lru_lock);
202         }
203 }
204
205 static void dentry_lru_move_tail(struct dentry *dentry)
206 {
207         spin_lock(&dcache_lru_lock);
208         if (list_empty(&dentry->d_lru)) {
209                 list_add_tail(&dentry->d_lru, &dentry->d_sb->s_dentry_lru);
210                 dentry->d_sb->s_nr_dentry_unused++;
211                 dentry_stat.nr_unused++;
212         } else {
213                 list_move_tail(&dentry->d_lru, &dentry->d_sb->s_dentry_lru);
214         }
215         spin_unlock(&dcache_lru_lock);
216 }
217
218 /**
219  * d_kill - kill dentry and return parent
220  * @dentry: dentry to kill
221  *
222  * The dentry must already be unhashed and removed from the LRU.
223  *
224  * If this is the root of the dentry tree, return NULL.
225  *
226  * dcache_lock and d_lock must be held by caller, are dropped by d_kill.
227  */
228 static struct dentry *d_kill(struct dentry *dentry)
229         __releases(dentry->d_lock)
230         __releases(dcache_lock)
231 {
232         struct dentry *parent;
233
234         list_del(&dentry->d_u.d_child);
235         dentry_iput(dentry);
236         /*
237          * dentry_iput drops the locks, at which point nobody (except
238          * transient RCU lookups) can reach this dentry.
239          */
240         if (IS_ROOT(dentry))
241                 parent = NULL;
242         else
243                 parent = dentry->d_parent;
244         d_free(dentry);
245         return parent;
246 }
247
248 /**
249  * d_drop - drop a dentry
250  * @dentry: dentry to drop
251  *
252  * d_drop() unhashes the entry from the parent dentry hashes, so that it won't
253  * be found through a VFS lookup any more. Note that this is different from
254  * deleting the dentry - d_delete will try to mark the dentry negative if
255  * possible, giving a successful _negative_ lookup, while d_drop will
256  * just make the cache lookup fail.
257  *
258  * d_drop() is used mainly for stuff that wants to invalidate a dentry for some
259  * reason (NFS timeouts or autofs deletes).
260  *
261  * __d_drop requires dentry->d_lock.
262  */
263 void __d_drop(struct dentry *dentry)
264 {
265         if (!(dentry->d_flags & DCACHE_UNHASHED)) {
266                 dentry->d_flags |= DCACHE_UNHASHED;
267                 spin_lock(&dcache_hash_lock);
268                 hlist_del_rcu(&dentry->d_hash);
269                 spin_unlock(&dcache_hash_lock);
270         }
271 }
272 EXPORT_SYMBOL(__d_drop);
273
274 void d_drop(struct dentry *dentry)
275 {
276         spin_lock(&dcache_lock);
277         spin_lock(&dentry->d_lock);
278         __d_drop(dentry);
279         spin_unlock(&dentry->d_lock);
280         spin_unlock(&dcache_lock);
281 }
282 EXPORT_SYMBOL(d_drop);
283
284 /* 
285  * This is dput
286  *
287  * This is complicated by the fact that we do not want to put
288  * dentries that are no longer on any hash chain on the unused
289  * list: we'd much rather just get rid of them immediately.
290  *
291  * However, that implies that we have to traverse the dentry
292  * tree upwards to the parents which might _also_ now be
293  * scheduled for deletion (it may have been only waiting for
294  * its last child to go away).
295  *
296  * This tail recursion is done by hand as we don't want to depend
297  * on the compiler to always get this right (gcc generally doesn't).
298  * Real recursion would eat up our stack space.
299  */
300
301 /*
302  * dput - release a dentry
303  * @dentry: dentry to release 
304  *
305  * Release a dentry. This will drop the usage count and if appropriate
306  * call the dentry unlink method as well as removing it from the queues and
307  * releasing its resources. If the parent dentries were scheduled for release
308  * they too may now get deleted.
309  *
310  * no dcache lock, please.
311  */
312
313 void dput(struct dentry *dentry)
314 {
315         if (!dentry)
316                 return;
317
318 repeat:
319         if (dentry->d_count == 1)
320                 might_sleep();
321         spin_lock(&dentry->d_lock);
322         if (dentry->d_count == 1) {
323                 if (!spin_trylock(&dcache_lock)) {
324                         /*
325                          * Something of a livelock possibility we could avoid
326                          * by taking dcache_lock and trying again, but we
327                          * want to reduce dcache_lock anyway so this will
328                          * get improved.
329                          */
330                         spin_unlock(&dentry->d_lock);
331                         goto repeat;
332                 }
333         }
334         dentry->d_count--;
335         if (dentry->d_count) {
336                 spin_unlock(&dentry->d_lock);
337                 spin_unlock(&dcache_lock);
338                 return;
339         }
340
341         /*
342          * AV: ->d_delete() is _NOT_ allowed to block now.
343          */
344         if (dentry->d_op && dentry->d_op->d_delete) {
345                 if (dentry->d_op->d_delete(dentry))
346                         goto unhash_it;
347         }
348
349         /* Unreachable? Get rid of it */
350         if (d_unhashed(dentry))
351                 goto kill_it;
352
353         /* Otherwise leave it cached and ensure it's on the LRU */
354         dentry->d_flags |= DCACHE_REFERENCED;
355         dentry_lru_add(dentry);
356
357         spin_unlock(&dentry->d_lock);
358         spin_unlock(&dcache_lock);
359         return;
360
361 unhash_it:
362         __d_drop(dentry);
363 kill_it:
364         /* if dentry was on the d_lru list delete it from there */
365         dentry_lru_del(dentry);
366         dentry = d_kill(dentry);
367         if (dentry)
368                 goto repeat;
369 }
370 EXPORT_SYMBOL(dput);
371
372 /**
373  * d_invalidate - invalidate a dentry
374  * @dentry: dentry to invalidate
375  *
376  * Try to invalidate the dentry if it turns out to be
377  * possible. If there are other dentries that can be
378  * reached through this one we can't delete it and we
379  * return -EBUSY. On success we return 0.
380  *
381  * no dcache lock.
382  */
383  
384 int d_invalidate(struct dentry * dentry)
385 {
386         /*
387          * If it's already been dropped, return OK.
388          */
389         spin_lock(&dcache_lock);
390         spin_lock(&dentry->d_lock);
391         if (d_unhashed(dentry)) {
392                 spin_unlock(&dentry->d_lock);
393                 spin_unlock(&dcache_lock);
394                 return 0;
395         }
396         /*
397          * Check whether to do a partial shrink_dcache
398          * to get rid of unused child entries.
399          */
400         if (!list_empty(&dentry->d_subdirs)) {
401                 spin_unlock(&dentry->d_lock);
402                 spin_unlock(&dcache_lock);
403                 shrink_dcache_parent(dentry);
404                 spin_lock(&dcache_lock);
405                 spin_lock(&dentry->d_lock);
406         }
407
408         /*
409          * Somebody else still using it?
410          *
411          * If it's a directory, we can't drop it
412          * for fear of somebody re-populating it
413          * with children (even though dropping it
414          * would make it unreachable from the root,
415          * we might still populate it if it was a
416          * working directory or similar).
417          */
418         if (dentry->d_count > 1) {
419                 if (dentry->d_inode && S_ISDIR(dentry->d_inode->i_mode)) {
420                         spin_unlock(&dentry->d_lock);
421                         spin_unlock(&dcache_lock);
422                         return -EBUSY;
423                 }
424         }
425
426         __d_drop(dentry);
427         spin_unlock(&dentry->d_lock);
428         spin_unlock(&dcache_lock);
429         return 0;
430 }
431 EXPORT_SYMBOL(d_invalidate);
432
433 /* This must be called with dcache_lock and d_lock held */
434 static inline struct dentry * __dget_locked_dlock(struct dentry *dentry)
435 {
436         dentry->d_count++;
437         dentry_lru_del(dentry);
438         return dentry;
439 }
440
441 /* This should be called _only_ with dcache_lock held */
442 static inline struct dentry * __dget_locked(struct dentry *dentry)
443 {
444         spin_lock(&dentry->d_lock);
445         __dget_locked_dlock(dentry);
446         spin_unlock(&dentry->d_lock);
447         return dentry;
448 }
449
450 struct dentry * dget_locked_dlock(struct dentry *dentry)
451 {
452         return __dget_locked_dlock(dentry);
453 }
454
455 struct dentry * dget_locked(struct dentry *dentry)
456 {
457         return __dget_locked(dentry);
458 }
459 EXPORT_SYMBOL(dget_locked);
460
461 struct dentry *dget_parent(struct dentry *dentry)
462 {
463         struct dentry *ret;
464
465 repeat:
466         spin_lock(&dentry->d_lock);
467         ret = dentry->d_parent;
468         if (!ret)
469                 goto out;
470         if (dentry == ret) {
471                 ret->d_count++;
472                 goto out;
473         }
474         if (!spin_trylock(&ret->d_lock)) {
475                 spin_unlock(&dentry->d_lock);
476                 cpu_relax();
477                 goto repeat;
478         }
479         BUG_ON(!ret->d_count);
480         ret->d_count++;
481         spin_unlock(&ret->d_lock);
482 out:
483         spin_unlock(&dentry->d_lock);
484         return ret;
485 }
486 EXPORT_SYMBOL(dget_parent);
487
488 /**
489  * d_find_alias - grab a hashed alias of inode
490  * @inode: inode in question
491  * @want_discon:  flag, used by d_splice_alias, to request
492  *          that only a DISCONNECTED alias be returned.
493  *
494  * If inode has a hashed alias, or is a directory and has any alias,
495  * acquire the reference to alias and return it. Otherwise return NULL.
496  * Notice that if inode is a directory there can be only one alias and
497  * it can be unhashed only if it has no children, or if it is the root
498  * of a filesystem.
499  *
500  * If the inode has an IS_ROOT, DCACHE_DISCONNECTED alias, then prefer
501  * any other hashed alias over that one unless @want_discon is set,
502  * in which case only return an IS_ROOT, DCACHE_DISCONNECTED alias.
503  */
504 static struct dentry *__d_find_alias(struct inode *inode, int want_discon)
505 {
506         struct dentry *alias, *discon_alias;
507
508 again:
509         discon_alias = NULL;
510         list_for_each_entry(alias, &inode->i_dentry, d_alias) {
511                 spin_lock(&alias->d_lock);
512                 if (S_ISDIR(inode->i_mode) || !d_unhashed(alias)) {
513                         if (IS_ROOT(alias) &&
514                             (alias->d_flags & DCACHE_DISCONNECTED)) {
515                                 discon_alias = alias;
516                         } else if (!want_discon) {
517                                 __dget_locked_dlock(alias);
518                                 spin_unlock(&alias->d_lock);
519                                 return alias;
520                         }
521                 }
522                 spin_unlock(&alias->d_lock);
523         }
524         if (discon_alias) {
525                 alias = discon_alias;
526                 spin_lock(&alias->d_lock);
527                 if (S_ISDIR(inode->i_mode) || !d_unhashed(alias)) {
528                         if (IS_ROOT(alias) &&
529                             (alias->d_flags & DCACHE_DISCONNECTED)) {
530                                 __dget_locked_dlock(alias);
531                                 spin_unlock(&alias->d_lock);
532                                 return alias;
533                         }
534                 }
535                 spin_unlock(&alias->d_lock);
536                 goto again;
537         }
538         return NULL;
539 }
540
541 struct dentry *d_find_alias(struct inode *inode)
542 {
543         struct dentry *de = NULL;
544
545         if (!list_empty(&inode->i_dentry)) {
546                 spin_lock(&dcache_lock);
547                 de = __d_find_alias(inode, 0);
548                 spin_unlock(&dcache_lock);
549         }
550         return de;
551 }
552 EXPORT_SYMBOL(d_find_alias);
553
554 /*
555  *      Try to kill dentries associated with this inode.
556  * WARNING: you must own a reference to inode.
557  */
558 void d_prune_aliases(struct inode *inode)
559 {
560         struct dentry *dentry;
561 restart:
562         spin_lock(&dcache_lock);
563         list_for_each_entry(dentry, &inode->i_dentry, d_alias) {
564                 spin_lock(&dentry->d_lock);
565                 if (!dentry->d_count) {
566                         __dget_locked_dlock(dentry);
567                         __d_drop(dentry);
568                         spin_unlock(&dentry->d_lock);
569                         spin_unlock(&dcache_lock);
570                         dput(dentry);
571                         goto restart;
572                 }
573                 spin_unlock(&dentry->d_lock);
574         }
575         spin_unlock(&dcache_lock);
576 }
577 EXPORT_SYMBOL(d_prune_aliases);
578
579 /*
580  * Throw away a dentry - free the inode, dput the parent.  This requires that
581  * the LRU list has already been removed.
582  *
583  * Try to prune ancestors as well.  This is necessary to prevent
584  * quadratic behavior of shrink_dcache_parent(), but is also expected
585  * to be beneficial in reducing dentry cache fragmentation.
586  */
587 static void prune_one_dentry(struct dentry * dentry)
588         __releases(dentry->d_lock)
589         __releases(dcache_lock)
590 {
591         __d_drop(dentry);
592         dentry = d_kill(dentry);
593
594         /*
595          * Prune ancestors.  Locking is simpler than in dput(),
596          * because dcache_lock needs to be taken anyway.
597          */
598         while (dentry) {
599                 spin_lock(&dcache_lock);
600                 spin_lock(&dentry->d_lock);
601                 dentry->d_count--;
602                 if (dentry->d_count) {
603                         spin_unlock(&dentry->d_lock);
604                         spin_unlock(&dcache_lock);
605                         return;
606                 }
607
608                 dentry_lru_del(dentry);
609                 __d_drop(dentry);
610                 dentry = d_kill(dentry);
611         }
612 }
613
614 static void shrink_dentry_list(struct list_head *list)
615 {
616         struct dentry *dentry;
617
618         while (!list_empty(list)) {
619                 dentry = list_entry(list->prev, struct dentry, d_lru);
620
621                 if (!spin_trylock(&dentry->d_lock)) {
622                         spin_unlock(&dcache_lru_lock);
623                         cpu_relax();
624                         spin_lock(&dcache_lru_lock);
625                         continue;
626                 }
627
628                 __dentry_lru_del(dentry);
629
630                 /*
631                  * We found an inuse dentry which was not removed from
632                  * the LRU because of laziness during lookup.  Do not free
633                  * it - just keep it off the LRU list.
634                  */
635                 if (dentry->d_count) {
636                         spin_unlock(&dentry->d_lock);
637                         continue;
638                 }
639                 spin_unlock(&dcache_lru_lock);
640
641                 prune_one_dentry(dentry);
642                 /* dcache_lock and dentry->d_lock dropped */
643                 spin_lock(&dcache_lock);
644                 spin_lock(&dcache_lru_lock);
645         }
646 }
647
648 /**
649  * __shrink_dcache_sb - shrink the dentry LRU on a given superblock
650  * @sb:         superblock to shrink dentry LRU.
651  * @count:      number of entries to prune
652  * @flags:      flags to control the dentry processing
653  *
654  * If flags contains DCACHE_REFERENCED reference dentries will not be pruned.
655  */
656 static void __shrink_dcache_sb(struct super_block *sb, int *count, int flags)
657 {
658         /* called from prune_dcache() and shrink_dcache_parent() */
659         struct dentry *dentry;
660         LIST_HEAD(referenced);
661         LIST_HEAD(tmp);
662         int cnt = *count;
663
664         spin_lock(&dcache_lock);
665 relock:
666         spin_lock(&dcache_lru_lock);
667         while (!list_empty(&sb->s_dentry_lru)) {
668                 dentry = list_entry(sb->s_dentry_lru.prev,
669                                 struct dentry, d_lru);
670                 BUG_ON(dentry->d_sb != sb);
671
672                 if (!spin_trylock(&dentry->d_lock)) {
673                         spin_unlock(&dcache_lru_lock);
674                         cpu_relax();
675                         goto relock;
676                 }
677
678                 /*
679                  * If we are honouring the DCACHE_REFERENCED flag and the
680                  * dentry has this flag set, don't free it.  Clear the flag
681                  * and put it back on the LRU.
682                  */
683                 if (flags & DCACHE_REFERENCED &&
684                                 dentry->d_flags & DCACHE_REFERENCED) {
685                         dentry->d_flags &= ~DCACHE_REFERENCED;
686                         list_move(&dentry->d_lru, &referenced);
687                         spin_unlock(&dentry->d_lock);
688                 } else {
689                         list_move_tail(&dentry->d_lru, &tmp);
690                         spin_unlock(&dentry->d_lock);
691                         if (!--cnt)
692                                 break;
693                 }
694                 /* XXX: re-add cond_resched_lock when dcache_lock goes away */
695         }
696
697         *count = cnt;
698         shrink_dentry_list(&tmp);
699
700         if (!list_empty(&referenced))
701                 list_splice(&referenced, &sb->s_dentry_lru);
702         spin_unlock(&dcache_lru_lock);
703         spin_unlock(&dcache_lock);
704
705 }
706
707 /**
708  * prune_dcache - shrink the dcache
709  * @count: number of entries to try to free
710  *
711  * Shrink the dcache. This is done when we need more memory, or simply when we
712  * need to unmount something (at which point we need to unuse all dentries).
713  *
714  * This function may fail to free any resources if all the dentries are in use.
715  */
716 static void prune_dcache(int count)
717 {
718         struct super_block *sb, *p = NULL;
719         int w_count;
720         int unused = dentry_stat.nr_unused;
721         int prune_ratio;
722         int pruned;
723
724         if (unused == 0 || count == 0)
725                 return;
726         spin_lock(&dcache_lock);
727         if (count >= unused)
728                 prune_ratio = 1;
729         else
730                 prune_ratio = unused / count;
731         spin_lock(&sb_lock);
732         list_for_each_entry(sb, &super_blocks, s_list) {
733                 if (list_empty(&sb->s_instances))
734                         continue;
735                 if (sb->s_nr_dentry_unused == 0)
736                         continue;
737                 sb->s_count++;
738                 /* Now, we reclaim unused dentrins with fairness.
739                  * We reclaim them same percentage from each superblock.
740                  * We calculate number of dentries to scan on this sb
741                  * as follows, but the implementation is arranged to avoid
742                  * overflows:
743                  * number of dentries to scan on this sb =
744                  * count * (number of dentries on this sb /
745                  * number of dentries in the machine)
746                  */
747                 spin_unlock(&sb_lock);
748                 if (prune_ratio != 1)
749                         w_count = (sb->s_nr_dentry_unused / prune_ratio) + 1;
750                 else
751                         w_count = sb->s_nr_dentry_unused;
752                 pruned = w_count;
753                 /*
754                  * We need to be sure this filesystem isn't being unmounted,
755                  * otherwise we could race with generic_shutdown_super(), and
756                  * end up holding a reference to an inode while the filesystem
757                  * is unmounted.  So we try to get s_umount, and make sure
758                  * s_root isn't NULL.
759                  */
760                 if (down_read_trylock(&sb->s_umount)) {
761                         if ((sb->s_root != NULL) &&
762                             (!list_empty(&sb->s_dentry_lru))) {
763                                 spin_unlock(&dcache_lock);
764                                 __shrink_dcache_sb(sb, &w_count,
765                                                 DCACHE_REFERENCED);
766                                 pruned -= w_count;
767                                 spin_lock(&dcache_lock);
768                         }
769                         up_read(&sb->s_umount);
770                 }
771                 spin_lock(&sb_lock);
772                 if (p)
773                         __put_super(p);
774                 count -= pruned;
775                 p = sb;
776                 /* more work left to do? */
777                 if (count <= 0)
778                         break;
779         }
780         if (p)
781                 __put_super(p);
782         spin_unlock(&sb_lock);
783         spin_unlock(&dcache_lock);
784 }
785
786 /**
787  * shrink_dcache_sb - shrink dcache for a superblock
788  * @sb: superblock
789  *
790  * Shrink the dcache for the specified super block. This is used to free
791  * the dcache before unmounting a file system.
792  */
793 void shrink_dcache_sb(struct super_block *sb)
794 {
795         LIST_HEAD(tmp);
796
797         spin_lock(&dcache_lock);
798         spin_lock(&dcache_lru_lock);
799         while (!list_empty(&sb->s_dentry_lru)) {
800                 list_splice_init(&sb->s_dentry_lru, &tmp);
801                 shrink_dentry_list(&tmp);
802         }
803         spin_unlock(&dcache_lru_lock);
804         spin_unlock(&dcache_lock);
805 }
806 EXPORT_SYMBOL(shrink_dcache_sb);
807
808 /*
809  * destroy a single subtree of dentries for unmount
810  * - see the comments on shrink_dcache_for_umount() for a description of the
811  *   locking
812  */
813 static void shrink_dcache_for_umount_subtree(struct dentry *dentry)
814 {
815         struct dentry *parent;
816         unsigned detached = 0;
817
818         BUG_ON(!IS_ROOT(dentry));
819
820         /* detach this root from the system */
821         spin_lock(&dcache_lock);
822         spin_lock(&dentry->d_lock);
823         dentry_lru_del(dentry);
824         __d_drop(dentry);
825         spin_unlock(&dentry->d_lock);
826         spin_unlock(&dcache_lock);
827
828         for (;;) {
829                 /* descend to the first leaf in the current subtree */
830                 while (!list_empty(&dentry->d_subdirs)) {
831                         struct dentry *loop;
832
833                         /* this is a branch with children - detach all of them
834                          * from the system in one go */
835                         spin_lock(&dcache_lock);
836                         list_for_each_entry(loop, &dentry->d_subdirs,
837                                             d_u.d_child) {
838                                 spin_lock(&loop->d_lock);
839                                 dentry_lru_del(loop);
840                                 __d_drop(loop);
841                                 spin_unlock(&loop->d_lock);
842                                 cond_resched_lock(&dcache_lock);
843                         }
844                         spin_unlock(&dcache_lock);
845
846                         /* move to the first child */
847                         dentry = list_entry(dentry->d_subdirs.next,
848                                             struct dentry, d_u.d_child);
849                 }
850
851                 /* consume the dentries from this leaf up through its parents
852                  * until we find one with children or run out altogether */
853                 do {
854                         struct inode *inode;
855
856                         if (dentry->d_count != 0) {
857                                 printk(KERN_ERR
858                                        "BUG: Dentry %p{i=%lx,n=%s}"
859                                        " still in use (%d)"
860                                        " [unmount of %s %s]\n",
861                                        dentry,
862                                        dentry->d_inode ?
863                                        dentry->d_inode->i_ino : 0UL,
864                                        dentry->d_name.name,
865                                        dentry->d_count,
866                                        dentry->d_sb->s_type->name,
867                                        dentry->d_sb->s_id);
868                                 BUG();
869                         }
870
871                         if (IS_ROOT(dentry))
872                                 parent = NULL;
873                         else {
874                                 parent = dentry->d_parent;
875                                 spin_lock(&parent->d_lock);
876                                 parent->d_count--;
877                                 spin_unlock(&parent->d_lock);
878                         }
879
880                         list_del(&dentry->d_u.d_child);
881                         detached++;
882
883                         inode = dentry->d_inode;
884                         if (inode) {
885                                 dentry->d_inode = NULL;
886                                 list_del_init(&dentry->d_alias);
887                                 if (dentry->d_op && dentry->d_op->d_iput)
888                                         dentry->d_op->d_iput(dentry, inode);
889                                 else
890                                         iput(inode);
891                         }
892
893                         d_free(dentry);
894
895                         /* finished when we fall off the top of the tree,
896                          * otherwise we ascend to the parent and move to the
897                          * next sibling if there is one */
898                         if (!parent)
899                                 return;
900                         dentry = parent;
901                 } while (list_empty(&dentry->d_subdirs));
902
903                 dentry = list_entry(dentry->d_subdirs.next,
904                                     struct dentry, d_u.d_child);
905         }
906 }
907
908 /*
909  * destroy the dentries attached to a superblock on unmounting
910  * - we don't need to use dentry->d_lock, and only need dcache_lock when
911  *   removing the dentry from the system lists and hashes because:
912  *   - the superblock is detached from all mountings and open files, so the
913  *     dentry trees will not be rearranged by the VFS
914  *   - s_umount is write-locked, so the memory pressure shrinker will ignore
915  *     any dentries belonging to this superblock that it comes across
916  *   - the filesystem itself is no longer permitted to rearrange the dentries
917  *     in this superblock
918  */
919 void shrink_dcache_for_umount(struct super_block *sb)
920 {
921         struct dentry *dentry;
922
923         if (down_read_trylock(&sb->s_umount))
924                 BUG();
925
926         dentry = sb->s_root;
927         sb->s_root = NULL;
928         spin_lock(&dentry->d_lock);
929         dentry->d_count--;
930         spin_unlock(&dentry->d_lock);
931         shrink_dcache_for_umount_subtree(dentry);
932
933         while (!hlist_empty(&sb->s_anon)) {
934                 dentry = hlist_entry(sb->s_anon.first, struct dentry, d_hash);
935                 shrink_dcache_for_umount_subtree(dentry);
936         }
937 }
938
939 /*
940  * Search for at least 1 mount point in the dentry's subdirs.
941  * We descend to the next level whenever the d_subdirs
942  * list is non-empty and continue searching.
943  */
944  
945 /**
946  * have_submounts - check for mounts over a dentry
947  * @parent: dentry to check.
948  *
949  * Return true if the parent or its subdirectories contain
950  * a mount point
951  */
952  
953 int have_submounts(struct dentry *parent)
954 {
955         struct dentry *this_parent = parent;
956         struct list_head *next;
957
958         spin_lock(&dcache_lock);
959         if (d_mountpoint(parent))
960                 goto positive;
961 repeat:
962         next = this_parent->d_subdirs.next;
963 resume:
964         while (next != &this_parent->d_subdirs) {
965                 struct list_head *tmp = next;
966                 struct dentry *dentry = list_entry(tmp, struct dentry, d_u.d_child);
967                 next = tmp->next;
968                 /* Have we found a mount point ? */
969                 if (d_mountpoint(dentry))
970                         goto positive;
971                 if (!list_empty(&dentry->d_subdirs)) {
972                         this_parent = dentry;
973                         goto repeat;
974                 }
975         }
976         /*
977          * All done at this level ... ascend and resume the search.
978          */
979         if (this_parent != parent) {
980                 next = this_parent->d_u.d_child.next;
981                 this_parent = this_parent->d_parent;
982                 goto resume;
983         }
984         spin_unlock(&dcache_lock);
985         return 0; /* No mount points found in tree */
986 positive:
987         spin_unlock(&dcache_lock);
988         return 1;
989 }
990 EXPORT_SYMBOL(have_submounts);
991
992 /*
993  * Search the dentry child list for the specified parent,
994  * and move any unused dentries to the end of the unused
995  * list for prune_dcache(). We descend to the next level
996  * whenever the d_subdirs list is non-empty and continue
997  * searching.
998  *
999  * It returns zero iff there are no unused children,
1000  * otherwise  it returns the number of children moved to
1001  * the end of the unused list. This may not be the total
1002  * number of unused children, because select_parent can
1003  * drop the lock and return early due to latency
1004  * constraints.
1005  */
1006 static int select_parent(struct dentry * parent)
1007 {
1008         struct dentry *this_parent = parent;
1009         struct list_head *next;
1010         int found = 0;
1011
1012         spin_lock(&dcache_lock);
1013 repeat:
1014         next = this_parent->d_subdirs.next;
1015 resume:
1016         while (next != &this_parent->d_subdirs) {
1017                 struct list_head *tmp = next;
1018                 struct dentry *dentry = list_entry(tmp, struct dentry, d_u.d_child);
1019                 next = tmp->next;
1020
1021                 spin_lock(&dentry->d_lock);
1022
1023                 /* 
1024                  * move only zero ref count dentries to the end 
1025                  * of the unused list for prune_dcache
1026                  */
1027                 if (!dentry->d_count) {
1028                         dentry_lru_move_tail(dentry);
1029                         found++;
1030                 } else {
1031                         dentry_lru_del(dentry);
1032                 }
1033
1034                 spin_unlock(&dentry->d_lock);
1035
1036                 /*
1037                  * We can return to the caller if we have found some (this
1038                  * ensures forward progress). We'll be coming back to find
1039                  * the rest.
1040                  */
1041                 if (found && need_resched())
1042                         goto out;
1043
1044                 /*
1045                  * Descend a level if the d_subdirs list is non-empty.
1046                  */
1047                 if (!list_empty(&dentry->d_subdirs)) {
1048                         this_parent = dentry;
1049                         goto repeat;
1050                 }
1051         }
1052         /*
1053          * All done at this level ... ascend and resume the search.
1054          */
1055         if (this_parent != parent) {
1056                 next = this_parent->d_u.d_child.next;
1057                 this_parent = this_parent->d_parent;
1058                 goto resume;
1059         }
1060 out:
1061         spin_unlock(&dcache_lock);
1062         return found;
1063 }
1064
1065 /**
1066  * shrink_dcache_parent - prune dcache
1067  * @parent: parent of entries to prune
1068  *
1069  * Prune the dcache to remove unused children of the parent dentry.
1070  */
1071  
1072 void shrink_dcache_parent(struct dentry * parent)
1073 {
1074         struct super_block *sb = parent->d_sb;
1075         int found;
1076
1077         while ((found = select_parent(parent)) != 0)
1078                 __shrink_dcache_sb(sb, &found, 0);
1079 }
1080 EXPORT_SYMBOL(shrink_dcache_parent);
1081
1082 /*
1083  * Scan `nr' dentries and return the number which remain.
1084  *
1085  * We need to avoid reentering the filesystem if the caller is performing a
1086  * GFP_NOFS allocation attempt.  One example deadlock is:
1087  *
1088  * ext2_new_block->getblk->GFP->shrink_dcache_memory->prune_dcache->
1089  * prune_one_dentry->dput->dentry_iput->iput->inode->i_sb->s_op->put_inode->
1090  * ext2_discard_prealloc->ext2_free_blocks->lock_super->DEADLOCK.
1091  *
1092  * In this case we return -1 to tell the caller that we baled.
1093  */
1094 static int shrink_dcache_memory(struct shrinker *shrink, int nr, gfp_t gfp_mask)
1095 {
1096         if (nr) {
1097                 if (!(gfp_mask & __GFP_FS))
1098                         return -1;
1099                 prune_dcache(nr);
1100         }
1101
1102         return (dentry_stat.nr_unused / 100) * sysctl_vfs_cache_pressure;
1103 }
1104
1105 static struct shrinker dcache_shrinker = {
1106         .shrink = shrink_dcache_memory,
1107         .seeks = DEFAULT_SEEKS,
1108 };
1109
1110 /**
1111  * d_alloc      -       allocate a dcache entry
1112  * @parent: parent of entry to allocate
1113  * @name: qstr of the name
1114  *
1115  * Allocates a dentry. It returns %NULL if there is insufficient memory
1116  * available. On a success the dentry is returned. The name passed in is
1117  * copied and the copy passed in may be reused after this call.
1118  */
1119  
1120 struct dentry *d_alloc(struct dentry * parent, const struct qstr *name)
1121 {
1122         struct dentry *dentry;
1123         char *dname;
1124
1125         dentry = kmem_cache_alloc(dentry_cache, GFP_KERNEL);
1126         if (!dentry)
1127                 return NULL;
1128
1129         if (name->len > DNAME_INLINE_LEN-1) {
1130                 dname = kmalloc(name->len + 1, GFP_KERNEL);
1131                 if (!dname) {
1132                         kmem_cache_free(dentry_cache, dentry); 
1133                         return NULL;
1134                 }
1135         } else  {
1136                 dname = dentry->d_iname;
1137         }       
1138         dentry->d_name.name = dname;
1139
1140         dentry->d_name.len = name->len;
1141         dentry->d_name.hash = name->hash;
1142         memcpy(dname, name->name, name->len);
1143         dname[name->len] = 0;
1144
1145         dentry->d_count = 1;
1146         dentry->d_flags = DCACHE_UNHASHED;
1147         spin_lock_init(&dentry->d_lock);
1148         dentry->d_inode = NULL;
1149         dentry->d_parent = NULL;
1150         dentry->d_sb = NULL;
1151         dentry->d_op = NULL;
1152         dentry->d_fsdata = NULL;
1153         dentry->d_mounted = 0;
1154         INIT_HLIST_NODE(&dentry->d_hash);
1155         INIT_LIST_HEAD(&dentry->d_lru);
1156         INIT_LIST_HEAD(&dentry->d_subdirs);
1157         INIT_LIST_HEAD(&dentry->d_alias);
1158
1159         if (parent) {
1160                 dentry->d_parent = dget(parent);
1161                 dentry->d_sb = parent->d_sb;
1162         } else {
1163                 INIT_LIST_HEAD(&dentry->d_u.d_child);
1164         }
1165
1166         spin_lock(&dcache_lock);
1167         if (parent)
1168                 list_add(&dentry->d_u.d_child, &parent->d_subdirs);
1169         spin_unlock(&dcache_lock);
1170
1171         this_cpu_inc(nr_dentry);
1172
1173         return dentry;
1174 }
1175 EXPORT_SYMBOL(d_alloc);
1176
1177 struct dentry *d_alloc_name(struct dentry *parent, const char *name)
1178 {
1179         struct qstr q;
1180
1181         q.name = name;
1182         q.len = strlen(name);
1183         q.hash = full_name_hash(q.name, q.len);
1184         return d_alloc(parent, &q);
1185 }
1186 EXPORT_SYMBOL(d_alloc_name);
1187
1188 /* the caller must hold dcache_lock */
1189 static void __d_instantiate(struct dentry *dentry, struct inode *inode)
1190 {
1191         if (inode)
1192                 list_add(&dentry->d_alias, &inode->i_dentry);
1193         dentry->d_inode = inode;
1194         fsnotify_d_instantiate(dentry, inode);
1195 }
1196
1197 /**
1198  * d_instantiate - fill in inode information for a dentry
1199  * @entry: dentry to complete
1200  * @inode: inode to attach to this dentry
1201  *
1202  * Fill in inode information in the entry.
1203  *
1204  * This turns negative dentries into productive full members
1205  * of society.
1206  *
1207  * NOTE! This assumes that the inode count has been incremented
1208  * (or otherwise set) by the caller to indicate that it is now
1209  * in use by the dcache.
1210  */
1211  
1212 void d_instantiate(struct dentry *entry, struct inode * inode)
1213 {
1214         BUG_ON(!list_empty(&entry->d_alias));
1215         spin_lock(&dcache_lock);
1216         __d_instantiate(entry, inode);
1217         spin_unlock(&dcache_lock);
1218         security_d_instantiate(entry, inode);
1219 }
1220 EXPORT_SYMBOL(d_instantiate);
1221
1222 /**
1223  * d_instantiate_unique - instantiate a non-aliased dentry
1224  * @entry: dentry to instantiate
1225  * @inode: inode to attach to this dentry
1226  *
1227  * Fill in inode information in the entry. On success, it returns NULL.
1228  * If an unhashed alias of "entry" already exists, then we return the
1229  * aliased dentry instead and drop one reference to inode.
1230  *
1231  * Note that in order to avoid conflicts with rename() etc, the caller
1232  * had better be holding the parent directory semaphore.
1233  *
1234  * This also assumes that the inode count has been incremented
1235  * (or otherwise set) by the caller to indicate that it is now
1236  * in use by the dcache.
1237  */
1238 static struct dentry *__d_instantiate_unique(struct dentry *entry,
1239                                              struct inode *inode)
1240 {
1241         struct dentry *alias;
1242         int len = entry->d_name.len;
1243         const char *name = entry->d_name.name;
1244         unsigned int hash = entry->d_name.hash;
1245
1246         if (!inode) {
1247                 __d_instantiate(entry, NULL);
1248                 return NULL;
1249         }
1250
1251         list_for_each_entry(alias, &inode->i_dentry, d_alias) {
1252                 struct qstr *qstr = &alias->d_name;
1253
1254                 if (qstr->hash != hash)
1255                         continue;
1256                 if (alias->d_parent != entry->d_parent)
1257                         continue;
1258                 if (qstr->len != len)
1259                         continue;
1260                 if (memcmp(qstr->name, name, len))
1261                         continue;
1262                 dget_locked(alias);
1263                 return alias;
1264         }
1265
1266         __d_instantiate(entry, inode);
1267         return NULL;
1268 }
1269
1270 struct dentry *d_instantiate_unique(struct dentry *entry, struct inode *inode)
1271 {
1272         struct dentry *result;
1273
1274         BUG_ON(!list_empty(&entry->d_alias));
1275
1276         spin_lock(&dcache_lock);
1277         result = __d_instantiate_unique(entry, inode);
1278         spin_unlock(&dcache_lock);
1279
1280         if (!result) {
1281                 security_d_instantiate(entry, inode);
1282                 return NULL;
1283         }
1284
1285         BUG_ON(!d_unhashed(result));
1286         iput(inode);
1287         return result;
1288 }
1289
1290 EXPORT_SYMBOL(d_instantiate_unique);
1291
1292 /**
1293  * d_alloc_root - allocate root dentry
1294  * @root_inode: inode to allocate the root for
1295  *
1296  * Allocate a root ("/") dentry for the inode given. The inode is
1297  * instantiated and returned. %NULL is returned if there is insufficient
1298  * memory or the inode passed is %NULL.
1299  */
1300  
1301 struct dentry * d_alloc_root(struct inode * root_inode)
1302 {
1303         struct dentry *res = NULL;
1304
1305         if (root_inode) {
1306                 static const struct qstr name = { .name = "/", .len = 1 };
1307
1308                 res = d_alloc(NULL, &name);
1309                 if (res) {
1310                         res->d_sb = root_inode->i_sb;
1311                         res->d_parent = res;
1312                         d_instantiate(res, root_inode);
1313                 }
1314         }
1315         return res;
1316 }
1317 EXPORT_SYMBOL(d_alloc_root);
1318
1319 static inline struct hlist_head *d_hash(struct dentry *parent,
1320                                         unsigned long hash)
1321 {
1322         hash += ((unsigned long) parent ^ GOLDEN_RATIO_PRIME) / L1_CACHE_BYTES;
1323         hash = hash ^ ((hash ^ GOLDEN_RATIO_PRIME) >> D_HASHBITS);
1324         return dentry_hashtable + (hash & D_HASHMASK);
1325 }
1326
1327 /**
1328  * d_obtain_alias - find or allocate a dentry for a given inode
1329  * @inode: inode to allocate the dentry for
1330  *
1331  * Obtain a dentry for an inode resulting from NFS filehandle conversion or
1332  * similar open by handle operations.  The returned dentry may be anonymous,
1333  * or may have a full name (if the inode was already in the cache).
1334  *
1335  * When called on a directory inode, we must ensure that the inode only ever
1336  * has one dentry.  If a dentry is found, that is returned instead of
1337  * allocating a new one.
1338  *
1339  * On successful return, the reference to the inode has been transferred
1340  * to the dentry.  In case of an error the reference on the inode is released.
1341  * To make it easier to use in export operations a %NULL or IS_ERR inode may
1342  * be passed in and will be the error will be propagate to the return value,
1343  * with a %NULL @inode replaced by ERR_PTR(-ESTALE).
1344  */
1345 struct dentry *d_obtain_alias(struct inode *inode)
1346 {
1347         static const struct qstr anonstring = { .name = "" };
1348         struct dentry *tmp;
1349         struct dentry *res;
1350
1351         if (!inode)
1352                 return ERR_PTR(-ESTALE);
1353         if (IS_ERR(inode))
1354                 return ERR_CAST(inode);
1355
1356         res = d_find_alias(inode);
1357         if (res)
1358                 goto out_iput;
1359
1360         tmp = d_alloc(NULL, &anonstring);
1361         if (!tmp) {
1362                 res = ERR_PTR(-ENOMEM);
1363                 goto out_iput;
1364         }
1365         tmp->d_parent = tmp; /* make sure dput doesn't croak */
1366
1367         spin_lock(&dcache_lock);
1368         res = __d_find_alias(inode, 0);
1369         if (res) {
1370                 spin_unlock(&dcache_lock);
1371                 dput(tmp);
1372                 goto out_iput;
1373         }
1374
1375         /* attach a disconnected dentry */
1376         spin_lock(&tmp->d_lock);
1377         tmp->d_sb = inode->i_sb;
1378         tmp->d_inode = inode;
1379         tmp->d_flags |= DCACHE_DISCONNECTED;
1380         tmp->d_flags &= ~DCACHE_UNHASHED;
1381         list_add(&tmp->d_alias, &inode->i_dentry);
1382         spin_lock(&dcache_hash_lock);
1383         hlist_add_head(&tmp->d_hash, &inode->i_sb->s_anon);
1384         spin_unlock(&dcache_hash_lock);
1385         spin_unlock(&tmp->d_lock);
1386
1387         spin_unlock(&dcache_lock);
1388         return tmp;
1389
1390  out_iput:
1391         iput(inode);
1392         return res;
1393 }
1394 EXPORT_SYMBOL(d_obtain_alias);
1395
1396 /**
1397  * d_splice_alias - splice a disconnected dentry into the tree if one exists
1398  * @inode:  the inode which may have a disconnected dentry
1399  * @dentry: a negative dentry which we want to point to the inode.
1400  *
1401  * If inode is a directory and has a 'disconnected' dentry (i.e. IS_ROOT and
1402  * DCACHE_DISCONNECTED), then d_move that in place of the given dentry
1403  * and return it, else simply d_add the inode to the dentry and return NULL.
1404  *
1405  * This is needed in the lookup routine of any filesystem that is exportable
1406  * (via knfsd) so that we can build dcache paths to directories effectively.
1407  *
1408  * If a dentry was found and moved, then it is returned.  Otherwise NULL
1409  * is returned.  This matches the expected return value of ->lookup.
1410  *
1411  */
1412 struct dentry *d_splice_alias(struct inode *inode, struct dentry *dentry)
1413 {
1414         struct dentry *new = NULL;
1415
1416         if (inode && S_ISDIR(inode->i_mode)) {
1417                 spin_lock(&dcache_lock);
1418                 new = __d_find_alias(inode, 1);
1419                 if (new) {
1420                         BUG_ON(!(new->d_flags & DCACHE_DISCONNECTED));
1421                         spin_unlock(&dcache_lock);
1422                         security_d_instantiate(new, inode);
1423                         d_move(new, dentry);
1424                         iput(inode);
1425                 } else {
1426                         /* already taking dcache_lock, so d_add() by hand */
1427                         __d_instantiate(dentry, inode);
1428                         spin_unlock(&dcache_lock);
1429                         security_d_instantiate(dentry, inode);
1430                         d_rehash(dentry);
1431                 }
1432         } else
1433                 d_add(dentry, inode);
1434         return new;
1435 }
1436 EXPORT_SYMBOL(d_splice_alias);
1437
1438 /**
1439  * d_add_ci - lookup or allocate new dentry with case-exact name
1440  * @inode:  the inode case-insensitive lookup has found
1441  * @dentry: the negative dentry that was passed to the parent's lookup func
1442  * @name:   the case-exact name to be associated with the returned dentry
1443  *
1444  * This is to avoid filling the dcache with case-insensitive names to the
1445  * same inode, only the actual correct case is stored in the dcache for
1446  * case-insensitive filesystems.
1447  *
1448  * For a case-insensitive lookup match and if the the case-exact dentry
1449  * already exists in in the dcache, use it and return it.
1450  *
1451  * If no entry exists with the exact case name, allocate new dentry with
1452  * the exact case, and return the spliced entry.
1453  */
1454 struct dentry *d_add_ci(struct dentry *dentry, struct inode *inode,
1455                         struct qstr *name)
1456 {
1457         int error;
1458         struct dentry *found;
1459         struct dentry *new;
1460
1461         /*
1462          * First check if a dentry matching the name already exists,
1463          * if not go ahead and create it now.
1464          */
1465         found = d_hash_and_lookup(dentry->d_parent, name);
1466         if (!found) {
1467                 new = d_alloc(dentry->d_parent, name);
1468                 if (!new) {
1469                         error = -ENOMEM;
1470                         goto err_out;
1471                 }
1472
1473                 found = d_splice_alias(inode, new);
1474                 if (found) {
1475                         dput(new);
1476                         return found;
1477                 }
1478                 return new;
1479         }
1480
1481         /*
1482          * If a matching dentry exists, and it's not negative use it.
1483          *
1484          * Decrement the reference count to balance the iget() done
1485          * earlier on.
1486          */
1487         if (found->d_inode) {
1488                 if (unlikely(found->d_inode != inode)) {
1489                         /* This can't happen because bad inodes are unhashed. */
1490                         BUG_ON(!is_bad_inode(inode));
1491                         BUG_ON(!is_bad_inode(found->d_inode));
1492                 }
1493                 iput(inode);
1494                 return found;
1495         }
1496
1497         /*
1498          * Negative dentry: instantiate it unless the inode is a directory and
1499          * already has a dentry.
1500          */
1501         spin_lock(&dcache_lock);
1502         if (!S_ISDIR(inode->i_mode) || list_empty(&inode->i_dentry)) {
1503                 __d_instantiate(found, inode);
1504                 spin_unlock(&dcache_lock);
1505                 security_d_instantiate(found, inode);
1506                 return found;
1507         }
1508
1509         /*
1510          * In case a directory already has a (disconnected) entry grab a
1511          * reference to it, move it in place and use it.
1512          */
1513         new = list_entry(inode->i_dentry.next, struct dentry, d_alias);
1514         dget_locked(new);
1515         spin_unlock(&dcache_lock);
1516         security_d_instantiate(found, inode);
1517         d_move(new, found);
1518         iput(inode);
1519         dput(found);
1520         return new;
1521
1522 err_out:
1523         iput(inode);
1524         return ERR_PTR(error);
1525 }
1526 EXPORT_SYMBOL(d_add_ci);
1527
1528 /**
1529  * d_lookup - search for a dentry
1530  * @parent: parent dentry
1531  * @name: qstr of name we wish to find
1532  * Returns: dentry, or NULL
1533  *
1534  * d_lookup searches the children of the parent dentry for the name in
1535  * question. If the dentry is found its reference count is incremented and the
1536  * dentry is returned. The caller must use dput to free the entry when it has
1537  * finished using it. %NULL is returned if the dentry does not exist.
1538  */
1539 struct dentry * d_lookup(struct dentry * parent, struct qstr * name)
1540 {
1541         struct dentry * dentry = NULL;
1542         unsigned long seq;
1543
1544         do {
1545                 seq = read_seqbegin(&rename_lock);
1546                 dentry = __d_lookup(parent, name);
1547                 if (dentry)
1548                         break;
1549         } while (read_seqretry(&rename_lock, seq));
1550         return dentry;
1551 }
1552 EXPORT_SYMBOL(d_lookup);
1553
1554 /*
1555  * __d_lookup - search for a dentry (racy)
1556  * @parent: parent dentry
1557  * @name: qstr of name we wish to find
1558  * Returns: dentry, or NULL
1559  *
1560  * __d_lookup is like d_lookup, however it may (rarely) return a
1561  * false-negative result due to unrelated rename activity.
1562  *
1563  * __d_lookup is slightly faster by avoiding rename_lock read seqlock,
1564  * however it must be used carefully, eg. with a following d_lookup in
1565  * the case of failure.
1566  *
1567  * __d_lookup callers must be commented.
1568  */
1569 struct dentry * __d_lookup(struct dentry * parent, struct qstr * name)
1570 {
1571         unsigned int len = name->len;
1572         unsigned int hash = name->hash;
1573         const unsigned char *str = name->name;
1574         struct hlist_head *head = d_hash(parent,hash);
1575         struct dentry *found = NULL;
1576         struct hlist_node *node;
1577         struct dentry *dentry;
1578
1579         /*
1580          * The hash list is protected using RCU.
1581          *
1582          * Take d_lock when comparing a candidate dentry, to avoid races
1583          * with d_move().
1584          *
1585          * It is possible that concurrent renames can mess up our list
1586          * walk here and result in missing our dentry, resulting in the
1587          * false-negative result. d_lookup() protects against concurrent
1588          * renames using rename_lock seqlock.
1589          *
1590          * See Documentation/vfs/dcache-locking.txt for more details.
1591          */
1592         rcu_read_lock();
1593         
1594         hlist_for_each_entry_rcu(dentry, node, head, d_hash) {
1595                 struct qstr *qstr;
1596
1597                 if (dentry->d_name.hash != hash)
1598                         continue;
1599                 if (dentry->d_parent != parent)
1600                         continue;
1601
1602                 spin_lock(&dentry->d_lock);
1603
1604                 /*
1605                  * Recheck the dentry after taking the lock - d_move may have
1606                  * changed things. Don't bother checking the hash because
1607                  * we're about to compare the whole name anyway.
1608                  */
1609                 if (dentry->d_parent != parent)
1610                         goto next;
1611
1612                 /* non-existing due to RCU? */
1613                 if (d_unhashed(dentry))
1614                         goto next;
1615
1616                 /*
1617                  * It is safe to compare names since d_move() cannot
1618                  * change the qstr (protected by d_lock).
1619                  */
1620                 qstr = &dentry->d_name;
1621                 if (parent->d_op && parent->d_op->d_compare) {
1622                         if (parent->d_op->d_compare(parent, parent->d_inode,
1623                                                 dentry, dentry->d_inode,
1624                                                 qstr->len, qstr->name, name))
1625                                 goto next;
1626                 } else {
1627                         if (qstr->len != len)
1628                                 goto next;
1629                         if (memcmp(qstr->name, str, len))
1630                                 goto next;
1631                 }
1632
1633                 dentry->d_count++;
1634                 found = dentry;
1635                 spin_unlock(&dentry->d_lock);
1636                 break;
1637 next:
1638                 spin_unlock(&dentry->d_lock);
1639         }
1640         rcu_read_unlock();
1641
1642         return found;
1643 }
1644
1645 /**
1646  * d_hash_and_lookup - hash the qstr then search for a dentry
1647  * @dir: Directory to search in
1648  * @name: qstr of name we wish to find
1649  *
1650  * On hash failure or on lookup failure NULL is returned.
1651  */
1652 struct dentry *d_hash_and_lookup(struct dentry *dir, struct qstr *name)
1653 {
1654         struct dentry *dentry = NULL;
1655
1656         /*
1657          * Check for a fs-specific hash function. Note that we must
1658          * calculate the standard hash first, as the d_op->d_hash()
1659          * routine may choose to leave the hash value unchanged.
1660          */
1661         name->hash = full_name_hash(name->name, name->len);
1662         if (dir->d_op && dir->d_op->d_hash) {
1663                 if (dir->d_op->d_hash(dir, dir->d_inode, name) < 0)
1664                         goto out;
1665         }
1666         dentry = d_lookup(dir, name);
1667 out:
1668         return dentry;
1669 }
1670
1671 /**
1672  * d_validate - verify dentry provided from insecure source (deprecated)
1673  * @dentry: The dentry alleged to be valid child of @dparent
1674  * @dparent: The parent dentry (known to be valid)
1675  *
1676  * An insecure source has sent us a dentry, here we verify it and dget() it.
1677  * This is used by ncpfs in its readdir implementation.
1678  * Zero is returned in the dentry is invalid.
1679  *
1680  * This function is slow for big directories, and deprecated, do not use it.
1681  */
1682 int d_validate(struct dentry *dentry, struct dentry *dparent)
1683 {
1684         struct dentry *child;
1685
1686         spin_lock(&dcache_lock);
1687         list_for_each_entry(child, &dparent->d_subdirs, d_u.d_child) {
1688                 if (dentry == child) {
1689                         __dget_locked(dentry);
1690                         spin_unlock(&dcache_lock);
1691                         return 1;
1692                 }
1693         }
1694         spin_unlock(&dcache_lock);
1695
1696         return 0;
1697 }
1698 EXPORT_SYMBOL(d_validate);
1699
1700 /*
1701  * When a file is deleted, we have two options:
1702  * - turn this dentry into a negative dentry
1703  * - unhash this dentry and free it.
1704  *
1705  * Usually, we want to just turn this into
1706  * a negative dentry, but if anybody else is
1707  * currently using the dentry or the inode
1708  * we can't do that and we fall back on removing
1709  * it from the hash queues and waiting for
1710  * it to be deleted later when it has no users
1711  */
1712  
1713 /**
1714  * d_delete - delete a dentry
1715  * @dentry: The dentry to delete
1716  *
1717  * Turn the dentry into a negative dentry if possible, otherwise
1718  * remove it from the hash queues so it can be deleted later
1719  */
1720  
1721 void d_delete(struct dentry * dentry)
1722 {
1723         int isdir = 0;
1724         /*
1725          * Are we the only user?
1726          */
1727         spin_lock(&dcache_lock);
1728         spin_lock(&dentry->d_lock);
1729         isdir = S_ISDIR(dentry->d_inode->i_mode);
1730         if (dentry->d_count == 1) {
1731                 dentry->d_flags &= ~DCACHE_CANT_MOUNT;
1732                 dentry_iput(dentry);
1733                 fsnotify_nameremove(dentry, isdir);
1734                 return;
1735         }
1736
1737         if (!d_unhashed(dentry))
1738                 __d_drop(dentry);
1739
1740         spin_unlock(&dentry->d_lock);
1741         spin_unlock(&dcache_lock);
1742
1743         fsnotify_nameremove(dentry, isdir);
1744 }
1745 EXPORT_SYMBOL(d_delete);
1746
1747 static void __d_rehash(struct dentry * entry, struct hlist_head *list)
1748 {
1749
1750         entry->d_flags &= ~DCACHE_UNHASHED;
1751         hlist_add_head_rcu(&entry->d_hash, list);
1752 }
1753
1754 static void _d_rehash(struct dentry * entry)
1755 {
1756         __d_rehash(entry, d_hash(entry->d_parent, entry->d_name.hash));
1757 }
1758
1759 /**
1760  * d_rehash     - add an entry back to the hash
1761  * @entry: dentry to add to the hash
1762  *
1763  * Adds a dentry to the hash according to its name.
1764  */
1765  
1766 void d_rehash(struct dentry * entry)
1767 {
1768         spin_lock(&dcache_lock);
1769         spin_lock(&entry->d_lock);
1770         spin_lock(&dcache_hash_lock);
1771         _d_rehash(entry);
1772         spin_unlock(&dcache_hash_lock);
1773         spin_unlock(&entry->d_lock);
1774         spin_unlock(&dcache_lock);
1775 }
1776 EXPORT_SYMBOL(d_rehash);
1777
1778 /**
1779  * dentry_update_name_case - update case insensitive dentry with a new name
1780  * @dentry: dentry to be updated
1781  * @name: new name
1782  *
1783  * Update a case insensitive dentry with new case of name.
1784  *
1785  * dentry must have been returned by d_lookup with name @name. Old and new
1786  * name lengths must match (ie. no d_compare which allows mismatched name
1787  * lengths).
1788  *
1789  * Parent inode i_mutex must be held over d_lookup and into this call (to
1790  * keep renames and concurrent inserts, and readdir(2) away).
1791  */
1792 void dentry_update_name_case(struct dentry *dentry, struct qstr *name)
1793 {
1794         BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
1795         BUG_ON(dentry->d_name.len != name->len); /* d_lookup gives this */
1796
1797         spin_lock(&dcache_lock);
1798         spin_lock(&dentry->d_lock);
1799         memcpy((unsigned char *)dentry->d_name.name, name->name, name->len);
1800         spin_unlock(&dentry->d_lock);
1801         spin_unlock(&dcache_lock);
1802 }
1803 EXPORT_SYMBOL(dentry_update_name_case);
1804
1805 /*
1806  * When switching names, the actual string doesn't strictly have to
1807  * be preserved in the target - because we're dropping the target
1808  * anyway. As such, we can just do a simple memcpy() to copy over
1809  * the new name before we switch.
1810  *
1811  * Note that we have to be a lot more careful about getting the hash
1812  * switched - we have to switch the hash value properly even if it
1813  * then no longer matches the actual (corrupted) string of the target.
1814  * The hash value has to match the hash queue that the dentry is on..
1815  */
1816 static void switch_names(struct dentry *dentry, struct dentry *target)
1817 {
1818         if (dname_external(target)) {
1819                 if (dname_external(dentry)) {
1820                         /*
1821                          * Both external: swap the pointers
1822                          */
1823                         swap(target->d_name.name, dentry->d_name.name);
1824                 } else {
1825                         /*
1826                          * dentry:internal, target:external.  Steal target's
1827                          * storage and make target internal.
1828                          */
1829                         memcpy(target->d_iname, dentry->d_name.name,
1830                                         dentry->d_name.len + 1);
1831                         dentry->d_name.name = target->d_name.name;
1832                         target->d_name.name = target->d_iname;
1833                 }
1834         } else {
1835                 if (dname_external(dentry)) {
1836                         /*
1837                          * dentry:external, target:internal.  Give dentry's
1838                          * storage to target and make dentry internal
1839                          */
1840                         memcpy(dentry->d_iname, target->d_name.name,
1841                                         target->d_name.len + 1);
1842                         target->d_name.name = dentry->d_name.name;
1843                         dentry->d_name.name = dentry->d_iname;
1844                 } else {
1845                         /*
1846                          * Both are internal.  Just copy target to dentry
1847                          */
1848                         memcpy(dentry->d_iname, target->d_name.name,
1849                                         target->d_name.len + 1);
1850                         dentry->d_name.len = target->d_name.len;
1851                         return;
1852                 }
1853         }
1854         swap(dentry->d_name.len, target->d_name.len);
1855 }
1856
1857 /*
1858  * We cannibalize "target" when moving dentry on top of it,
1859  * because it's going to be thrown away anyway. We could be more
1860  * polite about it, though.
1861  *
1862  * This forceful removal will result in ugly /proc output if
1863  * somebody holds a file open that got deleted due to a rename.
1864  * We could be nicer about the deleted file, and let it show
1865  * up under the name it had before it was deleted rather than
1866  * under the original name of the file that was moved on top of it.
1867  */
1868  
1869 /*
1870  * d_move_locked - move a dentry
1871  * @dentry: entry to move
1872  * @target: new dentry
1873  *
1874  * Update the dcache to reflect the move of a file name. Negative
1875  * dcache entries should not be moved in this way.
1876  */
1877 static void d_move_locked(struct dentry * dentry, struct dentry * target)
1878 {
1879         if (!dentry->d_inode)
1880                 printk(KERN_WARNING "VFS: moving negative dcache entry\n");
1881
1882         write_seqlock(&rename_lock);
1883         /*
1884          * XXXX: do we really need to take target->d_lock?
1885          */
1886         if (d_ancestor(dentry, target)) {
1887                 spin_lock(&dentry->d_lock);
1888                 spin_lock_nested(&target->d_lock, DENTRY_D_LOCK_NESTED);
1889         } else if (d_ancestor(target, dentry) || target < dentry) {
1890                 spin_lock(&target->d_lock);
1891                 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
1892         } else {
1893                 spin_lock(&dentry->d_lock);
1894                 spin_lock_nested(&target->d_lock, DENTRY_D_LOCK_NESTED);
1895         }
1896
1897         /* Move the dentry to the target hash queue, if on different bucket */
1898         spin_lock(&dcache_hash_lock);
1899         if (!d_unhashed(dentry))
1900                 hlist_del_rcu(&dentry->d_hash);
1901         __d_rehash(dentry, d_hash(target->d_parent, target->d_name.hash));
1902         spin_unlock(&dcache_hash_lock);
1903
1904         /* Unhash the target: dput() will then get rid of it */
1905         __d_drop(target);
1906
1907         list_del(&dentry->d_u.d_child);
1908         list_del(&target->d_u.d_child);
1909
1910         /* Switch the names.. */
1911         switch_names(dentry, target);
1912         swap(dentry->d_name.hash, target->d_name.hash);
1913
1914         /* ... and switch the parents */
1915         if (IS_ROOT(dentry)) {
1916                 dentry->d_parent = target->d_parent;
1917                 target->d_parent = target;
1918                 INIT_LIST_HEAD(&target->d_u.d_child);
1919         } else {
1920                 swap(dentry->d_parent, target->d_parent);
1921
1922                 /* And add them back to the (new) parent lists */
1923                 list_add(&target->d_u.d_child, &target->d_parent->d_subdirs);
1924         }
1925
1926         list_add(&dentry->d_u.d_child, &dentry->d_parent->d_subdirs);
1927         spin_unlock(&target->d_lock);
1928         fsnotify_d_move(dentry);
1929         spin_unlock(&dentry->d_lock);
1930         write_sequnlock(&rename_lock);
1931 }
1932
1933 /**
1934  * d_move - move a dentry
1935  * @dentry: entry to move
1936  * @target: new dentry
1937  *
1938  * Update the dcache to reflect the move of a file name. Negative
1939  * dcache entries should not be moved in this way.
1940  */
1941
1942 void d_move(struct dentry * dentry, struct dentry * target)
1943 {
1944         spin_lock(&dcache_lock);
1945         d_move_locked(dentry, target);
1946         spin_unlock(&dcache_lock);
1947 }
1948 EXPORT_SYMBOL(d_move);
1949
1950 /**
1951  * d_ancestor - search for an ancestor
1952  * @p1: ancestor dentry
1953  * @p2: child dentry
1954  *
1955  * Returns the ancestor dentry of p2 which is a child of p1, if p1 is
1956  * an ancestor of p2, else NULL.
1957  */
1958 struct dentry *d_ancestor(struct dentry *p1, struct dentry *p2)
1959 {
1960         struct dentry *p;
1961
1962         for (p = p2; !IS_ROOT(p); p = p->d_parent) {
1963                 if (p->d_parent == p1)
1964                         return p;
1965         }
1966         return NULL;
1967 }
1968
1969 /*
1970  * This helper attempts to cope with remotely renamed directories
1971  *
1972  * It assumes that the caller is already holding
1973  * dentry->d_parent->d_inode->i_mutex and the dcache_lock
1974  *
1975  * Note: If ever the locking in lock_rename() changes, then please
1976  * remember to update this too...
1977  */
1978 static struct dentry *__d_unalias(struct dentry *dentry, struct dentry *alias)
1979         __releases(dcache_lock)
1980 {
1981         struct mutex *m1 = NULL, *m2 = NULL;
1982         struct dentry *ret;
1983
1984         /* If alias and dentry share a parent, then no extra locks required */
1985         if (alias->d_parent == dentry->d_parent)
1986                 goto out_unalias;
1987
1988         /* Check for loops */
1989         ret = ERR_PTR(-ELOOP);
1990         if (d_ancestor(alias, dentry))
1991                 goto out_err;
1992
1993         /* See lock_rename() */
1994         ret = ERR_PTR(-EBUSY);
1995         if (!mutex_trylock(&dentry->d_sb->s_vfs_rename_mutex))
1996                 goto out_err;
1997         m1 = &dentry->d_sb->s_vfs_rename_mutex;
1998         if (!mutex_trylock(&alias->d_parent->d_inode->i_mutex))
1999                 goto out_err;
2000         m2 = &alias->d_parent->d_inode->i_mutex;
2001 out_unalias:
2002         d_move_locked(alias, dentry);
2003         ret = alias;
2004 out_err:
2005         spin_unlock(&dcache_lock);
2006         if (m2)
2007                 mutex_unlock(m2);
2008         if (m1)
2009                 mutex_unlock(m1);
2010         return ret;
2011 }
2012
2013 /*
2014  * Prepare an anonymous dentry for life in the superblock's dentry tree as a
2015  * named dentry in place of the dentry to be replaced.
2016  */
2017 static void __d_materialise_dentry(struct dentry *dentry, struct dentry *anon)
2018 {
2019         struct dentry *dparent, *aparent;
2020
2021         switch_names(dentry, anon);
2022         swap(dentry->d_name.hash, anon->d_name.hash);
2023
2024         dparent = dentry->d_parent;
2025         aparent = anon->d_parent;
2026
2027         dentry->d_parent = (aparent == anon) ? dentry : aparent;
2028         list_del(&dentry->d_u.d_child);
2029         if (!IS_ROOT(dentry))
2030                 list_add(&dentry->d_u.d_child, &dentry->d_parent->d_subdirs);
2031         else
2032                 INIT_LIST_HEAD(&dentry->d_u.d_child);
2033
2034         anon->d_parent = (dparent == dentry) ? anon : dparent;
2035         list_del(&anon->d_u.d_child);
2036         if (!IS_ROOT(anon))
2037                 list_add(&anon->d_u.d_child, &anon->d_parent->d_subdirs);
2038         else
2039                 INIT_LIST_HEAD(&anon->d_u.d_child);
2040
2041         anon->d_flags &= ~DCACHE_DISCONNECTED;
2042 }
2043
2044 /**
2045  * d_materialise_unique - introduce an inode into the tree
2046  * @dentry: candidate dentry
2047  * @inode: inode to bind to the dentry, to which aliases may be attached
2048  *
2049  * Introduces an dentry into the tree, substituting an extant disconnected
2050  * root directory alias in its place if there is one
2051  */
2052 struct dentry *d_materialise_unique(struct dentry *dentry, struct inode *inode)
2053 {
2054         struct dentry *actual;
2055
2056         BUG_ON(!d_unhashed(dentry));
2057
2058         spin_lock(&dcache_lock);
2059
2060         if (!inode) {
2061                 actual = dentry;
2062                 __d_instantiate(dentry, NULL);
2063                 goto found_lock;
2064         }
2065
2066         if (S_ISDIR(inode->i_mode)) {
2067                 struct dentry *alias;
2068
2069                 /* Does an aliased dentry already exist? */
2070                 alias = __d_find_alias(inode, 0);
2071                 if (alias) {
2072                         actual = alias;
2073                         /* Is this an anonymous mountpoint that we could splice
2074                          * into our tree? */
2075                         if (IS_ROOT(alias)) {
2076                                 spin_lock(&alias->d_lock);
2077                                 __d_materialise_dentry(dentry, alias);
2078                                 __d_drop(alias);
2079                                 goto found;
2080                         }
2081                         /* Nope, but we must(!) avoid directory aliasing */
2082                         actual = __d_unalias(dentry, alias);
2083                         if (IS_ERR(actual))
2084                                 dput(alias);
2085                         goto out_nolock;
2086                 }
2087         }
2088
2089         /* Add a unique reference */
2090         actual = __d_instantiate_unique(dentry, inode);
2091         if (!actual)
2092                 actual = dentry;
2093         else if (unlikely(!d_unhashed(actual)))
2094                 goto shouldnt_be_hashed;
2095
2096 found_lock:
2097         spin_lock(&actual->d_lock);
2098 found:
2099         spin_lock(&dcache_hash_lock);
2100         _d_rehash(actual);
2101         spin_unlock(&dcache_hash_lock);
2102         spin_unlock(&actual->d_lock);
2103         spin_unlock(&dcache_lock);
2104 out_nolock:
2105         if (actual == dentry) {
2106                 security_d_instantiate(dentry, inode);
2107                 return NULL;
2108         }
2109
2110         iput(inode);
2111         return actual;
2112
2113 shouldnt_be_hashed:
2114         spin_unlock(&dcache_lock);
2115         BUG();
2116 }
2117 EXPORT_SYMBOL_GPL(d_materialise_unique);
2118
2119 static int prepend(char **buffer, int *buflen, const char *str, int namelen)
2120 {
2121         *buflen -= namelen;
2122         if (*buflen < 0)
2123                 return -ENAMETOOLONG;
2124         *buffer -= namelen;
2125         memcpy(*buffer, str, namelen);
2126         return 0;
2127 }
2128
2129 static int prepend_name(char **buffer, int *buflen, struct qstr *name)
2130 {
2131         return prepend(buffer, buflen, name->name, name->len);
2132 }
2133
2134 /**
2135  * Prepend path string to a buffer
2136  *
2137  * @path: the dentry/vfsmount to report
2138  * @root: root vfsmnt/dentry (may be modified by this function)
2139  * @buffer: pointer to the end of the buffer
2140  * @buflen: pointer to buffer length
2141  *
2142  * Caller holds the dcache_lock.
2143  *
2144  * If path is not reachable from the supplied root, then the value of
2145  * root is changed (without modifying refcounts).
2146  */
2147 static int prepend_path(const struct path *path, struct path *root,
2148                         char **buffer, int *buflen)
2149 {
2150         struct dentry *dentry = path->dentry;
2151         struct vfsmount *vfsmnt = path->mnt;
2152         bool slash = false;
2153         int error = 0;
2154
2155         br_read_lock(vfsmount_lock);
2156         while (dentry != root->dentry || vfsmnt != root->mnt) {
2157                 struct dentry * parent;
2158
2159                 if (dentry == vfsmnt->mnt_root || IS_ROOT(dentry)) {
2160                         /* Global root? */
2161                         if (vfsmnt->mnt_parent == vfsmnt) {
2162                                 goto global_root;
2163                         }
2164                         dentry = vfsmnt->mnt_mountpoint;
2165                         vfsmnt = vfsmnt->mnt_parent;
2166                         continue;
2167                 }
2168                 parent = dentry->d_parent;
2169                 prefetch(parent);
2170                 error = prepend_name(buffer, buflen, &dentry->d_name);
2171                 if (!error)
2172                         error = prepend(buffer, buflen, "/", 1);
2173                 if (error)
2174                         break;
2175
2176                 slash = true;
2177                 dentry = parent;
2178         }
2179
2180 out:
2181         if (!error && !slash)
2182                 error = prepend(buffer, buflen, "/", 1);
2183
2184         br_read_unlock(vfsmount_lock);
2185         return error;
2186
2187 global_root:
2188         /*
2189          * Filesystems needing to implement special "root names"
2190          * should do so with ->d_dname()
2191          */
2192         if (IS_ROOT(dentry) &&
2193             (dentry->d_name.len != 1 || dentry->d_name.name[0] != '/')) {
2194                 WARN(1, "Root dentry has weird name <%.*s>\n",
2195                      (int) dentry->d_name.len, dentry->d_name.name);
2196         }
2197         root->mnt = vfsmnt;
2198         root->dentry = dentry;
2199         goto out;
2200 }
2201
2202 /**
2203  * __d_path - return the path of a dentry
2204  * @path: the dentry/vfsmount to report
2205  * @root: root vfsmnt/dentry (may be modified by this function)
2206  * @buf: buffer to return value in
2207  * @buflen: buffer length
2208  *
2209  * Convert a dentry into an ASCII path name.
2210  *
2211  * Returns a pointer into the buffer or an error code if the
2212  * path was too long.
2213  *
2214  * "buflen" should be positive.
2215  *
2216  * If path is not reachable from the supplied root, then the value of
2217  * root is changed (without modifying refcounts).
2218  */
2219 char *__d_path(const struct path *path, struct path *root,
2220                char *buf, int buflen)
2221 {
2222         char *res = buf + buflen;
2223         int error;
2224
2225         prepend(&res, &buflen, "\0", 1);
2226         spin_lock(&dcache_lock);
2227         error = prepend_path(path, root, &res, &buflen);
2228         spin_unlock(&dcache_lock);
2229
2230         if (error)
2231                 return ERR_PTR(error);
2232         return res;
2233 }
2234
2235 /*
2236  * same as __d_path but appends "(deleted)" for unlinked files.
2237  */
2238 static int path_with_deleted(const struct path *path, struct path *root,
2239                                  char **buf, int *buflen)
2240 {
2241         prepend(buf, buflen, "\0", 1);
2242         if (d_unlinked(path->dentry)) {
2243                 int error = prepend(buf, buflen, " (deleted)", 10);
2244                 if (error)
2245                         return error;
2246         }
2247
2248         return prepend_path(path, root, buf, buflen);
2249 }
2250
2251 static int prepend_unreachable(char **buffer, int *buflen)
2252 {
2253         return prepend(buffer, buflen, "(unreachable)", 13);
2254 }
2255
2256 /**
2257  * d_path - return the path of a dentry
2258  * @path: path to report
2259  * @buf: buffer to return value in
2260  * @buflen: buffer length
2261  *
2262  * Convert a dentry into an ASCII path name. If the entry has been deleted
2263  * the string " (deleted)" is appended. Note that this is ambiguous.
2264  *
2265  * Returns a pointer into the buffer or an error code if the path was
2266  * too long. Note: Callers should use the returned pointer, not the passed
2267  * in buffer, to use the name! The implementation often starts at an offset
2268  * into the buffer, and may leave 0 bytes at the start.
2269  *
2270  * "buflen" should be positive.
2271  */
2272 char *d_path(const struct path *path, char *buf, int buflen)
2273 {
2274         char *res = buf + buflen;
2275         struct path root;
2276         struct path tmp;
2277         int error;
2278
2279         /*
2280          * We have various synthetic filesystems that never get mounted.  On
2281          * these filesystems dentries are never used for lookup purposes, and
2282          * thus don't need to be hashed.  They also don't need a name until a
2283          * user wants to identify the object in /proc/pid/fd/.  The little hack
2284          * below allows us to generate a name for these objects on demand:
2285          */
2286         if (path->dentry->d_op && path->dentry->d_op->d_dname)
2287                 return path->dentry->d_op->d_dname(path->dentry, buf, buflen);
2288
2289         get_fs_root(current->fs, &root);
2290         spin_lock(&dcache_lock);
2291         tmp = root;
2292         error = path_with_deleted(path, &tmp, &res, &buflen);
2293         if (error)
2294                 res = ERR_PTR(error);
2295         spin_unlock(&dcache_lock);
2296         path_put(&root);
2297         return res;
2298 }
2299 EXPORT_SYMBOL(d_path);
2300
2301 /**
2302  * d_path_with_unreachable - return the path of a dentry
2303  * @path: path to report
2304  * @buf: buffer to return value in
2305  * @buflen: buffer length
2306  *
2307  * The difference from d_path() is that this prepends "(unreachable)"
2308  * to paths which are unreachable from the current process' root.
2309  */
2310 char *d_path_with_unreachable(const struct path *path, char *buf, int buflen)
2311 {
2312         char *res = buf + buflen;
2313         struct path root;
2314         struct path tmp;
2315         int error;
2316
2317         if (path->dentry->d_op && path->dentry->d_op->d_dname)
2318                 return path->dentry->d_op->d_dname(path->dentry, buf, buflen);
2319
2320         get_fs_root(current->fs, &root);
2321         spin_lock(&dcache_lock);
2322         tmp = root;
2323         error = path_with_deleted(path, &tmp, &res, &buflen);
2324         if (!error && !path_equal(&tmp, &root))
2325                 error = prepend_unreachable(&res, &buflen);
2326         spin_unlock(&dcache_lock);
2327         path_put(&root);
2328         if (error)
2329                 res =  ERR_PTR(error);
2330
2331         return res;
2332 }
2333
2334 /*
2335  * Helper function for dentry_operations.d_dname() members
2336  */
2337 char *dynamic_dname(struct dentry *dentry, char *buffer, int buflen,
2338                         const char *fmt, ...)
2339 {
2340         va_list args;
2341         char temp[64];
2342         int sz;
2343
2344         va_start(args, fmt);
2345         sz = vsnprintf(temp, sizeof(temp), fmt, args) + 1;
2346         va_end(args);
2347
2348         if (sz > sizeof(temp) || sz > buflen)
2349                 return ERR_PTR(-ENAMETOOLONG);
2350
2351         buffer += buflen - sz;
2352         return memcpy(buffer, temp, sz);
2353 }
2354
2355 /*
2356  * Write full pathname from the root of the filesystem into the buffer.
2357  */
2358 static char *__dentry_path(struct dentry *dentry, char *buf, int buflen)
2359 {
2360         char *end = buf + buflen;
2361         char *retval;
2362
2363         prepend(&end, &buflen, "\0", 1);
2364         if (buflen < 1)
2365                 goto Elong;
2366         /* Get '/' right */
2367         retval = end-1;
2368         *retval = '/';
2369
2370         while (!IS_ROOT(dentry)) {
2371                 struct dentry *parent = dentry->d_parent;
2372
2373                 prefetch(parent);
2374                 if ((prepend_name(&end, &buflen, &dentry->d_name) != 0) ||
2375                     (prepend(&end, &buflen, "/", 1) != 0))
2376                         goto Elong;
2377
2378                 retval = end;
2379                 dentry = parent;
2380         }
2381         return retval;
2382 Elong:
2383         return ERR_PTR(-ENAMETOOLONG);
2384 }
2385
2386 char *dentry_path_raw(struct dentry *dentry, char *buf, int buflen)
2387 {
2388         char *retval;
2389
2390         spin_lock(&dcache_lock);
2391         retval = __dentry_path(dentry, buf, buflen);
2392         spin_unlock(&dcache_lock);
2393
2394         return retval;
2395 }
2396 EXPORT_SYMBOL(dentry_path_raw);
2397
2398 char *dentry_path(struct dentry *dentry, char *buf, int buflen)
2399 {
2400         char *p = NULL;
2401         char *retval;
2402
2403         spin_lock(&dcache_lock);
2404         if (d_unlinked(dentry)) {
2405                 p = buf + buflen;
2406                 if (prepend(&p, &buflen, "//deleted", 10) != 0)
2407                         goto Elong;
2408                 buflen++;
2409         }
2410         retval = __dentry_path(dentry, buf, buflen);
2411         spin_unlock(&dcache_lock);
2412         if (!IS_ERR(retval) && p)
2413                 *p = '/';       /* restore '/' overriden with '\0' */
2414         return retval;
2415 Elong:
2416         spin_unlock(&dcache_lock);
2417         return ERR_PTR(-ENAMETOOLONG);
2418 }
2419
2420 /*
2421  * NOTE! The user-level library version returns a
2422  * character pointer. The kernel system call just
2423  * returns the length of the buffer filled (which
2424  * includes the ending '\0' character), or a negative
2425  * error value. So libc would do something like
2426  *
2427  *      char *getcwd(char * buf, size_t size)
2428  *      {
2429  *              int retval;
2430  *
2431  *              retval = sys_getcwd(buf, size);
2432  *              if (retval >= 0)
2433  *                      return buf;
2434  *              errno = -retval;
2435  *              return NULL;
2436  *      }
2437  */
2438 SYSCALL_DEFINE2(getcwd, char __user *, buf, unsigned long, size)
2439 {
2440         int error;
2441         struct path pwd, root;
2442         char *page = (char *) __get_free_page(GFP_USER);
2443
2444         if (!page)
2445                 return -ENOMEM;
2446
2447         get_fs_root_and_pwd(current->fs, &root, &pwd);
2448
2449         error = -ENOENT;
2450         spin_lock(&dcache_lock);
2451         if (!d_unlinked(pwd.dentry)) {
2452                 unsigned long len;
2453                 struct path tmp = root;
2454                 char *cwd = page + PAGE_SIZE;
2455                 int buflen = PAGE_SIZE;
2456
2457                 prepend(&cwd, &buflen, "\0", 1);
2458                 error = prepend_path(&pwd, &tmp, &cwd, &buflen);
2459                 spin_unlock(&dcache_lock);
2460
2461                 if (error)
2462                         goto out;
2463
2464                 /* Unreachable from current root */
2465                 if (!path_equal(&tmp, &root)) {
2466                         error = prepend_unreachable(&cwd, &buflen);
2467                         if (error)
2468                                 goto out;
2469                 }
2470
2471                 error = -ERANGE;
2472                 len = PAGE_SIZE + page - cwd;
2473                 if (len <= size) {
2474                         error = len;
2475                         if (copy_to_user(buf, cwd, len))
2476                                 error = -EFAULT;
2477                 }
2478         } else
2479                 spin_unlock(&dcache_lock);
2480
2481 out:
2482         path_put(&pwd);
2483         path_put(&root);
2484         free_page((unsigned long) page);
2485         return error;
2486 }
2487
2488 /*
2489  * Test whether new_dentry is a subdirectory of old_dentry.
2490  *
2491  * Trivially implemented using the dcache structure
2492  */
2493
2494 /**
2495  * is_subdir - is new dentry a subdirectory of old_dentry
2496  * @new_dentry: new dentry
2497  * @old_dentry: old dentry
2498  *
2499  * Returns 1 if new_dentry is a subdirectory of the parent (at any depth).
2500  * Returns 0 otherwise.
2501  * Caller must ensure that "new_dentry" is pinned before calling is_subdir()
2502  */
2503   
2504 int is_subdir(struct dentry *new_dentry, struct dentry *old_dentry)
2505 {
2506         int result;
2507         unsigned long seq;
2508
2509         if (new_dentry == old_dentry)
2510                 return 1;
2511
2512         /*
2513          * Need rcu_readlock to protect against the d_parent trashing
2514          * due to d_move
2515          */
2516         rcu_read_lock();
2517         do {
2518                 /* for restarting inner loop in case of seq retry */
2519                 seq = read_seqbegin(&rename_lock);
2520                 if (d_ancestor(old_dentry, new_dentry))
2521                         result = 1;
2522                 else
2523                         result = 0;
2524         } while (read_seqretry(&rename_lock, seq));
2525         rcu_read_unlock();
2526
2527         return result;
2528 }
2529
2530 int path_is_under(struct path *path1, struct path *path2)
2531 {
2532         struct vfsmount *mnt = path1->mnt;
2533         struct dentry *dentry = path1->dentry;
2534         int res;
2535
2536         br_read_lock(vfsmount_lock);
2537         if (mnt != path2->mnt) {
2538                 for (;;) {
2539                         if (mnt->mnt_parent == mnt) {
2540                                 br_read_unlock(vfsmount_lock);
2541                                 return 0;
2542                         }
2543                         if (mnt->mnt_parent == path2->mnt)
2544                                 break;
2545                         mnt = mnt->mnt_parent;
2546                 }
2547                 dentry = mnt->mnt_mountpoint;
2548         }
2549         res = is_subdir(dentry, path2->dentry);
2550         br_read_unlock(vfsmount_lock);
2551         return res;
2552 }
2553 EXPORT_SYMBOL(path_is_under);
2554
2555 void d_genocide(struct dentry *root)
2556 {
2557         struct dentry *this_parent = root;
2558         struct list_head *next;
2559
2560         spin_lock(&dcache_lock);
2561 repeat:
2562         next = this_parent->d_subdirs.next;
2563 resume:
2564         while (next != &this_parent->d_subdirs) {
2565                 struct list_head *tmp = next;
2566                 struct dentry *dentry = list_entry(tmp, struct dentry, d_u.d_child);
2567                 next = tmp->next;
2568                 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
2569                 if (d_unhashed(dentry) || !dentry->d_inode) {
2570                         spin_unlock(&dentry->d_lock);
2571                         continue;
2572                 }
2573                 if (!list_empty(&dentry->d_subdirs)) {
2574                         spin_unlock(&dentry->d_lock);
2575                         this_parent = dentry;
2576                         goto repeat;
2577                 }
2578                 dentry->d_count--;
2579                 spin_unlock(&dentry->d_lock);
2580         }
2581         if (this_parent != root) {
2582                 next = this_parent->d_u.d_child.next;
2583                 spin_lock(&this_parent->d_lock);
2584                 this_parent->d_count--;
2585                 spin_unlock(&this_parent->d_lock);
2586                 this_parent = this_parent->d_parent;
2587                 goto resume;
2588         }
2589         spin_unlock(&dcache_lock);
2590 }
2591
2592 /**
2593  * find_inode_number - check for dentry with name
2594  * @dir: directory to check
2595  * @name: Name to find.
2596  *
2597  * Check whether a dentry already exists for the given name,
2598  * and return the inode number if it has an inode. Otherwise
2599  * 0 is returned.
2600  *
2601  * This routine is used to post-process directory listings for
2602  * filesystems using synthetic inode numbers, and is necessary
2603  * to keep getcwd() working.
2604  */
2605  
2606 ino_t find_inode_number(struct dentry *dir, struct qstr *name)
2607 {
2608         struct dentry * dentry;
2609         ino_t ino = 0;
2610
2611         dentry = d_hash_and_lookup(dir, name);
2612         if (dentry) {
2613                 if (dentry->d_inode)
2614                         ino = dentry->d_inode->i_ino;
2615                 dput(dentry);
2616         }
2617         return ino;
2618 }
2619 EXPORT_SYMBOL(find_inode_number);
2620
2621 static __initdata unsigned long dhash_entries;
2622 static int __init set_dhash_entries(char *str)
2623 {
2624         if (!str)
2625                 return 0;
2626         dhash_entries = simple_strtoul(str, &str, 0);
2627         return 1;
2628 }
2629 __setup("dhash_entries=", set_dhash_entries);
2630
2631 static void __init dcache_init_early(void)
2632 {
2633         int loop;
2634
2635         /* If hashes are distributed across NUMA nodes, defer
2636          * hash allocation until vmalloc space is available.
2637          */
2638         if (hashdist)
2639                 return;
2640
2641         dentry_hashtable =
2642                 alloc_large_system_hash("Dentry cache",
2643                                         sizeof(struct hlist_head),
2644                                         dhash_entries,
2645                                         13,
2646                                         HASH_EARLY,
2647                                         &d_hash_shift,
2648                                         &d_hash_mask,
2649                                         0);
2650
2651         for (loop = 0; loop < (1 << d_hash_shift); loop++)
2652                 INIT_HLIST_HEAD(&dentry_hashtable[loop]);
2653 }
2654
2655 static void __init dcache_init(void)
2656 {
2657         int loop;
2658
2659         /* 
2660          * A constructor could be added for stable state like the lists,
2661          * but it is probably not worth it because of the cache nature
2662          * of the dcache. 
2663          */
2664         dentry_cache = KMEM_CACHE(dentry,
2665                 SLAB_RECLAIM_ACCOUNT|SLAB_PANIC|SLAB_MEM_SPREAD);
2666         
2667         register_shrinker(&dcache_shrinker);
2668
2669         /* Hash may have been set up in dcache_init_early */
2670         if (!hashdist)
2671                 return;
2672
2673         dentry_hashtable =
2674                 alloc_large_system_hash("Dentry cache",
2675                                         sizeof(struct hlist_head),
2676                                         dhash_entries,
2677                                         13,
2678                                         0,
2679                                         &d_hash_shift,
2680                                         &d_hash_mask,
2681                                         0);
2682
2683         for (loop = 0; loop < (1 << d_hash_shift); loop++)
2684                 INIT_HLIST_HEAD(&dentry_hashtable[loop]);
2685 }
2686
2687 /* SLAB cache for __getname() consumers */
2688 struct kmem_cache *names_cachep __read_mostly;
2689 EXPORT_SYMBOL(names_cachep);
2690
2691 EXPORT_SYMBOL(d_genocide);
2692
2693 void __init vfs_caches_init_early(void)
2694 {
2695         dcache_init_early();
2696         inode_init_early();
2697 }
2698
2699 void __init vfs_caches_init(unsigned long mempages)
2700 {
2701         unsigned long reserve;
2702
2703         /* Base hash sizes on available memory, with a reserve equal to
2704            150% of current kernel size */
2705
2706         reserve = min((mempages - nr_free_pages()) * 3/2, mempages - 1);
2707         mempages -= reserve;
2708
2709         names_cachep = kmem_cache_create("names_cache", PATH_MAX, 0,
2710                         SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
2711
2712         dcache_init();
2713         inode_init();
2714         files_init(mempages);
2715         mnt_init();
2716         bdev_cache_init();
2717         chrdev_init();
2718 }