From nobody Fri Dec 19 04:52:56 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 1B4D11F9F69; Tue, 3 Dec 2024 17:08:58 +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=1733245740; cv=none; b=Ia1zv4AOJVNxq9/yZfjYZ2REO2X0+PFc+ECcnr5eo+I7ts/pzUw51g1+2Q1lkrquu6pIxKVUFmKBZ744xB7dDyLPcuqvt3XRfZyN5TcQs/RIyBvdRY8vyz0mkzmdijLyf2b0doFHKVvuC/P9Bzo+6VjvPBtz7AJwd+HH4TJ4szY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1733245740; c=relaxed/simple; bh=7TF0D7iSdGT2magME+zHIHzqeRneKEyOSjHsh3ydk2A=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=KwHetaNe0MO7xoRdJF27m8BO6deLPTX654OOW3EVHkwVv11KeNQ60vN6ETAVkP0D5NeCIytxiPy+NElLalnDSZ2uKO6Ps9B+0kYYYXQU+evpFkn+28dmEtmJm33vcYYITOhEuGQRBxTCxMkfmNPmYXc7zJA4VegbUU80S9A0TH4= 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=RxhbtP6K; 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="RxhbtP6K" Received: by mail-lf1-f51.google.com with SMTP id 2adb3069b0e04-53de852a287so6494488e87.2; Tue, 03 Dec 2024 09:08:58 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1733245737; x=1733850537; 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=rtMK3W1LybcvR677zqhzHXJkDBdRMP3ngjp2gwl/Zfc=; b=RxhbtP6KrFZWgTYgMBaVkwhAy+MTZHxi9LGTOQBBnvSbMqxB/4gnfZxLzKhEB9C/vC N9mjElXgYeS31BCrdCEMYt8GmPE3BfzRiGdZLRmv4AojRUoaBSVa0t6dLJU8ASJ07KLi kpIZe2agLX1EhnhfSDQGBD6Fiamv+cPLrYpb67KCIDqCJ7pifm67SyyP7FvRWLPnmV03 Xv5v9F0y0OlbyUIxQ54ElpQhoc+3OQvpdRoYE8rT44IZCeFVYvrqUc/qgP99ocAsr66o u34drrojVgZ420RJCn78Y9NbqzP85UILZLJutrCZei59fJZgFBuPNHwUAGax6yATPt+X kjxQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1733245737; x=1733850537; 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=rtMK3W1LybcvR677zqhzHXJkDBdRMP3ngjp2gwl/Zfc=; b=tfj4sH8ibo7nN0K+peilEefBRVqH1xmOBtdjPvrLlaSo4I8npudT9psBZJOTZzRMOT gYhs/LNMmCS/kUHmodDDmhDsh9JPhW3kOS+8nol8HuJmaWcoKL/wQwgfJC0421syCo9F kgs4ZvYxExYZRHt9iOc+Ju9POtInrPV4KUt58AC5lDi6jx/wELXM74DTvim2gUoB6V1L Sgql86aOwhQj+te7OZFOADBsq+5JSDRnyf7qlZE+k5V6ErH8deRh5DUMVH8I+NUNFM/v yNUTBSxaxdgZeINkxp9Njhp6WQeNQ6BDn3XDlBx/kZq+4O0HACZIF36OaS1F2PdESfPE aFLA== X-Forwarded-Encrypted: i=1; AJvYcCVkt8OTpS1pFXTqppgWV19nhF7xjYiSf/ZdAABCdxHRQMU5vVioVyuJH4uRixKaf6YvsHX82qB9d356fmQ=@vger.kernel.org X-Gm-Message-State: AOJu0Yx5PmW2VxX+L0DTgcDWpEIjfbHlPZ+v1tvDyW3ShxiKOrVMS6Ne 04Rz9L30Ns8ocE3ejbdylA1GiHbREK0da9fb1dXSWJM1s77Mixeqt6H/rw== X-Gm-Gg: ASbGncvdwoxoKCu+455j1iiLaiM+IhxZHkXwUcQ7i6ye6dLp9qQOHmWbVi3brsEb72U rVoi2b4xJ9O7NXiUHAkcEBPpyCBb6DUqBb8ouKRrw9GSYKssFAOSH1oDMzcTVEEJYbYxqgQsITa TQbaw6sGuf6MeR9HhulvWODcyaikW6ol8Okr/kzgWhEAlPIpQkAQIaYDuhpI3VN5fvRyAudSRz0 vP0EY1bEMImCcSquHUfcv7QqrhzmldlOnEaEHsDEXUgaHkpZwJr6VqH5o/ynfg9n7hOak9W0OjG FPocLUEmvzJcQTMKJHnF X-Google-Smtp-Source: AGHT+IGKT8ncZs0BP4yUL9QW6s/N/Mve2dCBM9yZqZKLjTOm7noCdEwcNW5Zgom1ytAzSOeyIWx0Og== X-Received: by 2002:a05:6512:b9c:b0:53d:ed16:7a43 with SMTP id 2adb3069b0e04-53e1b882fb2mr581462e87.17.1733245736835; Tue, 03 Dec 2024 09:08:56 -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-53df644336fsm1893394e87.80.2024.12.03.09.08.55 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 03 Dec 2024 09:08:55 -0800 (PST) From: Abdiel Janulgue To: 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 , Danilo Krummrich , Wedson Almeida Filho , 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 v5 1/2] rust: error: Add EOVERFLOW Date: Tue, 3 Dec 2024 19:07:43 +0200 Message-ID: <20241203170752.1834271-2-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20241203170752.1834271-1-abdiel.janulgue@gmail.com> References: <20241203170752.1834271-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 --- rust/kernel/error.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 52c502432447..cd57fac7f1f9 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -63,6 +63,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 Fri Dec 19 04:52:56 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 DD68E1FAC49; Tue, 3 Dec 2024 17:09:01 +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=1733245743; cv=none; b=UqycR+n6oW54S9WXYAmbDWbipIXfG27a/eb2KcNvGvZhHjrhuWBqGaFCl+GinTJw4Ig6yyBS5uI2WmSDqTxgDReR8v26EMGW820LMx66I2XyBPHtSeXFpqi9bzIkpLc7l3e8NGCUWa0AzP/Sr22G9S1Vu5mGigeBwR5kmeXGuzE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1733245743; c=relaxed/simple; bh=jDgoZVWs1EZ0BLsWSC/biSIEBFBgOOP/XfjuZPS8yO0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=aMDTWQSWOQGV1368Jk+XPJr4pNEo7rAae4Jzl16a+TknnSPvepk09hQae1jzYnSBj8scSp4ZERL/c/TPunCuADGPcZqWEC5WWzdKaLLHveVqouvwL+b2YlTQGP5hIdeNdKdhRXH8NQnUVQuX68jmk033xX3kyVsGyOkqvqChJmM= 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=PE692NiP; 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="PE692NiP" Received: by mail-lf1-f43.google.com with SMTP id 2adb3069b0e04-53df19bf6a9so6662521e87.1; Tue, 03 Dec 2024 09:09:01 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1733245740; x=1733850540; 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=OTR6Ylpv3eNdxiaC7COAI2rMXOLAET8qmxvIBqqw6fM=; b=PE692NiPR2rmEqjy/LyPQyvIVGmZlgWY7AF2p3ojDFlH2IvI9EbN2RA/z2J5RU3J5k kQPLoejngnSwRRQiFrWWuaN3xHjeAI8ycG0lXrenU9/JzEaSd7KGeyCy6LL7L5XNfEW0 cOSJGXRy9cTn+TDg4+3xClney1V0ggoOdzXZoHOMkBUrON+aIT624ZBWDkiu+/xAgt+A 68C/DTQ22kMrqiTWjcBFM1Mr6Yu534tp4QoIxJOIw0JkiB2GulnOSJqgYL1H8KDkrnw4 ypoGlBVaRiVY3sO4ovVxhOXAxFYDdVZ0P5vEpW7zavxpabpqbW2LBuyX5gEmoVAR/CRM /dDw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1733245740; x=1733850540; 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=OTR6Ylpv3eNdxiaC7COAI2rMXOLAET8qmxvIBqqw6fM=; b=UyxUsiLAAkoSDJ0DIFDmGlaf5r9d3uYA/hSoufLfMGDi7CK9i/iNtCAWpzfDchsjKA yuTF3cfJtKkuYdK4CGDZo9rNjjCdDGbQkmaQiuV5tY7U6JUnRabFIM4Ur4LN4RzmSr/P r5FFpPFYPqkNXoVtMkmCU7PwRl53ODGw9eYjd3wmGVSI2glUP4Ka2z4itNOayPhN2HSF L9Tt+3yPDnZZ8bjmJAWCUXl3rYaA/lgmU+tqiDNb5zNefogtRD5cNSQ9AKD4J6QeiK6m BvQImLFNYDdKp0xssDE/MgKXUqHczeMQK8mnZRv8zr4JGd1cO+X3HupGhjQ4yiDwTbBs sJmw== X-Forwarded-Encrypted: i=1; AJvYcCWHZk3lyHT5cN+r/5XZ8EUjekysPyLp9tgemBBvEq/hUX4+dQrF8QW8WDzxTqC/gF47dKb9/reHl7cHCAo=@vger.kernel.org X-Gm-Message-State: AOJu0YyQ+KCMznxMJ2oISyvoV+/RxxwBMQoFhDKunRF5RouTHT3WyRJI sozF9sxCD8GSE81+w4T+H2TlaYW6pxK6J/3xbUKoT+kGiLyiSzk3yFUkIQ== X-Gm-Gg: ASbGncsEmLGBc3yO3k1qj9HYXyYKed58FMXM5n+YtYLyp/21HK9/XQHf9HAm0pUbW1O Bz+1ekUU91lzb2r/Zr7FNKKz35EugbdnR1zbkZ7nRxna+DIcJYtWzsDTHnDOXgA2scHIDnGh+UH I4hStWZ3KLW8OPdRxcJRdQhNStEhrW6xe91DKHTZLtKyFAoG0bSbI0HG1dSto3+CZUyWtSKJOZ9 9vR1AN6b4lyOSluA5SHylpuupCGHQHDW5IvNHsvmkX4jRsMwYTO67NXiEEZOwdni99gIRdk/CNZ 4phm0J4oVWD5LLF4+qLP X-Google-Smtp-Source: AGHT+IHk1IYP2NKFAmvEFFHZPc7mvlW5OfXCL9iqwuQ5vcHYn6pBy4IkJ3t9oeRJ73P75rqoJytFaw== X-Received: by 2002:ac2:5b90:0:b0:53e:12d6:7853 with SMTP id 2adb3069b0e04-53e12d6786fmr1874749e87.4.1733245739714; Tue, 03 Dec 2024 09:08:59 -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-53df644336fsm1893394e87.80.2024.12.03.09.08.57 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 03 Dec 2024 09:08:58 -0800 (PST) From: Abdiel Janulgue To: 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 , Danilo Krummrich , Wedson Almeida Filho , 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 v5 2/2] rust: add dma coherent allocator abstraction. Date: Tue, 3 Dec 2024 19:07:44 +0200 Message-ID: <20241203170752.1834271-3-abdiel.janulgue@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20241203170752.1834271-1-abdiel.janulgue@gmail.com> References: <20241203170752.1834271-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 Reviewed-by: Daniel Almeida Tested-by: Daniel Almeida --- rust/bindings/bindings_helper.h | 1 + rust/kernel/dma.rs | 136 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 138 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..9279be235fcf --- /dev/null +++ b/rust/kernel/dma.rs @@ -0,0 +1,136 @@ +// 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, + types::ARef, + transmute::{AsBytes, FromBytes}, +}; + +/// 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, +} + +impl CoherentAllocation { + /// Allocates a region of `size_of:: * count` of consistent memory. + /// + /// # Examples + /// + /// ``` + /// use kernel::device::Device; + /// use kernel::dma::CoherentAllocation; + /// + /// # fn test(dev: &Device) -> Result { + /// let c: CoherentAllocation =3D CoherentAllocation::alloc_coher= ent(dev, 4, GFP_KERNEL)?; + /// # Ok::<(), Error>(()) } + /// ``` + pub fn alloc_coherent( + dev: &Device, + count: usize, + flags: kernel::alloc::Flags, + ) -> 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(EO= VERFLOW)?; + 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, flags.as_raw(), + 0, + ) + }; + 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: dev.into(), + dma_handle, + count, + cpu_addr: ret as *mut T, + }) + } + + /// Returns the base address to the allocated region and the dma handl= e. The caller takes + /// ownership of the returned resources. + pub fn into_parts(self) -> (usize, bindings::dma_addr_t) { + let ret =3D (self.cpu_addr as _, self.dma_handle); + 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 as _ + } + + /// 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 + } + + /// Returns the CPU-addressable region as a slice. + pub fn cpu_buf<'a>(&self) -> &'a [T] + { + // SAFETY: The pointer is valid due to type invariant on `Coherent= Allocation` and + // is valid for reads for `self.count * size_of::` bytes. + unsafe { core::slice::from_raw_parts(self.cpu_addr, self.count) } + } + + /// Performs the same functionality as `cpu_buf`, except that a mutabl= e slice is returned. + pub fn cpu_buf_mut<'a>(&mut self) -> &'a mut [T] + { + // SAFETY: The pointer is valid due to type invariant on `Coherent= Allocation` and + // is valid for reads for `self.count * size_of::` bytes. + unsafe { core::slice::from_raw_parts_mut(self.cpu_addr, self.count= ) } + } +} + +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, 0) } + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index e1065a7551a3..6e90ebf5a130 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -35,6 +35,7 @@ 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