summaryrefslogtreecommitdiff
path: root/at91lib/usb/device/ccid/cciddriver.c
blob: a23fc216efdecb0959e34da9b1a57dce6fad43df (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
/* ----------------------------------------------------------------------------
 *         ATMEL Microcontroller Software Support 
 * ----------------------------------------------------------------------------
 * Copyright (c) 2008, Atmel Corporation
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer below.
 *
 * Atmel's name may not be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ----------------------------------------------------------------------------
 */

//------------------------------------------------------------------------------
/// \unit
///
/// !Purpose
/// 
/// CCID driver
/// 
/// !Usage
/// 
/// Explanation on the usage of the code made available through the header file.
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//       Headers
//------------------------------------------------------------------------------

#include <board.h>
#include <utility/trace.h>
#include <usb/device/core/USBD.h>
#include <usb/device/core/USBDDriver.h>
#include <usb/common/core/USBGenericRequest.h>
#include <usb/common/core/USBStringDescriptor.h>
#include <usb/device/ccid/cciddriver.h>
#include <usb/device/ccid/cciddriverdescriptors.h>
#include <iso7816/iso7816_4.h>
#include <string.h>

//------------------------------------------------------------------------------
//         Local definition
//------------------------------------------------------------------------------

/// Constants: IDs: Device product ID.
#define CCIDDriverDescriptors_PRODUCTID       0x6129
/// Constants: IDs: Device vendor ID.
#define CCIDDriverDescriptors_VENDORID        0x03EB
/// Constants: IDs: Device release number.
#define CCIDDriverDescriptors_RELEASE         0x0100

/// Returns the minimum between two values.
#define MIN(a, b)       ((a < b) ? a : b)

//------------------------------------------------------------------------------
//         Types
//------------------------------------------------------------------------------

/// CCIDDriverConfiguration Descriptors
/// List of descriptors that make up the configuration descriptors of a
/// device using the CCID driver.
typedef struct {

    /// Configuration descriptor
    USBConfigurationDescriptor configuration;
    /// Interface descriptor
    USBInterfaceDescriptor     interface;
    /// CCID descriptor
    CCIDDescriptor             ccid;
    /// Bulk OUT endpoint descriptor
    USBEndpointDescriptor      bulkOut;
    /// Bulk IN endpoint descriptor
    USBEndpointDescriptor      bulkIn;
    /// Interrupt OUT endpoint descriptor
    USBEndpointDescriptor      interruptIn;

} __attribute__ ((packed)) CCIDDriverConfigurationDescriptors;

//------------------------------------------------------------------------------
//         Types
//------------------------------------------------------------------------------

/// Driver structure for an CCID device
typedef struct {

    /// Standard USB device driver instance
    USBDDriver             usbdDriver;
    /// CCID message
    S_ccid_bulk_in_header  sCcidMessage;
    /// CCID command
    S_ccid_bulk_out_header sCcidCommand;
    /// Interrupt message answer
    unsigned char          BufferINT[4];
    /// Buffer data of message
    unsigned char          ProtocolDataStructure[10];
    /// Protocol used
    unsigned char          bProtocol;
    /// SlotStatus
    /// Bit 0 = Slot 0 current state
    /// Bit 1 = Slot 0 changed status
    /// Bit 2 = Slot 1 current state
    /// Bit 3 = Slot 1 changed status
    /// Bit 4 = Slot 2 current state
    /// Bit 5 = Slot 2 changed status
    unsigned char          SlotStatus;

} CCIDDriver;

//------------------------------------------------------------------------------
//         Local variables
//------------------------------------------------------------------------------

/// Static instance of the CCID device driver.
static CCIDDriver ccidDriver;

/// Standard USB device descriptor.
static const USBDeviceDescriptor deviceDescriptor = {

    sizeof(USBDeviceDescriptor),
    USBGenericDescriptor_DEVICE,
    USBDeviceDescriptor_USB2_00,
    0,
    0,
    0,
    BOARD_USB_ENDPOINTS_MAXPACKETSIZE(0),
    CCIDDriverDescriptors_VENDORID,
    CCIDDriverDescriptors_PRODUCTID,
    CCIDDriverDescriptors_RELEASE,
    1, // Index of manufacturer description
    2, // Index of product description
    3, // Index of serial number description
    1  // One possible configuration
};


/// List of configuration descriptors.
static const CCIDDriverConfigurationDescriptors configurationDescriptorsFS = {

    // Standard USB configuration descriptor
    {
        sizeof(USBConfigurationDescriptor),
        USBGenericDescriptor_CONFIGURATION,
        sizeof(CCIDDriverConfigurationDescriptors),
        1, // One interface in this configuration
        1, // This is configuration #1
        0, // No associated string descriptor
        BOARD_USB_BMATTRIBUTES,
        USBConfigurationDescriptor_POWER(100)
    },
    // CCID interface descriptor
    // Table 4.3-1 Interface Descriptor
    // Interface descriptor
    {
        sizeof(USBInterfaceDescriptor),
        USBGenericDescriptor_INTERFACE,
        0,                       // Interface 0
        0,                       // No alternate settings
        3,                       // uses bulk-IN, bulk-OUT and interrupt–IN
        SMART_CARD_DEVICE_CLASS,
        0,                       // Subclass code
        0,                       // bulk transfers optional interrupt-IN
        0                        // No associated string descriptor
    },
    {
        sizeof(CCIDDescriptor), // bLength: Size of this descriptor in bytes
        CCID_DECRIPTOR_TYPE,    // bDescriptorType:Functional descriptor type
        CCID1_10,               // bcdCCID: CCID version
        0,               // bMaxSlotIndex: Value 0 indicates that one slot is supported
        VOLTS_5_0,       // bVoltageSupport
        PROTOCOL_TO,     // dwProtocols
        3580,            // dwDefaultClock
        3580,            // dwMaxClock
        0,               // bNumClockSupported
        9600,            // dwDataRate : 9600 bauds
        9600,            // dwMaxDataRate : 9600 bauds
        0,               // bNumDataRatesSupported
        0xfe,            // dwMaxIFSD
        0,               // dwSynchProtocols
        0,               // dwMechanical
        //0x00010042,      // dwFeatures: Short APDU level exchanges
        CCID_FEATURES_AUTO_PCONF | CCID_FEATURES_AUTO_PNEGO | CCID_FEATURES_EXC_TPDU,
        0x0000010F,      // dwMaxCCIDMessageLength: For extended APDU level the value shall be between 261 + 10
        0xFF,            // bClassGetResponse: Echoes the class of the APDU
        0xFF,            // bClassEnvelope: Echoes the class of the APDU
        0,               // wLcdLayout: no LCD
        0,               // bPINSupport: No PIN
        1                // bMaxCCIDBusySlot
    },
    // Bulk-OUT endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_OUT, CCID_EPT_DATA_OUT ),
        USBEndpointDescriptor_BULK,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_DATA_OUT),
            USBEndpointDescriptor_MAXBULKSIZE_FS),
        0x00                               // Does not apply to Bulk endpoints
    },
    // Bulk-IN endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, CCID_EPT_DATA_IN ),
        USBEndpointDescriptor_BULK,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_DATA_IN),
            USBEndpointDescriptor_MAXBULKSIZE_FS),
        0x00                               // Does not apply to Bulk endpoints
    },
    // Notification endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, CCID_EPT_NOTIFICATION ),
        USBEndpointDescriptor_INTERRUPT,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_NOTIFICATION),
            USBEndpointDescriptor_MAXINTERRUPTSIZE_FS),
        0x10                              
    }
};

#ifdef BOARD_USB_UDPHS
static const CCIDDriverConfigurationDescriptors configurationDescriptorsHS = {

    // Standard USB configuration descriptor
    {
        sizeof(USBConfigurationDescriptor),
        USBGenericDescriptor_CONFIGURATION,
        sizeof(CCIDDriverConfigurationDescriptors),
        1, // One interface in this configuration
        1, // This is configuration #1
        0, // No associated string descriptor
        BOARD_USB_BMATTRIBUTES,
        USBConfigurationDescriptor_POWER(100)
    },
    // CCID interface descriptor
    // Table 4.3-1 Interface Descriptor
    // Interface descriptor
    {
        sizeof(USBInterfaceDescriptor),
        USBGenericDescriptor_INTERFACE,
        0,                       // Interface 0
        0,                       // No alternate settings
        3,                       // uses bulk-IN, bulk-OUT and interrupt–IN
        SMART_CARD_DEVICE_CLASS,
        0,                       // Subclass code
        0,                       // bulk transfers optional interrupt-IN
        0                        // No associated string descriptor
    },
    {
        sizeof(CCIDDescriptor), // bLength: Size of this descriptor in bytes
        CCID_DECRIPTOR_TYPE,    // bDescriptorType:Functional descriptor type
        CCID1_10,               // bcdCCID: CCID version
        0,               // bMaxSlotIndex: Value 0 indicates that one slot is supported
        VOLTS_5_0,       // bVoltageSupport
        PROTOCOL_TO,     // dwProtocols
        3580,            // dwDefaultClock
        3580,            // dwMaxClock
        0,               // bNumClockSupported
        9600,            // dwDataRate : 9600 bauds
        9600,            // dwMaxDataRate : 9600 bauds
        0,               // bNumDataRatesSupported
        0xfe,            // dwMaxIFSD
        0,               // dwSynchProtocols
        0,               // dwMechanical
        //0x00010042,      // dwFeatures: Short APDU level exchanges
        CCID_FEATURES_AUTO_PCONF | CCID_FEATURES_AUTO_PNEGO | CCID_FEATURES_EXC_TPDU,
        0x0000010F,      // dwMaxCCIDMessageLength: For extended APDU level the value shall be between 261 + 10
        0xFF,            // bClassGetResponse: Echoes the class of the APDU
        0xFF,            // bClassEnvelope: Echoes the class of the APDU
        0,               // wLcdLayout: no LCD
        0,               // bPINSupport: No PIN
        1                // bMaxCCIDBusySlot
    },
    // Bulk-OUT endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_OUT, CCID_EPT_DATA_OUT ),
        USBEndpointDescriptor_BULK,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_DATA_OUT),
            USBEndpointDescriptor_MAXBULKSIZE_HS),
        0x00                               // Does not apply to Bulk endpoints
    },
    // Bulk-IN endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, CCID_EPT_DATA_IN ),
        USBEndpointDescriptor_BULK,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_DATA_IN),
            USBEndpointDescriptor_MAXBULKSIZE_HS),
        0x00                               // Does not apply to Bulk endpoints
    },
    // Notification endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, CCID_EPT_NOTIFICATION ),
        USBEndpointDescriptor_INTERRUPT,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_NOTIFICATION),
            USBEndpointDescriptor_MAXINTERRUPTSIZE_HS),
        0x10                              
    }
};

/// Qualifier descriptor
const USBDeviceQualifierDescriptor deviceQualifierDescriptor = {

    sizeof(USBDeviceQualifierDescriptor),  // Size of this descriptor in bytes
    USBGenericDescriptor_DEVICEQUALIFIER,  // Qualifier Descriptor Type
    USBDeviceDescriptor_USB2_00,           // USB specification 2.00
    0x00,                                  // Class is specified in interface
    0x00,                                  // Subclass is specified in interface
    0x00,                                  // Protocol is specified in interface
    BOARD_USB_ENDPOINTS_MAXPACKETSIZE(0),    
    0x01,                                  // One possible configuration
    0x00                                   // Reserved for future use, must be zero
};

/// OtherSpeed configuration descriptor in Full Speed mode
static const CCIDDriverConfigurationDescriptors sOtherSpeedConfigurationFS = {

    // Standard USB configuration descriptor
    {
        sizeof(USBConfigurationDescriptor),
        USBGenericDescriptor_OTHERSPEEDCONFIGURATION,
        sizeof(CCIDDriverConfigurationDescriptors),
        1, // One interface in this configuration
        1, // This is configuration #1
        0, // No associated string descriptor
        BOARD_USB_BMATTRIBUTES,
        USBConfigurationDescriptor_POWER(100)
    },
    // CCID interface descriptor
    // Table 4.3-1 Interface Descriptor
    // Interface descriptor
    {
        sizeof(USBInterfaceDescriptor),
        USBGenericDescriptor_INTERFACE,
        0,                       // Interface 0
        0,                       // No alternate settings
        3,                       // uses bulk-IN, bulk-OUT and interrupt–IN
        SMART_CARD_DEVICE_CLASS,
        0,                       // Subclass code
        0,                       // bulk transfers optional interrupt-IN
        0                        // No associated string descriptor
    },
    {
        sizeof(CCIDDescriptor), // bLength: Size of this descriptor in bytes
        CCID_DECRIPTOR_TYPE,    // bDescriptorType:Functional descriptor type
        CCID1_10,               // bcdCCID: CCID version
        0,               // bMaxSlotIndex: Value 0 indicates that one slot is supported
        VOLTS_5_0,       // bVoltageSupport
        PROTOCOL_TO,     // dwProtocols
        3580,            // dwDefaultClock
        3580,            // dwMaxClock
        0,               // bNumClockSupported
        9600,            // dwDataRate : 9600 bauds
        9600,            // dwMaxDataRate : 9600 bauds
        0,               // bNumDataRatesSupported
        0xfe,            // dwMaxIFSD
        0,               // dwSynchProtocols
        0,               // dwMechanical
        //0x00010042,      // dwFeatures: Short APDU level exchanges
        CCID_FEATURES_AUTO_PCONF | CCID_FEATURES_AUTO_PNEGO | CCID_FEATURES_EXC_TPDU,
        0x0000010F,      // dwMaxCCIDMessageLength: For extended APDU level the value shall be between 261 + 10
        0xFF,            // bClassGetResponse: Echoes the class of the APDU
        0xFF,            // bClassEnvelope: Echoes the class of the APDU
        0,               // wLcdLayout: no LCD
        0,               // bPINSupport: No PIN
        1                // bMaxCCIDBusySlot
    },
    // Bulk-OUT endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_OUT, CCID_EPT_DATA_OUT ),
        USBEndpointDescriptor_BULK,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_DATA_OUT),
            USBEndpointDescriptor_MAXBULKSIZE_FS),
        0x00                               // Does not apply to Bulk endpoints
    },
    // Bulk-IN endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, CCID_EPT_DATA_IN ),
        USBEndpointDescriptor_BULK,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_DATA_IN),
            USBEndpointDescriptor_MAXBULKSIZE_FS),
        0x00                               // Does not apply to Bulk endpoints
    },
    // Notification endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, CCID_EPT_NOTIFICATION ),
        USBEndpointDescriptor_INTERRUPT,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_NOTIFICATION),
            USBEndpointDescriptor_MAXINTERRUPTSIZE_FS),
        0x10                              
    }
};

/// OtherSpeed configuration descriptor in High Speed mode
static const CCIDDriverConfigurationDescriptors sOtherSpeedConfigurationHS = {

    // Standard USB configuration descriptor
    {
        sizeof(USBConfigurationDescriptor),
        USBGenericDescriptor_OTHERSPEEDCONFIGURATION,
        sizeof(CCIDDriverConfigurationDescriptors),
        1, // One interface in this configuration
        1, // This is configuration #1
        0, // No associated string descriptor
        BOARD_USB_BMATTRIBUTES,
        USBConfigurationDescriptor_POWER(100)
    },
    // CCID interface descriptor
    // Table 4.3-1 Interface Descriptor
    // Interface descriptor
    {
        sizeof(USBInterfaceDescriptor),
        USBGenericDescriptor_INTERFACE,
        0,                       // Interface 0
        0,                       // No alternate settings
        3,                       // uses bulk-IN, bulk-OUT and interrupt–IN
        SMART_CARD_DEVICE_CLASS,
        0,                       // Subclass code
        0,                       // bulk transfers optional interrupt-IN
        0                        // No associated string descriptor
    },
    {
        sizeof(CCIDDescriptor), // bLength: Size of this descriptor in bytes
        CCID_DECRIPTOR_TYPE,    // bDescriptorType:Functional descriptor type
        CCID1_10,               // bcdCCID: CCID version
        0,               // bMaxSlotIndex: Value 0 indicates that one slot is supported
        VOLTS_5_0,       // bVoltageSupport
        PROTOCOL_TO,     // dwProtocols
        3580,            // dwDefaultClock
        3580,            // dwMaxClock
        0,               // bNumClockSupported
        9600,            // dwDataRate : 9600 bauds
        9600,            // dwMaxDataRate : 9600 bauds
        0,               // bNumDataRatesSupported
        0xfe,            // dwMaxIFSD
        0,               // dwSynchProtocols
        0,               // dwMechanical
        //0x00010042,      // dwFeatures: Short APDU level exchanges
        CCID_FEATURES_AUTO_PCONF | CCID_FEATURES_AUTO_PNEGO | CCID_FEATURES_EXC_TPDU,
        0x0000010F,      // dwMaxCCIDMessageLength: For extended APDU level the value shall be between 261 + 10
        0xFF,            // bClassGetResponse: Echoes the class of the APDU
        0xFF,            // bClassEnvelope: Echoes the class of the APDU
        0,               // wLcdLayout: no LCD
        0,               // bPINSupport: No PIN
        1                // bMaxCCIDBusySlot
    },
    // Bulk-OUT endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_OUT, CCID_EPT_DATA_OUT ),
        USBEndpointDescriptor_BULK,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_DATA_OUT),
            USBEndpointDescriptor_MAXBULKSIZE_HS),
        0x00                               // Does not apply to Bulk endpoints
    },
    // Bulk-IN endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, CCID_EPT_DATA_IN ),
        USBEndpointDescriptor_BULK,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_DATA_IN),
            USBEndpointDescriptor_MAXBULKSIZE_HS),
        0x00                               // Does not apply to Bulk endpoints
    },
    // Notification endpoint descriptor
    {
        sizeof(USBEndpointDescriptor),
        USBGenericDescriptor_ENDPOINT,
        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, CCID_EPT_NOTIFICATION ),
        USBEndpointDescriptor_INTERRUPT,
        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(CCID_EPT_NOTIFICATION),
            USBEndpointDescriptor_MAXINTERRUPTSIZE_HS),
        0x10                              
    }
};
#endif

/// Language ID string descriptor.
static const unsigned char languageIdDescriptor[] = {

    USBStringDescriptor_LENGTH(1),
    USBGenericDescriptor_STRING,
    USBStringDescriptor_ENGLISH_US
};

/// Manufacturer name.
static const unsigned char manufacturerDescriptor[] = {

    USBStringDescriptor_LENGTH(5),
    USBGenericDescriptor_STRING,
    USBStringDescriptor_UNICODE('A'),
    USBStringDescriptor_UNICODE('T'),
    USBStringDescriptor_UNICODE('M'),
    USBStringDescriptor_UNICODE('E'),
    USBStringDescriptor_UNICODE('L')
};

/// Product name.
static const unsigned char productDescriptor[] = {

    USBStringDescriptor_LENGTH(23),
    USBGenericDescriptor_STRING,
    USBStringDescriptor_UNICODE('A'),
    USBStringDescriptor_UNICODE('T'),
    USBStringDescriptor_UNICODE('M'),
    USBStringDescriptor_UNICODE('E'),
    USBStringDescriptor_UNICODE('L'),
    USBStringDescriptor_UNICODE(' '),
    USBStringDescriptor_UNICODE('A'),
    USBStringDescriptor_UNICODE('T'),
    USBStringDescriptor_UNICODE('9'),
    USBStringDescriptor_UNICODE('1'),
    USBStringDescriptor_UNICODE(' '),
    USBStringDescriptor_UNICODE('C'),
    USBStringDescriptor_UNICODE('C'),
    USBStringDescriptor_UNICODE('I'),
    USBStringDescriptor_UNICODE('D'),
    USBStringDescriptor_UNICODE(' '),
    USBStringDescriptor_UNICODE('D'),
    USBStringDescriptor_UNICODE('R'),
    USBStringDescriptor_UNICODE('I'),
    USBStringDescriptor_UNICODE('V'),
    USBStringDescriptor_UNICODE('E'),
    USBStringDescriptor_UNICODE('R'),
    USBStringDescriptor_UNICODE(' ')
};

/// Product serial number.
static const unsigned char serialNumberDescriptor[] = {

    USBStringDescriptor_LENGTH(12),
    USBGenericDescriptor_STRING,
    USBStringDescriptor_UNICODE('0'),
    USBStringDescriptor_UNICODE('1'),
    USBStringDescriptor_UNICODE('2'),
    USBStringDescriptor_UNICODE('3'),
    USBStringDescriptor_UNICODE('4'),
    USBStringDescriptor_UNICODE('5'),
    USBStringDescriptor_UNICODE('6'),
    USBStringDescriptor_UNICODE('7'),
    USBStringDescriptor_UNICODE('8'),
    USBStringDescriptor_UNICODE('9'),
    USBStringDescriptor_UNICODE('A'),
    USBStringDescriptor_UNICODE('F')
};

/// Array of pointers to string descriptors.
static const unsigned char *stringDescriptors[] = {

    languageIdDescriptor,
    manufacturerDescriptor,
    productDescriptor,
    serialNumberDescriptor
};


/// List of standard descriptors for the serial driver.
const USBDDriverDescriptors ccidDriverDescriptors = {

    &deviceDescriptor, // FS
    (USBConfigurationDescriptor *) &configurationDescriptorsFS,
#ifdef BOARD_USB_UDPHS
    (USBDeviceQualifierDescriptor *) &deviceQualifierDescriptor, // FS
    (USBConfigurationDescriptor *) &sOtherSpeedConfigurationFS,
    &deviceDescriptor, // HS
    (USBConfigurationDescriptor *) &configurationDescriptorsHS,
    (USBDeviceQualifierDescriptor *) &deviceQualifierDescriptor, // HS
    (USBConfigurationDescriptor *) &sOtherSpeedConfigurationHS,
#else
    0, // No qualifier descriptor FS
    0, // No other-speed configuration FS
    0, // No device descriptor HS
    0, // No configuration HS
    0, // No qualifier descriptor HS
    0, // No other-speed configuration HS
#endif
    stringDescriptors,
    4 // Four string descriptors in array
};

//------------------------------------------------------------------------------
//      Internal functions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Return the Slot Status to the host
/// Answer to:
///   PC_to_RDR_IccPowerOff
///   PC_to_RDR_GetSlotStatus
///   PC_to_RDR_IccClock
///   PC_to_RDR_T0APDU
///   PC_to_RDR_Mechanical
///   PC_to_RDR_Abort and Class specific ABORT request
//------------------------------------------------------------------------------
static void RDRtoPCSlotStatus( void )
{
    TRACE_DEBUG("RDRtoPCSlotStatus\n\r");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_SLOTSTATUS;
    ccidDriver.sCcidMessage.wLength   = 0;
    ccidDriver.sCcidMessage.bStatus   = ccidDriver.SlotStatus;
    ccidDriver.sCcidMessage.bError    = 0;
    // 00h Clock running
    // 01h Clock stopped in state L
    // 02h Clock stopped in state H
    // 03h Clock stopped in an unknown state
    // All other values are Reserved for Future Use.
    ccidDriver.sCcidMessage.bSpecific = 0;
}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Answer to PC_to_RDR_IccPowerOn
//------------------------------------------------------------------------------
static void RDRtoPCDatablock_ATR( void )
{
    unsigned char i;
    unsigned char Atr[ATR_SIZE_MAX];
    unsigned char length;

    //TRACE_DEBUG("RDRtoPCDatablock\n\r");

    ISO7816_Datablock_ATR( Atr, &length );

    if( length > 5 ) {
        ccidDriver.ProtocolDataStructure[1] = Atr[5]&0x0F; // TD(1)
        ccidDriver.bProtocol = Atr[5]&0x0F;           // TD(1)
    }

    // S_ccid_protocol_t0
    // bmFindexDindex
    ccidDriver.ProtocolDataStructure[0] = Atr[2];     // TA(1)

    // bmTCCKST0
    // For T=0 ,B0 – 0b, B7-2 – 000000b
    // B1 – Convention used (b1=0 for direct, b1=1 for inverse)

    // bGuardTimeT0
    // Extra Guardtime between two characters. Add 0 to 254 etu to the normal 
    // guardtime of 12etu. FFh is the same as 00h.
    ccidDriver.ProtocolDataStructure[2] = Atr[4];     // TC(1)
    // AT91C_BASE_US0->US_TTGR = 0;  // TC1

    // bWaitingIntegerT0
    // WI for T=0 used to define WWT
    ccidDriver.ProtocolDataStructure[3] = Atr[7];     // TC(2)

    // bClockStop
    // ICC Clock Stop Support
    // 00 = Stopping the Clock is not allowed
    // 01 = Stop with Clock signal Low
    // 02 = Stop with Clock signal High
    // 03 = Stop with Clock either High or Low
    ccidDriver.ProtocolDataStructure[4] = 0x00;       // 0 to 3

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_DATABLOCK;
    ccidDriver.sCcidMessage.wLength      = length;  // Size of ATR
    ccidDriver.sCcidMessage.bSizeToSend += length;  // Size of ATR
    // bChainParameter: 00 the response APDU begins and ends in this command
    ccidDriver.sCcidMessage.bSpecific    = 0;

    for( i=0; i<length; i++ ) {

        ccidDriver.sCcidMessage.abData[i]  = Atr[i];
    }

    // Set the slot to an active status
    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError = 0;
}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// In other cases, the response message has the following format: 
/// The response data will contain the optional data returned by the ICC, 
/// followed by the 2 byte-size status words SW1-SW2.
///
/// Answer to:
///   PC_to_RDR_XfrBlock
///   PC_to_RDR_Secure
//------------------------------------------------------------------------------
static void RDRtoPCDatablock( void )
{
    //TRACE_DEBUG("RDRtoPCDatablock\n\r");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_DATABLOCK;
    ccidDriver.sCcidMessage.bSizeToSend += ccidDriver.sCcidMessage.wLength;
    // bChainParameter: 00 the response APDU begins and ends in this command
    ccidDriver.sCcidMessage.bSpecific = 0;

    // Set the slot to an active status
    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError = 0;
}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Answer to:
///   PC_to_RDR_GetParameters
///   PC_to_RDR_ResetParameters
///   PC_to_RDR_SetParameters
//------------------------------------------------------------------------------
static void RDRtoPCParameters( void )
{
    unsigned int i;

    TRACE_DEBUG("RDRtoPCParameters\n\r");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_PARAMETERS;

    //ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError  = 0;

    if( ccidDriver.ProtocolDataStructure[1] == PROTOCOL_TO ) {

        // T=0
        ccidDriver.sCcidMessage.wLength   = sizeof(S_ccid_protocol_t0);
        ccidDriver.sCcidMessage.bSpecific = PROTOCOL_TO;
    }
    else {

        // T=1
        ccidDriver.sCcidMessage.wLength   = sizeof(S_ccid_protocol_t1);
        ccidDriver.sCcidMessage.bSpecific = PROTOCOL_T1;
    }

    ccidDriver.sCcidMessage.bSizeToSend += ccidDriver.sCcidMessage.wLength;

    for( i=0; i<ccidDriver.sCcidMessage.wLength; i++ ) {
        ccidDriver.sCcidMessage.abData[i] = ccidDriver.ProtocolDataStructure[i];
    }

}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Answer to:
///   PC_to_RDR_Escape
//------------------------------------------------------------------------------
static void RDRtoPCEscape( unsigned char length, unsigned char *data_send_from_CCID )
{
    unsigned int i;

    TRACE_DEBUG("RDRtoPCEscape\n\r");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_ESCAPE;

    ccidDriver.sCcidMessage.wLength   = length;

    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError  = 0;

    ccidDriver.sCcidMessage.bSpecific = 0;  // bRFU

    for( i=0; i<length; i++ ) {
        ccidDriver.sCcidMessage.abData[i] = data_send_from_CCID[i];
    }
}

//------------------------------------------------------------------------------
/// Response Pipe, Bulk-IN Messages
/// Answer to: 
///   PC_to_RDR_SetDataRateAndClockFrequency
//------------------------------------------------------------------------------
static void RDRtoPCDataRateAndClockFrequency( unsigned int dwClockFrequency, 
                                       unsigned int dwDataRate )
{
    TRACE_DEBUG("RDRtoPCDataRateAndClockFrequency\n\r");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_DATARATEANDCLOCKFREQUENCY;

    ccidDriver.sCcidMessage.wLength   = 8;

    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError  = 0;

    ccidDriver.sCcidMessage.bSpecific = 0;  // bRFU

    ccidDriver.sCcidMessage.abData[0] = dwClockFrequency;
    
    ccidDriver.sCcidMessage.abData[4] = dwDataRate;
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// Power On Command - Cold Reset & Warm Reset 
/// Return the ATR to the host
//------------------------------------------------------------------------------
static void PCtoRDRIccPowerOn( void )
{
    TRACE_DEBUG("PCtoRDRIccPowerOn\n\r");

    if( CCID_FEATURES_AUTO_VOLT == (configurationDescriptorsFS.ccid.dwFeatures & CCID_FEATURES_AUTO_VOLT) ) {

        // bPowerSelect = ccidDriver.sCcidCommand.bSpecific_0;
        ccidDriver.sCcidCommand.bSpecific_0 = VOLTS_AUTO;
    }

    ISO7816_cold_reset();

    // for emulation only //JCB 
    if ( ccidDriver.sCcidCommand.bSpecific_0 != VOLTS_5_0 ) {

        TRACE_ERROR("POWER_NOT_SUPPORTED\n\r");
    }

    else {

        RDRtoPCDatablock_ATR();

    }
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// Power Off Command - Set the ICC in an inactive state
/// Return the slot status to the host
//------------------------------------------------------------------------------
static void PCtoRDRIccPowerOff( void )
{
    unsigned char bStatus;

    TRACE_DEBUG("PCtoRDRIccPowerOff\n\r");

    ISO7816_IccPowerOff();

    //JCB stub
    bStatus = ICC_BS_PRESENT_NOTACTIVATED;

    // Set the slot to an inactive status
    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError = 0;

    // if error, see Table 6.1-2 errors

    // Return the slot status to the host
    RDRtoPCSlotStatus();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// Get slot status
//------------------------------------------------------------------------------
static void PCtoRDRGetSlotStatus( void )
{
    TRACE_DEBUG("PCtoRDRGetSlotStatus\n\r");

    ccidDriver.sCcidMessage.bStatus = 0;
    ccidDriver.sCcidMessage.bError = 0;

    // Return the slot status to the host
    RDRtoPCSlotStatus();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// If the command header is valid, an APDU command is received and can be read
/// by the application
//------------------------------------------------------------------------------
static void PCtoRDRXfrBlock( void )
{
    unsigned char indexMessage = 0;
    unsigned char i;

    //TRACE_DEBUG("PCtoRDRXfrBlock\n\r");

    i = 0;

    // Check the block length
    if ( ccidDriver.sCcidCommand.wLength > (configurationDescriptorsFS.ccid.dwMaxCCIDMessageLength-10) ) {

        ccidDriver.sCcidMessage.bStatus = 1;
        ccidDriver.sCcidMessage.bError  = 0;
    }
    // check bBWI
    else if ( 0 != ccidDriver.sCcidCommand.bSpecific_0 ) {

         TRACE_ERROR("Bad bBWI\n\r");
    }
    else {

        // APDU or TPDU
        switch(configurationDescriptorsFS.ccid.dwFeatures 
              & (CCID_FEATURES_EXC_TPDU|CCID_FEATURES_EXC_SAPDU|CCID_FEATURES_EXC_APDU)) {

            case CCID_FEATURES_EXC_TPDU:
                if (ccidDriver.ProtocolDataStructure[1] == PROTOCOL_TO) {

                    // Send commande APDU
                    indexMessage = ISO7816_XfrBlockTPDU_T0( ccidDriver.sCcidCommand.APDU , 
                                            ccidDriver.sCcidMessage.abData, 
                                            ccidDriver.sCcidCommand.wLength );
                }
                else {
                    if (ccidDriver.ProtocolDataStructure[1] == PROTOCOL_T1) {
                        TRACE_INFO("Not supported T=1\n\r");
                    }
                    else {
                        TRACE_INFO("Not supported\n\r");
                    }
                }
                break;

            case CCID_FEATURES_EXC_APDU:
                TRACE_INFO("Not supported\n\r");
                break;

            default:
                break;
        }

    }

    ccidDriver.sCcidMessage.wLength = indexMessage;
    TRACE_DEBUG("USB: 0x%X, 0x%X, 0x%X, 0x%X, 0x%X\n\r", ccidDriver.sCcidMessage.abData[0], 
                                                                    ccidDriver.sCcidMessage.abData[1], 
                                                                    ccidDriver.sCcidMessage.abData[2], 
                                                                    ccidDriver.sCcidMessage.abData[3],
                                                                    ccidDriver.sCcidMessage.abData[4] );
     RDRtoPCDatablock();

}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// return parameters by the command: RDR_to_PC_Parameters
//------------------------------------------------------------------------------
static void PCtoRDRGetParameters( void )
{
    TRACE_DEBUG("PCtoRDRGetParameters\n\r");

    // We support only one slot

    // bmIccStatus
    if( ISO7816_StatusReset() ) {
        // 0: An ICC is present and active (power is on and stable, RST is inactive
        ccidDriver.sCcidMessage.bStatus = 0;
    }
    else {
        // 1: An ICC is present and inactive (not activated or shut down by hardware error)
        ccidDriver.sCcidMessage.bStatus = 1;
    }

    RDRtoPCParameters();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command resets the slot parameters to their default values
//------------------------------------------------------------------------------
static void PCtoRDRResetParameters( void )
{
    TRACE_DEBUG("PCtoRDRResetParameters\n\r");

    ccidDriver.SlotStatus = ICC_NOT_PRESENT;
    ccidDriver.sCcidMessage.bStatus = ccidDriver.SlotStatus;

    RDRtoPCParameters();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command is used to change the parameters for a given slot.
//------------------------------------------------------------------------------
static void PCtoRDRSetParameters( void )
{
    TRACE_DEBUG("PCtoRDRSetParameters\n\r");

    ccidDriver.SlotStatus = ccidDriver.sCcidCommand.bSlot;
    ccidDriver.sCcidMessage.bStatus = ccidDriver.SlotStatus;
    // Not all feature supported

    RDRtoPCParameters();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command allows the CCID manufacturer to define and access extended 
/// features. 
/// Information sent via this command is processed by the CCID control logic.
//------------------------------------------------------------------------------
static void PCtoRDREscape( void )
{
    TRACE_DEBUG("PCtoRDREscape\n\r");

    // If needed by the user
    ISO7816_Escape();

    // stub, return all value send
    RDRtoPCEscape( ccidDriver.sCcidCommand.wLength, ccidDriver.sCcidCommand.APDU);    
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command stops or restarts the clock.
//------------------------------------------------------------------------------
static void PCtoRDRICCClock( void )
{
    TRACE_DEBUG("PCtoRDRICCClock\n\r");

    if( 0 == ccidDriver.sCcidCommand.bSpecific_0 ) {
        // restarts the clock
        ISO7816_RestartClock();
    }
    else {
        // stop clock in the state shown in the bClockStop field
        ISO7816_StopClock();
    }

    RDRtoPCSlotStatus( );    
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command changes the parameters used to perform the transportation of 
/// APDU messages by the T=0 protocol. 
//------------------------------------------------------------------------------
static void PCtoRDRtoAPDU( void )
{
    unsigned char bmChanges;
    unsigned char bClassGetResponse;
    unsigned char bClassEnvelope;

    TRACE_DEBUG("PCtoRDRtoAPDU\n\r");

    if( configurationDescriptorsFS.ccid.dwFeatures == (CCID_FEATURES_EXC_SAPDU|CCID_FEATURES_EXC_APDU) ) {

        bmChanges = ccidDriver.sCcidCommand.bSpecific_0;
        bClassGetResponse = ccidDriver.sCcidCommand.bSpecific_1;
        bClassEnvelope = ccidDriver.sCcidCommand.bSpecific_2;

        ISO7816_toAPDU();
    }

    RDRtoPCSlotStatus();    
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This is a command message to allow entering the PIN for verification or
/// modification.
//------------------------------------------------------------------------------
static void PCtoRDRSecure( void )
{
    TRACE_DEBUG("PCtoRDRSecure\n\r");

    TRACE_DEBUG("For user\n\r");
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command is used to manage motorized type CCID functionality. 
/// The Lock Card function is used to hold the ICC. 
/// This prevents an ICC from being easily removed from the CCID. 
/// The Unlock Card function is used to remove the hold initiated by the Lock 
/// Card function
//------------------------------------------------------------------------------
static void PCtoRDRMechanical( void )
{
    TRACE_DEBUG("PCtoRDRMechanical\n\r");
    TRACE_DEBUG("Not implemented\n\r");

    RDRtoPCSlotStatus();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command is used with the Control pipe Abort request to tell the CCID 
/// to stop any current transfer at the specified slot and return to a state 
/// where the slot is ready to accept a new command pipe Bulk-OUT message.
//------------------------------------------------------------------------------
static void PCtoRDRAbort( void )
{
    TRACE_DEBUG("PCtoRDRAbort\n\r");

    RDRtoPCSlotStatus();
}

//------------------------------------------------------------------------------
/// Command Pipe, Bulk-OUT Messages
/// This command is used to manually set the data rate and clock frequency of 
/// a specific slot.
//------------------------------------------------------------------------------
static void PCtoRDRSetDataRateAndClockFrequency( void )
{
    unsigned int dwClockFrequency;
    unsigned int dwDataRate;

    TRACE_DEBUG("PCtoRDRSetDatarateandClockFrequency\n\r");

    dwClockFrequency = ccidDriver.sCcidCommand.APDU[0]
                     + (ccidDriver.sCcidCommand.APDU[1]<<8)
                     + (ccidDriver.sCcidCommand.APDU[2]<<16)
                     + (ccidDriver.sCcidCommand.APDU[3]<<24);

    dwDataRate = ccidDriver.sCcidCommand.APDU[4]
               + (ccidDriver.sCcidCommand.APDU[5]<<8)
               + (ccidDriver.sCcidCommand.APDU[6]<<16)
               + (ccidDriver.sCcidCommand.APDU[7]<<24);

    ISO7816_SetDataRateandClockFrequency( dwClockFrequency, dwDataRate );

    RDRtoPCDataRateAndClockFrequency( dwClockFrequency, dwDataRate );

}

//------------------------------------------------------------------------------
/// Report the CMD_NOT_SUPPORTED error to the host
//------------------------------------------------------------------------------
static void vCCIDCommandNotSupported( void )
{
    // Command not supported
    // vCCIDReportError(CMD_NOT_SUPPORTED);

    TRACE_DEBUG("CMD_NOT_SUPPORTED\n\r");

    // Header fields settings
    ccidDriver.sCcidMessage.bMessageType = RDR_TO_PC_SLOTSTATUS;
    ccidDriver.sCcidMessage.wLength      = 0;
    ccidDriver.sCcidMessage.bSpecific    = 0;

    ccidDriver.sCcidMessage.bStatus |= ICC_CS_FAILED;

    // Send the response to the host
    //vCCIDSendResponse();
}

//------------------------------------------------------------------------------
/// Sent CCID response on USB
//------------------------------------------------------------------------------
static void vCCIDSendResponse( void )
{
    unsigned char bStatus;

    do {
        bStatus = USBD_Write( CCID_EPT_DATA_IN, (void*)&ccidDriver.sCcidMessage, 
                              ccidDriver.sCcidMessage.bSizeToSend, 0, 0 );
    }
    while (bStatus != USBD_STATUS_SUCCESS);
}


//------------------------------------------------------------------------------
///  Description: CCID Command dispatcher
//------------------------------------------------------------------------------
static void CCIDCommandDispatcher( void )
{
    unsigned char MessageToSend = 0;

    //TRACE_DEBUG("Command: 0x%X 0x%x 0x%X 0x%X 0x%X 0x%X 0x%X\n\r\n\r",
    //               (unsigned int)ccidDriver.sCcidCommand.bMessageType,
    //               (unsigned int)ccidDriver.sCcidCommand.wLength,
    //               (unsigned int)ccidDriver.sCcidCommand.bSlot,
    //               (unsigned int)ccidDriver.sCcidCommand.bSeq,
    //               (unsigned int)ccidDriver.sCcidCommand.bSpecific_0,
    //               (unsigned int)ccidDriver.sCcidCommand.bSpecific_1,
    //               (unsigned int)ccidDriver.sCcidCommand.bSpecific_2);

    // Check the slot number
    if ( ccidDriver.sCcidCommand.bSlot > 0 ) {

        TRACE_ERROR("BAD_SLOT_NUMBER\n\r");
    }

    TRACE_DEBUG("typ=0x%X\n\r", ccidDriver.sCcidCommand.bMessageType);

    ccidDriver.sCcidMessage.bStatus = 0;

    ccidDriver.sCcidMessage.bSeq  = ccidDriver.sCcidCommand.bSeq;
    ccidDriver.sCcidMessage.bSlot = ccidDriver.sCcidCommand.bSlot;

    ccidDriver.sCcidMessage.bSizeToSend = sizeof(S_ccid_bulk_in_header)-(ABDATA_SIZE+1);


    // Command dispatcher
    switch ( ccidDriver.sCcidCommand.bMessageType ) {

        case PC_TO_RDR_ICCPOWERON:
            PCtoRDRIccPowerOn();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_ICCPOWEROFF:
            PCtoRDRIccPowerOff();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_GETSLOTSTATUS:
            PCtoRDRGetSlotStatus();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_XFRBLOCK:
            PCtoRDRXfrBlock();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_GETPARAMETERS:
            PCtoRDRGetParameters();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_RESETPARAMETERS:
            PCtoRDRResetParameters();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_SETPARAMETERS:
            PCtoRDRSetParameters();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_ESCAPE:
            PCtoRDREscape();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_ICCCLOCK:
            PCtoRDRICCClock();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_T0APDU:
            // Only CCIDs reporting a short or extended APDU level in the dwFeatures 
            // field of the CCID class descriptor may take this command into account.
            if( (CCID_FEATURES_EXC_SAPDU == (CCID_FEATURES_EXC_SAPDU&configurationDescriptorsFS.ccid.dwFeatures))
            || (CCID_FEATURES_EXC_APDU  == (CCID_FEATURES_EXC_APDU &configurationDescriptorsFS.ccid.dwFeatures)) ) {

                // command supported
                PCtoRDRtoAPDU();
            }
            else {
                // command not supported
                TRACE_DEBUG("PC_TO_RDR_T0APDU\n\r");
                vCCIDCommandNotSupported();
            }
            MessageToSend = 1;
            break;

        case PC_TO_RDR_SECURE:
            PCtoRDRSecure();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_MECHANICAL:
            PCtoRDRMechanical();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_ABORT:
            PCtoRDRAbort();
            MessageToSend = 1;
            break;

        case PC_TO_RDR_SETDATARATEANDCLOCKFREQUENCY:
            PCtoRDRSetDataRateAndClockFrequency();
            MessageToSend = 1;
            break;

        default:
            TRACE_DEBUG("default: 0x%X\n\r", ccidDriver.sCcidCommand.bMessageType);
            vCCIDCommandNotSupported();
            MessageToSend = 1;
            break;

    }

    if( MessageToSend == 1 ) {
        vCCIDSendResponse();
    }
}


//------------------------------------------------------------------------------
/// SETUP request handler for a CCID device
/// \param pRequest Pointer to a USBGenericRequest instance
//------------------------------------------------------------------------------
static void CCID_RequestHandler(const USBGenericRequest *pRequest)
{
    TRACE_DEBUG("CCID_RHl\n\r");

    // Check if this is a class request
    if (USBGenericRequest_GetType(pRequest) == USBGenericRequest_CLASS) {

        // Check if the request is supported
        switch (USBGenericRequest_GetRequest(pRequest)) {

            case CCIDGenericRequest_ABORT:
                TRACE_DEBUG("CCIDGenericRequest_ABORT\n\r");
                break;

            case CCIDGenericRequest_GET_CLOCK_FREQUENCIES:
                TRACE_DEBUG("Not supported\n\r");
                // A CCID with bNumClockSupported equal to 00h does not have 
                // to support this request
                break;

            case CCIDGenericRequest_GET_DATA_RATES:
                TRACE_DEBUG("Not supported\n\r");
                // A CCID with bNumDataRatesSupported equal to 00h does not have 
                // to support this request.
                break;

            default:
                TRACE_WARNING( "CCIDDriver_RequestHandler: Unsupported request (%d)\n\r",
                                                    USBGenericRequest_GetRequest(pRequest));
                USBD_Stall(0);
        }
    }

    else if (USBGenericRequest_GetType(pRequest) == USBGenericRequest_STANDARD) {

        // Forward request to the standard handler
        USBDDriver_RequestHandler(&(ccidDriver.usbdDriver), pRequest);
    }
    else {

        // Unsupported request type
        TRACE_WARNING( "CCIDDriver_RequestHandler: Unsupported request type (%d)\n\r",
                                                    USBGenericRequest_GetType(pRequest));
        USBD_Stall(0);
    }
}


//------------------------------------------------------------------------------
//      Exported functions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
/// Optional callback re-implementation
//------------------------------------------------------------------------------
#if !defined(NOAUTOCALLBACK)
// not static function
void USBDCallbacks_RequestReceived(const USBGenericRequest *request)
{
    CCID_RequestHandler(request);
}
#endif


//------------------------------------------------------------------------------
/// Handles SmartCart request
//------------------------------------------------------------------------------
void CCID_SmartCardRequest( void )
{
    unsigned char bStatus;

    do {

        bStatus = CCID_Read( (void*)&ccidDriver.sCcidCommand,
                             sizeof(S_ccid_bulk_out_header),
                             (TransferCallback)&CCIDCommandDispatcher,
                             (void*)0 );
    } 
    while (bStatus != USBD_STATUS_SUCCESS);

}

//------------------------------------------------------------------------------
/// Initializes the CCID device driver.
//------------------------------------------------------------------------------
void CCIDDriver_Initialize( void )
{
    TRACE_DEBUG("CCID_Init\n\r");
    USBDDriver_Initialize(&(ccidDriver.usbdDriver),
                          &ccidDriverDescriptors,
                          0); // Multiple interface settings not supported
    USBD_Init();
}

//------------------------------------------------------------------------------
/// Reads data from the Data OUT endpoint
/// \param pBuffer   Buffer to store the received data
/// \param dLength   data buffer length
/// \param fCallback Optional callback function
/// \param pArgument Optional parameter for the callback function
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char CCID_Read(void *pBuffer,
                        unsigned int dLength,
                        TransferCallback fCallback,
                        void *pArgument)
{
    return USBD_Read(CCID_EPT_DATA_OUT, pBuffer, dLength, fCallback, pArgument);
}

//------------------------------------------------------------------------------
/// Sends data through the Data IN endpoint
/// \param pBuffer   Buffer holding the data to transmit
/// \param dLength   Length of data buffer
/// \param fCallback Optional callback function
/// \param pArgument Optional parameter for the callback function
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char CCID_Write(void *pBuffer,
                         unsigned int dLength,
                         TransferCallback fCallback,
                         void *pArgument)
{
    return USBD_Write(CCID_EPT_DATA_IN, pBuffer, dLength, fCallback, pArgument);
}

//------------------------------------------------------------------------------
/// Sends data through the interrupt endpoint, ICC insertion event
/// RDR_to_PC_NotifySlotChange
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char CCID_Insertion( void )
{
    TRACE_DEBUG("CCID_Insertion\n\r");

    // Build the Interrupt-IN message
    ccidDriver.BufferINT[0] = RDR_TO_PC_NOTIFYSLOTCHANGE;
    ccidDriver.BufferINT[1] = ICC_INSERTED_EVENT;
    ccidDriver.SlotStatus   = ICC_INSERTED_EVENT;

    // Notify the host that a ICC is inserted
    return USBD_Write( CCID_EPT_NOTIFICATION, ccidDriver.BufferINT, 2, 0, 0 );
}

//------------------------------------------------------------------------------
/// Sends data through the interrupt endpoint, ICC removal event
/// RDR_to_PC_NotifySlotChange
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char CCID_Removal( void )
{
    TRACE_DEBUG("CCID_Removal\n\r");

    // Build the Interrupt-IN message
    ccidDriver.BufferINT[0] = RDR_TO_PC_NOTIFYSLOTCHANGE;
    ccidDriver.BufferINT[1] = ICC_NOT_PRESENT;
    ccidDriver.SlotStatus   = ICC_NOT_PRESENT;

    // Notify the host that a ICC is inserted
    return USBD_Write( CCID_EPT_NOTIFICATION, ccidDriver.BufferINT, 2, 0, 0 );
}

//------------------------------------------------------------------------------
/// Interrupt-IN Messages
/// This message is sent when any bit in the bHardwareErrorCode field is set. 
/// If this message is sent when there is no “outstanding” command, the bSeq 
/// field will be undefined.
/// \param bSlot ICC slot number
/// \param bSeq  Sequence number of the bulk OUT command when the hardware error
/// occured
/// \param bHardwareErrorCode Hardware error code
/// \return USBD_STATUS_LOCKED or USBD_STATUS_SUCCESS
//------------------------------------------------------------------------------
unsigned char RDRtoPCHardwareError( unsigned char bSlot, 
                                    unsigned char bSeq, 
                                    unsigned char bHardwareErrorCode )
{
    TRACE_DEBUG("RDRtoPCHardwareError\n\r");

    // Build the Interrupt-IN message
    ccidDriver.BufferINT[0] = RDR_TO_PC_HARDWAREERROR;
    ccidDriver.BufferINT[1] = bSlot;
    ccidDriver.BufferINT[2] = bSeq;
    ccidDriver.BufferINT[3] = bHardwareErrorCode;

    // Notify the host that a ICC is inserted
    return USBD_Write( CCID_EPT_NOTIFICATION, ccidDriver.BufferINT, 4, 0, 0 );
}


personal git repositories of Harald Welte. Your mileage may vary