From nobody Wed Oct 8 05:57:15 2025 Received: from mail-qt1-f175.google.com (mail-qt1-f175.google.com [209.85.160.175]) (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 818291F428F; Tue, 1 Jul 2025 16:27:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.175 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751387244; cv=none; b=nqdwRP0pJcQIkw6bdGM0QdECew3MC2okkG+vX/3gmsZQbnn47maeK/HWiibmslZe6vgS3EuzT85S3N/kT4cuKjdUD/CoDeCnp1z7Vq9dI1oXWZC9mI378cGotvy8y6RbFIO5usmVWP9sN65lVs84alRrZht5WWKvpwyg2en+9SQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751387244; c=relaxed/simple; bh=6+JWHRQrsJr9x2ppc7qmssdLhjjYvIA6rjRIQSQBx6E=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=cVQID7eQJZjqxo8sp9dIUHYO+ktTQOa4q+ITUuqzv71/qcufSbae/civ574NnNLLN6dTPuerTZifYLDGn4klXqP3G9/ibZAHkyWVuWqvkr0lHTzudcy0YUmbFjQJvM9DCjWigZi4yEFzccEQAg9WXf+FZ5z8GdssqVMmsw5r4HE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=UHo058GP; arc=none smtp.client-ip=209.85.160.175 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="UHo058GP" Received: by mail-qt1-f175.google.com with SMTP id d75a77b69052e-4a5903bceffso80258821cf.3; Tue, 01 Jul 2025 09:27:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1751387241; x=1751992041; darn=vger.kernel.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=mLU+YZa8/2fX3jeZYFHTBUPRRth7cMW0M2466qiW6WY=; b=UHo058GPTo46PblhyH+yBeOa6/6EOYMq08FgxXwrZTDvPN8WMkUFFZkSdCfqI31wUX 4Ca1Gm9B5ixYXmfBPYMpydsN9eM+XiOv8gf0UjFuEB+ARHtYgsjPWGx1gNjfI4eyIEn+ zB2zrhFoT1zLQac0rbHPDcNYrTruy0BGBPZ0zcBGsAGmqarmeOKzI+gRQ8eFkSLyL/u5 thsHO3NcSrRZ06JcgYS0SJ4WxVF1x5M3qNc2KU0i3Bezdv/F7XpR9QhMEbTjflMdzKDq hPM8za/87Qd+QNmCVPBtwJOzuYSKW0djweLz5zIjgJ0gpo0si1fL2Zj8shGrByQpe9W5 F+Kg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1751387241; x=1751992041; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=mLU+YZa8/2fX3jeZYFHTBUPRRth7cMW0M2466qiW6WY=; b=nwbg8m9czcm5lRJjqH9V1arCbVJ0TpcYHZUMFhMJ9b+0XPzp242gfJft7avD9YyRx6 KbvNRmNGPSLEWBMJRf83GMCYgyolrGh/dkmqa/Hju4YinBi6Q4eBGWc/tKrhiSgSA9ou rWujLxALTnQePau/ukvssL7es6a6iJIxXU9myXOcGjAm2r+uS6yg706sGdnzusSL08Q6 FwX1qY4gLy/y4PK1U7l1LqcBqCATPPraJCvNwbgs+xIsIxIXI8nOWOP2LpRo6TzG2UFA 4BH2B8ahaPqy2v225WBRoA/+cEZIAodzxiGfGwOuJKdJ/H1AKDU/uaOf+EV8qUdWHhYv pA2A== X-Forwarded-Encrypted: i=1; AJvYcCVAq/VZtpNcT+soC4km8RWWCgB+YrSDZQLYdFx5hBlMLp8xoU1Y02/yFmFWUbfrG5vWZsSiKYRjKhe/KAZV@vger.kernel.org, AJvYcCViB4nthllPBbrU07aXl58mYHT7ms3x4EyoX0bWV+BHju0QSehuyzbkhUvbJd+ZuR15zpqLyHIw04KV/6Dx@vger.kernel.org X-Gm-Message-State: AOJu0Yy3WEMjCEUZwa9eYwKje3aZlI2jj0yQq90QM9th5/AQujk0sD26 4tDM8z7Qgcd0pvkRZ2XwYwVLDJrX0HuuCi9GawGuUAten9ssPEm5Po9V X-Gm-Gg: ASbGncsfDxcfDYX/0Jh3DA9ezRu5byUf9RIyR/1lVyRUXG5m5mpQR4hVLveBwTCaTCs q0QCsXqs6Di5Zx7Zgtu3j3J7AoAxc72r8QLcyvXm5+CGtg6GC2Dsn5XptX7zyWpXlti10q7UZYO xm/iie+2XSTNDuG6piWt6eHhOzA8i5H7En2g1sonEo5LuHSm/vl4nmYnQwwpR7dVTOM86pQGnS0 1Bwqm5xDG3m07GuMZD8UkFyf/omUqTZI3ynv2aHrPH2GoLtpmEZRiEdh8PQjaxzCbt7NXYS+TBW 7i3rao+cLJFg+JdT5aCkazyDhxkJnvbNR6dFUJuuvCwEWozUTkEqjGY+EE1WlnnnwctcOMF++Lx IN7rMclxwc2FEelvxm+pC43PoaaYUgPSdbGqznEdxi1DgFW1efuPEvY7yBbhOXDBqwqFPo/TMEG 98cLmZjEc9 X-Google-Smtp-Source: AGHT+IHjull5pZaZOmzFoWcLMMTVVB/TU/UDIVBB2RfCc3y0hEwP4g/cpzzoaBBku8R/IYqzsSGzTQ== X-Received: by 2002:ac8:6908:0:b0:4a7:6be7:c0a1 with SMTP id d75a77b69052e-4a7fc9d55e3mr261092331cf.7.1751387241221; Tue, 01 Jul 2025 09:27:21 -0700 (PDT) Received: from a.1.b.d.0.e.7.9.6.4.2.0.b.3.4.b.0.0.1.1.e.f.b.5.1.4.0.4.0.0.6.2.ip6.arpa ([2600:4041:5bfe:1100:70ac:5fd8:4c25:89ec]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-4a7fc57d530sm78032551cf.61.2025.07.01.09.27.20 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 01 Jul 2025 09:27:20 -0700 (PDT) From: Tamir Duberstein Date: Tue, 01 Jul 2025 12:27:17 -0400 Subject: [PATCH 1/3] rust: xarray: use the prelude Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250701-xarray-insert-reserve-v1-1-25df2b0d706a@gmail.com> References: <20250701-xarray-insert-reserve-v1-0-25df2b0d706a@gmail.com> In-Reply-To: <20250701-xarray-insert-reserve-v1-0-25df2b0d706a@gmail.com> To: Andreas Hindborg , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Danilo Krummrich , Matthew Wilcox , Andrew Morton Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-fsdevel@vger.kernel.org, linux-mm@kvack.org, Daniel Almeida , Tamir Duberstein X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openssh-sha256; t=1751387238; l=2572; i=tamird@gmail.com; h=from:subject:message-id; bh=6+JWHRQrsJr9x2ppc7qmssdLhjjYvIA6rjRIQSQBx6E=; b=U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAgtYz36g7iDMSkY5K7Ab51ksGX7hJgs MRt+XVZTrIzMVIAAAAGcGF0YXR0AAAAAAAAAAZzaGE1MTIAAABTAAAAC3NzaC1lZDI1NTE5AAAA QDakeJi/FwTTBDnMaXReFFgJmz/pR3aoj2VMRZA241i/MtypqGlmssWkhQAB2n1ll13P3DfXYS1 BElXBlnovSw0= X-Developer-Key: i=tamird@gmail.com; a=openssh; fpr=SHA256:264rPmnnrb+ERkS7DDS3tuwqcJss/zevJRzoylqMsbc Using the prelude is customary in the kernel crate. Signed-off-by: Tamir Duberstein Reviewed-by: Janne Grunau Tested-by: Janne Grunau --- rust/kernel/xarray.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/rust/kernel/xarray.rs b/rust/kernel/xarray.rs index 75719e7bb491..436faad99c89 100644 --- a/rust/kernel/xarray.rs +++ b/rust/kernel/xarray.rs @@ -5,16 +5,15 @@ //! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h) =20 use crate::{ - alloc, bindings, build_assert, - error::{Error, Result}, + alloc, + prelude::*, types::{ForeignOwnable, NotThreadSafe, Opaque}, }; -use core::{iter, marker::PhantomData, mem, pin::Pin, ptr::NonNull}; -use pin_init::{pin_data, pin_init, pinned_drop, PinInit}; +use core::{iter, marker::PhantomData, mem, ptr::NonNull}; =20 /// An array which efficiently maps sparse integer indices to owned object= s. /// -/// This is similar to a [`crate::alloc::kvec::Vec>`], but more = efficient when there are +/// This is similar to a [`Vec>`], but more efficient when there= are /// holes in the index space, and can be efficiently grown. /// /// # Invariants @@ -104,16 +103,23 @@ pub fn new(kind: AllocKind) -> impl PinInit { fn iter(&self) -> impl Iterator> + '_ { let mut index =3D 0; =20 - // SAFETY: `self.xa` is always valid by the type invariant. - iter::once(unsafe { - bindings::xa_find(self.xa.get(), &mut index, usize::MAX, bindi= ngs::XA_PRESENT) - }) - .chain(iter::from_fn(move || { + core::iter::Iterator::chain( // SAFETY: `self.xa` is always valid by the type invariant. - Some(unsafe { - bindings::xa_find_after(self.xa.get(), &mut index, usize::= MAX, bindings::XA_PRESENT) - }) - })) + iter::once(unsafe { + bindings::xa_find(self.xa.get(), &mut index, usize::MAX, b= indings::XA_PRESENT) + }), + iter::from_fn(move || { + // SAFETY: `self.xa` is always valid by the type invariant. + Some(unsafe { + bindings::xa_find_after( + self.xa.get(), + &mut index, + usize::MAX, + bindings::XA_PRESENT, + ) + }) + }), + ) .map_while(|ptr| NonNull::new(ptr.cast())) } =20 --=20 2.50.0 From nobody Wed Oct 8 05:57:15 2025 Received: from mail-qt1-f178.google.com (mail-qt1-f178.google.com [209.85.160.178]) (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 C59F427C145; Tue, 1 Jul 2025 16:27:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.178 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751387245; cv=none; b=dDVcm1VHLzUtjuR+5bjI9vj/j6pe2QKGGtvUVNFLwK33c0PsCY+yFO4SemqsZLpVZcmUkaGhsFF1/gmWj+QFfySi08QfykkNXd8qSc1fwycO7ngbOyZftHotprBYUwZ6XrEqlFLvBx1Bfa78WRswlYfYtwnjMjQmrqNvn8fSlGY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751387245; c=relaxed/simple; bh=aGvJvyB8w+moAcSxmTaopQJRgroqK4bgIeBJiWTqd7I=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=sOsqxl/KOqGl71GVx4wxI7JnVEiiCXPKdEKJM6ZImZVfydcRB4r89xrn5amGpML2K4G4Bt/UavlhBIVGFOuCIju/S73rLP8/+ZK1srPpGlcXcvRasC58IRe9dL94q+qiO3BiqUl8c35DL6+XVKr+0JMnm+NeYwaA4RA3pdEWVkY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=Kl3IHeWm; arc=none smtp.client-ip=209.85.160.178 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="Kl3IHeWm" Received: by mail-qt1-f178.google.com with SMTP id d75a77b69052e-4a823b532a4so19118871cf.2; Tue, 01 Jul 2025 09:27:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1751387243; x=1751992043; darn=vger.kernel.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=7m5LLXh6Vvt1HNHQi7mgcWgQec9riTqSsqAgm3pbC2Y=; b=Kl3IHeWm+BU9o0a6/XS9mVLy05rDcjp3KPlALocL9jkJRlRdPxkmvNQgw0m3TjML7C 8tjZ+DID0+czISK+lMb5iru87qdQyAsLFqILXxYFJyF2K0gDdfhtvUVDthlrg8uxoOv5 /oeZRQCm0lKgsmjdsQ6JsIOLuaXptULodA5ZzZtBFJjd+kF+KvQo3E6crlEd4aACTMP9 fOVcW3JJsYdv9+dlv6vwKNB8boqQ5vMQEechJoHQaJUi5L01eSE0ioLh8TVa8L98g2jG Q1fVdu4DAPbCFp+1e0KE4YpAJ2VerLu6mGYAuF6eT0mDSdQsUceaKhlyEHSxeaE/sj9V SECA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1751387243; x=1751992043; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=7m5LLXh6Vvt1HNHQi7mgcWgQec9riTqSsqAgm3pbC2Y=; b=k85uk3m44irQYr0PmoSnuLjpGFVMf3tTQLrSa4dtjJqdygFnVPws/kO15W0RbR8XJS 0peu/+jm/TUXCz1QjfJ79B0T6+jLSj0ql5beavNNhyV5pTpAUE8O/oqK9neFgQvNTIKd BvDFCZEd7i+W946K+eHK3d0jpkmCFzy/sm8+A0jjBTC+NeeWvbQ9to8AA6F288w40jJC /+7fr3MulOHnlvvmeQ1l6RtyGw72PDlB6ZJ4TvH0JK2rDa/YpGJ8DFNBBkOVo9oRtul2 EdMmZXY/LxzvKkZ6bjWPPkxXtbRQKLjUfOCBjF+FxUTjdCt29oSdoYhmsXTP9QeA5oKh 9UjA== X-Forwarded-Encrypted: i=1; AJvYcCWQAswWf9ITlfxgea+w/P3PK/nVudjrBxUYD3pYdOqzGVwKKoYuFoUd3C2pOHimVANV0uIzPfjrUS+KhscS@vger.kernel.org, AJvYcCXT3RL05rhT5cn0ib/ytJXU87YvxifCW8UvAevPv15JWAI0t5kt7W+kELvUD1zowroPH7vSqECl/3lq9xQn@vger.kernel.org X-Gm-Message-State: AOJu0YxTgGIM5g9vD4T9UjyMfD2kYu6AtNCEojg4KalnTiv0IKzoTzvU NjsK9P4Cc05MZwzohLEfEtuyvOPCZu5GdycGL2cCg0APX5uZCse2ZMWt X-Gm-Gg: ASbGncuMepXOd+gkU5FwR14cKh+52tg022K9SBOCFYU/UnzjluUrO1NklSmmvfuo7T8 Zmv1+oAFf6p1+EpfBOwX1ryBTc3a0s0ihc0VoPLxyqwhpWfZadrXD7nG52SoampjiDPQwsbqpgH JbACe+135DqVChkJtwSl9eV1iWP/5++vc1FaTM0XeYoykzDD3Qaxk1RnaKm24sJfN6ZAMt5+xMk Iu9h4WukOOIdzp6cpgq5bfCUdu/zrSDcDDRnAJp6sBSjDzDCHhgfvrNgZ3TIAvUoMHgzfZz7930 XzRu56zy+0L2ULUnNy56tgfVuvY3pPPra2K5msVXD2RAzoqVV0/edfBf5F9FbmFEzWAYOUm3v52 HDZBof3nU4DCe2ZfY01FulgS5yygrBUs/oQRSo6nX3RAbAJ1v6bnTV4txvEmc4fkYEWvcEMkHwQ == X-Google-Smtp-Source: AGHT+IGwGnhb8l9Hw1Mzr0aiSE5JQQWjgKVQGGbklZpx2Mzk98f9kxCEeLmoUVK9vQ4i8xFf2yAhHQ== X-Received: by 2002:ac8:7c4c:0:b0:4a5:98ad:5640 with SMTP id d75a77b69052e-4a7fca4e44cmr315848531cf.23.1751387242446; Tue, 01 Jul 2025 09:27:22 -0700 (PDT) Received: from a.1.b.d.0.e.7.9.6.4.2.0.b.3.4.b.0.0.1.1.e.f.b.5.1.4.0.4.0.0.6.2.ip6.arpa ([2600:4041:5bfe:1100:70ac:5fd8:4c25:89ec]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-4a7fc57d530sm78032551cf.61.2025.07.01.09.27.21 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 01 Jul 2025 09:27:22 -0700 (PDT) From: Tamir Duberstein Date: Tue, 01 Jul 2025 12:27:18 -0400 Subject: [PATCH 2/3] rust: xarray: implement Default for AllocKind Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250701-xarray-insert-reserve-v1-2-25df2b0d706a@gmail.com> References: <20250701-xarray-insert-reserve-v1-0-25df2b0d706a@gmail.com> In-Reply-To: <20250701-xarray-insert-reserve-v1-0-25df2b0d706a@gmail.com> To: Andreas Hindborg , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Danilo Krummrich , Matthew Wilcox , Andrew Morton Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-fsdevel@vger.kernel.org, linux-mm@kvack.org, Daniel Almeida , Tamir Duberstein X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openssh-sha256; t=1751387238; l=1262; i=tamird@gmail.com; h=from:subject:message-id; bh=aGvJvyB8w+moAcSxmTaopQJRgroqK4bgIeBJiWTqd7I=; b=U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAgtYz36g7iDMSkY5K7Ab51ksGX7hJgs MRt+XVZTrIzMVIAAAAGcGF0YXR0AAAAAAAAAAZzaGE1MTIAAABTAAAAC3NzaC1lZDI1NTE5AAAA QD7o3/Mx9a2d9i3hzu8whxbHWeViTVLI5JV/NK1oVEI4eienN6VIXBhryqdEc0J7F3lMl5Fvi7t ZoQmAlUUdtAM= X-Developer-Key: i=tamird@gmail.com; a=openssh; fpr=SHA256:264rPmnnrb+ERkS7DDS3tuwqcJss/zevJRzoylqMsbc Most users are likely to want 0-indexed arrays. Clean up the documentation test accordingly. Signed-off-by: Tamir Duberstein Reviewed-by: Janne Grunau Tested-by: Janne Grunau --- rust/kernel/xarray.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/rust/kernel/xarray.rs b/rust/kernel/xarray.rs index 436faad99c89..bbce54ec695c 100644 --- a/rust/kernel/xarray.rs +++ b/rust/kernel/xarray.rs @@ -24,10 +24,11 @@ /// # Examples /// /// ```rust -/// use kernel::alloc::KBox; -/// use kernel::xarray::{AllocKind, XArray}; +/// # use kernel::alloc::KBox; +/// # use kernel::xarray::XArray; +/// # use pin_init::stack_pin_init; /// -/// let xa =3D KBox::pin_init(XArray::new(AllocKind::Alloc1), GFP_KERNEL)?; +/// stack_pin_init!(let xa =3D XArray::new(Default::default())); /// /// let dead =3D KBox::new(0xdead, GFP_KERNEL)?; /// let beef =3D KBox::new(0xbeef, GFP_KERNEL)?; @@ -75,8 +76,10 @@ fn drop(self: Pin<&mut Self>) { } =20 /// Flags passed to [`XArray::new`] to configure the array's allocation tr= acking behavior. +#[derive(Default)] pub enum AllocKind { /// Consider the first element to be at index 0. + #[default] Alloc, /// Consider the first element to be at index 1. Alloc1, --=20 2.50.0 From nobody Wed Oct 8 05:57:15 2025 Received: from mail-qt1-f178.google.com (mail-qt1-f178.google.com [209.85.160.178]) (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 4426327E04B; Tue, 1 Jul 2025 16:27:25 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.178 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751387247; cv=none; b=tHKlMfvUzssWjiRcfqnQlC8mGLOxJPtEMjyW31xvljWznpxhYt2jQywcMdC5Idw6BiEVjQm/FUXYtQL8HhS7LtZyS+Hmc69FsRm0TOWu8csNU5+WMQc93gJMWFNJsY1JbTC/RIUyPG4TkGOFOn9WoaXrbeseJe9wEzneqkHLJ0w= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1751387247; c=relaxed/simple; bh=jojRZnleqPCP2n75PqJ21Lf6xcs4Lt4lOIu2vTR83hw=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=VEeN6cgAmkFsJjcx7s1TOzO38xZXySuWYYr5mgTq1zfQvx/uuzpd5sr43y54sY1L3gnCLmKBF0b6ald75uYESPWjroJggHZQh3aJAEaNph3wmjqdmc0Z5yDsWiMTJsl6z1nqR6AUSsNwldEiC+RkHshfR2DUzYG4paCoXg+66b0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=ZJFUKZAd; arc=none smtp.client-ip=209.85.160.178 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="ZJFUKZAd" Received: by mail-qt1-f178.google.com with SMTP id d75a77b69052e-4a4323fe8caso22922041cf.2; Tue, 01 Jul 2025 09:27:25 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1751387244; x=1751992044; darn=vger.kernel.org; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:from:to:cc:subject:date:message-id :reply-to; bh=vRIP3sZ8XpmbMloGMu5iJhjGHLcDD0hWOMx3cgyxyPc=; b=ZJFUKZAdnNuxCbbKVfuuucUOi3npJmMGJxdbaRiM87nkkJy6SQRFv9l81HjVjLRVCI +6XYr8R6JGan+p2t0/v3oSusVWIx+rWUd0w9k1n++cKXDpgmvEY9RExdb8YuDtH1iXSo MUkCCDUaPVc+BzMXBftrDfnLjix+JAFayHpyWSRxuU9yrhEwyxyz1Fzi3BZ6/QOl26Fr 3vuH3YdBpNRyYAIjHO2N8o1iPdEETW/1GCpNsoO44QdmnBr8pyjKmHPBZiyNH5wZs9c4 FBwfJX8Owjj0jpe4u/qQL6cTbnee3s0N2UW8VXIwqft0McD5vVh2nrcGwDF7t1B08CbU EtEw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1751387244; x=1751992044; h=cc:to:in-reply-to:references:message-id:content-transfer-encoding :mime-version:subject:date:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=vRIP3sZ8XpmbMloGMu5iJhjGHLcDD0hWOMx3cgyxyPc=; b=VaECnEUrIzFFdbowiTJnxnAJrPxREaP2YEzYB/tA3/paXXCg+b08rkSMZev6vh4Zie rR9lMWfNCWx+GMZUxoKO9oGNAbHgJ9JqlzBKQl0mbZs9VsxFaAlvq25IWYC2fgGWvMn8 mrJlBH3rJVc5+O2GVz+Lc7Z0bgqY5BJMzN5evlemA1c7aoos+edafn20r6Z6wqkRpHFC rS54NfPnCNUvetEjBUUrpoMnE3B5kGFr/k5IfOxYne+6E0cz7l0m/r4imU3pUdXuhCI6 BeUx1wV4dqWaytai7NGebm6zy+y4S49mr+PTSp/80NsFLcOyRajKPIyymz+QSnrhI1iI xzig== X-Forwarded-Encrypted: i=1; AJvYcCWjeVGgf/zZ8KfEq32bfBzyGk+mqItbWSG8PZ7i1sNwZ3IHktWNx3bSluKIN0aCXdbvjHqbxqlvH+r6mr9N@vger.kernel.org, AJvYcCXMdHtjZy70O+Pgx3+NP+g8dwoeleTy4AxIrQDxg1F1Wri7KX7Zm4shzIWrs9ocs+tgFh+L7ZnuUAmRquWd@vger.kernel.org X-Gm-Message-State: AOJu0YzDpUjJUVnbswsF1RAzJbNA1L0xSJiZdTGJaW1tmp/U4U/NL+Bi hN77UDaL4u+zoKh3eIJFLX2DZjiCERKF7SxbaWMTeViyKTqH/WYjJdyk X-Gm-Gg: ASbGncsBAhVei25OsdYF2ldx6mi8U5Bih8COoV1xryA7Arwv+rC3UiwwqtW0O45GpKJ WRNTmxjFYaSAvCqr0a3bi9iI/eqPCyhB0hcD2qlaXduK17T4LvaGsENk50YUzGj1jGl6Y19YnD2 Yn/N2EqlpTUS9WpeGZptTF4QXkz+wJlU4kekD0rmGj3wukgoiPkwRYWXLny/Xbs6OYL8KgOalDe Y2DwFogABuUF+BSOLALzd8xR8ovnuei3SCmc72StmG12P0aDRtxW59jdOze/w4GxmpLSwFTRkgA HHHlm2+ILrununh/0IaIHt6Cb14lTURHB+shEU4Qv/FmYr5AJT0uc06Kg34VfrvY1ITns+1+7KI 7khZ92FIY4cJUb2BoASlMhxw1UqYkiUtG7EqgT5AqgXdNmA0rKJO8AWW9eOS3C8axpdSVxLaHFZ r4X8bq4RSA X-Google-Smtp-Source: AGHT+IFALn/cE/vWx+m2W5lf0bpYEA8//NXPUM50VPRZIeiX5E8TGmoTgjPWgyXQITETkjC81YWoTA== X-Received: by 2002:a05:622a:1c05:b0:4a6:f4ca:68e8 with SMTP id d75a77b69052e-4a82badaf1fmr74151131cf.48.1751387243727; Tue, 01 Jul 2025 09:27:23 -0700 (PDT) Received: from a.1.b.d.0.e.7.9.6.4.2.0.b.3.4.b.0.0.1.1.e.f.b.5.1.4.0.4.0.0.6.2.ip6.arpa ([2600:4041:5bfe:1100:70ac:5fd8:4c25:89ec]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-4a7fc57d530sm78032551cf.61.2025.07.01.09.27.22 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 01 Jul 2025 09:27:23 -0700 (PDT) From: Tamir Duberstein Date: Tue, 01 Jul 2025 12:27:19 -0400 Subject: [PATCH 3/3] rust: xarray: add `insert` and `reserve` Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250701-xarray-insert-reserve-v1-3-25df2b0d706a@gmail.com> References: <20250701-xarray-insert-reserve-v1-0-25df2b0d706a@gmail.com> In-Reply-To: <20250701-xarray-insert-reserve-v1-0-25df2b0d706a@gmail.com> To: Andreas Hindborg , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Danilo Krummrich , Matthew Wilcox , Andrew Morton Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, linux-fsdevel@vger.kernel.org, linux-mm@kvack.org, Daniel Almeida , Tamir Duberstein X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openssh-sha256; t=1751387238; l=20620; i=tamird@gmail.com; h=from:subject:message-id; bh=jojRZnleqPCP2n75PqJ21Lf6xcs4Lt4lOIu2vTR83hw=; b=U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAgtYz36g7iDMSkY5K7Ab51ksGX7hJgs MRt+XVZTrIzMVIAAAAGcGF0YXR0AAAAAAAAAAZzaGE1MTIAAABTAAAAC3NzaC1lZDI1NTE5AAAA QEm6abl0/rc2Wkc4pUld5Dv0UunpYl5G1hhRUdnQpXLh0zjbjmhp5GHrwTTSYm6V2hdNqgVulsF lNDGjcJfcuQE= X-Developer-Key: i=tamird@gmail.com; a=openssh; fpr=SHA256:264rPmnnrb+ERkS7DDS3tuwqcJss/zevJRzoylqMsbc Add `Guard::{insert,reserve}` and `Guard::{insert,reserve}_limit`, which are akin to `__xa_{alloc,insert}` in C. Note that unlike `xa_reserve` which only ensures that memory is allocated, the semantics of `Reservation` are stricter and require precise management of the reservation. Indices which have been reserved can still be overwritten with `Guard::store`, which allows for C-like semantics if desired. `__xa_cmpxchg_raw` is exported to facilitate the semantics described above. Signed-off-by: Tamir Duberstein Reviewed-by: Janne Grunau Tested-by: Janne Grunau --- include/linux/xarray.h | 2 + lib/xarray.c | 28 +++- rust/helpers/xarray.c | 5 + rust/kernel/xarray.rs | 419 +++++++++++++++++++++++++++++++++++++++++++++= +++- 4 files changed, 447 insertions(+), 7 deletions(-) diff --git a/include/linux/xarray.h b/include/linux/xarray.h index be850174e802..64f2a5e06ceb 100644 --- a/include/linux/xarray.h +++ b/include/linux/xarray.h @@ -563,6 +563,8 @@ void *__xa_erase(struct xarray *, unsigned long index); void *__xa_store(struct xarray *, unsigned long index, void *entry, gfp_t); void *__xa_cmpxchg(struct xarray *, unsigned long index, void *old, void *entry, gfp_t); +void *__xa_cmpxchg_raw(struct xarray *, unsigned long index, void *old, + void *entry, gfp_t); int __must_check __xa_insert(struct xarray *, unsigned long index, void *entry, gfp_t); int __must_check __xa_alloc(struct xarray *, u32 *id, void *entry, diff --git a/lib/xarray.c b/lib/xarray.c index 76dde3a1cacf..58202b6fbb59 100644 --- a/lib/xarray.c +++ b/lib/xarray.c @@ -1738,9 +1738,6 @@ void *xa_store(struct xarray *xa, unsigned long index= , void *entry, gfp_t gfp) } EXPORT_SYMBOL(xa_store); =20 -static inline void *__xa_cmpxchg_raw(struct xarray *xa, unsigned long inde= x, - void *old, void *entry, gfp_t gfp); - /** * __xa_cmpxchg() - Conditionally replace an entry in the XArray. * @xa: XArray. @@ -1767,7 +1764,29 @@ void *__xa_cmpxchg(struct xarray *xa, unsigned long = index, } EXPORT_SYMBOL(__xa_cmpxchg); =20 -static inline void *__xa_cmpxchg_raw(struct xarray *xa, unsigned long inde= x, +/** + * __xa_cmpxchg_raw() - Conditionally replace an entry in the XArray. + * @xa: XArray. + * @index: Index into array. + * @old: Old value to test against. + * @entry: New value to place in array. + * @gfp: Memory allocation flags. + * + * You must already be holding the xa_lock when calling this function. + * It will drop the lock if needed to allocate memory, and then reacquire + * it afterwards. + * + * If the entry at @index is the same as @old, replace it with @entry. + * If the return value is equal to @old, then the exchange was successful. + * + * This function is the same as __xa_cmpxchg() except that it does not coe= rce + * XA_ZERO_ENTRY to NULL on egress. + * + * Context: Any context. Expects xa_lock to be held on entry. May + * release and reacquire xa_lock if @gfp flags permit. + * Return: The old value at this index or xa_err() if an error happened. + */ +void *__xa_cmpxchg_raw(struct xarray *xa, unsigned long index, void *old, void *entry, gfp_t gfp) { XA_STATE(xas, xa, index); @@ -1787,6 +1806,7 @@ static inline void *__xa_cmpxchg_raw(struct xarray *x= a, unsigned long index, =20 return xas_result(&xas, curr); } +EXPORT_SYMBOL(__xa_cmpxchg_raw); =20 /** * __xa_insert() - Store this entry in the XArray if no entry is present. diff --git a/rust/helpers/xarray.c b/rust/helpers/xarray.c index 60b299f11451..b6c078e6a343 100644 --- a/rust/helpers/xarray.c +++ b/rust/helpers/xarray.c @@ -2,6 +2,11 @@ =20 #include =20 +void *rust_helper_xa_zero_entry(void) +{ + return XA_ZERO_ENTRY; +} + int rust_helper_xa_err(void *entry) { return xa_err(entry); diff --git a/rust/kernel/xarray.rs b/rust/kernel/xarray.rs index bbce54ec695c..87fa3259cdd7 100644 --- a/rust/kernel/xarray.rs +++ b/rust/kernel/xarray.rs @@ -9,7 +9,12 @@ prelude::*, types::{ForeignOwnable, NotThreadSafe, Opaque}, }; -use core::{iter, marker::PhantomData, mem, ptr::NonNull}; +use core::{ + fmt, iter, + marker::PhantomData, + mem, ops, + ptr::{null_mut, NonNull}, +}; =20 /// An array which efficiently maps sparse integer indices to owned object= s. /// @@ -126,6 +131,19 @@ fn iter(&self) -> impl Iterator> + '_ { .map_while(|ptr| NonNull::new(ptr.cast())) } =20 + fn with_guard(&self, guard: Option<&mut Guard<'_, T>>, f: F) -> U + where + F: FnOnce(&mut Guard<'_, T>) -> U, + { + match guard { + None =3D> f(&mut self.lock()), + Some(guard) =3D> { + assert_eq!(guard.xa.xa.get(), self.xa.get()); + f(guard) + } + } + } + /// Attempts to lock the [`XArray`] for exclusive access. pub fn try_lock(&self) -> Option> { // SAFETY: `self.xa` is always valid by the type invariant. @@ -172,6 +190,7 @@ fn drop(&mut self) { /// The error returned by [`store`](Guard::store). /// /// Contains the underlying error and the value that was not stored. +#[derive(Debug)] pub struct StoreError { /// The error that occurred. pub error: Error, @@ -185,6 +204,11 @@ fn from(value: StoreError) -> Self { } } =20 +fn to_usize(i: u32) -> usize { + i.try_into() + .unwrap_or_else(|_| build_error!("cannot convert u32 to usize")) +} + impl<'a, T: ForeignOwnable> Guard<'a, T> { fn load(&self, index: usize, f: F) -> Option where @@ -219,7 +243,7 @@ pub fn remove(&mut self, index: usize) -> Option { // - The caller holds the lock. let ptr =3D unsafe { bindings::__xa_erase(self.xa.xa.get(), index)= }.cast(); // SAFETY: - // - `ptr` is either NULL or came from `T::into_foreign`. + // - `ptr` is either `NULL` or came from `T::into_foreign`. // - `&mut self` guarantees that the lifetimes of [`T::Borrowed`] = and [`T::BorrowedMut`] // borrowed from `self` have ended. unsafe { T::try_from_foreign(ptr) } @@ -267,13 +291,272 @@ pub fn store( }) } else { let old =3D old.cast(); - // SAFETY: `ptr` is either NULL or came from `T::into_foreign`. + // SAFETY: `ptr` is either `NULL` or came from `T::into_foreig= n`. // // NB: `XA_ZERO_ENTRY` is never returned by functions belongin= g to the Normal XArray // API; such entries present as `NULL`. Ok(unsafe { T::try_from_foreign(old) }) } } + + /// Stores an element at the given index if no entry is present. + /// + /// May drop the lock if needed to allocate memory, and then reacquire= it afterwards. + /// + /// On failure, returns the element which was attempted to be stored. + pub fn insert( + &mut self, + index: usize, + value: T, + gfp: alloc::Flags, + ) -> Result<(), StoreError> { + build_assert!( + mem::align_of::() >=3D 4, + "pointers stored in XArray must be 4-byte aligned" + ); + let ptr =3D value.into_foreign(); + // SAFETY: `self.xa` is always valid by the type invariant. + // + // INVARIANT: `ptr` came from `T::into_foreign`. + match unsafe { bindings::__xa_insert(self.xa.xa.get(), index, ptr.= cast(), gfp.as_raw()) } { + 0 =3D> Ok(()), + errno =3D> { + // SAFETY: `ptr` came from `T::into_foreign` and `__xa_ins= ert` does not take + // ownership of the value on error. + let value =3D unsafe { T::from_foreign(ptr) }; + Err(StoreError { + value, + error: Error::from_errno(errno), + }) + } + } + } + + /// Wrapper around `__xa_alloc`. + /// + /// On success, takes ownership of pointers passed in `op`. + /// + /// On failure, ownership returns to the caller. + /// + /// # Safety + /// + /// `ptr` must be `NULL` or have come from a previous call to `T::into= _foreign`. + unsafe fn alloc( + &mut self, + limit: impl ops::RangeBounds, + ptr: *mut T::PointedTo, + gfp: alloc::Flags, + ) -> Result { + // NB: `xa_limit::{max,min}` are inclusive. + let limit =3D bindings::xa_limit { + max: match limit.end_bound() { + ops::Bound::Included(&end) =3D> end, + ops::Bound::Excluded(&end) =3D> end - 1, + ops::Bound::Unbounded =3D> u32::MAX, + }, + min: match limit.start_bound() { + ops::Bound::Included(&start) =3D> start, + ops::Bound::Excluded(&start) =3D> start + 1, + ops::Bound::Unbounded =3D> 0, + }, + }; + + let mut index =3D u32::MAX; + + // SAFETY: + // - `self.xa` is always valid by the type invariant. + // - `self.xa` was initialized with `XA_FLAGS_ALLOC` or `XA_FLAGS_= ALLOC1`. + // + // INVARIANT: `ptr` is either `NULL` or came from `T::into_foreign= `. + match unsafe { + bindings::__xa_alloc( + self.xa.xa.get(), + &mut index, + ptr.cast(), + limit, + gfp.as_raw(), + ) + } { + 0 =3D> Ok(to_usize(index)), + errno =3D> Err(Error::from_errno(errno)), + } + } + + /// Allocates an entry somewhere in the array. + /// + /// On success, returns the index at which the entry was stored. + /// + /// On failure, returns the entry which was attempted to be stored. + pub fn insert_limit( + &mut self, + limit: impl ops::RangeBounds, + value: T, + gfp: alloc::Flags, + ) -> Result> { + build_assert!( + mem::align_of::() >=3D 4, + "pointers stored in XArray must be 4-byte aligned" + ); + let ptr =3D value.into_foreign(); + // SAFETY: `ptr` came from `T::into_foreign`. + unsafe { self.alloc(limit, ptr, gfp) }.map_err(|error| { + // SAFETY: `ptr` came from `T::into_foreign` and `self.alloc` = does not take ownership of + // the value on error. + let value =3D unsafe { T::from_foreign(ptr) }; + StoreError { value, error } + }) + } + + /// Reserves an entry in the array. + pub fn reserve(&mut self, index: usize, gfp: alloc::Flags) -> Result> { + // NB: `__xa_insert` internally coerces `NULL` to `XA_ZERO_ENTRY` = on ingress. + let ptr =3D null_mut(); + // SAFETY: `self.xa` is always valid by the type invariant. + // + // INVARIANT: `ptr` is `NULL`. + match unsafe { bindings::__xa_insert(self.xa.xa.get(), index, ptr,= gfp.as_raw()) } { + 0 =3D> Ok(Reservation { xa: self.xa, index }), + errno =3D> Err(Error::from_errno(errno)), + } + } + + /// Reserves an entry somewhere in the array. + pub fn reserve_limit( + &mut self, + limit: impl ops::RangeBounds, + gfp: alloc::Flags, + ) -> Result> { + // NB: `__xa_alloc` internally coerces `NULL` to `XA_ZERO_ENTRY` o= n ingress. + let ptr =3D null_mut(); + // SAFETY: `ptr` is `NULL`. + unsafe { self.alloc(limit, ptr, gfp) }.map(|index| Reservation { x= a: self.xa, index }) + } +} + +/// A reserved slot in an array. +/// +/// The slot is released when the reservation goes out of scope. +/// +/// Note that the array lock *must not* be held when the reservation is fi= lled or dropped as this +/// will lead to deadlock. [`Reservation::fill_locked`] and [`Reservation:= :release_locked`] can be +/// used in context where the array lock is held. +#[must_use =3D "the reservation is released immediately when the reservati= on is unused"] +pub struct Reservation<'a, T: ForeignOwnable> { + xa: &'a XArray, + index: usize, +} + +impl fmt::Debug for Reservation<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Reservation") + .field("index", &self.index()) + .finish() + } +} + +impl Reservation<'_, T> { + /// Returns the index of the reservation. + pub fn index(&self) -> usize { + self.index + } + + /// Replaces the reserved entry with the given entry. + /// + /// # Safety + /// + /// `ptr` must be `NULL` or have come from a previous call to `T::into= _foreign`. + unsafe fn replace(guard: &mut Guard<'_, T>, index: usize, ptr: *mut T:= :PointedTo) -> Result { + // SAFETY: `xa_zero_entry` wraps `XA_ZERO_ENTRY` which is always s= afe to use. + let old =3D unsafe { bindings::xa_zero_entry() }; + + // NB: `__xa_cmpxchg_raw` is used over `__xa_cmpxchg` because the = latter coerces + // `XA_ZERO_ENTRY` to `NULL` on egress, which would prevent us fro= m determining whether a + // replacement was made. + // + // SAFETY: `self.xa` is always valid by the type invariant. + // + // INVARIANT: `ptr` is either `NULL` or came from `T::into_foreign= ` and `old` is + // `XA_ZERO_ENTRY`. + let ret =3D + unsafe { bindings::__xa_cmpxchg_raw(guard.xa.xa.get(), index, = old, ptr.cast(), 0) }; + + // SAFETY: `__xa_cmpxchg_raw` returns the old entry at this index = on success or `xa_err` if + // an error happened. + match unsafe { bindings::xa_err(ret) } { + 0 =3D> { + if ret =3D=3D old { + Ok(()) + } else { + Err(EBUSY) + } + } + errno =3D> Err(Error::from_errno(errno)), + } + } + + fn fill_inner(&self, guard: Option<&mut Guard<'_, T>>, value: T) -> Re= sult<(), StoreError> { + let Self { xa, index } =3D self; + let index =3D *index; + + let ptr =3D value.into_foreign(); + xa.with_guard(guard, |guard| { + // SAFETY: `ptr` came from `T::into_foreign`. + unsafe { Self::replace(guard, index, ptr) } + }) + .map_err(|error| { + // SAFETY: `ptr` came from `T::into_foreign` and `Self::replac= e` does not take ownership + // of the value on error. + let value =3D unsafe { T::from_foreign(ptr) }; + StoreError { value, error } + }) + } + + /// Fills the reservation. + pub fn fill(self, value: T) -> Result<(), StoreError> { + let result =3D self.fill_inner(None, value); + mem::forget(self); + result + } + + /// Fills the reservation without acquiring the array lock. + /// + /// # Panics + /// + /// Panics if the passed guard locks a different array. + pub fn fill_locked(self, guard: &mut Guard<'_, T>, value: T) -> Result= <(), StoreError> { + let result =3D self.fill_inner(Some(guard), value); + mem::forget(self); + result + } + + fn release_inner(&self, guard: Option<&mut Guard<'_, T>>) -> Result { + let Self { xa, index } =3D self; + let index =3D *index; + + xa.with_guard(guard, |guard| { + let ptr =3D null_mut(); + // SAFETY: `ptr` is `NULL`. + unsafe { Self::replace(guard, index, ptr) } + }) + } + + /// Releases the reservation without acquiring the array lock. + /// + /// # Panics + /// + /// Panics if the passed guard locks a different array. + pub fn release_locked(self, guard: &mut Guard<'_, T>) -> Result { + let result =3D self.release_inner(Some(guard)); + mem::forget(self); + result + } +} + +impl Drop for Reservation<'_, T> { + fn drop(&mut self) { + // NB: Errors here are possible since `Guard::store` does not hono= r reservations. + let _: Result =3D self.release_inner(None); + } } =20 // SAFETY: `XArray` has no shared mutable state so it is `Send` iff `T`= is `Send`. @@ -282,3 +565,133 @@ unsafe impl Send for XArray= {} // SAFETY: `XArray` serialises the interior mutability it provides so i= t is `Sync` iff `T` is // `Send`. unsafe impl Sync for XArray {} + +#[macros::kunit_tests(rust_xarray_kunit)] +mod tests { + use super::*; + use pin_init::stack_pin_init; + + fn new_kbox(value: T) -> Result> { + KBox::new(value, GFP_KERNEL).map_err(Into::into) + } + + #[test] + fn test_alloc_kind_alloc() -> Result { + test_alloc_kind(AllocKind::Alloc, 0) + } + + #[test] + fn test_alloc_kind_alloc1() -> Result { + test_alloc_kind(AllocKind::Alloc1, 1) + } + + fn test_alloc_kind(kind: AllocKind, expected_index: usize) -> Result { + stack_pin_init!(let xa =3D XArray::new(kind)); + let mut guard =3D xa.lock(); + + let reservation =3D guard.reserve_limit(.., GFP_KERNEL)?; + assert_eq!(reservation.index(), expected_index); + reservation.release_locked(&mut guard)?; + + let insertion =3D guard.insert_limit(.., new_kbox(0x1337)?, GFP_KE= RNEL); + assert!(insertion.is_ok()); + let insertion_index =3D insertion.unwrap(); + assert_eq!(insertion_index, expected_index); + + Ok(()) + } + + const IDX: usize =3D 0x1337; + + fn insert(guard: &mut Guard<'_, T>, value: T) -> Re= sult<(), StoreError> { + guard.insert(IDX, value, GFP_KERNEL) + } + + fn reserve<'a, T: ForeignOwnable>(guard: &mut Guard<'a, T>) -> Result<= Reservation<'a, T>> { + guard.reserve(IDX, GFP_KERNEL) + } + + #[track_caller] + fn check_not_vacant<'a>(guard: &mut Guard<'a, KBox>) -> Result { + // Insertion fails. + { + let beef =3D new_kbox(0xbeef)?; + let ret =3D insert(guard, beef); + assert!(ret.is_err()); + let StoreError { error, value } =3D ret.unwrap_err(); + assert_eq!(error, EBUSY); + assert_eq!(*value, 0xbeef); + } + + // Reservation fails. + { + let ret =3D reserve(guard); + assert!(ret.is_err()); + assert_eq!(ret.unwrap_err(), EBUSY); + } + + Ok(()) + } + + #[test] + fn test_insert_and_reserve_interaction() -> Result { + stack_pin_init!(let xa =3D XArray::new(Default::default())); + let mut guard =3D xa.lock(); + + // Vacant. + assert_eq!(guard.get(IDX), None); + + // Reservation succeeds. + let reservation =3D { + let ret =3D reserve(&mut guard); + assert!(ret.is_ok()); + ret.unwrap() + }; + + // Reserved presents as vacant. + assert_eq!(guard.get(IDX), None); + + check_not_vacant(&mut guard)?; + + // Release reservation. + { + let ret =3D reservation.release_locked(&mut guard); + assert!(ret.is_ok()); + let () =3D ret.unwrap(); + } + + // Vacant again. + assert_eq!(guard.get(IDX), None); + + // Insert succeeds. + { + let dead =3D new_kbox(0xdead)?; + let ret =3D insert(&mut guard, dead); + assert!(ret.is_ok()); + let () =3D ret.unwrap(); + } + + check_not_vacant(&mut guard)?; + + // Remove. + assert_eq!(guard.remove(IDX).as_deref(), Some(&0xdead)); + + // Reserve and fill. + { + let beef =3D new_kbox(0xbeef)?; + let ret =3D reserve(&mut guard); + assert!(ret.is_ok()); + let reservation =3D ret.unwrap(); + let ret =3D reservation.fill_locked(&mut guard, beef); + assert!(ret.is_ok()); + let () =3D ret.unwrap(); + }; + + check_not_vacant(&mut guard)?; + + // Remove. + assert_eq!(guard.remove(IDX).as_deref(), Some(&0xbeef)); + + Ok(()) + } +} --=20 2.50.0