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