xref: /linux/fs/dcache.c (revision 87e801e1678342fc23b1eb92c0eecedf5dca79cb)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * fs/dcache.c
4  *
5  * Complete reimplementation
6  * (C) 1997 Thomas Schoebel-Theuer,
7  * with heavy changes by Linus Torvalds
8  */
9 
10 /*
11  * Notes on the allocation strategy:
12  *
13  * The dcache is a master of the icache - whenever a dcache entry
14  * exists, the inode will always exist. "iput()" is done either when
15  * the dcache entry is deleted or garbage collected.
16  */
17 
18 #include <linux/ratelimit.h>
19 #include <linux/string.h>
20 #include <linux/mm.h>
21 #include <linux/fs.h>
22 #include <linux/fscrypt.h>
23 #include <linux/fsnotify.h>
24 #include <linux/slab.h>
25 #include <linux/init.h>
26 #include <linux/hash.h>
27 #include <linux/cache.h>
28 #include <linux/export.h>
29 #include <linux/security.h>
30 #include <linux/seqlock.h>
31 #include <linux/memblock.h>
32 #include <linux/bit_spinlock.h>
33 #include <linux/rculist_bl.h>
34 #include <linux/list_lru.h>
35 #include "internal.h"
36 #include "mount.h"
37 
38 #include <asm/runtime-const.h>
39 
40 /*
41  * Usage:
42  * dcache->d_inode->i_lock protects:
43  *   - i_dentry, d_alias, d_inode of aliases
44  * dcache_hash_bucket lock protects:
45  *   - the dcache hash table
46  * s_roots bl list spinlock protects:
47  *   - the s_roots list (see __d_drop)
48  * dentry->d_sb->s_dentry_lru_lock protects:
49  *   - the dcache lru lists and counters
50  * d_lock protects:
51  *   - d_flags
52  *   - d_name
53  *   - d_lru
54  *   - d_count
55  *   - d_unhashed()
56  *   - d_parent and d_chilren
57  *   - childrens' d_sib and d_parent
58  *   - d_alias, d_inode
59  *
60  * Ordering:
61  * dentry->d_inode->i_lock
62  *   dentry->d_lock
63  *     dentry->d_sb->s_dentry_lru_lock
64  *     dcache_hash_bucket lock
65  *     s_roots lock
66  *
67  * If there is an ancestor relationship:
68  * dentry->d_parent->...->d_parent->d_lock
69  *   ...
70  *     dentry->d_parent->d_lock
71  *       dentry->d_lock
72  *
73  * If no ancestor relationship:
74  * arbitrary, since it's serialized on rename_lock
75  */
76 static int sysctl_vfs_cache_pressure __read_mostly = 100;
77 static int sysctl_vfs_cache_pressure_denom __read_mostly = 100;
78 
79 unsigned long vfs_pressure_ratio(unsigned long val)
80 {
81 	return mult_frac(val, sysctl_vfs_cache_pressure, sysctl_vfs_cache_pressure_denom);
82 }
83 EXPORT_SYMBOL_GPL(vfs_pressure_ratio);
84 
85 __cacheline_aligned_in_smp DEFINE_SEQLOCK(rename_lock);
86 
87 EXPORT_SYMBOL(rename_lock);
88 
89 static struct kmem_cache *__dentry_cache __ro_after_init;
90 #define dentry_cache runtime_const_ptr(__dentry_cache)
91 
92 const struct qstr empty_name = QSTR_INIT("", 0);
93 EXPORT_SYMBOL(empty_name);
94 const struct qstr slash_name = QSTR_INIT("/", 1);
95 EXPORT_SYMBOL(slash_name);
96 const struct qstr dotdot_name = QSTR_INIT("..", 2);
97 EXPORT_SYMBOL(dotdot_name);
98 
99 /*
100  * This is the single most critical data structure when it comes
101  * to the dcache: the hashtable for lookups. Somebody should try
102  * to make this good - I've just made it work.
103  *
104  * This hash-function tries to avoid losing too many bits of hash
105  * information, yet avoid using a prime hash-size or similar.
106  *
107  * Marking the variables "used" ensures that the compiler doesn't
108  * optimize them away completely on architectures with runtime
109  * constant infrastructure, this allows debuggers to see their
110  * values. But updating these values has no effect on those arches.
111  */
112 
113 static unsigned int d_hash_shift __ro_after_init __used;
114 
115 static struct hlist_bl_head *dentry_hashtable __ro_after_init __used;
116 
117 static inline struct hlist_bl_head *d_hash(unsigned long hashlen)
118 {
119 	return runtime_const_ptr(dentry_hashtable) +
120 		runtime_const_shift_right_32(hashlen, d_hash_shift);
121 }
122 
123 #define IN_LOOKUP_SHIFT 10
124 static struct hlist_bl_head in_lookup_hashtable[1 << IN_LOOKUP_SHIFT];
125 
126 static inline struct hlist_bl_head *in_lookup_hash(const struct dentry *parent,
127 					unsigned int hash)
128 {
129 	hash += (unsigned long) parent / L1_CACHE_BYTES;
130 	return in_lookup_hashtable + hash_32(hash, IN_LOOKUP_SHIFT);
131 }
132 
133 struct dentry_stat_t {
134 	long nr_dentry;
135 	long nr_unused;
136 	long age_limit;		/* age in seconds */
137 	long want_pages;	/* pages requested by system */
138 	long nr_negative;	/* # of unused negative dentries */
139 	long dummy;		/* Reserved for future use */
140 };
141 
142 static DEFINE_PER_CPU(long, nr_dentry);
143 static DEFINE_PER_CPU(long, nr_dentry_unused);
144 static DEFINE_PER_CPU(long, nr_dentry_negative);
145 static int dentry_negative_policy;
146 
147 #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS)
148 /* Statistics gathering. */
149 static struct dentry_stat_t dentry_stat = {
150 	.age_limit = 45,
151 };
152 
153 /*
154  * Here we resort to our own counters instead of using generic per-cpu counters
155  * for consistency with what the vfs inode code does. We are expected to harvest
156  * better code and performance by having our own specialized counters.
157  *
158  * Please note that the loop is done over all possible CPUs, not over all online
159  * CPUs. The reason for this is that we don't want to play games with CPUs going
160  * on and off. If one of them goes off, we will just keep their counters.
161  *
162  * glommer: See cffbc8a for details, and if you ever intend to change this,
163  * please update all vfs counters to match.
164  */
165 static long get_nr_dentry(void)
166 {
167 	int i;
168 	long sum = 0;
169 	for_each_possible_cpu(i)
170 		sum += per_cpu(nr_dentry, i);
171 	return sum < 0 ? 0 : sum;
172 }
173 
174 static long get_nr_dentry_unused(void)
175 {
176 	int i;
177 	long sum = 0;
178 	for_each_possible_cpu(i)
179 		sum += per_cpu(nr_dentry_unused, i);
180 	return sum < 0 ? 0 : sum;
181 }
182 
183 static long get_nr_dentry_negative(void)
184 {
185 	int i;
186 	long sum = 0;
187 
188 	for_each_possible_cpu(i)
189 		sum += per_cpu(nr_dentry_negative, i);
190 	return sum < 0 ? 0 : sum;
191 }
192 
193 static int proc_nr_dentry(const struct ctl_table *table, int write, void *buffer,
194 			  size_t *lenp, loff_t *ppos)
195 {
196 	dentry_stat.nr_dentry = get_nr_dentry();
197 	dentry_stat.nr_unused = get_nr_dentry_unused();
198 	dentry_stat.nr_negative = get_nr_dentry_negative();
199 	return proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
200 }
201 
202 static const struct ctl_table fs_dcache_sysctls[] = {
203 	{
204 		.procname	= "dentry-state",
205 		.data		= &dentry_stat,
206 		.maxlen		= 6*sizeof(long),
207 		.mode		= 0444,
208 		.proc_handler	= proc_nr_dentry,
209 	},
210 	{
211 		.procname	= "dentry-negative",
212 		.data		= &dentry_negative_policy,
213 		.maxlen		= sizeof(dentry_negative_policy),
214 		.mode		= 0644,
215 		.proc_handler	= proc_dointvec_minmax,
216 		.extra1		= SYSCTL_ZERO,
217 		.extra2		= SYSCTL_ONE,
218 	},
219 };
220 
221 static const struct ctl_table vm_dcache_sysctls[] = {
222 	{
223 		.procname	= "vfs_cache_pressure",
224 		.data		= &sysctl_vfs_cache_pressure,
225 		.maxlen		= sizeof(sysctl_vfs_cache_pressure),
226 		.mode		= 0644,
227 		.proc_handler	= proc_dointvec_minmax,
228 		.extra1		= SYSCTL_ZERO,
229 	},
230 	{
231 		.procname	= "vfs_cache_pressure_denom",
232 		.data		= &sysctl_vfs_cache_pressure_denom,
233 		.maxlen		= sizeof(sysctl_vfs_cache_pressure_denom),
234 		.mode		= 0644,
235 		.proc_handler	= proc_dointvec_minmax,
236 		.extra1		= SYSCTL_ONE_HUNDRED,
237 	},
238 };
239 
240 static int __init init_fs_dcache_sysctls(void)
241 {
242 	register_sysctl_init("vm", vm_dcache_sysctls);
243 	register_sysctl_init("fs", fs_dcache_sysctls);
244 	return 0;
245 }
246 fs_initcall(init_fs_dcache_sysctls);
247 #endif
248 
249 /*
250  * Compare 2 name strings, return 0 if they match, otherwise non-zero.
251  * The strings are both count bytes long, and count is non-zero.
252  */
253 #ifdef CONFIG_DCACHE_WORD_ACCESS
254 
255 #include <asm/word-at-a-time.h>
256 /*
257  * NOTE! 'cs' and 'scount' come from a dentry, so it has a
258  * aligned allocation for this particular component. We don't
259  * strictly need the load_unaligned_zeropad() safety, but it
260  * doesn't hurt either.
261  *
262  * In contrast, 'ct' and 'tcount' can be from a pathname, and do
263  * need the careful unaligned handling.
264  */
265 static inline int dentry_string_cmp(const unsigned char *cs, const unsigned char *ct, unsigned tcount)
266 {
267 	unsigned long a,b,mask;
268 
269 	for (;;) {
270 		a = read_word_at_a_time(cs);
271 		b = load_unaligned_zeropad(ct);
272 		if (tcount < sizeof(unsigned long))
273 			break;
274 		if (unlikely(a != b))
275 			return 1;
276 		cs += sizeof(unsigned long);
277 		ct += sizeof(unsigned long);
278 		tcount -= sizeof(unsigned long);
279 		if (!tcount)
280 			return 0;
281 	}
282 	mask = bytemask_from_count(tcount);
283 	return unlikely(!!((a ^ b) & mask));
284 }
285 
286 #else
287 
288 static inline int dentry_string_cmp(const unsigned char *cs, const unsigned char *ct, unsigned tcount)
289 {
290 	do {
291 		if (*cs != *ct)
292 			return 1;
293 		cs++;
294 		ct++;
295 		tcount--;
296 	} while (tcount);
297 	return 0;
298 }
299 
300 #endif
301 
302 static inline int dentry_cmp(const struct dentry *dentry, const unsigned char *ct, unsigned tcount)
303 {
304 	/*
305 	 * Be careful about RCU walk racing with rename:
306 	 * use 'READ_ONCE' to fetch the name pointer.
307 	 *
308 	 * NOTE! Even if a rename will mean that the length
309 	 * was not loaded atomically, we don't care. The
310 	 * RCU walk will check the sequence count eventually,
311 	 * and catch it. And we won't overrun the buffer,
312 	 * because we're reading the name pointer atomically,
313 	 * and a dentry name is guaranteed to be properly
314 	 * terminated with a NUL byte.
315 	 *
316 	 * End result: even if 'len' is wrong, we'll exit
317 	 * early because the data cannot match (there can
318 	 * be no NUL in the ct/tcount data)
319 	 */
320 	const unsigned char *cs = READ_ONCE(dentry->d_name.name);
321 
322 	return dentry_string_cmp(cs, ct, tcount);
323 }
324 
325 /*
326  * long names are allocated separately from dentry and never modified.
327  * Refcounted, freeing is RCU-delayed.  See take_dentry_name_snapshot()
328  * for the reason why ->count and ->head can't be combined into a union.
329  * dentry_string_cmp() relies upon ->name[] being word-aligned.
330  */
331 struct external_name {
332 	atomic_t count;
333 	struct rcu_head head;
334 	unsigned char name[] __aligned(sizeof(unsigned long));
335 };
336 
337 static inline struct external_name *external_name(struct dentry *dentry)
338 {
339 	return container_of(dentry->d_name.name, struct external_name, name[0]);
340 }
341 
342 static void __d_free(struct rcu_head *head)
343 {
344 	struct dentry *dentry = container_of(head, struct dentry, d_rcu);
345 
346 	kmem_cache_free(dentry_cache, dentry);
347 }
348 
349 static void __d_free_external(struct rcu_head *head)
350 {
351 	struct dentry *dentry = container_of(head, struct dentry, d_rcu);
352 	kfree(external_name(dentry));
353 	kmem_cache_free(dentry_cache, dentry);
354 }
355 
356 static inline int dname_external(const struct dentry *dentry)
357 {
358 	return dentry->d_name.name != dentry->d_shortname.string;
359 }
360 
361 void take_dentry_name_snapshot(struct name_snapshot *name, struct dentry *dentry)
362 {
363 	unsigned seq;
364 	const unsigned char *s;
365 
366 	rcu_read_lock();
367 retry:
368 	seq = read_seqcount_begin(&dentry->d_seq);
369 	s = READ_ONCE(dentry->d_name.name);
370 	name->name.hash_len = dentry->d_name.hash_len;
371 	name->name.name = name->inline_name.string;
372 	if (likely(s == dentry->d_shortname.string)) {
373 		name->inline_name = dentry->d_shortname;
374 	} else {
375 		struct external_name *p;
376 		p = container_of(s, struct external_name, name[0]);
377 		// get a valid reference
378 		if (unlikely(!atomic_inc_not_zero(&p->count)))
379 			goto retry;
380 		name->name.name = s;
381 	}
382 	if (read_seqcount_retry(&dentry->d_seq, seq)) {
383 		release_dentry_name_snapshot(name);
384 		goto retry;
385 	}
386 	rcu_read_unlock();
387 }
388 EXPORT_SYMBOL(take_dentry_name_snapshot);
389 
390 void release_dentry_name_snapshot(struct name_snapshot *name)
391 {
392 	if (unlikely(name->name.name != name->inline_name.string)) {
393 		struct external_name *p;
394 		p = container_of(name->name.name, struct external_name, name[0]);
395 		if (unlikely(atomic_dec_and_test(&p->count)))
396 			kfree_rcu(p, head);
397 	}
398 }
399 EXPORT_SYMBOL(release_dentry_name_snapshot);
400 
401 static inline void __d_set_inode_and_type(struct dentry *dentry,
402 					  struct inode *inode,
403 					  unsigned type_flags)
404 {
405 	unsigned flags;
406 
407 	dentry->d_inode = inode;
408 	flags = READ_ONCE(dentry->d_flags);
409 	flags &= ~DCACHE_ENTRY_TYPE;
410 	flags |= type_flags;
411 	smp_store_release(&dentry->d_flags, flags);
412 }
413 
414 static inline void __d_clear_type_and_inode(struct dentry *dentry)
415 {
416 	unsigned flags = READ_ONCE(dentry->d_flags);
417 
418 	flags &= ~DCACHE_ENTRY_TYPE;
419 	WRITE_ONCE(dentry->d_flags, flags);
420 	dentry->d_inode = NULL;
421 	/*
422 	 * The negative counter only tracks dentries on the LRU. Don't inc if
423 	 * d_lru is on another list.
424 	 */
425 	if ((flags & (DCACHE_LRU_LIST|DCACHE_SHRINK_LIST)) == DCACHE_LRU_LIST)
426 		this_cpu_inc(nr_dentry_negative);
427 }
428 
429 static void dentry_free(struct dentry *dentry)
430 {
431 	WARN_ON(d_really_is_positive(dentry));
432 	if (unlikely(dname_external(dentry))) {
433 		struct external_name *p = external_name(dentry);
434 		if (likely(atomic_dec_and_test(&p->count))) {
435 			call_rcu(&dentry->d_rcu, __d_free_external);
436 			return;
437 		}
438 	}
439 	/* if dentry was never visible to RCU, immediate free is OK */
440 	if (dentry->d_flags & DCACHE_NORCU)
441 		__d_free(&dentry->d_rcu);
442 	else
443 		call_rcu(&dentry->d_rcu, __d_free);
444 }
445 
446 /*
447  * Release the dentry's inode, using the filesystem
448  * d_iput() operation if defined.
449  */
450 static void dentry_unlink_inode(struct dentry * dentry)
451 	__releases(dentry->d_lock)
452 	__releases(dentry->d_inode->i_lock)
453 {
454 	struct inode *inode = dentry->d_inode;
455 
456 	raw_write_seqcount_begin(&dentry->d_seq);
457 	__d_clear_type_and_inode(dentry);
458 	hlist_del_init(&dentry->d_alias);
459 	/*
460 	 * dentry becomes negative, so the space occupied by ->d_alias
461 	 * belongs to ->waiters now; we could use __hlist_del() instead
462 	 * of hlist_del_init(), if not for the stunt pulled by nfs
463 	 * dummy root dentries - positive dentry *not* included into
464 	 * the alias list of its inode.  Open-coding hlist_del_init()
465 	 * and removing zeroing would be too clumsy...
466 	 */
467 	dentry->waiters = NULL;
468 	raw_write_seqcount_end(&dentry->d_seq);
469 	spin_unlock(&dentry->d_lock);
470 	spin_unlock(&inode->i_lock);
471 	if (!inode->i_nlink)
472 		fsnotify_inoderemove(inode);
473 	if (dentry->d_op && dentry->d_op->d_iput)
474 		dentry->d_op->d_iput(dentry, inode);
475 	else
476 		iput(inode);
477 }
478 
479 /*
480  * The DCACHE_LRU_LIST bit is set whenever the 'd_lru' entry
481  * is in use - which includes both the "real" per-superblock
482  * LRU list _and_ the DCACHE_SHRINK_LIST use.
483  *
484  * The DCACHE_SHRINK_LIST bit is set whenever the dentry is
485  * on the shrink list (ie not on the superblock LRU list).
486  *
487  * The per-cpu "nr_dentry_unused" counters are updated with
488  * the DCACHE_LRU_LIST bit.
489  *
490  * The per-cpu "nr_dentry_negative" counters are only updated
491  * when deleted from or added to the per-superblock LRU list, not
492  * from/to the shrink list. That is to avoid an unneeded dec/inc
493  * pair when moving from LRU to shrink list in select_collect().
494  *
495  * These helper functions make sure we always follow the
496  * rules. d_lock must be held by the caller.
497  */
498 #define D_FLAG_VERIFY(dentry,x) WARN_ON_ONCE(((dentry)->d_flags & (DCACHE_LRU_LIST | DCACHE_SHRINK_LIST)) != (x))
499 static void d_lru_add(struct dentry *dentry)
500 {
501 	D_FLAG_VERIFY(dentry, 0);
502 	dentry->d_flags |= DCACHE_LRU_LIST;
503 	this_cpu_inc(nr_dentry_unused);
504 	if (d_is_negative(dentry))
505 		this_cpu_inc(nr_dentry_negative);
506 	WARN_ON_ONCE(!list_lru_add_obj(
507 			&dentry->d_sb->s_dentry_lru, &dentry->d_lru));
508 }
509 
510 static void d_lru_del(struct dentry *dentry)
511 {
512 	D_FLAG_VERIFY(dentry, DCACHE_LRU_LIST);
513 	dentry->d_flags &= ~DCACHE_LRU_LIST;
514 	this_cpu_dec(nr_dentry_unused);
515 	if (d_is_negative(dentry))
516 		this_cpu_dec(nr_dentry_negative);
517 	WARN_ON_ONCE(!list_lru_del_obj(
518 			&dentry->d_sb->s_dentry_lru, &dentry->d_lru));
519 }
520 
521 static void d_shrink_del(struct dentry *dentry)
522 {
523 	D_FLAG_VERIFY(dentry, DCACHE_SHRINK_LIST | DCACHE_LRU_LIST);
524 	list_del_init(&dentry->d_lru);
525 	dentry->d_flags &= ~(DCACHE_SHRINK_LIST | DCACHE_LRU_LIST);
526 	this_cpu_dec(nr_dentry_unused);
527 }
528 
529 static void d_shrink_add(struct dentry *dentry, struct list_head *list)
530 {
531 	D_FLAG_VERIFY(dentry, 0);
532 	list_add(&dentry->d_lru, list);
533 	dentry->d_flags |= DCACHE_SHRINK_LIST | DCACHE_LRU_LIST;
534 	this_cpu_inc(nr_dentry_unused);
535 }
536 
537 /*
538  * These can only be called under the global LRU lock, ie during the
539  * callback for freeing the LRU list. "isolate" removes it from the
540  * LRU lists entirely, while shrink_move moves it to the indicated
541  * private list.
542  */
543 static void d_lru_isolate(struct list_lru_one *lru, struct dentry *dentry)
544 {
545 	D_FLAG_VERIFY(dentry, DCACHE_LRU_LIST);
546 	dentry->d_flags &= ~DCACHE_LRU_LIST;
547 	this_cpu_dec(nr_dentry_unused);
548 	if (d_is_negative(dentry))
549 		this_cpu_dec(nr_dentry_negative);
550 	list_lru_isolate(lru, &dentry->d_lru);
551 }
552 
553 static void d_lru_shrink_move(struct list_lru_one *lru, struct dentry *dentry,
554 			      struct list_head *list)
555 {
556 	D_FLAG_VERIFY(dentry, DCACHE_LRU_LIST);
557 	dentry->d_flags |= DCACHE_SHRINK_LIST;
558 	if (d_is_negative(dentry))
559 		this_cpu_dec(nr_dentry_negative);
560 	list_lru_isolate_move(lru, &dentry->d_lru, list);
561 }
562 
563 static void ___d_drop(struct dentry *dentry)
564 {
565 	struct hlist_bl_head *b;
566 	/*
567 	 * Hashed dentries are normally on the dentry hashtable,
568 	 * with the exception of those newly allocated by
569 	 * d_obtain_root, which are always IS_ROOT:
570 	 */
571 	if (unlikely(IS_ROOT(dentry)))
572 		b = &dentry->d_sb->s_roots;
573 	else
574 		b = d_hash(dentry->d_name.hash);
575 
576 	hlist_bl_lock(b);
577 	__hlist_bl_del(&dentry->d_hash);
578 	hlist_bl_unlock(b);
579 }
580 
581 void __d_drop(struct dentry *dentry)
582 {
583 	if (!d_unhashed(dentry)) {
584 		___d_drop(dentry);
585 		dentry->d_hash.pprev = NULL;
586 		write_seqcount_invalidate(&dentry->d_seq);
587 	}
588 }
589 EXPORT_SYMBOL(__d_drop);
590 
591 /**
592  * d_drop - drop a dentry
593  * @dentry: dentry to drop
594  *
595  * d_drop() unhashes the entry from the parent dentry hashes, so that it won't
596  * be found through a VFS lookup any more. Note that this is different from
597  * deleting the dentry - d_delete will try to mark the dentry negative if
598  * possible, giving a successful _negative_ lookup, while d_drop will
599  * just make the cache lookup fail.
600  *
601  * d_drop() is used mainly for stuff that wants to invalidate a dentry for some
602  * reason (NFS timeouts or autofs deletes).
603  *
604  * __d_drop requires dentry->d_lock
605  *
606  * ___d_drop doesn't mark dentry as "unhashed"
607  * (dentry->d_hash.pprev will be LIST_POISON2, not NULL).
608  */
609 void d_drop(struct dentry *dentry)
610 {
611 	spin_lock(&dentry->d_lock);
612 	__d_drop(dentry);
613 	spin_unlock(&dentry->d_lock);
614 }
615 EXPORT_SYMBOL(d_drop);
616 
617 struct completion_list {
618 	struct completion_list *next;
619 	struct completion completion;
620 };
621 
622 /*
623  *  shrink_dcache_tree() needs to be notified when dentry in process of
624  *  being evicted finally gets unlisted.  Such dentries are
625  *	already with negative ->d_count
626  *	already negative
627  *	already not in in-lookup hash
628  *	reachable only via ->d_sib.
629  *
630  *  Use ->waiters for a single-linked list of struct completion_list of
631  *  waiters.
632  */
633 static inline void d_add_waiter(struct dentry *dentry, struct completion_list *p)
634 {
635 	struct completion_list *v = dentry->waiters;
636 	init_completion(&p->completion);
637 	p->next = v;
638 	dentry->waiters = p;
639 }
640 
641 static inline void d_complete_waiters(struct dentry *dentry)
642 {
643 	struct completion_list *v = dentry->waiters;
644 	if (unlikely(v)) {
645 		/* some shrink_dcache_tree() instances are waiting */
646 		dentry->waiters = NULL;
647 		while (v) {
648 			struct completion *r = &v->completion;
649 			v = v->next;
650 			complete(r);
651 		}
652 	}
653 }
654 
655 static inline void dentry_unlist(struct dentry *dentry)
656 {
657 	struct dentry *next;
658 	/*
659 	 * Inform d_walk() and shrink_dentry_list() that we are no longer
660 	 * attached to the dentry tree
661 	 */
662 	dentry->d_flags |= DCACHE_DENTRY_KILLED;
663 	d_complete_waiters(dentry);
664 	if (unlikely(hlist_unhashed(&dentry->d_sib)))
665 		return;
666 	__hlist_del(&dentry->d_sib);
667 	/*
668 	 * Cursors can move around the list of children.  While we'd been
669 	 * a normal list member, it didn't matter - ->d_sib.next would've
670 	 * been updated.  However, from now on it won't be and for the
671 	 * things like d_walk() it might end up with a nasty surprise.
672 	 * Normally d_walk() doesn't care about cursors moving around -
673 	 * ->d_lock on parent prevents that and since a cursor has no children
674 	 * of its own, we get through it without ever unlocking the parent.
675 	 * There is one exception, though - if we ascend from a child that
676 	 * gets killed as soon as we unlock it, the next sibling is found
677 	 * using the value left in its ->d_sib.next.  And if _that_
678 	 * pointed to a cursor, and cursor got moved (e.g. by lseek())
679 	 * before d_walk() regains parent->d_lock, we'll end up skipping
680 	 * everything the cursor had been moved past.
681 	 *
682 	 * Solution: make sure that the pointer left behind in ->d_sib.next
683 	 * points to something that won't be moving around.  I.e. skip the
684 	 * cursors.
685 	 */
686 	while (dentry->d_sib.next) {
687 		next = hlist_entry(dentry->d_sib.next, struct dentry, d_sib);
688 		if (likely(!(next->d_flags & DCACHE_DENTRY_CURSOR)))
689 			break;
690 		dentry->d_sib.next = next->d_sib.next;
691 	}
692 }
693 
694 static struct dentry *__dentry_kill(struct dentry *dentry)
695 {
696 	struct dentry *parent = NULL;
697 	bool can_free = true;
698 
699 	/*
700 	 * The dentry is now unrecoverably dead to the world.
701 	 */
702 	lockref_mark_dead(&dentry->d_lockref);
703 
704 	/*
705 	 * inform the fs via d_prune that this dentry is about to be
706 	 * unhashed and destroyed.
707 	 */
708 	if (dentry->d_flags & DCACHE_OP_PRUNE)
709 		dentry->d_op->d_prune(dentry);
710 
711 	if (dentry->d_flags & DCACHE_LRU_LIST) {
712 		if (!(dentry->d_flags & DCACHE_SHRINK_LIST))
713 			d_lru_del(dentry);
714 	}
715 	/* if it was on the hash then remove it */
716 	__d_drop(dentry);
717 	if (dentry->d_inode)
718 		dentry_unlink_inode(dentry);
719 	else
720 		spin_unlock(&dentry->d_lock);
721 	this_cpu_dec(nr_dentry);
722 	if (dentry->d_op && dentry->d_op->d_release)
723 		dentry->d_op->d_release(dentry);
724 
725 	cond_resched();
726 	/* now that it's negative, ->d_parent is stable */
727 	if (!IS_ROOT(dentry)) {
728 		parent = dentry->d_parent;
729 		spin_lock(&parent->d_lock);
730 	}
731 	spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
732 	dentry_unlist(dentry);
733 	if (dentry->d_flags & DCACHE_SHRINK_LIST)
734 		can_free = false;
735 	spin_unlock(&dentry->d_lock);
736 	if (likely(can_free))
737 		dentry_free(dentry);
738 	if (parent && --parent->d_lockref.count) {
739 		spin_unlock(&parent->d_lock);
740 		return NULL;
741 	}
742 	return parent;
743 }
744 
745 /*
746  * Lock a dentry for feeding it to __dentry_kill().
747  * Called under rcu_read_lock() and dentry->d_lock; the former
748  * guarantees that nothing we access will be freed under us.
749  * Note that dentry is *not* protected from concurrent dentry_kill(),
750  * d_delete(), etc.
751  *
752  * Return false if dentry is busy.  Otherwise, return true and have
753  * that dentry's inode locked.
754  */
755 
756 static bool lock_for_kill(struct dentry *dentry)
757 {
758 	struct inode *inode = dentry->d_inode;
759 
760 	if (unlikely(dentry->d_lockref.count))
761 		return false;
762 
763 	if (!inode || likely(spin_trylock(&inode->i_lock)))
764 		return true;
765 
766 	do {
767 		spin_unlock(&dentry->d_lock);
768 		spin_lock(&inode->i_lock);
769 		spin_lock(&dentry->d_lock);
770 		if (likely(inode == dentry->d_inode))
771 			break;
772 		spin_unlock(&inode->i_lock);
773 		inode = dentry->d_inode;
774 	} while (inode);
775 	if (likely(!dentry->d_lockref.count))
776 		return true;
777 	if (inode)
778 		spin_unlock(&inode->i_lock);
779 	return false;
780 }
781 
782 /*
783  * Decide if dentry is worth retaining.  Usually this is called with dentry
784  * locked; if not locked, we are more limited and might not be able to tell
785  * without a lock.  False in this case means "punt to locked path and recheck".
786  *
787  * In case we aren't locked, these predicates are not "stable". However, it is
788  * sufficient that at some point after we dropped the reference the dentry was
789  * hashed and the flags had the proper value. Other dentry users may have
790  * re-gotten a reference to the dentry and change that, but our work is done -
791  * we can leave the dentry around with a zero refcount.
792  */
793 static inline bool retain_dentry(struct dentry *dentry, bool locked)
794 {
795 	unsigned int d_flags;
796 
797 	smp_rmb();
798 	d_flags = READ_ONCE(dentry->d_flags);
799 
800 	// Unreachable? Nobody would be able to look it up, no point retaining
801 	if (unlikely(d_unhashed(dentry)))
802 		return false;
803 
804 	// Same if it's disconnected
805 	if (unlikely(d_flags & DCACHE_DISCONNECTED))
806 		return false;
807 
808 	// ->d_delete() might tell us not to bother, but that requires
809 	// ->d_lock; can't decide without it
810 	if (unlikely(d_flags & DCACHE_OP_DELETE)) {
811 		if (!locked || dentry->d_op->d_delete(dentry))
812 			return false;
813 	}
814 
815 	// Explicitly told not to bother
816 	if (unlikely(d_flags & DCACHE_DONTCACHE))
817 		return false;
818 
819 	// At this point it looks like we ought to keep it.  We also might
820 	// need to do something - put it on LRU if it wasn't there already
821 	// and mark it referenced if it was on LRU, but not marked yet.
822 	// Unfortunately, both actions require ->d_lock, so in lockless
823 	// case we'd have to punt rather than doing those.
824 	if (unlikely(!(d_flags & DCACHE_LRU_LIST))) {
825 		if (!locked)
826 			return false;
827 		d_lru_add(dentry);
828 	} else if (unlikely(!(d_flags & DCACHE_REFERENCED))) {
829 		if (!locked)
830 			return false;
831 		dentry->d_flags |= DCACHE_REFERENCED;
832 	}
833 	return true;
834 }
835 
836 void d_mark_dontcache(struct inode *inode)
837 {
838 	struct dentry *de;
839 
840 	spin_lock(&inode->i_lock);
841 	for_each_alias(de, inode) {
842 		spin_lock(&de->d_lock);
843 		de->d_flags |= DCACHE_DONTCACHE;
844 		spin_unlock(&de->d_lock);
845 	}
846 	inode_state_set(inode, I_DONTCACHE);
847 	spin_unlock(&inode->i_lock);
848 }
849 EXPORT_SYMBOL(d_mark_dontcache);
850 
851 /*
852  * Try to do a lockless dput(), and return whether that was successful.
853  *
854  * If unsuccessful, we return false, having already taken the dentry lock.
855  * In that case refcount is guaranteed to be zero and we have already
856  * decided that it's not worth keeping around.
857  *
858  * The caller needs to hold the RCU read lock, so that the dentry is
859  * guaranteed to stay around even if the refcount goes down to zero!
860  */
861 static inline bool fast_dput(struct dentry *dentry)
862 {
863 	int ret;
864 
865 	/*
866 	 * try to decrement the lockref optimistically.
867 	 */
868 	ret = lockref_put_return(&dentry->d_lockref);
869 
870 	/*
871 	 * If the lockref_put_return() failed due to the lock being held
872 	 * by somebody else, the fast path has failed. We will need to
873 	 * get the lock, and then check the count again.
874 	 */
875 	if (unlikely(ret < 0)) {
876 		spin_lock(&dentry->d_lock);
877 		if (WARN_ON_ONCE(dentry->d_lockref.count <= 0)) {
878 			spin_unlock(&dentry->d_lock);
879 			return true;
880 		}
881 		dentry->d_lockref.count--;
882 		goto locked;
883 	}
884 
885 	/*
886 	 * If we weren't the last ref, we're done.
887 	 */
888 	if (ret)
889 		return true;
890 
891 	/*
892 	 * Can we decide that decrement of refcount is all we needed without
893 	 * taking the lock?  There's a very common case when it's all we need -
894 	 * dentry looks like it ought to be retained and there's nothing else
895 	 * to do.
896 	 */
897 	if (retain_dentry(dentry, false))
898 		return true;
899 
900 	/*
901 	 * Either not worth retaining or we can't tell without the lock.
902 	 * Get the lock, then.  We've already decremented the refcount to 0,
903 	 * but we'll need to re-check the situation after getting the lock.
904 	 */
905 	spin_lock(&dentry->d_lock);
906 
907 	/*
908 	 * Did somebody else grab a reference to it in the meantime, and
909 	 * we're no longer the last user after all? Alternatively, somebody
910 	 * else could have killed it and marked it dead. Either way, we
911 	 * don't need to do anything else.
912 	 */
913 locked:
914 	if (dentry->d_lockref.count || retain_dentry(dentry, true)) {
915 		spin_unlock(&dentry->d_lock);
916 		return true;
917 	}
918 	return false;
919 }
920 
921 static void finish_dput(struct dentry *dentry)
922 	__releases(dentry->d_lock)
923 	__releases(RCU)
924 {
925 	while (lock_for_kill(dentry)) {
926 		rcu_read_unlock();
927 		dentry = __dentry_kill(dentry);
928 		if (!dentry)
929 			return;
930 		if (retain_dentry(dentry, true)) {
931 			spin_unlock(&dentry->d_lock);
932 			return;
933 		}
934 		rcu_read_lock();
935 	}
936 	rcu_read_unlock();
937 	spin_unlock(&dentry->d_lock);
938 }
939 
940 /*
941  * This is dput
942  *
943  * This is complicated by the fact that we do not want to put
944  * dentries that are no longer on any hash chain on the unused
945  * list: we'd much rather just get rid of them immediately.
946  *
947  * However, that implies that we have to traverse the dentry
948  * tree upwards to the parents which might _also_ now be
949  * scheduled for deletion (it may have been only waiting for
950  * its last child to go away).
951  *
952  * This tail recursion is done by hand as we don't want to depend
953  * on the compiler to always get this right (gcc generally doesn't).
954  * Real recursion would eat up our stack space.
955  */
956 
957 /*
958  * dput - release a dentry
959  * @dentry: dentry to release
960  *
961  * Release a dentry. This will drop the usage count and if appropriate
962  * call the dentry unlink method as well as removing it from the queues and
963  * releasing its resources. If the parent dentries were scheduled for release
964  * they too may now get deleted.
965  */
966 void dput(struct dentry *dentry)
967 {
968 	if (!dentry)
969 		return;
970 	might_sleep();
971 	rcu_read_lock();
972 	if (likely(fast_dput(dentry))) {
973 		rcu_read_unlock();
974 		return;
975 	}
976 	finish_dput(dentry);
977 }
978 EXPORT_SYMBOL(dput);
979 
980 void d_make_discardable(struct dentry *dentry)
981 {
982 	spin_lock(&dentry->d_lock);
983 	WARN_ON(!(dentry->d_flags & DCACHE_PERSISTENT));
984 	dentry->d_flags &= ~DCACHE_PERSISTENT;
985 	dentry->d_lockref.count--;
986 	rcu_read_lock();
987 	finish_dput(dentry);
988 }
989 EXPORT_SYMBOL(d_make_discardable);
990 
991 static void to_shrink_list(struct dentry *dentry, struct list_head *list)
992 __must_hold(&dentry->d_lock)
993 {
994 	if (!(dentry->d_flags & DCACHE_SHRINK_LIST)) {
995 		if (dentry->d_flags & DCACHE_LRU_LIST)
996 			d_lru_del(dentry);
997 		d_shrink_add(dentry, list);
998 	}
999 }
1000 
1001 void dput_to_list(struct dentry *dentry, struct list_head *list)
1002 {
1003 	rcu_read_lock();
1004 	if (likely(fast_dput(dentry))) {
1005 		rcu_read_unlock();
1006 		return;
1007 	}
1008 	rcu_read_unlock();
1009 	to_shrink_list(dentry, list);
1010 	spin_unlock(&dentry->d_lock);
1011 }
1012 
1013 struct dentry *dget_parent(struct dentry *dentry)
1014 {
1015 	int gotref;
1016 	struct dentry *ret;
1017 	unsigned seq;
1018 
1019 	/*
1020 	 * Do optimistic parent lookup without any
1021 	 * locking.
1022 	 */
1023 	rcu_read_lock();
1024 	seq = raw_seqcount_begin(&dentry->d_seq);
1025 	ret = READ_ONCE(dentry->d_parent);
1026 	gotref = lockref_get_not_zero(&ret->d_lockref);
1027 	rcu_read_unlock();
1028 	if (likely(gotref)) {
1029 		if (!read_seqcount_retry(&dentry->d_seq, seq))
1030 			return ret;
1031 		dput(ret);
1032 	}
1033 
1034 repeat:
1035 	/*
1036 	 * Don't need rcu_dereference because we re-check it was correct under
1037 	 * the lock.
1038 	 */
1039 	rcu_read_lock();
1040 	ret = dentry->d_parent;
1041 	spin_lock(&ret->d_lock);
1042 	if (unlikely(ret != dentry->d_parent)) {
1043 		spin_unlock(&ret->d_lock);
1044 		rcu_read_unlock();
1045 		goto repeat;
1046 	}
1047 	rcu_read_unlock();
1048 	BUG_ON(!ret->d_lockref.count);
1049 	ret->d_lockref.count++;
1050 	spin_unlock(&ret->d_lock);
1051 	return ret;
1052 }
1053 EXPORT_SYMBOL(dget_parent);
1054 
1055 /*
1056  * inode is a directory, inode->i_lock is held by the caller
1057  */
1058 static struct dentry * __d_find_dir_alias(struct inode *inode)
1059 {
1060 	struct dentry *alias;
1061 
1062 	if (hlist_empty(&inode->i_dentry))
1063 		return NULL;
1064 	alias = hlist_entry(inode->i_dentry.first, struct dentry, d_alias);
1065 	lockref_get(&alias->d_lockref);
1066 	return alias;
1067 }
1068 
1069 static struct dentry * __d_find_any_alias(struct inode *inode)
1070 {
1071 	struct dentry *alias;
1072 
1073 	if (hlist_empty(&inode->i_dentry))
1074 		return NULL;
1075 	for_each_alias(alias, inode)
1076 		if (dget_alias_ilocked(alias))
1077 			return alias;
1078 	return NULL;
1079 }
1080 
1081 /**
1082  * d_find_any_alias - find any alias for a given inode
1083  * @inode: inode to find an alias for
1084  *
1085  * If any aliases exist for the given inode, take and return a
1086  * reference for one of them.  If no aliases exist, return %NULL.
1087  */
1088 struct dentry *d_find_any_alias(struct inode *inode)
1089 {
1090 	struct dentry *de;
1091 
1092 	spin_lock(&inode->i_lock);
1093 	de = __d_find_any_alias(inode);
1094 	spin_unlock(&inode->i_lock);
1095 	return de;
1096 }
1097 EXPORT_SYMBOL(d_find_any_alias);
1098 
1099 static struct dentry *__d_find_alias(struct inode *inode)
1100 {
1101 	struct dentry *alias;
1102 
1103 	if (S_ISDIR(inode->i_mode))
1104 		return __d_find_dir_alias(inode);
1105 
1106 	for_each_alias(alias, inode) {
1107 		spin_lock(&alias->d_lock);
1108  		if (!d_unhashed(alias)) {
1109 			dget_dlock(alias);
1110 			spin_unlock(&alias->d_lock);
1111 			return alias;
1112 		}
1113 		spin_unlock(&alias->d_lock);
1114 	}
1115 	return NULL;
1116 }
1117 
1118 /**
1119  * d_find_alias - grab a hashed alias of inode
1120  * @inode: inode in question
1121  *
1122  * If inode has a hashed alias, or is a directory and has any alias,
1123  * acquire the reference to alias and return it. Otherwise return NULL.
1124  * Notice that if inode is a directory there can be only one alias and
1125  * it can be unhashed only if it has no children, or if it is the root
1126  * of a filesystem, or if the directory was renamed and d_revalidate
1127  * was the first vfs operation to notice.
1128  *
1129  * If the inode has an IS_ROOT, DCACHE_DISCONNECTED alias, then prefer
1130  * any other hashed alias over that one.
1131  */
1132 struct dentry *d_find_alias(struct inode *inode)
1133 {
1134 	struct dentry *de = NULL;
1135 
1136 	if (!hlist_empty(&inode->i_dentry)) {
1137 		spin_lock(&inode->i_lock);
1138 		de = __d_find_alias(inode);
1139 		spin_unlock(&inode->i_lock);
1140 	}
1141 	return de;
1142 }
1143 EXPORT_SYMBOL(d_find_alias);
1144 
1145 /*
1146  *  Caller MUST be holding rcu_read_lock() and be guaranteed
1147  *  that inode won't get freed until rcu_read_unlock().
1148  */
1149 struct dentry *d_find_alias_rcu(struct inode *inode)
1150 {
1151 	struct hlist_head *l = &inode->i_dentry;
1152 	struct dentry *de = NULL;
1153 
1154 	spin_lock(&inode->i_lock);
1155 	// ->i_dentry and ->i_rcu are colocated, but the latter won't be
1156 	// used without having I_FREEING set, which means no aliases left
1157 	if (likely(!(inode_state_read(inode) & I_FREEING) && !hlist_empty(l))) {
1158 		if (S_ISDIR(inode->i_mode)) {
1159 			de = hlist_entry(l->first, struct dentry, d_alias);
1160 		} else {
1161 			hlist_for_each_entry(de, l, d_alias)
1162 				if (!d_unhashed(de))
1163 					break;
1164 		}
1165 	}
1166 	spin_unlock(&inode->i_lock);
1167 	return de;
1168 }
1169 
1170 /**
1171  * d_dispose_if_unused - move unreferenced dentries to shrink list
1172  * @dentry: dentry in question
1173  * @dispose: head of shrink list
1174  *
1175  * If dentry has no external references, move it to shrink list.
1176  *
1177  * NOTE!!! The caller is responsible for preventing eviction of the dentry by
1178  * holding dentry->d_inode->i_lock or equivalent.
1179  */
1180 void d_dispose_if_unused(struct dentry *dentry, struct list_head *dispose)
1181 {
1182 	spin_lock(&dentry->d_lock);
1183 	if (!dentry->d_lockref.count)
1184 		to_shrink_list(dentry, dispose);
1185 	spin_unlock(&dentry->d_lock);
1186 }
1187 EXPORT_SYMBOL(d_dispose_if_unused);
1188 
1189 /*
1190  *	Try to kill dentries associated with this inode.
1191  * WARNING: you must own a reference to inode.
1192  */
1193 void d_prune_aliases(struct inode *inode)
1194 {
1195 	LIST_HEAD(dispose);
1196 	struct dentry *dentry;
1197 
1198 	spin_lock(&inode->i_lock);
1199 	for_each_alias(dentry, inode)
1200 		d_dispose_if_unused(dentry, &dispose);
1201 	spin_unlock(&inode->i_lock);
1202 	shrink_dentry_list(&dispose);
1203 }
1204 EXPORT_SYMBOL(d_prune_aliases);
1205 
1206 static inline void shrink_kill(struct dentry *victim)
1207 {
1208 	do {
1209 		rcu_read_unlock();
1210 		victim = __dentry_kill(victim);
1211 		rcu_read_lock();
1212 	} while (victim && lock_for_kill(victim));
1213 	rcu_read_unlock();
1214 	if (victim)
1215 		spin_unlock(&victim->d_lock);
1216 }
1217 
1218 void shrink_dentry_list(struct list_head *list)
1219 {
1220 	while (!list_empty(list)) {
1221 		struct dentry *dentry;
1222 
1223 		dentry = list_entry(list->prev, struct dentry, d_lru);
1224 		spin_lock(&dentry->d_lock);
1225 		rcu_read_lock();
1226 		if (!lock_for_kill(dentry)) {
1227 			bool can_free;
1228 			rcu_read_unlock();
1229 			d_shrink_del(dentry);
1230 			can_free = dentry->d_flags & DCACHE_DENTRY_KILLED;
1231 			spin_unlock(&dentry->d_lock);
1232 			if (can_free)
1233 				dentry_free(dentry);
1234 			continue;
1235 		}
1236 		d_shrink_del(dentry);
1237 		shrink_kill(dentry);
1238 	}
1239 }
1240 EXPORT_SYMBOL(shrink_dentry_list);
1241 
1242 static enum lru_status dentry_lru_isolate(struct list_head *item,
1243 		struct list_lru_one *lru, void *arg)
1244 {
1245 	struct list_head *freeable = arg;
1246 	struct dentry	*dentry = container_of(item, struct dentry, d_lru);
1247 
1248 
1249 	/*
1250 	 * we are inverting the lru lock/dentry->d_lock here,
1251 	 * so use a trylock. If we fail to get the lock, just skip
1252 	 * it
1253 	 */
1254 	if (!spin_trylock(&dentry->d_lock))
1255 		return LRU_SKIP;
1256 
1257 	/*
1258 	 * Referenced dentries are still in use. If they have active
1259 	 * counts, just remove them from the LRU. Otherwise give them
1260 	 * another pass through the LRU.
1261 	 */
1262 	if (dentry->d_lockref.count) {
1263 		d_lru_isolate(lru, dentry);
1264 		spin_unlock(&dentry->d_lock);
1265 		return LRU_REMOVED;
1266 	}
1267 
1268 	if (dentry->d_flags & DCACHE_REFERENCED) {
1269 		dentry->d_flags &= ~DCACHE_REFERENCED;
1270 		spin_unlock(&dentry->d_lock);
1271 
1272 		/*
1273 		 * The list move itself will be made by the common LRU code. At
1274 		 * this point, we've dropped the dentry->d_lock but keep the
1275 		 * lru lock. This is safe to do, since every list movement is
1276 		 * protected by the lru lock even if both locks are held.
1277 		 *
1278 		 * This is guaranteed by the fact that all LRU management
1279 		 * functions are intermediated by the LRU API calls like
1280 		 * list_lru_add_obj and list_lru_del_obj. List movement in this file
1281 		 * only ever occur through this functions or through callbacks
1282 		 * like this one, that are called from the LRU API.
1283 		 *
1284 		 * The only exceptions to this are functions like
1285 		 * shrink_dentry_list, and code that first checks for the
1286 		 * DCACHE_SHRINK_LIST flag.  Those are guaranteed to be
1287 		 * operating only with stack provided lists after they are
1288 		 * properly isolated from the main list.  It is thus, always a
1289 		 * local access.
1290 		 */
1291 		return LRU_ROTATE;
1292 	}
1293 
1294 	d_lru_shrink_move(lru, dentry, freeable);
1295 	spin_unlock(&dentry->d_lock);
1296 
1297 	return LRU_REMOVED;
1298 }
1299 
1300 /**
1301  * prune_dcache_sb - shrink the dcache
1302  * @sb: superblock
1303  * @sc: shrink control, passed to list_lru_shrink_walk()
1304  *
1305  * Attempt to shrink the superblock dcache LRU by @sc->nr_to_scan entries. This
1306  * is done when we need more memory and called from the superblock shrinker
1307  * function.
1308  *
1309  * This function may fail to free any resources if all the dentries are in
1310  * use.
1311  */
1312 long prune_dcache_sb(struct super_block *sb, struct shrink_control *sc)
1313 {
1314 	LIST_HEAD(dispose);
1315 	long freed;
1316 
1317 	freed = list_lru_shrink_walk(&sb->s_dentry_lru, sc,
1318 				     dentry_lru_isolate, &dispose);
1319 	shrink_dentry_list(&dispose);
1320 	return freed;
1321 }
1322 
1323 static enum lru_status dentry_lru_isolate_shrink(struct list_head *item,
1324 		struct list_lru_one *lru, void *arg)
1325 {
1326 	struct list_head *freeable = arg;
1327 	struct dentry	*dentry = container_of(item, struct dentry, d_lru);
1328 
1329 	/*
1330 	 * we are inverting the lru lock/dentry->d_lock here,
1331 	 * so use a trylock. If we fail to get the lock, just skip
1332 	 * it
1333 	 */
1334 	if (!spin_trylock(&dentry->d_lock))
1335 		return LRU_SKIP;
1336 
1337 	d_lru_shrink_move(lru, dentry, freeable);
1338 	spin_unlock(&dentry->d_lock);
1339 
1340 	return LRU_REMOVED;
1341 }
1342 
1343 
1344 /**
1345  * shrink_dcache_sb - shrink dcache for a superblock
1346  * @sb: superblock
1347  *
1348  * Shrink the dcache for the specified super block. This is used to free
1349  * the dcache before unmounting a file system.
1350  */
1351 void shrink_dcache_sb(struct super_block *sb)
1352 {
1353 	do {
1354 		LIST_HEAD(dispose);
1355 
1356 		list_lru_walk(&sb->s_dentry_lru,
1357 			dentry_lru_isolate_shrink, &dispose, 1024);
1358 		shrink_dentry_list(&dispose);
1359 	} while (list_lru_count(&sb->s_dentry_lru) > 0);
1360 }
1361 EXPORT_SYMBOL(shrink_dcache_sb);
1362 
1363 /**
1364  * enum d_walk_ret - action to take during tree walk
1365  * @D_WALK_CONTINUE:	continue walk
1366  * @D_WALK_QUIT:	quit walk
1367  * @D_WALK_NORETRY:	quit when retry is needed
1368  * @D_WALK_SKIP:	skip this dentry and its children
1369  */
1370 enum d_walk_ret {
1371 	D_WALK_CONTINUE,
1372 	D_WALK_QUIT,
1373 	D_WALK_NORETRY,
1374 	D_WALK_SKIP,
1375 };
1376 
1377 /**
1378  * d_walk - walk the dentry tree
1379  * @parent:	start of walk
1380  * @data:	data passed to @enter() and @finish()
1381  * @enter:	callback when first entering the dentry
1382  *
1383  * The @enter() callbacks are called with d_lock held.
1384  */
1385 static void d_walk(struct dentry *parent, void *data,
1386 		   enum d_walk_ret (*enter)(void *, struct dentry *))
1387 {
1388 	struct dentry *this_parent, *dentry;
1389 	unsigned seq = 0;
1390 	enum d_walk_ret ret;
1391 	bool retry = true;
1392 
1393 again:
1394 	read_seqbegin_or_lock(&rename_lock, &seq);
1395 	this_parent = parent;
1396 	spin_lock(&this_parent->d_lock);
1397 
1398 	ret = enter(data, this_parent);
1399 	switch (ret) {
1400 	case D_WALK_CONTINUE:
1401 		break;
1402 	case D_WALK_QUIT:
1403 	case D_WALK_SKIP:
1404 		goto out_unlock;
1405 	case D_WALK_NORETRY:
1406 		retry = false;
1407 		break;
1408 	}
1409 repeat:
1410 	dentry = d_first_child(this_parent);
1411 resume:
1412 	hlist_for_each_entry_from(dentry, d_sib) {
1413 		if (unlikely(dentry->d_flags & DCACHE_DENTRY_CURSOR))
1414 			continue;
1415 
1416 		spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
1417 
1418 		ret = enter(data, dentry);
1419 		switch (ret) {
1420 		case D_WALK_CONTINUE:
1421 			break;
1422 		case D_WALK_QUIT:
1423 			spin_unlock(&dentry->d_lock);
1424 			goto out_unlock;
1425 		case D_WALK_NORETRY:
1426 			retry = false;
1427 			break;
1428 		case D_WALK_SKIP:
1429 			spin_unlock(&dentry->d_lock);
1430 			continue;
1431 		}
1432 
1433 		if (!hlist_empty(&dentry->d_children)) {
1434 			spin_unlock(&this_parent->d_lock);
1435 			spin_release(&dentry->d_lock.dep_map, _RET_IP_);
1436 			this_parent = dentry;
1437 			spin_acquire(&this_parent->d_lock.dep_map, 0, 1, _RET_IP_);
1438 			goto repeat;
1439 		}
1440 		spin_unlock(&dentry->d_lock);
1441 	}
1442 	/*
1443 	 * All done at this level ... ascend and resume the search.
1444 	 */
1445 	rcu_read_lock();
1446 ascend:
1447 	if (this_parent != parent) {
1448 		dentry = this_parent;
1449 		this_parent = dentry->d_parent;
1450 
1451 		spin_unlock(&dentry->d_lock);
1452 		spin_lock(&this_parent->d_lock);
1453 
1454 		/* might go back up the wrong parent if we have had a rename. */
1455 		if (need_seqretry(&rename_lock, seq))
1456 			goto rename_retry;
1457 		/* go into the first sibling still alive */
1458 		hlist_for_each_entry_continue(dentry, d_sib) {
1459 			if (likely(!(dentry->d_flags & DCACHE_DENTRY_KILLED))) {
1460 				rcu_read_unlock();
1461 				goto resume;
1462 			}
1463 		}
1464 		goto ascend;
1465 	}
1466 	if (need_seqretry(&rename_lock, seq))
1467 		goto rename_retry;
1468 	rcu_read_unlock();
1469 
1470 out_unlock:
1471 	spin_unlock(&this_parent->d_lock);
1472 	done_seqretry(&rename_lock, seq);
1473 	return;
1474 
1475 rename_retry:
1476 	spin_unlock(&this_parent->d_lock);
1477 	rcu_read_unlock();
1478 	BUG_ON(seq & 1);
1479 	if (!retry)
1480 		return;
1481 	seq = 1;
1482 	goto again;
1483 }
1484 
1485 struct check_mount {
1486 	struct vfsmount *mnt;
1487 	unsigned int mounted;
1488 };
1489 
1490 /* locks: mount_locked_reader && dentry->d_lock */
1491 static enum d_walk_ret path_check_mount(void *data, struct dentry *dentry)
1492 {
1493 	struct check_mount *info = data;
1494 	struct path path = { .mnt = info->mnt, .dentry = dentry };
1495 
1496 	if (likely(!d_mountpoint(dentry)))
1497 		return D_WALK_CONTINUE;
1498 	if (__path_is_mountpoint(&path)) {
1499 		info->mounted = 1;
1500 		return D_WALK_QUIT;
1501 	}
1502 	return D_WALK_CONTINUE;
1503 }
1504 
1505 /**
1506  * path_has_submounts - check for mounts over a dentry in the
1507  *                      current namespace.
1508  * @parent: path to check.
1509  *
1510  * Return true if the parent or its subdirectories contain
1511  * a mount point in the current namespace.
1512  */
1513 int path_has_submounts(const struct path *parent)
1514 {
1515 	struct check_mount data = { .mnt = parent->mnt, .mounted = 0 };
1516 
1517 	guard(mount_locked_reader)();
1518 	d_walk(parent->dentry, &data, path_check_mount);
1519 
1520 	return data.mounted;
1521 }
1522 EXPORT_SYMBOL(path_has_submounts);
1523 
1524 /*
1525  * Called by mount code to set a mountpoint and check if the mountpoint is
1526  * reachable (e.g. NFS can unhash a directory dentry and then the complete
1527  * subtree can become unreachable).
1528  *
1529  * Only one of d_invalidate() and d_set_mounted() must succeed.  For
1530  * this reason take rename_lock and d_lock on dentry and ancestors.
1531  */
1532 int d_set_mounted(struct dentry *dentry)
1533 {
1534 	struct dentry *p;
1535 	int ret = -ENOENT;
1536 	read_seqlock_excl(&rename_lock);
1537 	for (p = dentry->d_parent; !IS_ROOT(p); p = p->d_parent) {
1538 		/* Need exclusion wrt. d_invalidate() */
1539 		spin_lock(&p->d_lock);
1540 		if (unlikely(d_unhashed(p))) {
1541 			spin_unlock(&p->d_lock);
1542 			goto out;
1543 		}
1544 		spin_unlock(&p->d_lock);
1545 	}
1546 	spin_lock(&dentry->d_lock);
1547 	if (!d_unlinked(dentry)) {
1548 		ret = -EBUSY;
1549 		if (!d_mountpoint(dentry)) {
1550 			dentry->d_flags |= DCACHE_MOUNTED;
1551 			ret = 0;
1552 		}
1553 	}
1554  	spin_unlock(&dentry->d_lock);
1555 out:
1556 	read_sequnlock_excl(&rename_lock);
1557 	return ret;
1558 }
1559 
1560 /*
1561  * Search the dentry child list of the specified parent,
1562  * and move any unused dentries to the end of the unused
1563  * list for prune_dcache(). We descend to the next level
1564  * whenever the d_children list is non-empty and continue
1565  * searching.
1566  *
1567  * It returns zero iff there are no unused children,
1568  * otherwise  it returns the number of children moved to
1569  * the end of the unused list. This may not be the total
1570  * number of unused children, because select_parent can
1571  * drop the lock and return early due to latency
1572  * constraints.
1573  */
1574 
1575 struct select_data {
1576 	struct dentry *start;
1577 	union {
1578 		long found;
1579 		struct dentry *victim;
1580 	};
1581 	struct list_head dispose;
1582 };
1583 
1584 static enum d_walk_ret select_collect(void *_data, struct dentry *dentry)
1585 {
1586 	struct select_data *data = _data;
1587 	enum d_walk_ret ret = D_WALK_CONTINUE;
1588 
1589 	if (data->start == dentry)
1590 		goto out;
1591 
1592 	if (dentry->d_flags & DCACHE_SHRINK_LIST) {
1593 		data->found++;
1594 	} else if (!dentry->d_lockref.count) {
1595 		to_shrink_list(dentry, &data->dispose);
1596 		data->found++;
1597 	} else if (dentry->d_lockref.count < 0) {
1598 		data->found++;
1599 	}
1600 	/*
1601 	 * We can return to the caller if we have found some (this
1602 	 * ensures forward progress). We'll be coming back to find
1603 	 * the rest.
1604 	 */
1605 	if (!list_empty(&data->dispose))
1606 		ret = need_resched() ? D_WALK_QUIT : D_WALK_NORETRY;
1607 out:
1608 	return ret;
1609 }
1610 
1611 static enum d_walk_ret select_collect_umount(void *_data, struct dentry *dentry)
1612 {
1613 	if (dentry->d_flags & DCACHE_PERSISTENT) {
1614 		dentry->d_flags &= ~DCACHE_PERSISTENT;
1615 		dentry->d_lockref.count--;
1616 	}
1617 	return select_collect(_data, dentry);
1618 }
1619 
1620 static enum d_walk_ret select_collect2(void *_data, struct dentry *dentry)
1621 {
1622 	struct select_data *data = _data;
1623 	enum d_walk_ret ret = D_WALK_CONTINUE;
1624 
1625 	if (data->start == dentry)
1626 		goto out;
1627 
1628 	if (!dentry->d_lockref.count) {
1629 		if (dentry->d_flags & DCACHE_SHRINK_LIST) {
1630 			rcu_read_lock();
1631 			data->victim = dentry;
1632 			return D_WALK_QUIT;
1633 		}
1634 		to_shrink_list(dentry, &data->dispose);
1635 	} else if (dentry->d_lockref.count < 0) {
1636 		rcu_read_lock();
1637 		data->victim = dentry;
1638 		return D_WALK_QUIT;
1639 	}
1640 	/*
1641 	 * We can return to the caller if we have found some (this
1642 	 * ensures forward progress). We'll be coming back to find
1643 	 * the rest.
1644 	 */
1645 	if (!list_empty(&data->dispose))
1646 		ret = need_resched() ? D_WALK_QUIT : D_WALK_NORETRY;
1647 out:
1648 	return ret;
1649 }
1650 
1651 /**
1652  * shrink_dcache_tree - prune dcache
1653  * @parent: parent of entries to prune
1654  * @for_umount: true if we want to unpin the persistent ones
1655  *
1656  * Prune the dcache to remove unused children of the parent dentry.
1657  */
1658 static void shrink_dcache_tree(struct dentry *parent, bool for_umount)
1659 {
1660 	for (;;) {
1661 		struct select_data data = {.start = parent};
1662 
1663 		INIT_LIST_HEAD(&data.dispose);
1664 		d_walk(parent, &data,
1665 			for_umount ? select_collect_umount : select_collect);
1666 
1667 		if (!list_empty(&data.dispose)) {
1668 			shrink_dentry_list(&data.dispose);
1669 			continue;
1670 		}
1671 
1672 		cond_resched();
1673 		if (!data.found)
1674 			break;
1675 		data.victim = NULL;
1676 		d_walk(parent, &data, select_collect2);
1677 		if (data.victim) {
1678 			struct dentry *v = data.victim;
1679 
1680 			spin_lock(&v->d_lock);
1681 			if (v->d_lockref.count < 0 &&
1682 			    !(v->d_flags & DCACHE_DENTRY_KILLED)) {
1683 				struct completion_list wait;
1684 				// It's busy dying; have it notify us once
1685 				// it becomes invisible to d_walk().
1686 				d_add_waiter(v, &wait);
1687 				spin_unlock(&v->d_lock);
1688 				rcu_read_unlock();
1689 				if (!list_empty(&data.dispose))
1690 					shrink_dentry_list(&data.dispose);
1691 				wait_for_completion(&wait.completion);
1692 				continue;
1693 			}
1694 			if (!lock_for_kill(v)) {
1695 				spin_unlock(&v->d_lock);
1696 				rcu_read_unlock();
1697 			} else {
1698 				shrink_kill(v);
1699 			}
1700 		}
1701 		if (!list_empty(&data.dispose))
1702 			shrink_dentry_list(&data.dispose);
1703 	}
1704 }
1705 
1706 void shrink_dcache_parent(struct dentry *parent)
1707 {
1708 	shrink_dcache_tree(parent, false);
1709 }
1710 EXPORT_SYMBOL(shrink_dcache_parent);
1711 
1712 static enum d_walk_ret umount_check(void *_data, struct dentry *dentry)
1713 {
1714 	/* it has busy descendents; complain about those instead */
1715 	if (!hlist_empty(&dentry->d_children))
1716 		return D_WALK_CONTINUE;
1717 
1718 	/* root with refcount 1 is fine */
1719 	if (dentry == _data && dentry->d_lockref.count == 1)
1720 		return D_WALK_CONTINUE;
1721 
1722 	WARN(1, "BUG: Dentry %p{i=%llx,n=%pd} "
1723 			" still in use (%d) [unmount of %s %s]\n",
1724 		       dentry,
1725 		       dentry->d_inode ?
1726 		       dentry->d_inode->i_ino : (u64)0,
1727 		       dentry,
1728 		       dentry->d_lockref.count,
1729 		       dentry->d_sb->s_type->name,
1730 		       dentry->d_sb->s_id);
1731 	return D_WALK_CONTINUE;
1732 }
1733 
1734 static void do_one_tree(struct dentry *dentry)
1735 {
1736 	shrink_dcache_tree(dentry, true);
1737 	d_walk(dentry, dentry, umount_check);
1738 	d_drop(dentry);
1739 	dput(dentry);
1740 }
1741 
1742 /*
1743  * destroy the dentries attached to a superblock on unmounting
1744  */
1745 void shrink_dcache_for_umount(struct super_block *sb)
1746 {
1747 	struct dentry *dentry;
1748 
1749 	rwsem_assert_held_write(&sb->s_umount);
1750 
1751 	dentry = sb->s_root;
1752 	sb->s_root = NULL;
1753 	do_one_tree(dentry);
1754 
1755 	while (!hlist_bl_empty(&sb->s_roots)) {
1756 		dentry = dget(hlist_bl_entry(hlist_bl_first(&sb->s_roots), struct dentry, d_hash));
1757 		do_one_tree(dentry);
1758 	}
1759 }
1760 
1761 static enum d_walk_ret find_submount(void *_data, struct dentry *dentry)
1762 {
1763 	struct dentry **victim = _data;
1764 	if (d_mountpoint(dentry)) {
1765 		*victim = dget_dlock(dentry);
1766 		return D_WALK_QUIT;
1767 	}
1768 	return D_WALK_CONTINUE;
1769 }
1770 
1771 /**
1772  * d_invalidate - detach submounts, prune dcache, and drop
1773  * @dentry: dentry to invalidate (aka detach, prune and drop)
1774  */
1775 void d_invalidate(struct dentry *dentry)
1776 {
1777 	bool had_submounts = false;
1778 	spin_lock(&dentry->d_lock);
1779 	if (d_unhashed(dentry)) {
1780 		spin_unlock(&dentry->d_lock);
1781 		return;
1782 	}
1783 	__d_drop(dentry);
1784 	spin_unlock(&dentry->d_lock);
1785 
1786 	/* Negative dentries can be dropped without further checks */
1787 	if (!dentry->d_inode)
1788 		return;
1789 
1790 	shrink_dcache_parent(dentry);
1791 	for (;;) {
1792 		struct dentry *victim = NULL;
1793 		d_walk(dentry, &victim, find_submount);
1794 		if (!victim) {
1795 			if (had_submounts)
1796 				shrink_dcache_parent(dentry);
1797 			return;
1798 		}
1799 		had_submounts = true;
1800 		detach_mounts(victim);
1801 		dput(victim);
1802 	}
1803 }
1804 EXPORT_SYMBOL(d_invalidate);
1805 
1806 /**
1807  * __d_alloc - allocate a dcache entry
1808  * @sb: filesystem it will belong to
1809  * @name: qstr of the name
1810  *
1811  * Allocates a dentry. It returns %NULL if there is insufficient memory
1812  * available. On a success the dentry is returned. The name passed in is
1813  * copied and the copy passed in may be reused after this call.
1814  */
1815 
1816 static struct dentry *__d_alloc(struct super_block *sb, const struct qstr *name)
1817 {
1818 	struct dentry *dentry;
1819 	char *dname;
1820 	int err;
1821 
1822 	dentry = kmem_cache_alloc_lru(dentry_cache, &sb->s_dentry_lru,
1823 				      GFP_KERNEL);
1824 	if (!dentry)
1825 		return NULL;
1826 
1827 	/*
1828 	 * We guarantee that the inline name is always NUL-terminated.
1829 	 * This way the memcpy() done by the name switching in rename
1830 	 * will still always have a NUL at the end, even if we might
1831 	 * be overwriting an internal NUL character
1832 	 */
1833 	dentry->d_shortname.string[DNAME_INLINE_LEN-1] = 0;
1834 	if (unlikely(!name)) {
1835 		name = &slash_name;
1836 		dname = dentry->d_shortname.string;
1837 	} else if (name->len > DNAME_INLINE_LEN-1) {
1838 		size_t size = offsetof(struct external_name, name[1]);
1839 		struct external_name *p = kmalloc(size + name->len,
1840 						  GFP_KERNEL_ACCOUNT |
1841 						  __GFP_RECLAIMABLE);
1842 		if (!p) {
1843 			kmem_cache_free(dentry_cache, dentry);
1844 			return NULL;
1845 		}
1846 		atomic_set(&p->count, 1);
1847 		dname = p->name;
1848 	} else  {
1849 		dname = dentry->d_shortname.string;
1850 	}
1851 
1852 	dentry->__d_name.len = name->len;
1853 	dentry->__d_name.hash = name->hash;
1854 	memcpy(dname, name->name, name->len);
1855 	dname[name->len] = 0;
1856 
1857 	/* Make sure we always see the terminating NUL character */
1858 	smp_store_release(&dentry->__d_name.name, dname); /* ^^^ */
1859 
1860 	dentry->d_flags = 0;
1861 	lockref_init(&dentry->d_lockref);
1862 	seqcount_spinlock_init(&dentry->d_seq, &dentry->d_lock);
1863 	dentry->d_inode = NULL;
1864 	dentry->d_parent = dentry;
1865 	dentry->d_sb = sb;
1866 	dentry->d_op = sb->__s_d_op;
1867 	dentry->d_flags = sb->s_d_flags;
1868 	dentry->d_fsdata = NULL;
1869 	INIT_HLIST_BL_NODE(&dentry->d_hash);
1870 	INIT_LIST_HEAD(&dentry->d_lru);
1871 	INIT_HLIST_HEAD(&dentry->d_children);
1872 	dentry->waiters = NULL;
1873 	INIT_HLIST_NODE(&dentry->d_sib);
1874 
1875 	if (dentry->d_op && dentry->d_op->d_init) {
1876 		err = dentry->d_op->d_init(dentry);
1877 		if (err) {
1878 			if (dname_external(dentry))
1879 				kfree(external_name(dentry));
1880 			kmem_cache_free(dentry_cache, dentry);
1881 			return NULL;
1882 		}
1883 	}
1884 
1885 	this_cpu_inc(nr_dentry);
1886 
1887 	return dentry;
1888 }
1889 
1890 /**
1891  * d_alloc - allocate a dcache entry
1892  * @parent: parent of entry to allocate
1893  * @name: qstr of the name
1894  *
1895  * Allocates a dentry. It returns %NULL if there is insufficient memory
1896  * available. On a success the dentry is returned. The name passed in is
1897  * copied and the copy passed in may be reused after this call.
1898  */
1899 struct dentry *d_alloc(struct dentry * parent, const struct qstr *name)
1900 {
1901 	struct dentry *dentry = __d_alloc(parent->d_sb, name);
1902 	if (!dentry)
1903 		return NULL;
1904 	spin_lock(&parent->d_lock);
1905 	/*
1906 	 * don't need child lock because it is not subject
1907 	 * to concurrency here
1908 	 */
1909 	dentry->d_parent = dget_dlock(parent);
1910 	hlist_add_head(&dentry->d_sib, &parent->d_children);
1911 	spin_unlock(&parent->d_lock);
1912 
1913 	return dentry;
1914 }
1915 EXPORT_SYMBOL(d_alloc);
1916 
1917 struct dentry *d_alloc_anon(struct super_block *sb)
1918 {
1919 	return __d_alloc(sb, NULL);
1920 }
1921 EXPORT_SYMBOL(d_alloc_anon);
1922 
1923 struct dentry *d_alloc_cursor(struct dentry * parent)
1924 {
1925 	struct dentry *dentry = d_alloc_anon(parent->d_sb);
1926 	if (dentry) {
1927 		dentry->d_flags |= DCACHE_DENTRY_CURSOR;
1928 		dentry->d_parent = dget(parent);
1929 	}
1930 	return dentry;
1931 }
1932 
1933 /**
1934  * d_alloc_pseudo - allocate a dentry (for lookup-less filesystems)
1935  * @sb: the superblock
1936  * @name: qstr of the name
1937  *
1938  * For a filesystem that just pins its dentries in memory and never
1939  * performs lookups at all, return an unhashed IS_ROOT dentry.
1940  * This is used for pipes, sockets et.al. - the stuff that should
1941  * never be anyone's children or parents.  Unlike all other
1942  * dentries, these will not have RCU delay between dropping the
1943  * last reference and freeing them.
1944  *
1945  * The only user is alloc_file_pseudo() and that's what should
1946  * be considered a public interface.  Don't use directly.
1947  */
1948 struct dentry *d_alloc_pseudo(struct super_block *sb, const struct qstr *name)
1949 {
1950 	static const struct dentry_operations anon_ops = {
1951 		.d_dname = simple_dname
1952 	};
1953 	struct dentry *dentry = __d_alloc(sb, name);
1954 	if (likely(dentry)) {
1955 		dentry->d_flags |= DCACHE_NORCU;
1956 		/* d_op_flags(&anon_ops) is 0 */
1957 		if (!dentry->d_op)
1958 			dentry->d_op = &anon_ops;
1959 	}
1960 	return dentry;
1961 }
1962 
1963 struct dentry *d_alloc_name(struct dentry *parent, const char *name)
1964 {
1965 	struct qstr q;
1966 
1967 	q.name = name;
1968 	q.hash_len = hashlen_string(parent, name);
1969 	return d_alloc(parent, &q);
1970 }
1971 EXPORT_SYMBOL(d_alloc_name);
1972 
1973 #define DCACHE_OP_FLAGS \
1974 	(DCACHE_OP_HASH | DCACHE_OP_COMPARE | DCACHE_OP_REVALIDATE | \
1975 	 DCACHE_OP_WEAK_REVALIDATE | DCACHE_OP_DELETE | DCACHE_OP_PRUNE | \
1976 	 DCACHE_OP_REAL)
1977 
1978 static unsigned int d_op_flags(const struct dentry_operations *op)
1979 {
1980 	unsigned int flags = 0;
1981 	if (op) {
1982 		if (op->d_hash)
1983 			flags |= DCACHE_OP_HASH;
1984 		if (op->d_compare)
1985 			flags |= DCACHE_OP_COMPARE;
1986 		if (op->d_revalidate)
1987 			flags |= DCACHE_OP_REVALIDATE;
1988 		if (op->d_weak_revalidate)
1989 			flags |= DCACHE_OP_WEAK_REVALIDATE;
1990 		if (op->d_delete)
1991 			flags |= DCACHE_OP_DELETE;
1992 		if (op->d_prune)
1993 			flags |= DCACHE_OP_PRUNE;
1994 		if (op->d_real)
1995 			flags |= DCACHE_OP_REAL;
1996 	}
1997 	return flags;
1998 }
1999 
2000 static void d_set_d_op(struct dentry *dentry, const struct dentry_operations *op)
2001 {
2002 	unsigned int flags = d_op_flags(op);
2003 	WARN_ON_ONCE(dentry->d_op);
2004 	WARN_ON_ONCE(dentry->d_flags & DCACHE_OP_FLAGS);
2005 	dentry->d_op = op;
2006 	if (flags)
2007 		dentry->d_flags |= flags;
2008 }
2009 
2010 void set_default_d_op(struct super_block *s, const struct dentry_operations *ops)
2011 {
2012 	unsigned int flags = d_op_flags(ops);
2013 	s->__s_d_op = ops;
2014 	s->s_d_flags = (s->s_d_flags & ~DCACHE_OP_FLAGS) | flags;
2015 }
2016 EXPORT_SYMBOL(set_default_d_op);
2017 
2018 static unsigned d_flags_for_inode(struct inode *inode)
2019 {
2020 	unsigned add_flags = DCACHE_REGULAR_TYPE;
2021 
2022 	if (!inode)
2023 		return DCACHE_MISS_TYPE;
2024 
2025 	if (S_ISDIR(inode->i_mode)) {
2026 		add_flags = DCACHE_DIRECTORY_TYPE;
2027 		if (unlikely(!(inode->i_opflags & IOP_LOOKUP))) {
2028 			if (unlikely(!inode->i_op->lookup))
2029 				add_flags = DCACHE_AUTODIR_TYPE;
2030 			else
2031 				inode->i_opflags |= IOP_LOOKUP;
2032 		}
2033 		goto type_determined;
2034 	}
2035 
2036 	if (unlikely(!(inode->i_opflags & IOP_NOFOLLOW))) {
2037 		if (unlikely(inode->i_op->get_link)) {
2038 			add_flags = DCACHE_SYMLINK_TYPE;
2039 			goto type_determined;
2040 		}
2041 		inode->i_opflags |= IOP_NOFOLLOW;
2042 	}
2043 
2044 	if (unlikely(!S_ISREG(inode->i_mode)))
2045 		add_flags = DCACHE_SPECIAL_TYPE;
2046 
2047 type_determined:
2048 	if (unlikely(IS_AUTOMOUNT(inode)))
2049 		add_flags |= DCACHE_NEED_AUTOMOUNT;
2050 	return add_flags;
2051 }
2052 
2053 static void __d_instantiate(struct dentry *dentry, struct inode *inode)
2054 {
2055 	unsigned add_flags = d_flags_for_inode(inode);
2056 	WARN_ON(d_in_lookup(dentry));
2057 
2058 	/*
2059 	 * The negative counter only tracks dentries on the LRU. Don't dec if
2060 	 * d_lru is on another list.
2061 	 */
2062 	if ((dentry->d_flags &
2063 	     (DCACHE_LRU_LIST|DCACHE_SHRINK_LIST)) == DCACHE_LRU_LIST)
2064 		this_cpu_dec(nr_dentry_negative);
2065 	hlist_add_head(&dentry->d_alias, &inode->i_dentry);
2066 	raw_write_seqcount_begin(&dentry->d_seq);
2067 	__d_set_inode_and_type(dentry, inode, add_flags);
2068 	raw_write_seqcount_end(&dentry->d_seq);
2069 	fsnotify_update_flags(dentry);
2070 }
2071 
2072 /**
2073  * d_instantiate - fill in inode information for a dentry
2074  * @entry: dentry to complete
2075  * @inode: inode to attach to this dentry
2076  *
2077  * Fill in inode information in the entry.
2078  *
2079  * This turns negative dentries into productive full members
2080  * of society.
2081  *
2082  * NOTE! This assumes that the inode count has been incremented
2083  * (or otherwise set) by the caller to indicate that it is now
2084  * in use by the dcache.
2085  */
2086 
2087 void d_instantiate(struct dentry *entry, struct inode * inode)
2088 {
2089 	BUG_ON(d_really_is_positive(entry));
2090 	if (inode) {
2091 		security_d_instantiate(entry, inode);
2092 		spin_lock(&inode->i_lock);
2093 		spin_lock(&entry->d_lock);
2094 		__d_instantiate(entry, inode);
2095 		spin_unlock(&entry->d_lock);
2096 		spin_unlock(&inode->i_lock);
2097 	}
2098 }
2099 EXPORT_SYMBOL(d_instantiate);
2100 
2101 /*
2102  * This should be equivalent to d_instantiate() + unlock_new_inode(),
2103  * with lockdep-related part of unlock_new_inode() done before
2104  * anything else.  Use that instead of open-coding d_instantiate()/
2105  * unlock_new_inode() combinations.
2106  */
2107 void d_instantiate_new(struct dentry *entry, struct inode *inode)
2108 {
2109 	BUG_ON(d_really_is_positive(entry));
2110 	BUG_ON(!inode);
2111 	lockdep_annotate_inode_mutex_key(inode);
2112 	security_d_instantiate(entry, inode);
2113 	spin_lock(&inode->i_lock);
2114 	spin_lock(&entry->d_lock);
2115 	__d_instantiate(entry, inode);
2116 	spin_unlock(&entry->d_lock);
2117 	WARN_ON(!(inode_state_read(inode) & I_NEW));
2118 	inode_state_clear(inode, I_NEW | I_CREATING);
2119 	inode_wake_up_bit(inode, __I_NEW);
2120 	spin_unlock(&inode->i_lock);
2121 }
2122 EXPORT_SYMBOL(d_instantiate_new);
2123 
2124 struct dentry *d_make_root(struct inode *root_inode)
2125 {
2126 	struct dentry *res = NULL;
2127 
2128 	if (root_inode) {
2129 		res = d_alloc_anon(root_inode->i_sb);
2130 		if (res)
2131 			d_instantiate(res, root_inode);
2132 		else
2133 			iput(root_inode);
2134 	}
2135 	return res;
2136 }
2137 EXPORT_SYMBOL(d_make_root);
2138 
2139 static struct dentry *__d_obtain_alias(struct inode *inode, bool disconnected)
2140 {
2141 	struct super_block *sb;
2142 	struct dentry *new, *res;
2143 
2144 	if (!inode)
2145 		return ERR_PTR(-ESTALE);
2146 	if (IS_ERR(inode))
2147 		return ERR_CAST(inode);
2148 
2149 	sb = inode->i_sb;
2150 
2151 	res = d_find_any_alias(inode); /* existing alias? */
2152 	if (res)
2153 		goto out;
2154 
2155 	new = d_alloc_anon(sb);
2156 	if (!new) {
2157 		res = ERR_PTR(-ENOMEM);
2158 		goto out;
2159 	}
2160 
2161 	security_d_instantiate(new, inode);
2162 	spin_lock(&inode->i_lock);
2163 	res = __d_find_any_alias(inode); /* recheck under lock */
2164 	if (likely(!res)) { /* still no alias, attach a disconnected dentry */
2165 		unsigned add_flags = d_flags_for_inode(inode);
2166 
2167 		if (disconnected)
2168 			add_flags |= DCACHE_DISCONNECTED;
2169 
2170 		spin_lock(&new->d_lock);
2171 		__d_set_inode_and_type(new, inode, add_flags);
2172 		hlist_add_head(&new->d_alias, &inode->i_dentry);
2173 		if (!disconnected) {
2174 			hlist_bl_lock(&sb->s_roots);
2175 			hlist_bl_add_head(&new->d_hash, &sb->s_roots);
2176 			hlist_bl_unlock(&sb->s_roots);
2177 		}
2178 		spin_unlock(&new->d_lock);
2179 		spin_unlock(&inode->i_lock);
2180 		inode = NULL; /* consumed by new->d_inode */
2181 		res = new;
2182 	} else {
2183 		spin_unlock(&inode->i_lock);
2184 		dput(new);
2185 	}
2186 
2187  out:
2188 	iput(inode);
2189 	return res;
2190 }
2191 
2192 /**
2193  * d_obtain_alias - find or allocate a DISCONNECTED dentry for a given inode
2194  * @inode: inode to allocate the dentry for
2195  *
2196  * Obtain a dentry for an inode resulting from NFS filehandle conversion or
2197  * similar open by handle operations.  The returned dentry may be anonymous,
2198  * or may have a full name (if the inode was already in the cache).
2199  *
2200  * When called on a directory inode, we must ensure that the inode only ever
2201  * has one dentry.  If a dentry is found, that is returned instead of
2202  * allocating a new one.
2203  *
2204  * On successful return, the reference to the inode has been transferred
2205  * to the dentry.  In case of an error the reference on the inode is released.
2206  * To make it easier to use in export operations a %NULL or IS_ERR inode may
2207  * be passed in and the error will be propagated to the return value,
2208  * with a %NULL @inode replaced by ERR_PTR(-ESTALE).
2209  */
2210 struct dentry *d_obtain_alias(struct inode *inode)
2211 {
2212 	return __d_obtain_alias(inode, true);
2213 }
2214 EXPORT_SYMBOL(d_obtain_alias);
2215 
2216 /**
2217  * d_obtain_root - find or allocate a dentry for a given inode
2218  * @inode: inode to allocate the dentry for
2219  *
2220  * Obtain an IS_ROOT dentry for the root of a filesystem.
2221  *
2222  * We must ensure that directory inodes only ever have one dentry.  If a
2223  * dentry is found, that is returned instead of allocating a new one.
2224  *
2225  * On successful return, the reference to the inode has been transferred
2226  * to the dentry.  In case of an error the reference on the inode is
2227  * released.  A %NULL or IS_ERR inode may be passed in and will be the
2228  * error will be propagate to the return value, with a %NULL @inode
2229  * replaced by ERR_PTR(-ESTALE).
2230  */
2231 struct dentry *d_obtain_root(struct inode *inode)
2232 {
2233 	return __d_obtain_alias(inode, false);
2234 }
2235 EXPORT_SYMBOL(d_obtain_root);
2236 
2237 /**
2238  * d_add_ci - lookup or allocate new dentry with case-exact name
2239  * @dentry: the negative dentry that was passed to the parent's lookup func
2240  * @inode:  the inode case-insensitive lookup has found
2241  * @name:   the case-exact name to be associated with the returned dentry
2242  *
2243  * This is to avoid filling the dcache with case-insensitive names to the
2244  * same inode, only the actual correct case is stored in the dcache for
2245  * case-insensitive filesystems.
2246  *
2247  * For a case-insensitive lookup match and if the case-exact dentry
2248  * already exists in the dcache, use it and return it.
2249  *
2250  * If no entry exists with the exact case name, allocate new dentry with
2251  * the exact case, and return the spliced entry.
2252  */
2253 struct dentry *d_add_ci(struct dentry *dentry, struct inode *inode,
2254 			struct qstr *name)
2255 {
2256 	struct dentry *found, *res;
2257 
2258 	/*
2259 	 * First check if a dentry matching the name already exists,
2260 	 * if not go ahead and create it now.
2261 	 */
2262 	found = d_hash_and_lookup(dentry->d_parent, name);
2263 	if (found) {
2264 		iput(inode);
2265 		return found;
2266 	}
2267 	if (d_in_lookup(dentry)) {
2268 		found = d_alloc_parallel(dentry->d_parent, name);
2269 		if (IS_ERR(found) || !d_in_lookup(found)) {
2270 			iput(inode);
2271 			return found;
2272 		}
2273 	} else {
2274 		found = d_alloc(dentry->d_parent, name);
2275 		if (!found) {
2276 			iput(inode);
2277 			return ERR_PTR(-ENOMEM);
2278 		}
2279 	}
2280 	res = d_splice_alias(inode, found);
2281 	if (res) {
2282 		d_lookup_done(found);
2283 		dput(found);
2284 		return res;
2285 	}
2286 	return found;
2287 }
2288 EXPORT_SYMBOL(d_add_ci);
2289 
2290 /**
2291  * d_same_name - compare dentry name with case-exact name
2292  * @dentry: the negative dentry that was passed to the parent's lookup func
2293  * @parent: parent dentry
2294  * @name:   the case-exact name to be associated with the returned dentry
2295  *
2296  * Return: true if names are same, or false
2297  */
2298 bool d_same_name(const struct dentry *dentry, const struct dentry *parent,
2299 		 const struct qstr *name)
2300 {
2301 	if (likely(!(parent->d_flags & DCACHE_OP_COMPARE))) {
2302 		if (dentry->d_name.len != name->len)
2303 			return false;
2304 		return dentry_cmp(dentry, name->name, name->len) == 0;
2305 	}
2306 	return parent->d_op->d_compare(dentry,
2307 				       dentry->d_name.len, dentry->d_name.name,
2308 				       name) == 0;
2309 }
2310 EXPORT_SYMBOL_GPL(d_same_name);
2311 
2312 /*
2313  * This is __d_lookup_rcu() when the parent dentry has
2314  * DCACHE_OP_COMPARE, which makes things much nastier.
2315  */
2316 static noinline struct dentry *__d_lookup_rcu_op_compare(
2317 	const struct dentry *parent,
2318 	const struct qstr *name,
2319 	unsigned *seqp)
2320 {
2321 	u64 hashlen = name->hash_len;
2322 	struct hlist_bl_head *b = d_hash(hashlen);
2323 	struct hlist_bl_node *node;
2324 	struct dentry *dentry;
2325 
2326 	hlist_bl_for_each_entry_rcu(dentry, node, b, d_hash) {
2327 		int tlen;
2328 		const char *tname;
2329 		unsigned seq;
2330 
2331 seqretry:
2332 		seq = raw_seqcount_begin(&dentry->d_seq);
2333 		if (dentry->d_parent != parent)
2334 			continue;
2335 		if (d_unhashed(dentry))
2336 			continue;
2337 		if (dentry->d_name.hash != hashlen_hash(hashlen))
2338 			continue;
2339 		tlen = dentry->d_name.len;
2340 		tname = dentry->d_name.name;
2341 		/* we want a consistent (name,len) pair */
2342 		if (read_seqcount_retry(&dentry->d_seq, seq)) {
2343 			cpu_relax();
2344 			goto seqretry;
2345 		}
2346 		if (parent->d_op->d_compare(dentry, tlen, tname, name) != 0)
2347 			continue;
2348 		*seqp = seq;
2349 		return dentry;
2350 	}
2351 	return NULL;
2352 }
2353 
2354 /**
2355  * __d_lookup_rcu - search for a dentry (racy, store-free)
2356  * @parent: parent dentry
2357  * @name: qstr of name we wish to find
2358  * @seqp: returns d_seq value at the point where the dentry was found
2359  * Returns: dentry, or NULL
2360  *
2361  * __d_lookup_rcu is the dcache lookup function for rcu-walk name
2362  * resolution (store-free path walking) design described in
2363  * Documentation/filesystems/path-lookup.txt.
2364  *
2365  * This is not to be used outside core vfs.
2366  *
2367  * __d_lookup_rcu must only be used in rcu-walk mode, ie. with vfsmount lock
2368  * held, and rcu_read_lock held. The returned dentry must not be stored into
2369  * without taking d_lock and checking d_seq sequence count against @seq
2370  * returned here.
2371  *
2372  * Alternatively, __d_lookup_rcu may be called again to look up the child of
2373  * the returned dentry, so long as its parent's seqlock is checked after the
2374  * child is looked up. Thus, an interlocking stepping of sequence lock checks
2375  * is formed, giving integrity down the path walk.
2376  *
2377  * NOTE! The caller *has* to check the resulting dentry against the sequence
2378  * number we've returned before using any of the resulting dentry state!
2379  */
2380 struct dentry *__d_lookup_rcu(const struct dentry *parent,
2381 				const struct qstr *name,
2382 				unsigned *seqp)
2383 {
2384 	u64 hashlen = name->hash_len;
2385 	const unsigned char *str = name->name;
2386 	struct hlist_bl_head *b = d_hash(hashlen);
2387 	struct hlist_bl_node *node;
2388 	struct dentry *dentry;
2389 
2390 	/*
2391 	 * Note: There is significant duplication with __d_lookup_rcu which is
2392 	 * required to prevent single threaded performance regressions
2393 	 * especially on architectures where smp_rmb (in seqcounts) are costly.
2394 	 * Keep the two functions in sync.
2395 	 */
2396 
2397 	if (unlikely(parent->d_flags & DCACHE_OP_COMPARE))
2398 		return __d_lookup_rcu_op_compare(parent, name, seqp);
2399 
2400 	/*
2401 	 * The hash list is protected using RCU.
2402 	 *
2403 	 * Carefully use d_seq when comparing a candidate dentry, to avoid
2404 	 * races with d_move().
2405 	 *
2406 	 * It is possible that concurrent renames can mess up our list
2407 	 * walk here and result in missing our dentry, resulting in the
2408 	 * false-negative result. d_lookup() protects against concurrent
2409 	 * renames using rename_lock seqlock.
2410 	 *
2411 	 * See Documentation/filesystems/path-lookup.txt for more details.
2412 	 */
2413 	hlist_bl_for_each_entry_rcu(dentry, node, b, d_hash) {
2414 		unsigned seq;
2415 
2416 		/*
2417 		 * The dentry sequence count protects us from concurrent
2418 		 * renames, and thus protects parent and name fields.
2419 		 *
2420 		 * The caller must perform a seqcount check in order
2421 		 * to do anything useful with the returned dentry.
2422 		 *
2423 		 * NOTE! We do a "raw" seqcount_begin here. That means that
2424 		 * we don't wait for the sequence count to stabilize if it
2425 		 * is in the middle of a sequence change. If we do the slow
2426 		 * dentry compare, we will do seqretries until it is stable,
2427 		 * and if we end up with a successful lookup, we actually
2428 		 * want to exit RCU lookup anyway.
2429 		 *
2430 		 * Note that raw_seqcount_begin still *does* smp_rmb(), so
2431 		 * we are still guaranteed NUL-termination of ->d_name.name.
2432 		 */
2433 		seq = raw_seqcount_begin(&dentry->d_seq);
2434 		if (dentry->d_parent != parent)
2435 			continue;
2436 		if (dentry->d_name.hash_len != hashlen)
2437 			continue;
2438 		if (unlikely(dentry_cmp(dentry, str, hashlen_len(hashlen)) != 0))
2439 			continue;
2440 		/*
2441 		 * Check for the dentry being unhashed.
2442 		 *
2443 		 * As tempting as it is, we *can't* skip it because of a race window
2444 		 * between us finding the dentry before it gets unhashed and loading
2445 		 * the sequence counter after unhashing is finished.
2446 		 *
2447 		 * We can at least predict on it.
2448 		 */
2449 		if (unlikely(d_unhashed(dentry)))
2450 			continue;
2451 		*seqp = seq;
2452 		return dentry;
2453 	}
2454 	return NULL;
2455 }
2456 
2457 /**
2458  * d_lookup - search for a dentry
2459  * @parent: parent dentry
2460  * @name: qstr of name we wish to find
2461  * Returns: dentry, or NULL
2462  *
2463  * d_lookup searches the children of the parent dentry for the name in
2464  * question. If the dentry is found its reference count is incremented and the
2465  * dentry is returned. The caller must use dput to free the entry when it has
2466  * finished using it. %NULL is returned if the dentry does not exist.
2467  */
2468 struct dentry *d_lookup(const struct dentry *parent, const struct qstr *name)
2469 {
2470 	struct dentry *dentry;
2471 	unsigned seq;
2472 
2473 	do {
2474 		seq = read_seqbegin(&rename_lock);
2475 		dentry = __d_lookup(parent, name);
2476 		if (dentry)
2477 			break;
2478 	} while (read_seqretry(&rename_lock, seq));
2479 	return dentry;
2480 }
2481 EXPORT_SYMBOL(d_lookup);
2482 
2483 /**
2484  * __d_lookup - search for a dentry (racy)
2485  * @parent: parent dentry
2486  * @name: qstr of name we wish to find
2487  * Returns: dentry, or NULL
2488  *
2489  * __d_lookup is like d_lookup, however it may (rarely) return a
2490  * false-negative result due to unrelated rename activity.
2491  *
2492  * __d_lookup is slightly faster by avoiding rename_lock read seqlock,
2493  * however it must be used carefully, eg. with a following d_lookup in
2494  * the case of failure.
2495  *
2496  * __d_lookup callers must be commented.
2497  */
2498 struct dentry *__d_lookup(const struct dentry *parent, const struct qstr *name)
2499 {
2500 	unsigned int hash = name->hash;
2501 	struct hlist_bl_head *b = d_hash(hash);
2502 	struct hlist_bl_node *node;
2503 	struct dentry *found = NULL;
2504 	struct dentry *dentry;
2505 
2506 	/*
2507 	 * Note: There is significant duplication with __d_lookup_rcu which is
2508 	 * required to prevent single threaded performance regressions
2509 	 * especially on architectures where smp_rmb (in seqcounts) are costly.
2510 	 * Keep the two functions in sync.
2511 	 */
2512 
2513 	/*
2514 	 * The hash list is protected using RCU.
2515 	 *
2516 	 * Take d_lock when comparing a candidate dentry, to avoid races
2517 	 * with d_move().
2518 	 *
2519 	 * It is possible that concurrent renames can mess up our list
2520 	 * walk here and result in missing our dentry, resulting in the
2521 	 * false-negative result. d_lookup() protects against concurrent
2522 	 * renames using rename_lock seqlock.
2523 	 *
2524 	 * See Documentation/filesystems/path-lookup.txt for more details.
2525 	 */
2526 	rcu_read_lock();
2527 
2528 	hlist_bl_for_each_entry_rcu(dentry, node, b, d_hash) {
2529 
2530 		if (dentry->d_name.hash != hash)
2531 			continue;
2532 
2533 		spin_lock(&dentry->d_lock);
2534 		if (dentry->d_parent != parent)
2535 			goto next;
2536 		if (d_unhashed(dentry))
2537 			goto next;
2538 
2539 		if (!d_same_name(dentry, parent, name))
2540 			goto next;
2541 
2542 		dentry->d_lockref.count++;
2543 		found = dentry;
2544 		spin_unlock(&dentry->d_lock);
2545 		break;
2546 next:
2547 		spin_unlock(&dentry->d_lock);
2548  	}
2549  	rcu_read_unlock();
2550 
2551  	return found;
2552 }
2553 
2554 /**
2555  * d_hash_and_lookup - hash the qstr then search for a dentry
2556  * @dir: Directory to search in
2557  * @name: qstr of name we wish to find
2558  *
2559  * On lookup failure NULL is returned; on bad name - ERR_PTR(-error)
2560  */
2561 struct dentry *d_hash_and_lookup(struct dentry *dir, struct qstr *name)
2562 {
2563 	/*
2564 	 * Check for a fs-specific hash function. Note that we must
2565 	 * calculate the standard hash first, as the d_op->d_hash()
2566 	 * routine may choose to leave the hash value unchanged.
2567 	 */
2568 	name->hash = full_name_hash(dir, name->name, name->len);
2569 	if (dir->d_flags & DCACHE_OP_HASH) {
2570 		int err = dir->d_op->d_hash(dir, name);
2571 		if (unlikely(err < 0))
2572 			return ERR_PTR(err);
2573 	}
2574 	return d_lookup(dir, name);
2575 }
2576 
2577 /*
2578  * When a file is deleted, we have two options:
2579  * - turn this dentry into a negative dentry
2580  * - unhash this dentry and free it.
2581  *
2582  * Usually, we want to just turn this into
2583  * a negative dentry, but if anybody else is
2584  * currently using the dentry or the inode
2585  * we can't do that and we fall back on removing
2586  * it from the hash queues and waiting for
2587  * it to be deleted later when it has no users
2588  */
2589 
2590 /**
2591  * d_delete - delete a dentry
2592  * @dentry: The dentry to delete
2593  *
2594  * Turn the dentry into a negative dentry if possible, otherwise
2595  * remove it from the hash queues so it can be deleted later
2596  */
2597 
2598 void d_delete(struct dentry * dentry)
2599 {
2600 	struct inode *inode = dentry->d_inode;
2601 
2602 	spin_lock(&inode->i_lock);
2603 	spin_lock(&dentry->d_lock);
2604 	/*
2605 	 * Are we the only user?
2606 	 */
2607 	if (dentry->d_lockref.count == 1) {
2608 		if (dentry_negative_policy)
2609 			__d_drop(dentry);
2610 		dentry->d_flags &= ~DCACHE_CANT_MOUNT;
2611 		dentry_unlink_inode(dentry);
2612 	} else {
2613 		__d_drop(dentry);
2614 		spin_unlock(&dentry->d_lock);
2615 		spin_unlock(&inode->i_lock);
2616 	}
2617 }
2618 EXPORT_SYMBOL(d_delete);
2619 
2620 static void __d_rehash(struct dentry *entry)
2621 {
2622 	struct hlist_bl_head *b = d_hash(entry->d_name.hash);
2623 
2624 	hlist_bl_lock(b);
2625 	hlist_bl_add_head_rcu(&entry->d_hash, b);
2626 	hlist_bl_unlock(b);
2627 }
2628 
2629 /**
2630  * d_rehash - add an entry back to the hash
2631  * @entry: dentry to add to the hash
2632  *
2633  * Adds a dentry to the hash according to its name.
2634  */
2635 
2636 void d_rehash(struct dentry * entry)
2637 {
2638 	spin_lock(&entry->d_lock);
2639 	__d_rehash(entry);
2640 	spin_unlock(&entry->d_lock);
2641 }
2642 EXPORT_SYMBOL(d_rehash);
2643 
2644 static inline unsigned start_dir_add(struct inode *dir)
2645 {
2646 	preempt_disable_nested();
2647 	for (;;) {
2648 		unsigned n = READ_ONCE(dir->i_dir_seq);
2649 		if (!(n & 1) && try_cmpxchg(&dir->i_dir_seq, &n, n + 1))
2650 			return n;
2651 		cpu_relax();
2652 	}
2653 }
2654 
2655 static inline void end_dir_add(struct inode *dir, unsigned int n)
2656 {
2657 	smp_store_release(&dir->i_dir_seq, n + 2);
2658 	preempt_enable_nested();
2659 }
2660 
2661 static void d_wait_lookup(struct dentry *dentry)
2662 {
2663 	if (likely(d_in_lookup(dentry))) {
2664 		dentry->d_flags |= DCACHE_LOOKUP_WAITERS;
2665 		wait_var_event_spinlock(&dentry->d_flags,
2666 					!d_in_lookup(dentry),
2667 					&dentry->d_lock);
2668 	}
2669 }
2670 
2671 struct dentry *d_alloc_parallel(struct dentry *parent,
2672 				const struct qstr *name)
2673 {
2674 	unsigned int hash = name->hash;
2675 	struct hlist_bl_head *b = in_lookup_hash(parent, hash);
2676 	struct hlist_bl_node *node;
2677 	struct dentry *new = __d_alloc(parent->d_sb, name);
2678 	struct dentry *dentry;
2679 	unsigned seq, r_seq, d_seq;
2680 
2681 	if (unlikely(!new))
2682 		return ERR_PTR(-ENOMEM);
2683 
2684 	new->d_flags |= DCACHE_PAR_LOOKUP;
2685 	spin_lock(&parent->d_lock);
2686 	new->d_parent = dget_dlock(parent);
2687 	hlist_add_head(&new->d_sib, &parent->d_children);
2688 	if (parent->d_flags & DCACHE_DISCONNECTED)
2689 		new->d_flags |= DCACHE_DISCONNECTED;
2690 	spin_unlock(&parent->d_lock);
2691 
2692 retry:
2693 	rcu_read_lock();
2694 	seq = smp_load_acquire(&parent->d_inode->i_dir_seq);
2695 	r_seq = read_seqbegin(&rename_lock);
2696 	dentry = __d_lookup_rcu(parent, name, &d_seq);
2697 	if (unlikely(dentry)) {
2698 		if (!lockref_get_not_dead(&dentry->d_lockref)) {
2699 			rcu_read_unlock();
2700 			goto retry;
2701 		}
2702 		if (read_seqcount_retry(&dentry->d_seq, d_seq)) {
2703 			rcu_read_unlock();
2704 			dput(dentry);
2705 			goto retry;
2706 		}
2707 		rcu_read_unlock();
2708 		dput(new);
2709 		return dentry;
2710 	}
2711 	if (unlikely(read_seqretry(&rename_lock, r_seq))) {
2712 		rcu_read_unlock();
2713 		goto retry;
2714 	}
2715 
2716 	if (unlikely(seq & 1)) {
2717 		rcu_read_unlock();
2718 		goto retry;
2719 	}
2720 
2721 	hlist_bl_lock(b);
2722 	if (unlikely(READ_ONCE(parent->d_inode->i_dir_seq) != seq)) {
2723 		hlist_bl_unlock(b);
2724 		rcu_read_unlock();
2725 		goto retry;
2726 	}
2727 	/*
2728 	 * No changes for the parent since the beginning of d_lookup().
2729 	 * Since all removals from the chain happen with hlist_bl_lock(),
2730 	 * any potential in-lookup matches are going to stay here until
2731 	 * we unlock the chain.  All fields are stable in everything
2732 	 * we encounter.
2733 	 */
2734 	hlist_bl_for_each_entry(dentry, node, b, d_in_lookup_hash) {
2735 		if (dentry->d_name.hash != hash)
2736 			continue;
2737 		if (dentry->d_parent != parent)
2738 			continue;
2739 		if (!d_same_name(dentry, parent, name))
2740 			continue;
2741 		hlist_bl_unlock(b);
2742 		/* now we can try to grab a reference */
2743 		if (!lockref_get_not_dead(&dentry->d_lockref)) {
2744 			rcu_read_unlock();
2745 			goto retry;
2746 		}
2747 
2748 		rcu_read_unlock();
2749 		/*
2750 		 * somebody is likely to be still doing lookup for it;
2751 		 * wait for them to finish
2752 		 */
2753 		spin_lock(&dentry->d_lock);
2754 		d_wait_lookup(dentry);
2755 		/*
2756 		 * it's not in-lookup anymore; in principle we should repeat
2757 		 * everything from dcache lookup, but it's likely to be what
2758 		 * d_lookup() would've found anyway.  If it is, just return it;
2759 		 * otherwise we really have to repeat the whole thing.
2760 		 */
2761 		if (unlikely(dentry->d_name.hash != hash))
2762 			goto mismatch;
2763 		if (unlikely(dentry->d_parent != parent))
2764 			goto mismatch;
2765 		if (unlikely(d_unhashed(dentry)))
2766 			goto mismatch;
2767 		if (unlikely(!d_same_name(dentry, parent, name)))
2768 			goto mismatch;
2769 		/* OK, it *is* a hashed match; return it */
2770 		spin_unlock(&dentry->d_lock);
2771 		dput(new);
2772 		return dentry;
2773 	}
2774 	rcu_read_unlock();
2775 	hlist_bl_add_head(&new->d_in_lookup_hash, b);
2776 	hlist_bl_unlock(b);
2777 	return new;
2778 mismatch:
2779 	spin_unlock(&dentry->d_lock);
2780 	dput(dentry);
2781 	goto retry;
2782 }
2783 EXPORT_SYMBOL(d_alloc_parallel);
2784 
2785 /*
2786  * Move dentry from in-lookup state to busy-negative one.
2787  *
2788  * From now on d_in_lookup(dentry) will return false and dentry is gone from
2789  * in-lookup hash.
2790  *
2791  * Anyone who had been waiting on it in d_alloc_parallel() is free to
2792  * proceed after that.  Note that waking such waiters up is left to
2793  * the callers; PREEMPT_RT kernels can't have that wakeup done while
2794  * in write-side critical area for ->i_dir_seq, so it's done by calling
2795  * __d_wake_in_lookup_waiters() once it's safe to do so.
2796  *
2797  * Both __d_lookup_unhash() and __d_wake_in_lookup_waiters() should
2798  * be called within the same ->d_lock scope.  PAR_LOOKUP is cleared
2799  * here, while LOOKUP_WAITERS (set by somebody finding dentry in
2800  * the in-lookup hash and setting down to wait) is checked and cleared
2801  * in __d_wake_in_lookup_waiters().  Both are gone by the end of
2802  * ->d_lock scope.
2803  */
2804 static void __d_lookup_unhash(struct dentry *dentry)
2805 {
2806 	struct hlist_bl_head *b;
2807 
2808 	lockdep_assert_held(&dentry->d_lock);
2809 
2810 	b = in_lookup_hash(dentry->d_parent, dentry->d_name.hash);
2811 	hlist_bl_lock(b);
2812 	dentry->d_flags &= ~DCACHE_PAR_LOOKUP;
2813 	__hlist_bl_del(&dentry->d_in_lookup_hash);
2814 	hlist_bl_unlock(b);
2815 	dentry->waiters = NULL;
2816 }
2817 
2818 static inline void __d_wake_in_lookup_waiters(struct dentry *dentry)
2819 {
2820 	if (dentry->d_flags & DCACHE_LOOKUP_WAITERS) {
2821 		wake_up_var_locked(&dentry->d_flags, &dentry->d_lock);
2822 		dentry->d_flags &= ~DCACHE_LOOKUP_WAITERS;
2823 	}
2824 }
2825 
2826 void __d_lookup_unhash_wake(struct dentry *dentry)
2827 {
2828 	spin_lock(&dentry->d_lock);
2829 	__d_lookup_unhash(dentry);
2830 	__d_wake_in_lookup_waiters(dentry);
2831 	spin_unlock(&dentry->d_lock);
2832 }
2833 EXPORT_SYMBOL(__d_lookup_unhash_wake);
2834 
2835 /* inode->i_lock held if inode is non-NULL */
2836 
2837 static inline void __d_add(struct dentry *dentry, struct inode *inode,
2838 			   const struct dentry_operations *ops)
2839 {
2840 	struct inode *dir = NULL;
2841 	unsigned n;
2842 	spin_lock(&dentry->d_lock);
2843 	if (unlikely(d_in_lookup(dentry))) {
2844 		dir = dentry->d_parent->d_inode;
2845 		n = start_dir_add(dir);
2846 		__d_lookup_unhash(dentry);
2847 	}
2848 	if (unlikely(ops))
2849 		d_set_d_op(dentry, ops);
2850 	if (inode) {
2851 		unsigned add_flags = d_flags_for_inode(inode);
2852 		hlist_add_head(&dentry->d_alias, &inode->i_dentry);
2853 		raw_write_seqcount_begin(&dentry->d_seq);
2854 		__d_set_inode_and_type(dentry, inode, add_flags);
2855 		raw_write_seqcount_end(&dentry->d_seq);
2856 		fsnotify_update_flags(dentry);
2857 	}
2858 	__d_rehash(dentry);
2859 	if (dir) {
2860 		end_dir_add(dir, n);
2861 		__d_wake_in_lookup_waiters(dentry);
2862 	}
2863 	spin_unlock(&dentry->d_lock);
2864 	if (inode)
2865 		spin_unlock(&inode->i_lock);
2866 }
2867 
2868 /**
2869  * d_add - add dentry to hash queues
2870  * @entry: dentry to add
2871  * @inode: The inode to attach to this dentry
2872  *
2873  * This adds the entry to the hash queues and initializes @inode.
2874  * The entry was actually filled in earlier during d_alloc().
2875  */
2876 
2877 void d_add(struct dentry *entry, struct inode *inode)
2878 {
2879 	if (inode) {
2880 		security_d_instantiate(entry, inode);
2881 		spin_lock(&inode->i_lock);
2882 	}
2883 	__d_add(entry, inode, NULL);
2884 }
2885 EXPORT_SYMBOL(d_add);
2886 
2887 struct dentry *d_make_persistent(struct dentry *dentry, struct inode *inode)
2888 {
2889 	WARN_ON(d_really_is_positive(dentry));
2890 	WARN_ON(!inode);
2891 	security_d_instantiate(dentry, inode);
2892 	spin_lock(&inode->i_lock);
2893 	spin_lock(&dentry->d_lock);
2894 	__d_instantiate(dentry, inode);
2895 	dentry->d_flags |= DCACHE_PERSISTENT;
2896 	dget_dlock(dentry);
2897 	if (d_unhashed(dentry))
2898 		__d_rehash(dentry);
2899 	spin_unlock(&dentry->d_lock);
2900 	spin_unlock(&inode->i_lock);
2901 	return dentry;
2902 }
2903 EXPORT_SYMBOL(d_make_persistent);
2904 
2905 static void swap_names(struct dentry *dentry, struct dentry *target)
2906 {
2907 	if (unlikely(dname_external(target))) {
2908 		if (unlikely(dname_external(dentry))) {
2909 			/*
2910 			 * Both external: swap the pointers
2911 			 */
2912 			swap(target->__d_name.name, dentry->__d_name.name);
2913 		} else {
2914 			/*
2915 			 * dentry:internal, target:external.  Steal target's
2916 			 * storage and make target internal.
2917 			 */
2918 			dentry->__d_name.name = target->__d_name.name;
2919 			target->d_shortname = dentry->d_shortname;
2920 			target->__d_name.name = target->d_shortname.string;
2921 		}
2922 	} else {
2923 		if (unlikely(dname_external(dentry))) {
2924 			/*
2925 			 * dentry:external, target:internal.  Give dentry's
2926 			 * storage to target and make dentry internal
2927 			 */
2928 			target->__d_name.name = dentry->__d_name.name;
2929 			dentry->d_shortname = target->d_shortname;
2930 			dentry->__d_name.name = dentry->d_shortname.string;
2931 		} else {
2932 			/*
2933 			 * Both are internal.
2934 			 */
2935 			for (int i = 0; i < DNAME_INLINE_WORDS; i++)
2936 				swap(dentry->d_shortname.words[i],
2937 				     target->d_shortname.words[i]);
2938 		}
2939 	}
2940 	swap(dentry->__d_name.hash_len, target->__d_name.hash_len);
2941 }
2942 
2943 static void copy_name(struct dentry *dentry, struct dentry *target)
2944 {
2945 	struct external_name *old_name = NULL;
2946 	if (unlikely(dname_external(dentry)))
2947 		old_name = external_name(dentry);
2948 	if (unlikely(dname_external(target))) {
2949 		atomic_inc(&external_name(target)->count);
2950 		dentry->__d_name = target->__d_name;
2951 	} else {
2952 		dentry->d_shortname = target->d_shortname;
2953 		dentry->__d_name.name = dentry->d_shortname.string;
2954 		dentry->__d_name.hash_len = target->__d_name.hash_len;
2955 	}
2956 	if (old_name && likely(atomic_dec_and_test(&old_name->count)))
2957 		kfree_rcu(old_name, head);
2958 }
2959 
2960 /*
2961  * __d_move - move a dentry
2962  * @dentry: entry to move
2963  * @target: new dentry
2964  * @exchange: exchange the two dentries
2965  *
2966  * Update the dcache to reflect the move of a file name. Negative dcache
2967  * entries should not be moved in this way. Caller must hold rename_lock, the
2968  * i_rwsem of the source and target directories (exclusively), and the sb->
2969  * s_vfs_rename_mutex if they differ. See lock_rename().
2970  */
2971 static void __d_move(struct dentry *dentry, struct dentry *target,
2972 		     bool exchange)
2973 {
2974 	struct dentry *old_parent, *p;
2975 	struct inode *dir = NULL;
2976 	unsigned n;
2977 
2978 	WARN_ON(!dentry->d_inode);
2979 	if (WARN_ON(dentry == target))
2980 		return;
2981 
2982 	BUG_ON(d_ancestor(target, dentry));
2983 	old_parent = dentry->d_parent;
2984 	p = d_ancestor(old_parent, target);
2985 	if (IS_ROOT(dentry)) {
2986 		BUG_ON(p);
2987 		spin_lock(&target->d_parent->d_lock);
2988 	} else if (!p) {
2989 		/* target is not a descendent of dentry->d_parent */
2990 		spin_lock(&target->d_parent->d_lock);
2991 		spin_lock_nested(&old_parent->d_lock, DENTRY_D_LOCK_NESTED);
2992 	} else {
2993 		BUG_ON(p == dentry);
2994 		spin_lock(&old_parent->d_lock);
2995 		if (p != target)
2996 			spin_lock_nested(&target->d_parent->d_lock,
2997 					DENTRY_D_LOCK_NESTED);
2998 	}
2999 	spin_lock_nested(&dentry->d_lock, 2);
3000 	spin_lock_nested(&target->d_lock, 3);
3001 
3002 	if (unlikely(d_in_lookup(target))) {
3003 		dir = target->d_parent->d_inode;
3004 		n = start_dir_add(dir);
3005 		__d_lookup_unhash(target);
3006 	}
3007 
3008 	write_seqcount_begin(&dentry->d_seq);
3009 	write_seqcount_begin_nested(&target->d_seq, DENTRY_D_LOCK_NESTED);
3010 
3011 	/* unhash both */
3012 	if (!d_unhashed(dentry))
3013 		___d_drop(dentry);
3014 	if (!d_unhashed(target))
3015 		___d_drop(target);
3016 
3017 	/* ... and switch them in the tree */
3018 	dentry->d_parent = target->d_parent;
3019 	if (!exchange) {
3020 		copy_name(dentry, target);
3021 		target->d_hash.pprev = NULL;
3022 		dentry->d_parent->d_lockref.count++;
3023 		if (dentry != old_parent) /* wasn't IS_ROOT */
3024 			WARN_ON(!--old_parent->d_lockref.count);
3025 	} else {
3026 		target->d_parent = old_parent;
3027 		swap_names(dentry, target);
3028 		if (!hlist_unhashed(&target->d_sib))
3029 			__hlist_del(&target->d_sib);
3030 		hlist_add_head(&target->d_sib, &target->d_parent->d_children);
3031 		__d_rehash(target);
3032 		fsnotify_update_flags(target);
3033 	}
3034 	if (!hlist_unhashed(&dentry->d_sib))
3035 		__hlist_del(&dentry->d_sib);
3036 	hlist_add_head(&dentry->d_sib, &dentry->d_parent->d_children);
3037 	__d_rehash(dentry);
3038 	fsnotify_update_flags(dentry);
3039 	fscrypt_handle_d_move(dentry);
3040 
3041 	write_seqcount_end(&target->d_seq);
3042 	write_seqcount_end(&dentry->d_seq);
3043 
3044 	if (dir) {
3045 		end_dir_add(dir, n);
3046 		__d_wake_in_lookup_waiters(target);
3047 	}
3048 	if (dentry->d_parent != old_parent)
3049 		spin_unlock(&dentry->d_parent->d_lock);
3050 	if (dentry != old_parent)
3051 		spin_unlock(&old_parent->d_lock);
3052 	spin_unlock(&target->d_lock);
3053 	spin_unlock(&dentry->d_lock);
3054 }
3055 
3056 /*
3057  * d_move - move a dentry
3058  * @dentry: entry to move
3059  * @target: new dentry
3060  *
3061  * Update the dcache to reflect the move of a file name. Negative
3062  * dcache entries should not be moved in this way. See the locking
3063  * requirements for __d_move.
3064  */
3065 void d_move(struct dentry *dentry, struct dentry *target)
3066 {
3067 	write_seqlock(&rename_lock);
3068 	__d_move(dentry, target, false);
3069 	write_sequnlock(&rename_lock);
3070 }
3071 EXPORT_SYMBOL(d_move);
3072 
3073 /*
3074  * d_exchange - exchange two dentries
3075  * @dentry1: first dentry
3076  * @dentry2: second dentry
3077  */
3078 void d_exchange(struct dentry *dentry1, struct dentry *dentry2)
3079 {
3080 	write_seqlock(&rename_lock);
3081 
3082 	WARN_ON(!dentry1->d_inode);
3083 	WARN_ON(!dentry2->d_inode);
3084 	WARN_ON(IS_ROOT(dentry1));
3085 	WARN_ON(IS_ROOT(dentry2));
3086 
3087 	__d_move(dentry1, dentry2, true);
3088 
3089 	write_sequnlock(&rename_lock);
3090 }
3091 EXPORT_SYMBOL(d_exchange);
3092 
3093 /**
3094  * d_ancestor - search for an ancestor
3095  * @p1: ancestor dentry
3096  * @p2: child dentry
3097  *
3098  * Returns the ancestor dentry of p2 which is a child of p1, if p1 is
3099  * an ancestor of p2, else NULL.
3100  */
3101 struct dentry *d_ancestor(struct dentry *p1, struct dentry *p2)
3102 {
3103 	struct dentry *p;
3104 
3105 	for (p = p2; !IS_ROOT(p); p = p->d_parent) {
3106 		if (p->d_parent == p1)
3107 			return p;
3108 	}
3109 	return NULL;
3110 }
3111 
3112 /*
3113  * This helper attempts to cope with remotely renamed directories
3114  *
3115  * It assumes that the caller is already holding
3116  * dentry->d_parent->d_inode->i_rwsem, and rename_lock
3117  *
3118  * Note: If ever the locking in lock_rename() changes, then please
3119  * remember to update this too...
3120  */
3121 static int __d_unalias(struct dentry *dentry, struct dentry *alias)
3122 {
3123 	struct mutex *m1 = NULL;
3124 	struct rw_semaphore *m2 = NULL;
3125 	int ret = -ESTALE;
3126 
3127 	/* If alias and dentry share a parent, then no extra locks required */
3128 	if (alias->d_parent == dentry->d_parent)
3129 		goto out_unalias;
3130 
3131 	/* See lock_rename() */
3132 	if (!mutex_trylock(&dentry->d_sb->s_vfs_rename_mutex))
3133 		goto out_err;
3134 	m1 = &dentry->d_sb->s_vfs_rename_mutex;
3135 	if (!inode_trylock_shared(alias->d_parent->d_inode))
3136 		goto out_err;
3137 	m2 = &alias->d_parent->d_inode->i_rwsem;
3138 out_unalias:
3139 	if (alias->d_op && alias->d_op->d_unalias_trylock &&
3140 	    !alias->d_op->d_unalias_trylock(alias))
3141 		goto out_err;
3142 	__d_move(alias, dentry, false);
3143 	if (alias->d_op && alias->d_op->d_unalias_unlock)
3144 		alias->d_op->d_unalias_unlock(alias);
3145 	ret = 0;
3146 out_err:
3147 	if (m2)
3148 		up_read(m2);
3149 	if (m1)
3150 		mutex_unlock(m1);
3151 	return ret;
3152 }
3153 
3154 struct dentry *d_splice_alias_ops(struct inode *inode, struct dentry *dentry,
3155 				  const struct dentry_operations *ops)
3156 {
3157 	if (IS_ERR(inode))
3158 		return ERR_CAST(inode);
3159 
3160 	BUG_ON(!d_unhashed(dentry));
3161 
3162 	if (!inode)
3163 		goto out;
3164 
3165 	security_d_instantiate(dentry, inode);
3166 	spin_lock(&inode->i_lock);
3167 	if (S_ISDIR(inode->i_mode)) {
3168 		struct dentry *new = __d_find_dir_alias(inode);
3169 		if (unlikely(new)) {
3170 			/* The reference to new ensures it remains an alias */
3171 			spin_unlock(&inode->i_lock);
3172 			write_seqlock(&rename_lock);
3173 			if (unlikely(d_ancestor(new, dentry))) {
3174 				write_sequnlock(&rename_lock);
3175 				dput(new);
3176 				new = ERR_PTR(-ELOOP);
3177 				pr_warn_ratelimited(
3178 					"VFS: Lookup of '%s' in %s %s"
3179 					" would have caused loop\n",
3180 					dentry->d_name.name,
3181 					inode->i_sb->s_type->name,
3182 					inode->i_sb->s_id);
3183 			} else if (!IS_ROOT(new)) {
3184 				struct dentry *old_parent = dget(new->d_parent);
3185 				int err = __d_unalias(dentry, new);
3186 				write_sequnlock(&rename_lock);
3187 				if (err) {
3188 					dput(new);
3189 					new = ERR_PTR(err);
3190 				}
3191 				dput(old_parent);
3192 			} else {
3193 				__d_move(new, dentry, false);
3194 				write_sequnlock(&rename_lock);
3195 			}
3196 			iput(inode);
3197 			return new;
3198 		}
3199 	}
3200 out:
3201 	__d_add(dentry, inode, ops);
3202 	return NULL;
3203 }
3204 
3205 /**
3206  * d_splice_alias - splice a disconnected dentry into the tree if one exists
3207  * @inode:  the inode which may have a disconnected dentry
3208  * @dentry: a negative dentry which we want to point to the inode.
3209  *
3210  * If inode is a directory and has an IS_ROOT alias, then d_move that in
3211  * place of the given dentry and return it, else simply d_add the inode
3212  * to the dentry and return NULL.
3213  *
3214  * If a non-IS_ROOT directory is found, the filesystem is corrupt, and
3215  * we should error out: directories can't have multiple aliases.
3216  *
3217  * This is needed in the lookup routine of any filesystem that is exportable
3218  * (via knfsd) so that we can build dcache paths to directories effectively.
3219  *
3220  * If a dentry was found and moved, then it is returned.  Otherwise NULL
3221  * is returned.  This matches the expected return value of ->lookup.
3222  *
3223  * Cluster filesystems may call this function with a negative, hashed dentry.
3224  * In that case, we know that the inode will be a regular file, and also this
3225  * will only occur during atomic_open. So we need to check for the dentry
3226  * being already hashed only in the final case.
3227  */
3228 struct dentry *d_splice_alias(struct inode *inode, struct dentry *dentry)
3229 {
3230 	return d_splice_alias_ops(inode, dentry, NULL);
3231 }
3232 EXPORT_SYMBOL(d_splice_alias);
3233 
3234 /*
3235  * Test whether new_dentry is a subdirectory of old_dentry.
3236  *
3237  * Trivially implemented using the dcache structure
3238  */
3239 
3240 /**
3241  * is_subdir - is new dentry a subdirectory of old_dentry
3242  * @new_dentry: new dentry
3243  * @old_dentry: old dentry
3244  *
3245  * Returns true if new_dentry is a subdirectory of the parent (at any depth).
3246  * Returns false otherwise.
3247  * Caller must ensure that "new_dentry" is pinned before calling is_subdir()
3248  */
3249 
3250 bool is_subdir(struct dentry *new_dentry, struct dentry *old_dentry)
3251 {
3252 	bool subdir;
3253 	unsigned seq;
3254 
3255 	if (new_dentry == old_dentry)
3256 		return true;
3257 
3258 	/* Access d_parent under rcu as d_move() may change it. */
3259 	rcu_read_lock();
3260 	seq = read_seqbegin(&rename_lock);
3261 	subdir = d_ancestor(old_dentry, new_dentry);
3262 	 /* Try lockless once... */
3263 	if (read_seqretry(&rename_lock, seq)) {
3264 		/* ...else acquire lock for progress even on deep chains. */
3265 		read_seqlock_excl(&rename_lock);
3266 		subdir = d_ancestor(old_dentry, new_dentry);
3267 		read_sequnlock_excl(&rename_lock);
3268 	}
3269 	rcu_read_unlock();
3270 	return subdir;
3271 }
3272 EXPORT_SYMBOL(is_subdir);
3273 
3274 void d_mark_tmpfile(struct file *file, struct inode *inode)
3275 {
3276 	struct dentry *dentry = file->f_path.dentry;
3277 
3278 	BUG_ON(dname_external(dentry) ||
3279 		d_really_is_positive(dentry) ||
3280 		!d_unlinked(dentry));
3281 	spin_lock(&dentry->d_parent->d_lock);
3282 	spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
3283 	dentry->__d_name.len = sprintf(dentry->d_shortname.string, "#%llu",
3284 				(unsigned long long)inode->i_ino);
3285 	spin_unlock(&dentry->d_lock);
3286 	spin_unlock(&dentry->d_parent->d_lock);
3287 }
3288 EXPORT_SYMBOL(d_mark_tmpfile);
3289 
3290 int d_mark_tmpfile_name(struct file *file, const struct qstr *name)
3291 {
3292 	struct dentry *dentry = file->f_path.dentry;
3293 	char *dname = dentry->d_shortname.string;
3294 
3295 	if (unlikely(dname_external(dentry) ||
3296 		     d_really_is_positive(dentry) ||
3297 		     !d_unlinked(dentry)))
3298 		return -EINVAL;
3299 	if (unlikely(name->len > DNAME_INLINE_LEN - 1))
3300 		return -ENAMETOOLONG;
3301 
3302 	spin_lock(&dentry->d_parent->d_lock);
3303 	spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
3304 	dentry->__d_name.len = name->len;
3305 	memcpy(dname, name->name, name->len);
3306 	dname[name->len] = '\0';
3307 	spin_unlock(&dentry->d_lock);
3308 	spin_unlock(&dentry->d_parent->d_lock);
3309 	return 0;
3310 }
3311 EXPORT_SYMBOL(d_mark_tmpfile_name);
3312 
3313 void d_tmpfile(struct file *file, struct inode *inode)
3314 {
3315 	struct dentry *dentry = file->f_path.dentry;
3316 
3317 	inode_dec_link_count(inode);
3318 	d_mark_tmpfile(file, inode);
3319 	d_instantiate(dentry, inode);
3320 }
3321 EXPORT_SYMBOL(d_tmpfile);
3322 
3323 /*
3324  * Obtain inode number of the parent dentry.
3325  */
3326 ino_t d_parent_ino(struct dentry *dentry)
3327 {
3328 	struct dentry *parent;
3329 	struct inode *iparent;
3330 	unsigned seq;
3331 	ino_t ret;
3332 
3333 	scoped_guard(rcu) {
3334 		seq = raw_seqcount_begin(&dentry->d_seq);
3335 		parent = READ_ONCE(dentry->d_parent);
3336 		iparent = d_inode_rcu(parent);
3337 		if (likely(iparent)) {
3338 			ret = iparent->i_ino;
3339 			if (!read_seqcount_retry(&dentry->d_seq, seq))
3340 				return ret;
3341 		}
3342 	}
3343 
3344 	spin_lock(&dentry->d_lock);
3345 	ret = dentry->d_parent->d_inode->i_ino;
3346 	spin_unlock(&dentry->d_lock);
3347 	return ret;
3348 }
3349 EXPORT_SYMBOL(d_parent_ino);
3350 
3351 static __initdata unsigned long dhash_entries;
3352 static int __init set_dhash_entries(char *str)
3353 {
3354 	return kstrtoul(str, 0, &dhash_entries) == 0;
3355 }
3356 __setup("dhash_entries=", set_dhash_entries);
3357 
3358 static void __init dcache_init_early(void)
3359 {
3360 	/* If hashes are distributed across NUMA nodes, defer
3361 	 * hash allocation until vmalloc space is available.
3362 	 */
3363 	if (hashdist)
3364 		return;
3365 
3366 	dentry_hashtable =
3367 		alloc_large_system_hash("Dentry cache",
3368 					sizeof(struct hlist_bl_head),
3369 					dhash_entries,
3370 					13,
3371 					HASH_EARLY | HASH_ZERO,
3372 					&d_hash_shift,
3373 					NULL,
3374 					2,
3375 					0);
3376 	d_hash_shift = 32 - d_hash_shift;
3377 
3378 	runtime_const_init(shift, d_hash_shift);
3379 	runtime_const_init(ptr, dentry_hashtable);
3380 }
3381 
3382 static void __init dcache_init(void)
3383 {
3384 	/*
3385 	 * A constructor could be added for stable state like the lists,
3386 	 * but it is probably not worth it because of the cache nature
3387 	 * of the dcache.
3388 	 */
3389 	__dentry_cache = KMEM_CACHE_USERCOPY(dentry,
3390 		SLAB_RECLAIM_ACCOUNT|SLAB_PANIC|SLAB_ACCOUNT,
3391 		d_shortname.string);
3392 	runtime_const_init(ptr, __dentry_cache);
3393 
3394 	/* Hash may have been set up in dcache_init_early */
3395 	if (!hashdist)
3396 		return;
3397 
3398 	dentry_hashtable =
3399 		alloc_large_system_hash("Dentry cache",
3400 					sizeof(struct hlist_bl_head),
3401 					dhash_entries,
3402 					13,
3403 					HASH_ZERO,
3404 					&d_hash_shift,
3405 					NULL,
3406 					2,
3407 					0);
3408 	d_hash_shift = 32 - d_hash_shift;
3409 
3410 	runtime_const_init(shift, d_hash_shift);
3411 	runtime_const_init(ptr, dentry_hashtable);
3412 }
3413 
3414 void __init vfs_caches_init_early(void)
3415 {
3416 	int i;
3417 
3418 	for (i = 0; i < ARRAY_SIZE(in_lookup_hashtable); i++)
3419 		INIT_HLIST_BL_HEAD(&in_lookup_hashtable[i]);
3420 
3421 	dcache_init_early();
3422 	inode_init_early();
3423 }
3424 
3425 void __init vfs_caches_init(void)
3426 {
3427 	filename_init();
3428 	dcache_init();
3429 	inode_init();
3430 	files_init();
3431 	files_maxfiles_init();
3432 	mnt_init();
3433 	bdev_cache_init();
3434 	chrdev_init();
3435 }
3436