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