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