block: Fix iterating over an empty bio with bio_for_each_folio_all
authorMatthew Wilcox (Oracle) <willy@infradead.org>
Tue, 16 Jan 2024 21:29:59 +0000 (21:29 +0000)
committerJens Axboe <axboe@kernel.dk>
Tue, 16 Jan 2024 22:02:25 +0000 (15:02 -0700)
If the bio contains no data, bio_first_folio() calls page_folio() on a
NULL pointer and oopses.  Move the test that we've reached the end of
the bio from bio_next_folio() to bio_first_folio().

Reported-by: syzbot+8b23309d5788a79d3eea@syzkaller.appspotmail.com
Reported-by: syzbot+004c1e0fced2b4bc3dcc@syzkaller.appspotmail.com
Fixes: 640d1930bef4 ("block: Add bio_for_each_folio_all()")
Cc: stable@vger.kernel.org
Signed-off-by: Matthew Wilcox (Oracle) <willy@infradead.org>
Link: https://lore.kernel.org/r/20240116212959.3413014-1-willy@infradead.org
[axboe: add unlikely() to error case]
Signed-off-by: Jens Axboe <axboe@kernel.dk>
include/linux/bio.h

index ec4db73e5f4ec42409c38d228dcf3a9d9c42c184..875d792bffff827aa2f489a7aa1b631810750b10 100644 (file)
@@ -286,6 +286,11 @@ static inline void bio_first_folio(struct folio_iter *fi, struct bio *bio,
 {
        struct bio_vec *bvec = bio_first_bvec_all(bio) + i;
 
+       if (unlikely(i >= bio->bi_vcnt)) {
+               fi->folio = NULL;
+               return;
+       }
+
        fi->folio = page_folio(bvec->bv_page);
        fi->offset = bvec->bv_offset +
                        PAGE_SIZE * (bvec->bv_page - &fi->folio->page);
@@ -303,10 +308,8 @@ static inline void bio_next_folio(struct folio_iter *fi, struct bio *bio)
                fi->offset = 0;
                fi->length = min(folio_size(fi->folio), fi->_seg_count);
                fi->_next = folio_next(fi->folio);
-       } else if (fi->_i + 1 < bio->bi_vcnt) {
-               bio_first_folio(fi, bio, fi->_i + 1);
        } else {
-               fi->folio = NULL;
+               bio_first_folio(fi, bio, fi->_i + 1);
        }
 }