From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.217.44 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796179848; b=KmjkVRGhWvzUBVKa9SkF/oQGAO4tm/I5aZ00Hr4s/mRc3UFXXaM18aMTZ6JDMA1tvMTq s1YyKCxJ5QJV/KgDsNowQD3pQ0qjY0VnfwCyeAwbue9fJF6XztkISLhU+zOcGr/8C3NVx LhscykBE0AATxIFIfTwmtTjbblHTESBCArJADmgTQnwfHPBLqF5yWmPRxt7rJRPFbhRM7 eVodT29vVcDZ/u4RdJY970Vu2X/Yo7Ou1unVP1Mv7x0uqH60Sdq5OgbVLpPDJ2Ecz0V/R km2lsMkV96kYhLRW5wb5FqV6ZUTjPivzmx0yT6FKsXvCKnth9uA5kUhwb//CrdUI2qA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796179848; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Gm-Gg:X-Received:Received: From:To:Cc:Subject:Date:Message-ID:X-Mailer:In-Reply-To:References: MIME-Version:Content-Type:Content-Transfer-Encoding; bh=xDeuVX1gZv3V8mfUiHcNMx4DSHFlUTjiSTUEclxyhBo=; b=qwDoGx1AfLYCVo2/6oBM/6fmkORVcu0skrIUOEUeZVCrYghBcH8FLX2M/iB/9yn8ev4h onTnGKzT3jvsRj564ZOGz3x8rToyDucmdHHiapg6/CwjdfKVEBpBbT1oManlqlwPxEtmG ot4lunGAoM86c9UvN6Uf4aSh7M0oHvqjz5dFjew1vo2sfr/03ntrXub8aDb8yNZnyH8WW PjX6yPHbHgxKsnP8Zy/Bt+Frpim+8P/osHVA51womkdgy5wA77nLbfApB5Cv/ukVy0wUj AQAACG/6mRmxjDtIvnkvD0xdxhkHvTHzYW6RJoRaFzp7SXTZfrhGyAiB/G7d1tm42cw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=NtB1lF9B; arc=none smtp.remote-ip=209.85.217.44 Received: from mail-vs1-f44.google.com (mail-vs1-f44.google.com [209.85.217.44]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E2E69606A322 for ; Wed, 2 Dec 2026 02:50:46 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E2E69606A322 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=NtB1lF9B Received: by mail-vs1-f44.google.com with SMTP id ada2fe7eead31-7d2ca055399so3839324137.3 for ; Tue, 01 Dec 2026 18:50:46 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796179846; x=1796784646; darn=vger.kernel.org; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to:content-type; bh=xDeuVX1gZv3V8mfUiHcNMx4DSHFlUTjiSTUEclxyhBo=; b=NtB1lF9B4gz0ofe+vnmqR0hfGA4DPEwB/BOdAaf10z0+vfzKsaSfp4oP2ITDJiXNZq 84YCeEbvyGPx6aKj3e5a2m26txO6ZA8h2jAGZJrWS1Jue53c9ki0BOKx6owpvdjJ+pNf vCQes8ZwjAU7RNWi76VjfoaitkabDKW7pNk57PMmdX76x+aceQZBwWm/PvHBGAo3lzPL eQr73vdZXDWPgOblFQksbsROioDMY8FwR1pBha5XdrCZGTvGoL3qsyD6fYI5FSnVwbvX YubLvQSw53CySw1IEEXzSNGEzS4ewesZnhGbx32layWpAwDH7oZuT4ahqRoNrnKowE5v c+Qw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796179846; x=1796784646; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-gg :x-gm-message-state:from:to:cc:subject:date:message-id:reply-to :content-type; bh=xDeuVX1gZv3V8mfUiHcNMx4DSHFlUTjiSTUEclxyhBo=; b=O3W5zD0pDgZonL9YFPZyhbArSrYrZhGHr4o02ppoPvuksQzkChxpr5ruMmIH5YrO7W 3Jgw29Q77zNi8+ZiZESgqMbBIS1m0usj2U1SBENGP1C0dfbwoNpbgcMf6hhStJ+b+Wi5 wSOq4l/0YQMU4LXrYwTvlmMAsUBU+m9171PFaRQrUFYtVH0XUcd1PPlW1l1FD1uqPrbK y6+8XkcOUg6kDPlM/ti6YAMz6MK9Yu1MDztsDujpiyhp+cZUidrHG/6L+odiTZTKEPLu 7hiJq8XK6bGMzLim+9ImoODW41P3cHv1zdgJ06BzojJ6VRbi8Fz5GojDboAVyMpNWmXe TsEw== X-Forwarded-Encrypted: i=1; AL+hErEAiVMLsHsTCuBqljPuXA4q/NFWA5KA+TmZeKRfKcRRZA0PB1sP5JFa4/C0FTQbbxvvkwnBsWWOL5Y3hEA=@vger.kernel.org X-Gm-Message-State: APuU4Z9JZc3IC0vPrmOfUN35grMXIo7wGUEdWaXWYugT8YASABHWSAPL Laz+D4q+cUQD+5NUphu6d7oSDf8/DY8HLGutnx5Xl2Bgln96Cz+Xn3cflFH+IpB4 X-Gm-Gg: AZFdTZf//BHpvlsY2JK0p4Mj//dFpRmaVBupOs8zeY8IDYBmbIdw4l9uZaaL2i1GV8P UnpG/6n0oDC/L/+7x37lrHYP6/lbNQu1yzOYRbIPR9XWJwvu7KpSJn/Z1NWhP27r97QbqA0Xulh T1F8T60hWHgColPJeBQAlT4QPNLqYxhpWsal6RKVCKyhNGE3TZw0pBr18ZTnRq6hJw/l+k04gmO f+krFxKehxK72Kl88tRht+j061Tdtf71XW3zkqk6BewN39BbNaV/cqpneNg3EEBY06RDVL/fEKH gEpOuieBAqh11U+dIXtj555xT0B5AjAVvg1TnfsOAYD3w+KxPtuFUC3MOByOxYWP/IY2PvxsQHC EB3Wor7yQSKJsCpH8fB3C70KRre25sAEdqYljRb7iczXgPohUgH8pkvrLF56tdZitmiHf4IFLF+ rPi+FbST5KQ3C+aRPBYQr9ZtFdp2AsG05JE2Q9kuIcXRvPp4Y8vyNPAtI9M++ZFQS0gjiRKBq3T ydiW1glq38bOG0Bo2mtT9+FHQB5YP9y0CNOD3aZF/HygjG4AwwK30AIwTYqcae5cXBQPIb93V5O UrqwbGxRpdDhTlaJbxVnyualD5Li5n/+RWeag89vElpbkUm+l+9dEl/nHLnj8AlzxkRinRd5OvV +d8b2wwE/yJvWb7kpp1DRSj4ZELSN3OnKL5XD3Cg4cbPj X-Received: by 2002:a05:6102:84c8:b0:7a7:19aa:f0d4 with SMTP id ada2fe7eead31-7d7396a6e4dmr17372745137.33.1796179845359; Tue, 01 Dec 2026 18:50:45 -0800 (PST) Received: from fedora.tail32f8bf.ts.net (201-189-218-205.fo.baf.movistar.cl. [201.189.218.205]) by smtp.gmail.com with ESMTPSA id ada2fe7eead31-7d6e81cee49sm41444266137.8.2026.12.01.18.50.42 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Tue, 01 Dec 2026 18:50:45 -0800 (PST) From: =?UTF-8?q?Agust=C3=ADn=20Pereira?= To: Danilo Krummrich , Alexandre Courbot Cc: David Airlie , Simona Vetter , Miguel Ojeda , nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, =?UTF-8?q?Agust=C3=ADn=20Pereira?= Subject: [RFC PATCH v2] gpu: nova-core: gsp: add RM alloc/control/free RPCs and client/device API Date: Tue, 1 Dec 2026 21:50:28 -0500 Message-ID: <20261202025028.43497-2-agustin.pereira.ro@gmail.com> X-Mailer: git-send-email 2.56.1 In-Reply-To: <20261202025028.43497-1-agustin.pereira.ro@gmail.com> References: <20261202025028.43497-1-agustin.pereira.ro@gmail.com> 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-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nova-core currently supports only fixed boot and teardown GSP RPCs (`SetSystemInfo`, `SetRegistry`, `GetGspStaticInfo`, and `UnloadingGuestDriver`). Higher-level GPU subsystems such as FIFO, GR, and CE engines require allocating, controlling, and freeing GSP-RM objects arranged in a client -> device -> subdevice hierarchy. Implement the GSP-RM object RPC layer and RAII handle abstractions: - Add the r570.144 firmware definitions (`rpc_gsp_rm_alloc_v03_00`, `rpc_gsp_rm_control_v03_00`, `rpc_free_v03_00`, `NV0000_ALLOC_PARAMETERS`, `NV0080_ALLOC_PARAMETERS`, and `NV2080_ALLOC_PARAMETERS`) and wrap them in firmware-independent types in `gsp::fw::commands` with compile-time layout assertions and `RmStatus` (`NV_STATUS` to kernel `Error`) conversion. - Validate the outer `rpc_result` field in `CmdqInner::receive_msg()` and avoid returning early before advancing `cpu_read_ptr` on malformed replies. - Expose `MsgFunction::GspRmAlloc` and implement typed `CommandToGsp` / `MessageFromGsp` commands (`RmAlloc`, `RmControl`, and `RmFree`) in `gsp::commands`. - Add `gsp::rm` providing `RmHandle`, an `IdPool`-backed `RmClientIdAllocator` for handle allocation and recycling, and RAII handles (`RmClient`, `RmDevice`, `RmSubdevice`, and `RmObject`) whose Rust lifetime hierarchy enforces child-before-parent `FREE` teardown. - Wire `Gsp::alloc_client()` into a `CONFIG_NOVA_CORE_SELFTESTS` probe self-test and add KUnit unit tests (`nova_core_gsp_rm`) covering handle encoding, allocator growth/recycling, `RmStatus` mapping, and RPC wire serialization/reply decoding. Testing: - Compiled `drivers/gpu/nova-core.o` and `drivers/gpu/nova-drm.o` with `LLVM=1 W=1 CLIPPY=1` (`CONFIG_RUST=y`, `CONFIG_NOVA_CORE=m`, `CONFIG_DRM_NOVA=m`) under both (`CONFIG_NOVA_CORE_SELFTESTS=y`, `CONFIG_KUNIT=y`) and (`CONFIG_NOVA_CORE_SELFTESTS=n`, `CONFIG_KUNIT=n`) with zero warnings. - Verified formatting with `rustfmt --check` and patch style with `scripts/checkpatch.pl`. - Tested on NVIDIA GeForce RTX 4070 Laptop GPU (AD106M, Ada, rev a.1) with r570.144 TLV firmware on 7.4.0-rc5: `GSP RM` client/device/ subdevice alloc/control/free self-test passed on initial probe and re-bind with zero warnings. This change was drafted with the assistance of an AI coding assistant. Signed-off-by: Agustín Pereira --- Changes in v2: - Validate the outer rpc_result field in CmdqInner::receive_msg() and avoid returning early before advancing cpu_read_ptr on malformed replies (reported by Sashiko AI review). - Stop draining sbuffer after read_exact() in RmControlReply::read() so unexpectedly large control payloads trigger the unprocessed-data warning (reported by Sashiko AI review). - Kept the 16-byte GspRmFree reply payload in RmFreeReply: testing on real AD106M hardware (r570.144) confirmed GSP-RM echoes rpc_free_v03_00 in the FREE reply (using Message = () produced "GSP message Free has unprocessed data" warnings). Both outer rpc_result and params.status are now checked. - Tested on real hardware: NVIDIA GeForce RTX 4070 Laptop GPU (AD106M, Ada, rev a.1, r570.144 TLV firmware) on 7.4.0-rc5; GSP RM client/device/subdevice alloc/control/free self-test passed on initial probe and re-bind with zero warnings. drivers/gpu/nova-core/gpu.rs | 4 + drivers/gpu/nova-core/gsp.rs | 17 +- drivers/gpu/nova-core/gsp/cmdq.rs | 42 +- drivers/gpu/nova-core/gsp/commands.rs | 186 +++++ drivers/gpu/nova-core/gsp/fw.rs | 7 + drivers/gpu/nova-core/gsp/fw/commands.rs | 229 +++++++ .../gpu/nova-core/gsp/fw/r570_144/bindings.rs | 73 ++ drivers/gpu/nova-core/gsp/rm.rs | 640 ++++++++++++++++++ drivers/gpu/nova-core/sbuffer.rs | 1 - 9 files changed, 1183 insertions(+), 16 deletions(-) create mode 100644 drivers/gpu/nova-core/gsp/rm.rs diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs index 4e59072cab50..10a3d2ae4d6f 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -629,6 +629,10 @@ pub(crate) fn run_selftests(self: Pin<&mut Self>, pdev: &pci::Device { /// Command queue. #[pin] pub(crate) cmdq: Cmdq<'gsp>, + /// RM client handle allocator. + #[pin] + rm_clients: RmClientIdAllocator, /// RM arguments. rmargs: Coherent<'gsp, GspArgumentsPadded>, } @@ -177,6 +185,7 @@ pub(crate) fn new( // kgspSetupLibosInitArgs_IMPL (creates pLibosInitArgs[] array) Ok(try_pin_init!(Self { cmdq <- Cmdq::new(dev, bar), + rm_clients <- RmClientIdAllocator::new(), rmargs: Coherent::init(dev, GFP_KERNEL, GspArgumentsPadded::new(&cmdq))?, libos: { let mut libos = CoherentBox::zeroed_slice( @@ -223,6 +232,12 @@ pub(crate) fn new( pub(crate) fn get_static_info(&self) -> Result { self.cmdq.send_command(commands::GetGspStaticInfo) } + + /// Allocates a new GSP-RM root client (`NV01_ROOT`). + #[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))] + pub(crate) fn alloc_client(&self) -> Result> { + RmClient::new(&self.cmdq, &self.rm_clients) + } } /// Opaque bundle required to unload the GSP. Created by [`Gsp::boot`], consumed by [`Gsp::unload`]. diff --git a/drivers/gpu/nova-core/gsp/cmdq.rs b/drivers/gpu/nova-core/gsp/cmdq.rs index 1b2f346a237f..910a52dcd984 100644 --- a/drivers/gpu/nova-core/gsp/cmdq.rs +++ b/drivers/gpu/nova-core/gsp/cmdq.rs @@ -867,20 +867,34 @@ fn receive_msg(&mut self, timeout: Delta) -> Result // An early return here would leave the read pointer on this message. let result = if matches!(function, Ok(f) if f == M::FUNCTION) { - let (cmd, contents_1) = M::Message::from_bytes_prefix(message.contents.0).ok_or(EIO)?; - let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]); - - M::read(cmd, &mut sbuffer) - .map_err(|e| e.into()) - .inspect(|_| { - if !sbuffer.is_empty() { - dev_warn!( - &self.dev, - "GSP message {:?} has unprocessed data\n", - M::FUNCTION - ); - } - }) + let rpc_result = message.header.rpc_result(); + if let Err(err) = rpc_result.into_result() { + dev_err!( + &self.dev, + "GSP RPC {:?} failed with rpc_result={:#x}\n", + M::FUNCTION, + rpc_result.raw(), + ); + Err(err) + } else if let Some((cmd, contents_1)) = + M::Message::from_bytes_prefix(message.contents.0) + { + let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]); + + M::read(cmd, &mut sbuffer) + .map_err(|e| e.into()) + .inspect(|_| { + if !sbuffer.is_empty() { + dev_warn!( + &self.dev, + "GSP message {:?} has unprocessed data\n", + M::FUNCTION + ); + } + }) + } else { + Err(EIO) + } } else { self.log_event(function, seq); diff --git a/drivers/gpu/nova-core/gsp/commands.rs b/drivers/gpu/nova-core/gsp/commands.rs index cdbb13674f08..b52413735504 100644 --- a/drivers/gpu/nova-core/gsp/commands.rs +++ b/drivers/gpu/nova-core/gsp/commands.rs @@ -5,6 +5,7 @@ array, convert::Infallible, ffi::FromBytesUntilNulError, + marker::PhantomData, ops::Range, str::Utf8Error, // }; @@ -329,3 +330,188 @@ fn read( Ok(UnloadingGuestDriverReply) } } + +/// The `GSP_RM_ALLOC` command for allocating an RM object with typed parameters `P`. +pub(super) struct RmAlloc<'a, P: AsBytes + FromBytes> { + client: u32, + parent: u32, + object: u32, + class: u32, + params: &'a P, +} + +impl<'a, P: AsBytes + FromBytes> RmAlloc<'a, P> { + /// Creates a new `GSP_RM_ALLOC` command. + pub(super) fn new(client: u32, parent: u32, object: u32, class: u32, params: &'a P) -> Self { + Self { + client, + parent, + object, + class, + params, + } + } +} + +impl CommandToGsp for RmAlloc<'_, P> { + const FUNCTION: MsgFunction = MsgFunction::GspRmAlloc; + type Command = fw::commands::GspRmAllocHeader; + type Reply = RmAllocReply; + type InitError = Error; + + fn init(&self) -> impl Init { + fw::commands::GspRmAllocHeader::init( + self.client, + self.parent, + self.object, + self.class, + size_of::

(), + ) + } + + fn variable_payload_len(&self) -> usize { + size_of::

() + } + + fn init_variable_payload( + &self, + dst: &mut SBufferIter>, + ) -> Result { + dst.write_all(self.params.as_bytes()) + } +} + +/// The reply from the GSP to [`RmAlloc`]. +pub(super) struct RmAllocReply; + +impl MessageFromGsp for RmAllocReply { + const FUNCTION: MsgFunction = MsgFunction::GspRmAlloc; + type InitError = Error; + type Message = fw::commands::GspRmAllocHeader; + + fn read( + msg: &Self::Message, + sbuffer: &mut SBufferIter>, + ) -> Result { + msg.status().into_result()?; + + // GSP echoes the allocation parameters in the reply; drain them so the + // command queue does not warn about unprocessed bytes. + while sbuffer.next().is_some() {} + + Ok(RmAllocReply) + } +} + +/// The `GSP_RM_CONTROL` command for invoking an RM control call with typed parameters `P`. +pub(super) struct RmControl<'a, P: AsBytes + FromBytes + Zeroable> { + client: u32, + object: u32, + cmd: u32, + params: &'a P, + _reply: PhantomData

, +} + +impl<'a, P: AsBytes + FromBytes + Zeroable> RmControl<'a, P> { + /// Creates a new `GSP_RM_CONTROL` command. + pub(super) fn new(client: u32, object: u32, cmd: u32, params: &'a P) -> Self { + Self { + client, + object, + cmd, + params, + _reply: PhantomData, + } + } +} + +impl CommandToGsp for RmControl<'_, P> { + const FUNCTION: MsgFunction = MsgFunction::GspRmControl; + type Command = fw::commands::GspRmControlHeader; + type Reply = RmControlReply

; + type InitError = Error; + + fn init(&self) -> impl Init { + fw::commands::GspRmControlHeader::init(self.client, self.object, self.cmd, size_of::

()) + } + + fn variable_payload_len(&self) -> usize { + size_of::

() + } + + fn init_variable_payload( + &self, + dst: &mut SBufferIter>, + ) -> Result { + dst.write_all(self.params.as_bytes()) + } +} + +/// The reply from the GSP to [`RmControl`], carrying the updated parameter structure `P`. +pub(super) struct RmControlReply { + /// Output parameters returned by GSP-RM. + pub(super) params: P, +} + +impl MessageFromGsp for RmControlReply

{ + const FUNCTION: MsgFunction = MsgFunction::GspRmControl; + type InitError = Error; + type Message = fw::commands::GspRmControlHeader; + + fn read( + msg: &Self::Message, + sbuffer: &mut SBufferIter>, + ) -> Result { + msg.status().into_result()?; + + let mut params = P::zeroed(); + sbuffer.read_exact(params.as_bytes_mut())?; + + Ok(Self { params }) + } +} + +/// The `FREE` command for releasing an RM object handle on the GSP. +pub(super) struct RmFree { + root: u32, + object: u32, +} + +impl RmFree { + /// Creates a new `FREE` command for `object` belonging to client `root`. + pub(super) fn new(root: u32, object: u32) -> Self { + Self { root, object } + } +} + +impl CommandToGsp for RmFree { + const FUNCTION: MsgFunction = MsgFunction::Free; + type Command = fw::commands::GspRmFree; + type Reply = RmFreeReply; + type InitError = Infallible; + + fn init(&self) -> impl Init { + fw::commands::GspRmFree::new(self.root, self.object) + } +} + +/// The reply from the GSP to [`RmFree`]. +/// +/// The GSP reports RPC-level completion in the outer header's `rpc_result` +/// (checked in `CmdqInner::receive_msg`) and echoes back the 16-byte +/// `rpc_free_v03_00` payload with `params.status`. +pub(super) struct RmFreeReply; + +impl MessageFromGsp for RmFreeReply { + const FUNCTION: MsgFunction = MsgFunction::Free; + type InitError = Error; + type Message = fw::commands::GspRmFree; + + fn read( + msg: &Self::Message, + _sbuffer: &mut SBufferIter>, + ) -> Result { + msg.status().into_result()?; + Ok(RmFreeReply) + } +} diff --git a/drivers/gpu/nova-core/gsp/fw.rs b/drivers/gpu/nova-core/gsp/fw.rs index 918a7ae809eb..c41e4a2c4c7f 100644 --- a/drivers/gpu/nova-core/gsp/fw.rs +++ b/drivers/gpu/nova-core/gsp/fw.rs @@ -285,6 +285,7 @@ pub(crate) enum MsgFunction { GetGspStaticInfo = bindings::NV_VGPU_MSG_FUNCTION_GET_GSP_STATIC_INFO, GetStaticInfo = bindings::NV_VGPU_MSG_FUNCTION_GET_STATIC_INFO, GspInitPostObjGpu = bindings::NV_VGPU_MSG_FUNCTION_GSP_INIT_POST_OBJGPU, + GspRmAlloc = bindings::NV_VGPU_MSG_FUNCTION_GSP_RM_ALLOC, GspRmControl = bindings::NV_VGPU_MSG_FUNCTION_GSP_RM_CONTROL, GspSetSystemInfo = bindings::NV_VGPU_MSG_FUNCTION_GSP_SET_SYSTEM_INFO, Log = bindings::NV_VGPU_MSG_FUNCTION_LOG, @@ -328,6 +329,7 @@ fn try_from(value: u32) -> Result { bindings::NV_VGPU_MSG_FUNCTION_GSP_INIT_POST_OBJGPU => { Ok(MsgFunction::GspInitPostObjGpu) } + bindings::NV_VGPU_MSG_FUNCTION_GSP_RM_ALLOC => Ok(MsgFunction::GspRmAlloc), bindings::NV_VGPU_MSG_FUNCTION_GSP_RM_CONTROL => Ok(MsgFunction::GspRmControl), bindings::NV_VGPU_MSG_FUNCTION_GSP_SET_SYSTEM_INFO => Ok(MsgFunction::GspSetSystemInfo), bindings::NV_VGPU_MSG_FUNCTION_LOG => Ok(MsgFunction::Log), @@ -879,6 +881,11 @@ pub(crate) fn function(&self) -> Result { pub(crate) fn element_count(&self) -> u32 { self.inner.elemCount } + + /// Returns the `NV_STATUS` completion code from the outer RPC header. + pub(crate) fn rpc_result(&self) -> commands::RmStatus { + commands::RmStatus::from_raw(self.inner.rpc.rpc_result) + } } // SAFETY: Padding is explicit and does not contain uninitialized data. diff --git a/drivers/gpu/nova-core/gsp/fw/commands.rs b/drivers/gpu/nova-core/gsp/fw/commands.rs index 567c56fbbfe3..6ed091c3edc2 100644 --- a/drivers/gpu/nova-core/gsp/fw/commands.rs +++ b/drivers/gpu/nova-core/gsp/fw/commands.rs @@ -245,3 +245,232 @@ unsafe impl AsBytes for UnloadingGuestDriver {} // SAFETY: This struct only contains integer types for which all bit patterns // are valid. unsafe impl FromBytes for UnloadingGuestDriver {} + +/// RM class identifier for allocating a root client (`NV01_ROOT`). +pub(crate) const RM_CLASS_ROOT: u32 = bindings::NV01_ROOT; + +/// RM class identifier for allocating a device (`NV01_DEVICE_0`). +pub(crate) const RM_CLASS_DEVICE: u32 = bindings::NV01_DEVICE_0; + +/// RM class identifier for allocating a subdevice (`NV20_SUBDEVICE_0`). +pub(crate) const RM_CLASS_SUBDEVICE: u32 = bindings::NV20_SUBDEVICE_0; + +/// Status code returned by GSP-RM object RPCs (`NV_STATUS`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(transparent)] +pub(crate) struct RmStatus(u32); + +impl RmStatus { + /// Creates an [`RmStatus`] from a raw firmware status code. + pub(crate) const fn from_raw(status: u32) -> Self { + Self(status) + } + + /// Returns the raw `NV_STATUS` code. + pub(crate) const fn raw(self) -> u32 { + self.0 + } + + /// Converts this `NV_STATUS` into a kernel [`Result`]. + pub(crate) fn into_result(self) -> Result { + match self.0 { + bindings::NV_OK => Ok(()), + bindings::NV_ERR_NOT_READY | bindings::NV_ERR_TIMEOUT_RETRY => Err(EBUSY), + bindings::NV_ERR_NO_MEMORY => Err(ENOMEM), + _ => Err(EINVAL), + } + } +} + +/// Header of the `GSP_RM_ALLOC` RPC command and reply. +#[repr(transparent)] +pub(crate) struct GspRmAllocHeader { + inner: bindings::rpc_gsp_rm_alloc_v03_00, +} + +static_assert!(size_of::() == 32); + +impl GspRmAllocHeader { + /// Returns an in-place initializer for a `GSP_RM_ALLOC` header. + pub(crate) fn init( + client: u32, + parent: u32, + object: u32, + class: u32, + params_size: usize, + ) -> impl Init { + let init_inner = try_init!(bindings::rpc_gsp_rm_alloc_v03_00 { + hClient: client, + hParent: parent, + hObject: object, + hClass: class, + status: 0, + paramsSize: u32::try_from(params_size).map_err(|_| EOVERFLOW)?, + flags: 0, + reserved: [0; 4], + ..Zeroable::init_zeroed() + }); + + try_init!(Self { + inner <- init_inner, + }) + } + + /// Returns the `NV_STATUS` reported by the GSP in the reply header. + pub(crate) fn status(&self) -> RmStatus { + RmStatus::from_raw(self.inner.status) + } +} + +// SAFETY: All fields are plain integers with no implicit padding. +unsafe impl AsBytes for GspRmAllocHeader {} + +// SAFETY: All bit patterns are valid for the integer fields in this header. +unsafe impl FromBytes for GspRmAllocHeader {} + +/// Header of the `GSP_RM_CONTROL` RPC command and reply. +#[repr(transparent)] +pub(crate) struct GspRmControlHeader { + inner: bindings::rpc_gsp_rm_control_v03_00, +} + +static_assert!(size_of::() == 24); + +impl GspRmControlHeader { + /// Returns an in-place initializer for a `GSP_RM_CONTROL` header. + pub(crate) fn init( + client: u32, + object: u32, + cmd: u32, + params_size: usize, + ) -> impl Init { + let init_inner = try_init!(bindings::rpc_gsp_rm_control_v03_00 { + hClient: client, + hObject: object, + cmd, + status: 0, + paramsSize: u32::try_from(params_size).map_err(|_| EOVERFLOW)?, + flags: 0, + ..Zeroable::init_zeroed() + }); + + try_init!(Self { + inner <- init_inner, + }) + } + + /// Returns the `NV_STATUS` reported by the GSP in the reply header. + pub(crate) fn status(&self) -> RmStatus { + RmStatus::from_raw(self.inner.status) + } +} + +// SAFETY: All fields are plain integers with no implicit padding. +unsafe impl AsBytes for GspRmControlHeader {} + +// SAFETY: All bit patterns are valid for the integer fields in this header. +unsafe impl FromBytes for GspRmControlHeader {} + +/// Payload of the `FREE` RM RPC command and reply. +#[repr(transparent)] +#[derive(Clone, Copy, Debug, Zeroable)] +pub(crate) struct GspRmFree(bindings::rpc_free_v03_00); + +static_assert!(size_of::() == 16); + +impl GspRmFree { + /// Creates a new `FREE` payload for freeing `object` under `root`. + pub(crate) fn new(root: u32, object: u32) -> Self { + Self(bindings::rpc_free_v03_00 { + params: bindings::NVOS00_PARAMETERS_v03_00 { + hRoot: root, + hObjectParent: 0, + hObjectOld: object, + status: 0, + }, + }) + } + + /// Returns the `NV_STATUS` reported by the GSP in the reply payload. + pub(crate) fn status(&self) -> RmStatus { + RmStatus::from_raw(self.0.params.status) + } +} + +// SAFETY: All fields are plain integers with no padding. +unsafe impl AsBytes for GspRmFree {} + +// SAFETY: All bit patterns are valid for the integer fields in this struct. +unsafe impl FromBytes for GspRmFree {} + +/// Allocation parameters for an `NV01_ROOT` RM client (`NV0000_ALLOC_PARAMETERS`). +#[repr(transparent)] +#[derive(Clone, Copy, Debug, Zeroable)] +pub(crate) struct RmClientAllocParams(bindings::NV0000_ALLOC_PARAMETERS); + +static_assert!(size_of::() == 120); + +impl RmClientAllocParams { + /// Creates allocation parameters for a kernel RM client with `client_handle`. + pub(crate) fn new(client_handle: u32) -> Self { + Self(bindings::NV0000_ALLOC_PARAMETERS { + hClient: client_handle, + processID: u32::MAX, + processName: [0; 100], + __bindgen_padding_0: [0; 4], + pOsPidInfo: 0, + }) + } +} + +// SAFETY: Padding is explicit and initialized to zero. +unsafe impl AsBytes for RmClientAllocParams {} + +// SAFETY: All bit patterns are valid for the integer and byte array fields. +unsafe impl FromBytes for RmClientAllocParams {} + +/// Allocation parameters for an `NV01_DEVICE_0` RM device (`NV0080_ALLOC_PARAMETERS`). +#[repr(transparent)] +#[derive(Clone, Copy, Debug, Zeroable)] +pub(crate) struct RmDeviceAllocParams(bindings::NV0080_ALLOC_PARAMETERS); + +static_assert!(size_of::() == 56); + +impl RmDeviceAllocParams { + /// Creates allocation parameters for device `device_id` under `client_share`. + pub(crate) fn new(client_share: u32, device_id: u32) -> Self { + Self(bindings::NV0080_ALLOC_PARAMETERS { + deviceId: device_id, + hClientShare: client_share, + ..Zeroable::zeroed() + }) + } +} + +// SAFETY: Padding is explicit and initialized to zero. +unsafe impl AsBytes for RmDeviceAllocParams {} + +// SAFETY: All bit patterns are valid for the integer fields. +unsafe impl FromBytes for RmDeviceAllocParams {} + +/// Allocation parameters for an `NV20_SUBDEVICE_0` RM subdevice (`NV2080_ALLOC_PARAMETERS`). +#[repr(transparent)] +#[derive(Clone, Copy, Debug, Zeroable)] +pub(crate) struct RmSubdeviceAllocParams(bindings::NV2080_ALLOC_PARAMETERS); + +static_assert!(size_of::() == 4); + +impl RmSubdeviceAllocParams { + /// Creates allocation parameters for subdevice `subdevice_id`. + pub(crate) fn new(subdevice_id: u32) -> Self { + Self(bindings::NV2080_ALLOC_PARAMETERS { + subDeviceId: subdevice_id, + }) + } +} + +// SAFETY: This struct contains a single `u32` with no padding. +unsafe impl AsBytes for RmSubdeviceAllocParams {} + +// SAFETY: All bit patterns are valid for `u32`. +unsafe impl FromBytes for RmSubdeviceAllocParams {} diff --git a/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs b/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs index afe3e007f088..0bf4e6a0a406 100644 --- a/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs +++ b/drivers/gpu/nova-core/gsp/fw/r570_144/bindings.rs @@ -33,6 +33,13 @@ fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { pub const NV2080_CTRL_GPU_SET_POWER_STATE_GPU_LEVEL_0: u32 = 0; pub const NV2080_CTRL_GPU_SET_POWER_STATE_GPU_LEVEL_3: u32 = 3; pub const NV2080_CTRL_GPU_SET_POWER_STATE_GPU_LEVEL_7: u32 = 7; +pub const NV01_ROOT: u32 = 0x0; +pub const NV01_DEVICE_0: u32 = 0x80; +pub const NV20_SUBDEVICE_0: u32 = 0x2080; +pub const NV_OK: u32 = 0x0; +pub const NV_ERR_NO_MEMORY: u32 = 0x51; +pub const NV_ERR_NOT_READY: u32 = 0x55; +pub const NV_ERR_TIMEOUT_RETRY: u32 = 0x66; pub const NV_VGPU_MSG_SIGNATURE_VALID: u32 = 1129337430; pub const GSP_FW_HEAP_PARAM_OS_SIZE_LIBOS2: u32 = 0; pub const GSP_FW_HEAP_PARAM_OS_SIZE_LIBOS3_BAREMETAL: u32 = 23068672; @@ -982,6 +989,72 @@ pub struct rpc_run_cpu_sequencer_v17_00 { pub regSaveArea: [u32_; 8usize], pub commandBuffer: __IncompleteArrayField, } +#[repr(C)] +#[derive(Debug, Default, MaybeZeroable)] +pub struct rpc_gsp_rm_alloc_v03_00 { + pub hClient: u32_, + pub hParent: u32_, + pub hObject: u32_, + pub hClass: u32_, + pub status: u32_, + pub paramsSize: u32_, + pub flags: u32_, + pub reserved: [u8_; 4usize], + pub params: __IncompleteArrayField, +} +#[repr(C)] +#[derive(Debug, Default, MaybeZeroable)] +pub struct rpc_gsp_rm_control_v03_00 { + pub hClient: u32_, + pub hObject: u32_, + pub cmd: u32_, + pub status: u32_, + pub paramsSize: u32_, + pub flags: u32_, + pub params: __IncompleteArrayField, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, MaybeZeroable)] +pub struct NVOS00_PARAMETERS_v03_00 { + pub hRoot: u32_, + pub hObjectParent: u32_, + pub hObjectOld: u32_, + pub status: u32_, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, MaybeZeroable)] +pub struct rpc_free_v03_00 { + pub params: NVOS00_PARAMETERS_v03_00, +} +#[repr(C)] +#[derive(Debug, Copy, Clone, MaybeZeroable)] +pub struct NV0000_ALLOC_PARAMETERS { + pub hClient: u32_, + pub processID: u32_, + pub processName: [u8_; 100usize], + pub __bindgen_padding_0: [u8; 4usize], + pub pOsPidInfo: u64_, +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, MaybeZeroable)] +pub struct NV0080_ALLOC_PARAMETERS { + pub deviceId: u32_, + pub hClientShare: u32_, + pub hTargetClient: u32_, + pub hTargetDevice: u32_, + pub flags: u32_, + pub __bindgen_padding_0: [u8; 4usize], + pub vaSpaceSize: u64_, + pub vaStartInternal: u64_, + pub vaLimitInternal: u64_, + pub vaMode: u32_, + pub __bindgen_padding_1: [u8; 4usize], +} +#[repr(C)] +#[derive(Debug, Default, Copy, Clone, MaybeZeroable)] +pub struct NV2080_ALLOC_PARAMETERS { + pub subDeviceId: u32_, +} pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_WRITE: GSP_SEQ_BUF_OPCODE = 0; pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_MODIFY: GSP_SEQ_BUF_OPCODE = 1; pub const GSP_SEQ_BUF_OPCODE_GSP_SEQ_BUF_OPCODE_REG_POLL: GSP_SEQ_BUF_OPCODE = 2; diff --git a/drivers/gpu/nova-core/gsp/rm.rs b/drivers/gpu/nova-core/gsp/rm.rs new file mode 100644 index 000000000000..29bddfb699de --- /dev/null +++ b/drivers/gpu/nova-core/gsp/rm.rs @@ -0,0 +1,640 @@ +// SPDX-License-Identifier: GPL-2.0-only + +//! GSP-RM object allocation, control, and client/device lifecycle management. +//! +//! GSP-RM organizes GPU resources in a handle hierarchy rooted at an RM client +//! (`NV01_ROOT`), with child devices (`NV01_DEVICE_0`), subdevices +//! (`NV20_SUBDEVICE_0`), and engine or memory objects underneath. +//! +//! This module models that hierarchy using Rust lifetimes and RAII: +//! - [`RmClient`] borrows the [`Cmdq`] and [`RmClientIdAllocator`] from [`Gsp`]. +//! - [`RmDevice`] borrows its parent [`RmClient`]. +//! - [`RmSubdevice`] borrows its parent [`RmDevice`]. +//! - [`RmObject`] represents an arbitrary child object borrowing its [`RmClient`]. +//! +//! Dropping any handle automatically issues a `FREE` RPC to GSP-RM, and the +//! borrow hierarchy guarantees child objects are always freed before their +//! parent device and client. + +use kernel::{ + id_pool::IdPool, + new_mutex, + prelude::*, + sync::Mutex, + transmute::{ + AsBytes, + FromBytes, // + }, // +}; + +use crate::gsp::{ + cmdq::Cmdq, + commands::{ + RmAlloc, + RmControl, + RmFree, // + }, + fw::commands::{ + RmClientAllocParams, + RmDeviceAllocParams, + RmSubdeviceAllocParams, + RM_CLASS_DEVICE, + RM_CLASS_ROOT, + RM_CLASS_SUBDEVICE, // + }, // +}; + +/// Base prefix for RM client handles allocated by nova-core. +const RM_CLIENT_HANDLE_BASE: u32 = 0xc1d0_0000; + +/// Mask covering the 16-bit client ID encoded in an RM client handle. +const RM_CLIENT_ID_MASK: u32 = 0x0000_ffff; + +/// Maximum number of concurrent RM client handles supported per GPU. +const RM_CLIENT_MAX_IDS: usize = (RM_CLIENT_ID_MASK as usize) + 1; + +/// Fixed RM handle used for the primary device object under a client. +const RM_DEVICE_HANDLE: RmHandle = RmHandle::new(0xde1d_0000); + +/// Fixed RM handle used for the primary subdevice object under a device. +const RM_SUBDEVICE_HANDLE: RmHandle = RmHandle::new(0x5d1d_0000); + +/// Strongly typed GSP-RM object handle (`NvHandle`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[repr(transparent)] +pub(crate) struct RmHandle(u32); + +impl RmHandle { + /// Creates an [`RmHandle`] from a raw 32-bit RM handle value. + pub(crate) const fn new(raw: u32) -> Self { + Self(raw) + } + + /// Returns the raw 32-bit RM handle value. + pub(crate) const fn raw(self) -> u32 { + self.0 + } + + /// Encodes a client ID in `0..=0xffff` into a client [`RmHandle`]. + /// + /// # Errors + /// + /// Returns `EINVAL` if `id` exceeds [`RM_CLIENT_ID_MASK`]. + pub(crate) const fn client_from_id(id: u32) -> Result { + if id > RM_CLIENT_ID_MASK { + return Err(EINVAL); + } + + Ok(Self(RM_CLIENT_HANDLE_BASE | id)) + } + + /// Extracts the client ID from a client [`RmHandle`], or [`None`] if the + /// handle does not carry the client prefix. + pub(crate) const fn client_id(self) -> Option { + if (self.0 & !RM_CLIENT_ID_MASK) == RM_CLIENT_HANDLE_BASE { + Some((self.0 & RM_CLIENT_ID_MASK) as usize) + } else { + None + } + } +} + +/// Thread-safe allocator and recycler for RM client IDs backed by [`IdPool`]. +#[pin_data] +pub(crate) struct RmClientIdAllocator { + #[pin] + pool: Mutex, +} + +impl RmClientIdAllocator { + /// Creates an in-place initializer for an [`RmClientIdAllocator`]. + pub(crate) fn new() -> impl PinInit { + pin_init!(Self { + pool <- new_mutex!(IdPool::new(), "nova_rm_client_ids"), + }) + } + + /// Allocates an unused client ID and returns its encoded [`RmHandle`]. + /// + /// Grows the underlying [`IdPool`] outside the mutex if all currently + /// tracked slots are occupied. + /// + /// # Errors + /// + /// - `ENOSPC` if all [`RM_CLIENT_MAX_IDS`] client handles are in use. + /// - `ENOMEM` if growing the backing bitmap fails. + pub(crate) fn alloc(&self) -> Result { + loop { + let mut pool = self.pool.lock(); + if let Some(unused) = pool.find_unused_id(0) { + if unused.as_usize() >= RM_CLIENT_MAX_IDS { + return Err(ENOSPC); + } + let id = unused.as_u32(); + let _ = unused.acquire(); + return RmHandle::client_from_id(id); + } + + if pool.capacity() >= RM_CLIENT_MAX_IDS { + return Err(ENOSPC); + } + + let grow_req = pool.grow_request().ok_or(ENOSPC)?; + drop(pool); + + let resizer = grow_req.realloc(GFP_KERNEL)?; + self.pool.lock().grow(resizer); + } + } + + /// Releases a previously allocated client [`RmHandle`] back to the pool. + pub(crate) fn free(&self, handle: RmHandle) { + if let Some(id) = handle.client_id() { + self.pool.lock().release_id(id); + } + } +} + +/// RAII handle to a GSP-RM root client (`NV01_ROOT`). +/// +/// Dropping this handle sends a `FREE` RPC to GSP-RM and recycles its client ID. +pub(crate) struct RmClient<'a, 'gsp> { + cmdq: &'a Cmdq<'gsp>, + allocator: &'a RmClientIdAllocator, + handle: RmHandle, +} + +impl<'a, 'gsp> RmClient<'a, 'gsp> { + /// Allocates a new GSP-RM root client (`NV01_ROOT`). + pub(super) fn new(cmdq: &'a Cmdq<'gsp>, allocator: &'a RmClientIdAllocator) -> Result { + let handle = allocator.alloc()?; + let params = RmClientAllocParams::new(handle.raw()); + + if let Err(e) = cmdq.send_command(RmAlloc::new( + handle.raw(), + handle.raw(), + handle.raw(), + RM_CLASS_ROOT, + ¶ms, + )) { + allocator.free(handle); + return Err(e); + } + + Ok(Self { + cmdq, + allocator, + handle, + }) + } + + /// Returns this client's [`RmHandle`]. + pub(crate) const fn handle(&self) -> RmHandle { + self.handle + } + + /// Allocates an RM device (`NV01_DEVICE_0`) belonging to this client. + #[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))] + pub(crate) fn alloc_device(&self, device_id: u32) -> Result> { + RmDevice::new(self, device_id) + } + + /// Allocates an arbitrary RM child object under `parent` using typed parameters `P`. + #[expect(dead_code)] + pub(crate) fn alloc_object( + &self, + parent: RmHandle, + object: RmHandle, + class: u32, + params: &P, + ) -> Result> { + self.cmdq.send_command(RmAlloc::new( + self.handle.raw(), + parent.raw(), + object.raw(), + class, + params, + ))?; + + Ok(RmObject { + cmdq: self.cmdq, + client_handle: self.handle, + handle: object, + }) + } + + /// Invokes a `GSP_RM_CONTROL` call targeting `object` under this client. + #[expect(dead_code)] + pub(crate) fn control( + &self, + object: RmHandle, + cmd: u32, + params: &P, + ) -> Result

{ + let reply = + self.cmdq + .send_command(RmControl::new(self.handle.raw(), object.raw(), cmd, params))?; + + Ok(reply.params) + } +} + +impl Drop for RmClient<'_, '_> { + fn drop(&mut self) { + let _ = self + .cmdq + .send_command(RmFree::new(self.handle.raw(), self.handle.raw())); + self.allocator.free(self.handle); + } +} + +/// RAII handle to a GSP-RM device (`NV01_DEVICE_0`). +/// +/// Borrows its parent [`RmClient`] so the device is always freed before its client. +#[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))] +pub(crate) struct RmDevice<'a, 'gsp> { + cmdq: &'a Cmdq<'gsp>, + client_handle: RmHandle, + handle: RmHandle, +} + +#[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))] +impl<'a, 'gsp> RmDevice<'a, 'gsp> { + /// Allocates an `NV01_DEVICE_0` object under `client`. + fn new(client: &'a RmClient<'_, 'gsp>, device_id: u32) -> Result { + let handle = RM_DEVICE_HANDLE; + let client_handle = client.handle(); + let params = RmDeviceAllocParams::new(client_handle.raw(), device_id); + + client.cmdq.send_command(RmAlloc::new( + client_handle.raw(), + client_handle.raw(), + handle.raw(), + RM_CLASS_DEVICE, + ¶ms, + ))?; + + Ok(Self { + cmdq: client.cmdq, + client_handle, + handle, + }) + } + + /// Returns this device's [`RmHandle`]. + pub(crate) const fn handle(&self) -> RmHandle { + self.handle + } + + /// Allocates an RM subdevice (`NV20_SUBDEVICE_0`) belonging to this device. + pub(crate) fn alloc_subdevice(&self, subdevice_id: u32) -> Result> { + RmSubdevice::new(self, subdevice_id) + } + + /// Invokes a `GSP_RM_CONTROL` call targeting this device. + #[expect(dead_code)] + pub(crate) fn control( + &self, + cmd: u32, + params: &P, + ) -> Result

{ + let reply = self.cmdq.send_command(RmControl::new( + self.client_handle.raw(), + self.handle.raw(), + cmd, + params, + ))?; + + Ok(reply.params) + } +} + +impl Drop for RmDevice<'_, '_> { + fn drop(&mut self) { + let _ = self + .cmdq + .send_command(RmFree::new(self.client_handle.raw(), self.handle.raw())); + } +} + +/// RAII handle to a GSP-RM subdevice (`NV20_SUBDEVICE_0`). +/// +/// Borrows its parent [`RmDevice`] so the subdevice is always freed before its device. +#[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))] +pub(crate) struct RmSubdevice<'a, 'gsp> { + cmdq: &'a Cmdq<'gsp>, + client_handle: RmHandle, + handle: RmHandle, +} + +#[cfg_attr(not(CONFIG_NOVA_CORE_SELFTESTS), expect(dead_code))] +impl<'a, 'gsp> RmSubdevice<'a, 'gsp> { + /// Allocates an `NV20_SUBDEVICE_0` object under `device`. + fn new(device: &'a RmDevice<'_, 'gsp>, subdevice_id: u32) -> Result { + let handle = RM_SUBDEVICE_HANDLE; + let params = RmSubdeviceAllocParams::new(subdevice_id); + let client_handle = device.client_handle; + + device.cmdq.send_command(RmAlloc::new( + client_handle.raw(), + device.handle().raw(), + handle.raw(), + RM_CLASS_SUBDEVICE, + ¶ms, + ))?; + + Ok(Self { + cmdq: device.cmdq, + client_handle, + handle, + }) + } + + /// Returns this subdevice's [`RmHandle`]. + pub(crate) const fn handle(&self) -> RmHandle { + self.handle + } + + /// Invokes a `GSP_RM_CONTROL` call targeting this subdevice. + #[expect(dead_code)] + pub(crate) fn control( + &self, + cmd: u32, + params: &P, + ) -> Result

{ + let reply = self.cmdq.send_command(RmControl::new( + self.client_handle.raw(), + self.handle.raw(), + cmd, + params, + ))?; + + Ok(reply.params) + } +} + +impl Drop for RmSubdevice<'_, '_> { + fn drop(&mut self) { + let _ = self + .cmdq + .send_command(RmFree::new(self.client_handle.raw(), self.handle.raw())); + } +} + +/// RAII handle to an arbitrary child RM object allocated under an [`RmClient`]. +#[expect(dead_code)] +pub(crate) struct RmObject<'a, 'gsp> { + cmdq: &'a Cmdq<'gsp>, + client_handle: RmHandle, + handle: RmHandle, +} + +#[expect(dead_code)] +impl RmObject<'_, '_> { + /// Returns this object's [`RmHandle`]. + pub(crate) const fn handle(&self) -> RmHandle { + self.handle + } + + /// Invokes a `GSP_RM_CONTROL` call targeting this object. + pub(crate) fn control( + &self, + cmd: u32, + params: &P, + ) -> Result

{ + let reply = self.cmdq.send_command(RmControl::new( + self.client_handle.raw(), + self.handle.raw(), + cmd, + params, + ))?; + + Ok(reply.params) + } +} + +impl Drop for RmObject<'_, '_> { + fn drop(&mut self) { + let _ = self + .cmdq + .send_command(RmFree::new(self.client_handle.raw(), self.handle.raw())); + } +} + +/// Probe-time self-test verifying RM client, device, and subdevice allocation +/// and teardown against the booted GSP. +#[cfg(CONFIG_NOVA_CORE_SELFTESTS)] +pub(crate) fn run_selftest( + dev: &kernel::device::Device, + gsp: &crate::gsp::Gsp<'_>, +) -> Result { + dev_info!(dev, "GSP RM: Starting client/device self-test...\n"); + + let client = gsp.alloc_client()?; + let device = client.alloc_device(0)?; + let subdevice = device.alloc_subdevice(0)?; + + dev_info!( + dev, + "GSP RM: Allocated client={:#x}, device={:#x}, subdevice={:#x}\n", + client.handle().raw(), + device.handle().raw(), + subdevice.handle().raw() + ); + + drop(subdevice); + drop(device); + drop(client); + + dev_info!(dev, "GSP RM: Self-test PASSED\n"); + Ok(()) +} + +#[kunit_tests(nova_core_gsp_rm)] +mod tests { + use super::*; + + use crate::{ + gsp::{ + cmdq::{ + CommandToGsp, + MessageFromGsp, // + }, + commands::{ + RmAllocReply, + RmControlReply, + RmFreeReply, // + }, + fw::commands::{ + GspRmAllocHeader, + GspRmControlHeader, + GspRmFree, + RmStatus, // + }, // + }, + sbuffer::SBufferIter, // + }; + + #[repr(C)] + #[derive(Clone, Copy, Debug, PartialEq, Eq, Zeroable)] + struct TestCtrlParams { + arg: u32, + out: u32, + } + + // SAFETY: `TestCtrlParams` consists only of two `u32` fields with no padding. + unsafe impl AsBytes for TestCtrlParams {} + + // SAFETY: All bit patterns are valid for `u32` fields. + unsafe impl FromBytes for TestCtrlParams {} + + #[test] + fn handle_client_encoding_and_bounds() -> Result { + let h0 = RmHandle::client_from_id(0)?; + assert_eq!(h0.raw(), 0xc1d0_0000); + assert_eq!(h0.client_id(), Some(0)); + + let hmax = RmHandle::client_from_id(0xffff)?; + assert_eq!(hmax.raw(), 0xc1d0_ffff); + assert_eq!(hmax.client_id(), Some(0xffff)); + + assert_eq!(RmHandle::client_from_id(0x1_0000), Err(EINVAL)); + assert_eq!(RM_DEVICE_HANDLE.client_id(), None); + assert_eq!(RM_SUBDEVICE_HANDLE.client_id(), None); + + Ok(()) + } + + #[test] + fn client_id_allocator_recycles_and_grows() -> Result { + let alloc = KBox::pin_init(RmClientIdAllocator::new(), GFP_KERNEL)?; + + // Allocate beyond the initial inline IdPool capacity (64) to exercise growth. + let mut handles = KVec::with_capacity(80, GFP_KERNEL)?; + for expected in 0..80u32 { + let h = alloc.alloc()?; + assert_eq!(h, RmHandle::client_from_id(expected)?); + handles.push(h, GFP_KERNEL)?; + } + + // Release an ID in the middle and verify it is recycled first. + alloc.free(handles[17]); + let reused = alloc.alloc()?; + assert_eq!(reused, RmHandle::client_from_id(17)?); + + // Clean up all allocated handles. + for h in handles { + alloc.free(h); + } + + // Slot 0 should now be available again. + assert_eq!(alloc.alloc()?, RmHandle::client_from_id(0)?); + + Ok(()) + } + + #[test] + fn rm_status_mapping() { + assert_eq!(RmStatus::from_raw(0x0).into_result(), Ok(())); + assert_eq!(RmStatus::from_raw(0x51).into_result(), Err(ENOMEM)); + assert_eq!(RmStatus::from_raw(0x55).into_result(), Err(EBUSY)); + assert_eq!(RmStatus::from_raw(0x66).into_result(), Err(EBUSY)); + assert_eq!(RmStatus::from_raw(0xdead_beef).into_result(), Err(EINVAL)); + assert_eq!(RmStatus::from_raw(0x55).raw(), 0x55); + } + + #[test] + fn rm_alloc_and_free_serialization() -> Result { + let client = RmHandle::client_from_id(3)?; + let params = RmClientAllocParams::new(client.raw()); + let cmd = RmAlloc::new( + client.raw(), + client.raw(), + client.raw(), + RM_CLASS_ROOT, + ¶ms, + ); + + assert_eq!(cmd.variable_payload_len(), size_of::()); + let mut payload = KVec::zeroed(cmd.variable_payload_len(), GFP_KERNEL)?; + let mut sbuf = SBufferIter::new_writer([payload.as_mut_slice(), &mut []]); + cmd.init_variable_payload(&mut sbuf)?; + assert!(sbuf.is_empty()); + drop(sbuf); + assert_eq!(payload.as_slice(), params.as_bytes()); + + // Verify reply decoding drains trailing echoed parameter bytes. + let ok_hdr = KBox::init( + GspRmAllocHeader::init( + client.raw(), + client.raw(), + client.raw(), + RM_CLASS_ROOT, + size_of::(), + ), + GFP_KERNEL, + )?; + let mut reply_sbuf = SBufferIter::new_reader([payload.as_slice(), &[]]); + let _ = RmAllocReply::read(&ok_hdr, &mut reply_sbuf)?; + assert!(reply_sbuf.is_empty()); + + // Verify RmFree command size and reply payload handling. + let free_ok = GspRmFree::new(client.raw(), RM_DEVICE_HANDLE.raw()); + assert_eq!(free_ok.as_bytes().len(), 16); + let mut empty = SBufferIter::new_reader([&[][..], &[][..]]); + let _ = RmFreeReply::read(&free_ok, &mut empty)?; + + Ok(()) + } + + #[test] + fn rm_control_roundtrip_and_error() -> Result { + let client = RmHandle::client_from_id(1)?; + let req = TestCtrlParams { + arg: 0x1234_5678, + out: 0, + }; + let cmd = RmControl::new(client.raw(), RM_SUBDEVICE_HANDLE.raw(), 0x2080_0101, &req); + + assert_eq!(cmd.variable_payload_len(), size_of::()); + let mut req_buf = [0u8; size_of::()]; + let mut wbuf = SBufferIter::new_writer([&mut req_buf[..], &mut []]); + cmd.init_variable_payload(&mut wbuf)?; + drop(wbuf); + assert_eq!(&req_buf, req.as_bytes()); + + // Simulate a reply carrying updated output parameters split across slices. + let expected = TestCtrlParams { + arg: 0x1234_5678, + out: 0xcafe_babe, + }; + let hdr = KBox::init( + GspRmControlHeader::init( + client.raw(), + RM_SUBDEVICE_HANDLE.raw(), + 0x2080_0101, + size_of::(), + ), + GFP_KERNEL, + )?; + let (p1, p2) = expected.as_bytes().split_at(3); + let mut rbuf = SBufferIter::new_reader([p1, p2]); + let reply = RmControlReply::::read(&hdr, &mut rbuf)?; + assert_eq!(reply.params, expected); + assert!(rbuf.is_empty()); + + // Simulate a non-zero NV_STATUS error in reply header (`NV_ERR_NO_MEMORY`). + let mut err_hdr_bytes = [0u8; size_of::()]; + err_hdr_bytes.copy_from_slice(hdr.as_bytes()); + // `status` is the 4th `u32` field (byte offset 12) in `rpc_gsp_rm_control_v03_00`. + err_hdr_bytes[12..16].copy_from_slice(&0x51u32.to_le_bytes()); + let err_hdr = GspRmControlHeader::from_bytes(&err_hdr_bytes).ok_or(EIO)?; + let mut rbuf2 = SBufferIter::new_reader([p1, p2]); + assert!(matches!( + RmControlReply::::read(err_hdr, &mut rbuf2), + Err(ENOMEM) + )); + + Ok(()) + } +} diff --git a/drivers/gpu/nova-core/sbuffer.rs b/drivers/gpu/nova-core/sbuffer.rs index 3a41d224c77a..b8c01104c255 100644 --- a/drivers/gpu/nova-core/sbuffer.rs +++ b/drivers/gpu/nova-core/sbuffer.rs @@ -146,7 +146,6 @@ fn get_slice(&mut self, len: usize) -> Option<&'a [u8]> { /// Ideally we would implement `Read`, but it is not available in `core`. /// So mimic `std::io::Read::read_exact`. - #[expect(unused)] pub(crate) fn read_exact(&mut self, mut dst: &mut [u8]) -> Result { while !dst.is_empty() { match self.get_slice(dst.len()) { base-commit: 693c2e04e3f1d4c59af236e1211b7b8cb165a790 -- 2.56.1