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