mediatek-optical 1.0.0

MediaTek MT1959/MT1939 optical drive (BD/DVD) protocol: command encoding, identity and flash sequences over any SCSI transport, chip detection, hardware families, AES-CMAC integrity, family-gated updates and OEM image reconstruction. no_std by default.
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
//! Shared transfer and verification over a caller's transport.

use core::time::Duration;

#[cfg(test)]
use super::PreparedUpdate;
use crate::drive::{self, Error, Transport};
use crate::sense::{self, Triplet};
use crate::{cdb, layout};

/// The two transports a flash uses, both addressing the drive the update was
/// prepared for. Prevent any other access to the drive throughout.
pub struct FlashTransport<'a, R, W> {
    /// Readiness polls, sense reads and read-back.
    pub reads: &'a mut R,
    /// The update session: PROBE, TEST UNIT READY, PREPARE, STREAM and
    /// COMMIT. Must never retry a write.
    pub writes: &'a mut W,
}

/// When a sense reply was read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stage {
    /// Right after COMMIT.
    Commit,
    /// Once the drive answered TEST UNIT READY again.
    Settled,
}

/// A REQUEST SENSE outcome that does not fail the flash.
#[derive(Debug)]
pub enum Status<'a, E> {
    /// A parsed sense that proves no programming failure.
    Sense(Triplet),
    /// A reply of this many bytes that does not parse as sense data.
    Unparseable(usize),
    /// The command failed; read-back verification decides.
    Failed(&'a Error<E>),
}

/// Host timing and progress for receiver-bound update execution.
pub trait FlashRuntime<E> {
    /// Monotonic time from a fixed origin; must advance across
    /// [`FlashRuntime::sleep`].
    fn elapsed(&self) -> Duration;
    /// Wait at least `duration`.
    fn sleep(&mut self, duration: Duration);
    /// The session is about to start; `bytes` will be streamed.
    fn starting(&mut self, _bytes: usize) {}
    /// A STREAM write completed.
    fn progress(&mut self, _written: usize, _total: usize) {}
    /// Explicit Recovery only: PREPARE failed, was not retried, and recovery
    /// proceeds to the selected image. Hosts should persist the full error.
    /// Normal Flash never invokes this callback and aborts on entry failure.
    fn recovery_entry_failed(&mut self, _error: &Error<E>) {}
    /// COMMIT failed. The drive programmed when the last chunk landed and may
    /// answer COMMIT while it reinitializes, so the flash goes on to its
    /// checks.
    fn commit_failed(&mut self, _error: &Error<E>) {}
    /// TEST UNIT READY right after COMMIT failed; expected while programming.
    fn commit_not_ready(&mut self, _error: &Error<E>) {}
    /// A REQUEST SENSE outcome that does not fail the flash.
    fn status(&mut self, _stage: Stage, _status: Status<'_, E>) {}
    /// The upload is complete; readiness polling starts.
    fn uploaded(&mut self, _bytes: usize) {}
    /// A readiness poll failed after `elapsed` of polling.
    fn poll_failed(&mut self, _elapsed: Duration, _error: &Error<E>) {}
    /// Read-back verification starts.
    fn verifying(&mut self) {}
    /// A chunk holding protected bytes could not be read back in full.
    fn unverified(&mut self, _offset: usize, _length: usize, _error: &Error<E>) {}
}

/// What read-back verification proved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Verified {
    /// Protected bytes compared, all equal.
    pub checked: usize,
    /// Protected ranges in the image; `0` when it has none to compare.
    pub ranges: usize,
}

/// A failed flash. Every variant after [`FlashError::Entry`] may leave the
/// drive holding partial or unverified firmware; nothing is retried or rolled
/// back.
#[derive(Debug)]
#[non_exhaustive]
pub enum FlashError<E> {
    /// PROBE, TEST UNIT READY or PREPARE failed; no firmware data was sent. If
    /// PREPARE was reached the drive may be in update mode.
    Entry(Error<E>),
    /// A STREAM write failed.
    Transfer {
        /// Offset of the failed chunk.
        offset: usize,
        /// Its length.
        length: usize,
        /// The command failure.
        source: Error<E>,
    },
    /// REQUEST SENSE reported a programming failure.
    Fault {
        /// When the sense was read.
        stage: Stage,
        /// The sense.
        sense: Triplet,
    },
    /// The drive did not answer TEST UNIT READY within
    /// [`crate::DriveClass::ready_timeout`]; the last poll's error.
    ReadyTimeout(Error<E>),
    /// Readiness/read-back completed, but the selected target was not confirmed running.
    Startup(super::StartupError<E>),
    /// A protected byte read back differently.
    Mismatch {
        /// Offset of the first differing byte.
        address: usize,
        /// The byte read back.
        read: u8,
        /// The byte written.
        wrote: u8,
        /// Protected bytes that differ.
        differing: usize,
        /// Protected bytes compared.
        checked: usize,
    },
    /// Chunks holding protected bytes could not be read back.
    Incomplete {
        /// Chunks not verified.
        unverified: usize,
        /// Protected bytes compared, all equal.
        checked: usize,
    },
}

impl<E: core::fmt::Debug> core::fmt::Display for FlashError<E> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Entry(e) => write!(f, "update entry failed before any firmware data: {e}"),
            Self::Transfer {
                offset,
                length,
                source,
            } => write!(
                f,
                "firmware write at {offset:#x}, length {length}: {source}"
            ),
            Self::Fault { stage, sense } => write!(
                f,
                "{stage:?} sense {:02X}/{:02X}/{:02X} reports a flash fault",
                sense.0, sense.1, sense.2
            ),
            Self::ReadyTimeout(e) => write!(f, "drive did not settle after the burn: {e}"),
            Self::Startup(error) => write!(f, "target startup was not confirmed: {error}"),
            Self::Mismatch {
                address,
                read,
                wrote,
                differing,
                checked,
            } => write!(
                f,
                "read-back differs at {address:#08x} (read {read:#04x}, wrote {wrote:#04x}); \
                 {differing} of {checked} protected bytes differ"
            ),
            Self::Incomplete {
                unverified,
                checked,
            } => write!(
                f,
                "{unverified} protected chunks unreadable; {checked} protected bytes verified"
            ),
        }
    }
}

impl<E: core::fmt::Debug + 'static> std::error::Error for FlashError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Entry(source) | Self::ReadyTimeout(source) => Some(source),
            Self::Transfer { source, .. } => Some(source),
            Self::Startup(source) => Some(source),
            _ => None,
        }
    }
}

/// REQUEST SENSE as the OEM sequence issues it: the reply length and its
/// parse.
fn request_sense<T: Transport>(t: &mut T) -> Result<(usize, Option<Triplet>), Error<T::Error>> {
    let mut buf = [0; cdb::REQUEST_SENSE_LEN];
    let n = drive::read(t, &cdb::request_sense(), &mut buf, 0)?;
    Ok((n, sense::parse(&buf[..n])))
}

/// REQUEST SENSE at `stage`: a flash fault fails, anything else is reported.
fn status<T: Transport, H: FlashRuntime<T::Error>>(
    t: &mut T,
    runtime: &mut H,
    stage: Stage,
) -> Result<(), FlashError<T::Error>> {
    match request_sense(t) {
        Ok((_, Some(sense))) if sense::is_flash_fault(sense.0) => {
            Err(FlashError::Fault { stage, sense })
        }
        Ok((_, Some(sense))) => {
            runtime.status(stage, Status::Sense(sense));
            Ok(())
        }
        Ok((n, None)) => {
            runtime.status(stage, Status::Unparseable(n));
            Ok(())
        }
        Err(error) => {
            runtime.status(stage, Status::Failed(&error));
            Ok(())
        }
    }
}

#[cfg(test)]
impl PreparedUpdate {
    /// Write the update and prove it: PROBE, TEST UNIT READY, PREPARE, the
    /// transfer in STREAM chunks, COMMIT, TEST UNIT READY and REQUEST SENSE;
    /// then poll TEST UNIT READY until the drive has programmed, REQUEST SENSE
    /// again, and read back every chunk, comparing the integrity-protected
    /// ranges with the image.
    ///
    /// First capture a backup, enforce tray and consent policy and exclude
    /// other users of the drive. A failure stops at once; nothing is retried.
    pub(crate) fn flash<R, W, H>(
        &self,
        io: FlashTransport<'_, R, W>,
        runtime: &mut H,
    ) -> Result<Verified, FlashError<W::Error>>
    where
        W: Transport,
        R: Transport<Error = W::Error>,
        H: FlashRuntime<W::Error>,
    {
        Payload {
            class: self.class,
            image: &self.image,
            transfer: self.transfer(),
        }
        .flash(io, runtime, ExecutionMode::Flash, cdb::Prepare::ModeOne)
    }
}

/// Shared transfer and verification implementation; recovery supplies no family policy.
pub(crate) struct Payload<'a> {
    pub(crate) class: crate::DriveClass,
    pub(crate) image: &'a [u8],
    pub(crate) transfer: &'a [u8],
}

/// Host policy is separate from receiver encoding and entry-command evidence.
/// Only the corresponding public prepared operation selects this mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ExecutionMode {
    Flash,
    Recovery,
}
impl Payload<'_> {
    pub(crate) fn flash<R, W, H>(
        &self,
        io: FlashTransport<'_, R, W>,
        runtime: &mut H,
        mode: ExecutionMode,
        prepare: cdb::Prepare,
    ) -> Result<Verified, FlashError<W::Error>>
    where
        W: Transport,
        R: Transport<Error = W::Error>,
        H: FlashRuntime<W::Error>,
    {
        let transfer = self.transfer;
        runtime.starting(transfer.len());
        let mut session = match mode {
            ExecutionMode::Recovery => {
                drive::enter_recovery_reporting(io.writes, prepare, |error| {
                    runtime.recovery_entry_failed(error)
                })
            }
            ExecutionMode::Flash => {
                drive::enter_update_command(io.writes, prepare).map_err(FlashError::Entry)?
            }
        };
        let chunk = self.class.chunk();
        for (index, piece) in transfer.chunks(chunk).enumerate() {
            let offset = index * chunk;
            session
                .write(offset as u32, piece)
                .map_err(|source| FlashError::Transfer {
                    offset,
                    length: piece.len(),
                    source,
                })?;
            runtime.progress(offset + piece.len(), transfer.len());
        }
        if let Err(error) = session.finish() {
            runtime.commit_failed(&error);
        }
        if let Err(error) = drive::test_unit_ready(io.reads) {
            runtime.commit_not_ready(&error);
        }
        status(io.reads, runtime, Stage::Commit)?;

        runtime.uploaded(transfer.len());
        let start = runtime.elapsed();
        while let Err(error) = drive::test_unit_ready(io.reads) {
            let waited = runtime.elapsed().saturating_sub(start);
            runtime.poll_failed(waited, &error);
            if waited >= self.class.ready_timeout() {
                return Err(FlashError::ReadyTimeout(error));
            }
            runtime.sleep(self.class.poll_interval());
        }
        status(io.reads, runtime, Stage::Settled)?;

        runtime.verifying();
        self.verify(io.reads, runtime)
    }

    /// Execute and retain read-back quality, then require exact target startup.
    pub(crate) fn flash_completed<R, W, H>(
        &self,
        io: FlashTransport<'_, R, W>,
        runtime: &mut H,
        mode: ExecutionMode,
        prepare: cdb::Prepare,
    ) -> Result<super::Completion, FlashError<W::Error>>
    where
        W: Transport,
        R: Transport<Error = W::Error>,
        H: FlashRuntime<W::Error>,
    {
        let result = self.flash(
            FlashTransport {
                reads: io.reads,
                writes: io.writes,
            },
            runtime,
            mode,
            prepare,
        );
        super::completion::complete(io.reads, self.image, result)
    }

    /// Read back every chunk and compare the protected bytes.
    fn verify<R: Transport, H: FlashRuntime<R::Error>>(
        &self,
        reads: &mut R,
        runtime: &mut H,
    ) -> Result<Verified, FlashError<R::Error>> {
        let ranges = self.class.verification_ranges(self.image);
        let protected = |at: usize| ranges.iter().any(|r| r.contains(&at));
        let (mut checked, mut differing, mut unverified) = (0, 0, 0);
        let mut first: Option<(usize, u8, u8)> = None;
        let chunk = self.class.chunk();
        let mut buf = vec![0; chunk];
        for (index, piece) in self.image.chunks(chunk).enumerate() {
            let offset = index * chunk;
            let got = &mut buf[..piece.len()];
            match drive::read_memory(reads, offset as u32, got) {
                Ok(()) => {
                    for (i, (&read, &wrote)) in got.iter().zip(piece).enumerate() {
                        if !protected(offset + i) {
                            continue;
                        }
                        checked += 1;
                        if read != wrote {
                            differing += 1;
                            first.get_or_insert((offset + i, read, wrote));
                        }
                    }
                }
                Err(error) => {
                    if (offset..offset + piece.len()).any(protected) {
                        unverified += 1;
                        runtime.unverified(offset, piece.len(), &error);
                    }
                }
            }
        }
        if let Some((address, read, wrote)) = first {
            return Err(FlashError::Mismatch {
                address,
                read,
                wrote,
                differing,
                checked,
            });
        }
        if !ranges.is_empty() && unverified > 0 {
            return Err(FlashError::Incomplete {
                unverified,
                checked,
            });
        }
        debug_assert_eq!(self.image.len(), layout::IMAGE_SIZE);
        Ok(Verified {
            checked,
            ranges: ranges.len(),
        })
    }
}