All of lore.kernel.org
 help / color / mirror / Atom feed
From: sashiko-bot@kernel.org
To: "Vitaly Wool" <vitaly.wool@konsulko.se>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Jens Axboe" <axboe@kernel.dk>, "Miguel Ojeda" <ojeda@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>
Cc: "Boqun Feng" <boqun@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>,
	"Lorenzo Stoakes" <ljs@kernel.org>,
	"Liam R . Howlett" <liam@infradead.org>,
	linux-mm@kvack.org, "Igor B" <igor.b@beldev.am>
Subject: Re: [PATCH 1/3] rust: block: add bio segment iteration and request accessors
Date: Wed, 18 Nov 2026 23:36:22 +0000	[thread overview]
Message-ID: <sashiko-outbox-222196@kernel.org> (raw)
In-Reply-To: <20261117233211.3137168-2-vitaly.wool@konsulko.se>

Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [Medium] rust: block: NULL bi_io_vec dereference in
  SegmentIter::next()
- [Medium] rust: block: unsound safe Segment::zero() and copy_*_page()
  safety docs
- [Low] rust: block: wrong default block size in discard_granularity()
  docs
- [Low] rust: block: missing #[inline] and Bio::from_raw() INVARIANT
  comment
--

commit f73d6ca145fdbea749b64ff55a7ec48747dee38e
Author: Igor B <igor.b@beldev.am>

rust: block: add bio segment iteration and request accessors

This commit adds a Rust bio wrapper and segment iterator, request
accessors for command, sector, byte length, and bios, and GenDiskBuilder
helpers for configuring discard limits.

> diff --git a/rust/kernel/block/bio.rs b/rust/kernel/block/bio.rs
> new file mode 100644
> index 0000000000000..183f9ae6d48d9
> --- /dev/null
> +++ b/rust/kernel/block/bio.rs
> @@ -0,0 +1,253 @@

[ ... ]

> +/// A wrapper around a C [`struct bio`].
> +///
> +/// # Invariants
> +///
> +/// `self.0` is a valid `struct bio` that is part of a request owned by the
> +/// driver. Neither the bio nor its data pages are released while a `&Bio` is
> +/// alive.
> +///
> +/// [`struct bio`]: srctree/include/linux/blk_types.h
> +#[repr(transparent)]
> +pub struct Bio(Opaque<bindings::bio>);
> +
> +impl Bio {
> +    /// Create a reference to a [`Bio`] from a raw pointer.
> +    ///
> +    /// # Safety
> +    ///
> +    /// `ptr` must point to a valid `struct bio` that stays valid, and is not
> +    /// modified by anyone but the holder of the returned reference, for the
> +    /// duration of `'a`.
> +    pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::bio) -> &'a Self {
> +        // SAFETY: `Bio` is `repr(transparent)` over `bindings::bio`, and the
> +        // safety requirements of this function make the reference valid.
> +        unsafe { &*ptr.cast::<Self>() }
> +    }

[Severity: Low]
Since struct Bio has an # Invariants section, Bio::from_raw() should have
an // INVARIANT: comment explaining how the caller's safety guarantees
satisfy those invariants.

Also, in the kernel crate abstractions, small functions and functions that
forward to C bindings should be marked #[inline]; none of the new methods in
rust/kernel/block/bio.rs, rust/kernel/block/mq/gen_disk.rs, or
rust/kernel/block/mq/request.rs have #[inline].

[ ... ]

> +    /// Return an iterator over the single-page segments of this bio.
> +    ///
> +    /// This is the equivalent of the C `bio_for_each_segment()` macro.
> +    pub fn segment_iter(&self) -> SegmentIter<'_> {
> +        SegmentIter {
> +            bio: self,
> +            // SAFETY: By the type invariant `self.raw()` is valid.
> +            iter: unsafe { (*self.raw()).bi_iter },
> +        }
> +    }

[ ... ]

> +impl<'a> Iterator for SegmentIter<'a> {
> +    type Item = Segment<'a>;
> +
> +    fn next(&mut self) -> Option<Segment<'a>> {
> +        if self.iter.bi_size == 0 {
> +            return None;
> +        }
> +
> +        let sector = self.iter.bi_sector;
> +
> +        // SAFETY: By the type invariant of `Bio`, `self.bio.raw()` is valid,
> +        // and `self.iter` is a copy of its `bi_iter` that was only advanced
> +        // through `bio_advance_iter_single`, so it is within bounds.
> +        let bvec = unsafe { bindings::bio_iter_iovec(self.bio.raw(), &self.iter) };

[Severity: Medium]
Can calling Bio::segment_iter() in safe Rust cause a NULL pointer
dereference in SegmentIter::next() on a discard or write-zeroes request?

In block/blk-lib.c, bios for REQ_OP_DISCARD, REQ_OP_WRITE_ZEROES, and
REQ_OP_SECURE_ERASE are allocated with nr_vecs = 0, which sets
bio->bi_io_vec = NULL while setting bio->bi_iter.bi_size to the non-zero
byte length of the operation (and REQ_DMABUF bios store bi_dmabuf_map in
the union with bi_io_vec).  Because Request::bio_iter() and
Bio::segment_iter() are safe functions and neither checks bio_has_data()
or !bio_no_advance_iter(), iterating segments of such a bio calls
bio_iter_iovec() with bi_size > 0 and dereferences a NULL (or non-bvec)
bi_io_vec pointer.

[ ... ]

> +    /// Copy `len` bytes starting at byte `off` of this segment into `dst`
> +    /// starting at `dst_off`.
> +    ///
> +    /// Returns [`EINVAL`] if either range is out of bounds.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The caller must ensure that this call does not race with a read or
> +    /// write of the same range of `dst`.
> +    pub unsafe fn copy_to_page(
> +        &self,
> +        off: usize,
> +        dst: &Page,
> +        dst_off: usize,
> +        len: usize,
> +    ) -> Result {
> +        self.with_mapped(off, len, |src| {
> +            // SAFETY: `src` is valid for reading `len` bytes, and the caller
> +            // guarantees there is no racing access to `dst`.
> +            unsafe { dst.write_raw(src, dst_off, len) }
> +        })
> +    }
> +
> +    /// Copy `len` bytes from `src` starting at `src_off` into this segment
> +    /// starting at byte `off`.
> +    ///
> +    /// Returns [`EINVAL`] if either range is out of bounds.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The caller must ensure that this call does not race with a write to the
> +    /// same range of `src`.
> +    pub unsafe fn copy_from_page(
> +        &self,
> +        off: usize,
> +        src: &Page,
> +        src_off: usize,
> +        len: usize,
> +    ) -> Result {
> +        self.with_mapped(off, len, |dst| {
> +            // SAFETY: `dst` is valid for writing `len` bytes. The data buffer
> +            // of the bio is owned by the driver while the request is in
> +            // flight. The caller guarantees there is no racing write to `src`.
> +            unsafe { src.read_raw(dst, src_off, len) }
> +        })
> +    }
> +
> +    /// Fill `len` bytes starting at byte `off` of this segment with zeroes.
> +    ///
> +    /// Returns [`EINVAL`] if the range is out of bounds.
> +    pub fn zero(&self, off: usize, len: usize) -> Result {
> +        self.with_mapped(off, len, |dst| {
> +            // SAFETY: `dst` is valid for writing `len` bytes. The data buffer
> +            // of the bio is owned by the driver while the request is in
> +            // flight.
> +            unsafe { ptr::write_bytes(dst, 0, len) };
> +            Ok(())
> +        })
> +    }
> +}

[Severity: Medium]
Is Segment::zero(&self, ...) sound as a safe method, and are the safety
contracts on copy_to_page() and copy_from_page() complete?

Request<T> implements Send, Sync, and AlwaysRefCounted, and
Request::bio_iter(), Bio::segment_iter(), and Segment::zero() all take
&self.  Two threads holding shared &Request<T> references (or a bio with
multiple bvecs referencing the same page) can call Segment::zero()
concurrently from safe Rust, causing a data race.  Moreover, on
REQ_OP_WRITE bios the segment pages are read-only source buffers that can
point to shared kernel pages such as largest_zero_folio() in
__blkdev_issue_zero_pages(), so writing to them via Segment::zero() or
Segment::copy_from_page() corrupts shared memory.

Segment::zero() should be unsafe (matching Page::fill_zero_raw()), and the
safety requirements for zero(), copy_from_page(), and copy_to_page()
should also require that no concurrent accesses race on the segment's own
page range and that mutating methods are only called on writable request
buffers.

> diff --git a/rust/kernel/block/mq/gen_disk.rs b/rust/kernel/block/mq/gen_disk.rs
> index 0fe640f3aec63..57d5431654303 100644
> --- a/rust/kernel/block/mq/gen_disk.rs
> +++ b/rust/kernel/block/mq/gen_disk.rs

[ ... ]

> @@ -106,6 +110,25 @@ pub fn capacity_sectors(mut self, capacity: u64) -> Self {
>          self
>      }
>  
> +    /// Set the maximum number of sectors (512 bytes) the device can discard in
> +    /// a single request.
> +    ///
> +    /// Zero, the default, means that the device does not support discard.
> +    pub fn max_hw_discard_sectors(mut self, sectors: u32) -> Self {
> +        self.max_hw_discard_sectors = sectors;
> +        self
> +    }
> +
> +    /// Set the discard granularity of the device in bytes.
> +    ///
> +    /// This is the internal allocation unit of the device. Discards smaller
> +    /// than this, or not aligned to it, may not free any storage. Zero, the
> +    /// default, lets the block layer use the logical block size.
> +    pub fn discard_granularity(mut self, granularity: u32) -> Self {
> +        self.discard_granularity = granularity;
> +        self
> +    }

[Severity: Low]
Does a discard_granularity of zero default to the logical block size or
the physical block size?

In block/blk-settings.c, blk_validate_limits() clamps
lim->discard_granularity with:

    lim->discard_granularity =
        max(lim->discard_granularity, lim->physical_block_size);

so leaving discard_granularity at zero causes the block layer to use
physical_block_size rather than logical_block_size.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261117233211.3137168-1-vitaly.wool@konsulko.se?part=1


  parent reply	other threads:[~2026-11-18 23:36 UTC|newest]

Thread overview: 11+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-17 23:32 [PATCH 0/3] rust: block: add rbrd, a RAM backed block driver Vitaly Wool
2026-11-17 23:32 ` [PATCH 1/3] rust: block: add bio segment iteration and request accessors Vitaly Wool
2026-11-18 15:19   ` Andreas Hindborg
2026-11-18 23:36   ` sashiko-bot [this message]
2026-11-17 23:32 ` [PATCH 2/3] rust: page: add reference counting, raw pointers and a private bit lock Vitaly Wool
2026-11-18 15:23   ` Andreas Hindborg
2026-11-18 23:36   ` sashiko-bot
2026-11-17 23:32 ` [PATCH 3/3] rust: block: add rbrd, a RAM backed block driver Vitaly Wool
2026-11-18 23:36   ` sashiko-bot
2026-11-18 11:43 ` [PATCH 0/3] " Jan Engelhardt
2026-11-18 14:48   ` Vitaly Wool

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=sashiko-outbox-222196@kernel.org \
    --to=sashiko-bot@kernel.org \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=axboe@kernel.dk \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=gary@garyguo.net \
    --cc=igor.b@beldev.am \
    --cc=liam@infradead.org \
    --cc=linux-mm@kvack.org \
    --cc=ljs@kernel.org \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=sashiko-reviews@lists.linux.dev \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=vitaly.wool@konsulko.se \
    --cc=work@onurozkan.dev \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.