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