From patchwork Mon Mar 24 22:01:30 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14027927 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 CAB671A83F8; Mon, 24 Mar 2025 22:01:46 +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=1742853708; cv=none; b=V+m0Y7aE2WzlqC7UaYWOxLE3+nnm4swec80mhIxkV8dIAMznDsVxpPGpSkyDCsc7ybzBabWODzVA0xmqd0jFASYk3vY5PIlAsWShj7/4r2pNv/K2Po6fLx8h3p7040gDkm5tRi+hs0reC/21e64FVG0+WGDl4qxdbY7D3uNNdVE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742853708; c=relaxed/simple; bh=jXBOpo5UWtwyrzWvahiJ2pLNqcTsAoQ2rJCCE9+N488=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=slJO5rD3MoadNeR75vNe4ZTNhytdw5tbgTpMKBAPwd2V7+GNOajxctO7dE79TwFleHmbaNNbTcxCFZ3ZC2KEca8oqJC8Gtbo5rb7BIxR0VIhB2veCZgG2vUQEQb7T9/maPJOHkDB5vJigrHhvFqa716mvcUc14rCuO78VGxMy00= 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=ac5C/BK+; 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="ac5C/BK+" Received: by mail-qt1-f179.google.com with SMTP id d75a77b69052e-474f0c1e1c6so75604391cf.1; Mon, 24 Mar 2025 15:01:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742853705; x=1743458505; 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=VLYdB8oz2i/GfcI4zN53mys18Ki2XN46F1DPNODr+Tk=; b=ac5C/BK+lIVre3hExgxqeJbkMUWOQvXcwgQROQDkqqIB9dKRl/wWUAtEbIWsTjxgbG IHaaOovBCkrHQEiRxkn/82LyeIOFg8S5v6szFc2mHIv2jjXT9Z4gtFV63zSRZtfH466S n/BY9gytp+PrHv4MHxc/pvjik6315rsTpi7HndyxC/KSLuXdLvjHquq9kPLdCtz6gg1/ bDACxnGLtD92L8SKpBGGU2iN7NOZVOL3VnJW1Ugdrg2bum3gasQIDv/8LJsx43ectCAc 4iF/KnaU7jVfbkEbhrnpdDwZ1bNhd3a+L9QmxD+Wo6iRpH12025+xgHLlwqut65xBnWS 1EnA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742853705; x=1743458505; 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=VLYdB8oz2i/GfcI4zN53mys18Ki2XN46F1DPNODr+Tk=; b=n+B++mf1p4SI698CgKjn2yTdBY9ymhfWCWAvESUD7j08tlKHyEr4hrLj+dYfZdNwvt ATZmepU6nuuCjovLbZTaPqHUD93EaYgJ8jfrzmTk/6CFPEKAlBQAksczMyiYddbXAErq 6VFTXZmJLJyT9KP/oYCLsg9tB050XEL2HMkaRVX6b5VP0GL6+a6JEwRFgeRhbkBDT1Iv tNCFAEWCqdZ1uos3rDlKhFJUIWsfWczj9G/+Rzq4/65dBptQm736xzTcDAQmrLiBqRZT 9PRTQigA9Yl1wejkNV3NqjLXSYntz2eaDdXaG3lqManVEJXcxdhfN3eUfE5VN3KqkX6y CKrQ== X-Forwarded-Encrypted: i=1; AJvYcCULFhBpyYtztMZ3bA6fiP+FJ4+T5ttDAhtRKGImXLqfjXxnsVH4IMRI2lm94iQh+wDwJ8MDJjUMQhPX@vger.kernel.org, AJvYcCUh1PlhQqd8aUdZK2JWf2bDKQJgmHyFocSG9j+dD26v7g0JkSmh/oONgXoFjYUKWEaW9pzPN8SoDI9AgaVzcAw=@vger.kernel.org, AJvYcCWhq/YWJvSX7Ew1uXCttWmLnfbXBBeQMADpl8AHRBRIuYWX4NyvnunZvoX4FZsimTepwEX4FZxQ@vger.kernel.org, AJvYcCWoKH35vVesDjkS07LbF7Oiwg3b2dPBKJuyaOgw/9NE6wzUH7Q5fRAMKbf6wxgB3gyWDxi7S04gw8WPDH0=@vger.kernel.org, AJvYcCXgMw64Bh+MbdyoWHWcQkNRcYBSusfqF8eKxrpnsH1TIGB3fvCYXWr1vvVjL+9x7sYRcV7o/1xtzcRk@vger.kernel.org, AJvYcCXsrbC2451oV+9hIqOhaEjvynJIe30HsIdTkUaeaYZI4gMbrpRE1FAWZvy7DOkQWvLepp/Bep6CQA0Mo7JgJmBz@vger.kernel.org, AJvYcCXuyLtcH54cof2cvy7QBvLjE+ZK4Y74Y/wRrS9OlD9t1Aj8+AhVQOssJzPrIjtHhbDb2KKyyN2XvoHIa0tj@vger.kernel.org X-Gm-Message-State: AOJu0Yxyg4vD8T6G0HngbpqiMf6ZhN6xpjA90TSYIvNm4BDOTWqt7BMO yjxAGGcs4807E0SkJKsdPnMXMA8EOaPTx8Lbbai3pUWP0tnOnhNi X-Gm-Gg: ASbGnctFsJSkOngo5Ym09GRV9peJLYcTx5QzBVZi5pI9Fhhtcgnww/XYHWoxvSFsI38 E2IbijVKoQpqiLTIpc9ddAYzIDidH5Riu6GsHIsQRRlI6mzgxdsMsO+XicYXZRGhGOXxYi5CvLs 4WR3zee0H61zDB2bbUGSryz6aHzEGK2gCFORhz3iC2od6LF+QDsm6iKgvhKmdN3LiFkPynX410l y0uXBtlBdGFth6sMbGjo02hvwSBLuYfnEbNWcTmMcjt+BhsHKp51cMyIZ8kmpYriT7jQgXMzXpD 3RxsR1y5pn/JakZ97Rll70POsPsiNBMDFxX+JoW5T4BZtXj6kKKteLs+pi/Pi0m7I346mmBciII ENZwKrr0rhQ6wuORRYS1UYiBJCjx9Lb7GtgL8h1DOcq1clOXSpO2a6fjSbS9HCY/8 X-Google-Smtp-Source: AGHT+IETbkIsiMSS3aJnwxSeNF2HAjbJX2SYSBhI/Fk+fnGg2Vjy1M9GacySt+Gyh5yE9AnyKA+qog== X-Received: by 2002:a05:622a:4d03:b0:476:77a5:3106 with SMTP id d75a77b69052e-4771dd615e2mr239659571cf.5.1742853705391; Mon, 24 Mar 2025 15:01:45 -0700 (PDT) Received: from 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa ([2620:10d:c091:600::1:43c7]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-4771d0ad87esm52129541cf.0.2025.03.24.15.01.43 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 24 Mar 2025 15:01:44 -0700 (PDT) From: Tamir Duberstein Date: Mon, 24 Mar 2025 18:01:30 -0400 Subject: [PATCH v6 1/6] rust: retain pointer mut-ness in `container_of!` Precedence: bulk X-Mailing-List: netdev@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250324-ptr-as-ptr-v6-1-49d1b7fd4290@gmail.com> References: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@gmail.com> In-Reply-To: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@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 , Abdiel Janulgue , Daniel Almeida , Robin Murphy , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , David Airlie , Simona Vetter , FUJITA Tomonori 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, dri-devel@lists.freedesktop.org, netdev@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 ba0f3b0297b2..cffa0d837f06 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -190,7 +190,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) }; @@ -199,9 +199,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 5246b2c8a4ff..8d978c896747 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 24 22:01:31 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14027928 Received: from mail-qt1-f174.google.com (mail-qt1-f174.google.com [209.85.160.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 CCB9F1EFFB5; Mon, 24 Mar 2025 22:01:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.174 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742853711; cv=none; b=hjShDYSxFT3oczn5Ud4lfuMR6BtauDlhASQaKEsDNFpEnfuUn52G+r9t24Kp/xPmPiX0Mta8/yavwwHe3RvhCvQSZOW3ygug3OPGdhH9UjBeaNUyZfqwEEM7R9XDEItqZYJEgCLIFdOYTRp1vLawZSRGfBA4NHA0nCgLdGmLtf4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742853711; c=relaxed/simple; bh=NBQvPcFh+32+8+lHBfmSggmRBFNPMKcfPl5vn3Il/Cc=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=X0Ey9dMIvN04+sdp4voWs568WbeB9uTylaDUGkHf4cr70HlM/E8rk/q1f/T1ZvlCI/7qlNZh8PgzuvAnpe7gnPndt48bastRkNSfkt9cTVaEFXLpBENFRBBvaIfyJbXrvuxWZuhGK72Ad4bbEtXPyQ9/2pbzxN73vmP6cmDyUJQ= 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=X8wO7Xza; arc=none smtp.client-ip=209.85.160.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="X8wO7Xza" Received: by mail-qt1-f174.google.com with SMTP id d75a77b69052e-47677b77725so43143001cf.3; Mon, 24 Mar 2025 15:01:48 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742853708; x=1743458508; 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=eeQV0FJRJSt3ITZrRzVCsatZj6ANmNyp/gKDtLz53QI=; b=X8wO7XzaVQQOB8H7fszhZZM7bicss0k+LTHJK0Uok+wy3LqDQtl3NrdluzH/2EmRpy n3WFo3H5qEenQod2xGBZTSwAK86DijmO5UvWiMLUMF4/zfaESN49McivD5SGBhh/CN9n G9tlJ461kNY9j3i6ac23aOMYJjtw1kUCfNiMZgHpAj2d/07KoSJF1ATcAbHq89faJkk6 qteGpMuna/7pMEHp/V4JyADgxvyw9o7xjI4opeGdVd39ydFbYS0thom34lvn1hWubDSw 3F+i7bCrHhrZ6WHsoue2Z6eDzyhNfcyCpDgDUplwZq1+t4svbeV/s/Y2qzwKutWkz61X dabA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742853708; x=1743458508; 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=eeQV0FJRJSt3ITZrRzVCsatZj6ANmNyp/gKDtLz53QI=; b=HnE3mRAc6/yTa9gCl5NpB7YwiH7dQDPi1iEBDy+j8sVLDVV5Jil3+1mq/YAlZtS10d +lVYGRnZwkrqiQukkwlQiN+N9YGfgq/0GTnUsfrMiSQPYn11fzV4sKpBJ015uGgxJU+P bbYVOyABg/+TDv8AUKTCSzncsQHiam5N5sRGTWDOQXTNw5jmfSKxTSsScZrFw9Siz2yO /TV1EwzwuG4WkqZiBpNK/5jWkadTHBwEpc659CC1T798e1Ch6H5Qourdmbx03j+XC8GJ WIoeUqxS+IuAZhI8cBTXsP0Eh3RMTpyLCgg/dzHoFOvQshSQXWyHx4UCnzhoYlFYJ0tJ K1HA== X-Forwarded-Encrypted: i=1; AJvYcCU5PkTeaH/B5nMA1TBoGdhXeVvFr/+PUebJxsxvtrxEk8PO+XEjEekCo1vg1oeQ7MlOj5P6SkgyKOTgk0r4/1Qq@vger.kernel.org, AJvYcCUoAXeHQrQqgt/42HV3Io9HzXUQZFIesRL30KOUBhU/A/VsHaFxjDn7krM6Xk04DXxu9bkaKFfd@vger.kernel.org, AJvYcCV6mJpxF8RScGCigZaRSbdPdwqHl9iqQgcrQvrpJM3l8T+SSd3DjA8Jvomsjnndni7ivpi204+EyPHLZ6s=@vger.kernel.org, AJvYcCVVSIm1Vvg8eGZ0IQBLz1TkGCndeOhSrcTv3nGao2znYDEmuMWvEyriP2ruawDVqbNezBkMrIn7w2RlsKci1+k=@vger.kernel.org, AJvYcCWnUHUiBZEhgwMX66SBCZpYAyIDGPIUQBBxt/qehw/CABWpy9AY3Yl71VmPOwEqYfnK4nERancQZ2R4@vger.kernel.org, AJvYcCX43CjlFzUUoDADU49XEW+l4b5x2LGpNk9LRkxJUmnDoQhkicZnVRxWC5nKCfeVoZ9hdW59JnAC9PHS1UZj@vger.kernel.org, AJvYcCXtS0PaLX3sYkOSUKRUo9u1r+z1SJOFOO3IqmYw0aOjJiAjiuO3XBolH2R9lVXYEO7BSpMWq81WjhHg@vger.kernel.org X-Gm-Message-State: AOJu0Yy5Bk2jW+7Tzp47EDGG8FZ3766TjQQAolmMUxGQ3l9TvGqCMZJb RV5DEhyKXDdJumTIDrz8k/L/FE2G57x9z/eqJaoJEWVxmRNcaOKN X-Gm-Gg: ASbGncvPuym1AXEWWHWFuoQwcSeZiIpc7KkajUqzrtg65FTQiri5dAWNtL2B6ng0OJF rnPKwGtaZwnhdAPbaluygCiHaiWS+JdqDiKap5VEWGH8Hxj9TYnU1BEAj7VMBKS1zmBuB6NCc4B +9WitmZnf9zRpLguKU+lbRHmGJwgm7I/KRWFBJ6TcT9Pf4n1isXDOV1KgvZGcSH0Z3RuAYjU+Tc B93Y5E6xOQlCBHElRFH1BJCJtwew+tyVnLnd0Ag/44eEFVsG0SoMDxvDK+GnDzIGdZJMOQiozqK r3h8r4c1ogDWCB5mPT4fQfQJVyfWud8iDU/uCY0g4tY7tfyYcEeHNGLcwW29mx6UWweoXI4eMvA /Kr4J3g6qhxm1oXwfM2iPNbFdgvN1NVLnHXOzMMDgCQu+V957bH03fQ== X-Google-Smtp-Source: AGHT+IEBILZmdMWiuJrl8nEvW9uRFwR6hGfFOX9SdoEHx889XFkG1q6ts5jdQJ1o2PHrMpTlJd6NZA== X-Received: by 2002:a05:622a:1f85:b0:477:e7c:a4c with SMTP id d75a77b69052e-4771de41ea9mr260612861cf.39.1742853707177; Mon, 24 Mar 2025 15:01:47 -0700 (PDT) Received: from 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa ([2620:10d:c091:600::1:43c7]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-4771d0ad87esm52129541cf.0.2025.03.24.15.01.45 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 24 Mar 2025 15:01:46 -0700 (PDT) From: Tamir Duberstein Date: Mon, 24 Mar 2025 18:01:31 -0400 Subject: [PATCH v6 2/6] rust: enable `clippy::ptr_as_ptr` lint Precedence: bulk X-Mailing-List: netdev@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250324-ptr-as-ptr-v6-2-49d1b7fd4290@gmail.com> References: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@gmail.com> In-Reply-To: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@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 , Abdiel Janulgue , Daniel Almeida , Robin Murphy , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , David Airlie , Simona Vetter , FUJITA Tomonori 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, dri-devel@lists.freedesktop.org, netdev@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/dma.rs | 4 ++-- 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 + 20 files changed, 42 insertions(+), 36 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 e3240d16040b..30ce85326a50 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -64,7 +64,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/dma.rs b/rust/kernel/dma.rs index 8cdc76043ee7..f395d1a6fe48 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -186,7 +186,7 @@ pub fn alloc_attrs( dev: dev.into(), dma_handle, count, - cpu_addr: ret as *mut T, + cpu_addr: ret.cast(), dma_attrs, }) } @@ -293,7 +293,7 @@ fn drop(&mut self) { bindings::dma_free_attrs( self.dev.as_raw(), size, - self.cpu_addr as _, + self.cpu_addr.cast(), self.dma_handle, self.dma_attrs.as_raw(), ) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 30014d507ed3..b0e3d1bc0449 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -153,7 +153,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 1604fb6a5b1b..83d15cfcda84 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 878111cb77bc..02863c40c21b 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -237,7 +237,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 24 22:01:32 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14027929 Received: from mail-qt1-f171.google.com (mail-qt1-f171.google.com [209.85.160.171]) (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 3FDA71F1307; Mon, 24 Mar 2025 22:01:49 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742853712; cv=none; b=JuggLmUFWJeIKuQcCbSFcx97yTDTnMHVg5jw595L08CVdbxEtVWEUeQ/IDnG0bDyL+jNiHQrRJv/oy6TbU56z/Sa4vJPuucS/xg1EGEQSX7REquWq1e3/MiMo8Ca4jN8NOFXtDWBGP5Nb+jA/I4bCyFv1vkofaZV8lzd2fo5344= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742853712; c=relaxed/simple; bh=xbVg7Xhp/6dsdm/KyWD3Le3ZeFNfssrbQ2pquJNc7H4=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=OuTkz98ybLprDPYzvd0IDxLr+zhOdzV0Na+Emu83r3usGf/ZX9yJX2Sv3J4Em/MiZEntXm2IgZSnNztYj5D+fBcTCTxMYOc9dirjkumY8oJzE/Fl06KSePVSNX5aRAK/4XuN0Pn3F3Cp/TpKlf2LPjqoDZ7ACH1oFZSA1X16TDw= 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=BnbMKDEN; arc=none smtp.client-ip=209.85.160.171 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="BnbMKDEN" Received: by mail-qt1-f171.google.com with SMTP id d75a77b69052e-4767e969b94so30224591cf.2; Mon, 24 Mar 2025 15:01:49 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742853709; x=1743458509; 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=RrSMUDZZYlyoJ9Y4j+pFyX1Efp/qPB5Vo8olgw4flH0=; b=BnbMKDEN2KtY+5hcjtIpZkS7G5MyUQRQQyrySnCLFM0FTEuixN9XGNHSmQgqWOSL6J zILwIrzKsWQHg9pKet3G3r4aWv8EXNI/I538coHJFzhTAMol0jNe8OrJv6gnp08QsBEj LJd0APxhaKet08L3alrrpP7Wv67MU6xT/QV/kVLxeYAiHfq9qBAWLOxX6n99p2QrXKYM gewoEry4isIXBfz7t9KdKPr+Erkreua95GGMwlXh0TQY/a2rxyesapKHYCZkOqpjGygl ayIC0hu+u7OV/H3wm7YYPB1QlVpDvMws352/AQMG/4QEPAyOxXn0yo4ktNzd4RsLqXec hieQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742853709; x=1743458509; 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=RrSMUDZZYlyoJ9Y4j+pFyX1Efp/qPB5Vo8olgw4flH0=; b=fRDi+z4cJ/jHqOjbg0XprGWizQzhBEDWQdPAusHBLrBhWSzFnIfT6H1Ikk70fMHTpI XBv02OgpLsPe0EpPHboyVom8CdRCz9Mg5VP/ouwXwHIUaM8/BpfajjrBQZJh4nee91WY RxOPSQ6QvhqpBh8ZtjEz80YErmk0g26XRVgikhxbLuAzjwMXSKEDFHSaalO9Gn+0dlvo MGUDzI5QaQpTEH+wRI0SzWFpOd9fDFrfGtfUuKBGsPRMLCX8zYbvVCUez5d3CFQk0qqc dAidLRL8ji6MW7XSapo6bsFjl20FLhAoK09xO1+68ZMV+DzyV5Uda9AOrEp9A4b6/8Wv PCFw== X-Forwarded-Encrypted: i=1; AJvYcCUk2xJV4cE2TODzGlUKKG8e/DSDJimARAgTArLCOzemwXRxj9AlX5ZQBJu1gg2Kv36M77DWEQGX1mQUDLpn@vger.kernel.org, AJvYcCVuOf67s9jsGlr87XxtY92bVCznYfh/xesN2jPBGLOaQzFs+phqXnqHmsLkvJJhDhoLqKUlb0BUQjmLOLU=@vger.kernel.org, AJvYcCWORogAWEVISootgX6imclFlyLZLTtIAbIf+oYnUrqId90fAjTPwOhZ7XVBR0LPP0b+Gf0ylolvXp2r5nEAwg8=@vger.kernel.org, AJvYcCWoQwvrpylitY6OkAgtK2gTT2sCtWjtt9O4pq65Vf6ay1DQSLnT+CnDkDiUiggrAyyh3rKU2nWtoc2v@vger.kernel.org, AJvYcCWuwthuN6VdW22MR4w+PaEXkNCSk1twVatdqtGdQtCgxA02IAAVWCzpjTpyiUkYZsL5+S1Xo4XTpr4Uv8f/4fL5@vger.kernel.org, AJvYcCXOg2qrGlErKJVCVysDM9Dor2Qwa5y3boxH2drnKdHMGDCg+KxgxYVROgFivJ++vnC9QD/PnUJiO/bx@vger.kernel.org, AJvYcCXkIfq3+S192a2KNVNi85IBV4idr9PRcz6ElbNuN1hnCAupD98xPIMrcoxZk58xPyy1Dalw7MCL@vger.kernel.org X-Gm-Message-State: AOJu0YxIyrIFowa3vZ8E1mPoAACpG2C17pAPrYETaVUEfo3akwq9JfBA SjZO1jkOauyMYLPVp6unUIPtFfgN46cmEOG0H7xNkGvaLftDUO/K X-Gm-Gg: ASbGncu80opFwyTPLPJ1/JU+8B+U8GpSHFuVXrHZAiTLQ3+h7sq/g/hx6VdAFRoNeXe +b0WsZ4oul8rKzIETFiIXlZSEbj6Y/e6k1JH5ntJ8xhyQgXaXcM/0u+4QBOqh0xVQvVzjaCnmhM pslEaWNNBGmdO1YoZv8F59XzejgXFX0VCyb6pjfylhuzcJMqivLT/Vp4X3ZlhPw/uYAdq/DBZup LBi3hwTz1Pw5H1SMbuX56KSO/cvKseOKcfQ+MsJe4++wNcZisGMpNq9av1ocn7Si/JHkrQagQfP V3k/T4b8YkCQfCNSGLjwOCkulDQ0zb0Cj+G3NAawV/Yq+YoELSODCC0/U3zc+8VWREUSaWTDQCb JgMEmtOV5K+nVNB2EOsIYCLwr+4+OnOuWkCZtTs9f+KtqP+hcqy8k6g== X-Google-Smtp-Source: AGHT+IGClCAaATZslBV1U1w4j++Vn9oRujV1utPTcSNqeAgqWjnn31iDitDZyWoTomflHvtQ1nvRqA== X-Received: by 2002:a05:622a:244a:b0:477:db8:e15b with SMTP id d75a77b69052e-4771dd608acmr207554641cf.9.1742853708852; Mon, 24 Mar 2025 15:01:48 -0700 (PDT) Received: from 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa ([2620:10d:c091:600::1:43c7]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-4771d0ad87esm52129541cf.0.2025.03.24.15.01.47 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 24 Mar 2025 15:01:48 -0700 (PDT) From: Tamir Duberstein Date: Mon, 24 Mar 2025 18:01:32 -0400 Subject: [PATCH v6 3/6] rust: enable `clippy::ptr_cast_constness` lint Precedence: bulk X-Mailing-List: netdev@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250324-ptr-as-ptr-v6-3-49d1b7fd4290@gmail.com> References: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@gmail.com> In-Reply-To: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@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 , Abdiel Janulgue , Daniel Almeida , Robin Murphy , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , David Airlie , Simona Vetter , FUJITA Tomonori 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, dri-devel@lists.freedesktop.org, netdev@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 +++-- rust/kernel/dma.rs | 2 +- 3 files changed, 5 insertions(+), 3 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 4a5b7ec914ef..c9f8046af65c 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() } } } diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index f395d1a6fe48..43ecf3c2e860 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -186,7 +186,7 @@ pub fn alloc_attrs( dev: dev.into(), dma_handle, count, - cpu_addr: ret.cast(), + cpu_addr: ret.cast::(), dma_attrs, }) } From patchwork Mon Mar 24 22:01:33 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14027930 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 D006B1F1818; Mon, 24 Mar 2025 22:01:51 +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=1742853713; cv=none; b=S5OrYNgLbqmxeCPjMoXhvGrM6xOVsk5tFK7mQ89n7+3MBLjDRfQOe1GYLG31cDppMTHAv8bYzzjt3aKjblOl+FOHjPX91DAjILVn+yJP77LfcRbKjBBY0q3YsEvwaxXajHR7DDi0Txtivc8pUoMo7LSkqOWGP6N+HGrYPwxXeZ8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742853713; c=relaxed/simple; bh=eOC8GNYrVfiMmJjIlMnjsi5R6euOkfd+217Ym/0TGMU=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=esM+UXoQu2vzK9hDGdmoDZdyOAiOcOTwc72mJF2g+HMc94eJuZleb34qg+VinoR6yneqsPjschC0N10SlaY7s/BWwmLN+lFh7CbgBRyHiJd9154kcPncl0UpuEnIJmL/OQTNcemcBPRqLae4vjX0ny7BB8JWVbVx0tHx8nVgVAI= 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=WdTZU7pl; 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="WdTZU7pl" Received: by mail-qt1-f169.google.com with SMTP id d75a77b69052e-476f4e9cf92so33006231cf.3; Mon, 24 Mar 2025 15:01:51 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742853710; x=1743458510; 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=WdTZU7plV7GkbNJFye/EY3dsg0YQQ1lWbnpT2YLuAztfsL+W6/YDxH8ZOrmQuo5YHf NlseHKPxgsmW3Z9R1+rmDyj+ifQZvmpeLRLsykULvIOxMmbZ6NOQMNcFy/C/0lzN1dFv q61VkXDNtQdCLff/FCdxrwzSeiO77prDXZHDc3HRrmR3eYCn1gCaz/9Oetfapu78ckhb 9AxblaTrj2FGC7Ps58nBU4903myFAx4EYh/nI/woj17ghVx0BdQDIKd/JbjzIp/f0WqR sG0eNKkkLCy/C+aUMsgg4eA+MLWxq673u5G3xQPaqy6YIypE6UboE6vYS16o2/AWdogQ 1P8A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742853710; x=1743458510; 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=kcBQJhslX1gDNDCoZizjwbmx4cqhAfI3z5lgd89deTQ/W5UOsh9MH2p28LtpR+BDti DcWzN9/ElpR+UqKzMVXWW9svUkMyPlvUEs/pEPWf25J7rYYsn+LBx/UfCDQSKoK25Ttb NIfiWrDM12srE3BMA5ThF5MTgAzgVlCdKHXy01FU4pM3kcoGBFvJDhj/ed1lkvwxpJMw o5Fa3A4VU+kOpcV3e7kILtOUOf2PbTl3Bj7zNSkER2dwwTKu1CfOaG3ZDqfpmEoLoQuv m5a4e2ecTcbRcIaO8OPRy5PjxDluEDmeTmcMh8isdT39rdHzf4+XsLRmezBU3iwL097T pfUw== X-Forwarded-Encrypted: i=1; AJvYcCU0EQMpI1XlzWJyvzoiNGQbCNhu3YbdmOCwdDJ9p6hNV9bbr6J5DqOQ4lxIPY1dkoaCwpHl/qY4tfWX@vger.kernel.org, AJvYcCV/LPNg/ILsQpFaEobWTq6XgJUvcSR+Q9Cc08lkeC896AxHOc4Gz1jhjKDhT0sES81Tkq+jm0f1@vger.kernel.org, AJvYcCV73CQu3lr3cap7ijqQzpZK4zKajWquG0PzbN9IUV9G1EY4DLBMplQZY9gSqzEisj+Z7IqMAr05EQJx50f47Co=@vger.kernel.org, AJvYcCVUZBCD0ZtiURjR9DYUI+htUhsODuF4rAL4WohjANwFVMxqGxexM09HDCPdGRPg4Pb0xHL5FeAM/80AAqUv@vger.kernel.org, AJvYcCVVZG2JgzwWJ/JsyFGKOvdkRfQTpV9Lc18LwA+ymdabagMecfjc8mFrJP3zu6I49xbxJ23BCC6VH8r+@vger.kernel.org, AJvYcCX1WbRlM7JMf5GmLevgRltfeW95OVuQHDazgOuQ/CJLsL7m5ZZR4N3956KOqSoV68gKMdz7Cm7N9nOi0B8GUmRL@vger.kernel.org, AJvYcCXO63+ql1JY5K9OQA+swORDZ/uR9SxO+tleMoomEHehSCKnsCvL1dO5dmQg5xjHhMJNbOIO8fFsw9furk0=@vger.kernel.org X-Gm-Message-State: AOJu0Yz8+Aivd/i83i//HyhIW/kU7SNyp/e3w+2uvj2+suNWN+BB9tXj LpKEliBX+AOVztohhXNCs7rgnrSzBn55xQmOObvMaOAQXC+GPY7k X-Gm-Gg: ASbGncvcq1b8Dc+3/7+ayrb183Wc0/JZoCRD1b0K2aVtXfgLDXHz7jCNhW/qYzfeP2Z DSMyhGbaEnf4p4PKHunRr0CE4M/xjol5LjLQvsq+0zWAZSwRMsi1A4nsobnAZDOfbu2Zn56jmCw 9/9wRH/8dqxPnm9lyV0OA/ttNow59ePzDTFiomGAE27AhKmBuq19DKaVF3nWfQRVtaZymVYpqsm aNyOGK1ZSmnRoRnIGn1FR5Qofg/MSTD+XkqfTFbnEeAHNpzyaCWMuabjdsRjrO0gTK0cMRyN4go NQfq3eZz9Xukd9gxhK3z63ewQAPqK1g0+p9JGu3OZYwDedXNH86QBy4/L3xVaEzFxE+5e8ckoBB q4sxirnugYf9Jf8Iok3K99k9lCEAUpLunB4eCYkUnU99jLUvWZl568w== X-Google-Smtp-Source: AGHT+IFmPbwb4p7A5O3ShEsQauN8bwD2gzq9L0MWbRn2vSApft5OKiV5A0a4gUNuHtVtJVvTJbnmZg== X-Received: by 2002:a05:622a:17c9:b0:476:7d74:dd10 with SMTP id d75a77b69052e-4771dd94dfcmr252627141cf.19.1742853710412; Mon, 24 Mar 2025 15:01:50 -0700 (PDT) Received: from 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa ([2620:10d:c091:600::1:43c7]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-4771d0ad87esm52129541cf.0.2025.03.24.15.01.48 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 24 Mar 2025 15:01:50 -0700 (PDT) From: Tamir Duberstein Date: Mon, 24 Mar 2025 18:01:33 -0400 Subject: [PATCH v6 4/6] rust: enable `clippy::as_ptr_cast_mut` lint Precedence: bulk X-Mailing-List: netdev@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250324-ptr-as-ptr-v6-4-49d1b7fd4290@gmail.com> References: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@gmail.com> In-Reply-To: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@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 , Abdiel Janulgue , Daniel Almeida , Robin Murphy , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , David Airlie , Simona Vetter , FUJITA Tomonori 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, dri-devel@lists.freedesktop.org, netdev@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 24 22:01:34 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14027931 Received: from mail-qt1-f178.google.com (mail-qt1-f178.google.com [209.85.160.178]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 988DC1EDA33; Mon, 24 Mar 2025 22:01:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.160.178 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742853716; cv=none; b=qiJQmZimCqSeLC7vBD1bh9MqopfOLobqrv6kLbiBex57TBeEgUK1FAOrq9sw0AWrYlNe0JJ9Z4hoQlbH9TqYlyZWoWSnObfxcwoDfAuu/BPWXDRgEE24FBnYn1a7NICIJvbiAuxRZwxG8x4rygJs0jAhGZfdATA1PFUyNKwZYTs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742853716; c=relaxed/simple; bh=vaB+g5yKu2Mlnf772JK5VkB679nHOhi2QuEegk9Z1pA=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=FtLJZjzkoQz31V9Dfc2G3DCMxqIT3UfFq26isW1kxozKK/xS6gWUl+QNRr8G1ASt039d38KyCJqfjXXsiuIqibzhumRoHAZc2dyPGvAWiEjS7Vlq2WanYJ6JJPRO81+dRdR/5ohhbULj4xE4wENtGqKu1uBUIf7XUSFyJo0C6go= 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=RG1NQeeH; arc=none smtp.client-ip=209.85.160.178 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="RG1NQeeH" Received: by mail-qt1-f178.google.com with SMTP id d75a77b69052e-476f4e9cf92so33006381cf.3; Mon, 24 Mar 2025 15:01:53 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742853712; x=1743458512; 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=3msj9yCtJiGy0EO2iHZnNA6wr/0BgpnHoxtNdRcAn/w=; b=RG1NQeeHT6Nf0y1HV8JSBQwdLUmTkAz9e0ascPHJ5X8E1lR95FrEvzTj3WnsXcaJhP kvn19PBLdlaBYWrWLHeyXI1zasXWXKVECP1ZHiXPzrAYRriG4J6IdePgYUhRFHrTrZds KMBYHiiy6qA8doFk+O67OkuMJOF3qi+VtbsACfpu1W0dzOYrlBggBSdVsfZOaJKs/i40 1vwh9j6VQqpXODv9sYh1S9eBkvJDf7Ca6yjh3y3ZhyjT9rWqhaMvbEEzc+irycRcAAwQ sFjBBt9pw9H6Mq7K3tNrAYrkYwEsQwoNst4stKliF/zgpDDc6ZzVR9mbYGu+EtLfo7Cs 3pIw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742853712; x=1743458512; 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=3msj9yCtJiGy0EO2iHZnNA6wr/0BgpnHoxtNdRcAn/w=; b=ib/uP+6MtfsuAulL+Q2nhRlMQ7TeFFKi/t1vHxpqpU55oKVmDXRYTNgrJnRq78Jbdp 9//+Rx3aiJst+l5jxYyC1x4ZvFfa728aZ7+BtbXDe6uD3MXu7hXfvIHpreJmUG2xwx23 oj3XcpkCyirLX/Mi14JE5fDJpk5EqYyoGd6657sBFYGwI71pZMTaEi34WlUyq+VqPbEu kCPzfTrD0EBZZfTJlRlcqOxne8KORaDGkWuiq0SD9yhfx1hP7MBLZ/eZjDvtRFKly+PN qTUyy0/cZeAWmaaoYxRYvqAcim7ECrVy3b7DtDg6/r+xK+UFHfHxYvHtzj+oqLdlLiuu SBmQ== X-Forwarded-Encrypted: i=1; AJvYcCUMvlSMIUZ7OVgHzd3d+g4Q6E0oraMV3p9TkTyv1qmkRe23FkheOIVq2ZZbqTA4mtMQz4gPNA//@vger.kernel.org, AJvYcCUh/dE2z/dO3aRezUfOIP5/7XiW6W+zjCpWH/xeZVfWecsR9AZuK8AaKikYLwpZt0T2k4hai83N0ZTSXhhC@vger.kernel.org, AJvYcCW5MRWekYfNaixORdo4NpBsFEnmhXh63BqpBRQlRbHjNEgcPE2EjUdthV0ua015lRyLbne6ki9AP41rHYw=@vger.kernel.org, AJvYcCWIvw4dTPV6/0ZjCGRCo4bVAHAbFxJNKOvJ1H1jgE62M/CI/ywZHmTfDLnp04jWy2lfpiB5L3VD3AGIP7qyJKg=@vger.kernel.org, AJvYcCWOxZJZR9hJ2y2CPQsHZLZhWyhqkOPaDzue2qy7HQ/wMwAFYIzlqIuo9FxsrA8BHKmw2d9NMxrlbF5x@vger.kernel.org, AJvYcCXdaAFWA7+2zaK/mbGyeRHkvsOh0lpYNJ5EPjL1r8FYZJBQ1q12KVUvvEIu+6oGtye/BHNTwhyNaLedmOXcRvna@vger.kernel.org, AJvYcCXe0et6llvhRUSok4YfwWGj5yLd/KiZQ2hkBAV4jm4ijOWUNr82sYVJ0r5j1UUDle7WFC+L/RMT0Hx7@vger.kernel.org X-Gm-Message-State: AOJu0YwY7Pc9z/7ewy+u4sxNRpT3q1hKM8FbttALv7mNeIBTY7qD+0EL dm1xF+s83zkSmot5kjbNL5UH3+evAMMpfU1BbamtNKlGWHW0i0sy X-Gm-Gg: ASbGnctReSxwABnGeJfanHlwY7G0TCXii1prj/waHwilmh7plahZOeDQO2+4tcT9l5U ohhSwjONnd5nU/s2Ew5YIRz6eXhGzg8hNrJuwOS4QIesZ49ssaksB0sXtVc+TT/iOpobN3nYR42 6OwpkSjJXXThhRaynolWUdAqq3UbBD9BJGuRqU53wZRsqYw9Kn4KeEyHoFmIUdfSGwP8nWCVh1g jcruO1cNJApJzi7AZ4qTPNb2LpNy1aNdzGSU2a+rRHPgjFQepyWPMlpBPJoTsLDwMZXGts8W10W g3yMWaJyP7VLygfYx61u7bIMHxg1h9rRTu3wqJsHFu4R8BCrjEbFcfmumjx8XJYrOTnLF4mKI0P knjj9DelwYa/GfUHUqA51x0Q9TC8RwtakSQolrGS+zz2DVBd8q0jhPRpP3UHVvYMr X-Google-Smtp-Source: AGHT+IGy6TR0vEfH8SPazsfXhisCujtVWVyKHe6XCKSv4lKoF54XubMeM3jWpXfsqZ4o8KMulfUKQA== X-Received: by 2002:a05:622a:4d0e:b0:477:114a:ba0c with SMTP id d75a77b69052e-4771dd61cb1mr222380531cf.6.1742853712003; Mon, 24 Mar 2025 15:01:52 -0700 (PDT) Received: from 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa ([2620:10d:c091:600::1:43c7]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-4771d0ad87esm52129541cf.0.2025.03.24.15.01.50 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 24 Mar 2025 15:01:51 -0700 (PDT) From: Tamir Duberstein Date: Mon, 24 Mar 2025 18:01:34 -0400 Subject: [PATCH v6 5/6] rust: enable `clippy::as_underscore` lint Precedence: bulk X-Mailing-List: netdev@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250324-ptr-as-ptr-v6-5-49d1b7fd4290@gmail.com> References: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@gmail.com> In-Reply-To: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@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 , Abdiel Janulgue , Daniel Almeida , Robin Murphy , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , David Airlie , Simona Vetter , FUJITA Tomonori 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, dri-devel@lists.freedesktop.org, netdev@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/dma.rs | 2 +- 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 +- 13 files changed, 38 insertions(+), 33 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 c9f8046af65c..807a72de6455 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/dma.rs b/rust/kernel/dma.rs index 43ecf3c2e860..851a6339aa90 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -38,7 +38,7 @@ impl Attrs { /// Get the raw representation of this attribute. pub(crate) fn as_raw(self) -> crate::ffi::c_ulong { - self.0 as _ + self.0 as crate::ffi::c_ulong } /// Check whether `flags` is contained in `self`. diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index b0e3d1bc0449..cff84d427627 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -153,7 +153,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 02863c40c21b..40034f77fc2f 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -738,9 +738,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, } } @@ -765,7 +765,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 24 22:01:35 2025 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Tamir Duberstein X-Patchwork-Id: 14027932 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 43C0C1F1927; Mon, 24 Mar 2025 22:01:54 +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=1742853717; cv=none; b=Fam8M1TzcxR+YYcZjSptkT2noYM98DCDVtr4gV6jxAEUz5uwO8ZWtDo/qIam3i4lXj3moFrq9GeaBgqpeFBxhbyDTRd3ia9UeBfmS3HkAaTjfvn9wP9y3tTOhZiLQN3400dL4zk+VL54KzGQthVqCw9xKfjrOMSCx2Y/r3Y3oVI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1742853717; c=relaxed/simple; bh=msdLEXr/9qeuW34/7CWTD5wgn+JSkfbwHI2pYO6sLxI=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=MoftDPr8f+8pxB6jzMlhqqZerOPFSpzWLQC16dzvbRxW/80OgrR0IxgpvGNFW+9G7FSgYFwmzW9z1Ji+LwtmPhOxGnV0AuKlgUs99z4YmGYO6az54khv1+eMM7uck7tjhweQpGJT2cfp5cnvtTnG7yyTdG17TPgEvkMlLpdUoJE= 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=HB6riEto; 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="HB6riEto" Received: by mail-qt1-f179.google.com with SMTP id d75a77b69052e-4769f3e19a9so31657781cf.0; Mon, 24 Mar 2025 15:01:54 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1742853714; x=1743458514; 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=Okf71mJ2fjHM6RavOTp6+N0Ztqg8E8Xvt1yqhkIK7vU=; b=HB6riEto2LdZZ+bPam1xbeRiUzWsRmfgoi1uDRcxzWDnS3WRRhIeXuuzXvOOjoclLR LCiu5ElCuYFhMeMbJ8xyMbSVwomxeK0k74KhU0H4V8OvzDx1TJz3vc5lzdJbOulc5Yse 0PsS7qWRJo0/P5vf58PIsQ5HQucb5MeJGqAw/M3cZaH/do9db7JNCs2ulNMpG28KkTfc tU9TLGjDhG4oZk0KC31NBPrFh+49qf5pAGuFLHUIKbR4Mx9/i8aBCAq13bBuzMrKLLY4 wgIXJF+zLs+2KGbgfwB79ms58T91vIM7sOd2LkS7hXiD9dWNGDRTRtRMeVohmfHuARA4 /Y3A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1742853714; x=1743458514; 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=Okf71mJ2fjHM6RavOTp6+N0Ztqg8E8Xvt1yqhkIK7vU=; b=K3xI9uN6nPPqdvPOppiMWgmwF8MsijzcVZIANbc3Z0JlnOFA1AMa9wKm15ga9xq1XO eyeug6pPDjrUZhPAPAsbrxvtPNMYm4k+tD1daaTraIOM7PS1gLLWzaTIjbGaVB+Kh3t8 XwoRzOKrDQHhlXi7Zbz4kXt1+1Ty2gwTSkbXQUOhfdeGsP9STCphwuMdORyZSpGUHDil KUJ25UQWv/Bev1nnFFKas9ucA2RYXd+Vb3cUKo0dnZbJ153tuUd7BhDSpxjTWKeV06M/ Pxyy5yIpOH3YFNRiLxGhTckfOOklmI6lFLSC/NP1MF7HwgNGjXDfltBWO3GuC/iWzqzf m8/g== X-Forwarded-Encrypted: i=1; AJvYcCUZxw8E4S5wMxA9UhAB9sSO8IatVSDSHY0qOyACamf3apMka2Mt+yrSuM591YBfAAihdr5hBRrIFzJZRGU=@vger.kernel.org, AJvYcCUv1JvrRdfWXTJYgpeK0iYHLQGUHYRUlFjvkqX2puPdatvOPk1FR5rxaw9silJITKZ+APTzDo2acKVObxOJ@vger.kernel.org, AJvYcCVlTXxlcReMd7Wy+HqLaQ+OLazUT89RQdJUAcKn+WdSRLpBMRp726VHPGGgl/pYy+OIVwigWXXNDLSL@vger.kernel.org, AJvYcCVohrwxgpHds6Pq+vwEg/zQEbwP0i0oSTX/SdGZY7dLSs3t6ZfPi6T8NR+9tHFdnyZTJcPifC8M@vger.kernel.org, AJvYcCVx8fcHCVLspgXYHErE/GoOAFol708TUiO/E13RyFrJgrs7ySeifMU7wbTmiWebV2k8gTW+0NE5Dk8opoS2u3uu@vger.kernel.org, AJvYcCXPyx/hWTzthizzqhvE1yVtmJvU+gb7c/ul0sFZ0PQaNZzr/8iiOCR+oMFmcyB9CoqjMcxF6fP+3TOl@vger.kernel.org, AJvYcCXv7OYhKyQFDzCuIOXpn9VC1Dd3K72wM4TY8F9S+a7qaBjp36LCk3ITNYC2s1avKi/WwIqa3ZaMVyDWgQqJMgk=@vger.kernel.org X-Gm-Message-State: AOJu0YwpetyXUIzO/h/UqpW8YCErZWcyxpQrdnUhs+oVwL2opVyBg5Rg D/2+7u2rr4BLdG4EHydUJ2+z+TbRedl4enRfgyb/sqTcaDHfy1hD X-Gm-Gg: ASbGncvJqqIjU2jsisvrW+IXJD930ZrEWE8jcO3brMmCi3jwppikLKQQYkYICDjOufj N+xN9dr/GP0DPtqEYCW9nDWuPfKiMu/RFHkFTDYmJpQwYnkvo1WmTJJYg+iaayHwNnTQnyQnFGk JZ8ud0jURqo8AEdROqEd6X1t6CqTAOke57cTs9aDRt9lBOIPLZaeZUibpZBkwTr1hQP2JPYmZ4H KYTL+s+CUKE+o2gKn7BXP/izX87D462yEwvBWiWZtysLgF0KiENqdEVUDQ5/zz+FSiTICgWiXAF E4LwSrspK8292rnRLy0+aYMEKKPWeQbi0fJMhH3/lHhNX9nPQyCYowY02x36Zf3DFu8zE6J10gt 7r6LKhCQr/NnzZheFr7bBO7r3Qn2/IEXvGD0oG3qfQjrw8OFuGhxwDHtdjWgca+xG X-Google-Smtp-Source: AGHT+IGiTpxJOfUP6yEDw+BZ5IoEtfpjeRAnSg8Fp13Y/l+nete8QxRyDKUWgvo+a1iooMF3ftJdsw== X-Received: by 2002:a05:622a:1805:b0:477:1e1f:8a0a with SMTP id d75a77b69052e-4771e1f928bmr226073741cf.0.1742853713644; Mon, 24 Mar 2025 15:01:53 -0700 (PDT) Received: from 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa ([2620:10d:c091:600::1:43c7]) by smtp.gmail.com with ESMTPSA id d75a77b69052e-4771d0ad87esm52129541cf.0.2025.03.24.15.01.52 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 24 Mar 2025 15:01:53 -0700 (PDT) From: Tamir Duberstein Date: Mon, 24 Mar 2025 18:01:35 -0400 Subject: [PATCH v6 6/6] rust: enable `clippy::cast_lossless` lint Precedence: bulk X-Mailing-List: netdev@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Message-Id: <20250324-ptr-as-ptr-v6-6-49d1b7fd4290@gmail.com> References: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@gmail.com> In-Reply-To: <20250324-ptr-as-ptr-v6-0-49d1b7fd4290@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 , Abdiel Janulgue , Daniel Almeida , Robin Murphy , Maarten Lankhorst , Maxime Ripard , Thomas Zimmermann , David Airlie , Simona Vetter , FUJITA Tomonori 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, dri-devel@lists.freedesktop.org, netdev@vger.kernel.org, Tamir Duberstein X-Mailer: b4 0.15-dev Before Rust 1.29.0, Clippy introduced the `cast_lossless` lint [1]: > Rust’s `as` keyword will perform many kinds of conversions, including > silently lossy conversions. Conversion functions such as `i32::from` > will only perform lossless conversions. Using the conversion functions > prevents conversions from becoming silently lossy if the input types > ever change, and makes it clear for people reading the code that the > conversion is lossless. 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#cast_lossless [1] Suggested-by: Benno Lossin Link: https://lore.kernel.org/all/D8ORTXSUTKGL.1KOJAGBM8F8TN@proton.me/ Signed-off-by: Tamir Duberstein Reviewed-by: Benno Lossin --- Makefile | 1 + drivers/gpu/drm/drm_panic_qr.rs | 10 +++++----- rust/bindings/lib.rs | 2 +- rust/kernel/net/phy.rs | 4 ++-- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index 2af40bfed9ce..2e9eca8b7671 100644 --- a/Makefile +++ b/Makefile @@ -479,6 +479,7 @@ export rust_common_flags := --edition=2021 \ -Wclippy::all \ -Wclippy::as_ptr_cast_mut \ -Wclippy::as_underscore \ + -Wclippy::cast_lossless \ -Wclippy::ignored_unit_patterns \ -Wclippy::mut_mut \ -Wclippy::needless_bitwise_bool \ diff --git a/drivers/gpu/drm/drm_panic_qr.rs b/drivers/gpu/drm/drm_panic_qr.rs index ecd87e8ffe05..01337ce896df 100644 --- a/drivers/gpu/drm/drm_panic_qr.rs +++ b/drivers/gpu/drm/drm_panic_qr.rs @@ -305,15 +305,15 @@ fn get_next_13b(data: &[u8], offset: usize) -> Option<(u16, usize)> { // `b` is 20 at max (`bit_off` <= 7 and `size` <= 13). let b = (bit_off + size) as u16; - let first_byte = (data[byte_off] << bit_off >> bit_off) as u16; + let first_byte = u16::from(data[byte_off] << bit_off >> bit_off); let number = match b { 0..=8 => first_byte >> (8 - b), - 9..=16 => (first_byte << (b - 8)) + (data[byte_off + 1] >> (16 - b)) as u16, + 9..=16 => (first_byte << (b - 8)) + u16::from(data[byte_off + 1] >> (16 - b)), _ => { (first_byte << (b - 8)) - + ((data[byte_off + 1] as u16) << (b - 16)) - + (data[byte_off + 2] >> (24 - b)) as u16 + + u16::from(data[byte_off + 1] << (b - 16)) + + u16::from(data[byte_off + 2] >> (24 - b)) } }; Some((number, size)) @@ -414,7 +414,7 @@ fn next(&mut self) -> Option { match self.segment { Segment::Binary(data) => { if self.offset < data.len() { - let byte = data[self.offset] as u16; + let byte = data[self.offset].into(); self.offset += 1; Some((byte, 8)) } else { diff --git a/rust/bindings/lib.rs b/rust/bindings/lib.rs index 0486a32ed314..591e4ca9bc54 100644 --- a/rust/bindings/lib.rs +++ b/rust/bindings/lib.rs @@ -25,7 +25,7 @@ )] #[allow(dead_code)] -#[allow(clippy::ptr_as_ptr)] +#[allow(clippy::cast_lossless, clippy::ptr_as_ptr)] #[allow(clippy::undocumented_unsafe_blocks)] mod bindings_raw { // Manual definition for blocklisted types. diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs index a59469c785e3..abc58b4d1bf4 100644 --- a/rust/kernel/net/phy.rs +++ b/rust/kernel/net/phy.rs @@ -142,7 +142,7 @@ pub fn is_autoneg_enabled(&self) -> bool { // SAFETY: The struct invariant ensures that we may access // this field without additional synchronization. let bit_field = unsafe { &(*self.0.get())._bitfield_1 }; - bit_field.get(13, 1) == bindings::AUTONEG_ENABLE as u64 + bit_field.get(13, 1) == bindings::AUTONEG_ENABLE.into() } /// Gets the current auto-negotiation state. @@ -426,7 +426,7 @@ impl Adapter { // where we hold `phy_device->lock`, so the accessors on // `Device` are okay to call. let dev = unsafe { Device::from_raw(phydev) }; - T::match_phy_device(dev) as i32 + T::match_phy_device(dev).into() } /// # Safety