Statistics
| Branch: | Revision:

root / hw / usb-ccid.c @ 6df658f5

History | View | Annotate | Download (44.4 kB)

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 it's copyright and attributions below.
9
 *
10
 * This work is licensed under the terms of the GNU GPL, version 2.1 or later.
11
 * See the COPYING file in the top-level directory.
12
 * ------- (original copyright & attribution for usb-serial.c below) --------
13
 * Copyright (c) 2006 CodeSourcery.
14
 * Copyright (c) 2008 Samuel Thibault <samuel.thibault@ens-lyon.org>
15
 * Written by Paul Brook, reused for FTDI by Samuel Thibault,
16
 */
17

    
18
/*
19
 * References:
20
 *
21
 * CCID Specification Revision 1.1 April 22nd 2005
22
 *  "Universal Serial Bus, Device Class: Smart Card"
23
 *  Specification for Integrated Circuit(s) Cards Interface Devices
24
 *
25
 * Endianness note: from the spec (1.3)
26
 *  "Fields that are larger than a byte are stored in little endian"
27
 *
28
 * KNOWN BUGS
29
 * 1. remove/insert can sometimes result in removed state instead of inserted.
30
 * This is a result of the following:
31
 *  symptom: dmesg shows ERMOTEIO (-121), pcscd shows -99. This can happen
32
 *  when a short packet is sent, as seen in uhci-usb.c, resulting from a urb
33
 *  from the guest requesting SPD and us returning a smaller packet.
34
 *  Not sure which messages trigger this.
35
 */
36

    
37
#include "qemu-common.h"
38
#include "qemu-error.h"
39
#include "usb.h"
40
#include "monitor.h"
41

    
42
#include "hw/ccid.h"
43

    
44
#define DPRINTF(s, lvl, fmt, ...) \
45
do { \
46
    if (lvl <= s->debug) { \
47
        printf("usb-ccid: " fmt , ## __VA_ARGS__); \
48
    } \
49
} while (0)
50

    
51
#define D_WARN 1
52
#define D_INFO 2
53
#define D_MORE_INFO 3
54
#define D_VERBOSE 4
55

    
56
#define CCID_DEV_NAME "usb-ccid"
57

    
58
/*
59
 * The two options for variable sized buffers:
60
 * make them constant size, for large enough constant,
61
 * or handle the migration complexity - VMState doesn't handle this case.
62
 * sizes are expected never to be exceeded, unless guest misbehaves.
63
 */
64
#define BULK_OUT_DATA_SIZE 65536
65
#define PENDING_ANSWERS_NUM 128
66

    
67
#define BULK_IN_BUF_SIZE 384
68
#define BULK_IN_PENDING_NUM 8
69

    
70
#define InterfaceOutClass \
71
    ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE)<<8)
72

    
73
#define InterfaceInClass  \
74
    ((USB_DIR_IN  | USB_TYPE_CLASS | USB_RECIP_INTERFACE)<<8)
75

    
76
#define CCID_MAX_PACKET_SIZE                64
77

    
78
#define CCID_CONTROL_ABORT                  0x1
79
#define CCID_CONTROL_GET_CLOCK_FREQUENCIES  0x2
80
#define CCID_CONTROL_GET_DATA_RATES         0x3
81

    
82
#define CCID_PRODUCT_DESCRIPTION        "QEMU USB CCID"
83
#define CCID_VENDOR_DESCRIPTION         "QEMU " QEMU_VERSION
84
#define CCID_INTERFACE_NAME             "CCID Interface"
85
#define CCID_SERIAL_NUMBER_STRING       "1"
86
/*
87
 * Using Gemplus Vendor and Product id
88
 * Effect on various drivers:
89
 *  usbccid.sys (winxp, others untested) is a class driver so it doesn't care.
90
 *  linux has a number of class drivers, but openct filters based on
91
 *   vendor/product (/etc/openct.conf under fedora), hence Gemplus.
92
 */
93
#define CCID_VENDOR_ID                  0x08e6
94
#define CCID_PRODUCT_ID                 0x4433
95
#define CCID_DEVICE_VERSION             0x0000
96

    
97
/*
98
 * BULK_OUT messages from PC to Reader
99
 * Defined in CCID Rev 1.1 6.1 (page 26)
100
 */
101
#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn              0x62
102
#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff             0x63
103
#define CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus           0x65
104
#define CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock                0x6f
105
#define CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters           0x6c
106
#define CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters         0x6d
107
#define CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters           0x61
108
#define CCID_MESSAGE_TYPE_PC_to_RDR_Escape                  0x6b
109
#define CCID_MESSAGE_TYPE_PC_to_RDR_IccClock                0x6e
110
#define CCID_MESSAGE_TYPE_PC_to_RDR_T0APDU                  0x6a
111
#define CCID_MESSAGE_TYPE_PC_to_RDR_Secure                  0x69
112
#define CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical              0x71
113
#define CCID_MESSAGE_TYPE_PC_to_RDR_Abort                   0x72
114
#define CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency 0x73
115

    
116
/*
117
 * BULK_IN messages from Reader to PC
118
 * Defined in CCID Rev 1.1 6.2 (page 48)
119
 */
120
#define CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock               0x80
121
#define CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus              0x81
122
#define CCID_MESSAGE_TYPE_RDR_to_PC_Parameters              0x82
123
#define CCID_MESSAGE_TYPE_RDR_to_PC_Escape                  0x83
124
#define CCID_MESSAGE_TYPE_RDR_to_PC_DataRateAndClockFrequency 0x84
125

    
126
/*
127
 * INTERRUPT_IN messages from Reader to PC
128
 * Defined in CCID Rev 1.1 6.3 (page 56)
129
 */
130
#define CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange        0x50
131
#define CCID_MESSAGE_TYPE_RDR_to_PC_HardwareError           0x51
132

    
133
/*
134
 * Endpoints for CCID - addresses are up to us to decide.
135
 * To support slot insertion and removal we must have an interrupt in ep
136
 * in addition we need a bulk in and bulk out ep
137
 * 5.2, page 20
138
 */
139
#define CCID_INT_IN_EP       1
140
#define CCID_BULK_IN_EP      2
141
#define CCID_BULK_OUT_EP     3
142

    
143
/* bmSlotICCState masks */
144
#define SLOT_0_STATE_MASK    1
145
#define SLOT_0_CHANGED_MASK  2
146

    
147
/* Status codes that go in bStatus (see 6.2.6) */
148
enum {
149
    ICC_STATUS_PRESENT_ACTIVE = 0,
150
    ICC_STATUS_PRESENT_INACTIVE,
151
    ICC_STATUS_NOT_PRESENT
152
};
153

    
154
enum {
155
    COMMAND_STATUS_NO_ERROR = 0,
156
    COMMAND_STATUS_FAILED,
157
    COMMAND_STATUS_TIME_EXTENSION_REQUIRED
158
};
159

    
160
/* Error codes that go in bError (see 6.2.6) */
161
enum {
162
    ERROR_CMD_NOT_SUPPORTED = 0,
163
    ERROR_CMD_ABORTED       = -1,
164
    ERROR_ICC_MUTE          = -2,
165
    ERROR_XFR_PARITY_ERROR  = -3,
166
    ERROR_XFR_OVERRUN       = -4,
167
    ERROR_HW_ERROR          = -5,
168
};
169

    
170
/* 6.2.6 RDR_to_PC_SlotStatus definitions */
171
enum {
172
    CLOCK_STATUS_RUNNING = 0,
173
    /*
174
     * 0 - Clock Running, 1 - Clock stopped in State L, 2 - H,
175
     * 3 - unknown state. rest are RFU
176
     */
177
};
178

    
179
typedef struct __attribute__ ((__packed__)) CCID_Header {
180
    uint8_t     bMessageType;
181
    uint32_t    dwLength;
182
    uint8_t     bSlot;
183
    uint8_t     bSeq;
184
} CCID_Header;
185

    
186
typedef struct __attribute__ ((__packed__)) CCID_BULK_IN {
187
    CCID_Header hdr;
188
    uint8_t     bStatus;        /* Only used in BULK_IN */
189
    uint8_t     bError;         /* Only used in BULK_IN */
190
} CCID_BULK_IN;
191

    
192
typedef struct __attribute__ ((__packed__)) CCID_SlotStatus {
193
    CCID_BULK_IN b;
194
    uint8_t     bClockStatus;
195
} CCID_SlotStatus;
196

    
197
typedef struct __attribute__ ((__packed__)) CCID_Parameter {
198
    CCID_BULK_IN b;
199
    uint8_t     bProtocolNum;
200
    uint8_t     abProtocolDataStructure[0];
201
} CCID_Parameter;
202

    
203
typedef struct __attribute__ ((__packed__)) CCID_DataBlock {
204
    CCID_BULK_IN b;
205
    uint8_t      bChainParameter;
206
    uint8_t      abData[0];
207
} CCID_DataBlock;
208

    
209
/* 6.1.4 PC_to_RDR_XfrBlock */
210
typedef struct __attribute__ ((__packed__)) CCID_XferBlock {
211
    CCID_Header  hdr;
212
    uint8_t      bBWI; /* Block Waiting Timeout */
213
    uint16_t     wLevelParameter; /* XXX currently unused */
214
    uint8_t      abData[0];
215
} CCID_XferBlock;
216

    
217
typedef struct __attribute__ ((__packed__)) CCID_IccPowerOn {
218
    CCID_Header hdr;
219
    uint8_t     bPowerSelect;
220
    uint16_t    abRFU;
221
} CCID_IccPowerOn;
222

    
223
typedef struct __attribute__ ((__packed__)) CCID_IccPowerOff {
224
    CCID_Header hdr;
225
    uint16_t    abRFU;
226
} CCID_IccPowerOff;
227

    
228
typedef struct __attribute__ ((__packed__)) CCID_SetParameters {
229
    CCID_Header hdr;
230
    uint8_t     bProtocolNum;
231
    uint16_t   abRFU;
232
    uint8_t    abProtocolDataStructure[0];
233
} CCID_SetParameters;
234

    
235
typedef struct CCID_Notify_Slot_Change {
236
    uint8_t     bMessageType; /* CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange */
237
    uint8_t     bmSlotICCState;
238
} CCID_Notify_Slot_Change;
239

    
240
/* used for DataBlock response to XferBlock */
241
typedef struct Answer {
242
    uint8_t slot;
243
    uint8_t seq;
244
} Answer;
245

    
246
/* pending BULK_IN messages */
247
typedef struct BulkIn {
248
    uint8_t  data[BULK_IN_BUF_SIZE];
249
    uint32_t len;
250
    uint32_t pos;
251
} BulkIn;
252

    
253
enum {
254
    MIGRATION_NONE,
255
    MIGRATION_MIGRATED,
256
};
257

    
258
typedef struct CCIDBus {
259
    BusState qbus;
260
} CCIDBus;
261

    
262
#define MAX_PROTOCOL_SIZE   7
263

    
264
/*
265
 * powered - defaults to true, changed by PowerOn/PowerOff messages
266
 */
267
typedef struct USBCCIDState {
268
    USBDevice dev;
269
    CCIDBus bus;
270
    CCIDCardState *card;
271
    CCIDCardInfo *cardinfo; /* caching the info pointer */
272
    BulkIn bulk_in_pending[BULK_IN_PENDING_NUM]; /* circular */
273
    uint32_t bulk_in_pending_start;
274
    uint32_t bulk_in_pending_end; /* first free */
275
    uint32_t bulk_in_pending_num;
276
    BulkIn *current_bulk_in;
277
    uint8_t  bulk_out_data[BULK_OUT_DATA_SIZE];
278
    uint32_t bulk_out_pos;
279
    uint64_t last_answer_error;
280
    Answer pending_answers[PENDING_ANSWERS_NUM];
281
    uint32_t pending_answers_start;
282
    uint32_t pending_answers_end;
283
    uint32_t pending_answers_num;
284
    uint8_t  bError;
285
    uint8_t  bmCommandStatus;
286
    uint8_t  bProtocolNum;
287
    uint8_t  abProtocolDataStructure[MAX_PROTOCOL_SIZE];
288
    uint32_t ulProtocolDataStructureSize;
289
    uint32_t state_vmstate;
290
    uint32_t migration_target_ip;
291
    uint16_t migration_target_port;
292
    uint8_t  migration_state;
293
    uint8_t  bmSlotICCState;
294
    uint8_t  powered;
295
    uint8_t  notify_slot_change;
296
    uint8_t  debug;
297
} USBCCIDState;
298

    
299
/*
300
 * CCID Spec chapter 4: CCID uses a standard device descriptor per Chapter 9,
301
 * "USB Device Framework", section 9.6.1, in the Universal Serial Bus
302
 * Specification.
303
 *
304
 * This device implemented based on the spec and with an Athena Smart Card
305
 * Reader as reference:
306
 *   0dc3:1004 Athena Smartcard Solutions, Inc.
307
 */
308

    
309
static const uint8_t qemu_ccid_dev_descriptor[] = {
310
        0x12,       /*  u8 bLength; */
311
        USB_DT_DEVICE, /*  u8 bDescriptorType; Device */
312
        0x10, 0x01, /*  u16 bcdUSB; v1.1 */
313

    
314
        0x00,       /*  u8  bDeviceClass; */
315
        0x00,       /*  u8  bDeviceSubClass; */
316
        0x00,       /*  u8  bDeviceProtocol; [ low/full speeds only ] */
317
        0x40,       /*  u8  bMaxPacketSize0; 8 Bytes (valid: 8,16,32,64) */
318

    
319
        /* Vendor and product id are arbitrary.  */
320
                    /*  u16 idVendor  */
321
        CCID_VENDOR_ID & 0xff, CCID_VENDOR_ID >> 8,
322
                    /*  u16 idProduct */
323
        CCID_PRODUCT_ID & 0xff, CCID_PRODUCT_ID >> 8,
324
                    /*  u16 bcdDevice */
325
        CCID_DEVICE_VERSION & 0xff, CCID_DEVICE_VERSION >> 8,
326
        0x01,       /*  u8  iManufacturer; */
327
        0x02,       /*  u8  iProduct; */
328
        0x03,       /*  u8  iSerialNumber; */
329
        0x01,       /*  u8  bNumConfigurations; */
330
};
331

    
332
static const uint8_t qemu_ccid_config_descriptor[] = {
333

    
334
        /* one configuration */
335
        0x09,       /* u8  bLength; */
336
        USB_DT_CONFIG, /* u8  bDescriptorType; Configuration */
337
        0x5d, 0x00, /* u16 wTotalLength; 9+9+54+7+7+7 */
338
        0x01,       /* u8  bNumInterfaces; (1) */
339
        0x01,       /* u8  bConfigurationValue; */
340
        0x00,       /* u8  iConfiguration; */
341
        0xe0,       /* u8  bmAttributes;
342
                                 Bit 7: must be set,
343
                                     6: Self-powered,
344
                                     5: Remote wakeup,
345
                                     4..0: resvd */
346
        100/2,      /* u8  MaxPower; 50 == 100mA */
347

    
348
        /* one interface */
349
        0x09,       /* u8  if_bLength; */
350
        USB_DT_INTERFACE, /* u8  if_bDescriptorType; Interface */
351
        0x00,       /* u8  if_bInterfaceNumber; */
352
        0x00,       /* u8  if_bAlternateSetting; */
353
        0x03,       /* u8  if_bNumEndpoints; */
354
        0x0b,       /* u8  if_bInterfaceClass; Smart Card Device Class */
355
        0x00,       /* u8  if_bInterfaceSubClass; Subclass code */
356
        0x00,       /* u8  if_bInterfaceProtocol; Protocol code */
357
        0x04,       /* u8  if_iInterface; Index of string descriptor */
358

    
359
        /* Smart Card Device Class Descriptor */
360
        0x36,       /* u8  bLength; */
361
        0x21,       /* u8  bDescriptorType; Functional */
362
        0x10, 0x01, /* u16 bcdCCID; CCID Specification Release Number. */
363
        0x00,       /*
364
                     * u8  bMaxSlotIndex; The index of the highest available
365
                     * slot on this device. All slots are consecutive starting
366
                     * at 00h.
367
                     */
368
        0x07,       /* u8  bVoltageSupport; 01h - 5.0v, 02h - 3.0, 03 - 1.8 */
369

    
370
        0x03, 0x00, /* u32 dwProtocols; RRRR PPPP. RRRR = 0000h.*/
371
        0x00, 0x00, /* PPPP: 0001h = Protocol T=0, 0002h = Protocol T=1 */
372
                    /* u32 dwDefaultClock; in kHZ (0x0fa0 is 4 MHz) */
373
        0xa0, 0x0f, 0x00, 0x00,
374
                    /* u32 dwMaximumClock; */
375
        0x00, 0x00, 0x01, 0x00,
376
        0x00,       /* u8 bNumClockSupported;                 *
377
                     *    0 means just the default and max.   */
378
                    /* u32 dwDataRate ;bps. 9600 == 00002580h */
379
        0x80, 0x25, 0x00, 0x00,
380
                    /* u32 dwMaxDataRate ; 11520 bps == 0001C200h */
381
        0x00, 0xC2, 0x01, 0x00,
382
        0x00,       /* u8  bNumDataRatesSupported; 00 means all rates between
383
                     *     default and max */
384
                    /* u32 dwMaxIFSD;                                  *
385
                     *     maximum IFSD supported by CCID for protocol *
386
                     *     T=1 (Maximum seen from various cards)       */
387
        0xfe, 0x00, 0x00, 0x00,
388
                    /* u32 dwSyncProtocols; 1 - 2-wire, 2 - 3-wire, 4 - I2C */
389
        0x00, 0x00, 0x00, 0x00,
390
                    /* u32 dwMechanical;  0 - no special characteristics. */
391
        0x00, 0x00, 0x00, 0x00,
392
                    /*
393
                     * u32 dwFeatures;
394
                     * 0 - No special characteristics
395
                     * + 2 Automatic parameter configuration based on ATR data
396
                     * + 4 Automatic activation of ICC on inserting
397
                     * + 8 Automatic ICC voltage selection
398
                     * + 10 Automatic ICC clock frequency change
399
                     * + 20 Automatic baud rate change
400
                     * + 40 Automatic parameters negotiation made by the CCID
401
                     * + 80 automatic PPS made by the CCID
402
                     * 100 CCID can set ICC in clock stop mode
403
                     * 200 NAD value other then 00 accepted (T=1 protocol)
404
                     * + 400 Automatic IFSD exchange as first exchange (T=1)
405
                     * One of the following only:
406
                     * + 10000 TPDU level exchanges with CCID
407
                     * 20000 Short APDU level exchange with CCID
408
                     * 40000 Short and Extended APDU level exchange with CCID
409
                     *
410
                     * + 100000 USB Wake up signaling supported on card
411
                     * insertion and removal. Must set bit 5 in bmAttributes
412
                     * in Configuration descriptor if 100000 is set.
413
                     */
414
        0xfe, 0x04, 0x11, 0x00,
415
                    /*
416
                     * u32 dwMaxCCIDMessageLength; For extended APDU in
417
                     * [261 + 10 , 65544 + 10]. Otherwise the minimum is
418
                     * wMaxPacketSize of the Bulk-OUT endpoint
419
                     */
420
        0x12, 0x00, 0x01, 0x00,
421
        0xFF,       /*
422
                     * u8  bClassGetResponse; Significant only for CCID that
423
                     * offers an APDU level for exchanges. Indicates the
424
                     * default class value used by the CCID when it sends a
425
                     * Get Response command to perform the transportation of
426
                     * an APDU by T=0 protocol
427
                     * FFh indicates that the CCID echos the class of the APDU.
428
                     */
429
        0xFF,       /*
430
                     * u8  bClassEnvelope; EAPDU only. Envelope command for
431
                     * T=0
432
                     */
433
        0x00, 0x00, /*
434
                     * u16 wLcdLayout; XXYY Number of lines (XX) and chars per
435
                     * line for LCD display used for PIN entry. 0000 - no LCD
436
                     */
437
        0x01,       /*
438
                     * u8  bPINSupport; 01h PIN Verification,
439
                     *                  02h PIN Modification
440
                     */
441
        0x01,       /* u8  bMaxCCIDBusySlots; */
442

    
443
        /* Interrupt-IN endpoint */
444
        0x07,       /* u8  ep_bLength; */
445
                    /* u8  ep_bDescriptorType; Endpoint */
446
        USB_DT_ENDPOINT,
447
                    /* u8  ep_bEndpointAddress; IN Endpoint 1 */
448
        0x80 | CCID_INT_IN_EP,
449
        0x03,       /* u8  ep_bmAttributes; Interrupt */
450
                    /* u16 ep_wMaxPacketSize; */
451
        CCID_MAX_PACKET_SIZE & 0xff, (CCID_MAX_PACKET_SIZE >> 8),
452
        0xff,       /* u8  ep_bInterval; */
453

    
454
        /* Bulk-In endpoint */
455
        0x07,       /* u8  ep_bLength; */
456
                    /* u8  ep_bDescriptorType; Endpoint */
457
        USB_DT_ENDPOINT,
458
                    /* u8  ep_bEndpointAddress; IN Endpoint 2 */
459
        0x80 | CCID_BULK_IN_EP,
460
        0x02,       /* u8  ep_bmAttributes; Bulk */
461
        0x40, 0x00, /* u16 ep_wMaxPacketSize; */
462
        0x00,       /* u8  ep_bInterval; */
463

    
464
        /* Bulk-Out endpoint */
465
        0x07,       /* u8  ep_bLength; */
466
                    /* u8  ep_bDescriptorType; Endpoint */
467
        USB_DT_ENDPOINT,
468
                    /* u8  ep_bEndpointAddress; OUT Endpoint 3 */
469
        CCID_BULK_OUT_EP,
470
        0x02,       /* u8  ep_bmAttributes; Bulk */
471
        0x40, 0x00, /* u16 ep_wMaxPacketSize; */
472
        0x00,       /* u8  ep_bInterval; */
473

    
474
};
475

    
476
static bool ccid_has_pending_answers(USBCCIDState *s)
477
{
478
    return s->pending_answers_num > 0;
479
}
480

    
481
static void ccid_clear_pending_answers(USBCCIDState *s)
482
{
483
    s->pending_answers_num = 0;
484
    s->pending_answers_start = 0;
485
    s->pending_answers_end = 0;
486
}
487

    
488
static void ccid_print_pending_answers(USBCCIDState *s)
489
{
490
    Answer *answer;
491
    int i, count;
492

    
493
    DPRINTF(s, D_VERBOSE, "usb-ccid: pending answers:");
494
    if (!ccid_has_pending_answers(s)) {
495
        DPRINTF(s, D_VERBOSE, " empty\n");
496
        return;
497
    }
498
    for (i = s->pending_answers_start, count = s->pending_answers_num ;
499
         count > 0; count--, i++) {
500
        answer = &s->pending_answers[i % PENDING_ANSWERS_NUM];
501
        if (count == 1) {
502
            DPRINTF(s, D_VERBOSE, "%d:%d\n", answer->slot, answer->seq);
503
        } else {
504
            DPRINTF(s, D_VERBOSE, "%d:%d,", answer->slot, answer->seq);
505
        }
506
    }
507
}
508

    
509
static void ccid_add_pending_answer(USBCCIDState *s, CCID_Header *hdr)
510
{
511
    Answer *answer;
512

    
513
    assert(s->pending_answers_num < PENDING_ANSWERS_NUM);
514
    s->pending_answers_num++;
515
    answer =
516
        &s->pending_answers[(s->pending_answers_end++) % PENDING_ANSWERS_NUM];
517
    answer->slot = hdr->bSlot;
518
    answer->seq = hdr->bSeq;
519
    ccid_print_pending_answers(s);
520
}
521

    
522
static void ccid_remove_pending_answer(USBCCIDState *s,
523
    uint8_t *slot, uint8_t *seq)
524
{
525
    Answer *answer;
526

    
527
    assert(s->pending_answers_num > 0);
528
    s->pending_answers_num--;
529
    answer =
530
        &s->pending_answers[(s->pending_answers_start++) % PENDING_ANSWERS_NUM];
531
    *slot = answer->slot;
532
    *seq = answer->seq;
533
    ccid_print_pending_answers(s);
534
}
535

    
536
static void ccid_bulk_in_clear(USBCCIDState *s)
537
{
538
    s->bulk_in_pending_start = 0;
539
    s->bulk_in_pending_end = 0;
540
    s->bulk_in_pending_num = 0;
541
}
542

    
543
static void ccid_bulk_in_release(USBCCIDState *s)
544
{
545
    assert(s->current_bulk_in != NULL);
546
    s->current_bulk_in->pos = 0;
547
    s->current_bulk_in = NULL;
548
}
549

    
550
static void ccid_bulk_in_get(USBCCIDState *s)
551
{
552
    if (s->current_bulk_in != NULL || s->bulk_in_pending_num == 0) {
553
        return;
554
    }
555
    assert(s->bulk_in_pending_num > 0);
556
    s->bulk_in_pending_num--;
557
    s->current_bulk_in =
558
        &s->bulk_in_pending[(s->bulk_in_pending_start++) % BULK_IN_PENDING_NUM];
559
}
560

    
561
static void *ccid_reserve_recv_buf(USBCCIDState *s, uint16_t len)
562
{
563
    BulkIn *bulk_in;
564

    
565
    DPRINTF(s, D_VERBOSE, "%s: QUEUE: reserve %d bytes\n", __func__, len);
566

    
567
    /* look for an existing element */
568
    if (len > BULK_IN_BUF_SIZE) {
569
        DPRINTF(s, D_WARN, "usb-ccid.c: %s: len larger then max (%d>%d). "
570
                           "discarding message.\n",
571
                           __func__, len, BULK_IN_BUF_SIZE);
572
        return NULL;
573
    }
574
    if (s->bulk_in_pending_num >= BULK_IN_PENDING_NUM) {
575
        DPRINTF(s, D_WARN, "usb-ccid.c: %s: No free bulk_in buffers. "
576
                           "discarding message.\n", __func__);
577
        return NULL;
578
    }
579
    bulk_in =
580
        &s->bulk_in_pending[(s->bulk_in_pending_end++) % BULK_IN_PENDING_NUM];
581
    s->bulk_in_pending_num++;
582
    bulk_in->len = len;
583
    return bulk_in->data;
584
}
585

    
586
static void ccid_reset(USBCCIDState *s)
587
{
588
    ccid_bulk_in_clear(s);
589
    ccid_clear_pending_answers(s);
590
}
591

    
592
static void ccid_detach(USBCCIDState *s)
593
{
594
    ccid_reset(s);
595
}
596

    
597
static void ccid_handle_reset(USBDevice *dev)
598
{
599
    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
600

    
601
    DPRINTF(s, 1, "Reset\n");
602

    
603
    ccid_reset(s);
604
}
605

    
606
static int ccid_handle_control(USBDevice *dev, USBPacket *p, int request,
607
                               int value, int index, int length, uint8_t *data)
608
{
609
    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
610
    int ret = 0;
611

    
612
    DPRINTF(s, 1, "got control %x, value %x\n", request, value);
613
    switch (request) {
614
    case DeviceRequest | USB_REQ_GET_STATUS:
615
        data[0] = (1 << USB_DEVICE_SELF_POWERED) |
616
            (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);
617
        data[1] = 0x00;
618
        ret = 2;
619
        break;
620
    case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
621
        if (value == USB_DEVICE_REMOTE_WAKEUP) {
622
            dev->remote_wakeup = 0;
623
        } else {
624
            goto fail;
625
        }
626
        ret = 0;
627
        break;
628
    case DeviceOutRequest | USB_REQ_SET_FEATURE:
629
        if (value == USB_DEVICE_REMOTE_WAKEUP) {
630
            dev->remote_wakeup = 1;
631
        } else {
632
            goto fail;
633
        }
634
        ret = 0;
635
        break;
636
    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
637
        dev->addr = value;
638
        ret = 0;
639
        break;
640
    case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
641
        switch (value >> 8) {
642
        case USB_DT_DEVICE:
643
            memcpy(data, qemu_ccid_dev_descriptor,
644
                   sizeof(qemu_ccid_dev_descriptor));
645
            ret = sizeof(qemu_ccid_dev_descriptor);
646
            break;
647
        case USB_DT_CONFIG:
648
            memcpy(data, qemu_ccid_config_descriptor,
649
                   sizeof(qemu_ccid_config_descriptor));
650
            ret = sizeof(qemu_ccid_config_descriptor);
651
            break;
652
        case USB_DT_STRING:
653
            switch (value & 0xff) {
654
            case 0:
655
                /* language ids */
656
                data[0] = 4;
657
                data[1] = 3;
658
                data[2] = 0x09;
659
                data[3] = 0x04;
660
                ret = 4;
661
                break;
662
            case 1:
663
                /* vendor description */
664
                ret = set_usb_string(data, CCID_VENDOR_DESCRIPTION);
665
                break;
666
            case 2:
667
                /* product description */
668
                ret = set_usb_string(data, CCID_PRODUCT_DESCRIPTION);
669
                break;
670
            case 3:
671
                /* serial number */
672
                ret = set_usb_string(data, CCID_SERIAL_NUMBER_STRING);
673
                break;
674
            case 4:
675
                /* interface name */
676
                ret = set_usb_string(data, CCID_INTERFACE_NAME);
677
                break;
678
            default:
679
                goto fail;
680
            }
681
            break;
682
        default:
683
            goto fail;
684
        }
685
        break;
686
    case DeviceRequest | USB_REQ_GET_CONFIGURATION:
687
        data[0] = 1;
688
        ret = 1;
689
        break;
690
    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
691
        /* Only one configuration - we just ignore the request */
692
        ret = 0;
693
        break;
694
    case DeviceRequest | USB_REQ_GET_INTERFACE:
695
        data[0] = 0;
696
        ret = 1;
697
        break;
698
    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
699
        ret = 0;
700
        break;
701
    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
702
        ret = 0;
703
        break;
704

    
705
        /* Class specific requests.  */
706
    case InterfaceOutClass | CCID_CONTROL_ABORT:
707
        DPRINTF(s, 1, "ccid_control abort UNIMPLEMENTED\n");
708
        ret = USB_RET_STALL;
709
        break;
710
    case InterfaceInClass | CCID_CONTROL_GET_CLOCK_FREQUENCIES:
711
        DPRINTF(s, 1, "ccid_control get clock frequencies UNIMPLEMENTED\n");
712
        ret = USB_RET_STALL;
713
        break;
714
    case InterfaceInClass | CCID_CONTROL_GET_DATA_RATES:
715
        DPRINTF(s, 1, "ccid_control get data rates UNIMPLEMENTED\n");
716
        ret = USB_RET_STALL;
717
        break;
718
    default:
719
fail:
720
        DPRINTF(s, 1, "got unsupported/bogus control %x, value %x\n",
721
                request, value);
722
        ret = USB_RET_STALL;
723
        break;
724
    }
725
    return ret;
726
}
727

    
728
static bool ccid_card_inserted(USBCCIDState *s)
729
{
730
    return s->bmSlotICCState & SLOT_0_STATE_MASK;
731
}
732

    
733
static uint8_t ccid_card_status(USBCCIDState *s)
734
{
735
    return ccid_card_inserted(s)
736
            ? (s->powered ?
737
                ICC_STATUS_PRESENT_ACTIVE
738
              : ICC_STATUS_PRESENT_INACTIVE
739
              )
740
            : ICC_STATUS_NOT_PRESENT;
741
}
742

    
743
static uint8_t ccid_calc_status(USBCCIDState *s)
744
{
745
    /*
746
     * page 55, 6.2.6, calculation of bStatus from bmICCStatus and
747
     * bmCommandStatus
748
     */
749
    uint8_t ret = ccid_card_status(s) | (s->bmCommandStatus << 6);
750
    DPRINTF(s, D_VERBOSE, "status = %d\n", ret);
751
    return ret;
752
}
753

    
754
static void ccid_reset_error_status(USBCCIDState *s)
755
{
756
    s->bError = ERROR_CMD_NOT_SUPPORTED;
757
    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
758
}
759

    
760
static void ccid_write_slot_status(USBCCIDState *s, CCID_Header *recv)
761
{
762
    CCID_SlotStatus *h = ccid_reserve_recv_buf(s, sizeof(CCID_SlotStatus));
763
    if (h == NULL) {
764
        return;
765
    }
766
    h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus;
767
    h->b.hdr.dwLength = 0;
768
    h->b.hdr.bSlot = recv->bSlot;
769
    h->b.hdr.bSeq = recv->bSeq;
770
    h->b.bStatus = ccid_calc_status(s);
771
    h->b.bError = s->bError;
772
    h->bClockStatus = CLOCK_STATUS_RUNNING;
773
    ccid_reset_error_status(s);
774
}
775

    
776
static void ccid_write_parameters(USBCCIDState *s, CCID_Header *recv)
777
{
778
    CCID_Parameter *h;
779
    uint32_t len = s->ulProtocolDataStructureSize;
780

    
781
    h = ccid_reserve_recv_buf(s, sizeof(CCID_Parameter) + len);
782
    if (h == NULL) {
783
        return;
784
    }
785
    h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_Parameters;
786
    h->b.hdr.dwLength = 0;
787
    h->b.hdr.bSlot = recv->bSlot;
788
    h->b.hdr.bSeq = recv->bSeq;
789
    h->b.bStatus = ccid_calc_status(s);
790
    h->b.bError = s->bError;
791
    h->bProtocolNum = s->bProtocolNum;
792
    memcpy(h->abProtocolDataStructure, s->abProtocolDataStructure, len);
793
    ccid_reset_error_status(s);
794
}
795

    
796
static void ccid_write_data_block(USBCCIDState *s, uint8_t slot, uint8_t seq,
797
                                  const uint8_t *data, uint32_t len)
798
{
799
    CCID_DataBlock *p = ccid_reserve_recv_buf(s, sizeof(*p) + len);
800

    
801
    if (p == NULL) {
802
        return;
803
    }
804
    p->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock;
805
    p->b.hdr.dwLength = cpu_to_le32(len);
806
    p->b.hdr.bSlot = slot;
807
    p->b.hdr.bSeq = seq;
808
    p->b.bStatus = ccid_calc_status(s);
809
    p->b.bError = s->bError;
810
    if (p->b.bError) {
811
        DPRINTF(s, D_VERBOSE, "error %d", p->b.bError);
812
    }
813
    memcpy(p->abData, data, len);
814
    ccid_reset_error_status(s);
815
}
816

    
817
static void ccid_write_data_block_answer(USBCCIDState *s,
818
    const uint8_t *data, uint32_t len)
819
{
820
    uint8_t seq;
821
    uint8_t slot;
822

    
823
    if (!ccid_has_pending_answers(s)) {
824
        abort();
825
    }
826
    ccid_remove_pending_answer(s, &slot, &seq);
827
    ccid_write_data_block(s, slot, seq, data, len);
828
}
829

    
830
static void ccid_write_data_block_atr(USBCCIDState *s, CCID_Header *recv)
831
{
832
    const uint8_t *atr = NULL;
833
    uint32_t len = 0;
834

    
835
    if (s->card) {
836
        atr = s->cardinfo->get_atr(s->card, &len);
837
    }
838
    ccid_write_data_block(s, recv->bSlot, recv->bSeq, atr, len);
839
}
840

    
841
static void ccid_set_parameters(USBCCIDState *s, CCID_Header *recv)
842
{
843
    CCID_SetParameters *ph = (CCID_SetParameters *) recv;
844
    uint32_t len = 0;
845
    if ((ph->bProtocolNum & 3) == 0) {
846
        len = 5;
847
    }
848
    if ((ph->bProtocolNum & 3) == 1) {
849
        len = 7;
850
    }
851
    if (len == 0) {
852
        s->bmCommandStatus = COMMAND_STATUS_FAILED;
853
        s->bError = 7; /* Protocol invalid or not supported */
854
        return;
855
    }
856
    s->bProtocolNum = ph->bProtocolNum;
857
    memcpy(s->abProtocolDataStructure, ph->abProtocolDataStructure, len);
858
    s->ulProtocolDataStructureSize = len;
859
    DPRINTF(s, 1, "%s: using len %d\n", __func__, len);
860
}
861

    
862
/*
863
 * must be 5 bytes for T=0, 7 bytes for T=1
864
 * See page 52
865
 */
866
static const uint8_t abDefaultProtocolDataStructure[7] = {
867
    0x77, 0x00, 0x00, 0x00, 0x00, 0xfe /*IFSC*/, 0x00 /*NAD*/ };
868

    
869
static void ccid_reset_parameters(USBCCIDState *s)
870
{
871
   uint32_t len = sizeof(abDefaultProtocolDataStructure);
872

    
873
   s->bProtocolNum = 1; /* T=1 */
874
   s->ulProtocolDataStructureSize = len;
875
   memcpy(s->abProtocolDataStructure, abDefaultProtocolDataStructure, len);
876
}
877

    
878
static void ccid_report_error_failed(USBCCIDState *s, uint8_t error)
879
{
880
    s->bmCommandStatus = COMMAND_STATUS_FAILED;
881
    s->bError = error;
882
}
883

    
884
/* NOTE: only a single slot is supported (SLOT_0) */
885
static void ccid_on_slot_change(USBCCIDState *s, bool full)
886
{
887
    /* RDR_to_PC_NotifySlotChange, 6.3.1 page 56 */
888
    uint8_t current = s->bmSlotICCState;
889
    if (full) {
890
        s->bmSlotICCState |= SLOT_0_STATE_MASK;
891
    } else {
892
        s->bmSlotICCState &= ~SLOT_0_STATE_MASK;
893
    }
894
    if (current != s->bmSlotICCState) {
895
        s->bmSlotICCState |= SLOT_0_CHANGED_MASK;
896
    }
897
    s->notify_slot_change = true;
898
}
899

    
900
static void ccid_write_data_block_error(
901
    USBCCIDState *s, uint8_t slot, uint8_t seq)
902
{
903
    ccid_write_data_block(s, slot, seq, NULL, 0);
904
}
905

    
906
static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
907
{
908
    uint32_t len;
909

    
910
    if (ccid_card_status(s) != ICC_STATUS_PRESENT_ACTIVE) {
911
        DPRINTF(s, 1,
912
                "usb-ccid: not sending apdu to client, no card connected\n");
913
        ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);
914
        return;
915
    }
916
    len = le32_to_cpu(recv->hdr.dwLength);
917
    DPRINTF(s, 1, "%s: seq %d, len %d\n", __func__,
918
                recv->hdr.bSeq, len);
919
    ccid_add_pending_answer(s, (CCID_Header *)recv);
920
    if (s->card) {
921
        s->cardinfo->apdu_from_guest(s->card, recv->abData, len);
922
    } else {
923
        DPRINTF(s, D_WARN, "warning: discarded apdu\n");
924
    }
925
}
926

    
927
/*
928
 * Handle a single USB_TOKEN_OUT, return value returned to guest.
929
 * Return value:
930
 *  0             - all ok
931
 *  USB_RET_STALL - failed to handle packet
932
 */
933
static int ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
934
{
935
    CCID_Header *ccid_header;
936

    
937
    if (p->len + s->bulk_out_pos > BULK_OUT_DATA_SIZE) {
938
        return USB_RET_STALL;
939
    }
940
    ccid_header = (CCID_Header *)s->bulk_out_data;
941
    memcpy(s->bulk_out_data + s->bulk_out_pos, p->data, p->len);
942
    s->bulk_out_pos += p->len;
943
    if (p->len == CCID_MAX_PACKET_SIZE) {
944
        DPRINTF(s, D_VERBOSE,
945
            "usb-ccid: bulk_in: expecting more packets (%d/%d)\n",
946
            p->len, ccid_header->dwLength);
947
        return 0;
948
    }
949
    if (s->bulk_out_pos < 10) {
950
        DPRINTF(s, 1,
951
                "%s: bad USB_TOKEN_OUT length, should be at least 10 bytes\n",
952
                __func__);
953
    } else {
954
        DPRINTF(s, D_MORE_INFO, "%s %x\n", __func__, ccid_header->bMessageType);
955
        switch (ccid_header->bMessageType) {
956
        case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus:
957
            ccid_write_slot_status(s, ccid_header);
958
            break;
959
        case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:
960
            DPRINTF(s, 1, "PowerOn: %d\n",
961
                ((CCID_IccPowerOn *)(ccid_header))->bPowerSelect);
962
            s->powered = true;
963
            if (!ccid_card_inserted(s)) {
964
                ccid_report_error_failed(s, ERROR_ICC_MUTE);
965
            }
966
            /* atr is written regardless of error. */
967
            ccid_write_data_block_atr(s, ccid_header);
968
            break;
969
        case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff:
970
            DPRINTF(s, 1, "PowerOff\n");
971
            ccid_reset_error_status(s);
972
            s->powered = false;
973
            ccid_write_slot_status(s, ccid_header);
974
            break;
975
        case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:
976
            ccid_on_apdu_from_guest(s, (CCID_XferBlock *)s->bulk_out_data);
977
            break;
978
        case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters:
979
            ccid_reset_error_status(s);
980
            ccid_set_parameters(s, ccid_header);
981
            ccid_write_parameters(s, ccid_header);
982
            break;
983
        case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters:
984
            ccid_reset_error_status(s);
985
            ccid_reset_parameters(s);
986
            ccid_write_parameters(s, ccid_header);
987
            break;
988
        case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters:
989
            ccid_reset_error_status(s);
990
            ccid_write_parameters(s, ccid_header);
991
            break;
992
        default:
993
            DPRINTF(s, 1,
994
                "handle_data: ERROR: unhandled message type %Xh\n",
995
                ccid_header->bMessageType);
996
            /*
997
             * The caller is expecting the device to respond, tell it we
998
             * don't support the operation.
999
             */
1000
            ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
1001
            ccid_write_slot_status(s, ccid_header);
1002
            break;
1003
        }
1004
    }
1005
    s->bulk_out_pos = 0;
1006
    return 0;
1007
}
1008

    
1009
static int ccid_bulk_in_copy_to_guest(USBCCIDState *s, uint8_t *data, int len)
1010
{
1011
    int ret = 0;
1012

    
1013
    assert(len > 0);
1014
    ccid_bulk_in_get(s);
1015
    if (s->current_bulk_in != NULL) {
1016
        ret = MIN(s->current_bulk_in->len - s->current_bulk_in->pos, len);
1017
        memcpy(data, s->current_bulk_in->data + s->current_bulk_in->pos, ret);
1018
        s->current_bulk_in->pos += ret;
1019
        if (s->current_bulk_in->pos == s->current_bulk_in->len) {
1020
            ccid_bulk_in_release(s);
1021
        }
1022
    } else {
1023
        /* return when device has no data - usb 2.0 spec Table 8-4 */
1024
        ret = USB_RET_NAK;
1025
    }
1026
    if (ret > 0) {
1027
        DPRINTF(s, D_MORE_INFO,
1028
                "%s: %d/%d req/act to guest (BULK_IN)\n", __func__, len, ret);
1029
    }
1030
    if (ret != USB_RET_NAK && ret < len) {
1031
        DPRINTF(s, 1,
1032
            "%s: returning short (EREMOTEIO) %d < %d\n", __func__, ret, len);
1033
    }
1034
    return ret;
1035
}
1036

    
1037
static int ccid_handle_data(USBDevice *dev, USBPacket *p)
1038
{
1039
    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
1040
    int ret = 0;
1041
    uint8_t *data = p->data;
1042
    int len = p->len;
1043

    
1044
    switch (p->pid) {
1045
    case USB_TOKEN_OUT:
1046
        ret = ccid_handle_bulk_out(s, p);
1047
        break;
1048

    
1049
    case USB_TOKEN_IN:
1050
        switch (p->devep & 0xf) {
1051
        case CCID_BULK_IN_EP:
1052
            if (!len) {
1053
                ret = USB_RET_NAK;
1054
            } else {
1055
                ret = ccid_bulk_in_copy_to_guest(s, data, len);
1056
            }
1057
            break;
1058
        case CCID_INT_IN_EP:
1059
            if (s->notify_slot_change) {
1060
                /* page 56, RDR_to_PC_NotifySlotChange */
1061
                data[0] = CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange;
1062
                data[1] = s->bmSlotICCState;
1063
                ret = 2;
1064
                s->notify_slot_change = false;
1065
                s->bmSlotICCState &= ~SLOT_0_CHANGED_MASK;
1066
                DPRINTF(s, D_INFO,
1067
                        "handle_data: int_in: notify_slot_change %X, "
1068
                        "requested len %d\n",
1069
                        s->bmSlotICCState, len);
1070
            }
1071
            break;
1072
        default:
1073
            DPRINTF(s, 1, "Bad endpoint\n");
1074
            break;
1075
        }
1076
        break;
1077
    default:
1078
        DPRINTF(s, 1, "Bad token\n");
1079
        ret = USB_RET_STALL;
1080
        break;
1081
    }
1082

    
1083
    return ret;
1084
}
1085

    
1086
static void ccid_handle_destroy(USBDevice *dev)
1087
{
1088
    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
1089

    
1090
    ccid_bulk_in_clear(s);
1091
}
1092

    
1093
static void ccid_flush_pending_answers(USBCCIDState *s)
1094
{
1095
    while (ccid_has_pending_answers(s)) {
1096
        ccid_write_data_block_answer(s, NULL, 0);
1097
    }
1098
}
1099

    
1100
static Answer *ccid_peek_next_answer(USBCCIDState *s)
1101
{
1102
    return s->pending_answers_num == 0
1103
        ? NULL
1104
        : &s->pending_answers[s->pending_answers_start % PENDING_ANSWERS_NUM];
1105
}
1106

    
1107
static void ccid_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent)
1108
{
1109
    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
1110
    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, qdev->info);
1111

    
1112
    if (info->print) {
1113
        info->print(mon, card, indent);
1114
    }
1115
}
1116

    
1117
static struct BusInfo ccid_bus_info = {
1118
    .name = "ccid-bus",
1119
    .size = sizeof(CCIDBus),
1120
    .print_dev = ccid_bus_dev_print,
1121
    .props = (Property[]) {
1122
        DEFINE_PROP_UINT32("slot", struct CCIDCardState, slot, 0),
1123
        DEFINE_PROP_END_OF_LIST(),
1124
    }
1125
};
1126

    
1127
void ccid_card_send_apdu_to_guest(CCIDCardState *card,
1128
                                  uint8_t *apdu, uint32_t len)
1129
{
1130
    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev,
1131
                                card->qdev.parent_bus->parent);
1132
    Answer *answer;
1133

    
1134
    if (!ccid_has_pending_answers(s)) {
1135
        DPRINTF(s, 1, "CCID ERROR: got an APDU without pending answers\n");
1136
        return;
1137
    }
1138
    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
1139
    answer = ccid_peek_next_answer(s);
1140
    if (answer == NULL) {
1141
        abort();
1142
    }
1143
    DPRINTF(s, 1, "APDU returned to guest %d (answer seq %d, slot %d)\n",
1144
        len, answer->seq, answer->slot);
1145
    ccid_write_data_block_answer(s, apdu, len);
1146
}
1147

    
1148
void ccid_card_card_removed(CCIDCardState *card)
1149
{
1150
    USBCCIDState *s =
1151
        DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1152

    
1153
    ccid_on_slot_change(s, false);
1154
    ccid_flush_pending_answers(s);
1155
    ccid_reset(s);
1156
}
1157

    
1158
int ccid_card_ccid_attach(CCIDCardState *card)
1159
{
1160
    USBCCIDState *s =
1161
        DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1162

    
1163
    DPRINTF(s, 1, "CCID Attach\n");
1164
    if (s->migration_state == MIGRATION_MIGRATED) {
1165
        s->migration_state = MIGRATION_NONE;
1166
    }
1167
    return 0;
1168
}
1169

    
1170
void ccid_card_ccid_detach(CCIDCardState *card)
1171
{
1172
    USBCCIDState *s =
1173
        DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1174

    
1175
    DPRINTF(s, 1, "CCID Detach\n");
1176
    if (ccid_card_inserted(s)) {
1177
        ccid_on_slot_change(s, false);
1178
    }
1179
    ccid_detach(s);
1180
}
1181

    
1182
void ccid_card_card_error(CCIDCardState *card, uint64_t error)
1183
{
1184
    USBCCIDState *s =
1185
        DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1186

    
1187
    s->bmCommandStatus = COMMAND_STATUS_FAILED;
1188
    s->last_answer_error = error;
1189
    DPRINTF(s, 1, "VSC_Error: %" PRIX64 "\n", s->last_answer_error);
1190
    /* TODO: these errors should be more verbose and propagated to the guest.*/
1191
    /*
1192
     * We flush all pending answers on CardRemove message in ccid-card-passthru,
1193
     * so check that first to not trigger abort
1194
     */
1195
    if (ccid_has_pending_answers(s)) {
1196
        ccid_write_data_block_answer(s, NULL, 0);
1197
    }
1198
}
1199

    
1200
void ccid_card_card_inserted(CCIDCardState *card)
1201
{
1202
    USBCCIDState *s =
1203
        DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1204

    
1205
    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
1206
    ccid_flush_pending_answers(s);
1207
    ccid_on_slot_change(s, true);
1208
}
1209

    
1210
static int ccid_card_exit(DeviceState *qdev)
1211
{
1212
    int ret = 0;
1213
    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
1214
    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, qdev->info);
1215
    USBCCIDState *s =
1216
        DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1217

    
1218
    if (ccid_card_inserted(s)) {
1219
        ccid_card_card_removed(card);
1220
    }
1221
    if (info->exitfn) {
1222
        ret = info->exitfn(card);
1223
    }
1224
    s->card = NULL;
1225
    s->cardinfo = NULL;
1226
    return ret;
1227
}
1228

    
1229
static int ccid_card_init(DeviceState *qdev, DeviceInfo *base)
1230
{
1231
    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
1232
    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, base);
1233
    USBCCIDState *s =
1234
        DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
1235
    int ret = 0;
1236

    
1237
    if (card->slot != 0) {
1238
        error_report("Warning: usb-ccid supports one slot, can't add %d",
1239
                card->slot);
1240
        return -1;
1241
    }
1242
    if (s->card != NULL) {
1243
        error_report("Warning: usb-ccid card already full, not adding\n");
1244
        return -1;
1245
    }
1246
    ret = info->initfn ? info->initfn(card) : ret;
1247
    if (ret == 0) {
1248
        s->card = card;
1249
        s->cardinfo = info;
1250
    }
1251
    return ret;
1252
}
1253

    
1254
void ccid_card_qdev_register(CCIDCardInfo *card)
1255
{
1256
    card->qdev.bus_info = &ccid_bus_info;
1257
    card->qdev.init = ccid_card_init;
1258
    card->qdev.exit = ccid_card_exit;
1259
    qdev_register(&card->qdev);
1260
}
1261

    
1262
static int ccid_initfn(USBDevice *dev)
1263
{
1264
    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
1265

    
1266
    qbus_create_inplace(&s->bus.qbus, &ccid_bus_info, &dev->qdev, NULL);
1267
    s->bus.qbus.allow_hotplug = 1;
1268
    s->card = NULL;
1269
    s->cardinfo = NULL;
1270
    s->migration_state = MIGRATION_NONE;
1271
    s->migration_target_ip = 0;
1272
    s->migration_target_port = 0;
1273
    s->dev.speed = USB_SPEED_FULL;
1274
    s->notify_slot_change = false;
1275
    s->powered = true;
1276
    s->pending_answers_num = 0;
1277
    s->last_answer_error = 0;
1278
    s->bulk_in_pending_start = 0;
1279
    s->bulk_in_pending_end = 0;
1280
    s->current_bulk_in = NULL;
1281
    ccid_reset_error_status(s);
1282
    s->bulk_out_pos = 0;
1283
    ccid_reset_parameters(s);
1284
    ccid_reset(s);
1285
    return 0;
1286
}
1287

    
1288
static int ccid_post_load(void *opaque, int version_id)
1289
{
1290
    USBCCIDState *s = opaque;
1291

    
1292
    /*
1293
     * This must be done after usb_device_attach, which sets state to ATTACHED,
1294
     * while it must be DEFAULT in order to accept packets (like it is after
1295
     * reset, but reset will reset our addr and call our reset handler which
1296
     * may change state, and we don't want to do that when migrating).
1297
     */
1298
    s->dev.state = s->state_vmstate;
1299
    return 0;
1300
}
1301

    
1302
static void ccid_pre_save(void *opaque)
1303
{
1304
    USBCCIDState *s = opaque;
1305

    
1306
    s->state_vmstate = s->dev.state;
1307
    if (s->dev.attached) {
1308
        /*
1309
         * Migrating an open device, ignore reconnection CHR_EVENT to avoid an
1310
         * erroneous detach.
1311
         */
1312
        s->migration_state = MIGRATION_MIGRATED;
1313
    }
1314
}
1315

    
1316
static VMStateDescription bulk_in_vmstate = {
1317
    .name = "CCID BulkIn state",
1318
    .version_id = 1,
1319
    .minimum_version_id = 1,
1320
    .fields = (VMStateField[]) {
1321
        VMSTATE_BUFFER(data, BulkIn),
1322
        VMSTATE_UINT32(len, BulkIn),
1323
        VMSTATE_UINT32(pos, BulkIn),
1324
        VMSTATE_END_OF_LIST()
1325
    }
1326
};
1327

    
1328
static VMStateDescription answer_vmstate = {
1329
    .name = "CCID Answer state",
1330
    .version_id = 1,
1331
    .minimum_version_id = 1,
1332
    .fields = (VMStateField[]) {
1333
        VMSTATE_UINT8(slot, Answer),
1334
        VMSTATE_UINT8(seq, Answer),
1335
        VMSTATE_END_OF_LIST()
1336
    }
1337
};
1338

    
1339
static VMStateDescription usb_device_vmstate = {
1340
    .name = "usb_device",
1341
    .version_id = 1,
1342
    .minimum_version_id = 1,
1343
    .fields = (VMStateField[]) {
1344
        VMSTATE_UINT8(addr, USBDevice),
1345
        VMSTATE_BUFFER(setup_buf, USBDevice),
1346
        VMSTATE_BUFFER(data_buf, USBDevice),
1347
        VMSTATE_END_OF_LIST()
1348
    }
1349
};
1350

    
1351
static VMStateDescription ccid_vmstate = {
1352
    .name = CCID_DEV_NAME,
1353
    .version_id = 1,
1354
    .minimum_version_id = 1,
1355
    .post_load = ccid_post_load,
1356
    .pre_save = ccid_pre_save,
1357
    .fields = (VMStateField[]) {
1358
        VMSTATE_STRUCT(dev, USBCCIDState, 1, usb_device_vmstate, USBDevice),
1359
        VMSTATE_UINT8(debug, USBCCIDState),
1360
        VMSTATE_BUFFER(bulk_out_data, USBCCIDState),
1361
        VMSTATE_UINT32(bulk_out_pos, USBCCIDState),
1362
        VMSTATE_UINT8(bmSlotICCState, USBCCIDState),
1363
        VMSTATE_UINT8(powered, USBCCIDState),
1364
        VMSTATE_UINT8(notify_slot_change, USBCCIDState),
1365
        VMSTATE_UINT64(last_answer_error, USBCCIDState),
1366
        VMSTATE_UINT8(bError, USBCCIDState),
1367
        VMSTATE_UINT8(bmCommandStatus, USBCCIDState),
1368
        VMSTATE_UINT8(bProtocolNum, USBCCIDState),
1369
        VMSTATE_BUFFER(abProtocolDataStructure, USBCCIDState),
1370
        VMSTATE_UINT32(ulProtocolDataStructureSize, USBCCIDState),
1371
        VMSTATE_STRUCT_ARRAY(bulk_in_pending, USBCCIDState,
1372
                       BULK_IN_PENDING_NUM, 1, bulk_in_vmstate, BulkIn),
1373
        VMSTATE_UINT32(bulk_in_pending_start, USBCCIDState),
1374
        VMSTATE_UINT32(bulk_in_pending_end, USBCCIDState),
1375
        VMSTATE_STRUCT_ARRAY(pending_answers, USBCCIDState,
1376
                        PENDING_ANSWERS_NUM, 1, answer_vmstate, Answer),
1377
        VMSTATE_UINT32(pending_answers_num, USBCCIDState),
1378
        VMSTATE_UINT8(migration_state, USBCCIDState),
1379
        VMSTATE_UINT32(state_vmstate, USBCCIDState),
1380
        VMSTATE_END_OF_LIST()
1381
    }
1382
};
1383

    
1384
static struct USBDeviceInfo ccid_info = {
1385
    .product_desc   = "QEMU USB CCID",
1386
    .qdev.name      = CCID_DEV_NAME,
1387
    .qdev.desc      = "CCID Rev 1.1 smartcard reader",
1388
    .qdev.size      = sizeof(USBCCIDState),
1389
    .init           = ccid_initfn,
1390
    .handle_packet  = usb_generic_handle_packet,
1391
    .handle_reset   = ccid_handle_reset,
1392
    .handle_control = ccid_handle_control,
1393
    .handle_data    = ccid_handle_data,
1394
    .handle_destroy = ccid_handle_destroy,
1395
    .usbdevice_name = "ccid",
1396
    .qdev.props     = (Property[]) {
1397
        DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
1398
        DEFINE_PROP_END_OF_LIST(),
1399
    },
1400
    .qdev.vmsd      = &ccid_vmstate,
1401
};
1402

    
1403
static void ccid_register_devices(void)
1404
{
1405
    usb_qdev_register(&ccid_info);
1406
}
1407
device_init(ccid_register_devices)