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