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