From nobody Thu Dec 18 05:08:57 2025 Received: from mail-lj1-f174.google.com (mail-lj1-f174.google.com [209.85.208.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 518512561AA; Wed, 26 Mar 2025 20:13:05 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.208.174 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1743019987; cv=none; b=i8xmopwy/LiJe2mm3yazgZb6ftRcmue3XwCL9IESFhGnX8n/Be4mnKKb6KeCHJWbLblfr2y6ChclCgvi5jZ7uES1KB6JS5p1gAM/6veI2TNsgxKB8KNaa4m1FoBUqLLXc9xFqRuEyxRJiVhL6Xs4PIUn68KYqWM1xjpmNMXeHhE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1743019987; c=relaxed/simple; bh=QklNTkE+U9D+pTS8UKveElBjdJatRbS+Ai62Y7tPWXM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=DXsI2K/C1b0CSIjjNkwgn3oIgo3b6i0r/XpoCoY6GyllCY2+HDYdhUvpzgA4r7AleXOlLQEEIejKeLSGRn8ansxPXvXfdF1JyLxNLv9TQI/HU3kcBqeBN47JTZLl1HQU1EvXvW3EGavlAc3aBWXSl8Iqth2L+Rq9RZGN1kSimrY= 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=YXnO8NI/; arc=none smtp.client-ip=209.85.208.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="YXnO8NI/" Received: by mail-lj1-f174.google.com with SMTP id 38308e7fff4ca-30c2d427194so2949241fa.0; Wed, 26 Mar 2025 13:13:04 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1743019983; x=1743624783; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=pveoisS0dkHjk8AoQMkPJTBRAAfPuiNG6lIhjvhzlA8=; b=YXnO8NI/yB9I1lVql5uMKKmdnMQswJd8E0/Ol2eBYecfepstmGu/Hs3ZZy+dAtncZh CqJ5xfjz+SbJ8lG8TCCeTeo46yWMeKnGlL+C80KjY45h5voAgbAC7aPGqbkQJfsg7/Pg oSKkOUuwkZyXdKddqF2zc+TplpObkJ06DyXMTR2dsk3vB3VIJt2L7LraxwF4ULWYSeKi Eq7JcjW6uQEwF26S2EBSsg5ZlU9NHoFeCh0fLyO0/pi/QQ4AFPGioapYo05EZlIN6PY1 AJwQYFX/DKh0IpRlK8LTANTYHatl837PMQeNom36i4BZBWGCpcT1OJay16Fbw/FW6Rt6 FtDA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1743019983; x=1743624783; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=pveoisS0dkHjk8AoQMkPJTBRAAfPuiNG6lIhjvhzlA8=; b=P+c5dmuL9IoYYCMNI2pe6Jo70qWDoql3h4ECTonw+T5H/ENpfzIA9hBrRgVMGBYOxb HJQwPCA5WsHRD4IEPh2v2/mLcf0+5mYjCVLqleoa8NPJKhH/GJvgEhAxoO+iHUeHiwx9 iz3C0jtXvvs/gFekIowwQWq1o08cBc3EnwzvDzhQFdwZcYA0N4Bks/xXONtJySxyVWmM SA/9sEKtvunriF9/lgE55vMzSc4uICP0mT7Fe2zmGrYNRciVvw04lHQGkgLB9yNBNFY8 BlYTY6jNGhu3eX6XDs3WPw74bKNXmqk5SmY4+4fh/3me5MoK5n3ojms7w5J2r5O/4tXd cPsg== X-Forwarded-Encrypted: i=1; AJvYcCUnLY70BiWk/If271heWYuCvg0I9zANCss1yFb+rfIT0LVWcMJpYvBEvpSWP0pCucqwV6ZTmF9khVNx6CH878Q=@vger.kernel.org, AJvYcCWP/3IUCMm0D3Zf+gTleY2tuT4UeZNOBVWIAdP4JEgbuuEjbo7ehbJ8/kdRO7/equ6A310k2phiUJjx5Qk=@vger.kernel.org X-Gm-Message-State: AOJu0Yzm+iNJZz3wojOOze9+nJ/PtinVeYQz7CxmYDE6szNH8kB7Lod6 PH6Mn1iI+cqm3RJHPuk7cPS3acANbfBGuUg3Ax4GwBt5CauNnrpu X-Gm-Gg: ASbGncvETHY4NLGdCXeFpVsicIxY7BPLSciGsA2JKeSKn05P0VmInaL7xdwY7Hpodtm 5l482mVGvz/sLpnvjBTMg5WEXpLDjZTEAkWp5i9Im1gqloT6+vvArLcfv0WaVhnLiJvlha7lRVn HR04Ms8yrA9+T8ldbizKKb0qe7BFgNrsA3i7LuGhBjrDKxUNNHUJXrmwvB5bnW/XcRZen2YErPJ cD2VNDkym8XtFbUTJRGef+LvKKlsfbkRadLXHX64aotQvDPI0Cpdt2nkq88V2LDox0gTtFWl4XD rK5eSJVUV+xvACMJRA9wapIUpSGaP2bqMmlHsRtBhLMj/MB/iu9oENmQMo0tpYSUMpN9biKmqWv SNmOcxArq+Gz4DsPDbM98HA== X-Google-Smtp-Source: AGHT+IFayDpBMS79xivFqH7xf6jKCQW1raM5CGZsxw5i6zi+hzQ0h4CALk7kf9R32eciaIZyk6BJIA== X-Received: by 2002:a05:6512:3e08:b0:549:5b54:2c68 with SMTP id 2adb3069b0e04-54b011d6355mr391157e87.22.1743019983084; Wed, 26 Mar 2025 13:13:03 -0700 (PDT) Received: from abj-NUC9VXQNX.. (dsl-hkibng22-54f8dc-251.dhcp.inet.fi. [84.248.220.251]) by smtp.gmail.com with ESMTPSA id 2adb3069b0e04-54ad646873asm1872136e87.46.2025.03.26.13.13.00 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 26 Mar 2025 13:13:01 -0700 (PDT) From: Abdiel Janulgue To: a.hindborg@kernel.org, ojeda@kernel.org Cc: Danilo Krummrich , Daniel Almeida , Robin Murphy , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , rust-for-linux@vger.kernel.org (open list:DMA MAPPING HELPERS DEVICE DRIVER API [RUST]), Marek Szyprowski , iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), linux-kernel@vger.kernel.org (open list), Abdiel Janulgue Subject: [PATCH 1/3] rust: dma: be consistent in using the `coherent` nomenclature Date: Wed, 26 Mar 2025 22:11:42 +0200 Message-ID: <20250326201230.3193329-2-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250326201230.3193329-1-abdiel.janulgue@gmail.com> References: <20250326201230.3193329-1-abdiel.janulgue@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" In the kernel, `consistent` and `coherent` are used interchangeably for the region described in this api. Stick with `coherent` nomenclature to show that dma_alloc_coherent() is being used. Signed-off-by: Abdiel Janulgue Reviewed-by: Benno Lossin --- rust/kernel/dma.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index 8cdc76043ee7..d3f448868457 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -89,15 +89,15 @@ pub mod attrs { /// Forces contiguous allocation of the buffer in physical memory. pub const DMA_ATTR_FORCE_CONTIGUOUS: Attrs =3D Attrs(bindings::DMA_ATT= R_FORCE_CONTIGUOUS); =20 - /// This is a hint to the DMA-mapping subsystem that it's probably not= worth the time to try + /// Hints DMA-mapping subsystem that it's probably not worth the time = to try /// to allocate memory to in a way that gives better TLB efficiency. pub const DMA_ATTR_ALLOC_SINGLE_PAGES: Attrs =3D Attrs(bindings::DMA_A= TTR_ALLOC_SINGLE_PAGES); =20 - /// This tells the DMA-mapping subsystem to suppress allocation failur= e reports (similarly to + /// Tells the DMA-mapping subsystem to suppress allocation failure rep= orts (similarly to /// __GFP_NOWARN). pub const DMA_ATTR_NO_WARN: Attrs =3D Attrs(bindings::DMA_ATTR_NO_WARN= ); =20 - /// Used to indicate that the buffer is fully accessible at an elevate= d privilege level (and + /// Indicates that the buffer is fully accessible at an elevated privi= lege level (and /// ideally inaccessible or at least read-only at lesser-privileged le= vels). pub const DMA_ATTR_PRIVILEGED: Attrs =3D Attrs(bindings::DMA_ATTR_PRIV= ILEGED); } @@ -105,7 +105,7 @@ pub mod attrs { /// An abstraction of the `dma_alloc_coherent` API. /// /// This is an abstraction around the `dma_alloc_coherent` API which is us= ed to allocate and map -/// large consistent DMA regions. +/// large coherent DMA regions. /// /// A [`CoherentAllocation`] instance contains a pointer to the allocated = region (in the /// processor's virtual address space) and the device address which can be= given to the device @@ -115,7 +115,7 @@ pub mod attrs { /// # Invariants /// /// For the lifetime of an instance of [`CoherentAllocation`], the `cpu_ad= dr` is a valid pointer -/// to an allocated region of consistent memory and `dma_handle` is the DM= A address base of +/// to an allocated region of coherent memory and `dma_handle` is the DMA = address base of /// the region. // TODO // @@ -138,7 +138,7 @@ pub struct CoherentAllocation { } =20 impl CoherentAllocation { - /// Allocates a region of `size_of:: * count` of consistent memory. + /// Allocates a region of `size_of:: * count` of coherent memory. /// /// # Examples /// --=20 2.43.0 From nobody Thu Dec 18 05:08:57 2025 Received: from mail-lf1-f43.google.com (mail-lf1-f43.google.com [209.85.167.43]) (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 4D3E92571B4; Wed, 26 Mar 2025 20:13:07 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.43 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1743019989; cv=none; b=UXGNI7lkgXB5vSo80LuRma13RMMfh9xpxGRo0Qr64TYFHnhk7EpBcZqSD4zINCSXZvo2MuMekaQgqMKcv77RQUxXvetgAuOGZ4d3DxpD3h0L0RhR9z2O//ibVC4xNJECNXKHnYoLOU+W6a8jJDJAaUK/8Kn8aqIchAgJvJ+BDys= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1743019989; c=relaxed/simple; bh=KUEjh4hK5AwiNirfSdvvzr04GjjI9soaojGNwlt+gYQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=KHHlttO775crTWj1eqj40CJAOZsImGRSaf5WL+RNWFbtyRcMzKVREZrRI4TN7rT/MDYp3DRA/BRun0BqiNwwYjUlnj9o0S8ToW0dwvD6FoA3CvABfbRKYd3dm7idGDOFk9CxUsC3pn3HZie2m/HdkCbYlHkG+RbBN6gfANHuQGQ= 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=ksZJiA2R; arc=none smtp.client-ip=209.85.167.43 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="ksZJiA2R" Received: by mail-lf1-f43.google.com with SMTP id 2adb3069b0e04-549b12ad16eso263791e87.0; Wed, 26 Mar 2025 13:13:06 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1743019985; x=1743624785; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=IqPyNQzlsZ2VM/tXZ2FXS0OL5lARsE8hyIi3dCnvYUw=; b=ksZJiA2R/2faCBiKS9KC0Ej8oyN+Dsuk6EwDF+tHWJXabKtry6q8nDdmCUb4bRc+dY 22IW8/A2x8QA8TIpUw/GyJamzB3dpoTajmEDJbDlOVNMJouIOcBJe7W3XExfgY49hD3q LFbDcor4lhTF/Eqc3Kgt2Ybg+FZ/fYnda4q3rI2q+CY0a6vD2UnfddDaqYSswwialUVe b931wri3FeLyKX6Wqpgw3HMeohHA+wEtTbhK2oZ3me1zCrpPFOuU5PIEJWN+drLeqkKu 6FhldSWUVApKvAVDKqSOQm+FI407FYSNV21MJlNkeGXhEBQ47fEoi51HurGkh6m+jpAu GyCQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1743019985; x=1743624785; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=IqPyNQzlsZ2VM/tXZ2FXS0OL5lARsE8hyIi3dCnvYUw=; b=FiiTQdutKqyv154O7YBvD/aF/kF8/lbBh1z9uv+MurLNHt4DVH9MXvCrT4NgXaeVSD 4gnnNo4L8mbxNhVwuHa/wuzwK4DdH2VM2E8mnFeMLpPlncysr9pgDnkEYglSD9+F0fd2 8jN12toIxMVtzyp3JK5zgyGfBNV2JjT2ZNGo8xNPgFQbnSg8l11vPmYrtdn0CvtMwbt6 S5ro/FfWj/QME5csZn4vRgNgSScap4M/14+8UjfWkOdmBFux8ZZtLmk8c7/MZ/MxZDy5 kwan64mLipCEYkoGfEGB4I/Rg4HtM18WWtEo39Zi139/hg2jEpES8d9wEu3UvqWD9Ojj z/Yw== X-Forwarded-Encrypted: i=1; AJvYcCWPD6hbbRXm2kGszNUN1e2O3hLZfwRIK04t9kohG1IroKvBTrAjPJt2R9CePbMzT2ITCcAXUnbV+8XNauDLV2c=@vger.kernel.org, AJvYcCWguosVFTWDFCboCcuOiLKVxOqwDjjWqRVIU+jy0h2h9IvWU8GU8KWczTPX8r9EOn5+9IndI0h4JqgtbF4=@vger.kernel.org X-Gm-Message-State: AOJu0YwhTWUt05n27xkyiyVWcojGVz5VSHAICXZZWYzg6RolTZ0E6ri5 /PJidZMeHmx48+ddYtfWN+P+1zOUw0jdngL76xce1rcAGS0ymkPA X-Gm-Gg: ASbGncsLgavyxkSGrbSWNGrBjuX5IUYnYrLilMTzLnNYezR9KfGAFH5GylmvhD0xXyk k7oP2zWlR/GZCRg7gf5gCz/RffCRBbxxL8YWvngnGAJR/NHEDbMQfXnKMzMb1ke56WholdmOAPo HKQZVgu+/nXyjOlPmgY6bErjVq1PTXCyX+mUn53TMS4TKenSnTFGbdXNMNeJc7eE/8FbdOMTIHu hZu8ZIDK+UL7go1/wtAlEF1lbLpcA46vemNgGmjXSXOmacgfYvHluMDigBww14Ir2GS74Fy/7gy UYRUx1krC/sTjnmE8KAfW3WUMiBY8Z5i7PcuwZaRJY+MiGoSdABLkyIkNz0Mhl3YcQZOOMhdLxH TD5+EUtb9EJFAZW3DqvErVw== X-Google-Smtp-Source: AGHT+IG5DWfivJ6phDkqR8mJ7+AXG7ZqtqivCgyez055JfZ+pxmclpEKwBt74y4guotavXKViI0gpQ== X-Received: by 2002:a05:6512:3d11:b0:545:652:109 with SMTP id 2adb3069b0e04-54b01264efemr392524e87.51.1743019985037; Wed, 26 Mar 2025 13:13:05 -0700 (PDT) Received: from abj-NUC9VXQNX.. (dsl-hkibng22-54f8dc-251.dhcp.inet.fi. [84.248.220.251]) by smtp.gmail.com with ESMTPSA id 2adb3069b0e04-54ad646873asm1872136e87.46.2025.03.26.13.13.03 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 26 Mar 2025 13:13:04 -0700 (PDT) From: Abdiel Janulgue To: a.hindborg@kernel.org, ojeda@kernel.org Cc: Danilo Krummrich , Daniel Almeida , Robin Murphy , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , rust-for-linux@vger.kernel.org (open list:DMA MAPPING HELPERS DEVICE DRIVER API [RUST]), Marek Szyprowski , iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), linux-kernel@vger.kernel.org (open list), Abdiel Janulgue Subject: [PATCH 2/3] rust: dma: convert the read/write macros to return Result Date: Wed, 26 Mar 2025 22:11:43 +0200 Message-ID: <20250326201230.3193329-3-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250326201230.3193329-1-abdiel.janulgue@gmail.com> References: <20250326201230.3193329-1-abdiel.janulgue@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" As suggested by Andreas Hindborg, we could do better here by having the macros return `Result`, so that we don't have to wrap these calls in a closure for validation which is confusing. Signed-off-by: Abdiel Janulgue Reviewed-by: Andreas Hindborg Suggested-by: Andreas Hindborg --- rust/kernel/dma.rs | 54 +++++++++++++++++++++++----------------- samples/rust/rust_dma.rs | 21 ++++++---------- 2 files changed, 38 insertions(+), 37 deletions(-) diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index d3f448868457..24a6f10370c4 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -328,20 +328,22 @@ unsafe impl Send for C= oherentAllocation {} #[macro_export] macro_rules! dma_read { ($dma:expr, $idx: expr, $($field:tt)*) =3D> {{ - let item =3D $crate::dma::CoherentAllocation::item_from_index(&$dm= a, $idx)?; - // SAFETY: `item_from_index` ensures that `item` is always a valid= pointer and can be - // dereferenced. The compiler also further validates the expressio= n on whether `field` - // is a member of `item` when expanded by the macro. - unsafe { - let ptr_field =3D ::core::ptr::addr_of!((*item) $($field)*); - $crate::dma::CoherentAllocation::field_read(&$dma, ptr_field) - } + (|| -> Result<_> { + let item =3D $crate::dma::CoherentAllocation::item_from_index(= &$dma, $idx)?; + // SAFETY: `item_from_index` ensures that `item` is always a v= alid pointer and can be + // dereferenced. The compiler also further validates the expre= ssion on whether `field` + // is a member of `item` when expanded by the macro. + unsafe { + let ptr_field =3D ::core::ptr::addr_of!((*item) $($field)*= ); + ::core::result::Result::Ok($crate::dma::CoherentAllocation= ::field_read(&$dma, ptr_field)) + } + })() }}; ($dma:ident [ $idx:expr ] $($field:tt)* ) =3D> { - $crate::dma_read!($dma, $idx, $($field)*); + $crate::dma_read!($dma, $idx, $($field)*) }; ($($dma:ident).* [ $idx:expr ] $($field:tt)* ) =3D> { - $crate::dma_read!($($dma).*, $idx, $($field)*); + $crate::dma_read!($($dma).*, $idx, $($field)*) }; } =20 @@ -368,24 +370,30 @@ macro_rules! dma_read { #[macro_export] macro_rules! dma_write { ($dma:ident [ $idx:expr ] $($field:tt)*) =3D> {{ - $crate::dma_write!($dma, $idx, $($field)*); + $crate::dma_write!($dma, $idx, $($field)*) }}; ($($dma:ident).* [ $idx:expr ] $($field:tt)* ) =3D> {{ - $crate::dma_write!($($dma).*, $idx, $($field)*); + $crate::dma_write!($($dma).*, $idx, $($field)*) }}; ($dma:expr, $idx: expr, =3D $val:expr) =3D> { - let item =3D $crate::dma::CoherentAllocation::item_from_index(&$dm= a, $idx)?; - // SAFETY: `item_from_index` ensures that `item` is always a valid= item. - unsafe { $crate::dma::CoherentAllocation::field_write(&$dma, item,= $val) } + (|| -> Result { + let item =3D $crate::dma::CoherentAllocation::item_from_index(= &$dma, $idx)?; + // SAFETY: `item_from_index` ensures that `item` is always a v= alid item. + unsafe { $crate::dma::CoherentAllocation::field_write(&$dma, i= tem, $val) } + ::core::result::Result::Ok(()) + })() }; ($dma:expr, $idx: expr, $(.$field:ident)* =3D $val:expr) =3D> { - let item =3D $crate::dma::CoherentAllocation::item_from_index(&$dm= a, $idx)?; - // SAFETY: `item_from_index` ensures that `item` is always a valid= pointer and can be - // dereferenced. The compiler also further validates the expressio= n on whether `field` - // is a member of `item` when expanded by the macro. - unsafe { - let ptr_field =3D ::core::ptr::addr_of_mut!((*item) $(.$field)= *); - $crate::dma::CoherentAllocation::field_write(&$dma, ptr_field,= $val) - } + (|| -> Result { + let item =3D $crate::dma::CoherentAllocation::item_from_index(= &$dma, $idx)?; + // SAFETY: `item_from_index` ensures that `item` is always a v= alid pointer and can be + // dereferenced. The compiler also further validates the expre= ssion on whether `field` + // is a member of `item` when expanded by the macro. + unsafe { + let ptr_field =3D ::core::ptr::addr_of_mut!((*item) $(.$fi= eld)*); + $crate::dma::CoherentAllocation::field_write(&$dma, ptr_fi= eld, $val) + } + ::core::result::Result::Ok(()) + })() }; } diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs index 908acd34b8db..cc09d49f2056 100644 --- a/samples/rust/rust_dma.rs +++ b/samples/rust/rust_dma.rs @@ -54,13 +54,9 @@ fn probe(pdev: &mut pci::Device, _info: &Self::IdInfo) -= > Result> let ca: CoherentAllocation =3D CoherentAllocation::alloc_coherent(pdev.as_ref(), TEST_VALUES.= len(), GFP_KERNEL)?; =20 - || -> Result { - for (i, value) in TEST_VALUES.into_iter().enumerate() { - kernel::dma_write!(ca[i] =3D MyStruct::new(value.0, value.= 1)); - } - - Ok(()) - }()?; + for (i, value) in TEST_VALUES.into_iter().enumerate() { + kernel::dma_write!(ca[i] =3D MyStruct::new(value.0, value.1))?; + } =20 let drvdata =3D KBox::new( Self { @@ -78,13 +74,10 @@ impl Drop for DmaSampleDriver { fn drop(&mut self) { dev_info!(self.pdev.as_ref(), "Unload DMA test driver.\n"); =20 - let _ =3D || -> Result { - for (i, value) in TEST_VALUES.into_iter().enumerate() { - assert_eq!(kernel::dma_read!(self.ca[i].h), value.0); - assert_eq!(kernel::dma_read!(self.ca[i].b), value.1); - } - Ok(()) - }(); + for (i, value) in TEST_VALUES.into_iter().enumerate() { + assert_eq!(kernel::dma_read!(self.ca[i].h).unwrap(), value.0); + assert_eq!(kernel::dma_read!(self.ca[i].b).unwrap(), value.1); + } } } =20 --=20 2.43.0 From nobody Thu Dec 18 05:08:57 2025 Received: from mail-lf1-f42.google.com (mail-lf1-f42.google.com [209.85.167.42]) (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 516C62580D3; Wed, 26 Mar 2025 20:13:09 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.42 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1743019991; cv=none; b=oAj1tnDvMhNkaDuKgdkvGeJFGi/SN/A/1+uBvuNsHD+4sGroGMik8IfUPUJ5s6jyCr0oIK9T9kSGBDmpIr2K1qeIQlgt/lnwGsM3CoK8WomZ6aKB60D/E/4/9f6FnZbzCCILzXXCzbvHl0X/raCkkSC0mtKMMubIMPpLIxVFhgs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1743019991; c=relaxed/simple; bh=gqLyi9zMVoqhf8dZ1h7qevw1bHrpNpkeCv+mNLriNlM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=VeaKmLOII6H914r3wiqDkEhnmUqxtwusLJ3IIi7N8Dym7H0fuyjPC2GMV0ktGrIvk8MgvvY7O2gTRXKGaTRv8CRCEO3d9T2pXwMBrFCNrGo55amDK6vf48kUfZRXQeHcxe6Q8dctzQYpi1ukWUpo0S360aXqAv6FJxtHAmvn678= 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=PeQ5rwwG; arc=none smtp.client-ip=209.85.167.42 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="PeQ5rwwG" Received: by mail-lf1-f42.google.com with SMTP id 2adb3069b0e04-5497590ffbbso270207e87.1; Wed, 26 Mar 2025 13:13:09 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1743019987; x=1743624787; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=W53DecoGOTRTNw2U+SerlppI9Y+PI0pGAG3CfwRejNY=; b=PeQ5rwwGl94r1vctH7FPjdbc17pHqcKmZsouuIUwVqmYvGw0pEORBw01Jm7E0qlnNf 9KYyucwPxkdmy2BTldFHhtmdFfEPw8G10MjiVE4fgQW+OnHHZQ9oNjME2/H0uu8XoTGQ fbs9zMfRDVinT3AR4oQg55PWQCzD+iFjFghKRu29EVUscGtmIrwLYlUXGEoo3cbO6nln Tob6dIbwSN0ay+7FP+a5PLC6W/njSuGycRcLxmisty4gUubJi8n6h+Je+VSDUcqpghC6 6NJZRDRoiMMqOSc3O3um+yRG02OHtqCWE3W0H4fuCaz3qCd2ApFMzl+Uf93rheZzKLwH +BRA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1743019987; x=1743624787; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=W53DecoGOTRTNw2U+SerlppI9Y+PI0pGAG3CfwRejNY=; b=XyhIZROaAVmzk2SGvhWjnG66ly89d/ioYJyvzXciXrAWdyuJ8Kh59uG/HR7V9zhQIM EOHoAcR4rhumHGfmEex4nQ97vHHzdAwAsDxQkzlVa81RR2pFVFDvsEbIrMzTTGTCuAEG nfWBLy/oQlEulYTwPN/oVPO1NmYGv7tsDpgPB3wNjwVeLFReYJmHkHMx2x4YzEL4bjRd 5rGaCf6rwSArOPagNQhNz14ENWK5Nh3xR/NycrbcEVIochUElmJjDINMMy2VaBAO4ZIp a9jYXSJWzYf7bfub4/Xpg/pHHd3HupCWcBvEEz4ZuooEkrCfnjoFJ91PsABRY7d/mCbp RMIg== X-Forwarded-Encrypted: i=1; AJvYcCWJJb4jSHv1H0ZvqUg+/wRyc4QZqDJpeHlULjYdVq+c7j27YvuHqp1l0Yz24aQAm/x6L96q90EB9phLC/dvcI4=@vger.kernel.org, AJvYcCXbDa9oDGZ4NiIWlglcdd4/5WhR6yCk+AD6qiN/Mpb9KGwUdGZDi5JjBZAO79gii94NZryQsyBLI0JsFK4=@vger.kernel.org X-Gm-Message-State: AOJu0YywyUZH/gCEa5D4W815ffBhrVXhvFqDc2en3nB9h2AQnABkjS24 mHMrGnGHyosk23d4PrLWFhos0zsz0HhLvcYrfhJdGev3VGVU9fFd X-Gm-Gg: ASbGncvR8uNoBmu1gauj45I1Wl2iQdhT6eDAWkoIcqYo8oMN+PL2W57ImagiBxpCGZJ zUdKsBs0Ouj0BG+R5cAZPtpne9aKaOFiT/3LD/sey6RFvYxuvGq8n0WlsQpGDeFecckk3j8zXnw WpegG036xRVLgBl+bPzQ9XI7sSgBdXHwGIlzENkFflRJniOWQ3Bvza3YG8YSfIW5JveG8sfKXYe Tn6TLmIm16nk7BLK+o/25sYydOpRRY4Yemu9GpUt51/7addtU3i6KywGiWVEefIJPtFjiH4V+Mw TS/zc3bYhbv/0xBJxpN+vHlYPC2vDpcXVGwhnIKxKtZzfN3yzx3ZzBZXQN6ZJ+KXEXGxp89ZzKP fZTC5AHz+o83sXE03SYaQjA== X-Google-Smtp-Source: AGHT+IF6mqMJizxHDY+F9zAuhEFm/36zPBMO1NkVB0kRHeyeNEM/AoK/eSPeVqXuM8dMCdgMLHtDNA== X-Received: by 2002:a05:6512:1392:b0:545:48c:6352 with SMTP id 2adb3069b0e04-54b012535d7mr466901e87.43.1743019987197; Wed, 26 Mar 2025 13:13:07 -0700 (PDT) Received: from abj-NUC9VXQNX.. (dsl-hkibng22-54f8dc-251.dhcp.inet.fi. [84.248.220.251]) by smtp.gmail.com with ESMTPSA id 2adb3069b0e04-54ad646873asm1872136e87.46.2025.03.26.13.13.05 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 26 Mar 2025 13:13:05 -0700 (PDT) From: Abdiel Janulgue To: a.hindborg@kernel.org, ojeda@kernel.org Cc: Danilo Krummrich , Daniel Almeida , Robin Murphy , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , rust-for-linux@vger.kernel.org (open list:DMA MAPPING HELPERS DEVICE DRIVER API [RUST]), Marek Szyprowski , iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), linux-kernel@vger.kernel.org (open list), Abdiel Janulgue Subject: [PATCH 3/3] rust: dma: add as_slice/write functions for CoherentAllocation Date: Wed, 26 Mar 2025 22:11:44 +0200 Message-ID: <20250326201230.3193329-4-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250326201230.3193329-1-abdiel.janulgue@gmail.com> References: <20250326201230.3193329-1-abdiel.janulgue@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add unsafe accessors for the region for reading or writing large blocks of data. Reviewed-by: Andreas Hindborg Signed-off-by: Abdiel Janulgue --- rust/kernel/dma.rs | 87 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index 24a6f10370c4..24025ec602ff 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -218,6 +218,93 @@ pub fn dma_handle(&self) -> bindings::dma_addr_t { self.dma_handle } =20 + /// Returns the data from the region starting from `offset` as a slice. + /// `offset` and `count` are in units of `T`, not the number of bytes. + /// + /// Due to the safety requirements of slice, the caller should conside= r that the region could + /// be modified by the device at anytime. For ringbuffer type of r/w a= ccess or use-cases where + /// the pointer to the live data is needed, `start_ptr()` or `start_pt= r_mut()` could be + /// used instead. + /// + /// # Safety + /// + /// * Callers must ensure that no hardware operations that involve the= buffer are currently + /// taking place while the returned slice is live. + /// * Callers must ensure that this call does not race with a write to= the same region while + /// while the returned slice is live. + pub unsafe fn as_slice(&self, offset: usize, count: usize) -> Result<&= [T]> { + let end =3D offset.checked_add(count).ok_or(EOVERFLOW)?; + if end >=3D self.count { + return Err(EINVAL); + } + // SAFETY: + // - The pointer is valid due to type invariant on `CoherentAlloca= tion`, + // we've just checked that the range and index is within bounds. T= he immutability of the + // of data is also guaranteed by the safety requirements of the fu= nction. + // - `offset` can't overflow since it is smaller than `self.count`= and we've checked + // that `self.count` won't overflow early in the constructor. + Ok(unsafe { core::slice::from_raw_parts(self.cpu_addr.add(offset),= count) }) + } + + /// Performs the same functionality as [`CoherentAllocation::as_slice`= ], except that a mutable + /// slice is returned. + /// + /// # Safety + /// + /// * Callers must ensure that no hardware operations that involve the= buffer are currently + /// taking place while the returned slice is live. + /// * Callers must ensure that this call does not race with a read or = write to the same region + /// while the returned slice is live. + pub unsafe fn as_slice_mut(&self, offset: usize, count: usize) -> Resu= lt<&mut [T]> { + let end =3D offset.checked_add(count).ok_or(EOVERFLOW)?; + if end >=3D self.count { + return Err(EINVAL); + } + // SAFETY: + // - The pointer is valid due to type invariant on `CoherentAlloca= tion`, + // we've just checked that the range and index is within bounds. T= he immutability of the + // of data is also guaranteed by the safety requirements of the fu= nction. + // - `offset` can't overflow since it is smaller than `self.count`= and we've checked + // that `self.count` won't overflow early in the constructor. + Ok(unsafe { core::slice::from_raw_parts_mut(self.cpu_addr.add(offs= et), count) }) + } + + /// Writes data to the region starting from `offset`. `offset` is in u= nits of `T`, not the + /// number of bytes. + /// + /// # Safety + /// + /// * Callers must ensure that no hardware operations that involve the= buffer overlaps with + /// this write. + /// * Callers must ensure that this call does not race with a read or = write to the same region + /// that overlaps with this write. + /// + /// # Examples + /// + /// ``` + /// # fn test(alloc: &mut kernel::dma::CoherentAllocation) -> Resu= lt { + /// let somedata: [u8; 4] =3D [0xf; 4]; + /// let buf: &[u8] =3D &somedata; + /// // SAFETY: No hw operation on the device and no other r/w access t= o the region at this point. + /// unsafe { alloc.write(buf, 0)?; } + /// # Ok::<(), Error>(()) } + /// ``` + pub unsafe fn write(&self, src: &[T], offset: usize) -> Result { + let end =3D offset.checked_add(src.len()).ok_or(EOVERFLOW)?; + if end >=3D self.count { + return Err(EINVAL); + } + // SAFETY: + // - The pointer is valid due to type invariant on `CoherentAlloca= tion` + // and we've just checked that the range and index is within bound= s. + // - `offset` can't overflow since it is smaller than `self.count`= and we've checked + // that `self.count` won't overflow early in the constructor. + unsafe { + core::ptr::copy_nonoverlapping(src.as_ptr(), self.cpu_addr.add= (offset), src.len()) + }; + Ok(()) + } + /// Returns a pointer to an element from the region with bounds checki= ng. `offset` is in /// units of `T`, not the number of bytes. /// --=20 2.43.0