scsir 0.3.0

A simple library for issuing SCSI commands
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#![allow(dead_code)]

use std::mem::size_of;

use modular_bitfield_msb::prelude::*;

use crate::{
    command::{bitfield_bound_check, get_array},
    data_wrapper::{AnyType, VecBufferWrapper},
    result_data::ResultData,
    Command, DataDirection, Scsi,
};

#[derive(Clone, Debug)]
pub struct PersistentReserveInCommand<'a> {
    interface: &'a Scsi,
    service_action: ServiceAction,
    command_buffer: CommandBuffer,
}

#[derive(Clone, Copy, Debug)]
pub enum ServiceAction {
    ReadKeys,
    ReadReservation,
    ReportCapabilities,
    ReadFullStatus,
    Other(u8),
}

pub enum CommandResult {
    ReadKeys(ReadKeysData),
    ReadReservation(ReadReservationData),
    ReportCapabilities(ReportCapabilitiesData),
    ReadFullStatus(ReadFullStatusData),
    Raw(Vec<u8>),
}

pub struct ReadKeysData {
    pub persistent_reservations_generation: u32,
    pub required_length: u32,
    pub reservation_keys: Vec<u64>,
}

pub struct ReadReservationData {
    pub persistent_reservations_generation: u32,
    pub reservation_key: u64,
    pub reservation_scope: u8,
    pub reservation_type: u8,
}

pub struct ReportCapabilitiesData {
    pub replace_lost_reservation_capable: bool,
    pub compatible_reservation_handling: bool,
    pub specify_initiator_ports_capable: bool,
    pub target_ports_capable: bool,
    pub persist_through_power_loss_capable: bool,
    pub type_mask_valid: bool,
    pub allow_commands: u8,
    pub persist_through_power_loss_activated: bool,
    pub write_exclusive_all_registrants: bool,
    pub exclusive_access_registrants_only: bool,
    pub write_exclusive_registrants_only: bool,
    pub exclusive_access: bool,
    pub write_exclusive: bool,
    pub exclusive_access_all_registrants: bool,
}

pub struct ReadFullStatusData {
    pub persistent_reservations_generation: u32,
    pub required_length: u32,
    pub descriptors: Vec<ReadFullStatusDescriptor>,
}

pub struct ReadFullStatusDescriptor {
    pub reservation_key: u64,
    pub all_target_ports: bool,
    pub reservation_holder: bool,
    pub reservation_scope: u8,
    pub reservation_type: u8,
    pub relative_target_port_identifier: u16,
    pub transportid: Vec<u8>,
}

impl<'a> PersistentReserveInCommand<'a> {
    fn new(interface: &'a Scsi) -> Self {
        Self {
            interface,
            service_action: ServiceAction::ReadKeys,
            command_buffer: CommandBuffer::new().with_operation_code(OPERATION_CODE),
        }
    }

    // service_action must be less than 0x20
    pub fn service_action(&mut self, value: ServiceAction) -> &mut Self {
        self.service_action = value;
        self
    }

    pub fn allocation_length(&mut self, value: u16) -> &mut Self {
        self.command_buffer.set_allocation_length(value);
        self
    }

    pub fn control(&mut self, value: u8) -> &mut Self {
        self.command_buffer.set_control(value);
        self
    }

    pub fn issue(&mut self) -> crate::Result<CommandResult> {
        bitfield_bound_check!(u8::from(self.service_action), 5, "service action")?;
        self.command_buffer
            .set_service_action(self.service_action.into());

        let temp = ThisCommand {
            command_buffer: self.command_buffer,
            service_action: self.service_action,
        };
        self.interface.issue(&temp)
    }
}

impl Scsi {
    pub fn persistent_reserve_in(&self) -> PersistentReserveInCommand<'_> {
        PersistentReserveInCommand::new(self)
    }
}

impl ReadKeysData {
    fn from_bytes(bytes: &[u8]) -> Self {
        let (array, bytes) = get_array(bytes);
        let persistent_reservations_generation = u32::from_be_bytes(array);

        let (array, bytes) = get_array(bytes);
        let additional_length = u32::from_be_bytes(array);
        let required_length = additional_length.saturating_add(8);

        let mut reservation_keys = vec![];

        for chunk in bytes.chunks(size_of::<u64>()) {
            reservation_keys.push(u64::from_be_bytes(get_array(chunk).0))
        }

        Self {
            persistent_reservations_generation,
            required_length,
            reservation_keys,
        }
    }
}

impl ReadReservationData {
    fn from_bytes(bytes: &[u8]) -> Self {
        let (array, _) = get_array(bytes);
        let data = ReadReservationBitfield::from_bytes(array);

        Self {
            persistent_reservations_generation: data.persistent_reservations_generation(),
            reservation_key: data.reservation_key(),
            reservation_scope: data.reservation_scope(),
            reservation_type: data.reservation_type(),
        }
    }
}

impl ReportCapabilitiesData {
    fn from_bytes(bytes: &[u8]) -> Self {
        let (array, _) = get_array(bytes);
        let data = ReportCapabilitiesBitfield::from_bytes(array);

        Self {
            replace_lost_reservation_capable: data.replace_lost_reservation_capable() != 0,
            compatible_reservation_handling: data.compatible_reservation_handling() != 0,
            specify_initiator_ports_capable: data.specify_initiator_ports_capable() != 0,
            target_ports_capable: data.target_ports_capable() != 0,
            persist_through_power_loss_capable: data.persist_through_power_loss_capable() != 0,
            type_mask_valid: data.type_mask_valid() != 0,
            allow_commands: data.allow_commands(),
            persist_through_power_loss_activated: data.persist_through_power_loss_activated() != 0,
            write_exclusive_all_registrants: data.write_exclusive_all_registrants() != 0,
            exclusive_access_registrants_only: data.exclusive_access_registrants_only() != 0,
            write_exclusive_registrants_only: data.write_exclusive_registrants_only() != 0,
            exclusive_access: data.exclusive_access() != 0,
            write_exclusive: data.write_exclusive() != 0,
            exclusive_access_all_registrants: data.exclusive_access_all_registrants() != 0,
        }
    }
}

impl ReadFullStatusData {
    fn from_bytes(bytes: &[u8]) -> Self {
        let (array, mut bytes) = get_array(bytes);
        let header = ReadFullsstatusHeaderBitfield::from_bytes(array);

        let mut descriptors = vec![];

        while !bytes.is_empty() {
            let (array, left_bytes) = get_array(bytes);
            let descriptor_header = ReadFullsstatusDescriptorHeaderBitfield::from_bytes(array);
            let additional_descriptor_length = usize::min(
                descriptor_header.additional_descriptor_length() as usize,
                left_bytes.len(),
            );
            let transportid = Vec::from(&left_bytes[..additional_descriptor_length]);

            let descriptor = ReadFullStatusDescriptor {
                reservation_key: descriptor_header.reservation_key(),
                all_target_ports: descriptor_header.all_target_ports() != 0,
                reservation_holder: descriptor_header.reservation_holder() != 0,
                reservation_scope: descriptor_header.reservation_scope(),
                reservation_type: descriptor_header.reservation_type(),
                relative_target_port_identifier: descriptor_header
                    .relative_target_port_identifier(),
                transportid,
            };

            descriptors.push(descriptor);
            bytes = &left_bytes[additional_descriptor_length..];
        }

        Self {
            persistent_reservations_generation: header.persistent_reservations_generation(),
            required_length: header.additional_length().saturating_add(8),
            descriptors,
        }
    }
}

impl From<ServiceAction> for u8 {
    fn from(value: ServiceAction) -> Self {
        match value {
            ServiceAction::ReadKeys => 0x00,
            ServiceAction::ReadReservation => 0x01,
            ServiceAction::ReportCapabilities => 0x02,
            ServiceAction::ReadFullStatus => 0x03,
            ServiceAction::Other(x) => x,
        }
    }
}

#[bitfield]
#[derive(Clone, Copy)]
struct ReadReservationBitfield {
    persistent_reservations_generation: B32,
    additional_length: B32,
    reservation_key: B64,
    obsolete_0: B32,
    reserved: B8,
    reservation_scope: B4,
    reservation_type: B4,
    obsolete_1: B16,
}

#[bitfield]
#[derive(Clone, Copy)]
struct ReportCapabilitiesBitfield {
    length: B16,
    replace_lost_reservation_capable: B1,
    reserved_0: B2,
    compatible_reservation_handling: B1,
    specify_initiator_ports_capable: B1,
    target_ports_capable: B1,
    reserved_1: B1,
    persist_through_power_loss_capable: B1,
    type_mask_valid: B1,
    allow_commands: B3,
    reserved_2: B3,
    persist_through_power_loss_activated: B1,
    write_exclusive_all_registrants: B1,
    exclusive_access_registrants_only: B1,
    write_exclusive_registrants_only: B1,
    reserved_3: B1,
    exclusive_access: B1,
    reserved_4: B1,
    write_exclusive: B1,
    reserved_5: B1,
    reserved_6: B7,
    exclusive_access_all_registrants: B1,
    reserved_7: B16,
}

#[bitfield]
#[derive(Clone, Copy)]
struct ReadFullsstatusHeaderBitfield {
    persistent_reservations_generation: B32,
    additional_length: B32,
}

#[bitfield]
#[derive(Clone, Copy)]
struct ReadFullsstatusDescriptorHeaderBitfield {
    reservation_key: B64,
    reserved_0: B32,
    reserved_1: B6,
    all_target_ports: B1,
    reservation_holder: B1,
    reservation_scope: B4,
    reservation_type: B4,
    reserved_2: B32,
    relative_target_port_identifier: B16,
    additional_descriptor_length: B32,
}

const OPERATION_CODE: u8 = 0x5E;

#[bitfield]
#[derive(Clone, Copy, Debug)]
struct CommandBuffer {
    operation_code: B8,
    reserved_0: B3,
    service_action: B5,
    reserved_1: B40,
    allocation_length: B16,
    control: B8,
}

struct ThisCommand {
    command_buffer: CommandBuffer,
    service_action: ServiceAction,
}

impl Command for ThisCommand {
    type CommandBuffer = CommandBuffer;

    type DataBuffer = AnyType;

    type DataBufferWrapper = VecBufferWrapper;

    type ReturnType = crate::Result<CommandResult>;

    fn direction(&self) -> DataDirection {
        DataDirection::FromDevice
    }

    fn command(&self) -> Self::CommandBuffer {
        self.command_buffer
    }

    fn data(&self) -> Self::DataBufferWrapper {
        unsafe { VecBufferWrapper::with_len(self.command_buffer.allocation_length() as usize) }
    }

    fn data_size(&self) -> u32 {
        self.command_buffer.allocation_length() as u32
    }

    fn process_result(&self, result: ResultData<Self::DataBufferWrapper>) -> Self::ReturnType {
        result.check_ioctl_error()?;
        result.check_common_error()?;

        let bytes = &result.data()[..];

        Ok(match self.service_action {
            ServiceAction::ReadKeys => CommandResult::ReadKeys(ReadKeysData::from_bytes(bytes)),
            ServiceAction::ReadReservation => {
                CommandResult::ReadReservation(ReadReservationData::from_bytes(bytes))
            }
            ServiceAction::ReportCapabilities => {
                CommandResult::ReportCapabilities(ReportCapabilitiesData::from_bytes(bytes))
            }
            ServiceAction::ReadFullStatus => {
                CommandResult::ReadFullStatus(ReadFullStatusData::from_bytes(bytes))
            }
            ServiceAction::Other(_) => CommandResult::Raw(Vec::from(bytes)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::mem::size_of;

    const COMMAND_LENGTH: usize = 10;
    const READ_RESERVATION_BITFIELD_LENGTH: usize = 24;
    const REPORT_CAPABILITIES_BITFIELD_LENGTH: usize = 8;
    const READ_FULLSSTATUS_HEADER_BITFIELD_LENGTH: usize = 8;
    const READ_FULLSSTATUS_DESCRIPTOR_HEADER_BITFIELD_LENGTH: usize = 24;

    #[test]
    fn layout_test() {
        assert_eq!(
            size_of::<CommandBuffer>(),
            COMMAND_LENGTH,
            concat!("Size of: ", stringify!(CommandBuffer))
        );

        assert_eq!(
            size_of::<ReadReservationBitfield>(),
            READ_RESERVATION_BITFIELD_LENGTH,
            concat!("Size of: ", stringify!(ReadReservationBitfield))
        );

        assert_eq!(
            size_of::<ReportCapabilitiesBitfield>(),
            REPORT_CAPABILITIES_BITFIELD_LENGTH,
            concat!("Size of: ", stringify!(ReportCapabilitiesBitfield))
        );

        assert_eq!(
            size_of::<ReadFullsstatusHeaderBitfield>(),
            READ_FULLSSTATUS_HEADER_BITFIELD_LENGTH,
            concat!("Size of: ", stringify!(ReadFullsstatusHeaderBitfield))
        );

        assert_eq!(
            size_of::<ReadFullsstatusDescriptorHeaderBitfield>(),
            READ_FULLSSTATUS_DESCRIPTOR_HEADER_BITFIELD_LENGTH,
            concat!(
                "Size of: ",
                stringify!(ReadFullsstatusDescriptorHeaderBitfield)
            )
        );
    }
}