1 // SPDX-License-Identifier: GPL-2.0 2 3 use core::{ 4 cmp, 5 mem, 6 sync::atomic::{ 7 fence, 8 Ordering, // 9 }, // 10 }; 11 12 use kernel::{ 13 device, 14 dma::CoherentAllocation, 15 dma_write, 16 io::poll::read_poll_timeout, 17 prelude::*, 18 sync::aref::ARef, 19 time::Delta, 20 transmute::{ 21 AsBytes, 22 FromBytes, // 23 }, 24 }; 25 26 use crate::{ 27 driver::Bar0, 28 gsp::{ 29 fw::{ 30 GspMsgElement, 31 MsgFunction, 32 MsgqRxHeader, 33 MsgqTxHeader, // 34 }, 35 PteArray, 36 GSP_PAGE_SIZE, // 37 }, 38 num, 39 regs, 40 sbuffer::SBufferIter, // 41 }; 42 43 /// Trait implemented by types representing a command to send to the GSP. 44 /// 45 /// The main purpose of this trait is to provide [`Cmdq::send_command`] with the information it 46 /// needs to send a given command. 47 /// 48 /// [`CommandToGsp::init`] in particular is responsible for initializing the command directly 49 /// into the space reserved for it in the command queue buffer. 50 /// 51 /// Some commands may be followed by a variable-length payload. For these, the 52 /// [`CommandToGsp::variable_payload_len`] and [`CommandToGsp::init_variable_payload`] need to be 53 /// defined as well. 54 pub(crate) trait CommandToGsp { 55 /// Function identifying this command to the GSP. 56 const FUNCTION: MsgFunction; 57 58 /// Type generated by [`CommandToGsp::init`], to be written into the command queue buffer. 59 type Command: FromBytes + AsBytes; 60 61 /// Error type returned by [`CommandToGsp::init`]. 62 type InitError; 63 64 /// In-place command initializer responsible for filling the command in the command queue 65 /// buffer. 66 fn init(&self) -> impl Init<Self::Command, Self::InitError>; 67 68 /// Size of the variable-length payload following the command structure generated by 69 /// [`CommandToGsp::init`]. 70 /// 71 /// Most commands don't have a variable-length payload, so this is zero by default. 72 fn variable_payload_len(&self) -> usize { 73 0 74 } 75 76 /// Method initializing the variable-length payload. 77 /// 78 /// The command buffer is circular, which means that we may need to jump back to its beginning 79 /// while in the middle of a command. For this reason, the variable-length payload is 80 /// initialized using a [`SBufferIter`]. 81 /// 82 /// This method will receive a buffer of the length returned by 83 /// [`CommandToGsp::variable_payload_len`], and must write every single byte of it. Leaving 84 /// unwritten space will lead to an error. 85 /// 86 /// Most commands don't have a variable-length payload, so this does nothing by default. 87 fn init_variable_payload( 88 &self, 89 _dst: &mut SBufferIter<core::array::IntoIter<&mut [u8], 2>>, 90 ) -> Result { 91 Ok(()) 92 } 93 } 94 95 /// Trait representing messages received from the GSP. 96 /// 97 /// This trait tells [`Cmdq::receive_msg`] how it can receive a given type of message. 98 pub(crate) trait MessageFromGsp: Sized { 99 /// Function identifying this message from the GSP. 100 const FUNCTION: MsgFunction; 101 102 /// Error type returned by [`MessageFromGsp::read`]. 103 type InitError; 104 105 /// Type containing the raw message to be read from the message queue. 106 type Message: FromBytes; 107 108 /// Method reading the message from the message queue and returning it. 109 /// 110 /// From a `Self::Message` and a [`SBufferIter`], constructs an instance of `Self` and returns 111 /// it. 112 fn read( 113 msg: &Self::Message, 114 sbuffer: &mut SBufferIter<core::array::IntoIter<&[u8], 2>>, 115 ) -> Result<Self, Self::InitError>; 116 } 117 118 /// Number of GSP pages making the [`Msgq`]. 119 pub(crate) const MSGQ_NUM_PAGES: u32 = 0x3f; 120 121 /// Circular buffer of a [`Msgq`]. 122 /// 123 /// This area of memory is to be shared between the driver and the GSP to exchange commands or 124 /// messages. 125 #[repr(C, align(0x1000))] 126 #[derive(Debug)] 127 struct MsgqData { 128 data: [[u8; GSP_PAGE_SIZE]; num::u32_as_usize(MSGQ_NUM_PAGES)], 129 } 130 131 // Annoyingly we are forced to use a literal to specify the alignment of 132 // `MsgqData`, so check that it corresponds to the actual GSP page size here. 133 static_assert!(align_of::<MsgqData>() == GSP_PAGE_SIZE); 134 135 /// Unidirectional message queue. 136 /// 137 /// Contains the data for a message queue, that either the driver or GSP writes to. 138 /// 139 /// Note that while the write pointer of `tx` corresponds to the `msgq` of the same instance, the 140 /// read pointer of `rx` actually refers to the `Msgq` owned by the other side. 141 /// This design ensures that only the driver or GSP ever writes to a given instance of this struct. 142 #[repr(C)] 143 // There is no struct defined for this in the open-gpu-kernel-source headers. 144 // Instead it is defined by code in `GspMsgQueuesInit()`. 145 struct Msgq { 146 /// Header for sending messages, including the write pointer. 147 tx: MsgqTxHeader, 148 /// Header for receiving messages, including the read pointer. 149 rx: MsgqRxHeader, 150 /// The message queue proper. 151 msgq: MsgqData, 152 } 153 154 /// Structure shared between the driver and the GSP and containing the command and message queues. 155 #[repr(C)] 156 struct GspMem { 157 /// Self-mapping page table entries. 158 ptes: PteArray<{ GSP_PAGE_SIZE / size_of::<u64>() }>, 159 /// CPU queue: the driver writes commands here, and the GSP reads them. It also contains the 160 /// write and read pointers that the CPU updates. 161 /// 162 /// This member is read-only for the GSP. 163 cpuq: Msgq, 164 /// GSP queue: the GSP writes messages here, and the driver reads them. It also contains the 165 /// write and read pointers that the GSP updates. 166 /// 167 /// This member is read-only for the driver. 168 gspq: Msgq, 169 } 170 171 // SAFETY: These structs don't meet the no-padding requirements of AsBytes but 172 // that is not a problem because they are not used outside the kernel. 173 unsafe impl AsBytes for GspMem {} 174 175 // SAFETY: These structs don't meet the no-padding requirements of FromBytes but 176 // that is not a problem because they are not used outside the kernel. 177 unsafe impl FromBytes for GspMem {} 178 179 /// Wrapper around [`GspMem`] to share it with the GPU using a [`CoherentAllocation`]. 180 /// 181 /// This provides the low-level functionality to communicate with the GSP, including allocation of 182 /// queue space to write messages to and management of read/write pointers. 183 /// 184 /// This is shared with the GSP, with clear ownership rules regarding the command queues: 185 /// 186 /// * The driver owns (i.e. can write to) the part of the CPU message queue between the CPU write 187 /// pointer and the GSP read pointer. This region is returned by [`Self::driver_write_area`]. 188 /// * The driver owns (i.e. can read from) the part of the GSP message queue between the CPU read 189 /// pointer and the GSP write pointer. This region is returned by [`Self::driver_read_area`]. 190 struct DmaGspMem(CoherentAllocation<GspMem>); 191 192 impl DmaGspMem { 193 /// Allocate a new instance and map it for `dev`. 194 fn new(dev: &device::Device<device::Bound>) -> Result<Self> { 195 const MSGQ_SIZE: u32 = num::usize_into_u32::<{ size_of::<Msgq>() }>(); 196 const RX_HDR_OFF: u32 = num::usize_into_u32::<{ mem::offset_of!(Msgq, rx) }>(); 197 198 let gsp_mem = 199 CoherentAllocation::<GspMem>::alloc_coherent(dev, 1, GFP_KERNEL | __GFP_ZERO)?; 200 dma_write!(gsp_mem[0].ptes = PteArray::new(gsp_mem.dma_handle())?)?; 201 dma_write!(gsp_mem[0].cpuq.tx = MsgqTxHeader::new(MSGQ_SIZE, RX_HDR_OFF, MSGQ_NUM_PAGES))?; 202 dma_write!(gsp_mem[0].cpuq.rx = MsgqRxHeader::new())?; 203 204 Ok(Self(gsp_mem)) 205 } 206 207 /// Returns the region of the CPU message queue that the driver is currently allowed to write 208 /// to. 209 /// 210 /// As the message queue is a circular buffer, the region may be discontiguous in memory. In 211 /// that case the second slice will have a non-zero length. 212 fn driver_write_area(&mut self) -> (&mut [[u8; GSP_PAGE_SIZE]], &mut [[u8; GSP_PAGE_SIZE]]) { 213 let tx = self.cpu_write_ptr() as usize; 214 let rx = self.gsp_read_ptr() as usize; 215 216 // SAFETY: 217 // - The `CoherentAllocation` contains exactly one object. 218 // - We will only access the driver-owned part of the shared memory. 219 // - Per the safety statement of the function, no concurrent access will be performed. 220 let gsp_mem = &mut unsafe { self.0.as_slice_mut(0, 1) }.unwrap()[0]; 221 // PANIC: per the invariant of `cpu_write_ptr`, `tx` is `<= MSGQ_NUM_PAGES`. 222 let (before_tx, after_tx) = gsp_mem.cpuq.msgq.data.split_at_mut(tx); 223 224 if rx <= tx { 225 // The area from `tx` up to the end of the ring, and from the beginning of the ring up 226 // to `rx`, minus one unit, belongs to the driver. 227 if rx == 0 { 228 let last = after_tx.len() - 1; 229 (&mut after_tx[..last], &mut before_tx[0..0]) 230 } else { 231 (after_tx, &mut before_tx[..rx]) 232 } 233 } else { 234 // The area from `tx` to `rx`, minus one unit, belongs to the driver. 235 // 236 // PANIC: per the invariants of `cpu_write_ptr` and `gsp_read_ptr`, `rx` and `tx` are 237 // `<= MSGQ_NUM_PAGES`, and the test above ensured that `rx > tx`. 238 (after_tx.split_at_mut(rx - tx).0, &mut before_tx[0..0]) 239 } 240 } 241 242 /// Returns the region of the GSP message queue that the driver is currently allowed to read 243 /// from. 244 /// 245 /// As the message queue is a circular buffer, the region may be discontiguous in memory. In 246 /// that case the second slice will have a non-zero length. 247 fn driver_read_area(&self) -> (&[[u8; GSP_PAGE_SIZE]], &[[u8; GSP_PAGE_SIZE]]) { 248 let tx = self.gsp_write_ptr() as usize; 249 let rx = self.cpu_read_ptr() as usize; 250 251 // SAFETY: 252 // - The `CoherentAllocation` contains exactly one object. 253 // - We will only access the driver-owned part of the shared memory. 254 // - Per the safety statement of the function, no concurrent access will be performed. 255 let gsp_mem = &unsafe { self.0.as_slice(0, 1) }.unwrap()[0]; 256 // PANIC: per the invariant of `cpu_read_ptr`, `xx` is `<= MSGQ_NUM_PAGES`. 257 let (before_rx, after_rx) = gsp_mem.gspq.msgq.data.split_at(rx); 258 259 match tx.cmp(&rx) { 260 cmp::Ordering::Equal => (&after_rx[0..0], &after_rx[0..0]), 261 cmp::Ordering::Greater => (&after_rx[..tx], &before_rx[0..0]), 262 cmp::Ordering::Less => (after_rx, &before_rx[..tx]), 263 } 264 } 265 266 /// Allocates a region on the command queue that is large enough to send a command of `size` 267 /// bytes. 268 /// 269 /// This returns a [`GspCommand`] ready to be written to by the caller. 270 /// 271 /// # Errors 272 /// 273 /// - `EAGAIN` if the driver area is too small to hold the requested command. 274 /// - `EIO` if the command header is not properly aligned. 275 fn allocate_command(&mut self, size: usize) -> Result<GspCommand<'_>> { 276 // Get the current writable area as an array of bytes. 277 let (slice_1, slice_2) = { 278 let (slice_1, slice_2) = self.driver_write_area(); 279 280 #[allow(clippy::incompatible_msrv)] 281 (slice_1.as_flattened_mut(), slice_2.as_flattened_mut()) 282 }; 283 284 // If the GSP is still processing previous messages the shared region 285 // may be full in which case we will have to retry once the GSP has 286 // processed the existing commands. 287 if size_of::<GspMsgElement>() + size > slice_1.len() + slice_2.len() { 288 return Err(EAGAIN); 289 } 290 291 // Extract area for the `GspMsgElement`. 292 let (header, slice_1) = GspMsgElement::from_bytes_mut_prefix(slice_1).ok_or(EIO)?; 293 294 // Create the contents area. 295 let (slice_1, slice_2) = if slice_1.len() > size { 296 // Contents fits entirely in `slice_1`. 297 (&mut slice_1[..size], &mut slice_2[0..0]) 298 } else { 299 // Need all of `slice_1` and some of `slice_2`. 300 let slice_2_len = size - slice_1.len(); 301 (slice_1, &mut slice_2[..slice_2_len]) 302 }; 303 304 Ok(GspCommand { 305 header, 306 contents: (slice_1, slice_2), 307 }) 308 } 309 310 // Returns the index of the memory page the GSP will write the next message to. 311 // 312 // # Invariants 313 // 314 // - The returned value is between `0` and `MSGQ_NUM_PAGES`. 315 fn gsp_write_ptr(&self) -> u32 { 316 let gsp_mem = self.0.start_ptr(); 317 318 // SAFETY: 319 // - The 'CoherentAllocation' contains at least one object. 320 // - By the invariants of `CoherentAllocation` the pointer is valid. 321 (unsafe { (*gsp_mem).gspq.tx.write_ptr() } % MSGQ_NUM_PAGES) 322 } 323 324 // Returns the index of the memory page the GSP will read the next command from. 325 // 326 // # Invariants 327 // 328 // - The returned value is between `0` and `MSGQ_NUM_PAGES`. 329 fn gsp_read_ptr(&self) -> u32 { 330 let gsp_mem = self.0.start_ptr(); 331 332 // SAFETY: 333 // - The 'CoherentAllocation' contains at least one object. 334 // - By the invariants of `CoherentAllocation` the pointer is valid. 335 (unsafe { (*gsp_mem).gspq.rx.read_ptr() } % MSGQ_NUM_PAGES) 336 } 337 338 // Returns the index of the memory page the CPU can read the next message from. 339 // 340 // # Invariants 341 // 342 // - The returned value is between `0` and `MSGQ_NUM_PAGES`. 343 fn cpu_read_ptr(&self) -> u32 { 344 let gsp_mem = self.0.start_ptr(); 345 346 // SAFETY: 347 // - The ['CoherentAllocation'] contains at least one object. 348 // - By the invariants of CoherentAllocation the pointer is valid. 349 (unsafe { (*gsp_mem).cpuq.rx.read_ptr() } % MSGQ_NUM_PAGES) 350 } 351 352 // Informs the GSP that it can send `elem_count` new pages into the message queue. 353 fn advance_cpu_read_ptr(&mut self, elem_count: u32) { 354 let rptr = self.cpu_read_ptr().wrapping_add(elem_count) % MSGQ_NUM_PAGES; 355 356 // Ensure read pointer is properly ordered. 357 fence(Ordering::SeqCst); 358 359 let gsp_mem = self.0.start_ptr_mut(); 360 361 // SAFETY: 362 // - The 'CoherentAllocation' contains at least one object. 363 // - By the invariants of `CoherentAllocation` the pointer is valid. 364 unsafe { (*gsp_mem).cpuq.rx.set_read_ptr(rptr) }; 365 } 366 367 // Returns the index of the memory page the CPU can write the next command to. 368 // 369 // # Invariants 370 // 371 // - The returned value is between `0` and `MSGQ_NUM_PAGES`. 372 fn cpu_write_ptr(&self) -> u32 { 373 let gsp_mem = self.0.start_ptr(); 374 375 // SAFETY: 376 // - The 'CoherentAllocation' contains at least one object. 377 // - By the invariants of `CoherentAllocation` the pointer is valid. 378 (unsafe { (*gsp_mem).cpuq.tx.write_ptr() } % MSGQ_NUM_PAGES) 379 } 380 381 // Informs the GSP that it can process `elem_count` new pages from the command queue. 382 fn advance_cpu_write_ptr(&mut self, elem_count: u32) { 383 let wptr = self.cpu_write_ptr().wrapping_add(elem_count) & MSGQ_NUM_PAGES; 384 let gsp_mem = self.0.start_ptr_mut(); 385 386 // SAFETY: 387 // - The 'CoherentAllocation' contains at least one object. 388 // - By the invariants of `CoherentAllocation` the pointer is valid. 389 unsafe { (*gsp_mem).cpuq.tx.set_write_ptr(wptr) }; 390 391 // Ensure all command data is visible before triggering the GSP read. 392 fence(Ordering::SeqCst); 393 } 394 } 395 396 /// A command ready to be sent on the command queue. 397 /// 398 /// This is the type returned by [`DmaGspMem::allocate_command`]. 399 struct GspCommand<'a> { 400 // Writable reference to the header of the command. 401 header: &'a mut GspMsgElement, 402 // Writable slices to the contents of the command. The second slice is zero unless the command 403 // loops over the command queue. 404 contents: (&'a mut [u8], &'a mut [u8]), 405 } 406 407 /// A message ready to be processed from the message queue. 408 /// 409 /// This is the type returned by [`Cmdq::wait_for_msg`]. 410 struct GspMessage<'a> { 411 // Reference to the header of the message. 412 header: &'a GspMsgElement, 413 // Slices to the contents of the message. The second slice is zero unless the message loops 414 // over the message queue. 415 contents: (&'a [u8], &'a [u8]), 416 } 417 418 /// GSP command queue. 419 /// 420 /// Provides the ability to send commands and receive messages from the GSP using a shared memory 421 /// area. 422 pub(crate) struct Cmdq { 423 /// Device this command queue belongs to. 424 dev: ARef<device::Device>, 425 /// Current command sequence number. 426 seq: u32, 427 /// Memory area shared with the GSP for communicating commands and messages. 428 gsp_mem: DmaGspMem, 429 } 430 431 impl Cmdq { 432 /// Creates a new command queue for `dev`. 433 pub(crate) fn new(dev: &device::Device<device::Bound>) -> Result<Cmdq> { 434 let gsp_mem = DmaGspMem::new(dev)?; 435 436 Ok(Cmdq { 437 dev: dev.into(), 438 seq: 0, 439 gsp_mem, 440 }) 441 } 442 443 /// Computes the checksum for the message pointed to by `it`. 444 /// 445 /// A message is made of several parts, so `it` is an iterator over byte slices representing 446 /// these parts. 447 fn calculate_checksum<T: Iterator<Item = u8>>(it: T) -> u32 { 448 let sum64 = it 449 .enumerate() 450 .map(|(idx, byte)| (((idx % 8) * 8) as u32, byte)) 451 .fold(0, |acc, (rol, byte)| acc ^ u64::from(byte).rotate_left(rol)); 452 453 ((sum64 >> 32) as u32) ^ (sum64 as u32) 454 } 455 456 /// Notifies the GSP that we have updated the command queue pointers. 457 fn notify_gsp(bar: &Bar0) { 458 regs::NV_PGSP_QUEUE_HEAD::default() 459 .set_address(0) 460 .write(bar); 461 } 462 463 /// Sends `command` to the GSP. 464 /// 465 /// # Errors 466 /// 467 /// - `EAGAIN` if there was not enough space in the command queue to send the command. 468 /// - `EIO` if the variable payload requested by the command has not been entirely 469 /// written to by its [`CommandToGsp::init_variable_payload`] method. 470 /// 471 /// Error codes returned by the command initializers are propagated as-is. 472 #[expect(unused)] 473 pub(crate) fn send_command<M>(&mut self, bar: &Bar0, command: M) -> Result 474 where 475 M: CommandToGsp, 476 // This allows all error types, including `Infallible`, to be used for `M::InitError`. 477 Error: From<M::InitError>, 478 { 479 let command_size = size_of::<M::Command>() + command.variable_payload_len(); 480 let dst = self.gsp_mem.allocate_command(command_size)?; 481 482 // Extract area for the command itself. 483 let (cmd, payload_1) = M::Command::from_bytes_mut_prefix(dst.contents.0).ok_or(EIO)?; 484 485 // Fill the header and command in-place. 486 let msg_element = GspMsgElement::init(self.seq, command_size, M::FUNCTION); 487 // SAFETY: `msg_header` and `cmd` are valid references, and not touched if the initializer 488 // fails. 489 unsafe { 490 msg_element.__init(core::ptr::from_mut(dst.header))?; 491 command.init().__init(core::ptr::from_mut(cmd))?; 492 } 493 494 // Fill the variable-length payload. 495 if command_size > size_of::<M::Command>() { 496 let mut sbuffer = 497 SBufferIter::new_writer([&mut payload_1[..], &mut dst.contents.1[..]]); 498 command.init_variable_payload(&mut sbuffer)?; 499 500 if !sbuffer.is_empty() { 501 return Err(EIO); 502 } 503 } 504 505 // Compute checksum now that the whole message is ready. 506 dst.header 507 .set_checksum(Cmdq::calculate_checksum(SBufferIter::new_reader([ 508 dst.header.as_bytes(), 509 dst.contents.0, 510 dst.contents.1, 511 ]))); 512 513 dev_dbg!( 514 &self.dev, 515 "GSP RPC: send: seq# {}, function={}, length=0x{:x}\n", 516 self.seq, 517 M::FUNCTION, 518 dst.header.length(), 519 ); 520 521 // All set - update the write pointer and inform the GSP of the new command. 522 let elem_count = dst.header.element_count(); 523 self.seq += 1; 524 self.gsp_mem.advance_cpu_write_ptr(elem_count); 525 Cmdq::notify_gsp(bar); 526 527 Ok(()) 528 } 529 530 /// Wait for a message to become available on the message queue. 531 /// 532 /// This works purely at the transport layer and does not interpret or validate the message 533 /// beyond the advertised length in its [`GspMsgElement`]. 534 /// 535 /// This method returns: 536 /// 537 /// - A reference to the [`GspMsgElement`] of the message, 538 /// - Two byte slices with the contents of the message. The second slice is empty unless the 539 /// message loops across the message queue. 540 /// 541 /// # Errors 542 /// 543 /// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. 544 /// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the 545 /// message queue. 546 /// 547 /// Error codes returned by the message constructor are propagated as-is. 548 fn wait_for_msg(&self, timeout: Delta) -> Result<GspMessage<'_>> { 549 // Wait for a message to arrive from the GSP. 550 let (slice_1, slice_2) = read_poll_timeout( 551 || Ok(self.gsp_mem.driver_read_area()), 552 |driver_area| !driver_area.0.is_empty(), 553 Delta::from_millis(1), 554 timeout, 555 ) 556 .map(|(slice_1, slice_2)| { 557 #[allow(clippy::incompatible_msrv)] 558 (slice_1.as_flattened(), slice_2.as_flattened()) 559 })?; 560 561 // Extract the `GspMsgElement`. 562 let (header, slice_1) = GspMsgElement::from_bytes_prefix(slice_1).ok_or(EIO)?; 563 564 dev_dbg!( 565 self.dev, 566 "GSP RPC: receive: seq# {}, function={:?}, length=0x{:x}\n", 567 header.sequence(), 568 header.function(), 569 header.length(), 570 ); 571 572 // Check that the driver read area is large enough for the message. 573 if slice_1.len() + slice_2.len() < header.length() { 574 return Err(EIO); 575 } 576 577 // Cut the message slices down to the actual length of the message. 578 let (slice_1, slice_2) = if slice_1.len() > header.length() { 579 // PANIC: we checked above that `slice_1` is at least as long as `msg_header.length()`. 580 (slice_1.split_at(header.length()).0, &slice_2[0..0]) 581 } else { 582 ( 583 slice_1, 584 // PANIC: we checked above that `slice_1.len() + slice_2.len()` is at least as 585 // large as `msg_header.length()`. 586 slice_2.split_at(header.length() - slice_1.len()).0, 587 ) 588 }; 589 590 // Validate checksum. 591 if Cmdq::calculate_checksum(SBufferIter::new_reader([ 592 header.as_bytes(), 593 slice_1, 594 slice_2, 595 ])) != 0 596 { 597 dev_err!( 598 self.dev, 599 "GSP RPC: receive: Call {} - bad checksum", 600 header.sequence() 601 ); 602 return Err(EIO); 603 } 604 605 Ok(GspMessage { 606 header, 607 contents: (slice_1, slice_2), 608 }) 609 } 610 611 /// Receive a message from the GSP. 612 /// 613 /// `init` is a closure tasked with processing the message. It receives a reference to the 614 /// message in the message queue, and a [`SBufferIter`] pointing to its variable-length 615 /// payload, if any. 616 /// 617 /// The expected message is specified using the `M` generic parameter. If the pending message 618 /// is different, `EAGAIN` is returned and the unexpected message is dropped. 619 /// 620 /// This design is by no means final, but it is simple and will let us go through GSP 621 /// initialization. 622 /// 623 /// # Errors 624 /// 625 /// - `ETIMEDOUT` if `timeout` has elapsed before any message becomes available. 626 /// - `EIO` if there was some inconsistency (e.g. message shorter than advertised) on the 627 /// message queue. 628 /// - `EINVAL` if the function of the message was unrecognized. 629 #[expect(unused)] 630 pub(crate) fn receive_msg<M: MessageFromGsp>(&mut self, timeout: Delta) -> Result<M> 631 where 632 // This allows all error types, including `Infallible`, to be used for `M::InitError`. 633 Error: From<M::InitError>, 634 { 635 let message = self.wait_for_msg(timeout)?; 636 let function = message.header.function().map_err(|_| EINVAL)?; 637 638 // Extract the message. Store the result as we want to advance the read pointer even in 639 // case of failure. 640 let result = if function == M::FUNCTION { 641 let (cmd, contents_1) = M::Message::from_bytes_prefix(message.contents.0).ok_or(EIO)?; 642 let mut sbuffer = SBufferIter::new_reader([contents_1, message.contents.1]); 643 644 M::read(cmd, &mut sbuffer).map_err(|e| e.into()) 645 } else { 646 Err(ERANGE) 647 }; 648 649 // Advance the read pointer past this message. 650 self.gsp_mem.advance_cpu_read_ptr(u32::try_from( 651 message.header.length().div_ceil(GSP_PAGE_SIZE), 652 )?); 653 654 result 655 } 656 } 657