libfreemkv 0.5.0

Open source raw disc access library for optical drives
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! MT1959 platform implementation — all 10 handlers translated from ARM.
//!
//! Two variants share this code:
//!   MT1959-A: mode=0x01, buffer_id=0x44 (all 10 handlers)
//!   MT1959-B: mode=0x02, buffer_id=0x77 (handlers 4-9, 0-3 are no-ops)
//!
//! Per-drive data comes from the profile (extracted from SDF blob).
//! The handler logic is identical across all 206 drives — only the
//! profile data differs (signature, register CDBs, microcode, etc).
//!
//! ARM source: research/arm/HANDLER_LOGIC.md
//! Hardware proof: archive/logs/cold_boot_stderr.log

use crate::error::{Error, Result};
use crate::profile::DriveProfile;
use crate::scsi::{self, DataDirection, ScsiTransport};
use super::{Platform, DriveStatus};

/// MT1959 driver state.
pub struct Mt1959 {
    profile: DriveProfile,
    mode: u8,
    buffer_id: u8,
    unlocked: bool,
    /// Speed table: 64 × u16, built by calibrate().
    /// Stores zone boundary addresses from disc surface probes.
    /// Indexed by handler 8 to find closest zone for a target LBA.
    speed_table: [u16; 64],
    /// Total disc sectors — from READ CAPACITY.
    disc_sectors: u32,
    calibrated: bool,
    /// 4 config bytes stored by calibrate() from initial probe response.
    /// [0]=speed_mult, [1]=data_byte, [2]=data_byte, [3]=last_speed
    calibration_config: [u8; 4],
}

impl Mt1959 {
    pub fn new(profile: DriveProfile) -> Self {
        let mode = profile.unlock_mode;
        let buffer_id = profile.unlock_buf_id;
        Mt1959 {
            profile,
            mode,
            buffer_id,
            unlocked: false,
            speed_table: [0u16; 64],
            disc_sectors: 0,
            calibrated: false,
            calibration_config: [0u8; 4],
        }
    }

    // ── SCSI helpers (ARM: FUN_81E0, FUN_8204, FUN_8288) ──────────────

    /// ARM: FUN_8204 — dynamic_read_buffer.
    /// Build READ_BUFFER with sub_cmd in CDB[3] and address in CDB[4:6].
    fn read_buffer_sub(&self, sub_cmd: u8, address: u16, length: u8) -> [u8; 10] {
        [
            0x3C, self.mode, self.buffer_id, sub_cmd,
            (address >> 8) as u8, address as u8,
            0x00, 0x00, length, 0x00,
        ]
    }

    /// ARM: FUN_8288 — read_buffer_probe.
    /// Calls dynamic_read_buffer, validates response size matches expected.
    /// Returns Ok(bytes_transferred) or Err.
    fn read_buffer_probe(
        &self, scsi: &mut dyn ScsiTransport,
        sub_cmd: u8, address: u16, buf: &mut [u8], expected: usize,
    ) -> Result<usize> {
        let cdb = self.read_buffer_sub(sub_cmd, address, expected as u8);
        let result = scsi.execute(&cdb, DataDirection::FromDevice, buf, 5_000)?;
        if result.bytes_transferred != expected {
            return Err(Error::ScsiError { opcode: 0x3C, status: 0xFF, sense_key: 0 });
        }
        Ok(result.bytes_transferred)
    }

    /// ARM: FUN_85B0 — set_cd_speed_max.
    /// Sends SET_CD_SPEED from CDB template at 0x9A78: BB 00 FF FF FF FF...
    fn set_cd_speed_max(&self, scsi: &mut dyn ScsiTransport) -> Result<()> {
        let cdb = scsi::build_set_cd_speed(0xFFFF);
        let mut dummy = [0u8; 0];
        scsi.execute(&cdb, DataDirection::None, &mut dummy, 5_000)?;
        Ok(())
    }

    /// Build and send a custom SET_CD_SPEED with a specific speed value.
    /// ARM: handler 8 builds this on the stack at sp+0x20.
    fn set_cd_speed(&self, scsi: &mut dyn ScsiTransport, speed: u16) -> Result<()> {
        let cdb = scsi::build_set_cd_speed(speed);
        let mut dummy = [0u8; 0];
        scsi.execute(&cdb, DataDirection::None, &mut dummy, 5_000)?;
        Ok(())
    }

    // ── do_unlock (ARM: FUN_82B8) ──────────────────────────────────────

    /// Core unlock function. Returns the full response on success.
    ///
    /// ARM logic:
    ///   r3 = unlock_init_value (1)
    ///   sp[0x1C] = r3
    ///   r3 += unlock_response_size_minus_init (0x3F)
    ///   sp[0] = r3 (= 64 = response size)
    ///   scsi_cmd_wrapper(result, 0x0A, unlock_CDB, response)
    ///   check response[0:4] == drive_signature (LE u32)
    ///   check response[12:16] == "MMkv" (0x766B4D4D LE)
    ///   check response[16:20] version range
    fn do_unlock(&mut self, scsi: &mut dyn ScsiTransport) -> Result<Vec<u8>> {
        let response_size = self.profile.unlock_init_value as u32
            + self.profile.unlock_response_size_minus_init as u32;

        let cdb = [
            0x3C, self.mode, self.buffer_id,
            0x00, 0x00, 0x00,
            0x00, 0x00, response_size as u8, 0x00,
        ];
        let mut response = vec![0u8; response_size as usize];
        scsi.execute(&cdb, DataDirection::FromDevice, &mut response, 30_000)?;

        // ARM: compare response[0:4] with drive_signature (LE u32)
        if response.len() >= 4 {
            let got = &response[0..4];
            if got != self.profile.drive_signature {
                return Err(Error::SignatureMismatch {
                    expected: self.profile.drive_signature,
                    got: got.try_into().unwrap_or([0; 4]),
                });
            }
        }

        // ARM: compare response[12:16] with "MMkv"
        if response.len() >= 16 && &response[12..16] != b"MMkv" {
            return Err(Error::UnlockFailed {
                detail: format!(
                    "mode not active: {:02x}{:02x}{:02x}{:02x}",
                    response[12], response[13], response[14], response[15]
                ),
            });
        }

        // ARM: version check at response[16:20] — arithmetic check
        // If signature + MMkv match, version is almost always OK.

        self.unlocked = true;
        Ok(response)
    }

    /// ARM: FUN_8788 — validate_with_retry.
    /// Sends a short READ_BUFFER probe, retries up to 5 times.
    fn validate(&self, scsi: &mut dyn ScsiTransport) -> Result<()> {
        for _attempt in 0..5 {
            let cdb = [
                0x3C, self.mode, self.buffer_id,
                0x00, 0x00, 0x00,
                0x00, 0x00, 0x04, 0x00,
            ];
            let mut resp = [0u8; 4];
            if scsi.execute(&cdb, DataDirection::FromDevice, &mut resp, 5_000).is_ok() {
                return Ok(());
            }
        }
        Err(Error::ScsiError { opcode: 0x3C, status: 0xFF, sense_key: 0 })
    }
}

impl Platform for Mt1959 {
    /// Handler 0 (ARM: FUN_8378).
    /// Thin wrapper → do_unlock(). Returns Ok if mode active, Err if not.
    fn unlock(&mut self, scsi: &mut dyn ScsiTransport) -> Result<()> {
        self.do_unlock(scsi)?;
        Ok(())
    }

    /// Handler 1: Upload LibreDrive microcode to drive.
    ///
    /// Two variants with different upload sequences:
    ///
    /// MT1959-A (ARM: FUN_8380):
    ///   1. WRITE_BUFFER mode=6 with ld_microcode
    ///   2. READ_BUFFER buf=0x45 verify (expect response == 2)
    ///   3. do_unlock() × 2
    ///
    /// MT1959-B (ARM: FUN_84DC):
    ///   1. WRITE_BUFFER with mode=2 buf=0x77 initial handshake (0x9C0 bytes)
    ///   2. Check response == 2
    ///   3. READ_BUFFER at offset 0x3000 (16 bytes, firmware metadata check)
    ///   4. WRITE_BUFFER mode=6 with ld_microcode (16 bytes from payload+16)
    ///   5. READ verify
    ///   6. do_unlock() × 5 retries
    fn load_firmware(&mut self, scsi: &mut dyn ScsiTransport) -> Result<()> {
        let microcode = &self.profile.ld_microcode;
        if microcode.is_empty() {
            return Err(Error::UnlockFailed {
                detail: "no ld_microcode in profile".into(),
            });
        }

        if self.mode == 0x01 {
            // ── MT1959-A path ──────────────────────────────────────────
            self.load_firmware_a(scsi)?;
        } else {
            // ── MT1959-B path ──────────────────────────────────────────
            self.load_firmware_b(scsi)?;
        }

        Ok(())
    }

    /// Handler 2 (ARM: FUN_8958 with param=0).
    ///
    /// do_unlock → validate × 5 → send hardware_register_a_cdb (10B) →
    /// check 36B response → return response[4:20] (16 bytes)
    fn read_register_a(&mut self, scsi: &mut dyn ScsiTransport) -> Result<[u8; 16]> {
        if !self.unlocked { self.do_unlock(scsi)?; }
        self.validate(scsi)?;

        let cdb = &self.profile.hardware_register_a_cdb;
        if cdb.len() != 10 {
            return Err(Error::UnlockFailed { detail: "missing register_a_cdb".into() });
        }
        let mut response = [0u8; 36];
        scsi.execute(cdb, DataDirection::FromDevice, &mut response, 30_000)?;

        // ARM: check response signature, then extract [4:20]
        let mut out = [0u8; 16];
        out.copy_from_slice(&response[4..20]);
        Ok(out)
    }

    /// Handler 3 (ARM: FUN_8958 with param!=0).
    fn read_register_b(&mut self, scsi: &mut dyn ScsiTransport) -> Result<[u8; 16]> {
        if !self.unlocked { self.do_unlock(scsi)?; }
        self.validate(scsi)?;

        let cdb = &self.profile.hardware_register_b_cdb;
        if cdb.len() != 10 {
            return Err(Error::UnlockFailed { detail: "missing register_b_cdb".into() });
        }
        let mut response = [0u8; 36];
        scsi.execute(cdb, DataDirection::FromDevice, &mut response, 30_000)?;

        let mut out = [0u8; 16];
        out.copy_from_slice(&response[4..20]);
        Ok(out)
    }

    /// Handler 4 (ARM: FUN_881C).
    ///
    /// Full calibration sequence:
    ///   1. do_unlock()
    ///   2. init_timing()
    ///   3. read_buffer_probe(0x12, init_addr, 4) — calibration init
    ///   4. validate_with_retry()
    ///   5. memset speed_table to 0
    ///   6. First probe: sub_cmd=0x14, addr=0 → initial speed
    ///   7. Scan loop: addresses 0x0000-0x5800, step 0x100, detect zone boundaries
    ///   8. Build loop: scan all zones up to 0x10000, store in speed_table[(speed>>1)-1]
    ///   9. Triple SET_CD_SPEED: max → drive_nominal_speed → max
    ///  10. Store 4 calibration config bytes
    fn calibrate(&mut self, scsi: &mut dyn ScsiTransport) -> Result<()> {
        // Step 1: ensure unlocked
        if !self.unlocked { self.do_unlock(scsi)?; }

        // Step 2: read disc capacity
        let cap_cdb = [0x25u8, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        let mut cap_buf = [0u8; 8];
        if scsi.execute(&cap_cdb, DataDirection::FromDevice, &mut cap_buf, 5_000).is_ok() {
            self.disc_sectors = u32::from_be_bytes([cap_buf[0], cap_buf[1], cap_buf[2], cap_buf[3]]) + 1;
        }

        // Step 3: calibration init — sub_cmd 0x12
        // ARM uses 0x0100 for BD, 0x0200 for UHD
        let init_addr: u16 = 0x0100; // TODO: detect disc type
        let mut init_resp = [0u8; 4];
        let _ = self.read_buffer_probe(scsi, 0x12, init_addr, &mut init_resp, 4);

        // Step 4: validate
        self.validate(scsi)?;

        // Step 5: clear speed table
        self.speed_table = [0u16; 64];

        // Step 6: first probe
        let mut probe_buf = [0u8; 4];
        let _ = self.read_buffer_probe(scsi, 0x14, 0, &mut probe_buf, 4);
        let initial_speed = probe_buf[0];
        self.calibration_config[0] = probe_buf[0];
        self.calibration_config[1] = probe_buf[1];
        self.calibration_config[2] = probe_buf[2];

        // Step 7: scan loop — find zone boundaries (0x0000-0x5800, step 0x100)
        // ARM: when speed changes, record the boundary address
        let mut addr: u16 = 0;
        let mut prev_speed = initial_speed;
        while addr < 0x5800 {
            let mut resp = [0u8; 4];
            if self.read_buffer_probe(scsi, 0x14, addr, &mut resp, 4).is_err() {
                self.speed_table = [0u16; 64];
                self.calibration_config = [0u8; 4];
                return Err(Error::ScsiError { opcode: 0x3C, status: 0xFF, sense_key: 0 });
            }
            if resp[0] != prev_speed {
                prev_speed = resp[0];
                // Zone boundary — ARM records this but the main table build is step 8
            }
            addr = addr.wrapping_add(0x100);
        }

        // Step 8: build speed table — probe all zones up to 0x10000
        // ARM: speed_table[(speed >> 1) - 1] = addr (if entry is empty)
        let mut addr: u32 = 0;
        let mut prev_speed: u8 = 0;
        while addr < 0x10000 {
            let mut resp = [0u8; 4];
            if self.read_buffer_probe(scsi, 0x14, addr as u16, &mut resp, 4).is_err() {
                break;
            }
            let speed = resp[0];
            if speed > prev_speed && speed > 0 {
                let idx = ((speed as usize) >> 1).saturating_sub(1);
                if idx < 64 && self.speed_table[idx] == 0 {
                    self.speed_table[idx] = addr as u16;
                }
            }
            prev_speed = speed;
            addr += 0x100;
        }
        self.calibration_config[3] = prev_speed;

        // Step 9: triple SET_CD_SPEED — max → nominal → max
        let _ = self.set_cd_speed_max(scsi);

        // Send drive_nominal_speed_cdb (the specific speed from the profile)
        if self.profile.drive_nominal_speed_cdb.len() >= 6 {
            let cdb = &self.profile.drive_nominal_speed_cdb;
            let mut dummy = [0u8; 0];
            let _ = scsi.execute(cdb, DataDirection::None, &mut dummy, 5_000);
        }

        let _ = self.set_cd_speed_max(scsi);

        self.calibrated = true;
        Ok(())
    }

    /// Handler 5 (ARM: FUN_81C0).
    ///
    /// NOT a no-op. Sends 16 bytes from a data buffer to the host via host_write.
    /// In our context: the x86 reads 16 bytes back. We return the data.
    /// The buffer at 0x9AB8 in the blob is right before the handler table.
    /// For now we just acknowledge — the x86 calls this to confirm VM is alive.
    fn keepalive(&mut self, _scsi: &mut dyn ScsiTransport) -> Result<()> {
        // ARM: host_write(buf_0x9AB8, 16) — sends 16 bytes to x86
        // In driver context: no host_write mechanism. This is a VM-to-host
        // communication that doesn't translate to a SCSI command.
        Ok(())
    }

    /// Handler 6 (ARM: FUN_8A7C).
    ///
    /// Full status check:
    ///   1. Read 4 bytes from host (param input)
    ///   2. Validate param == 4
    ///   3. do_unlock()
    ///   4. validate_with_retry()
    ///   5. Call helper FUN_817C with input to get probe address
    ///   6. read_buffer_probe(0x13, addr, response, 36)
    ///   7. validate_with_retry() again
    ///   8. Check REV32(response[0:4]) == 0x00220054
    ///   9. If mismatch: call fallback() with speed_zone_table
    ///  10. If match: host_write(response[4:20]) — 16 bytes features
    fn status(&mut self, scsi: &mut dyn ScsiTransport) -> Result<DriveStatus> {
        if !self.unlocked { self.do_unlock(scsi)?; }
        self.validate(scsi)?;

        // ARM: read_buffer_probe(0x13, 0, response, 36)
        let cdb = self.read_buffer_sub(0x13, 0, 36);
        let mut response = [0u8; 36];
        scsi.execute(&cdb, DataDirection::FromDevice, &mut response, 30_000)?;

        self.validate(scsi)?;

        // ARM: REV32(response[0:4]) and compare to 0x00220054
        let sig = u32::from_be_bytes(response[0..4].try_into().unwrap());
        let expected = 0x00220054;

        let mut features = [0u8; 16];
        features.copy_from_slice(&response[4..20]);

        Ok(DriveStatus {
            unlocked: sig == expected,
            features,
        })
    }

    /// Handler 7 (ARM: FUN_8454).
    ///
    /// Three code paths based on param count:
    ///   param=1 (5 bytes in): sub_cmd + nothing else → dynamic_read_buffer
    ///   param=5 (5+4 bytes in): sub_cmd + address → dynamic_read_buffer with addr
    ///   param=9 (9+ bytes in): builds full 12-byte CDB on stack:
    ///     [0x3C, mode, buf_id, sub_cmd, addr[2], addr[1], addr[0], len[2], len[1], len[0]]
    ///     then calls scsi_cmd_wrapper directly
    fn probe(
        &mut self, scsi: &mut dyn ScsiTransport,
        sub_cmd: u8, address: u32, length: u32,
    ) -> Result<Vec<u8>> {
        let cdb = [
            0x3C, self.mode, self.buffer_id, sub_cmd,
            (address >> 16) as u8, (address >> 8) as u8, address as u8,
            (length >> 16) as u8, (length >> 8) as u8, length as u8,
        ];
        let mut buf = vec![0u8; length as usize];
        let result = scsi.execute(&cdb, DataDirection::FromDevice, &mut buf, 30_000)?;
        buf.truncate(result.bytes_transferred);
        Ok(buf)
    }

    /// Handler 8 (ARM: FUN_85E8).
    ///
    /// Speed management for content reads. Called per zone change.
    ///
    /// ARM logic:
    ///   1. Read 4-byte target LBA from host
    ///   2. REV(LBA) for big-endian comparison
    ///   3. Search speed_table[64] for closest entry to LBA
    ///      - Each entry is u16 zone boundary address
    ///      - Find entry with smallest |entry - LBA| distance
    ///   4. If no match found → call fallback() with speed_calc_table
    ///   5. If match:
    ///      a. r6 = speed_table[best_idx] (the zone address = speed value)
    ///      b. Position check: read_buffer_probe(0x14, 0x100 | rev16(r6), 4)
    ///      c. SET_CD_SPEED max (BB 00 FF FF FF FF)
    ///      d. Build custom SET_CD_SPEED: BB 00 [r6>>8] [r6&FF] FF FF 00...
    ///      e. Send custom SET_CD_SPEED
    ///      f. Return next speed_table entry to host
    fn set_read_speed(&mut self, scsi: &mut dyn ScsiTransport, lba: u32) -> Result<()> {
        if !self.calibrated {
            return Ok(());
        }

        // ARM: REV(LBA) for comparison — we compare as u32 directly
        // Speed table entries are u16, LBA is u32 — the ARM compares
        // the byte-swapped LBA against table entries. Since entries are
        // zone boundary addresses (u16), we compare the low 16 bits.

        // Step 2-3: search speed_table for closest entry
        let mut best_idx: usize = 0;
        let mut best_diff: u32 = 0x10000000; // ARM: r6 = 0x80 << 17
        let mut found = false;

        for i in 0..64 {
            let entry = self.speed_table[i] as u32;
            if entry == 0 { continue; }
            let diff = if lba > entry { lba - entry } else { entry - lba };
            if diff < best_diff {
                best_diff = diff;
                best_idx = i;
                found = true;
            }
        }

        if !found {
            // ARM: fallback() with speed_calc_table — alternate lookup
            // For now, skip speed adjustment when no table match
            return Ok(());
        }

        // Step 5a: get the matched speed value
        let speed_val = self.speed_table[best_idx];

        // Step 5b: position check probe
        // ARM: rev16(speed_val) | 0x100
        let probe_addr = 0x0100 | (speed_val.swap_bytes() as u16);
        let mut probe_resp = [0u8; 4];
        let _ = self.read_buffer_probe(scsi, 0x14, probe_addr, &mut probe_resp, 4);

        // Step 5c: SET_CD_SPEED max
        let _ = self.set_cd_speed_max(scsi);

        // Step 5d-e: custom SET_CD_SPEED with the matched speed value
        // ARM: sp[0x22] = r6 >> 8, sp[0x23] = r6 & 0xFF
        let _ = self.set_cd_speed(scsi, speed_val);

        Ok(())
    }

    /// Handler 9 (ARM: FUN_813C).
    ///
    /// Reads 8 bytes from host, byte-swaps as 32-bit value, returns.
    /// Has a helper for unaligned 4-byte reads with manual byte copy.
    /// In driver context: no host communication, so this is a no-op.
    fn timing(&mut self, _scsi: &mut dyn ScsiTransport) -> Result<()> {
        // ARM: host_read(8 bytes) → REV32 → return
        // VM-to-host timing measurement, not a SCSI command.
        Ok(())
    }

    /// Full init sequence — matches x86 dispatch exactly.
    ///
    /// x86 (FUN_006bd600 + FUN_00695700 + FUN_006958e0 + FUN_00695b90):
    ///   Phase 1: cmd 0 → [cmd 1 if fail] × 6 retries (unlock + fw upload)
    ///   Phase 2: cmd 4 × 6 retries (calibrate)
    ///   Phase 3: cmd 7 → [cmd 5 fallback] (drive info)
    ///   Phase 4: cmd 2 + cmd 3 × 5 retries (registers)
    ///   Phase 5: cmd 9 × 6 retries (status)
    fn init(&mut self, scsi: &mut dyn ScsiTransport) -> Result<()> {
        // Phase 1: Unlock + firmware upload (6 retries)
        let mut unlocked = false;
        for _attempt in 0..6 {
            match self.unlock(scsi) {
                Ok(_) => { unlocked = true; break; }
                Err(_) => {
                    if self.load_firmware(scsi).is_ok() {
                        unlocked = true;
                        break;
                    }
                }
            }
        }
        if !unlocked {
            return Err(Error::UnlockFailed {
                detail: "failed after 6 attempts (unlock + load_firmware)".into(),
            });
        }

        // Phase 2: Calibrate (6 retries)
        let mut calibrated = false;
        for _attempt in 0..6 {
            if self.calibrate(scsi).is_ok() {
                calibrated = true;
                break;
            }
        }
        if !calibrated {
            return Err(Error::ScsiError { opcode: 0x3C, status: 0xFF, sense_key: 0 });
        }

        // Phase 3: Drive info via probe (handler 7)
        // ARM: cmd 7 → get info string (up to 1024 bytes)
        // If fails: cmd 5 fallback (keepalive)
        // In our context: this fetches a display string, not critical for reads
        let _ = self.probe(scsi, 0x00, 0, 0x3FF);

        // Phase 4: Read registers (5 retries, as in x86 FUN_00695b90)
        for _attempt in 0..5 {
            let a_ok = self.read_register_a(scsi).is_ok();
            let b_ok = self.read_register_b(scsi).is_ok();
            if a_ok && b_ok { break; }
        }

        // Phase 5: Status (6 retries)
        for _attempt in 0..6 {
            if self.status(scsi).is_ok() { break; }
        }

        Ok(())
    }

    fn is_unlocked(&self) -> bool {
        self.unlocked
    }
}

// ── Private firmware upload variants ───────────────────────────────────

impl Mt1959 {
    /// MT1959-A firmware upload (ARM: FUN_8380).
    ///
    /// Simple: WRITE all microcode → verify buf=0x45 → unlock × 2.
    fn load_firmware_a(&mut self, scsi: &mut dyn ScsiTransport) -> Result<()> {
        let microcode = &self.profile.ld_microcode;
        let len = microcode.len();

        // WRITE_BUFFER mode=6: send entire microcode payload
        let cdb = [
            0x3B, 0x06, 0x00,
            0x00, 0x00, 0x00,
            (len >> 16) as u8, (len >> 8) as u8, len as u8,
            0x00,
        ];
        let mut data = microcode.clone();
        scsi.execute(&cdb, DataDirection::ToDevice, &mut data, 30_000)?;

        // Verify: READ_BUFFER buf=0x45, 4 bytes — may fail, ARM continues
        let verify_cdb = [0x3C, 0x01, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00];
        let mut verify_resp = [0u8; 4];
        let _ = scsi.execute(
            &verify_cdb, DataDirection::FromDevice, &mut verify_resp, 5_000,
        );

        // Unlock × 2
        self.do_unlock(scsi)?;
        self.do_unlock(scsi)?;
        Ok(())
    }

    /// MT1959-B firmware upload (ARM: FUN_84DC).
    ///
    /// Verified byte-by-byte from B blob disassembly:
    ///   1. MODE SELECT (0x55) — send 2496 bytes from ld_microcode
    ///   2. Check result == 2 (firmware accepted)
    ///   3. READ_BUFFER mode=6 offset=0x3000 (16 bytes firmware metadata)
    ///   4. WRITE_BUFFER mode=6 (16 bytes from profile's fw_write_data)
    ///   5. Vendor verify command (from profile's verify_cdb)
    ///   6. do_unlock() × 5 retries + 1 final
    fn load_firmware_b(&mut self, scsi: &mut dyn ScsiTransport) -> Result<()> {
        let microcode = &self.profile.ld_microcode;

        // Step 1: MODE SELECT (0x55) with vendor mode page data
        // ARM CDB: 55 10 00 00 00 00 00 09 C0 00
        // Transfer: 0x9C0 = 2496 bytes from the firmware payload
        let write_len = 0x9C0usize.min(microcode.len());
        let mode_select_cdb = [
            0x55, 0x10, 0x00,
            0x00, 0x00, 0x00,
            (write_len >> 16) as u8, (write_len >> 8) as u8, write_len as u8,
            0x00,
        ];
        let mut data = microcode[..write_len].to_vec();
        scsi.execute(&mode_select_cdb, DataDirection::ToDevice, &mut data, 30_000)?;

        // Step 2: Check SCSI result — ARM checks sp[0x08] == 2
        // The execute above will Err on SCSI failure. If we get here, command accepted.

        // Step 3: READ_BUFFER mode=6, offset=0x3000, 16 bytes
        // ARM CDB at 0x9A88: 3C 06 00 00 30 00 00 00 10 00
        let read_meta_cdb = [0x3C, 0x06, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x10, 0x00];
        let mut meta_resp = [0u8; 16];
        let _ = scsi.execute(&read_meta_cdb, DataDirection::FromDevice, &mut meta_resp, 5_000);

        // Step 4: WRITE_BUFFER mode=6, 16 bytes
        // ARM CDB at 0x9AE0: 3B 06 00 00 00 00 00 00 10 00
        // ARM source: blob[0x1B04] = 16 bytes (handler table area in B blob)
        // This data is stored in profile.fw_write_data (16 bytes)
        if self.profile.fw_write_data.len() >= 16 {
            let write2_cdb = [0x3B, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00];
            let mut data2 = self.profile.fw_write_data[..16].to_vec();
            let _ = scsi.execute(&write2_cdb, DataDirection::ToDevice, &mut data2, 5_000);
        }

        // Step 5: Vendor verify command
        // ARM CDB at 0x9ACC — vendor-specific, from profile
        if self.profile.verify_cdb.len() >= 10 {
            let mut dummy = [0u8; 0];
            let _ = scsi.execute(&self.profile.verify_cdb, DataDirection::None, &mut dummy, 5_000);
        }

        // Step 6: do_unlock() × 5 retries + 1 confirmation
        for _attempt in 0..5 {
            if self.do_unlock(scsi).is_ok() {
                // One more unlock for confirmation (ARM: FUN_82B8 at 0x859C)
                let _ = self.do_unlock(scsi);
                return Ok(());
            }
        }
        self.do_unlock(scsi)?;
        Ok(())
    }
}