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