xref: /linux/fs/iomap/ioend.c (revision 1d140731753a277be36637300a0f3faa396edec1)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2016-2025 Christoph Hellwig.
4  */
5 #include <linux/bio-integrity.h>
6 #include <linux/iomap.h>
7 #include <linux/list_sort.h>
8 #include <linux/pagemap.h>
9 #include <linux/writeback.h>
10 #include <linux/fserror.h>
11 #include "internal.h"
12 #include "trace.h"
13 
14 struct bio_set iomap_ioend_bioset;
15 EXPORT_SYMBOL_GPL(iomap_ioend_bioset);
16 
17 struct iomap_ioend *iomap_init_ioend(struct inode *inode,
18 		struct bio *bio, loff_t file_offset, u16 ioend_flags)
19 {
20 	struct iomap_ioend *ioend = iomap_ioend_from_bio(bio);
21 
22 	atomic_set(&ioend->io_remaining, 1);
23 	ioend->io_error = 0;
24 	ioend->io_parent = NULL;
25 	INIT_LIST_HEAD(&ioend->io_list);
26 	ioend->io_flags = ioend_flags;
27 	ioend->io_inode = inode;
28 	ioend->io_offset = file_offset;
29 	ioend->io_size = bio->bi_iter.bi_size;
30 	ioend->io_sector = bio->bi_iter.bi_sector;
31 	ioend->io_vi = NULL;
32 	ioend->io_private = NULL;
33 	return ioend;
34 }
35 EXPORT_SYMBOL_GPL(iomap_init_ioend);
36 
37 /*
38  * We're now finished for good with this ioend structure.  Update the folio
39  * state, release holds on bios, and finally free up memory.  Do not use the
40  * ioend after this.
41  */
42 static u32 iomap_finish_ioend_buffered_write(struct iomap_ioend *ioend)
43 {
44 	struct inode *inode = ioend->io_inode;
45 	struct bio *bio = &ioend->io_bio;
46 	struct folio_iter fi;
47 	u32 folio_count = 0;
48 
49 	if (ioend->io_error) {
50 		mapping_set_error(inode->i_mapping, ioend->io_error);
51 		if (!bio_flagged(bio, BIO_QUIET)) {
52 			pr_err_ratelimited(
53 "%s: writeback error on inode %llu, offset %lld, sector %llu",
54 				inode->i_sb->s_id, inode->i_ino,
55 				ioend->io_offset, ioend->io_sector);
56 		}
57 	}
58 
59 	/* walk all folios in bio, ending page IO on them */
60 	bio_for_each_folio_all(fi, bio) {
61 		if (ioend->io_error)
62 			fserror_report_io(inode, FSERR_BUFFERED_WRITE,
63 					  folio_pos(fi.folio) + fi.offset,
64 					  fi.length, ioend->io_error,
65 					  GFP_ATOMIC);
66 		iomap_finish_folio_write(inode, fi.folio, fi.length);
67 		folio_count++;
68 	}
69 
70 	if (bio_integrity(bio))
71 		fs_bio_integrity_free(bio);
72 	bio_put(bio);	/* frees the ioend */
73 	return folio_count;
74 }
75 
76 static DEFINE_SPINLOCK(failed_ioend_lock);
77 static LIST_HEAD(failed_ioend_list);
78 
79 static void
80 iomap_fail_ioends(
81 	struct work_struct	*work)
82 {
83 	struct iomap_ioend	*ioend;
84 	struct list_head	tmp;
85 	unsigned long		flags;
86 
87 	spin_lock_irqsave(&failed_ioend_lock, flags);
88 	list_replace_init(&failed_ioend_list, &tmp);
89 	spin_unlock_irqrestore(&failed_ioend_lock, flags);
90 
91 	while ((ioend = list_first_entry_or_null(&tmp, struct iomap_ioend,
92 			io_list))) {
93 		list_del_init(&ioend->io_list);
94 		iomap_finish_ioend_buffered_write(ioend);
95 		cond_resched();
96 	}
97 }
98 
99 static DECLARE_WORK(failed_ioend_work, iomap_fail_ioends);
100 
101 static void iomap_fail_ioend_buffered(struct iomap_ioend *ioend)
102 {
103 	unsigned long flags;
104 
105 	/*
106 	 * Bounce I/O errors to a workqueue to avoid nested i_lock acquisitions
107 	 * in the fserror code.  The caller no longer owns the ioend reference
108 	 * after the spinlock drops.
109 	 */
110 	spin_lock_irqsave(&failed_ioend_lock, flags);
111 	if (list_empty(&failed_ioend_list))
112 		WARN_ON_ONCE(!schedule_work(&failed_ioend_work));
113 	list_add_tail(&ioend->io_list, &failed_ioend_list);
114 	spin_unlock_irqrestore(&failed_ioend_lock, flags);
115 }
116 
117 static void ioend_writeback_end_bio(struct bio *bio)
118 {
119 	struct iomap_ioend *ioend = iomap_ioend_from_bio(bio);
120 
121 	ioend->io_error = blk_status_to_errno(bio->bi_status);
122 	if (ioend->io_error) {
123 		iomap_fail_ioend_buffered(ioend);
124 		return;
125 	}
126 
127 	iomap_finish_ioend_buffered_write(ioend);
128 }
129 
130 /*
131  * We cannot cancel the ioend directly in case of an error, so call the bio end
132  * I/O handler with the error status here to run the normal I/O completion
133  * handler.
134  */
135 int iomap_ioend_writeback_submit(struct iomap_writepage_ctx *wpc, int error)
136 {
137 	struct iomap_ioend *ioend = wpc->wb_ctx;
138 
139 	if (!ioend->io_bio.bi_end_io)
140 		ioend->io_bio.bi_end_io = ioend_writeback_end_bio;
141 
142 	if (WARN_ON_ONCE(wpc->iomap.flags & IOMAP_F_ANON_WRITE))
143 		error = -EIO;
144 
145 	if (error) {
146 		ioend->io_bio.bi_status = errno_to_blk_status(error);
147 		bio_endio(&ioend->io_bio);
148 		return error;
149 	}
150 
151 	if (wpc->iomap.flags & IOMAP_F_INTEGRITY)
152 		fs_bio_integrity_generate(&ioend->io_bio);
153 	submit_bio(&ioend->io_bio);
154 	return 0;
155 }
156 EXPORT_SYMBOL_GPL(iomap_ioend_writeback_submit);
157 
158 static struct iomap_ioend *iomap_alloc_ioend(struct iomap_writepage_ctx *wpc,
159 		loff_t pos, u16 ioend_flags)
160 {
161 	struct bio *bio;
162 
163 	bio = bio_alloc_bioset(wpc->iomap.bdev, BIO_MAX_VECS,
164 			       REQ_OP_WRITE | wbc_to_write_flags(wpc->wbc),
165 			       GFP_NOFS, &iomap_ioend_bioset);
166 	bio->bi_iter.bi_sector = iomap_sector(&wpc->iomap, pos);
167 	bio->bi_write_hint = wpc->inode->i_write_hint;
168 	wbc_init_bio(wpc->wbc, bio);
169 	wpc->nr_folios = 0;
170 	return iomap_init_ioend(wpc->inode, bio, pos, ioend_flags);
171 }
172 
173 static bool iomap_can_add_to_ioend(struct iomap_writepage_ctx *wpc, loff_t pos,
174 		unsigned int map_len, u16 ioend_flags)
175 {
176 	struct iomap_ioend *ioend = wpc->wb_ctx;
177 
178 	if (ioend->io_bio.bi_iter.bi_size >
179 	    iomap_max_bio_size(&wpc->iomap) - map_len)
180 		return false;
181 	if (ioend_flags & IOMAP_IOEND_BOUNDARY)
182 		return false;
183 	if ((ioend_flags & IOMAP_IOEND_NOMERGE_FLAGS) !=
184 	    (ioend->io_flags & IOMAP_IOEND_NOMERGE_FLAGS))
185 		return false;
186 	if (pos != ioend->io_offset + ioend->io_size)
187 		return false;
188 	if (!(wpc->iomap.flags & IOMAP_F_ANON_WRITE) &&
189 	    iomap_sector(&wpc->iomap, pos) != bio_end_sector(&ioend->io_bio))
190 		return false;
191 	/*
192 	 * Limit ioend bio chain lengths to minimise IO completion latency. This
193 	 * also prevents long tight loops ending page writeback on all the
194 	 * folios in the ioend.
195 	 */
196 	if (wpc->nr_folios >= IOEND_BATCH_SIZE)
197 		return false;
198 	return true;
199 }
200 
201 /*
202  * Test to see if we have an existing ioend structure that we could append to
203  * first; otherwise finish off the current ioend and start another.
204  *
205  * If a new ioend is created and cached, the old ioend is submitted to the block
206  * layer instantly.  Batching optimisations are provided by higher level block
207  * plugging.
208  *
209  * At the end of a writeback pass, there will be a cached ioend remaining on the
210  * writepage context that the caller will need to submit.
211  */
212 ssize_t iomap_add_to_ioend(struct iomap_writepage_ctx *wpc, struct folio *folio,
213 		loff_t pos, loff_t end_pos, unsigned int dirty_len)
214 {
215 	struct iomap_ioend *ioend = wpc->wb_ctx;
216 	size_t poff = offset_in_folio(folio, pos);
217 	unsigned int ioend_flags = 0;
218 	unsigned int map_len = min_t(u64, dirty_len,
219 		wpc->iomap.offset + wpc->iomap.length - pos);
220 	int error;
221 
222 	trace_iomap_add_to_ioend(wpc->inode, pos, dirty_len, &wpc->iomap);
223 
224 	WARN_ON_ONCE(!folio->private && map_len < dirty_len);
225 
226 	switch (wpc->iomap.type) {
227 	case IOMAP_UNWRITTEN:
228 		ioend_flags |= IOMAP_IOEND_UNWRITTEN;
229 		break;
230 	case IOMAP_MAPPED:
231 		break;
232 	case IOMAP_HOLE:
233 		return map_len;
234 	default:
235 		WARN_ON_ONCE(1);
236 		return -EIO;
237 	}
238 
239 	if (wpc->iomap.flags & IOMAP_F_SHARED)
240 		ioend_flags |= IOMAP_IOEND_SHARED;
241 	if (folio_test_dropbehind(folio))
242 		ioend_flags |= IOMAP_IOEND_DONTCACHE;
243 	if (pos == wpc->iomap.offset && (wpc->iomap.flags & IOMAP_F_BOUNDARY))
244 		ioend_flags |= IOMAP_IOEND_BOUNDARY;
245 
246 	if (!ioend || !iomap_can_add_to_ioend(wpc, pos, map_len, ioend_flags)) {
247 new_ioend:
248 		if (ioend) {
249 			error = wpc->ops->writeback_submit(wpc, 0);
250 			if (error)
251 				return error;
252 		}
253 		wpc->wb_ctx = ioend = iomap_alloc_ioend(wpc, pos, ioend_flags);
254 	}
255 
256 	if (!bio_add_folio(&ioend->io_bio, folio, map_len, poff))
257 		goto new_ioend;
258 
259 	/*
260 	 * Clamp io_offset and io_size to the incore EOF so that ondisk
261 	 * file size updates in the ioend completion are byte-accurate.
262 	 * This avoids recovering files with zeroed tail regions when
263 	 * writeback races with appending writes:
264 	 *
265 	 *    Thread 1:                  Thread 2:
266 	 *    ------------               -----------
267 	 *    write [A, A+B]
268 	 *    update inode size to A+B
269 	 *    submit I/O [A, A+BS]
270 	 *                               write [A+B, A+B+C]
271 	 *                               update inode size to A+B+C
272 	 *    <I/O completes, updates disk size to min(A+B+C, A+BS)>
273 	 *    <power failure>
274 	 *
275 	 *  After reboot:
276 	 *    1) with A+B+C < A+BS, the file has zero padding in range
277 	 *       [A+B, A+B+C]
278 	 *
279 	 *    |<     Block Size (BS)   >|
280 	 *    |DDDDDDDDDDDD0000000000000|
281 	 *    ^           ^        ^
282 	 *    A          A+B     A+B+C
283 	 *                       (EOF)
284 	 *
285 	 *    2) with A+B+C > A+BS, the file has zero padding in range
286 	 *       [A+B, A+BS]
287 	 *
288 	 *    |<     Block Size (BS)   >|<     Block Size (BS)    >|
289 	 *    |DDDDDDDDDDDD0000000000000|00000000000000000000000000|
290 	 *    ^           ^             ^           ^
291 	 *    A          A+B           A+BS       A+B+C
292 	 *                             (EOF)
293 	 *
294 	 *    D = Valid Data
295 	 *    0 = Zero Padding
296 	 *
297 	 * Note that this defeats the ability to chain the ioends of
298 	 * appending writes.
299 	 */
300 	ioend->io_size += map_len;
301 	if (ioend->io_offset + ioend->io_size > end_pos)
302 		ioend->io_size = end_pos - ioend->io_offset;
303 
304 	wbc_account_cgroup_owner(wpc->wbc, folio, map_len);
305 	return map_len;
306 }
307 EXPORT_SYMBOL_GPL(iomap_add_to_ioend);
308 
309 static u32 iomap_finish_ioend(struct iomap_ioend *ioend, int error)
310 {
311 	if (ioend->io_parent) {
312 		struct bio *bio = &ioend->io_bio;
313 
314 		ioend = ioend->io_parent;
315 		bio_put(bio);
316 	}
317 
318 	if (error)
319 		cmpxchg(&ioend->io_error, 0, error);
320 
321 	if (!atomic_dec_and_test(&ioend->io_remaining))
322 		return 0;
323 
324 	if (!ioend->io_error &&
325 	    bio_integrity(&ioend->io_bio) &&
326 	    bio_op(&ioend->io_bio) == REQ_OP_READ) {
327 		ioend->io_error = fs_bio_integrity_verify(&ioend->io_bio,
328 			ioend->io_sector, ioend->io_size);
329 	}
330 
331 	if (ioend->io_flags & IOMAP_IOEND_DIRECT)
332 		return iomap_finish_ioend_direct(ioend);
333 	if (bio_op(&ioend->io_bio) == REQ_OP_READ)
334 		return iomap_finish_ioend_buffered_read(ioend);
335 	return iomap_finish_ioend_buffered_write(ioend);
336 }
337 
338 /*
339  * Ioend completion routine for merged bios. This can only be called from task
340  * contexts as merged ioends can be of unbound length. Hence we have to break up
341  * the writeback completions into manageable chunks to avoid long scheduler
342  * holdoffs. We aim to keep scheduler holdoffs down below 10ms so that we get
343  * good batch processing throughput without creating adverse scheduler latency
344  * conditions.
345  */
346 void iomap_finish_ioends(struct iomap_ioend *ioend, int error)
347 {
348 	struct list_head tmp;
349 	u32 completions;
350 
351 	might_sleep();
352 
353 	list_replace_init(&ioend->io_list, &tmp);
354 	completions = iomap_finish_ioend(ioend, error);
355 
356 	while (!list_empty(&tmp)) {
357 		if (completions > IOEND_BATCH_SIZE * 8) {
358 			cond_resched();
359 			completions = 0;
360 		}
361 		ioend = list_first_entry(&tmp, struct iomap_ioend, io_list);
362 		list_del_init(&ioend->io_list);
363 		completions += iomap_finish_ioend(ioend, error);
364 	}
365 }
366 EXPORT_SYMBOL_GPL(iomap_finish_ioends);
367 
368 /*
369  * We can merge two adjacent ioends if they have the same set of work to do.
370  */
371 static bool iomap_ioend_can_merge(struct iomap_ioend *ioend,
372 		struct iomap_ioend *next)
373 {
374 	/*
375 	 * There is no point in merging reads as there is no completion
376 	 * processing that can be easily batched up for them.
377 	 */
378 	if (bio_op(&ioend->io_bio) == REQ_OP_READ ||
379 	    bio_op(&next->io_bio) == REQ_OP_READ)
380 		return false;
381 
382 	if (ioend->io_bio.bi_status != next->io_bio.bi_status)
383 		return false;
384 	if (next->io_flags & IOMAP_IOEND_BOUNDARY)
385 		return false;
386 	if ((ioend->io_flags & IOMAP_IOEND_NOMERGE_FLAGS) !=
387 	    (next->io_flags & IOMAP_IOEND_NOMERGE_FLAGS))
388 		return false;
389 	if (ioend->io_offset + ioend->io_size != next->io_offset)
390 		return false;
391 	/*
392 	 * Do not merge physically discontiguous ioends. The filesystem
393 	 * completion functions will have to iterate the physical
394 	 * discontiguities even if we merge the ioends at a logical level, so
395 	 * we don't gain anything by merging physical discontiguities here.
396 	 *
397 	 * We cannot use bio->bi_iter.bi_sector here as it is modified during
398 	 * submission so does not point to the start sector of the bio at
399 	 * completion.
400 	 */
401 	if (ioend->io_sector + (ioend->io_size >> SECTOR_SHIFT) !=
402 	    next->io_sector)
403 		return false;
404 	return true;
405 }
406 
407 void iomap_ioend_try_merge(struct iomap_ioend *ioend,
408 		struct list_head *more_ioends)
409 {
410 	struct iomap_ioend *next;
411 
412 	INIT_LIST_HEAD(&ioend->io_list);
413 
414 	while ((next = list_first_entry_or_null(more_ioends, struct iomap_ioend,
415 			io_list))) {
416 		if (!iomap_ioend_can_merge(ioend, next))
417 			break;
418 		list_move_tail(&next->io_list, &ioend->io_list);
419 		ioend->io_size += next->io_size;
420 	}
421 }
422 EXPORT_SYMBOL_GPL(iomap_ioend_try_merge);
423 
424 static int iomap_ioend_compare(void *priv, const struct list_head *a,
425 		const struct list_head *b)
426 {
427 	struct iomap_ioend *ia = container_of(a, struct iomap_ioend, io_list);
428 	struct iomap_ioend *ib = container_of(b, struct iomap_ioend, io_list);
429 
430 	if (ia->io_offset < ib->io_offset)
431 		return -1;
432 	if (ia->io_offset > ib->io_offset)
433 		return 1;
434 	return 0;
435 }
436 
437 void iomap_sort_ioends(struct list_head *ioend_list)
438 {
439 	list_sort(NULL, ioend_list, iomap_ioend_compare);
440 }
441 EXPORT_SYMBOL_GPL(iomap_sort_ioends);
442 
443 /*
444  * Split up to the first @max_len bytes from @ioend if the ioend covers more
445  * than @max_len bytes.
446  *
447  * If @is_append is set, the split will be based on the hardware limits for
448  * REQ_OP_ZONE_APPEND commands and can be less than @max_len if the hardware
449  * limits don't allow the entire @max_len length.
450  *
451  * The bio embedded into @ioend must be a REQ_OP_WRITE because the block layer
452  * does not allow splitting REQ_OP_ZONE_APPEND bios.  The file systems has to
453  * switch the operation after this call, but before submitting the bio.
454  */
455 struct iomap_ioend *iomap_split_ioend(struct iomap_ioend *ioend,
456 		unsigned int max_len, bool is_append)
457 {
458 	struct bio *bio = &ioend->io_bio;
459 	struct iomap_ioend *split_ioend;
460 	unsigned int nr_segs;
461 	int sector_offset;
462 	struct bio *split;
463 
464 	if (is_append) {
465 		struct queue_limits *lim = bdev_limits(bio->bi_bdev);
466 
467 		max_len = min(max_len,
468 			      lim->max_zone_append_sectors << SECTOR_SHIFT);
469 
470 		sector_offset = bio_split_rw_at(bio, lim, &nr_segs, max_len);
471 		if (unlikely(sector_offset < 0))
472 			return ERR_PTR(sector_offset);
473 		if (!sector_offset)
474 			return NULL;
475 	} else {
476 		if (bio->bi_iter.bi_size <= max_len)
477 			return NULL;
478 		sector_offset = max_len >> SECTOR_SHIFT;
479 	}
480 
481 	/* ensure the split ioend is still block size aligned */
482 	sector_offset = ALIGN_DOWN(sector_offset << SECTOR_SHIFT,
483 			i_blocksize(ioend->io_inode)) >> SECTOR_SHIFT;
484 
485 	split = bio_split(bio, sector_offset, GFP_NOFS, &iomap_ioend_bioset);
486 	if (IS_ERR(split))
487 		return ERR_CAST(split);
488 	split->bi_private = bio->bi_private;
489 	split->bi_end_io = bio->bi_end_io;
490 
491 	split_ioend = iomap_init_ioend(ioend->io_inode, split, ioend->io_offset,
492 			ioend->io_flags);
493 	split_ioend->io_parent = ioend;
494 
495 	atomic_inc(&ioend->io_remaining);
496 	ioend->io_offset += split_ioend->io_size;
497 	ioend->io_size -= split_ioend->io_size;
498 
499 	split_ioend->io_sector = ioend->io_sector;
500 	if (!is_append)
501 		ioend->io_sector += (split_ioend->io_size >> SECTOR_SHIFT);
502 	return split_ioend;
503 }
504 EXPORT_SYMBOL_GPL(iomap_split_ioend);
505 
506 static int __init iomap_ioend_init(void)
507 {
508 	return bioset_init(&iomap_ioend_bioset, 4 * (PAGE_SIZE / SECTOR_SIZE),
509 			   offsetof(struct iomap_ioend, io_bio),
510 			   BIOSET_NEED_BVECS);
511 }
512 fs_initcall(iomap_ioend_init);
513