summaryrefslogtreecommitdiff
path: root/nuttx/arch/arm/src/stm32/stm32_i2c.c
blob: fb8718316517ad4a107e9b90770472137105af31 (plain) (blame)
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
/************************************************************************************
 * arch/arm/src/stm32/stm32_i2c.c
 * STM32 I2C Hardware Layer - Device Driver
 *
 *   Copyright (C) 2011 Uros Platise. All rights reserved.
 *   Author: Uros Platise <uros.platise@isotel.eu>
 *
 * With extensions, modifications by:
 *
 *   Copyright (C) 2011-2013 Gregory Nutt. All rights reserved.
 *   Author: Gregroy Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ************************************************************************************/

/* Supports:
 *  - Master operation, 100 kHz (standard) and 400 kHz (full speed)
 *  - Multiple instances (shared bus)
 *  - Interrupt based operation
 * 
 * Structure naming:
 *  - Device: structure as defined by the nuttx/i2c/i2c.h
 *  - Instance: represents each individual access to the I2C driver, obtained by
 *      the i2c_init(); it extends the Device structure from the nuttx/i2c/i2c.h; 
 *      Instance points to OPS, to common I2C Hardware private data and contains
 *      its own private data, as frequency, address, mode of operation (in the future)
 *  - Private: Private data of an I2C Hardware
 * 
 * TODO
 *  - Check for all possible deadlocks (as BUSY='1' I2C needs to be reset in HW using the I2C_CR1_SWRST)
 *  - SMBus support (hardware layer timings are already supported) and add SMBA gpio pin
 *  - Slave support with multiple addresses (on multiple instances):
 *      - 2 x 7-bit address or 
 *      - 1 x 10 bit adresses + 1 x 7 bit address (?)
 *      - plus the broadcast address (general call)
 *  - Multi-master support
 *  - DMA (to get rid of too many CPU wake-ups and interventions)
 *  - Be ready for IPMI
 */

/************************************************************************************
 * Included Files
 ************************************************************************************/

#include <nuttx/config.h>

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <semaphore.h>
#include <errno.h>
#include <debug.h>

#include <nuttx/arch.h>
#include <nuttx/irq.h>
#include <nuttx/i2c.h>
#include <nuttx/kmalloc.h>
#include <nuttx/clock.h>

#include <arch/board/board.h>

#include "up_arch.h"

#include "stm32_rcc.h"
#include "stm32_i2c.h"
#include "stm32_waste.h"

// useful when debugging
// #pragma GCC optimize("O0")

/* At least one I2C peripheral must be enabled */

#if defined(CONFIG_STM32_I2C1) || defined(CONFIG_STM32_I2C2) || defined(CONFIG_STM32_I2C3)

/* This implementation is for the STM32 F1, F2, and F4 only */

#if defined(CONFIG_STM32_STM32F10XX) || defined(CONFIG_STM32_STM32F20XX) || \
    defined(CONFIG_STM32_STM32F40XX)

/************************************************************************************
 * Pre-processor Definitions
 ************************************************************************************/
/* Configuration ********************************************************************/
/* CONFIG_I2C_POLLED may be set so that I2C interrrupts will not be used.  Instead,
 * CPU-intensive polling will be used.
 */

/* Interrupt wait timeout in seconds and milliseconds */

#if !defined(CONFIG_STM32_I2CTIMEOSEC) && !defined(CONFIG_STM32_I2CTIMEOMS)
#  define CONFIG_STM32_I2CTIMEOSEC 0
#  define CONFIG_STM32_I2CTIMEOMS  500   /* Default is 500 milliseconds */
#elif !defined(CONFIG_STM32_I2CTIMEOSEC)
#  define CONFIG_STM32_I2CTIMEOSEC 0     /* User provided milliseconds */
#elif !defined(CONFIG_STM32_I2CTIMEOMS)
#  define CONFIG_STM32_I2CTIMEOMS  0     /* User provided seconds */
#endif

/* Interrupt wait time timeout in system timer ticks */

#define CONFIG_STM32_I2CTIMEOTICKS \
(SEC2TICK(CONFIG_STM32_I2CTIMEOSEC) + MSEC2TICK(CONFIG_STM32_I2CTIMEOMS))

/* On the STM32F103ZE, there is an internal conflict between I2C1 and FSMC.  In that
 * case, it is necessary to disable FSMC before each I2C1 access and re-enable FSMC
 * when the I2C access completes.
 */

#undef I2C1_FSMC_CONFLICT
#if defined(CONFIG_STM32_STM32F10XX) && defined(CONFIG_STM32_FSMC) && defined(CONFIG_STM32_I2C1)
#  define I2C1_FSMC_CONFLICT
#endif

/* Debug ****************************************************************************/
/* CONFIG_DEBUG_I2C + CONFIG_DEBUG enables general I2C debug output. */

#ifdef CONFIG_DEBUG_I2C
#  define i2cdbg dbg
#  define i2cvdbg vdbg
#else
#  define i2cdbg(x...)
#  define i2cvdbg(x...)
#endif

/* I2C event trace logic.  NOTE:  trace uses the internal, non-standard, low-level
 * debug interface syslog() but does not require that any other debug
 * is enabled.
 */

#ifndef CONFIG_I2C_TRACE
#  define stm32_i2c_tracereset(p)
#  define stm32_i2c_tracenew(p,s)
#  define stm32_i2c_traceevent(p,e,a)
#  define stm32_i2c_tracedump(p)
#endif

#ifndef CONFIG_I2C_NTRACE
#  define CONFIG_I2C_NTRACE 32
#endif

/************************************************************************************
 * Private Types
 ************************************************************************************/
/* Interrupt state */

enum stm32_intstate_e
{
    INTSTATE_IDLE = 0,      /* No I2C activity */
    INTSTATE_WAITING,       /* Waiting for completion of interrupt activity */
    INTSTATE_DONE,          /* Interrupt activity complete */
};

/* Trace events */

enum stm32_trace_e
{
    I2CEVENT_NONE = 0,      /* No events have occurred with this status */
    I2CEVENT_SENDADDR,      /* Start/Master bit set and address sent, param = msgc */
    I2CEVENT_SENDBYTE,      /* Send byte, param = dcnt */
    I2CEVENT_ITBUFEN,       /* Enable buffer interrupts, param = 0 */
    I2CEVENT_RCVBYTE,       /* Read more dta, param = dcnt */
    I2CEVENT_REITBUFEN,     /* Re-enable buffer interrupts, param = 0 */
    I2CEVENT_DISITBUFEN,    /* Disable buffer interrupts, param = 0 */
    I2CEVENT_BTFNOSTART,    /* BTF on last byte with no restart, param = msgc */
    I2CEVENT_BTFRESTART,    /* Last byte sent, re-starting, param = msgc */
    I2CEVENT_BTFSTOP,       /* Last byte sten, send stop, param = 0 */
    I2CEVENT_ERROR          /* Error occurred, param = 0 */
};

#ifdef CONFIG_I2C_TRACE
static const char *stm32_trace_names[] = {
    "NONE      ",
    "SENDADDR  ",
    "SENDBYTE  ",
    "ITBUFEN   ",
    "RCVBYTE   ",
    "REITBUFEN ",
    "DISITBUFEN",
    "BTFNOSTART",
    "BTFRESTART",
    "BTFSTOP   ",
    "ERROR     "
};
#endif

/* Trace data */

struct stm32_trace_s
{
    uint32_t status;             /* I2C 32-bit SR2|SR1 status */
    uint32_t count;              /* Interrupt count when status change */
    enum stm32_intstate_e event; /* Last event that occurred with this status */
    uint32_t parm;               /* Parameter associated with the event */
    uint32_t time;               /* First of event or first status */
};

/* I2C Device hardware configuration */

struct stm32_i2c_config_s
{
    uint32_t    base;        /* I2C base address */
#ifndef CONFIG_I2C_POLLED
    int         ( *isr)(int, void *); /* Interrupt handler */
#endif
    uint32_t    clk_bit;     /* Clock enable bit */
    uint32_t    reset_bit;   /* Reset bit */
    uint32_t    scl_pin;     /* GPIO configuration for SCL as SCL */
    uint32_t    scl_gpio;    /* GPIO configuration for SCL as a GPIO */
    uint32_t    sda_pin;     /* GPIO configuration for SDA as SDA */
    uint32_t    sda_gpio;    /* GPIO configuration for SDA as a GPIO */
    uint32_t    ev_irq;      /* Event IRQ */
    uint32_t    er_irq;      /* Error IRQ */
};

/* I2C Device Private Data */

struct stm32_i2c_priv_s
{
    const struct stm32_i2c_config_s *config; /* Port configuration */
    int refs;                    /* Referernce count */
    sem_t sem_excl;              /* Mutual exclusion semaphore */
#ifndef CONFIG_I2C_POLLED
    sem_t sem_isr;               /* Interrupt wait semaphore */
#endif
    volatile uint8_t intstate;   /* Interrupt handshake (see enum stm32_intstate_e) */
    
    uint8_t msgc;                /* Message count */
    struct i2c_msg_s *msgv;      /* Message list */
    uint8_t *ptr;                /* Current message buffer */
    int dcnt;                    /* Current message length */
    uint16_t flags;              /* Current message flags */
    
    /* I2C trace support */
    
#ifdef CONFIG_I2C_TRACE
    int tndx;                    /* Trace array index */
    uint32_t start_time;         /* Time when the trace was started */
    
    /* The actual trace data */
    
    struct stm32_trace_s trace[CONFIG_I2C_NTRACE];
#endif
    
    uint32_t status;             /* End of transfer SR2|SR1 status */
};

/* I2C Device, Instance */

struct stm32_i2c_inst_s
{
    struct i2c_ops_s        *ops;  /* Standard I2C operations */
    struct stm32_i2c_priv_s *priv; /* Common driver private data structure */
    
    uint32_t    frequency;   /* Frequency used in this instantiation */
    int         address;     /* Address used in this instantiation */
    uint16_t    flags;       /* Flags used in this instantiation */
};

/************************************************************************************
 * Private Function Prototypes
 ************************************************************************************/

static inline uint16_t stm32_i2c_getreg(FAR struct stm32_i2c_priv_s *priv,
                                        uint8_t offset);
static inline void stm32_i2c_putreg(FAR struct stm32_i2c_priv_s *priv, uint8_t offset,
                                    uint16_t value);
static inline void stm32_i2c_modifyreg(FAR struct stm32_i2c_priv_s *priv,
                                       uint8_t offset, uint16_t clearbits,
                                       uint16_t setbits);
static inline void stm32_i2c_sem_wait(FAR struct i2c_dev_s *dev);
static inline int  stm32_i2c_sem_waitdone(FAR struct stm32_i2c_priv_s *priv, int timeout_us);
static inline void stm32_i2c_sem_waitstop(FAR struct stm32_i2c_priv_s *priv, int timeout_us);
static inline void stm32_i2c_sem_post(FAR struct i2c_dev_s *dev);
static inline void stm32_i2c_sem_init(FAR struct i2c_dev_s *dev);
static inline void stm32_i2c_sem_destroy(FAR struct i2c_dev_s *dev);
#ifdef CONFIG_I2C_TRACE
static void stm32_i2c_tracereset(FAR struct stm32_i2c_priv_s *priv);
static void stm32_i2c_tracenew(FAR struct stm32_i2c_priv_s *priv, uint32_t status);
static void stm32_i2c_traceevent(FAR struct stm32_i2c_priv_s *priv,
                                 enum stm32_trace_e event, uint32_t parm);
static void stm32_i2c_tracedump(FAR struct stm32_i2c_priv_s *priv);
#endif /* CONFIG_I2C_TRACE */
static void stm32_i2c_setclock(FAR struct stm32_i2c_priv_s *priv,
                               uint32_t frequency);
static inline void stm32_i2c_sendstart(FAR struct stm32_i2c_priv_s *priv);
static inline void stm32_i2c_clrstart(FAR struct stm32_i2c_priv_s *priv);
static inline void stm32_i2c_sendstop(FAR struct stm32_i2c_priv_s *priv);
static inline uint32_t stm32_i2c_getstatus(FAR struct stm32_i2c_priv_s *priv);
#ifdef I2C1_FSMC_CONFLICT
static inline uint32_t stm32_i2c_disablefsmc(FAR struct stm32_i2c_priv_s *priv);
static inline void stm32_i2c_enablefsmc(uint32_t ahbenr);
#endif /* I2C1_FSMC_CONFLICT */
static int stm32_i2c_isr(struct stm32_i2c_priv_s * priv);
// useful when debugging
// static int stm32_i2c_isr(struct stm32_i2c_priv_s *priv) __attribute__((optimize("O0")));
#ifndef CONFIG_I2C_POLLED
#ifdef CONFIG_STM32_I2C1
static int stm32_i2c1_isr(int irq, void *context);
#endif
#ifdef CONFIG_STM32_I2C2
static int stm32_i2c2_isr(int irq, void *context);
#endif
#ifdef CONFIG_STM32_I2C3
static int stm32_i2c3_isr(int irq, void *context);
#endif
#endif
static int stm32_i2c_init(FAR struct stm32_i2c_priv_s *priv);
static int stm32_i2c_deinit(FAR struct stm32_i2c_priv_s *priv);
static uint32_t stm32_i2c_setfrequency(FAR struct i2c_dev_s *dev,
                                       uint32_t frequency);
static int stm32_i2c_setaddress(FAR struct i2c_dev_s *dev, int addr, int nbits);
static int stm32_i2c_process(FAR struct i2c_dev_s *dev, FAR struct i2c_msg_s *msgs,
                             int count);
static int stm32_i2c_write(FAR struct i2c_dev_s *dev, const uint8_t *buffer,
                           int buflen);
static int stm32_i2c_read(FAR struct i2c_dev_s *dev, uint8_t *buffer, int buflen);
#ifdef CONFIG_I2C_WRITEREAD
static int stm32_i2c_writeread(FAR struct i2c_dev_s *dev,
                               const uint8_t *wbuffer, int wbuflen,
                               uint8_t *buffer, int buflen);
#endif
#ifdef CONFIG_I2C_TRANSFER
static int stm32_i2c_transfer(FAR struct i2c_dev_s *dev, FAR struct i2c_msg_s *msgs,
                              int count);
#endif

/************************************************************************************
 * Private Data
 ************************************************************************************/

#ifdef CONFIG_STM32_I2C1
# ifndef GPIO_I2C1_SCL_GPIO
#  define  GPIO_I2C1_SCL_GPIO 0
# endif
# ifndef GPIO_I2C1_SDA_GPIO
#  define  GPIO_I2C1_SDA_GPIO 0
# endif

static const struct stm32_i2c_config_s stm32_i2c1_config =
{
    .base       = STM32_I2C1_BASE,
#ifndef CONFIG_I2C_POLLED
    .isr        = stm32_i2c1_isr,
#endif
    .clk_bit    = RCC_APB1ENR_I2C1EN,
    .reset_bit  = RCC_APB1RSTR_I2C1RST,
    .scl_pin    = GPIO_I2C1_SCL,
    .scl_gpio   = GPIO_I2C1_SCL_GPIO,
    .sda_pin    = GPIO_I2C1_SDA,
    .sda_gpio   = GPIO_I2C1_SDA_GPIO,
    .ev_irq     = STM32_IRQ_I2C1EV,
    .er_irq     = STM32_IRQ_I2C1ER
};

struct stm32_i2c_priv_s stm32_i2c1_priv =
{
    .config     = &stm32_i2c1_config,
    .refs       = 0,
    .intstate   = INTSTATE_IDLE,
    .msgc       = 0,
    .msgv       = NULL,
    .ptr        = NULL,
    .dcnt       = 0,
    .flags      = 0,
    .status     = 0
};
#endif

#ifdef CONFIG_STM32_I2C2
# ifndef GPIO_I2C2_SCL_GPIO
#  define  GPIO_I2C2_SCL_GPIO 0
# endif
# ifndef GPIO_I2C2_SDA_GPIO
#  define  GPIO_I2C2_SDA_GPIO 0
# endif

static const struct stm32_i2c_config_s stm32_i2c2_config =
{
    .base       = STM32_I2C2_BASE,
#ifndef CONFIG_I2C_POLLED
    .isr        = stm32_i2c2_isr,
#endif
    .clk_bit    = RCC_APB1ENR_I2C2EN,
    .reset_bit  = RCC_APB1RSTR_I2C2RST,
    .scl_pin    = GPIO_I2C2_SCL,
    .scl_gpio   = GPIO_I2C2_SCL_GPIO,
    .sda_pin    = GPIO_I2C2_SDA,
    .sda_gpio   = GPIO_I2C2_SDA_GPIO,
    .ev_irq     = STM32_IRQ_I2C2EV,
    .er_irq     = STM32_IRQ_I2C2ER
};

struct stm32_i2c_priv_s stm32_i2c2_priv =
{
    .config     = &stm32_i2c2_config,
    .refs       = 0,
    .intstate   = INTSTATE_IDLE,
    .msgc       = 0,
    .msgv       = NULL,
    .ptr        = NULL,
    .dcnt       = 0,
    .flags      = 0,
    .status     = 0
};
#endif

#ifdef CONFIG_STM32_I2C3
# ifndef GPIO_I2C3_SCL_GPIO
#  define  GPIO_I2C3_SCL_GPIO 0
# endif
# ifndef GPIO_I2C3_SDA_GPIO
#  define  GPIO_I2C3_SDA_GPIO 0
# endif

static const struct stm32_i2c_config_s stm32_i2c3_config =
{
    .base       = STM32_I2C3_BASE,
#ifndef CONFIG_I2C_POLLED
    .isr        = stm32_i2c3_isr,
#endif
    .clk_bit    = RCC_APB1ENR_I2C3EN,
    .reset_bit  = RCC_APB1RSTR_I2C3RST,
    .scl_pin    = GPIO_I2C3_SCL,
    .scl_gpio   = GPIO_I2C3_SCL_GPIO,
    .sda_pin    = GPIO_I2C3_SDA,
    .sda_gpio   = GPIO_I2C3_SDA_GPIO,
    .ev_irq     = STM32_IRQ_I2C3EV,
    .er_irq     = STM32_IRQ_I2C3ER
};

struct stm32_i2c_priv_s stm32_i2c3_priv =
{
    .config     = &stm32_i2c3_config,
    .refs       = 0,
    .intstate   = INTSTATE_IDLE,
    .msgc       = 0,
    .msgv       = NULL,
    .ptr        = NULL,
    .dcnt       = 0,
    .flags      = 0,
    .status     = 0
};
#endif

/* Device Structures, Instantiation */

struct i2c_ops_s stm32_i2c_ops =
{
    .setfrequency       = stm32_i2c_setfrequency,
    .setaddress         = stm32_i2c_setaddress,
    .write              = stm32_i2c_write,
    .read               = stm32_i2c_read
#ifdef CONFIG_I2C_WRITEREAD
    , .writeread          = stm32_i2c_writeread
#endif
#ifdef CONFIG_I2C_TRANSFER
    , .transfer           = stm32_i2c_transfer
#endif
#ifdef CONFIG_I2C_SLAVE
    , .setownaddress      = stm32_i2c_setownaddress,
    .registercallback   = stm32_i2c_registercallback
#endif
};

/************************************************************************************
 * Private Functions
 ************************************************************************************/

/************************************************************************************
 * Name: stm32_i2c_getreg
 *
 * Description:
 *   Get register value by offset
 *
 ************************************************************************************/

static inline uint16_t stm32_i2c_getreg(FAR struct stm32_i2c_priv_s *priv,
                                        uint8_t offset)
{
    return getreg16(priv->config->base + offset);
}

/************************************************************************************
 * Name: stm32_i2c_putreg
 *
 * Description:
 *  Put register value by offset
 *
 ************************************************************************************/

static inline void stm32_i2c_putreg(FAR struct stm32_i2c_priv_s *priv, uint8_t offset,
                                    uint16_t value)
{
    putreg16(value, priv->config->base + offset);
}

/************************************************************************************
 * Name: stm32_i2c_modifyreg
 *
 * Description:
 *   Modify register value by offset
 *
 ************************************************************************************/

static inline void stm32_i2c_modifyreg(FAR struct stm32_i2c_priv_s *priv,
                                       uint8_t offset, uint16_t clearbits,
                                       uint16_t setbits)
{
    modifyreg16(priv->config->base + offset, clearbits, setbits);
}

/************************************************************************************
 * Name:
 *
 * Description:
 *
 *
 ************************************************************************************/

static inline void stm32_i2c_sem_wait(FAR struct i2c_dev_s *dev)
{
    while (sem_wait(&((struct stm32_i2c_inst_s *)dev)->priv->sem_excl) != 0)
    {
        ASSERT(errno == EINTR);
    }
}

/************************************************************************************
 * Name: stm32_i2c_sem_waitdone
 *
 * Description:
 *   Wait for a transfer to complete
 *
 ************************************************************************************/

#ifndef CONFIG_I2C_POLLED
static inline int stm32_i2c_sem_waitdone(FAR struct stm32_i2c_priv_s *priv, int timeout_us)
{
    struct timespec abstime;
    irqstate_t flags;
    uint32_t regval;
    int ret;
    
    flags = irqsave();
    
    /* Enable I2C interrupts */
    
    regval  = stm32_i2c_getreg(priv, STM32_I2C_CR2_OFFSET);
    regval |= (I2C_CR2_ITERREN | I2C_CR2_ITEVFEN);
    stm32_i2c_putreg(priv, STM32_I2C_CR2_OFFSET, regval);
    
    /* Signal the interrupt handler that we are waiting.  NOTE:  Interrupts
     * are currently disabled but will be temporarily re-enabled below when
     * sem_timedwait() sleeps.
     */
    
    priv->intstate = INTSTATE_WAITING;
    do
    {
        /* Get the current time */
        
        (void)clock_gettime(CLOCK_REALTIME, &abstime);
        
        /* Calculate a time in the future */
        
#if CONFIG_STM32_I2CTIMEOSEC > 0
        abstime.tv_sec += CONFIG_STM32_I2CTIMEOSEC;
#endif
#if CONFIG_STM32_I2CTIMEOUS_PER_BYTE > 0
        
        /* Count the number of bytes left to process */
        int i;
        int bytecount = 0;
        for (i = 0; i < priv->msgc; i++)
        {
            bytecount += priv->msgv[i].length;
        }
        
        abstime.tv_nsec += (CONFIG_STM32_I2CTIMEOUS_PER_BYTE * bytecount) * 1000;
        if (abstime.tv_nsec > 1000 * 1000 * 1000)
        {
            abstime.tv_sec++;
            abstime.tv_nsec -= 1000 * 1000 * 1000;
        }
        
#elif CONFIG_STM32_I2CTIMEOMS > 0
        abstime.tv_nsec += CONFIG_STM32_I2CTIMEOMS * 1000 * 1000;
        if (abstime.tv_nsec > 1000 * 1000 * 1000)
        {
            abstime.tv_sec++;
            abstime.tv_nsec -= 1000 * 1000 * 1000;
        }
#endif
        /* Wait until either the transfer is complete or the timeout expires */
        
        ret = sem_timedwait(&priv->sem_isr, &abstime);
        if (ret != OK && errno != EINTR)
        {
            /* Break out of the loop on irrecoverable errors.  This would
             * include timeouts and mystery errors reported by sem_timedwait.
             * NOTE that we try again if we are awakened by a signal (EINTR).
             */
            
            break;
        }
    }
    
    /* Loop until the interrupt level transfer is complete. */
    
    while (priv->intstate != INTSTATE_DONE);
    
    /* Set the interrupt state back to IDLE */
    
    priv->intstate = INTSTATE_IDLE;
    
    /* Disable I2C interrupts */
    
    regval  = stm32_i2c_getreg(priv, STM32_I2C_CR2_OFFSET);
    regval &= ~I2C_CR2_ALLINTS;
    stm32_i2c_putreg(priv, STM32_I2C_CR2_OFFSET, regval);
    
    irqrestore(flags);
    return ret;
}
#else
static inline int stm32_i2c_sem_waitdone(FAR struct stm32_i2c_priv_s *priv, int timeout_us)
{
    uint32_t start;
    uint32_t elapsed;
    int ret;
    
    /* Signal the interrupt handler that we are waiting.  NOTE:  Interrupts
     * are currently disabled but will be temporarily re-enabled below when
     * sem_timedwait() sleeps.
     */
    
    priv->intstate = INTSTATE_WAITING;
    start = clock_systimer();
    
    do
    {
        /* Poll by simply calling the timer interrupt handler until it
         * reports that it is done.
         */
        
        stm32_i2c_isr(priv);
        
        /* Calculate the elapsed time */
        
        elapsed = clock_systimer() - start;
    }
    
    /* Loop until the transfer is complete. */
    while (priv->intstate != INTSTATE_DONE && elapsed < USEC2TICK(timeout_us));
    
    i2cvdbg("intstate: %d elapsed: %d threshold: %d status: %08x\n",
            priv->intstate, elapsed, USEC2TICK(timeout_us), priv->status);
    
    /* Set the interrupt state back to IDLE */
    
    ret = priv->intstate == INTSTATE_DONE ? OK : -ETIMEDOUT;
    priv->intstate = INTSTATE_IDLE;
    return ret;
}
#endif

/************************************************************************************
 * Name: stm32_i2c_sem_waitstop
 *
 * Description:
 *   Wait for a STOP to complete
 *
 ************************************************************************************/

static inline void stm32_i2c_sem_waitstop(FAR struct stm32_i2c_priv_s *priv, int timeout_us)
{
    uint32_t start;
    uint32_t elapsed;
    uint32_t cr1;
    uint32_t sr1;
    
    /* Wait as stop might still be in progress; but stop might also
     * be set because of a timeout error: "The [STOP] bit is set and
     * cleared by software, cleared by hardware when a Stop condition is
     * detected, set by hardware when a timeout error is detected."
     */
    
    start = clock_systimer();
    do
    {
        /* Check for STOP condition */
        
        cr1 = stm32_i2c_getreg(priv, STM32_I2C_CR1_OFFSET);
        if ((cr1 & I2C_CR1_STOP) == 0)
        {
            return;
        }
        
        /* Check for timeout error */
        
        sr1 = stm32_i2c_getreg(priv, STM32_I2C_SR1_OFFSET);
        if ((sr1 & I2C_SR1_TIMEOUT) != 0)
        {
            return;
        }
        
        /* Calculate the elapsed time */
        
        elapsed = clock_systimer() - start;
    }
    
    /* Loop until the stop is complete or a timeout occurs. */
    
    while (elapsed < USEC2TICK(timeout_us));
    
    /* If we get here then a timeout occurred with the STOP condition
     * still pending.
     */
    
    i2cvdbg("Timeout with CR1: %04x SR1: %04x\n", cr1, sr1);
}

/************************************************************************************
 * Name: stm32_i2c_sem_post
 *
 * Description:
 *   Release the mutual exclusion semaphore
 *
 ************************************************************************************/

static inline void stm32_i2c_sem_post(FAR struct i2c_dev_s *dev)
{
    sem_post( &((struct stm32_i2c_inst_s *)dev)->priv->sem_excl );
}

/************************************************************************************
 * Name: stm32_i2c_sem_init
 *
 * Description:
 *   Initialize semaphores
 *
 ************************************************************************************/

static inline void stm32_i2c_sem_init(FAR struct i2c_dev_s *dev)
{
    sem_init(&((struct stm32_i2c_inst_s *)dev)->priv->sem_excl, 0, 1);
#ifndef CONFIG_I2C_POLLED
    sem_init(&((struct stm32_i2c_inst_s *)dev)->priv->sem_isr, 0, 0);
#endif
}

/************************************************************************************
 * Name: stm32_i2c_sem_destroy
 *
 * Description:
 *   Destroy semaphores.
 *
 ************************************************************************************/

static inline void stm32_i2c_sem_destroy(FAR struct i2c_dev_s *dev)
{
    sem_destroy(&((struct stm32_i2c_inst_s *)dev)->priv->sem_excl);
#ifndef CONFIG_I2C_POLLED
    sem_destroy(&((struct stm32_i2c_inst_s *)dev)->priv->sem_isr);
#endif
}

/************************************************************************************
 * Name: stm32_i2c_trace*
 *
 * Description:
 *   I2C trace instrumentation
 *
 ************************************************************************************/

#ifdef CONFIG_I2C_TRACE
static void stm32_i2c_traceclear(FAR struct stm32_i2c_priv_s *priv)
{
    struct stm32_trace_s *trace = &priv->trace[priv->tndx];
    
    trace->status = 0;              /* I2C 32-bit SR2|SR1 status */
    trace->count  = 0;              /* Interrupt count when status change */
    trace->event  = I2CEVENT_NONE;  /* Last event that occurred with this status */
    trace->parm   = 0;              /* Parameter associated with the event */
    trace->time   = 0;              /* Time of first status or event */
}

static void stm32_i2c_tracereset(FAR struct stm32_i2c_priv_s *priv)
{
    /* Reset the trace info for a new data collection */
    
    priv->tndx       = 0;
    priv->start_time = clock_systimer();
    stm32_i2c_traceclear(priv);
}

static void stm32_i2c_tracenew(FAR struct stm32_i2c_priv_s *priv, uint32_t status)
{
    struct stm32_trace_s *trace = &priv->trace[priv->tndx];
    
    /* Is the current entry uninitialized?   Has the status changed? */
    
    if (trace->count == 0 || status != trace->status)
    {
        /* Yes.. Was it the status changed?  */
        
        if (trace->count != 0)
        {
            /* Yes.. bump up the trace index (unless we are out of trace entries) */
            
            if (priv->tndx >= (CONFIG_I2C_NTRACE-1))
            {
                i2cdbg("Trace table overflow\n");
                return;
            }
            
            priv->tndx++;
            trace = &priv->trace[priv->tndx];
        }
        
        /* Initialize the new trace entry */
        
        stm32_i2c_traceclear(priv);
        trace->status = status;
        trace->count  = 1;
        trace->time   = clock_systimer();
    }
    else
    {
        /* Just increment the count of times that we have seen this status */
        
        trace->count++;
    }
}

static void stm32_i2c_traceevent(FAR struct stm32_i2c_priv_s *priv,
                                 enum stm32_trace_e event, uint32_t parm)
{
    struct stm32_trace_s *trace;
    
    if (event != I2CEVENT_NONE)
    {
        trace = &priv->trace[priv->tndx];
        
        /* Initialize the new trace entry */
        
        trace->event  = event;
        trace->parm   = parm;
        trace->time   = clock_systimer();
        
        /* Bump up the trace index (unless we are out of trace entries) */
        
        if (priv->tndx >= (CONFIG_I2C_NTRACE-1))
        {
            i2cdbg("Trace table overflow\n");
            return;
        }
        
        priv->tndx++;
        stm32_i2c_traceclear(priv);
    }
}

static void stm32_i2c_tracedump(FAR struct stm32_i2c_priv_s *priv)
{
    struct stm32_trace_s *trace;
    int i;
    
    syslog("Elapsed time: %d\n",  clock_systimer() - priv->start_time);
    for (i = 0; i <= priv->tndx; i++)
    {
        trace = &priv->trace[i];
        syslog("%2d. STATUS: %08x COUNT: %3d EVENT: %s PARM: %08x TIME: %d\n",
               i+1, trace->status, trace->count, stm32_trace_names[trace->event], trace->parm,
               trace->time - priv->start_time);
    }
}
#endif /* CONFIG_I2C_TRACE */

/************************************************************************************
 * Name: stm32_i2c_setclock
 *
 * Description:
 *   Set the I2C clock
 *
 ************************************************************************************/

static void stm32_i2c_setclock(FAR struct stm32_i2c_priv_s *priv, uint32_t frequency)
{
    uint16_t cr1;
    uint16_t ccr;
    uint16_t trise;
    uint16_t freqmhz;
    uint16_t speed;
    
    /* Disable the selected I2C peripheral to configure TRISE */
    
    cr1 = stm32_i2c_getreg(priv, STM32_I2C_CR1_OFFSET);
    stm32_i2c_putreg(priv, STM32_I2C_CR1_OFFSET, cr1 & ~I2C_CR1_PE);
    
    /* Update timing and control registers */
    
    freqmhz = (uint16_t)(STM32_PCLK1_FREQUENCY / 1000000);
    ccr = 0;
    
    /* Configure speed in standard mode */
    
    if (frequency <= 100000)
    {
        /* Standard mode speed calculation */
        
        speed = (uint16_t)(STM32_PCLK1_FREQUENCY / (frequency << 1));
        
        /* The CCR fault must be >= 4 */
        
        if (speed < 4)
        {
            /* Set the minimum allowed value */
            
            speed = 4;
        }
        ccr |= speed;
        
        /* Set Maximum Rise Time for standard mode */
        
        trise = freqmhz + 1;
    }
    
    /* Configure speed in fast mode */
    
    else /* (frequency <= 400000) */
    {
        /* Fast mode speed calculation with Tlow/Thigh = 16/9 */
        
#ifdef CONFIG_STM32_I2C_DUTY16_9
        speed = (uint16_t)(STM32_PCLK1_FREQUENCY / (frequency * 25));
        
        /* Set DUTY and fast speed bits */
        
        ccr |= (I2C_CCR_DUTY|I2C_CCR_FS);
#else
        /* Fast mode speed calculation with Tlow/Thigh = 2 */
        
        speed = (uint16_t)(STM32_PCLK1_FREQUENCY / (frequency * 3));
        
        /* Set fast speed bit */
        
        ccr |= I2C_CCR_FS;
#endif
        
        /* Verify that the CCR speed value is nonzero */
        
        if (speed < 1)
        {
            /* Set the minimum allowed value */
            
            speed = 1;
        }
        ccr |= speed;
        
        /* Set Maximum Rise Time for fast mode */
        
        trise = (uint16_t)(((freqmhz * 300) / 1000) + 1);
    }
    
    /* Write the new values of the CCR and TRISE registers */
    
    stm32_i2c_putreg(priv, STM32_I2C_CCR_OFFSET, ccr);
    stm32_i2c_putreg(priv, STM32_I2C_TRISE_OFFSET, trise);
    
    /* Bit 14 of OAR1 must be configured and kept at 1 */
    
    stm32_i2c_putreg(priv, STM32_I2C_OAR1_OFFSET, I2C_OAR1_ONE);
    
    /* Re-enable the peripheral (or not) */
    
    stm32_i2c_putreg(priv, STM32_I2C_CR1_OFFSET, cr1);
}

/************************************************************************************
 * Name: stm32_i2c_sendstart
 *
 * Description:
 *   Send the START conditions/force Master mode
 *
 ************************************************************************************/

static inline void stm32_i2c_sendstart(FAR struct stm32_i2c_priv_s *priv)
{
    /* Disable ACK on receive by default and generate START */
    
    stm32_i2c_modifyreg(priv, STM32_I2C_CR1_OFFSET, I2C_CR1_ACK, I2C_CR1_START);
}

/************************************************************************************
 * Name: stm32_i2c_clrstart
 *
 * Description:
 *   Clear the STOP, START or PEC condition on certain error recovery steps.
 *
 ************************************************************************************/

static inline void stm32_i2c_clrstart(FAR struct stm32_i2c_priv_s *priv)
{
    /* "Note: When the STOP, START or PEC bit is set, the software must
     *  not perform any write access to I2C_CR1 before this bit is
     *  cleared by hardware. Otherwise there is a risk of setting a
     *  second STOP, START or PEC request."
     *
     * "The [STOP] bit is set and cleared by software, cleared by hardware
     *  when a Stop condition is detected, set by hardware when a timeout
     *  error is detected.
     *
     * "This [START] bit is set and cleared by software and cleared by hardware
     *  when start is sent or PE=0."  The bit must be cleared by software if the
     *  START is never sent.
     *
     * "This [PEC] bit is set and cleared by software, and cleared by hardware
     *  when PEC is transferred or by a START or Stop condition or when PE=0."
     */
    
    stm32_i2c_modifyreg(priv, STM32_I2C_CR1_OFFSET,
                        I2C_CR1_START|I2C_CR1_STOP|I2C_CR1_PEC, 0);
}

/************************************************************************************
 * Name: stm32_i2c_sendstop
 *
 * Description:
 *   Send the STOP conditions
 *
 ************************************************************************************/

static inline void stm32_i2c_sendstop(FAR struct stm32_i2c_priv_s *priv)
{
    stm32_i2c_modifyreg(priv, STM32_I2C_CR1_OFFSET, I2C_CR1_ACK, I2C_CR1_STOP);
}

/************************************************************************************
 * Name: stm32_i2c_getstatus
 *
 * Description:
 *   Get 32-bit status (SR1 and SR2 combined)
 *
 ************************************************************************************/

static inline uint32_t stm32_i2c_getstatus(FAR struct stm32_i2c_priv_s *priv)
{
    uint32_t status = stm32_i2c_getreg(priv, STM32_I2C_SR1_OFFSET);
    status |= (stm32_i2c_getreg(priv, STM32_I2C_SR2_OFFSET) << 16);
    return status;
}

/************************************************************************************
 * Name: stm32_i2c_disablefsmc
 *
 * Description:
 *   FSMC must be disable while accessing I2C1 because it uses a common resource
 *   (LBAR)
 *
 *  NOTE: This is an issue with the STM32F103ZE, but may not be an issue with other
 *  STM32s.  You may need to experiment
 *
 ************************************************************************************/

#ifdef I2C1_FSMC_CONFLICT
static inline uint32_t stm32_i2c_disablefsmc(FAR struct stm32_i2c_priv_s *priv)
{
    uint32_t ret = 0;
    uint32_t regval;
    
    /* Is this I2C1 */
    
#if defined(CONFIG_STM32_I2C2) || defined(CONFIG_STM32_I2C3)
    if (priv->config->base == STM32_I2C1_BASE)
#endif
    {
        /* Disable FSMC unconditionally */
        
        ret    = getreg32( STM32_RCC_AHBENR);
        regval = ret & ~RCC_AHBENR_FSMCEN;
        putreg32(regval, STM32_RCC_AHBENR);
    }
    return ret;
}

/************************************************************************************
 * Name: stm32_i2c_enablefsmc
 *
 * Description:
 *   Re-enabled the FSMC
 *
 ************************************************************************************/

static inline void stm32_i2c_enablefsmc(uint32_t ahbenr)
{
    uint32_t regval;
    
    /* Enable AHB clocking to the FSMC only if it was previously enabled. */
    
    if ((ahbenr & RCC_AHBENR_FSMCEN) != 0)
    {
        regval  = getreg32( STM32_RCC_AHBENR);
        regval |= RCC_AHBENR_FSMCEN;
        putreg32(regval, STM32_RCC_AHBENR);
    }
}
#else
#  define stm32_i2c_disablefsmc(priv) (0)
#  define stm32_i2c_enablefsmc(ahbenr)
#endif /* I2C1_FSMC_CONFLICT */

/************************************************************************************
 * Name: stm32_i2c_isr
 *
 * Description:
 *  Common Interrupt Service Routine
 *
 ************************************************************************************/

static int stm32_i2c_isr(struct stm32_i2c_priv_s *priv)
{
    uint32_t status = stm32_i2c_getstatus(priv);
    
    /* Check for new trace setup */
    
    stm32_i2c_tracenew(priv, status);
    
    /* Was start bit sent */
    
    if ((status & I2C_SR1_SB) != 0)
    {
        stm32_i2c_traceevent(priv, I2CEVENT_SENDADDR, priv->msgc);

        /*
          we check for msgc > 0 here as an unexpected interrupt with
          I2C_SR1_SB set due to noise on the I2C cable can otherwise
          cause msgc to wrap causing memory overwrite
         */
        if (priv->msgc > 0 && priv->msgv != NULL) {
            /* Get run-time data */
        
            priv->ptr   = priv->msgv->buffer;
            priv->dcnt  = priv->msgv->length;
            priv->flags = priv->msgv->flags;
        
            /* Send address byte and define addressing mode */
        
            stm32_i2c_putreg(priv, STM32_I2C_DR_OFFSET,
                             (priv->flags & I2C_M_TEN) ?
                             0 : ((priv->msgv->addr << 1) | (priv->flags & I2C_M_READ)));
        
            /* Set ACK for receive mode */
            
            if (priv->dcnt > 1 && (priv->flags & I2C_M_READ) != 0)
            {
                stm32_i2c_modifyreg(priv, STM32_I2C_CR1_OFFSET, 0, I2C_CR1_ACK);
            }
        
            /* Increment to next pointer and decrement message count */
        
            priv->msgv++;
            priv->msgc--;
        } else {
            /* clear ISR by writing to DR register */
            stm32_i2c_putreg(priv, STM32_I2C_DR_OFFSET, 0);
        }
    }
    
    /* In 10-bit addressing mode, was first byte sent */
    
    else if ((status & I2C_SR1_ADD10) != 0)
    {
        /* TODO: Finish 10-bit mode addressing
           for now just clear ISR by writing to DR register. As we
           don't do 10 bit addressing this must be a spurious ISR
        */
        stm32_i2c_putreg(priv, STM32_I2C_DR_OFFSET, 0);
    }
    
    /* Was address sent, continue with either sending or reading data */
    
    else if ((priv->flags & I2C_M_READ) == 0 && (status & (I2C_SR1_ADDR | I2C_SR1_TXE)) != 0)
    {
        if (priv->dcnt > 0)
        {
            /* Send a byte */
            
            stm32_i2c_traceevent(priv, I2CEVENT_SENDBYTE, priv->dcnt);
            stm32_i2c_putreg(priv, STM32_I2C_DR_OFFSET, *priv->ptr++);
            priv->dcnt--;
        }
    }
    
    else if ((priv->flags & I2C_M_READ) != 0 && (status & I2C_SR1_ADDR) != 0)
    {
        /* Enable RxNE and TxE buffers in order to receive one or multiple bytes */
        
#ifndef CONFIG_I2C_POLLED
        stm32_i2c_traceevent(priv, I2CEVENT_ITBUFEN, 0);
        stm32_i2c_modifyreg(priv, STM32_I2C_CR2_OFFSET, 0, I2C_CR2_ITBUFEN);
#endif
    }
    
    /* More bytes to read */
    
    else if ((status & I2C_SR1_RXNE) != 0)
    {
        /* Read a byte, if dcnt goes < 0, then read dummy bytes to ack ISRs */
        
        if (priv->dcnt > 0)
        {
            stm32_i2c_traceevent(priv, I2CEVENT_RCVBYTE, priv->dcnt);
            
            /* No interrupts or context switches may occur in the following
             * sequence.  Otherwise, additional bytes may be sent by the
             * device.
             */
            
#ifdef CONFIG_I2C_POLLED
            irqstate_t state = irqsave();
#endif
            /* Receive a byte */
            
            *priv->ptr++ = stm32_i2c_getreg(priv, STM32_I2C_DR_OFFSET);
            
            /* Disable acknowledge when last byte is to be received */
            
            priv->dcnt--;
            if (priv->dcnt == 1)
            {
                stm32_i2c_modifyreg(priv, STM32_I2C_CR1_OFFSET, I2C_CR1_ACK, 0);
            }
            
#ifdef CONFIG_I2C_POLLED
            irqrestore(state);
#endif
        } else {
            // throw away the unexpected byte
            stm32_i2c_getreg(priv, STM32_I2C_DR_OFFSET);
        }
    } else if (status & I2C_SR1_TXE) {
	    /* this should never happen, but it does happen
	       occasionally with lots of noise on the bus. It means the
	       peripheral is expecting more data bytes, but we don't have
	       any to give.
	       This has been seen with status=0x70084, reproduced with
	       noise generated by a Jabra wireless headset in close
	       proximity to the I2C lines
	    */
            stm32_i2c_putreg(priv, STM32_I2C_DR_OFFSET, 0);
    } else if (status & I2C_SR1_BTF) {
	    /*
	      we should have handled all cases where this could happen
	      above, but just to ensure it gets acked, lets clear it here
	     */
            stm32_i2c_getreg(priv, STM32_I2C_DR_OFFSET);
    } else if (status & I2C_SR1_STOPF) {
	    /*
	      we should never get this, as we are a master not a
	      slave. Write CR1 with its current value to clear the
	      error
	     */
	    stm32_i2c_modifyreg(priv, STM32_I2C_CR1_OFFSET, 0, 0);
    }
    
    /* Do we have more bytes to send, enable/disable buffer interrupts
     * (these ISRs could be replaced by DMAs)
     */
    
#ifndef CONFIG_I2C_POLLED
    if (priv->dcnt > 0)
    {
        stm32_i2c_traceevent(priv, I2CEVENT_REITBUFEN, 0);
        stm32_i2c_modifyreg(priv, STM32_I2C_CR2_OFFSET, 0, I2C_CR2_ITBUFEN);
    }
    else if (priv->dcnt == 0)
    {
        stm32_i2c_traceevent(priv, I2CEVENT_DISITBUFEN, 0);
        stm32_i2c_modifyreg(priv, STM32_I2C_CR2_OFFSET, I2C_CR2_ITBUFEN, 0);
    }
#endif
    
    /* Was last byte received or sent?  Hmmm... the F2 and F4 seems to differ from
     * the F1 in that BTF is not set after data is received (only RXNE).
     */
    
#if defined(CONFIG_STM32_STM32F20XX) || defined(CONFIG_STM32_STM32F40XX)
    if (priv->dcnt <= 0 && (status & (I2C_SR1_BTF|I2C_SR1_RXNE)) != 0)
#else
        if (priv->dcnt <= 0 && (status & I2C_SR1_BTF) != 0)
#endif
        {
            stm32_i2c_getreg(priv, STM32_I2C_DR_OFFSET);    /* ACK ISR */
            
            /* Do we need to terminate or restart after this byte?
             * If there are more messages to send, then we may:
             *
             *  - continue with repeated start
             *  - or just continue sending writeable part
             *  - or we close down by sending the stop bit
             */
            
            if (priv->msgc > 0)
            {
                if (priv->msgv->flags & I2C_M_NORESTART)
                {
                    stm32_i2c_traceevent(priv, I2CEVENT_BTFNOSTART, priv->msgc);
                    priv->ptr   = priv->msgv->buffer;
                    priv->dcnt  = priv->msgv->length;
                    priv->flags = priv->msgv->flags;
                    priv->msgv++;
                    priv->msgc--;
                    
                    /* Restart this ISR! */
                    
#ifndef CONFIG_I2C_POLLED
                    stm32_i2c_modifyreg(priv, STM32_I2C_CR2_OFFSET, 0, I2C_CR2_ITBUFEN);
#endif
                }
                else
                {
                    stm32_i2c_traceevent(priv, I2CEVENT_BTFRESTART, priv->msgc);
                    stm32_i2c_sendstart(priv);
                }
            }
            else if (priv->msgv)
            {
                stm32_i2c_traceevent(priv, I2CEVENT_BTFSTOP, 0);
                stm32_i2c_sendstop(priv);
                
                /* Is there a thread waiting for this event (there should be) */
                
#ifndef CONFIG_I2C_POLLED
                if (priv->intstate == INTSTATE_WAITING)
                {
                    /* Yes.. inform the thread that the transfer is complete
                     * and wake it up.
                     */
                    
                    sem_post( &priv->sem_isr );
                    priv->intstate = INTSTATE_DONE;
                }
#else
                priv->intstate = INTSTATE_DONE;
#endif
                
                /* Mark that we have stopped with this transaction */
                
                priv->msgv = NULL;
            }
        }
    
    /* Check for errors, in which case, stop the transfer and return
     * Note that in master reception mode AF becomes set on last byte
     * since ACK is not returned. We should ignore this error.
     */
    
    if ((status & I2C_SR1_ERRORMASK) != 0)
    {
        stm32_i2c_traceevent(priv, I2CEVENT_ERROR, 0);
        
        /* Clear interrupt flags */
        
        stm32_i2c_putreg(priv, STM32_I2C_SR1_OFFSET, 0);
        
        /* Is there a thread waiting for this event (there should be) */
        
#ifndef CONFIG_I2C_POLLED
        if (priv->intstate == INTSTATE_WAITING)
        {
            /* Yes.. inform the thread that the transfer is complete
             * and wake it up.
             */
            
            sem_post( &priv->sem_isr );
            priv->intstate = INTSTATE_DONE;
        }
#else
        priv->intstate = INTSTATE_DONE;
#endif
    }
    
    priv->status = status;
    return OK;
}

/************************************************************************************
 * Name: stm32_i2c1_isr
 *
 * Description:
 *   I2C1 interrupt service routine
 *
 ************************************************************************************/

#ifndef CONFIG_I2C_POLLED
#ifdef CONFIG_STM32_I2C1
static int stm32_i2c1_isr(int irq, void *context)
{
    return stm32_i2c_isr(&stm32_i2c1_priv);
}
#endif

/************************************************************************************
 * Name: stm32_i2c2_isr
 *
 * Description:
 *   I2C2 interrupt service routine
 *
 ************************************************************************************/

#ifdef CONFIG_STM32_I2C2
static int stm32_i2c2_isr(int irq, void *context)
{
    return stm32_i2c_isr(&stm32_i2c2_priv);
}
#endif

/************************************************************************************
 * Name: stm32_i2c3_isr
 *
 * Description:
 *   I2C2 interrupt service routine
 *
 ************************************************************************************/

#ifdef CONFIG_STM32_I2C3
static int stm32_i2c3_isr(int irq, void *context)
{
    return stm32_i2c_isr(&stm32_i2c3_priv);
}
#endif
#endif

/************************************************************************************
 * Private Initialization and Deinitialization
 ************************************************************************************/

/************************************************************************************
 * Name: stm32_i2c_init
 *
 * Description:
 *   Setup the I2C hardware, ready for operation with defaults
 *
 ************************************************************************************/

static int stm32_i2c_init(FAR struct stm32_i2c_priv_s *priv)
{
    /* Power-up and configure GPIOs */
    
    /* Enable power and reset the peripheral */
    
    modifyreg32(STM32_RCC_APB1ENR, 0, priv->config->clk_bit);
    modifyreg32(STM32_RCC_APB1RSTR, 0, priv->config->reset_bit);
    modifyreg32(STM32_RCC_APB1RSTR, priv->config->reset_bit, 0);
    
    /* Configure pins */
    
    if (stm32_configgpio(priv->config->scl_pin) < 0)
    {
        return ERROR;
    }
    
    if (stm32_configgpio(priv->config->sda_pin) < 0)
    {
        stm32_unconfiggpio(priv->config->scl_pin);
        return ERROR;
    }
    
    /* Attach ISRs */
    
#ifndef CONFIG_I2C_POLLED
    irq_attach(priv->config->ev_irq, priv->config->isr);
    irq_attach(priv->config->er_irq, priv->config->isr);
    up_enable_irq(priv->config->ev_irq);
    up_enable_irq(priv->config->er_irq);
#endif
    
    /* Set peripheral frequency, where it must be at least 2 MHz  for 100 kHz
     * or 4 MHz for 400 kHz.  This also disables all I2C interrupts.
     */
    
    stm32_i2c_putreg(priv, STM32_I2C_CR2_OFFSET, (STM32_PCLK1_FREQUENCY / 1000000));
    stm32_i2c_setclock(priv, 100000);
    
    /* Enable I2C */
    
    stm32_i2c_putreg(priv, STM32_I2C_CR1_OFFSET, I2C_CR1_PE);
    return OK;
}

/************************************************************************************
 * Name: stm32_i2c_deinit
 *
 * Description:
 *   Shutdown the I2C hardware
 *
 ************************************************************************************/

static int stm32_i2c_deinit(FAR struct stm32_i2c_priv_s *priv)
{
    /* Disable I2C */
    
    stm32_i2c_putreg(priv, STM32_I2C_CR1_OFFSET, 0);
    
    /* Unconfigure GPIO pins */
    
    stm32_unconfiggpio(priv->config->scl_pin);
    stm32_unconfiggpio(priv->config->sda_pin);
    
    /* Disable and detach interrupts */
    
#ifndef CONFIG_I2C_POLLED
    up_disable_irq(priv->config->ev_irq);
    up_disable_irq(priv->config->er_irq);
    irq_detach(priv->config->ev_irq);
    irq_detach(priv->config->er_irq);
#endif
    
    /* Disable clocking */
    
    modifyreg32(STM32_RCC_APB1ENR, priv->config->clk_bit, 0);
    return OK;
}

/************************************************************************************
 * Device Driver Operations
 ************************************************************************************/

/************************************************************************************
 * Name: stm32_i2c_setfrequency
 *
 * Description:
 *   Set the I2C frequency
 *
 ************************************************************************************/

static uint32_t stm32_i2c_setfrequency(FAR struct i2c_dev_s *dev, uint32_t frequency)
{
    stm32_i2c_sem_wait(dev);
    
#if STM32_PCLK1_FREQUENCY < 4000000
    ((struct stm32_i2c_inst_s *)dev)->frequency = 100000;
#else
    ((struct stm32_i2c_inst_s *)dev)->frequency = frequency;
#endif
    
    stm32_i2c_sem_post(dev);
    return ((struct stm32_i2c_inst_s *)dev)->frequency;
}

/************************************************************************************
 * Name: stm32_i2c_setaddress
 *
 * Description:
 *   Set the I2C slave address
 *
 ************************************************************************************/

static int stm32_i2c_setaddress(FAR struct i2c_dev_s *dev, int addr, int nbits)
{
    stm32_i2c_sem_wait(dev);
    
    ((struct stm32_i2c_inst_s *)dev)->address = addr;
    ((struct stm32_i2c_inst_s *)dev)->flags   = (nbits == 10) ? I2C_M_TEN : 0;
    
    stm32_i2c_sem_post(dev);
    return OK;
}

/************************************************************************************
 * Name: stm32_i2c_process
 *
 * Description:
 *   Common I2C transfer logic
 *
 ************************************************************************************/

static int stm32_i2c_process(FAR struct i2c_dev_s *dev, FAR struct i2c_msg_s *msgs, int count)
{
    struct stm32_i2c_inst_s     *inst = (struct stm32_i2c_inst_s *)dev;
    FAR struct stm32_i2c_priv_s *priv = inst->priv;
    uint32_t    status = 0;
    //uint32_t    ahbenr;
    int         errval = 0;
    
    ASSERT(count);
    
    /* Disable FSMC that shares a pin with I2C1 (LBAR) */
    
    (void)stm32_i2c_disablefsmc(priv);
    
    /* Wait for any STOP in progress.  NOTE:  If we have to disable the FSMC
     * then we cannot do this at the top of the loop, unfortunately.  The STOP
     * will not complete normally if the FSMC is enabled.
     */
    
#ifndef I2C1_FSMC_CONFLICT
#if CONFIG_STM32_I2CTIMEOUS_START_STOP > 0
    stm32_i2c_sem_waitstop(priv, CONFIG_STM32_I2CTIMEOUS_START_STOP);
#else
    stm32_i2c_sem_waitstop(priv, CONFIG_STM32_I2CTIMEOMS * 1000UL + CONFIG_STM32_I2CTIMEOSEC * 1000000UL);
#endif
#endif
    
    /* Clear any pending error interrupts */
    
    stm32_i2c_putreg(priv, STM32_I2C_SR1_OFFSET, 0);
    
    /* "Note: When the STOP, START or PEC bit is set, the software must
     *  not perform any write access to I2C_CR1 before this bit is
     *  cleared by hardware. Otherwise there is a risk of setting a
     *  second STOP, START or PEC request."  However, if the bits are
     *  not cleared by hardware, then we will have to do that from hardware.
     */
    
    stm32_i2c_clrstart(priv);
    
    /* Old transfers are done */

    /* reset ptr and dcnt to ensure an unexpected data 
       interrupt doesn't overwrite stale data */
    priv->dcnt = 0;
    priv->ptr = NULL;

    priv->msgv = msgs;
    priv->msgc = count;
    
    /* Calculate timeout values */
    int timeout_us = 0;
#if CONFIG_STM32_I2CTIMEOUS_PER_BYTE > 0
    /* Count the number of bytes left to process */
    int i;
    int bytecount = 10;
    for (i = 0; i < count; i++)
    {
        bytecount += msgs[i].length;
    }
    timeout_us = CONFIG_STM32_I2CTIMEOUS_PER_BYTE * bytecount;
    //i2cvdbg("i2c wait: %d\n", timeout_us);
#else
    timeout_us = CONFIG_STM32_I2CTIMEOMS * 1000UL + CONFIG_STM32_I2CTIMEOSEC * 1000000UL;
#endif
    
    /* Reset I2C trace logic */
    
    stm32_i2c_tracereset(priv);
    
    /* Set I2C clock frequency (on change it toggles I2C_CR1_PE !) */
    
    stm32_i2c_setclock(priv, inst->frequency);
    
    /* Trigger start condition, then the process moves into the ISR.  I2C
     * interrupts will be enabled within stm32_i2c_waitdone().
     */
    
    priv->status = 0;
    stm32_i2c_sendstart(priv);
    
    /* Wait for an ISR, if there was a timeout, fetch latest status to get
     * the BUSY flag.
     */
    
    if (stm32_i2c_sem_waitdone(priv, timeout_us) < 0)
    {
        status = stm32_i2c_getstatus(priv);
        errval = ETIMEDOUT;
        
        i2cdbg("Timed out: CR1: %04x status: %08x after %d\n",
               stm32_i2c_getreg(priv, STM32_I2C_CR1_OFFSET), status, timeout_us);
        
        /* "Note: When the STOP, START or PEC bit is set, the software must
         *  not perform any write access to I2C_CR1 before this bit is
         *  cleared by hardware. Otherwise there is a risk of setting a
         *  second STOP, START or PEC request."
         */
        
        stm32_i2c_clrstart(priv);
        
        /* Clear busy flag in case of timeout */
        
        status = priv->status & 0xffff;
    }
    else
    {
        /* clear SR2 (BUSY flag) as we've done successfully */
        
        status = priv->status & 0xffff;
    }
    
    /* Check for error status conditions */
    
    if ((status & I2C_SR1_ERRORMASK) != 0)
    {
        /* I2C_SR1_ERRORMASK is the 'OR' of the following individual bits: */
        
        if (status & I2C_SR1_BERR)
        {
            /* Bus Error */
            
            errval = EIO;
        }
        else if (status & I2C_SR1_ARLO)
        {
            /* Arbitration Lost (master mode) */
            
            errval = EAGAIN;
        }
        else if (status & I2C_SR1_AF)
        {
            /* Acknowledge Failure */
            
            errval = ENXIO;
        }
        else if (status & I2C_SR1_OVR)
        {
            /* Overrun/Underrun */
            
            errval = EIO;
        }
        else if (status & I2C_SR1_PECERR)
        {
            /* PEC Error in reception */
            
            errval = EPROTO;
        }
        else if (status & I2C_SR1_TIMEOUT)
        {
            /* Timeout or Tlow Error */
            
            errval = ETIME;
        }
        
        /* This is not an error and should never happen since SMBus is not enabled */
        
        else /* if (status & I2C_SR1_SMBALERT) */
        {
            /* SMBus alert is an optional signal with an interrupt line for devices
             * that want to trade their ability to master for a pin.
             */
            
            errval = EINTR;
        }
    }
    
    /* This is not an error, but should not happen.  The BUSY signal can hang,
     * however, if there are unhealthy devices on the bus that need to be reset.
     * NOTE:  We will only see this buy indication if stm32_i2c_sem_waitdone()
     * fails above;  Otherwise it is cleared.
     */
    
    else if ((status & (I2C_SR2_BUSY << 16)) != 0)
    {
        /* I2C Bus is for some reason busy */
        
        errval = EBUSY;
    }
    
    /* Dump the trace result */
    
    stm32_i2c_tracedump(priv);
    
    /* Wait for any STOP in progress.  NOTE:  If we have to disable the FSMC
     * then we cannot do this at the top of the loop, unfortunately.  The STOP
     * will not complete normally if the FSMC is enabled.
     */
    
#ifdef I2C1_FSMC_CONFLICT
    stm32_i2c_sem_waitstop(priv);
#endif
    
    /* Re-enable the FSMC */
    
    stm32_i2c_enablefsmc(ahbenr);

    /* ensure that any ISR happening after we finish can't overwrite any user data */
    priv->dcnt = 0;
    priv->ptr = NULL;
    
    stm32_i2c_sem_post(dev);

    return -errval;
}

/************************************************************************************
 * Name: stm32_i2c_write
 *
 * Description:
 *   Write I2C data
 *
 ************************************************************************************/

static int stm32_i2c_write(FAR struct i2c_dev_s *dev, const uint8_t *buffer, int buflen)
{
    stm32_i2c_sem_wait(dev);   /* ensure that address or flags don't change meanwhile */
    
    struct i2c_msg_s msgv =
    {
        .addr   = ((struct stm32_i2c_inst_s *)dev)->address,
        .flags  = ((struct stm32_i2c_inst_s *)dev)->flags,
        .buffer = (uint8_t *)buffer,
        .length = buflen
    };
    
    return stm32_i2c_process(dev, &msgv, 1);
}

/************************************************************************************
 * Name: stm32_i2c_read
 *
 * Description:
 *   Read I2C data
 *
 ************************************************************************************/

int stm32_i2c_read(FAR struct i2c_dev_s *dev, uint8_t *buffer, int buflen)
{
    stm32_i2c_sem_wait(dev);   /* ensure that address or flags don't change meanwhile */
    
    struct i2c_msg_s msgv =
    {
        .addr   = ((struct stm32_i2c_inst_s *)dev)->address,
        .flags  = ((struct stm32_i2c_inst_s *)dev)->flags | I2C_M_READ,
        .buffer = buffer,
        .length = buflen
    };
    
    return stm32_i2c_process(dev, &msgv, 1);
}

/************************************************************************************
 * Name: stm32_i2c_writeread
 *
 * Description:
 *  Read then write I2C data
 *
 ************************************************************************************/

#ifdef CONFIG_I2C_WRITEREAD
static int stm32_i2c_writeread(FAR struct i2c_dev_s *dev,
                               const uint8_t *wbuffer, int wbuflen,
                               uint8_t *buffer, int buflen)
{
    stm32_i2c_sem_wait(dev);   /* ensure that address or flags don't change meanwhile */
    
    struct i2c_msg_s msgv[2] =
    {
        {
            .addr   = ((struct stm32_i2c_inst_s *)dev)->address,
            .flags  = ((struct stm32_i2c_inst_s *)dev)->flags,
            .buffer = (uint8_t *)wbuffer,          /* this is really ugly, sorry const ... */
            .length = wbuflen
        },
        {
            .addr   = ((struct stm32_i2c_inst_s *)dev)->address,
            .flags  = ((struct stm32_i2c_inst_s *)dev)->flags | ((buflen>0) ? I2C_M_READ : I2C_M_NORESTART),
            .buffer = buffer,
            .length = (buflen>0) ? buflen : -buflen
        }
    };
    
    return stm32_i2c_process(dev, msgv, 2);
}
#endif

/************************************************************************************
 * Name: stm32_i2c_transfer
 *
 * Description:
 *   Generic I2C transfer function
 *
 ************************************************************************************/

#ifdef CONFIG_I2C_TRANSFER
static int stm32_i2c_transfer(FAR struct i2c_dev_s *dev, FAR struct i2c_msg_s *msgs,
                              int count)
{
    stm32_i2c_sem_wait(dev);   /* ensure that address or flags don't change meanwhile */
    return stm32_i2c_process(dev, msgs, count);
}
#endif

/************************************************************************************
 * Public Functions
 ************************************************************************************/

/************************************************************************************
 * Name: up_i2cinitialize
 *
 * Description:
 *   Initialize one I2C bus
 *
 ************************************************************************************/

FAR struct i2c_dev_s *up_i2cinitialize(int port)
{
    struct stm32_i2c_priv_s * priv = NULL;  /* private data of device with multiple instances */
    struct stm32_i2c_inst_s * inst = NULL;  /* device, single instance */
    int irqs;
    
#if STM32_PCLK1_FREQUENCY < 4000000
#   warning STM32_I2C_INIT: Peripheral clock must be at least 4 MHz to support 400 kHz operation.
#endif
    
#if STM32_PCLK1_FREQUENCY < 2000000
#   warning STM32_I2C_INIT: Peripheral clock must be at least 2 MHz to support 100 kHz operation.
    return NULL;
#endif
    
    /* Get I2C private structure */
    
    switch (port)
    {
#ifdef CONFIG_STM32_I2C1
        case 1:
            priv = (struct stm32_i2c_priv_s *)&stm32_i2c1_priv;
            break;
#endif
#ifdef CONFIG_STM32_I2C2
        case 2:
            priv = (struct stm32_i2c_priv_s *)&stm32_i2c2_priv;
            break;
#endif
#ifdef CONFIG_STM32_I2C3
        case 3:
            priv = (struct stm32_i2c_priv_s *)&stm32_i2c3_priv;
            break;
#endif
        default:
            return NULL;
    }
    
    /* Allocate instance */
    
    if (!(inst = kmalloc( sizeof(struct stm32_i2c_inst_s))))
    {
        return NULL;
    }
    
    /* Initialize instance */
    
    inst->ops       = &stm32_i2c_ops;
    inst->priv      = priv;
    inst->frequency = 100000;
    inst->address   = 0;
    inst->flags     = 0;
    
    /* Init private data for the first time, increment refs count,
     * power-up hardware and configure GPIOs.
     */
    
    irqs = irqsave();
    
    if ((volatile int)priv->refs++ == 0)
    {
        stm32_i2c_sem_init( (struct i2c_dev_s *)inst );
        stm32_i2c_init( priv );
    }
    
    irqrestore(irqs);
    return (struct i2c_dev_s *)inst;
}

/************************************************************************************
 * Name: up_i2cuninitialize
 *
 * Description:
 *   Uninitialize an I2C bus
 *
 ************************************************************************************/

int up_i2cuninitialize(FAR struct i2c_dev_s * dev)
{
    int irqs;
    
    ASSERT(dev);
    
    /* Decrement refs and check for underflow */
    
    if (((struct stm32_i2c_inst_s *)dev)->priv->refs == 0)
    {
        return ERROR;
    }
    
    irqs = irqsave();
    
    if (--((struct stm32_i2c_inst_s *)dev)->priv->refs)
    {
        irqrestore(irqs);
        kfree(dev);
        return OK;
    }
    
    irqrestore(irqs);
    
    /* Disable power and other HW resource (GPIO's) */
    
    stm32_i2c_deinit( ((struct stm32_i2c_inst_s *)dev)->priv );
    
    /* Release unused resources */
    
    stm32_i2c_sem_destroy( (struct i2c_dev_s *)dev );
    
    kfree(dev);
    return OK;
}

/************************************************************************************
 * Name: up_i2creset
 *
 * Description:
 *   Reset an I2C bus
 *
 ************************************************************************************/

int up_i2creset(FAR struct i2c_dev_s * dev)
{
    struct stm32_i2c_priv_s * priv;
    unsigned clock_count;
    unsigned stretch_count;
    int ret = ERROR;
    irqstate_t state;
    
    ASSERT(dev);
    
    /* Get I2C private structure */
    
    priv = ((struct stm32_i2c_inst_s *)dev)->priv;
    
    /* Our caller must own a ref */
    
    ASSERT(priv->refs > 0);
    
    /* Lock out other clients */
    
    stm32_i2c_sem_wait(dev);
    
    /* De-init the port */
    
    stm32_i2c_deinit(priv);
    
    /* If possible, use GPIO configuration to un-wedge the bus */
    
    if ((priv->config->scl_gpio != 0) && (priv->config->sda_gpio != 0))
    {
        stm32_configgpio(priv->config->scl_gpio);
        stm32_configgpio(priv->config->sda_gpio);
        
        /*
         * Clock the bus until any slaves currently driving it let it go.
         */
        
        clock_count = 0;
        while (!stm32_gpioread(priv->config->sda_gpio)) 
        {
            
            /* Give up if we have tried too hard */
            
            if (clock_count++ > CONFIG_STM32_I2CTIMEOTICKS)
            { 
                goto out;
            }
            
            /*
             * Sniff to make sure that clock stretching has finished.
             *
             * If the bus never relaxes, the reset has failed.
             */
            
            stretch_count = 0;
            while (!stm32_gpioread(priv->config->scl_gpio))
            { 
                
                /* Give up if we have tried too hard */
                
                if (stretch_count++ > 1000)
                { 
                    goto out;
                }
                
                up_udelay(10);
                
            }
            
            /* Drive SCL low */
            
            stm32_gpiowrite(priv->config->scl_gpio, 0);
            up_udelay(10);
            
            /* Drive SCL high again */
            
            stm32_gpiowrite(priv->config->scl_gpio, 1);
            up_udelay(10);
            
        }
        
        /*
         * Generate a start followed by a stop to reset slave
         * state machines.
         */
        
        stm32_gpiowrite(priv->config->sda_gpio, 0);
        up_udelay(10);
        stm32_gpiowrite(priv->config->scl_gpio, 0);
        up_udelay(10);
        stm32_gpiowrite(priv->config->scl_gpio, 1);
        up_udelay(10);
        stm32_gpiowrite(priv->config->sda_gpio, 1);
        up_udelay(10);
        
        /*
         * Revert the GPIO configuration.
         */
        stm32_unconfiggpio(priv->config->sda_gpio);
        stm32_unconfiggpio(priv->config->scl_gpio);
        
    }
    
    /* Re-init the port */
    
    stm32_i2c_init(priv);
    ret = OK;
    
out:
    
    /* release the port for re-use by other clients */
    
    stm32_i2c_sem_post(dev);
    
    return ret;
}

#endif /* CONFIG_STM32_STM32F10XX || CONFIG_STM32_STM32F20XX || CONFIG_STM32_STM32F40XX */
#endif /* CONFIG_STM32_I2C1 || CONFIG_STM32_I2C2 || CONFIG_STM32_I2C3 */