use anyhow::{Result, anyhow, bail};
use tracing::warn;
use zerocopy::{
BigEndian, FromBytes as ZFromBytes, Immutable, IntoBytes, KnownLayout, U32,
};
use crate::{
client::pdu_connection::FromBytes,
models::{
common::{
BasicHeaderSegment, HEADER_LEN, InitiatorTaskTag, LogicalUnitNumber,
SendingData, TargetTaskTag,
},
data_fromat::ZeroCopyType,
opcode::{BhsOpcode, Opcode, RawBhsOpcode},
},
};
#[repr(C)]
#[derive(Debug, Default, PartialEq, ZFromBytes, IntoBytes, KnownLayout, Immutable)]
pub struct NopInResponse {
pub opcode: RawBhsOpcode, reserved1: [u8; 3], pub total_ahs_length: u8, pub data_segment_length: [u8; 3], pub lun: LogicalUnitNumber, pub initiator_task_tag: InitiatorTaskTag, pub target_task_tag: TargetTaskTag, pub stat_sn: U32<BigEndian>, pub exp_cmd_sn: U32<BigEndian>, pub max_cmd_sn: U32<BigEndian>, reserved2: [u8; 12], }
impl NopInResponse {
pub fn to_bhs_bytes(&self, buf: &mut [u8]) -> Result<()> {
if buf.len() != HEADER_LEN {
bail!("buffer length must be {HEADER_LEN}, got {}", buf.len());
}
buf.copy_from_slice(self.as_bytes());
Ok(())
}
pub fn from_bhs_bytes(buf: &mut [u8]) -> Result<&mut Self> {
let hdr = <Self as zerocopy::FromBytes>::mut_from_bytes(buf)
.map_err(|e| anyhow!("failed convert buffer NopInResponse: {e}"))?;
if hdr.opcode.opcode_known() != Some(Opcode::NopIn) {
bail!(
"NopInResponse: invalid opcode 0x{:02x}",
hdr.opcode.opcode_raw()
);
}
Ok(hdr)
}
}
impl SendingData for NopInResponse {
fn get_final_bit(&self) -> bool {
true
}
fn set_final_bit(&mut self) {
warn!("NopIn Response cannot be marked as Final");
}
fn get_continue_bit(&self) -> bool {
false
}
fn set_continue_bit(&mut self) {
warn!("NopIn Response cannot be marked as Contine");
}
}
impl FromBytes for NopInResponse {
fn from_bhs_bytes(bytes: &mut [u8]) -> Result<&mut Self> {
NopInResponse::from_bhs_bytes(bytes)
}
}
impl BasicHeaderSegment for NopInResponse {
#[inline]
fn to_bhs_bytes(&self, buf: &mut [u8]) -> Result<()> {
self.to_bhs_bytes(buf)
}
#[inline]
fn get_opcode(&self) -> Result<BhsOpcode> {
BhsOpcode::try_from(self.opcode.raw())
}
#[inline]
fn get_initiator_task_tag(&self) -> u32 {
self.initiator_task_tag.get()
}
#[inline]
fn get_ahs_length_bytes(&self) -> usize {
(self.total_ahs_length as usize) * 4
}
#[inline]
fn set_ahs_length_bytes(&mut self, len: u8) {
self.total_ahs_length = len >> 2;
}
#[inline]
fn get_data_length_bytes(&self) -> usize {
u32::from_be_bytes([
0,
self.data_segment_length[0],
self.data_segment_length[1],
self.data_segment_length[2],
]) as usize
}
#[inline]
fn set_data_length_bytes(&mut self, len: u32) {
let be = len.to_be_bytes();
self.data_segment_length = [be[1], be[2], be[3]];
}
}
impl ZeroCopyType for NopInResponse {}