aboutsummaryrefslogtreecommitdiff
path: root/src/flash/nor/stmqspi.c
blob: a1e1d34116a243473e0be2782dbed70b7400e29e (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
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
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
// SPDX-License-Identifier: GPL-2.0-or-later

/***************************************************************************
 *   Copyright (C) 2016 - 2019 by Andreas Bolsch                           *
 *   andreas.bolsch@mni.thm.de                                             *
 *                                                                         *
 *   Copyright (C) 2010 by Antonio Borneo                                  *
 *   borneo.antonio@gmail.com                                              *
 ***************************************************************************/

/* STM QuadSPI (QSPI) and OctoSPI (OCTOSPI) controller are SPI bus controllers
 * specifically designed for SPI memories.
 * Two working modes are available:
 * - indirect mode: the SPI is controlled by SW. Any custom commands can be sent
 *   on the bus.
 * - memory mapped mode: the SPI is under QSPI/OCTOSPI control. Memory content
 *   is directly accessible in CPU memory space. CPU can read and execute from
 *   memory (but not write to) */

/* ATTENTION:
 * To have flash mapped in CPU memory space, the QSPI/OCTOSPI controller
 * has to be in "memory mapped mode". This requires following constraints:
 * 1) The command "reset init" has to initialize QSPI/OCTOSPI controller and put
 *    it in memory mapped mode;
 * 2) every command in this file has to return to prompt in memory mapped mode. */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "imp.h"
#include <helper/binarybuffer.h>
#include <helper/bits.h>
#include <helper/time_support.h>
#include <target/algorithm.h>
#include <target/armv7m.h>
#include <target/image.h>
#include "stmqspi.h"
#include "sfdp.h"

/* deprecated */
#undef SPIFLASH_READ
#undef SPIFLASH_PAGE_PROGRAM

/* saved mode settings */
#define QSPI_MODE (stmqspi_info->saved_ccr & \
	(0xF0000000U | QSPI_DCYC_MASK | QSPI_4LINE_MODE | QSPI_ALTB_MODE | QSPI_ADDR4))

/* saved read mode settings but indirect read instead of memory mapped
 * in particular, use the dummy cycle setting from this saved setting */
#define	QSPI_CCR_READ (QSPI_READ_MODE | (stmqspi_info->saved_ccr & \
	(0xF0000000U | QSPI_DCYC_MASK | QSPI_4LINE_MODE | QSPI_ALTB_MODE | QSPI_ADDR4 | 0xFF)))

/* QSPI_CCR for various other commands, these never use dummy cycles nor alternate bytes */
#define	QSPI_CCR_READ_STATUS \
	((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB) | \
	(QSPI_READ_MODE | SPIFLASH_READ_STATUS))

#define	QSPI_CCR_READ_ID \
	((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB) | \
	(QSPI_READ_MODE | SPIFLASH_READ_ID))

#define	QSPI_CCR_READ_MID \
	((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB) | \
	(QSPI_READ_MODE | SPIFLASH_READ_MID))

/* always use 3-byte addresses for read SFDP */
#define	QSPI_CCR_READ_SFDP \
	((QSPI_MODE & ~QSPI_DCYC_MASK & ~QSPI_ADDR4 & QSPI_NO_ALTB) | \
	(QSPI_READ_MODE | QSPI_ADDR3 | SPIFLASH_READ_SFDP))

#define QSPI_CCR_WRITE_ENABLE \
	((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB & QSPI_NO_DATA) | \
	(QSPI_WRITE_MODE | SPIFLASH_WRITE_ENABLE))

#define QSPI_CCR_SECTOR_ERASE \
	((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ALTB & QSPI_NO_DATA) | \
	(QSPI_WRITE_MODE | stmqspi_info->dev.erase_cmd))

#define QSPI_CCR_MASS_ERASE \
	((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ADDR & QSPI_NO_ALTB & QSPI_NO_DATA) | \
	(QSPI_WRITE_MODE | stmqspi_info->dev.chip_erase_cmd))

#define QSPI_CCR_PAGE_PROG \
	((QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ALTB) | \
	(QSPI_WRITE_MODE | stmqspi_info->dev.pprog_cmd))

/* saved mode settings */
#define OCTOSPI_MODE (stmqspi_info->saved_cr & 0xCFFFFFFF)

#define OPI_MODE ((stmqspi_info->saved_ccr & OCTOSPI_ISIZE_MASK) != 0)

#define OCTOSPI_MODE_CCR (stmqspi_info->saved_ccr & \
	(0xF0000000U | OCTOSPI_8LINE_MODE | OCTOSPI_ALTB_MODE | OCTOSPI_ADDR4))

/* use saved ccr for read */
#define OCTOSPI_CCR_READ OCTOSPI_MODE_CCR

/* OCTOSPI_CCR for various other commands, these never use alternate bytes	*
 * for READ_STATUS and READ_ID, 4-byte address 0							*
 * 4 dummy cycles must sent in OPI mode when DQS is disabled. However, when	*
 * DQS is enabled, some STM32 devices need at least 6 dummy cycles for		*
 * proper operation, but otherwise the actual number has no effect!			*
 * E.g. RM0432 Rev. 7 is incorrect regarding this: L4R9 works well with 4	*
 * dummy clocks whereas L4P5 not at all.									*
 */
#define OPI_DUMMY \
	((stmqspi_info->saved_ccr & OCTOSPI_DQSEN) ? 6U : 4U)

#define	OCTOSPI_CCR_READ_STATUS \
	((OCTOSPI_MODE_CCR & OCTOSPI_NO_DDTR & \
	(OPI_MODE ? ~0U : OCTOSPI_NO_ADDR) & OCTOSPI_NO_ALTB))

#define	OCTOSPI_CCR_READ_ID \
	((OCTOSPI_MODE_CCR & OCTOSPI_NO_DDTR & \
	(OPI_MODE ? ~0U : OCTOSPI_NO_ADDR) & OCTOSPI_NO_ALTB))

#define	OCTOSPI_CCR_READ_MID OCTOSPI_CCR_READ_ID

/* 4-byte address in octo mode, else 3-byte address for read SFDP */
#define	OCTOSPI_CCR_READ_SFDP(len) \
	((OCTOSPI_MODE_CCR & OCTOSPI_NO_DDTR & ~OCTOSPI_ADDR4 & OCTOSPI_NO_ALTB) | \
	(((len) < 4) ? OCTOSPI_ADDR3 : OCTOSPI_ADDR4))

#define OCTOSPI_CCR_WRITE_ENABLE \
	((OCTOSPI_MODE_CCR & OCTOSPI_NO_ADDR & OCTOSPI_NO_ALTB & OCTOSPI_NO_DATA))

#define OCTOSPI_CCR_SECTOR_ERASE \
	((OCTOSPI_MODE_CCR & OCTOSPI_NO_ALTB & OCTOSPI_NO_DATA))

#define OCTOSPI_CCR_MASS_ERASE \
	((OCTOSPI_MODE_CCR & OCTOSPI_NO_ADDR & OCTOSPI_NO_ALTB & OCTOSPI_NO_DATA))

#define OCTOSPI_CCR_PAGE_PROG \
	((OCTOSPI_MODE_CCR & QSPI_NO_ALTB))

#define SPI_ADSIZE (((stmqspi_info->saved_ccr >> SPI_ADSIZE_POS) & 0x3) + 1)

#define OPI_CMD(cmd) ((OPI_MODE ? ((((uint16_t)(cmd)) << 8) | (~(cmd) & 0xFFU)) : (cmd)))

/* convert uint32_t into 4 uint8_t in little endian byte order */
static inline uint32_t h_to_le_32(uint32_t val)
{
	uint32_t result;

	h_u32_to_le((uint8_t *)&result, val);
	return result;
}

/* Timeout in ms */
#define SPI_CMD_TIMEOUT			(100)
#define SPI_PROBE_TIMEOUT		(100)
#define SPI_MAX_TIMEOUT			(2000)
#define SPI_MASS_ERASE_TIMEOUT	(400000)

struct sector_info {
	uint32_t offset;
	uint32_t size;
	uint32_t result;
};

struct stmqspi_flash_bank {
	bool probed;
	char devname[32];
	bool octo;
	struct flash_device dev;
	uint32_t io_base;
	uint32_t saved_cr;	/* in particular FSEL, DFM bit mask in QUADSPI_CR *AND* OCTOSPI_CR */
	uint32_t saved_ccr; /* different meaning for QUADSPI and OCTOSPI */
	uint32_t saved_tcr;	/* only for OCTOSPI */
	uint32_t saved_ir;	/* only for OCTOSPI */
	unsigned int sfdp_dummy1;	/* number of dummy bytes for SFDP read for flash1 and octo */
	unsigned int sfdp_dummy2;	/* number of dummy bytes for SFDP read for flash2 */
};

static inline int octospi_cmd(struct flash_bank *bank, uint32_t mode,
		uint32_t ccr, uint32_t ir)
{
	struct target *target = bank->target;
	const struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	const uint32_t io_base = stmqspi_info->io_base;

	int retval = target_write_u32(target, io_base + OCTOSPI_CR,
		OCTOSPI_MODE | mode);

	if (retval != ERROR_OK)
		return retval;

	retval = target_write_u32(target, io_base + OCTOSPI_TCR,
		(stmqspi_info->saved_tcr & ~OCTOSPI_DCYC_MASK) |
		((OPI_MODE && (mode == OCTOSPI_READ_MODE)) ?
		(OPI_DUMMY << OCTOSPI_DCYC_POS) : 0));

	if (retval != ERROR_OK)
		return retval;

	retval = target_write_u32(target, io_base + OCTOSPI_CCR, ccr);

	if (retval != ERROR_OK)
		return retval;

	return target_write_u32(target, io_base + OCTOSPI_IR, OPI_CMD(ir));
}

FLASH_BANK_COMMAND_HANDLER(stmqspi_flash_bank_command)
{
	struct stmqspi_flash_bank *stmqspi_info;
	uint32_t io_base;

	LOG_DEBUG("%s", __func__);

	if (CMD_ARGC < 7)
		return ERROR_COMMAND_SYNTAX_ERROR;

	COMMAND_PARSE_NUMBER(u32, CMD_ARGV[6], io_base);

	stmqspi_info = malloc(sizeof(struct stmqspi_flash_bank));
	if (!stmqspi_info) {
		LOG_ERROR("not enough memory");
		return ERROR_FAIL;
	}

	bank->driver_priv = stmqspi_info;
	stmqspi_info->sfdp_dummy1 = 0;
	stmqspi_info->sfdp_dummy2 = 0;
	stmqspi_info->probed = false;
	stmqspi_info->io_base = io_base;

	return ERROR_OK;
}

/* Poll busy flag */
/* timeout in ms */
static int poll_busy(struct flash_bank *bank, int timeout)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	uint32_t io_base = stmqspi_info->io_base;
	long long endtime;

	endtime = timeval_ms() + timeout;
	do {
		uint32_t spi_sr;
		int retval = target_read_u32(target, io_base + SPI_SR, &spi_sr);

		if (retval != ERROR_OK)
			return retval;

		if ((spi_sr & BIT(SPI_BUSY)) == 0) {
			/* Clear transmit finished flag */
			return target_write_u32(target, io_base + SPI_FCR, BIT(SPI_TCF));
		} else
			LOG_DEBUG("busy: 0x%08X", spi_sr);
		alive_sleep(1);
	} while (timeval_ms() < endtime);

	LOG_ERROR("Timeout while polling BUSY");
	return ERROR_FLASH_OPERATION_FAILED;
}

static int stmqspi_abort(struct flash_bank *bank)
{
	struct target *target = bank->target;
	const struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	const uint32_t io_base = stmqspi_info->io_base;
	uint32_t cr;

	int retval = target_read_u32(target, io_base + SPI_CR, &cr);

	if (retval != ERROR_OK)
		cr = 0;

	return target_write_u32(target, io_base + SPI_CR, cr | BIT(SPI_ABORT));
}

/* Set to memory-mapped mode, e.g. after an error */
static int set_mm_mode(struct flash_bank *bank)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	uint32_t io_base = stmqspi_info->io_base;
	int retval;

	/* Reset Address register bits 0 and 1, see various errata sheets */
	retval = target_write_u32(target, io_base + SPI_AR, 0x0);
	if (retval != ERROR_OK)
		return retval;

	/* Abort any previous operation */
	retval = stmqspi_abort(bank);
	if (retval != ERROR_OK)
		return retval;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		return retval;

	/* Finally switch to memory mapped mode */
	if (IS_OCTOSPI) {
		retval = target_write_u32(target, io_base + OCTOSPI_CR,
			OCTOSPI_MODE | OCTOSPI_MM_MODE);
		if (retval == ERROR_OK)
			retval = target_write_u32(target, io_base + OCTOSPI_CCR,
				stmqspi_info->saved_ccr);
		if (retval == ERROR_OK)
			retval = target_write_u32(target, io_base + OCTOSPI_TCR,
				stmqspi_info->saved_tcr);
		if (retval == ERROR_OK)
			retval = target_write_u32(target, io_base + OCTOSPI_IR,
				stmqspi_info->saved_ir);
	} else {
		retval = target_write_u32(target, io_base + QSPI_CR,
			stmqspi_info->saved_cr);
		if (retval == ERROR_OK)
			retval = target_write_u32(target, io_base + QSPI_CCR,
				stmqspi_info->saved_ccr);
	}
	return retval;
}

/* Read the status register of the external SPI flash chip(s). */
static int read_status_reg(struct flash_bank *bank, uint16_t *status)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	uint32_t io_base = stmqspi_info->io_base;
	uint8_t data;
	int count, retval;

	/* Abort any previous operation */
	retval = stmqspi_abort(bank);
	if (retval != ERROR_OK)
		return retval;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		goto err;

	/* Read always two (for DTR mode) bytes per chip */
	count = 2;
	retval = target_write_u32(target, io_base + SPI_DLR,
		((stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 2 * count : count) - 1);
	if (retval != ERROR_OK)
		goto err;

	/* Read status */
	if (IS_OCTOSPI) {
		retval = octospi_cmd(bank, OCTOSPI_READ_MODE, OCTOSPI_CCR_READ_STATUS,
			SPIFLASH_READ_STATUS);
		if (OPI_MODE) {
			/* Dummy address 0, only required for 8-line mode */
			retval = target_write_u32(target, io_base + SPI_AR, 0);
			if (retval != ERROR_OK)
				goto err;
		}
	} else
		retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_STATUS);
	if (retval != ERROR_OK)
		goto err;

	*status = 0;

	/* for debugging only */
	uint32_t dummy;
	(void)target_read_u32(target, io_base + SPI_SR, &dummy);

	for ( ; count > 0; --count) {
		if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH)))
			!= BIT(SPI_FSEL_FLASH)) {
			/* get status of flash 1 in dual mode or flash 1 only mode */
			retval = target_read_u8(target, io_base + SPI_DR, &data);
			if (retval != ERROR_OK)
				goto err;
			*status |= data;
		}

		if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0) {
			/* get status of flash 2 in dual mode or flash 2 only mode */
			retval = target_read_u8(target, io_base + SPI_DR, &data);
			if (retval != ERROR_OK)
				goto err;
			*status |= ((uint16_t)data) << 8;
		}
	}

	LOG_DEBUG("flash status regs: 0x%04" PRIx16, *status);

err:
	return retval;
}

/* check for WIP (write in progress) bit(s) in status register(s) */
/* timeout in ms */
static int wait_till_ready(struct flash_bank *bank, int timeout)
{
	uint16_t status;
	int retval;
	long long endtime;

	endtime = timeval_ms() + timeout;
	do {
		/* Read flash status register(s) */
		retval = read_status_reg(bank, &status);
		if (retval != ERROR_OK)
			return retval;

		if ((status & ((SPIFLASH_BSY_BIT << 8) | SPIFLASH_BSY_BIT)) == 0)
			return retval;
		alive_sleep(25);
	} while (timeval_ms() < endtime);

	LOG_ERROR("timeout");
	return ERROR_FLASH_OPERATION_FAILED;
}

/* Send "write enable" command to SPI flash chip(s). */
static int qspi_write_enable(struct flash_bank *bank)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	uint32_t io_base = stmqspi_info->io_base;
	uint16_t status;
	int retval;

	/* Abort any previous operation */
	retval = stmqspi_abort(bank);
	if (retval != ERROR_OK)
		return retval;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		goto err;

	/* Send write enable command */
	if (IS_OCTOSPI) {
		retval = octospi_cmd(bank, OCTOSPI_WRITE_MODE, OCTOSPI_CCR_WRITE_ENABLE,
			SPIFLASH_WRITE_ENABLE);
		if (OPI_MODE) {
			/* Dummy address 0, only required for 8-line mode */
			retval = target_write_u32(target, io_base + SPI_AR, 0);
			if (retval != ERROR_OK)
				goto err;
		}
	} else
		retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_WRITE_ENABLE);
	if (retval != ERROR_OK)
		goto err;


	/* Wait for transmit of command completed */
	poll_busy(bank, SPI_CMD_TIMEOUT);
	if (retval != ERROR_OK)
		goto err;

	/* Read flash status register */
	retval = read_status_reg(bank, &status);
	if (retval != ERROR_OK)
		goto err;

	/* Check write enabled for flash 1 */
	if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH)))
		!= BIT(SPI_FSEL_FLASH))
		if ((status & (SPIFLASH_WE_BIT | SPIFLASH_BSY_BIT)) != SPIFLASH_WE_BIT) {
			LOG_ERROR("Cannot write enable flash1. Status=0x%02x",
				status & 0xFFU);
			return ERROR_FLASH_OPERATION_FAILED;
		}

	/* Check write enabled for flash 2 */
	status >>= 8;
	if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0)
		if ((status & (SPIFLASH_WE_BIT | SPIFLASH_BSY_BIT)) != SPIFLASH_WE_BIT) {
			LOG_ERROR("Cannot write enable flash2. Status=0x%02x",
				status & 0xFFU);
			return ERROR_FLASH_OPERATION_FAILED;
		}

err:
	return retval;
}

COMMAND_HANDLER(stmqspi_handle_mass_erase_command)
{
	struct target *target = NULL;
	struct flash_bank *bank;
	struct stmqspi_flash_bank *stmqspi_info;
	struct duration bench;
	uint32_t io_base;
	uint16_t status;
	unsigned int sector;
	int retval;

	LOG_DEBUG("%s", __func__);

	if (CMD_ARGC != 1)
		return ERROR_COMMAND_SYNTAX_ERROR;

	retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
	if (retval != ERROR_OK)
		return retval;

	stmqspi_info = bank->driver_priv;
	target = bank->target;

	if (target->state != TARGET_HALTED) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	if (!(stmqspi_info->probed)) {
		LOG_ERROR("Flash bank not probed");
		return ERROR_FLASH_BANK_NOT_PROBED;
	}

	if (stmqspi_info->dev.chip_erase_cmd == 0x00) {
		LOG_ERROR("Mass erase not available for this device");
		return ERROR_FLASH_OPER_UNSUPPORTED;
	}

	for (sector = 0; sector < bank->num_sectors; sector++) {
		if (bank->sectors[sector].is_protected) {
			LOG_ERROR("Flash sector %u protected", sector);
			return ERROR_FLASH_PROTECTED;
		}
	}

	io_base = stmqspi_info->io_base;
	duration_start(&bench);

	retval = qspi_write_enable(bank);
	if (retval != ERROR_OK)
		goto err;

	/* Send Mass Erase command */
	if (IS_OCTOSPI)
		retval = octospi_cmd(bank, OCTOSPI_WRITE_MODE, OCTOSPI_CCR_MASS_ERASE,
			stmqspi_info->dev.chip_erase_cmd);
	else
		retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_MASS_ERASE);
	if (retval != ERROR_OK)
		goto err;

	/* Wait for transmit of command completed */
	poll_busy(bank, SPI_CMD_TIMEOUT);
	if (retval != ERROR_OK)
		goto err;

	/* Read flash status register(s) */
	retval = read_status_reg(bank, &status);
	if (retval != ERROR_OK)
		goto err;

	/* Check for command in progress for flash 1 */
	if (((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH)))
		!= BIT(SPI_FSEL_FLASH)) && ((status & SPIFLASH_BSY_BIT) == 0) &&
		((status & SPIFLASH_WE_BIT) != 0)) {
		LOG_ERROR("Mass erase command not accepted by flash1. Status=0x%02x",
			status & 0xFFU);
		retval = ERROR_FLASH_OPERATION_FAILED;
		goto err;
	}

	/* Check for command in progress for flash 2 */
	status >>= 8;
	if (((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0) &&
		((status & SPIFLASH_BSY_BIT) == 0) &&
		((status & SPIFLASH_WE_BIT) != 0)) {
		LOG_ERROR("Mass erase command not accepted by flash2. Status=0x%02x",
			status & 0xFFU);
		retval = ERROR_FLASH_OPERATION_FAILED;
		goto err;
	}

	/* Poll WIP for end of self timed Sector Erase cycle */
	retval = wait_till_ready(bank, SPI_MASS_ERASE_TIMEOUT);

	duration_measure(&bench);
	if (retval == ERROR_OK)
		command_print(CMD, "stmqspi mass erase completed in %fs (%0.3f KiB/s)",
			duration_elapsed(&bench),
			duration_kbps(&bench, bank->size));
	else
		command_print(CMD, "stmqspi mass erase not completed even after %fs",
			duration_elapsed(&bench));

err:
	/* Switch to memory mapped mode before return to prompt */
	set_mm_mode(bank);

	return retval;
}

static int log2u(uint32_t word)
{
	int result;

	for (result = 0; (unsigned int) result < sizeof(uint32_t) * CHAR_BIT; result++)
		if (word == BIT(result))
			return result;

	return -1;
}

COMMAND_HANDLER(stmqspi_handle_set)
{
	struct flash_bank *bank = NULL;
	struct target *target = NULL;
	struct stmqspi_flash_bank *stmqspi_info = NULL;
	struct flash_sector *sectors = NULL;
	uint32_t io_base;
	unsigned int index = 0, dual, fsize;
	int retval;

	LOG_DEBUG("%s", __func__);

	/* chip_erase_cmd, sectorsize and erase_cmd are optional */
	if ((CMD_ARGC < 7) || (CMD_ARGC > 10))
		return ERROR_COMMAND_SYNTAX_ERROR;

	retval = CALL_COMMAND_HANDLER(flash_command_get_bank, index++, &bank);
	if (retval != ERROR_OK)
		return retval;

	target = bank->target;
	stmqspi_info = bank->driver_priv;
	dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;

	/* invalidate all flash device info */
	if (stmqspi_info->probed)
		free(bank->sectors);
	bank->size = 0;
	bank->num_sectors = 0;
	bank->sectors = NULL;
	stmqspi_info->sfdp_dummy1 = 0;
	stmqspi_info->sfdp_dummy2 = 0;
	stmqspi_info->probed = false;
	memset(&stmqspi_info->dev, 0, sizeof(stmqspi_info->dev));
	stmqspi_info->dev.name = "unknown";

	strncpy(stmqspi_info->devname, CMD_ARGV[index++], sizeof(stmqspi_info->devname) - 1);
	stmqspi_info->devname[sizeof(stmqspi_info->devname) - 1] = '\0';

	COMMAND_PARSE_NUMBER(u32, CMD_ARGV[index++], stmqspi_info->dev.size_in_bytes);
	if (log2u(stmqspi_info->dev.size_in_bytes) < 8) {
		command_print(CMD, "stmqspi: device size must be 2^n with n >= 8");
		return ERROR_COMMAND_ARGUMENT_INVALID;
	}

	COMMAND_PARSE_NUMBER(u32, CMD_ARGV[index++], stmqspi_info->dev.pagesize);
	if (stmqspi_info->dev.pagesize > stmqspi_info->dev.size_in_bytes ||
		(log2u(stmqspi_info->dev.pagesize) < 0)) {
		command_print(CMD, "stmqspi: page size must be 2^n and <= device size");
		return ERROR_COMMAND_ARGUMENT_INVALID;
	}

	COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.read_cmd);
	if ((stmqspi_info->dev.read_cmd != 0x03) &&
		(stmqspi_info->dev.read_cmd != 0x13)) {
		command_print(CMD, "stmqspi: only 0x03/0x13 READ cmd allowed");
		return ERROR_COMMAND_ARGUMENT_INVALID;
	}

	COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.qread_cmd);
	if ((stmqspi_info->dev.qread_cmd != 0x00) &&
		(stmqspi_info->dev.qread_cmd != 0x0B) &&
		(stmqspi_info->dev.qread_cmd != 0x0C) &&
		(stmqspi_info->dev.qread_cmd != 0x3B) &&
		(stmqspi_info->dev.qread_cmd != 0x3C) &&
		(stmqspi_info->dev.qread_cmd != 0x6B) &&
		(stmqspi_info->dev.qread_cmd != 0x6C) &&
		(stmqspi_info->dev.qread_cmd != 0xBB) &&
		(stmqspi_info->dev.qread_cmd != 0xBC) &&
		(stmqspi_info->dev.qread_cmd != 0xEB) &&
		(stmqspi_info->dev.qread_cmd != 0xEC) &&
		(stmqspi_info->dev.qread_cmd != 0xEE)) {
		command_print(CMD, "stmqspi: only 0x0B/0x0C/0x3B/0x3C/"
			"0x6B/0x6C/0xBB/0xBC/0xEB/0xEC/0xEE QREAD allowed");
		return ERROR_COMMAND_ARGUMENT_INVALID;
	}

	COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.pprog_cmd);
	if ((stmqspi_info->dev.pprog_cmd != 0x02) &&
		(stmqspi_info->dev.pprog_cmd != 0x12) &&
		(stmqspi_info->dev.pprog_cmd != 0x32)) {
		command_print(CMD, "stmqspi: only 0x02/0x12/0x32 PPRG cmd allowed");
		return ERROR_COMMAND_ARGUMENT_INVALID;
	}

	if (index < CMD_ARGC)
		COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.chip_erase_cmd);
	else
		stmqspi_info->dev.chip_erase_cmd = 0x00;

	if (index < CMD_ARGC) {
		COMMAND_PARSE_NUMBER(u32, CMD_ARGV[index++], stmqspi_info->dev.sectorsize);
		if ((stmqspi_info->dev.sectorsize > stmqspi_info->dev.size_in_bytes) ||
			(stmqspi_info->dev.sectorsize < stmqspi_info->dev.pagesize) ||
			(log2u(stmqspi_info->dev.sectorsize) < 0)) {
			command_print(CMD, "stmqspi: sector size must be 2^n and <= device size");
			return ERROR_COMMAND_ARGUMENT_INVALID;
		}

		if (index < CMD_ARGC)
			COMMAND_PARSE_NUMBER(u8, CMD_ARGV[index++], stmqspi_info->dev.erase_cmd);
		else
			return ERROR_COMMAND_SYNTAX_ERROR;
	} else {
		/* no sector size / sector erase cmd given, treat whole bank as a single sector */
		stmqspi_info->dev.erase_cmd = 0x00;
		stmqspi_info->dev.sectorsize = stmqspi_info->dev.size_in_bytes;
	}

	/* set correct size value */
	bank->size = stmqspi_info->dev.size_in_bytes << dual;

	io_base = stmqspi_info->io_base;

	uint32_t dcr;
	retval = target_read_u32(target, io_base + SPI_DCR, &dcr);
	if (retval != ERROR_OK)
		return retval;
	fsize = (dcr >> SPI_FSIZE_POS) & (BIT(SPI_FSIZE_LEN) - 1);

	LOG_DEBUG("FSIZE = 0x%04x", fsize);
	if (bank->size == BIT(fsize + 1))
		LOG_DEBUG("FSIZE in DCR(1) matches actual capacity. Beware of silicon bug in H7, L4+, MP1.");
	else if (bank->size == BIT(fsize + 0))
		LOG_DEBUG("FSIZE in DCR(1) is off by one regarding actual capacity. Fix for silicon bug?");
	else
		LOG_ERROR("FSIZE in DCR(1) doesn't match actual capacity.");

	/* create and fill sectors array */
	bank->num_sectors =
		stmqspi_info->dev.size_in_bytes / stmqspi_info->dev.sectorsize;
	sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
	if (!sectors) {
		LOG_ERROR("not enough memory");
		return ERROR_FAIL;
	}

	for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
		sectors[sector].offset = sector * (stmqspi_info->dev.sectorsize << dual);
		sectors[sector].size = (stmqspi_info->dev.sectorsize << dual);
		sectors[sector].is_erased = -1;
		sectors[sector].is_protected = 0;
	}

	bank->sectors = sectors;
	stmqspi_info->dev.name = stmqspi_info->devname;
	if (stmqspi_info->dev.size_in_bytes / 4096)
		LOG_INFO("flash \'%s\' id = unknown\nchip size = %" PRIu32 " KiB,"
			" bank size = %" PRIu32 " KiB", stmqspi_info->dev.name,
			stmqspi_info->dev.size_in_bytes / 1024,
			(stmqspi_info->dev.size_in_bytes / 1024) << dual);
	else
		LOG_INFO("flash \'%s\' id = unknown\nchip size = %" PRIu32 " B,"
			" bank size = %" PRIu32 " B", stmqspi_info->dev.name,
			stmqspi_info->dev.size_in_bytes,
			stmqspi_info->dev.size_in_bytes << dual);

	stmqspi_info->probed = true;

	return ERROR_OK;
}

COMMAND_HANDLER(stmqspi_handle_cmd)
{
	struct target *target = NULL;
	struct flash_bank *bank;
	struct stmqspi_flash_bank *stmqspi_info = NULL;
	uint32_t io_base, addr;
	uint8_t num_write, num_read, cmd_byte, data;
	unsigned int count;
	const int max = 21;
	char temp[4], output[(2 + max + 256) * 3 + 8];
	int retval;

	LOG_DEBUG("%s", __func__);

	if (CMD_ARGC < 3)
		return ERROR_COMMAND_SYNTAX_ERROR;

	num_write = CMD_ARGC - 2;
	if (num_write > max) {
		LOG_ERROR("at most %d bytes may be sent", max);
		return ERROR_COMMAND_ARGUMENT_INVALID;
	}

	retval = CALL_COMMAND_HANDLER(flash_command_get_bank, 0, &bank);
	if (retval != ERROR_OK)
		return retval;

	target = bank->target;
	stmqspi_info = bank->driver_priv;
	io_base = stmqspi_info->io_base;

	if (target->state != TARGET_HALTED) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	COMMAND_PARSE_NUMBER(u8, CMD_ARGV[1], num_read);
	COMMAND_PARSE_NUMBER(u8, CMD_ARGV[2], cmd_byte);

	if (num_read == 0) {
		/* nothing to read, then one command byte and for dual flash
		 * an *even* number of data bytes to follow */
		if (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) {
			if ((num_write & 1) == 0) {
				LOG_ERROR("number of data bytes to write must be even in dual mode");
				return ERROR_COMMAND_ARGUMENT_INVALID;
			}
		}
	} else {
		/* read mode, one command byte and up to four following address bytes */
		if (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) {
			if ((num_read & 1) != 0) {
				LOG_ERROR("number of bytes to read must be even in dual mode");
				return ERROR_COMMAND_ARGUMENT_INVALID;
			}
		}
		if ((num_write < 1) || (num_write > 5)) {
			LOG_ERROR("one cmd and up to four addr bytes must be send when reading");
			return ERROR_COMMAND_ARGUMENT_INVALID;
		}
	}

	/* Abort any previous operation */
	retval = stmqspi_abort(bank);
	if (retval != ERROR_OK)
		return retval;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		return retval;

	/* send command byte */
	snprintf(output, sizeof(output), "spi: %02x ", cmd_byte);
	if (num_read == 0) {
		/* write, send cmd byte */
		retval = target_write_u32(target, io_base + SPI_DLR, ((uint32_t)num_write) - 2);
		if (retval != ERROR_OK)
			goto err;

		if (IS_OCTOSPI)
			retval = octospi_cmd(bank, OCTOSPI_WRITE_MODE,
				(OCTOSPI_MODE_CCR & OCTOSPI_NO_ALTB & OCTOSPI_NO_ADDR &
				((num_write == 1) ? OCTOSPI_NO_DATA : ~0U)), cmd_byte);
		else
			retval = target_write_u32(target, io_base + QSPI_CCR,
				(QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ALTB & QSPI_NO_ADDR &
				((num_write == 1) ? QSPI_NO_DATA : ~0U)) |
				(QSPI_WRITE_MODE | cmd_byte));
		if (retval != ERROR_OK)
			goto err;

		/* send additional data bytes */
		for (count = 3; count < CMD_ARGC; count++) {
			COMMAND_PARSE_NUMBER(u8, CMD_ARGV[count], data);
			snprintf(temp, sizeof(temp), "%02" PRIx8 " ", data);
			retval = target_write_u8(target, io_base + SPI_DR, data);
			if (retval != ERROR_OK)
				goto err;
			strncat(output, temp, sizeof(output) - strlen(output) - 1);
		}
		strncat(output, "-> ", sizeof(output) - strlen(output) - 1);
	} else {
		/* read, pack additional bytes into address */
		addr = 0;
		for (count = 3; count < CMD_ARGC; count++) {
			COMMAND_PARSE_NUMBER(u8, CMD_ARGV[count], data);
			snprintf(temp, sizeof(temp), "%02" PRIx8 " ", data);
			addr = (addr << 8) | data;
			strncat(output, temp, sizeof(output) - strlen(output) - 1);
		}
		strncat(output, "-> ", sizeof(output) - strlen(output) - 1);

		/* send cmd byte, if ADMODE indicates no address, this already triggers command */
		retval = target_write_u32(target, io_base + SPI_DLR, ((uint32_t)num_read) - 1);
		if (retval != ERROR_OK)
			goto err;
		if (IS_OCTOSPI)
			retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
				(OCTOSPI_MODE_CCR & OCTOSPI_NO_DDTR & OCTOSPI_NO_ALTB & ~OCTOSPI_ADDR4 &
					((num_write == 1) ? OCTOSPI_NO_ADDR : ~0U)) |
				(((num_write - 2) & 0x3U) << SPI_ADSIZE_POS), cmd_byte);
		else
			retval = target_write_u32(target, io_base + QSPI_CCR,
				(QSPI_MODE & ~QSPI_DCYC_MASK & QSPI_NO_ALTB & ~QSPI_ADDR4 &
					((num_write == 1) ? QSPI_NO_ADDR : ~0U)) |
				((QSPI_READ_MODE | (((num_write - 2) & 0x3U) << SPI_ADSIZE_POS) | cmd_byte)));
		if (retval != ERROR_OK)
			goto err;

		if (num_write > 1) {
			/* if ADMODE indicates address required, only the write to AR triggers command */
			retval = target_write_u32(target, io_base + SPI_AR, addr);
			if (retval != ERROR_OK)
				goto err;
		}

		/* read response bytes */
		for ( ; num_read > 0; num_read--) {
			retval = target_read_u8(target, io_base + SPI_DR, &data);
			if (retval != ERROR_OK)
				goto err;
			snprintf(temp, sizeof(temp), "%02" PRIx8 " ", data);
			strncat(output, temp, sizeof(output) - strlen(output) - 1);
		}
	}
	command_print(CMD, "%s", output);

err:
	/* Switch to memory mapped mode before return to prompt */
	set_mm_mode(bank);

	return retval;
}

static int qspi_erase_sector(struct flash_bank *bank, unsigned int sector)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	uint32_t io_base = stmqspi_info->io_base;
	uint16_t status;
	int retval;

	retval = qspi_write_enable(bank);
	if (retval != ERROR_OK)
		goto err;

	/* Send Sector Erase command */
	if (IS_OCTOSPI)
		retval = octospi_cmd(bank, OCTOSPI_WRITE_MODE, OCTOSPI_CCR_SECTOR_ERASE,
			stmqspi_info->dev.erase_cmd);
	else
		retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_SECTOR_ERASE);
	if (retval != ERROR_OK)
		goto err;

	/* Address is sector offset, this write initiates command transmission */
	retval = target_write_u32(target, io_base + SPI_AR, bank->sectors[sector].offset);
	if (retval != ERROR_OK)
		goto err;

	/* Wait for transmit of command completed */
	poll_busy(bank, SPI_CMD_TIMEOUT);
	if (retval != ERROR_OK)
		goto err;

	/* Read flash status register(s) */
	retval = read_status_reg(bank, &status);
	if (retval != ERROR_OK)
		goto err;

	LOG_DEBUG("erase status regs: 0x%04" PRIx16, status);

	/* Check for command in progress for flash 1 */
	/* If BSY and WE are already cleared the erase did probably complete already */
	if (((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH)))
		!= BIT(SPI_FSEL_FLASH)) && ((status & SPIFLASH_BSY_BIT) == 0) &&
		((status & SPIFLASH_WE_BIT) != 0)) {
		LOG_ERROR("Sector erase command not accepted by flash1. Status=0x%02x",
			status & 0xFFU);
		retval = ERROR_FLASH_OPERATION_FAILED;
		goto err;
	}

	/* Check for command in progress for flash 2 */
	/* If BSY and WE are already cleared the erase did probably complete already */
	status >>= 8;
	if (((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0) &&
		((status & SPIFLASH_BSY_BIT) == 0) &&
		((status & SPIFLASH_WE_BIT) != 0)) {
		LOG_ERROR("Sector erase command not accepted by flash2. Status=0x%02x",
			status & 0xFFU);
		retval = ERROR_FLASH_OPERATION_FAILED;
		goto err;
	}

	/* Erase takes a long time, so some sort of progress message is a good idea */
	LOG_DEBUG("erasing sector %4u", sector);

	/* Poll WIP for end of self timed Sector Erase cycle */
	retval = wait_till_ready(bank, SPI_MAX_TIMEOUT);

err:
	return retval;
}

static int stmqspi_erase(struct flash_bank *bank, unsigned int first, unsigned int last)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	unsigned int sector;
	int retval = ERROR_OK;

	LOG_DEBUG("%s: from sector %u to sector %u", __func__, first, last);

	if (target->state != TARGET_HALTED) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	if (!(stmqspi_info->probed)) {
		LOG_ERROR("Flash bank not probed");
		return ERROR_FLASH_BANK_NOT_PROBED;
	}

	if (stmqspi_info->dev.erase_cmd == 0x00) {
		LOG_ERROR("Sector erase not available for this device");
		return ERROR_FLASH_OPER_UNSUPPORTED;
	}

	if ((last < first) || (last >= bank->num_sectors)) {
		LOG_ERROR("Flash sector invalid");
		return ERROR_FLASH_SECTOR_INVALID;
	}

	for (sector = first; sector <= last; sector++) {
		if (bank->sectors[sector].is_protected) {
			LOG_ERROR("Flash sector %u protected", sector);
			return ERROR_FLASH_PROTECTED;
		}
	}

	for (sector = first; sector <= last; sector++) {
		retval = qspi_erase_sector(bank, sector);
		if (retval != ERROR_OK)
			break;
		alive_sleep(10);
		keep_alive();
	}

	if (retval != ERROR_OK)
		LOG_ERROR("Flash sector_erase failed on sector %u", sector);

	/* Switch to memory mapped mode before return to prompt */
	set_mm_mode(bank);

	return retval;
}

static int stmqspi_protect(struct flash_bank *bank, int set,
	unsigned int first, unsigned int last)
{
	unsigned int sector;

	for (sector = first; sector <= last; sector++)
		bank->sectors[sector].is_protected = set;

	if (set)
		LOG_WARNING("setting soft protection only, not related to flash's hardware write protection");

	return ERROR_OK;
}

/* Check whether flash is blank */
static int stmqspi_blank_check(struct flash_bank *bank)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	struct duration bench;
	struct reg_param reg_params[2];
	struct armv7m_algorithm armv7m_info;
	struct working_area *algorithm;
	const uint8_t *code;
	struct sector_info erase_check_info;
	uint32_t codesize, maxsize, result, exit_point;
	unsigned int count, index, num_sectors, sector;
	int retval;
	const uint32_t erased = 0x00FF;

	if (target->state != TARGET_HALTED) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	if (!(stmqspi_info->probed)) {
		LOG_ERROR("Flash bank not probed");
		return ERROR_FLASH_BANK_NOT_PROBED;
	}

	/* Abort any previous operation */
	retval = stmqspi_abort(bank);
	if (retval != ERROR_OK)
		return retval;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		return retval;

	/* see contrib/loaders/flash/stmqspi/stmqspi_erase_check.S for src */
	static const uint8_t stmqspi_erase_check_code[] = {
		#include "../../../contrib/loaders/flash/stmqspi/stmqspi_erase_check.inc"
	};

	/* see contrib/loaders/flash/stmqspi/stmoctospi_erase_check.S for src */
	static const uint8_t stmoctospi_erase_check_code[] = {
		#include "../../../contrib/loaders/flash/stmqspi/stmoctospi_erase_check.inc"
	};

	if (IS_OCTOSPI) {
		code = stmoctospi_erase_check_code;
		codesize = sizeof(stmoctospi_erase_check_code);
	} else {
		code = stmqspi_erase_check_code;
		codesize = sizeof(stmqspi_erase_check_code);
	}

	/* This will overlay the last 4 words of stmqspi/stmoctospi_erase_check_code in target */
	/* for read use the saved settings (memory mapped mode) but indirect read mode */
	uint32_t ccr_buffer[][4] = {
		/* cr  (not used for QSPI)			*
		 * ccr (for both QSPI and OCTOSPI)	*
		 * tcr (not used for QSPI)			*
		 * ir  (not used for QSPI)			*/
		{
			h_to_le_32(OCTOSPI_MODE | OCTOSPI_READ_MODE),
			h_to_le_32(IS_OCTOSPI ? OCTOSPI_CCR_READ : QSPI_CCR_READ),
			h_to_le_32(stmqspi_info->saved_tcr),
			h_to_le_32(stmqspi_info->saved_ir),
		},
	};

	maxsize = target_get_working_area_avail(target);
	if (maxsize < codesize + sizeof(erase_check_info)) {
		LOG_ERROR("Not enough working area, can't do QSPI blank check");
		return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
	}

	num_sectors = (maxsize - codesize) / sizeof(erase_check_info);
	num_sectors = (bank->num_sectors < num_sectors) ? bank->num_sectors : num_sectors;

	if (target_alloc_working_area_try(target,
			codesize + num_sectors * sizeof(erase_check_info), &algorithm) != ERROR_OK) {
		LOG_ERROR("allocating working area failed");
		return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
	};

	/* prepare blank check code, excluding ccr_buffer */
	retval = target_write_buffer(target, algorithm->address,
		codesize - sizeof(ccr_buffer), code);
	if (retval != ERROR_OK)
		goto err;

	/* prepare QSPI/OCTOSPI_CCR register values */
	retval = target_write_buffer(target, algorithm->address
		+ codesize - sizeof(ccr_buffer),
		sizeof(ccr_buffer), (uint8_t *)ccr_buffer);
	if (retval != ERROR_OK)
		goto err;

	duration_start(&bench);

	/* after breakpoint instruction (halfword), one nop (halfword) and
	 * port_buffer till end of code */
	exit_point = algorithm->address + codesize - sizeof(uint32_t) - sizeof(ccr_buffer);

	init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);	/* sector count */
	init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);	/* QSPI/OCTOSPI io_base */

	sector = 0;
	while (sector < bank->num_sectors) {
		/* at most num_sectors sectors to handle in one run */
		count = bank->num_sectors - sector;
		if (count > num_sectors)
			count = num_sectors;

		for (index = 0; index < count; index++) {
			erase_check_info.offset = h_to_le_32(bank->sectors[sector + index].offset);
			erase_check_info.size = h_to_le_32(bank->sectors[sector + index].size);
			erase_check_info.result = h_to_le_32(erased);

			retval = target_write_buffer(target, algorithm->address
				+ codesize + index * sizeof(erase_check_info),
					sizeof(erase_check_info), (uint8_t *)&erase_check_info);
			if (retval != ERROR_OK)
				goto err;
		}

		buf_set_u32(reg_params[0].value, 0, 32, count);
		buf_set_u32(reg_params[1].value, 0, 32, stmqspi_info->io_base);

		armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
		armv7m_info.core_mode = ARM_MODE_THREAD;

		LOG_DEBUG("checking sectors %u to %u", sector, sector + count - 1);
		/* check a block of sectors */
		retval = target_run_algorithm(target,
			0, NULL,
			ARRAY_SIZE(reg_params), reg_params,
			algorithm->address, exit_point,
			count * ((bank->sectors[sector].size >> 6) + 1) + 1000,
			&armv7m_info);
		if (retval != ERROR_OK)
			break;

		for (index = 0; index < count; index++) {
			retval = target_read_buffer(target, algorithm->address
				+ codesize + index * sizeof(erase_check_info),
					sizeof(erase_check_info), (uint8_t *)&erase_check_info);
			if (retval != ERROR_OK)
				goto err;

			if ((erase_check_info.offset != h_to_le_32(bank->sectors[sector + index].offset)) ||
				(erase_check_info.size != 0)) {
				LOG_ERROR("corrupted blank check info");
				goto err;
			}

			/* we need le_32_to_h, but that's the same as h_to_le_32 */
			result = h_to_le_32(erase_check_info.result);
			bank->sectors[sector + index].is_erased = ((result & 0xFF) == 0xFF);
			LOG_DEBUG("Flash sector %u checked: 0x%04x", sector + index, result & 0xFFFFU);
		}
		keep_alive();
		sector += count;
	}

	destroy_reg_param(&reg_params[0]);
	destroy_reg_param(&reg_params[1]);

	duration_measure(&bench);
	LOG_INFO("stmqspi blank checked in %fs (%0.3f KiB/s)", duration_elapsed(&bench),
		duration_kbps(&bench, bank->size));

err:
	target_free_working_area(target, algorithm);

	/* Switch to memory mapped mode before return to prompt */
	set_mm_mode(bank);

	return retval;
}

/* Verify checksum */
static int qspi_verify(struct flash_bank *bank, uint8_t *buffer,
	uint32_t offset, uint32_t count)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	struct reg_param reg_params[4];
	struct armv7m_algorithm armv7m_info;
	struct working_area *algorithm;
	const uint8_t *code;
	uint32_t pagesize, codesize, crc32, result, exit_point;
	int retval;

	/* see contrib/loaders/flash/stmqspi/stmqspi_crc32.S for src */
	static const uint8_t stmqspi_crc32_code[] = {
		#include "../../../contrib/loaders/flash/stmqspi/stmqspi_crc32.inc"
	};

	/* see contrib/loaders/flash/stmqspi/stmoctospi_crc32.S for src */
	static const uint8_t stmoctospi_crc32_code[] = {
		#include "../../../contrib/loaders/flash/stmqspi/stmoctospi_crc32.inc"
	};

	if (IS_OCTOSPI) {
		code = stmoctospi_crc32_code;
		codesize = sizeof(stmoctospi_crc32_code);
	} else {
		code = stmqspi_crc32_code;
		codesize = sizeof(stmqspi_crc32_code);
	}

	/* block size doesn't matter that much here */
	pagesize = stmqspi_info->dev.sectorsize;
	if (pagesize == 0)
		pagesize = stmqspi_info->dev.pagesize;
	if (pagesize == 0)
		pagesize = SPIFLASH_DEF_PAGESIZE;

	/* adjust size according to dual flash mode */
	pagesize = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? pagesize << 1 : pagesize;

	/* This will overlay the last 4 words of stmqspi/stmoctospi_crc32_code in target */
	/* for read use the saved settings (memory mapped mode) but indirect read mode */
	uint32_t ccr_buffer[][4] = {
		/* cr  (not used for QSPI)			*
		 * ccr (for both QSPI and OCTOSPI)	*
		 * tcr (not used for QSPI)			*
		 * ir  (not used for QSPI)			*/
		{
			h_to_le_32(OCTOSPI_MODE | OCTOSPI_READ_MODE),
			h_to_le_32(IS_OCTOSPI ? OCTOSPI_CCR_READ : QSPI_CCR_READ),
			h_to_le_32(stmqspi_info->saved_tcr),
			h_to_le_32(stmqspi_info->saved_ir),
		},
	};

	if (target_alloc_working_area_try(target, codesize, &algorithm) != ERROR_OK) {
		LOG_ERROR("Not enough working area, can't do QSPI verify");
		return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
	};

	/* prepare verify code, excluding ccr_buffer */
	retval = target_write_buffer(target, algorithm->address,
		codesize - sizeof(ccr_buffer), code);
	if (retval != ERROR_OK)
		goto err;

	/* prepare QSPI/OCTOSPI_CCR register values */
	retval = target_write_buffer(target, algorithm->address
		+ codesize - sizeof(ccr_buffer),
		sizeof(ccr_buffer), (uint8_t *)ccr_buffer);
	if (retval != ERROR_OK)
		goto err;

	/* after breakpoint instruction (halfword), one nop (halfword) and
	 * port_buffer till end of code */
	exit_point = algorithm->address + codesize - sizeof(uint32_t) - sizeof(ccr_buffer);

	init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* count (in), crc32 (out) */
	init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);	/* pagesize */
	init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);	/* offset into flash address */
	init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);	/* QSPI/OCTOSPI io_base */

	buf_set_u32(reg_params[0].value, 0, 32, count);
	buf_set_u32(reg_params[1].value, 0, 32, pagesize);
	buf_set_u32(reg_params[2].value, 0, 32, offset);
	buf_set_u32(reg_params[3].value, 0, 32, stmqspi_info->io_base);


	armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
	armv7m_info.core_mode = ARM_MODE_THREAD;

	retval = target_run_algorithm(target,
		0, NULL,
		ARRAY_SIZE(reg_params), reg_params,
		algorithm->address, exit_point,
		(count >> 5) + 1000,
		&armv7m_info);
	keep_alive();

	image_calculate_checksum(buffer, count, &crc32);

	if (retval == ERROR_OK) {
		result = buf_get_u32(reg_params[0].value, 0, 32);
		LOG_DEBUG("addr " TARGET_ADDR_FMT ", len 0x%08" PRIx32 ", crc 0x%08" PRIx32 " 0x%08" PRIx32,
			offset + bank->base, count, ~crc32, result);
		if (~crc32 != result)
			retval = ERROR_FAIL;
	}

	destroy_reg_param(&reg_params[0]);
	destroy_reg_param(&reg_params[1]);
	destroy_reg_param(&reg_params[2]);
	destroy_reg_param(&reg_params[3]);

err:
	target_free_working_area(target, algorithm);

	/* Switch to memory mapped mode before return to prompt */
	set_mm_mode(bank);

	return retval;
}

static int qspi_read_write_block(struct flash_bank *bank, uint8_t *buffer,
	uint32_t offset, uint32_t count, bool write)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	uint32_t io_base = stmqspi_info->io_base;
	struct reg_param reg_params[6];
	struct armv7m_algorithm armv7m_info;
	struct working_area *algorithm;
	uint32_t pagesize, fifo_start, fifosize, remaining;
	uint32_t maxsize, codesize, exit_point;
	const uint8_t *code = NULL;
	unsigned int dual;
	int retval;

	LOG_DEBUG("%s: offset=0x%08" PRIx32 " len=0x%08" PRIx32,
		__func__, offset, count);

	dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;

	/* see contrib/loaders/flash/stmqspi/stmqspi_read.S for src */
	static const uint8_t stmqspi_read_code[] = {
#include "../../../contrib/loaders/flash/stmqspi/stmqspi_read.inc"
	};

	/* see contrib/loaders/flash/stmqspi/stmoctospi_read.S for src */
	static const uint8_t stmoctospi_read_code[] = {
#include "../../../contrib/loaders/flash/stmqspi/stmoctospi_read.inc"
	};

	/* see contrib/loaders/flash/stmqspi/stmqspi_write.S for src */
	static const uint8_t stmqspi_write_code[] = {
#include "../../../contrib/loaders/flash/stmqspi/stmqspi_write.inc"
	};

	/* see contrib/loaders/flash/stmqspi/stmoctospi_write.S for src */
	static const uint8_t stmoctospi_write_code[] = {
#include "../../../contrib/loaders/flash/stmqspi/stmoctospi_write.inc"
	};

	/* This will overlay the last 12 words of stmqspi/stmoctospi_read/write_code in target */
	/* for read use the saved settings (memory mapped mode) but indirect read mode */
	uint32_t ccr_buffer[][4] = {
		/* cr  (not used for QSPI)			*
		 * ccr (for both QSPI and OCTOSPI)	*
		 * tcr (not used for QSPI)			*
		 * ir  (not used for QSPI)			*/
		{
			h_to_le_32(OCTOSPI_MODE | OCTOSPI_READ_MODE),
			h_to_le_32(IS_OCTOSPI ? OCTOSPI_CCR_READ_STATUS : QSPI_CCR_READ_STATUS),
			h_to_le_32((stmqspi_info->saved_tcr & ~OCTOSPI_DCYC_MASK) |
						(OPI_MODE ? (OPI_DUMMY << OCTOSPI_DCYC_POS) : 0)),
			h_to_le_32(OPI_CMD(SPIFLASH_READ_STATUS)),
		},
		{
			h_to_le_32(OCTOSPI_MODE | OCTOSPI_WRITE_MODE),
			h_to_le_32(IS_OCTOSPI ? OCTOSPI_CCR_WRITE_ENABLE : QSPI_CCR_WRITE_ENABLE),
			h_to_le_32(stmqspi_info->saved_tcr & ~OCTOSPI_DCYC_MASK),
			h_to_le_32(OPI_CMD(SPIFLASH_WRITE_ENABLE)),
		},
		{
			h_to_le_32(OCTOSPI_MODE | (write ? OCTOSPI_WRITE_MODE : OCTOSPI_READ_MODE)),
			h_to_le_32(write ? (IS_OCTOSPI ? OCTOSPI_CCR_PAGE_PROG : QSPI_CCR_PAGE_PROG) :
				(IS_OCTOSPI ? OCTOSPI_CCR_READ : QSPI_CCR_READ)),
			h_to_le_32(write ? (stmqspi_info->saved_tcr & ~OCTOSPI_DCYC_MASK) :
				stmqspi_info->saved_tcr),
			h_to_le_32(write ? OPI_CMD(stmqspi_info->dev.pprog_cmd) : stmqspi_info->saved_ir),
		},
	};

	/* force reasonable defaults */
	fifosize = stmqspi_info->dev.sectorsize ?
		stmqspi_info->dev.sectorsize : stmqspi_info->dev.size_in_bytes;

	if (write) {
		if (IS_OCTOSPI) {
			code = stmoctospi_write_code;
			codesize = sizeof(stmoctospi_write_code);
		} else {
			code = stmqspi_write_code;
			codesize = sizeof(stmqspi_write_code);
		}
	} else {
		if (IS_OCTOSPI) {
			code = stmoctospi_read_code;
			codesize = sizeof(stmoctospi_read_code);
		} else {
			code = stmqspi_read_code;
			codesize = sizeof(stmqspi_read_code);
		}
	}

	/* for write, pagesize must be taken into account */
	/* for read, the page size doesn't matter that much */
	pagesize = stmqspi_info->dev.pagesize;
	if (pagesize == 0)
		pagesize = (fifosize <= SPIFLASH_DEF_PAGESIZE) ?
			fifosize : SPIFLASH_DEF_PAGESIZE;

	/* adjust sizes according to dual flash mode */
	pagesize <<= dual;
	fifosize <<= dual;

	/* memory buffer, we assume sectorsize to be a power of 2 times pagesize */
	maxsize = target_get_working_area_avail(target);
	if (maxsize < codesize + 2 * sizeof(uint32_t) + pagesize) {
		LOG_ERROR("not enough working area, can't do QSPI page reads/writes");
		return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
	}

	/* fifo size at most sector size, and multiple of page size */
	maxsize -= (codesize + 2 * sizeof(uint32_t));
	fifosize = ((maxsize < fifosize) ? maxsize : fifosize) & ~(pagesize - 1);

	if (target_alloc_working_area_try(target,
		codesize + 2 * sizeof(uint32_t) + fifosize, &algorithm) != ERROR_OK) {
		LOG_ERROR("allocating working area failed");
		return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
	};

	/* prepare flash write code, excluding ccr_buffer */
	retval = target_write_buffer(target, algorithm->address,
		codesize - sizeof(ccr_buffer), code);
	if (retval != ERROR_OK)
		goto err;

	/* prepare QSPI/OCTOSPI_CCR register values */
	retval = target_write_buffer(target, algorithm->address
		+ codesize - sizeof(ccr_buffer),
		sizeof(ccr_buffer), (uint8_t *)ccr_buffer);
	if (retval != ERROR_OK)
		goto err;

	/* target buffer starts right after flash_write_code, i.e.
	 * wp and rp are implicitly included in buffer!!! */
	fifo_start = algorithm->address + codesize + 2 * sizeof(uint32_t);

	init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* count (in), status (out) */
	init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);	/* pagesize */
	init_reg_param(&reg_params[2], "r2", 32, PARAM_IN_OUT);	/* offset into flash address */
	init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);	/* QSPI/OCTOSPI io_base */
	init_reg_param(&reg_params[4], "r8", 32, PARAM_OUT);	/* fifo start */
	init_reg_param(&reg_params[5], "r9", 32, PARAM_OUT);	/* fifo end + 1 */

	buf_set_u32(reg_params[0].value, 0, 32, count);
	buf_set_u32(reg_params[1].value, 0, 32, pagesize);
	buf_set_u32(reg_params[2].value, 0, 32, offset);
	buf_set_u32(reg_params[3].value, 0, 32, io_base);
	buf_set_u32(reg_params[4].value, 0, 32, fifo_start);
	buf_set_u32(reg_params[5].value, 0, 32, fifo_start + fifosize);

	armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
	armv7m_info.core_mode = ARM_MODE_THREAD;

	/* after breakpoint instruction (halfword), one nop (halfword) and
	 * ccr_buffer follow till end of code */
	exit_point = algorithm->address + codesize
		- (sizeof(ccr_buffer) + sizeof(uint32_t));

	if (write) {
		retval = target_run_flash_async_algorithm(target, buffer, count, 1,
				0, NULL,
				ARRAY_SIZE(reg_params), reg_params,
				algorithm->address + codesize,
				fifosize + 2 * sizeof(uint32_t),
				algorithm->address, exit_point,
				&armv7m_info);
	} else {
		retval = target_run_read_async_algorithm(target, buffer, count, 1,
				0, NULL,
				ARRAY_SIZE(reg_params), reg_params,
				algorithm->address + codesize,
				fifosize + 2 * sizeof(uint32_t),
				algorithm->address, exit_point,
				&armv7m_info);
	}

	remaining = buf_get_u32(reg_params[0].value, 0, 32);
	if ((retval == ERROR_OK) && remaining)
		retval = ERROR_FLASH_OPERATION_FAILED;

	if (retval != ERROR_OK) {
		offset = buf_get_u32(reg_params[2].value, 0, 32);
		LOG_ERROR("flash %s failed at address 0x%" PRIx32 ", remaining 0x%" PRIx32,
			write ? "write" : "read", offset, remaining);
	}

	destroy_reg_param(&reg_params[0]);
	destroy_reg_param(&reg_params[1]);
	destroy_reg_param(&reg_params[2]);
	destroy_reg_param(&reg_params[3]);
	destroy_reg_param(&reg_params[4]);
	destroy_reg_param(&reg_params[5]);

err:
	target_free_working_area(target, algorithm);

	/* Switch to memory mapped mode before return to prompt */
	set_mm_mode(bank);

	return retval;
}

static int stmqspi_read(struct flash_bank *bank, uint8_t *buffer,
	uint32_t offset, uint32_t count)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	int retval;

	LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
		__func__, offset, count);

	if (target->state != TARGET_HALTED) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	if (!(stmqspi_info->probed)) {
		LOG_ERROR("Flash bank not probed");
		return ERROR_FLASH_BANK_NOT_PROBED;
	}

	if (offset + count > bank->size) {
		LOG_WARNING("Read beyond end of flash. Extra data to be ignored.");
		count = bank->size - offset;
	}

	/* Abort any previous operation */
	retval = stmqspi_abort(bank);
	if (retval != ERROR_OK)
		return retval;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		return retval;

	return qspi_read_write_block(bank, buffer, offset, count, false);
}

static int stmqspi_write(struct flash_bank *bank, const uint8_t *buffer,
	uint32_t offset, uint32_t count)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	unsigned int dual, sector;
	bool octal_dtr;
	int retval;

	LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
		__func__, offset, count);

	dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
	octal_dtr = IS_OCTOSPI && (stmqspi_info->saved_ccr & BIT(OCTOSPI_DDTR));

	if (target->state != TARGET_HALTED) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	if (!(stmqspi_info->probed)) {
		LOG_ERROR("Flash bank not probed");
		return ERROR_FLASH_BANK_NOT_PROBED;
	}

	if (offset + count > bank->size) {
		LOG_WARNING("Write beyond end of flash. Extra data discarded.");
		count = bank->size - offset;
	}

	/* Check sector protection */
	for (sector = 0; sector < bank->num_sectors; sector++) {
		/* Start offset in or before this sector? */
		/* End offset in or behind this sector? */
		if ((offset < (bank->sectors[sector].offset + bank->sectors[sector].size)) &&
			((offset + count - 1) >= bank->sectors[sector].offset) &&
			bank->sectors[sector].is_protected) {
			LOG_ERROR("Flash sector %u protected", sector);
			return ERROR_FLASH_PROTECTED;
		}
	}

	if ((dual || octal_dtr) && ((offset & 1) != 0 || (count & 1) != 0)) {
		LOG_ERROR("In dual-QSPI and octal-DTR modes writes must be two byte aligned: "
			"%s: address=0x%08" PRIx32 " len=0x%08" PRIx32, __func__, offset, count);
		return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
	}

	/* Abort any previous operation */
	retval = stmqspi_abort(bank);
	if (retval != ERROR_OK)
		return retval;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		return retval;

	return qspi_read_write_block(bank, (uint8_t *)buffer, offset, count, true);
}

static int stmqspi_verify(struct flash_bank *bank, const uint8_t *buffer,
	uint32_t offset, uint32_t count)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	unsigned int dual;
	bool octal_dtr;
	int retval;

	LOG_DEBUG("%s: offset=0x%08" PRIx32 " count=0x%08" PRIx32,
		__func__, offset, count);

	dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
	octal_dtr = IS_OCTOSPI && (stmqspi_info->saved_ccr & BIT(OCTOSPI_DDTR));

	if (target->state != TARGET_HALTED) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	if (!(stmqspi_info->probed)) {
		LOG_ERROR("Flash bank not probed");
		return ERROR_FLASH_BANK_NOT_PROBED;
	}

	if (offset + count > bank->size) {
		LOG_WARNING("Verify beyond end of flash. Extra data ignored.");
		count = bank->size - offset;
	}

	if ((dual || octal_dtr) && ((offset & 1) != 0 || (count & 1) != 0)) {
		LOG_ERROR("In dual-QSPI and octal-DTR modes reads must be two byte aligned: "
			"%s: address=0x%08" PRIx32 " len=0x%08" PRIx32, __func__, offset, count);
		return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
	}

	/* Abort any previous operation */
	retval = stmqspi_abort(bank);
	if (retval != ERROR_OK)
		return retval;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		return retval;

	return qspi_verify(bank, (uint8_t *)buffer, offset, count);
}

/* Find appropriate dummy setting, in particular octo mode */
static int find_sfdp_dummy(struct flash_bank *bank, int len)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	uint32_t io_base = stmqspi_info->io_base;
	uint8_t data;
	unsigned int dual, count;
	bool flash1 = !(stmqspi_info->saved_cr & BIT(SPI_FSEL_FLASH));
	int retval;
	const unsigned int max_bytes = 64;

	dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;

	LOG_DEBUG("%s: len=%d, dual=%u, flash1=%d",
		__func__, len, dual, flash1);

	/* Abort any previous operation */
	retval = target_write_u32(target, io_base + SPI_CR,
		stmqspi_info->saved_cr | BIT(SPI_ABORT));
	if (retval != ERROR_OK)
		goto err;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		goto err;

	/* Switch to saved_cr (had to be set accordingly before this call) */
	retval = target_write_u32(target, io_base + SPI_CR, stmqspi_info->saved_cr);
	if (retval != ERROR_OK)
		goto err;

	/* Read at most that many bytes */
	retval = target_write_u32(target, io_base + SPI_DLR, (max_bytes << dual) - 1);
	if (retval != ERROR_OK)
		return retval;

	/* Read SFDP block */
	if (IS_OCTOSPI)
		retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
			OCTOSPI_CCR_READ_SFDP(len), SPIFLASH_READ_SFDP);
	else
		retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_SFDP);
	if (retval != ERROR_OK)
		goto err;

	/* Read from start of sfdp block */
	retval = target_write_u32(target, io_base + SPI_AR, 0);
	if (retval != ERROR_OK)
		goto err;

	for (count = 0 ; count < max_bytes; count++) {
		if ((dual != 0) && !flash1) {
			/* discard even byte in dual flash-mode if flash2 */
			retval = target_read_u8(target, io_base + SPI_DR, &data);
			if (retval != ERROR_OK)
				goto err;
		}

		retval = target_read_u8(target, io_base + SPI_DR, &data);
		if (retval != ERROR_OK)
			goto err;

		if (data == 0x53) {
			LOG_DEBUG("start of SFDP header for flash%c after %u dummy bytes",
				flash1 ? '1' : '2', count);
			if (flash1)
				stmqspi_info->sfdp_dummy1 = count;
			else
				stmqspi_info->sfdp_dummy2 = count;
			return ERROR_OK;
		}

		if ((dual != 0) && flash1) {
			/* discard odd byte in dual flash-mode if flash1 */
			retval = target_read_u8(target, io_base + SPI_DR, &data);
			if (retval != ERROR_OK)
				goto err;
		}
	}

	LOG_DEBUG("no start of SFDP header even after %u dummy bytes", count);

err:
	/* Abort operation */
	retval = stmqspi_abort(bank);

	return retval;
}

/* Read SFDP parameter block */
static int read_sfdp_block(struct flash_bank *bank, uint32_t addr,
	uint32_t words, uint32_t *buffer)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	uint32_t io_base = stmqspi_info->io_base;
	bool flash1 = !(stmqspi_info->saved_cr & BIT(SPI_FSEL_FLASH));
	unsigned int dual, count, len, *dummy;
	int retval;

	dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;

	if (IS_OCTOSPI && (((stmqspi_info->saved_ccr >> SPI_DMODE_POS) & 0x7) > 3)) {
		/* in OCTO mode 4-byte address and (yet) unknown number of dummy clocks */
		len = 4;

		/* in octo mode, use sfdp_dummy1 only */
		dummy = &stmqspi_info->sfdp_dummy1;
		if (*dummy == 0) {
			retval = find_sfdp_dummy(bank, len);
			if (retval != ERROR_OK)
				return retval;
		}
	} else {
		/* in all other modes 3-byte-address and 8(?) dummy clocks */
		len = 3;

		/* use sfdp_dummy1/2 according to currently selected flash */
		dummy = (stmqspi_info->saved_cr & BIT(SPI_FSEL_FLASH)) ?
			&stmqspi_info->sfdp_dummy2 : &stmqspi_info->sfdp_dummy1;

		/* according to SFDP standard, there should always be 8 dummy *CLOCKS*
		 * giving 1, 2 or 4 dummy *BYTES*, however, this is apparently not
		 * always implemented correctly, so determine the number of dummy bytes
		 * dynamically */
		if (*dummy == 0) {
			retval = find_sfdp_dummy(bank, len);
			if (retval != ERROR_OK)
				return retval;
		}
	}

	LOG_DEBUG("%s: addr=0x%08" PRIx32 " words=0x%08" PRIx32 " dummy=%u",
		__func__, addr, words, *dummy);

	/* Abort any previous operation */
	retval = target_write_u32(target, io_base + SPI_CR,
		stmqspi_info->saved_cr | BIT(SPI_ABORT));
	if (retval != ERROR_OK)
		goto err;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		goto err;

	/* Switch to one flash only */
	retval = target_write_u32(target, io_base + SPI_CR, stmqspi_info->saved_cr);
	if (retval != ERROR_OK)
		goto err;

	/* Read that many words plus dummy bytes */
	retval = target_write_u32(target, io_base + SPI_DLR,
		((*dummy + words * sizeof(uint32_t)) << dual) - 1);
	if (retval != ERROR_OK)
		goto err;

	/* Read SFDP block */
	if (IS_OCTOSPI)
		retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
			OCTOSPI_CCR_READ_SFDP(len), SPIFLASH_READ_SFDP);
	else
		retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_SFDP);
	if (retval != ERROR_OK)
		goto err;

	retval = target_write_u32(target, io_base + SPI_AR, addr << dual);
	if (retval != ERROR_OK)
		goto err;

	/* dummy clocks */
	for (count = *dummy << dual; count > 0; --count) {
		retval = target_read_u8(target, io_base + SPI_DR, (uint8_t *)buffer);
		if (retval != ERROR_OK)
			goto err;
	}

	for ( ; words > 0; words--) {
		if (dual != 0) {
			uint32_t word1, word2;

			retval = target_read_u32(target, io_base + SPI_DR, &word1);
			if (retval != ERROR_OK)
				goto err;
			retval = target_read_u32(target, io_base + SPI_DR, &word2);
			if (retval != ERROR_OK)
				goto err;

			if (!flash1) {
				/* shift odd numbered bytes into even numbered ones */
				word1 >>= 8;
				word2 >>= 8;
			}

			/* pack even numbered bytes into one word */
			*buffer = (word1 & 0xFFU) | ((word1 & 0xFF0000U) >> 8) |
				((word2 & 0xFFU) << 16) | ((word2 & 0xFF0000U) << 8);


		} else {
			retval = target_read_u32(target, io_base + SPI_DR, buffer);
			if (retval != ERROR_OK)
				goto err;
		}
		LOG_DEBUG("raw SFDP data 0x%08" PRIx32, *buffer);

		/* endian correction, sfdp data is always le uint32_t based */
		*buffer = le_to_h_u32((uint8_t *)buffer);
		buffer++;
	}

err:
	return retval;
}

/* Return ID of flash device(s) */
/* On exit, indirect mode is kept */
static int read_flash_id(struct flash_bank *bank, uint32_t *id1, uint32_t *id2)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	uint32_t io_base = stmqspi_info->io_base;
	uint8_t byte;
	unsigned int type, count, len1, len2;
	int retval = ERROR_OK;

	/* invalidate both ids */
	*id1 = 0;
	*id2 = 0;

	if (target->state != TARGET_HALTED) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	/* SPIFLASH_READ_MID causes device in octal mode to go berserk, so don't use in this case */
	for (type = (IS_OCTOSPI && OPI_MODE) ? 1 : 0; type < 2 ; type++) {
		/* Abort any previous operation */
		retval = stmqspi_abort(bank);
		if (retval != ERROR_OK)
			goto err;

		/* Poll WIP */
		retval = wait_till_ready(bank, SPI_PROBE_TIMEOUT);
		if (retval != ERROR_OK)
			goto err;

		/* Wait for busy to be cleared */
		retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
		if (retval != ERROR_OK)
			goto err;

		/* Read at most 16 bytes per chip */
		count = 16;
		retval = target_write_u32(target, io_base + SPI_DLR,
			(stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH) ? count * 2 : count) - 1);
		if (retval != ERROR_OK)
			goto err;

		/* Read id: one particular flash chip (N25Q128) switches back to SPI mode when receiving
		 * SPI_FLASH_READ_ID in QPI mode, hence try SPIFLASH_READ_MID first */
		switch (type) {
			case 0:
				if (IS_OCTOSPI)
					retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
						OCTOSPI_CCR_READ_MID, SPIFLASH_READ_MID);
				else
					retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_MID);
				break;

			case 1:
				if (IS_OCTOSPI)
					retval = octospi_cmd(bank, OCTOSPI_READ_MODE,
						OCTOSPI_CCR_READ_ID, SPIFLASH_READ_ID);
				else
					retval = target_write_u32(target, io_base + QSPI_CCR, QSPI_CCR_READ_ID);
				break;

			default:
				return ERROR_FAIL;
		}

		if (retval != ERROR_OK)
			goto err;

		/* Dummy address 0, only required for 8-line mode */
		if (IS_OCTOSPI && OPI_MODE) {
			retval = target_write_u32(target, io_base + SPI_AR, 0);
			if (retval != ERROR_OK)
				goto err;
		}

		/* for debugging only */
		uint32_t dummy;
		(void)target_read_u32(target, io_base + SPI_SR, &dummy);

		/* Read ID from Data Register */
		for (len1 = 0, len2 = 0; count > 0; --count) {
			if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
				BIT(SPI_FSEL_FLASH))) != BIT(SPI_FSEL_FLASH)) {
				retval = target_read_u8(target, io_base + SPI_DR, &byte);
				if (retval != ERROR_OK)
					goto err;
				/* collect 3 bytes without continuation codes */
				if ((byte != 0x7F) && (len1 < 3)) {
					*id1 = (*id1 >> 8) | ((uint32_t)byte) << 16;
					len1++;
				}
			}
			if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
				BIT(SPI_FSEL_FLASH))) != 0) {
				retval = target_read_u8(target, io_base + SPI_DR, &byte);
				if (retval != ERROR_OK)
					goto err;
				/* collect 3 bytes without continuation codes */
				if ((byte != 0x7F) && (len2 < 3)) {
					*id2 = (*id2 >> 8) | ((uint32_t)byte) << 16;
					len2++;
				}
			}
		}

		if (((*id1 != 0x000000) && (*id1 != 0xFFFFFF)) ||
			((*id2 != 0x000000) && (*id2 != 0xFFFFFF)))
			break;
	}

	if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
		BIT(SPI_FSEL_FLASH))) != BIT(SPI_FSEL_FLASH)) {
		if ((*id1 == 0x000000) || (*id1 == 0xFFFFFF)) {
			/* no id retrieved, so id must be set manually */
			LOG_INFO("No id from flash1");
			retval = ERROR_FLASH_BANK_NOT_PROBED;
		}
	}

	if ((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) | BIT(SPI_FSEL_FLASH))) != 0) {
		if ((*id2 == 0x000000) || (*id2 == 0xFFFFFF)) {
			/* no id retrieved, so id must be set manually */
			LOG_INFO("No id from flash2");
			retval = ERROR_FLASH_BANK_NOT_PROBED;
		}
	}

err:
	return retval;
}

static int stmqspi_probe(struct flash_bank *bank)
{
	struct target *target = bank->target;
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;
	struct flash_sector *sectors = NULL;
	uint32_t io_base = stmqspi_info->io_base;
	uint32_t id1 = 0, id2 = 0, data = 0;
	const struct flash_device *p;
	const uint32_t magic = 0xAEF1510E;
	unsigned int dual, fsize;
	bool octal_dtr;
	int retval;

	/* invalidate all flash device info */
	if (stmqspi_info->probed)
		free(bank->sectors);
	bank->size = 0;
	bank->num_sectors = 0;
	bank->sectors = NULL;
	stmqspi_info->sfdp_dummy1 = 0;
	stmqspi_info->sfdp_dummy2 = 0;
	stmqspi_info->probed = false;
	memset(&stmqspi_info->dev, 0, sizeof(stmqspi_info->dev));
	stmqspi_info->dev.name = "unknown";

	/* Abort any previous operation */
	retval = stmqspi_abort(bank);
	if (retval != ERROR_OK)
		return retval;

	/* Wait for busy to be cleared */
	retval = poll_busy(bank, SPI_PROBE_TIMEOUT);
	if (retval != ERROR_OK)
		return retval;

	/* check whether QSPI_ABR is writeable and readback returns the value written */
	retval = target_write_u32(target, io_base + QSPI_ABR, magic);
	if (retval == ERROR_OK) {
		(void)target_read_u32(target, io_base + QSPI_ABR, &data);
		(void)target_write_u32(target, io_base + QSPI_ABR, 0);
	}

	if (data == magic) {
		LOG_DEBUG("QSPI_ABR register present");
		stmqspi_info->octo = false;
	} else {
		uint32_t magic_id;

		retval = target_read_u32(target, io_base + OCTOSPI_MAGIC, &magic_id);

		if (retval == ERROR_OK && magic_id == OCTO_MAGIC_ID) {
			LOG_DEBUG("OCTOSPI_MAGIC present");
			stmqspi_info->octo = true;
		} else {
			LOG_ERROR("No QSPI, no OCTOSPI at 0x%08" PRIx32, io_base);
			stmqspi_info->probed = false;
			stmqspi_info->dev.name = "none";
			return ERROR_FAIL;
		}
	}

	/* save current FSEL and DFM bits in QSPI/OCTOSPI_CR, current QSPI/OCTOSPI_CCR value */
	retval = target_read_u32(target, io_base + SPI_CR, &stmqspi_info->saved_cr);
	if (retval == ERROR_OK)
		retval = target_read_u32(target, io_base + SPI_CCR, &stmqspi_info->saved_ccr);

	if (IS_OCTOSPI) {
		uint32_t dcr1;

		retval = target_read_u32(target, io_base + OCTOSPI_DCR1, &dcr1);

		if (retval == ERROR_OK)
			retval = target_read_u32(target, io_base + OCTOSPI_TCR,
				&stmqspi_info->saved_tcr);

		if (retval == ERROR_OK)
			retval = target_read_u32(target, io_base + OCTOSPI_IR,
				&stmqspi_info->saved_ir);

		if (retval != ERROR_OK) {
			LOG_ERROR("No OCTOSPI at io_base 0x%08" PRIx32, io_base);
			stmqspi_info->probed = false;
			stmqspi_info->dev.name = "none";
			return ERROR_FAIL;
		}

		const uint32_t mtyp = (dcr1 & OCTOSPI_MTYP_MASK) >> OCTOSPI_MTYP_POS;

		if ((mtyp != 0x0) && (mtyp != 0x1)) {
			LOG_ERROR("Only regular SPI protocol supported in OCTOSPI");
			stmqspi_info->probed = false;
			stmqspi_info->dev.name = "none";
			return ERROR_FAIL;
		}

		LOG_DEBUG("OCTOSPI at 0x%08" PRIx64 ", io_base at 0x%08" PRIx32 ", OCTOSPI_CR 0x%08"
			PRIx32 ", OCTOSPI_CCR 0x%08" PRIx32 ", %d-byte addr", bank->base, io_base,
			stmqspi_info->saved_cr, stmqspi_info->saved_ccr, SPI_ADSIZE);
	} else {
		if (retval == ERROR_OK) {
			LOG_DEBUG("QSPI at 0x%08" PRIx64 ", io_base at 0x%08" PRIx32 ", QSPI_CR 0x%08"
				PRIx32 ", QSPI_CCR 0x%08" PRIx32 ", %d-byte addr", bank->base, io_base,
				stmqspi_info->saved_cr, stmqspi_info->saved_ccr, SPI_ADSIZE);
				if (stmqspi_info->saved_ccr & (1U << QSPI_DDRM))
					LOG_WARNING("DDR mode is untested and suffers from some silicon bugs");
		} else {
			LOG_ERROR("No QSPI at io_base 0x%08" PRIx32, io_base);
			stmqspi_info->probed = false;
			stmqspi_info->dev.name = "none";
			return ERROR_FAIL;
		}
	}

	dual = (stmqspi_info->saved_cr & BIT(SPI_DUAL_FLASH)) ? 1 : 0;
	octal_dtr = IS_OCTOSPI && (stmqspi_info->saved_ccr & BIT(OCTOSPI_DDTR));
	if (dual || octal_dtr)
		bank->write_start_alignment = bank->write_end_alignment = 2;
	else
		bank->write_start_alignment = bank->write_end_alignment = 1;

	/* read and decode flash ID; returns in indirect mode */
	retval = read_flash_id(bank, &id1, &id2);
	LOG_DEBUG("id1 0x%06" PRIx32 ", id2 0x%06" PRIx32, id1, id2);
	if (retval == ERROR_FLASH_BANK_NOT_PROBED) {
		/* no id retrieved, so id must be set manually */
		LOG_INFO("No id - set flash parameters manually");
		retval = ERROR_OK;
		goto err;
	}

	if (retval != ERROR_OK)
		goto err;

	/* identify flash1 */
	for (p = flash_devices; id1 && p->name ; p++) {
		if (p->device_id == id1) {
			memcpy(&stmqspi_info->dev, p, sizeof(stmqspi_info->dev));
			if (p->size_in_bytes / 4096)
				LOG_INFO("flash1 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
					" KiB", p->name, id1, p->size_in_bytes / 1024);
			else
				LOG_INFO("flash1 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
					" B", p->name, id1, p->size_in_bytes);
			break;
		}
	}

	if (id1 && !p->name) {
		/* chip not been identified by id, then try SFDP */
		struct flash_device temp;
		uint32_t saved_cr = stmqspi_info->saved_cr;

		/* select flash1 */
		stmqspi_info->saved_cr = stmqspi_info->saved_cr & ~BIT(SPI_FSEL_FLASH);
		retval = spi_sfdp(bank, &temp, &read_sfdp_block);

		/* restore saved_cr */
		stmqspi_info->saved_cr = saved_cr;

		if (retval == ERROR_OK) {
			LOG_INFO("flash1 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
				" KiB", temp.name, id1, temp.size_in_bytes / 1024);
			/* save info and retrieved *good* id as spi_sfdp clears all info */
			memcpy(&stmqspi_info->dev, &temp, sizeof(stmqspi_info->dev));
			stmqspi_info->dev.device_id = id1;
		} else {
			/* even not identified by SFDP, then give up */
			LOG_WARNING("Unknown flash1 device id = 0x%06" PRIx32
				" - set flash parameters manually", id1);
			retval = ERROR_OK;
			goto err;
		}
	}

	/* identify flash2 */
	for (p = flash_devices; id2 && p->name ; p++) {
		if (p->device_id == id2) {
			if (p->size_in_bytes / 4096)
				LOG_INFO("flash2 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
					" KiB", p->name, id2, p->size_in_bytes / 1024);
			else
				LOG_INFO("flash2 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
					" B", p->name, id2, p->size_in_bytes);

			if (!id1)
				memcpy(&stmqspi_info->dev, p, sizeof(stmqspi_info->dev));
			else {
				if ((stmqspi_info->dev.read_cmd != p->read_cmd) ||
					(stmqspi_info->dev.qread_cmd != p->qread_cmd) ||
					(stmqspi_info->dev.pprog_cmd != p->pprog_cmd) ||
					(stmqspi_info->dev.erase_cmd != p->erase_cmd) ||
					(stmqspi_info->dev.chip_erase_cmd != p->chip_erase_cmd) ||
					(stmqspi_info->dev.sectorsize != p->sectorsize) ||
					(stmqspi_info->dev.size_in_bytes != p->size_in_bytes)) {
					LOG_ERROR("Incompatible flash1/flash2 devices");
					goto err;
				}
				/* page size is optional in SFDP, so accept smallest value */
				if (p->pagesize < stmqspi_info->dev.pagesize)
					stmqspi_info->dev.pagesize = p->pagesize;
			}
			break;
		}
	}

	if (id2 && !p->name) {
		/* chip not been identified by id, then try SFDP */
		struct flash_device temp;
		uint32_t saved_cr = stmqspi_info->saved_cr;

		/* select flash2 */
		stmqspi_info->saved_cr = stmqspi_info->saved_cr | BIT(SPI_FSEL_FLASH);
		retval = spi_sfdp(bank, &temp, &read_sfdp_block);

		/* restore saved_cr */
		stmqspi_info->saved_cr = saved_cr;

		if (retval == ERROR_OK)
			LOG_INFO("flash2 \'%s\' id = 0x%06" PRIx32 " size = %" PRIu32
				" KiB", temp.name, id2, temp.size_in_bytes / 1024);
		else {
			/* even not identified by SFDP, then give up */
			LOG_WARNING("Unknown flash2 device id = 0x%06" PRIx32
				" - set flash parameters manually", id2);
			retval = ERROR_OK;
			goto err;
		}

		if (!id1)
			memcpy(&stmqspi_info->dev, &temp, sizeof(stmqspi_info->dev));
		else {
			if ((stmqspi_info->dev.read_cmd != temp.read_cmd) ||
				(stmqspi_info->dev.qread_cmd != temp.qread_cmd) ||
				(stmqspi_info->dev.pprog_cmd != temp.pprog_cmd) ||
				(stmqspi_info->dev.erase_cmd != temp.erase_cmd) ||
				(stmqspi_info->dev.chip_erase_cmd != temp.chip_erase_cmd) ||
				(stmqspi_info->dev.sectorsize != temp.sectorsize) ||
				(stmqspi_info->dev.size_in_bytes != temp.size_in_bytes)) {
				LOG_ERROR("Incompatible flash1/flash2 devices");
				goto err;
			}
			/* page size is optional in SFDP, so accept smallest value */
			if (temp.pagesize < stmqspi_info->dev.pagesize)
				stmqspi_info->dev.pagesize = temp.pagesize;
		}
	}

	/* Set correct size value */
	bank->size = stmqspi_info->dev.size_in_bytes << dual;

	uint32_t dcr;
	retval = target_read_u32(target, io_base + SPI_DCR, &dcr);

	if (retval != ERROR_OK)
		goto err;

	fsize = (dcr >> SPI_FSIZE_POS) & (BIT(SPI_FSIZE_LEN) - 1);

	LOG_DEBUG("FSIZE = 0x%04x", fsize);
	if (bank->size == BIT((fsize + 1)))
		LOG_DEBUG("FSIZE in DCR(1) matches actual capacity. Beware of silicon bug in H7, L4+, MP1.");
	else if (bank->size == BIT((fsize + 0)))
		LOG_DEBUG("FSIZE in DCR(1) is off by one regarding actual capacity. Fix for silicon bug?");
	else
		LOG_ERROR("FSIZE in DCR(1) doesn't match actual capacity.");

	/* if no sectors, then treat whole flash as single sector */
	if (stmqspi_info->dev.sectorsize == 0)
		stmqspi_info->dev.sectorsize = stmqspi_info->dev.size_in_bytes;
	/* if no page_size, then use sectorsize as page_size */
	if (stmqspi_info->dev.pagesize == 0)
		stmqspi_info->dev.pagesize = stmqspi_info->dev.sectorsize;

	/* create and fill sectors array */
	bank->num_sectors = stmqspi_info->dev.size_in_bytes / stmqspi_info->dev.sectorsize;
	sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
	if (!sectors) {
		LOG_ERROR("not enough memory");
		retval = ERROR_FAIL;
		goto err;
	}

	for (unsigned int sector = 0; sector < bank->num_sectors; sector++) {
		sectors[sector].offset = sector * (stmqspi_info->dev.sectorsize << dual);
		sectors[sector].size = (stmqspi_info->dev.sectorsize << dual);
		sectors[sector].is_erased = -1;
		sectors[sector].is_protected = 0;
	}

	bank->sectors = sectors;
	stmqspi_info->probed = true;

err:
	/* Switch to memory mapped mode before return to prompt */
	set_mm_mode(bank);

	return retval;
}

static int stmqspi_auto_probe(struct flash_bank *bank)
{
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;

	if (stmqspi_info->probed)
		return ERROR_OK;
	stmqspi_probe(bank);
	return ERROR_OK;
}

static int stmqspi_protect_check(struct flash_bank *bank)
{
	/* Nothing to do. Protection is only handled in SW. */
	return ERROR_OK;
}

static int get_stmqspi_info(struct flash_bank *bank, struct command_invocation *cmd)
{
	struct stmqspi_flash_bank *stmqspi_info = bank->driver_priv;

	if (!(stmqspi_info->probed)) {
		command_print_sameline(cmd, "\nQSPI flash bank not probed yet\n");
		return ERROR_FLASH_BANK_NOT_PROBED;
	}

	command_print_sameline(cmd, "flash%s%s \'%s\', device id = 0x%06" PRIx32
			", flash size = %" PRIu32 "%s B\n(page size = %" PRIu32
			", read = 0x%02" PRIx8 ", qread = 0x%02" PRIx8
			", pprog = 0x%02" PRIx8 ", mass_erase = 0x%02" PRIx8
			", sector size = %" PRIu32 " %sB, sector_erase = 0x%02" PRIx8 ")",
			((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
			BIT(SPI_FSEL_FLASH))) != BIT(SPI_FSEL_FLASH)) ? "1" : "",
			((stmqspi_info->saved_cr & (BIT(SPI_DUAL_FLASH) |
			BIT(SPI_FSEL_FLASH))) != 0) ? "2" : "",
			stmqspi_info->dev.name, stmqspi_info->dev.device_id,
			bank->size / 4096 ? bank->size / 1024 : bank->size,
			bank->size / 4096 ? "Ki" : "", stmqspi_info->dev.pagesize,
			stmqspi_info->dev.read_cmd, stmqspi_info->dev.qread_cmd,
			stmqspi_info->dev.pprog_cmd, stmqspi_info->dev.chip_erase_cmd,
			stmqspi_info->dev.sectorsize / 4096 ?
				stmqspi_info->dev.sectorsize / 1024 : stmqspi_info->dev.sectorsize,
			stmqspi_info->dev.sectorsize / 4096 ? "Ki" : "",
			stmqspi_info->dev.erase_cmd);

	return ERROR_OK;
}

static const struct command_registration stmqspi_exec_command_handlers[] = {
	{
		.name = "mass_erase",
		.handler = stmqspi_handle_mass_erase_command,
		.mode = COMMAND_EXEC,
		.usage = "bank_id",
		.help = "Mass erase entire flash device.",
	},
	{
		.name = "set",
		.handler = stmqspi_handle_set,
		.mode = COMMAND_EXEC,
		.usage = "bank_id name chip_size page_size read_cmd qread_cmd pprg_cmd "
			"[ mass_erase_cmd ] [ sector_size sector_erase_cmd ]",
		.help = "Set params of single flash chip",
	},
	{
		.name = "cmd",
		.handler = stmqspi_handle_cmd,
		.mode = COMMAND_EXEC,
		.usage = "bank_id num_resp cmd_byte ...",
		.help = "Send low-level command cmd_byte and following bytes or read num_resp.",
	},
	COMMAND_REGISTRATION_DONE
};

static const struct command_registration stmqspi_command_handlers[] = {
	{
		.name = "stmqspi",
		.mode = COMMAND_ANY,
		.help = "stmqspi flash command group",
		.usage = "",
		.chain = stmqspi_exec_command_handlers,
	},
	COMMAND_REGISTRATION_DONE
};

const struct flash_driver stmqspi_flash = {
	.name = "stmqspi",
	.commands = stmqspi_command_handlers,
	.flash_bank_command = stmqspi_flash_bank_command,
	.erase = stmqspi_erase,
	.protect = stmqspi_protect,
	.write = stmqspi_write,
	.read = stmqspi_read,
	.verify = stmqspi_verify,
	.probe = stmqspi_probe,
	.auto_probe = stmqspi_auto_probe,
	.erase_check = stmqspi_blank_check,
	.protect_check = stmqspi_protect_check,
	.info = get_stmqspi_info,
	.free_driver_priv = default_flash_free_driver_priv,
};