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