mediatek_optical/lib.rs
1//! MediaTek MT1959 / MT1939 optical drive (BD/DVD) protocol: command encoding,
2//! identity decoding, firmware image analysis and OEM image reconstruction.
3//!
4//! The crate root is `no_std`, allocation-free and dependency-free:
5//!
6//! - [`cdb`] — the command descriptor blocks, as byte constructors.
7//! - [`Identity`] — the decoded INQUIRY, boot banner and identity descriptor.
8//! - [`Chip`] — which controller generation a drive or image belongs to.
9//! - [`DriveClass`] — the update dialect a drive speaks ([`Identity::class`]).
10//! - [`layout`] — the fixed 2 MiB image geometry and the drive-written regions.
11//! - [`sense`] — sense-data parsing and classification of flash faults.
12//!
13//! Optional features add:
14//!
15//! - `drive` — `drive`: the command sequences (identify, memory read, flash
16//! session) over a caller-supplied `drive::Transport`.
17//! - `image` — `image`: chip detection from image bytes and the AES-CMAC
18//! integrity table (`image::cmac`). Uses `std`.
19//! - `enc` — `enc`: the AES-128-ECB transport envelope.
20//! - `oem` — `oem`: rebuild the flashable OEM image from a drive read, with
21//! the provenance of every substituted byte. Implies `image`.
22//! - `image` also enables `update`: an update prepared against the installed
23//! firmware, refused across chips and hardware families. With `drive`,
24//! the receiver-bound `receiver::PreparedUpdate::flash` runs it.
25//! - `std` — links the standard library (implied by `image`).
26//!
27//! ## Drive memory
28//!
29//! READ BUFFER mode 6 exposes the 2 MiB flash at file offsets, with one
30//! exception: the boot page `0x0..0x400` reads back as the image's own page at
31//! [`layout::BOOT_MIRROR`] instead of its stored form. The drive also rewrites
32//! the regions in [`layout::DRIVE_WRITTEN`] at runtime (revocation lists,
33//! settings, calibration), so a read is never byte-identical to the image that
34//! was flashed. `oem::rebuild` undoes both.
35#![cfg_attr(not(feature = "std"), no_std)]
36#![deny(missing_docs)]
37#![forbid(unsafe_code)]
38
39#[cfg(all(test, not(feature = "std")))]
40extern crate std;
41
42mod error_codes;
43pub use error_codes::CodedError;
44
45pub mod cdb;
46#[cfg(feature = "drive")]
47pub mod drive;
48#[cfg(feature = "enc")]
49pub mod enc;
50#[cfg(all(feature = "image", feature = "enc"))]
51pub mod envelope;
52#[cfg(feature = "image")]
53pub mod image;
54pub mod layout;
55#[cfg(feature = "oem")]
56pub mod oem;
57#[cfg(feature = "drive")]
58pub mod receiver;
59#[cfg(all(feature = "drive", feature = "image", feature = "enc"))]
60pub mod recovery;
61#[cfg(feature = "image")]
62pub mod update;
63
64/// Length of a standard INQUIRY response header, in bytes.
65pub const INQUIRY_LEN: usize = 36;
66
67/// A MediaTek optical controller generation.
68///
69/// Deliberately exhaustive: a new generation is a breaking change, so every
70/// caller that dispatches on the chip must decide how to handle it.
71#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
72pub enum Chip {
73 /// MediaTek MT1959.
74 Mt1959,
75 /// MediaTek MT1939.
76 Mt1939,
77}
78
79impl Chip {
80 /// Short label, `"MT1959"` or `"MT1939"`.
81 pub const fn label(self) -> &'static str {
82 match self {
83 Chip::Mt1959 => "MT1959",
84 Chip::Mt1939 => "MT1939",
85 }
86 }
87
88 /// Map the two trailing digits of an `MTEKMT19xx` or `MT19xx` tag.
89 pub const fn from_digits(d0: u8, d1: u8) -> Option<Self> {
90 match (d0, d1) {
91 (b'5', b'9') => Some(Chip::Mt1959),
92 (b'3', b'9') => Some(Chip::Mt1939),
93 _ => None,
94 }
95 }
96
97 /// The chip named by the first `MTEKMT19xx` identity tag in `bytes`.
98 ///
99 /// This is a label parser, not operational chip detection. OEM identity
100 /// tags can be stale; [`Identity::chip`] and image analysis use the boot
101 /// banner instead. Never use this label to override their result.
102 pub fn from_tag(bytes: &[u8]) -> Option<Self> {
103 const PREFIX: &[u8] = b"MTEKMT19";
104 bytes
105 .windows(PREFIX.len() + 2)
106 .filter(|w| w.starts_with(PREFIX))
107 .find_map(|w| Self::from_digits(w[PREFIX.len()], w[PREFIX.len() + 1]))
108 }
109
110 /// The chip named by a boot banner such as `MT1939 Boot JB7`. This is the
111 /// source used by live identity and image analysis, even when a descriptor
112 /// carries a conflicting [`Chip::from_tag`] label.
113 pub fn from_banner(banner: &[u8]) -> Option<Self> {
114 banner
115 .windows(6)
116 .filter(|w| w.starts_with(b"MT19"))
117 .find_map(|w| Self::from_digits(w[4], w[5]))
118 }
119}
120
121impl core::fmt::Display for Chip {
122 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
123 f.write_str(self.label())
124 }
125}
126
127/// [`Chip::label`] did not name a chip.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub struct UnknownChip;
130
131impl core::fmt::Display for UnknownChip {
132 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
133 f.write_str("not an MT1959 or MT1939 label")
134 }
135}
136
137#[cfg(feature = "std")]
138impl std::error::Error for UnknownChip {}
139
140impl core::str::FromStr for Chip {
141 type Err = UnknownChip;
142
143 /// Parse a [`Chip::label`], e.g. `MT1939`.
144 fn from_str(label: &str) -> Result<Self, Self::Err> {
145 match label {
146 "MT1959" => Ok(Chip::Mt1959),
147 "MT1939" => Ok(Chip::Mt1939),
148 _ => Err(UnknownChip),
149 }
150 }
151}
152
153/// The update dialect a drive speaks, chosen by [`Identity::class`].
154///
155/// The dialect owns the update session: its command sequence, chunking,
156/// readiness timing after the burn and which bytes read-back verification may
157/// compare.
158#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
159#[non_exhaustive]
160pub enum DriveClass {
161 /// MT1959 and MT1939: the OEM session of 12-byte CDBs. PROBE, TEST UNIT
162 /// READY and PREPARE, the image in [`cdb::CHUNK`] STREAM writes, COMMIT,
163 /// then TEST UNIT READY and REQUEST SENSE. The drive programs when the
164 /// last chunk lands.
165 Mt19,
166}
167
168impl DriveClass {
169 /// Whether a host should offer automatic installed-firmware acquisition.
170 ///
171 /// Stock MT19 firmware does not provide a reliable complete firmware read.
172 /// Hosts should request a Current firmware file instead. Metadata and
173 /// restricted memory reads remain available; this does not forbid them or
174 /// a modified firmware's separate dump command.
175 pub const fn can_read(self) -> bool {
176 match self {
177 Self::Mt19 => false,
178 }
179 }
180
181 /// The dialect of a drive with `chip`.
182 pub const fn of(chip: Chip) -> Self {
183 match chip {
184 Chip::Mt1959 | Chip::Mt1939 => DriveClass::Mt19,
185 }
186 }
187
188 /// Bytes per STREAM write.
189 pub const fn chunk(self) -> usize {
190 cdb::CHUNK
191 }
192
193 /// How long programming may keep the drive from answering TEST UNIT READY
194 /// after COMMIT: 120 s.
195 ///
196 /// The OEM updaters wait for the drive without a total bound and give each
197 /// command a 100 s timeout, so a drive that answers within one OEM command
198 /// window must not be declared failed. 120 s covers that window plus 20 s
199 /// (40 polls) of margin. A shorter bound fails a drive that is still
200 /// programming and invites a power cycle mid-burn; a longer one only costs
201 /// time on a drive that never comes back.
202 pub const fn ready_timeout(self) -> core::time::Duration {
203 core::time::Duration::from_secs(120)
204 }
205
206 /// Delay between TEST UNIT READY polls while the drive programs.
207 pub const fn poll_interval(self) -> core::time::Duration {
208 core::time::Duration::from_millis(500)
209 }
210
211 /// Read-back verification compares no byte below this offset: the drive
212 /// serves its boot area remapped ([`layout::BOOT_AREA`]).
213 pub const fn verify_floor(self) -> usize {
214 layout::BOOT_AREA.end()
215 }
216}
217
218/// Trim trailing ASCII spaces and NULs and decode as UTF-8; `""` if invalid.
219fn field(raw: &[u8]) -> &str {
220 let start = raw.iter().position(|&b| b != b' ').unwrap_or(raw.len());
221 let raw = &raw[start..];
222 let end = raw
223 .iter()
224 .rposition(|&b| b != b' ' && b != 0)
225 .map_or(0, |i| i + 1);
226 core::str::from_utf8(&raw[..end]).unwrap_or("")
227}
228
229/// A drive's identity: the standard INQUIRY response, the boot banner at
230/// [`layout::BANNER`] and the identity descriptor at [`layout::DESCRIPTOR`].
231#[derive(Clone, Debug, PartialEq, Eq)]
232pub struct Identity {
233 inquiry: [u8; INQUIRY_LEN],
234 banner: [u8; layout::BANNER.len],
235 descriptor: [u8; layout::DESCRIPTOR.len],
236}
237
238impl Identity {
239 /// Decode an INQUIRY response (at least [`INQUIRY_LEN`] bytes), a boot
240 /// banner and an identity descriptor. Short banner and descriptor reads
241 /// are zero-padded. Returns `None` if the INQUIRY is short.
242 pub fn parse(inquiry: &[u8], banner: &[u8], descriptor: &[u8]) -> Option<Self> {
243 if inquiry.len() < INQUIRY_LEN {
244 return None;
245 }
246 let mut id = Self {
247 inquiry: [0; INQUIRY_LEN],
248 banner: [0; layout::BANNER.len],
249 descriptor: [0; layout::DESCRIPTOR.len],
250 };
251 id.inquiry.copy_from_slice(&inquiry[..INQUIRY_LEN]);
252 let n = banner.len().min(id.banner.len());
253 id.banner[..n].copy_from_slice(&banner[..n]);
254 let n = descriptor.len().min(id.descriptor.len());
255 id.descriptor[..n].copy_from_slice(&descriptor[..n]);
256 Some(id)
257 }
258
259 /// Peripheral device type; `0x05` for an optical drive.
260 pub fn device_type(&self) -> u8 {
261 self.inquiry[0] & 0x1f
262 }
263 /// Vendor identification, e.g. `HL-DT-ST`.
264 pub fn vendor(&self) -> &str {
265 field(&self.inquiry[8..16])
266 }
267 /// Product identification, e.g. `BD-RE BU40N`.
268 pub fn product(&self) -> &str {
269 field(&self.inquiry[16..32])
270 }
271 /// Firmware revision, e.g. `1.00`.
272 pub fn revision(&self) -> &str {
273 field(&self.inquiry[32..36])
274 }
275 /// The boot banner, e.g. `MT1959 Boot BU5`, up to its first NUL or
276 /// non-printable byte.
277 pub fn banner(&self) -> &str {
278 let end = self
279 .banner
280 .iter()
281 .position(|&b| !(0x20..0x7f).contains(&b))
282 .unwrap_or(self.banner.len());
283 field(&self.banner[..end])
284 }
285 /// `true` when the descriptor carries an `MTEKMT19xx` identity tag.
286 pub fn has_descriptor(&self) -> bool {
287 Chip::from_tag(&self.descriptor).is_some()
288 }
289 /// Model from the identity descriptor; `""` without a descriptor.
290 pub fn descriptor_model(&self) -> &str {
291 if self.has_descriptor() {
292 field(&self.descriptor[0x08..0x18])
293 } else {
294 ""
295 }
296 }
297 /// Vendor-specific SKU code from the identity descriptor, e.g. `N003600`;
298 /// `""` without a descriptor.
299 pub fn sku(&self) -> &str {
300 if self.has_descriptor() {
301 field(&self.descriptor[0x1C..0x24])
302 } else {
303 ""
304 }
305 }
306 /// The controller generation, decided by the drive's boot banner
307 /// ([`Chip::from_banner`]) and nothing else. The `MTEKMT19xx` identity tag
308 /// is a stale vendor label and is never consulted. `None` for a drive whose
309 /// banner names no supported generation.
310 pub fn chip(&self) -> Option<Chip> {
311 Chip::from_banner(&self.banner)
312 }
313 /// The update dialect this drive speaks: [`DriveClass::Mt19`] for a drive
314 /// that names an MT1959 or MT1939 chip, else `None`.
315 pub fn class(&self) -> Option<DriveClass> {
316 self.chip().map(DriveClass::of)
317 }
318 /// `true` when the banner carries the MT19-family `MT19` signature.
319 pub fn is_mt19(&self) -> bool {
320 self.banner.windows(4).any(|w| w == b"MT19")
321 }
322 /// The raw INQUIRY response.
323 pub fn inquiry_bytes(&self) -> &[u8; INQUIRY_LEN] {
324 &self.inquiry
325 }
326 /// The raw boot banner.
327 pub fn banner_bytes(&self) -> &[u8; layout::BANNER.len] {
328 &self.banner
329 }
330 /// The raw identity descriptor.
331 pub fn descriptor_bytes(&self) -> &[u8; layout::DESCRIPTOR.len] {
332 &self.descriptor
333 }
334}
335
336/// Sense-data parsing and classification.
337pub mod sense {
338 /// Parsed sense: `(key, asc, ascq)`.
339 pub type Triplet = (u8, u8, u8);
340
341 /// Sense key `NOT READY`.
342 pub const NOT_READY: u8 = 0x02;
343 /// Sense key `MEDIUM ERROR`.
344 pub const MEDIUM_ERROR: u8 = 0x03;
345 /// Sense key `HARDWARE ERROR`.
346 pub const HARDWARE_ERROR: u8 = 0x04;
347 /// Sense key `ILLEGAL REQUEST`.
348 pub const ILLEGAL_REQUEST: u8 = 0x05;
349 /// Sense key `ABORTED COMMAND`.
350 pub const ABORTED_COMMAND: u8 = 0x0B;
351
352 /// Parse fixed-format (`0x70`/`0x71`) or descriptor-format (`0x72`/`0x73`)
353 /// sense data into `(key, asc, ascq)`. `None` when short or unrecognized.
354 pub fn parse(data: &[u8]) -> Option<Triplet> {
355 match *data.first()? & 0x7f {
356 0x70 | 0x71 if data.len() >= 14 => Some((data[2] & 0x0f, data[12], data[13])),
357 0x72 | 0x73 if data.len() >= 4 => Some((data[1] & 0x0f, data[2], data[3])),
358 _ => None,
359 }
360 }
361
362 /// `true` for the keys that prove a programming failure after a flash:
363 /// MEDIUM ERROR, HARDWARE ERROR and ABORTED COMMAND. Every other key is a
364 /// transient or unrelated condition; read-back verification decides.
365 pub const fn is_flash_fault(key: u8) -> bool {
366 matches!(key, MEDIUM_ERROR | HARDWARE_ERROR | ABORTED_COMMAND)
367 }
368
369 /// `true` for `02/3A/xx`, the benign "medium not present" of an empty tray.
370 pub const fn is_no_medium(key: u8, asc: u8) -> bool {
371 key == NOT_READY && asc == 0x3A
372 }
373}
374
375#[cfg(all(test, feature = "image"))]
376mod fixtures;
377
378#[cfg(test)]
379#[path = "lib_tests.rs"]
380mod tests;
381
382#[cfg(all(feature = "drive", feature = "image", feature = "enc"))]
383#[doc = include_str!("../README.md")]
384mod readme_examples {}