xref: /linux/fs/xfs/xfs_file.c (revision 5f5be6584cf5af0d70ee2fd40aa6264da18617ec)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs_platform.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_mount.h"
13 #include "xfs_inode.h"
14 #include "xfs_trans.h"
15 #include "xfs_inode_item.h"
16 #include "xfs_bmap.h"
17 #include "xfs_bmap_util.h"
18 #include "xfs_dir2.h"
19 #include "xfs_dir2_priv.h"
20 #include "xfs_ioctl.h"
21 #include "xfs_trace.h"
22 #include "xfs_log.h"
23 #include "xfs_icache.h"
24 #include "xfs_pnfs.h"
25 #include "xfs_iomap.h"
26 #include "xfs_reflink.h"
27 #include "xfs_file.h"
28 #include "xfs_ioend.h"
29 #include "xfs_zone_alloc.h"
30 #include "xfs_error.h"
31 #include "xfs_errortag.h"
32 
33 #include <linux/dax.h>
34 #include <linux/falloc.h>
35 #include <linux/backing-dev.h>
36 #include <linux/mman.h>
37 #include <linux/fadvise.h>
38 #include <linux/mount.h>
39 #include <linux/filelock.h>
40 #include <linux/bio-integrity.h>
41 
42 static const struct vm_operations_struct xfs_file_vm_ops;
43 
44 /*
45  * Decide if the given file range is aligned to the size of the fundamental
46  * allocation unit for the file.
47  */
48 bool
49 xfs_is_falloc_aligned(
50 	struct xfs_inode	*ip,
51 	loff_t			pos,
52 	long long int		len)
53 {
54 	unsigned int		alloc_unit = xfs_inode_alloc_unitsize(ip);
55 
56 	if (!is_power_of_2(alloc_unit))
57 		return isaligned_64(pos, alloc_unit) &&
58 		       isaligned_64(len, alloc_unit);
59 
60 	return !((pos | len) & (alloc_unit - 1));
61 }
62 
63 /*
64  * Fsync operations on directories are much simpler than on regular files,
65  * as there is no file data to flush, and thus also no need for explicit
66  * cache flush operations, and there are no non-transaction metadata updates
67  * on directories either.
68  */
69 STATIC int
70 xfs_dir_fsync(
71 	struct file		*file,
72 	loff_t			start,
73 	loff_t			end,
74 	int			datasync)
75 {
76 	struct xfs_inode	*ip = XFS_I(file->f_mapping->host);
77 
78 	trace_xfs_dir_fsync(ip);
79 	return xfs_log_force_inode(ip, false, NULL);
80 }
81 
82 STATIC int
83 xfs_file_fsync(
84 	struct file		*file,
85 	loff_t			start,
86 	loff_t			end,
87 	int			datasync)
88 {
89 	struct xfs_inode	*ip = XFS_I(file->f_mapping->host);
90 	int			log_flushed = 0;
91 	int			error;
92 
93 	trace_xfs_file_fsync(ip);
94 
95 	error = file_write_and_wait_range(file, start, end);
96 	if (error)
97 		return error;
98 
99 	if (xfs_is_shutdown(ip->i_mount))
100 		return -EIO;
101 
102 	xfs_iflags_clear(ip, XFS_ITRUNCATED);
103 
104 	/*
105 	 * If the inode has a log item attached, we must force the log up to the
106 	 * last LSN in which the inode was modified to ensure all metadata is
107 	 * persisted.  The log force will flush the caches for all devices
108 	 * before writing the log records unless it is a no-op because there are
109 	 * no modifications to this inode that need to be pushed out.
110 	 */
111 	if (ip->i_itemp) {
112 		error = xfs_log_force_inode(ip, datasync, &log_flushed);
113 		if (error)
114 			return error;
115 	}
116 
117 	/*
118 	 * If the log force was a no-op, we may still need to flush the
119 	 * file data target cache here. This can happen for fdatasync/O_DSYNC
120 	 * when no metadata needed to be committed.
121 	 *
122 	 * Use the inode's actual file data target rather than assuming the
123 	 * main data device.
124 	 */
125 	if (!log_flushed)
126 		return blkdev_issue_flush(xfs_inode_buftarg(ip)->bt_bdev);
127 	return 0;
128 }
129 
130 static int
131 xfs_ilock_iocb(
132 	struct kiocb		*iocb,
133 	unsigned int		lock_mode)
134 {
135 	struct xfs_inode	*ip = XFS_I(file_inode(iocb->ki_filp));
136 
137 	if (iocb->ki_flags & IOCB_NOWAIT) {
138 		if (!xfs_ilock_nowait(ip, lock_mode))
139 			return -EAGAIN;
140 	} else {
141 		xfs_ilock(ip, lock_mode);
142 	}
143 
144 	return 0;
145 }
146 
147 static int
148 xfs_ilock_iocb_for_write(
149 	struct kiocb		*iocb,
150 	unsigned int		*lock_mode)
151 {
152 	ssize_t			ret;
153 	struct xfs_inode	*ip = XFS_I(file_inode(iocb->ki_filp));
154 
155 	ret = xfs_ilock_iocb(iocb, *lock_mode);
156 	if (ret)
157 		return ret;
158 
159 	/*
160 	 * If a reflink remap is in progress we always need to take the iolock
161 	 * exclusively to wait for it to finish.
162 	 */
163 	if (*lock_mode == XFS_IOLOCK_SHARED &&
164 	    xfs_iflags_test(ip, XFS_IREMAPPING)) {
165 		xfs_iunlock(ip, *lock_mode);
166 		*lock_mode = XFS_IOLOCK_EXCL;
167 		return xfs_ilock_iocb(iocb, *lock_mode);
168 	}
169 
170 	return 0;
171 }
172 
173 /*
174  * Bounce buffering dio reads need a user context to copy back the data.
175  * Use an ioend to provide that.
176  */
177 static void
178 xfs_dio_read_bounce_submit_io(
179 	const struct iomap_iter	*iter,
180 	struct bio		*bio,
181 	loff_t			file_offset)
182 {
183 	xfs_ioend_submit_read(iter->inode, bio, file_offset,
184 			iomap_ioend_flags(&iter->iomap) | IOMAP_IOEND_DIRECT);
185 }
186 
187 static const struct iomap_dio_ops xfs_dio_read_bounce_ops = {
188 	.submit_io	= xfs_dio_read_bounce_submit_io,
189 	.bio_set	= &iomap_ioend_bioset,
190 };
191 
192 STATIC ssize_t
193 xfs_file_dio_read(
194 	struct kiocb		*iocb,
195 	struct iov_iter		*to)
196 {
197 	struct xfs_inode	*ip = XFS_I(file_inode(iocb->ki_filp));
198 	ssize_t			ret;
199 
200 	trace_xfs_file_direct_read(iocb, to);
201 
202 	if (!iov_iter_count(to))
203 		return 0; /* skip atime */
204 
205 	file_accessed(iocb->ki_filp);
206 
207 	ret = xfs_ilock_iocb(iocb, XFS_IOLOCK_SHARED);
208 	if (ret)
209 		return ret;
210 	if (mapping_stable_writes(iocb->ki_filp->f_mapping)) {
211 		ret = iomap_dio_rw(iocb, to, xfs_read_iomap_next,
212 				&xfs_dio_read_bounce_ops, 0, NULL, 0);
213 	} else {
214 		ret = iomap_dio_read_simple(iocb, to, xfs_read_iomap_begin);
215 		if (ret == -ENOTBLK)
216 			ret = iomap_dio_rw(iocb, to, xfs_read_iomap_next, NULL,
217 					0, NULL, 0);
218 	}
219 	xfs_iunlock(ip, XFS_IOLOCK_SHARED);
220 
221 	return ret;
222 }
223 
224 static noinline ssize_t
225 xfs_file_dax_read(
226 	struct kiocb		*iocb,
227 	struct iov_iter		*to)
228 {
229 	struct xfs_inode	*ip = XFS_I(iocb->ki_filp->f_mapping->host);
230 	ssize_t			ret = 0;
231 
232 	trace_xfs_file_dax_read(iocb, to);
233 
234 	if (!iov_iter_count(to))
235 		return 0; /* skip atime */
236 
237 	ret = xfs_ilock_iocb(iocb, XFS_IOLOCK_SHARED);
238 	if (ret)
239 		return ret;
240 	ret = dax_iomap_rw(iocb, to, xfs_read_iomap_next);
241 	xfs_iunlock(ip, XFS_IOLOCK_SHARED);
242 
243 	file_accessed(iocb->ki_filp);
244 	return ret;
245 }
246 
247 STATIC ssize_t
248 xfs_file_buffered_read(
249 	struct kiocb		*iocb,
250 	struct iov_iter		*to)
251 {
252 	struct xfs_inode	*ip = XFS_I(file_inode(iocb->ki_filp));
253 	ssize_t			ret;
254 
255 	trace_xfs_file_buffered_read(iocb, to);
256 
257 	ret = xfs_ilock_iocb(iocb, XFS_IOLOCK_SHARED);
258 	if (ret)
259 		return ret;
260 	ret = generic_file_read_iter(iocb, to);
261 	xfs_iunlock(ip, XFS_IOLOCK_SHARED);
262 
263 	return ret;
264 }
265 
266 STATIC ssize_t
267 xfs_file_read_iter(
268 	struct kiocb		*iocb,
269 	struct iov_iter		*to)
270 {
271 	struct inode		*inode = file_inode(iocb->ki_filp);
272 	struct xfs_mount	*mp = XFS_I(inode)->i_mount;
273 	ssize_t			ret = 0;
274 
275 	XFS_STATS_INC(mp, xs_read_calls);
276 
277 	if (xfs_is_shutdown(mp))
278 		return -EIO;
279 
280 	if (IS_DAX(inode))
281 		ret = xfs_file_dax_read(iocb, to);
282 	else if (iocb->ki_flags & IOCB_DIRECT)
283 		ret = xfs_file_dio_read(iocb, to);
284 	else
285 		ret = xfs_file_buffered_read(iocb, to);
286 
287 	if (ret > 0)
288 		XFS_STATS_ADD(mp, xs_read_bytes, ret);
289 	return ret;
290 }
291 
292 STATIC ssize_t
293 xfs_file_splice_read(
294 	struct file		*in,
295 	loff_t			*ppos,
296 	struct pipe_inode_info	*pipe,
297 	size_t			len,
298 	unsigned int		flags)
299 {
300 	struct inode		*inode = file_inode(in);
301 	struct xfs_inode	*ip = XFS_I(inode);
302 	struct xfs_mount	*mp = ip->i_mount;
303 	ssize_t			ret = 0;
304 
305 	XFS_STATS_INC(mp, xs_read_calls);
306 
307 	if (xfs_is_shutdown(mp))
308 		return -EIO;
309 
310 	trace_xfs_file_splice_read(ip, *ppos, len);
311 
312 	xfs_ilock(ip, XFS_IOLOCK_SHARED);
313 	ret = filemap_splice_read(in, ppos, pipe, len, flags);
314 	xfs_iunlock(ip, XFS_IOLOCK_SHARED);
315 	if (ret > 0)
316 		XFS_STATS_ADD(mp, xs_read_bytes, ret);
317 	return ret;
318 }
319 
320 /*
321  * Take care of zeroing post-EOF blocks when they might exist.
322  *
323  * Returns 0 if successfully, a negative error for a failure, or 1 if this
324  * function dropped the iolock and reacquired it exclusively and the caller
325  * needs to restart the write sanity checks.
326  */
327 static ssize_t
328 xfs_file_write_zero_eof(
329 	struct kiocb		*iocb,
330 	struct iov_iter		*from,
331 	unsigned int		*iolock,
332 	size_t			count,
333 	bool			*drained_dio,
334 	struct xfs_zone_alloc_ctx *ac)
335 {
336 	struct xfs_inode	*ip = XFS_I(iocb->ki_filp->f_mapping->host);
337 	loff_t			isize;
338 	int			error;
339 
340 	/*
341 	 * We need to serialise against EOF updates that occur in IO completions
342 	 * here. We want to make sure that nobody is changing the size while
343 	 * we do this check until we have placed an IO barrier (i.e. hold
344 	 * XFS_IOLOCK_EXCL) that prevents new IO from being dispatched.  The
345 	 * spinlock effectively forms a memory barrier once we have
346 	 * XFS_IOLOCK_EXCL so we are guaranteed to see the latest EOF value and
347 	 * hence be able to correctly determine if we need to run zeroing.
348 	 */
349 	spin_lock(&ip->i_flags_lock);
350 	isize = i_size_read(VFS_I(ip));
351 	if (iocb->ki_pos <= isize) {
352 		spin_unlock(&ip->i_flags_lock);
353 		return 0;
354 	}
355 	spin_unlock(&ip->i_flags_lock);
356 
357 	if (iocb->ki_flags & IOCB_NOWAIT)
358 		return -EAGAIN;
359 
360 	if (!*drained_dio) {
361 		/*
362 		 * If zeroing is needed and we are currently holding the iolock
363 		 * shared, we need to update it to exclusive which implies
364 		 * having to redo all checks before.
365 		 */
366 		if (*iolock == XFS_IOLOCK_SHARED) {
367 			xfs_iunlock(ip, *iolock);
368 			*iolock = XFS_IOLOCK_EXCL;
369 			xfs_ilock(ip, *iolock);
370 			iov_iter_reexpand(from, count);
371 		}
372 
373 		/*
374 		 * We now have an IO submission barrier in place, but AIO can do
375 		 * EOF updates during IO completion and hence we now need to
376 		 * wait for all of them to drain.  Non-AIO DIO will have drained
377 		 * before we are given the XFS_IOLOCK_EXCL, and so for most
378 		 * cases this wait is a no-op.
379 		 */
380 		inode_dio_wait(VFS_I(ip));
381 		*drained_dio = true;
382 		return 1;
383 	}
384 
385 	trace_xfs_zero_eof(ip, isize, iocb->ki_pos - isize);
386 
387 	xfs_ilock(ip, XFS_MMAPLOCK_EXCL);
388 	error = xfs_zero_range(ip, isize, iocb->ki_pos - isize, ac, NULL);
389 	xfs_iunlock(ip, XFS_MMAPLOCK_EXCL);
390 
391 	return error;
392 }
393 
394 /*
395  * Common pre-write limit and setup checks.
396  *
397  * Called with the iolock held either shared and exclusive according to
398  * @iolock, and returns with it held.  Might upgrade the iolock to exclusive
399  * if called for a direct write beyond i_size.
400  */
401 STATIC ssize_t
402 xfs_file_write_checks(
403 	struct kiocb		*iocb,
404 	struct iov_iter		*from,
405 	unsigned int		*iolock,
406 	struct xfs_zone_alloc_ctx *ac)
407 {
408 	struct inode		*inode = iocb->ki_filp->f_mapping->host;
409 	size_t			count = iov_iter_count(from);
410 	bool			drained_dio = false;
411 	ssize_t			error;
412 
413 restart:
414 	error = generic_write_checks(iocb, from);
415 	if (error <= 0)
416 		return error;
417 
418 	if (iocb->ki_flags & IOCB_NOWAIT) {
419 		error = break_layout(inode, false);
420 		if (error == -EWOULDBLOCK)
421 			error = -EAGAIN;
422 	} else {
423 		error = xfs_break_layouts(inode, iolock, BREAK_WRITE);
424 	}
425 
426 	if (error)
427 		return error;
428 
429 	/*
430 	 * For changing security info in file_remove_privs() we need i_rwsem
431 	 * exclusively.
432 	 */
433 	if (*iolock == XFS_IOLOCK_SHARED && !IS_NOSEC(inode)) {
434 		xfs_iunlock(XFS_I(inode), *iolock);
435 		*iolock = XFS_IOLOCK_EXCL;
436 		error = xfs_ilock_iocb(iocb, *iolock);
437 		if (error) {
438 			*iolock = 0;
439 			return error;
440 		}
441 		goto restart;
442 	}
443 
444 	/*
445 	 * If the offset is beyond the size of the file, we need to zero all
446 	 * blocks that fall between the existing EOF and the start of this
447 	 * write.
448 	 *
449 	 * We can do an unlocked check for i_size here safely as I/O completion
450 	 * can only extend EOF.  Truncate is locked out at this point, so the
451 	 * EOF can not move backwards, only forwards. Hence we only need to take
452 	 * the slow path when we are at or beyond the current EOF.
453 	 */
454 	if (iocb->ki_pos > i_size_read(inode)) {
455 		error = xfs_file_write_zero_eof(iocb, from, iolock, count,
456 				&drained_dio, ac);
457 		if (error == 1)
458 			goto restart;
459 		if (error)
460 			return error;
461 	}
462 
463 	return kiocb_modified(iocb);
464 }
465 
466 static ssize_t
467 xfs_zoned_write_space_reserve(
468 	struct xfs_mount		*mp,
469 	struct kiocb			*iocb,
470 	struct iov_iter			*from,
471 	unsigned int			flags,
472 	struct xfs_zone_alloc_ctx	*ac)
473 {
474 	loff_t				count = iov_iter_count(from);
475 	int				error;
476 
477 	if (iocb->ki_flags & IOCB_NOWAIT)
478 		flags |= XFS_ZR_NOWAIT;
479 
480 	/*
481 	 * Check the rlimit and LFS boundary first so that we don't over-reserve
482 	 * by possibly a lot.
483 	 *
484 	 * The generic write path will redo this check later, and it might have
485 	 * changed by then.  If it got expanded we'll stick to our earlier
486 	 * smaller limit, and if it is decreased the new smaller limit will be
487 	 * used and our extra space reservation will be returned after finishing
488 	 * the write.
489 	 */
490 	error = generic_write_check_limits(iocb->ki_filp, iocb->ki_pos, &count);
491 	if (error)
492 		return error;
493 
494 	/*
495 	 * Sloppily round up count to file system blocks.
496 	 *
497 	 * This will often reserve an extra block, but that avoids having to look
498 	 * at the start offset, which isn't stable for O_APPEND until taking the
499 	 * iolock.  Also we need to reserve a block each for zeroing the old
500 	 * EOF block and the new start block if they are unaligned.
501 	 *
502 	 * Any remaining block will be returned after the write.
503 	 */
504 	return xfs_zoned_space_reserve(mp, XFS_B_TO_FSB(mp, count) + 1 + 2,
505 			flags, ac);
506 }
507 
508 /*
509  * We need to lock the test/set EOF update as we can be racing with
510  * other IO completions here to update the EOF. Failing to serialise
511  * here can result in EOF moving backwards and Bad Things Happen when
512  * that occurs.
513  *
514  * As IO completion only ever extends EOF, we can do an unlocked check
515  * here to avoid taking the spinlock. If we land within the current EOF,
516  * then we do not need to do an extending update at all, and we don't
517  * need to take the lock to check this. If we race with an update moving
518  * EOF, then we'll either still be beyond EOF and need to take the lock,
519  * or we'll be within EOF and we don't need to take it at all.
520  */
521 static int
522 xfs_dio_endio_set_isize(
523 	struct inode		*inode,
524 	loff_t			offset,
525 	ssize_t			size)
526 {
527 	struct xfs_inode	*ip = XFS_I(inode);
528 
529 	if (offset + size <= i_size_read(inode))
530 		return 0;
531 
532 	spin_lock(&ip->i_flags_lock);
533 	if (offset + size <= i_size_read(inode)) {
534 		spin_unlock(&ip->i_flags_lock);
535 		return 0;
536 	}
537 
538 	i_size_write(inode, offset + size);
539 	spin_unlock(&ip->i_flags_lock);
540 
541 	return xfs_setfilesize(ip, offset, size);
542 }
543 
544 static int
545 xfs_zoned_dio_write_end_io(
546 	struct kiocb		*iocb,
547 	ssize_t			size,
548 	int			error,
549 	unsigned		flags)
550 {
551 	struct inode		*inode = file_inode(iocb->ki_filp);
552 	struct xfs_inode	*ip = XFS_I(inode);
553 	unsigned int		nofs_flag;
554 
555 	ASSERT(!(flags & (IOMAP_DIO_UNWRITTEN | IOMAP_DIO_COW)));
556 
557 	trace_xfs_end_io_direct_write(ip, iocb->ki_pos, size);
558 
559 	if (xfs_is_shutdown(ip->i_mount))
560 		return -EIO;
561 
562 	if (error || !size)
563 		return error;
564 
565 	XFS_STATS_ADD(ip->i_mount, xs_write_bytes, size);
566 
567 	nofs_flag = memalloc_nofs_save();
568 	error = xfs_dio_endio_set_isize(inode, iocb->ki_pos, size);
569 	memalloc_nofs_restore(nofs_flag);
570 
571 	return error;
572 }
573 
574 static int
575 xfs_dio_write_end_io(
576 	struct kiocb		*iocb,
577 	ssize_t			size,
578 	int			error,
579 	unsigned		flags)
580 {
581 	struct inode		*inode = file_inode(iocb->ki_filp);
582 	struct xfs_inode	*ip = XFS_I(inode);
583 	loff_t			offset = iocb->ki_pos;
584 	unsigned int		nofs_flag;
585 
586 	ASSERT(!xfs_is_zoned_inode(ip));
587 
588 	trace_xfs_end_io_direct_write(ip, offset, size);
589 
590 	if (xfs_is_shutdown(ip->i_mount))
591 		return -EIO;
592 
593 	if (error)
594 		return error;
595 	if (!size)
596 		return 0;
597 
598 	/*
599 	 * Capture amount written on completion as we can't reliably account
600 	 * for it on submission.
601 	 */
602 	XFS_STATS_ADD(ip->i_mount, xs_write_bytes, size);
603 
604 	/*
605 	 * We can allocate memory here while doing writeback on behalf of
606 	 * memory reclaim.  To avoid memory allocation deadlocks set the
607 	 * task-wide nofs context for the following operations.
608 	 */
609 	nofs_flag = memalloc_nofs_save();
610 
611 	if (flags & IOMAP_DIO_COW) {
612 		if (iocb->ki_flags & IOCB_ATOMIC)
613 			error = xfs_reflink_end_atomic_cow(ip, offset, size);
614 		else
615 			error = xfs_reflink_end_cow(ip, offset, size);
616 		if (error)
617 			goto out;
618 	}
619 
620 	/*
621 	 * Unwritten conversion updates the in-core isize after extent
622 	 * conversion but before updating the on-disk size. Updating isize any
623 	 * earlier allows a racing dio read to find unwritten extents before
624 	 * they are converted.
625 	 */
626 	if (flags & IOMAP_DIO_UNWRITTEN) {
627 		error = xfs_iomap_write_unwritten(ip, offset, size, true, 0);
628 		goto out;
629 	}
630 
631 	/*
632 	 * We need to update the in-core inode size here so that we don't end up
633 	 * with the on-disk inode size being outside the in-core inode size. We
634 	 * have no other method of updating EOF for AIO, so always do it here
635 	 * if necessary.
636 	 */
637 	error = xfs_dio_endio_set_isize(inode, offset, size);
638 
639 out:
640 	memalloc_nofs_restore(nofs_flag);
641 	return error;
642 }
643 
644 static const struct iomap_dio_ops xfs_dio_write_ops = {
645 	.end_io		= xfs_dio_write_end_io,
646 };
647 
648 static void
649 xfs_dio_zoned_submit_io(
650 	const struct iomap_iter	*iter,
651 	struct bio		*bio,
652 	loff_t			file_offset)
653 {
654 	struct xfs_mount	*mp = XFS_I(iter->inode)->i_mount;
655 	struct xfs_zone_alloc_ctx *ac = iter->private;
656 	xfs_filblks_t		count_fsb;
657 	struct iomap_ioend	*ioend;
658 
659 	count_fsb = XFS_B_TO_FSB(mp, bio->bi_iter.bi_size);
660 	if (count_fsb > ac->reserved_blocks) {
661 		xfs_err(mp,
662 "allocation (%lld) larger than reservation (%lld).",
663 			count_fsb, ac->reserved_blocks);
664 		xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
665 		bio_io_error(bio);
666 		return;
667 	}
668 	ac->reserved_blocks -= count_fsb;
669 
670 	bio->bi_end_io = xfs_end_bio;
671 	ioend = iomap_init_ioend(iter->inode, bio, file_offset,
672 			iomap_ioend_flags(&iter->iomap) | IOMAP_IOEND_DIRECT);
673 	xfs_zone_alloc_and_submit(ioend, &ac->open_zone);
674 }
675 
676 static const struct iomap_dio_ops xfs_dio_zoned_write_ops = {
677 	.bio_set	= &iomap_ioend_bioset,
678 	.submit_io	= xfs_dio_zoned_submit_io,
679 	.end_io		= xfs_zoned_dio_write_end_io,
680 };
681 
682 /*
683  * Handle block aligned direct I/O writes.
684  */
685 static noinline ssize_t
686 xfs_file_dio_write_aligned(
687 	struct xfs_inode	*ip,
688 	struct kiocb		*iocb,
689 	struct iov_iter		*from,
690 	iomap_iter_next_fn	next,
691 	const struct iomap_dio_ops *dops,
692 	struct xfs_zone_alloc_ctx *ac)
693 {
694 	unsigned int		iolock = XFS_IOLOCK_SHARED;
695 	unsigned int		dio_flags = 0;
696 	ssize_t			ret;
697 
698 	/*
699 	 * For always COW inodes, each bio must be aligned to the file system
700 	 * block size and not just the device sector size because we need to
701 	 * allocate a block-aligned amount of space for each write.
702 	 */
703 	if (xfs_is_always_cow_inode(ip))
704 		dio_flags |= IOMAP_DIO_FSBLOCK_ALIGNED;
705 
706 	ret = xfs_ilock_iocb_for_write(iocb, &iolock);
707 	if (ret)
708 		return ret;
709 	ret = xfs_file_write_checks(iocb, from, &iolock, ac);
710 	if (ret)
711 		goto out_unlock;
712 
713 	/*
714 	 * We don't need to hold the IOLOCK exclusively across the IO, so demote
715 	 * the iolock back to shared if we had to take the exclusive lock in
716 	 * xfs_file_write_checks() for other reasons.
717 	 */
718 	if (iolock == XFS_IOLOCK_EXCL) {
719 		xfs_ilock_demote(ip, XFS_IOLOCK_EXCL);
720 		iolock = XFS_IOLOCK_SHARED;
721 	}
722 	if (mapping_stable_writes(iocb->ki_filp->f_mapping))
723 		dio_flags |= IOMAP_DIO_BOUNCE;
724 	trace_xfs_file_direct_write(iocb, from);
725 	ret = iomap_dio_rw(iocb, from, next, dops, dio_flags, ac, 0);
726 out_unlock:
727 	if (iolock)
728 		xfs_iunlock(ip, iolock);
729 	return ret;
730 }
731 
732 /*
733  * Handle block aligned direct I/O writes to zoned devices.
734  */
735 static noinline ssize_t
736 xfs_file_dio_write_zoned(
737 	struct xfs_inode	*ip,
738 	struct kiocb		*iocb,
739 	struct iov_iter		*from)
740 {
741 	struct xfs_zone_alloc_ctx ac = { };
742 	ssize_t			ret;
743 
744 	ret = xfs_zoned_write_space_reserve(ip->i_mount, iocb, from, 0, &ac);
745 	if (ret < 0)
746 		return ret;
747 	ret = xfs_file_dio_write_aligned(ip, iocb, from,
748 			xfs_zoned_direct_write_iomap_next,
749 			&xfs_dio_zoned_write_ops, &ac);
750 	xfs_zoned_space_unreserve(ip->i_mount, &ac);
751 	return ret;
752 }
753 
754 /*
755  * Handle block atomic writes
756  *
757  * Two methods of atomic writes are supported:
758  * - REQ_ATOMIC-based, which would typically use some form of HW offload in the
759  *   disk
760  * - COW-based, which uses a COW fork as a staging extent for data updates
761  *   before atomically updating extent mappings for the range being written
762  *
763  */
764 static noinline ssize_t
765 xfs_file_dio_write_atomic(
766 	struct xfs_inode	*ip,
767 	struct kiocb		*iocb,
768 	struct iov_iter		*from)
769 {
770 	unsigned int		iolock = XFS_IOLOCK_SHARED;
771 	ssize_t			ret, ocount = iov_iter_count(from);
772 	unsigned int		dio_flags = 0;
773 	iomap_iter_next_fn	next;
774 
775 	/*
776 	 * HW offload should be faster, so try that first if it is already
777 	 * known that the write length is not too large.
778 	 */
779 	if (ocount > xfs_inode_buftarg(ip)->bt_awu_max)
780 		next = xfs_atomic_write_cow_iomap_next;
781 	else
782 		next = xfs_direct_write_iomap_next;
783 
784 retry:
785 	ret = xfs_ilock_iocb_for_write(iocb, &iolock);
786 	if (ret)
787 		return ret;
788 
789 	ret = xfs_file_write_checks(iocb, from, &iolock, NULL);
790 	if (ret)
791 		goto out_unlock;
792 
793 	/* Demote similar to xfs_file_dio_write_aligned() */
794 	if (iolock == XFS_IOLOCK_EXCL) {
795 		xfs_ilock_demote(ip, XFS_IOLOCK_EXCL);
796 		iolock = XFS_IOLOCK_SHARED;
797 	}
798 
799 	trace_xfs_file_direct_write(iocb, from);
800 	if (mapping_stable_writes(iocb->ki_filp->f_mapping))
801 		dio_flags |= IOMAP_DIO_BOUNCE;
802 	ret = iomap_dio_rw(iocb, from, next, &xfs_dio_write_ops, dio_flags,
803 			NULL, 0);
804 
805 	/*
806 	 * The retry mechanism is based on the iomap_iter_next_fn callback
807 	 * returning -ENOPROTOOPT, which would be when the REQ_ATOMIC-based
808 	 * write is not possible. The REQ_ATOMIC-based method is typically not
809 	 * possible if the write spans multiple extents or the disk blocks are
810 	 * misaligned.
811 	 */
812 	if (ret == -ENOPROTOOPT && next == xfs_direct_write_iomap_next) {
813 		xfs_iunlock(ip, iolock);
814 		next = xfs_atomic_write_cow_iomap_next;
815 		goto retry;
816 	}
817 
818 out_unlock:
819 	if (iolock)
820 		xfs_iunlock(ip, iolock);
821 	return ret;
822 }
823 
824 /*
825  * Handle block unaligned direct I/O writes
826  *
827  * In most cases direct I/O writes will be done holding IOLOCK_SHARED, allowing
828  * them to be done in parallel with reads and other direct I/O writes.  However,
829  * if the I/O is not aligned to filesystem blocks, the direct I/O layer may need
830  * to do sub-block zeroing and that requires serialisation against other direct
831  * I/O to the same block.  In this case we need to serialise the submission of
832  * the unaligned I/O so that we don't get racing block zeroing in the dio layer.
833  * In the case where sub-block zeroing is not required, we can do concurrent
834  * sub-block dios to the same block successfully.
835  *
836  * Optimistically submit the I/O using the shared lock first, but use the
837  * IOMAP_DIO_OVERWRITE_ONLY flag to tell the lower layers to return -EAGAIN
838  * if block allocation or partial block zeroing would be required.  In that case
839  * we try again with the exclusive lock.
840  */
841 static noinline ssize_t
842 xfs_file_dio_write_unaligned(
843 	struct xfs_inode	*ip,
844 	struct kiocb		*iocb,
845 	struct iov_iter		*from)
846 {
847 	size_t			isize = i_size_read(VFS_I(ip));
848 	size_t			count = iov_iter_count(from);
849 	unsigned int		iolock = XFS_IOLOCK_SHARED;
850 	unsigned int		flags = IOMAP_DIO_OVERWRITE_ONLY;
851 	ssize_t			ret;
852 
853 	/*
854 	 * Extending writes need exclusivity because of the sub-block zeroing
855 	 * that the DIO code always does for partial tail blocks beyond EOF, so
856 	 * don't even bother trying the fast path in this case.
857 	 */
858 	if (iocb->ki_pos > isize || iocb->ki_pos + count >= isize) {
859 		if (iocb->ki_flags & IOCB_NOWAIT)
860 			return -EAGAIN;
861 retry_exclusive:
862 		iolock = XFS_IOLOCK_EXCL;
863 		flags = IOMAP_DIO_FORCE_WAIT;
864 	}
865 
866 	ret = xfs_ilock_iocb_for_write(iocb, &iolock);
867 	if (ret)
868 		return ret;
869 
870 	/*
871 	 * We can't properly handle unaligned direct I/O to reflink files yet,
872 	 * as we can't unshare a partial block.
873 	 */
874 	if (xfs_is_cow_inode(ip)) {
875 		trace_xfs_reflink_bounce_dio_write(iocb, from);
876 		ret = -ENOTBLK;
877 		goto out_unlock;
878 	}
879 
880 	ret = xfs_file_write_checks(iocb, from, &iolock, NULL);
881 	if (ret)
882 		goto out_unlock;
883 
884 	/*
885 	 * If we are doing exclusive unaligned I/O, this must be the only I/O
886 	 * in-flight.  Otherwise we risk data corruption due to unwritten extent
887 	 * conversions from the AIO end_io handler.  Wait for all other I/O to
888 	 * drain first.
889 	 */
890 	if (flags & IOMAP_DIO_FORCE_WAIT)
891 		inode_dio_wait(VFS_I(ip));
892 
893 	if (mapping_stable_writes(iocb->ki_filp->f_mapping))
894 		flags |= IOMAP_DIO_BOUNCE;
895 
896 	trace_xfs_file_direct_write(iocb, from);
897 	ret = iomap_dio_rw(iocb, from, xfs_direct_write_iomap_next,
898 			   &xfs_dio_write_ops, flags, NULL, 0);
899 
900 	/*
901 	 * Retry unaligned I/O with exclusive blocking semantics if the DIO
902 	 * layer rejected it for mapping or locking reasons. If we are doing
903 	 * nonblocking user I/O, propagate the error.
904 	 */
905 	if (ret == -EAGAIN && !(iocb->ki_flags & IOCB_NOWAIT)) {
906 		ASSERT(flags & IOMAP_DIO_OVERWRITE_ONLY);
907 		xfs_iunlock(ip, iolock);
908 		goto retry_exclusive;
909 	}
910 
911 out_unlock:
912 	if (iolock)
913 		xfs_iunlock(ip, iolock);
914 	return ret;
915 }
916 
917 static ssize_t
918 xfs_file_dio_write(
919 	struct kiocb		*iocb,
920 	struct iov_iter		*from)
921 {
922 	struct xfs_inode	*ip = XFS_I(file_inode(iocb->ki_filp));
923 	struct xfs_buftarg      *target = xfs_inode_buftarg(ip);
924 	size_t			count = iov_iter_count(from);
925 
926 	/* direct I/O must be aligned to device logical sector size */
927 	if ((iocb->ki_pos | count) & target->bt_logical_sectormask)
928 		return -EINVAL;
929 
930 	if ((iocb->ki_pos | count) & ip->i_mount->m_blockmask)
931 		return xfs_file_dio_write_unaligned(ip, iocb, from);
932 	if (xfs_is_zoned_inode(ip))
933 		return xfs_file_dio_write_zoned(ip, iocb, from);
934 	if (iocb->ki_flags & IOCB_ATOMIC)
935 		return xfs_file_dio_write_atomic(ip, iocb, from);
936 	return xfs_file_dio_write_aligned(ip, iocb, from,
937 			xfs_direct_write_iomap_next, &xfs_dio_write_ops, NULL);
938 }
939 
940 static noinline ssize_t
941 xfs_file_dax_write(
942 	struct kiocb		*iocb,
943 	struct iov_iter		*from)
944 {
945 	struct inode		*inode = iocb->ki_filp->f_mapping->host;
946 	struct xfs_inode	*ip = XFS_I(inode);
947 	unsigned int		iolock = XFS_IOLOCK_EXCL;
948 	ssize_t			ret, error = 0;
949 	loff_t			pos;
950 
951 	ret = xfs_ilock_iocb(iocb, iolock);
952 	if (ret)
953 		return ret;
954 	ret = xfs_file_write_checks(iocb, from, &iolock, NULL);
955 	if (ret)
956 		goto out;
957 
958 	pos = iocb->ki_pos;
959 
960 	trace_xfs_file_dax_write(iocb, from);
961 	ret = dax_iomap_rw(iocb, from, xfs_dax_write_iomap_next);
962 	if (ret > 0 && iocb->ki_pos > i_size_read(inode)) {
963 		i_size_write(inode, iocb->ki_pos);
964 		error = xfs_setfilesize(ip, pos, ret);
965 	}
966 out:
967 	if (iolock)
968 		xfs_iunlock(ip, iolock);
969 	if (error)
970 		return error;
971 
972 	if (ret > 0) {
973 		XFS_STATS_ADD(ip->i_mount, xs_write_bytes, ret);
974 
975 		/* Handle various SYNC-type writes */
976 		ret = generic_write_sync(iocb, ret);
977 	}
978 	return ret;
979 }
980 
981 STATIC ssize_t
982 xfs_file_buffered_write(
983 	struct kiocb		*iocb,
984 	struct iov_iter		*from)
985 {
986 	struct inode		*inode = iocb->ki_filp->f_mapping->host;
987 	struct xfs_inode	*ip = XFS_I(inode);
988 	ssize_t			ret;
989 	bool			cleared_space = false;
990 	unsigned int		iolock;
991 
992 write_retry:
993 	iolock = XFS_IOLOCK_EXCL;
994 	ret = xfs_ilock_iocb(iocb, iolock);
995 	if (ret)
996 		return ret;
997 
998 	ret = xfs_file_write_checks(iocb, from, &iolock, NULL);
999 	if (ret)
1000 		goto out;
1001 
1002 	trace_xfs_file_buffered_write(iocb, from);
1003 	ret = iomap_file_buffered_write(iocb, from,
1004 			xfs_buffered_write_iomap_next, &xfs_iomap_write_ops,
1005 			NULL);
1006 
1007 	/*
1008 	 * If we hit a space limit, try to free up some lingering preallocated
1009 	 * space before returning an error. In the case of ENOSPC, first try to
1010 	 * write back all dirty inodes to free up some of the excess reserved
1011 	 * metadata space. This reduces the chances that the eofblocks scan
1012 	 * waits on dirty mappings. Since xfs_flush_inodes() is serialized, this
1013 	 * also behaves as a filter to prevent too many eofblocks scans from
1014 	 * running at the same time.  Use a synchronous scan to increase the
1015 	 * effectiveness of the scan.
1016 	 */
1017 	if (ret == -EDQUOT && !cleared_space) {
1018 		xfs_iunlock(ip, iolock);
1019 		xfs_blockgc_free_quota(ip, XFS_ICWALK_FLAG_SYNC);
1020 		cleared_space = true;
1021 		goto write_retry;
1022 	} else if (ret == -ENOSPC && !cleared_space) {
1023 		struct xfs_icwalk	icw = {0};
1024 
1025 		cleared_space = true;
1026 		xfs_flush_inodes(ip->i_mount);
1027 
1028 		xfs_iunlock(ip, iolock);
1029 		icw.icw_flags = XFS_ICWALK_FLAG_SYNC;
1030 		xfs_blockgc_free_space(ip->i_mount, &icw);
1031 		goto write_retry;
1032 	}
1033 
1034 out:
1035 	if (iolock)
1036 		xfs_iunlock(ip, iolock);
1037 
1038 	if (ret > 0) {
1039 		XFS_STATS_ADD(ip->i_mount, xs_write_bytes, ret);
1040 		/* Handle various SYNC-type writes */
1041 		ret = generic_write_sync(iocb, ret);
1042 	}
1043 	return ret;
1044 }
1045 
1046 STATIC ssize_t
1047 xfs_file_buffered_write_zoned(
1048 	struct kiocb		*iocb,
1049 	struct iov_iter		*from)
1050 {
1051 	struct xfs_inode	*ip = XFS_I(iocb->ki_filp->f_mapping->host);
1052 	struct xfs_mount	*mp = ip->i_mount;
1053 	unsigned int		iolock = XFS_IOLOCK_EXCL;
1054 	bool			cleared_space = false;
1055 	struct xfs_zone_alloc_ctx ac = { };
1056 	ssize_t			ret;
1057 
1058 	ret = xfs_zoned_write_space_reserve(mp, iocb, from, XFS_ZR_GREEDY, &ac);
1059 	if (ret < 0)
1060 		return ret;
1061 
1062 	ret = xfs_ilock_iocb(iocb, iolock);
1063 	if (ret)
1064 		goto out_unreserve;
1065 
1066 	ret = xfs_file_write_checks(iocb, from, &iolock, &ac);
1067 	if (ret)
1068 		goto out_unlock;
1069 
1070 	/*
1071 	 * Truncate the iter to the length that we were actually able to
1072 	 * allocate blocks for.  This needs to happen after
1073 	 * xfs_file_write_checks, because that assigns ki_pos for O_APPEND
1074 	 * writes.
1075 	 */
1076 	iov_iter_truncate(from,
1077 			XFS_FSB_TO_B(mp, ac.reserved_blocks) -
1078 			(iocb->ki_pos & mp->m_blockmask));
1079 	if (!iov_iter_count(from))
1080 		goto out_unlock;
1081 
1082 retry:
1083 	trace_xfs_file_buffered_write(iocb, from);
1084 	ret = iomap_file_buffered_write(iocb, from,
1085 			xfs_buffered_write_iomap_next, &xfs_iomap_write_ops,
1086 			&ac);
1087 	if (ret == -ENOSPC && !cleared_space) {
1088 		/*
1089 		 * Kick off writeback to convert delalloc space and release the
1090 		 * usually too pessimistic indirect block reservations.
1091 		 */
1092 		xfs_flush_inodes(mp);
1093 		cleared_space = true;
1094 		goto retry;
1095 	}
1096 
1097 out_unlock:
1098 	xfs_iunlock(ip, iolock);
1099 out_unreserve:
1100 	xfs_zoned_space_unreserve(ip->i_mount, &ac);
1101 	if (ret > 0) {
1102 		XFS_STATS_ADD(mp, xs_write_bytes, ret);
1103 		ret = generic_write_sync(iocb, ret);
1104 	}
1105 	return ret;
1106 }
1107 
1108 STATIC ssize_t
1109 xfs_file_write_iter(
1110 	struct kiocb		*iocb,
1111 	struct iov_iter		*from)
1112 {
1113 	struct inode		*inode = iocb->ki_filp->f_mapping->host;
1114 	struct xfs_inode	*ip = XFS_I(inode);
1115 	ssize_t			ret;
1116 	size_t			ocount = iov_iter_count(from);
1117 
1118 	XFS_STATS_INC(ip->i_mount, xs_write_calls);
1119 
1120 	if (ocount == 0)
1121 		return 0;
1122 
1123 	if (xfs_is_shutdown(ip->i_mount))
1124 		return -EIO;
1125 
1126 	if (iocb->ki_flags & IOCB_ATOMIC) {
1127 		if (ocount < xfs_get_atomic_write_min(ip))
1128 			return -EINVAL;
1129 
1130 		if (ocount > xfs_get_atomic_write_max(ip))
1131 			return -EINVAL;
1132 
1133 		ret = generic_atomic_write_valid(iocb, from);
1134 		if (ret)
1135 			return ret;
1136 	}
1137 
1138 	if (IS_DAX(inode))
1139 		return xfs_file_dax_write(iocb, from);
1140 
1141 	if (iocb->ki_flags & IOCB_DIRECT) {
1142 		/*
1143 		 * Allow a directio write to fall back to a buffered
1144 		 * write *only* in the case that we're doing a reflink
1145 		 * CoW.  In all other directio scenarios we do not
1146 		 * allow an operation to fall back to buffered mode.
1147 		 */
1148 		ret = xfs_file_dio_write(iocb, from);
1149 		if (ret != -ENOTBLK)
1150 			return ret;
1151 	}
1152 
1153 	if (xfs_is_zoned_inode(ip))
1154 		return xfs_file_buffered_write_zoned(iocb, from);
1155 	return xfs_file_buffered_write(iocb, from);
1156 }
1157 
1158 /* Does this file, inode, or mount want synchronous writes? */
1159 static inline bool xfs_file_sync_writes(struct file *filp)
1160 {
1161 	struct xfs_inode	*ip = XFS_I(file_inode(filp));
1162 
1163 	if (xfs_has_wsync(ip->i_mount))
1164 		return true;
1165 	if (filp->f_flags & (__O_SYNC | O_DSYNC))
1166 		return true;
1167 	if (IS_SYNC(file_inode(filp)))
1168 		return true;
1169 
1170 	return false;
1171 }
1172 
1173 static int
1174 xfs_falloc_newsize(
1175 	struct file		*file,
1176 	int			mode,
1177 	loff_t			offset,
1178 	loff_t			len,
1179 	loff_t			*new_size)
1180 {
1181 	struct inode		*inode = file_inode(file);
1182 
1183 	if ((mode & FALLOC_FL_KEEP_SIZE) || offset + len <= i_size_read(inode))
1184 		return 0;
1185 	*new_size = offset + len;
1186 	return inode_newsize_ok(inode, *new_size);
1187 }
1188 
1189 static int
1190 xfs_falloc_setsize(
1191 	struct file		*file,
1192 	loff_t			new_size)
1193 {
1194 	struct iattr iattr = {
1195 		.ia_valid	= ATTR_SIZE,
1196 		.ia_size	= new_size,
1197 	};
1198 
1199 	if (!new_size)
1200 		return 0;
1201 	return xfs_vn_setattr_size(file_mnt_idmap(file), file_dentry(file),
1202 			&iattr);
1203 }
1204 
1205 static int
1206 xfs_falloc_collapse_range(
1207 	struct file		*file,
1208 	loff_t			offset,
1209 	loff_t			len,
1210 	struct xfs_zone_alloc_ctx *ac)
1211 {
1212 	struct inode		*inode = file_inode(file);
1213 	loff_t			new_size = i_size_read(inode) - len;
1214 	int			error;
1215 
1216 	if (!xfs_is_falloc_aligned(XFS_I(inode), offset, len))
1217 		return -EINVAL;
1218 
1219 	/*
1220 	 * There is no need to overlap collapse range with EOF, in which case it
1221 	 * is effectively a truncate operation
1222 	 */
1223 	if (offset + len >= i_size_read(inode))
1224 		return -EINVAL;
1225 
1226 	error = xfs_collapse_file_space(XFS_I(inode), offset, len, ac);
1227 	if (error)
1228 		return error;
1229 	return xfs_falloc_setsize(file, new_size);
1230 }
1231 
1232 static int
1233 xfs_falloc_insert_range(
1234 	struct file		*file,
1235 	loff_t			offset,
1236 	loff_t			len)
1237 {
1238 	struct inode		*inode = file_inode(file);
1239 	loff_t			isize = i_size_read(inode);
1240 	int			error;
1241 
1242 	if (!xfs_is_falloc_aligned(XFS_I(inode), offset, len))
1243 		return -EINVAL;
1244 
1245 	/*
1246 	 * New inode size must not exceed ->s_maxbytes, accounting for
1247 	 * possible signed overflow.
1248 	 */
1249 	if (inode->i_sb->s_maxbytes - isize < len)
1250 		return -EFBIG;
1251 
1252 	/* Offset should be less than i_size */
1253 	if (offset >= isize)
1254 		return -EINVAL;
1255 
1256 	/*
1257 	 * Let writeback clean up EOF folio state before we bump i_size. The
1258 	 * insert flushes before it starts shifting and under certain
1259 	 * circumstances we can write back blocks that should technically be
1260 	 * considered post-eof (and thus should not be submitted for writeback).
1261 	 *
1262 	 * For example, a large, dirty folio that spans EOF and is backed by
1263 	 * post-eof COW fork preallocation can cause block remap into the data
1264 	 * fork. This shifts back out beyond EOF, but creates an expectedly
1265 	 * written post-eof block. The insert is going to flush, unmap and
1266 	 * cancel prealloc across this whole range, so flush EOF now before we
1267 	 * bump i_size to provide consistent behavior.
1268 	 */
1269 	error = filemap_write_and_wait_range(inode->i_mapping, isize, isize);
1270 	if (error)
1271 		return error;
1272 
1273 	error = xfs_falloc_setsize(file, isize + len);
1274 	if (error)
1275 		return error;
1276 
1277 	/*
1278 	 * Perform hole insertion now that the file size has been updated so
1279 	 * that if we crash during the operation we don't leave shifted extents
1280 	 * past EOF and hence losing access to the data that is contained within
1281 	 * them.
1282 	 */
1283 	return xfs_insert_file_space(XFS_I(inode), offset, len);
1284 }
1285 
1286 /*
1287  * For various operations we need to zero up to one block at each end of
1288  * the affected range.  For zoned file systems this will require a space
1289  * allocation, for which we need a reservation ahead of time.
1290  */
1291 #define XFS_ZONED_ZERO_EDGE_SPACE_RES		2
1292 
1293 /*
1294  * Zero range implements a full zeroing mechanism but is only used in limited
1295  * situations. It is more efficient to allocate unwritten extents than to
1296  * perform zeroing here, so use an errortag to randomly force zeroing on DEBUG
1297  * kernels for added test coverage.
1298  *
1299  * On zoned file systems, the error is already injected by
1300  * xfs_file_zoned_fallocate, which then reserves the additional space needed.
1301  * We only check for this extra space reservation here.
1302  */
1303 static inline bool
1304 xfs_falloc_force_zero(
1305 	struct xfs_inode		*ip,
1306 	struct xfs_zone_alloc_ctx	*ac)
1307 {
1308 	if (xfs_is_zoned_inode(ip)) {
1309 		if (ac->reserved_blocks > XFS_ZONED_ZERO_EDGE_SPACE_RES) {
1310 			ASSERT(IS_ENABLED(CONFIG_XFS_DEBUG));
1311 			return true;
1312 		}
1313 		return false;
1314 	}
1315 	return XFS_TEST_ERROR(ip->i_mount, XFS_ERRTAG_FORCE_ZERO_RANGE);
1316 }
1317 
1318 static int
1319 xfs_falloc_write_zeroes(
1320 	struct file		*file,
1321 	int			mode,
1322 	loff_t			offset,
1323 	loff_t			len,
1324 	struct xfs_zone_alloc_ctx *ac)
1325 {
1326 	struct inode		*inode = file_inode(file);
1327 	struct xfs_inode	*ip = XFS_I(inode);
1328 	loff_t			new_size = 0;
1329 	int			error;
1330 
1331 	/*
1332 	 * XXX: There is an issue with bigrtalloc inodes where there can be blocks
1333 	 * that are written after the EOF block. This breaks the promise of no
1334 	 * written blocks past EOF. Return EOPNOTSUPP until it is fixed.
1335 	 */
1336 	if (xfs_is_always_cow_inode(ip) || xfs_inode_has_bigrtalloc(ip) ||
1337 	    !bdev_write_zeroes_unmap_sectors(xfs_inode_buftarg(ip)->bt_bdev))
1338 		return -EOPNOTSUPP;
1339 
1340 	error = xfs_falloc_newsize(file, mode, offset, len, &new_size);
1341 	if (error)
1342 		return error;
1343 
1344 	/*
1345 	 *
1346 	 *    |----------|----------|----------|----------|----------|
1347 	 *    ^     ^    ^                     ^     ^    ^
1348 	 *    |     |    |                     |     |    |
1349 	 *    |   offset |                     |    end   |
1350 	 *    |          |                     |          |
1351 	 * offset_rd   offset_ru              end_rd    end_ru
1352 	 *
1353 	 * xfs_free_file_space() punches the aligned interior offset_ru -> end_rd
1354 	 * to holes and byte-zeroes the in-range parts of the partial edge blocks,
1355 	 * offset -> offset_ru and end_rd -> end.  xfs_zero_range() only touches
1356 	 * already-written blocks here; it skips holes and unwritten extents, so
1357 	 * unallocated/unwritten edge blocks are left for the allocation below.
1358 	 */
1359 	error = xfs_free_file_space(ip, offset, len, ac);
1360 	if (error)
1361 		return error;
1362 
1363 	/*
1364 	 * Publish the new size while the punched range is still a hole, then
1365 	 * fill it with written zeroes.  Like the other fallocate modes we use
1366 	 * xfs_falloc_setsize(), but it must run *before* we convert the range
1367 	 * to written extents: xfs_setattr_size() zeroes [old EOF, new size) via
1368 	 * xfs_zero_range(), which skips holes, so there is nothing to re-zero.
1369 	 * It will also writeback partial EOF block before the on-disk size is
1370 	 * logged.
1371 	 * Note: extending the size before allocating means a failure below
1372 	 * leaves the file larger with unallocated holes in the new range.
1373 	 * That is safe as holes within i_size read back as zeroes and expose
1374 	 * no stale data while the error is propagated to the caller.
1375 	 */
1376 	error = xfs_falloc_setsize(file, new_size);
1377 	if (error)
1378 		return error;
1379 
1380 	/*
1381 	 * Allocate written, zeroed extents across the range.  xfs_alloc_file_space()
1382 	 * rounds outward to block granularity:
1383 	 *  - holes (the punched interior and any unallocated edge block) are
1384 	 *    allocated and zeroed;
1385 	 *  - unwritten extents (including unwritten edge blocks) are converted to
1386 	 *    written and zeroed;
1387 	 *  - Already written edge blocks are skipped. The out-of-range bytes of
1388 	 *    a written edge block keep their data (offset_rd -> offset and
1389 	 *    end -> end_rd); their in-range bytes (offset -> offset_ru and
1390 	 *    end_ru -> end were already zeroed by xfs_free_file_space().
1391 	 */
1392 	return xfs_alloc_file_space(ip, offset, len,
1393 			XFS_ALLOC_FILE_SPACE_WRITE_ZEROES);
1394 }
1395 
1396 /*
1397  * Punch a hole and prealloc the range.  We use a hole punch rather than
1398  * unwritten extent conversion for two reasons:
1399  *
1400  *   1.) Hole punch handles partial block zeroing for us.
1401  *   2.) If prealloc returns ENOSPC, the file range is still zero-valued by
1402  *	 virtue of the hole punch.
1403  */
1404 static int
1405 xfs_falloc_zero_range(
1406 	struct file		*file,
1407 	int			mode,
1408 	loff_t			offset,
1409 	loff_t			len,
1410 	struct xfs_zone_alloc_ctx *ac)
1411 {
1412 	struct inode		*inode = file_inode(file);
1413 	struct xfs_inode	*ip = XFS_I(inode);
1414 	unsigned int		blksize = i_blocksize(inode);
1415 	loff_t			new_size = 0;
1416 	int			error;
1417 
1418 	trace_xfs_zero_file_space(ip);
1419 
1420 	error = xfs_falloc_newsize(file, mode, offset, len, &new_size);
1421 	if (error)
1422 		return error;
1423 
1424 	if (xfs_falloc_force_zero(ip, ac)) {
1425 		error = xfs_zero_range(ip, offset, len, ac, NULL);
1426 	} else {
1427 		error = xfs_free_file_space(ip, offset, len, ac);
1428 		if (error)
1429 			return error;
1430 
1431 		len = round_up(offset + len, blksize) -
1432 			round_down(offset, blksize);
1433 		offset = round_down(offset, blksize);
1434 		error = xfs_alloc_file_space(ip, offset, len,
1435 				XFS_ALLOC_FILE_SPACE_PREALLOC);
1436 	}
1437 	if (error)
1438 		return error;
1439 	return xfs_falloc_setsize(file, new_size);
1440 }
1441 
1442 static int
1443 xfs_falloc_unshare_range(
1444 	struct file		*file,
1445 	int			mode,
1446 	loff_t			offset,
1447 	loff_t			len)
1448 {
1449 	struct inode		*inode = file_inode(file);
1450 	loff_t			new_size = 0;
1451 	int			error;
1452 
1453 	error = xfs_falloc_newsize(file, mode, offset, len, &new_size);
1454 	if (error)
1455 		return error;
1456 
1457 	error = xfs_reflink_unshare(XFS_I(inode), offset, len);
1458 	if (error)
1459 		return error;
1460 
1461 	error = xfs_alloc_file_space(XFS_I(inode), offset, len,
1462 			XFS_ALLOC_FILE_SPACE_PREALLOC);
1463 	if (error)
1464 		return error;
1465 	return xfs_falloc_setsize(file, new_size);
1466 }
1467 
1468 static int
1469 xfs_falloc_allocate_range(
1470 	struct file		*file,
1471 	int			mode,
1472 	loff_t			offset,
1473 	loff_t			len)
1474 {
1475 	struct inode		*inode = file_inode(file);
1476 	loff_t			new_size = 0;
1477 	int			error;
1478 
1479 	/*
1480 	 * If always_cow mode we can't use preallocations and thus should not
1481 	 * create them.
1482 	 */
1483 	if (xfs_is_always_cow_inode(XFS_I(inode)))
1484 		return -EOPNOTSUPP;
1485 
1486 	error = xfs_falloc_newsize(file, mode, offset, len, &new_size);
1487 	if (error)
1488 		return error;
1489 
1490 	error = xfs_alloc_file_space(XFS_I(inode), offset, len,
1491 			XFS_ALLOC_FILE_SPACE_PREALLOC);
1492 	if (error)
1493 		return error;
1494 	return xfs_falloc_setsize(file, new_size);
1495 }
1496 
1497 #define	XFS_FALLOC_FL_SUPPORTED						\
1498 		(FALLOC_FL_ALLOCATE_RANGE | FALLOC_FL_KEEP_SIZE |	\
1499 		 FALLOC_FL_PUNCH_HOLE |	FALLOC_FL_COLLAPSE_RANGE |	\
1500 		 FALLOC_FL_ZERO_RANGE |	FALLOC_FL_INSERT_RANGE |	\
1501 		 FALLOC_FL_UNSHARE_RANGE | FALLOC_FL_WRITE_ZEROES)
1502 
1503 STATIC long
1504 __xfs_file_fallocate(
1505 	struct file		*file,
1506 	int			mode,
1507 	loff_t			offset,
1508 	loff_t			len,
1509 	struct xfs_zone_alloc_ctx *ac)
1510 {
1511 	struct inode		*inode = file_inode(file);
1512 	struct xfs_inode	*ip = XFS_I(inode);
1513 	long			error;
1514 	uint			iolock = XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL;
1515 
1516 	xfs_ilock(ip, iolock);
1517 	error = xfs_break_layouts(inode, &iolock, BREAK_UNMAP);
1518 	if (error)
1519 		goto out_unlock;
1520 
1521 	/*
1522 	 * Must wait for all AIO to complete before we continue as AIO can
1523 	 * change the file size on completion without holding any locks we
1524 	 * currently hold. We must do this first because AIO can update both
1525 	 * the on disk and in memory inode sizes, and the operations that follow
1526 	 * require the in-memory size to be fully up-to-date.
1527 	 */
1528 	inode_dio_wait(inode);
1529 
1530 	error = file_modified(file);
1531 	if (error)
1532 		goto out_unlock;
1533 
1534 	switch (mode & FALLOC_FL_MODE_MASK) {
1535 	case FALLOC_FL_PUNCH_HOLE:
1536 		error = xfs_free_file_space(ip, offset, len, ac);
1537 		break;
1538 	case FALLOC_FL_COLLAPSE_RANGE:
1539 		error = xfs_falloc_collapse_range(file, offset, len, ac);
1540 		break;
1541 	case FALLOC_FL_INSERT_RANGE:
1542 		error = xfs_falloc_insert_range(file, offset, len);
1543 		break;
1544 	case FALLOC_FL_ZERO_RANGE:
1545 		error = xfs_falloc_zero_range(file, mode, offset, len, ac);
1546 		break;
1547 	case FALLOC_FL_UNSHARE_RANGE:
1548 		error = xfs_falloc_unshare_range(file, mode, offset, len);
1549 		break;
1550 	case FALLOC_FL_ALLOCATE_RANGE:
1551 		error = xfs_falloc_allocate_range(file, mode, offset, len);
1552 		break;
1553 	case FALLOC_FL_WRITE_ZEROES:
1554 		error = xfs_falloc_write_zeroes(file, mode, offset, len, ac);
1555 		break;
1556 	default:
1557 		error = -EOPNOTSUPP;
1558 		break;
1559 	}
1560 
1561 	if (!error && xfs_file_sync_writes(file))
1562 		error = xfs_log_force_inode(ip, false, NULL);
1563 
1564 out_unlock:
1565 	xfs_iunlock(ip, iolock);
1566 	return error;
1567 }
1568 
1569 static long
1570 xfs_file_zoned_fallocate(
1571 	struct file		*file,
1572 	int			mode,
1573 	loff_t			offset,
1574 	loff_t			len)
1575 {
1576 	struct xfs_zone_alloc_ctx ac = { };
1577 	struct xfs_inode	*ip = XFS_I(file_inode(file));
1578 	struct xfs_mount	*mp = ip->i_mount;
1579 	xfs_filblks_t		count_fsb;
1580 	int			error;
1581 
1582 	/*
1583 	 * If full zeroing is forced by the error injection knob, we need a
1584 	 * space reservation that covers the entire range.  See the comment in
1585 	 * xfs_zoned_write_space_reserve for the rationale for the calculation.
1586 	 * Otherwise just reserve space for the two boundary blocks.
1587 	 */
1588 	count_fsb = XFS_ZONED_ZERO_EDGE_SPACE_RES;
1589 	if ((mode & FALLOC_FL_MODE_MASK) == FALLOC_FL_ZERO_RANGE &&
1590 	    XFS_TEST_ERROR(mp, XFS_ERRTAG_FORCE_ZERO_RANGE))
1591 		count_fsb += XFS_B_TO_FSB(mp, len) + 1;
1592 
1593 	error = xfs_zoned_space_reserve(mp, count_fsb, XFS_ZR_RESERVED, &ac);
1594 	if (error)
1595 		return error;
1596 	error = __xfs_file_fallocate(file, mode, offset, len, &ac);
1597 	xfs_zoned_space_unreserve(mp, &ac);
1598 	return error;
1599 }
1600 
1601 static long
1602 xfs_file_fallocate(
1603 	struct file		*file,
1604 	int			mode,
1605 	loff_t			offset,
1606 	loff_t			len)
1607 {
1608 	struct inode		*inode = file_inode(file);
1609 
1610 	if (!S_ISREG(inode->i_mode))
1611 		return -EINVAL;
1612 	if (mode & ~XFS_FALLOC_FL_SUPPORTED)
1613 		return -EOPNOTSUPP;
1614 
1615 	/*
1616 	 * For zoned file systems, zeroing the first and last block of a hole
1617 	 * punch requires allocating a new block to rewrite the remaining data
1618 	 * and new zeroes out of place.  Get a reservations for those before
1619 	 * taking the iolock.  Dip into the reserved pool because we are
1620 	 * expected to be able to punch a hole even on a completely full
1621 	 * file system.
1622 	 */
1623 	if (xfs_is_zoned_inode(XFS_I(inode)) &&
1624 	    (mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_ZERO_RANGE |
1625 		     FALLOC_FL_COLLAPSE_RANGE)))
1626 		return xfs_file_zoned_fallocate(file, mode, offset, len);
1627 	return __xfs_file_fallocate(file, mode, offset, len, NULL);
1628 }
1629 
1630 STATIC int
1631 xfs_file_fadvise(
1632 	struct file	*file,
1633 	loff_t		start,
1634 	loff_t		end,
1635 	int		advice)
1636 {
1637 	struct xfs_inode *ip = XFS_I(file_inode(file));
1638 	int ret;
1639 	int lockflags = 0;
1640 
1641 	/*
1642 	 * Operations creating pages in page cache need protection from hole
1643 	 * punching and similar ops
1644 	 */
1645 	if (advice == POSIX_FADV_WILLNEED) {
1646 		lockflags = XFS_IOLOCK_SHARED;
1647 		xfs_ilock(ip, lockflags);
1648 	}
1649 	ret = generic_fadvise(file, start, end, advice);
1650 	if (lockflags)
1651 		xfs_iunlock(ip, lockflags);
1652 	return ret;
1653 }
1654 
1655 STATIC loff_t
1656 xfs_file_remap_range(
1657 	struct file		*file_in,
1658 	loff_t			pos_in,
1659 	struct file		*file_out,
1660 	loff_t			pos_out,
1661 	loff_t			len,
1662 	unsigned int		remap_flags)
1663 {
1664 	struct inode		*inode_in = file_inode(file_in);
1665 	struct xfs_inode	*src = XFS_I(inode_in);
1666 	struct inode		*inode_out = file_inode(file_out);
1667 	struct xfs_inode	*dest = XFS_I(inode_out);
1668 	struct xfs_mount	*mp = src->i_mount;
1669 	loff_t			remapped = 0;
1670 	xfs_extlen_t		cowextsize;
1671 	int			ret;
1672 
1673 	if (remap_flags & ~(REMAP_FILE_DEDUP | REMAP_FILE_ADVISORY))
1674 		return -EINVAL;
1675 
1676 	if (!xfs_has_reflink(mp))
1677 		return -EOPNOTSUPP;
1678 
1679 	if (xfs_is_shutdown(mp))
1680 		return -EIO;
1681 
1682 	/* Prepare and then clone file data. */
1683 	ret = xfs_reflink_remap_prep(file_in, pos_in, file_out, pos_out,
1684 			&len, remap_flags);
1685 	if (ret || len == 0)
1686 		return ret;
1687 
1688 	trace_xfs_reflink_remap_range(src, pos_in, len, dest, pos_out);
1689 
1690 	ret = xfs_reflink_remap_blocks(src, pos_in, dest, pos_out, len,
1691 			&remapped);
1692 	if (ret)
1693 		goto out_unlock;
1694 
1695 	/*
1696 	 * Carry the cowextsize hint from src to dest if we're sharing the
1697 	 * entire source file to the entire destination file, the source file
1698 	 * has a cowextsize hint, and the destination file does not.
1699 	 */
1700 	cowextsize = 0;
1701 	if (pos_in == 0 && len == i_size_read(inode_in) &&
1702 	    (src->i_diflags2 & XFS_DIFLAG2_COWEXTSIZE) &&
1703 	    pos_out == 0 && len >= i_size_read(inode_out) &&
1704 	    !(dest->i_diflags2 & XFS_DIFLAG2_COWEXTSIZE))
1705 		cowextsize = src->i_cowextsize;
1706 
1707 	ret = xfs_reflink_update_dest(dest, pos_out + len, cowextsize,
1708 			remap_flags);
1709 	if (ret)
1710 		goto out_unlock;
1711 
1712 	if (xfs_file_sync_writes(file_in) || xfs_file_sync_writes(file_out))
1713 		xfs_log_force_inode(dest, false, NULL);
1714 out_unlock:
1715 	xfs_iunlock2_remapping(src, dest);
1716 	if (ret)
1717 		trace_xfs_reflink_remap_range_error(dest, ret, _RET_IP_);
1718 	/*
1719 	 * If the caller did not set CAN_SHORTEN, then it is not prepared to
1720 	 * handle partial results -- either the whole remap succeeds, or we
1721 	 * must say why it did not.  In this case, any error should be returned
1722 	 * to the caller.
1723 	 */
1724 	if (ret && remapped < len && !(remap_flags & REMAP_FILE_CAN_SHORTEN))
1725 		return ret;
1726 	return remapped > 0 ? remapped : ret;
1727 }
1728 
1729 STATIC int
1730 xfs_file_open(
1731 	struct inode	*inode,
1732 	struct file	*file)
1733 {
1734 	if (xfs_is_shutdown(XFS_M(inode->i_sb)))
1735 		return -EIO;
1736 	file->f_mode |= FMODE_NOWAIT | FMODE_CAN_ODIRECT;
1737 	if (xfs_get_atomic_write_min(XFS_I(inode)) > 0)
1738 		file->f_mode |= FMODE_CAN_ATOMIC_WRITE;
1739 	return generic_file_open(inode, file);
1740 }
1741 
1742 STATIC int
1743 xfs_dir_open(
1744 	struct inode	*inode,
1745 	struct file	*file)
1746 {
1747 	struct xfs_inode *ip = XFS_I(inode);
1748 	unsigned int	mode;
1749 	int		error;
1750 
1751 	if (xfs_is_shutdown(ip->i_mount))
1752 		return -EIO;
1753 	error = generic_file_open(inode, file);
1754 	if (error)
1755 		return error;
1756 
1757 	/*
1758 	 * If there are any blocks, read-ahead block 0 as we're almost
1759 	 * certain to have the next operation be a read there.
1760 	 */
1761 	mode = xfs_ilock_data_map_shared(ip);
1762 	if (ip->i_df.if_nextents > 0)
1763 		error = xfs_dir3_data_readahead(ip, 0, 0);
1764 	xfs_iunlock(ip, mode);
1765 	return error;
1766 }
1767 
1768 /*
1769  * Don't bother propagating errors.  We're just doing cleanup, and the caller
1770  * ignores the return value anyway.
1771  */
1772 STATIC int
1773 xfs_file_release(
1774 	struct inode		*inode,
1775 	struct file		*file)
1776 {
1777 	struct xfs_inode	*ip = XFS_I(inode);
1778 	struct xfs_mount	*mp = ip->i_mount;
1779 
1780 	/*
1781 	 * If this is a read-only mount or the file system has been shut down,
1782 	 * don't generate I/O.
1783 	 */
1784 	if (xfs_is_readonly(mp) || xfs_is_shutdown(mp))
1785 		return 0;
1786 
1787 	/*
1788 	 * If we previously truncated this file and removed old data in the
1789 	 * process, we want to initiate "early" writeout on the last close.
1790 	 * This is an attempt to combat the notorious NULL files problem which
1791 	 * is particularly noticeable from a truncate down, buffered (re-)write
1792 	 * (delalloc), followed by a crash.  What we are effectively doing here
1793 	 * is significantly reducing the time window where we'd otherwise be
1794 	 * exposed to that problem.
1795 	 */
1796 	if (xfs_iflags_test_and_clear(ip, XFS_ITRUNCATED)) {
1797 		xfs_iflags_clear(ip, XFS_EOFBLOCKS_RELEASED);
1798 		if (ip->i_delayed_blks > 0)
1799 			filemap_flush(inode->i_mapping);
1800 	}
1801 
1802 	/*
1803 	 * XFS aggressively preallocates post-EOF space to generate contiguous
1804 	 * allocations for writers that append to the end of the file.
1805 	 *
1806 	 * To support workloads that close and reopen the file frequently, these
1807 	 * preallocations usually persist after a close unless it is the first
1808 	 * close for the inode.  This is a tradeoff to generate tightly packed
1809 	 * data layouts for unpacking tarballs or similar archives that write
1810 	 * one file after another without going back to it while keeping the
1811 	 * preallocation for files that have recurring open/write/close cycles.
1812 	 *
1813 	 * This heuristic is skipped for inodes with the append-only flag as
1814 	 * that flag is rather pointless for inodes written only once.
1815 	 *
1816 	 * There is no point in freeing blocks here for open but unlinked files
1817 	 * as they will be taken care of by the inactivation path soon.
1818 	 *
1819 	 * When releasing a read-only context, don't flush data or trim post-EOF
1820 	 * blocks.  This avoids open/read/close workloads from removing EOF
1821 	 * blocks that other writers depend upon to reduce fragmentation.
1822 	 *
1823 	 * Inodes on the zoned RT device never have preallocations, so skip
1824 	 * taking the locks below.
1825 	 */
1826 	if (!inode->i_nlink ||
1827 	    !(file->f_mode & FMODE_WRITE) ||
1828 	    (ip->i_diflags & XFS_DIFLAG_APPEND) ||
1829 	    xfs_is_zoned_inode(ip))
1830 		return 0;
1831 
1832 	/*
1833 	 * If we can't get the iolock or if the filesystem is frozen, just skip
1834 	 * truncating the blocks past EOF because we could deadlock with the
1835 	 * mmap_lock or hang the close() call. We'll get another chance to drop
1836 	 * them once the last reference to the inode is dropped, so we'll never
1837 	 * leak blocks permanently.
1838 	 */
1839 	if (!xfs_iflags_test(ip, XFS_EOFBLOCKS_RELEASED) &&
1840 	    sb_start_write_trylock(mp->m_super)) {
1841 		if (xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL)) {
1842 			if (xfs_can_free_eofblocks(ip) &&
1843 			    !xfs_iflags_test_and_set(ip, XFS_EOFBLOCKS_RELEASED))
1844 				xfs_free_eofblocks(ip);
1845 			xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1846 		}
1847 		sb_end_write(mp->m_super);
1848 	}
1849 
1850 	return 0;
1851 }
1852 
1853 STATIC int
1854 xfs_file_readdir(
1855 	struct file	*file,
1856 	struct dir_context *ctx)
1857 {
1858 	struct inode	*inode = file_inode(file);
1859 	xfs_inode_t	*ip = XFS_I(inode);
1860 	size_t		bufsize;
1861 
1862 	/*
1863 	 * The Linux API doesn't pass down the total size of the buffer
1864 	 * we read into down to the filesystem.  With the filldir concept
1865 	 * it's not needed for correct information, but the XFS dir2 leaf
1866 	 * code wants an estimate of the buffer size to calculate it's
1867 	 * readahead window and size the buffers used for mapping to
1868 	 * physical blocks.
1869 	 *
1870 	 * Try to give it an estimate that's good enough, maybe at some
1871 	 * point we can change the ->readdir prototype to include the
1872 	 * buffer size.  For now we use the current glibc buffer size.
1873 	 */
1874 	bufsize = (size_t)min_t(loff_t, XFS_READDIR_BUFSIZE, ip->i_disk_size);
1875 
1876 	return xfs_readdir(NULL, ip, ctx, bufsize);
1877 }
1878 
1879 STATIC loff_t
1880 xfs_file_llseek(
1881 	struct file	*file,
1882 	loff_t		offset,
1883 	int		whence)
1884 {
1885 	struct inode		*inode = file->f_mapping->host;
1886 
1887 	if (xfs_is_shutdown(XFS_I(inode)->i_mount))
1888 		return -EIO;
1889 
1890 	switch (whence) {
1891 	default:
1892 		return generic_file_llseek(file, offset, whence);
1893 	case SEEK_HOLE:
1894 		offset = iomap_seek_hole(inode, offset, xfs_seek_iomap_next);
1895 		break;
1896 	case SEEK_DATA:
1897 		offset = iomap_seek_data(inode, offset, xfs_seek_iomap_next);
1898 		break;
1899 	}
1900 
1901 	if (offset < 0)
1902 		return offset;
1903 	return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
1904 }
1905 
1906 static inline vm_fault_t
1907 xfs_dax_fault_locked(
1908 	struct vm_fault		*vmf,
1909 	unsigned int		order,
1910 	bool			write_fault)
1911 {
1912 	vm_fault_t		ret;
1913 	unsigned long		pfn;
1914 
1915 	if (!IS_ENABLED(CONFIG_FS_DAX)) {
1916 		ASSERT(0);
1917 		return VM_FAULT_SIGBUS;
1918 	}
1919 	ret = dax_iomap_fault(vmf, order, &pfn, NULL,
1920 			(write_fault && !vmf->cow_page) ?
1921 				xfs_dax_write_iomap_next :
1922 				xfs_read_iomap_next);
1923 	if (ret & VM_FAULT_NEEDDSYNC)
1924 		ret = dax_finish_sync_fault(vmf, order, pfn);
1925 	return ret;
1926 }
1927 
1928 static vm_fault_t
1929 xfs_dax_read_fault(
1930 	struct vm_fault		*vmf,
1931 	unsigned int		order)
1932 {
1933 	struct xfs_inode	*ip = XFS_I(file_inode(vmf->vma->vm_file));
1934 	vm_fault_t		ret;
1935 
1936 	trace_xfs_read_fault(ip, order);
1937 
1938 	xfs_ilock(ip, XFS_MMAPLOCK_SHARED);
1939 	ret = xfs_dax_fault_locked(vmf, order, false);
1940 	xfs_iunlock(ip, XFS_MMAPLOCK_SHARED);
1941 
1942 	return ret;
1943 }
1944 
1945 /*
1946  * Locking for serialisation of IO during page faults. This results in a lock
1947  * ordering of:
1948  *
1949  * mmap_lock (MM)
1950  *   sb_start_pagefault(vfs, freeze)
1951  *     invalidate_lock (vfs/XFS_MMAPLOCK - truncate serialisation)
1952  *       page_lock (MM)
1953  *         i_lock (XFS - extent map serialisation)
1954  */
1955 static vm_fault_t
1956 __xfs_write_fault(
1957 	struct vm_fault		*vmf,
1958 	unsigned int		order,
1959 	struct xfs_zone_alloc_ctx *ac)
1960 {
1961 	struct inode		*inode = file_inode(vmf->vma->vm_file);
1962 	struct xfs_inode	*ip = XFS_I(inode);
1963 	unsigned int		lock_mode = XFS_MMAPLOCK_SHARED;
1964 	vm_fault_t		ret;
1965 
1966 	trace_xfs_write_fault(ip, order);
1967 
1968 	sb_start_pagefault(inode->i_sb);
1969 	file_update_time(vmf->vma->vm_file);
1970 
1971 	/*
1972 	 * Normally we only need the shared mmaplock, but if a reflink remap is
1973 	 * in progress we take the exclusive lock to wait for the remap to
1974 	 * finish before taking a write fault.
1975 	 */
1976 	xfs_ilock(ip, XFS_MMAPLOCK_SHARED);
1977 	if (xfs_iflags_test(ip, XFS_IREMAPPING)) {
1978 		xfs_iunlock(ip, XFS_MMAPLOCK_SHARED);
1979 		xfs_ilock(ip, XFS_MMAPLOCK_EXCL);
1980 		lock_mode = XFS_MMAPLOCK_EXCL;
1981 	}
1982 
1983 	if (IS_DAX(inode))
1984 		ret = xfs_dax_fault_locked(vmf, order, true);
1985 	else
1986 		ret = iomap_page_mkwrite(vmf, xfs_buffered_write_iomap_next,
1987 				ac);
1988 	xfs_iunlock(ip, lock_mode);
1989 
1990 	sb_end_pagefault(inode->i_sb);
1991 	return ret;
1992 }
1993 
1994 static vm_fault_t
1995 xfs_write_fault_zoned(
1996 	struct vm_fault		*vmf,
1997 	unsigned int		order)
1998 {
1999 	struct xfs_inode	*ip = XFS_I(file_inode(vmf->vma->vm_file));
2000 	unsigned int		len = folio_size(page_folio(vmf->page));
2001 	struct xfs_zone_alloc_ctx ac = { };
2002 	int			error;
2003 	vm_fault_t		ret;
2004 
2005 	/*
2006 	 * This could over-allocate as it doesn't check for truncation.
2007 	 *
2008 	 * But as the overallocation is limited to less than a folio and will be
2009 	 * release instantly that's just fine.
2010 	 */
2011 	error = xfs_zoned_space_reserve(ip->i_mount,
2012 			XFS_B_TO_FSB(ip->i_mount, len), 0, &ac);
2013 	if (error < 0)
2014 		return vmf_fs_error(error);
2015 	ret = __xfs_write_fault(vmf, order, &ac);
2016 	xfs_zoned_space_unreserve(ip->i_mount, &ac);
2017 	return ret;
2018 }
2019 
2020 static vm_fault_t
2021 xfs_write_fault(
2022 	struct vm_fault		*vmf,
2023 	unsigned int		order)
2024 {
2025 	if (xfs_is_zoned_inode(XFS_I(file_inode(vmf->vma->vm_file))))
2026 		return xfs_write_fault_zoned(vmf, order);
2027 	return __xfs_write_fault(vmf, order, NULL);
2028 }
2029 
2030 static inline bool
2031 xfs_is_write_fault(
2032 	struct vm_fault		*vmf)
2033 {
2034 	return (vmf->flags & FAULT_FLAG_WRITE) &&
2035 	       (vmf->vma->vm_flags & VM_SHARED);
2036 }
2037 
2038 static vm_fault_t
2039 xfs_filemap_fault(
2040 	struct vm_fault		*vmf)
2041 {
2042 	struct inode		*inode = file_inode(vmf->vma->vm_file);
2043 
2044 	/* DAX can shortcut the normal fault path on write faults! */
2045 	if (IS_DAX(inode)) {
2046 		if (xfs_is_write_fault(vmf))
2047 			return xfs_write_fault(vmf, 0);
2048 		return xfs_dax_read_fault(vmf, 0);
2049 	}
2050 
2051 	trace_xfs_read_fault(XFS_I(inode), 0);
2052 	return filemap_fault(vmf);
2053 }
2054 
2055 static vm_fault_t
2056 xfs_filemap_huge_fault(
2057 	struct vm_fault		*vmf,
2058 	unsigned int		order)
2059 {
2060 	if (!IS_DAX(file_inode(vmf->vma->vm_file)))
2061 		return VM_FAULT_FALLBACK;
2062 
2063 	/* DAX can shortcut the normal fault path on write faults! */
2064 	if (xfs_is_write_fault(vmf))
2065 		return xfs_write_fault(vmf, order);
2066 	return xfs_dax_read_fault(vmf, order);
2067 }
2068 
2069 static vm_fault_t
2070 xfs_filemap_page_mkwrite(
2071 	struct vm_fault		*vmf)
2072 {
2073 	return xfs_write_fault(vmf, 0);
2074 }
2075 
2076 /*
2077  * pfn_mkwrite was originally intended to ensure we capture time stamp updates
2078  * on write faults. In reality, it needs to serialise against truncate and
2079  * prepare memory for writing so handle is as standard write fault.
2080  */
2081 static vm_fault_t
2082 xfs_filemap_pfn_mkwrite(
2083 	struct vm_fault		*vmf)
2084 {
2085 	return xfs_write_fault(vmf, 0);
2086 }
2087 
2088 static const struct vm_operations_struct xfs_file_vm_ops = {
2089 	.fault		= xfs_filemap_fault,
2090 	.huge_fault	= xfs_filemap_huge_fault,
2091 	.map_pages	= filemap_map_pages,
2092 	.page_mkwrite	= xfs_filemap_page_mkwrite,
2093 	.pfn_mkwrite	= xfs_filemap_pfn_mkwrite,
2094 };
2095 
2096 STATIC int
2097 xfs_file_mmap_prepare(
2098 	struct vm_area_desc	*desc)
2099 {
2100 	struct file		*file = desc->file;
2101 	struct inode		*inode = file_inode(file);
2102 	struct xfs_buftarg	*target = xfs_inode_buftarg(XFS_I(inode));
2103 
2104 	/*
2105 	 * We don't support synchronous mappings for non-DAX files and
2106 	 * for DAX files if underneath dax_device is not synchronous.
2107 	 */
2108 	if (!daxdev_mapping_supported(desc, file_inode(file),
2109 				      target->bt_daxdev))
2110 		return -EOPNOTSUPP;
2111 
2112 	file_accessed(file);
2113 	desc->vm_ops = &xfs_file_vm_ops;
2114 	if (IS_DAX(inode))
2115 		vma_desc_set_flags(desc, VMA_HUGEPAGE_BIT);
2116 	return 0;
2117 }
2118 
2119 const struct file_operations xfs_file_operations = {
2120 	.llseek		= xfs_file_llseek,
2121 	.read_iter	= xfs_file_read_iter,
2122 	.write_iter	= xfs_file_write_iter,
2123 	.splice_read	= xfs_file_splice_read,
2124 	.splice_write	= iter_file_splice_write,
2125 	.iopoll		= iocb_bio_iopoll,
2126 	.unlocked_ioctl	= xfs_file_ioctl,
2127 #ifdef CONFIG_COMPAT
2128 	.compat_ioctl	= xfs_file_compat_ioctl,
2129 #endif
2130 	.mmap_prepare	= xfs_file_mmap_prepare,
2131 	.open		= xfs_file_open,
2132 	.release	= xfs_file_release,
2133 	.fsync		= xfs_file_fsync,
2134 	.get_unmapped_area = thp_get_unmapped_area,
2135 	.fallocate	= xfs_file_fallocate,
2136 	.fadvise	= xfs_file_fadvise,
2137 	.remap_file_range = xfs_file_remap_range,
2138 	.fop_flags	= FOP_MMAP_SYNC | FOP_BUFFER_RASYNC |
2139 			  FOP_BUFFER_WASYNC | FOP_DIO_PARALLEL_WRITE |
2140 			  FOP_DONTCACHE,
2141 	.setlease	= generic_setlease,
2142 };
2143 
2144 const struct file_operations xfs_dir_file_operations = {
2145 	.open		= xfs_dir_open,
2146 	.read		= generic_read_dir,
2147 	.iterate_shared	= xfs_file_readdir,
2148 	.llseek		= generic_file_llseek,
2149 	.unlocked_ioctl	= xfs_file_ioctl,
2150 #ifdef CONFIG_COMPAT
2151 	.compat_ioctl	= xfs_file_compat_ioctl,
2152 #endif
2153 	.fsync		= xfs_dir_fsync,
2154 	.setlease	= generic_setlease,
2155 };
2156