rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: Benno Lossin <benno.lossin@proton.me>
To: Alice Ryhl <aliceryhl@google.com>,
	Miguel Ojeda <ojeda@kernel.org>,
	Andrew Morton <akpm@linux-foundation.org>
Cc: "Alex Gaynor" <alex.gaynor@gmail.com>,
	"Wedson Almeida Filho" <wedsonaf@gmail.com>,
	"Boqun Feng" <boqun.feng@gmail.com>,
	"Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Andreas Hindborg" <a.hindborg@samsung.com>,
	"Marco Elver" <elver@google.com>, "Coly Li" <colyli@suse.de>,
	"Paolo Abeni" <pabeni@redhat.com>,
	"Pierre Gondois" <pierre.gondois@arm.com>,
	"Ingo Molnar" <mingo@kernel.org>,
	"Jakub Kicinski" <kuba@kernel.org>,
	"Wei Yang" <richard.weiyang@gmail.com>,
	"Matthew Wilcox" <willy@infradead.org>,
	linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org,
	"Kees Cook" <kees@kernel.org>
Subject: Re: [PATCH v3 05/10] rust: list: add macro for implementing ListItem
Date: Wed, 31 Jul 2024 20:17:09 +0000	[thread overview]
Message-ID: <e6a57401-7b44-4ba5-ba9a-7948e5f7c7a1@proton.me> (raw)
In-Reply-To: <20240723-linked-list-v3-5-89db92c7dbf4@google.com>

On 23.07.24 10:22, Alice Ryhl wrote:
> diff --git a/rust/kernel/list/impl_list_item_mod.rs b/rust/kernel/list/impl_list_item_mod.rs
> new file mode 100644
> index 000000000000..9b1947371c63
> --- /dev/null
> +++ b/rust/kernel/list/impl_list_item_mod.rs
> @@ -0,0 +1,139 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +// Copyright (C) 2024 Google LLC.
> +
> +//! Helpers for implementing list traits safely.
> +
> +use crate::list::ListLinks;
> +
> +/// Declares that this type has a `ListLinks<ID>` field at a fixed offset.
> +///
> +/// This trait is only used to help implement `ListItem` safely. If `ListItem` is implemented
> +/// manually, then this trait is not needed.

Can you reference the `impl_has_list_links!` macro here to guide the
user to the safe version?

> +///
> +/// # Safety
> +///
> +/// All values of this type must have a `ListLinks<ID>` field at the given offset.
> +///
> +/// The implementation of `raw_get_list_links` must not be changed.
> +pub unsafe trait HasListLinks<const ID: u64 = 0> {
> +    /// The offset of the `ListLinks` field.
> +    const OFFSET: usize;
> +
> +    /// Returns a pointer to the [`ListLinks<T, ID>`] field.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The provided pointer must point at a valid struct of type `Self`.
> +    ///
> +    /// [`ListLinks<T, ID>`]: ListLinks
> +    // We don't really need this method, but it's necessary for the implementation of
> +    // `impl_has_work!` to be correct.

Stale comment (this has nothing to do with `impl_has_work!`).

> +    #[inline]
> +    unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut ListLinks<ID> {
> +        // SAFETY: The caller promises that the pointer is valid. The implementer promises that the
> +        // `OFFSET` constant is correct.
> +        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut ListLinks<ID> }
> +    }
> +}
> +
> +/// Implements the [`HasListLinks`] trait for the given type.
> +#[macro_export]
> +macro_rules! impl_has_list_links {
> +    ($(impl$(<$($implarg:ident),*>)?
> +       HasListLinks$(<$id:tt>)?
> +       for $self:ident $(<$($selfarg:ty),*>)?
> +       { self$(.$field:ident)* }
> +    )*) => {$(
> +        // SAFETY: The implementation of `raw_get_list_links` only compiles if the field has the
> +        // right type.
> +        //
> +        // The implementation of `raw_get_list_links` is not changed since the `addr_of_mut!` macro
> +        // is equivalent to the pointer offset operation in the trait definition.
> +        unsafe impl$(<$($implarg),*>)? $crate::list::HasListLinks$(<$id>)? for
> +            $self $(<$($selfarg),*>)?
> +        {
> +            const OFFSET: usize = ::core::mem::offset_of!(Self, $($field).*) as usize;
> +
> +            #[inline]
> +            unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut $crate::list::ListLinks$(<$id>)? {
> +                // SAFETY: The caller promises that the pointer is not dangling. We know that this
> +                // expression doesn't follow any pointers, as the `offset_of!` invocation above
> +                // would otherwise not compile.
> +                unsafe { ::core::ptr::addr_of_mut!((*ptr)$(.$field)*) }
> +            }
> +        }
> +    )*};
> +}
> +pub use impl_has_list_links;
> +
> +/// Implements the [`ListItem`] trait for the given type.
> +///
> +/// Assumes that the type implements [`HasListLinks`].

I would write "Requires", since "Assumes" sounds as if it isn't checked.

Can you also reference the `impl_has_list_links!` macro here to guide
the user to the safe version?

> +///
> +/// [`ListItem`]: crate::list::ListItem
> +#[macro_export]
> +macro_rules! impl_list_item {
> +    (
> +        impl$({$($generics:tt)*})? ListItem<$num:tt> for $t:ty {
> +            using ListLinks;
> +        } $($rest:tt)*
> +    ) => {
> +        // SAFETY: See GUARANTEES comment on each method.
> +        unsafe impl$(<$($generics)*>)? $crate::list::ListItem<$num> for $t {
> +            // GUARANTEES:
> +            // * This returns the same pointer as `prepare_to_insert` because `prepare_to_insert`
> +            //   is implemented in terms of `view_links`.
> +            // * By the type invariants of `ListLinks`, the `ListLinks` has two null pointers when
> +            //   this value is not in a list.
> +            unsafe fn view_links(me: *const Self) -> *mut $crate::list::ListLinks<$num> {
> +                // SAFETY: The caller guarantees that `me` points at a valid value of type `Self`.
> +                unsafe {
> +                    <Self as $crate::list::HasListLinks<$num>>::raw_get_list_links(me.cast_mut())
> +                }
> +            }
> +
> +            // GUARANTEES:
> +            // * `me` originates from the most recent call to `prepare_to_insert`, which just added
> +            //   `offset` to the pointer passed to `prepare_to_insert`. This method subtracts
> +            //   `offset` from `me` so it returns the pointer originally passed to
> +            //   `prepare_to_insert`.
> +            // * The pointer remains valid until the next call to `post_remove` because the caller
> +            //   of the most recent call to `prepare_to_insert` promised to retain ownership of the
> +            //   `ListArc` containing `Self` until the next call to `post_remove`. The value cannot
> +            //   be destroyed while a `ListArc` reference exists.
> +            unsafe fn view_value(me: *mut $crate::list::ListLinks<$num>) -> *const Self {
> +                let offset = <Self as $crate::list::HasListLinks<$num>>::OFFSET;
> +                // SAFETY: `me` originates from the most recent call to `prepare_to_insert`, so it
> +                // points at the field at offset `offset` in a value of type `Self`. Thus,
> +                // subtracting `offset` from `me` is still in-bounds of the allocation.
> +                unsafe { (me as *const u8).sub(offset) as *const Self }
> +            }
> +
> +            // GUARANTEES:
> +            // This implementation of `ListItem` will not give out exclusive access to the same
> +            // `ListLinks` several times because calls to `prepare_to_insert` and `post_remove`
> +            // must alternate and exclusive access is given up when `post_remove` is called.
> +            //
> +            // Other invocations of `impl_list_item!` also cannot give out exclusive access to the
> +            // same `ListLinks` because you can only implement `ListItem` once for each value of
> +            // `ID`, and the `ListLinks` fields only work with the specified `ID`.
> +            unsafe fn prepare_to_insert(me: *const Self) -> *mut $crate::list::ListLinks<$num> {
> +                // SAFETY: The caller promises that `me` points at a valid value.
> +                unsafe { <Self as $crate::list::ListItem<$num>>::view_links(me) }
> +            }
> +
> +            // GUARANTEES:
> +            // The first guarantee of `view_value` is exactly what `post_remove` guarantees.
> +            unsafe fn post_remove(me: *mut $crate::list::ListLinks<$num>) -> *const Self {
> +                // SAFETY: This violates the safety requirement that `post_remove` has not been
> +                // called since the most recent call to `prepare_to_insert`, but that is okay
> +                // because the concrete implementation of `view_value` above does not rely on that
> +                // requirement anywhere except for its second guarantee, and we don't need its
> +                // second guarantee.

I don't like the "this isn't correct, but if you look closely at the
implementations, it's fine". Do you think it would be better if you just
copy paste the impl of `view_value`?

---
Cheers,
Benno

> +                unsafe { <Self as $crate::list::ListItem<$num>>::view_value(me) }
> +            }
> +        }
> +    };
> +}
> +pub use impl_list_item;
> 
> --
> 2.45.2.1089.g2a221341d9-goog
> 


  parent reply	other threads:[~2024-07-31 20:17 UTC|newest]

Thread overview: 31+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2024-07-23  8:22 [PATCH v3 00/10] Add Rust linked list for reference counted values Alice Ryhl
2024-07-23  8:22 ` [PATCH v3 01/10] rust: init: add `assert_pinned` macro Alice Ryhl
2024-07-23  8:22 ` [PATCH v3 02/10] rust: list: add ListArc Alice Ryhl
2024-07-31 16:47   ` Benno Lossin
2024-08-06 13:16     ` Alice Ryhl
2024-08-06 14:11       ` Benno Lossin
2024-08-06 14:14     ` Miguel Ojeda
2024-07-23  8:22 ` [PATCH v3 03/10] rust: list: add tracking for ListArc Alice Ryhl
2024-07-31 17:17   ` Benno Lossin
2024-07-23  8:22 ` [PATCH v3 04/10] rust: list: add struct with prev/next pointers Alice Ryhl
2024-07-31 18:41   ` Benno Lossin
2024-08-01  9:42     ` Alice Ryhl
2024-08-01 10:45       ` Benno Lossin
2024-08-01 12:51         ` Alice Ryhl
2024-08-01 13:46           ` Benno Lossin
2024-08-01 13:47             ` Alice Ryhl
2024-07-23  8:22 ` [PATCH v3 05/10] rust: list: add macro for implementing ListItem Alice Ryhl
2024-07-31 13:03   ` Alice Ryhl
2024-07-31 20:17   ` Benno Lossin [this message]
2024-07-23  8:22 ` [PATCH v3 06/10] rust: list: add List Alice Ryhl
2024-08-01  9:11   ` Benno Lossin
2024-08-01  9:40     ` Alice Ryhl
2024-08-01 10:48       ` Benno Lossin
2024-07-23  8:22 ` [PATCH v3 07/10] rust: list: add iterators Alice Ryhl
2024-07-23  8:22 ` [PATCH v3 08/10] rust: list: add cursor Alice Ryhl
2024-07-23  8:22 ` [PATCH v3 09/10] rust: list: support heterogeneous lists Alice Ryhl
2024-08-01  9:24   ` Benno Lossin
2024-08-01  9:38     ` Alice Ryhl
2024-08-01 10:50       ` Benno Lossin
2024-08-01 12:33         ` Alice Ryhl
2024-07-23  8:22 ` [PATCH v3 10/10] rust: list: add ListArcField Alice Ryhl

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=e6a57401-7b44-4ba5-ba9a-7948e5f7c7a1@proton.me \
    --to=benno.lossin@proton.me \
    --cc=a.hindborg@samsung.com \
    --cc=akpm@linux-foundation.org \
    --cc=alex.gaynor@gmail.com \
    --cc=aliceryhl@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=colyli@suse.de \
    --cc=elver@google.com \
    --cc=gary@garyguo.net \
    --cc=kees@kernel.org \
    --cc=kuba@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=mingo@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=pabeni@redhat.com \
    --cc=pierre.gondois@arm.com \
    --cc=richard.weiyang@gmail.com \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=wedsonaf@gmail.com \
    --cc=willy@infradead.org \
    /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 a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).