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