xref: /linux/fs/inode.c (revision a1a8bab74176eed204a3139ab7ad840caa3d73b8)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * (C) 1997 Linus Torvalds
4  * (C) 1999 Andrea Arcangeli <andrea@suse.de> (dynamic inode allocation)
5  */
6 #include <linux/export.h>
7 #include <linux/fs.h>
8 #include <linux/filelock.h>
9 #include <linux/mm.h>
10 #include <linux/backing-dev.h>
11 #include <linux/hash.h>
12 #include <linux/swap.h>
13 #include <linux/security.h>
14 #include <linux/cdev.h>
15 #include <linux/memblock.h>
16 #include <linux/fsnotify.h>
17 #include <linux/fsverity.h>
18 #include <linux/mount.h>
19 #include <linux/posix_acl.h>
20 #include <linux/ratelimit.h>
21 #include <linux/list_lru.h>
22 #include <linux/iversion.h>
23 #include <linux/rw_hint.h>
24 #include <linux/seq_file.h>
25 #include <linux/debugfs.h>
26 #include <trace/events/writeback.h>
27 #define CREATE_TRACE_POINTS
28 #include <trace/events/timestamp.h>
29 
30 #include "internal.h"
31 
32 /*
33  * Inode locking rules:
34  *
35  * inode->i_lock protects:
36  *   inode->i_state, inode->i_hash, __iget(), inode->i_io_list
37  * Inode LRU list locks protect:
38  *   inode->i_sb->s_inode_lru, inode->i_lru
39  * inode->i_sb->s_inode_list_lock protects:
40  *   inode->i_sb->s_inodes, inode->i_sb_list
41  * bdi->wb.list_lock protects:
42  *   bdi->wb.b_{dirty,io,more_io,dirty_time}, inode->i_io_list
43  * inode_hash_lock protects:
44  *   inode_hashtable, inode->i_hash
45  *
46  * Lock ordering:
47  *
48  * inode->i_sb->s_inode_list_lock
49  *   inode->i_lock
50  *     Inode LRU list locks
51  *
52  * bdi->wb.list_lock
53  *   inode->i_lock
54  *
55  * inode_hash_lock
56  *   inode->i_lock
57  */
58 
59 static unsigned int i_hash_mask __ro_after_init;
60 static unsigned int i_hash_shift __ro_after_init;
61 static struct hlist_head *inode_hashtable __ro_after_init;
62 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(inode_hash_lock);
63 
64 /*
65  * Empty aops. Can be used for the cases where the user does not
66  * define any of the address_space operations.
67  */
68 const struct address_space_operations empty_aops = {
69 };
70 EXPORT_SYMBOL(empty_aops);
71 
72 static DEFINE_PER_CPU(unsigned long, nr_inodes);
73 static DEFINE_PER_CPU(unsigned long, nr_unused);
74 
75 static struct kmem_cache *inode_cachep __ro_after_init;
76 
77 static long get_nr_inodes(void)
78 {
79 	int i;
80 	long sum = 0;
81 	for_each_possible_cpu(i)
82 		sum += per_cpu(nr_inodes, i);
83 	return sum < 0 ? 0 : sum;
84 }
85 
86 static inline long get_nr_inodes_unused(void)
87 {
88 	int i;
89 	long sum = 0;
90 	for_each_possible_cpu(i)
91 		sum += per_cpu(nr_unused, i);
92 	return sum < 0 ? 0 : sum;
93 }
94 
95 long get_nr_dirty_inodes(void)
96 {
97 	/* not actually dirty inodes, but a wild approximation */
98 	long nr_dirty = get_nr_inodes() - get_nr_inodes_unused();
99 	return nr_dirty > 0 ? nr_dirty : 0;
100 }
101 
102 #ifdef CONFIG_DEBUG_FS
103 static DEFINE_PER_CPU(long, mg_ctime_updates);
104 static DEFINE_PER_CPU(long, mg_fine_stamps);
105 static DEFINE_PER_CPU(long, mg_ctime_swaps);
106 
107 static unsigned long get_mg_ctime_updates(void)
108 {
109 	unsigned long sum = 0;
110 	int i;
111 
112 	for_each_possible_cpu(i)
113 		sum += data_race(per_cpu(mg_ctime_updates, i));
114 	return sum;
115 }
116 
117 static unsigned long get_mg_fine_stamps(void)
118 {
119 	unsigned long sum = 0;
120 	int i;
121 
122 	for_each_possible_cpu(i)
123 		sum += data_race(per_cpu(mg_fine_stamps, i));
124 	return sum;
125 }
126 
127 static unsigned long get_mg_ctime_swaps(void)
128 {
129 	unsigned long sum = 0;
130 	int i;
131 
132 	for_each_possible_cpu(i)
133 		sum += data_race(per_cpu(mg_ctime_swaps, i));
134 	return sum;
135 }
136 
137 #define mgtime_counter_inc(__var)	this_cpu_inc(__var)
138 
139 static int mgts_show(struct seq_file *s, void *p)
140 {
141 	unsigned long ctime_updates = get_mg_ctime_updates();
142 	unsigned long ctime_swaps = get_mg_ctime_swaps();
143 	unsigned long fine_stamps = get_mg_fine_stamps();
144 	unsigned long floor_swaps = timekeeping_get_mg_floor_swaps();
145 
146 	seq_printf(s, "%lu %lu %lu %lu\n",
147 		   ctime_updates, ctime_swaps, fine_stamps, floor_swaps);
148 	return 0;
149 }
150 
151 DEFINE_SHOW_ATTRIBUTE(mgts);
152 
153 static int __init mg_debugfs_init(void)
154 {
155 	debugfs_create_file("multigrain_timestamps", S_IFREG | S_IRUGO, NULL, NULL, &mgts_fops);
156 	return 0;
157 }
158 late_initcall(mg_debugfs_init);
159 
160 #else /* ! CONFIG_DEBUG_FS */
161 
162 #define mgtime_counter_inc(__var)	do { } while (0)
163 
164 #endif /* CONFIG_DEBUG_FS */
165 
166 /*
167  * Handle nr_inode sysctl
168  */
169 #ifdef CONFIG_SYSCTL
170 /*
171  * Statistics gathering..
172  */
173 static struct inodes_stat_t inodes_stat;
174 
175 static int proc_nr_inodes(const struct ctl_table *table, int write, void *buffer,
176 			  size_t *lenp, loff_t *ppos)
177 {
178 	inodes_stat.nr_inodes = get_nr_inodes();
179 	inodes_stat.nr_unused = get_nr_inodes_unused();
180 	return proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
181 }
182 
183 static const struct ctl_table inodes_sysctls[] = {
184 	{
185 		.procname	= "inode-nr",
186 		.data		= &inodes_stat,
187 		.maxlen		= 2*sizeof(long),
188 		.mode		= 0444,
189 		.proc_handler	= proc_nr_inodes,
190 	},
191 	{
192 		.procname	= "inode-state",
193 		.data		= &inodes_stat,
194 		.maxlen		= 7*sizeof(long),
195 		.mode		= 0444,
196 		.proc_handler	= proc_nr_inodes,
197 	},
198 };
199 
200 static int __init init_fs_inode_sysctls(void)
201 {
202 	register_sysctl_init("fs", inodes_sysctls);
203 	return 0;
204 }
205 early_initcall(init_fs_inode_sysctls);
206 #endif
207 
208 static int no_open(struct inode *inode, struct file *file)
209 {
210 	return -ENXIO;
211 }
212 
213 /**
214  * inode_init_always_gfp - perform inode structure initialisation
215  * @sb: superblock inode belongs to
216  * @inode: inode to initialise
217  * @gfp: allocation flags
218  *
219  * These are initializations that need to be done on every inode
220  * allocation as the fields are not initialised by slab allocation.
221  * If there are additional allocations required @gfp is used.
222  */
223 int inode_init_always_gfp(struct super_block *sb, struct inode *inode, gfp_t gfp)
224 {
225 	static const struct inode_operations empty_iops;
226 	static const struct file_operations no_open_fops = {.open = no_open};
227 	struct address_space *const mapping = &inode->i_data;
228 
229 	inode->i_sb = sb;
230 	inode->i_blkbits = sb->s_blocksize_bits;
231 	inode->i_flags = 0;
232 	inode_state_assign_raw(inode, 0);
233 	atomic64_set(&inode->i_sequence, 0);
234 	atomic_set(&inode->i_count, 1);
235 	inode->i_op = &empty_iops;
236 	inode->i_fop = &no_open_fops;
237 	inode->i_ino = 0;
238 	inode->__i_nlink = 1;
239 	inode->i_opflags = 0;
240 	if (sb->s_xattr)
241 		inode->i_opflags |= IOP_XATTR;
242 	if (sb->s_type->fs_flags & FS_MGTIME)
243 		inode->i_opflags |= IOP_MGTIME;
244 	i_uid_write(inode, 0);
245 	i_gid_write(inode, 0);
246 	atomic_set(&inode->i_writecount, 0);
247 	inode->i_size = 0;
248 	inode->i_write_hint = WRITE_LIFE_NOT_SET;
249 	inode->i_blocks = 0;
250 	inode->i_bytes = 0;
251 	inode->i_generation = 0;
252 	inode->i_pipe = NULL;
253 	inode->i_cdev = NULL;
254 	inode->i_link = NULL;
255 	inode->i_dir_seq = 0;
256 	inode->i_rdev = 0;
257 	inode->dirtied_when = 0;
258 
259 #ifdef CONFIG_CGROUP_WRITEBACK
260 	inode->i_wb_frn_winner = 0;
261 	inode->i_wb_frn_avg_time = 0;
262 	inode->i_wb_frn_history = 0;
263 #endif
264 
265 	spin_lock_init(&inode->i_lock);
266 	lockdep_set_class(&inode->i_lock, &sb->s_type->i_lock_key);
267 
268 	init_rwsem(&inode->i_rwsem);
269 	lockdep_set_class(&inode->i_rwsem, &sb->s_type->i_mutex_key);
270 
271 	atomic_set(&inode->i_dio_count, 0);
272 
273 	mapping->a_ops = &empty_aops;
274 	mapping->host = inode;
275 	mapping->flags = 0;
276 	mapping->wb_err = 0;
277 	atomic_set(&mapping->i_mmap_writable, 0);
278 	mapping_set_gfp_mask(mapping, GFP_HIGHUSER_MOVABLE);
279 	mapping->writeback_index = 0;
280 	init_rwsem(&mapping->invalidate_lock);
281 	lockdep_set_class_and_name(&mapping->invalidate_lock,
282 				   &sb->s_type->invalidate_lock_key,
283 				   "mapping.invalidate_lock");
284 	if (sb->s_iflags & SB_I_STABLE_WRITES)
285 		mapping_set_stable_writes(mapping);
286 	inode->i_private = NULL;
287 	inode->i_mapping = mapping;
288 	INIT_HLIST_HEAD(&inode->i_dentry);	/* buggered by rcu freeing */
289 #ifdef CONFIG_FS_POSIX_ACL
290 	inode->i_acl = inode->i_default_acl = ACL_NOT_CACHED;
291 #endif
292 
293 #ifdef CONFIG_FSNOTIFY
294 	inode->i_fsnotify_mask = 0;
295 #endif
296 	inode->i_flctx = NULL;
297 
298 	if (unlikely(security_inode_alloc(inode, gfp)))
299 		return -ENOMEM;
300 
301 	this_cpu_inc(nr_inodes);
302 
303 	return 0;
304 }
305 EXPORT_SYMBOL(inode_init_always_gfp);
306 
307 void free_inode_nonrcu(struct inode *inode)
308 {
309 	kmem_cache_free(inode_cachep, inode);
310 }
311 EXPORT_SYMBOL(free_inode_nonrcu);
312 
313 static void i_callback(struct rcu_head *head)
314 {
315 	struct inode *inode = container_of(head, struct inode, i_rcu);
316 	if (inode->free_inode)
317 		inode->free_inode(inode);
318 	else
319 		free_inode_nonrcu(inode);
320 }
321 
322 /**
323  *	alloc_inode 	- obtain an inode
324  *	@sb: superblock
325  *
326  *	Allocates a new inode for given superblock.
327  *	Inode wont be chained in superblock s_inodes list
328  *	This means :
329  *	- fs can't be unmount
330  *	- quotas, fsnotify, writeback can't work
331  */
332 struct inode *alloc_inode(struct super_block *sb)
333 {
334 	const struct super_operations *ops = sb->s_op;
335 	struct inode *inode;
336 
337 	if (ops->alloc_inode)
338 		inode = ops->alloc_inode(sb);
339 	else
340 		inode = alloc_inode_sb(sb, inode_cachep, GFP_KERNEL);
341 
342 	if (!inode)
343 		return NULL;
344 
345 	if (unlikely(inode_init_always(sb, inode))) {
346 		if (ops->destroy_inode) {
347 			ops->destroy_inode(inode);
348 			if (!ops->free_inode)
349 				return NULL;
350 		}
351 		inode->free_inode = ops->free_inode;
352 		i_callback(&inode->i_rcu);
353 		return NULL;
354 	}
355 
356 	return inode;
357 }
358 
359 void __destroy_inode(struct inode *inode)
360 {
361 	inode_detach_wb(inode);
362 	security_inode_free(inode);
363 	fsnotify_inode_delete(inode);
364 	locks_free_lock_context(inode);
365 	if (!inode->i_nlink) {
366 		WARN_ON(atomic_long_read(&inode->i_sb->s_remove_count) == 0);
367 		atomic_long_dec(&inode->i_sb->s_remove_count);
368 	}
369 
370 #ifdef CONFIG_FS_POSIX_ACL
371 	if (inode->i_acl && !is_uncached_acl(inode->i_acl))
372 		posix_acl_release(inode->i_acl);
373 	if (inode->i_default_acl && !is_uncached_acl(inode->i_default_acl))
374 		posix_acl_release(inode->i_default_acl);
375 #endif
376 	this_cpu_dec(nr_inodes);
377 }
378 EXPORT_SYMBOL(__destroy_inode);
379 
380 static void destroy_inode(struct inode *inode)
381 {
382 	const struct super_operations *ops = inode->i_sb->s_op;
383 
384 	BUG_ON(!list_empty(&inode->i_lru));
385 	__destroy_inode(inode);
386 	if (ops->destroy_inode) {
387 		ops->destroy_inode(inode);
388 		if (!ops->free_inode)
389 			return;
390 	}
391 	inode->free_inode = ops->free_inode;
392 	call_rcu(&inode->i_rcu, i_callback);
393 }
394 
395 /**
396  * drop_nlink - directly drop an inode's link count
397  * @inode: inode
398  *
399  * This is a low-level filesystem helper to replace any
400  * direct filesystem manipulation of i_nlink.  In cases
401  * where we are attempting to track writes to the
402  * filesystem, a decrement to zero means an imminent
403  * write when the file is truncated and actually unlinked
404  * on the filesystem.
405  */
406 void drop_nlink(struct inode *inode)
407 {
408 	WARN_ON(inode->i_nlink == 0);
409 	inode->__i_nlink--;
410 	if (!inode->i_nlink)
411 		atomic_long_inc(&inode->i_sb->s_remove_count);
412 }
413 EXPORT_SYMBOL(drop_nlink);
414 
415 /**
416  * clear_nlink - directly zero an inode's link count
417  * @inode: inode
418  *
419  * This is a low-level filesystem helper to replace any
420  * direct filesystem manipulation of i_nlink.  See
421  * drop_nlink() for why we care about i_nlink hitting zero.
422  */
423 void clear_nlink(struct inode *inode)
424 {
425 	if (inode->i_nlink) {
426 		inode->__i_nlink = 0;
427 		atomic_long_inc(&inode->i_sb->s_remove_count);
428 	}
429 }
430 EXPORT_SYMBOL(clear_nlink);
431 
432 /**
433  * set_nlink - directly set an inode's link count
434  * @inode: inode
435  * @nlink: new nlink (should be non-zero)
436  *
437  * This is a low-level filesystem helper to replace any
438  * direct filesystem manipulation of i_nlink.
439  */
440 void set_nlink(struct inode *inode, unsigned int nlink)
441 {
442 	if (!nlink) {
443 		clear_nlink(inode);
444 	} else {
445 		/* Yes, some filesystems do change nlink from zero to one */
446 		if (inode->i_nlink == 0)
447 			atomic_long_dec(&inode->i_sb->s_remove_count);
448 
449 		inode->__i_nlink = nlink;
450 	}
451 }
452 EXPORT_SYMBOL(set_nlink);
453 
454 /**
455  * inc_nlink - directly increment an inode's link count
456  * @inode: inode
457  *
458  * This is a low-level filesystem helper to replace any
459  * direct filesystem manipulation of i_nlink.  Currently,
460  * it is only here for parity with dec_nlink().
461  */
462 void inc_nlink(struct inode *inode)
463 {
464 	if (unlikely(inode->i_nlink == 0)) {
465 		WARN_ON(!(inode_state_read_once(inode) & I_LINKABLE));
466 		atomic_long_dec(&inode->i_sb->s_remove_count);
467 	}
468 
469 	inode->__i_nlink++;
470 }
471 EXPORT_SYMBOL(inc_nlink);
472 
473 static void __address_space_init_once(struct address_space *mapping)
474 {
475 	xa_init_flags(&mapping->i_pages, XA_FLAGS_LOCK_IRQ | XA_FLAGS_ACCOUNT);
476 	init_rwsem(&mapping->i_mmap_rwsem);
477 	spin_lock_init(&mapping->i_private_lock);
478 	mapping->i_mmap = RB_ROOT_CACHED;
479 }
480 
481 void address_space_init_once(struct address_space *mapping)
482 {
483 	memset(mapping, 0, sizeof(*mapping));
484 	__address_space_init_once(mapping);
485 }
486 EXPORT_SYMBOL(address_space_init_once);
487 
488 /*
489  * These are initializations that only need to be done
490  * once, because the fields are idempotent across use
491  * of the inode, so let the slab aware of that.
492  */
493 void inode_init_once(struct inode *inode)
494 {
495 	memset(inode, 0, sizeof(*inode));
496 	INIT_HLIST_NODE(&inode->i_hash);
497 	INIT_LIST_HEAD(&inode->i_devices);
498 	INIT_LIST_HEAD(&inode->i_io_list);
499 	INIT_LIST_HEAD(&inode->i_wb_list);
500 	INIT_LIST_HEAD(&inode->i_lru);
501 	INIT_LIST_HEAD(&inode->i_sb_list);
502 	__address_space_init_once(&inode->i_data);
503 	i_size_ordered_init(inode);
504 }
505 EXPORT_SYMBOL(inode_init_once);
506 
507 static void init_once(void *foo)
508 {
509 	struct inode *inode = (struct inode *) foo;
510 
511 	inode_init_once(inode);
512 }
513 
514 struct wait_queue_head *inode_bit_waitqueue(struct wait_bit_queue_entry *wqe,
515 					    struct inode *inode, u32 bit)
516 {
517 	void *bit_address;
518 
519 	bit_address = inode_state_wait_address(inode, bit);
520 	init_wait_var_entry(wqe, bit_address, 0);
521 	return __var_waitqueue(bit_address);
522 }
523 EXPORT_SYMBOL(inode_bit_waitqueue);
524 
525 void wait_on_new_inode(struct inode *inode)
526 {
527 	struct wait_bit_queue_entry wqe;
528 	struct wait_queue_head *wq_head;
529 
530 	spin_lock(&inode->i_lock);
531 	if (!(inode_state_read(inode) & I_NEW)) {
532 		spin_unlock(&inode->i_lock);
533 		return;
534 	}
535 
536 	wq_head = inode_bit_waitqueue(&wqe, inode, __I_NEW);
537 	for (;;) {
538 		prepare_to_wait_event(wq_head, &wqe.wq_entry, TASK_UNINTERRUPTIBLE);
539 		if (!(inode_state_read(inode) & I_NEW))
540 			break;
541 		spin_unlock(&inode->i_lock);
542 		schedule();
543 		spin_lock(&inode->i_lock);
544 	}
545 	finish_wait(wq_head, &wqe.wq_entry);
546 	WARN_ON(inode_state_read(inode) & I_NEW);
547 	spin_unlock(&inode->i_lock);
548 }
549 EXPORT_SYMBOL(wait_on_new_inode);
550 
551 static void __inode_lru_list_add(struct inode *inode, bool rotate)
552 {
553 	lockdep_assert_held(&inode->i_lock);
554 
555 	if (inode_state_read(inode) & (I_DIRTY_ALL | I_SYNC | I_FREEING | I_WILL_FREE))
556 		return;
557 	if (icount_read(inode))
558 		return;
559 	if (!(inode->i_sb->s_flags & SB_ACTIVE))
560 		return;
561 	if (!mapping_shrinkable(&inode->i_data))
562 		return;
563 
564 	if (list_lru_add_obj(&inode->i_sb->s_inode_lru, &inode->i_lru))
565 		this_cpu_inc(nr_unused);
566 	else if (rotate)
567 		inode_state_set(inode, I_REFERENCED);
568 }
569 
570 /*
571  * Add inode to LRU if needed (inode is unused and clean).
572  */
573 void inode_lru_list_add(struct inode *inode)
574 {
575 	__inode_lru_list_add(inode, false);
576 }
577 
578 static void inode_lru_list_del(struct inode *inode)
579 {
580 	if (list_empty(&inode->i_lru))
581 		return;
582 
583 	if (list_lru_del_obj(&inode->i_sb->s_inode_lru, &inode->i_lru))
584 		this_cpu_dec(nr_unused);
585 }
586 
587 static void inode_pin_lru_isolating(struct inode *inode)
588 {
589 	lockdep_assert_held(&inode->i_lock);
590 	WARN_ON(inode_state_read(inode) & (I_LRU_ISOLATING | I_FREEING | I_WILL_FREE));
591 	inode_state_set(inode, I_LRU_ISOLATING);
592 }
593 
594 static void inode_unpin_lru_isolating(struct inode *inode)
595 {
596 	spin_lock(&inode->i_lock);
597 	WARN_ON(!(inode_state_read(inode) & I_LRU_ISOLATING));
598 	inode_state_clear(inode, I_LRU_ISOLATING);
599 	/* Called with inode->i_lock which ensures memory ordering. */
600 	inode_wake_up_bit(inode, __I_LRU_ISOLATING);
601 	spin_unlock(&inode->i_lock);
602 }
603 
604 static void inode_wait_for_lru_isolating(struct inode *inode)
605 {
606 	struct wait_bit_queue_entry wqe;
607 	struct wait_queue_head *wq_head;
608 
609 	lockdep_assert_held(&inode->i_lock);
610 	if (!(inode_state_read(inode) & I_LRU_ISOLATING))
611 		return;
612 
613 	wq_head = inode_bit_waitqueue(&wqe, inode, __I_LRU_ISOLATING);
614 	for (;;) {
615 		prepare_to_wait_event(wq_head, &wqe.wq_entry, TASK_UNINTERRUPTIBLE);
616 		/*
617 		 * Checking I_LRU_ISOLATING with inode->i_lock guarantees
618 		 * memory ordering.
619 		 */
620 		if (!(inode_state_read(inode) & I_LRU_ISOLATING))
621 			break;
622 		spin_unlock(&inode->i_lock);
623 		schedule();
624 		spin_lock(&inode->i_lock);
625 	}
626 	finish_wait(wq_head, &wqe.wq_entry);
627 	WARN_ON(inode_state_read(inode) & I_LRU_ISOLATING);
628 }
629 
630 /**
631  * inode_sb_list_add - add inode to the superblock list of inodes
632  * @inode: inode to add
633  */
634 void inode_sb_list_add(struct inode *inode)
635 {
636 	struct super_block *sb = inode->i_sb;
637 
638 	spin_lock(&sb->s_inode_list_lock);
639 	list_add(&inode->i_sb_list, &sb->s_inodes);
640 	spin_unlock(&sb->s_inode_list_lock);
641 }
642 EXPORT_SYMBOL_GPL(inode_sb_list_add);
643 
644 static inline void inode_sb_list_del(struct inode *inode)
645 {
646 	struct super_block *sb = inode->i_sb;
647 
648 	if (!list_empty(&inode->i_sb_list)) {
649 		spin_lock(&sb->s_inode_list_lock);
650 		list_del_init(&inode->i_sb_list);
651 		spin_unlock(&sb->s_inode_list_lock);
652 	}
653 }
654 
655 static unsigned long hash(struct super_block *sb, u64 hashval)
656 {
657 	unsigned long tmp;
658 
659 	tmp = (hashval * (unsigned long)sb) ^ (GOLDEN_RATIO_PRIME + hashval) /
660 			L1_CACHE_BYTES;
661 	tmp = tmp ^ ((tmp ^ GOLDEN_RATIO_PRIME) >> i_hash_shift);
662 	return tmp & i_hash_mask;
663 }
664 
665 /**
666  *	__insert_inode_hash - hash an inode
667  *	@inode: unhashed inode
668  *	@hashval: u64 value used to locate this object in the
669  *		inode_hashtable.
670  *
671  *	Add an inode to the inode hash for this superblock.
672  */
673 void __insert_inode_hash(struct inode *inode, u64 hashval)
674 {
675 	struct hlist_head *b = inode_hashtable + hash(inode->i_sb, hashval);
676 
677 	spin_lock(&inode_hash_lock);
678 	spin_lock(&inode->i_lock);
679 	hlist_add_head_rcu(&inode->i_hash, b);
680 	spin_unlock(&inode->i_lock);
681 	spin_unlock(&inode_hash_lock);
682 }
683 EXPORT_SYMBOL(__insert_inode_hash);
684 
685 /**
686  *	__remove_inode_hash - remove an inode from the hash
687  *	@inode: inode to unhash
688  *
689  *	Remove an inode from the superblock.
690  */
691 void __remove_inode_hash(struct inode *inode)
692 {
693 	spin_lock(&inode_hash_lock);
694 	spin_lock(&inode->i_lock);
695 	hlist_del_init_rcu(&inode->i_hash);
696 	spin_unlock(&inode->i_lock);
697 	spin_unlock(&inode_hash_lock);
698 }
699 EXPORT_SYMBOL(__remove_inode_hash);
700 
701 void dump_mapping(const struct address_space *mapping)
702 {
703 	struct inode *host;
704 	const struct address_space_operations *a_ops;
705 	struct hlist_node *dentry_first;
706 	struct dentry *dentry_ptr;
707 	struct dentry dentry;
708 	char fname[64] = {};
709 	u64 ino;
710 
711 	/*
712 	 * If mapping is an invalid pointer, we don't want to crash
713 	 * accessing it, so probe everything depending on it carefully.
714 	 */
715 	if (get_kernel_nofault(host, &mapping->host) ||
716 	    get_kernel_nofault(a_ops, &mapping->a_ops)) {
717 		pr_warn("invalid mapping:%px\n", mapping);
718 		return;
719 	}
720 
721 	if (!host) {
722 		pr_warn("aops:%ps\n", a_ops);
723 		return;
724 	}
725 
726 	if (get_kernel_nofault(dentry_first, &host->i_dentry.first) ||
727 	    get_kernel_nofault(ino, &host->i_ino)) {
728 		pr_warn("aops:%ps invalid inode:%px\n", a_ops, host);
729 		return;
730 	}
731 
732 	if (!dentry_first) {
733 		pr_warn("aops:%ps ino:%llx\n", a_ops, ino);
734 		return;
735 	}
736 
737 	dentry_ptr = container_of(dentry_first, struct dentry, d_alias);
738 	if (get_kernel_nofault(dentry, dentry_ptr) ||
739 	    !dentry.d_parent || !dentry.d_name.name) {
740 		pr_warn("aops:%ps ino:%llx invalid dentry:%px\n",
741 				a_ops, ino, dentry_ptr);
742 		return;
743 	}
744 
745 	if (strncpy_from_kernel_nofault(fname, dentry.d_name.name, 63) < 0)
746 		strscpy(fname, "<invalid>");
747 	/*
748 	 * Even if strncpy_from_kernel_nofault() succeeded,
749 	 * the fname could be unreliable
750 	 */
751 	pr_warn("aops:%ps ino:%llx dentry name(?):\"%s\"\n",
752 		a_ops, ino, fname);
753 }
754 
755 void clear_inode(struct inode *inode)
756 {
757 	/*
758 	 * Only IS_VERITY() inodes can have verity info, so start by checking
759 	 * for IS_VERITY() (which is faster than retrieving the pointer to the
760 	 * verity info).  This minimizes overhead for non-verity inodes.
761 	 */
762 	if (IS_ENABLED(CONFIG_FS_VERITY) && IS_VERITY(inode))
763 		fsverity_cleanup_inode(inode);
764 
765 	/*
766 	 * We have to cycle the i_pages lock here because reclaim can be in the
767 	 * process of removing the last page (in __filemap_remove_folio())
768 	 * and we must not free the mapping under it.
769 	 */
770 	xa_lock_irq(&inode->i_data.i_pages);
771 	BUG_ON(inode->i_data.nrpages);
772 	/*
773 	 * Almost always, mapping_empty(&inode->i_data) here; but there are
774 	 * two known and long-standing ways in which nodes may get left behind
775 	 * (when deep radix-tree node allocation failed partway; or when THP
776 	 * collapse_file() failed). Until those two known cases are cleaned up,
777 	 * or a cleanup function is called here, do not BUG_ON(!mapping_empty),
778 	 * nor even WARN_ON(!mapping_empty).
779 	 */
780 	xa_unlock_irq(&inode->i_data.i_pages);
781 	BUG_ON(!(inode_state_read_once(inode) & I_FREEING));
782 	BUG_ON(inode_state_read_once(inode) & I_CLEAR);
783 	BUG_ON(!list_empty(&inode->i_wb_list));
784 	/* don't need i_lock here, no concurrent mods to i_state */
785 	inode_state_assign_raw(inode, I_FREEING | I_CLEAR);
786 }
787 EXPORT_SYMBOL(clear_inode);
788 
789 /*
790  * Free the inode passed in, removing it from the lists it is still connected
791  * to. We remove any pages still attached to the inode and wait for any IO that
792  * is still in progress before finally destroying the inode.
793  *
794  * An inode must already be marked I_FREEING so that we avoid the inode being
795  * moved back onto lists if we race with other code that manipulates the lists
796  * (e.g. writeback_single_inode). The caller is responsible for setting this.
797  *
798  * An inode must already be removed from the LRU list before being evicted from
799  * the cache. This should occur atomically with setting the I_FREEING state
800  * flag, so no inodes here should ever be on the LRU when being evicted.
801  */
802 static void evict(struct inode *inode)
803 {
804 	const struct super_operations *op = inode->i_sb->s_op;
805 
806 	BUG_ON(!(inode_state_read_once(inode) & I_FREEING));
807 	BUG_ON(!list_empty(&inode->i_lru));
808 
809 	inode_io_list_del(inode);
810 	inode_sb_list_del(inode);
811 
812 	spin_lock(&inode->i_lock);
813 	inode_wait_for_lru_isolating(inode);
814 
815 	/*
816 	 * Wait for flusher thread to be done with the inode so that filesystem
817 	 * does not start destroying it while writeback is still running. Since
818 	 * the inode has I_FREEING set, flusher thread won't start new work on
819 	 * the inode.  We just have to wait for running writeback to finish.
820 	 */
821 	inode_wait_for_writeback(inode);
822 	spin_unlock(&inode->i_lock);
823 
824 	if (op->evict_inode) {
825 		op->evict_inode(inode);
826 	} else {
827 		truncate_inode_pages_final(&inode->i_data);
828 		clear_inode(inode);
829 	}
830 	if (S_ISCHR(inode->i_mode) && inode->i_cdev)
831 		cd_forget(inode);
832 
833 	remove_inode_hash(inode);
834 
835 	/*
836 	 * Wake up waiters in __wait_on_freeing_inode().
837 	 *
838 	 * It is an invariant that any thread we need to wake up is already
839 	 * accounted for before remove_inode_hash() acquires ->i_lock -- both
840 	 * sides take the lock and sleep is aborted if the inode is found
841 	 * unhashed. Thus either the sleeper wins and goes off CPU, or removal
842 	 * wins and the sleeper aborts after testing with the lock.
843 	 *
844 	 * This also means we don't need any fences for the call below.
845 	 */
846 	inode_wake_up_bit(inode, __I_NEW);
847 	BUG_ON(inode_state_read_once(inode) != (I_FREEING | I_CLEAR));
848 
849 	destroy_inode(inode);
850 }
851 
852 /*
853  * dispose_list - dispose of the contents of a local list
854  * @head: the head of the list to free
855  *
856  * Dispose-list gets a local list with local inodes in it, so it doesn't
857  * need to worry about list corruption and SMP locks.
858  */
859 static void dispose_list(struct list_head *head)
860 {
861 	while (!list_empty(head)) {
862 		struct inode *inode;
863 
864 		inode = list_first_entry(head, struct inode, i_lru);
865 		list_del_init(&inode->i_lru);
866 
867 		evict(inode);
868 		cond_resched();
869 	}
870 }
871 
872 /**
873  * evict_inodes	- evict all evictable inodes for a superblock
874  * @sb:		superblock to operate on
875  *
876  * Make sure that no inodes with zero refcount are retained.  This is
877  * called by superblock shutdown after having SB_ACTIVE flag removed,
878  * so any inode reaching zero refcount during or after that call will
879  * be immediately evicted.
880  */
881 void evict_inodes(struct super_block *sb)
882 {
883 	struct inode *inode;
884 	LIST_HEAD(dispose);
885 
886 again:
887 	spin_lock(&sb->s_inode_list_lock);
888 	list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
889 		if (icount_read_once(inode))
890 			continue;
891 
892 		spin_lock(&inode->i_lock);
893 		if (icount_read(inode)) {
894 			spin_unlock(&inode->i_lock);
895 			continue;
896 		}
897 		if (inode_state_read(inode) & (I_NEW | I_FREEING | I_WILL_FREE)) {
898 			spin_unlock(&inode->i_lock);
899 			continue;
900 		}
901 
902 		inode_state_set(inode, I_FREEING);
903 		inode_lru_list_del(inode);
904 		spin_unlock(&inode->i_lock);
905 		list_add(&inode->i_lru, &dispose);
906 
907 		/*
908 		 * We can have a ton of inodes to evict at unmount time given
909 		 * enough memory, check to see if we need to go to sleep for a
910 		 * bit so we don't livelock.
911 		 */
912 		if (need_resched()) {
913 			spin_unlock(&sb->s_inode_list_lock);
914 			cond_resched();
915 			dispose_list(&dispose);
916 			goto again;
917 		}
918 	}
919 	spin_unlock(&sb->s_inode_list_lock);
920 
921 	dispose_list(&dispose);
922 }
923 EXPORT_SYMBOL_GPL(evict_inodes);
924 
925 /*
926  * Isolate the inode from the LRU in preparation for freeing it.
927  *
928  * If the inode has the I_REFERENCED flag set, then it means that it has been
929  * used recently - the flag is set in iput_final(). When we encounter such an
930  * inode, clear the flag and move it to the back of the LRU so it gets another
931  * pass through the LRU before it gets reclaimed. This is necessary because of
932  * the fact we are doing lazy LRU updates to minimise lock contention so the
933  * LRU does not have strict ordering. Hence we don't want to reclaim inodes
934  * with this flag set because they are the inodes that are out of order.
935  */
936 static enum lru_status inode_lru_isolate(struct list_head *item,
937 		struct list_lru_one *lru, void *arg)
938 {
939 	struct list_head *freeable = arg;
940 	struct inode	*inode = container_of(item, struct inode, i_lru);
941 
942 	/*
943 	 * We are inverting the lru lock/inode->i_lock here, so use a
944 	 * trylock. If we fail to get the lock, just skip it.
945 	 */
946 	if (!spin_trylock(&inode->i_lock))
947 		return LRU_SKIP;
948 
949 	/*
950 	 * Inodes can get referenced, redirtied, or repopulated while
951 	 * they're already on the LRU, and this can make them
952 	 * unreclaimable for a while. Remove them lazily here; iput,
953 	 * sync, or the last page cache deletion will requeue them.
954 	 */
955 	if (icount_read(inode) ||
956 	    (inode_state_read(inode) & ~I_REFERENCED) ||
957 	    !mapping_shrinkable(&inode->i_data)) {
958 		list_lru_isolate(lru, &inode->i_lru);
959 		spin_unlock(&inode->i_lock);
960 		this_cpu_dec(nr_unused);
961 		return LRU_REMOVED;
962 	}
963 
964 	/* Recently referenced inodes get one more pass */
965 	if (inode_state_read(inode) & I_REFERENCED) {
966 		inode_state_clear(inode, I_REFERENCED);
967 		spin_unlock(&inode->i_lock);
968 		return LRU_ROTATE;
969 	}
970 
971 	/*
972 	 * On highmem systems, mapping_shrinkable() permits dropping
973 	 * page cache in order to free up struct inodes: lowmem might
974 	 * be under pressure before the cache inside the highmem zone.
975 	 */
976 	if (!mapping_empty(&inode->i_data)) {
977 		unsigned long reap;
978 
979 		inode_pin_lru_isolating(inode);
980 		spin_unlock(&inode->i_lock);
981 		spin_unlock(&lru->lock);
982 		reap = invalidate_mapping_pages(&inode->i_data, 0, -1);
983 		if (current_is_kswapd())
984 			__count_vm_events(KSWAPD_INODESTEAL, reap);
985 		else
986 			__count_vm_events(PGINODESTEAL, reap);
987 		mm_account_reclaimed_pages(reap);
988 		inode_unpin_lru_isolating(inode);
989 		return LRU_RETRY;
990 	}
991 
992 	WARN_ON(inode_state_read(inode) & I_NEW);
993 	inode_state_set(inode, I_FREEING);
994 	list_lru_isolate_move(lru, &inode->i_lru, freeable);
995 	spin_unlock(&inode->i_lock);
996 
997 	this_cpu_dec(nr_unused);
998 	return LRU_REMOVED;
999 }
1000 
1001 /*
1002  * Walk the superblock inode LRU for freeable inodes and attempt to free them.
1003  * This is called from the superblock shrinker function with a number of inodes
1004  * to trim from the LRU. Inodes to be freed are moved to a temporary list and
1005  * then are freed outside inode_lock by dispose_list().
1006  */
1007 long prune_icache_sb(struct super_block *sb, struct shrink_control *sc)
1008 {
1009 	LIST_HEAD(freeable);
1010 	long freed;
1011 
1012 	freed = list_lru_shrink_walk(&sb->s_inode_lru, sc,
1013 				     inode_lru_isolate, &freeable);
1014 	dispose_list(&freeable);
1015 	return freed;
1016 }
1017 
1018 static void __wait_on_freeing_inode(struct inode *inode, bool hash_locked, bool rcu_locked);
1019 static bool igrab_from_hash(struct inode *inode);
1020 
1021 /*
1022  * Called with the inode lock held.
1023  */
1024 static struct inode *find_inode(struct super_block *sb,
1025 				struct hlist_head *head,
1026 				int (*test)(struct inode *, void *),
1027 				void *data, bool hash_locked,
1028 				bool *isnew)
1029 {
1030 	struct inode *inode = NULL;
1031 
1032 	if (hash_locked)
1033 		lockdep_assert_held(&inode_hash_lock);
1034 	else
1035 		lockdep_assert_not_held(&inode_hash_lock);
1036 
1037 	rcu_read_lock();
1038 repeat:
1039 	hlist_for_each_entry_rcu(inode, head, i_hash) {
1040 		if (inode->i_sb != sb)
1041 			continue;
1042 		if (!test(inode, data))
1043 			continue;
1044 		if (igrab_from_hash(inode)) {
1045 			rcu_read_unlock();
1046 			*isnew = false;
1047 			return inode;
1048 		}
1049 		spin_lock(&inode->i_lock);
1050 		if (inode_state_read(inode) & (I_FREEING | I_WILL_FREE)) {
1051 			__wait_on_freeing_inode(inode, hash_locked, true);
1052 			goto repeat;
1053 		}
1054 		if (unlikely(inode_state_read(inode) & I_CREATING)) {
1055 			spin_unlock(&inode->i_lock);
1056 			rcu_read_unlock();
1057 			return ERR_PTR(-ESTALE);
1058 		}
1059 		__iget(inode);
1060 		*isnew = !!(inode_state_read(inode) & I_NEW);
1061 		spin_unlock(&inode->i_lock);
1062 		rcu_read_unlock();
1063 		return inode;
1064 	}
1065 	rcu_read_unlock();
1066 	return NULL;
1067 }
1068 
1069 /*
1070  * find_inode_fast is the fast path version of find_inode, see the comment at
1071  * iget_locked for details.
1072  */
1073 static struct inode *find_inode_fast(struct super_block *sb,
1074 				struct hlist_head *head, u64 ino,
1075 				bool hash_locked, bool *isnew)
1076 {
1077 	struct inode *inode = NULL;
1078 
1079 	if (hash_locked)
1080 		lockdep_assert_held(&inode_hash_lock);
1081 	else
1082 		lockdep_assert_not_held(&inode_hash_lock);
1083 
1084 	rcu_read_lock();
1085 repeat:
1086 	hlist_for_each_entry_rcu(inode, head, i_hash) {
1087 		if (inode->i_ino != ino)
1088 			continue;
1089 		if (inode->i_sb != sb)
1090 			continue;
1091 		if (igrab_from_hash(inode)) {
1092 			rcu_read_unlock();
1093 			*isnew = false;
1094 			return inode;
1095 		}
1096 		spin_lock(&inode->i_lock);
1097 		if (inode_state_read(inode) & (I_FREEING | I_WILL_FREE)) {
1098 			__wait_on_freeing_inode(inode, hash_locked, true);
1099 			goto repeat;
1100 		}
1101 		if (unlikely(inode_state_read(inode) & I_CREATING)) {
1102 			spin_unlock(&inode->i_lock);
1103 			rcu_read_unlock();
1104 			return ERR_PTR(-ESTALE);
1105 		}
1106 		__iget(inode);
1107 		*isnew = !!(inode_state_read(inode) & I_NEW);
1108 		spin_unlock(&inode->i_lock);
1109 		rcu_read_unlock();
1110 		return inode;
1111 	}
1112 	rcu_read_unlock();
1113 	return NULL;
1114 }
1115 
1116 /*
1117  * Each cpu owns a range of LAST_INO_BATCH numbers.
1118  * 'shared_last_ino' is dirtied only once out of LAST_INO_BATCH allocations,
1119  * to renew the exhausted range.
1120  *
1121  * This does not significantly increase overflow rate because every CPU can
1122  * consume at most LAST_INO_BATCH-1 unused inode numbers. So there is
1123  * NR_CPUS*(LAST_INO_BATCH-1) wastage. At 4096 and 1024, this is ~0.1% of the
1124  * 2^32 range, and is a worst-case. Even a 50% wastage would only increase
1125  * overflow rate by 2x, which does not seem too significant.
1126  *
1127  * On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW
1128  * error if st_ino won't fit in target struct field. Use 32bit counter
1129  * here to attempt to avoid that.
1130  */
1131 #define LAST_INO_BATCH 1024
1132 static DEFINE_PER_CPU(unsigned int, last_ino);
1133 
1134 unsigned int get_next_ino(void)
1135 {
1136 	unsigned int *p = &get_cpu_var(last_ino);
1137 	unsigned int res = *p;
1138 
1139 #ifdef CONFIG_SMP
1140 	if (unlikely((res & (LAST_INO_BATCH-1)) == 0)) {
1141 		static atomic_t shared_last_ino;
1142 		int next = atomic_add_return(LAST_INO_BATCH, &shared_last_ino);
1143 
1144 		res = next - LAST_INO_BATCH;
1145 	}
1146 #endif
1147 
1148 	res++;
1149 	/* get_next_ino should not provide a 0 inode number */
1150 	if (unlikely(!res))
1151 		res++;
1152 	*p = res;
1153 	put_cpu_var(last_ino);
1154 	return res;
1155 }
1156 EXPORT_SYMBOL(get_next_ino);
1157 
1158 /**
1159  *	new_inode 	- obtain an inode
1160  *	@sb: superblock
1161  *
1162  *	Allocates a new inode for given superblock. The default gfp_mask
1163  *	for allocations related to inode->i_mapping is GFP_HIGHUSER_MOVABLE.
1164  *	If HIGHMEM pages are unsuitable or it is known that pages allocated
1165  *	for the page cache are not reclaimable or migratable,
1166  *	mapping_set_gfp_mask() must be called with suitable flags on the
1167  *	newly created inode's mapping
1168  *
1169  */
1170 struct inode *new_inode(struct super_block *sb)
1171 {
1172 	struct inode *inode;
1173 
1174 	inode = alloc_inode(sb);
1175 	if (inode)
1176 		inode_sb_list_add(inode);
1177 	return inode;
1178 }
1179 EXPORT_SYMBOL(new_inode);
1180 
1181 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1182 void lockdep_annotate_inode_mutex_key(struct inode *inode)
1183 {
1184 	if (S_ISDIR(inode->i_mode)) {
1185 		struct file_system_type *type = inode->i_sb->s_type;
1186 
1187 		/* Set new key only if filesystem hasn't already changed it */
1188 		if (lockdep_match_class(&inode->i_rwsem, &type->i_mutex_key)) {
1189 			/*
1190 			 * ensure nobody is actually holding i_rwsem
1191 			 */
1192 			init_rwsem(&inode->i_rwsem);
1193 			lockdep_set_class(&inode->i_rwsem,
1194 					  &type->i_mutex_dir_key);
1195 		}
1196 	}
1197 }
1198 EXPORT_SYMBOL(lockdep_annotate_inode_mutex_key);
1199 #endif
1200 
1201 /**
1202  * unlock_new_inode - clear the I_NEW state and wake up any waiters
1203  * @inode:	new inode to unlock
1204  *
1205  * Called when the inode is fully initialised to clear the new state of the
1206  * inode and wake up anyone waiting for the inode to finish initialisation.
1207  */
1208 void unlock_new_inode(struct inode *inode)
1209 {
1210 	lockdep_annotate_inode_mutex_key(inode);
1211 	spin_lock(&inode->i_lock);
1212 	WARN_ON(!(inode_state_read(inode) & I_NEW));
1213 	/*
1214 	 * Paired with igrab_from_hash()
1215 	 */
1216 	smp_wmb();
1217 	inode_state_clear(inode, I_NEW | I_CREATING);
1218 	inode_wake_up_bit(inode, __I_NEW);
1219 	spin_unlock(&inode->i_lock);
1220 }
1221 EXPORT_SYMBOL(unlock_new_inode);
1222 
1223 void discard_new_inode(struct inode *inode)
1224 {
1225 	lockdep_annotate_inode_mutex_key(inode);
1226 	spin_lock(&inode->i_lock);
1227 	WARN_ON(!(inode_state_read(inode) & I_NEW));
1228 	/*
1229 	 * Paired with igrab_from_hash()
1230 	 */
1231 	smp_wmb();
1232 	inode_state_clear(inode, I_NEW);
1233 	inode_wake_up_bit(inode, __I_NEW);
1234 	spin_unlock(&inode->i_lock);
1235 	iput(inode);
1236 }
1237 EXPORT_SYMBOL(discard_new_inode);
1238 
1239 /**
1240  * lock_two_nondirectories - take two i_mutexes on non-directory objects
1241  *
1242  * Lock any non-NULL argument. Passed objects must not be directories.
1243  * Zero, one or two objects may be locked by this function.
1244  *
1245  * @inode1: first inode to lock
1246  * @inode2: second inode to lock
1247  */
1248 void lock_two_nondirectories(struct inode *inode1, struct inode *inode2)
1249 {
1250 	if (inode1)
1251 		WARN_ON_ONCE(S_ISDIR(inode1->i_mode));
1252 	if (inode2)
1253 		WARN_ON_ONCE(S_ISDIR(inode2->i_mode));
1254 	if (inode1 > inode2)
1255 		swap(inode1, inode2);
1256 	if (inode1)
1257 		inode_lock(inode1);
1258 	if (inode2 && inode2 != inode1)
1259 		inode_lock_nested(inode2, I_MUTEX_NONDIR2);
1260 }
1261 EXPORT_SYMBOL(lock_two_nondirectories);
1262 
1263 /**
1264  * unlock_two_nondirectories - release locks from lock_two_nondirectories()
1265  * @inode1: first inode to unlock
1266  * @inode2: second inode to unlock
1267  */
1268 void unlock_two_nondirectories(struct inode *inode1, struct inode *inode2)
1269 {
1270 	if (inode1) {
1271 		WARN_ON_ONCE(S_ISDIR(inode1->i_mode));
1272 		inode_unlock(inode1);
1273 	}
1274 	if (inode2 && inode2 != inode1) {
1275 		WARN_ON_ONCE(S_ISDIR(inode2->i_mode));
1276 		inode_unlock(inode2);
1277 	}
1278 }
1279 EXPORT_SYMBOL(unlock_two_nondirectories);
1280 
1281 /**
1282  * inode_insert5 - obtain an inode from a mounted file system
1283  * @inode:	pre-allocated inode to use for insert to cache
1284  * @hashval:	hash value (usually inode number) to get
1285  * @test:	callback used for comparisons between inodes
1286  * @set:	callback used to initialize a new struct inode
1287  * @data:	opaque data pointer to pass to @test and @set
1288  * @isnew:	pointer to a bool which will indicate whether I_NEW is set
1289  *
1290  * Search for the inode specified by @hashval and @data in the inode cache,
1291  * and if present return it with an increased reference count. This is a
1292  * variant of iget5_locked() that doesn't allocate an inode.
1293  *
1294  * If the inode is not present in the cache, insert the pre-allocated inode and
1295  * return it locked, hashed, and with the I_NEW flag set. The file system gets
1296  * to fill it in before unlocking it via unlock_new_inode().
1297  *
1298  * Note that both @test and @set are called with the inode_hash_lock held, so
1299  * they can't sleep.
1300  */
1301 struct inode *inode_insert5(struct inode *inode, u64 hashval,
1302 			    int (*test)(struct inode *, void *),
1303 			    int (*set)(struct inode *, void *), void *data)
1304 {
1305 	struct hlist_head *head = inode_hashtable + hash(inode->i_sb, hashval);
1306 	struct inode *old;
1307 	bool isnew;
1308 
1309 	might_sleep();
1310 
1311 again:
1312 	spin_lock(&inode_hash_lock);
1313 	old = find_inode(inode->i_sb, head, test, data, true, &isnew);
1314 	if (unlikely(old)) {
1315 		/*
1316 		 * Uhhuh, somebody else created the same inode under us.
1317 		 * Use the old inode instead of the preallocated one.
1318 		 */
1319 		spin_unlock(&inode_hash_lock);
1320 		if (IS_ERR(old))
1321 			return NULL;
1322 		if (unlikely(isnew))
1323 			wait_on_new_inode(old);
1324 		if (unlikely(inode_unhashed(old))) {
1325 			iput(old);
1326 			goto again;
1327 		}
1328 		return old;
1329 	}
1330 
1331 	if (set && unlikely(set(inode, data))) {
1332 		spin_unlock(&inode_hash_lock);
1333 		return NULL;
1334 	}
1335 
1336 	/*
1337 	 * Return the locked inode with I_NEW set, the
1338 	 * caller is responsible for filling in the contents
1339 	 */
1340 	spin_lock(&inode->i_lock);
1341 	inode_state_set(inode, I_NEW);
1342 	hlist_add_head_rcu(&inode->i_hash, head);
1343 	spin_unlock(&inode->i_lock);
1344 
1345 	spin_unlock(&inode_hash_lock);
1346 
1347 	/*
1348 	 * Add inode to the sb list if it's not already. It has I_NEW at this
1349 	 * point, so it should be safe to test i_sb_list locklessly.
1350 	 */
1351 	if (list_empty(&inode->i_sb_list))
1352 		inode_sb_list_add(inode);
1353 
1354 	return inode;
1355 }
1356 EXPORT_SYMBOL(inode_insert5);
1357 
1358 /**
1359  * iget5_locked - obtain an inode from a mounted file system
1360  * @sb:		super block of file system
1361  * @hashval:	hash value (usually inode number) to get
1362  * @test:	callback used for comparisons between inodes
1363  * @set:	callback used to initialize a new struct inode
1364  * @data:	opaque data pointer to pass to @test and @set
1365  *
1366  * Search for the inode specified by @hashval and @data in the inode cache,
1367  * and if present return it with an increased reference count. This is a
1368  * generalized version of iget_locked() for file systems where the inode
1369  * number is not sufficient for unique identification of an inode.
1370  *
1371  * If the inode is not present in the cache, allocate and insert a new inode
1372  * and return it locked, hashed, and with the I_NEW flag set. The file system
1373  * gets to fill it in before unlocking it via unlock_new_inode().
1374  *
1375  * Note that both @test and @set are called with the inode_hash_lock held, so
1376  * they can't sleep.
1377  */
1378 struct inode *iget5_locked(struct super_block *sb, u64 hashval,
1379 		int (*test)(struct inode *, void *),
1380 		int (*set)(struct inode *, void *), void *data)
1381 {
1382 	struct inode *inode = ilookup5(sb, hashval, test, data);
1383 
1384 	if (!inode) {
1385 		struct inode *new = alloc_inode(sb);
1386 
1387 		if (new) {
1388 			inode = inode_insert5(new, hashval, test, set, data);
1389 			if (unlikely(inode != new))
1390 				destroy_inode(new);
1391 		}
1392 	}
1393 	return inode;
1394 }
1395 EXPORT_SYMBOL(iget5_locked);
1396 
1397 /**
1398  * iget5_locked_rcu - obtain an inode from a mounted file system
1399  * @sb:		super block of file system
1400  * @hashval:	hash value (usually inode number) to get
1401  * @test:	callback used for comparisons between inodes
1402  * @set:	callback used to initialize a new struct inode
1403  * @data:	opaque data pointer to pass to @test and @set
1404  *
1405  * This is equivalent to iget5_locked, except the @test callback must
1406  * tolerate the inode not being stable, including being mid-teardown.
1407  */
1408 struct inode *iget5_locked_rcu(struct super_block *sb, u64 hashval,
1409 		int (*test)(struct inode *, void *),
1410 		int (*set)(struct inode *, void *), void *data)
1411 {
1412 	struct hlist_head *head = inode_hashtable + hash(sb, hashval);
1413 	struct inode *inode, *new;
1414 	bool isnew;
1415 
1416 	might_sleep();
1417 
1418 again:
1419 	inode = find_inode(sb, head, test, data, false, &isnew);
1420 	if (inode) {
1421 		if (IS_ERR(inode))
1422 			return NULL;
1423 		if (unlikely(isnew))
1424 			wait_on_new_inode(inode);
1425 		if (unlikely(inode_unhashed(inode))) {
1426 			iput(inode);
1427 			goto again;
1428 		}
1429 		return inode;
1430 	}
1431 
1432 	new = alloc_inode(sb);
1433 	if (new) {
1434 		inode = inode_insert5(new, hashval, test, set, data);
1435 		if (unlikely(inode != new))
1436 			destroy_inode(new);
1437 	}
1438 	return inode;
1439 }
1440 EXPORT_SYMBOL_GPL(iget5_locked_rcu);
1441 
1442 /**
1443  * iget_locked - obtain an inode from a mounted file system
1444  * @sb:		super block of file system
1445  * @ino:	inode number to get
1446  *
1447  * Search for the inode specified by @ino in the inode cache and if present
1448  * return it with an increased reference count. This is for file systems
1449  * where the inode number is sufficient for unique identification of an inode.
1450  *
1451  * If the inode is not in cache, allocate a new inode and return it locked,
1452  * hashed, and with the I_NEW flag set.  The file system gets to fill it in
1453  * before unlocking it via unlock_new_inode().
1454  */
1455 struct inode *iget_locked(struct super_block *sb, u64 ino)
1456 {
1457 	struct hlist_head *head = inode_hashtable + hash(sb, ino);
1458 	struct inode *inode;
1459 	bool isnew;
1460 
1461 	might_sleep();
1462 
1463 again:
1464 	inode = find_inode_fast(sb, head, ino, false, &isnew);
1465 	if (inode) {
1466 		if (IS_ERR(inode))
1467 			return NULL;
1468 		if (unlikely(isnew))
1469 			wait_on_new_inode(inode);
1470 		if (unlikely(inode_unhashed(inode))) {
1471 			iput(inode);
1472 			goto again;
1473 		}
1474 		return inode;
1475 	}
1476 
1477 	inode = alloc_inode(sb);
1478 	if (inode) {
1479 		struct inode *old;
1480 
1481 		spin_lock(&inode_hash_lock);
1482 		/* We released the lock, so.. */
1483 		old = find_inode_fast(sb, head, ino, true, &isnew);
1484 		if (!old) {
1485 			inode->i_ino = ino;
1486 			spin_lock(&inode->i_lock);
1487 			inode_state_assign(inode, I_NEW);
1488 			hlist_add_head_rcu(&inode->i_hash, head);
1489 			spin_unlock(&inode->i_lock);
1490 			spin_unlock(&inode_hash_lock);
1491 			inode_sb_list_add(inode);
1492 
1493 			/* Return the locked inode with I_NEW set, the
1494 			 * caller is responsible for filling in the contents
1495 			 */
1496 			return inode;
1497 		}
1498 
1499 		/*
1500 		 * Uhhuh, somebody else created the same inode under
1501 		 * us. Use the old inode instead of the one we just
1502 		 * allocated.
1503 		 */
1504 		spin_unlock(&inode_hash_lock);
1505 		destroy_inode(inode);
1506 		if (IS_ERR(old))
1507 			return NULL;
1508 		inode = old;
1509 		if (unlikely(isnew))
1510 			wait_on_new_inode(inode);
1511 		if (unlikely(inode_unhashed(inode))) {
1512 			iput(inode);
1513 			goto again;
1514 		}
1515 	}
1516 	return inode;
1517 }
1518 EXPORT_SYMBOL(iget_locked);
1519 
1520 /*
1521  * search the inode cache for a matching inode number.
1522  * If we find one, then the inode number we are trying to
1523  * allocate is not unique and so we should not use it.
1524  *
1525  * Returns 1 if the inode number is unique, 0 if it is not.
1526  */
1527 static int test_inode_iunique(struct super_block *sb, u64 ino)
1528 {
1529 	struct hlist_head *b = inode_hashtable + hash(sb, ino);
1530 	struct inode *inode;
1531 
1532 	hlist_for_each_entry_rcu(inode, b, i_hash) {
1533 		if (inode->i_ino == ino && inode->i_sb == sb)
1534 			return 0;
1535 	}
1536 	return 1;
1537 }
1538 
1539 /**
1540  *	iunique - get a unique inode number
1541  *	@sb: superblock
1542  *	@max_reserved: highest reserved inode number
1543  *
1544  *	Obtain an inode number that is unique on the system for a given
1545  *	superblock. This is used by file systems that have no natural
1546  *	permanent inode numbering system. An inode number is returned that
1547  *	is higher than the reserved limit but unique.
1548  *
1549  *	BUGS:
1550  *	With a large number of inodes live on the file system this function
1551  *	currently becomes quite slow.
1552  */
1553 ino_t iunique(struct super_block *sb, ino_t max_reserved)
1554 {
1555 	/*
1556 	 * On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW
1557 	 * error if st_ino won't fit in target struct field. Use 32bit counter
1558 	 * here to attempt to avoid that.
1559 	 */
1560 	static DEFINE_SPINLOCK(iunique_lock);
1561 	static unsigned int counter;
1562 	ino_t res;
1563 
1564 	rcu_read_lock();
1565 	spin_lock(&iunique_lock);
1566 	do {
1567 		if (counter <= max_reserved)
1568 			counter = max_reserved + 1;
1569 		res = counter++;
1570 	} while (!test_inode_iunique(sb, res));
1571 	spin_unlock(&iunique_lock);
1572 	rcu_read_unlock();
1573 
1574 	return res;
1575 }
1576 EXPORT_SYMBOL(iunique);
1577 
1578 /**
1579  * ihold - get a reference on the inode, provided you already have one
1580  * @inode:	inode to operate on
1581  */
1582 void ihold(struct inode *inode)
1583 {
1584 	VFS_BUG_ON_INODE(icount_read_once(inode) < 1, inode);
1585 	WARN_ON(atomic_inc_return(&inode->i_count) < 2);
1586 }
1587 EXPORT_SYMBOL(ihold);
1588 
1589 struct inode *igrab(struct inode *inode)
1590 {
1591 	/*
1592 	 * Read commentary above igrab_from_hash() for an explanation why this works.
1593 	 */
1594 	if (atomic_add_unless(&inode->i_count, 1, 0)) {
1595 		VFS_BUG_ON_INODE(inode_state_read_once(inode) & (I_FREEING | I_WILL_FREE), inode);
1596 		return inode;
1597 	}
1598 
1599 	spin_lock(&inode->i_lock);
1600 	if (!(inode_state_read(inode) & (I_FREEING | I_WILL_FREE))) {
1601 		__iget(inode);
1602 		spin_unlock(&inode->i_lock);
1603 	} else {
1604 		spin_unlock(&inode->i_lock);
1605 		/*
1606 		 * Handle the case where s_op->clear_inode is not been
1607 		 * called yet, and somebody is calling igrab
1608 		 * while the inode is getting freed.
1609 		 */
1610 		inode = NULL;
1611 	}
1612 	return inode;
1613 }
1614 EXPORT_SYMBOL(igrab);
1615 
1616 /*
1617  * igrab_from_hash - special inode refcount acquire primitive for the inode hash
1618  *
1619  * It provides lockless refcount acquire in the common case of no problematic
1620  * flags being set and the count being > 0.
1621  *
1622  * There are 4 state flags to worry about and the routine makes sure to not bump the
1623  * ref if any of them is present.
1624  *
1625  * I_NEW and I_CREATING can only legally get set *before* the inode becomes visible
1626  * during lookup. Thus if the flags are not spotted, they are guaranteed to not be
1627  * a factor. However, we need an acquire fence before returning the inode just
1628  * in case we raced against clearing the state to make sure our consumer picks up
1629  * any other changes made prior. atomic_add_unless provides a full fence, which
1630  * takes care of it.
1631  *
1632  * I_FREEING and I_WILL_FREE can only legally get set if ->i_count == 0 and it is
1633  * illegal to bump the ref if either is present. Consequently if atomic_add_unless
1634  * managed to replace a non-0 value with a bigger one, we have a guarantee neither
1635  * of these flags is set. Note this means explicitly checking of these flags below
1636  * is not necessary, it is only done because it does not cost anything on top of the
1637  * load which already needs to be done to handle the other flags.
1638  */
1639 static bool igrab_from_hash(struct inode *inode)
1640 {
1641 	if (inode_state_read_once(inode) & (I_NEW | I_CREATING | I_FREEING | I_WILL_FREE))
1642 		return false;
1643 	/*
1644 	 * Paired with routines clearing I_NEW
1645 	 */
1646 	if (atomic_add_unless(&inode->i_count, 1, 0)) {
1647 		VFS_BUG_ON_INODE(inode_state_read_once(inode) & (I_FREEING | I_WILL_FREE), inode);
1648 		return true;
1649 	}
1650 	return false;
1651 }
1652 
1653 /**
1654  * ilookup5_nowait - search for an inode in the inode cache
1655  * @sb:		super block of file system to search
1656  * @hashval:	hash value (usually inode number) to search for
1657  * @test:	callback used for comparisons between inodes
1658  * @data:	opaque data pointer to pass to @test
1659  * @isnew:	return argument telling whether I_NEW was set when
1660  *		the inode was found in hash (the caller needs to
1661  *		wait for I_NEW to clear)
1662  *
1663  * Search for the inode specified by @hashval and @data in the inode cache.
1664  * If the inode is in the cache, the inode is returned with an incremented
1665  * reference count.
1666  *
1667  * Note: I_NEW is not waited upon so you have to be very careful what you do
1668  * with the returned inode.  You probably should be using ilookup5() instead.
1669  *
1670  * Note2: @test is called with the inode_hash_lock held, so can't sleep.
1671  */
1672 struct inode *ilookup5_nowait(struct super_block *sb, u64 hashval,
1673 		int (*test)(struct inode *, void *), void *data, bool *isnew)
1674 {
1675 	struct hlist_head *head = inode_hashtable + hash(sb, hashval);
1676 	struct inode *inode;
1677 
1678 	spin_lock(&inode_hash_lock);
1679 	inode = find_inode(sb, head, test, data, true, isnew);
1680 	spin_unlock(&inode_hash_lock);
1681 
1682 	return IS_ERR(inode) ? NULL : inode;
1683 }
1684 EXPORT_SYMBOL(ilookup5_nowait);
1685 
1686 /**
1687  * ilookup5 - search for an inode in the inode cache
1688  * @sb:		super block of file system to search
1689  * @hashval:	hash value (usually inode number) to search for
1690  * @test:	callback used for comparisons between inodes
1691  * @data:	opaque data pointer to pass to @test
1692  *
1693  * Search for the inode specified by @hashval and @data in the inode cache,
1694  * and if the inode is in the cache, return the inode with an incremented
1695  * reference count.  Waits on I_NEW before returning the inode.
1696  * returned with an incremented reference count.
1697  *
1698  * This is a generalized version of ilookup() for file systems where the
1699  * inode number is not sufficient for unique identification of an inode.
1700  *
1701  * Note: @test is called with the inode_hash_lock held, so can't sleep.
1702  */
1703 struct inode *ilookup5(struct super_block *sb, u64 hashval,
1704 		int (*test)(struct inode *, void *), void *data)
1705 {
1706 	struct inode *inode;
1707 	bool isnew;
1708 
1709 	might_sleep();
1710 
1711 again:
1712 	inode = ilookup5_nowait(sb, hashval, test, data, &isnew);
1713 	if (inode) {
1714 		if (unlikely(isnew))
1715 			wait_on_new_inode(inode);
1716 		if (unlikely(inode_unhashed(inode))) {
1717 			iput(inode);
1718 			goto again;
1719 		}
1720 	}
1721 	return inode;
1722 }
1723 EXPORT_SYMBOL(ilookup5);
1724 
1725 /**
1726  * ilookup - search for an inode in the inode cache
1727  * @sb:		super block of file system to search
1728  * @ino:	inode number to search for
1729  *
1730  * Search for the inode @ino in the inode cache, and if the inode is in the
1731  * cache, the inode is returned with an incremented reference count.
1732  */
1733 struct inode *ilookup(struct super_block *sb, u64 ino)
1734 {
1735 	struct hlist_head *head = inode_hashtable + hash(sb, ino);
1736 	struct inode *inode;
1737 	bool isnew;
1738 
1739 	might_sleep();
1740 
1741 again:
1742 	inode = find_inode_fast(sb, head, ino, false, &isnew);
1743 
1744 	if (inode) {
1745 		if (IS_ERR(inode))
1746 			return NULL;
1747 		if (unlikely(isnew))
1748 			wait_on_new_inode(inode);
1749 		if (unlikely(inode_unhashed(inode))) {
1750 			iput(inode);
1751 			goto again;
1752 		}
1753 	}
1754 	return inode;
1755 }
1756 EXPORT_SYMBOL(ilookup);
1757 
1758 /**
1759  * find_inode_nowait - find an inode in the inode cache
1760  * @sb:		super block of file system to search
1761  * @hashval:	hash value (usually inode number) to search for
1762  * @match:	callback used for comparisons between inodes
1763  * @data:	opaque data pointer to pass to @match
1764  *
1765  * Search for the inode specified by @hashval and @data in the inode
1766  * cache, where the helper function @match will return 0 if the inode
1767  * does not match, 1 if the inode does match, and -1 if the search
1768  * should be stopped.  The @match function must be responsible for
1769  * taking the i_lock spin_lock and checking i_state for an inode being
1770  * freed or being initialized, and incrementing the reference count
1771  * before returning 1.  It also must not sleep, since it is called with
1772  * the inode_hash_lock spinlock held.
1773  *
1774  * This is a even more generalized version of ilookup5() when the
1775  * function must never block --- find_inode() can block in
1776  * __wait_on_freeing_inode() --- or when the caller can not increment
1777  * the reference count because the resulting iput() might cause an
1778  * inode eviction.  The tradeoff is that the @match funtion must be
1779  * very carefully implemented.
1780  */
1781 struct inode *find_inode_nowait(struct super_block *sb,
1782 				u64 hashval,
1783 				int (*match)(struct inode *, u64,
1784 					     void *),
1785 				void *data)
1786 {
1787 	struct hlist_head *head = inode_hashtable + hash(sb, hashval);
1788 	struct inode *inode, *ret_inode = NULL;
1789 	int mval;
1790 
1791 	spin_lock(&inode_hash_lock);
1792 	hlist_for_each_entry(inode, head, i_hash) {
1793 		if (inode->i_sb != sb)
1794 			continue;
1795 		mval = match(inode, hashval, data);
1796 		if (mval == 0)
1797 			continue;
1798 		if (mval == 1)
1799 			ret_inode = inode;
1800 		goto out;
1801 	}
1802 out:
1803 	spin_unlock(&inode_hash_lock);
1804 	return ret_inode;
1805 }
1806 EXPORT_SYMBOL(find_inode_nowait);
1807 
1808 /**
1809  * find_inode_rcu - find an inode in the inode cache
1810  * @sb:		Super block of file system to search
1811  * @hashval:	Key to hash
1812  * @test:	Function to test match on an inode
1813  * @data:	Data for test function
1814  *
1815  * Search for the inode specified by @hashval and @data in the inode cache,
1816  * where the helper function @test will return 0 if the inode does not match
1817  * and 1 if it does.  The @test function must be responsible for taking the
1818  * i_lock spin_lock and checking i_state for an inode being freed or being
1819  * initialized.
1820  *
1821  * If successful, this will return the inode for which the @test function
1822  * returned 1 and NULL otherwise.
1823  *
1824  * The @test function is not permitted to take a ref on any inode presented.
1825  * It is also not permitted to sleep.
1826  *
1827  * The caller must hold the RCU read lock.
1828  */
1829 struct inode *find_inode_rcu(struct super_block *sb, u64 hashval,
1830 			     int (*test)(struct inode *, void *), void *data)
1831 {
1832 	struct hlist_head *head = inode_hashtable + hash(sb, hashval);
1833 	struct inode *inode;
1834 
1835 	RCU_LOCKDEP_WARN(!rcu_read_lock_held(),
1836 			 "suspicious find_inode_rcu() usage");
1837 
1838 	hlist_for_each_entry_rcu(inode, head, i_hash) {
1839 		if (inode->i_sb == sb &&
1840 		    !(inode_state_read_once(inode) & (I_FREEING | I_WILL_FREE)) &&
1841 		    test(inode, data))
1842 			return inode;
1843 	}
1844 	return NULL;
1845 }
1846 EXPORT_SYMBOL(find_inode_rcu);
1847 
1848 /**
1849  * find_inode_by_ino_rcu - Find an inode in the inode cache
1850  * @sb:		Super block of file system to search
1851  * @ino:	The inode number to match
1852  *
1853  * Search for the inode specified by @hashval and @data in the inode cache,
1854  * where the helper function @test will return 0 if the inode does not match
1855  * and 1 if it does.  The @test function must be responsible for taking the
1856  * i_lock spin_lock and checking i_state for an inode being freed or being
1857  * initialized.
1858  *
1859  * If successful, this will return the inode for which the @test function
1860  * returned 1 and NULL otherwise.
1861  *
1862  * The @test function is not permitted to take a ref on any inode presented.
1863  * It is also not permitted to sleep.
1864  *
1865  * The caller must hold the RCU read lock.
1866  */
1867 struct inode *find_inode_by_ino_rcu(struct super_block *sb,
1868 				    u64 ino)
1869 {
1870 	struct hlist_head *head = inode_hashtable + hash(sb, ino);
1871 	struct inode *inode;
1872 
1873 	RCU_LOCKDEP_WARN(!rcu_read_lock_held(),
1874 			 "suspicious find_inode_by_ino_rcu() usage");
1875 
1876 	hlist_for_each_entry_rcu(inode, head, i_hash) {
1877 		if (inode->i_ino == ino &&
1878 		    inode->i_sb == sb &&
1879 		    !(inode_state_read_once(inode) & (I_FREEING | I_WILL_FREE)))
1880 		    return inode;
1881 	}
1882 	return NULL;
1883 }
1884 EXPORT_SYMBOL(find_inode_by_ino_rcu);
1885 
1886 int insert_inode_locked(struct inode *inode)
1887 {
1888 	struct super_block *sb = inode->i_sb;
1889 	u64 ino = inode->i_ino;
1890 	struct hlist_head *head = inode_hashtable + hash(sb, ino);
1891 	bool isnew;
1892 
1893 	might_sleep();
1894 
1895 	while (1) {
1896 		struct inode *old = NULL;
1897 		spin_lock(&inode_hash_lock);
1898 repeat:
1899 		hlist_for_each_entry(old, head, i_hash) {
1900 			if (old->i_ino != ino)
1901 				continue;
1902 			if (old->i_sb != sb)
1903 				continue;
1904 			spin_lock(&old->i_lock);
1905 			break;
1906 		}
1907 		if (likely(!old)) {
1908 			spin_lock(&inode->i_lock);
1909 			inode_state_set(inode, I_NEW | I_CREATING);
1910 			hlist_add_head_rcu(&inode->i_hash, head);
1911 			spin_unlock(&inode->i_lock);
1912 			spin_unlock(&inode_hash_lock);
1913 			return 0;
1914 		}
1915 		if (inode_state_read(old) & (I_FREEING | I_WILL_FREE)) {
1916 			__wait_on_freeing_inode(old, true, false);
1917 			old = NULL;
1918 			goto repeat;
1919 		}
1920 		if (unlikely(inode_state_read(old) & I_CREATING)) {
1921 			spin_unlock(&old->i_lock);
1922 			spin_unlock(&inode_hash_lock);
1923 			return -EBUSY;
1924 		}
1925 		__iget(old);
1926 		isnew = !!(inode_state_read(old) & I_NEW);
1927 		spin_unlock(&old->i_lock);
1928 		spin_unlock(&inode_hash_lock);
1929 		if (isnew)
1930 			wait_on_new_inode(old);
1931 		if (unlikely(!inode_unhashed(old))) {
1932 			iput(old);
1933 			return -EBUSY;
1934 		}
1935 		iput(old);
1936 	}
1937 }
1938 EXPORT_SYMBOL(insert_inode_locked);
1939 
1940 int insert_inode_locked4(struct inode *inode, u64 hashval,
1941 		int (*test)(struct inode *, void *), void *data)
1942 {
1943 	struct inode *old;
1944 
1945 	might_sleep();
1946 
1947 	inode_state_set_raw(inode, I_CREATING);
1948 	old = inode_insert5(inode, hashval, test, NULL, data);
1949 
1950 	if (old != inode) {
1951 		iput(old);
1952 		return -EBUSY;
1953 	}
1954 	return 0;
1955 }
1956 EXPORT_SYMBOL(insert_inode_locked4);
1957 
1958 
1959 int inode_just_drop(struct inode *inode)
1960 {
1961 	return 1;
1962 }
1963 EXPORT_SYMBOL(inode_just_drop);
1964 
1965 /*
1966  * Called when we're dropping the last reference
1967  * to an inode.
1968  *
1969  * Call the FS "drop_inode()" function, defaulting to
1970  * the legacy UNIX filesystem behaviour.  If it tells
1971  * us to evict inode, do so.  Otherwise, retain inode
1972  * in cache if fs is alive, sync and evict if fs is
1973  * shutting down.
1974  */
1975 static void iput_final(struct inode *inode)
1976 {
1977 	struct super_block *sb = inode->i_sb;
1978 	const struct super_operations *op = inode->i_sb->s_op;
1979 	int drop;
1980 
1981 	WARN_ON(inode_state_read(inode) & I_NEW);
1982 	VFS_BUG_ON_INODE(icount_read(inode) != 0, inode);
1983 
1984 	if (op->drop_inode)
1985 		drop = op->drop_inode(inode);
1986 	else
1987 		drop = inode_generic_drop(inode);
1988 
1989 	if (!drop &&
1990 	    !(inode_state_read(inode) & I_DONTCACHE) &&
1991 	    (sb->s_flags & SB_ACTIVE)) {
1992 		__inode_lru_list_add(inode, true);
1993 		spin_unlock(&inode->i_lock);
1994 		return;
1995 	}
1996 
1997 	/*
1998 	 * Re-check ->i_count in case the ->drop_inode() hooks played games.
1999 	 * Note we only execute this if the verdict was to drop the inode.
2000 	 */
2001 	VFS_BUG_ON_INODE(icount_read(inode) != 0, inode);
2002 
2003 	if (drop) {
2004 		inode_state_set(inode, I_FREEING);
2005 	} else {
2006 		inode_state_set(inode, I_WILL_FREE);
2007 		spin_unlock(&inode->i_lock);
2008 
2009 		write_inode_now(inode, 1);
2010 
2011 		spin_lock(&inode->i_lock);
2012 		WARN_ON(inode_state_read(inode) & I_NEW);
2013 		inode_state_replace(inode, I_WILL_FREE, I_FREEING);
2014 	}
2015 
2016 	inode_lru_list_del(inode);
2017 	spin_unlock(&inode->i_lock);
2018 
2019 	evict(inode);
2020 }
2021 
2022 /**
2023  *	iput	- put an inode
2024  *	@inode: inode to put
2025  *
2026  *	Puts an inode, dropping its usage count. If the inode use count hits
2027  *	zero, the inode is then freed and may also be destroyed.
2028  *
2029  *	Consequently, iput() can sleep.
2030  */
2031 void iput(struct inode *inode)
2032 {
2033 	might_sleep();
2034 	if (unlikely(!inode))
2035 		return;
2036 
2037 retry:
2038 	lockdep_assert_not_held(&inode->i_lock);
2039 	VFS_BUG_ON_INODE(inode_state_read_once(inode) & (I_FREEING | I_CLEAR), inode);
2040 	/*
2041 	 * Note this assert is technically racy as if the count is bogusly
2042 	 * equal to one, then two CPUs racing to further drop it can both
2043 	 * conclude it's fine.
2044 	 */
2045 	VFS_BUG_ON_INODE(icount_read_once(inode) < 1, inode);
2046 
2047 	if (atomic_add_unless(&inode->i_count, -1, 1))
2048 		return;
2049 
2050 	if (inode->i_nlink && sync_lazytime(inode))
2051 		goto retry;
2052 
2053 	spin_lock(&inode->i_lock);
2054 	if (unlikely((inode_state_read(inode) & I_DIRTY_TIME) && inode->i_nlink)) {
2055 		spin_unlock(&inode->i_lock);
2056 		goto retry;
2057 	}
2058 
2059 	if (!atomic_dec_and_test(&inode->i_count)) {
2060 		spin_unlock(&inode->i_lock);
2061 		return;
2062 	}
2063 
2064 	/*
2065 	 * iput_final() drops ->i_lock, we can't assert on it as the inode may
2066 	 * be deallocated by the time the call returns.
2067 	 */
2068 	iput_final(inode);
2069 }
2070 EXPORT_SYMBOL(iput);
2071 
2072 /**
2073  *	iput_not_last	- put an inode assuming this is not the last reference
2074  *	@inode: inode to put
2075  */
2076 void iput_not_last(struct inode *inode)
2077 {
2078 	VFS_BUG_ON_INODE(inode_state_read_once(inode) & (I_FREEING | I_CLEAR), inode);
2079 	VFS_BUG_ON_INODE(icount_read_once(inode) < 2, inode);
2080 
2081 	WARN_ON(atomic_sub_return(1, &inode->i_count) == 0);
2082 }
2083 EXPORT_SYMBOL(iput_not_last);
2084 
2085 #ifdef CONFIG_BLOCK
2086 /**
2087  *	bmap	- find a block number in a file
2088  *	@inode:  inode owning the block number being requested
2089  *	@block: pointer containing the block to find
2090  *
2091  *	Replaces the value in ``*block`` with the block number on the device holding
2092  *	corresponding to the requested block number in the file.
2093  *	That is, asked for block 4 of inode 1 the function will replace the
2094  *	4 in ``*block``, with disk block relative to the disk start that holds that
2095  *	block of the file.
2096  *
2097  *	Returns -EINVAL in case of error, 0 otherwise. If mapping falls into a
2098  *	hole, returns 0 and ``*block`` is also set to 0.
2099  */
2100 int bmap(struct inode *inode, sector_t *block)
2101 {
2102 	if (!inode->i_mapping->a_ops->bmap)
2103 		return -EINVAL;
2104 
2105 	*block = inode->i_mapping->a_ops->bmap(inode->i_mapping, *block);
2106 	return 0;
2107 }
2108 EXPORT_SYMBOL(bmap);
2109 #endif
2110 
2111 /*
2112  * With relative atime, only update atime if the previous atime is
2113  * earlier than or equal to either the ctime or mtime,
2114  * or if at least a day has passed since the last atime update.
2115  */
2116 static bool relatime_need_update(struct vfsmount *mnt, struct inode *inode,
2117 			     struct timespec64 now)
2118 {
2119 	struct timespec64 atime, mtime, ctime;
2120 
2121 	if (!(mnt->mnt_flags & MNT_RELATIME))
2122 		return true;
2123 	/*
2124 	 * Is mtime younger than or equal to atime? If yes, update atime:
2125 	 */
2126 	atime = inode_get_atime(inode);
2127 	mtime = inode_get_mtime(inode);
2128 	if (timespec64_compare(&mtime, &atime) >= 0)
2129 		return true;
2130 	/*
2131 	 * Is ctime younger than or equal to atime? If yes, update atime:
2132 	 */
2133 	ctime = inode_get_ctime(inode);
2134 	if (timespec64_compare(&ctime, &atime) >= 0)
2135 		return true;
2136 
2137 	/*
2138 	 * Is the previous atime value older than a day? If yes,
2139 	 * update atime:
2140 	 */
2141 	if ((long)(now.tv_sec - atime.tv_sec) >= 24*60*60)
2142 		return true;
2143 	/*
2144 	 * Good, we can skip the atime update:
2145 	 */
2146 	return false;
2147 }
2148 
2149 static int inode_update_atime(struct inode *inode)
2150 {
2151 	struct timespec64 atime = inode_get_atime(inode);
2152 	struct timespec64 now = current_time(inode);
2153 
2154 	if (timespec64_equal(&now, &atime))
2155 		return 0;
2156 
2157 	inode_set_atime_to_ts(inode, now);
2158 	return inode_time_dirty_flag(inode);
2159 }
2160 
2161 static int inode_update_cmtime(struct inode *inode, unsigned int flags)
2162 {
2163 	struct timespec64 ctime = inode_get_ctime(inode);
2164 	struct timespec64 mtime = inode_get_mtime(inode);
2165 	struct timespec64 now = inode_set_ctime_current(inode);
2166 	unsigned int dirty = 0;
2167 	bool mtime_changed;
2168 
2169 	mtime_changed = !timespec64_equal(&now, &mtime);
2170 	if (mtime_changed || !timespec64_equal(&now, &ctime))
2171 		dirty = inode_time_dirty_flag(inode);
2172 
2173 	/*
2174 	 * Pure timestamp updates can be recorded in the inode without blocking
2175 	 * by not dirtying the inode.  But when the file system requires
2176 	 * i_version updates, the update of i_version can still block.
2177 	 * Error out if we'd actually have to update i_version or don't support
2178 	 * lazytime.
2179 	 */
2180 	if (IS_I_VERSION(inode)) {
2181 		if (flags & IOCB_NOWAIT) {
2182 			if (!(inode->i_sb->s_flags & SB_LAZYTIME) ||
2183 			    inode_iversion_need_inc(inode))
2184 				return -EAGAIN;
2185 		} else {
2186 			/*
2187 			 * Don't force iversion increment for pure lazytime
2188 			 * updates (I_DIRTY_TIME only), let I_VERSION_QUERIED
2189 			 * dictate whether the increment is needed.
2190 			 */
2191 			if (inode_maybe_inc_iversion(inode,
2192 						     dirty != I_DIRTY_TIME))
2193 				dirty |= I_DIRTY_SYNC;
2194 		}
2195 	}
2196 
2197 	if (mtime_changed)
2198 		inode_set_mtime_to_ts(inode, now);
2199 	return dirty;
2200 }
2201 
2202 /**
2203  * inode_update_time - update either atime or c/mtime and i_version on the inode
2204  * @inode: inode to be updated
2205  * @type: timestamp to be updated
2206  * @flags: flags for the update
2207  *
2208  * Update either atime or c/mtime and version in a inode if needed for a file
2209  * access or modification.  It is up to the caller to mark the inode dirty
2210  * appropriately.
2211  *
2212  * Returns the positive I_DIRTY_* flags for __mark_inode_dirty() if the inode
2213  * needs to be marked dirty, 0 if it did not, or a negative errno if an error
2214  * happened.
2215  */
2216 int inode_update_time(struct inode *inode, enum fs_update_time type,
2217 		unsigned int flags)
2218 {
2219 	switch (type) {
2220 	case FS_UPD_ATIME:
2221 		return inode_update_atime(inode);
2222 	case FS_UPD_CMTIME:
2223 		return inode_update_cmtime(inode, flags);
2224 	default:
2225 		WARN_ON_ONCE(1);
2226 		return -EIO;
2227 	}
2228 }
2229 EXPORT_SYMBOL(inode_update_time);
2230 
2231 /**
2232  * generic_update_time - update the timestamps on the inode
2233  * @inode: inode to be updated
2234  * @type: timestamp to be updated
2235  * @flags: flags for the update
2236  *
2237  * Returns a negative error value on error, else 0.
2238  */
2239 int generic_update_time(struct inode *inode, enum fs_update_time type,
2240 		unsigned int flags)
2241 {
2242 	int dirty;
2243 
2244 	/*
2245 	 * ->dirty_inode is what could make generic timestamp updates block.
2246 	 * Don't support non-blocking timestamp updates here if it is set.
2247 	 * File systems that implement ->dirty_inode but want to support
2248 	 * non-blocking timestamp updates should call inode_update_time
2249 	 * directly.
2250 	 */
2251 	if ((flags & IOCB_NOWAIT) && inode->i_sb->s_op->dirty_inode)
2252 		return -EAGAIN;
2253 
2254 	dirty = inode_update_time(inode, type, flags);
2255 	if (dirty <= 0)
2256 		return dirty;
2257 	__mark_inode_dirty(inode, dirty);
2258 	return 0;
2259 }
2260 EXPORT_SYMBOL(generic_update_time);
2261 
2262 /**
2263  *	atime_needs_update	-	update the access time
2264  *	@path: the &struct path to update
2265  *	@inode: inode to update
2266  *
2267  *	Update the accessed time on an inode and mark it for writeback.
2268  *	This function automatically handles read only file systems and media,
2269  *	as well as the "noatime" flag and inode specific "noatime" markers.
2270  */
2271 bool atime_needs_update(const struct path *path, struct inode *inode)
2272 {
2273 	struct vfsmount *mnt = path->mnt;
2274 	struct timespec64 now, atime;
2275 
2276 	if (inode->i_flags & S_NOATIME)
2277 		return false;
2278 
2279 	/* Atime updates will likely cause i_uid and i_gid to be written
2280 	 * back improprely if their true value is unknown to the vfs.
2281 	 */
2282 	if (HAS_UNMAPPED_ID(mnt_idmap(mnt), inode))
2283 		return false;
2284 
2285 	if (IS_NOATIME(inode))
2286 		return false;
2287 	if ((inode->i_sb->s_flags & SB_NODIRATIME) && S_ISDIR(inode->i_mode))
2288 		return false;
2289 
2290 	if (mnt->mnt_flags & MNT_NOATIME)
2291 		return false;
2292 	if ((mnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode))
2293 		return false;
2294 
2295 	now = current_time(inode);
2296 
2297 	if (!relatime_need_update(mnt, inode, now))
2298 		return false;
2299 
2300 	atime = inode_get_atime(inode);
2301 	if (timespec64_equal(&atime, &now))
2302 		return false;
2303 
2304 	return true;
2305 }
2306 
2307 void touch_atime(const struct path *path)
2308 {
2309 	struct vfsmount *mnt = path->mnt;
2310 	struct inode *inode = d_inode(path->dentry);
2311 
2312 	if (!atime_needs_update(path, inode))
2313 		return;
2314 
2315 	if (!sb_start_write_trylock(inode->i_sb))
2316 		return;
2317 
2318 	if (mnt_get_write_access(mnt) != 0)
2319 		goto skip_update;
2320 	/*
2321 	 * File systems can error out when updating inodes if they need to
2322 	 * allocate new space to modify an inode (such is the case for
2323 	 * Btrfs), but since we touch atime while walking down the path we
2324 	 * really don't care if we failed to update the atime of the file,
2325 	 * so just ignore the return value.
2326 	 * We may also fail on filesystems that have the ability to make parts
2327 	 * of the fs read only, e.g. subvolumes in Btrfs.
2328 	 */
2329 	if (inode->i_op->update_time)
2330 		inode->i_op->update_time(inode, FS_UPD_ATIME, 0);
2331 	else
2332 		generic_update_time(inode, FS_UPD_ATIME, 0);
2333 	mnt_put_write_access(mnt);
2334 skip_update:
2335 	sb_end_write(inode->i_sb);
2336 }
2337 EXPORT_SYMBOL(touch_atime);
2338 
2339 /*
2340  * Return mask of changes for notify_change() that need to be done as a
2341  * response to write or truncate. Return 0 if nothing has to be changed.
2342  * Negative value on error (change should be denied).
2343  */
2344 int dentry_needs_remove_privs(struct mnt_idmap *idmap,
2345 			      struct dentry *dentry)
2346 {
2347 	struct inode *inode = d_inode(dentry);
2348 	int mask = 0;
2349 	int ret;
2350 
2351 	if (IS_NOSEC(inode))
2352 		return 0;
2353 
2354 	mask = setattr_should_drop_suidgid(idmap, inode);
2355 	ret = security_inode_need_killpriv(dentry);
2356 	if (ret < 0)
2357 		return ret;
2358 	if (ret)
2359 		mask |= ATTR_KILL_PRIV;
2360 	return mask;
2361 }
2362 
2363 static int __remove_privs(struct mnt_idmap *idmap,
2364 			  struct dentry *dentry, int kill)
2365 {
2366 	struct iattr newattrs;
2367 
2368 	newattrs.ia_valid = ATTR_FORCE | kill;
2369 	/*
2370 	 * Note we call this on write, so notify_change will not
2371 	 * encounter any conflicting delegations:
2372 	 */
2373 	return notify_change(idmap, dentry, &newattrs, NULL);
2374 }
2375 
2376 static int file_remove_privs_flags(struct file *file, unsigned int flags)
2377 {
2378 	struct dentry *dentry = file_dentry(file);
2379 	struct inode *inode = file_inode(file);
2380 	int error = 0;
2381 	int kill;
2382 
2383 	if (IS_NOSEC(inode) || !S_ISREG(inode->i_mode))
2384 		return 0;
2385 
2386 	kill = dentry_needs_remove_privs(file_mnt_idmap(file), dentry);
2387 	if (kill < 0)
2388 		return kill;
2389 
2390 	if (kill) {
2391 		if (flags & IOCB_NOWAIT)
2392 			return -EAGAIN;
2393 
2394 		error = __remove_privs(file_mnt_idmap(file), dentry, kill);
2395 	}
2396 
2397 	if (!error)
2398 		inode_has_no_xattr(inode);
2399 	return error;
2400 }
2401 
2402 /**
2403  * file_remove_privs - remove special file privileges (suid, capabilities)
2404  * @file: file to remove privileges from
2405  *
2406  * When file is modified by a write or truncation ensure that special
2407  * file privileges are removed.
2408  *
2409  * Return: 0 on success, negative errno on failure.
2410  */
2411 int file_remove_privs(struct file *file)
2412 {
2413 	return file_remove_privs_flags(file, 0);
2414 }
2415 EXPORT_SYMBOL(file_remove_privs);
2416 
2417 /**
2418  * current_time - Return FS time (possibly fine-grained)
2419  * @inode: inode.
2420  *
2421  * Return the current time truncated to the time granularity supported by
2422  * the fs, as suitable for a ctime/mtime change. If the ctime is flagged
2423  * as having been QUERIED, get a fine-grained timestamp, but don't update
2424  * the floor.
2425  *
2426  * For a multigrain inode, this is effectively an estimate of the timestamp
2427  * that a file would receive. An actual update must go through
2428  * inode_set_ctime_current().
2429  */
2430 struct timespec64 current_time(struct inode *inode)
2431 {
2432 	struct timespec64 now;
2433 	u32 cns;
2434 
2435 	ktime_get_coarse_real_ts64_mg(&now);
2436 
2437 	if (!is_mgtime(inode))
2438 		goto out;
2439 
2440 	/* If nothing has queried it, then coarse time is fine */
2441 	cns = smp_load_acquire(&inode->i_ctime_nsec);
2442 	if (cns & I_CTIME_QUERIED) {
2443 		/*
2444 		 * If there is no apparent change, then get a fine-grained
2445 		 * timestamp.
2446 		 */
2447 		if (now.tv_nsec == (cns & ~I_CTIME_QUERIED))
2448 			ktime_get_real_ts64(&now);
2449 	}
2450 out:
2451 	return timestamp_truncate(now, inode);
2452 }
2453 EXPORT_SYMBOL(current_time);
2454 
2455 static inline bool need_cmtime_update(struct inode *inode)
2456 {
2457 	struct timespec64 now = current_time(inode), ts;
2458 
2459 	ts = inode_get_mtime(inode);
2460 	if (!timespec64_equal(&ts, &now))
2461 		return true;
2462 	ts = inode_get_ctime(inode);
2463 	if (!timespec64_equal(&ts, &now))
2464 		return true;
2465 	return IS_I_VERSION(inode) && inode_iversion_need_inc(inode);
2466 }
2467 
2468 static int file_update_time_flags(struct file *file, unsigned int flags)
2469 {
2470 	struct inode *inode = file_inode(file);
2471 	int ret;
2472 
2473 	/* First try to exhaust all avenues to not sync */
2474 	if (IS_NOCMTIME(inode))
2475 		return 0;
2476 	if (unlikely(file->f_mode & FMODE_NOCMTIME))
2477 		return 0;
2478 	if (!need_cmtime_update(inode))
2479 		return 0;
2480 
2481 	flags &= IOCB_NOWAIT;
2482 	if (mnt_get_write_access_file(file))
2483 		return 0;
2484 	if (inode->i_op->update_time)
2485 		ret = inode->i_op->update_time(inode, FS_UPD_CMTIME, flags);
2486 	else
2487 		ret = generic_update_time(inode, FS_UPD_CMTIME, flags);
2488 	mnt_put_write_access_file(file);
2489 	return ret;
2490 }
2491 
2492 /**
2493  * file_update_time - update mtime and ctime time
2494  * @file: file accessed
2495  *
2496  * Update the mtime and ctime members of an inode and mark the inode for
2497  * writeback. Note that this function is meant exclusively for usage in
2498  * the file write path of filesystems, and filesystems may choose to
2499  * explicitly ignore updates via this function with the _NOCMTIME inode
2500  * flag, e.g. for network filesystem where these imestamps are handled
2501  * by the server. This can return an error for file systems who need to
2502  * allocate space in order to update an inode.
2503  *
2504  * Return: 0 on success, negative errno on failure.
2505  */
2506 int file_update_time(struct file *file)
2507 {
2508 	return file_update_time_flags(file, 0);
2509 }
2510 EXPORT_SYMBOL(file_update_time);
2511 
2512 /**
2513  * file_modified_flags - handle mandated vfs changes when modifying a file
2514  * @file: file that was modified
2515  * @flags: kiocb flags
2516  *
2517  * When file has been modified ensure that special
2518  * file privileges are removed and time settings are updated.
2519  *
2520  * If IOCB_NOWAIT is set, special file privileges will not be removed and
2521  * time settings will not be updated. It will return -EAGAIN.
2522  *
2523  * Context: Caller must hold the file's inode lock.
2524  *
2525  * Return: 0 on success, negative errno on failure.
2526  */
2527 static int file_modified_flags(struct file *file, int flags)
2528 {
2529 	int ret;
2530 
2531 	/*
2532 	 * Clear the security bits if the process is not being run by root.
2533 	 * This keeps people from modifying setuid and setgid binaries.
2534 	 */
2535 	ret = file_remove_privs_flags(file, flags);
2536 	if (ret)
2537 		return ret;
2538 	return file_update_time_flags(file, flags);
2539 }
2540 
2541 /**
2542  * file_modified - handle mandated vfs changes when modifying a file
2543  * @file: file that was modified
2544  *
2545  * When file has been modified ensure that special
2546  * file privileges are removed and time settings are updated.
2547  *
2548  * Context: Caller must hold the file's inode lock.
2549  *
2550  * Return: 0 on success, negative errno on failure.
2551  */
2552 int file_modified(struct file *file)
2553 {
2554 	return file_modified_flags(file, 0);
2555 }
2556 EXPORT_SYMBOL(file_modified);
2557 
2558 /**
2559  * kiocb_modified - handle mandated vfs changes when modifying a file
2560  * @iocb: iocb that was modified
2561  *
2562  * When file has been modified ensure that special
2563  * file privileges are removed and time settings are updated.
2564  *
2565  * Context: Caller must hold the file's inode lock.
2566  *
2567  * Return: 0 on success, negative errno on failure.
2568  */
2569 int kiocb_modified(struct kiocb *iocb)
2570 {
2571 	return file_modified_flags(iocb->ki_filp, iocb->ki_flags);
2572 }
2573 EXPORT_SYMBOL_GPL(kiocb_modified);
2574 
2575 int inode_needs_sync(struct inode *inode)
2576 {
2577 	if (IS_SYNC(inode))
2578 		return 1;
2579 	if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode))
2580 		return 1;
2581 	return 0;
2582 }
2583 EXPORT_SYMBOL(inode_needs_sync);
2584 
2585 /*
2586  * If we try to find an inode in the inode hash while it is being
2587  * deleted, we have to wait until the filesystem completes its
2588  * deletion before reporting that it isn't found.  This function waits
2589  * until the deletion _might_ have completed.  Callers are responsible
2590  * to recheck inode state.
2591  *
2592  * It doesn't matter if I_NEW is not set initially, a call to
2593  * wake_up_bit(&inode->i_state, __I_NEW) after removing from the hash list
2594  * will DTRT.
2595  */
2596 static void __wait_on_freeing_inode(struct inode *inode, bool hash_locked, bool rcu_locked)
2597 {
2598 	struct wait_bit_queue_entry wqe;
2599 	struct wait_queue_head *wq_head;
2600 
2601 	VFS_BUG_ON(!hash_locked && !rcu_locked);
2602 
2603 	/*
2604 	 * Handle racing against evict(), see that routine for more details.
2605 	 */
2606 	if (unlikely(inode_unhashed(inode))) {
2607 		WARN_ON(hash_locked);
2608 		spin_unlock(&inode->i_lock);
2609 		return;
2610 	}
2611 
2612 	wq_head = inode_bit_waitqueue(&wqe, inode, __I_NEW);
2613 	prepare_to_wait_event(wq_head, &wqe.wq_entry, TASK_UNINTERRUPTIBLE);
2614 	spin_unlock(&inode->i_lock);
2615 	if (rcu_locked)
2616 		rcu_read_unlock();
2617 	if (hash_locked)
2618 		spin_unlock(&inode_hash_lock);
2619 	schedule();
2620 	finish_wait(wq_head, &wqe.wq_entry);
2621 	if (hash_locked)
2622 		spin_lock(&inode_hash_lock);
2623 	if (rcu_locked)
2624 		rcu_read_lock();
2625 }
2626 
2627 static __initdata unsigned long ihash_entries;
2628 static int __init set_ihash_entries(char *str)
2629 {
2630 	return kstrtoul(str, 0, &ihash_entries) == 0;
2631 }
2632 __setup("ihash_entries=", set_ihash_entries);
2633 
2634 /*
2635  * Initialize the waitqueues and inode hash table.
2636  */
2637 void __init inode_init_early(void)
2638 {
2639 	/* If hashes are distributed across NUMA nodes, defer
2640 	 * hash allocation until vmalloc space is available.
2641 	 */
2642 	if (hashdist)
2643 		return;
2644 
2645 	inode_hashtable =
2646 		alloc_large_system_hash("Inode-cache",
2647 					sizeof(struct hlist_head),
2648 					ihash_entries,
2649 					14,
2650 					HASH_EARLY | HASH_ZERO,
2651 					&i_hash_shift,
2652 					&i_hash_mask,
2653 					0,
2654 					0);
2655 }
2656 
2657 void __init inode_init(void)
2658 {
2659 	/* inode slab cache */
2660 	inode_cachep = kmem_cache_create("inode_cache",
2661 					 sizeof(struct inode),
2662 					 0,
2663 					 (SLAB_RECLAIM_ACCOUNT|SLAB_PANIC|
2664 					 SLAB_ACCOUNT),
2665 					 init_once);
2666 
2667 	/* Hash may have been set up in inode_init_early */
2668 	if (!hashdist)
2669 		return;
2670 
2671 	inode_hashtable =
2672 		alloc_large_system_hash("Inode-cache",
2673 					sizeof(struct hlist_head),
2674 					ihash_entries,
2675 					14,
2676 					HASH_ZERO,
2677 					&i_hash_shift,
2678 					&i_hash_mask,
2679 					0,
2680 					0);
2681 }
2682 
2683 void init_special_inode(struct inode *inode, umode_t mode, dev_t rdev)
2684 {
2685 	inode->i_mode = mode;
2686 	switch (inode->i_mode & S_IFMT) {
2687 	case S_IFCHR:
2688 		inode->i_fop = &def_chr_fops;
2689 		inode->i_rdev = rdev;
2690 		break;
2691 	case S_IFBLK:
2692 		if (IS_ENABLED(CONFIG_BLOCK))
2693 			inode->i_fop = &def_blk_fops;
2694 		inode->i_rdev = rdev;
2695 		break;
2696 	case S_IFIFO:
2697 		inode->i_fop = &pipefifo_fops;
2698 		break;
2699 	case S_IFSOCK:
2700 		/* leave it no_open_fops */
2701 		break;
2702 	default:
2703 		pr_debug("init_special_inode: bogus i_mode (%o) for inode %s:%llu\n",
2704 			 mode, inode->i_sb->s_id, inode->i_ino);
2705 		break;
2706 	}
2707 }
2708 EXPORT_SYMBOL(init_special_inode);
2709 
2710 /**
2711  * inode_init_owner - Init uid,gid,mode for new inode according to posix standards
2712  * @idmap: idmap of the mount the inode was created from
2713  * @inode: New inode
2714  * @dir: Directory inode
2715  * @mode: mode of the new inode
2716  *
2717  * If the inode has been created through an idmapped mount the idmap of
2718  * the vfsmount must be passed through @idmap. This function will then take
2719  * care to map the inode according to @idmap before checking permissions
2720  * and initializing i_uid and i_gid. On non-idmapped mounts or if permission
2721  * checking is to be performed on the raw inode simply pass @nop_mnt_idmap.
2722  */
2723 void inode_init_owner(struct mnt_idmap *idmap, struct inode *inode,
2724 		      const struct inode *dir, umode_t mode)
2725 {
2726 	inode_fsuid_set(inode, idmap);
2727 	if (dir && dir->i_mode & S_ISGID) {
2728 		inode->i_gid = dir->i_gid;
2729 
2730 		/* Directories are special, and always inherit S_ISGID */
2731 		if (S_ISDIR(mode))
2732 			mode |= S_ISGID;
2733 	} else
2734 		inode_fsgid_set(inode, idmap);
2735 	inode->i_mode = mode;
2736 }
2737 EXPORT_SYMBOL(inode_init_owner);
2738 
2739 /**
2740  * inode_owner_or_capable - check current task permissions to inode
2741  * @idmap: idmap of the mount the inode was found from
2742  * @inode: inode being checked
2743  *
2744  * Return true if current either has CAP_FOWNER in a namespace with the
2745  * inode owner uid mapped, or owns the file.
2746  *
2747  * If the inode has been found through an idmapped mount the idmap of
2748  * the vfsmount must be passed through @idmap. This function will then take
2749  * care to map the inode according to @idmap before checking permissions.
2750  * On non-idmapped mounts or if permission checking is to be performed on the
2751  * raw inode simply pass @nop_mnt_idmap.
2752  */
2753 bool inode_owner_or_capable(struct mnt_idmap *idmap,
2754 			    const struct inode *inode)
2755 {
2756 	vfsuid_t vfsuid;
2757 	struct user_namespace *ns;
2758 
2759 	vfsuid = i_uid_into_vfsuid(idmap, inode);
2760 	if (vfsuid_eq_kuid(vfsuid, current_fsuid()))
2761 		return true;
2762 
2763 	ns = current_user_ns();
2764 	if (vfsuid_has_mapping(ns, vfsuid) && ns_capable(ns, CAP_FOWNER))
2765 		return true;
2766 	return false;
2767 }
2768 EXPORT_SYMBOL(inode_owner_or_capable);
2769 
2770 /*
2771  * Direct i/o helper functions
2772  */
2773 bool inode_dio_finished(const struct inode *inode)
2774 {
2775 	return atomic_read(&inode->i_dio_count) == 0;
2776 }
2777 EXPORT_SYMBOL(inode_dio_finished);
2778 
2779 /**
2780  * inode_dio_wait - wait for outstanding DIO requests to finish
2781  * @inode: inode to wait for
2782  *
2783  * Waits for all pending direct I/O requests to finish so that we can
2784  * proceed with a truncate or equivalent operation.
2785  *
2786  * Must be called under a lock that serializes taking new references
2787  * to i_dio_count, usually by inode->i_rwsem.
2788  */
2789 void inode_dio_wait(struct inode *inode)
2790 {
2791 	wait_var_event(&inode->i_dio_count, inode_dio_finished(inode));
2792 }
2793 EXPORT_SYMBOL(inode_dio_wait);
2794 
2795 void inode_dio_wait_interruptible(struct inode *inode)
2796 {
2797 	wait_var_event_interruptible(&inode->i_dio_count,
2798 				     inode_dio_finished(inode));
2799 }
2800 EXPORT_SYMBOL(inode_dio_wait_interruptible);
2801 
2802 /*
2803  * inode_set_flags - atomically set some inode flags
2804  *
2805  * Note: the caller should be holding i_rwsem exclusively, or else be sure that
2806  * they have exclusive access to the inode structure (i.e., while the
2807  * inode is being instantiated).  The reason for the cmpxchg() loop
2808  * --- which wouldn't be necessary if all code paths which modify
2809  * i_flags actually followed this rule, is that there is at least one
2810  * code path which doesn't today so we use cmpxchg() out of an abundance
2811  * of caution.
2812  *
2813  * In the long run, i_rwsem is overkill, and we should probably look
2814  * at using the i_lock spinlock to protect i_flags, and then make sure
2815  * it is so documented in include/linux/fs.h and that all code follows
2816  * the locking convention!!
2817  */
2818 void inode_set_flags(struct inode *inode, unsigned int flags,
2819 		     unsigned int mask)
2820 {
2821 	WARN_ON_ONCE(flags & ~mask);
2822 	set_mask_bits(&inode->i_flags, mask, flags);
2823 }
2824 EXPORT_SYMBOL(inode_set_flags);
2825 
2826 void inode_nohighmem(struct inode *inode)
2827 {
2828 	mapping_set_gfp_mask(inode->i_mapping, GFP_USER);
2829 }
2830 EXPORT_SYMBOL(inode_nohighmem);
2831 
2832 struct timespec64 inode_set_ctime_to_ts(struct inode *inode, struct timespec64 ts)
2833 {
2834 	trace_inode_set_ctime_to_ts(inode, &ts);
2835 	set_normalized_timespec64(&ts, ts.tv_sec, ts.tv_nsec);
2836 	inode->i_ctime_sec = ts.tv_sec;
2837 	inode->i_ctime_nsec = ts.tv_nsec;
2838 	return ts;
2839 }
2840 EXPORT_SYMBOL(inode_set_ctime_to_ts);
2841 
2842 /**
2843  * timestamp_truncate - Truncate timespec to a granularity
2844  * @t: Timespec
2845  * @inode: inode being updated
2846  *
2847  * Truncate a timespec to the granularity supported by the fs
2848  * containing the inode. Always rounds down. gran must
2849  * not be 0 nor greater than a second (NSEC_PER_SEC, or 10^9 ns).
2850  */
2851 struct timespec64 timestamp_truncate(struct timespec64 t, struct inode *inode)
2852 {
2853 	struct super_block *sb = inode->i_sb;
2854 	unsigned int gran = sb->s_time_gran;
2855 
2856 	t.tv_sec = clamp(t.tv_sec, sb->s_time_min, sb->s_time_max);
2857 	if (unlikely(t.tv_sec == sb->s_time_max || t.tv_sec == sb->s_time_min))
2858 		t.tv_nsec = 0;
2859 
2860 	/* Avoid division in the common cases 1 ns and 1 s. */
2861 	if (gran == 1)
2862 		; /* nothing */
2863 	else if (gran == NSEC_PER_SEC)
2864 		t.tv_nsec = 0;
2865 	else if (gran > 1 && gran < NSEC_PER_SEC)
2866 		t.tv_nsec -= t.tv_nsec % gran;
2867 	else
2868 		WARN(1, "invalid file time granularity: %u", gran);
2869 	return t;
2870 }
2871 EXPORT_SYMBOL(timestamp_truncate);
2872 
2873 /**
2874  * inode_set_ctime_current - set the ctime to current_time
2875  * @inode: inode
2876  *
2877  * Set the inode's ctime to the current value for the inode. Returns the
2878  * current value that was assigned. If this is not a multigrain inode, then we
2879  * set it to the later of the coarse time and floor value.
2880  *
2881  * If it is multigrain, then we first see if the coarse-grained timestamp is
2882  * distinct from what is already there. If so, then use that. Otherwise, get a
2883  * fine-grained timestamp.
2884  *
2885  * After that, try to swap the new value into i_ctime_nsec. Accept the
2886  * resulting ctime, regardless of the outcome of the swap. If it has
2887  * already been replaced, then that timestamp is later than the earlier
2888  * unacceptable one, and is thus acceptable.
2889  */
2890 struct timespec64 inode_set_ctime_current(struct inode *inode)
2891 {
2892 	struct timespec64 now;
2893 	u32 cns, cur;
2894 
2895 	ktime_get_coarse_real_ts64_mg(&now);
2896 	now = timestamp_truncate(now, inode);
2897 
2898 	/* Just return that if this is not a multigrain fs */
2899 	if (!is_mgtime(inode)) {
2900 		inode_set_ctime_to_ts(inode, now);
2901 		goto out;
2902 	}
2903 
2904 	/*
2905 	 * A fine-grained time is only needed if someone has queried
2906 	 * for timestamps, and the current coarse grained time isn't
2907 	 * later than what's already there.
2908 	 */
2909 	cns = smp_load_acquire(&inode->i_ctime_nsec);
2910 	if (cns & I_CTIME_QUERIED) {
2911 		struct timespec64 ctime = { .tv_sec = inode->i_ctime_sec,
2912 					    .tv_nsec = cns & ~I_CTIME_QUERIED };
2913 
2914 		if (timespec64_compare(&now, &ctime) <= 0) {
2915 			ktime_get_real_ts64_mg(&now);
2916 			now = timestamp_truncate(now, inode);
2917 			mgtime_counter_inc(mg_fine_stamps);
2918 		}
2919 	}
2920 	mgtime_counter_inc(mg_ctime_updates);
2921 
2922 	/* No need to cmpxchg if it's exactly the same */
2923 	if (cns == now.tv_nsec && inode->i_ctime_sec == now.tv_sec) {
2924 		trace_ctime_xchg_skip(inode, &now);
2925 		goto out;
2926 	}
2927 	cur = cns;
2928 retry:
2929 	/* Try to swap the nsec value into place. */
2930 	if (try_cmpxchg(&inode->i_ctime_nsec, &cur, now.tv_nsec)) {
2931 		/* If swap occurred, then we're (mostly) done */
2932 		inode->i_ctime_sec = now.tv_sec;
2933 		trace_ctime_ns_xchg(inode, cns, now.tv_nsec, cur);
2934 		mgtime_counter_inc(mg_ctime_swaps);
2935 	} else {
2936 		/*
2937 		 * Was the change due to someone marking the old ctime QUERIED?
2938 		 * If so then retry the swap. This can only happen once since
2939 		 * the only way to clear I_CTIME_QUERIED is to stamp the inode
2940 		 * with a new ctime.
2941 		 */
2942 		if (!(cns & I_CTIME_QUERIED) && (cns | I_CTIME_QUERIED) == cur) {
2943 			cns = cur;
2944 			goto retry;
2945 		}
2946 		/* Otherwise, keep the existing ctime */
2947 		now.tv_sec = inode->i_ctime_sec;
2948 		now.tv_nsec = cur & ~I_CTIME_QUERIED;
2949 	}
2950 out:
2951 	return now;
2952 }
2953 EXPORT_SYMBOL(inode_set_ctime_current);
2954 
2955 /**
2956  * inode_set_ctime_deleg - try to update the ctime on a delegated inode
2957  * @inode: inode to update
2958  * @update: timespec64 to set the ctime
2959  *
2960  * Attempt to atomically update the ctime on behalf of a delegation holder.
2961  *
2962  * The nfs server can call back the holder of a delegation to get updated
2963  * inode attributes, including the mtime. When updating the mtime, update
2964  * the ctime to a value at least equal to that.
2965  *
2966  * This can race with concurrent updates to the inode, in which
2967  * case the update is skipped.
2968  *
2969  * Note that this works even when multigrain timestamps are not enabled,
2970  * so it is used in either case.
2971  */
2972 struct timespec64 inode_set_ctime_deleg(struct inode *inode, struct timespec64 update)
2973 {
2974 	struct timespec64 now, cur_ts;
2975 	u32 cur, old;
2976 
2977 	/* pairs with try_cmpxchg below */
2978 	cur = smp_load_acquire(&inode->i_ctime_nsec);
2979 	cur_ts.tv_nsec = cur & ~I_CTIME_QUERIED;
2980 	cur_ts.tv_sec = inode->i_ctime_sec;
2981 
2982 	/* If the update is older than the existing value, skip it. */
2983 	if (timespec64_compare(&update, &cur_ts) <= 0)
2984 		return cur_ts;
2985 
2986 	ktime_get_coarse_real_ts64_mg(&now);
2987 
2988 	/* Clamp the update to "now" if it's in the future */
2989 	if (timespec64_compare(&update, &now) > 0)
2990 		update = now;
2991 
2992 	update = timestamp_truncate(update, inode);
2993 
2994 	/* No need to update if the values are already the same */
2995 	if (timespec64_equal(&update, &cur_ts))
2996 		return cur_ts;
2997 
2998 	/*
2999 	 * Try to swap the nsec value into place. If it fails, that means
3000 	 * it raced with an update due to a write or similar activity. That
3001 	 * stamp takes precedence, so just skip the update.
3002 	 */
3003 retry:
3004 	old = cur;
3005 	if (try_cmpxchg(&inode->i_ctime_nsec, &cur, update.tv_nsec)) {
3006 		inode->i_ctime_sec = update.tv_sec;
3007 		mgtime_counter_inc(mg_ctime_swaps);
3008 		return update;
3009 	}
3010 
3011 	/*
3012 	 * Was the change due to another task marking the old ctime QUERIED?
3013 	 *
3014 	 * If so, then retry the swap. This can only happen once since
3015 	 * the only way to clear I_CTIME_QUERIED is to stamp the inode
3016 	 * with a new ctime.
3017 	 */
3018 	if (!(old & I_CTIME_QUERIED) && (cur == (old | I_CTIME_QUERIED)))
3019 		goto retry;
3020 
3021 	/* Otherwise, it was a new timestamp. */
3022 	cur_ts.tv_sec = inode->i_ctime_sec;
3023 	cur_ts.tv_nsec = cur & ~I_CTIME_QUERIED;
3024 	return cur_ts;
3025 }
3026 EXPORT_SYMBOL(inode_set_ctime_deleg);
3027 
3028 /**
3029  * in_group_or_capable - check whether caller is CAP_FSETID privileged
3030  * @idmap:	idmap of the mount @inode was found from
3031  * @inode:	inode to check
3032  * @vfsgid:	the new/current vfsgid of @inode
3033  *
3034  * Check whether @vfsgid is in the caller's group list or if the caller is
3035  * privileged with CAP_FSETID over @inode. This can be used to determine
3036  * whether the setgid bit can be kept or must be dropped.
3037  *
3038  * Return: true if the caller is sufficiently privileged, false if not.
3039  */
3040 bool in_group_or_capable(struct mnt_idmap *idmap,
3041 			 const struct inode *inode, vfsgid_t vfsgid)
3042 {
3043 	if (vfsgid_in_group_p(vfsgid))
3044 		return true;
3045 	if (capable_wrt_inode_uidgid(idmap, inode, CAP_FSETID))
3046 		return true;
3047 	return false;
3048 }
3049 EXPORT_SYMBOL(in_group_or_capable);
3050 
3051 /**
3052  * mode_strip_sgid - handle the sgid bit for non-directories
3053  * @idmap: idmap of the mount the inode was created from
3054  * @dir: parent directory inode
3055  * @mode: mode of the file to be created in @dir
3056  *
3057  * If the @mode of the new file has both the S_ISGID and S_IXGRP bit
3058  * raised and @dir has the S_ISGID bit raised ensure that the caller is
3059  * either in the group of the parent directory or they have CAP_FSETID
3060  * in their user namespace and are privileged over the parent directory.
3061  * In all other cases, strip the S_ISGID bit from @mode.
3062  *
3063  * Return: the new mode to use for the file
3064  */
3065 umode_t mode_strip_sgid(struct mnt_idmap *idmap,
3066 			const struct inode *dir, umode_t mode)
3067 {
3068 	if ((mode & (S_ISGID | S_IXGRP)) != (S_ISGID | S_IXGRP))
3069 		return mode;
3070 	if (S_ISDIR(mode) || !dir || !(dir->i_mode & S_ISGID))
3071 		return mode;
3072 	if (in_group_or_capable(idmap, dir, i_gid_into_vfsgid(idmap, dir)))
3073 		return mode;
3074 	return mode & ~S_ISGID;
3075 }
3076 EXPORT_SYMBOL(mode_strip_sgid);
3077 
3078 #ifdef CONFIG_DEBUG_VFS
3079 /**
3080  * dump_inode - dump an inode.
3081  * @inode: inode to dump
3082  * @reason: reason for dumping
3083  *
3084  * If inode is an invalid pointer, we don't want to crash accessing it,
3085  * so probe everything depending on it carefully with get_kernel_nofault().
3086  */
3087 void dump_inode(struct inode *inode, const char *reason)
3088 {
3089 	struct super_block *sb;
3090 	struct file_system_type *s_type;
3091 	const char *fs_name_ptr;
3092 	char fs_name[32] = {};
3093 	umode_t mode;
3094 	unsigned short opflags;
3095 	unsigned int flags;
3096 	unsigned int state;
3097 	int count;
3098 
3099 	if (get_kernel_nofault(sb, &inode->i_sb) ||
3100 	    get_kernel_nofault(mode, &inode->i_mode) ||
3101 	    get_kernel_nofault(opflags, &inode->i_opflags) ||
3102 	    get_kernel_nofault(flags, &inode->i_flags)) {
3103 		pr_warn("%s: unreadable inode:%px\n", reason, inode);
3104 		return;
3105 	}
3106 
3107 	state = inode_state_read_once(inode);
3108 	count = icount_read_once(inode);
3109 
3110 	if (!sb ||
3111 	    get_kernel_nofault(s_type, &sb->s_type) || !s_type ||
3112 	    get_kernel_nofault(fs_name_ptr, &s_type->name) || !fs_name_ptr ||
3113 	    strncpy_from_kernel_nofault(fs_name, fs_name_ptr, sizeof(fs_name) - 1) < 0)
3114 		strscpy(fs_name, "<unknown, sb unreadable>");
3115 
3116 	pr_warn("%s: inode:%px fs:%s mode:%ho opflags:%#x flags:%#x state:%#x count:%d\n",
3117 		reason, inode, fs_name, mode, opflags, flags, state, count);
3118 }
3119 EXPORT_SYMBOL(dump_inode);
3120 #endif
3121