summaryrefslogtreecommitdiff
path: root/nuttx/drivers/usbdev/usbdev_serial.c
blob: 9ab99d3cbc385becda5a7fc91debcd01f56be2e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
/****************************************************************************
 * drivers/usbdev/usbdev_serial.c
 *
 *   Copyright (C) 2008 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <spudmonkey@racsa.co.cr>
 *
 * This logic emulates the Prolific PL2303 serial/USB converter
 *
 * 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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>
#include <errno.h>
#include <queue.h>
#include <debug.h>

#include <nuttx/arch.h>
#include <nuttx/serial.h>
#include <nuttx/usb.h>
#include <nuttx/usbdev.h>
#include <nuttx/usbdev_trace.h>

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

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

/* Number of requests in the write queue */

#ifndef CONFIG_USBSER_NWRREQS
#  define CONFIG_USBSER_NWRREQS 4
#endif

/* Number of requests in the read queue */

#ifndef CONFIG_USBSER_NRDREQS
#  define CONFIG_USBSER_NRDREQS 4
#endif

/* Write buffer size */

#ifndef CONFIG_USBSER_WRBUFFERSIZE
#  define CONFIG_USBSER_WRBUFFERSIZE 1024
#endif

/* Logical endpoint numbers / max packet sizes */

#ifndef CONFIG_USBSER_EPINTIN
#  warning "EPINTIN not defined in the configuration"
#  define CONFIG_USBSER_EPINTIN 1
#endif

#ifndef CONFIG_USBSER_EPBULKOUT
#  warning "EPBULKOUT not defined in the configuration"
#  define CONFIG_USBSER_EPBULKOUT 2
#endif

#ifndef CONFIG_USBSER_EPBULKIN
#  warning "EPBULKIN not defined in the configuration"
#  define CONFIG_USBSER_EPBULKIN 3
#endif

/* Packet and request buffer sizes */

#ifndef CONFIG_USBSER_EP0MAXPACKET
#  define CONFIG_USBSER_EP0MAXPACKET 64
#endif

#undef CONFIG_USBSER_BULKREQLEN

/* Vendor and product IDs and strings */

#ifndef CONFIG_USBSER_VENDORID
#  define CONFIG_USBSER_VENDORID  0x067b
#endif

#ifndef CONFIG_USBSER_PRODUCTID
#  define CONFIG_USBSER_PRODUCTID 0x2303
#endif

#ifndef CONFIG_USBSER_VENDORSTR
#  warning "No Vendor string specified"
#  define CONFIG_USBSER_VENDORSTR  "NuttX"
#endif

#ifndef CONFIG_USBSER_PRODUCTSTR
#  warning "No Product string specified"
#  define CONFIG_USBSER_PRODUCTSTR "USBdev Serial"
#endif

#undef CONFIG_USBSER_SERIALSTR
#define CONFIG_USBSER_SERIALSTR "0"

#undef CONFIG_USBSER_CONFIGSTR
#define CONFIG_USBSER_CONFIGSTR "Bulk"

/* USB Controller */

#ifndef CONFIG_USBDEV_SELFPOWERED
#  define SELFPOWERED USB_CONFIG_ATT_SELFPOWER
#else
#  define SELFPOWERED (0)
#endif

#ifndef CONFIG_USBDEV_REMOTEWAKEUP
#  define REMOTEWAKEUP USB_CONFIG_ATTR_WAKEUP
#else
#  define REMOTEWAKEUP (0)
#endif

#ifndef CONFIG_USBDEV_MAXPOWER
#  define CONFIG_USBDEV_MAXPOWER 100
#endif

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

/* These settings are not modifiable via the NuttX configuration */

#define USBSER_VERSIONNO           (0x0202) /* Device version number */
#define USBSER_CONFIGIDNONE        (0)      /* Config ID means to return to address mode */
#define USBSER_CONFIGID            (1)      /* The only supported configuration ID */
#define USBSER_NCONFIGS            (1)      /* Number of configurations supported */
#define USBSER_INTERFACEID         (0)
#define USBSER_ALTINTERFACEID      (0)
#define USBSER_NINTERFACES         (1)      /* Number of interfaces in the configuration */
#define USBSER_NENDPOINTS          (3)      /* Number of endpoints in the interface  */

/* Endpoint configuration */

#define USBSER_EPINTIN_ADDR        (USB_DIR_IN|CONFIG_USBSER_EPINTIN)
#define USBSER_EPINTIN_ATTR        (USB_EP_ATTR_XFER_INT)
#define USBSER_EPINTIN_MXPACKET    (10)

#define USBSER_EPOUTBULK_ADDR      (CONFIG_USBSER_EPBULKOUT)
#define USBSER_EPOUTBULK_ATTR      (USB_EP_ATTR_XFER_BULK)

#define USBSER_EPINBULK_ADDR       (USB_DIR_IN|CONFIG_USBSER_EPBULKIN)
#define USBSER_EPINBULK_ATTR       (USB_EP_ATTR_XFER_BULK)

/* String language */

#define USBSER_STR_LANGUAGE        (0x0409) /* en-us */

/* Descriptor strings */

#define USBSER_MANUFACTURERSTRID   (1)
#define USBSER_PRODUCTSTRID        (2)
#define USBSER_SERIALSTRID         (3)
#define USBSER_CONFIGSTRID         (4)

/* Buffer big enough for any of our descriptors */

#define USBSER_MXDESCLEN           (64)

/* Vender specific control requests *******************************************/

#define PL2303_CONTROL_TYPE        (0x20)
#define PL2303_SETLINEREQUEST      (0x20) /* OUT, Recipient interface */
#define PL2303_GETLINEREQUEST      (0x21) /* IN, Recipient interface */
#define PL2303_SETCONTROLREQUEST   (0x22) /* OUT, Recipient interface */
#define PL2303_BREAKREQUEST        (0x23) /* OUT, Recipient interface */

/* Vendor read/write */

#define PL2303_RWREQUEST_TYPE      (0x40)
#define PL2303_RWREQUEST           (0x01) /* IN/OUT, Recipient device */

/* Misc Macros ****************************************************************/

/* min/max macros */

#ifndef min
#  define min(a,b) ((a)<(b)?(a):(b))
#endif

#ifndef max
#  define max(a,b) ((a)>(b)?(a):(b))
#endif

/* Trace values *************************************************************/

#define USBSER_CLASSAPI_SETUP       TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_SETUP)
#define USBSER_CLASSAPI_SHUTDOWN    TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_SHUTDOWN)
#define USBSER_CLASSAPI_ATTACH      TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_ATTACH)
#define USBSER_CLASSAPI_DETACH      TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_DETACH)
#define USBSER_CLASSAPI_IOCTL       TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_IOCTL)
#define USBSER_CLASSAPI_RECEIVE     TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_RECEIVE)
#define USBSER_CLASSAPI_RXINT       TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_RXINT)
#define USBSER_CLASSAPI_RXAVAILABLE TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_RXAVAILABLE)
#define USBSER_CLASSAPI_SEND        TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_SEND)
#define USBSER_CLASSAPI_TXINT       TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_TXINT)
#define USBSER_CLASSAPI_TXREADY     TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_TXREADY)
#define USBSER_CLASSAPI_TXEMPTY     TRACE_EVENT(TRACE_CLASSAPI_ID, USBSER_TRACECLASSAPI_TXEMPTY)

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

/* Container to support a list of requests */

struct usbser_req_s
{
  FAR struct usbser_req_s *flink;     /* Implements a singly linked list */
  FAR struct usbdev_req_s *req;       /* The contained request */
};

/* This structure describes the internal state of the driver */

struct usbser_dev_s
{
  FAR struct uart_dev_s    serdev;    /* Serial device structure */
  FAR struct usbdev_s     *usbdev;    /* usbdev driver pointer */

  ubyte config;                       /* Configuration number */
  ubyte nwrq;                         /* Number of queue write requests (in reqlist)*/
  ubyte nrdq;                         /* Number of queue read requests (in epbulkout) */
  ubyte open      : 1;                /* 1: Driver has been opened */
  ubyte rxenabled : 1;                /* 1: UART RX "interrupts" enabled */
  ubyte linest[7];                    /* Fake line status */
  sint16 rxhead;                      /* Working head; used when rx int disabled */

  FAR struct usbdev_ep_s  *epintin;   /* Address of Interrupt IN endpoint */
  FAR struct usbdev_ep_s  *epbulkin;  /* Address of Bulk IN endpoint */
  FAR struct usbdev_ep_s  *epbulkout; /* Address of Bulk OUT endpoint */
  FAR struct usbdev_req_s *ctrlreq;   /* Control request */
  struct sq_queue_s        reqlist;   /* List of write request containers */

  /* Pre-allocated write request containers.  The write requests will
   * be linked in a free list (reqlist), and used to send requests to
   * EPBULKIN; Read requests will be queued in the EBULKOUT.
   */

  struct usbser_req_s wrreqs[CONFIG_USBSER_NWRREQS];
  struct usbser_req_s rdreqs[CONFIG_USBSER_NWRREQS];

  /* Serial I/O buffers */

  char rxbuffer[CONFIG_USBSER_RXBUFSIZE];
  char txbuffer[CONFIG_USBSER_TXBUFSIZE];
};

/* The internal version of the class driver */

struct usbser_driver_s
{
  struct usbdevclass_driver_s drvr;
  FAR struct usbser_dev_s     *dev;
};

/* This is what is allocated */

struct usbser_alloc_s
{
  struct usbser_dev_s    dev;
  struct usbser_driver_s drvr;
};

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

/* Transfer helpers *********************************************************/

static uint16  usbclass_fillrequest(FAR struct usbser_dev_s *priv,
                 char *reqbuf, uint16 reqlen);
static int     usbclass_sndpacket(FAR struct usbser_dev_s *priv);
static inline int usbclass_recvpacket(FAR struct usbser_dev_s *priv,
                 char *reqbuf, uint16 reqlen);

/* Request helpers *********************************************************/

static struct usbdev_req_s *usbclass_allocreq(FAR struct usbdev_ep_s *ep,
                 uint16 len);
static void    usbclass_freereq(FAR struct usbdev_ep_s *ep,
                 FAR struct usbdev_req_s *req);

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

static int     usbclass_mkstrdesc(ubyte id, struct usb_strdesc_s *strdesc);
#ifdef CONFIG_USBDEV_DUALSPEED
static void    usbclass_mkepbulkdesc(const struct up_epdesc *indesc,
                 uint16 mxpacket, struct usb_epdesc_s *outdesc)
static sint16  usbclass_mkcfgdesc(ubyte *buf, ubyte speed);
#else
static sint16  usbclass_mkcfgdesc(ubyte *buf);
#endif
static void    usbclass_resetconfig(FAR struct usbser_dev_s *priv);
static int     usbclass_setconfig(FAR struct usbser_dev_s *priv,
                 ubyte config);

/* Completion event handlers ***********************************************/

static void    usbclass_ep0incomplete(FAR struct usbdev_ep_s *ep,
                 FAR struct usbdev_req_s *req);
static void    usbclass_rdcomplete(FAR struct usbdev_ep_s *ep,
                 FAR struct usbdev_req_s *req);
static void    usbclass_wrcomplete(FAR struct usbdev_ep_s *ep,
                 FAR struct usbdev_req_s *req);

/* USB class device ********************************************************/

static int     usbclass_bind(FAR struct usbdev_s *dev,
                 FAR struct usbdevclass_driver_s *driver);
static void    usbclass_unbind(FAR struct usbdev_s *dev);
static int     usbclass_setup(FAR struct usbdev_s *dev,
                 const struct usb_ctrlreq_s *ctrl);
static void    usbclass_disconnect(FAR struct usbdev_s *dev);

/* Serial port *************************************************************/

static int     usbser_setup(FAR struct uart_dev_s *dev);
static void    usbser_shutdown(FAR struct uart_dev_s *dev);
static int     usbser_attach(FAR struct uart_dev_s *dev);
static void    usbser_detach(FAR struct uart_dev_s *dev);
static void    usbser_rxint(FAR struct uart_dev_s *dev, boolean enable);
static void    usbser_txint(FAR struct uart_dev_s *dev, boolean enable);
static boolean usbser_txempty(FAR struct uart_dev_s *dev);

/****************************************************************************
 * Private Variables
 ****************************************************************************/

/* USB class device ********************************************************/

static const struct usbdevclass_driverops_s g_driverops =
{
  usbclass_bind,        /* bind */
  usbclass_unbind,      /* unbind */
  usbclass_setup,       /* setup */
  usbclass_disconnect,  /* disconnect */
  NULL,                 /* suspend */
  NULL,                 /* resume */
};

/* Serial port *************************************************************/

static const struct uart_ops_s g_uartops =
{
  usbser_setup,         /* setup */
  usbser_shutdown,      /* shutdown */
  usbser_attach,        /* attach */
  usbser_detach,        /* detach */
  NULL,                 /* ioctl */
  NULL,                 /* receive */
  usbser_rxint,         /* rxinit */
  NULL,                 /* rxavailable */
  NULL,                 /* send */
  usbser_txint,         /* txinit */
  NULL,                 /* txready */
  usbser_txempty        /* txempty */
};

/* USB descriptor templates these will be copied and modified **************/

static const struct usb_devdesc_s g_devdesc =
{
  USB_SIZEOF_DEVDESC,                           /* len */
  USB_DESC_TYPE_DEVICE,                         /* type */
  {LSBYTE(0x0200), MSBYTE(0x0200)},             /* usb */
  USB_CLASS_PER_INTERFACE,                      /* class */
  0,                                            /* subclass */
  0,                                            /* protocol */
  CONFIG_USBSER_EP0MAXPACKET,                   /* maxpacketsize */
  { LSBYTE(CONFIG_USBSER_VENDORID),             /* vendor */
    MSBYTE(CONFIG_USBSER_VENDORID) },
  { LSBYTE(CONFIG_USBSER_PRODUCTID),            /* product */
    MSBYTE(CONFIG_USBSER_PRODUCTID) },
  { LSBYTE(USBSER_VERSIONNO),                   /* device */
    MSBYTE(USBSER_VERSIONNO) },
  USBSER_MANUFACTURERSTRID,                     /* imfgr */
  USBSER_PRODUCTSTRID,                          /* iproduct */
  USBSER_SERIALSTRID,                           /* serno */
  USBSER_NCONFIGS                               /* nconfigs */
};

static const struct usb_cfgdesc_s g_cfgdesc =
{
  USB_SIZEOF_CFGDESC,                           /* len */
  USB_DESC_TYPE_CONFIG,                         /* type */
  {0, 0},                                       /* totallen -- to be provided */
  USBSER_NINTERFACES,                           /* ninterfaces */
  USBSER_CONFIGID,                              /* cfgvalue */
  USBSER_CONFIGSTRID,                           /* icfg */
  USB_CONFIG_ATTR_ONE|SELFPOWERED|REMOTEWAKEUP, /* attr */
  (CONFIG_USBDEV_MAXPOWER + 1) / 2              /* mxpower */
};

static const struct usb_ifdesc_s g_ifdesc =
{
  USB_SIZEOF_IFDESC,                            /* len */
  USB_DESC_TYPE_INTERFACE,                      /* type */
  0,                                            /* ifno */
  0,                                            /* alt */
  USBSER_NENDPOINTS,                            /* neps */
  USB_CLASS_VENDOR_SPEC,                        /* class */
  0,                                            /* subclass */
  0,                                            /* protocol */
  USBSER_CONFIGSTRID                            /* iif */
};

static const struct usb_epdesc_s g_epintindesc =
{
  USB_SIZEOF_EPDESC,                            /* len */
  USB_DESC_TYPE_ENDPOINT,                       /* type */
  USBSER_EPINTIN_ADDR,                          /* addr */
  USBSER_EPINTIN_ATTR,                          /* attr */
  { LSBYTE(USBSER_EPINTIN_MXPACKET),            /* maxpacket */
    MSBYTE(USBSER_EPINTIN_MXPACKET) },
  1                                             /* interval */
};

static const struct usb_epdesc_s g_epbulkoutdesc =
{
  USB_SIZEOF_EPDESC,                            /* len */
  USB_DESC_TYPE_ENDPOINT,                       /* type */
  USBSER_EPOUTBULK_ADDR,                        /* addr */
  USBSER_EPOUTBULK_ATTR,                        /* attr */
  { LSBYTE(64), MSBYTE(64) },                   /* maxpacket -- might change to 512*/
  0                                             /* interval */
};

static const struct usb_epdesc_s g_epbulkindesc =
{
  USB_SIZEOF_EPDESC,                            /* len */
  USB_DESC_TYPE_ENDPOINT,                       /* type */
  USBSER_EPINBULK_ADDR,                         /* addr */
  USBSER_EPINBULK_ATTR,                         /* attr */
  { LSBYTE(64), MSBYTE(64) },                   /* maxpacket -- might change to 512*/
  0                                             /* interval */
};

#ifdef CONFIG_USBDEV_DUALSPEED
static const struct usb_qualdesc_s g_qualdesc =
{
  USB_SIZEOF_QUALDESC,                          /* len */
  USB_DESC_TYPE_DEVICEQUALIFIER,                /* type */
  {LSBYTE(0x0200), MSBYTE(0x0200) },            /* USB */
  USB_CLASS_VENDOR_SPEC,                        /* class */
  0,                                            /* subclass */
  0,                                            /* protocol */
  CONFIG_USBSER_EP0MAXPACKET,                   /* mxpacketsize */
  USBSER_NCONFIGS,                              /* nconfigs */
  0,                                            /* reserved */
};
#endif

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

/************************************************************************************
 * Name: usbclass_fillrequest
 *
 * Description:
 *   If there is data to send it is copied to the given buffer.  Called either
 *   to initiate the first write operation, or from the completion interrupt handler
 *   service consecutive write operations.
 *
 * NOTE: The USB serial driver does not use the serial drivers uart_xmitchars()
 *   API.  That logic is essentially duplicated here because unlike UART hardware,
 *   we need to be able to handle writes not byte-by-byte, but packet-by-packet.
 *   Unfortunately, that decision also exposes some internals of the serial driver
 *   in the following.
 *
 ************************************************************************************/

static uint16 usbclass_fillrequest(FAR struct usbser_dev_s *priv, char *reqbuf, uint16 reqlen)
{
  FAR uart_dev_t *serdev = &priv->serdev;
  FAR struct uart_buffer_s *xmit = &serdev->xmit;
  irqstate_t flags;
  uint16 nbytes = 0;

  /* Disable interrupts */

  flags = irqsave();

  /* Transfer bytes while we have bytes available and there is room in the request */

  while (xmit->head != xmit->tail && nbytes < reqlen)
    {
      *reqbuf++ = xmit->buffer[xmit->tail];
      nbytes++;

      /* Increment the tail pointer */

      if (++(xmit->tail) >= xmit->size)
        {
          xmit->tail = 0;
        }

      /* Check if we have to wake up the serial driver */

      if (serdev->xmitwaiting)
        {
          serdev->xmitwaiting = FALSE;
          sem_post(&serdev->xmitsem);
        }
    }

  /* When all of the characters have been sent from the buffer
   * disable the "TX interrupt".
   */

  if (xmit->head == xmit->tail)
    {
      uart_disabletxint(serdev);
    }

  irqrestore(flags);
  return nbytes;
}

/************************************************************************************
 * Name: usbclass_sndpacket
 *
 * Description:
 *   This function obtains write requests, transfers the TX data into the request,
 *   and submits the requests to the USB controller.  This continues untils either
 *   (1) there are no further packets available, or (2) thre is not further data
 *   to send.
 *
 ************************************************************************************/

static int usbclass_sndpacket(FAR struct usbser_dev_s *priv)
{
  FAR struct usbdev_ep_s *ep;
  FAR struct usbdev_req_s *req;
  FAR struct usbser_req_s *reqcontainer;
  irqstate_t flags;
  int len;
  int ret = OK;

#ifdef CONFIG_DEBUG
  if (priv == NULL)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
      return -ENODEV;
    }
#endif

  flags = irqsave();

  /* Use our IN endpoint for the transfer */

  ep = priv->epbulkin;

  /* Loop until either (1) we run out or write requests, or (2) usbclass_fillrequest()
   * is unable to fill the request with data (i.e., untilthere is no more data
   * to be sent).
   */

  uvdbg("head=%d tail=%d nwrq=%d empty=%d\n",
        priv->serdev.xmit.head, priv->serdev.xmit.tail,
        priv->nwrq, sq_empty(&priv->reqlist));

  while (!sq_empty(&priv->reqlist))
    {
      /* Peek at the request in the container at the head of the list */

      reqcontainer = (struct usbser_req_s *)sq_peek(&priv->reqlist);
      req          = reqcontainer->req;

      /* Fill the request with serial TX data */

      len = usbclass_fillrequest(priv, req->buf, req->len);
      if (len > 0)
        {
          /* Remove the empty container from the request list */

          (void)sq_remfirst(&priv->reqlist);
          priv->nwrq--;

          /* Then submit the request to the endpoint */

          req->len     = len;
          req->private = reqcontainer;
          ret          = EP_SUBMIT(ep, req);
          if (ret != OK)
            {
              usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_SUBMITFAIL), (uint16)-ret);
              break;
            }
        }
      else
        {
          break;
        }
    }

  irqrestore(flags);
  return ret;
}

/************************************************************************************
 * Name: usbclass_recvpacket
 *
 * Description:
 *   A normal completion event was received by the read completion handler at the
 *   interrupt level (with interrupts disabled).  This function handles the USB packet
 *   and provides the received data to the uart RX buffer.
 *
 * Assumptions:
 *   Called from the USB interrupt handler with interrupts disabled.
 *
 ************************************************************************************/

static inline int usbclass_recvpacket(FAR struct usbser_dev_s *priv,
                                      char *reqbuf, uint16 reqlen)
{
  FAR uart_dev_t *serdev = &priv->serdev;
  FAR struct uart_buffer_s *recv = &serdev->recv;
  uint16 currhead;
  uint16 nexthead;

  /* Get the next head index. During the time that RX interrupts are disabled, the
   * the serial driver will be extracting data from the circular buffer and modifying
   * recv.tail.  During this time, we should avoid modifying recv.head; Instead we will
   * use a shadow copy of the index.  When interrupts are restored, the real recv.head
   * will be updated with this indes.
   */

  if (priv->rxenabled)
    {
      currhead = recv->head;
    }
  else
    {
      currhead = priv->rxhead;
    }

  /* Then copy data into the RX buffer until either: (1) all of the data has been
   * copied, or (2) the RX buffer is full.  NOTE:  If the RX buffer becomes full,
   * then we have overrun the serial driver and data will be lost.
   */

  while (nexthead != recv->tail && reqlen > 0)
    {
      /* Pre-increment the head index and check for wrap around.  We need to do this
       * so that we can determine if the circular buffer will overrun BEFORE we
       * overrun the buffer!
       */

      nexthead = currhead + 1;
      if (nexthead >= recv->size)
        {
          nexthead = 0;
        }

      /* Copy one byte to the head of the circular RX buffer */

      recv->buffer[currhead] = *reqbuf++;

      /* Update counts and indices */

      currhead = nexthead;
      reqlen--;

      /* Wake up the serial driver if it is waiting for incoming data. If we
       * are running in an interrupt handler, then the serial driver will
       * not run until the interrupt handler returns.  But we will exercise
       * care in the following just in case the serial driver does run.
       */

      if (priv->rxenabled && serdev->recvwaiting)
        {
          recv->head          = currhead;
          serdev->recvwaiting = FALSE;
          sem_post(&serdev->recvsem);
          currhead            = recv->head;
        }
    }

  /* Write back the head pointer using the shadow index if RX "interrupts"
   * are disabled.
   */

  if (priv->rxenabled)
    {
      recv->head = currhead;
    }
  else
    {
      priv->rxhead = currhead;
    }

  /* Return an error if the entire packet could not be transferred */

  if (reqlen > 0)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_RXOVERRUN), 0);
      return -ENOSPC;
    }
  return OK;
}

/****************************************************************************
 * Name: usbclass_allocreq
 *
 * Description:
 *   Allocate a request instance along with its buffer
 *
 ****************************************************************************/

static struct usbdev_req_s *usbclass_allocreq(FAR struct usbdev_ep_s *ep, uint16 len)
{
  FAR struct usbdev_req_s *req;

  req = EP_ALLOCREQ(ep);
  if (req != NULL)
    {
      req->len = len;
      req->buf = EP_ALLOCBUFFER(ep, len);
      if (!req->buf)
        {
          EP_FREEREQ(ep, req);
          req = NULL;
        }
    }
  return req;
}

/****************************************************************************
 * Name: usbclass_freereq
 *
 * Description:
 *   Free a request instance along with its buffer
 *
 ****************************************************************************/

static void usbclass_freereq(FAR struct usbdev_ep_s *ep, struct usbdev_req_s *req)
{
  if (ep != NULL && req != NULL)
    {
      if (req->buf != NULL)
        {
          EP_FREEBUFFER(ep, req->buf);
        }
      EP_FREEREQ(ep, req);
    }
}

/****************************************************************************
 * Name: usbclass_mkstrdesc
 *
 * Description:
 *   Construct a string descriptor
 *
 ****************************************************************************/

static int usbclass_mkstrdesc(ubyte id, struct usb_strdesc_s *strdesc)
{
  const char *str;
  int len;
  int ndata;
  int i;

  switch (id)
    {
    case 0:
      {
        /* Descriptor 0 is the language id */

        strdesc->len     = 4;
        strdesc->type    = USB_DESC_TYPE_STRING;
        strdesc->data[0] = LSBYTE(USBSER_STR_LANGUAGE);
        strdesc->data[1] = MSBYTE(USBSER_STR_LANGUAGE);
        return 4;
      }

    case USBSER_MANUFACTURERSTRID:
      str = CONFIG_USBSER_VENDORSTR;
      break;

    case USBSER_PRODUCTSTRID:
      str = CONFIG_USBSER_PRODUCTSTR;
      break;

    case USBSER_SERIALSTRID:
      str = CONFIG_USBSER_SERIALSTR;
      break;

    case USBSER_CONFIGSTRID:
      str = CONFIG_USBSER_CONFIGSTR;
      break;

    default:
      return -EINVAL;
    }

   /* The string is utf16-le.  The poor man's utf-8 to utf16-le
    * conversion below will only handle 7-bit en-us ascii
    */

   len = strlen(str);
   for (i = 0, ndata = 0; i < len; i++, ndata += 2)
     {
       strdesc->data[ndata]   = str[i];
       strdesc->data[ndata+1] = 0;
     }

   strdesc->len  = ndata+2;
   strdesc->type = USB_DESC_TYPE_STRING;
   return strdesc->len;
}

/****************************************************************************
 * Name: usbclass_mkepbulkdesc
 *
 * Description:
 *   Construct the endpoint descriptor
 *
 ****************************************************************************/

#ifdef CONFIG_USBDEV_DUALSPEED
static inline void usbclass_mkepbulkdesc(const FAR struct up_epdesc *indesc,
                                         uint16 mxpacket,
                                         FAR struct usb_epdesc_s *outdesc)
{
  /* Copy the canned descriptor */

  memcpy(outdesc, indesc, USB_SIZEOF_EPDESC);

  /* Then add the correct max packet size */

  outdesc->mxpacketsize[0] = LSBYTE(mxpacket);
  outdesc->mxpacketsize[1] = MSBYTE(mxpacket);
}
#endif

/****************************************************************************
 * Name: usbclass_mkcfgdesc
 *
 * Description:
 *   Construct the configuration descriptor
 *
 ****************************************************************************/

#ifdef CONFIG_USBDEV_DUALSPEED
static sint16  usbclass_mkcfgdesc(ubyte *buf, ubyte speed)
#else
static sint16  usbclass_mkcfgdesc(ubyte *buf)
#endif
{
  FAR struct usb_cfgdesc_s *cfgdesc = (struct usb_cfgdesc_s*)buf;
#ifdef CONFIG_USBDEV_DUALSPEED
  boolean highspeed = (speed == USB_SPEED_HIGH);
  uint16 bulkmxpacket;
#endif
  uint16 totallen;

  /* This is the total length of the configuration (not necessarily the
   * size that we will be sending now.
   */

  totallen = USB_SIZEOF_CFGDESC + USB_SIZEOF_IFDESC + USBSER_NENDPOINTS * USB_SIZEOF_EPDESC;

  /* Configuration descriptor -- Copy the canned descriptor and fill in the
   * type (we'll also need to update the size below
   */

  memcpy(cfgdesc, &g_cfgdesc, USB_SIZEOF_CFGDESC);
  buf += USB_SIZEOF_CFGDESC;

  /*  Copy the canned interface descriptor */

  memcpy(buf, &g_ifdesc, USB_SIZEOF_IFDESC);
  buf += USB_SIZEOF_IFDESC;

  /* Make the two endpoint configurations.  First, check for switches
   * between high and full speed
   */

#ifdef CONFIG_USBDEV_DUALSPEED
  if (type == USB_DESC_TYPE_OTHERSPEEDCONFIG)
    {
      hispeed = !hispeed;
    }
#endif

  memcpy(buf, &g_epintindesc, USB_SIZEOF_EPDESC);
  buf += USB_SIZEOF_EPDESC;

#ifdef CONFIG_USBDEV_DUALSPEED
  if (hispeed)
    {
      bulkmxpacket = 512;
    }
  else
    {
      bulkmxpacket = 64;
    }

  usbclass_mkepbulkdesc(&g_epbulkoutdesc, bulkmxpacket, (struct usb_epdesc_s*)buf);
  buf += USB_SIZEOF_EPDESC;
  usbclass_mkepbulkdesc(&g_epbulkindesc, bulkmxpacket, (struct usb_epdesc_s*)buf);
#else
  memcpy(buf, &g_epbulkoutdesc, USB_SIZEOF_EPDESC);
  buf += USB_SIZEOF_EPDESC;
  memcpy(buf, &g_epbulkindesc, USB_SIZEOF_EPDESC);
#endif

  /* Finally, fill in the total size of the configuration descriptor */

  cfgdesc->totallen[0] = LSBYTE(totallen);
  cfgdesc->totallen[1] = MSBYTE(totallen);
  return totallen;
}

/****************************************************************************
 * Name: usbclass_resetconfig
 *
 * Description:
 *   Mark the device as not configured and disable all endpoints.
 *
 ****************************************************************************/

static void usbclass_resetconfig(FAR struct usbser_dev_s *priv)
{
  /* Are we configured? */

  if (priv->config != USBSER_CONFIGIDNONE)
    {
      /* Yes.. but not anymore */

      priv->config = USBSER_CONFIGIDNONE;

      /* Disable endpoints.  This should force completion of all pending
       * transfers.
       */

      EP_DISABLE(priv->epintin);
      EP_DISABLE(priv->epbulkin);
      EP_DISABLE(priv->epbulkout);
    }
}

/****************************************************************************
 * Name: usbclass_setconfig
 *
 * Description:
 *   Set the device configuration by allocating and configuring endpoints and
 *   by allocating and queue read and write requests.
 *
 ****************************************************************************/

static int usbclass_setconfig(FAR struct usbser_dev_s *priv, ubyte config)
{
  FAR struct usbdev_req_s *req;
#ifdef CONFIG_USBDEV_DUALSPEED
  struct usb_epdesc_s epdesc;
  uint16 bulkmxpacket;
#endif
  int i;
  int ret = 0;

#if CONFIG_DEBUG
  if (priv == NULL)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
      return -EIO;
    }
#endif

  if (config == priv->config)
    {
      /* Already configured -- Do nothing */

      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_ALREADYCONFIGURED), 0);
      return 0;
    }

  /* Discard the previous configuration data */

  usbclass_resetconfig(priv);

  /* Was this a request to simply discard the current configuration? */

  if (config == USBSER_CONFIGIDNONE)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_CONFIGNONE), 0);
      return 0;
    }

  /* We only accept one configuration */

  if (config != USBSER_CONFIGID)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_CONFIGIDBAD), 0);
      return -EINVAL;
    }

  /* Configure the IN interrupt endpoint */

  ret = EP_CONFIGURE(priv->epintin, &g_epintindesc, FALSE);
  if (ret < 0)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EPINTINCONFIGFAIL), 0);
      goto errout;
    }
  priv->epintin->private = priv;

  /* Configure the IN bulk endpoint */

#ifdef CONFIG_USBDEV_DUALSPEED
  if (dev->speed == USB_SPEED_HIGH)
    {
      bulkmxpacket = 512;
    }
  else
    {
      bulkmxpacket = 64;
    }

  usbclass_mkepbulkdesc(&g_epbulkindesc, bulkmxpacket, &epdesc);
  ret = EP_CONFIGURE(priv->epbulkin, &epdesc, FALSE);
#else
  ret = EP_CONFIGURE(priv->epbulkin, &g_epbulkindesc, FALSE);
#endif
  if (ret < 0)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EPBULKINCONFIGFAIL), 0);
      goto errout;
    }

  priv->epbulkin->private = priv;

  /* Configure the OUT bulk endpoint */

#ifdef CONFIG_USBDEV_DUALSPEED
  usbclass_mkepbulkdesc(&g_epbulkoutdesc, bulkmxpacket, &epdesc);
  ret = EP_CONFIGURE(priv->epbulkout, &epdesc, TRUE);
#else
  ret = EP_CONFIGURE(priv->epbulkout, &g_epbulkoutdesc, TRUE);
#endif
  if (ret < 0)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EPBULKOUTCONFIGFAIL), 0);
      goto errout;
    }

  priv->epbulkout->private = priv;

  /* Queue read requests in the bulk OUT endpoint */

  DEBUGASSERT(priv->nrdq == 0);
  for (i = 0; i < CONFIG_USBSER_NRDREQS; i++)
    {
      req           = priv->rdreqs[i].req;
      req->callback = usbclass_rdcomplete;
      ret           = EP_SUBMIT(priv->epbulkout, req);
      if (ret != OK)
        {
          usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_RDSUBMIT), (uint16)-ret);
          goto errout;
        }
      priv->nrdq++;
    }

  priv->config = config;
  return OK;

errout:
  usbclass_resetconfig(priv);
  return ret;
}

/****************************************************************************
 * Name: usbclass_ep0incomplete
 *
 * Description:
 *   Handle completion of EP0 control operations
 *
 ****************************************************************************/

static void usbclass_ep0incomplete(FAR struct usbdev_ep_s *ep, struct usbdev_req_s *req)
{
  if (req->result || req->xfrd != req->len)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_REQRESULT), (uint16)-req->result);
    }
}

/****************************************************************************
 * Name: usbclass_rdcomplete
 *
 * Description:
 *   Handle completion of read request on the bulk OUT endpoint.  This
 *   is handled like the receipt of serial data on the "UART"
 *
 ****************************************************************************/

static void usbclass_rdcomplete(FAR struct usbdev_ep_s *ep, struct usbdev_req_s *req)
{
  FAR struct usbser_dev_s *priv;
  irqstate_t flags;
  int ret;

  /* Sanity check */

#ifdef CONFIG_DEBUG
  if (!ep || !ep->private || !req)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
      return;
     }
#endif

  /* Extract references to private data */

  priv = (FAR struct usbser_dev_s*)ep->private;

  /* Process the received data unless this is some unusual condition */

  flags = irqsave();
  switch (req->result)
    {
    case 0: /* Normal completion */
      usbtrace(TRACE_CLASSRDCOMPLETE, priv->nrdq);
      usbclass_recvpacket(priv, req->buf, req->xfrd);
      break;

    case -ESHUTDOWN: /* Disconnection */
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_RDSHUTDOWN), 0);
      priv->nrdq--;
      irqrestore(flags);
      return;

    default: /* Some other error occurred */
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_RDUNEXPECTED), (uint16)-req->result);
      break;
    };

  /* Requeue the read request */

#ifdef CONFIG_USBSER_BULKREQLEN
  req->len = max(CONFIG_USBSER_BULKREQLEN, ep->maxpacket);
#else
  req->len = ep->maxpacket;
#endif

  ret      = EP_SUBMIT(ep, req);
  if (ret != OK)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_RDSUBMIT), (uint16)-req->result);
    }
  irqrestore(flags);
}

/****************************************************************************
 * Name: usbclass_wrcomplete
 *
 * Description:
 *   Handle completion of write request.  This function probably executes
 *   in the context of an interrupt handler.
 *
 ****************************************************************************/

static void usbclass_wrcomplete(FAR struct usbdev_ep_s *ep, struct usbdev_req_s *req)
{
  FAR struct usbser_dev_s *priv;
  FAR struct usbser_req_s *reqcontainer;
  irqstate_t flags;

  /* Sanity check */

#ifdef CONFIG_DEBUG
  if (!ep || !ep->private || !req || !req->private)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
      return;
     }
#endif

  /* Extract references to our private data */

  priv         = (FAR struct usbser_dev_s *)ep->private;
  reqcontainer = (FAR struct usbser_req_s *)req->private;

  /* Return the write request to the free list */

  flags = irqsave();
  sq_addlast((sq_entry_t*)reqcontainer, &priv->reqlist);
  priv->nwrq++;
  irqrestore(flags);

  /* Send the next packet unless this was some unusual termination
   * condition
   */

  switch (req->result)
    {
    case OK: /* Normal completion */
      usbtrace(TRACE_CLASSWRCOMPLETE, priv->nwrq);
      usbclass_sndpacket(priv);
      break;

    case -ESHUTDOWN: /* Disconnection */
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_WRSHUTDOWN), priv->nwrq);
      break;

    default: /* Some other error occurred */
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_WRUNEXPECTED), (uint16)-req->result);
      break;
    }
}

/****************************************************************************
 * USB Class Driver Methods
 ****************************************************************************/

/****************************************************************************
 * Name: usbclass_bind
 *
 * Description:
 *   Invoked when the driver is bound to a USB device driver
 *
 ****************************************************************************/

static int usbclass_bind(FAR struct usbdev_s *dev, FAR struct usbdevclass_driver_s *driver)
{
  FAR struct usbser_dev_s *priv = ((struct usbser_driver_s*)driver)->dev;
  FAR struct usbser_req_s *reqcontainer;
  irqstate_t flags;
  uint16 reqlen;
  int ret;
  int i;

  usbtrace(TRACE_CLASSBIND, 0);

  /* Bind the structures */

  priv->usbdev      = dev;
  dev->ep0->private = priv;

  /* Preallocate control request */

  priv->ctrlreq = usbclass_allocreq(dev->ep0, USBSER_MXDESCLEN);
  if (priv->ctrlreq == NULL)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_ALLOCCTRLREQ), 0);
      ret = -ENOMEM;
      goto errout;
    }
  priv->ctrlreq->callback = usbclass_ep0incomplete;

  /* Pre-allocate all endpoints... the endpoints will not be functional
   * until the SET CONFIGURATION request is processed in usbclass_setconfig.
   * This is done here because there may be calls to malloc and the SET
   * CONFIGURATION processing probably occurrs within interrupt handling
   * logic where malloc calls will fail.
   */

  /* Pre-allocate the IN interrupt endpoint */

  priv->epintin = DEV_ALLOCEP(dev, USBSER_EPINTIN_ADDR, TRUE, USB_EP_ATTR_XFER_INT);
  if (!priv->epintin)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EPINTINALLOCFAIL), 0);
      ret = -ENODEV;
      goto errout;
    }
  priv->epintin->private = priv;

  /* Pre-allocate the IN bulk endpoint */

  priv->epbulkin = DEV_ALLOCEP(dev, USBSER_EPINBULK_ADDR, TRUE, USB_EP_ATTR_XFER_BULK);
  if (!priv->epbulkin)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EPBULKINALLOCFAIL), 0);
      ret = -ENODEV;
      goto errout;
    }
  priv->epbulkin->private = priv;

  /* Pre-allocate the OUT bulk endpoint */

  priv->epbulkout = DEV_ALLOCEP(dev, USBSER_EPOUTBULK_ADDR, FALSE, USB_EP_ATTR_XFER_BULK);
  if (!priv->epbulkout)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EPBULKOUTALLOCFAIL), 0);
      ret = -ENODEV;
      goto errout;
    }
  priv->epbulkout->private = priv;

  /* Pre-allocate read requests */

#ifdef CONFIG_USBSER_BULKREQLEN
  reqlen = max(CONFIG_USBSER_BULKREQLEN, priv->epbulkout->maxpacket);
#else
  reqlen =priv->epbulkout->maxpacket;
#endif

  for (i = 0; i < CONFIG_USBSER_NRDREQS; i++)
    {
      reqcontainer      = &priv->rdreqs[i];
      reqcontainer->req = usbclass_allocreq(priv->epbulkout, reqlen);
      if (reqcontainer->req == NULL)
        {
          usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_RDALLOCREQ), (uint16)-ret);
          ret = -ENOMEM;
          goto errout;
        }
      reqcontainer->req->private  = reqcontainer;
      reqcontainer->req->callback = usbclass_rdcomplete;
    }

  /* Pre-allocate write request containers and put in a free list */

#ifdef CONFIG_USBSER_BULKREQLEN
  reqlen = max(CONFIG_USBSER_BULKREQLEN, priv->epbulkin->maxpacket);
#else
  reqlen = priv->epbulkin->maxpacket;
#endif

  for (i = 0; i < CONFIG_USBSER_NWRREQS; i++)
    {
      reqcontainer      = &priv->wrreqs[i];
      reqcontainer->req = usbclass_allocreq(priv->epbulkin, reqlen);
      if (reqcontainer->req == NULL)
        {
          usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_WRALLOCREQ), (uint16)-ret);
          ret = -ENOMEM;
          goto errout;
        }
      reqcontainer->req->private  = reqcontainer;
      reqcontainer->req->callback = usbclass_wrcomplete;

      flags = irqsave();
      sq_addlast((sq_entry_t*)reqcontainer, &priv->reqlist);
      priv->nwrq++;     /* Count of write requests available */
      irqrestore(flags);
    }

  return OK;

errout:
  usbclass_unbind(dev);
  return ret;

}

/****************************************************************************
 * Name: usbclass_unbind
 *
 * Description:
 *    Invoked when the driver is unbound from a USB device driver
 *
 ****************************************************************************/

static void usbclass_unbind(FAR struct usbdev_s *dev)
{
  FAR struct usbser_dev_s *priv;
  FAR struct usbser_req_s *reqcontainer;
  irqstate_t flags;
  int i;

  usbtrace(TRACE_CLASSUNBIND, 0);

#ifdef CONFIG_DEBUG
  if (!dev || !dev->ep0)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
      return;
     }
#endif

  /* Extract reference to private data */

  priv = (FAR struct usbser_dev_s *)dev->ep0->private;

#ifdef CONFIG_DEBUG
  if (!priv)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EP0NOTBOUND), 0);
      return;
    }
#endif

  /* Make sure that we are not already unbound */

  if (priv != NULL)
    {
     /* Make sure that the endpoints have been unconfigured.  If
      * we were terminated gracefully, then the configuration should
      * already have been reset.  If not, then calling usbclass_resetconfig
      * should cause the endpoints to immediately terminate all
      * transfers and return the requests to us (with result == -ESHUTDOWN)
      */

       usbclass_resetconfig(priv);
       up_mdelay(50);

      if (priv->ctrlreq != NULL)
        {
          usbclass_freereq(dev->ep0, priv->ctrlreq);
        }
      dev->ep0->private = priv;

      /* Free int interrupt IN endpoint */

      if (priv->epintin)
        {
          DEV_FREEEP(dev, priv->epintin);
          priv->epintin = NULL;
        }

      if (priv->epbulkin)
        {
          DEV_FREEEP(dev, priv->epbulkin);
          priv->epbulkin = NULL;
        }

      /* Free the pre-allocated control request */

      if (priv->ctrlreq != NULL)
        {
          usbclass_freereq(dev->ep0, priv->ctrlreq);
        }

      /* Free pre-allocated read requests (which should all have
       * been returned to the free list at this time -- we don't check)
       */

      DEBUGASSERT(priv->nrdq == 0);
      for (i = 0; i < CONFIG_USBSER_NRDREQS; i++)
        {
          reqcontainer = &priv->rdreqs[i];
          if (reqcontainer->req)
            {
              usbclass_freereq(priv->epbulkout, reqcontainer->req);
              reqcontainer->req = NULL;
            }
        }

      /* Free the bulk OUT endpoint */

      if (priv->epbulkout)
        {
          DEV_FREEEP(dev, priv->epbulkout);
          priv->epbulkout = NULL;
        }

      /* Free write requests that are not in use (which should be all
       * of them
       */

      flags = irqsave();
      DEBUGASSERT(priv->nwrq == CONFIG_USBSER_NWRREQS);
      while (!sq_empty(&priv->reqlist))
        {
          reqcontainer = (struct usbser_req_s *)sq_remfirst(&priv->reqlist);
          if (reqcontainer->req != NULL)
            {
              usbclass_freereq(priv->epbulkin, reqcontainer->req);
              priv->nwrq--;     /* Number of write requests queued */
            }
        }
      DEBUGASSERT(priv->nwrq == 0);
      irqrestore(flags);
    }

  /* Clear out all data in the circular buffer */

  priv->serdev.xmit.head = 0;
  priv->serdev.xmit.tail = 0;
}

/****************************************************************************
 * Name: usbclass_setup
 *
 * Description:
 *   Invoked for ep0 control requests.  This function probably executes
 *   in the context of an interrupt handler.
 *
 ****************************************************************************/

static int usbclass_setup(FAR struct usbdev_s *dev, const struct usb_ctrlreq_s *ctrl)
{
  FAR struct usbser_dev_s *priv;
  FAR struct usbdev_req_s *ctrlreq;
  uint16 value;
  uint16 index;
  uint16 len;
  int ret = -EOPNOTSUPP;

#ifdef CONFIG_DEBUG
  if (!dev || !dev->ep0 || !ctrl)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
      return -EIO;
     }
#endif

  /* Extract reference to private data */

  usbtrace(TRACE_CLASSSETUP, ctrl->req);
  priv = (FAR struct usbser_dev_s *)dev->ep0->private;

#ifdef CONFIG_DEBUG
  if (!priv || !priv->ctrlreq)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EP0NOTBOUND), 0);
      return -ENODEV;
    }
#endif
  ctrlreq = priv->ctrlreq;

  /* Extract the little-endian 16-bit values to host order */

  value = GETUINT16(ctrl->value);
  index = GETUINT16(ctrl->index);
  len   = GETUINT16(ctrl->len);

  uvdbg("type=%02x req=%02x value=%04x index=%04x len=%04x\n",
        ctrl->type, ctrl->req, value, index, len);

  switch (ctrl->type & USB_REQ_TYPE_MASK)
    {
    case USB_REQ_TYPE_STANDARD:
      {
        switch (ctrl->req)
          {
          case USB_REQ_GETDESCRIPTOR:
            {
              /* The value field specifies the descriptor type in the MS byte and the
               * descriptor index in the LS byte (order is little endian)
               */

              switch (ctrl->value[1])
                {
                case USB_DESC_TYPE_DEVICE:
                  {
                    ret = USB_SIZEOF_DEVDESC;
                    memcpy(ctrlreq->buf, &g_devdesc, ret);
                  }
                  break;

#ifdef CONFIG_USBDEV_DUALSPEED
                case USB_DESC_TYPE_DEVICEQUALIFIER:
                  {
                    ret = USB_SIZEOF_QUALDESC;
                    memcpy(ctrlreq->buf, &g_qualdesc, ret);
                  }
                  break;

                case USB_DESC_TYPE_OTHERSPEEDCONFIG:
#endif /* CONFIG_USBDEV_DUALSPEED */

                case USB_DESC_TYPE_CONFIG:
                  {
#ifdef CONFIG_USBDEV_DUALSPEED
                    ret = usbclass_mkcfgdesc(ctrlreq->buf, dev->speed, len);
#else
                    ret = usbclass_mkcfgdesc(ctrlreq->buf);
#endif
                  }
                  break;

                case USB_DESC_TYPE_STRING:
                  {
                    /* index == language code. */

                    ret = usbclass_mkstrdesc(ctrl->value[0], (struct usb_strdesc_s *)ctrlreq->buf);
                  }
                  break;

                default:
                  {
                    usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_GETUNKNOWNDESC), value);
                  }
                  break;
                }
            }
            break;

          case USB_REQ_SETCONFIGURATION:
            {
              if (ctrl->type == 0)
                {
                  ret = usbclass_setconfig(priv, value);
                }
            }
            break;

          case USB_REQ_GETCONFIGURATION:
            {
              if (ctrl->type == USB_DIR_IN)
                {
                  *(ubyte*)ctrlreq->buf = priv->config;
                  ret = 1;
                }
            }
            break;

          case USB_REQ_SETINTERFACE:
            {
              if (ctrl->type == USB_REQ_RECIPIENT_INTERFACE)
                {
                  if (priv->config == USBSER_CONFIGID &&
                      index == USBSER_INTERFACEID &&
                      value == USBSER_ALTINTERFACEID)
                    {
                      usbclass_resetconfig(priv);
                      usbclass_setconfig(priv, priv->config);
                      ret = 0;
                    }
                }
            }
            break;

          case USB_REQ_GETINTERFACE:
            {
              if (ctrl->type == (USB_DIR_IN|USB_REQ_RECIPIENT_INTERFACE) &&
                  priv->config == USBSER_CONFIGIDNONE)
                {
                  if (index != USBSER_INTERFACEID)
                    {
                      ret = -EDOM;
                    }
                  else
                     {
                      *(ubyte*) ctrlreq->buf = USBSER_ALTINTERFACEID;
                      ret = 1;
                    }
                }
             }
             break;

          default:
            usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_UNSUPPORTEDSTDREQ), ctrl->req);
            break;
          }
      }
      break;

    case PL2303_CONTROL_TYPE:
      {
        if ((ctrl->type & USB_REQ_RECIPIENT_MASK) == USB_REQ_RECIPIENT_INTERFACE)
          {
            switch (ctrl->req)
              {
              case PL2303_SETLINEREQUEST:
                {
                   memcpy(priv->linest, ctrlreq->buf, min(len, 7));
                   ret = 0;
                }
                break;


              case PL2303_GETLINEREQUEST:
                {
                   memcpy(ctrlreq->buf, priv->linest, 7);
                   ret = 7;
                }
                break;

              case PL2303_SETCONTROLREQUEST:
              case PL2303_BREAKREQUEST:
                {
                  ret = 0;
                }
                break;

              default:
                usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_UNSUPPORTEDCTRLREQ), ctrl->type);
                break;
              }
          }
      }
      break;

    case PL2303_RWREQUEST_TYPE:
      {
        if ((ctrl->type & USB_REQ_RECIPIENT_MASK) == USB_REQ_RECIPIENT_DEVICE)
          {
            if (ctrl->req == PL2303_RWREQUEST)
              {
                if ((ctrl->type & USB_DIR_IN) != 0)
                  {
                    *(uint32*)ctrlreq->buf = 0xdeadbeef;
                    ret = 4;
                  }
                else
                  {
                     ret = 0;
                  }
              }
            else
              {
                usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_UNSUPPORTEDRWREQ), ctrl->type);
              }
          }
      }
      break;

    default:
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_UNSUPPORTEDTYPE), ctrl->type);
      break;
    }

  /* Respond with data transfer before status phase? */

  if (ret >= 0)
    {
      ctrlreq->len = min(len, ret);
      ret          = EP_SUBMIT(dev->ep0, ctrlreq);
      if (ret < 0)
        {
          usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EPRESPQ), (uint16)-ret);
          ctrlreq->result = OK;
          usbclass_ep0incomplete(dev->ep0, ctrlreq);
        }
    }

  return ret;
}

/****************************************************************************
 * Name: usbclass_disconnect
 *
 * Description:
 *   Invoked after all transfers have been stopped, when the host is
 *   disconnected.  This function is probably called from the context of an
 *   interrupt handler.
 *
 ****************************************************************************/

static void usbclass_disconnect(FAR struct usbdev_s *dev)
{
  FAR struct usbser_dev_s *priv;
  irqstate_t flags;

  usbtrace(TRACE_CLASSDISCONNECT, 0);

#ifdef CONFIG_DEBUG
  if (!dev || !dev->ep0)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
      return;
     }
#endif

  /* Extract reference to private data */

  priv = (FAR struct usbser_dev_s *)dev->ep0->private;

#ifdef CONFIG_DEBUG
  if (!priv)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_EP0NOTBOUND), 0);
      return;
    }
#endif

  /* Reset the configuration */

  flags = irqsave();
  usbclass_resetconfig(priv);

  /* Clear out all data in the circular buffer */

  priv->serdev.xmit.head = 0;
  priv->serdev.xmit.tail = 0;
  irqrestore(flags);
}

/****************************************************************************
 * Serial Device Methods
 ****************************************************************************/

/****************************************************************************
 * Name: usbser_setup
 *
 * Description:
 *   This method is called the first time that the serial port is opened.
 *
 ****************************************************************************/

static int usbser_setup(FAR struct uart_dev_s *dev)
{
  FAR struct usbser_dev_s *priv;

  usbtrace(USBSER_CLASSAPI_SETUP, 0);

  /* Sanity check */

#if CONFIG_DEBUG
  if (!dev || !dev->priv)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
      return -EIO;
    }
#endif

  /* Extract reference to private data */

  priv = (FAR struct usbser_dev_s*)dev->priv;

  /* Check if we have been configured */

  if (priv->config == USBSER_CONFIGIDNONE)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_SETUPNOTCONNECTED), 0);
      return -ENOTCONN;
    }

  /* Mark the device as opened */

  priv->open = 1;
  return OK;
}

/****************************************************************************
 * Name: usbser_shutdown
 *
 * Description:
 *   This method is called when the serial port is closed.  This operation
 *   is very simple for the USB serial backend because the serial driver
 *   has already assured that the TX data has full drained -- it calls
 *   usbser_txempty() until that function returns TRUE before calling this
 *   function.
 *
 ****************************************************************************/

static void usbser_shutdown(FAR struct uart_dev_s *dev)
{
  FAR struct usbser_dev_s *priv;
  irqstate_t flags;

  usbtrace(USBSER_CLASSAPI_SHUTDOWN, 0);

  /* Sanity check */

#if CONFIG_DEBUG
  if (!dev || !dev->priv)
    {
       usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
       return;
    }
#endif

  /* Extract reference to private data */

  priv  = (FAR struct usbser_dev_s*)dev->priv;
  flags = irqsave();

#if CONFIG_DEBUG
  if (!priv->open)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_ALREADYCLOSED), 0);
      irqrestore(flags);
      return;
    }
#endif

  /* Make sure that we are disconnected from the host */

  usbclass_resetconfig(priv);
  priv->open = 0;
  irqrestore(flags);
}

/****************************************************************************
 * Name: usbser_attach
 *
 * Description:
 *   Does not apply to the USB serial class device
 *
 ****************************************************************************/

static int usbser_attach(FAR struct uart_dev_s *dev)
{
  usbtrace(USBSER_CLASSAPI_ATTACH, 0);
  return OK;
}

/****************************************************************************
 * Name: usbser_detach
 *
 * Description:
*   Does not apply to the USB serial class device
  *
 ****************************************************************************/

static void usbser_detach(FAR struct uart_dev_s *dev)
{
  usbtrace(USBSER_CLASSAPI_DETACH, 0);
}

/****************************************************************************
 * Name: usbser_rxint
 *
 * Description:
 *   Called by the serial driver to enable or disable RX interrupts.  We, of
 *   course, have no RX interrupts but must behave consistently.  This method
 *   is called under the conditions:
 *
 *   1. With enable==TRUE when the port is opened (just after usbser_setup
 *      and usbser_attach are called called)
 *   2. With enable==FALSE while transferring data from the RX buffer
 *   2. With enable==TRUE while waiting for more incoming data
 *   3. With enable==FALSE when the port is closed (just before usbser_detach
 *      and usbser_shutdown are called).
 *
 ****************************************************************************/

static void usbser_rxint(FAR struct uart_dev_s *dev, boolean enable)
{
  FAR struct usbser_dev_s *priv;
  FAR uart_dev_t *serdev;
  irqstate_t flags;

  usbtrace(USBSER_CLASSAPI_RXINT, (uint16)enable);

  /* Sanity check */

#if CONFIG_DEBUG
  if (!dev || !dev->priv)
    {
       usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
       return;
    }
#endif

  /* Extract reference to private data */

  priv   = (FAR struct usbser_dev_s*)dev->priv;
  serdev = &priv->serdev;

  /* We need exclusive access to the RX buffer and private structure
   * in the following.
   */

  flags = irqsave();
  if (enable)
    {
       /* RX "interrupts" are enabled.  Is this a transition from disabled
        * to enabled state?
        */

       if (!priv->rxenabled)
         {
           /* Yes.  During the time that RX interrupts are disabled, the
            * the serial driver will be extracting data from the circular
            * buffer and modifying recv.tail.  During this time, we
            * should avoid modifying recv.head; When interrupts are restored,
            * we can update the head pointer for all of the data that we
            * put into cicular buffer while "interrupts" were disabled.
            */

          if (priv->rxhead != serdev->recv.head)
            {
              serdev->recv.head = priv->rxhead;

              /* Is the serial driver waiting for more data? */

              if (serdev->recvwaiting)
                {
                  /* Yes... signal the availability of new data */

                  sem_post(&serdev->recvsem);
                  serdev->recvwaiting = FALSE;
                }
            }

          /* RX "interrupts are no longer disabled */

          priv->rxenabled = 1;
        }
    }

  /* RX "interrupts" are disabled.  Is this a transition from enabled
   * to disabled state?
   */

  else if (priv->rxenabled)
    {
      /* Yes.  During the time that RX interrupts are disabled, the
       * the serial driver will be extracting data from the circular
       * buffer and modifying recv.tail.  During this time, we
       * should avoid modifying recv.head; When interrupts are disabled,
       * we use a shadow index and continue adding data to the circular
       * buffer.
       */

      priv->rxhead    = serdev->recv.head;
      priv->rxenabled = 0;
    }
  irqrestore(flags);
}

/****************************************************************************
 * Name: usbser_txint
 *
 * Description:
 *   Called by the serial driver to enable or disable TX interrupts.  We, of
 *   course, have no TX interrupts but must behave consistently.  Initially,
 *   TX interrupts are disabled.  This method is called under the conditions:
 *
 *   1. With enable==FALSE while transferring data into the TX buffer
 *   2. With enable==TRUE when data may be taken from the buffer.
 *   3. With enable==FALSE when the TX buffer is empty
 *
 ****************************************************************************/

static void usbser_txint(FAR struct uart_dev_s *dev, boolean enable)
{
  FAR struct usbser_dev_s *priv;

  usbtrace(USBSER_CLASSAPI_TXINT, (uint16)enable);

  /* Sanity checks */

#if CONFIG_DEBUG
  if (!dev || !dev->priv)
    {
       usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
       return;
    }
#endif

 /* Extract references to private data */

  priv = (FAR struct usbser_dev_s*)dev->priv;

  /* If the new state is enabled and if there is data in the XMIT buffer,
   * send the next packet now.
   */

  uvdbg("enable=%d head=%d tail=%d\n",
        enable, priv->serdev.xmit.head, priv->serdev.xmit.tail);

  if (enable && priv->serdev.xmit.head != priv->serdev.xmit.tail)
    {
      usbclass_sndpacket(priv);
    }
}

/****************************************************************************
 * Name: usbser_txempty
 *
 * Description:
 *   Return TRUE when all data has been sent.  This is called from the
 *   serial driver when the driver is closed.  It will call this API
 *   periodically until it reports TRUE.  NOTE that the serial driver takes all
 *   responsibility for flushing TX data through the hardware so we can be
 *   a bit sloppy about that.
 *
 ****************************************************************************/

static boolean usbser_txempty(FAR struct uart_dev_s *dev)
{
  FAR struct usbser_dev_s *priv = (FAR struct usbser_dev_s*)dev->priv;

  usbtrace(USBSER_CLASSAPI_TXEMPTY, 0);

#if CONFIG_DEBUG
  if (!priv)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_INVALIDARG), 0);
      return TRUE;
    }
#endif

  /* When all of the allocated write requests have been returned to the
   * reqlist, then there is no longer any TX data in flight.
   */

  return priv->nwrq >= CONFIG_USBSER_NWRREQS;
}

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

/****************************************************************************
 * Name: usbdev_serialinitialize
 *
 * Description:
 *   Register USB serial port (and USB serial console if so configured).
 *
 ****************************************************************************/

int usbdev_serialinitialize(int minor)
{
  FAR struct usbser_alloc_s *alloc;
  FAR struct usbser_dev_s *priv;
  FAR struct usbser_driver_s *drvr;
  char devname[16];
  int ret;

  /* Allocate the structures needed */

  alloc = (FAR struct usbser_alloc_s*)malloc(sizeof(struct usbser_alloc_s));
  if (!alloc)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_ALLOCDEVSTRUCT), 0);
      return -ENOMEM;
    }

  /* Convenience pointers into the allocated blob */

  priv = &alloc->dev;
  drvr = &alloc->drvr;

  /* Initialize the USB serial driver structure */

  memset(priv, 0, sizeof(struct usbser_dev_s));
  sq_init(&priv->reqlist);

  /* Fake line status */

  priv->linest[0] = (115200) & 0xff;       /* Baud=115200 */
  priv->linest[1] = (115200 >> 8) & 0xff;
  priv->linest[2] = (115200 >> 16) & 0xff;
  priv->linest[3] = (115200 >> 24) & 0xff;
  priv->linest[4] = 0;                     /* One stop bit */
  priv->linest[5] = 0;                     /* No parity */
  priv->linest[6] = 8;                     /*8 data bits */

  /* Initialize the serial driver sub-structure */

  priv->serdev.recv.size   = CONFIG_USBSER_RXBUFSIZE;
  priv->serdev.recv.buffer = priv->rxbuffer;
  priv->serdev.xmit.size   = CONFIG_USBSER_TXBUFSIZE;
  priv->serdev.xmit.buffer = priv->txbuffer;
  priv->serdev.ops         = &g_uartops;
  priv->serdev.priv        = priv;

  /* Initialize the USB class driver structure */

#ifdef CONFIG_USBDEV_DUALSPEED
  drvr->drvr.speed         = USB_SPEED_HIGH;
#else
  drvr->drvr.speed         = USB_SPEED_FULL;
#endif
  drvr->drvr.ops           = &g_driverops;
  drvr->dev                = priv;

  /* Register the USB serial class driver */

  ret = usbdev_register(&drvr->drvr);
  if (ret)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_DEVREGISTER), (uint16)-ret);
      goto errout_with_alloc;
    }

  /* Register the USB serial console */

#ifdef CONFIG_USBSER_CONSOLE
  g_usbserialport.isconsole = TRUE;
  ret = uart_register("/dev/console", &pri->serdev);
  if (ret < 0)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_CONSOLEREGISTER), (uint16)-ret);
      goto errout_with_class;
    }
#endif

  /* Register the single port supported by this implementation */

  sprintf(devname, "/dev/ttyUSB%d", minor);
  ret = uart_register(devname, &priv->serdev);
  if (ret)
    {
      usbtrace(TRACE_CLSERROR(USBSER_TRACEERR_UARTREGISTER), (uint16)-ret);
      goto errout_with_class;
    }
  return OK;

errout_with_class:
  usbdev_unregister(&drvr->drvr);
errout_with_alloc:
  free(alloc);
  return ret;
}