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
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]

extern crate libc;
#[cfg(feature = "polling")]
extern crate mio;
extern crate nix;

#[cfg(feature = "polling")]
use mio::event::Evented;
#[cfg(feature = "polling")]
use mio::unix::EventedFd;
#[cfg(feature = "polling")]
use mio::{Poll, PollOpt, Ready, Token};
use nix::sys::uio;
use std::fs::{File, OpenOptions};
use std::io;
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use std::time::Duration;

///
pub mod sys {
    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
    pub const SG_FLAG_Q_AT_TAIL: u32 = 0x10;
}

///
#[derive(Debug, Copy, Clone)]
pub enum Direction {
    None,
    ToDevice,
    FromDevice,
    ToFromDevice,
}

impl Direction {
    fn to_underlying(self) -> std::os::raw::c_int {
        match self {
            Direction::None => sys::SG_DXFER_NONE,
            Direction::ToDevice => sys::SG_DXFER_TO_DEV,
            Direction::FromDevice => sys::SG_DXFER_FROM_DEV,
            Direction::ToFromDevice => sys::SG_DXFER_TO_FROM_DEV,
        }
    }
}

///
#[derive(Copy, Clone, Debug, Default)]
pub struct Task(sys::sg_io_hdr);

impl Task {
    ///
    pub fn new() -> Self {
        Task(sys::sg_io_hdr {
            interface_id: 'S' as std::os::raw::c_int,
            dxfer_direction: sys::SG_DXFER_NONE,
            ..Default::default()
        })
    }

    fn from_underlying(sg: sys::sg_io_hdr) -> Self {
        Task(sg)
    }

    ///
    pub fn set_cdb(&mut self, buf: &[u8]) -> &mut Self {
        self.0.cmdp = buf.as_ptr() as *mut u8;
        self.0.cmd_len = buf.len() as u8;
        self
    }

    ///
    pub fn cdb(&self) -> &[u8] {
        unsafe { std::slice::from_raw_parts(self.0.cmdp, self.0.cmd_len as usize) }
    }

    ///
    pub fn set_timeout(&mut self, timeout: Duration) -> &mut Self {
        self.0.timeout =
            (timeout.as_secs() * 1_000 + (u64::from(timeout.subsec_nanos()) / 1_000_000)) as u32;
        self
    }

    ///
    pub fn timeout(&self) -> Duration {
        Duration::from_millis(self.0.timeout.into())
    }

    ///
    pub fn set_data(&mut self, buf: &[u8], direction: Direction) -> &mut Self {
        self.0.dxferp = buf.as_ptr() as *mut std::os::raw::c_void;
        self.0.dxfer_len = buf.len() as u32;
        self.0.dxfer_direction = direction.to_underlying();
        self
    }

    ///
    pub fn set_data_mut(&mut self, buf: &mut [u8], direction: Direction) -> &mut Self {
        self.0.dxferp = buf.as_ptr() as *mut std::os::raw::c_void;
        self.0.dxfer_len = buf.len() as u32;
        self.0.dxfer_direction = direction.to_underlying();
        self
    }

    ///
    pub fn data(&self) -> &[u8] {
        unsafe { std::slice::from_raw_parts(self.0.dxferp as *const u8, self.0.dxfer_len as usize) }
    }

    ///
    pub fn data_mut(&mut self) -> &mut [u8] {
        unsafe {
            std::slice::from_raw_parts_mut(self.0.dxferp as *mut u8, self.0.dxfer_len as usize)
        }
    }

    ///
    pub fn set_sense_buffer(&mut self, buf: &[u8]) -> &mut Self {
        self.0.sbp = buf.as_ptr() as *mut u8;
        self.0.mx_sb_len = buf.len() as u8;
        self
    }

    ///
    pub fn sense_buffer(&self) -> &[u8] {
        unsafe { std::slice::from_raw_parts(self.0.sbp, self.0.sb_len_wr as usize) }
    }

    ///
    pub fn set_flags(&mut self, flags: u32) -> &mut Self {
        self.0.flags = flags;
        self
    }

    ///
    pub fn flags(&self) -> u32 {
        self.0.flags
    }

    ///
    pub fn set_usr_ptr(&mut self, ptr: *const std::os::raw::c_void) -> &mut Self {
        self.0.usr_ptr = ptr as *mut std::os::raw::c_void;
        self
    }

    ///
    pub fn usr_ptr(&self) -> *const std::os::raw::c_void {
        self.0.usr_ptr as *const std::os::raw::c_void
    }

    ///
    pub fn duration(&self) -> u32 {
        self.0.duration
    }

    ///
    pub fn residual_data(&self) -> i32 {
        self.0.resid
    }

    ///
    pub fn status(&self) -> u8 {
        self.0.status
    }

    ///
    pub fn host_status(&self) -> u16 {
        self.0.host_status
    }

    ///
    pub fn driver_status(&self) -> u16 {
        self.0.driver_status
    }

    ///
    pub fn ok(&self) -> bool {
        (self.0.info & sys::SG_INFO_OK_MASK) == sys::SG_INFO_OK
    }
}

///
pub struct Device(File);

impl Device {
    pub fn open<P: AsRef<Path>>(path: P) -> io::Result<Device> {
        Ok(Device(
            OpenOptions::new()
                .read(true)
                .write(true)
                .custom_flags(libc::O_NONBLOCK)
                .open(path)?,
        ))
    }

    /// Returns the number of tasks successfully sent.
    pub fn send(&self, tasks: &[Task]) -> io::Result<usize> {
        if tasks.is_empty() {
            return Ok(0);
        }

        let mut iovecs: [uio::IoVec<&[u8]>; sys::SG_MAX_QUEUE as usize] =
            unsafe { std::mem::uninitialized() };
        for (task, mut iovec) in tasks.iter().zip(iovecs.iter_mut()) {
            *iovec = uio::IoVec::from_slice(unsafe {
                std::slice::from_raw_parts(
                    &task.0 as *const sys::sg_io_hdr as *const u8,
                    std::mem::size_of::<sys::sg_io_hdr>(),
                )
            });
        }

        loop {
            match uio::writev(self.0.as_raw_fd(), &iovecs[..tasks.len()]) {
                Ok(n) => break Ok(n / std::mem::size_of::<sys::sg_io_hdr>()),
                Err(nix::Error::Sys(ref e)) if e == &nix::errno::Errno::EINTR => {}
                Err(nix::Error::Sys(e)) => break Err(e.into()),
                _ => unreachable!(),
            }
        }
    }

    /// Returns the number of tasks received - how many were added to `tasks`.
    pub fn receive(&self, tasks: &mut Vec<Task>) -> io::Result<usize> {
        let mut hdrs: [sys::sg_io_hdr; sys::SG_MAX_QUEUE as usize] =
            unsafe { std::mem::uninitialized() };
        let mut iovecs: [uio::IoVec<&mut [u8]>; sys::SG_MAX_QUEUE as usize] =
            unsafe { std::mem::uninitialized() };

        for (mut hdr, mut iovec) in hdrs.iter_mut().zip(iovecs.iter_mut()) {
            *iovec = uio::IoVec::from_mut_slice(unsafe {
                std::slice::from_raw_parts_mut(
                    hdr as *mut sys::sg_io_hdr as *mut u8,
                    std::mem::size_of::<sys::sg_io_hdr>(),
                )
            });
        }

        let bytes_read = loop {
            match uio::readv(self.0.as_raw_fd(), &mut iovecs) {
                Ok(n) => break n,
                Err(nix::Error::Sys(ref e))
                    if e == &nix::errno::Errno::EINTR || e == &nix::errno::Errno::EAGAIN => {}
                Err(nix::Error::Sys(e)) => return Err(e.into()),
                _ => unreachable!(),
            }
        };

        assert!(bytes_read > 0);
        let tasks_read = bytes_read / std::mem::size_of::<sys::sg_io_hdr>();
        assert!(tasks_read > 0);
        tasks.extend(
            hdrs.into_iter()
                .map(|hdr| Task::from_underlying(*hdr))
                .take(tasks_read),
        );
        Ok(tasks_read)
    }

    ///
    pub fn perform(&self, task: &Task) -> io::Result<()> {
        #[cfg(target_env = "musl")]
        let request = sys::SG_IO as i32;
        #[cfg(not(target_env = "musl"))]
        let request: u64 = sys::SG_IO.into();

        let ret = unsafe { libc::ioctl(self.0.as_raw_fd(), request, &task.0) };
        if ret == -1 {
            Err(io::Error::last_os_error())
        } else {
            Ok(())
        }
    }
}

impl std::os::unix::io::AsRawFd for Device {
    fn as_raw_fd(&self) -> std::os::unix::io::RawFd {
        self.0.as_raw_fd()
    }
}

#[cfg(feature = "polling")]
impl Evented for Device {
    fn register(
        &self,
        poll: &Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        EventedFd(&self.0.as_raw_fd()).register(poll, token, interest, opts)
    }

    fn reregister(
        &self,
        poll: &Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        EventedFd(&self.0.as_raw_fd()).reregister(poll, token, interest, opts)
    }

    fn deregister(&self, poll: &Poll) -> io::Result<()> {
        EventedFd(&self.0.as_raw_fd()).deregister(poll)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_sys() {
        assert_eq!(super::sys::SG_IO, 0x2285);
    }

    #[test]
    fn test_task_fields() {
        let mut task = Task::new();
        let x = 42;
        assert_eq!(task.0.interface_id as u8 as char, 'S');
        task.set_usr_ptr(&x as *const i32 as *const std::os::raw::c_void);
        assert_eq!(task.usr_ptr() as *const i32, &x as *const i32);
        assert_eq!(unsafe { *(task.usr_ptr() as *const i32) }, x);
    }

    #[test]
    fn test_cdb() {
        let cdb = [0; 6];
        let mut task = Task::new();
        task.set_cdb(&cdb);
    }
}