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