rockusb 0.3.0

Rockchip usb protocol host implementation
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use std::marker::PhantomData;

use crate::protocol::{
    self, Capability, ChipInfo, CommandBlock, CommandStatus, CommandStatusParseError, Direction,
    FlashId, FlashInfo, ResetOpcode,
};
use thiserror::Error;

/// Errors for usb operations
#[derive(Debug, Clone, Eq, PartialEq, Error)]
pub enum UsbOperationError {
    #[error("Tag mismatch between command and status")]
    TagMismatch,
    #[error("Incorrect status Signature receveived: {0:?}")]
    InvalidStatusSignature([u8; 4]),
    #[error("Invalid status status: {0}")]
    InvalidStatusStatus(u8),
    #[error("Invalid status data length")]
    InvalidStatusLength,
    #[error("Failed to parse reply")]
    ReplyParseFailure,
    #[error("Device indicated operation failed")]
    FailedStatus,
}

impl From<CommandStatusParseError> for UsbOperationError {
    fn from(e: CommandStatusParseError) -> Self {
        match e {
            CommandStatusParseError::InvalidSignature(s) => {
                UsbOperationError::InvalidStatusSignature(s)
            }
            CommandStatusParseError::InvalidLength(_) => UsbOperationError::InvalidStatusLength,
            CommandStatusParseError::InvalidStatus(s) => UsbOperationError::InvalidStatusStatus(s),
        }
    }
}

/// Step to take by the transport implementation
#[derive(Debug, Eq, PartialEq)]
pub enum UsbStep<'a, T> {
    /// Write USB data using a control transfer
    WriteControl {
        request_type: u8,
        request: u8,
        value: u16,
        index: u16,
        data: &'a [u8],
    },
    /// Write USB data using a bulk transfer
    WriteBulk { data: &'a [u8] },
    /// Read USB data using a bulk transfer
    ReadBulk { data: &'a mut [u8] },
    /// Operation is finished with a given result or failure
    Finished(Result<T, UsbOperationError>),
}

/// steps to take to finish an operation
pub trait OperationSteps<T> {
    /// Next step to execute by a transport
    fn step(&mut self) -> UsbStep<T>;
}

enum MaskRomSteps {
    Writing(crc::Digest<'static, u16>),
    Dummy,
    Done,
}

/// Operations that can be executed when the SoC is in MaskRom mode
pub struct MaskRomOperation<'a> {
    written: usize,
    block: [u8; 4096],
    data: &'a [u8],
    area: u16,
    steps: MaskRomSteps,
}

const CRC: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_3740);
impl<'a> MaskRomOperation<'a> {
    fn new(area: u16, data: &'a [u8]) -> Self {
        Self {
            written: 0,
            block: [0; 4096],
            data,
            area,
            steps: MaskRomSteps::Writing(CRC.digest()),
        }
    }
}

impl OperationSteps<()> for MaskRomOperation<'_> {
    fn step(&mut self) -> UsbStep<()> {
        let mut current = MaskRomSteps::Done;
        std::mem::swap(&mut self.steps, &mut current);
        match current {
            MaskRomSteps::Writing(mut crc) => {
                let chunksize = 4096.min(self.data.len() - self.written);
                self.block[..chunksize]
                    .copy_from_slice(&self.data[self.written..self.written + chunksize]);
                self.written += chunksize;
                let chunk = match chunksize {
                    4096 => {
                        crc.update(&self.block);
                        self.steps = MaskRomSteps::Writing(crc);
                        &self.block[..]
                    }
                    4095 => {
                        // Add extra 0 to avoid splitting crc over two blocks
                        self.block[4095] = 0;
                        crc.update(&self.block);
                        self.steps = MaskRomSteps::Writing(crc);
                        &self.block[..]
                    }
                    mut end => {
                        crc.update(&self.block[0..end]);
                        let crc = crc.finalize();
                        self.block[end] = (crc >> 8) as u8;
                        self.block[end + 1] = (crc & 0xff) as u8;
                        end += 2;
                        if end == 4096 {
                            self.steps = MaskRomSteps::Dummy;
                        } else {
                            self.steps = MaskRomSteps::Done;
                        }

                        &self.block[0..end]
                    }
                };

                UsbStep::WriteControl {
                    request_type: 0x40,
                    request: 0xc,
                    value: 0,
                    index: self.area,
                    data: chunk,
                }
            }
            MaskRomSteps::Dummy => {
                self.steps = MaskRomSteps::Done;
                self.block[0] = 0;
                UsbStep::WriteControl {
                    request_type: 0x40,
                    request: 0xc,
                    value: 0,
                    index: self.area,
                    data: &self.block[0..1],
                }
            }
            MaskRomSteps::Done => UsbStep::Finished(Ok(())),
        }
    }
}

/// Write a specific area; typically 0x471 or 0x472 data as retrieved from a rockchip boot file
pub fn write_area(area: u16, data: &[u8]) -> MaskRomOperation {
    MaskRomOperation::new(area, data)
}

trait FromOperation {
    fn from_operation(io: &[u8], status: &CommandStatus) -> Result<Self, UsbOperationError>
    where
        Self: Sized;
}

enum Operation {
    CommandBlock,
    IO,
    CommandStatus,
    Finish,
}

enum IOBytes<'a> {
    // Biggest transfer that's not a data read/write
    Inband([u8; 16]),
    Read(&'a mut [u8]),
    Write(&'a [u8]),
}

/// Operation to execute using the "full" USB protocol
pub struct UsbOperation<'a, T> {
    command: CommandBlock,
    command_bytes: [u8; 31],
    data: IOBytes<'a>,
    next: Operation,
    _result: PhantomData<T>,
}

impl<'a, T> UsbOperation<'a, T> {
    fn new(command: CommandBlock) -> Self {
        Self {
            command,
            command_bytes: [0u8; protocol::COMMAND_BLOCK_BYTES],
            data: IOBytes::Inband([0u8; 16]),
            next: Operation::CommandBlock,
            _result: PhantomData,
        }
    }

    fn new_write(command: CommandBlock, data: &'a [u8]) -> Self {
        Self {
            command,
            command_bytes: [0u8; protocol::COMMAND_BLOCK_BYTES],
            data: IOBytes::Write(data),
            next: Operation::CommandBlock,
            _result: PhantomData,
        }
    }

    fn new_read(command: CommandBlock, data: &'a mut [u8]) -> Self {
        Self {
            command,
            command_bytes: [0u8; protocol::COMMAND_BLOCK_BYTES],
            data: IOBytes::Read(data),
            next: Operation::CommandBlock,
            _result: PhantomData,
        }
    }

    fn io_data_mut(&mut self) -> &mut [u8] {
        match &mut self.data {
            IOBytes::Inband(data) => data,
            IOBytes::Read(data) => data,
            IOBytes::Write(_) => unreachable!(),
        }
    }

    fn io_data(&mut self) -> &[u8] {
        match self.data {
            IOBytes::Inband(ref data) => data,
            IOBytes::Read(ref data) => data,
            IOBytes::Write(data) => data,
        }
    }
}

impl<T> OperationSteps<T> for UsbOperation<'_, T>
where
    T: FromOperation,
    T: std::fmt::Debug,
{
    fn step(&mut self) -> UsbStep<T> {
        let mut next = Operation::CommandBlock;
        std::mem::swap(&mut self.next, &mut next);
        match next {
            Operation::CommandBlock => {
                let len = self.command.to_bytes(&mut self.command_bytes);
                // If there is no transfer to be made (e.g. a command) just skip
                // sending data.
                if self.command.transfer_length() == 0 {
                    self.next = Operation::CommandStatus;
                } else {
                    self.next = Operation::IO;
                }
                UsbStep::WriteBulk {
                    data: &self.command_bytes[..len],
                }
            }
            Operation::IO => {
                self.next = Operation::CommandStatus;
                let len = self.command.transfer_length() as usize;
                match self.command.direction() {
                    Direction::Out => UsbStep::WriteBulk {
                        data: &self.io_data()[..len],
                    },
                    Direction::In => UsbStep::ReadBulk {
                        data: &mut self.io_data_mut()[..len],
                    },
                }
            }
            Operation::CommandStatus => {
                self.next = Operation::Finish;
                UsbStep::ReadBulk {
                    data: &mut self.command_bytes[..protocol::COMMAND_STATUS_BYTES],
                }
            }
            Operation::Finish => {
                let r = CommandStatus::from_bytes(&self.command_bytes)
                    .map_err(UsbOperationError::from)
                    .and_then(|csw| {
                        if csw.status == protocol::Status::FAILED {
                            Err(UsbOperationError::FailedStatus)
                        } else if csw.tag == self.command.tag() {
                            let transfer = self.command.transfer_length() as usize;
                            T::from_operation(&self.io_data()[..transfer], &csw)
                        } else {
                            Err(UsbOperationError::TagMismatch)
                        }
                    });
                UsbStep::Finished(r)
            }
        }
    }
}

impl FromOperation for ChipInfo {
    fn from_operation(io: &[u8], _status: &CommandStatus) -> Result<Self, UsbOperationError>
    where
        Self: Sized,
    {
        let data = io
            .try_into()
            .map_err(|_e| UsbOperationError::ReplyParseFailure)?;
        Ok(ChipInfo::from_bytes(data))
    }
}

/// Create operation to retrieve SoC Chip information
pub fn chip_info() -> UsbOperation<'static, ChipInfo> {
    UsbOperation::new(CommandBlock::chip_info())
}

impl FromOperation for FlashId {
    fn from_operation(io: &[u8], _status: &CommandStatus) -> Result<Self, UsbOperationError>
    where
        Self: Sized,
    {
        let data = io
            .try_into()
            .map_err(|_e| UsbOperationError::ReplyParseFailure)?;
        Ok(FlashId::from_bytes(data))
    }
}

/// Create operation to retrieve SoC flash identifier
pub fn flash_id() -> UsbOperation<'static, FlashId> {
    UsbOperation::new(CommandBlock::flash_id())
}

impl FromOperation for FlashInfo {
    fn from_operation(io: &[u8], _status: &CommandStatus) -> Result<Self, UsbOperationError>
    where
        Self: Sized,
    {
        let data = io
            .try_into()
            .map_err(|_e| UsbOperationError::ReplyParseFailure)?;
        Ok(FlashInfo::from_bytes(data))
    }
}

/// Create operation to retrieve SoC flash information
pub fn flash_info() -> UsbOperation<'static, FlashInfo> {
    UsbOperation::new(CommandBlock::flash_info())
}

impl FromOperation for Capability {
    fn from_operation(io: &[u8], _status: &CommandStatus) -> Result<Self, UsbOperationError>
    where
        Self: Sized,
    {
        let data = io
            .try_into()
            .map_err(|_e| UsbOperationError::ReplyParseFailure)?;
        Ok(Capability::from_bytes(data))
    }
}

/// Create operation to retrieve SoC capability
pub fn capability() -> UsbOperation<'static, Capability> {
    UsbOperation::new(CommandBlock::capability())
}

impl FromOperation for () {
    fn from_operation(_io: &[u8], _status: &CommandStatus) -> Result<Self, UsbOperationError>
    where
        Self: Sized,
    {
        Ok(())
    }
}

/// Create operation to reset the SoC
pub fn reset_device(opcode: ResetOpcode) -> UsbOperation<'static, ()> {
    UsbOperation::new(CommandBlock::reset_device(opcode))
}

/// Bytes transferred
#[derive(Debug, Clone, Copy)]
pub struct Transferred(u32);
impl FromOperation for Transferred {
    fn from_operation(io: &[u8], status: &CommandStatus) -> Result<Self, UsbOperationError>
    where
        Self: Sized,
    {
        let totransfer = io.len() as u32;
        if status.residue > totransfer {
            Err(UsbOperationError::ReplyParseFailure)
        } else {
            Ok(Transferred(totransfer - status.residue))
        }
    }
}

impl From<Transferred> for u32 {
    fn from(t: Transferred) -> Self {
        t.0
    }
}

/// Create operation to read an lba from the flash
///
/// start_sector with [protocol::SECTOR_SIZE] sectors. the data to be read must be a multiple of
/// [protocol::SECTOR_SIZE] bytes
pub fn read_lba(start_sector: u32, read: &mut [u8]) -> UsbOperation<'_, Transferred> {
    assert_eq!(read.len() % 512, 0, "Not a multiple of 512: {}", read.len());
    UsbOperation::new_read(
        CommandBlock::read_lba(start_sector, (read.len() / 512) as u16),
        read,
    )
}

/// Create operation to write an lba to the flash
///
/// start_sector with [protocol::SECTOR_SIZE] sectors. the data to be written must be a multiple of
/// [protocol::SECTOR_SIZE] bytes
pub fn write_lba(start_sector: u32, write: &[u8]) -> UsbOperation<'_, Transferred> {
    assert_eq!(
        write.len() % 512,
        0,
        "Not a multiple of 512: {}",
        write.len()
    );
    UsbOperation::new_write(
        CommandBlock::write_lba(start_sector, (write.len() / 512) as u16),
        write,
    )
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn chip_info_operation() {
        let mut o = chip_info();
        let cb = CommandBlock::chip_info();
        let mut cb_bytes = [0u8; protocol::COMMAND_BLOCK_BYTES];
        cb.to_bytes(&mut cb_bytes);
        // Write the command block
        let tag = match o.step() {
            UsbStep::WriteBulk { data } if data.len() == protocol::COMMAND_BLOCK_BYTES => {
                [data[4], data[5], data[6], data[7]]
            }
            o => panic!("Unexpected step: {:?}", o),
        };

        // Reading the chip info
        match o.step() {
            UsbStep::ReadBulk { data } if data.len() as u32 == cb.transfer_length() => {
                data.fill(0);
                /* 3588 */
                data[0] = 0x38;
                data[1] = 0x38;
                data[2] = 0x35;
                data[3] = 0x33;
            }
            o => panic!("Unexpected step: {:?}", o),
        }

        // reading status
        match o.step() {
            UsbStep::ReadBulk { data } if data.len() == protocol::COMMAND_STATUS_BYTES => {
                data.fill(0);
                /* signature */
                data[0] = b'U';
                data[1] = b'S';
                data[2] = b'B';
                data[3] = b'S';
                /* tag */
                data[4] = tag[0];
                data[5] = tag[1];
                data[6] = tag[2];
                data[7] = tag[3];
                // status good
                data[12] = 0;
            }
            o => panic!("Unexpected step: {:?}", o),
        }

        match o.step() {
            UsbStep::Finished(Ok(info)) => {
                assert_eq!(
                    info.inner(),
                    [
                        0x38u8, 0x38, 0x35, 0x33, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
                        0x0, 0x0
                    ]
                )
            }
            o => panic!("Unexpected step: {:?}", o),
        }
    }
}