From nobody Mon Sep 16 19:06:39 2024 Received: from mail-yb1-f201.google.com (mail-yb1-f201.google.com [209.85.219.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9C64F61FCF for ; Fri, 26 Jul 2024 19:57:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023874; cv=none; b=b6HCNnC0AmhxO2xcZKoidF1hfPIqaQkVEsKXFrukASHHlGrjn+nTYyWDLB4eKAZdQGKxEYYCr6sALrpyQM22qREjRR9Xhqo8IgW7rjZqIf8rSd+fWJ1b5nxMhOi8zaHWYFi0jsAJJELQVoJYO0Wcz0UzsOUObE5UKiomLUWx1sk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023874; c=relaxed/simple; bh=JMYAJfnvh5fBjtCAE9lnpRby5Iz4gLoiR7otAicAG7Q=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=eFF9n204qDDK1xyA9WTd8wbhJKdrDTaZh+U7oHfPucGdc6cdZg9TRyEHFKn+SH3ITJSomWLcI27mw7o5DfQpjtt6PwT3un8nVtrVTZ3gdm7zvbRMYb/BwVKARbDPy573tkyF8ACCcrkkyabaauhZ5GhGfLtIT0WwlKw+aik0FHc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=HLYaDYlN; arc=none smtp.client-ip=209.85.219.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="HLYaDYlN" Received: by mail-yb1-f201.google.com with SMTP id 3f1490d57ef6-e0b2ca2952eso113660276.0 for ; Fri, 26 Jul 2024 12:57:52 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1722023871; x=1722628671; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=nsba2l+mTog8DKmlCLg5ao+hwsKRjwNNTQ3oaykOYeU=; b=HLYaDYlNRmNdRCZB3f3lZBegM0apDoC2d7Xx7ssqet6uRoqmb2uJYVYwxWfWF8x3jM 9zIXVPJol5PeuJJJKTnwvaHd4AY+U3MgHuXEusUpY33dtjJRuahKWUK5Pk5zug2PW0tL 5kCY3wUFK+R2IO9w+pbGChHeTkpLK/JrnFsmMOZY0ZuxSnmAEmp2cqcQ0CW26zblIQeL nov5BRYXK1d9KrbuSGehM8vrsXbQXqyqwwclCAH5UyyyFFODvjTckFDKOBhi646E2yvX Cw2vtEKra931Pfx2s6Pu2WZ6O9GtzXVuBCTJ8YUHjarqgnPRg7cLUnOFssFd5biRFhdL HN5Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722023871; x=1722628671; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=nsba2l+mTog8DKmlCLg5ao+hwsKRjwNNTQ3oaykOYeU=; b=dd3M8/KXa0gQVCMfd6g86IoHR69uTMXwwB6zio7KpYE21t1QvTOilWeuESPZuXeKic FYmzGIauRPfD6ywTfCd5oov0J5b+hmcaXS04m7RoqQf3Dul76TOGMxVDYvXCl65VGC0a P6Nkzry7NaTnaGzTWP/HXwWLvjfuSjcBjCKc2acuW/sX7yA4GR0pT4jGzfuHSU7Bb2/d 6wJX1dxaloPtphUdOPOTVj2cRzH2TZ5Nt5ofcKJu/ANG52JilLA90Q3qrXhkc0SllU5C /TeYcOFPU1BfwNWjGSOPXfqOTRi7HPAioc0j7wl1peQmHyLTQhwAUtZEQ9256vsjexm9 4YnA== X-Forwarded-Encrypted: i=1; AJvYcCXZxwvCEA3MF12U5J0NObKNVwedwyFYdNhQY1J1YavnfzfqY9ezcU3FWdkRTvJGvgQ+207aM/D2JKoaild9fcGNtmsJnL2oLjFeMB0W X-Gm-Message-State: AOJu0YwQkqRk/15rlWFAaWlqaf9frO//gVCU6ahdRNyB8KNgDq8KbtSy +g7TkBdqb/UPX0J1xOGqlHOHZ3aAeVn8AyQZ2Q6Ikg79eE69gxg1wS8WxJnU05XCtTpE9asIuud c+XSiKFU2h92uv8nf6dEdTdo2FQ== X-Google-Smtp-Source: AGHT+IFV09z4ES9eTc1iwHg44IFOc1rJLNlXM+zIS2NRSs9E8mi20tWIoRHVg0rk6F7j6t+9cKH8vnFmQ+2I9wUdlrk= X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a05:6902:181d:b0:e03:5144:1d48 with SMTP id 3f1490d57ef6-e0b5452490amr1280276.11.1722023871606; Fri, 26 Jul 2024 12:57:51 -0700 (PDT) Date: Fri, 26 Jul 2024 19:57:40 +0000 In-Reply-To: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> X-Mailer: b4 0.13.0 Message-ID: <20240726-b4-rbtree-v7-1-aee88caaf97c@google.com> Subject: [PATCH v7 1/6] rust: kernel: add `drop_contents` to `BoxExt` From: Matt Gilbride To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?=" , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Christian Brauner Cc: Rob Landley , Davidlohr Bueso , Michel Lespinasse , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matt Gilbride Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable From: Benno Lossin Sometimes (see [1]) it is necessary to drop the value inside of a `Box`, but retain the allocation. For example to reuse the allocation in the future. Introduce a new function `drop_contents` that turns a `Box` into `Box>` by dropping the value. Signed-off-by: Benno Lossin Link: https://lore.kernel.org/rust-for-linux/20240418-b4-rbtree-v3-5-323e13= 4390ce@google.com/ [1] Reviewed-by: Boqun Feng --- rust/kernel/alloc/box_ext.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc/box_ext.rs b/rust/kernel/alloc/box_ext.rs index 829cb1c1cf9e..557895db4f48 100644 --- a/rust/kernel/alloc/box_ext.rs +++ b/rust/kernel/alloc/box_ext.rs @@ -4,7 +4,7 @@ =20 use super::{AllocError, Flags}; use alloc::boxed::Box; -use core::mem::MaybeUninit; +use core::{mem::MaybeUninit, ptr}; =20 /// Extensions to [`Box`]. pub trait BoxExt: Sized { @@ -17,6 +17,20 @@ pub trait BoxExt: Sized { /// /// The allocation may fail, in which case an error is returned. fn new_uninit(flags: Flags) -> Result>, AllocError>; + + /// Drops the contents, but keeps the allocation. + /// + /// # Examples + /// + /// ``` + /// use kernel::alloc::flags; + /// + /// let value =3D Box::new([0; 32], flags::GFP_KERNEL); + /// let value =3D value.unwrap().drop_contents(); + /// // Now we can re-use `value`: + /// Box::write(value, [1; 32]); + /// ``` + fn drop_contents(self) -> Box>; } =20 impl BoxExt for Box { @@ -53,4 +67,12 @@ fn new_uninit(flags: Flags) -> Result= >, AllocError> { // zero-sized types, we use `NonNull::dangling`. Ok(unsafe { Box::from_raw(ptr) }) } + + fn drop_contents(self) -> Box> { + let ptr =3D Box::into_raw(self); + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. + unsafe { ptr::drop_in_place(ptr) }; + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. + unsafe { Box::from_raw(ptr.cast()) } + } } --=20 2.46.0.rc1.232.g9752f9e123-goog From nobody Mon Sep 16 19:06:39 2024 Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id EEC2313CF9C for ; Fri, 26 Jul 2024 19:57:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023876; cv=none; b=aeIQmKUZpA6bW3Sf9rkrYDf50C1e+8UcyMIgeojiU9NFSDhITdMbCArlTnjQlmQPw7WmKHQljdf7NacDp8LkQ/pHLDtsUaDqa0bqjpuB5ExTEMGOg6gd83D/ObYCO+Q1sxYYGXJvVkuBLH1TMMnVQhLpUh0uey99s5N9jcFPCq0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023876; c=relaxed/simple; bh=2VKk3FUDlYlHReLlrlCNsQ09tx2CaHlVERy+wm/mVu4=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=q5wlf7yhq1IViRgMylZN70PpEsYpgtSVl1x80oOfNg1ntMygz+aVwkI61PjEuuqt5MDRjTVuVMkYlXoFUp5A3Wn3v+tiC0+O9h3ZGDrO4d7pfbKJxeX7CRCo9tGwTtoc54VAQQGM/HRCJv7GbJtdZTlwFrOwf5MCL11zPOe28ak= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=jLlkH8Sr; arc=none smtp.client-ip=209.85.219.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="jLlkH8Sr" Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-e035f7b5976so221219276.0 for ; Fri, 26 Jul 2024 12:57:53 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1722023873; x=1722628673; darn=vger.kernel.org; h=content-transfer-encoding:cc:to:from:subject:message-id:references :mime-version:in-reply-to:date:from:to:cc:subject:date:message-id :reply-to; bh=XYKPlgZkB15fqyZ0dTQtThhTtnaeO6vpmsGLPMhJuOU=; b=jLlkH8Srlf+e+pF1AwYK3AjgiYFXHhGH5pI/vVtt3zpX0S0lbMIY4jw8KNLQbUi0Nz TMJEfWNAvynP5Fgq+1ulF3RdnSjbaPPMKQuD0CMqDY4lXOPFSvXKYiJVHiDZGimGeaZH UG3T/C/uAY2PgdZukVAXqAlLwO0nXxLABUUo0Et2qPg7y438c5f75AnmPaM4q1A7YdHs VKpQaG31mxdUsI9YWWJLUS5eqRydkoRFCf2F0t+qMC2H60lxksvI9Tqp9mcn4bC6U3XF xMlMJPkvd+VrNJmLif7Y8OaoekHamqbKdjjIdb6kvSkYiqOXVFrOL070KBtE42OUQwSi GRrg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722023873; x=1722628673; h=content-transfer-encoding:cc:to:from:subject:message-id:references :mime-version:in-reply-to:date:x-gm-message-state:from:to:cc:subject :date:message-id:reply-to; bh=XYKPlgZkB15fqyZ0dTQtThhTtnaeO6vpmsGLPMhJuOU=; b=Z7kfn/D2J3n4zjMba98Pg2wM+KtII9CR19vDMAmTkEmWvL/3dJ+9ovf5zqoUZyRYmp mk2A65WigeOO82B7zgyCFZQs/PV/pXOO/RLFr7apNwVk/ZgyC4343SXCAgLRsIzktwQR Z6M+nNZTEN0ia2Io4aOlMUtGa0F01gOOsD7TDHoQE5rYxd2MsUz4c0glKM/Cw/l+dcLy 18zEB5EhKIQVpOcA+/hURj6cq2+Wi+hsEb9hijz1pOtSo+al110SsKkbze5cEkS9HTGH KD1km/hhMm5Q2OvJUZ96jOTq+eSB/mTcxV7FDbLlh+AROnOuNs+OOVFMrxgqpTw3Sguq LO0A== X-Forwarded-Encrypted: i=1; AJvYcCVmoFQ64WFkw4OS+g6Xulrd90EMqUT1rdWZ0WbOGLSDlFj3zR3bDghRM76fDTihRaxIaFN4asGpESP/18YxotsIsrcwJlfHo0GfNcA2 X-Gm-Message-State: AOJu0YxsUeqFTv6s4TSz2F8DMdfeActWiJSWk/SeUedTUJP1JH3hXMQr aXWvWNKLNIf5AI10XSysE+ptL4WFbhKhoMkGczpA4SpQ4NfN6dcO8Daes19oW9aws+b3EAGi+98 cdJxsSjBaACRNYqfBRyv8eNPZOw== X-Google-Smtp-Source: AGHT+IHprPEeo15PjcQwCDp/lCM105NI16F/+Sqn9rf+V5UlpEuCbOzI4orXfCGTY2KZXHlCdkd9/qqlVqldugBTFLU= X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a05:6902:c0a:b0:e05:a890:5aaa with SMTP id 3f1490d57ef6-e0b555474d7mr10091276.1.1722023872864; Fri, 26 Jul 2024 12:57:52 -0700 (PDT) Date: Fri, 26 Jul 2024 19:57:41 +0000 In-Reply-To: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> X-Mailer: b4 0.13.0 Message-ID: <20240726-b4-rbtree-v7-2-aee88caaf97c@google.com> Subject: [PATCH v7 2/6] rust: rbtree: add red-black tree implementation backed by the C version From: Matt Gilbride To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?=" , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Christian Brauner Cc: Rob Landley , Davidlohr Bueso , Michel Lespinasse , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matt Gilbride Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable From: Wedson Almeida Filho The rust rbtree exposes a map-like interface over keys and values, backed by the kernel red-black tree implementation. Values can be inserted, deleted, and retrieved from a `RBTree` by key. This base abstraction is used by binder to store key/value pairs and perform lookups, for example the patch "[PATCH RFC 03/20] rust_binder: add threading support" in the binder RFC [1]. Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-3-08ba= 9197f637@google.com/ [1] Signed-off-by: Wedson Almeida Filho Reviewed-by: Alice Ryhl Tested-by: Alice Ryhl Signed-off-by: Matt Gilbride Reviewed-by: Boqun Feng --- rust/helpers.c | 7 + rust/kernel/lib.rs | 1 + rust/kernel/rbtree.rs | 432 ++++++++++++++++++++++++++++++++++++++++++++++= ++++ 3 files changed, 440 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 4c8b7b92a4f4..608b38c0b3e8 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -157,6 +157,13 @@ void rust_helper_init_work_with_key(struct work_struct= *work, work_func_t func, } EXPORT_SYMBOL_GPL(rust_helper_init_work_with_key); =20 +void rust_helper_rb_link_node(struct rb_node *node, struct rb_node *parent, + struct rb_node **rb_link) +{ + rb_link_node(node, parent, rb_link); +} +EXPORT_SYMBOL_GPL(rust_helper_rb_link_node); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indi= ces. diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 9a943d99c71a..dc2678803637 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -37,6 +37,7 @@ pub mod net; pub mod prelude; pub mod print; +pub mod rbtree; mod static_assert; #[doc(hidden)] pub mod std_vendor; diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs new file mode 100644 index 000000000000..a515bfa80113 --- /dev/null +++ b/rust/kernel/rbtree.rs @@ -0,0 +1,432 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Red-black trees. +//! +//! C header: [`include/linux/rbtree.h`](srctree/include/linux/rbtree.h) +//! +//! Reference: + +use crate::{alloc::Flags, bindings, container_of, error::Result, prelude::= *}; +use alloc::boxed::Box; +use core::{ + cmp::{Ord, Ordering}, + marker::PhantomData, + mem::MaybeUninit, + ptr::{addr_of_mut, NonNull}, +}; + +/// A red-black tree with owned nodes. +/// +/// It is backed by the kernel C red-black trees. +/// +/// # Invariants +/// +/// Non-null parent/children pointers stored in instances of the `rb_node`= C struct are always +/// valid, and pointing to a field of our internal representation [`Node`]. +/// +/// # Examples +/// +/// In the example below we do several operations on a tree. We note that = insertions may fail if +/// the system is out of memory. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNode, RBTreeNodeRese= rvation}}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert three elements. +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// +/// // Check the nodes we just inserted. +/// { +/// assert_eq!(tree.get(&10).unwrap(), &100); +/// assert_eq!(tree.get(&20).unwrap(), &200); +/// assert_eq!(tree.get(&30).unwrap(), &300); +/// } +/// +/// // Replace one of the elements. +/// tree.try_create_and_insert(10, 1000, flags::GFP_KERNEL)?; +/// +/// // Check that the tree reflects the replacement. +/// { +/// assert_eq!(tree.get(&10).unwrap(), &1000); +/// assert_eq!(tree.get(&20).unwrap(), &200); +/// assert_eq!(tree.get(&30).unwrap(), &300); +/// } +/// +/// // Change the value of one of the elements. +/// *tree.get_mut(&30).unwrap() =3D 3000; +/// +/// // Check that the tree reflects the update. +/// { +/// assert_eq!(tree.get(&10).unwrap(), &1000); +/// assert_eq!(tree.get(&20).unwrap(), &200); +/// assert_eq!(tree.get(&30).unwrap(), &3000); +/// } +/// +/// // Remove an element. +/// tree.remove(&10); +/// +/// // Check that the tree reflects the removal. +/// { +/// assert_eq!(tree.get(&10), None); +/// assert_eq!(tree.get(&20).unwrap(), &200); +/// assert_eq!(tree.get(&30).unwrap(), &3000); +/// } +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// In the example below, we first allocate a node, acquire a spinlock, th= en insert the node into +/// the tree. This is useful when the insertion context does not allow sle= eping, for example, when +/// holding a spinlock. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNode}, sync::SpinLoc= k}; +/// +/// fn insert_test(tree: &SpinLock>) -> Result { +/// // Pre-allocate node. This may fail (as it allocates memory). +/// let node =3D RBTreeNode::new(10, 100, flags::GFP_KERNEL)?; +/// +/// // Insert node while holding the lock. It is guaranteed to succeed= with no allocation +/// // attempts. +/// let mut guard =3D tree.lock(); +/// guard.insert(node); +/// Ok(()) +/// } +/// ``` +/// +/// In the example below, we reuse an existing node allocation from an ele= ment we removed. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::{RBTree, RBTreeNodeReservation}}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert three elements. +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// +/// // Check the nodes we just inserted. +/// { +/// assert_eq!(tree.get(&10).unwrap(), &100); +/// assert_eq!(tree.get(&20).unwrap(), &200); +/// assert_eq!(tree.get(&30).unwrap(), &300); +/// } +/// +/// // Remove a node, getting back ownership of it. +/// let existing =3D tree.remove(&30).unwrap(); +/// +/// // Check that the tree reflects the removal. +/// { +/// assert_eq!(tree.get(&10).unwrap(), &100); +/// assert_eq!(tree.get(&20).unwrap(), &200); +/// assert_eq!(tree.get(&30), None); +/// } +/// +/// // Create a preallocated reservation that we can re-use later. +/// let reservation =3D RBTreeNodeReservation::new(flags::GFP_KERNEL)?; +/// +/// // Insert a new node into the tree, reusing the previous allocation. T= his is guaranteed to +/// // succeed (no memory allocations). +/// tree.insert(reservation.into_node(15, 150)); +/// +/// // Check that the tree reflect the new insertion. +/// { +/// assert_eq!(tree.get(&10).unwrap(), &100); +/// assert_eq!(tree.get(&15).unwrap(), &150); +/// assert_eq!(tree.get(&20).unwrap(), &200); +/// } +/// +/// # Ok::<(), Error>(()) +/// ``` +pub struct RBTree { + root: bindings::rb_root, + _p: PhantomData>, +} + +// SAFETY: An [`RBTree`] allows the same kinds of access to its values tha= t a struct allows to its +// fields, so we use the same Send condition as would be used for a struct= with K and V fields. +unsafe impl Send for RBTree {} + +// SAFETY: An [`RBTree`] allows the same kinds of access to its values tha= t a struct allows to its +// fields, so we use the same Sync condition as would be used for a struct= with K and V fields. +unsafe impl Sync for RBTree {} + +impl RBTree { + /// Creates a new and empty tree. + pub fn new() -> Self { + Self { + // INVARIANT: There are no nodes in the tree, so the invariant= holds vacuously. + root: bindings::rb_root::default(), + _p: PhantomData, + } + } +} + +impl RBTree +where + K: Ord, +{ + /// Tries to insert a new value into the tree. + /// + /// It overwrites a node if one already exists with the same key and r= eturns it (containing the + /// key/value pair). Returns [`None`] if a node with the same key didn= 't already exist. + /// + /// Returns an error if it cannot allocate memory for the new node. + pub fn try_create_and_insert( + &mut self, + key: K, + value: V, + flags: Flags, + ) -> Result>> { + Ok(self.insert(RBTreeNode::new(key, value, flags)?)) + } + + /// Inserts a new node into the tree. + /// + /// It overwrites a node if one already exists with the same key and r= eturns it (containing the + /// key/value pair). Returns [`None`] if a node with the same key didn= 't already exist. + /// + /// This function always succeeds. + pub fn insert(&mut self, RBTreeNode { node }: RBTreeNode) -> Opt= ion> { + let node =3D Box::into_raw(node); + // SAFETY: `node` is valid at least until we call `Box::from_raw`,= which only happens when + // the node is removed or replaced. + let node_links =3D unsafe { addr_of_mut!((*node).links) }; + + // The parameters of `rb_link_node` are as follows: + // - `node`: A pointer to an uninitialized node being inserted. + // - `parent`: A pointer to an existing node in the tree. One of i= ts child pointers must be + // null, and `node` will become a child of `parent` by re= placing that child pointer + // with a pointer to `node`. + // - `rb_link`: A pointer to either the left-child or right-child = field of `parent`. This + // specifies which child of `parent` should hold `node` a= fter this call. The + // value of `*rb_link` must be null before the call to `r= b_link_node`. If the + // red/black tree is empty, then it=E2=80=99s also possib= le for `parent` to be null. In + // this case, `rb_link` is a pointer to the `root` field = of the red/black tree. + // + // We will traverse the tree looking for a node that has a null po= inter as its child, + // representing an empty subtree where we can insert our new node.= We need to make sure + // that we preserve the ordering of the nodes in the tree. In each= iteration of the loop + // we store `parent` and `child_field_of_parent`, and the new `nod= e` will go somewhere + // in the subtree of `parent` that `child_field_of_parent` points = at. Once + // we find an empty subtree, we can insert the new node using `rb_= link_node`. + let mut parent =3D core::ptr::null_mut(); + let mut child_field_of_parent: &mut *mut bindings::rb_node =3D &mu= t self.root.rb_node; + while !child_field_of_parent.is_null() { + parent =3D *child_field_of_parent; + + // We need to determine whether `node` should be the left or r= ight child of `parent`, + // so we will compare with the `key` field of `parent` a.k.a. = `this` below. + // + // SAFETY: By the type invariant of `Self`, all non-null `rb_n= ode` pointers stored in `self` + // point to the links field of `Node` objects. + let this =3D unsafe { container_of!(parent, Node, links)= }; + + // SAFETY: `this` is a non-null node so it is valid by the typ= e invariants. `node` is + // valid until the node is removed. + match unsafe { (*node).key.cmp(&(*this).key) } { + // We would like `node` to be the left child of `parent`. = Move to this child to check + // whether we can use it, or continue searching, at the ne= xt iteration. + // + // SAFETY: `parent` is a non-null node so it is valid by t= he type invariants. + Ordering::Less =3D> child_field_of_parent =3D unsafe { &mu= t (*parent).rb_left }, + // We would like `node` to be the right child of `parent`.= Move to this child to check + // whether we can use it, or continue searching, at the ne= xt iteration. + // + // SAFETY: `parent` is a non-null node so it is valid by t= he type invariants. + Ordering::Greater =3D> child_field_of_parent =3D unsafe { = &mut (*parent).rb_right }, + Ordering::Equal =3D> { + // There is an existing node in the tree with this key= , and that node is + // parent. Thus, we are replacing parent with a new n= ode. + // + // INVARIANT: We are replacing an existing node with a= new one, which is valid. + // It remains valid because we "forgot" it with `Box::= into_raw`. + // SAFETY: All pointers are non-null and valid. + unsafe { bindings::rb_replace_node(parent, node_links,= &mut self.root) }; + + // INVARIANT: The node is being returned and the calle= r may free it, however, + // it was removed from the tree. So the invariants sti= ll hold. + return Some(RBTreeNode { + // SAFETY: `this` was a node in the tree, so it is= valid. + node: unsafe { Box::from_raw(this.cast_mut()) }, + }); + } + } + } + + // INVARIANT: We are linking in a new node, which is valid. It rem= ains valid because we + // "forgot" it with `Box::into_raw`. + // SAFETY: All pointers are non-null and valid (`*child_field_of_p= arent` is null, but `child_field_of_parent` is a + // mutable reference). + unsafe { bindings::rb_link_node(node_links, parent, child_field_of= _parent) }; + + // SAFETY: All pointers are valid. `node` has just been inserted i= nto the tree. + unsafe { bindings::rb_insert_color(node_links, &mut self.root) }; + None + } + + /// Returns a node with the given key, if one exists. + fn find(&self, key: &K) -> Option>> { + let mut node =3D self.root.rb_node; + while !node.is_null() { + // SAFETY: By the type invariant of `Self`, all non-null `rb_n= ode` pointers stored in `self` + // point to the links field of `Node` objects. + let this =3D unsafe { container_of!(node, Node, links) }; + // SAFETY: `this` is a non-null node so it is valid by the typ= e invariants. + node =3D match key.cmp(unsafe { &(*this).key }) { + // SAFETY: `node` is a non-null node so it is valid by the= type invariants. + Ordering::Less =3D> unsafe { (*node).rb_left }, + // SAFETY: `node` is a non-null node so it is valid by the= type invariants. + Ordering::Greater =3D> unsafe { (*node).rb_right }, + Ordering::Equal =3D> return NonNull::new(this.cast_mut()), + } + } + None + } + + /// Returns a reference to the value corresponding to the key. + pub fn get(&self, key: &K) -> Option<&V> { + // SAFETY: The `find` return value is a node in the tree, so it is= valid. + self.find(key).map(|node| unsafe { &node.as_ref().value }) + } + + /// Returns a mutable reference to the value corresponding to the key. + pub fn get_mut(&mut self, key: &K) -> Option<&mut V> { + // SAFETY: The `find` return value is a node in the tree, so it is= valid. + self.find(key) + .map(|mut node| unsafe { &mut node.as_mut().value }) + } + + /// Removes the node with the given key from the tree. + /// + /// It returns the node that was removed if one exists, or [`None`] ot= herwise. + fn remove_node(&mut self, key: &K) -> Option> { + let mut node =3D self.find(key)?; + + // SAFETY: The `find` return value is a node in the tree, so it is= valid. + unsafe { bindings::rb_erase(&mut node.as_mut().links, &mut self.ro= ot) }; + + // INVARIANT: The node is being returned and the caller may free i= t, however, it was + // removed from the tree. So the invariants still hold. + Some(RBTreeNode { + // SAFETY: The `find` return value was a node in the tree, so = it is valid. + node: unsafe { Box::from_raw(node.as_ptr()) }, + }) + } + + /// Removes the node with the given key from the tree. + /// + /// It returns the value that was removed if one exists, or [`None`] o= therwise. + pub fn remove(&mut self, key: &K) -> Option { + self.remove_node(key).map(|node| node.node.value) + } +} + +impl Default for RBTree { + fn default() -> Self { + Self::new() + } +} + +impl Drop for RBTree { + fn drop(&mut self) { + // SAFETY: `root` is valid as it's embedded in `self` and we have = a valid `self`. + let mut next =3D unsafe { bindings::rb_first_postorder(&self.root)= }; + + // INVARIANT: The loop invariant is that all tree nodes from `next= ` in postorder are valid. + while !next.is_null() { + // SAFETY: All links fields we create are in a `Node`. + let this =3D unsafe { container_of!(next, Node, links) }; + + // Find out what the next node is before disposing of the curr= ent one. + // SAFETY: `next` and all nodes in postorder are still valid. + next =3D unsafe { bindings::rb_next_postorder(next) }; + + // INVARIANT: This is the destructor, so we break the type inv= ariant during clean-up, + // but it is not observable. The loop invariant is still maint= ained. + + // SAFETY: `this` is valid per the loop invariant. + unsafe { drop(Box::from_raw(this.cast_mut())) }; + } + } +} + +/// A memory reservation for a red-black tree node. +/// +/// +/// It contains the memory needed to hold a node that can be inserted into= a red-black tree. One +/// can be obtained by directly allocating it ([`RBTreeNodeReservation::ne= w`]). +pub struct RBTreeNodeReservation { + node: Box>>, +} + +impl RBTreeNodeReservation { + /// Allocates memory for a node to be eventually initialised and inser= ted into the tree via a + /// call to [`RBTree::insert`]. + pub fn new(flags: Flags) -> Result> { + Ok(RBTreeNodeReservation { + node: Box::new_uninit(flags)?, + }) + } +} + +// SAFETY: This doesn't actually contain K or V, and is just a memory allo= cation. Those can always +// be moved across threads. +unsafe impl Send for RBTreeNodeReservation {} + +// SAFETY: This doesn't actually contain K or V, and is just a memory allo= cation. +unsafe impl Sync for RBTreeNodeReservation {} + +impl RBTreeNodeReservation { + /// Initialises a node reservation. + /// + /// It then becomes an [`RBTreeNode`] that can be inserted into a tree. + pub fn into_node(self, key: K, value: V) -> RBTreeNode { + let node =3D Box::write( + self.node, + Node { + key, + value, + links: bindings::rb_node::default(), + }, + ); + RBTreeNode { node } + } +} + +/// A red-black tree node. +/// +/// The node is fully initialised (with key and value) and can be inserted= into a tree without any +/// extra allocations or failure paths. +pub struct RBTreeNode { + node: Box>, +} + +impl RBTreeNode { + /// Allocates and initialises a node that can be inserted into the tre= e via + /// [`RBTree::insert`]. + pub fn new(key: K, value: V, flags: Flags) -> Result>= { + Ok(RBTreeNodeReservation::new(flags)?.into_node(key, value)) + } +} + +// SAFETY: If K and V can be sent across threads, then it's also okay to s= end [`RBTreeNode`] across +// threads. +unsafe impl Send for RBTreeNode {} + +// SAFETY: If K and V can be accessed without synchronization, then it's a= lso okay to access +// [`RBTreeNode`] without synchronization. +unsafe impl Sync for RBTreeNode {} + +struct Node { + links: bindings::rb_node, + key: K, + value: V, +} --=20 2.46.0.rc1.232.g9752f9e123-goog From nobody Mon Sep 16 19:06:39 2024 Received: from mail-yw1-f202.google.com (mail-yw1-f202.google.com [209.85.128.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 253DB146A67 for ; Fri, 26 Jul 2024 19:57:55 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023876; cv=none; b=REl7zOiJHd1GZXBTLwFbz4L9HcVBfCshh56sM/Dyo/Vb+t54tKBeQnWvWlH3ZZ43+YfeuoAQ2v3Go/63UBDtQ7o3KqQH3BtHYmexq+8HvSL59eE2GCPdYBM1dkNvMAcL6zrs/dRfzM5kvaWlgVt5tc4zUV3xJeF0zZfDmEH9aNI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023876; c=relaxed/simple; bh=lh+E0+QKl06qMd0KFf0RtTQycHQtGmCYpzuID3PCah0=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=VFx/EGhYJitaxQ24D1YhUK59fPxVYyC4Y43tgFyRRe33IM8bop8absHYYYCsXtdouD1zq6lbKhdRFXDg4R6owdmUM2B6qJSwPn8JNKnaSS1icZt7cF9okSRpQeZKCNp1neh8gtw0HB7PoAovigeLn8ljlogHFCLyzmN2wo7y7wM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=X6UC4PNl; arc=none smtp.client-ip=209.85.128.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="X6UC4PNl" Received: by mail-yw1-f202.google.com with SMTP id 00721157ae682-6506bfeaf64so1312937b3.1 for ; Fri, 26 Jul 2024 12:57:55 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1722023874; x=1722628674; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=vFanFGcywiGbyGhLAep+JACloXHjNhZ8W+dyLV5kGwo=; b=X6UC4PNlicF8oJAcJRSPaUG6N9Q5CK9Y+vxW9DVw1HOe2Bc2eJSUEFIwbbUuHU2GZU 7js8SS/7Rclr1H7ARpQkHmBRaOwwI4ZJjM7GXw4NeeDMhc4fijnjkAspmx9NsC6z1yAy rzukbU28TcFcWQ/kLGu6C5CKtLEZrSddu5MgGcWLYKynBKr0pQRZttjEjl+vf/mcQoVQ m3E8gocoKftdh3Bszl8cinyIzypWZVUTen6+TKa1EgrwlOdF45NLJ/gpx5f8iiwSVl3x 4iPL3j5lGuI2fEt1s3e+c1UGlHvyMsM4bz435yrR0ab4mQ3jPQaA6TBIR0qaN1xbUNY4 b9YA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722023874; x=1722628674; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=vFanFGcywiGbyGhLAep+JACloXHjNhZ8W+dyLV5kGwo=; b=Y6/vB8i4OocrVGUzymHJJGK/RMItyO7+dyoi6Sv2qqMzOlgP51JsH6AuRjSjVSBDSo jFFhe+mdFXsTp6c+Ss/voC6hk5jcnRa9TZN6TqW9f+bXSudkJiSr0GzO0MMuBpyC+csq 1NZGKPwO8eQfA3+0TyV7TOaJC0yRL4uD5kdCmmt1IL3yJrF9SZ1Xx9iS/OB3JZYqmaxw LJtDSxvT/lb6JzbLFFiflQZMNrYo1C1kcVJYeLmMcdUn20iZTxv/bX53j4hM+AZeTafN HmmVQIJ5Q5MUkehOqPpc4MUf/tadDQwlYIOt14tFcDA1XdMSrvEc6h4X1FDqcQdKuxNh kIrw== X-Forwarded-Encrypted: i=1; AJvYcCV7HxpK3sfCaLkAWWpiD8+VFulfPUx+MLMQwAiHtmejoldA15hnr0u+HQOZImYmmluyjbcutozpNW7XwkFPJTdIVThR+LMdYhKyCi29 X-Gm-Message-State: AOJu0YyKcZxjmEVYS33cBZypejyLV5VGgifNfT/DlIfUQsSxQ+e1QSca XriIHcSUwzqr5G/75klXLEa9zFbHVpou04TtroEKY8Mbe1Op4pwFLRJKYUJ4QOrI1iu5nyIn1nW UnPgcN0qyMB4CZOyhAsFsNG0khA== X-Google-Smtp-Source: AGHT+IEP9J2DjD5HA0ZSN/BJvVibY0Ls/MstyZsZEQWgz1n1BSb/ovRch3VceKBnAxx7zU92paEOMqLBqSqBUgb9GsE= X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a81:b049:0:b0:669:f244:2ae5 with SMTP id 00721157ae682-67a0625130amr315367b3.3.1722023874151; Fri, 26 Jul 2024 12:57:54 -0700 (PDT) Date: Fri, 26 Jul 2024 19:57:42 +0000 In-Reply-To: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> X-Mailer: b4 0.13.0 Message-ID: <20240726-b4-rbtree-v7-3-aee88caaf97c@google.com> Subject: [PATCH v7 3/6] rust: rbtree: add iterator From: Matt Gilbride To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?=" , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Christian Brauner Cc: Rob Landley , Davidlohr Bueso , Michel Lespinasse , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matt Gilbride Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable From: Wedson Almeida Filho - Add Iterator implementation for `RBTree`, allowing iteration over (key, value) pairs in key order. - Add individual `keys()` and `values()` functions to iterate over keys or values alone. - Update doctests to use iteration instead of explicitly getting items. Iteration is needed by the binder driver to enumerate all values in a tree for oneway spam detection [1]. Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-17-08b= a9197f637@google.com/ [1] Signed-off-by: Wedson Almeida Filho Reviewed-by: Alice Ryhl Tested-by: Alice Ryhl Signed-off-by: Matt Gilbride Reviewed-by: Boqun Feng --- rust/kernel/rbtree.rs | 130 +++++++++++++++++++++++++++++++++++++++++++---= ---- 1 file changed, 112 insertions(+), 18 deletions(-) diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index a515bfa80113..40db6d3e732b 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -47,14 +47,30 @@ /// assert_eq!(tree.get(&30).unwrap(), &300); /// } /// +/// // Iterate over the nodes we just inserted. +/// { +/// let mut iter =3D tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &100)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert!(iter.next().is_none()); +/// } +/// +/// // Print all elements. +/// for (key, value) in &tree { +/// pr_info!("{} =3D {}\n", key, value); +/// } +/// /// // Replace one of the elements. /// tree.try_create_and_insert(10, 1000, flags::GFP_KERNEL)?; /// /// // Check that the tree reflects the replacement. /// { -/// assert_eq!(tree.get(&10).unwrap(), &1000); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &300); +/// let mut iter =3D tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &1000)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert!(iter.next().is_none()); /// } /// /// // Change the value of one of the elements. @@ -62,9 +78,11 @@ /// /// // Check that the tree reflects the update. /// { -/// assert_eq!(tree.get(&10).unwrap(), &1000); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &3000); +/// let mut iter =3D tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &1000)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &3000)); +/// assert!(iter.next().is_none()); /// } /// /// // Remove an element. @@ -72,9 +90,10 @@ /// /// // Check that the tree reflects the removal. /// { -/// assert_eq!(tree.get(&10), None); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &3000); +/// let mut iter =3D tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &3000)); +/// assert!(iter.next().is_none()); /// } /// /// # Ok::<(), Error>(()) @@ -114,9 +133,11 @@ /// /// // Check the nodes we just inserted. /// { -/// assert_eq!(tree.get(&10).unwrap(), &100); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &300); +/// let mut iter =3D tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &100)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert!(iter.next().is_none()); /// } /// /// // Remove a node, getting back ownership of it. @@ -124,9 +145,10 @@ /// /// // Check that the tree reflects the removal. /// { -/// assert_eq!(tree.get(&10).unwrap(), &100); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30), None); +/// let mut iter =3D tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &100)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert!(iter.next().is_none()); /// } /// /// // Create a preallocated reservation that we can re-use later. @@ -138,9 +160,11 @@ /// /// // Check that the tree reflect the new insertion. /// { -/// assert_eq!(tree.get(&10).unwrap(), &100); -/// assert_eq!(tree.get(&15).unwrap(), &150); -/// assert_eq!(tree.get(&20).unwrap(), &200); +/// let mut iter =3D tree.iter(); +/// assert_eq!(iter.next().unwrap(), (&10, &100)); +/// assert_eq!(iter.next().unwrap(), (&15, &150)); +/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert!(iter.next().is_none()); /// } /// /// # Ok::<(), Error>(()) @@ -167,6 +191,26 @@ pub fn new() -> Self { _p: PhantomData, } } + + /// Returns an iterator over the tree nodes, sorted by key. + pub fn iter(&self) -> Iter<'_, K, V> { + // INVARIANT: `bindings::rb_first` returns a valid pointer to a tr= ee node given a valid pointer to a tree root. + Iter { + _tree: PhantomData, + // SAFETY: `self.root` is a valid pointer to the tree root. + next: unsafe { bindings::rb_first(&self.root) }, + } + } + + /// Returns an iterator over the keys of the nodes in the tree, in sor= ted order. + pub fn keys(&self) -> impl Iterator { + self.iter().map(|(k, _)| k) + } + + /// Returns an iterator over the values of the nodes in the tree, sort= ed by key. + pub fn values(&self) -> impl Iterator { + self.iter().map(|(_, v)| v) + } } =20 impl RBTree @@ -358,6 +402,56 @@ fn drop(&mut self) { } } =20 +impl<'a, K, V> IntoIterator for &'a RBTree { + type Item =3D (&'a K, &'a V); + type IntoIter =3D Iter<'a, K, V>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +/// An iterator over the nodes of a [`RBTree`]. +/// +/// Instances are created by calling [`RBTree::iter`]. +/// +/// # Invariants +/// - `self.next` is a valid pointer. +/// - `self.next` points to a node stored inside of a valid `RBTree`. +pub struct Iter<'a, K, V> { + _tree: PhantomData<&'a RBTree>, + next: *mut bindings::rb_node, +} + +// SAFETY: The [`Iter`] gives out immutable references to K and V, so it h= as the same +// thread safety requirements as immutable references. +unsafe impl<'a, K: Sync, V: Sync> Send for Iter<'a, K, V> {} + +// SAFETY: The [`Iter`] gives out immutable references to K and V, so it h= as the same +// thread safety requirements as immutable references. +unsafe impl<'a, K: Sync, V: Sync> Sync for Iter<'a, K, V> {} + +impl<'a, K, V> Iterator for Iter<'a, K, V> { + type Item =3D (&'a K, &'a V); + + fn next(&mut self) -> Option { + if self.next.is_null() { + return None; + } + + // SAFETY: By the type invariant of `Iter`, `self.next` is a valid= node in an `RBTree`, + // and by the type invariant of `RBTree`, all nodes point to the l= inks field of `Node` objects. + let cur =3D unsafe { container_of!(self.next, Node, links) }; + + // SAFETY: `self.next` is a valid tree node by the type invariants. + self.next =3D unsafe { bindings::rb_next(self.next) }; + + // SAFETY: By the same reasoning above, it is safe to dereference = the node. Additionally, + // it is ok to return a reference to members because the iterator = must outlive it. + Some(unsafe { (&(*cur).key, &(*cur).value) }) + } +} + /// A memory reservation for a red-black tree node. /// /// --=20 2.46.0.rc1.232.g9752f9e123-goog From nobody Mon Sep 16 19:06:39 2024 Received: from mail-qk1-f201.google.com (mail-qk1-f201.google.com [209.85.222.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B018613AD23 for ; Fri, 26 Jul 2024 19:57:56 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.222.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023878; cv=none; b=OksJYB+g1ODaE2JvnWL12LeWLuoamLKo6hjmThvh46XeC4um62SFshPsVtItUZh4bCKpgstHCCak7xVAba6XKJWwlJoQ0FB3pGY4w7BmeGBgr4tjEviTCkNSj99iNKgqVZLBtj2VyPhHNoHpGHYVf/UJCRQpenPeijoYwWMv5QE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023878; c=relaxed/simple; bh=HbW5lC39Vo3FURu7yDg9XBOa7VQg6g+00xAEsgLTbPc=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=JA+tggv72Mwzw83uApF93HZqPQNi8JXoMheSam2B5Dx+qgHrCXRR8c8CBzdZZpLFwBo3pvi56Fx5IkbJgeU8n0kbcMRdVnU4s1BUT8YgHkpuuUh8KIPNXithfOt9eU1bDK2Qfk9UJ4IuFCMKYywVohR0FRYZUe0sXxm7/AocodQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=0IYLrdnI; arc=none smtp.client-ip=209.85.222.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="0IYLrdnI" Received: by mail-qk1-f201.google.com with SMTP id af79cd13be357-7a1d8c45a90so115981185a.2 for ; Fri, 26 Jul 2024 12:57:56 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1722023875; x=1722628675; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=3IqQsQDq69/bEZnFmqp2qCypa2nZHW197Tj8Jy+RTMM=; b=0IYLrdnI7bpBO41N0IuAACbkC8FQDJs4kW3kkbxyb+9Zi+rrns760UzYvchPoFj82f 04teuyV8Yx4h/w//DXabdSiz64BctMvdajlI2hkvIVf7ehguoSB6iIABPTBxhgimDoXF YF/cyW/JVcz+sGf2N7zK+zMW+CP4CNp0DEH4qi2xoBB8R/Bmq/hJptmkDQsKAo2VSNCB CMLdBJVsMollvGbEDe9hYRcmtIyJicJLCbCJQx/EbIItDKu3mu9EPwyFM+3OU/9MUrB0 nS7q5BL6ncHhugqm0iC4xJn9dogTvasGyirQY4qS5pYRURfJLwuL3+T0WXt/0OxiU/sy PlhQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722023875; x=1722628675; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=3IqQsQDq69/bEZnFmqp2qCypa2nZHW197Tj8Jy+RTMM=; b=SusSsya4sXKPvtMKiWFMvJ60BpjdW25S1gQBmiv5MOfyzDTNAENXR6kP/Rv3NDBSp4 WHCXzCQJRXaennJyVBLKrpZVvjH/HgP3TUPrwhQOA/k1PmaaZa5HzigV5B5n7dRGKTb+ 2nPKGTpiiTbT6HCcOx6r+A+3ZFLh5wOzOI9ARRMQbJEF2Oe9FKrHzm/JY1N49s0amVjE zirfj5Ge/DKkxKgmtWGmTopGsyGjJqv0t0nlXM2Ol8wV/NOMXNGp1R/DBrWh+4FegMc+ xPTDNfQSucNM3pLWiWSYyFPeY2lXQL7rlrxLnYrYEPr8y2YJVt7oWrl4/UnuXPIC3PyY Qo1A== X-Forwarded-Encrypted: i=1; AJvYcCWPdHx+YjLbu1cKX5u8lkZKYLIv8RQv5OMFewdHD/eWc1TDufNrZzT5LwvCJw23zfbNqKkg1wazmkmBVb+T4PyZh0IVcqVnFmCx+L7n X-Gm-Message-State: AOJu0YzLYBsfZDduWC8s9fyZz1pOvNMOt3/80AygLeULU597pvw1PerR 1vTisgsGKg+BwCA6ZifwuNavc71QPjz2tLCkQ4fCJpvF5V0gnyiw6niHaAJKeP8E8JVVjubSp7E uxfrrYubJb77T3JESpDybvCxB/A== X-Google-Smtp-Source: AGHT+IFozQVyWYpBnnmpalmayTIsqFPCJ6h1elphCf3vKOH7Zb1f08un6I4N3tCgnom/hu4zdMn5Fc/XV4dEul5gHE4= X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a05:620a:2727:b0:79f:29:4e53 with SMTP id af79cd13be357-7a1e523d5acmr140385a.4.1722023875498; Fri, 26 Jul 2024 12:57:55 -0700 (PDT) Date: Fri, 26 Jul 2024 19:57:43 +0000 In-Reply-To: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> X-Mailer: b4 0.13.0 Message-ID: <20240726-b4-rbtree-v7-4-aee88caaf97c@google.com> Subject: [PATCH v7 4/6] rust: rbtree: add mutable iterator From: Matt Gilbride To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?=" , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Christian Brauner Cc: Rob Landley , Davidlohr Bueso , Michel Lespinasse , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matt Gilbride Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable From: Wedson Almeida Filho Add mutable Iterator implementation for `RBTree`, allowing iteration over (key, value) pairs in key order. Only values are mutable, as mutating keys implies modifying a node's position in the tree. Mutable iteration is used by the binder driver during shutdown to clean up the tree maintained by the "range allocator" [1]. Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-6-08ba= 9197f637@google.com/ [1] Signed-off-by: Wedson Almeida Filho Signed-off-by: Matt Gilbride Reviewed-by: Alice Ryhl Tested-by: Alice Ryhl Reviewed-by: Boqun Feng --- rust/kernel/rbtree.rs | 98 ++++++++++++++++++++++++++++++++++++++++++++---= ---- 1 file changed, 86 insertions(+), 12 deletions(-) diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index 40db6d3e732b..64e0f2328879 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -197,8 +197,26 @@ pub fn iter(&self) -> Iter<'_, K, V> { // INVARIANT: `bindings::rb_first` returns a valid pointer to a tr= ee node given a valid pointer to a tree root. Iter { _tree: PhantomData, - // SAFETY: `self.root` is a valid pointer to the tree root. - next: unsafe { bindings::rb_first(&self.root) }, + iter_raw: IterRaw { + // SAFETY: by the invariants, all pointers are valid. + next: unsafe { bindings::rb_first(&self.root) }, + _phantom: PhantomData, + }, + } + } + + /// Returns a mutable iterator over the tree nodes, sorted by key. + pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { + IterMut { + _tree: PhantomData, + // INVARIANT: + // - `self.root` is a valid pointer to a tree root. + // - `bindings::rb_first` produces a valid pointer to a node= given `root` is valid. + iter_raw: IterRaw { + // SAFETY: by the invariants, all pointers are valid. + next: unsafe { bindings::rb_first(&self.root) }, + _phantom: PhantomData, + }, } } =20 @@ -211,6 +229,11 @@ pub fn keys(&self) -> impl Iterator { pub fn values(&self) -> impl Iterator { self.iter().map(|(_, v)| v) } + + /// Returns a mutable iterator over the values of the nodes in the tre= e, sorted by key. + pub fn values_mut(&mut self) -> impl Iterator { + self.iter_mut().map(|(_, v)| v) + } } =20 impl RBTree @@ -414,13 +437,9 @@ fn into_iter(self) -> Self::IntoIter { /// An iterator over the nodes of a [`RBTree`]. /// /// Instances are created by calling [`RBTree::iter`]. -/// -/// # Invariants -/// - `self.next` is a valid pointer. -/// - `self.next` points to a node stored inside of a valid `RBTree`. pub struct Iter<'a, K, V> { _tree: PhantomData<&'a RBTree>, - next: *mut bindings::rb_node, + iter_raw: IterRaw, } =20 // SAFETY: The [`Iter`] gives out immutable references to K and V, so it h= as the same @@ -434,21 +453,76 @@ unsafe impl<'a, K: Sync, V: Sync> Sync for Iter<'a, K= , V> {} impl<'a, K, V> Iterator for Iter<'a, K, V> { type Item =3D (&'a K, &'a V); =20 + fn next(&mut self) -> Option { + self.iter_raw.next().map(|(k, v)| + // SAFETY: Due to `self._tree`, `k` and `v` are valid for the = lifetime of `'a`. + unsafe { (&*k, &*v) }) + } +} + +impl<'a, K, V> IntoIterator for &'a mut RBTree { + type Item =3D (&'a K, &'a mut V); + type IntoIter =3D IterMut<'a, K, V>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +/// A mutable iterator over the nodes of a [`RBTree`]. +/// +/// Instances are created by calling [`RBTree::iter_mut`]. +pub struct IterMut<'a, K, V> { + _tree: PhantomData<&'a mut RBTree>, + iter_raw: IterRaw, +} + +// SAFETY: The [`IterMut`] gives out immutable references to K and mutable= references to V, so it has the same +// thread safety requirements as mutable references. +unsafe impl<'a, K: Send, V: Send> Send for IterMut<'a, K, V> {} + +// SAFETY: The [`IterMut`] gives out immutable references to K and mutable= references to V, so it has the same +// thread safety requirements as mutable references. +unsafe impl<'a, K: Sync, V: Sync> Sync for IterMut<'a, K, V> {} + +impl<'a, K, V> Iterator for IterMut<'a, K, V> { + type Item =3D (&'a K, &'a mut V); + + fn next(&mut self) -> Option { + self.iter_raw.next().map(|(k, v)| + // SAFETY: Due to `&mut self`, we have exclusive access to `k`= and `v`, for the lifetime of `'a`. + unsafe { (&*k, &mut *v) }) + } +} + +/// A raw iterator over the nodes of a [`RBTree`]. +/// +/// # Invariants +/// - `self.next` is a valid pointer. +/// - `self.next` points to a node stored inside of a valid `RBTree`. +struct IterRaw { + next: *mut bindings::rb_node, + _phantom: PhantomData (K, V)>, +} + +impl Iterator for IterRaw { + type Item =3D (*mut K, *mut V); + fn next(&mut self) -> Option { if self.next.is_null() { return None; } =20 - // SAFETY: By the type invariant of `Iter`, `self.next` is a valid= node in an `RBTree`, + // SAFETY: By the type invariant of `IterRaw`, `self.next` is a va= lid node in an `RBTree`, // and by the type invariant of `RBTree`, all nodes point to the l= inks field of `Node` objects. - let cur =3D unsafe { container_of!(self.next, Node, links) }; + let cur: *mut Node =3D + unsafe { container_of!(self.next, Node, links) }.cast_mu= t(); =20 // SAFETY: `self.next` is a valid tree node by the type invariants. self.next =3D unsafe { bindings::rb_next(self.next) }; =20 - // SAFETY: By the same reasoning above, it is safe to dereference = the node. Additionally, - // it is ok to return a reference to members because the iterator = must outlive it. - Some(unsafe { (&(*cur).key, &(*cur).value) }) + // SAFETY: By the same reasoning above, it is safe to dereference = the node. + Some(unsafe { (addr_of_mut!((*cur).key), addr_of_mut!((*cur).value= )) }) } } =20 --=20 2.46.0.rc1.232.g9752f9e123-goog From nobody Mon Sep 16 19:06:39 2024 Received: from mail-qk1-f201.google.com (mail-qk1-f201.google.com [209.85.222.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0F60761FCF for ; Fri, 26 Jul 2024 19:57:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.222.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023880; cv=none; b=HrM/H3TNp4i95Ng1JZQ/1Pf9nuH9sz5nx2vPo5xbpFfUP4Gtzdswc+tACiD5aGQvhMg8jZTckQ2tJa/41GwGVdBnpwuTLjHoY4wseynWthCt6Dx5inJhvTH44+h0t1nrPfmH2qpS9JAEdlGSEBwHSQuYu6nPqLDz857i/QCmlrg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023880; c=relaxed/simple; bh=q4QRA80ZniVAEhnFSRFNLIyXwhFvaAjS9p/cLfM7FLM=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=KfzCQQcW8lgMy0N4FApG1dnFUr1Bd3xMADOrVTrtqlG5mWjBfrqYSu6004LwCL5UZ5LwD9TPiotD8lbhkOKtFNuoptAQBsskUSCnMybZ+pAk26doTGH8ptzKUc+N3hskrgC0DssKxTLVrbp3Pp1YErmMGnwLRN7vZLLJdooyu/U= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=HA9qb4zU; arc=none smtp.client-ip=209.85.222.201 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="HA9qb4zU" Received: by mail-qk1-f201.google.com with SMTP id af79cd13be357-7a1df9ced6fso116319185a.2 for ; Fri, 26 Jul 2024 12:57:57 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1722023877; x=1722628677; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=d8GaitvJd3HTC0qdEAqCrtZyprc/3NqgvgsE5rl1gFA=; b=HA9qb4zUBs3O3PteRMaSzfZ3J828P4C3QyI6nNZ+CV3TP0ZCGguXSVWPzevWWPZkqM sxLXFpJsxEC+Qmk161rqcMUne9YitbvuedX4jhqB6dsSg6eAZjzn1QMleOyVhBolUZvo KroJiULPqNQu+E46sP9XRvsx70Vizwvs8pyo9utvdkLbGPUnkp6d/nQ9b0ZPehYdWLz6 CrvJUXRYdPdoHEsYDxO7o/R8OHDxhqMi8v6jwHlNdqlcMUzZs5XtFppI3bWOGxLSbM1n GssgmzGOVBgWEF2uv6mtfwjD3fTDmuqPRkOGkV3yBnASWwkFWtxXtPE/nWyZEkSzft/A DD9Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722023877; x=1722628677; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=d8GaitvJd3HTC0qdEAqCrtZyprc/3NqgvgsE5rl1gFA=; b=rvscCf2wRGhpgMwsNysPTubEQpLnhsU9+USTivxyuytResZKYFP9Qly0kOANx5m/yn A86hlbbeaKcUNWwhyFHovV64s47BnlR40tS9Sq3B2eOMgBqZMzdaLXkSusm7/07NP3Xt /qvogMoaKUWORsIdWDMqDXU93JRwEezvJ9X6mQm39IzAirICo1iWiya5/Sbi/PCJvGQT kG2ngt0T+dNaN+/MenMyJkVPvk43zDOh/Eb/juBRxfGGXtNTHBMEw0TCnwYCdJKbhlIf 2zV7L0pjGQEevk3XD7WMqzBIapkRqbV1C2HdnLxM5ScGGOot1z+Z2YF4bl/dKLSsmrNG tcSQ== X-Forwarded-Encrypted: i=1; AJvYcCVWjKoAAzTsrUxlB0KJZ7e0Y74tl/ufvUrpIqWEYn/VYbLCBlu1tjsLxO5dtxTp6ODiCuNOADzi/fKXDEFm8bWyPP9BvNe+5w41HDc8 X-Gm-Message-State: AOJu0Yx4EMlV84pAZMInABEs/mA3Yo6IOs0EQwcVrAQjiexPgcEtKFRV m8Pc9sf72KZWVVvgg2Cyal6pqYPsd4wOkeFfP4cH7QMI+ODQIMtO6w5iKF1u5mzD/bluYpqEjMV /TuAvruqPz8WYh3LwYgVr2BBnvQ== X-Google-Smtp-Source: AGHT+IHyb/LbXvb2BO9cvjYJaxebXRB3fBNSA3hIC7buLJSepRBdh2ixF8JT864LcG7pN2CstdyP1OkL03MZDfdItRs= X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a05:620a:25d4:b0:79f:955:56df with SMTP id af79cd13be357-7a1e52a2a31mr171785a.11.1722023877073; Fri, 26 Jul 2024 12:57:57 -0700 (PDT) Date: Fri, 26 Jul 2024 19:57:44 +0000 In-Reply-To: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> X-Mailer: b4 0.13.0 Message-ID: <20240726-b4-rbtree-v7-5-aee88caaf97c@google.com> Subject: [PATCH v7 5/6] rust: rbtree: add `RBTreeCursor` From: Matt Gilbride To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?=" , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Christian Brauner Cc: Rob Landley , Davidlohr Bueso , Michel Lespinasse , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matt Gilbride Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Add a cursor interface to `RBTree`, supporting the following use cases: - Inspect the current node pointed to by the cursor, inspect/move to it's neighbors in sort order (bidirectionally). - Mutate the tree itself by removing the current node pointed to by the cursor, or one of its neighbors. Add functions to obtain a cursor to the tree by key: - The node with the smallest key - The node with the largest key - The node matching the given key, or the one with the next larger key The cursor abstraction is needed by the binder driver to efficiently search for nodes and (conditionally) modify them, as well as their neighbors [1]. Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-6-08ba= 9197f637@google.com/ [1] Co-developed-by: Alice Ryhl Signed-off-by: Alice Ryhl Reviewed-by: Alice Ryhl Tested-by: Alice Ryhl Signed-off-by: Matt Gilbride Reviewed-by: Boqun Feng --- rust/kernel/rbtree.rs | 538 ++++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 538 insertions(+) diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index 64e0f2328879..5611ae903779 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -234,6 +234,40 @@ pub fn values(&self) -> impl Iterator { pub fn values_mut(&mut self) -> impl Iterator { self.iter_mut().map(|(_, v)| v) } + + /// Returns a cursor over the tree nodes, starting with the smallest k= ey. + pub fn cursor_front(&mut self) -> Option> { + let root =3D addr_of_mut!(self.root); + // SAFETY: `self.root` is always a valid root node + let current =3D unsafe { bindings::rb_first(root) }; + NonNull::new(current).map(|current| { + // INVARIANT: + // - `current` is a valid node in the [`RBTree`] pointed to by= `self`. + // - Due to the type signature of this function, the returned = [`RBTreeCursor`] + // borrows mutably from `self`. + RBTreeCursor { + current, + tree: self, + } + }) + } + + /// Returns a cursor over the tree nodes, starting with the largest ke= y. + pub fn cursor_back(&mut self) -> Option> { + let root =3D addr_of_mut!(self.root); + // SAFETY: `self.root` is always a valid root node + let current =3D unsafe { bindings::rb_last(root) }; + NonNull::new(current).map(|current| { + // INVARIANT: + // - `current` is a valid node in the [`RBTree`] pointed to by= `self`. + // - Due to the type signature of this function, the returned = [`RBTreeCursor`] + // borrows mutably from `self`. + RBTreeCursor { + current, + tree: self, + } + }) + } } =20 impl RBTree @@ -394,6 +428,77 @@ fn remove_node(&mut self, key: &K) -> Option> { pub fn remove(&mut self, key: &K) -> Option { self.remove_node(key).map(|node| node.node.value) } + + /// Returns a cursor over the tree nodes based on the given key. + /// + /// If the given key exists, the cursor starts there. + /// Otherwise it starts with the first larger key in sort order. + /// If there is no larger key, it returns [`None`]. + pub fn cursor_lower_bound(&mut self, key: &K) -> Option> + where + K: Ord, + { + let mut node =3D self.root.rb_node; + let mut best_match: Option>> =3D None; + while !node.is_null() { + // SAFETY: By the type invariant of `Self`, all non-null `rb_n= ode` pointers stored in `self` + // point to the links field of `Node` objects. + let this =3D unsafe { container_of!(node, Node, links) }= .cast_mut(); + // SAFETY: `this` is a non-null node so it is valid by the typ= e invariants. + let this_key =3D unsafe { &(*this).key }; + // SAFETY: `node` is a non-null node so it is valid by the typ= e invariants. + let left_child =3D unsafe { (*node).rb_left }; + // SAFETY: `node` is a non-null node so it is valid by the typ= e invariants. + let right_child =3D unsafe { (*node).rb_right }; + if key =3D=3D this_key { + return NonNull::new(node).map(|current| { + // INVARIANT: + // - `node` is a valid node in the [`RBTree`] pointed = to by `self`. + // - Due to the type signature of this function, the r= eturned [`RBTreeCursor`] + // borrows mutably from `self`. + RBTreeCursor { + current, + tree: self, + } + }); + } else { + node =3D if key > this_key { + right_child + } else { + let is_better_match =3D match best_match { + None =3D> true, + Some(best) =3D> { + // SAFETY: `best` is a non-null node so it is = valid by the type invariants. + let best_key =3D unsafe { &(*best.as_ptr()).ke= y }; + best_key > this_key + } + }; + if is_better_match { + best_match =3D NonNull::new(this); + } + left_child + }; + } + } + + let Some(best) =3D best_match else { + return None; + }; + + // SAFETY: `best` is a non-null node so it is valid by the type in= variants. + let links =3D unsafe { addr_of_mut!((*best.as_ptr()).links) }; + + NonNull::new(links).map(|current| { + // INVARIANT: + // - `current` is a valid node in the [`RBTree`] pointed to by= `self`. + // - Due to the type signature of this function, the returned = [`RBTreeCursor`] + // borrows mutably from `self`. + RBTreeCursor { + current, + tree: self, + } + }) + } } =20 impl Default for RBTree { @@ -425,6 +530,434 @@ fn drop(&mut self) { } } =20 +/// A bidirectional cursor over the tree nodes, sorted by key. +/// +/// # Examples +/// +/// In the following example, we obtain a cursor to the first element in t= he tree. +/// The cursor allows us to iterate bidirectionally over key/value pairs i= n the tree. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::RBTree}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert three elements. +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// +/// // Get a cursor to the first element. +/// let mut cursor =3D tree.cursor_front().unwrap(); +/// let mut current =3D cursor.current(); +/// assert_eq!(current, (&10, &100)); +/// +/// // Move the cursor, updating it to the 2nd element. +/// cursor =3D cursor.move_next().unwrap(); +/// current =3D cursor.current(); +/// assert_eq!(current, (&20, &200)); +/// +/// // Peek at the next element without impacting the cursor. +/// let next =3D cursor.peek_next().unwrap(); +/// assert_eq!(next, (&30, &300)); +/// current =3D cursor.current(); +/// assert_eq!(current, (&20, &200)); +/// +/// // Moving past the last element causes the cursor to return [`None`]. +/// cursor =3D cursor.move_next().unwrap(); +/// current =3D cursor.current(); +/// assert_eq!(current, (&30, &300)); +/// let cursor =3D cursor.move_next(); +/// assert!(cursor.is_none()); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// A cursor can also be obtained at the last element in the tree. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::RBTree}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert three elements. +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// +/// let mut cursor =3D tree.cursor_back().unwrap(); +/// let current =3D cursor.current(); +/// assert_eq!(current, (&30, &300)); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// Obtaining a cursor returns [`None`] if the tree is empty. +/// +/// ``` +/// use kernel::rbtree::RBTree; +/// +/// let mut tree: RBTree =3D RBTree::new(); +/// assert!(tree.cursor_front().is_none()); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// [`RBTree::cursor_lower_bound`] can be used to start at an arbitrary no= de in the tree. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::RBTree}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert five elements. +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(40, 400, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(50, 500, flags::GFP_KERNEL)?; +/// +/// // If the provided key exists, a cursor to that key is returned. +/// let cursor =3D tree.cursor_lower_bound(&20).unwrap(); +/// let current =3D cursor.current(); +/// assert_eq!(current, (&20, &200)); +/// +/// // If the provided key doesn't exist, a cursor to the first larger ele= ment in sort order is returned. +/// let cursor =3D tree.cursor_lower_bound(&25).unwrap(); +/// let current =3D cursor.current(); +/// assert_eq!(current, (&30, &300)); +/// +/// // If there is no larger key, [`None`] is returned. +/// let cursor =3D tree.cursor_lower_bound(&55); +/// assert!(cursor.is_none()); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// The cursor allows mutation of values in the tree. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::RBTree}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert three elements. +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// +/// // Retrieve a cursor. +/// let mut cursor =3D tree.cursor_front().unwrap(); +/// +/// // Get a mutable reference to the current value. +/// let (k, v) =3D cursor.current_mut(); +/// *v =3D 1000; +/// +/// // The updated value is reflected in the tree. +/// let updated =3D tree.get(&10).unwrap(); +/// assert_eq!(updated, &1000); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// It also allows node removal. The following examples demonstrate the be= havior of removing the current node. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::RBTree}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert three elements. +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// +/// // Remove the first element. +/// let mut cursor =3D tree.cursor_front().unwrap(); +/// let mut current =3D cursor.current(); +/// assert_eq!(current, (&10, &100)); +/// cursor =3D cursor.remove_current().0.unwrap(); +/// +/// // If a node exists after the current element, it is returned. +/// current =3D cursor.current(); +/// assert_eq!(current, (&20, &200)); +/// +/// // Get a cursor to the last element, and remove it. +/// cursor =3D tree.cursor_back().unwrap(); +/// current =3D cursor.current(); +/// assert_eq!(current, (&30, &300)); +/// +/// // Since there is no next node, the previous node is returned. +/// cursor =3D cursor.remove_current().0.unwrap(); +/// current =3D cursor.current(); +/// assert_eq!(current, (&20, &200)); +/// +/// // Removing the last element in the tree returns [`None`]. +/// assert!(cursor.remove_current().0.is_none()); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// Nodes adjacent to the current node can also be removed. +/// +/// ``` +/// use kernel::{alloc::flags, rbtree::RBTree}; +/// +/// // Create a new tree. +/// let mut tree =3D RBTree::new(); +/// +/// // Insert three elements. +/// tree.try_create_and_insert(10, 100, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(20, 200, flags::GFP_KERNEL)?; +/// tree.try_create_and_insert(30, 300, flags::GFP_KERNEL)?; +/// +/// // Get a cursor to the first element. +/// let mut cursor =3D tree.cursor_front().unwrap(); +/// let mut current =3D cursor.current(); +/// assert_eq!(current, (&10, &100)); +/// +/// // Calling `remove_prev` from the first element returns [`None`]. +/// assert!(cursor.remove_prev().is_none()); +/// +/// // Get a cursor to the last element. +/// cursor =3D tree.cursor_back().unwrap(); +/// current =3D cursor.current(); +/// assert_eq!(current, (&30, &300)); +/// +/// // Calling `remove_prev` removes and returns the middle element. +/// assert_eq!(cursor.remove_prev().unwrap().to_key_value(), (20, 200)); +/// +/// // Calling `remove_next` from the last element returns [`None`]. +/// assert!(cursor.remove_next().is_none()); +/// +/// // Move to the first element +/// cursor =3D cursor.move_prev().unwrap(); +/// current =3D cursor.current(); +/// assert_eq!(current, (&10, &100)); +/// +/// // Calling `remove_next` removes and returns the last element. +/// assert_eq!(cursor.remove_next().unwrap().to_key_value(), (30, 300)); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// # Invariants +/// - `current` points to a node that is in the same [`RBTree`] as `tree`. +pub struct RBTreeCursor<'a, K, V> { + tree: &'a mut RBTree, + current: NonNull, +} + +// SAFETY: The [`RBTreeCursor`] gives out immutable references to K and mu= table references to V, +// so it has the same thread safety requirements as mutable references. +unsafe impl<'a, K: Send, V: Send> Send for RBTreeCursor<'a, K, V> {} + +// SAFETY: The [`RBTreeCursor`] gives out immutable references to K and mu= table references to V, +// so it has the same thread safety requirements as mutable references. +unsafe impl<'a, K: Sync, V: Sync> Sync for RBTreeCursor<'a, K, V> {} + +impl<'a, K, V> RBTreeCursor<'a, K, V> { + /// The current node + pub fn current(&self) -> (&K, &V) { + // SAFETY: + // - `self.current` is a valid node by the type invariants. + // - We have an immutable reference by the function signature. + unsafe { Self::to_key_value(self.current) } + } + + /// The current node, with a mutable value + pub fn current_mut(&mut self) -> (&K, &mut V) { + // SAFETY: + // - `self.current` is a valid node by the type invariants. + // - We have an mutable reference by the function signature. + unsafe { Self::to_key_value_mut(self.current) } + } + + /// Remove the current node from the tree. + /// + /// Returns a tuple where the first element is a cursor to the next no= de, if it exists, + /// else the previous node, else [`None`] (if the tree becomes empty).= The second element + /// is the removed node. + pub fn remove_current(self) -> (Option, RBTreeNode) { + let prev =3D self.get_neighbor_raw(Direction::Prev); + let next =3D self.get_neighbor_raw(Direction::Next); + // SAFETY: By the type invariant of `Self`, all non-null `rb_node`= pointers stored in `self` + // point to the links field of `Node` objects. + let this =3D unsafe { container_of!(self.current.as_ptr(), Node, links) }.cast_mut(); + // SAFETY: `this` is valid by the type invariants as described abo= ve. + let node =3D unsafe { Box::from_raw(this) }; + let node =3D RBTreeNode { node }; + // SAFETY: The reference to the tree used to create the cursor out= lives the cursor, so + // the tree cannot change. By the tree invariant, all nodes are va= lid. + unsafe { bindings::rb_erase(&mut (*this).links, addr_of_mut!(self.= tree.root)) }; + + let current =3D match (prev, next) { + (_, Some(next)) =3D> next, + (Some(prev), None) =3D> prev, + (None, None) =3D> { + return (None, node); + } + }; + + ( + // INVARIANT: + // - `current` is a valid node in the [`RBTree`] pointed to by= `self.tree`. + // - Due to the function signature, `self` is an owned [`RBTre= eCursor`], + // and [`RBTreeCursor`]s are only created via functions with= a mutable reference + // to an [`RBTree`]. + Some(Self { + current, + tree: self.tree, + }), + node, + ) + } + + /// Remove the previous node, returning it if it exists. + pub fn remove_prev(&mut self) -> Option> { + self.remove_neighbor(Direction::Prev) + } + + /// Remove the next node, returning it if it exists. + pub fn remove_next(&mut self) -> Option> { + self.remove_neighbor(Direction::Next) + } + + fn remove_neighbor(&mut self, direction: Direction) -> Option> { + if let Some(neighbor) =3D self.get_neighbor_raw(direction) { + let neighbor =3D neighbor.as_ptr(); + // SAFETY: The reference to the tree used to create the cursor= outlives the cursor, so + // the tree cannot change. By the tree invariant, all nodes ar= e valid. + unsafe { bindings::rb_erase(neighbor, addr_of_mut!(self.tree.r= oot)) }; + // SAFETY: By the type invariant of `Self`, all non-null `rb_n= ode` pointers stored in `self` + // point to the links field of `Node` objects. + let this =3D unsafe { container_of!(neighbor, Node, link= s) }.cast_mut(); + // SAFETY: `this` is valid by the type invariants as described= above. + let node =3D unsafe { Box::from_raw(this) }; + return Some(RBTreeNode { node }); + } + None + } + + /// Move the cursor to the previous node, returning [`None`] if it doe= sn't exist. + pub fn move_prev(self) -> Option { + self.mv(Direction::Prev) + } + + /// Move the cursor to the next node, returning [`None`] if it doesn't= exist. + pub fn move_next(self) -> Option { + self.mv(Direction::Next) + } + + fn mv(self, direction: Direction) -> Option { + // INVARIANT: + // - `neighbor` is a valid node in the [`RBTree`] pointed to by `s= elf.tree`. + // - Due to the function signature, `self` is an owned [`RBTreeCur= sor`], + // and [`RBTreeCursor`]s are only created via functions with a m= utable reference + // to an [`RBTree`]. + self.get_neighbor_raw(direction).map(|neighbor| Self { + tree: self.tree, + current: neighbor, + }) + } + + /// Access the previous node without moving the cursor. + pub fn peek_prev(&self) -> Option<(&K, &V)> { + self.peek(Direction::Prev) + } + + /// Access the previous node without moving the cursor. + pub fn peek_next(&self) -> Option<(&K, &V)> { + self.peek(Direction::Next) + } + + fn peek(&self, direction: Direction) -> Option<(&K, &V)> { + self.get_neighbor_raw(direction) + // SAFETY: + // - `neighbor` is a valid tree node. + // - By the function signature, we have an immutable reference= to `self`. + .map(|neighbor| unsafe { Self::to_key_value(neighbor) }) + } + + /// Access the previous node mutably without moving the cursor. + pub fn peek_prev_mut(&mut self) -> Option<(&K, &mut V)> { + self.peek_mut(Direction::Prev) + } + + /// Access the next node mutably without moving the cursor. + pub fn peek_next_mut(&mut self) -> Option<(&K, &mut V)> { + self.peek_mut(Direction::Next) + } + + fn peek_mut(&mut self, direction: Direction) -> Option<(&K, &mut V)> { + self.get_neighbor_raw(direction) + // SAFETY: + // - `neighbor` is a valid tree node. + // - By the function signature, we have a mutable reference to= `self`. + .map(|neighbor| unsafe { Self::to_key_value_mut(neighbor) }) + } + + fn get_neighbor_raw(&self, direction: Direction) -> Option> { + // SAFETY: `self.current` is valid by the type invariants. + let neighbor =3D unsafe { + match direction { + Direction::Prev =3D> bindings::rb_prev(self.current.as_ptr= ()), + Direction::Next =3D> bindings::rb_next(self.current.as_ptr= ()), + } + }; + + NonNull::new(neighbor) + } + + /// SAFETY: + /// - `node` must be a valid pointer to a node in an [`RBTree`]. + /// - The caller has immutable access to `node` for the duration of 'b. + unsafe fn to_key_value<'b>(node: NonNull) -> (&'b K= , &'b V) { + // SAFETY: the caller guarantees that `node` is a valid pointer in= an `RBTree`. + let (k, v) =3D unsafe { Self::to_key_value_raw(node) }; + // SAFETY: the caller guarantees immutable access to `node`. + (k, unsafe { &*v }) + } + + /// SAFETY: + /// - `node` must be a valid pointer to a node in an [`RBTree`]. + /// - The caller has mutable access to `node` for the duration of 'b. + unsafe fn to_key_value_mut<'b>(node: NonNull) -> (&= 'b K, &'b mut V) { + // SAFETY: the caller guarantees that `node` is a valid pointer in= an `RBTree`. + let (k, v) =3D unsafe { Self::to_key_value_raw(node) }; + // SAFETY: the caller guarantees mutable access to `node`. + (k, unsafe { &mut *v }) + } + + /// SAFETY: + /// - `node` must be a valid pointer to a node in an [`RBTree`]. + /// - The caller has immutable access to the key for the duration of '= b. + unsafe fn to_key_value_raw<'b>(node: NonNull) -> (&= 'b K, *mut V) { + // SAFETY: By the type invariant of `Self`, all non-null `rb_node`= pointers stored in `self` + // point to the links field of `Node` objects. + let this =3D unsafe { container_of!(node.as_ptr(), Node, lin= ks) }.cast_mut(); + // SAFETY: The passed `node` is the current node or a non-null nei= ghbor, + // thus `this` is valid by the type invariants. + let k =3D unsafe { &(*this).key }; + // SAFETY: The passed `node` is the current node or a non-null nei= ghbor, + // thus `this` is valid by the type invariants. + let v =3D unsafe { addr_of_mut!((*this).value) }; + (k, v) + } +} + +/// Direction for [`RBTreeCursor`] operations. +enum Direction { + /// the node immediately before, in sort order + Prev, + /// the node immediately after, in sort order + Next, +} + impl<'a, K, V> IntoIterator for &'a RBTree { type Item =3D (&'a K, &'a V); type IntoIter =3D Iter<'a, K, V>; @@ -583,6 +1116,11 @@ impl RBTreeNode { pub fn new(key: K, value: V, flags: Flags) -> Result>= { Ok(RBTreeNodeReservation::new(flags)?.into_node(key, value)) } + + /// Get the key and value from inside the node. + pub fn to_key_value(self) -> (K, V) { + (self.node.key, self.node.value) + } } =20 // SAFETY: If K and V can be sent across threads, then it's also okay to s= end [`RBTreeNode`] across --=20 2.46.0.rc1.232.g9752f9e123-goog From nobody Mon Sep 16 19:06:39 2024 Received: from mail-yb1-f202.google.com (mail-yb1-f202.google.com [209.85.219.202]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6723D14A08D for ; Fri, 26 Jul 2024 19:57:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.219.202 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023881; cv=none; b=EECueKv7iLsLl2m9GJXkUvuxQTS8DVa4k4xwvqnA6gLT4A7+qliue1UNPz1C3hTo/vuwz4Q9NFev0alhhPaQtyKZAaM/vmGUPDhbx2oj2npIzEjAw67ajzRRDNvAQPS5PHenbR3WkSvx83Wbbkw2ImbcdYNpjYrFJF9jsynP5nc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722023881; c=relaxed/simple; bh=YlJB5S4znumNDllZHof+0NmmQ4v4IlYqKiGjmVkimaM=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=CrQ62p/tNf40CyxXUUZlr17fHdIOQzoKbwpBI+Vgjm5ozNb5nYAJpQEBd96MYzraOWNkMyehmnrGlyh0UA3hEYCyseH0suc3roWoR8Q3LHUR3hLqA37oDTqonJmPFdbuhP2rUtaNZXOdzeKUuF8z2vGNTD+lhYSGXDvFh5aPXDw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=r+iXl8TY; arc=none smtp.client-ip=209.85.219.202 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--mattgilbride.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="r+iXl8TY" Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-e0353b731b8so104871276.2 for ; Fri, 26 Jul 2024 12:57:59 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1722023878; x=1722628678; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=5iuSDXVb2/pesIXeo/fDaEA7XP6L6y8oWIFuWGtUIt0=; b=r+iXl8TYPYjtfl0TFrn90R8U36ROUxqBiNu7kGOyms9AxW1v3Xb/MWyXwqCVWND6YH scux526OaJKHdyHZX4+h/xZBtSGdyIpgboGoHgmoBeWPmeYb4TA9L3BDG0DxehEu7yja dzWiykr5rd4o5FKuMmuNic1DC5qfER+WKnaYldIBFev5ZC4cwh4oX2VW2Bdb3BOr6Jlb AvClc3X3NnSzsq9aIusTZ5EP9/04BQWzRih3zvEosUUvbE8PmNwLH+/ERGbzc81D/nZo AZFjYep07BjZ3FA5m/o1G8wF2Ytq+Hh2sXYs31Wu5AfD2BegiVU2EE/TL3hKAhg48riQ 3hBg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1722023878; x=1722628678; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=5iuSDXVb2/pesIXeo/fDaEA7XP6L6y8oWIFuWGtUIt0=; b=v609BmjYk/1c/rQ8UAcsTkoI+irxeQgVQqlfe7pNeR8RfNkZaoDKxpY8/Q6mvVIY+t ia1dm8INuu/0VDH0FCetKoNMlJ1OyOdL6hXZJJGndOXpP0DRlNKurJLgP1BxIXJgs6xS 1juWav3s1qmnO1tmqt5DMJs0GUAeJzOGDarokkTGjbJ0Gq7pl+Kdcp94XZLrJR7XSV7f ZKPYwN+Ld5WXgRKVmvFDJiExfyELLoH02NoaIMfNQcT7w8MWjkf4vmtFFD95x8v79Fc/ GD5C1SnYtqBi0uX2BGgOEgD0L2IVC7MJW4UmvrcGnTSUAUIG+QfoKhLq1KOWyqylGZ3P RAWw== X-Forwarded-Encrypted: i=1; AJvYcCUTEGSbJgbBBx8FR4nWj9fxVdOJQ/9aarZnzmWQWPd9H0qHEJLr4GAzH9u7OsRN6MM4JqlqMJqy1sFaDX/M9xxxXdBztFQt0aVcHy88 X-Gm-Message-State: AOJu0Yz1SiR2Au+mlyyqcwh2AOyg1P7LTQlk5OujrN6lwBXFu96XjNcU ytbw2jNkE0om6gS/7QVWCOYqXgtbGvCLwvx6JILvu0x8XQt/E3YpX0skaZAPhYRWw0gT8nyUAJY 52EHHoynbPfZAzBJstHgoykPodg== X-Google-Smtp-Source: AGHT+IFkRTh9HZ3eVuZO3vsYMvvsq09tsJhhns3b63+3vyk89h3guMwYDDNIp1EhFRLRfdGKKHkeMwjWQb8OsdPC6Pk= X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a05:6902:2b8f:b0:e03:59e2:e82 with SMTP id 3f1490d57ef6-e0b545a3f3dmr1133276.10.1722023878276; Fri, 26 Jul 2024 12:57:58 -0700 (PDT) Date: Fri, 26 Jul 2024 19:57:45 +0000 In-Reply-To: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240726-b4-rbtree-v7-0-aee88caaf97c@google.com> X-Mailer: b4 0.13.0 Message-ID: <20240726-b4-rbtree-v7-6-aee88caaf97c@google.com> Subject: [PATCH v7 6/6] rust: rbtree: add `RBTree::entry` From: Matt Gilbride To: Miguel Ojeda , Alex Gaynor , Wedson Almeida Filho , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Alice Ryhl , Greg Kroah-Hartman , "=?utf-8?q?Arve_Hj=C3=B8nnev=C3=A5g?=" , Todd Kjos , Martijn Coenen , Joel Fernandes , Carlos Llamas , Suren Baghdasaryan , Christian Brauner Cc: Rob Landley , Davidlohr Bueso , Michel Lespinasse , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Matt Gilbride Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable From: Alice Ryhl This mirrors the entry API [1] from the Rust standard library on `RBTree`. This API can be used to access the entry at a specific key and make modifications depending on whether the key is vacant or occupied. This API is useful because it can often be used to avoid traversing the tree multiple times. This is used by binder to look up and conditionally access or insert a value, depending on whether it is there or not [2]. Link: https://doc.rust-lang.org/stable/std/collections/btree_map/enum.Entry= .html [1] Link: https://android-review.googlesource.com/c/kernel/common/+/2849906 [2] Signed-off-by: Alice Ryhl Tested-by: Alice Ryhl Signed-off-by: Matt Gilbride Reviewed-by: Boqun Feng --- rust/kernel/rbtree.rs | 302 +++++++++++++++++++++++++++++++++++++---------= ---- 1 file changed, 227 insertions(+), 75 deletions(-) diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index 5611ae903779..f6d5162e46f5 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -295,12 +295,19 @@ pub fn try_create_and_insert( /// key/value pair). Returns [`None`] if a node with the same key didn= 't already exist. /// /// This function always succeeds. - pub fn insert(&mut self, RBTreeNode { node }: RBTreeNode) -> Opt= ion> { - let node =3D Box::into_raw(node); - // SAFETY: `node` is valid at least until we call `Box::from_raw`,= which only happens when - // the node is removed or replaced. - let node_links =3D unsafe { addr_of_mut!((*node).links) }; + pub fn insert(&mut self, node: RBTreeNode) -> Option> { + match self.raw_entry(&node.node.key) { + RawEntry::Occupied(entry) =3D> Some(entry.replace(node)), + RawEntry::Vacant(entry) =3D> { + entry.insert(node); + None + } + } + } =20 + fn raw_entry(&mut self, key: &K) -> RawEntry<'_, K, V> { + let raw_self: *mut RBTree =3D self; + // The returned `RawEntry` is used to call either `rb_link_node` o= r `rb_replace_node`. // The parameters of `rb_link_node` are as follows: // - `node`: A pointer to an uninitialized node being inserted. // - `parent`: A pointer to an existing node in the tree. One of i= ts child pointers must be @@ -319,62 +326,56 @@ pub fn insert(&mut self, RBTreeNode { node }: RBTreeN= ode) -> Option`. + let node =3D unsafe { container_of!(curr, Node, links) }; =20 - // We need to determine whether `node` should be the left or r= ight child of `parent`, - // so we will compare with the `key` field of `parent` a.k.a. = `this` below. - // - // SAFETY: By the type invariant of `Self`, all non-null `rb_n= ode` pointers stored in `self` - // point to the links field of `Node` objects. - let this =3D unsafe { container_of!(parent, Node, links)= }; - - // SAFETY: `this` is a non-null node so it is valid by the typ= e invariants. `node` is - // valid until the node is removed. - match unsafe { (*node).key.cmp(&(*this).key) } { - // We would like `node` to be the left child of `parent`. = Move to this child to check - // whether we can use it, or continue searching, at the ne= xt iteration. - // - // SAFETY: `parent` is a non-null node so it is valid by t= he type invariants. - Ordering::Less =3D> child_field_of_parent =3D unsafe { &mu= t (*parent).rb_left }, - // We would like `node` to be the right child of `parent`.= Move to this child to check - // whether we can use it, or continue searching, at the ne= xt iteration. - // - // SAFETY: `parent` is a non-null node so it is valid by t= he type invariants. - Ordering::Greater =3D> child_field_of_parent =3D unsafe { = &mut (*parent).rb_right }, + // SAFETY: `node` is a non-null node so it is valid by the typ= e invariants. + match key.cmp(unsafe { &(*node).key }) { + // SAFETY: `curr` is a non-null node so it is valid by the= type invariants. + Ordering::Less =3D> child_field_of_parent =3D unsafe { &mu= t (*curr).rb_left }, + // SAFETY: `curr` is a non-null node so it is valid by the= type invariants. + Ordering::Greater =3D> child_field_of_parent =3D unsafe { = &mut (*curr).rb_right }, Ordering::Equal =3D> { - // There is an existing node in the tree with this key= , and that node is - // parent. Thus, we are replacing parent with a new n= ode. - // - // INVARIANT: We are replacing an existing node with a= new one, which is valid. - // It remains valid because we "forgot" it with `Box::= into_raw`. - // SAFETY: All pointers are non-null and valid. - unsafe { bindings::rb_replace_node(parent, node_links,= &mut self.root) }; - - // INVARIANT: The node is being returned and the calle= r may free it, however, - // it was removed from the tree. So the invariants sti= ll hold. - return Some(RBTreeNode { - // SAFETY: `this` was a node in the tree, so it is= valid. - node: unsafe { Box::from_raw(this.cast_mut()) }, - }); + return RawEntry::Occupied(OccupiedEntry { + rbtree: self, + node_links: curr, + }) } } + parent =3D curr; } =20 - // INVARIANT: We are linking in a new node, which is valid. It rem= ains valid because we - // "forgot" it with `Box::into_raw`. - // SAFETY: All pointers are non-null and valid (`*child_field_of_p= arent` is null, but `child_field_of_parent` is a - // mutable reference). - unsafe { bindings::rb_link_node(node_links, parent, child_field_of= _parent) }; + RawEntry::Vacant(RawVacantEntry { + rbtree: raw_self, + parent, + child_field_of_parent, + _phantom: PhantomData, + }) + } =20 - // SAFETY: All pointers are valid. `node` has just been inserted i= nto the tree. - unsafe { bindings::rb_insert_color(node_links, &mut self.root) }; - None + /// Gets the given key's corresponding entry in the map for in-place m= anipulation. + pub fn entry(&mut self, key: K) -> Entry<'_, K, V> { + match self.raw_entry(&key) { + RawEntry::Occupied(entry) =3D> Entry::Occupied(entry), + RawEntry::Vacant(entry) =3D> Entry::Vacant(VacantEntry { raw: = entry, key }), + } + } + + /// Used for accessing the given node, if it exists. + pub fn find_mut(&mut self, key: &K) -> Option>= { + match self.raw_entry(key) { + RawEntry::Occupied(entry) =3D> Some(entry), + RawEntry::Vacant(_entry) =3D> None, + } } =20 - /// Returns a node with the given key, if one exists. - fn find(&self, key: &K) -> Option>> { + /// Returns a reference to the value corresponding to the key. + pub fn get(&self, key: &K) -> Option<&V> { let mut node =3D self.root.rb_node; while !node.is_null() { // SAFETY: By the type invariant of `Self`, all non-null `rb_n= ode` pointers stored in `self` @@ -386,47 +387,30 @@ fn find(&self, key: &K) -> Option>= > { Ordering::Less =3D> unsafe { (*node).rb_left }, // SAFETY: `node` is a non-null node so it is valid by the= type invariants. Ordering::Greater =3D> unsafe { (*node).rb_right }, - Ordering::Equal =3D> return NonNull::new(this.cast_mut()), + // SAFETY: `node` is a non-null node so it is valid by the= type invariants. + Ordering::Equal =3D> return Some(unsafe { &(*this).value }= ), } } None } =20 - /// Returns a reference to the value corresponding to the key. - pub fn get(&self, key: &K) -> Option<&V> { - // SAFETY: The `find` return value is a node in the tree, so it is= valid. - self.find(key).map(|node| unsafe { &node.as_ref().value }) - } - /// Returns a mutable reference to the value corresponding to the key. pub fn get_mut(&mut self, key: &K) -> Option<&mut V> { - // SAFETY: The `find` return value is a node in the tree, so it is= valid. - self.find(key) - .map(|mut node| unsafe { &mut node.as_mut().value }) + self.find_mut(key).map(|node| node.into_mut()) } =20 /// Removes the node with the given key from the tree. /// /// It returns the node that was removed if one exists, or [`None`] ot= herwise. - fn remove_node(&mut self, key: &K) -> Option> { - let mut node =3D self.find(key)?; - - // SAFETY: The `find` return value is a node in the tree, so it is= valid. - unsafe { bindings::rb_erase(&mut node.as_mut().links, &mut self.ro= ot) }; - - // INVARIANT: The node is being returned and the caller may free i= t, however, it was - // removed from the tree. So the invariants still hold. - Some(RBTreeNode { - // SAFETY: The `find` return value was a node in the tree, so = it is valid. - node: unsafe { Box::from_raw(node.as_ptr()) }, - }) + pub fn remove_node(&mut self, key: &K) -> Option> { + self.find_mut(key).map(OccupiedEntry::remove_node) } =20 /// Removes the node with the given key from the tree. /// /// It returns the value that was removed if one exists, or [`None`] o= therwise. pub fn remove(&mut self, key: &K) -> Option { - self.remove_node(key).map(|node| node.node.value) + self.find_mut(key).map(OccupiedEntry::remove) } =20 /// Returns a cursor over the tree nodes based on the given key. @@ -1131,6 +1115,174 @@ unsafe impl Send for RBTreeNode {} // [`RBTreeNode`] without synchronization. unsafe impl Sync for RBTreeNode {} =20 +impl RBTreeNode { + /// Drop the key and value, but keep the allocation. + /// + /// It then becomes a reservation that can be re-initialised into a di= fferent node (i.e., with + /// a different key and/or value). + /// + /// The existing key and value are dropped in-place as part of this op= eration, that is, memory + /// may be freed (but only for the key/value; memory for the node itse= lf is kept for reuse). + pub fn into_reservation(self) -> RBTreeNodeReservation { + RBTreeNodeReservation { + node: Box::drop_contents(self.node), + } + } +} + +/// A view into a single entry in a map, which may either be vacant or occ= upied. +/// +/// This enum is constructed from the [`RBTree::entry`]. +/// +/// [`entry`]: fn@RBTree::entry +pub enum Entry<'a, K, V> { + /// This [`RBTree`] does not have a node with this key. + Vacant(VacantEntry<'a, K, V>), + /// This [`RBTree`] already has a node with this key. + Occupied(OccupiedEntry<'a, K, V>), +} + +/// Like [`Entry`], except that it doesn't have ownership of the key. +enum RawEntry<'a, K, V> { + Vacant(RawVacantEntry<'a, K, V>), + Occupied(OccupiedEntry<'a, K, V>), +} + +/// A view into a vacant entry in a [`RBTree`]. It is part of the [`Entry`= ] enum. +pub struct VacantEntry<'a, K, V> { + key: K, + raw: RawVacantEntry<'a, K, V>, +} + +/// Like [`VacantEntry`], but doesn't hold on to the key.a +/// +/// # Invariants +/// - `parent` may be null if the new node becomes the root. +/// - `child_field_of_parent` is a valid pointer to the left-child or righ= t-child of `parent`. If `parent` is +/// null, it is a pointer to the root of the [`RBTree`]. +struct RawVacantEntry<'a, K, V> { + rbtree: *mut RBTree, + /// The node that will become the parent of the new node if we insert = one. + parent: *mut bindings::rb_node, + /// This points to the left-child or right-child field of `parent`, or= `root` if `parent` is + /// null. + child_field_of_parent: *mut *mut bindings::rb_node, + _phantom: PhantomData<&'a mut RBTree>, +} + +impl<'a, K, V> RawVacantEntry<'a, K, V> { + /// Inserts the given node into the [`RBTree`] at this entry. + /// + /// The `node` must have a key such that inserting it here does not br= eak the ordering of this + /// [`RBTree`]. + fn insert(self, node: RBTreeNode) -> &'a mut V { + let node =3D Box::into_raw(node.node); + + // SAFETY: `node` is valid at least until we call `Box::from_raw`,= which only happens when + // the node is removed or replaced. + let node_links =3D unsafe { addr_of_mut!((*node).links) }; + + // INVARIANT: We are linking in a new node, which is valid. It rem= ains valid because we + // "forgot" it with `Box::into_raw`. + // SAFETY: The type invariants of `RawVacantEntry` are exactly the= safety requirements of `rb_link_node`. + unsafe { bindings::rb_link_node(node_links, self.parent, self.chil= d_field_of_parent) }; + + // SAFETY: All pointers are valid. `node` has just been inserted i= nto the tree. + unsafe { bindings::rb_insert_color(node_links, addr_of_mut!((*self= .rbtree).root)) }; + + // SAFETY: The node is valid until we remove it from the tree. + unsafe { &mut (*node).value } + } +} + +impl<'a, K, V> VacantEntry<'a, K, V> { + /// Inserts the given node into the [`RBTree`] at this entry. + pub fn insert(self, value: V, reservation: RBTreeNodeReservation= ) -> &'a mut V { + self.raw.insert(reservation.into_node(self.key, value)) + } +} + +/// A view into an occupied entry in a [`RBTree`]. It is part of the [`Ent= ry`] enum. +/// +/// # Invariants +/// - `node_links` is a valid, non-null pointer to a tree node in `self.rb= tree` +pub struct OccupiedEntry<'a, K, V> { + rbtree: &'a mut RBTree, + /// The node that this entry corresponds to. + node_links: *mut bindings::rb_node, +} + +impl<'a, K, V> OccupiedEntry<'a, K, V> { + fn node_ptr(&self) -> *mut Node { + // SAFETY: By the type invariant of `Self`, all `node_links` point= ers stored in `self` + // point to the links field of `Node` objects. + unsafe { container_of!(self.node_links, Node, links) }.cast_= mut() + } + + /// Gets a reference to the value in the entry. + pub fn get(&self) -> &V { + // SAFETY: `self.node_ptr` produces a valid pointer to a node in t= he tree. + unsafe { &(*self.node_ptr()).value } + } + + /// Gets a mutable reference to the value in the entry. + pub fn get_mut(&mut self) -> &mut V { + // SAFETY: `self.node_ptr` produces a valid pointer to a node in t= he tree. + unsafe { &mut (*self.node_ptr()).value } + } + + /// Converts the entry into a mutable reference to its value. + /// + /// If you need multiple references to the `OccupiedEntry`, see [`self= #get_mut`]. + pub fn into_mut(self) -> &'a mut V { + // SAFETY: `self.node_ptr` produces a valid pointer to a node in t= he tree. + unsafe { &mut (*self.node_ptr()).value } + } + + /// Remove this entry from the [`RBTree`]. + pub fn remove_node(self) -> RBTreeNode { + // SAFETY: The node is a node in the tree, so it is valid. + unsafe { bindings::rb_erase(self.node_links, &mut self.rbtree.root= ) }; + + // INVARIANT: The node is being returned and the caller may free i= t, however, it was + // removed from the tree. So the invariants still hold. + RBTreeNode { + // SAFETY: The node was a node in the tree, but we removed it,= so we can convert it + // back into a box. + node: unsafe { Box::from_raw(self.node_ptr()) }, + } + } + + /// Takes the value of the entry out of the map, and returns it. + pub fn remove(self) -> V { + self.remove_node().node.value + } + + /// Swap the current node for the provided node. + /// + /// The key of both nodes must be equal. + fn replace(self, node: RBTreeNode) -> RBTreeNode { + let node =3D Box::into_raw(node.node); + + // SAFETY: `node` is valid at least until we call `Box::from_raw`,= which only happens when + // the node is removed or replaced. + let new_node_links =3D unsafe { addr_of_mut!((*node).links) }; + + // SAFETY: This updates the pointers so that `new_node_links` is i= n the tree where + // `self.node_links` used to be. + unsafe { + bindings::rb_replace_node(self.node_links, new_node_links, &mu= t self.rbtree.root) + }; + + // SAFETY: + // - `self.node_ptr` produces a valid pointer to a node in the tre= e. + // - Now that we removed this entry from the tree, we can convert = the node to a box. + let old_node =3D unsafe { Box::from_raw(self.node_ptr()) }; + + RBTreeNode { node: old_node } + } +} + struct Node { links: bindings::rb_node, key: K, --=20 2.46.0.rc1.232.g9752f9e123-goog