aboutsummaryrefslogtreecommitdiff
path: root/embassy-stm32/src/i2c/v1.rs
blob: 128a58db78e3777b95ca7223f2ebea544f7807d0 (plain)
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
//! # I2Cv1
//!
//! This implementation is used for STM32F1, STM32F2, STM32F4, and STM32L1 devices.
//!
//! All other devices (as of 2023-12-28) use [`v2`](super::v2) instead.

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

use embassy_embedded_hal::SetConfig;
use embassy_futures::select::{Either, select};
use embassy_hal_internal::drop::OnDrop;
use embedded_hal_1::i2c::Operation;
use mode::Master;

use super::*;
use crate::mode::Mode as PeriMode;
use crate::pac::i2c;

// /!\                      /!\
// /!\ Implementation note! /!\
// /!\                      /!\
//
// It's somewhat unclear whether using interrupts here in a *strictly* one-shot style is actually
// what we want! If you are looking in this file because you are doing async I2C and your code is
// just totally hanging (sometimes), maybe swing by this issue:
// <https://github.com/embassy-rs/embassy/issues/2372>.
//
// There's some more details there, and we might have a fix for you. But please let us know if you
// hit a case like this!
pub unsafe fn on_interrupt<T: Instance>() {
    let regs = T::info().regs;
    trace!("I2C interrupt triggered");
    // i2c v2 only woke the task on transfer complete interrupts. v1 uses interrupts for a bunch of
    // other stuff, so we wake the task on every interrupt.
    T::state().waker.wake();
    critical_section::with(|_| {
        // Clear event interrupt flag.
        regs.cr2().modify(|w| {
            w.set_itevten(false);
            w.set_iterren(false);
        });
    });
}

impl<'d, M: PeriMode, IM: MasterMode> I2c<'d, M, IM> {
    pub(crate) fn init(&mut self, config: Config) {
        self.info.regs.cr1().modify(|reg| {
            reg.set_pe(false);
            //reg.set_anfoff(false);
        });

        // Errata: "Start cannot be generated after a misplaced Stop"
        //
        // > If a master generates a misplaced Stop on the bus (bus error)
        // > while the microcontroller I2C peripheral attempts to switch to
        // > Master mode by setting the START bit, the Start condition is
        // > not properly generated.
        //
        // This also can occur with falsely detected STOP events, for example
        // if the SDA line is shorted to low.
        //
        // The workaround for this is to trigger the SWRST line AFTER power is
        // enabled, AFTER PE is disabled and BEFORE making any other configuration.
        //
        // It COULD be possible to apply this workaround at runtime, instead of
        // only on initialization, however this would require detecting the timeout
        // or BUSY lockup condition, and re-configuring the peripheral after reset.
        //
        // This presents as an ~infinite hang on read or write, as the START condition
        // is never generated, meaning the start event is never generated.
        self.info.regs.cr1().modify(|reg| {
            reg.set_swrst(true);
        });
        self.info.regs.cr1().modify(|reg| {
            reg.set_swrst(false);
        });

        let timings = Timings::new(self.kernel_clock, config.frequency);

        self.info.regs.cr2().modify(|reg| {
            reg.set_freq(timings.freq);
        });
        self.info.regs.ccr().modify(|reg| {
            reg.set_f_s(timings.mode.f_s());
            reg.set_duty(timings.duty.duty());
            reg.set_ccr(timings.ccr);
        });
        self.info.regs.trise().modify(|reg| {
            reg.set_trise(timings.trise);
        });

        self.info.regs.cr1().modify(|reg| {
            reg.set_pe(true);
        });
        trace!("i2c v1 init complete");
    }

    fn check_and_clear_error_flags(info: &'static Info) -> Result<i2c::regs::Sr1, Error> {
        // Note that flags should only be cleared once they have been registered. If flags are
        // cleared otherwise, there may be an inherent race condition and flags may be missed.
        let sr1 = info.regs.sr1().read();

        if sr1.timeout() {
            info.regs.sr1().write(|reg| {
                reg.0 = !0;
                reg.set_timeout(false);
            });
            return Err(Error::Timeout);
        }

        if sr1.pecerr() {
            info.regs.sr1().write(|reg| {
                reg.0 = !0;
                reg.set_pecerr(false);
            });
            return Err(Error::Crc);
        }

        if sr1.ovr() {
            info.regs.sr1().write(|reg| {
                reg.0 = !0;
                reg.set_ovr(false);
            });
            return Err(Error::Overrun);
        }

        if sr1.af() {
            info.regs.sr1().write(|reg| {
                reg.0 = !0;
                reg.set_af(false);
            });
            return Err(Error::Nack);
        }

        if sr1.arlo() {
            info.regs.sr1().write(|reg| {
                reg.0 = !0;
                reg.set_arlo(false);
            });
            return Err(Error::Arbitration);
        }

        // The errata indicates that BERR may be incorrectly detected. It recommends ignoring and
        // clearing the BERR bit instead.
        if sr1.berr() {
            info.regs.sr1().write(|reg| {
                reg.0 = !0;
                reg.set_berr(false);
            });
        }

        Ok(sr1)
    }

    fn write_bytes(
        &mut self,
        address: u8,
        write_buffer: &[u8],
        timeout: Timeout,
        frame: FrameOptions,
    ) -> Result<(), Error> {
        if frame.send_start() {
            // Send a START condition

            self.info.regs.cr1().modify(|reg| {
                reg.set_start(true);
            });

            // Wait until START condition was generated
            while !Self::check_and_clear_error_flags(self.info)?.start() {
                timeout.check()?;
            }

            // Check if we were the ones to generate START
            if self.info.regs.cr1().read().start() || !self.info.regs.sr2().read().msl() {
                return Err(Error::Arbitration);
            }

            // Set up current address we're trying to talk to
            self.info.regs.dr().write(|reg| reg.set_dr(address << 1));

            // Wait until address was sent
            // Wait for the address to be acknowledged
            // Check for any I2C errors. If a NACK occurs, the ADDR bit will never be set.
            while !Self::check_and_clear_error_flags(self.info)?.addr() {
                timeout.check()?;
            }

            // Clear condition by reading SR2
            let _ = self.info.regs.sr2().read();
        }

        // Send bytes
        for c in write_buffer {
            self.send_byte(*c, timeout)?;
        }

        if frame.send_stop() {
            // Send a STOP condition
            self.info.regs.cr1().modify(|reg| reg.set_stop(true));
        }

        // Fallthrough is success
        Ok(())
    }

    fn send_byte(&self, byte: u8, timeout: Timeout) -> Result<(), Error> {
        // Wait until we're ready for sending
        while {
            // Check for any I2C errors. If a NACK occurs, the ADDR bit will never be set.
            !Self::check_and_clear_error_flags(self.info)?.txe()
        } {
            timeout.check()?;
        }

        // Push out a byte of data
        self.info.regs.dr().write(|reg| reg.set_dr(byte));

        // Wait until byte is transferred
        while {
            // Check for any potential error conditions.
            !Self::check_and_clear_error_flags(self.info)?.btf()
        } {
            timeout.check()?;
        }

        Ok(())
    }

    fn recv_byte(&self, timeout: Timeout) -> Result<u8, Error> {
        while {
            // Check for any potential error conditions.
            Self::check_and_clear_error_flags(self.info)?;

            !self.info.regs.sr1().read().rxne()
        } {
            timeout.check()?;
        }

        let value = self.info.regs.dr().read().dr();
        Ok(value)
    }

    fn blocking_read_timeout(
        &mut self,
        address: u8,
        read_buffer: &mut [u8],
        timeout: Timeout,
        frame: FrameOptions,
    ) -> Result<(), Error> {
        let Some((last_byte, read_buffer)) = read_buffer.split_last_mut() else {
            return Err(Error::Overrun);
        };

        if frame.send_start() {
            // Send a START condition and set ACK bit
            self.info.regs.cr1().modify(|reg| {
                reg.set_start(true);
                reg.set_ack(true);
            });

            // Wait until START condition was generated
            while !Self::check_and_clear_error_flags(self.info)?.start() {
                timeout.check()?;
            }

            // Check if we were the ones to generate START
            if self.info.regs.cr1().read().start() || !self.info.regs.sr2().read().msl() {
                return Err(Error::Arbitration);
            }

            // Set up current address we're trying to talk to
            self.info.regs.dr().write(|reg| reg.set_dr((address << 1) + 1));

            // Wait until address was sent
            // Wait for the address to be acknowledged
            while !Self::check_and_clear_error_flags(self.info)?.addr() {
                timeout.check()?;
            }

            // Clear condition by reading SR2
            let _ = self.info.regs.sr2().read();
        }

        // Receive bytes into buffer
        for c in read_buffer {
            *c = self.recv_byte(timeout)?;
        }

        // Prepare to send NACK then STOP after next byte
        self.info.regs.cr1().modify(|reg| {
            if frame.send_nack() {
                reg.set_ack(false);
            }
            if frame.send_stop() {
                reg.set_stop(true);
            }
        });

        // Receive last byte
        *last_byte = self.recv_byte(timeout)?;

        // Fallthrough is success
        Ok(())
    }

    /// Blocking read.
    pub fn blocking_read(&mut self, address: u8, read_buffer: &mut [u8]) -> Result<(), Error> {
        self.blocking_read_timeout(address, read_buffer, self.timeout(), FrameOptions::FirstAndLastFrame)
    }

    /// Blocking write.
    pub fn blocking_write(&mut self, address: u8, write_buffer: &[u8]) -> Result<(), Error> {
        self.write_bytes(address, write_buffer, self.timeout(), FrameOptions::FirstAndLastFrame)?;

        // Fallthrough is success
        Ok(())
    }

    /// Blocking write, restart, read.
    pub fn blocking_write_read(
        &mut self,
        address: u8,
        write_buffer: &[u8],
        read_buffer: &mut [u8],
    ) -> Result<(), Error> {
        // Check empty read buffer before starting transaction. Otherwise, we would not generate the
        // stop condition below.
        if read_buffer.is_empty() {
            return Err(Error::Overrun);
        }

        let timeout = self.timeout();

        self.write_bytes(address, write_buffer, timeout, FrameOptions::FirstFrame)?;
        self.blocking_read_timeout(address, read_buffer, timeout, FrameOptions::FirstAndLastFrame)?;

        Ok(())
    }

    /// Blocking transaction with operations.
    ///
    /// Consecutive operations of same type are merged. See [transaction contract] for details.
    ///
    /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction
    pub fn blocking_transaction(&mut self, address: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> {
        let timeout = self.timeout();

        for (op, frame) in operation_frames(operations)? {
            match op {
                Operation::Read(read_buffer) => self.blocking_read_timeout(address, read_buffer, timeout, frame)?,
                Operation::Write(write_buffer) => self.write_bytes(address, write_buffer, timeout, frame)?,
            }
        }

        Ok(())
    }

    /// Can be used by both blocking and async implementations  
    #[inline] // pretty sure this should always be inlined
    fn enable_interrupts(info: &'static Info) {
        // The interrupt handler disables interrupts globally, so we need to re-enable them
        // This must be done in a critical section to avoid races
        critical_section::with(|_| {
            info.regs.cr2().modify(|w| {
                w.set_iterren(true);
                w.set_itevten(true);
            });
        });
    }

    /// Can be used by both blocking and async implementations
    fn clear_stop_flag(info: &'static Info) {
        trace!("I2C slave: clearing STOPF flag (v1 sequence)");
        // v1 requires: READ SR1 then WRITE CR1 to clear STOPF
        let _ = info.regs.sr1().read();
        info.regs.cr1().modify(|_| {}); // Dummy write to clear STOPF
    }
}

impl<'d, IM: MasterMode> I2c<'d, Async, IM> {
    async fn write_frame(&mut self, address: u8, write_buffer: &[u8], frame: FrameOptions) -> Result<(), Error> {
        self.info.regs.cr2().modify(|w| {
            // Note: Do not enable the ITBUFEN bit in the I2C_CR2 register if DMA is used for
            // reception.
            w.set_itbufen(false);
            // DMA mode can be enabled for transmission by setting the DMAEN bit in the I2C_CR2
            // register.
            w.set_dmaen(true);
            // Sending NACK is not necessary (nor possible) for write transfer.
            w.set_last(false);
        });

        // Sentinel to disable transfer when an error occurs or future is canceled.
        // TODO: Generate STOP condition on cancel?
        let on_drop = OnDrop::new(|| {
            self.info.regs.cr2().modify(|w| {
                w.set_dmaen(false);
                w.set_iterren(false);
                w.set_itevten(false);
            })
        });

        if frame.send_start() {
            // Send a START condition
            self.info.regs.cr1().modify(|reg| {
                reg.set_start(true);
            });

            // Wait until START condition was generated
            poll_fn(|cx| {
                self.state.waker.register(cx.waker());

                match Self::check_and_clear_error_flags(self.info) {
                    Err(e) => Poll::Ready(Err(e)),
                    Ok(sr1) => {
                        if sr1.start() {
                            Poll::Ready(Ok(()))
                        } else {
                            // When pending, (re-)enable interrupts to wake us up.
                            Self::enable_interrupts(self.info);
                            Poll::Pending
                        }
                    }
                }
            })
            .await?;

            // Check if we were the ones to generate START
            if self.info.regs.cr1().read().start() || !self.info.regs.sr2().read().msl() {
                return Err(Error::Arbitration);
            }

            // Set up current address we're trying to talk to
            self.info.regs.dr().write(|reg| reg.set_dr(address << 1));

            // Wait for the address to be acknowledged
            poll_fn(|cx| {
                self.state.waker.register(cx.waker());

                match Self::check_and_clear_error_flags(self.info) {
                    Err(e) => Poll::Ready(Err(e)),
                    Ok(sr1) => {
                        if sr1.addr() {
                            Poll::Ready(Ok(()))
                        } else {
                            // When pending, (re-)enable interrupts to wake us up.
                            Self::enable_interrupts(self.info);
                            Poll::Pending
                        }
                    }
                }
            })
            .await?;

            // Clear condition by reading SR2
            self.info.regs.sr2().read();
        }

        let dma_transfer = unsafe {
            // Set the I2C_DR register address in the DMA_SxPAR register. The data will be moved to
            // this address from the memory after each TxE event.
            let dst = self.info.regs.dr().as_ptr() as *mut u8;

            self.tx_dma
                .as_mut()
                .unwrap()
                .write(write_buffer, dst, Default::default())
        };

        // Wait for bytes to be sent, or an error to occur.
        let poll_error = poll_fn(|cx| {
            self.state.waker.register(cx.waker());

            match Self::check_and_clear_error_flags(self.info) {
                Err(e) => Poll::Ready(Err::<(), Error>(e)),
                Ok(_) => {
                    // When pending, (re-)enable interrupts to wake us up.
                    Self::enable_interrupts(self.info);
                    Poll::Pending
                }
            }
        });

        // Wait for either the DMA transfer to successfully finish, or an I2C error to occur.
        match select(dma_transfer, poll_error).await {
            Either::Second(Err(e)) => Err(e),
            _ => Ok(()),
        }?;

        self.info.regs.cr2().modify(|w| {
            w.set_dmaen(false);
        });

        if frame.send_stop() {
            // The I2C transfer itself will take longer than the DMA transfer, so wait for that to finish too.

            // 18.3.8 “Master transmitter: In the interrupt routine after the EOT interrupt, disable DMA
            // requests then wait for a BTF event before programming the Stop condition.”
            poll_fn(|cx| {
                self.state.waker.register(cx.waker());

                match Self::check_and_clear_error_flags(self.info) {
                    Err(e) => Poll::Ready(Err(e)),
                    Ok(sr1) => {
                        if sr1.btf() {
                            Poll::Ready(Ok(()))
                        } else {
                            // When pending, (re-)enable interrupts to wake us up.
                            Self::enable_interrupts(self.info);
                            Poll::Pending
                        }
                    }
                }
            })
            .await?;

            self.info.regs.cr1().modify(|w| {
                w.set_stop(true);
            });
        }

        drop(on_drop);

        // Fallthrough is success
        Ok(())
    }

    /// Write.
    pub async fn write(&mut self, address: u8, write_buffer: &[u8]) -> Result<(), Error> {
        self.write_frame(address, write_buffer, FrameOptions::FirstAndLastFrame)
            .await?;

        Ok(())
    }

    /// Read.
    pub async fn read(&mut self, address: u8, read_buffer: &mut [u8]) -> Result<(), Error> {
        self.read_frame(address, read_buffer, FrameOptions::FirstAndLastFrame)
            .await?;

        Ok(())
    }

    async fn read_frame(&mut self, address: u8, read_buffer: &mut [u8], frame: FrameOptions) -> Result<(), Error> {
        if read_buffer.is_empty() {
            return Err(Error::Overrun);
        }

        // Some branches below depend on whether the buffer contains only a single byte.
        let single_byte = read_buffer.len() == 1;

        self.info.regs.cr2().modify(|w| {
            // Note: Do not enable the ITBUFEN bit in the I2C_CR2 register if DMA is used for
            // reception.
            w.set_itbufen(false);
            // DMA mode can be enabled for transmission by setting the DMAEN bit in the I2C_CR2
            // register.
            w.set_dmaen(true);
            // If, in the I2C_CR2 register, the LAST bit is set, I2C automatically sends a NACK
            // after the next byte following EOT_1. The user can generate a Stop condition in
            // the DMA Transfer Complete interrupt routine if enabled.
            w.set_last(frame.send_nack() && !single_byte);
        });

        // Sentinel to disable transfer when an error occurs or future is canceled.
        // TODO: Generate STOP condition on cancel?
        let on_drop = OnDrop::new(|| {
            self.info.regs.cr2().modify(|w| {
                w.set_dmaen(false);
                w.set_iterren(false);
                w.set_itevten(false);
            })
        });

        if frame.send_start() {
            // Send a START condition and set ACK bit
            self.info.regs.cr1().modify(|reg| {
                reg.set_start(true);
                reg.set_ack(true);
            });

            // Wait until START condition was generated
            poll_fn(|cx| {
                self.state.waker.register(cx.waker());

                match Self::check_and_clear_error_flags(self.info) {
                    Err(e) => Poll::Ready(Err(e)),
                    Ok(sr1) => {
                        if sr1.start() {
                            Poll::Ready(Ok(()))
                        } else {
                            // When pending, (re-)enable interrupts to wake us up.
                            Self::enable_interrupts(self.info);
                            Poll::Pending
                        }
                    }
                }
            })
            .await?;

            // Check if we were the ones to generate START
            if self.info.regs.cr1().read().start() || !self.info.regs.sr2().read().msl() {
                return Err(Error::Arbitration);
            }

            // Set up current address we're trying to talk to
            self.info.regs.dr().write(|reg| reg.set_dr((address << 1) + 1));

            // Wait for the address to be acknowledged
            poll_fn(|cx| {
                self.state.waker.register(cx.waker());

                match Self::check_and_clear_error_flags(self.info) {
                    Err(e) => Poll::Ready(Err(e)),
                    Ok(sr1) => {
                        if sr1.addr() {
                            Poll::Ready(Ok(()))
                        } else {
                            // When pending, (re-)enable interrupts to wake us up.
                            Self::enable_interrupts(self.info);
                            Poll::Pending
                        }
                    }
                }
            })
            .await?;

            // 18.3.8: When a single byte must be received: the NACK must be programmed during EV6
            // event, i.e. program ACK=0 when ADDR=1, before clearing ADDR flag.
            if frame.send_nack() && single_byte {
                self.info.regs.cr1().modify(|w| {
                    w.set_ack(false);
                });
            }

            // Clear condition by reading SR2
            self.info.regs.sr2().read();
        } else {
            // Before starting reception of single byte (but without START condition, i.e. in case
            // of merged operations), program NACK to emit at end of this byte.
            if frame.send_nack() && single_byte {
                self.info.regs.cr1().modify(|w| {
                    w.set_ack(false);
                });
            }
        }

        // 18.3.8: When a single byte must be received: [snip] Then the user can program the STOP
        // condition either after clearing ADDR flag, or in the DMA Transfer Complete interrupt
        // routine.
        if frame.send_stop() && single_byte {
            self.info.regs.cr1().modify(|w| {
                w.set_stop(true);
            });
        }

        let dma_transfer = unsafe {
            // Set the I2C_DR register address in the DMA_SxPAR register. The data will be moved
            // from this address from the memory after each RxE event.
            let src = self.info.regs.dr().as_ptr() as *mut u8;

            self.rx_dma.as_mut().unwrap().read(src, read_buffer, Default::default())
        };

        // Wait for bytes to be received, or an error to occur.
        let poll_error = poll_fn(|cx| {
            self.state.waker.register(cx.waker());

            match Self::check_and_clear_error_flags(self.info) {
                Err(e) => Poll::Ready(Err::<(), Error>(e)),
                _ => {
                    // When pending, (re-)enable interrupts to wake us up.
                    Self::enable_interrupts(self.info);
                    Poll::Pending
                }
            }
        });

        match select(dma_transfer, poll_error).await {
            Either::Second(Err(e)) => Err(e),
            _ => Ok(()),
        }?;

        self.info.regs.cr2().modify(|w| {
            w.set_dmaen(false);
        });

        if frame.send_stop() && !single_byte {
            self.info.regs.cr1().modify(|w| {
                w.set_stop(true);
            });
        }

        drop(on_drop);

        // Fallthrough is success
        Ok(())
    }

    /// Write, restart, read.
    pub async fn write_read(&mut self, address: u8, write_buffer: &[u8], read_buffer: &mut [u8]) -> Result<(), Error> {
        // Check empty read buffer before starting transaction. Otherwise, we would not generate the
        // stop condition below.
        if read_buffer.is_empty() {
            return Err(Error::Overrun);
        }

        self.write_frame(address, write_buffer, FrameOptions::FirstFrame)
            .await?;
        self.read_frame(address, read_buffer, FrameOptions::FirstAndLastFrame)
            .await
    }

    /// Transaction with operations.
    ///
    /// Consecutive operations of same type are merged. See [transaction contract] for details.
    ///
    /// [transaction contract]: embedded_hal_1::i2c::I2c::transaction
    pub async fn transaction(&mut self, address: u8, operations: &mut [Operation<'_>]) -> Result<(), Error> {
        for (op, frame) in operation_frames(operations)? {
            match op {
                Operation::Read(read_buffer) => self.read_frame(address, read_buffer, frame).await?,
                Operation::Write(write_buffer) => self.write_frame(address, write_buffer, frame).await?,
            }
        }

        Ok(())
    }
}

enum Mode {
    Fast,
    Standard,
}

impl Mode {
    fn f_s(&self) -> i2c::vals::FS {
        match self {
            Mode::Fast => i2c::vals::FS::FAST,
            Mode::Standard => i2c::vals::FS::STANDARD,
        }
    }
}

enum Duty {
    Duty2_1,
    Duty16_9,
}

impl Duty {
    fn duty(&self) -> i2c::vals::Duty {
        match self {
            Duty::Duty2_1 => i2c::vals::Duty::DUTY2_1,
            Duty::Duty16_9 => i2c::vals::Duty::DUTY16_9,
        }
    }
}

/// Result of attempting to send a byte in slave transmitter mode
#[derive(Debug, PartialEq)]
enum TransmitResult {
    /// Byte sent and ACKed by master - continue transmission
    Acknowledged,
    /// Byte sent but NACKed by master - normal end of read transaction
    NotAcknowledged,
    /// STOP condition detected - master terminated transaction
    Stopped,
    /// RESTART condition detected - master starting new transaction
    Restarted,
}

/// Result of attempting to receive a byte in slave receiver mode
#[derive(Debug, PartialEq)]
enum ReceiveResult {
    /// Data byte successfully received
    Data(u8),
    /// STOP condition detected - end of write transaction
    Stopped,
    /// RESTART condition detected - master starting new transaction
    Restarted,
}

/// Enumeration of slave transaction termination conditions
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
enum SlaveTermination {
    /// STOP condition received - normal end of transaction
    Stop,
    /// RESTART condition received - master starting new transaction  
    Restart,
    /// NACK received - normal end of read transaction
    Nack,
}

impl<'d, M: PeriMode> I2c<'d, M, Master> {
    /// Configure the I2C driver for slave operations, allowing for the driver to be used as a slave and a master (multimaster)
    pub fn into_slave_multimaster(mut self, slave_addr_config: SlaveAddrConfig) -> I2c<'d, M, MultiMaster> {
        let mut slave = I2c {
            info: self.info,
            state: self.state,
            kernel_clock: self.kernel_clock,
            tx_dma: self.tx_dma.take(), // Use take() to move ownership
            rx_dma: self.rx_dma.take(), // Use take() to move ownership
            #[cfg(feature = "time")]
            timeout: self.timeout,
            _phantom: PhantomData,
            _phantom2: PhantomData,
            _drop_guard: self._drop_guard, // Move the drop guard
        };
        slave.init_slave(slave_addr_config);
        slave
    }
}

// Address configuration methods
impl<'d, M: PeriMode, IM: MasterMode> I2c<'d, M, IM> {
    /// Initialize slave mode with address configuration
    pub(crate) fn init_slave(&mut self, config: SlaveAddrConfig) {
        trace!("I2C slave: initializing with config={:?}", config);

        // Disable peripheral for configuration
        self.info.regs.cr1().modify(|reg| reg.set_pe(false));

        // Configure slave addresses
        self.apply_address_configuration(config);

        // Enable peripheral with slave settings
        self.info.regs.cr1().modify(|reg| {
            reg.set_pe(true);
            reg.set_ack(true); // Enable acknowledgment for slave mode
            reg.set_nostretch(false); // Allow clock stretching for processing time
        });

        trace!("I2C slave: initialization complete");
    }

    /// Apply the complete address configuration for slave mode
    fn apply_address_configuration(&mut self, config: SlaveAddrConfig) {
        match config.addr {
            OwnAddresses::OA1(addr) => {
                self.configure_primary_address(addr);
                self.disable_secondary_address();
            }
            OwnAddresses::OA2(oa2) => {
                self.configure_default_primary_address();
                self.configure_secondary_address(oa2.addr); // v1 ignores mask
            }
            OwnAddresses::Both { oa1, oa2 } => {
                self.configure_primary_address(oa1);
                self.configure_secondary_address(oa2.addr); // v1 ignores mask
            }
        }

        // Configure general call detection
        if config.general_call {
            self.info.regs.cr1().modify(|w| w.set_engc(true));
        }
    }

    /// Configure the primary address (OA1) register
    fn configure_primary_address(&mut self, addr: Address) {
        match addr {
            Address::SevenBit(addr) => {
                self.info.regs.oar1().write(|reg| {
                    let hw_addr = (addr as u16) << 1; // Address in bits [7:1]
                    reg.set_add(hw_addr);
                    reg.set_addmode(i2c::vals::Addmode::BIT7);
                });
            }
            Address::TenBit(addr) => {
                self.info.regs.oar1().write(|reg| {
                    reg.set_add(addr);
                    reg.set_addmode(i2c::vals::Addmode::BIT10);
                });
            }
        }

        // Set required bit 14 as per reference manual
        self.info.regs.oar1().modify(|reg| reg.0 |= 1 << 14);
    }

    /// Configure the secondary address (OA2) register  
    fn configure_secondary_address(&mut self, addr: u8) {
        self.info.regs.oar2().write(|reg| {
            reg.set_add2(addr);
            reg.set_endual(i2c::vals::Endual::DUAL);
        });
    }

    /// Set a default primary address when using OA2-only mode
    fn configure_default_primary_address(&mut self) {
        self.info.regs.oar1().write(|reg| {
            reg.set_add(0); // Reserved address, safe to use
            reg.set_addmode(i2c::vals::Addmode::BIT7);
        });
        self.info.regs.oar1().modify(|reg| reg.0 |= 1 << 14);
    }

    /// Disable secondary address when not needed
    fn disable_secondary_address(&mut self) {
        self.info.regs.oar2().write(|reg| {
            reg.set_endual(i2c::vals::Endual::SINGLE);
        });
    }
}

impl<'d, M: PeriMode> I2c<'d, M, MultiMaster> {
    /// Listen for incoming I2C address match and return the command type
    ///
    /// This method blocks until the slave address is matched by a master.
    /// Returns the command type (Read/Write) and the matched address.
    pub fn blocking_listen(&mut self) -> Result<SlaveCommand, Error> {
        trace!("I2C slave: starting blocking listen for address match");
        let result = self.blocking_listen_with_timeout(self.timeout());
        trace!("I2C slave: blocking listen complete, result={:?}", result);
        result
    }

    /// Respond to a master read request by transmitting data
    ///
    /// Sends the provided data to the master. If the master requests more bytes
    /// than available, padding bytes (0x00) are sent until the master terminates
    /// the transaction with NACK.
    ///
    /// Returns the total number of bytes transmitted (including padding).
    pub fn blocking_respond_to_read(&mut self, data: &[u8]) -> Result<usize, Error> {
        trace!("I2C slave: starting blocking respond_to_read, data_len={}", data.len());

        if let Some(zero_length_result) = self.detect_zero_length_read(self.timeout())? {
            trace!("I2C slave: zero-length read detected");
            return Ok(zero_length_result);
        }

        let result = self.transmit_to_master(data, self.timeout());
        trace!("I2C slave: blocking respond_to_read complete, result={:?}", result);
        result
    }

    /// Respond to a master write request by receiving data
    ///
    /// Receives data from the master into the provided buffer. If the master
    /// sends more bytes than the buffer can hold, excess bytes are acknowledged
    /// but discarded.
    ///
    /// Returns the number of bytes stored in the buffer (not total received).
    pub fn blocking_respond_to_write(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
        trace!(
            "I2C slave: starting blocking respond_to_write, buffer_len={}",
            buffer.len()
        );
        let result = self.receive_from_master(buffer, self.timeout());
        trace!("I2C slave: blocking respond_to_write complete, result={:?}", result);
        result
    }

    // Private implementation methods

    /// Wait for address match and determine transaction type
    fn blocking_listen_with_timeout(&mut self, timeout: Timeout) -> Result<SlaveCommand, Error> {
        // Ensure interrupts are disabled for blocking operation
        self.disable_i2c_interrupts();

        // Wait for address match (ADDR flag)
        loop {
            let sr1 = Self::read_status_and_handle_errors(self.info)?;

            if sr1.addr() {
                // Address matched - read SR2 to get direction and clear ADDR flag
                let sr2 = self.info.regs.sr2().read();
                let direction = if sr2.tra() {
                    SlaveCommandKind::Read
                } else {
                    SlaveCommandKind::Write
                };

                // Use the static method instead of the instance method
                let matched_address = Self::decode_matched_address(sr2, self.info)?;
                trace!(
                    "I2C slave: address matched, direction={:?}, addr={:?}",
                    direction, matched_address
                );

                return Ok(SlaveCommand {
                    kind: direction,
                    address: matched_address,
                });
            }

            timeout.check()?;
        }
    }

    /// Transmit data to master in response to read request
    fn transmit_to_master(&mut self, data: &[u8], timeout: Timeout) -> Result<usize, Error> {
        let mut bytes_transmitted = 0;
        let mut padding_count = 0;

        loop {
            let byte_to_send = if bytes_transmitted < data.len() {
                data[bytes_transmitted]
            } else {
                padding_count += 1;
                0x00 // Send padding bytes when data is exhausted
            };

            match self.transmit_byte(byte_to_send, timeout)? {
                TransmitResult::Acknowledged => {
                    bytes_transmitted += 1;
                }
                TransmitResult::NotAcknowledged => {
                    bytes_transmitted += 1; // Count the NACKed byte
                    break;
                }
                TransmitResult::Stopped | TransmitResult::Restarted => {
                    break;
                }
            }
        }

        if padding_count > 0 {
            trace!(
                "I2C slave: sent {} data bytes + {} padding bytes = {} total",
                data.len(),
                padding_count,
                bytes_transmitted
            );
        }

        Ok(bytes_transmitted)
    }

    /// Receive data from master during write request
    fn receive_from_master(&mut self, buffer: &mut [u8], timeout: Timeout) -> Result<usize, Error> {
        let mut bytes_stored = 0;

        // Receive bytes that fit in buffer
        while bytes_stored < buffer.len() {
            match self.receive_byte(timeout)? {
                ReceiveResult::Data(byte) => {
                    buffer[bytes_stored] = byte;
                    bytes_stored += 1;
                }
                ReceiveResult::Stopped | ReceiveResult::Restarted => {
                    return Ok(bytes_stored);
                }
            }
        }

        // Handle buffer overflow by discarding excess bytes
        if bytes_stored == buffer.len() {
            trace!("I2C slave: buffer full, discarding excess bytes");
            self.discard_excess_bytes(timeout)?;
        }

        Ok(bytes_stored)
    }

    /// Detect zero-length read pattern early
    ///
    /// Zero-length reads occur when a master sends START+ADDR+R followed immediately
    /// by NACK+STOP without wanting any data. This must be detected before attempting
    /// to transmit any bytes to avoid SDA line issues.
    fn detect_zero_length_read(&mut self, _timeout: Timeout) -> Result<Option<usize>, Error> {
        // Quick check for immediate termination signals
        let sr1 = self.info.regs.sr1().read();

        // Check for immediate NACK (fastest zero-length pattern)
        if sr1.af() {
            self.clear_acknowledge_failure();
            return Ok(Some(0));
        }

        // Check for immediate STOP (alternative zero-length pattern)
        if sr1.stopf() {
            Self::clear_stop_flag(self.info);
            return Ok(Some(0));
        }

        // Give a brief window for master to send termination signals
        // This handles masters that have slight delays between address ACK and NACK
        const ZERO_LENGTH_DETECTION_CYCLES: u32 = 20; // ~5-10µs window

        for _ in 0..ZERO_LENGTH_DETECTION_CYCLES {
            let sr1 = self.info.regs.sr1().read();

            // Immediate NACK indicates zero-length read
            if sr1.af() {
                self.clear_acknowledge_failure();
                return Ok(Some(0));
            }

            // Immediate STOP indicates zero-length read
            if sr1.stopf() {
                Self::clear_stop_flag(self.info);
                return Ok(Some(0));
            }

            // If TXE becomes ready, master is waiting for data - not zero-length
            if sr1.txe() {
                return Ok(None); // Proceed with normal transmission
            }

            // If RESTART detected, handle as zero-length
            if sr1.addr() {
                return Ok(Some(0));
            }
        }

        // No zero-length pattern detected within the window
        Ok(None)
    }

    /// Discard excess bytes when buffer is full
    fn discard_excess_bytes(&mut self, timeout: Timeout) -> Result<(), Error> {
        let mut discarded_count = 0;

        loop {
            match self.receive_byte(timeout)? {
                ReceiveResult::Data(_) => {
                    discarded_count += 1;
                    continue;
                }
                ReceiveResult::Stopped | ReceiveResult::Restarted => {
                    if discarded_count > 0 {
                        trace!("I2C slave: discarded {} excess bytes", discarded_count);
                    }
                    break;
                }
            }
        }
        Ok(())
    }

    /// Send a single byte and wait for master's response
    fn transmit_byte(&mut self, byte: u8, timeout: Timeout) -> Result<TransmitResult, Error> {
        // Wait for transmit buffer ready
        self.wait_for_transmit_ready(timeout)?;

        // Send the byte
        self.info.regs.dr().write(|w| w.set_dr(byte));

        // Wait for transmission completion or master response
        self.wait_for_transmit_completion(timeout)
    }

    /// Wait until transmit buffer is ready (TXE flag set)
    fn wait_for_transmit_ready(&mut self, timeout: Timeout) -> Result<(), Error> {
        loop {
            let sr1 = Self::read_status_and_handle_errors(self.info)?;

            // Check for early termination conditions
            if let Some(result) = Self::check_early_termination(sr1) {
                return Err(self.handle_early_termination(result));
            }

            if sr1.txe() {
                return Ok(()); // Ready to transmit
            }

            timeout.check()?;
        }
    }

    /// Wait for byte transmission completion or master response
    fn wait_for_transmit_completion(&mut self, timeout: Timeout) -> Result<TransmitResult, Error> {
        loop {
            let sr1 = self.info.regs.sr1().read();

            // Check flags in priority order
            if sr1.af() {
                self.clear_acknowledge_failure();
                return Ok(TransmitResult::NotAcknowledged);
            }

            if sr1.btf() {
                return Ok(TransmitResult::Acknowledged);
            }

            if sr1.stopf() {
                Self::clear_stop_flag(self.info);
                return Ok(TransmitResult::Stopped);
            }

            if sr1.addr() {
                return Ok(TransmitResult::Restarted);
            }

            // Check for other error conditions
            self.check_for_hardware_errors(sr1)?;

            timeout.check()?;
        }
    }

    /// Receive a single byte or detect transaction termination
    fn receive_byte(&mut self, timeout: Timeout) -> Result<ReceiveResult, Error> {
        loop {
            let sr1 = Self::read_status_and_handle_errors(self.info)?;

            // Check for received data first (prioritize data over control signals)
            if sr1.rxne() {
                let byte = self.info.regs.dr().read().dr();
                return Ok(ReceiveResult::Data(byte));
            }

            // Check for transaction termination
            if sr1.addr() {
                return Ok(ReceiveResult::Restarted);
            }

            if sr1.stopf() {
                Self::clear_stop_flag(self.info);
                return Ok(ReceiveResult::Stopped);
            }

            timeout.check()?;
        }
    }

    /// Determine which slave address was matched based on SR2 flags
    fn decode_matched_address(sr2: i2c::regs::Sr2, info: &'static Info) -> Result<Address, Error> {
        if sr2.gencall() {
            Ok(Address::SevenBit(0x00)) // General call address
        } else if sr2.dualf() {
            // OA2 (secondary address) was matched
            let oar2 = info.regs.oar2().read();
            if oar2.endual() != i2c::vals::Endual::DUAL {
                return Err(Error::Bus); // Hardware inconsistency
            }
            Ok(Address::SevenBit(oar2.add2()))
        } else {
            // OA1 (primary address) was matched
            let oar1 = info.regs.oar1().read();
            match oar1.addmode() {
                i2c::vals::Addmode::BIT7 => {
                    let addr = (oar1.add() >> 1) as u8;
                    Ok(Address::SevenBit(addr))
                }
                i2c::vals::Addmode::BIT10 => Ok(Address::TenBit(oar1.add())),
            }
        }
    }

    // Helper methods for hardware interaction

    /// Read status register and handle I2C errors (except NACK in slave mode)
    fn read_status_and_handle_errors(info: &'static Info) -> Result<i2c::regs::Sr1, Error> {
        match Self::check_and_clear_error_flags(info) {
            Ok(sr1) => Ok(sr1),
            Err(Error::Nack) => {
                // In slave mode, NACK is normal protocol behavior, not an error
                Ok(info.regs.sr1().read())
            }
            Err(other_error) => Err(other_error),
        }
    }

    /// Check for conditions that cause early termination of operations
    fn check_early_termination(sr1: i2c::regs::Sr1) -> Option<TransmitResult> {
        if sr1.stopf() {
            Some(TransmitResult::Stopped)
        } else if sr1.addr() {
            Some(TransmitResult::Restarted)
        } else if sr1.af() {
            Some(TransmitResult::NotAcknowledged)
        } else {
            None
        }
    }

    /// Convert early termination to appropriate error
    fn handle_early_termination(&mut self, result: TransmitResult) -> Error {
        match result {
            TransmitResult::Stopped => {
                Self::clear_stop_flag(self.info);
                Error::Bus // Unexpected STOP during setup
            }
            TransmitResult::Restarted => {
                Error::Bus // Unexpected RESTART during setup
            }
            TransmitResult::NotAcknowledged => {
                self.clear_acknowledge_failure();
                Error::Bus // Unexpected NACK during setup
            }
            TransmitResult::Acknowledged => {
                unreachable!() // This should never be passed to this function
            }
        }
    }

    /// Check for hardware-level I2C errors during transmission
    fn check_for_hardware_errors(&self, sr1: i2c::regs::Sr1) -> Result<(), Error> {
        if sr1.timeout() || sr1.ovr() || sr1.arlo() || sr1.berr() {
            // Delegate to existing error handling
            Self::check_and_clear_error_flags(self.info)?;
        }
        Ok(())
    }

    /// Disable I2C event and error interrupts for blocking operations
    fn disable_i2c_interrupts(&mut self) {
        self.info.regs.cr2().modify(|w| {
            w.set_itevten(false);
            w.set_iterren(false);
        });
    }

    /// Clear the acknowledge failure flag
    fn clear_acknowledge_failure(&mut self) {
        self.info.regs.sr1().write(|reg| {
            reg.0 = !0;
            reg.set_af(false);
        });
    }

    /// Configure DMA settings for slave operations (shared between read/write)
    fn setup_slave_dma_base(&mut self) {
        self.info.regs.cr2().modify(|w| {
            w.set_itbufen(false); // Always disable buffer interrupts when using DMA
            w.set_dmaen(true); // Enable DMA requests
            w.set_last(false); // LAST bit not used in slave mode for v1 hardware
        });
    }

    /// Disable DMA and interrupts in a critical section
    fn disable_dma_and_interrupts(info: &'static Info) {
        critical_section::with(|_| {
            info.regs.cr2().modify(|w| {
                w.set_dmaen(false);
                w.set_iterren(false);
                w.set_itevten(false);
            });
        });
    }

    /// Check for early termination conditions during slave operations
    /// Returns Some(result) if termination detected, None to continue
    fn check_slave_termination_conditions(sr1: i2c::regs::Sr1) -> Option<SlaveTermination> {
        if sr1.stopf() {
            Some(SlaveTermination::Stop)
        } else if sr1.addr() {
            Some(SlaveTermination::Restart)
        } else if sr1.af() {
            Some(SlaveTermination::Nack)
        } else {
            None
        }
    }
}

impl<'d> I2c<'d, Async, MultiMaster> {
    /// Async listen for incoming I2C messages using interrupts
    ///
    /// Waits for a master to address this slave and returns the command type
    /// (Read/Write) and the matched address. This method will suspend until
    /// an address match occurs.
    pub async fn listen(&mut self) -> Result<SlaveCommand, Error> {
        trace!("I2C slave: starting async listen for address match");
        let state = self.state;
        let info = self.info;

        Self::enable_interrupts(info);

        let on_drop = OnDrop::new(|| {
            Self::disable_dma_and_interrupts(info);
        });

        let result = poll_fn(|cx| {
            state.waker.register(cx.waker());

            match Self::check_and_clear_error_flags(info) {
                Err(e) => {
                    error!("I2C slave: error during listen: {:?}", e);
                    Poll::Ready(Err(e))
                }
                Ok(sr1) => {
                    if sr1.addr() {
                        let sr2 = info.regs.sr2().read();
                        let direction = if sr2.tra() {
                            SlaveCommandKind::Read
                        } else {
                            SlaveCommandKind::Write
                        };

                        let matched_address = match Self::decode_matched_address(sr2, info) {
                            Ok(addr) => {
                                trace!("I2C slave: address matched, direction={:?}, addr={:?}", direction, addr);
                                addr
                            }
                            Err(e) => {
                                error!("I2C slave: failed to decode matched address: {:?}", e);
                                return Poll::Ready(Err(e));
                            }
                        };

                        Poll::Ready(Ok(SlaveCommand {
                            kind: direction,
                            address: matched_address,
                        }))
                    } else {
                        Self::enable_interrupts(info);
                        Poll::Pending
                    }
                }
            }
        })
        .await;

        drop(on_drop);
        trace!("I2C slave: listen complete, result={:?}", result);
        result
    }

    /// Async respond to write command using RX DMA
    ///
    /// Receives data from the master into the provided buffer using DMA.
    /// If the master sends more bytes than the buffer can hold, excess bytes
    /// are acknowledged but discarded to prevent interrupt flooding.
    ///
    /// Returns the number of bytes stored in the buffer (not total received).
    pub async fn respond_to_write(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
        trace!("I2C slave: starting respond_to_write, buffer_len={}", buffer.len());

        if buffer.is_empty() {
            warn!("I2C slave: respond_to_write called with empty buffer");
            return Err(Error::Overrun);
        }

        let state = self.state;
        let info = self.info;

        self.setup_slave_dma_base();

        let on_drop = OnDrop::new(|| {
            Self::disable_dma_and_interrupts(info);
        });

        info.regs.sr2().read();

        let result = self.execute_slave_receive_transfer(buffer, state, info).await;

        drop(on_drop);
        trace!("I2C slave: respond_to_write complete, result={:?}", result);
        result
    }

    /// Async respond to read command using TX DMA
    ///
    /// Transmits data to the master using DMA. If the master requests more bytes
    /// than available in the data buffer, padding bytes (0x00) are sent until
    /// the master terminates the transaction with NACK, STOP, or RESTART.
    ///
    /// Returns the total number of bytes transmitted (data + padding).
    pub async fn respond_to_read(&mut self, data: &[u8]) -> Result<usize, Error> {
        trace!("I2C slave: starting respond_to_read, data_len={}", data.len());

        if data.is_empty() {
            warn!("I2C slave: respond_to_read called with empty data");
            return Err(Error::Overrun);
        }

        let state = self.state;
        let info = self.info;

        self.setup_slave_dma_base();

        let on_drop = OnDrop::new(|| {
            Self::disable_dma_and_interrupts(info);
        });

        info.regs.sr2().read();

        let result = self.execute_slave_transmit_transfer(data, state, info).await;

        drop(on_drop);
        trace!("I2C slave: respond_to_read complete, result={:?}", result);
        result
    }

    // === Private Transfer Execution Methods ===

    /// Execute complete slave receive transfer with excess byte handling
    async fn execute_slave_receive_transfer(
        &mut self,
        buffer: &mut [u8],
        state: &'static State,
        info: &'static Info,
    ) -> Result<usize, Error> {
        let dma_transfer = unsafe {
            let src = info.regs.dr().as_ptr() as *mut u8;
            self.rx_dma.as_mut().unwrap().read(src, buffer, Default::default())
        };

        let i2c_monitor =
            Self::create_termination_monitor(state, info, &[SlaveTermination::Stop, SlaveTermination::Restart]);

        match select(dma_transfer, i2c_monitor).await {
            Either::Second(Err(e)) => {
                error!("I2C slave: error during receive transfer: {:?}", e);
                Self::disable_dma_and_interrupts(info);
                Err(e)
            }
            Either::First(_) => {
                trace!("I2C slave: DMA receive completed, handling excess bytes");
                Self::disable_dma_and_interrupts(info);
                self.handle_excess_bytes(state, info).await?;
                Ok(buffer.len())
            }
            Either::Second(Ok(termination)) => {
                trace!("I2C slave: receive terminated by I2C event: {:?}", termination);
                Self::disable_dma_and_interrupts(info);
                Ok(buffer.len())
            }
        }
    }

    /// Execute complete slave transmit transfer with padding byte handling
    async fn execute_slave_transmit_transfer(
        &mut self,
        data: &[u8],
        state: &'static State,
        info: &'static Info,
    ) -> Result<usize, Error> {
        let dma_transfer = unsafe {
            let dst = info.regs.dr().as_ptr() as *mut u8;
            self.tx_dma.as_mut().unwrap().write(data, dst, Default::default())
        };

        let i2c_monitor = Self::create_termination_monitor(
            state,
            info,
            &[
                SlaveTermination::Stop,
                SlaveTermination::Restart,
                SlaveTermination::Nack,
            ],
        );

        match select(dma_transfer, i2c_monitor).await {
            Either::Second(Err(e)) => {
                error!("I2C slave: error during transmit transfer: {:?}", e);
                Self::disable_dma_and_interrupts(info);
                Err(e)
            }
            Either::First(_) => {
                trace!("I2C slave: DMA transmit completed, handling padding bytes");
                Self::disable_dma_and_interrupts(info);
                let padding_count = self.handle_padding_bytes(state, info).await?;
                let total_bytes = data.len() + padding_count;
                trace!(
                    "I2C slave: sent {} data bytes + {} padding bytes = {} total",
                    data.len(),
                    padding_count,
                    total_bytes
                );
                Ok(total_bytes)
            }
            Either::Second(Ok(termination)) => {
                trace!("I2C slave: transmit terminated by I2C event: {:?}", termination);
                Self::disable_dma_and_interrupts(info);
                Ok(data.len())
            }
        }
    }

    /// Create a future that monitors for specific slave termination conditions
    fn create_termination_monitor(
        state: &'static State,
        info: &'static Info,
        allowed_terminations: &'static [SlaveTermination],
    ) -> impl Future<Output = Result<SlaveTermination, Error>> {
        poll_fn(move |cx| {
            state.waker.register(cx.waker());

            match Self::check_and_clear_error_flags(info) {
                Err(Error::Nack) if allowed_terminations.contains(&SlaveTermination::Nack) => {
                    Poll::Ready(Ok(SlaveTermination::Nack))
                }
                Err(e) => Poll::Ready(Err(e)),
                Ok(sr1) => {
                    if let Some(termination) = Self::check_slave_termination_conditions(sr1) {
                        if allowed_terminations.contains(&termination) {
                            // Handle the specific termination condition
                            match termination {
                                SlaveTermination::Stop => Self::clear_stop_flag(info),
                                SlaveTermination::Nack => {
                                    info.regs.sr1().write(|reg| {
                                        reg.0 = !0;
                                        reg.set_af(false);
                                    });
                                }
                                SlaveTermination::Restart => {
                                    // ADDR flag will be handled by next listen() call
                                }
                            }
                            Poll::Ready(Ok(termination))
                        } else {
                            // Unexpected termination condition
                            Poll::Ready(Err(Error::Bus))
                        }
                    } else {
                        Self::enable_interrupts(info);
                        Poll::Pending
                    }
                }
            }
        })
    }

    /// Handle excess bytes after DMA buffer is full
    ///
    /// Reads and discards bytes until transaction termination to prevent interrupt flooding
    async fn handle_excess_bytes(&mut self, state: &'static State, info: &'static Info) -> Result<(), Error> {
        let mut discarded_count = 0;

        poll_fn(|cx| {
            state.waker.register(cx.waker());

            match Self::check_and_clear_error_flags(info) {
                Err(e) => {
                    error!("I2C slave: error while discarding excess bytes: {:?}", e);
                    Poll::Ready(Err(e))
                }
                Ok(sr1) => {
                    if let Some(termination) = Self::check_slave_termination_conditions(sr1) {
                        match termination {
                            SlaveTermination::Stop => Self::clear_stop_flag(info),
                            SlaveTermination::Restart => {}
                            SlaveTermination::Nack => unreachable!("NACK not expected during receive"),
                        }
                        if discarded_count > 0 {
                            trace!("I2C slave: discarded {} excess bytes", discarded_count);
                        }
                        return Poll::Ready(Ok(()));
                    }

                    if sr1.rxne() {
                        let _discarded_byte = info.regs.dr().read().dr();
                        discarded_count += 1;
                        Self::enable_interrupts(info);
                        return Poll::Pending;
                    }

                    Self::enable_interrupts(info);
                    Poll::Pending
                }
            }
        })
        .await
    }

    /// Handle padding bytes after DMA data is exhausted
    ///
    /// Sends 0x00 bytes until transaction termination to prevent interrupt flooding
    async fn handle_padding_bytes(&mut self, state: &'static State, info: &'static Info) -> Result<usize, Error> {
        let mut padding_count = 0;

        poll_fn(|cx| {
            state.waker.register(cx.waker());

            match Self::check_and_clear_error_flags(info) {
                Err(Error::Nack) => Poll::Ready(Ok(padding_count)),
                Err(e) => {
                    error!("I2C slave: error while sending padding bytes: {:?}", e);
                    Poll::Ready(Err(e))
                }
                Ok(sr1) => {
                    if let Some(termination) = Self::check_slave_termination_conditions(sr1) {
                        match termination {
                            SlaveTermination::Stop => Self::clear_stop_flag(info),
                            SlaveTermination::Restart => {}
                            SlaveTermination::Nack => {
                                info.regs.sr1().write(|reg| {
                                    reg.0 = !0;
                                    reg.set_af(false);
                                });
                            }
                        }
                        return Poll::Ready(Ok(padding_count));
                    }

                    if sr1.txe() {
                        info.regs.dr().write(|w| w.set_dr(0x00));
                        padding_count += 1;
                        Self::enable_interrupts(info);
                        return Poll::Pending;
                    }

                    Self::enable_interrupts(info);
                    Poll::Pending
                }
            }
        })
        .await
    }
}

/// Timing configuration for I2C v1 hardware
///
/// This struct encapsulates the complex timing calculations required for STM32 I2C v1
/// peripherals, which use three separate registers (CR2.FREQ, CCR, TRISE) instead of
/// the unified TIMINGR register found in v2 hardware.
struct Timings {
    freq: u8,   // APB frequency in MHz for CR2.FREQ register
    mode: Mode, // Standard or Fast mode selection
    trise: u8,  // Rise time compensation value
    ccr: u16,   // Clock control register value
    duty: Duty, // Fast mode duty cycle selection
}

impl Timings {
    fn new(i2cclk: Hertz, frequency: Hertz) -> Self {
        // Calculate settings for I2C speed modes
        let frequency = frequency.0;
        let clock = i2cclk.0;
        let freq = clock / 1_000_000;
        assert!((2..=50).contains(&freq));

        // Configure bus frequency into I2C peripheral
        let trise = if frequency <= 100_000 {
            freq + 1
        } else {
            (freq * 300) / 1000 + 1
        };

        let mut ccr;
        let duty;
        let mode;

        // I2C clock control calculation
        if frequency <= 100_000 {
            duty = Duty::Duty2_1;
            mode = Mode::Standard;
            ccr = {
                let ccr = clock / (frequency * 2);
                if ccr < 4 { 4 } else { ccr }
            };
        } else {
            const DUTYCYCLE: u8 = 0;
            mode = Mode::Fast;
            if DUTYCYCLE == 0 {
                duty = Duty::Duty2_1;
                ccr = clock / (frequency * 3);
                ccr = if ccr < 1 { 1 } else { ccr };
            } else {
                duty = Duty::Duty16_9;
                ccr = clock / (frequency * 25);
                ccr = if ccr < 1 { 1 } else { ccr };
            }
        }

        Self {
            freq: freq as u8,
            trise: trise as u8,
            ccr: ccr as u16,
            duty,
            mode,
        }
    }
}

impl<'d, M: PeriMode> SetConfig for I2c<'d, M, Master> {
    type Config = Hertz;
    type ConfigError = ();
    fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
        let timings = Timings::new(self.kernel_clock, *config);
        self.info.regs.cr2().modify(|reg| {
            reg.set_freq(timings.freq);
        });
        self.info.regs.ccr().modify(|reg| {
            reg.set_f_s(timings.mode.f_s());
            reg.set_duty(timings.duty.duty());
            reg.set_ccr(timings.ccr);
        });
        self.info.regs.trise().modify(|reg| {
            reg.set_trise(timings.trise);
        });

        Ok(())
    }
}