From nobody Mon Oct 6 21:04:27 2025 Received: from mail-lf1-f52.google.com (mail-lf1-f52.google.com [209.85.167.52]) (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 23E7620E00C; Thu, 23 Jan 2025 10:43:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.52 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737629034; cv=none; b=oT4Xgp81oZ4yeUtGld9S/irlpIMa9bPU6SWJ/DL5HITi0aMHu9HZbHvKYizYwPb1Skmc3g7kslBNJNHMjhhb4QLs3M7i+R9RYa+X2WvHBsnQez/EIbryJ35Gu2nNSf+9lZZt65vPFpfRyBfmtlSw95QYmCqXXAAx2fDjhCaprow= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737629034; c=relaxed/simple; bh=7y/5voRRl3iVEWd8dd9FMx/aIm3fFsPYaagWFci7DeI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=cqbFWkSNnyPKLWAV7e3h68SmDnQngWrVU2w8S2n6FKBeao36M0H7SJRgLXmhOW8ft86ySfVJZ8diNPXS8djptvP1nEZfyiV4av+T9fTpoiUJushMf76lTZ7QbjHtEtPs5oA1STD7mkOVNYkuE4p2NhGFS/0Jsk1w7u95H9KK7w4= 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=hkMT+K4x; arc=none smtp.client-ip=209.85.167.52 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="hkMT+K4x" Received: by mail-lf1-f52.google.com with SMTP id 2adb3069b0e04-5439e331cceso945337e87.1; Thu, 23 Jan 2025 02:43:52 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1737629031; x=1738233831; 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=MsTWX9yoQTMgLsmI/WJU+pLJbUvjBW8MdXlesjuHNQQ=; b=hkMT+K4xrHN9SwK93u1jmyBAs3XKs/ic6oXSSLwj1biyMxpLLTXsSYd6eFQ+u+/ZhV AhQXpPZgaDU62GqiJ1RSPi7435vb4GR/FvEIBbSkCZaewoflg2khIrqftUGx7xkYu8bB k4cfjhLIYIjuQiaTKTZyYLy9kbAroT18utyQ9NcjpFEiTkIp5r6NMB+9Hu8HLHzBsJXg LWOPvSMNOYaHIZswjVVDnRZgWOYMxbPjQR8AEhxJWHFq0hi2Zt3Tkrpfx9c0IdNAVnA4 A1C7Rq6WubgGiT1EHfOPh3Ul1qybncrc95sMEBy3jgI/LWB/pXYCT1pWIDTATOMyKDeM V9MQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1737629031; x=1738233831; 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=MsTWX9yoQTMgLsmI/WJU+pLJbUvjBW8MdXlesjuHNQQ=; b=RcnmqY6Tj+bLYcE5JkeyTA2/MGGERnCyDdYjGIl3NNU0PwWEGAAPbV8RB8kzwFL8QF ItKfFwy8xXsowisrPE2xKje5qv/up8b76uW+EZ8k+vnbM2e0FOfvWFPd8xQQb+Y5mIom eTVCc+OhjCbUVABDJkywoBQi9oCegcoyDQispxso6/TP5JXiDbruwhcax07IFB9v804z kvEDUgiEPiHULmLuSLCg+loqsRBwTIjQZSYHONdmHuW4mUaSWwjQuT72K4PI70NQ4cWi U212MUAg0LZYIgXY5ZFD4ZGuU0g87ZANNJe3M42VTfgMgV5xDkeMUCpAEUDP6DvBqv0I 6+Pw== X-Forwarded-Encrypted: i=1; AJvYcCX4E6J+H5Jk0Ap30wugdCdI8Qp9r6luxRVx5412QBoHSCnMCY1RYzCNjSqAGmVKHDOuPjo9Gc+7VSmbfFw=@vger.kernel.org X-Gm-Message-State: AOJu0YxvkEJX7rdW0XecHnqSEpQA3kZZTFSdV+3iCt+1dDSCufHYlPHQ DyusmJ7CYvnUm4v3p2yNq9BIwgEwHKlBBQow7r6is2trlriRtjgTzYyOxQ== X-Gm-Gg: ASbGncuIKkKO5aWS1Slu0x04x2kLnRaoejyEezDOIEZomAzTHFugujJcECD/svwTtH8 zU11PkMJJg9qll5xo37XfGOs8rkqQrNBHODjasnaBNjDZL4JIii2pDnLfKq+D5Eizr0G8iLT21a jeShazuRBV1nw7TC0GlDQ+MchfGblRoPzbqXkICE2HjBaWIG3cxrNrWy9k/HN8TheIjhR9O+RF3 qUqPhciCddr282I5oXYgDX1pXmAkwNqZtJyR1LvYWknxdUBnvGb2qLHls1frn6slPvZafWLr5ZZ GR8aFZiNiJO9UEmGkR06a934xnxbnK5PpVN8ejp/DNr4wENOZ9I= X-Google-Smtp-Source: AGHT+IHnDXq/rQt9rvIEwMH/Qu1x3vMN4D/Sfbrtt3HCkRjO/okvdPh6Tg6yj0BiKhp7C2EH/cOaNw== X-Received: by 2002:a05:6512:3d2:b0:542:1b63:2e78 with SMTP id 2adb3069b0e04-5439c216b34mr5857889e87.2.1737629031044; Thu, 23 Jan 2025 02:43:51 -0800 (PST) Received: from abj-NUC9VXQNX.. (87-94-132-183.rev.dnainternet.fi. [87.94.132.183]) by smtp.gmail.com with ESMTPSA id 2adb3069b0e04-5439af0ea8esm2579873e87.80.2025.01.23.02.43.49 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 23 Jan 2025 02:43:49 -0800 (PST) From: Abdiel Janulgue To: rust-for-linux@vger.kernel.org, daniel.almeida@collabora.com, dakr@kernel.org, robin.murphy@arm.com, aliceryhl@google.com Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Valentin Obst , linux-kernel@vger.kernel.org (open list), Christoph Hellwig , Marek Szyprowski , airlied@redhat.com, iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), Abdiel Janulgue Subject: [PATCH v11 1/3] rust: error: Add EOVERFLOW Date: Thu, 23 Jan 2025 12:42:57 +0200 Message-ID: <20250123104333.1340512-2-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250123104333.1340512-1-abdiel.janulgue@gmail.com> References: <20250123104333.1340512-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" Trivial addition for missing EOVERFLOW error. This is used by a subsequent patch that might require returning EOVERFLOW as a result of `checked_mul`. Signed-off-by: Abdiel Janulgue Reviewed-by: Alice Ryhl --- rust/kernel/error.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index f6ecf09cb65f..1e510181432c 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -64,6 +64,7 @@ macro_rules! declare_err { declare_err!(EPIPE, "Broken pipe."); declare_err!(EDOM, "Math argument out of domain of func."); declare_err!(ERANGE, "Math result not representable."); + declare_err!(EOVERFLOW, "Value too large for defined data type."); declare_err!(ERESTARTSYS, "Restart the system call."); declare_err!(ERESTARTNOINTR, "System call was interrupted by a signal = and will be restarted."); declare_err!(ERESTARTNOHAND, "Restart if no handler."); --=20 2.43.0 From nobody Mon Oct 6 21:04:27 2025 Received: from mail-lf1-f48.google.com (mail-lf1-f48.google.com [209.85.167.48]) (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 5C96620E6E7; Thu, 23 Jan 2025 10:43:56 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.167.48 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737629038; cv=none; b=QqHuzFn8hMqjmY9Y7iVFVw8I42lgdphm1tdTwx3zNH5qVJneMBHH0x31nhk4DeYfx68qjs2DdokZqd54xptgghlIM8pvzJM76ca+7DVCtc55ZEyVO6Hz7akERW0IaMgk/PzwH8JeGO/8fwJB+BM46N79h3Bz+OZyuBbAwDrEN9M= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737629038; c=relaxed/simple; bh=A81Dn1Fs+f579XHqKrFftv0/wbKO0KgyoGrMVeZ9Qrg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=X50Vwc8U3ZziHL/EOj4nrsae0fVIrUKMOTU9qiVJnp+TtRcIFWcKdFsp2G9rFz8oK/q41POd8tA/dWz+k+YnSeyuq1JaQeg0L0OZYMnR1EnKA2IrKaffu31fCMEWKu6TzK+4uNTe2GKf9CVZhZsGkj9/CUHkHG11dIi19PLI5qg= 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=F+S3rf4h; arc=none smtp.client-ip=209.85.167.48 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="F+S3rf4h" Received: by mail-lf1-f48.google.com with SMTP id 2adb3069b0e04-53f757134cdso852897e87.2; Thu, 23 Jan 2025 02:43:56 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1737629034; x=1738233834; 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=kSY83d3vWtDpbwnz/2tvzzgog+EHfgVcX3FixpXY9WY=; b=F+S3rf4h8dJKCOVm3NHIADGd/dInLE7nureUHr6RyWjpPN3SXRBYvMEoElPycqCgRF XZqFTY6MVj6ibWYUlS269VI9PJ05u8JBLolzAIbwPWR/WCk4UDZ1tUqzEwT6eEWBdV+1 vqm/poRJmNf4LC+ZrjGXD053uJJVK33/ZY998DK9mk4GiXfSryoLX0b/ZRVIu0nC1v/t KYpElda4BP8km/gdW7Zn0ZkY+foicGXFG193JeFMgfppuoQwnGHmRWzoo1T/Jjf1jRhW SGzptJDVB3rcjkET4YBiMimzjM9hgikhbRMlquX4Ez1zlfy8SxDyb7y+mxMEQGS7y9bD PSDw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1737629034; x=1738233834; 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=kSY83d3vWtDpbwnz/2tvzzgog+EHfgVcX3FixpXY9WY=; b=GiwLNgOIEU9zgwbvKlqKH5NTRvfBPBc5FcMPdat4hom2AbBXO+j/J3JlHQTV/YCnyc JmcvYDgDq1yWOMbk5uzT2P9n+CPkuOvnduMwJ9Mrk4+UPe+3vC0FXMf96AaXayyLDvi4 ub1mMqiH5dFIR0Bti6Mhhj1lm/8SpNf20wxOMwaCIueJ+5S8ynXXLKL0bHNVkAN2n95C XsCDi+YwOO3GrrlM6g8AHnIlTeDhxaroR2xp0yivA104SmY9c6o737Sb80rgJjQbqSUb OqBphwsxrdNYIYJkY6Mu8ggCqFpz+F5JZhQXLUlM7wpnr4QWR76h6hPajmjGuu7OnRi0 8RhQ== X-Forwarded-Encrypted: i=1; AJvYcCWRyw725XUhs9Bji6/p8L15H5G9tGE08Zr49/e732urErOgddSzlHmARZlLuR8eaB8lmApjK0DOe/OYRpg=@vger.kernel.org X-Gm-Message-State: AOJu0YxXVi6YOSHCvk+5kIt+NDJgkelm5d+S1gAWcUnGtDbCFmQbbtfa MM+Z0y8NX5mmK+Jcikk7yl35In6En1ZygLqpjPr7C90gDYqBM9BWQEhtAw== X-Gm-Gg: ASbGnct2QY/4FcuyISBxVYQjtv6gy/L4mlp07Qgwq5GIQEFtulGNhLUUto9dTkxuOTk ADaKLlYzDhpyIyHut1Am6ZJNQ+WDztdqAecl5PsnV93Q9jO3aHcxcyupItH+iMDzu3hKYJ9nSuX Qrz/ufapjVtxruni1ogZllUXxlrUrCEiPYY3VBNoaZtcaumqG6901fKm7qBWB3l1ic5v/L1zYme yAnJSCxnEMPUsPgsoEeMO59VlDLhLGvUtr7AUKtTwUo4jEMENB79jz2Zulilunt/HblRfKkcvzx ePOTjxR0tJCUwbvCYg5Dep/Sna0d9COUr0FEFRyV0gN5duRNB7s= X-Google-Smtp-Source: AGHT+IFTE145iWigVz7U1b1eLG+HVja8LX4jND2xki1OlFkXgaokSRg/0Pt4/T8Us3RAVW+GocTx/A== X-Received: by 2002:ac2:4155:0:b0:53e:395c:688e with SMTP id 2adb3069b0e04-5439c216b55mr6587969e87.10.1737629034066; Thu, 23 Jan 2025 02:43:54 -0800 (PST) Received: from abj-NUC9VXQNX.. (87-94-132-183.rev.dnainternet.fi. [87.94.132.183]) by smtp.gmail.com with ESMTPSA id 2adb3069b0e04-5439af0ea8esm2579873e87.80.2025.01.23.02.43.51 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 23 Jan 2025 02:43:52 -0800 (PST) From: Abdiel Janulgue To: rust-for-linux@vger.kernel.org, daniel.almeida@collabora.com, dakr@kernel.org, robin.murphy@arm.com, aliceryhl@google.com Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Valentin Obst , linux-kernel@vger.kernel.org (open list), Christoph Hellwig , Marek Szyprowski , airlied@redhat.com, iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), Abdiel Janulgue Subject: [PATCH v11 2/3] rust: add dma coherent allocator abstraction. Date: Thu, 23 Jan 2025 12:42:58 +0200 Message-ID: <20250123104333.1340512-3-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250123104333.1340512-1-abdiel.janulgue@gmail.com> References: <20250123104333.1340512-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 a simple dma coherent allocator rust abstraction. Based on Andreas Hindborg's dma abstractions from the rnvme driver, which was also based on earlier work by Wedson Almeida Filho. Signed-off-by: Abdiel Janulgue --- rust/bindings/bindings_helper.h | 1 + rust/kernel/dma.rs | 282 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 284 insertions(+) create mode 100644 rust/kernel/dma.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 5c4dfe22f41a..49bf713b9bb6 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs new file mode 100644 index 000000000000..83afc606d67a --- /dev/null +++ b/rust/kernel/dma.rs @@ -0,0 +1,282 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Direct memory access (DMA). +//! +//! C header: [`include/linux/dma-mapping.h`](srctree/include/linux/dma-ma= pping.h) + +use crate::{ + bindings, build_assert, + device::Device, + error::code::*, + error::Result, + transmute::{AsBytes, FromBytes}, + types::ARef, +}; + +/// Possible attributes associated with a DMA mapping. +/// +/// They can be combined with the operators `|`, `&`, and `!`. +/// +/// Values can be used from the [`attrs`] module. +#[derive(Clone, Copy, PartialEq)] +#[repr(transparent)] +pub struct Attrs(u32); + +impl Attrs { + /// Get the raw representation of this attribute. + pub(crate) fn as_raw(self) -> crate::ffi::c_ulong { + self.0 as _ + } + + /// Check whether `flags` is contained in `self`. + pub fn contains(self, flags: Attrs) -> bool { + (self & flags) =3D=3D flags + } +} + +impl core::ops::BitOr for Attrs { + type Output =3D Self; + fn bitor(self, rhs: Self) -> Self::Output { + Self(self.0 | rhs.0) + } +} + +impl core::ops::BitAnd for Attrs { + type Output =3D Self; + fn bitand(self, rhs: Self) -> Self::Output { + Self(self.0 & rhs.0) + } +} + +impl core::ops::Not for Attrs { + type Output =3D Self; + fn not(self) -> Self::Output { + Self(!self.0) + } +} + +/// DMA mapping attrributes. +pub mod attrs { + use super::Attrs; + + /// Specifies that reads and writes to the mapping may be weakly order= ed, that is that reads + /// and writes may pass each other. + pub const DMA_ATTR_WEAK_ORDERING: Attrs =3D Attrs(bindings::DMA_ATTR_W= EAK_ORDERING); + + /// Specifies that writes to the mapping may be buffered to improve pe= rformance. + pub const DMA_ATTR_WRITE_COMBINE: Attrs =3D Attrs(bindings::DMA_ATTR_W= RITE_COMBINE); + + /// Lets the platform to avoid creating a kernel virtual mapping for t= he allocated buffer. + pub const DMA_ATTR_NO_KERNEL_MAPPING: Attrs =3D Attrs(bindings::DMA_AT= TR_NO_KERNEL_MAPPING); + + /// Allows platform code to skip synchronization of the CPU cache for = the given buffer assuming + /// that it has been already transferred to 'device' domain. + pub const DMA_ATTR_SKIP_CPU_SYNC: Attrs =3D Attrs(bindings::DMA_ATTR_S= KIP_CPU_SYNC); + + /// Forces contiguous allocation of the buffer in physical memory. + pub const DMA_ATTR_FORCE_CONTIGUOUS: Attrs =3D Attrs(bindings::DMA_ATT= R_FORCE_CONTIGUOUS); + + /// This is a hint to the 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); + + /// This tells the DMA-mapping subsystem to suppress allocation failur= e reports (similarly to + /// __GFP_NOWARN). + pub const DMA_ATTR_NO_WARN: Attrs =3D Attrs(bindings::DMA_ATTR_NO_WARN= ); + + /// Used to indicate that the buffer is fully accessible at an elevate= d privilege 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); +} + +/// 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. +/// +/// 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 +/// as the DMA address base of the region. The region is released once [`C= oherentAllocation`] +/// is dropped. +/// +/// # Invariants +/// +/// For the lifetime of an instance of [`CoherentAllocation`], the cpu add= ress is a valid pointer +/// to an allocated region of consistent memory and we hold a reference to= the device. +pub struct CoherentAllocation { + dev: ARef, + dma_handle: bindings::dma_addr_t, + count: usize, + cpu_addr: *mut T, + dma_attrs: Attrs, +} + +impl CoherentAllocation { + /// Allocates a region of `size_of:: * count` of consistent memory. + /// + /// # Examples + /// + /// ``` + /// use kernel::device::Device; + /// use kernel::dma::{attrs::*, CoherentAllocation}; + /// + /// # fn test(dev: &Device) -> Result { + /// let c: CoherentAllocation =3D CoherentAllocation::alloc_attrs= (dev.into(), 4, GFP_KERNEL, + /// D= MA_ATTR_NO_WARN)?; + /// # Ok::<(), Error>(()) } + /// ``` + pub fn alloc_attrs( + dev: ARef, + count: usize, + gfp_flags: kernel::alloc::Flags, + dma_attrs: Attrs, + ) -> Result> { + build_assert!( + core::mem::size_of::() > 0, + "It doesn't make sense for the allocated type to be a ZST" + ); + + let size =3D count + .checked_mul(core::mem::size_of::()) + .ok_or(EOVERFLOW)?; + let mut dma_handle =3D 0; + // SAFETY: device pointer is guaranteed as valid by invariant on `= Device`. + // We ensure that we catch the failure on this function and throw = an ENOMEM + let ret =3D unsafe { + bindings::dma_alloc_attrs( + dev.as_raw(), + size, + &mut dma_handle, + gfp_flags.as_raw(), + dma_attrs.as_raw(), + ) + }; + if ret.is_null() { + return Err(ENOMEM); + } + // INVARIANT: We just successfully allocated a coherent region whi= ch is accessible for + // `count` elements, hence the cpu address is valid. We also hold = a refcounted reference + // to the device. + Ok(Self { + dev, + dma_handle, + count, + cpu_addr: ret as *mut T, + dma_attrs, + }) + } + + /// Performs the same functionality as `alloc_attrs`, except the `dma_= attrs` is 0 by default. + pub fn alloc_coherent( + dev: ARef, + count: usize, + gfp_flags: kernel::alloc::Flags, + ) -> Result> { + CoherentAllocation::alloc_attrs(dev, count, gfp_flags, Attrs(0)) + } + + /// Returns the device, base address, dma handle, attributes and the s= ize of the + /// allocated region. + /// + /// The caller takes ownership of the returned resources, i.e., will h= ave the responsibility + /// in calling `bindings::dma_free_attrs`. The allocated region is val= id as long as + /// the returned device exists. + pub fn into_parts( + self, + ) -> ( + ARef, + *mut T, + bindings::dma_addr_t, + crate::ffi::c_ulong, + usize, + ) { + let size =3D self.count * core::mem::size_of::(); + let ret =3D ( + // SAFETY: `&self.dev` is valid for reads. + unsafe { core::ptr::read(&self.dev) }, + self.cpu_addr, + self.dma_handle, + self.dma_attrs.as_raw(), + size, + ); + core::mem::forget(self); + ret + } + + /// Returns the base address to the allocated region in the CPU's virt= ual address space. + pub fn start_ptr(&self) -> *const T { + self.cpu_addr + } + + /// Returns the base address to the allocated region in the CPU's virt= ual address space as + /// a mutable pointer. + pub fn start_ptr_mut(&mut self) -> *mut T { + self.cpu_addr + } + + /// Returns a DMA handle which may given to the device as the DMA addr= ess base of + /// the region. + pub fn dma_handle(&self) -> bindings::dma_addr_t { + self.dma_handle + } + + /// Reads 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 data returned should = be regarded by the + /// caller as a snapshot of the region when this function is called, a= s 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 `st= art_ptr_mut()` + /// could be used instead. + /// + /// # Safety + /// + /// Callers must ensure that no hardware operations that involve the b= uffer are currently + /// taking place while the returned slice is live. + pub unsafe fn as_slice(&self, offset: usize, count: usize) -> Result<&= [T]> { + if offset + count >=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) }) + } + + /// Writes data to the region starting from `offset`. `offset` is in u= nits of `T`, not the + /// number of bytes. + pub fn write(&self, src: &[T], offset: usize) -> Result { + if offset + src.len() >=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(()) + } +} + +impl Drop for CoherentAllocation { + fn drop(&mut self) { + let size =3D self.count * core::mem::size_of::(); + // SAFETY: the device, cpu address, and the dma handle is valid du= e to the + // type invariants on `CoherentAllocation`. + unsafe { + bindings::dma_free_attrs( + self.dev.as_raw(), + size, + self.cpu_addr as _, + self.dma_handle, + self.dma_attrs.as_raw(), + ) + } + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 545d1170ee63..36ac88fd91e7 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -37,6 +37,7 @@ pub mod build_assert; pub mod cred; pub mod device; +pub mod dma; pub mod error; #[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)] pub mod firmware; --=20 2.43.0 From nobody Mon Oct 6 21:04:27 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 2A18520E007; Thu, 23 Jan 2025 10:43:57 +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=1737629039; cv=none; b=vE/g5xAjR/88nETWbC6G0lEEFH0xzZrKeYb2XxUug1A/vELtGkNCRkspWrf7ML41DZSZFvg6HS+Pxnrpf9NJSKobkAtGTl2vcVLkqYjmPXINpJUzMcxKMgYeu6Hws+sjrSsIv4Ak1/Q1XARXl4C4nQhuXh6w2F7jCYMCQGbpVCs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1737629039; c=relaxed/simple; bh=FNwkKYtNgY128tT+Ow8mqes42EjX7w9jGfWwlvxYpFc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=DWpDFw4j3Ad02D1LhKrQnYd9NtqYKPTv6VIG2VXyqCx9ejMva2l3nSZ04TJTsEDpy5OEgPgoV/qzILWSGRw2QMeVAG2FAhnXPcI75uhn0/S/+mbOMLzHbfQTR1QzPiwTU2/qbutEQYQw+86tClKjqFHHiH3meN2414ia7rZluM8= 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=GNpHfz1O; 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="GNpHfz1O" Received: by mail-lf1-f49.google.com with SMTP id 2adb3069b0e04-5439a6179a7so837428e87.1; Thu, 23 Jan 2025 02:43:57 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1737629036; x=1738233836; 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=F4s3hoprJz1ioDJMXWp67H1qXVNKWcKbvshZNe+AKy0=; b=GNpHfz1OIA0yduVUxn41ONMoYhaX6JGKfX5AbfZWm0d75P+O3bKK8l7+JaHt3bS6CB Jrns0+paHLk+zEqnvkqAtY7EzW4LNMdtoOwd+DJvwW3+h1cS6U6j7FA0bFblh1HoY+Ne eLbEOI4kHmr5MoOOcHDKEFGKdZg3Xs3VcRRfeZbvUEbHkSmM5Kv6l1PdRe7dQsfkJJEx 5TKZ25lJixqmeh6rrLd6YcApYsBu3EgK2JcNoFFsfgL8uTgQHcMB1Gwq/zycqSSIeUuA kRKsA+Y5AW7/gse5AumCVqvgaWbNopdj2+zcz96m129nl1RXILcg8uMnSltN+oLbiZpF Emug== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1737629036; x=1738233836; 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=F4s3hoprJz1ioDJMXWp67H1qXVNKWcKbvshZNe+AKy0=; b=UiT9dYlKEybatn2u04BA/HyfloRKnF1o20uypYVzhkrjx1yxfUl30D36BuWBBv4pif /dXbDxN2Jvxp5M3gG1fSJjgpNhqG7tG8IvPzWdHeYGzrTOuaQ5eRHMA+N8WSJSm+AGjb 9KBRj/4Ff2hUlCxwngoGs4fKasBqTF5/5NOA5wMDonbJxkSzS6QcW7n2UzXc8eLDu80T +zNTlbTubMLXunr+4IX5z4R+YCD3hl8oZ9DszhFkPNMoHOhQQlqFKduhWd7CAlGMDtdG BZelMc8I4S9qbmQ37ynG5m06YokSmBZqYQ45yFkBkA8lw3uUyYWdH/3RmF4TW/nwC/RH whZA== X-Forwarded-Encrypted: i=1; AJvYcCVfPi40qeCGFZllQz3vAGrPUlAc9/eSteXrTR/gg52RJOkUfqGJXV700bAneBi+4s6mwdzQiQ2XZ8jWGoU=@vger.kernel.org X-Gm-Message-State: AOJu0YwAaSCwVn41AO4CWuDJIZLmlFmpI66ndT6568Nj89tKOfojhKFK Kmqz/u5wmzgRejfo6Rt6wvGQICyczKhwzp0fet07Mt8dKIF0y0YVrsjLmQ== X-Gm-Gg: ASbGncvrgQuD+o5WvPfeoN5MMQarad7zWIBLB2N+e5GCb16pWtG+gVRp+itbGtoyF1o 7quITkIo/T1LQo6q6l5iSlKqcymudqqH2awH0WpFN65jLdPqrh2tam4QwWLmPfMlrS1T/OJqSPP G9SFZYOeo6fZ8ScztIKZQhkGPPLWn3MbwlaSRY22cQ3H9rcz9yJd2Tjo4DdYH8pYXG1JFT+bXey SeXbSwPAHGQGr4fYiZ9nloQ1a00HJ8Qpdc1OEN98ZVrzwfL9vh15Hje1wgMV3jASSVt3PtIm5lF 47ZrZzxMn6ckUL74Dw4IQjNFwOX01h4e+VpHomxA7wpruh0TMaM= X-Google-Smtp-Source: AGHT+IHcT7/RQNeQOAcU8PvDPDdbWBolwS3y95KvFPLTulFvDVapY73EUjtaarvuodv6G+7bXgxMBw== X-Received: by 2002:a05:6512:1044:b0:53f:67be:507 with SMTP id 2adb3069b0e04-543c2278880mr846834e87.16.1737629035933; Thu, 23 Jan 2025 02:43:55 -0800 (PST) Received: from abj-NUC9VXQNX.. (87-94-132-183.rev.dnainternet.fi. [87.94.132.183]) by smtp.gmail.com with ESMTPSA id 2adb3069b0e04-5439af0ea8esm2579873e87.80.2025.01.23.02.43.54 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 23 Jan 2025 02:43:54 -0800 (PST) From: Abdiel Janulgue To: rust-for-linux@vger.kernel.org, daniel.almeida@collabora.com, dakr@kernel.org, robin.murphy@arm.com, aliceryhl@google.com Cc: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Trevor Gross , Valentin Obst , linux-kernel@vger.kernel.org (open list), Christoph Hellwig , Marek Szyprowski , airlied@redhat.com, iommu@lists.linux.dev (open list:DMA MAPPING HELPERS), Abdiel Janulgue Subject: [PATCH v11 3/3] MAINTAINERS: add entry for Rust dma mapping helpers device driver API Date: Thu, 23 Jan 2025 12:42:59 +0200 Message-ID: <20250123104333.1340512-4-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250123104333.1340512-1-abdiel.janulgue@gmail.com> References: <20250123104333.1340512-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 an entry for the Rust dma mapping helpers abstractions. Signed-off-by: Abdiel Janulgue --- MAINTAINERS | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index baf0eeb9a355..4808c9880b3e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -6822,6 +6822,16 @@ F: include/linux/dma-mapping.h F: include/linux/swiotlb.h F: kernel/dma/ =20 +DMA MAPPING HELPERS DEVICE DRIVER API [RUST] +M: Abdiel Janulgue +M: Danilo Krummrich +R: Daniel Almeida +L: rust-for-linux@vger.kernel.org +S: Supported +W: https://rust-for-linux.com +T: git https://github.com/Rust-for-Linux/linux.git rust-next +F: rust/kernel/dma.rs + DMA-BUF HEAPS FRAMEWORK M: Sumit Semwal R: Benjamin Gaignard --=20 2.43.0