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