summaryrefslogtreecommitdiff
path: root/nuttx/arch/arm/src/lpc17xx/lpc17_usbhost.c
blob: f62ff43e76fefb9fd53322b7faf961ad2bd238bd (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
/*******************************************************************************
 * arch/arm/src/lpc17xx/lpc17_usbhost.c
 *
 *   Copyright (C) 2010 Gregory Nutt. All rights reserved.
 *   Authors: Rafael Noronha <rafael@pdsolucoes.com.br>
 *            Gregory Nutt <spudmonkey@racsa.co.cr>
 *
 * 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>

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

#include <nuttx/arch.h>
#include <nuttx/usb/usb.h>
#include <nuttx/usb/ohci.h>
#include <nuttx/usb/usbhost.h>

#include <arch/irq.h>
#include <arch/board/board.h>

#include "chip.h"
#include "up_arch.h"
#include "up_internal.h"

#include "lpc17_internal.h"
#include "lpc17_usb.h"
#include "lpc17_syscon.h"
#include "lpc17_ohciram.h"

/*******************************************************************************
 * Definitions
 *******************************************************************************/

/* I think it is the case that all I/O buffers must lie in AHB SRAM because of
 * the OHCI DMA.  But this definition has here so that I can experiment later
 * to see if this really required.
 */

#define CONFIG_UBHOST_AHBIOBUFFERS 1

#if defined(CONFIG_UBHOST_AHBIOBUFFERS) && LPC17_IOBUFFERS < 1
#  error "No IO buffers allocated"
#endif

/* Frame Interval */

#define  FI                     (12000-1) /* 12000 bits per frame (-1) */
#define  DEFAULT_FMINTERVAL     ((((6 * (FI - 210)) / 7) << 16) | FI)

/* CLKCTRL enable bits */

#define LPC17_CLKCTRL_ENABLES (USBOTG_CLK_HOSTCLK|USBDEV_CLK_PORTSELCLK|USBOTG_CLK_AHBCLK)

/* Dump GPIO registers */

#if defined(CONFIG_LPC17_USBHOST_REGDEBUG) && defined(CONFIG_DEBUG_GPIO)
#  define usbhost_dumpgpio() \
   do { \
     lpc17_dumpgpio(GPIO_USB_DP, "D+ P0.29; D- P0.30"); \
     lpc17_dumpgpio(GPIO_USB_UPLED, "LED P1:18; PPWR P1:19 PWRD P1:22 PVRCR P1:27"); \
   } while (0);
#else
#  define usbhost_dumpgpio()
#endif

/* USB Host Memory *************************************************************/

/* Helper definitions */

#define HCCA        ((volatile struct lpc17_hcca_s *)LPC17_HCCA_BASE)
#define TDHEAD      ((volatile struct lpc17_hctd_s *)LPC17_TDHEAD_ADDR)
#define TDTAIL      ((volatile struct lpc17_hctd_s *)LPC17_TDTAIL_ADDR)
#define EDCTRL      ((volatile struct lpc17_hced_s *)LPC17_EDCTRL_ADDR)

#define EDFREE      ((struct lpc17_hced_s *)LPC17_EDFREE_BASE)
#define TDFREE      ((uint8_t *)LPC17_TDFREE_BASE)
#define IOFREE      ((uint8_t *)LPC17_IOFREE_BASE)

/* Descriptors *****************************************************************/

/* TD delay interrupt value */

#define TD_DELAY(n) (uint32_t)((n) << GTD_STATUS_DI_SHIFT)

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

/* This structure retains the state of the USB host controller */

struct lpc17_usbhost_s
{
  /* Common device fields.  This must be the first thing defined in the
   * structure so that it is possible to simply cast from struct usbhost_s
   * to structlpc17_usbhost_s.
   */

  struct usbhost_driver_s drvr;

  /* The bound device class driver */

  struct usbhost_class_s *class;

  /* Driver status */

  volatile uint8_t tdstatus;  /* TD control status bits from last Writeback Done Head event */
  volatile bool    connected; /* Connected to device */
  sem_t            rhssem;    /* Semaphore  to wait Root Hub Status change */
  sem_t            wdhsem;    /* Semaphore  used to wait for Writeback Done Head event */
};

/* Host Controller Communication Area */

struct lpc17_hcca_s
{
  volatile  uint32_t  inttbl[32];       /* Interrupt table */
  volatile  uint32_t  frameno;          /* Frame number */
  volatile  uint32_t  donehead;         /* Done head */
  volatile  uint8_t   reserved[116];    /* Reserved for future use */
  volatile  uint8_t   unused[4];        /* Unused */
};

/* HostController Transfer Descriptor */

struct lpc17_hctd_s
{                       
  volatile  uint32_t  ctrl;            /* Transfer descriptor control */
  volatile  uint32_t  currptr;         /* Physical address of current buffer pointer */
  volatile  uint32_t  next;            /* Physical pointer to next Transfer Descriptor */
  volatile  uint32_t  bufend;          /* Physical address of end of buffer */
};

/* HostController EndPoint Descriptor */

struct lpc17_hced_s
{
  volatile  uint32_t  ctrl;            /* Endpoint descriptor control */
  volatile  uint32_t  tailtd;          /* Physical address of tail in Transfer descriptor list */
  volatile  uint32_t  headtd;          /* Physical address of head in Transfer descriptor list */
  volatile  uint32_t  next;            /* Physical address of next Endpoint descriptor */
};

/* The following are used to manage lists of free EDs and TD buffers*/

struct lpc17_edlist_s
{
  struct lpc17_edlist_s *flink;        /* Link to next ED in the list */
  uint32_t               pad[3];       /* To make the same size as struct lpc17_hced_s */
};

struct lpc17_buflist_s
{
  struct lpc17_buflist_s *flink;       /* Link to next buffer in the list */
                                       /* Variable length buffer data follows */
};

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

/* Register operations ********************************************************/

#ifdef CONFIG_LPC17_USBHOST_REGDEBUG
static void lpc17_printreg(uint32_t addr, uint32_t val, bool iswrite);
static void lpc17_checkreg(uint32_t addr, uint32_t val, bool iswrite);
static uint32_t lpc17_getreg(uint32_t addr);
static void lpc17_putreg(uint32_t val, uint32_t addr);
#else
# define lpc17_getreg(addr)     getreg32(addr)
# define lpc17_putreg(val,addr) putreg32(val,addr)
#endif

/* Semaphores ******************************************************************/

static void lpc17_takesem(sem_t *sem);
#define lpc17_givesem(s) sem_post(s);

/* Byte stream access helper functions *****************************************/

static inline uint16_t lpc17_getle16(const uint8_t *val);
static void lpc17_putle16(uint8_t *dest, uint16_t val);

/* Descriptor helper functions *************************************************/

static struct lpc17_hced_s *lpc17_edalloc(struct lpc17_usbhost_s *priv);
static void lpc17_edfree(struct lpc17_usbhost_s *priv, struct lpc17_hced_s *ed);
static uint8_t *lpc17_tdalloc(struct lpc17_usbhost_s *priv);
static void lpc17_tdfree(struct lpc17_usbhost_s *priv, uint8_t *buffer);
#ifdef CONFIG_UBHOST_AHBIOBUFFERS
static uint8_t *lpc17_ioalloc(struct lpc17_usbhost_s *priv);
static void lpc17_iofree(struct lpc17_usbhost_s *priv, uint8_t *buffer);
#endif
static void lpc17_enqueuetd(volatile struct lpc17_hced_s *ed, uint32_t dirpid,
                            uint32_t toggle, volatile uint8_t *buffer,
                            size_t buflen);
static int lpc17_ctrltd(struct lpc17_usbhost_s *priv, uint32_t dirpid,
                        uint8_t *buffer, size_t buflen);

/* Class helper functions ******************************************************/

static inline int lpc17_devdesc(struct lpc17_usbhost_s *priv,
                                const struct usb_devdesc_s *devdesc, int desclen,
                                struct usbhost_id_s *id);
static inline int lpc17_configdesc(struct lpc17_usbhost_s *priv,
                                   const uint8_t *configdesc, int desclen,
                                   struct usbhost_id_s *id);
static inline int lpc17_classbind(struct lpc17_usbhost_s *priv,
                                  const uint8_t *configdesc, int desclen,
                                  struct usbhost_id_s *id);

/* Interrupt handling **********************************************************/

static int lpc17_usbinterrupt(int irq, FAR void *context);

/* USB host controller operations **********************************************/

static int lpc17_wait(FAR struct usbhost_driver_s *drvr, bool connected);
static int lpc17_enumerate(FAR struct usbhost_driver_s *drvr);
static int lpc17_alloc(FAR struct usbhost_driver_s *drvr,
                         FAR uint8_t **buffer, FAR size_t *maxlen);
static int lpc17_free(FAR struct usbhost_driver_s *drvr, FAR uint8_t *buffer);
static int lpc17_ctrlin(FAR struct usbhost_driver_s *drvr,
                        FAR const struct usb_ctrlreq_s *req,
                        FAR uint8_t *buffer);
static int lpc17_ctrlout(FAR struct usbhost_driver_s *drvr,
                         FAR const struct usb_ctrlreq_s *req,
                         FAR const uint8_t *buffer);
static int lpc17_transfer(FAR struct usbhost_driver_s *drvr,
                            FAR struct usbhost_epdesc_s *ed,
                            FAR uint8_t *buffer, size_t buflen);
static void lpc17_disconnect(FAR struct usbhost_driver_s *drvr);
  
/* Initializaion ***************************************************************/

static void lpc17_tdinit(volatile struct lpc17_hctd_s *td);
static void lpc17_edinit(volatile struct lpc17_hced_s *ed);
static void lpc17_hccainit(volatile struct lpc17_hcca_s *hcca);

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

/* In this driver implementation, support is provided for only a single a single
 * USB device.  All status information can be simply retained in a single global
 * instance.
 */

static struct lpc17_usbhost_s g_usbhost =
{
  .drvr           =
    {
	  .wait       = lpc17_wait,
      .enumerate  = lpc17_enumerate,
      .alloc      = lpc17_alloc,
      .free       = lpc17_free,
      .ctrlin     = lpc17_ctrlin,
      .ctrlout    = lpc17_ctrlout,
      .transfer   = lpc17_transfer,
      .disconnect = lpc17_disconnect,
    },
  .class          = NULL,
};

/* This is a free list of EDs and TD buffers */

static struct lpc17_edlist_s  *g_edfree;
static struct lpc17_buflist_s *g_tdfree;
#ifdef CONFIG_UBHOST_AHBIOBUFFERS
static struct lpc17_buflist_s *g_iofree;
#endif

/*******************************************************************************
 * Public Data
 *******************************************************************************/

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

/*******************************************************************************
 * Name: lpc17_printreg
 *
 * Description:
 *   Print the contents of an LPC17xx register operation
 *
 *******************************************************************************/

#ifdef CONFIG_LPC17_USBHOST_REGDEBUG
static void lpc17_printreg(uint32_t addr, uint32_t val, bool iswrite)
{
  lldbg("%08x%s%08x\n", addr, iswrite ? "<-" : "->", val);
}
#endif

/*******************************************************************************
 * Name: lpc17_checkreg
 *
 * Description:
 *   Get the contents of an LPC17xx register
 *
 *******************************************************************************/

#ifdef CONFIG_LPC17_USBHOST_REGDEBUG
static void lpc17_checkreg(uint32_t addr, uint32_t val, bool iswrite)
{
  static uint32_t prevaddr = 0;
  static uint32_t preval = 0;
  static uint32_t count = 0;
  static bool     prevwrite = false;

  /* Is this the same value that we read from/wrote to the same register last time?
   * Are we polling the register?  If so, suppress the output.
   */

  if (addr == prevaddr && val == preval && prevwrite == iswrite)
    {
      /* Yes.. Just increment the count */

      count++;
    }
  else
    {
      /* No this is a new address or value or operation. Were there any
       * duplicate accesses before this one?
       */

      if (count > 0)
        {
          /* Yes.. Just one? */

          if (count == 1)
            {
              /* Yes.. Just one */

              lpc17_printreg(prevaddr, preval, prevwrite);
            }
          else
            {
              /* No.. More than one. */

              lldbg("[repeats %d more times]\n", count);
            }
        }

      /* Save the new address, value, count, and operation for next time */

      prevaddr  = addr;
      preval    = val;
      count     = 0;
      prevwrite = iswrite;

      /* Show the new regisgter access */

      lpc17_printreg(addr, val, iswrite);
    }
}
#endif

/*******************************************************************************
 * Name: lpc17_getreg
 *
 * Description:
 *   Get the contents of an LPC17xx register
 *
 *******************************************************************************/

#ifdef CONFIG_LPC17_USBHOST_REGDEBUG
static uint32_t lpc17_getreg(uint32_t addr)
{
  /* Read the value from the register */

  uint32_t val = getreg32(addr);

  /* Check if we need to print this value */

  lpc17_checkreg(addr, val, false);
  return val;
}
#endif

/*******************************************************************************
 * Name: lpc17_putreg
 *
 * Description:
 *   Set the contents of an LPC17xx register to a value
 *
 *******************************************************************************/

#ifdef CONFIG_LPC17_USBHOST_REGDEBUG
static void lpc17_putreg(uint32_t val, uint32_t addr)
{
  /* Check if we need to print this value */

  lpc17_checkreg(addr, val, true);

  /* Write the value */

  putreg32(val, addr);
}
#endif

/****************************************************************************
 * Name: lpc17_takesem
 *
 * Description:
 *   This is just a wrapper to handle the annoying behavior of semaphore
 *   waits that return due to the receipt of a signal.
 *
 *******************************************************************************/

static void lpc17_takesem(sem_t *sem)
{
  /* Take the semaphore (perhaps waiting) */

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

      ASSERT(errno == EINTR);
    }
}

/****************************************************************************
 * Name: lpc17_getle16
 *
 * Description:
 *   Get a (possibly unaligned) 16-bit little endian value.
 *
 *******************************************************************************/

static inline uint16_t lpc17_getle16(const uint8_t *val)
{
  return (uint16_t)val[1] << 8 | (uint16_t)val[0];
}

/****************************************************************************
 * Name: lpc17_putle16
 *
 * Description:
 *   Put a (possibly unaligned) 16-bit little endian value.
 *
 *******************************************************************************/

static void lpc17_putle16(uint8_t *dest, uint16_t val)
{
  dest[0] = val & 0xff; /* Little endian means LS byte first in byte stream */
  dest[1] = val >> 8;
}

/*******************************************************************************
 * Name: lpc17_edalloc
 *
 * Description:
 *   Allocate an ED from the free list
 *
 *******************************************************************************/

static struct lpc17_hced_s *lpc17_edalloc(struct lpc17_usbhost_s *priv)
{
  struct lpc17_hced_s *ret = (struct lpc17_hced_s *)g_edfree;
  if (ret)
    {
      g_edfree = ((struct lpc17_edlist_s*)ret)->flink;
    }
  return ret;
}

/*******************************************************************************
 * Name: lpc17_edfree
 *
 * Description:
 *   Return an ED to the free list
 *
 *******************************************************************************/

static void lpc17_edfree(struct lpc17_usbhost_s *priv, struct lpc17_hced_s *ed)
{
  struct lpc17_edlist_s *edfree = (struct lpc17_edlist_s *)ed;
  edfree->flink                 = g_edfree;
  g_edfree                      = edfree;
}

/*******************************************************************************
 * Name: lpc17_tdalloc
 *
 * Description:
 *   Allocate an TD buffer from the free list
 *
 * Assumptions:
 *   - Called from a single thread so no mutual exclusion is required.
 *   - Never called from an interrupt handler.
 *
 *******************************************************************************/

static uint8_t *lpc17_tdalloc(struct lpc17_usbhost_s *priv)
{
  uint8_t *ret = (uint8_t *)g_tdfree;
  if (ret)
    {
      g_tdfree = ((struct lpc17_buflist_s*)ret)->flink;
    }
  return ret;
}

/*******************************************************************************
 * Name: lpc17_tdfree
 *
 * Description:
 *   Return an TD buffer to the free list
 *
 *******************************************************************************/

static void lpc17_tdfree(struct lpc17_usbhost_s *priv, uint8_t *buffer)
{
  struct lpc17_buflist_s *tdfree = (struct lpc17_buflist_s *)buffer;

  /* This may get called with a NULL buffer pointer on certain error handling
   * paths.
   */

  if (tdfree)
    {
      tdfree->flink              = g_tdfree;
      g_tdfree                   = tdfree;
    }
}

/*******************************************************************************
 * Name: lpc17_ioalloc
 *
 * Description:
 *   Allocate an IO buffer from the free list
 *
 * Assumptions:
 *   - Called from a single thread so no mutual exclusion is required.
 *   - Never called from an interrupt handler.
 *
 *******************************************************************************/

#ifdef CONFIG_UBHOST_AHBIOBUFFERS
static uint8_t *lpc17_ioalloc(struct lpc17_usbhost_s *priv)
{
  uint8_t *ret = (uint8_t *)g_iofree;
  if (ret)
    {
      g_iofree = ((struct lpc17_buflist_s*)ret)->flink;
    }
  return ret;
}
#endif

/*******************************************************************************
 * Name: lpc17_iofree
 *
 * Description:
 *   Return an TD buffer to the free list
 *
 *******************************************************************************/

#ifdef CONFIG_UBHOST_AHBIOBUFFERS
static void lpc17_iofree(struct lpc17_usbhost_s *priv, uint8_t *buffer)
{
  struct lpc17_buflist_s *iofree = (struct lpc17_buflist_s *)buffer;
  iofree->flink                  = g_iofree;
  g_iofree                       = iofree;
}
#endif

/*******************************************************************************
 * Name: lpc17_enqueuetd
 *
 * Description:
 *   Enqueue a transfer descriptor
 *
 *******************************************************************************/

static void lpc17_enqueuetd(volatile struct lpc17_hced_s *ed, uint32_t dirpid,
                            uint32_t toggle, volatile uint8_t *buffer, size_t buflen)
{
  TDHEAD->ctrl    = (GTD_STATUS_R | dirpid | TD_DELAY(0) | toggle | GTD_STATUS_CC_MASK);
  TDTAIL->ctrl    = 0;
  TDHEAD->currptr = (uint32_t)buffer;
  TDTAIL->currptr = 0;
  TDHEAD->next    = (uint32_t)TDTAIL;
  TDTAIL->next    = 0;
  TDHEAD->bufend  = (uint32_t)(buffer + (buflen - 1));
  TDTAIL->bufend  = 0;

  ed->headtd      = (uint32_t)TDHEAD | ((ed->headtd) & 0x00000002);
  ed->tailtd      = (uint32_t)TDTAIL;
  ed->next        = 0;
}

/*******************************************************************************
 * Name: lpc17_ctrltd
 *
 * Description:
 *   Process a IN or OUT request on the control endpoint.  This function
 *   will enqueue the request and wait for it to complete.  Only one transfer
 *   may be queued; Neither these methods nor the transfer() method can be
 *   called again until the control transfer functions returns.
 *
 *   These are blocking methods; these functions will not return until the
 *   control transfer has completed.
 *
 *******************************************************************************/

static int lpc17_ctrltd(struct lpc17_usbhost_s *priv, uint32_t dirpid,
                        uint8_t *buffer, size_t buflen)
{
  uint32_t toggle;
  uint32_t regval;

  if (dirpid == GTD_STATUS_DP_SETUP)
    {
      toggle = GTD_STATUS_T_DATA0;
    }
  else
    {
      toggle = GTD_STATUS_T_DATA1;
    }

  /* Then enqueue the transfer */

  priv->tdstatus = 0;
  lpc17_enqueuetd(EDCTRL, dirpid, toggle, buffer, buflen);

  lpc17_putreg(LPC17_EDCTRL_ADDR, LPC17_USBHOST_CTRLHEADED);

  regval = lpc17_getreg(LPC17_USBHOST_CMDST);
  regval |= OHCI_CMDST_CLF;
  lpc17_putreg(regval, LPC17_USBHOST_CMDST);
      
  regval = lpc17_getreg(LPC17_USBHOST_CTRL);
  regval |= OHCI_CTRL_CLE;
  lpc17_putreg(regval, LPC17_USBHOST_CTRL);

  /* Wait for the Writeback Done Head interrupt */

  lpc17_takesem(&priv->wdhsem);

  /* Check the TDHEAD completion status bits */

  if (priv->tdstatus == 0)
    {
      return OK;
    }
  else 
    {
      return -EIO;
    }
}

/*******************************************************************************
 * Name: lpc17_devdesc
 *
 * Description:
 *   A configuration descriptor has been obtained from the device.  Find the
 *   ID information for the class that supports this device.
 *
 *******************************************************************************/

static inline int lpc17_devdesc(struct lpc17_usbhost_s *priv,
                                const struct usb_devdesc_s *devdesc, int desclen,
                                struct usbhost_id_s *id)
{
  /* Clear the ID info */

  memset(id, 0, sizeof(struct usbhost_id_s));

  /* Check we have enough of the structure to see the ID info. */

  if (desclen >= 7)
    {
      /* Pick off the ID info */

      id->base     = devdesc->class;
      id->subclass = devdesc->subclass;
      id->proto    = devdesc->protocol;

      /* Check if we have enough of the structure to see the VID/PID */

      if (desclen >= 12)
        {
          /* Yes, then pick off the VID and PID as well */

          id->vid = lpc17_getle16(devdesc->vendor);
          id->pid = lpc17_getle16(devdesc->product);
        }
    }

  return OK;
}
                                
/*******************************************************************************
 * Name: lpc17_configdesc
 *
 * Description:
 *   A configuration descriptor has been obtained from the device.  Find the
 *   ID information for the class that supports this device.
 *
 *******************************************************************************/

static inline int
lpc17_configdesc(struct lpc17_usbhost_s *priv, const uint8_t *configdesc,
                 int desclen, struct usbhost_id_s *id)
{
  struct usb_cfgdesc_s *cfgdesc;
  struct usb_ifdesc_s *ifdesc;
  int remaining;

  DEBUGASSERT(priv != NULL && 
              configdesc != NULL &&
              desclen >= sizeof(struct usb_cfgdesc_s));
  
  /* Verify that we were passed a configuration descriptor */

  cfgdesc = (struct usb_cfgdesc_s *)configdesc;
  if (cfgdesc->type != USB_DESC_TYPE_CONFIG)
    {
      return -EINVAL;
    }

  /* Get the total length of the configuration descriptor (little endian).
   * It might be a good check to get the number of interfaces here too.
  */

  remaining = (int)lpc17_getle16(cfgdesc->totallen);

  /* Skip to the next entry descriptor */

  configdesc += cfgdesc->len;
  remaining  -= cfgdesc->len;

  /* Loop where there are more dscriptors to examine */

  memset(&id, 0, sizeof(FAR struct usb_desc_s));
  while (remaining >= sizeof(struct usb_desc_s))
    {
      /* What is the next descriptor? Is it an interface descriptor? */

      ifdesc = (struct usb_ifdesc_s *)configdesc;
      if (ifdesc->type == USB_DESC_TYPE_INTERFACE)
        {
          /* Yes, extract the class information from the interface descriptor.
           * (We are going to need to do more than this here in the future:
           *  ID information might lie elsewhere and we will need the VID and
           *  PID as well).
           */
 
          DEBUGASSERT(remaining >= sizeof(struct usb_ifdesc_s));
          id->base     = ifdesc->class;
          id->subclass = ifdesc->subclass;
          id->proto    = ifdesc->protocol;
          return OK;
        }

     /* Increment the address of the next descriptor */
 
      configdesc += ifdesc->len;
      remaining  -= ifdesc->len;
    }

  return -ENOENT;
}

/*******************************************************************************
 * Name: lpc17_classbind
 *
 * Description:
 *   A configuration descriptor has been obtained from the device.  Try to
 *   bind this configuration descriptor with a supported class.
 *
 *******************************************************************************/

static inline int lpc17_classbind(struct lpc17_usbhost_s *priv,
                                  const uint8_t *configdesc, int desclen,
                                  struct usbhost_id_s *id)
{
  const struct usbhost_registry_s *reg;
  int ret = -EINVAL;

  DEBUGASSERT(priv && priv->class == NULL);
  if (id->base == USB_CLASS_VENDOR_SPEC)
    {
      udbg("BUG: More logic needed to extract VID and PID\n");
    }

  /* Is there is a class implementation registered to support this device. */

  reg = usbhost_findclass(id);
  uvdbg("usbhost_findclass: %p\n", reg);
  if (reg)
    {
      /* Yes.. there is a class for this device.  Get an instance of
       * its interface.
       */

      ret = -ENOMEM;
      priv->class = CLASS_CREATE(reg, &priv->drvr, id);
      uvdbg("CLASS_CREATE: %p\n", priv->class);
      if (priv->class)
        {
          /* Then bind the newly instantiated class instance */

          ret = CLASS_CONNECT(priv->class, configdesc, desclen);
          if (ret != OK)
            {
              udbg("CLASS_CONNECT failed: %d\n", ret);
              CLASS_DISCONNECTED(priv->class);
              priv->class = NULL;
            }
        }
    }

  uvdbg("Returning: %d\n", ret);
  return ret;
}

/*******************************************************************************
 * Name: lpc17_usbinterrupt
 *
 * Description:
 *   USB interrupt handler
 *
 *******************************************************************************/

static int lpc17_usbinterrupt(int irq, FAR void *context)
{
  struct lpc17_usbhost_s *priv = &g_usbhost;

  /* Read the device interrupt status register */

  uint32_t intstatus;
  uint32_t intenable;

  /* Read Interrupt Status and mask out interrupts that are not enabled. */

  intstatus  = lpc17_getreg(LPC17_USBHOST_INTST);
  intenable  = lpc17_getreg(LPC17_USBHOST_INTEN);
  ullvdbg("INST: %08x INTEN:\n", intstatus, intenable);

  intstatus &= intenable;
  if (intstatus != 0)
    {
      /* Root hub status change interrupt */

      if ((intstatus & OHCI_INT_RHSC) != 0)
        {
          uint32_t rhportst1 = lpc17_getreg(LPC17_USBHOST_RHPORTST1);
          ullvdbg("Root Hub Status Change, RHPORTST: %08x\n", rhportst1);

          if ((rhportst1 & OHCI_RHPORTST_CSC) != 0)
            {
              uint32_t rhstatus = lpc17_getreg(LPC17_USBHOST_RHSTATUS);
              ullvdbg("Connect Status Change, RHSTATUS: %08x\n", rhportst1);

              /* If DRWE is set, Connect Status Change indicates a remote wake-up event */

              if (rhstatus & OHCI_RHSTATUS_DRWE)
                {
                  ullvdbg("DRWE: Remote wake-up\n");
                }

              /* Otherwise... Not a remote wake-up event */

              else
                {
                  /* Check if we are now connected */

                  if ((rhportst1 & OHCI_RHPORTST_CCS) != 0)
                    {
                      if (!priv->connected)
                        {
                          ullvdbg("Connected\n");
                          DEBUGASSERT(priv->rhssem.semcount <= 0);
                          priv->tdstatus = 0;
                          priv->connected = true;
                          lpc17_givesem(&priv->rhssem);
                        }
                      else
                        {
                          ulldbg("Spurious status change (connected)\n");
                        }
                    }

                  /* Check if we are now disconnected */
 
                  else if (priv->connected)
                    {
                      /* Yes.. disable interrupts and disconnect the device */

                      ullvdbg("Disconnected\n");
                      lpc17_putreg(0, LPC17_USBHOST_INTEN);
                      priv->connected = false;

                      /* Are we bound to a class instance? */

                      if (priv->class)
                        {
                          /* Yes.. Disconnect the class */

                          CLASS_DISCONNECTED(priv->class);
                        }
                      lpc17_givesem(&priv->rhssem);
                    }
                  else
                    {
                       ulldbg("Spurious status change (disconnected)\n");
                    }
                }

              /* Clear the CSC interrupt */

              lpc17_putreg(OHCI_RHPORTST_CSC, LPC17_USBHOST_RHPORTST1);
            }

          /* Check for port reset status change */

          if ((rhportst1 & OHCI_RHPORTST_PRSC) != 0)
            {
              /* Release the RH port from reset */

              lpc17_putreg(OHCI_RHPORTST_PRSC, LPC17_USBHOST_RHPORTST1);
            }
        }

      /* Writeback Done Head interrupt */
 
      if ((intstatus & OHCI_INT_WDH) != 0)
        {
          /* Get the condition code from the control word */

          priv->tdstatus = (TDHEAD->ctrl & GTD_STATUS_CC_MASK) >> GTD_STATUS_CC_SHIFT;

          /* And wake up the thread waiting for the WDH event */

          DEBUGASSERT(priv->wdhsem.semcount <= 0);
          lpc17_givesem(&priv->wdhsem);
        }

      /* Clear interrupt status register */

      lpc17_putreg(intstatus, LPC17_USBHOST_INTST);
    }

  return OK;
}

/*******************************************************************************
 * USB Host Controller Operations
 *******************************************************************************/

/*******************************************************************************
 * Name: lpc17_wait
 *
 * Description:
 *   Wait for a device to be connected or disconneced.
 *
 * Input Parameters:
 *   drvr - The USB host driver instance obtained as a parameter from the call to
 *      the class create() method.
 *   connected - TRUE: Wait for device to be connected; FALSE: wait for device
 *      to be disconnected
 *
 * Returned Values:
 *   Zero (OK) is returned when a device in connected. This function will not
 *   return until either (1) a device is connected or (2) some failure occurs.
 *   On a failure, a negated errno value is returned indicating the nature of
 *   the failure
 *
 * Assumptions:
 *   - Called from a single thread so no mutual exclusion is required.
 *   - Never called from an interrupt handler.
 *
 *******************************************************************************/

static int lpc17_wait(FAR struct usbhost_driver_s *drvr, bool connected)
{
  struct lpc17_usbhost_s *priv = (struct lpc17_usbhost_s *)drvr;

  /* Are we already connected? */

  while (priv->connected == connected)
    {
      /* No... wait for the connection/disconnection */

      lpc17_takesem(&priv->rhssem);
    }

  return OK;
}

/*******************************************************************************
 * Name: lpc17_enumerate
 *
 * Description:
 *   Enumerate the connected device.  As part of this enumeration process,
 *   the driver will (1) get the device's configuration descriptor, (2)
 *   extract the class ID info from the configuration descriptor, (3) call
 *   usbhost_findclass() to find the class that supports this device, (4)
 *   call the create() method on the struct usbhost_registry_s interface
 *   to get a class instance, and finally (5) call the configdesc() method
 *   of the struct usbhost_class_s interface.  After that, the class is in
 *   charge of the sequence of operations.
 *
 * Input Parameters:
 *   drvr - The USB host driver instance obtained as a parameter from the call to
 *      the class create() method.
 *
 * Returned Values:
 *   On success, zero (OK) is returned. On a failure, a negated errno value is
 *   returned indicating the nature of the failure
 *
 * Assumptions:
 *   - Only a single class bound to a single device is supported.
 *   - Called from a single thread so no mutual exclusion is required.
 *   - Never called from an interrupt handler.
 *
 *******************************************************************************/

static int lpc17_enumerate(FAR struct usbhost_driver_s *drvr)
{
  struct lpc17_usbhost_s *priv = (struct lpc17_usbhost_s *)drvr;
  struct usb_ctrlreq_s *ctrlreq;
  struct usbhost_id_s id;
  unsigned int len;
  uint8_t *buffer;
  int  ret;

  /* Are we connected to a device?  The caller should have called the wait()
   * method first to be assured that a device is connected.
   */

  while (!priv->connected)
    {
      /* No, return an error */

      udbg("Not connected\n");
	  return -ENODEV;
    }
  uvdbg("Enumerate the device\n");

  /* Allocate TD buffers for use in this function.  We will need two:
   * One for the request and one for the data buffer.
   */

  ctrlreq = (struct usb_ctrlreq_s *)lpc17_tdalloc(priv);
  if (!ctrlreq)
    {
      udbg("lpc17_tdalloc() failed\n");
      return -ENOMEM;
    }

  buffer = lpc17_tdalloc(priv);
  if (!buffer)
    {
      udbg("lpc17_tdalloc() failed\n");
      ret = -ENOMEM;
      goto errout;
    }

  /* USB 2.0 spec says at least 50ms delay before port reset */

  up_mdelay(100);

  /* Put the RH port in reset */

  lpc17_putreg(OHCI_RHPORTST_PRS, LPC17_USBHOST_RHPORTST1);

  /* Wait for the port reset to complete */

  while ((lpc17_getreg(LPC17_USBHOST_RHPORTST1) & OHCI_RHPORTST_PRS) != 0);

  /* Release the RH port from reset and wait a bit */

  lpc17_putreg(OHCI_RHPORTST_PRSC, LPC17_USBHOST_RHPORTST1);
  up_mdelay(200);

  /* Set max pkt size = 8 */

  EDCTRL->ctrl = 8 << ED_CONTROL_MPS_SHIFT;

  /* Read first 8 bytes of the device descriptor */

  ctrlreq->type = USB_REQ_DIR_IN|USB_REQ_RECIPIENT_DEVICE;
  ctrlreq->req  = USB_REQ_GETDESCRIPTOR;
  lpc17_putle16(ctrlreq->value, (USB_DESC_TYPE_DEVICE << 8));
  lpc17_putle16(ctrlreq->index, 0);
  lpc17_putle16(ctrlreq->len, 8);

  ret = lpc17_ctrlin(drvr, ctrlreq, buffer);
  if (ret != OK)
    {
      udbg("ERROR: GETDESCRIPTOR/DEVICE, lpc17_ctrlin returned %d\n", ret);
      goto errout;
    }

  /* Extract info from the device descriptor */

  {
    struct usb_devdesc_s *devdesc = (struct usb_devdesc_s *)buffer;

    /* Extract the max packetsize for endpoint 0 */

    EDCTRL->ctrl = (uint32_t)(devdesc->mxpacketsize) << ED_CONTROL_MPS_SHIFT;
    
    /* Get class identification information from the device descriptor.  Most
     * devices set this to USB_CLASS_PER_INTERFACE (zero) and provide the
     * identification informatino in the interface descriptor(s).  That allows
     * a device to support multiple, different classes.
     */

    (void)lpc17_devdesc(priv, devdesc, 8, &id);

    /* NOTE: Additional logic is needed here.  We will need additional logic
     * to (1) get the full device descriptor, (1) extract the vendor/product IDs
     * and (2) extract the number of configurations from the (full) device
     * descriptor.
     */
  }

  /* Set the device address to 1 */

  ctrlreq->type = USB_REQ_DIR_OUT|USB_REQ_RECIPIENT_DEVICE;
  ctrlreq->req  = USB_REQ_SETADDRESS;
  lpc17_putle16(ctrlreq->value, (1 << 8));
  lpc17_putle16(ctrlreq->index, 0);
  lpc17_putle16(ctrlreq->len, 0);

  ret = lpc17_ctrlout(drvr, ctrlreq, NULL);
  if (ret != OK)
    {
      udbg("ERROR: SETADDRESS lpc17_ctrlout returned %d\n", ret);
      goto errout;
    }
  up_mdelay(2);

  /* Modify control pipe with address 1 */

  EDCTRL->ctrl = (EDCTRL->ctrl) | 1;

 /* Get the configuration descriptor (only), index == 0.  More logic is
  * needed in order to handle devices with multiple configurations.
  */

  ctrlreq->type = USB_REQ_DIR_IN|USB_REQ_RECIPIENT_DEVICE;
  ctrlreq->req  = USB_REQ_GETDESCRIPTOR;
  lpc17_putle16(ctrlreq->value, (USB_DESC_TYPE_CONFIG << 8));
  lpc17_putle16(ctrlreq->index, 0);
  lpc17_putle16(ctrlreq->len, USB_SIZEOF_CFGDESC);

  ret = lpc17_ctrlin(drvr, ctrlreq, buffer);
  if (ret != OK)
   {
      udbg("ERROR: GETDESCRIPTOR/CONFIG, lpc17_ctrlin returned %d\n", ret);
      goto errout;
    }

  /* Extract the full size of the configuration data */

  len = ((struct usb_cfgdesc_s *)buffer)->len;

  /* Get all of the configuration descriptor data, index == 0 */

  ctrlreq->type = USB_REQ_DIR_IN|USB_REQ_RECIPIENT_DEVICE;
  ctrlreq->req  = USB_REQ_GETDESCRIPTOR;
  lpc17_putle16(ctrlreq->value, (USB_DESC_TYPE_CONFIG << 8));
  lpc17_putle16(ctrlreq->index, 0);
  lpc17_putle16(ctrlreq->len, len);

  ret = lpc17_ctrlin(drvr, ctrlreq, buffer);
  if (ret != OK)
    {
      udbg("ERROR: GETDESCRIPTOR/CONFIG, lpc17_ctrlin returned %d\n", ret);
      goto errout;
    }

  /* Select device configuration 1 */

  ctrlreq->type = USB_REQ_DIR_OUT|USB_REQ_RECIPIENT_DEVICE;
  ctrlreq->req  = USB_REQ_SETCONFIGURATION;
  lpc17_putle16(ctrlreq->value, 1);
  lpc17_putle16(ctrlreq->index, 0);
  lpc17_putle16(ctrlreq->len, 0);

  ret = lpc17_ctrlout(drvr, ctrlreq, NULL);
  if (ret != OK)
    {
      udbg("ERROR: SETCONFIGURATION, lpc17_ctrlout returned %d\n", ret);
      goto errout;
    }

  /* Free the TD that we were using for the request buffer.  It is not needed
   * further here but it may be needed by the class driver during its connection
   * operations.  NOTE:  lpc17_tdfree() can be called with a NULL pointer later.
   */
 
  lpc17_tdfree(priv, (uint8_t*)ctrlreq);
  ctrlreq = NULL;

  /* Was the class identification information provided in the device descriptor?
   * Or do we need to find it in the interface descriptor(s)?
   */

  if (id.base == USB_CLASS_PER_INTERFACE)
    {
      /* Get the class identification information for this device from the
       * interface descriptor(s).  Hmmm.. More logic is need to handle the
       * case of multiple interface descriptors.
       */

      ret = lpc17_configdesc(priv, buffer, len, &id);
      if (ret != OK)
        {
          udbg("ERROR: lpc17_configdesc returned %d\n", ret);
          goto errout;
        }
    }

  /* Some devices may require this delay before initialization */

  up_mdelay(100);

  /* Parse the configuration descriptor and bind to the class instance for the
   * device.  This needs to be the last thing done because the class driver
   * will begin configuring the device.
   */

  ret = lpc17_classbind(priv, buffer, len, &id);
  if (ret != OK)
    {
      udbg("ERROR: lpc17_classbind returned %d\n", ret);
    }

errout:
  lpc17_tdfree(priv, buffer);
  lpc17_tdfree(priv, (uint8_t*)ctrlreq);
  return ret;
}

/*******************************************************************************
 * Name: lpc17_alloc
 *
 * Description:
 *   Some hardware supports special memory in which transfer descriptors can
 *   be accessed more efficiently.  This method provides a mechanism to allocate
 *   the transfer descriptor memory.  If the underlying hardware does not support
 *   such "special" memory, this functions may simply map to malloc.
 *
 * Input Parameters:
 *   drvr - The USB host driver instance obtained as a parameter from the call to
 *      the class create() method.
 *   buffer - The address of a memory location provided by the caller in which to
 *     return the allocated buffer memory address.
 *   maxlen - The address of a memory location provided by the caller in which to
 *     return the maximum size of the allocated buffer memory.
 *
 * Returned Values:
 *   On success, zero (OK) is returned. On a failure, a negated errno value is
 *   returned indicating the nature of the failure
 *
 * Assumptions:
 *   - Called from a single thread so no mutual exclusion is required.
 *   - Never called from an interrupt handler.
 *
 *******************************************************************************/

static int lpc17_alloc(FAR struct usbhost_driver_s *drvr,
                       FAR uint8_t **buffer, FAR size_t *maxlen)
{
  struct lpc17_usbhost_s *priv = (struct lpc17_usbhost_s *)drvr;
  DEBUGASSERT(priv && buffer && maxlen);

  *buffer = lpc17_tdalloc(priv);
  if (*buffer)
    {
      *maxlen = CONFIG_USBHOST_TDBUFSIZE;
      return OK;
    }
  return -ENOMEM;
}

/*******************************************************************************
 * Name: lpc17_free
 *
 * Description:
 *   Some hardware supports special memory in which transfer descriptors can
 *   be accessed more efficiently.  This method provides a mechanism to free that
 *   transfer descriptor memory.  If the underlying hardware does not support
 *   such "special" memory, this functions may simply map to free().
 *
 * Input Parameters:
 *   drvr - The USB host driver instance obtained as a parameter from the call to
 *      the class create() method.
 *   buffer - The address of the allocated buffer memory to be freed.
 *
 * Returned Values:
 *   On success, zero (OK) is returned. On a failure, a negated errno value is
 *   returned indicating the nature of the failure
 *
 * Assumptions:
 *   - Called from a single thread so no mutual exclusion is required.
 *   - Never called from an interrupt handler.
 *
 *******************************************************************************/

static int lpc17_free(FAR struct usbhost_driver_s *drvr, FAR uint8_t *buffer)
{
  struct lpc17_usbhost_s *priv = (struct lpc17_usbhost_s *)drvr;
  DEBUGASSERT(priv && buffer);
  lpc17_tdfree(priv, buffer);
  return OK;
}

/*******************************************************************************
 * Name: lpc17_ctrlin and lpc17_ctrlout
 *
 * Description:
 *   Process a IN or OUT request on the control endpoint.  These methods
 *   will enqueue the request and wait for it to complete.  Only one transfer may be
 *   queued; Neither these methods nor the transfer() method can be called again
 *   until the control transfer functions returns.
 *
 *   These are blocking methods; these functions will not return until the
 *   control transfer has completed.
 *
 * Input Parameters:
 *   drvr - The USB host driver instance obtained as a parameter from the call to
 *      the class create() method.
 *   req - Describes the request to be sent.  This request must lie in memory
 *      created by DRVR_ALLOC.
 *   buffer - A buffer used for sending the request and for returning any
 *     responses.  This buffer must be large enough to hold the length value
 *     in the request description. buffer must have been allocated using DRVR_ALLOC
 *
 *   NOTE: On an IN transaction, req and buffer may refer to the same allocated
 *   memory.
 *
 * Returned Values:
 *   On success, zero (OK) is returned. On a failure, a negated errno value is
 *   returned indicating the nature of the failure
 *
 * Assumptions:
 *   - Only a single class bound to a single device is supported.
 *   - Called from a single thread so no mutual exclusion is required.
 *   - Never called from an interrupt handler.
 *
 *******************************************************************************/

static int lpc17_ctrlin(FAR struct usbhost_driver_s *drvr,
                        FAR const struct usb_ctrlreq_s *req,
                        FAR uint8_t *buffer)
{
  struct lpc17_usbhost_s *priv = (struct lpc17_usbhost_s *)drvr;
  uint16_t len;
  int  ret;

  len = lpc17_getle16(req->len);
  ret = lpc17_ctrltd(priv, GTD_STATUS_DP_SETUP, (uint8_t*)req, USB_SIZEOF_CTRLREQ);
  if (ret == OK)
    {
      if (len)
        {
          ret = lpc17_ctrltd(priv, GTD_STATUS_DP_IN, buffer, len);
        }

      if (ret == OK)
        {
          ret = lpc17_ctrltd(priv, GTD_STATUS_DP_OUT, NULL, 0);
        }
    }
  return ret;
}

static int lpc17_ctrlout(FAR struct usbhost_driver_s *drvr,
                         FAR const struct usb_ctrlreq_s *req,
                         FAR const uint8_t *buffer)
{
  struct lpc17_usbhost_s *priv = (struct lpc17_usbhost_s *)drvr;
  uint16_t len;
  int  ret;

  len = lpc17_getle16(req->len);
  ret = lpc17_ctrltd(priv, GTD_STATUS_DP_SETUP, (uint8_t*)req, USB_SIZEOF_CTRLREQ);
  if (ret == OK)
    {
      if (len)
        {
          ret = lpc17_ctrltd(priv, GTD_STATUS_DP_OUT, (uint8_t*)buffer, len);
        }

      if (ret == OK)
        {
          ret = lpc17_ctrltd(priv, GTD_STATUS_DP_IN, NULL, 0);
        }
    }
  return ret;
}

/*******************************************************************************
 * Name: lpc17_transfer
 *
 * Description:
 *   Process a request to handle a transfer descriptor.  This method will
 *   enqueue the transfer request and return immediately.  Only one transfer may be
 *   queued; Neither this method nor the ctrlin or ctrlout methods can be called
 *   again until this function returns.
 *
 *   This is a blocking method; this functions will not return until the
 *   transfer has completed.
 *
 * Input Parameters:
 *   drvr - The USB host driver instance obtained as a parameter from the call to
 *      the class create() method.
 *   ed - The IN or OUT endpoint descriptor for the device endpoint on which to
 *      perform the transfer.
 *   buffer - A buffer containing the data to be sent (OUT endpoint) or received
 *     (IN endpoint).  buffer must have been allocated using DRVR_ALLOC
 *   buflen - The length of the data to be sent or received.
 *
 * Returned Values:
 *   On success, zero (OK) is returned. On a failure, a negated errno value is
 *   returned indicating the nature of the failure
 *
 * Assumptions:
 *   - Only a single class bound to a single device is supported.
 *   - Called from a single thread so no mutual exclusion is required.
 *   - Never called from an interrupt handler.
 *
 *******************************************************************************/

static int lpc17_transfer(FAR struct usbhost_driver_s *drvr,
                          FAR struct usbhost_epdesc_s *ep,
                          FAR uint8_t *buffer, size_t buflen)
{
  struct lpc17_usbhost_s *priv = (struct lpc17_usbhost_s *)drvr;
  struct lpc17_hced_s *ed = NULL;
  uint32_t dirpid;
  uint32_t regval;
#ifdef CONFIG_UBHOST_AHBIOBUFFERS
  uint8_t *origbuf = NULL;
#endif
  int ret = -ENOMEM;

  /* Allocate an IO buffer if the user buffer does not lie in AHB SRAM */

#ifdef CONFIG_UBHOST_AHBIOBUFFERS
  if ((uintptr_t)buffer < LPC17_SRAM_BANK0 ||
      (uintptr_t)buffer >= (LPC17_SRAM_BANK0 + LPC17_SRAM_BANK0 + LPC17_SRAM_BANK0))
    {
      /* Will the transfer fit in an IO buffer? */

      if (buflen > CONFIG_USBHOST_IOBUFSIZE)
        {
          uvdbg("buflen (%d) > IO buffer size (%d)\n",
                 buflen, CONFIG_USBHOST_IOBUFSIZE);
          goto errout;
        }

      /* Allocate an IO buffer in AHB SRAM */

      origbuf = buffer;
      buffer  = lpc17_ioalloc(priv);
      if (!buffer)
        {
          uvdbg("IO buffer allocation failed\n");
          goto errout;
        }

      /* Copy the user data into the AHB SRAM IO buffer.  Sad... so
       * inefficient.  But without exposing the AHB SRAM to the final,
       * end-user client I don't know of any way around this copy.
       */

      memcpy(buffer, origbuf, buflen);
    }
#endif

  /* Allocate an ED */

  ed = lpc17_edalloc(priv);
  if (!ed)
    {
      uvdbg("ED allocation failed\n");
      goto errout;
    }

  /* Format the endpoint descriptor */
 
  lpc17_edinit(ed);
  ed->ctrl = (uint32_t)(ep->addr) << ED_CONTROL_EN_SHIFT |
             (uint32_t)(ep->mxpacketsize) << ED_CONTROL_MPS_SHIFT;

  /* Get the direction of the endpoint */

  if (ep->in)
    {
      ed->ctrl |= ED_CONTROL_D_IN;
      dirpid    = GTD_STATUS_DP_IN;
    }
  else
    {
      ed->ctrl |= ED_CONTROL_D_OUT;
      dirpid    = GTD_STATUS_DP_OUT;
    }

  /* Then enqueue the transfer */

  priv->tdstatus = 0;
  lpc17_enqueuetd(ed, dirpid, GTD_STATUS_T_TOGGLE, buffer, buflen);

  lpc17_putreg((uint32_t)ed, LPC17_USBHOST_BULKHEADED);

  regval = lpc17_getreg(LPC17_USBHOST_CMDST);
  regval |= OHCI_CMDST_BLF;
  lpc17_putreg(regval, LPC17_USBHOST_CMDST);
      
  regval = lpc17_getreg(LPC17_USBHOST_CTRL);
  regval |= OHCI_CTRL_BLE;
  lpc17_putreg(regval, LPC17_USBHOST_CTRL);

  /* Wait for the Writeback Done Head interrupt */

  lpc17_takesem(&priv->wdhsem);

  /* Check the TDHEAD completion status bits */

  if (priv->tdstatus == 0)
    {
      ret = OK;
    }
  else 
    {
      uvdbg("Bad TD completion status: %d\n", priv->tdstatus);
      ret = -EIO;
    }

errout:
  /* Free any temporary IO buffers */

#ifdef CONFIG_UBHOST_AHBIOBUFFERS
  if (buffer && origbuf)
    {
      lpc17_iofree(priv, buffer);
    }
#endif

  /* Free the endpoint descriptor */

  if (ed)
    {
      lpc17_edfree(priv, ed);
    }

  return ret;
}

/*******************************************************************************
 * Name: lpc17_disconnect
 *
 * Description:
 *   Called by the class when an error occurs and driver has been disconnected.
 *   The USB host driver should discard the handle to the class instance (it is
 *   stale) and not attempt any further interaction with the class driver instance
 *   (until a new instance is received from the create() method).  The driver
 *   should not called the class' disconnected() method.
 *
 * Input Parameters:
 *   drvr - The USB host driver instance obtained as a parameter from the call to
 *      the class create() method.
 *
 * Returned Values:
 *   None
 *
 * Assumptions:
 *   - Only a single class bound to a single device is supported.
 *   - Called from a single thread so no mutual exclusion is required.
 *   - Never called from an interrupt handler.
 *
 *******************************************************************************/

static void lpc17_disconnect(FAR struct usbhost_driver_s *drvr)
{
  struct lpc17_usbhost_s *priv = (struct lpc17_usbhost_s *)drvr;
  priv->class = NULL;
}
  
/*******************************************************************************
 * Initialization
 *******************************************************************************/

static void lpc17_tdinit(volatile struct lpc17_hctd_s *td)
{
  td->ctrl    = 0;
  td->currptr = 0;
  td->next    = 0;
  td->bufend  = 0;
}

static void lpc17_edinit(volatile struct lpc17_hced_s *ed)
{
  ed->ctrl    = 0;
  ed->tailtd  = 0;
  ed->headtd  = 0;
  ed->next    = 0;
}

static void lpc17_hccainit(volatile struct lpc17_hcca_s *hcca)
{
  int  i;

  for (i = 0; i < 32; i++)
    {
      hcca->inttbl[i] = 0;
    }

  hcca->frameno   = 0;
  hcca->donehead  = 0;
}

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

/*******************************************************************************
 * Name: usbhost_initialize
 *
 * Description:
 *   Initialize USB host device controller hardware.
 *
 * Input Parameters:
 *   controller -- If the device supports more than USB host controller, then
 *     this identifies which controller is being intialized.  Normally, this
 *     is just zero.
 *
 * Returned Value:
 *   And instance of the USB host interface.  The controlling task should
 *   use this interface to (1) call the wait() method to wait for a device
 *   to be connected, and (2) call the enumerate() method to bind the device
 *   to a class driver.
 *
 * Assumptions:
 * - This function should called in the initialization sequence in order
 *   to initialize the USB device functionality.
 * - Class drivers should be initialized prior to calling this function.
 *   Otherwise, there is a race condition if the device is already connected.
 *
 *******************************************************************************/

FAR struct usbhost_driver_s *usbhost_initialize(int controller)
{
  struct lpc17_usbhost_s *priv = &g_usbhost;
  uint32_t regval;
  uint8_t *buffer;
  irqstate_t flags;
  int i;

  DEBUGASSERT(controller == 0);

  /* Initialize the state data structure */

  sem_init(&priv->rhssem, 0, 0);
  sem_init(&priv->wdhsem, 0, 0);

  /* Enable power by setting PCUSB in the PCONP register */

  flags   = irqsave();
  regval  = lpc17_getreg(LPC17_SYSCON_PCONP);
  regval |= SYSCON_PCONP_PCUSB;
  lpc17_putreg(regval, LPC17_SYSCON_PCONP);

  /* Enable clocking on USB (USB PLL clocking was initialized in very low-
   * evel clock setup logic (see lpc17_clockconfig.c)).  We do still need
   * to set up USBOTG CLKCTRL to enable clocking.
   *
   * NOTE: The PORTSEL clock needs to be enabled only when accessing OTGSTCTRL
   */

  lpc17_putreg(LPC17_CLKCTRL_ENABLES, LPC17_USBOTG_CLKCTRL);

  /* Then wait for the clocks to be reported as "ON" */

  do
    {
      regval = lpc17_getreg(LPC17_USBOTG_CLKST);
    }
  while ((regval & LPC17_CLKCTRL_ENABLES) != LPC17_CLKCTRL_ENABLES);

  /* Set the OTG status and control register.  Bits 0:1 apparently mean:
   *
   *   00: U1=device, U2=host
   *   01: U1=host, U2=host
   *   10: reserved
   *   11: U1=host, U2=device
   *
   * NOTE: The PORTSEL clock needs to be enabled when accessing OTGSTCTRL
   */

  lpc17_putreg(1, LPC17_USBOTG_STCTRL);

  /* Now we can turn off the PORTSEL clock */

  lpc17_putreg((LPC17_CLKCTRL_ENABLES & ~USBDEV_CLK_PORTSELCLK), LPC17_USBOTG_CLKCTRL);

  /* Step 3: Configure I/O pins */

  usbhost_dumpgpio();
  lpc17_configgpio(GPIO_USB_DP);      /* Positive differential data */
  lpc17_configgpio(GPIO_USB_DM);      /* Negative differential data */
  lpc17_configgpio(GPIO_USB_UPLED);   /* GoodLink LED control signal */
  lpc17_configgpio(GPIO_USB_PPWR);    /* Port Power enable signal for USB port */
  lpc17_configgpio(GPIO_USB_PWRD);    /* Power Status for USB port (host power switch) */
  lpc17_configgpio(GPIO_USB_OVRCR);   /* USB port Over-Current status */
  usbhost_dumpgpio();

  udbg("Initializing Host Stack\n");

  /* Initialize all the TDs, EDs and HCCA to 0 */

  lpc17_hccainit(HCCA);
  lpc17_tdinit(TDHEAD);
  lpc17_tdinit(TDTAIL);
  lpc17_edinit(EDCTRL);

  /* Initialize user-configurable EDs */

  for (i = 0; i < CONFIG_USBHOST_NEDS; i++)
    {
      /* Put the ED in a free list */

      lpc17_edfree(priv, &EDFREE[i]);
    }

  /* Initialize user-configurable TD buffers */

  buffer = TDFREE;
  for (i = 0; i < CONFIG_USBHOST_NEDS; i++)
    {
      /* Put the TD buffer in a free list */

      lpc17_tdfree(priv, buffer);
      buffer += CONFIG_USBHOST_TDBUFSIZE;
    }

#ifdef CONFIG_UBHOST_AHBIOBUFFERS
  /* Initialize user-configurable IO buffers */

  buffer = IOFREE;
  for (i = 0; i < LPC17_IOBUFFERS; i++)
    {
      /* Put the IO buffer in a free list */

      lpc17_iofree(priv, buffer);
      buffer += CONFIG_USBHOST_IOBUFSIZE;
    }
#endif

  /* Wait 50MS then perform hardware reset */

  up_mdelay(50);

  lpc17_putreg(0, LPC17_USBHOST_CTRL);        /* Hardware reset */
  lpc17_putreg(0, LPC17_USBHOST_CTRLHEADED);  /* Initialize control list head to Zero */
  lpc17_putreg(0, LPC17_USBHOST_BULKHEADED);  /* Initialize bulk list head to Zero */

  /* Software reset */

  lpc17_putreg(OHCI_CMDST_HCR, LPC17_USBHOST_CMDST);
  
  /* Write Fm interval and largest data packet counter */
  
  lpc17_putreg(DEFAULT_FMINTERVAL, LPC17_USBHOST_FMINT);

  /* Put HC in operational state */

  regval  = lpc17_getreg(LPC17_USBHOST_CTRL);
  regval &= ~OHCI_CTRL_HCFS_MASK;
  regval |= OHCI_CTRL_HCFS_OPER;
  lpc17_putreg(regval, LPC17_USBHOST_CTRL);

  /* Set global power */

  lpc17_putreg(OHCI_RHSTATUS_LPS, LPC17_USBHOST_RHSTATUS);

  /* Set HCCA base address */

  lpc17_putreg((uint32_t)HCCA, LPC17_USBHOST_HCCA);

  /* Clear pending interrupts */

  regval = lpc17_getreg(LPC17_USBHOST_INTST);
  lpc17_putreg(regval, LPC17_USBHOST_INTST);

  /* Enable OHCI interrupts */
 
  lpc17_putreg((OHCI_INT_MIE | OHCI_INT_WDH | OHCI_INT_RHSC), LPC17_USBHOST_INTEN);

  /* Attach USB host controller interrupt handler */

  if (irq_attach(LPC17_IRQ_USB, lpc17_usbinterrupt) != 0)
    {
      udbg("Failed to attach IRQ\n");
      return NULL;
    }

  /* Enable USB interrupts at the SYCON controller */

  flags = irqsave();
  regval = lpc17_getreg(LPC17_SYSCON_USBINTST);
  regval |= SYSCON_USBINTST_ENINTS;
  lpc17_putreg(regval, LPC17_SYSCON_USBINTST);
  irqrestore(flags);

  /* Enable interrupts at the interrupt controller */

  up_enable_irq(LPC17_IRQ_USB); /* enable USB interrupt */
  udbg("USB host Initialized\n");
  return &priv->drvr;
}