From nobody Tue Nov 24 11:35:53 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=91.216.248.203 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795466399; b=rSy7/Bd2VxpHl2HTFWH4VQKyP5ikhVyMScJAGURqNZ0i8ALjICMHunb2Jeb4Kv9m5aWJ iP8vrMs40Mx7pIQNf4XJx1G4C1Mkid8DwttEoa1ce/LiRhRSpHn9UglFgDkS8+KOTVGXR jHU5/vTkTxfXNqh//OJJzCc94RfnGZnxRioUgP5kdSQxc5bXLaUfd+6/04cEMN+/W1PWn kYLouml9MoAiqxibwVYK8vmfdSocA3HWdb93B9Lik0Itp5xvVUq2eSz8dtTH2fbnpQsVn 3IE+ekctV0toR0fyeWSeyvPkZ4TrBp+s0ZI0aa93PoqaEt8wSDM6xinc1MjxG2PtJDQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795466399; h=DMARC-Filter:From:DKIM-Signature:To:Cc:Subject:Date:Message-ID: X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=6cQCl+niXlEMYTUYZXjMbn9i9gRKODH83pxxH7Ja3k4=; b=nj2rRH06nwjOb8Shs+VVP2kC5cMqwCWJDkj4j6KHLvT5+kca/eGt6a6Ow+Fk39SMC8AE ezdMuN4ro5f2NhTlkhaPnfMMZAlkKne8lZkgs929MG3TX5k8XGMEpF+ehtm2vpwVOhiZF 8oxtXQTo7a634qgEnF2w+n3cuKIL4375fm4uI3No9K76dG7tuKL12Ep23aRx2ExdydYln s8GpS5egSOzzpT0AwgZEhymgXOBp0JyIqiELncGaas7R8VCfvk8iNgyvBe0Xh8lyMrj05 ZrdvzBjYVQpvR4oRtt7qFxpZ1X5C4X8U1E/A2IXrtgeSCMwX0sC8C2D4KKM0c4tzmhA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=matt3o12.de; spf=pass smtp.mailfrom=matt3o12.de; dkim=pass header.d=matt3o12.de header.i=@matt3o12.de header.a=rsa-sha256 header.s=securedbylima-20230709 header.b=MQ7zupQl; arc=none smtp.remote-ip=91.216.248.203 Received: from mx1.mail-out.lima-city.de (mx1.mail-out.lima-city.de [91.216.248.203]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id BB754606A32E; Mon, 23 Nov 2026 20:39:58 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org BB754606A32E Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=matt3o12.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=matt3o12.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=matt3o12.de header.i=@matt3o12.de header.a=rsa-sha256 header.s=securedbylima-20230709 header.b=MQ7zupQl From: Matteo Kloiber DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=matt3o12.de; s=securedbylima-20230709; t=1795466390; bh=XALVTHWMsgu1a0FxagPF6ryKmWly2pkY8mk75dxeV4I=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=MQ7zupQleLZOjBgocgFfXMWGtGg9t/Q0IYuYF4fU4bBMU4QixbgpQmT0gLWAzfJE8 7Z5KDnFZ/6RrjZ7AKIY53W393WoFqDZOCbOtLlVxdhVH3A4gWDMQntHZofFJm33ey0 phRPbppo8PplLK4gLTQ8O37fsrzPm4dl9FkPR+SDvYWowC7MYwknGb0pvX1hJvJInV DUZVJJReacAQvt86SCbulwtykCQMm5Yhu5GokSORQpnE5TzxVYosJkQv4bV02cjQKn NdqorE9EDdzKH8ipR96f5vZNi2hdQgjG3h31nZX8pBh/RqTF9amkqU/O8YERZ0tlNy ehBul6c5iBNag== To: Danilo Krummrich , Alexandre Courbot , Alice Ryhl , Abdiel Janulgue , Robin Murphy , Andreas Hindborg , Gary Guo Cc: Daniel Almeida , Miguel Ojeda , David Airlie , Simona Vetter , Bjorn Helgaas , =?UTF-8?q?Krzysztof=20Wilczy=C5=84ski?= , Greg Kroah-Hartman , rust-for-linux@vger.kernel.org, driver-core@lists.linux.dev, dri-devel@lists.freedesktop.org, nova-gpu@lists.linux.dev, linux-kernel@vger.kernel.org, Matteo Kloiber Subject: [RFC PATCH 1/3] rust: pci, platform: pass InitTokens to probe() Date: Mon, 23 Nov 2026 21:39:24 +0100 Message-ID: <20261123203926.1787169-2-kernel@matt3o12.de> X-Mailer: git-send-email 2.51.2 In-Reply-To: <20261123203926.1787169-1-kernel@matt3o12.de> References: <20261123203926.1787169-1-kernel@matt3o12.de> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Some capabilities should only be available to a driver while it binds to a device, for example configuring the device for DMA before any memory is allocated or mapped. A probe-time token lets the type system enforce such ordering, but adding a new argument to probe() for every token would touch every driver each time. Add an InitTokens struct to the PCI and platform buses and pass it to Driver::probe(). Buses add new tokens as fields of this struct. It is marked #[non_exhaustive], so drivers destructure it with `..` and adding tokens later does not break them. The struct carries no tokens yet. Update all drivers, samples and doctests to accept and ignore it. Suggested-by: Danilo Krummrich Link: https://lore.kernel.org/DLR1JCUWS824.35QJU45D2W9ZE@nvidia.com Signed-off-by: Matteo Kloiber --- drivers/cpufreq/rcpufreq_dt.rs | 1 + drivers/gpu/drm/tyr/driver.rs | 1 + drivers/gpu/nova-core/driver.rs | 1 + drivers/pwm/pwm_th1520.rs | 1 + rust/kernel/cpufreq.rs | 1 + rust/kernel/io/mem.rs | 2 ++ rust/kernel/pci.rs | 10 +++++++++- rust/kernel/platform.rs | 10 +++++++++- samples/rust/rust_debugfs.rs | 1 + samples/rust/rust_dma.rs | 1 + samples/rust/rust_driver_auxiliary.rs | 1 + samples/rust/rust_driver_pci.rs | 1 + samples/rust/rust_driver_platform.rs | 1 + samples/rust/rust_i2c_client.rs | 1 + samples/rust/rust_soc.rs | 1 + 15 files changed, 32 insertions(+), 2 deletions(-) diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs index 2b1f18b7a1e7..a6e314f4d809 100644 --- a/drivers/cpufreq/rcpufreq_dt.rs +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -212,6 +212,7 @@ impl platform::Driver for CPUFreqDTDriver { =20 fn probe<'bound>( pdev: &'bound platform::Device>, + _tokens: platform::InitTokens<'bound>, _id_info: Option<&'bound Self::IdInfo>, ) -> impl PinInit + 'bound { cpufreq::Registration::::new_foreign_owned(pdev.a= s_ref())?; diff --git a/drivers/gpu/drm/tyr/driver.rs b/drivers/gpu/drm/tyr/driver.rs index 557f2ec0a767..7650ade4ad72 100644 --- a/drivers/gpu/drm/tyr/driver.rs +++ b/drivers/gpu/drm/tyr/driver.rs @@ -119,6 +119,7 @@ impl platform::Driver for TyrPlatformDriver { =20 fn probe<'bound>( pdev: &'bound platform::Device>, + _tokens: platform::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { pin_init::pin_init_scope(move || { diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver= .rs index d6bc972d47c7..e42987e35846 100644 --- a/drivers/gpu/nova-core/driver.rs +++ b/drivers/gpu/nova-core/driver.rs @@ -100,6 +100,7 @@ impl pci::Driver for NovaCoreDriver { =20 fn probe<'bound>( pdev: &'bound pci::Device>, + _tokens: pci::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { dev_dbg!(pdev, "Probe Nova Core GPU driver.\n"); diff --git a/drivers/pwm/pwm_th1520.rs b/drivers/pwm/pwm_th1520.rs index 728993998446..2486333c4a91 100644 --- a/drivers/pwm/pwm_th1520.rs +++ b/drivers/pwm/pwm_th1520.rs @@ -316,6 +316,7 @@ impl platform::Driver for Th1520PwmPlatformDriver { =20 fn probe<'bound>( pdev: &'bound platform::Device>, + _tokens: platform::InitTokens<'bound>, _id_info: Option<&'bound Self::IdInfo>, ) -> impl PinInit + 'bound { let dev =3D pdev.as_ref(); diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index b75d692846a2..0032264fe72c 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -916,6 +916,7 @@ fn register_em(_policy: &mut Policy) { /// /// fn probe<'bound>( /// pdev: &'bound platform::Device>, +/// _tokens: platform::InitTokens<'bound>, /// _id_info: Option<&'bound Self::IdInfo>, /// ) -> impl PinInit + 'bound { /// cpufreq::Registration::::new_foreign_owned(pdev.= as_ref())?; diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs index 32a919099dcd..50dedd32d1a7 100644 --- a/rust/kernel/io/mem.rs +++ b/rust/kernel/io/mem.rs @@ -70,6 +70,7 @@ pub(crate) unsafe fn new(device: &'a Device, resou= rce: &'a Resource) -> S /// /// fn probe<'bound>( /// pdev: &'bound platform::Device>, + /// _tokens: platform::InitTokens<'bound>, /// info: Option<&'bound Self::IdInfo>, /// ) -> impl PinInit + 'bound { /// let offset =3D 0; // Some offset. @@ -130,6 +131,7 @@ pub fn iomap_exclusive_sized(self) -= > Result( /// pdev: &'bound platform::Device>, + /// _tokens: platform::InitTokens<'bound>, /// info: Option<&'bound Self::IdInfo>, /// ) -> impl PinInit + 'bound { /// let offset =3D 0; // Some offset. diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index 769d01d23429..fdb2934eda0d 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -128,7 +128,7 @@ extern "C" fn probe_callback( let info =3D unsafe { id.info_unchecked_opt::() }; =20 from_result(|| { - let data =3D T::probe(pdev, info); + let data =3D T::probe(pdev, InitTokens { _p: PhantomData }, in= fo); =20 pdev.as_ref().set_drvdata(data)?; Ok(0) @@ -261,6 +261,12 @@ macro_rules! pci_device_table { }; } =20 +/// Initialization tokens passed to a PCI driver's [`Driver::probe`] callb= ack. +#[non_exhaustive] +pub struct InitTokens<'bound> { + _p: PhantomData<&'bound ()>, +} + /// The PCI driver trait. /// /// # Examples @@ -288,6 +294,7 @@ macro_rules! pci_device_table { /// /// fn probe<'bound>( /// _pdev: &'bound pci::Device>, +/// _tokens: pci::InitTokens<'bound>, /// _id_info: Option<&'bound Self::IdInfo>, /// ) -> impl PinInit, Error> + 'bound { /// Err(ENODEV) @@ -317,6 +324,7 @@ pub trait Driver { /// attempt to initialize the device here. fn probe<'bound>( dev: &'bound Device>, + tokens: InitTokens<'bound>, id_info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound; =20 diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index ac0a012ae1bb..a7b33e229a30 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -104,7 +104,7 @@ extern "C" fn probe_callback(pdev: *mut bindings::platf= orm_device) -> kernel::ff let info =3D unsafe { ::id_info(pdev.as_r= ef()) }; =20 from_result(|| { - let data =3D T::probe(pdev, info); + let data =3D T::probe(pdev, InitTokens { _p: PhantomData }, in= fo); =20 pdev.as_ref().set_drvdata(data)?; Ok(0) @@ -159,6 +159,12 @@ macro_rules! module_platform_driver { }; } =20 +/// Initialization tokens passed to a platform driver's [`Driver::probe`] = callback. +#[non_exhaustive] +pub struct InitTokens<'bound> { + _p: PhantomData<&'bound ()>, +} + /// The platform driver trait. /// /// Drivers must implement this trait in order to get a platform driver re= gistered. @@ -199,6 +205,7 @@ macro_rules! module_platform_driver { /// /// fn probe<'bound>( /// _pdev: &'bound platform::Device>, +/// _tokens: platform::InitTokens<'bound>, /// _id_info: Option<&'bound Self::IdInfo>, /// ) -> impl PinInit, Error> + 'bound { /// Err(ENODEV) @@ -229,6 +236,7 @@ pub trait Driver { /// Implementers should attempt to initialize the device here. fn probe<'bound>( dev: &'bound Device>, + tokens: InitTokens<'bound>, id_info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound; =20 diff --git a/samples/rust/rust_debugfs.rs b/samples/rust/rust_debugfs.rs index 77c19a437695..d0cc2b624835 100644 --- a/samples/rust/rust_debugfs.rs +++ b/samples/rust/rust_debugfs.rs @@ -122,6 +122,7 @@ impl platform::Driver for RustDebugFs { =20 fn probe<'bound>( pdev: &'bound platform::Device>, + _tokens: platform::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit + 'bound { RustDebugFs::new(pdev).pin_chain(|this| { diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs index ffb693544673..25ce01f2d224 100644 --- a/samples/rust/rust_dma.rs +++ b/samples/rust/rust_dma.rs @@ -76,6 +76,7 @@ impl pci::Driver for DmaSampleDriver { =20 fn probe<'bound>( pdev: &'bound pci::Device>, + _tokens: pci::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { pin_init::pin_init_scope(move || { diff --git a/samples/rust/rust_driver_auxiliary.rs b/samples/rust/rust_driv= er_auxiliary.rs index 0bee16faecc6..20d2b6d0fb77 100644 --- a/samples/rust/rust_driver_auxiliary.rs +++ b/samples/rust/rust_driver_auxiliary.rs @@ -98,6 +98,7 @@ impl pci::Driver for ParentDriver { =20 fn probe<'bound>( pdev: &'bound pci::Device>, + _tokens: pci::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { try_pin_init!(ParentData { diff --git a/samples/rust/rust_driver_pci.rs b/samples/rust/rust_driver_pci= .rs index 13b035a95756..f658efcd11bf 100644 --- a/samples/rust/rust_driver_pci.rs +++ b/samples/rust/rust_driver_pci.rs @@ -147,6 +147,7 @@ impl pci::Driver for SampleDriver { =20 fn probe<'bound>( pdev: &'bound pci::Device>, + _tokens: pci::InitTokens<'bound>, info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { let vendor =3D pdev.vendor_id(); diff --git a/samples/rust/rust_driver_platform.rs b/samples/rust/rust_drive= r_platform.rs index 710145b3605a..80b08d32435f 100644 --- a/samples/rust/rust_driver_platform.rs +++ b/samples/rust/rust_driver_platform.rs @@ -105,6 +105,7 @@ impl platform::Driver for SampleDriver { =20 fn probe<'bound>( pdev: &'bound platform::Device>, + _tokens: platform::InitTokens<'bound>, info: Option<&'bound Self::IdInfo>, ) -> impl PinInit + 'bound { let dev =3D pdev.as_ref(); diff --git a/samples/rust/rust_i2c_client.rs b/samples/rust/rust_i2c_client= .rs index c8a23875ef5b..93b207699860 100644 --- a/samples/rust/rust_i2c_client.rs +++ b/samples/rust/rust_i2c_client.rs @@ -110,6 +110,7 @@ impl platform::Driver for SampleDriver { =20 fn probe<'bound>( pdev: &'bound platform::Device>, + _tokens: platform::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit + 'bound { dev_info!( diff --git a/samples/rust/rust_soc.rs b/samples/rust/rust_soc.rs index f5e5f2f9adf7..f54c173fed94 100644 --- a/samples/rust/rust_soc.rs +++ b/samples/rust/rust_soc.rs @@ -41,6 +41,7 @@ impl platform::Driver for SampleSocDriver { =20 fn probe<'bound>( pdev: &'bound platform::Device>, + _tokens: platform::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit + 'bound { dev_dbg!(pdev, "Probe Rust SoC driver sample.\n"); --=20 2.51.2 From nobody Tue Nov 24 11:35:53 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=91.216.248.203 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795466400; b=Rwrn9gotM877TkL7BYM8uM7qJ7BbpEzHDQ3+oTY1zpZj7QqQ0dwJka4ePECWZ3BiZe8s uVmJY/qQreRWS81+jUZlgUQ7ME/y5kO1b0AQeS7AI6gw9S6KDvrb5wWVrRsErUUenqA95 cfPCPNDApfl1y66Zi9KdbhgQcQK3dRUiSXe2fmyzIzmur7rjudd7RM5ny2m+sWJP9xJFJ QhY00Qeq3au+eLMvkUwnL38eFQKD8sZ4CNdUDltr4D88M7OnBzzl/Ti7hhHh3W4sjosS0 ptXrmjzrIb7JjdS0X/71e9cGg2eZuCgBxgfJWzcJU5AaoZ677D8oJp/j8qMXW2nRiNg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795466400; h=DMARC-Filter:From:DKIM-Signature:To:Cc:Subject:Date:Message-ID: X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=kdWYwUIrCg4oDc4JID/SSuchsNWPhtmGlygsP9T5Vas=; b=sZHr1/bgfZIme5L7ZdErW1p92lensRQ4R9/8TfCoRv2I66GsrltUVU8i+5W28ILPBLvy MqRfR05M0Ctuc5mslJ6IR6qb7DkggsHHBchxb2j6T725GuwsaHpkEmVblRnzx6TwLsRac zRWjU8MN2zhb9doYMFVDxYN0Tb1P6eDxQaEoSSdSsTTiaJ4TBIyOelS2PN4QP8xbe3Q7Y z8ZEPNsC0PpFn7beuU2pfnq8flwhmf1Yon+9QvPuReS0GeoRNwJZBVZpc37i5nx20RUwL CJvk1BN5nxHRq0QRXts1FitU6jaXJwafltquTJrIacYhzPR41zAWEyGAu2mQciw8XQw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=matt3o12.de; spf=pass smtp.mailfrom=matt3o12.de; dkim=pass header.d=matt3o12.de header.i=@matt3o12.de header.a=rsa-sha256 header.s=securedbylima-20230709 header.b=eXH+cTpt; arc=none smtp.remote-ip=91.216.248.203 Received: from mx1.mail-out.lima-city.de (mx1.mail-out.lima-city.de [91.216.248.203]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E13D5606A33D; Mon, 23 Nov 2026 20:39:59 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E13D5606A33D Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=matt3o12.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=matt3o12.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=matt3o12.de header.i=@matt3o12.de header.a=rsa-sha256 header.s=securedbylima-20230709 header.b=eXH+cTpt From: Matteo Kloiber DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=matt3o12.de; s=securedbylima-20230709; t=1795466392; bh=Lr6DCDd2JVmMA2pnLdm6Y0re5QDYDWHDXLkvL8wD3vM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eXH+cTptI3CiNW1vjnVa+sMF4hw1g8i+pvhAMiHST5LuUz/UAkC4a+UR4dwz7sgct x4D02R8Ucu+0uodMP2j13gV7w4ZWOx+mS9846asQNnsMqZRpSYUVX11yU3XCUwkAfK m+iHwnNnbIf6W1ghWD6X6Bob4RCQJzkkmM8HWQPyBOrGKPs7R9xJiJqs3zZF3LHyaG oEjF/Ca2/n1OLvFQAnHeoZBKcLDBkakX0laSC/s7GTVGsX4sD7ergkNvxASLa2lUZc ng10T6grJw+8TRZSq1fddyhtjoE3ylgngb7N653s4mwuvwgrlq+8bINOVrpMIAUN92 M+qAMQk9Vjgog== To: Danilo Krummrich , Alexandre Courbot , Alice Ryhl , Abdiel Janulgue , Robin Murphy , Andreas Hindborg , Gary Guo Cc: Daniel Almeida , Miguel Ojeda , David Airlie , Simona Vetter , Bjorn Helgaas , =?UTF-8?q?Krzysztof=20Wilczy=C5=84ski?= , Greg Kroah-Hartman , rust-for-linux@vger.kernel.org, driver-core@lists.linux.dev, dri-devel@lists.freedesktop.org, nova-gpu@lists.linux.dev, linux-kernel@vger.kernel.org, Matteo Kloiber Subject: [RFC PATCH 2/3] gpu: nova-core: build Gpu inside pin_init_scope Date: Mon, 23 Nov 2026 21:39:25 +0100 Message-ID: <20261123203926.1787169-3-kernel@matt3o12.de> X-Mailer: git-send-email 2.51.2 In-Reply-To: <20261123203926.1787169-1-kernel@matt3o12.de> References: <20261123203926.1787169-1-kernel@matt3o12.de> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Gpu::new() sets the DMA mask and maximum segment size from inside the try_pin_init!() initializer, after Tree::new(). A follow-up change replaces these setters with a DMA configuration step that returns a handle, and that handle must be available to several fields of the initializer. Wrap the initializer in pin_init_scope(), compute the chip spec before it, and set the DMA parameters right after the spec is known. This keeps the reindentation out of the follow-up change. No functional change, except that the DMA parameters are now set before Tree::new() instead of after it. Signed-off-by: Matteo Kloiber --- drivers/gpu/nova-core/gpu.rs | 233 ++++++++++++++++++----------------- 1 file changed, 118 insertions(+), 115 deletions(-) diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs index 8ab1687847ff..993f1512c391 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -455,142 +455,145 @@ pub(crate) fn new<'a>( ) -> impl PinInit + use<'gpu, 'a> { let dev =3D pdev.as_ref(); =20 - try_pin_init!(Self { - spec: Spec::new(dev, bar).inspect(|spec| { - dev_info!(dev,"NVIDIA ({})\n", spec); - })?, + pin_init::pin_init_scope(move || { + let spec =3D Spec::new(dev, bar).inspect(|spec| { + dev_info!(dev, "NVIDIA ({})\n", spec); + })?; + let dma_mask =3D hal::gpu_hal(spec.chipset).dma_mask(); + // SAFETY: `Gpu` owns all DMA allocations for this device, and= we are + // still constructing it, so no concurrent DMA allocations can= exist. + unsafe { pdev.dma_set_mask_and_coherent(dma_mask)? }; + + // Nova walks SG segments to build page tables, so their lengt= h is + // irrelevant to the device. + // + // SAFETY: `Gpu` owns all DMA allocations for this device, and= we are + // still constructing it, so no concurrent DMA allocations can= exist. + unsafe { pdev.dma_set_max_seg_size(u32::MAX) }; + + Ok(try_pin_init!(Self { + spec, + + tree: Tree::new(pdev, bar, spec.chipset, irq::gsp::GSP_SUB= TREE.into())?, + + _: { + // We must wait for GFW_BOOT completion before doing a= ny significant setup on + // the GPU. + Self::wait_gfw_boot_completion(dev, bar, spec.chipset)= ?; + }, =20 - tree: Tree::new(pdev, bar, spec.chipset, irq::gsp::GSP_SUBTREE= .into())?, + // Initialize this early because `gsp_resources` depends o= n it. + sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset= )?, =20 - _: { - let dma_mask =3D hal::gpu_hal(spec.chipset).dma_mask(); + gsp_resources <- try_pin_init!(GspResources { + device: pdev, =20 - // SAFETY: `Gpu` owns all DMA allocations for this device,= and we are - // still constructing it, so no concurrent DMA allocations= can exist. - unsafe { pdev.dma_set_mask_and_coherent(dma_mask)? }; + spec: *spec, =20 - // Nova walks SG segments to build page tables, so their l= ength is - // irrelevant to the device. - // - // SAFETY: `Gpu` owns all DMA allocations for this device,= and we are - // still constructing it, so no concurrent DMA allocations= can exist. - unsafe { pdev.dma_set_max_seg_size(u32::MAX) }; + bar, =20 - // We must wait for GFW_BOOT completion before doing any s= ignificant setup on the GPU. - Self::wait_gfw_boot_completion(dev, bar, spec.chipset)?; - }, + gsp_falcon: Falcon::new(dev, spec.chipset, bar)?, =20 - // Initialize this early because `gsp_resources` depends on it. - sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset)?, + sec2_falcon: Falcon::new(dev, spec.chipset, bar)?, =20 - gsp_resources <- try_pin_init!(GspResources { - device: pdev, + fsp: Fsp::try_new(dev, bar, spec.chipset)?, =20 - spec: *spec, + timer: Timer::setup(dev, bar, spec.chipset, fsp.as_ref= ())?, =20 - bar, + vgpu: VgpuManager::new(pdev, spec.chipset, fsp.as_mut(= )), =20 - gsp_falcon: Falcon::new(dev, spec.chipset, bar)?, + gsp <- Gsp::new(pdev, bar), =20 - sec2_falcon: Falcon::new(dev, spec.chipset, bar)?, + // This member must be initialized last, so the `Unloa= dBundle` can never be + // dropped from outside of the constructed `GspResourc= es`, ensuring that the + // unload sequence is properly run in case of failure. + unload_bundle: gsp.boot(GspBootContext { + pdev, + bar, + chipset: spec.chipset, + gsp_falcon, + sec2_falcon, + fsp: fsp.as_mut(), + vgpu, + })?, + }), =20 - fsp: Fsp::try_new(dev, bar, spec.chipset)?, + _: { + irq::gsp::quiesce(tree.get_ref(), &gsp_resources.gsp_f= alcon); + }, =20 - timer: Timer::setup(dev, bar, spec.chipset, fsp.as_ref())?, + // SAFETY: The registration is owned by `Gpu`, which is dr= opped when the device is + // unbound, so the registration's `Drop` runs. + _gsp_subtree <- unsafe { + GspSubtree::new( + pdev, + tree.get_ref(), + &gsp_resources.get_ref().gsp_falcon, + &gsp_resources.get_ref().gsp.cmdq, + ) + }, =20 - vgpu: VgpuManager::new(pdev, spec.chipset, fsp.as_mut()), + // No interrupt announces the messages that the GSP posted= during boot, before the + // SWGEN0 latch was cleared. + _: { + gsp_resources.gsp.cmdq.drain()?; + }, =20 - gsp <- Gsp::new(pdev, bar), + gsp_static_info: { + // Obtain and display basic GPU information. + let info =3D gsp_resources.gsp.get_static_info()?; + match info.gpu_name() { + Ok(name) =3D> dev_info!(dev, "GPU name: {}\n", nam= e), + Err(e) =3D> dev_warn!(dev, "GPU name unavailable: = {:?}\n", e), + } =20 - // This member must be initialized last, so the `UnloadBun= dle` can never be dropped - // from outside of the constructed `GspResources`, ensurin= g that the unload sequence - // is properly run in case of failure. - unload_bundle: gsp.boot(GspBootContext { - pdev, - bar, - chipset: spec.chipset, - gsp_falcon, - sec2_falcon, - fsp: fsp.as_mut(), - vgpu, - })?, - }), - - _: { - irq::gsp::quiesce(tree.get_ref(), &gsp_resources.gsp_falco= n); - }, - - // SAFETY: The registration is owned by `Gpu`, which is droppe= d when the device is - // unbound, so the registration's `Drop` runs. - _gsp_subtree <- unsafe { - GspSubtree::new( - pdev, - tree.get_ref(), - &gsp_resources.get_ref().gsp_falcon, - &gsp_resources.get_ref().gsp.cmdq, - ) - }, - - // No interrupt announces the messages that the GSP posted dur= ing boot, before the - // SWGEN0 latch was cleared. - _: { - gsp_resources.gsp.cmdq.drain()?; - }, - - gsp_static_info: { - // Obtain and display basic GPU information. - let info =3D gsp_resources.gsp.get_static_info()?; - match info.gpu_name() { - Ok(name) =3D> dev_info!(dev, "GPU name: {}\n", name), - Err(e) =3D> dev_warn!(dev, "GPU name unavailable: {:?}= \n", e), - } + if !info.usable_fb_regions.is_empty() { + dev_dbg!(dev, "Usable FB regions:\n"); + for region in &info.usable_fb_regions { + dev_dbg!(dev, " - {:#x?}\n", region); + } =20 - if !info.usable_fb_regions.is_empty() { - dev_dbg!(dev, "Usable FB regions:\n"); - for region in &info.usable_fb_regions { - dev_dbg!(dev, " - {:#x?}\n", region); + dev_dbg!( + dev, + "Total usable VRAM: {} MiB\n", + info.vram_size() / u64::SZ_1M + ); } =20 - dev_dbg!( - dev, - "Total usable VRAM: {} MiB\n", - info.vram_size() / u64::SZ_1M - ); - } - - info - }, + info + }, =20 - // Create GPU memory manager owning memory management resource= s. - mm: { - let usable_vram =3D gsp_static_info.usable_fb_regions.firs= t().ok_or(ENODEV)?; - let buddy_params =3D GpuBuddyParams { - base_offset: usable_vram.start, - size: usable_vram.end - usable_vram.start, - chunk_size: Alignment::SZ_4K, - }; + // Create GPU memory manager owning memory management reso= urces. + mm: { + let usable_vram =3D gsp_static_info.usable_fb_regions.= first().ok_or(ENODEV)?; + let buddy_params =3D GpuBuddyParams { + base_offset: usable_vram.start, + size: usable_vram.end - usable_vram.start, + chunk_size: Alignment::SZ_4K, + }; + + GpuMm::new( + bar, + gsp_resources.spec.chipset, + buddy_params, + VramAddress::from_raw(gsp_static_info.total_fb_end= ), + )? + }, =20 - GpuMm::new( - bar, - gsp_resources.spec.chipset, - buddy_params, - VramAddress::from_raw(gsp_static_info.total_fb_end), - )? - }, - - // Create BAR1 user interface for CPU access to GPU virtual me= mory. - bar_user <- { - let pdb_addr =3D VramAddress::from_raw(gsp_static_info.bar= 1_pde_base); - let bar1_idx =3D crate::driver::bar1_resource_index(pdev)?; - let bar1_size =3D pdev.resource_len(bar1_idx)?; - - BarUser::new( - pdb_addr, - gsp_resources.spec.chipset, - bar1_size, - bar1, - ) - }, + // Create BAR1 user interface for CPU access to GPU virtua= l memory. + bar_user <- { + let pdb_addr =3D VramAddress::from_raw(gsp_static_info= .bar1_pde_base); + let bar1_idx =3D crate::driver::bar1_resource_index(pd= ev)?; + let bar1_size =3D pdev.resource_len(bar1_idx)?; + + BarUser::new( + pdb_addr, + gsp_resources.spec.chipset, + bar1_size, + bar1, + ) + }, + })) }) } =20 --=20 2.51.2 From nobody Tue Nov 24 11:35:53 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=91.216.248.203 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795466402; b=bIl1MBML59eb4iDGmKteeDOY7mkgIGl2nwrArCKHLBLfJVmoPtKwMHJujty3PJTdwyaE cQzyDS8sv3f3jSOo6M2CslwQ2Qq3GC/OiE+hxN5PnRA3yNwzRdbOApu9L16dXjsYjj8jq 4egDRAMUKG61Ocg72U3HYS22I66JmF400kqp/Cx0Y3P2RyYSraxkGbb3BVEhm/90J3DLx pi/imskI5nSZFXS6FkenjV/Hg6F0yVnxakRwuZJMVJoKJEAOksZiQBv+OE0Z2qqOI5tAm 8doX9G/A+pzSZUDvXopcIoa/VfeHL3qq+JBAIJIJZtHwWWshlfk8UVZY/jlxhtxNCLQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795466402; h=DMARC-Filter:From:DKIM-Signature:To:Cc:Subject:Date:Message-ID: X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=v5xVNhag/wW39CkeGWS44roUqG8sSUNDSruRGybRBaA=; b=J6Ya6io4g7BchLCxwxdcUoEtYUrwCB6SRw/i2jAGOsUqvKyZWBPt6BDh5nmw3hs3t8CQ yvvaDitozPo03sdJ9VQpc8MVVTSk+1/ERwQ6Z6iHa3CAWE50L8Zr2oSJZzjuOIZ+dvARn zUqBql94M/YchBIUm9wEgq+TcnODdkDYIeIJnZZYT2Eu+qqI3QRibXCJ87bRCHoVFyCaR Z+jt4fPPMqrXvpMrRVbF420ouyYp2mgdUQOb2B1BayZK8aaQoZX2JEaq12go9nzYl7i8O vI35onKpKrjd/W/bFfoUcpjhTJEW4lJ5jUBZVHaGlcNELI4ZK6oSXnW5I02Kn7+mOcQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=matt3o12.de; spf=pass smtp.mailfrom=matt3o12.de; dkim=pass header.d=matt3o12.de header.i=@matt3o12.de header.a=rsa-sha256 header.s=securedbylima-20230709 header.b=VJqOYnOH; arc=none smtp.remote-ip=91.216.248.203 Received: from mx1.mail-out.lima-city.de (mx1.mail-out.lima-city.de [91.216.248.203]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 4036A606A68E; Mon, 23 Nov 2026 20:40:01 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 4036A606A68E Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=matt3o12.de Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=matt3o12.de Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=matt3o12.de header.i=@matt3o12.de header.a=rsa-sha256 header.s=securedbylima-20230709 header.b=VJqOYnOH From: Matteo Kloiber DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=matt3o12.de; s=securedbylima-20230709; t=1795466393; bh=XFtFx6yuzOdS0rMQwsslfA8mrrvFL4PucwDMubk+Yko=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=VJqOYnOHrWcHeBN9Rrn4KjECwiU2xfj18wBk/E589L09beI+u2sIanA1vfZ0QaAnT cy64XlWyfBt765cSWeT55zn2gSMELQjLXRVfXVCPoC26EgJptHFzjSastBaUJcdClr 7SxrgUAPmXQJ0RllFCRPvxYdfpnhQSKGBqxCbgoIsZXw82pM7LkG8SLYvL+hFFc09/ aDhGgaSoxPHEp4xbBB5e71bhp3u+4tHqclMYaYcm3fhmfgyb/KPKL8Ju0CgtorGm8w TL/T66UeD02JBMTKMW0RDTk6xm4H1jldNseDA0SiptPOlvttlLhMejJnmmyJwajGCV pq6vgBVGNwDBw== To: Danilo Krummrich , Alexandre Courbot , Alice Ryhl , Abdiel Janulgue , Robin Murphy , Andreas Hindborg , Gary Guo Cc: Daniel Almeida , Miguel Ojeda , David Airlie , Simona Vetter , Bjorn Helgaas , =?UTF-8?q?Krzysztof=20Wilczy=C5=84ski?= , Greg Kroah-Hartman , rust-for-linux@vger.kernel.org, driver-core@lists.linux.dev, dri-devel@lists.freedesktop.org, nova-gpu@lists.linux.dev, linux-kernel@vger.kernel.org, Matteo Kloiber Subject: [RFC PATCH 3/3] rust: dma: require device configuration before DMA Date: Mon, 23 Nov 2026 21:39:26 +0100 Message-ID: <20261123203926.1787169-4-kernel@matt3o12.de> X-Mailer: git-send-email 2.51.2 In-Reply-To: <20261123203926.1787169-1-kernel@matt3o12.de> References: <20261123203926.1787169-1-kernel@matt3o12.de> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Rust drivers can allocate or map DMA memory without first setting the DMA parameters. A missing setter leaves the existing value in use, which is the bus default or whatever a previously bound driver left behind. This happened with Nova's maximum segment size, fixed in commit 6bd5eaeb9827 ("gpu: nova-core: declare unlimited DMA max segment size"). Add a DMA Setup token to the PCI and platform InitTokens passed to probe. Drivers can read device registers before they configure DMA. Drivers that do not use DMA can discard the token. Add Params for the streaming mask, coherent mask and maximum segment size. Some(value) sets a parameter; None keeps its current value. Do not implement Default, so drivers must specify every field, including new fields. Setup::configure consumes the token and returns a copyable Handle on success. Require this handle for DMA allocations, scatterlist mappings and IOMMU page tables. The handle prevents use of these APIs before configuration and does not permit later changes to DMA parameters. Document the same requirement for DRM callbacks that use the C DMA APIs. Remove the dma::Device trait and its setters, and update drivers and samples. Keep Nova's unlimited segment size and the DMA sample's 64 KiB limit. Leave Tyr's existing segment size unchanged pending a hardware limit review. Link: https://lore.kernel.org/DLHH0K25NLX5.616R4D860TXU@nvidia.com Link: https://lore.kernel.org/DLR1JCUWS824.35QJU45D2W9ZE@nvidia.com Suggested-by: Alexandre Courbot Signed-off-by: Matteo Kloiber --- drivers/gpu/drm/tyr/driver.rs | 19 +- drivers/gpu/drm/tyr/fw.rs | 11 +- drivers/gpu/drm/tyr/mmu/address_space.rs | 7 +- drivers/gpu/drm/tyr/vm.rs | 28 +- drivers/gpu/nova-core/driver.rs | 5 +- drivers/gpu/nova-core/falcon.rs | 13 +- drivers/gpu/nova-core/fb.rs | 11 +- .../nova-core/firmware/fwsec/bootloader.rs | 13 +- drivers/gpu/nova-core/firmware/gsp.rs | 18 +- drivers/gpu/nova-core/firmware/gsp_fmc.rs | 10 +- drivers/gpu/nova-core/firmware/radix3.rs | 17 +- drivers/gpu/nova-core/firmware/riscv.rs | 11 +- drivers/gpu/nova-core/fsp.rs | 20 +- drivers/gpu/nova-core/gpu.rs | 40 +-- drivers/gpu/nova-core/gsp.rs | 19 +- drivers/gpu/nova-core/gsp/boot.rs | 2 +- drivers/gpu/nova-core/gsp/cmdq.rs | 14 +- drivers/gpu/nova-core/gsp/hal/gh100.rs | 9 +- drivers/gpu/nova-core/gsp/hal/tu102.rs | 24 +- drivers/gpu/nova-core/gsp/logbuffer.rs | 23 +- rust/helpers/dma.c | 6 - rust/kernel/dma.rs | 264 +++++++++--------- rust/kernel/drm/driver.rs | 4 + rust/kernel/drm/gem/shmem.rs | 23 +- rust/kernel/iommu/pgtable.rs | 24 +- rust/kernel/pci.rs | 14 +- rust/kernel/platform.rs | 14 +- rust/kernel/scatterlist.rs | 20 +- samples/rust/rust_dma.rs | 19 +- 29 files changed, 387 insertions(+), 315 deletions(-) diff --git a/drivers/gpu/drm/tyr/driver.rs b/drivers/gpu/drm/tyr/driver.rs index 7650ade4ad72..9b9c7bd0fc6a 100644 --- a/drivers/gpu/drm/tyr/driver.rs +++ b/drivers/gpu/drm/tyr/driver.rs @@ -12,7 +12,7 @@ DeviceContext, // }, dma::{ - Device as DmaDevice, + self, DmaMask, // }, drm, @@ -119,9 +119,10 @@ impl platform::Driver for TyrPlatformDriver { =20 fn probe<'bound>( pdev: &'bound platform::Device>, - _tokens: platform::InitTokens<'bound>, + tokens: platform::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { + let platform::InitTokens { dma: setup, .. } =3D tokens; pin_init::pin_init_scope(move || { let core_clk =3D Clk::get(pdev.as_ref(), Some(c"core"))?; let stacks_clk =3D OptionalClk::get(pdev.as_ref(), Some(c"stac= ks"))?; @@ -147,17 +148,21 @@ fn probe<'bound>( let pa_bits =3D MMU_FEATURES::from_raw(gpu_info.mmu_features) .pa_bits() .get(); - // SAFETY: No concurrent DMA allocations or mappings can be ma= de because - // the device is still being probed and therefore isn't being = used by - // other threads of execution. - unsafe { pdev.dma_set_mask_and_coherent(DmaMask::try_new(pa_bi= ts)?)? }; + let mask =3D DmaMask::try_new(pa_bits)?; + let dma =3D setup.configure(dma::Params { + streaming_mask: Some(mask), + coherent_mask: Some(mask), + // TODO: Panthor calls `dma_set_max_seg_size(dev, UINT_MAX= )`; Tyr probably wants + // `Some(NonZeroU32::MAX)` here as well. + max_seg_size: None, + })?; =20 let unreg_dev =3D drm::UnregisteredDevice::::new= (pdev)?; =20 let mmu =3D Mmu::new(pdev.as_ref(), iomem.as_arc_borrow(), &gp= u_info)?; =20 let firmware =3D Firmware::new( - pdev.as_ref(), + dma, iomem.clone(), &unreg_dev, mmu.as_arc_borrow(), diff --git a/drivers/gpu/drm/tyr/fw.rs b/drivers/gpu/drm/tyr/fw.rs index aea151ff1f93..b4e9de26ead5 100644 --- a/drivers/gpu/drm/tyr/fw.rs +++ b/drivers/gpu/drm/tyr/fw.rs @@ -15,10 +15,8 @@ =20 use kernel::{ bitfield, - device::{ - Bound, - Device, // - }, + device::Device, + dma, drm::{ gem::BaseObject, // }, @@ -213,13 +211,14 @@ fn load( =20 /// Load firmware and map sections into MCU VM. pub(crate) fn new( - dev: &'drm Device, + dma: dma::Handle<'drm>, iomem: Arc>, ddev: &TyrDrmDevice, mmu: ArcBorrow<'_, Mmu<'drm>>, gpu_info: &GpuInfo, ) -> Result> { - let vm =3D Vm::new(dev, ddev, mmu, gpu_info)?; + let dev =3D dma.device(); + let vm =3D Vm::new(dma, ddev, mmu, gpu_info)?; vm.activate()?; =20 let result =3D (|| { diff --git a/drivers/gpu/drm/tyr/mmu/address_space.rs b/drivers/gpu/drm/tyr= /mmu/address_space.rs index 76e3d2df6afd..ed131b8a6b57 100644 --- a/drivers/gpu/drm/tyr/mmu/address_space.rs +++ b/drivers/gpu/drm/tyr/mmu/address_space.rs @@ -12,7 +12,8 @@ device::{ Bound, Device, // - }, // + }, + dma, error::Result, io::{ poll, @@ -89,7 +90,7 @@ impl<'drm> VmAsData<'drm> { /// Creates VM address space data by initializing all of its fields. pub(crate) fn new<'a>( mmu: &'a Mmu<'drm>, - dev: &'drm Device, + dma: dma::Handle<'drm>, va_bits: u32, pa_bits: u32, ) -> impl pin_init::PinInit, Error> + 'a { @@ -101,7 +102,7 @@ pub(crate) fn new<'a>( coherent_walk: false, }; =20 - let page_table_init =3D IoPageTable::new(dev, pt_config); + let page_table_init =3D IoPageTable::new(dma, pt_config); =20 try_pin_init!(Self { as_seat: LockedBy::new(&mmu.as_manager, Seat::NoSeat), diff --git a/drivers/gpu/drm/tyr/vm.rs b/drivers/gpu/drm/tyr/vm.rs index 1dd11b2b1253..d3614ca602cc 100644 --- a/drivers/gpu/drm/tyr/vm.rs +++ b/drivers/gpu/drm/tyr/vm.rs @@ -15,6 +15,7 @@ Bound, Device, // }, + dma, drm::{ gem::BaseObject, gpuvm::{ @@ -219,8 +220,10 @@ enum PtOpType { /// Memory Management Unit (MMU) state is properly managed and Translation /// Lookaside Buffer (TLB) entries are flushed. pub(crate) struct PtUpdateContext<'ctx, 'drm> { - /// Device used for DMA-mapping GEM shmem SG tables. + /// Device used for log messages. dev: &'ctx Device, + /// DMA handle used to map GEM shmem SG tables. + dma: dma::Handle<'ctx>, =20 /// Page table. pt: &'ctx IoPageTable<'drm, ARM64LPAES1>, @@ -248,7 +251,7 @@ impl<'ctx, 'drm> PtUpdateContext<'ctx, 'drm> { /// The context will automatically flush the TLB and /// complete the update when dropped. fn new( - dev: &'ctx Device, + dma: dma::Handle<'ctx>, pt: &'ctx IoPageTable<'drm, ARM64LPAES1>, mmu: &'ctx Mmu<'drm>, as_data: &'ctx VmAsData<'drm>, @@ -259,7 +262,8 @@ fn new( mmu.start_vm_update(as_data, ®ion)?; =20 Ok(Self { - dev, + dev: dma.device(), + dma, pt, mmu, as_data, @@ -321,8 +325,10 @@ pub(crate) struct Vm<'drm> { as_data: Arc>, /// MMU manager. mmu: Arc>, - /// Parent device used for DMA mapping and page-table operations. + /// Parent device. dev: &'drm Device, + /// DMA handle used for mappings and page-table operations. + dma: dma::Handle<'drm>, /// DRM GPUVM core for managing virtual address space. #[pin] gpuvm_unique: Mutex>>, @@ -339,11 +345,12 @@ impl<'drm> Vm<'drm> { /// The VM is initialized with a page table configured according to th= e GPU's /// address translation capabilities and registered with the GPUVM fra= mework. pub(crate) fn new( - dev: &'drm Device, + dma: dma::Handle<'drm>, ddev: &TyrDrmDevice, mmu: ArcBorrow<'_, Mmu<'drm>>, gpu_info: &GpuInfo, ) -> Result>> { + let dev =3D dma.device(); let mmu_features =3D MMU_FEATURES::from_raw(gpu_info.mmu_features); let va_bits =3D mmu_features.va_bits().get(); let pa_bits =3D mmu_features.pa_bits().get(); @@ -371,12 +378,13 @@ pub(crate) fn new( })?; let gpuvm =3D ARef::from(&*gpuvm_unique); =20 - let as_data =3D Arc::pin_init(VmAsData::new(&mmu, dev, va_bits, pa= _bits), GFP_KERNEL)?; + let as_data =3D Arc::pin_init(VmAsData::new(&mmu, dma, va_bits, pa= _bits), GFP_KERNEL)?; =20 let vm =3D Arc::pin_init( pin_init!(Self{ as_data, dev, + dma, mmu: mmu.into(), gpuvm, gpuvm_unique <- new_mutex!(gpuvm_unique), @@ -388,7 +396,7 @@ pub(crate) fn new( Ok(vm) } =20 - /// Returns the parent device used by this VM for DMA mapping and page= -table operations. + /// Returns the parent device. pub(crate) fn dev(&self) -> &'drm Device { self.dev } @@ -435,7 +443,7 @@ fn exec_op<'a>( match req.op_type { VmOpType::Map(args) =3D> { let mut pt_upd =3D PtUpdateContext::new( - self.dev, + self.dma, pt, &self.mmu, &self.as_data, @@ -457,7 +465,7 @@ fn exec_op<'a>( } VmOpType::Unmap =3D> { let mut pt_upd =3D PtUpdateContext::new( - self.dev, + self.dma, pt, &self.mmu, &self.as_data, @@ -630,7 +638,7 @@ fn sm_step_map<'op>( return Err(EINVAL); } =20 - let sgt =3D op.obj().sg_table(context.dev).inspect_err(|e| { + let sgt =3D op.obj().sg_table(context.dma).inspect_err(|e| { dev_err!(context.dev, "Failed to get sg_table: {:?}", e); })?; let prot =3D match &context.op_type { diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver= .rs index e42987e35846..cdf0d703538b 100644 --- a/drivers/gpu/nova-core/driver.rs +++ b/drivers/gpu/nova-core/driver.rs @@ -100,9 +100,10 @@ impl pci::Driver for NovaCoreDriver { =20 fn probe<'bound>( pdev: &'bound pci::Device>, - _tokens: pci::InitTokens<'bound>, + tokens: pci::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { + let pci::InitTokens { dma, .. } =3D tokens; dev_dbg!(pdev, "Probe Nova Core GPU driver.\n"); =20 try_pin_init!(NovaCore { @@ -132,7 +133,7 @@ fn probe<'bound>( crate::irq::doorbell_test::run_selftest(pdev, bar, spec.ch= ipset)?; }, =20 - gpu <- Gpu::new(pdev, bar, bar1).pin_chain(|_gpu| { + gpu <- Gpu::new(pdev, dma, bar, bar1).pin_chain(|_gpu| { #[cfg(CONFIG_NOVA_CORE_SELFTESTS)] _gpu.run_selftests(pdev); Ok(()) diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon= .rs index fb4f1cad867e..a3a6f853b7e4 100644 --- a/drivers/gpu/nova-core/falcon.rs +++ b/drivers/gpu/nova-core/falcon.rs @@ -7,6 +7,7 @@ use kernel::{ device, dma::{ + self, Coherent, CoherentBox, DmaAddress, // @@ -374,6 +375,7 @@ pub(crate) trait FalconFirmware { pub(crate) struct Falcon<'a, E: FalconEngine> { hal: KBox>, dev: &'a device::Device, + dma: dma::Handle<'a>, bar: Bar0<'a>, // TODO: make private pub(crate) pfalcon: Mmio<'a, PFalconRegisters>, @@ -382,14 +384,11 @@ pub(crate) struct Falcon<'a, E: FalconEngine> { =20 impl<'a, E: FalconEngine + 'static> Falcon<'a, E> { /// Create a new falcon instance. - pub(crate) fn new( - dev: &'a device::Device, - chipset: Chipset, - bar: Bar0<'a>, - ) -> Result { + pub(crate) fn new(dma: dma::Handle<'a>, chipset: Chipset, bar: Bar0<'a= >) -> Result { Ok(Self { hal: hal::falcon_hal(chipset)?, - dev, + dev: dma.device(), + dma, bar, pfalcon: E::pfalcon(bar), pfalcon2: E::pfalcon2(bar), @@ -651,7 +650,7 @@ fn dma_load + FalconDma= Loadable>(&self, fw: &F) -> // DMA copies are done in chunks of `MEM_BLOCK_ALIGNMENT`, so = pad the length // accordingly and fill with `0`. let mut dma_obj =3D CoherentBox::zeroed_slice( - self.dev, + self.dma, fw_slice.len().next_multiple_of(MEM_BLOCK_ALIGNMENT), GFP_KERNEL, )?; diff --git a/drivers/gpu/nova-core/fb.rs b/drivers/gpu/nova-core/fb.rs index 5ceb7760c78e..164e14a8b6fc 100644 --- a/drivers/gpu/nova-core/fb.rs +++ b/drivers/gpu/nova-core/fb.rs @@ -7,7 +7,10 @@ =20 use kernel::{ device, - dma::CoherentHandle, + dma::{ + self, + CoherentHandle, // + }, fmt, io::Io, prelude::*, @@ -55,17 +58,17 @@ pub(crate) struct SysmemFlush<'sys> { impl<'sys> SysmemFlush<'sys> { /// Allocate a memory page and register it as the sysmem flush page. pub(crate) fn register( - dev: &'sys device::Device, + dma: dma::Handle<'sys>, bar: Bar0<'sys>, chipset: Chipset, ) -> Result { - let page =3D CoherentHandle::alloc(dev, kernel::page::PAGE_SIZE, G= FP_KERNEL)?; + let page =3D CoherentHandle::alloc(dma, kernel::page::PAGE_SIZE, G= FP_KERNEL)?; =20 hal::fb_hal(chipset).write_sysmem_flush_page(bar, page.dma_address= ())?; =20 Ok(Self { chipset, - device: dev, + device: dma.device(), bar, page, }) diff --git a/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs b/drivers/g= pu/nova-core/firmware/fwsec/bootloader.rs index 461e5e6f7899..d504c33d789f 100644 --- a/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +++ b/drivers/gpu/nova-core/firmware/fwsec/bootloader.rs @@ -11,7 +11,10 @@ self, Device, // }, - dma::Coherent, + dma::{ + self, + Coherent, // + }, prelude::*, // }; =20 @@ -45,14 +48,14 @@ pub(crate) struct FwsecFirmwareWithBl<'a> { } =20 impl<'a> FwsecFirmwareWithBl<'a> { - /// Loads the bootloader firmware for `dev` and `chipset`, and wrap `f= irmware` so it can be + /// Loads the bootloader firmware for the device and `chipset`, and wr= ap `firmware` so it can be /// loaded using it. pub(crate) fn new( firmware: FwsecFirmware, - dev: &'a Device, + dma: dma::Handle<'a>, chipset: Chipset, ) -> Result { - let bootloader =3D GenericBootloader::new(dev, chipset)?; + let bootloader =3D GenericBootloader::new(dma.device(), chipset)?; =20 // `BootloaderDmemDescV2` expects the source to be a mirror image = of the destination and // uses the same offset parameter for both. @@ -77,7 +80,7 @@ pub(crate) fn new( =20 ( align_padding, - Coherent::from_slice(dev, firmware_obj.as_slice(), GFP_KER= NEL)?, + Coherent::from_slice(dma, firmware_obj.as_slice(), GFP_KER= NEL)?, ) }; =20 diff --git a/drivers/gpu/nova-core/firmware/gsp.rs b/drivers/gpu/nova-core/= firmware/gsp.rs index 341a8b19aa38..aafa6c583421 100644 --- a/drivers/gpu/nova-core/firmware/gsp.rs +++ b/drivers/gpu/nova-core/firmware/gsp.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: GPL-2.0 =20 use kernel::{ - device, dma::{ + self, Coherent, DmaAddress, // }, @@ -37,12 +37,10 @@ pub(crate) struct GspFirmware<'a> { } =20 impl<'a> GspFirmware<'a> { - /// Loads the GSP firmware binaries, map them into `dev`'s address-spa= ce, and creates the page - /// tables expected by the GSP bootloader to load it. - pub(crate) fn new( - dev: &'a device::Device, - chipset: Chipset, - ) -> impl PinInit + 'a { + /// Loads the GSP firmware binaries, maps them into the device's addre= ss space, and creates + /// the page tables expected by the GSP bootloader to load it. + pub(crate) fn new(dma: dma::Handle<'a>, chipset: Chipset) -> impl PinI= nit + 'a { + let dev =3D dma.device(); pin_init::pin_init_scope(move || { let firmware =3D request_tlv(dev, chipset, "gsp")?; let tlv =3D Tlv::new(firmware.data())?; @@ -56,15 +54,15 @@ pub(crate) fn new( let filename =3D CString::try_from_fmt(fmt!("nvidia/{chip_name= }/gsp/{file}"))?; firmware::request_into_buf(&filename, dev, fw_vvec.as_mut_slic= e())?; =20 - let signatures =3D Coherent::from_slice(dev, tlv.get_bytes(b"S= IGN")?, GFP_KERNEL)?; + let signatures =3D Coherent::from_slice(dma, tlv.get_bytes(b"S= IGN")?, GFP_KERNEL)?; =20 Ok(try_pin_init!(Self { - radix3 <- Radix3::new(dev, fw_vvec), + radix3 <- Radix3::new(dma, fw_vvec), signatures, bootloader: { let bl =3D request_tlv(dev, chipset, "gsp_bootloader")= ?; =20 - RiscvFirmware::new(dev, &bl)? + RiscvFirmware::new(dma, &bl)? }, })) }) diff --git a/drivers/gpu/nova-core/firmware/gsp_fmc.rs b/drivers/gpu/nova-c= ore/firmware/gsp_fmc.rs index 94fcc86c7dff..6c52eb2dbed9 100644 --- a/drivers/gpu/nova-core/firmware/gsp_fmc.rs +++ b/drivers/gpu/nova-core/firmware/gsp_fmc.rs @@ -6,7 +6,10 @@ =20 use kernel::{ device, - dma::Coherent, + dma::{ + self, + Coherent, // + }, prelude::*, // }; =20 @@ -48,7 +51,8 @@ pub(crate) struct GspFmcFirmware<'a> { } =20 impl<'a> GspFmcFirmware<'a> { - pub(crate) fn new(dev: &'a device::Device, chipset: Chi= pset) -> Result { + pub(crate) fn new(dma: dma::Handle<'a>, chipset: Chipset) -> Result { + let dev =3D dma.device(); let fw =3D request_tlv(dev, chipset, "fmc")?; let tlv =3D Tlv::new(fw.data())?; dev_dbg!( @@ -58,7 +62,7 @@ pub(crate) fn new(dev: &'a device::Device,= chipset: Chipset) -> R ); =20 let fmc_image_data =3D tlv.get_bytes(b"BLOB")?; - let fmc_image =3D Coherent::from_slice(dev, fmc_image_data, GFP_KE= RNEL)?; + let fmc_image =3D Coherent::from_slice(dma, fmc_image_data, GFP_KE= RNEL)?; =20 Ok(Self { fmc_image, diff --git a/drivers/gpu/nova-core/firmware/radix3.rs b/drivers/gpu/nova-co= re/firmware/radix3.rs index 94235bd1209d..1dfe6b96ab45 100644 --- a/drivers/gpu/nova-core/firmware/radix3.rs +++ b/drivers/gpu/nova-core/firmware/radix3.rs @@ -12,8 +12,8 @@ //! ``` =20 use kernel::{ - device, dma::{ + self, Coherent, CoherentBox, DataDirection, @@ -50,23 +50,20 @@ pub(crate) struct Radix3<'a> { } =20 impl<'a> Radix3<'a> { - /// Builds a radix3 page table over `data`, mapped for `dev` to read. = May sleep. - pub(crate) fn new( - dev: &'a device::Device, - data: VVec, - ) -> impl PinInit + 'a { + /// Builds a radix3 page table over `data`, mapped for the device to r= ead. May sleep. + pub(crate) fn new(dma: dma::Handle<'a>, data: VVec) -> impl PinIni= t + 'a { let size =3D data.len(); =20 pin_init::pin_init_scope(move || { Ok(try_pin_init!(Self { - data <- SGTable::new(dev, data, DataDirection::ToDevice, G= FP_KERNEL), + data <- SGTable::new(dma, data, DataDirection::ToDevice, G= FP_KERNEL), level2 <- { build_lvl(&data) - .map(|l2| SGTable::new(dev, l2, DataDirection::ToD= evice, GFP_KERNEL))? + .map(|l2| SGTable::new(dma, l2, DataDirection::ToD= evice, GFP_KERNEL))? }, level1 <- { build_lvl(&level2) - .map(|l1| SGTable::new(dev, l1, DataDirection::ToD= evice, GFP_KERNEL))? + .map(|l1| SGTable::new(dma, l1, DataDirection::ToD= evice, GFP_KERNEL))? }, level0: { // Allocate the level 0 page table as a device-visible= DMA object, and map the @@ -79,7 +76,7 @@ pub(crate) fn new( // Create level 0 page table data and fill its first e= ntry with the level 1 // table. let mut level0 =3D CoherentBox::<'_, [u64]>::zeroed_sl= ice( - dev, + dma, GSP_PAGE_SIZE / size_of::(), GFP_KERNEL )?; diff --git a/drivers/gpu/nova-core/firmware/riscv.rs b/drivers/gpu/nova-cor= e/firmware/riscv.rs index f05cfb1c65da..f78af9bba740 100644 --- a/drivers/gpu/nova-core/firmware/riscv.rs +++ b/drivers/gpu/nova-core/firmware/riscv.rs @@ -4,8 +4,10 @@ //! dedicated header. =20 use kernel::{ - device, - dma::Coherent, + dma::{ + self, + Coherent, // + }, firmware::Firmware, prelude::*, // }; @@ -28,7 +30,8 @@ pub(crate) struct RiscvFirmware<'a> { =20 impl<'a> RiscvFirmware<'a> { /// Parses the RISC-V firmware image contained in `fw`. - pub(crate) fn new(dev: &'a device::Device, fw: &Firmwar= e) -> Result { + pub(crate) fn new(dma: dma::Handle<'a>, fw: &Firmware) -> Result= { + let dev =3D dma.device(); let tlv =3D Tlv::new(fw.data())?; dev_dbg!( dev, @@ -41,7 +44,7 @@ pub(crate) fn new(dev: &'a device::Device,= fw: &Firmware) -> Resu let manifest_offset =3D tlv.get_u32(b"MFOF")?; let app_version =3D tlv.get_u32(b"APPV")?; =20 - let ucode =3D Coherent::from_slice(dev, tlv.get_bytes(b"BLOB")?, G= FP_KERNEL)?; + let ucode =3D Coherent::from_slice(dma, tlv.get_bytes(b"BLOB")?, G= FP_KERNEL)?; =20 Ok(Self { ucode, diff --git a/drivers/gpu/nova-core/fsp.rs b/drivers/gpu/nova-core/fsp.rs index ea08cd58346f..9675d3941ed5 100644 --- a/drivers/gpu/nova-core/fsp.rs +++ b/drivers/gpu/nova-core/fsp.rs @@ -12,7 +12,10 @@ =20 use kernel::{ device, - dma::Coherent, + dma::{ + self, + Coherent, // + }, io::poll::read_poll_timeout, num::TryIntoBounded, prelude::*, @@ -359,7 +362,7 @@ impl<'a> FmcBootArgs<'a> { /// Builds FMC boot arguments, allocating the DMA-coherent boot parame= ter /// structure that FSP will read. pub(crate) fn new( - dev: &'a device::Device, + dma: dma::Handle<'a>, chipset: Chipset, wpr_meta: Coherent<'a, GspFwWprMeta>, libos: &'a Coherent<'a, [LibosMemoryRegionInitArgument]>, @@ -369,7 +372,7 @@ pub(crate) fn new( =20 Ok(Self { chipset, - fmc_boot_params: Coherent::init(dev, GFP_KERNEL, init)?, + fmc_boot_params: Coherent::init(dma, GFP_KERNEL, init)?, resume, _wpr_meta: wpr_meta, _libos: libos, @@ -401,13 +404,13 @@ impl<'a> Fsp<'a> { /// /// If `chipset` doesn't support FSP, `Ok(None)` is returned. pub(crate) fn try_new( - dev: &'a device::Device, + dma: dma::Handle<'a>, bar: Bar0<'a>, chipset: Chipset, ) -> Result> { match hal::fsp_hal(chipset) { None =3D> Ok(None), - Some(hal) =3D> Self::wait_secure_boot(dev, bar, chipset, hal).= map(Option::Some), + Some(hal) =3D> Self::wait_secure_boot(dma, bar, chipset, hal).= map(Option::Some), } } =20 @@ -417,7 +420,7 @@ pub(crate) fn try_new( /// elapses. Returning an [`Fsp`] only on success guarantees, at the A= PI level, that the /// interface is not used before secure boot has completed. fn wait_secure_boot( - dev: &'a device::Device, + dma: dma::Handle<'a>, bar: Bar0<'a>, chipset: Chipset, hal: &'static dyn hal::FspHal, @@ -425,8 +428,9 @@ fn wait_secure_boot( /// FSP secure boot completion timeout in milliseconds. const FSP_SECURE_BOOT_TIMEOUT_MS: i64 =3D 5000; =20 - let falcon =3D Falcon::::new(dev, chipset, bar)?; - let fmc_fw =3D GspFmcFirmware::new(dev, chipset)?; + let dev =3D dma.device(); + let falcon =3D Falcon::::new(dma, chipset, bar)?; + let fmc_fw =3D GspFmcFirmware::new(dma, chipset)?; =20 read_poll_timeout( || Ok(hal.fsp_boot_status(bar)), diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs index 993f1512c391..47ec4fa1400e 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -1,10 +1,13 @@ // SPDX-License-Identifier: GPL-2.0 =20 -use core::ops::Range; +use core::{ + num::NonZeroU32, + ops::Range, // +}; =20 use kernel::{ device, - dma::Device, + dma, fmt, gpu::buddy::GpuBuddyParams, io::Io, @@ -322,6 +325,8 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Resul= t { struct GspResources<'gpu> { /// Device owning the GPU. device: &'gpu pci::Device, + /// DMA handle used for the GPU's allocations. + dma_handle: dma::Handle<'gpu>, /// Details about the chipset. spec: Spec, /// MMIO mapping of PCI BAR 0. @@ -434,6 +439,7 @@ fn drop(self: Pin<&mut Self>) { .unload( GspBootContext { pdev: device, + dma: *this.dma_handle, bar, chipset: this.spec.chipset, gsp_falcon: &*this.gsp_falcon, @@ -450,6 +456,7 @@ fn drop(self: Pin<&mut Self>) { impl<'gpu> Gpu<'gpu> { pub(crate) fn new<'a>( pdev: &'gpu pci::Device>, + setup: dma::Setup<'gpu>, bar: Bar0<'gpu>, bar1: Bar1<'gpu>, ) -> impl PinInit + use<'gpu, 'a> { @@ -460,16 +467,13 @@ pub(crate) fn new<'a>( dev_info!(dev, "NVIDIA ({})\n", spec); })?; let dma_mask =3D hal::gpu_hal(spec.chipset).dma_mask(); - // SAFETY: `Gpu` owns all DMA allocations for this device, and= we are - // still constructing it, so no concurrent DMA allocations can= exist. - unsafe { pdev.dma_set_mask_and_coherent(dma_mask)? }; - - // Nova walks SG segments to build page tables, so their lengt= h is - // irrelevant to the device. - // - // SAFETY: `Gpu` owns all DMA allocations for this device, and= we are - // still constructing it, so no concurrent DMA allocations can= exist. - unsafe { pdev.dma_set_max_seg_size(u32::MAX) }; + let dma =3D setup.configure(dma::Params { + streaming_mask: Some(dma_mask), + coherent_mask: Some(dma_mask), + // Nova walks SG segments to build page tables, so their l= ength is + // irrelevant to the device. + max_seg_size: Some(NonZeroU32::MAX), + })?; =20 Ok(try_pin_init!(Self { spec, @@ -483,32 +487,34 @@ pub(crate) fn new<'a>( }, =20 // Initialize this early because `gsp_resources` depends o= n it. - sysmem_flush: SysmemFlush::register(dev, bar, spec.chipset= )?, + sysmem_flush: SysmemFlush::register(dma, bar, spec.chipset= )?, =20 gsp_resources <- try_pin_init!(GspResources { device: pdev, + dma_handle: dma, =20 spec: *spec, =20 bar, =20 - gsp_falcon: Falcon::new(dev, spec.chipset, bar)?, + gsp_falcon: Falcon::new(dma, spec.chipset, bar)?, =20 - sec2_falcon: Falcon::new(dev, spec.chipset, bar)?, + sec2_falcon: Falcon::new(dma, spec.chipset, bar)?, =20 - fsp: Fsp::try_new(dev, bar, spec.chipset)?, + fsp: Fsp::try_new(dma, bar, spec.chipset)?, =20 timer: Timer::setup(dev, bar, spec.chipset, fsp.as_ref= ())?, =20 vgpu: VgpuManager::new(pdev, spec.chipset, fsp.as_mut(= )), =20 - gsp <- Gsp::new(pdev, bar), + gsp <- Gsp::new(dma, bar), =20 // This member must be initialized last, so the `Unloa= dBundle` can never be // dropped from outside of the constructed `GspResourc= es`, ensuring that the // unload sequence is properly run in case of failure. unload_bundle: gsp.boot(GspBootContext { pdev, + dma, bar, chipset: spec.chipset, gsp_falcon, diff --git a/drivers/gpu/nova-core/gsp.rs b/drivers/gpu/nova-core/gsp.rs index 2f1cdf8b7bec..e218a1628646 100644 --- a/drivers/gpu/nova-core/gsp.rs +++ b/drivers/gpu/nova-core/gsp.rs @@ -7,6 +7,7 @@ debugfs, device, dma::{ + self, Coherent, CoherentBox, CoherentView, @@ -64,6 +65,7 @@ /// - `'ctx` is a shorter lifetime during which this context borrows those= subdevices. pub(crate) struct GspBootContext<'ctx, 'gpu> { pub(crate) pdev: &'gpu pci::Device, + pub(crate) dma: dma::Handle<'gpu>, pub(crate) bar: Bar0<'gpu>, pub(crate) chipset: Chipset, pub(crate) gsp_falcon: &'ctx Falcon<'gpu, GspFalcon>, @@ -114,25 +116,20 @@ pub(crate) struct Gsp<'gsp> { } =20 impl<'gsp> Gsp<'gsp> { - // Creates an in-place initializer for a `Gsp` manager for `pdev`. - pub(crate) fn new( - pdev: &'gsp pci::Device, - bar: Bar0<'gsp>, - ) -> impl PinInit + 'gsp { + // Creates an in-place initializer for a `Gsp` manager for the device. + pub(crate) fn new(dma: dma::Handle<'gsp>, bar: Bar0<'gsp>) -> impl Pin= Init + 'gsp { pin_init::pin_init_scope(move || { - let dev =3D pdev.as_ref(); - - let log_buffers =3D LogBuffers::new(dev)?; + let log_buffers =3D LogBuffers::new(dma)?; =20 // Initialise the logging structures. The OpenRM equivalents a= re in: // _kgspInitLibosLoggingStructures (allocates memory for buffe= rs) // kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array) Ok(try_pin_init!(Self { - cmdq <- Cmdq::new(dev, bar), - rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded= ::new(&cmdq))?, + cmdq <- Cmdq::new(dma, bar), + rmargs: Coherent::init(dma, GFP_KERNEL, GspArgumentsPadded= ::new(&cmdq))?, libos: { let mut libos =3D CoherentBox::zeroed_slice( - dev, + dma, GSP_PAGE_SIZE / size_of::(), GFP_KERNEL, )?; diff --git a/drivers/gpu/nova-core/gsp/boot.rs b/drivers/gpu/nova-core/gsp/= boot.rs index 9d5da5b165ac..fc24a779305f 100644 --- a/drivers/gpu/nova-core/gsp/boot.rs +++ b/drivers/gpu/nova-core/gsp/boot.rs @@ -39,7 +39,7 @@ pub(crate) fn boot( let dev =3D pdev.as_ref(); let hal =3D super::hal::gsp_hal(chipset); =20 - let gsp_fw =3D KBox::pin_init(GspFirmware::new(dev, chipset), GFP_= KERNEL)?; + let gsp_fw =3D KBox::pin_init(GspFirmware::new(ctx.dma, chipset), = GFP_KERNEL)?; =20 self.cmdq .send_rpc_command_no_wait(commands::rpc::SetSystemInfo::new( diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/= cmdq.rs index e2b9a5383a66..e442d956ce19 100644 --- a/drivers/gpu/nova-core/gsp/cmdq.rs +++ b/drivers/gpu/nova-core/gsp/cmdq.rs @@ -12,6 +12,7 @@ use kernel::{ device, dma::{ + self, Coherent, CoherentBox, DmaAddress, // @@ -174,12 +175,12 @@ struct DmaGspMem<'a> { } =20 impl<'a> DmaGspMem<'a> { - /// Allocate a new instance and map it for `dev`. - fn new(dev: &'a device::Device, bar: Bar0<'a>) -> Resul= t { + /// Allocate a new instance and map it for the device. + fn new(dma: dma::Handle<'a>, bar: Bar0<'a>) -> Result { const MSGQ_SIZE: u32 =3D cv!(size_of::()); const RX_HDR_OFF: u32 =3D cv!(mem::offset_of!(Msgq, rx)); =20 - let mut gsp_mem =3D CoherentBox::<'_, GspMem>::zeroed(dev, GFP_KER= NEL)?; + let mut gsp_mem =3D CoherentBox::<'_, GspMem>::zeroed(dma, GFP_KER= NEL)?; gsp_mem.cpuq.tx =3D MsgqTxHeader::new(MSGQ_SIZE, RX_HDR_OFF, MSGQ_= NUM_PAGES); gsp_mem.cpuq.rx =3D MsgqRxHeader::new(); =20 @@ -489,13 +490,14 @@ impl<'cmdq> Cmdq<'cmdq> { /// Default timeout for receiving a message from the GSP. pub(super) const RECEIVE_TIMEOUT: Delta =3D Delta::from_secs(5); =20 - /// Creates a new command queue for `dev`. + /// Creates a new command queue for the device. pub(crate) fn new( - dev: &'cmdq device::Device, + dma: dma::Handle<'cmdq>, bar: Bar0<'cmdq>, ) -> impl PinInit + 'cmdq { pin_init_scope(move || { - let gsp_mem =3D DmaGspMem::new(dev, bar)?; + let dev =3D dma.device(); + let gsp_mem =3D DmaGspMem::new(dma, bar)?; =20 Ok(try_pin_init!(Self { dma_addr: gsp_mem.mem.dma_address(), diff --git a/drivers/gpu/nova-core/gsp/hal/gh100.rs b/drivers/gpu/nova-core= /gsp/hal/gh100.rs index 91201b51030e..aad4a6b222aa 100644 --- a/drivers/gpu/nova-core/gsp/hal/gh100.rs +++ b/drivers/gpu/nova-core/gsp/hal/gh100.rs @@ -154,9 +154,12 @@ fn boot<'gpu>( let fb_sizes =3D FbSizes::new(chipset, ctx.bar, ctx.vgpu.state())?; dev_dbg!(dev, "{:#x?}\n", fb_sizes); =20 - let wpr_meta =3D - Coherent::init(dev, GFP_KERNEL, GspFwWprMeta::from_sizes(gsp_f= w, &fb_sizes))?; - let args =3D FmcBootArgs::new(dev, chipset, wpr_meta, &gsp.libos, = false)?; + let wpr_meta =3D Coherent::init( + ctx.dma, + GFP_KERNEL, + GspFwWprMeta::from_sizes(gsp_fw, &fb_sizes), + )?; + let args =3D FmcBootArgs::new(ctx.dma, chipset, wpr_meta, &gsp.lib= os, false)?; =20 let unload_bundle =3D crate::gsp::UnloadBundle( KBox::new(FspUnloadBundle, GFP_KERNEL)? as KBox diff --git a/drivers/gpu/nova-core/gsp/hal/tu102.rs b/drivers/gpu/nova-core= /gsp/hal/tu102.rs index e90db1a23032..48f6a3dffa29 100644 --- a/drivers/gpu/nova-core/gsp/hal/tu102.rs +++ b/drivers/gpu/nova-core/gsp/hal/tu102.rs @@ -5,7 +5,10 @@ =20 use kernel::{ device, - dma::Coherent, + dma::{ + self, + Coherent, // + }, io::Io, types::ScopeGuard, // }; @@ -136,13 +139,15 @@ impl Tu102 { /// created the WPR2 region. fn run_fwsec_frts( &self, - dev: &device::Device, + dma: dma::Handle<'_>, chipset: Chipset, falcon: &Falcon<'_, GspEngine>, bar: Bar0<'_>, bios: &Vbios, fb_ranges: &FbRanges, ) -> Result { + let dev =3D dma.device(); + // Check that the WPR2 region does not already exist - if it does,= we cannot run // FWSEC-FRTS until the GPU is reset. if wpr2_range(bar).is_some() { @@ -165,7 +170,7 @@ fn run_fwsec_frts( )?; =20 if self.needs_fwsec_bootloader { - let fwsec_frts_bl =3D FwsecFirmwareWithBl::new(fwsec_frts, dev= , chipset)?; + let fwsec_frts_bl =3D FwsecFirmwareWithBl::new(fwsec_frts, dma= , chipset)?; // Load and run the bootloader, which will load FWSEC-FRTS and= run it. fwsec_frts_bl.run(dev, falcon)?; } else { @@ -214,16 +219,18 @@ fn run_fwsec_frts( /// Load and prepare the resources required to properly reset the GSP = after it has been stopped. fn build_unload_bundle<'gpu>( &self, - dev: &'gpu device::Device, + dma: dma::Handle<'gpu>, chipset: Chipset, bios: &Vbios, gsp_falcon: &Falcon<'_, GspEngine>, sec2_falcon: &Falcon<'_, Sec2>, ) -> Result> { + let dev =3D dma.device(); + // Load the FWSEC SB firmware, as well as its bootloader if requir= ed. let fwsec_sb =3D FwsecFirmware::new(dev, gsp_falcon, bios, FwsecCo= mmand::Sb)?; let fwsec_sb =3D if self.needs_fwsec_bootloader { - FwsecUnloadFirmware::WithBl(FwsecFirmwareWithBl::new(fwsec_sb,= dev, chipset)?) + FwsecUnloadFirmware::WithBl(FwsecFirmwareWithBl::new(fwsec_sb,= dma, chipset)?) } else { FwsecUnloadFirmware::WithoutBl(fwsec_sb) }; @@ -252,6 +259,7 @@ fn boot<'gpu>( ctx: &mut GspBootContext<'_, 'gpu>, gsp_fw: &GspFirmware<'gpu>, ) -> Result>> { + let dma =3D ctx.dma; let dev =3D ctx.dev(); let bar =3D ctx.bar; let chipset =3D ctx.chipset; @@ -264,7 +272,7 @@ fn boot<'gpu>( // Declared before the unload guard so that if Booter fails while = running, SEC2 is reset // by the guard before this allocation is freed. let wpr_meta =3D Coherent::init( - dev, + dma, GFP_KERNEL, GspFwWprMeta::from_ranges(gsp_fw, &fb_ranges), )?; @@ -276,7 +284,7 @@ fn boot<'gpu>( // If the unload bundle creation fails, the GPU will need to be re= set before the driver can // be probed again. let unload_bundle =3D self - .build_unload_bundle(dev, chipset, &bios, gsp_falcon, sec2_fal= con) + .build_unload_bundle(dma, chipset, &bios, gsp_falcon, sec2_fal= con) .inspect_err(|e| dev_warn!(dev, "Failed to prepare unload firm= ware: {:?}\n", e)) .ok(); =20 @@ -289,7 +297,7 @@ fn boot<'gpu>( =20 // FWSEC-FRTS is not executed on chips where the FRTS region size = is 0 (e.g. GA100). if !fb_ranges.frts.is_empty() { - self.run_fwsec_frts(dev, chipset, gsp_falcon, bar, &bios, &fb_= ranges)?; + self.run_fwsec_frts(dma, chipset, gsp_falcon, bar, &bios, &fb_= ranges)?; } =20 gsp_falcon.reset()?; diff --git a/drivers/gpu/nova-core/gsp/logbuffer.rs b/drivers/gpu/nova-core= /gsp/logbuffer.rs index 5455d990ffb4..2b3494470a83 100644 --- a/drivers/gpu/nova-core/gsp/logbuffer.rs +++ b/drivers/gpu/nova-core/gsp/logbuffer.rs @@ -5,7 +5,10 @@ use kernel::{ debugfs, device, - dma::Coherent, + dma::{ + self, + Coherent, // + }, io::{ io_project, Io, // @@ -47,9 +50,9 @@ pub(super) struct LogBuffer<'a>(pub(super) Coherent<'a, [u8; LOG_BUFFER_SI= ZE]>); =20 impl<'a> LogBuffer<'a> { - /// Creates a new `LogBuffer` mapped on `dev`. - fn new(dev: &'a device::Device) -> Result { - let obj =3D Self(Coherent::zeroed(dev, GFP_KERNEL)?); + /// Creates a new `LogBuffer` mapped on the device. + fn new(dma: dma::Handle<'a>) -> Result { + let obj =3D Self(Coherent::zeroed(dma, GFP_KERNEL)?); =20 let start_addr =3D obj.0.dma_address(); =20 @@ -98,13 +101,13 @@ pub(super) struct LogBuffers<'a> { } =20 impl<'a> LogBuffers<'a> { - /// Allocates the log buffers of `dev`. - pub(super) fn new(dev: &'a device::Device) -> Result { + /// Allocates the log buffers of the device. + pub(super) fn new(dma: dma::Handle<'a>) -> Result { Ok(Self { - dev, - loginit: LogBuffer::new(dev)?, - logintr: LogBuffer::new(dev)?, - logrm: LogBuffer::new(dev)?, + dev: dma.device(), + loginit: LogBuffer::new(dma)?, + logintr: LogBuffer::new(dma)?, + logrm: LogBuffer::new(dma)?, }) } =20 diff --git a/rust/helpers/dma.c b/rust/helpers/dma.c index ff8f24dae9df..443360237606 100644 --- a/rust/helpers/dma.c +++ b/rust/helpers/dma.c @@ -17,12 +17,6 @@ __rust_helper void rust_helper_dma_free_attrs(struct dev= ice *dev, size_t size, dma_free_attrs(dev, size, cpu_addr, dma_handle, attrs); } =20 -__rust_helper int rust_helper_dma_set_mask_and_coherent(struct device *dev, - u64 mask) -{ - return dma_set_mask_and_coherent(dev, mask); -} - __rust_helper int rust_helper_dma_set_mask(struct device *dev, u64 mask) { return dma_set_mask(dev, mask); diff --git a/rust/kernel/dma.rs b/rust/kernel/dma.rs index 580e1c3427bc..03f48bd1f940 100644 --- a/rust/kernel/dma.rs +++ b/rust/kernel/dma.rs @@ -9,8 +9,7 @@ debugfs, device::{ self, - Bound, - Core, // + Bound, // }, error::to_result, fs::file, @@ -31,6 +30,7 @@ uaccess::UserSliceWriter, // }; use core::{ + num::NonZeroU32, ops::{ Deref, DerefMut, // @@ -48,83 +48,124 @@ /// Note that this may be `u64` even on 32-bit architectures. pub type DmaAddress =3D bindings::dma_addr_t; =20 -/// Trait to be implemented by DMA capable bus devices. +/// DMA parameters passed to [`Setup::configure`]. /// -/// The [`dma::Device`](Device) trait should be implemented by bus specifi= c device representations, -/// where the underlying bus is DMA capable, such as: -#[cfg_attr(CONFIG_PCI, doc =3D "* [`pci::Device`](kernel::pci::Device)")] -/// * [`platform::Device`](::kernel::platform::Device) -pub trait Device<'a>: AsRef>> { - /// Set up the device's DMA streaming addressing capabilities. +/// `Some(value)` sets a parameter and `None` keeps its current value. The= current value is whatever +/// the bus set up or a previously bound driver left behind, so it is not = necessarily the bus +/// default. There is intentionally no `Default` implementation, so driver= s have to decide on every +/// parameter, including ones added later. +/// +/// # Examples +/// +/// ``` +/// # use core::num::NonZeroU32; +/// use kernel::dma::{self, Coherent, DmaMask}; +/// +/// # fn test(setup: dma::Setup<'_>) -> Result { +/// let dma =3D setup.configure(dma::Params { +/// streaming_mask: Some(DmaMask::new::<64>()), +/// coherent_mask: Some(DmaMask::new::<64>()), +/// max_seg_size: Some(NonZeroU32::MAX), +/// })?; +/// +/// let _buf =3D Coherent::::zeroed(dma, GFP_KERNEL)?; +/// # Ok::<(), Error>(()) } +/// ``` +pub struct Params { + /// Address mask for streaming DMA mappings. + pub streaming_mask: Option, + /// Address mask for coherent DMA allocations. + pub coherent_mask: Option, + /// Maximum length in bytes of a DMA segment supported by the device. /// - /// This method is usually called once from `probe()` as soon as the d= evice capabilities are - /// known. + /// Use `Some(NonZeroU32::MAX)` if the device has no segment size limi= t. + pub max_seg_size: Option, +} + +/// Token for configuring a device's DMA parameters. +/// +/// The bus passes it to the driver's `probe()` callback. The driver can a= ccess the device, e.g. to +/// read its capabilities, before calling [`Setup::configure`], which cons= umes the token. Drivers +/// that don't use DMA can drop it. +/// +/// # Invariants +/// +/// - The bus has initialized the device's DMA parameters. +/// - There is only one `Setup` per driver binding, and no [`Handle`] has = been created for it yet. +/// - No DMA allocation or mapping for this device can run concurrently wi= th +/// [`Setup::configure`], and nothing else changes the DMA parameters wh= ile the device is bound. +pub struct Setup<'bound> { + dev: &'bound device::Device, +} + +impl<'bound> Setup<'bound> { + /// Creates the setup token passed to a driver's probe callback. /// /// # Safety /// - /// This method must not be called concurrently with any DMA allocatio= n or mapping primitives, - /// such as [`Coherent::zeroed`]. - unsafe fn dma_set_mask(&self, mask: DmaMask) -> Result { - // SAFETY: - // - By the type invariant of `device::Device`, `self.as_ref().as_= raw()` is valid. - // - The safety requirement of this function guarantees that there= are no concurrent calls - // to DMA allocation and mapping primitives using this mask. - to_result(unsafe { bindings::dma_set_mask(self.as_ref().as_raw(), = mask.value()) }) + /// The caller must ensure the invariants of [`Self`], including uniqu= eness of the token. + pub(crate) unsafe fn new(dev: &'bound device::Device) -> Self { + Self { dev } } =20 - /// Set up the device's DMA coherent addressing capabilities. - /// - /// This method is usually called once from `probe()` as soon as the d= evice capabilities are - /// known. - /// - /// # Safety + /// Applies `params` and returns a [`Handle`] for DMA allocations and = mappings. /// - /// This method must not be called concurrently with any DMA allocatio= n or mapping primitives, - /// such as [`Coherent::zeroed`]. - unsafe fn dma_set_coherent_mask(&self, mask: DmaMask) -> Result { - // SAFETY: - // - By the type invariant of `device::Device`, `self.as_ref().as_= raw()` is valid. - // - The safety requirement of this function guarantees that there= are no concurrent calls - // to DMA allocation and mapping primitives using this mask. - to_result(unsafe { bindings::dma_set_coherent_mask(self.as_ref().a= s_raw(), mask.value()) }) + /// If a setter fails, its error is returned and parameters applied be= fore it are not restored. + pub fn configure(self, params: Params) -> Result> { + let dev =3D self.dev.as_raw(); + + if let Some(mask) =3D params.streaming_mask { + // SAFETY: `dev` is valid. The `Setup` invariants exclude conc= urrent DMA operations + // and other parameter setters, and consuming the token preven= ts reconfiguration. + to_result(unsafe { bindings::dma_set_mask(dev, mask.value()) }= )?; + } + if let Some(mask) =3D params.coherent_mask { + // SAFETY: `dev` is valid. The `Setup` invariants exclude conc= urrent DMA operations + // and other parameter setters, and consuming the token preven= ts reconfiguration. + to_result(unsafe { bindings::dma_set_coherent_mask(dev, mask.v= alue()) })?; + } + if let Some(size) =3D params.max_seg_size { + // SAFETY: `dev` is valid and its DMA parameters are initializ= ed. The `Setup` + // invariants exclude concurrent DMA operations and other para= meter setters, + // and consuming the token prevents reconfiguration. + unsafe { bindings::dma_set_max_seg_size(dev, size.get()) }; + } + + // INVARIANT: All requested setters succeeded. The `Setup` invaria= nts prevent further + // changes while the device is bound to the driver. + Ok(Handle { dev: self.dev }) + } +} + +/// Handle for DMA allocations and mappings on a configured device. +/// +/// Returned by [`Setup::configure`]. It can be copied freely, but cannot = change the DMA parameters. +/// +/// # Invariants +/// +/// The requested DMA parameters have been applied and do not change durin= g `'bound`. +#[derive(Clone, Copy)] +pub struct Handle<'bound> { + dev: &'bound device::Device, +} + +impl<'bound> Handle<'bound> { + /// Returns the device associated with this DMA handle. + pub fn device(self) -> &'bound device::Device { + self.dev } =20 - /// Set up the device's DMA addressing capabilities. - /// - /// This is a combination of [`Device::dma_set_mask`] and [`Device::dm= a_set_coherent_mask`]. - /// - /// This method is usually called once from `probe()` as soon as the d= evice capabilities are - /// known. - /// - /// # Safety - /// - /// This method must not be called concurrently with any DMA allocatio= n or mapping primitives, - /// such as [`Coherent::zeroed`]. - unsafe fn dma_set_mask_and_coherent(&self, mask: DmaMask) -> Result { - // SAFETY: - // - By the type invariant of `device::Device`, `self.as_ref().as_= raw()` is valid. - // - The safety requirement of this function guarantees that there= are no concurrent calls - // to DMA allocation and mapping primitives using this mask. - to_result(unsafe { - bindings::dma_set_mask_and_coherent(self.as_ref().as_raw(), ma= sk.value()) - }) + pub(crate) fn as_raw(self) -> *mut bindings::device { + self.dev.as_raw() } =20 - /// Set the maximum size of a single DMA segment the device may reques= t. + /// Creates a handle for `dev` without calling [`Setup::configure`]. /// - /// This method is usually called once from `probe()` as soon as the d= evice capabilities are - /// known. - /// - /// # Safety - /// - /// This method must not be called concurrently with any DMA allocatio= n or mapping primitives, - /// such as [`Coherent::zeroed`]. - unsafe fn dma_set_max_seg_size(&self, size: u32) { - // SAFETY: - // - By the type invariant of `device::Device`, `self.as_ref().as_= raw()` is valid. - // - The safety requirement of this function guarantees that there= are no concurrent calls - // to DMA allocation and mapping primitives using this parameter. - unsafe { bindings::dma_set_max_seg_size(self.as_ref().as_raw(), si= ze) } + /// For tests only. + #[cfg(CONFIG_KUNIT =3D "y")] + #[allow(dead_code)] // Only used by tests of other, optional abstracti= ons. + pub(crate) fn new_for_test(dev: &'bound device::Device) -> Self= { + Self { dev } } } =20 @@ -217,10 +258,9 @@ pub const fn value(&self) -> u64 { /// # Examples /// /// ``` -/// # use kernel::device::{Bound, Device}; /// use kernel::dma::{attrs::*, Coherent}; /// -/// # fn test(dev: &Device) -> Result { +/// # fn test(dev: kernel::dma::Handle<'_>) -> Result { /// let attribs =3D DMA_ATTR_FORCE_CONTIGUOUS | DMA_ATTR_NO_WARN; /// let c: Coherent<'_, [u64]> =3D /// Coherent::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, attribs)?; @@ -380,16 +420,12 @@ fn from(direction: DataDirection) -> Self { /// `CoherentBox`: /// /// ``` -/// # use kernel::device::{ -/// # Bound, -/// # Device, -/// # }; /// use kernel::dma::{attrs::*, /// Coherent, /// CoherentBox, /// }; /// -/// # fn test(dev: &Device) -> Result { +/// # fn test(dev: kernel::dma::Handle<'_>) -> Result { /// let mut dmem: CoherentBox<'_, u64> =3D CoherentBox::zeroed(dev, GFP_KE= RNEL)?; /// *dmem =3D 42; /// let dmem: Coherent<'_, u64> =3D dmem.into(); @@ -400,16 +436,12 @@ fn from(direction: DataDirection) -> Self { /// /// /// ``` -/// # use kernel::device::{ -/// # Bound, -/// # Device, -/// # }; /// use kernel::dma::{attrs::*, /// Coherent, /// CoherentBox, /// }; /// -/// # fn test(dev: &Device) -> Result { +/// # fn test(dev: kernel::dma::Handle<'_>) -> Result { /// let mut dmem: CoherentBox<'_, [u64]> =3D CoherentBox::zeroed_slice(dev= , 4, GFP_KERNEL)?; /// dmem.fill(42); /// let dmem: Coherent<'_, [u64]> =3D dmem.into(); @@ -421,7 +453,7 @@ impl<'a, T: AsBytes + FromBytes> CoherentBox<'a, [T]> { /// [`CoherentBox`] variant of [`Coherent::zeroed_slice_with_attrs`]. #[inline] pub fn zeroed_slice_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, count: usize, gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, @@ -432,7 +464,7 @@ pub fn zeroed_slice_with_attrs( /// Same as [CoherentBox::zeroed_slice_with_attrs], but with `dma::Att= rs(0)`. #[inline] pub fn zeroed_slice( - dev: &'a device::Device, + dev: Handle<'a>, count: usize, gfp_flags: kernel::alloc::Flags, ) -> Result { @@ -472,13 +504,12 @@ pub fn init_at(&mut self, i: usize, init: impl Ini= t) -> Result /// ``` /// use core::ops::Deref; /// - /// # use kernel::device::{Bound, Device}; /// use kernel::dma::{ /// attrs::*, /// CoherentBox /// }; /// - /// # fn test(dev: &Device) -> Result { + /// # fn test(dev: kernel::dma::Handle<'_>) -> Result { /// let data =3D [0u8, 1u8, 2u8, 3u8]; /// let c: CoherentBox<'_, [u8]> =3D /// CoherentBox::from_slice_with_attrs(dev, &data, GFP_KERNEL, DMA= _ATTR_NO_WARN)?; @@ -487,7 +518,7 @@ pub fn init_at(&mut self, i: usize, init: impl Init<= T, E>) -> Result /// # Ok::<(), Error>(()) } /// ``` pub fn from_slice_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, data: &[T], gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, @@ -511,11 +542,7 @@ pub fn from_slice_with_attrs( /// Performs the same functionality as [`CoherentBox::from_slice_with_= attrs`], except the /// `dma_attrs` is 0 by default. #[inline] - pub fn from_slice( - dev: &'a device::Device, - data: &[T], - gfp_flags: kernel::alloc::Flags, - ) -> Result + pub fn from_slice(dev: Handle<'a>, data: &[T], gfp_flags: kernel::allo= c::Flags) -> Result where T: Copy, { @@ -527,7 +554,7 @@ impl<'a, T: AsBytes + FromBytes> CoherentBox<'a, T> { /// Same as [`CoherentBox::zeroed_slice_with_attrs`], but for a single= element. #[inline] pub fn zeroed_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, ) -> Result { @@ -536,7 +563,7 @@ pub fn zeroed_with_attrs( =20 /// Same as [`CoherentBox::zeroed_slice`], but for a single element. #[inline] - pub fn zeroed(dev: &'a device::Device, gfp_flags: kernel::alloc= ::Flags) -> Result { + pub fn zeroed(dev: Handle<'a>, gfp_flags: kernel::alloc::Flags) -> Res= ult { Self::zeroed_with_attrs(dev, gfp_flags, Attrs(0)) } } @@ -595,7 +622,7 @@ fn from(value: CoherentBox<'a, T>) -> Self { // constructors `unsafe` to prevent this is considered too restrictive for= the common case; this // soundness hole is accepted for now. pub struct Coherent<'a, T: KnownSize + ?Sized> { - dev: &'a device::Device, + dev: Handle<'a>, dma_addr: DmaAddress, cpu_addr: NonNull, dma_attrs: Attrs, @@ -660,7 +687,7 @@ pub unsafe fn as_mut(&self) -> &mut T { impl<'a, T: AsBytes + FromBytes> Coherent<'a, T> { /// Allocates a region of `T` of coherent memory. fn alloc_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, ) -> Result { @@ -672,7 +699,7 @@ fn alloc_with_attrs( } =20 let mut dma_addr =3D 0; - // SAFETY: Device pointer is guaranteed as valid by the type invar= iant on `Device`. + // SAFETY: Device pointer is guaranteed as valid by the type invar= iant on `device::Device`. let addr =3D unsafe { bindings::dma_alloc_attrs( dev.as_raw(), @@ -686,7 +713,7 @@ fn alloc_with_attrs( // INVARIANT: // - We just successfully allocated a coherent region which is ade= quately sized for `T`, // hence the cpu address is valid. - // - `dev` is a valid reference to a bound device that outlives th= is allocation. + // - `dev` is a configured DMA handle for a device that outlives t= his allocation. Ok(Self { dev, dma_addr, @@ -700,23 +727,19 @@ fn alloc_with_attrs( /// # Examples /// /// ``` - /// # use kernel::device::{ - /// # Bound, - /// # Device, - /// # }; /// use kernel::dma::{ /// attrs::*, /// Coherent, /// }; /// - /// # fn test(dev: &Device) -> Result { + /// # fn test(dev: kernel::dma::Handle<'_>) -> Result { /// let c: Coherent<'_, [u64; 4]> =3D /// Coherent::zeroed_with_attrs(dev, GFP_KERNEL, DMA_ATTR_NO_WARN)= ?; /// # Ok::<(), Error>(()) } /// ``` #[inline] pub fn zeroed_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, ) -> Result { @@ -726,14 +749,14 @@ pub fn zeroed_with_attrs( /// Performs the same functionality as [`Coherent::zeroed_with_attrs`]= , except the /// `dma_attrs` is 0 by default. #[inline] - pub fn zeroed(dev: &'a device::Device, gfp_flags: kernel::alloc= ::Flags) -> Result { + pub fn zeroed(dev: Handle<'a>, gfp_flags: kernel::alloc::Flags) -> Res= ult { Self::zeroed_with_attrs(dev, gfp_flags, Attrs(0)) } =20 /// Same as [`Coherent::zeroed_with_attrs`], but instead of a zero-ini= tialization the memory is /// initialized with `init`. pub fn init_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, init: impl Init, @@ -758,7 +781,7 @@ pub fn init_with_attrs( /// with `init`. #[inline] pub fn init( - dev: &'a device::Device, + dev: Handle<'a>, gfp_flags: kernel::alloc::Flags, init: impl Init, ) -> Result @@ -770,7 +793,7 @@ pub fn init( =20 /// Allocates a region of `[T; len]` of coherent memory. fn alloc_slice_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, len: usize, gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, @@ -789,7 +812,7 @@ fn alloc_slice_with_attrs( =20 let size =3D core::mem::size_of::().checked_mul(len).ok_or(ENOM= EM)?; let mut dma_addr =3D 0; - // SAFETY: Device pointer is guaranteed as valid by the type invar= iant on `Device`. + // SAFETY: Device pointer is guaranteed as valid by the type invar= iant on `device::Device`. let addr =3D unsafe { bindings::dma_alloc_attrs( dev.as_raw(), @@ -803,7 +826,7 @@ fn alloc_slice_with_attrs( // INVARIANT: // - We just successfully allocated a coherent region which is ade= quately sized for // `[T; len]`, hence the cpu address is valid. - // - `dev` is a valid reference to a bound device that outlives th= is allocation. + // - `dev` is a configured DMA handle for a device that outlives t= his allocation. Ok(Coherent { dev, dma_addr, @@ -820,23 +843,19 @@ fn alloc_slice_with_attrs( /// # Examples /// /// ``` - /// # use kernel::device::{ - /// # Bound, - /// # Device, - /// # }; /// use kernel::dma::{ /// attrs::*, /// Coherent, /// }; /// - /// # fn test(dev: &Device) -> Result { + /// # fn test(dev: kernel::dma::Handle<'_>) -> Result { /// let c: Coherent<'_, [u64]> =3D /// Coherent::zeroed_slice_with_attrs(dev, 4, GFP_KERNEL, DMA_ATTR= _NO_WARN)?; /// # Ok::<(), Error>(()) } /// ``` #[inline] pub fn zeroed_slice_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, len: usize, gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, @@ -848,7 +867,7 @@ pub fn zeroed_slice_with_attrs( /// `dma_attrs` is 0 by default. #[inline] pub fn zeroed_slice( - dev: &'a device::Device, + dev: Handle<'a>, len: usize, gfp_flags: kernel::alloc::Flags, ) -> Result> { @@ -861,13 +880,12 @@ pub fn zeroed_slice( /// # Examples /// /// ``` - /// # use kernel::device::{Bound, Device}; /// use kernel::dma::{ /// attrs::*, /// Coherent /// }; /// - /// # fn test(dev: &Device) -> Result { + /// # fn test(dev: kernel::dma::Handle<'_>) -> Result { /// let data =3D [0u8, 1u8, 2u8, 3u8]; /// // `c` has the same content as `data`. /// let c: Coherent<'_, [u8]> =3D @@ -877,7 +895,7 @@ pub fn zeroed_slice( /// ``` #[inline] pub fn from_slice_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, data: &[T], gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, @@ -892,7 +910,7 @@ pub fn from_slice_with_attrs( /// `dma_attrs` is 0 by default. #[inline] pub fn from_slice( - dev: &'a device::Device, + dev: Handle<'a>, data: &[T], gfp_flags: kernel::alloc::Flags, ) -> Result> @@ -991,7 +1009,7 @@ fn write_to_slice( /// - `dma_attrs` contains the attributes used for the allocation, always = including /// `DMA_ATTR_NO_KERNEL_MAPPING`. pub struct CoherentHandle<'a> { - dev: &'a device::Device, + dev: Handle<'a>, dma_addr: DmaAddress, cpu_handle: NonNull, size: usize, @@ -1006,7 +1024,7 @@ impl<'a> CoherentHandle<'a> { /// /// Returns `EINVAL` if `size` is zero, `ENOMEM` if the allocation fai= ls. pub fn alloc_with_attrs( - dev: &'a device::Device, + dev: Handle<'a>, size: usize, gfp_flags: kernel::alloc::Flags, dma_attrs: Attrs, @@ -1032,7 +1050,7 @@ pub fn alloc_with_attrs( =20 // INVARIANT: `cpu_handle` is the opaque handle from a successful = `dma_alloc_attrs` call // with `DMA_ATTR_NO_KERNEL_MAPPING`, `dma_addr` is the correspond= ing DMA address, - // and `dev` is a valid reference to a bound device that outlives = this allocation. + // and `dev` is a configured DMA handle for a device that outlives= this allocation. Ok(Self { dev, dma_addr, @@ -1044,11 +1062,7 @@ pub fn alloc_with_attrs( =20 /// Allocates `size` bytes of coherent DMA memory without creating a k= ernel virtual mapping. #[inline] - pub fn alloc( - dev: &'a device::Device, - size: usize, - gfp_flags: kernel::alloc::Flags, - ) -> Result { + pub fn alloc(dev: Handle<'a>, size: usize, gfp_flags: kernel::alloc::F= lags) -> Result { Self::alloc_with_attrs(dev, size, gfp_flags, Attrs(0)) } =20 diff --git a/rust/kernel/drm/driver.rs b/rust/kernel/drm/driver.rs index 3e16a67801a0..af9d7ee376dd 100644 --- a/rust/kernel/drm/driver.rs +++ b/rust/kernel/drm/driver.rs @@ -175,6 +175,10 @@ pub struct Registration<'a, T: Driver> { impl<'a, T: Driver> Registration<'a, T> { /// Register a new [`UnregisteredDevice`](drm::UnregisteredDevice) wit= h userspace. /// + /// If the driver's C callbacks allocate or map DMA memory, DMA must b= e configured for the + /// device before calling this, and its DMA parameters must not change= while those callbacks + /// can run. + /// /// # Safety /// /// The caller must not `mem::forget()` the returned [`Registration`] = or otherwise prevent its diff --git a/rust/kernel/drm/gem/shmem.rs b/rust/kernel/drm/gem/shmem.rs index 386b8894fe2e..f33aff1e0c95 100644 --- a/rust/kernel/drm/gem/shmem.rs +++ b/rust/kernel/drm/gem/shmem.rs @@ -11,11 +11,8 @@ =20 use crate::{ container_of, - device::{ - self, - Bound, // - }, devres::*, + dma, drm::{ driver, gem, @@ -255,13 +252,10 @@ pub fn vmap(&self) -> Result> { /// Creates (if necessary) and returns an immutable reference to a sca= tter-gather table of DMA /// pages for this object. /// - /// This will pin the object in memory. It is expected that `dev` shou= ld be a pointer to the - /// same [`device::Device`] which `self` belongs to, otherwise this fu= nction will return - /// `Err(EINVAL)`. - pub fn sg_table<'a>( - &'a self, - dev: &'a device::Device, - ) -> Result<&'a scatterlist::SGTable> { + /// This pins the object in memory. The DMA handle must belong to this= object's parent + /// device, otherwise this function returns `Err(EINVAL)`. + pub fn sg_table<'a>(&'a self, dma: dma::Handle<'a>) -> Result<&'a scat= terlist::SGTable> { + let dev =3D dma.device(); let parent =3D self.dev().as_ref(); if dev.as_raw() !=3D parent.as_ref().as_raw() { return Err(EINVAL); @@ -578,6 +572,7 @@ unsafe impl Sync for SGTableMap {} mod tests { use super::*; use crate::{ + device, drm::{ self, UnregisteredDevice, // @@ -704,14 +699,14 @@ fn vmap_io() -> Result { fn fail_sg_table_on_wrong_dev() -> Result { let (_dev, drm) =3D create_drm_dev()?; let reg =3D faux::Registration::new(c"EvilKunit", None)?; - let wrong_dev =3D reg.as_ref(); + let wrong_dma =3D dma::Handle::new_for_test(reg.as_ref().as_ref()); =20 let obj =3D Object::::new(&drm, PAGE_SIZE, ObjectConf= ig::default(), ())?; =20 - assert_eq!(obj.sg_table(wrong_dev.as_ref()).err().unwrap(), EINVAL= ); + assert_eq!(obj.sg_table(wrong_dma).err().unwrap(), EINVAL); =20 // If sgt_res was not initialized mistakenly with the wrong device= , this should still fail. - assert_eq!(obj.sg_table(wrong_dev.as_ref()).err().unwrap(), EINVAL= ); + assert_eq!(obj.sg_table(wrong_dma).err().unwrap(), EINVAL); =20 // TODO: Someday, we should test that creating an sg_table here st= ill succeeds. =20 diff --git a/rust/kernel/iommu/pgtable.rs b/rust/kernel/iommu/pgtable.rs index 5f9b42ca92c2..78acef800011 100644 --- a/rust/kernel/iommu/pgtable.rs +++ b/rust/kernel/iommu/pgtable.rs @@ -12,10 +12,7 @@ use crate::{ alloc, bindings, - device::{ - Bound, - Device, // - }, + dma, error::to_result, io::PhysAddr, prelude::*, // @@ -57,10 +54,11 @@ pub struct Config { /// /// # Invariants /// -/// The pointer references a valid io page table. +/// The pointer references a valid io page table whose device's DMA parame= ters have been +/// configured and remain unchanged for the lifetime of the page table. pub struct IoPageTable<'a, F: IoPageTableFmt> { ptr: NonNull, - _dev: PhantomData<&'a Device>, + _dma: PhantomData>, _marker: PhantomData, } =20 @@ -77,8 +75,10 @@ pub trait IoPageTableFmt: 'static { =20 impl<'a, F: IoPageTableFmt> IoPageTable<'a, F> { /// Create a new `IoPageTable`. + /// + /// Requires a configured DMA handle because non-coherent page tables = may use DMA mappings. #[inline] - pub fn new(dev: &'a Device, config: Config) -> Result> { + pub fn new(dma: dma::Handle<'a>, config: Config) -> Result> { let mut raw_cfg =3D bindings::io_pgtable_cfg { quirks: config.quirks, pgsize_bitmap: config.pgsize_bitmap, @@ -86,7 +86,7 @@ pub fn new(dev: &'a Device, config: Config) -> Res= ult> oas: config.oas, coherent_walk: config.coherent_walk, tlb: &raw const NOOP_FLUSH_OPS, - iommu_dev: dev.as_raw(), + iommu_dev: dma.as_raw(), ..Zeroable::zeroed() }; =20 @@ -94,15 +94,17 @@ pub fn new(dev: &'a Device, config: Config) -> R= esult> // * The raw_cfg pointer is valid for the duration of this call. // * The provided `FLUSH_OPS` contains valid function pointers tha= t accept a null pointer // as cookie. - // * The caller ensures that the io pgtable does not outlive the d= evice. + // * The DMA handle ensures that the device is configured and rema= ins bound for `'a`. + // The returned page table cannot outlive this lifetime. let ops =3D unsafe { bindings::alloc_io_pgtable_ops(F::FORMAT, &mut raw_cfg, core::= ptr::null_mut()) }; =20 - // INVARIANT: We successfully created a valid page table. + // INVARIANT: We successfully created a valid page table. The DMA = handle guarantees + // that its device's parameters are configured and remain unchange= d for `'a`. Ok(IoPageTable { ptr: NonNull::new(ops).ok_or(ENOMEM)?, - _dev: PhantomData, + _dma: PhantomData, _marker: PhantomData, }) } diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index fdb2934eda0d..0e50eff34f35 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -12,6 +12,7 @@ RawDeviceId, RawDeviceIdIndex, // }, + dma, driver, error::{ from_result, @@ -128,7 +129,11 @@ extern "C" fn probe_callback( let info =3D unsafe { id.info_unchecked_opt::() }; =20 from_result(|| { - let data =3D T::probe(pdev, InitTokens { _p: PhantomData }, in= fo); + // SAFETY: The bus initializes DMA parameters before probing. = This is the only + // setup token issued for this binding, and the driver cannot = use the Rust DMA + // allocation or mapping APIs until it consumes the token to c= onfigure DMA. + let dma =3D unsafe { dma::Setup::new(pdev.as_ref()) }; + let data =3D T::probe(pdev, InitTokens { dma }, info); =20 pdev.as_ref().set_drvdata(data)?; Ok(0) @@ -264,7 +269,8 @@ macro_rules! pci_device_table { /// Initialization tokens passed to a PCI driver's [`Driver::probe`] callb= ack. #[non_exhaustive] pub struct InitTokens<'bound> { - _p: PhantomData<&'bound ()>, + /// Token for configuring DMA, see [`dma::Setup`]. + pub dma: dma::Setup<'bound>, } =20 /// The PCI driver trait. @@ -322,6 +328,8 @@ pub trait Driver { /// /// Called when a new pci device is added or discovered. Implementers = should /// attempt to initialize the device here. + /// + /// Drivers that use DMA must configure it through `tokens.dma` first. fn probe<'bound>( dev: &'bound Device>, tokens: InitTokens<'bound>, @@ -515,8 +523,6 @@ unsafe impl device::AsBusDe= vice for Device kernel::impl_device_context_deref!(unsafe { Device }); kernel::impl_device_context_into_aref!(Device); =20 -impl<'a> crate::dma::Device<'a> for Device> {} - // SAFETY: Instances of `Device` are always reference-counted. unsafe impl crate::sync::aref::AlwaysRefCounted for Device { #[inline] diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index a7b33e229a30..d22c291739ee 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -12,6 +12,7 @@ self, Bound, // }, + dma, driver, error::{ from_result, @@ -104,7 +105,11 @@ extern "C" fn probe_callback(pdev: *mut bindings::plat= form_device) -> kernel::ff let info =3D unsafe { ::id_info(pdev.as_r= ef()) }; =20 from_result(|| { - let data =3D T::probe(pdev, InitTokens { _p: PhantomData }, in= fo); + // SAFETY: The bus initializes DMA parameters before probing. = This is the only + // setup token issued for this binding, and the driver cannot = use the Rust DMA + // allocation or mapping APIs until it consumes the token to c= onfigure DMA. + let dma =3D unsafe { dma::Setup::new(pdev.as_ref()) }; + let data =3D T::probe(pdev, InitTokens { dma }, info); =20 pdev.as_ref().set_drvdata(data)?; Ok(0) @@ -162,7 +167,8 @@ macro_rules! module_platform_driver { /// Initialization tokens passed to a platform driver's [`Driver::probe`] = callback. #[non_exhaustive] pub struct InitTokens<'bound> { - _p: PhantomData<&'bound ()>, + /// Token for configuring DMA, see [`dma::Setup`]. + pub dma: dma::Setup<'bound>, } =20 /// The platform driver trait. @@ -234,6 +240,8 @@ pub trait Driver { /// /// Called when a new platform device is added or discovered. /// Implementers should attempt to initialize the device here. + /// + /// Drivers that use DMA must configure it through `tokens.dma` first. fn probe<'bound>( dev: &'bound Device>, tokens: InitTokens<'bound>, @@ -539,8 +547,6 @@ pub fn optional_irq_by_name(&self, name: &CStr) -> Resu= lt> { kernel::impl_device_context_deref!(unsafe { Device }); kernel::impl_device_context_into_aref!(Device); =20 -impl<'a> crate::dma::Device<'a> for Device> {} - // SAFETY: Instances of `Device` are always reference-counted. unsafe impl crate::sync::aref::AlwaysRefCounted for Device { fn inc_ref(&self) { diff --git a/rust/kernel/scatterlist.rs b/rust/kernel/scatterlist.rs index 3a5250f85000..bd54a2e04cb9 100644 --- a/rust/kernel/scatterlist.rs +++ b/rust/kernel/scatterlist.rs @@ -333,12 +333,13 @@ impl

Owned

where for<'a> P: page::AsPageIter =3D VmallocPageIter<'a>> + 'stati= c, { - fn new( - dev: &Device, + fn new<'a>( + dma: dma::Handle<'a>, mut pages: P, dir: dma::DataDirection, flags: alloc::Flags, - ) -> Result + '_> { + ) -> Result + 'a> { + let dev =3D dma.device(); let page_iter =3D pages.page_iter(); let size =3D page_iter.size(); =20 @@ -406,7 +407,7 @@ impl

SGTable> /// /// # Parameters /// - /// * `dev`: The [`Device`] that will be performing the DMA. + /// * `dma`: A handle for the device whose DMA parameters have been co= nfigured. /// * `pages`: The entity providing the backing pages. It must impleme= nt [`page::AsPageIter`]. /// The ownership of this entity is moved into the new [`SGTable`]. /// * `dir`: The [`dma::DataDirection`] of the DMA transfer. @@ -416,13 +417,12 @@ impl

SGTable> /// /// ``` /// use kernel::{ - /// device::{Bound, Device}, /// dma, page, /// prelude::*, /// scatterlist::{SGTable, Owned}, /// }; /// - /// fn test(dev: &Device) -> Result { + /// fn test(dev: dma::Handle<'_>) -> Result { /// let size =3D 4 * page::PAGE_SIZE; /// let pages =3D VVec::::with_capacity(size, GFP_KERNEL)?; /// @@ -436,14 +436,14 @@ impl

SGTable> /// Ok(()) /// } /// ``` - pub fn new( - dev: &Device, + pub fn new<'a>( + dma: dma::Handle<'a>, pages: P, dir: dma::DataDirection, flags: alloc::Flags, - ) -> impl PinInit + '_ { + ) -> impl PinInit + 'a { try_pin_init!(Self { - inner <- Owned::new(dev, pages, dir, flags)? + inner <- Owned::new(dma, pages, dir, flags)? }) } } diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs index 25ce01f2d224..9d93524204b2 100644 --- a/samples/rust/rust_dma.rs +++ b/samples/rust/rust_dma.rs @@ -4,15 +4,17 @@ //! //! To make this driver probe, QEMU must be run with `-device pci-testdev`. =20 +use core::num::NonZeroU32; + use kernel::{ device::{ Bound, Core, // }, dma::{ + self, Coherent, DataDirection, - Device, DmaMask, // }, io::{ @@ -27,6 +29,7 @@ Owned, SGTable, // }, // + sizes::SizeConstants, }; =20 struct DmaSampleDriver; @@ -76,19 +79,23 @@ impl pci::Driver for DmaSampleDriver { =20 fn probe<'bound>( pdev: &'bound pci::Device>, - _tokens: pci::InitTokens<'bound>, + tokens: pci::InitTokens<'bound>, _info: Option<&'bound Self::IdInfo>, ) -> impl PinInit, Error> + 'bound { + let pci::InitTokens { dma: setup, .. } =3D tokens; pin_init::pin_init_scope(move || { dev_info!(pdev, "Probe DMA test driver.\n"); =20 let mask =3D DmaMask::new::<64>(); =20 - // SAFETY: There are no concurrent calls to DMA allocation and= mapping primitives. - unsafe { pdev.dma_set_mask_and_coherent(mask)? }; + let dma =3D setup.configure(dma::Params { + streaming_mask: Some(mask), + coherent_mask: Some(mask), + max_seg_size: Some(const { NonZeroU32::new(u32::SZ_64K).un= wrap() }), + })?; =20 let ca: Coherent<'_, [MyStruct]> =3D - Coherent::zeroed_slice(pdev.as_ref(), TEST_VALUES.len(), G= FP_KERNEL)?; + Coherent::zeroed_slice(dma, TEST_VALUES.len(), GFP_KERNEL)= ?; =20 for (i, value) in TEST_VALUES.into_iter().enumerate() { io_project!(ca, [panic: i]).copy_write(MyStruct::new(value= .0, value.1)); @@ -97,7 +104,7 @@ fn probe<'bound>( let size =3D 4 * page::PAGE_SIZE; let pages =3D VVec::with_capacity(size, GFP_KERNEL)?; =20 - let sgt =3D SGTable::new(pdev.as_ref(), pages, DataDirection::= ToDevice, GFP_KERNEL); + let sgt =3D SGTable::new(dma, pages, DataDirection::ToDevice, = GFP_KERNEL); =20 Ok(try_pin_init!(Self::Data { pdev, --=20 2.51.2