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