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