BIO preparation and re-dirtying before unpin can lock each destination folio. Preparing a 128 KiB read into 4 KiB anonymous pages can take 32 lock/unlock pairs even when the buffer is dirty. Set PG_dirty directly for referenced anonymous folios outside swap cache, where folio_mark_dirty() reduces to setting the same bit. Keep the locked helper for other folios. Reclaim checks for DMA pins before allocating swap and again before writeback. If swap-cache insertion races with the test, swap's dirty callback also sets PG_dirty. The unlocked path can leave the PG_reclaim hint set. On a WD Blue SN580, 128 KiB QD32 io_uring reads into ordinary anonymous buffers reduced median issuing-thread CPU time from 12.73 to 10.86 us per I/O across five boot pairs. Throughput rose 2.2%. Registered buffers bypass per-I/O dirtying and their throughput moved by 0.03%. OpenAI reported this optimization opportunity and helped implement it. Link: https://lore.kernel.org/linux-block/20250124225104.326613-1-willy@infradead.org/ Signed-off-by: Shao Mingyin --- The read-only NVMe test alternated ordinary and registered buffers. QEMU checked anonymous data after swap-out and reload and shared ext4/tmpfs mappings after fsync and eviction. The specific race with swap-cache insertion remains untested. block/bio.c | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/block/bio.c b/block/bio.c index b0fcc69de653..e90169ca97f5 100644 --- a/block/bio.c +++ b/block/bio.c @@ -1187,6 +1187,18 @@ bool bio_add_vmalloc(struct bio *bio, void *vaddr, unsigned int len) } EXPORT_SYMBOL_GPL(bio_add_vmalloc); +static inline void bio_mark_folio_dirty(struct folio *folio) +{ + /* Anonymous folios outside swap cache have no writeback mapping. */ + if (folio_test_anon(folio) && !folio_test_swapcache(folio)) { + if (!folio_test_dirty(folio)) + folio_set_dirty(folio); + return; + } + + folio_mark_dirty_lock(folio); +} + void __bio_release_pages(struct bio *bio, bool mark_dirty) { struct folio_iter fi; @@ -1194,11 +1206,8 @@ void __bio_release_pages(struct bio *bio, bool mark_dirty) bio_for_each_folio_all(fi, bio) { size_t nr_pages; - if (mark_dirty) { - folio_lock(fi.folio); - folio_mark_dirty(fi.folio); - folio_unlock(fi.folio); - } + if (mark_dirty) + bio_mark_folio_dirty(fi.folio); nr_pages = (fi.offset + fi.length - 1) / PAGE_SIZE - fi.offset / PAGE_SIZE + 1; unpin_user_folio(fi.folio, nr_pages); @@ -1708,11 +1717,8 @@ void bio_set_pages_dirty(struct bio *bio) { struct folio_iter fi; - bio_for_each_folio_all(fi, bio) { - folio_lock(fi.folio); - folio_mark_dirty(fi.folio); - folio_unlock(fi.folio); - } + bio_for_each_folio_all(fi, bio) + bio_mark_folio_dirty(fi.folio); } /* base-commit: 9437046953b2fb3bf55b36582450ea0267df82a7 -- 2.27.0