gpu: nova-core: gsp: prepare the command queue for r000 dual-message types
Subsystems (5)
Alexandre Courbot
maintainerv4 cover gpu: nova-core: gsp: prepare the command queue for r000 dual-message types
The upcoming r000 firmware support [1] introduces a new type of command named GMC alongside the existing and already supported RPC command type.
Since RPC was the only command type supported so far, it was embedded into the lowest command queue level: the message header actually includes the RPC header and the code considers them as one.
This makes the r000/GMC support difficult to land without a refactor, with the result of transport layer code being duplicated between the two message types, and no clear separation between the RPC and GMC code which are mixed together in the command queue. Merging the code that way would introduce quite some technical debt.
Thus, this series prepares a proper landing ground for a new message type by extracting all the RPC layer code and moving it into its own sub-modules, making the cmdq module completely agnostic of the type of message it transports. By the end of the series, the only mention of RPC in cmdq.rs is for the rpc sub-module.
With the transport and message layers properly separated, support for GMC can be added into sibling modules of rpc, and the transport layer can be converted once when doing the switch to r000.
This moves quite a bit of code around, but most of it is moved verbatim. No significant functional change is intended.
For the r000 series, this essentially means the following:
- Its patch 7 making allocate_command generic can be dropped as the transport layer makes no assumption about the message type.
- Patches adding GMC support will do it in dedicated gmc sub-modules, following the model set by RPC. These gmc sub-modules will start as dead_code as they are being built.
- The "switch to r000" patch will essentially operate on the transport layer level, i.e. cmdq.rs.
- There should be no need for extra post-switch RPC fixing, as the transport layer code will already be shared with GMC.
Overall, this should make the r000 series much easier to review and eventually land, while not creating new technical debt.
This series is based on drm-rust-next.
[1] https://lore.kernel.org/all/[email protected]/
---
Changes in v4:
- Rebase on top of latest drm-rust-next, including the interrupt series.
- Move RPC parsing code to RpcMessage. (Eliot)
- Do not mention the command queue slots in the public documentation. (Eliot)
- Use different names for the length methods of the message and RPC headers. (Eliot)
- Fix bug where the RPC header length was used instead of the message one to compute the number of pages to advance by. (Eliot)
- Add a patch moving the message logging code to RpcMessage.
- Make the rpc module only visible from gsp. (Eliot)
- Link to v3: https://patch.msgid.link/[email protected]
Changes in v3:
- Use dedicated RpcMessage type to distinguish parsed RPC message from the transport-level GspMessage.
- Introduce traits for sending and receiving elements on the command queue (thanks Eliot!).
- Split unsafe blocks, drop unused impls, and other fixes on patch 2. (thanks Eliot!)
- Squash the two move commits into a single one.
- Link to v2: https://patch.msgid.link/[email protected]
Changes in v2:
- Fix checksum on receive incorrectly using the whole slots allocated to the message instead of its actual length. (Sashiko)
- Drop patch 1 to avoid having to validate the elemCount header member against edge cases. (Sashiko)
- Fix incorrect layer separation in receive path, where the CPU read pointer was advanced in the message layer.
- Move log_event into a method of RpcMessage.
- Make the rpc module only visible to gsp and its submodules.
- Fix doclinks pointing to old function names. (Sashiko)
- Link to v1: https://patch.msgid.link/[email protected]
---
Alexandre Courbot (10):
gpu: nova-core: gsp: cmdq: validate checksum earlier on receive
gpu: nova-core: gsp: introduce and use proper RpcMessageHeader type
gpu: nova-core: gsp: cmdq: group the RPC-specific part of send_single_command
gpu: nova-core: gsp: cmdq: split the transport part of the send path
gpu: nova-core: gsp: cmdq: split RPC parsing part of the receive path
gpu: nova-core: gsp: cmdq: move RPC message logging to RpcMessage
gpu: nova-core: gsp: cmdq: split the transport part of the receive path
gpu: nova-core: gsp: cmdq: move the RPC code into a sub-module
gpu: nova-core: gsp: move the RPC commands into a sub-module
gpu: nova-core: gsp: add rpc to RPC message send/receive methods
drivers/gpu/nova-core/api.rs | 2 +-
drivers/gpu/nova-core/gpu.rs | 2 +-
drivers/gpu/nova-core/gsp.rs | 4 +-
drivers/gpu/nova-core/gsp/boot.rs | 12 +-
drivers/gpu/nova-core/gsp/cmdq.rs | 429 +++-----------------
drivers/gpu/nova-core/gsp/cmdq/rpc.rs | 443 +++++++++++++++++++++
.../nova-core/gsp/cmdq/{ => rpc}/continuation.rs | 0
drivers/gpu/nova-core/gsp/commands.rs | 329 +--------------
drivers/gpu/nova-core/gsp/commands/rpc.rs | 333 ++++++++++++++++
drivers/gpu/nova-core/gsp/fw.rs | 123 +++---
drivers/gpu/nova-core/gsp/sequencer.rs | 4 +-
11 files changed, 913 insertions(+), 768 deletions(-)---
base-commit: 3e3404c52370595e37eb5b942df169884f38a124
change-id: 20260927-cmdq-rpc-ed5f850b207e
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
maintainerPATCH v4 1/10 gpu: nova-core: gsp: cmdq: validate checksum earlier on receive
The checksum validation error message of wait_for_msg prints the message's sequence number before validating the checksum.
But the checksum is part of the transport layer, and it not validating indicates a corruption that could very well be in the RPC message header, meaning the value of this field cannot be trusted.
Furthermore, the transport layer is not supposed to know the kind of message it transports, and it accessing the RPC header is a layering violation.
Thus, move the checksum validation before we start looking at the message header, and drop that information from the error message.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +9 -15
@@ -792,6 +792,15 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {// Extract the `GspMsgElement`. let (header, slice_1) =GspMsgElement ::from_bytes_prefix (slice_1).ok_or (EIO )?; +// Validate checksum after truncating the message to its exact length. +if Cmdq ::calculate_checksum ( +SBufferIter ::new_reader ([header.as_bytes (), slice_1, slice_2]).take (header.length ()), + ) !=0 + { +dev_err! (&self.dev,"GSP receive: bad checksum\n" ); +return Err (EIO ); + } +dev_dbg! ( &self.dev,"GSP RPC: receive: seq# {}, function={:?}, length=0x{:x}\n" ,
@@ -820,21 +829,6 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { ) }; -// Validate checksum. -if Cmdq ::calculate_checksum (SBufferIter ::new_reader ([ - header.as_bytes (), - slice_1, - slice_2, - ])) !=0 - { -dev_err! ( - &self.dev, -"GSP RPC: receive: Call {} - bad checksum\n" , - header.sequence () - ); -return Err (EIO ); - } -Ok (GspMessage { header, contents: (slice_1, slice_2),
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 01/10] gpu: nova-core: gsp: cmdq: validate checksum earlier on receive
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] gpu: nova-core: double fetch of message length allows queue desynchronization --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] gpu: nova-core: double fetch of message length allows queue desynchronization --
commit 946fd7a5c2c75e7ae4c51655010ee1c1c0977129
Author: Alexandre Courbot <[email protected]>
gpu: nova-core: gsp: cmdq: validate checksum earlier on receive
This moves the checksum validation before accessing the RPC header to avoid printing an unvalidated sequence number.
drivers/gpu/nova-core/gsp/cmdq.rs fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { · line 798
Quoted 12 lines
drivers/gpu/nova-core/gsp/cmdq.rs +4
-0@@ -792,6 +792,15 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {// Extract the `GspMsgElement`. let (header, slice_1) =GspMsgElement ::from_bytes_prefix (slice_1).ok_or (EIO )?; +// Validate checksum after truncating the message to its exact length. + if Cmdq::calculate_checksum( + SBufferIter::new_reader([header.as_bytes(), slice_1, slice_2]).take(header.length()), + ) != 0
[Severity: High]
Does this code introduce a double fetch regression? Because the GSP message queue resides in DMA-coherent shared memory, the device can concurrently modify header.length().
By using header.length() to bound the checksum calculation via take() here, but later using header.payload_length() to slice the payload:
drivers/gpu/nova-core/gsp/cmdq.rs:wait_for_msg() {
...
let payload_length = header.payload_length();
...
}
could the GSP modify the length field between these fetches, causing the slices to cover unvalidated payload data and bypassing the checksum?
Furthermore, there is a third fetch of the length later in receive_msg():
drivers/gpu/nova-core/gsp/cmdq.rs:receive_msg() {
...
self.gsp_mem.advance_cpu_read_ptr(u32::try_from(
message.header.length().div_ceil(GSP_PAGE_SIZE),
)?);...
}
Could modifying the length before this fetch cause the CPU to advance the pointer by an arbitrary amount, desynchronizing the command queue and potentially processing arbitrary data as commands?
Do follow-up patches in this series retain this same structure in other areas, such as consume_element and RpcMessage::parse?
Quoted 4 lines
drivers/gpu/nova-core/gsp/cmdq.rs +4
-0+ { +dev_err! (&self.dev,"GSP receive: bad checksum\n" ); +return Err (EIO ); + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Alexandre Courbot
maintainerPATCH v4 2/10 gpu: nova-core: gsp: introduce and use proper RpcMessageHeader type
In reply to Alexandre CourbotSo far, the GSP command queue transport and message layer code were intertwined, a design issue that goes as deep as the types themselves:
the generated bindings for GspMsgElement even include the RPC header at its end.
This makes it difficult to introduce the new GMC message type; thus this patch works around these limitations to make the RPC message header more explicit and allow it to be eventually handled by a different layer.
The RpcMessageHeader wrapping type is introduced following the same model as GspMsgElement, and can be obtained from the latter. The methods of GspMsgElement that actually query the RPC header are moved to RpcMessageHeader.
Regarding initialization, GspMsgElement leaves the RPC header zeroed, and the command queue code is now responsible for initializing it in a separate call.
The only functional change is that the RPC debug messages now display the size of the RPC payload instead of the whole message including its headers, as they are technically part of the message layer. This metric is arguably more useful as the headers have successfully been parsed by the time we can print these messages.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 50 ++++++++++------ drivers/gpu/nova-core/gsp/fw.rs | 123 ++++++++++++++++++++++---------------- 2 files changed, 106 insertions(+), 67 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +33 -17
@@ -54,6 +54,7 @@ MsgFunction, MsgqRxHeader, MsgqTxHeader, + RpcMessageHeader, GSP_MSG_QUEUE_ELEMENT_SIZE_MAX, // }, PteArray,
@@ -688,11 +689,22 @@ fn send_single_command<M>(&mut self, command: M) -> Resultlet (cmd, payload_1) =M ::Command ::from_bytes_mut_prefix (dst.contents.0 ).ok_or (EIO )?;// Fill the header and command in-place. -let msg_element =GspMsgElement ::init (self.seq, size_in_bytes,M ::FUNCTION ); -// SAFETY: `msg_header` and `cmd` are valid references, and not touched if the initializer -// fails. +let msg_element_init =GspMsgElement ::init (self.seq, size_in_bytes); +let rpc_header_init =RpcMessageHeader ::init (size_in_bytes,M ::FUNCTION ); +// SAFETY: `dst.header` is a valid reference, and is not touched if the initializer fails. +unsafe { + pin_init::raw_try_init (core::ptr::from_mut (dst.header), msg_element_init)?; + } +// SAFETY: `dst.header.rpc_header_mut()` is a valid reference, and is not touched if the +// initializer fails. +unsafe { + pin_init::raw_try_init ( + core::ptr::from_mut (dst.header.rpc_header_mut ()), + rpc_header_init, + )?; + } +// SAFETY: `cmd` is a valid reference, and is not touched if the initializer fails. unsafe { - pin_init::raw_try_init (core::ptr::from_mut (dst.header), msg_element)?; pin_init::raw_try_init (core::ptr::from_mut (cmd), command.init ())?; }
@@ -718,7 +730,7 @@ fn send_single_command<M>(&mut self, command: M) -> Result "GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n", self.seq, M::FUNCTION, - dst.header.length(), + size_in_bytes, );// All set - update the write pointer and inform the GSP of the new command.
@@ -794,23 +806,25 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {// Validate checksum after truncating the message to its exact length. if Cmdq ::calculate_checksum ( -SBufferIter ::new_reader ([header.as_bytes (), slice_1, slice_2]).take (header.length ()), +SBufferIter ::new_reader ([header.as_bytes (), slice_1, slice_2]) + .take (header.msg_length ()), ) !=0 {dev_err! (&self.dev,"GSP receive: bad checksum\n" );return Err (EIO ); } +let rpc_header = header.rpc_header (); +let payload_length = rpc_header.rpc_length (); +dev_dbg! ( &self.dev,"GSP RPC: receive: seq# {}, function={:?}, length=0x{:x}\n" , - header.sequence (), - header.function (), - header.length (), + rpc_header.sequence (), + rpc_header.function (), + payload_length, ); -let payload_length = header.payload_length (); -// Check that the driver read area is large enough for the message. if slice_1.len () + slice_2.len () < payload_length {return Err (EIO );
@@ -856,8 +870,9 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> Error: From<M::InitError>, {let message = self.wait_for_msg (timeout)?; -let function = message.header.function (); -let seq = message.header.sequence (); +let rpc_header = message.header.rpc_header (); +let function = rpc_header.function (); +let seq = rpc_header.sequence ();// An early return here would leave the read pointer on this message. let result =if matches! (function,Ok (f)if f ==M ::FUNCTION ) {
@@ -883,7 +898,7 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M>// Advance the read pointer past this message. self.gsp_mem.advance_cpu_read_ptr (u32::try_from ( - message.header.length ().div_ceil (GSP_PAGE_SIZE ), + message.header.msg_length ().div_ceil (GSP_PAGE_SIZE ), )?); result
@@ -962,12 +977,13 @@ fn drain(&mut self) -> Result {let msg = self.wait_for_msg (Delta ::ZERO )?;let pages = - u32::try_from (msg.header.length ().div_ceil (GSP_PAGE_SIZE )).map_err (|_| { + u32::try_from (msg.header.msg_length ().div_ceil (GSP_PAGE_SIZE )).map_err (|_| {dev_err! (&self.dev,"GSP drain: message length overflow\n" );EIO })?; -let function = msg.header.function (); -let seq = msg.header.sequence (); +let rpc_header = msg.header.rpc_header (); +let function = rpc_header.function (); +let seq = rpc_header.sequence (); self.gsp_mem.advance_cpu_read_ptr (pages); self.log_event (function, seq);
drivers/gpu/nova-core/gsp/fw.rs +73 -50
162 lines not on this page · raw message
Signature · 1 line
2.56.0
Alexandre Courbot
maintainerPATCH v4 3/10 gpu: nova-core: gsp: cmdq: group the RPC-specific part of send_single_command
In reply to Alexandre Courbotsend_single_command handles both the transport and message layers of the command, intertwining the logic of the two.
Reorder the code so the message layer logic is within the same contiguous block of code, so it can easily be moved.
No functional change intended.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +15 -15
@@ -683,18 +683,18 @@ fn send_single_command<M>(&mut self, command: M) -> Result .gsp_mem .allocate_command (size_in_bytes,Self ::ALLOCATE_TIMEOUT )?; -// Extract area for the command itself. The GSP message header and the command header -// together are guaranteed to fit entirely into a single page, so it's ok to only look -// at `dst.contents.0` here. -let (cmd, payload_1) =M ::Command ::from_bytes_mut_prefix (dst.contents.0 ).ok_or (EIO )?; - -// Fill the header and command in-place. +// Fill the header. let msg_element_init =GspMsgElement ::init (self.seq, size_in_bytes); -let rpc_header_init =RpcMessageHeader ::init (size_in_bytes,M ::FUNCTION );// SAFETY: `dst.header` is a valid reference, and is not touched if the initializer fails. unsafe { pin_init::raw_try_init (core::ptr::from_mut (dst.header), msg_element_init)?; } + +// Extract area for the command itself. The GSP message header and the command header +// together are guaranteed to fit entirely into a single page, so it's ok to only look +// at `dst.contents.0` here. +let (cmd, payload_1) =M ::Command ::from_bytes_mut_prefix (dst.contents.0 ).ok_or (EIO )?; +let rpc_header_init =RpcMessageHeader ::init (size_in_bytes,M ::FUNCTION );// SAFETY: `dst.header.rpc_header_mut()` is a valid reference, and is not touched if the // initializer fails. unsafe {
@@ -717,14 +717,6 @@ fn send_single_command<M>(&mut self, command: M) -> Result }drop (sbuffer); -// Compute checksum now that the whole message is ready. - dst.header - .set_checksum (Cmdq ::calculate_checksum (SBufferIter ::new_reader ([ - dst.header.as_bytes (), - dst.contents.0 , - dst.contents.1 , - ]))); -dev_dbg! ( &self.dev,"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n" ,
@@ -733,6 +725,14 @@ fn send_single_command<M>(&mut self, command: M) -> Result size_in_bytes, ); +// Compute checksum now that the whole message is ready. + dst.header + .set_checksum (Cmdq ::calculate_checksum (SBufferIter ::new_reader ([ + dst.header.as_bytes (), + dst.contents.0 , + dst.contents.1 , + ]))); +// All set - update the write pointer and inform the GSP of the new command. let elem_count = dst.header.element_count (); self.seq +=1 ;
Signature · 1 line
2.56.0
Alexandre Courbot
maintainerPATCH v4 4/10 gpu: nova-core: gsp: cmdq: split the transport part of the send path
In reply to Alexandre CourbotIntroduce the CommandElement trait and RpcCommandElement wrapper type to define how messages (independently of their type) are sent through the transport layer. send_single_command becomes send_command_element, which allocates the queue slots, writes the element header, and delegates the writing of the message itself to the implementation of CommandElement before computing the checksum, advancing the write pointer and ringing the doorbell.
The RPC part of send_single_command (writing the RPC header and the command payload) is now part of the CommandElement implementation. This sets things up for moving the RPC code into its own sub-module, leaving the transport agnostic of the message type.
No functional change intended.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 133 +++++++++++++++++++++++--------------- 1 file changed, 80 insertions(+), 53 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +80 -53
@@ -39,10 +39,7 @@ }, }; -use continuation::{ -ContinuationRecord , -SplitState ,// -}; +use continuation::SplitState ;use pin_init::pin_init_scope;
@@ -71,6 +68,19 @@/// reply type are sent using [`Cmdq::send_command_no_wait`]. pub (crate )struct NoReply ; +/// Trait implemented by types that can be sent as a single command queue element. +/// +/// The command queue allocates `size()` bytes after the `GspMsgElement` header and calls `write()` +/// to fill them. +trait CommandElement { +/// Size in bytes of the element, not including the `GspMsgElement` header. +fn size (&self) ->usize ; + +/// Writes the contents of the command into `dst`. `dev` is the queue's device (to be used for +/// logging), `seq` is the sequence number of the element. +fn write (&self, dev: &device::Device , seq:u32 , dst: &mut GspCommand <'_>) ->Result ; +} +/// Trait implemented by types representing a command to send to the GSP. /// /// The main purpose of this trait is to provide [`Cmdq`] with the information it needs to send
@@ -133,6 +143,62 @@ fn size(&self) -> usize { } } +/// Wrapper type for sending a RPC command as a command queue element. +/// +/// [`CommandElement`] cannot be directly implemented for all [`CommandToGsp`] with a blanket +/// implementation as it would conflict with other future command types. +struct RpcCommandElement <M >(M ); + +impl <M >CommandElement for RpcCommandElement <M > +where +M :CommandToGsp , +Error :From <M ::InitError >, +{ +fn size (&self) ->usize { + self.0 .size () + } + +fn write (&self, dev: &device::Device , seq:u32 , dst: &mut GspCommand <'_>) ->Result { +let command = &self.0 ; +let size_in_bytes = command.size (); +// Extract area for the command itself. The GSP message header and the command header +// together are guaranteed to fit entirely into a single page, so it's ok to only look +// at `dst.contents.0` here. +let (cmd, payload_1) =M ::Command ::from_bytes_mut_prefix (dst.contents.0 ).ok_or (EIO )?; +let rpc_header_init =RpcMessageHeader ::init (size_in_bytes,M ::FUNCTION ); +// SAFETY: `dst.header.rpc_header_mut()` is a valid reference, and is not touched if the +// initializer fails. +unsafe { + pin_init::raw_try_init ( + core::ptr::from_mut (dst.header.rpc_header_mut ()), + rpc_header_init, + )?; + } +// SAFETY: `cmd` is a valid reference, and is not touched if the initializer fails. +unsafe { + pin_init::raw_try_init (core::ptr::from_mut (cmd), command.init ())?; + } + +// Fill the variable-length payload, which may be empty. +let mut sbuffer =SBufferIter ::new_writer ([&mut payload_1[..], &mut dst.contents.1 [..]]); + command.init_variable_payload (&mut sbuffer)?; + +if !sbuffer.is_empty () { +return Err (EIO ); + } + +dev_dbg! ( + dev, +"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n" , + seq, +M ::FUNCTION , + size_in_bytes, + ); + +Ok (()) + } +} +/// Trait representing messages received from the GSP. /// /// A reply that [`Cmdq::send_command`] waits for, or an event that [`Cmdq::await_msg`] waits for.
@@ -662,24 +728,18 @@ impl CmdqInner<'_> {/// Timeout for waiting for space on the command queue. const ALLOCATE_TIMEOUT :Delta =Delta ::from_secs (1 ); -/// Sends `command` to the GSP, without splitting it. +/// Allocate enough space on the command queue to store `command`, initialize it with +/// [`CommandElement::write`], and send the command to the GSP. /// /// # Errors /// /// - `EMSGSIZE` if the command exceeds the maximum queue element size. /// - `ETIMEDOUT` if space does not become available within the timeout. -/// - `EIO` if the variable payload requested by the command has not been entirely -/// written to by its [`CommandToGsp::init_variable_payload`] method. /// -/// Error codes returned by the command initializers are propagated as-is. -fn send_single_command <M >(&mut self, command:M ) ->Result -where -M :CommandToGsp , -// This allows all error types, including `Infallible`, to be used for `M::InitError`. -Error :From <M ::InitError >, - { +/// Error codes returned by [`CommandElement::write`] are returned as-is. +fn send_command_element <E :CommandElement >(&mut self, command:E ) ->Result {let size_in_bytes = command.size (); -let dst = self +let mut dst = self .gsp_mem .allocate_command (size_in_bytes,Self ::ALLOCATE_TIMEOUT )?;
@@ -690,40 +750,8 @@ fn send_single_command<M>(&mut self, command: M) -> Result pin_init::raw_try_init (core::ptr::from_mut (dst.header), msg_element_init)?; } -// Extract area for the command itself. The GSP message header and the command header -// together are guaranteed to fit entirely into a single page, so it's ok to only look -// at `dst.contents.0` here. -let (cmd, payload_1) =M ::Command ::from_bytes_mut_prefix (dst.contents.0 ).ok_or (EIO )?; -let rpc_header_init =RpcMessageHeader ::init (size_in_bytes,M ::FUNCTION ); -// SAFETY: `dst.header.rpc_header_mut()` is a valid reference, and is not touched if the -// initializer fails. -unsafe { - pin_init::raw_try_init ( - core::ptr::from_mut (dst.header.rpc_header_mut ()), - rpc_header_init, - )?; - } -// SAFETY: `cmd` is a valid reference, and is not touched if the initializer fails. -unsafe { - pin_init::raw_try_init (core::ptr::from_mut (cmd), command.init ())?; - } - -// Fill the variable-length payload, which may be empty. -let mut sbuffer =SBufferIter ::new_writer ([&mut payload_1[..], &mut dst.contents.1 [..]]); - command.init_variable_payload (&mut sbuffer)?; - -if !sbuffer.is_empty () { -return Err (EIO ); - } -drop (sbuffer); - -dev_dbg! ( - &self.dev, -"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n" , - self.seq, -M ::FUNCTION , - size_in_bytes, - ); +// Write the message payload. + command.write (self.dev, self.seq, &mut dst)?;// Compute checksum now that the whole message is ready. dst.header
@@ -759,13 +787,12 @@ fn send_command<M>(&mut self, command: M) -> Result Error: From<M::InitError>, {match SplitState ::new (command)? { -SplitState ::Single (command) => self.send_single_command (command), +SplitState ::Single (command) => self.send_command_element (RpcCommandElement (command)),SplitState ::Split (command,mut continuations) => { - self.send_single_command (command)?; + self.send_command_element (RpcCommandElement (command))?;while let Some (continuation) = continuations.next () { -// Turbofish needed because the compiler cannot infer M here. - self.send_single_command ::<ContinuationRecord <'_>>(continuation)?; + self.send_command_element (RpcCommandElement (continuation))?; }Ok (())
Signature · 1 line
2.56.0
Alexandre Courbot
maintainerPATCH v4 5/10 gpu: nova-core: gsp: cmdq: split RPC parsing part of the receive path
In reply to Alexandre CourbotThe RPC parsing should not be done in the same method as the transport header parsing. Split it out and introduce a RpcMessage type to indicate messages that have been successfully parsed as RPC. This makes the code easier to move around into its new destination.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 112 ++++++++++++++++++++++++-------------- 1 file changed, 70 insertions(+), 42 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +70 -42
@@ -554,11 +554,69 @@ struct GspCommand<'a> {struct GspMessage <'a> {// Reference to the header of the message. header: &'aGspMsgElement , -// Slices to the contents of the message. The second slice is zero unless the message loops +// Slices to the contents of the message. The second slice is empty unless the message loops // over the message queue. contents: (&'a [u8 ], &'a [u8 ]), } +/// A RPC message ready to be processed from the message queue. +struct RpcMessage <'a> { +// Reference to the RPC header of the message. + header: &'aRpcMessageHeader , +// Slices to the contents of the message. The second slice is empty unless the message loops +// over the message queue. + contents: (&'a [u8 ], &'a [u8 ]), +} + +impl <'a>RpcMessage <'a> { +/// Validate the RPC layer of `element` and returns its RPC header and its contents trimmed down +/// to the RPC payload. +/// +/// # Errors +/// +/// - `EIO` if the element is shorter than the payload length advertised by the RPC header. +fn parse (dev: &device::Device , element:GspMessage <'a>) ->Result <RpcMessage <'a>> { +let GspMessage { + header, + contents: (slice_1, slice_2), + } = element; + +let rpc_header = header.rpc_header (); +let payload_length = rpc_header.rpc_length (); + +dev_dbg! ( + dev, +"GSP RPC: receive: seq# {}, function={:?}, length=0x{:x}\n" , + rpc_header.sequence (), + rpc_header.function (), + payload_length, + ); + +// Check that the driver read area is large enough for the message. +if slice_1.len () + slice_2.len () < payload_length { +return Err (EIO ); + } + +// Cut the message slices down to the actual length of the message. +let (slice_1, slice_2) =if slice_1.len () > payload_length { +// PANIC: we checked above that `slice_1` is at least as long as `payload_length`. + (slice_1.split_at (payload_length).0 , &slice_2[0 ..0 ]) + }else { + ( + slice_1, +// PANIC: we checked above that `slice_1.len() + slice_2.len()` is at least as +// large as `payload_length`. + slice_2.split_at (payload_length - slice_1.len ()).0 , + ) + }; + +Ok (RpcMessage { + header: rpc_header, + contents: (slice_1, slice_2), + }) + } +} +/// GSP command queue. /// /// Provides the ability to send commands and receive messages from the GSP using a shared memory
@@ -841,35 +899,6 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {return Err (EIO ); } -let rpc_header = header.rpc_header (); -let payload_length = rpc_header.rpc_length (); - -dev_dbg! ( - &self.dev, -"GSP RPC: receive: seq# {}, function={:?}, length=0x{:x}\n" , - rpc_header.sequence (), - rpc_header.function (), - payload_length, - ); - -// Check that the driver read area is large enough for the message. -if slice_1.len () + slice_2.len () < payload_length { -return Err (EIO ); - } - -// Cut the message slices down to the actual length of the message. -let (slice_1, slice_2) =if slice_1.len () > payload_length { -// PANIC: we checked above that `slice_1` is at least as long as `payload_length`. - (slice_1.split_at (payload_length).0 , &slice_2[0 ..0 ]) - }else { - ( - slice_1, -// PANIC: we checked above that `slice_1.len() + slice_2.len()` is at least as -// large as `payload_length`. - slice_2.split_at (payload_length - slice_1.len ()).0 , - ) - }; -Ok (GspMessage { header, contents: (slice_1, slice_2),
@@ -897,14 +926,15 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> Error: From<M::InitError>, {let message = self.wait_for_msg (timeout)?; -let rpc_header = message.header.rpc_header (); -let function = rpc_header.function (); -let seq = rpc_header.sequence (); +let elem_count = u32::try_from (message.header.msg_length ().div_ceil (GSP_PAGE_SIZE ))?; +let rpc_message =RpcMessage ::parse (self.dev, message)?; +let function = rpc_message.header.function ();// 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 ]); +let (cmd, contents_1) = +M ::Message ::from_bytes_prefix (rpc_message.contents.0 ).ok_or (EIO )?; +let mut sbuffer =SBufferIter ::new_reader ([contents_1, rpc_message.contents.1 ]);M ::read (cmd, &mut sbuffer) .map_err (|e| e.into ())
@@ -918,15 +948,13 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> } }) }else { - self.log_event (function, seq); + self.log_event (function, rpc_message.header.sequence ());Err (ENOMSG ) };// Advance the read pointer past this message. - self.gsp_mem.advance_cpu_read_ptr (u32::try_from ( - message.header.msg_length ().div_ceil (GSP_PAGE_SIZE ), - )?); + self.gsp_mem.advance_cpu_read_ptr (elem_count); result }
@@ -1008,9 +1036,9 @@ fn drain(&mut self) -> Result {dev_err! (&self.dev,"GSP drain: message length overflow\n" );EIO })?; -let rpc_header = msg.header.rpc_header (); -let function = rpc_header.function (); -let seq = rpc_header.sequence (); +let rpc_msg =RpcMessage ::parse (self.dev, msg)?; +let function = rpc_msg.header.function (); +let seq = rpc_msg.header.sequence (); self.gsp_mem.advance_cpu_read_ptr (pages); self.log_event (function, seq);
Signature · 1 line
2.56.0
Re: [PATCH v4 05/10] gpu: nova-core: gsp: cmdq: split RPC parsing part of the receive path
Quoted 7 lines · Alexandre Courbot
The RPC parsing should not be done in the same method as the transport header parsing. Split it out and introduce a
RpcMessagetype to indicate messages that have been successfully parsed as RPC. This makes the code easier to move around into its new destination.Signed-off-by Alexandre Courbot <[email protected]>---
Alexandre Courbot
maintainerPATCH v4 6/10 gpu: nova-core: gsp: cmdq: move RPC message logging to RpcMessage
In reply to Alexandre CourbotThe RpcMessage type is the right container for the log_event method, since it contains all the data we passed to it. Move it there so callers don't need to extract the required data themselves.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 66 ++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 35 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +31 -35
@@ -615,6 +615,34 @@ fn parse(dev: &device::Device, element: GspMessage<'a>) -> Result<RpcMessage<'a> contents: (slice_1, slice_2), }) } + +/// Logs an event, meaning a message that no caller was waiting for. +/// +/// An OS error or robust-channel record is logged at error level and an unknown function code +/// at warning level. Other events are not logged. +fn log (&self, dev: &device::Device ) { +let function = self.header.function (); +let seq = self.header.sequence (); + +match function { +Ok (MsgFunction ::OsErrorLog ) => { +dev_err! (dev,"GSP reported an OS error (seq {})\n" , seq); + } +Ok (MsgFunction ::RcTriggered ) => { +dev_err! (dev,"GSP triggered robust-channel recovery (seq {})\n" , seq); + } +// Nothing to do for the remaining known function codes. +Ok (_) => {} +Err (raw) => { +dev_warn! ( + dev, +"unknown GSP message function {:#x} (seq {})\n" , + raw, + seq + ); + } + } + } }/// GSP command queue.
@@ -948,7 +976,7 @@ fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> } }) }else { - self.log_event (function, rpc_message.header.sequence ()); + rpc_message.log (self.dev);Err (ENOMSG ) };
@@ -990,36 +1018,6 @@ fn await_msg<M: MessageFromGsp>(&mut self) -> Result<M> } } -/// Logs an event, meaning a message that no caller was waiting for. -/// -/// An OS error or robust-channel record is logged at error level and an unknown function code -/// at warning level. Every other event is recorded only by the receive trace in -/// [`Self::wait_for_msg`]. -fn log_event (&self, function:Result <MsgFunction ,u32 >, seq:u32 ) { -match function { -Ok (MsgFunction ::OsErrorLog ) => { -dev_err! (&self.dev,"GSP reported an OS error (seq {})\n" , seq); - } -Ok (MsgFunction ::RcTriggered ) => { -dev_err! ( - &self.dev, -"GSP triggered robust-channel recovery (seq {})\n" , - seq - ); - } -// Nothing to do for the remaining known function codes. -Ok (_) => {} -Err (raw) => { -dev_warn! ( - &self.dev, -"unknown GSP message function {:#x} (seq {})\n" , - raw, - seq - ); - } - } - } -/// Logs and consumes every message the queue holds. /// /// # Errors
@@ -1036,12 +1034,10 @@ fn drain(&mut self) -> Result {dev_err! (&self.dev,"GSP drain: message length overflow\n" );EIO })?; -let rpc_msg =RpcMessage ::parse (self.dev, msg)?; -let function = rpc_msg.header.function (); -let seq = rpc_msg.header.sequence (); + +RpcMessage ::parse (self.dev, msg)?.log (self.dev); self.gsp_mem.advance_cpu_read_ptr (pages); - self.log_event (function, seq); }Ok (())
Signature · 1 line
2.56.0
Re: [PATCH v4 06/10] gpu: nova-core: gsp: cmdq: move RPC message logging to RpcMessage
Quoted 6 lines · Alexandre Courbot
The
RpcMessagetype is the right container for thelog_eventmethod, since it contains all the data we passed to it. Move it there so callers don't need to extract the required data themselves.Signed-off-by Alexandre Courbot <[email protected]>---
Re: [PATCH v4 06/10] gpu: nova-core: gsp: cmdq: move RPC message logging to RpcMessage
In reply to Alexandre CourbotQuoted 6 lines · Alexandre Courbot
The
RpcMessagetype is the right container for thelog_eventmethod, since it contains all the data we passed to it. Move it there so callers don't need to extract the required data themselves.Signed-off-by Alexandre Courbot <[email protected]>---
[...]
drivers/gpu/nova-core/gsp/cmdq.rs fn drain(&mut self) -> Result { · line 1038
Quoted 4 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-2-let function = rpc_msg.header.function (); -let seq = rpc_msg.header.sequence (); + +RpcMessage ::parse (self.dev, msg)?.log (self.dev);
nit: in core/interrupts.rst we say:
``` A drain fails when a message's framing or checksum is bad (see "Draining the GSP-to-CPU queue"). The message stays at the queue head, so every later drain would fail the same way, and the IRQ thread disables vector 155 and logs the failure, which leaves the queue unserviced until the device is reset. ```
So parse()? returning early on failure here is intentional, but I reckon it is worth a comment, especially since the behaviour is different to the semantics for consuming elements regularly (still consumes and progresses for failed elements). Especially since you wouldn't expect this behaviour to differ for a method which explicitly "consumes every message the queue holds".
It looks like this is acting as some kind of implicit poisoning.
Quoted 5 lines
self.gsp_mem.advance_cpu_read_ptr(pages);
- self.log_event(function, seq);
}
Ok(())Alexandre Courbot
maintainerRe: [PATCH v4 06/10] gpu: nova-core: gsp: cmdq: move RPC message logging to RpcMessage
Quoted 21 lines · Eliot Courtney
Quoted 6 lines · Alexandre Courbot
The
RpcMessagetype is the right container for thelog_eventmethod, since it contains all the data we passed to it. Move it there so callers don't need to extract the required data themselves.Signed-off-by Alexandre Courbot <[email protected]>---
[...]
drivers/gpu/nova-core/gsp/cmdq.rs fn drain(&mut self) -> Result { · line 1038
Quoted 4 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-2-let function = rpc_msg.header.function (); -let seq = rpc_msg.header.sequence (); + +RpcMessage ::parse (self.dev, msg)?.log (self.dev);nit: in
core/interrupts.rstwe say:``` A drain fails when a message's framing or checksum is bad (see "Draining the GSP-to-CPU queue"). The message stays at the queue head, so every later drain would fail the same way, and the IRQ thread disables vector 155 and logs the failure, which leaves the queue unserviced until the device is reset. ```
Quoted 6 lines
So
parse()?returning early on failure here is intentional, but I reckon it is worth a comment, especially since the behaviour is different to the semantics for consuming elements regularly (still consumes and progresses for failed elements). Especially since you wouldn't expect this behaviour to differ for a method which explicitly "consumes every message the queue holds".
Sure, I'll add a comment.
Quoted 2 lines
It looks like this is acting as some kind of implicit poisoning.
Indeed, and things will look better once we add the proper poisoning container (after r000 to keep things smooth).
Alexandre Courbot
maintainerRe: [PATCH v4 06/10] gpu: nova-core: gsp: cmdq: move RPC message logging to RpcMessage
Quoted 22 lines · Alexandre Courbot
Quoted 21 lines · Eliot Courtney
Quoted 6 lines · Alexandre Courbot
The
RpcMessagetype is the right container for thelog_eventmethod, since it contains all the data we passed to it. Move it there so callers don't need to extract the required data themselves.Signed-off-by Alexandre Courbot <[email protected]>---
[...]
drivers/gpu/nova-core/gsp/cmdq.rs fn drain(&mut self) -> Result { · line 1038
Quoted 4 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-2-let function = rpc_msg.header.function (); -let seq = rpc_msg.header.sequence (); + +RpcMessage ::parse (self.dev, msg)?.log (self.dev);nit: in
core/interrupts.rstwe say:``` A drain fails when a message's framing or checksum is bad (see "Draining the GSP-to-CPU queue"). The message stays at the queue head, so every later drain would fail the same way, and the IRQ thread disables vector 155 and logs the failure, which leaves the queue unserviced until the device is reset. ```
Quoted 8 lines
Quoted 6 lines
So
parse()?returning early on failure here is intentional, but I reckon it is worth a comment, especially since the behaviour is different to the semantics for consuming elements regularly (still consumes and progresses for failed elements). Especially since you wouldn't expect this behaviour to differ for a method which explicitly "consumes every message the queue holds".Sure, I'll add a comment.
The inconsistency in dropping behavior between drain and await_msg really bothered me, so I've spent more time than I should have reworking that to harmonize the two. As a result v5 has changed a bit more than I wanted, but hopefully it's for the better.
Re: [PATCH v4 06/10] gpu: nova-core: gsp: cmdq: move RPC message logging to RpcMessage
Quoted 30 lines · Alexandre Courbot
Quoted 29 lines · Alexandre Courbot
Quoted 27 lines · Eliot Courtney
Quoted 6 lines · Alexandre Courbot
The
RpcMessagetype is the right container for thelog_eventmethod, since it contains all the data we passed to it. Move it there so callers don't need to extract the required data themselves.Signed-off-by Alexandre Courbot <[email protected]>---
[...]
drivers/gpu/nova-core/gsp/cmdq.rs fn drain(&mut self) -> Result { · line 1038
Quoted 4 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-2-let function = rpc_msg.header.function (); -let seq = rpc_msg.header.sequence (); + +RpcMessage ::parse (self.dev, msg)?.log (self.dev);nit: in
core/interrupts.rstwe say:``` A drain fails when a message's framing or checksum is bad (see "Draining the GSP-to-CPU queue"). The message stays at the queue head, so every later drain would fail the same way, and the IRQ thread disables vector 155 and logs the failure, which leaves the queue unserviced until the device is reset. ```
So
parse()?returning early on failure here is intentional, but I reckon it is worth a comment, especially since the behaviour is different to the semantics for consuming elements regularly (still consumes and progresses for failed elements). Especially since you wouldn't expect this behaviour to differ for a method which explicitly "consumes every message the queue holds".
Quoted 6 lines
Quoted 1 line
Sure, I'll add a comment.
The inconsistency in dropping behavior between
drainandawait_msgreally bothered me, so I've spent more time than I should have reworking that to harmonize the two. As a result v5 has changed a bit more than I wanted, but hopefully it's for the better.
I took a look and it's looking really nice now, so well worth it IMO.
Alexandre Courbot
maintainerPATCH v4 7/10 gpu: nova-core: gsp: cmdq: split the transport part of the receive path
In reply to Alexandre Courbotreceive_msg currently handles both the transport and RPC layers. Introduce the MessageElement trait to define how messages are processed, independently of their type.
Keep the transport layer in wait_for_msg, and introduce consume_element, a transport-level method which reads the message's contents using an implementation of the MessageElement trait before advancing the CPU read pointer past it. RPC messages are handled by the RpcMessageElement wrapper, and the RPC part of receive_msg is moved to its implementation of MessageElement. This sets things up for moving the RPC code into its own module, leaving the transport agnostic of the message type.
As a result of the new abstraction layer, RPC messages whose size is unexpected are consumed instead of remaining on the queue.
--- drivers/gpu/nova-core/gsp/cmdq.rs | 102 ++++++++++++++++++++++---------------- 1 file changed, 58 insertions(+), 44 deletions(-)
drivers/gpu/nova-core/gsp/cmdq.rs +58 -44
@@ -199,6 +199,15 @@ fn write(&self, dev: &device::Device, seq: u32, dst: &mut GspCommand<'_>) -> Res } } +/// Trait implemented by types that can be received as single command queue elements. +/// +/// The command queue validates the element header before calling `read()` to interpret the +/// contents. +trait MessageElement :Sized { +/// Tries to read `Self` from `message`. `dev` is the queue's device, to be used for logging. +fn read (dev: &device::Device , message:GspMessage <'_>) ->Result <Self >; +} +/// Trait representing messages received from the GSP. /// /// A reply that [`Cmdq::send_command`] waits for, or an event that [`Cmdq::await_msg`] waits for.
@@ -224,6 +233,45 @@ fn read( ) -> Result<Self, Self::InitError>; } +/// Wrapper type for receiving a RPC message from a command queue element. +/// +/// [`MessageElement`] cannot be directly implemented for all [`MessageFromGsp`] with a blanket +/// implementation as it would conflict with other future message types. +struct RpcMessageElement <M >(M ); + +impl <M >MessageElement for RpcMessageElement <M > +where +M :MessageFromGsp , +Error :From <M ::InitError >, +{ +fn read (dev: &device::Device , message:GspMessage <'_>) ->Result <Self > { +let rpc_message =RpcMessage ::parse (dev, message)?; +let function = rpc_message.header.function (); + +// 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 (rpc_message.contents.0 ).ok_or (EIO )?; +let mut sbuffer =SBufferIter ::new_reader ([contents_1, rpc_message.contents.1 ]); + +M ::read (cmd, &mut sbuffer) + .map (Self ) + .map_err (|e| e.into ()) + .inspect (|_| { +if !sbuffer.is_empty () { +dev_warn! (dev,"GSP message {:?} has unprocessed data\n" ,M ::FUNCTION ); + } + }) + }else { + rpc_message.log (dev); + +Err (ENOMSG ) + }; + + result + } +} +/// Number of GSP pages making the [`Msgq`]. pub (crate )const MSGQ_NUM_PAGES :u32 =0x3f ;
@@ -886,7 +934,7 @@ fn send_command<M>(&mut self, command: M) -> Result } } -/// Wait for a message to become available on the message queue. +/// Wait for the next element to become available on the message queue. /// /// This works purely at the transport layer and does not interpret or validate the message /// beyond the advertised length in its [`GspMsgElement`].
@@ -933,53 +981,19 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { }) } -/// Receive a message from the GSP. +/// Wait for the next element on the message queue, pass it to [`MessageElement::read`], and +/// advances the read pointer past it. /// -/// A message whose function code is `M::FUNCTION` is decoded and returned. Any other message -/// is logged as an event. -/// -/// The read pointer is always advanced past the message, regardless of whether it matched. +/// The read pointer advances regardless of whether [`MessageElement::read`] succeeds or not. /// /// # Errors /// -/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. -/// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the -/// message queue. -/// - `ENOMSG` if the message was not the awaited reply. -/// -/// Error codes returned by [`MessageFromGsp::read`] are propagated as-is. -fn receive_msg <M :MessageFromGsp >(&mut self, timeout:Delta ) ->Result <M > -where -// This allows all error types, including `Infallible`, to be used for `M::InitError`. -Error :From <M ::InitError >, - { +/// Errors from [`Self::wait_for_msg`] and from [`MessageElement::read`] are propagated +/// as-is. +fn consume_element <M :MessageElement >(&mut self, timeout:Delta ) ->Result <M > {let message = self.wait_for_msg (timeout)?;let elem_count = u32::try_from (message.header.msg_length ().div_ceil (GSP_PAGE_SIZE ))?; -let rpc_message =RpcMessage ::parse (self.dev, message)?; -let function = rpc_message.header.function (); - -// 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 (rpc_message.contents.0 ).ok_or (EIO )?; -let mut sbuffer =SBufferIter ::new_reader ([contents_1, rpc_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 { - rpc_message.log (self.dev); - -Err (ENOMSG ) - }; +let result =M ::read (self.dev, message);// Advance the read pointer past this message. self.gsp_mem.advance_cpu_read_ptr (elem_count);
@@ -1010,8 +1024,8 @@ fn await_msg<M: MessageFromGsp>(&mut self) -> Result<M>if remaining.is_negative () {break Err (ETIMEDOUT ); } -match self.receive_msg ::<M >(remaining) { -Ok (msg) =>break Ok (msg), +match self.consume_element ::<RpcMessageElement <M >>(remaining) { +Ok (msg) =>break Ok (msg.0 ),Err (ENOMSG ) =>continue ,Err (e) =>break Err (e), }
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v4 07/10] gpu: nova-core: gsp: cmdq: split the transport part of the receive path
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] gsp: cmdq: drain() wedges queue on malformed RPC message - [High] gpu: nova-core: ring buffer…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] gsp: cmdq: drain() wedges queue on malformed RPC message
- [High] gpu: nova-core: ring buffer desynchronization on malformed GSP messages
- [Low] cmdq: stale comment regarding read pointer advancement on early return --
commit a033b6d3e9c45eced0baaf0fa5456db1072ad255
Author: Alexandre Courbot <[email protected]>
Subject: gpu: nova-core: gsp: cmdq: split the transport part of the receive path
This patch separates the transport and RPC layers in the GSP command queue receive path by introducing a MessageElement trait. It replaces receive_msg with a transport-agnostic consume_element which parses messages via the trait and advances the read pointer.
Quoted 6 lines
drivers/gpu/nova-core/gsp/cmdq.rs +1
-0@@ -233,45 +233,45 @@ +impl <M >MessageElement for RpcMessageElement <M >
drivers/gpu/nova-core/gsp/cmdq.rs line 243
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +10
-0+where + M: MessageFromGsp, + Error: From<M::InitError>, +{ +fn read (dev: &device::Device , message:GspMessage <'_>) ->Result <Self > { +let rpc_message =RpcMessage ::parse (dev, message)?; +let function = rpc_message.header.function (); + +// An early return here would leave the read pointer on this message. +let result =if matches! (function,Ok (f)if f ==M ::FUNCTION ) {
[Severity: Low]
Is this comment still accurate under the new architecture?
Under the new abstraction, CmdqInner::consume_element() executes M::read(), captures the result, and unconditionally advances the read pointer before returning the result:
CmdqInner::consume_element() {
...
let result = M::read(self.dev, message);
self.gsp_mem.advance_cpu_read_ptr(elem_count);
result
}An early return inside RpcMessageElement::read() no longer leaves the read pointer on the message, making this comment misleading.
[ ... ]
Quoted 15 lines
drivers/gpu/nova-core/gsp/cmdq.rs +1
-10@@ -933,53 +981,19 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { -fn receive_msg <M :MessageFromGsp >(&mut self, timeout:Delta ) ->Result <M > -where -// This allows all error types, including `Infallible`, to be used for `M::InitError`. -Error :From <M ::InitError >, - { +fn consume_element <M :MessageElement >(&mut self, timeout:Delta ) ->Result <M > {let message = self.wait_for_msg (timeout)?;let elem_count = u32::try_from (message.header.msg_length ().div_ceil (GSP_PAGE_SIZE ))?; -let rpc_message =RpcMessage ::parse (self.dev, message)?; -let function = rpc_message.header.function (); - -// An early return here would leave the read pointer on this message. -let result =if matches! (function,Ok (f)if f ==M ::FUNCTION ) {
drivers/gpu/nova-core/gsp/cmdq.rs fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> {
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-2-let (cmd, contents_1) = -M ::Message ::from_bytes_prefix (rpc_message.contents.0 ).ok_or (EIO )?; +let result =M ::read (self.dev, message);// Advance the read pointer past this message. + self.gsp_mem.advance_cpu_read_ptr (elem_count); result }
[Severity: High]
Does this code introduce a regression where malformed GSP messages can desynchronize the ring buffer?
The read pointer is unconditionally advanced by an unvalidated elem_count calculated from message.header.msg_length().
If the GSP sends a message with an rpc_length exceeding the queue's capacity, M::read() (via RpcMessage::parse()) correctly returns an error because the message is physically too large.
However, because advance_cpu_read_ptr() is executed regardless of the error, the read pointer is advanced by the oversized, corrupted elem_count.
Can this cause the read pointer to wrap around arbitrarily, permanently desynchronizing the ring buffer and breaking all further GSP communication?
The previous code correctly bubbled up the error from RpcMessage::parse() before advancing the pointer.
[ ... ]
Quoted 9 lines
drivers/gpu/nova-core/gsp/cmdq.rs +1
-1@@ -1044,14 +1044,14 @@ fn drain(&mut self) -> Result {while !self.gsp_mem.driver_read_area ().0 .is_empty () {// A message is available, so this returns without waiting. let msg = self.wait_for_msg (Delta ::ZERO )?;let pages = - u32::try_from(msg.header.length().div_ceil(GSP_PAGE_SIZE)).map_err(|_| { + u32::try_from(msg.header.msg_length().div_ceil(GSP_PAGE_SIZE)).map_err(|_| { dev_err!(&self.dev, "GSP drain: message length overflow\n");
drivers/gpu/nova-core/gsp/cmdq.rs fn drain(&mut self) -> Result {
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +2
-3EIO })?; -let function = msg.header.function (); -let seq = msg.header.sequence (); + +RpcMessage ::parse (self.dev, msg)?.log (self.dev); self.gsp_mem.advance_cpu_read_ptr (pages); - self.log_event (function, seq); }
[Severity: High]
Can this code permanently wedge the queue if RpcMessage::parse() fails?
The commit message states that messages with unexpected sizes are consumed instead of remaining on the queue.
However, if RpcMessage::parse() returns an error for a malformed message, the ? operator causes an early return from drain().
This skips self.gsp_mem.advance_cpu_read_ptr(pages), leaving the malformed message on the queue.
Any subsequent calls to drain() would repeatedly fail on the same message, permanently wedging the queue.
Verification at the series end commit (37073815d78fabf6293f38e4abb8f78d887d7841) confirms this issue is not fixed by subsequent patches.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Re: [PATCH v4 07/10] gpu: nova-core: gsp: cmdq: split the transport part of the receive path
In reply to Alexandre CourbotQuoted 51 lines · Alexandre Courbot
receive_msgcurrently handles both the transport and RPC layers. Introduce theMessageElementtrait to define how messages are processed, independently of their type.Keep the transport layer in
wait_for_msg, and introduceconsume_element, a transport-level method which reads the message's contents using an implementation of theMessageElementtrait before advancing the CPU read pointer past it. RPC messages are handled by theRpcMessageElementwrapper, and the RPC part ofreceive_msgis moved to its implementation ofMessageElement. This sets things up for moving the RPC code into its own module, leaving the transport agnostic of the message type.As a result of the new abstraction layer, RPC messages whose size is unexpected are consumed instead of remaining on the queue.
Signed-off-by Alexandre Courbot <[email protected]>--- drivers/gpu/nova-core/gsp/cmdq.rs | 102 ++++++++++++++++++++++---------------- 1 file changed, 58 insertions(+), 44 deletions(-)drivers/gpu/nova-core/gsp/cmdq.rs +15
-0@@ -199,6 +199,15 @@ fn write(&self, dev: &device::Device, seq: u32, dst: &mut GspCommand<'_>) -> Res } } +/// Trait implemented by types that can be received as single command queue elements. +/// +/// The command queue validates the element header before calling `read()` to interpret the +/// contents. +trait MessageElement :Sized { +/// Tries to read `Self` from `message`. `dev` is the queue's device, to be used for logging. +fn read (dev: &device::Device , message:GspMessage <'_>) ->Result <Self >; +} +/// Trait representing messages received from the GSP. /// /// A reply that [`Cmdq::send_command`] waits for, or an event that [`Cmdq::await_msg`] waits for. @@ -224,6 +233,45 @@ fn read( ) -> Result<Self, Self::InitError>; } +/// Wrapper type for receiving a RPC message from a command queue element. +/// +/// [`MessageElement`] cannot be directly implemented for all [`MessageFromGsp`] with a blanket +/// implementation as it would conflict with other future message types. +struct RpcMessageElement <M >(M ); +
drivers/gpu/nova-core/gsp/cmdq.rs fn read( · line 251
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +10
-0+impl <M >MessageElement for RpcMessageElement <M > +where +M :MessageFromGsp , +Error :From <M ::InitError >, +{ +fn read (dev: &device::Device , message:GspMessage <'_>) ->Result <Self > { +let rpc_message =RpcMessage ::parse (dev, message)?; +let function = rpc_message.header.function (); + +// An early return here would leave the read pointer on this message.
I think this comment is no longer accurate.
Quoted 12 lines
drivers/gpu/nova-core/gsp/cmdq.rs +12
-0+let result =if matches! (function,Ok (f)if f ==M ::FUNCTION ) { +let (cmd, contents_1) = +M ::Message ::from_bytes_prefix (rpc_message.contents.0 ).ok_or (EIO )?; +let mut sbuffer =SBufferIter ::new_reader ([contents_1, rpc_message.contents.1 ]); + +M ::read (cmd, &mut sbuffer) + .map (Self ) + .map_err (|e| e.into ()) + .inspect (|_| { +if !sbuffer.is_empty () { +dev_warn! (dev,"GSP message {:?} has unprocessed data\n" ,M ::FUNCTION ); + }
drivers/gpu/nova-core/gsp/cmdq.rs fn read( · line 273
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +10
-0+ }) + }else { + rpc_message.log (dev); + +Err (ENOMSG ) + }; + + result + } +}
nit: temporary result here is not necessary since you can just have the if/else as the last expression. Clippy (only at 1.85.0) complains about this, so might be worth fixing.
Quoted 33 lines
drivers/gpu/nova-core/gsp/cmdq.rs +5
-10+/// Number of GSP pages making the [`Msgq`]. pub (crate )const MSGQ_NUM_PAGES :u32 =0x3f ;@@ -886,7 +934,7 @@ fn send_command<M>(&mut self, command: M) -> Result } } -/// Wait for a message to become available on the message queue. +/// Wait for the next element to become available on the message queue. /// /// This works purely at the transport layer and does not interpret or validate the message /// beyond the advertised length in its [`GspMsgElement`]. @@ -933,53 +981,19 @@ fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { }) } -/// Receive a message from the GSP. +/// Wait for the next element on the message queue, pass it to [`MessageElement::read`], and +/// advances the read pointer past it. /// -/// A message whose function code is `M::FUNCTION` is decoded and returned. Any other message -/// is logged as an event. -/// -/// The read pointer is always advanced past the message, regardless of whether it matched. +/// The read pointer advances regardless of whether [`MessageElement::read`] succeeds or not. /// /// # Errors /// -/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. -/// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the -/// message queue. -/// - `ENOMSG` if the message was not the awaited reply.
drivers/gpu/nova-core/gsp/cmdq.rs fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { · line 993
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3
-7-/// -/// Error codes returned by [`MessageFromGsp::read`] are propagated as-is. -fn receive_msg <M :MessageFromGsp >(&mut self, timeout:Delta ) ->Result <M > -where -// This allows all error types, including `Infallible`, to be used for `M::InitError`. -Error :From <M ::InitError >, - { +/// Errors from [`Self::wait_for_msg`] and from [`MessageElement::read`] are propagated +/// as-is. +fn consume_element <M :MessageElement >(&mut self, timeout:Delta ) ->Result <M > {
Ok, so we are changing the semantics to this always consumes the element in a few more cases. I think this is ok and it's documented so sgtm. And maybe we do something for poisoning later?
Alexandre Courbot
maintainerRe: [PATCH v4 07/10] gpu: nova-core: gsp: cmdq: split the transport part of the receive path
On Wed Oct 14, 2026 at 12:56 PM JST, Eliot Courtney wrote:
<...>
Quoted 27 lines
Quoted 16 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3
-9-/// Receive a message from the GSP. +/// Wait for the next element on the message queue, pass it to [`MessageElement::read`], and +/// advances the read pointer past it. /// -/// A message whose function code is `M::FUNCTION` is decoded and returned. Any other message -/// is logged as an event. -/// -/// The read pointer is always advanced past the message, regardless of whether it matched. +/// The read pointer advances regardless of whether [`MessageElement::read`] succeeds or not. /// /// # Errors /// -/// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. -/// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the -/// message queue. -/// - `ENOMSG` if the message was not the awaited reply. drivers/gpu/nova-core/gsp/cmdq.rs fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { · line 993
Quoted 10 lines
drivers/gpu/nova-core/gsp/cmdq.rs +3
-7-/// -/// Error codes returned by [`MessageFromGsp::read`] are propagated as-is. -fn receive_msg <M :MessageFromGsp >(&mut self, timeout:Delta ) ->Result <M > -where -// This allows all error types, including `Infallible`, to be used for `M::InitError`. -Error :From <M ::InitError >, - { +/// Errors from [`Self::wait_for_msg`] and from [`MessageElement::read`] are propagated +/// as-is. +fn consume_element <M :MessageElement >(&mut self, timeout:Delta ) ->Result <M > {
Quoted 3 lines
Ok, so we are changing the semantics to this always consumes the element in a few more cases. I think this is ok and it's documented so sgtm. And maybe we do something for poisoning later?
Yes, John had a proper poisoning mechanism in the r000 series, but I suggested we revisit that after the r000 conversion to simplify and introduce a generic Poisonable container (or something in the same fashion as Mutex) instead of using a bool. So that's definitely on the radar.
Alexandre Courbot
maintainerPATCH v4 8/10 gpu: nova-core: gsp: cmdq: move the RPC code into a sub-module
In reply to Alexandre CourbotMove the types and code related to sending and receiving RPC commands and messages into the rpc sub-module. The methods are still declared as members of CmdqInner and Cmdq; only they are now in their own sub-module.
This is a pure move commit, with no functional change intended.
---
drivers/gpu/nova-core/gsp/cmdq.rs | 412 +------------------
drivers/gpu/nova-core/gsp/cmdq/rpc.rs | 443 +++++++++++++++++++++
.../nova-core/gsp/cmdq/{ => rpc}/continuation.rs | 0
drivers/gpu/nova-core/gsp/commands.rs | 6 +-
drivers/gpu/nova-core/gsp/sequencer.rs | 4 +-
5 files changed, 454 insertions(+), 411 deletions(-)drivers/gpu/nova-core/gsp/cmdq.rs +5 -407
@@ -1,6 +1,7 @@// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -mod continuation; +pub (super )mod rpc;use core::mem;
@@ -28,19 +29,13 @@ }, Mutex, // }, - time::{ - Delta, - Instant, - Monotonic, // - }, + time::Delta, transmute::{AsBytes ,FromBytes ,// }, }; -use continuation::SplitState ; -use pin_init::pin_init_scope;use crate ::{
@@ -48,10 +43,8 @@ gsp::{ fw::{GspMsgElement , -MsgFunction ,MsgqRxHeader ,MsgqTxHeader , -RpcMessageHeader ,GSP_MSG_QUEUE_ELEMENT_SIZE_MAX ,// }, PteArray,
@@ -81,124 +74,6 @@ trait CommandElement {fn write (&self, dev: &device::Device , seq:u32 , dst: &mut GspCommand <'_>) ->Result ; } -/// Trait implemented by types representing a command to send to the GSP. -/// -/// The main purpose of this trait is to provide [`Cmdq`] with the information it needs to send -/// a given command. -/// -/// [`CommandToGsp::init`] in particular is responsible for initializing the command directly -/// into the space reserved for it in the command queue buffer. -/// -/// Some commands may be followed by a variable-length payload. For these, the -/// [`CommandToGsp::variable_payload_len`] and [`CommandToGsp::init_variable_payload`] need to be -/// defined as well. -pub (crate )trait CommandToGsp { -/// Function identifying this command to the GSP. -const FUNCTION :MsgFunction ; - -/// Type generated by [`CommandToGsp::init`], to be written into the command queue buffer. -type Command :FromBytes +AsBytes ; - -/// Type of the reply expected from the GSP, or [`NoReply`] for commands that don't -/// have a reply. -type Reply ; - -/// Error type returned by [`CommandToGsp::init`]. -type InitError ; - -/// In-place command initializer responsible for filling the command in the command queue -/// buffer. -fn init (&self) ->impl Init <Self ::Command ,Self ::InitError >; - -/// Size of the variable-length payload following the command structure generated by -/// [`CommandToGsp::init`]. -/// -/// Most commands don't have a variable-length payload, so this is zero by default. -fn variable_payload_len (&self) ->usize { -0 - } - -/// Method initializing the variable-length payload. -/// -/// The command buffer is circular, which means that we may need to jump back to its beginning -/// while in the middle of a command. For this reason, the variable-length payload is -/// initialized using a [`SBufferIter`]. -/// -/// This method will receive a buffer of the length returned by -/// [`CommandToGsp::variable_payload_len`], and must write every single byte of it. Leaving -/// unwritten space will lead to an error. -/// -/// Most commands don't have a variable-length payload, so this does nothing by default. -fn init_variable_payload ( - &self, - _dst: &mut SBufferIter <core::array::IntoIter <&mut [u8 ],2 >>, - ) ->Result { -Ok (()) - } - -/// Total size of the command (including its variable-length payload) without the -/// [`GspMsgElement`] header. -fn size (&self) ->usize { -size_of ::<Self ::Command >() + self.variable_payload_len () - } -} - -/// Wrapper type for sending a RPC command as a command queue element. -/// -/// [`CommandElement`] cannot be directly implemented for all [`CommandToGsp`] with a blanket -/// implementation as it would conflict with other future command types. -struct RpcCommandElement <M >(M ); - -impl <M >CommandElement for RpcCommandElement <M > -where -M :CommandToGsp , -Error :From <M ::InitError >, -{ -fn size (&self) ->usize { - self.0 .size () - } - -fn write (&self, dev: &device::Device , seq:u32 , dst: &mut GspCommand <'_>) ->Result { -let command = &self.0 ; -let size_in_bytes = command.size (); -// Extract area for the command itself. The GSP message header and the command header -// together are guaranteed to fit entirely into a single page, so it's ok to only look -// at `dst.contents.0` here. -let (cmd, payload_1) =M ::Command ::from_bytes_mut_prefix (dst.contents.0 ).ok_or (EIO )?; -let rpc_header_init =RpcMessageHeader ::init (size_in_bytes,M ::FUNCTION ); -// SAFETY: `dst.header.rpc_header_mut()` is a valid reference, and is not touched if the -// initializer fails. -unsafe { - pin_init::raw_try_init ( - core::ptr::from_mut (dst.header.rpc_header_mut ()), - rpc_header_init, - )?; - } -// SAFETY: `cmd` is a valid reference, and is not touched if the initializer fails. -unsafe { - pin_init::raw_try_init (core::ptr::from_mut (cmd), command.init ())?; - } - -// Fill the variable-length payload, which may be empty. -let mut sbuffer =SBufferIter ::new_writer ([&mut payload_1[..], &mut dst.contents.1 [..]]); - command.init_variable_payload (&mut sbuffer)?; - -if !sbuffer.is_empty () { -return Err (EIO ); - } - -dev_dbg! ( - dev, -"GSP RPC: send: seq# {}, function={:?}, length=0x{:x}\n" , - seq, -M ::FUNCTION , - size_in_bytes, - ); - -Ok (()) - } -} -/// Trait implemented by types that can be received as single command queue elements. /// /// The command queue validates the element header before calling `read()` to interpret the
@@ -208,70 +83,6 @@ trait MessageElement: Sized {fn read (dev: &device::Device , message:GspMessage <'_>) ->Result <Self >; } -/// Trait representing messages received from the GSP. -/// -/// A reply that [`Cmdq::send_command`] waits for, or an event that [`Cmdq::await_msg`] waits for. -/// The receiver matches a message's function code against [`Self::FUNCTION`] and decodes the -/// message with [`Self::read`]. -pub (crate )trait MessageFromGsp :Sized { -/// Function identifying this message from the GSP. -const FUNCTION :MsgFunction ; - -/// Error type returned by [`MessageFromGsp::read`]. -type InitError ; - -/// Type containing the raw message to be read from the message queue. -type Message :FromBytes ; - -/// Method reading the message from the message queue and returning it. -/// -/// From a `Self::Message` and a [`SBufferIter`], constructs an instance of `Self` and returns -/// it. -fn read ( - msg: &Self ::Message , - sbuffer: &mut SBufferIter <core::array::IntoIter <&[u8 ],2 >>, - ) ->Result <Self ,Self ::InitError >; -} - -/// Wrapper type for receiving a RPC message from a command queue element. -/// -/// [`MessageElement`] cannot be directly implemented for all [`MessageFromGsp`] with a blanket -/// implementation as it would conflict with other future message types. -struct RpcMessageElement <M >(M ); - -impl <M >MessageElement for RpcMessageElement <M > -where -M :MessageFromGsp , -Error :From <M ::InitError >, -{ -fn read (dev: &device::Device , message:GspMessage <'_>) ->Result <Self > { -let rpc_message =RpcMessage ::parse (dev, message)?; -let function = rpc_message.header.function (); - -// 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 (rpc_message.contents.0 ).ok_or (EIO )?; -let mut sbuffer =SBufferIter ::new_reader ([contents_1, rpc_message.contents.1 ]); - -M ::read (cmd, &mut sbuffer) - .map (Self ) - .map_err (|e| e.into ()) - .inspect (|_| { -if !sbuffer.is_empty () { -dev_warn! (dev,"GSP message {:?} has unprocessed data\n" ,M ::FUNCTION ); - } - }) - }else { - rpc_message.log (dev); - -Err (ENOMSG ) - }; - - result - } -} -/// Number of GSP pages making the [`Msgq`]. pub (crate )const MSGQ_NUM_PAGES :u32 =0x3f ;
@@ -607,92 +418,6 @@ struct GspMessage<'a> { contents: (&'a [u8], &'a [u8]), } -/// A RPC message ready to be processed from the message queue. -struct RpcMessage <'a> { -// Reference to the RPC header of the message. - header: &'aRpcMessageHeader , -// Slices to the contents of the message. The second slice is empty unless the message loops -// over the message queue. - contents: (&'a [u8 ], &'a [u8 ]), -} - -impl <'a>RpcMessage <'a> { -/// Validate the RPC layer of `element` and returns its RPC header and its contents trimmed down -/// to the RPC payload. -/// -/// # Errors -/// -/// - `EIO` if the element is shorter than the payload length advertised by the RPC header. -fn parse (dev: &device::Device , element:GspMessage <'a>) ->Result <RpcMessage <'a>> { -let GspMessage { - header, - contents: (slice_1, slice_2), - } = element; - -let rpc_header = header.rpc_header (); -let payload_length = rpc_header.rpc_length (); - -dev_dbg! ( - dev, -"GSP RPC: receive: seq# {}, function={:?}, length=0x{:x}\n" , - rpc_header.sequence (), - rpc_header.function (), - payload_length, - ); - -// Check that the driver read area is large enough for the message. -if slice_1.len () + slice_2.len () < payload_length { -return Err (EIO ); - } - -// Cut the message slices down to the actual length of the message. -let (slice_1, slice_2) =if slice_1.len () > payload_length { -// PANIC: we checked above that `slice_1` is at least as long as `payload_length`. - (slice_1.split_at (payload_length).0 , &slice_2[0 ..0 ]) - }else { - ( - slice_1, -// PANIC: we checked above that `slice_1.len() + slice_2.len()` is at least as -// large as `payload_length`. - slice_2.split_at (payload_length - slice_1.len ()).0 , - ) - }; - -Ok (RpcMessage { - header: rpc_header, - contents: (slice_1, slice_2), - }) - } - -/// Logs an event, meaning a message that no caller was waiting for. -/// -/// An OS error or robust-channel record is logged at error level and an unknown function code -/// at warning level. Other events are not logged. -fn log (&self, dev: &device::Device ) { -let function = self.header.function (); -let seq = self.header.sequence (); - -match function { -Ok (MsgFunction ::OsErrorLog ) => { -dev_err! (dev,"GSP reported an OS error (seq {})\n" , seq); - } -Ok (MsgFunction ::RcTriggered ) => { -dev_err! (dev,"GSP triggered robust-channel recovery (seq {})\n" , seq); - } -// Nothing to do for the remaining known function codes. -Ok (_) => {} -Err (raw) => { -dev_warn! ( - dev, -"unknown GSP message function {:#x} (seq {})\n" , - raw, - seq - ); - } - } - } -} -/// GSP command queue. /// /// Provides the ability to send commands and receive messages from the GSP using a shared memory
@@ -764,73 +489,6 @@ fn notify_gsp(bar: Bar0<'_>) { bar.write_reg (regs::NV_PGSP_QUEUE_HEAD ::zeroed ().with_address (0u32 )); } -/// Sends `command` to the GSP and waits for the reply. -/// -/// Events that arrive before the reply are logged and consumed. -/// -/// The queue is locked for the entire send+receive cycle to ensure that no other command can -/// be interleaved. -/// -/// # Errors -/// -/// - `ETIMEDOUT` if space does not become available to send the command, or if the reply does -/// not arrive within [`Self::RECEIVE_TIMEOUT`] of the send, however many events arrive -/// while waiting. -/// - `EIO` if the variable payload requested by the command has not been entirely -/// written to by its [`CommandToGsp::init_variable_payload`] method. -/// -/// Error codes returned by the command and reply initializers are propagated as-is. -pub (crate )fn send_command <M >(&self, command:M ) ->Result <M ::Reply > -where -M :CommandToGsp , -M ::Reply :MessageFromGsp , -Error :From <M ::InitError >, -Error :From <<M ::Reply as MessageFromGsp >::InitError >, - { -let mut inner = self.inner.lock (); - inner.send_command (command)?; - - inner.await_msg () - } - -/// Sends `command` to the GSP without waiting for a reply. -/// -/// # Errors -/// -/// - `ETIMEDOUT` if space does not become available within the timeout. -/// - `EIO` if the variable payload requested by the command has not been entirely -/// written to by its [`CommandToGsp::init_variable_payload`] method. -/// -/// Error codes returned by the command initializers are propagated as-is. -pub (crate )fn send_command_no_wait <M >(&self, command:M ) ->Result -where -M :CommandToGsp <Reply =NoReply >, -Error :From <M ::InitError >, - { - self.inner.lock ().send_command (command) - } - -/// Waits for an unsolicited GSP event of type `M`. Events that arrive before it are logged and -/// consumed. -/// -/// The queue mutex is held for the whole wait, up to [`Self::RECEIVE_TIMEOUT`], so no other -/// caller can send a command or consume an event meanwhile. -/// -/// # Errors -/// -/// - `ETIMEDOUT` if the event does not arrive within [`Self::RECEIVE_TIMEOUT`] of the call, -/// however many other events arrive while waiting. -/// - `EIO` if a message fails framing or checksum validation. -/// -/// Error codes returned by [`MessageFromGsp::read`] are propagated as-is. -pub (crate )fn await_msg <M :MessageFromGsp >(&self) ->Result <M > -where -// This allows all error types, including `Infallible`, to be used for `M::InitError`. -Error :From <M ::InitError >, - { - self.inner.lock ().await_msg () - } -/// Logs and consumes every message the GSP has already posted, and returns without waiting for /// more. ///
@@ -904,36 +562,6 @@ fn send_command_element<E: CommandElement>(&mut self, command: E) -> Result {Ok (()) } -/// Sends `command` to the GSP. -/// -/// The command may be split into multiple messages if it is large. -/// -/// # Errors -/// -/// - `ETIMEDOUT` if space does not become available within the timeout. -/// - `EIO` if the variable payload requested by the command has not been entirely -/// written to by its [`CommandToGsp::init_variable_payload`] method. -/// -/// Error codes returned by the command initializers are propagated as-is. -fn send_command <M >(&mut self, command:M ) ->Result -where -M :CommandToGsp , -Error :From <M ::InitError >, - { -match SplitState ::new (command)? { -SplitState ::Single (command) => self.send_command_element (RpcCommandElement (command)), -SplitState ::Split (command,mut continuations) => { - self.send_command_element (RpcCommandElement (command))?; - -while let Some (continuation) = continuations.next () { - self.send_command_element (RpcCommandElement (continuation))?; - } - -Ok (()) - } - } - } -/// Wait for the next element to become available on the message queue. /// /// This works purely at the transport layer and does not interpret or validate the message
@@ -1001,37 +629,6 @@ fn consume_element<M: MessageElement>(&mut self, timeout: Delta) -> Result<M> { result } -/// Receives a message of type `M`, waiting up to [`Cmdq::RECEIVE_TIMEOUT`] from the call. -/// -/// Any other message that arrives first is logged as an event and does not extend the -/// deadline. -/// -/// # Errors -/// -/// - `ETIMEDOUT` if no message of type `M` arrives before the deadline, however many other -/// messages arrive while waiting. -/// - `EIO` if a message fails framing or checksum validation (see [`Self::wait_for_msg`]). -/// -/// Error codes returned by [`MessageFromGsp::read`] are propagated as-is. -fn await_msg <M :MessageFromGsp >(&mut self) ->Result <M > -where -// This allows all error types, including `Infallible`, to be used for `M::InitError`. -Error :From <M ::InitError >, - { -let deadline =Instant ::<Monotonic >::now () +Cmdq ::RECEIVE_TIMEOUT ; -loop { -let remaining = deadline -Instant ::<Monotonic >::now (); -if remaining.is_negative () { -break Err (ETIMEDOUT ); - } -match self.consume_element ::<RpcMessageElement <M >>(remaining) { -Ok (msg) =>break Ok (msg.0 ), -Err (ENOMSG ) =>continue , -Err (e) =>break Err (e), - } - } - } -/// Logs and consumes every message the queue holds. /// /// # Errors
@@ -1049,7 +646,8 @@ fn drain(&mut self) -> Result {EIO })?; -RpcMessage ::parse (self.dev, msg)?.log (self.dev); +// RPC is the only type of message supported, so dispatch the message there. + rpc::RpcMessage ::parse (self.dev, msg)?.log (self.dev); self.gsp_mem.advance_cpu_read_ptr (pages); }
drivers/gpu/nova-core/gsp/cmdq/rpc.rs new file +443 -0
443 lines not on this page · raw message
drivers/gpu/nova-core/gsp/cmdq/rpc/continuation.rs renamed from drivers/gpu/nova-core/gsp/cmdq/continuation.rs +0 -0
drivers/gpu/nova-core/gsp/commands.rs +4 -2
@@ -23,9 +23,11 @@ gpu::Chipset, gsp::{ cmdq::{ + rpc::{ +CommandToGsp , +MessageFromGsp ,// + }, Cmdq, - CommandToGsp, - MessageFromGsp, NoReply, // }, fw::{
drivers/gpu/nova-core/gsp/sequencer.rs +2 -2
@@ -28,8 +28,8 @@ }, gsp::{ cmdq::{ - Cmdq, - MessageFromGsp, // + rpc::MessageFromGsp, + Cmdq, // }, fw, GspBootContext,
Signature · 1 line
2.56.0
Alexandre Courbot
maintainerPATCH v4 9/10 gpu: nova-core: gsp: move the RPC commands into a sub-module
In reply to Alexandre CourbotMove the types and code related to RPC commands into the rpc sub-module, and update their users to reference them from their new location.
This is a pure move commit, with no functional change intended.
--- drivers/gpu/nova-core/api.rs | 2 +- drivers/gpu/nova-core/gpu.rs | 2 +- drivers/gpu/nova-core/gsp.rs | 4 +- drivers/gpu/nova-core/gsp/boot.rs | 12 +- drivers/gpu/nova-core/gsp/commands.rs | 331 +---------------------------- drivers/gpu/nova-core/gsp/commands/rpc.rs | 333 ++++++++++++++++++++++++++++++ 6 files changed, 344 insertions(+), 340 deletions(-)
drivers/gpu/nova-core/api.rs +1 -1
@@ -18,7 +18,7 @@use crate ::{ driver, gpu::Gpu , - gsp::commands::GetGspStaticInfoReply ,// + gsp::commands::rpc::GetGspStaticInfoReply ,// };/// API handle for the auxiliary bus child drivers to interact with nova-core.
drivers/gpu/nova-core/gpu.rs +1 -1
@@ -35,7 +35,7 @@ gsp::{ self, cmdq::Cmdq, - commands::GetGspStaticInfoReply, + commands::rpc::GetGspStaticInfoReply,Gsp ,GspBootContext ,// },
drivers/gpu/nova-core/gsp.rs +2 -2
@@ -220,8 +220,8 @@ pub(crate) fn new( }/// Query the GSP for the static GPU information. -pub (crate )fn get_static_info (&self) ->Result <commands::GetGspStaticInfoReply > { - self.cmdq.send_command (commands::GetGspStaticInfo ) +pub (crate )fn get_static_info (&self) ->Result <commands::rpc::GetGspStaticInfoReply > { + self.cmdq.send_command (commands::rpc::GetGspStaticInfo ) } }
drivers/gpu/nova-core/gsp/boot.rs +6 -6
@@ -43,9 +43,9 @@ pub(crate) fn boot(let gsp_fw =KBox ::pin_init (GspFirmware ::new (dev, chipset),GFP_KERNEL )?; self.cmdq - .send_command_no_wait (commands::SetSystemInfo ::new (pdev, chipset))?; + .send_command_no_wait (commands::rpc::SetSystemInfo ::new (pdev, chipset))?; self.cmdq - .send_command_no_wait (commands::SetRegistry ::new (ctx.vgpu.state ())?)?; + .send_command_no_wait (commands::rpc::SetRegistry ::new (ctx.vgpu.state ())?)?;// Perform the chipset-specific boot sequence, and retrieve the unload bundle. let unload_bundle = hal.boot(&self, &mut ctx, &gsp_fw)?.or_else(|| {
@@ -79,7 +79,7 @@ pub(crate) fn boot( hal.post_boot (&self, ctx, &gsp_fw)?;// Wait until GSP is fully initialized. - commands::wait_gsp_init_done (&self.cmdq)?; + commands::rpc::wait_gsp_init_done (&self.cmdq)?;Ok (unload_guard.dismiss ().1 ) }
@@ -88,10 +88,10 @@ pub(crate) fn boot(fn shutdown_gsp ( cmdq: &Cmdq <'_>, gsp_falcon: &Falcon <'_,Gsp >, - mode: commands::PowerStateLevel , + mode: commands::rpc::PowerStateLevel , ) ->Result {// Command to shut the GSP down. - cmdq.send_command (commands::UnloadingGuestDriver ::new (mode))?; + cmdq.send_command (commands::rpc::UnloadingGuestDriver ::new (mode))?;// Wait until GSP signals it is suspended. const LIBOS_INTERRUPT_PROCESSOR_SUSPENDED :u32 = bits::bit_u32 (31 );
@@ -118,7 +118,7 @@ pub(crate) fn unload(let mut res =Self ::shutdown_gsp ( &self.cmdq, ctx.gsp_falcon, - commands::PowerStateLevel ::Level0 , + commands::rpc::PowerStateLevel ::Level0 , ) .inspect_err (|e|dev_err! (dev,"GSP shutdown failed: {:?}\n" , e));
drivers/gpu/nova-core/gsp/commands.rs +1 -330
334 lines not on this page · raw message
drivers/gpu/nova-core/gsp/commands/rpc.rs new file +333 -0
333 lines not on this page · raw message
Signature · 1 line
2.56.0
Alexandre Courbot
maintainerPATCH v4 10/10 gpu: nova-core: gsp: add `rpc` to RPC message send/receive methods
In reply to Alexandre CourbotSince we are going to introduce a second type of message, add rpc to the names of the relevant command queue methods so we can distinguish between the two.
No functional change intended.
--- drivers/gpu/nova-core/gsp.rs | 2 +- drivers/gpu/nova-core/gsp/boot.rs | 6 +++--- drivers/gpu/nova-core/gsp/cmdq.rs | 2 +- drivers/gpu/nova-core/gsp/cmdq/rpc.rs | 14 +++++++------- 4 files changed, 12 insertions(+), 12 deletions(-)
drivers/gpu/nova-core/gsp.rs +1 -1
@@ -221,7 +221,7 @@ pub(crate) fn new(/// Query the GSP for the static GPU information. pub (crate )fn get_static_info (&self) ->Result <commands::rpc::GetGspStaticInfoReply > { - self.cmdq.send_command (commands::rpc::GetGspStaticInfo ) + self.cmdq.send_rpc_command (commands::rpc::GetGspStaticInfo ) } }
drivers/gpu/nova-core/gsp/boot.rs +3 -3
@@ -43,9 +43,9 @@ pub(crate) fn boot(let gsp_fw =KBox ::pin_init (GspFirmware ::new (dev, chipset),GFP_KERNEL )?; self.cmdq - .send_command_no_wait (commands::rpc::SetSystemInfo ::new (pdev, chipset))?; + .send_rpc_command_no_wait (commands::rpc::SetSystemInfo ::new (pdev, chipset))?; self.cmdq - .send_command_no_wait (commands::rpc::SetRegistry ::new (ctx.vgpu.state ())?)?; + .send_rpc_command_no_wait (commands::rpc::SetRegistry ::new (ctx.vgpu.state ())?)?;// Perform the chipset-specific boot sequence, and retrieve the unload bundle. let unload_bundle = hal.boot(&self, &mut ctx, &gsp_fw)?.or_else(|| {
@@ -91,7 +91,7 @@ fn shutdown_gsp( mode: commands::rpc::PowerStateLevel, ) -> Result {// Command to shut the GSP down. - cmdq.send_command(commands::rpc::UnloadingGuestDriver::new(mode))?; + cmdq.send_rpc_command(commands::rpc::UnloadingGuestDriver::new(mode))?;// Wait until GSP signals it is suspended. const LIBOS_INTERRUPT_PROCESSOR_SUSPENDED :u32 = bits::bit_u32 (31 );
drivers/gpu/nova-core/gsp/cmdq.rs +1 -1
@@ -58,7 +58,7 @@use super ::regs;/// Marker type representing the absence of a reply for a command. Commands using this as their -/// reply type are sent using [`Cmdq::send_command_no_wait`]. +/// reply type are sent using [`Cmdq::send_rpc_command_no_wait`]. pub (crate )struct NoReply ;/// Trait implemented by types that can be sent as a single command queue element.
drivers/gpu/nova-core/gsp/cmdq/rpc.rs +7 -7
@@ -162,8 +162,8 @@ fn write(&self, dev: &device::Device, seq: u32, dst: &mut GspCommand<'_>) -> Res/// Trait representing messages received from the GSP. /// -/// A reply that [`Cmdq::send_command`] waits for, or an event that [`Cmdq::await_msg`] waits for. -/// The receiver matches a message's function code against [`Self::FUNCTION`] and decodes the +/// A reply that [`Cmdq::send_rpc_command`] waits for, or an event that [`Cmdq::await_msg`] waits +/// for. The receiver matches a message's function code against [`Self::FUNCTION`] and decodes the /// message with [`Self::read`]. pub (crate )trait MessageFromGsp :Sized {/// Function identifying this message from the GSP.
@@ -327,7 +327,7 @@ impl Cmdq<'_> {/// written to by its [`CommandToGsp::init_variable_payload`] method. /// /// Error codes returned by the command and reply initializers are propagated as-is. -pub (crate )fn send_command <M >(&self, command:M ) ->Result <M ::Reply > +pub (crate )fn send_rpc_command <M >(&self, command:M ) ->Result <M ::Reply >where M :CommandToGsp ,M ::Reply :MessageFromGsp ,
@@ -335,7 +335,7 @@ pub(crate) fn send_command<M>(&self, command: M) -> Result<M::Reply> Error: From<<M::Reply as MessageFromGsp>::InitError>, {let mut inner = self.inner.lock (); - inner.send_command (command)?; + inner.send_rpc_command (command)?; inner.await_msg () }
@@ -349,12 +349,12 @@ pub(crate) fn send_command<M>(&self, command: M) -> Result<M::Reply>/// written to by its [`CommandToGsp::init_variable_payload`] method. /// /// Error codes returned by the command initializers are propagated as-is. -pub (crate )fn send_command_no_wait <M >(&self, command:M ) ->Result +pub (crate )fn send_rpc_command_no_wait <M >(&self, command:M ) ->Result where M :CommandToGsp <Reply =NoReply >,Error :From <M ::InitError >, { - self.inner.lock ().send_command (command) + self.inner.lock ().send_rpc_command (command) }/// Waits for an unsolicited GSP event of type `M`. Events that arrive before it are logged and
@@ -391,7 +391,7 @@ impl CmdqInner<'_> {/// written to by its [`CommandToGsp::init_variable_payload`] method. /// /// Error codes returned by the command initializers are propagated as-is. -fn send_command <M >(&mut self, command:M ) ->Result +fn send_rpc_command <M >(&mut self, command:M ) ->Result where M :CommandToGsp ,Error :From <M ::InitError >,
Signature · 1 line
2.56.0
Re: [PATCH v4 10/10] gpu: nova-core: gsp: add `rpc` to RPC message send/receive methods
Quoted 9 lines · Alexandre Courbot
Since we are going to introduce a second type of message, add
rpcto the names of the relevant command queue methods so we can distinguish between the two.No functional change intended.
Signed-off-by Alexandre Courbot <[email protected]>Reviewed-by Eliot Courtney <[email protected]>---
nit: should also rename await_msg to await_rpc_msg?