From patchwork Mon Mar 17 14:23:51 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14019277 Received: from mail-qk1-f174.google.com (mail-qk1-f174.google.com [209.85.222.174]) (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 32D69157E99; Mon, 17 Mar 2025 14:23:56 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.222.174 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221439; cv=none; b=Ws+oj+/wx6rX6lNp0FwJPLvdVJkeSCP1JOuo1gB4w6UMOzMkdBA8qOX+1+zbngosy7hAMUil3zGpcGqMrFz0KsDcxhpyXNCohZ28Oqiup+IhKSqaX/GMOvLhJz/XD3ofVyOcqDTGDqYp83Kcf/JZa8Z/xUrx+wmBYOBz5AWXXQk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221439; c=relaxed/simple; bh=hUqDrxpSwpP9E50itXENwmGSsydhbnNR1/5lsGr8dMg=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=jqOqE339gQRlISQPCEj/aXFpEFLpBlA35EuzRXS2bKYA4bRnSgpajlNuZFyQWXdmNGz2htTOZeQ+CMwc1s/ScfvaulRNPD71HzNo4yAnuZBkwM7DW2bwYnaUr8gCXQNqD+XHs8p1PGBE2+UnBmD0Exsu3W7oTxMmfyM6MzyDjD0= 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=X2rmOgqG; arc=none smtp.client-ip=209.85.222.174 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="X2rmOgqG" Received: by mail-qk1-f174.google.com with SMTP id af79cd13be357-7c542ffec37so448289485a.2; Mon, 17 Mar 2025 07:23:56 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742221436; x=1742826236; 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=e0rwCqLo0r32XXWfSsHXFhEq1/YRdQfuRGfOXmpf1Ag=; b=X2rmOgqGL0Qphp1qq9sM+jxRFfOHMlwwRO3I7dxRVOm7JAX8noLr/1iJ4M4H/nuIEP qNCszrRBbELZsOJJEtOITFuRApujoIqepuRHwnsJzXPgZxs2Vkbu0QlVJhpriYbMv78o mufhcI1BrkcKkVKf65lkDZFc98eWcgXKADFEnuLtvRQ438JvpR9iLyDp6O0FxhNI8Bde qwcx9+xMoomI0AyvAEObNV7LEcSYjLSvw9bKwwyHA0OYQhPtrik31ZQ8NzSqIxtVbRpx NXenoJzqWjOXOcQtj8u/HhETqKb7cm18VxxKnXxjdFqYsVpTQSg5wzTiqUwMD/lB6iKY UB2Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742221436; x=1742826236; 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=e0rwCqLo0r32XXWfSsHXFhEq1/YRdQfuRGfOXmpf1Ag=; b=gijjrGJXTWDc35xF29x0eilETFZPBYUhK2rUOYYT58Fy5lVGkadgnuJnXo+vjfKeBz KHOPMce+rjeaqbiOr1KyNsMqRO7/f0yhqiw/IQLAkqSBPPj/QylKJvy6O6A9l5c44tV0 SCVE+9tf18l9cVwZ2Dr9goK43BPyNQ04e7jIwBr3m+k1vmvjFnjySJOuigJAZiHUvLiW qtVfT2HItZUuXlDCQZ+MjzMuuChZCUWoXZZ4VHK7g0/UuAPGxCx3gAN407+4Ln/4vkt1 NcgOuhUgMaDBh2DrryVHuAsnHzmEU2bQ8nSd0OycGzy44D4cbS1DPS+aAt+OzcRu4n+Q dm8g== X-Forwarded-Encrypted: i=1; AJvYcCUpM50zNDMh0jmHTeKr7SIDKUG4geELjTmhPECCvuCHfUk2/Cyf8OWrzpBS3mGzgjZ4HHpyGyfFI1SL@vger.kernel.org, AJvYcCUptc8eezgmMRN3D2qbs+T2NfRIx/0M82s34nGFZAL4v9QbchFYJem6wWRLTrdyMIuH8LhrRa+BD8MtN52OKGoY@vger.kernel.org, AJvYcCVtVrCpfycw2O54H2FpDv6GJ3jclxa8MSyqAga4tQ2xwG6VJ1gNzZ7dBmQqAbw6IuDbOLdAlDqKmkDe@vger.kernel.org, AJvYcCX9JcjSHE7fQsK4216fuuewMYzQ7xlzBbsaCvXefBXHjQEp9UzCuWwvBj/ydymsO3TgqTu4NBB2b2/M+bpm@vger.kernel.org, AJvYcCXOBlwMKkm+natgZ7D7t4QMJb1Srn8GI7aSGCJl7oPkXZIdWJz7IE0Cz2fqeKoSq+dylpdQCjrQgQ4HejfjVe8=@vger.kernel.org, AJvYcCXqtz70nvLuGSBVEOf6CIGa528UVOteZLIR18QjNM9W/9DM9EzIeGqvnCjhS6h08MId+bsltfP1/9YwPSg=@vger.kernel.org X-Gm-Message-State: AOJu0YzZUrf9N9F7ivCng0T+Iyd79+/wWMxuf6rRXE+KajjeVLiml6pu 7Wx3FQIvxhQK1hOzlfCr1sF3y0MGZJRaRCNr578+Y3NF2j4atqL3 X-Gm-Gg: ASbGncv3dZGypXVchC/fqNeMqyGBBCZ9EOXUPT03rIB/EaGSHoLc94++d8KQX44OC4O OoNyOZgwJrCAdAjZ/9P6BeMbQQv/HsmzglQWkIJRVx4HAlZlzrn2qKXpQR6McL55YqX4BPZsK1l KBTdhGT441TnywSJ+GaVOwr2Kh/LHuxsf+U/HQZjcor1ov2eN8XbI9VZqKHUw7XCkF05xDBvEIq p2GJwktdFsz1aap9+L0aGGMG6z3i88P12t+guFkzicFRAphgomvIu66LgTEnhvWr9fo4ox8HWrN 3DPmpmFENFrdv4q5m2FVwcGuH9AXdjsdvb4d71t6OVXCo6iKLO6vbbQ6mp5zmbUTqU6Jpl2oUg= = X-Google-Smtp-Source: AGHT+IFbwRJE3tF5G5WYrzWKq9JvMgDWQhfQ91Zvfz64Hy339PZNTzQeIy5WWTHghR6VT2wL2+ZrZA== X-Received: by 2002:a05:620a:24c9:b0:7c5:431f:f5e6 with SMTP id af79cd13be357-7c57c81205amr1542683985a.33.1742221435870; Mon, 17 Mar 2025 07:23:55 -0700 (PDT) Received: from tamird-mac.local ([2600:4041:5be7:7c00:6895:24c6:e898:e320]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-476bb60b13esm54601011cf.6.2025.03.17.07.23.54 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 17 Mar 2025 07:23:55 -0700 (PDT) From: Tamir Duberstein Date: Mon, 17 Mar 2025 10:23:51 -0400 Subject: [PATCH v5 1/6] rust: retain pointer mut-ness in `container_of!` Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250317-ptr-as-ptr-v5-1-5b5f21fa230a@gmail.com> References: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> In-Reply-To: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> To: Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Brendan Higgins , David Gow , Rae Moar , Bjorn Helgaas , Luis Chamberlain , Russ Weight , Rob Herring , Saravana Kannan Cc: linux-kbuild@vger.kernel.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, linux-pci@vger.kernel.org, linux-block@vger.kernel.org, devicetree@vger.kernel.org, Tamir Duberstein X-Mailer: b4 0.15-dev Avoid casting the input pointer to `*const _`, allowing the output pointer to be `*mut` if the input is `*mut`. This allows a number of `*const` to `*mut` conversions to be removed at the cost of slightly worse ergonomics when the macro is used with a reference rather than a pointer; the only example of this was in the macro's own doctest. Reviewed-by: Benno Lossin Reviewed-by: Alice Ryhl Signed-off-by: Tamir Duberstein --- rust/kernel/lib.rs | 5 ++--- rust/kernel/pci.rs | 2 +- rust/kernel/platform.rs | 2 +- rust/kernel/rbtree.rs | 23 ++++++++++------------- 4 files changed, 14 insertions(+), 18 deletions(-) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index c92497c7c655..fc6835cc36a3 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -187,7 +187,7 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! { /// } /// /// let test = Test { a: 10, b: 20 }; -/// let b_ptr = &test.b; +/// let b_ptr: *const _ = &test.b; /// // SAFETY: The pointer points at the `b` field of a `Test`, so the resulting pointer will be /// // in-bounds of the same allocation as `b_ptr`. /// let test_alias = unsafe { container_of!(b_ptr, Test, b) }; @@ -196,9 +196,8 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! { #[macro_export] macro_rules! container_of { ($ptr:expr, $type:ty, $($f:tt)*) => {{ - let ptr = $ptr as *const _ as *const u8; let offset: usize = ::core::mem::offset_of!($type, $($f)*); - ptr.sub(offset) as *const $type + $ptr.byte_sub(offset).cast::<$type>() }} } diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index f7b2743828ae..271a7690a9a0 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -364,7 +364,7 @@ pub unsafe fn from_dev(dev: ARef) -> Self { fn as_raw(&self) -> *mut bindings::pci_dev { // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device` // embedded in `struct pci_dev`. - unsafe { container_of!(self.0.as_raw(), bindings::pci_dev, dev) as _ } + unsafe { container_of!(self.0.as_raw(), bindings::pci_dev, dev) } } /// Returns the PCI vendor ID. diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index 1297f5292ba9..84a4ecc642a1 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -189,7 +189,7 @@ unsafe fn from_dev(dev: ARef) -> Self { fn as_raw(&self) -> *mut bindings::platform_device { // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device` // embedded in `struct platform_device`. - unsafe { container_of!(self.0.as_raw(), bindings::platform_device, dev) }.cast_mut() + unsafe { container_of!(self.0.as_raw(), bindings::platform_device, dev) } } } diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index 1ea25c7092fb..27de954a0889 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -424,7 +424,7 @@ pub fn cursor_lower_bound(&mut self, key: &K) -> Option> while !node.is_null() { // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self` // point to the links field of `Node` objects. - let this = unsafe { container_of!(node, Node, links) }.cast_mut(); + let this = unsafe { container_of!(node, Node, links) }; // SAFETY: `this` is a non-null node so it is valid by the type invariants. let this_key = unsafe { &(*this).key }; // SAFETY: `node` is a non-null node so it is valid by the type invariants. @@ -496,7 +496,7 @@ fn drop(&mut self) { // but it is not observable. The loop invariant is still maintained. // SAFETY: `this` is valid per the loop invariant. - unsafe { drop(KBox::from_raw(this.cast_mut())) }; + unsafe { drop(KBox::from_raw(this)) }; } } } @@ -761,7 +761,7 @@ pub fn remove_current(self) -> (Option, RBTreeNode) { let next = self.get_neighbor_raw(Direction::Next); // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self` // point to the links field of `Node` objects. - let this = unsafe { container_of!(self.current.as_ptr(), Node, links) }.cast_mut(); + let this = unsafe { container_of!(self.current.as_ptr(), Node, links) }; // SAFETY: `this` is valid by the type invariants as described above. let node = unsafe { KBox::from_raw(this) }; let node = RBTreeNode { node }; @@ -806,7 +806,7 @@ fn remove_neighbor(&mut self, direction: Direction) -> Option> unsafe { bindings::rb_erase(neighbor, addr_of_mut!(self.tree.root)) }; // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self` // point to the links field of `Node` objects. - let this = unsafe { container_of!(neighbor, Node, links) }.cast_mut(); + let this = unsafe { container_of!(neighbor, Node, links) }; // SAFETY: `this` is valid by the type invariants as described above. let node = unsafe { KBox::from_raw(this) }; return Some(RBTreeNode { node }); @@ -912,7 +912,7 @@ unsafe fn to_key_value_mut<'b>(node: NonNull) -> (&'b K, &'b unsafe fn to_key_value_raw<'b>(node: NonNull) -> (&'b K, *mut V) { // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self` // point to the links field of `Node` objects. - let this = unsafe { container_of!(node.as_ptr(), Node, links) }.cast_mut(); + let this = unsafe { container_of!(node.as_ptr(), Node, links) }; // SAFETY: The passed `node` is the current node or a non-null neighbor, // thus `this` is valid by the type invariants. let k = unsafe { &(*this).key }; @@ -1021,7 +1021,7 @@ fn next(&mut self) -> Option { // SAFETY: By the type invariant of `IterRaw`, `self.next` is a valid node in an `RBTree`, // and by the type invariant of `RBTree`, all nodes point to the links field of `Node` objects. - let cur = unsafe { container_of!(self.next, Node, links) }.cast_mut(); + let cur = unsafe { container_of!(self.next, Node, links) }; // SAFETY: `self.next` is a valid tree node by the type invariants. self.next = unsafe { bindings::rb_next(self.next) }; @@ -1216,7 +1216,7 @@ pub fn get_mut(&mut self) -> &mut V { // SAFETY: // - `self.node_links` is a valid pointer to a node in the tree. // - We have exclusive access to the underlying tree, and can thus give out a mutable reference. - unsafe { &mut (*(container_of!(self.node_links, Node, links).cast_mut())).value } + unsafe { &mut (*(container_of!(self.node_links, Node, links))).value } } /// Converts the entry into a mutable reference to its value. @@ -1226,7 +1226,7 @@ pub fn into_mut(self) -> &'a mut V { // SAFETY: // - `self.node_links` is a valid pointer to a node in the tree. // - This consumes the `&'a mut RBTree`, therefore it can give out a mutable reference that lives for `'a`. - unsafe { &mut (*(container_of!(self.node_links, Node, links).cast_mut())).value } + unsafe { &mut (*(container_of!(self.node_links, Node, links))).value } } /// Remove this entry from the [`RBTree`]. @@ -1239,9 +1239,7 @@ pub fn remove_node(self) -> RBTreeNode { RBTreeNode { // SAFETY: The node was a node in the tree, but we removed it, so we can convert it // back into a box. - node: unsafe { - KBox::from_raw(container_of!(self.node_links, Node, links).cast_mut()) - }, + node: unsafe { KBox::from_raw(container_of!(self.node_links, Node, links)) }, } } @@ -1272,8 +1270,7 @@ fn replace(self, node: RBTreeNode) -> RBTreeNode { // SAFETY: // - `self.node_ptr` produces a valid pointer to a node in the tree. // - Now that we removed this entry from the tree, we can convert the node to a box. - let old_node = - unsafe { KBox::from_raw(container_of!(self.node_links, Node, links).cast_mut()) }; + let old_node = unsafe { KBox::from_raw(container_of!(self.node_links, Node, links)) }; RBTreeNode { node: old_node } } From patchwork Mon Mar 17 14:23:52 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14019278 Received: from mail-qk1-f178.google.com (mail-qk1-f178.google.com [209.85.222.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 ED465242915; Mon, 17 Mar 2025 14:23:58 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.222.178 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221441; cv=none; b=lzhEMTPhQEcutufR2laVmXyMoTYsFS+dUFnirlvIhHqv7v1/0ieeoC5sE3zozs3TVwER+BwIubKn4ESw1WNKVFLXLJwI3QZs70XVmxNoLSGkrGw3OELgG/yGsE/l0gk3QC1OBBFMWn7zgvoDORFRuSiOVcP2kWaatshF4SJJsB0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221441; c=relaxed/simple; bh=bLj1lCQhwechJ/KYJ981kIYuutyn+Ax5IBNtHzsp3As=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=cvMepV3LgpRU0q9c+wda8g3Ddn3W2EhxsF7XyqcghSmm4+NMY4kgAtbjdffOn8onZ53EtYn4bGSMTWtHbhHHrMvlYp+mXEG7RYCWcSaAK1Kmo/oRh13jX2CPs3Nz+DdonR8SbHDDCVBfp0MiVGdFbh/dH58nyzOXyVbpsBBBAew= 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=GAhYlstJ; arc=none smtp.client-ip=209.85.222.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="GAhYlstJ" Received: by mail-qk1-f178.google.com with SMTP id af79cd13be357-7c554d7dc2aso741734485a.3; Mon, 17 Mar 2025 07:23:58 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742221438; x=1742826238; 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=B41I45ZtntWIGMfCDbZ2RGkAC7sZEShqmrbzHTGpLoI=; b=GAhYlstJq9n00dyBmzpxyNVPPi6GeHb760naKUu+E+Fnx1M87T3jZYdR+j4V2OPNCR rPkGAXPB1/jGkNsvQ2urQSdHWTYYIs8DRwFGqLN3q49o8WepADXnB09s+aMvpS8uoWBa ZlMBrL+ZSWyFAuq8xPObTxggOIov8jlbIL5Tb9gKB0JeorPFNGE+DT8WwgEgkfesxlv5 inA9iuntfFja1acbpBdXaDb/khx7wUKX3O5imcWf0u7xs5+ioes77zE+0dwPb0eRYHNn T+QOqUEdVr+wqVXoJFbY/C3ej7kmWCAvI90tOnCseWWHdqIPk0JdkEXfKttkdv8P4o99 gM3Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742221438; x=1742826238; 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=B41I45ZtntWIGMfCDbZ2RGkAC7sZEShqmrbzHTGpLoI=; b=c+DLQubetTh7eN4Ur5nljFGzgWutOqQbWApcoLIO6BWq5Sv3hsAeOQuoeOkgv4Uw+Z o3yb29tGFY0n2/YdWOkhQ3JKAFRPiHYDm+Z/A9bbQc7BhCX8IPpukzenmtlcMI6otemo ywGXd9z+wapeNSJr5AiBGQrGx9lG82l/c6OorZjYyA/A9uVy2ITz6vXSSsqLRHq+2J+t Iq8VyhhXp6W2nK44+kwVzLe5Ife1QStxkaJZlXpGPDfG/umqLkXfZe7PE3ueP/8fNOVs 9NZ5bUHJgAaC7dtposOyMvC7NlBLraqXvWdviEUBLZSq+xkxEu0l98U42++KP8tJzprt wb0g== X-Forwarded-Encrypted: i=1; AJvYcCUEqqlXzcdlQshSkJLhqKIjp8bdhbXpJ/S9y+TcYA74NNWgaI43YHMFvlgE/ZT1FvGogzeOxtFRF0RMix4=@vger.kernel.org, AJvYcCVJezi0k9EjM3nRq2F6hEklJ5RQy9uPCp2wXkIkIk66MLGt3lP0iVgYll3RglFfcNTJ6f2cW4Kzz0Lz@vger.kernel.org, AJvYcCVgJHP9owVPjnVqYhtRu02tqx0o7Dtzh5olS0um63yQAYRtqe2knxN5TgX7BmDrGLvSGxNSOUmY++sVtSo6rc0=@vger.kernel.org, AJvYcCVp/3msOfoPipa9rKXVUwU4rfcvBqPbmZCVjVnKd8DvKjM1Qq/R59+wBqtFSB19AX726W2qnuT7Aqykxalvdf4F@vger.kernel.org, AJvYcCW0mKqYT6MCyn5nFpiUR0yiN+0V4Hzlra4ydTssXdYSNq+Spoxmi2TSakRQ2YnNZp2WrjTZCdh6OhgUrp3I@vger.kernel.org, AJvYcCXi4YH963+5pIpDWM1jPopwpE+Oj1hdWj1E3e3PjW29tdNWU6jYy16LeQFVHnBGQn9n/6KyC0Jl2w/k@vger.kernel.org X-Gm-Message-State: AOJu0YwwujABmeh5VIfWoVSr8Y9G8U/d3Uksjgm8FiWz+QzWlWpA5/g4 y7XOGVQPaadbzFyTnOMyA8TmmnzMOLH0l8Y/Xg8BGeTlssSBD4C1 X-Gm-Gg: ASbGnctSae7fqsrq0PNA447k9BGJBbQvXc3QJDw6XfpCnDBucB6XjYRRAA7xIZGa3XK qzF8RdUIWCoSqIaUGnQsG+/FUYJfF3oZNCVXG9FRxs4Njo7EaqFhuGGlzvqFoY9xa1p0Pt5qgqt Y6wQIz8ln8W6dq0Afx6EjdKqbvbf0aILfLmEjYwol7y/6oxZiHX+wn3p4YjIspff2vb0nWcPO3O KePqqrVQ3vxFM+e6qRQFsHGNWZGvcOwfoCuMWhm5DHKKQPDQF3X7n+k8fTAuczSJfHgzns2tdeL Mj856AKYPY4B0c0fqnJnje4UdCE91y54bN4ZnyIIw2HZ3GbkTzPK57kOOidQezrD1En1oBUFnA= = X-Google-Smtp-Source: AGHT+IEoXsnrwxN2Xi8oaVHqyWOXYptgcezswkKcTzWLcM7lNNw1zTK/Y02tYLv9pB6wW5ntdpkMVQ== X-Received: by 2002:a05:620a:4386:b0:7c3:d5a4:3df3 with SMTP id af79cd13be357-7c57c80f0fbmr1501704685a.34.1742221437530; Mon, 17 Mar 2025 07:23:57 -0700 (PDT) Received: from tamird-mac.local ([2600:4041:5be7:7c00:6895:24c6:e898:e320]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-476bb60b13esm54601011cf.6.2025.03.17.07.23.56 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 17 Mar 2025 07:23:56 -0700 (PDT) From: Tamir Duberstein Date: Mon, 17 Mar 2025 10:23:52 -0400 Subject: [PATCH v5 2/6] rust: enable `clippy::ptr_as_ptr` lint Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250317-ptr-as-ptr-v5-2-5b5f21fa230a@gmail.com> References: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> In-Reply-To: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> To: Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Brendan Higgins , David Gow , Rae Moar , Bjorn Helgaas , Luis Chamberlain , Russ Weight , Rob Herring , Saravana Kannan Cc: linux-kbuild@vger.kernel.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, linux-pci@vger.kernel.org, linux-block@vger.kernel.org, devicetree@vger.kernel.org, Tamir Duberstein X-Mailer: b4 0.15-dev In Rust 1.51.0, Clippy introduced the `ptr_as_ptr` lint [1]: > Though `as` casts between raw pointers are not terrible, > `pointer::cast` is safer because it cannot accidentally change the > pointer's mutability, nor cast the pointer to other types like `usize`. There are a few classes of changes required: - Modules generated by bindgen are marked `#[allow(clippy::ptr_as_ptr)]`. - Inferred casts (` as _`) are replaced with `.cast()`. - Ascribed casts (` as *... T`) are replaced with `.cast::()`. - Multistep casts from references (` as *const _ as *const T`) are replaced with `let x: *const _ = &x;` and `.cast()` or `.cast::()` according to the previous rules. The intermediate `let` binding is required because `(x as *const _).cast::()` results in inference failure. - Native literal C strings are replaced with `c_str!().as_char_ptr()`. - `*mut *mut T as _` is replaced with `let *mut *const T = (*mut *mut T)`.cast();` since pointer to pointer can be confusing. Apply these changes and enable the lint -- no functional change intended. Link: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr [1] Reviewed-by: Benno Lossin Signed-off-by: Tamir Duberstein --- Makefile | 1 + rust/bindings/lib.rs | 1 + rust/kernel/alloc/allocator_test.rs | 2 +- rust/kernel/alloc/kvec.rs | 4 ++-- rust/kernel/device.rs | 5 +++-- rust/kernel/devres.rs | 2 +- rust/kernel/error.rs | 2 +- rust/kernel/firmware.rs | 3 ++- rust/kernel/fs/file.rs | 2 +- rust/kernel/kunit.rs | 15 +++++++-------- rust/kernel/list/impl_list_item_mod.rs | 2 +- rust/kernel/pci.rs | 2 +- rust/kernel/platform.rs | 4 +++- rust/kernel/print.rs | 11 +++++------ rust/kernel/seq_file.rs | 3 ++- rust/kernel/str.rs | 2 +- rust/kernel/sync/poll.rs | 2 +- rust/kernel/workqueue.rs | 10 +++++----- rust/uapi/lib.rs | 1 + 19 files changed, 40 insertions(+), 34 deletions(-) diff --git a/Makefile b/Makefile index 70bdbf2218fc..ec8efc8e23ba 100644 --- a/Makefile +++ b/Makefile @@ -483,6 +483,7 @@ export rust_common_flags := --edition=2021 \ -Wclippy::needless_continue \ -Aclippy::needless_lifetimes \ -Wclippy::no_mangle_with_rust_abi \ + -Wclippy::ptr_as_ptr \ -Wclippy::undocumented_unsafe_blocks \ -Wclippy::unnecessary_safety_comment \ -Wclippy::unnecessary_safety_doc \ diff --git a/rust/bindings/lib.rs b/rust/bindings/lib.rs index 014af0d1fc70..0486a32ed314 100644 --- a/rust/bindings/lib.rs +++ b/rust/bindings/lib.rs @@ -25,6 +25,7 @@ )] #[allow(dead_code)] +#[allow(clippy::ptr_as_ptr)] #[allow(clippy::undocumented_unsafe_blocks)] mod bindings_raw { // Manual definition for blocklisted types. diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index c37d4c0c64e9..8017aa9d5213 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -82,7 +82,7 @@ unsafe fn realloc( // SAFETY: Returns either NULL or a pointer to a memory allocation that satisfies or // exceeds the given size and alignment requirements. - let dst = unsafe { libc_aligned_alloc(layout.align(), layout.size()) } as *mut u8; + let dst = unsafe { libc_aligned_alloc(layout.align(), layout.size()) }.cast::(); let dst = NonNull::new(dst).ok_or(AllocError)?; if flags.contains(__GFP_ZERO) { diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index ae9d072741ce..c12844764671 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -262,7 +262,7 @@ pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is // guaranteed to be part of the same allocated object. // - `self.len` can not overflow `isize`. - let ptr = unsafe { self.as_mut_ptr().add(self.len) } as *mut MaybeUninit; + let ptr = unsafe { self.as_mut_ptr().add(self.len) }.cast::>(); // SAFETY: The memory between `self.len` and `self.capacity` is guaranteed to be allocated // and valid, but uninitialized. @@ -554,7 +554,7 @@ fn drop(&mut self) { // - `ptr` points to memory with at least a size of `size_of::() * len`, // - all elements within `b` are initialized values of `T`, // - `len` does not exceed `isize::MAX`. - unsafe { Vec::from_raw_parts(ptr as _, len, len) } + unsafe { Vec::from_raw_parts(ptr.cast(), len, len) } } } diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs index db2d9658ba47..9e500498835d 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -168,16 +168,17 @@ pub fn pr_dbg(&self, args: fmt::Arguments<'_>) { /// `KERN_*`constants, for example, `KERN_CRIT`, `KERN_ALERT`, etc. #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))] unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) { + let msg: *const _ = &msg; // SAFETY: `klevel` is null-terminated and one of the kernel constants. `self.as_raw` // is valid because `self` is valid. The "%pA" format string expects a pointer to // `fmt::Arguments`, which is what we're passing as the last argument. #[cfg(CONFIG_PRINTK)] unsafe { bindings::_dev_printk( - klevel as *const _ as *const crate::ffi::c_char, + klevel.as_ptr().cast::(), self.as_raw(), c_str!("%pA").as_char_ptr(), - &msg as *const _ as *const crate::ffi::c_void, + msg.cast::(), ) }; } diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 942376f6f3af..3a9d998ec371 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -157,7 +157,7 @@ fn remove_action(this: &Arc) { #[allow(clippy::missing_safety_doc)] unsafe extern "C" fn devres_callback(ptr: *mut kernel::ffi::c_void) { - let ptr = ptr as *mut DevresInner; + let ptr = ptr.cast::>(); // Devres owned this memory; now that we received the callback, drop the `Arc` and hence the // reference. // SAFETY: Safe, since we leaked an `Arc` reference to devm_add_action() in diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 376f6a6ae5e3..8eca5be30f2c 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -152,7 +152,7 @@ pub(crate) fn to_blk_status(self) -> bindings::blk_status_t { /// Returns the error encoded as a pointer. pub fn to_ptr(self) -> *mut T { // SAFETY: `self.0` is a valid error due to its invariant. - unsafe { bindings::ERR_PTR(self.0.get() as _) as *mut _ } + unsafe { bindings::ERR_PTR(self.0.get() as _).cast() } } /// Returns a string representing the error, if one exists. diff --git a/rust/kernel/firmware.rs b/rust/kernel/firmware.rs index c5162fdc95ff..74df815d2f4e 100644 --- a/rust/kernel/firmware.rs +++ b/rust/kernel/firmware.rs @@ -58,10 +58,11 @@ impl Firmware { fn request_internal(name: &CStr, dev: &Device, func: FwFunc) -> Result { let mut fw: *mut bindings::firmware = core::ptr::null_mut(); let pfw: *mut *mut bindings::firmware = &mut fw; + let pfw: *mut *const bindings::firmware = pfw.cast(); // SAFETY: `pfw` is a valid pointer to a NULL initialized `bindings::firmware` pointer. // `name` and `dev` are valid as by their type invariants. - let ret = unsafe { func.0(pfw as _, name.as_char_ptr(), dev.as_raw()) }; + let ret = unsafe { func.0(pfw, name.as_char_ptr(), dev.as_raw()) }; if ret != 0 { return Err(Error::from_errno(ret)); } diff --git a/rust/kernel/fs/file.rs b/rust/kernel/fs/file.rs index ed57e0137cdb..9e2639aee61a 100644 --- a/rust/kernel/fs/file.rs +++ b/rust/kernel/fs/file.rs @@ -364,7 +364,7 @@ fn deref(&self) -> &LocalFile { // // By the type invariants, there are no `fdget_pos` calls that did not take the // `f_pos_lock` mutex. - unsafe { LocalFile::from_raw_file(self as *const File as *const bindings::file) } + unsafe { LocalFile::from_raw_file((self as *const Self).cast()) } } } diff --git a/rust/kernel/kunit.rs b/rust/kernel/kunit.rs index 824da0e9738a..7ed2063c1af0 100644 --- a/rust/kernel/kunit.rs +++ b/rust/kernel/kunit.rs @@ -8,19 +8,20 @@ use core::{ffi::c_void, fmt}; +#[cfg(CONFIG_PRINTK)] +use crate::c_str; + /// Prints a KUnit error-level message. /// /// Public but hidden since it should only be used from KUnit generated code. #[doc(hidden)] pub fn err(args: fmt::Arguments<'_>) { + let args: *const _ = &args; // SAFETY: The format string is null-terminated and the `%pA` specifier matches the argument we // are passing. #[cfg(CONFIG_PRINTK)] unsafe { - bindings::_printk( - c"\x013%pA".as_ptr() as _, - &args as *const _ as *const c_void, - ); + bindings::_printk(c_str!("\x013%pA").as_char_ptr(), args.cast::()); } } @@ -29,14 +30,12 @@ pub fn err(args: fmt::Arguments<'_>) { /// Public but hidden since it should only be used from KUnit generated code. #[doc(hidden)] pub fn info(args: fmt::Arguments<'_>) { + let args: *const _ = &args; // SAFETY: The format string is null-terminated and the `%pA` specifier matches the argument we // are passing. #[cfg(CONFIG_PRINTK)] unsafe { - bindings::_printk( - c"\x016%pA".as_ptr() as _, - &args as *const _ as *const c_void, - ); + bindings::_printk(c_str!("\x016%pA").as_char_ptr(), args.cast::()); } } diff --git a/rust/kernel/list/impl_list_item_mod.rs b/rust/kernel/list/impl_list_item_mod.rs index a0438537cee1..1f9498c1458f 100644 --- a/rust/kernel/list/impl_list_item_mod.rs +++ b/rust/kernel/list/impl_list_item_mod.rs @@ -34,7 +34,7 @@ pub unsafe trait HasListLinks { unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut ListLinks { // SAFETY: The caller promises that the pointer is valid. The implementer promises that the // `OFFSET` constant is correct. - unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut ListLinks } + unsafe { ptr.cast::().add(Self::OFFSET).cast() } } } diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index 271a7690a9a0..003c9aaafb24 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -75,7 +75,7 @@ extern "C" fn probe_callback( // Let the `struct pci_dev` own a reference of the driver's private data. // SAFETY: By the type invariant `pdev.as_raw` returns a valid pointer to a // `struct pci_dev`. - unsafe { bindings::pci_set_drvdata(pdev.as_raw(), data.into_foreign() as _) }; + unsafe { bindings::pci_set_drvdata(pdev.as_raw(), data.into_foreign().cast()) }; } Err(err) => return Error::to_errno(err), } diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index 84a4ecc642a1..26b2502970ef 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -66,7 +66,9 @@ extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ff // Let the `struct platform_device` own a reference of the driver's private data. // SAFETY: By the type invariant `pdev.as_raw` returns a valid pointer to a // `struct platform_device`. - unsafe { bindings::platform_set_drvdata(pdev.as_raw(), data.into_foreign() as _) }; + unsafe { + bindings::platform_set_drvdata(pdev.as_raw(), data.into_foreign().cast()) + }; } Err(err) => return Error::to_errno(err), } diff --git a/rust/kernel/print.rs b/rust/kernel/print.rs index cf4714242e14..8ae57d2cd36c 100644 --- a/rust/kernel/print.rs +++ b/rust/kernel/print.rs @@ -25,7 +25,7 @@ // SAFETY: The C contract guarantees that `buf` is valid if it's less than `end`. let mut w = unsafe { RawFormatter::from_ptrs(buf.cast(), end.cast()) }; // SAFETY: TODO. - let _ = w.write_fmt(unsafe { *(ptr as *const fmt::Arguments<'_>) }); + let _ = w.write_fmt(unsafe { *ptr.cast::>() }); w.pos().cast() } @@ -102,6 +102,7 @@ pub unsafe fn call_printk( module_name: &[u8], args: fmt::Arguments<'_>, ) { + let args: *const _ = &args; // `_printk` does not seem to fail in any path. #[cfg(CONFIG_PRINTK)] // SAFETY: TODO. @@ -109,7 +110,7 @@ pub unsafe fn call_printk( bindings::_printk( format_string.as_ptr(), module_name.as_ptr(), - &args as *const _ as *const c_void, + args.cast::(), ); } } @@ -122,15 +123,13 @@ pub unsafe fn call_printk( #[doc(hidden)] #[cfg_attr(not(CONFIG_PRINTK), allow(unused_variables))] pub fn call_printk_cont(args: fmt::Arguments<'_>) { + let args: *const _ = &args; // `_printk` does not seem to fail in any path. // // SAFETY: The format string is fixed. #[cfg(CONFIG_PRINTK)] unsafe { - bindings::_printk( - format_strings::CONT.as_ptr(), - &args as *const _ as *const c_void, - ); + bindings::_printk(format_strings::CONT.as_ptr(), args.cast::()); } } diff --git a/rust/kernel/seq_file.rs b/rust/kernel/seq_file.rs index 4c03881a9eba..d7a530d3eb07 100644 --- a/rust/kernel/seq_file.rs +++ b/rust/kernel/seq_file.rs @@ -31,12 +31,13 @@ pub unsafe fn from_raw<'a>(ptr: *mut bindings::seq_file) -> &'a SeqFile { /// Used by the [`seq_print`] macro. pub fn call_printf(&self, args: core::fmt::Arguments<'_>) { + let args: *const _ = &args; // SAFETY: Passing a void pointer to `Arguments` is valid for `%pA`. unsafe { bindings::seq_printf( self.inner.get(), c_str!("%pA").as_char_ptr(), - &args as *const _ as *const crate::ffi::c_void, + args.cast::(), ); } } diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 28e2201604d6..6a1a982b946d 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -191,7 +191,7 @@ pub unsafe fn from_char_ptr<'a>(ptr: *const crate::ffi::c_char) -> &'a Self { // to a `NUL`-terminated C string. let len = unsafe { bindings::strlen(ptr) } + 1; // SAFETY: Lifetime guaranteed by the safety precondition. - let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len) }; + let bytes = unsafe { core::slice::from_raw_parts(ptr.cast(), len) }; // SAFETY: As `len` is returned by `strlen`, `bytes` does not contain interior `NUL`. // As we have added 1 to `len`, the last byte is known to be `NUL`. unsafe { Self::from_bytes_with_nul_unchecked(bytes) } diff --git a/rust/kernel/sync/poll.rs b/rust/kernel/sync/poll.rs index e105477a3cb1..d04d90486b09 100644 --- a/rust/kernel/sync/poll.rs +++ b/rust/kernel/sync/poll.rs @@ -73,7 +73,7 @@ pub fn register_wait(&mut self, file: &File, cv: &PollCondVar) { // be destroyed, the destructor must run. That destructor first removes all waiters, // and then waits for an rcu grace period. Therefore, `cv.wait_queue_head` is valid for // long enough. - unsafe { qproc(file.as_ptr() as _, cv.wait_queue_head.get(), self.0.get()) }; + unsafe { qproc(file.as_ptr().cast(), cv.wait_queue_head.get(), self.0.get()) }; } } } diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 0cd100d2aefb..8ff54105be3f 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -170,7 +170,7 @@ impl Queue { pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> &'a Queue { // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The // caller promises that the pointer is not dangling. - unsafe { &*(ptr as *const Queue) } + unsafe { &*ptr.cast::() } } /// Enqueues a work item. @@ -457,7 +457,7 @@ fn get_work_offset(&self) -> usize { #[inline] unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work { // SAFETY: The caller promises that the pointer is valid. - unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work } + unsafe { ptr.cast::().add(Self::OFFSET).cast::>() } } /// Returns a pointer to the struct containing the [`Work`] field. @@ -472,7 +472,7 @@ unsafe fn work_container_of(ptr: *mut Work) -> *mut Self { // SAFETY: The caller promises that the pointer points at a field of the right type in the // right kind of struct. - unsafe { (ptr as *mut u8).sub(Self::OFFSET) as *mut Self } + unsafe { ptr.cast::().sub(Self::OFFSET).cast::() } } } @@ -538,7 +538,7 @@ unsafe impl WorkItemPointer for Arc { unsafe extern "C" fn run(ptr: *mut bindings::work_struct) { // The `__enqueue` method always uses a `work_struct` stored in a `Work`. - let ptr = ptr as *mut Work; + let ptr = ptr.cast::>(); // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. let ptr = unsafe { T::work_container_of(ptr) }; // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. @@ -591,7 +591,7 @@ unsafe impl WorkItemPointer for Pin> { unsafe extern "C" fn run(ptr: *mut bindings::work_struct) { // The `__enqueue` method always uses a `work_struct` stored in a `Work`. - let ptr = ptr as *mut Work; + let ptr = ptr.cast::>(); // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. let ptr = unsafe { T::work_container_of(ptr) }; // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. diff --git a/rust/uapi/lib.rs b/rust/uapi/lib.rs index 13495910271f..fe9bf7b5a306 100644 --- a/rust/uapi/lib.rs +++ b/rust/uapi/lib.rs @@ -15,6 +15,7 @@ #![allow( clippy::all, clippy::undocumented_unsafe_blocks, + clippy::ptr_as_ptr, dead_code, missing_docs, non_camel_case_types, From patchwork Mon Mar 17 14:23:53 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14019279 Received: from mail-qt1-f179.google.com (mail-qt1-f179.google.com [209.85.160.179]) (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 3F5BB245026; Mon, 17 Mar 2025 14:23:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.179 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221442; cv=none; b=Vy+CqoFYYW4IevVR6tK7sbWlJB11oI0TGzQccXwZuy5DjZVWNbZrFzh5joCROGwJAOeOJGNR9grJ4IcscaRJV57ajO1PPo+GJdNNwDy2mTUYumbVYRL9q4UkIMzpyQxgP2LCvbksopuSD7sP5UMYhm7d4DAVBOCvq6wGWKCO+yg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221442; c=relaxed/simple; bh=/r0m5YzIWWRQazZFOJwTQSRLej9n6gB2sGQQ7S4a1Yg=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=Ci92zCBLQ4/dbxZAFy8aveTqzYUXL/Xz17EPREKYcK6N/7qZ8hM/LCoQmElrii3lOHfOpoZd6LJHl6mm3HSJ9hfMrlJTjNwJ9p/MIE72JFxCkXejFmL2rXgmpLnNmvwmrZfytr/08AXbkJBSMU+FT5sdPpTrR4xc6qnWzdOcyRg= 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=keyNMPyV; arc=none smtp.client-ip=209.85.160.179 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="keyNMPyV" Received: by mail-qt1-f179.google.com with SMTP id d75a77b69052e-4766cb762b6so41789061cf.0; Mon, 17 Mar 2025 07:23:59 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742221439; x=1742826239; 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=3pDD8iTOqsV2dG/t13s+olVTpQHy7nswKrZLCkN6NIk=; b=keyNMPyVmv90F+WY2dK58NX1eF3UmlAOBoOzRZSANeWZUycu2nsiPo71SRqiGfgLz9 +z+7r/ciFj0FfuMcEhFYdrC8ESOSc7eagR6u9W+Wn+DJmUf24yiiJ7HNm3KsIRlwdFn5 yJ6io4/WUfHHVuL0vn1shCQkNoF4kSQtp2rkE2aiCJVCJ5VnUHKXbJRi/OrM+6wivW4B CafkrymxuFsLYqqXExex49ZhK0PzB1dSnKMcXAIlopl8tklhHmGnJec6iRRswiG+WRZj swhHLtGPoe/dgT9Bw3LVJEsVLQdinfhdphYL8vqzW5GKmW5SGt20sDE8uLPTFr5RE3H+ MB3A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742221439; x=1742826239; 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=3pDD8iTOqsV2dG/t13s+olVTpQHy7nswKrZLCkN6NIk=; b=TrcZdZof+HoO884Ns1rwdMYyVcapAA1sU3dNW5knR7eLOwYxhdwxespYhch1GVbyuu 9sicqa5ZRgNmS6LffRSkVbCRsw1TTQ2n+615sr27+4ReaJNkzgtsj+EOlXLQx6/0HXls 3AbZvlmvD5NSFbjcPpcWHWkjBJEh9fED/ksudv33Z4HS/Fmqq5f8NA6eVWP+CsFSdZPY WWxb7go1x3AGNHkzKq/yrEVGl0tN2LvGFhlu0v+RvcdPj45nZfsRFuKngZOnsEEfInRh zxQjhC2gg3ZgzoxOQ+ljBmobCkLXsH+H7tlJTIBoFfRXg2RsMn09o8Htkq+TnV++h+rI 4m7w== X-Forwarded-Encrypted: i=1; AJvYcCUCNKk1jHTu1GruWuyF3lPN2kiJn6UD7KTAF5eoQJIlP8B7kR4KO0Y/HII760l54jaqmx9aG9/nGrLm@vger.kernel.org, AJvYcCUQioMXBa8+Nfqtx4a1tQ7INY3z2aO2B8dlwIH7mdDOWfsLMzv6K12q4dPtwZkbxNoqPl61aznAKvzuI01M@vger.kernel.org, AJvYcCUU75vpHvsHcwvUc9j9HDIM1vaDJrhfsBv7DGnWTlH72CWm3Cb2+VNIGq92R7VRf/Km3YISe0cDTEohE8e9tT6/@vger.kernel.org, AJvYcCUirkVT44GznVLAkDAocpZTKA2YhSR7NS5GfulLhYR8pYAgPIzqPJincwqQ8rIt/ZBUkHxMSt22CDliz4Q=@vger.kernel.org, AJvYcCVGdtV5Rj/iMjf6XY7Oztz2FSTkud0D/geB5e/yNpeuCL7FcKkMnzkMkLRUTwBcbGD3SrsGuGHX+LsK+/9YdOM=@vger.kernel.org, AJvYcCWBWSqPphH47uKp/0swo3b316OGQXzZ60D3OpmGtFZDUXms55rjFqz2OUEf43dRoRnLLjx7JRZcurua@vger.kernel.org X-Gm-Message-State: AOJu0YzGBq9xHzqOSZS8t6BkgDK0bKRhKyKM/pNOtLFGAqUDbERbU+dF kxeF8kNSqxPIQr5LayDobHQM4a/ofbV/32syhZ6Vc79LL0o6i63t X-Gm-Gg: ASbGncsldHdHobFnJ92D2frseNM+hl4wRgnBWovtLrX6iY2feHipkO7+zWU33kpHtgS DTdqSHZ/ZjDMrzeVi7ExDZvVUMUvCBZDdWyDDGoBPHhAYTdvPmbzkgtQtAxoxntJns2FrQkUD/D xoIvD954+4VWeSVn8zO2+fz7SMiaTcJw/lclGbxs3WKZdpYirP0pjuUuA/7IgJcOX+mfC3W2hgp /Iw+u0dOPNao5lK26udnczwzegV4JbN8awcG2oDhAGbrMzXJIsRN5v9P4RCkfSBsZVq+eOcbAfl R9dqMNRTHe7Vjv2J2Jm02PYQ9MsvCuu/DHzIFpnNk7379UrJje9SKaMWGCgzaHIto+CIUJqQbw= = X-Google-Smtp-Source: AGHT+IFRlDG35n4MDH7v/SCuYgNy5RJhqN2IH/eGOc1MDtnnqVTwWyf0e4O3awIHjyo7Fk1WiLgD/Q== X-Received: by 2002:ac8:598c:0:b0:471:825d:aa52 with SMTP id d75a77b69052e-476c93243b8mr162288801cf.20.1742221439007; Mon, 17 Mar 2025 07:23:59 -0700 (PDT) Received: from tamird-mac.local ([2600:4041:5be7:7c00:6895:24c6:e898:e320]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-476bb60b13esm54601011cf.6.2025.03.17.07.23.57 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 17 Mar 2025 07:23:58 -0700 (PDT) From: Tamir Duberstein Date: Mon, 17 Mar 2025 10:23:53 -0400 Subject: [PATCH v5 3/6] rust: enable `clippy::ptr_cast_constness` lint Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250317-ptr-as-ptr-v5-3-5b5f21fa230a@gmail.com> References: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> In-Reply-To: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> To: Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Brendan Higgins , David Gow , Rae Moar , Bjorn Helgaas , Luis Chamberlain , Russ Weight , Rob Herring , Saravana Kannan Cc: linux-kbuild@vger.kernel.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, linux-pci@vger.kernel.org, linux-block@vger.kernel.org, devicetree@vger.kernel.org, Tamir Duberstein X-Mailer: b4 0.15-dev In Rust 1.72.0, Clippy introduced the `ptr_cast_constness` lint [1]: > Though `as` casts between raw pointers are not terrible, > `pointer::cast_mut` and `pointer::cast_const` are safer because they > cannot accidentally cast the pointer to another type. There are only 2 affected sites: - `*mut T as *const U as *mut U` becomes `(*mut T).cast()` - `&self as *const Self as *mut Self` becomes a reference-to-pointer coercion + `(*const Self).cast()`. Apply these changes and enable the lint -- no functional change intended. Link: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_cast_constness [1] Reviewed-by: Benno Lossin Signed-off-by: Tamir Duberstein --- Makefile | 1 + rust/kernel/block/mq/request.rs | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index ec8efc8e23ba..c62bae2b107b 100644 --- a/Makefile +++ b/Makefile @@ -484,6 +484,7 @@ export rust_common_flags := --edition=2021 \ -Aclippy::needless_lifetimes \ -Wclippy::no_mangle_with_rust_abi \ -Wclippy::ptr_as_ptr \ + -Wclippy::ptr_cast_constness \ -Wclippy::undocumented_unsafe_blocks \ -Wclippy::unnecessary_safety_comment \ -Wclippy::unnecessary_safety_doc \ diff --git a/rust/kernel/block/mq/request.rs b/rust/kernel/block/mq/request.rs index 7943f43b9575..10c6d69be7f3 100644 --- a/rust/kernel/block/mq/request.rs +++ b/rust/kernel/block/mq/request.rs @@ -69,7 +69,7 @@ pub(crate) unsafe fn aref_from_raw(ptr: *mut bindings::request) -> ARef { // INVARIANT: By the safety requirements of this function, invariants are upheld. // SAFETY: By the safety requirement of this function, we own a // reference count that we can pass to `ARef`. - unsafe { ARef::from_raw(NonNull::new_unchecked(ptr as *const Self as *mut Self)) } + unsafe { ARef::from_raw(NonNull::new_unchecked(ptr.cast())) } } /// Notify the block layer that a request is going to be processed now. @@ -151,11 +151,12 @@ pub(crate) unsafe fn wrapper_ptr(this: *mut Self) -> NonNull /// Return a reference to the [`RequestDataWrapper`] stored in the private /// area of the request structure. pub(crate) fn wrapper_ref(&self) -> &RequestDataWrapper { + let this: *const _ = self; // SAFETY: By type invariant, `self.0` is a valid allocation. Further, // the private data associated with this request is initialized and // valid. The existence of `&self` guarantees that the private data is // valid as a shared reference. - unsafe { Self::wrapper_ptr(self as *const Self as *mut Self).as_ref() } + unsafe { Self::wrapper_ptr(this.cast_mut()).as_ref() } } } From patchwork Mon Mar 17 14:23:54 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14019280 Received: from mail-qt1-f170.google.com (mail-qt1-f170.google.com [209.85.160.170]) (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 E7C222459FC; Mon, 17 Mar 2025 14:24:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.170 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221443; cv=none; b=NN/2jWX+etER5VoyXMD2ao4ZCmUq63C1rqLy82EaCKMLAxM9xzA+DOX6cPLRw+hb6kSFOAKFcsmVNcvDthWDbh25vbY6Ftr2mEzOwxcWeDEm/O2nVR0OcJPH98FXB4newWeF5ngpFpxTLZqm08qGWgzqfi8yx98GmTxESE2SMnw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221443; c=relaxed/simple; bh=eOC8GNYrVfiMmJjIlMnjsi5R6euOkfd+217Ym/0TGMU=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=IoVyGyyyqVoBS3295NxdXNzTZdO1CISN3Fbaw+S1DA1kW/EtOxODYPLmgsoW0V6aup69FUMxEjU7b8PtIfzxpNbZTavmCH1Lr535vBCx051kZXmqYxlXHxTMO2UINILm/HsKyMJf8G2O1lOYspvqVwYzWtlZR1qeq0yszjVqp90= 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=SmrGf//d; arc=none smtp.client-ip=209.85.160.170 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="SmrGf//d" Received: by mail-qt1-f170.google.com with SMTP id d75a77b69052e-4766631a6a4so45528291cf.2; Mon, 17 Mar 2025 07:24:01 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742221441; x=1742826241; 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=0DKJLM7Z9Stu40Q/kKnTtPbAzpv2yQ1EFXVOPNeWeiM=; b=SmrGf//dlRODNS3EFkIRINdwG8DOrAw57F9551SDb4NCdCXzNEGGxdnW+GL6q2OueE 7nX4W1mI1DU+RwOPUiL4nTGiEPuHItFdjwP8jE9I3xjvjj6aAmbDU3lpLGlrTIHvttWw j65OOz9ZtA0gopYXdNWc+gqy6qHny+IxXk9avScdkFsFZfv+8v2w1KsvXB7MZO+MuAcI ze/ckKEtZcNU/RrlT42eZILcNLqOoORhyXYZagifgwjUu5cMBLota0Ry4zI9/0370hsK QDR4K9tvGH3ZWQO/XjDUphC9VFtAklaA3NHpitcVW3jpGkaVb8NwgPkVJ0OESgYUDe3e +8MA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742221441; x=1742826241; 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=0DKJLM7Z9Stu40Q/kKnTtPbAzpv2yQ1EFXVOPNeWeiM=; b=FkPSBoZTPv6o46+UWLLqDKhJ1IRTRJpcGmoIYd8yBqYkJHrD3t86vUf5elac/o2PVG MMDoiLCjPTQVqWPuQjRtujmellzU+sCHmeqksvfymaj2ofRYD5HHrnP45p6OKyB0q4fn EeGoUnTt/KqXiMdK9JGdBiFty3YoCssvz5Uy1xTmRObQfezyZ7Uvr5iYTY0TetgpSKB0 Z9th8oE8ut+6rAZPUjJQNUOM2QEMiLLM5rdoRq3OYVZk6XjfnGKbHixbMwbfaIK9us/8 vS9CxF+2D4dxgQJubu9z5AK7FWgztKwFZiVqfCNpa86tiYMlFZB9YBIY1md3dCxtfrKr dzhA== X-Forwarded-Encrypted: i=1; AJvYcCWSp049ViGwcxu2vKZc4Hy4FtnHpwY60luFV8i3PN0ze0li0xCtQhexNp1dQDRg98/qlDQMvN9EmrfK@vger.kernel.org, AJvYcCWo0OF/VZmbQ8neKKexdGZuqOKiLkOgev1Kq2/Wnqk3uFZJrWQOrltnTjrUZbMxgGe/YrcPMw5wCOYNDNI=@vger.kernel.org, AJvYcCWsYJx7gJZfiK2CEdPWGFcgtd44QRi/2mhtjYOwTUN9A61IU4pES6lPA6yD3UTZwxD7ZlTnzDQ0U7mvTCBtsyQ=@vger.kernel.org, AJvYcCXTsvL1lqEzkd1H9wPyZPFRVu8tjhIl8BkgM5AzvyBUM3ltzdc8AYhyp1t0sI/TlcO77wUwSno15lY4m6np@vger.kernel.org, AJvYcCXc7fgww3diUp0HeraP3Nr7JYPfLbxLaH4J7CvHhjtz4iFbU8EZDECu9+QDTOvPByfdhgX63ED666PT@vger.kernel.org, AJvYcCXguZg9RS9PYj4zQrAhcPU94mDEXTVFIzk8OjB7mnT1DeTAC73yztOWK5gAiPvrwYccezVNOu91hRBC/VYisiZG@vger.kernel.org X-Gm-Message-State: AOJu0YyTDsrFiBHAyeWWmUNv1rjf6mipM/f2INWRcaefJspkR1y/B+DF XAjQSRio5Q0U8yL1IldwRnGQbTqo3J8wv37TXAB5a7+cGU448OxK70rxlO6DSog= X-Gm-Gg: ASbGncvmQ8Pat1Rw4MKL8HY6D2wsdv8MrufeX6j4+IJBDToIoJYsY+suW7fefkGIzr1 7LHXOzgf1z782BB6wYlU79MO3xBKAQWu3bk/XNLlGR7wkBEnOUZjVrB1FmkQuDsM+Sd12biddId sNBKF2bnpiGeC+mrLceOTBpJVnKDpYwvE/nDRa7Yb+HbLclWdA/z8P5Sr/4tLAu6vznuQAzkN6D enOgDzY3d4TqCUXtzyeVIy3HHiPzexfVYa+HlGqdZ0N9RQGmvu8jcoZvw7DseAkpJzGXW8YKQvE uGX1fBIC5agQfyjLqH0pj3gcWRP8S7fm0IubuNoBONnWOutuamFi0lzxn2aFmGk2efw5PSvRPA= = X-Google-Smtp-Source: AGHT+IGW4rw89ZFFbVEcn+X1uJyv5hQbpNSEeeMe8/EJAtes1dgkOySMbKI6jcF0Eq27FoJF6gAMEg== X-Received: by 2002:a05:622a:4c8:b0:476:838c:b0ce with SMTP id d75a77b69052e-476c812caa7mr238396871cf.13.1742221440614; Mon, 17 Mar 2025 07:24:00 -0700 (PDT) Received: from tamird-mac.local ([2600:4041:5be7:7c00:6895:24c6:e898:e320]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-476bb60b13esm54601011cf.6.2025.03.17.07.23.59 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 17 Mar 2025 07:24:00 -0700 (PDT) From: Tamir Duberstein Date: Mon, 17 Mar 2025 10:23:54 -0400 Subject: [PATCH v5 4/6] rust: enable `clippy::as_ptr_cast_mut` lint Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250317-ptr-as-ptr-v5-4-5b5f21fa230a@gmail.com> References: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> In-Reply-To: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> To: Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Brendan Higgins , David Gow , Rae Moar , Bjorn Helgaas , Luis Chamberlain , Russ Weight , Rob Herring , Saravana Kannan Cc: linux-kbuild@vger.kernel.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, linux-pci@vger.kernel.org, linux-block@vger.kernel.org, devicetree@vger.kernel.org, Tamir Duberstein X-Mailer: b4 0.15-dev In Rust 1.66.0, Clippy introduced the `as_ptr_cast_mut` lint [1]: > Since `as_ptr` takes a `&self`, the pointer won’t have write > permissions unless interior mutability is used, making it unlikely > that having it as a mutable pointer is correct. There is only one affected callsite, and the change amounts to replacing `as _` with `.cast_mut().cast()`. This doesn't change the semantics, but is more descriptive of what's going on. Apply this change and enable the lint -- no functional change intended. Link: https://rust-lang.github.io/rust-clippy/master/index.html#as_ptr_cast_mut [1] Reviewed-by: Benno Lossin Signed-off-by: Tamir Duberstein --- Makefile | 1 + rust/kernel/devres.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index c62bae2b107b..bb15b86182a3 100644 --- a/Makefile +++ b/Makefile @@ -477,6 +477,7 @@ export rust_common_flags := --edition=2021 \ -Wrust_2018_idioms \ -Wunreachable_pub \ -Wclippy::all \ + -Wclippy::as_ptr_cast_mut \ -Wclippy::ignored_unit_patterns \ -Wclippy::mut_mut \ -Wclippy::needless_bitwise_bool \ diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 3a9d998ec371..598001157293 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -143,7 +143,7 @@ fn remove_action(this: &Arc) { bindings::devm_remove_action_nowarn( this.dev.as_raw(), Some(this.callback), - this.as_ptr() as _, + this.as_ptr().cast_mut().cast(), ) }; From patchwork Mon Mar 17 14:23:55 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14019281 Received: from mail-qt1-f169.google.com (mail-qt1-f169.google.com [209.85.160.169]) (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 7B73F24886F; Mon, 17 Mar 2025 14:24:03 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.169 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221445; cv=none; b=MiOSpl4p1Xx4aBFdlbFbIr3jTy4vs5RRRhMIKho72wItO3uSd19NaVJZiuNNqYh8B7RZKGWUqKD6FYKQKrGYhrm+/mFc+FEZr7zxFDc00Q2a3IY9yLGHDiWZp0CFlm/27SdOzjB+zKGvRnMCyErt4QnnbjKm3mMKQCNFn5LHOdE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221445; c=relaxed/simple; bh=iqdLqdc24YU6g2e8AJmmfHRlo02LNz0JFfvHbGp/fx4=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=E16/GMMsJxz1H2+N18nB0H1U4woaW+oQZRLBohigio9b9kYVUURc4rxLWo6+o8V0Ojkercx2/yrCgAdbhc/L/HKzV3uh4emomTvcdXaIg9MlsDfi4gAg8Ofcd/e76QH8+Cvclaq1SawOA//WVZncuF/fyeOm47HyHpScT4UGRKQ= 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=A35+6BUm; arc=none smtp.client-ip=209.85.160.169 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="A35+6BUm" Received: by mail-qt1-f169.google.com with SMTP id d75a77b69052e-47692b9d059so59332011cf.3; Mon, 17 Mar 2025 07:24:03 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742221442; x=1742826242; 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=ntpBnz8Sl2qSarDG75PiDTyH/uRCykgl2bz19Zggh1s=; b=A35+6BUmmuc7taFlGNVmdImU8T1cQV5lL7Qq7p5CXoIGHy13McJd395mC44CvVzFaD Nv7Wb0krI0ITTjVE9pQgeoQpqvRMQqku/hLJNZ47EKrsrns6emSin1ysxunc8v6PfyBe CQqIRZOPQ0VUw9lDIJx7OQUJAxXz1Lyvr9lFT2pvwtge121KKpXEuURtaCMd3iP5HZSG PtvTZqtS7H3fEzFvTNrUi2lTc0/lRrpLfCS07SzajDfy27imHlcdBYJM2RzeEhqEtBnP qyQWgxqnu22ivvctEqGW7Qi2LDyLt3WmoFVUVItZZ/hR5iMKPeiIIwaLmEORzf3ihBBq jOLQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742221442; x=1742826242; 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=ntpBnz8Sl2qSarDG75PiDTyH/uRCykgl2bz19Zggh1s=; b=jgsC5RoET5dWKGnOdPiUd4hePX8weDyt4JiLQ5E7s0BHlL05AB3uSRpVVfkiA6Z+b0 Cb7qRsmk1Wq6umSAcBKr9FB9jY9PLIAgl1xoCikiD10dR2Kc9jHy3s4kcVR+dnqsb8Bw lJFbowI5xm8PGupotrV5HmU+KyvqozhLKCo+CU4RGhO4pHEEV1z++LQrLdm8Qfb4coyB J0L/t86+cWVmNJfU/vlz06mdQc5R8oEehNSLCV2naCKcV7kNS4DQjwTKa6Jm6bm7eDzH OuMe/XUh6rsXNGMpZG4K371SpYugYNXZzaJ1ZX5VA16DHuTrZuZzEgHc1X/lSDVAK88U JAWQ== X-Forwarded-Encrypted: i=1; AJvYcCUA8DW2bFxRrGBCAD1EKzf5+H5aaecuLItcov1ehW/ErnTo0gmw34OBpVWSnOd4AghZx5T/Vhgb/hh+sXZL85tp@vger.kernel.org, AJvYcCUgQiFEysS8olAbk9iR94IV3Ymrk5nJBotVMVVa3PMdrggui8ll4hye4rN+uFBDll1jL0kp+1cXa+No@vger.kernel.org, AJvYcCV0L1UIXF1GuR4Rg5WZ5EmpM80NbZXlAA8e+3NCkLxjo8bAbOGecVadqhWZomCV/obLNgnCCPgXWS+iiJtm8vc=@vger.kernel.org, AJvYcCVJRPbhydMtYVJE7rOkY9MWlvincKRdaqZV5j51Unw2IvZLQ2LiMr6CJh+KnU2YoCZwqK6KNe4/txXNJcQ=@vger.kernel.org, AJvYcCVqPhccQ7GRcXClIUXOPg1f+s2DgRJGpDMW58Bx6eivLSEmUwXVkqh0NdaOEc4lzBpG7BcGZcukPV65CM7+@vger.kernel.org, AJvYcCX1DeW70n5eV2jv2CrnwzqH19On01DxyRVOswBpYyVAzRIWj5DyNcC+ZC0/cTVvwaMfD5eVNXC1OprW@vger.kernel.org X-Gm-Message-State: AOJu0YzCSgxaM68jeLVbLDsR5p54qr/2czM1h1AJPrLGv+fXgSongaQv eRRP/ZKf8EQKnnvOtbovwjTgy/jHEvy0jcL+EpJsj0qi7GhNYcXB X-Gm-Gg: ASbGncueznvjCrpZ9NhQnOQKa//D37yv4nRXDyZ7LUNa2cct4sE4RDo3hKWZq1d5lhi mpAUrTIl30t7MqD6703FFCaY1w76c8OBixOp3GUd7RbQA7hpC7Ef2jBdyGO9zV9Mczh1eYK8wjx qd9wa24tcMT1IYcO7qviiDP/3bvXfUIsFfJyfKG1QiIy20DiAWSCVGmwJw8pNQbJFIh649O2NxA XHFOwWPQRgdAlouM7qjjGqV4ZHsMSps+OKTG1ZcAWFu65KgCw027d25w/7veuC/8lkmlWy7UGdO AwjGygkaqwujgy/kA8a0sodmHoqCP8Aygp/3xcSKCJ9UmjXaZdNZccaII0vfYC13NFMqeAH/xg= = X-Google-Smtp-Source: AGHT+IGf4RMgilab7hC5ejxSK4TGI/+q9CICkeBIRXsDctmXnXikqzu6WNh+3Bl8n1/UVsC1eNnYzQ== X-Received: by 2002:ac8:5a4e:0:b0:476:add4:d2bf with SMTP id d75a77b69052e-476c8143482mr154641701cf.22.1742221442182; Mon, 17 Mar 2025 07:24:02 -0700 (PDT) Received: from tamird-mac.local ([2600:4041:5be7:7c00:6895:24c6:e898:e320]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-476bb60b13esm54601011cf.6.2025.03.17.07.24.00 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 17 Mar 2025 07:24:01 -0700 (PDT) From: Tamir Duberstein Date: Mon, 17 Mar 2025 10:23:55 -0400 Subject: [PATCH v5 5/6] rust: enable `clippy::as_underscore` lint Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250317-ptr-as-ptr-v5-5-5b5f21fa230a@gmail.com> References: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> In-Reply-To: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> To: Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Brendan Higgins , David Gow , Rae Moar , Bjorn Helgaas , Luis Chamberlain , Russ Weight , Rob Herring , Saravana Kannan Cc: linux-kbuild@vger.kernel.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, linux-pci@vger.kernel.org, linux-block@vger.kernel.org, devicetree@vger.kernel.org, Tamir Duberstein X-Mailer: b4 0.15-dev In Rust 1.63.0, Clippy introduced the `as_underscore` lint [1]: > The conversion might include lossy conversion or a dangerous cast that > might go undetected due to the type being inferred. > > The lint is allowed by default as using `_` is less wordy than always > specifying the type. Always specifying the type is especially helpful in function call contexts where the inferred type may change at a distance. Specifying the type also allows Clippy to spot more cases of `useless_conversion`. The primary downside is the need to specify the type in trivial getters. There are 4 such functions: 3 have become slightly less ergonomic, 1 was revealed to be a `useless_conversion`. While this doesn't eliminate unchecked `as` conversions, it makes such conversions easier to scrutinize. It also has the slight benefit of removing a degree of freedom on which to bikeshed. Thus apply the changes and enable the lint -- no functional change intended. Link: https://rust-lang.github.io/rust-clippy/master/index.html#as_underscore [1] Reviewed-by: Benno Lossin Signed-off-by: Tamir Duberstein --- Makefile | 1 + rust/kernel/block/mq/operations.rs | 2 +- rust/kernel/block/mq/request.rs | 2 +- rust/kernel/device_id.rs | 2 +- rust/kernel/devres.rs | 15 ++++++++------- rust/kernel/error.rs | 2 +- rust/kernel/io.rs | 18 +++++++++--------- rust/kernel/miscdevice.rs | 2 +- rust/kernel/of.rs | 6 +++--- rust/kernel/pci.rs | 9 ++++++--- rust/kernel/str.rs | 8 ++++---- rust/kernel/workqueue.rs | 2 +- 12 files changed, 37 insertions(+), 32 deletions(-) diff --git a/Makefile b/Makefile index bb15b86182a3..2af40bfed9ce 100644 --- a/Makefile +++ b/Makefile @@ -478,6 +478,7 @@ export rust_common_flags := --edition=2021 \ -Wunreachable_pub \ -Wclippy::all \ -Wclippy::as_ptr_cast_mut \ + -Wclippy::as_underscore \ -Wclippy::ignored_unit_patterns \ -Wclippy::mut_mut \ -Wclippy::needless_bitwise_bool \ diff --git a/rust/kernel/block/mq/operations.rs b/rust/kernel/block/mq/operations.rs index 864ff379dc91..d18ef55490da 100644 --- a/rust/kernel/block/mq/operations.rs +++ b/rust/kernel/block/mq/operations.rs @@ -101,7 +101,7 @@ impl OperationsVTable { if let Err(e) = ret { e.to_blk_status() } else { - bindings::BLK_STS_OK as _ + bindings::BLK_STS_OK as u8 } } diff --git a/rust/kernel/block/mq/request.rs b/rust/kernel/block/mq/request.rs index 10c6d69be7f3..bcf2b73d9189 100644 --- a/rust/kernel/block/mq/request.rs +++ b/rust/kernel/block/mq/request.rs @@ -125,7 +125,7 @@ pub fn end_ok(this: ARef) -> Result<(), ARef> { // success of the call to `try_set_end` guarantees that there are no // `ARef`s pointing to this request. Therefore it is safe to hand it // back to the block layer. - unsafe { bindings::blk_mq_end_request(request_ptr, bindings::BLK_STS_OK as _) }; + unsafe { bindings::blk_mq_end_request(request_ptr, bindings::BLK_STS_OK as u8) }; Ok(()) } diff --git a/rust/kernel/device_id.rs b/rust/kernel/device_id.rs index e5859217a579..4063f09d76d9 100644 --- a/rust/kernel/device_id.rs +++ b/rust/kernel/device_id.rs @@ -82,7 +82,7 @@ impl IdArray { unsafe { raw_ids[i] .as_mut_ptr() - .byte_offset(T::DRIVER_DATA_OFFSET as _) + .byte_add(T::DRIVER_DATA_OFFSET) .cast::() .write(i); } diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 598001157293..34571f992f0d 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -45,7 +45,7 @@ struct DevresInner { /// # Example /// /// ```no_run -/// # use kernel::{bindings, c_str, device::Device, devres::Devres, io::{Io, IoRaw}}; +/// # use kernel::{bindings, c_str, device::Device, devres::Devres, ffi::c_void, io::{Io, IoRaw}}; /// # use core::ops::Deref; /// /// // See also [`pci::Bar`] for a real example. @@ -59,19 +59,19 @@ struct DevresInner { /// unsafe fn new(paddr: usize) -> Result{ /// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is /// // valid for `ioremap`. -/// let addr = unsafe { bindings::ioremap(paddr as _, SIZE as _) }; +/// let addr = unsafe { bindings::ioremap(paddr as bindings::phys_addr_t, SIZE) }; /// if addr.is_null() { /// return Err(ENOMEM); /// } /// -/// Ok(IoMem(IoRaw::new(addr as _, SIZE)?)) +/// Ok(IoMem(IoRaw::new(addr as usize, SIZE)?)) /// } /// } /// /// impl Drop for IoMem { /// fn drop(&mut self) { /// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`. -/// unsafe { bindings::iounmap(self.0.addr() as _); }; +/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); }; /// } /// } /// @@ -115,8 +115,9 @@ fn new(dev: &Device, data: T, flags: Flags) -> Result>> { // SAFETY: `devm_add_action` guarantees to call `Self::devres_callback` once `dev` is // detached. - let ret = - unsafe { bindings::devm_add_action(dev.as_raw(), Some(inner.callback), data as _) }; + let ret = unsafe { + bindings::devm_add_action(dev.as_raw(), Some(inner.callback), data.cast_mut().cast()) + }; if ret != 0 { // SAFETY: We just created another reference to `inner` in order to pass it to @@ -130,7 +131,7 @@ fn new(dev: &Device, data: T, flags: Flags) -> Result>> { } fn as_ptr(&self) -> *const Self { - self as _ + self } fn remove_action(this: &Arc) { diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 8eca5be30f2c..340650abf446 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -152,7 +152,7 @@ pub(crate) fn to_blk_status(self) -> bindings::blk_status_t { /// Returns the error encoded as a pointer. pub fn to_ptr(self) -> *mut T { // SAFETY: `self.0` is a valid error due to its invariant. - unsafe { bindings::ERR_PTR(self.0.get() as _).cast() } + unsafe { bindings::ERR_PTR(self.0.get() as isize).cast() } } /// Returns a string representing the error, if one exists. diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index d4a73e52e3ee..9d2aadf40edf 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -5,7 +5,7 @@ //! C header: [`include/asm-generic/io.h`](srctree/include/asm-generic/io.h) use crate::error::{code::EINVAL, Result}; -use crate::{bindings, build_assert}; +use crate::{bindings, build_assert, ffi::c_void}; /// Raw representation of an MMIO region. /// @@ -56,7 +56,7 @@ pub fn maxsize(&self) -> usize { /// # Examples /// /// ```no_run -/// # use kernel::{bindings, io::{Io, IoRaw}}; +/// # use kernel::{bindings, ffi::c_void, io::{Io, IoRaw}}; /// # use core::ops::Deref; /// /// // See also [`pci::Bar`] for a real example. @@ -70,19 +70,19 @@ pub fn maxsize(&self) -> usize { /// unsafe fn new(paddr: usize) -> Result{ /// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is /// // valid for `ioremap`. -/// let addr = unsafe { bindings::ioremap(paddr as _, SIZE as _) }; +/// let addr = unsafe { bindings::ioremap(paddr as bindings::phys_addr_t, SIZE) }; /// if addr.is_null() { /// return Err(ENOMEM); /// } /// -/// Ok(IoMem(IoRaw::new(addr as _, SIZE)?)) +/// Ok(IoMem(IoRaw::new(addr as usize, SIZE)?)) /// } /// } /// /// impl Drop for IoMem { /// fn drop(&mut self) { /// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`. -/// unsafe { bindings::iounmap(self.0.addr() as _); }; +/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); }; /// } /// } /// @@ -119,7 +119,7 @@ pub fn $name(&self, offset: usize) -> $type_name { let addr = self.io_addr_assert::<$type_name>(offset); // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. - unsafe { bindings::$name(addr as _) } + unsafe { bindings::$name(addr as *const c_void) } } /// Read IO data from a given offset. @@ -131,7 +131,7 @@ pub fn $try_name(&self, offset: usize) -> Result<$type_name> { let addr = self.io_addr::<$type_name>(offset)?; // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. - Ok(unsafe { bindings::$name(addr as _) }) + Ok(unsafe { bindings::$name(addr as *const c_void) }) } }; } @@ -148,7 +148,7 @@ pub fn $name(&self, value: $type_name, offset: usize) { let addr = self.io_addr_assert::<$type_name>(offset); // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. - unsafe { bindings::$name(value, addr as _, ) } + unsafe { bindings::$name(value, addr as *mut c_void) } } /// Write IO data from a given offset. @@ -160,7 +160,7 @@ pub fn $try_name(&self, value: $type_name, offset: usize) -> Result { let addr = self.io_addr::<$type_name>(offset)?; // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. - unsafe { bindings::$name(value, addr as _) } + unsafe { bindings::$name(value, addr as *mut c_void) } Ok(()) } }; diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index e14433b2ab9d..2c66e926bffb 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -33,7 +33,7 @@ impl MiscDeviceOptions { pub const fn into_raw(self) -> bindings::miscdevice { // SAFETY: All zeros is valid for this C type. let mut result: bindings::miscdevice = unsafe { MaybeUninit::zeroed().assume_init() }; - result.minor = bindings::MISC_DYNAMIC_MINOR as _; + result.minor = bindings::MISC_DYNAMIC_MINOR as i32; result.name = self.name.as_char_ptr(); result.fops = create_vtable::(); result diff --git a/rust/kernel/of.rs b/rust/kernel/of.rs index 04f2d8ef29cb..40d1bd13682c 100644 --- a/rust/kernel/of.rs +++ b/rust/kernel/of.rs @@ -22,7 +22,7 @@ unsafe impl RawDeviceId for DeviceId { const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::of_device_id, data); fn index(&self) -> usize { - self.0.data as _ + self.0.data as usize } } @@ -34,10 +34,10 @@ pub const fn new(compatible: &'static CStr) -> Self { // SAFETY: FFI type is valid to be zero-initialized. let mut of: bindings::of_device_id = unsafe { core::mem::zeroed() }; - // TODO: Use `clone_from_slice` once the corresponding types do match. + // TODO: Use `copy_from_slice` once stabilized for `const`. let mut i = 0; while i < src.len() { - of.compatible[i] = src[i] as _; + of.compatible[i] = src[i]; i += 1; } diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index 003c9aaafb24..a26f154ae1b9 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -166,7 +166,7 @@ unsafe impl RawDeviceId for DeviceId { const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::pci_device_id, driver_data); fn index(&self) -> usize { - self.0.driver_data as _ + self.0.driver_data } } @@ -201,7 +201,10 @@ macro_rules! pci_device_table { /// MODULE_PCI_TABLE, /// ::IdInfo, /// [ -/// (pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, bindings::PCI_ANY_ID as _), ()) +/// ( +/// pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, bindings::PCI_ANY_ID as u32), +/// (), +/// ) /// ] /// ); /// @@ -317,7 +320,7 @@ unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) { // `ioptr` is valid by the safety requirements. // `num` is valid by the safety requirements. unsafe { - bindings::pci_iounmap(pdev.as_raw(), ioptr as _); + bindings::pci_iounmap(pdev.as_raw(), ioptr as *mut kernel::ffi::c_void); bindings::pci_release_region(pdev.as_raw(), num); } } diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 6a1a982b946d..0b80a119d5f0 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -692,9 +692,9 @@ fn new() -> Self { pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self { // INVARIANT: The safety requirements guarantee the type invariants. Self { - beg: pos as _, - pos: pos as _, - end: end as _, + beg: pos as usize, + pos: pos as usize, + end: end as usize, } } @@ -719,7 +719,7 @@ pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { /// /// N.B. It may point to invalid memory. pub(crate) fn pos(&self) -> *mut u8 { - self.pos as _ + self.pos as *mut u8 } /// Returns the number of bytes written to the formatter. diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 8ff54105be3f..d03f3440cb5a 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -198,7 +198,7 @@ pub fn enqueue(&self, w: W) -> W::EnqueueOutput unsafe { w.__enqueue(move |work_ptr| { bindings::queue_work_on( - bindings::wq_misc_consts_WORK_CPU_UNBOUND as _, + bindings::wq_misc_consts_WORK_CPU_UNBOUND as i32, queue_ptr, work_ptr, ) From patchwork Mon Mar 17 14:23:56 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14019282 Received: from mail-qt1-f177.google.com (mail-qt1-f177.google.com [209.85.160.177]) (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 713D924BBFA; Mon, 17 Mar 2025 14:24:05 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.177 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221447; cv=none; b=dSIFs0OJVHAb84ee1KCUxScYxjawdsUvDqw1nVO2APVZt5j+K1AAG0wO2GAhkrgfhRIRORq4oTQEQinD5btdv7vdLRfewZxLvl05VQhlvfXFJ7gCLs2ROi8G0GmrOeRR60GrIMQcuC40Vj3MNG1guVo0eGwmpH8bIphmEseezPM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742221447; c=relaxed/simple; bh=987TtpkPPaoRHA6crXpHFcJAOt/VWj29CNmz2SRJV7s=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=WlvKhwtdAXAoCddnZxhIaSn+Bh/J2jSXDNCKJKL0c7ZCPSSDECJA9GSHinDn1Dh6HmoU/pJlDiJ60nmOisCyIvKfBbEHFToAL6NR6PxLTW1qZkxEmvHt/wlcWNoYI7H7mYWLdDM2VhhVBOuRz0ZrqqsYK5uoKFQr0HhMPC/iu08= 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=XgQboESw; arc=none smtp.client-ip=209.85.160.177 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="XgQboESw" Received: by mail-qt1-f177.google.com with SMTP id d75a77b69052e-47688ae873fso43244551cf.0; Mon, 17 Mar 2025 07:24:05 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742221444; x=1742826244; 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=3AoPgamZTGw+bLyE66VJT+0+YBBvA1ZVLa2NjT4B3rE=; b=XgQboESwWpO3/ZTLwe90iaKpkrKBiBoQXI7624HdgL89ivAZNL3TJnq1gML7fygt7L cDnZiIz58iTmkzPW6Qr3d3yVH6ZX042DBys3lFiQpmmVurmhRRN1xcc9PAFJotRzBqQ0 iXIBd7RgDRcnSGPFZqqexv+FyBLQXrsG0dZ7oUxuLprE80Am71XRUvG6Hbfo7xkzf5+Q gn1IRMc1vj7O7+JIp1VoU3V0K/q0gEJtn+TRdIIq2M0fpESmH2msbu6p8ybiTQJNQj/c Pm+FaHP1qfvAvQZ6iMfmRaZ9WXgi+YD4WXfetloRdz4O3rEo4YcZxkBABmmInXkLFBTz cviA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742221444; x=1742826244; 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=3AoPgamZTGw+bLyE66VJT+0+YBBvA1ZVLa2NjT4B3rE=; b=xFTlVSUUjaIld1WoqicJAHwFuCHatnwcL1gbVl6mwa62ubaOYBxtTVyZbGl31i8jSG Vgdiwq/FPjBAViBX+HLBAa0ooKGNJdafMXix0B/5nwUFMEJOQDc2srJpf1ABC0Ta2a2K WiJyt1ehTGOJqSpR4QM5NoFYShdOVgHhTD76FJq019+Axfy5AZwd8tsACDzu2lQW8HMz k/WXm82EmZJ+Iyz8+U7Ba6j2vgC2ZEUAekI9fu0ore94Km55ROWn4+GOdcP68P6kX2rQ LWuvtOhNOB9UChYY4MKDU5dASiRg6yE2rfdI5/0a/1YD1v62ilQyk75AvJv9BKS/0qev HtPA== X-Forwarded-Encrypted: i=1; AJvYcCV2NSUAOEAsWaHaTUUfaNqiPEhouXwsj8RCZZmCbQszSLWS+/L9mgXrJyT73/Il2eQzspGosOfZFwbj@vger.kernel.org, AJvYcCV3+qg89VknENCySsn8NGZ0HW4EBlK74tH22+cnSrXx2ycaAoICdQWcRgxY3drS+4ePNwSw+fvl8Ar+@vger.kernel.org, AJvYcCVWApQkjJFTs92nM0aaUodYmOskwlRnJOSvDlQolfhSGl4XViGhIo3qhRVN5roft2cFliGf3cQtj3w0pFg=@vger.kernel.org, AJvYcCVZMhmMUS5m3LT/lItkKYqIAeug0QWjrsZg0Uuzj/dLL10tic86bK4oaEObfJg5PVjvxx3BbNBhwp0TaAEP@vger.kernel.org, AJvYcCXYh9Qkj/xWmzuaDwywMamrxQLuWZE2f5DidK6H/7hu/bXjVckFRdX56bZwcfVmPtLRmp+N5kIrzWrhiePrhA/H@vger.kernel.org, AJvYcCXol4F/xsOlgdYfszHcfnpeu+iXZMvUgwZ2dC4Epm3AUa2OXTcmHlLhVe9+13F/IApJipO9cf486dxjwzlNx5o=@vger.kernel.org X-Gm-Message-State: AOJu0YxSHjDacf59h6CUfQssCm44zUTmZnjAleDWa7ZlIodM2+xn1a3g c0XY9dIlCHw4yA+1ENPkWWKORYJH+2Y0zlHvUN1HdialOIzSyXWK X-Gm-Gg: ASbGncsC0Z90ZpdcabG7v5J8us6Bqx+Ln+nCx/hkbRvpTP8CklBl/zXroUDtHn47fC0 dhtZ7xuYsBjjUxgB62phZrqVlvj6J4+Z2aE94mtwp/RtwtQXlkkbGWuQiTs75eg/3qcE+oZvP0D 1MZ04YrmIw50yhlerKlBybc2TOFNh9CuKbJpV4HVhsXkjlCmI6Zl+wdXkMfGvbAc6Hqi6m4J43Q DxHcBygW9I126PURve02ieNlf75hx8tWGzRY3DFkUbCd3RhnmsRSOB0kky6p5058l6Z9cAmTLW6 xMWmKrnWAsk/nqzv6FW7hVLJGSt5JcZ/vj+4KLwEbRG+AcBGTOnFGFJH8RP1l0WF2zCLaAaa5g= = X-Google-Smtp-Source: AGHT+IEOcZaAErVkrTUiISs/oSWF4CNXcbc1QPv9pQ6mWesRhgejS3Ggisnz7nL3giOYmSt+NZV5+Q== X-Received: by 2002:ac8:5d13:0:b0:476:884e:52f4 with SMTP id d75a77b69052e-476c812c79cmr189000251cf.12.1742221444046; Mon, 17 Mar 2025 07:24:04 -0700 (PDT) Received: from tamird-mac.local ([2600:4041:5be7:7c00:6895:24c6:e898:e320]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-476bb60b13esm54601011cf.6.2025.03.17.07.24.02 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 17 Mar 2025 07:24:03 -0700 (PDT) From: Tamir Duberstein Date: Mon, 17 Mar 2025 10:23:56 -0400 Subject: [PATCH v5 6/6] rust: use strict provenance APIs Precedence: bulk X-Mailing-List: linux-kselftest@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250317-ptr-as-ptr-v5-6-5b5f21fa230a@gmail.com> References: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> In-Reply-To: <20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com> To: Masahiro Yamada , Nathan Chancellor , Nicolas Schier , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Brendan Higgins , David Gow , Rae Moar , Bjorn Helgaas , Luis Chamberlain , Russ Weight , Rob Herring , Saravana Kannan Cc: linux-kbuild@vger.kernel.org, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-kselftest@vger.kernel.org, kunit-dev@googlegroups.com, linux-pci@vger.kernel.org, linux-block@vger.kernel.org, devicetree@vger.kernel.org, Tamir Duberstein X-Mailer: b4 0.15-dev Throughout the tree, use the strict provenance APIs stabilized in Rust 1.84.0[1]. Retain backwards-compatibility by introducing forwarding functions at the `kernel` crate root along with polyfills for rustc < 1.84.0. Use `#[allow(clippy::incompatible_msrv)]` to avoid warnings on rustc < 1.84.0 as our MSRV is 1.78.0. In the `kernel` crate, enable the strict provenance lints on rustc >= 1.84.0; do this in `lib.rs` rather than `Makefile` to avoid introducing compiler flags that are dependent on the rustc version in use. Link: https://blog.rust-lang.org/2025/01/09/Rust-1.84.0.html#strict-provenance-apis [1] Suggested-by: Benno Lossin Link: https://lore.kernel.org/all/D8EIXDMRXMJP.36TFCGWZBRS3Y@proton.me/ Signed-off-by: Tamir Duberstein Reviewed-by: Benno Lossin --- init/Kconfig | 3 ++ rust/kernel/alloc.rs | 2 +- rust/kernel/devres.rs | 4 +- rust/kernel/io.rs | 14 +++---- rust/kernel/lib.rs | 108 +++++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/of.rs | 2 +- rust/kernel/pci.rs | 4 +- rust/kernel/str.rs | 16 +++----- rust/kernel/uaccess.rs | 12 ++++-- 9 files changed, 138 insertions(+), 27 deletions(-) diff --git a/init/Kconfig b/init/Kconfig index d0d021b3fa3b..82e28d6f7c3f 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -132,6 +132,9 @@ config CC_HAS_COUNTED_BY config RUSTC_HAS_COERCE_POINTEE def_bool RUSTC_VERSION >= 108400 +config RUSTC_HAS_STABLE_STRICT_PROVENANCE + def_bool RUSTC_VERSION >= 108400 + config PAHOLE_VERSION int default $(shell,$(srctree)/scripts/pahole-version.sh $(PAHOLE)) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index fc9c9c41cd79..a1d282e48249 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -217,7 +217,7 @@ unsafe fn free(ptr: NonNull, layout: Layout) { /// Returns a properly aligned dangling pointer from the given `layout`. pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull { - let ptr = layout.align() as *mut u8; + let ptr = crate::without_provenance_mut(layout.align()); // SAFETY: `layout.align()` (and hence `ptr`) is guaranteed to be non-zero. unsafe { NonNull::new_unchecked(ptr) } diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 34571f992f0d..e8232bb771b2 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -64,14 +64,14 @@ struct DevresInner { /// return Err(ENOMEM); /// } /// -/// Ok(IoMem(IoRaw::new(addr as usize, SIZE)?)) +/// Ok(IoMem(IoRaw::new(kernel::expose_provenance(addr), SIZE)?)) /// } /// } /// /// impl Drop for IoMem { /// fn drop(&mut self) { /// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`. -/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); }; +/// unsafe { bindings::iounmap(kernel::with_exposed_provenance_mut(self.0.addr())); }; /// } /// } /// diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 9d2aadf40edf..0a018ad7478a 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -5,7 +5,7 @@ //! C header: [`include/asm-generic/io.h`](srctree/include/asm-generic/io.h) use crate::error::{code::EINVAL, Result}; -use crate::{bindings, build_assert, ffi::c_void}; +use crate::{bindings, build_assert}; /// Raw representation of an MMIO region. /// @@ -75,14 +75,14 @@ pub fn maxsize(&self) -> usize { /// return Err(ENOMEM); /// } /// -/// Ok(IoMem(IoRaw::new(addr as usize, SIZE)?)) +/// Ok(IoMem(IoRaw::new(kernel::expose_provenance(addr), SIZE)?)) /// } /// } /// /// impl Drop for IoMem { /// fn drop(&mut self) { /// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`. -/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); }; +/// unsafe { bindings::iounmap(kernel::with_exposed_provenance_mut(self.0.addr())); }; /// } /// } /// @@ -119,7 +119,7 @@ pub fn $name(&self, offset: usize) -> $type_name { let addr = self.io_addr_assert::<$type_name>(offset); // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. - unsafe { bindings::$name(addr as *const c_void) } + unsafe { bindings::$name(crate::with_exposed_provenance(addr)) } } /// Read IO data from a given offset. @@ -131,7 +131,7 @@ pub fn $try_name(&self, offset: usize) -> Result<$type_name> { let addr = self.io_addr::<$type_name>(offset)?; // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. - Ok(unsafe { bindings::$name(addr as *const c_void) }) + Ok(unsafe { bindings::$name(crate::with_exposed_provenance(addr)) }) } }; } @@ -148,7 +148,7 @@ pub fn $name(&self, value: $type_name, offset: usize) { let addr = self.io_addr_assert::<$type_name>(offset); // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. - unsafe { bindings::$name(value, addr as *mut c_void) } + unsafe { bindings::$name(value, crate::with_exposed_provenance_mut(addr)) } } /// Write IO data from a given offset. @@ -160,7 +160,7 @@ pub fn $try_name(&self, value: $type_name, offset: usize) -> Result { let addr = self.io_addr::<$type_name>(offset)?; // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. - unsafe { bindings::$name(value, addr as *mut c_void) } + unsafe { bindings::$name(value, crate::with_exposed_provenance_mut(addr)) } Ok(()) } }; diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index fc6835cc36a3..c1b274c04a0f 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -17,6 +17,11 @@ #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(coerce_unsized))] #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(dispatch_from_dyn))] #![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(unsize))] +#![cfg_attr( + CONFIG_RUSTC_HAS_STABLE_STRICT_PROVENANCE, + feature(strict_provenance_lints), + deny(fuzzy_provenance_casts, lossy_provenance_casts) +)] #![feature(inline_const)] #![feature(lint_reasons)] // Stable in Rust 1.83 @@ -25,6 +30,109 @@ #![feature(const_ptr_write)] #![feature(const_refs_to_cell)] +#[cfg(CONFIG_RUSTC_HAS_STABLE_STRICT_PROVENANCE)] +#[allow(clippy::incompatible_msrv)] +mod strict_provenance { + /// Gets the "address" portion of the pointer. + /// + /// See https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.addr. + #[inline] + pub fn addr(ptr: *const T) -> usize { + ptr.addr() + } + + /// Exposes the "provenance" part of the pointer for future use in + /// [`with_exposed_provenance`] and returns the "address" portion. + /// + /// See https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.expose_provenance. + #[inline] + pub fn expose_provenance(ptr: *const T) -> usize { + ptr.expose_provenance() + } + + /// Converts an address back to a pointer, picking up some previously 'exposed' + /// provenance. + /// + /// See https://doc.rust-lang.org/stable/core/ptr/fn.with_exposed_provenance.html. + #[inline] + pub fn with_exposed_provenance(addr: usize) -> *const T { + core::ptr::with_exposed_provenance(addr) + } + + /// Converts an address back to a mutable pointer, picking up some previously 'exposed' + /// provenance. + /// + /// See https://doc.rust-lang.org/stable/core/ptr/fn.with_exposed_provenance_mut.html + #[inline] + pub fn with_exposed_provenance_mut(addr: usize) -> *mut T { + core::ptr::with_exposed_provenance_mut(addr) + } + + /// Creates a pointer with the given address and no [provenance][crate::ptr#provenance]. + /// + /// See https://doc.rust-lang.org/stable/core/ptr/fn.without_provenance_mut.html. + #[inline] + pub fn without_provenance_mut(addr: usize) -> *mut T { + core::ptr::without_provenance_mut(addr) + } +} + +#[cfg(not(CONFIG_RUSTC_HAS_STABLE_STRICT_PROVENANCE))] +mod strict_provenance { + /// Gets the "address" portion of the pointer. + /// + /// See https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.addr. + #[inline] + pub fn addr(ptr: *const T) -> usize { + // This is core's implementation from + // https://github.com/rust-lang/rust/commit/4291332175d12e79e6061cdc3f5dccac2e28b969 through + // https://github.com/rust-lang/rust/blob/1.84.0/library/core/src/ptr/const_ptr.rs#L172 + // which is the first version that satisfies `CONFIG_RUSTC_HAS_STABLE_STRICT_PROVENANCE`. + #[allow(clippy::undocumented_unsafe_blocks)] + unsafe { + #[allow(clippy::transmutes_expressible_as_ptr_casts)] + core::mem::transmute(ptr.cast::<()>()) + } + } + + /// Exposes the "provenance" part of the pointer for future use in + /// [`with_exposed_provenance`] and returns the "address" portion. + /// + /// See https://doc.rust-lang.org/stable/core/primitive.pointer.html#method.expose_provenance. + #[inline] + pub fn expose_provenance(ptr: *const T) -> usize { + ptr.cast::<()>() as usize + } + + /// Converts an address back to a pointer, picking up some previously 'exposed' + /// provenance. + /// + /// See https://doc.rust-lang.org/stable/core/ptr/fn.with_exposed_provenance.html. + #[inline] + pub fn with_exposed_provenance(addr: usize) -> *const T { + addr as *const T + } + + /// Converts an address back to a mutable pointer, picking up some previously 'exposed' + /// provenance. + /// + /// See https://doc.rust-lang.org/stable/core/ptr/fn.with_exposed_provenance_mut.html + #[inline] + pub fn with_exposed_provenance_mut(addr: usize) -> *mut T { + addr as *mut T + } + + /// Creates a pointer with the given address and no [provenance][crate::ptr#provenance]. + /// + /// See https://doc.rust-lang.org/stable/core/ptr/fn.without_provenance_mut.html. + #[inline] + pub fn without_provenance_mut(addr: usize) -> *mut T { + addr as *mut T + } +} + +pub use strict_provenance::*; + // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling. #[cfg(not(CONFIG_RUST))] diff --git a/rust/kernel/of.rs b/rust/kernel/of.rs index 40d1bd13682c..b70076d16008 100644 --- a/rust/kernel/of.rs +++ b/rust/kernel/of.rs @@ -22,7 +22,7 @@ unsafe impl RawDeviceId for DeviceId { const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::of_device_id, data); fn index(&self) -> usize { - self.0.data as usize + crate::addr(self.0.data) } } diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index a26f154ae1b9..87c9f67b3f0f 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -287,7 +287,7 @@ fn new(pdev: Device, num: u32, name: &CStr) -> Result { // `pdev` is valid by the invariants of `Device`. // `num` is checked for validity by a previous call to `Device::resource_len`. // `name` is always valid. - let ioptr: usize = unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) } as usize; + let ioptr = crate::expose_provenance(unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) }); if ioptr == 0 { // SAFETY: // `pdev` valid by the invariants of `Device`. @@ -320,7 +320,7 @@ unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) { // `ioptr` is valid by the safety requirements. // `num` is valid by the safety requirements. unsafe { - bindings::pci_iounmap(pdev.as_raw(), ioptr as *mut kernel::ffi::c_void); + bindings::pci_iounmap(pdev.as_raw(), crate::with_exposed_provenance_mut(ioptr)); bindings::pci_release_region(pdev.as_raw(), num); } } diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 0b80a119d5f0..6bc6357293e4 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -692,9 +692,9 @@ fn new() -> Self { pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self { // INVARIANT: The safety requirements guarantee the type invariants. Self { - beg: pos as usize, - pos: pos as usize, - end: end as usize, + beg: crate::expose_provenance(pos), + pos: crate::expose_provenance(pos), + end: crate::expose_provenance(end), } } @@ -705,7 +705,7 @@ pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self { /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes /// for the lifetime of the returned [`RawFormatter`]. pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { - let pos = buf as usize; + let pos = crate::expose_provenance(buf); // INVARIANT: We ensure that `end` is never less then `buf`, and the safety requirements // guarantees that the memory region is valid for writes. Self { @@ -719,7 +719,7 @@ pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { /// /// N.B. It may point to invalid memory. pub(crate) fn pos(&self) -> *mut u8 { - self.pos as *mut u8 + crate::with_exposed_provenance_mut(self.pos) } /// Returns the number of bytes written to the formatter. @@ -741,11 +741,7 @@ fn write_str(&mut self, s: &str) -> fmt::Result { // SAFETY: If `len_to_copy` is non-zero, then we know `pos` has not gone past `end` // yet, so it is valid for write per the type invariants. unsafe { - core::ptr::copy_nonoverlapping( - s.as_bytes().as_ptr(), - self.pos as *mut u8, - len_to_copy, - ) + core::ptr::copy_nonoverlapping(s.as_bytes().as_ptr(), self.pos(), len_to_copy) }; } diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index 719b0a48ff55..96393bcf6bd7 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -226,7 +226,9 @@ pub fn read_raw(&mut self, out: &mut [MaybeUninit]) -> Result { } // SAFETY: `out_ptr` points into a mutable slice of length `len`, so we may write // that many bytes to it. - let res = unsafe { bindings::copy_from_user(out_ptr, self.ptr as *const c_void, len) }; + let res = unsafe { + bindings::copy_from_user(out_ptr, crate::with_exposed_provenance(self.ptr), len) + }; if res != 0 { return Err(EFAULT); } @@ -264,7 +266,7 @@ pub fn read(&mut self) -> Result { let res = unsafe { bindings::_copy_from_user( out.as_mut_ptr().cast::(), - self.ptr as *const c_void, + crate::with_exposed_provenance(self.ptr), len, ) }; @@ -330,7 +332,9 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result { } // SAFETY: `data_ptr` points into an immutable slice of length `len`, so we may read // that many bytes from it. - let res = unsafe { bindings::copy_to_user(self.ptr as *mut c_void, data_ptr, len) }; + let res = unsafe { + bindings::copy_to_user(crate::with_exposed_provenance_mut(self.ptr), data_ptr, len) + }; if res != 0 { return Err(EFAULT); } @@ -357,7 +361,7 @@ pub fn write(&mut self, value: &T) -> Result { // is a compile-time constant. let res = unsafe { bindings::_copy_to_user( - self.ptr as *mut c_void, + crate::with_exposed_provenance_mut(self.ptr), (value as *const T).cast::(), len, )