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