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