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