xref: /linux/include/linux/fs.h (revision afdf0fb340948a8c0f581ed1dc42828af89b80b6)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_FS_H
3 #define _LINUX_FS_H
4 
5 #include <linux/fs/super.h>
6 #include <linux/vfsdebug.h>
7 #include <linux/linkage.h>
8 #include <linux/wait_bit.h>
9 #include <linux/kdev_t.h>
10 #include <linux/dcache.h>
11 #include <linux/path.h>
12 #include <linux/stat.h>
13 #include <linux/cache.h>
14 #include <linux/list.h>
15 #include <linux/llist.h>
16 #include <linux/radix-tree.h>
17 #include <linux/xarray.h>
18 #include <linux/rbtree.h>
19 #include <linux/init.h>
20 #include <linux/pid.h>
21 #include <linux/bug.h>
22 #include <linux/mutex.h>
23 #include <linux/rwsem.h>
24 #include <linux/mm_types.h>
25 #include <linux/capability.h>
26 #include <linux/semaphore.h>
27 #include <linux/fcntl.h>
28 #include <linux/rculist_bl.h>
29 #include <linux/atomic.h>
30 #include <linux/shrinker.h>
31 #include <linux/migrate_mode.h>
32 #include <linux/uidgid.h>
33 #include <linux/lockdep.h>
34 #include <linux/percpu-rwsem.h>
35 #include <linux/workqueue.h>
36 #include <linux/delayed_call.h>
37 #include <linux/uuid.h>
38 #include <linux/errseq.h>
39 #include <linux/ioprio.h>
40 #include <linux/build_bug.h>
41 #include <linux/stddef.h>
42 #include <linux/mount.h>
43 #include <linux/cred.h>
44 #include <linux/mnt_idmapping.h>
45 #include <linux/slab.h>
46 #include <linux/maple_tree.h>
47 #include <linux/rw_hint.h>
48 #include <linux/file_ref.h>
49 #include <linux/unicode.h>
50 
51 #include <asm/byteorder.h>
52 #include <uapi/linux/fs.h>
53 
54 struct bdi_writeback;
55 struct bio;
56 struct io_comp_batch;
57 struct fiemap_extent_info;
58 struct hd_geometry;
59 struct iovec;
60 struct kiocb;
61 struct kobject;
62 struct pipe_inode_info;
63 struct poll_table_struct;
64 struct kstatfs;
65 struct vm_area_struct;
66 struct vfsmount;
67 struct cred;
68 struct swap_info_struct;
69 struct seq_file;
70 struct iov_iter;
71 struct fsnotify_mark_connector;
72 struct fs_context;
73 struct fs_parameter_spec;
74 struct file_kattr;
75 struct iomap_ops;
76 
77 extern void __init inode_init(void);
78 extern void __init inode_init_early(void);
79 extern void __init files_init(void);
80 extern void __init files_maxfiles_init(void);
81 
82 extern unsigned long get_max_files(void);
83 extern unsigned int sysctl_nr_open;
84 
85 typedef __kernel_rwf_t rwf_t;
86 
87 struct buffer_head;
88 typedef int (get_block_t)(struct inode *inode, sector_t iblock,
89 			struct buffer_head *bh_result, int create);
90 typedef int (dio_iodone_t)(struct kiocb *iocb, loff_t offset,
91 			ssize_t bytes, void *private);
92 
93 #define MAY_EXEC		0x00000001
94 #define MAY_WRITE		0x00000002
95 #define MAY_READ		0x00000004
96 #define MAY_APPEND		0x00000008
97 #define MAY_ACCESS		0x00000010
98 #define MAY_OPEN		0x00000020
99 #define MAY_CHDIR		0x00000040
100 /* called from RCU mode, don't block */
101 #define MAY_NOT_BLOCK		0x00000080
102 
103 /*
104  * flags in file.f_mode.  Note that FMODE_READ and FMODE_WRITE must correspond
105  * to O_WRONLY and O_RDWR via the strange trick in do_dentry_open()
106  */
107 
108 /* file is open for reading */
109 #define FMODE_READ		((__force fmode_t)(1 << 0))
110 /* file is open for writing */
111 #define FMODE_WRITE		((__force fmode_t)(1 << 1))
112 /* file is seekable */
113 #define FMODE_LSEEK		((__force fmode_t)(1 << 2))
114 /* file can be accessed using pread */
115 #define FMODE_PREAD		((__force fmode_t)(1 << 3))
116 /* file can be accessed using pwrite */
117 #define FMODE_PWRITE		((__force fmode_t)(1 << 4))
118 /* File is opened for execution with sys_execve / sys_uselib */
119 #define FMODE_EXEC		((__force fmode_t)(1 << 5))
120 /* File writes are restricted (block device specific) */
121 #define FMODE_WRITE_RESTRICTED	((__force fmode_t)(1 << 6))
122 /* File supports atomic writes */
123 #define FMODE_CAN_ATOMIC_WRITE	((__force fmode_t)(1 << 7))
124 
125 /* FMODE_* bit 8 */
126 
127 /* 32bit hashes as llseek() offset (for directories) */
128 #define FMODE_32BITHASH         ((__force fmode_t)(1 << 9))
129 /* 64bit hashes as llseek() offset (for directories) */
130 #define FMODE_64BITHASH         ((__force fmode_t)(1 << 10))
131 
132 /*
133  * Don't update ctime and mtime.
134  *
135  * Currently a special hack for the XFS open_by_handle ioctl, but we'll
136  * hopefully graduate it to a proper O_CMTIME flag supported by open(2) soon.
137  */
138 #define FMODE_NOCMTIME		((__force fmode_t)(1 << 11))
139 
140 /* Expect random access pattern */
141 #define FMODE_RANDOM		((__force fmode_t)(1 << 12))
142 
143 /* Supports IOCB_HAS_METADATA */
144 #define FMODE_HAS_METADATA	((__force fmode_t)(1 << 13))
145 
146 /* File is opened with O_PATH; almost nothing can be done with it */
147 #define FMODE_PATH		((__force fmode_t)(1 << 14))
148 
149 /* File needs atomic accesses to f_pos */
150 #define FMODE_ATOMIC_POS	((__force fmode_t)(1 << 15))
151 /* Write access to underlying fs */
152 #define FMODE_WRITER		((__force fmode_t)(1 << 16))
153 /* Has read method(s) */
154 #define FMODE_CAN_READ          ((__force fmode_t)(1 << 17))
155 /* Has write method(s) */
156 #define FMODE_CAN_WRITE         ((__force fmode_t)(1 << 18))
157 
158 #define FMODE_OPENED		((__force fmode_t)(1 << 19))
159 #define FMODE_CREATED		((__force fmode_t)(1 << 20))
160 
161 /* File is stream-like */
162 #define FMODE_STREAM		((__force fmode_t)(1 << 21))
163 
164 /* File supports DIRECT IO */
165 #define	FMODE_CAN_ODIRECT	((__force fmode_t)(1 << 22))
166 
167 #define	FMODE_NOREUSE		((__force fmode_t)(1 << 23))
168 
169 /* File is embedded in backing_file object */
170 #define FMODE_BACKING		((__force fmode_t)(1 << 24))
171 
172 /*
173  * Together with FMODE_NONOTIFY_PERM defines which fsnotify events shouldn't be
174  * generated (see below)
175  */
176 #define FMODE_NONOTIFY		((__force fmode_t)(1 << 25))
177 
178 /*
179  * Together with FMODE_NONOTIFY defines which fsnotify events shouldn't be
180  * generated (see below)
181  */
182 #define FMODE_NONOTIFY_PERM	((__force fmode_t)(1 << 26))
183 
184 /* File is capable of returning -EAGAIN if I/O will block */
185 #define FMODE_NOWAIT		((__force fmode_t)(1 << 27))
186 
187 /* File represents mount that needs unmounting */
188 #define FMODE_NEED_UNMOUNT	((__force fmode_t)(1 << 28))
189 
190 /* File does not contribute to nr_files count */
191 #define FMODE_NOACCOUNT		((__force fmode_t)(1 << 29))
192 
193 /*
194  * The two FMODE_NONOTIFY* define which fsnotify events should not be generated
195  * for an open file. These are the possible values of
196  * (f->f_mode & FMODE_FSNOTIFY_MASK) and their meaning:
197  *
198  * FMODE_NONOTIFY - suppress all (incl. non-permission) events.
199  * FMODE_NONOTIFY_PERM - suppress permission (incl. pre-content) events.
200  * FMODE_NONOTIFY | FMODE_NONOTIFY_PERM - suppress only FAN_ACCESS_PERM.
201  */
202 #define FMODE_FSNOTIFY_MASK \
203 	(FMODE_NONOTIFY | FMODE_NONOTIFY_PERM)
204 
205 #define FMODE_FSNOTIFY_NONE(mode) \
206 	((mode & FMODE_FSNOTIFY_MASK) == FMODE_NONOTIFY)
207 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
208 #define FMODE_FSNOTIFY_HSM(mode) \
209 	((mode & FMODE_FSNOTIFY_MASK) == 0 || \
210 	 (mode & FMODE_FSNOTIFY_MASK) == (FMODE_NONOTIFY | FMODE_NONOTIFY_PERM))
211 #define FMODE_FSNOTIFY_ACCESS_PERM(mode) \
212 	((mode & FMODE_FSNOTIFY_MASK) == 0)
213 #else
214 #define FMODE_FSNOTIFY_ACCESS_PERM(mode) 0
215 #define FMODE_FSNOTIFY_HSM(mode)	0
216 #endif
217 
218 /*
219  * Attribute flags.  These should be or-ed together to figure out what
220  * has been changed!
221  */
222 #define ATTR_MODE	(1 << 0)
223 #define ATTR_UID	(1 << 1)
224 #define ATTR_GID	(1 << 2)
225 #define ATTR_SIZE	(1 << 3)
226 #define ATTR_ATIME	(1 << 4)
227 #define ATTR_MTIME	(1 << 5)
228 #define ATTR_CTIME	(1 << 6)
229 #define ATTR_ATIME_SET	(1 << 7)
230 #define ATTR_MTIME_SET	(1 << 8)
231 #define ATTR_FORCE	(1 << 9) /* Not a change, but a change it */
232 #define ATTR_CTIME_SET	(1 << 10)
233 #define ATTR_KILL_SUID	(1 << 11)
234 #define ATTR_KILL_SGID	(1 << 12)
235 #define ATTR_FILE	(1 << 13)
236 #define ATTR_KILL_PRIV	(1 << 14)
237 #define ATTR_OPEN	(1 << 15) /* Truncating from open(O_TRUNC) */
238 #define ATTR_TIMES_SET	(1 << 16)
239 #define ATTR_TOUCH	(1 << 17)
240 #define ATTR_DELEG	(1 << 18) /* Delegated attrs. Don't break write delegations */
241 
242 /*
243  * Whiteout is represented by a char device.  The following constants define the
244  * mode and device number to use.
245  */
246 #define WHITEOUT_MODE 0
247 #define WHITEOUT_DEV 0
248 
249 /*
250  * This is the Inode Attributes structure, used for notify_change().  It
251  * uses the above definitions as flags, to know which values have changed.
252  * Also, in this manner, a Filesystem can look at only the values it cares
253  * about.  Basically, these are the attributes that the VFS layer can
254  * request to change from the FS layer.
255  *
256  * Derek Atkins <warlord@MIT.EDU> 94-10-20
257  */
258 struct iattr {
259 	unsigned int	ia_valid;
260 	umode_t		ia_mode;
261 	/*
262 	 * The two anonymous unions wrap structures with the same member.
263 	 *
264 	 * Filesystems raising FS_ALLOW_IDMAP need to use ia_vfs{g,u}id which
265 	 * are a dedicated type requiring the filesystem to use the dedicated
266 	 * helpers. Other filesystem can continue to use ia_{g,u}id until they
267 	 * have been ported.
268 	 *
269 	 * They always contain the same value. In other words FS_ALLOW_IDMAP
270 	 * pass down the same value on idmapped mounts as they would on regular
271 	 * mounts.
272 	 */
273 	union {
274 		kuid_t		ia_uid;
275 		vfsuid_t	ia_vfsuid;
276 	};
277 	union {
278 		kgid_t		ia_gid;
279 		vfsgid_t	ia_vfsgid;
280 	};
281 	loff_t		ia_size;
282 	struct timespec64 ia_atime;
283 	struct timespec64 ia_mtime;
284 	struct timespec64 ia_ctime;
285 
286 	/*
287 	 * Not an attribute, but an auxiliary info for filesystems wanting to
288 	 * implement an ftruncate() like method.  NOTE: filesystem should
289 	 * check for (ia_valid & ATTR_FILE), and not for (ia_file != NULL).
290 	 */
291 	struct file	*ia_file;
292 };
293 
294 /*
295  * Maximum number of layers of fs stack.  Needs to be limited to
296  * prevent kernel stack overflow
297  */
298 #define FILESYSTEM_MAX_STACK_DEPTH 2
299 
300 /**
301  * enum positive_aop_returns - aop return codes with specific semantics
302  *
303  * @AOP_WRITEPAGE_ACTIVATE: Informs the caller that page writeback has
304  * 			    completed, that the page is still locked, and
305  * 			    should be considered active.  The VM uses this hint
306  * 			    to return the page to the active list -- it won't
307  * 			    be a candidate for writeback again in the near
308  * 			    future.  Other callers must be careful to unlock
309  * 			    the page if they get this return.  Returned by
310  * 			    writepage();
311  *
312  * @AOP_TRUNCATED_PAGE: The AOP method that was handed a locked page has
313  *  			unlocked it and the page might have been truncated.
314  *  			The caller should back up to acquiring a new page and
315  *  			trying again.  The aop will be taking reasonable
316  *  			precautions not to livelock.  If the caller held a page
317  *  			reference, it should drop it before retrying.  Returned
318  *  			by read_folio().
319  *
320  * address_space_operation functions return these large constants to indicate
321  * special semantics to the caller.  These are much larger than the bytes in a
322  * page to allow for functions that return the number of bytes operated on in a
323  * given page.
324  */
325 
326 enum positive_aop_returns {
327 	AOP_WRITEPAGE_ACTIVATE	= 0x80000,
328 	AOP_TRUNCATED_PAGE	= 0x80001,
329 };
330 
331 /*
332  * oh the beauties of C type declarations.
333  */
334 struct page;
335 struct address_space;
336 struct writeback_control;
337 struct readahead_control;
338 
339 /* Match RWF_* bits to IOCB bits */
340 #define IOCB_HIPRI		(__force int) RWF_HIPRI
341 #define IOCB_DSYNC		(__force int) RWF_DSYNC
342 #define IOCB_SYNC		(__force int) RWF_SYNC
343 #define IOCB_NOWAIT		(__force int) RWF_NOWAIT
344 #define IOCB_APPEND		(__force int) RWF_APPEND
345 #define IOCB_ATOMIC		(__force int) RWF_ATOMIC
346 #define IOCB_DONTCACHE		(__force int) RWF_DONTCACHE
347 #define IOCB_NOSIGNAL		(__force int) RWF_NOSIGNAL
348 
349 /* non-RWF related bits - start at 16 */
350 #define IOCB_EVENTFD		(1 << 16)
351 #define IOCB_DIRECT		(1 << 17)
352 #define IOCB_WRITE		(1 << 18)
353 /* iocb->ki_waitq is valid */
354 #define IOCB_WAITQ		(1 << 19)
355 #define IOCB_NOIO		(1 << 20)
356 /* can use bio alloc cache */
357 #define IOCB_ALLOC_CACHE	(1 << 21)
358 /* kiocb is a read or write operation submitted by fs/aio.c. */
359 #define IOCB_AIO_RW		(1 << 22)
360 #define IOCB_HAS_METADATA	(1 << 23)
361 
362 /* for use in trace events */
363 #define TRACE_IOCB_STRINGS \
364 	{ IOCB_HIPRI,		"HIPRI" }, \
365 	{ IOCB_DSYNC,		"DSYNC" }, \
366 	{ IOCB_SYNC,		"SYNC" }, \
367 	{ IOCB_NOWAIT,		"NOWAIT" }, \
368 	{ IOCB_APPEND,		"APPEND" }, \
369 	{ IOCB_ATOMIC,		"ATOMIC" }, \
370 	{ IOCB_DONTCACHE,	"DONTCACHE" }, \
371 	{ IOCB_EVENTFD,		"EVENTFD"}, \
372 	{ IOCB_DIRECT,		"DIRECT" }, \
373 	{ IOCB_WRITE,		"WRITE" }, \
374 	{ IOCB_WAITQ,		"WAITQ" }, \
375 	{ IOCB_NOIO,		"NOIO" }, \
376 	{ IOCB_ALLOC_CACHE,	"ALLOC_CACHE" }, \
377 	{ IOCB_AIO_RW,		"AIO_RW" }, \
378 	{ IOCB_HAS_METADATA,	"AIO_HAS_METADATA" }
379 
380 struct kiocb {
381 	struct file		*ki_filp;
382 	loff_t			ki_pos;
383 	void (*ki_complete)(struct kiocb *iocb, long ret);
384 	void			*private;
385 	int			ki_flags;
386 	u16			ki_ioprio; /* See linux/ioprio.h */
387 	u8			ki_write_stream;
388 
389 	/*
390 	 * Only used for async buffered reads, where it denotes the page
391 	 * waitqueue associated with completing the read.
392 	 * Valid IFF IOCB_WAITQ is set.
393 	 */
394 	struct wait_page_queue	*ki_waitq;
395 };
396 
is_sync_kiocb(struct kiocb * kiocb)397 static inline bool is_sync_kiocb(struct kiocb *kiocb)
398 {
399 	return kiocb->ki_complete == NULL;
400 }
401 
402 struct address_space_operations {
403 	int (*read_folio)(struct file *, struct folio *);
404 
405 	/* Write back some dirty pages from this mapping. */
406 	int (*writepages)(struct address_space *, struct writeback_control *);
407 
408 	/* Mark a folio dirty.  Return true if this dirtied it */
409 	bool (*dirty_folio)(struct address_space *, struct folio *);
410 
411 	void (*readahead)(struct readahead_control *);
412 
413 	int (*write_begin)(const struct kiocb *, struct address_space *mapping,
414 				loff_t pos, unsigned len,
415 				struct folio **foliop, void **fsdata);
416 	int (*write_end)(const struct kiocb *, struct address_space *mapping,
417 				loff_t pos, unsigned len, unsigned copied,
418 				struct folio *folio, void *fsdata);
419 
420 	/* Unfortunately this kludge is needed for FIBMAP. Don't use it */
421 	sector_t (*bmap)(struct address_space *, sector_t);
422 	void (*invalidate_folio) (struct folio *, size_t offset, size_t len);
423 	bool (*release_folio)(struct folio *, gfp_t);
424 	void (*free_folio)(struct folio *folio);
425 	ssize_t (*direct_IO)(struct kiocb *, struct iov_iter *iter);
426 	/*
427 	 * migrate the contents of a folio to the specified target. If
428 	 * migrate_mode is MIGRATE_ASYNC, it must not block.
429 	 */
430 	int (*migrate_folio)(struct address_space *, struct folio *dst,
431 			struct folio *src, enum migrate_mode);
432 	int (*launder_folio)(struct folio *);
433 	bool (*is_partially_uptodate) (struct folio *, size_t from,
434 			size_t count);
435 	void (*is_dirty_writeback) (struct folio *, bool *dirty, bool *wb);
436 	int (*error_remove_folio)(struct address_space *, struct folio *);
437 
438 	/* swapfile support */
439 	int (*swap_activate)(struct swap_info_struct *sis, struct file *file,
440 				sector_t *span);
441 	void (*swap_deactivate)(struct file *file);
442 	int (*swap_rw)(struct kiocb *iocb, struct iov_iter *iter);
443 };
444 
445 extern const struct address_space_operations empty_aops;
446 
447 /**
448  * struct address_space - Contents of a cacheable, mappable object.
449  * @host: Owner, either the inode or the block_device.
450  * @i_pages: Cached pages.
451  * @invalidate_lock: Guards coherency between page cache contents and
452  *   file offset->disk block mappings in the filesystem during invalidates.
453  *   It is also used to block modification of page cache contents through
454  *   memory mappings.
455  * @gfp_mask: Memory allocation flags to use for allocating pages.
456  * @i_mmap_writable: Number of VM_SHARED, VM_MAYWRITE mappings.
457  * @nr_thps: Number of THPs in the pagecache (non-shmem only).
458  * @i_mmap: Tree of private and shared mappings.
459  * @i_mmap_rwsem: Protects @i_mmap and @i_mmap_writable.
460  * @nrpages: Number of page entries, protected by the i_pages lock.
461  * @writeback_index: Writeback starts here.
462  * @a_ops: Methods.
463  * @flags: Error bits and flags (AS_*).
464  * @wb_err: The most recent error which has occurred.
465  * @i_private_lock: For use by the owner of the address_space.
466  * @i_private_list: For use by the owner of the address_space.
467  * @i_private_data: For use by the owner of the address_space.
468  */
469 struct address_space {
470 	struct inode		*host;
471 	struct xarray		i_pages;
472 	struct rw_semaphore	invalidate_lock;
473 	gfp_t			gfp_mask;
474 	atomic_t		i_mmap_writable;
475 #ifdef CONFIG_READ_ONLY_THP_FOR_FS
476 	/* number of thp, only for non-shmem files */
477 	atomic_t		nr_thps;
478 #endif
479 	struct rb_root_cached	i_mmap;
480 	unsigned long		nrpages;
481 	pgoff_t			writeback_index;
482 	const struct address_space_operations *a_ops;
483 	unsigned long		flags;
484 	errseq_t		wb_err;
485 	spinlock_t		i_private_lock;
486 	struct list_head	i_private_list;
487 	struct rw_semaphore	i_mmap_rwsem;
488 	void *			i_private_data;
489 } __attribute__((aligned(sizeof(long)))) __randomize_layout;
490 	/*
491 	 * On most architectures that alignment is already the case; but
492 	 * must be enforced here for CRIS, to let the least significant bit
493 	 * of struct folio's "mapping" pointer be used for FOLIO_MAPPING_ANON.
494 	 */
495 
496 /* XArray tags, for tagging dirty and writeback pages in the pagecache. */
497 #define PAGECACHE_TAG_DIRTY	XA_MARK_0
498 #define PAGECACHE_TAG_WRITEBACK	XA_MARK_1
499 #define PAGECACHE_TAG_TOWRITE	XA_MARK_2
500 
501 /*
502  * Returns true if any of the pages in the mapping are marked with the tag.
503  */
mapping_tagged(const struct address_space * mapping,xa_mark_t tag)504 static inline bool mapping_tagged(const struct address_space *mapping, xa_mark_t tag)
505 {
506 	return xa_marked(&mapping->i_pages, tag);
507 }
508 
i_mmap_lock_write(struct address_space * mapping)509 static inline void i_mmap_lock_write(struct address_space *mapping)
510 {
511 	down_write(&mapping->i_mmap_rwsem);
512 }
513 
i_mmap_trylock_write(struct address_space * mapping)514 static inline int i_mmap_trylock_write(struct address_space *mapping)
515 {
516 	return down_write_trylock(&mapping->i_mmap_rwsem);
517 }
518 
i_mmap_unlock_write(struct address_space * mapping)519 static inline void i_mmap_unlock_write(struct address_space *mapping)
520 {
521 	up_write(&mapping->i_mmap_rwsem);
522 }
523 
i_mmap_trylock_read(struct address_space * mapping)524 static inline int i_mmap_trylock_read(struct address_space *mapping)
525 {
526 	return down_read_trylock(&mapping->i_mmap_rwsem);
527 }
528 
i_mmap_lock_read(struct address_space * mapping)529 static inline void i_mmap_lock_read(struct address_space *mapping)
530 {
531 	down_read(&mapping->i_mmap_rwsem);
532 }
533 
i_mmap_unlock_read(struct address_space * mapping)534 static inline void i_mmap_unlock_read(struct address_space *mapping)
535 {
536 	up_read(&mapping->i_mmap_rwsem);
537 }
538 
i_mmap_assert_locked(struct address_space * mapping)539 static inline void i_mmap_assert_locked(struct address_space *mapping)
540 {
541 	lockdep_assert_held(&mapping->i_mmap_rwsem);
542 }
543 
i_mmap_assert_write_locked(struct address_space * mapping)544 static inline void i_mmap_assert_write_locked(struct address_space *mapping)
545 {
546 	lockdep_assert_held_write(&mapping->i_mmap_rwsem);
547 }
548 
549 /*
550  * Might pages of this file be mapped into userspace?
551  */
mapping_mapped(const struct address_space * mapping)552 static inline int mapping_mapped(const struct address_space *mapping)
553 {
554 	return	!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root);
555 }
556 
557 /*
558  * Might pages of this file have been modified in userspace?
559  * Note that i_mmap_writable counts all VM_SHARED, VM_MAYWRITE vmas: do_mmap
560  * marks vma as VM_SHARED if it is shared, and the file was opened for
561  * writing i.e. vma may be mprotected writable even if now readonly.
562  *
563  * If i_mmap_writable is negative, no new writable mappings are allowed. You
564  * can only deny writable mappings, if none exists right now.
565  */
mapping_writably_mapped(const struct address_space * mapping)566 static inline int mapping_writably_mapped(const struct address_space *mapping)
567 {
568 	return atomic_read(&mapping->i_mmap_writable) > 0;
569 }
570 
mapping_map_writable(struct address_space * mapping)571 static inline int mapping_map_writable(struct address_space *mapping)
572 {
573 	return atomic_inc_unless_negative(&mapping->i_mmap_writable) ?
574 		0 : -EPERM;
575 }
576 
mapping_unmap_writable(struct address_space * mapping)577 static inline void mapping_unmap_writable(struct address_space *mapping)
578 {
579 	atomic_dec(&mapping->i_mmap_writable);
580 }
581 
mapping_deny_writable(struct address_space * mapping)582 static inline int mapping_deny_writable(struct address_space *mapping)
583 {
584 	return atomic_dec_unless_positive(&mapping->i_mmap_writable) ?
585 		0 : -EBUSY;
586 }
587 
mapping_allow_writable(struct address_space * mapping)588 static inline void mapping_allow_writable(struct address_space *mapping)
589 {
590 	atomic_inc(&mapping->i_mmap_writable);
591 }
592 
593 /*
594  * Use sequence counter to get consistent i_size on 32-bit processors.
595  */
596 #if BITS_PER_LONG==32 && defined(CONFIG_SMP)
597 #include <linux/seqlock.h>
598 #define __NEED_I_SIZE_ORDERED
599 #define i_size_ordered_init(inode) seqcount_init(&inode->i_size_seqcount)
600 #else
601 #define i_size_ordered_init(inode) do { } while (0)
602 #endif
603 
604 struct posix_acl;
605 #define ACL_NOT_CACHED ((void *)(-1))
606 /*
607  * ACL_DONT_CACHE is for stacked filesystems, that rely on underlying fs to
608  * cache the ACL.  This also means that ->get_inode_acl() can be called in RCU
609  * mode with the LOOKUP_RCU flag.
610  */
611 #define ACL_DONT_CACHE ((void *)(-3))
612 
613 static inline struct posix_acl *
uncached_acl_sentinel(struct task_struct * task)614 uncached_acl_sentinel(struct task_struct *task)
615 {
616 	return (void *)task + 1;
617 }
618 
619 static inline bool
is_uncached_acl(struct posix_acl * acl)620 is_uncached_acl(struct posix_acl *acl)
621 {
622 	return (long)acl & 1;
623 }
624 
625 #define IOP_FASTPERM		0x0001
626 #define IOP_LOOKUP		0x0002
627 #define IOP_NOFOLLOW		0x0004
628 #define IOP_XATTR		0x0008
629 #define IOP_DEFAULT_READLINK	0x0010
630 #define IOP_MGTIME		0x0020
631 #define IOP_CACHED_LINK		0x0040
632 #define IOP_FASTPERM_MAY_EXEC	0x0080
633 
634 /*
635  * Inode state bits.  Protected by inode->i_lock
636  *
637  * Four bits determine the dirty state of the inode: I_DIRTY_SYNC,
638  * I_DIRTY_DATASYNC, I_DIRTY_PAGES, and I_DIRTY_TIME.
639  *
640  * Four bits define the lifetime of an inode.  Initially, inodes are I_NEW,
641  * until that flag is cleared.  I_WILL_FREE, I_FREEING and I_CLEAR are set at
642  * various stages of removing an inode.
643  *
644  * Two bits are used for locking and completion notification, I_NEW and I_SYNC.
645  *
646  * I_DIRTY_SYNC		Inode is dirty, but doesn't have to be written on
647  *			fdatasync() (unless I_DIRTY_DATASYNC is also set).
648  *			Timestamp updates are the usual cause.
649  * I_DIRTY_DATASYNC	Data-related inode changes pending.  We keep track of
650  *			these changes separately from I_DIRTY_SYNC so that we
651  *			don't have to write inode on fdatasync() when only
652  *			e.g. the timestamps have changed.
653  * I_DIRTY_PAGES	Inode has dirty pages.  Inode itself may be clean.
654  * I_DIRTY_TIME		The inode itself has dirty timestamps, and the
655  *			lazytime mount option is enabled.  We keep track of this
656  *			separately from I_DIRTY_SYNC in order to implement
657  *			lazytime.  This gets cleared if I_DIRTY_INODE
658  *			(I_DIRTY_SYNC and/or I_DIRTY_DATASYNC) gets set. But
659  *			I_DIRTY_TIME can still be set if I_DIRTY_SYNC is already
660  *			in place because writeback might already be in progress
661  *			and we don't want to lose the time update
662  * I_NEW		Serves as both a mutex and completion notification.
663  *			New inodes set I_NEW.  If two processes both create
664  *			the same inode, one of them will release its inode and
665  *			wait for I_NEW to be released before returning.
666  *			Inodes in I_WILL_FREE, I_FREEING or I_CLEAR state can
667  *			also cause waiting on I_NEW, without I_NEW actually
668  *			being set.  find_inode() uses this to prevent returning
669  *			nearly-dead inodes.
670  * I_WILL_FREE		Must be set when calling write_inode_now() if i_count
671  *			is zero.  I_FREEING must be set when I_WILL_FREE is
672  *			cleared.
673  * I_FREEING		Set when inode is about to be freed but still has dirty
674  *			pages or buffers attached or the inode itself is still
675  *			dirty.
676  * I_CLEAR		Added by clear_inode().  In this state the inode is
677  *			clean and can be destroyed.  Inode keeps I_FREEING.
678  *
679  *			Inodes that are I_WILL_FREE, I_FREEING or I_CLEAR are
680  *			prohibited for many purposes.  iget() must wait for
681  *			the inode to be completely released, then create it
682  *			anew.  Other functions will just ignore such inodes,
683  *			if appropriate.  I_NEW is used for waiting.
684  *
685  * I_SYNC		Writeback of inode is running. The bit is set during
686  *			data writeback, and cleared with a wakeup on the bit
687  *			address once it is done. The bit is also used to pin
688  *			the inode in memory for flusher thread.
689  *
690  * I_REFERENCED		Marks the inode as recently references on the LRU list.
691  *
692  * I_WB_SWITCH		Cgroup bdi_writeback switching in progress.  Used to
693  *			synchronize competing switching instances and to tell
694  *			wb stat updates to grab the i_pages lock.  See
695  *			inode_switch_wbs_work_fn() for details.
696  *
697  * I_OVL_INUSE		Used by overlayfs to get exclusive ownership on upper
698  *			and work dirs among overlayfs mounts.
699  *
700  * I_CREATING		New object's inode in the middle of setting up.
701  *
702  * I_DONTCACHE		Evict inode as soon as it is not used anymore.
703  *
704  * I_SYNC_QUEUED	Inode is queued in b_io or b_more_io writeback lists.
705  *			Used to detect that mark_inode_dirty() should not move
706  *			inode between dirty lists.
707  *
708  * I_PINNING_FSCACHE_WB	Inode is pinning an fscache object for writeback.
709  *
710  * I_LRU_ISOLATING	Inode is pinned being isolated from LRU without holding
711  *			i_count.
712  *
713  * Q: What is the difference between I_WILL_FREE and I_FREEING?
714  *
715  * __I_{SYNC,NEW,LRU_ISOLATING} are used to derive unique addresses to wait
716  * upon. There's one free address left.
717  */
718 
719 enum inode_state_bits {
720 	__I_NEW			= 0U,
721 	__I_SYNC		= 1U,
722 	__I_LRU_ISOLATING	= 2U
723 	/* reserved wait address bit 3 */
724 };
725 
726 enum inode_state_flags_enum {
727 	I_NEW			= (1U << __I_NEW),
728 	I_SYNC			= (1U << __I_SYNC),
729 	I_LRU_ISOLATING         = (1U << __I_LRU_ISOLATING),
730 	/* reserved flag bit 3 */
731 	I_DIRTY_SYNC		= (1U << 4),
732 	I_DIRTY_DATASYNC	= (1U << 5),
733 	I_DIRTY_PAGES		= (1U << 6),
734 	I_WILL_FREE		= (1U << 7),
735 	I_FREEING		= (1U << 8),
736 	I_CLEAR			= (1U << 9),
737 	I_REFERENCED		= (1U << 10),
738 	I_LINKABLE		= (1U << 11),
739 	I_DIRTY_TIME		= (1U << 12),
740 	I_WB_SWITCH		= (1U << 13),
741 	I_OVL_INUSE		= (1U << 14),
742 	I_CREATING		= (1U << 15),
743 	I_DONTCACHE		= (1U << 16),
744 	I_SYNC_QUEUED		= (1U << 17),
745 	I_PINNING_NETFS_WB	= (1U << 18)
746 };
747 
748 #define I_DIRTY_INODE (I_DIRTY_SYNC | I_DIRTY_DATASYNC)
749 #define I_DIRTY (I_DIRTY_INODE | I_DIRTY_PAGES)
750 #define I_DIRTY_ALL (I_DIRTY | I_DIRTY_TIME)
751 
752 /*
753  * Use inode_state_read() & friends to access.
754  */
755 struct inode_state_flags {
756 	enum inode_state_flags_enum __state;
757 };
758 
759 /*
760  * Keep mostly read-only and often accessed (especially for
761  * the RCU path lookup and 'stat' data) fields at the beginning
762  * of the 'struct inode'
763  */
764 struct inode {
765 	umode_t			i_mode;
766 	unsigned short		i_opflags;
767 	unsigned int		i_flags;
768 #ifdef CONFIG_FS_POSIX_ACL
769 	struct posix_acl	*i_acl;
770 	struct posix_acl	*i_default_acl;
771 #endif
772 	kuid_t			i_uid;
773 	kgid_t			i_gid;
774 
775 	const struct inode_operations	*i_op;
776 	struct super_block	*i_sb;
777 	struct address_space	*i_mapping;
778 
779 #ifdef CONFIG_SECURITY
780 	void			*i_security;
781 #endif
782 
783 	/* Stat data, not accessed from path walking */
784 	unsigned long		i_ino;
785 	/*
786 	 * Filesystems may only read i_nlink directly.  They shall use the
787 	 * following functions for modification:
788 	 *
789 	 *    (set|clear|inc|drop)_nlink
790 	 *    inode_(inc|dec)_link_count
791 	 */
792 	union {
793 		const unsigned int i_nlink;
794 		unsigned int __i_nlink;
795 	};
796 	dev_t			i_rdev;
797 	loff_t			i_size;
798 	time64_t		i_atime_sec;
799 	time64_t		i_mtime_sec;
800 	time64_t		i_ctime_sec;
801 	u32			i_atime_nsec;
802 	u32			i_mtime_nsec;
803 	u32			i_ctime_nsec;
804 	u32			i_generation;
805 	spinlock_t		i_lock;	/* i_blocks, i_bytes, maybe i_size */
806 	unsigned short          i_bytes;
807 	u8			i_blkbits;
808 	enum rw_hint		i_write_hint;
809 	blkcnt_t		i_blocks;
810 
811 #ifdef __NEED_I_SIZE_ORDERED
812 	seqcount_t		i_size_seqcount;
813 #endif
814 
815 	/* Misc */
816 	struct inode_state_flags i_state;
817 	/* 32-bit hole */
818 	struct rw_semaphore	i_rwsem;
819 
820 	unsigned long		dirtied_when;	/* jiffies of first dirtying */
821 	unsigned long		dirtied_time_when;
822 
823 	struct hlist_node	i_hash;
824 	struct list_head	i_io_list;	/* backing dev IO list */
825 #ifdef CONFIG_CGROUP_WRITEBACK
826 	struct bdi_writeback	*i_wb;		/* the associated cgroup wb */
827 
828 	/* foreign inode detection, see wbc_detach_inode() */
829 	int			i_wb_frn_winner;
830 	u16			i_wb_frn_avg_time;
831 	u16			i_wb_frn_history;
832 #endif
833 	struct list_head	i_lru;		/* inode LRU list */
834 	struct list_head	i_sb_list;
835 	struct list_head	i_wb_list;	/* backing dev writeback list */
836 	union {
837 		struct hlist_head	i_dentry;
838 		struct rcu_head		i_rcu;
839 	};
840 	atomic64_t		i_version;
841 	atomic64_t		i_sequence; /* see futex */
842 	atomic_t		i_count;
843 	atomic_t		i_dio_count;
844 	atomic_t		i_writecount;
845 #if defined(CONFIG_IMA) || defined(CONFIG_FILE_LOCKING)
846 	atomic_t		i_readcount; /* struct files open RO */
847 #endif
848 	union {
849 		const struct file_operations	*i_fop;	/* former ->i_op->default_file_ops */
850 		void (*free_inode)(struct inode *);
851 	};
852 	struct file_lock_context	*i_flctx;
853 	struct address_space	i_data;
854 	union {
855 		struct list_head	i_devices;
856 		int			i_linklen;
857 	};
858 	union {
859 		struct pipe_inode_info	*i_pipe;
860 		struct cdev		*i_cdev;
861 		char			*i_link;
862 		unsigned		i_dir_seq;
863 	};
864 
865 
866 #ifdef CONFIG_FSNOTIFY
867 	__u32			i_fsnotify_mask; /* all events this inode cares about */
868 	/* 32-bit hole reserved for expanding i_fsnotify_mask */
869 	struct fsnotify_mark_connector __rcu	*i_fsnotify_marks;
870 #endif
871 
872 	void			*i_private; /* fs or device private pointer */
873 } __randomize_layout;
874 
875 /*
876  * i_state handling
877  *
878  * We hide all of it behind helpers so that we can validate consumers.
879  */
inode_state_read_once(struct inode * inode)880 static inline enum inode_state_flags_enum inode_state_read_once(struct inode *inode)
881 {
882 	return READ_ONCE(inode->i_state.__state);
883 }
884 
inode_state_read(struct inode * inode)885 static inline enum inode_state_flags_enum inode_state_read(struct inode *inode)
886 {
887 	lockdep_assert_held(&inode->i_lock);
888 	return inode->i_state.__state;
889 }
890 
inode_state_set_raw(struct inode * inode,enum inode_state_flags_enum flags)891 static inline void inode_state_set_raw(struct inode *inode,
892 				       enum inode_state_flags_enum flags)
893 {
894 	WRITE_ONCE(inode->i_state.__state, inode->i_state.__state | flags);
895 }
896 
inode_state_set(struct inode * inode,enum inode_state_flags_enum flags)897 static inline void inode_state_set(struct inode *inode,
898 				   enum inode_state_flags_enum flags)
899 {
900 	lockdep_assert_held(&inode->i_lock);
901 	inode_state_set_raw(inode, flags);
902 }
903 
inode_state_clear_raw(struct inode * inode,enum inode_state_flags_enum flags)904 static inline void inode_state_clear_raw(struct inode *inode,
905 					 enum inode_state_flags_enum flags)
906 {
907 	WRITE_ONCE(inode->i_state.__state, inode->i_state.__state & ~flags);
908 }
909 
inode_state_clear(struct inode * inode,enum inode_state_flags_enum flags)910 static inline void inode_state_clear(struct inode *inode,
911 				     enum inode_state_flags_enum flags)
912 {
913 	lockdep_assert_held(&inode->i_lock);
914 	inode_state_clear_raw(inode, flags);
915 }
916 
inode_state_assign_raw(struct inode * inode,enum inode_state_flags_enum flags)917 static inline void inode_state_assign_raw(struct inode *inode,
918 					  enum inode_state_flags_enum flags)
919 {
920 	WRITE_ONCE(inode->i_state.__state, flags);
921 }
922 
inode_state_assign(struct inode * inode,enum inode_state_flags_enum flags)923 static inline void inode_state_assign(struct inode *inode,
924 				      enum inode_state_flags_enum flags)
925 {
926 	lockdep_assert_held(&inode->i_lock);
927 	inode_state_assign_raw(inode, flags);
928 }
929 
inode_state_replace_raw(struct inode * inode,enum inode_state_flags_enum clearflags,enum inode_state_flags_enum setflags)930 static inline void inode_state_replace_raw(struct inode *inode,
931 					   enum inode_state_flags_enum clearflags,
932 					   enum inode_state_flags_enum setflags)
933 {
934 	enum inode_state_flags_enum flags;
935 	flags = inode->i_state.__state;
936 	flags &= ~clearflags;
937 	flags |= setflags;
938 	inode_state_assign_raw(inode, flags);
939 }
940 
inode_state_replace(struct inode * inode,enum inode_state_flags_enum clearflags,enum inode_state_flags_enum setflags)941 static inline void inode_state_replace(struct inode *inode,
942 				       enum inode_state_flags_enum clearflags,
943 				       enum inode_state_flags_enum setflags)
944 {
945 	lockdep_assert_held(&inode->i_lock);
946 	inode_state_replace_raw(inode, clearflags, setflags);
947 }
948 
inode_set_cached_link(struct inode * inode,char * link,int linklen)949 static inline void inode_set_cached_link(struct inode *inode, char *link, int linklen)
950 {
951 	VFS_WARN_ON_INODE(strlen(link) != linklen, inode);
952 	VFS_WARN_ON_INODE(inode->i_opflags & IOP_CACHED_LINK, inode);
953 	inode->i_link = link;
954 	inode->i_linklen = linklen;
955 	inode->i_opflags |= IOP_CACHED_LINK;
956 }
957 
958 /*
959  * Get bit address from inode->i_state to use with wait_var_event()
960  * infrastructre.
961  */
962 #define inode_state_wait_address(inode, bit) ((char *)&(inode)->i_state + (bit))
963 
964 struct wait_queue_head *inode_bit_waitqueue(struct wait_bit_queue_entry *wqe,
965 					    struct inode *inode, u32 bit);
966 
inode_wake_up_bit(struct inode * inode,u32 bit)967 static inline void inode_wake_up_bit(struct inode *inode, u32 bit)
968 {
969 	/* Caller is responsible for correct memory barriers. */
970 	wake_up_var(inode_state_wait_address(inode, bit));
971 }
972 
973 struct timespec64 timestamp_truncate(struct timespec64 t, struct inode *inode);
974 
i_blocksize(const struct inode * node)975 static inline unsigned int i_blocksize(const struct inode *node)
976 {
977 	return (1 << node->i_blkbits);
978 }
979 
inode_unhashed(struct inode * inode)980 static inline int inode_unhashed(struct inode *inode)
981 {
982 	return hlist_unhashed(&inode->i_hash);
983 }
984 
985 /*
986  * __mark_inode_dirty expects inodes to be hashed.  Since we don't
987  * want special inodes in the fileset inode space, we make them
988  * appear hashed, but do not put on any lists.  hlist_del()
989  * will work fine and require no locking.
990  */
inode_fake_hash(struct inode * inode)991 static inline void inode_fake_hash(struct inode *inode)
992 {
993 	hlist_add_fake(&inode->i_hash);
994 }
995 
996 void wait_on_new_inode(struct inode *inode);
997 
998 /*
999  * inode->i_rwsem nesting subclasses for the lock validator:
1000  *
1001  * 0: the object of the current VFS operation
1002  * 1: parent
1003  * 2: child/target
1004  * 3: xattr
1005  * 4: second non-directory
1006  * 5: second parent (when locking independent directories in rename)
1007  *
1008  * I_MUTEX_NONDIR2 is for certain operations (such as rename) which lock two
1009  * non-directories at once.
1010  *
1011  * The locking order between these classes is
1012  * parent[2] -> child -> grandchild -> normal -> xattr -> second non-directory
1013  */
1014 enum inode_i_mutex_lock_class
1015 {
1016 	I_MUTEX_NORMAL,
1017 	I_MUTEX_PARENT,
1018 	I_MUTEX_CHILD,
1019 	I_MUTEX_XATTR,
1020 	I_MUTEX_NONDIR2,
1021 	I_MUTEX_PARENT2,
1022 };
1023 
inode_lock(struct inode * inode)1024 static inline void inode_lock(struct inode *inode)
1025 {
1026 	down_write(&inode->i_rwsem);
1027 }
1028 
inode_lock_killable(struct inode * inode)1029 static inline __must_check int inode_lock_killable(struct inode *inode)
1030 {
1031 	return down_write_killable(&inode->i_rwsem);
1032 }
1033 
inode_unlock(struct inode * inode)1034 static inline void inode_unlock(struct inode *inode)
1035 {
1036 	up_write(&inode->i_rwsem);
1037 }
1038 
inode_lock_shared(struct inode * inode)1039 static inline void inode_lock_shared(struct inode *inode)
1040 {
1041 	down_read(&inode->i_rwsem);
1042 }
1043 
inode_lock_shared_killable(struct inode * inode)1044 static inline __must_check int inode_lock_shared_killable(struct inode *inode)
1045 {
1046 	return down_read_killable(&inode->i_rwsem);
1047 }
1048 
inode_unlock_shared(struct inode * inode)1049 static inline void inode_unlock_shared(struct inode *inode)
1050 {
1051 	up_read(&inode->i_rwsem);
1052 }
1053 
inode_trylock(struct inode * inode)1054 static inline int inode_trylock(struct inode *inode)
1055 {
1056 	return down_write_trylock(&inode->i_rwsem);
1057 }
1058 
inode_trylock_shared(struct inode * inode)1059 static inline int inode_trylock_shared(struct inode *inode)
1060 {
1061 	return down_read_trylock(&inode->i_rwsem);
1062 }
1063 
inode_is_locked(struct inode * inode)1064 static inline int inode_is_locked(struct inode *inode)
1065 {
1066 	return rwsem_is_locked(&inode->i_rwsem);
1067 }
1068 
inode_lock_nested(struct inode * inode,unsigned subclass)1069 static inline void inode_lock_nested(struct inode *inode, unsigned subclass)
1070 {
1071 	down_write_nested(&inode->i_rwsem, subclass);
1072 }
1073 
inode_lock_shared_nested(struct inode * inode,unsigned subclass)1074 static inline void inode_lock_shared_nested(struct inode *inode, unsigned subclass)
1075 {
1076 	down_read_nested(&inode->i_rwsem, subclass);
1077 }
1078 
filemap_invalidate_lock(struct address_space * mapping)1079 static inline void filemap_invalidate_lock(struct address_space *mapping)
1080 {
1081 	down_write(&mapping->invalidate_lock);
1082 }
1083 
filemap_invalidate_unlock(struct address_space * mapping)1084 static inline void filemap_invalidate_unlock(struct address_space *mapping)
1085 {
1086 	up_write(&mapping->invalidate_lock);
1087 }
1088 
filemap_invalidate_lock_shared(struct address_space * mapping)1089 static inline void filemap_invalidate_lock_shared(struct address_space *mapping)
1090 {
1091 	down_read(&mapping->invalidate_lock);
1092 }
1093 
filemap_invalidate_trylock_shared(struct address_space * mapping)1094 static inline int filemap_invalidate_trylock_shared(
1095 					struct address_space *mapping)
1096 {
1097 	return down_read_trylock(&mapping->invalidate_lock);
1098 }
1099 
filemap_invalidate_unlock_shared(struct address_space * mapping)1100 static inline void filemap_invalidate_unlock_shared(
1101 					struct address_space *mapping)
1102 {
1103 	up_read(&mapping->invalidate_lock);
1104 }
1105 
1106 void lock_two_nondirectories(struct inode *, struct inode*);
1107 void unlock_two_nondirectories(struct inode *, struct inode*);
1108 
1109 void filemap_invalidate_lock_two(struct address_space *mapping1,
1110 				 struct address_space *mapping2);
1111 void filemap_invalidate_unlock_two(struct address_space *mapping1,
1112 				   struct address_space *mapping2);
1113 
1114 
1115 /*
1116  * NOTE: in a 32bit arch with a preemptable kernel and
1117  * an UP compile the i_size_read/write must be atomic
1118  * with respect to the local cpu (unlike with preempt disabled),
1119  * but they don't need to be atomic with respect to other cpus like in
1120  * true SMP (so they need either to either locally disable irq around
1121  * the read or for example on x86 they can be still implemented as a
1122  * cmpxchg8b without the need of the lock prefix). For SMP compiles
1123  * and 64bit archs it makes no difference if preempt is enabled or not.
1124  */
i_size_read(const struct inode * inode)1125 static inline loff_t i_size_read(const struct inode *inode)
1126 {
1127 #if BITS_PER_LONG==32 && defined(CONFIG_SMP)
1128 	loff_t i_size;
1129 	unsigned int seq;
1130 
1131 	do {
1132 		seq = read_seqcount_begin(&inode->i_size_seqcount);
1133 		i_size = inode->i_size;
1134 	} while (read_seqcount_retry(&inode->i_size_seqcount, seq));
1135 	return i_size;
1136 #elif BITS_PER_LONG==32 && defined(CONFIG_PREEMPTION)
1137 	loff_t i_size;
1138 
1139 	preempt_disable();
1140 	i_size = inode->i_size;
1141 	preempt_enable();
1142 	return i_size;
1143 #else
1144 	/* Pairs with smp_store_release() in i_size_write() */
1145 	return smp_load_acquire(&inode->i_size);
1146 #endif
1147 }
1148 
1149 /*
1150  * NOTE: unlike i_size_read(), i_size_write() does need locking around it
1151  * (normally i_rwsem), otherwise on 32bit/SMP an update of i_size_seqcount
1152  * can be lost, resulting in subsequent i_size_read() calls spinning forever.
1153  */
i_size_write(struct inode * inode,loff_t i_size)1154 static inline void i_size_write(struct inode *inode, loff_t i_size)
1155 {
1156 #if BITS_PER_LONG==32 && defined(CONFIG_SMP)
1157 	preempt_disable();
1158 	write_seqcount_begin(&inode->i_size_seqcount);
1159 	inode->i_size = i_size;
1160 	write_seqcount_end(&inode->i_size_seqcount);
1161 	preempt_enable();
1162 #elif BITS_PER_LONG==32 && defined(CONFIG_PREEMPTION)
1163 	preempt_disable();
1164 	inode->i_size = i_size;
1165 	preempt_enable();
1166 #else
1167 	/*
1168 	 * Pairs with smp_load_acquire() in i_size_read() to ensure
1169 	 * changes related to inode size (such as page contents) are
1170 	 * visible before we see the changed inode size.
1171 	 */
1172 	smp_store_release(&inode->i_size, i_size);
1173 #endif
1174 }
1175 
iminor(const struct inode * inode)1176 static inline unsigned iminor(const struct inode *inode)
1177 {
1178 	return MINOR(inode->i_rdev);
1179 }
1180 
imajor(const struct inode * inode)1181 static inline unsigned imajor(const struct inode *inode)
1182 {
1183 	return MAJOR(inode->i_rdev);
1184 }
1185 
1186 struct fown_struct {
1187 	struct file *file;	/* backpointer for security modules */
1188 	rwlock_t lock;          /* protects pid, uid, euid fields */
1189 	struct pid *pid;	/* pid or -pgrp where SIGIO should be sent */
1190 	enum pid_type pid_type;	/* Kind of process group SIGIO should be sent to */
1191 	kuid_t uid, euid;	/* uid/euid of process setting the owner */
1192 	int signum;		/* posix.1b rt signal to be delivered on IO */
1193 };
1194 
1195 /**
1196  * struct file_ra_state - Track a file's readahead state.
1197  * @start: Where the most recent readahead started.
1198  * @size: Number of pages read in the most recent readahead.
1199  * @async_size: Numer of pages that were/are not needed immediately
1200  *      and so were/are genuinely "ahead".  Start next readahead when
1201  *      the first of these pages is accessed.
1202  * @ra_pages: Maximum size of a readahead request, copied from the bdi.
1203  * @order: Preferred folio order used for most recent readahead.
1204  * @mmap_miss: How many mmap accesses missed in the page cache.
1205  * @prev_pos: The last byte in the most recent read request.
1206  *
1207  * When this structure is passed to ->readahead(), the "most recent"
1208  * readahead means the current readahead.
1209  */
1210 struct file_ra_state {
1211 	pgoff_t start;
1212 	unsigned int size;
1213 	unsigned int async_size;
1214 	unsigned int ra_pages;
1215 	unsigned short order;
1216 	unsigned short mmap_miss;
1217 	loff_t prev_pos;
1218 };
1219 
1220 /*
1221  * Check if @index falls in the readahead windows.
1222  */
ra_has_index(struct file_ra_state * ra,pgoff_t index)1223 static inline int ra_has_index(struct file_ra_state *ra, pgoff_t index)
1224 {
1225 	return (index >= ra->start &&
1226 		index <  ra->start + ra->size);
1227 }
1228 
1229 /**
1230  * struct file - Represents a file
1231  * @f_lock: Protects f_ep, f_flags. Must not be taken from IRQ context.
1232  * @f_mode: FMODE_* flags often used in hotpaths
1233  * @f_op: file operations
1234  * @f_mapping: Contents of a cacheable, mappable object.
1235  * @private_data: filesystem or driver specific data
1236  * @f_inode: cached inode
1237  * @f_flags: file flags
1238  * @f_iocb_flags: iocb flags
1239  * @f_cred: stashed credentials of creator/opener
1240  * @f_owner: file owner
1241  * @f_path: path of the file
1242  * @__f_path: writable alias for @f_path; *ONLY* for core VFS and only before
1243  *   the file gets open
1244  * @f_pos_lock: lock protecting file position
1245  * @f_pipe: specific to pipes
1246  * @f_pos: file position
1247  * @f_security: LSM security context of this file
1248  * @f_wb_err: writeback error
1249  * @f_sb_err: per sb writeback errors
1250  * @f_ep: link of all epoll hooks for this file
1251  * @f_task_work: task work entry point
1252  * @f_llist: work queue entrypoint
1253  * @f_ra: file's readahead state
1254  * @f_freeptr: Pointer used by SLAB_TYPESAFE_BY_RCU file cache (don't touch.)
1255  * @f_ref: reference count
1256  */
1257 struct file {
1258 	spinlock_t			f_lock;
1259 	fmode_t				f_mode;
1260 	const struct file_operations	*f_op;
1261 	struct address_space		*f_mapping;
1262 	void				*private_data;
1263 	struct inode			*f_inode;
1264 	unsigned int			f_flags;
1265 	unsigned int			f_iocb_flags;
1266 	const struct cred		*f_cred;
1267 	struct fown_struct		*f_owner;
1268 	/* --- cacheline 1 boundary (64 bytes) --- */
1269 	union {
1270 		const struct path	f_path;
1271 		struct path		__f_path;
1272 	};
1273 	union {
1274 		/* regular files (with FMODE_ATOMIC_POS) and directories */
1275 		struct mutex		f_pos_lock;
1276 		/* pipes */
1277 		u64			f_pipe;
1278 	};
1279 	loff_t				f_pos;
1280 #ifdef CONFIG_SECURITY
1281 	void				*f_security;
1282 #endif
1283 	/* --- cacheline 2 boundary (128 bytes) --- */
1284 	errseq_t			f_wb_err;
1285 	errseq_t			f_sb_err;
1286 #ifdef CONFIG_EPOLL
1287 	struct hlist_head		*f_ep;
1288 #endif
1289 	union {
1290 		struct callback_head	f_task_work;
1291 		struct llist_node	f_llist;
1292 		struct file_ra_state	f_ra;
1293 		freeptr_t		f_freeptr;
1294 	};
1295 	file_ref_t			f_ref;
1296 	/* --- cacheline 3 boundary (192 bytes) --- */
1297 } __randomize_layout
1298   __attribute__((aligned(4)));	/* lest something weird decides that 2 is OK */
1299 
1300 struct file_handle {
1301 	__u32 handle_bytes;
1302 	int handle_type;
1303 	/* file identifier */
1304 	unsigned char f_handle[] __counted_by(handle_bytes);
1305 };
1306 
get_file(struct file * f)1307 static inline struct file *get_file(struct file *f)
1308 {
1309 	file_ref_inc(&f->f_ref);
1310 	return f;
1311 }
1312 
1313 struct file *get_file_rcu(struct file __rcu **f);
1314 struct file *get_file_active(struct file **f);
1315 
1316 #define file_count(f)	file_ref_read(&(f)->f_ref)
1317 
1318 #define	MAX_NON_LFS	((1UL<<31) - 1)
1319 
1320 /* Page cache limit. The filesystems should put that into their s_maxbytes
1321    limits, otherwise bad things can happen in VM. */
1322 #if BITS_PER_LONG==32
1323 #define MAX_LFS_FILESIZE	((loff_t)ULONG_MAX << PAGE_SHIFT)
1324 #elif BITS_PER_LONG==64
1325 #define MAX_LFS_FILESIZE 	((loff_t)LLONG_MAX)
1326 #endif
1327 
1328 /* legacy typedef, should eventually be removed */
1329 typedef void *fl_owner_t;
1330 
1331 struct file_lock;
1332 struct file_lease;
1333 
1334 /* The following constant reflects the upper bound of the file/locking space */
1335 #ifndef OFFSET_MAX
1336 #define OFFSET_MAX	type_max(loff_t)
1337 #define OFFT_OFFSET_MAX	type_max(off_t)
1338 #endif
1339 
1340 int file_f_owner_allocate(struct file *file);
file_f_owner(const struct file * file)1341 static inline struct fown_struct *file_f_owner(const struct file *file)
1342 {
1343 	return READ_ONCE(file->f_owner);
1344 }
1345 
1346 extern void send_sigio(struct fown_struct *fown, int fd, int band);
1347 
file_inode(const struct file * f)1348 static inline struct inode *file_inode(const struct file *f)
1349 {
1350 	return f->f_inode;
1351 }
1352 
1353 /*
1354  * file_dentry() is a relic from the days that overlayfs was using files with a
1355  * "fake" path, meaning, f_path on overlayfs and f_inode on underlying fs.
1356  * In those days, file_dentry() was needed to get the underlying fs dentry that
1357  * matches f_inode.
1358  * Files with "fake" path should not exist nowadays, so use an assertion to make
1359  * sure that file_dentry() was not papering over filesystem bugs.
1360  */
file_dentry(const struct file * file)1361 static inline struct dentry *file_dentry(const struct file *file)
1362 {
1363 	struct dentry *dentry = file->f_path.dentry;
1364 
1365 	WARN_ON_ONCE(d_inode(dentry) != file_inode(file));
1366 	return dentry;
1367 }
1368 
1369 struct fasync_struct {
1370 	rwlock_t		fa_lock;
1371 	int			magic;
1372 	int			fa_fd;
1373 	struct fasync_struct	*fa_next; /* singly linked list */
1374 	struct file		*fa_file;
1375 	struct rcu_head		fa_rcu;
1376 };
1377 
1378 #define FASYNC_MAGIC 0x4601
1379 
1380 /* SMP safe fasync helpers: */
1381 extern int fasync_helper(int, struct file *, int, struct fasync_struct **);
1382 extern struct fasync_struct *fasync_insert_entry(int, struct file *, struct fasync_struct **, struct fasync_struct *);
1383 extern int fasync_remove_entry(struct file *, struct fasync_struct **);
1384 extern struct fasync_struct *fasync_alloc(void);
1385 extern void fasync_free(struct fasync_struct *);
1386 
1387 /* can be called from interrupts */
1388 extern void kill_fasync(struct fasync_struct **, int, int);
1389 
1390 extern void __f_setown(struct file *filp, struct pid *, enum pid_type, int force);
1391 extern int f_setown(struct file *filp, int who, int force);
1392 extern void f_delown(struct file *filp);
1393 extern pid_t f_getown(struct file *filp);
1394 extern int send_sigurg(struct file *file);
1395 
1396 /*
1397  *	Umount options
1398  */
1399 
1400 #define MNT_FORCE	0x00000001	/* Attempt to forcibily umount */
1401 #define MNT_DETACH	0x00000002	/* Just detach from the tree */
1402 #define MNT_EXPIRE	0x00000004	/* Mark for expiry */
1403 #define UMOUNT_NOFOLLOW	0x00000008	/* Don't follow symlink on umount */
1404 #define UMOUNT_UNUSED	0x80000000	/* Flag guaranteed to be unused */
1405 
i_user_ns(const struct inode * inode)1406 static inline struct user_namespace *i_user_ns(const struct inode *inode)
1407 {
1408 	return inode->i_sb->s_user_ns;
1409 }
1410 
1411 /* Helper functions so that in most cases filesystems will
1412  * not need to deal directly with kuid_t and kgid_t and can
1413  * instead deal with the raw numeric values that are stored
1414  * in the filesystem.
1415  */
i_uid_read(const struct inode * inode)1416 static inline uid_t i_uid_read(const struct inode *inode)
1417 {
1418 	return from_kuid(i_user_ns(inode), inode->i_uid);
1419 }
1420 
i_gid_read(const struct inode * inode)1421 static inline gid_t i_gid_read(const struct inode *inode)
1422 {
1423 	return from_kgid(i_user_ns(inode), inode->i_gid);
1424 }
1425 
i_uid_write(struct inode * inode,uid_t uid)1426 static inline void i_uid_write(struct inode *inode, uid_t uid)
1427 {
1428 	inode->i_uid = make_kuid(i_user_ns(inode), uid);
1429 }
1430 
i_gid_write(struct inode * inode,gid_t gid)1431 static inline void i_gid_write(struct inode *inode, gid_t gid)
1432 {
1433 	inode->i_gid = make_kgid(i_user_ns(inode), gid);
1434 }
1435 
1436 /**
1437  * i_uid_into_vfsuid - map an inode's i_uid down according to an idmapping
1438  * @idmap: idmap of the mount the inode was found from
1439  * @inode: inode to map
1440  *
1441  * Return: whe inode's i_uid mapped down according to @idmap.
1442  * If the inode's i_uid has no mapping INVALID_VFSUID is returned.
1443  */
i_uid_into_vfsuid(struct mnt_idmap * idmap,const struct inode * inode)1444 static inline vfsuid_t i_uid_into_vfsuid(struct mnt_idmap *idmap,
1445 					 const struct inode *inode)
1446 {
1447 	return make_vfsuid(idmap, i_user_ns(inode), inode->i_uid);
1448 }
1449 
1450 /**
1451  * i_uid_needs_update - check whether inode's i_uid needs to be updated
1452  * @idmap: idmap of the mount the inode was found from
1453  * @attr: the new attributes of @inode
1454  * @inode: the inode to update
1455  *
1456  * Check whether the $inode's i_uid field needs to be updated taking idmapped
1457  * mounts into account if the filesystem supports it.
1458  *
1459  * Return: true if @inode's i_uid field needs to be updated, false if not.
1460  */
i_uid_needs_update(struct mnt_idmap * idmap,const struct iattr * attr,const struct inode * inode)1461 static inline bool i_uid_needs_update(struct mnt_idmap *idmap,
1462 				      const struct iattr *attr,
1463 				      const struct inode *inode)
1464 {
1465 	return ((attr->ia_valid & ATTR_UID) &&
1466 		!vfsuid_eq(attr->ia_vfsuid,
1467 			   i_uid_into_vfsuid(idmap, inode)));
1468 }
1469 
1470 /**
1471  * i_uid_update - update @inode's i_uid field
1472  * @idmap: idmap of the mount the inode was found from
1473  * @attr: the new attributes of @inode
1474  * @inode: the inode to update
1475  *
1476  * Safely update @inode's i_uid field translating the vfsuid of any idmapped
1477  * mount into the filesystem kuid.
1478  */
i_uid_update(struct mnt_idmap * idmap,const struct iattr * attr,struct inode * inode)1479 static inline void i_uid_update(struct mnt_idmap *idmap,
1480 				const struct iattr *attr,
1481 				struct inode *inode)
1482 {
1483 	if (attr->ia_valid & ATTR_UID)
1484 		inode->i_uid = from_vfsuid(idmap, i_user_ns(inode),
1485 					   attr->ia_vfsuid);
1486 }
1487 
1488 /**
1489  * i_gid_into_vfsgid - map an inode's i_gid down according to an idmapping
1490  * @idmap: idmap of the mount the inode was found from
1491  * @inode: inode to map
1492  *
1493  * Return: the inode's i_gid mapped down according to @idmap.
1494  * If the inode's i_gid has no mapping INVALID_VFSGID is returned.
1495  */
i_gid_into_vfsgid(struct mnt_idmap * idmap,const struct inode * inode)1496 static inline vfsgid_t i_gid_into_vfsgid(struct mnt_idmap *idmap,
1497 					 const struct inode *inode)
1498 {
1499 	return make_vfsgid(idmap, i_user_ns(inode), inode->i_gid);
1500 }
1501 
1502 /**
1503  * i_gid_needs_update - check whether inode's i_gid needs to be updated
1504  * @idmap: idmap of the mount the inode was found from
1505  * @attr: the new attributes of @inode
1506  * @inode: the inode to update
1507  *
1508  * Check whether the $inode's i_gid field needs to be updated taking idmapped
1509  * mounts into account if the filesystem supports it.
1510  *
1511  * Return: true if @inode's i_gid field needs to be updated, false if not.
1512  */
i_gid_needs_update(struct mnt_idmap * idmap,const struct iattr * attr,const struct inode * inode)1513 static inline bool i_gid_needs_update(struct mnt_idmap *idmap,
1514 				      const struct iattr *attr,
1515 				      const struct inode *inode)
1516 {
1517 	return ((attr->ia_valid & ATTR_GID) &&
1518 		!vfsgid_eq(attr->ia_vfsgid,
1519 			   i_gid_into_vfsgid(idmap, inode)));
1520 }
1521 
1522 /**
1523  * i_gid_update - update @inode's i_gid field
1524  * @idmap: idmap of the mount the inode was found from
1525  * @attr: the new attributes of @inode
1526  * @inode: the inode to update
1527  *
1528  * Safely update @inode's i_gid field translating the vfsgid of any idmapped
1529  * mount into the filesystem kgid.
1530  */
i_gid_update(struct mnt_idmap * idmap,const struct iattr * attr,struct inode * inode)1531 static inline void i_gid_update(struct mnt_idmap *idmap,
1532 				const struct iattr *attr,
1533 				struct inode *inode)
1534 {
1535 	if (attr->ia_valid & ATTR_GID)
1536 		inode->i_gid = from_vfsgid(idmap, i_user_ns(inode),
1537 					   attr->ia_vfsgid);
1538 }
1539 
1540 /**
1541  * inode_fsuid_set - initialize inode's i_uid field with callers fsuid
1542  * @inode: inode to initialize
1543  * @idmap: idmap of the mount the inode was found from
1544  *
1545  * Initialize the i_uid field of @inode. If the inode was found/created via
1546  * an idmapped mount map the caller's fsuid according to @idmap.
1547  */
inode_fsuid_set(struct inode * inode,struct mnt_idmap * idmap)1548 static inline void inode_fsuid_set(struct inode *inode,
1549 				   struct mnt_idmap *idmap)
1550 {
1551 	inode->i_uid = mapped_fsuid(idmap, i_user_ns(inode));
1552 }
1553 
1554 /**
1555  * inode_fsgid_set - initialize inode's i_gid field with callers fsgid
1556  * @inode: inode to initialize
1557  * @idmap: idmap of the mount the inode was found from
1558  *
1559  * Initialize the i_gid field of @inode. If the inode was found/created via
1560  * an idmapped mount map the caller's fsgid according to @idmap.
1561  */
inode_fsgid_set(struct inode * inode,struct mnt_idmap * idmap)1562 static inline void inode_fsgid_set(struct inode *inode,
1563 				   struct mnt_idmap *idmap)
1564 {
1565 	inode->i_gid = mapped_fsgid(idmap, i_user_ns(inode));
1566 }
1567 
1568 /**
1569  * fsuidgid_has_mapping() - check whether caller's fsuid/fsgid is mapped
1570  * @sb: the superblock we want a mapping in
1571  * @idmap: idmap of the relevant mount
1572  *
1573  * Check whether the caller's fsuid and fsgid have a valid mapping in the
1574  * s_user_ns of the superblock @sb. If the caller is on an idmapped mount map
1575  * the caller's fsuid and fsgid according to the @idmap first.
1576  *
1577  * Return: true if fsuid and fsgid is mapped, false if not.
1578  */
fsuidgid_has_mapping(struct super_block * sb,struct mnt_idmap * idmap)1579 static inline bool fsuidgid_has_mapping(struct super_block *sb,
1580 					struct mnt_idmap *idmap)
1581 {
1582 	struct user_namespace *fs_userns = sb->s_user_ns;
1583 	kuid_t kuid;
1584 	kgid_t kgid;
1585 
1586 	kuid = mapped_fsuid(idmap, fs_userns);
1587 	if (!uid_valid(kuid))
1588 		return false;
1589 	kgid = mapped_fsgid(idmap, fs_userns);
1590 	if (!gid_valid(kgid))
1591 		return false;
1592 	return kuid_has_mapping(fs_userns, kuid) &&
1593 	       kgid_has_mapping(fs_userns, kgid);
1594 }
1595 
1596 struct timespec64 current_time(struct inode *inode);
1597 struct timespec64 inode_set_ctime_current(struct inode *inode);
1598 struct timespec64 inode_set_ctime_deleg(struct inode *inode,
1599 					struct timespec64 update);
1600 
inode_get_atime_sec(const struct inode * inode)1601 static inline time64_t inode_get_atime_sec(const struct inode *inode)
1602 {
1603 	return inode->i_atime_sec;
1604 }
1605 
inode_get_atime_nsec(const struct inode * inode)1606 static inline long inode_get_atime_nsec(const struct inode *inode)
1607 {
1608 	return inode->i_atime_nsec;
1609 }
1610 
inode_get_atime(const struct inode * inode)1611 static inline struct timespec64 inode_get_atime(const struct inode *inode)
1612 {
1613 	struct timespec64 ts = { .tv_sec  = inode_get_atime_sec(inode),
1614 				 .tv_nsec = inode_get_atime_nsec(inode) };
1615 
1616 	return ts;
1617 }
1618 
inode_set_atime_to_ts(struct inode * inode,struct timespec64 ts)1619 static inline struct timespec64 inode_set_atime_to_ts(struct inode *inode,
1620 						      struct timespec64 ts)
1621 {
1622 	inode->i_atime_sec = ts.tv_sec;
1623 	inode->i_atime_nsec = ts.tv_nsec;
1624 	return ts;
1625 }
1626 
inode_set_atime(struct inode * inode,time64_t sec,long nsec)1627 static inline struct timespec64 inode_set_atime(struct inode *inode,
1628 						time64_t sec, long nsec)
1629 {
1630 	struct timespec64 ts = { .tv_sec  = sec,
1631 				 .tv_nsec = nsec };
1632 
1633 	return inode_set_atime_to_ts(inode, ts);
1634 }
1635 
inode_get_mtime_sec(const struct inode * inode)1636 static inline time64_t inode_get_mtime_sec(const struct inode *inode)
1637 {
1638 	return inode->i_mtime_sec;
1639 }
1640 
inode_get_mtime_nsec(const struct inode * inode)1641 static inline long inode_get_mtime_nsec(const struct inode *inode)
1642 {
1643 	return inode->i_mtime_nsec;
1644 }
1645 
inode_get_mtime(const struct inode * inode)1646 static inline struct timespec64 inode_get_mtime(const struct inode *inode)
1647 {
1648 	struct timespec64 ts = { .tv_sec  = inode_get_mtime_sec(inode),
1649 				 .tv_nsec = inode_get_mtime_nsec(inode) };
1650 	return ts;
1651 }
1652 
inode_set_mtime_to_ts(struct inode * inode,struct timespec64 ts)1653 static inline struct timespec64 inode_set_mtime_to_ts(struct inode *inode,
1654 						      struct timespec64 ts)
1655 {
1656 	inode->i_mtime_sec = ts.tv_sec;
1657 	inode->i_mtime_nsec = ts.tv_nsec;
1658 	return ts;
1659 }
1660 
inode_set_mtime(struct inode * inode,time64_t sec,long nsec)1661 static inline struct timespec64 inode_set_mtime(struct inode *inode,
1662 						time64_t sec, long nsec)
1663 {
1664 	struct timespec64 ts = { .tv_sec  = sec,
1665 				 .tv_nsec = nsec };
1666 	return inode_set_mtime_to_ts(inode, ts);
1667 }
1668 
1669 /*
1670  * Multigrain timestamps
1671  *
1672  * Conditionally use fine-grained ctime and mtime timestamps when there
1673  * are users actively observing them via getattr. The primary use-case
1674  * for this is NFS clients that use the ctime to distinguish between
1675  * different states of the file, and that are often fooled by multiple
1676  * operations that occur in the same coarse-grained timer tick.
1677  */
1678 #define I_CTIME_QUERIED		((u32)BIT(31))
1679 
inode_get_ctime_sec(const struct inode * inode)1680 static inline time64_t inode_get_ctime_sec(const struct inode *inode)
1681 {
1682 	return inode->i_ctime_sec;
1683 }
1684 
inode_get_ctime_nsec(const struct inode * inode)1685 static inline long inode_get_ctime_nsec(const struct inode *inode)
1686 {
1687 	return inode->i_ctime_nsec & ~I_CTIME_QUERIED;
1688 }
1689 
inode_get_ctime(const struct inode * inode)1690 static inline struct timespec64 inode_get_ctime(const struct inode *inode)
1691 {
1692 	struct timespec64 ts = { .tv_sec  = inode_get_ctime_sec(inode),
1693 				 .tv_nsec = inode_get_ctime_nsec(inode) };
1694 
1695 	return ts;
1696 }
1697 
1698 struct timespec64 inode_set_ctime_to_ts(struct inode *inode, struct timespec64 ts);
1699 
1700 /**
1701  * inode_set_ctime - set the ctime in the inode
1702  * @inode: inode in which to set the ctime
1703  * @sec: tv_sec value to set
1704  * @nsec: tv_nsec value to set
1705  *
1706  * Set the ctime in @inode to { @sec, @nsec }
1707  */
inode_set_ctime(struct inode * inode,time64_t sec,long nsec)1708 static inline struct timespec64 inode_set_ctime(struct inode *inode,
1709 						time64_t sec, long nsec)
1710 {
1711 	struct timespec64 ts = { .tv_sec  = sec,
1712 				 .tv_nsec = nsec };
1713 
1714 	return inode_set_ctime_to_ts(inode, ts);
1715 }
1716 
1717 struct timespec64 simple_inode_init_ts(struct inode *inode);
1718 
1719 /*
1720  * Snapshotting support.
1721  */
1722 
1723 /**
1724  * file_write_started - check if SB_FREEZE_WRITE is held
1725  * @file: the file we write to
1726  *
1727  * May be false positive with !CONFIG_LOCKDEP/LOCK_STATE_UNKNOWN.
1728  * May be false positive with !S_ISREG, because file_start_write() has
1729  * no effect on !S_ISREG.
1730  */
file_write_started(const struct file * file)1731 static inline bool file_write_started(const struct file *file)
1732 {
1733 	if (!S_ISREG(file_inode(file)->i_mode))
1734 		return true;
1735 	return sb_write_started(file_inode(file)->i_sb);
1736 }
1737 
1738 /**
1739  * file_write_not_started - check if SB_FREEZE_WRITE is not held
1740  * @file: the file we write to
1741  *
1742  * May be false positive with !CONFIG_LOCKDEP/LOCK_STATE_UNKNOWN.
1743  * May be false positive with !S_ISREG, because file_start_write() has
1744  * no effect on !S_ISREG.
1745  */
file_write_not_started(const struct file * file)1746 static inline bool file_write_not_started(const struct file *file)
1747 {
1748 	if (!S_ISREG(file_inode(file)->i_mode))
1749 		return true;
1750 	return sb_write_not_started(file_inode(file)->i_sb);
1751 }
1752 
1753 bool inode_owner_or_capable(struct mnt_idmap *idmap,
1754 			    const struct inode *inode);
1755 
1756 /*
1757  * VFS helper functions..
1758  */
1759 int vfs_create(struct mnt_idmap *, struct inode *,
1760 	       struct dentry *, umode_t, bool);
1761 struct dentry *vfs_mkdir(struct mnt_idmap *, struct inode *,
1762 			 struct dentry *, umode_t);
1763 int vfs_mknod(struct mnt_idmap *, struct inode *, struct dentry *,
1764               umode_t, dev_t);
1765 int vfs_symlink(struct mnt_idmap *, struct inode *,
1766 		struct dentry *, const char *);
1767 int vfs_link(struct dentry *, struct mnt_idmap *, struct inode *,
1768 	     struct dentry *, struct inode **);
1769 int vfs_rmdir(struct mnt_idmap *, struct inode *, struct dentry *);
1770 int vfs_unlink(struct mnt_idmap *, struct inode *, struct dentry *,
1771 	       struct inode **);
1772 
1773 /**
1774  * struct renamedata - contains all information required for renaming
1775  * @mnt_idmap:     idmap of the mount in which the rename is happening.
1776  * @old_parent:        parent of source
1777  * @old_dentry:                source
1778  * @new_parent:        parent of destination
1779  * @new_dentry:                destination
1780  * @delegated_inode:   returns an inode needing a delegation break
1781  * @flags:             rename flags
1782  */
1783 struct renamedata {
1784 	struct mnt_idmap *mnt_idmap;
1785 	struct dentry *old_parent;
1786 	struct dentry *old_dentry;
1787 	struct dentry *new_parent;
1788 	struct dentry *new_dentry;
1789 	struct inode **delegated_inode;
1790 	unsigned int flags;
1791 } __randomize_layout;
1792 
1793 int vfs_rename(struct renamedata *);
1794 
vfs_whiteout(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry)1795 static inline int vfs_whiteout(struct mnt_idmap *idmap,
1796 			       struct inode *dir, struct dentry *dentry)
1797 {
1798 	return vfs_mknod(idmap, dir, dentry, S_IFCHR | WHITEOUT_MODE,
1799 			 WHITEOUT_DEV);
1800 }
1801 
1802 struct file *kernel_tmpfile_open(struct mnt_idmap *idmap,
1803 				 const struct path *parentpath,
1804 				 umode_t mode, int open_flag,
1805 				 const struct cred *cred);
1806 struct file *kernel_file_open(const struct path *path, int flags,
1807 			      const struct cred *cred);
1808 
1809 int vfs_mkobj(struct dentry *, umode_t,
1810 		int (*f)(struct dentry *, umode_t, void *),
1811 		void *);
1812 
1813 int vfs_fchown(struct file *file, uid_t user, gid_t group);
1814 int vfs_fchmod(struct file *file, umode_t mode);
1815 int vfs_utimes(const struct path *path, struct timespec64 *times);
1816 
1817 #ifdef CONFIG_COMPAT
1818 extern long compat_ptr_ioctl(struct file *file, unsigned int cmd,
1819 					unsigned long arg);
1820 #else
1821 #define compat_ptr_ioctl NULL
1822 #endif
1823 
1824 /*
1825  * VFS file helper functions.
1826  */
1827 void inode_init_owner(struct mnt_idmap *idmap, struct inode *inode,
1828 		      const struct inode *dir, umode_t mode);
1829 extern bool may_open_dev(const struct path *path);
1830 umode_t mode_strip_sgid(struct mnt_idmap *idmap,
1831 			const struct inode *dir, umode_t mode);
1832 bool in_group_or_capable(struct mnt_idmap *idmap,
1833 			 const struct inode *inode, vfsgid_t vfsgid);
1834 
1835 /*
1836  * This is the "filldir" function type, used by readdir() to let
1837  * the kernel specify what kind of dirent layout it wants to have.
1838  * This allows the kernel to read directories into kernel space or
1839  * to have different dirent layouts depending on the binary type.
1840  * Return 'true' to keep going and 'false' if there are no more entries.
1841  */
1842 struct dir_context;
1843 typedef bool (*filldir_t)(struct dir_context *, const char *, int, loff_t, u64,
1844 			 unsigned);
1845 
1846 struct dir_context {
1847 	filldir_t actor;
1848 	loff_t pos;
1849 	/*
1850 	 * Filesystems MUST NOT MODIFY count, but may use as a hint:
1851 	 * 0	    unknown
1852 	 * > 0      space in buffer (assume at least one entry)
1853 	 * INT_MAX  unlimited
1854 	 */
1855 	int count;
1856 };
1857 
1858 /* If OR-ed with d_type, pending signals are not checked */
1859 #define FILLDIR_FLAG_NOINTR	0x1000
1860 
1861 /*
1862  * These flags let !MMU mmap() govern direct device mapping vs immediate
1863  * copying more easily for MAP_PRIVATE, especially for ROM filesystems.
1864  *
1865  * NOMMU_MAP_COPY:	Copy can be mapped (MAP_PRIVATE)
1866  * NOMMU_MAP_DIRECT:	Can be mapped directly (MAP_SHARED)
1867  * NOMMU_MAP_READ:	Can be mapped for reading
1868  * NOMMU_MAP_WRITE:	Can be mapped for writing
1869  * NOMMU_MAP_EXEC:	Can be mapped for execution
1870  */
1871 #define NOMMU_MAP_COPY		0x00000001
1872 #define NOMMU_MAP_DIRECT	0x00000008
1873 #define NOMMU_MAP_READ		VM_MAYREAD
1874 #define NOMMU_MAP_WRITE		VM_MAYWRITE
1875 #define NOMMU_MAP_EXEC		VM_MAYEXEC
1876 
1877 #define NOMMU_VMFLAGS \
1878 	(NOMMU_MAP_READ | NOMMU_MAP_WRITE | NOMMU_MAP_EXEC)
1879 
1880 /*
1881  * These flags control the behavior of the remap_file_range function pointer.
1882  * If it is called with len == 0 that means "remap to end of source file".
1883  * See Documentation/filesystems/vfs.rst for more details about this call.
1884  *
1885  * REMAP_FILE_DEDUP: only remap if contents identical (i.e. deduplicate)
1886  * REMAP_FILE_CAN_SHORTEN: caller can handle a shortened request
1887  */
1888 #define REMAP_FILE_DEDUP		(1 << 0)
1889 #define REMAP_FILE_CAN_SHORTEN		(1 << 1)
1890 
1891 /*
1892  * These flags signal that the caller is ok with altering various aspects of
1893  * the behavior of the remap operation.  The changes must be made by the
1894  * implementation; the vfs remap helper functions can take advantage of them.
1895  * Flags in this category exist to preserve the quirky behavior of the hoisted
1896  * btrfs clone/dedupe ioctls.
1897  */
1898 #define REMAP_FILE_ADVISORY		(REMAP_FILE_CAN_SHORTEN)
1899 
1900 /*
1901  * These flags control the behavior of vfs_copy_file_range().
1902  * They are not available to the user via syscall.
1903  *
1904  * COPY_FILE_SPLICE: call splice direct instead of fs clone/copy ops
1905  */
1906 #define COPY_FILE_SPLICE		(1 << 0)
1907 
1908 struct iov_iter;
1909 struct io_uring_cmd;
1910 struct offset_ctx;
1911 
1912 typedef unsigned int __bitwise fop_flags_t;
1913 
1914 struct file_operations {
1915 	struct module *owner;
1916 	fop_flags_t fop_flags;
1917 	loff_t (*llseek) (struct file *, loff_t, int);
1918 	ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
1919 	ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
1920 	ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
1921 	ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
1922 	int (*iopoll)(struct kiocb *kiocb, struct io_comp_batch *,
1923 			unsigned int flags);
1924 	int (*iterate_shared) (struct file *, struct dir_context *);
1925 	__poll_t (*poll) (struct file *, struct poll_table_struct *);
1926 	long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
1927 	long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
1928 	int (*mmap) (struct file *, struct vm_area_struct *);
1929 	int (*open) (struct inode *, struct file *);
1930 	int (*flush) (struct file *, fl_owner_t id);
1931 	int (*release) (struct inode *, struct file *);
1932 	int (*fsync) (struct file *, loff_t, loff_t, int datasync);
1933 	int (*fasync) (int, struct file *, int);
1934 	int (*lock) (struct file *, int, struct file_lock *);
1935 	unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
1936 	int (*check_flags)(int);
1937 	int (*flock) (struct file *, int, struct file_lock *);
1938 	ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
1939 	ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
1940 	void (*splice_eof)(struct file *file);
1941 	int (*setlease)(struct file *, int, struct file_lease **, void **);
1942 	long (*fallocate)(struct file *file, int mode, loff_t offset,
1943 			  loff_t len);
1944 	void (*show_fdinfo)(struct seq_file *m, struct file *f);
1945 #ifndef CONFIG_MMU
1946 	unsigned (*mmap_capabilities)(struct file *);
1947 #endif
1948 	ssize_t (*copy_file_range)(struct file *, loff_t, struct file *,
1949 			loff_t, size_t, unsigned int);
1950 	loff_t (*remap_file_range)(struct file *file_in, loff_t pos_in,
1951 				   struct file *file_out, loff_t pos_out,
1952 				   loff_t len, unsigned int remap_flags);
1953 	int (*fadvise)(struct file *, loff_t, loff_t, int);
1954 	int (*uring_cmd)(struct io_uring_cmd *ioucmd, unsigned int issue_flags);
1955 	int (*uring_cmd_iopoll)(struct io_uring_cmd *, struct io_comp_batch *,
1956 				unsigned int poll_flags);
1957 	int (*mmap_prepare)(struct vm_area_desc *);
1958 } __randomize_layout;
1959 
1960 /* Supports async buffered reads */
1961 #define FOP_BUFFER_RASYNC	((__force fop_flags_t)(1 << 0))
1962 /* Supports async buffered writes */
1963 #define FOP_BUFFER_WASYNC	((__force fop_flags_t)(1 << 1))
1964 /* Supports synchronous page faults for mappings */
1965 #define FOP_MMAP_SYNC		((__force fop_flags_t)(1 << 2))
1966 /* Supports non-exclusive O_DIRECT writes from multiple threads */
1967 #define FOP_DIO_PARALLEL_WRITE	((__force fop_flags_t)(1 << 3))
1968 /* Contains huge pages */
1969 #define FOP_HUGE_PAGES		((__force fop_flags_t)(1 << 4))
1970 /* Treat loff_t as unsigned (e.g., /dev/mem) */
1971 #define FOP_UNSIGNED_OFFSET	((__force fop_flags_t)(1 << 5))
1972 /* Supports asynchronous lock callbacks */
1973 #define FOP_ASYNC_LOCK		((__force fop_flags_t)(1 << 6))
1974 /* File system supports uncached read/write buffered IO */
1975 #define FOP_DONTCACHE		((__force fop_flags_t)(1 << 7))
1976 
1977 /* Wrap a directory iterator that needs exclusive inode access */
1978 int wrap_directory_iterator(struct file *, struct dir_context *,
1979 			    int (*) (struct file *, struct dir_context *));
1980 #define WRAP_DIR_ITER(x) \
1981 	static int shared_##x(struct file *file , struct dir_context *ctx) \
1982 	{ return wrap_directory_iterator(file, ctx, x); }
1983 
1984 struct inode_operations {
1985 	struct dentry * (*lookup) (struct inode *,struct dentry *, unsigned int);
1986 	const char * (*get_link) (struct dentry *, struct inode *, struct delayed_call *);
1987 	int (*permission) (struct mnt_idmap *, struct inode *, int);
1988 	struct posix_acl * (*get_inode_acl)(struct inode *, int, bool);
1989 
1990 	int (*readlink) (struct dentry *, char __user *,int);
1991 
1992 	int (*create) (struct mnt_idmap *, struct inode *,struct dentry *,
1993 		       umode_t, bool);
1994 	int (*link) (struct dentry *,struct inode *,struct dentry *);
1995 	int (*unlink) (struct inode *,struct dentry *);
1996 	int (*symlink) (struct mnt_idmap *, struct inode *,struct dentry *,
1997 			const char *);
1998 	struct dentry *(*mkdir) (struct mnt_idmap *, struct inode *,
1999 				 struct dentry *, umode_t);
2000 	int (*rmdir) (struct inode *,struct dentry *);
2001 	int (*mknod) (struct mnt_idmap *, struct inode *,struct dentry *,
2002 		      umode_t,dev_t);
2003 	int (*rename) (struct mnt_idmap *, struct inode *, struct dentry *,
2004 			struct inode *, struct dentry *, unsigned int);
2005 	int (*setattr) (struct mnt_idmap *, struct dentry *, struct iattr *);
2006 	int (*getattr) (struct mnt_idmap *, const struct path *,
2007 			struct kstat *, u32, unsigned int);
2008 	ssize_t (*listxattr) (struct dentry *, char *, size_t);
2009 	int (*fiemap)(struct inode *, struct fiemap_extent_info *, u64 start,
2010 		      u64 len);
2011 	int (*update_time)(struct inode *, int);
2012 	int (*atomic_open)(struct inode *, struct dentry *,
2013 			   struct file *, unsigned open_flag,
2014 			   umode_t create_mode);
2015 	int (*tmpfile) (struct mnt_idmap *, struct inode *,
2016 			struct file *, umode_t);
2017 	struct posix_acl *(*get_acl)(struct mnt_idmap *, struct dentry *,
2018 				     int);
2019 	int (*set_acl)(struct mnt_idmap *, struct dentry *,
2020 		       struct posix_acl *, int);
2021 	int (*fileattr_set)(struct mnt_idmap *idmap,
2022 			    struct dentry *dentry, struct file_kattr *fa);
2023 	int (*fileattr_get)(struct dentry *dentry, struct file_kattr *fa);
2024 	struct offset_ctx *(*get_offset_ctx)(struct inode *inode);
2025 } ____cacheline_aligned;
2026 
2027 /* Did the driver provide valid mmap hook configuration? */
can_mmap_file(struct file * file)2028 static inline bool can_mmap_file(struct file *file)
2029 {
2030 	bool has_mmap = file->f_op->mmap;
2031 	bool has_mmap_prepare = file->f_op->mmap_prepare;
2032 
2033 	/* Hooks are mutually exclusive. */
2034 	if (WARN_ON_ONCE(has_mmap && has_mmap_prepare))
2035 		return false;
2036 	if (!has_mmap && !has_mmap_prepare)
2037 		return false;
2038 
2039 	return true;
2040 }
2041 
2042 int __compat_vma_mmap_prepare(const struct file_operations *f_op,
2043 		struct file *file, struct vm_area_struct *vma);
2044 int compat_vma_mmap_prepare(struct file *file, struct vm_area_struct *vma);
2045 
vfs_mmap(struct file * file,struct vm_area_struct * vma)2046 static inline int vfs_mmap(struct file *file, struct vm_area_struct *vma)
2047 {
2048 	if (file->f_op->mmap_prepare)
2049 		return compat_vma_mmap_prepare(file, vma);
2050 
2051 	return file->f_op->mmap(file, vma);
2052 }
2053 
vfs_mmap_prepare(struct file * file,struct vm_area_desc * desc)2054 static inline int vfs_mmap_prepare(struct file *file, struct vm_area_desc *desc)
2055 {
2056 	return file->f_op->mmap_prepare(desc);
2057 }
2058 
2059 extern ssize_t vfs_read(struct file *, char __user *, size_t, loff_t *);
2060 extern ssize_t vfs_write(struct file *, const char __user *, size_t, loff_t *);
2061 extern ssize_t vfs_copy_file_range(struct file *, loff_t , struct file *,
2062 				   loff_t, size_t, unsigned int);
2063 int remap_verify_area(struct file *file, loff_t pos, loff_t len, bool write);
2064 int __generic_remap_file_range_prep(struct file *file_in, loff_t pos_in,
2065 				    struct file *file_out, loff_t pos_out,
2066 				    loff_t *len, unsigned int remap_flags,
2067 				    const struct iomap_ops *dax_read_ops);
2068 int generic_remap_file_range_prep(struct file *file_in, loff_t pos_in,
2069 				  struct file *file_out, loff_t pos_out,
2070 				  loff_t *count, unsigned int remap_flags);
2071 extern loff_t vfs_clone_file_range(struct file *file_in, loff_t pos_in,
2072 				   struct file *file_out, loff_t pos_out,
2073 				   loff_t len, unsigned int remap_flags);
2074 extern int vfs_dedupe_file_range(struct file *file,
2075 				 struct file_dedupe_range *same);
2076 extern loff_t vfs_dedupe_file_range_one(struct file *src_file, loff_t src_pos,
2077 					struct file *dst_file, loff_t dst_pos,
2078 					loff_t len, unsigned int remap_flags);
2079 
2080 /*
2081  * Inode flags - they have no relation to superblock flags now
2082  */
2083 #define S_SYNC		(1 << 0)  /* Writes are synced at once */
2084 #define S_NOATIME	(1 << 1)  /* Do not update access times */
2085 #define S_APPEND	(1 << 2)  /* Append-only file */
2086 #define S_IMMUTABLE	(1 << 3)  /* Immutable file */
2087 #define S_DEAD		(1 << 4)  /* removed, but still open directory */
2088 #define S_NOQUOTA	(1 << 5)  /* Inode is not counted to quota */
2089 #define S_DIRSYNC	(1 << 6)  /* Directory modifications are synchronous */
2090 #define S_NOCMTIME	(1 << 7)  /* Do not update file c/mtime */
2091 #define S_SWAPFILE	(1 << 8)  /* Do not truncate: swapon got its bmaps */
2092 #define S_PRIVATE	(1 << 9)  /* Inode is fs-internal */
2093 #define S_IMA		(1 << 10) /* Inode has an associated IMA struct */
2094 #define S_AUTOMOUNT	(1 << 11) /* Automount/referral quasi-directory */
2095 #define S_NOSEC		(1 << 12) /* no suid or xattr security attributes */
2096 #ifdef CONFIG_FS_DAX
2097 #define S_DAX		(1 << 13) /* Direct Access, avoiding the page cache */
2098 #else
2099 #define S_DAX		0	  /* Make all the DAX code disappear */
2100 #endif
2101 #define S_ENCRYPTED	(1 << 14) /* Encrypted file (using fs/crypto/) */
2102 #define S_CASEFOLD	(1 << 15) /* Casefolded file */
2103 #define S_VERITY	(1 << 16) /* Verity file (using fs/verity/) */
2104 #define S_KERNEL_FILE	(1 << 17) /* File is in use by the kernel (eg. fs/cachefiles) */
2105 #define S_ANON_INODE	(1 << 19) /* Inode is an anonymous inode */
2106 
2107 /*
2108  * Note that nosuid etc flags are inode-specific: setting some file-system
2109  * flags just means all the inodes inherit those flags by default. It might be
2110  * possible to override it selectively if you really wanted to with some
2111  * ioctl() that is not currently implemented.
2112  *
2113  * Exception: SB_RDONLY is always applied to the entire file system.
2114  *
2115  * Unfortunately, it is possible to change a filesystems flags with it mounted
2116  * with files in use.  This means that all of the inodes will not have their
2117  * i_flags updated.  Hence, i_flags no longer inherit the superblock mount
2118  * flags, so these have to be checked separately. -- rmk@arm.uk.linux.org
2119  */
2120 #define __IS_FLG(inode, flg)	((inode)->i_sb->s_flags & (flg))
2121 
2122 #define IS_RDONLY(inode)	sb_rdonly((inode)->i_sb)
2123 #define IS_SYNC(inode)		(__IS_FLG(inode, SB_SYNCHRONOUS) || \
2124 					((inode)->i_flags & S_SYNC))
2125 #define IS_DIRSYNC(inode)	(__IS_FLG(inode, SB_SYNCHRONOUS|SB_DIRSYNC) || \
2126 					((inode)->i_flags & (S_SYNC|S_DIRSYNC)))
2127 #define IS_MANDLOCK(inode)	__IS_FLG(inode, SB_MANDLOCK)
2128 #define IS_NOATIME(inode)	__IS_FLG(inode, SB_RDONLY|SB_NOATIME)
2129 #define IS_I_VERSION(inode)	__IS_FLG(inode, SB_I_VERSION)
2130 
2131 #define IS_NOQUOTA(inode)	((inode)->i_flags & S_NOQUOTA)
2132 #define IS_APPEND(inode)	((inode)->i_flags & S_APPEND)
2133 #define IS_IMMUTABLE(inode)	((inode)->i_flags & S_IMMUTABLE)
2134 
2135 #ifdef CONFIG_FS_POSIX_ACL
2136 #define IS_POSIXACL(inode)	__IS_FLG(inode, SB_POSIXACL)
2137 #else
2138 #define IS_POSIXACL(inode)	0
2139 #endif
2140 
2141 #define IS_DEADDIR(inode)	((inode)->i_flags & S_DEAD)
2142 #define IS_NOCMTIME(inode)	((inode)->i_flags & S_NOCMTIME)
2143 
2144 #ifdef CONFIG_SWAP
2145 #define IS_SWAPFILE(inode)	((inode)->i_flags & S_SWAPFILE)
2146 #else
2147 #define IS_SWAPFILE(inode)	((void)(inode), 0U)
2148 #endif
2149 
2150 #define IS_PRIVATE(inode)	((inode)->i_flags & S_PRIVATE)
2151 #define IS_IMA(inode)		((inode)->i_flags & S_IMA)
2152 #define IS_AUTOMOUNT(inode)	((inode)->i_flags & S_AUTOMOUNT)
2153 #define IS_NOSEC(inode)		((inode)->i_flags & S_NOSEC)
2154 #define IS_DAX(inode)		((inode)->i_flags & S_DAX)
2155 #define IS_ENCRYPTED(inode)	((inode)->i_flags & S_ENCRYPTED)
2156 #define IS_CASEFOLDED(inode)	((inode)->i_flags & S_CASEFOLD)
2157 #define IS_VERITY(inode)	((inode)->i_flags & S_VERITY)
2158 
2159 #define IS_WHITEOUT(inode)	(S_ISCHR(inode->i_mode) && \
2160 				 (inode)->i_rdev == WHITEOUT_DEV)
2161 #define IS_ANON_FILE(inode)	((inode)->i_flags & S_ANON_INODE)
2162 
HAS_UNMAPPED_ID(struct mnt_idmap * idmap,struct inode * inode)2163 static inline bool HAS_UNMAPPED_ID(struct mnt_idmap *idmap,
2164 				   struct inode *inode)
2165 {
2166 	return !vfsuid_valid(i_uid_into_vfsuid(idmap, inode)) ||
2167 	       !vfsgid_valid(i_gid_into_vfsgid(idmap, inode));
2168 }
2169 
init_sync_kiocb(struct kiocb * kiocb,struct file * filp)2170 static inline void init_sync_kiocb(struct kiocb *kiocb, struct file *filp)
2171 {
2172 	*kiocb = (struct kiocb) {
2173 		.ki_filp = filp,
2174 		.ki_flags = filp->f_iocb_flags,
2175 		.ki_ioprio = get_current_ioprio(),
2176 	};
2177 }
2178 
kiocb_clone(struct kiocb * kiocb,struct kiocb * kiocb_src,struct file * filp)2179 static inline void kiocb_clone(struct kiocb *kiocb, struct kiocb *kiocb_src,
2180 			       struct file *filp)
2181 {
2182 	*kiocb = (struct kiocb) {
2183 		.ki_filp = filp,
2184 		.ki_flags = kiocb_src->ki_flags,
2185 		.ki_ioprio = kiocb_src->ki_ioprio,
2186 		.ki_pos = kiocb_src->ki_pos,
2187 	};
2188 }
2189 
2190 extern void __mark_inode_dirty(struct inode *, int);
mark_inode_dirty(struct inode * inode)2191 static inline void mark_inode_dirty(struct inode *inode)
2192 {
2193 	__mark_inode_dirty(inode, I_DIRTY);
2194 }
2195 
mark_inode_dirty_sync(struct inode * inode)2196 static inline void mark_inode_dirty_sync(struct inode *inode)
2197 {
2198 	__mark_inode_dirty(inode, I_DIRTY_SYNC);
2199 }
2200 
icount_read(const struct inode * inode)2201 static inline int icount_read(const struct inode *inode)
2202 {
2203 	return atomic_read(&inode->i_count);
2204 }
2205 
2206 /*
2207  * Returns true if the given inode itself only has dirty timestamps (its pages
2208  * may still be dirty) and isn't currently being allocated or freed.
2209  * Filesystems should call this if when writing an inode when lazytime is
2210  * enabled, they want to opportunistically write the timestamps of other inodes
2211  * located very nearby on-disk, e.g. in the same inode block.  This returns true
2212  * if the given inode is in need of such an opportunistic update.  Requires
2213  * i_lock, or at least later re-checking under i_lock.
2214  */
inode_is_dirtytime_only(struct inode * inode)2215 static inline bool inode_is_dirtytime_only(struct inode *inode)
2216 {
2217 	return (inode_state_read_once(inode) &
2218 	       (I_DIRTY_TIME | I_NEW | I_FREEING | I_WILL_FREE)) == I_DIRTY_TIME;
2219 }
2220 
2221 extern void inc_nlink(struct inode *inode);
2222 extern void drop_nlink(struct inode *inode);
2223 extern void clear_nlink(struct inode *inode);
2224 extern void set_nlink(struct inode *inode, unsigned int nlink);
2225 
inode_inc_link_count(struct inode * inode)2226 static inline void inode_inc_link_count(struct inode *inode)
2227 {
2228 	inc_nlink(inode);
2229 	mark_inode_dirty(inode);
2230 }
2231 
inode_dec_link_count(struct inode * inode)2232 static inline void inode_dec_link_count(struct inode *inode)
2233 {
2234 	drop_nlink(inode);
2235 	mark_inode_dirty(inode);
2236 }
2237 
2238 enum file_time_flags {
2239 	S_ATIME = 1,
2240 	S_MTIME = 2,
2241 	S_CTIME = 4,
2242 	S_VERSION = 8,
2243 };
2244 
2245 extern bool atime_needs_update(const struct path *, struct inode *);
2246 extern void touch_atime(const struct path *);
2247 int inode_update_time(struct inode *inode, int flags);
2248 
file_accessed(struct file * file)2249 static inline void file_accessed(struct file *file)
2250 {
2251 	if (!(file->f_flags & O_NOATIME))
2252 		touch_atime(&file->f_path);
2253 }
2254 
2255 extern int file_modified(struct file *file);
2256 int kiocb_modified(struct kiocb *iocb);
2257 
2258 int sync_inode_metadata(struct inode *inode, int wait);
2259 
2260 struct file_system_type {
2261 	const char *name;
2262 	int fs_flags;
2263 #define FS_REQUIRES_DEV		1
2264 #define FS_BINARY_MOUNTDATA	2
2265 #define FS_HAS_SUBTYPE		4
2266 #define FS_USERNS_MOUNT		8	/* Can be mounted by userns root */
2267 #define FS_DISALLOW_NOTIFY_PERM	16	/* Disable fanotify permission events */
2268 #define FS_ALLOW_IDMAP         32      /* FS has been updated to handle vfs idmappings. */
2269 #define FS_MGTIME		64	/* FS uses multigrain timestamps */
2270 #define FS_LBS			128	/* FS supports LBS */
2271 #define FS_POWER_FREEZE		256	/* Always freeze on suspend/hibernate */
2272 #define FS_RENAME_DOES_D_MOVE	32768	/* FS will handle d_move() during rename() internally. */
2273 	int (*init_fs_context)(struct fs_context *);
2274 	const struct fs_parameter_spec *parameters;
2275 	struct dentry *(*mount) (struct file_system_type *, int,
2276 		       const char *, void *);
2277 	void (*kill_sb) (struct super_block *);
2278 	struct module *owner;
2279 	struct file_system_type * next;
2280 	struct hlist_head fs_supers;
2281 
2282 	struct lock_class_key s_lock_key;
2283 	struct lock_class_key s_umount_key;
2284 	struct lock_class_key s_vfs_rename_key;
2285 	struct lock_class_key s_writers_key[SB_FREEZE_LEVELS];
2286 
2287 	struct lock_class_key i_lock_key;
2288 	struct lock_class_key i_mutex_key;
2289 	struct lock_class_key invalidate_lock_key;
2290 	struct lock_class_key i_mutex_dir_key;
2291 };
2292 
2293 #define MODULE_ALIAS_FS(NAME) MODULE_ALIAS("fs-" NAME)
2294 
2295 /**
2296  * is_mgtime: is this inode using multigrain timestamps
2297  * @inode: inode to test for multigrain timestamps
2298  *
2299  * Return true if the inode uses multigrain timestamps, false otherwise.
2300  */
is_mgtime(const struct inode * inode)2301 static inline bool is_mgtime(const struct inode *inode)
2302 {
2303 	return inode->i_opflags & IOP_MGTIME;
2304 }
2305 
2306 extern struct dentry *mount_subtree(struct vfsmount *mnt, const char *path);
2307 void retire_super(struct super_block *sb);
2308 void generic_shutdown_super(struct super_block *sb);
2309 void kill_block_super(struct super_block *sb);
2310 void kill_anon_super(struct super_block *sb);
2311 void kill_litter_super(struct super_block *sb);
2312 void deactivate_super(struct super_block *sb);
2313 void deactivate_locked_super(struct super_block *sb);
2314 int set_anon_super(struct super_block *s, void *data);
2315 int set_anon_super_fc(struct super_block *s, struct fs_context *fc);
2316 int get_anon_bdev(dev_t *);
2317 void free_anon_bdev(dev_t);
2318 struct super_block *sget_fc(struct fs_context *fc,
2319 			    int (*test)(struct super_block *, struct fs_context *),
2320 			    int (*set)(struct super_block *, struct fs_context *));
2321 struct super_block *sget(struct file_system_type *type,
2322 			int (*test)(struct super_block *,void *),
2323 			int (*set)(struct super_block *,void *),
2324 			int flags, void *data);
2325 struct super_block *sget_dev(struct fs_context *fc, dev_t dev);
2326 
2327 /* Alas, no aliases. Too much hassle with bringing module.h everywhere */
2328 #define fops_get(fops) ({						\
2329 	const struct file_operations *_fops = (fops);			\
2330 	(((_fops) && try_module_get((_fops)->owner) ? (_fops) : NULL));	\
2331 })
2332 
2333 #define fops_put(fops) ({						\
2334 	const struct file_operations *_fops = (fops);			\
2335 	if (_fops)							\
2336 		module_put((_fops)->owner);				\
2337 })
2338 
2339 /*
2340  * This one is to be used *ONLY* from ->open() instances.
2341  * fops must be non-NULL, pinned down *and* module dependencies
2342  * should be sufficient to pin the caller down as well.
2343  */
2344 #define replace_fops(f, fops) \
2345 	do {	\
2346 		struct file *__file = (f); \
2347 		fops_put(__file->f_op); \
2348 		BUG_ON(!(__file->f_op = (fops))); \
2349 	} while(0)
2350 
2351 extern int register_filesystem(struct file_system_type *);
2352 extern int unregister_filesystem(struct file_system_type *);
2353 extern int vfs_statfs(const struct path *, struct kstatfs *);
2354 extern int user_statfs(const char __user *, struct kstatfs *);
2355 extern int fd_statfs(int, struct kstatfs *);
2356 extern __printf(2, 3)
2357 int super_setup_bdi_name(struct super_block *sb, char *fmt, ...);
2358 extern int super_setup_bdi(struct super_block *sb);
2359 
super_set_uuid(struct super_block * sb,const u8 * uuid,unsigned len)2360 static inline void super_set_uuid(struct super_block *sb, const u8 *uuid, unsigned len)
2361 {
2362 	if (WARN_ON(len > sizeof(sb->s_uuid)))
2363 		len = sizeof(sb->s_uuid);
2364 	sb->s_uuid_len = len;
2365 	memcpy(&sb->s_uuid, uuid, len);
2366 }
2367 
2368 /* set sb sysfs name based on sb->s_bdev */
super_set_sysfs_name_bdev(struct super_block * sb)2369 static inline void super_set_sysfs_name_bdev(struct super_block *sb)
2370 {
2371 	snprintf(sb->s_sysfs_name, sizeof(sb->s_sysfs_name), "%pg", sb->s_bdev);
2372 }
2373 
2374 /* set sb sysfs name based on sb->s_uuid */
super_set_sysfs_name_uuid(struct super_block * sb)2375 static inline void super_set_sysfs_name_uuid(struct super_block *sb)
2376 {
2377 	WARN_ON(sb->s_uuid_len != sizeof(sb->s_uuid));
2378 	snprintf(sb->s_sysfs_name, sizeof(sb->s_sysfs_name), "%pU", sb->s_uuid.b);
2379 }
2380 
2381 /* set sb sysfs name based on sb->s_id */
super_set_sysfs_name_id(struct super_block * sb)2382 static inline void super_set_sysfs_name_id(struct super_block *sb)
2383 {
2384 	strscpy(sb->s_sysfs_name, sb->s_id, sizeof(sb->s_sysfs_name));
2385 }
2386 
2387 /* try to use something standard before you use this */
2388 __printf(2, 3)
super_set_sysfs_name_generic(struct super_block * sb,const char * fmt,...)2389 static inline void super_set_sysfs_name_generic(struct super_block *sb, const char *fmt, ...)
2390 {
2391 	va_list args;
2392 
2393 	va_start(args, fmt);
2394 	vsnprintf(sb->s_sysfs_name, sizeof(sb->s_sysfs_name), fmt, args);
2395 	va_end(args);
2396 }
2397 
2398 extern void ihold(struct inode * inode);
2399 extern void iput(struct inode *);
2400 void iput_not_last(struct inode *);
2401 int inode_update_timestamps(struct inode *inode, int flags);
2402 int generic_update_time(struct inode *, int);
2403 
2404 /* /sys/fs */
2405 extern struct kobject *fs_kobj;
2406 
2407 #define MAX_RW_COUNT (INT_MAX & PAGE_MASK)
2408 
2409 /* fs/open.c */
2410 struct audit_names;
2411 struct filename {
2412 	const char		*name;	/* pointer to actual string */
2413 	const __user char	*uptr;	/* original userland pointer */
2414 	atomic_t		refcnt;
2415 	struct audit_names	*aname;
2416 	const char		iname[];
2417 };
2418 static_assert(offsetof(struct filename, iname) % sizeof(long) == 0);
2419 
file_mnt_idmap(const struct file * file)2420 static inline struct mnt_idmap *file_mnt_idmap(const struct file *file)
2421 {
2422 	return mnt_idmap(file->f_path.mnt);
2423 }
2424 
2425 /**
2426  * is_idmapped_mnt - check whether a mount is mapped
2427  * @mnt: the mount to check
2428  *
2429  * If @mnt has an non @nop_mnt_idmap attached to it then @mnt is mapped.
2430  *
2431  * Return: true if mount is mapped, false if not.
2432  */
is_idmapped_mnt(const struct vfsmount * mnt)2433 static inline bool is_idmapped_mnt(const struct vfsmount *mnt)
2434 {
2435 	return mnt_idmap(mnt) != &nop_mnt_idmap;
2436 }
2437 
2438 int vfs_truncate(const struct path *, loff_t);
2439 int do_truncate(struct mnt_idmap *, struct dentry *, loff_t start,
2440 		unsigned int time_attrs, struct file *filp);
2441 extern int vfs_fallocate(struct file *file, int mode, loff_t offset,
2442 			loff_t len);
2443 int do_sys_open(int dfd, const char __user *filename, int flags,
2444 		umode_t mode);
2445 extern struct file *file_open_name(struct filename *, int, umode_t);
2446 extern struct file *filp_open(const char *, int, umode_t);
2447 extern struct file *file_open_root(const struct path *,
2448 				   const char *, int, umode_t);
file_open_root_mnt(struct vfsmount * mnt,const char * name,int flags,umode_t mode)2449 static inline struct file *file_open_root_mnt(struct vfsmount *mnt,
2450 				   const char *name, int flags, umode_t mode)
2451 {
2452 	return file_open_root(&(struct path){.mnt = mnt, .dentry = mnt->mnt_root},
2453 			      name, flags, mode);
2454 }
2455 struct file *dentry_open(const struct path *path, int flags,
2456 			 const struct cred *creds);
2457 struct file *dentry_open_nonotify(const struct path *path, int flags,
2458 				  const struct cred *cred);
2459 struct file *dentry_create(const struct path *path, int flags, umode_t mode,
2460 			   const struct cred *cred);
2461 const struct path *backing_file_user_path(const struct file *f);
2462 
2463 /*
2464  * When mmapping a file on a stackable filesystem (e.g., overlayfs), the file
2465  * stored in ->vm_file is a backing file whose f_inode is on the underlying
2466  * filesystem.  When the mapped file path and inode number are displayed to
2467  * user (e.g. via /proc/<pid>/maps), these helpers should be used to get the
2468  * path and inode number to display to the user, which is the path of the fd
2469  * that user has requested to map and the inode number that would be returned
2470  * by fstat() on that same fd.
2471  */
2472 /* Get the path to display in /proc/<pid>/maps */
file_user_path(const struct file * f)2473 static inline const struct path *file_user_path(const struct file *f)
2474 {
2475 	if (unlikely(f->f_mode & FMODE_BACKING))
2476 		return backing_file_user_path(f);
2477 	return &f->f_path;
2478 }
2479 /* Get the inode whose inode number to display in /proc/<pid>/maps */
file_user_inode(const struct file * f)2480 static inline const struct inode *file_user_inode(const struct file *f)
2481 {
2482 	if (unlikely(f->f_mode & FMODE_BACKING))
2483 		return d_inode(backing_file_user_path(f)->dentry);
2484 	return file_inode(f);
2485 }
2486 
file_clone_open(struct file * file)2487 static inline struct file *file_clone_open(struct file *file)
2488 {
2489 	return dentry_open(&file->f_path, file->f_flags, file->f_cred);
2490 }
2491 extern int filp_close(struct file *, fl_owner_t id);
2492 
2493 extern struct filename *getname_flags(const char __user *, int);
2494 extern struct filename *getname_uflags(const char __user *, int);
getname(const char __user * name)2495 static inline struct filename *getname(const char __user *name)
2496 {
2497 	return getname_flags(name, 0);
2498 }
2499 extern struct filename *getname_kernel(const char *);
2500 extern struct filename *__getname_maybe_null(const char __user *);
getname_maybe_null(const char __user * name,int flags)2501 static inline struct filename *getname_maybe_null(const char __user *name, int flags)
2502 {
2503 	if (!(flags & AT_EMPTY_PATH))
2504 		return getname(name);
2505 
2506 	if (!name)
2507 		return NULL;
2508 	return __getname_maybe_null(name);
2509 }
2510 extern void putname(struct filename *name);
2511 DEFINE_FREE(putname, struct filename *, if (!IS_ERR_OR_NULL(_T)) putname(_T))
2512 
refname(struct filename * name)2513 static inline struct filename *refname(struct filename *name)
2514 {
2515 	atomic_inc(&name->refcnt);
2516 	return name;
2517 }
2518 
2519 extern int finish_open(struct file *file, struct dentry *dentry,
2520 			int (*open)(struct inode *, struct file *));
2521 extern int finish_no_open(struct file *file, struct dentry *dentry);
2522 
2523 /* Helper for the simple case when original dentry is used */
finish_open_simple(struct file * file,int error)2524 static inline int finish_open_simple(struct file *file, int error)
2525 {
2526 	if (error)
2527 		return error;
2528 
2529 	return finish_open(file, file->f_path.dentry, NULL);
2530 }
2531 
2532 /* fs/dcache.c */
2533 extern void __init vfs_caches_init_early(void);
2534 extern void __init vfs_caches_init(void);
2535 
2536 extern struct kmem_cache *names_cachep;
2537 
2538 #define __getname()		kmem_cache_alloc(names_cachep, GFP_KERNEL)
2539 #define __putname(name)		kmem_cache_free(names_cachep, (void *)(name))
2540 
2541 void emergency_thaw_all(void);
2542 extern int sync_filesystem(struct super_block *);
2543 extern const struct file_operations def_blk_fops;
2544 extern const struct file_operations def_chr_fops;
2545 
2546 /* fs/char_dev.c */
2547 #define CHRDEV_MAJOR_MAX 512
2548 /* Marks the bottom of the first segment of free char majors */
2549 #define CHRDEV_MAJOR_DYN_END 234
2550 /* Marks the top and bottom of the second segment of free char majors */
2551 #define CHRDEV_MAJOR_DYN_EXT_START 511
2552 #define CHRDEV_MAJOR_DYN_EXT_END 384
2553 
2554 extern int alloc_chrdev_region(dev_t *, unsigned, unsigned, const char *);
2555 extern int register_chrdev_region(dev_t, unsigned, const char *);
2556 extern int __register_chrdev(unsigned int major, unsigned int baseminor,
2557 			     unsigned int count, const char *name,
2558 			     const struct file_operations *fops);
2559 extern void __unregister_chrdev(unsigned int major, unsigned int baseminor,
2560 				unsigned int count, const char *name);
2561 extern void unregister_chrdev_region(dev_t, unsigned);
2562 extern void chrdev_show(struct seq_file *,off_t);
2563 
register_chrdev(unsigned int major,const char * name,const struct file_operations * fops)2564 static inline int register_chrdev(unsigned int major, const char *name,
2565 				  const struct file_operations *fops)
2566 {
2567 	return __register_chrdev(major, 0, 256, name, fops);
2568 }
2569 
unregister_chrdev(unsigned int major,const char * name)2570 static inline void unregister_chrdev(unsigned int major, const char *name)
2571 {
2572 	__unregister_chrdev(major, 0, 256, name);
2573 }
2574 
2575 extern void init_special_inode(struct inode *, umode_t, dev_t);
2576 
2577 /* Invalid inode operations -- fs/bad_inode.c */
2578 extern void make_bad_inode(struct inode *);
2579 extern bool is_bad_inode(struct inode *);
2580 
2581 extern int __must_check file_fdatawait_range(struct file *file, loff_t lstart,
2582 						loff_t lend);
2583 extern int __must_check file_check_and_advance_wb_err(struct file *file);
2584 extern int __must_check file_write_and_wait_range(struct file *file,
2585 						loff_t start, loff_t end);
2586 int filemap_flush_range(struct address_space *mapping, loff_t start,
2587 		loff_t end);
2588 
file_write_and_wait(struct file * file)2589 static inline int file_write_and_wait(struct file *file)
2590 {
2591 	return file_write_and_wait_range(file, 0, LLONG_MAX);
2592 }
2593 
2594 extern int vfs_fsync_range(struct file *file, loff_t start, loff_t end,
2595 			   int datasync);
2596 extern int vfs_fsync(struct file *file, int datasync);
2597 
2598 extern int sync_file_range(struct file *file, loff_t offset, loff_t nbytes,
2599 				unsigned int flags);
2600 
iocb_is_dsync(const struct kiocb * iocb)2601 static inline bool iocb_is_dsync(const struct kiocb *iocb)
2602 {
2603 	return (iocb->ki_flags & IOCB_DSYNC) ||
2604 		IS_SYNC(iocb->ki_filp->f_mapping->host);
2605 }
2606 
2607 /*
2608  * Sync the bytes written if this was a synchronous write.  Expect ki_pos
2609  * to already be updated for the write, and will return either the amount
2610  * of bytes passed in, or an error if syncing the file failed.
2611  */
generic_write_sync(struct kiocb * iocb,ssize_t count)2612 static inline ssize_t generic_write_sync(struct kiocb *iocb, ssize_t count)
2613 {
2614 	if (iocb_is_dsync(iocb)) {
2615 		int ret = vfs_fsync_range(iocb->ki_filp,
2616 				iocb->ki_pos - count, iocb->ki_pos - 1,
2617 				(iocb->ki_flags & IOCB_SYNC) ? 0 : 1);
2618 		if (ret)
2619 			return ret;
2620 	} else if (iocb->ki_flags & IOCB_DONTCACHE) {
2621 		struct address_space *mapping = iocb->ki_filp->f_mapping;
2622 
2623 		filemap_flush_range(mapping, iocb->ki_pos - count,
2624 				iocb->ki_pos - 1);
2625 	}
2626 
2627 	return count;
2628 }
2629 
2630 extern void emergency_sync(void);
2631 extern void emergency_remount(void);
2632 
2633 #ifdef CONFIG_BLOCK
2634 extern int bmap(struct inode *inode, sector_t *block);
2635 #else
bmap(struct inode * inode,sector_t * block)2636 static inline int bmap(struct inode *inode,  sector_t *block)
2637 {
2638 	return -EINVAL;
2639 }
2640 #endif
2641 
2642 int notify_change(struct mnt_idmap *, struct dentry *,
2643 		  struct iattr *, struct inode **);
2644 int inode_permission(struct mnt_idmap *, struct inode *, int);
2645 int generic_permission(struct mnt_idmap *, struct inode *, int);
file_permission(struct file * file,int mask)2646 static inline int file_permission(struct file *file, int mask)
2647 {
2648 	return inode_permission(file_mnt_idmap(file),
2649 				file_inode(file), mask);
2650 }
path_permission(const struct path * path,int mask)2651 static inline int path_permission(const struct path *path, int mask)
2652 {
2653 	return inode_permission(mnt_idmap(path->mnt),
2654 				d_inode(path->dentry), mask);
2655 }
2656 int __check_sticky(struct mnt_idmap *idmap, struct inode *dir,
2657 		   struct inode *inode);
2658 
execute_ok(struct inode * inode)2659 static inline bool execute_ok(struct inode *inode)
2660 {
2661 	return (inode->i_mode & S_IXUGO) || S_ISDIR(inode->i_mode);
2662 }
2663 
inode_wrong_type(const struct inode * inode,umode_t mode)2664 static inline bool inode_wrong_type(const struct inode *inode, umode_t mode)
2665 {
2666 	return (inode->i_mode ^ mode) & S_IFMT;
2667 }
2668 
2669 /**
2670  * file_start_write - get write access to a superblock for regular file io
2671  * @file: the file we want to write to
2672  *
2673  * This is a variant of sb_start_write() which is a noop on non-regular file.
2674  * Should be matched with a call to file_end_write().
2675  */
file_start_write(struct file * file)2676 static inline void file_start_write(struct file *file)
2677 {
2678 	if (!S_ISREG(file_inode(file)->i_mode))
2679 		return;
2680 	sb_start_write(file_inode(file)->i_sb);
2681 }
2682 
file_start_write_trylock(struct file * file)2683 static inline bool file_start_write_trylock(struct file *file)
2684 {
2685 	if (!S_ISREG(file_inode(file)->i_mode))
2686 		return true;
2687 	return sb_start_write_trylock(file_inode(file)->i_sb);
2688 }
2689 
2690 /**
2691  * file_end_write - drop write access to a superblock of a regular file
2692  * @file: the file we wrote to
2693  *
2694  * Should be matched with a call to file_start_write().
2695  */
file_end_write(struct file * file)2696 static inline void file_end_write(struct file *file)
2697 {
2698 	if (!S_ISREG(file_inode(file)->i_mode))
2699 		return;
2700 	sb_end_write(file_inode(file)->i_sb);
2701 }
2702 
2703 /**
2704  * kiocb_start_write - get write access to a superblock for async file io
2705  * @iocb: the io context we want to submit the write with
2706  *
2707  * This is a variant of sb_start_write() for async io submission.
2708  * Should be matched with a call to kiocb_end_write().
2709  */
kiocb_start_write(struct kiocb * iocb)2710 static inline void kiocb_start_write(struct kiocb *iocb)
2711 {
2712 	struct inode *inode = file_inode(iocb->ki_filp);
2713 
2714 	sb_start_write(inode->i_sb);
2715 	/*
2716 	 * Fool lockdep by telling it the lock got released so that it
2717 	 * doesn't complain about the held lock when we return to userspace.
2718 	 */
2719 	__sb_writers_release(inode->i_sb, SB_FREEZE_WRITE);
2720 }
2721 
2722 /**
2723  * kiocb_end_write - drop write access to a superblock after async file io
2724  * @iocb: the io context we sumbitted the write with
2725  *
2726  * Should be matched with a call to kiocb_start_write().
2727  */
kiocb_end_write(struct kiocb * iocb)2728 static inline void kiocb_end_write(struct kiocb *iocb)
2729 {
2730 	struct inode *inode = file_inode(iocb->ki_filp);
2731 
2732 	/*
2733 	 * Tell lockdep we inherited freeze protection from submission thread.
2734 	 */
2735 	__sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2736 	sb_end_write(inode->i_sb);
2737 }
2738 
2739 /*
2740  * This is used for regular files where some users -- especially the
2741  * currently executed binary in a process, previously handled via
2742  * VM_DENYWRITE -- cannot handle concurrent write (and maybe mmap
2743  * read-write shared) accesses.
2744  *
2745  * get_write_access() gets write permission for a file.
2746  * put_write_access() releases this write permission.
2747  * deny_write_access() denies write access to a file.
2748  * allow_write_access() re-enables write access to a file.
2749  *
2750  * The i_writecount field of an inode can have the following values:
2751  * 0: no write access, no denied write access
2752  * < 0: (-i_writecount) users that denied write access to the file.
2753  * > 0: (i_writecount) users that have write access to the file.
2754  *
2755  * Normally we operate on that counter with atomic_{inc,dec} and it's safe
2756  * except for the cases where we don't hold i_writecount yet. Then we need to
2757  * use {get,deny}_write_access() - these functions check the sign and refuse
2758  * to do the change if sign is wrong.
2759  */
get_write_access(struct inode * inode)2760 static inline int get_write_access(struct inode *inode)
2761 {
2762 	return atomic_inc_unless_negative(&inode->i_writecount) ? 0 : -ETXTBSY;
2763 }
deny_write_access(struct file * file)2764 static inline int deny_write_access(struct file *file)
2765 {
2766 	struct inode *inode = file_inode(file);
2767 	return atomic_dec_unless_positive(&inode->i_writecount) ? 0 : -ETXTBSY;
2768 }
put_write_access(struct inode * inode)2769 static inline void put_write_access(struct inode * inode)
2770 {
2771 	atomic_dec(&inode->i_writecount);
2772 }
allow_write_access(struct file * file)2773 static inline void allow_write_access(struct file *file)
2774 {
2775 	if (file)
2776 		atomic_inc(&file_inode(file)->i_writecount);
2777 }
2778 
2779 /*
2780  * Do not prevent write to executable file when watched by pre-content events.
2781  *
2782  * Note that FMODE_FSNOTIFY_HSM mode is set depending on pre-content watches at
2783  * the time of file open and remains constant for entire lifetime of the file,
2784  * so if pre-content watches are added post execution or removed before the end
2785  * of the execution, it will not cause i_writecount reference leak.
2786  */
exe_file_deny_write_access(struct file * exe_file)2787 static inline int exe_file_deny_write_access(struct file *exe_file)
2788 {
2789 	if (unlikely(FMODE_FSNOTIFY_HSM(exe_file->f_mode)))
2790 		return 0;
2791 	return deny_write_access(exe_file);
2792 }
exe_file_allow_write_access(struct file * exe_file)2793 static inline void exe_file_allow_write_access(struct file *exe_file)
2794 {
2795 	if (unlikely(!exe_file || FMODE_FSNOTIFY_HSM(exe_file->f_mode)))
2796 		return;
2797 	allow_write_access(exe_file);
2798 }
2799 
file_set_fsnotify_mode(struct file * file,fmode_t mode)2800 static inline void file_set_fsnotify_mode(struct file *file, fmode_t mode)
2801 {
2802 	file->f_mode &= ~FMODE_FSNOTIFY_MASK;
2803 	file->f_mode |= mode;
2804 }
2805 
inode_is_open_for_write(const struct inode * inode)2806 static inline bool inode_is_open_for_write(const struct inode *inode)
2807 {
2808 	return atomic_read(&inode->i_writecount) > 0;
2809 }
2810 
2811 #if defined(CONFIG_IMA) || defined(CONFIG_FILE_LOCKING)
i_readcount_dec(struct inode * inode)2812 static inline void i_readcount_dec(struct inode *inode)
2813 {
2814 	BUG_ON(atomic_dec_return(&inode->i_readcount) < 0);
2815 }
i_readcount_inc(struct inode * inode)2816 static inline void i_readcount_inc(struct inode *inode)
2817 {
2818 	atomic_inc(&inode->i_readcount);
2819 }
2820 #else
i_readcount_dec(struct inode * inode)2821 static inline void i_readcount_dec(struct inode *inode)
2822 {
2823 	return;
2824 }
i_readcount_inc(struct inode * inode)2825 static inline void i_readcount_inc(struct inode *inode)
2826 {
2827 	return;
2828 }
2829 #endif
2830 extern int do_pipe_flags(int *, int);
2831 
2832 extern ssize_t kernel_read(struct file *, void *, size_t, loff_t *);
2833 ssize_t __kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);
2834 extern ssize_t kernel_write(struct file *, const void *, size_t, loff_t *);
2835 extern ssize_t __kernel_write(struct file *, const void *, size_t, loff_t *);
2836 extern struct file * open_exec(const char *);
2837 
2838 /* fs/dcache.c -- generic fs support functions */
2839 extern bool is_subdir(struct dentry *, struct dentry *);
2840 extern bool path_is_under(const struct path *, const struct path *);
2841 
2842 extern char *file_path(struct file *, char *, int);
2843 
2844 /**
2845  * is_dot_dotdot - returns true only if @name is "." or ".."
2846  * @name: file name to check
2847  * @len: length of file name, in bytes
2848  */
is_dot_dotdot(const char * name,size_t len)2849 static inline bool is_dot_dotdot(const char *name, size_t len)
2850 {
2851 	return len && unlikely(name[0] == '.') &&
2852 		(len == 1 || (len == 2 && name[1] == '.'));
2853 }
2854 
2855 /**
2856  * name_contains_dotdot - check if a file name contains ".." path components
2857  * @name: File path string to check
2858  * Search for ".." surrounded by either '/' or start/end of string.
2859  */
name_contains_dotdot(const char * name)2860 static inline bool name_contains_dotdot(const char *name)
2861 {
2862 	size_t name_len;
2863 
2864 	name_len = strlen(name);
2865 	return strcmp(name, "..") == 0 ||
2866 	       strncmp(name, "../", 3) == 0 ||
2867 	       strstr(name, "/../") != NULL ||
2868 	       (name_len >= 3 && strcmp(name + name_len - 3, "/..") == 0);
2869 }
2870 
2871 #include <linux/err.h>
2872 
2873 /* needed for stackable file system support */
2874 extern loff_t default_llseek(struct file *file, loff_t offset, int whence);
2875 
2876 extern loff_t vfs_llseek(struct file *file, loff_t offset, int whence);
2877 
2878 extern int inode_init_always_gfp(struct super_block *, struct inode *, gfp_t);
inode_init_always(struct super_block * sb,struct inode * inode)2879 static inline int inode_init_always(struct super_block *sb, struct inode *inode)
2880 {
2881 	return inode_init_always_gfp(sb, inode, GFP_NOFS);
2882 }
2883 
2884 extern void inode_init_once(struct inode *);
2885 extern void address_space_init_once(struct address_space *mapping);
2886 extern struct inode * igrab(struct inode *);
2887 extern ino_t iunique(struct super_block *, ino_t);
2888 extern int inode_needs_sync(struct inode *inode);
2889 extern int inode_just_drop(struct inode *inode);
inode_generic_drop(struct inode * inode)2890 static inline int inode_generic_drop(struct inode *inode)
2891 {
2892 	return !inode->i_nlink || inode_unhashed(inode);
2893 }
2894 extern void d_mark_dontcache(struct inode *inode);
2895 
2896 extern struct inode *ilookup5_nowait(struct super_block *sb,
2897 		unsigned long hashval, int (*test)(struct inode *, void *),
2898 		void *data, bool *isnew);
2899 extern struct inode *ilookup5(struct super_block *sb, unsigned long hashval,
2900 		int (*test)(struct inode *, void *), void *data);
2901 extern struct inode *ilookup(struct super_block *sb, unsigned long ino);
2902 
2903 extern struct inode *inode_insert5(struct inode *inode, unsigned long hashval,
2904 		int (*test)(struct inode *, void *),
2905 		int (*set)(struct inode *, void *),
2906 		void *data);
2907 struct inode *iget5_locked(struct super_block *, unsigned long,
2908 			   int (*test)(struct inode *, void *),
2909 			   int (*set)(struct inode *, void *), void *);
2910 struct inode *iget5_locked_rcu(struct super_block *, unsigned long,
2911 			       int (*test)(struct inode *, void *),
2912 			       int (*set)(struct inode *, void *), void *);
2913 extern struct inode * iget_locked(struct super_block *, unsigned long);
2914 extern struct inode *find_inode_nowait(struct super_block *,
2915 				       unsigned long,
2916 				       int (*match)(struct inode *,
2917 						    unsigned long, void *),
2918 				       void *data);
2919 extern struct inode *find_inode_rcu(struct super_block *, unsigned long,
2920 				    int (*)(struct inode *, void *), void *);
2921 extern struct inode *find_inode_by_ino_rcu(struct super_block *, unsigned long);
2922 extern int insert_inode_locked4(struct inode *, unsigned long, int (*test)(struct inode *, void *), void *);
2923 extern int insert_inode_locked(struct inode *);
2924 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2925 extern void lockdep_annotate_inode_mutex_key(struct inode *inode);
2926 #else
lockdep_annotate_inode_mutex_key(struct inode * inode)2927 static inline void lockdep_annotate_inode_mutex_key(struct inode *inode) { };
2928 #endif
2929 extern void unlock_new_inode(struct inode *);
2930 extern void discard_new_inode(struct inode *);
2931 extern unsigned int get_next_ino(void);
2932 extern void evict_inodes(struct super_block *sb);
2933 void dump_mapping(const struct address_space *);
2934 
2935 /*
2936  * Userspace may rely on the inode number being non-zero. For example, glibc
2937  * simply ignores files with zero i_ino in unlink() and other places.
2938  *
2939  * As an additional complication, if userspace was compiled with
2940  * _FILE_OFFSET_BITS=32 on a 64-bit kernel we'll only end up reading out the
2941  * lower 32 bits, so we need to check that those aren't zero explicitly. With
2942  * _FILE_OFFSET_BITS=64, this may cause some harmless false-negatives, but
2943  * better safe than sorry.
2944  */
is_zero_ino(ino_t ino)2945 static inline bool is_zero_ino(ino_t ino)
2946 {
2947 	return (u32)ino == 0;
2948 }
2949 
__iget(struct inode * inode)2950 static inline void __iget(struct inode *inode)
2951 {
2952 	lockdep_assert_held(&inode->i_lock);
2953 	atomic_inc(&inode->i_count);
2954 }
2955 
2956 extern void iget_failed(struct inode *);
2957 extern void clear_inode(struct inode *);
2958 extern void __destroy_inode(struct inode *);
2959 struct inode *alloc_inode(struct super_block *sb);
new_inode_pseudo(struct super_block * sb)2960 static inline struct inode *new_inode_pseudo(struct super_block *sb)
2961 {
2962 	return alloc_inode(sb);
2963 }
2964 extern struct inode *new_inode(struct super_block *sb);
2965 extern void free_inode_nonrcu(struct inode *inode);
2966 extern int setattr_should_drop_suidgid(struct mnt_idmap *, struct inode *);
2967 extern int file_remove_privs(struct file *);
2968 int setattr_should_drop_sgid(struct mnt_idmap *idmap,
2969 			     const struct inode *inode);
2970 
2971 /*
2972  * This must be used for allocating filesystems specific inodes to set
2973  * up the inode reclaim context correctly.
2974  */
2975 #define alloc_inode_sb(_sb, _cache, _gfp) kmem_cache_alloc_lru(_cache, &_sb->s_inode_lru, _gfp)
2976 
2977 extern void __insert_inode_hash(struct inode *, unsigned long hashval);
insert_inode_hash(struct inode * inode)2978 static inline void insert_inode_hash(struct inode *inode)
2979 {
2980 	__insert_inode_hash(inode, inode->i_ino);
2981 }
2982 
2983 extern void __remove_inode_hash(struct inode *);
remove_inode_hash(struct inode * inode)2984 static inline void remove_inode_hash(struct inode *inode)
2985 {
2986 	if (!inode_unhashed(inode) && !hlist_fake(&inode->i_hash))
2987 		__remove_inode_hash(inode);
2988 }
2989 
2990 extern void inode_sb_list_add(struct inode *inode);
2991 extern void inode_lru_list_add(struct inode *inode);
2992 
2993 int generic_file_mmap(struct file *, struct vm_area_struct *);
2994 int generic_file_mmap_prepare(struct vm_area_desc *desc);
2995 int generic_file_readonly_mmap(struct file *, struct vm_area_struct *);
2996 int generic_file_readonly_mmap_prepare(struct vm_area_desc *desc);
2997 extern ssize_t generic_write_checks(struct kiocb *, struct iov_iter *);
2998 int generic_write_checks_count(struct kiocb *iocb, loff_t *count);
2999 extern int generic_write_check_limits(struct file *file, loff_t pos,
3000 		loff_t *count);
3001 extern int generic_file_rw_checks(struct file *file_in, struct file *file_out);
3002 ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *to,
3003 		ssize_t already_read);
3004 extern ssize_t generic_file_read_iter(struct kiocb *, struct iov_iter *);
3005 extern ssize_t __generic_file_write_iter(struct kiocb *, struct iov_iter *);
3006 extern ssize_t generic_file_write_iter(struct kiocb *, struct iov_iter *);
3007 extern ssize_t generic_file_direct_write(struct kiocb *, struct iov_iter *);
3008 ssize_t generic_perform_write(struct kiocb *, struct iov_iter *);
3009 ssize_t direct_write_fallback(struct kiocb *iocb, struct iov_iter *iter,
3010 		ssize_t direct_written, ssize_t buffered_written);
3011 
3012 ssize_t vfs_iter_read(struct file *file, struct iov_iter *iter, loff_t *ppos,
3013 		rwf_t flags);
3014 ssize_t vfs_iter_write(struct file *file, struct iov_iter *iter, loff_t *ppos,
3015 		rwf_t flags);
3016 ssize_t vfs_iocb_iter_read(struct file *file, struct kiocb *iocb,
3017 			   struct iov_iter *iter);
3018 ssize_t vfs_iocb_iter_write(struct file *file, struct kiocb *iocb,
3019 			    struct iov_iter *iter);
3020 
3021 /* fs/splice.c */
3022 ssize_t filemap_splice_read(struct file *in, loff_t *ppos,
3023 			    struct pipe_inode_info *pipe,
3024 			    size_t len, unsigned int flags);
3025 ssize_t copy_splice_read(struct file *in, loff_t *ppos,
3026 			 struct pipe_inode_info *pipe,
3027 			 size_t len, unsigned int flags);
3028 extern ssize_t iter_file_splice_write(struct pipe_inode_info *,
3029 		struct file *, loff_t *, size_t, unsigned int);
3030 
3031 
3032 extern void
3033 file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping);
3034 extern loff_t noop_llseek(struct file *file, loff_t offset, int whence);
3035 extern loff_t vfs_setpos(struct file *file, loff_t offset, loff_t maxsize);
3036 extern loff_t generic_file_llseek(struct file *file, loff_t offset, int whence);
3037 extern loff_t generic_file_llseek_size(struct file *file, loff_t offset,
3038 		int whence, loff_t maxsize, loff_t eof);
3039 loff_t generic_llseek_cookie(struct file *file, loff_t offset, int whence,
3040 			     u64 *cookie);
3041 extern loff_t fixed_size_llseek(struct file *file, loff_t offset,
3042 		int whence, loff_t size);
3043 extern loff_t no_seek_end_llseek_size(struct file *, loff_t, int, loff_t);
3044 extern loff_t no_seek_end_llseek(struct file *, loff_t, int);
3045 int rw_verify_area(int, struct file *, const loff_t *, size_t);
3046 extern int generic_file_open(struct inode * inode, struct file * filp);
3047 extern int nonseekable_open(struct inode * inode, struct file * filp);
3048 extern int stream_open(struct inode * inode, struct file * filp);
3049 
3050 #ifdef CONFIG_BLOCK
3051 typedef void (dio_submit_t)(struct bio *bio, struct inode *inode,
3052 			    loff_t file_offset);
3053 
3054 enum {
3055 	/* need locking between buffered and direct access */
3056 	DIO_LOCKING	= 0x01,
3057 
3058 	/* filesystem does not support filling holes */
3059 	DIO_SKIP_HOLES	= 0x02,
3060 };
3061 
3062 ssize_t __blockdev_direct_IO(struct kiocb *iocb, struct inode *inode,
3063 			     struct block_device *bdev, struct iov_iter *iter,
3064 			     get_block_t get_block,
3065 			     dio_iodone_t end_io,
3066 			     int flags);
3067 
blockdev_direct_IO(struct kiocb * iocb,struct inode * inode,struct iov_iter * iter,get_block_t get_block)3068 static inline ssize_t blockdev_direct_IO(struct kiocb *iocb,
3069 					 struct inode *inode,
3070 					 struct iov_iter *iter,
3071 					 get_block_t get_block)
3072 {
3073 	return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter,
3074 			get_block, NULL, DIO_LOCKING | DIO_SKIP_HOLES);
3075 }
3076 #endif
3077 
3078 bool inode_dio_finished(const struct inode *inode);
3079 void inode_dio_wait(struct inode *inode);
3080 void inode_dio_wait_interruptible(struct inode *inode);
3081 
3082 /**
3083  * inode_dio_begin - signal start of a direct I/O requests
3084  * @inode: inode the direct I/O happens on
3085  *
3086  * This is called once we've finished processing a direct I/O request,
3087  * and is used to wake up callers waiting for direct I/O to be quiesced.
3088  */
inode_dio_begin(struct inode * inode)3089 static inline void inode_dio_begin(struct inode *inode)
3090 {
3091 	atomic_inc(&inode->i_dio_count);
3092 }
3093 
3094 /**
3095  * inode_dio_end - signal finish of a direct I/O requests
3096  * @inode: inode the direct I/O happens on
3097  *
3098  * This is called once we've finished processing a direct I/O request,
3099  * and is used to wake up callers waiting for direct I/O to be quiesced.
3100  */
inode_dio_end(struct inode * inode)3101 static inline void inode_dio_end(struct inode *inode)
3102 {
3103 	if (atomic_dec_and_test(&inode->i_dio_count))
3104 		wake_up_var(&inode->i_dio_count);
3105 }
3106 
3107 extern void inode_set_flags(struct inode *inode, unsigned int flags,
3108 			    unsigned int mask);
3109 
3110 extern const struct file_operations generic_ro_fops;
3111 
3112 #define special_file(m) (S_ISCHR(m)||S_ISBLK(m)||S_ISFIFO(m)||S_ISSOCK(m))
3113 
3114 extern int readlink_copy(char __user *, int, const char *, int);
3115 extern int page_readlink(struct dentry *, char __user *, int);
3116 extern const char *page_get_link_raw(struct dentry *, struct inode *,
3117 				     struct delayed_call *);
3118 extern const char *page_get_link(struct dentry *, struct inode *,
3119 				 struct delayed_call *);
3120 extern void page_put_link(void *);
3121 extern int page_symlink(struct inode *inode, const char *symname, int len);
3122 extern const struct inode_operations page_symlink_inode_operations;
3123 extern void kfree_link(void *);
3124 void fill_mg_cmtime(struct kstat *stat, u32 request_mask, struct inode *inode);
3125 void generic_fillattr(struct mnt_idmap *, u32, struct inode *, struct kstat *);
3126 void generic_fill_statx_attr(struct inode *inode, struct kstat *stat);
3127 void generic_fill_statx_atomic_writes(struct kstat *stat,
3128 				      unsigned int unit_min,
3129 				      unsigned int unit_max,
3130 				      unsigned int unit_max_opt);
3131 extern int vfs_getattr_nosec(const struct path *, struct kstat *, u32, unsigned int);
3132 extern int vfs_getattr(const struct path *, struct kstat *, u32, unsigned int);
3133 void __inode_add_bytes(struct inode *inode, loff_t bytes);
3134 void inode_add_bytes(struct inode *inode, loff_t bytes);
3135 void __inode_sub_bytes(struct inode *inode, loff_t bytes);
3136 void inode_sub_bytes(struct inode *inode, loff_t bytes);
__inode_get_bytes(struct inode * inode)3137 static inline loff_t __inode_get_bytes(struct inode *inode)
3138 {
3139 	return (((loff_t)inode->i_blocks) << 9) + inode->i_bytes;
3140 }
3141 loff_t inode_get_bytes(struct inode *inode);
3142 void inode_set_bytes(struct inode *inode, loff_t bytes);
3143 const char *simple_get_link(struct dentry *, struct inode *,
3144 			    struct delayed_call *);
3145 extern const struct inode_operations simple_symlink_inode_operations;
3146 
3147 extern int iterate_dir(struct file *, struct dir_context *);
3148 
3149 int vfs_fstatat(int dfd, const char __user *filename, struct kstat *stat,
3150 		int flags);
3151 int vfs_fstat(int fd, struct kstat *stat);
3152 
vfs_stat(const char __user * filename,struct kstat * stat)3153 static inline int vfs_stat(const char __user *filename, struct kstat *stat)
3154 {
3155 	return vfs_fstatat(AT_FDCWD, filename, stat, 0);
3156 }
vfs_lstat(const char __user * name,struct kstat * stat)3157 static inline int vfs_lstat(const char __user *name, struct kstat *stat)
3158 {
3159 	return vfs_fstatat(AT_FDCWD, name, stat, AT_SYMLINK_NOFOLLOW);
3160 }
3161 
3162 extern const char *vfs_get_link(struct dentry *, struct delayed_call *);
3163 extern int vfs_readlink(struct dentry *, char __user *, int);
3164 
3165 extern struct file_system_type *get_filesystem(struct file_system_type *fs);
3166 extern void put_filesystem(struct file_system_type *fs);
3167 extern struct file_system_type *get_fs_type(const char *name);
3168 extern void drop_super(struct super_block *sb);
3169 extern void drop_super_exclusive(struct super_block *sb);
3170 extern void iterate_supers(void (*f)(struct super_block *, void *), void *arg);
3171 extern void iterate_supers_type(struct file_system_type *,
3172 			        void (*)(struct super_block *, void *), void *);
3173 void filesystems_freeze(bool freeze_all);
3174 void filesystems_thaw(void);
3175 
3176 extern int dcache_dir_open(struct inode *, struct file *);
3177 extern int dcache_dir_close(struct inode *, struct file *);
3178 extern loff_t dcache_dir_lseek(struct file *, loff_t, int);
3179 extern int dcache_readdir(struct file *, struct dir_context *);
3180 extern int simple_setattr(struct mnt_idmap *, struct dentry *,
3181 			  struct iattr *);
3182 extern int simple_getattr(struct mnt_idmap *, const struct path *,
3183 			  struct kstat *, u32, unsigned int);
3184 extern int simple_statfs(struct dentry *, struct kstatfs *);
3185 extern int simple_open(struct inode *inode, struct file *file);
3186 extern int simple_link(struct dentry *, struct inode *, struct dentry *);
3187 extern int simple_unlink(struct inode *, struct dentry *);
3188 extern int simple_rmdir(struct inode *, struct dentry *);
3189 void simple_rename_timestamp(struct inode *old_dir, struct dentry *old_dentry,
3190 			     struct inode *new_dir, struct dentry *new_dentry);
3191 extern int simple_rename_exchange(struct inode *old_dir, struct dentry *old_dentry,
3192 				  struct inode *new_dir, struct dentry *new_dentry);
3193 extern int simple_rename(struct mnt_idmap *, struct inode *,
3194 			 struct dentry *, struct inode *, struct dentry *,
3195 			 unsigned int);
3196 extern void simple_recursive_removal(struct dentry *,
3197                               void (*callback)(struct dentry *));
3198 extern void locked_recursive_removal(struct dentry *,
3199                               void (*callback)(struct dentry *));
3200 extern int noop_fsync(struct file *, loff_t, loff_t, int);
3201 extern ssize_t noop_direct_IO(struct kiocb *iocb, struct iov_iter *iter);
3202 extern int simple_empty(struct dentry *);
3203 extern int simple_write_begin(const struct kiocb *iocb,
3204 			      struct address_space *mapping,
3205 			      loff_t pos, unsigned len,
3206 			      struct folio **foliop, void **fsdata);
3207 extern const struct address_space_operations ram_aops;
3208 extern int always_delete_dentry(const struct dentry *);
3209 extern struct inode *alloc_anon_inode(struct super_block *);
3210 struct inode *anon_inode_make_secure_inode(struct super_block *sb, const char *name,
3211 					   const struct inode *context_inode);
3212 extern int simple_nosetlease(struct file *, int, struct file_lease **, void **);
3213 
3214 extern struct dentry *simple_lookup(struct inode *, struct dentry *, unsigned int flags);
3215 extern ssize_t generic_read_dir(struct file *, char __user *, size_t, loff_t *);
3216 extern const struct file_operations simple_dir_operations;
3217 extern const struct inode_operations simple_dir_inode_operations;
3218 extern void make_empty_dir_inode(struct inode *inode);
3219 extern bool is_empty_dir_inode(struct inode *inode);
3220 struct tree_descr { const char *name; const struct file_operations *ops; int mode; };
3221 struct dentry *d_alloc_name(struct dentry *, const char *);
3222 extern int simple_fill_super(struct super_block *, unsigned long,
3223 			     const struct tree_descr *);
3224 extern int simple_pin_fs(struct file_system_type *, struct vfsmount **mount, int *count);
3225 extern void simple_release_fs(struct vfsmount **mount, int *count);
3226 struct dentry *simple_start_creating(struct dentry *, const char *);
3227 
3228 extern ssize_t simple_read_from_buffer(void __user *to, size_t count,
3229 			loff_t *ppos, const void *from, size_t available);
3230 extern ssize_t simple_write_to_buffer(void *to, size_t available, loff_t *ppos,
3231 		const void __user *from, size_t count);
3232 
3233 struct offset_ctx {
3234 	struct maple_tree	mt;
3235 	unsigned long		next_offset;
3236 };
3237 
3238 void simple_offset_init(struct offset_ctx *octx);
3239 int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry);
3240 void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry);
3241 int simple_offset_rename(struct inode *old_dir, struct dentry *old_dentry,
3242 			 struct inode *new_dir, struct dentry *new_dentry);
3243 int simple_offset_rename_exchange(struct inode *old_dir,
3244 				  struct dentry *old_dentry,
3245 				  struct inode *new_dir,
3246 				  struct dentry *new_dentry);
3247 void simple_offset_destroy(struct offset_ctx *octx);
3248 
3249 extern const struct file_operations simple_offset_dir_operations;
3250 
3251 extern int __generic_file_fsync(struct file *, loff_t, loff_t, int);
3252 extern int generic_file_fsync(struct file *, loff_t, loff_t, int);
3253 
3254 extern int generic_check_addressable(unsigned, u64);
3255 
3256 extern void generic_set_sb_d_ops(struct super_block *sb);
3257 extern int generic_ci_match(const struct inode *parent,
3258 			    const struct qstr *name,
3259 			    const struct qstr *folded_name,
3260 			    const u8 *de_name, u32 de_name_len);
3261 
3262 #if IS_ENABLED(CONFIG_UNICODE)
3263 int generic_ci_d_hash(const struct dentry *dentry, struct qstr *str);
3264 int generic_ci_d_compare(const struct dentry *dentry, unsigned int len,
3265 			 const char *str, const struct qstr *name);
3266 
3267 /**
3268  * generic_ci_validate_strict_name - Check if a given name is suitable
3269  * for a directory
3270  *
3271  * This functions checks if the proposed filename is valid for the
3272  * parent directory. That means that only valid UTF-8 filenames will be
3273  * accepted for casefold directories from filesystems created with the
3274  * strict encoding flag.  That also means that any name will be
3275  * accepted for directories that doesn't have casefold enabled, or
3276  * aren't being strict with the encoding.
3277  *
3278  * @dir: inode of the directory where the new file will be created
3279  * @name: name of the new file
3280  *
3281  * Return:
3282  * * True: if the filename is suitable for this directory. It can be
3283  *   true if a given name is not suitable for a strict encoding
3284  *   directory, but the directory being used isn't strict
3285  * * False if the filename isn't suitable for this directory. This only
3286  *   happens when a directory is casefolded and the filesystem is strict
3287  *   about its encoding.
3288  */
generic_ci_validate_strict_name(struct inode * dir,const struct qstr * name)3289 static inline bool generic_ci_validate_strict_name(struct inode *dir,
3290 						   const struct qstr *name)
3291 {
3292 	if (!IS_CASEFOLDED(dir) || !sb_has_strict_encoding(dir->i_sb))
3293 		return true;
3294 
3295 	/*
3296 	 * A casefold dir must have a encoding set, unless the filesystem
3297 	 * is corrupted
3298 	 */
3299 	if (WARN_ON_ONCE(!dir->i_sb->s_encoding))
3300 		return true;
3301 
3302 	return !utf8_validate(dir->i_sb->s_encoding, name);
3303 }
3304 #else
generic_ci_validate_strict_name(struct inode * dir,const struct qstr * name)3305 static inline bool generic_ci_validate_strict_name(struct inode *dir,
3306 						   const struct qstr *name)
3307 {
3308 	return true;
3309 }
3310 #endif
3311 
3312 int may_setattr(struct mnt_idmap *idmap, struct inode *inode,
3313 		unsigned int ia_valid);
3314 int setattr_prepare(struct mnt_idmap *, struct dentry *, struct iattr *);
3315 extern int inode_newsize_ok(const struct inode *, loff_t offset);
3316 void setattr_copy(struct mnt_idmap *, struct inode *inode,
3317 		  const struct iattr *attr);
3318 
3319 extern int file_update_time(struct file *file);
3320 
file_is_dax(const struct file * file)3321 static inline bool file_is_dax(const struct file *file)
3322 {
3323 	return file && IS_DAX(file->f_mapping->host);
3324 }
3325 
vma_is_dax(const struct vm_area_struct * vma)3326 static inline bool vma_is_dax(const struct vm_area_struct *vma)
3327 {
3328 	return file_is_dax(vma->vm_file);
3329 }
3330 
vma_is_fsdax(struct vm_area_struct * vma)3331 static inline bool vma_is_fsdax(struct vm_area_struct *vma)
3332 {
3333 	struct inode *inode;
3334 
3335 	if (!IS_ENABLED(CONFIG_FS_DAX) || !vma->vm_file)
3336 		return false;
3337 	if (!vma_is_dax(vma))
3338 		return false;
3339 	inode = file_inode(vma->vm_file);
3340 	if (S_ISCHR(inode->i_mode))
3341 		return false; /* device-dax */
3342 	return true;
3343 }
3344 
iocb_flags(struct file * file)3345 static inline int iocb_flags(struct file *file)
3346 {
3347 	int res = 0;
3348 	if (file->f_flags & O_APPEND)
3349 		res |= IOCB_APPEND;
3350 	if (file->f_flags & O_DIRECT)
3351 		res |= IOCB_DIRECT;
3352 	if (file->f_flags & O_DSYNC)
3353 		res |= IOCB_DSYNC;
3354 	if (file->f_flags & __O_SYNC)
3355 		res |= IOCB_SYNC;
3356 	return res;
3357 }
3358 
kiocb_set_rw_flags(struct kiocb * ki,rwf_t flags,int rw_type)3359 static inline int kiocb_set_rw_flags(struct kiocb *ki, rwf_t flags,
3360 				     int rw_type)
3361 {
3362 	int kiocb_flags = 0;
3363 
3364 	/* make sure there's no overlap between RWF and private IOCB flags */
3365 	BUILD_BUG_ON((__force int) RWF_SUPPORTED & IOCB_EVENTFD);
3366 
3367 	if (!flags)
3368 		return 0;
3369 	if (unlikely(flags & ~RWF_SUPPORTED))
3370 		return -EOPNOTSUPP;
3371 	if (unlikely((flags & RWF_APPEND) && (flags & RWF_NOAPPEND)))
3372 		return -EINVAL;
3373 
3374 	if (flags & RWF_NOWAIT) {
3375 		if (!(ki->ki_filp->f_mode & FMODE_NOWAIT))
3376 			return -EOPNOTSUPP;
3377 	}
3378 	if (flags & RWF_ATOMIC) {
3379 		if (rw_type != WRITE)
3380 			return -EOPNOTSUPP;
3381 		if (!(ki->ki_filp->f_mode & FMODE_CAN_ATOMIC_WRITE))
3382 			return -EOPNOTSUPP;
3383 	}
3384 	if (flags & RWF_DONTCACHE) {
3385 		/* file system must support it */
3386 		if (!(ki->ki_filp->f_op->fop_flags & FOP_DONTCACHE))
3387 			return -EOPNOTSUPP;
3388 		/* DAX mappings not supported */
3389 		if (IS_DAX(ki->ki_filp->f_mapping->host))
3390 			return -EOPNOTSUPP;
3391 	}
3392 	kiocb_flags |= (__force int) (flags & RWF_SUPPORTED);
3393 	if (flags & RWF_SYNC)
3394 		kiocb_flags |= IOCB_DSYNC;
3395 
3396 	if ((flags & RWF_NOAPPEND) && (ki->ki_flags & IOCB_APPEND)) {
3397 		if (IS_APPEND(file_inode(ki->ki_filp)))
3398 			return -EPERM;
3399 		ki->ki_flags &= ~IOCB_APPEND;
3400 	}
3401 
3402 	ki->ki_flags |= kiocb_flags;
3403 	return 0;
3404 }
3405 
3406 /* Transaction based IO helpers */
3407 
3408 /*
3409  * An argresp is stored in an allocated page and holds the
3410  * size of the argument or response, along with its content
3411  */
3412 struct simple_transaction_argresp {
3413 	ssize_t size;
3414 	char data[];
3415 };
3416 
3417 #define SIMPLE_TRANSACTION_LIMIT (PAGE_SIZE - sizeof(struct simple_transaction_argresp))
3418 
3419 char *simple_transaction_get(struct file *file, const char __user *buf,
3420 				size_t size);
3421 ssize_t simple_transaction_read(struct file *file, char __user *buf,
3422 				size_t size, loff_t *pos);
3423 int simple_transaction_release(struct inode *inode, struct file *file);
3424 
3425 void simple_transaction_set(struct file *file, size_t n);
3426 
3427 /*
3428  * simple attribute files
3429  *
3430  * These attributes behave similar to those in sysfs:
3431  *
3432  * Writing to an attribute immediately sets a value, an open file can be
3433  * written to multiple times.
3434  *
3435  * Reading from an attribute creates a buffer from the value that might get
3436  * read with multiple read calls. When the attribute has been read
3437  * completely, no further read calls are possible until the file is opened
3438  * again.
3439  *
3440  * All attributes contain a text representation of a numeric value
3441  * that are accessed with the get() and set() functions.
3442  */
3443 #define DEFINE_SIMPLE_ATTRIBUTE_XSIGNED(__fops, __get, __set, __fmt, __is_signed)	\
3444 static int __fops ## _open(struct inode *inode, struct file *file)	\
3445 {									\
3446 	__simple_attr_check_format(__fmt, 0ull);			\
3447 	return simple_attr_open(inode, file, __get, __set, __fmt);	\
3448 }									\
3449 static const struct file_operations __fops = {				\
3450 	.owner	 = THIS_MODULE,						\
3451 	.open	 = __fops ## _open,					\
3452 	.release = simple_attr_release,					\
3453 	.read	 = simple_attr_read,					\
3454 	.write	 = (__is_signed) ? simple_attr_write_signed : simple_attr_write,	\
3455 	.llseek	 = generic_file_llseek,					\
3456 }
3457 
3458 #define DEFINE_SIMPLE_ATTRIBUTE(__fops, __get, __set, __fmt)		\
3459 	DEFINE_SIMPLE_ATTRIBUTE_XSIGNED(__fops, __get, __set, __fmt, false)
3460 
3461 #define DEFINE_SIMPLE_ATTRIBUTE_SIGNED(__fops, __get, __set, __fmt)	\
3462 	DEFINE_SIMPLE_ATTRIBUTE_XSIGNED(__fops, __get, __set, __fmt, true)
3463 
3464 static inline __printf(1, 2)
__simple_attr_check_format(const char * fmt,...)3465 void __simple_attr_check_format(const char *fmt, ...)
3466 {
3467 	/* don't do anything, just let the compiler check the arguments; */
3468 }
3469 
3470 int simple_attr_open(struct inode *inode, struct file *file,
3471 		     int (*get)(void *, u64 *), int (*set)(void *, u64),
3472 		     const char *fmt);
3473 int simple_attr_release(struct inode *inode, struct file *file);
3474 ssize_t simple_attr_read(struct file *file, char __user *buf,
3475 			 size_t len, loff_t *ppos);
3476 ssize_t simple_attr_write(struct file *file, const char __user *buf,
3477 			  size_t len, loff_t *ppos);
3478 ssize_t simple_attr_write_signed(struct file *file, const char __user *buf,
3479 				 size_t len, loff_t *ppos);
3480 
3481 struct ctl_table;
3482 int __init list_bdev_fs_names(char *buf, size_t size);
3483 
3484 #define __FMODE_EXEC		((__force int) FMODE_EXEC)
3485 
3486 #define ACC_MODE(x) ("\004\002\006\006"[(x)&O_ACCMODE])
3487 #define OPEN_FMODE(flag) ((__force fmode_t)((flag + 1) & O_ACCMODE))
3488 
is_sxid(umode_t mode)3489 static inline bool is_sxid(umode_t mode)
3490 {
3491 	return mode & (S_ISUID | S_ISGID);
3492 }
3493 
check_sticky(struct mnt_idmap * idmap,struct inode * dir,struct inode * inode)3494 static inline int check_sticky(struct mnt_idmap *idmap,
3495 			       struct inode *dir, struct inode *inode)
3496 {
3497 	if (!(dir->i_mode & S_ISVTX))
3498 		return 0;
3499 
3500 	return __check_sticky(idmap, dir, inode);
3501 }
3502 
inode_has_no_xattr(struct inode * inode)3503 static inline void inode_has_no_xattr(struct inode *inode)
3504 {
3505 	if (!is_sxid(inode->i_mode) && (inode->i_sb->s_flags & SB_NOSEC))
3506 		inode->i_flags |= S_NOSEC;
3507 }
3508 
is_root_inode(struct inode * inode)3509 static inline bool is_root_inode(struct inode *inode)
3510 {
3511 	return inode == inode->i_sb->s_root->d_inode;
3512 }
3513 
dir_emit(struct dir_context * ctx,const char * name,int namelen,u64 ino,unsigned type)3514 static inline bool dir_emit(struct dir_context *ctx,
3515 			    const char *name, int namelen,
3516 			    u64 ino, unsigned type)
3517 {
3518 	return ctx->actor(ctx, name, namelen, ctx->pos, ino, type);
3519 }
dir_emit_dot(struct file * file,struct dir_context * ctx)3520 static inline bool dir_emit_dot(struct file *file, struct dir_context *ctx)
3521 {
3522 	return ctx->actor(ctx, ".", 1, ctx->pos,
3523 			  file->f_path.dentry->d_inode->i_ino, DT_DIR);
3524 }
dir_emit_dotdot(struct file * file,struct dir_context * ctx)3525 static inline bool dir_emit_dotdot(struct file *file, struct dir_context *ctx)
3526 {
3527 	return ctx->actor(ctx, "..", 2, ctx->pos,
3528 			  d_parent_ino(file->f_path.dentry), DT_DIR);
3529 }
dir_emit_dots(struct file * file,struct dir_context * ctx)3530 static inline bool dir_emit_dots(struct file *file, struct dir_context *ctx)
3531 {
3532 	if (ctx->pos == 0) {
3533 		if (!dir_emit_dot(file, ctx))
3534 			return false;
3535 		ctx->pos = 1;
3536 	}
3537 	if (ctx->pos == 1) {
3538 		if (!dir_emit_dotdot(file, ctx))
3539 			return false;
3540 		ctx->pos = 2;
3541 	}
3542 	return true;
3543 }
dir_relax(struct inode * inode)3544 static inline bool dir_relax(struct inode *inode)
3545 {
3546 	inode_unlock(inode);
3547 	inode_lock(inode);
3548 	return !IS_DEADDIR(inode);
3549 }
3550 
dir_relax_shared(struct inode * inode)3551 static inline bool dir_relax_shared(struct inode *inode)
3552 {
3553 	inode_unlock_shared(inode);
3554 	inode_lock_shared(inode);
3555 	return !IS_DEADDIR(inode);
3556 }
3557 
3558 extern bool path_noexec(const struct path *path);
3559 extern void inode_nohighmem(struct inode *inode);
3560 
3561 /* mm/fadvise.c */
3562 extern int vfs_fadvise(struct file *file, loff_t offset, loff_t len,
3563 		       int advice);
3564 extern int generic_fadvise(struct file *file, loff_t offset, loff_t len,
3565 			   int advice);
3566 
vfs_empty_path(int dfd,const char __user * path)3567 static inline bool vfs_empty_path(int dfd, const char __user *path)
3568 {
3569 	char c;
3570 
3571 	if (dfd < 0)
3572 		return false;
3573 
3574 	/* We now allow NULL to be used for empty path. */
3575 	if (!path)
3576 		return true;
3577 
3578 	if (unlikely(get_user(c, path)))
3579 		return false;
3580 
3581 	return !c;
3582 }
3583 
3584 int generic_atomic_write_valid(struct kiocb *iocb, struct iov_iter *iter);
3585 
extensible_ioctl_valid(unsigned int cmd_a,unsigned int cmd_b,size_t min_size)3586 static inline bool extensible_ioctl_valid(unsigned int cmd_a,
3587 					  unsigned int cmd_b, size_t min_size)
3588 {
3589 	if (_IOC_DIR(cmd_a) != _IOC_DIR(cmd_b))
3590 		return false;
3591 	if (_IOC_TYPE(cmd_a) != _IOC_TYPE(cmd_b))
3592 		return false;
3593 	if (_IOC_NR(cmd_a) != _IOC_NR(cmd_b))
3594 		return false;
3595 	if (_IOC_SIZE(cmd_a) < min_size)
3596 		return false;
3597 	return true;
3598 }
3599 
3600 #endif /* _LINUX_FS_H */
3601