xref: /openbmc/qemu/hw/usb/dev-smartcard-reader.c (revision 0399a381)
1 /*
2  * Copyright (C) 2011 Red Hat, Inc.
3  *
4  * CCID Device emulation
5  *
6  * Written by Alon Levy, with contributions from Robert Relyea.
7  *
8  * Based on usb-serial.c, see its copyright and attributions below.
9  *
10  * This work is licensed under the terms of the GNU GPL, version 2.1 or later.
11  * See the COPYING file in the top-level directory.
12  * ------- (original copyright & attribution for usb-serial.c below) --------
13  * Copyright (c) 2006 CodeSourcery.
14  * Copyright (c) 2008 Samuel Thibault <samuel.thibault@ens-lyon.org>
15  * Written by Paul Brook, reused for FTDI by Samuel Thibault,
16  */
17 
18 /*
19  * References:
20  *
21  * CCID Specification Revision 1.1 April 22nd 2005
22  *  "Universal Serial Bus, Device Class: Smart Card"
23  *  Specification for Integrated Circuit(s) Cards Interface Devices
24  *
25  * Endianness note: from the spec (1.3)
26  *  "Fields that are larger than a byte are stored in little endian"
27  *
28  * KNOWN BUGS
29  * 1. remove/insert can sometimes result in removed state instead of inserted.
30  * This is a result of the following:
31  *  symptom: dmesg shows ERMOTEIO (-121), pcscd shows -99. This can happen
32  *  when a short packet is sent, as seen in uhci-usb.c, resulting from a urb
33  *  from the guest requesting SPD and us returning a smaller packet.
34  *  Not sure which messages trigger this.
35  */
36 
37 #include "qemu-common.h"
38 #include "qemu/error-report.h"
39 #include "hw/usb.h"
40 #include "hw/usb/desc.h"
41 #include "monitor/monitor.h"
42 
43 #include "ccid.h"
44 
45 #define DPRINTF(s, lvl, fmt, ...) \
46 do { \
47     if (lvl <= s->debug) { \
48         printf("usb-ccid: " fmt , ## __VA_ARGS__); \
49     } \
50 } while (0)
51 
52 #define D_WARN 1
53 #define D_INFO 2
54 #define D_MORE_INFO 3
55 #define D_VERBOSE 4
56 
57 #define CCID_DEV_NAME "usb-ccid"
58 
59 /*
60  * The two options for variable sized buffers:
61  * make them constant size, for large enough constant,
62  * or handle the migration complexity - VMState doesn't handle this case.
63  * sizes are expected never to be exceeded, unless guest misbehaves.
64  */
65 #define BULK_OUT_DATA_SIZE 65536
66 #define PENDING_ANSWERS_NUM 128
67 
68 #define BULK_IN_BUF_SIZE 384
69 #define BULK_IN_PENDING_NUM 8
70 
71 #define CCID_MAX_PACKET_SIZE                64
72 
73 #define CCID_CONTROL_ABORT                  0x1
74 #define CCID_CONTROL_GET_CLOCK_FREQUENCIES  0x2
75 #define CCID_CONTROL_GET_DATA_RATES         0x3
76 
77 #define CCID_PRODUCT_DESCRIPTION        "QEMU USB CCID"
78 #define CCID_VENDOR_DESCRIPTION         "QEMU"
79 #define CCID_INTERFACE_NAME             "CCID Interface"
80 #define CCID_SERIAL_NUMBER_STRING       "1"
81 /*
82  * Using Gemplus Vendor and Product id
83  * Effect on various drivers:
84  *  usbccid.sys (winxp, others untested) is a class driver so it doesn't care.
85  *  linux has a number of class drivers, but openct filters based on
86  *   vendor/product (/etc/openct.conf under fedora), hence Gemplus.
87  */
88 #define CCID_VENDOR_ID                  0x08e6
89 #define CCID_PRODUCT_ID                 0x4433
90 #define CCID_DEVICE_VERSION             0x0000
91 
92 /*
93  * BULK_OUT messages from PC to Reader
94  * Defined in CCID Rev 1.1 6.1 (page 26)
95  */
96 #define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn              0x62
97 #define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff             0x63
98 #define CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus           0x65
99 #define CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock                0x6f
100 #define CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters           0x6c
101 #define CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters         0x6d
102 #define CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters           0x61
103 #define CCID_MESSAGE_TYPE_PC_to_RDR_Escape                  0x6b
104 #define CCID_MESSAGE_TYPE_PC_to_RDR_IccClock                0x6e
105 #define CCID_MESSAGE_TYPE_PC_to_RDR_T0APDU                  0x6a
106 #define CCID_MESSAGE_TYPE_PC_to_RDR_Secure                  0x69
107 #define CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical              0x71
108 #define CCID_MESSAGE_TYPE_PC_to_RDR_Abort                   0x72
109 #define CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency 0x73
110 
111 /*
112  * BULK_IN messages from Reader to PC
113  * Defined in CCID Rev 1.1 6.2 (page 48)
114  */
115 #define CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock               0x80
116 #define CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus              0x81
117 #define CCID_MESSAGE_TYPE_RDR_to_PC_Parameters              0x82
118 #define CCID_MESSAGE_TYPE_RDR_to_PC_Escape                  0x83
119 #define CCID_MESSAGE_TYPE_RDR_to_PC_DataRateAndClockFrequency 0x84
120 
121 /*
122  * INTERRUPT_IN messages from Reader to PC
123  * Defined in CCID Rev 1.1 6.3 (page 56)
124  */
125 #define CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange        0x50
126 #define CCID_MESSAGE_TYPE_RDR_to_PC_HardwareError           0x51
127 
128 /*
129  * Endpoints for CCID - addresses are up to us to decide.
130  * To support slot insertion and removal we must have an interrupt in ep
131  * in addition we need a bulk in and bulk out ep
132  * 5.2, page 20
133  */
134 #define CCID_INT_IN_EP       1
135 #define CCID_BULK_IN_EP      2
136 #define CCID_BULK_OUT_EP     3
137 
138 /* bmSlotICCState masks */
139 #define SLOT_0_STATE_MASK    1
140 #define SLOT_0_CHANGED_MASK  2
141 
142 /* Status codes that go in bStatus (see 6.2.6) */
143 enum {
144     ICC_STATUS_PRESENT_ACTIVE = 0,
145     ICC_STATUS_PRESENT_INACTIVE,
146     ICC_STATUS_NOT_PRESENT
147 };
148 
149 enum {
150     COMMAND_STATUS_NO_ERROR = 0,
151     COMMAND_STATUS_FAILED,
152     COMMAND_STATUS_TIME_EXTENSION_REQUIRED
153 };
154 
155 /* Error codes that go in bError (see 6.2.6) */
156 enum {
157     ERROR_CMD_NOT_SUPPORTED = 0,
158     ERROR_CMD_ABORTED       = -1,
159     ERROR_ICC_MUTE          = -2,
160     ERROR_XFR_PARITY_ERROR  = -3,
161     ERROR_XFR_OVERRUN       = -4,
162     ERROR_HW_ERROR          = -5,
163 };
164 
165 /* 6.2.6 RDR_to_PC_SlotStatus definitions */
166 enum {
167     CLOCK_STATUS_RUNNING = 0,
168     /*
169      * 0 - Clock Running, 1 - Clock stopped in State L, 2 - H,
170      * 3 - unknown state. rest are RFU
171      */
172 };
173 
174 typedef struct QEMU_PACKED CCID_Header {
175     uint8_t     bMessageType;
176     uint32_t    dwLength;
177     uint8_t     bSlot;
178     uint8_t     bSeq;
179 } CCID_Header;
180 
181 typedef struct QEMU_PACKED CCID_BULK_IN {
182     CCID_Header hdr;
183     uint8_t     bStatus;        /* Only used in BULK_IN */
184     uint8_t     bError;         /* Only used in BULK_IN */
185 } CCID_BULK_IN;
186 
187 typedef struct QEMU_PACKED CCID_SlotStatus {
188     CCID_BULK_IN b;
189     uint8_t     bClockStatus;
190 } CCID_SlotStatus;
191 
192 typedef struct QEMU_PACKED CCID_T0ProtocolDataStructure {
193     uint8_t     bmFindexDindex;
194     uint8_t     bmTCCKST0;
195     uint8_t     bGuardTimeT0;
196     uint8_t     bWaitingIntegerT0;
197     uint8_t     bClockStop;
198 } CCID_T0ProtocolDataStructure;
199 
200 typedef struct QEMU_PACKED CCID_T1ProtocolDataStructure {
201     uint8_t     bmFindexDindex;
202     uint8_t     bmTCCKST1;
203     uint8_t     bGuardTimeT1;
204     uint8_t     bWaitingIntegerT1;
205     uint8_t     bClockStop;
206     uint8_t     bIFSC;
207     uint8_t     bNadValue;
208 } CCID_T1ProtocolDataStructure;
209 
210 typedef union CCID_ProtocolDataStructure {
211     CCID_T0ProtocolDataStructure t0;
212     CCID_T1ProtocolDataStructure t1;
213     uint8_t data[7]; /* must be = max(sizeof(t0), sizeof(t1)) */
214 } CCID_ProtocolDataStructure;
215 
216 typedef struct QEMU_PACKED CCID_Parameter {
217     CCID_BULK_IN b;
218     uint8_t     bProtocolNum;
219     CCID_ProtocolDataStructure abProtocolDataStructure;
220 } CCID_Parameter;
221 
222 typedef struct QEMU_PACKED CCID_DataBlock {
223     CCID_BULK_IN b;
224     uint8_t      bChainParameter;
225     uint8_t      abData[0];
226 } CCID_DataBlock;
227 
228 /* 6.1.4 PC_to_RDR_XfrBlock */
229 typedef struct QEMU_PACKED CCID_XferBlock {
230     CCID_Header  hdr;
231     uint8_t      bBWI; /* Block Waiting Timeout */
232     uint16_t     wLevelParameter; /* XXX currently unused */
233     uint8_t      abData[0];
234 } CCID_XferBlock;
235 
236 typedef struct QEMU_PACKED CCID_IccPowerOn {
237     CCID_Header hdr;
238     uint8_t     bPowerSelect;
239     uint16_t    abRFU;
240 } CCID_IccPowerOn;
241 
242 typedef struct QEMU_PACKED CCID_IccPowerOff {
243     CCID_Header hdr;
244     uint16_t    abRFU;
245 } CCID_IccPowerOff;
246 
247 typedef struct QEMU_PACKED CCID_SetParameters {
248     CCID_Header hdr;
249     uint8_t     bProtocolNum;
250     uint16_t   abRFU;
251     CCID_ProtocolDataStructure abProtocolDataStructure;
252 } CCID_SetParameters;
253 
254 typedef struct CCID_Notify_Slot_Change {
255     uint8_t     bMessageType; /* CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange */
256     uint8_t     bmSlotICCState;
257 } CCID_Notify_Slot_Change;
258 
259 /* used for DataBlock response to XferBlock */
260 typedef struct Answer {
261     uint8_t slot;
262     uint8_t seq;
263 } Answer;
264 
265 /* pending BULK_IN messages */
266 typedef struct BulkIn {
267     uint8_t  data[BULK_IN_BUF_SIZE];
268     uint32_t len;
269     uint32_t pos;
270 } BulkIn;
271 
272 enum {
273     MIGRATION_NONE,
274     MIGRATION_MIGRATED,
275 };
276 
277 typedef struct CCIDBus {
278     BusState qbus;
279 } CCIDBus;
280 
281 /*
282  * powered - defaults to true, changed by PowerOn/PowerOff messages
283  */
284 typedef struct USBCCIDState {
285     USBDevice dev;
286     USBEndpoint *intr;
287     CCIDBus bus;
288     CCIDCardState *card;
289     BulkIn bulk_in_pending[BULK_IN_PENDING_NUM]; /* circular */
290     uint32_t bulk_in_pending_start;
291     uint32_t bulk_in_pending_end; /* first free */
292     uint32_t bulk_in_pending_num;
293     BulkIn *current_bulk_in;
294     uint8_t  bulk_out_data[BULK_OUT_DATA_SIZE];
295     uint32_t bulk_out_pos;
296     uint64_t last_answer_error;
297     Answer pending_answers[PENDING_ANSWERS_NUM];
298     uint32_t pending_answers_start;
299     uint32_t pending_answers_end;
300     uint32_t pending_answers_num;
301     uint8_t  bError;
302     uint8_t  bmCommandStatus;
303     uint8_t  bProtocolNum;
304     CCID_ProtocolDataStructure abProtocolDataStructure;
305     uint32_t ulProtocolDataStructureSize;
306     uint32_t state_vmstate;
307     uint32_t migration_target_ip;
308     uint16_t migration_target_port;
309     uint8_t  migration_state;
310     uint8_t  bmSlotICCState;
311     uint8_t  powered;
312     uint8_t  notify_slot_change;
313     uint8_t  debug;
314 } USBCCIDState;
315 
316 /*
317  * CCID Spec chapter 4: CCID uses a standard device descriptor per Chapter 9,
318  * "USB Device Framework", section 9.6.1, in the Universal Serial Bus
319  * Specification.
320  *
321  * This device implemented based on the spec and with an Athena Smart Card
322  * Reader as reference:
323  *   0dc3:1004 Athena Smartcard Solutions, Inc.
324  */
325 
326 static const uint8_t qemu_ccid_descriptor[] = {
327         /* Smart Card Device Class Descriptor */
328         0x36,       /* u8  bLength; */
329         0x21,       /* u8  bDescriptorType; Functional */
330         0x10, 0x01, /* u16 bcdCCID; CCID Specification Release Number. */
331         0x00,       /*
332                      * u8  bMaxSlotIndex; The index of the highest available
333                      * slot on this device. All slots are consecutive starting
334                      * at 00h.
335                      */
336         0x07,       /* u8  bVoltageSupport; 01h - 5.0v, 02h - 3.0, 03 - 1.8 */
337 
338         0x00, 0x00, /* u32 dwProtocols; RRRR PPPP. RRRR = 0000h.*/
339         0x01, 0x00, /* PPPP: 0001h = Protocol T=0, 0002h = Protocol T=1 */
340                     /* u32 dwDefaultClock; in kHZ (0x0fa0 is 4 MHz) */
341         0xa0, 0x0f, 0x00, 0x00,
342                     /* u32 dwMaximumClock; */
343         0x00, 0x00, 0x01, 0x00,
344         0x00,       /* u8 bNumClockSupported;                 *
345                      *    0 means just the default and max.   */
346                     /* u32 dwDataRate ;bps. 9600 == 00002580h */
347         0x80, 0x25, 0x00, 0x00,
348                     /* u32 dwMaxDataRate ; 11520 bps == 0001C200h */
349         0x00, 0xC2, 0x01, 0x00,
350         0x00,       /* u8  bNumDataRatesSupported; 00 means all rates between
351                      *     default and max */
352                     /* u32 dwMaxIFSD;                                  *
353                      *     maximum IFSD supported by CCID for protocol *
354                      *     T=1 (Maximum seen from various cards)       */
355         0xfe, 0x00, 0x00, 0x00,
356                     /* u32 dwSyncProtocols; 1 - 2-wire, 2 - 3-wire, 4 - I2C */
357         0x00, 0x00, 0x00, 0x00,
358                     /* u32 dwMechanical;  0 - no special characteristics. */
359         0x00, 0x00, 0x00, 0x00,
360                     /*
361                      * u32 dwFeatures;
362                      * 0 - No special characteristics
363                      * + 2 Automatic parameter configuration based on ATR data
364                      * + 4 Automatic activation of ICC on inserting
365                      * + 8 Automatic ICC voltage selection
366                      * + 10 Automatic ICC clock frequency change
367                      * + 20 Automatic baud rate change
368                      * + 40 Automatic parameters negotiation made by the CCID
369                      * + 80 automatic PPS made by the CCID
370                      * 100 CCID can set ICC in clock stop mode
371                      * 200 NAD value other then 00 accepted (T=1 protocol)
372                      * + 400 Automatic IFSD exchange as first exchange (T=1)
373                      * One of the following only:
374                      * + 10000 TPDU level exchanges with CCID
375                      * 20000 Short APDU level exchange with CCID
376                      * 40000 Short and Extended APDU level exchange with CCID
377                      *
378                      * 100000 USB Wake up signaling supported on card
379                      * insertion and removal. Must set bit 5 in bmAttributes
380                      * in Configuration descriptor if 100000 is set.
381                      */
382         0xfe, 0x04, 0x01, 0x00,
383                     /*
384                      * u32 dwMaxCCIDMessageLength; For extended APDU in
385                      * [261 + 10 , 65544 + 10]. Otherwise the minimum is
386                      * wMaxPacketSize of the Bulk-OUT endpoint
387                      */
388         0x12, 0x00, 0x01, 0x00,
389         0xFF,       /*
390                      * u8  bClassGetResponse; Significant only for CCID that
391                      * offers an APDU level for exchanges. Indicates the
392                      * default class value used by the CCID when it sends a
393                      * Get Response command to perform the transportation of
394                      * an APDU by T=0 protocol
395                      * FFh indicates that the CCID echos the class of the APDU.
396                      */
397         0xFF,       /*
398                      * u8  bClassEnvelope; EAPDU only. Envelope command for
399                      * T=0
400                      */
401         0x00, 0x00, /*
402                      * u16 wLcdLayout; XXYY Number of lines (XX) and chars per
403                      * line for LCD display used for PIN entry. 0000 - no LCD
404                      */
405         0x01,       /*
406                      * u8  bPINSupport; 01h PIN Verification,
407                      *                  02h PIN Modification
408                      */
409         0x01,       /* u8  bMaxCCIDBusySlots; */
410 };
411 
412 enum {
413     STR_MANUFACTURER = 1,
414     STR_PRODUCT,
415     STR_SERIALNUMBER,
416     STR_INTERFACE,
417 };
418 
419 static const USBDescStrings desc_strings = {
420     [STR_MANUFACTURER]  = "QEMU",
421     [STR_PRODUCT]       = "QEMU USB CCID",
422     [STR_SERIALNUMBER]  = "1",
423     [STR_INTERFACE]     = "CCID Interface",
424 };
425 
426 static const USBDescIface desc_iface0 = {
427     .bInterfaceNumber              = 0,
428     .bNumEndpoints                 = 3,
429     .bInterfaceClass               = USB_CLASS_CSCID,
430     .bInterfaceSubClass            = USB_SUBCLASS_UNDEFINED,
431     .bInterfaceProtocol            = 0x00,
432     .iInterface                    = STR_INTERFACE,
433     .ndesc                         = 1,
434     .descs = (USBDescOther[]) {
435         {
436             /* smartcard descriptor */
437             .data = qemu_ccid_descriptor,
438         },
439     },
440     .eps = (USBDescEndpoint[]) {
441         {
442             .bEndpointAddress      = USB_DIR_IN | CCID_INT_IN_EP,
443             .bmAttributes          = USB_ENDPOINT_XFER_INT,
444             .bInterval             = 255,
445             .wMaxPacketSize        = 64,
446         },{
447             .bEndpointAddress      = USB_DIR_IN | CCID_BULK_IN_EP,
448             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
449             .wMaxPacketSize        = 64,
450         },{
451             .bEndpointAddress      = USB_DIR_OUT | CCID_BULK_OUT_EP,
452             .bmAttributes          = USB_ENDPOINT_XFER_BULK,
453             .wMaxPacketSize        = 64,
454         },
455     }
456 };
457 
458 static const USBDescDevice desc_device = {
459     .bcdUSB                        = 0x0110,
460     .bMaxPacketSize0               = 64,
461     .bNumConfigurations            = 1,
462     .confs = (USBDescConfig[]) {
463         {
464             .bNumInterfaces        = 1,
465             .bConfigurationValue   = 1,
466             .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER |
467                                      USB_CFG_ATT_WAKEUP,
468             .bMaxPower             = 50,
469             .nif = 1,
470             .ifs = &desc_iface0,
471         },
472     },
473 };
474 
475 static const USBDesc desc_ccid = {
476     .id = {
477         .idVendor          = CCID_VENDOR_ID,
478         .idProduct         = CCID_PRODUCT_ID,
479         .bcdDevice         = CCID_DEVICE_VERSION,
480         .iManufacturer     = STR_MANUFACTURER,
481         .iProduct          = STR_PRODUCT,
482         .iSerialNumber     = STR_SERIALNUMBER,
483     },
484     .full = &desc_device,
485     .str  = desc_strings,
486 };
487 
488 static const uint8_t *ccid_card_get_atr(CCIDCardState *card, uint32_t *len)
489 {
490     CCIDCardClass *cc = CCID_CARD_GET_CLASS(card);
491 
492     if (cc->get_atr) {
493         return cc->get_atr(card, len);
494     }
495     return NULL;
496 }
497 
498 static void ccid_card_apdu_from_guest(CCIDCardState *card,
499                                       const uint8_t *apdu,
500                                       uint32_t len)
501 {
502     CCIDCardClass *cc = CCID_CARD_GET_CLASS(card);
503 
504     if (cc->apdu_from_guest) {
505         cc->apdu_from_guest(card, apdu, len);
506     }
507 }
508 
509 static int ccid_card_exitfn(CCIDCardState *card)
510 {
511     CCIDCardClass *cc = CCID_CARD_GET_CLASS(card);
512 
513     if (cc->exitfn) {
514         return cc->exitfn(card);
515     }
516     return 0;
517 }
518 
519 static int ccid_card_initfn(CCIDCardState *card)
520 {
521     CCIDCardClass *cc = CCID_CARD_GET_CLASS(card);
522 
523     if (cc->initfn) {
524         return cc->initfn(card);
525     }
526     return 0;
527 }
528 
529 static bool ccid_has_pending_answers(USBCCIDState *s)
530 {
531     return s->pending_answers_num > 0;
532 }
533 
534 static void ccid_clear_pending_answers(USBCCIDState *s)
535 {
536     s->pending_answers_num = 0;
537     s->pending_answers_start = 0;
538     s->pending_answers_end = 0;
539 }
540 
541 static void ccid_print_pending_answers(USBCCIDState *s)
542 {
543     Answer *answer;
544     int i, count;
545 
546     DPRINTF(s, D_VERBOSE, "usb-ccid: pending answers:");
547     if (!ccid_has_pending_answers(s)) {
548         DPRINTF(s, D_VERBOSE, " empty\n");
549         return;
550     }
551     for (i = s->pending_answers_start, count = s->pending_answers_num ;
552          count > 0; count--, i++) {
553         answer = &s->pending_answers[i % PENDING_ANSWERS_NUM];
554         if (count == 1) {
555             DPRINTF(s, D_VERBOSE, "%d:%d\n", answer->slot, answer->seq);
556         } else {
557             DPRINTF(s, D_VERBOSE, "%d:%d,", answer->slot, answer->seq);
558         }
559     }
560 }
561 
562 static void ccid_add_pending_answer(USBCCIDState *s, CCID_Header *hdr)
563 {
564     Answer *answer;
565 
566     assert(s->pending_answers_num < PENDING_ANSWERS_NUM);
567     s->pending_answers_num++;
568     answer =
569         &s->pending_answers[(s->pending_answers_end++) % PENDING_ANSWERS_NUM];
570     answer->slot = hdr->bSlot;
571     answer->seq = hdr->bSeq;
572     ccid_print_pending_answers(s);
573 }
574 
575 static void ccid_remove_pending_answer(USBCCIDState *s,
576     uint8_t *slot, uint8_t *seq)
577 {
578     Answer *answer;
579 
580     assert(s->pending_answers_num > 0);
581     s->pending_answers_num--;
582     answer =
583         &s->pending_answers[(s->pending_answers_start++) % PENDING_ANSWERS_NUM];
584     *slot = answer->slot;
585     *seq = answer->seq;
586     ccid_print_pending_answers(s);
587 }
588 
589 static void ccid_bulk_in_clear(USBCCIDState *s)
590 {
591     s->bulk_in_pending_start = 0;
592     s->bulk_in_pending_end = 0;
593     s->bulk_in_pending_num = 0;
594 }
595 
596 static void ccid_bulk_in_release(USBCCIDState *s)
597 {
598     assert(s->current_bulk_in != NULL);
599     s->current_bulk_in->pos = 0;
600     s->current_bulk_in = NULL;
601 }
602 
603 static void ccid_bulk_in_get(USBCCIDState *s)
604 {
605     if (s->current_bulk_in != NULL || s->bulk_in_pending_num == 0) {
606         return;
607     }
608     assert(s->bulk_in_pending_num > 0);
609     s->bulk_in_pending_num--;
610     s->current_bulk_in =
611         &s->bulk_in_pending[(s->bulk_in_pending_start++) % BULK_IN_PENDING_NUM];
612 }
613 
614 static void *ccid_reserve_recv_buf(USBCCIDState *s, uint16_t len)
615 {
616     BulkIn *bulk_in;
617 
618     DPRINTF(s, D_VERBOSE, "%s: QUEUE: reserve %d bytes\n", __func__, len);
619 
620     /* look for an existing element */
621     if (len > BULK_IN_BUF_SIZE) {
622         DPRINTF(s, D_WARN, "usb-ccid.c: %s: len larger then max (%d>%d). "
623                            "discarding message.\n",
624                            __func__, len, BULK_IN_BUF_SIZE);
625         return NULL;
626     }
627     if (s->bulk_in_pending_num >= BULK_IN_PENDING_NUM) {
628         DPRINTF(s, D_WARN, "usb-ccid.c: %s: No free bulk_in buffers. "
629                            "discarding message.\n", __func__);
630         return NULL;
631     }
632     bulk_in =
633         &s->bulk_in_pending[(s->bulk_in_pending_end++) % BULK_IN_PENDING_NUM];
634     s->bulk_in_pending_num++;
635     bulk_in->len = len;
636     return bulk_in->data;
637 }
638 
639 static void ccid_reset(USBCCIDState *s)
640 {
641     ccid_bulk_in_clear(s);
642     ccid_clear_pending_answers(s);
643 }
644 
645 static void ccid_detach(USBCCIDState *s)
646 {
647     ccid_reset(s);
648 }
649 
650 static void ccid_handle_reset(USBDevice *dev)
651 {
652     USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
653 
654     DPRINTF(s, 1, "Reset\n");
655 
656     ccid_reset(s);
657 }
658 
659 static const char *ccid_control_to_str(USBCCIDState *s, int request)
660 {
661     switch (request) {
662         /* generic - should be factored out if there are other debugees */
663     case DeviceOutRequest | USB_REQ_SET_ADDRESS:
664         return "(generic) set address";
665     case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
666         return "(generic) get descriptor";
667     case DeviceRequest | USB_REQ_GET_CONFIGURATION:
668         return "(generic) get configuration";
669     case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
670         return "(generic) set configuration";
671     case DeviceRequest | USB_REQ_GET_STATUS:
672         return "(generic) get status";
673     case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
674         return "(generic) clear feature";
675     case DeviceOutRequest | USB_REQ_SET_FEATURE:
676         return "(generic) set_feature";
677     case InterfaceRequest | USB_REQ_GET_INTERFACE:
678         return "(generic) get interface";
679     case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
680         return "(generic) set interface";
681         /* class requests */
682     case ClassInterfaceOutRequest | CCID_CONTROL_ABORT:
683         return "ABORT";
684     case ClassInterfaceRequest | CCID_CONTROL_GET_CLOCK_FREQUENCIES:
685         return "GET_CLOCK_FREQUENCIES";
686     case ClassInterfaceRequest | CCID_CONTROL_GET_DATA_RATES:
687         return "GET_DATA_RATES";
688     }
689     return "unknown";
690 }
691 
692 static void ccid_handle_control(USBDevice *dev, USBPacket *p, int request,
693                                int value, int index, int length, uint8_t *data)
694 {
695     USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
696     int ret;
697 
698     DPRINTF(s, 1, "%s: got control %s (%x), value %x\n", __func__,
699             ccid_control_to_str(s, request), request, value);
700     ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
701     if (ret >= 0) {
702         return;
703     }
704 
705     switch (request) {
706         /* Class specific requests.  */
707     case ClassInterfaceOutRequest | CCID_CONTROL_ABORT:
708         DPRINTF(s, 1, "ccid_control abort UNIMPLEMENTED\n");
709         p->status = USB_RET_STALL;
710         break;
711     case ClassInterfaceRequest | CCID_CONTROL_GET_CLOCK_FREQUENCIES:
712         DPRINTF(s, 1, "ccid_control get clock frequencies UNIMPLEMENTED\n");
713         p->status = USB_RET_STALL;
714         break;
715     case ClassInterfaceRequest | CCID_CONTROL_GET_DATA_RATES:
716         DPRINTF(s, 1, "ccid_control get data rates UNIMPLEMENTED\n");
717         p->status = USB_RET_STALL;
718         break;
719     default:
720         DPRINTF(s, 1, "got unsupported/bogus control %x, value %x\n",
721                 request, value);
722         p->status = USB_RET_STALL;
723         break;
724     }
725 }
726 
727 static bool ccid_card_inserted(USBCCIDState *s)
728 {
729     return s->bmSlotICCState & SLOT_0_STATE_MASK;
730 }
731 
732 static uint8_t ccid_card_status(USBCCIDState *s)
733 {
734     return ccid_card_inserted(s)
735             ? (s->powered ?
736                 ICC_STATUS_PRESENT_ACTIVE
737               : ICC_STATUS_PRESENT_INACTIVE
738               )
739             : ICC_STATUS_NOT_PRESENT;
740 }
741 
742 static uint8_t ccid_calc_status(USBCCIDState *s)
743 {
744     /*
745      * page 55, 6.2.6, calculation of bStatus from bmICCStatus and
746      * bmCommandStatus
747      */
748     uint8_t ret = ccid_card_status(s) | (s->bmCommandStatus << 6);
749     DPRINTF(s, D_VERBOSE, "%s: status = %d\n", __func__, ret);
750     return ret;
751 }
752 
753 static void ccid_reset_error_status(USBCCIDState *s)
754 {
755     s->bError = ERROR_CMD_NOT_SUPPORTED;
756     s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
757 }
758 
759 static void ccid_write_slot_status(USBCCIDState *s, CCID_Header *recv)
760 {
761     CCID_SlotStatus *h = ccid_reserve_recv_buf(s, sizeof(CCID_SlotStatus));
762     if (h == NULL) {
763         return;
764     }
765     h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus;
766     h->b.hdr.dwLength = 0;
767     h->b.hdr.bSlot = recv->bSlot;
768     h->b.hdr.bSeq = recv->bSeq;
769     h->b.bStatus = ccid_calc_status(s);
770     h->b.bError = s->bError;
771     h->bClockStatus = CLOCK_STATUS_RUNNING;
772     ccid_reset_error_status(s);
773 }
774 
775 static void ccid_write_parameters(USBCCIDState *s, CCID_Header *recv)
776 {
777     CCID_Parameter *h;
778     uint32_t len = s->ulProtocolDataStructureSize;
779 
780     h = ccid_reserve_recv_buf(s, sizeof(CCID_Parameter) + len);
781     if (h == NULL) {
782         return;
783     }
784     h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_Parameters;
785     h->b.hdr.dwLength = 0;
786     h->b.hdr.bSlot = recv->bSlot;
787     h->b.hdr.bSeq = recv->bSeq;
788     h->b.bStatus = ccid_calc_status(s);
789     h->b.bError = s->bError;
790     h->bProtocolNum = s->bProtocolNum;
791     h->abProtocolDataStructure = s->abProtocolDataStructure;
792     ccid_reset_error_status(s);
793 }
794 
795 static void ccid_write_data_block(USBCCIDState *s, uint8_t slot, uint8_t seq,
796                                   const uint8_t *data, uint32_t len)
797 {
798     CCID_DataBlock *p = ccid_reserve_recv_buf(s, sizeof(*p) + len);
799 
800     if (p == NULL) {
801         return;
802     }
803     p->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock;
804     p->b.hdr.dwLength = cpu_to_le32(len);
805     p->b.hdr.bSlot = slot;
806     p->b.hdr.bSeq = seq;
807     p->b.bStatus = ccid_calc_status(s);
808     p->b.bError = s->bError;
809     if (p->b.bError) {
810         DPRINTF(s, D_VERBOSE, "error %d\n", p->b.bError);
811     }
812     memcpy(p->abData, data, len);
813     ccid_reset_error_status(s);
814 }
815 
816 static void ccid_report_error_failed(USBCCIDState *s, uint8_t error)
817 {
818     s->bmCommandStatus = COMMAND_STATUS_FAILED;
819     s->bError = error;
820 }
821 
822 static void ccid_write_data_block_answer(USBCCIDState *s,
823     const uint8_t *data, uint32_t len)
824 {
825     uint8_t seq;
826     uint8_t slot;
827 
828     if (!ccid_has_pending_answers(s)) {
829         DPRINTF(s, D_WARN, "error: no pending answer to return to guest\n");
830         ccid_report_error_failed(s, ERROR_ICC_MUTE);
831         return;
832     }
833     ccid_remove_pending_answer(s, &slot, &seq);
834     ccid_write_data_block(s, slot, seq, data, len);
835 }
836 
837 static uint8_t atr_get_protocol_num(const uint8_t *atr, uint32_t len)
838 {
839     int i;
840 
841     if (len < 2 || !(atr[1] & 0x80)) {
842         /* too short or TD1 not included */
843         return 0; /* T=0, default */
844     }
845     i = 1 + !!(atr[1] & 0x10) + !!(atr[1] & 0x20) + !!(atr[1] & 0x40);
846     i += !!(atr[1] & 0x80);
847     return atr[i] & 0x0f;
848 }
849 
850 static void ccid_write_data_block_atr(USBCCIDState *s, CCID_Header *recv)
851 {
852     const uint8_t *atr = NULL;
853     uint32_t len = 0;
854     uint8_t atr_protocol_num;
855     CCID_T0ProtocolDataStructure *t0 = &s->abProtocolDataStructure.t0;
856     CCID_T1ProtocolDataStructure *t1 = &s->abProtocolDataStructure.t1;
857 
858     if (s->card) {
859         atr = ccid_card_get_atr(s->card, &len);
860     }
861     atr_protocol_num = atr_get_protocol_num(atr, len);
862     DPRINTF(s, D_VERBOSE, "%s: atr contains protocol=%d\n", __func__,
863             atr_protocol_num);
864     /* set parameters from ATR - see spec page 109 */
865     s->bProtocolNum = (atr_protocol_num <= 1 ? atr_protocol_num
866                                              : s->bProtocolNum);
867     switch (atr_protocol_num) {
868     case 0:
869         /* TODO: unimplemented ATR T0 parameters */
870         t0->bmFindexDindex = 0;
871         t0->bmTCCKST0 = 0;
872         t0->bGuardTimeT0 = 0;
873         t0->bWaitingIntegerT0 = 0;
874         t0->bClockStop = 0;
875         break;
876     case 1:
877         /* TODO: unimplemented ATR T1 parameters */
878         t1->bmFindexDindex = 0;
879         t1->bmTCCKST1 = 0;
880         t1->bGuardTimeT1 = 0;
881         t1->bWaitingIntegerT1 = 0;
882         t1->bClockStop = 0;
883         t1->bIFSC = 0;
884         t1->bNadValue = 0;
885         break;
886     default:
887         DPRINTF(s, D_WARN, "%s: error: unsupported ATR protocol %d\n",
888                 __func__, atr_protocol_num);
889     }
890     ccid_write_data_block(s, recv->bSlot, recv->bSeq, atr, len);
891 }
892 
893 static void ccid_set_parameters(USBCCIDState *s, CCID_Header *recv)
894 {
895     CCID_SetParameters *ph = (CCID_SetParameters *) recv;
896     uint32_t protocol_num = ph->bProtocolNum & 3;
897 
898     if (protocol_num != 0 && protocol_num != 1) {
899         ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
900         return;
901     }
902     s->bProtocolNum = protocol_num;
903     s->abProtocolDataStructure = ph->abProtocolDataStructure;
904 }
905 
906 /*
907  * must be 5 bytes for T=0, 7 bytes for T=1
908  * See page 52
909  */
910 static const CCID_ProtocolDataStructure defaultProtocolDataStructure = {
911     .t1 = {
912         .bmFindexDindex = 0x77,
913         .bmTCCKST1 = 0x00,
914         .bGuardTimeT1 = 0x00,
915         .bWaitingIntegerT1 = 0x00,
916         .bClockStop = 0x00,
917         .bIFSC = 0xfe,
918         .bNadValue = 0x00,
919     }
920 };
921 
922 static void ccid_reset_parameters(USBCCIDState *s)
923 {
924    s->bProtocolNum = 0; /* T=0 */
925    s->abProtocolDataStructure = defaultProtocolDataStructure;
926 }
927 
928 /* NOTE: only a single slot is supported (SLOT_0) */
929 static void ccid_on_slot_change(USBCCIDState *s, bool full)
930 {
931     /* RDR_to_PC_NotifySlotChange, 6.3.1 page 56 */
932     uint8_t current = s->bmSlotICCState;
933     if (full) {
934         s->bmSlotICCState |= SLOT_0_STATE_MASK;
935     } else {
936         s->bmSlotICCState &= ~SLOT_0_STATE_MASK;
937     }
938     if (current != s->bmSlotICCState) {
939         s->bmSlotICCState |= SLOT_0_CHANGED_MASK;
940     }
941     s->notify_slot_change = true;
942     usb_wakeup(s->intr, 0);
943 }
944 
945 static void ccid_write_data_block_error(
946     USBCCIDState *s, uint8_t slot, uint8_t seq)
947 {
948     ccid_write_data_block(s, slot, seq, NULL, 0);
949 }
950 
951 static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
952 {
953     uint32_t len;
954 
955     if (ccid_card_status(s) != ICC_STATUS_PRESENT_ACTIVE) {
956         DPRINTF(s, 1,
957                 "usb-ccid: not sending apdu to client, no card connected\n");
958         ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);
959         return;
960     }
961     len = le32_to_cpu(recv->hdr.dwLength);
962     DPRINTF(s, 1, "%s: seq %d, len %d\n", __func__,
963                 recv->hdr.bSeq, len);
964     ccid_add_pending_answer(s, (CCID_Header *)recv);
965     if (s->card) {
966         ccid_card_apdu_from_guest(s->card, recv->abData, len);
967     } else {
968         DPRINTF(s, D_WARN, "warning: discarded apdu\n");
969     }
970 }
971 
972 static const char *ccid_message_type_to_str(uint8_t type)
973 {
974     switch (type) {
975     case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn: return "IccPowerOn";
976     case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff: return "IccPowerOff";
977     case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus: return "GetSlotStatus";
978     case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock: return "XfrBlock";
979     case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters: return "GetParameters";
980     case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters: return "ResetParameters";
981     case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters: return "SetParameters";
982     case CCID_MESSAGE_TYPE_PC_to_RDR_Escape: return "Escape";
983     case CCID_MESSAGE_TYPE_PC_to_RDR_IccClock: return "IccClock";
984     case CCID_MESSAGE_TYPE_PC_to_RDR_T0APDU: return "T0APDU";
985     case CCID_MESSAGE_TYPE_PC_to_RDR_Secure: return "Secure";
986     case CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical: return "Mechanical";
987     case CCID_MESSAGE_TYPE_PC_to_RDR_Abort: return "Abort";
988     case CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency:
989         return "SetDataRateAndClockFrequency";
990     }
991     return "unknown";
992 }
993 
994 static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
995 {
996     CCID_Header *ccid_header;
997 
998     if (p->iov.size + s->bulk_out_pos > BULK_OUT_DATA_SIZE) {
999         p->status = USB_RET_STALL;
1000         return;
1001     }
1002     ccid_header = (CCID_Header *)s->bulk_out_data;
1003     usb_packet_copy(p, s->bulk_out_data + s->bulk_out_pos, p->iov.size);
1004     s->bulk_out_pos += p->iov.size;
1005     if (p->iov.size == CCID_MAX_PACKET_SIZE) {
1006         DPRINTF(s, D_VERBOSE,
1007             "usb-ccid: bulk_in: expecting more packets (%zd/%d)\n",
1008             p->iov.size, ccid_header->dwLength);
1009         return;
1010     }
1011     if (s->bulk_out_pos < 10) {
1012         DPRINTF(s, 1,
1013                 "%s: bad USB_TOKEN_OUT length, should be at least 10 bytes\n",
1014                 __func__);
1015     } else {
1016         DPRINTF(s, D_MORE_INFO, "%s %x %s\n", __func__,
1017                 ccid_header->bMessageType,
1018                 ccid_message_type_to_str(ccid_header->bMessageType));
1019         switch (ccid_header->bMessageType) {
1020         case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus:
1021             ccid_write_slot_status(s, ccid_header);
1022             break;
1023         case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:
1024             DPRINTF(s, 1, "%s: PowerOn: %d\n", __func__,
1025                 ((CCID_IccPowerOn *)(ccid_header))->bPowerSelect);
1026             s->powered = true;
1027             if (!ccid_card_inserted(s)) {
1028                 ccid_report_error_failed(s, ERROR_ICC_MUTE);
1029             }
1030             /* atr is written regardless of error. */
1031             ccid_write_data_block_atr(s, ccid_header);
1032             break;
1033         case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff:
1034             ccid_reset_error_status(s);
1035             s->powered = false;
1036             ccid_write_slot_status(s, ccid_header);
1037             break;
1038         case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:
1039             ccid_on_apdu_from_guest(s, (CCID_XferBlock *)s->bulk_out_data);
1040             break;
1041         case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters:
1042             ccid_reset_error_status(s);
1043             ccid_set_parameters(s, ccid_header);
1044             ccid_write_parameters(s, ccid_header);
1045             break;
1046         case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters:
1047             ccid_reset_error_status(s);
1048             ccid_reset_parameters(s);
1049             ccid_write_parameters(s, ccid_header);
1050             break;
1051         case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters:
1052             ccid_reset_error_status(s);
1053             ccid_write_parameters(s, ccid_header);
1054             break;
1055         case CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical:
1056             ccid_report_error_failed(s, 0);
1057             ccid_write_slot_status(s, ccid_header);
1058             break;
1059         default:
1060             DPRINTF(s, 1,
1061                 "handle_data: ERROR: unhandled message type %Xh\n",
1062                 ccid_header->bMessageType);
1063             /*
1064              * The caller is expecting the device to respond, tell it we
1065              * don't support the operation.
1066              */
1067             ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
1068             ccid_write_slot_status(s, ccid_header);
1069             break;
1070         }
1071     }
1072     s->bulk_out_pos = 0;
1073 }
1074 
1075 static void ccid_bulk_in_copy_to_guest(USBCCIDState *s, USBPacket *p)
1076 {
1077     int len = 0;
1078 
1079     ccid_bulk_in_get(s);
1080     if (s->current_bulk_in != NULL) {
1081         len = MIN(s->current_bulk_in->len - s->current_bulk_in->pos,
1082                   p->iov.size);
1083         usb_packet_copy(p, s->current_bulk_in->data +
1084                         s->current_bulk_in->pos, len);
1085         s->current_bulk_in->pos += len;
1086         if (s->current_bulk_in->pos == s->current_bulk_in->len) {
1087             ccid_bulk_in_release(s);
1088         }
1089     } else {
1090         /* return when device has no data - usb 2.0 spec Table 8-4 */
1091         p->status = USB_RET_NAK;
1092     }
1093     if (len) {
1094         DPRINTF(s, D_MORE_INFO,
1095                 "%s: %zd/%d req/act to guest (BULK_IN)\n",
1096                 __func__, p->iov.size, len);
1097     }
1098     if (len < p->iov.size) {
1099         DPRINTF(s, 1,
1100                 "%s: returning short (EREMOTEIO) %d < %zd\n",
1101                 __func__, len, p->iov.size);
1102     }
1103 }
1104 
1105 static void ccid_handle_data(USBDevice *dev, USBPacket *p)
1106 {
1107     USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
1108     uint8_t buf[2];
1109 
1110     switch (p->pid) {
1111     case USB_TOKEN_OUT:
1112         ccid_handle_bulk_out(s, p);
1113         break;
1114 
1115     case USB_TOKEN_IN:
1116         switch (p->ep->nr) {
1117         case CCID_BULK_IN_EP:
1118             ccid_bulk_in_copy_to_guest(s, p);
1119             break;
1120         case CCID_INT_IN_EP:
1121             if (s->notify_slot_change) {
1122                 /* page 56, RDR_to_PC_NotifySlotChange */
1123                 buf[0] = CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange;
1124                 buf[1] = s->bmSlotICCState;
1125                 usb_packet_copy(p, buf, 2);
1126                 s->notify_slot_change = false;
1127                 s->bmSlotICCState &= ~SLOT_0_CHANGED_MASK;
1128                 DPRINTF(s, D_INFO,
1129                         "handle_data: int_in: notify_slot_change %X, "
1130                         "requested len %zd\n",
1131                         s->bmSlotICCState, p->iov.size);
1132             } else {
1133                 p->status = USB_RET_NAK;
1134             }
1135             break;
1136         default:
1137             DPRINTF(s, 1, "Bad endpoint\n");
1138             p->status = USB_RET_STALL;
1139             break;
1140         }
1141         break;
1142     default:
1143         DPRINTF(s, 1, "Bad token\n");
1144         p->status = USB_RET_STALL;
1145         break;
1146     }
1147 }
1148 
1149 static void ccid_handle_destroy(USBDevice *dev)
1150 {
1151     USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
1152 
1153     ccid_bulk_in_clear(s);
1154 }
1155 
1156 static void ccid_flush_pending_answers(USBCCIDState *s)
1157 {
1158     while (ccid_has_pending_answers(s)) {
1159         ccid_write_data_block_answer(s, NULL, 0);
1160     }
1161 }
1162 
1163 static Answer *ccid_peek_next_answer(USBCCIDState *s)
1164 {
1165     return s->pending_answers_num == 0
1166         ? NULL
1167         : &s->pending_answers[s->pending_answers_start % PENDING_ANSWERS_NUM];
1168 }
1169 
1170 static Property ccid_props[] = {
1171     DEFINE_PROP_UINT32("slot", struct CCIDCardState, slot, 0),
1172     DEFINE_PROP_END_OF_LIST(),
1173 };
1174 
1175 #define TYPE_CCID_BUS "ccid-bus"
1176 #define CCID_BUS(obj) OBJECT_CHECK(CCIDBus, (obj), TYPE_CCID_BUS)
1177 
1178 static const TypeInfo ccid_bus_info = {
1179     .name = TYPE_CCID_BUS,
1180     .parent = TYPE_BUS,
1181     .instance_size = sizeof(CCIDBus),
1182 };
1183 
1184 void ccid_card_send_apdu_to_guest(CCIDCardState *card,
1185                                   uint8_t *apdu, uint32_t len)
1186 {
1187     USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev,
1188                                 card->qdev.parent_bus->parent);
1189     Answer *answer;
1190 
1191     if (!ccid_has_pending_answers(s)) {
1192         DPRINTF(s, 1, "CCID ERROR: got an APDU without pending answers\n");
1193         return;
1194     }
1195     s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
1196     answer = ccid_peek_next_answer(s);
1197     if (answer == NULL) {
1198         DPRINTF(s, D_WARN, "%s: error: unexpected lack of answer\n", __func__);
1199         ccid_report_error_failed(s, ERROR_HW_ERROR);
1200         return;
1201     }
1202     DPRINTF(s, 1, "APDU returned to guest %d (answer seq %d, slot %d)\n",
1203         len, answer->seq, answer->slot);
1204     ccid_write_data_block_answer(s, apdu, len);
1205 }
1206 
1207 void ccid_card_card_removed(CCIDCardState *card)
1208 {
1209     USBCCIDState *s =
1210         DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1211 
1212     ccid_on_slot_change(s, false);
1213     ccid_flush_pending_answers(s);
1214     ccid_reset(s);
1215 }
1216 
1217 int ccid_card_ccid_attach(CCIDCardState *card)
1218 {
1219     USBCCIDState *s =
1220         DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1221 
1222     DPRINTF(s, 1, "CCID Attach\n");
1223     if (s->migration_state == MIGRATION_MIGRATED) {
1224         s->migration_state = MIGRATION_NONE;
1225     }
1226     return 0;
1227 }
1228 
1229 void ccid_card_ccid_detach(CCIDCardState *card)
1230 {
1231     USBCCIDState *s =
1232         DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1233 
1234     DPRINTF(s, 1, "CCID Detach\n");
1235     if (ccid_card_inserted(s)) {
1236         ccid_on_slot_change(s, false);
1237     }
1238     ccid_detach(s);
1239 }
1240 
1241 void ccid_card_card_error(CCIDCardState *card, uint64_t error)
1242 {
1243     USBCCIDState *s =
1244         DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1245 
1246     s->bmCommandStatus = COMMAND_STATUS_FAILED;
1247     s->last_answer_error = error;
1248     DPRINTF(s, 1, "VSC_Error: %" PRIX64 "\n", s->last_answer_error);
1249     /* TODO: these errors should be more verbose and propagated to the guest.*/
1250     /*
1251      * We flush all pending answers on CardRemove message in ccid-card-passthru,
1252      * so check that first to not trigger abort
1253      */
1254     if (ccid_has_pending_answers(s)) {
1255         ccid_write_data_block_answer(s, NULL, 0);
1256     }
1257 }
1258 
1259 void ccid_card_card_inserted(CCIDCardState *card)
1260 {
1261     USBCCIDState *s =
1262         DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1263 
1264     s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
1265     ccid_flush_pending_answers(s);
1266     ccid_on_slot_change(s, true);
1267 }
1268 
1269 static int ccid_card_exit(DeviceState *qdev)
1270 {
1271     int ret = 0;
1272     CCIDCardState *card = CCID_CARD(qdev);
1273     USBCCIDState *s =
1274         DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1275 
1276     if (ccid_card_inserted(s)) {
1277         ccid_card_card_removed(card);
1278     }
1279     ret = ccid_card_exitfn(card);
1280     s->card = NULL;
1281     return ret;
1282 }
1283 
1284 static int ccid_card_init(DeviceState *qdev)
1285 {
1286     CCIDCardState *card = CCID_CARD(qdev);
1287     USBCCIDState *s =
1288         DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1289     int ret = 0;
1290 
1291     if (card->slot != 0) {
1292         error_report("Warning: usb-ccid supports one slot, can't add %d",
1293                 card->slot);
1294         return -1;
1295     }
1296     if (s->card != NULL) {
1297         error_report("Warning: usb-ccid card already full, not adding");
1298         return -1;
1299     }
1300     ret = ccid_card_initfn(card);
1301     if (ret == 0) {
1302         s->card = card;
1303     }
1304     return ret;
1305 }
1306 
1307 static int ccid_initfn(USBDevice *dev)
1308 {
1309     USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
1310 
1311     usb_desc_create_serial(dev);
1312     usb_desc_init(dev);
1313     qbus_create_inplace(&s->bus, sizeof(s->bus), TYPE_CCID_BUS, DEVICE(dev),
1314                         NULL);
1315     s->intr = usb_ep_get(dev, USB_TOKEN_IN, CCID_INT_IN_EP);
1316     s->bus.qbus.allow_hotplug = 1;
1317     s->card = NULL;
1318     s->migration_state = MIGRATION_NONE;
1319     s->migration_target_ip = 0;
1320     s->migration_target_port = 0;
1321     s->dev.speed = USB_SPEED_FULL;
1322     s->dev.speedmask = USB_SPEED_MASK_FULL;
1323     s->notify_slot_change = false;
1324     s->powered = true;
1325     s->pending_answers_num = 0;
1326     s->last_answer_error = 0;
1327     s->bulk_in_pending_start = 0;
1328     s->bulk_in_pending_end = 0;
1329     s->current_bulk_in = NULL;
1330     ccid_reset_error_status(s);
1331     s->bulk_out_pos = 0;
1332     ccid_reset_parameters(s);
1333     ccid_reset(s);
1334     s->debug = parse_debug_env("QEMU_CCID_DEBUG", D_VERBOSE, s->debug);
1335     return 0;
1336 }
1337 
1338 static int ccid_post_load(void *opaque, int version_id)
1339 {
1340     USBCCIDState *s = opaque;
1341 
1342     /*
1343      * This must be done after usb_device_attach, which sets state to ATTACHED,
1344      * while it must be DEFAULT in order to accept packets (like it is after
1345      * reset, but reset will reset our addr and call our reset handler which
1346      * may change state, and we don't want to do that when migrating).
1347      */
1348     s->dev.state = s->state_vmstate;
1349     return 0;
1350 }
1351 
1352 static void ccid_pre_save(void *opaque)
1353 {
1354     USBCCIDState *s = opaque;
1355 
1356     s->state_vmstate = s->dev.state;
1357     if (s->dev.attached) {
1358         /*
1359          * Migrating an open device, ignore reconnection CHR_EVENT to avoid an
1360          * erroneous detach.
1361          */
1362         s->migration_state = MIGRATION_MIGRATED;
1363     }
1364 }
1365 
1366 static VMStateDescription bulk_in_vmstate = {
1367     .name = "CCID BulkIn state",
1368     .version_id = 1,
1369     .minimum_version_id = 1,
1370     .fields = (VMStateField[]) {
1371         VMSTATE_BUFFER(data, BulkIn),
1372         VMSTATE_UINT32(len, BulkIn),
1373         VMSTATE_UINT32(pos, BulkIn),
1374         VMSTATE_END_OF_LIST()
1375     }
1376 };
1377 
1378 static VMStateDescription answer_vmstate = {
1379     .name = "CCID Answer state",
1380     .version_id = 1,
1381     .minimum_version_id = 1,
1382     .fields = (VMStateField[]) {
1383         VMSTATE_UINT8(slot, Answer),
1384         VMSTATE_UINT8(seq, Answer),
1385         VMSTATE_END_OF_LIST()
1386     }
1387 };
1388 
1389 static VMStateDescription usb_device_vmstate = {
1390     .name = "usb_device",
1391     .version_id = 1,
1392     .minimum_version_id = 1,
1393     .fields = (VMStateField[]) {
1394         VMSTATE_UINT8(addr, USBDevice),
1395         VMSTATE_BUFFER(setup_buf, USBDevice),
1396         VMSTATE_BUFFER(data_buf, USBDevice),
1397         VMSTATE_END_OF_LIST()
1398     }
1399 };
1400 
1401 static VMStateDescription ccid_vmstate = {
1402     .name = "usb-ccid",
1403     .version_id = 1,
1404     .minimum_version_id = 1,
1405     .post_load = ccid_post_load,
1406     .pre_save = ccid_pre_save,
1407     .fields = (VMStateField[]) {
1408         VMSTATE_STRUCT(dev, USBCCIDState, 1, usb_device_vmstate, USBDevice),
1409         VMSTATE_UINT8(debug, USBCCIDState),
1410         VMSTATE_BUFFER(bulk_out_data, USBCCIDState),
1411         VMSTATE_UINT32(bulk_out_pos, USBCCIDState),
1412         VMSTATE_UINT8(bmSlotICCState, USBCCIDState),
1413         VMSTATE_UINT8(powered, USBCCIDState),
1414         VMSTATE_UINT8(notify_slot_change, USBCCIDState),
1415         VMSTATE_UINT64(last_answer_error, USBCCIDState),
1416         VMSTATE_UINT8(bError, USBCCIDState),
1417         VMSTATE_UINT8(bmCommandStatus, USBCCIDState),
1418         VMSTATE_UINT8(bProtocolNum, USBCCIDState),
1419         VMSTATE_BUFFER(abProtocolDataStructure.data, USBCCIDState),
1420         VMSTATE_UINT32(ulProtocolDataStructureSize, USBCCIDState),
1421         VMSTATE_STRUCT_ARRAY(bulk_in_pending, USBCCIDState,
1422                        BULK_IN_PENDING_NUM, 1, bulk_in_vmstate, BulkIn),
1423         VMSTATE_UINT32(bulk_in_pending_start, USBCCIDState),
1424         VMSTATE_UINT32(bulk_in_pending_end, USBCCIDState),
1425         VMSTATE_STRUCT_ARRAY(pending_answers, USBCCIDState,
1426                         PENDING_ANSWERS_NUM, 1, answer_vmstate, Answer),
1427         VMSTATE_UINT32(pending_answers_num, USBCCIDState),
1428         VMSTATE_UINT8(migration_state, USBCCIDState),
1429         VMSTATE_UINT32(state_vmstate, USBCCIDState),
1430         VMSTATE_END_OF_LIST()
1431     }
1432 };
1433 
1434 static Property ccid_properties[] = {
1435     DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
1436     DEFINE_PROP_END_OF_LIST(),
1437 };
1438 
1439 static void ccid_class_initfn(ObjectClass *klass, void *data)
1440 {
1441     DeviceClass *dc = DEVICE_CLASS(klass);
1442     USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1443 
1444     uc->init           = ccid_initfn;
1445     uc->product_desc   = "QEMU USB CCID";
1446     uc->usb_desc       = &desc_ccid;
1447     uc->handle_reset   = ccid_handle_reset;
1448     uc->handle_control = ccid_handle_control;
1449     uc->handle_data    = ccid_handle_data;
1450     uc->handle_destroy = ccid_handle_destroy;
1451     dc->desc = "CCID Rev 1.1 smartcard reader";
1452     dc->vmsd = &ccid_vmstate;
1453     dc->props = ccid_properties;
1454     set_bit(DEVICE_CATEGORY_INPUT, dc->categories);
1455 }
1456 
1457 static const TypeInfo ccid_info = {
1458     .name          = CCID_DEV_NAME,
1459     .parent        = TYPE_USB_DEVICE,
1460     .instance_size = sizeof(USBCCIDState),
1461     .class_init    = ccid_class_initfn,
1462 };
1463 
1464 static void ccid_card_class_init(ObjectClass *klass, void *data)
1465 {
1466     DeviceClass *k = DEVICE_CLASS(klass);
1467     k->bus_type = TYPE_CCID_BUS;
1468     k->init = ccid_card_init;
1469     k->exit = ccid_card_exit;
1470     k->props = ccid_props;
1471 }
1472 
1473 static const TypeInfo ccid_card_type_info = {
1474     .name = TYPE_CCID_CARD,
1475     .parent = TYPE_DEVICE,
1476     .instance_size = sizeof(CCIDCardState),
1477     .abstract = true,
1478     .class_size = sizeof(CCIDCardClass),
1479     .class_init = ccid_card_class_init,
1480 };
1481 
1482 static void ccid_register_types(void)
1483 {
1484     type_register_static(&ccid_bus_info);
1485     type_register_static(&ccid_card_type_info);
1486     type_register_static(&ccid_info);
1487     usb_legacy_register(CCID_DEV_NAME, "ccid", NULL);
1488 }
1489 
1490 type_init(ccid_register_types)
1491