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