From nobody Sat Feb 7 20:44:05 2026 Received: from mail-lj1-f182.google.com (mail-lj1-f182.google.com [209.85.208.182]) (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 3A20A22E3F3; Fri, 25 Apr 2025 07:37:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.208.182 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745566665; cv=none; b=RFQWxIByeD50JM5WgvuaFrsFliCGEoQQxRDiEH2HvScexScXtb86yICeenfmosSCEl5vRyF7xOnIuXSAaKHEMl9xGdTYOzVZYK+uEBhqOO9PdXtXJKbUizmg1yMzyD3ahiS8mbsSAc6y4kI8EbkbhS311tKhmaLadEOKMIYQcts= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745566665; c=relaxed/simple; bh=WqzuZjN2OlAEP5U+WrT20wORev7uTKByfRxp1ekMkR8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=l2aLLm/hFJzdV3fdhn6r8UEppdjOQokxg1KZ2OI4ePfgVmiee1H4gNDNh9ESLbCPGFKP9ZltDvEZIlDtRHTkveB/1GrKA0qK9dVMGluAB7/4oA4YbeKtpIT0iSNh/VRcqr2ySyE5o50i95mpWn/T3ypHVdlxxAzg38DmeWxpcF8= 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=ncpAAgJz; arc=none smtp.client-ip=209.85.208.182 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="ncpAAgJz" Received: by mail-lj1-f182.google.com with SMTP id 38308e7fff4ca-30c44a87b9cso16447851fa.3; Fri, 25 Apr 2025 00:37:42 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1745566661; x=1746171461; 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=q4Cn3iGXk2B43PzN7CtJiYrgGpJ21xhd2OrhojDiLX8=; b=ncpAAgJzKje/ISvhnrK98+zoPhjca4u4G9l8NCzvmvPPZqPcCrr3iVCd//ktWBLEZ2 jk4Yh53F2g2QEGFb3ohQDmxW+v3HIxGnFbMU5BB1UR/DyiJpR6xlHIhqDnKMu0MRoEIh XYCjbINM0R2WZBZUqFiZpjoSoZOVxq7WB9Xw78LcN7VdcKLZkhtRxFOBj8Le/S+IAk2z pHPCoxbZfZsvA7FOScL7y5B9lV4iw1f0o7cX1dT8Jj+I0IC76KoLgUGwy+nMMnbC1DXB lYpsFO6kSLxzv3pVVhu6rBqVLC91NDxrl08qSh+AX9avD1v1rHwr1VM6O2q3dzUPbpW/ vZ8Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745566661; x=1746171461; 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=q4Cn3iGXk2B43PzN7CtJiYrgGpJ21xhd2OrhojDiLX8=; b=A8WWphdRgv2cpsykWkPWbl6P1B6w4enLh8Qn7BFvejBQN271N9lnx2uFV6wryIAp6A 1gkntpemUJnUQtA6lfmEy0EbTBnbDwSppT4OD/Gs/ZAazXBs/U81UG+8h1+9Kv/PDtNE j/ws3cAQy4WSkqBOtIy7oSyptNJhDvi6KzijdseCCAq70Xc0Iv6fm3QMGr72F8IoxIxB BTHQB0tDYswLKJw0ao7PkQ2YEUfRBmwfai0i0/f3k1kRGssUhiEYQAeb2rIlKADwx8Pg a5D6BNi3UDt9LW4u6lXj7Ck4butSzwESjsaTzKWOaPILL/YsYA6oVxrFscfi8U2bJ3Im 37jg== X-Forwarded-Encrypted: i=1; AJvYcCWBMw4n6yaCr8pemSsYgl3rMn7S3LhYFjK/2icf3i5N+sh8UbkKFtEN4IcSQTaF6PyOwGIzinCRhtReDgQ=@vger.kernel.org, AJvYcCX5NxuIF7369TC6GFJ3SPU29vg8L7UkkQqmiTfacV83vFt8uDk/dx14O7XjKRpqZSmC11sU65yixtJD64y+7vo=@vger.kernel.org X-Gm-Message-State: AOJu0Ywozwgl7ck65rwfLdGBG2jDtvAwWk2ETIEUgIZQIYgIbJ4QDJC6 HoCTYd7pXX5Hc9mgCY4U8M6Rf1H4plUADngrvwOUgeuf51ieLF+0 X-Gm-Gg: ASbGncsa5s6D2qDhp290t45+CXZiRfrEMV6ZHL1l0FT0RW/hzBFHrtlyHezj+lvBjZa YZ0BV/JjIxDreeZCBWyiAyziym0PzbSkrMWiVUGZ7wcmTxqqIw3BNlfgxKRp/5uNEP8+ykHwSFX l8j0K9FhlSKAxrbeVNlJ5wMtS4kD0zHEjjnZyc1PX9cXV0zdDZUnS7oLnbhHjyw3dhZUrzl4Fxf 3RUPF7722NbC7T3h0bBw14kDSVypSR7xlMTDPhIh/jSZv/DYZmujNjsKCwUtIxp1QKyqdQjaD9y 4NGljRuaJs0Jj3452RKfSy1Sbt/IuoQ5enXfZGO1Q6eo/woOiXKg2MrQ1SImOnHPNxMcCgrZnQd OcLnXKKx4SyfYAGCBQ+8Xpfcdp6B6 X-Google-Smtp-Source: AGHT+IE2pq4NMC62iFfUfxNncOQ4QYZVoaBSclW1fBNBOsWB4SrRHwoy3yvkk2RaMxEl6RrMrQTP+Q== X-Received: by 2002:a05:651c:3129:b0:30c:dbf:51a5 with SMTP id 38308e7fff4ca-319080e469emr3639321fa.35.1745566660941; Fri, 25 Apr 2025 00:37:40 -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-54e7cc9e9a5sm504391e87.132.2025.04.25.00.37.40 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 25 Apr 2025 00:37:40 -0700 (PDT) From: Abdiel Janulgue To: dakr@kernel.org, rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Valentin Obst , linux-kernel@vger.kernel.org (open list), Marek Szyprowski , Robin Murphy , airlied@redhat.com, iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), Abdiel Janulgue Subject: [PATCH v3 1/3] rust: dma: clarify wording and be consistent in `coherent` nomenclature Date: Fri, 25 Apr 2025 10:35:40 +0300 Message-ID: <20250425073726.1027068-2-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250425073726.1027068-1-abdiel.janulgue@gmail.com> References: <20250425073726.1027068-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, in addition to improving the clarity in the DMA mapping attributes documentation. Reviewed-by: Benno Lossin Signed-off-by: Abdiel Janulgue --- 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 Sat Feb 7 20:44:05 2026 Received: from mail-lf1-f49.google.com (mail-lf1-f49.google.com [209.85.167.49]) (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 E43B622E41D; Fri, 25 Apr 2025 07:37:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.49 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745566665; cv=none; b=h0FbD/lGn0vFsftNqRnHdf3QDB5H9IR9u7fnwqTXYbCOLztoAK3bdiNCJYvekXqy0it4KO7KeIn4nc5rWPsmEokqrBIWQspK3nTGL5Ype/MHE0OiG2a1TSB7ungFtj0cEy+ogaI4oPPH2MkMw99IlN9z+RwF718jFiauaTN4xAI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745566665; c=relaxed/simple; bh=p9KuyczkRk04gYMkFGGJnxWv0QoLL1+yqvWdiiBeT3o=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=htrBeVrsJu63qjoXB+rWUfzUHbW50LTPjmi/rxAvGYLPk+9dPmIENv/YOHumt+pfjBNPfdo4tJhB7utHphadCrCDa/ssoK41FKcL1Fuq23ySPCO+sbSrreSN08b5hpYxdru3yYY3n8aE2qBAS31xKuq3R2sk2Gl3FRj5oEFzcHE= 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=XmNxgeEp; arc=none smtp.client-ip=209.85.167.49 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="XmNxgeEp" Received: by mail-lf1-f49.google.com with SMTP id 2adb3069b0e04-54b09cb06b0so1914037e87.1; Fri, 25 Apr 2025 00:37:43 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1745566662; x=1746171462; 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=a1kYjA5v2ZxXF+57lF/W+Zxp4CYc0PDu1KuPLGZgYLw=; b=XmNxgeEpkZfthsc7n4Adk7jD1xHQWiOig/LY8esW1Z5LnGpwz5YAiUIKv5T3ionm+T 2wUCMZQVDLFVFVP+VacXa39C/t5QqqwMMbzyTQmgut18qYuLqRsqJhF66KuR13qJ+hQ+ pPx9V8m+qyEbjLiVbY+Mnj0KC6G0XamHHXWTMZn6QGAIsUyaeDMGMfOb9zlNcrMDIt0z FWwMLcFgPT8kssJAaB0w3caefnJEMfcxe0FhAfobgMhbvj+z3gNvJu7nGdiZRy/K303e GE+C+gw6CU0Gen3Nh2AH06dSksZGI4RNhLp3az8dD39eto91uFXEHBjcteJDlEr4QebI ryhw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745566662; x=1746171462; 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=a1kYjA5v2ZxXF+57lF/W+Zxp4CYc0PDu1KuPLGZgYLw=; b=pVah+QhC4Nz1WGq7IuWz+vTiW0T9dqG1mV2gMQtGqwhtxvSmVMl1t2yQZuodMuGlbD cUxlF7ObyMoexm0y8F9tPpb92P7dtIUDAzh74JLGNooZb+PgNmfDbyM7tJgwIEOH7bMy vh8tW49ATk75l0W47xL4SWPSdi668n5y50P6NpzpTIMPx8oVpqsimoFmluG3JdOtvFD4 q37fMUj/4fOeXz92JJP/wPSSpe262vMXKPG48EkHlH7nAAgZmIS5rfOyPkS2rBwXt0AN mali+f0Rr1qp3RY/CwuQy/HAOfr6dLZlsVV9IFG8us7PwLteAlWK1ssWz446DrvaUtq8 IeYQ== X-Forwarded-Encrypted: i=1; AJvYcCVR5XjMjmoNYCv8NFmFltbdjQFRsYOtZYlk9qeqSzptqOdWZ1lUJpsgrJKZjwhsoRrDXruzunpa9XJuSWE=@vger.kernel.org, AJvYcCXkiCHGCf/1tZvJuDhoJXfeSBT7xOEbTbNWS4e+qxo5y1f7M+lTh/6p4SlEE5k4h8PfAxgvMvDg4Z002XU/YkU=@vger.kernel.org X-Gm-Message-State: AOJu0YwdGVfTUlwDA/YsoK1ZzaGpIwxSiUv3b7vkIWY0zGSyrXrz7uIV ejKjKdgVWcFp3wKusZiIDsz4bx9qTqlfmyXXn9Bo7vfolK2L2BjO X-Gm-Gg: ASbGncuvw8OfYRoWPuzi3RS2goEGFBzlnX16Cg2fHwUjQOt2I770OfRogtVSHcJH7OJ cblXpoz/ehPmZUpz6oI3P/9ar5En1Csdx+zU/7NHusu3mqauvWXmjyZcdWYFfI0Y2D3aCpj3Kc+ bfbUrGVBFj8cEiExeUnA+W9Z9oFlEIISYx4rCa4sDbnUfRci0XAqxcthbP1xI9JLaS3HVOfOzdF kpt6F9FfffcZ0Va1aYMfjTclOrjXop79SVs4X38BJMYq7S3Jy/YjEdHcITMAMo3AI/1ju4Nfqo4 fOySP0q3B0CIKgVMsbUSCyidrHsjK/heJqWNs3sqIF/0NI2OnaKUysISswAIvtxvM8BYh46qioR W7DlaQ1yebN3ECcmIVqo5rJJbAoWc X-Google-Smtp-Source: AGHT+IG0vJEK9kerNJ+x87uQuMGI3i+Ng+kKkkJ+CqAjbAHJkHQPScomcHYgoQzdCHw9f91km5IT7Q== X-Received: by 2002:a05:6512:2399:b0:549:2ae5:99db with SMTP id 2adb3069b0e04-54e8cc0e6bcmr383224e87.45.1745566661791; Fri, 25 Apr 2025 00:37:41 -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-54e7cc9e9a5sm504391e87.132.2025.04.25.00.37.41 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 25 Apr 2025 00:37:41 -0700 (PDT) From: Abdiel Janulgue To: dakr@kernel.org, rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Valentin Obst , linux-kernel@vger.kernel.org (open list), Marek Szyprowski , Robin Murphy , airlied@redhat.com, iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), Abdiel Janulgue Subject: [PATCH v3 2/3] rust: dma: convert the read/write macros to return Result Date: Fri, 25 Apr 2025 10:35:41 +0300 Message-ID: <20250425073726.1027068-3-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250425073726.1027068-1-abdiel.janulgue@gmail.com> References: <20250425073726.1027068-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" 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. Co-developed-by: Andreas Hindborg Signed-off-by: Andreas Hindborg Link: https://lore.kernel.org/rust-for-linux/87h63qhz4q.fsf@kernel.org/ Reviewed-by: Andreas Hindborg Signed-off-by: Abdiel Janulgue --- rust/kernel/dma.rs | 54 +++++++++++++++++++++++----------------- samples/rust/rust_dma.rs | 28 +++++++++++---------- 2 files changed, 46 insertions(+), 36 deletions(-) diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index d3f448868457..a61da5eeb017 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) - } + (|| -> ::core::result::Result<_, $crate::error::Error> { + 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) } + (|| -> ::core::result::Result<_, $crate::error::Error> { + 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) - } + (|| -> ::core::result::Result<_, $crate::error::Error> { + 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 874c2c964afa..9e05d5c0cdae 100644 --- a/samples/rust/rust_dma.rs +++ b/samples/rust/rust_dma.rs @@ -54,13 +54,9 @@ fn probe(pdev: &pci::Device, _info: &Self::IdInfo)= -> Result =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,19 @@ 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); + for (i, value) in TEST_VALUES.into_iter().enumerate() { + let val0 =3D kernel::dma_read!(self.ca[i].h); + let val1 =3D kernel::dma_read!(self.ca[i].b); + assert!(val0.is_ok()); + assert!(val1.is_ok()); + + if let Ok(val0) =3D val0 { + assert_eq!(val0, value.0); + } + if let Ok(val1) =3D val1 { + assert_eq!(val1, value.1); } - Ok(()) - }(); + } } } =20 --=20 2.43.0 From nobody Sat Feb 7 20:44:05 2026 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 19C3922F76A; Fri, 25 Apr 2025 07:37:44 +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=1745566667; cv=none; b=MMfvHv4DatPF5fpiHCXtR8VSdulbNMRPPQbaG8CDCkbCOW5n2eAlyWTBVIUiMW6Q7Ke1uL+AWe22XxBiUNU4Q9UTBVyVWjAlppt4C0/MqzjnQsXoVMK/rHk/QDFv/8Lf5vam9DfRRTU6q6kiy61HGKEv6IjkT45dfOnBHoGlx5A= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1745566667; c=relaxed/simple; bh=XWuGO4SJLJGrF+nTghBBzNefxbhT1CZpxRKb9GjitCk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=kqn2aZ045lufO2ULPxrA/nXKUdFwapbd/S3LnO5+V57AaTq/y5lSW8yeliTHWpwxcjItP7Y7xsJmAkADOBl7cAIc5I404msU/N/F2QGfxC4+3vgDA3XUiSyfXRMqJ9OuCsHZMFsHe2pQEVlof4uGFaAtdUvloI7V32Pg7GKxhWU= 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=gUwGbhrr; 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="gUwGbhrr" Received: by mail-lf1-f42.google.com with SMTP id 2adb3069b0e04-5498d2a8b89so1971387e87.1; Fri, 25 Apr 2025 00:37:44 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1745566663; x=1746171463; 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=3I7bm+ySgu/DQq5ttF0NDzcE8tALma2xJRSt3C9wY9w=; b=gUwGbhrrwPpuDCZdRn8Kn3QYxkQby6YNgqtqmPBOi1x5hJuMPj8WJsOTSEE9+ZWuFN LFaQUxRZoAMy9dr3pLIAn98mxxobp0n73xKjzreuTfvRejbvjtGqangXdUhzBJo8dQG0 B2duldf0vkPrmljhELZvuAQJKsGjLE1r9VsmeoWNHiByE68AJ3rg/nnS7daJ0H4SaXof N4BSr+66HF9hByMGyBzzhBK8g9VPIDHm3kczNCm0sUek9evcl7SYfdIqzo9gj0IL8hju YrgodAvYt4OqeuAMAIhRgLWNyydkAXMRdSV4TR9OHannnYHRTB+7VFhkaX0uDHw+duRf 4rFw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1745566663; x=1746171463; 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=3I7bm+ySgu/DQq5ttF0NDzcE8tALma2xJRSt3C9wY9w=; b=m5kTbV17EWeJa56uzqYO8OaDzvF4WiSL61PEa82ewG2iYtr6KRzmVijLO/yF3nWjWq gyzCS6XY4ZCcDG/Qvlh8ZBENDEEQdIaTcbVk0ybtWCcHRT4u+qJre5LzUx69gNAUZwfi khpVjQFHWYIAbXKqC9Y+CxEb00QUqw3p7ZfjDfOz+9F/JNshRywL8WF+h+xx1GkeRwcc rZtmDpZwGhbsregtypfvs+kqCi2wxOEFpFF9yNZgslTBgPqeHi050ojXwtd6lDpWsLbX mB992TTf1yrcPPWSEt8XmInqW8HO808Js1hWEHeKZrK6wq6PTPxFnihQVQIqhiBUToFN M5Mw== X-Forwarded-Encrypted: i=1; AJvYcCV2vwyJntpa4SAHiV3VuHTiYKVLWi8RLzVJioXZjnqvWAINOt4knvqJeIckDFBma2sOy2++kxMtLypQU31HUU8=@vger.kernel.org, AJvYcCVBUFHnNoZgrr9Z+3DWVPNbpRGCkH4Odnp4ITsJJfEHC2IDfkvol+1FLqSqWZYrc1vgRsNGI8OPxNnNtnw=@vger.kernel.org X-Gm-Message-State: AOJu0Yy7iFcjWEI9vwx7vOnURQm/BUDnvnKmbLzKlb8S7NPQ2kGwDRud +5IKmqacMLiHqEB6WrrFz54rDvMwsvSdedmiSpYggiPbTTx01D84 X-Gm-Gg: ASbGncuSteeVqdltyvdDZ5ZxO4gbunNi1yYeSvCIuWWkxeXGWIH7UmaaCyn4DmV7iYR Nen4p05/AxoSml6p7Tl10vKjWUt6dFy/QAhRnqTUl5IzqY7OUWmlJUtjQzSBFpzX+rF5nfJ25lu iJFIjM8wv244AYmyOWxwpOWoaYPnzno32jpNwzHzxq9eaVnVjxvvbjjFC5TvPQzwIrIx3qyG53v tO6gM9lp2TrdEAJPo3qKy70K/5g75UshlXAPgPsc/GVawjE8SJDViu9wvg1rc7Jzgfxi3YiBtP5 yr/iXUIbJmZahZYSL7yr36B4tjcZBHCRfnwazWuS0/qRzEgHpGwjWZdWuN49L6aZsspFhwPadvg +CRjYvgTIiC5zwg8WHGIFiiJo+/RV X-Google-Smtp-Source: AGHT+IE/O7y+ibpJZn77AUv3aPfHPZbiY7wPyl4ijZldhKUFWJKAEQIowa051VjLOyzso8Bq8UG5fA== X-Received: by 2002:a05:6512:318b:b0:545:6cf:6f3e with SMTP id 2adb3069b0e04-54e8cc0f2c2mr287610e87.49.1745566662719; Fri, 25 Apr 2025 00:37:42 -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-54e7cc9e9a5sm504391e87.132.2025.04.25.00.37.41 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 25 Apr 2025 00:37:42 -0700 (PDT) From: Abdiel Janulgue To: dakr@kernel.org, rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Valentin Obst , linux-kernel@vger.kernel.org (open list), Marek Szyprowski , Robin Murphy , airlied@redhat.com, iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), Abdiel Janulgue Subject: [PATCH v3 3/3] rust: dma: add as_slice/write functions for CoherentAllocation Date: Fri, 25 Apr 2025 10:35:42 +0300 Message-ID: <20250425073726.1027068-4-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250425073726.1027068-1-abdiel.janulgue@gmail.com> References: <20250425073726.1027068-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 | 85 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index a61da5eeb017..e01bb7e7c440 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -218,6 +218,91 @@ 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. + /// + /// For ringbuffer type of r/w access or use-cases where the pointer t= o the live data is needed, + /// [`CoherentAllocation::start_ptr`] or [`CoherentAllocation::start_p= tr_mut`] could be used instead. + /// + /// # Safety + /// + /// * Callers must ensure that the device does not read/write to/from = memory 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 > 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.= The immutability of the + // of data is also guaranteed by the safety requirements of the = function. + // - `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 the device does not read/write to/from = memory 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 > 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.= The immutability of the + // of data is also guaranteed by the safety requirements of the = function. + // - `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 the device does not read/write to/from = memory while the returned + /// slice is live. + /// * 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 > 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 bou= nds. + // - `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