consortium-hal-imx9 0.5.0

Consortium HAL for i.MX 9 family devices
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! I3C controller driver for the NXP I3C block used by i.MX 9.
//!
//! The controller engine follows Embassy MCXA's NXP I3C implementation. It
//! supports controller-mode I3C SDR and legacy I2C private transfers, repeated
//! starts, broadcast CCCs, and dynamic address assignment. Blocking calls need
//! no interrupt. Async calls require the application to forward the instance
//! IRQ to [`on_interrupt::<T>`](on_interrupt).
//!
//! Every blocking wait is bounded by the driver's [`Timeout`] (see
//! [`I3c::set_timeout`]) and fails with [`Error::Timeout`] if the bus stalls.

use core::future::poll_fn;
use core::task::Poll;

use embassy_hal_internal::{Peri, PeripheralType};
use embassy_sync::waitqueue::AtomicWaker;
use pac::peripherals::i3c::{I3C, I3C_MWDATAB, I3C_MWDATABE};

use crate::hal::timeout::Timeout;
use crate::pac;

const REQUEST_START: u8 = 1;
const REQUEST_STOP: u8 = 2;
const REQUEST_DAA: u8 = 4;
const TYPE_I3C: u8 = 0;
const TYPE_I2C: u8 = 1;
const MASTER_ON: u8 = 1;
const MAX_READ_CHUNK: usize = 256;

/// Protocol used for a private transfer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BusMode {
    /// I3C single-data-rate transfer to a dynamic address.
    #[default]
    I3cSdr,
    /// Legacy I2C transfer to a static address.
    I2c,
}

impl BusMode {
    const fn type_bits(self) -> u8 {
        match self {
            Self::I3cSdr => TYPE_I3C,
            Self::I2c => TYPE_I2C,
        }
    }
}

/// One operation in a repeated-start transaction.
pub enum Operation<'a> {
    /// Read into the supplied buffer.
    Read(&'a mut [u8]),
    /// Write the supplied bytes.
    Write(&'a [u8]),
}

/// Information returned by dynamic address assignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DeviceInfo {
    /// 15-bit MIPI manufacturer identifier.
    pub manufacturer_id: u16,
    /// 32-bit part number portion of the provisional ID.
    pub part_number: u32,
    /// Bus Characteristics Register.
    pub bcr: u8,
    /// Device Characteristics Register.
    pub dcr: u8,
    /// Assigned dynamic address.
    pub dynamic_address: u8,
}

/// I3C setup error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigError {
    /// A requested frequency is zero or cannot fit the hardware dividers.
    InvalidFrequency,
}

/// I3C transfer error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// A target did not acknowledge.
    Nack,
    /// Transmit underrun.
    Underrun,
    /// A write was aborted.
    WriteAbort,
    /// A target terminated a transfer.
    Terminated,
    /// FIFO over-read or overwrite.
    Fifo,
    /// A malformed message or invalid controller request.
    Protocol,
    /// The hardware timeout expired, or a blocking wait ran out of its
    /// [`Timeout`] budget.
    Timeout,
    /// Address or buffer arguments are invalid.
    InvalidArgument,
}

/// Controller clock configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
    /// Functional clock feeding the I3C instance.
    pub clock_hz: u32,
    /// I3C push-pull SCL frequency.
    pub push_pull_hz: u32,
    /// I3C open-drain SCL frequency.
    pub open_drain_hz: u32,
    /// Legacy I2C SCL frequency.
    pub i2c_hz: u32,
}

impl Config {
    /// A conservative configuration based on a 24 MHz functional clock.
    pub const fn new(clock_hz: u32) -> Self {
        Self {
            clock_hz,
            push_pull_hz: 4_000_000,
            open_drain_hz: 1_000_000,
            i2c_hz: 400_000,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Baud {
    pp: u8,
    od: u8,
    i2c: u8,
}

fn baud(config: Config) -> Result<Baud, ConfigError> {
    if config.clock_hz == 0
        || config.push_pull_hz == 0
        || config.open_drain_hz == 0
        || config.i2c_hz == 0
        || config.push_pull_hz > config.clock_hz / 2
    {
        return Err(ConfigError::InvalidFrequency);
    }

    // NXP: push-pull frequency is fclk / (2 * (PPBAUD + 1)).
    let pp_div = config
        .clock_hz
        .div_ceil(config.push_pull_hz.saturating_mul(2));
    if !(1..=16).contains(&pp_div) {
        return Err(ConfigError::InvalidFrequency);
    }
    let pp = pp_div - 1;
    let actual_pp = config.clock_hz / (2 * (pp + 1));
    if config.open_drain_hz > actual_pp {
        return Err(ConfigError::InvalidFrequency);
    }

    // Use high-speed open-drain mode, matching Embassy MCXA: OD frequency is
    // 2 * PP / (ODBAUD + 2).
    let od_div = actual_pp
        .saturating_mul(2)
        .div_ceil(config.open_drain_hz)
        .max(2);
    if od_div > 257 {
        return Err(ConfigError::InvalidFrequency);
    }
    let od = od_div - 2;

    // The I2C divider is a four-bit multiplier on the OD timing. Select the
    // first value that does not exceed the requested rate.
    let od_rate = actual_pp.saturating_mul(2) / od_div;
    if config.i2c_hz > od_rate {
        return Err(ConfigError::InvalidFrequency);
    }
    let i2c_div = od_rate.div_ceil(config.i2c_hz).clamp(1, 16);

    Ok(Baud {
        pp: pp as u8,
        od: od as u8,
        i2c: (i2c_div - 1) as u8,
    })
}

/// Per-instance interrupt state.
pub struct State {
    waker: AtomicWaker,
}

impl State {
    /// Create state suitable for a `static`.
    pub(crate) const fn new() -> Self {
        Self {
            waker: AtomicWaker::new(),
        }
    }

    /// Mask asserted controller interrupts and wake the pending async transfer.
    fn on_interrupt(&self, r: I3C) {
        let pending = r.MINTMASKED().read().0;
        if pending != 0 {
            r.MINTCLR()
                .write_value(pac::peripherals::i3c::I3C_MINTCLR(pending));
            self.waker.wake();
        }
    }
}

/// Crate-internal half of [`Instance`]: visible to the generated bindings that
/// implement it, sealed against downstream crates.
pub(crate) trait SealedInstance {
    /// This instance's register block, at its database-resolved base.
    fn regs() -> I3C;
    /// This instance's dedicated interrupt state.
    fn state() -> &'static State;
    /// The CCM gate the constructor opens before the first register access
    /// (see [`crate::clock`]); `None` where this core need not open one.
    const LPCG: Option<u32>;
}

/// An I3C instance the [`I3c`] driver can drive.
///
/// Implemented by the generated peripheral singletons; sealed so the base
/// address and interrupt state stay single-sourced from the chip database.
#[allow(private_bounds)]
pub trait Instance: SealedInstance + PeripheralType {
    /// NVIC line this instance raises, when the chip routes one to this core.
    const IRQ: Option<u16>;
}

/// Bind a generated peripheral singleton to this driver. Invoked only by the
/// generated `peripherals` module.
macro_rules! impl_i3c {
    ($instance:ident, $base:expr, $irq:expr) => {
        impl crate::i3c::SealedInstance for crate::peripherals::$instance {
            const LPCG: ::core::option::Option<u32> = crate::clock::lpcg(stringify!($instance));

            #[inline]
            fn regs() -> crate::pac::peripherals::i3c::I3C {
                // SAFETY: `$base` is this instance's base as extracted from the
                // chip database, and the singleton this impl is keyed to can be
                // held by only one driver at a time.
                unsafe { crate::pac::peripherals::i3c::I3C::from_ptr($base as *mut ()) }
            }

            #[inline]
            fn state() -> &'static crate::i3c::State {
                static STATE: crate::i3c::State = crate::i3c::State::new();
                &STATE
            }
        }

        impl crate::i3c::Instance for crate::peripherals::$instance {
            const IRQ: ::core::option::Option<u16> = $irq;
        }
    };
}
pub(crate) use impl_i3c;

/// Handle the interrupt of instance `T`.
///
/// Call this from the application's `#[interrupt]` handler for `T`'s vector;
/// the HAL installs no handlers of its own.
pub fn on_interrupt<T: Instance>() {
    T::state().on_interrupt(T::regs());
}

/// Controller over one i.MX9 I3C instance.
pub struct I3c {
    regs: I3C,
    state: &'static State,
    timeout: Timeout,
}

impl I3c {
    /// Configure an instance from its peripheral singleton.
    ///
    /// The platform must leave the instance clocked and pinned out. For async
    /// transfers, forward its interrupt to [`on_interrupt::<T>`](on_interrupt).
    pub fn new<T: Instance>(peri: Peri<'static, T>, config: Config) -> Result<Self, ConfigError> {
        let b = baud(config)?;
        // Owning the singleton for the driver's lifetime is what makes exclusive
        // register access safe; it is consumed here and never reissued.
        let _ = peri;
        // On i.MX 93 Linux closes the gate of every peripheral no kernel
        // driver claims; the first register access would BusFault without this.
        crate::clock::ungate(T::LPCG);
        let regs = T::regs();

        regs.MCONFIG().write(|w| w.set_MSTENA(0));
        regs.MDATACTRL().write(|w| {
            w.set_FLUSHTB(true);
            w.set_FLUSHFB(true);
            w.set_UNLOCK(true);
            w.set_TXTRIG(0);
            w.set_RXTRIG(0);
        });
        regs.MCONFIG().write(|w| {
            w.set_PPBAUD(b.pp);
            w.set_ODBAUD(b.od);
            w.set_I2CBAUD(b.i2c);
            w.set_ODHPP(true);
            // `DISTO = 0` keeps the hardware transfer timeout enabled.
            w.set_DISTO(false);
            w.set_MSTENA(MASTER_ON);
        });
        Ok(Self {
            regs,
            state: T::state(),
            timeout: Timeout::DEFAULT,
        })
    }

    /// Bound every blocking wait (one FIFO slot, one byte, a control request,
    /// message completion) to `timeout` polls. Defaults to
    /// [`Timeout::DEFAULT`].
    pub fn set_timeout(&mut self, timeout: Timeout) {
        self.timeout = timeout;
    }

    /// Spin until `ready` yields a value, surfacing any error first.
    fn wait_blocking<T>(&self, mut ready: impl FnMut(&I3C) -> Option<T>) -> Result<T, Error> {
        let mut deadline = self.timeout.start();
        loop {
            self.check_error()?;
            if let Some(value) = ready(&self.regs) {
                return Ok(value);
            }
            deadline.tick().map_err(|_| Error::Timeout)?;
        }
    }

    fn clear_status(&self) {
        self.regs
            .MSTATUS()
            .write_value(pac::peripherals::i3c::I3C_MSTATUS(
                (1 << 8) | (1 << 9) | (1 << 10) | (1 << 15),
            ));
        self.regs
            .MERRWARN()
            .write_value(pac::peripherals::i3c::I3C_MERRWARN(u32::MAX));
    }

    fn check_error(&self) -> Result<(), Error> {
        let e = self.regs.MERRWARN().read();
        if e.NACK() {
            return Err(Error::Nack);
        }
        if e.URUN() {
            return Err(Error::Underrun);
        }
        if e.WRABT() {
            return Err(Error::WriteAbort);
        }
        if e.TERM() {
            return Err(Error::Terminated);
        }
        if e.OREAD() || e.OWRITE() {
            return Err(Error::Fifo);
        }
        if e.MSGERR() || e.INVREQ() || e.HPAR() || e.HCRC() {
            return Err(Error::Protocol);
        }
        if e.TIMEOUT() {
            return Err(Error::Timeout);
        }
        Ok(())
    }

    fn start(&self, address: u8, read: bool, len: usize, mode: BusMode) -> Result<(), Error> {
        if address >= 0x80 || len > MAX_READ_CHUNK {
            return Err(Error::InvalidArgument);
        }
        self.regs.MCTRL().write(|w| {
            w.set_REQUEST(REQUEST_START);
            w.set_TYPE(mode.type_bits());
            w.set_DIR(read);
            w.set_ADDR(address);
            // Zero encodes 256 bytes for reads.
            w.set_RDTERM((len & 0xff) as u8);
        });
        self.wait_control()
    }

    fn wait_control(&self) -> Result<(), Error> {
        self.wait_blocking(|r| r.MSTATUS().read().MCTRLDONE().then_some(()))?;
        self.regs.MSTATUS().write(|w| w.set_MCTRLDONE(true));
        Ok(())
    }

    fn wait_tx(&self) -> Result<(), Error> {
        self.wait_blocking(|r| r.MSTATUS().read().TXNOTFULL().then_some(()))
    }

    fn wait_rx(&self) -> Result<u8, Error> {
        self.wait_blocking(|r| {
            r.MSTATUS()
                .read()
                .RXPEND()
                .then(|| r.MRDATAB().read().VALUE())
        })
    }

    fn wait_complete(&self) -> Result<(), Error> {
        self.wait_blocking(|r| r.MSTATUS().read().COMPLETE().then_some(()))?;
        self.regs.MSTATUS().write(|w| w.set_COMPLETE(true));
        Ok(())
    }

    fn stop(&self, mode: BusMode) -> Result<(), Error> {
        self.regs
            .MCONFIG()
            .modify(|w| w.set_ODSTOP(mode == BusMode::I2c));
        self.regs.MCTRL().write(|w| {
            w.set_REQUEST(REQUEST_STOP);
            w.set_TYPE(mode.type_bits());
        });
        self.wait_control()
    }

    fn write_part(&self, address: u8, bytes: &[u8], mode: BusMode) -> Result<(), Error> {
        self.start(address, false, 0, mode)?;
        if let Some((last, rest)) = bytes.split_last() {
            for &byte in rest {
                self.wait_tx()?;
                self.regs
                    .MWDATAB()
                    .write_value(I3C_MWDATAB(u32::from(byte)));
            }
            self.wait_tx()?;
            self.regs
                .MWDATABE()
                .write_value(I3C_MWDATABE(u32::from(*last)));
            self.wait_complete()?;
        }
        Ok(())
    }

    fn read_part(&self, address: u8, bytes: &mut [u8], mode: BusMode) -> Result<(), Error> {
        if bytes.is_empty() {
            return Err(Error::InvalidArgument);
        }
        for chunk in bytes.chunks_mut(MAX_READ_CHUNK) {
            self.start(address, true, chunk.len(), mode)?;
            for byte in chunk {
                *byte = self.wait_rx()?;
            }
        }
        Ok(())
    }

    /// Blocking private write followed by STOP.
    pub fn blocking_write(
        &mut self,
        address: u8,
        bytes: &[u8],
        mode: BusMode,
    ) -> Result<(), Error> {
        self.clear_status();
        let guard = RecoverGuard::new(self.regs, mode);
        self.write_part(address, bytes, mode)?;
        self.stop(mode)?;
        guard.defuse();
        Ok(())
    }

    /// Blocking private read followed by STOP.
    pub fn blocking_read(
        &mut self,
        address: u8,
        bytes: &mut [u8],
        mode: BusMode,
    ) -> Result<(), Error> {
        self.clear_status();
        let guard = RecoverGuard::new(self.regs, mode);
        self.read_part(address, bytes, mode)?;
        self.stop(mode)?;
        guard.defuse();
        Ok(())
    }

    /// Blocking write/read with a repeated START.
    pub fn blocking_write_read(
        &mut self,
        address: u8,
        write: &[u8],
        read: &mut [u8],
        mode: BusMode,
    ) -> Result<(), Error> {
        self.clear_status();
        let guard = RecoverGuard::new(self.regs, mode);
        self.write_part(address, write, mode)?;
        self.read_part(address, read, mode)?;
        self.stop(mode)?;
        guard.defuse();
        Ok(())
    }

    /// Execute a repeated-start transaction and emit one final STOP.
    pub fn blocking_transaction(
        &mut self,
        address: u8,
        operations: &mut [Operation<'_>],
        mode: BusMode,
    ) -> Result<(), Error> {
        if operations.is_empty() {
            return Ok(());
        }
        self.clear_status();
        let guard = RecoverGuard::new(self.regs, mode);
        for operation in operations {
            match operation {
                Operation::Read(bytes) => self.read_part(address, bytes, mode)?,
                Operation::Write(bytes) => self.write_part(address, bytes, mode)?,
            }
        }
        self.stop(mode)?;
        guard.defuse();
        Ok(())
    }

    /// Send one broadcast CCC with no defining byte.
    pub fn broadcast_ccc(&mut self, command: u8) -> Result<(), Error> {
        self.blocking_write(0x7e, &[command], BusMode::I3cSdr)
    }

    /// Reset target dynamic addresses with the broadcast RSTDAA CCC.
    pub fn reset_daa(&mut self) -> Result<(), Error> {
        self.broadcast_ccc(0x06)
    }

    /// Run ENTDAA and assign consecutive dynamic addresses.
    ///
    /// The slice bounds the number of devices accepted. The returned count can
    /// be smaller when fewer targets participate.
    pub fn daa(&mut self, devices: &mut [DeviceInfo], first_address: u8) -> Result<usize, Error> {
        if first_address == 0
            || first_address >= 0x7e
            || first_address as usize + devices.len() >= 0x7e
        {
            return Err(Error::InvalidArgument);
        }
        self.clear_status();
        self.regs.MCTRL().write(|w| w.set_REQUEST(REQUEST_DAA));

        let mut assigned = 0;
        for device in devices {
            let complete = self.wait_blocking(|r| {
                let status = r.MSTATUS().read();
                if status.COMPLETE() {
                    return Some(true);
                }
                // MSTATUS.STATE = 0b101 while the controller is in DAA.
                (status.MCTRLDONE() && status.STATE() == 5).then_some(false)
            })?;
            if complete {
                return Ok(assigned);
            }

            let mut payload = [0u8; 8];
            for byte in &mut payload {
                *byte = self.wait_blocking(|r| {
                    (!r.MDATACTRL().read().RXEMPTY()).then(|| r.MRDATAB().read().VALUE())
                })?;
            }
            let address = first_address + assigned as u8;
            *device = DeviceInfo {
                manufacturer_id: u16::from_be_bytes([payload[0], payload[1]]) >> 1,
                part_number: u32::from_be_bytes([payload[2], payload[3], payload[4], payload[5]]),
                bcr: payload[6],
                dcr: payload[7],
                dynamic_address: address,
            };
            self.regs
                .MWDATAB()
                .write_value(I3C_MWDATAB(u32::from(address)));
            self.regs.MCTRL().write(|w| w.set_REQUEST(REQUEST_DAA));
            assigned += 1;
        }
        Ok(assigned)
    }

    async fn wait_async(
        &self,
        mask: u32,
        ready: impl Fn(&Self) -> Option<Result<(), Error>>,
    ) -> Result<(), Error> {
        poll_fn(|cx| {
            if let Some(result) = ready(self) {
                return Poll::Ready(result);
            }
            self.state.waker.register(cx.waker());
            self.regs
                .MINTSET()
                .write_value(pac::peripherals::i3c::I3C_MINTSET(mask));
            if let Some(result) = ready(self) {
                return Poll::Ready(result);
            }
            Poll::Pending
        })
        .await
    }

    async fn start_async(
        &self,
        address: u8,
        read: bool,
        len: usize,
        mode: BusMode,
    ) -> Result<(), Error> {
        if address >= 0x80 || len > MAX_READ_CHUNK {
            return Err(Error::InvalidArgument);
        }
        self.regs.MCTRL().write(|w| {
            w.set_REQUEST(REQUEST_START);
            w.set_TYPE(mode.type_bits());
            w.set_DIR(read);
            w.set_ADDR(address);
            w.set_RDTERM((len & 0xff) as u8);
        });
        self.wait_async((1 << 9) | (1 << 15), |s| match s.check_error() {
            Err(e) => Some(Err(e)),
            Ok(()) if s.regs.MSTATUS().read().MCTRLDONE() => Some(Ok(())),
            Ok(()) => None,
        })
        .await
    }

    async fn write_part_async(
        &self,
        address: u8,
        bytes: &[u8],
        mode: BusMode,
    ) -> Result<(), Error> {
        self.start_async(address, false, 0, mode).await?;
        if let Some((last, rest)) = bytes.split_last() {
            for &byte in rest {
                self.wait_async((1 << 12) | (1 << 15), |s| match s.check_error() {
                    Err(e) => Some(Err(e)),
                    Ok(()) if s.regs.MSTATUS().read().TXNOTFULL() => Some(Ok(())),
                    Ok(()) => None,
                })
                .await?;
                self.regs
                    .MWDATAB()
                    .write_value(I3C_MWDATAB(u32::from(byte)));
            }
            self.wait_async((1 << 12) | (1 << 15), |s| match s.check_error() {
                Err(e) => Some(Err(e)),
                Ok(()) if s.regs.MSTATUS().read().TXNOTFULL() => Some(Ok(())),
                Ok(()) => None,
            })
            .await?;
            self.regs
                .MWDATABE()
                .write_value(I3C_MWDATABE(u32::from(*last)));
            self.wait_async((1 << 10) | (1 << 15), |s| match s.check_error() {
                Err(e) => Some(Err(e)),
                Ok(()) if s.regs.MSTATUS().read().COMPLETE() => Some(Ok(())),
                Ok(()) => None,
            })
            .await?;
        }
        Ok(())
    }

    async fn read_part_async(
        &self,
        address: u8,
        bytes: &mut [u8],
        mode: BusMode,
    ) -> Result<(), Error> {
        if bytes.is_empty() {
            return Err(Error::InvalidArgument);
        }
        for chunk in bytes.chunks_mut(MAX_READ_CHUNK) {
            self.start_async(address, true, chunk.len(), mode).await?;
            for byte in chunk {
                self.wait_async((1 << 11) | (1 << 15), |s| match s.check_error() {
                    Err(e) => Some(Err(e)),
                    Ok(()) if s.regs.MSTATUS().read().RXPEND() => Some(Ok(())),
                    Ok(()) => None,
                })
                .await?;
                *byte = self.regs.MRDATAB().read().VALUE();
            }
        }
        Ok(())
    }

    async fn stop_async(&self, mode: BusMode) -> Result<(), Error> {
        self.regs
            .MCONFIG()
            .modify(|w| w.set_ODSTOP(mode == BusMode::I2c));
        self.regs.MCTRL().write(|w| {
            w.set_REQUEST(REQUEST_STOP);
            w.set_TYPE(mode.type_bits());
        });
        self.wait_async((1 << 9) | (1 << 15), |s| match s.check_error() {
            Err(e) => Some(Err(e)),
            Ok(()) if s.regs.MSTATUS().read().MCTRLDONE() => Some(Ok(())),
            Ok(()) => None,
        })
        .await
    }

    /// Async private write followed by STOP.
    pub async fn write(&mut self, address: u8, bytes: &[u8], mode: BusMode) -> Result<(), Error> {
        self.clear_status();
        let guard = RecoverGuard::new(self.regs, mode);
        self.write_part_async(address, bytes, mode).await?;
        self.stop_async(mode).await?;
        guard.defuse();
        Ok(())
    }

    /// Async private read followed by STOP.
    pub async fn read(
        &mut self,
        address: u8,
        bytes: &mut [u8],
        mode: BusMode,
    ) -> Result<(), Error> {
        self.clear_status();
        let guard = RecoverGuard::new(self.regs, mode);
        self.read_part_async(address, bytes, mode).await?;
        self.stop_async(mode).await?;
        guard.defuse();
        Ok(())
    }

    /// Async write/read with a repeated START.
    pub async fn write_read(
        &mut self,
        address: u8,
        write: &[u8],
        read: &mut [u8],
        mode: BusMode,
    ) -> Result<(), Error> {
        self.clear_status();
        let guard = RecoverGuard::new(self.regs, mode);
        self.write_part_async(address, write, mode).await?;
        self.read_part_async(address, read, mode).await?;
        self.stop_async(mode).await?;
        guard.defuse();
        Ok(())
    }

    /// Async repeated-start transaction.
    pub async fn transaction(
        &mut self,
        address: u8,
        operations: &mut [Operation<'_>],
        mode: BusMode,
    ) -> Result<(), Error> {
        if operations.is_empty() {
            return Ok(());
        }
        self.clear_status();
        let guard = RecoverGuard::new(self.regs, mode);
        for operation in operations {
            match operation {
                Operation::Read(bytes) => self.read_part_async(address, bytes, mode).await?,
                Operation::Write(bytes) => self.write_part_async(address, bytes, mode).await?,
            }
        }
        self.stop_async(mode).await?;
        guard.defuse();
        Ok(())
    }
}

/// Upper bound on status polls while waiting for a recovery STOP. Drop cannot
/// await or read a clock, so this is a spin count: comfortably more than one
/// open-drain byte plus STOP at the slowest supported I2C rate.
const RECOVERY_SPINS: u32 = 200_000;

/// Return the controller to idle after a failed or abandoned transfer.
///
/// Follows `embassy-mcxa`'s `blocking_remediation`: drop whatever the FIFOs
/// still hold, then, if the controller has not returned to idle (a NACK, or a
/// transfer dropped mid-flight, leaves it holding the bus), emit a STOP and
/// give it time to complete.
fn recover(r: I3C, mode: BusMode) {
    r.MINTCLR()
        .write_value(pac::peripherals::i3c::I3C_MINTCLR(u32::MAX));
    r.MDATACTRL().modify(|w| {
        w.set_FLUSHTB(true);
        w.set_FLUSHFB(true);
    });
    let clear = || {
        r.MSTATUS().write_value(pac::peripherals::i3c::I3C_MSTATUS(
            (1 << 8) | (1 << 9) | (1 << 10) | (1 << 15),
        ));
        r.MERRWARN()
            .write_value(pac::peripherals::i3c::I3C_MERRWARN(u32::MAX));
    };
    clear();
    if r.MSTATUS().read().STATE() != 0 {
        r.MCONFIG().modify(|w| w.set_ODSTOP(mode == BusMode::I2c));
        r.MCTRL().write(|w| {
            w.set_REQUEST(REQUEST_STOP);
            w.set_TYPE(mode.type_bits());
        });
        let mut spins = RECOVERY_SPINS;
        while spins > 0 && !r.MSTATUS().read().MCTRLDONE() {
            spins -= 1;
        }
    }
    clear();
}

/// Runs [`recover`] when dropped unless [`defuse`](Self::defuse)d, so an
/// error propagated with `?` and an async transfer dropped mid-flight both
/// leave the controller idle and the bus released.
struct RecoverGuard {
    regs: I3C,
    mode: BusMode,
    armed: bool,
}

impl RecoverGuard {
    fn new(regs: I3C, mode: BusMode) -> Self {
        Self {
            regs,
            mode,
            armed: true,
        }
    }

    /// The transfer completed cleanly; skip recovery.
    fn defuse(mut self) {
        self.armed = false;
    }
}

impl Drop for RecoverGuard {
    fn drop(&mut self) {
        if self.armed {
            recover(self.regs, self.mode);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Config, baud};

    #[test]
    fn common_clock_plan_fits() {
        let b = baud(Config::new(24_000_000)).unwrap();
        assert!(b.pp <= 15);
    }

    #[test]
    fn impossible_push_pull_rate_is_rejected() {
        let mut config = Config::new(1_000_000);
        config.push_pull_hz = 10_000_000;
        assert!(baud(config).is_err());
    }

    #[test]
    fn open_drain_cannot_exceed_push_pull_clock() {
        let mut config = Config::new(24_000_000);
        config.open_drain_hz = 20_000_000;
        assert!(baud(config).is_err());
    }
}