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