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