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

Copyright (c) 2004 - 2013, Intel Corporation. All rights reserved.
Portions Copyright 2012 Ashley DeSimone
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD
License which accompanies this distribution.  The full text of the license may
be found at http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

**/

//

// Tested with VEND_ID 0x0403, DEVICE_ID 0x6001
//
// Driver starts the device with the following values:
// 115200, No parity, 8 data bits, 1 stop bit, No Flow control
//

#include "FtdiUsbSerialDriver.h"

//
// Table of supported devices. This is the device information that this
// driver was developed with. Add other FTDI devices as needed.
//
USB_DEVICE gUSBDeviceList[] = {
  {VID_FTDI, DID_FTDI_FT232},
  {0,0}
};

//
// USB Serial Driver Global Variables
//
EFI_DRIVER_BINDING_PROTOCOL  gUsbSerialDriverBinding = {
  UsbSerialDriverBindingSupported,
  UsbSerialDriverBindingStart,
  UsbSerialDriverBindingStop,
  0xa,
  NULL,
  NULL
};

//
// Table with the nearest power of 2 for the numbers 0-15
//
UINT8 gRoundedPowersOf2[16] = { 0, 2, 2, 4, 4, 4, 8, 8, 8, 8, 8, 8, 16, 16, 16, 16 };

/**
  Check to see if the device path node is the Flow control node

  @param[in] FlowControl    The device path node to be checked

  @retval    TRUE           It is the flow control node
  @retval    FALSE          It is not the flow control node

**/
BOOLEAN
IsUartFlowControlNode (
  IN UART_FLOW_CONTROL_DEVICE_PATH *FlowControl
  )
{
  return (BOOLEAN) (
           (DevicePathType (FlowControl) == MESSAGING_DEVICE_PATH) &&
           (DevicePathSubType (FlowControl) == MSG_VENDOR_DP) &&
           (CompareGuid (&FlowControl->Guid, &gEfiUartDevicePathGuid))
           );
}

/**
  Checks the device path to see if it contains flow control.

  @param[in] DevicePath    The device path to be checked

  @retval    TRUE          It contains flow control
  @retval    FALSE         It does not contain flow control

**/
BOOLEAN
ContainsFlowControl (
  IN EFI_DEVICE_PATH_PROTOCOL  *DevicePath
  )
{
  while (!IsDevicePathEnd (DevicePath)) {
    if (IsUartFlowControlNode ((UART_FLOW_CONTROL_DEVICE_PATH *) DevicePath)) {
      return TRUE;
    }
    DevicePath = NextDevicePathNode (DevicePath);
  }
  return FALSE;
}

/**
  Transfer the data between the device and host.

  This function transfers the data between the device and host.
  BOT transfer is composed of three phases: Command, Data, and Status.
  This is the Data phase.

  @param  UsbBot[in]                     The USB BOT device
  @param  DataDir[in]                    The direction of the data
  @param  Data[in, out]                  The buffer to hold data
  @param  TransLen[in, out]              The expected length of the data
  @param  Timeout[in]                    The time to wait the command to complete

  @retval EFI_SUCCESS                    The data is transferred
  @retval EFI_SUCCESS                    No data to transfer
  @retval EFI_NOT_READY                  The device return NAK to the transfer
  @retval Others                         Failed to transfer data

**/
EFI_STATUS
UsbSerialDataTransfer (
  IN USB_SER_DEV             *UsbBot,
  IN EFI_USB_DATA_DIRECTION  DataDir,
  IN OUT VOID                *Data,
  IN OUT UINTN               *TransLen,
  IN UINT32                  Timeout
  )
{
  EFI_USB_ENDPOINT_DESCRIPTOR  *Endpoint;
  EFI_STATUS                   Status;
  UINT32                       Result;

  //
  // If no data to transfer, just return EFI_SUCCESS.
  //
  if ((DataDir == EfiUsbNoData) || (*TransLen == 0)) {
    return EFI_SUCCESS;
  }

  //
  // Select the endpoint then issue the transfer
  //
  if (DataDir == EfiUsbDataIn) {
    Endpoint = &UsbBot->InEndpointDescriptor;
  } else {
    Endpoint = &UsbBot->OutEndpointDescriptor;
  }

  Result = 0;
  Status = UsbBot->UsbIo->UsbBulkTransfer (
                            UsbBot->UsbIo,
                            Endpoint->EndpointAddress,
                            Data,
                            TransLen,
                            Timeout,
                            &Result
                            );
  if (EFI_ERROR (Status)) {
    if (USB_IS_ERROR (Result, EFI_USB_ERR_NAK)) {
      Status = EFI_NOT_READY;
    } else {
      UsbBot->Shutdown = TRUE; // Fixes infinite loop in older EFI
    }
    return Status;
  }
  return Status;
}

/**
  Sets the status values of the Usb Serial Device.

  @param  UsbSerialDevice[in]  Handle to the Usb Serial Device to set the status
                               for
  @param  StatusBuffer[in]     Buffer holding the status values

  @retval EFI_SUCCESS          The status values were read and set correctly

**/
EFI_STATUS
EFIAPI
SetStatusInternal (
  IN USB_SER_DEV  *UsbSerialDevice,
  IN UINT8        *StatusBuffer
  )
{
  UINT8  Msr;

  Msr = (StatusBuffer[0] & MSR_MASK);

  //
  // set the Status values to disabled
  //
  UsbSerialDevice->StatusValues.CtsState = FALSE;
  UsbSerialDevice->StatusValues.DsrState = FALSE;
  UsbSerialDevice->StatusValues.RiState  = FALSE;
  UsbSerialDevice->StatusValues.SdState  = FALSE;

  //
  // Check the values from the status buffer and set the appropriate status
  // values to enabled
  //
  if ((Msr & CTS_MASK) == CTS_MASK) {
    UsbSerialDevice->StatusValues.CtsState = TRUE;
  }
  if ((Msr & DSR_MASK) == DSR_MASK) {
    UsbSerialDevice->StatusValues.DsrState = TRUE;
  }
  if ((Msr & RI_MASK) == RI_MASK) {
    UsbSerialDevice->StatusValues.RiState = TRUE;
  }
  if ((Msr & SD_MASK) == SD_MASK) {
    UsbSerialDevice->StatusValues.SdState = TRUE;
  }
  return EFI_SUCCESS;
}

/**
  Initiates a read operation on the Usb Serial Device.

  @param  UsbSerialDevice[in]        Handle to the USB device to read
  @param  BufferSize[in, out]        On input, the size of the Buffer. On output,
                                     the amount of data returned in Buffer.
                                     Setting this to zero will initiate a read
                                     and store all data returned in the internal
                                     buffer.
  @param  Buffer [out]               The buffer to return the data into.

  @retval EFI_SUCCESS                The data was read.
  @retval EFI_DEVICE_ERROR           The device reported an error.
  @retval EFI_TIMEOUT                The data write was stopped due to a timeout.

**/
EFI_STATUS
EFIAPI
ReadDataFromUsb (
  IN USB_SER_DEV  *UsbSerialDevice,
  IN OUT UINTN    *BufferSize,
  OUT VOID        *Buffer
  )
{
  EFI_STATUS  Status;
  UINTN       ReadBufferSize;
  UINT8       *ReadBuffer;
  UINTN       Index;
  EFI_TPL     Tpl;
  UINT8       StatusBuffer[2]; // buffer to store the status bytes

  ReadBufferSize = 512;
  ReadBuffer     = &(UsbSerialDevice->ReadBuffer[0]);

  if (UsbSerialDevice->Shutdown) {
    return EFI_DEVICE_ERROR;
  }

  Tpl = gBS->RaiseTPL (TPL_NOTIFY);

  Status = UsbSerialDataTransfer (
             UsbSerialDevice,
             EfiUsbDataIn,
             ReadBuffer,
             &ReadBufferSize,
             FTDI_TIMEOUT*2  //Padded because timers won't be exactly aligned
             );
  if (EFI_ERROR (Status)) {
    gBS->RestoreTPL (Tpl);
    if (Status == EFI_TIMEOUT) {
      return EFI_TIMEOUT;
    } else {
      return EFI_DEVICE_ERROR;
    }
  }

  //
  // Store the status bytes in the status buffer
  //
  for (Index = 0; Index < 2; Index++) {//only the first 2 bytes are status bytes
    StatusBuffer[Index] = ReadBuffer[Index];
  }
  //
  // update the statusvalue field of the usbserialdevice
  //
  Status = SetStatusInternal (UsbSerialDevice, StatusBuffer);
  if (Status != EFI_SUCCESS) {
  }

  //
  // Store the read data in the read buffer, start at 2 to ignore status bytes
  //
  for (Index = 2; Index < ReadBufferSize; Index++) {
    if (((UsbSerialDevice->DataBufferTail + 1) % SW_FIFO_DEPTH) == UsbSerialDevice->DataBufferHead) {
      break;
    }
    if (ReadBuffer[Index] == 0x00) {
      //
      // This is null, do not add
      //
    } else {
      UsbSerialDevice->DataBuffer[UsbSerialDevice->DataBufferTail] = ReadBuffer[Index];
      UsbSerialDevice->DataBufferTail = (UsbSerialDevice->DataBufferTail + 1) % SW_FIFO_DEPTH;
    }
  }

  //
  // Read characters out of the buffer to satisfy caller's request.
  //
  for (Index = 0; Index < *BufferSize; Index++) {
    if (UsbSerialDevice->DataBufferHead == UsbSerialDevice->DataBufferTail) {
      break;
    }
    //
    // Still have characters in the buffer to return
    //
    ((UINT8 *)Buffer)[Index]        = UsbSerialDevice->DataBuffer[UsbSerialDevice->DataBufferHead];
    UsbSerialDevice->DataBufferHead = (UsbSerialDevice->DataBufferHead + 1) % SW_FIFO_DEPTH;
  }
  //
  // Return actual number of bytes returned.
  //
  *BufferSize = Index;
  gBS->RestoreTPL (Tpl);
  return EFI_SUCCESS;
}

/**
  Sets the initial status values of the Usb Serial Device by reading the status
  bytes from the device.

  @param  UsbSerialDevice[in]  Handle to the Usb Serial Device that needs its
                               initial status values set

  @retval EFI_SUCCESS          The status bytes were read successfully and the
                               initial status values were set correctly
  @retval EFI_TIMEOUT          The read of the status bytes was stopped due to a
                               timeout
  @retval EFI_DEVICE_ERROR     The device reported an error during the read of
                               the status bytes

**/
EFI_STATUS
EFIAPI
SetInitialStatus (
  IN USB_SER_DEV          *UsbSerialDevice
  )
{
  EFI_STATUS      Status;
  UINTN           BufferSize;
  EFI_TPL         Tpl;
  UINT8           StatusBuffer[2];

  Status          = EFI_UNSUPPORTED;
  BufferSize      = sizeof (StatusBuffer);

  if (UsbSerialDevice->Shutdown) {
    return EFI_DEVICE_ERROR;
  }

  Tpl = gBS->RaiseTPL (TPL_NOTIFY);

  Status = UsbSerialDataTransfer (
             UsbSerialDevice,
             EfiUsbDataIn,
             StatusBuffer,
             &BufferSize,
             40    //Slightly more than 2x the FTDI polling frequency to make sure that data will be returned
             );

  Status = SetStatusInternal (UsbSerialDevice, StatusBuffer);

  gBS->RestoreTPL (Tpl);

  return Status;
}

/**
  UsbSerialDriverCheckInput.
  attempts to read data in from the device periodically, stores any read data
  and updates the control attributes.

  @param  Event[in]
  @param  Context[in]....The current instance of the USB serial device

**/
VOID
EFIAPI
UsbSerialDriverCheckInput (
  IN  EFI_EVENT  Event,
  IN  VOID       *Context
  )
{
  UINTN        BufferSize;
  USB_SER_DEV  *UsbSerialDevice;

  UsbSerialDevice = (USB_SER_DEV*)Context;

  if (UsbSerialDevice->DataBufferHead == UsbSerialDevice->DataBufferTail) {
    //
    // Data buffer is empty, try to read from device
    //
    BufferSize = 0;
    ReadDataFromUsb (UsbSerialDevice, &BufferSize, NULL);
    if (UsbSerialDevice->DataBufferHead == UsbSerialDevice->DataBufferTail) {
      //
      // Data buffer still has no data, set the EFI_SERIAL_INPUT_BUFFER_EMPTY
      // flag
      //
      UsbSerialDevice->ControlBits |= EFI_SERIAL_INPUT_BUFFER_EMPTY;
    } else {
      //
      // Read has returned some data, clear the EFI_SERIAL_INPUT_BUFFER_EMPTY
      // flag
      //
      UsbSerialDevice->ControlBits &= ~(EFI_SERIAL_INPUT_BUFFER_EMPTY);
    }
  } else {
    //
    // Data buffer has data, no read attempt required
    //
    UsbSerialDevice->ControlBits &= ~(EFI_SERIAL_INPUT_BUFFER_EMPTY);
  }
}

/**
  Encodes the baud rate into the format expected by the Ftdi device.

  @param  BaudRate[in]                The baudrate to be set on the device
  @param  EncodedBaudRate[out]        The baud rate encoded in the format
                                      expected by the Ftdi device

  @return EFI_SUCCESS                 Baudrate encoding was calculated
                                      successfully
  @return EFI_INVALID_PARAMETER       An invalid value of BaudRate was received

**/
EFI_STATUS
EFIAPI
EncodeBaudRateForFtdi (
  IN  UINT64  BaudRate,
  OUT UINT16  *EncodedBaudRate
  )
{
  UINT32 Divisor;
  UINT32 AdjustedFrequency;
  UINT16 Result;

  //
  // Check to make sure we won't get an integer overflow
  //
  if ((BaudRate < 178) || ( BaudRate > ((FTDI_UART_FREQUENCY * 100) / 97))) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Baud Rates of 2000000 and 3000000 are special cases
  //
  if ((BaudRate >= FTDI_SPECIAL_CASE_300_MIN) && (BaudRate <= FTDI_SPECIAL_CASE_300_MAX)) {
    *EncodedBaudRate = 0;
    return EFI_SUCCESS;
  }
  if ((BaudRate >= FTDI_SPECIAL_CASE_200_MIN) && (BaudRate <= FTDI_SPECIAL_CASE_200_MAX)) {
    *EncodedBaudRate = 1;
    return EFI_SUCCESS;
  }

  //
  // Compute divisor
  //
  Divisor = (FTDI_UART_FREQUENCY << 4) / (UINT32)BaudRate;

  //
  // Round the last 4 bits to the nearest power of 2
  //
  Divisor = (Divisor & ~(0xF)) + (gRoundedPowersOf2[Divisor & 0xF]);

  //
  // Check to make sure computed divisor is within 
  // the min and max that FTDI controller will accept
  //
  if (Divisor < FTDI_MIN_DIVISOR) {
    Divisor = FTDI_MIN_DIVISOR;
  } else if (Divisor > FTDI_MAX_DIVISOR) {
    Divisor = FTDI_MAX_DIVISOR;
  }

  //
  // Check to make sure the frequency that the FTDI chip will need to
  // generate to attain the requested Baud Rate is within 3% of the
  // 3MHz clock frequency that the FTDI chip runs at.
  //
  // (3MHz * 1600) / 103 = 46601941
  // (3MHz * 1600) / 97  = 49484536
  //
  AdjustedFrequency = (((UINT32)BaudRate) * Divisor);
  if ((AdjustedFrequency < FTDI_MIN_FREQUENCY) || (AdjustedFrequency > FTDI_MAX_FREQUENCY)) {
    return EFI_INVALID_PARAMETER;
  }

  //
  // Encode the Divisor into the format FTDI expects
  //
  Result = (UINT16)(Divisor >> 4);
  if ((Divisor & 0x8) != 0) {
    Result |= 0x4000;
  } else if ((Divisor & 0x4) != 0) {
    Result |= 0x8000;
  } else if ((Divisor & 0x2) != 0) {
    Result |= 0xC000;
  }

  *EncodedBaudRate = Result;
  return EFI_SUCCESS;
}

/**
  Uses USB I/O to check whether the device is a USB Serial device.

  @param  UsbIo[in]    Pointer to a USB I/O protocol instance.

  @retval TRUE         Device is a USB Serial device.
  @retval FALSE        Device is a not USB Serial device.

**/
BOOLEAN
IsUsbSerial (
  IN  EFI_USB_IO_PROTOCOL  *UsbIo
  )
{
  EFI_STATUS                 Status;
  EFI_USB_DEVICE_DESCRIPTOR  DeviceDescriptor;
  CHAR16                     *StrMfg;
  BOOLEAN                    Found;
  UINT32                     Index;

  //
  // Get the default device descriptor
  //
  Status = UsbIo->UsbGetDeviceDescriptor (
                    UsbIo,
                    &DeviceDescriptor
                    );
  if (EFI_ERROR (Status)) {
    return FALSE;
  }

  Found = FALSE;
  Index = 0;
  while (gUSBDeviceList[Index].VendorId != 0 &&
         gUSBDeviceList[Index].DeviceId != 0 &&
         !Found                                  ) {
    if (DeviceDescriptor.IdProduct == gUSBDeviceList[Index].DeviceId &&
        DeviceDescriptor.IdVendor  == gUSBDeviceList[Index].VendorId      ){
        //
        // Checks to see if a string descriptor can be pulled from the device in
        // the selected language. If not False is returned indicating that this
        // is not a Usb Serial Device that can be managegd by this driver
        //
        StrMfg = NULL;
        Status = UsbIo->UsbGetStringDescriptor (
                          UsbIo,
                          USB_US_LANG_ID, // LANGID selector, should make this
                                          // more robust to verify lang support
                                          // for device
                          DeviceDescriptor.StrManufacturer,
                          &StrMfg
                          );
        if (StrMfg != NULL) {
          FreePool (StrMfg);
        }
        if (EFI_ERROR (Status)) {
          return FALSE;
        }
        return TRUE;
    }
    Index++;
  }
  return FALSE;
}

/**
  Internal function that sets the Data Bits, Stop Bits and Parity values on the
  Usb Serial Device with a single usb control transfer.

  @param  UsbIo[in]                  Usb Io Protocol instance pointer
  @param  DataBits[in]               The data bits value to be set on the Usb
                                     Serial Device
  @param  Parity[in]                 The parity type that will be set on the Usb
                                     Serial Device
  @param  StopBits[in]               The stop bits type that will be set on the
                                     Usb Serial Device
  @param  LastSettings[in]           A pointer to the Usb Serial Device's
                                     PREVIOUS_ATTRIBUTES item

  @retval EFI_SUCCESS                The data items were correctly set on the
                                     USB Serial Device
  @retval EFI_INVALID_PARAMETER      An invalid data parameter or an invalid
                                     combination or parameters was used
  @retval EFI_DEVICE_ERROR           The device is not functioning correctly and
                                     the data values were unable to be set

**/
EFI_STATUS
EFIAPI
SetDataInternal (
  IN EFI_USB_IO_PROTOCOL  *UsbIo,
  IN UINT8                DataBits,
  IN EFI_PARITY_TYPE      Parity,
  IN EFI_STOP_BITS_TYPE   StopBits,
  IN PREVIOUS_ATTRIBUTES  *LastSettings
  )
{
  EFI_STATUS              Status;
  EFI_USB_DEVICE_REQUEST  DevReq;
  UINT32                  ReturnValue;
  UINT8                   ConfigurationValue;

  //
  // Since data bits settings of 6,7,8 cannot be set with a stop bits setting of
  // 1.5 check to see if this happens when the values of last settings are used
  //
  if ((DataBits == 0) && (StopBits == OneFiveStopBits)) {
    if ((LastSettings->DataBits == 6) || (LastSettings->DataBits == 7) || (LastSettings->DataBits == 8)) {
      return EFI_INVALID_PARAMETER;
    }
  } else if ((StopBits == DefaultStopBits) && ((DataBits == 6) || (DataBits == 7) || (DataBits == 8))) {
    if (LastSettings->StopBits == OneFiveStopBits) {
      return EFI_INVALID_PARAMETER;
    }
  } else if ((DataBits == 0) && (StopBits == DefaultStopBits)) {
    if (LastSettings->StopBits == OneFiveStopBits) {
      if ((LastSettings->DataBits == 6) || (LastSettings->DataBits == 7) || (LastSettings->DataBits == 8)) {
        return EFI_INVALID_PARAMETER;
      }
    }
  }

  //
  // set the DevReq.Value for the usb control transfer to the correct value
  // based on the seleceted number of data bits if there is an invalid number of
  // data bits requested return EFI_INVALID_PARAMETER
  //
  if (((DataBits < 5 ) || (DataBits > 8)) && (DataBits != 0)) {
    return EFI_INVALID_PARAMETER;
  }
  if (DataBits == 0) {
    //
    // use the value of LastDataBits
    //
    DevReq.Value = SET_DATA_BITS (LastSettings->DataBits);
  } else {
    //
    // use the value of DataBits
    //
    DevReq.Value = SET_DATA_BITS (DataBits);
  }

  //
  // Set Parity
  //
  if (Parity == DefaultParity) {
    Parity = LastSettings->Parity;
  }

  if (Parity == NoParity) {
    DevReq.Value |= SET_PARITY_NONE;
  } else if (Parity == EvenParity) {
    DevReq.Value |= SET_PARITY_EVEN;
  } else if (Parity == OddParity){
    DevReq.Value |= SET_PARITY_ODD;
  } else if (Parity == MarkParity) {
    DevReq.Value |= SET_PARITY_MARK;
  } else if (Parity == SpaceParity) {
    DevReq.Value |= SET_PARITY_SPACE;
  }

  //
  // Set Stop Bits
  //
  if (StopBits == DefaultStopBits) {
    StopBits = LastSettings->StopBits;
  }

  if (StopBits == OneStopBit) {
    DevReq.Value |= SET_STOP_BITS_1;
  } else if (StopBits == OneFiveStopBits) {
    DevReq.Value |= SET_STOP_BITS_15;
  } else if (StopBits == TwoStopBits) {
    DevReq.Value |= SET_STOP_BITS_2;
  }

  //
  // set the rest of the DevReq parameters and perform the usb control transfer
  // to set the data bits on the device
  //
  DevReq.Request     = FTDI_COMMAND_SET_DATA;
  DevReq.RequestType = USB_REQ_TYPE_VENDOR;
  DevReq.Index       = FTDI_PORT_IDENTIFIER;
  DevReq.Length      = 0; // indicates that there is no data phase in this request

  Status = UsbIo->UsbControlTransfer (
                    UsbIo,
                    &DevReq,
                    EfiUsbDataOut,
                    WDR_SHORT_TIMEOUT,
                    &ConfigurationValue,
                    1,
                    &ReturnValue
                    );
  if (EFI_ERROR (Status)) {
    goto StatusError;
  }
  return Status;

StatusError:
  if ((Status != EFI_INVALID_PARAMETER) || (Status != EFI_DEVICE_ERROR)) {
    return EFI_DEVICE_ERROR;
  } else {
    return Status;
  }
}

/**
  Internal function that sets the baudrate on the Usb Serial Device.

  @param  UsbIo[in]                  Usb Io Protocol instance pointer
  @param  BaudRate[in]               The baudrate value to be set on the device.
                                     If this value is 0 the value of LastBaudRate
                                     will be used instead
  @param  LastBaudRate[in]           The baud rate value that was previously set
                                     on the Usb Serial Device

  @retval EFI_SUCCESS                The baudrate was set succesfully
  @retval EFI_INVALID_PARAMETER      An invalid baudrate was used
  @retval EFI_DEVICE_ERROR           The device is not functioning correctly and
                                     the baudrate was unable to be set

**/
EFI_STATUS
EFIAPI
SetBaudRateInternal (
  IN EFI_USB_IO_PROTOCOL  *UsbIo,
  IN UINT64               BaudRate,
  IN UINT64               LastBaudRate
  )
{
  EFI_STATUS              Status;
  EFI_USB_DEVICE_REQUEST  DevReq;
  UINT32                  ReturnValue;
  UINT8                   ConfigurationValue;
  UINT16                  EncodedBaudRate;
  EFI_TPL                 Tpl;

  Tpl    = gBS->RaiseTPL(TPL_NOTIFY);

  //
  // set the value of DevReq.Value based on the value of BaudRate
  // if 0 is selected as baud rate use the value of LastBaudRate
  //
  if (BaudRate == 0) {
    Status = EncodeBaudRateForFtdi (LastBaudRate, &EncodedBaudRate);
    if (EFI_ERROR (Status)) {
      gBS->RestoreTPL (Tpl);
      //
      // EncodeBaudRateForFtdi returns EFI_INVALID_PARAMETER when not
      // succesfull
      //
      return Status;
    }
    DevReq.Value = EncodedBaudRate;
  } else {
    Status = EncodeBaudRateForFtdi (BaudRate, &EncodedBaudRate);
    if (EFI_ERROR (Status)) {
      gBS->RestoreTPL (Tpl);
      //
      // EncodeBaudRateForFtdi returns EFI_INVALID_PARAMETER when not
      // successfull
      //
      return Status;
    }
    DevReq.Value = EncodedBaudRate;
  }

  //
  // set the remaining parameters of DevReq and perform the usb control transfer
  // to set the device
  //
  DevReq.Request     = FTDI_COMMAND_SET_BAUDRATE;
  DevReq.RequestType = USB_REQ_TYPE_VENDOR;
  DevReq.Index       = FTDI_PORT_IDENTIFIER;
  DevReq.Length      = 0; // indicates that there is no data phase in this request

  Status = UsbIo->UsbControlTransfer (
                    UsbIo,
                    &DevReq,
                    EfiUsbDataOut,
                    WDR_SHORT_TIMEOUT,
                    &ConfigurationValue,
                    1,
                    &ReturnValue
                    );
  if (EFI_ERROR (Status)) {
    goto StatusError;
  }
  gBS->RestoreTPL (Tpl);
  return Status;

StatusError:
  gBS->RestoreTPL (Tpl);
  if ((Status != EFI_INVALID_PARAMETER) || (Status != EFI_DEVICE_ERROR)) {
    return EFI_DEVICE_ERROR;
  } else {
    return Status;
  }
}

/**
  Sets the baud rate, receive FIFO depth, transmit/receice time out, parity,
  data bits, and stop bits on a serial device.

  @param  UsbSerialDevice[in]  Pointer to the current instance of the USB Serial
                               Device.
  @param  BaudRate[in]         The requested baud rate. A BaudRate value of 0
                               will use the device's default interface speed.
  @param  ReveiveFifoDepth[in] The requested depth of the FIFO on the receive
                               side of the serial interface. A ReceiveFifoDepth
                               value of 0 will use the device's default FIFO
                               depth.
  @param  Timeout[in]          The requested time out for a single character in
                               microseconds.This timeout applies to both the
                               transmit and receive side of the interface.A
                               Timeout value of 0 will use the device's default
                               time out value.
  @param  Parity[in]           The type of parity to use on this serial device.
                               A Parity value of DefaultParity will use the
                               device's default parity value.
  @param  DataBits[in]         The number of data bits to use on the serial
                               device. A DataBits value of 0 will use the
                               device's default data bit setting.
  @param  StopBits[in]         The number of stop bits to use on this serial
                               device. A StopBits value of DefaultStopBits will
                               use the device's default number of stop bits.

  @retval EFI_SUCCESS          The attributes were set
  @retval EFI_DEVICE_ERROR     The attributes were not able to be set

**/
EFI_STATUS
EFIAPI
SetAttributesInternal (
  IN USB_SER_DEV         *UsbSerialDevice,
  IN UINT64              BaudRate,
  IN UINT32              ReceiveFifoDepth,
  IN UINT32              Timeout,
  IN EFI_PARITY_TYPE     Parity,
  IN UINT8               DataBits,
  IN EFI_STOP_BITS_TYPE  StopBits
  )
{
  EFI_STATUS                Status;
  EFI_TPL                   Tpl;
  UART_DEVICE_PATH          *Uart;
  EFI_DEVICE_PATH_PROTOCOL  *RemainingDevicePath;

  Status = EFI_UNSUPPORTED;
  Tpl    = gBS->RaiseTPL(TPL_NOTIFY);
  Uart   = NULL;

  //
  // check for invalid combinations of parameters
  //
  if (((DataBits >= 6) && (DataBits <= 8)) && (StopBits == OneFiveStopBits)) {
    return  EFI_INVALID_PARAMETER;
  }

  //
  // set data bits, parity and stop bits
  //
  Status = SetDataInternal (
             UsbSerialDevice->UsbIo,
             DataBits,
             Parity,
             StopBits,
             &(UsbSerialDevice->LastSettings)
             );
  if (EFI_ERROR (Status)) {
    goto StatusError;
  }
  //
  // set baudrate
  //
  Status = SetBaudRateInternal (
             UsbSerialDevice->UsbIo,
             BaudRate,
             UsbSerialDevice->LastSettings.BaudRate
             );
  if (EFI_ERROR (Status)){
    goto StatusError;
  }

  //
  // update the values of UsbSerialDevice->LastSettings and UsbSerialDevice->SerialIo.Mode
  //
  if (BaudRate == 0) {
    UsbSerialDevice->LastSettings.BaudRate   = UsbSerialDevice->LastSettings.BaudRate;
    UsbSerialDevice->SerialIo.Mode->BaudRate = UsbSerialDevice->LastSettings.BaudRate;
  } else {
    UsbSerialDevice->LastSettings.BaudRate   = BaudRate;
    UsbSerialDevice->SerialIo.Mode->BaudRate = BaudRate;
  }

  UsbSerialDevice->LastSettings.Timeout          = FTDI_TIMEOUT;
  UsbSerialDevice->LastSettings.ReceiveFifoDepth = FTDI_MAX_RECEIVE_FIFO_DEPTH;

  if (Parity == DefaultParity) {
    UsbSerialDevice->LastSettings.Parity   = UsbSerialDevice->LastSettings.Parity;
    UsbSerialDevice->SerialIo.Mode->Parity = UsbSerialDevice->LastSettings.Parity;
  } else {
    UsbSerialDevice->LastSettings.Parity   = Parity;
    UsbSerialDevice->SerialIo.Mode->Parity = Parity;
  }
  if (DataBits == 0) {
    UsbSerialDevice->LastSettings.DataBits   = UsbSerialDevice->LastSettings.DataBits;
    UsbSerialDevice->SerialIo.Mode->DataBits = UsbSerialDevice->LastSettings.DataBits;
  } else {
    UsbSerialDevice->LastSettings.DataBits   = DataBits;
    UsbSerialDevice->SerialIo.Mode->DataBits = DataBits;
  }
  if (StopBits == DefaultStopBits) {
    UsbSerialDevice->LastSettings.StopBits   = UsbSerialDevice->LastSettings.StopBits;
    UsbSerialDevice->SerialIo.Mode->StopBits = UsbSerialDevice->LastSettings.StopBits;
  } else {
    UsbSerialDevice->LastSettings.StopBits   = StopBits;
    UsbSerialDevice->SerialIo.Mode->StopBits = StopBits;
  }

  //
  // See if the device path node has changed
  //
  if (UsbSerialDevice->UartDevicePath.BaudRate == BaudRate &&
      UsbSerialDevice->UartDevicePath.DataBits == DataBits &&
      UsbSerialDevice->UartDevicePath.StopBits == StopBits &&
      UsbSerialDevice->UartDevicePath.Parity == Parity
      ) {
    gBS->RestoreTPL (Tpl);
    return EFI_SUCCESS;
  }

  //
  // Update the device path
  //
  UsbSerialDevice->UartDevicePath.BaudRate = BaudRate;
  UsbSerialDevice->UartDevicePath.DataBits = DataBits;
  UsbSerialDevice->UartDevicePath.StopBits = (UINT8) StopBits;
  UsbSerialDevice->UartDevicePath.Parity   = (UINT8) Parity;

  Status = EFI_SUCCESS;
  if (UsbSerialDevice->ControllerHandle != NULL) {
    RemainingDevicePath = UsbSerialDevice->DevicePath;
    while (!IsDevicePathEnd (RemainingDevicePath)) {
      Uart = (UART_DEVICE_PATH *) NextDevicePathNode (RemainingDevicePath);
      if (Uart->Header.Type == MESSAGING_DEVICE_PATH &&
          Uart->Header.SubType == MSG_UART_DP &&
          sizeof (UART_DEVICE_PATH) == DevicePathNodeLength ((EFI_DEVICE_PATH *) Uart)) {
        Uart->BaudRate = BaudRate;
        Uart->DataBits = DataBits;
        Uart->StopBits = (UINT8)StopBits;
        Uart->Parity   = (UINT8) Parity;
        break;
        }
        RemainingDevicePath = NextDevicePathNode (RemainingDevicePath);
    }
  }

  gBS->RestoreTPL (Tpl);
  return Status;

StatusError:
  gBS->RestoreTPL (Tpl);
  if ((Status != EFI_INVALID_PARAMETER) || (Status != EFI_DEVICE_ERROR)) {
    return EFI_DEVICE_ERROR;
  } else {
    return Status;
  }
}

/**
  Internal function that performs a Usb Control Transfer to set the flow control
  on the Usb Serial Device.

  @param  UsbIo[in]                  Usb Io Protocol instance pointer
  @param  FlowControlEnable[in]      Data on the Enable/Disable status of Flow
                                     Control on the Usb Serial Device

  @retval EFI_SUCCESS                The flow control was set on the Usb Serial
                                     device
  @retval EFI_INVALID_PARAMETER      An invalid flow control value was used
  @retval EFI_EFI_UNSUPPORTED        The operation is not supported
  @retval EFI_DEVICE_ERROR           The device is not functioning correctly

**/
EFI_STATUS
EFIAPI
SetFlowControlInternal (
  IN EFI_USB_IO_PROTOCOL  *UsbIo,
  IN BOOLEAN              FlowControlEnable
  )
{
  EFI_STATUS               Status;
  EFI_USB_DEVICE_REQUEST   DevReq;
  UINT32                   ReturnValue;
  UINT8                    ConfigurationValue;

  //
  // set DevReq.Value based on the value of FlowControlEnable
  //
  if (!FlowControlEnable) {
    DevReq.Value = NO_FLOW_CTRL;
  }
  if (FlowControlEnable) {
    DevReq.Value = XON_XOFF_CTRL;
  }
  //
  // set the remaining DevReq parameters and perform the usb control transfer to
  // set the flow control on the device
  //
  DevReq.Request      = FTDI_COMMAND_SET_FLOW_CTRL;
  DevReq.RequestType  = USB_REQ_TYPE_VENDOR;
  DevReq.Index        = FTDI_PORT_IDENTIFIER;
  DevReq.Length       = 0; // indicates that this transfer has no data phase
  Status              = UsbIo->UsbControlTransfer (
                                 UsbIo,
                                 &DevReq,
                                 EfiUsbDataOut,
                                 WDR_TIMEOUT,
                                 &ConfigurationValue,
                                 1,
                                 &ReturnValue
                                 );
  if (EFI_ERROR (Status)) {
    goto StatusError;
  }

  return Status;

StatusError:
  if ((Status != EFI_INVALID_PARAMETER) ||
      (Status != EFI_DEVICE_ERROR)      ||
      (Status != EFI_UNSUPPORTED)          ) {
    return EFI_DEVICE_ERROR;
  } else {
    return Status;
  }
}

/**
  Internal function that performs a Usb Control Transfer to set the Dtr value on
  the Usb Serial Device.

  @param  UsbIo[in]                  Usb Io Protocol instance pointer
  @param  DtrEnable[in]              Data on the Enable/Disable status of the
                                     Dtr for the Usb Serial Device

  @retval EFI_SUCCESS                The Dtr value was set on the Usb Serial
                                     Device
  @retval EFI_INVALID_PARAMETER      An invalid Dtr value was used
  @retval EFI_UNSUPPORTED            The operation is not supported
  @retval EFI_DEVICE_ERROR           The device is not functioning correctly

**/
EFI_STATUS
EFIAPI
SetDtrInternal (
  IN EFI_USB_IO_PROTOCOL  *UsbIo,
  IN BOOLEAN              DtrEnable
  )
{
  EFI_STATUS              Status;
  EFI_USB_DEVICE_REQUEST  DevReq;
  UINT32                  ReturnValue;
  UINT8                   ConfigurationValue;

  //
  // set the value of DevReq.Value based on the value of DtrEnable
  //
  if (!DtrEnable) {
    DevReq.Value = SET_DTR_LOW;
  }
  if (DtrEnable) {
    DevReq.Value = SET_DTR_HIGH;
  }
  //
  // set the remaining attributes of DevReq and perform the usb control transfer
  // to set the device
  //
  DevReq.Request      = FTDI_COMMAND_MODEM_CTRL;
  DevReq.RequestType  = USB_REQ_TYPE_VENDOR;
  DevReq.Index        = FTDI_PORT_IDENTIFIER;
  DevReq.Length       = 0; // indicates that there is no data phase in this transfer

  Status = UsbIo->UsbControlTransfer (
                    UsbIo,
                    &DevReq,
                    EfiUsbDataOut,
                    WDR_TIMEOUT,
                    &ConfigurationValue,
                    1,
                    &ReturnValue
                    );
  if (EFI_ERROR (Status)) {
    goto StatusError;
  }
  return Status;

StatusError:
  if ((Status != EFI_INVALID_PARAMETER) ||
      (Status != EFI_DEVICE_ERROR)      ||
      (Status != EFI_UNSUPPORTED)          ) {
    return EFI_DEVICE_ERROR;
  } else {
    return Status;
  }
}

/**
  Internal function that performs a Usb Control Transfer to set the Dtr value on
  the Usb Serial Device.
  
  @param  UsbIo[in]                  Usb Io Protocol instance pointer
  @param  RtsEnable[in]              Data on the Enable/Disable status of the
                                     Rts for the Usb Serial Device

  @retval EFI_SUCCESS                The Rts value was set on the Usb Serial
                                     Device
  @retval EFI_INVALID_PARAMETER      An invalid Rts value was used
  @retval EFI_UNSUPPORTED            The operation is not supported
  @retval EFI_DEVICE_ERROR           The device is not functioning correctly

**/
EFI_STATUS
EFIAPI
SetRtsInternal (
  IN EFI_USB_IO_PROTOCOL  *UsbIo,
  IN BOOLEAN              RtsEnable
  )
{
  EFI_STATUS              Status;
  EFI_USB_DEVICE_REQUEST  DevReq;
  UINT32                  ReturnValue;
  UINT8                   ConfigurationValue;

  //
  // set DevReq.Value based on the value of RtsEnable
  //
  if (!RtsEnable) {
    DevReq.Value = SET_RTS_LOW;
  }
  if (RtsEnable) {
    DevReq.Value = SET_RTS_HIGH;
  }

  //
  // set the remaining parameters of DevReq and perform the usb control transfer
  // to set the values on the device
  //
  DevReq.Request     = FTDI_COMMAND_MODEM_CTRL;
  DevReq.RequestType = USB_REQ_TYPE_VENDOR;
  DevReq.Index       = FTDI_PORT_IDENTIFIER;
  DevReq.Length      = 0; // indicates that there is no data phase in this request

  Status = UsbIo->UsbControlTransfer (
                    UsbIo,
                    &DevReq,
                    EfiUsbDataOut,
                    WDR_TIMEOUT,
                    &ConfigurationValue,
                    1,
                    &ReturnValue
                    );
  if (EFI_ERROR (Status)) {
    goto StatusError;
  }

  return Status;

StatusError:
  if ((Status != EFI_INVALID_PARAMETER) ||
      (Status != EFI_DEVICE_ERROR)      ||
      (Status != EFI_UNSUPPORTED)          ) {
    return EFI_DEVICE_ERROR;
  } else {
    return Status;
  }
}

/**
  Internal function that checks for valid control values and sets the control
  bits on the Usb Serial Device.

  @param  UsbSerialDevice[in]        Handle to the Usb Serial Device whose
                                     control bits are being set
  @param  Control[in]                The control value passed to the function
                                     that contains the values of the control
                                     bits that are being set

  @retval EFI_SUCCESS                The control bits were set on the Usb Serial
                                     Device
  @retval EFI_INVALID_PARAMETER      An invalid control value was encountered
  @retval EFI_EFI_UNSUPPORTED        The operation is not supported
  @retval EFI_DEVICE_ERROR           The device is not functioning correctly

**/
EFI_STATUS
EFIAPI
SetControlBitsInternal (
  IN USB_SER_DEV   *UsbSerialDevice,
  IN CONTROL_BITS  *Control
  )
{
  EFI_STATUS                    Status;
  UART_FLOW_CONTROL_DEVICE_PATH *FlowControl;
  EFI_DEVICE_PATH_PROTOCOL      *RemainingDevicePath;

  //
  // check for invalid control parameters hardware and software loopback enabled
  // must always be set to FALSE
  //
  Control->HardwareLoopBack = FALSE;
  Control->SoftwareLoopBack = FALSE;

  //
  // set hardware flow control
  //
  Status  = SetFlowControlInternal (
              UsbSerialDevice->UsbIo,
              Control->HardwareFlowControl
              );
  if (EFI_ERROR (Status)) {
    goto StatusError;
  }

  //
  // set Dtr state
  //
  Status = SetDtrInternal (UsbSerialDevice->UsbIo, Control->DtrState);
  if (EFI_ERROR (Status)) {
    goto StatusError;
  }

  //
  // set Rts state
  //
  Status = SetRtsInternal (UsbSerialDevice->UsbIo, Control->RtsState);
  if (EFI_ERROR (Status)){
    goto StatusError;
  }

  //
  // update the remaining control values for UsbSerialDevice->ControlValues
  //
  UsbSerialDevice->ControlValues.DtrState            = Control->DtrState;
  UsbSerialDevice->ControlValues.RtsState            = Control->RtsState;
  UsbSerialDevice->ControlValues.HardwareFlowControl = Control->HardwareFlowControl;
  UsbSerialDevice->ControlValues.HardwareLoopBack    = FALSE;
  UsbSerialDevice->ControlValues.SoftwareLoopBack    = FALSE;

  Status = EFI_SUCCESS;
  //
  // Update the device path to have the correct flow control values
  //
  if (UsbSerialDevice->ControllerHandle != NULL) {
    RemainingDevicePath = UsbSerialDevice->DevicePath;
    while (!IsDevicePathEnd (RemainingDevicePath)) {
      FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (RemainingDevicePath);
      if (FlowControl->Header.Type == MESSAGING_DEVICE_PATH &&
          FlowControl->Header.SubType == MSG_VENDOR_DP &&
          sizeof (UART_FLOW_CONTROL_DEVICE_PATH) == DevicePathNodeLength ((EFI_DEVICE_PATH *) FlowControl)){
        if (UsbSerialDevice->ControlValues.HardwareFlowControl == TRUE) {
          FlowControl->FlowControlMap = UART_FLOW_CONTROL_HARDWARE;
        } else if (UsbSerialDevice->ControlValues.HardwareFlowControl == FALSE) {
          FlowControl->FlowControlMap = 0;
        }
        break;
      }
      RemainingDevicePath = NextDevicePathNode (RemainingDevicePath);
    }
  }

  return Status;

StatusError:
  if ((Status != EFI_INVALID_PARAMETER) ||
      (Status != EFI_DEVICE_ERROR)      ||
      (Status != EFI_UNSUPPORTED)          ) {
    return EFI_DEVICE_ERROR;
  } else {
    return Status;
  }
}

/**
  Internal function that calculates the Control value used by GetControlBits()
  based on the status and control values of the Usb Serial Device.

  @param  UsbSerialDevice[in]        Handle to the Usb Serial Devie whose status
                                     and control values are being used to set
                                     Control
  @param  Control[out]               On output the formated value of Control
                                     that has been calculated based on the
                                     control and status values of the Usb Serial
                                     Device

  @retval EFI_SUCCESS                The value of Control was successfully
                                     calculated

**/
EFI_STATUS
EFIAPI
GetControlBitsInternal (
  IN USB_SER_DEV  *UsbSerialDevice,
  OUT UINT32      *Control
  )
{
  *Control = 0;

  //
  // Check the values of UsbSerialDevice->Status Values and modify control
  // accordingly these values correspond to the modem status register
  //
  if (UsbSerialDevice->StatusValues.CtsState) {
    *Control |= EFI_SERIAL_CLEAR_TO_SEND;
  }
  if (UsbSerialDevice->StatusValues.DsrState) {
    *Control |= EFI_SERIAL_DATA_SET_READY;
  }
  if (UsbSerialDevice->StatusValues.RiState) {
    *Control |= EFI_SERIAL_RING_INDICATE;
  }
  if (UsbSerialDevice->StatusValues.SdState) {
    *Control |= EFI_SERIAL_CARRIER_DETECT;
  }

  //
  // check the values of UsbSerialDevice->ControlValues and modify control
  // accordingly these values correspond to the values of the Modem Control
  // Register
  //
  if (UsbSerialDevice->ControlValues.DtrState) {
    *Control |= EFI_SERIAL_DATA_TERMINAL_READY;
  }
  if (UsbSerialDevice->ControlValues.RtsState) {
    *Control |= EFI_SERIAL_REQUEST_TO_SEND;
  }
  if (UsbSerialDevice->ControlValues.HardwareLoopBack) {
    *Control |= EFI_SERIAL_HARDWARE_LOOPBACK_ENABLE;
  }
  if (UsbSerialDevice->ControlValues.HardwareFlowControl) {
    *Control |= EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE;
  }
  //
  // check if the buffer is empty since only one is being used if it is empty
  // set both the receive and transmit buffers to empty
  //
  if (UsbSerialDevice->DataBufferHead == UsbSerialDevice->DataBufferTail) {
    *Control |= EFI_SERIAL_OUTPUT_BUFFER_EMPTY;
    *Control |= EFI_SERIAL_INPUT_BUFFER_EMPTY;
  }
  //
  // check for software loopback enable in UsbSerialDevice->ControlValues
  //
  if (UsbSerialDevice->ControlValues.SoftwareLoopBack) {
    *Control |= EFI_SERIAL_SOFTWARE_LOOPBACK_ENABLE;
  }

  return EFI_SUCCESS;
}

/**
  Resets the USB Serial Device

  This function is the internal method for resetting the device and is called by
  SerialReset()

  @param  UsbSerialDevice[in]  A pointer to the USB Serial device

  @retval EFI_SUCCESS          The device was reset
  @retval EFI_DEVICE_ERROR     The device could not be reset

**/
EFI_STATUS
EFIAPI
ResetInternal (
  IN USB_SER_DEV  *UsbSerialDevice
  )
{
  EFI_STATUS              Status;
  EFI_USB_DEVICE_REQUEST  DevReq;
  UINT8                   ConfigurationValue;
  UINT32                  ReturnValue;

  DevReq.Request     = FTDI_COMMAND_RESET_PORT;
  DevReq.RequestType = USB_REQ_TYPE_VENDOR;
  DevReq.Value       = RESET_PORT_PURGE_RX;
  DevReq.Index       = FTDI_PORT_IDENTIFIER;
  DevReq.Length      = 0; //indicates that there is not data phase in this request

  Status = UsbSerialDevice->UsbIo->UsbControlTransfer (
                                     UsbSerialDevice->UsbIo,
                                     &DevReq,
                                     EfiUsbDataIn,
                                     WDR_TIMEOUT,
                                     &ConfigurationValue,
                                     1,
                                     &ReturnValue
                                     );
  if (EFI_ERROR (Status)) {
    return EFI_DEVICE_ERROR;
  }

  DevReq.Request     = FTDI_COMMAND_RESET_PORT;
  DevReq.RequestType = USB_REQ_TYPE_VENDOR;
  DevReq.Value       = RESET_PORT_PURGE_TX;
  DevReq.Index       = FTDI_PORT_IDENTIFIER;
  DevReq.Length      = 0; //indicates that there is no data phase in this request

  Status = UsbSerialDevice->UsbIo->UsbControlTransfer (
                                     UsbSerialDevice->UsbIo,
                                     &DevReq,
                                     EfiUsbDataIn,
                                     WDR_TIMEOUT,
                                     &ConfigurationValue,
                                     1,
                                     &ReturnValue
                                     );
  if (EFI_ERROR (Status)) {
    return EFI_DEVICE_ERROR;
  }
  return Status;
}

/**
  Entrypoint of USB Serial Driver.

  This function is the entrypoint of USB Serial Driver. It installs
  Driver Binding Protocols together with Component Name Protocols.

  @param  ImageHandle[in]       The firmware allocated handle for the EFI image.
  @param  SystemTable[in]       A pointer to the EFI System Table.

  @retval EFI_SUCCESS           The entry point is executed successfully.

**/
EFI_STATUS
EFIAPI
FtdiUsbSerialEntryPoint (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS  Status;

  Status = EfiLibInstallDriverBindingComponentName2 (
             ImageHandle,
             SystemTable,
             &gUsbSerialDriverBinding,
             ImageHandle,
             &gUsbSerialComponentName,
             &gUsbSerialComponentName2
             );
  ASSERT_EFI_ERROR (Status);
  return EFI_SUCCESS;
}

/**
  Unload function for the Usb Serial Driver.

  @param  ImageHandle[in]    The allocated handle for the EFI image

  @retval EFI_SUCCESS        The driver was unloaded successfully
**/
EFI_STATUS
EFIAPI
FtdiUsbSerialUnload (
  IN EFI_HANDLE  ImageHandle
  )
{
  EFI_STATUS  Status;
  EFI_HANDLE  *HandleBuffer;
  UINTN       HandleCount;
  UINTN       Index;

  //
  // Retrieve all handles in the handle database
  //
  Status = gBS->LocateHandleBuffer (
                  AllHandles,
                  NULL,
                  NULL,
                  &HandleCount,
                  &HandleBuffer
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  //
  // Disconnect the driver from the handles in the handle database
  //
  for (Index = 0; Index < HandleCount; Index++) {
    Status = gBS->DisconnectController (
                    HandleBuffer[Index],
                    gImageHandle,
                    NULL
                    );
  }

  //
  // Free the handle array
  //
  FreePool (HandleBuffer);

  //
  // Uninstall protocols installed by the driver in its entrypoint
  //
  Status = gBS->UninstallMultipleProtocolInterfaces (
                  ImageHandle,
                  &gEfiDriverBindingProtocolGuid,
                  &gUsbSerialDriverBinding,
                  &gEfiComponentNameProtocolGuid,
                  &gUsbSerialComponentName,
                  &gEfiComponentName2ProtocolGuid,
                  &gUsbSerialComponentName2,
                  NULL
                  );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  return EFI_SUCCESS;
}

/**
  Check whether USB Serial driver supports this device.

  @param  This[in]                   The USB Serial driver binding protocol.
  @param  Controller[in]             The controller handle to check.
  @param  RemainingDevicePath[in]    The remaining device path.

  @retval EFI_SUCCESS                The driver supports this controller.
  @retval other                      This device isn't supported.

**/
EFI_STATUS
EFIAPI
UsbSerialDriverBindingSupported (
  IN EFI_DRIVER_BINDING_PROTOCOL  *This,
  IN EFI_HANDLE                   Controller,
  IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath
  )
{
  EFI_STATUS           Status;
  EFI_USB_IO_PROTOCOL  *UsbIo;
  UART_DEVICE_PATH     *UartNode;
  UART_FLOW_CONTROL_DEVICE_PATH        *FlowControlNode;
  UINTN                                Index;
  UINTN                                EntryCount;
  EFI_OPEN_PROTOCOL_INFORMATION_ENTRY  *OpenInfoBuffer;
  BOOLEAN                              HasFlowControl;
  EFI_DEVICE_PATH_PROTOCOL             *DevicePath;
  EFI_DEVICE_PATH_PROTOCOL             *ParentDevicePath;

  if (RemainingDevicePath != NULL) {
    if (!IsDevicePathEnd (RemainingDevicePath)) {
      Status = EFI_UNSUPPORTED;
      UartNode = (UART_DEVICE_PATH *) NextDevicePathNode (RemainingDevicePath);
      if (UartNode->Header.Type != MESSAGING_DEVICE_PATH ||
          UartNode->Header.SubType != MSG_UART_DP ||
          sizeof (UART_DEVICE_PATH) != DevicePathNodeLength ((EFI_DEVICE_PATH *) UartNode)) {
        goto Error;
      }
      FlowControlNode = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (UartNode);
      if ((ReadUnaligned32 (&FlowControlNode->FlowControlMap) & ~UART_FLOW_CONTROL_HARDWARE) != 0) {
        goto Error;
      }
    }
  }

  //
  // Check if USB I/O Protocol is attached on the controller handle.
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiUsbIoProtocolGuid,
                  (VOID **) &UsbIo,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );
  if (Status == EFI_ALREADY_STARTED) {
    if (RemainingDevicePath == NULL || IsDevicePathEnd (RemainingDevicePath)) {
      return EFI_SUCCESS;
    }
    Status = gBS->OpenProtocolInformation (
                    Controller,
                    &gEfiUsbIoProtocolGuid,
                    &OpenInfoBuffer,
                    &EntryCount
                    );
    if (EFI_ERROR (Status)) {
      return Status;
    }
    for (Index = 0; Index < EntryCount; Index++) {
      if ((OpenInfoBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0) {
        Status = gBS->OpenProtocol (
                        OpenInfoBuffer[Index].ControllerHandle,
                        &gEfiDevicePathProtocolGuid,
                        (VOID **) &DevicePath,
                        This->DriverBindingHandle,
                        Controller,
                        EFI_OPEN_PROTOCOL_GET_PROTOCOL
                        );
        if (!EFI_ERROR (Status)) {
          HasFlowControl = ContainsFlowControl (RemainingDevicePath);
          if (HasFlowControl ^ ContainsFlowControl (DevicePath)) {
            Status = EFI_UNSUPPORTED;
          }
        }
        break;
      }
    }
    FreePool (OpenInfoBuffer);
    return Status;
  }

  if (EFI_ERROR (Status)) {
    return Status;
  }

  gBS->CloseProtocol (
         Controller,
         &gEfiUsbIoProtocolGuid,
         This->DriverBindingHandle,
         Controller
         );

  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiDevicePathProtocolGuid,
                  (VOID **) &ParentDevicePath,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );
  if (Status == EFI_ALREADY_STARTED) {
    return EFI_SUCCESS;
  }
  if (EFI_ERROR (Status)) {
    return Status;
  }

  //
  // Use the USB I/O Protocol interface to check whether Controller is
  // a USB Serial device that can be managed by this driver.
  //
  Status = EFI_SUCCESS;

  if (!IsUsbSerial (UsbIo)) {
    Status = EFI_UNSUPPORTED;
    goto Error;
  }

Error:
  gBS->CloseProtocol (
         Controller,
         &gEfiDevicePathProtocolGuid,
         This->DriverBindingHandle,
         Controller
         );
  return Status;
}

/**
  Starts the USB Serial device with this driver.

  This function produces initializes the USB Serial device and
  produces the Serial IO Protocol.

  @param  This[in]                   The USB Serial driver binding instance.
  @param  Controller[in]             Handle of device to bind driver to.
  @param  RemainingDevicePath[in]    Optional parameter use to pick a specific
                                     child device to start.

  @retval EFI_SUCCESS                The controller is controlled by the usb USB
                                     Serial driver.
  @retval EFI_UNSUPPORTED            No interrupt endpoint can be found.
  @retval Other                      This controller cannot be started.

**/
EFI_STATUS
EFIAPI
UsbSerialDriverBindingStart (
  IN EFI_DRIVER_BINDING_PROTOCOL  *This,
  IN EFI_HANDLE                   Controller,
  IN EFI_DEVICE_PATH_PROTOCOL     *RemainingDevicePath
  )
{
  EFI_STATUS                          Status;
  EFI_USB_IO_PROTOCOL                 *UsbIo;
  USB_SER_DEV                         *UsbSerialDevice;
  UINT8                               EndpointNumber;
  EFI_USB_ENDPOINT_DESCRIPTOR         EndpointDescriptor;
  UINT8                               Index;
  BOOLEAN                             FoundIn;
  BOOLEAN                             FoundOut;
  EFI_DEVICE_PATH_PROTOCOL            *ParentDevicePath;
  EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfoBuffer;
  UINTN                               EntryCount;
  EFI_SERIAL_IO_PROTOCOL              *SerialIo;
  UART_DEVICE_PATH                    *Uart;
  UART_FLOW_CONTROL_DEVICE_PATH       *FlowControl;
  UINT32                              Control;
  EFI_DEVICE_PATH_PROTOCOL            *TempDevicePath;

  UsbSerialDevice = AllocateZeroPool (sizeof (USB_SER_DEV));
  ASSERT (UsbSerialDevice != NULL);

  //
  // Get the Parent Device path
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiDevicePathProtocolGuid,
                  (VOID **) &ParentDevicePath,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );
  if (EFI_ERROR (Status) && Status != EFI_ALREADY_STARTED) {
    goto ErrorExit1;
  }

  //
  // Open USB I/O Protocol
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiUsbIoProtocolGuid,
                  (VOID **) &UsbIo,
                  This->DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );
  if (EFI_ERROR (Status) && Status != EFI_ALREADY_STARTED) {
    goto ErrorExit1;
  }

  if (Status == EFI_ALREADY_STARTED) {
    if (RemainingDevicePath == NULL || IsDevicePathEnd (RemainingDevicePath)) {
      FreePool (UsbSerialDevice);
      return EFI_SUCCESS;
    }

    //
    // Check to see if a child handle exists
    //
    Status = gBS->OpenProtocolInformation (
                    Controller,
                    &gEfiSerialIoProtocolGuid,
                    &OpenInfoBuffer,
                    &EntryCount
                    );
    if (EFI_ERROR (Status)) {
      goto ErrorExit1;
    }

    Status = EFI_ALREADY_STARTED;
    for (Index = 0; Index < EntryCount; Index++) {
      if ((OpenInfoBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0) {
        Status = gBS->OpenProtocol (
                        OpenInfoBuffer[Index].ControllerHandle,
                        &gEfiSerialIoProtocolGuid,
                        (VOID **) &SerialIo,
                        This->DriverBindingHandle,
                        Controller,
                        EFI_OPEN_PROTOCOL_GET_PROTOCOL
                        );
        if (EFI_ERROR (Status)) {
        }
        if (!EFI_ERROR (Status)) {
          Uart = (UART_DEVICE_PATH *) RemainingDevicePath;
          Status = SerialIo->SetAttributes (
                               SerialIo,
                               Uart->BaudRate,
                               SerialIo->Mode->ReceiveFifoDepth,
                               SerialIo->Mode->Timeout,
                               (EFI_PARITY_TYPE) Uart->Parity,
                               Uart->DataBits,
                               (EFI_STOP_BITS_TYPE) Uart->StopBits
                               );
          FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (Uart);
          if (!EFI_ERROR (Status) && IsUartFlowControlNode (FlowControl)) {
            Status = SerialIo->GetControl (
                                 SerialIo,
                                 &Control
                                 );
            if (!EFI_ERROR (Status)) {
              if (ReadUnaligned32 (&FlowControl->FlowControlMap) == UART_FLOW_CONTROL_HARDWARE) {
                Control |= EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE;
              } else {
                Control &= ~EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE;
              }
              //
              // Clear bits that are not allowed to be passed to SetControl
              //
              Control &= (EFI_SERIAL_REQUEST_TO_SEND | 
                          EFI_SERIAL_DATA_TERMINAL_READY |
                          EFI_SERIAL_HARDWARE_LOOPBACK_ENABLE |
                          EFI_SERIAL_SOFTWARE_LOOPBACK_ENABLE |
                          EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE);
              Status = SerialIo->SetControl (SerialIo, Control);
            }
          }
        }
        break;
      }
    }
    FreePool (OpenInfoBuffer);
    return Status;
  }

  if (RemainingDevicePath != NULL) {
    if (IsDevicePathEnd (RemainingDevicePath)) {
      return EFI_SUCCESS;
    }
  }

  UsbSerialDevice->UsbIo = UsbIo;

  //
  // Get interface & endpoint descriptor
  //
  UsbIo->UsbGetInterfaceDescriptor (
           UsbIo,
           &UsbSerialDevice->InterfaceDescriptor
           );

  EndpointNumber = UsbSerialDevice->InterfaceDescriptor.NumEndpoints;

  //
  // Traverse endpoints to find the IN and OUT endpoints that will send and
  // receive data.
  //
  FoundIn = FALSE;
  FoundOut = FALSE;
  for (Index = 0; Index < EndpointNumber; Index++) {

    Status = UsbIo->UsbGetEndpointDescriptor (
                      UsbIo,
                      Index,
                      &EndpointDescriptor
                      );
    if (EFI_ERROR (Status)) {
      return Status;
    }

    if (EndpointDescriptor.EndpointAddress == FTDI_ENDPOINT_ADDRESS_OUT) {
      //
      // Set the Out endpoint device
      //
      CopyMem (
        &UsbSerialDevice->OutEndpointDescriptor,
        &EndpointDescriptor,
        sizeof(EndpointDescriptor)
        );
      FoundOut = TRUE;
    }

    if (EndpointDescriptor.EndpointAddress == FTDI_ENDPOINT_ADDRESS_IN) {
      //
      // Set the In endpoint device
      //
      CopyMem (
        &UsbSerialDevice->InEndpointDescriptor,
        &EndpointDescriptor,
        sizeof(EndpointDescriptor)
        );
      FoundIn = TRUE;
    }
  }

  if (!FoundIn || !FoundOut) {
    //
    // No interrupt endpoint found, then return unsupported.
    //
    Status = EFI_UNSUPPORTED;
    goto ErrorExit;
  }
  //
  // set the initial values of UsbSerialDevice->LastSettings to the default
  // values
  //
  UsbSerialDevice->LastSettings.BaudRate         = 115200;
  UsbSerialDevice->LastSettings.DataBits         = 8;
  UsbSerialDevice->LastSettings.Parity           = NoParity;
  UsbSerialDevice->LastSettings.ReceiveFifoDepth = FTDI_MAX_RECEIVE_FIFO_DEPTH;
  UsbSerialDevice->LastSettings.StopBits         = OneStopBit;
  UsbSerialDevice->LastSettings.Timeout          = FTDI_TIMEOUT;

  //
  // set the initial values of UsbSerialDevice->ControlValues
  //
  UsbSerialDevice->ControlValues.DtrState            = FALSE;
  UsbSerialDevice->ControlValues.RtsState            = FALSE;
  UsbSerialDevice->ControlValues.HardwareFlowControl = FALSE;
  UsbSerialDevice->ControlValues.HardwareLoopBack    = FALSE;
  UsbSerialDevice->ControlValues.SoftwareLoopBack    = FALSE;

  //
  // set the values of UsbSerialDevice->UartDevicePath
  //
  UsbSerialDevice->UartDevicePath.Header.Type    = MESSAGING_DEVICE_PATH;
  UsbSerialDevice->UartDevicePath.Header.SubType = MSG_UART_DP;
  UsbSerialDevice->UartDevicePath.Header.Length[0] = (UINT8) (sizeof (UART_DEVICE_PATH));
  UsbSerialDevice->UartDevicePath.Header.Length[1] = (UINT8) ((sizeof (UART_DEVICE_PATH)) >> 8);

  //
  // set the values of UsbSerialDevice->FlowControlDevicePath
  UsbSerialDevice->FlowControlDevicePath.Header.Type = MESSAGING_DEVICE_PATH;
  UsbSerialDevice->FlowControlDevicePath.Header.SubType = MSG_VENDOR_DP;
  UsbSerialDevice->FlowControlDevicePath.Header.Length[0] = (UINT8) (sizeof (UART_FLOW_CONTROL_DEVICE_PATH));
  UsbSerialDevice->FlowControlDevicePath.Header.Length[1] = (UINT8) ((sizeof (UART_FLOW_CONTROL_DEVICE_PATH)) >> 8);
  UsbSerialDevice->FlowControlDevicePath.FlowControlMap = 0;

  Status = SetAttributesInternal (
             UsbSerialDevice, 
             UsbSerialDevice->LastSettings.BaudRate,
             UsbSerialDevice->LastSettings.ReceiveFifoDepth, 
             UsbSerialDevice->LastSettings.Timeout,
             UsbSerialDevice->LastSettings.Parity, 
             UsbSerialDevice->LastSettings.DataBits,
             UsbSerialDevice->LastSettings.StopBits
             );

  ASSERT_EFI_ERROR (Status);

  Status = SetControlBitsInternal (
             UsbSerialDevice,
             &(UsbSerialDevice->ControlValues)
             );

  ASSERT_EFI_ERROR (Status);

  //
  // Publish Serial GUID and protocol
  //

  UsbSerialDevice->Signature              = USB_SER_DEV_SIGNATURE;
  UsbSerialDevice->SerialIo.Reset         = SerialReset;
  UsbSerialDevice->SerialIo.SetControl    = SetControlBits;
  UsbSerialDevice->SerialIo.SetAttributes = SetAttributes;
  UsbSerialDevice->SerialIo.GetControl    = GetControlBits;
  UsbSerialDevice->SerialIo.Read          = ReadSerialIo;
  UsbSerialDevice->SerialIo.Write         = WriteSerialIo;

  //
  // Set the static Serial IO modes that will display when running
  // "sermode" within the UEFI shell.
  //

  UsbSerialDevice->SerialIo.Mode->Timeout  = 0;
  UsbSerialDevice->SerialIo.Mode->BaudRate = 115200;
  UsbSerialDevice->SerialIo.Mode->DataBits = 8;
  UsbSerialDevice->SerialIo.Mode->Parity   = 1;
  UsbSerialDevice->SerialIo.Mode->StopBits = 1;

  UsbSerialDevice->ParentDevicePath = ParentDevicePath;
  UsbSerialDevice->ControllerHandle = NULL;
  FlowControl                       = NULL;

  //
  // Allocate space for the receive buffer
  //
  UsbSerialDevice->DataBuffer = AllocateZeroPool (SW_FIFO_DEPTH);

  //
  // Initialize data buffer pointers.
  // Head==Tail = true means buffer is empty.
  //
  UsbSerialDevice->DataBufferHead = 0;
  UsbSerialDevice->DataBufferTail = 0;

  UsbSerialDevice->ControllerNameTable = NULL;
  AddUnicodeString2 (
    "eng",
    gUsbSerialComponentName.SupportedLanguages,
    &UsbSerialDevice->ControllerNameTable,
    L"FTDI USB Serial Adapter",
    TRUE
    );
  AddUnicodeString2 (
    "en",
    gUsbSerialComponentName2.SupportedLanguages,
    &UsbSerialDevice->ControllerNameTable,
    L"FTDI USB Serial Adapter",
    FALSE
    );

  Status = SetInitialStatus (UsbSerialDevice);
  ASSERT_EFI_ERROR (Status);

  //
  // Create a polling loop to check for input
  //

  gBS->CreateEvent (
         EVT_TIMER | EVT_NOTIFY_SIGNAL,
         TPL_CALLBACK,
         UsbSerialDriverCheckInput,
         UsbSerialDevice,
         &(UsbSerialDevice->PollingLoop)
         );
  //
  // add code to set trigger time based on baud rate
  // setting to 0.5s for now
  //
  gBS->SetTimer (
         UsbSerialDevice->PollingLoop,
         TimerPeriodic,
         EFI_TIMER_PERIOD_MILLISECONDS (500)
         );

  //
  // Check if the remaining device path is null. If it is not null change the settings
  // of the device to match those on the device path
  //
  if (RemainingDevicePath != NULL) {
    CopyMem (
      &UsbSerialDevice->UartDevicePath,
      RemainingDevicePath,
      sizeof (UART_DEVICE_PATH)
      );
    FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (RemainingDevicePath);
    if (IsUartFlowControlNode (FlowControl)) {
      UsbSerialDevice->FlowControlDevicePath.FlowControlMap = ReadUnaligned32 (&FlowControl->FlowControlMap);
    } else {
      FlowControl = NULL;
    }
  }

  //
  // Build the device path by appending the UART node to the parent device path
  //
  UsbSerialDevice->DevicePath = AppendDevicePathNode (
                                  ParentDevicePath,
                                  (EFI_DEVICE_PATH_PROTOCOL *) &UsbSerialDevice->UartDevicePath
                                  );
  //
  // Continue building the device path by appending the flow control node
  //
  TempDevicePath = UsbSerialDevice->DevicePath;
  UsbSerialDevice->DevicePath = AppendDevicePathNode (
                                  TempDevicePath,
                                  (EFI_DEVICE_PATH_PROTOCOL *) &UsbSerialDevice->FlowControlDevicePath
                                  );
  FreePool (TempDevicePath);

  if (UsbSerialDevice->DevicePath == NULL) {
    Status = EFI_OUT_OF_RESOURCES;
    goto ErrorExit;
  }

  //
  // Install protocol interfaces for the device
  //
  Status = gBS->InstallMultipleProtocolInterfaces (
                  &UsbSerialDevice->ControllerHandle,
                  &gEfiDevicePathProtocolGuid,
                  UsbSerialDevice->DevicePath,
                  &gEfiSerialIoProtocolGuid,
                  &UsbSerialDevice->SerialIo,
                  NULL
                  );
  if (EFI_ERROR (Status)){
    goto ErrorExit;
  }

  //
  // Open for child device
  //
  Status = gBS->OpenProtocol (
                 Controller,
                 &gEfiUsbIoProtocolGuid,
                 (VOID **) &UsbIo,
                 This->DriverBindingHandle,
                 UsbSerialDevice->ControllerHandle,
                 EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
                 );

  UsbSerialDevice->Shutdown = FALSE;

  return EFI_SUCCESS;

ErrorExit:
  //
  // Error handler
  //

  Status = gBS->UninstallMultipleProtocolInterfaces (
                  Controller,
                  &gEfiSerialIoProtocolGuid,
                  &UsbSerialDevice->SerialIo,
                  NULL
                  );
  if (EFI_ERROR (Status)) {
    goto ErrorExit1;
  }

  FreePool (UsbSerialDevice->DataBuffer);
  FreePool (UsbSerialDevice);

  UsbSerialDevice = NULL;
  gBS->CloseProtocol (
         Controller,
         &gEfiUsbIoProtocolGuid,
         This->DriverBindingHandle,
         Controller
         );

ErrorExit1:
  return Status;
}

/**
  Stop the USB Serial device handled by this driver.

  @param  This[in]                   The USB Serial driver binding protocol.
  @param  Controller[in]             The controller to release.
  @param  NumberOfChildren[in]       The number of handles in ChildHandleBuffer.
  @param  ChildHandleBuffer[in]      The array of child handle.

  @retval EFI_SUCCESS                The device was stopped.
  @retval EFI_UNSUPPORTED            Serial IO Protocol is not installed on
                                     Controller.
  @retval EFI_DEVICE_ERROR           The device could not be stopped due to a
                                     device error.
  @retval Others                     Fail to uninstall protocols attached on the
                                     device.

**/
EFI_STATUS
EFIAPI
UsbSerialDriverBindingStop (
  IN  EFI_DRIVER_BINDING_PROTOCOL  *This,
  IN  EFI_HANDLE                   Controller,
  IN  UINTN                        NumberOfChildren,
  IN  EFI_HANDLE                   *ChildHandleBuffer
  )
{
  EFI_STATUS                Status;
  EFI_SERIAL_IO_PROTOCOL    *SerialIo;
  EFI_USB_IO_PROTOCOL       *UsbIo;
  USB_SER_DEV               *UsbSerialDevice;
  UINTN                     Index;
  BOOLEAN                   AllChildrenStopped;

  Status = EFI_SUCCESS;
  UsbSerialDevice = NULL;

  if (NumberOfChildren == 0) {
    //
    // Close the driver
    //
    Status = gBS->CloseProtocol (
                    Controller,
                    &gEfiUsbIoProtocolGuid,
                    This->DriverBindingHandle,
                    Controller
                    );
    Status = gBS->CloseProtocol (
                    Controller,
                    &gEfiDevicePathProtocolGuid,
                    This->DriverBindingHandle,
                    Controller
                    );
    return Status;
  }

  AllChildrenStopped = TRUE;

  for (Index = 0; Index < NumberOfChildren ;Index++) {
    Status = gBS->OpenProtocol (
                    ChildHandleBuffer[Index],
                    &gEfiSerialIoProtocolGuid,
                    (VOID **) &SerialIo,
                    This->DriverBindingHandle,
                    Controller,
                    EFI_OPEN_PROTOCOL_GET_PROTOCOL
                    );
    if (Status == EFI_SUCCESS) {//!EFI_ERROR (Status)) {
      UsbSerialDevice = USB_SER_DEV_FROM_THIS (SerialIo);
      Status = gBS->CloseProtocol (
                      Controller,
                      &gEfiUsbIoProtocolGuid,
                      This->DriverBindingHandle,
                      ChildHandleBuffer[Index]
                      );
      Status = gBS->UninstallMultipleProtocolInterfaces (
                      ChildHandleBuffer[Index],
                      &gEfiDevicePathProtocolGuid,
                      UsbSerialDevice->DevicePath,
                      &gEfiSerialIoProtocolGuid,
                      &UsbSerialDevice->SerialIo,
                      NULL
                      );

      if (EFI_ERROR (Status)) {
        gBS->OpenProtocol (
               Controller,
               &gEfiUsbIoProtocolGuid,
               (VOID **) &UsbIo,
               This->DriverBindingHandle,
               ChildHandleBuffer[Index],
               EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
               );
      } else {
        if (UsbSerialDevice->DevicePath != NULL) {
          gBS->FreePool (UsbSerialDevice->DevicePath);
        }
        gBS->SetTimer (
               UsbSerialDevice->PollingLoop,
               TimerCancel,
               0
               );
        gBS->CloseEvent (UsbSerialDevice->PollingLoop);
        UsbSerialDevice->Shutdown = TRUE;
        FreeUnicodeStringTable (UsbSerialDevice->ControllerNameTable);
        FreePool (UsbSerialDevice->DataBuffer);
        FreePool (UsbSerialDevice);
      }
    }
    if (EFI_ERROR (Status)) {
      AllChildrenStopped = FALSE;
    }
  }

  if (!AllChildrenStopped) {
    return EFI_DEVICE_ERROR;
  }
  return EFI_SUCCESS;
}

//
// Serial IO Member Functions
//

/**
  Reset the serial device.

  @param  This[in]              Protocol instance pointer.

  @retval EFI_SUCCESS           The device was reset.
  @retval EFI_DEVICE_ERROR      The serial device could not be reset.

**/
EFI_STATUS
EFIAPI
SerialReset (
  IN EFI_SERIAL_IO_PROTOCOL  *This
  )
{
  EFI_STATUS    Status;
  USB_SER_DEV  *UsbSerialDevice;

  UsbSerialDevice = USB_SER_DEV_FROM_THIS (This);
  Status          = ResetInternal (UsbSerialDevice);
  if (EFI_ERROR (Status)){
    return EFI_DEVICE_ERROR;
  }
  return Status;
}

/**
  Set the control bits on a serial device.

  @param  This[in]             Protocol instance pointer.
  @param  Control[in]          Set the bits of Control that are settable.

  @retval EFI_SUCCESS          The new control bits were set on the serial device.
  @retval EFI_UNSUPPORTED      The serial device does not support this operation.
  @retval EFI_DEVICE_ERROR     The serial device is not functioning correctly.

**/
EFI_STATUS
EFIAPI
SetControlBits (
  IN EFI_SERIAL_IO_PROTOCOL  *This,
  IN UINT32                  Control
  )
{
  EFI_STATUS    Status;
  USB_SER_DEV   *UsbSerialDevice;
  CONTROL_BITS  ControlBits;
  
  UsbSerialDevice = USB_SER_DEV_FROM_THIS (This);
  
  //
  // check for invalid control parameters 
  //
  if ((Control & (~(EFI_SERIAL_REQUEST_TO_SEND          |
                    EFI_SERIAL_DATA_TERMINAL_READY      |
                    EFI_SERIAL_HARDWARE_LOOPBACK_ENABLE |
                    EFI_SERIAL_SOFTWARE_LOOPBACK_ENABLE |
                    EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE))) != 0 ) {
    return EFI_UNSUPPORTED;
  }

  //
  // check the control parameters and set the correct setting for
  // the paramerts of ControlBits
  // both loopback enables are always set to FALSE
  //
  ControlBits.HardwareLoopBack = FALSE;
  ControlBits.SoftwareLoopBack = FALSE;
  //
  // check for hardware flow control
  //
  if ((Control & EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE) == EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE) {
    ControlBits.HardwareFlowControl = TRUE;
  } else {
    ControlBits.HardwareFlowControl = FALSE;
  }
  //
  // check for DTR enabled
  //
  if ((Control & EFI_SERIAL_DATA_TERMINAL_READY) == EFI_SERIAL_DATA_TERMINAL_READY) {
    ControlBits.DtrState = TRUE;
  } else {
    ControlBits.DtrState = FALSE;
  }
  //
  // check for RTS enabled
  //
  if ((Control & EFI_SERIAL_REQUEST_TO_SEND) == EFI_SERIAL_REQUEST_TO_SEND) {
    ControlBits.RtsState = TRUE;
  } else {
    ControlBits.RtsState = FALSE;
  }

  //
  // set the control values with a call to SetControlBitsInternal()
  //
  Status = SetControlBitsInternal (UsbSerialDevice, &ControlBits);

  return Status;
}

/**
  calls SetAttributesInternal() to set the baud rate, receive FIFO depth,
  transmit/receive time out, parity, data buts, and stop bits on a serial
  device.

  @param  This[in]             Protocol instance pointer.
  @param  BaudRate[in]         The requested baud rate. A BaudRate value of 0
                               will use the device's default interface speed.
  @param  ReveiveFifoDepth[in] The requested depth of the FIFO on the receive
                               side of the serial interface. A ReceiveFifoDepth
                               value of 0 will use the device's default FIFO
                               depth.
  @param  Timeout[in]          The requested time out for a single character in
                               microseconds.This timeout applies to both the
                               transmit and receive side of the interface. A
                               Timeout value of 0 will use the device's default
                               time out value.
  @param  Parity[in]           The type of parity to use on this serial device.
                               A Parity value of DefaultParity will use the
                               device's default parity value.
  @param  DataBits[in]         The number of data bits to use on the serial
                               device. A DataBit vaule of 0 will use the
                               device's default data bit setting.
  @param  StopBits[in]         The number of stop bits to use on this serial
                               device. A StopBits value of DefaultStopBits will
                               use the device's default number of stop bits.

  @retval EFI_SUCCESS          The attributes were set
  @retval EFI_DEVICE_ERROR     The attributes were not able to be

**/
EFI_STATUS
EFIAPI
SetAttributes (
  IN EFI_SERIAL_IO_PROTOCOL  *This,
  IN UINT64                  BaudRate,
  IN UINT32                  ReceiveFifoDepth,
  IN UINT32                  Timeout,
  IN EFI_PARITY_TYPE         Parity,
  IN UINT8                   DataBits,
  IN EFI_STOP_BITS_TYPE      StopBits
  )
{

  EFI_STATUS   Status;
  USB_SER_DEV  *UsbSerialDevice;

  UsbSerialDevice = USB_SER_DEV_FROM_THIS (This);

  Status = SetAttributesInternal (
             UsbSerialDevice,
             BaudRate,
             ReceiveFifoDepth,
             Timeout,
             Parity,
             DataBits,
             StopBits
             );
  if (EFI_ERROR (Status)) {
    return Status;
  }

  return Status;
}


/**
  Retrieves the status of the control bits on a serial device.

  @param  This[in]               Protocol instance pointer.
  @param  Control[out]           A pointer to return the current Control signals
                                 from the serial device.

  @retval EFI_SUCCESS            The control bits were read from the serial
                                 device.
  @retval EFI_DEVICE_ERROR       The serial device is not functioning correctly.

**/
EFI_STATUS
EFIAPI
GetControlBits (
  IN EFI_SERIAL_IO_PROTOCOL  *This,
  OUT UINT32                 *Control
  )
{
  USB_SER_DEV  *UsbSerialDevice;
  EFI_STATUS   Status;

  UsbSerialDevice = USB_SER_DEV_FROM_THIS (This);

  *Control        = 0;

  Status = GetControlBitsInternal (UsbSerialDevice, Control);

  if (EFI_ERROR (Status)) {
    return EFI_DEVICE_ERROR;
  }
  return Status;
}

/**
  Reads data from a serial device.

  @param  This[in]                   Protocol instance pointer.
  @param  BufferSize[in, out]        On input, the size of the Buffer. On output,
                                     the amount of data returned in Buffer.
  @param  Buffer[out]                The buffer to return the data into.

  @retval EFI_SUCCESS                The data was read.
  @retval EFI_DEVICE_ERROR           The device reported an error.
  @retval EFI_TIMEOUT                The data write was stopped due to a timeout.

**/
EFI_STATUS
EFIAPI
ReadSerialIo (
  IN EFI_SERIAL_IO_PROTOCOL  *This,
  IN OUT UINTN               *BufferSize,
  OUT VOID                   *Buffer
  )
{
  UINTN        Index;
  UINTN        RemainingCallerBufferSize;
  USB_SER_DEV  *UsbSerialDevice;
  EFI_STATUS   Status;


  if (*BufferSize == 0) {
    return EFI_SUCCESS;
  }

  if (Buffer == NULL) {
    return EFI_DEVICE_ERROR;
  }

  Status          = EFI_SUCCESS;
  UsbSerialDevice = USB_SER_DEV_FROM_THIS (This);

  //
  // Clear out any data that we already have in our internal buffer
  //
  for (Index = 0; Index < *BufferSize; Index++) {
    if (UsbSerialDevice->DataBufferHead == UsbSerialDevice->DataBufferTail) {
      break;
    }

    //
    // Still have characters in the buffer to return
    //
    ((UINT8 *)Buffer)[Index] = UsbSerialDevice->DataBuffer[UsbSerialDevice->DataBufferHead];
    UsbSerialDevice->DataBufferHead = (UsbSerialDevice->DataBufferHead + 1) % SW_FIFO_DEPTH;
  }

  //
  // If we haven't filled the caller's buffer using data that we already had on
  // hand We need to generate an additional USB request to try and fill the
  // caller's buffer
  //
  if (Index != *BufferSize) {
    RemainingCallerBufferSize = *BufferSize - Index;
    Status = ReadDataFromUsb (
               UsbSerialDevice,
               &RemainingCallerBufferSize,
               (VOID *)(((CHAR8 *)Buffer) + Index)
               );
    if (!EFI_ERROR (Status)) {
      *BufferSize = RemainingCallerBufferSize + Index;
    } else {
      *BufferSize = Index;
    }
  }

  if (UsbSerialDevice->DataBufferHead == UsbSerialDevice->DataBufferTail) {
    //
    // Data buffer has no data, set the EFI_SERIAL_INPUT_BUFFER_EMPTY flag
    //
    UsbSerialDevice->ControlBits |= EFI_SERIAL_INPUT_BUFFER_EMPTY;
  } else {
    //
    // There is some leftover data, clear EFI_SERIAL_INPUT_BUFFER_EMPTY flag
    //
    UsbSerialDevice->ControlBits &= ~(EFI_SERIAL_INPUT_BUFFER_EMPTY);
  }
  return Status;
}

/**
  Writes data to a serial device.

  @param  This[in]                   Protocol instance pointer.
  @param  BufferSize[in, out]        On input, the size of the Buffer. On output,
                                     the amount of data actually written.
  @param  Buffer[in]                 The buffer of data to write

  @retval EFI_SUCCESS                The data was written.
  @retval EFI_DEVICE_ERROR           The device reported an error.
  @retval EFI_TIMEOUT                The data write was stopped due to a timeout.

**/
EFI_STATUS
EFIAPI
WriteSerialIo (
  IN EFI_SERIAL_IO_PROTOCOL  *This,
  IN OUT UINTN               *BufferSize,
  IN VOID                    *Buffer
  )
{
  EFI_STATUS   Status;
  USB_SER_DEV  *UsbSerialDevice;
  EFI_TPL      Tpl;

  UsbSerialDevice = USB_SER_DEV_FROM_THIS (This);

  if (UsbSerialDevice->Shutdown) {
    return EFI_DEVICE_ERROR;
  }

  Tpl = gBS->RaiseTPL (TPL_NOTIFY);

  Status = UsbSerialDataTransfer (
             UsbSerialDevice,
             EfiUsbDataOut,
             Buffer,
             BufferSize,
             FTDI_TIMEOUT
             );

  gBS->RestoreTPL (Tpl);
  if (EFI_ERROR (Status)) {
    if (Status == EFI_TIMEOUT){
      return Status;
    } else {
      return EFI_DEVICE_ERROR;
    }
  }

  return EFI_SUCCESS;
}