esp-hal 0.16.1

Bare-metal HAL for Espressif 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
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
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
//! # PSRAM "virtual peripheral" driver (ESP32-S2)
//!
//! ## Overview
//!
//! The `PSRAM` module provides support for accessing and controlling the
//! `Pseudo Static Random Access Memory (PSRAM)` on the `ESP32-S2`.
//!
//! The `PSRAM` module enables users to interface with the `PSRAM` memory
//! present on the `ESP32-S2` chip. `PSRAM` provides additional external memory
//! to supplement the internal memory of the `ESP32-S2`, allowing for increased
//! storage capacity and improved performance in certain applications.
//!
//! The `PSRAM` module is accessed through a virtual address, defined as
//! `PSRAM_VADDR`. The starting virtual address for the PSRAM module is
//! 0x3f500000. The `PSRAM` module size depends on the configuration specified
//! during the compilation process. The available `PSRAM` sizes are `2MB`,
//! `4MB`, and `8MB`.

static mut PSRAM_VADDR: u32 = 0x3C000000;

pub fn psram_vaddr_start() -> usize {
    unsafe { PSRAM_VADDR as usize }
}

cfg_if::cfg_if! {
    if #[cfg(feature = "psram-2m")] {
        const PSRAM_SIZE: u32 = 2;
    } else if #[cfg(feature = "psram-4m")] {
        const PSRAM_SIZE: u32 = 4;
    } else if #[cfg(feature = "psram-8m")] {
        const PSRAM_SIZE: u32 = 8;
    } else if #[cfg(feature = "opsram-2m")] {
        const PSRAM_SIZE: u32 = 2;
    } else if #[cfg(feature = "opsram-4m")] {
        const PSRAM_SIZE: u32 = 4;
    } else if #[cfg(feature = "opsram-8m")] {
        const PSRAM_SIZE: u32 = 8;
    } else if #[cfg(feature = "opsram-16m")] {
        const PSRAM_SIZE: u32 = 16;
    }else {
        const PSRAM_SIZE: u32 = 0;
    }
}

pub const PSRAM_BYTES: usize = PSRAM_SIZE as usize * 1024 * 1024;

/// Initialize PSRAM to be used for data.
///
/// Currently only QSPI is supported.
#[cfg(any(
    feature = "psram-2m",
    feature = "psram-4m",
    feature = "psram-8m",
    feature = "opsram-2m",
    feature = "opsram-4m",
    feature = "opsram-8m",
    feature = "opsram-16m"
))]
pub fn init_psram(_peripheral: impl crate::peripheral::Peripheral<P = crate::peripherals::PSRAM>) {
    const CONFIG_ESP32S3_INSTRUCTION_CACHE_SIZE: u32 = 0x4000;
    const CONFIG_ESP32S3_ICACHE_ASSOCIATED_WAYS: u8 = 8;
    const CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_SIZE: u8 = 32;
    const CONFIG_ESP32S3_DATA_CACHE_SIZE: u32 = 0x8000;
    const CONFIG_ESP32S3_DCACHE_ASSOCIATED_WAYS: u8 = 8;
    const CONFIG_ESP32S3_DATA_CACHE_LINE_SIZE: u8 = 32;
    const MMU_ACCESS_SPIRAM: u32 = 1 << 15;
    const START_PAGE: u32 = 0;

    extern "C" {
        fn rom_config_instruction_cache_mode(
            cfg_cache_size: u32,
            cfg_cache_ways: u8,
            cfg_cache_line_size: u8,
        );

        fn Cache_Suspend_DCache();

        fn rom_config_data_cache_mode(
            cfg_cache_size: u32,
            cfg_cache_ways: u8,
            cfg_cache_line_size: u8,
        );

        fn Cache_Resume_DCache(param: u32);

        /// Set DCache mmu mapping.
        ///
        /// [`ext_ram`]: u32 DPORT_MMU_ACCESS_FLASH for flash, DPORT_MMU_ACCESS_SPIRAM for spiram, DPORT_MMU_INVALID for invalid.
        /// [`vaddr`]: u32 Virtual address in CPU address space.
        /// [`paddr`]: u32 Physical address in external memory. Should be aligned by psize.
        /// [`psize`]: u32 Page size of DCache, in kilobytes. Should be 64 here.
        /// [`num`]: u32 Pages to be set.
        /// [`fixes`]: u32 0 for physical pages grow with virtual pages, other for virtual pages map to same physical page.
        fn cache_dbus_mmu_set(
            ext_ram: u32,
            vaddr: u32,
            paddr: u32,
            psize: u32,
            num: u32,
            fixed: u32,
        ) -> i32;
    }
    unsafe {
        const MMU_PAGE_SIZE: u32 = 0x10000;
        const ICACHE_MMU_SIZE: usize = 0x800;
        const FLASH_MMU_TABLE_SIZE: usize = ICACHE_MMU_SIZE / core::mem::size_of::<u32>();
        const MMU_INVALID: u32 = 1 << 14;
        const DR_REG_MMU_TABLE: u32 = 0x600C5000;

        // calculate the PSRAM start address to map
        let mut start = PSRAM_VADDR;
        let mmu_table_ptr = DR_REG_MMU_TABLE as *const u32;
        for i in 0..FLASH_MMU_TABLE_SIZE {
            if mmu_table_ptr.add(i).read_volatile() != MMU_INVALID {
                start += MMU_PAGE_SIZE;
            } else {
                break;
            }
        }
        debug!("PSRAM start address = {:x}", start);
        PSRAM_VADDR = start;

        // Configure the mode of instruction cache : cache size, cache line size.
        rom_config_instruction_cache_mode(
            CONFIG_ESP32S3_INSTRUCTION_CACHE_SIZE,
            CONFIG_ESP32S3_ICACHE_ASSOCIATED_WAYS,
            CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_SIZE,
        );

        // If we need use SPIRAM, we should use data cache.Connfigure the mode of data :
        // cache size, cache line size.
        Cache_Suspend_DCache();

        rom_config_data_cache_mode(
            CONFIG_ESP32S3_DATA_CACHE_SIZE,
            CONFIG_ESP32S3_DCACHE_ASSOCIATED_WAYS,
            CONFIG_ESP32S3_DATA_CACHE_LINE_SIZE,
        );

        if cache_dbus_mmu_set(
            MMU_ACCESS_SPIRAM,
            PSRAM_VADDR,
            START_PAGE << 16,
            64,
            PSRAM_SIZE * 1024 / 64, // number of pages to map
            0,
        ) != 0
        {
            panic!("cache_dbus_mmu_set failed");
        }

        let extmem = &*esp32s3::EXTMEM::PTR;
        extmem.dcache_ctrl1().modify(|_, w| {
            w.dcache_shut_core0_bus()
                .clear_bit()
                .dcache_shut_core1_bus()
                .clear_bit()
        });

        Cache_Resume_DCache(0);
    }

    utils::psram_init();
}

#[cfg(any(feature = "psram-2m", feature = "psram-4m", feature = "psram-8m"))]
pub(crate) mod utils {
    use procmacros::ram;

    // these should probably be configurable, relates to https://github.com/esp-rs/esp-hal/issues/42
    // probably also the PSRAM size shouldn't get configured via features
    const SPI_TIMING_CORE_CLOCK: SpiTimingConfigCoreClock =
        SpiTimingConfigCoreClock::SpiTimingConfigCoreClock80m;
    const FLASH_FREQ: FlashFreq = FlashFreq::FlashFreq80m;

    cfg_if::cfg_if! {
        if #[cfg(feature = "psram-80mhz")] {
            const SPIRAM_SPEED: SpiRamFreq = SpiRamFreq::Freq80m;
        } else {
            const SPIRAM_SPEED: SpiRamFreq = SpiRamFreq::Freq40m;
        }
    }

    #[allow(unused)]
    enum FlashFreq {
        FlashFreq20m,
        FlashFreq40m,
        FlashFreq80m,
        FlashFreq120m,
    }

    #[allow(unused)]
    enum SpiRamFreq {
        Freq40m,
        Freq80m,
        Freq120m,
    }

    #[allow(unused)]
    #[derive(Debug)]
    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
    enum SpiTimingConfigCoreClock {
        SpiTimingConfigCoreClock80m,
        SpiTimingConfigCoreClock120m,
        SpiTimingConfigCoreClock160m,
        SpiTimingConfigCoreClock240m,
    }

    impl SpiTimingConfigCoreClock {
        fn mhz(&self) -> u32 {
            match self {
                SpiTimingConfigCoreClock::SpiTimingConfigCoreClock80m => 80,
                SpiTimingConfigCoreClock::SpiTimingConfigCoreClock120m => 120,
                SpiTimingConfigCoreClock::SpiTimingConfigCoreClock160m => 160,
                SpiTimingConfigCoreClock::SpiTimingConfigCoreClock240m => 240,
            }
        }
    }

    #[ram]
    pub(crate) fn psram_init() {
        psram_gpio_config();
        psram_set_cs_timing();

        // SPI1: send psram reset command
        psram_reset_mode_spi1();
        // SPI1: send QPI enable command
        psram_enable_qio_mode_spi1();

        // Do PSRAM timing tuning, we use SPI1 to do the tuning, and set the SPI0 PSRAM
        // timing related registers accordingly
        mspi_timing_psram_tuning();

        // Configure SPI0 PSRAM related SPI Phases
        config_psram_spi_phases();
        // Back to the high speed mode. Flash/PSRAM clocks are set to the clock that
        // user selected. SPI0/1 registers are all set correctly
        mspi_timing_enter_high_speed_mode(true);
    }

    const PSRAM_CS_IO: u8 = 26;
    const SPI_CS1_GPIO_NUM: u8 = 26;
    const FUNC_SPICS1_SPICS1: u8 = 0;
    const PIN_FUNC_GPIO: u8 = 2;
    const PSRAM_SPIWP_SD3_IO: u8 = 10;
    const ESP_ROM_EFUSE_FLASH_DEFAULT_SPI: u32 = 0;
    const SPICS1_OUT_IDX: u8 = 6;

    const DR_REG_SPI0_BASE: u32 = 0x60003000;
    const SPI0_MEM_SPI_SMEM_AC_REG: u32 = DR_REG_SPI0_BASE + 0xDC;
    const SPI_MEM_SPI_SMEM_CS_HOLD_TIME_V: u32 = 0x1F;
    const SPI_MEM_SPI_SMEM_CS_HOLD_TIME_S: u32 = 7;
    const SPI_MEM_SPI_SMEM_CS_SETUP_TIME_V: u32 = 0x1F;
    const SPI_MEM_SPI_SMEM_CS_SETUP_TIME_S: u32 = 2;
    const SPI_MEM_SPI_SMEM_CS_HOLD_M: u32 = 1 << 1;
    const SPI_MEM_SPI_SMEM_CS_SETUP_M: u32 = 1 << 0;
    const SPI0_MEM_CACHE_SCTRL_REG: u32 = DR_REG_SPI0_BASE + 0x40;
    const SPI0_MEM_SRAM_DWR_CMD_REG: u32 = DR_REG_SPI0_BASE + 0x4C;
    const SPI0_MEM_SRAM_DRD_CMD_REG: u32 = DR_REG_SPI0_BASE + 0x48;
    const SPI_MEM_USR_SRAM_DIO_M: u32 = 1 << 1;
    const SPI_MEM_USR_SRAM_QIO_M: u32 = 1 << 2;
    const SPI_MEM_CACHE_SRAM_USR_RCMD_M: u32 = 1 << 5;
    const SPI_MEM_CACHE_SRAM_USR_WCMD_M: u32 = 1 << 20;
    const SPI_MEM_CACHE_SRAM_USR_WR_CMD_BITLEN: u32 = 0x0000000F;
    const SPI_MEM_CACHE_SRAM_USR_WR_CMD_BITLEN_S: u32 = 28;
    const SPI_MEM_CACHE_SRAM_USR_WR_CMD_VALUE: u32 = 0x0000FFFF;
    const SPI_MEM_CACHE_SRAM_USR_WR_CMD_VALUE_S: u32 = 0;
    const PSRAM_QUAD_WRITE: u32 = 0x38;
    const SPI_MEM_CACHE_SRAM_USR_RD_CMD_BITLEN_V: u32 = 0xF;
    const SPI_MEM_CACHE_SRAM_USR_RD_CMD_BITLEN_S: u32 = 28;
    const SPI_MEM_CACHE_SRAM_USR_RD_CMD_VALUE_V: u32 = 0xFFFF;
    const PSRAM_FAST_READ_QUAD: u32 = 0xEB;
    const SPI_MEM_CACHE_SRAM_USR_RD_CMD_VALUE_S: u32 = 0;
    const SPI_MEM_SRAM_ADDR_BITLEN_V: u32 = 0x3F;
    const SPI_MEM_SRAM_ADDR_BITLEN_S: u32 = 14;
    const SPI_MEM_USR_RD_SRAM_DUMMY_M: u32 = 1 << 4;
    const SPI_MEM_SRAM_RDUMMY_CYCLELEN_V: u32 = 0x3F;
    const PSRAM_FAST_READ_QUAD_DUMMY: u32 = 6;
    const SPI_MEM_SRAM_RDUMMY_CYCLELEN_S: u32 = 6;
    const SPI0_MEM_MISC_REG: u32 = DR_REG_SPI0_BASE + 0x34;
    const SPI_MEM_CS1_DIS_M: u32 = 1 << 1;
    const SPI0_MEM_CORE_CLK_SEL_REG: u32 = DR_REG_SPI0_BASE + 0xEC;
    const SPI_MEM_CORE_CLK_SEL: u32 = 0x00000003;
    const DR_REG_SPI1_BASE: u32 = 0x60002000;
    const SPI0_MEM_CLOCK_REG: u32 = DR_REG_SPI0_BASE + 0x14;
    const SPI1_MEM_CLOCK_REG: u32 = DR_REG_SPI1_BASE + 0x14;
    const SPI0_MEM_SRAM_CLK_REG: u32 = DR_REG_SPI0_BASE + 0x50;
    const SPI_MEM_CLK_EQU_SYSCLK: u32 = 1 << 31;
    const SPI_MEM_SCLK_EQU_SYSCLK: u32 = 1 << 31;
    const SPI_MEM_CLKCNT_N_S: u32 = 16;
    const SPI_MEM_SCLKCNT_N_S: u32 = 16;
    const SPI_MEM_CLKCNT_H_S: u32 = 8;
    const SPI_MEM_SCLKCNT_H_S: u32 = 8;
    const SPI_MEM_CLKCNT_L_S: u32 = 0;
    const SPI_MEM_SCLKCNT_L_S: u32 = 0;

    extern "C" {
        fn esp_rom_efuse_get_flash_gpio_info() -> u32;

        fn esp_rom_efuse_get_flash_wp_gpio() -> u8;

        fn esp_rom_gpio_connect_out_signal(
            gpio_num: u8,
            signal_idx: u8,
            out_inv: bool,
            oen_inv: bool,
        );

        /// Enable Quad I/O pin functions
        ///
        /// Sets the HD & WP pin functions for Quad I/O modes, based on the
        /// efuse SPI pin configuration.
        ///
        /// [`wp_gpio_num`]: u8 Number of the WP pin to reconfigure for quad I/O
        /// [`spiconfig`]: u32 Pin configuration, as returned from ets_efuse_get_spiconfig().
        /// - If this parameter is 0, default SPI pins are used and wp_gpio_num
        ///   parameter is ignored.
        /// - If this parameter is 1, default HSPI pins are used and wp_gpio_num
        ///   parameter is ignored.
        /// - For other values, this parameter encodes the HD pin number and
        ///   also the CLK pin number. CLK pin selection is used to determine if
        ///   HSPI or SPI peripheral will be used (use HSPI if CLK pin is the
        ///   HSPI clock pin, otherwise use SPI).
        //   Both HD & WP pins are configured via GPIO matrix to map to the selected peripheral.
        fn esp_rom_spiflash_select_qio_pins(wp_gpio_num: u8, spiconfig: u32);
    }

    // Configure PSRAM SPI0 phase related registers here according to the PSRAM chip
    // requirement
    #[ram]
    fn config_psram_spi_phases() {
        // Config CMD phase
        clear_peri_reg_mask(SPI0_MEM_CACHE_SCTRL_REG, SPI_MEM_USR_SRAM_DIO_M); // disable dio mode for cache command
        set_peri_reg_mask(SPI0_MEM_CACHE_SCTRL_REG, SPI_MEM_USR_SRAM_QIO_M); // enable qio mode for cache command
        set_peri_reg_mask(SPI0_MEM_CACHE_SCTRL_REG, SPI_MEM_CACHE_SRAM_USR_RCMD_M); // enable cache read command
        set_peri_reg_mask(SPI0_MEM_CACHE_SCTRL_REG, SPI_MEM_CACHE_SRAM_USR_WCMD_M); // enable cache write command
        set_peri_reg_bits(
            SPI0_MEM_SRAM_DWR_CMD_REG,
            SPI_MEM_CACHE_SRAM_USR_WR_CMD_BITLEN,
            7,
            SPI_MEM_CACHE_SRAM_USR_WR_CMD_BITLEN_S,
        );
        set_peri_reg_bits(
            SPI0_MEM_SRAM_DWR_CMD_REG,
            SPI_MEM_CACHE_SRAM_USR_WR_CMD_VALUE,
            PSRAM_QUAD_WRITE,
            SPI_MEM_CACHE_SRAM_USR_WR_CMD_VALUE_S,
        ); // 0x38
        set_peri_reg_bits(
            SPI0_MEM_SRAM_DRD_CMD_REG,
            SPI_MEM_CACHE_SRAM_USR_RD_CMD_BITLEN_V,
            7,
            SPI_MEM_CACHE_SRAM_USR_RD_CMD_BITLEN_S,
        );
        set_peri_reg_bits(
            SPI0_MEM_SRAM_DRD_CMD_REG,
            SPI_MEM_CACHE_SRAM_USR_RD_CMD_VALUE_V,
            PSRAM_FAST_READ_QUAD,
            SPI_MEM_CACHE_SRAM_USR_RD_CMD_VALUE_S,
        ); // 0xEB

        // Config ADDR phase
        set_peri_reg_bits(
            SPI0_MEM_CACHE_SCTRL_REG,
            SPI_MEM_SRAM_ADDR_BITLEN_V,
            23,
            SPI_MEM_SRAM_ADDR_BITLEN_S,
        );

        // Dummy
        // We set the PSRAM chip required dummy here. If timing tuning is
        // needed, the dummy length will be updated in
        // `mspi_timing_enter_high_speed_mode()`
        set_peri_reg_mask(SPI0_MEM_CACHE_SCTRL_REG, SPI_MEM_USR_RD_SRAM_DUMMY_M); // enable cache read dummy
        set_peri_reg_bits(
            SPI0_MEM_CACHE_SCTRL_REG,
            SPI_MEM_SRAM_RDUMMY_CYCLELEN_V,
            PSRAM_FAST_READ_QUAD_DUMMY - 1,
            SPI_MEM_SRAM_RDUMMY_CYCLELEN_S,
        ); // dummy

        clear_peri_reg_mask(SPI0_MEM_MISC_REG, SPI_MEM_CS1_DIS_M); // ENABLE SPI0 CS1 TO PSRAM(CS0--FLASH; CS1--SRAM)
    }

    #[ram]
    fn mspi_timing_psram_tuning() {
        // currently we only support !SPI_TIMING_PSRAM_NEEDS_TUNING
        // see https://github.com/espressif/esp-idf/blob/4e24516ee2731eb55687182d4e061b5b93a9e33f/components/esp_hw_support/mspi_timing_tuning.c#L391-L415
    }

    /// Set SPI0 FLASH and PSRAM module clock, din_num, din_mode and extra
    /// dummy, according to the configuration got from timing tuning
    /// function (`calculate_best_flash_tuning_config`). iF control_spi1 ==
    /// 1, will also update SPI1 timing registers. Should only be set to 1 when
    /// do tuning.
    ///
    /// This function should always be called after `mspi_timing_flash_tuning`
    /// or `calculate_best_flash_tuning_config`
    #[ram]
    fn mspi_timing_enter_high_speed_mode(control_spi1: bool) {
        let core_clock: SpiTimingConfigCoreClock = get_mspi_core_clock();
        let flash_div: u32 = get_flash_clock_divider();
        let psram_div: u32 = get_psram_clock_divider();

        info!(
            "PSRAM core_clock {:?}, flash_div = {}, psram_div = {}",
            core_clock, flash_div, psram_div
        );

        // Set SPI01 core clock
        // SPI0 and SPI1 share the register for core clock. So we only set SPI0 here.
        // Set FLASH module clock
        spi0_timing_config_set_core_clock(core_clock);

        spi0_timing_config_set_flash_clock(flash_div);
        if control_spi1 {
            spi1_timing_config_set_flash_clock(flash_div);
        }
        // Set PSRAM module clock
        spi0_timing_config_set_psram_clock(psram_div);

        // #if SPI_TIMING_FLASH_NEEDS_TUNING || SPI_TIMING_PSRAM_NEEDS_TUNING
        //     set_timing_tuning_regs_as_required(true);
        // #endif
    }

    #[ram]
    fn spi0_timing_config_set_core_clock(core_clock: SpiTimingConfigCoreClock) {
        let reg_val = match core_clock {
            SpiTimingConfigCoreClock::SpiTimingConfigCoreClock80m => 0,
            SpiTimingConfigCoreClock::SpiTimingConfigCoreClock120m => 1,
            SpiTimingConfigCoreClock::SpiTimingConfigCoreClock160m => 2,
            SpiTimingConfigCoreClock::SpiTimingConfigCoreClock240m => 3,
        };

        set_peri_reg_bits(SPI0_MEM_CORE_CLK_SEL_REG, SPI_MEM_CORE_CLK_SEL, reg_val, 0);
    }

    #[ram]
    fn spi0_timing_config_set_flash_clock(freqdiv: u32) {
        if freqdiv == 1 {
            write_peri_reg(SPI0_MEM_CLOCK_REG, SPI_MEM_CLK_EQU_SYSCLK);
        } else {
            let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_CLKCNT_N_S)
                | ((freqdiv / 2 - 1) << SPI_MEM_CLKCNT_H_S)
                | ((freqdiv - 1) << SPI_MEM_CLKCNT_L_S);
            write_peri_reg(SPI0_MEM_CLOCK_REG, freqbits);
        }
    }

    #[ram]
    fn spi1_timing_config_set_flash_clock(freqdiv: u32) {
        if freqdiv == 1 {
            write_peri_reg(SPI1_MEM_CLOCK_REG, SPI_MEM_CLK_EQU_SYSCLK);
        } else {
            let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_CLKCNT_N_S)
                | ((freqdiv / 2 - 1) << SPI_MEM_CLKCNT_H_S)
                | ((freqdiv - 1) << SPI_MEM_CLKCNT_L_S);
            write_peri_reg(SPI1_MEM_CLOCK_REG, freqbits);
        }
    }

    #[ram]
    fn spi0_timing_config_set_psram_clock(freqdiv: u32) {
        if freqdiv == 1 {
            write_peri_reg(SPI0_MEM_SRAM_CLK_REG, SPI_MEM_SCLK_EQU_SYSCLK);
        } else {
            let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_SCLKCNT_N_S)
                | ((freqdiv / 2 - 1) << SPI_MEM_SCLKCNT_H_S)
                | ((freqdiv - 1) << SPI_MEM_SCLKCNT_L_S);
            write_peri_reg(SPI0_MEM_SRAM_CLK_REG, freqbits);
        }
    }

    #[ram]
    fn get_mspi_core_clock() -> SpiTimingConfigCoreClock {
        SPI_TIMING_CORE_CLOCK
    }

    #[ram]
    fn get_flash_clock_divider() -> u32 {
        match FLASH_FREQ {
            FlashFreq::FlashFreq20m => SPI_TIMING_CORE_CLOCK.mhz() / 20,
            FlashFreq::FlashFreq40m => SPI_TIMING_CORE_CLOCK.mhz() / 40,
            FlashFreq::FlashFreq80m => SPI_TIMING_CORE_CLOCK.mhz() / 80,
            FlashFreq::FlashFreq120m => SPI_TIMING_CORE_CLOCK.mhz() / 120,
        }
    }

    #[ram]
    fn get_psram_clock_divider() -> u32 {
        match SPIRAM_SPEED {
            SpiRamFreq::Freq40m => SPI_TIMING_CORE_CLOCK.mhz() / 40,
            SpiRamFreq::Freq80m => SPI_TIMING_CORE_CLOCK.mhz() / 80,
            SpiRamFreq::Freq120m => SPI_TIMING_CORE_CLOCK.mhz() / 120,
        }
    }

    // send reset command to psram, in spi mode
    #[ram]
    fn psram_reset_mode_spi1() {
        const PSRAM_RESET_EN: u16 = 0x66;
        const PSRAM_RESET: u16 = 0x99;
        const CS_PSRAM_SEL: u8 = 1 << 1;

        psram_exec_cmd(
            CommandMode::PsramCmdSpi,
            PSRAM_RESET_EN,
            8, // command and command bit len
            0,
            0, // address and address bit len
            0, // dummy bit len
            core::ptr::null(),
            0, // tx data and tx bit len
            core::ptr::null_mut(),
            0,            // rx data and rx bit len
            CS_PSRAM_SEL, // cs bit mask
            false,
        ); // whether is program/erase operation

        psram_exec_cmd(
            CommandMode::PsramCmdSpi,
            PSRAM_RESET,
            8, // command and command bit len
            0,
            0, // address and address bit len
            0, // dummy bit len
            core::ptr::null(),
            0, // tx data and tx bit len
            core::ptr::null_mut(),
            0,            // rx data and rx bit len
            CS_PSRAM_SEL, // cs bit mask
            false,
        ); // whether is program/erase operation
    }

    #[derive(PartialEq)]
    #[allow(unused)]
    enum CommandMode {
        PsramCmdQpi = 0,
        PsramCmdSpi = 1,
    }

    #[ram]
    fn psram_exec_cmd(
        mode: CommandMode,
        cmd: u16,
        cmd_bit_len: u16,
        addr: u32,
        addr_bit_len: u32,
        dummy_bits: u32,
        mosi_data: *const u8,
        mosi_bit_len: u32,
        miso_data: *mut u8,
        miso_bit_len: u32,
        cs_mask: u8,
        is_write_erase_operation: bool,
    ) {
        extern "C" {
            ///  Start a spi user command sequence
            ///  [`spi_num`] spi port
            ///  [`rx_buf`] buffer pointer to receive data
            ///  [`rx_len`] receive data length in byte
            ///  [`cs_en_mask`] decide which cs to use, 0 for cs0, 1 for cs1
            ///  [`is_write_erase`] to indicate whether this is a write or erase
            /// operation, since the CPU would check permission
            fn esp_rom_spi_cmd_start(
                spi_num: u32,
                rx_buf: *const u8,
                rx_len: u16,
                cs_en_mask: u8,
                is_write_erase: bool,
            );
        }

        unsafe {
            let spi1 = &*esp32s3::SPI1::PTR;
            let backup_usr = spi1.user().read().bits();
            let backup_usr1 = spi1.user1().read().bits();
            let backup_usr2 = spi1.user2().read().bits();
            let backup_ctrl = spi1.ctrl().read().bits();
            psram_set_op_mode(mode);
            _psram_exec_cmd(
                cmd,
                cmd_bit_len,
                addr,
                addr_bit_len,
                dummy_bits,
                mosi_data,
                mosi_bit_len,
                miso_data,
                miso_bit_len,
            );
            esp_rom_spi_cmd_start(
                1,
                miso_data,
                (miso_bit_len / 8) as u16,
                cs_mask,
                is_write_erase_operation,
            );

            spi1.user().write(|w| w.bits(backup_usr));
            spi1.user1().write(|w| w.bits(backup_usr1));
            spi1.user2().write(|w| w.bits(backup_usr2));
            spi1.ctrl().write(|w| w.bits(backup_ctrl));
        }
    }

    #[ram]
    fn _psram_exec_cmd(
        cmd: u16,
        cmd_bit_len: u16,
        addr: u32,
        addr_bit_len: u32,
        dummy_bits: u32,
        mosi_data: *const u8,
        mosi_bit_len: u32,
        miso_data: *mut u8,
        miso_bit_len: u32,
    ) {
        #[repr(C)]
        struct esp_rom_spi_cmd_t {
            cmd: u16,             // Command value
            cmd_bit_len: u16,     // Command byte length
            addr: *const u32,     // Point to address value
            addr_bit_len: u32,    // Address byte length
            tx_data: *const u32,  // Point to send data buffer
            tx_data_bit_len: u32, // Send data byte length.
            rx_data: *mut u32,    // Point to recevie data buffer
            rx_data_bit_len: u32, // Recevie Data byte length.
            dummy_bit_len: u32,
        }

        extern "C" {
            /// Config the spi user command
            /// [`spi_num`] spi port
            /// [`pcmd`] pointer to accept the spi command struct
            fn esp_rom_spi_cmd_config(spi_num: u32, pcmd: *const esp_rom_spi_cmd_t);
        }

        let conf = esp_rom_spi_cmd_t {
            cmd,
            cmd_bit_len,
            addr: addr as *const u32,
            addr_bit_len,
            tx_data: mosi_data as *const u32,
            tx_data_bit_len: mosi_bit_len,
            rx_data: miso_data as *mut u32,
            rx_data_bit_len: miso_bit_len,
            dummy_bit_len: dummy_bits,
        };

        unsafe {
            esp_rom_spi_cmd_config(1, &conf);
        }
    }

    #[ram]
    fn psram_set_op_mode(mode: CommandMode) {
        extern "C" {
            fn esp_rom_spi_set_op_mode(spi: u32, mode: u32);
        }

        const ESP_ROM_SPIFLASH_QIO_MODE: u32 = 0;
        const ESP_ROM_SPIFLASH_SLOWRD_MODE: u32 = 5;

        unsafe {
            match mode {
                CommandMode::PsramCmdQpi => {
                    esp_rom_spi_set_op_mode(1, ESP_ROM_SPIFLASH_QIO_MODE);
                    let spi1 = &*esp32s3::SPI1::PTR;
                    spi1.ctrl().modify(|_, w| w.fcmd_quad().set_bit());
                }
                CommandMode::PsramCmdSpi => {
                    esp_rom_spi_set_op_mode(1, ESP_ROM_SPIFLASH_SLOWRD_MODE);
                }
            }
        }
    }

    /// Enter QPI mode
    #[ram]
    fn psram_enable_qio_mode_spi1() {
        const PSRAM_ENTER_QMODE: u16 = 0x35;
        const CS_PSRAM_SEL: u8 = 1 << 1;

        psram_exec_cmd(
            CommandMode::PsramCmdSpi,
            PSRAM_ENTER_QMODE,
            8, // command and command bit len
            0,
            0, // address and address bit len
            0, // dummy bit len
            core::ptr::null(),
            0, // tx data and tx bit len
            core::ptr::null_mut(),
            0,            // rx data and rx bit len
            CS_PSRAM_SEL, // cs bit mask
            false,        // whether is program/erase operation
        );
    }

    #[ram]
    fn psram_set_cs_timing() {
        // SPI0/1 share the cs_hold / cs_setup, cd_hold_time / cd_setup_time registers
        // for PSRAM, so we only need to set SPI0 related registers here
        set_peri_reg_bits(
            SPI0_MEM_SPI_SMEM_AC_REG,
            SPI_MEM_SPI_SMEM_CS_HOLD_TIME_V,
            0,
            SPI_MEM_SPI_SMEM_CS_HOLD_TIME_S,
        );
        set_peri_reg_bits(
            SPI0_MEM_SPI_SMEM_AC_REG,
            SPI_MEM_SPI_SMEM_CS_SETUP_TIME_V,
            0,
            SPI_MEM_SPI_SMEM_CS_SETUP_TIME_S,
        );
        set_peri_reg_mask(
            SPI0_MEM_SPI_SMEM_AC_REG,
            SPI_MEM_SPI_SMEM_CS_HOLD_M | SPI_MEM_SPI_SMEM_CS_SETUP_M,
        );
    }

    #[ram]
    fn psram_gpio_config() {
        // CS1
        let cs1_io: u8 = PSRAM_CS_IO;
        if cs1_io == SPI_CS1_GPIO_NUM {
            unsafe {
                let iomux = &*esp32s3::IO_MUX::PTR;
                iomux
                    .gpio(cs1_io as usize)
                    .modify(|_, w| w.mcu_sel().variant(FUNC_SPICS1_SPICS1))
            }
        } else {
            unsafe {
                esp_rom_gpio_connect_out_signal(cs1_io, SPICS1_OUT_IDX, false, false);

                let iomux = &*esp32s3::IO_MUX::PTR;
                iomux
                    .gpio(cs1_io as usize)
                    .modify(|_, w| w.mcu_sel().variant(PIN_FUNC_GPIO))
            }
        }

        // WP HD
        let mut wp_io: u8 = PSRAM_SPIWP_SD3_IO;
        let spiconfig = unsafe { esp_rom_efuse_get_flash_gpio_info() };
        if spiconfig == ESP_ROM_EFUSE_FLASH_DEFAULT_SPI {
            // MSPI pins (except wp / hd) are all configured via IO_MUX in 1st
            // bootloader.
        } else {
            // MSPI pins (except wp / hd) are all configured via GPIO matrix in 1st
            // bootloader.
            wp_io = unsafe { esp_rom_efuse_get_flash_wp_gpio() };
        }
        // This ROM function will init both WP and HD pins.
        unsafe {
            esp_rom_spiflash_select_qio_pins(wp_io, spiconfig);
        }
    }

    #[inline(always)]
    fn clear_peri_reg_mask(reg: u32, mask: u32) {
        unsafe {
            (reg as *mut u32).write_volatile((reg as *mut u32).read_volatile() & !mask);
        }
    }

    #[inline(always)]
    fn set_peri_reg_mask(reg: u32, mask: u32) {
        unsafe {
            (reg as *mut u32).write_volatile((reg as *mut u32).read_volatile() | mask);
        }
    }

    #[inline(always)]
    fn set_peri_reg_bits(reg: u32, bitmap: u32, value: u32, shift: u32) {
        unsafe {
            (reg as *mut u32).write_volatile(
                ((reg as *mut u32).read_volatile() & !(bitmap << shift))
                    | ((value & bitmap) << shift),
            );
        }
    }

    #[inline(always)]
    fn write_peri_reg(reg: u32, val: u32) {
        unsafe {
            (reg as *mut u32).write_volatile(val);
        }
    }
}

#[cfg(any(
    feature = "opsram-2m",
    feature = "opsram-4m",
    feature = "opsram-8m",
    feature = "opsram-16m"
))]
pub(crate) mod utils {
    use procmacros::ram;

    // these should probably be configurable, relates to https://github.com/esp-rs/esp-hal/issues/42
    // probably also the PSRAM size shouldn't get configured via features
    const SPI_TIMING_CORE_CLOCK: SpiTimingConfigCoreClock =
        SpiTimingConfigCoreClock::SpiTimingConfigCoreClock80m;
    const FLASH_FREQ: FlashFreq = FlashFreq::FlashFreq80m;

    cfg_if::cfg_if! {
        if #[cfg(feature = "psram-80mhz")] {
            const SPIRAM_SPEED: SpiRamFreq = SpiRamFreq::Freq80m;
        } else {
            const SPIRAM_SPEED: SpiRamFreq = SpiRamFreq::Freq40m;
        }
    }

    #[allow(unused)]
    enum FlashFreq {
        FlashFreq20m,
        FlashFreq40m,
        FlashFreq80m,
        FlashFreq120m,
    }

    #[allow(unused)]
    enum SpiRamFreq {
        Freq40m,
        Freq80m,
        Freq120m,
    }

    #[allow(unused)]
    #[derive(Debug)]
    #[cfg_attr(feature = "defmt", derive(defmt::Format))]
    enum SpiTimingConfigCoreClock {
        SpiTimingConfigCoreClock80m,
        SpiTimingConfigCoreClock120m,
        SpiTimingConfigCoreClock160m,
        SpiTimingConfigCoreClock240m,
    }

    impl SpiTimingConfigCoreClock {
        fn mhz(&self) -> u32 {
            match self {
                SpiTimingConfigCoreClock::SpiTimingConfigCoreClock80m => 80,
                SpiTimingConfigCoreClock::SpiTimingConfigCoreClock120m => 120,
                SpiTimingConfigCoreClock::SpiTimingConfigCoreClock160m => 160,
                SpiTimingConfigCoreClock::SpiTimingConfigCoreClock240m => 240,
            }
        }
    }

    const OPI_PSRAM_SYNC_READ: u16 = 0x0000;
    const OPI_PSRAM_SYNC_WRITE: u16 = 0x8080;
    const OPI_PSRAM_REG_READ: u16 = 0x4040;
    const OPI_PSRAM_REG_WRITE: u16 = 0xC0C0;
    const OCT_PSRAM_RD_CMD_BITLEN: u8 = 16;
    const OCT_PSRAM_WR_CMD_BITLEN: u8 = 16;
    const OCT_PSRAM_ADDR_BITLEN: u8 = 32;
    const OCT_PSRAM_RD_DUMMY_BITLEN: u8 = 2 * (10 - 1);
    const OCT_PSRAM_WR_DUMMY_BITLEN: u8 = 2 * (5 - 1);
    const OCT_PSRAM_CS1_IO: u8 = SPI_CS1_GPIO_NUM;
    const OCT_PSRAM_VENDOR_ID: u8 = 0xD;

    const OCT_PSRAM_CS_SETUP_TIME: u8 = 3;
    const OCT_PSRAM_CS_HOLD_TIME: u8 = 3;
    const OCT_PSRAM_CS_HOLD_DELAY: u8 = 2;

    const PSRAM_SIZE_2MB: usize = 2 * 1024 * 1024;
    const PSRAM_SIZE_4MB: usize = 4 * 1024 * 1024;
    const PSRAM_SIZE_8MB: usize = 8 * 1024 * 1024;
    const PSRAM_SIZE_16MB: usize = 16 * 1024 * 1024;
    const PSRAM_SIZE_32MB: usize = 32 * 1024 * 1024;

    const SPI_CS1_GPIO_NUM: u8 = 26;
    const FUNC_SPICS1_SPICS1: u8 = 0;

    const SPI1_MEM_DDR_REG: u32 = DR_REG_SPI1_BASE + 0xe0;
    const SPI_MEM_SPI_FMEM_VAR_DUMMY: u32 = 1 << 1;

    const DR_REG_SPI0_BASE: u32 = 0x60003000;
    const SPI0_MEM_SPI_SMEM_AC_REG: u32 = DR_REG_SPI0_BASE + 0xDC;
    const SPI_MEM_SPI_SMEM_CS_HOLD_TIME_V: u32 = 0x1F;
    const SPI_MEM_SPI_SMEM_CS_HOLD_TIME_S: u32 = 7;
    const SPI_MEM_SPI_SMEM_CS_SETUP_TIME_V: u32 = 0x1F;
    const SPI_MEM_SPI_SMEM_CS_SETUP_TIME_S: u32 = 2;
    const SPI_MEM_SPI_SMEM_CS_HOLD_M: u32 = 1 << 1;
    const SPI_MEM_SPI_SMEM_CS_SETUP_M: u32 = 1 << 0;
    const SPI0_MEM_CACHE_SCTRL_REG: u32 = DR_REG_SPI0_BASE + 0x40;
    const SPI0_MEM_SRAM_DWR_CMD_REG: u32 = DR_REG_SPI0_BASE + 0x4C;
    const SPI0_MEM_SRAM_DRD_CMD_REG: u32 = DR_REG_SPI0_BASE + 0x48;
    const SPI_MEM_CACHE_SRAM_USR_RCMD_M: u32 = 1 << 5;
    const SPI_MEM_CACHE_SRAM_USR_WCMD_M: u32 = 1 << 20;
    const SPI_MEM_CACHE_SRAM_USR_WR_CMD_BITLEN: u32 = 0x0000000F;
    const SPI_MEM_CACHE_SRAM_USR_WR_CMD_BITLEN_S: u32 = 28;
    const SPI_MEM_CACHE_SRAM_USR_WR_CMD_VALUE: u32 = 0x0000FFFF;
    const SPI_MEM_CACHE_SRAM_USR_WR_CMD_VALUE_S: u32 = 0;
    const SPI_MEM_CACHE_SRAM_USR_RD_CMD_BITLEN_V: u32 = 0xF;
    const SPI_MEM_CACHE_SRAM_USR_RD_CMD_BITLEN_S: u32 = 28;
    const SPI_MEM_CACHE_SRAM_USR_RD_CMD_VALUE_V: u32 = 0xFFFF;
    const SPI_MEM_CACHE_SRAM_USR_RD_CMD_VALUE_S: u32 = 0;
    const SPI_MEM_SRAM_ADDR_BITLEN_V: u32 = 0x3F;
    const SPI_MEM_SRAM_ADDR_BITLEN_S: u32 = 14;
    const SPI_MEM_USR_RD_SRAM_DUMMY_M: u32 = 1 << 4;
    const SPI_MEM_SRAM_RDUMMY_CYCLELEN_V: u32 = 0x3F;
    const SPI_MEM_SRAM_RDUMMY_CYCLELEN_S: u32 = 6;
    const SPI0_MEM_CORE_CLK_SEL_REG: u32 = DR_REG_SPI0_BASE + 0xEC;
    const SPI_MEM_CORE_CLK_SEL: u32 = 0x00000003;
    const DR_REG_SPI1_BASE: u32 = 0x60002000;
    const SPI0_MEM_DATE_REG: u32 = DR_REG_SPI0_BASE + 0x3FC;
    const SPI0_MEM_CLOCK_REG: u32 = DR_REG_SPI0_BASE + 0x14;
    const SPI1_MEM_CLOCK_REG: u32 = DR_REG_SPI1_BASE + 0x14;
    const SPI0_MEM_SRAM_CLK_REG: u32 = DR_REG_SPI0_BASE + 0x50;
    const SPI_MEM_CLK_EQU_SYSCLK: u32 = 1 << 31;
    const SPI_MEM_SCLK_EQU_SYSCLK: u32 = 1 << 31;
    const SPI_MEM_CLKCNT_N_S: u32 = 16;
    const SPI_MEM_SCLKCNT_N_S: u32 = 16;
    const SPI_MEM_CLKCNT_H_S: u32 = 8;
    const SPI_MEM_SCLKCNT_H_S: u32 = 8;
    const SPI_MEM_CLKCNT_L_S: u32 = 0;
    const SPI_MEM_SCLKCNT_L_S: u32 = 0;
    const SPI_MEM_CACHE_USR_SCMD_4BYTE_M: u32 = 1 << 0;
    const SPI_MEM_USR_WR_SRAM_DUMMY_M: u32 = 1 << 3;
    const SPI0_MEM_SPI_SMEM_DDR_REG: u32 = DR_REG_SPI0_BASE + 0xE4;
    const SPI0_MEM_SRAM_CMD_REG: u32 = DR_REG_SPI0_BASE + 0x44;
    const SPI_MEM_SPI_SMEM_VAR_DUMMY_M: u32 = 1 << 1;
    const SPI_MEM_SRAM_WDUMMY_CYCLELEN_V: u32 = 0x3F;
    const SPI_MEM_SRAM_WDUMMY_CYCLELEN_S: u32 = 22;
    const SPI_MEM_SPI_SMEM_DDR_WDAT_SWP_M: u32 = 1 << 3;
    const SPI_MEM_SPI_SMEM_DDR_RDAT_SWP_M: u32 = 1 << 2;
    const SPI_MEM_SPI_SMEM_DDR_EN_M: u32 = 1 << 0;
    const SPI_MEM_SDUMMY_OUT_M: u32 = 1 << 22;
    const SPI_MEM_SCMD_OCT_M: u32 = 1 << 21;
    const SPI_MEM_SADDR_OCT_M: u32 = 1 << 20;
    const SPI_MEM_SDOUT_OCT_M: u32 = 1 << 19;
    const SPI_MEM_SDIN_OCT_M: u32 = 1 << 18;
    const SPI_MEM_SRAM_OCT_M: u32 = 1 << 21;
    const SPI_MEM_SPI_SMEM_CS_HOLD_DELAY_V: u32 = 0x3F;
    const SPI_MEM_SPI_SMEM_CS_HOLD_DELAY_S: u32 = 25;
    const SPI_MEM_SPI_SMEM_SPICLK_FUN_DRV: u32 = 0x00000003;
    const SPI_MEM_SPI_SMEM_SPICLK_FUN_DRV_V: u32 = 0x3;
    const SPI_MEM_SPI_SMEM_SPICLK_FUN_DRV_S: u32 = 0;
    const ESP_ROM_SPIFLASH_OPI_DTR_MODE: u8 = 7;

    extern "C" {
        // @brief To execute a flash operation command
        // @param spi_num spi port
        // @param mode Flash Read Mode
        // @param cmd data to send in command field
        // @param cmd_bit_len bit length of command field
        // @param addr data to send in address field
        // @param addr_bit_len bit length of address field
        // @param dummy_bits bit length of dummy field
        // @param mosi_data data buffer to be sent in mosi field
        // @param mosi_bit_len bit length of data buffer to be sent in mosi field
        // @param miso_data data buffer to accept data in miso field
        // @param miso_bit_len bit length of data buffer to accept data in miso field
        // @param cs_mark decide which cs pin to use. 0: cs0, 1: cs1
        // @param is_write_erase_operation to indicate whether this a write or erase
        // flash operation
        fn esp_rom_opiflash_exec_cmd(
            spi_num: u32,
            mode: u8,
            cmd: u32,
            cmd_bit_len: u32,
            addr: u32,
            addr_bit_len: u32,
            dummy_bits: u32,
            mosi_data: *const u8,
            mosi_bit_len: u32,
            miso_data: *mut u8,
            miso_bit_len: u32,
            cs_mask: u32,
            is_write_erase_operation: bool,
        );

        // @brief Set data swap mode in DTR(DDR) mode
        // @param spi_num spi port
        // @param wr_swap to decide whether to swap fifo data in dtr write operation
        // @param rd_swap to decide whether to swap fifo data in dtr read operation
        fn esp_rom_spi_set_dtr_swap_mode(spi: u32, wr_swap: bool, rd_swap: bool);

        fn esp_rom_opiflash_pin_config();
    }

    #[derive(Default)]
    #[repr(C)]
    struct OpiPsramModeReg {
        pub mr0: u8,
        pub mr1: u8,
        pub mr2: u8,
        pub mr3: u8,
        pub mr4: u8,
        pub mr8: u8,
    }

    #[allow(unused)]
    impl OpiPsramModeReg {
        fn drive_str(&self) -> u8 {
            self.mr0 & 0b11
        }

        fn set_drive_str(&mut self, value: u8) {
            self.mr0 &= !0b11;
            self.mr0 |= value & 0b11;
        }

        fn read_latency(&self) -> u8 {
            (self.mr0 >> 2) & 0b111
        }

        fn set_read_latency(&mut self, value: u8) {
            self.mr0 &= !(0b111 << 2);
            self.mr0 |= (value & 0b111) << 2;
        }

        fn lt(&self) -> u8 {
            (self.mr0 >> 5) & 0b1
        }

        fn set_lt(&mut self, value: u8) {
            self.mr0 &= !(0b1 << 5);
            self.mr0 |= (value & 0b1) << 5;
        }

        fn rsvd0_1(&self) -> u8 {
            (self.mr0 >> 6) & 0b11
        }

        fn set_rsvd0_1(&mut self, value: u8) {
            self.mr0 &= !(0b11 << 6);
            self.mr0 |= (value & 0b11) << 6;
        }

        fn vendor_id(&self) -> u8 {
            self.mr1 & 0b11111
        }

        fn set_vendor_id(&mut self, value: u8) {
            self.mr1 &= !0b11111;
            self.mr1 |= value & 0b11111;
        }

        fn rsvd0_2(&self) -> u8 {
            (self.mr1 >> 5) & 0b111
        }

        fn set_rsvd0_2(&mut self, value: u8) {
            self.mr1 &= !(0b111 << 5);
            self.mr1 |= (value & 0b111) << 5;
        }

        fn density(&self) -> u8 {
            self.mr2 & 0b111
        }

        fn set_density(&mut self, value: u8) {
            self.mr2 &= !0b111;
            self.mr2 |= value & 0b111;
        }

        fn dev_id(&self) -> u8 {
            (self.mr2 >> 3) & 0b11
        }

        fn set_dev_id(&mut self, value: u8) {
            self.mr2 &= !(0b11 << 3);
            self.mr2 |= (value & 0b11) << 3;
        }

        fn rsvd1_2(&self) -> u8 {
            (self.mr2 >> 5) & 0b11
        }

        fn set_rsvd1_2(&mut self, value: u8) {
            self.mr2 &= !(0b11 << 5);
            self.mr2 |= (value & 0b11) << 5;
        }

        fn gb(&self) -> u8 {
            (self.mr2 >> 7) & 0b1
        }

        fn set_gb(&mut self, value: u8) {
            self.mr2 &= !(0b1 << 7);
            self.mr2 |= (value & 0b1) << 7;
        }

        fn rsvd3_7(&self) -> u8 {
            self.mr3 & 0b11111
        }

        fn set_rsvd3_7(&mut self, value: u8) {
            self.mr3 &= !0b11111;
            self.mr3 |= value & 0b11111;
        }

        fn srf(&self) -> u8 {
            (self.mr3 >> 5) & 0b1
        }

        fn set_srf(&mut self, value: u8) {
            self.mr3 &= !(0b1 << 5);
            self.mr3 |= (value & 0b1) << 5;
        }

        fn vcc(&self) -> u8 {
            (self.mr3 >> 6) & 0b1
        }

        fn set_vcc(&mut self, value: u8) {
            self.mr3 &= !(0b1 << 6);
            self.mr3 |= (value & 0b1) << 6;
        }

        fn rsvd0(&self) -> u8 {
            (self.mr3 >> 7) & 0b1
        }

        fn set_rsvd0(&mut self, value: u8) {
            self.mr3 &= !(0b1 << 7);
            self.mr3 |= (value & 0b1) << 7;
        }

        fn pasr(&self) -> u8 {
            self.mr4 & 0b111
        }

        fn set_pasr(&mut self, value: u8) {
            self.mr4 &= !0b111;
            self.mr4 |= value & 0b111;
        }

        fn rf(&self) -> u8 {
            (self.mr4 >> 3) & 0b1
        }

        fn set_rf(&mut self, value: u8) {
            self.mr4 &= !(0b1 << 3);
            self.mr4 |= (value & 0b1) << 3;
        }

        fn rsvd3(&self) -> u8 {
            (self.mr4 >> 4) & 0b1
        }

        fn set_rsvd3(&mut self, value: u8) {
            self.mr4 &= !(0b1 << 4);
            self.mr4 |= (value & 0b1) << 4;
        }

        fn wr_latency(&self) -> u8 {
            (self.mr4 >> 5) & 0b111
        }

        fn set_wr_latency(&mut self, value: u8) {
            self.mr4 &= !(0b111 << 5);
            self.mr4 |= (value & 0b111) << 5;
        }

        fn bl(&self) -> u8 {
            self.mr8 & 0b11
        }

        fn set_bl(&mut self, value: u8) {
            self.mr8 &= !0b11;
            self.mr8 |= value & 0b11;
        }

        fn bt(&self) -> u8 {
            (self.mr8 >> 2) & 0b1
        }

        fn set_bt(&mut self, value: u8) {
            self.mr8 &= !(0b1 << 2);
            self.mr8 |= (value & 0b1) << 2;
        }

        fn rsvd0_4(&self) -> u8 {
            (self.mr8 >> 3) & 0b11111
        }

        fn set_rsvd0_4(&mut self, value: u8) {
            self.mr8 &= !(0b11111 << 3);
            self.mr8 |= (value & 0b11111) << 3;
        }
    }

    #[ram]
    pub(crate) fn psram_init() {
        mspi_pin_init();
        init_psram_pins();
        set_psram_cs_timing();

        // for now we don't support ECC
        // "s_configure_psram_ecc();"

        // enter MSPI slow mode to init PSRAM device registers
        spi_timing_enter_mspi_low_speed_mode(true);

        // set to variable dummy mode
        set_peri_reg_mask(SPI1_MEM_DDR_REG, SPI_MEM_SPI_FMEM_VAR_DUMMY);
        unsafe {
            esp_rom_spi_set_dtr_swap_mode(1, false, false);
        }

        // Set PSRAM read latency and drive strength
        let mut mode_reg = OpiPsramModeReg::default();
        mode_reg.set_lt(1);
        mode_reg.set_read_latency(2);
        mode_reg.set_drive_str(0);
        mode_reg.set_bl(3);
        mode_reg.set_bt(0);

        init_psram_mode_reg(1, &mode_reg);
        // Print PSRAM info
        get_psram_mode_reg(1, &mut mode_reg);

        print_psram_info(&mode_reg);

        if mode_reg.vendor_id() != OCT_PSRAM_VENDOR_ID {
            warn!("PSRAM ID read error: {:x}, PSRAM chip not found or not supported, or wrong PSRAM line mode", mode_reg.vendor_id());
            return;
        }

        let psram_size = match mode_reg.density() {
            0x0 => PSRAM_SIZE_2MB,
            0x1 => PSRAM_SIZE_4MB,
            0x3 => PSRAM_SIZE_8MB,
            0x5 => PSRAM_SIZE_16MB,
            0x7 => PSRAM_SIZE_32MB,
            _ => 0,
        };
        info!("{} bytes of PSRAM", psram_size);

        // Do PSRAM timing tuning, we use SPI1 to do the tuning, and set the
        // SPI0 PSRAM timing related registers accordingly
        // this is unsupported for now
        // spi_timing_psram_tuning();

        // Back to the high speed mode. Flash/PSRAM clocks are set to the clock
        // that user selected. SPI0/1 registers are all set correctly
        spi_timing_enter_mspi_high_speed_mode(true);

        // Tuning may change SPI1 regs, whereas legacy spi_flash APIs rely on
        // these regs. This function is to restore SPI1 init state.
        spi_flash_set_rom_required_regs();

        // Flash chip requires MSPI specifically, call this function to set them
        // this is unsupported for now
        // spi_flash_set_vendor_required_regs();

        config_psram_spi_phases();
    }

    // Configure PSRAM SPI0 phase related registers here according to the PSRAM chip
    // requirement
    fn config_psram_spi_phases() {
        // Config Write CMD phase for SPI0 to access PSRAM
        set_peri_reg_mask(SPI0_MEM_CACHE_SCTRL_REG, SPI_MEM_CACHE_SRAM_USR_WCMD_M);
        set_peri_reg_bits(
            SPI0_MEM_SRAM_DWR_CMD_REG,
            SPI_MEM_CACHE_SRAM_USR_WR_CMD_BITLEN,
            (OCT_PSRAM_WR_CMD_BITLEN - 1) as u32,
            SPI_MEM_CACHE_SRAM_USR_WR_CMD_BITLEN_S,
        );
        set_peri_reg_bits(
            SPI0_MEM_SRAM_DWR_CMD_REG,
            SPI_MEM_CACHE_SRAM_USR_WR_CMD_VALUE,
            OPI_PSRAM_SYNC_WRITE as u32,
            SPI_MEM_CACHE_SRAM_USR_WR_CMD_VALUE_S,
        );

        // Config Read CMD phase for SPI0 to access PSRAM
        set_peri_reg_mask(SPI0_MEM_CACHE_SCTRL_REG, SPI_MEM_CACHE_SRAM_USR_RCMD_M);
        set_peri_reg_bits(
            SPI0_MEM_SRAM_DRD_CMD_REG,
            SPI_MEM_CACHE_SRAM_USR_RD_CMD_BITLEN_V,
            (OCT_PSRAM_RD_CMD_BITLEN - 1) as u32,
            SPI_MEM_CACHE_SRAM_USR_RD_CMD_BITLEN_S,
        );
        set_peri_reg_bits(
            SPI0_MEM_SRAM_DRD_CMD_REG,
            SPI_MEM_CACHE_SRAM_USR_RD_CMD_VALUE_V,
            OPI_PSRAM_SYNC_READ as u32,
            SPI_MEM_CACHE_SRAM_USR_RD_CMD_VALUE_S,
        );

        // Config ADDR phase
        set_peri_reg_bits(
            SPI0_MEM_CACHE_SCTRL_REG,
            SPI_MEM_SRAM_ADDR_BITLEN_V,
            (OCT_PSRAM_ADDR_BITLEN - 1) as u32,
            SPI_MEM_SRAM_ADDR_BITLEN_S,
        );
        set_peri_reg_mask(SPI0_MEM_CACHE_SCTRL_REG, SPI_MEM_CACHE_USR_SCMD_4BYTE_M);

        // Config RD/WR Dummy phase
        set_peri_reg_mask(
            SPI0_MEM_CACHE_SCTRL_REG,
            SPI_MEM_USR_RD_SRAM_DUMMY_M | SPI_MEM_USR_WR_SRAM_DUMMY_M,
        );
        set_peri_reg_bits(
            SPI0_MEM_CACHE_SCTRL_REG,
            SPI_MEM_SRAM_RDUMMY_CYCLELEN_V,
            (OCT_PSRAM_RD_DUMMY_BITLEN - 1) as u32,
            SPI_MEM_SRAM_RDUMMY_CYCLELEN_S,
        );
        set_peri_reg_mask(SPI0_MEM_SPI_SMEM_DDR_REG, SPI_MEM_SPI_SMEM_VAR_DUMMY_M);
        set_peri_reg_bits(
            SPI0_MEM_CACHE_SCTRL_REG,
            SPI_MEM_SRAM_WDUMMY_CYCLELEN_V,
            (OCT_PSRAM_WR_DUMMY_BITLEN - 1) as u32,
            SPI_MEM_SRAM_WDUMMY_CYCLELEN_S,
        );

        clear_peri_reg_mask(
            SPI0_MEM_SPI_SMEM_DDR_REG,
            SPI_MEM_SPI_SMEM_DDR_WDAT_SWP_M | SPI_MEM_SPI_SMEM_DDR_RDAT_SWP_M,
        );
        set_peri_reg_mask(SPI0_MEM_SPI_SMEM_DDR_REG, SPI_MEM_SPI_SMEM_DDR_EN_M);

        set_peri_reg_mask(
            SPI0_MEM_SRAM_CMD_REG,
            SPI_MEM_SDUMMY_OUT_M
                | SPI_MEM_SCMD_OCT_M
                | SPI_MEM_SADDR_OCT_M
                | SPI_MEM_SDOUT_OCT_M
                | SPI_MEM_SDIN_OCT_M,
        );
        set_peri_reg_mask(SPI0_MEM_CACHE_SCTRL_REG, SPI_MEM_SRAM_OCT_M);
    }

    #[ram]
    fn spi_flash_set_rom_required_regs() {
        // Disable the variable dummy mode when doing timing tuning
        clear_peri_reg_mask(SPI1_MEM_DDR_REG, SPI_MEM_SPI_FMEM_VAR_DUMMY);
        // STR /DTR mode setting is done every time when
        // `esp_rom_opiflash_exec_cmd` is called
        //
        // Add any registers that are not set in ROM SPI flash functions here in
        // the future
    }

    #[ram]
    fn mspi_pin_init() {
        unsafe {
            esp_rom_opiflash_pin_config();
        }
        spi_timing_set_pin_drive_strength();
        // Set F4R4 board pin drive strength. TODO: IDF-3663
    }

    #[ram]
    fn spi_timing_set_pin_drive_strength() {
        // For now, set them all to 3. Need to check after QVL test results are out.
        // TODO: IDF-3663 Set default clk
        set_peri_reg_mask(SPI0_MEM_DATE_REG, SPI_MEM_SPICLK_PAD_DRV_CTL_EN);
        set_peri_reg_bits(
            SPI0_MEM_DATE_REG,
            SPI_MEM_SPI_SMEM_SPICLK_FUN_DRV,
            3,
            SPI_MEM_SPI_SMEM_SPICLK_FUN_DRV_S,
        );
        set_peri_reg_bits(
            SPI0_MEM_DATE_REG,
            SPI_MEM_SPI_FMEM_SPICLK_FUN_DRV,
            3,
            SPI_MEM_SPI_FMEM_SPICLK_FUN_DRV_S,
        );
        // Set default mspi d0 ~ d7, dqs pin drive strength
        let pins = &[27usize, 28, 31, 32, 33, 34, 35, 36, 37];
        for pin in pins {
            unsafe {
                let iomux = &*esp32s3::IO_MUX::PTR;
                iomux.gpio(*pin).modify(|_, w| w.fun_drv().variant(3))
            }
        }
    }

    const SPI_MEM_SPICLK_PAD_DRV_CTL_EN: u32 = 1 << 4;
    const SPI_MEM_SPI_FMEM_SPICLK_FUN_DRV: u32 = 0x00000003;
    const SPI_MEM_SPI_FMEM_SPICLK_FUN_DRV_S: u32 = 2;

    fn spi_timing_enter_mspi_low_speed_mode(control_spi1: bool) {
        // Here we are going to slow the SPI1 frequency to 20Mhz, so we need to
        // set SPI1 din_num and din_mode regs.
        //
        // Because SPI0 and SPI1 share the din_num and din_mode regs, so if we
        // clear SPI1 din_num and din_mode to 0, if the SPI0 flash
        // module clock is still in high freq, it may not work correctly.
        //
        // Therefore, here we need to slow both the SPI0 and SPI1 and related
        // timing tuning regs to 20Mhz configuration.
        // Switch SPI1 and SPI0 clock as 20MHz, set its SPIMEM core clock as 80M and set
        // clock division as 4
        spi0_timing_config_set_core_clock(SpiTimingConfigCoreClock::SpiTimingConfigCoreClock80m); // SPI0 and SPI1 share the register for core clock. So we only set SPI0 here.
        spi0_timing_config_set_flash_clock(4);
        if control_spi1 {
            // After tuning, won't touch SPI1 again
            spi1_timing_config_set_flash_clock(4);
        }

        // Set PSRAM module clock
        spi0_timing_config_set_psram_clock(4);

        // for now we don't support tuning the timing
        // "clear_timing_tuning_regs(control_spi1);"
    }

    // Set SPI0 FLASH and PSRAM module clock, din_num, din_mode and extra dummy,
    // according to the configuration got from timing tuning function
    // (`calculate_best_flash_tuning_config`). iF control_spi1 == 1, will also
    // update SPI1 timing registers. Should only be set to 1 when do tuning.
    //
    // This function should always be called after `spi_timing_flash_tuning` or
    // `calculate_best_flash_tuning_config`
    fn spi_timing_enter_mspi_high_speed_mode(control_spi1: bool) {
        // spi_timing_config_core_clock_t core_clock = get_mspi_core_clock();
        let core_clock = SpiTimingConfigCoreClock::SpiTimingConfigCoreClock80m;

        let flash_div: u32 = get_flash_clock_divider();
        let psram_div: u32 = get_psram_clock_divider();

        // Set SPI01 core clock
        spi0_timing_config_set_core_clock(core_clock); // SPI0 and SPI1 share the register for core clock. So we only set SPI0 here.
                                                       // Set FLASH module clock
        spi0_timing_config_set_flash_clock(flash_div);
        if control_spi1 {
            spi1_timing_config_set_flash_clock(flash_div);
        }
        // Set PSRAM module clock
        spi0_timing_config_set_psram_clock(psram_div);

        // for now we don't support tuning the timing
        // "set_timing_tuning_regs_as_required(true);"
    }

    fn set_psram_cs_timing() {
        // SPI0/1 share the cs_hold / cs_setup, cd_hold_time / cd_setup_time,
        // cs_hold_delay registers for PSRAM, so we only need to set SPI0 related
        // registers here
        set_peri_reg_mask(
            SPI0_MEM_SPI_SMEM_AC_REG,
            SPI_MEM_SPI_SMEM_CS_HOLD_M | SPI_MEM_SPI_SMEM_CS_SETUP_M,
        );
        set_peri_reg_bits(
            SPI0_MEM_SPI_SMEM_AC_REG,
            SPI_MEM_SPI_SMEM_CS_HOLD_TIME_V,
            OCT_PSRAM_CS_HOLD_TIME as u32,
            SPI_MEM_SPI_SMEM_CS_HOLD_TIME_S,
        );
        set_peri_reg_bits(
            SPI0_MEM_SPI_SMEM_AC_REG,
            SPI_MEM_SPI_SMEM_CS_SETUP_TIME_V,
            OCT_PSRAM_CS_SETUP_TIME as u32,
            SPI_MEM_SPI_SMEM_CS_SETUP_TIME_S,
        );
        // CONFIG_SPIRAM_ECC_ENABLE unsupported for now
        // CS1 high time
        set_peri_reg_bits(
            SPI0_MEM_SPI_SMEM_AC_REG,
            SPI_MEM_SPI_SMEM_CS_HOLD_DELAY_V,
            OCT_PSRAM_CS_HOLD_DELAY as u32,
            SPI_MEM_SPI_SMEM_CS_HOLD_DELAY_S,
        );
    }

    fn init_psram_pins() {
        // Set cs1 pin function
        unsafe {
            let iomux = &*esp32s3::IO_MUX::PTR;
            iomux
                .gpio(OCT_PSRAM_CS1_IO as usize)
                .modify(|_, w| w.mcu_sel().variant(FUNC_SPICS1_SPICS1))
        }

        // Set mspi cs1 drive strength
        unsafe {
            let iomux = &*esp32s3::IO_MUX::PTR;
            iomux
                .gpio(OCT_PSRAM_CS1_IO as usize)
                .modify(|_, w| w.fun_drv().variant(3))
        }

        // Set psram clock pin drive strength
        set_peri_reg_bits(
            SPI0_MEM_DATE_REG,
            SPI_MEM_SPI_SMEM_SPICLK_FUN_DRV_V,
            3,
            SPI_MEM_SPI_SMEM_SPICLK_FUN_DRV_S,
        );
    }

    fn get_psram_mode_reg(spi_num: u32, out_reg: &mut OpiPsramModeReg) {
        let mode = ESP_ROM_SPIFLASH_OPI_DTR_MODE;
        let cmd_len: u32 = 16;
        let addr_bit_len: u32 = 32;
        let dummy: u32 = OCT_PSRAM_RD_DUMMY_BITLEN as u32;
        let mut data_bit_len: u32 = 16;

        unsafe {
            // Read MR0~1 register
            esp_rom_opiflash_exec_cmd(
                spi_num,
                mode,
                OPI_PSRAM_REG_READ as u32,
                cmd_len,
                0x0,
                addr_bit_len,
                dummy,
                core::ptr::null(),
                0,
                &mut out_reg.mr0,
                data_bit_len,
                1 << 1,
                false,
            );
            // Read MR2~3 register
            esp_rom_opiflash_exec_cmd(
                spi_num,
                mode,
                OPI_PSRAM_REG_READ as u32,
                cmd_len,
                0x2,
                addr_bit_len,
                dummy,
                core::ptr::null(),
                0,
                &mut out_reg.mr2,
                data_bit_len,
                1 << 1,
                false,
            );
            data_bit_len = 8;
            // Read MR4 register
            esp_rom_opiflash_exec_cmd(
                spi_num,
                mode,
                OPI_PSRAM_REG_READ as u32,
                cmd_len,
                0x4,
                addr_bit_len,
                dummy,
                core::ptr::null(),
                0,
                &mut out_reg.mr4,
                data_bit_len,
                1 << 1,
                false,
            );
            // Read MR8 register
            esp_rom_opiflash_exec_cmd(
                spi_num,
                mode,
                OPI_PSRAM_REG_READ as u32,
                cmd_len,
                0x8,
                addr_bit_len,
                dummy,
                core::ptr::null(),
                0,
                &mut out_reg.mr8,
                data_bit_len,
                1 << 1,
                false,
            );
        }
    }

    // Initialise mode registers of the PSRAM
    fn init_psram_mode_reg(spi_num: u32, mode_reg_config: &OpiPsramModeReg) {
        let mode = ESP_ROM_SPIFLASH_OPI_DTR_MODE;
        let cmd_len: u32 = 16;
        let addr: u32 = 0x0; // 0x0 is the MR0 register
        let addr_bit_len: u32 = 32;
        let dummy = OCT_PSRAM_RD_DUMMY_BITLEN as u32;
        let mut mode_reg = OpiPsramModeReg::default();
        let data_bit_len: u32 = 16;

        // read
        unsafe {
            esp_rom_opiflash_exec_cmd(
                spi_num,
                mode,
                OPI_PSRAM_REG_READ as u32,
                cmd_len,
                addr,
                addr_bit_len,
                dummy,
                core::ptr::null(),
                0,
                &mut mode_reg.mr0,
                data_bit_len,
                1 << 1,
                false,
            );
        }

        // modify
        mode_reg.set_lt(mode_reg_config.lt());
        mode_reg.set_read_latency(mode_reg_config.read_latency());
        mode_reg.set_drive_str(mode_reg_config.drive_str());

        // write
        unsafe {
            esp_rom_opiflash_exec_cmd(
                spi_num,
                mode,
                OPI_PSRAM_REG_WRITE as u32,
                cmd_len,
                addr,
                addr_bit_len,
                0,
                &mode_reg.mr0,
                16,
                core::ptr::null_mut(),
                0,
                1 << 1,
                false,
            );
        }

        // CONFIG_SPIRAM_ECC_ENABLE not yet supported
    }

    fn print_psram_info(reg_val: &OpiPsramModeReg) {
        info!(
            "vendor id    : {:02x} ({})",
            reg_val.vendor_id(),
            if reg_val.vendor_id() == 0x0d {
                "AP"
            } else {
                "UNKNOWN"
            }
        );
        info!(
            "dev id       : {:02x} (generation {})",
            reg_val.dev_id(),
            reg_val.dev_id() + 1
        );
        info!(
            "density      : {:02x} ({} Mbit)",
            reg_val.density(),
            if reg_val.density() == 0x1 {
                32
            } else if reg_val.density() == 0x3 {
                64
            } else if reg_val.density() == 0x5 {
                128
            } else if reg_val.density() == 0x7 {
                256
            } else {
                0
            }
        );
        info!(
            "good-die     : {:02x} ({})",
            reg_val.gb(),
            if reg_val.gb() == 1 { "Pass" } else { "Fail" }
        );
        info!(
            "Latency      : {:02x} ({})",
            reg_val.lt(),
            if reg_val.lt() == 1 {
                "Fixed"
            } else {
                "Variable"
            }
        );
        info!(
            "VCC          : {:02x} ({})",
            reg_val.vcc(),
            if reg_val.vcc() == 1 { "3V" } else { "1.8V" }
        );
        info!(
            "SRF          : {:02x} ({} Refresh)",
            reg_val.srf(),
            if reg_val.srf() == 0x1 { "Fast" } else { "Slow" }
        );
        info!(
            "BurstType    : {:02x} ({} Wrap)",
            reg_val.bt(),
            if reg_val.bt() == 1 && reg_val.bl() != 3 {
                "Hybrid"
            } else {
                ""
            }
        );
        info!(
            "BurstLen     : {:02x} ({} Byte)",
            reg_val.bl(),
            if reg_val.bl() == 0x00 {
                16
            } else if reg_val.bl() == 0x01 {
                32
            } else if reg_val.bl() == 0x10 {
                64
            } else {
                1024
            }
        );
        info!(
            "Readlatency  : {:02x} ({} cycles@{})",
            reg_val.read_latency(),
            reg_val.read_latency() * 2 + 6,
            if reg_val.lt() == 1 {
                "Fixed"
            } else {
                "Variable"
            }
        );
        info!(
            "DriveStrength: {:02x} (1/{})",
            reg_val.drive_str(),
            if reg_val.drive_str() == 0x00 {
                1
            } else if reg_val.drive_str() == 0x01 {
                2
            } else if reg_val.drive_str() == 0x02 {
                4
            } else {
                8
            }
        );
    }

    #[ram]
    fn spi0_timing_config_set_core_clock(core_clock: SpiTimingConfigCoreClock) {
        let reg_val = match core_clock {
            SpiTimingConfigCoreClock::SpiTimingConfigCoreClock80m => 0,
            SpiTimingConfigCoreClock::SpiTimingConfigCoreClock120m => 1,
            SpiTimingConfigCoreClock::SpiTimingConfigCoreClock160m => 2,
            SpiTimingConfigCoreClock::SpiTimingConfigCoreClock240m => 3,
        };

        set_peri_reg_bits(SPI0_MEM_CORE_CLK_SEL_REG, SPI_MEM_CORE_CLK_SEL, reg_val, 0);
    }

    #[ram]
    fn spi0_timing_config_set_flash_clock(freqdiv: u32) {
        if freqdiv == 1 {
            write_peri_reg(SPI0_MEM_CLOCK_REG, SPI_MEM_CLK_EQU_SYSCLK);
        } else {
            let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_CLKCNT_N_S)
                | ((freqdiv / 2 - 1) << SPI_MEM_CLKCNT_H_S)
                | ((freqdiv - 1) << SPI_MEM_CLKCNT_L_S);
            write_peri_reg(SPI0_MEM_CLOCK_REG, freqbits);
        }
    }

    #[ram]
    fn spi1_timing_config_set_flash_clock(freqdiv: u32) {
        if freqdiv == 1 {
            write_peri_reg(SPI1_MEM_CLOCK_REG, SPI_MEM_CLK_EQU_SYSCLK);
        } else {
            let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_CLKCNT_N_S)
                | ((freqdiv / 2 - 1) << SPI_MEM_CLKCNT_H_S)
                | ((freqdiv - 1) << SPI_MEM_CLKCNT_L_S);
            write_peri_reg(SPI1_MEM_CLOCK_REG, freqbits);
        }
    }

    #[ram]
    fn spi0_timing_config_set_psram_clock(freqdiv: u32) {
        if freqdiv == 1 {
            write_peri_reg(SPI0_MEM_SRAM_CLK_REG, SPI_MEM_SCLK_EQU_SYSCLK);
        } else {
            let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_SCLKCNT_N_S)
                | ((freqdiv / 2 - 1) << SPI_MEM_SCLKCNT_H_S)
                | ((freqdiv - 1) << SPI_MEM_SCLKCNT_L_S);
            write_peri_reg(SPI0_MEM_SRAM_CLK_REG, freqbits);
        }
    }

    #[ram]
    fn get_flash_clock_divider() -> u32 {
        match FLASH_FREQ {
            FlashFreq::FlashFreq20m => SPI_TIMING_CORE_CLOCK.mhz() / 20,
            FlashFreq::FlashFreq40m => SPI_TIMING_CORE_CLOCK.mhz() / 40,
            FlashFreq::FlashFreq80m => SPI_TIMING_CORE_CLOCK.mhz() / 80,
            FlashFreq::FlashFreq120m => SPI_TIMING_CORE_CLOCK.mhz() / 120,
        }
    }

    #[ram]
    fn get_psram_clock_divider() -> u32 {
        match SPIRAM_SPEED {
            SpiRamFreq::Freq40m => SPI_TIMING_CORE_CLOCK.mhz() / 40,
            SpiRamFreq::Freq80m => SPI_TIMING_CORE_CLOCK.mhz() / 80,
            SpiRamFreq::Freq120m => SPI_TIMING_CORE_CLOCK.mhz() / 120,
        }
    }

    #[inline(always)]
    fn clear_peri_reg_mask(reg: u32, mask: u32) {
        unsafe {
            (reg as *mut u32).write_volatile((reg as *mut u32).read_volatile() & !mask);
        }
    }

    #[inline(always)]
    fn set_peri_reg_mask(reg: u32, mask: u32) {
        unsafe {
            (reg as *mut u32).write_volatile((reg as *mut u32).read_volatile() | mask);
        }
    }

    #[inline(always)]
    fn set_peri_reg_bits(reg: u32, bitmap: u32, value: u32, shift: u32) {
        unsafe {
            (reg as *mut u32).write_volatile(
                ((reg as *mut u32).read_volatile() & !(bitmap << shift))
                    | ((value & bitmap) << shift),
            );
        }
    }

    #[inline(always)]
    fn write_peri_reg(reg: u32, val: u32) {
        unsafe {
            (reg as *mut u32).write_volatile(val);
        }
    }
}