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