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