Received: by 2002:ab2:6309:0:b0:1fb:d597:ff75 with SMTP id s9csp453606lqt; Thu, 6 Jun 2024 08:20:24 -0700 (PDT) X-Forwarded-Encrypted: i=3; AJvYcCVi7Ca7lFC5sKZw753J5Y1rK0ku2D1kPNf8Pbr9FcH9UFcPaUAfmRW0MRwmFYfEMeZXAINMsaQJ6NT6Kj/1cYqCxROTR6LZZoZFS6ZV1w== X-Google-Smtp-Source: AGHT+IF9cRsDJL+v/yiAwN1OcRozALPchWJ0Eat4LMBSwjNqNFagS0cDR7bjMTfCzN5NB+iOI3hw X-Received: by 2002:a05:6a20:6a26:b0:1b1:e7de:4d39 with SMTP id adf61e73a8af0-1b2b6ed82acmr7119369637.16.1717687223797; Thu, 06 Jun 2024 08:20:23 -0700 (PDT) ARC-Seal: i=2; a=rsa-sha256; t=1717687223; cv=pass; d=google.com; s=arc-20160816; b=HbA4/n99vRT+MGAjtAswRUJia+ORFuw8gJ0bkC469veeNn7edQtVCPWq4hDFQZiENH 19Do2zpngBYcuuH1JP0+0Pm+XZVcMSoWKkaHB93GQlP00zufROjZWDPB4yUNSgfSty4G ldEV8/dM/nBBz/caMWfw3LYEqdeiHjFFAHTGWU8ZzgyA2IEESVj3SPQz8tHUUC+F2UQV Ualwyb0sg0C847CiqN5kMXcoulAMko9IJtX4fL8ygnmHU2xjRLjcm6BvThVSxttEmeUh 1c50F2cd7aRV9hdfmoclmX2+Qg+QlcDaEW51qSUsKw0Lus62wdW1tRoz/YKmQke+RrYJ 3MpQ== ARC-Message-Signature: i=2; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=cc:to:from:subject:message-id:references:mime-version :list-unsubscribe:list-subscribe:list-id:precedence:in-reply-to:date :dkim-signature; bh=tpcQthLt2ymcISiYcygIvr8b8/AUKo/Ks1I8+CxjzuM=; fh=wBNt2lXB9o8k9QV8nXZBgDh3rAFpDeloOliOZFgu3W4=; b=Twt/RUy3LptN484jUgHtGsRLE5W80DLsCTKjnPxNmzHR4yzGqVEps4ZORaMauWQmld lf/FoAVn9h/LHr3V5MDHuP0MGkNFlk2xX9OcsWqXIfcNLmd2OxVHN1bRcNoaRwO2i4Ly AEH1gwNiiRrtYfAv9IrEbZQWsQL+xFVg6y0sQv4yuoiNG7+xyK4U5+bz1tyt92+Zq5eQ bRCH+rt+ElZQMnQPHLjldWxOj4KgeZ+uyGZGCwN9PCpM8vs0n60j0tOPUJLYe8ManQ0m romFkQvuxuqd5jDQ9MaD/vPP59bmtjTuPD+Ms/otaN63NNTm5P0d43BEz7sfFTdxSzMP Szgg==; dara=google.com ARC-Authentication-Results: i=2; mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=w7MC9K7d; arc=pass (i=1 spf=pass spfdomain=flex--mattgilbride.bounces.google.com dkim=pass dkdomain=google.com dmarc=pass fromdomain=google.com); spf=pass (google.com: domain of linux-kernel+bounces-204524-linux.lists.archive=gmail.com@vger.kernel.org designates 2604:1380:45e3:2400::1 as permitted sender) smtp.mailfrom="linux-kernel+bounces-204524-linux.lists.archive=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Return-Path: Received: from sv.mirrors.kernel.org (sv.mirrors.kernel.org. [2604:1380:45e3:2400::1]) by mx.google.com with ESMTPS id 41be03b00d2f7-6de27cc6380si1314907a12.558.2024.06.06.08.20.23 for (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 06 Jun 2024 08:20:23 -0700 (PDT) Received-SPF: pass (google.com: domain of linux-kernel+bounces-204524-linux.lists.archive=gmail.com@vger.kernel.org designates 2604:1380:45e3:2400::1 as permitted sender) client-ip=2604:1380:45e3:2400::1; Authentication-Results: mx.google.com; dkim=pass header.i=@google.com header.s=20230601 header.b=w7MC9K7d; arc=pass (i=1 spf=pass spfdomain=flex--mattgilbride.bounces.google.com dkim=pass dkdomain=google.com dmarc=pass fromdomain=google.com); spf=pass (google.com: domain of linux-kernel+bounces-204524-linux.lists.archive=gmail.com@vger.kernel.org designates 2604:1380:45e3:2400::1 as permitted sender) smtp.mailfrom="linux-kernel+bounces-204524-linux.lists.archive=gmail.com@vger.kernel.org"; dmarc=pass (p=REJECT sp=REJECT dis=NONE) header.from=google.com Received: from smtp.subspace.kernel.org (wormhole.subspace.kernel.org [52.25.139.140]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by sv.mirrors.kernel.org (Postfix) with ESMTPS id 0AB0C287E6C for ; Thu, 6 Jun 2024 15:11:41 +0000 (UTC) Received: from localhost.localdomain (localhost.localdomain [127.0.0.1]) by smtp.subspace.kernel.org (Postfix) with ESMTP id ACC111A0B07; Thu, 6 Jun 2024 14:50:30 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="w7MC9K7d" 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 6EE8D1A01BE for ; Thu, 6 Jun 2024 14:50:26 +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=1717685429; cv=none; b=bANSx9DwjCRMnNynjf3Hitie+TONHAKvgMwWQ/jVIUdnzoU/sJKQUJ6W0pFhC8bNj/OuhAkJoDFvCQ6vrRPZiSoz9nTNc07L0wMbieqxXlyl/Uwdf12+IIGrUG7ulbKxcVchHWp0HUKTvbJpkAiuIJBPel7+jru1Jq+fbzZKElE= ARC-Message-Signature:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1717685429; c=relaxed/simple; bh=i+7bw4mDJ6wxt7468SYhV7yMxNQQl0UlbzuIKHgsdNI=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=MF6D7ZtnOS6qlezVlGEFHLyQW8DEp93dXGslETjqOoWgTgr/8AX4GVNVe59cbtHCFOHr6P5CL9ZYNlKo9H9jVYywMMO6hxeQyMADfrHfigUa2o+PlGtd7yJ3DMstDJKICZdjnV6k1CVM4p6IDEJhbgoCqwYFvlAggAHINL4NQyA= 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=w7MC9K7d; 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 Received: by mail-yb1-f202.google.com with SMTP id 3f1490d57ef6-df77196089eso1794896276.1 for ; Thu, 06 Jun 2024 07:50:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1717685425; x=1718290225; 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=tpcQthLt2ymcISiYcygIvr8b8/AUKo/Ks1I8+CxjzuM=; b=w7MC9K7d0px6wtoa2SaLVyRuOOpsSNtkAmLaUSYl6UEZTRA5djN0Gob0nmeLa94422 5y697r7IZKyxNHfKnDUEIS/971qFHemt8eUelEJEdtrlhokuT8nZKvKTB+UJ9QskmBrF 6sCxnpqQNp/K2lykwOoEveNF3ubrUwDshRozj/ehIn2eqViuvQaYDPmMugIWSjlNgsGP LyZKpTPtQJXlQlhMtfTX6Xt5zLlu5ShQhCLOo37yQ0rwhrtCW4SrkqNEg3xx8wy2nuBO BlKsfx3cpU+cbHzkXoycB6cTth+mle/xPHrRJ5BbV3+qEyrzLM/FWet+0EkuJHEtW/Oq qBIA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1717685425; x=1718290225; 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=tpcQthLt2ymcISiYcygIvr8b8/AUKo/Ks1I8+CxjzuM=; b=Z0695kxWk62e2x0Y9lxpWswjFMjp71oRRhEuMyUW4n+8z1gTgrUCHSjZ4sSXOA6JRa GSbUpqOF3he2/sV8UkDwHSmtuKnBqUxPk3NDWljpe1Jief8qt89a8sOUGA6bJovVMjZ6 EitJRRi+Oua7OhDgUUNcgLJsYDV1S3XKsKuj4Pf5niId0KE213Cah7P08FJ49DhGIJPu yiV0emwi4tnHNEW0SxXCPLvyfbju+rpO69TZolmuk5M/m3JFmevzSrnNs5WLqfMeMuhe yk3eJl4oNmrWis0FESj/5842PMaKKPIH0jtC9hROYIXjUe9i3brENtgsjH+t5Q4CPlcA j92g== X-Forwarded-Encrypted: i=1; AJvYcCUZxWcD+IkY7gGe0NtN89EyhH+ltIe4mWqKlxCVnLsBdpgAacGL7KUw1RTSnLXdJrmb3Jn5q2e7vYKwXSHW3wuaCJH5q9lCBfb3pRF0 X-Gm-Message-State: AOJu0Yw6IUKNkUwj6f3VmyK7vI3k19NLn86aFAUVD0bkVzmxCEIG6uAZ WPkHU6u6zfLbzGBb6idmCk0Gp1FYs6J2OmaBfKuxbxY43lwjc1PbvzCVl4Ve8jlNRCinG9xTu8U o2uhCqsdR9fbg5vvMS4LMla/CxQ== X-Received: from mattgilbride.c.googlers.com ([fda3:e722:ac3:cc00:2b:7d90:c0a8:2ac5]) (user=mattgilbride job=sendgmr) by 2002:a05:6902:1202:b0:df4:572b:a82f with SMTP id 3f1490d57ef6-dfacace2163mr319169276.8.1717685425443; Thu, 06 Jun 2024 07:50:25 -0700 (PDT) Date: Thu, 06 Jun 2024 14:50:07 +0000 In-Reply-To: <20240606-b4-rbtree-v5-0-96fe1a0e97c0@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20240606-b4-rbtree-v5-0-96fe1a0e97c0@google.com> X-Mailer: b4 0.12.4 Message-ID: <20240606-b4-rbtree-v5-4-96fe1a0e97c0@google.com> Subject: [PATCH v5 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" 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-08ba9197f637@google.com/ [1] Signed-off-by: Wedson Almeida Filho Signed-off-by: Matt Gilbride Reviewed-by: Alice Ryhl Tested-by: Alice Ryhl --- 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 tree 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, + }, } } @@ -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 tree, sorted by key. + pub fn values_mut(&mut self) -> impl Iterator { + self.iter_mut().map(|(_, v)| v) + } } 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, } // SAFETY: The [`Iter`] gives out immutable references to K and V, so it has 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 = (&'a K, &'a V); + 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 = (&'a K, &'a mut V); + type IntoIter = 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 = (&'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 = (*mut K, *mut 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`, + // SAFETY: By the type invariant of `IterRaw`, `self.next` is a valid node in an `RBTree`, // and by the type invariant of `RBTree`, all nodes point to the links field of `Node` objects. - let cur = unsafe { container_of!(self.next, Node, links) }; + let cur: *mut Node = + unsafe { container_of!(self.next, Node, links) }.cast_mut(); // SAFETY: `self.next` is a valid tree node by the type invariants. self.next = 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) }) + // 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)) }) } } -- 2.45.1.467.gbab1589fc0-goog