blob: 5d9f8e4c4cdee19dc8768be134b2f385bb08205c [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4 * Copyright (c) 2016-2018 Christoph Hellwig.
5 * All Rights Reserved.
6 */
7#include "xfs.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
21/*
22 * structure owned by writepages passed to individual writepage calls
23 */
24struct xfs_writepage_ctx {
25 struct xfs_bmbt_irec imap;
26 int fork;
27 unsigned int data_seq;
28 unsigned int cow_seq;
29 struct xfs_ioend *ioend;
30};
31
32struct block_device *
33xfs_find_bdev_for_inode(
34 struct inode *inode)
35{
36 struct xfs_inode *ip = XFS_I(inode);
37 struct xfs_mount *mp = ip->i_mount;
38
39 if (XFS_IS_REALTIME_INODE(ip))
40 return mp->m_rtdev_targp->bt_bdev;
41 else
42 return mp->m_ddev_targp->bt_bdev;
43}
44
45struct dax_device *
46xfs_find_daxdev_for_inode(
47 struct inode *inode)
48{
49 struct xfs_inode *ip = XFS_I(inode);
50 struct xfs_mount *mp = ip->i_mount;
51
52 if (XFS_IS_REALTIME_INODE(ip))
53 return mp->m_rtdev_targp->bt_daxdev;
54 else
55 return mp->m_ddev_targp->bt_daxdev;
56}
57
58static void
59xfs_finish_page_writeback(
60 struct inode *inode,
61 struct bio_vec *bvec,
62 int error)
63{
64 struct iomap_page *iop = to_iomap_page(bvec->bv_page);
65
66 if (error) {
67 SetPageError(bvec->bv_page);
68 mapping_set_error(inode->i_mapping, -EIO);
69 }
70
71 ASSERT(iop || i_blocksize(inode) == PAGE_SIZE);
72 ASSERT(!iop || atomic_read(&iop->write_count) > 0);
73
74 if (!iop || atomic_dec_and_test(&iop->write_count))
75 end_page_writeback(bvec->bv_page);
76}
77
78/*
79 * We're now finished for good with this ioend structure. Update the page
80 * state, release holds on bios, and finally free up memory. Do not use the
81 * ioend after this.
82 */
83STATIC void
84xfs_destroy_ioend(
85 struct xfs_ioend *ioend,
86 int error)
87{
88 struct inode *inode = ioend->io_inode;
89 struct bio *bio = &ioend->io_inline_bio;
90 struct bio *last = ioend->io_bio, *next;
91 u64 start = bio->bi_iter.bi_sector;
92 bool quiet = bio_flagged(bio, BIO_QUIET);
93
94 for (bio = &ioend->io_inline_bio; bio; bio = next) {
95 struct bio_vec *bvec;
96 struct bvec_iter_all iter_all;
97
98 /*
99 * For the last bio, bi_private points to the ioend, so we
100 * need to explicitly end the iteration here.
101 */
102 if (bio == last)
103 next = NULL;
104 else
105 next = bio->bi_private;
106
107 /* walk each page on bio, ending page IO on them */
108 bio_for_each_segment_all(bvec, bio, iter_all)
109 xfs_finish_page_writeback(inode, bvec, error);
110 bio_put(bio);
111 }
112
113 if (unlikely(error && !quiet)) {
114 xfs_err_ratelimited(XFS_I(inode)->i_mount,
115 "writeback error on sector %llu", start);
116 }
117}
118
119/*
120 * Fast and loose check if this write could update the on-disk inode size.
121 */
122static inline bool xfs_ioend_is_append(struct xfs_ioend *ioend)
123{
124 return ioend->io_offset + ioend->io_size >
125 XFS_I(ioend->io_inode)->i_d.di_size;
126}
127
128STATIC int
129xfs_setfilesize_trans_alloc(
130 struct xfs_ioend *ioend)
131{
132 struct xfs_mount *mp = XFS_I(ioend->io_inode)->i_mount;
133 struct xfs_trans *tp;
134 int error;
135
136 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_fsyncts, 0, 0, 0, &tp);
137 if (error)
138 return error;
139
140 ioend->io_append_trans = tp;
141
142 /*
143 * We may pass freeze protection with a transaction. So tell lockdep
144 * we released it.
145 */
146 __sb_writers_release(ioend->io_inode->i_sb, SB_FREEZE_FS);
147 /*
148 * We hand off the transaction to the completion thread now, so
149 * clear the flag here.
150 */
151 current_restore_flags_nested(&tp->t_pflags, PF_MEMALLOC_NOFS);
152 return 0;
153}
154
155/*
156 * Update on-disk file size now that data has been written to disk.
157 */
158STATIC int
159__xfs_setfilesize(
160 struct xfs_inode *ip,
161 struct xfs_trans *tp,
162 xfs_off_t offset,
163 size_t size)
164{
165 xfs_fsize_t isize;
166
167 xfs_ilock(ip, XFS_ILOCK_EXCL);
168 isize = xfs_new_eof(ip, offset + size);
169 if (!isize) {
170 xfs_iunlock(ip, XFS_ILOCK_EXCL);
171 xfs_trans_cancel(tp);
172 return 0;
173 }
174
175 trace_xfs_setfilesize(ip, offset, size);
176
177 ip->i_d.di_size = isize;
178 xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
179 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
180
181 return xfs_trans_commit(tp);
182}
183
184int
185xfs_setfilesize(
186 struct xfs_inode *ip,
187 xfs_off_t offset,
188 size_t size)
189{
190 struct xfs_mount *mp = ip->i_mount;
191 struct xfs_trans *tp;
192 int error;
193
194 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_fsyncts, 0, 0, 0, &tp);
195 if (error)
196 return error;
197
198 return __xfs_setfilesize(ip, tp, offset, size);
199}
200
201STATIC int
202xfs_setfilesize_ioend(
203 struct xfs_ioend *ioend,
204 int error)
205{
206 struct xfs_inode *ip = XFS_I(ioend->io_inode);
207 struct xfs_trans *tp = ioend->io_append_trans;
208
209 /*
210 * The transaction may have been allocated in the I/O submission thread,
211 * thus we need to mark ourselves as being in a transaction manually.
212 * Similarly for freeze protection.
213 */
214 current_set_flags_nested(&tp->t_pflags, PF_MEMALLOC_NOFS);
215 __sb_writers_acquired(VFS_I(ip)->i_sb, SB_FREEZE_FS);
216
217 /* we abort the update if there was an IO error */
218 if (error) {
219 xfs_trans_cancel(tp);
220 return error;
221 }
222
223 return __xfs_setfilesize(ip, tp, ioend->io_offset, ioend->io_size);
224}
225
226/*
227 * IO write completion.
228 */
229STATIC void
230xfs_end_ioend(
231 struct xfs_ioend *ioend)
232{
233 struct list_head ioend_list;
234 struct xfs_inode *ip = XFS_I(ioend->io_inode);
235 xfs_off_t offset = ioend->io_offset;
236 size_t size = ioend->io_size;
237 unsigned int nofs_flag;
238 int error;
239
240 /*
241 * We can allocate memory here while doing writeback on behalf of
242 * memory reclaim. To avoid memory allocation deadlocks set the
243 * task-wide nofs context for the following operations.
244 */
245 nofs_flag = memalloc_nofs_save();
246
247 /*
248 * Just clean up the in-memory strutures if the fs has been shut down.
249 */
250 if (XFS_FORCED_SHUTDOWN(ip->i_mount)) {
251 error = -EIO;
252 goto done;
253 }
254
255 /*
256 * Clean up any COW blocks on an I/O error.
257 */
258 error = blk_status_to_errno(ioend->io_bio->bi_status);
259 if (unlikely(error)) {
260 if (ioend->io_fork == XFS_COW_FORK)
261 xfs_reflink_cancel_cow_range(ip, offset, size, true);
262 goto done;
263 }
264
265 /*
266 * Success: commit the COW or unwritten blocks if needed.
267 */
268 if (ioend->io_fork == XFS_COW_FORK)
269 error = xfs_reflink_end_cow(ip, offset, size);
270 else if (ioend->io_state == XFS_EXT_UNWRITTEN)
271 error = xfs_iomap_write_unwritten(ip, offset, size, false);
272 else
273 ASSERT(!xfs_ioend_is_append(ioend) || ioend->io_append_trans);
274
275done:
276 if (ioend->io_append_trans)
277 error = xfs_setfilesize_ioend(ioend, error);
278 list_replace_init(&ioend->io_list, &ioend_list);
279 xfs_destroy_ioend(ioend, error);
280
281 while (!list_empty(&ioend_list)) {
282 ioend = list_first_entry(&ioend_list, struct xfs_ioend,
283 io_list);
284 list_del_init(&ioend->io_list);
285 xfs_destroy_ioend(ioend, error);
286 }
287
288 memalloc_nofs_restore(nofs_flag);
289}
290
291/*
292 * We can merge two adjacent ioends if they have the same set of work to do.
293 */
294static bool
295xfs_ioend_can_merge(
296 struct xfs_ioend *ioend,
297 struct xfs_ioend *next)
298{
299 if (ioend->io_bio->bi_status != next->io_bio->bi_status)
300 return false;
301 if ((ioend->io_fork == XFS_COW_FORK) ^ (next->io_fork == XFS_COW_FORK))
302 return false;
303 if ((ioend->io_state == XFS_EXT_UNWRITTEN) ^
304 (next->io_state == XFS_EXT_UNWRITTEN))
305 return false;
306 if (ioend->io_offset + ioend->io_size != next->io_offset)
307 return false;
308 return true;
309}
310
311/*
312 * If the to be merged ioend has a preallocated transaction for file
313 * size updates we need to ensure the ioend it is merged into also
314 * has one. If it already has one we can simply cancel the transaction
315 * as it is guaranteed to be clean.
316 */
317static void
318xfs_ioend_merge_append_transactions(
319 struct xfs_ioend *ioend,
320 struct xfs_ioend *next)
321{
322 if (!ioend->io_append_trans) {
323 ioend->io_append_trans = next->io_append_trans;
324 next->io_append_trans = NULL;
325 } else {
326 xfs_setfilesize_ioend(next, -ECANCELED);
327 }
328}
329
330/* Try to merge adjacent completions. */
331STATIC void
332xfs_ioend_try_merge(
333 struct xfs_ioend *ioend,
334 struct list_head *more_ioends)
335{
336 struct xfs_ioend *next_ioend;
337
338 while (!list_empty(more_ioends)) {
339 next_ioend = list_first_entry(more_ioends, struct xfs_ioend,
340 io_list);
341 if (!xfs_ioend_can_merge(ioend, next_ioend))
342 break;
343 list_move_tail(&next_ioend->io_list, &ioend->io_list);
344 ioend->io_size += next_ioend->io_size;
345 if (next_ioend->io_append_trans)
346 xfs_ioend_merge_append_transactions(ioend, next_ioend);
347 }
348}
349
350/* list_sort compare function for ioends */
351static int
352xfs_ioend_compare(
353 void *priv,
354 struct list_head *a,
355 struct list_head *b)
356{
357 struct xfs_ioend *ia;
358 struct xfs_ioend *ib;
359
360 ia = container_of(a, struct xfs_ioend, io_list);
361 ib = container_of(b, struct xfs_ioend, io_list);
362 if (ia->io_offset < ib->io_offset)
363 return -1;
364 else if (ia->io_offset > ib->io_offset)
365 return 1;
366 return 0;
367}
368
369/* Finish all pending io completions. */
370void
371xfs_end_io(
372 struct work_struct *work)
373{
374 struct xfs_inode *ip;
375 struct xfs_ioend *ioend;
376 struct list_head completion_list;
377 unsigned long flags;
378
379 ip = container_of(work, struct xfs_inode, i_ioend_work);
380
381 spin_lock_irqsave(&ip->i_ioend_lock, flags);
382 list_replace_init(&ip->i_ioend_list, &completion_list);
383 spin_unlock_irqrestore(&ip->i_ioend_lock, flags);
384
385 list_sort(NULL, &completion_list, xfs_ioend_compare);
386
387 while (!list_empty(&completion_list)) {
388 ioend = list_first_entry(&completion_list, struct xfs_ioend,
389 io_list);
390 list_del_init(&ioend->io_list);
391 xfs_ioend_try_merge(ioend, &completion_list);
392 xfs_end_ioend(ioend);
393 }
394}
395
396STATIC void
397xfs_end_bio(
398 struct bio *bio)
399{
400 struct xfs_ioend *ioend = bio->bi_private;
401 struct xfs_inode *ip = XFS_I(ioend->io_inode);
402 struct xfs_mount *mp = ip->i_mount;
403 unsigned long flags;
404
405 if (ioend->io_fork == XFS_COW_FORK ||
406 ioend->io_state == XFS_EXT_UNWRITTEN ||
407 ioend->io_append_trans != NULL) {
408 spin_lock_irqsave(&ip->i_ioend_lock, flags);
409 if (list_empty(&ip->i_ioend_list))
410 WARN_ON_ONCE(!queue_work(mp->m_unwritten_workqueue,
411 &ip->i_ioend_work));
412 list_add_tail(&ioend->io_list, &ip->i_ioend_list);
413 spin_unlock_irqrestore(&ip->i_ioend_lock, flags);
414 } else
415 xfs_destroy_ioend(ioend, blk_status_to_errno(bio->bi_status));
416}
417
418/*
419 * Fast revalidation of the cached writeback mapping. Return true if the current
420 * mapping is valid, false otherwise.
421 */
422static bool
423xfs_imap_valid(
424 struct xfs_writepage_ctx *wpc,
425 struct xfs_inode *ip,
426 xfs_fileoff_t offset_fsb)
427{
428 if (offset_fsb < wpc->imap.br_startoff ||
429 offset_fsb >= wpc->imap.br_startoff + wpc->imap.br_blockcount)
430 return false;
431 /*
432 * If this is a COW mapping, it is sufficient to check that the mapping
433 * covers the offset. Be careful to check this first because the caller
434 * can revalidate a COW mapping without updating the data seqno.
435 */
436 if (wpc->fork == XFS_COW_FORK)
437 return true;
438
439 /*
440 * This is not a COW mapping. Check the sequence number of the data fork
441 * because concurrent changes could have invalidated the extent. Check
442 * the COW fork because concurrent changes since the last time we
443 * checked (and found nothing at this offset) could have added
444 * overlapping blocks.
445 */
446 if (wpc->data_seq != READ_ONCE(ip->i_df.if_seq))
447 return false;
448 if (xfs_inode_has_cow_data(ip) &&
449 wpc->cow_seq != READ_ONCE(ip->i_cowfp->if_seq))
450 return false;
451 return true;
452}
453
454/*
455 * Pass in a dellalloc extent and convert it to real extents, return the real
456 * extent that maps offset_fsb in wpc->imap.
457 *
458 * The current page is held locked so nothing could have removed the block
459 * backing offset_fsb, although it could have moved from the COW to the data
460 * fork by another thread.
461 */
462static int
463xfs_convert_blocks(
464 struct xfs_writepage_ctx *wpc,
465 struct xfs_inode *ip,
466 xfs_fileoff_t offset_fsb)
467{
468 int error;
469
470 /*
471 * Attempt to allocate whatever delalloc extent currently backs
472 * offset_fsb and put the result into wpc->imap. Allocate in a loop
473 * because it may take several attempts to allocate real blocks for a
474 * contiguous delalloc extent if free space is sufficiently fragmented.
475 */
476 do {
477 error = xfs_bmapi_convert_delalloc(ip, wpc->fork, offset_fsb,
478 &wpc->imap, wpc->fork == XFS_COW_FORK ?
479 &wpc->cow_seq : &wpc->data_seq);
480 if (error)
481 return error;
482 } while (wpc->imap.br_startoff + wpc->imap.br_blockcount <= offset_fsb);
483
484 return 0;
485}
486
487STATIC int
488xfs_map_blocks(
489 struct xfs_writepage_ctx *wpc,
490 struct inode *inode,
491 loff_t offset)
492{
493 struct xfs_inode *ip = XFS_I(inode);
494 struct xfs_mount *mp = ip->i_mount;
495 ssize_t count = i_blocksize(inode);
496 xfs_fileoff_t offset_fsb = XFS_B_TO_FSBT(mp, offset);
497 xfs_fileoff_t end_fsb = XFS_B_TO_FSB(mp, offset + count);
498 xfs_fileoff_t cow_fsb;
499 struct xfs_bmbt_irec imap;
500 struct xfs_iext_cursor icur;
501 int retries = 0;
502 int error = 0;
503
504 if (XFS_FORCED_SHUTDOWN(mp))
505 return -EIO;
506
507 /*
508 * COW fork blocks can overlap data fork blocks even if the blocks
509 * aren't shared. COW I/O always takes precedent, so we must always
510 * check for overlap on reflink inodes unless the mapping is already a
511 * COW one, or the COW fork hasn't changed from the last time we looked
512 * at it.
513 *
514 * It's safe to check the COW fork if_seq here without the ILOCK because
515 * we've indirectly protected against concurrent updates: writeback has
516 * the page locked, which prevents concurrent invalidations by reflink
517 * and directio and prevents concurrent buffered writes to the same
518 * page. Changes to if_seq always happen under i_lock, which protects
519 * against concurrent updates and provides a memory barrier on the way
520 * out that ensures that we always see the current value.
521 */
522 if (xfs_imap_valid(wpc, ip, offset_fsb))
523 return 0;
524
525 /*
526 * If we don't have a valid map, now it's time to get a new one for this
527 * offset. This will convert delayed allocations (including COW ones)
528 * into real extents. If we return without a valid map, it means we
529 * landed in a hole and we skip the block.
530 */
531retry:
532 cow_fsb = NULLFILEOFF;
533 wpc->fork = XFS_DATA_FORK;
534 xfs_ilock(ip, XFS_ILOCK_SHARED);
535 ASSERT(ip->i_d.di_format != XFS_DINODE_FMT_BTREE ||
536 (ip->i_df.if_flags & XFS_IFEXTENTS));
537
538 /*
539 * Check if this is offset is covered by a COW extents, and if yes use
540 * it directly instead of looking up anything in the data fork.
541 */
542 if (xfs_inode_has_cow_data(ip) &&
543 xfs_iext_lookup_extent(ip, ip->i_cowfp, offset_fsb, &icur, &imap))
544 cow_fsb = imap.br_startoff;
545 if (cow_fsb != NULLFILEOFF && cow_fsb <= offset_fsb) {
546 wpc->cow_seq = READ_ONCE(ip->i_cowfp->if_seq);
547 xfs_iunlock(ip, XFS_ILOCK_SHARED);
548
549 wpc->fork = XFS_COW_FORK;
550 goto allocate_blocks;
551 }
552
553 /*
554 * No COW extent overlap. Revalidate now that we may have updated
555 * ->cow_seq. If the data mapping is still valid, we're done.
556 */
557 if (xfs_imap_valid(wpc, ip, offset_fsb)) {
558 xfs_iunlock(ip, XFS_ILOCK_SHARED);
559 return 0;
560 }
561
562 /*
563 * If we don't have a valid map, now it's time to get a new one for this
564 * offset. This will convert delayed allocations (including COW ones)
565 * into real extents.
566 */
567 if (!xfs_iext_lookup_extent(ip, &ip->i_df, offset_fsb, &icur, &imap))
568 imap.br_startoff = end_fsb; /* fake a hole past EOF */
569 wpc->data_seq = READ_ONCE(ip->i_df.if_seq);
570 xfs_iunlock(ip, XFS_ILOCK_SHARED);
571
572 wpc->fork = XFS_DATA_FORK;
573
574 /* landed in a hole or beyond EOF? */
575 if (imap.br_startoff > offset_fsb) {
576 imap.br_blockcount = imap.br_startoff - offset_fsb;
577 imap.br_startoff = offset_fsb;
578 imap.br_startblock = HOLESTARTBLOCK;
579 imap.br_state = XFS_EXT_NORM;
580 }
581
582 /*
583 * Truncate to the next COW extent if there is one. This is the only
584 * opportunity to do this because we can skip COW fork lookups for the
585 * subsequent blocks in the mapping; however, the requirement to treat
586 * the COW range separately remains.
587 */
588 if (cow_fsb != NULLFILEOFF &&
589 cow_fsb < imap.br_startoff + imap.br_blockcount)
590 imap.br_blockcount = cow_fsb - imap.br_startoff;
591
592 /* got a delalloc extent? */
593 if (imap.br_startblock != HOLESTARTBLOCK &&
594 isnullstartblock(imap.br_startblock))
595 goto allocate_blocks;
596
597 wpc->imap = imap;
598 trace_xfs_map_blocks_found(ip, offset, count, wpc->fork, &imap);
599 return 0;
600allocate_blocks:
601 error = xfs_convert_blocks(wpc, ip, offset_fsb);
602 if (error) {
603 /*
604 * If we failed to find the extent in the COW fork we might have
605 * raced with a COW to data fork conversion or truncate.
606 * Restart the lookup to catch the extent in the data fork for
607 * the former case, but prevent additional retries to avoid
608 * looping forever for the latter case.
609 */
610 if (error == -EAGAIN && wpc->fork == XFS_COW_FORK && !retries++)
611 goto retry;
612 ASSERT(error != -EAGAIN);
613 return error;
614 }
615
616 /*
617 * Due to merging the return real extent might be larger than the
618 * original delalloc one. Trim the return extent to the next COW
619 * boundary again to force a re-lookup.
620 */
621 if (wpc->fork != XFS_COW_FORK && cow_fsb != NULLFILEOFF &&
622 cow_fsb < wpc->imap.br_startoff + wpc->imap.br_blockcount)
623 wpc->imap.br_blockcount = cow_fsb - wpc->imap.br_startoff;
624
625 ASSERT(wpc->imap.br_startoff <= offset_fsb);
626 ASSERT(wpc->imap.br_startoff + wpc->imap.br_blockcount > offset_fsb);
627 trace_xfs_map_blocks_alloc(ip, offset, count, wpc->fork, &imap);
628 return 0;
629}
630
631/*
632 * Submit the bio for an ioend. We are passed an ioend with a bio attached to
633 * it, and we submit that bio. The ioend may be used for multiple bio
634 * submissions, so we only want to allocate an append transaction for the ioend
635 * once. In the case of multiple bio submission, each bio will take an IO
636 * reference to the ioend to ensure that the ioend completion is only done once
637 * all bios have been submitted and the ioend is really done.
638 *
639 * If @status is non-zero, it means that we have a situation where some part of
640 * the submission process has failed after we have marked paged for writeback
641 * and unlocked them. In this situation, we need to fail the bio and ioend
642 * rather than submit it to IO. This typically only happens on a filesystem
643 * shutdown.
644 */
645STATIC int
646xfs_submit_ioend(
647 struct writeback_control *wbc,
648 struct xfs_ioend *ioend,
649 int status)
650{
651 unsigned int nofs_flag;
652
653 /*
654 * We can allocate memory here while doing writeback on behalf of
655 * memory reclaim. To avoid memory allocation deadlocks set the
656 * task-wide nofs context for the following operations.
657 */
658 nofs_flag = memalloc_nofs_save();
659
660 /* Convert CoW extents to regular */
661 if (!status && ioend->io_fork == XFS_COW_FORK) {
662 status = xfs_reflink_convert_cow(XFS_I(ioend->io_inode),
663 ioend->io_offset, ioend->io_size);
664 }
665
666 /* Reserve log space if we might write beyond the on-disk inode size. */
667 if (!status &&
668 (ioend->io_fork == XFS_COW_FORK ||
669 ioend->io_state != XFS_EXT_UNWRITTEN) &&
670 xfs_ioend_is_append(ioend) &&
671 !ioend->io_append_trans)
672 status = xfs_setfilesize_trans_alloc(ioend);
673
674 memalloc_nofs_restore(nofs_flag);
675
676 ioend->io_bio->bi_private = ioend;
677 ioend->io_bio->bi_end_io = xfs_end_bio;
678
679 /*
680 * If we are failing the IO now, just mark the ioend with an
681 * error and finish it. This will run IO completion immediately
682 * as there is only one reference to the ioend at this point in
683 * time.
684 */
685 if (status) {
686 ioend->io_bio->bi_status = errno_to_blk_status(status);
687 bio_endio(ioend->io_bio);
688 return status;
689 }
690
691 submit_bio(ioend->io_bio);
692 return 0;
693}
694
695static struct xfs_ioend *
696xfs_alloc_ioend(
697 struct inode *inode,
698 int fork,
699 xfs_exntst_t state,
700 xfs_off_t offset,
701 struct block_device *bdev,
702 sector_t sector,
703 struct writeback_control *wbc)
704{
705 struct xfs_ioend *ioend;
706 struct bio *bio;
707
708 bio = bio_alloc_bioset(GFP_NOFS, BIO_MAX_PAGES, &xfs_ioend_bioset);
709 bio_set_dev(bio, bdev);
710 bio->bi_iter.bi_sector = sector;
711 bio->bi_opf = REQ_OP_WRITE | wbc_to_write_flags(wbc);
712 bio->bi_write_hint = inode->i_write_hint;
713 wbc_init_bio(wbc, bio);
714
715 ioend = container_of(bio, struct xfs_ioend, io_inline_bio);
716 INIT_LIST_HEAD(&ioend->io_list);
717 ioend->io_fork = fork;
718 ioend->io_state = state;
719 ioend->io_inode = inode;
720 ioend->io_size = 0;
721 ioend->io_offset = offset;
722 ioend->io_append_trans = NULL;
723 ioend->io_bio = bio;
724 return ioend;
725}
726
727/*
728 * Allocate a new bio, and chain the old bio to the new one.
729 *
730 * Note that we have to do perform the chaining in this unintuitive order
731 * so that the bi_private linkage is set up in the right direction for the
732 * traversal in xfs_destroy_ioend().
733 */
734static struct bio *
735xfs_chain_bio(
736 struct bio *prev)
737{
738 struct bio *new;
739
740 new = bio_alloc(GFP_NOFS, BIO_MAX_PAGES);
741 bio_copy_dev(new, prev);/* also copies over blkcg information */
742 new->bi_iter.bi_sector = bio_end_sector(prev);
743 new->bi_opf = prev->bi_opf;
744 new->bi_write_hint = prev->bi_write_hint;
745
746 bio_chain(prev, new);
747 bio_get(prev); /* for xfs_destroy_ioend */
748 submit_bio(prev);
749 return new;
750}
751
752/*
753 * Test to see if we have an existing ioend structure that we could append to
754 * first, otherwise finish off the current ioend and start another.
755 */
756STATIC void
757xfs_add_to_ioend(
758 struct inode *inode,
759 xfs_off_t offset,
760 struct page *page,
761 struct iomap_page *iop,
762 struct xfs_writepage_ctx *wpc,
763 struct writeback_control *wbc,
764 struct list_head *iolist)
765{
766 struct xfs_inode *ip = XFS_I(inode);
767 struct xfs_mount *mp = ip->i_mount;
768 struct block_device *bdev = xfs_find_bdev_for_inode(inode);
769 unsigned len = i_blocksize(inode);
770 unsigned poff = offset & (PAGE_SIZE - 1);
771 bool merged, same_page = false;
772 sector_t sector;
773
774 sector = xfs_fsb_to_db(ip, wpc->imap.br_startblock) +
775 ((offset - XFS_FSB_TO_B(mp, wpc->imap.br_startoff)) >> 9);
776
777 if (!wpc->ioend ||
778 wpc->fork != wpc->ioend->io_fork ||
779 wpc->imap.br_state != wpc->ioend->io_state ||
780 sector != bio_end_sector(wpc->ioend->io_bio) ||
781 offset != wpc->ioend->io_offset + wpc->ioend->io_size) {
782 if (wpc->ioend)
783 list_add(&wpc->ioend->io_list, iolist);
784 wpc->ioend = xfs_alloc_ioend(inode, wpc->fork,
785 wpc->imap.br_state, offset, bdev, sector, wbc);
786 }
787
788 merged = __bio_try_merge_page(wpc->ioend->io_bio, page, len, poff,
789 &same_page);
790
791 if (iop && !same_page)
792 atomic_inc(&iop->write_count);
793
794 if (!merged) {
795 if (bio_full(wpc->ioend->io_bio, len))
796 wpc->ioend->io_bio = xfs_chain_bio(wpc->ioend->io_bio);
797 bio_add_page(wpc->ioend->io_bio, page, len, poff);
798 }
799
800 wpc->ioend->io_size += len;
801 wbc_account_cgroup_owner(wbc, page, len);
802}
803
804STATIC void
805xfs_vm_invalidatepage(
806 struct page *page,
807 unsigned int offset,
808 unsigned int length)
809{
810 trace_xfs_invalidatepage(page->mapping->host, page, offset, length);
811 iomap_invalidatepage(page, offset, length);
812}
813
814/*
815 * If the page has delalloc blocks on it, we need to punch them out before we
816 * invalidate the page. If we don't, we leave a stale delalloc mapping on the
817 * inode that can trip up a later direct I/O read operation on the same region.
818 *
819 * We prevent this by truncating away the delalloc regions on the page. Because
820 * they are delalloc, we can do this without needing a transaction. Indeed - if
821 * we get ENOSPC errors, we have to be able to do this truncation without a
822 * transaction as there is no space left for block reservation (typically why we
823 * see a ENOSPC in writeback).
824 */
825STATIC void
826xfs_aops_discard_page(
827 struct page *page)
828{
829 struct inode *inode = page->mapping->host;
830 struct xfs_inode *ip = XFS_I(inode);
831 struct xfs_mount *mp = ip->i_mount;
832 loff_t offset = page_offset(page);
833 xfs_fileoff_t start_fsb = XFS_B_TO_FSBT(mp, offset);
834 int error;
835
836 if (XFS_FORCED_SHUTDOWN(mp))
837 goto out_invalidate;
838
839 xfs_alert(mp,
840 "page discard on page "PTR_FMT", inode 0x%llx, offset %llu.",
841 page, ip->i_ino, offset);
842
843 error = xfs_bmap_punch_delalloc_range(ip, start_fsb,
844 PAGE_SIZE / i_blocksize(inode));
845 if (error && !XFS_FORCED_SHUTDOWN(mp))
846 xfs_alert(mp, "page discard unable to remove delalloc mapping.");
847out_invalidate:
848 xfs_vm_invalidatepage(page, 0, PAGE_SIZE);
849}
850
851/*
852 * We implement an immediate ioend submission policy here to avoid needing to
853 * chain multiple ioends and hence nest mempool allocations which can violate
854 * forward progress guarantees we need to provide. The current ioend we are
855 * adding blocks to is cached on the writepage context, and if the new block
856 * does not append to the cached ioend it will create a new ioend and cache that
857 * instead.
858 *
859 * If a new ioend is created and cached, the old ioend is returned and queued
860 * locally for submission once the entire page is processed or an error has been
861 * detected. While ioends are submitted immediately after they are completed,
862 * batching optimisations are provided by higher level block plugging.
863 *
864 * At the end of a writeback pass, there will be a cached ioend remaining on the
865 * writepage context that the caller will need to submit.
866 */
867static int
868xfs_writepage_map(
869 struct xfs_writepage_ctx *wpc,
870 struct writeback_control *wbc,
871 struct inode *inode,
872 struct page *page,
873 uint64_t end_offset)
874{
875 LIST_HEAD(submit_list);
876 struct iomap_page *iop = to_iomap_page(page);
877 unsigned len = i_blocksize(inode);
878 struct xfs_ioend *ioend, *next;
879 uint64_t file_offset; /* file offset of page */
880 int error = 0, count = 0, i;
881
882 ASSERT(iop || i_blocksize(inode) == PAGE_SIZE);
883 ASSERT(!iop || atomic_read(&iop->write_count) == 0);
884
885 /*
886 * Walk through the page to find areas to write back. If we run off the
887 * end of the current map or find the current map invalid, grab a new
888 * one.
889 */
890 for (i = 0, file_offset = page_offset(page);
891 i < (PAGE_SIZE >> inode->i_blkbits) && file_offset < end_offset;
892 i++, file_offset += len) {
893 if (iop && !test_bit(i, iop->uptodate))
894 continue;
895
896 error = xfs_map_blocks(wpc, inode, file_offset);
897 if (error)
898 break;
899 if (wpc->imap.br_startblock == HOLESTARTBLOCK)
900 continue;
901 xfs_add_to_ioend(inode, file_offset, page, iop, wpc, wbc,
902 &submit_list);
903 count++;
904 }
905
906 ASSERT(wpc->ioend || list_empty(&submit_list));
907 ASSERT(PageLocked(page));
908 ASSERT(!PageWriteback(page));
909
910 /*
911 * On error, we have to fail the ioend here because we may have set
912 * pages under writeback, we have to make sure we run IO completion to
913 * mark the error state of the IO appropriately, so we can't cancel the
914 * ioend directly here. That means we have to mark this page as under
915 * writeback if we included any blocks from it in the ioend chain so
916 * that completion treats it correctly.
917 *
918 * If we didn't include the page in the ioend, the on error we can
919 * simply discard and unlock it as there are no other users of the page
920 * now. The caller will still need to trigger submission of outstanding
921 * ioends on the writepage context so they are treated correctly on
922 * error.
923 */
924 if (unlikely(error)) {
925 if (!count) {
926 xfs_aops_discard_page(page);
927 ClearPageUptodate(page);
928 unlock_page(page);
929 goto done;
930 }
931
932 /*
933 * If the page was not fully cleaned, we need to ensure that the
934 * higher layers come back to it correctly. That means we need
935 * to keep the page dirty, and for WB_SYNC_ALL writeback we need
936 * to ensure the PAGECACHE_TAG_TOWRITE index mark is not removed
937 * so another attempt to write this page in this writeback sweep
938 * will be made.
939 */
940 set_page_writeback_keepwrite(page);
941 } else {
942 clear_page_dirty_for_io(page);
943 set_page_writeback(page);
944 }
945
946 unlock_page(page);
947
948 /*
949 * Preserve the original error if there was one, otherwise catch
950 * submission errors here and propagate into subsequent ioend
951 * submissions.
952 */
953 list_for_each_entry_safe(ioend, next, &submit_list, io_list) {
954 int error2;
955
956 list_del_init(&ioend->io_list);
957 error2 = xfs_submit_ioend(wbc, ioend, error);
958 if (error2 && !error)
959 error = error2;
960 }
961
962 /*
963 * We can end up here with no error and nothing to write only if we race
964 * with a partial page truncate on a sub-page block sized filesystem.
965 */
966 if (!count)
967 end_page_writeback(page);
968done:
969 mapping_set_error(page->mapping, error);
970 return error;
971}
972
973/*
974 * Write out a dirty page.
975 *
976 * For delalloc space on the page we need to allocate space and flush it.
977 * For unwritten space on the page we need to start the conversion to
978 * regular allocated space.
979 */
980STATIC int
981xfs_do_writepage(
982 struct page *page,
983 struct writeback_control *wbc,
984 void *data)
985{
986 struct xfs_writepage_ctx *wpc = data;
987 struct inode *inode = page->mapping->host;
988 loff_t offset;
989 uint64_t end_offset;
990 pgoff_t end_index;
991
992 trace_xfs_writepage(inode, page, 0, 0);
993
994 /*
995 * Refuse to write the page out if we are called from reclaim context.
996 *
997 * This avoids stack overflows when called from deeply used stacks in
998 * random callers for direct reclaim or memcg reclaim. We explicitly
999 * allow reclaim from kswapd as the stack usage there is relatively low.
1000 *
1001 * This should never happen except in the case of a VM regression so
1002 * warn about it.
1003 */
1004 if (WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
1005 PF_MEMALLOC))
1006 goto redirty;
1007
1008 /*
1009 * Given that we do not allow direct reclaim to call us, we should
1010 * never be called while in a filesystem transaction.
1011 */
1012 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC_NOFS))
1013 goto redirty;
1014
1015 /*
1016 * Is this page beyond the end of the file?
1017 *
1018 * The page index is less than the end_index, adjust the end_offset
1019 * to the highest offset that this page should represent.
1020 * -----------------------------------------------------
1021 * | file mapping | <EOF> |
1022 * -----------------------------------------------------
1023 * | Page ... | Page N-2 | Page N-1 | Page N | |
1024 * ^--------------------------------^----------|--------
1025 * | desired writeback range | see else |
1026 * ---------------------------------^------------------|
1027 */
1028 offset = i_size_read(inode);
1029 end_index = offset >> PAGE_SHIFT;
1030 if (page->index < end_index)
1031 end_offset = (xfs_off_t)(page->index + 1) << PAGE_SHIFT;
1032 else {
1033 /*
1034 * Check whether the page to write out is beyond or straddles
1035 * i_size or not.
1036 * -------------------------------------------------------
1037 * | file mapping | <EOF> |
1038 * -------------------------------------------------------
1039 * | Page ... | Page N-2 | Page N-1 | Page N | Beyond |
1040 * ^--------------------------------^-----------|---------
1041 * | | Straddles |
1042 * ---------------------------------^-----------|--------|
1043 */
1044 unsigned offset_into_page = offset & (PAGE_SIZE - 1);
1045
1046 /*
1047 * Skip the page if it is fully outside i_size, e.g. due to a
1048 * truncate operation that is in progress. We must redirty the
1049 * page so that reclaim stops reclaiming it. Otherwise
1050 * xfs_vm_releasepage() is called on it and gets confused.
1051 *
1052 * Note that the end_index is unsigned long, it would overflow
1053 * if the given offset is greater than 16TB on 32-bit system
1054 * and if we do check the page is fully outside i_size or not
1055 * via "if (page->index >= end_index + 1)" as "end_index + 1"
1056 * will be evaluated to 0. Hence this page will be redirtied
1057 * and be written out repeatedly which would result in an
1058 * infinite loop, the user program that perform this operation
1059 * will hang. Instead, we can verify this situation by checking
1060 * if the page to write is totally beyond the i_size or if it's
1061 * offset is just equal to the EOF.
1062 */
1063 if (page->index > end_index ||
1064 (page->index == end_index && offset_into_page == 0))
1065 goto redirty;
1066
1067 /*
1068 * The page straddles i_size. It must be zeroed out on each
1069 * and every writepage invocation because it may be mmapped.
1070 * "A file is mapped in multiples of the page size. For a file
1071 * that is not a multiple of the page size, the remaining
1072 * memory is zeroed when mapped, and writes to that region are
1073 * not written out to the file."
1074 */
1075 zero_user_segment(page, offset_into_page, PAGE_SIZE);
1076
1077 /* Adjust the end_offset to the end of file */
1078 end_offset = offset;
1079 }
1080
1081 return xfs_writepage_map(wpc, wbc, inode, page, end_offset);
1082
1083redirty:
1084 redirty_page_for_writepage(wbc, page);
1085 unlock_page(page);
1086 return 0;
1087}
1088
1089STATIC int
1090xfs_vm_writepage(
1091 struct page *page,
1092 struct writeback_control *wbc)
1093{
1094 struct xfs_writepage_ctx wpc = { };
1095 int ret;
1096
1097 ret = xfs_do_writepage(page, wbc, &wpc);
1098 if (wpc.ioend)
1099 ret = xfs_submit_ioend(wbc, wpc.ioend, ret);
1100 return ret;
1101}
1102
1103STATIC int
1104xfs_vm_writepages(
1105 struct address_space *mapping,
1106 struct writeback_control *wbc)
1107{
1108 struct xfs_writepage_ctx wpc = { };
1109 int ret;
1110
1111 xfs_iflags_clear(XFS_I(mapping->host), XFS_ITRUNCATED);
1112 ret = write_cache_pages(mapping, wbc, xfs_do_writepage, &wpc);
1113 if (wpc.ioend)
1114 ret = xfs_submit_ioend(wbc, wpc.ioend, ret);
1115 return ret;
1116}
1117
1118STATIC int
1119xfs_dax_writepages(
1120 struct address_space *mapping,
1121 struct writeback_control *wbc)
1122{
1123 xfs_iflags_clear(XFS_I(mapping->host), XFS_ITRUNCATED);
1124 return dax_writeback_mapping_range(mapping,
1125 xfs_find_bdev_for_inode(mapping->host), wbc);
1126}
1127
1128STATIC int
1129xfs_vm_releasepage(
1130 struct page *page,
1131 gfp_t gfp_mask)
1132{
1133 trace_xfs_releasepage(page->mapping->host, page, 0, 0);
1134 return iomap_releasepage(page, gfp_mask);
1135}
1136
1137STATIC sector_t
1138xfs_vm_bmap(
1139 struct address_space *mapping,
1140 sector_t block)
1141{
1142 struct xfs_inode *ip = XFS_I(mapping->host);
1143
1144 trace_xfs_vm_bmap(ip);
1145
1146 /*
1147 * The swap code (ab-)uses ->bmap to get a block mapping and then
1148 * bypasses the file system for actual I/O. We really can't allow
1149 * that on reflinks inodes, so we have to skip out here. And yes,
1150 * 0 is the magic code for a bmap error.
1151 *
1152 * Since we don't pass back blockdev info, we can't return bmap
1153 * information for rt files either.
1154 */
1155 if (xfs_is_cow_inode(ip) || XFS_IS_REALTIME_INODE(ip))
1156 return 0;
1157 return iomap_bmap(mapping, block, &xfs_iomap_ops);
1158}
1159
1160STATIC int
1161xfs_vm_readpage(
1162 struct file *unused,
1163 struct page *page)
1164{
1165 trace_xfs_vm_readpage(page->mapping->host, 1);
1166 return iomap_readpage(page, &xfs_iomap_ops);
1167}
1168
1169STATIC int
1170xfs_vm_readpages(
1171 struct file *unused,
1172 struct address_space *mapping,
1173 struct list_head *pages,
1174 unsigned nr_pages)
1175{
1176 trace_xfs_vm_readpages(mapping->host, nr_pages);
1177 return iomap_readpages(mapping, pages, nr_pages, &xfs_iomap_ops);
1178}
1179
1180static int
1181xfs_iomap_swapfile_activate(
1182 struct swap_info_struct *sis,
1183 struct file *swap_file,
1184 sector_t *span)
1185{
1186 sis->bdev = xfs_find_bdev_for_inode(file_inode(swap_file));
1187 return iomap_swapfile_activate(sis, swap_file, span, &xfs_iomap_ops);
1188}
1189
1190const struct address_space_operations xfs_address_space_operations = {
1191 .readpage = xfs_vm_readpage,
1192 .readpages = xfs_vm_readpages,
1193 .writepage = xfs_vm_writepage,
1194 .writepages = xfs_vm_writepages,
1195 .set_page_dirty = iomap_set_page_dirty,
1196 .releasepage = xfs_vm_releasepage,
1197 .invalidatepage = xfs_vm_invalidatepage,
1198 .bmap = xfs_vm_bmap,
1199 .direct_IO = noop_direct_IO,
1200 .migratepage = iomap_migrate_page,
1201 .is_partially_uptodate = iomap_is_partially_uptodate,
1202 .error_remove_page = generic_error_remove_page,
1203 .swap_activate = xfs_iomap_swapfile_activate,
1204};
1205
1206const struct address_space_operations xfs_dax_aops = {
1207 .writepages = xfs_dax_writepages,
1208 .direct_IO = noop_direct_IO,
1209 .set_page_dirty = noop_set_page_dirty,
1210 .invalidatepage = noop_invalidatepage,
1211 .swap_activate = xfs_iomap_swapfile_activate,
1212};