Merge tag 'x86-asm-2024-03-11' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip
[linux-2.6-block.git] / fs / iomap / buffered-io.c
CommitLineData
afc51aaa
DW
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (C) 2010 Red Hat, Inc.
30deff85 4 * Copyright (C) 2016-2023 Christoph Hellwig.
afc51aaa
DW
5 */
6#include <linux/module.h>
7#include <linux/compiler.h>
8#include <linux/fs.h>
9#include <linux/iomap.h>
10#include <linux/pagemap.h>
11#include <linux/uio.h>
12#include <linux/buffer_head.h>
13#include <linux/dax.h>
14#include <linux/writeback.h>
598ecfba 15#include <linux/list_sort.h>
afc51aaa
DW
16#include <linux/swap.h>
17#include <linux/bio.h>
18#include <linux/sched/signal.h>
19#include <linux/migrate.h>
9e91c572 20#include "trace.h"
afc51aaa
DW
21
22#include "../internal.h"
23
ebb7fb15
DC
24#define IOEND_BATCH_SIZE 4096
25
0af2b37d 26typedef int (*iomap_punch_t)(struct inode *inode, loff_t offset, loff_t length);
ab08b01e 27/*
4ce02c67 28 * Structure allocated for each folio to track per-block uptodate, dirty state
04f52c4e 29 * and I/O completions.
ab08b01e 30 */
04f52c4e 31struct iomap_folio_state {
04f52c4e 32 spinlock_t state_lock;
f45b494e
MWO
33 unsigned int read_bytes_pending;
34 atomic_t write_bytes_pending;
4ce02c67
RHI
35
36 /*
37 * Each block has two bits in this bitmap:
38 * Bits [0..blocks_per_folio) has the uptodate status.
39 * Bits [b_p_f...(2*b_p_f)) has the dirty status.
40 */
04f52c4e 41 unsigned long state[];
ab08b01e
CH
42};
43
598ecfba
CH
44static struct bio_set iomap_ioend_bioset;
45
cc86181a
RHI
46static inline bool ifs_is_fully_uptodate(struct folio *folio,
47 struct iomap_folio_state *ifs)
48{
49 struct inode *inode = folio->mapping->host;
50
51 return bitmap_full(ifs->state, i_blocks_per_folio(inode, folio));
52}
53
54static inline bool ifs_block_is_uptodate(struct iomap_folio_state *ifs,
55 unsigned int block)
56{
57 return test_bit(block, ifs->state);
58}
59
279d5fc3 60static bool ifs_set_range_uptodate(struct folio *folio,
3ea5c76c
RHI
61 struct iomap_folio_state *ifs, size_t off, size_t len)
62{
63 struct inode *inode = folio->mapping->host;
64 unsigned int first_blk = off >> inode->i_blkbits;
65 unsigned int last_blk = (off + len - 1) >> inode->i_blkbits;
66 unsigned int nr_blks = last_blk - first_blk + 1;
3ea5c76c 67
3ea5c76c 68 bitmap_set(ifs->state, first_blk, nr_blks);
279d5fc3 69 return ifs_is_fully_uptodate(folio, ifs);
3ea5c76c
RHI
70}
71
72static void iomap_set_range_uptodate(struct folio *folio, size_t off,
73 size_t len)
74{
75 struct iomap_folio_state *ifs = folio->private;
279d5fc3
MWO
76 unsigned long flags;
77 bool uptodate = true;
3ea5c76c 78
279d5fc3
MWO
79 if (ifs) {
80 spin_lock_irqsave(&ifs->state_lock, flags);
81 uptodate = ifs_set_range_uptodate(folio, ifs, off, len);
82 spin_unlock_irqrestore(&ifs->state_lock, flags);
83 }
3ea5c76c 84
279d5fc3 85 if (uptodate)
3ea5c76c
RHI
86 folio_mark_uptodate(folio);
87}
88
4ce02c67
RHI
89static inline bool ifs_block_is_dirty(struct folio *folio,
90 struct iomap_folio_state *ifs, int block)
91{
92 struct inode *inode = folio->mapping->host;
93 unsigned int blks_per_folio = i_blocks_per_folio(inode, folio);
94
95 return test_bit(block + blks_per_folio, ifs->state);
96}
97
30deff85
CH
98static unsigned ifs_find_dirty_range(struct folio *folio,
99 struct iomap_folio_state *ifs, u64 *range_start, u64 range_end)
100{
101 struct inode *inode = folio->mapping->host;
102 unsigned start_blk =
103 offset_in_folio(folio, *range_start) >> inode->i_blkbits;
104 unsigned end_blk = min_not_zero(
105 offset_in_folio(folio, range_end) >> inode->i_blkbits,
106 i_blocks_per_folio(inode, folio));
107 unsigned nblks = 1;
108
109 while (!ifs_block_is_dirty(folio, ifs, start_blk))
110 if (++start_blk == end_blk)
111 return 0;
112
113 while (start_blk + nblks < end_blk) {
114 if (!ifs_block_is_dirty(folio, ifs, start_blk + nblks))
115 break;
116 nblks++;
117 }
118
119 *range_start = folio_pos(folio) + (start_blk << inode->i_blkbits);
120 return nblks << inode->i_blkbits;
121}
122
123static unsigned iomap_find_dirty_range(struct folio *folio, u64 *range_start,
124 u64 range_end)
125{
126 struct iomap_folio_state *ifs = folio->private;
127
128 if (*range_start >= range_end)
129 return 0;
130
131 if (ifs)
132 return ifs_find_dirty_range(folio, ifs, range_start, range_end);
133 return range_end - *range_start;
134}
135
4ce02c67
RHI
136static void ifs_clear_range_dirty(struct folio *folio,
137 struct iomap_folio_state *ifs, size_t off, size_t len)
138{
139 struct inode *inode = folio->mapping->host;
140 unsigned int blks_per_folio = i_blocks_per_folio(inode, folio);
141 unsigned int first_blk = (off >> inode->i_blkbits);
142 unsigned int last_blk = (off + len - 1) >> inode->i_blkbits;
143 unsigned int nr_blks = last_blk - first_blk + 1;
144 unsigned long flags;
145
146 spin_lock_irqsave(&ifs->state_lock, flags);
147 bitmap_clear(ifs->state, first_blk + blks_per_folio, nr_blks);
148 spin_unlock_irqrestore(&ifs->state_lock, flags);
149}
150
151static void iomap_clear_range_dirty(struct folio *folio, size_t off, size_t len)
152{
153 struct iomap_folio_state *ifs = folio->private;
154
155 if (ifs)
156 ifs_clear_range_dirty(folio, ifs, off, len);
157}
158
159static void ifs_set_range_dirty(struct folio *folio,
160 struct iomap_folio_state *ifs, size_t off, size_t len)
161{
162 struct inode *inode = folio->mapping->host;
163 unsigned int blks_per_folio = i_blocks_per_folio(inode, folio);
164 unsigned int first_blk = (off >> inode->i_blkbits);
165 unsigned int last_blk = (off + len - 1) >> inode->i_blkbits;
166 unsigned int nr_blks = last_blk - first_blk + 1;
167 unsigned long flags;
168
169 spin_lock_irqsave(&ifs->state_lock, flags);
170 bitmap_set(ifs->state, first_blk + blks_per_folio, nr_blks);
171 spin_unlock_irqrestore(&ifs->state_lock, flags);
172}
173
174static void iomap_set_range_dirty(struct folio *folio, size_t off, size_t len)
175{
176 struct iomap_folio_state *ifs = folio->private;
177
178 if (ifs)
179 ifs_set_range_dirty(folio, ifs, off, len);
180}
181
04f52c4e
RHI
182static struct iomap_folio_state *ifs_alloc(struct inode *inode,
183 struct folio *folio, unsigned int flags)
afc51aaa 184{
04f52c4e 185 struct iomap_folio_state *ifs = folio->private;
435d44b3 186 unsigned int nr_blocks = i_blocks_per_folio(inode, folio);
9753b868 187 gfp_t gfp;
afc51aaa 188
04f52c4e
RHI
189 if (ifs || nr_blocks <= 1)
190 return ifs;
afc51aaa 191
9753b868
SR
192 if (flags & IOMAP_NOWAIT)
193 gfp = GFP_NOWAIT;
194 else
195 gfp = GFP_NOFS | __GFP_NOFAIL;
196
4ce02c67
RHI
197 /*
198 * ifs->state tracks two sets of state flags when the
199 * filesystem block size is smaller than the folio size.
200 * The first state tracks per-block uptodate and the
201 * second tracks per-block dirty state.
202 */
203 ifs = kzalloc(struct_size(ifs, state,
204 BITS_TO_LONGS(2 * nr_blocks)), gfp);
205 if (!ifs)
206 return ifs;
207
208 spin_lock_init(&ifs->state_lock);
209 if (folio_test_uptodate(folio))
210 bitmap_set(ifs->state, 0, nr_blocks);
211 if (folio_test_dirty(folio))
212 bitmap_set(ifs->state, nr_blocks, nr_blocks);
213 folio_attach_private(folio, ifs);
214
04f52c4e 215 return ifs;
afc51aaa
DW
216}
217
04f52c4e 218static void ifs_free(struct folio *folio)
afc51aaa 219{
04f52c4e 220 struct iomap_folio_state *ifs = folio_detach_private(folio);
afc51aaa 221
04f52c4e 222 if (!ifs)
afc51aaa 223 return;
f45b494e 224 WARN_ON_ONCE(ifs->read_bytes_pending != 0);
04f52c4e 225 WARN_ON_ONCE(atomic_read(&ifs->write_bytes_pending));
cc86181a 226 WARN_ON_ONCE(ifs_is_fully_uptodate(folio, ifs) !=
c46e8324 227 folio_test_uptodate(folio));
04f52c4e 228 kfree(ifs);
afc51aaa
DW
229}
230
231/*
431c0566 232 * Calculate the range inside the folio that we actually need to read.
afc51aaa 233 */
431c0566
MWO
234static void iomap_adjust_read_range(struct inode *inode, struct folio *folio,
235 loff_t *pos, loff_t length, size_t *offp, size_t *lenp)
afc51aaa 236{
04f52c4e 237 struct iomap_folio_state *ifs = folio->private;
afc51aaa
DW
238 loff_t orig_pos = *pos;
239 loff_t isize = i_size_read(inode);
240 unsigned block_bits = inode->i_blkbits;
241 unsigned block_size = (1 << block_bits);
431c0566
MWO
242 size_t poff = offset_in_folio(folio, *pos);
243 size_t plen = min_t(loff_t, folio_size(folio) - poff, length);
afc51aaa
DW
244 unsigned first = poff >> block_bits;
245 unsigned last = (poff + plen - 1) >> block_bits;
246
247 /*
f1f264b4 248 * If the block size is smaller than the page size, we need to check the
afc51aaa
DW
249 * per-block uptodate status and adjust the offset and length if needed
250 * to avoid reading in already uptodate ranges.
251 */
04f52c4e 252 if (ifs) {
afc51aaa
DW
253 unsigned int i;
254
255 /* move forward for each leading block marked uptodate */
256 for (i = first; i <= last; i++) {
cc86181a 257 if (!ifs_block_is_uptodate(ifs, i))
afc51aaa
DW
258 break;
259 *pos += block_size;
260 poff += block_size;
261 plen -= block_size;
262 first++;
263 }
264
265 /* truncate len if we find any trailing uptodate block(s) */
266 for ( ; i <= last; i++) {
cc86181a 267 if (ifs_block_is_uptodate(ifs, i)) {
afc51aaa
DW
268 plen -= (last - i + 1) * block_size;
269 last = i - 1;
270 break;
271 }
272 }
273 }
274
275 /*
f1f264b4 276 * If the extent spans the block that contains the i_size, we need to
afc51aaa
DW
277 * handle both halves separately so that we properly zero data in the
278 * page cache for blocks that are entirely outside of i_size.
279 */
280 if (orig_pos <= isize && orig_pos + length > isize) {
431c0566 281 unsigned end = offset_in_folio(folio, isize - 1) >> block_bits;
afc51aaa
DW
282
283 if (first <= end && last > end)
284 plen -= (last - end) * block_size;
285 }
286
287 *offp = poff;
288 *lenp = plen;
289}
290
f45b494e 291static void iomap_finish_folio_read(struct folio *folio, size_t off,
8ffd74e9 292 size_t len, int error)
afc51aaa 293{
04f52c4e 294 struct iomap_folio_state *ifs = folio->private;
f45b494e
MWO
295 bool uptodate = !error;
296 bool finished = true;
afc51aaa 297
f45b494e
MWO
298 if (ifs) {
299 unsigned long flags;
300
301 spin_lock_irqsave(&ifs->state_lock, flags);
302 if (!error)
303 uptodate = ifs_set_range_uptodate(folio, ifs, off, len);
304 ifs->read_bytes_pending -= len;
305 finished = !ifs->read_bytes_pending;
306 spin_unlock_irqrestore(&ifs->state_lock, flags);
afc51aaa
DW
307 }
308
f45b494e
MWO
309 if (error)
310 folio_set_error(folio);
f45b494e 311 if (finished)
7a4847e5 312 folio_end_read(folio, uptodate);
afc51aaa
DW
313}
314
8ffd74e9 315static void iomap_read_end_io(struct bio *bio)
afc51aaa
DW
316{
317 int error = blk_status_to_errno(bio->bi_status);
8ffd74e9 318 struct folio_iter fi;
afc51aaa 319
8ffd74e9
MWO
320 bio_for_each_folio_all(fi, bio)
321 iomap_finish_folio_read(fi.folio, fi.offset, fi.length, error);
afc51aaa
DW
322 bio_put(bio);
323}
324
325struct iomap_readpage_ctx {
3aa9c659
MWO
326 struct folio *cur_folio;
327 bool cur_folio_in_bio;
afc51aaa 328 struct bio *bio;
9d24a13a 329 struct readahead_control *rac;
afc51aaa
DW
330};
331
5ad448ce
AG
332/**
333 * iomap_read_inline_data - copy inline data into the page cache
334 * @iter: iteration structure
874628a2 335 * @folio: folio to copy to
5ad448ce 336 *
874628a2 337 * Copy the inline data in @iter into @folio and zero out the rest of the folio.
5ad448ce
AG
338 * Only a single IOMAP_INLINE extent is allowed at the end of each file.
339 * Returns zero for success to complete the read, or the usual negative errno.
340 */
341static int iomap_read_inline_data(const struct iomap_iter *iter,
874628a2 342 struct folio *folio)
afc51aaa 343{
fad0a1ab 344 const struct iomap *iomap = iomap_iter_srcmap(iter);
1b5c1e36 345 size_t size = i_size_read(iter->inode) - iomap->offset;
431c0566 346 size_t offset = offset_in_folio(folio, iomap->offset);
afc51aaa 347
874628a2 348 if (folio_test_uptodate(folio))
5ad448ce 349 return 0;
afc51aaa 350
69f4a26c
GX
351 if (WARN_ON_ONCE(size > iomap->length))
352 return -EIO;
431c0566 353 if (offset > 0)
3ea5c76c 354 ifs_alloc(iter->inode, folio, iter->flags);
afc51aaa 355
6eaa266b
MWO
356 folio_fill_tail(folio, offset, iomap->inline_data, size);
357 iomap_set_range_uptodate(folio, offset, folio_size(folio) - offset);
5ad448ce 358 return 0;
afc51aaa
DW
359}
360
fad0a1ab 361static inline bool iomap_block_needs_zeroing(const struct iomap_iter *iter,
1b5c1e36 362 loff_t pos)
009d8d84 363{
fad0a1ab 364 const struct iomap *srcmap = iomap_iter_srcmap(iter);
1b5c1e36
CH
365
366 return srcmap->type != IOMAP_MAPPED ||
367 (srcmap->flags & IOMAP_F_NEW) ||
368 pos >= i_size_read(iter->inode);
009d8d84
CH
369}
370
fad0a1ab 371static loff_t iomap_readpage_iter(const struct iomap_iter *iter,
f6d48000 372 struct iomap_readpage_ctx *ctx, loff_t offset)
afc51aaa 373{
fad0a1ab 374 const struct iomap *iomap = &iter->iomap;
f6d48000
CH
375 loff_t pos = iter->pos + offset;
376 loff_t length = iomap_length(iter) - offset;
3aa9c659 377 struct folio *folio = ctx->cur_folio;
04f52c4e 378 struct iomap_folio_state *ifs;
afc51aaa 379 loff_t orig_pos = pos;
431c0566 380 size_t poff, plen;
afc51aaa
DW
381 sector_t sector;
382
5ad448ce 383 if (iomap->type == IOMAP_INLINE)
874628a2 384 return iomap_read_inline_data(iter, folio);
afc51aaa
DW
385
386 /* zero post-eof blocks as the page may be mapped */
04f52c4e 387 ifs = ifs_alloc(iter->inode, folio, iter->flags);
431c0566 388 iomap_adjust_read_range(iter->inode, folio, &pos, length, &poff, &plen);
afc51aaa
DW
389 if (plen == 0)
390 goto done;
391
1b5c1e36 392 if (iomap_block_needs_zeroing(iter, pos)) {
431c0566 393 folio_zero_range(folio, poff, plen);
3ea5c76c 394 iomap_set_range_uptodate(folio, poff, plen);
afc51aaa
DW
395 goto done;
396 }
397
3aa9c659 398 ctx->cur_folio_in_bio = true;
f45b494e
MWO
399 if (ifs) {
400 spin_lock_irq(&ifs->state_lock);
401 ifs->read_bytes_pending += plen;
402 spin_unlock_irq(&ifs->state_lock);
403 }
afc51aaa 404
afc51aaa 405 sector = iomap_sector(iomap, pos);
d0364f94
CH
406 if (!ctx->bio ||
407 bio_end_sector(ctx->bio) != sector ||
431c0566 408 !bio_add_folio(ctx->bio, folio, plen, poff)) {
3aa9c659 409 gfp_t gfp = mapping_gfp_constraint(folio->mapping, GFP_KERNEL);
457df33e 410 gfp_t orig_gfp = gfp;
5f7136db 411 unsigned int nr_vecs = DIV_ROUND_UP(length, PAGE_SIZE);
afc51aaa
DW
412
413 if (ctx->bio)
414 submit_bio(ctx->bio);
415
9d24a13a 416 if (ctx->rac) /* same as readahead_gfp_mask */
afc51aaa 417 gfp |= __GFP_NORETRY | __GFP_NOWARN;
07888c66
CH
418 ctx->bio = bio_alloc(iomap->bdev, bio_max_segs(nr_vecs),
419 REQ_OP_READ, gfp);
457df33e
MWO
420 /*
421 * If the bio_alloc fails, try it again for a single page to
422 * avoid having to deal with partial page reads. This emulates
f132ab7d 423 * what do_mpage_read_folio does.
457df33e 424 */
07888c66
CH
425 if (!ctx->bio) {
426 ctx->bio = bio_alloc(iomap->bdev, 1, REQ_OP_READ,
427 orig_gfp);
428 }
9d24a13a 429 if (ctx->rac)
afc51aaa
DW
430 ctx->bio->bi_opf |= REQ_RAHEAD;
431 ctx->bio->bi_iter.bi_sector = sector;
afc51aaa 432 ctx->bio->bi_end_io = iomap_read_end_io;
c2478469 433 bio_add_folio_nofail(ctx->bio, folio, plen, poff);
afc51aaa 434 }
431c0566 435
afc51aaa
DW
436done:
437 /*
438 * Move the caller beyond our range so that it keeps making progress.
f1f264b4 439 * For that, we have to include any leading non-uptodate ranges, but
afc51aaa
DW
440 * we can skip trailing ones as they will be handled in the next
441 * iteration.
442 */
443 return pos - orig_pos + plen;
444}
445
7479c505 446int iomap_read_folio(struct folio *folio, const struct iomap_ops *ops)
afc51aaa 447{
f6d48000 448 struct iomap_iter iter = {
3aa9c659
MWO
449 .inode = folio->mapping->host,
450 .pos = folio_pos(folio),
451 .len = folio_size(folio),
f6d48000
CH
452 };
453 struct iomap_readpage_ctx ctx = {
3aa9c659 454 .cur_folio = folio,
f6d48000
CH
455 };
456 int ret;
afc51aaa 457
3aa9c659 458 trace_iomap_readpage(iter.inode, 1);
9e91c572 459
f6d48000
CH
460 while ((ret = iomap_iter(&iter, ops)) > 0)
461 iter.processed = iomap_readpage_iter(&iter, &ctx, 0);
462
463 if (ret < 0)
3aa9c659 464 folio_set_error(folio);
afc51aaa
DW
465
466 if (ctx.bio) {
467 submit_bio(ctx.bio);
3aa9c659 468 WARN_ON_ONCE(!ctx.cur_folio_in_bio);
afc51aaa 469 } else {
3aa9c659
MWO
470 WARN_ON_ONCE(ctx.cur_folio_in_bio);
471 folio_unlock(folio);
afc51aaa
DW
472 }
473
474 /*
2c69e205 475 * Just like mpage_readahead and block_read_full_folio, we always
7479c505 476 * return 0 and just set the folio error flag on errors. This
f1f264b4 477 * should be cleaned up throughout the stack eventually.
afc51aaa
DW
478 */
479 return 0;
480}
7479c505 481EXPORT_SYMBOL_GPL(iomap_read_folio);
afc51aaa 482
fad0a1ab 483static loff_t iomap_readahead_iter(const struct iomap_iter *iter,
f6d48000 484 struct iomap_readpage_ctx *ctx)
afc51aaa 485{
f6d48000 486 loff_t length = iomap_length(iter);
afc51aaa
DW
487 loff_t done, ret;
488
489 for (done = 0; done < length; done += ret) {
3aa9c659
MWO
490 if (ctx->cur_folio &&
491 offset_in_folio(ctx->cur_folio, iter->pos + done) == 0) {
492 if (!ctx->cur_folio_in_bio)
493 folio_unlock(ctx->cur_folio);
494 ctx->cur_folio = NULL;
afc51aaa 495 }
3aa9c659
MWO
496 if (!ctx->cur_folio) {
497 ctx->cur_folio = readahead_folio(ctx->rac);
498 ctx->cur_folio_in_bio = false;
afc51aaa 499 }
f6d48000 500 ret = iomap_readpage_iter(iter, ctx, done);
d8af404f
AG
501 if (ret <= 0)
502 return ret;
afc51aaa
DW
503 }
504
505 return done;
506}
507
9d24a13a
MWO
508/**
509 * iomap_readahead - Attempt to read pages from a file.
510 * @rac: Describes the pages to be read.
511 * @ops: The operations vector for the filesystem.
512 *
513 * This function is for filesystems to call to implement their readahead
514 * address_space operation.
515 *
516 * Context: The @ops callbacks may submit I/O (eg to read the addresses of
517 * blocks from disc), and may wait for it. The caller may be trying to
518 * access a different page, and so sleeping excessively should be avoided.
519 * It may allocate memory, but should avoid costly allocations. This
520 * function is called with memalloc_nofs set, so allocations will not cause
521 * the filesystem to be reentered.
522 */
523void iomap_readahead(struct readahead_control *rac, const struct iomap_ops *ops)
afc51aaa 524{
f6d48000
CH
525 struct iomap_iter iter = {
526 .inode = rac->mapping->host,
527 .pos = readahead_pos(rac),
528 .len = readahead_length(rac),
529 };
afc51aaa 530 struct iomap_readpage_ctx ctx = {
9d24a13a 531 .rac = rac,
afc51aaa 532 };
afc51aaa 533
f6d48000 534 trace_iomap_readahead(rac->mapping->host, readahead_count(rac));
9e91c572 535
f6d48000
CH
536 while (iomap_iter(&iter, ops) > 0)
537 iter.processed = iomap_readahead_iter(&iter, &ctx);
9d24a13a 538
afc51aaa
DW
539 if (ctx.bio)
540 submit_bio(ctx.bio);
3aa9c659
MWO
541 if (ctx.cur_folio) {
542 if (!ctx.cur_folio_in_bio)
543 folio_unlock(ctx.cur_folio);
afc51aaa 544 }
afc51aaa 545}
9d24a13a 546EXPORT_SYMBOL_GPL(iomap_readahead);
afc51aaa
DW
547
548/*
2e7e80f7 549 * iomap_is_partially_uptodate checks whether blocks within a folio are
afc51aaa
DW
550 * uptodate or not.
551 *
2e7e80f7
MWO
552 * Returns true if all blocks which correspond to the specified part
553 * of the folio are uptodate.
afc51aaa 554 */
2e7e80f7 555bool iomap_is_partially_uptodate(struct folio *folio, size_t from, size_t count)
afc51aaa 556{
04f52c4e 557 struct iomap_folio_state *ifs = folio->private;
2e7e80f7 558 struct inode *inode = folio->mapping->host;
2e7e80f7 559 unsigned first, last, i;
afc51aaa 560
04f52c4e 561 if (!ifs)
2e7e80f7 562 return false;
afc51aaa 563
2756c818
MWO
564 /* Caller's range may extend past the end of this folio */
565 count = min(folio_size(folio) - from, count);
afc51aaa 566
2756c818 567 /* First and last blocks in range within folio */
afc51aaa 568 first = from >> inode->i_blkbits;
2756c818 569 last = (from + count - 1) >> inode->i_blkbits;
afc51aaa 570
2e7e80f7 571 for (i = first; i <= last; i++)
cc86181a 572 if (!ifs_block_is_uptodate(ifs, i))
2e7e80f7
MWO
573 return false;
574 return true;
afc51aaa
DW
575}
576EXPORT_SYMBOL_GPL(iomap_is_partially_uptodate);
577
98321b51
AG
578/**
579 * iomap_get_folio - get a folio reference for writing
580 * @iter: iteration structure
581 * @pos: start offset of write
d6bb59a9 582 * @len: Suggested size of folio to create.
98321b51
AG
583 *
584 * Returns a locked reference to the folio at @pos, or an error pointer if the
585 * folio could not be obtained.
586 */
d6bb59a9 587struct folio *iomap_get_folio(struct iomap_iter *iter, loff_t pos, size_t len)
98321b51 588{
ffc143db 589 fgf_t fgp = FGP_WRITEBEGIN | FGP_NOFS;
98321b51
AG
590
591 if (iter->flags & IOMAP_NOWAIT)
592 fgp |= FGP_NOWAIT;
d6bb59a9 593 fgp |= fgf_set_order(len);
98321b51 594
66dabbb6 595 return __filemap_get_folio(iter->inode->i_mapping, pos >> PAGE_SHIFT,
98321b51 596 fgp, mapping_gfp_mask(iter->inode->i_mapping));
98321b51
AG
597}
598EXPORT_SYMBOL_GPL(iomap_get_folio);
599
8597447d 600bool iomap_release_folio(struct folio *folio, gfp_t gfp_flags)
afc51aaa 601{
8597447d 602 trace_iomap_release_folio(folio->mapping->host, folio_pos(folio),
39f16c83 603 folio_size(folio));
9e91c572 604
afc51aaa 605 /*
7a8eb01b
MWO
606 * If the folio is dirty, we refuse to release our metadata because
607 * it may be partially dirty. Once we track per-block dirty state,
608 * we can release the metadata if every block is dirty.
afc51aaa 609 */
7a8eb01b 610 if (folio_test_dirty(folio))
8597447d 611 return false;
04f52c4e 612 ifs_free(folio);
8597447d 613 return true;
afc51aaa 614}
8597447d 615EXPORT_SYMBOL_GPL(iomap_release_folio);
afc51aaa 616
8306a5f5 617void iomap_invalidate_folio(struct folio *folio, size_t offset, size_t len)
afc51aaa 618{
d82354f6 619 trace_iomap_invalidate_folio(folio->mapping->host,
1241ebec 620 folio_pos(folio) + offset, len);
9e91c572 621
afc51aaa 622 /*
60d82310
MWO
623 * If we're invalidating the entire folio, clear the dirty state
624 * from it and release it to avoid unnecessary buildup of the LRU.
afc51aaa 625 */
8306a5f5
MWO
626 if (offset == 0 && len == folio_size(folio)) {
627 WARN_ON_ONCE(folio_test_writeback(folio));
628 folio_cancel_dirty(folio);
04f52c4e 629 ifs_free(folio);
afc51aaa
DW
630 }
631}
8306a5f5
MWO
632EXPORT_SYMBOL_GPL(iomap_invalidate_folio);
633
4ce02c67
RHI
634bool iomap_dirty_folio(struct address_space *mapping, struct folio *folio)
635{
636 struct inode *inode = mapping->host;
637 size_t len = folio_size(folio);
638
639 ifs_alloc(inode, folio, 0);
640 iomap_set_range_dirty(folio, 0, len);
641 return filemap_dirty_folio(mapping, folio);
642}
643EXPORT_SYMBOL_GPL(iomap_dirty_folio);
644
afc51aaa
DW
645static void
646iomap_write_failed(struct inode *inode, loff_t pos, unsigned len)
647{
648 loff_t i_size = i_size_read(inode);
649
650 /*
651 * Only truncate newly allocated pages beyoned EOF, even if the
652 * write started inside the existing inode size.
653 */
654 if (pos + len > i_size)
b71450e2
AG
655 truncate_pagecache_range(inode, max(pos, i_size),
656 pos + len - 1);
afc51aaa
DW
657}
658
431c0566
MWO
659static int iomap_read_folio_sync(loff_t block_start, struct folio *folio,
660 size_t poff, size_t plen, const struct iomap *iomap)
afc51aaa
DW
661{
662 struct bio_vec bvec;
663 struct bio bio;
664
49add496 665 bio_init(&bio, iomap->bdev, &bvec, 1, REQ_OP_READ);
afc51aaa 666 bio.bi_iter.bi_sector = iomap_sector(iomap, block_start);
c2478469 667 bio_add_folio_nofail(&bio, folio, plen, poff);
afc51aaa
DW
668 return submit_bio_wait(&bio);
669}
670
fad0a1ab 671static int __iomap_write_begin(const struct iomap_iter *iter, loff_t pos,
bc6123a8 672 size_t len, struct folio *folio)
afc51aaa 673{
fad0a1ab 674 const struct iomap *srcmap = iomap_iter_srcmap(iter);
04f52c4e 675 struct iomap_folio_state *ifs;
1b5c1e36 676 loff_t block_size = i_blocksize(iter->inode);
6cc19c5f
NB
677 loff_t block_start = round_down(pos, block_size);
678 loff_t block_end = round_up(pos + len, block_size);
cae2de69 679 unsigned int nr_blocks = i_blocks_per_folio(iter->inode, folio);
431c0566
MWO
680 size_t from = offset_in_folio(folio, pos), to = from + len;
681 size_t poff, plen;
afc51aaa 682
a01b8f22 683 /*
35d30c9c 684 * If the write or zeroing completely overlaps the current folio, then
a01b8f22
RHI
685 * entire folio will be dirtied so there is no need for
686 * per-block state tracking structures to be attached to this folio.
35d30c9c
DW
687 * For the unshare case, we must read in the ondisk contents because we
688 * are not changing pagecache contents.
a01b8f22 689 */
35d30c9c 690 if (!(iter->flags & IOMAP_UNSHARE) && pos <= folio_pos(folio) &&
a01b8f22 691 pos + len >= folio_pos(folio) + folio_size(folio))
afc51aaa
DW
692 return 0;
693
04f52c4e
RHI
694 ifs = ifs_alloc(iter->inode, folio, iter->flags);
695 if ((iter->flags & IOMAP_NOWAIT) && !ifs && nr_blocks > 1)
cae2de69 696 return -EAGAIN;
9753b868 697
a01b8f22
RHI
698 if (folio_test_uptodate(folio))
699 return 0;
700 folio_clear_error(folio);
701
afc51aaa 702 do {
431c0566 703 iomap_adjust_read_range(iter->inode, folio, &block_start,
afc51aaa
DW
704 block_end - block_start, &poff, &plen);
705 if (plen == 0)
706 break;
707
b74b1293 708 if (!(iter->flags & IOMAP_UNSHARE) &&
32a38a49 709 (from <= poff || from >= poff + plen) &&
d3b40439
CH
710 (to <= poff || to >= poff + plen))
711 continue;
712
1b5c1e36 713 if (iomap_block_needs_zeroing(iter, block_start)) {
b74b1293 714 if (WARN_ON_ONCE(iter->flags & IOMAP_UNSHARE))
32a38a49 715 return -EIO;
431c0566 716 folio_zero_segments(folio, poff, from, to, poff + plen);
14284fed 717 } else {
cae2de69
SR
718 int status;
719
720 if (iter->flags & IOMAP_NOWAIT)
721 return -EAGAIN;
722
723 status = iomap_read_folio_sync(block_start, folio,
14284fed
MWO
724 poff, plen, srcmap);
725 if (status)
726 return status;
afc51aaa 727 }
3ea5c76c 728 iomap_set_range_uptodate(folio, poff, plen);
afc51aaa
DW
729 } while ((block_start += plen) < block_end);
730
d3b40439 731 return 0;
afc51aaa
DW
732}
733
07c22b56
AG
734static struct folio *__iomap_get_folio(struct iomap_iter *iter, loff_t pos,
735 size_t len)
736{
471859f5 737 const struct iomap_folio_ops *folio_ops = iter->iomap.folio_ops;
07c22b56 738
471859f5
AG
739 if (folio_ops && folio_ops->get_folio)
740 return folio_ops->get_folio(iter, pos, len);
07c22b56 741 else
d6bb59a9 742 return iomap_get_folio(iter, pos, len);
07c22b56
AG
743}
744
7a70a508
AG
745static void __iomap_put_folio(struct iomap_iter *iter, loff_t pos, size_t ret,
746 struct folio *folio)
747{
471859f5 748 const struct iomap_folio_ops *folio_ops = iter->iomap.folio_ops;
7a70a508 749
471859f5
AG
750 if (folio_ops && folio_ops->put_folio) {
751 folio_ops->put_folio(iter->inode, pos, ret, folio);
9060bc4d 752 } else {
7a70a508 753 folio_unlock(folio);
7a70a508 754 folio_put(folio);
80baab88 755 }
7a70a508
AG
756}
757
fad0a1ab 758static int iomap_write_begin_inline(const struct iomap_iter *iter,
bc6123a8 759 struct folio *folio)
69f4a26c
GX
760{
761 /* needs more work for the tailpacking case; disable for now */
1b5c1e36 762 if (WARN_ON_ONCE(iomap_iter_srcmap(iter)->offset != 0))
69f4a26c 763 return -EIO;
874628a2 764 return iomap_read_inline_data(iter, folio);
69f4a26c
GX
765}
766
d7b64041 767static int iomap_write_begin(struct iomap_iter *iter, loff_t pos,
bc6123a8 768 size_t len, struct folio **foliop)
afc51aaa 769{
471859f5 770 const struct iomap_folio_ops *folio_ops = iter->iomap.folio_ops;
fad0a1ab 771 const struct iomap *srcmap = iomap_iter_srcmap(iter);
d1bd0b4e 772 struct folio *folio;
afc51aaa
DW
773 int status = 0;
774
1b5c1e36
CH
775 BUG_ON(pos + len > iter->iomap.offset + iter->iomap.length);
776 if (srcmap != &iter->iomap)
c039b997 777 BUG_ON(pos + len > srcmap->offset + srcmap->length);
afc51aaa
DW
778
779 if (fatal_signal_pending(current))
780 return -EINTR;
781
d454ab82
MWO
782 if (!mapping_large_folio_support(iter->inode->i_mapping))
783 len = min_t(size_t, len, PAGE_SIZE - offset_in_page(pos));
784
07c22b56 785 folio = __iomap_get_folio(iter, pos, len);
9060bc4d 786 if (IS_ERR(folio))
98321b51 787 return PTR_ERR(folio);
d7b64041
DC
788
789 /*
790 * Now we have a locked folio, before we do anything with it we need to
791 * check that the iomap we have cached is not stale. The inode extent
792 * mapping can change due to concurrent IO in flight (e.g.
793 * IOMAP_UNWRITTEN state can change and memory reclaim could have
794 * reclaimed a previously partially written page at this index after IO
795 * completion before this write reaches this file offset) and hence we
796 * could do the wrong thing here (zero a page range incorrectly or fail
797 * to zero) and corrupt data.
798 */
471859f5
AG
799 if (folio_ops && folio_ops->iomap_valid) {
800 bool iomap_valid = folio_ops->iomap_valid(iter->inode,
801 &iter->iomap);
d7b64041
DC
802 if (!iomap_valid) {
803 iter->iomap.flags |= IOMAP_F_STALE;
804 status = 0;
805 goto out_unlock;
806 }
807 }
808
d454ab82
MWO
809 if (pos + len > folio_pos(folio) + folio_size(folio))
810 len = folio_pos(folio) + folio_size(folio) - pos;
afc51aaa 811
c039b997 812 if (srcmap->type == IOMAP_INLINE)
bc6123a8 813 status = iomap_write_begin_inline(iter, folio);
1b5c1e36 814 else if (srcmap->flags & IOMAP_F_BUFFER_HEAD)
d1bd0b4e 815 status = __block_write_begin_int(folio, pos, len, NULL, srcmap);
afc51aaa 816 else
bc6123a8 817 status = __iomap_write_begin(iter, pos, len, folio);
afc51aaa
DW
818
819 if (unlikely(status))
820 goto out_unlock;
821
bc6123a8 822 *foliop = folio;
afc51aaa
DW
823 return 0;
824
825out_unlock:
7a70a508 826 __iomap_put_folio(iter, pos, 0, folio);
1b5c1e36 827 iomap_write_failed(iter->inode, pos, len);
afc51aaa 828
afc51aaa
DW
829 return status;
830}
831
e25ba8cb 832static size_t __iomap_write_end(struct inode *inode, loff_t pos, size_t len,
bc6123a8 833 size_t copied, struct folio *folio)
afc51aaa 834{
bc6123a8 835 flush_dcache_folio(folio);
afc51aaa
DW
836
837 /*
838 * The blocks that were entirely written will now be uptodate, so we
7479c505 839 * don't have to worry about a read_folio reading them and overwriting a
f1f264b4 840 * partial write. However, if we've encountered a short write and only
afc51aaa 841 * partially written into a block, it will not be marked uptodate, so a
7479c505 842 * read_folio might come in and destroy our partial write.
afc51aaa 843 *
f1f264b4
AG
844 * Do the simplest thing and just treat any short write to a
845 * non-uptodate page as a zero-length write, and force the caller to
846 * redo the whole thing.
afc51aaa 847 */
bc6123a8 848 if (unlikely(copied < len && !folio_test_uptodate(folio)))
afc51aaa 849 return 0;
3ea5c76c 850 iomap_set_range_uptodate(folio, offset_in_folio(folio, pos), len);
4ce02c67 851 iomap_set_range_dirty(folio, offset_in_folio(folio, pos), copied);
bc6123a8 852 filemap_dirty_folio(inode->i_mapping, folio);
afc51aaa
DW
853 return copied;
854}
855
fad0a1ab 856static size_t iomap_write_end_inline(const struct iomap_iter *iter,
9c4ce08d 857 struct folio *folio, loff_t pos, size_t copied)
afc51aaa 858{
fad0a1ab 859 const struct iomap *iomap = &iter->iomap;
afc51aaa
DW
860 void *addr;
861
9c4ce08d 862 WARN_ON_ONCE(!folio_test_uptodate(folio));
69f4a26c 863 BUG_ON(!iomap_inline_data_valid(iomap));
afc51aaa 864
9c4ce08d
MWO
865 flush_dcache_folio(folio);
866 addr = kmap_local_folio(folio, pos);
ab069d5f
MWO
867 memcpy(iomap_inline_data(iomap, pos), addr, copied);
868 kunmap_local(addr);
afc51aaa 869
1b5c1e36 870 mark_inode_dirty(iter->inode);
afc51aaa
DW
871 return copied;
872}
873
e25ba8cb 874/* Returns the number of bytes copied. May be 0. Cannot be an errno. */
1b5c1e36 875static size_t iomap_write_end(struct iomap_iter *iter, loff_t pos, size_t len,
bc6123a8 876 size_t copied, struct folio *folio)
afc51aaa 877{
fad0a1ab 878 const struct iomap *srcmap = iomap_iter_srcmap(iter);
1b5c1e36 879 loff_t old_size = iter->inode->i_size;
e25ba8cb 880 size_t ret;
afc51aaa 881
c039b997 882 if (srcmap->type == IOMAP_INLINE) {
9c4ce08d 883 ret = iomap_write_end_inline(iter, folio, pos, copied);
c039b997 884 } else if (srcmap->flags & IOMAP_F_BUFFER_HEAD) {
1b5c1e36 885 ret = block_write_end(NULL, iter->inode->i_mapping, pos, len,
bc6123a8 886 copied, &folio->page, NULL);
afc51aaa 887 } else {
bc6123a8 888 ret = __iomap_write_end(iter->inode, pos, len, copied, folio);
afc51aaa
DW
889 }
890
891 /*
892 * Update the in-memory inode size after copying the data into the page
893 * cache. It's up to the file system to write the updated size to disk,
894 * preferably after I/O completion so that no stale data is exposed.
895 */
896 if (pos + ret > old_size) {
1b5c1e36
CH
897 i_size_write(iter->inode, pos + ret);
898 iter->iomap.flags |= IOMAP_F_SIZE_CHANGED;
afc51aaa 899 }
7a70a508 900 __iomap_put_folio(iter, pos, ret, folio);
afc51aaa
DW
901
902 if (old_size < pos)
1b5c1e36 903 pagecache_isize_extended(iter->inode, old_size, pos);
afc51aaa 904 if (ret < len)
d74999c8 905 iomap_write_failed(iter->inode, pos + ret, len - ret);
afc51aaa
DW
906 return ret;
907}
908
ce83a025 909static loff_t iomap_write_iter(struct iomap_iter *iter, struct iov_iter *i)
afc51aaa 910{
ce83a025 911 loff_t length = iomap_length(iter);
5d8edfb9 912 size_t chunk = PAGE_SIZE << MAX_PAGECACHE_ORDER;
ce83a025 913 loff_t pos = iter->pos;
afc51aaa 914 ssize_t written = 0;
ce83a025 915 long status = 0;
cae2de69
SR
916 struct address_space *mapping = iter->inode->i_mapping;
917 unsigned int bdp_flags = (iter->flags & IOMAP_NOWAIT) ? BDP_ASYNC : 0;
afc51aaa
DW
918
919 do {
bc6123a8 920 struct folio *folio;
5d8edfb9
MWO
921 size_t offset; /* Offset into folio */
922 size_t bytes; /* Bytes to write to folio */
afc51aaa
DW
923 size_t copied; /* Bytes copied from user */
924
3ac97479
JS
925 bytes = iov_iter_count(i);
926retry:
5d8edfb9 927 offset = pos & (chunk - 1);
3ac97479 928 bytes = min(chunk - offset, bytes);
cae2de69
SR
929 status = balance_dirty_pages_ratelimited_flags(mapping,
930 bdp_flags);
931 if (unlikely(status))
932 break;
933
afc51aaa
DW
934 if (bytes > length)
935 bytes = length;
936
937 /*
f1f264b4 938 * Bring in the user page that we'll copy from _first_.
afc51aaa
DW
939 * Otherwise there's a nasty deadlock on copying from the
940 * same page as we're writing to, without it being marked
941 * up-to-date.
cae2de69
SR
942 *
943 * For async buffered writes the assumption is that the user
944 * page has already been faulted in. This can be optimized by
945 * faulting the user page.
afc51aaa 946 */
631f871f 947 if (unlikely(fault_in_iov_iter_readable(i, bytes) == bytes)) {
afc51aaa
DW
948 status = -EFAULT;
949 break;
950 }
951
bc6123a8 952 status = iomap_write_begin(iter, pos, bytes, &folio);
afc51aaa
DW
953 if (unlikely(status))
954 break;
d7b64041
DC
955 if (iter->iomap.flags & IOMAP_F_STALE)
956 break;
afc51aaa 957
5d8edfb9
MWO
958 offset = offset_in_folio(folio, pos);
959 if (bytes > folio_size(folio) - offset)
960 bytes = folio_size(folio) - offset;
afc51aaa 961
5d8edfb9
MWO
962 if (mapping_writably_mapped(mapping))
963 flush_dcache_folio(folio);
afc51aaa 964
5d8edfb9 965 copied = copy_folio_from_iter_atomic(folio, offset, bytes, i);
bc6123a8 966 status = iomap_write_end(iter, pos, bytes, copied, folio);
afc51aaa 967
f0b65f39
AV
968 if (unlikely(copied != status))
969 iov_iter_revert(i, copied - status);
afc51aaa 970
f0b65f39 971 cond_resched();
bc1bb416 972 if (unlikely(status == 0)) {
afc51aaa 973 /*
bc1bb416
AV
974 * A short copy made iomap_write_end() reject the
975 * thing entirely. Might be memory poisoning
976 * halfway through, might be a race with munmap,
977 * might be severe memory pressure.
afc51aaa 978 */
5d8edfb9
MWO
979 if (chunk > PAGE_SIZE)
980 chunk /= 2;
3ac97479
JS
981 if (copied) {
982 bytes = copied;
983 goto retry;
984 }
5d8edfb9
MWO
985 } else {
986 pos += status;
987 written += status;
988 length -= status;
afc51aaa 989 }
afc51aaa
DW
990 } while (iov_iter_count(i) && length);
991
18e419f6
SR
992 if (status == -EAGAIN) {
993 iov_iter_revert(i, written);
994 return -EAGAIN;
995 }
afc51aaa
DW
996 return written ? written : status;
997}
998
999ssize_t
ce83a025 1000iomap_file_buffered_write(struct kiocb *iocb, struct iov_iter *i,
afc51aaa
DW
1001 const struct iomap_ops *ops)
1002{
ce83a025
CH
1003 struct iomap_iter iter = {
1004 .inode = iocb->ki_filp->f_mapping->host,
1005 .pos = iocb->ki_pos,
1006 .len = iov_iter_count(i),
1007 .flags = IOMAP_WRITE,
1008 };
219580ee 1009 ssize_t ret;
afc51aaa 1010
cae2de69
SR
1011 if (iocb->ki_flags & IOCB_NOWAIT)
1012 iter.flags |= IOMAP_NOWAIT;
1013
ce83a025
CH
1014 while ((ret = iomap_iter(&iter, ops)) > 0)
1015 iter.processed = iomap_write_iter(&iter, i);
219580ee 1016
20c64ec8 1017 if (unlikely(iter.pos == iocb->ki_pos))
ce83a025 1018 return ret;
219580ee 1019 ret = iter.pos - iocb->ki_pos;
efa96cc9 1020 iocb->ki_pos = iter.pos;
219580ee 1021 return ret;
afc51aaa
DW
1022}
1023EXPORT_SYMBOL_GPL(iomap_file_buffered_write);
1024
4ce02c67
RHI
1025static int iomap_write_delalloc_ifs_punch(struct inode *inode,
1026 struct folio *folio, loff_t start_byte, loff_t end_byte,
1027 iomap_punch_t punch)
1028{
1029 unsigned int first_blk, last_blk, i;
1030 loff_t last_byte;
1031 u8 blkbits = inode->i_blkbits;
1032 struct iomap_folio_state *ifs;
1033 int ret = 0;
1034
1035 /*
1036 * When we have per-block dirty tracking, there can be
1037 * blocks within a folio which are marked uptodate
1038 * but not dirty. In that case it is necessary to punch
1039 * out such blocks to avoid leaking any delalloc blocks.
1040 */
1041 ifs = folio->private;
1042 if (!ifs)
1043 return ret;
1044
1045 last_byte = min_t(loff_t, end_byte - 1,
1046 folio_pos(folio) + folio_size(folio) - 1);
1047 first_blk = offset_in_folio(folio, start_byte) >> blkbits;
1048 last_blk = offset_in_folio(folio, last_byte) >> blkbits;
1049 for (i = first_blk; i <= last_blk; i++) {
1050 if (!ifs_block_is_dirty(folio, ifs, i)) {
1051 ret = punch(inode, folio_pos(folio) + (i << blkbits),
1052 1 << blkbits);
1053 if (ret)
1054 return ret;
1055 }
1056 }
1057
1058 return ret;
1059}
1060
1061
7f79d85b
RHI
1062static int iomap_write_delalloc_punch(struct inode *inode, struct folio *folio,
1063 loff_t *punch_start_byte, loff_t start_byte, loff_t end_byte,
1064 iomap_punch_t punch)
1065{
1066 int ret = 0;
1067
1068 if (!folio_test_dirty(folio))
1069 return ret;
1070
1071 /* if dirty, punch up to offset */
1072 if (start_byte > *punch_start_byte) {
1073 ret = punch(inode, *punch_start_byte,
1074 start_byte - *punch_start_byte);
1075 if (ret)
1076 return ret;
1077 }
1078
4ce02c67
RHI
1079 /* Punch non-dirty blocks within folio */
1080 ret = iomap_write_delalloc_ifs_punch(inode, folio, start_byte,
1081 end_byte, punch);
1082 if (ret)
1083 return ret;
1084
7f79d85b
RHI
1085 /*
1086 * Make sure the next punch start is correctly bound to
1087 * the end of this data range, not the end of the folio.
1088 */
1089 *punch_start_byte = min_t(loff_t, end_byte,
1090 folio_pos(folio) + folio_size(folio));
1091
1092 return ret;
1093}
1094
f43dc4dc
DC
1095/*
1096 * Scan the data range passed to us for dirty page cache folios. If we find a
684f7e6d 1097 * dirty folio, punch out the preceding range and update the offset from which
f43dc4dc
DC
1098 * the next punch will start from.
1099 *
1100 * We can punch out storage reservations under clean pages because they either
1101 * contain data that has been written back - in which case the delalloc punch
1102 * over that range is a no-op - or they have been read faults in which case they
1103 * contain zeroes and we can remove the delalloc backing range and any new
1104 * writes to those pages will do the normal hole filling operation...
1105 *
1106 * This makes the logic simple: we only need to keep the delalloc extents only
1107 * over the dirty ranges of the page cache.
1108 *
1109 * This function uses [start_byte, end_byte) intervals (i.e. open ended) to
1110 * simplify range iterations.
1111 */
1112static int iomap_write_delalloc_scan(struct inode *inode,
1113 loff_t *punch_start_byte, loff_t start_byte, loff_t end_byte,
0af2b37d 1114 iomap_punch_t punch)
f43dc4dc
DC
1115{
1116 while (start_byte < end_byte) {
1117 struct folio *folio;
7f79d85b 1118 int ret;
f43dc4dc
DC
1119
1120 /* grab locked page */
1121 folio = filemap_lock_folio(inode->i_mapping,
1122 start_byte >> PAGE_SHIFT);
66dabbb6 1123 if (IS_ERR(folio)) {
f43dc4dc
DC
1124 start_byte = ALIGN_DOWN(start_byte, PAGE_SIZE) +
1125 PAGE_SIZE;
1126 continue;
1127 }
1128
7f79d85b
RHI
1129 ret = iomap_write_delalloc_punch(inode, folio, punch_start_byte,
1130 start_byte, end_byte, punch);
1131 if (ret) {
1132 folio_unlock(folio);
1133 folio_put(folio);
1134 return ret;
f43dc4dc
DC
1135 }
1136
1137 /* move offset to start of next folio in range */
1138 start_byte = folio_next_index(folio) << PAGE_SHIFT;
1139 folio_unlock(folio);
1140 folio_put(folio);
1141 }
1142 return 0;
1143}
1144
1145/*
1146 * Punch out all the delalloc blocks in the range given except for those that
1147 * have dirty data still pending in the page cache - those are going to be
1148 * written and so must still retain the delalloc backing for writeback.
1149 *
1150 * As we are scanning the page cache for data, we don't need to reimplement the
1151 * wheel - mapping_seek_hole_data() does exactly what we need to identify the
1152 * start and end of data ranges correctly even for sub-folio block sizes. This
1153 * byte range based iteration is especially convenient because it means we
1154 * don't have to care about variable size folios, nor where the start or end of
1155 * the data range lies within a folio, if they lie within the same folio or even
1156 * if there are multiple discontiguous data ranges within the folio.
1157 *
1158 * It should be noted that mapping_seek_hole_data() is not aware of EOF, and so
1159 * can return data ranges that exist in the cache beyond EOF. e.g. a page fault
1160 * spanning EOF will initialise the post-EOF data to zeroes and mark it up to
1161 * date. A write page fault can then mark it dirty. If we then fail a write()
1162 * beyond EOF into that up to date cached range, we allocate a delalloc block
1163 * beyond EOF and then have to punch it out. Because the range is up to date,
1164 * mapping_seek_hole_data() will return it, and we will skip the punch because
1165 * the folio is dirty. THis is incorrect - we always need to punch out delalloc
1166 * beyond EOF in this case as writeback will never write back and covert that
1167 * delalloc block beyond EOF. Hence we limit the cached data scan range to EOF,
1168 * resulting in always punching out the range from the EOF to the end of the
1169 * range the iomap spans.
1170 *
1171 * Intervals are of the form [start_byte, end_byte) (i.e. open ended) because it
1172 * matches the intervals returned by mapping_seek_hole_data(). i.e. SEEK_DATA
1173 * returns the start of a data range (start_byte), and SEEK_HOLE(start_byte)
1174 * returns the end of the data range (data_end). Using closed intervals would
1175 * require sprinkling this code with magic "+ 1" and "- 1" arithmetic and expose
1176 * the code to subtle off-by-one bugs....
1177 */
1178static int iomap_write_delalloc_release(struct inode *inode,
0af2b37d 1179 loff_t start_byte, loff_t end_byte, iomap_punch_t punch)
f43dc4dc
DC
1180{
1181 loff_t punch_start_byte = start_byte;
1182 loff_t scan_end_byte = min(i_size_read(inode), end_byte);
1183 int error = 0;
1184
1185 /*
1186 * Lock the mapping to avoid races with page faults re-instantiating
1187 * folios and dirtying them via ->page_mkwrite whilst we walk the
1188 * cache and perform delalloc extent removal. Failing to do this can
1189 * leave dirty pages with no space reservation in the cache.
1190 */
1191 filemap_invalidate_lock(inode->i_mapping);
1192 while (start_byte < scan_end_byte) {
1193 loff_t data_end;
1194
1195 start_byte = mapping_seek_hole_data(inode->i_mapping,
1196 start_byte, scan_end_byte, SEEK_DATA);
1197 /*
1198 * If there is no more data to scan, all that is left is to
1199 * punch out the remaining range.
1200 */
1201 if (start_byte == -ENXIO || start_byte == scan_end_byte)
1202 break;
1203 if (start_byte < 0) {
1204 error = start_byte;
1205 goto out_unlock;
1206 }
1207 WARN_ON_ONCE(start_byte < punch_start_byte);
1208 WARN_ON_ONCE(start_byte > scan_end_byte);
1209
1210 /*
1211 * We find the end of this contiguous cached data range by
1212 * seeking from start_byte to the beginning of the next hole.
1213 */
1214 data_end = mapping_seek_hole_data(inode->i_mapping, start_byte,
1215 scan_end_byte, SEEK_HOLE);
1216 if (data_end < 0) {
1217 error = data_end;
1218 goto out_unlock;
1219 }
1220 WARN_ON_ONCE(data_end <= start_byte);
1221 WARN_ON_ONCE(data_end > scan_end_byte);
1222
1223 error = iomap_write_delalloc_scan(inode, &punch_start_byte,
1224 start_byte, data_end, punch);
1225 if (error)
1226 goto out_unlock;
1227
1228 /* The next data search starts at the end of this one. */
1229 start_byte = data_end;
1230 }
1231
1232 if (punch_start_byte < end_byte)
1233 error = punch(inode, punch_start_byte,
1234 end_byte - punch_start_byte);
1235out_unlock:
1236 filemap_invalidate_unlock(inode->i_mapping);
1237 return error;
1238}
1239
9c7babf9
DC
1240/*
1241 * When a short write occurs, the filesystem may need to remove reserved space
1242 * that was allocated in ->iomap_begin from it's ->iomap_end method. For
1243 * filesystems that use delayed allocation, we need to punch out delalloc
1244 * extents from the range that are not dirty in the page cache. As the write can
1245 * race with page faults, there can be dirty pages over the delalloc extent
1246 * outside the range of a short write but still within the delalloc extent
1247 * allocated for this iomap.
1248 *
1249 * This function uses [start_byte, end_byte) intervals (i.e. open ended) to
f43dc4dc
DC
1250 * simplify range iterations.
1251 *
1252 * The punch() callback *must* only punch delalloc extents in the range passed
1253 * to it. It must skip over all other types of extents in the range and leave
1254 * them completely unchanged. It must do this punch atomically with respect to
1255 * other extent modifications.
1256 *
1257 * The punch() callback may be called with a folio locked to prevent writeback
1258 * extent allocation racing at the edge of the range we are currently punching.
1259 * The locked folio may or may not cover the range being punched, so it is not
1260 * safe for the punch() callback to lock folios itself.
1261 *
1262 * Lock order is:
1263 *
1264 * inode->i_rwsem (shared or exclusive)
1265 * inode->i_mapping->invalidate_lock (exclusive)
1266 * folio_lock()
1267 * ->punch
1268 * internal filesystem allocation lock
9c7babf9
DC
1269 */
1270int iomap_file_buffered_write_punch_delalloc(struct inode *inode,
1271 struct iomap *iomap, loff_t pos, loff_t length,
0af2b37d 1272 ssize_t written, iomap_punch_t punch)
9c7babf9
DC
1273{
1274 loff_t start_byte;
1275 loff_t end_byte;
302efbef 1276 unsigned int blocksize = i_blocksize(inode);
9c7babf9
DC
1277
1278 if (iomap->type != IOMAP_DELALLOC)
1279 return 0;
1280
1281 /* If we didn't reserve the blocks, we're not allowed to punch them. */
1282 if (!(iomap->flags & IOMAP_F_NEW))
1283 return 0;
1284
1285 /*
1286 * start_byte refers to the first unused block after a short write. If
1287 * nothing was written, round offset down to point at the first block in
1288 * the range.
1289 */
1290 if (unlikely(!written))
1291 start_byte = round_down(pos, blocksize);
1292 else
1293 start_byte = round_up(pos + written, blocksize);
1294 end_byte = round_up(pos + length, blocksize);
1295
1296 /* Nothing to do if we've written the entire delalloc extent */
1297 if (start_byte >= end_byte)
1298 return 0;
1299
f43dc4dc
DC
1300 return iomap_write_delalloc_release(inode, start_byte, end_byte,
1301 punch);
9c7babf9
DC
1302}
1303EXPORT_SYMBOL_GPL(iomap_file_buffered_write_punch_delalloc);
1304
8fc274d1 1305static loff_t iomap_unshare_iter(struct iomap_iter *iter)
afc51aaa 1306{
8fc274d1 1307 struct iomap *iomap = &iter->iomap;
fad0a1ab 1308 const struct iomap *srcmap = iomap_iter_srcmap(iter);
8fc274d1
CH
1309 loff_t pos = iter->pos;
1310 loff_t length = iomap_length(iter);
d4ff3b2e 1311 loff_t written = 0;
afc51aaa 1312
3590c4d8
CH
1313 /* don't bother with blocks that are not shared to start with */
1314 if (!(iomap->flags & IOMAP_F_SHARED))
1315 return length;
1316 /* don't bother with holes or unwritten extents */
c039b997 1317 if (srcmap->type == IOMAP_HOLE || srcmap->type == IOMAP_UNWRITTEN)
3590c4d8
CH
1318 return length;
1319
afc51aaa 1320 do {
bc6123a8 1321 struct folio *folio;
a5f31a50
DW
1322 int status;
1323 size_t offset;
1324 size_t bytes = min_t(u64, SIZE_MAX, length);
afc51aaa 1325
bc6123a8 1326 status = iomap_write_begin(iter, pos, bytes, &folio);
afc51aaa
DW
1327 if (unlikely(status))
1328 return status;
a5f31a50 1329 if (iomap->flags & IOMAP_F_STALE)
d7b64041 1330 break;
afc51aaa 1331
a5f31a50
DW
1332 offset = offset_in_folio(folio, pos);
1333 if (bytes > folio_size(folio) - offset)
1334 bytes = folio_size(folio) - offset;
1335
1336 bytes = iomap_write_end(iter, pos, bytes, bytes, folio);
1337 if (WARN_ON_ONCE(bytes == 0))
e25ba8cb 1338 return -EIO;
afc51aaa
DW
1339
1340 cond_resched();
1341
a5f31a50
DW
1342 pos += bytes;
1343 written += bytes;
1344 length -= bytes;
afc51aaa 1345
8fc274d1 1346 balance_dirty_pages_ratelimited(iter->inode->i_mapping);
a5f31a50 1347 } while (length > 0);
afc51aaa
DW
1348
1349 return written;
1350}
1351
1352int
3590c4d8 1353iomap_file_unshare(struct inode *inode, loff_t pos, loff_t len,
afc51aaa
DW
1354 const struct iomap_ops *ops)
1355{
8fc274d1
CH
1356 struct iomap_iter iter = {
1357 .inode = inode,
1358 .pos = pos,
1359 .len = len,
b74b1293 1360 .flags = IOMAP_WRITE | IOMAP_UNSHARE,
8fc274d1
CH
1361 };
1362 int ret;
afc51aaa 1363
8fc274d1
CH
1364 while ((ret = iomap_iter(&iter, ops)) > 0)
1365 iter.processed = iomap_unshare_iter(&iter);
1366 return ret;
afc51aaa 1367}
3590c4d8 1368EXPORT_SYMBOL_GPL(iomap_file_unshare);
afc51aaa 1369
2aa3048e 1370static loff_t iomap_zero_iter(struct iomap_iter *iter, bool *did_zero)
afc51aaa 1371{
fad0a1ab 1372 const struct iomap *srcmap = iomap_iter_srcmap(iter);
2aa3048e
CH
1373 loff_t pos = iter->pos;
1374 loff_t length = iomap_length(iter);
afc51aaa 1375 loff_t written = 0;
afc51aaa
DW
1376
1377 /* already zeroed? we're done. */
c039b997 1378 if (srcmap->type == IOMAP_HOLE || srcmap->type == IOMAP_UNWRITTEN)
81ee8e52 1379 return length;
afc51aaa
DW
1380
1381 do {
4d7bd0eb
MWO
1382 struct folio *folio;
1383 int status;
1384 size_t offset;
1385 size_t bytes = min_t(u64, SIZE_MAX, length);
1386
4d7bd0eb
MWO
1387 status = iomap_write_begin(iter, pos, bytes, &folio);
1388 if (status)
1389 return status;
d7b64041
DC
1390 if (iter->iomap.flags & IOMAP_F_STALE)
1391 break;
4d7bd0eb
MWO
1392
1393 offset = offset_in_folio(folio, pos);
1394 if (bytes > folio_size(folio) - offset)
1395 bytes = folio_size(folio) - offset;
1396
1397 folio_zero_range(folio, offset, bytes);
1398 folio_mark_accessed(folio);
1399
1400 bytes = iomap_write_end(iter, pos, bytes, bytes, folio);
4d7bd0eb
MWO
1401 if (WARN_ON_ONCE(bytes == 0))
1402 return -EIO;
afc51aaa
DW
1403
1404 pos += bytes;
81ee8e52 1405 length -= bytes;
afc51aaa 1406 written += bytes;
81ee8e52 1407 } while (length > 0);
afc51aaa 1408
98eb8d95
KX
1409 if (did_zero)
1410 *did_zero = true;
afc51aaa
DW
1411 return written;
1412}
1413
1414int
1415iomap_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero,
1416 const struct iomap_ops *ops)
1417{
2aa3048e
CH
1418 struct iomap_iter iter = {
1419 .inode = inode,
1420 .pos = pos,
1421 .len = len,
1422 .flags = IOMAP_ZERO,
1423 };
1424 int ret;
afc51aaa 1425
2aa3048e
CH
1426 while ((ret = iomap_iter(&iter, ops)) > 0)
1427 iter.processed = iomap_zero_iter(&iter, did_zero);
1428 return ret;
afc51aaa
DW
1429}
1430EXPORT_SYMBOL_GPL(iomap_zero_range);
1431
1432int
1433iomap_truncate_page(struct inode *inode, loff_t pos, bool *did_zero,
1434 const struct iomap_ops *ops)
1435{
1436 unsigned int blocksize = i_blocksize(inode);
1437 unsigned int off = pos & (blocksize - 1);
1438
1439 /* Block boundary? Nothing to do */
1440 if (!off)
1441 return 0;
1442 return iomap_zero_range(inode, pos, blocksize - off, did_zero, ops);
1443}
1444EXPORT_SYMBOL_GPL(iomap_truncate_page);
1445
ea0f843a
MWO
1446static loff_t iomap_folio_mkwrite_iter(struct iomap_iter *iter,
1447 struct folio *folio)
afc51aaa 1448{
253564ba 1449 loff_t length = iomap_length(iter);
afc51aaa
DW
1450 int ret;
1451
253564ba 1452 if (iter->iomap.flags & IOMAP_F_BUFFER_HEAD) {
d1bd0b4e 1453 ret = __block_write_begin_int(folio, iter->pos, length, NULL,
253564ba 1454 &iter->iomap);
afc51aaa
DW
1455 if (ret)
1456 return ret;
ea0f843a 1457 block_commit_write(&folio->page, 0, length);
afc51aaa 1458 } else {
ea0f843a
MWO
1459 WARN_ON_ONCE(!folio_test_uptodate(folio));
1460 folio_mark_dirty(folio);
afc51aaa
DW
1461 }
1462
1463 return length;
1464}
1465
1466vm_fault_t iomap_page_mkwrite(struct vm_fault *vmf, const struct iomap_ops *ops)
1467{
253564ba
CH
1468 struct iomap_iter iter = {
1469 .inode = file_inode(vmf->vma->vm_file),
1470 .flags = IOMAP_WRITE | IOMAP_FAULT,
1471 };
ea0f843a 1472 struct folio *folio = page_folio(vmf->page);
afc51aaa
DW
1473 ssize_t ret;
1474
ea0f843a
MWO
1475 folio_lock(folio);
1476 ret = folio_mkwrite_check_truncate(folio, iter.inode);
243145bc 1477 if (ret < 0)
afc51aaa 1478 goto out_unlock;
ea0f843a 1479 iter.pos = folio_pos(folio);
253564ba
CH
1480 iter.len = ret;
1481 while ((ret = iomap_iter(&iter, ops)) > 0)
ea0f843a 1482 iter.processed = iomap_folio_mkwrite_iter(&iter, folio);
afc51aaa 1483
253564ba
CH
1484 if (ret < 0)
1485 goto out_unlock;
ea0f843a 1486 folio_wait_stable(folio);
afc51aaa
DW
1487 return VM_FAULT_LOCKED;
1488out_unlock:
ea0f843a 1489 folio_unlock(folio);
2ba39cc4 1490 return vmf_fs_error(ret);
afc51aaa
DW
1491}
1492EXPORT_SYMBOL_GPL(iomap_page_mkwrite);
598ecfba 1493
8ffd74e9 1494static void iomap_finish_folio_write(struct inode *inode, struct folio *folio,
6b865d65 1495 size_t len)
598ecfba 1496{
04f52c4e 1497 struct iomap_folio_state *ifs = folio->private;
598ecfba 1498
04f52c4e
RHI
1499 WARN_ON_ONCE(i_blocks_per_folio(inode, folio) > 1 && !ifs);
1500 WARN_ON_ONCE(ifs && atomic_read(&ifs->write_bytes_pending) <= 0);
598ecfba 1501
04f52c4e 1502 if (!ifs || atomic_sub_and_test(len, &ifs->write_bytes_pending))
8ffd74e9 1503 folio_end_writeback(folio);
598ecfba
CH
1504}
1505
1506/*
1507 * We're now finished for good with this ioend structure. Update the page
1508 * state, release holds on bios, and finally free up memory. Do not use the
1509 * ioend after this.
1510 */
ebb7fb15 1511static u32
598ecfba
CH
1512iomap_finish_ioend(struct iomap_ioend *ioend, int error)
1513{
1514 struct inode *inode = ioend->io_inode;
ae5535ef
CH
1515 struct bio *bio = &ioend->io_bio;
1516 struct folio_iter fi;
ebb7fb15 1517 u32 folio_count = 0;
598ecfba 1518
6b865d65
CH
1519 if (error) {
1520 mapping_set_error(inode->i_mapping, error);
1521 if (!bio_flagged(bio, BIO_QUIET)) {
1522 pr_err_ratelimited(
1523"%s: writeback error on inode %lu, offset %lld, sector %llu",
1524 inode->i_sb->s_id, inode->i_ino,
1525 ioend->io_offset, ioend->io_sector);
1526 }
1527 }
1528
ae5535ef
CH
1529 /* walk all folios in bio, ending page IO on them */
1530 bio_for_each_folio_all(fi, bio) {
6b865d65
CH
1531 if (error)
1532 folio_set_error(fi.folio);
1533 iomap_finish_folio_write(inode, fi.folio, fi.length);
ae5535ef 1534 folio_count++;
598ecfba
CH
1535 }
1536
ae5535ef 1537 bio_put(bio); /* frees the ioend */
ebb7fb15 1538 return folio_count;
598ecfba
CH
1539}
1540
ebb7fb15
DC
1541/*
1542 * Ioend completion routine for merged bios. This can only be called from task
1543 * contexts as merged ioends can be of unbound length. Hence we have to break up
1544 * the writeback completions into manageable chunks to avoid long scheduler
1545 * holdoffs. We aim to keep scheduler holdoffs down below 10ms so that we get
1546 * good batch processing throughput without creating adverse scheduler latency
1547 * conditions.
1548 */
598ecfba
CH
1549void
1550iomap_finish_ioends(struct iomap_ioend *ioend, int error)
1551{
1552 struct list_head tmp;
ebb7fb15
DC
1553 u32 completions;
1554
1555 might_sleep();
598ecfba
CH
1556
1557 list_replace_init(&ioend->io_list, &tmp);
ebb7fb15 1558 completions = iomap_finish_ioend(ioend, error);
598ecfba
CH
1559
1560 while (!list_empty(&tmp)) {
ebb7fb15
DC
1561 if (completions > IOEND_BATCH_SIZE * 8) {
1562 cond_resched();
1563 completions = 0;
1564 }
598ecfba
CH
1565 ioend = list_first_entry(&tmp, struct iomap_ioend, io_list);
1566 list_del_init(&ioend->io_list);
ebb7fb15 1567 completions += iomap_finish_ioend(ioend, error);
598ecfba
CH
1568 }
1569}
1570EXPORT_SYMBOL_GPL(iomap_finish_ioends);
1571
1572/*
1573 * We can merge two adjacent ioends if they have the same set of work to do.
1574 */
1575static bool
1576iomap_ioend_can_merge(struct iomap_ioend *ioend, struct iomap_ioend *next)
1577{
ae5535ef 1578 if (ioend->io_bio.bi_status != next->io_bio.bi_status)
598ecfba
CH
1579 return false;
1580 if ((ioend->io_flags & IOMAP_F_SHARED) ^
1581 (next->io_flags & IOMAP_F_SHARED))
1582 return false;
1583 if ((ioend->io_type == IOMAP_UNWRITTEN) ^
1584 (next->io_type == IOMAP_UNWRITTEN))
1585 return false;
1586 if (ioend->io_offset + ioend->io_size != next->io_offset)
1587 return false;
ebb7fb15
DC
1588 /*
1589 * Do not merge physically discontiguous ioends. The filesystem
1590 * completion functions will have to iterate the physical
1591 * discontiguities even if we merge the ioends at a logical level, so
1592 * we don't gain anything by merging physical discontiguities here.
1593 *
1594 * We cannot use bio->bi_iter.bi_sector here as it is modified during
1595 * submission so does not point to the start sector of the bio at
1596 * completion.
1597 */
1598 if (ioend->io_sector + (ioend->io_size >> 9) != next->io_sector)
1599 return false;
598ecfba
CH
1600 return true;
1601}
1602
1603void
6e552494 1604iomap_ioend_try_merge(struct iomap_ioend *ioend, struct list_head *more_ioends)
598ecfba
CH
1605{
1606 struct iomap_ioend *next;
1607
1608 INIT_LIST_HEAD(&ioend->io_list);
1609
1610 while ((next = list_first_entry_or_null(more_ioends, struct iomap_ioend,
1611 io_list))) {
1612 if (!iomap_ioend_can_merge(ioend, next))
1613 break;
1614 list_move_tail(&next->io_list, &ioend->io_list);
1615 ioend->io_size += next->io_size;
598ecfba
CH
1616 }
1617}
1618EXPORT_SYMBOL_GPL(iomap_ioend_try_merge);
1619
1620static int
4f0f586b
ST
1621iomap_ioend_compare(void *priv, const struct list_head *a,
1622 const struct list_head *b)
598ecfba 1623{
b3d423ec
CH
1624 struct iomap_ioend *ia = container_of(a, struct iomap_ioend, io_list);
1625 struct iomap_ioend *ib = container_of(b, struct iomap_ioend, io_list);
598ecfba 1626
598ecfba
CH
1627 if (ia->io_offset < ib->io_offset)
1628 return -1;
b3d423ec 1629 if (ia->io_offset > ib->io_offset)
598ecfba
CH
1630 return 1;
1631 return 0;
1632}
1633
1634void
1635iomap_sort_ioends(struct list_head *ioend_list)
1636{
1637 list_sort(NULL, ioend_list, iomap_ioend_compare);
1638}
1639EXPORT_SYMBOL_GPL(iomap_sort_ioends);
1640
1641static void iomap_writepage_end_bio(struct bio *bio)
1642{
ae5535ef
CH
1643 iomap_finish_ioend(iomap_ioend_from_bio(bio),
1644 blk_status_to_errno(bio->bi_status));
598ecfba
CH
1645}
1646
1647/*
1648 * Submit the final bio for an ioend.
1649 *
1650 * If @error is non-zero, it means that we have a situation where some part of
410bb2ce
CH
1651 * the submission process has failed after we've marked pages for writeback.
1652 * We cannot cancel ioend directly in that case, so call the bio end I/O handler
1653 * with the error status here to run the normal I/O completion handler to clear
1654 * the writeback bit and let the file system proess the errors.
598ecfba 1655 */
410bb2ce 1656static int iomap_submit_ioend(struct iomap_writepage_ctx *wpc, int error)
598ecfba 1657{
410bb2ce
CH
1658 if (!wpc->ioend)
1659 return error;
1660
1661 /*
1662 * Let the file systems prepare the I/O submission and hook in an I/O
1663 * comletion handler. This also needs to happen in case after a
1664 * failure happened so that the file system end I/O handler gets called
1665 * to clean up.
1666 */
598ecfba 1667 if (wpc->ops->prepare_ioend)
410bb2ce
CH
1668 error = wpc->ops->prepare_ioend(wpc->ioend, error);
1669
598ecfba 1670 if (error) {
410bb2ce
CH
1671 wpc->ioend->io_bio.bi_status = errno_to_blk_status(error);
1672 bio_endio(&wpc->ioend->io_bio);
1673 } else {
1674 submit_bio(&wpc->ioend->io_bio);
598ecfba
CH
1675 }
1676
410bb2ce
CH
1677 wpc->ioend = NULL;
1678 return error;
598ecfba
CH
1679}
1680
dec3a7b3
CH
1681static struct iomap_ioend *iomap_alloc_ioend(struct iomap_writepage_ctx *wpc,
1682 struct writeback_control *wbc, struct inode *inode, loff_t pos)
598ecfba
CH
1683{
1684 struct iomap_ioend *ioend;
1685 struct bio *bio;
1686
609be106
CH
1687 bio = bio_alloc_bioset(wpc->iomap.bdev, BIO_MAX_VECS,
1688 REQ_OP_WRITE | wbc_to_write_flags(wbc),
1689 GFP_NOFS, &iomap_ioend_bioset);
dec3a7b3 1690 bio->bi_iter.bi_sector = iomap_sector(&wpc->iomap, pos);
ae5535ef 1691 bio->bi_end_io = iomap_writepage_end_bio;
598ecfba 1692 wbc_init_bio(wbc, bio);
86835c39 1693 bio->bi_write_hint = inode->i_write_hint;
598ecfba 1694
ae5535ef 1695 ioend = iomap_ioend_from_bio(bio);
598ecfba
CH
1696 INIT_LIST_HEAD(&ioend->io_list);
1697 ioend->io_type = wpc->iomap.type;
1698 ioend->io_flags = wpc->iomap.flags;
1699 ioend->io_inode = inode;
1700 ioend->io_size = 0;
dec3a7b3 1701 ioend->io_offset = pos;
dec3a7b3 1702 ioend->io_sector = bio->bi_iter.bi_sector;
432acd55
CH
1703
1704 wpc->nr_folios = 0;
598ecfba
CH
1705 return ioend;
1706}
1707
dec3a7b3 1708static bool iomap_can_add_to_ioend(struct iomap_writepage_ctx *wpc, loff_t pos)
598ecfba
CH
1709{
1710 if ((wpc->iomap.flags & IOMAP_F_SHARED) !=
1711 (wpc->ioend->io_flags & IOMAP_F_SHARED))
1712 return false;
1713 if (wpc->iomap.type != wpc->ioend->io_type)
1714 return false;
dec3a7b3 1715 if (pos != wpc->ioend->io_offset + wpc->ioend->io_size)
598ecfba 1716 return false;
dec3a7b3 1717 if (iomap_sector(&wpc->iomap, pos) !=
ae5535ef 1718 bio_end_sector(&wpc->ioend->io_bio))
598ecfba 1719 return false;
ebb7fb15
DC
1720 /*
1721 * Limit ioend bio chain lengths to minimise IO completion latency. This
1722 * also prevents long tight loops ending page writeback on all the
1723 * folios in the ioend.
1724 */
432acd55 1725 if (wpc->nr_folios >= IOEND_BATCH_SIZE)
ebb7fb15 1726 return false;
598ecfba
CH
1727 return true;
1728}
1729
1730/*
1731 * Test to see if we have an existing ioend structure that we could append to
f1f264b4 1732 * first; otherwise finish off the current ioend and start another.
410bb2ce
CH
1733 *
1734 * If a new ioend is created and cached, the old ioend is submitted to the block
1735 * layer instantly. Batching optimisations are provided by higher level block
1736 * plugging.
1737 *
1738 * At the end of a writeback pass, there will be a cached ioend remaining on the
1739 * writepage context that the caller will need to submit.
598ecfba 1740 */
410bb2ce 1741static int iomap_add_to_ioend(struct iomap_writepage_ctx *wpc,
7edfc610 1742 struct writeback_control *wbc, struct folio *folio,
30deff85 1743 struct inode *inode, loff_t pos, unsigned len)
598ecfba 1744{
7edfc610 1745 struct iomap_folio_state *ifs = folio->private;
e735c007 1746 size_t poff = offset_in_folio(folio, pos);
410bb2ce 1747 int error;
598ecfba 1748
dec3a7b3 1749 if (!wpc->ioend || !iomap_can_add_to_ioend(wpc, pos)) {
ae5535ef 1750new_ioend:
410bb2ce
CH
1751 error = iomap_submit_ioend(wpc, 0);
1752 if (error)
1753 return error;
dec3a7b3 1754 wpc->ioend = iomap_alloc_ioend(wpc, wbc, inode, pos);
598ecfba
CH
1755 }
1756
ae5535ef
CH
1757 if (!bio_add_folio(&wpc->ioend->io_bio, folio, len, poff))
1758 goto new_ioend;
598ecfba 1759
04f52c4e
RHI
1760 if (ifs)
1761 atomic_add(len, &ifs->write_bytes_pending);
598ecfba 1762 wpc->ioend->io_size += len;
e735c007 1763 wbc_account_cgroup_owner(wbc, &folio->page, len);
410bb2ce 1764 return 0;
598ecfba
CH
1765}
1766
f525152a
CH
1767static int iomap_writepage_map_blocks(struct iomap_writepage_ctx *wpc,
1768 struct writeback_control *wbc, struct folio *folio,
30deff85
CH
1769 struct inode *inode, u64 pos, unsigned dirty_len,
1770 unsigned *count)
f525152a
CH
1771{
1772 int error;
1773
30deff85
CH
1774 do {
1775 unsigned map_len;
1776
19871b5c 1777 error = wpc->ops->map_blocks(wpc, inode, pos, dirty_len);
30deff85
CH
1778 if (error)
1779 break;
54943abc 1780 trace_iomap_writepage_map(inode, pos, dirty_len, &wpc->iomap);
30deff85
CH
1781
1782 map_len = min_t(u64, dirty_len,
1783 wpc->iomap.offset + wpc->iomap.length - pos);
1784 WARN_ON_ONCE(!folio->private && map_len < dirty_len);
1785
1786 switch (wpc->iomap.type) {
1787 case IOMAP_INLINE:
1788 WARN_ON_ONCE(1);
1789 error = -EIO;
1790 break;
1791 case IOMAP_HOLE:
1792 break;
1793 default:
1794 error = iomap_add_to_ioend(wpc, wbc, folio, inode, pos,
1795 map_len);
1796 if (!error)
1797 (*count)++;
1798 break;
1799 }
1800 dirty_len -= map_len;
1801 pos += map_len;
1802 } while (dirty_len && !error);
f525152a 1803
f525152a
CH
1804 /*
1805 * We cannot cancel the ioend directly here on error. We may have
1806 * already set other pages under writeback and hence we have to run I/O
1807 * completion to mark the error state of the pages under writeback
1808 * appropriately.
1809 *
1810 * Just let the file system know what portion of the folio failed to
1811 * map.
1812 */
1813 if (error && wpc->ops->discard_folio)
1814 wpc->ops->discard_folio(folio, pos);
1815 return error;
1816}
1817
e3a491a2
CH
1818/*
1819 * Check interaction of the folio with the file end.
1820 *
1821 * If the folio is entirely beyond i_size, return false. If it straddles
1822 * i_size, adjust end_pos and zero all data beyond i_size.
1823 */
1824static bool iomap_writepage_handle_eof(struct folio *folio, struct inode *inode,
1825 u64 *end_pos)
1826{
1827 u64 isize = i_size_read(inode);
1828
1829 if (*end_pos > isize) {
1830 size_t poff = offset_in_folio(folio, isize);
1831 pgoff_t end_index = isize >> PAGE_SHIFT;
1832
1833 /*
1834 * If the folio is entirely ouside of i_size, skip it.
1835 *
1836 * This can happen due to a truncate operation that is in
1837 * progress and in that case truncate will finish it off once
1838 * we've dropped the folio lock.
1839 *
1840 * Note that the pgoff_t used for end_index is an unsigned long.
1841 * If the given offset is greater than 16TB on a 32-bit system,
1842 * then if we checked if the folio is fully outside i_size with
1843 * "if (folio->index >= end_index + 1)", "end_index + 1" would
1844 * overflow and evaluate to 0. Hence this folio would be
1845 * redirtied and written out repeatedly, which would result in
1846 * an infinite loop; the user program performing this operation
1847 * would hang. Instead, we can detect this situation by
1848 * checking if the folio is totally beyond i_size or if its
1849 * offset is just equal to the EOF.
1850 */
1851 if (folio->index > end_index ||
1852 (folio->index == end_index && poff == 0))
1853 return false;
1854
1855 /*
1856 * The folio straddles i_size.
1857 *
1858 * It must be zeroed out on each and every writepage invocation
1859 * because it may be mmapped:
1860 *
1861 * A file is mapped in multiples of the page size. For a
1862 * file that is not a multiple of the page size, the
1863 * remaining memory is zeroed when mapped, and writes to that
1864 * region are not written out to the file.
1865 *
1866 * Also adjust the writeback range to skip all blocks entirely
1867 * beyond i_size.
1868 */
1869 folio_zero_segment(folio, poff, folio_size(folio));
30deff85 1870 *end_pos = round_up(isize, i_blocksize(inode));
e3a491a2
CH
1871 }
1872
1873 return true;
1874}
1875
cc954253
CH
1876static int iomap_writepage_map(struct iomap_writepage_ctx *wpc,
1877 struct writeback_control *wbc, struct folio *folio)
598ecfba 1878{
4ce02c67 1879 struct iomap_folio_state *ifs = folio->private;
cc954253 1880 struct inode *inode = folio->mapping->host;
92655036 1881 u64 pos = folio_pos(folio);
cc954253 1882 u64 end_pos = pos + folio_size(folio);
f525152a 1883 unsigned count = 0;
30deff85
CH
1884 int error = 0;
1885 u32 rlen;
410bb2ce
CH
1886
1887 WARN_ON_ONCE(!folio_test_locked(folio));
1888 WARN_ON_ONCE(folio_test_dirty(folio));
1889 WARN_ON_ONCE(folio_test_writeback(folio));
598ecfba 1890
cc954253
CH
1891 trace_iomap_writepage(inode, pos, folio_size(folio));
1892
1893 if (!iomap_writepage_handle_eof(folio, inode, &end_pos)) {
1894 folio_unlock(folio);
1895 return 0;
1896 }
4ce02c67
RHI
1897 WARN_ON_ONCE(end_pos <= pos);
1898
30deff85 1899 if (i_blocks_per_folio(inode, folio) > 1) {
410bb2ce
CH
1900 if (!ifs) {
1901 ifs = ifs_alloc(inode, folio, 0);
1902 iomap_set_range_dirty(folio, 0, end_pos - pos);
1903 }
1904
1905 /*
1906 * Keep the I/O completion handler from clearing the writeback
1907 * bit until we have submitted all blocks by adding a bias to
1908 * ifs->write_bytes_pending, which is dropped after submitting
1909 * all blocks.
1910 */
1911 WARN_ON_ONCE(atomic_read(&ifs->write_bytes_pending) != 0);
1912 atomic_inc(&ifs->write_bytes_pending);
4ce02c67
RHI
1913 }
1914
410bb2ce
CH
1915 /*
1916 * Set the writeback bit ASAP, as the I/O completion for the single
1917 * block per folio case happen hit as soon as we're submitting the bio.
1918 */
1919 folio_start_writeback(folio);
598ecfba
CH
1920
1921 /*
30deff85 1922 * Walk through the folio to find dirty areas to write back.
598ecfba 1923 */
30deff85
CH
1924 while ((rlen = iomap_find_dirty_range(folio, &pos, end_pos))) {
1925 error = iomap_writepage_map_blocks(wpc, wbc, folio, inode,
1926 pos, rlen, &count);
598ecfba
CH
1927 if (error)
1928 break;
30deff85 1929 pos += rlen;
598ecfba 1930 }
30deff85 1931
ebb7fb15 1932 if (count)
432acd55 1933 wpc->nr_folios++;
598ecfba 1934
4ce02c67
RHI
1935 /*
1936 * We can have dirty bits set past end of file in page_mkwrite path
1937 * while mapping the last partial folio. Hence it's better to clear
1938 * all the dirty bits in the folio here.
1939 */
1940 iomap_clear_range_dirty(folio, 0, folio_size(folio));
7ea1d9b4
CH
1941
1942 /*
410bb2ce
CH
1943 * Usually the writeback bit is cleared by the I/O completion handler.
1944 * But we may end up either not actually writing any blocks, or (when
1945 * there are multiple blocks in a folio) all I/O might have finished
1946 * already at this point. In that case we need to clear the writeback
1947 * bit ourselves right after unlocking the page.
7ea1d9b4 1948 */
e735c007 1949 folio_unlock(folio);
410bb2ce
CH
1950 if (ifs) {
1951 if (atomic_dec_and_test(&ifs->write_bytes_pending))
1952 folio_end_writeback(folio);
1953 } else {
1954 if (!count)
1955 folio_end_writeback(folio);
598ecfba 1956 }
3d5f3ba1 1957 mapping_set_error(inode->i_mapping, error);
598ecfba
CH
1958 return error;
1959}
1960
d585bdbe
MWO
1961static int iomap_do_writepage(struct folio *folio,
1962 struct writeback_control *wbc, void *data)
598ecfba 1963{
cc954253 1964 return iomap_writepage_map(data, wbc, folio);
598ecfba
CH
1965}
1966
598ecfba
CH
1967int
1968iomap_writepages(struct address_space *mapping, struct writeback_control *wbc,
1969 struct iomap_writepage_ctx *wpc,
1970 const struct iomap_writeback_ops *ops)
1971{
1972 int ret;
1973
c2dc7e55
CH
1974 /*
1975 * Writeback from reclaim context should never happen except in the case
1976 * of a VM regression so warn about it and refuse to write the data.
1977 */
1978 if (WARN_ON_ONCE((current->flags & (PF_MEMALLOC | PF_KSWAPD)) ==
1979 PF_MEMALLOC))
1980 return -EIO;
1981
598ecfba
CH
1982 wpc->ops = ops;
1983 ret = write_cache_pages(mapping, wbc, iomap_do_writepage, wpc);
410bb2ce 1984 return iomap_submit_ioend(wpc, ret);
598ecfba
CH
1985}
1986EXPORT_SYMBOL_GPL(iomap_writepages);
1987
1988static int __init iomap_init(void)
1989{
1990 return bioset_init(&iomap_ioend_bioset, 4 * (PAGE_SIZE / SECTOR_SIZE),
ae5535ef 1991 offsetof(struct iomap_ioend, io_bio),
598ecfba
CH
1992 BIOSET_NEED_BVECS);
1993}
1994fs_initcall(iomap_init);