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