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