summaryrefslogtreecommitdiff
path: root/nuttx/drivers/mmcsd/mmcsd_spi.c
blob: 16fc31089f67616dee80cc91641402574689e54c (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
/****************************************************************************
 * drivers/mmcsd/mmcsd_spi.c
 *
 *   Copyright (C) 2008-2010, 2011-2013 Gregory Nutt. All rights reserved.
 *   Author: Gregory 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.
 *
 ****************************************************************************/

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

#include <nuttx/config.h>

#if defined (CONFIG_MMCSD) && defined (CONFIG_MMCSD_SPI)

#include <sys/types.h>

#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <debug.h>

#include <nuttx/arch.h>
#include <nuttx/clock.h>
#include <nuttx/spi/spi.h>
#include <nuttx/fs/fs.h>
#include <nuttx/mmcsd.h>

#include "mmcsd_spi.h"
#include "mmcsd_csd.h"
#include "mmcsd_internal.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/* Configuration ************************************************************/

#ifndef CONFIG_MMCSD_NSLOTS
#  ifdef CONFIG_CPP_HAVE_WARNING
#    warning "CONFIG_MMCSD_NSLOTS not defined"
#  endif
#  define CONFIG_MMCSD_NSLOTS 1
#endif

#define MMCSD_IDMODE_CLOCK           (400000)

#if defined(CONFIG_FS_WRITABLE) && !defined(CONFIG_MMCSD_READONLY)
#  define MMCSD_MODE 0666
#else
#  define MMCSD_MODE 0444
#endif

#ifndef CONFIG_MMCSD_SPICLOCK
#  define CONFIG_MMCSD_SPICLOCK 20000000
#endif

#ifndef CONFIG_MMCSD_SPIMODE
#  define CONFIG_MMCSD_SPIMODE SPIDEV_MODE0
#endif

#ifndef CONFIG_MMCSD_SECTOR512
#  define CONFIG_MMCSD_SECTOR512          /* Force 512 byte sectors on all cards */
#endif

/* Slot struct info *********************************************************/
/* Slot status definitions */

#define MMCSD_SLOTSTATUS_NOTREADY    0x01 /* Card not initialized */
#define MMCSD_SLOTSTATUS_NODISK      0x02 /* No card in the slot */
#define MMCSD_SLOTSTATUS_WRPROTECT   0x04 /* Card is write protected */
#define MMCSD_SLOTSTATUS_MEDIACHGD   0x08 /* Media changed in slot */

/* Values in the MMC/SD command table ***************************************/
/* These define the value returned by the MMC/SD command */

#define MMCSD_CMDRESP_R1             0
#define MMCSD_CMDRESP_R1B            1
#define MMCSD_CMDRESP_R2             2
#define MMCSD_CMDRESP_R3             3
#define MMCSD_CMDRESP_R7             4

#ifdef CONFIG_MMCSD_SECTOR512
#  define SECTORSIZE(s)              (512)
#else
#  define SECTORSIZE(s)              ((s)->sectorsize)
#endif

/* Time delays in units of the system clock. CLK_TCK is the number of clock
 * ticks per second.
 */

#define MMCSD_DELAY_10MS             (CLK_TCK/100  + 1)
#define MMCSD_DELAY_50MS             (CLK_TCK/20   + 1)
#define MMCSD_DELAY_100MS            (CLK_TCK/10   + 1)
#define MMCSD_DELAY_250MS            (CLK_TCK/4    + 1)
#define MMCSD_DELAY_500MS            (CLK_TCK/2    + 1)
#define MMCSD_DELAY_1SEC             (CLK_TCK      + 1)
#define MMCSD_DELAY_10SEC            (10 * CLK_TCK + 1)

#define ELAPSED_TIME(t)              (clock_systimer()-(t))
#define START_TIME                   (clock_systimer())

/* SD read timeout: ~100msec, Write Time out ~250ms.  Units of clock ticks */

#define SD_READACCESS                MMCSD_DELAY_100MS
#define SD_WRITEACCESS               MMCSD_DELAY_250MS

/****************************************************************************
 * Private Types
 ****************************************************************************/

/* This structure represents the state of one card slot */

struct mmcsd_slot_s
{
  FAR struct spi_dev_s *spi; /* SPI port bound to this slot */
  sem_t  sem;                /* Assures mutually exclusive access to card and SPI */
  uint8_t  state;            /* State of the slot (see MMCSD_SLOTSTATUS_* definitions) */
  uint8_t  type;             /* Disk type */
  uint8_t  csd[16];          /* Copy of card CSD */
#ifndef CONFIG_MMCSD_SECTOR512
  uint16_t sectorsize;       /* Media block size (in bytes) */
#endif
  uint32_t nsectors;         /* Number of blocks on the media */
  uint32_t taccess;          /* Card access time */
  uint32_t twrite;           /* Card write time */
  uint32_t ocr;              /* Last 4 bytes of OCR (R3) */
  uint32_t r7;               /* Last 4 bytes of R7 */
#ifndef CONFIG_SPI_OWNBUS
  uint32_t spispeed;         /* Speed to use for SPI in data mode */
#endif
};

struct mmcsd_cmdinfo_s
{
  uint8_t  cmd;
  uint8_t  resp;
  uint8_t  chksum;
};

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

/* Misc *********************************************************************/

static void     mmcsd_semtake(FAR struct mmcsd_slot_s *slot);
static void     mmcsd_semgive(FAR struct mmcsd_slot_s *slot);

/* Card SPI interface *******************************************************/

#ifdef CONFIG_SPI_OWNBUS
static inline void mmcsd_spiinit(FAR struct mmcsd_slot_s *slot);
#else
#  define mmcsd_spiinit(slot)
#endif

static int      mmcsd_waitready(FAR struct mmcsd_slot_s *slot);
static uint32_t mmcsd_sendcmd(FAR struct mmcsd_slot_s *slot,
                  const struct mmcsd_cmdinfo_s *cmd, uint32_t arg);
static void     mmcsd_setblklen(FAR struct mmcsd_slot_s *slot,
                  uint32_t length);
static uint32_t mmcsd_nsac(FAR struct mmcsd_slot_s *slot, uint8_t *csd,
                  uint32_t frequency);
static uint32_t mmcsd_taac(FAR struct mmcsd_slot_s *slot, uint8_t *csd);
static void     mmcsd_decodecsd(FAR struct mmcsd_slot_s *slot, uint8_t *csd);
static void     mmcsd_checkwrprotect(FAR struct mmcsd_slot_s *slot,
                  uint8_t *csd);
static int      mmcsd_getcardinfo(FAR struct mmcsd_slot_s *slot,
                  uint8_t *buffer, const struct mmcsd_cmdinfo_s *cmd);

#define mmcsd_getcsd(slot, csd) mmcsd_getcardinfo(slot, csd, &g_cmd9);
#define mmcsd_getcid(slot, cid) mmcsd_getcardinfo(slot, cid, &g_cmd10);

static int      mmcsd_recvblock(FAR struct mmcsd_slot_s *slot,
                 uint8_t *buffer, int nbytes);
#if defined(CONFIG_FS_WRITABLE) && !defined(CONFIG_MMCSD_READONLY)
static int      mmcsd_xmitblock(FAR struct mmcsd_slot_s *slot,
                 const uint8_t *buffer, int nbytes, uint8_t token);
#endif

/* Block driver interfaces **************************************************/

static int       mmcsd_open(FAR struct inode *inode);
static int       mmcsd_close(FAR struct inode *inode);
static ssize_t   mmcsd_read(FAR struct inode *inode, unsigned char *buffer,
                   size_t start_sector, unsigned int nsectors);
#if defined(CONFIG_FS_WRITABLE) && !defined(CONFIG_MMCSD_READONLY)
static ssize_t   mmcsd_write(FAR struct inode *inode,
                   const unsigned char *buffer, size_t start_sector,
                   unsigned int nsectors);
#endif
static int       mmcsd_geometry(FAR struct inode *inode,
                    struct geometry *geometry);

/* Initialization ***********************************************************/

static int      mmcsd_mediainitialize(FAR struct mmcsd_slot_s *slot);
static void     mmcsd_mediachanged(void *arg);

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

/* Driver state *************************************************************/

/* These are the lock driver methods supported by this file */

static const struct block_operations g_bops =
{
  mmcsd_open,     /* open     */
  mmcsd_close,    /* close    */
  mmcsd_read,     /* read     */
#if defined(CONFIG_FS_WRITABLE) && !defined(CONFIG_MMCSD_READONLY)
  mmcsd_write,    /* write    */
#else
  NULL,           /* write    */
#endif
  mmcsd_geometry, /* geometry */
  NULL            /* ioctl    */
};

/* A slot structure allocated for each configured slot */

static struct mmcsd_slot_s g_mmcsdslot[CONFIG_MMCSD_NSLOTS];

/* Timing *******************************************************************/

/* We will use the TRAN_SPEED from the CSD to determine the maximum SPI
 * clocking (TRAN_SPEED defines the maximum transfer rate per bit per data
 * line).
 *
 * The CSD TRAN_SPEED is provided as a 3 bit rate unit (RU) and a 4 bit time
 * value (TU). We need the transfer frequency which is:  RU*TU bits/sec
 *
 * g_transpeedru holds RU/10 and g_transpeedtu holds TU*10 so that the
 * correct value is returned in the product
 */

static const uint32_t g_transpeedru[8] =
{
     10000,   /*  0:   10 Kbit/sec / 10 */
    100000,   /*  1:    1 Mbit/sec / 10 */
   1000000,   /*  2:   10 Mbit/sec / 10 */
  10000000,   /*  3:  100 Mbit/sec / 10*/

  0, 0, 0, 0  /* 4-7: Reserved values */
};

static const uint32_t g_transpeedtu[16] =
{
   0, 10, 12, 13, /*  0-3:  Reserved, 1.0, 1.1, 1.2, 1.3 */
  15, 20, 25, 30, /*  4-7:  1.5, 2.0, 2.5, 3.0 */
  35, 40, 45, 50, /*  8-11: 3.5, 4.0, 4.5, 5.0 */
  55, 60, 70, 80, /* 12-15: 5.5, 6.0, 7.0, 8.0 */
};

/* The TAAC defines the asynchronous part of the data access time.  The
 * read access time the sum of the TAAC and the NSAC.  These define the
 * time from the end bit of the read command to start bit of the data block.
 *
 * The TAAC consists of a 3-bit time unit (TU) and a 4-bit time value (TV).
 * TAAC is in units of time; NSAC is in units of SPI clocks.
 * The access time we need is then given by:
 *
 *   taccess = TU*TV + NSAC/spifrequency
 *
 * g_taactu holds TU in units of nanoseconds and microseconds (you have to
 * use the index to distinguish).  g_taactv holds TV with 8-bits of
 * fraction.
 */

#define MAX_USTUNDX 2
static const uint16_t g_taactu[8] =
{
  /* Units of nanoseconds */

      1, /* 0:   1 ns */
     10, /* 1:  10 ns */
    100, /* 2: 100 ns */

  /* Units of microseconds */

      1, /* 3:   1 us 1,000 ns */
     10, /* 4:  10 us 10,000 ns */
    100, /* 5: 100 us 100,000 ns */
   1000, /* 6:   1 ms 1,000,000 ns*/
  10000, /* 7:  10 ms 10,000,000 ns */
};

static const uint16_t g_taactv[] =
{
  0x000,  0x100, 0x133, 0x14d, /*  0-3:  Reserved, 1.0, 1.2, 1.3 */
  0x180,  0x200, 0x280, 0x300, /*  4-7:   1.5, 2.0, 2.5, 3.0 */
  0x380,  0x400, 0x480, 0x500, /*  8-11:  3.5, 4.0, 4.5, 5.0 */
  0x580,  0x600, 0x700, 0x800  /* 12-15:  5.5, 6.0, 7.0, 8.0 */
};

/* Commands *****************************************************************/

static const struct mmcsd_cmdinfo_s g_cmd0   = {CMD0,   MMCSD_CMDRESP_R1, 0x95};
static const struct mmcsd_cmdinfo_s g_cmd1   = {CMD1,   MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd8   = {CMD8,   MMCSD_CMDRESP_R7, 0x87};
static const struct mmcsd_cmdinfo_s g_cmd9   = {CMD9,   MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd10  = {CMD10,  MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd12  = {CMD12,  MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd16  = {CMD16,  MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd17  = {CMD17,  MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd18  = {CMD18,  MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd24  = {CMD24,  MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd25  = {CMD25,  MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd55  = {CMD55,  MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_cmd58  = {CMD58,  MMCSD_CMDRESP_R3, 0xff};
static const struct mmcsd_cmdinfo_s g_acmd23 = {ACMD23, MMCSD_CMDRESP_R1, 0xff};
static const struct mmcsd_cmdinfo_s g_acmd41 = {ACMD41, MMCSD_CMDRESP_R1, 0xff};

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

/****************************************************************************
 * Name: mmcsd_semtake
 ****************************************************************************/

static void mmcsd_semtake(FAR struct mmcsd_slot_s *slot)
{
  /* Get exclusive access to the SPI bus (if necessary) */

#ifndef CONFIG_SPI_OWNBUS
  (void)SPI_LOCK(slot->spi, true);

  /* Set the frequency, bit width and mode, as some other driver could have
   * changed those since the last time that we had the SPI bus.
   */

  SPI_SETFREQUENCY(slot->spi, slot->spispeed);
  SPI_SETMODE(slot->spi, CONFIG_MMCSD_SPIMODE);
  SPI_SETBITS(slot->spi, 8);
#endif

  /* Get exclusive access to the MMC/SD device (possibly unnecessary if
   * SPI_LOCK is also implemented as a semaphore).
   */

  while (sem_wait(&slot->sem) != 0)
    {
      /* The only case that an error should occur here is if the wait was
       * awakened by a signal.
       */

      ASSERT(errno == EINTR);
    }
}

/****************************************************************************
 * Name: mmcsd_semgive
 ****************************************************************************/

static void mmcsd_semgive(FAR struct mmcsd_slot_s *slot)
{
  /* Relinquish the lock on the MMC/SD device */

  sem_post(&slot->sem);

  /* Relinquish the lock on the SPI bus */

#ifndef CONFIG_SPI_OWNBUS
  /* The card may need up to 8 SCLK cycles to sample the CS status
   * and release the MISO line.
   */

  (void)SPI_SEND(slot->spi, 0xff);

  /* Relinquish exclusive access to the SPI bus */

  (void)SPI_LOCK(slot->spi, false);
#endif
}

/****************************************************************************
 * Name: mmcsd_spiinit
 *
 * Description:
 *   Set SPI mode and data width.
 *
 * Assumptions:
 *   MMC/SD card already selected
 *
 ****************************************************************************/

#ifdef CONFIG_SPI_OWNBUS
static inline void mmcsd_spiinit(FAR struct mmcsd_slot_s *slot)
{
  SPI_SETMODE(slot->spi, CONFIG_MMCSD_SPIMODE);
  SPI_SETBITS(slot->spi, 8);
}
#endif

/****************************************************************************
 * Name: mmcsd_waitready
 *
 * Description:
 *   Wait until the card is no longer busy
 *
 * Assumptions:
 *   MMC/SD card already selected
 *
 ****************************************************************************/

static int mmcsd_waitready(FAR struct mmcsd_slot_s *slot)
{
  FAR struct spi_dev_s *spi = slot->spi;
  uint8_t response;
  uint32_t start;
  uint32_t elapsed;

  /* Wait until the card is no longer busy (up to 500MS) */

  start = START_TIME;
  do
    {
      response = SPI_SEND(spi, 0xff);
      if (response == 0xff)
        {
          return OK;
        }

      elapsed = ELAPSED_TIME(start);
    }
  while (elapsed < MMCSD_DELAY_500MS);

  fdbg("Card still busy, last response: %02x\n", response);
  return -EBUSY;
}

/****************************************************************************
 * Name: mmcsd_sendcmd
 *
 * Description:
 *   Send a command to MMC
 *
 * Assumptions:
 *   MMC/SD card already selected
 *
 ****************************************************************************/

static uint32_t mmcsd_sendcmd(FAR struct mmcsd_slot_s *slot,
                              const struct mmcsd_cmdinfo_s *cmd, uint32_t arg)
{
  FAR struct spi_dev_s *spi = slot->spi;
  uint32_t result;
  uint8_t response = 0xff;
  int ret;
  int i;

  /* Wait until the card is not busy.  Some SD cards will not enter the IDLE
   * state until CMD0 is sent for the first time, switching the card  to SPI
   * mode.  Having a pull-up resistor on MISO may avoid this problem, but
   * this check makes it work also without the pull-up.
   */

  ret = mmcsd_waitready(slot);
  if (ret != OK && cmd != &g_cmd0)
    {
      return ret;
    }

  /* Send command code */

  SPI_SEND(spi, cmd->cmd);

  /* Send command's arguments (should be zero if there are no arguments) */

  SPI_SEND(spi, (arg >> 24) & 0xff);
  SPI_SEND(spi, (arg >> 16) & 0xff);
  SPI_SEND(spi, (arg >> 8) & 0xff);
  SPI_SEND(spi, arg & 0xff);

  /* Send CRC if needed.  The SPI interface is initialized in non-protected
   * mode.  However, the reset command (CMD0) and CMD8 are received by the
   * card while it is still in SD mode and, therefore, must have a valid
   * CRC field.
   */

  SPI_SEND(spi, cmd->chksum);

  /* Skip stuff byte on CMD12 */

  if (cmd->cmd == CMD12)
    {
      SPI_SEND(spi, 0xff);
    }

  /* Get the response to the command.  A valid response will have bit7=0.
   * Usually, the non-response is 0xff, but I have seen 0xc0 too.
   */

  for (i = 0; i < 9 && (response & 0x80) != 0; i++)
    {
      response = SPI_SEND(spi, 0xff);
    }

  if ((response & 0x80) != 0)
    {
      fdbg("Failed: i=%d response=%02x\n", i, response);
      return (uint32_t)-1;
    }

  /* Interpret the response according to the command */

  result = response;
  switch (cmd->resp)
    {
    /* The R1B response is two bytes long */

    case MMCSD_CMDRESP_R1B:
      {
        uint32_t busy = 0;
        uint32_t start;
        uint32_t elapsed;

        start = START_TIME;
        do
          {
            busy = SPI_SEND(spi, 0xff);
            elapsed = ELAPSED_TIME(start);
          }
        while (elapsed < slot->twrite && busy != 0xff);

        if (busy != 0xff)
          {
            fdbg("Failed: card still busy (%02x)\n", busy);
            return (uint32_t)-1;
          }

        fvdbg("CMD%d[%08x] R1B=%02x\n",
              cmd->cmd & 0x3f, arg, response);
      }
      break;

    /* The R1 response is a single byte */

    case MMCSD_CMDRESP_R1:
      {
        fvdbg("CMD%d[%08x] R1=%02x\n",
              cmd->cmd & 0x3f, arg, response);
      }
      break;

    /* The R2 response is two bytes long */

    case MMCSD_CMDRESP_R2:
      {
        result  = ((uint32_t)(response & 0xff) << 8);
        result |= SPI_SEND(spi, 0xff) & 0xff;

        fvdbg("CMD%d[%08x] R2=%04x\n",
              cmd->cmd & 0x3f, arg, result);
      }
      break;

    /* The R3 response is 5 bytes long. The first byte is identical to R1. */

    case MMCSD_CMDRESP_R3:
      {
        slot->ocr  = ((uint32_t)(SPI_SEND(spi, 0xff) & 0xff) << 24);
        slot->ocr |= ((uint32_t)(SPI_SEND(spi, 0xff) & 0xff) << 16);
        slot->ocr |= ((uint32_t)(SPI_SEND(spi, 0xff) & 0xff) << 8);
        slot->ocr |= SPI_SEND(spi, 0xff) & 0xff;

        fvdbg("CMD%d[%08x] R1=%02x OCR=%08x\n",
              cmd->cmd & 0x3f, arg, response, slot->ocr);
      }
      break;

    /* The R7 response is 5 bytes long. The first byte is identical to R1. */

    case MMCSD_CMDRESP_R7:
    default:
      {
        slot->r7  = ((uint32_t)(SPI_SEND(spi, 0xff) & 0xff) << 24);
        slot->r7 |= ((uint32_t)(SPI_SEND(spi, 0xff) & 0xff) << 16);
        slot->r7 |= ((uint32_t)(SPI_SEND(spi, 0xff) & 0xff) << 8);
        slot->r7 |= SPI_SEND(spi, 0xff) & 0xff;

        fvdbg("CMD%d[%08x] R1=%02x R7=%08x\n",
              cmd->cmd & 0x3f, arg, response, slot->r7);
      }
      break;
    }

  return result;
}

/****************************************************************************
 * Name: mmcsd_setblklen
 *
 * Description:
 *   Set block length
 *
 * Assumptions:
 *   MMC/SD card already selected
 *
 ****************************************************************************/

static void mmcsd_setblklen(FAR struct mmcsd_slot_s *slot, uint32_t length)
{
  uint32_t response;

  fvdbg("Set block length to %d\n", length);
  response = mmcsd_sendcmd(slot, &g_cmd16, length);
  if (response != MMCSD_SPIR1_OK)
    {
      fdbg("Failed to set block length: %02x\n", response);
    }
}

/****************************************************************************
 * Name: mmcsd_nsac
 *
 * Description: Convert the value of the NSAC to microseconds
 *
 ****************************************************************************/

static uint32_t mmcsd_nsac(FAR struct mmcsd_slot_s *slot, uint8_t *csd,
                           uint32_t frequency)
{
  /* NSAC is 8-bits wide and is in units of 100 clock cycles.  Therefore,
   * the maximum value is 25.5K clock cycles.
   */

  uint32_t nsac = MMCSD_CSD_NSAC(csd) * ((uint32_t)100*1000);
  uint32_t fhkz = (frequency + 500) / 1000;
  return (nsac + (fhkz >> 1)) / fhkz;
}

/****************************************************************************
 * Name: mmcsd_taac
 *
 * Description: Convert the value of the TAAC to microseconds
 *
 ****************************************************************************/

static uint32_t mmcsd_taac(FAR struct mmcsd_slot_s *slot, uint8_t *csd)
{
  int tundx;

  /*The TAAC consists of a 3-bit time unit (TU) and a 4-bit time value (TV).
   * TAAC is in units of time; NSAC is in units of SPI clocks.
   * The access time we need is then given by:
   *
   *   taccess = TU*TV + NSAC/spifrequency
   *
   * g_taactu holds TU in units of nanoseconds and microseconds (you have to
   * use the index to distinguish.  g_taactv holds TV with 8-bits of fraction.
   */

  tundx  = MMCSD_CSD_TAAC_TIMEUNIT(csd);
  if (tundx <= MAX_USTUNDX)
    {
      /* The maximum value of the nanosecond TAAC is 800 ns. The rounded
       * answer in microseconds will be at most 1.
       */

      return 1;
    }
  else
    {
      /* Return the answer in microseconds */

      return (g_taactu[tundx]*g_taactv[MMCSD_CSD_TAAC_TIMEVALUE(csd)] + 0x80) >> 8;
    }
}

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

static void mmcsd_decodecsd(FAR struct mmcsd_slot_s *slot, uint8_t *csd)
{
  FAR struct spi_dev_s *spi = slot->spi;
  uint32_t maxfrequency;
  uint32_t frequency;
  uint32_t readbllen;
  uint32_t csizemult;
  uint32_t csize;

  /* Calculate the SPI max clock frequency */

  maxfrequency =
    g_transpeedtu[MMCSD_CSD_TRANSPEED_TIMEVALUE(csd)] *
    g_transpeedru[MMCSD_CSD_TRANSPEED_TRANSFERRATEUNIT(csd)];

  /* Clip the max frequency to account for board limitations */

  frequency = maxfrequency;
  if (frequency > CONFIG_MMCSD_SPICLOCK)
    {
      frequency = CONFIG_MMCSD_SPICLOCK;
    }

  /* Set the actual SPI frequency as close as possible to the max frequency */

#ifndef CONFIG_SPI_OWNBUS
  slot->spispeed = frequency;
#endif
  frequency = SPI_SETFREQUENCY(spi, frequency);

  /* Now determine the delay to access data */

  if (slot->type == MMCSD_CARDTYPE_MMC)
    {
      /* The TAAC consists of a 3-bit time unit (TU) and a 4-bit time value
       * (TV).  TAAC is in units of time; NSAC is in units of SPI clocks.
       * The access time we need is then given by:
       *
       *   taccess = TU*TV + NSAC/spifrequency
       *
       * Example: TAAC = 1.5 ms,  NSAC = 0, r2wfactor = 4, CLK_TCK=100
       *          taccessus = 1,500uS
       *          taccess   = (1,500 * 100) / 100,000) + 1 = 2 (ideal, 1.5)
       *          twrite    = (1,500 * 4 * 100) / 100,000) + 1 = 7 (ideal 6.0)
       *
       * First get the access time in microseconds
       */

      uint32_t taccessus = mmcsd_taac(slot, csd) + mmcsd_nsac(slot, csd, frequency);

      /* Then convert to system clock ticks.  The maximum read access is 10 times
       * the tacc value: taccess = 10 * (taccessus / 1,000,000) * CLK_TCK, or
       */

      slot->taccess = (taccessus * CLK_TCK) / 100000 + 1;

      /* NOTE that we add one to taccess to assure that we wait at least this
       * time.  The write access time is larger by the R2WFACTOR: */

      slot->taccess = (taccessus * MMCSD_CSD_R2WFACTOR(csd) * CLK_TCK) / 100000 + 1;
    }
  else
    {
      /* For SD, the average is still given by the TAAC+NSAC, but the
       * maximum are the constants 100 and 250MS
       */

      slot->taccess  = SD_READACCESS;
      slot->twrite   = SD_WRITEACCESS;
    }

  fvdbg("SPI Frequency\n");
  fvdbg("  Maximum:         %d Hz\n", maxfrequency);
  fvdbg("  Actual:          %d Hz\n", frequency);
  fvdbg("Read access time:  %d ticks\n", slot->taccess);
  fvdbg("Write access time: %d ticks\n", slot->twrite);

  /* Get the physical geometry of the card: sector size and number of
   * sectors. The card's total capacity is computed from
   *
   *   capacity  = BLOCKNR * BLOCK_LEN
   *   BLOCKNR   = (C_SIZE+1)*MULT
   *   MULT      = 2**(C_SIZE_MULT+2)    (C_SIZE_MULT < 8)
   *   BLOCK_LEN = 2**READ_BL_LEN        (READ_BL_LEN < 12)
   *
   * Or
   *
   *   capacity = ((C_SIZE+1) << (READD_BL_LEN + C_SIZE_MULT + 2))
   *
   * In units of the sector size (1 << READ_BL_LEN), then simplifies to
   *
   *   nsectors = ((C_SIZE+1) << (C_SIZE_MULT + 2))
   */

  if (MMCSD_CSD_CSDSTRUCT(csd) != 0)
    {
      /* SDC structure ver 2.xx */
      /* Note: On SD card WRITE_BL_LEN is always the same as READ_BL_LEN */

      readbllen = SD20_CSD_READBLLEN(csd);
      csizemult = SD20_CSD_CSIZEMULT(csd) + 2;
      csize     = SD20_CSD_CSIZE(csd) + 1;
    }
  else
    {
      /* MMC or SD structure ver 1.xx */
      /* Note: On SD card WRITE_BL_LEN is always the same as READ_BL_LEN */

      readbllen = MMCSD_CSD_READBLLEN(csd);
      csizemult = MMCSD_CSD_CSIZEMULT(csd) + 2;
      csize     = MMCSD_CSD_CSIZE(csd) + 1;
    }

  /* SDHC ver2.x cards have fixed block transfer size of 512 bytes.  SDC
   * ver1.x cards with capacity less than 1Gb, will have sector size
   * 512 byes. SDC ver1.x cards with capacity of 2Gb will report readbllen
   * of 1024 but should use 512 bytes for block transfers.  SDC ver1.x 4Gb
   * cards will report readbllen of 2048 bytes -- are they also 512 bytes?
   */

#ifdef CONFIG_MMCSD_SECTOR512
  if (readbllen > 9)
    {
      csizemult += (readbllen - 9);
    }
  else
    {
      DEBUGASSERT(readbllen == 9);
    }
#else
  if (IS_SDV2(slot->type))
    {
      if (readbllen > 9)
        {
          fdbg("Forcing 512 byte sector size\n");
          csizemult += (readbllen - 9);
          readbllen  = 9;
        }
    }

  slot->sectorsize = 1 << readbllen;
#endif
  slot->nsectors   = csize << csizemult;
  fvdbg("Sector size:       %d\n", SECTORSIZE(slot));
  fvdbg("Number of sectors: %d\n", slot->nsectors);
}

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

static void mmcsd_checkwrprotect(FAR struct mmcsd_slot_s *slot, uint8_t *csd)
{
  FAR struct spi_dev_s *spi = slot->spi;

  /* Check if (1) the slot is reporting that reporting that write protection
   * is set, (2) the card reports permanent write protect, or (2) the card
   * reports temporary write protect.
   */

  if ((SPI_STATUS(spi, SPIDEV_MMCSD) & SPI_STATUS_WRPROTECTED) != 0 ||
      MMCSD_CSD_PERMWRITEPROTECT(csd) ||
      MMCSD_CSD_TMPWRITEPROTECT(csd))
    {
      slot->state |= MMCSD_SLOTSTATUS_WRPROTECT;
    }
  else
    {
      slot->state &= ~MMCSD_SLOTSTATUS_WRPROTECT;
    }
}

/****************************************************************************
 * Name: mmcsd_getcardinfo
 *
 * Description:
 *   Read CSD or CID  registers
 *
 * Assumptions:
 *   MMC/SD card already selected
 *
 ****************************************************************************/

static int mmcsd_getcardinfo(FAR struct mmcsd_slot_s *slot, uint8_t *buffer,
                             const struct mmcsd_cmdinfo_s *cmd)
{
  FAR struct spi_dev_s *spi = slot->spi;
  uint32_t result;
  uint8_t response;
  int i;

  SPI_SEND(spi, 0xff);

  /* Send the CMD9 or CMD10 */

  result = mmcsd_sendcmd(slot, cmd, 0);
  if (result != MMCSD_SPIR1_OK)
    {
      fdbg("CMD9/10 failed: R1=%02x\n", result);
      return -EIO;
    }

  /* Try up to 8 times to find the start of block (or until an error occurs) */

  for (i = 0; i < 8; i++)
    {
      response = SPI_SEND(spi, 0xff);
      fvdbg("%d. SPI send returned %02x\n", i, response);

      /* If a read operation fails and the card cannot provide the requested
       * data, it will send a data error token instead.  The 4 least
       * significant bits are the same as those in the R2 response.
       */

      if (response != 0 && (response & MMCSD_SPIDET_UPPER) == 0)
        {
          fdbg("%d. Data transfer error: %02x\n", i, response);
          return -EIO;
        }
      else if (response == MMCSD_SPIDT_STARTBLKSNGL)
        {
          for (i = 0; i < 16; ++i)
            {
              *buffer++ = SPI_SEND(spi, 0xff);
            }

          /* CRC receive */

          SPI_SEND(spi, 0xff);
          SPI_SEND(spi, 0xff);
          return OK;
        }
    }

  fdbg("%d. Did not find start of block\n");
  return -EIO;
}

/****************************************************************************
 * Name: mmcsd_recvblock
 *
 * Description:  Receive a data block from the card
 *
 ****************************************************************************/

static int mmcsd_recvblock(FAR struct mmcsd_slot_s *slot, uint8_t *buffer,
                           int nbytes)
{
  FAR struct spi_dev_s *spi = slot->spi;
  uint32_t start;
  uint32_t elapsed;
  uint8_t  token;

  /* Wait up to the maximum to receive a valid data token.  taccess is the
   * time from when the command is sent until the first byte of data is
   * received */

  start = START_TIME;
  do
    {
      token = SPI_SEND(spi, 0xff);
      elapsed = ELAPSED_TIME(start);
    }
  while (token == 0xff && elapsed < slot->taccess);

  if (token == MMCSD_SPIDT_STARTBLKSNGL)
    {
      /* Receive the block */

      SPI_RECVBLOCK(spi, buffer, nbytes);

      /* Discard the CRC */

      SPI_SEND(spi, 0xff);
      SPI_SEND(spi, 0xff);
      return OK;
    }

  fdbg("Did not receive data token (%02x)\n", token);
  return ERROR;
}

/****************************************************************************
 * Name: mmcsd_xmitblock
 *
 * Description:  Transmit a data block to the card
 *
 ****************************************************************************/

#if defined(CONFIG_FS_WRITABLE) && !defined(CONFIG_MMCSD_READONLY)
static int mmcsd_xmitblock(FAR struct mmcsd_slot_s *slot,
                           FAR const uint8_t *buffer, int nbytes,
                           uint8_t token)
{
  FAR struct spi_dev_s *spi = slot->spi;
  uint8_t response;

  /* Start the block transfer:
   * 1. 0xff (sync)
   * 2. 0xfe or 0xfc (start of block token)
   * 3. Followed by the block of data and 2 byte CRC
   */

  SPI_SEND(spi, 0xff);                     /* sync */
  SPI_SEND(spi, token);                    /* data token */

  /* Transmit the block to the MMC/SD card */

  (void)SPI_SNDBLOCK(spi, buffer, nbytes);

  /* Add the bogus CRC.  By default, the SPI interface is initialized in
   * non-protected mode.  However, we still have to send bogus CRC values
   */

  SPI_SEND(spi, 0xff);
  SPI_SEND(spi, 0xff);

  /* Now get the data response */

  response = SPI_SEND(spi, 0xff);
  if ((response & MMCSD_SPIDR_MASK) != MMCSD_SPIDR_ACCEPTED)
    {
      fdbg("Bad data response: %02x\n", response);
      return -EIO;
    }

  return OK;
}
#endif /* CONFIG_FS_WRITABLE && !CONFIG_MMCSD_READONLY */

/****************************************************************************
 * Block Driver Operations
 ****************************************************************************/

/****************************************************************************
 * Name: mmcsd_open
 *
 * Description: Open the block device
 *
 ****************************************************************************/

static int mmcsd_open(FAR struct inode *inode)
{
  FAR struct mmcsd_slot_s *slot;
  FAR struct spi_dev_s *spi;
  int ret;

  fvdbg("Entry\n");

#ifdef CONFIG_DEBUG
  if (!inode || !inode->i_private)
    {
      fdbg("Internal confusion\n");
      return -EIO;
    }
#endif

  /* Extract our private data from the inode structure */

  slot = (FAR struct mmcsd_slot_s *)inode->i_private;
  spi  = slot->spi;

#ifdef CONFIG_DEBUG
  if (!spi)
    {
      fdbg("Internal confusion\n");
      return -EIO;
    }
#endif

  /* Verify that an MMC/SD card has been inserted */

  ret = -ENODEV;
  mmcsd_semtake(slot);
  if ((SPI_STATUS(spi, SPIDEV_MMCSD) & SPI_STATUS_PRESENT) != 0)
    {
      /* Yes.. a card is present.  Has it been initialized? */

      if (slot->type == MMCSD_CARDTYPE_UNKNOWN)
        {
          /* Initialize for the media in the slot */

          ret = mmcsd_mediainitialize(slot);
          if (ret < 0)
            {
              fvdbg("Failed to initialize card\n");
              goto errout_with_sem;
            }
        }

      /* Make sure that the card is ready */

      SPI_SELECT(spi, SPIDEV_MMCSD, true);
      ret = mmcsd_waitready(slot);
      SPI_SELECT(spi, SPIDEV_MMCSD, false);
    }

errout_with_sem:
  mmcsd_semgive(slot);
  return ret;
}

/****************************************************************************
 * Name: mmcsd_close
 *
 * Description: close the block device
 *
 ****************************************************************************/

static int mmcsd_close(FAR struct inode *inode)
{
  fvdbg("Entry\n");
  return OK;
}

/****************************************************************************
 * Name: mmcsd_read
 *
 * Description:  Read the specified numer of sectors
 *
 ****************************************************************************/

static ssize_t mmcsd_read(FAR struct inode *inode, unsigned char *buffer,
                          size_t start_sector, unsigned int nsectors)
{
  FAR struct mmcsd_slot_s *slot;
  FAR struct spi_dev_s *spi;
  size_t nbytes;
  off_t  offset;
  uint8_t  response;
  int    i;

  fvdbg("start_sector=%d nsectors=%d\n", start_sector, nsectors);

#ifdef CONFIG_DEBUG
  if (!buffer)
    {
      fdbg("Invalid parameters\n");
      return -EINVAL;
    }

  if (!inode || !inode->i_private)
    {
      fdbg("Internal confusion\n");
      return -EIO;
    }
#endif

  /* Extract our private data from the inode structure */

  slot = (FAR struct mmcsd_slot_s *)inode->i_private;
  spi  = slot->spi;

#ifdef CONFIG_DEBUG
  if (!spi)
    {
      fdbg("Internal confusion\n");
      return -EIO;
    }
#endif

  /* Verify that card is available */

  if (slot->state & MMCSD_SLOTSTATUS_NOTREADY)
    {
      fdbg("Slot not ready\n");
      return -ENODEV;
    }

  /* Do nothing on zero-length transfer */

  if (nsectors < 1)
    {
      return 0;
    }

  /* Convert sector and nsectors to nbytes and byte offset */

  nbytes = nsectors * SECTORSIZE(slot);
  UNUSED(nbytes);

  if (IS_BLOCK(slot->type))
    {
      offset = start_sector;
      fvdbg("nbytes=%d sector offset=%d\n", nbytes, offset);
    }
  else
    {
      offset = start_sector * SECTORSIZE(slot);
      fvdbg("nbytes=%d byte offset=%d\n", nbytes, offset);
    }

  /* Select the slave */

  mmcsd_semtake(slot);
  SPI_SELECT(spi, SPIDEV_MMCSD, true);

  /* Single or multiple block read? */

  if (nsectors == 1)
    {
      /* Send CMD17: Reads a block of the size selected by the SET_BLOCKLEN
       * command and verify that good R1 status is returned
       */

      response = mmcsd_sendcmd(slot, &g_cmd17, offset);
      if (response != MMCSD_SPIR1_OK)
        {
          fdbg("CMD17 failed: R1=%02x\n", response);
          goto errout_with_eio;
        }

      /* Receive the block */

      if (mmcsd_recvblock(slot, buffer, SECTORSIZE(slot)) != 0)
        {
          fdbg("Failed: to receive the block\n");
          goto errout_with_eio;
        }
    }
  else
    {
      /* Send CMD18: Reads a block of the size selected by the SET_BLOCKLEN
       * command and verify that good R1 status is returned
       */

      response = mmcsd_sendcmd(slot, &g_cmd18, offset);
      if (response != MMCSD_SPIR1_OK)
        {
          fdbg("CMD18 failed: R1=%02x\n", response);
          goto errout_with_eio;
        }

      /* Receive each block */

      for (i = 0; i < nsectors; i++)
        {
          if (mmcsd_recvblock(slot, buffer, SECTORSIZE(slot)) != 0)
            {
              fdbg("Failed: to receive the block\n");
              goto errout_with_eio;
            }

         buffer += SECTORSIZE(slot);
       }

      /* Send CMD12: Stops transmission */

      response = mmcsd_sendcmd(slot, &g_cmd12, 0);
    }

  /* On success, return the number of sectors transfer */

  SPI_SELECT(spi, SPIDEV_MMCSD, false);
  SPI_SEND(spi, 0xff);
  mmcsd_semgive(slot);

  fvdbg("Read %d bytes:\n", nbytes);
  mmcsd_dumpbuffer("Read buffer", buffer, nbytes);
  return nsectors;

errout_with_eio:
  SPI_SELECT(spi, SPIDEV_MMCSD, false);
  mmcsd_semgive(slot);
  return -EIO;
}

/****************************************************************************
 * Name: mmcsd_write
 *
 * Description:
 *   Write the specified number of sectors
 *
 ****************************************************************************/

#if defined(CONFIG_FS_WRITABLE) && !defined(CONFIG_MMCSD_READONLY)
static ssize_t mmcsd_write(FAR struct inode *inode, const unsigned char *buffer,
                        size_t start_sector, unsigned int nsectors)
{
  FAR struct mmcsd_slot_s *slot;
  FAR struct spi_dev_s *spi;
  size_t nbytes;
  off_t  offset;
  uint8_t response;
  int i;

  fvdbg("start_sector=%d nsectors=%d\n", start_sector, nsectors);

#ifdef CONFIG_DEBUG
  if (!buffer)
    {
      fdbg("Invalid parameters\n");
      return -EINVAL;
    }

  if (!inode || !inode->i_private)
    {
      fdbg("Internal confusion\n");
      return -EIO;
    }
#endif

  /* Extract our private data from the inode structure */

  slot = (FAR struct mmcsd_slot_s *)inode->i_private;
  spi  = slot->spi;

#ifdef CONFIG_DEBUG
  if (!spi)
    {
      fdbg("Internal confusion\n");
      return -EIO;
    }
#endif

  /* Verify that card is available */

  if (slot->state & MMCSD_SLOTSTATUS_NOTREADY)
    {
      fdbg("Slot not ready\n");
      return -ENODEV;
    }

  /* Verify that the card is write enabled */

  if (slot->state & MMCSD_SLOTSTATUS_WRPROTECT)
    {
      fdbg("Not write enabled\n");
      return -EACCES;
    }

  /* Do nothing on zero-length transfer */

  if (nsectors < 1)
    {
      return 0;
    }

  /* Convert sector and nsectors to nbytes and byte offset */

  nbytes = nsectors * SECTORSIZE(slot);
  UNUSED(nbytes);

  if (IS_BLOCK(slot->type))
    {
      offset = start_sector;
      fvdbg("nbytes=%d sector offset=%d\n", nbytes, offset);
    }
  else
    {
      offset = start_sector * SECTORSIZE(slot);
      fvdbg("nbytes=%d byte offset=%d\n", nbytes, offset);
    }

  mmcsd_dumpbuffer("Write buffer", buffer, nbytes);

  /* Select the slave */

  mmcsd_semtake(slot);
  SPI_SELECT(spi, SPIDEV_MMCSD, true);

  /* Single or multiple block transfer? */

  if (nsectors == 1)
    {
      /* Send CMD24 (WRITE_BLOCK) and verify that good R1 status is returned */

      response = mmcsd_sendcmd(slot, &g_cmd24, offset);
      if (response != MMCSD_SPIR1_OK)
        {
          fdbg("CMD24 failed: R1=%02x\n", response);
          goto errout_with_sem;
        }

      /* Then transfer the sector */

      if (mmcsd_xmitblock(slot, buffer, SECTORSIZE(slot), 0xfe) != 0)
        {
          fdbg("Block transfer failed\n");
          goto errout_with_sem;
        }
    }
  else
    {
      /* Set the number of blocks to be pre-erased (SD only) */

      if (IS_SD(slot->type))
        {
          response = mmcsd_sendcmd(slot, &g_cmd55, 0);
          if (response != MMCSD_SPIR1_OK)
            {
              fdbg("CMD55 failed: R1=%02x\n", response);
              goto errout_with_sem;
            }

          response = mmcsd_sendcmd(slot, &g_acmd23, nsectors);
          if (response != MMCSD_SPIR1_OK)
            {
              fdbg("ACMD23 failed: R1=%02x\n", response);
              goto errout_with_sem;
            }
       }

      /* Send CMD25:  Continuously write blocks of data until the
       * transmission is stopped.
       */

      response = mmcsd_sendcmd(slot, &g_cmd25, offset);
      if (response != MMCSD_SPIR1_OK)
        {
          fdbg("CMD25 failed: R1=%02x\n", response);
          goto errout_with_sem;
        }

      /* Transmit each block */

      for (i = 0; i < nsectors; i++)
        {
          if (mmcsd_xmitblock(slot, buffer, SECTORSIZE(slot), 0xfc) != 0)
            {
              fdbg("Failed: to receive the block\n");
              goto errout_with_sem;
            }
          buffer += SECTORSIZE(slot);

          if (mmcsd_waitready(slot) != OK)
            {
              fdbg("Failed: card is busy\n");
              goto errout_with_sem;
            }
        }

      /* Send the stop transmission token */

      SPI_SEND(spi, MMCSD_SPIDT_STOPTRANS);
    }

  /* Wait until the card is no longer busy */

  (void)mmcsd_waitready(slot);
  SPI_SELECT(spi, SPIDEV_MMCSD, false);
  SPI_SEND(spi, 0xff);
  mmcsd_semgive(slot);

  /* The success return value is the number of sectors written */

  return nsectors;

errout_with_sem:
  SPI_SELECT(spi, SPIDEV_MMCSD, false);
  mmcsd_semgive(slot);
  return -EIO;
}
#endif

/****************************************************************************
 * Name: mmcsd_geometry
 *
 * Description:
 *   Return device geometry
 *
 ****************************************************************************/

static int mmcsd_geometry(FAR struct inode *inode, struct geometry *geometry)
{
  FAR struct mmcsd_slot_s *slot;
  FAR struct spi_dev_s *spi;
  uint8_t csd[16];
  int ret;

#ifdef CONFIG_DEBUG
  if (!geometry)
    {
      fdbg("Invalid parameters\n");
      return -EINVAL;
    }

  if (!inode || !inode->i_private)
    {
      fdbg("Internal confusion\n");
      return -EIO;
    }
#endif

  /* Extract our private data from the inode structure */

  slot = (FAR struct mmcsd_slot_s *)inode->i_private;
  spi  = slot->spi;

#ifdef CONFIG_DEBUG
  if (!spi)
    {
      fdbg("Internal confusion\n");
      return -EIO;
    }
#endif

  /* Re-sample the CSD */

  mmcsd_semtake(slot);
  SPI_SELECT(spi, SPIDEV_MMCSD, true);
  ret = mmcsd_getcsd(slot, csd);
  SPI_SELECT(spi, SPIDEV_MMCSD, false);

  if (ret < 0)
    {
      mmcsd_semgive(slot);
      fdbg("mmcsd_getcsd returned %d\n", ret);
      return ret;
    }

  /* Check for changes related to write protection */

  mmcsd_checkwrprotect(slot, csd);

  /* Then return the card geometry */

  geometry->geo_available =
    ((slot->state & (MMCSD_SLOTSTATUS_NOTREADY|MMCSD_SLOTSTATUS_NODISK)) == 0);
  geometry->geo_mediachanged =
    ((slot->state & MMCSD_SLOTSTATUS_MEDIACHGD) != 0);
#if defined(CONFIG_FS_WRITABLE) && !defined(CONFIG_MMCSD_READONLY)
  geometry->geo_writeenabled =
    ((slot->state & MMCSD_SLOTSTATUS_WRPROTECT) == 0);
#else
  geometry->geo_writeenabled = false;
#endif
  geometry->geo_nsectors   = slot->nsectors;
  geometry->geo_sectorsize = SECTORSIZE(slot);

  /* After reporting mediachanged, clear the indication so that it is not
   * reported again.
   */

  slot->state &= ~MMCSD_SLOTSTATUS_MEDIACHGD;
  mmcsd_semgive(slot);

  fvdbg("geo_available:     %d\n", geometry->geo_available);
  fvdbg("geo_mediachanged:  %d\n", geometry->geo_mediachanged);
  fvdbg("geo_writeenabled:  %d\n", geometry->geo_writeenabled);
  fvdbg("geo_nsectors:      %d\n", geometry->geo_nsectors);
  fvdbg("geo_sectorsize:    %d\n", geometry->geo_sectorsize);

  return OK;
}

/****************************************************************************
 * Initialization
 ****************************************************************************/

/****************************************************************************
 * Name: mmcsd_mediainitialize
 *
 * Description:
 *   Detect media and initialize
 *
 * Precondition:
 *   Semaphore has been taken.
 ****************************************************************************/

static int mmcsd_mediainitialize(FAR struct mmcsd_slot_s *slot)
{
  FAR struct spi_dev_s *spi = slot->spi;
  uint8_t csd[16];
  uint32_t result = MMCSD_SPIR1_IDLESTATE;
  uint32_t start;
  uint32_t elapsed;
  int i;
  int j;

  /* Assume that the card is not ready (we'll clear this on successful card
   * initialization.
   */

  slot->state |= MMCSD_SLOTSTATUS_NOTREADY;

  /* Check if there is a card present in the slot.  This is normally a matter is
   * of GPIO sensing and does not really involve SPI, but by putting this
   * functionality in the SPI interface, we encapsulate the SPI MMC/SD
   * interface
   */

  if ((SPI_STATUS(spi, SPIDEV_MMCSD) & SPI_STATUS_PRESENT) == 0)
    {
      fdbg("No card present\n");
      slot->state |= MMCSD_SLOTSTATUS_NODISK;
      return -ENODEV;
    }

  /* Clock Freq. Identification Mode < 400kHz */

#ifndef CONFIG_SPI_OWNBUS
  slot->spispeed = MMCSD_IDMODE_CLOCK;
#endif
  SPI_SETFREQUENCY(spi, MMCSD_IDMODE_CLOCK);

  /* Set the maximum access time out */

  slot->taccess = SD_READACCESS;

  /* The SD card wakes up in SD mode. It will enter SPI mode if the chip
   * select signal is asserted (negative) during the reception of the reset
   * command (CMD0) and the card is in IDLE state.
   */

  for (i = 0; i < 2; i++)
    {
      /* After power up at least 74 clock cycles are required prior to
       * starting bus communication
       */

      for (j = 10; j; j--)
        {
          SPI_SEND(spi, 0xff);
        }

      /* Send CMD0 (GO_TO_IDLE) with CS asserted to put MMC/SD in
       * IDLE/SPI mode. Return from CMD0 is R1 which should now
       * show IDLE STATE
       */

      fvdbg("Send CMD0\n");
      SPI_SELECT(spi, SPIDEV_MMCSD, true);
      result = mmcsd_sendcmd(slot, &g_cmd0, 0);
      if (result == MMCSD_SPIR1_IDLESTATE)
        {
          /* Break out of the loop with card selected */

          fvdbg("Card is in IDLE state\n");
          break;
        }

      /* De-select card and try again */

      SPI_SELECT(spi, SPIDEV_MMCSD, false);
    }

  /* Verify that we exit the above loop with the card reporting IDLE state */

  if (result != MMCSD_SPIR1_IDLESTATE)
    {
      fdbg("Send CMD0 failed: R1=%02x\n", result);
      SPI_SELECT(spi, SPIDEV_MMCSD, false);
      mmcsd_semgive(slot);
      return -EIO;
    }

  slot->type = MMCSD_CARDTYPE_UNKNOWN;

  /* Check for SDHC Version 2.x.  CMD 8 is reserved on SD version 1.0 and
   * MMC.
   */

  fvdbg("Send CMD8\n");
  result = mmcsd_sendcmd(slot, &g_cmd8, 0x1aa);
  if (result == MMCSD_SPIR1_IDLESTATE)
    {
      /* Verify the operating voltage and that the 0xaa was correctly echoed */

      if (((slot->r7 & MMCSD_SPIR7_VOLTAGE_MASK) == MMCSD_SPIR7_VOLTAGE_27) &&
          ((slot->r7 & MMCSD_SPIR7_ECHO_MASK) == 0xaa))
        {
          /* Try CMD55/ACMD41 for up to 1 second or until the card exits
           * the IDLE state
           */

          start   = START_TIME;
          elapsed = 0;
          do
            {
              fvdbg("%d. Send CMD55/ACMD41\n", elapsed);
              result = mmcsd_sendcmd(slot, &g_cmd55, 0);
              if (result == MMCSD_SPIR1_IDLESTATE || result == MMCSD_SPIR1_OK)
                {
                  result = mmcsd_sendcmd(slot, &g_acmd41, (uint32_t)1 << 30);
                  if (result == MMCSD_SPIR1_OK)
                    {
                      break;
                    }
                }

              elapsed = ELAPSED_TIME(start);
            }
          while (elapsed < MMCSD_DELAY_1SEC);

          /* Check if ACMD41 was sent successfully */

          if (elapsed < MMCSD_DELAY_1SEC)
           {
             fvdbg("Send CMD58\n");

             SPI_SEND(spi, 0xff);
             result = mmcsd_sendcmd(slot, &g_cmd58, 0);
             if (result == MMCSD_SPIR1_OK)
               {
                  fvdbg("OCR: %08x\n", slot->ocr);
                  if ((slot->ocr & MMCSD_OCR_CCS) != 0)
                    {
                      fdbg("Identified SD ver2 card/with block access\n");
                      slot->type = MMCSD_CARDTYPE_SDV2|MMCSD_CARDTYPE_BLOCK;
                    }
                  else
                    {
                      fdbg("Identified SD ver2 card\n");
                      slot->type = MMCSD_CARDTYPE_SDV2;
                    }
               }
           }
        }
    }

  /* Check for SDC version 1.x or MMC */

  else
    {
      /* Both the MMC card and the SD card support CMD55 */

      fvdbg("Send CMD55/ACMD41\n");
      result = mmcsd_sendcmd(slot, &g_cmd55, 0);
      if (result == MMCSD_SPIR1_IDLESTATE || result == MMCSD_SPIR1_OK)
        {
          /* But ACMD41 is supported only on SD */

          result = mmcsd_sendcmd(slot, &g_acmd41, 0);
          if (result == MMCSD_SPIR1_IDLESTATE || result == MMCSD_SPIR1_OK)
            {
              fdbg("Identified SD ver1 card\n");
              slot->type = MMCSD_CARDTYPE_SDV1;
            }
        }

      /* Make sure that we are out of the Idle state */

      start   = START_TIME;
      elapsed = 0;
      do
        {
          if (IS_SD(slot->type))
            {
              fvdbg("%d. Send CMD55/ACMD41\n", elapsed);
              result = mmcsd_sendcmd(slot, &g_cmd55, 0);
              if (result == MMCSD_SPIR1_IDLESTATE || result == MMCSD_SPIR1_OK)
                {
                  result = mmcsd_sendcmd(slot, &g_acmd41, 0);
                  if (result == MMCSD_SPIR1_OK)
                    {
                       break;
                    }
                }
            }
          else
            {
              fvdbg("%d. Send CMD1\n", i);
              result = mmcsd_sendcmd(slot, &g_cmd1, 0);
              if (result == MMCSD_SPIR1_OK)
                {
                   fdbg("%d. Identified MMC card\n", i);
                   slot->type = MMCSD_CARDTYPE_MMC;
                   break;
                }
             }

          elapsed = ELAPSED_TIME(start);
        }
      while (elapsed < MMCSD_DELAY_1SEC);

      if (elapsed >= MMCSD_DELAY_1SEC)
        {
          fdbg("Failed to exit IDLE state\n");
          SPI_SELECT(spi, SPIDEV_MMCSD, false);
          mmcsd_semgive(slot);
          return -EIO;
        }
    }

  if (slot->type == MMCSD_CARDTYPE_UNKNOWN)
    {
      fdbg("Failed to identify card\n");
      SPI_SELECT(spi, SPIDEV_MMCSD, false);
      mmcsd_semgive(slot);
      return -EIO;
    }

  /* Read CSD. CSD must always be valid */

  fvdbg("Get CSD\n");
  result = mmcsd_getcsd(slot, csd);
  if (result != OK)
    {
      fdbg("mmcsd_getcsd(CMD9) failed: %d\n", result);
      SPI_SELECT(spi, SPIDEV_MMCSD, false);
      mmcsd_semgive(slot);
      return -EIO;
    }

  mmcsd_dmpcsd(csd, slot->type);

  /* CSD data and set block size */

  mmcsd_decodecsd(slot, csd);
  mmcsd_checkwrprotect(slot, csd);

  /* SDHC ver2.x cards have fixed block transfer size of 512 bytes.  SDC
   * ver1.x cards with capacity less than 1Gb, will have sector size
   * 512 byes. SDC ver1.x cards with capacity of 2Gb will report readbllen
   * of 1024 but should use 512 bytes for block transfers.  SDC ver1.x 4Gb
   * cards will report readbllen of 2048 bytes -- are they also 512 bytes?
   * I think that none of these high capacity cards support setting the
   * block length??
   */

#ifdef CONFIG_MMCSD_SECTOR512
  /* Using 512 byte sectors, the maximum ver1.x capacity is 4096 x 512 blocks.
   * The saved slot->nsectors is converted to 512 byte blocks, so if slot->nsectors
   * exceeds 4096 x 512, then we must be dealing with a card with read_bl_len
   * of 1024 or 2048.
   */

  if (!IS_SDV2(slot->type) && slot->nsectors <= ((uint32_t)4096*12))
    {
      /* Don't set the block len on high capacity cards (ver1.x or ver2.x) */

      mmcsd_setblklen(slot, SECTORSIZE(slot));
    }
#else
  if (!IS_SDV2(slot->type))
    {
      /* Don't set the block len on ver2.x cards */

      mmcsd_setblklen(slot, SECTORSIZE(slot));
    }
#endif

  slot->state &= ~MMCSD_SLOTSTATUS_NOTREADY;
  SPI_SELECT(spi, SPIDEV_MMCSD, false);
  return OK;
}

/****************************************************************************
 * Name: mmcsd_mediachanged
 *
 * Description:
 *   Handle initialization/media change events
 *
 ****************************************************************************/

static void mmcsd_mediachanged(void *arg)
{
  struct mmcsd_slot_s *slot = (struct mmcsd_slot_s*)arg;
  FAR struct spi_dev_s *spi;
  uint8_t oldstate;
  int ret;

#ifdef CONFIG_DEBUG
  if (!slot || !slot->spi)
    {
      fdbg("Internal confusion\n");
      return;
    }
#endif

  spi  = slot->spi;

  /* Save the current slot state and reassess the new state */

  mmcsd_semtake(slot);
  oldstate = slot->state;

  /* Check if media was removed or inserted */

  slot->state &= ~(MMCSD_SLOTSTATUS_NODISK | MMCSD_SLOTSTATUS_NOTREADY |
                   MMCSD_SLOTSTATUS_MEDIACHGD);

  if ((SPI_STATUS(spi, SPIDEV_MMCSD) & SPI_STATUS_PRESENT) == 0)
    {
      /* Media is not present */

      fdbg("No card present\n");
      slot->state |= (MMCSD_SLOTSTATUS_NODISK|MMCSD_SLOTSTATUS_NOTREADY);

      /* Was media removed? */

      if ((oldstate & MMCSD_SLOTSTATUS_NODISK) == 0)
        {
          slot->state |= MMCSD_SLOTSTATUS_MEDIACHGD;
        }
    }

  /* Media is present, was it just inserted? Or, if it was previously not
   * ready, then try re-initializing it
   */

  else if ((oldstate & (MMCSD_SLOTSTATUS_NODISK|MMCSD_SLOTSTATUS_NOTREADY)) != 0)
    {
      /* (Re-)initialize for the media in the slot */

      ret = mmcsd_mediainitialize(slot);
      if (ret == 0)
        {
          fvdbg("mmcsd_mediainitialize returned OK\n");
          slot->state |= MMCSD_SLOTSTATUS_MEDIACHGD;
        }
    }

  mmcsd_semgive(slot);
}

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

/****************************************************************************
 * Name: mmcsd_spislotinitialize
 *
 * Description:
 *   Initialize one slot for operation using the SPI MMC/SD interface
 *
 * Input Parameters:
 *   minor - The MMC/SD minor device number.  The MMC/SD device will be
 *     registered as /dev/mmcsdN where N is the minor number
 *   slotno - The slot number to use.  This is only meaningful for
 *     architectures that support multiple MMC/SD slots.  This value must be
 *     in the range {0, ..., CONFIG_MMCSD_NSLOTS}.
 *   spi - And instance of an SPI interface obtained by called
 *     up_spiinitialize() with the appropriate port number (see spi.h)
 *
 ****************************************************************************/

int mmcsd_spislotinitialize(int minor, int slotno, FAR struct spi_dev_s *spi)
{
  struct mmcsd_slot_s *slot;
  char devname[16];
  int ret;

#ifdef CONFIG_DEBUG
  if ((unsigned)slotno >= CONFIG_MMCSD_NSLOTS || (unsigned)minor > 255 || !spi)
    {
      fdbg("Invalid arguments\n");
      return -EINVAL;
    }
#endif

  /* Select the slot structure */

  slot = &g_mmcsdslot[slotno];
  memset(slot, 0, sizeof(struct mmcsd_slot_s));
  sem_init(&slot->sem, 0, 1);

#ifdef CONFIG_DEBUG
  if (slot->spi)
    {
      fdbg("Already registered\n");
      return -EBUSY;
    }
#endif

  /* Bind the SPI port to the slot */

  slot->spi = spi;
#ifndef CONFIG_SPI_OWNBUS
  slot->spispeed = MMCSD_IDMODE_CLOCK;
#endif

  /* Get exclusive access to the SPI bus and make sure that SPI is properly
   * configured for the MMC/SD card
   */

  mmcsd_semtake(slot);
  mmcsd_spiinit(slot);

  /* Initialize for the media in the slot (if any) */

  ret = mmcsd_mediainitialize(slot);
  mmcsd_semgive(slot);
  if (ret == 0)
    {
      fvdbg("mmcsd_mediainitialize returned OK\n");
      slot->state |= MMCSD_SLOTSTATUS_MEDIACHGD;
    }

  /* Create a MMC/SD device name */

  snprintf(devname, 16, "/dev/mmcsd%d", minor);

  /* Register the driver, even on a failure condition.  A
   * card may be inserted later, for example.
   */

  ret = register_blockdriver(devname, &g_bops, MMCSD_MODE, slot);
  if (ret < 0)
    {
      fdbg("register_blockdriver failed: %d\n", -ret);
      slot->spi = NULL;
      return ret;
    }

  /* Register a media change callback to handle insertion and
   * removal of cards.
   */

  (void)SPI_REGISTERCALLBACK(spi, mmcsd_mediachanged, (void*)slot);
  return OK;
}

#endif /* defined (CONFIG_MMCSD) && defined (CONFIG_MMCSD_SPI) */