Fake GSP: offline software GSP-RM model, fault injection, 25 tests, docs/OFFLINE_TESTING.md

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
LIghtJUNction
2026-12-01 23:01:23 +08:00
parent ac5945e200
commit b21d499211
4 changed files with 1516 additions and 0 deletions

59
docs/OFFLINE_TESTING.md Normal file
View File

@ -0,0 +1,59 @@
# Offline testing
## Fake GSP
Host-side software model of GSP-RM with fault injection. No GPU, no module.
```sh
cd src/nvidia && RUSTUP_TOOLCHAIN=nightly-2026-11-29 cargo test --lib fake_gsp
```
Code: `src/nvidia/src/gpu/fake_gsp.rs` (model) and `fake_gsp/tests.rs` (tests), `#[cfg(test)]` only.
### What is modelled
- **R620 linked queues** (`R620LinkedQueues`): the shared DMA image in the `R620BootQueues`
layout (63 command slots, 127 status slots, firmware-owned status header), the
`QUEUE_HEAD`/`CMDQ_TAIL`/`QUEUE_TAIL`/`MSGQ_TAIL` registers, monotonic cursors, slot
modulo wrap-around, multi-page elements. The model parses every command element (MCTP
magic, NVDM type, length fields, RPC header, strictly increasing sequence) and records
protocol violations; `assert_balanced()` checks that cursors balance and none occurred.
It also enforces the driver's DMA access rules (reads only in the status queue, writes
only to command slots or the SEEN magic).
- Scripted replies per request (`Fault`): ok, silent, late (released by `deliver_late()`),
bad magic, bad sequence, wrong function, `rpc_result` codes, embedded control/alloc
status codes (0x1f/0x56/0x57/0x51), payload of any size, truncated, `CONTINUATION_RECORD`
split, flipped payload bit. Unsolicited events (`push_event`) and the GMCAPI `GSP_INIT`
exchange.
- Driver-side faults: failure of the n-th DMA read/write (`NvStatus(0xffff)`, the error the
Linux queue adapter returns), failure of a doorbell or ack register write, withheld status
header (link timeout), tiny caller frames.
- **Legacy page ring** (`send_rpc*`, `recv_rpc*`, `wait_for_rm_init_done`): `LegacyGsp`
validates the XOR checksum and sequence of what the driver sends and writes replies,
including fragmented ones, into a small wrapping ring.
- `Host::rpc` exercises `R620LinkedQueues::rm_rpc`, which is the exact code path of the
kernel's `R620PreparedDma::rm_rpc` (the kernel now calls it; no behaviour change).
### What is NOT modelled
- Real GSP-RM behaviour. Statuses, reply sizes and ordering are chosen by the test; they only
exist on hardware. A passing test means the driver handles that wire behaviour, not that
GSP-RM produces it.
- The kernel-only layer: `service_r620_rm`, `LinuxR620Queue`, DMA allocation (`-12`) at each
allocation point, session teardown, `stop_phase`. These live in the kernel crate and cannot
be built on the host. DMA read/write failure is injected at the `R620QueueMemory` seam
instead.
- `u32` cursor wrap at 2^32 (needs private state), cache/coherency, timing, interrupts,
encrypted (CC) elements, the sequencer and boot (`execute_gsp_boot`), RM-class semantics.
- The R620 element has no checksum (`unpack_message_620`), so "bad checksum" is only
testable on the legacy ring.
### Findings pinned by tests
- A corrupt or oversized-for-frame reply element is never consumed, so every later RPC fails
the same way; nothing marks the session wedged (`corrupt_magic_is_rejected_and_stays_stuck`).
- After a timeout the driver does not wedge: a late reply is dispatched as an unrelated
message by sequence mismatch and the next RPC works.
- `wait_rm_reply` returns only the primary packet of a `CONTINUATION_RECORD` reply.
- Largest accepted reply payload is `RPC_MAX_LENGTH - 0x20` (65456 bytes), not the 16-page
element limit.

View File

@ -81,6 +81,8 @@ pub mod gsp_live;
pub mod gsp_rpc;
pub mod gsp_sequencer;
pub mod gsp_transport;
#[cfg(test)]
mod fake_gsp;
pub mod gsp_ucode;
pub mod gv100_ce_scrub;
pub mod gv100_irq_service;

View File

@ -0,0 +1,775 @@
//! Offline software GSP-RM model with fault injection (test only).
//!
//! `FakeGsp` plays the firmware side of the R620 linked queues: it owns the
//! shared DMA image (`R620BootQueues` layout), the BAR0 doorbell/cursor
//! registers, consumes what the driver writes and answers with scripted
//! replies. `LegacyGsp` does the same for the page-ring transport
//! (`send_rpc*`/`recv_rpc*`, XOR checksum). Real firmware behaviour is NOT
//! modelled; see docs/OFFLINE_TESTING.md.
//!
//! Evidence: `[seen]` = read in this tree (cited), `[inferred]` = chosen to be
//! consistent with the driver code and not verified against GSP-RM.
extern crate std;
use super::gsp_rpc::{
func, mctp_create_nvdm_header, mctp_create_transport_header, nvdm_header_type,
nvdm_header_vendor_id, pack_gmcapi_620, pack_message, GmcApiHeader, RpcHeader, MCTP_MAGIC,
MSG_ELEM_HDR_620_NO_ENC, MSG_PAGE_BYTES, NVDM_TYPE_GMCAPI, NVDM_TYPE_RM_RPC,
NV_PGSP_CMDQ_TAIL_0, NV_PGSP_MSGQ_TAIL_0, NV_PGSP_QUEUE_HEAD_0, NV_PGSP_QUEUE_TAIL_0,
RPC_HEADER_BYTES,
};
use super::gsp_sequencer::SequencerHost;
use super::gsp_transport::{
write_ring_pages, R620BootQueues, R620Incoming, R620LinkedQueues, R620QueueMemory,
};
use super::registers::RegisterIo;
use nv_rs_abi::NvStatus;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::format;
use std::rc::Rc;
use std::string::String;
use std::vec;
use std::vec::Vec;
pub const TX_SLOTS: u32 = 63;
pub const RX_SLOTS: u32 = 127;
pub const FRAME_BYTES: usize = 128 * 1024;
pub const NV_ERR_TIMEOUT: NvStatus = NvStatus(0x65);
/// How the model answers the next request it receives.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Fault {
/// Well-formed reply, `rpc_result = 0`.
Ok,
/// Never answers.
Silent,
/// Answers only once `deliver_late()` is called.
Late,
/// Reply with a corrupted MCTP magic.
BadMagic,
/// Reply sequence XORed with the value.
BadSequence(u32),
/// Reply carries another function id.
WrongFunction(u32),
/// Reply with this `rpc_result`.
RpcResult(u32),
/// Control/alloc reply with this embedded status (`+0x0c` / `+0x10`).
EmbeddedStatus(u32),
/// Reply with this many payload bytes.
Payload(usize),
/// Header advertises one page more than is ever published.
Truncated,
/// Reply split into a primary packet of this payload size plus a
/// `CONTINUATION_RECORD` with the rest.
Continuation(usize),
/// One payload bit flipped; the R620 element has no checksum.
FlipPayloadBit,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Request {
pub function: u32,
pub sequence: u32,
pub payload: Vec<u8>,
pub pages: u32,
}
struct Inner {
dma: Vec<u8>,
publish_header: bool,
cmd_head: u32,
cmd_tail: u32,
msg_head: u32,
msg_tail: u32,
out: VecDeque<(Vec<u8>, usize)>,
held: VecDeque<(Vec<u8>, usize)>,
faults: VecDeque<Fault>,
gmc_init_payload: Vec<u8>,
requests: Vec<Request>,
violations: Vec<String>,
last_rm_sequence: Option<u32>,
reads: u32,
writes: u32,
fail_read_at: Option<u32>,
fail_write_at: Option<u32>,
fail_reg_write: Option<u32>,
}
/// Firmware side of the R620 linked queues. Clone-free: use `regs()`/`dma()`.
pub struct FakeGsp(Rc<RefCell<Inner>>);
pub struct Regs(Rc<RefCell<Inner>>);
pub struct Dma(Rc<RefCell<Inner>>);
fn slot_offset_tx(counter: u32) -> usize {
R620BootQueues::COMMAND_OFFSET
+ R620BootQueues::PAGE_BYTES * (1 + (counter % TX_SLOTS) as usize)
}
fn slot_offset_rx(counter: u32) -> usize {
R620BootQueues::STATUS_OFFSET
+ R620BootQueues::PAGE_BYTES
+ R620BootQueues::PAGE_BYTES * (counter % RX_SLOTS) as usize
}
fn rd32(b: &[u8], o: usize) -> u32 {
u32::from_le_bytes(b[o..o + 4].try_into().unwrap())
}
/// Builds an unencrypted R620 RM RPC element with arbitrary lengths.
pub fn build_rm_element(header: &RpcHeader, body: &[u8]) -> Vec<u8> {
let total = MSG_ELEM_HDR_620_NO_ENC + RPC_HEADER_BYTES + body.len();
let mut out = vec![0u8; total.div_ceil(8) * 8];
out[0..4].copy_from_slice(&MCTP_MAGIC.to_le_bytes());
out[4..8].copy_from_slice(&(total as u32).to_le_bytes());
out[8..12].copy_from_slice(&mctp_create_transport_header(1, 1, 0, 0, 0).to_le_bytes());
out[12..16].copy_from_slice(&mctp_create_nvdm_header(NVDM_TYPE_RM_RPC).to_le_bytes());
out[16..20].copy_from_slice(&((total - MSG_ELEM_HDR_620_NO_ENC) as u32).to_le_bytes());
header.encode(&mut out[MSG_ELEM_HDR_620_NO_ENC..]).unwrap();
out[MSG_ELEM_HDR_620_NO_ENC + RPC_HEADER_BYTES..total].copy_from_slice(body);
out.truncate(total);
out
}
impl FakeGsp {
pub fn new() -> Self {
Self(Rc::new(RefCell::new(Inner {
dma: vec![0; R620BootQueues::DMA_BYTES],
publish_header: true,
cmd_head: 0,
cmd_tail: 0,
msg_head: 0,
msg_tail: 0,
out: VecDeque::new(),
held: VecDeque::new(),
faults: VecDeque::new(),
gmc_init_payload: vec![0; 16],
requests: Vec::new(),
violations: Vec::new(),
last_rm_sequence: None,
reads: 0,
writes: 0,
fail_read_at: None,
fail_write_at: None,
fail_reg_write: None,
})))
}
pub fn regs(&self) -> Regs {
Regs(self.0.clone())
}
pub fn dma(&self) -> Dma {
Dma(self.0.clone())
}
/// Queue a fault for the next unanswered request (FIFO, `Ok` when empty).
pub fn script(&self, fault: Fault) {
self.0.borrow_mut().faults.push_back(fault);
}
pub fn withhold_status_header(&self) {
self.0.borrow_mut().publish_header = false;
}
pub fn set_gmc_init_payload(&self, payload: &[u8]) {
self.0.borrow_mut().gmc_init_payload = payload.to_vec();
}
/// Fail the n-th (0-based, counted from now) DMA read / write.
pub fn fail_dma_read_after(&self, n: u32) {
let mut s = self.0.borrow_mut();
s.fail_read_at = Some(s.reads + n);
}
pub fn fail_dma_write_after(&self, n: u32) {
let mut s = self.0.borrow_mut();
s.fail_write_at = Some(s.writes + n);
}
pub fn fail_register_write(&self, reg: u32) {
self.0.borrow_mut().fail_reg_write = Some(reg);
}
/// Unsolicited RM event placed on the status queue.
pub fn push_event(&self, function: u32, payload: &[u8]) {
let header = RpcHeader {
rpc_result: 0,
rpc_result_private: 0,
..RpcHeader::request(function, payload.len() as u32, 0, 0)
};
let element = build_rm_element(&header, payload);
let mut s = self.0.borrow_mut();
let pages = element.len().div_ceil(MSG_PAGE_BYTES);
s.out.push_back((element, pages));
s.pump();
}
/// Publishes replies held back by `Fault::Late`.
pub fn deliver_late(&self) {
let mut s = self.0.borrow_mut();
while let Some(held) = s.held.pop_front() {
s.out.push_back(held);
}
s.pump();
}
pub fn requests(&self) -> Vec<Request> {
self.0.borrow().requests.clone()
}
pub fn violations(&self) -> Vec<String> {
self.0.borrow().violations.clone()
}
/// `(cmd_head, cmd_tail, msg_head, msg_tail)`.
pub fn cursors(&self) -> (u32, u32, u32, u32) {
let s = self.0.borrow();
(s.cmd_head, s.cmd_tail, s.msg_head, s.msg_tail)
}
/// Everything the driver sent was consumed and everything we sent was acked.
pub fn assert_balanced(&self) {
let s = self.0.borrow();
assert_eq!(s.cmd_head, s.cmd_tail, "unconsumed commands");
assert_eq!(s.msg_head, s.msg_tail, "unacked status pages");
assert!(s.out.is_empty(), "status pages still queued");
assert!(
s.violations.is_empty(),
"protocol violations: {:?}",
s.violations
);
}
/// Links like the kernel does: polls the firmware-owned status header.
pub fn link(&self, retry: impl FnMut() -> bool) -> Result<R620LinkedQueues, NvStatus> {
let mut regs = self.regs();
let mut dma = self.dma();
R620LinkedQueues::link(&mut regs, |off, hdr| dma.read(off, hdr), retry)
}
}
impl Inner {
fn publish_status_header(&mut self) {
if !self.publish_header {
return;
}
let words = [2u32, 0x80000, 4096, RX_SLOTS, 4096];
for (i, w) in words.iter().enumerate() {
let o = R620BootQueues::STATUS_OFFSET + i * 4;
self.dma[o..o + 4].copy_from_slice(&w.to_le_bytes());
}
}
/// Moves queued elements into the status ring while there is room.
fn pump(&mut self) {
while let Some((_, publish)) = self.out.front() {
let pages = *publish as u32;
if self.msg_head.wrapping_sub(self.msg_tail) + pages > RX_SLOTS {
break;
}
let (bytes, publish) = self.out.pop_front().unwrap();
for (i, chunk) in bytes.chunks(MSG_PAGE_BYTES).take(publish).enumerate() {
let o = slot_offset_rx(self.msg_head.wrapping_add(i as u32));
self.dma[o..o + MSG_PAGE_BYTES].fill(0);
self.dma[o..o + chunk.len()].copy_from_slice(chunk);
}
self.msg_head = self.msg_head.wrapping_add(publish as u32);
}
}
fn gather_command(&self, first: u32, pages: u32) -> Vec<u8> {
let mut bytes = Vec::new();
for i in 0..pages {
let o = slot_offset_tx(first.wrapping_add(i));
bytes.extend_from_slice(&self.dma[o..o + MSG_PAGE_BYTES]);
}
bytes
}
fn doorbell(&mut self, head: u32) {
if head.wrapping_sub(self.cmd_tail) > TX_SLOTS {
self.violations
.push(format!("command head {head} overruns ring"));
return;
}
self.cmd_head = head;
while self.cmd_tail != self.cmd_head {
let first = self.gather_command(self.cmd_tail, 1);
let magic = rd32(&first, 0);
let total = rd32(&first, 4) as usize;
let nvdm = rd32(&first, 12);
let min = MSG_ELEM_HDR_620_NO_ENC + RPC_HEADER_BYTES;
if magic != MCTP_MAGIC || nvdm_header_vendor_id(nvdm) != 0x10de || total < min {
self.violations.push(format!(
"bad command element magic={magic:#x} total={total}"
));
self.cmd_tail = self.cmd_tail.wrapping_add(1);
continue;
}
let pages = total.div_ceil(MSG_PAGE_BYTES) as u32;
if self.cmd_head.wrapping_sub(self.cmd_tail) < pages {
self.violations.push("element not fully published".into());
break;
}
let bytes = self.gather_command(self.cmd_tail, pages);
let kind = nvdm_header_type(nvdm);
let body = &bytes[MSG_ELEM_HDR_620_NO_ENC..total];
if rd32(&bytes, 16) as usize != total - MSG_ELEM_HDR_620_NO_ENC {
self.violations.push("nvdm length != mctp length".into());
}
self.cmd_tail = self.cmd_tail.wrapping_add(pages);
if kind == NVDM_TYPE_RM_RPC {
self.handle_rm(body, pages);
} else if kind == NVDM_TYPE_GMCAPI {
self.handle_gmc(body, pages);
} else {
self.violations.push(format!("unknown nvdm type {kind:#x}"));
}
}
}
fn handle_rm(&mut self, body: &[u8], pages: u32) {
let header = match RpcHeader::decode(body) {
Ok(h) => h,
Err(e) => {
self.violations.push(format!("bad rpc header {e:?}"));
return;
}
};
if header.length as usize != body.len() {
self.violations
.push(format!("rpc length {} != {}", header.length, body.len()));
}
if header.rpc_result != 0xffff_ffff {
self.violations
.push("request rpc_result not sentinel".into());
}
if let Some(last) = self.last_rm_sequence {
if header.sequence.wrapping_sub(last) == 0
|| header.sequence.wrapping_sub(last) > 0x8000_0000
{
self.violations
.push(format!("sequence {} after {last}", header.sequence));
}
}
self.last_rm_sequence = Some(header.sequence);
let payload = body[RPC_HEADER_BYTES..].to_vec();
self.requests.push(Request {
function: header.function,
sequence: header.sequence,
payload: payload.clone(),
pages,
});
let fault = self.faults.pop_front().unwrap_or(Fault::Ok);
self.reply(&header, &payload, fault);
}
fn handle_gmc(&mut self, body: &[u8], pages: u32) {
let Ok(h) = GmcApiHeader::decode(body) else {
self.violations.push("bad gmcapi header".into());
return;
};
self.requests.push(Request {
function: h.command_id(),
sequence: h.sequence as u32,
payload: body[super::gsp_rpc::GMCAPI_HEADER_BYTES..].to_vec(),
pages,
});
let fault = self.faults.pop_front().unwrap_or(Fault::Ok);
if matches!(fault, Fault::Silent) {
return;
}
let payload = self.gmc_init_payload.clone();
let mut frame =
vec![
0u8;
MSG_ELEM_HDR_620_NO_ENC + super::gsp_rpc::GMCAPI_HEADER_BYTES + payload.len()
];
let status = if let Fault::RpcResult(s) = fault {
s
} else {
0
};
let total = pack_gmcapi_620(
&mut frame,
GmcApiHeader::response(h.command_id(), payload.len() as u32, h.sequence, status),
&payload,
)
.unwrap();
frame.truncate(total);
let pages = total.div_ceil(MSG_PAGE_BYTES);
self.out.push_back((frame, pages));
self.pump();
}
fn default_body(function: u32, payload: &[u8], embedded: u32) -> Vec<u8> {
let mut body = payload.to_vec();
match function {
func::GSP_RM_CONTROL if body.len() >= 0x28 => {
body[0x0c..0x10].copy_from_slice(&embedded.to_le_bytes())
}
func::GSP_RM_ALLOC if body.len() >= 0x20 => {
body[0x10..0x14].copy_from_slice(&embedded.to_le_bytes())
}
func::GSP_RM_CONTROL | func::GSP_RM_ALLOC => {}
_ => body.clear(),
}
body
}
fn reply(&mut self, request: &RpcHeader, payload: &[u8], fault: Fault) {
if fault == Fault::Silent {
return;
}
let embedded = if let Fault::EmbeddedStatus(s) = fault {
s
} else {
0
};
let mut body = Self::default_body(request.function, payload, embedded);
let mut header = RpcHeader {
rpc_result: 0,
rpc_result_private: 0,
..RpcHeader::request(request.function, 0, request.sequence, 0)
};
let mut continuation = None;
match fault {
Fault::RpcResult(r) => header.rpc_result = r,
Fault::BadSequence(x) => header.sequence ^= x,
Fault::WrongFunction(f) => header.function = f,
Fault::Payload(n) => {
body = vec![0xa5; n];
if n >= 0x28 {
body[0x0c..0x10].fill(0);
}
}
Fault::Continuation(first) => {
let first = first.min(body.len());
continuation = Some(body.split_off(first));
}
Fault::FlipPayloadBit => {
if let Some(b) = body.last_mut() {
*b ^= 1;
}
}
_ => {}
}
header.length = (RPC_HEADER_BYTES + body.len()) as u32;
if fault == Fault::Truncated {
// Advertise at least two pages, publish all but the last.
body.resize(body.len().max(MSG_PAGE_BYTES), 0);
header.length = (RPC_HEADER_BYTES + body.len()) as u32;
let element = build_rm_element(&header, &body);
let pages = element.len().div_ceil(MSG_PAGE_BYTES);
self.out.push_back((element, pages - 1));
self.pump();
return;
}
let mut element = build_rm_element(&header, &body);
let pages = element.len().div_ceil(MSG_PAGE_BYTES);
if fault == Fault::BadMagic {
element[0..4].copy_from_slice(&0xdead_beefu32.to_le_bytes());
}
let target = if fault == Fault::Late {
&mut self.held
} else {
&mut self.out
};
target.push_back((element, pages));
if let Some(rest) = continuation {
let cont = RpcHeader {
rpc_result: 0,
rpc_result_private: 0,
..RpcHeader::request(
func::CONTINUATION_RECORD,
rest.len() as u32,
request.sequence.wrapping_add(1),
0,
)
};
let element = build_rm_element(&cont, &rest);
let pages = element.len().div_ceil(MSG_PAGE_BYTES);
target.push_back((element, pages));
}
self.pump();
}
}
impl Regs {
fn check_reg_write(&self, off: u32) -> Result<(), NvStatus> {
if self.0.borrow().fail_reg_write == Some(off) {
return Err(NvStatus(0xffff));
}
Ok(())
}
}
impl RegisterIo for Regs {
fn read32(&mut self, off: u32) -> Result<u32, NvStatus> {
let mut s = self.0.borrow_mut();
match off {
NV_PGSP_CMDQ_TAIL_0 => Ok(s.cmd_tail),
NV_PGSP_QUEUE_TAIL_0 => Ok(s.msg_head),
_ => {
s.violations
.push(format!("unexpected register read {off:#x}"));
Err(NvStatus(0x51))
}
}
}
fn write32(&mut self, off: u32, value: u32) -> Result<(), NvStatus> {
self.check_reg_write(off)?;
let mut s = self.0.borrow_mut();
match off {
NV_PGSP_QUEUE_HEAD_0 => s.doorbell(value),
NV_PGSP_MSGQ_TAIL_0 => {
if value.wrapping_sub(s.msg_tail) > s.msg_head.wrapping_sub(s.msg_tail) {
let head = s.msg_head;
s.violations
.push(format!("status tail {value} beyond head {head}"));
} else {
s.msg_tail = value;
s.pump();
}
}
_ => s
.violations
.push(format!("unexpected register write {off:#x}")),
}
Ok(())
}
}
impl R620QueueMemory for Dma {
fn read(&mut self, offset: usize, out: &mut [u8]) -> Result<(), NvStatus> {
let mut s = self.0.borrow_mut();
s.publish_status_header();
let n = s.reads;
s.reads += 1;
if s.fail_read_at == Some(n) {
return Err(NvStatus(0xffff));
}
let end = offset
.checked_add(out.len())
.ok_or(NvStatus::INVALID_ARGUMENT)?;
if offset < R620BootQueues::STATUS_OFFSET || end > R620BootQueues::DMA_BYTES {
s.violations
.push(format!("driver read outside status queue {offset:#x}"));
return Err(NvStatus::INVALID_ARGUMENT);
}
out.copy_from_slice(&s.dma[offset..end]);
Ok(())
}
fn write(&mut self, offset: usize, bytes: &[u8]) -> Result<(), NvStatus> {
let mut s = self.0.borrow_mut();
let n = s.writes;
s.writes += 1;
if s.fail_write_at == Some(n) {
return Err(NvStatus(0xffff));
}
let end = offset
.checked_add(bytes.len())
.ok_or(NvStatus::INVALID_ARGUMENT)?;
let command =
offset >= R620BootQueues::COMMAND_OFFSET + 4096 && end <= R620BootQueues::STATUS_OFFSET;
let seen = offset >= R620BootQueues::STATUS_OFFSET + 32
&& end <= R620BootQueues::DMA_BYTES
&& bytes == super::gsp_rpc::MCTP_MAGIC_SEEN.to_le_bytes();
if !command && !seen {
s.violations.push(format!(
"driver wrote outside allowed ranges {offset:#x}+{}",
bytes.len()
));
return Err(NvStatus::INVALID_ARGUMENT);
}
s.dma[offset..end].copy_from_slice(bytes);
Ok(())
}
}
/// Driver-side harness mirroring the kernel's `rm_rpc` forward path.
pub struct Host {
pub queues: R620LinkedQueues,
pub regs: Regs,
pub dma: Dma,
pub frame: Vec<u8>,
pub sequence: u32,
pub events: Vec<u32>,
}
impl Host {
pub fn new(gsp: &FakeGsp) -> Self {
Self::with_frame(gsp, FRAME_BYTES)
}
pub fn with_frame(gsp: &FakeGsp, frame_bytes: usize) -> Self {
Self {
queues: gsp.link(|| false).expect("link"),
regs: gsp.regs(),
dma: gsp.dma(),
frame: vec![0; frame_bytes],
sequence: 0x1000,
events: Vec::new(),
}
}
/// One RPC with a poll budget (`false` from the retry closure = timeout).
pub fn rpc(
&mut self,
function: u32,
payload: &[u8],
polls: u32,
) -> Result<(RpcHeader, usize), NvStatus> {
let mut left = polls;
self.rpc_with(function, payload, move || {
if left == 0 {
false
} else {
left -= 1;
true
}
})
}
pub fn rpc_with(
&mut self,
function: u32,
payload: &[u8],
retry: impl FnMut() -> bool,
) -> Result<(RpcHeader, usize), NvStatus> {
self.sequence += 1;
let request = RpcHeader::request(function, payload.len() as u32, self.sequence, 0);
let events = &mut self.events;
self.queues.rm_rpc(
&mut self.regs,
&mut self.dma,
&mut self.frame,
&request,
payload,
|_, incoming| {
match incoming {
R620Incoming::Rm(h, _) => events.push(h.function),
R620Incoming::Gmc(h, _) => events.push(h.command_id()),
}
Ok(())
},
retry,
)
}
pub fn reply_payload(&self, len: usize) -> &[u8] {
let o = MSG_ELEM_HDR_620_NO_ENC + RPC_HEADER_BYTES;
&self.frame[o..o + len]
}
}
/// Firmware side of the legacy page-ring transport (`send_rpc`, 0x30-byte
/// element, XOR checksum) with its own head/tail registers.
pub struct LegacyGsp {
pub ring_pages: u32,
pub cmd_head: u32,
pub cmd_tail: u32,
pub msg_head: u32,
pub msg_tail: u32,
pub requests: Vec<Request>,
pub violations: Vec<String>,
expected_seq: Option<u32>,
}
impl LegacyGsp {
pub fn new(ring_pages: u32) -> Self {
Self {
ring_pages,
cmd_head: 0,
cmd_tail: 0,
msg_head: 0,
msg_tail: 0,
requests: Vec::new(),
violations: Vec::new(),
expected_seq: None,
}
}
/// Consumes everything the driver published in `cmdq`, validating each element.
pub fn process(&mut self, cmdq: &[u8]) {
while self.cmd_tail != self.cmd_head {
let mut first = vec![0u8; MSG_PAGE_BYTES];
super::gsp_transport::read_ring_pages(
cmdq,
self.ring_pages,
self.cmd_tail,
1,
&mut first,
)
.unwrap();
let pages = rd32(&first, 0x28);
if pages == 0 || pages > self.ring_pages {
self.violations.push(format!("bad elem_count {pages}"));
self.cmd_tail = self.cmd_head;
return;
}
let mut frame = vec![0u8; pages as usize * MSG_PAGE_BYTES];
super::gsp_transport::read_ring_pages(
cmdq,
self.ring_pages,
self.cmd_tail,
pages,
&mut frame,
)
.unwrap();
match super::gsp_rpc::unpack_message(&frame) {
Ok((seq, rpc, payload)) => {
if let Some(want) = self.expected_seq {
if seq != want || rpc.sequence != want {
self.violations
.push(format!("sequence {seq}/{} want {want}", rpc.sequence));
}
}
self.expected_seq = Some(seq.wrapping_add(1));
self.requests.push(Request {
function: rpc.function,
sequence: rpc.sequence,
payload: payload.to_vec(),
pages,
});
}
Err(e) => self.violations.push(format!("element rejected: {e:?}")),
}
self.cmd_tail = (self.cmd_tail + pages) % self.ring_pages;
}
}
/// Writes one reply element (`seq_num` and RPC sequence given) into `msgq`.
pub fn reply(&mut self, msgq: &mut [u8], seq: u32, rpc: &RpcHeader, payload: &[u8]) {
let mut frame = vec![0u8; MSG_PAGE_BYTES * 4];
let (total, _) = pack_message(&mut frame, seq, rpc, payload).unwrap();
self.write_raw(msgq, &frame[..total]);
}
pub fn write_raw(&mut self, msgq: &mut [u8], bytes: &[u8]) {
self.msg_head = write_ring_pages(msgq, self.ring_pages, self.msg_head, bytes).unwrap();
}
}
impl RegisterIo for LegacyGsp {
fn read32(&mut self, off: u32) -> Result<u32, NvStatus> {
match off {
NV_PGSP_CMDQ_TAIL_0 => Ok(self.cmd_tail),
NV_PGSP_QUEUE_TAIL_0 => Ok(self.msg_head),
_ => Err(NvStatus(0x51)),
}
}
fn write32(&mut self, off: u32, value: u32) -> Result<(), NvStatus> {
match off {
NV_PGSP_QUEUE_HEAD_0 => self.cmd_head = value,
NV_PGSP_MSGQ_TAIL_0 => self.msg_tail = value,
_ => return Err(NvStatus(0x51)),
}
Ok(())
}
}
impl SequencerHost for LegacyGsp {
fn delay_us(&mut self, _us: u32) {}
fn store_reg(&mut self, _index: u32, _value: u32) -> Result<(), NvStatus> {
Ok(())
}
fn core_op(&mut self, _op: u32) -> Result<(), NvStatus> {
Ok(())
}
}
#[cfg(test)]
mod tests;

View File

@ -0,0 +1,680 @@
use super::*;
use crate::gpu::gsp_rpc::{event, func, ContinuationSplitter, RM_CONTROL_HEADER_BYTES};
use crate::gpu::gsp_transport::{
recv_rpc, recv_rpc_reassembled, send_rpc, send_rpc_fragmented, wait_for_rm_init_done,
RingIndices,
};
const CTRL_CMD: u32 = 0x2080_0101;
fn control_payload(params: usize) -> Vec<u8> {
let mut p = vec![0u8; RM_CONTROL_HEADER_BYTES + params];
p[0..4].copy_from_slice(&0xc1d0_0001u32.to_le_bytes());
p[4..8].copy_from_slice(&0xc1d0_0002u32.to_le_bytes());
p[8..12].copy_from_slice(&CTRL_CMD.to_le_bytes());
p[0x10..0x14].copy_from_slice(&(params as u32).to_le_bytes());
for (i, b) in p[RM_CONTROL_HEADER_BYTES..].iter_mut().enumerate() {
*b = i as u8;
}
p
}
fn embedded_status(host: &Host, bytes: usize) -> u32 {
assert!(bytes >= RM_CONTROL_HEADER_BYTES);
rd32(host.reply_payload(bytes), 0x0c)
}
#[test]
fn control_roundtrip_echoes_params_and_balances_queues() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
let payload = control_payload(64);
let (header, bytes) = host.rpc(func::GSP_RM_CONTROL, &payload, 4).unwrap();
assert_eq!(
(header.function, header.rpc_result),
(func::GSP_RM_CONTROL, 0)
);
assert_eq!(bytes, payload.len());
assert_eq!(
host.reply_payload(bytes)[RM_CONTROL_HEADER_BYTES..],
payload[RM_CONTROL_HEADER_BYTES..]
);
let requests = gsp.requests();
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].payload, payload);
assert_eq!(requests[0].sequence, host.sequence);
gsp.assert_balanced();
}
#[test]
fn alloc_and_free_roundtrip() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
let mut alloc = vec![0u8; 0x20 + 8];
alloc[0..4].copy_from_slice(&1u32.to_le_bytes());
let (h, bytes) = host.rpc(func::GSP_RM_ALLOC, &alloc, 4).unwrap();
assert_eq!((h.rpc_result, bytes), (0, alloc.len()));
assert_eq!(rd32(host.reply_payload(bytes), 0x10), 0);
let (h, bytes) = host.rpc(func::FREE, &[0; 16], 4).unwrap();
assert_eq!((h.rpc_result, bytes), (0, 0));
gsp.assert_balanced();
}
#[test]
fn embedded_rm_status_codes_surface_unchanged() {
for status in [0x1f, 0x56, 0x57, 0x51] {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::EmbeddedStatus(status));
let payload = control_payload(8);
let (h, bytes) = host.rpc(func::GSP_RM_CONTROL, &payload, 4).unwrap();
assert_eq!(h.rpc_result, 0);
assert_eq!(embedded_status(&host, bytes), status);
gsp.assert_balanced();
}
}
#[test]
fn rpc_result_codes_are_returned_in_the_header() {
for status in [0x1f, 0x56, 0x57, 0x51] {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::RpcResult(status));
let (h, _) = host.rpc(func::SET_PAGE_DIRECTORY, &[0; 48], 4).unwrap();
assert_eq!(h.rpc_result, status);
gsp.assert_balanced();
}
}
#[test]
fn silent_gsp_times_out_with_bounded_polls() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::Silent);
let mut polls = 0;
let result = host.rpc_with(func::GSP_RM_CONTROL, &control_payload(8), || {
polls += 1;
polls <= 50
});
assert_eq!(result.unwrap_err(), NV_ERR_TIMEOUT);
assert_eq!(polls, 51);
let (head, tail, msg_head, msg_tail) = gsp.cursors();
assert_eq!((head, tail, msg_head, msg_tail), (1, 1, 0, 0));
}
#[test]
fn late_reply_after_timeout_is_skipped_by_the_next_rpc() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::Late);
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 3)
.unwrap_err(),
NV_ERR_TIMEOUT
);
gsp.deliver_late();
let stale_sequence = host.sequence;
let (h, bytes) = host
.rpc(func::GSP_RM_CONTROL, &control_payload(8), 3)
.unwrap();
assert_eq!(h.sequence, stale_sequence + 1);
assert_eq!(embedded_status(&host, bytes), 0);
// The stale reply went to the event dispatcher, not to the new caller.
assert_eq!(host.events, [func::GSP_RM_CONTROL]);
gsp.assert_balanced();
}
#[test]
fn reply_with_wrong_sequence_or_function_is_not_accepted() {
for fault in [Fault::BadSequence(0x40), Fault::WrongFunction(func::FREE)] {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(fault.clone());
let r = host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 5);
assert_eq!(r.unwrap_err(), NV_ERR_TIMEOUT, "{fault:?}");
assert_eq!(host.events.len(), 1);
gsp.assert_balanced();
}
}
#[test]
fn corrupt_magic_is_rejected_and_stays_stuck() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::BadMagic);
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 3)
.unwrap_err(),
NvStatus::INVALID_ARGUMENT
);
// Finding: the bad element is never consumed, so every later RPC fails
// the same way. The session needs a reload; nothing marks it wedged.
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 3)
.unwrap_err(),
NvStatus::INVALID_ARGUMENT
);
let (_, _, msg_head, msg_tail) = gsp.cursors();
assert_eq!((msg_head, msg_tail), (2, 0));
}
#[test]
fn truncated_reply_times_out_without_consuming() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::Truncated);
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 5)
.unwrap_err(),
NV_ERR_TIMEOUT
);
let (_, _, msg_head, msg_tail) = gsp.cursors();
assert_eq!((msg_head, msg_tail), (1, 0));
}
#[test]
fn largest_encodable_reply_fits_the_128k_frame() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
// RPC_MAX_LENGTH (0xffd0) bounds the RPC, tighter than the 16-page element limit.
let max = 0xffd0 - RPC_HEADER_BYTES;
gsp.script(Fault::Payload(max));
let (_, bytes) = host
.rpc(func::GSP_RM_CONTROL, &control_payload(8), 4)
.unwrap();
assert_eq!(bytes, max);
assert!(host
.reply_payload(bytes)
.iter()
.skip(0x10)
.all(|&b| b == 0xa5));
gsp.assert_balanced();
}
#[test]
fn reply_bigger_than_the_link_limit_or_the_frame_is_an_error() {
// Larger than the 16-page element limit: rejected as invalid.
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::Payload(128 * 1024 - 64));
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 4)
.unwrap_err(),
NvStatus::INVALID_ARGUMENT
);
// One byte over RPC_MAX_LENGTH, still within 16 pages.
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::Payload(0xffd0 - RPC_HEADER_BYTES + 1));
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 4)
.unwrap_err(),
NvStatus::INVALID_ARGUMENT
);
// Valid element, caller frame too small.
let gsp = FakeGsp::new();
let mut host = Host::with_frame(&gsp, 16 * 1024);
gsp.script(Fault::Payload(40 * 1024));
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 4)
.unwrap_err(),
NvStatus::INSUFFICIENT_RESOURCES
);
}
#[test]
fn continuation_reply_returns_primary_and_leaves_the_record_queued() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::Continuation(RM_CONTROL_HEADER_BYTES + 8));
let (_, bytes) = host
.rpc(func::GSP_RM_CONTROL, &control_payload(64), 4)
.unwrap();
// The R620 forward path does not reassemble: the caller sees only the primary.
assert_eq!(bytes, RM_CONTROL_HEADER_BYTES + 8);
assert_eq!(gsp.cursors().2, gsp.cursors().3 + 1);
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 4)
.unwrap();
assert_eq!(host.events, [func::CONTINUATION_RECORD]);
gsp.assert_balanced();
}
#[test]
fn flipped_reply_payload_bit_is_not_detected_on_r620() {
// [seen gsp_rpc.rs unpack_message_620] the R620 element has no checksum.
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.script(Fault::FlipPayloadBit);
let (_, bytes) = host
.rpc(func::GSP_RM_CONTROL, &control_payload(16), 4)
.unwrap();
let sent = control_payload(16);
assert_ne!(host.reply_payload(bytes)[bytes - 1], sent[bytes - 1]);
}
#[test]
fn queues_wrap_around_with_multi_page_elements() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
for i in 0..300u32 {
let params = [8usize, 5000, 9000][(i % 3) as usize];
let payload = control_payload(params);
let (_, bytes) = host.rpc(func::GSP_RM_CONTROL, &payload, 4).unwrap();
assert_eq!(bytes, payload.len());
assert_eq!(
host.reply_payload(bytes)[RM_CONTROL_HEADER_BYTES..],
payload[RM_CONTROL_HEADER_BYTES..]
);
}
let (head, _, msg_head, _) = gsp.cursors();
assert!(head > 2 * TX_SLOTS && msg_head > 2 * RX_SLOTS);
assert!(host.events.is_empty());
gsp.assert_balanced();
}
#[test]
fn oversized_request_is_rejected_before_anything_is_sent() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
let err = host
.rpc(func::GSP_RM_CONTROL, &vec![0u8; 70_000], 4)
.unwrap_err();
assert_eq!(err, NvStatus::INVALID_ARGUMENT);
assert_eq!(gsp.cursors(), (0, 0, 0, 0));
}
#[test]
fn dma_write_failure_at_every_point_sends_nothing_and_recovers() {
let payload = control_payload(5000);
for point in 0..2 {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.fail_dma_write_after(point);
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &payload, 4).unwrap_err(),
NvStatus(0xffff)
);
assert_eq!(
gsp.cursors(),
(0, 0, 0, 0),
"doorbell rang after failed write {point}"
);
host.rpc(func::GSP_RM_CONTROL, &payload, 4).unwrap();
gsp.assert_balanced();
}
}
#[test]
fn dma_read_failure_at_every_point_is_an_error_not_a_panic() {
let payload = control_payload(5000);
let reads = {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
let before = gsp.0.borrow().reads;
host.rpc(func::GSP_RM_CONTROL, &payload, 4).unwrap();
gsp.0.borrow().reads - before
};
assert!(reads >= 3);
for point in 0..reads {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.fail_dma_read_after(point);
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &payload, 4).unwrap_err(),
NvStatus(0xffff),
"read {point}"
);
// Nothing was acknowledged, so the reply is still found by the next call.
host.rpc(func::GSP_RM_CONTROL, &payload, 4).unwrap();
assert!(gsp.violations().is_empty());
}
}
#[test]
fn doorbell_and_ack_register_failures_do_not_advance_driver_cursors() {
let gsp = FakeGsp::new();
let mut host = Host::new(&gsp);
gsp.fail_register_write(NV_PGSP_QUEUE_HEAD_0);
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 4)
.unwrap_err(),
NvStatus(0xffff)
);
assert!(gsp.requests().is_empty());
gsp.0.borrow_mut().fail_reg_write = None;
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 4)
.unwrap();
assert_eq!(gsp.requests().len(), 1);
gsp.fail_register_write(NV_PGSP_MSGQ_TAIL_0);
assert_eq!(
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 4)
.unwrap_err(),
NvStatus(0xffff)
);
gsp.0.borrow_mut().fail_reg_write = None;
// The unacknowledged page is marked seen, so it is skipped, not replayed.
host.rpc(func::GSP_RM_CONTROL, &control_payload(8), 4)
.unwrap();
gsp.assert_balanced();
}
#[test]
fn link_waits_for_the_firmware_header_and_times_out_without_it() {
let gsp = FakeGsp::new();
gsp.withhold_status_header();
let mut polls = 0;
// The model publishes the header on first read; withheld means all zeroes.
let err = gsp
.link(|| {
polls += 1;
polls < 5
})
.err();
assert_eq!(err, Some(NV_ERR_TIMEOUT));
assert_eq!(polls, 5);
assert!(FakeGsp::new().link(|| false).is_ok());
}
#[test]
fn gsp_init_handshake_drains_boot_events_and_reports_status() {
let system = [0x42u8; 16];
let run = |gsp: &FakeGsp, budget: u32| {
let mut queues = gsp.link(|| false).unwrap();
let (mut regs, mut dma) = (gsp.regs(), gsp.dma());
let mut frame = vec![0u8; FRAME_BYTES];
let mut left = budget;
let mut unhandled = Vec::new();
let r = queues.init_rpc(
&mut regs,
&mut dma,
&mut frame,
&system,
0x77,
|| {
left = left.saturating_sub(1);
left > 0
},
|kind, id| unhandled.push((kind, id)),
|_, _| panic!("no hs binary"),
);
(r, unhandled)
};
let gsp = FakeGsp::new();
gsp.set_gmc_init_payload(&[7; 32]);
gsp.push_event(event::UCODE_LIBOS_PRINT, &[0; 8]);
let (r, unhandled) = run(&gsp, 10);
assert_eq!(r, Ok(32));
assert!(unhandled.is_empty());
assert_eq!(gsp.requests()[0].payload, system);
gsp.assert_balanced();
let gsp = FakeGsp::new();
gsp.script(Fault::Silent);
assert_eq!(run(&gsp, 10).0, Err(NV_ERR_TIMEOUT));
let gsp = FakeGsp::new();
gsp.script(Fault::RpcResult(0x56));
assert_eq!(run(&gsp, 10).0, Err(NvStatus(0x56)));
// An unexpected RM event before the reply is reported and fails.
let gsp = FakeGsp::new();
gsp.push_event(event::POST_EVENT, &[0; 8]);
let (r, unhandled) = run(&gsp, 10);
assert_eq!(r, Err(NvStatus::NOT_SUPPORTED));
assert_eq!(unhandled.len(), 1);
}
fn legacy_rpc(function: u32, seq: u32, payload: &[u8]) -> RpcHeader {
RpcHeader {
rpc_result: 0,
rpc_result_private: 0,
..RpcHeader::request(function, payload.len() as u32, seq, 0)
}
}
#[test]
fn legacy_ring_send_recv_wraps_and_validates_checksum_and_sequence() {
const PAGES: u32 = 8;
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
let mut cmdq = vec![0u8; PAGES as usize * MSG_PAGE_BYTES];
let mut msgq = vec![0u8; PAGES as usize * MSG_PAGE_BYTES];
let mut scratch = vec![0u8; 4 * MSG_PAGE_BYTES];
for i in 0..40u32 {
let payload = vec![i as u8; [16usize, 5000][(i % 2) as usize]];
let seq = send_rpc(
&mut gsp,
&mut idx,
0,
&mut cmdq,
&mut scratch,
func::GSP_RM_CONTROL,
&payload,
0,
)
.unwrap();
gsp.process(&cmdq);
gsp.cmd_tail = gsp.cmd_head;
gsp.reply(
&mut msgq,
seq,
&legacy_rpc(func::GSP_RM_CONTROL, seq, &payload),
&payload,
);
let (rseq, rpc, len) = recv_rpc(&mut gsp, &mut idx, 0, &msgq, &mut scratch)
.unwrap()
.unwrap();
assert_eq!((rseq, rpc.sequence, len), (seq, seq, payload.len()));
assert!(recv_rpc(&mut gsp, &mut idx, 0, &msgq, &mut scratch)
.unwrap()
.is_none());
}
assert!(gsp.violations.is_empty(), "{:?}", gsp.violations);
assert_eq!(gsp.requests.len(), 40);
assert_eq!(gsp.msg_tail, gsp.msg_head);
}
#[test]
fn legacy_ring_bad_checksum_is_rejected_without_consuming() {
const PAGES: u32 = 4;
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
let mut msgq = vec![0u8; PAGES as usize * MSG_PAGE_BYTES];
let mut scratch = vec![0u8; 2 * MSG_PAGE_BYTES];
let mut frame = vec![0u8; MSG_PAGE_BYTES];
let rpc = legacy_rpc(func::GSP_RM_CONTROL, 0, &[1; 16]);
let (total, _) = pack_message(&mut frame, 0, &rpc, &[1; 16]).unwrap();
frame[0x34] ^= 0x10;
gsp.write_raw(&mut msgq, &frame[..total]);
assert_eq!(
recv_rpc(&mut gsp, &mut idx, 0, &msgq, &mut scratch).unwrap_err(),
NvStatus(0x2f)
);
assert_eq!(gsp.msg_tail, 0);
}
#[test]
fn legacy_ring_full_returns_insufficient_resources() {
const PAGES: u32 = 4;
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
let mut cmdq = vec![0u8; PAGES as usize * MSG_PAGE_BYTES];
let mut scratch = vec![0u8; 4 * MSG_PAGE_BYTES];
for _ in 0..3 {
send_rpc(
&mut gsp,
&mut idx,
0,
&mut cmdq,
&mut scratch,
func::NOP,
&[0; 8],
0,
)
.unwrap();
}
assert_eq!(
send_rpc(
&mut gsp,
&mut idx,
0,
&mut cmdq,
&mut scratch,
func::NOP,
&[0; 8],
0
)
.unwrap_err(),
NvStatus(0x1a)
);
assert_eq!(idx.next_seq, 3);
}
#[test]
fn legacy_fragmented_send_and_reassembled_reply_with_faults() {
const PAGES: u32 = 16;
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
let mut cmdq = vec![0u8; PAGES as usize * MSG_PAGE_BYTES];
let mut msgq = vec![0u8; PAGES as usize * MSG_PAGE_BYTES];
let mut scratch = vec![0u8; 4 * MSG_PAGE_BYTES];
let payload: Vec<u8> = (0..9000u32).map(|i| i as u8).collect();
let max_rpc = RPC_HEADER_BYTES + 3000;
let (start, packets) = send_rpc_fragmented(
&mut gsp,
&mut idx,
0,
&mut cmdq,
&mut scratch,
func::GSP_RM_CONTROL,
&payload,
0,
max_rpc,
)
.unwrap();
assert_eq!((start, packets), (0, 3));
gsp.cmd_head = idx.tx_head;
gsp.process(&cmdq);
assert!(gsp.violations.is_empty(), "{:?}", gsp.violations);
let seen: Vec<u32> = gsp.requests.iter().map(|r| r.function).collect();
assert_eq!(
seen,
[
func::GSP_RM_CONTROL,
func::CONTINUATION_RECORD,
func::CONTINUATION_RECORD
]
);
// Reply split into primary + continuation records, reassembled by the driver.
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
let mut splitter =
ContinuationSplitter::new(func::GSP_RM_CONTROL, &payload, 100, 0, max_rpc).unwrap();
let mut seq = 100;
let mut reply_pages = Vec::new();
while let Some((hdr, chunk)) = splitter.next_chunk() {
let hdr = RpcHeader {
rpc_result: 0,
rpc_result_private: 0,
..hdr
};
reply_pages.push((seq, hdr, chunk.to_vec()));
seq += 1;
}
for (s, hdr, chunk) in &reply_pages {
gsp.reply(&mut msgq, *s, hdr, chunk);
}
let mut out = vec![0u8; payload.len()];
let (status, got) = recv_rpc_reassembled(
&mut gsp,
&mut idx,
0,
&msgq,
&mut scratch,
func::GSP_RM_CONTROL,
100,
&mut out,
)
.unwrap();
assert_eq!((status, got), (NvStatus(0), payload.len()));
assert_eq!(out, payload);
// Skipped continuation sequence: rejected as 0x25.
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
for (i, (s, hdr, chunk)) in reply_pages.iter().enumerate() {
let s = if i == 1 { *s + 5 } else { *s };
let hdr = RpcHeader {
sequence: s,
..*hdr
};
gsp.reply(&mut msgq, s, &hdr, chunk);
}
assert_eq!(
recv_rpc_reassembled(
&mut gsp,
&mut idx,
0,
&msgq,
&mut scratch,
func::GSP_RM_CONTROL,
100,
&mut out
)
.unwrap_err(),
NvStatus(0x25)
);
// Reply cut short after the primary: timeout.
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
gsp.reply(&mut msgq, 100, &reply_pages[0].1, &reply_pages[0].2);
assert_eq!(
recv_rpc_reassembled(
&mut gsp,
&mut idx,
0,
&msgq,
&mut scratch,
func::GSP_RM_CONTROL,
100,
&mut out
)
.unwrap_err(),
NV_ERR_TIMEOUT
);
}
#[test]
fn legacy_init_done_wait_times_out_and_reports_failure() {
const PAGES: u32 = 4;
let mut msgq = vec![0u8; PAGES as usize * MSG_PAGE_BYTES];
let mut scratch = vec![0u8; 2 * MSG_PAGE_BYTES];
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
assert_eq!(
wait_for_rm_init_done(&mut gsp, &mut idx, 0, &msgq, &mut scratch, 8).unwrap_err(),
NV_ERR_TIMEOUT
);
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
let hdr = legacy_rpc(event::GSP_INIT_DONE, 0, &[0; 8]);
gsp.reply(&mut msgq, 0, &hdr, &[0; 8]);
wait_for_rm_init_done(&mut gsp, &mut idx, 0, &msgq, &mut scratch, 8).unwrap();
let mut gsp = LegacyGsp::new(PAGES);
let mut idx = RingIndices::new(PAGES);
let hdr = RpcHeader {
rpc_result: 0x57,
..legacy_rpc(event::GSP_INIT_DONE, 0, &[0; 8])
};
gsp.reply(&mut msgq, 0, &hdr, &[0; 8]);
assert_eq!(
wait_for_rm_init_done(&mut gsp, &mut idx, 0, &msgq, &mut scratch, 8).unwrap_err(),
NvStatus(0x57)
);
}