From nobody Wed Dec 17 08:51:13 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (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 430A22550B6 for ; Fri, 2 May 2025 13:19:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191985; cv=none; b=Db/mlyw53Du0HzQ1NBnI6LFCpKnXHBbwiLDOY+0jr29VLmqAr8lE1vH+ldtnxF0NuQHHsjV0nO5fhHm3cwH8dCm0dRWBa/n3ovtaBoBxDuO2hmED3akaBro3nL3KWJyqwvap5DA+oUfCN344QFImLg0GI1fGklxyJwdk6XxrID4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191985; c=relaxed/simple; bh=Lj+81o/3csbNz20I8Z+JfMBxmhdfE+7rQlFxU0lvpD0=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=ewGYzrMcKEb5zhxpKGVccUjZeklJsjp1tzfXN8uqbww1hBUtlmRWUVEd7xui2ZfiR2y8jMEl/36Fzj+yy+wyR7iYcrhZGVv3W4ShfFj/mmfTYujFArcpU7sW5x+Yj2/fAWWAkekYZfdBdyJfRjbWAEg2zMkalPpwmpbFne97HJ0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=AK6bDmV5; arc=none smtp.client-ip=209.85.128.73 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--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="AK6bDmV5" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43d733063cdso14481955e9.0 for ; Fri, 02 May 2025 06:19:42 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746191981; x=1746796781; 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=QQ3LimRO6FsoGl/TxK5K9OWXXlaU4y1qIyjhkeclqLI=; b=AK6bDmV5x8sAyJCCGWbBwGaQzTDjOQfAfMnuE2G1RG5dgZMOSx5wjPBguWmneKwBps crRyB50kRIXaYGsbu9zpkUFuzbPJwge8+N10xdMKnJD1oHHyxpaJica0aBr/r5D/Bvru XeT/cF05wdWx6REpVIhrl5RODzoDA/H6Rm8EuFX2Pz5HEzgzci/aNxPWqEvNRn5Dnz2H vS56YUqFu+QTTUL9SQ6cTESpYoPYm1Q4VaFwsvOmoGby8JSCox2W6EOYsPPYN6AWDbma tvGGenNW1IT0PPFQyDpsInjcbBFIqCjNsz6E09bbn6u+sTM/F/YNH85BU2iTqBP0DrC5 NNOA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746191981; x=1746796781; 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=QQ3LimRO6FsoGl/TxK5K9OWXXlaU4y1qIyjhkeclqLI=; b=WS6hL2Qp7kEbF5FOzWbj5aFQXGuJpw2Fb/OaYCErGBAmLjZKkckA1sRon0pTar5tVs LRbNUeukDniDGiVMTo74FmPqHE2lrYBGm6QdXlbHvr5qFtBfDNUSoHYj/3alsoVNRAVz c8pODtnQTI9IDMBmC6mLMGIXdUskoERfArvbisERZ6NHGJbDDh4cstuBhe2Pkz4Sy+S7 +sCqjkD9I4JWtS5tWNJ+7jKhaKJ35VKO96YRu5PkPbOTkhWBCzYfDlalVmL/+5N1OMdY 3yBkyY7jEqTDOxP1Q7/HhhjP+xkWdorhKqFrBcMR7K9eKA+tCpDc6Ci4ttkZ1K9whFYy LDug== X-Forwarded-Encrypted: i=1; AJvYcCWYK1bv365s8fPcs/nLKQfKOyR5nCf95J+QZFCeCBVT3brGz3tSBsE4cWM3/35hC3PHoqpJBrFuIzE7ZtM=@vger.kernel.org X-Gm-Message-State: AOJu0YwE5nvscA0pcGtbxOLuJzQZQHtZwL6Dq3QLPQ6dMOTbQSUa/+vH fnR34T27e+wN1Uv3th2F4JLsrgZv+/s2NO7g51WqgcoQAbxbu6C+ak8x3xhrgYmdvRLPwkI+FbG 7sChBPgjRAOvlVQ== X-Google-Smtp-Source: AGHT+IGFdLxIF2zFjzp9LDv0cq99M5Jj0pCAd48e2NBY0712BBTsbQDGWWrFm4DO8buY1w5pxldAL+U+ywHFRGA= X-Received: from wmbem21.prod.google.com ([2002:a05:600c:8215:b0:440:67d1:757b]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:5288:b0:441:b00d:e9d1 with SMTP id 5b1f17b1804b1-441bbea13c3mr27862595e9.2.1746191981786; Fri, 02 May 2025 06:19:41 -0700 (PDT) Date: Fri, 02 May 2025 13:19:29 +0000 In-Reply-To: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=1339; i=aliceryhl@google.com; h=from:subject:message-id; bh=Lj+81o/3csbNz20I8Z+JfMBxmhdfE+7rQlFxU0lvpD0=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoFMZoZsjjKw2dZC0jGRfcHEFHuq451GUXXmglq M7JCDXrafCJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaBTGaAAKCRAEWL7uWMY5 Rtm3EACMt/dY7679lCwQO5pRx93Tr8/Tblk/48CQMTtgxoULO2h0Ys8lbwNvYWb4Hu8iTcw+Fvi AdoHkrVZ5SDVMhUZaBquid58qkpeLY3jF7x5+1ucwuLGg4MvkPwSc/H16dAvWsn1iZ4kbgUgdMy xxJ8BkZk6/opyo1cViB+C53NyJmKhwlGQ27SpYZcQPUdsp9nidxj6TP2XGHqebiNCv3LfaMAZtN +6Zz7IyzqtUBGUNs6Mo8hdhvdbo3jHDiNfFiT+Py61ERjLTfNNa4/fftNYbwaYwEad33vkHCKLC yL7MP5OtHqx4KikIFYNr8MbSHsmCzH+c3bTbVBPTJszmgKt5olRKP/IAhPRcQlRMlQp3riokLJZ Fs3Q4772xKrBXrmxpuaC19UXVCJXD0XvaQdM6nw+e9yqIHY8dkVs/6rMpHbulSIepl34jKnBHRT lJaeJOZ35T+22/8b5VDHhJLy7kIXT6u+x8JO1/S3cCWCeaRfX5RsrbYYcs0G/cTUiA+Wdfh1AaX hjBEIVmpcPYVMNUiof/HCQ0SXuQe1IigIOe3Le8+C/ZncEbQL6pQ/33KkvoY1ndiV/5cj4ogL8L R7oSHo2Q/mI0HQ0+mMZKkUloWPf5yZmZevxE4VewfQp7IkzJoLiUEmcR4BnYHihR4wzTxqPaNRS Ozr4YSVWoD+XfJg== X-Mailer: b4 0.14.2 Message-ID: <20250502-vec-methods-v5-1-06d20ad9366f@google.com> Subject: [PATCH v5 1/7] rust: alloc: add Vec::clear From: Alice Ryhl To: Danilo Krummrich Cc: Matthew Maurer , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl , Benno Lossin , Tamir Duberstein Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Our custom Vec type is missing the stdlib method `clear`, thus add it. It will be used in the miscdevice sample. Reviewed-by: Benno Lossin Reviewed-by: Tamir Duberstein Signed-off-by: Alice Ryhl Reviewed-by: Greg Kroah-Hartman --- rust/kernel/alloc/kvec.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 5798e2c890a2140a12303706578ffa2a85423167..412a2fe3ce79a0681175bf358e8= e0f628e77e875 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -413,6 +413,26 @@ pub fn into_raw_parts(self) -> (*mut T, usize, usize) { (ptr, len, capacity) } =20 + /// Clears the vector, removing all values. + /// + /// Note that this method has no effect on the allocated capacity + /// of the vector. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D kernel::kvec![1, 2, 3]?; + /// + /// v.clear(); + /// + /// assert!(v.is_empty()); + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + pub fn clear(&mut self) { + self.truncate(0); + } + /// Ensures that the capacity exceeds the length by at least `addition= al` elements. /// /// # Examples --=20 2.49.0.967.g6a0df3ecc3-goog From nobody Wed Dec 17 08:51:13 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (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 2BA70255233 for ; Fri, 2 May 2025 13:19:45 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191986; cv=none; b=H7YNP2qZvj4pMQc+K/MvAtRiZ12ZIcr5t2p+42bTO/u9l56taFDoalABUrkrQmjUTAlLl3YQEbjBVkUhhOb0RZpUwZ5v22USWM1cKsAJJWzU1G1DF/Sn+/ZehLHha+ZKaNRSIvz43GvZbDWeJnx7w0if3CA+Z6MDmFurSGLugkw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191986; c=relaxed/simple; bh=zedv0Ud5AXr6VBmDd8zA+6r8ej92u1QpNNcD/1j6Igg=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=HGtAywx5Xm8HiP5UC5K+K3jfRwuNvCjVD1AYbTfyHVEU76nHapnI3mbJMQR42xWRSMSGHoDXHghOnX3UG1Dyd+Q5zbQpr5WwNzuUfqvFNM/fDWO+qI+EnT/46bLGbwznDw9pXspKt23ss9+Qhhz9w3ulV1KU4zaZOBxZBw+6QTY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=ebGt8LWT; arc=none smtp.client-ip=209.85.128.74 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--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="ebGt8LWT" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43d01024089so12513245e9.1 for ; Fri, 02 May 2025 06:19:44 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746191983; x=1746796783; 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=+L34cKVl/QWezEuUTAS3yiE8vFcujdL77woAc6rzSjw=; b=ebGt8LWTAfx/NeAJKg7GwbapU6S1Q/fdMmdqmeSxAKGfpjrSAxCXL1Z61zWEDyN5uJ LBdWmUqB5RS2VFObhzSUZJQqImB8bUJrB6UjHzHp6Js2hya8Xp+hamoXWI0UG1On32tE FjBKok6uzsX8sVYCmgpPU8SxRN5QsWdHCvAcHAK0xIe2oO/xuFWWBUSuzqe+Ne+yCVSL Se913SSNZm9IJTA87tDkNQdkkSDgmu7jbI1HCtjAHGeNXm3BFvyPMHcRrfo1tsxcUwGe 3NdUfA8Tn0favvWBPOPdRwxcSkYZU9BC8CdDHRC3xumKXzo56QxAecuxiKDDI/8BBA+b rxHA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746191983; x=1746796783; 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=+L34cKVl/QWezEuUTAS3yiE8vFcujdL77woAc6rzSjw=; b=vG+bbFJMHOwySOjs9Q/csIYtoMI3BcwXDIPRdfJjeSzvZ890vu62SjuIAPqndLYgBQ vmP+vJF/Lvv7T+F5bis9hlB7bKYTYwFi8hMerGd3s5w72zhH6/i8TH2uVfkJ/RPwIiWc aM6FcW3yqfPJHAm1nBTiwlN/7JGfHYFuCgq+EONV+9YLd6LdLBLRlFUL6vQRe6Y/tRfv a+5Gp0ni7ojnsQtekldjzCYqvuJSK5aRjgCqGI5lYV4SSLKi7JdrWRGSltp3BdmU3dZb pqnPOd5ucuSDWPQAnIuo7gKBD8oEnCHYSIiTeOBLlQ+Z0qEBCFzTF0DCKWxP58wpv5jt iDow== X-Forwarded-Encrypted: i=1; AJvYcCV+zX8WwPzNvFFGpEvWTUxoZMPquefSMyl2gMk0kEQdnX1/6CdhA2somMscG9pUwZNki0b1zRWheuUY/F8=@vger.kernel.org X-Gm-Message-State: AOJu0YzvqhGvix+l8UzCXg6g1jYMggXRacwSx3YoF/UH1BeALSPZHHV1 9PbJyUtm4l3/gqOuJi6W9JAA4SH847yK8UuIvCXzZQjKqwfCJ/OkHvYa9eSbFjmPtLUnHjJVYNy 1rS5Hip3F8S4pVw== X-Google-Smtp-Source: AGHT+IEuKQNKvecGdhwHBbYCN97yW+PFD8r7ZBIumcauLOIO27gV4LIw4vjXZi46OZNwh2XT0C1pG7y6e/XwrNU= X-Received: from wmpz12.prod.google.com ([2002:a05:600c:a0c:b0:43c:fd99:1b7e]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1e88:b0:43c:fd72:f039 with SMTP id 5b1f17b1804b1-441bbeb3813mr22539795e9.11.1746191983770; Fri, 02 May 2025 06:19:43 -0700 (PDT) Date: Fri, 02 May 2025 13:19:30 +0000 In-Reply-To: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=1873; i=aliceryhl@google.com; h=from:subject:message-id; bh=zedv0Ud5AXr6VBmDd8zA+6r8ej92u1QpNNcD/1j6Igg=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoFMZo1RXcw8Sq8mWMOC1GnKtfjkg4D0uDr8nSO nY7OzkiZUWJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaBTGaAAKCRAEWL7uWMY5 RogXD/9KcwpDA3U5qoXW3BvFp4l3F1NrKDrLmMpvC3d69DwgcJx8IkHKhEeF7sv0xVwtrcvKmoS kzhPcQaO99mHFQeCEguPQgcabMjbGx5jyihq689LgYe3EzQNbjdRrxnWYb/dN81hREAj7C66s2j lVQXSt4e2a4jnlFe1IzAKFymyLNLF9ZqLim7ETRQruETTBbpgGQ3pwU77p+C2XdZ6lPNXttyfsx My1PyJQ/HgsWTyhjvxNOmmbeFMkozhG+/aZhs0yHkrlwWfPN+SUoiYBVtcEcfD9A90TxN9SSyVs KQL/0IX9zHDTwPlLWCmJp+N06YRg/kM4JGT5WSsuOWOD099f0jE/xSUICCmnTaExjb6A4aP+12e BFqG2FeZvgnTakHme8crge+PG9O/U/hPnQbOjAFVsNfY17+esW6XBCzbtlyP0aMGfL0AZikLY+Z YPB7S8+Xuxq0Tlr69XSJkEOxMo4HT4UkXML8tLAmo1Ee8la4ChtDQPPmxXAinyfymu3YCBWRTzX oKimKE2FcKkUQzhwEu0euCDgfaU3HiU/j3RN7XaBiJ/AUeKTKMik6mPRQ0n+oaUC79QVtmAcJQ6 jzElr6EyTgYQcABI7Q/aMqZbVkyiiRhIqrPFzKIgM/zibPsbfP4QwfF+ktWrLw7T3ajcNYz3D/Q dW+EZ9lfvvChORw== X-Mailer: b4 0.14.2 Message-ID: <20250502-vec-methods-v5-2-06d20ad9366f@google.com> Subject: [PATCH v5 2/7] rust: alloc: add Vec::pop From: Alice Ryhl To: Danilo Krummrich Cc: Matthew Maurer , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This introduces a basic method that our custom Vec is missing. I expect that it will be used in many places, but at the time of writing, Rust Binder has six calls to Vec::pop. Signed-off-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Greg Kroah-Hartman --- rust/kernel/alloc/kvec.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 412a2fe3ce79a0681175bf358e8e0f628e77e875..ebca0cfd31c67f3ce13c4825d70= 39e34bb54f4d4 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -320,6 +320,37 @@ pub fn push(&mut self, v: T, flags: Flags) -> Result<(= ), AllocError> { Ok(()) } =20 + /// Removes the last element from a vector and returns it, or `None` i= f it is empty. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// v.push(2, GFP_KERNEL)?; + /// assert_eq!(&v, &[1, 2]); + /// + /// assert_eq!(v.pop(), Some(2)); + /// assert_eq!(v.pop(), Some(1)); + /// assert_eq!(v.pop(), None); + /// # Ok::<(), Error>(()) + /// ``` + pub fn pop(&mut self) -> Option { + if self.is_empty() { + return None; + } + + let removed: *mut T =3D { + // SAFETY: We just checked that the length is at least one. + let slice =3D unsafe { self.dec_len(1) }; + // SAFETY: The argument to `dec_len` was 1 so this returns a s= lice of length 1. + unsafe { slice.get_unchecked_mut(0) } + }; + + // SAFETY: The guarantees of `dec_len` allow us to take ownership = of this value. + Some(unsafe { removed.read() }) + } + /// Creates a new [`Vec`] instance with at least the given capacity. /// /// # Examples --=20 2.49.0.967.g6a0df3ecc3-goog From nobody Wed Dec 17 08:51:13 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (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 33ED4255E4D for ; Fri, 2 May 2025 13:19:47 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191989; cv=none; b=kRExF6FU/4GyL/oFRl8SE+vKkPp4U9f64Ne1katvvKIj1ioLhkLJEc7q1JN7ctXVHx8Q3Vck4JTwq3BMjaXqPoFhvDqbq52pHt//GOf+omya+R9UQoOXviRLqI0V/T9sUdwAyCsuR392m6jBV61Y1o84bBiYvAGhlliaHJij/YY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191989; c=relaxed/simple; bh=+Q2XjTWHwCfoLlwubHIATQqjUcgilGTTvVMpLQ5kNoY=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=t4OrT0FAwcdJ4Rn53Jhp51B7HnDFqglAcvbq/pXmm4WbqN6qibx2cqdjZm1/ErL05dH0mdeU9XIkKBXHlVvbKx1XOh+jlFjujqs6ClnexYEg9JrDTiN/sHatfRwlwi1/443CE/iDO7WaRZUB87eshVM33RGr4pMNhzjaotSGmpU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=0snNOZMU; arc=none smtp.client-ip=209.85.128.74 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--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="0snNOZMU" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43cf172ff63so8794435e9.3 for ; Fri, 02 May 2025 06:19:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746191985; x=1746796785; 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=bbk+dXSasxE2+5UsRYscIfb+Bcs8iWgnzx9jGxiqBZA=; b=0snNOZMUSR+S340iGjfcIa47PYELp/TinZZ+H8lQZGB9ubGyS4LgbvW6BhIf2MafcD 3mFIGskqtdPs9hT7tAQRepflsRBdKXSQEg6GGQJiyIJg/UVexAL+g6dtWE9OK3UHPukB d1eo+O3goySIr6jLxxi6f9t8fgeQEcZRZ9PU7dsCoyNbPV52bUtX+BA4qVi7RvdwwO2i XU3WhzYl5JbhF+VD38z6mYTOsNC5sCVhpnNHaKVXkEPNd6alhMcU+lxThaO+TXXAlb+o xIKWh40JQBYSvzNDfPojCxm8Xwarw3YaD48l8NVZWpSDaRBZoWE35BgtLzkrEc+HGaQK 07SA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746191985; x=1746796785; 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=bbk+dXSasxE2+5UsRYscIfb+Bcs8iWgnzx9jGxiqBZA=; b=k1wX/ippw9Mud8e6ZLGIUAjsnbA786MLqHCWJDoSPm4FPlU95XpONz0kDCfqt/pYP7 q3r0OKcRhXh53SbuWvfD1mhHhK5qbIhCzWKffdq5VzMuZUcdDXWRC9809av8MGpn0EKK b9iclBsmG4r4B+mcMLbyWmgyVJoTcqjkV124jUCsZzu+nDls3J6H+acCE2CLt9dCE7VG fM3guRrOSNyG48m4yJtGdOrDecSthq2YujPHTdg3MmnwejONpYiN2ylR06bff3W/4khB MhHQ5m6bKlcf0vzlTIPMSYT9fK8NIOTaN97DvjR6B/pQo58iXAPuCt9RDSmwSW2IXB3M sN3g== X-Forwarded-Encrypted: i=1; AJvYcCWo/XOfyC8EYMTjNasQeb7is4kgMuIlSsorplTm0bd+0xR+Jo1OqU1M0sztNMVFoCjzA4NeyKJG5hwpcE8=@vger.kernel.org X-Gm-Message-State: AOJu0YzwTngQCnxFG9M9uwwTJ3e8u/eJgGO8/CdC8JPXkzMeJrrct7KN +lfvsjhkm30jIqw1oYCN43bZpgggVOcf97nrjDLrhbNf02UjEqEM5o3GcYStgaKY609EpyDfg24 q3cD5BiBReqyeUQ== X-Google-Smtp-Source: AGHT+IGveiyur1EXCtMYwtOpwsJwYHZqUEzCRlV7GV9o+pqLu88Ln8BrBrrQCO9Y/ysGBU+D2T1w9oj2V9Uwtno= X-Received: from wmbay12.prod.google.com ([2002:a05:600c:1e0c:b0:43d:1dd4:37f2]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1e02:b0:43c:e8ba:e166 with SMTP id 5b1f17b1804b1-441bbf33b3emr22730035e9.22.1746191985797; Fri, 02 May 2025 06:19:45 -0700 (PDT) Date: Fri, 02 May 2025 13:19:31 +0000 In-Reply-To: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4725; i=aliceryhl@google.com; h=from:subject:message-id; bh=+Q2XjTWHwCfoLlwubHIATQqjUcgilGTTvVMpLQ5kNoY=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoFMZo2H1t/IpH48gsDLFYMZhiI/D1C1tt/QonY u2pzqdwyHqJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaBTGaAAKCRAEWL7uWMY5 Rj9tD/4l4umhgik/NJELACTCS6I5YHeFBKaxER2M5dFQqYIfY3wguZcYKGAXIkBFOeIILFgs+T0 PKNE/wQypSEbOfUqVpnOP3GtEMFULcAjsLmYxrUv8jyxgnZauixE0N9wjm6wLr691oxrEHeVpBt RQeZdG02AuUm9ZNph680Q7QcFOeOhXCtmq6KBWOqx17tscHRJzA4pftJwklGFBZs3DYG3dUH1GB FwRtyUe4Q5S6jaIBRaw8i2HB/y4nj8jSKBDG3KmPJCu+/EkpRzuLagiBvwJBzIZDLxMocZuK7tk xSp55CAPgmUOJeRb+Ub5obfMHmOGHU1ZTOOGmWgykBF2BlTv/Es5ODx4ePSxwf5i2wos8H0oyoj 5YPn6TPRSntpM+mGjRxER3/icfMkOyvFhto3MppGCfct7bzbmjCnFrzFS73AQ1eI0JrxLpa27UM 6jFRS3abdAeNAAq8TFk7IuA5WHDuF7xm5/ep5F71gk+gIV+MSfsowttRDkI0PsnwYetkepgmntN Yz8MPGCxk27Zrmj1H16V0Ujo4n0yO9ZwwD7Zw+6pzYPkvw2ZRt3JYwP4c616ucHm9MgT/bDie9o uuCo9bLOhNIecGuwjXxeNJVF3r5zWcBzISdHw8PcO4G/hcthtmoIMASHRGOgcO7dbWiN6atjk6q cTPHnWnQ/+w3Wnw== X-Mailer: b4 0.14.2 Message-ID: <20250502-vec-methods-v5-3-06d20ad9366f@google.com> Subject: [PATCH v5 3/7] rust: alloc: add Vec::push_within_capacity From: Alice Ryhl To: Danilo Krummrich Cc: Matthew Maurer , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This introduces a new method called `push_within_capacity` for appending to a vector without attempting to allocate if the capacity is full. Rust Binder will use this in various places to safely push to a vector while holding a spinlock. The implementation is moved to a push_within_capacity_unchecked method. This is preferred over having push() call push_within_capacity() followed by an unwrap_unchecked() for simpler unsafe. Panics in the kernel are best avoided when possible, so an error is returned if the vector does not have sufficient capacity. An error type is used rather than just returning Result<(),T> to make it more convenient for callers (i.e. they can use ? or unwrap). Signed-off-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Greg Kroah-Hartman --- rust/kernel/alloc/kvec.rs | 46 ++++++++++++++++++++++++++++++++++++= ---- rust/kernel/alloc/kvec/errors.rs | 23 ++++++++++++++++++++ 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index ebca0cfd31c67f3ce13c4825d7039e34bb54f4d4..e9bf4c97a5a78fc9b54751b57f1= 5a33c716c607b 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -21,6 +21,9 @@ slice::SliceIndex, }; =20 +mod errors; +pub use self::errors::PushError; + /// Create a [`KVec`] containing the arguments. /// /// New memory is allocated with `GFP_KERNEL`. @@ -307,17 +310,52 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUn= init] { /// ``` pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> { self.reserve(1, flags)?; + // SAFETY: The call to `reserve` was successful, so the capacity i= s at least one greater + // than the length. + unsafe { self.push_within_capacity_unchecked(v) }; + Ok(()) + } =20 + /// Appends an element to the back of the [`Vec`] instance without rea= llocating. + /// + /// Fails if the vector does not have capacity for the new element. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D KVec::with_capacity(10, GFP_KERNEL)?; + /// for i in 0..10 { + /// v.push_within_capacity(i)?; + /// } + /// + /// assert!(v.push_within_capacity(10).is_err()); + /// # Ok::<(), Error>(()) + /// ``` + pub fn push_within_capacity(&mut self, v: T) -> Result<(), PushError> { + if self.len() < self.capacity() { + // SAFETY: The length is less than the capacity. + unsafe { self.push_within_capacity_unchecked(v) }; + Ok(()) + } else { + Err(PushError(v)) + } + } + + /// Appends an element to the back of the [`Vec`] instance without rea= llocating. + /// + /// # Safety + /// + /// The length must be less than the capacity. + pub unsafe fn push_within_capacity_unchecked(&mut self, v: T) { let spare =3D self.spare_capacity_mut(); =20 - // SAFETY: The call to `reserve` was successful so the spare capac= ity is at least 1. + // SAFETY: By the safety requirements, `spare` is non-empty. unsafe { spare.get_unchecked_mut(0) }.write(v); =20 // SAFETY: We just initialised the first spare entry, so it is saf= e to increase the length - // by 1. We also know that the new length is <=3D capacity because= of the previous call to - // `reserve` above. + // by 1. We also know that the new length is <=3D capacity because= the caller guarantees that + // the length is less than the capacity at the beginning of this f= unction. unsafe { self.inc_len(1) }; - Ok(()) } =20 /// Removes the last element from a vector and returns it, or `None` i= f it is empty. diff --git a/rust/kernel/alloc/kvec/errors.rs b/rust/kernel/alloc/kvec/erro= rs.rs new file mode 100644 index 0000000000000000000000000000000000000000..84c96ec5007ddc676283cbce07f= 4d670c3873c1e --- /dev/null +++ b/rust/kernel/alloc/kvec/errors.rs @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Errors for the [`Vec`] type. + +use core::fmt::{self, Debug, Formatter}; +use kernel::prelude::*; + +/// Error type for [`Vec::push_within_capacity`]. +pub struct PushError(pub T); + +impl Debug for PushError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "Not enough capacity") + } +} + +impl From> for Error { + fn from(_: PushError) -> Error { + // Returning ENOMEM isn't appropriate because the system is not ou= t of memory. The vector + // is just full and we are refusing to resize it. + EINVAL + } +} --=20 2.49.0.967.g6a0df3ecc3-goog From nobody Wed Dec 17 08:51:13 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (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 5A2D4255F39 for ; Fri, 2 May 2025 13:19:49 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191991; cv=none; b=SPk3pFuQrjGTZgSAOBL/FdHKA78NyaHdT2zM4xIOkAT8NjRJYMsZU++2xGqKaA5XTPGyfhUZ1ff65F/xbCZo6AiDT0q+w5aBl5axjFf+1mVPn4jMDHfTXKoR0kN+Y7ybcW9dgYmEFM8VUYxD70nhybmfcK6IgEypG9ay2w9/DEA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191991; c=relaxed/simple; bh=MXQYfazmKkQqgGylg+AFvYi72rjPBnY451sRoj98mHU=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=hWbNMy3kCzRjmCstiT+0BLaPvpNSKjuQuYbIpdJaKRDkpOjTBF0o+Fl0dYvmR5NxC5kqehe1ySy+WdU3bK0yCxPFWYzICxxCaMq3yQhiFbvzbtN6sayUPBcgxjuhreQpVl//3yHgjeK519Itlzkw1ktIH07zFjo+4wJrIWu/wdE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=u+iYWXmx; arc=none smtp.client-ip=209.85.128.74 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--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="u+iYWXmx" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43d733063cdso14482835e9.0 for ; Fri, 02 May 2025 06:19:49 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746191987; x=1746796787; 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=yqmeFwn1Rj34pwx6jnFzRTB4vAw5UvMjZEUMYLZfhw4=; b=u+iYWXmx8anYaKW17xKMq4Z00d/vuaMbR1EWghM6sjRTXj5bVdydcdqCEMTvTW783u To1acmAEdCWBvZs1l8mmTMDiaTStTTTPP6kRSb0hdKTpl3qULri6ILswADOEhJvUH1Vr 4UNj53TFexww2XXiqrHubzRg+SlaEWGIK4dLnc/2WnfGIKxOOj/Vo2UqsA8FE8bBK/na nh/1o0skoUybewUtt72hwmkJWQIMNzuBDKwqZfz+n3v4pXZ1hH1ShI3jXRDrZ1LFpqSj 9OxSjQsk45slLtHdJ17vxKTzy/lJ4nTpLtDn2WgJ8icF+8YXviAyp+D5qyqNOkXS/alD gZ0g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746191987; x=1746796787; 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=yqmeFwn1Rj34pwx6jnFzRTB4vAw5UvMjZEUMYLZfhw4=; b=ENVUwPU4cE0077lZt4uN8pwTo7e9s+rTNHy6Xr35B9WmIoLOR+kYmGTFwG2j45VXAF +wU690ZVOhmY53COC7WVbbaN1nSso9r97z3LAmP1hqvG5o7l/fQtKgcv+PPV9To6vmOp 7vG1LMdEH6sOWnbajYRmDIP2a8TWHtrFw6YfYZ++r6kja57u5IT6/LncTQ15BFb+kgm7 JRD4z3xXiqdoFkd0kcZAh50Oonah5Hjs8fAxKuS12zGmB+iyS1yunDj9JApV9p7+CEFY F/xvnzyswMrldJvRTG0Se+nc9ob4ziFks87a+2Ovd9ySq4oegBihYp+M3ZqP8ncDkXAh u0HQ== X-Forwarded-Encrypted: i=1; AJvYcCV1tdjMby/RlVZJG6MPifHCKVZkvd+N8jeuf0sJ0cvtevA8f0rRWolLn5SP80p1RI52RDzl+LJDoLVKIT4=@vger.kernel.org X-Gm-Message-State: AOJu0YxZcPZ0wjAbnn+ecad9ZC80FMNwADEY/vc/IRZWX4tlERU3bvNS +ic60RmgKmAeCNYfZF/G1Hfca15NVw8dbOAbdYywxSIfPzhei8A+4Q+IiGZ+VX8svQ5Eh2tG9pZ DDPJNP/iNaPW5Jg== X-Google-Smtp-Source: AGHT+IHdXiLWdxIZ4Yqr6/Pv/iN43/E3gnSrF9FP5/rrTcGLwFIFHW42RprHgESHdFIvdvtzK5MckCDEno8bE4Q= X-Received: from wmbay23.prod.google.com ([2002:a05:600c:1e17:b0:43d:522a:45e8]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:1e19:b0:43c:f64c:44a4 with SMTP id 5b1f17b1804b1-441bbec221fmr23679805e9.8.1746191987828; Fri, 02 May 2025 06:19:47 -0700 (PDT) Date: Fri, 02 May 2025 13:19:32 +0000 In-Reply-To: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3038; i=aliceryhl@google.com; h=from:subject:message-id; bh=MXQYfazmKkQqgGylg+AFvYi72rjPBnY451sRoj98mHU=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoFMZpWvL5GIFDNDcl2YOYjwYZ0d1nB5fG6xJ9c guC9afNJq6JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaBTGaQAKCRAEWL7uWMY5 Ru+3EACvzMUzAcbwDz8cGLCeCy7muqK6ol9STRrLrVcM/mHKecC/PamFlhFrDvLBFbKeAtFLi63 tfvTtxOYreAtAx8txWykFe7kSYf8ukPCG2YmdDCoNR8zJib+Twv8UUdiv4Pam+ndFUP/FyIDuBm nkKO4fnEQR4fFgGAHSXZG5v8UECpV4M86CBFycmK7A71OXATGC9a+FRhD4vP9+yXRgU5J8Cpod+ AIuPyGBXy67K5mxEAWwwuzNhz8hAqf0B/X+XgGgd8D/gMKI+Nbcx1IrMvORZJJ4r59XmWvQFj9P I8VS6yCT0h1jwv9nRgt35rlVxUwzRthTk02RR9AdNpZwEptFS8gxNq06jbd7+2T0mP8SfpNaOuK WCTGggVymxFdDzyevzmbJkoJilgB0VPY+9WBj5ot/RWbqQxrZXFgR+aOXZzKPEHgxkik9bNfiyt hlkGYnyce7Xhs/hApEcbeGAExRqe8sNNm77Q7k7C5/6iQQHlIb0zf1dvcANrhE2OapRFEKI65Gi VSzexYrdtuqHL4KmQBDit85dTL0Ek/araLalV1J25Uh9KDH+svxrH9QcMO/9rosvYo68EqgAjk0 HaLFuyCSxbkHucE1M+q5ICHXRSt0BUUb17bb3s1zeH5l536rrxT79ctBbYbfxoSd98W6bftWfqC j2OZIBMkeBuxIsQ== X-Mailer: b4 0.14.2 Message-ID: <20250502-vec-methods-v5-4-06d20ad9366f@google.com> Subject: [PATCH v5 4/7] rust: alloc: add Vec::drain_all From: Alice Ryhl To: Danilo Krummrich Cc: Matthew Maurer , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This is like the stdlib method drain, except that it's hard-coded to use the entire vector's range. Rust Binder uses it in the range allocator to take ownership of everything in a vector in a case where reusing the vector is desirable. Implementing `DrainAll` in terms of `slice::IterMut` lets us reuse some nice optimizations in core for the case where T is a ZST. Signed-off-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Greg Kroah-Hartman --- rust/kernel/alloc/kvec.rs | 59 +++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 59 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index e9bf4c97a5a78fc9b54751b57f15a33c716c607b..7f75f3174ccb85daa3a9546d7b1= 10da97f46063f 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -586,6 +586,30 @@ pub fn truncate(&mut self, len: usize) { unsafe { ptr::drop_in_place(ptr) }; } } + + /// Takes ownership of all items in this vector without consuming the = allocation. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D kernel::kvec![0, 1, 2, 3]?; + /// + /// for (i, j) in v.drain_all().enumerate() { + /// assert_eq!(i, j); + /// } + /// + /// assert!(v.capacity() >=3D 4); + /// # Ok::<(), Error>(()) + /// ``` + pub fn drain_all(&mut self) -> DrainAll<'_, T> { + // SAFETY: This does not underflow the length. + let elems =3D unsafe { self.dec_len(self.len()) }; + // INVARIANT: The first `len` elements of the spare capacity are v= alid values, and as we + // just set the length to zero, we may transfer ownership to the `= DrainAll` object. + DrainAll { + elements: elems.iter_mut(), + } + } } =20 impl Vec { @@ -1073,3 +1097,38 @@ fn into_iter(self) -> Self::IntoIter { } } } + +/// An iterator that owns all items in a vector, but does not own its allo= cation. +/// +/// # Invariants +/// +/// Every `&mut T` returned by the iterator references a `T` that the iter= ator may take ownership +/// of. +pub struct DrainAll<'vec, T> { + elements: slice::IterMut<'vec, T>, +} + +impl<'vec, T> Iterator for DrainAll<'vec, T> { + type Item =3D T; + + fn next(&mut self) -> Option { + let elem: *mut T =3D self.elements.next()?; + // SAFETY: By the type invariants, we may take ownership of this v= alue. + Some(unsafe { elem.read() }) + } + + fn size_hint(&self) -> (usize, Option) { + self.elements.size_hint() + } +} + +impl<'vec, T> Drop for DrainAll<'vec, T> { + fn drop(&mut self) { + if core::mem::needs_drop::() { + let iter =3D core::mem::take(&mut self.elements); + let ptr: *mut [T] =3D iter.into_slice(); + // SAFETY: By the type invariants, we own these values so we m= ay destroy them. + unsafe { ptr::drop_in_place(ptr) }; + } + } +} --=20 2.49.0.967.g6a0df3ecc3-goog From nobody Wed Dec 17 08:51:13 2025 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (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 58AD5255F5D for ; Fri, 2 May 2025 13:19:51 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191993; cv=none; b=PuCGIJa8PA6AZT7GnM34B+As7kL8k1loH81kKYhaW7ycNka8bfJddhDcJWt+mfIfFMBKWNBMUCU/eLRoMhWoKvG80emhqTiiouPg0PJLZHg8FRJF50OobXKbXvNhW6VLPji/vJwDpQF6nP/FJh8RFM78dp0XHSrsStH5mc/R6lw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191993; c=relaxed/simple; bh=ntNHKD1aAus/XVUDLI6auIHzcPaub0zhy99OX5NhOao=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=OanCRFeUQ6Ot/qk5T/Y+w/c5tFD1/f42Wf1BvOW1M/eQY6tHlZeTNrB1EVr4q1FX+sVP36JtkFCPI613qUdXUBnqKd/voqlDsNrNoIevKiSnLSmmCh4O34Ykf46/ecbyerDC2jXQVV5bGpcQQb7m38nYf7tG++qF7KvIjfv/A4o= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=39gPze4X; arc=none smtp.client-ip=209.85.128.74 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--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="39gPze4X" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-43ea256f039so14592885e9.0 for ; Fri, 02 May 2025 06:19:51 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746191990; x=1746796790; 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=s1tpEf3+bu3lxuNrb8CKVDwlrCGOTDoKQVcY7PTqeRY=; b=39gPze4XylEbh5onl8W3gfJG1fMF3535/nrT6p+JQ+TiJLrD5kWBvqjV81q24bOT2c QNl4/DieKlirJIcuSAtLjf2sC8n9ndPpJrVHlhytBTd35m3tpjKz7NGqqEBn18U7VCbk lykzVbIYiVCgfXluuz32yk5J7ra1N+5t8YEUyZUfp7CioBWVrvG9c2y9mvVhrSrlfr2A J+ZxJX4gdq8xZDINXt/Vu3iQlU8C3EujyvXy1Bs0F1t0efsY4Qw84PBz/zY70Fg/3PR3 z3smGPZstgAboOOqGjk3NCsLbl4f0OSF2MyATGydz8IlBt+pd3fYmPcJFJuDePAONEuB IUeg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746191990; x=1746796790; 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=s1tpEf3+bu3lxuNrb8CKVDwlrCGOTDoKQVcY7PTqeRY=; b=IA/A3LLcm/2/DrJObFFTT+7EfCAaOPmI8g29E3MW8OAYlHudrKsJVDcylq5mUC3x8e YWRU8N2RgHyoNu16U/T6aPKKgMoMQPlcFKYAlZ2JFgDZ5enLRupcDkTbwdKvkfF5snRI 6q9nULWkcsLqhdSM+gpMw/fqivujn3/qUwFHciOEIF0gE4/MBwQAw0D6csGlQEH+32+y lhVXRmHZ7sVUGc7gQPK/XI2TB/HLrOolMZ4vXpW2R4xIE7eIW0mVAWdWCdnsI7FvI+Ge yaECnFVANx2ixcZS3fKC2M+48Bv0LKMjuQm7M+87dNYplmDMsV1SiB+CEojGBIpAUYXD z0tA== X-Forwarded-Encrypted: i=1; AJvYcCULv5yGCIg/XOD9Q4YWKGxjBVw+lAPNTjwQ8qsx5YXao/EmIiRxHqzNM3D4RiZuD2kNoyNfAt3fd51eL7E=@vger.kernel.org X-Gm-Message-State: AOJu0YzJha3vcyFBTh3IiuV+JdlGhHnwghcsBtNqR9tECoDYpsHByAWg MLGwTBZATROAGm8G3gG3LB0vKgKqn1WU7x9iLsexc7wt8KBjXPebQoOVrmd6on2LWBQileWsQ7b vX5Xfx/ECoyMAWA== X-Google-Smtp-Source: AGHT+IHAFqMJkAtqC2SWZxLVqIggAEd9I23F+Rr4fh+PToGXouWQ4XCpFH5Wsw5/aFzuNZFmLh2jeM6OTeI2tjY= X-Received: from wmbfp20.prod.google.com ([2002:a05:600c:6994:b0:43c:f5b8:aad0]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3155:b0:440:6a1a:d89f with SMTP id 5b1f17b1804b1-441bbea0e1dmr24794695e9.4.1746191989989; Fri, 02 May 2025 06:19:49 -0700 (PDT) Date: Fri, 02 May 2025 13:19:33 +0000 In-Reply-To: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3500; i=aliceryhl@google.com; h=from:subject:message-id; bh=ntNHKD1aAus/XVUDLI6auIHzcPaub0zhy99OX5NhOao=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoFMZpNca3fQ1kydJbsV7WpBUsdAazh+kXuZlEZ v14TxsM44WJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaBTGaQAKCRAEWL7uWMY5 RrIDEACIdhbzpcsrR3j0V7JeiyO3csHGQGJy5MMPwxn71owlEsaD+YPjE+unTZ5jKnkyBFiNtdc PmE1KoUHPxRhOa9WAYXQ+LN8hCCPUrmvySQbZY9BPwz3N56zxqtWCbaUldBy4qf0QuhOAQTz7wu cyRrC6JmMZ9zwdAgoBzV8BmKkls3MKCKyAnJebkCgCydQFms7W0tltvzv7vdxLBWzBDCYGHWeQO WPxJo9T8YEydA4armdMctooU9c5KCwZbpEtbrsOgqsBK5FXVjWddpNpQ2wyBz3vtXdynIZL5Bhq beSTEjH18j/gUxarR72KGLqXVH5NhczOXLLUDyXV9VN9OJixt+QHCFyALlUPGMx71TrnfI4/vSA TwPuxqk0q1KFXuwVUPrcWg5599tKgJFLSlXv/pjeunTCrUqGJI8eRm0Q1tjY9TR7qa/HEWNOX6M oCav5In6udDYm9p+KxnUtwy/5KOrjL1IY2R+Yqqt1viEI+zzLzS6beSqmgAyRBkBDuSsekfWDNO Ozw8PF1+hzv1yqqiM1O/HjNWBuHUY4tlnLre7YIkPnhuliQyHLaW+013cr3qRMPdEZEphxxUjJm OMV2G9XTQip7yx1fU453j5BUesKmMH3HG7dFtlt/hnG3A2COKu2NBWFS+wK2K1NcD78mVPBw4KN YTmcFlWd/JBl3tA== X-Mailer: b4 0.14.2 Message-ID: <20250502-vec-methods-v5-5-06d20ad9366f@google.com> Subject: [PATCH v5 5/7] rust: alloc: add Vec::retain From: Alice Ryhl To: Danilo Krummrich Cc: Matthew Maurer , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This adds a common Vec method called `retain` that removes all elements that don't match a certain condition. Rust Binder uses it to find all processes that match a given pid. The stdlib retain method takes &T rather than &mut T and has a separate retain_mut for the &mut T case. However, this is considered an API mistake that can't be fixed now due to backwards compatibility. There's no reason for us to repeat that mistake. Signed-off-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Greg Kroah-Hartman --- rust/kernel/alloc/kvec.rs | 72 +++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 72 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 7f75f3174ccb85daa3a9546d7b110da97f46063f..3298b3b0f32c70f3fe517fcb7af= 6b9922fea926b 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -610,6 +610,29 @@ pub fn drain_all(&mut self) -> DrainAll<'_, T> { elements: elems.iter_mut(), } } + + /// Removes all elements that don't match the provided closure. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D kernel::kvec![1, 2, 3, 4]?; + /// v.retain(|i| *i % 2 =3D=3D 0); + /// assert_eq!(v, [2, 4]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) { + let mut num_kept =3D 0; + let mut next_to_check =3D 0; + while let Some(to_check) =3D self.get_mut(next_to_check) { + if f(to_check) { + self.swap(num_kept, next_to_check); + num_kept +=3D 1; + } + next_to_check +=3D 1; + } + self.truncate(num_kept); + } } =20 impl Vec { @@ -1132,3 +1155,52 @@ fn drop(&mut self) { } } } + +#[macros::kunit_tests(rust_kvec_kunit)] +mod tests { + use super::*; + use crate::prelude::*; + + #[test] + fn test_kvec_retain() { + /// Verify correctness for one specific function. + #[expect(clippy::needless_range_loop)] + fn verify(c: &[bool]) { + let mut vec1: KVec =3D KVec::with_capacity(c.len(), GFP= _KERNEL).unwrap(); + let mut vec2: KVec =3D KVec::with_capacity(c.len(), GFP= _KERNEL).unwrap(); + + for i in 0..c.len() { + vec1.push_within_capacity(i).unwrap(); + if c[i] { + vec2.push_within_capacity(i).unwrap(); + } + } + + vec1.retain(|i| c[*i]); + + assert_eq!(vec1, vec2); + } + + /// Add one to a binary integer represented as a boolean array. + fn add(value: &mut [bool]) { + let mut carry =3D true; + for v in value { + let new_v =3D carry !=3D *v; + carry =3D carry && *v; + *v =3D new_v; + } + } + + // This boolean array represents a function from index to boolean.= We check that `retain` + // behaves correctly for all possible boolean arrays of every poss= ible length less than + // ten. + let mut func =3D KVec::with_capacity(10, GFP_KERNEL).unwrap(); + for len in 0..10 { + for _ in 0u32..1u32 << len { + verify(&func); + add(&mut func); + } + func.push_within_capacity(false).unwrap(); + } + } +} --=20 2.49.0.967.g6a0df3ecc3-goog From nobody Wed Dec 17 08:51:13 2025 Received: from mail-wr1-f73.google.com (mail-wr1-f73.google.com [209.85.221.73]) (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 0F26B255F4E for ; Fri, 2 May 2025 13:19:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191995; cv=none; b=OmZT6Q++9zILC5LiWvv1ypndbw7PjqwCHctN39DozkNClxUUKGMTrPbgzX1tsC6TxV1Fquysaj5YT8bWQr3q0vuLx484FRV3piZib1V95aaVVoBH1ZrJvqQR5edA2Ja8SXbi114tfQLGmrguzP8E2Va+MwpoeXmXiqrrLV6BmZU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191995; c=relaxed/simple; bh=NPI8Q0CzeDhYCgGRlOT+/ncU0nCVd9zf3HV87DMudMQ=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=G5/IeTxPBku7teWI/4ab8w3nCRFskET6qsJsLgYr01HR3dOHZb24T0CYH3APWXLUnZ9s8lyLoed/wNMqq0WLRQWpoJeHNIghNjqb/FSh/wPE0AFm7HU9nBe5m0MmT+CaxcYe8uEpivA/wtDcIY9qsJd4oN17ZGYCCSfm9dcTjww= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=ly42+29Y; arc=none smtp.client-ip=209.85.221.73 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--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="ly42+29Y" Received: by mail-wr1-f73.google.com with SMTP id ffacd0b85a97d-3a07a867a4dso1015546f8f.3 for ; Fri, 02 May 2025 06:19:53 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746191992; x=1746796792; 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=xzccJFQgm3Btdw/UpST5BSIO17Up7GalLaw9yByRn6A=; b=ly42+29YxXpVExFhm8YGYF3wR9/NK8l9/xOp/SzJAK88h60ycU3XNSWWwEUsKrXgbT qclKUnjzLqcs8Ztu0U8tvxN1YSzDAlUBVrs6OnqYO6ZQGpEFJIAEw7m2vzE5syunX/69 1CBJ3R1haE97W1KPL+ltUhvgVCmSgH7djFYQSjY64GpfWfmXfxXD5ViuBN3V6qXDcfOr hON1DMk1Ki/n50UB4eCwEXKv6j73GiKLt+PlhVwFAfQ6uoXoEFOzaRMh8wOJcu1AzSOy ne0W1vN9mheo3xkfi9HaMhCtewXQ7+VLKl8ZKAU7OKYIlBTkoRFvuZKHoPc5YFh7Pw4P 2vng== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746191992; x=1746796792; 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=xzccJFQgm3Btdw/UpST5BSIO17Up7GalLaw9yByRn6A=; b=GSVDnWr7GHDWH7gj5H537ioDcA50MEIMuMMawvbEH74q5xZv9xlVIAKVpGxZgofmPA HrdCh4AmlSwaai/2Uha/wL6q2O6AQD6n39zuQ9cgD1vxgzXvowtZsOsFxpzUoD3LhMBC T03Ydg1CxnKO2bHBTR7sB33tMhhRDKXq3qZhhlMVYO+4ZCxAGEGjsVrU5XwmAsHVAwhg meT/DHr74MHQnRs9qrsHm/Xr6wF6Y9sUu311cpOBJoHI3lg78poyapKs1+DnM7RkadHK WB3YLsD8mC7z9JKAurJn12CqgbnaSUj6ShH62KxrMXDwKk0Wgbj/aw4GfiBire+gFLam Llxg== X-Forwarded-Encrypted: i=1; AJvYcCXecnQOeT7IGB72hRJh4lfWgL8PRnRJJaK6VWuIsTwpGurwXtsdHnqHFMTXnSQwoqqNHNXqF3+Yrb5AJMI=@vger.kernel.org X-Gm-Message-State: AOJu0Yz9aAuXYnEWakwhj4MFmS0/NYbdN9KRRPC0foQD28QnQRTVlZrJ iF9wmkrhAqfn+hfyQG/SnHPdUUb+BObyKQ6Lw2KA8GDKnvyqvvBSag3UjCeF+UKg6u1p8ogdHby cHGOTIhcZAHlSPA== X-Google-Smtp-Source: AGHT+IERAEp6Y3HGppF1/OOjzNHvj6vYq+bUMzpiTu5TzcOhpBKMX4Gv/giZgYisNuR6fADi18ZYP+Bp7+ayHh4= X-Received: from wmbji5.prod.google.com ([2002:a05:600c:a345:b0:440:595d:fba9]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6000:1446:b0:391:3406:b4e2 with SMTP id ffacd0b85a97d-3a099af1304mr2118599f8f.49.1746191992447; Fri, 02 May 2025 06:19:52 -0700 (PDT) Date: Fri, 02 May 2025 13:19:34 +0000 In-Reply-To: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=3519; i=aliceryhl@google.com; h=from:subject:message-id; bh=NPI8Q0CzeDhYCgGRlOT+/ncU0nCVd9zf3HV87DMudMQ=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoFMZpQGtBpyeKhsH9KTgDwX8YIWvfvp819rVCW YiaMq2+1gKJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaBTGaQAKCRAEWL7uWMY5 RohPD/9xqXoqE6eao1bCOeaVAHUgZfFMO25NzqOL07q7JHy8Fg11q2TXwxY6bX/++nRczCVbjnP hrk+OsTrwAYjZYZDUXUtq8OMKBCwS/XBOltyx2PRUAo6QAqUcVtb6LA0PHoCoK1CO+L3p4u0lei IkaHFhImdw30BiXxJkSE9K4rF4BeaaQOzI/6IE2JqVWvOHCtX3yopWudEKOuZ8/ME+vxs5A3e7Y nz8uI9FNmFUAkslZWD0tXKltpZYG6XmskbiIvRvBVeXg0aQW0ysnhYyLJXKQP2LbkkZhKgsquQE t0gGlnuRu6NdtPO6KmoulGayRe6e3jE2GXx78uqMxSpDLvMftvo52G9EF0uylg5bn1ZijWnlAlg pOUTJX2QiqALXYRtGvTccFBLFxZl+PgpgOtV3vwIvL8B4or2tpM8V0bLwsCC+Iteim0ck/Zwp9r k0Ub7L5COkfII3YdNitpM0TRSSUoBT9KlBIfDsSryL1bNHkJUyiXzjjmcgNJr9V04LnRbPSmURK tnPHWwhbCfs9G/HxjkScyTOEQ3hNMYkj5tnGHwjz3XZFg+UH+dUWx3g8l1RlL9CWHXQU/ZZ+Jwo Tvpg4BRPLEHVEN+nEfnf8RDBYB9vm8n/MWuYxNguZZzyYTbmfnEBE01Sc8vhrVuKQweB9MCmH9c 51Yf9X9Jtlw7N/Q== X-Mailer: b4 0.14.2 Message-ID: <20250502-vec-methods-v5-6-06d20ad9366f@google.com> Subject: [PATCH v5 6/7] rust: alloc: add Vec::remove From: Alice Ryhl To: Danilo Krummrich Cc: Matthew Maurer , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This is needed by Rust Binder in the range allocator, and by upcoming GPU drivers during firmware initialization. Panics in the kernel are best avoided when possible, so an error is returned if the index is out of bounds. An error type is used rather than just returning Option to let callers handle errors with ?. Signed-off-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Greg Kroah-Hartman --- rust/kernel/alloc/kvec.rs | 42 ++++++++++++++++++++++++++++++++++++= +++- rust/kernel/alloc/kvec/errors.rs | 15 ++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 3298b3b0f32c70f3fe517fcb7af6b9922fea926b..8845e7694334b672476ff935580= f3a9eb94d23fe 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -22,7 +22,7 @@ }; =20 mod errors; -pub use self::errors::PushError; +pub use self::errors::{PushError, RemoveError}; =20 /// Create a [`KVec`] containing the arguments. /// @@ -389,6 +389,46 @@ pub fn pop(&mut self) -> Option { Some(unsafe { removed.read() }) } =20 + /// Removes the element at the given index. + /// + /// # Panics + /// + /// Panics if the index is out of bounds. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D kernel::kvec![1, 2, 3]?; + /// assert_eq!(v.remove(1)?, 2); + /// assert_eq!(v, [1, 3]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn remove(&mut self, i: usize) -> Result { + let value =3D { + let value_ref =3D self.get(i).ok_or(RemoveError)?; + // INVARIANT: This breaks the invariants by invalidating the v= alue at index `i`, but we + // restore the invariants below. + // SAFETY: The value at index `i` is valid, because otherwise = we would have already + // failed with `RemoveError`. + unsafe { ptr::read(value_ref) } + }; + + // SAFETY: We checked that `i` is in-bounds. + let p =3D unsafe { self.as_mut_ptr().add(i) }; + + // INVARIANT: After this call, the invalid value is at the last sl= ot, so the Vec invariants + // are restored after the below call to `dec_len(1)`. + // SAFETY: `p.add(1).add(self.len - i - 1)` is `i+1+len-i-1 =3D=3D= len` elements after the + // beginning of the vector, so this is in-bounds of the vector's a= llocation. + unsafe { ptr::copy(p.add(1), p, self.len - i - 1) }; + + // SAFETY: Since the check at the beginning of this call did not f= ail with `RemoveError`, + // the length is at least one. + unsafe { self.dec_len(1) }; + + Ok(value) + } + /// Creates a new [`Vec`] instance with at least the given capacity. /// /// # Examples diff --git a/rust/kernel/alloc/kvec/errors.rs b/rust/kernel/alloc/kvec/erro= rs.rs index 84c96ec5007ddc676283cbce07f4d670c3873c1e..06fe696e8bc6612a5e6aa2f6c28= b685033acfa2f 100644 --- a/rust/kernel/alloc/kvec/errors.rs +++ b/rust/kernel/alloc/kvec/errors.rs @@ -21,3 +21,18 @@ fn from(_: PushError) -> Error { EINVAL } } + +/// Error type for [`Vec::remove`]. +pub struct RemoveError; + +impl Debug for RemoveError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "Index out of bounds") + } +} + +impl From for Error { + fn from(_: RemoveError) -> Error { + EINVAL + } +} --=20 2.49.0.967.g6a0df3ecc3-goog From nobody Wed Dec 17 08:51:13 2025 Received: from mail-wm1-f73.google.com (mail-wm1-f73.google.com [209.85.128.73]) (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 226CB256C6A for ; Fri, 2 May 2025 13:19:55 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.73 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191997; cv=none; b=moFmeCIuI2Oa5fFbslNL/9R39oJYJomqBsjqZGryQpWonxtqzjZil6dCPacEmwVoX2dKpOYDb4txmOTTyAufOGrEBGgncSlBnV7z2NhphGAPcN6HFjHa3mTwCHHoVjv5EhartbA+pMNr/21pfgxi1iJhF/S0ad5PW56Oq34oGLc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746191997; c=relaxed/simple; bh=+9IyxSQyP27/emN3Z7piM0ajFLsCl/Pug5kGGN8P3Pw=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=HxuMD0XdXwOCVeE6D3KC//bPAKHM0hp9EX9crKkv6vICV7ExxRVjLiV6j7e41nMfBh/F5SEEMCXbma64iTS8OOPdXAPUc1mJFaFxp+XAouq4ts8wQSAGZEa7tU6O58gJt1XMkmd31A2yOp6Z+yz9DNFHpnXXiLISutFqhA5rBUc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=BCrXZ+Yv; arc=none smtp.client-ip=209.85.128.73 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--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="BCrXZ+Yv" Received: by mail-wm1-f73.google.com with SMTP id 5b1f17b1804b1-43f405810b4so9703165e9.1 for ; Fri, 02 May 2025 06:19:55 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20230601; t=1746191994; x=1746796794; 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=Tgf/dSBfhJF3XyhZfIU4YTUHWPpbhjb3fOqzjou+aqs=; b=BCrXZ+Yv/b38M+1aSMn2fYdQpA8YdVW96o2qRB9/w7g7ynzNxdlCQkHNl3hEExLQKN G6Gc+7qZOKfWQxUUScQP+1NG2swBa/zAgC74I8kk85t5WNpi5zKcU9GCjjYAgZcFqQTg bSl0Rklu0Lc0ZD5/O1yz9G3y7MsnFZCsHuIXkC0vzCbE/s45gZHdpznBWc0t1BP8iydu f5k2YYgf1YrQ9K230nfB4wp3iRBVl3Tk0JIpWZBy2tL3AszscCidaDSyR9OEubxr+J3C tmeT/XmW1RMea+Ev1bcA14lDfB8IJlx+LgjS1V8KLllZQRQJN8lHfDf2MxFCe+BgkM6r GEuQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1746191994; x=1746796794; 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=Tgf/dSBfhJF3XyhZfIU4YTUHWPpbhjb3fOqzjou+aqs=; b=DeKh2XHCHPsrtRp/9fp966PkjTB6/Wp1xUcTEw9vOKUIsB0ygwC11jsRI+dRRmfv34 pq31BvcmS6C7dP6Dz0qpIzPg49CDmucxYD0LisvFmx1K6F68SZ1/JvhWLz9gjUsKnMRu qZ7AyRyCnoQxceNt4DuxvtMJgcscm9nS3Phu0ztli7s+i8D9fBlVMoT5s3EHBMpheQST h8xGlpGKSrghrdPhtLe7yu+pUoEk+EuTrWLOmLBgw2zJiSmRfjQLmdLjmVstfOhENDJm IQcbwq4Vq31/W2jlHzHzWEai2S6Mi444esnhjdTxBgQf2wx2Jy5AfbJTXQSQ0KP/XVdm oCuw== X-Forwarded-Encrypted: i=1; AJvYcCU+B1dGm3LyocIcafyC/G1XM8qwpzCmuO5Pj8+0qYpeHxM4uIaS7ngo/GHfFBDf4Ru+0nxoqqTFpgr7lTg=@vger.kernel.org X-Gm-Message-State: AOJu0YzaLLHs8EIbtXBEjW5VrUIbI44f9y3BZhw6ocZl/xHL1LSysG8k y+0S2hODvQg29kCzGfvbjd5Vhbm1Mga3JlxcXECKmyWcJXgizn2rVHrMycHRiO2JWFaqhPStcFD GLTgiO0Q1x8KBvw== X-Google-Smtp-Source: AGHT+IGBP8X1327QOyf/N5JTak2KzCyZ3u2dbMq6hMfrVCBAcpWg7Vd3dSHLBCRIYSqFJaa16L7xos29pfG9a3c= X-Received: from wmbjt7.prod.google.com ([2002:a05:600c:5687:b0:441:bc26:4d3f]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:3d0c:b0:440:54ef:dfdc with SMTP id 5b1f17b1804b1-441bbeb36c5mr23309105e9.8.1746191994633; Fri, 02 May 2025 06:19:54 -0700 (PDT) Date: Fri, 02 May 2025 13:19:35 +0000 In-Reply-To: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20250502-vec-methods-v5-0-06d20ad9366f@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=4274; i=aliceryhl@google.com; h=from:subject:message-id; bh=+9IyxSQyP27/emN3Z7piM0ajFLsCl/Pug5kGGN8P3Pw=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBoFMZpYNjX33Q2M4DoOnNQNvAPltogL1FOhVVJs ZUXgBheHm2JAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCaBTGaQAKCRAEWL7uWMY5 RkYsD/wM2urXyc5ZVl+H41WRyHPKUpnzguGEX5AirWP+jwy0PpgupptS8mxUE33Psw7aQvdLn9y uXDpQSKFw0sUsb2acfJC7b6hMaQN6NCa5dRqxFfFrBA4Waz+Di8vMK2mCETBmgMDvzx7WmK0rea 6vUnKMjZuNaKv1RXEkAuc5DS5Sj+ISVQb+fI+MOUWNs+i1dBLIshBUP2LsWBreV0bCbi/EamEnX 7gPodBJuu82aedqM4sj915ccsErzAsJAULzKmhqUzEN3eU53x9SBQ09Z2tt8nm3uxs8xq9bywdC T5Xw+2WBW36GUAmmrdqcgN7SNYtAo9fwkyOdvgiQt28QcNQyajJxj9XtrnDYHRG0PNnJiTAuNDd yU65QxVQO6BwpsoSTQgGjlNqoF9TgFeqKXLAhvplrJVwHgLEmcdc13Y0YbJ63xzltl4dBTn3J4z dIu3o9GQcs2C/N+XTGY1iVACNP/FK27skASha/0p+IjbBkHX1pJigRpNdHfmIjKRPCQiXf7aFlU tFt2l1ScjP67S1Hda8XlfAQQ1YxzCSABNX/dVdrYJNxhrjGTszdiShOur+j9+AsKVta1XC9X83c UltWl0DN3Y2sGDnPiu6RSoOp8u1Mr6aBLw14Nml4aBGo5us598kVWm5NE1WFpLqJCpzwIG/P88R HcxmH9psjmjekMQ== X-Mailer: b4 0.14.2 Message-ID: <20250502-vec-methods-v5-7-06d20ad9366f@google.com> Subject: [PATCH v5 7/7] rust: alloc: add Vec::insert_within_capacity From: Alice Ryhl To: Danilo Krummrich Cc: Matthew Maurer , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable This adds a variant of Vec::insert that does not allocate memory. This makes it safe to use this function while holding a spinlock. Rust Binder uses it for the range allocator fast path. Signed-off-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Greg Kroah-Hartman --- rust/kernel/alloc/kvec.rs | 51 ++++++++++++++++++++++++++++++++++++= +++- rust/kernel/alloc/kvec/errors.rs | 23 ++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 8845e7694334b672476ff935580f3a9eb94d23fe..d2f3669c5417422dddaebcc7348= 543d3576b9ba8 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -22,7 +22,7 @@ }; =20 mod errors; -pub use self::errors::{PushError, RemoveError}; +pub use self::errors::{InsertError, PushError, RemoveError}; =20 /// Create a [`KVec`] containing the arguments. /// @@ -358,6 +358,55 @@ pub unsafe fn push_within_capacity_unchecked(&mut self= , v: T) { unsafe { self.inc_len(1) }; } =20 + /// Inserts an element at the given index in the [`Vec`] instance. + /// + /// Fails if the vector does not have capacity for the new element. Pa= nics if the index is out + /// of bounds. + /// + /// # Examples + /// + /// ``` + /// use kernel::alloc::kvec::InsertError; + /// + /// let mut v =3D KVec::with_capacity(5, GFP_KERNEL)?; + /// for i in 0..5 { + /// v.insert_within_capacity(0, i)?; + /// } + /// + /// assert!(matches!(v.insert_within_capacity(0, 5), Err(InsertError::= OutOfCapacity(_)))); + /// assert!(matches!(v.insert_within_capacity(1000, 5), Err(InsertErro= r::IndexOutOfBounds(_)))); + /// assert_eq!(v, [4, 3, 2, 1, 0]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn insert_within_capacity( + &mut self, + index: usize, + element: T, + ) -> Result<(), InsertError> { + let len =3D self.len(); + if index > len { + return Err(InsertError::IndexOutOfBounds(element)); + } + + if len >=3D self.capacity() { + return Err(InsertError::OutOfCapacity(element)); + } + + // SAFETY: This is in bounds since `index <=3D len < capacity`. + let p =3D unsafe { self.as_mut_ptr().add(index) }; + // INVARIANT: This breaks the Vec invariants by making `index` con= tain an invalid element, + // but we restore the invariants below. + // SAFETY: Both the src and dst ranges end no later than one eleme= nt after the length. + // Since the length is less than the capacity, both ranges are in = bounds of the allocation. + unsafe { ptr::copy(p, p.add(1), len - index) }; + // INVARIANT: This restores the Vec invariants. + // SAFETY: The pointer is in-bounds of the allocation. + unsafe { ptr::write(p, element) }; + // SAFETY: Index `len` contains a valid element due to the above c= opy and write. + unsafe { self.inc_len(1) }; + Ok(()) + } + /// Removes the last element from a vector and returns it, or `None` i= f it is empty. /// /// # Examples diff --git a/rust/kernel/alloc/kvec/errors.rs b/rust/kernel/alloc/kvec/erro= rs.rs index 06fe696e8bc6612a5e6aa2f6c28b685033acfa2f..348b8d27e102ca34a0d6194ae9d= 00b12c11547b4 100644 --- a/rust/kernel/alloc/kvec/errors.rs +++ b/rust/kernel/alloc/kvec/errors.rs @@ -36,3 +36,26 @@ fn from(_: RemoveError) -> Error { EINVAL } } + +/// Error type for [`Vec::insert_within_capacity`]. +pub enum InsertError { + /// The value could not be inserted because the index is out of bounds. + IndexOutOfBounds(T), + /// The value could not be inserted because the vector is out of capac= ity. + OutOfCapacity(T), +} + +impl Debug for InsertError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + match self { + InsertError::IndexOutOfBounds(_) =3D> write!(f, "Index out of = bounds"), + InsertError::OutOfCapacity(_) =3D> write!(f, "Not enough capac= ity"), + } + } +} + +impl From> for Error { + fn from(_: InsertError) -> Error { + EINVAL + } +} --=20 2.49.0.967.g6a0df3ecc3-goog