summaryrefslogtreecommitdiff
path: root/Core/EM/usb/rt/usbCCID.c
blob: c5bac503da3f36b3d69e3cf1eb8be008b287af93 (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
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
//****************************************************************************
//****************************************************************************
//**                                                                        **
//**             (C)Copyright 1985-2016, American Megatrends, Inc.          **
//**                                                                        **
//**                          All Rights Reserved.                          **
//**                                                                        **
//**                 5555 Oakbrook Pkwy, Norcross, GA 30093                 **
//**                                                                        **
//**                          Phone (770)-246-8600                          **
//**                                                                        **
//****************************************************************************
//****************************************************************************

//****************************************************************************
// $Header: /Alaska/SOURCE/Modules/USB/ALASKA/RT/usbCCID.c 19    10/16/16 10:12p Wilsonlee $
//
// $Revision: 19 $
//
// $Date: 10/16/16 10:12p $
//****************************************************************************
//****************************************************************************
// Revision History
// ----------------
//
// $Log: /Alaska/SOURCE/Modules/USB/ALASKA/RT/usbCCID.c $
// 
// 19    10/16/16 10:12p Wilsonlee
// [TAG]  		EIP288158
// [Category]  	Improvement
// [Description]  	Check if gUsbData is integrity.
// [Files]  		amiusb.cif, usbsb.c, AmiUsbLib.cif, AmiUsbLib.sdl,
// AmiUsbSmmGlobalDataValidationLib.c,
// AmiUsbSmmGlobalDataValidationLib.cif,
// AmiUsbSmmGlobalDataValidationLib.mak, Crc32.c, amiusb.c, amiusb.h,
// ehci.c, elib.c, ohci.c, syskbc.c, uhci.c, usb.c, usbCCID.c, usbdef.h,
// usbhid.c, usbhub.c, usbkbd.c, usbmass.c, usbms.c, usbrt.mak, xhci.c,
// amiusbhc.c, efiusbccid.c, efiusbmass.c, uhcd.c, usbmisc.c,
// AmiUsbController.h, AmiUsbLibInclude.cif,
// AmiUsbSmmGlobalDataValidationLib.h
// 
// 18    7/07/16 1:09a Wilsonlee
// [TAG]  		EIP277810
// [Category]  	Improvement
// [Description]  	Validate the memory buffer is entirely outside of SMM.
// [Files]  		usbsb.c, amiusb.c, ehci.c, ohci.c, uhci.c, usbCCID.c,
// usbdef.h, usbmass.c, xhci.c, amiusbhc.c, efiusbccid.c, efiusbmass.c,
// uhcd.c, uhcd.h, usbmisc.c
// 
// 17    3/02/16 9:41p Wilsonlee
// [TAG]  		EIP254309
// [Category]  	Bug Fix
// [Severity]  	Normal
// [Symptom]  	GK-FORCE K83 USB KB function abnormal.
// [RootCause]  	This device has an interrupt out endpoint and doesn't
// support "Set Report" request.
// [Solution]  	Use the interrupt out endpoint instead of sending "Set
// Report" request.
// [Files]  		AmiUsbController.h, xhci.c, usbmass.c, usbkbd.h, usbkbd.c,
// usbhub.c, usbhid.c, usbdef.h, usbCCID.c, usb.c, uhci.c, ohci.c, ehci.c,
// amiusb.h, efiusbms,c, amiusbhc.c
// 
// 16    4/10/15 3:10a Wilsonlee
// [TAG]  		EIP207413
// [Category]  	Improvement
// [Description]  	Install UsbApiTable and UsbMassApitTable in
// AmiUsbSmmProtocol.
// [Files]  		amiusbhc.c, AmiUsbController.h, usbdef.h, usbCCID.c, uhci.c,
// ehci.c, amiusbrtCCID.h, amiusb.h, amiusb.c, uhcd.c
// 
// 15    3/05/15 3:54a Wilsonlee
// [TAG]  		EIP203888
// [Category]  	Improvement
// [Description]  	RateAndProtocolManagement() default return changed from
// EFI_DEVICE_ERROR to EFI_SUCCESS.
// [Files]  		usbCCID.c
// 
// 14    2/16/15 2:45a Wilsonlee
// [TAG]  		EIP205373
// [Category]  	Improvement
// [Description]  	Cppcheck errors in Usb module.
// [Files]  		usb.c, usbport.c, uhcd.c, usbCCID.c
// 
// 13    6/26/14 1:16a Wilsonlee
// [TAG]  		EIP173387
// [Category]  	Improvement
// [Description]  	Remove TODO comments.
// [Files]  		usbsetup.c, xhci.c, usbmass.c, usbCCID.c, usb.c, uhci.c,
// syskbc.c, usbport.c, usbbus.c, uhcd.c, UsbBotPeim.c, PeiXhci.c,
// PeiEhci.c
// 
// 12    4/30/14 6:14a Ryanchou
// [TAG]  		EIP151374
// [Category]  	Improvement
// [Description]  	Calculates maximum data length to be reported in the
// HID device.
// [Files]  		ehci.c, ohci.c, uhci.c, usbCCID.c, usbdef.h, usbhid.c,
// usbhub.c, xhci.c
// 
// 11    2/26/14 1:55a Wilsonlee
// [TAG]  		EIP149854
// [Category]  	Improvement
// [Description]  	Add data length parameter to polling callback function.
// [Files]  		usbkbd.c, uhci.c, usb.c, usbhub.c, usbCCID.c, usbms.c,
// usbhid.c, usbpoint.c, usbkbd.h, ehci.c, ohci.c, xhci.c, usbdef.h
// 
// 10    2/11/14 11:47p Rameshr
// [TAG]  		EIP152203
// [Category]  	Improvement
// [Description]  	Hardcoded value for bProtocolNum removed.
// [Files]  		usbCCID.c
// 
// 9     6/20/13 10:22p Wilsonlee
// [TAG]  		EIP126814
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Security code check fail in the function
// USBAPI_CCIDRequest() in usbCCID.c.
// [RootCause]  	The function USBAPI_CCIDRequest() in usbCCID.c reads data
// from just outside the bounds of aUsbCCIDApiTable.
// [Solution]  	Condition is fixed from ">" to ">=".
// [Files]  		usbCCID.c
// 
// 8     4/02/13 7:54a Rameshr
// [TAG]  		EIP119028
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Insert smart card incorrectly (backwards), system will hang
// 0xA0 . 
// [RootCause]  	Invalid Status returned
// [Solution]  	Add a check whether ATR data is successfully read and
// processed, If not return error
// 
// 7     3/19/13 3:59a Ryanchou
// [TAG]  		EIP118177
// [Category]  	Improvement
// [Description]  	Dynamically allocate HCStrucTable at runtime.
// [Files]  		usb.sdl, usbport.c, usbsb.c, amiusb.c, ehci.c, ohci.c,
// syskbc.c, sysnokbc.c, uhci.c, usb.c, usbCCID.c, usbdef.h, usbhid.c,
// usbhub.c, usbmass.c, usbrt.mak, usb.sd, amiusbhc.c, efiusbccid.c,
// efiusbhid.c, efiusbmass.c, efiusbms.c, uhcd.c, uhcd.h, uhcd.mak,
// usbmisc.c, usbsrc.sdl
// 
// 6     1/23/13 4:36a Wilsonlee
// [TAG]  		EIP109538
// [Category]  	Improvement
// [Description]  	Fix the code check error result.
// [Files]  		usbkbd.c, usbCCID.c, usbbus.c, efiusbccid.c
// 
// 5     11/10/12 6:39a Ryanchou
// [TAG]  		EIP99431
// [Category]  	Bug Fix
// [Severity]  	Minor
// [Symptom]  	Cannot use the UsbIo's UsbAsyncInterruptTransfer for
// keyboard input
// [RootCause]  	Stopping EFI USB keyboard driver does not stop the
// endpoint polling, then application calls UsbAsyncInterruptTransfer,
// error will be returned.
// [Solution]  	Stops endpoint polling and release resource when
// disconnecting the device driver. And improve the
// UsbSyncInterruptTransfer.
// [Files]  		amiusb.c, amiusb.h, ehci.c, ohci.c, uhci.c, usb.c,
// usbCCID.c, usbdef.h, usbhub.c, usbkbd.c, usbmass.c, usbms.c,
// usbpoint.c, amiusbhc.c, efiusbhid.c, usbbus.c, usbbus.h
// 
// 4     9/28/12 2:38a Wilsonlee
// [TAG]  		EIP93154
// [Category]  	Improvement
// [Description]  	Change the unit of the FixedDelay from 15 us to 1 us.
// [Files]  		amiusb.h, xhci.c, ehci.c, ohci.c, uhci.c, usb.c, usbCCID.c,
// usbmass.c, usbhub.c, elib.c
// 
// 3     5/02/12 1:55a Rajeshms
// [TAG]  		EIP83117 
// [Category]  	Improvement
// [Description]  	Extend the Support to different smart card Readers and
// smart Cards.
// [Files]  		usbCCID.c, amiusbrtCCID.h, usbdef.h, efiusbccid.c,
// AmiusbCCID.h
// 
// 2     9/22/11 1:24a Rajeshms
// [TAG]  		EIP67832
// [Category]  	Bug Fix
// [Severity]  	Important
// [Symptom]  	When ICC(Smart Card) is unplugged and inserted again , it
// is not detected.
// [RootCause]  	The ChildHandle for the smart card where protocol is
// installed is not made to zero when it was unplugged.
// [Solution]  	The ChilHandle is changed to zero when smart card is
// unplugged.
// [Files]  		usbCCID.c
// 
// 1     7/12/11 8:04a Ryanchou
// [TAG]  		EIP56918
// [Category]  	New Feature
// [Description]  	Added CCID device support.
// [Files]  		amiusb.c, amiusb.h, amiusbrtCCID.h, ehci.c, ohci.c, uhci.c,
// usb.c, UsbCCID.c, usbdef.h, usbrt.cif, usbsetup.c, efiusbccid.c,
// framework.cif, uhcd.c, uhcd.cif, uhcd.h, usbsrc.sdl, AmiusbCCID.h,
// AmiUsbController.h, AmiUSBProtocols.cif
// 
//
//****************************************************************************

//<AMI_FHDR_START>
//-----------------------------------------------------------------------------
//
//  Name:           UsbCCID.c
//
//  Description:    AMI USB CCID Device class support driver
//
//-----------------------------------------------------------------------------
//<AMI_FHDR_END>

#include "amidef.h"
#include "usbdef.h"
#include "amiusb.h"
#include "amidxelib.h"
#if USB_RUNTIME_DRIVER_IN_SMM
#include <AmiBufferValidationLib.h>
#endif

extern      USB_GLOBAL_DATA *gUsbData;
extern      BOOLEAN gCheckUsbApiParameter;

UINT8       gSequence = 0;

VOID _FAR_ *
USB_MemAlloc(
    UINT16  wNumBlk
);

UINT8
USB_MemFree (
    VOID _FAR_ * fpPtr,
    UINT16    wNumBlk
);

void    FixedDelay(
    IN UINTN
);

typedef VOID (*API_FUNC)(URP_STRUC*);

extern  UINT8   USB_InstallCallBackFunction (CALLBACK_FUNC  pfnCallBackFunction);

//                      Fi   Max  Di
UINT16 FiFmaxDi[] = {   372,   4, 0, 
                        372,   5, 1, 
                        558,   6, 2,
                        744,   8, 4,
                        1116, 12, 8,
                        1488, 16, 16,
                        1860, 20, 32,
                        0,     0, 64, 
                        0,     0, 12,
                        512,   5, 20,
                        768,   7,  0,
                        1024, 10,  0,
                        1536, 15,  0,
                        2048, 20,  0,
                        0,     0,  0,
                        0,     0,  0
                        };

//<AMI_THDR_START>
//----------------------------------------------------------------------------
// Name:        USBCCIDAPITable - USB CCID API Function Dispatch Table
//
// Type:        Function Dispatch Table
//
// Description: This is the table of functions used by USB CCID API
//
//----------------------------------------------------------------------------
//<AMI_THDR_END>

API_FUNC aUsbCCIDApiTable[] = {

    USBCCIDAPISmartClassDescriptorSMM,  // USB Mass API Sub-Func 00h
    USBCCIDAPIAtrSMM,                   // USB Mass API Sub-Func 01h
    USBCCIDAPIPowerupSlotSMM,           // USB Mass API Sub-Func 02h
    USBCCIDAPIPowerDownSlotSMM,         // USB Mass API Sub-Func 03h
    USBCCIDAPIGetSlotStatusSMM,         // USB Mass API Sub-Func 04h
    USBCCIDAPIXfrBlockSMM,              // USB Mass API Sub-Func 05h
    USBCCIDAPIGetParametersSMM,         // USB Mass API Sub-Func 06h

};
 
//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDFillDriverEntries
//
// Description: This function fills DEV_DRIVER structure
//
// Input:   
//              fpDevDriver    Pointer to the DEV driver 
//
// Output: 
//              None
//
// 
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
USBCCIDFillDriverEntries (
    IN OUT DEV_DRIVER    *fpDevDriver
)
{

    fpDevDriver->bDevType               = BIOS_DEV_TYPE_STORAGE;
    fpDevDriver->bBaseClass             = BASE_CLASS_CCID_STORAGE;
    fpDevDriver->bSubClass              = SUB_CLASS_CCID;
    fpDevDriver->bProtocol              = PROTOCOL_CCID;
    fpDevDriver->bProtocol              = 0;
    fpDevDriver->pfnDeviceInit          = USBCCIDInitialize;
    fpDevDriver->pfnCheckDeviceType     = USBCCIDCheckForDevice;
    fpDevDriver->pfnConfigureDevice     = USBCCIDConfigureDevice;
    fpDevDriver->pfnDisconnectDevice    = USBCCIDDisconnectDevice;

    return;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDAPISmartClassDescriptorSMM
//
// Description: This function is part of the USB BIOS MASS API inside SMM
//
// Input:   
//              fpURPPointer    Pointer to the URP structure
//
// Output: 
//              fpURPPointer    Pointer to the URP structure
//              fpURP->bRetValue USB_SUCESS if data is returned
//
// Notes:       This API returns 36h bytes of SMART Class Descriptor to the caller. 
//              Input Buffer of 36h bytes long is provided by the caller. Caller is 
//              USBCCIDAPISmartClassDescriptor in EfiUsbCCID.C
// 
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBCCIDAPISmartClassDescriptorSMM(
    IN OUT URP_STRUC *Urp
)
{
   
    DEV_INFO        *DevInfo;
    EFI_STATUS      EfiStatus = EFI_SUCCESS;
    UINT8           *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        EfiStatus = AmiValidateMemoryBuffer((VOID*)(Urp->ApiData.CCIDSmartClassDescriptor.fpResponseBuffer), 
                        (UINT32)sizeof(SMARTCLASS_DESC));
        if (EFI_ERROR(EfiStatus)) {
            USB_DEBUG(3, "UsbCcid Invalid Pointer, Buffer is in SMRAM.\n");
            Urp->bRetValue = USB_ERROR;
            return;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    DevInfo = (DEV_INFO *)(Urp->ApiData.CCIDSmartClassDescriptor.fpDevInfo);

    // Check whether it is a valid CCID Device
    if (!DevInfo || !DevInfo->pCCIDDescriptor) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    EfiStatus = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(EfiStatus)) {
        Urp->bRetValue = USB_PARAMETER_ERROR;
        return;
    }

    if (((UINT8*)DevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)DevInfo->pCCIDDescriptor > MemBlockEnd)) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    MemCopy((UINT8 *)DevInfo->pCCIDDescriptor, 
            (UINT8 *)(Urp->ApiData.CCIDSmartClassDescriptor.fpResponseBuffer), 
            (UINT32)sizeof(SMARTCLASS_DESC)
            );

    Urp->bRetValue = USB_SUCCESS;

    return;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDAPIAtrSMM
//
// Description: This function is part of the USB BIOS MASS API inside SMM
//
// Input:   fpURPPointer    Pointer to the URP structure, it contains the following:
//
// Output: fpURPPointer Pointer to the URP structure
//         fpURP->bRetValue : USB_SUCESS if data is returned
//
// Notes:   This API returns ATR data if present
// 
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
USBCCIDAPIAtrSMM (
    IN OUT URP_STRUC *Urp

)
{

    DEV_INFO            *DevInfo;
    ICC_DEVICE          *IccDevice;
    EFI_STATUS          EfiStatus = EFI_SUCCESS;
    UINT8               *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        EfiStatus = AmiValidateMemoryBuffer((VOID*)(Urp->ApiData.CCIDAtr.ATRData), 
                        MAX_ATR_LENGTH);
        if (EFI_ERROR(EfiStatus)) {
            USB_DEBUG(3, "UsbCcid Invalid Pointer, Buffer is in SMRAM.\n");
            Urp->bRetValue = USB_ERROR;
            return;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    DevInfo = (DEV_INFO *)(Urp->ApiData.CCIDAtr.fpDevInfo);
    //
    // Check whether it is a valid CCID Device
    //
    if (!DevInfo || !DevInfo->pCCIDDescriptor) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    EfiStatus = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(EfiStatus)) {
        Urp->bRetValue = USB_PARAMETER_ERROR;
        return;
    }

    if (((UINT8*)DevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)DevInfo->pCCIDDescriptor > MemBlockEnd)) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    Urp->bRetValue = USB_ERROR;

    //
    // Locate the ICCDevice 
    //
    IccDevice = GetICCDevice(DevInfo, Urp->ApiData.CCIDAtr.Slot);

    if (IccDevice) {
        if (IccDevice->ConfiguredStatus & ATRDATAPRESENT) {
            MemCopy((UINT8 *)IccDevice->RawATRData, (UINT8 *)(Urp->ApiData.CCIDAtr.ATRData), MAX_ATR_LENGTH);
            Urp->bRetValue = USB_SUCCESS;
        }
    }

    return;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDAPIPowerupSlotSMM
//
// Description: This function is part of the USB BIOS MASS API inside SMM
//
// Input:       
//              fpURPPointer    Pointer to the URP structure
//
// Output:      
//              fpURPPointer Pointer to the URP structure
//              fpURP->bRetValue : USB_SUCESS if data is returned
//
// Notes:       This API powers up the particular slot in CCID and returns ATR data if successful
// 
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
USBCCIDAPIPowerupSlotSMM (
    IN OUT URP_STRUC *Urp

)
{

    EFI_STATUS          Status;    
    DEV_INFO            *DevInfo;
    ICC_DEVICE          *IccDevice;
    UINT8               *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        Status = AmiValidateMemoryBuffer((VOID*)(Urp->ApiData.CCIDPowerupSlot.ATRData),
                    MAX_ATR_LENGTH);
        if (EFI_ERROR(Status)) {
            USB_DEBUG(3, "UsbCcid Invalid Pointer, Buffer is in SMRAM.\n");
            Urp->bRetValue = USB_ERROR;
            return;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    DevInfo = (DEV_INFO *)(Urp->ApiData.CCIDPowerupSlot.fpDevInfo);

    //
    // Check whether it is a valid CCID Device
    //
    if (!DevInfo || !DevInfo->pCCIDDescriptor) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    Status = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(Status)) {
        Urp->bRetValue = USB_PARAMETER_ERROR;
        return;
    }

    if (((UINT8*)DevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)DevInfo->pCCIDDescriptor > MemBlockEnd)) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    //
    // Locate the ICCDevice 
    //
    IccDevice = GetICCDevice(DevInfo, Urp->ApiData.CCIDPowerupSlot.Slot);

    if (IccDevice) {
        //
        // The slot has been already discovered. Check the status.
        //
        if (IccDevice->ConfiguredStatus & VOLTAGEAPPLIED) {
            //
            // Power down the device
            //
            PCtoRDRIccPowerOff (DevInfo, IccDevice);
            RDRToPCSlotStatus(DevInfo, IccDevice);
        }
    }

    Status = ICCInsertEvent(DevInfo, Urp->ApiData.CCIDPowerupSlot.Slot);

    //
    // If the card has been successfully poweredup copy ATR data
    //
    if (!IccDevice) {
        IccDevice = GetICCDevice(DevInfo, Urp->ApiData.CCIDPowerupSlot.Slot);
        if (!IccDevice) {
            Urp->bRetValue = USB_ERROR;
            return;
        }
    }
    Urp->ApiData.CCIDPowerupSlot.bStatus = IccDevice->bStatus;
    Urp->ApiData.CCIDPowerupSlot.bError = IccDevice->bError;

    if (IccDevice->ConfiguredStatus & ATRDATAPRESENT) {
        MemCopy((UINT8 *)IccDevice->RawATRData, (UINT8 *)(Urp->ApiData.CCIDPowerupSlot.ATRData), MAX_ATR_LENGTH);        
    }

    Urp->bRetValue = USB_SUCCESS;

    if (Status == EFI_DEVICE_ERROR) {
        Urp->bRetValue = USB_ERROR;
    }

    return;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDAPIPowerDownSlotSMM
//
// Description: This function is part of the USB BIOS MASS API inside SMM
//
// Input:   
//              fpURPPointer    Pointer to the URP structure, it contains the following:
//
// Output: 
//              fpURPPointer Pointer to the URP structure
//              fpURP->bRetValue : USB_SUCESS if data is returned
//
// Notes:       This API powers down the particular slot.
// 
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
USBCCIDAPIPowerDownSlotSMM (
    IN OUT URP_STRUC *fpURP

)
{
    
    EFI_STATUS          Status = EFI_SUCCESS;
    DEV_INFO               *fpDevInfo;
    ICC_DEVICE            *fpICCDevice;
    UINT8       *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    fpDevInfo = (DEV_INFO *) (fpURP->ApiData.CCIDPowerdownSlot.fpDevInfo);

    fpURP->bRetValue    = USB_ERROR;

    //
    // Check whether it is a valid CCID Device
    //
    if (!fpDevInfo || !fpDevInfo->pCCIDDescriptor) {

        return;

    }

    Status = UsbDevInfoValidation(fpDevInfo);

    if (EFI_ERROR(Status)) {
        fpURP->bRetValue = USB_PARAMETER_ERROR;
        return;
    }

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        fpURP->bRetValue = USB_ERROR;
        return;
    }

    //
    // Locate the ICCDevice 
    //
    fpICCDevice = GetICCDevice(fpDevInfo, fpURP->ApiData.CCIDPowerdownSlot.Slot);

    if (fpICCDevice) {
        //
        // The slot has been already discovered. Check the status.
        //
        if (fpICCDevice->ConfiguredStatus & ICCPRESENT) {
        
            //
            // Power down the device
            //
            Status = PCtoRDRIccPowerOff (fpDevInfo,  fpICCDevice);
            RDRToPCSlotStatus(fpDevInfo, fpICCDevice);

            fpICCDevice->ConfiguredStatus &= (~VOLTAGEAPPLIED);

            fpURP->ApiData.CCIDPowerdownSlot.bStatus = fpICCDevice->bStatus;
            fpURP->ApiData.CCIDPowerdownSlot.bError = fpICCDevice->bError;

        }
    }

    fpURP->bRetValue    = USB_SUCCESS;

    if (Status == EFI_DEVICE_ERROR){
        fpURP->bRetValue    = USB_ERROR;
    }

    return;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDAPIGetSlotStatusSMM
//
// Description: This function is part of the USB BIOS MASS API inside SMM
//
// Input:   
//              fpURPPointer    Pointer to the URP structure, it contains the following:
//              UINT8           *bStatus;
//              UINT8           *bError;
//
// Output: 
//              fpURPPointer    Pointer to the URP structure
//              bRetValue       Return value
//              bClockStatus    Return Value
//
// Notes:       This API returns information from RDR_to_PC_SlotStatus. 
//              Caller is USBCCIDAPIGetSlotStatus in EfiUsbCCID.C
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBCCIDAPIGetSlotStatusSMM (
    IN OUT URP_STRUC *fpURP
)
{
    
    EFI_STATUS              Status;
    DEV_INFO                *fpDevInfo;
    ICC_DEVICE              *fpICCDevice;
    UINT8       *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    fpDevInfo = (DEV_INFO *) (fpURP->ApiData.CCIDGetSlotStatus.fpDevInfo);

    //
    // Check whether it is a valid CCID Device
    //
    if (!fpDevInfo || !fpDevInfo->pCCIDDescriptor) {

        fpURP->bRetValue    = USB_ERROR;
        return;

    }

    Status = UsbDevInfoValidation(fpDevInfo);

    if (EFI_ERROR(Status)) {
        fpURP->bRetValue = USB_PARAMETER_ERROR;
        return;
    }

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        fpURP->bRetValue = USB_ERROR;
        return;
    }

    //
    // Locate the ICCDevice 
    //
    fpICCDevice = GetICCDevice(fpDevInfo, fpURP->ApiData.CCIDGetSlotStatus.Slot);
    if (!fpICCDevice ||  !(fpICCDevice->ConfiguredStatus & ICCPRESENT)) {

        fpURP->ApiData.CCIDGetSlotStatus.bStatus = 0x42; 
        fpURP->ApiData.CCIDGetSlotStatus.bError = 0xFE;
        fpURP->bRetValue    = USB_ERROR;
        return;

    }
    
    //
    // Issue the cmd
    //
    Status = PCToRDRGetSlotStatus(fpDevInfo, fpICCDevice);

    if (EFI_ERROR(Status)){
        fpURP->bRetValue    = USB_ERROR;
        return;        
    }

    //
    // Get the response
    //
    Status = RDRToPCSlotStatus(fpDevInfo, fpICCDevice);

    fpURP->ApiData.CCIDGetSlotStatus.bStatus = fpICCDevice->bStatus;
    fpURP->ApiData.CCIDGetSlotStatus.bError = fpICCDevice->bError;
    fpURP->ApiData.CCIDGetSlotStatus.bClockStatus = fpICCDevice->bClockStatus;

    fpURP->bRetValue    = USB_SUCCESS;

    if (Status == EFI_DEVICE_ERROR){
        fpURP->bRetValue    = USB_ERROR;
    }

    return;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDAPIXfrBlockSMM
//
// Description: This function is part of the USB BIOS MASS API.
//
// Input:   
//              fpURPPointer    Pointer to the URP structure, it contains the following:
//              IN UINTN        CmdLength
//              IN UINTN        fpCmdBuffer
//              OUT UINT8       bStatus
//              OUT UINT8       bError
//              IN OUT UINTN    ResponseLength - Points to the buffer length of fpResponseBuffer
//              OUT UINTN       fpResponseBuffer
//
// Output: 
//              fpURPPointer    Pointer to the URP structure
//              OUT UINT8       bStatus
//              OUT UINT8       bError
//              IN OUT UINTN    ResponseLength - Points to the actual response bytes in fpResponseBuffer on return
//              OUT UINTN       fpResponseBuffer
//
// Note:        This API excutes PC_to_RDR_XfrBlock cmd and returns the response from 
//              RDR_to_PC_DataBlock to the caller.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBCCIDAPIXfrBlockSMM (
    IN OUT URP_STRUC *Urp
)
{

    EFI_STATUS          Status;
    DEV_INFO            *DevInfo;
    ICC_DEVICE          *IccDevice;
    UINT32              CmdLength = (UINT32)Urp->ApiData.CCIDXfrBlock.CmdLength;
    UINT8               *CmdBuffer = (UINT8 *)Urp->ApiData.CCIDXfrBlock.fpCmdBuffer;
    UINT8               IsBlock = (BOOLEAN)Urp->ApiData.CCIDXfrBlock.ISBlock;
    UINT32              *ResponseLength = (UINT32 *)&(Urp->ApiData.CCIDXfrBlock.ResponseLength);
    UINT8               *ResponseBuffer = (UINT8 *)(Urp->ApiData.CCIDXfrBlock.fpResponseBuffer);
    UINT8       *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        Status = AmiValidateMemoryBuffer((VOID*)(Urp->ApiData.CCIDXfrBlock.fpCmdBuffer),
                    Urp->ApiData.CCIDXfrBlock.CmdLength);
        if (EFI_ERROR(Status)) {
            USB_DEBUG(3, "UsbCcid Invalid Pointer, Buffer is in SMRAM.\n");
            Urp->bRetValue = USB_ERROR;
            return;
        }
        Status = AmiValidateMemoryBuffer((VOID*)(Urp->ApiData.CCIDXfrBlock.fpResponseBuffer),
                    Urp->ApiData.CCIDXfrBlock.ResponseLength);
        if (EFI_ERROR(Status)) {
            USB_DEBUG(3, "UsbCcid Invalid Pointer, Buffer is in SMRAM.\n");
            Urp->bRetValue = USB_ERROR;
            return;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    DevInfo = (DEV_INFO *)(Urp->ApiData.CCIDXfrBlock.fpDevInfo);

    //
    // Check whether it is a valid CCID Device
    //
    if (!DevInfo || !DevInfo->pCCIDDescriptor) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    Status = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(Status)) {
        Urp->bRetValue = USB_PARAMETER_ERROR;
        return;
    }

    if (((UINT8*)DevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)DevInfo->pCCIDDescriptor > MemBlockEnd)) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    //
    // Locate the ICCDevice 
    //
    IccDevice = GetICCDevice(DevInfo, Urp->ApiData.CCIDXfrBlock.Slot);

    if (!IccDevice || !(IccDevice->ConfiguredStatus & ICCPRESENT)) {

        Urp->ApiData.CCIDXfrBlock.bStatus = 0x42; 
        Urp->ApiData.CCIDXfrBlock.bError = 0xFE;
        Urp->bRetValue = USB_ERROR;
        return;
    }


    //
    // Only T0/T1 are recognized
    //
    if (IccDevice->bProtocolNum > 1) {
        Urp->bRetValue = USB_ERROR;        
        return;
    } 

    //
    // Check for T0/T1
    //
    if (IccDevice->bProtocolNum){    
        switch (((SMARTCLASS_DESC*)DevInfo->pCCIDDescriptor)->dwFeatures & 0x70000) {

            case TDPU_LEVEL_EXCHANGE:

                Status = TxRxT1TDPUChar(DevInfo, IccDevice, CmdLength, CmdBuffer, IsBlock, ResponseLength, ResponseBuffer);
                break;

            case CHARACTER_LEVEL_EXCHANGE:

                Status = TxRxT1TDPUChar(DevInfo, IccDevice, CmdLength, CmdBuffer, IsBlock, ResponseLength, ResponseBuffer);
                break;

            case SHORT_ADPU_LEVEL_EXCHANGE:
            case EXT_ADPU_LEVEL_EXCHANGE:
                Status = TxRxT1Adpu(DevInfo, IccDevice, CmdLength, CmdBuffer, ResponseLength, ResponseBuffer);
                break;
        }
    } else {
        // T0 not supported yet
        Urp->bRetValue = USB_ERROR;        
        return;
    }

    Urp->ApiData.CCIDXfrBlock.bStatus = IccDevice->bStatus;
    Urp->ApiData.CCIDXfrBlock.bError = IccDevice->bError;

    Urp->bRetValue = USB_SUCCESS;

    if (Status == EFI_DEVICE_ERROR) {
        Urp->bRetValue = USB_ERROR;
    }

    return;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDAPIGetParametersSMM
//
// Description: This function is part of the USB BIOS MASS API.
//
// Input:   
//              fpURPPointer    Pointer to the URP structure, it contains the following:
//              OUT UINT8       bStatus;
//              OUT UINT8       bError;
//              IN OUT UINTN    ResponseLength;
//              OUT UINTN       fpResponseBuffer;
//              IN  UINT8       Slot;
//              OUT UINTN       fpDevInfo;
//
// Output: 
//              fpURPPointer    Pointer to the URP structure
//              bRetValue       Return value
//
// Notes:       This API returns the response to RDR_to_PCParameters cmd
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBCCIDAPIGetParametersSMM (
    IN OUT URP_STRUC *Urp

)
{
    
    EFI_STATUS              Status;
    DEV_INFO                *DevInfo;
    ICC_DEVICE              *IccDevice;
    UINT8       *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

#if USB_RUNTIME_DRIVER_IN_SMM
    if (gCheckUsbApiParameter) {
        Status = AmiValidateMemoryBuffer((VOID*)(Urp->ApiData.CCIDGetParameters.fpResponseBuffer),
                    Urp->ApiData.CCIDGetParameters.ResponseLength);
        if (EFI_ERROR(Status)) {
            USB_DEBUG(3, "UsbCcid Invalid Pointer, Buffer is in SMRAM.\n");
            Urp->bRetValue = USB_ERROR;
            return;
        }
        gCheckUsbApiParameter = FALSE;
    }
#endif

    DevInfo = (DEV_INFO *)(Urp->ApiData.CCIDGetParameters.fpDevInfo);

    //
    // Check whether it is a valid CCID Device
    //
    if (!DevInfo || !DevInfo->pCCIDDescriptor) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    Status = UsbDevInfoValidation(DevInfo);

    if (EFI_ERROR(Status)) {
        Urp->bRetValue = USB_PARAMETER_ERROR;
        return;
    }

    if (((UINT8*)DevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)DevInfo->pCCIDDescriptor > MemBlockEnd)) {
        Urp->bRetValue = USB_ERROR;
        return;
    }

    //
    // Locate the ICCDevice 
    //
    IccDevice = GetICCDevice(DevInfo, Urp->ApiData.CCIDGetParameters.Slot);
    if (!IccDevice || !(IccDevice->ConfiguredStatus & ICCPRESENT)) {
        Urp->ApiData.CCIDGetParameters.bStatus = 0x42; 
        Urp->ApiData.CCIDGetParameters.bError = 0xFE;
        Urp->bRetValue = USB_ERROR;
        return;
    }

    // Should we check for device presence in data area. The call will find that out anyways.

    //    
    // Issue the cmd
    //
    Status = PCToRDRGetParameters(DevInfo, IccDevice);

    if (EFI_ERROR(Status)){
        Urp->bRetValue = USB_ERROR;
        return;        
    }

    //
    // Get the response
    //
    Status = RDRToPCParameters(DevInfo, IccDevice);
    if (!EFI_ERROR(Status)) {
        Urp->ApiData.CCIDGetParameters.ResponseLength = 6;
        if (IccDevice->bProtocolNum){
            Urp->ApiData.CCIDGetParameters.ResponseLength = 8;
        }
        //
        // Update the Data
        //
        MemCopy((UINT8 *)&(IccDevice->bProtocolNum), 
                (UINT8 *)(Urp->ApiData.CCIDGetParameters.fpResponseBuffer), 
                (UINT32)(Urp->ApiData.CCIDGetParameters.ResponseLength)
                );
    }

    Urp->ApiData.CCIDGetParameters.bStatus = IccDevice->bStatus;
    Urp->ApiData.CCIDGetParameters.bError = IccDevice->bError;

    Urp->bRetValue = USB_SUCCESS;

    if (Status == EFI_DEVICE_ERROR) {
        Urp->bRetValue = USB_ERROR;
    }

    return;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBAPI_CCIDRequest
//
// Description: This routine services the USB API function number 30h.  It
//              handles all the CCID related calls from the higher
//              layer. Different sub-functions are invoked depending on
//              the sub-function number
//
// Input:   
//              fpURPPointer    Pointer to the URP structure
//              fpURPPointer.bSubFunc   Subfunction number
//
// Output:  
//              URP structure is updated with the relevant information
//
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBAPI_CCIDRequest (
    URP_STRUC *fpURP
)
{
    UINT8 bCCIDFuncIndex = fpURP->bSubFunc;
    UINT8 bNumberOfCCIDFunctions = sizeof aUsbCCIDApiTable / sizeof (API_FUNC *);

    //
    // Make sure function number is valid
    //
    if (bCCIDFuncIndex >= bNumberOfCCIDFunctions) {
        //fpURP->bRetValue = USBAPI_INVALID_FUNCTION;
        USB_DEBUG(3, "UsbApi CCIDRequest Invalid function#%x\n", bCCIDFuncIndex);
        return;
    }
    //
    // Function number is valid - call it
    //
    aUsbCCIDApiTable[bCCIDFuncIndex](fpURP);

}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:    PCtoRDRIccPowerOn
//
// Description:  PC_TO_RDR_XFRBLOCK cmd is issued to the device
//
// Input  
//              IN DEV_INFO             *fpDevInfo,
//              IN ICC_DEVICE           *fpICCDevice,
//              IN UINT32               CmdLength,
//              IN UINT8                *CmdBuffer,
//              IN UINT8                BlockWaitingTime,
//              IN UINT16               LevelParameter
//
// Output :     
//              EFI_STATUS
//
// Notes:       This function sends PC_TO_RDR_XFRBLOCK to the device. 
//              See section 6.1.4 of CCID spec 1.1 for the details.
//              CmdBuffer points to abData.
//          
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
PCToRDRXfrBlock (
    IN DEV_INFO             *fpDevInfo,
    IN ICC_DEVICE           *fpICCDevice,
    IN UINT32               CmdLength,
    IN UINT8                *CmdBuffer,
    IN UINT8                BlockWaitingTime,
    IN UINT16               LevelParameter    

)
{

    EFI_STATUS                      Status = EFI_SUCCESS;
    PC_TO_RDR_XFRBLOCK_STRUC        *fpCmdBuffer;
    UINT32                          dwData;
    UINT32                          i;  

    USB_DEBUG (DEBUG_LEVEL_3, "PCToRDRXfrBlock ....");

    fpCmdBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_XFRBLOCK_STRUC) + CmdLength));
    ASSERT(fpCmdBuffer);
    if (!fpCmdBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpCmdBuffer, sizeof(PC_TO_RDR_XFRBLOCK_STRUC) + CmdLength, 0);

    //
    // Prepare  the cmd buffer
    //
    fpCmdBuffer->bMessageType = PC_TO_RDR_XFRBLOCK;
    fpCmdBuffer->dwLength = CmdLength;
    fpCmdBuffer->bSlot = fpICCDevice->Slot;
    fpCmdBuffer->bSeq = gSequence;
    fpCmdBuffer->bBWI = BlockWaitingTime;
    fpCmdBuffer->wLevelParameter = LevelParameter;

    //
    // Copy the cmd
    //
    if (CmdLength) {
        MemCopy(CmdBuffer, (UINT8 *)fpCmdBuffer + sizeof(PC_TO_RDR_XFRBLOCK_STRUC), CmdLength);
    }


    USB_DEBUG (DEBUG_LEVEL_3, "\n");
    for (i=0; i< sizeof(PC_TO_RDR_XFRBLOCK_STRUC) + CmdLength; i++) {
        USB_DEBUG (DEBUG_LEVEL_3, "%02X ", ((UINT8 *)fpCmdBuffer)[i]);
    }
    USB_DEBUG (DEBUG_LEVEL_3, "\n");

    dwData = USBCCIDIssueBulkTransfer(fpDevInfo, 0, 
                                    (UINT8 *)fpCmdBuffer, 
                                    sizeof(PC_TO_RDR_XFRBLOCK_STRUC) + CmdLength
                                    );

    //
    // Handle Error if any. This error is due to blk transfer
    //
    if (!dwData) {
        Status = EFI_DEVICE_ERROR;
    }

    USB_MemFree(fpCmdBuffer, (UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_XFRBLOCK_STRUC) + CmdLength));

    USB_DEBUG (DEBUG_LEVEL_3, "%r ....", Status);

    return Status;
    
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   PCtoRDRIccPowerOn
//
// Description: PC_TO_RDR_ICCPOWERON cmd is issued to the CCID
//
// Input:
//              IN DEV_INFO     *fpDevInfo,
//              IN ICC_DEVICE   *fpICCDevice,
//              IN UINT8        PowerLevel - 00:Automatic  Voltage selection, 01:5.0v, 02:3.0v, 03:1.8v
//
// Output: 
//              EFI_STATUS
//
// Notes:       See section 6.1.1 of CCID spec Rev 1.1 for more details
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
PCtoRDRIccPowerOn(
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice,
    IN UINT8            PowerLevel
)
{

    EFI_STATUS                    Status = EFI_SUCCESS;
    PC_TO_RDR_ICCPOWERON_STRUC     *fpCmdBuffer;
    UINT32                        dwData;

    USB_DEBUG (DEBUG_LEVEL_3, "PCtoRDRIccPowerOn ....");

    fpCmdBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_ICCPOWERON_STRUC)));
    ASSERT(fpCmdBuffer);
    if (!fpCmdBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpCmdBuffer, sizeof(PC_TO_RDR_ICCPOWERON_STRUC), 0);

    //
    // Prepare  the cmd buffer
    //
    fpCmdBuffer->bMessageType = PC_TO_RDR_ICCPOWERON;
    fpCmdBuffer->dwLength = 0;
    fpCmdBuffer->bSlot = fpICCDevice->Slot;
    fpCmdBuffer->bSeq = gSequence;
    fpCmdBuffer->bPowerSlot = PowerLevel;
    fpCmdBuffer->abRFU = 0;

    dwData = USBCCIDIssueBulkTransfer(fpDevInfo, 0, 
                                    (UINT8 *)fpCmdBuffer, 
                                    sizeof(PC_TO_RDR_ICCPOWERON_STRUC)
                                    );

    //
    // Handle Error if any. This error is due to blk transfer
    //
    if (!dwData) {
        Status = EFI_DEVICE_ERROR;
    }

    USB_MemFree(fpCmdBuffer, (UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_ICCPOWERON_STRUC)));

    USB_DEBUG (DEBUG_LEVEL_3, "%r ....", Status);

    return Status;

}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   PCtoRDRIccPowerOff
//
// Description: PC_TO_RDR_ICCPOWEROFF cmd is issued to the CCID
//
// Input :
//              IN DEV_INFO           *fpDevInfo,
//              IN ICC_DEVICE        *fpICCDevice
//
// Output : 
//              EFI_STATUS
//
// Notes:       See section 6.1.2 of CCID spec Rev 1.1 for more details
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
PCtoRDRIccPowerOff(
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice
)
{

    EFI_STATUS                  Status = EFI_SUCCESS;
    PC_TO_RDR_ICCPOWEROFF_STRUC *fpCmdBuffer;
    UINT32                      dwData;

    USB_DEBUG (DEBUG_LEVEL_3, "PCtoRDRIccPowerOff ....");

    fpCmdBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_ICCPOWEROFF_STRUC)));
    ASSERT(fpCmdBuffer);
    if (!fpCmdBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpCmdBuffer, sizeof(PC_TO_RDR_ICCPOWEROFF_STRUC), 0);

    //
    // Prepare the buffer
    //
    fpCmdBuffer->bMessageType = PC_TO_RDR_ICCPOWEROFF;
    fpCmdBuffer->dwLength = 0;
    fpCmdBuffer->bSlot = fpICCDevice->Slot;
    fpCmdBuffer->bSeq = gSequence;

    dwData = USBCCIDIssueBulkTransfer(fpDevInfo, 0, 
                                    (UINT8 *)fpCmdBuffer, 
                                    sizeof(PC_TO_RDR_ICCPOWEROFF_STRUC)
                                    );

    //
    // Handle Error if any. This error is due to blk transfer
    //
    if (!dwData) {
        Status = EFI_DEVICE_ERROR;
    }
    else {
        fpICCDevice->ConfiguredStatus = 0;
    }

    USB_MemFree(fpCmdBuffer, (UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_ICCPOWEROFF_STRUC)));

    USB_DEBUG (DEBUG_LEVEL_3, "%r ....", Status);

    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   PCToRDRGetSlotStatus
//
// Description: PC_TO_RDR_GETSLOTSTATUS cmd is issued to CCID
//
// Input: 
//              IN DEV_INFO           *fpDevInfo,
//              IN ICC_DEVICE        *fpICCDevice
//
// Output:
//              EFI_STATUS
//
//Notes:        See section 6.1.3 of CCID spec Rev 1.1 for more details
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
PCToRDRGetSlotStatus(
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice
)
{

    EFI_STATUS                    Status = EFI_SUCCESS;
    PC_TO_RDR_GETSLOT_STATUS_STRUC *fpCmdBuffer;
    UINT32                        dwData;

    USB_DEBUG (DEBUG_LEVEL_3, "PCToRDRGetSlotStatus ....");

    fpCmdBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_GETSLOT_STATUS_STRUC)));
    ASSERT(fpCmdBuffer);
    if (!fpCmdBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpCmdBuffer, sizeof(PC_TO_RDR_GETPARAMETERS_STRUC), 0);
    
    //
    // Prepare cmd buffer
    //
    fpCmdBuffer->bMessageType = PC_TO_RDR_GETSLOTSTATUS;
    fpCmdBuffer->bSlot = fpICCDevice->Slot;
    fpCmdBuffer->bSeq = gSequence;

    dwData = USBCCIDIssueBulkTransfer(fpDevInfo, 0, 
                                    (UINT8 *)fpCmdBuffer, 
                                    sizeof(PC_TO_RDR_GETSLOT_STATUS_STRUC)
                                    );

    //
    // Handle Error if any. This error is due to blk transfer
    //
    if (!dwData) {
        Status = EFI_DEVICE_ERROR;
    }

    USB_MemFree(fpCmdBuffer, (UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_GETSLOT_STATUS_STRUC)));

    USB_DEBUG (DEBUG_LEVEL_3, "%r ....", Status);

    return Status;

}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   PCToRDRGetParameters
//
// Description: PC_TO_RDR_GETPARAMETERS cmd is issued to CCID
//
// Input:
//              IN DEV_INFO           *fpDevInfo,
//              IN ICC_DEVICE        *fpICCDevice
//
// Output:
//              EFI_STATUS
//
// Notes:       See section 6.1.5 of CCID spec Rev 1.1 for more details
//             
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
PCToRDRGetParameters(
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice
)
{

    EFI_STATUS                    Status = EFI_SUCCESS;
    PC_TO_RDR_GETPARAMETERS_STRUC *fpCmdBuffer;
    UINT32                        dwData;

    USB_DEBUG (DEBUG_LEVEL_3, "PCToRDRGetParameters ....");

    fpCmdBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_GETPARAMETERS_STRUC)));
    ASSERT(fpCmdBuffer);
    if (!fpCmdBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpCmdBuffer, sizeof(PC_TO_RDR_GETPARAMETERS_STRUC), 0);

    //
    // Prepare cmd buffer
    //
    fpCmdBuffer->bMessageType = PC_TO_RDR_GETPARAMETERS;
    fpCmdBuffer->bSlot = fpICCDevice->Slot;
    fpCmdBuffer->bSeq = gSequence;

    dwData = USBCCIDIssueBulkTransfer(fpDevInfo, 0, 
                                    (UINT8 *)fpCmdBuffer, 
                                    sizeof(PC_TO_RDR_GETPARAMETERS_STRUC)
                                    );

    //
    // Handle Error if any. This error is due to blk transfer
    //
    if (!dwData) {
        Status = EFI_DEVICE_ERROR;
    }

    USB_MemFree(fpCmdBuffer, (UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_GETPARAMETERS_STRUC)));

    USB_DEBUG (DEBUG_LEVEL_3, "%r ....", Status);

    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   PCToRDRSetParameters
//
// Description: PC_TO_RDR_SETPARAMETERS cmd is issued to CCID
//
// Input :
//              IN DEV_INFO     *fpDevInfo
//              IN ICC_DEVICE   *fpICCDevice
//              IN UINT8        ProtocolNum -  0 : T=0, 1 : T=1
//              IN VOID         *Data - Points to data from abProtocolDataStructure 
//                                      in PC_TO_RDR_SETPARAMETERS
//
// Output:
//              EFI_STATUS
//
// Notes:       See section 6.1.7 of CCID spec Rev 1.1 for more details
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
PCToRDRSetParameters(
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice,
    IN UINT8            ProtocolNum,
    IN VOID             *Data
)
{

    EFI_STATUS                    Status = EFI_SUCCESS;
    PC_TO_RDR_SETPARAMETERS_T0_STRUC *fpCmdBuffer;
    UINT32                        dwData;
    UINT8                        Length = ProtocolNum == 0 ? sizeof(PROTOCOL_DATA_T0) : sizeof(PROTOCOL_DATA_T1);

    USB_DEBUG (DEBUG_LEVEL_3, "PCToRDRSetParameters ....");

    fpCmdBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(Length + sizeof(RDR_HEADER)));
    ASSERT(fpCmdBuffer);
    if (!fpCmdBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpCmdBuffer, Length + sizeof(RDR_HEADER), 0);

    //
    // Prepare 
    //
    fpCmdBuffer->bMessageType = PC_TO_RDR_SETPARAMETERS;
    fpCmdBuffer->dwLength = Length;
    fpCmdBuffer->bSlot = fpICCDevice->Slot;
    fpCmdBuffer->bSeq = gSequence;
    fpCmdBuffer->bProtocolNum = ProtocolNum;

    MemCopy ((UINT8 *)Data,  (UINT8 *)fpCmdBuffer +sizeof(RDR_HEADER), Length); 

    dwData = USBCCIDIssueBulkTransfer(fpDevInfo, 0, 
                                    (UINT8 *)fpCmdBuffer, 
                                    Length + sizeof(RDR_HEADER)
                                    );

    //
    // Handle Error if any. This error is due to blk transfer
    //
    if (!dwData) {
        Status = EFI_DEVICE_ERROR;
    }

    USB_MemFree(fpCmdBuffer, (UINT8)GET_MEM_BLK_COUNT(Length + sizeof(RDR_HEADER)));

    USB_DEBUG (DEBUG_LEVEL_3, "%r ....", Status);

    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   PCToRDRSetDataRateAndClockFrequency
//
// Description: PC_TO_RDR_SETDATARATEANDCLOCK cmd is issued. 
//              Response for this cmd is from RDR_TO_PC_DATARATEANDCLOCK
//
// Input: 
//              IN DEV_INFO         *fpDevInfo
//              IN ICC_DEVICE       *fpICCDevice
//              IN UINT32           ClockFrequency  - ICC Clock Frequency in KHz
//              IN UINT32           DataRate - ICC data rate in bpd
//
// Output:
//              EFI_STATUS
//
// Notes:       See section 6.1.14 of CCID spec Rev 1.1 for more details     
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
PCToRDRSetDataRateAndClockFrequency(
    IN DEV_INFO          *fpDevInfo,
    IN ICC_DEVICE        *fpICCDevice,
    IN UINT32            ClockFrequency, 
    IN UINT32            DataRate
)
{

    EFI_STATUS                    Status = EFI_SUCCESS;
    PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY_STRUC *fpCmdBuffer;
    UINT32                        dwData;

    USB_DEBUG (DEBUG_LEVEL_3, "PCToRDRGetParameters ....");

    fpCmdBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY_STRUC)));
    ASSERT(fpCmdBuffer);
    if (!fpCmdBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpCmdBuffer, sizeof(PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY_STRUC), 0);

    //
    // Prepare cmd buffer
    //
    fpCmdBuffer->bMessageType = PC_TO_RDR_SETDATARATEANDCLOCK;
    fpCmdBuffer->dwLength = 8;
    fpCmdBuffer->bSlot = fpICCDevice->Slot;
    fpCmdBuffer->bSeq = gSequence;
    fpCmdBuffer->dwCloclFrequency = ClockFrequency;
    fpCmdBuffer->dwDataRate = DataRate;

    dwData = USBCCIDIssueBulkTransfer(fpDevInfo, 0, 
                                    (UINT8 *)fpCmdBuffer, 
                                    sizeof(PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY_STRUC)
                                    );

    //
    // Handle Error if any. This error is due to blk transfer
    //
    if (!dwData) {
        Status = EFI_DEVICE_ERROR;
    }

    USB_MemFree(fpCmdBuffer, (UINT8)GET_MEM_BLK_COUNT(sizeof(PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY_STRUC)));

    USB_DEBUG (DEBUG_LEVEL_3, "%r ....", Status);

    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   RDRToPCDataBlock
//
// Description: RDR_TO_PC_DATABLOCK cmd is issued to the CCID. 
//              This is on response to PCI_to_RDR_XfrBlock
//
// Input: 
//              IN DEV_INFO        *fpDevInfo
//              IN ICC_DEVICE      *fpICCDevice
//              IN OUT UINT32      *dwLength - # of bytes in Buffer
//              OUT UINT8          *Buffer - Points to abData in RDR_TO_PC_DATABLOCK
//
// Output:
//              EFI_STATUS
//
// Notes:       See section 6.2.1 of CCID spec Rev 1.1 for more details     
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
RDRToPCDataBlock(
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice,
    IN OUT UINT32       *dwLength,
    OUT UINT8           *Buffer

)
{    

    EFI_STATUS      Status = EFI_SUCCESS;
    RDR_TO_PC_DATABLOCK_STRUC*  fpReceiveBuffer;
    UINT32          dwData;
    UINT8           Iterations = 3;
    UINT32          InputLength = *dwLength;
    UINT32           i;   

    //
    // Allocate memory for receiving data
    //
    fpReceiveBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(RDR_TO_PC_DATABLOCK_STRUC) + *dwLength));
    ASSERT(fpReceiveBuffer);
    if (!fpReceiveBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpReceiveBuffer, sizeof(RDR_TO_PC_DATABLOCK_STRUC) + *dwLength, 0);

    do {
        //
        // Get the response 
        //
        fpReceiveBuffer->bMessageType = RDR_TO_PC_DATABLOCK;
        fpReceiveBuffer->dwLength = *dwLength;
        fpReceiveBuffer->bSlot = fpICCDevice->Slot;
        fpReceiveBuffer->bSeq = gSequence;
        fpReceiveBuffer->bStatus = 0;
        fpReceiveBuffer->bError = 0;
        fpReceiveBuffer->bChainParameter = 0;

        dwData = USBCCIDIssueBulkTransfer(fpDevInfo, BIT7, 
                                        (UINT8 *)fpReceiveBuffer, 
                                        sizeof(RDR_TO_PC_DATABLOCK_STRUC) + *dwLength
                                        );

        USB_DEBUG (DEBUG_LEVEL_3, "\n");

        for (i=0; i< sizeof(RDR_TO_PC_DATABLOCK_STRUC) + fpReceiveBuffer->dwLength; i++) {
            USB_DEBUG (DEBUG_LEVEL_3, "%02X ", ((UINT8 *)fpReceiveBuffer)[i]);
        }

        USB_DEBUG (DEBUG_LEVEL_3, "\n");

        //    
        // Handle Error if any. This error is due to blk transfer
        //
        if (!dwData) {
            Status = EFI_DEVICE_ERROR;
            goto exit_RDRToPCDataBlock;
        }    

        //
        // Check for time extension 
        //
        if ((fpReceiveBuffer->bStatus & 0xC0) == 0x80) {
            FixedDelay(fpReceiveBuffer->bError * fpICCDevice->WaitTime * 1000);  
        } else {
            break;
        }

        Iterations--;
    } while (Iterations);    

    // Should the cmd be aborted if the response isn't received???

    //
    // Processed without error if Zero
    //
    if (fpReceiveBuffer->bStatus & 0xC0) {
        Status = EFI_DEVICE_ERROR;

        if ((fpReceiveBuffer->bStatus & 0x3) == 0x2) {        
            Status = EFI_NOT_FOUND;
        }
    }

    if (Iterations && !EFI_ERROR(Status)) {
    
        fpICCDevice->bChainParameter = fpReceiveBuffer->bChainParameter;

        //
        // If response is successful get the data
        //
        if (fpReceiveBuffer->dwLength && fpReceiveBuffer->dwLength <= *dwLength) {
    
            // Copy data 
            MemCopy ((UINT8 *)fpReceiveBuffer + sizeof(RDR_TO_PC_DATABLOCK_STRUC),  
                    Buffer, 
                    fpReceiveBuffer->dwLength
                    ); 

        }

        if  (fpReceiveBuffer->dwLength > *dwLength) {
            Status = EFI_BUFFER_TOO_SMALL;
        }

        //
        // Update the o/p buffer length
        //
        *dwLength = fpReceiveBuffer->dwLength;

    } else {

        Status = EFI_DEVICE_ERROR;
        *dwLength = 0;
    }

    //
    // Save the last cmd status 
    //
    fpICCDevice->bStatus = fpReceiveBuffer->bStatus;
    fpICCDevice->bError = fpReceiveBuffer->bError;


    //    
    // if success exit
    //
    if (!EFI_ERROR(Status) && !fpICCDevice->bStatus) {
        Status =  EFI_SUCCESS;
        goto exit_RDRToPCDataBlock;
    }

    // Card not present?
    Status = EFI_NOT_FOUND;
    if ((fpReceiveBuffer->bStatus & 7) == 2) goto exit_RDRToPCDataBlock;

    //
    // Other errors
    //
    Status = EFI_DEVICE_ERROR;

exit_RDRToPCDataBlock:

    gSequence++;

    USB_MemFree(fpReceiveBuffer, 
                (UINT8)GET_MEM_BLK_COUNT(sizeof(RDR_TO_PC_DATABLOCK_STRUC) + InputLength)
                );

    USB_DEBUG (DEBUG_LEVEL_3, " Status : %r bStatus : %02X bError : %02X\n", Status, fpICCDevice->bStatus, fpICCDevice->bError);
    
    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   RDRToPCSlotStatus
//
// Description: RDR_TO_PC_SLOTSTATUS cmd is issued to CCID.
//
// Input:
//              IN DEV_INFO         *fpDevInfo,
//              IN ICC_DEVICE       *fpICCDevice
//
// Output:
//              EFI_STATUS
//
// Notes:       bStatus, BError and bClockStatus is updated.  
//              See section 6.2.2 of CCID spec Rev 1.1 for more details.
//    
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
RDRToPCSlotStatus(
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice
)
{

    EFI_STATUS                  Status = EFI_SUCCESS;
    RDR_TO_PC_SLOTSTATUS_STRUC  *fpReceiveBuffer;
    UINT32                      dwData;
    UINT8                       Iterations = 3;    

    fpReceiveBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(RDR_TO_PC_SLOTSTATUS_STRUC)));
    ASSERT(fpReceiveBuffer);
    if (!fpReceiveBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpReceiveBuffer, sizeof(RDR_TO_PC_SLOTSTATUS_STRUC), 0);
    do {
        //
        // Read the PCSlot Status
        //
        fpReceiveBuffer->bMessageType = RDR_TO_PC_SLOTSTATUS;
        fpReceiveBuffer->dwLength = 0;
        fpReceiveBuffer->bSlot = fpICCDevice->Slot;
        fpReceiveBuffer->bSeq = gSequence;

        dwData = USBCCIDIssueBulkTransfer(fpDevInfo, BIT7, 
                                        (UINT8 *)fpReceiveBuffer, 
                                        sizeof(RDR_TO_PC_SLOTSTATUS_STRUC)
                                        );

        //
        // Handle Error if any. This error is due to blk transfer
        //
        if (!dwData) {
            Status = EFI_DEVICE_ERROR;
            goto exit_RDRToPCSlotStatus;
        }

        //
        // Check for time extension 
        //
        if ((fpReceiveBuffer->bStatus & 0xC0) == 0x80) {
            FixedDelay(fpReceiveBuffer->bError * fpICCDevice->WaitTime * 1000);  
        } else {
            break;
        }

        Iterations--;
    } while (Iterations);


    //
    // Save the last cmd status 
    //
    fpICCDevice->bStatus = fpReceiveBuffer->bStatus;
    fpICCDevice->bError = fpReceiveBuffer->bError;

    // Processed without error if Zero
    if (fpReceiveBuffer->bStatus & 0xC0) {
        Status = EFI_DEVICE_ERROR;

        if ((fpReceiveBuffer->bStatus & 0x3) == 0x2) {        
            Status = EFI_NOT_FOUND;
        }

    }

    if (Iterations && !EFI_ERROR(Status)) {
        //
        // Update the last ClockStatus
        //
        fpICCDevice->bClockStatus = fpReceiveBuffer->bClockStatus; 
    } else {
        Status = EFI_DEVICE_ERROR;
    }

exit_RDRToPCSlotStatus:

    gSequence++;

    USB_MemFree(fpReceiveBuffer, 
                (UINT8)GET_MEM_BLK_COUNT(sizeof(RDR_TO_PC_SLOTSTATUS_STRUC))
                );

    USB_DEBUG (DEBUG_LEVEL_3, " Status :  %r bStatus : %02X bError : %02X\n", Status, fpICCDevice->bStatus, fpICCDevice->bError);

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   RDRToPCParameters
//
// Description: RDR_TO_PC_SLOTSTATUS cmd is issued
//
// Input: 
//              IN DEV_INFO         *fpDevInfo,
//              IN ICC_DEVICE       *fpICCDevice
//
// Output:
//              EFI_STATUS
//              abProtocolDataStructure is copied
//        
//
// Notes:       bStatus, BErroris updated.  See section 6.2.3 of CCID spec 
//              Rev 1.1 for more details. 
//              bProtocolNum and abProtocolDatStructure is captured.
//
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
RDRToPCParameters(
    IN DEV_INFO           *fpDevInfo,
    IN ICC_DEVICE        *fpICCDevice
)
{

    EFI_STATUS                    Status = EFI_SUCCESS;
    RDR_TO_PC_PARAMETERS_T1_STRUC *fpReceiveBuffer;
    UINT32                        dwData;
    UINT8                         Iterations = 3;    

    fpReceiveBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(RDR_TO_PC_PARAMETERS_T1_STRUC)));
    ASSERT(fpReceiveBuffer);
    if (!fpReceiveBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpReceiveBuffer, sizeof(RDR_TO_PC_PARAMETERS_T1_STRUC), 0);

    do {

        //
        // Read the PCSlot Status
        //
        fpReceiveBuffer->Header.bMessageType = RDR_TO_PC_PARAMETERS;
        fpReceiveBuffer->Header.dwLength = 0;
        fpReceiveBuffer->Header.bSlot = fpICCDevice->Slot;
        fpReceiveBuffer->Header.bSeq = gSequence;

        dwData = USBCCIDIssueBulkTransfer(fpDevInfo, BIT7, 
                                        (UINT8 *)fpReceiveBuffer, 
                                        sizeof(RDR_TO_PC_PARAMETERS_T1_STRUC)
                                        );

        //
        // Handle Error if any. This error is due to blk transfer
        //
        if (!dwData) {
            Status = EFI_DEVICE_ERROR;
            goto exit_RDRToPCParameters;
        }

        //
        // Check for time extension 
        //
        if ((fpReceiveBuffer->Header.bStatus & 0xC0) == 0x80) {
            FixedDelay(fpReceiveBuffer->Header.bError * fpICCDevice->WaitTime * fpICCDevice->etu);  
        } else {
            break;
        }

        Iterations--;

    } while (Iterations);

    //
    // Save the last cmd status 
    //
    fpICCDevice->bStatus = fpReceiveBuffer->Header.bStatus;
    fpICCDevice->bError = fpReceiveBuffer->Header.bError;

    //
    // Processed without error if Zero
    //
    if (fpReceiveBuffer->Header.bStatus & 0xC0) {
        Status = EFI_DEVICE_ERROR;

        if ((fpReceiveBuffer->Header.bStatus & 0x3) == 0x2) {        
            Status = EFI_NOT_FOUND;
        }

    }

    if (Iterations && !EFI_ERROR(Status)) {

        //
        // Update the Data
        //
        MemCopy((UINT8 *)&(fpReceiveBuffer->Header.Data), 
                (UINT8 *)&(fpICCDevice->bProtocolNum), 
                sizeof(RDR_TO_PC_PARAMETERS_T1_STRUC) - 9);

    } else {

        Status = EFI_DEVICE_ERROR;
    }

exit_RDRToPCParameters:

    gSequence++;

    USB_MemFree(fpReceiveBuffer, 
                (UINT8)GET_MEM_BLK_COUNT(sizeof(RDR_TO_PC_PARAMETERS_T1_STRUC))
                );

    USB_DEBUG (DEBUG_LEVEL_3, " Status :  %r bStatus : %02X bError : %02X\n", Status, fpICCDevice->bStatus, fpICCDevice->bError);

    PrintPCParameters((UINT8 *)&(fpICCDevice->bProtocolNum));

    return Status;

}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   RDRToPCDataRateAndClockFrequency
//
// Description: RDR_TO_PC_DATARATEANDCLOCK cmd is issued. 
//
// Input:
//              IN DEV_INFO          *fpDevInfo,
//              IN ICC_DEVICE        *fpICCDevice
//
// Output:
//              EFI_STATUS
//         
// Notes:       Returns dwClockFrequency and dwDataRate. 
//              See section 6.2.5 of CCID spec Rev 1.1 for more details.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
RDRToPCDataRateAndClockFrequency(
    IN DEV_INFO          *fpDevInfo,
    IN ICC_DEVICE        *fpICCDevice
)
{

    EFI_STATUS                    Status = EFI_SUCCESS;
    RDR_TO_PC_DATARATEANDCLOCKFREQUENCY_STRUC  *fpReceiveBuffer;
    UINT32                        dwData;
    UINT8                        Iterations = 3;    

    fpReceiveBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(RDR_TO_PC_DATARATEANDCLOCKFREQUENCY_STRUC)));
    ASSERT(fpReceiveBuffer);
    if (!fpReceiveBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)fpReceiveBuffer, sizeof(RDR_TO_PC_DATARATEANDCLOCKFREQUENCY_STRUC), 0);

    do {

        //
        // Read the PCSlot Status
        //
        fpReceiveBuffer->bMessageType = RDR_TO_PC_DATARATEANDCLOCK;
        fpReceiveBuffer->dwLength = 8;
        fpReceiveBuffer->bSlot = fpICCDevice->Slot;
        fpReceiveBuffer->bSeq = gSequence;

        dwData = USBCCIDIssueBulkTransfer(fpDevInfo, BIT7, 
                                        (UINT8 *)fpReceiveBuffer, 
                                        sizeof(RDR_TO_PC_DATARATEANDCLOCKFREQUENCY_STRUC));

        //
        // Handle Error if any. This error is due to blk transfer
        //
        if (!dwData) {
            Status = EFI_DEVICE_ERROR;
            goto exit_RDRToPCDataRateAndClockFrequency;
        }

        //
        // Check for time extension 
        //
        if ((fpReceiveBuffer->bStatus & 0xC0) == 0x80) {
            FixedDelay(fpReceiveBuffer->bError * fpICCDevice->WaitTime * 1000);  
        } else {
            break;
        }

        Iterations--;

    } while (Iterations);


    //
    // Processed without error if Zero
    //
    if (fpReceiveBuffer->bStatus & 0xC0) {
        Status = EFI_DEVICE_ERROR;

        if ((fpReceiveBuffer->bStatus & 0x3) == 0x2) {        
            Status = EFI_NOT_FOUND;
        }
    }

    if (Iterations && !EFI_ERROR(Status)) {

         fpICCDevice->dwClockFrequency = fpReceiveBuffer->dwClockFrequency; 
         fpICCDevice->dwDataRate = fpReceiveBuffer->dwDataRate;

    } else {

        Status = EFI_DEVICE_ERROR;

    }

    //
    // Save the last cmd status 
    //
    fpICCDevice->bStatus = fpReceiveBuffer->bStatus;
    fpICCDevice->bError = fpReceiveBuffer->bError;

exit_RDRToPCDataRateAndClockFrequency:

    gSequence++;

    USB_MemFree(fpReceiveBuffer, 
                (UINT8)GET_MEM_BLK_COUNT(sizeof(RDR_TO_PC_DATARATEANDCLOCKFREQUENCY_STRUC))
                );

    USB_DEBUG (DEBUG_LEVEL_3, " Status :  %r bStatus : %02X bError : %02X\n", 
                Status, fpICCDevice->bStatus, fpICCDevice->bError);

    USB_DEBUG (DEBUG_LEVEL_3, " dwClockFrequency :  %4x dwDataRate : %4x\n", 
                fpICCDevice->dwClockFrequency, fpICCDevice->dwDataRate);

    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   TxRxT1Adpu
//
// Description: Transmit/Receive T1 ADPU
//
// Input:
//              IN DEV_INFO         *fpDevInfo,
//              IN ICC_DEVICE       *fpICCDevice,
//              IN UINT32           CmdLength,
//              IN UINT8            *CmdBuffer,
//              IN UINT8            BlockWaitingTime,
//              IN UINT16           LevelParameter    
//
// Output: 
//
//
// Notes: 
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
TxRxT1Adpu (
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice,
    IN UINT32           CmdLength,
    IN UINT8            *CmdBuffer,
    OUT UINT32          *ResponseLength,
    OUT UINT8           *ResponseBuffer
)
{

    EFI_STATUS  Status;

    //
    // Issue the cmd
    //
    Status = PCToRDRXfrBlock(fpDevInfo, fpICCDevice, CmdLength, CmdBuffer, 0, 0);
    
    if (EFI_ERROR(Status)){
        return Status;        
    }

    //
    // Get the response
    //
    Status = RDRToPCDataBlock(fpDevInfo, fpICCDevice, ResponseLength, ResponseBuffer);

    return Status;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:       TxRxT1TDPUChar
//
// Description:     Transmit/Receive T1 TDPU/Character 
//
// Input:
//    IN DEV_INFO         *fpDevInfo,
//    IN ICC_DEVICE       *fpICCDevice,
//    IN UINT32           CmdLength,
//    IN UINT8            *CmdBuffer,
//    IN UINT8            ISBlock,
//    OUT UINT32          *ResponseLength,
//    OUT UINT8           *ResponseBuffer   
//
// Output: 
//
//
// Notes: 
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
TxRxT1TDPUChar (
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice,
    IN UINT32           CmdLength,
    IN UINT8            *CmdBuffer,
    IN UINT8            ISBlock,
    IN OUT UINT32       *ResponseLength,
    OUT UINT8           *ResponseBuffer
)
{

    EFI_STATUS  Status;
    UINT8       Pcb = ISBlock;
    UINT32      InfLength = CmdLength;
    UINT8       *InfBuffer = CmdBuffer;

    UINT32      IBlockFrameLength = 0;      // Used for I-Block
    UINT8       *IBlockFrame = NULL;

    UINT32      SendBlockFrameLength = 0;   // Place holder for the block currently sent
    UINT8       *SendBlockFrame = NULL;

    UINT32      RBlockFrameLength = 0;      // Used for R-Block
    UINT8       *RBlockFrame = NULL;

    UINT32      SBlockFrameLength = 0;      // Used for S-Block
    UINT8       *SBlockFrame = NULL;

    UINT32      lResponseLength = 0;        // Response buffer for all the blocks I/S/R
    UINT32      OrglResponseLength = 0;     
    UINT8       *lResponseBuffer;

    UINT8       wLevelParameter = 0;

    UINT8       ReceiveStatus;
    UINT8       bBWIByte = 0;    

    UINT32      UserBufferLength = *ResponseLength;
    UINT32      lResponseBufferAddDataPtr = 0;

    BOOLEAN T1Char = ((SMARTCLASS_DESC*)fpDevInfo->pCCIDDescriptor)->dwFeatures & TDPU_LEVEL_EXCHANGE ? FALSE : TRUE;    
    UINT8     *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        return EFI_DEVICE_ERROR;
    }
    // Initialize Chaining is off
    fpICCDevice->Chaining = FALSE;
    *ResponseLength  = 0;

    // Update Pcb with Nas only for IBlocks
    if (!ISBlock) {
        Pcb = ((fpICCDevice->NaSInterface & 1) << 6);
    }

    Status = ConstructBlockFrame(fpDevInfo, fpICCDevice, 
                                fpICCDevice->NAD, Pcb, 
                                CmdLength, CmdBuffer, 
                                &wLevelParameter, &IBlockFrameLength, 
                                &IBlockFrame
                                );        


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

    SendBlockFrameLength = IBlockFrameLength;
    SendBlockFrame = IBlockFrame;

    if (UserBufferLength < 2)  lResponseLength = 2;

    lResponseLength += (UserBufferLength + 3 + (fpICCDevice->EpilogueFields == 0 ? 1 :  2));

    lResponseBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(lResponseLength));
    ASSERT(lResponseBuffer);
    if (!lResponseBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill(lResponseBuffer, lResponseLength, 0);    

    OrglResponseLength = lResponseLength;

    fpICCDevice->T1CharCmdDataPhase = TRUE; // Always Cmd Phase first

    do {

        Status = PCToRDRXfrBlock(fpDevInfo, fpICCDevice, 
                                SendBlockFrameLength, SendBlockFrame, 
                                bBWIByte, wLevelParameter
                                );

        if (EFI_ERROR(Status)){
            break;        
        }

        //
        // Get the response
        //
        lResponseLength = OrglResponseLength - lResponseBufferAddDataPtr;
        Status = RDRToPCDataBlock(fpDevInfo, fpICCDevice, &lResponseLength, lResponseBuffer + lResponseBufferAddDataPtr);

        if (EFI_ERROR(Status)){
            break;        
        }

        // Check for errors
        ReceiveStatus = HandleReceivedBlock(fpDevInfo, fpICCDevice, 
                                            IBlockFrameLength, IBlockFrame, 
                                            SendBlockFrameLength, SendBlockFrame, 
                                            lResponseBuffer
                                            );        

        bBWIByte = 0;

        switch (ReceiveStatus) {

            case BLOCK_TRANSMISION_SUCCESS:
                break;
    
            case RESEND_BLOCK:
                break;

            case SEND_R_BLOCK_1:
            case SEND_R_BLOCK_0:

                // Check if Chaining is in progress
                if (fpICCDevice->Chaining) {

                    // Copy the data from lResponseBuffer to the user buffer
                    //
                    // If success copy the data to Response buffer
                    //
                    if (lResponseBuffer[2] && ((UserBufferLength - *ResponseLength) < lResponseBuffer[2])) {
                        Status = EFI_BUFFER_TOO_SMALL;        
                    }

                    MemCopy(lResponseBuffer+3, ResponseBuffer + *ResponseLength, lResponseBuffer[2]);
                    *ResponseLength +=  lResponseBuffer[2];
                    lResponseBufferAddDataPtr = 0;          // Reset to use the lResponseBuffer from the beginning
                    
                    // Clear out the PCB/length feild so that by mistake the buffer is interpreted as valid data
                    lResponseBuffer[1] = 0;
                    lResponseBuffer[2] = 0;
                    lResponseLength = OrglResponseLength;
                    
                }
                Status = ConstructBlockFrame(fpDevInfo, fpICCDevice,    
                                            fpICCDevice->NAD, ReceiveStatus == SEND_R_BLOCK_1 ? 0x80 | 0x10 : 0x80, 
                                            0, NULL, &wLevelParameter, 
                                            &RBlockFrameLength, &RBlockFrame
                                            );        

                if (EFI_ERROR(Status)) {
                    ReceiveStatus = BLOCK_TRANSMISSION_TERMINATE;
                }
                SendBlockFrameLength = RBlockFrameLength;
                SendBlockFrame = RBlockFrame;
                fpICCDevice->T1CharCmdDataPhase = TRUE;
                break;

            case I_BLOCK_RESEND:

                Status = ConstructBlockFrame(fpDevInfo, fpICCDevice, 
                                            fpICCDevice->NAD, Pcb, CmdLength, 
                                            CmdBuffer, &wLevelParameter, 
                                            &IBlockFrameLength, &IBlockFrame
                                            );        

                if (EFI_ERROR(Status)) {
                    ReceiveStatus = BLOCK_TRANSMISSION_TERMINATE;
                }
                SendBlockFrameLength = IBlockFrameLength;
                SendBlockFrame = IBlockFrame;
                fpICCDevice->T1CharCmdDataPhase = TRUE;
                break;

            case WTX_RESPONSE:

                bBWIByte = lResponseBuffer[3];

                Status = ConstructBlockFrame(fpDevInfo, fpICCDevice, 
                                            fpICCDevice->NAD, WTX_RESPONSE, 
                                            lResponseBuffer[2], lResponseBuffer + 3, 
                                            &wLevelParameter, &SBlockFrameLength, 
                                            &SBlockFrame
                                            );        

                if (EFI_ERROR(Status)) {
                    ReceiveStatus = BLOCK_TRANSMISSION_TERMINATE;
                }

                SendBlockFrameLength = SBlockFrameLength;
                SendBlockFrame = SBlockFrame;
                fpICCDevice->T1CharCmdDataPhase = TRUE;
                break;

            case GET_DATA_T1_CHAR:
                
                //
                // Issue a PCToRDRXfrBlock with dwLength to zero. 
                // Check Page 68 of CCID spec Rev 1.1, Apr 22, 2005
                //

                SendBlockFrameLength = 0;
                // Assumption : only LRC is supported
                wLevelParameter = lResponseBuffer[2] + 1; 

                //
                // Since the prologue is received in the first three bytes increment 
                // the address so that data is recived after that  
                //
                lResponseBufferAddDataPtr += 3;   

                //
                // Indicate it is data phase now                  
                //
                fpICCDevice->T1CharCmdDataPhase = FALSE;  
                break;

            case IFS_RESPONSE:
                Status = ConstructBlockFrame(fpDevInfo, fpICCDevice, 
                                            fpICCDevice->NAD, IFS_RESPONSE, 
                                            lResponseBuffer[2], lResponseBuffer + 3, 
                                            &wLevelParameter, &SBlockFrameLength, 
                                            &SBlockFrame
                                            );        

                if (EFI_ERROR(Status)) {
                    ReceiveStatus = BLOCK_TRANSMISSION_TERMINATE;
                }

                SendBlockFrameLength = SBlockFrameLength;
                SendBlockFrame = SBlockFrame;
                fpICCDevice->T1CharCmdDataPhase = TRUE;
                break;

            case ABORT_RESPONSE:
                 Status = ConstructBlockFrame(fpDevInfo, fpICCDevice, 
                                            fpICCDevice->NAD, ABORT_RESPONSE, 
                                            lResponseBuffer[2], lResponseBuffer + 3, 
                                            &wLevelParameter, &SBlockFrameLength, 
                                            &SBlockFrame
                                            );        

                if (EFI_ERROR(Status)) {
                    ReceiveStatus = BLOCK_TRANSMISSION_TERMINATE;
                }

                SendBlockFrameLength = SBlockFrameLength;
                SendBlockFrame = SBlockFrame;
                fpICCDevice->T1CharCmdDataPhase = TRUE;
                break;

            default:
                break;
                        
        }

        if (ReceiveStatus == BLOCK_TRANSMISION_SUCCESS) {
            break;
        }       
    }while (1);

    //
    // If success copy the data to Response buffer for the last I-Block that was received.
    //
    if (lResponseBuffer[2] && ((UserBufferLength - *ResponseLength) < lResponseBuffer[2])) {
        Status = EFI_BUFFER_TOO_SMALL;        
    }

    if (lResponseBuffer[2] && ((UserBufferLength - *ResponseLength) >= lResponseBuffer[2])) {
        MemCopy(lResponseBuffer+3, ResponseBuffer + *ResponseLength, lResponseBuffer[2]);
        *ResponseLength +=  lResponseBuffer[2];
    }

    //
    // Free up memory I-Block allocated here
    //
    if (IBlockFrame && IBlockFrameLength) {
        USB_MemFree(IBlockFrame, (UINT8)GET_MEM_BLK_COUNT(IBlockFrameLength));
    }

    //
    // Free up S-Block memory allocated here
    //
    if (SBlockFrame && SBlockFrameLength) {
        USB_MemFree(SBlockFrame, (UINT8)GET_MEM_BLK_COUNT(SBlockFrameLength));
    }

    if (lResponseBuffer && OrglResponseLength) {
        USB_MemFree(lResponseBuffer, (UINT8)GET_MEM_BLK_COUNT(OrglResponseLength));
    }



    return Status;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   ConstructBlockFrame
//
// Description: Construct the Block Frame for the CCID
//
// Input:
//              IN DEV_INFO         *fpDevInfo,
//              IN ICC_DEVICE       *fpICCDevice,
//              IN UINT8            Nad,
//              IN UINT8            PCB,
//              IN UINT32           InfLength,
//              IN UINT8            *InfBuffer,
//              OUT UINT8           *wLevelParameter,
//              OUT UINT32          *BlockFrameLength,
//              OUT UINT8           **BlockFrame
//
// Output: 
//              EFI_STATUS      EFI Status
//
// Notes: 
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
ConstructBlockFrame(
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice,
    IN UINT8            Nad,
    IN UINT8            PCB,
    IN UINT32           InfLength,
    IN UINT8            *InfBuffer,
    OUT UINT8           *wLevelParameter,
    OUT UINT32          *BlockFrameLength,
    OUT UINT8           **BlockFrame
)
{

    UINT32  BufLengthRequired = InfLength + 3 + 
                                (fpICCDevice->EpilogueFields == 0 ? 1 :  2);
    UINT8   *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        return EFI_DEVICE_ERROR;
    }

    //
    // Check if the input buffer if already allocated is enough for the current case. 
    // If not free it up and allocate again.
    //
    
    if (BufLengthRequired > *BlockFrameLength) {
        if (*BlockFrame) {
            USB_MemFree(*BlockFrame, (UINT8)GET_MEM_BLK_COUNT(*BlockFrameLength));
            *BlockFrame = NULL;

        }
    }

    *BlockFrameLength = InfLength + 3 + (fpICCDevice->EpilogueFields == 0 ? 1 :  2);

    //
    // if BlockFrame is NULL only then allocate memory. Assumption is if Memory 
    // has been allocated before then it is sufficent enough for the length needed.
    //
    if (!*BlockFrame) {
        //
        // Allocate length needed to contruct the Block Frame
        //
        *BlockFrame = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(*BlockFrameLength));

        if (!*BlockFrame) {
            return EFI_OUT_OF_RESOURCES;
        }
    }

    MemFill(*BlockFrame, *BlockFrameLength, 0);    

    (*BlockFrame)[0] = Nad;
    (*BlockFrame)[1] = PCB;
    (*BlockFrame)[2] = InfLength;

    if (InfLength) {
        MemCopy((UINT8 *)InfBuffer, (UINT8 *)(*BlockFrame + 3), InfLength);
    }

    //
    // Update Checksum
    //
    (*BlockFrame)[*BlockFrameLength - 1] = 0;

    if (fpICCDevice->EpilogueFields == 0) {
        CalculateLRCChecksum(*BlockFrame, *BlockFrameLength);
    } else {
        return EFI_UNSUPPORTED;
    }

    //
    // For Character transfer update wLevelParameter also
    //
    if (!(((SMARTCLASS_DESC*)fpDevInfo->pCCIDDescriptor)->dwFeatures & 0x70000)) {
        *wLevelParameter = 3;
    }

    return EFI_SUCCESS;    

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   HandleReceivedBlock
//
// Description: Process the Recevied data from CCID device
//
// Input:
//              IN DEV_INFO         *fpDevInfo,
//              IN ICC_DEVICE       *fpICCDevice,
//              IN UINT32           OriginalBlockFrameLength,
//              IN UINT8            *OriginalBlockFrame,
//              IN UINT32           SentBlockFrameLength,
//              IN UINT8            *SentBlockFrame,
//              IN UINT8            *ReceivedBlockFrame
//
// Output: 
//
//
// Notes: 
//      For Character exchange control will come twice for S(Response), I-Block with M bit set. So while counting
//      number of exchnages this needs to be taken care of.
//      Refer to ISO/IEC 7816-1 First edition 1998-10-15 for different scenarios mentioned in this function.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
UINT8   
HandleReceivedBlock (
    IN DEV_INFO         *fpDevInfo,
    IN ICC_DEVICE       *fpICCDevice,
    IN UINT32           OriginalBlockFrameLength,
    IN UINT8            *OriginalBlockFrame,
    IN UINT32           SentBlockFrameLength,
    IN UINT8            *SentBlockFrame,
    IN UINT8            *ReceivedBlockFrame
)
{

    UINT8   ReturnParameter = BLOCK_TRANSMISION_SUCCESS;
    BOOLEAN T1Char = ((SMARTCLASS_DESC*)fpDevInfo->pCCIDDescriptor)->dwFeatures & 0x70000 ? FALSE : TRUE;
    UINT8     *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        return BLOCK_TRANSMISSION_TERMINATE;
    }

    // It is easy to support T1 TDPU & CHAR as they are almost same except that 
    // prologue and data are received separatly in T1 Char.
    // The trick here will be that when data is received we can combine the 
    // previously received prologue and the INF/Epilogue received 
    // later so that it will be similar to T1 TDPU. Then all the processing will be same.

    if (!ReceivedBlockFrame){    // if no response

        if (fpICCDevice->RBlockCounter == 2) {
            return BLOCK_TRANSMISSION_TERMINATE;
        }


        
        // If I-Block sent before and no response, send R-Block with the expected I Block(N(R). Rule 7.1/Rule 7.6
        if (!(SentBlockFrame[1] & 0x80)) { 
            
            fpICCDevice->RBlockCounter++;

            if (fpICCDevice->NaSCard) {
             return SEND_R_BLOCK_0;
            } else {
                return SEND_R_BLOCK_1;
            }
        }
        
    }

    // Reset the RBlock Counter if the response we received isn't a R-Block.
    if ((ReceivedBlockFrame[1] & 0xC0) !=  RBLOCK) {
            fpICCDevice->RBlockCounter = 0;
    }

    //
    // Is the block received an I-Block?
    //
    if (!(ReceivedBlockFrame[1] & 0x80)) {

        //
        // It is T1 Char and also if in cmd phase handle it.
        //
        if (T1Char && fpICCDevice->T1CharCmdDataPhase)  { 

            // Save the N(s) from the card for later use.
            fpICCDevice->NaSCard = (ReceivedBlockFrame[1] & NSBIT) >> 6;

            // If data needs to be received
            if (ReceivedBlockFrame[2]){
                return GET_DATA_T1_CHAR;
            }  else {
                return BLOCK_TRANSMISION_SUCCESS;
            }            

        }

        // It is T1TDPU or it is T1 Char but in data phase

       
        // Is Mbit set, then nothing more to do
        if (!(ReceivedBlockFrame[1] & 0x20)) {
            //
            // Toggle N(S) bit only after a successful I Block Transmission
            //
            fpICCDevice->Chaining = FALSE;
            fpICCDevice->NaSInterface = !(fpICCDevice->NaSInterface);

            return BLOCK_TRANSMISION_SUCCESS;
        }
        else {
            // Since Mbit is set, Send R-Block with the next N(s) expected from card. Section 5, Rules 2.2 and 5
            
            fpICCDevice->Chaining = TRUE;

            if (fpICCDevice->NaSCard){
                return SEND_R_BLOCK_0;
            }
            else {
                return SEND_R_BLOCK_1;
            }
        }
    }

    // No difference between T1 Char and T1 Tdpu in R-phase

    //
    // Is the Block received is a R block?
    //
    if ((ReceivedBlockFrame[1] & 0xC0) ==  RBLOCK) {
        

        // Is there an error?
        if (ReceivedBlockFrame[1] & 0x03) {
            //Re-transmit it
            if ((SentBlockFrame[1] & 0xc0) == 0x00) {
                return  I_BLOCK_RESEND;
            }
            else {
                return RESEND_BLOCK;
            }
        }

        if (T1Char && fpICCDevice->T1CharCmdDataPhase) {
            return  GET_DATA_T1_CHAR;
        }

        if (fpICCDevice->RBlockCounter == 3) {
            fpICCDevice->RBlockCounter = 0;
            return BLOCK_TRANSMISSION_TERMINATE;
        }
        fpICCDevice->RBlockCounter++;

        if (fpICCDevice->Chaining == FALSE) {

            //
            // if the received  R-Block is same as the last sent I-Block AND Chaining is not in progress, resend I-Block. Scenario 8
            //
            if ((ReceivedBlockFrame[1] & 0x10) >> 4 == (fpICCDevice->NaSInterface & 1) << 6) {
                return I_BLOCK_RESEND;
            } 
            else {
                //
                // Scenario 11/12
                //
                if (fpICCDevice->NaSInterface & 1) {
                    return SEND_R_BLOCK_1;
                } else {
                    return SEND_R_BLOCK_0;
                }
            }
        }
        else { 
            //
            // Chaining is in progress...
            //
            //   
            // Scenario 5
            //
            if ((ReceivedBlockFrame[1] & 0x10) >> 4 != (fpICCDevice->NaSInterface & 1) << 6) {
                // return I_BLOCK;
            }
            //
            // Scenario 23
            //
            if (ReceivedBlockFrame[1]  == SentBlockFrame[1]) {
                if (ReceivedBlockFrame[1] & 0x10) {
                    return SEND_R_BLOCK_1;
                } else {
                    return SEND_R_BLOCK_0;
                }
            }
           
        }

        // We can try giving S-Synch also if it doesn't respond to R-Block. 
        // S-Synch can be done only for 2nd Iblock on-wards.
    }    

    //
    // Is the Block Received is a S block? 
    //
    if ((ReceivedBlockFrame[1] & 0xC0) == 0xC0) {

        switch (ReceivedBlockFrame[1]) {

            case IFS_REQUEST:

               if (T1Char && fpICCDevice->T1CharCmdDataPhase) {
                    ReturnParameter = GET_DATA_T1_CHAR;
                    break;
                }
                // Save the new IFSD data
                fpICCDevice->IFSD = ReceivedBlockFrame[3];
                ReturnParameter = IFS_RESPONSE;
                break;

            case IFS_RESPONSE:
                //
                // It is T1 Char and also if in cmd phase handle it.
                //
                if (T1Char && fpICCDevice->T1CharCmdDataPhase)  { 

                    // If data needs to be received
                    if (ReceivedBlockFrame[2]){
                        return GET_DATA_T1_CHAR;
                    }  else {
                        return BLOCK_TRANSMISION_SUCCESS;
                    }            
                }  
                break;

            case ABORT_REQUEST:
                    fpICCDevice->Chaining = FALSE;
                    ReturnParameter = ABORT_RESPONSE;
                    break;

            case ABORT_RESPONSE:
                break;

            case WTX_REQUEST:

                if (T1Char && fpICCDevice->T1CharCmdDataPhase) {
                    ReturnParameter = GET_DATA_T1_CHAR;
                    break;
                }

                ReturnParameter = WTX_RESPONSE;
                break;                

            case RESYNCH_RESPONSE:
                break;

            case WTX_RESPONSE:              // Won't be received from card. Card will only generate WTX request.
                break;        
            case RESYNCH_REQUEST:           // Card won't issue ReSynch
                break;
            default:
                break;

        }  
  
    }                

   return ReturnParameter;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   CalculateLRCChecksum
//
// Description: Calculates LRC checksum
//
// Input:
//              UINT8            *BlockFrame
//              UINT32            BlockFrameLength
//
// Output: 
//              ICC_DEVICE* or NULL
//
// Notes: 
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
CalculateLRCChecksum (
    UINT8       *BlockFrame, 
    UINT32      BlockFrameLength
)
{
    UINT32  i = 0;

    for (; i < BlockFrameLength - 1; i++ ){
        BlockFrame[BlockFrameLength-1] ^= BlockFrame[i];
    }
    
    return;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   GetICCDevice
//
// Description: Search the linked list to find the ICC_DEVICE for the given slot #.
//
// Input:
//              DEV_INFO        *fpDevInfo
//              UINT8            Slot
//
// Output: 
//              ICC_DEVICE* or NULL
//
// Notes: 
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
ICC_DEVICE*
GetICCDevice(
    DEV_INFO        *fpDevInfo, 
    UINT8            Slot
)
{
    ICC_DEVICE        *fpICCDevice;
    DLINK           *dlink;
    UINT8           *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    dlink = fpDevInfo->ICCDeviceList.pHead;

    for ( ; dlink; dlink = dlink->pNext) {

        fpICCDevice = OUTTER(dlink, ICCDeviceLink, ICC_DEVICE);

        //
        // Slot # matches
        //
        if (fpICCDevice->Slot == Slot) {
            if (((UINT8*)fpICCDevice < gUsbData->fpMemBlockStart) ||
                ((UINT8*)((UINTN)fpICCDevice + sizeof(ICC_DEVICE)) > MemBlockEnd)) {
                return NULL;
            }
            return fpICCDevice;
        }      
          
    }

    return NULL;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   UpdateATRDataInfo
//
// Description: The routine update the Transmision protocol supported and other 
//              timing related data
//
// Input: 
//              DEV_INFO           *fpDevInfo
//              ICC_DEVICE        *fpICCDevice
//
// Output: 
//              None
//
// Notes:       This function looks into ATR data and updates CLASS A/B/C information, 
//              calculates ETU, WaitTime etc
//        
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
UpdateATRDataInfo(
    DEV_INFO            *fpDevInfo,
    ICC_DEVICE          *fpICCDevice
)
{
    UINT8    bData;
    UINT8    i=1;

    //
    // T0 is mandatory
    //
    fpICCDevice->AtrData.T0 = fpICCDevice->RawATRData[i];
    fpICCDevice->AtrData.NumberofHystoricalBytes = fpICCDevice->RawATRData[i] & 0xF;
    i++;

    //
    // Update TA1
    //
    if (fpICCDevice->AtrData.T0 & 0x10) {
        fpICCDevice->AtrData.TA1 = fpICCDevice->RawATRData[i];
        fpICCDevice->AtrData.TA1Present = TRUE;
        i++;
    } else {
        //
        // Default value if TA1 is not present
        //
        fpICCDevice->AtrData.TA1 = 0x11;        
    }

    bData = fpICCDevice->AtrData.TA1;
    fpICCDevice->GlobalFi = FiFmaxDi[(bData >> 4) * 3];
    fpICCDevice->GlobalFmax = (UINT8)FiFmaxDi[(bData >> 4) * 3 + 1];
    fpICCDevice->GlobalDi = (UINT8)FiFmaxDi[(bData& 0xF) * 3 + 2];


    //
    // Update TB1
    //
    if (fpICCDevice->AtrData.T0 & 0x20) {
        fpICCDevice->AtrData.TB1 = fpICCDevice->RawATRData[i];
        fpICCDevice->AtrData.TB1Present = TRUE;
        i++;
    }

    //
    // Update TC1
    //
    if (fpICCDevice->AtrData.T0 & 0x40) {
        fpICCDevice->AtrData.TC1 = fpICCDevice->RawATRData[i];
        fpICCDevice->AtrData.TC1Present = TRUE;
        i++;
    }

    //
    // Update TD1
    //
    if (fpICCDevice->AtrData.T0 & 0x80) {
        fpICCDevice->AtrData.TD1 = fpICCDevice->RawATRData[i];
        fpICCDevice->AtrData.TD1Present = TRUE;
        i++;
    }

    if (fpICCDevice->AtrData.TD1) {

        //
        // Update TA2
        //
        if (fpICCDevice->AtrData.TD1 & 0x10) {
            fpICCDevice->AtrData.TA2 = fpICCDevice->RawATRData[i];
            fpICCDevice->AtrData.TA2Present = TRUE;
            fpICCDevice->SpecificMode = fpICCDevice->AtrData.TA2 & BIT7 ? TRUE : FALSE;
            i++;
        }

        //
        // Update TB2
        //
        if (fpICCDevice->AtrData.TD1 & 0x20) {
            fpICCDevice->AtrData.TB2 = fpICCDevice->RawATRData[i];
            fpICCDevice->AtrData.TB2Present = TRUE;
            i++;
        }

        //
        // Update TC2
        //
        if (fpICCDevice->AtrData.TD1 & 0x40) {
            fpICCDevice->AtrData.TC2 = fpICCDevice->RawATRData[i];
            fpICCDevice->AtrData.TC2Present = TRUE;
            i++;
        }

        //
        // Update TD2
        //
        if (fpICCDevice->AtrData.TD1 & 0x80) {
            fpICCDevice->AtrData.TD2 = fpICCDevice->RawATRData[i];
            fpICCDevice->AtrData.TD2Present = TRUE;
            i++;
        }
    }

    //
    // Check if T15 is present else only CLASS A is supported. 
    // By default CLASS A is supported
    //
    fpICCDevice->ClassABC = 1;            

    for (bData = 1;  bData < MAX_ATR_LENGTH ;){

        //
        // Is it T15?
        //
        if ((fpICCDevice->RawATRData[bData] & 0xF) == 0xF){
            fpICCDevice->ClassABC = fpICCDevice->RawATRData[bData + 1] & 0x3F;
            fpICCDevice->StopClockSupport = fpICCDevice->RawATRData[bData + 1] >> 5; 

            fpICCDevice->AtrData.TD15 = fpICCDevice->RawATRData[bData];
            fpICCDevice->AtrData.TD15Present = TRUE;

            fpICCDevice->AtrData.TA15 = fpICCDevice->RawATRData[bData + 1];
            fpICCDevice->AtrData.TA15Present = TRUE;

            break;
        } else {
            // We need info on how many Transmission Protocols are supported by the 
            // card and what are those. Use these loop to do that.
            if (bData > 1) {    // Skip T0
                i = fpICCDevice->TransmissionProtocolSupported;
                fpICCDevice->TransmissionProtocolSupported |=  ( 1 << (fpICCDevice->RawATRData[bData] & 0x0F));
                if (i != fpICCDevice->TransmissionProtocolSupported) { 
                    fpICCDevice->NumofTransmissionProtocolSupported++;          
                }
            }                        

            // No more valid TDx?
            if (!(fpICCDevice->RawATRData[bData] & 0x80)) break;
            bData += FindNumberOfTs(fpICCDevice->RawATRData[bData]);
        }
    }

    return;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   GetDefaultProtocol
//
// Description: Find the First offerred Transmission protocol.
//
// Input: 
//              ICC_DEVICE        *fpICCDevice
//
// Output:
//              TRANSMISSION_PROTOCOL        
//
// Notes:       Section 8.2.3 ISO 7816-3 2006-11-01: TD1 encodes first offered protocol. 
//              If TD1 not present assume T0.
//    
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
TRANSMISSION_PROTOCOL GetDefaultProtocol (
    ICC_DEVICE        *fpICCDevice
)
{

    if (fpICCDevice->AtrData.TD1Present) {
        return fpICCDevice->AtrData.TD1 & 0xf;
    }

    return T0_PROTOCOL;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   FindBestTA1Value
//
// Description: CCID which doesn't perform "Automatic parameter config. based on ATR
//
// Input: 
//              DEV_INFO           *fpDevInfo
//              ICC_DEVICE        *fpICCDevice
//
// Output:
//              UINT8       Best TA1 value
//
// Notes:
//  1. Calculate the Baud rate using TA1 value
//
//  2. If in CCID bNumDataRatesSupported = 0 then any value between dwDatRate 
//     and dwMaxDataRate is supported
//
//  3. Check if ICC baud rate is less tha dwMaxDataRate. If yes use that.
//
//  4. If  bNumDataRatesSupported is not zero get all possible values and try to 
//     match it and use that value.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
UINT8 
FindBestTA1Value (
    DEV_INFO        *fpDevInfo,
    ICC_DEVICE      *fpICCDevice
)
{

    UINT32      ICCBaudrate;
    UINT8       Di = fpICCDevice->GlobalDi;
	SMARTCLASS_DESC	*CCIDDescriptor = (SMARTCLASS_DESC*)fpDevInfo->pCCIDDescriptor;
    UINT8       *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        return 0;
    }
    //
    // If Automatic parameter conf. based on ATR data is 
    //
    if (CCIDDescriptor->dwFeatures & AUTO_PARAMETER_CONFIG) {
        return fpICCDevice->AtrData.TA1;
    }

    ICCBaudrate =   (fpICCDevice->GlobalFmax * 1000 * fpICCDevice->GlobalDi)/fpICCDevice->GlobalFi;      

    if (fpDevInfo->DataRates && fpDevInfo->ClockFrequencies) {
        /*
        // Find the match
        for (i = fpDevInfo->pCCIDDescriptor->bNumDataRatesSupported; i; --i) {
            // Since the values may not match exactly give some leeway
            if (ICCBaudrate  >= (fpDevInfo->DataRates[i] - 1000) && ICCBaudrate  <= (fpDevInfo->DataRates[i] + 1000)){                
                // See whether the matched baud rate can be achieved with the supported frequencies                
                for (j = fpDevInfo->pCCIDDescriptor->bNumDataRatesSupported; j; --j) {
                    if (fpICCDevice->GlobalFmax == fpDevInfo->ClockFrequencies[i]) break;
                }
                if (j) {
                    CalcBaudRate =                 
                }
                else {
                }
                break;
            }
        }
        */
    } else {
        if (ICCBaudrate <= CCIDDescriptor->dwMaxDataRate) {
            return fpICCDevice->AtrData.TA1;
        } else {
            //
            // Can we decrement the Di value and try to match it
            //
            for ( ; Di ; --Di){
                ICCBaudrate =   (fpICCDevice->GlobalFmax * 1000 * Di)/fpICCDevice->GlobalFi;                
                if (ICCBaudrate <= CCIDDescriptor->dwMaxDataRate) {
                    return ((fpICCDevice->AtrData.TA1 & 0xF0) | Di);
                }
            }
        }
    }

    //
    // Worst case return the default value. 
    // Actuall we should fail saying this CCID/ICC combination isn't supported.
    //
    return fpICCDevice->AtrData.TA1;        

}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   CalculateTimingValues
//
// Description: Based on the agreed upon TA1 value and Transmission protocol 
//              calculate the timing values
//
// Input: 
//              DEV_INFO           *fpDevInfo
//              ICC_DEVICE        *fpICCDevice
//
// Output:
//              None
//
// Notes:
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
CalculateTimingValues (
    DEV_INFO          *fpDevInfo,
    ICC_DEVICE        *fpICCDevice
)
{

    UINT8   NValue;
    UINT8   bData;
    UINT8    TDCount = 0;

    fpICCDevice->bmFindIndex = fpICCDevice->AtrData.TA1;

    //
    // NValue defaults to zero if TC1 not present
    //
    NValue = fpICCDevice->AtrData.TC1Present == TRUE ? fpICCDevice->AtrData.TC1 : 0;

    //
    // Calculate 1 etu in micro sec
    //
    fpICCDevice->etu = fpICCDevice->GlobalFi / (fpICCDevice->GlobalDi * fpICCDevice->GlobalFmax); 

    //
    // Extra Gaurd Time GT in etu units (section 8.3)
    //
    if (fpICCDevice->AtrData.TA15Present) {
        fpICCDevice->ExtraGuardTime = 12 + 
                                (NValue / fpICCDevice->GlobalFmax  * fpICCDevice->GlobalFi/ fpICCDevice->GlobalDi);
    } else {
        fpICCDevice->ExtraGuardTime = 12 + (NValue / fpICCDevice->GlobalFmax) ;          
    }

    // Update Wait Time  (see section 10.2)
    // WT = WI * 960 * Fi /f where WI is TC2
    // Default if TC2 is not present
    bData = 10;         

    if (fpICCDevice->AtrData.TC2Present) {
        bData = fpICCDevice->AtrData.TC2;
    }    

    //
    // Calculate WT (wait time between two characters) in ETU units
    //
    fpICCDevice->WTwaittime = 960 * fpICCDevice->GlobalFi/(fpICCDevice->GlobalFmax);


    // update Block Width time and Epilogue bit
    // BWT = 11etu + 2 ^ BWI * 960 * Fd /f  (Section 11.4.3)
    // Default BWI is 4. Bit 7:4 in first TB for T1 encodes BWI
    // Fd = 372 (sec section 8.1)

    // Default values (11.4.3)
    fpICCDevice->BWI  = 4;
    fpICCDevice->CWI =  13;
    fpICCDevice->IFSC = 32;
    fpICCDevice->IFSD = 32;
    fpICCDevice->NAD = 0;

    for (bData = 1;  bData < MAX_ATR_LENGTH; ){

        // Look for the First TD for T= 1. It should from TD2
        if (TDCount < 2) {
            if (fpICCDevice->RawATRData[bData] & 0x80) {
                TDCount++;
                bData += FindNumberOfTs(fpICCDevice->RawATRData[bData]);
                continue;
            } else {
                break;
            }
        }

        // Is it T1?
        if ((fpICCDevice->RawATRData[bData] & 0xF) == 0x1){

            if (fpICCDevice->RawATRData[bData] & 0x10) {
                fpICCDevice->IFSC = fpICCDevice->RawATRData[bData + 1];
            }

            if (fpICCDevice->RawATRData[bData] & 0x20) {
                fpICCDevice->BWI = (fpICCDevice->RawATRData[bData + 2] & 0xF0) >> 4;
                fpICCDevice->CWI = fpICCDevice->RawATRData[bData + 2] & 0xF;
            }

            // Section 11.4.4
            if (fpICCDevice->RawATRData[bData] & 0x40) {
                fpICCDevice->EpilogueFields = (fpICCDevice->RawATRData[bData + 3] & 0x1);
            }

            break;
        }

        //
        // No more valid TDx?
        //
        if (!(fpICCDevice->RawATRData[bData] & 0x80)) break;

        bData += FindNumberOfTs(fpICCDevice->RawATRData[bData]);

    }    

    //
    // Block Widthtime in ETU units
    //
    fpICCDevice->BWT = ((1 << (fpICCDevice->BWI - 1)) * 960 * 372 /(fpICCDevice->GlobalFmax)) + 11;

    PrintTimingInfo(fpICCDevice);

    return;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   IssuePPSCmd
//
// Description: Issue PPS cmd to select T0/T1
//
// Input: 
//              DEV_INFO        *fpDevInfo
//              ICC_DEVICE      *fpICCDevice
//              UINT8           *Data : Points to the buffer which is sent to CCID. 
//                                      Refer Section 9.2 of 7816-3 spec for the format
//
// Output:
//              EFI_STATUS
//
// Notes:
//              This command is issued to CCID which doesn't support AUTO_PARAMETER_CONFIG 
//              or when default values or not acceptable
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
IssuePPSCmd(
    DEV_INFO            *fpDevInfo,
    ICC_DEVICE          *fpICCDevice,
    UINT8               *Data,
    UINT8               DataLength
)
{

    EFI_STATUS    Status = EFI_SUCCESS;
    UINT8        *ResponseBuffer;
    UINT32        ResponseLength = DataLength;
    SMARTCLASS_DESC	*CCIDDescriptor = (SMARTCLASS_DESC*)fpDevInfo->pCCIDDescriptor;
    UINT8        *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        return EFI_DEVICE_ERROR;
    }    
    //
    // Allocate memory for receiving data
    //
    ResponseBuffer = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(DataLength));
    ASSERT(ResponseBuffer);
    if (!ResponseBuffer) {
        return EFI_OUT_OF_RESOURCES;
    }
    MemFill((UINT8 *)ResponseBuffer, DataLength, 0);


    //
    //Check what level of Transmission Protocol is supported
    //
    ResponseLength = 0;
    if (!(CCIDDescriptor->dwFeatures & 0x70000)){
        ResponseLength = 2;                                 // For Character exchange only 2 bytes expected.
    }  


    Status = PCToRDRXfrBlock(fpDevInfo, fpICCDevice, DataLength, Data, 0, ResponseLength);
    if (CCIDDescriptor->dwFeatures & 0x70000){
        ResponseLength = 4;                                 // For TDPU expected data is 4
    }
    Status = RDRToPCDataBlock(fpDevInfo, fpICCDevice, &ResponseLength, ResponseBuffer);

    // If length is not same and only Character level Transmission is supported, 
    // issue another XfrBlock cmd to get the rest of the data
    if ((ResponseLength != DataLength) && !(CCIDDescriptor->dwFeatures & 0x70000)) {

        DataLength = ResponseLength;
        ResponseLength = 2;
        Status = PCToRDRXfrBlock(fpDevInfo, fpICCDevice, 0, Data, 0, ResponseLength);
        Status = RDRToPCDataBlock(fpDevInfo, fpICCDevice, &ResponseLength, ResponseBuffer + DataLength);
    
    }

    //
    // I/P and O/P should be identical for success
    //
    USB_MemFree(ResponseBuffer, (UINT8)GET_MEM_BLK_COUNT(DataLength));

    return Status;
}


//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   VoltageSelection
//
// Description: Based on the dwFeatures register setting, power up CCID/ICC
//
// Input:
//              DEV_INFO           *fpDevInfo,
//              ICC_DEVICE        *fpICCDevice
//
// Output:
//              EFI_STATUS   
//
// Notes:       Based on dwFeatures value from SMART Class Descriptor either 
//              do an automatic Power-on or go through a manual
//              power up sequence and then callect the ATR data.
//    
//    
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
VoltageSelection(
    DEV_INFO          *fpDevInfo,
    ICC_DEVICE        *fpICCDevice
)
{

    EFI_STATUS   Status = EFI_DEVICE_ERROR;
    EFI_STATUS   ATRStatus = EFI_DEVICE_ERROR;
	SMARTCLASS_DESC	*CCIDDescriptor = (SMARTCLASS_DESC*)fpDevInfo->pCCIDDescriptor;
    //
    // Get all voltage level supported by CCID
    //
    UINT8        VoltageLevelCCID = CCIDDescriptor->bVoltageSupport;        
    //
    // Select the lowest voltage
    //
    UINT8        VoltageMask = VOLT_18;                                                
    //
    // Successful poweron will result in ATR data
    //
    UINT32       BufferLength = MAX_ATR_LENGTH;                                        
    UINT8        *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        return EFI_DEVICE_ERROR;
    }
    //
    // Make sure the first selection is valid
    //
    do {

        if (VoltageLevelCCID & VoltageMask) {
            break;
        }

        VoltageMask = VoltageMask >> 1;

    }while (VoltageMask);

    //
    // If Automatic Voltage selection is supported go for it. 
    // Discard the initialization done above
    if (CCIDDescriptor->dwFeatures & AUTO_ACTIVATION_VOLT_SELECTION){
        //
        // Automatic Voltage selection is supported            
        //
        VoltageLevelCCID = AUTO_VOLT;
        VoltageMask = 0;
    }

    do {

        //
        // Issue the cmd to Power it up
        //
        Status = PCtoRDRIccPowerOn (fpDevInfo, 
                                    fpICCDevice, 
                                    ((VoltageLevelCCID & VoltageMask) == 4) ?  3 : VoltageMask);

        if(EFI_ERROR(Status)) { 
            break;
        }

        //
        // Get the response to IccPoweron
        //
        BufferLength = MAX_ATR_LENGTH;
        Status = RDRToPCDataBlock ( fpDevInfo, 
                                    fpICCDevice, 
                                    &BufferLength, 
                                    fpICCDevice->RawATRData
                                    );

        //
        // if successfully powered up, ATR data should be available
        //
        if (!EFI_ERROR(Status) && BufferLength) {

            fpICCDevice->ConfiguredStatus |= (ICCPRESENT | VOLTAGEAPPLIED | ATRDATAPRESENT);

            PrintATRData(fpICCDevice->RawATRData);
        
            // From the ATR data, get the required information
            UpdateATRDataInfo(fpDevInfo, fpICCDevice);

            // ATR data got successfully and configured successfully. 
            ATRStatus = EFI_SUCCESS;
            break;

        }

        //
        // if Card not present    
        //
        if ((fpICCDevice->bStatus & 7) == 2) {
            Status = EFI_NOT_FOUND;
            break;
        }

        //
        // ICC is present but some error
        //
        fpICCDevice->ConfiguredStatus |= ICCPRESENT;

        //
        // Card present but voltage selection is not OK. Power it off and select next voltage
        //
        Status =  PCtoRDRIccPowerOff (fpDevInfo,  fpICCDevice);
        if (EFI_ERROR(Status)) break;

        Status = RDRToPCSlotStatus(fpDevInfo, fpICCDevice);
        if (EFI_ERROR(Status)) break;

        VoltageMask = VoltageMask >> 1;

        //
        // 10 msec delay before applying the next power class Spec 6.2.3
        //
        FixedDelay (10 * 1000);

    } while (VoltageMask);

    // Return the status of the ATR data read and configuration
    return ATRStatus;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   RateAndProtocolManagement
//
// Description: Based on the ATR data and the dwFeature register contend 
//              do the Rate and Protocol programming
//
// Input:
//              DEV_INFO           *fpDevInfo
//              ICC_DEVICE        *fpICCDevice
//
// Output:
//              EFI_STATUS
//
// Notes:       Based on data received from Power-on sequence (ATR data) and dwFetaures value, 
//              Speed of communicatin is established.
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
RateAndProtocolManagement(
    DEV_INFO          *fpDevInfo,
    ICC_DEVICE        *fpICCDevice
)
{

    EFI_STATUS              Status = EFI_SUCCESS;
    PROTOCOL_DATA_T1        Data = {0};
    UINT8                   PPSData[] = {0xFF, 0x10, 0x11, 0x00};        
    UINT8                   Counter;
	SMARTCLASS_DESC			*CCIDDescriptor = (SMARTCLASS_DESC*)fpDevInfo->pCCIDDescriptor;
    UINT32                  ClockFrequency = CCIDDescriptor->dwMaximumClock;
    UINT32                  DataRate = CCIDDescriptor->dwMaxDataRate;
    BOOLEAN                 FlagToIssueSetParameters = FALSE;
    TRANSMISSION_PROTOCOL   FirstOfferredProtocol;
    UINT8                   DefaultTA1 = fpICCDevice->AtrData.TA1;
    UINT8                   SetIFS[] = {0xFC};
    UINT32                  ResponseLength;
    UINT8                   ResponseBuffer[20];
    UINT32                  ExchangeLevel = (CCIDDescriptor->dwFeatures & 0x70000);
    UINT8                   *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        return EFI_DEVICE_ERROR;
    }    
    FirstOfferredProtocol = GetDefaultProtocol(fpICCDevice);

    fpICCDevice->bProtocolNum = (UINT8)FirstOfferredProtocol;

    //
    // Check whether TA1 value is good enough for the reader. If not get the right value
    //
    fpICCDevice->AtrData.TA1 = FindBestTA1Value(fpDevInfo, fpICCDevice);    


    //
    // Check if more than one transmission protocol is supported. 
    // If yes then there may be a need for PPSCmd (ISO 7816-3:2006(E) Sec: 6.3.1)
    // Check if Automatic PPS negotiation done by CCID or not. If not issue one.
    // If TA2 is present Card is in Specific mode. So no need for PPS (7816-3:2006 see sec 6.3 fig 4)
    //

    // When PPS exchange must be made? (Page 19 CCID Rev 1.1) 
    // 1. If both AUTO_PPS_NEGOTIATION_CCID AND AUTO_PPS_NEGOTIATION_ACTIVE are not set PPS must be given in case of TDPU or Character
    //                          OR
    // 2. if AUTO_PPS_NEGOTIATION_ACTIVE is present AND TA2 not present AND the preferred protocol isn't USE_T0_T1_PROTOCOL

    if (((CCIDDescriptor->dwFeatures & (AUTO_PPS_NEGOTIATION_CCID | AUTO_PPS_NEGOTIATION_ACTIVE)) == 0 &&
            (ExchangeLevel <= 0x10000 ) && !fpICCDevice->AtrData.TA2Present) ||
        ((CCIDDescriptor->dwFeatures & AUTO_PPS_NEGOTIATION_ACTIVE) && !fpICCDevice->AtrData.TA2Present && 
            fpICCDevice->NumofTransmissionProtocolSupported > 1 && FirstOfferredProtocol != USE_T0_T1_PROTOCOL)) {
        //
        // Update PPS data if in case PPSCmd needs to be issued
        //
        PPSData[1] |= FirstOfferredProtocol;

        //
        // Update PPS2
        //
        PPSData[2] = fpICCDevice->AtrData.TA1;        
    
        //
        // Update checksum
        //
        for (Counter = 0; Counter < sizeof (PPSData) - 1; Counter++) {
            PPSData[sizeof (PPSData) - 1] ^= PPSData[Counter];
        }
    
        Status = IssuePPSCmd(fpDevInfo, fpICCDevice, PPSData, sizeof (PPSData));
    }
          
    if (CCIDDescriptor->dwFeatures & AUTO_PARAMETER_CONFIG) {   

        //
        // Issue GetParameters to get the Transmission Protocol and other parameters
        //
        Status = PCToRDRGetParameters(fpDevInfo, fpICCDevice);
        if (EFI_ERROR(Status)) return Status;
    
        Status = RDRToPCParameters(fpDevInfo, fpICCDevice);
        if (EFI_ERROR(Status)) return Status;        

        fpICCDevice->ExtraGuardTime = fpICCDevice->bGuardTime;
        fpICCDevice->WTwaittime = fpICCDevice->bWaitingInteger;
        fpICCDevice->IFSC =  fpICCDevice->bIFSC;
        fpICCDevice->NAD = fpICCDevice->nNadValue;

    } else {

        //
        // Now that the TA1 value and the protocol has been finalized, 
        // It is time to calculate the different timing parameters.
        //
        CalculateTimingValues (fpDevInfo, fpICCDevice);
    }

    //
    //If Automatic Parameters config. based on ATR data is not 
    //supported then issue SetParameters cmd
    //
    if (!(CCIDDescriptor->dwFeatures & AUTO_PPS_NEGOTIATION_ACTIVE)){  // 0x80

        //
        // Use the superset of the T0/T1 structure (ie T1 structure) even if it is T0. It should work.
        //
        Data.bmFindDindex = fpICCDevice->bmFindIndex;
        Data.bmTCCKST1 = fpICCDevice->bProtocolNum == 0  ? 0 : (fpICCDevice->EpilogueFields | 0x10);
        Data.bGuardTimeT1 = fpICCDevice->ExtraGuardTime;

        Data.bWaitingIntergersT1 = fpICCDevice->bProtocolNum == 0  ? 
                                fpICCDevice->WTwaittime : (fpICCDevice->BWI << 4 | fpICCDevice->CWI);

        Data.bClockStop = fpICCDevice->bClockStop;
        Data.bIFSC = fpICCDevice->IFSC;
        Data.bNadValue = fpICCDevice->NAD;
            
        Status = PCToRDRSetParameters(fpDevInfo, fpICCDevice, fpICCDevice->bProtocolNum, (VOID *)&Data);

        if (!EFI_ERROR(Status)){
            Status = RDRToPCParameters(fpDevInfo, fpICCDevice);
        } else {
            //
            // Handle failure cases. Look at it later.
            //
        }     
    }

    //
    // Based on T0 or T1 update Waittime. For T0 use WTWaittime, for T1 use BWT. 
    //
    if (fpICCDevice->bProtocolNum) {
        fpICCDevice->WaitTime = fpICCDevice->BWT;
    } else {
        fpICCDevice->WaitTime = fpICCDevice->WTwaittime;            
    }

    //
    // If Automatic ICC Clock Freq AND Automatic Buad Rate selection 
    // isn't supported issue SetDataRateAndClock cmd
    //
    if (!(CCIDDescriptor->dwFeatures & (AUTO_BAUD_RATE_SELECTION |AUTO_ICC_CLOCK_FREQ))){

    }

    //
    // Check if IFSC/IFSD needs to be increased. Default value is 0x20. T1 and TDPU/Char needs this cmd.
    //
    if (fpICCDevice->bProtocolNum){    
        switch(CCIDDescriptor->dwFeatures & 0x70000) { 
            case CHARACTER_LEVEL_EXCHANGE:
                // Both SUZCR90 and O2Micro oz77c6l1 didn't respond to SBlock call below without this delay
                FixedDelay(10 * 1000);      // 10msec delay. No break. Let the flow continue below.
            case TDPU_LEVEL_EXCHANGE:
              ResponseLength = 1;
                SetIFS[0] = (UINT8)CCIDDescriptor->dwMaxIFSD;          
                Status = TxRxT1TDPUChar (fpDevInfo, fpICCDevice, sizeof (SetIFS), SetIFS, IFS_REQUEST, &ResponseLength, ResponseBuffer);
                // Update the received IFSD
                if (!EFI_ERROR(Status) && ResponseLength == 1){
                    fpICCDevice->IFSD = ResponseBuffer[0];
                }
                break;
            default:
                break;
        }
    } 
    return Status;

}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:    ConfigureCCID
//
// Description: This function powers up, sets the clock/rate etc 
//              (configure CCID based on device capability)
//
// Input: 
//              DEV_INFO           *fpDevInfo,
//              ICC_DEVICE        *fpICCDevice
//
// Output:
//              EFI_STATUS
//
// Notes:       VoltageSelection, RateAndProtocolManagement
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
ConfigureCCID(
    DEV_INFO          *fpDevInfo,
    ICC_DEVICE        *fpICCDevice
)
{
    EFI_STATUS  Status;
    UINT8       RetryCount = 3;

    //
    // Power up the device
    //
    do {
        Status = VoltageSelection(fpDevInfo, fpICCDevice);
        RetryCount--;

        //    
        // check for errors and do try to recover
        //
        if(EFI_ERROR(Status) || fpICCDevice->bStatus) {
            //
            // If card present but not powered up retry it. 
            // If card not present the exit immediatly
            //
            if (fpICCDevice->bStatus ==  2) {
                break;
            }            
        } else {
            break;
        }

    }while (RetryCount);

    //    
    //Configure the data Rate and select the Protocol
    //
    if (!EFI_ERROR(Status)){
        Status = RateAndProtocolManagement (fpDevInfo, fpICCDevice);
    }
    
    if (EFI_ERROR(Status)) {
        fpICCDevice->ConfiguredStatus = CONFIGFAILED;
    }

    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDIssueBulkTransfer
//
// Description: This function executes a bulk transaction on the USB. The
//              transfer may be either DATA_IN or DATA_OUT packets containing
//              data sent from the host to the device or vice-versa. This
//              function wil not return until the request either completes
//              successfully or completes with error (due to time out, etc.)
//              Size of data can be upto 64K
//
// Input:   - DeviceInfo structure (if available else 0)
//          - Transfer direction
//              Bit 7   : Data direction
//                          0 Host sending data to device
//                          1 Device sending data to host
//              Bit 6-0 : Reserved
//          - Buffer containing data to be sent to the device or
//            buffer to be used to receive data. Value in
//          - Length request parameter, number of bytes of data
//            to be transferred in or out of the host controller
//
// Output:  Amount of data transferred
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT32
USBCCIDIssueBulkTransfer (
    DEV_INFO*   fpDevInfo, 
    UINT8       bXferDir,
    UINT8*      fpCmdBuffer, 
    UINT32      dSize
)
{
    return (*gUsbData->aHCDriverTable[GET_HCD_INDEX(gUsbData->HcTable
                [fpDevInfo->bHCNumber - 1]->bHCType)].pfnHCDBulkTransfer)
                (gUsbData->HcTable[fpDevInfo->bHCNumber -1],
                fpDevInfo, bXferDir,
                fpCmdBuffer, dSize);

    // Handle Bulk Transfer error here

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDIssueControlTransfer
//
// Description: Issues Control Pipe request to default pipe
//
// Parameters:     pDevInfo    DeviceInfo structure (if available else 0)
//          wRequest    Request type (low byte)
//              Bit 7   : Data direction
//                  0 = Host sending data to device
//                  1 = Device sending data to host
//              Bit 6-5 : Type
//                  00 = Standard USB request
//                  01 = Class specific
//                  10 = Vendor specific
//                  11 = Reserved
//              Bit 4-0 : Recipient
//                  00000 = Device
//                  00001 = Interface
//                  00010 = Endpoint
//                  00100 - 11111 = Reserved
//              Request code, a one byte code describing
//              the actual device request to be executed
//              (ex: 1 : ABORT, 2 : GET_CLOCK_FREQUENCIES, 3: GET_DATA_RATES)
//      wIndex      wIndex request parameter (meaning varies)
//      wValue      wValue request parameter (meaning varies)
//      fpBuffer    Buffer containing data to be sent to the
//              device or buffer to be used to receive data
//      wLength     wLength request parameter, number of bytes
//              of data to be transferred in or out
//              of the host controller
//
// Output:  Number of bytes actually transferred
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT32
USBCCIDIssueControlTransfer(
    DEV_INFO*   fpDevInfo,     
    UINT16      wRequest,
    UINT16      wIndex,
    UINT16      wValue,
    UINT8       *fpBuffer,
    UINT16      wLength
)
{

    //
    // Not tested due to lack of H/W which supports it
    //
    return (*gUsbData->aHCDriverTable[GET_HCD_INDEX(gUsbData->HcTable
                [fpDevInfo->bHCNumber - 1]->bHCType)].pfnHCDControlTransfer)
                (gUsbData->HcTable[fpDevInfo->bHCNumber - 1],
                        fpDevInfo,
                        wRequest,
                        wIndex,
                        wValue,
                        fpBuffer,
                        wLength);

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   FindNumberOfTs
//
// Description: Returns the # of Ts present in TDx
//
// Input:
//              UINT8    Data
//
// Output:
//              UINT8 - Returns number of TDx present in ATR data
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
UINT8
FindNumberOfTs(
    UINT8    Data
)
{
    UINT8    Count = 0;
    UINT8    Mask = 0x10;

    for ( ;Mask; Mask = Mask << 1){
        if (Data & Mask) { 
            Count++;
        }
    }

    return Count;    
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   PrintPCParameters
//
// Description: This function prints the information gathered from GetPCParameters
//
// Input:
//              UINT8 * Data   
//
// OutPut:
//              None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID 
PrintPCParameters(
    UINT8 * Data
)
{

    USB_DEBUG (DEBUG_LEVEL_3, "bProtocolNum     : %02X\n", Data[0]); 
    USB_DEBUG (DEBUG_LEVEL_3, "bmFindexDIndex   : %02X\n", Data[1]); 
    USB_DEBUG (DEBUG_LEVEL_3, "bmTCCKST0        : %02X\n", Data[2]); 
    USB_DEBUG (DEBUG_LEVEL_3, "bGaurdTime       : %02X\n", Data[3]); 
    USB_DEBUG (DEBUG_LEVEL_3, "bWaitingInterger : %02X\n", Data[4]); 
    USB_DEBUG (DEBUG_LEVEL_3, "bClockStop       : %02X\n", Data[5]); 
    USB_DEBUG (DEBUG_LEVEL_3, "bIFSC            : %02X\n", Data[6]); // Valid only for T1    
    USB_DEBUG (DEBUG_LEVEL_3, "bNadValue        : %02X\n", Data[7]); // Valid only for T1

    return;
} 


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   PrintTimingInfo
//
// Description: This function prints the information gathered from ATR data
//
// Input:  
//              ICC_DEVICE    *fpICCDevice
//
// Output:
//              None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
PrintTimingInfo(
    ICC_DEVICE    *fpICCDevice
)
{

    USB_DEBUG (DEBUG_LEVEL_3, "etu              : %02X  \n", fpICCDevice->etu); 
    USB_DEBUG (DEBUG_LEVEL_3, "GlobalFi         : %04x  \n", fpICCDevice->GlobalFi); 
    USB_DEBUG (DEBUG_LEVEL_3, "GlobalFmax       : %02X  \n", fpICCDevice->GlobalFmax); 
    USB_DEBUG (DEBUG_LEVEL_3, "GlobalDi         : %02X  \n", fpICCDevice->GlobalDi); 

    USB_DEBUG (DEBUG_LEVEL_3, "SpecificMode     : %02X  \n", fpICCDevice->SpecificMode); 

    USB_DEBUG (DEBUG_LEVEL_3, "ClassABC         : %02X  \n", fpICCDevice->ClassABC); 
    USB_DEBUG (DEBUG_LEVEL_3, "StopClockSupport : %02X  \n", fpICCDevice->StopClockSupport); 

    USB_DEBUG (DEBUG_LEVEL_3, "ExtraGuardTime   : %02X  \n", fpICCDevice->ExtraGuardTime); 
    USB_DEBUG (DEBUG_LEVEL_3, "WTwaittime       : %08x  \n", fpICCDevice->WTwaittime); 

    USB_DEBUG (DEBUG_LEVEL_3, "BWI              : %02X  \n", fpICCDevice->BWI); 
    USB_DEBUG (DEBUG_LEVEL_3, "CWI              : %02X  \n", fpICCDevice->CWI); 
    USB_DEBUG (DEBUG_LEVEL_3, "IFSC             : %02X  \n", fpICCDevice->IFSC); 
    USB_DEBUG (DEBUG_LEVEL_3, "NAD              : %02X  \n", fpICCDevice->NAD); 
    USB_DEBUG (DEBUG_LEVEL_3, "EpilogueFields   : %02X  \n", fpICCDevice->EpilogueFields); 
    USB_DEBUG (DEBUG_LEVEL_3, "BWT              : %02X  \n", fpICCDevice->BWT); 

    return;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   PrintATRData
//
// Description: This function Prints the RAW ATR Data
//
// Input:
//              UINT8       *ATRData
//
// Output:
//              None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
PrintATRData(
    UINT8            *ATRData
)
{

    UINT8        TDx = 2;
    UINT8        i;


    USB_DEBUG (DEBUG_LEVEL_3, "    ATR Data \n");

    for (i=0; i< 32; i++) {
        USB_DEBUG (DEBUG_LEVEL_3, "%02X ", ATRData[i]);
    }

    i = 0;

    USB_DEBUG (DEBUG_LEVEL_3, "\nTS  : %02X  \n", ATRData[i++]); 

    TDx = ATRData[i];
    USB_DEBUG (DEBUG_LEVEL_3, "T0  : %02X  \n", ATRData[i++]); 
    USB_DEBUG (DEBUG_LEVEL_3, "TA1 : %02X  \n", TDx & 0x10 ? ATRData[i++] : 0); 
    USB_DEBUG (DEBUG_LEVEL_3, "TB1 : %02X  \n", TDx & 0x20 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TC1 : %02X  \n", TDx & 0x40 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TD1 : %02X  \n", TDx & 0x80 ? ATRData[i++] : 0);

    if (!(TDx & 0x80)) return;
    TDx = ATRData[i-1];

 
    USB_DEBUG (DEBUG_LEVEL_3, "TA2 : %02X \n", TDx & 0x10 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TB2 : %02X \n", TDx & 0x20 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TC2 : %02X \n", TDx & 0x40 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TD2 : %02X \n", TDx & 0x80 ? ATRData[i++] : 0);

    if (!(TDx & 0x80)) return;
    TDx = ATRData[i-1];

    USB_DEBUG (DEBUG_LEVEL_3, "TA3 : %02X \n", TDx & 0x10 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TB3 : %02X \n", TDx & 0x20 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TC3 : %02X \n", TDx & 0x40 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TD3 : %02X \n", TDx & 0x80 ? ATRData[i++] : 0);

    if (!(TDx & 0x80)) return;
    TDx = ATRData[i-1];

    USB_DEBUG (DEBUG_LEVEL_3, "TA4 : %02X \n", TDx & 0x10 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TB4 : %02X \n", TDx & 0x20 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TC4 : %02X \n", TDx & 0x40 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TD4 : %02X \n", TDx & 0x80 ? ATRData[i++] : 0);

    if (!(TDx & 0x80)) return;
    TDx = ATRData[i-1];

    USB_DEBUG (DEBUG_LEVEL_3, "TA5 : %02X \n", TDx & 0x10 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TB5 : %02X \n", TDx & 0x20 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TC5 : %02X \n", TDx & 0x40 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TD5 : %02X \n", TDx & 0x80 ? ATRData[i++] : 0);

    if (!(TDx & 0x80)) return;
    TDx = ATRData[i-1];

    USB_DEBUG (DEBUG_LEVEL_3, "TA6 : %02X \n", TDx & 0x10 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TB6 : %02X \n", TDx & 0x20 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TC6 : %02X \n", TDx & 0x40 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TD6 : %02X \n", TDx & 0x80 ? ATRData[i++] : 0);

    if (!(TDx & 0x80)) return;
    TDx = ATRData[i-1];

    USB_DEBUG (DEBUG_LEVEL_3, "TA7 : %02X \n", TDx & 0x10 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TB7 : %02X \n", TDx & 0x20 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TC7 : %02X \n", TDx & 0x40 ? ATRData[i++] : 0);
    USB_DEBUG (DEBUG_LEVEL_3, "TD7 : %02X \n", TDx & 0x80 ? ATRData[i++] : 0);

    return;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   PrintDescriptorInformation
//
// Description: Prints SMART class Descriptor data
//
// Input:
//              SMARTCLASS_DESC *fpCCIDDesc
//
// Output:
//              None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
VOID
PrintDescriptorInformation (
    SMARTCLASS_DESC *fpCCIDDesc
)
{

    CHAR8    *Strings[] = {"CHARACTER", "TDPU", "Short ADPU", "Extended ADPU"};
    UINT8   Exchange = (fpCCIDDesc->dwFeatures & 0x70000) >> 16;

    USB_DEBUG (DEBUG_LEVEL_3, "Sizeof SMART Class Descriptor :  %X\n", sizeof (SMARTCLASS_DESC));
    USB_DEBUG (DEBUG_LEVEL_3, "bDescLength            :  %04X\n", fpCCIDDesc->bDescLength);
    USB_DEBUG (DEBUG_LEVEL_3, "bDescType              :  %04X\n", fpCCIDDesc->bDescType);
    USB_DEBUG (DEBUG_LEVEL_3, "bcdCCID                :  %04X\n", fpCCIDDesc->bcdCCID);
    USB_DEBUG (DEBUG_LEVEL_3, "bMaxSlotIndex          :  %04X\n", fpCCIDDesc->bMaxSlotIndex);
    USB_DEBUG (DEBUG_LEVEL_3, "bVoltageSupport        :  %04X\n", fpCCIDDesc->bVoltageSupport);
    USB_DEBUG (DEBUG_LEVEL_3, "dwProtocols            :  %04X\n", fpCCIDDesc->dwProtocols);
    USB_DEBUG (DEBUG_LEVEL_3, "dwDefaultClock         :  %04X\n", fpCCIDDesc->dwDefaultClock);
    USB_DEBUG (DEBUG_LEVEL_3, "dwMaximumClock         :  %04X\n", fpCCIDDesc->dwMaximumClock);
    USB_DEBUG (DEBUG_LEVEL_3, "bNumClockSupported     :  %04X\n", fpCCIDDesc->bNumClockSupported);
    USB_DEBUG (DEBUG_LEVEL_3, "dwDataRate             :  %04X\n", fpCCIDDesc->dwDataRate);
    USB_DEBUG (DEBUG_LEVEL_3, "dwMaxDataRate          :  %04X\n", fpCCIDDesc->dwMaxDataRate);
    USB_DEBUG (DEBUG_LEVEL_3, "bNumDataRatesSupported :  %04X\n", fpCCIDDesc->bNumDataRatesSupported);
    USB_DEBUG (DEBUG_LEVEL_3, "dwMaxIFSD              :  %04X\n", fpCCIDDesc->dwMaxIFSD);
    USB_DEBUG (DEBUG_LEVEL_3, "dwSynchProtocols       :  %04X\n", fpCCIDDesc->dwSynchProtocols);
    USB_DEBUG (DEBUG_LEVEL_3, "dwMechanical           :  %04X\n", fpCCIDDesc->dwMechanical);
    USB_DEBUG (DEBUG_LEVEL_3, "dwFeatures             :  %04X\n", fpCCIDDesc->dwFeatures);
    USB_DEBUG (DEBUG_LEVEL_3, "bClassGetResponse      :  %04X\n", fpCCIDDesc->dwMaxCCIDMessageLength);
    USB_DEBUG (DEBUG_LEVEL_3, "bClassGetResponse      :  %04X\n", fpCCIDDesc->bClassGetResponse);
    USB_DEBUG (DEBUG_LEVEL_3, "bClassEnvelope         :  %04X\n", fpCCIDDesc->bClassEnvelope);
    USB_DEBUG (DEBUG_LEVEL_3, "wLcdLayout             :  %04X\n", fpCCIDDesc->wLcdLayout);
    USB_DEBUG (DEBUG_LEVEL_3, "bPINSupport            :  %04X\n", fpCCIDDesc->bPINSupport);
    USB_DEBUG (DEBUG_LEVEL_3, "bMaxCCIDBusySlots      :  %04X\n", fpCCIDDesc->bMaxCCIDBusySlots);

    USB_DEBUG (DEBUG_LEVEL_3, "*************************************\n"); 
    USB_DEBUG (DEBUG_LEVEL_3, " Device is in:"); 
    USB_DEBUG (DEBUG_LEVEL_3, "%s Exchange mode\n", Strings[Exchange]); 
    USB_DEBUG (DEBUG_LEVEL_3, "*************************************\n"); 

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCID_ProcessInterruptData
//
// Description: This routine is called when InterruptIN messages is generated
//      
// Input:       pHCStruc    Pointer to HCStruc
//              pDevInfo    Pointer to device information structure
//              pTD         Pointer to the polling TD
//              pBuffer     Pointer to the data buffer
//
// Output:
//              UEB_ERROR/USB_SUCCESS
//
// Notes:       When an ICC card is inserted or removed Interrupt message is generated.   
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USBCCID_ProcessInterruptData (
    HC_STRUC    *HcStruc,
    DEV_INFO    *DevInfo,
    UINT8       *Td,
    UINT8       *Buffer,
    UINT16      DataLength
)
{

    EFI_STATUS      Status;
    UINT8           Data;
    UINT8           Slot = 0;
    UINT8           bmSlotICCByte = 0;
    UINT32          SlotICCStatus = *(UINT32 *)(Buffer + 1);
	SMARTCLASS_DESC	*CCIDDescriptor = (SMARTCLASS_DESC*)DevInfo->pCCIDDescriptor;
    UINT8           *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);

    if (((UINT8*)DevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)DevInfo->pCCIDDescriptor > MemBlockEnd)) {
        return USB_ERROR;
    }

    USB_DEBUG(DEBUG_LEVEL_3, "USBCCID_ProcessInterruptData.... %X %X %X %X\n", 
                *Buffer, *(Buffer +1), *(Buffer + 2), *(Buffer + 3));


    switch (*Buffer) {

        //
        // ICC Card either inserted or Removed
        //
        case RDR_TO_PC_NOTIFYSLOTCHANGE:        

            //
            // Find the # of bytes in this notification
            //
            Slot = CCIDDescriptor->bMaxSlotIndex + 1; // Make it 1 based
            bmSlotICCByte = (CCIDDescriptor->bMaxSlotIndex + 1) >> 2;

            if (Slot & 0x3) { 
                bmSlotICCByte++;
            }

            Slot = 0;
            do {
                Data = (SlotICCStatus >> Slot) & 0x3;
                //
                // Is there a change in status
                //
                if ((Data & 0x3) == 3) {                
                    Status = ICCInsertEvent (DevInfo, Slot);
                }
                if ((Data & 0x3) == 2) {                
                    Status = ICCRemovalEvent (DevInfo, Slot);
                }
                  Slot++;
            } while (Slot < (CCIDDescriptor->bMaxSlotIndex + 1));                        

            break;

        case RDR_TO_PC_HARDWAREERROR:        

            USB_DEBUG(DEBUG_LEVEL_3, "RDR To PC Hardware Error Slot %X Sequence %X Error Code %X \n", 
                            *Buffer, *(Buffer +1), *(Buffer + 2));
            break;

        default:
            break;
    }

    return USB_SUCCESS;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   ICCRemovalEvent
//
// Description: In response to Device removal, Interrupt-in message is received. 
//              Icc Device is removed from the linked list.
//
// Input:
//    DEV_INFO    *fpDevInfo,
//    UINT8        Slot
//
// Output:
//    EFI_STATUS    
//
// Notes: 
//    
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
ICCRemovalEvent(
        DEV_INFO    *fpDevInfo,
        UINT8        Slot
)
{

    ICC_DEVICE        *fpICCDevice;
    
    fpICCDevice = GetICCDevice(fpDevInfo, Slot);
   
    if (fpICCDevice) {

        // Don't free up the memory. EFI driver (EfiUsbCCID) makes use of this data area to 
        // find whether ICC has been removed or added.
        // Before freeing up, clear the bytes

//        MemFill((UINT8 *)fpICCDevice, sizeof(ICC_DEVICE), 0);

        //
        //Free up the memory and remove it from linked list
        //
//        DListDelete (&(fpDevInfo->ICCDeviceList), &(fpICCDevice->ICCDeviceLink));
//        USB_MemFree(fpICCDevice, (UINT8)GET_MEM_BLK_COUNT(sizeof(ICC_DEVICE)));

        if (fpICCDevice->ConfiguredStatus) {
            fpICCDevice->ConfiguredStatus = 0;
        } else {
            //
            // Handle if IccRemovalEven is called multiple times
            //
            return EFI_SUCCESS;
        }

        USB_DEBUG(DEBUG_LEVEL_3, "ICC device removed - Slot : %X\n", Slot);

        if (gUsbData->dUSBStateFlag & USB_FLAG_RUNNING_UNDER_EFI) {
            ICC_SmiQueuePut((void *)fpICCDevice);
        }
    }

    USB_DEBUG(DEBUG_LEVEL_3, "Removal: fpDevInfo %X fpICCDevice %X\n", fpDevInfo, fpICCDevice);

    return EFI_SUCCESS;
}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   ICCInsertEvent
//
// Description: In response to Device Insertion, Interrupt-in message is received. 
//              Icc Device is added to the linked list and configured.
//
// Input:
//              DEV_INFO    *fpDevInfo,
//              UINT8        Slot
//
// Output:
//              EFI_STATUS    
//
// Notes:       ConfigureCCID, GetICCDevice
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
ICCInsertEvent(
    DEV_INFO    *fpDevInfo,
    UINT8       Slot
)
{

    EFI_STATUS        Status;
    ICC_DEVICE        *fpICCDevice;
    BOOLEAN         NewDeviceAdded = FALSE;

    //
    // Check if the device already exist. if so use it.
    //
    fpICCDevice = GetICCDevice(fpDevInfo, Slot);

    if (!fpICCDevice) {
        //
        // Alocate memory for ICC_DEVICE and attach it to the linked list
        //
        fpICCDevice = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(ICC_DEVICE)));
        ASSERT(fpICCDevice);
        if (!fpICCDevice) {
            return EFI_OUT_OF_RESOURCES;
        }    
        MemFill((UINT8 *)fpICCDevice, sizeof(ICC_DEVICE), 0);

        //
        // Add to the slot list
        //
#if USB_RUNTIME_DRIVER_IN_SMM
        if (fpDevInfo->ICCDeviceList.pHead != NULL) {
            Status = AmiValidateMemoryBuffer((VOID*)(fpDevInfo->ICCDeviceList.pHead), 
                            (UINT32)sizeof(DLINK));
            if (EFI_ERROR(Status)) {
                return EFI_DEVICE_ERROR;
            }
        }
        if (fpDevInfo->ICCDeviceList.pTail != NULL) {
            Status = AmiValidateMemoryBuffer((VOID*)(fpDevInfo->ICCDeviceList.pTail), 
                            (UINT32)sizeof(DLINK));
            if (EFI_ERROR(Status)) {
                return EFI_DEVICE_ERROR;
            }
        }
#endif
        DListAdd(&(fpDevInfo->ICCDeviceList), &(fpICCDevice->ICCDeviceLink)); 
        NewDeviceAdded = TRUE;

    }

#if CCID_USE_INTERRUPT_INSERTION_REMOVAL
    // Handle Multiple ICCInsertEvent calls. Some cards generate 
    // Interrupt in Interrupt-IN endpoint and some don't.
    // For card which don't generate the intterupt, CCID API should be used to power up the device.
    if (fpICCDevice->ConfiguredStatus) {

        if (fpICCDevice->ConfiguredStatus == CONFIGFAILED) {
            return EFI_DEVICE_ERROR;
        }
        return EFI_SUCCESS;

    }
#endif
    
    fpICCDevice->ChildHandle = 0;
    fpICCDevice->Slot = Slot;
    fpICCDevice->WaitTime = INITWAITTIME;

    Status = ConfigureCCID(fpDevInfo, fpICCDevice);

#if CCID_USE_INTERRUPT_INSERTION_REMOVAL
    if(EFI_ERROR(Status)){

        //
        //Free up the memory and remove it from linked list
        //
#if USB_RUNTIME_DRIVER_IN_SMM
        if (fpDevInfo->ICCDeviceList.pHead != NULL) {
            Status = AmiValidateMemoryBuffer((VOID*)(fpDevInfo->ICCDeviceList.pHead), 
                            (UINT32)sizeof(DLINK));
            if (EFI_ERROR(Status)) {
                return EFI_DEVICE_ERROR;
            }
        }
        if (fpDevInfo->ICCDeviceList.pTail != NULL) {
            Status = AmiValidateMemoryBuffer((VOID*)(fpDevInfo->ICCDeviceList.pTail), 
                            (UINT32)sizeof(DLINK));
            if (EFI_ERROR(Status)) {
                return EFI_DEVICE_ERROR;
            }
        }
#endif
        DListDelete (&(fpDevInfo->ICCDeviceList), &(fpICCDevice->ICCDeviceLink));
        USB_MemFree(fpICCDevice, (UINT8)GET_MEM_BLK_COUNT(sizeof(ICC_DEVICE)));

    } else {
        USB_DEBUG(DEBUG_LEVEL_3, "ICC device added - Slot : %X\n", Slot);
    
        if (gUsbData->dUSBStateFlag & USB_FLAG_RUNNING_UNDER_EFI) {
            ICC_SmiQueuePut((void *)fpICCDevice);
        }
    }

#else
    //
    // Even if configuration failed install the protocol in polling mode.         
    //
    USB_DEBUG(DEBUG_LEVEL_3, "ICC device added - Slot : %X\n", Slot);
    
    if ((gUsbData->dUSBStateFlag & USB_FLAG_RUNNING_UNDER_EFI) && NewDeviceAdded) {
        ICC_SmiQueuePut((void *)fpICCDevice);
    }
#endif

    USB_DEBUG(DEBUG_LEVEL_3, "Insert : fpDevInfo %X fpICCDevice %X\n", fpDevInfo, fpICCDevice);

    return Status;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
//
// Procedure:   ICC_SmiQueuePut
//
// Description: Puts the pointer  into the queue for processing.
//              updates queue head and tail. This data is read from EfiUSBCCID.C 
//              which installs AMI_CCID_IO_PROTOCOL
//
// Input:
//              (void *)fpICCDevice
//
// Output:
//              None
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
ICC_SmiQueuePut(
    VOID * d
)
{
    QUEUE_T* q = &gUsbData->ICCQueueCnnctDisc;

    while (q->head >= q->maxsize) {
        q->head -= q->maxsize;
    }

    q->data[q->head++] = d;
    if (q->head == q->maxsize) {
        q->head -= q->maxsize;
    }
    if (q->head == q->tail) {
        //Drop data from queue
        q->tail++;
        while (q->tail >= q->maxsize) {
            q->tail -= q->maxsize;
        }
    }
    return;

}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   DoDevInfoInitialization
//
// Description: Do some USB device info data initialization 
//
// Input:
//              DEV_INFO    *fpDevInfo
//              UINT8       *fpDesc
//              UINT16      wStart
//              UINT16      wEnd
//
// Output:
//              EFI_STATUS
//
// Notes: 
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>
EFI_STATUS
DoDevInfoInitialization (
    DEV_INFO    *fpDevInfo,
    UINT8       *fpDesc,
    UINT16      wStart,
    UINT16      wEnd
)
{

    UINT8           bTemp;
    ENDP_DESC       *fpEndpDesc;
    INTRF_DESC      *fpIntrfDesc;
    SMARTCLASS_DESC *fpCCIDDesc = NULL;

    fpDevInfo->bDeviceType      = BIOS_DEV_TYPE_CCID;
    fpDevInfo->fpPollTDPtr      = 0;

    fpDevInfo->bCallBackIndex = USB_InstallCallBackFunction(USBCCID_ProcessInterruptData);

    //
    // Initialize the Initlist to hold data for each Slot 
    //
    DListInit(&(fpDevInfo->ICCDeviceList));
    fpIntrfDesc = (INTRF_DESC*)(fpDesc + wStart);

    //
    // Calculate the end of descriptor block
    //
    fpDesc+=((CNFG_DESC*)fpDesc)->wTotalLength; 
    fpEndpDesc = (ENDP_DESC*)((char*)fpIntrfDesc + fpIntrfDesc->bDescLength);

    do {
        if (fpIntrfDesc->bDescType == DESC_TYPE_SMART_CARD) {
            fpCCIDDesc = (SMARTCLASS_DESC *)fpIntrfDesc;
            break;
        }
        fpIntrfDesc = (INTRF_DESC*) ((UINT8 *)fpIntrfDesc + fpIntrfDesc->bDescLength);
    }while ((UINT8 *)fpIntrfDesc < fpDesc);

    if (!fpCCIDDesc) { 
        return EFI_DEVICE_ERROR;
    }

    fpDevInfo->pCCIDDescriptor = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(sizeof(SMARTCLASS_DESC)));
    ASSERT(fpDevInfo->pCCIDDescriptor);
    if (!fpDevInfo->pCCIDDescriptor) {
        return EFI_OUT_OF_RESOURCES;
    }      
    MemCopy((UINT8 *)fpCCIDDesc, (UINT8 *)(fpDevInfo->pCCIDDescriptor), sizeof(SMARTCLASS_DESC));
	fpCCIDDesc = (SMARTCLASS_DESC*)fpDevInfo->pCCIDDescriptor;

    if (fpCCIDDesc->bNumDataRatesSupported) {

        fpDevInfo->DataRates = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(
                                            fpCCIDDesc->bNumDataRatesSupported * sizeof(UINT32)));
        ASSERT(fpDevInfo->DataRates);
        if (!fpDevInfo->DataRates) {
            return EFI_OUT_OF_RESOURCES;
        }      
        //
        // Issue GET_DATA_RATES cmd. Should interface number be zero?
        //
        USBCCIDIssueControlTransfer(fpDevInfo, 
                                    CCID_CLASS_SPECIFIC_GET_DATA_RATES, 
                                    0x0, 0, (UINT8 *)fpDevInfo->DataRates, 
                                    fpCCIDDesc->bNumDataRatesSupported * sizeof(UINT32)
                                    );
        
    } else {
        fpDevInfo->DataRates = 0;
    }

    if (fpCCIDDesc->bNumClockSupported) {

        fpDevInfo->ClockFrequencies = USB_MemAlloc((UINT8)GET_MEM_BLK_COUNT(
                                        fpCCIDDesc->bNumClockSupported * sizeof(UINT32)));
        ASSERT(fpDevInfo->ClockFrequencies);
        if (!fpDevInfo->ClockFrequencies) {
            return EFI_OUT_OF_RESOURCES;
        }
        //            
        // Issue GET_CLOCK_FREQUENCIES. Should interface number be zero?
        //
        USBCCIDIssueControlTransfer(fpDevInfo,  
                                    CCID_CLASS_SPECIFIC_GET_CLOCK_FREQUENCIES, 
                                    0x0, 0, (UINT8 *)fpDevInfo->DataRates,
                                    fpCCIDDesc->bNumClockSupported * sizeof(UINT32));
    } else {
        fpDevInfo->ClockFrequencies = 0;
    }

    PrintDescriptorInformation(fpDevInfo->pCCIDDescriptor);

    bTemp = 0x03;       // bit 1 = Bulk In, bit 0 = Bulk Out

    for( ;(fpEndpDesc->bDescType != DESC_TYPE_INTERFACE) && ((UINT8*)fpEndpDesc < fpDesc);
        fpEndpDesc = (ENDP_DESC*)((UINT8 *)fpEndpDesc + fpEndpDesc->bDescLength)){

		if(!(fpEndpDesc->bDescLength)) {  
			  // Br if 0 length desc (should never happen, but...)
			  break;  
		}

        if( fpEndpDesc->bDescType != DESC_TYPE_ENDPOINT ) {
            continue;
        }

        if ((fpEndpDesc->bEndpointFlags & EP_DESC_FLAG_TYPE_BITS) ==
                EP_DESC_FLAG_TYPE_BULK) {   // Bit 1-0: 10 = Endpoint does bulk transfers
            if(!(fpEndpDesc->bEndpointAddr & EP_DESC_ADDR_DIR_BIT)) {
                //
                // Bit 7: Dir. of the endpoint: 1/0 = In/Out
                // If Bulk-Out endpoint already found then skip subsequent ones
                // on the interface.
                //
                if (bTemp & 1) {
                    fpDevInfo->bBulkOutEndpoint = (UINT8)(fpEndpDesc->bEndpointAddr
                                                        & EP_DESC_ADDR_EP_NUM);
                    fpDevInfo->wBulkOutMaxPkt = fpEndpDesc->wMaxPacketSize;
                    bTemp &= 0xFE;
                }
            } else {
                //
                // If Bulk-In endpoint already found then skip subsequent ones
                // on the interface
                //
                if (bTemp & 2) {
                    fpDevInfo->bBulkInEndpoint  = (UINT8)(fpEndpDesc->bEndpointAddr
                                                        & EP_DESC_ADDR_EP_NUM);
                    fpDevInfo->wBulkInMaxPkt    = fpEndpDesc->wMaxPacketSize;
                    bTemp   &= 0xFD;
                }
            }
        }

        //
        // Check for and configure Interrupt endpoint if present
        //
        if ((fpEndpDesc->bEndpointFlags & EP_DESC_FLAG_TYPE_BITS) !=
                EP_DESC_FLAG_TYPE_INT) {    // Bit 1-0: 10 = Endpoint does interrupt transfers
			continue;
        }

		if (fpEndpDesc->bEndpointAddr & EP_DESC_ADDR_DIR_BIT) {
			fpDevInfo->IntInEndpoint = fpEndpDesc->bEndpointAddr;
			fpDevInfo->IntInMaxPkt = fpEndpDesc->wMaxPacketSize;
			fpDevInfo->bPollInterval = fpEndpDesc->bPollInterval;	
		}
    }

    return EFI_SUCCESS;
}

//<AMI_PHDR_START>
//---------------------------------------------------------------------------
//
// Procedure:   USBCCIDInitialize
//
// Description: This function initializes CCID device related data
//
// Input:
//              None
//
// Output:      
//              None 
//
//---------------------------------------------------------------------------
//<AMI_PHDR_END>

VOID
USBCCIDInitialize ()
{
    USB_InstallCallBackFunction(USBCCID_ProcessInterruptData);
    return;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDCheckForDevice
//
// Description: This routine checks for CCID type device from the
//              interface data provided
//
// Input:
//              DEV_INFO    *fpDevInfo
//              UINT8       bBaseClass
//              UINT8       bSubClass
//              UINT8       bProtocol
//
// Output:      
//              BIOS_DEV_TYPE_STORAGE type on success or 0FFH on error
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USBCCIDCheckForDevice (
    DEV_INFO    *fpDevInfo,
    UINT8       bBaseClass,
    UINT8       bSubClass,
    UINT8       bProtocol
)
{

    if(bBaseClass == BASE_CLASS_CCID_STORAGE  && bProtocol == PROTOCOL_CCID) {
        return BIOS_DEV_TYPE_CCID;
    }

    return USB_ERROR;
}

//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDConfigureDevice
//
// Description: This function checks an interface descriptor of a device
//              to see if it describes a USB CCID device.  If the device
//              is a CCID device,  then it is configured
//              and initialized.
//
// Input:
//              pHCStruc    HCStruc pointer
//              pDevInfo    Device information structure pointer
//              pDesc       Pointer to the descriptor structure
//              wEnd        End offset of the device descriptor
//
// Output:    
//              New device info structure, NULL on error
//
// Notes:       DoDevInfoInitialization
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

DEV_INFO*
USBCCIDConfigureDevice (
    HC_STRUC        *fpHCStruc,
    DEV_INFO        *fpDevInfo,
    UINT8           *fpDesc,
    UINT16          wStart,
    UINT16          wEnd
)
{

    EFI_STATUS        Status;
    INTRF_DESC      *fpIntrfDesc = (INTRF_DESC*)(fpDesc + wStart);

    USB_DEBUG (DEBUG_LEVEL_3, "USBCCIDConfigureDevice ....\n");

    //
    // Do some house keeping related DEV_INFO structure. No H/W access
    //
    Status = DoDevInfoInitialization(fpDevInfo, fpDesc, wStart, wEnd);

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

#if CCID_USE_INTERRUPT_INSERTION_REMOVAL
    //
    // if Interrupt EndPoint is supported
    //
    if (fpIntrfDesc->bNumEndpoints == 3) {
		fpDevInfo->PollingLength = fpDevInfo->IntInMaxPkt;
        (*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDActivatePolling)
                    (fpHCStruc, fpDevInfo);
    }

#else

    Status = ICCInsertEvent(fpDevInfo, 0);

#endif

    //
    // Should we support CCID which doesn't support interrupt-IN Message.
    // Maybe not for now.
    //
    return  fpDevInfo;

}


//<AMI_PHDR_START>
//----------------------------------------------------------------------------
// Procedure:   USBCCIDDisconnectDevice
//
// Description: This function disconnects the CCID device.
//
// Input:    
//              pDevInfo    Device info structure pointer
//
// Output:
//              None
//
//Notes:        Free up all memory allocated to the device. 
//              Remove ICC device from the device list.
//
//----------------------------------------------------------------------------
//<AMI_PHDR_END>

UINT8
USBCCIDDisconnectDevice (
    DEV_INFO    *fpDevInfo
)
{

    ICC_DEVICE        *fpICCDevice;
    DLINK      *dlink = fpDevInfo->ICCDeviceList.pHead;
	HC_STRUC   *fpHCStruc = gUsbData->HcTable[fpDevInfo->bHCNumber - 1];
	SMARTCLASS_DESC *CCIDDescriptor = (SMARTCLASS_DESC*)fpDevInfo->pCCIDDescriptor;
    UINT8              *MemBlockEnd = gUsbData->fpMemBlockStart + (gUsbData->MemPages << 12);
    EFI_STATUS  Status = EFI_SUCCESS;

    if (((UINT8*)fpDevInfo->pCCIDDescriptor < gUsbData->fpMemBlockStart) ||
        ((UINT8*)fpDevInfo->pCCIDDescriptor > MemBlockEnd)) {
        return USB_ERROR;
    }

#if USB_RUNTIME_DRIVER_IN_SMM
    if (dlink != NULL) {
        Status = AmiValidateMemoryBuffer((VOID*)dlink, 
                            (UINT32)sizeof(DLINK));
        if (EFI_ERROR(Status)) {
            return USB_ERROR;
        }
    }
#endif

#if CCID_USE_INTERRUPT_INSERTION_REMOVAL
	// Stop polling the endpoint
	(*gUsbData->aHCDriverTable[GET_HCD_INDEX(fpHCStruc->bHCType)].pfnHCDDeactivatePolling)(fpHCStruc,fpDevInfo);
	fpDevInfo->IntInEndpoint = 0;

#endif

    //
    // Free up all the memory allocated for each ICC device
    //
    while (dlink) {
        fpICCDevice = OUTTER(dlink, ICCDeviceLink, ICC_DEVICE);
        if (((UINT8*)fpICCDevice < gUsbData->fpMemBlockStart) ||
            ((UINT8*)((UINTN)fpICCDevice + sizeof(ICC_DEVICE)) > MemBlockEnd)) {
            return USB_ERROR;
        }
        USB_MemFree(fpICCDevice, (UINT8)GET_MEM_BLK_COUNT(sizeof(ICC_DEVICE)));
#if USB_RUNTIME_DRIVER_IN_SMM
        if (fpDevInfo->ICCDeviceList.pHead != NULL) {
            Status = AmiValidateMemoryBuffer((VOID*)(fpDevInfo->ICCDeviceList.pHead), 
                            (UINT32)sizeof(DLINK));
            if (EFI_ERROR(Status)) {
                return USB_ERROR;
            }
        }
        if (fpDevInfo->ICCDeviceList.pTail != NULL) {
            Status = AmiValidateMemoryBuffer((VOID*)(fpDevInfo->ICCDeviceList.pTail), 
                            (UINT32)sizeof(DLINK));
            if (EFI_ERROR(Status)) {
                return USB_ERROR;
            }
        }
#endif
        DListDelete (&(fpDevInfo->ICCDeviceList), &(fpICCDevice->ICCDeviceLink));
        if (!dlink->pNext) break;
        dlink = dlink->pNext;       
    }

    if (fpDevInfo->DataRates) {
        USB_MemFree(fpDevInfo->DataRates, 
                    (UINT8)GET_MEM_BLK_COUNT(CCIDDescriptor->bNumDataRatesSupported * sizeof(UINT32))
                    );
    }

    if (fpDevInfo->ClockFrequencies) {
        USB_MemFree(fpDevInfo->ClockFrequencies, 
                    (UINT8)GET_MEM_BLK_COUNT(CCIDDescriptor->bNumClockSupported * sizeof(UINT32))
                    );
    }

    //
    // Free up all the memory allocated for CCID Descriptor
    //
    USB_MemFree(CCIDDescriptor, 
                (UINT8)GET_MEM_BLK_COUNT(sizeof(SMARTCLASS_DESC))
                );

    fpDevInfo->pCCIDDescriptor = 0;

    return USB_SUCCESS;
}

//****************************************************************************
//****************************************************************************
//**                                                                        **
//**             (C)Copyright 1985-2016, American Megatrends, Inc.          **
//**                                                                        **
//**                          All Rights Reserved.                          **
//**                                                                        **
//**                 5555 Oakbrook Pkwy, Norcross, GA 30093                 **
//**                                                                        **
//**                          Phone (770)-246-8600                          **
//**                                                                        **
//****************************************************************************
//****************************************************************************