xref: /linux/fs/xfs/xfs_aops.c (revision 6f7e6393d1ce636bb7ec77a7fe7b77458fddf701)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4  * Copyright (c) 2016-2025 Christoph Hellwig.
5  * All Rights Reserved.
6  */
7 #include "xfs_platform.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_iomap.h"
16 #include "xfs_trace.h"
17 #include "xfs_bmap.h"
18 #include "xfs_bmap_util.h"
19 #include "xfs_reflink.h"
20 #include "xfs_errortag.h"
21 #include "xfs_error.h"
22 #include "xfs_icache.h"
23 #include "xfs_zone_alloc.h"
24 #include "xfs_rtgroup.h"
25 
26 struct xfs_writepage_ctx {
27 	struct iomap_writepage_ctx ctx;
28 	unsigned int		data_seq;
29 	unsigned int		cow_seq;
30 };
31 
32 static inline struct xfs_writepage_ctx *
33 XFS_WPC(struct iomap_writepage_ctx *ctx)
34 {
35 	return container_of(ctx, struct xfs_writepage_ctx, ctx);
36 }
37 
38 /*
39  * Fast and loose check if this write could update the on-disk inode size.
40  */
41 static inline bool xfs_ioend_is_append(struct iomap_ioend *ioend)
42 {
43 	return ioend->io_offset + ioend->io_size >
44 		XFS_I(ioend->io_inode)->i_disk_size;
45 }
46 
47 /*
48  * Update on-disk file size now that data has been written to disk.
49  */
50 int
51 xfs_setfilesize(
52 	struct xfs_inode	*ip,
53 	xfs_off_t		offset,
54 	size_t			size)
55 {
56 	struct xfs_mount	*mp = ip->i_mount;
57 	struct xfs_trans	*tp;
58 	xfs_fsize_t		isize;
59 	int			error;
60 
61 	error = xfs_trans_alloc(mp, &M_RES(mp)->tr_fsyncts, 0, 0, 0, &tp);
62 	if (error)
63 		return error;
64 
65 	xfs_ilock(ip, XFS_ILOCK_EXCL);
66 	isize = xfs_new_eof(ip, offset + size);
67 	if (!isize) {
68 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
69 		xfs_trans_cancel(tp);
70 		return 0;
71 	}
72 
73 	trace_xfs_setfilesize(ip, offset, size);
74 
75 	ip->i_disk_size = isize;
76 	xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
77 	xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
78 
79 	return xfs_trans_commit(tp);
80 }
81 
82 static void
83 xfs_ioend_put_open_zones(
84 	struct iomap_ioend	*ioend)
85 {
86 	struct iomap_ioend *tmp;
87 
88 	/*
89 	 * Put the open zone for all ioends merged into this one (if any).
90 	 */
91 	list_for_each_entry(tmp, &ioend->io_list, io_list)
92 		xfs_open_zone_put(tmp->io_private);
93 
94 	/*
95 	 * The main ioend might not have an open zone if the submission failed
96 	 * before xfs_zone_alloc_and_submit got called.
97 	 */
98 	if (ioend->io_private)
99 		xfs_open_zone_put(ioend->io_private);
100 }
101 
102 /*
103  * IO write completion.
104  */
105 STATIC void
106 xfs_end_ioend_write(
107 	struct iomap_ioend	*ioend)
108 {
109 	struct xfs_inode	*ip = XFS_I(ioend->io_inode);
110 	struct xfs_mount	*mp = ip->i_mount;
111 	bool			is_zoned = xfs_is_zoned_inode(ip);
112 	xfs_off_t		offset = ioend->io_offset;
113 	size_t			size = ioend->io_size;
114 	unsigned int		nofs_flag;
115 	int			error;
116 
117 	/*
118 	 * We can allocate memory here while doing writeback on behalf of
119 	 * memory reclaim.  To avoid memory allocation deadlocks set the
120 	 * task-wide nofs context for the following operations.
121 	 */
122 	nofs_flag = memalloc_nofs_save();
123 
124 	/*
125 	 * Just clean up the in-memory structures if the fs has been shut down.
126 	 */
127 	if (xfs_is_shutdown(mp)) {
128 		error = -EIO;
129 		goto done;
130 	}
131 
132 	/*
133 	 * Clean up all COW blocks and underlying data fork delalloc blocks on
134 	 * I/O error. The delalloc punch is required because this ioend was
135 	 * mapped to blocks in the COW fork and the associated pages are no
136 	 * longer dirty. If we don't remove delalloc blocks here, they become
137 	 * stale and can corrupt free space accounting on unmount.
138 	 */
139 	error = blk_status_to_errno(ioend->io_bio.bi_status);
140 	if (unlikely(error)) {
141 		if (ioend->io_flags & IOMAP_IOEND_SHARED) {
142 			ASSERT(!is_zoned);
143 			xfs_reflink_cancel_cow_range(ip, offset, size, true);
144 			xfs_bmap_punch_delalloc_range(ip, XFS_DATA_FORK, offset,
145 					offset + size, NULL);
146 		}
147 		goto done;
148 	}
149 
150 	/*
151 	 * Success: commit the COW or unwritten blocks if needed.
152 	 */
153 	if (is_zoned)
154 		error = xfs_zoned_end_io(ip, offset, size, ioend->io_sector,
155 				ioend->io_private, NULLFSBLOCK);
156 	else if (ioend->io_flags & IOMAP_IOEND_SHARED)
157 		error = xfs_reflink_end_cow(ip, offset, size);
158 	else if (ioend->io_flags & IOMAP_IOEND_UNWRITTEN)
159 		error = xfs_iomap_write_unwritten(ip, offset, size, false);
160 
161 	if (!error &&
162 	    !(ioend->io_flags & IOMAP_IOEND_DIRECT) &&
163 	    xfs_ioend_is_append(ioend))
164 		error = xfs_setfilesize(ip, offset, size);
165 done:
166 	if (is_zoned)
167 		xfs_ioend_put_open_zones(ioend);
168 	iomap_finish_ioends(ioend, error);
169 	memalloc_nofs_restore(nofs_flag);
170 }
171 
172 /*
173  * Finish all pending IO completions that require transactional modifications.
174  *
175  * We try to merge physical and logically contiguous ioends before completion to
176  * minimise the number of transactions we need to perform during IO completion.
177  * Both unwritten extent conversion and COW remapping need to iterate and modify
178  * one physical extent at a time, so we gain nothing by merging physically
179  * discontiguous extents here.
180  *
181  * The ioend chain length that we can be processing here is largely unbound in
182  * length and we may have to perform significant amounts of work on each ioend
183  * to complete it. Hence we have to be careful about holding the CPU for too
184  * long in this loop.
185  */
186 void
187 xfs_end_io(
188 	struct work_struct	*work)
189 {
190 	struct xfs_inode	*ip =
191 		container_of(work, struct xfs_inode, i_ioend_work);
192 	struct iomap_ioend	*ioend;
193 	struct list_head	tmp;
194 	unsigned long		flags;
195 
196 	spin_lock_irqsave(&ip->i_ioend_lock, flags);
197 	list_replace_init(&ip->i_ioend_list, &tmp);
198 	spin_unlock_irqrestore(&ip->i_ioend_lock, flags);
199 
200 	iomap_sort_ioends(&tmp);
201 	while ((ioend = list_first_entry_or_null(&tmp, struct iomap_ioend,
202 			io_list))) {
203 		list_del_init(&ioend->io_list);
204 		iomap_ioend_try_merge(ioend, &tmp);
205 		if (bio_op(&ioend->io_bio) == REQ_OP_READ)
206 			iomap_finish_ioends(ioend,
207 				blk_status_to_errno(ioend->io_bio.bi_status));
208 		else
209 			xfs_end_ioend_write(ioend);
210 		cond_resched();
211 	}
212 }
213 
214 void
215 xfs_end_bio(
216 	struct bio		*bio)
217 {
218 	struct iomap_ioend	*ioend = iomap_ioend_from_bio(bio);
219 	struct xfs_inode	*ip = XFS_I(ioend->io_inode);
220 	struct xfs_mount	*mp = ip->i_mount;
221 	unsigned long		flags;
222 
223 	/*
224 	 * For Appends record the actually written block number and set the
225 	 * boundary flag if needed.
226 	 */
227 	if (IS_ENABLED(CONFIG_XFS_RT) && bio_is_zone_append(bio)) {
228 		ioend->io_sector = bio->bi_iter.bi_sector;
229 		xfs_mark_rtg_boundary(ioend);
230 	}
231 
232 	spin_lock_irqsave(&ip->i_ioend_lock, flags);
233 	if (list_empty(&ip->i_ioend_list))
234 		WARN_ON_ONCE(!queue_work(mp->m_unwritten_workqueue,
235 					 &ip->i_ioend_work));
236 	list_add_tail(&ioend->io_list, &ip->i_ioend_list);
237 	spin_unlock_irqrestore(&ip->i_ioend_lock, flags);
238 }
239 
240 /*
241  * We cannot cancel the ioend directly on error.  We may have already set other
242  * pages under writeback and hence we have to run I/O completion to mark the
243  * error state of the pages under writeback appropriately.
244  *
245  * If the folio has delalloc blocks on it, the caller is asking us to punch them
246  * out. If we don't, we can leave a stale delalloc mapping covered by a clean
247  * page that needs to be dirtied again before the delalloc mapping can be
248  * converted. This stale delalloc mapping can trip up a later direct I/O read
249  * operation on the same region.
250  *
251  * We prevent this by truncating away the delalloc regions on the folio. Because
252  * they are delalloc, we can do this without needing a transaction. Indeed - if
253  * we get ENOSPC errors, we have to be able to do this truncation without a
254  * transaction as there is no space left for block reservation (typically why
255  * we see a ENOSPC in writeback).
256  */
257 static void
258 xfs_discard_folio(
259 	struct folio		*folio,
260 	loff_t			pos)
261 {
262 	struct xfs_inode	*ip = XFS_I(folio->mapping->host);
263 	struct xfs_mount	*mp = ip->i_mount;
264 
265 	if (xfs_is_shutdown(mp))
266 		return;
267 
268 	xfs_alert_ratelimited(mp,
269 		"page discard on page "PTR_FMT", inode 0x%llx, pos %llu.",
270 			folio, ip->i_ino, pos);
271 
272 	/*
273 	 * The end of the punch range is always the offset of the first
274 	 * byte of the next folio. Hence the end offset is only dependent on the
275 	 * folio itself and not the start offset that is passed in.
276 	 */
277 	xfs_bmap_punch_delalloc_range(ip, XFS_DATA_FORK, pos,
278 				folio_next_pos(folio), NULL);
279 }
280 
281 /*
282  * Fast revalidation of the cached writeback mapping. Return true if the current
283  * mapping is valid, false otherwise.
284  */
285 static bool
286 xfs_imap_valid(
287 	struct iomap_writepage_ctx	*wpc,
288 	struct xfs_inode		*ip,
289 	loff_t				offset)
290 {
291 	if (offset < wpc->iomap.offset ||
292 	    offset >= wpc->iomap.offset + wpc->iomap.length)
293 		return false;
294 	/*
295 	 * If this is a COW mapping, it is sufficient to check that the mapping
296 	 * covers the offset. Be careful to check this first because the caller
297 	 * can revalidate a COW mapping without updating the data seqno.
298 	 */
299 	if (wpc->iomap.flags & IOMAP_F_SHARED)
300 		return true;
301 
302 	/*
303 	 * This is not a COW mapping. Check the sequence number of the data fork
304 	 * because concurrent changes could have invalidated the extent. Check
305 	 * the COW fork because concurrent changes since the last time we
306 	 * checked (and found nothing at this offset) could have added
307 	 * overlapping blocks.
308 	 */
309 	if (XFS_WPC(wpc)->data_seq != READ_ONCE(ip->i_df.if_seq)) {
310 		trace_xfs_wb_data_iomap_invalid(ip, &wpc->iomap,
311 				XFS_WPC(wpc)->data_seq, XFS_DATA_FORK);
312 		return false;
313 	}
314 	if (xfs_inode_has_cow_data(ip) &&
315 	    XFS_WPC(wpc)->cow_seq != READ_ONCE(ip->i_cowfp->if_seq)) {
316 		trace_xfs_wb_cow_iomap_invalid(ip, &wpc->iomap,
317 				XFS_WPC(wpc)->cow_seq, XFS_COW_FORK);
318 		return false;
319 	}
320 	return true;
321 }
322 
323 static int
324 xfs_map_blocks(
325 	struct iomap_writepage_ctx *wpc,
326 	loff_t			offset,
327 	unsigned int		len)
328 {
329 	struct xfs_inode	*ip = XFS_I(wpc->inode);
330 	struct xfs_mount	*mp = ip->i_mount;
331 	ssize_t			count = i_blocksize(wpc->inode);
332 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
333 	xfs_fileoff_t		end_fsb = XFS_B_TO_FSB(mp, offset + count);
334 	xfs_fileoff_t		cow_fsb;
335 	int			whichfork;
336 	struct xfs_bmbt_irec	imap;
337 	struct xfs_iext_cursor	icur;
338 	int			retries = 0;
339 	int			error = 0;
340 	unsigned int		*seq;
341 
342 	if (xfs_is_shutdown(mp))
343 		return -EIO;
344 
345 	XFS_ERRORTAG_DELAY(mp, XFS_ERRTAG_WB_DELAY_MS);
346 
347 	/*
348 	 * COW fork blocks can overlap data fork blocks even if the blocks
349 	 * aren't shared.  COW I/O always takes precedent, so we must always
350 	 * check for overlap on reflink inodes unless the mapping is already a
351 	 * COW one, or the COW fork hasn't changed from the last time we looked
352 	 * at it.
353 	 *
354 	 * It's safe to check the COW fork if_seq here without the ILOCK because
355 	 * we've indirectly protected against concurrent updates: writeback has
356 	 * the page locked, which prevents concurrent invalidations by reflink
357 	 * and directio and prevents concurrent buffered writes to the same
358 	 * page.  Changes to if_seq always happen under i_lock, which protects
359 	 * against concurrent updates and provides a memory barrier on the way
360 	 * out that ensures that we always see the current value.
361 	 */
362 	if (xfs_imap_valid(wpc, ip, offset))
363 		return 0;
364 
365 	/*
366 	 * If we don't have a valid map, now it's time to get a new one for this
367 	 * offset.  This will convert delayed allocations (including COW ones)
368 	 * into real extents.  If we return without a valid map, it means we
369 	 * landed in a hole and we skip the block.
370 	 */
371 retry:
372 	cow_fsb = NULLFILEOFF;
373 	whichfork = XFS_DATA_FORK;
374 	xfs_ilock(ip, XFS_ILOCK_SHARED);
375 	ASSERT(!xfs_need_iread_extents(&ip->i_df));
376 
377 	/*
378 	 * Check if this is offset is covered by a COW extents, and if yes use
379 	 * it directly instead of looking up anything in the data fork.
380 	 */
381 	if (xfs_inode_has_cow_data(ip) &&
382 	    xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, &imap))
383 		cow_fsb = imap.br_startoff;
384 	if (cow_fsb != NULLFILEOFF && cow_fsb <= offset_fsb) {
385 		XFS_WPC(wpc)->cow_seq = READ_ONCE(ip->i_cowfp->if_seq);
386 		xfs_iunlock(ip, XFS_ILOCK_SHARED);
387 
388 		whichfork = XFS_COW_FORK;
389 		goto allocate_blocks;
390 	}
391 
392 	/*
393 	 * No COW extent overlap. Revalidate now that we may have updated
394 	 * ->cow_seq. If the data mapping is still valid, we're done.
395 	 */
396 	if (xfs_imap_valid(wpc, ip, offset)) {
397 		xfs_iunlock(ip, XFS_ILOCK_SHARED);
398 		return 0;
399 	}
400 
401 	/*
402 	 * If we don't have a valid map, now it's time to get a new one for this
403 	 * offset.  This will convert delayed allocations (including COW ones)
404 	 * into real extents.
405 	 */
406 	if (!xfs_iext_lookup_extent(ip, &ip->i_df, offset_fsb, &icur, &imap))
407 		imap.br_startoff = end_fsb;	/* fake a hole past EOF */
408 	XFS_WPC(wpc)->data_seq = READ_ONCE(ip->i_df.if_seq);
409 	xfs_iunlock(ip, XFS_ILOCK_SHARED);
410 
411 	/* landed in a hole or beyond EOF? */
412 	if (imap.br_startoff > offset_fsb) {
413 		imap.br_blockcount = imap.br_startoff - offset_fsb;
414 		imap.br_startoff = offset_fsb;
415 		imap.br_startblock = HOLESTARTBLOCK;
416 		imap.br_state = XFS_EXT_NORM;
417 	}
418 
419 	/*
420 	 * Truncate to the next COW extent if there is one.  This is the only
421 	 * opportunity to do this because we can skip COW fork lookups for the
422 	 * subsequent blocks in the mapping; however, the requirement to treat
423 	 * the COW range separately remains.
424 	 */
425 	if (cow_fsb != NULLFILEOFF &&
426 	    cow_fsb < imap.br_startoff + imap.br_blockcount)
427 		imap.br_blockcount = cow_fsb - imap.br_startoff;
428 
429 	/* got a delalloc extent? */
430 	if (imap.br_startblock != HOLESTARTBLOCK &&
431 	    isnullstartblock(imap.br_startblock))
432 		goto allocate_blocks;
433 
434 	xfs_bmbt_to_iomap(ip, &wpc->iomap, &imap, 0, 0, XFS_WPC(wpc)->data_seq);
435 	trace_xfs_map_blocks_found(ip, offset, count, whichfork, &imap);
436 	return 0;
437 allocate_blocks:
438 	/*
439 	 * Convert a dellalloc extent to a real one. The current page is held
440 	 * locked so nothing could have removed the block backing offset_fsb,
441 	 * although it could have moved from the COW to the data fork by another
442 	 * thread.
443 	 */
444 	if (whichfork == XFS_COW_FORK)
445 		seq = &XFS_WPC(wpc)->cow_seq;
446 	else
447 		seq = &XFS_WPC(wpc)->data_seq;
448 
449 	error = xfs_bmapi_convert_delalloc(ip, whichfork, offset,
450 				&wpc->iomap, seq);
451 	if (error) {
452 		/*
453 		 * If we failed to find the extent in the COW fork we might have
454 		 * raced with a COW to data fork conversion or truncate.
455 		 * Restart the lookup to catch the extent in the data fork for
456 		 * the former case, but prevent additional retries to avoid
457 		 * looping forever for the latter case.
458 		 */
459 		if (error == -EAGAIN && whichfork == XFS_COW_FORK && !retries++)
460 			goto retry;
461 		ASSERT(error != -EAGAIN);
462 		return error;
463 	}
464 
465 	/*
466 	 * Due to merging the return real extent might be larger than the
467 	 * original delalloc one.  Trim the return extent to the next COW
468 	 * boundary again to force a re-lookup.
469 	 */
470 	if (whichfork != XFS_COW_FORK && cow_fsb != NULLFILEOFF) {
471 		loff_t		cow_offset = XFS_FSB_TO_B(mp, cow_fsb);
472 
473 		if (cow_offset < wpc->iomap.offset + wpc->iomap.length)
474 			wpc->iomap.length = cow_offset - wpc->iomap.offset;
475 	}
476 
477 	ASSERT(wpc->iomap.offset <= offset);
478 	ASSERT(wpc->iomap.offset + wpc->iomap.length > offset);
479 	trace_xfs_map_blocks_alloc(ip, offset, count, whichfork, &imap);
480 	return 0;
481 }
482 
483 static ssize_t
484 xfs_writeback_range(
485 	struct iomap_writepage_ctx *wpc,
486 	struct folio		*folio,
487 	u64			offset,
488 	unsigned int		len,
489 	u64			end_pos)
490 {
491 	ssize_t			ret;
492 
493 	ret = xfs_map_blocks(wpc, offset, len);
494 	if (!ret)
495 		ret = iomap_add_to_ioend(wpc, folio, offset, end_pos, len);
496 	if (ret < 0)
497 		xfs_discard_folio(folio, offset);
498 	return ret;
499 }
500 
501 static bool
502 xfs_ioend_needs_wq_completion(
503 	struct iomap_ioend	*ioend)
504 {
505 	/* Changing inode size requires a transaction. */
506 	if (xfs_ioend_is_append(ioend))
507 		return true;
508 
509 	/* Extent manipulation requires a transaction. */
510 	if (ioend->io_flags & (IOMAP_IOEND_UNWRITTEN | IOMAP_IOEND_SHARED))
511 		return true;
512 
513 	/* Page cache invalidation cannot be done in irq context. */
514 	if (ioend->io_flags & IOMAP_IOEND_DONTCACHE)
515 		return true;
516 
517 	return false;
518 }
519 
520 static int
521 xfs_writeback_submit(
522 	struct iomap_writepage_ctx	*wpc,
523 	int				error)
524 {
525 	struct iomap_ioend		*ioend = wpc->wb_ctx;
526 
527 	/*
528 	 * Convert CoW extents to regular.
529 	 *
530 	 * We can allocate memory here while doing writeback on behalf of memory
531 	 * reclaim.  To avoid memory allocation deadlocks, set the task-wide
532 	 * nofs context.
533 	 */
534 	if (!error && (ioend->io_flags & IOMAP_IOEND_SHARED)) {
535 		unsigned int		nofs_flag;
536 
537 		nofs_flag = memalloc_nofs_save();
538 		error = xfs_reflink_convert_cow(XFS_I(ioend->io_inode),
539 				ioend->io_offset, ioend->io_size);
540 		memalloc_nofs_restore(nofs_flag);
541 	}
542 
543 	/*
544 	 * Send ioends that might require a transaction to the completion wq.
545 	 */
546 	if (xfs_ioend_needs_wq_completion(ioend))
547 		ioend->io_bio.bi_end_io = xfs_end_bio;
548 
549 	return iomap_ioend_writeback_submit(wpc, error);
550 }
551 
552 static const struct iomap_writeback_ops xfs_writeback_ops = {
553 	.writeback_range	= xfs_writeback_range,
554 	.writeback_submit	= xfs_writeback_submit,
555 };
556 
557 struct xfs_zoned_writepage_ctx {
558 	struct iomap_writepage_ctx	ctx;
559 	struct xfs_open_zone		*open_zone;
560 };
561 
562 static inline struct xfs_zoned_writepage_ctx *
563 XFS_ZWPC(struct iomap_writepage_ctx *ctx)
564 {
565 	return container_of(ctx, struct xfs_zoned_writepage_ctx, ctx);
566 }
567 
568 static int
569 xfs_zoned_map_blocks(
570 	struct iomap_writepage_ctx *wpc,
571 	loff_t			offset,
572 	unsigned int		len)
573 {
574 	struct xfs_inode	*ip = XFS_I(wpc->inode);
575 	struct xfs_mount	*mp = ip->i_mount;
576 	xfs_fileoff_t		offset_fsb = XFS_B_TO_FSBT(mp, offset);
577 	xfs_fileoff_t		end_fsb = XFS_B_TO_FSB(mp, offset + len);
578 	xfs_filblks_t		count_fsb;
579 	struct xfs_bmbt_irec	imap, del;
580 	struct xfs_iext_cursor	icur;
581 
582 	if (xfs_is_shutdown(mp))
583 		return -EIO;
584 
585 	XFS_ERRORTAG_DELAY(mp, XFS_ERRTAG_WB_DELAY_MS);
586 
587 	/*
588 	 * All dirty data must be covered by delalloc extents.  But truncate can
589 	 * remove delalloc extents underneath us or reduce their size.
590 	 * Returning a hole tells iomap to not write back any data from this
591 	 * range, which is the right thing to do in that case.
592 	 *
593 	 * Otherwise just tell iomap to treat ranges previously covered by a
594 	 * delalloc extent as mapped.  The actual block allocation will be done
595 	 * just before submitting the bio.
596 	 *
597 	 * This implies we never map outside folios that are locked or marked
598 	 * as under writeback, and thus there is no need check the fork sequence
599 	 * count here.
600 	 */
601 	xfs_ilock(ip, XFS_ILOCK_EXCL);
602 	if (!xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, &imap))
603 		imap.br_startoff = end_fsb;	/* fake a hole past EOF */
604 	if (imap.br_startoff > offset_fsb) {
605 		imap.br_blockcount = imap.br_startoff - offset_fsb;
606 		imap.br_startoff = offset_fsb;
607 		imap.br_startblock = HOLESTARTBLOCK;
608 		imap.br_state = XFS_EXT_NORM;
609 		xfs_iunlock(ip, XFS_ILOCK_EXCL);
610 		xfs_bmbt_to_iomap(ip, &wpc->iomap, &imap, 0, 0, 0);
611 		return 0;
612 	}
613 	end_fsb = min(end_fsb, imap.br_startoff + imap.br_blockcount);
614 	count_fsb = end_fsb - offset_fsb;
615 
616 	del = imap;
617 	xfs_trim_extent(&del, offset_fsb, count_fsb);
618 	xfs_bmap_del_extent_delay(ip, XFS_COW_FORK, &icur, &imap, &del,
619 			XFS_BMAPI_REMAP);
620 	xfs_iunlock(ip, XFS_ILOCK_EXCL);
621 
622 	wpc->iomap.type = IOMAP_MAPPED;
623 	wpc->iomap.flags = IOMAP_F_DIRTY;
624 	wpc->iomap.bdev = mp->m_rtdev_targp->bt_bdev;
625 	wpc->iomap.offset = offset;
626 	wpc->iomap.length = XFS_FSB_TO_B(mp, count_fsb);
627 	wpc->iomap.flags = IOMAP_F_ANON_WRITE;
628 
629 	trace_xfs_zoned_map_blocks(ip, offset, wpc->iomap.length);
630 	return 0;
631 }
632 
633 static ssize_t
634 xfs_zoned_writeback_range(
635 	struct iomap_writepage_ctx *wpc,
636 	struct folio		*folio,
637 	u64			offset,
638 	unsigned int		len,
639 	u64			end_pos)
640 {
641 	ssize_t			ret;
642 
643 	ret = xfs_zoned_map_blocks(wpc, offset, len);
644 	if (!ret)
645 		ret = iomap_add_to_ioend(wpc, folio, offset, end_pos, len);
646 	if (ret < 0)
647 		xfs_discard_folio(folio, offset);
648 	return ret;
649 }
650 
651 static int
652 xfs_zoned_writeback_submit(
653 	struct iomap_writepage_ctx	*wpc,
654 	int				error)
655 {
656 	struct iomap_ioend		*ioend = wpc->wb_ctx;
657 
658 	ioend->io_bio.bi_end_io = xfs_end_bio;
659 	if (error) {
660 		ioend->io_bio.bi_status = errno_to_blk_status(error);
661 		bio_endio(&ioend->io_bio);
662 		return error;
663 	}
664 	xfs_zone_alloc_and_submit(ioend, &XFS_ZWPC(wpc)->open_zone);
665 	return 0;
666 }
667 
668 static const struct iomap_writeback_ops xfs_zoned_writeback_ops = {
669 	.writeback_range	= xfs_zoned_writeback_range,
670 	.writeback_submit	= xfs_zoned_writeback_submit,
671 };
672 
673 STATIC int
674 xfs_vm_writepages(
675 	struct address_space	*mapping,
676 	struct writeback_control *wbc)
677 {
678 	struct xfs_inode	*ip = XFS_I(mapping->host);
679 
680 	xfs_iflags_clear(ip, XFS_ITRUNCATED);
681 
682 	if (xfs_is_zoned_inode(ip)) {
683 		struct xfs_zoned_writepage_ctx	xc = {
684 			.ctx = {
685 				.inode	= mapping->host,
686 				.wbc	= wbc,
687 				.ops	= &xfs_zoned_writeback_ops
688 			},
689 		};
690 		int				error;
691 
692 		error = iomap_writepages(&xc.ctx);
693 		if (xc.open_zone)
694 			xfs_open_zone_put(xc.open_zone);
695 		return error;
696 	} else {
697 		struct xfs_writepage_ctx	wpc = {
698 			.ctx = {
699 				.inode	= mapping->host,
700 				.wbc	= wbc,
701 				.ops	= &xfs_writeback_ops
702 			},
703 		};
704 
705 		return iomap_writepages(&wpc.ctx);
706 	}
707 }
708 
709 STATIC int
710 xfs_dax_writepages(
711 	struct address_space	*mapping,
712 	struct writeback_control *wbc)
713 {
714 	struct xfs_inode	*ip = XFS_I(mapping->host);
715 
716 	xfs_iflags_clear(ip, XFS_ITRUNCATED);
717 	return dax_writeback_mapping_range(mapping,
718 			xfs_inode_buftarg(ip)->bt_daxdev, wbc);
719 }
720 
721 STATIC sector_t
722 xfs_vm_bmap(
723 	struct address_space	*mapping,
724 	sector_t		block)
725 {
726 	struct xfs_inode	*ip = XFS_I(mapping->host);
727 
728 	trace_xfs_vm_bmap(ip);
729 
730 	/*
731 	 * The swap code (ab-)uses ->bmap to get a block mapping and then
732 	 * bypasses the file system for actual I/O.  We really can't allow
733 	 * that on reflinks inodes, so we have to skip out here.  And yes,
734 	 * 0 is the magic code for a bmap error.
735 	 *
736 	 * Since we don't pass back blockdev info, we can't return bmap
737 	 * information for rt files either.
738 	 */
739 	if (xfs_is_cow_inode(ip) || XFS_IS_REALTIME_INODE(ip))
740 		return 0;
741 	return iomap_bmap(mapping, block, &xfs_read_iomap_ops);
742 }
743 
744 STATIC int
745 xfs_vm_read_folio(
746 	struct file		*unused,
747 	struct folio		*folio)
748 {
749 	iomap_bio_read_folio(folio, &xfs_read_iomap_ops);
750 	return 0;
751 }
752 
753 STATIC void
754 xfs_vm_readahead(
755 	struct readahead_control	*rac)
756 {
757 	iomap_bio_readahead(rac, &xfs_read_iomap_ops);
758 }
759 
760 static int
761 xfs_vm_swap_activate(
762 	struct swap_info_struct		*sis,
763 	struct file			*swap_file,
764 	sector_t			*span)
765 {
766 	struct xfs_inode		*ip = XFS_I(file_inode(swap_file));
767 
768 	if (xfs_is_zoned_inode(ip))
769 		return -EINVAL;
770 
771 	/*
772 	 * Swap file activation can race against concurrent shared extent
773 	 * removal in files that have been cloned.  If this happens,
774 	 * iomap_swapfile_iter() can fail because it encountered a shared
775 	 * extent even though an operation is in progress to remove those
776 	 * shared extents.
777 	 *
778 	 * This race becomes problematic when we defer extent removal
779 	 * operations beyond the end of a syscall (i.e. use async background
780 	 * processing algorithms).  Users think the extents are no longer
781 	 * shared, but iomap_swapfile_iter() still sees them as shared
782 	 * because the refcountbt entries for the extents being removed have
783 	 * not yet been updated.  Hence the swapon call fails unexpectedly.
784 	 *
785 	 * The race condition is currently most obvious from the unlink()
786 	 * operation as extent removal is deferred until after the last
787 	 * reference to the inode goes away.  We then process the extent
788 	 * removal asynchronously, hence triggers the "syscall completed but
789 	 * work not done" condition mentioned above.  To close this race
790 	 * window, we need to flush any pending inodegc operations to ensure
791 	 * they have updated the refcountbt records before we try to map the
792 	 * swapfile.
793 	 */
794 	xfs_inodegc_flush(ip->i_mount);
795 
796 	/*
797 	 * Direct the swap code to the correct block device when this file
798 	 * sits on the RT device.
799 	 */
800 	sis->bdev = xfs_inode_buftarg(ip)->bt_bdev;
801 
802 	return iomap_swapfile_activate(sis, swap_file, span,
803 			&xfs_read_iomap_ops);
804 }
805 
806 const struct address_space_operations xfs_address_space_operations = {
807 	.read_folio		= xfs_vm_read_folio,
808 	.readahead		= xfs_vm_readahead,
809 	.writepages		= xfs_vm_writepages,
810 	.dirty_folio		= iomap_dirty_folio,
811 	.release_folio		= iomap_release_folio,
812 	.invalidate_folio	= iomap_invalidate_folio,
813 	.bmap			= xfs_vm_bmap,
814 	.migrate_folio		= filemap_migrate_folio,
815 	.is_partially_uptodate  = iomap_is_partially_uptodate,
816 	.error_remove_folio	= generic_error_remove_folio,
817 	.swap_activate		= xfs_vm_swap_activate,
818 };
819 
820 const struct address_space_operations xfs_dax_aops = {
821 	.writepages		= xfs_dax_writepages,
822 	.dirty_folio		= noop_dirty_folio,
823 	.swap_activate		= xfs_vm_swap_activate,
824 };
825