From nobody Fri Dec 19 00:36:18 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 B230E20C460; Thu, 10 Apr 2025 08:59:25 +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=1744275567; cv=none; b=LNwEQPLbmCpB6wR7Ca0fJ4YW69PpNlcBDImPBS1cTAB3sfYYJMh0SBjnrtiXrcuO3OuluufGMOlK9y1lsS/CpkpeSbN4zBq6Y3qD89QyXpptpUQZm3dMpHYWfGzZdzY4iF7zGzfBm5tDeAUEm5Qn4lx7JOFBybbrzJqc7un+pak= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744275567; c=relaxed/simple; bh=WqzuZjN2OlAEP5U+WrT20wORev7uTKByfRxp1ekMkR8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=t9zfQcVerKbG7cKphVMR8QR7D3UvAfqmU0MNoBpBY3QJi6tg5FKpEOfYQYk8BfWL801xt7d8HpHYULFzk8glnzm8KsjlsYUOe+wIHL+fft1RksegIt617+QKnMSZ8SR0MvMTmVCiipu+sA6NMhqQn+H+HYAsifMiTLXmwQW6ri0= 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=fUOjcFDi; 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="fUOjcFDi" Received: by mail-lf1-f42.google.com with SMTP id 2adb3069b0e04-54298ec925bso850903e87.3; Thu, 10 Apr 2025 01:59:25 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1744275564; x=1744880364; 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=fUOjcFDiEwMlcZ/uOwK8/3CyRCqVBZD0NX3cZuwFxqX8VUtw6rPUvX7yo8PuVz9yam 7ujm0xzb+QWXgn20BldOWbPlQ7ai0RvYDdISkrJRu0Eh3zkv4zsgsCevJ9nbCyqp4sC8 mQcEyRmeEMctyUGt1oFKmNZjins3IeloNbEVqyeNuNWNNe/G5pd8iemDhqKCnAUiy/Hd C2SS9SmNizlqixQXgR/t/LHXdFnhqDAx0eXjI2EbtsMvzOLY7Q6k7om1gW+9+ZK12TUf QAWM1XcEghPK9QBZm4Ew2b9qYy4y7bf5CRzBVWDB+0nF0J3ZbDa9Ud/HgZb2wwzxvadm D9Lg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744275564; x=1744880364; 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=gfOFB9SUu3iszTUTPbVBgK9JSH7d0yThjyYNQ/5V5jybXoRXwziC1w0Ha8jbleO8KZ BM906EHS0ZhWcxBXWLbA4wYlT1LFxTlphjE6s1nAy9g1UAkSdTfIGtA/tMrZB+igLEzC q7TJ7bfDhJAv1/Cb+EhHRQbxQHMLrI8VfiB7rqEWQx+IBClQ5lMwjBT5PwdqUNWLAis3 t3Iqej/G+WiJztxnJatHNIOjnbrwkYYcYz+1hhu4o1Qp+QmTCcDFJZUUGzyO8r4Dud4f NpdDMPgpQx9/5S7obt4Yp32GFWDP0SmqL+WWsGdkHlHomYVW74FavH6WfShyHfL+374n HVFw== X-Forwarded-Encrypted: i=1; AJvYcCUOnMhUsbsW4vTsbRUugOd9fU5D9IybcUgCHOBkvPrVqcE3PfkbApU+SipgavOrKdSNzzmaAQHNgR7x+sE=@vger.kernel.org, AJvYcCV91yb3L2hKpGtIKogKpSgim8kgJD8ZcizkbDquEOmMTMZw+G31P0DYk544WrbF/4ldtvcp12HokNWxVZIZQoU=@vger.kernel.org X-Gm-Message-State: AOJu0YxpdSX60qDImw6WBD6o26XUwI5PK9s1E6gIAbhO+4v9+ObJo7ED AimcmdMS5dJuXX3fIfxhUmI8H77KNDbsLAqzgxRrp4usddeRDCKM X-Gm-Gg: ASbGncvDeogt+rl724mTiFYvVKR9h8Ikne/fHrUitddl9g3R/k5iU2nLWO/GAIeTd6A RZXoPQoBb68ZHKoiak9J8yPNxXKSfCYPo9dnoIK3SKYkUzpge0MEO1qC9VH6o7lkzQz5+tmqSYp s+BdNxI/iQMpOphMfX9yt1S30EMx+0SBAWZFNFZ+9ngKd4qNykeZLMBKy328rXXjN09MCm9zt32 cMFmYnwrusyrkn1+qPTk84DCoO6fB0/ReZEyEb2JBbtmZ2gkJFNQ69ZNR+7YldZGtyssJlGcfbD KGRRFZ79+AfkZm0Od0aa+TZpckKlvy3XfexvUcsozFFWICGKI8boto6xBKcKTOMbn6ms1huXpFj AvdNW1FIF/equYLA2LFP2tDby+l1T X-Google-Smtp-Source: AGHT+IGs/lD9lWhhqJTHnVSN2M7rMU3M0DOoajmMiMIfO1CH0MSvgj//lmfzQx4yyiHxY8DPuESrdg== X-Received: by 2002:a05:6512:1109:b0:549:38eb:d68b with SMTP id 2adb3069b0e04-54d3c5c0554mr469398e87.33.1744275563485; Thu, 10 Apr 2025 01:59:23 -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-54d3d50285csm80875e87.110.2025.04.10.01.59.22 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 10 Apr 2025 01:59:22 -0700 (PDT) From: Abdiel Janulgue To: a.hindborg@kernel.org, benno.lossin@proton.me, rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Alice Ryhl , Trevor Gross , Danilo Krummrich , Valentin Obst , linux-kernel@vger.kernel.org (open list), Christoph Hellwig , Marek Szyprowski , Robin Murphy , airlied@redhat.com, iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), Abdiel Janulgue Subject: [PATCH v2 1/3] rust: dma: clarify wording and be consistent in `coherent` nomenclature Date: Thu, 10 Apr 2025 11:58:16 +0300 Message-ID: <20250410085916.546511-2-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250410085916.546511-1-abdiel.janulgue@gmail.com> References: <20250410085916.546511-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 Fri Dec 19 00:36:18 2025 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 B9D8120CCCC; Thu, 10 Apr 2025 08:59:26 +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=1744275568; cv=none; b=j8txQl7LXlAqWtg6DqUBoFvBka4KxBdDpyunzzjLBENvPHgCI1Le7J7wdtG4Nh/ZjDg6D/ra1OZ9IIlQb8Y7u8ybOcfuJ9SklO8l5aVHu7VM5roJzb/kwXwXjFvZQU/DlH1KkUzzNIaNtBW7j1b4Fsjl6uuQezn1wqhDD7z12D4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744275568; c=relaxed/simple; bh=ym65ZHl+x7j2UBFJ7WrJbNmKqz9rKOx7DPKi9PWmqfw=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=hkCmGdCuMK229CJkj2Qcuo06q1g3OjaxpsDDG6BtAQVcPJwgbZiGz9tnbn8om/2yPBaUJW7OtMTYrZE9WCqMoJtLbqVnicnFpFrKt+bORBd6oyZpxt2qUMXNplf1R46ReK1+VfosSaldQRNM5LDmBaputnlE+jwiRjDi7SwZXlw= 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=mFdJfWTD; 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="mFdJfWTD" Received: by mail-lf1-f49.google.com with SMTP id 2adb3069b0e04-54d3ee30af1so224689e87.0; Thu, 10 Apr 2025 01:59:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1744275565; x=1744880365; 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=quYlemSJI/IPbTuyW/ur+mjtFnxkDwGn/F831OhHW4A=; b=mFdJfWTD7Psr4k4JSgFq0c5k2tjuDHOzTiUZ69QBl8mUFZaxhniH+JX0Db0hapCkpc GAFuK4HJuiaBqnJ0teUdAhvYmbXpnVwzGzxkXtUZ0IlkGXqvJR+89axR4uxzj/3cy8aY 6ehO6e4gJNafmRQgsF9k+sBiCWlnITWEnnf9lkbDa2vr8KhJCnOK4KlY03qLllGvR+lA xX8hKyoh0Dc0CC0VfM1IppsjIFOxEqBnjKLltEKSG2RfKApEnilQbr1PwIRBkCdufJXx VjQh68nNkv95yortpSwA8N04iBcT3+v7BzZ5v1Zqehsn2SXzeJI7i3q/dNdho2Yt4Tjf kS9Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744275565; x=1744880365; 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=quYlemSJI/IPbTuyW/ur+mjtFnxkDwGn/F831OhHW4A=; b=kGYoxh3migAUs6+7xZsFlp9iKFEIJDGje1KGIQF17oE5mNR0OlN8xeAr/hJJkukRqU msBL9xGZzkLvmgzcTHydlGBMlmAOs4jPNiaUDHAwESooOXA1ujKQ6xklfq4x9HDn6YCk uXbiJSyKCrcMHo+Q6eik71U2nIG5tcyH06mvcprld0gqN6AyzKVztP9tuCUEQ5aa4b+c M8EBqvKadsP06FjuJk3/2NJOidtfQg2B4xO5amI1ZnKxExwnqkqTEPbe3ASilpkZnVJV PnB9L+jMn3HZhTXa/03CB+aW/XneTkdaU64yEibq+02cLLkySoygterKjOzgyEmU1rgI Q3Ww== X-Forwarded-Encrypted: i=1; AJvYcCU1DFqafC5391S6N85KiBACZl2lQLRJK9gNdub5cXr2N+FbtZ7YMCNJJm3DAh4+M/+bMoGO85EQzMWD+VdxGpY=@vger.kernel.org, AJvYcCUjs1P5Xt7oPcD2IOnLIwc7vxCQwkpBsjLEkwgK6GWXiSQjvq64fr/6n6QiYGw6wBRmOMLZCwlda8zvv5M=@vger.kernel.org X-Gm-Message-State: AOJu0YyH+nsXpkHBZ1pWar8iNc/lX6niqgXTwrG27ejxTdA0sZegJkj/ iAWBmjodQ7wTBrKmSDYf6UCAqx0Ti+mhVO614AFJPlSEKFEt9KL5 X-Gm-Gg: ASbGnctS0YJD3Q/q41T0wMdU8XnXjqEZoyCYuZ3I31SLr8qDcLsIVQo1dgkkUDtkH7Z sTu6hY3X+Uc+8S8PiYRDYBKVBjizARVPAEP0wE4cjxLZX9ALih2D/ERfIIM8bj+dcCqVmjs0NL2 SWk0u13X3JsDYQmbAvd6aCSKFUc58o2Hql9831WRKZqWiJGFfmk40IgOkF+Ps5G4Pct2xCkSRoj r69B8gPGMCoSUqFo1RB8A8W67azkIa1HCxE3hc8TfTpk+NfIVQR3NmdaZRjegZkz04D8TjRTSMt u16msydpPdzD02A/cVsQ8C3HNXsaoYdu6nARw4y58UxHMBIfdibSI+Wql7xV/rq7B0XG9h+F480 1lr0as8AITNH7Bc+13w== X-Google-Smtp-Source: AGHT+IH3LEFp5SZfJTn9mBfnEMdw55TG3aOnTZaiquCIur+BQEvlh3TkT50lZo8liyX9R/vIcNMUdg== X-Received: by 2002:a05:6512:4010:b0:549:4ab7:7221 with SMTP id 2adb3069b0e04-54cb688ae13mr591027e87.50.1744275564501; Thu, 10 Apr 2025 01:59:24 -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-54d3d50285csm80875e87.110.2025.04.10.01.59.23 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 10 Apr 2025 01:59:24 -0700 (PDT) From: Abdiel Janulgue To: a.hindborg@kernel.org, benno.lossin@proton.me, rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Alice Ryhl , Trevor Gross , Danilo Krummrich , Valentin Obst , linux-kernel@vger.kernel.org (open list), Christoph Hellwig , Marek Szyprowski , Robin Murphy , airlied@redhat.com, iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), Abdiel Janulgue Subject: [PATCH v2 2/3] rust: dma: convert the read/write macros to return Result Date: Thu, 10 Apr 2025 11:58:17 +0300 Message-ID: <20250410085916.546511-3-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250410085916.546511-1-abdiel.janulgue@gmail.com> References: <20250410085916.546511-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 Suggested-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 | 25 ++++++++----------- 2 files changed, 42 insertions(+), 37 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..1e610545e100 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,14 @@ 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() { + 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()); + assert_eq!(val0.unwrap(), value.0); + assert_eq!(val1.unwrap(), value.1); + } } } =20 --=20 2.43.0 From nobody Fri Dec 19 00:36:18 2025 Received: from mail-lf1-f51.google.com (mail-lf1-f51.google.com [209.85.167.51]) (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 DB1E820C03E; Thu, 10 Apr 2025 08:59:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.51 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744275570; cv=none; b=j7KkEZziaoZ0Sst9DWHWyjlRQ8Y2bxs9guzPMnAP/kQ6qedQuquFO9FpAyqir1EwBs7HbA67qxSJPUlYQj3h9Bti5HrJ0dKF9vIoB2vJz21T/dQcHbgHf0YSZrUXh7bdnXO9dV7g0voDX7LLGd6FXW9daNYa2V5U+sbsb75Wi4I= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1744275570; c=relaxed/simple; bh=Dm0EuL/Hf72yUy+knejcLhK3TuBfjuxm/0quqsCP/xg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Ji8a9pBJavL29AudtlFG3gEAX8HdXu/jsqzNbT8b6xol6t+MA0OPHuJEFfpwVht+mBlhAADRHG4t3UWORuQFb55zMw4NebzofUM2QMiFUdqy26mXacpjhxPCTyQBpOT0mSpxPvhp9b7G8olgXtoaYU6wDiy3YhjucOYqo33xaEY= 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=VdKNBZ1F; arc=none smtp.client-ip=209.85.167.51 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="VdKNBZ1F" Received: by mail-lf1-f51.google.com with SMTP id 2adb3069b0e04-54b10956398so708603e87.0; Thu, 10 Apr 2025 01:59:27 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1744275566; x=1744880366; 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=AY+y/t6CAx0RYTvL64DfJN6U/KJsLf4NXsmWUCaqj0c=; b=VdKNBZ1Fq6BQHSiIjBdWidvIVVEzDiXOh2gaCoHqLdYuwpszclbSZfRxA4CfzMmV2Q 5S0A2/qL62g3m/LqvDyZ09ltPNwfGpFN734Rbcvm9G2tzyOuOMiXjHTZtOXRULR3BCmU /gQpHLHaNXlLfsJAPSRcxj2sbW1MkcUMPsHa84zH3pWdFU3QA5XaCcWQTHn7rfXDXs4B ibascD/Iqtv+nLU2hkcJHr5VYIvBbGPRWI7qO3Gy+N7NQyGeEwQ/HCtQMeraqvSodQDJ i8MgIN/Nh99A7FBQyW+mv+EBNIhs9eyH+VnC27+vGyJYdz7/ooQYJDGQDQsL7CN/n8ZI sIhA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1744275566; x=1744880366; 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=AY+y/t6CAx0RYTvL64DfJN6U/KJsLf4NXsmWUCaqj0c=; b=FHgODhT/9FZSzXhdeAkAGZ3UdYQLwatrUEt4kFkTMWyp5u5wfdKADZ4nujEGh47Qf7 I2jBn3qSBXhgEi5nCW/cXOJarPA4hjiI/wXABodFLOTnRKXfRuT7nJ3xdouUSqaQEekd t6dFjjX0eNQl9DEmi3Q+z2CL9+nF6v70syhEtj8fK57r8eRqodTDFxef5nbxBpEuR8l2 +xjnIM3LqJrn7IhY6OAcYdZNQwJWqGCdSPvVn5bxA7L2xM6Bv6mbwpiZE41AyTVTGbNt OW7qL+oToYcfl1Zb8YKN6kcsJOtdq5Js1CpJQu+0fOQ9T1f0RCFk+naYrwsPWv/2K5pw xpxw== X-Forwarded-Encrypted: i=1; AJvYcCVeJQ1e81iTm1WkdyABlDhGRviUCjL7PPt7LUSK5AFuA3GvvnGqyP7qrpQ/xLqMVfvyT7dzn7RuqVKTxOAsbOk=@vger.kernel.org, AJvYcCXZiC49JzpOx1qQZT+4pVWiIVcIVopQcvd75MnvNmCCMFEa88WGyoKdspsMDA9q+JEkGLUb4zdbZVESWHc=@vger.kernel.org X-Gm-Message-State: AOJu0YwdZ+W9i9qu89ROB16ZHsJiN+eP4I5gO5MBOBlj4XH01Lgw8w9P SiswAVTk+EybV+c6OdZCJEVstpOGqdfe0vfR3aamCPoac+7cbCXI X-Gm-Gg: ASbGncsna/jsbJqnKNS9CFH+3HXWtrtwP9hjB8T/7YIADhpyzlQ1TdDp+Yu4Ts8UJWj DvfnU5JTQGg9ppZ/+bIgB6jwwD44KQ9gNhtXONI4E18fAG9MroyoR+LBU3+Qdf3awvm1CzlEiSJ XEbTbH97dx/GtAtwHRbRVcgUkJLRupG+Yexti03mEtvizcavnCJzVvLLPAH1EV6bo0fZZzCAMao J4DQaD6hgkYzZrXz8jQj0cjqx1/Iwv2f0kIYht3QrKQsMg24BoiZeA6FdR9E5vCPQqS+ZldHRPR ahPazm3HDUK43Eh3GTTTrHTZfU2yEJnr+8f1NTtFWekS7fjiBd7AtAzMODj+gZ6f+I4U1BY33+b iyiJO/s2udEydVmmPTA== X-Google-Smtp-Source: AGHT+IGz1LYsDiprrFBJZFFqhs+1F1wEyvjL2TCIsFB9waYQMtth+506AVNqZHbMN3ejNCWqSKWKSA== X-Received: by 2002:a05:6512:15a0:b0:549:7145:5d2d with SMTP id 2adb3069b0e04-54ce8a48130mr530657e87.16.1744275565490; Thu, 10 Apr 2025 01:59:25 -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-54d3d50285csm80875e87.110.2025.04.10.01.59.24 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 10 Apr 2025 01:59:25 -0700 (PDT) From: Abdiel Janulgue To: a.hindborg@kernel.org, benno.lossin@proton.me, rust-for-linux@vger.kernel.org Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Alice Ryhl , Trevor Gross , Danilo Krummrich , Valentin Obst , linux-kernel@vger.kernel.org (open list), Christoph Hellwig , Marek Szyprowski , Robin Murphy , airlied@redhat.com, iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), Abdiel Janulgue Subject: [PATCH v2 3/3] rust: dma: add as_slice/write functions for CoherentAllocation Date: Thu, 10 Apr 2025 11:58:18 +0300 Message-ID: <20250410085916.546511-4-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250410085916.546511-1-abdiel.janulgue@gmail.com> References: <20250410085916.546511-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..880f6f04ba86 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 >=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.= 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 >=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.= 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 >=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 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