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