All of lore.kernel.org
 help / color / mirror / Atom feed
* [Qemu-devel] [PATCH 0/4] usb-ccid (v4)
@ 2010-10-24 13:18 Alon Levy
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 1/4] usb-ccid: add CCID bus Alon Levy
                   ` (4 more replies)
  0 siblings, 5 replies; 10+ messages in thread
From: Alon Levy @ 2010-10-24 13:18 UTC (permalink / raw)
  To: qemu-devel

This patchset adds three new devices, usb-ccid, ccid-card-passthru and ccid-card-emulated, providing a CCID bus, a simple passthru protocol implementing card requiring a client, and a standalone emulated card.

v4 changes just the bus following Markus remarks, but I'm resending everything since nothing has been ack'ed yet and it eases review.

v3->v4:
 * remove ccid field in CCIDBus
 * remove static debug
 * add back docs

v2->v3:
 * split into bus (usb-ccid.c, uses ccid.h) and card (ccid-card-passthru.c).
 * removed documentation (being revised).

v1->v2:
 * all QSIMPLEQ turned into fixed sized rings
 * all allocated buffers turned into fixed size buffers
 * added migration support
 * added a message to tell client qemu has migrated to ip:port
  * for lack of monitor commands ip:port are 0:0, which causes the updated
   vscclient to connect to one port higher on the same host. will add monitor
   commands in a separate patch. tested with current setup.

Alon Levy (4):
  usb-ccid: add CCID bus
  ccid: add passthru card device
  add ccid-card-emulated device (v2)
  ccid: add docs

 Makefile.objs           |    1 +
 configure               |   32 ++
 docs/ccid.txt           |  133 +++++
 hw/ccid-card-emulated.c |  495 +++++++++++++++++
 hw/ccid-card-passthru.c |  278 ++++++++++
 hw/ccid.h               |   34 ++
 hw/usb-ccid.c           | 1346 +++++++++++++++++++++++++++++++++++++++++++++++
 hw/vscard_common.h      |  130 +++++
 8 files changed, 2449 insertions(+), 0 deletions(-)
 create mode 100644 docs/ccid.txt
 create mode 100644 hw/ccid-card-emulated.c
 create mode 100644 hw/ccid-card-passthru.c
 create mode 100644 hw/ccid.h
 create mode 100644 hw/usb-ccid.c
 create mode 100644 hw/vscard_common.h

-- 
1.7.3.1

^ permalink raw reply	[flat|nested] 10+ messages in thread

* [Qemu-devel] [PATCH 1/4] usb-ccid: add CCID bus
  2010-10-24 13:18 [Qemu-devel] [PATCH 0/4] usb-ccid (v4) Alon Levy
@ 2010-10-24 13:18 ` Alon Levy
  2010-11-09 10:11   ` Markus Armbruster
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 2/4] ccid: add passthru card device Alon Levy
                   ` (3 subsequent siblings)
  4 siblings, 1 reply; 10+ messages in thread
From: Alon Levy @ 2010-10-24 13:18 UTC (permalink / raw)
  To: qemu-devel

A CCID device is a smart card reader. It is a USB device, defined at [1].
This patch introduces the usb-ccid device that is a ccid bus. Next patches will
introduce two card types to use it, a passthru card and an emulated card.

 [1] http://www.usb.org/developers/devclass_docs/DWG_Smart-Card_CCID_Rev110.

Signed-off-by: Alon Levy <alevy@redhat.com>
---
 Makefile.objs |    1 +
 configure     |   12 +
 hw/ccid.h     |   34 ++
 hw/usb-ccid.c | 1346 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1393 insertions(+), 0 deletions(-)
 create mode 100644 hw/ccid.h
 create mode 100644 hw/usb-ccid.c

diff --git a/Makefile.objs b/Makefile.objs
index f07fb01..5b52625 100644
--- a/Makefile.objs
+++ b/Makefile.objs
@@ -174,6 +174,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
 hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
 hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
 hw-obj-$(CONFIG_DMA) += dma.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
diff --git a/configure b/configure
index f62c1fe..15aee9e 100755
--- a/configure
+++ b/configure
@@ -332,6 +332,7 @@ zero_malloc=""
 trace_backend="nop"
 trace_file="trace"
 spice=""
+smartcard="no"
 
 # OS specific
 if check_define __linux__ ; then
@@ -739,6 +740,10 @@ for opt do
   ;;
   --enable-vhost-net) vhost_net="yes"
   ;;
+  --disable-smartcard) smartcard="no"
+  ;;
+  --enable-smartcard) smartcard="yes"
+  ;;
   --*dir)
   ;;
   *) echo "ERROR: unknown option $opt"; show_help="yes"
@@ -934,6 +939,8 @@ echo "  --trace-file=NAME        Full PATH,NAME of file to store traces"
 echo "                           Default:trace-<pid>"
 echo "  --disable-spice          disable spice"
 echo "  --enable-spice           enable spice"
+echo "  --disable-smartcard      disable smartcard support"
+echo "  --enable-smartcard       enable smartcard support"
 echo ""
 echo "NOTE: The object files are built at the place where configure is launched"
 exit 1
@@ -2338,6 +2345,7 @@ echo "vhost-net support $vhost_net"
 echo "Trace backend     $trace_backend"
 echo "Trace output file $trace_file-<pid>"
 echo "spice support     $spice"
+echo "smartcard support $smartcard"
 
 if test $sdl_too_old = "yes"; then
 echo "-> Your SDL version is too old - please upgrade to have SDL support"
@@ -2601,6 +2609,10 @@ if test "$spice" = "yes" ; then
   echo "CONFIG_SPICE=y" >> $config_host_mak
 fi
 
+if test "$smartcard" = "yes" ; then
+  echo "CONFIG_SMARTCARD=y" >> $config_host_mak
+fi
+
 # XXX: suppress that
 if [ "$bsd" = "yes" ] ; then
   echo "CONFIG_BSD=y" >> $config_host_mak
diff --git a/hw/ccid.h b/hw/ccid.h
new file mode 100644
index 0000000..a38f971
--- /dev/null
+++ b/hw/ccid.h
@@ -0,0 +1,34 @@
+#ifndef __CCID_H__
+#define __CCID_H__
+
+#include "qdev.h"
+
+typedef struct CCIDCardState CCIDCardState;
+typedef struct CCIDCardInfo CCIDCardInfo;
+
+struct CCIDCardState {
+    DeviceState qdev;
+};
+
+struct CCIDCardInfo {
+    DeviceInfo qdev;
+    void (*print)(Monitor *mon, CCIDCardState *card, int indent);
+    const uint8_t *(*get_atr)(CCIDCardState *card, uint32_t *len);
+    void (*apdu_from_guest)(CCIDCardState *card, const uint8_t *apdu, uint32_t len);
+    int (*exitfn)(CCIDCardState *card);
+    int (*initfn)(CCIDCardState *card);
+};
+
+void ccid_card_send_apdu_to_guest(CCIDCardState *card, uint8_t* apdu, uint32_t len);
+void ccid_card_card_removed(CCIDCardState *card);
+void ccid_card_card_inserted(CCIDCardState *card);
+void ccid_card_card_error(CCIDCardState *card, uint64_t error);
+void ccid_card_qdev_register(CCIDCardInfo *card);
+
+/* support guest visible insertion/removal of ccid devices based on actual
+ * devices connected/removed. Called by card implementation (passthru, local) */
+int ccid_card_ccid_attach(CCIDCardState *card);
+void ccid_card_ccid_detach(CCIDCardState *card);
+
+#endif // __CCID_H__
+
diff --git a/hw/usb-ccid.c b/hw/usb-ccid.c
new file mode 100644
index 0000000..157405a
--- /dev/null
+++ b/hw/usb-ccid.c
@@ -0,0 +1,1346 @@
+/*
+ * CCID Device emulation
+ *
+ * Based on usb-serial.c:
+ * Copyright (c) 2006 CodeSourcery.
+ * Copyright (c) 2008 Samuel Thibault <samuel.thibault@ens-lyon.org>
+ * Written by Paul Brook, reused for FTDI by Samuel Thibault,
+ * Reused for CCID by Alon Levy.
+ * Contributed to by Robert Relyea
+ * Copyright (c) 2010 Red Hat.
+ *
+ * This code is licenced under the LGPL.
+ */
+
+/* References:
+ *
+ * CCID Specification Revision 1.1 April 22nd 2005
+ *  "Universal Serial Bus, Device Class: Smart Card"
+ *  Specification for Integrated Circuit(s) Cards Interface Devices
+ *
+ * KNOWN BUGS
+ * 1. remove/insert can sometimes result in removed state instead of inserted.
+ * This is a result of the following:
+ *  symptom: dmesg shows ERMOTEIO (-121), pcscd shows -99. Thsi happens
+ *  when we send a too short packet, seen in uhci-usb.c, resulting from
+ *  a urb requesting SPD and us returning a smaller packet.
+ *  Not sure which messages trigger this.
+ *
+ */
+
+#include "qemu-common.h"
+#include "qemu-error.h"
+#include "usb.h"
+#include "monitor.h"
+
+#include "hw/ccid.h"
+
+//#define DEBUG_CCID
+
+#define DPRINTF(s, lvl, fmt, ...) \
+do { if (lvl <= s->debug) { printf("usb-ccid: " fmt , ## __VA_ARGS__); } } while (0)
+
+#define CCID_DEV_NAME "usb-ccid"
+
+/* The two options for variable sized buffers:
+ * make them constant size, for large enough constant,
+ * or handle the migration complexity - VMState doesn't handle this case.
+ * sizes are expected never to be exceeded, unless client misbehaves. */
+#define BULK_OUT_DATA_SIZE 65536
+#define PENDING_ANSWERS_NUM 128
+
+#define BULK_IN_BUF_SIZE 384
+#define BULK_IN_PENDING_NUM 8
+
+#define InterfaceOutClass    ((USB_DIR_OUT|USB_TYPE_CLASS|USB_RECIP_INTERFACE)<<8)
+#define InterfaceInClass     ((USB_DIR_IN |USB_TYPE_CLASS|USB_RECIP_INTERFACE)<<8)
+
+#define CCID_CONTROL_ABORT                  0x1
+#define CCID_CONTROL_GET_CLOCK_FREQUENCIES  0x2
+#define CCID_CONTROL_GET_DATA_RATES         0x3
+
+#define CCID_PRODUCT_DESCRIPTION        "QEMU USB CCID"
+#define CCID_VENDOR_DESCRIPTION         "QEMU " QEMU_VERSION
+#define CCID_INTERFACE_NAME             "CCID Interface"
+#define CCID_SERIAL_NUMBER_STRING       "1"
+/* Using Gemplus Vendor and Product id
+  Effect on various drivers:
+  * usbccid.sys (winxp, others untested) is a class driver so it doesn't care.
+  * linux has a number of class drivers, but openct filters based on
+    vendor/product (/etc/openct.conf under fedora), hence Gemplus.
+ */
+#define CCID_VENDOR_ID                  0x08e6
+#define CCID_PRODUCT_ID                 0x4433
+#define CCID_DEVICE_VERSION             0x0000
+
+/* BULK_OUT messages from PC to Reader
+   Defined in CCID Rev 1.1 6.1 (page 26)
+ */
+#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn              0x62
+#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff             0x63
+#define CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus           0x65
+#define CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock                0x6f
+#define CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters           0x6c
+#define CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters         0x6d
+#define CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters           0x61
+#define CCID_MESSAGE_TYPE_PC_to_RDR_Escape                  0x6b
+#define CCID_MESSAGE_TYPE_PC_to_RDR_IccClock                0x6e
+#define CCID_MESSAGE_TYPE_PC_to_RDR_T0APDU                  0x6a
+#define CCID_MESSAGE_TYPE_PC_to_RDR_Secure                  0x69
+#define CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical              0x71
+#define CCID_MESSAGE_TYPE_PC_to_RDR_Abort                   0x72
+#define CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency 0x73
+
+/* BULK_IN messages from Reader to PC
+   Defined in CCID Rev 1.1 6.2 (page 48)
+ */
+#define CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock               0x80
+#define CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus              0x81
+#define CCID_MESSAGE_TYPE_RDR_to_PC_Parameters              0x82
+#define CCID_MESSAGE_TYPE_RDR_to_PC_Escape                  0x83
+#define CCID_MESSAGE_TYPE_RDR_to_PC_DataRateAndClockFrequency 0x84
+
+/* INTERRUPT_IN messages from Reader to PC
+   Defined in CCID Rev 1.1 6.3 (page 56)
+ */
+#define CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange        0x50
+#define CCID_MESSAGE_TYPE_RDR_to_PC_HardwareError           0x51
+
+/* Endpoints for CCID - addresses are up to us to decide.
+   To support slot insertion and removal we must have an interrupt in ep
+   in addition we need a bulk in and bulk out ep
+   5.2, page 20
+ */
+#define CCID_INT_IN_EP       1
+#define CCID_BULK_IN_EP      2
+#define CCID_BULK_OUT_EP     3
+
+/* bmSlotICCState masks */
+#define SLOT_0_STATE_MASK    1
+#define SLOT_0_CHANGED_MASK  2
+
+/* Status codes that go in bStatus (see 6.2.6) */
+enum {
+    ICC_STATUS_PRESENT_ACTIVE = 0,
+    ICC_STATUS_PRESENT_INACTIVE,
+    ICC_STATUS_NOT_PRESENT
+};
+
+enum {
+    COMMAND_STATUS_NO_ERROR = 0,
+    COMMAND_STATUS_FAILED,
+    COMMAND_STATUS_TIME_EXTENSION_REQUIRED
+};
+
+/* Error codes that go in bError (see 6.2.6)
+ */
+enum {
+    ERROR_CMD_NOT_SUPPORTED = 0,
+    ERROR_CMD_ABORTED       = -1,
+    ERROR_ICC_MUTE          = -2,
+    ERROR_XFR_PARITY_ERROR  = -3,
+    ERROR_XFR_OVERRUN       = -4,
+    ERROR_HW_ERROR          = -5,
+};
+
+/* 6.2.6 RDR_to_PC_SlotStatus definitions */
+enum {
+    CLOCK_STATUS_RUNNING = 0,
+    /* 0 - Clock Running, 1 - Clock stopped in State L, 2 - H,
+       3 - unkonwn state. rest are RFU
+     */
+};
+
+typedef struct __attribute__ ((__packed__)) {
+    uint8_t     bMessageType;
+    uint32_t    dwLength;
+    uint8_t     bSlot;
+    uint8_t     bSeq;
+} CCID_Header;
+
+typedef struct __attribute__ ((__packed__)) {
+    CCID_Header hdr;
+    uint8_t     bStatus;        /* Only used in BULK_IN */
+    uint8_t     bError;         /* Only used in BULK_IN */
+} CCID_BULK_IN;
+
+typedef struct __attribute__ ((__packed__)) {
+    CCID_BULK_IN b;
+    uint8_t     bClockStatus;
+} CCID_SlotStatus;
+
+typedef struct __attribute__ ((__packed__)) {
+    CCID_BULK_IN b;
+    uint8_t     bProtocolNum;
+    uint8_t     abProtocolDataStructure[0];
+} CCID_Parameter;
+
+typedef struct __attribute__ ((__packed__)) {
+    CCID_BULK_IN b;
+    uint8_t      bChainParameter;
+    uint8_t      abData[0];
+} CCID_DataBlock;
+
+/* 6.1.4 PC_to_RDR_XfrBlock */
+typedef struct __attribute__ ((__packed__)) {
+    CCID_Header  hdr;
+    uint8_t      bBWI; /* Block Waiting Timeout */
+    uint16_t     wLevelParameter;
+    uint8_t      abData[0];
+} CCID_XferBlock;
+
+typedef struct __attribute__ ((__packed__)) {
+    CCID_Header hdr;
+    uint8_t     bPowerSelect;
+    uint16_t    abRFU;
+} CCID_IccPowerOn;
+
+typedef struct __attribute__ ((__packed__)) {
+    CCID_Header hdr;
+    uint16_t    abRFU;
+} CCID_IccPowerOff;
+
+typedef struct __attribute__ ((__packed__)) {
+    CCID_Header hdr;
+    uint8_t     bProtocolNum;
+    uint8_t    abProtocolDataStructure[0];
+} CCID_SetParameter;
+
+typedef struct {
+    uint8_t     bMessageType; /* CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange */
+    uint8_t     bmSlotICCState;
+} CCID_Notify_Slot_Change;
+
+/* used for DataBlock response to XferBlock */
+typedef struct answer_t {
+    uint8_t slot;
+    uint8_t seq;
+} answer_t;
+
+/* pending BULK_IN messages */
+typedef struct bulk_in_t {
+    uint8_t  data[BULK_IN_BUF_SIZE];
+    uint32_t len;
+    uint32_t pos;
+} bulk_in_t;
+
+enum {
+    MIGRATION_NONE,
+    MIGRATION_MIGRATED,
+};
+
+typedef struct CCIDBus CCIDBus;
+typedef struct USBCCIDState USBCCIDState;
+
+#define MAX_PROTOCOL_SIZE   7
+
+/**
+ * powered - defaults to true, changed by PowerOn/PowerOff messages
+ */
+struct USBCCIDState {
+    USBDevice dev;
+    CCIDBus *bus;
+    CCIDCardState *card;
+    CCIDCardInfo *cardinfo; /* caching the info pointer */
+    uint8_t  debug;
+    uint8_t  auto_attach;
+    bulk_in_t bulk_in_pending[BULK_IN_PENDING_NUM]; /* circular */
+    uint32_t bulk_in_pending_start;
+    uint32_t bulk_in_pending_end; /* first free */
+    uint32_t bulk_in_pending_num;
+    bulk_in_t *current_bulk_in;
+    uint8_t  bulk_out_data[BULK_OUT_DATA_SIZE];
+    uint32_t bulk_out_pos;
+    uint8_t  bmSlotICCState;
+    uint8_t  powered;
+    uint8_t  notify_slot_change;
+    uint64_t last_answer_error;
+    answer_t pending_answers[PENDING_ANSWERS_NUM];
+    uint32_t pending_answers_start;
+    uint32_t pending_answers_end;
+    uint32_t pending_answers_num;
+    uint8_t  bError;
+    uint8_t  bmCommandStatus;
+    uint8_t  bProtocolNum;
+    uint8_t  abProtocolDataStructure[MAX_PROTOCOL_SIZE];
+    uint32_t ulProtocolDataStructureSize;
+    uint8_t  attached_vmstate;
+    uint32_t state_vmstate;
+    uint8_t  migration_state;
+    uint32_t migration_target_ip;
+    uint16_t migration_target_port;
+};
+
+/* Slot specific variables. We emulate a single slot card reader.
+ */
+
+
+/* CCID Spec chapter 4: CCID uses a standard device descriptor per Chapter 9,
+ * "USB Device Framework", section 9.6.1, in the Universal Serial Bus
+ * Specification.
+ *
+ * This device implemented based on the spec and with an Athena Smart Card
+ * Reader as reference:
+ *   0dc3:1004 Athena Smartcard Solutions, Inc.
+ */
+
+static const uint8_t qemu_ccid_dev_descriptor[] = {
+        0x12,       /*  u8 bLength; */
+        USB_DT_DEVICE, /*  u8 bDescriptorType; Device */
+        0x10, 0x01, /*  u16 bcdUSB; v1.1 */
+
+        0x00,       /*  u8  bDeviceClass; */
+        0x00,       /*  u8  bDeviceSubClass; */
+        0x00,       /*  u8  bDeviceProtocol; [ low/full speeds only ] */
+        0x40,       /*  u8  bMaxPacketSize0; 8 Bytes (valid: 8,16,32,64) */
+
+        /* Vendor and product id are arbitrary.  */
+                    /*  u16 idVendor  */
+        CCID_VENDOR_ID & 0xff, CCID_VENDOR_ID >> 8,
+                    /*  u16 idProduct */
+        CCID_PRODUCT_ID & 0xff, CCID_PRODUCT_ID >> 8,
+                    /*  u16 bcdDevice */
+        CCID_DEVICE_VERSION & 0xff, CCID_DEVICE_VERSION >> 8,
+        0x01,       /*  u8  iManufacturer; */
+        0x02,       /*  u8  iProduct; */
+        0x03,       /*  u8  iSerialNumber; */
+        0x01,       /*  u8  bNumConfigurations; */
+};
+
+static const uint8_t qemu_ccid_config_descriptor[] = {
+
+        /* one configuration */
+        0x09,       /*  u8  bLength; */
+        USB_DT_CONFIG, /*  u8  bDescriptorType; Configuration */
+        0x5d, 0x00, /*  u16 wTotalLength; 9+9+54+7+7+7 */
+        0x01,       /*  u8  bNumInterfaces; (1) */
+        0x01,       /*  u8  bConfigurationValue; */
+        0x00,       /*  u8  iConfiguration; */
+        0xe0,       /*  u8  bmAttributes;
+                                 Bit 7: must be set,
+                                     6: Self-powered,
+                                     5: Remote wakeup,
+                                     4..0: resvd */
+        100/2,      /*  u8  MaxPower; 50 == 100mA */
+
+        /* one interface */
+        0x09,       /*  u8  if_bLength; */
+        USB_DT_INTERFACE, /*  u8  if_bDescriptorType; Interface */
+        0x00,       /*  u8  if_bInterfaceNumber; */
+        0x00,       /*  u8  if_bAlternateSetting; */
+        0x03,       /*  u8  if_bNumEndpoints; */
+        0x0b,       /*  u8  if_bInterfaceClass; Smart Card Device Class */
+        0x00,       /*  u8  if_bInterfaceSubClass; Subclass code */
+        0x00,       /*  u8  if_bInterfaceProtocol; Protocol code */
+        0x04,       /*  u8  if_iInterface; Index of string descriptor */
+
+        /* Smart Card Device Class Descriptor */
+        0x36,       /*  u8  bLength; */
+        0x21,       /*  u8  bDescriptorType; Functional */
+        0x10, 0x01, /*  u16 bcdCCID; CCID Specification Release Number. */
+        0x00,       /*  u8  bMaxSlotIndex; The index of the highest available
+                        slot on this device. All slots are consecutive starting
+                        at 00h. */
+        0x07,       /*  u8  bVoltageSupport; 01h - 5.0v, 02h - 3.0, 03 - 1.8 */
+
+        0x03, 0x00, /*  u32 dwProtocols; RRRR PPPP. RRRR = 0000h.*/
+        0x00, 0x00, /*  PPPP: 0001h = Protocol T=0, 0002h = Protocol T=1 */
+                    /*  u32 dwDefaultClock; in kHZ (0x0fa0 is 4 MHz) */
+        0xa0, 0x0f, 0x00, 0x00,
+                    /*  u32 dwMaximumClock; */
+        0x00, 0x00, 0x01, 0x00,
+        0x00,       /*  u8 bNumClockSupported; 0 means just the default and max. */
+                    /*  u32 dwDataRate ;bps. 9600 == 00002580h */
+        0x80, 0x25, 0x00, 0x00,
+                    /*  u32 dwMaxDataRate ; 11520 bps == 0001C200h */
+        0x00, 0xC2, 0x01, 0x00,
+        0x00,       /*  u8  bNumDataRatesSupported; 00 means all rates between
+                     *      default and max */
+                    /*  u32 dwMaxIFSD; maximum IFSD supported by CCID for protocol
+                     *      T=1 (Maximum seen from various cards) */
+        0xfe, 0x00, 0x00, 0x00,
+                    /*  u32 dwSyncProtocols; 1 - 2-wire, 2 - 3-wire, 4 - I2C */
+        0x00, 0x00, 0x00, 0x00,
+                    /*  u32 dwMechanical;  0 - no special characteristics. */
+        0x00, 0x00, 0x00, 0x00,
+                    /*  u32 dwFeatures;
+                     *  0 - No special characteristics
+                     *  + 2 Automatic parameter configuration based on ATR data
+                     *  + 4 Automatic activation of ICC on inserting
+                     *  + 8 Automatic ICC voltage selection
+                     *  + 10 Automatic ICC clock frequency change
+                     *  + 20 Automatic baud rate change
+                     *  + 40 Automatic parameters negotiation made by the CCID
+                     *  + 80 automatic PPS made by the CCID
+                     *  100 CCID can set ICC in clock stop mode
+                     *  200 NAD value other then 00 accepted (T=1 protocol)
+                     *  + 400 Automatic IFSD exchange as first exchange (T=1)
+                     *  One of the following only:
+                     *  + 10000 TPDU level exchanges with CCID
+                     *  20000 Short APDU level exchange with CCID
+                     *  40000 Short and Extended APDU level exchange with CCID
+                     *
+                     *  + 100000 USB Wake up signaling supported on card insertion
+                     *  and removal. Must set bit 5 in bmAttributes in Configuration
+                     *  descriptor if 100000 is set.*/
+        0xfe, 0x04, 0x11, 0x00,
+                    /*  u32 dwMaxCCIDMessageLength; For extended APDU in [261 + 10
+                     *  , 65544 + 10]. Otherwise the minimum is wMaxPacketSize of
+                     *  the Bulk-OUT endpoint */
+        0x12, 0x00, 0x01, 0x00,
+        0xFF,       /*  u8  bClassGetResponse; Significant only for CCID that
+                     *  offers an APDU level for exchanges. Indicates the default
+                     *  class value used by the CCID when it sends a Get Response
+                     *  command to perform the transportation of an APDU by T=0
+                     *  protocol
+                     *  FFh indicates that the CCID echos the class of the APDU.
+                     */
+        0xFF,       /*  u8  bClassEnvelope; EAPDU only. Envelope command for T=0 */
+        0x00, 0x00, /*  u16 wLcdLayout; XXYY Number of lines (XX) and chars per
+                     *  line for LCD display used for PIN entry. 0000 - no LCD */
+        0x01,       /*  u8  bPINSupport; 01h PIN Verification,
+                     *                   02h PIN Modification */
+        0x01,       /*  u8  bMaxCCIDBusySlots; */
+
+        /* Interrupt-IN endpoint */
+        0x07,       /*  u8  ep_bLength; */
+                    /*  u8  ep_bDescriptorType; Endpoint */
+        USB_DT_ENDPOINT,
+                    /*  u8  ep_bEndpointAddress; IN Endpoint 1 */
+        0x80 | CCID_INT_IN_EP,
+        0x03,       /*  u8  ep_bmAttributes; Interrupt */
+        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
+        0xff,       /*  u8  ep_bInterval; */
+
+        /* Bulk-In endpoint */
+        0x07,       /*  u8  ep_bLength; */
+                    /*  u8  ep_bDescriptorType; Endpoint */
+        USB_DT_ENDPOINT,
+                    /*  u8  ep_bEndpointAddress; IN Endpoint 2 */
+        0x80 | CCID_BULK_IN_EP,
+        0x02,       /*  u8  ep_bmAttributes; Bulk */
+        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
+        0x00,       /*  u8  ep_bInterval; */
+
+        /* Bulk-Out endpoint */
+        0x07,       /*  u8  ep_bLength; */
+                    /*  u8  ep_bDescriptorType; Endpoint */
+        USB_DT_ENDPOINT,
+                    /*  u8  ep_bEndpointAddress; OUT Endpoint 3 */
+        CCID_BULK_OUT_EP,
+        0x02,       /*  u8  ep_bmAttributes; Bulk */
+        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
+        0x00,       /*  u8  ep_bInterval; */
+
+};
+
+static bool ccid_has_pending_answers(USBCCIDState *s)
+{
+    return s->pending_answers_num > 0;
+}
+
+static void ccid_clear_pending_answers(USBCCIDState *s)
+{
+    s->pending_answers_num = 0;
+    s->pending_answers_start = 0;
+    s->pending_answers_end = 0;
+}
+
+static void ccid_print_pending_answers(USBCCIDState *s)
+{
+#ifdef DEBUG_CCID
+    answer_t *answer;
+    int i, count;
+
+    printf("usb-ccid: pending answers:");
+    if (!ccid_has_pending_answers(s)) {
+        printf(" empty\n");
+        return;
+    }
+    for (i = s->pending_answers_start, count=s->pending_answers_num ;
+         count > 0; count--, i++) {
+        answer = &s->pending_answers[i % PENDING_ANSWERS_NUM];
+        if (count == 1) {
+            printf("%d:%d\n", answer->slot, answer->seq);
+        } else {
+            printf("%d:%d,", answer->slot, answer->seq);
+        }
+    }
+#endif
+}
+
+static void ccid_add_pending_answer(USBCCIDState *s, CCID_Header *hdr)
+{
+    answer_t* answer;
+
+    assert(s->pending_answers_num++ < PENDING_ANSWERS_NUM);
+    answer = &s->pending_answers[(s->pending_answers_end++) % PENDING_ANSWERS_NUM];
+    answer->slot = hdr->bSlot;
+    answer->seq = hdr->bSeq;
+    ccid_print_pending_answers(s);
+}
+
+static void ccid_remove_pending_answer(USBCCIDState *s,
+    uint8_t *slot, uint8_t *seq)
+{
+    answer_t *answer;
+
+    assert(s->pending_answers_num-- > 0);
+    answer = &s->pending_answers[(s->pending_answers_start++) % PENDING_ANSWERS_NUM];
+    *slot = answer->slot;
+    *seq = answer->seq;
+    ccid_print_pending_answers(s);
+}
+
+static void ccid_bulk_in_clear(USBCCIDState *s)
+{
+    s->bulk_in_pending_start = 0;
+    s->bulk_in_pending_end = 0;
+    s->bulk_in_pending_num = 0;
+}
+
+static void ccid_bulk_in_release(USBCCIDState *s)
+{
+    assert(s->current_bulk_in != NULL);
+    s->current_bulk_in->pos = 0;
+    s->current_bulk_in = NULL;
+}
+
+static void ccid_bulk_in_get(USBCCIDState *s)
+{
+    if (s->current_bulk_in != NULL || s->bulk_in_pending_num == 0) {
+        return;
+    }
+    assert(s->bulk_in_pending_num > 0);
+    s->bulk_in_pending_num--;
+    s->current_bulk_in = &s->bulk_in_pending[
+        (s->bulk_in_pending_start++) % BULK_IN_PENDING_NUM];
+}
+
+static uint8_t* ccid_reserve_recv_buf(USBCCIDState* s, uint16_t len)
+{
+    bulk_in_t* bulk_in;
+
+    DPRINTF(s, 4, "%s: QUEUE: reserve %d bytes\n", __func__, len);
+
+    /* look for an existing element */
+    if (len > BULK_IN_BUF_SIZE) {
+        printf("usb-ccid.c: %s: len larger then max (%d>%d). bailing out.\n",
+            __func__, len, BULK_IN_BUF_SIZE);
+        exit(-1);
+    }
+    if (s->bulk_in_pending_num >= BULK_IN_PENDING_NUM) {
+        printf("usb-ccid.c: %s: No free bulk_in buffers. discarding message.\n",
+                __func__);
+        return NULL;
+    }
+    bulk_in = &s->bulk_in_pending[(s->bulk_in_pending_end++) % BULK_IN_PENDING_NUM];
+    s->bulk_in_pending_num++;
+    bulk_in->len = len;
+    return bulk_in->data;
+}
+
+static void ccid_reset(USBCCIDState *s)
+{
+    ccid_bulk_in_clear(s);
+    ccid_clear_pending_answers(s);
+}
+
+static void ccid_detach(USBCCIDState *s)
+{
+    ccid_reset(s);
+    if (s->auto_attach == 0 && s->dev.attached) {
+        usb_device_detach(&s->dev);
+    }
+}
+
+static void ccid_handle_reset(USBDevice *dev)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
+
+    DPRINTF(s, 1, "Reset\n");
+
+    ccid_reset(s);
+}
+
+static int ccid_handle_control(USBDevice *dev, int request, int value,
+                                  int index, int length, uint8_t *data)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
+    int ret = 0;
+
+    DPRINTF(s, 1, "got control %x, value %x\n",request, value);
+    switch (request) {
+    case DeviceRequest | USB_REQ_GET_STATUS:
+        data[0] = (0 << USB_DEVICE_SELF_POWERED) |
+            (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);
+        data[1] = 0x00;
+        ret = 2;
+        break;
+    case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
+        if (value == USB_DEVICE_REMOTE_WAKEUP) {
+            dev->remote_wakeup = 0;
+        } else {
+            goto fail;
+        }
+        ret = 0;
+        break;
+    case DeviceOutRequest | USB_REQ_SET_FEATURE:
+        if (value == USB_DEVICE_REMOTE_WAKEUP) {
+            dev->remote_wakeup = 1;
+        } else {
+            goto fail;
+        }
+        ret = 0;
+        break;
+    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
+        dev->addr = value;
+        ret = 0;
+        break;
+    case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
+        switch(value >> 8) {
+        case USB_DT_DEVICE:
+            memcpy(data, qemu_ccid_dev_descriptor,
+                   sizeof(qemu_ccid_dev_descriptor));
+            ret = sizeof(qemu_ccid_dev_descriptor);
+            break;
+        case USB_DT_CONFIG:
+            memcpy(data, qemu_ccid_config_descriptor,
+                   sizeof(qemu_ccid_config_descriptor));
+            ret = sizeof(qemu_ccid_config_descriptor);
+            break;
+        case USB_DT_STRING:
+            switch(value & 0xff) {
+            case 0:
+                /* language ids */
+                data[0] = 4;
+                data[1] = 3;
+                data[2] = 0x09;
+                data[3] = 0x04;
+                ret = 4;
+                break;
+            case 1:
+                /* vendor description */
+                ret = set_usb_string(data, CCID_VENDOR_DESCRIPTION);
+                break;
+            case 2:
+                /* product description */
+                ret = set_usb_string(data, CCID_PRODUCT_DESCRIPTION);
+                break;
+            case 3:
+                /* serial number */
+                ret = set_usb_string(data, CCID_SERIAL_NUMBER_STRING);
+                break;
+            case 4:
+                /* interface name */
+                ret = set_usb_string(data, CCID_INTERFACE_NAME);
+                break;
+            default:
+                goto fail;
+            }
+            break;
+        default:
+            goto fail;
+        }
+        break;
+    case DeviceRequest | USB_REQ_GET_CONFIGURATION:
+        data[0] = 1;
+        ret = 1;
+        break;
+    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
+        /* Only one configuration - we just ignore the request */
+        ret = 0;
+        break;
+    case DeviceRequest | USB_REQ_GET_INTERFACE:
+        data[0] = 0;
+        ret = 1;
+        break;
+    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
+        ret = 0;
+        break;
+    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
+        ret = 0;
+        break;
+
+        /* Class specific requests.  */
+    case InterfaceOutClass | CCID_CONTROL_ABORT:
+        DPRINTF(s, 1, "ccid_control abort UNIMPLEMENTED\n");
+        ret = USB_RET_STALL;
+        break;
+    case InterfaceInClass | CCID_CONTROL_GET_CLOCK_FREQUENCIES:
+        DPRINTF(s, 1, "ccid_control get clock frequencies UNIMPLEMENTED\n");
+        ret = USB_RET_STALL;
+        break;
+    case InterfaceInClass | CCID_CONTROL_GET_DATA_RATES:
+        DPRINTF(s, 1, "ccid_control get data rates UNIMPLEMENTED\n");
+        ret = USB_RET_STALL;
+        break;
+    default:
+    fail:
+        DPRINTF(s, 1, "got unsupported/bogus control %x, value %x\n", request, value);
+        ret = USB_RET_STALL;
+        break;
+    }
+    return ret;
+}
+
+static bool ccid_card_inserted(USBCCIDState *s)
+{
+    return s->bmSlotICCState & SLOT_0_STATE_MASK;
+}
+
+static uint8_t ccid_card_status(USBCCIDState *s)
+{
+    return ccid_card_inserted(s)
+            ? (s->powered ?
+                ICC_STATUS_PRESENT_ACTIVE
+              : ICC_STATUS_PRESENT_INACTIVE
+              )
+            : ICC_STATUS_NOT_PRESENT;
+}
+
+static uint8_t ccid_calc_status(USBCCIDState *s)
+{
+    /* page 55, 6.2.6, calculation of bStatus from bmICCStatus and
+       bmCommandStatus
+     */
+    uint8_t ret = ccid_card_status(s) | (s->bmCommandStatus << 6);
+    DPRINTF(s, 4, "status = %d\n", ret);
+    return ret;
+}
+
+static void ccid_reset_error_status(USBCCIDState* s)
+{
+    s->bError = ERROR_CMD_NOT_SUPPORTED;
+    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
+}
+
+static void ccid_write_slot_status(USBCCIDState* s, CCID_Header* recv)
+{
+    CCID_SlotStatus *h = (CCID_SlotStatus*)ccid_reserve_recv_buf(s, sizeof(CCID_SlotStatus));
+    if (h == NULL) {
+        return;
+    }
+    h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus;
+    h->b.hdr.dwLength = 0;
+    h->b.hdr.bSlot = recv->bSlot;
+    h->b.hdr.bSeq = recv->bSeq;
+    h->b.bStatus = ccid_calc_status(s);
+    h->b.bError = s->bError;
+    h->bClockStatus = CLOCK_STATUS_RUNNING;
+    ccid_reset_error_status(s);
+}
+
+static void ccid_write_parameters(USBCCIDState* s, CCID_Header* recv)
+{
+    CCID_Parameter *h;
+    uint32_t len = s->ulProtocolDataStructureSize;
+
+    h = (CCID_Parameter *)ccid_reserve_recv_buf(s, sizeof(CCID_Parameter) + len);
+    if (h == NULL) {
+        return;
+    }
+    h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_Parameters;
+    h->b.hdr.dwLength = 0;
+    h->b.hdr.bSlot = recv->bSlot;
+    h->b.hdr.bSeq = recv->bSeq;
+    h->b.bStatus = ccid_calc_status(s);
+    h->b.bError = s->bError;
+    h->bProtocolNum = s->bProtocolNum;
+    memcpy(h->abProtocolDataStructure, s->abProtocolDataStructure, len);
+    ccid_reset_error_status(s);
+}
+
+static void ccid_write_data_block(
+    USBCCIDState* s, uint8_t slot, uint8_t seq,
+    const uint8_t* data, uint32_t len)
+{
+    CCID_DataBlock *p;
+
+    p = (CCID_DataBlock*)ccid_reserve_recv_buf(s, sizeof(*p) + len);
+    if (p == NULL) {
+        return;
+    }
+    p->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock;
+    p->b.hdr.dwLength = len;
+    p->b.hdr.bSlot = slot;
+    p->b.hdr.bSeq = seq;
+    p->b.bStatus = ccid_calc_status(s);
+    p->b.bError = s->bError;
+#ifdef DEBUG_CCID
+    if (p->b.bError) {
+        DPRINTF(s, 4, "error %d", p->b.bError);
+    }
+#endif
+    memcpy(p->abData, data, len);
+    ccid_reset_error_status(s);
+}
+
+static void ccid_write_data_block_answer(USBCCIDState* s,
+    const uint8_t* data, uint32_t len)
+{
+    uint8_t seq;
+    uint8_t slot;
+
+    if (!ccid_has_pending_answers(s)) {
+        abort();
+    }
+    ccid_remove_pending_answer(s, &slot, &seq);
+    ccid_write_data_block(s, slot, seq, data, len);
+}
+
+static void ccid_write_data_block_atr(USBCCIDState* s, CCID_Header* recv)
+{
+    const uint8_t *atr = NULL;
+    uint32_t len = 0;
+
+    if (s->card) {
+        atr = s->cardinfo->get_atr(s->card, &len);
+    }
+    ccid_write_data_block(s, recv->bSlot, recv->bSeq, atr, len);
+}
+
+static void ccid_set_parameters(USBCCIDState *s, CCID_Header *recv)
+{
+    CCID_SetParameter *ph = (CCID_SetParameter *) recv;
+    uint32_t len = 0;
+    if (ph->bProtocolNum == 0) {
+        len = 5;
+    }
+    if (ph->bProtocolNum == 1) {
+        len = 7;
+    }
+    if (len == 0) {
+        s->bmCommandStatus = COMMAND_STATUS_FAILED;
+        s->bError = 7; /* Protocol invalid or not supported */
+        return;
+    }
+    s->bProtocolNum = ph->bProtocolNum;
+    memcpy(s->abProtocolDataStructure, ph->abProtocolDataStructure, len);
+    s->ulProtocolDataStructureSize = len;
+    DPRINTF(s, 1, "%s: using len %d\n", __func__, len);
+}
+
+/* must be 5 bytes for T=0, 7 bytes for T=1
+ * See page 52 */
+static const uint8_t abDefaultProtocolDataStructure[7] =
+    { 0x77, 0x00, 0x00, 0x00, 0x00, 0xfe /*IFSC*/, 0x00 /*NAD*/ };
+
+static void ccid_reset_parameters(USBCCIDState *s)
+{
+   uint32_t len = sizeof(abDefaultProtocolDataStructure);
+
+   s->bProtocolNum = 1; /* T=1 */
+   s->ulProtocolDataStructureSize = len;
+   memcpy(s->abProtocolDataStructure, abDefaultProtocolDataStructure, len);
+}
+
+static void ccid_report_error_failed(USBCCIDState *s, uint8_t error)
+{
+    s->bmCommandStatus = COMMAND_STATUS_FAILED;
+    s->bError = error;
+}
+
+/* NOTE: only a single slot is supported (SLOT_0)
+ */
+static void ccid_on_slot_change(USBCCIDState* s, bool full)
+{
+    /* RDR_to_PC_NotifySlotChange, 6.3.1 page 56
+     */
+    uint8_t current = s->bmSlotICCState;
+    if (full) {
+        s->bmSlotICCState |= SLOT_0_STATE_MASK;
+    } else {
+        s->bmSlotICCState &= ~SLOT_0_STATE_MASK;
+    }
+    if (current != s->bmSlotICCState) {
+        s->bmSlotICCState |= SLOT_0_CHANGED_MASK;
+    }
+    s->notify_slot_change = true;
+}
+
+static void ccid_write_data_block_error(
+    USBCCIDState *s, uint8_t slot, uint8_t seq)
+{
+    ccid_write_data_block(s, slot, seq, NULL, 0);
+}
+
+static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
+{
+    if (ccid_card_status(s) != ICC_STATUS_PRESENT_ACTIVE) {
+        DPRINTF(s, 1, "usb-ccid: not sending apdu to client, no card connected\n");
+        ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);
+        return;
+    }
+    DPRINTF(s, 1, "%s: seq %d, len %d\n", __FUNCTION__,
+                recv->hdr.bSeq, recv->hdr.dwLength);
+    ccid_add_pending_answer(s, (CCID_Header*)recv);
+    if (s->card) {
+        s->cardinfo->apdu_from_guest(s->card, recv->abData, recv->hdr.dwLength);
+    } else {
+        printf("warning: discarded apdu\n");
+    }
+}
+
+static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
+{
+    CCID_Header* ccid_header;
+
+    assert(p->len + s->bulk_out_pos <= BULK_OUT_DATA_SIZE);
+    ccid_header = (CCID_Header*)s->bulk_out_data;
+    memcpy(s->bulk_out_data + s->bulk_out_pos, p->data, p->len);
+    s->bulk_out_pos += p->len;
+    if (p->len == 64) {
+        DPRINTF(s, 4, "usb-ccid: bulk_in: expecting more packets (%d/%d)\n",
+            p->len, ccid_header->dwLength);
+        return;
+    }
+    if (s->bulk_out_pos < 10) {
+        DPRINTF(s, 1, "%s: bad USB_TOKEN_OUT length, should be at least 10 bytes\n", __func__);
+    } else {
+        DPRINTF(s, 3, "%s %x\n", __func__, ccid_header->bMessageType);
+        switch (ccid_header->bMessageType) {
+            case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus:
+                ccid_write_slot_status(s, ccid_header);
+                break;
+            case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:
+                DPRINTF(s, 1, "PowerOn: %d\n",
+                    ((CCID_IccPowerOn*)(ccid_header))->bPowerSelect);
+                s->powered = true;
+                if (!ccid_card_inserted(s)) {
+                    ccid_report_error_failed(s, ERROR_ICC_MUTE);
+                }
+                /* atr is written regardless of error. */
+                ccid_write_data_block_atr(s, ccid_header);
+                break;
+            case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff:
+                DPRINTF(s, 1, "PowerOff\n");
+                ccid_reset_error_status(s);
+                s->powered = false;
+                ccid_write_slot_status(s, ccid_header);
+                break;
+            case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:
+                ccid_on_apdu_from_guest(s, (CCID_XferBlock*)s->bulk_out_data);
+                break;
+            case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters:
+                ccid_reset_error_status(s);
+                ccid_set_parameters(s, ccid_header);
+                ccid_write_parameters(s, ccid_header);
+                break;
+            case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters:
+                ccid_reset_error_status(s);
+                ccid_reset_parameters(s);
+                ccid_write_parameters(s, ccid_header);
+                break;
+            case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters:
+                ccid_reset_error_status(s);
+                ccid_write_parameters(s, ccid_header);
+                break;
+            default:
+                DPRINTF(s, 1, "handle_data: ERROR: unhandled message type %Xh\n",
+                    ccid_header->bMessageType);
+                /* the caller is expecting the device to respond, tell it we
+                 * do't support the operation */
+                ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
+                ccid_write_slot_status(s, ccid_header);
+                break;
+        }
+    }
+    s->bulk_out_pos = 0;
+}
+
+static int ccid_bulk_in_copy_out(USBCCIDState *s, uint8_t *data, int len)
+{
+    int ret = 0;
+
+    assert(len>0);
+    ccid_bulk_in_get(s);
+    if (s->current_bulk_in != NULL) {
+        ret = MIN(s->current_bulk_in->len - s->current_bulk_in->pos, len);
+        memcpy(data, s->current_bulk_in->data + s->current_bulk_in->pos, ret);
+        s->current_bulk_in->pos += ret;
+        if (s->current_bulk_in->pos == s->current_bulk_in->len) {
+            ccid_bulk_in_release(s);
+        }
+    } else {
+        ret = USB_RET_NAK; /* return when device has no data - usb 2.0 spec Table 8-4 */
+    }
+    if (ret > 0) {
+        DPRINTF(s, 3, "%s: %d/%d req/act to guest (BULK_IN)\n", __func__, len, ret);
+    }
+    if (ret != USB_RET_NAK && ret < len) {
+        DPRINTF(s, 1, "%s: returning short (EREMOTEIO) %d < %d\n", __func__, ret, len);
+    }
+    return ret;
+}
+
+static int ccid_handle_data(USBDevice *dev, USBPacket *p)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
+    int ret = 0;
+    uint8_t *data = p->data;
+    int len = p->len;
+
+    switch (p->pid) {
+    case USB_TOKEN_OUT:
+        ccid_handle_bulk_out(s, p);
+        break;
+
+    case USB_TOKEN_IN:
+        switch (p->devep & 0xf) {
+            case CCID_BULK_IN_EP:
+                if (!len) {
+                    ret = USB_RET_NAK;
+                } else {
+                    ret = ccid_bulk_in_copy_out(s, data, len);
+                }
+                break;
+            case CCID_INT_IN_EP:
+                if (s->notify_slot_change) {
+                    /* page 56, RDR_to_PC_NotifySlotChange */
+                    data[0] = CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange;
+                    data[1] = s->bmSlotICCState;
+                    ret = 2;
+                    s->notify_slot_change = false;
+                    s->bmSlotICCState &= ~SLOT_0_CHANGED_MASK;
+                    DPRINTF(s, 2, "handle_data: int_in: notify_slot_change %X, requested len %d\n",
+                            s->bmSlotICCState, len);
+                }
+                break;
+            default:
+                DPRINTF(s, 1, "Bad endpoint\n");
+                break;
+        }
+        break;
+    default:
+        DPRINTF(s, 1, "Bad token\n");
+        ret = USB_RET_STALL;
+        break;
+    }
+
+    return ret;
+}
+
+static void ccid_handle_destroy(USBDevice *dev)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
+
+    ccid_bulk_in_clear(s);
+}
+
+static void ccid_flush_pending_answers(USBCCIDState *s) {
+    while (ccid_has_pending_answers(s)) {
+        ccid_write_data_block_answer(s, NULL, 0);
+    }
+}
+
+static answer_t *ccid_peek_next_answer(USBCCIDState *s)
+{
+    return s->pending_answers_num == 0
+        ? NULL
+        : &s->pending_answers[s->pending_answers_start % PENDING_ANSWERS_NUM];
+}
+
+static void ccid_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent)
+{
+    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
+    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, qdev->info);
+
+    if (info->print) {
+        info->print(mon, card, indent);
+    }
+}
+
+struct CCIDBus {
+    BusState qbus;
+};
+
+static struct BusInfo ccid_bus_info = {
+    .name = "ccid-bus",
+    .size = sizeof(CCIDBus),
+    .print_dev = ccid_bus_dev_print,
+};
+
+static CCIDBus *ccid_bus_new(DeviceState *dev)
+{
+    CCIDBus *bus;
+
+    bus = FROM_QBUS(CCIDBus, qbus_create(&ccid_bus_info, dev, NULL));
+    bus->qbus.allow_hotplug = 1;
+
+    return bus;
+}
+
+void ccid_card_send_apdu_to_guest(CCIDCardState *card, uint8_t* apdu, uint32_t len)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
+    answer_t *answer;
+
+    if (!ccid_has_pending_answers(s)) {
+        DPRINTF(s, 1, "CCID ERROR: got an APDU without pending answers\n");
+        return;
+    }
+    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
+    answer = ccid_peek_next_answer(s);
+    if (answer == NULL) {
+        abort();
+    }
+    DPRINTF(s, 1, "APDU returned to guest %d (answer seq %d, slot %d)\n",
+        len, answer->seq, answer->slot);
+    ccid_write_data_block_answer(s, apdu, len);
+}
+
+void ccid_card_card_removed(CCIDCardState *card)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
+
+    ccid_on_slot_change(s, false);
+    ccid_flush_pending_answers(s);
+    ccid_reset(s);
+}
+
+int ccid_card_ccid_attach(CCIDCardState *card)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
+
+    DPRINTF(s, 1, "CCID Attach\n");
+    if (s->auto_attach==0 && !s->dev.attached) {
+        usb_device_attach(&s->dev);
+        return 0;
+    } else {
+        if (s->migration_state == MIGRATION_MIGRATED) {
+            s->migration_state = MIGRATION_NONE;
+            return 0;
+        } else {
+            return -1;
+        }
+    }
+}
+
+void ccid_card_ccid_detach(CCIDCardState *card)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
+
+    DPRINTF(s, 1, "CCID Detach\n");
+    if (ccid_card_inserted(s)) {
+        ccid_on_slot_change(s, false);
+    }
+    ccid_detach(s);
+}
+
+void ccid_card_card_error(CCIDCardState *card, uint64_t error)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
+
+    s->bmCommandStatus = COMMAND_STATUS_FAILED;
+    s->last_answer_error = error;
+    DPRINTF(s, 1, "VSC_Error: %lX\n", s->last_answer_error);
+    /* TODO: these error's should be more verbose and propogated to the guest.
+     * */
+    ccid_write_data_block_answer(s, NULL, 0);
+}
+
+void ccid_card_card_inserted(CCIDCardState *card)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
+
+    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
+    ccid_flush_pending_answers(s);
+    ccid_on_slot_change(s, true);
+}
+
+static int ccid_card_exit(DeviceState *qdev)
+{
+    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
+    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, qdev->info);
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
+
+    if (ccid_card_inserted(s)) {
+        ccid_card_card_removed(card);
+    }
+    if (info->exitfn) {
+        return info->exitfn(card);
+    }
+    return 0;
+}
+
+static int ccid_card_init(DeviceState *qdev, DeviceInfo *base)
+{
+    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
+    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, base);
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
+
+    s->card = card;
+    s->cardinfo = info;
+    if (info->initfn) {
+        return info->initfn(card);
+    }
+    return 0;
+}
+
+void ccid_card_qdev_register(CCIDCardInfo *card)
+{
+    card->qdev.bus_info = &ccid_bus_info;
+    card->qdev.init = ccid_card_init;
+    card->qdev.exit = ccid_card_exit;
+    qdev_register(&card->qdev);
+}
+
+static int ccid_initfn(USBDevice *dev)
+{
+    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
+
+    s->bus = ccid_bus_new(&dev->qdev);
+    s->card = NULL;
+    s->cardinfo = NULL;
+    s->migration_state = MIGRATION_NONE;
+    dev->auto_attach = s->auto_attach;
+    s->migration_target_ip = 0;
+    s->migration_target_port = 0;
+    s->dev.speed = USB_SPEED_FULL;
+    s->notify_slot_change = false;
+    s->powered = true;
+    s->pending_answers_num = 0;
+    s->last_answer_error = 0;
+    s->bulk_in_pending_start = 0;
+    s->bulk_in_pending_end = 0;
+    s->current_bulk_in = NULL;
+    ccid_reset_error_status(s);
+    s->bulk_out_pos = 0;
+    ccid_reset_parameters(s);
+    ccid_reset(s);
+    return 0;
+}
+
+static int ccid_post_load(void *opaque, int version_id)
+{
+    USBCCIDState *s = opaque;
+
+    if (s->auto_attach == 0 && s->attached_vmstate && !s->dev.attached) {
+        usb_device_attach(&s->dev);
+    }
+    // This must be done after usb_device_attach, which sets state to ATTACHED,
+    // while it must be DEFAULT in order to accept packets (like it is after
+    // reset, but reset will reset our addr and call our reset handler which
+    // may change state, and we don't want to do that when migrating).
+    s->dev.state = s->state_vmstate;
+    return 0;
+}
+
+static void ccid_pre_save(void *opaque)
+{
+    USBCCIDState *s = opaque;
+
+    s->attached_vmstate = s->dev.attached;
+    s->state_vmstate = s->dev.state;
+    if (s->dev.attached) {
+        // migrating an open device, ignore reconnection CHR_EVENT to avoid an
+        // erronous detach.
+        s->migration_state = MIGRATION_MIGRATED;
+    }
+}
+
+static VMStateDescription bulk_in_t_vmstate = {
+    .name = "bulk_in_t",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_BUFFER(data, bulk_in_t),
+        VMSTATE_UINT32(len, bulk_in_t),
+        VMSTATE_UINT32(pos, bulk_in_t),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static VMStateDescription answer_t_vmstate = {
+    .name = "answer_t",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_UINT8(slot, answer_t),
+        VMSTATE_UINT8(seq, answer_t),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static VMStateDescription usb_device_vmstate = {
+    .name = "usb_device",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        //int speed;
+        VMSTATE_UINT8(addr, USBDevice),
+        //VMSTATE_BUFFER(product_desc, USBDevice), // char, not uint8_t - casting error
+        //int auto_attach;
+        //int attached;
+        //int state;
+        VMSTATE_BUFFER(setup_buf, USBDevice),
+        VMSTATE_BUFFER(data_buf, USBDevice),
+        // int remote_wakeup;
+        // int setup_state;
+        // int setup_len;
+        // int setup_index;
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static VMStateDescription ccid_vmstate = {
+    .name = CCID_DEV_NAME,
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .post_load = ccid_post_load,
+    .pre_save = ccid_pre_save,
+    .fields = (VMStateField []) {
+        VMSTATE_STRUCT(dev, USBCCIDState, 1, usb_device_vmstate, USBDevice),
+        VMSTATE_UINT8(debug, USBCCIDState),
+        VMSTATE_UINT8(auto_attach, USBCCIDState),
+        VMSTATE_BUFFER(bulk_out_data, USBCCIDState),
+        VMSTATE_UINT32(bulk_out_pos, USBCCIDState),
+        VMSTATE_UINT8(bmSlotICCState, USBCCIDState),
+        VMSTATE_UINT8(powered, USBCCIDState),
+        VMSTATE_UINT8(notify_slot_change, USBCCIDState),
+        VMSTATE_UINT64(last_answer_error, USBCCIDState),
+        VMSTATE_UINT8(bError, USBCCIDState),
+        VMSTATE_UINT8(bmCommandStatus, USBCCIDState),
+        VMSTATE_UINT8(bProtocolNum, USBCCIDState),
+        VMSTATE_BUFFER(abProtocolDataStructure, USBCCIDState),
+        VMSTATE_UINT32(ulProtocolDataStructureSize, USBCCIDState),
+        VMSTATE_STRUCT_ARRAY(bulk_in_pending, USBCCIDState,
+                       BULK_IN_PENDING_NUM, 1, bulk_in_t_vmstate, bulk_in_t),
+        VMSTATE_UINT32(bulk_in_pending_start, USBCCIDState),
+        VMSTATE_UINT32(bulk_in_pending_end, USBCCIDState),
+        VMSTATE_STRUCT_ARRAY(pending_answers, USBCCIDState,
+                        PENDING_ANSWERS_NUM, 1, answer_t_vmstate, answer_t),
+        VMSTATE_UINT32(pending_answers_num, USBCCIDState),
+        VMSTATE_UINT8(migration_state, USBCCIDState),
+        VMSTATE_UINT8(attached_vmstate, USBCCIDState),
+        VMSTATE_UINT32(state_vmstate, USBCCIDState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static struct USBDeviceInfo ccid_info = {
+    .product_desc   = "QEMU USB CCID",
+    .qdev.name      = CCID_DEV_NAME,
+    .qdev.size      = sizeof(USBCCIDState),
+    .qdev.vmsd      = &ccid_vmstate,
+    .init           = ccid_initfn,
+    .handle_packet  = usb_generic_handle_packet,
+    .handle_reset   = ccid_handle_reset,
+    .handle_control = ccid_handle_control,
+    .handle_data    = ccid_handle_data,
+    .handle_destroy = ccid_handle_destroy,
+    .usbdevice_name = "ccid",
+    .qdev.props     = (Property[]) {
+        DEFINE_PROP_UINT8("auto_attach", USBCCIDState, auto_attach, 0),
+        DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    },
+};
+
+
+static void ccid_register_devices(void)
+{
+    usb_qdev_register(&ccid_info);
+}
+device_init(ccid_register_devices)
-- 
1.7.3.1

^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [Qemu-devel] [PATCH 2/4] ccid: add passthru card device
  2010-10-24 13:18 [Qemu-devel] [PATCH 0/4] usb-ccid (v4) Alon Levy
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 1/4] usb-ccid: add CCID bus Alon Levy
@ 2010-10-24 13:18 ` Alon Levy
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 3/4] add ccid-card-emulated device (v2) Alon Levy
                   ` (2 subsequent siblings)
  4 siblings, 0 replies; 10+ messages in thread
From: Alon Levy @ 2010-10-24 13:18 UTC (permalink / raw)
  To: qemu-devel

For the client side utility vscclient, see libcac_card:

  libcac_card http://cgit.freedesktop.org/~alon/cac_card (temporary home)
  written by Robert Relyea <rrelyea@redhat.com>

Signed-off-by: Alon Levy <alevy@redhat.com>
---
 Makefile.objs           |    2 +-
 hw/ccid-card-passthru.c |  278 +++++++++++++++++++++++++++++++++++++++++++++++
 hw/vscard_common.h      |  130 ++++++++++++++++++++++
 3 files changed, 409 insertions(+), 1 deletions(-)
 create mode 100644 hw/ccid-card-passthru.c
 create mode 100644 hw/vscard_common.h

diff --git a/Makefile.objs b/Makefile.objs
index 5b52625..f2966e3 100644
--- a/Makefile.objs
+++ b/Makefile.objs
@@ -174,7 +174,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
 hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
 hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
 hw-obj-$(CONFIG_DMA) += dma.o
-hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
diff --git a/hw/ccid-card-passthru.c b/hw/ccid-card-passthru.c
new file mode 100644
index 0000000..ed9a833
--- /dev/null
+++ b/hw/ccid-card-passthru.c
@@ -0,0 +1,278 @@
+/*
+ * CCID Card Device emulation
+ *
+ * Copyright (c) 2010 Red Hat.
+ * Written by Alon Levy.
+ *
+ * This code is licenced under the LGPL.
+ */
+
+#include "qemu-char.h"
+#include "monitor.h"
+#include "hw/ccid.h"
+#include "hw/vscard_common.h"
+
+#define DPRINTF(lvl, fmt, ...) \
+do { if (lvl <= debug) { printf("ccid-card: " fmt , ## __VA_ARGS__); } } while (0)
+
+static int debug = 0;
+
+/* Passthru card */
+
+
+// TODO: do we still need this?
+uint8_t DEFAULT_ATR[] = {
+/* From some example somewhere
+ 0x3B, 0xB0, 0x18, 0x00, 0xD1, 0x81, 0x05, 0xB1, 0x40, 0x38, 0x1F, 0x03, 0x28
+ */
+
+/* From an Athena smart card */
+ 0x3B, 0xD5, 0x18, 0xFF, 0x80, 0x91, 0xFE, 0x1F, 0xC3, 0x80, 0x73, 0xC8, 0x21, 0x13, 0x08
+
+}; /* maximum size of ATR - from 7816-3 */
+
+
+#define PASSTHRU_DEV_NAME "ccid-card-passthru"
+#define VSCARD_IN_SIZE 65536
+#define MAX_ATR_SIZE        40
+
+typedef struct PassthruState PassthruState;
+
+struct PassthruState {
+    CCIDCardState base;
+    CharDriverState *cs;
+    uint8_t  vscard_in_data[VSCARD_IN_SIZE];
+    uint32_t vscard_in_pos;
+    uint32_t vscard_in_hdr;
+    uint8_t  atr[MAX_ATR_SIZE];
+    uint8_t  atr_length;
+    uint8_t debug;
+};
+
+/* VSCard protocol over chardev
+ * This code should not depend on the card type.
+ * */
+
+static void ccid_card_vscard_send_msg(
+    PassthruState *s, VSCMsgType type, reader_id_t reader_id,
+        const uint8_t* payload, uint32_t length)
+{
+    VSCMsgHeader scr_msg_header;
+
+    scr_msg_header.type = type;
+    scr_msg_header.reader_id = reader_id;
+    scr_msg_header.length = length;
+    qemu_chr_write(s->cs, (uint8_t*)&scr_msg_header, sizeof(VSCMsgHeader));
+    qemu_chr_write(s->cs, payload, length);
+}
+
+static void ccid_card_vscard_send_apdu(
+    PassthruState *s, const uint8_t* apdu, uint32_t length)
+{
+    ccid_card_vscard_send_msg(s, VSC_APDU, VSCARD_MINIMAL_READER_ID, apdu, length);
+}
+
+static void ccid_card_vscard_send_error(
+    PassthruState *s, reader_id_t reader_id, VSCErrorCode code)
+{
+    VSCMsgError msg = {.code=code};
+
+    ccid_card_vscard_send_msg(s, VSC_Error, reader_id, (uint8_t*)&msg, sizeof(msg));
+}
+
+static void ccid_card_vscard_send_init(PassthruState *s)
+{
+    VSCMsgInit msg = {.version=VSCARD_VERSION};
+
+    ccid_card_vscard_send_msg(s, VSC_Init, VSCARD_UNDEFINED_READER_ID,
+                         (uint8_t*)&msg, sizeof(msg));
+}
+
+static int ccid_card_vscard_can_read(void *opaque)
+{
+    return 65535;
+}
+
+static void ccid_card_vscard_handle_message(PassthruState *card,
+    VSCMsgHeader* scr_msg_header)
+{
+    uint8_t *data = (uint8_t*)&scr_msg_header[1];
+
+    switch (scr_msg_header->type) {
+        case VSC_ATR:
+            DPRINTF(1, "VSC_ATR %d\n", scr_msg_header->length);
+            assert(scr_msg_header->length <= MAX_ATR_SIZE);
+            memcpy(card->atr, data, scr_msg_header->length);
+            card->atr_length = scr_msg_header->length;
+            ccid_card_card_inserted(&card->base);
+            break;
+        case VSC_APDU:
+            ccid_card_send_apdu_to_guest(&card->base, data, scr_msg_header->length);
+            break;
+        case VSC_CardRemove:
+            DPRINTF(1, "VSC_CardRemove\n");
+            ccid_card_card_removed(&card->base);
+            break;
+        case VSC_Init:
+            break;
+        case VSC_Error:
+            ccid_card_card_error(&card->base, *(uint64_t*)data);
+            break;
+        case VSC_ReaderAdd:
+            if (ccid_card_ccid_attach(&card->base) < 0) {
+                ccid_card_vscard_send_error(card, VSCARD_UNDEFINED_READER_ID,
+                                          VSC_CANNOT_ADD_MORE_READERS);
+            } else {
+                ccid_card_vscard_send_msg(card, VSC_ReaderAddResponse,
+                                             VSCARD_MINIMAL_READER_ID, NULL, 0);
+            }
+            break;
+        case VSC_ReaderRemove:
+            ccid_card_ccid_detach(&card->base);
+            break;
+        default:
+            printf("usb-ccid: chardev: unexpected message of type %X\n",
+                   scr_msg_header->type);
+            ccid_card_vscard_send_error(card, scr_msg_header->reader_id,
+                VSC_GENERAL_ERROR);
+    }
+}
+
+static void ccid_card_vscard_read(void *opaque, const uint8_t *buf, int size)
+{
+    PassthruState *card = opaque;
+    VSCMsgHeader *hdr;
+
+    assert(card->vscard_in_pos + size <= VSCARD_IN_SIZE);
+    memcpy(card->vscard_in_data + card->vscard_in_pos, buf, size);
+    card->vscard_in_pos += size;
+    hdr = (VSCMsgHeader*)(card->vscard_in_data + card->vscard_in_hdr);
+
+    while ((card->vscard_in_pos - card->vscard_in_hdr >= sizeof(VSCMsgHeader)) &&
+           (card->vscard_in_pos - card->vscard_in_hdr - sizeof(VSCMsgHeader) >=
+           hdr->length)) {
+        ccid_card_vscard_handle_message(card, hdr);
+        card->vscard_in_hdr += hdr->length + sizeof(VSCMsgHeader);
+        hdr = (VSCMsgHeader*)(card->vscard_in_data + card->vscard_in_hdr);
+    }
+    if (card->vscard_in_hdr == card->vscard_in_pos) {
+        card->vscard_in_pos = card->vscard_in_hdr = 0;
+    }
+}
+
+static void ccid_card_vscard_event(void *opaque, int event)
+{
+    switch (event) {
+        case CHR_EVENT_BREAK:
+            break;
+        case CHR_EVENT_FOCUS:
+            break;
+        case CHR_EVENT_OPENED:
+            DPRINTF(1, "%s: CHR_EVENT_OPENED\n", __func__);
+            break;
+    }
+}
+
+/* End VSCard handling */
+
+static void passthru_apdu_from_guest(CCIDCardState *base, const uint8_t *apdu, uint32_t len)
+{
+    PassthruState *card = DO_UPCAST(PassthruState, base, base);
+
+    if (!card->cs) {
+        printf("ccid-passthru: no chardev, discarding apdu length %d\n", len);
+        return;
+    }
+    ccid_card_vscard_send_apdu(card, apdu, len);
+}
+
+static const uint8_t* passthru_get_atr(CCIDCardState *base, uint32_t *len)
+{
+    PassthruState *card = DO_UPCAST(PassthruState, base, base);
+
+    *len = card->atr_length;
+    return card->atr;
+}
+
+static int passthru_initfn(CCIDCardState *base)
+{
+    PassthruState *card = DO_UPCAST(PassthruState, base, base);
+
+    card->vscard_in_pos = 0;
+    card->vscard_in_hdr = 0;
+    if (card->cs) {
+        DPRINTF(1, "initing chardev\n");
+        qemu_chr_add_handlers(card->cs,
+            ccid_card_vscard_can_read,
+            ccid_card_vscard_read,
+            ccid_card_vscard_event, card);
+        ccid_card_vscard_send_init(card);
+    }
+    assert(sizeof(DEFAULT_ATR) <= MAX_ATR_SIZE);
+    memcpy(card->atr, DEFAULT_ATR, sizeof(DEFAULT_ATR));
+    card->atr_length = sizeof(DEFAULT_ATR);
+    debug = card->debug;
+    return 0;
+}
+
+static int passthru_exitfn(CCIDCardState *base)
+{
+    PassthruState *card = DO_UPCAST(PassthruState, base, base);
+
+    if (card->cs) {
+        qemu_chr_close(card->cs);
+    }
+    return 0;
+}
+
+static void passthru_pre_save(void *opaque)
+{
+    PassthruState *card = opaque;
+    VSCMsgReconnect reconnect;
+
+    reconnect.ip = 0; // TODO - does the bus keep the target ip? s->migration_target_ip;
+    reconnect.port = 0; // TODO - does the bus keep the target ip? s->migration_target_port;
+    ccid_card_vscard_send_msg(card, VSC_Reconnect, VSCARD_UNDEFINED_READER_ID,
+                         (uint8_t*)&reconnect, sizeof(reconnect));
+}
+
+static VMStateDescription passthru_vmstate = {
+    .name = PASSTHRU_DEV_NAME,
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .pre_save = passthru_pre_save,
+    .fields = (VMStateField []) {
+        VMSTATE_BUFFER(vscard_in_data, PassthruState),
+        VMSTATE_UINT32(vscard_in_pos, PassthruState),
+        VMSTATE_UINT32(vscard_in_hdr, PassthruState),
+        VMSTATE_BUFFER(atr, PassthruState),
+        VMSTATE_UINT8(atr_length, PassthruState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static CCIDCardInfo passthru_card_info = {
+    .qdev.name = PASSTHRU_DEV_NAME,
+    .qdev.size = sizeof(PassthruState),
+    .qdev.vmsd = &passthru_vmstate,
+    .initfn = passthru_initfn,
+    .exitfn = passthru_exitfn,
+    .get_atr = passthru_get_atr,
+    .apdu_from_guest = passthru_apdu_from_guest,
+    .qdev.props     = (Property[]) {
+        DEFINE_PROP_CHR("chardev", PassthruState, cs),
+        DEFINE_PROP_UINT8("debug", PassthruState, debug, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    },
+};
+
+static void ccid_card_passthru_register_devices(void)
+{
+    ccid_card_qdev_register(&passthru_card_info);
+    // TODO: passthru local card (or: just a case of passthru with no chardev
+    //  given and instead some other arguments that would be required for local
+    //  card anyway and can be shared with the emulated local card)
+    // TODO: emulated local card
+}
+
+device_init(ccid_card_passthru_register_devices)
diff --git a/hw/vscard_common.h b/hw/vscard_common.h
new file mode 100644
index 0000000..0468ea3
--- /dev/null
+++ b/hw/vscard_common.h
@@ -0,0 +1,130 @@
+/* Virtual Smart Card protocol definition
+ *
+ * This protocol is between a host implementing a group of virtual smart card
+ * reader, and a client implementing a virtual smart card, or passthrough to
+ * a real card.
+ *
+ * The current implementation passes the raw APDU's from 7816 and additionally
+ * contains messages to setup and teardown readers, handle insertion and
+ * removal of cards, negotiate the protocol and provide for error responses.
+ *
+ * Copyright (c) 2010 Red Hat.
+ *
+ * This code is licensed under the LGPL.
+ */
+
+#ifndef _VSCARD_COMMON_H
+#define _VSCARD_COMMON_H
+
+#include <stdint.h>
+
+#define VERSION_MAJOR_BITS 11
+#define VERSION_MIDDLE_BITS 11
+#define VERSION_MINOR_BITS 10
+
+#define MAKE_VERSION(major, middle, minor) \
+     (  (major  << (VERSION_MINOR_BITS + VERSION_MIDDLE_BITS)) \
+      | (middle <<  VERSION_MINOR_BITS) \
+      | (minor)  )
+
+/** IMPORTANT NOTE on VERSION
+ *
+ * The version below MUST be changed whenever a change in this file is made.
+ *
+ * The last digit, the minor, is for bug fix changes only.
+ *
+ * The middle digit is for backward / forward compatible changes, updates
+ * to the existing messages, addition of fields.
+ *
+ * The major digit is for a breaking change of protocol, presumably
+ * something that cannot be accomodated with the existing protocol.
+ */
+
+#define VSCARD_VERSION MAKE_VERSION(0,0,1)
+
+typedef enum {
+    VSC_Init,
+    VSC_Error,
+    VSC_ReaderAdd,
+    VSC_ReaderAddResponse,
+    VSC_ReaderRemove,
+    VSC_ATR,
+    VSC_CardRemove,
+    VSC_APDU,
+    VSC_Reconnect
+} VSCMsgType;
+
+typedef enum {
+    VSC_GENERAL_ERROR=1,
+    VSC_CANNOT_ADD_MORE_READERS,
+} VSCErrorCode;
+
+typedef uint32_t reader_id_t;
+#define VSCARD_UNDEFINED_READER_ID 0xfffffffe
+#define VSCARD_MINIMAL_READER_ID    0
+
+typedef struct VSCMsgHeader {
+    VSCMsgType type;
+    reader_id_t   reader_id;
+    uint32_t   length;
+    uint8_t    data[0];
+} VSCMsgHeader;
+
+/* VSCMsgInit               Client <-> Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * */
+typedef struct VSCMsgInit {
+    uint32_t   version;
+} VSCMsgInit;
+
+/* VSCMsgError              Client <-> Host
+ * */
+typedef struct VSCMsgError {
+    uint32_t   code;
+} VSCMsgError;
+
+/* VSCMsgReaderAdd          Client -> Host
+ * Host replies with allocated reader id in ReaderAddResponse
+ * name - name of the reader on client side.
+ * */
+typedef struct VSCMsgReaderAdd {
+    uint8_t    name[0];
+} VSCMsgReaderAdd;
+
+/* VSCMsgReaderAddResponse  Host -> Client
+ * Reply to ReaderAdd
+ * */
+typedef struct VSCMsgReaderAddResponse {
+} VSCMsgReaderAddResponse;
+
+/* VSCMsgReaderRemove       Client -> Host
+ * */
+typedef struct VSCMsgReaderRemove {
+} VSCMsgReaderRemove;
+
+/* VSCMsgATR                Client -> Host
+ * Answer to reset. Sent for card insertion or card reset.
+ * */
+typedef struct VSCMsgATR {
+    uint8_t     atr[0];
+} VSCMsgATR;
+
+/* VSCMsgCardRemove         Client -> Host
+ * */
+typedef struct VSCMsgCardRemove {
+} VSCMsgCardRemove;
+
+/* VSCMsgAPDU               Client <-> Host
+ * */
+typedef struct VSCMsgAPDU {
+    uint8_t    data[0];
+} VSCMsgAPDU;
+
+/* VSCMsgReconnect          Host -> Client
+ * */
+typedef struct VSCMsgReconnect {
+    uint32_t   ip;
+    uint16_t   port;
+} VSCMsgReconnect;
+
+#endif
-- 
1.7.3.1

^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [Qemu-devel] [PATCH 3/4] add ccid-card-emulated device (v2)
  2010-10-24 13:18 [Qemu-devel] [PATCH 0/4] usb-ccid (v4) Alon Levy
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 1/4] usb-ccid: add CCID bus Alon Levy
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 2/4] ccid: add passthru card device Alon Levy
@ 2010-10-24 13:18 ` Alon Levy
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 4/4] ccid: add docs Alon Levy
  2010-11-09 10:14 ` [Qemu-devel] [PATCH 0/4] usb-ccid (v4) Markus Armbruster
  4 siblings, 0 replies; 10+ messages in thread
From: Alon Levy @ 2010-10-24 13:18 UTC (permalink / raw)
  To: qemu-devel

changes from v1:
    remove stale comments, use only c-style comments
    bugfix, forgot to set recv_len
    change reader name to 'Virtual Reader'

Signed-off-by: Alon Levy <alevy@redhat.com>
---
 Makefile.objs           |    2 +-
 configure               |   20 ++
 hw/ccid-card-emulated.c |  495 +++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 516 insertions(+), 1 deletions(-)
 create mode 100644 hw/ccid-card-emulated.c

diff --git a/Makefile.objs b/Makefile.objs
index f2966e3..736edf1 100644
--- a/Makefile.objs
+++ b/Makefile.objs
@@ -174,7 +174,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
 hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
 hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
 hw-obj-$(CONFIG_DMA) += dma.o
-hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o ccid-card-emulated.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
diff --git a/configure b/configure
index 15aee9e..3a0989b 100755
--- a/configure
+++ b/configure
@@ -2130,6 +2130,26 @@ EOF
   fi
 fi
 
+# check for libcaccard for smartcard support
+if test "$smartcard" != "no" ; then
+  cat > $TMPC << EOF
+#include <vscard_common.h>
+int main() { return 0; }
+EOF
+  smartcard_cflags=$($pkgconfig --cflags cac_card cac_card 2>/dev/null)
+  smartcard_libs=$($pkgconfig --libs cac_card cac_card 2>/dev/null)
+  if $pkgconfig --atleast-version=0.0.1 cac_card &&\
+     compile_prog "$smartcard_cflags" "$smartcard_libs" ; then
+    smartcard="yes"
+    QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags"
+  else
+    if test "smartcard" = "yes" ; then
+      feature_not_found "smartcard"
+    fi
+    smartcard="no"
+  fi
+fi
+
 ##########################################
 
 ##########################################
diff --git a/hw/ccid-card-emulated.c b/hw/ccid-card-emulated.c
new file mode 100644
index 0000000..9eee6b7
--- /dev/null
+++ b/hw/ccid-card-emulated.c
@@ -0,0 +1,495 @@
+/*
+ * CCID Card Device. Emulated card.
+ *
+ * It can be used to provide access to the local hardware in a non exclusive
+ * way, or it can use certificates. It requires the usb-ccid bus.
+ *
+ * Usage 1: standard, mirror hardware reader+card:
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated
+ *
+ * Usage 2: use certificates, no hardware required
+ * one time: create the certificates:
+ *  for i in 1 2 3; do certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=user$i" -n user$i; done 
+ * qemu .. -usb -device usb-ccid -device ccid-card-emulated,cert1=user1,cert2=user2,cert3=user3
+ *
+ * If you use a non default db for the certificates you can specify it using the db parameter.
+ *
+ *
+ * Copyright (c) 2010 Red Hat.
+ * Written by Alon Levy.
+ *
+ * This code is licenced under the LGPL.
+ */
+
+#include <pthread.h>
+#include <eventt.h>
+#include <vevent.h>
+#include <vreader.h>
+#include <vcard_emul.h>
+#include "qemu-char.h"
+#include "monitor.h"
+#include "hw/ccid.h"
+
+#define DPRINTF(lvl, fmt, ...) \
+do { if (lvl <= debug) { printf("ccid-card-emul: %s: " fmt , __func__, ## __VA_ARGS__); } } while (0)
+
+static int debug = 0;
+
+#define EMULATED_DEV_NAME "ccid-card-emulated"
+
+#define BACKEND_NSS_EMULATED "nss-emulated" /* the default */
+#define BACKEND_CERTIFICATES "certificates"
+
+typedef struct EmulatedState EmulatedState;
+
+enum {
+    EMUL_READER_INSERT = 0,
+    EMUL_READER_REMOVE,
+    EMUL_CARD_INSERT,
+    EMUL_CARD_REMOVE,
+    EMUL_GUEST_APDU,
+    EMUL_RESPONSE_APDU,
+    EMUL_ERROR,
+};
+
+static const char* emul_event_to_string(uint32_t emul_event)
+{
+    switch (emul_event) {
+        case EMUL_READER_INSERT: return "EMUL_READER_INSERT";
+        case EMUL_READER_REMOVE: return "EMUL_READER_REMOVE";
+        case EMUL_CARD_INSERT: return "EMUL_CARD_INSERT";
+        case EMUL_CARD_REMOVE: return "EMUL_CARD_REMOVE";
+        case EMUL_GUEST_APDU: return "EMUL_GUEST_APDU";
+        case EMUL_RESPONSE_APDU: return "EMUL_RESPONSE_APDU";
+        case EMUL_ERROR: return "EMUL_ERROR";
+        default:
+            break;
+    }
+    return "UNKNOWN";
+}
+
+typedef struct EmulEvent {
+    QSIMPLEQ_ENTRY(EmulEvent) entry;
+    union {
+        struct {
+            uint32_t type;
+        } gen;
+        struct {
+            uint32_t type;
+            uint64_t code;
+        } error;
+        struct {
+            uint32_t type;
+            uint32_t len;
+            uint8_t data[];
+        } data;
+    } p;
+} EmulEvent;
+
+#define MAX_ATR_SIZE 40
+struct EmulatedState {
+    CCIDCardState base;
+    uint8_t  debug;
+    char*    backend;
+    char*    cert1;
+    char*    cert2;
+    char*    cert3;
+    char*    db;
+    uint8_t  atr[MAX_ATR_SIZE];
+    uint8_t  atr_length;
+    QSIMPLEQ_HEAD(event_list, EmulEvent) event_list;
+    pthread_mutex_t event_list_mutex;
+    VReader *reader;
+    QSIMPLEQ_HEAD(guest_apdu_list, EmulEvent) guest_apdu_list;
+    pthread_mutex_t vreader_mutex; /* and guest_apdu_list mutex */
+    pthread_mutex_t handle_apdu_mutex;
+    pthread_cond_t handle_apdu_cond;
+    int      pipe[2];
+    int      quit_apdu_thread;
+    pthread_mutex_t apdu_thread_quit_mutex;
+    pthread_cond_t apdu_thread_quit_cond;
+};
+
+static void emulated_apdu_from_guest(CCIDCardState *base, const uint8_t *apdu, uint32_t len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = EMUL_GUEST_APDU;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, apdu, len);
+    pthread_mutex_lock(&card->vreader_mutex);
+    QSIMPLEQ_INSERT_TAIL(&card->guest_apdu_list, event, entry);
+    pthread_mutex_unlock(&card->vreader_mutex);
+    pthread_cond_signal(&card->handle_apdu_cond);
+}
+
+static const uint8_t* emulated_get_atr(CCIDCardState *base, uint32_t *len)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+
+    *len = card->atr_length;
+    return card->atr;
+}
+
+static void emulated_push_event(EmulatedState *card, EmulEvent *event)
+{
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_INSERT_TAIL(&(card->event_list), event, entry);
+    pthread_mutex_unlock(&card->event_list_mutex);
+    if (write(card->pipe[1], card, 1) != 1) {
+        DPRINTF(1, "write to pipe failed\n");
+    }
+}
+
+static void emulated_push_type(EmulatedState *card, uint32_t type)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.gen.type = type;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_error(EmulatedState *card, uint64_t code)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent));
+
+    assert(event);
+    event->p.error.type = EMUL_ERROR;
+    event->p.error.code = code;
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_data_type(EmulatedState *card, uint32_t type,
+    const uint8_t *data, uint32_t len)
+{
+    EmulEvent *event = (EmulEvent*)malloc(sizeof(EmulEvent) + len);
+
+    assert(event);
+    event->p.data.type = type;
+    event->p.data.len = len;
+    memcpy(event->p.data.data, data, len);
+    emulated_push_event(card, event);
+}
+
+static void emulated_push_reader_insert(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_INSERT);
+}
+
+static void emulated_push_reader_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_READER_REMOVE);
+}
+
+static void emulated_push_card_insert(EmulatedState *card,
+    const uint8_t *atr, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_CARD_INSERT, atr, len);
+}
+
+static void emulated_push_card_remove(EmulatedState *card)
+{
+    emulated_push_type(card, EMUL_CARD_REMOVE);
+}
+
+static void emulated_push_response_apdu(EmulatedState *card,
+    const uint8_t* apdu, uint32_t len)
+{
+    emulated_push_data_type(card, EMUL_RESPONSE_APDU, apdu, len);
+}
+
+#define APDU_BUF_SIZE 270
+static void *handle_apdu_thread(void* arg)
+{
+    EmulatedState *card = arg;
+    uint8_t recv_data[APDU_BUF_SIZE];
+    int recv_len;
+    VReaderStatus reader_status;
+    EmulEvent *event;
+
+    while (1) {
+        pthread_mutex_lock(&card->handle_apdu_mutex);
+        pthread_cond_wait(&card->handle_apdu_cond, &card->handle_apdu_mutex);
+        pthread_mutex_unlock(&card->handle_apdu_mutex);
+        if (card->quit_apdu_thread) {
+            break;
+        }
+        pthread_mutex_lock(&card->vreader_mutex);
+        while (!QSIMPLEQ_EMPTY(&card->guest_apdu_list)) {
+            event = QSIMPLEQ_FIRST(&card->guest_apdu_list);
+            assert((unsigned long)event > 1000);
+            QSIMPLEQ_REMOVE_HEAD(&card->guest_apdu_list, entry);
+            if (event->p.data.type != EMUL_GUEST_APDU) {
+                DPRINTF(0, "unexpected message in handle_apdu_thread\n");
+                free(event);
+                continue;
+            }
+            if (card->reader == NULL) {
+                DPRINTF(0, "reader is NULL\n");
+                free(event);
+                continue;
+            }
+            recv_len = sizeof(recv_data);
+            reader_status = vreader_xfr_bytes(card->reader,
+                    event->p.data.data, event->p.data.len,
+                    recv_data, &recv_len);
+            DPRINTF(1, "got back apdu of length %d\n", recv_len);
+            if (reader_status == VREADER_OK) {
+                emulated_push_response_apdu(card, recv_data, recv_len);
+            } else {
+                emulated_push_error(card, reader_status);
+            }
+            free(event);
+        }
+        pthread_mutex_unlock(&card->vreader_mutex);
+    }
+    pthread_cond_signal(&card->apdu_thread_quit_cond);
+    return NULL;
+}
+
+static void *event_thread(void *arg)
+{
+    int atr_len = MAX_ATR_SIZE;
+    uint8_t atr[MAX_ATR_SIZE];
+    VEvent *event = NULL;
+    EmulatedState *card = arg;
+
+    while (1) {
+        const char *reader_name;
+
+        event = vevent_wait_next_vevent();
+        if (event == NULL) {
+            break;
+        }
+        if (event->type != VEVENT_READER_INSERT &&
+            event->reader != card->reader) {
+            DPRINTF(1, "EVENT ignored\n");
+            break;
+        }
+        switch (event->type) {
+        case VEVENT_READER_INSERT:
+            /* TODO: take a specific reader. i.e. track which reader
+             * we are seeing here, check it is the one we want (the first,
+             * or by a particular name), and ignore if we don't want it.
+             */
+            reader_name = vreader_get_name(event->reader);
+            if (card->reader == NULL) {
+                DPRINTF(1, "READER INSERT %s\n", reader_name);
+                card->reader = vreader_reference(event->reader);
+                emulated_push_reader_insert(card);
+            } else {
+                DPRINTF(1, "READER INSERT ignored %s\n", reader_name);
+            }
+            break;
+        case VEVENT_READER_REMOVE:
+            DPRINTF(1, " READER REMOVE: %s \n",
+                    vreader_get_name(event->reader));
+            pthread_mutex_lock(&card->vreader_mutex);
+            vreader_free(card->reader);
+            card->reader = NULL;
+            pthread_mutex_unlock(&card->vreader_mutex);
+            emulated_push_reader_remove(card);
+            break;
+        case VEVENT_CARD_INSERT:
+            /* get the ATR (intended as a response to a power on from the
+             * reader */
+            atr_len = MAX_ATR_SIZE;
+            vreader_power_on(event->reader, atr, &atr_len);
+            card->atr_length = (uint8_t)atr_len;
+            DPRINTF(1, " CARD INSERT\n");
+            emulated_push_card_insert(card, atr, atr_len);
+            break;
+        case VEVENT_CARD_REMOVE:
+            DPRINTF(1, " CARD REMOVE\n");
+            emulated_push_card_remove(card);
+            break;
+        case VEVENT_LAST: /* quit */
+            vevent_delete(event);
+            return NULL;
+            break;
+        default:
+            break;
+        }
+        vevent_delete(event);
+    }
+    return NULL;
+}
+
+static void pipe_read(void *opaque)
+{
+    EmulatedState *card = opaque;
+    EmulEvent *event, *next;
+    char dummy;
+    int len;
+
+    do {
+        len = read(card->pipe[0], &dummy, sizeof(dummy));
+    } while (len == sizeof(dummy));
+    pthread_mutex_lock(&card->event_list_mutex);
+    QSIMPLEQ_FOREACH_SAFE(event, &card->event_list, entry, next) {
+        DPRINTF(1, "event %s\n", emul_event_to_string(event->p.gen.type));
+        switch (event->p.gen.type) {
+            case EMUL_RESPONSE_APDU:
+                ccid_card_send_apdu_to_guest(&card->base, event->p.data.data,
+                    event->p.data.len);
+                break;
+            case EMUL_READER_INSERT:
+                ccid_card_ccid_attach(&card->base);
+                break;
+            case EMUL_READER_REMOVE:
+                ccid_card_ccid_detach(&card->base);
+                break;
+            case EMUL_CARD_INSERT:
+                assert(event->p.data.len <= MAX_ATR_SIZE);
+                card->atr_length = event->p.data.len;
+                memcpy(card->atr, event->p.data.data, card->atr_length);
+                ccid_card_card_inserted(&card->base);
+                break;
+            case EMUL_CARD_REMOVE:
+                ccid_card_card_removed(&card->base);
+                break;
+            case EMUL_ERROR:
+                ccid_card_card_error(&card->base, event->p.error.code);
+                break;
+            default:
+                DPRINTF(1, "unexpected event\n");
+                break;
+        }
+        free(event);
+    }
+    QSIMPLEQ_INIT(&card->event_list);
+    pthread_mutex_unlock(&card->event_list_mutex);
+}
+
+static int init_pipe_signaling(EmulatedState *card)
+{
+   if (pipe(card->pipe) < 0) {
+       DPRINTF(1, "pipe creation failed\n");
+       return -1;
+   }
+   fcntl(card->pipe[0], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[1], F_SETFL, O_NONBLOCK);
+   fcntl(card->pipe[0], F_SETOWN, getpid());
+   qemu_set_fd_handler(card->pipe[0], pipe_read, NULL, card);
+   return 0;
+}
+
+#define CERTIFICATES_DEFAULT_DB "/etc/pki/nssdb"
+#define CERTIFICATES_ARGS_TEMPLATE "db=\"%s\" use_hw=no soft=(,Virtual Reader,CAC,,%s,%s,%s)"
+
+static int emulated_initialize_vcard_from_certificates(EmulatedState *card)
+{
+    char emul_args[200];
+    VCardEmulOptions *options = NULL;
+
+    snprintf(emul_args, sizeof(emul_args) - 1, CERTIFICATES_ARGS_TEMPLATE,
+        card->db ? card->db : CERTIFICATES_DEFAULT_DB,
+        card->cert1, card->cert2, card->cert3);
+    options = vcard_emul_options(emul_args);
+    if (options == NULL) {
+        printf("%s: warning: not using certificates due to initialization error\n", __func__);
+    }
+    return vcard_emul_init(options);
+}
+
+static int emulated_initfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    int rv;
+    pthread_t thread_id;
+    VCardEmulError ret;
+
+    QSIMPLEQ_INIT(&card->event_list);
+    QSIMPLEQ_INIT(&card->guest_apdu_list);
+    pthread_mutex_init(&card->event_list_mutex, NULL);
+    pthread_mutex_init(&card->vreader_mutex, NULL);
+    pthread_mutex_init(&card->handle_apdu_mutex, NULL);
+    pthread_cond_init(&card->handle_apdu_cond, NULL);
+    card->reader = NULL;
+    card->quit_apdu_thread = 0;
+    if (init_pipe_signaling(card) < 0) {
+        return -1;
+    }
+    /* TODO: a passthru backened that works on local machine. third card type? */
+    if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0
+        && card->cert1 != NULL && card->cert2 != NULL && card->cert3 != NULL) {
+        ret = emulated_initialize_vcard_from_certificates(card);
+    } else {
+        if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0) {
+            printf("%s: you must provide all three certs for certificates backend\n",
+                EMULATED_DEV_NAME);
+            return -1;
+        }
+        if (card->backend && strcmp(BACKEND_NSS_EMULATED, card->backend) != 0) {
+            printf("%s: bad backend specified. The options are:\n%s (default), %s.\n",
+                EMULATED_DEV_NAME, BACKEND_NSS_EMULATED, BACKEND_CERTIFICATES);
+            return -1;
+        }
+        /* default to mirroring the local hardware readers */
+        ret = vcard_emul_init(NULL);
+    }
+    if (ret != VCARD_EMUL_OK) {
+        printf("%s: failed to initialize vcard\n", EMULATED_DEV_NAME);
+        return -1;
+    }
+    rv = pthread_create(&thread_id, NULL, event_thread, card);
+    if (rv < 0) {
+        printf("%s: error creating event thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }
+    rv = pthread_create(&thread_id, NULL, handle_apdu_thread, card);
+    if (rv < 0) {
+        printf("%s: error creating handle_apdu thread\n", EMULATED_DEV_NAME);
+        return -1;
+    }
+    debug = card->debug;
+    return 0;
+}
+
+static int emulated_exitfn(CCIDCardState *base)
+{
+    EmulatedState *card = DO_UPCAST(EmulatedState, base, base);
+    VEvent *vevent = vevent_new(VEVENT_LAST, NULL, NULL);
+
+    vevent_queue_vevent(vevent); /* stop vevent thread */
+    card->quit_apdu_thread = 1; /* stop handle_apdu thread */
+    pthread_cond_signal(&card->handle_apdu_cond);
+    pthread_mutex_lock(&card->apdu_thread_quit_mutex);
+    pthread_cond_wait(&card->apdu_thread_quit_cond, &card->apdu_thread_quit_mutex);
+    /* handle_apdu thread stopped, can destroy all of it's mutexes */
+    pthread_cond_destroy(&card->handle_apdu_cond);
+    pthread_cond_destroy(&card->apdu_thread_quit_cond);
+    pthread_mutex_destroy(&card->apdu_thread_quit_mutex);
+    pthread_mutex_destroy(&card->handle_apdu_mutex);
+    pthread_mutex_destroy(&card->vreader_mutex);
+    pthread_mutex_destroy(&card->event_list_mutex);
+    return 0;
+}
+
+static CCIDCardInfo emulated_card_info = {
+    .qdev.name = EMULATED_DEV_NAME,
+    .qdev.size = sizeof(EmulatedState),
+    .initfn = emulated_initfn,
+    .exitfn = emulated_exitfn,
+    .get_atr = emulated_get_atr,
+    .apdu_from_guest = emulated_apdu_from_guest,
+    .qdev.props     = (Property[]) {
+        DEFINE_PROP_STRING("backend", EmulatedState, backend),
+        DEFINE_PROP_STRING("cert1", EmulatedState, cert1),
+        DEFINE_PROP_STRING("cert2", EmulatedState, cert2),
+        DEFINE_PROP_STRING("cert3", EmulatedState, cert3),
+        DEFINE_PROP_STRING("db", EmulatedState, db),
+        DEFINE_PROP_UINT8("debug", EmulatedState, debug, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    },
+};
+
+static void ccid_card_emulated_register_devices(void)
+{
+    ccid_card_qdev_register(&emulated_card_info);
+}
+
+device_init(ccid_card_emulated_register_devices)
-- 
1.7.3.1

^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [Qemu-devel] [PATCH 4/4] ccid: add docs
  2010-10-24 13:18 [Qemu-devel] [PATCH 0/4] usb-ccid (v4) Alon Levy
                   ` (2 preceding siblings ...)
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 3/4] add ccid-card-emulated device (v2) Alon Levy
@ 2010-10-24 13:18 ` Alon Levy
  2010-11-09 10:14 ` [Qemu-devel] [PATCH 0/4] usb-ccid (v4) Markus Armbruster
  4 siblings, 0 replies; 10+ messages in thread
From: Alon Levy @ 2010-10-24 13:18 UTC (permalink / raw)
  To: qemu-devel

---
 docs/ccid.txt |  133 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 133 insertions(+), 0 deletions(-)
 create mode 100644 docs/ccid.txt

diff --git a/docs/ccid.txt b/docs/ccid.txt
new file mode 100644
index 0000000..5eac611
--- /dev/null
+++ b/docs/ccid.txt
@@ -0,0 +1,133 @@
+Qemu CCID Device Documentation.
+
+Contents
+1. USB CCID device
+2. Building
+3. Using ccid-card-emulated with hardware
+4. Using ccid-card-emulated with certificates
+5. Using ccid-card-passthru with client side hardware
+6. Using ccid-card-passthru with client side certificates
+7. Passthrough protocol scenario
+8. libcaccard
+
+1. USB CCID device
+
+The USB CCID device is a USB device implementing the CCID specification, which
+lets one connect smart card readers that implement the same spec. For more
+information see the specification:
+
+ Universal Serial Bus
+ Device Class: Smart Card
+ CCID
+ Specification for
+ Integrated Circuit(s) Cards Interface Devices
+ Revision 1.1
+ April 22rd, 2005
+
+Smartcard are used for authentication, single sign on, decryption in
+public/private schemes and digital signatures. A smartcard reader on the client
+cannot be used on a guest with simple usb passthrough since it will then not be
+available on the client, possibly locking the computer when it is "removed". On
+the other hand this device can let you use the smartcard on both the client and
+the guest machine. It is also possible to have a completely virtual smart card
+reader and smart card (i.e. not backed by a physical device) using this device.
+
+2. Building
+
+prerequisites:
+ libcaccard
+
+At the moment there are no binary or source releases, so it has to be retrieved
+from source control:
+
+    git clone git://anongit.freedesktop.org/~alon/cac_card
+
+fedora:
+    yum install nss-devel
+ubuntu:
+    apt-get install libnss3-dev
+    (not tested on ubuntu)
+
+build cac_card:
+    cd cac_card
+    ./configure && make && sudo make install
+
+qemu:
+    ./configure --enable-smartcard && make
+
+Note that if you install to a non default prefix you need to set
+PKG_CONFIG_PATH to compile qemu successfully.
+
+3. Using ccid-card-emulated with hardware
+
+Assuming you have a working smartcard on the host with the current
+user, using NSS, qemu acts as another NSS client using ccid-card-emulated:
+
+    qemu -usb -device usb-ccid -device ccid-card-emualated
+
+4. Using ccid-card-emulated with certificates
+
+You must create the certificates. This is a one time process. We use NSS certificates:
+
+    certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=cert1" -n cert1
+
+Note: you must have exactly three certificates.
+
+Assuming the current user can access the certificates (use certutil -L to verify),
+you can use the emulated card type with the certificates backend:
+
+    qemu -usb -device usb-ccid -device ccid-card-emulated,backend=certificates,cert1=cert1,cert2=cert2,cert3=cert3
+
+5. Using ccid-card-passthru with client side hardware
+
+on the host specify the ccid-card-passthru device with a suitable chardev:
+
+    qemu -chardev socket,server,host=0.0.0.0,port=2001,id=ccid,nowait -usb -device usb-ccid -device ccid-card-passthru,chardev=ccid
+
+on the client run vscclient, built when you built the libcaccard library:
+    vscclient <qemu-host> 2001
+
+6. Using ccid-card-passthru with client side certificates
+
+Run qemu as per #5, and run vscclient as follows:
+(Note: vscclient command line interface is in a state of change)
+
+    ./vscclient -e "db=\"/etc/pki/nssdb\" use_hw=no soft=(,Test,CAC,,cert1,cert2,cert3)" <qemu-host> 2001
+
+7. Passthrough protocol scenario
+
+This is a typical interchange of messages when using the passthru card device.
+usb-ccid is a usb device. It defaults to an unattached usb device on startup.
+usb-ccid expects a chardev and expects the protocol defined in cac_card/vscard_common.h to be passed over that.
+A typical interchange is:
+
+client event      |      vscclient           |    passthru    |     usb-ccid  |  guest event
+----------------------------------------------------------------------------------------------
+                  |      VSC_Init            |                |               |
+                  |      VSC_ReaderAdd       |                |     attach    |
+                  |                          |                |               |  sees new usb device.
+card inserted     |                          |                |               |
+                  |      VSC_ATR             |                |               |
+                  |                          |                |               |  guest operation, APDU transfer via CCID
+                  |                          |   VSC_APDU     |               |
+                  |      VSC_APDU            |                |               |
+client<->physical |                          |                |               |
+card APDU exchange|                          |                |               |
+                            [APDU<->APDU repeats several times]              
+card removed      |                          |                |               |
+                  |      VSC_CardRemove      |                |               |
+kill/quit         |                          |                |               |
+  vscclient       |                          |                |               |
+                  |      VSC_ReaderRemove    |                |    detach     |
+                  |                          |                |               |   usb device removed.
+
+
+8. libcaccard
+
+ccid-card-passthru and vscclient use libcaccard as the card emulator.
+libcaccard implements a completely virtual CAC (DoD standard for smart cards)
+compliant card and uses NSS to actually retrive certificates and do any
+encryption using the backend (real reader + card or file backed certificates).
+
+For documentation of cac_card see README in libcac_card package.
+
-- 
1.7.3.1

^ permalink raw reply related	[flat|nested] 10+ messages in thread

* Re: [Qemu-devel] [PATCH 1/4] usb-ccid: add CCID bus
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 1/4] usb-ccid: add CCID bus Alon Levy
@ 2010-11-09 10:11   ` Markus Armbruster
  2010-11-09 10:58     ` Alon Levy
  0 siblings, 1 reply; 10+ messages in thread
From: Markus Armbruster @ 2010-11-09 10:11 UTC (permalink / raw)
  To: Alon Levy; +Cc: qemu-devel

Alon Levy <alevy@redhat.com> writes:

> A CCID device is a smart card reader. It is a USB device, defined at [1].
> This patch introduces the usb-ccid device that is a ccid bus. Next patches will
> introduce two card types to use it, a passthru card and an emulated card.
>
>  [1] http://www.usb.org/developers/devclass_docs/DWG_Smart-Card_CCID_Rev110.

The issues I had with v3's PATCH 1/4 have been addressed satisfactorily.

However, 2+3/4 still have the same static debug issue I pointed out for
1/4:

    Wait a sec!  Each CCID device has its own property "debug" (defined
    below), but they all copy to the same static debug on
    initialization.  In other words, the device initialized last wins.
    Ugh.

A few more remarks inline.  Not a thorough review, as I'm not familiar
enough with our USB code to do that with reasonable efficiency.

> Signed-off-by: Alon Levy <alevy@redhat.com>
> ---
>  Makefile.objs |    1 +
>  configure     |   12 +
>  hw/ccid.h     |   34 ++
>  hw/usb-ccid.c | 1346 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>  4 files changed, 1393 insertions(+), 0 deletions(-)
>  create mode 100644 hw/ccid.h
>  create mode 100644 hw/usb-ccid.c
>
> diff --git a/Makefile.objs b/Makefile.objs
> index f07fb01..5b52625 100644
> --- a/Makefile.objs
> +++ b/Makefile.objs
> @@ -174,6 +174,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
>  hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
>  hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
>  hw-obj-$(CONFIG_DMA) += dma.o
> +hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o
>  
>  # PPC devices
>  hw-obj-$(CONFIG_OPENPIC) += openpic.o
> diff --git a/configure b/configure
> index f62c1fe..15aee9e 100755
> --- a/configure
> +++ b/configure
> @@ -332,6 +332,7 @@ zero_malloc=""
>  trace_backend="nop"
>  trace_file="trace"
>  spice=""
> +smartcard="no"
>  
>  # OS specific
>  if check_define __linux__ ; then
> @@ -739,6 +740,10 @@ for opt do
>    ;;
>    --enable-vhost-net) vhost_net="yes"
>    ;;
> +  --disable-smartcard) smartcard="no"
> +  ;;
> +  --enable-smartcard) smartcard="yes"
> +  ;;
>    --*dir)
>    ;;
>    *) echo "ERROR: unknown option $opt"; show_help="yes"
> @@ -934,6 +939,8 @@ echo "  --trace-file=NAME        Full PATH,NAME of file to store traces"
>  echo "                           Default:trace-<pid>"
>  echo "  --disable-spice          disable spice"
>  echo "  --enable-spice           enable spice"
> +echo "  --disable-smartcard      disable smartcard support"
> +echo "  --enable-smartcard       enable smartcard support"
>  echo ""
>  echo "NOTE: The object files are built at the place where configure is launched"
>  exit 1
> @@ -2338,6 +2345,7 @@ echo "vhost-net support $vhost_net"
>  echo "Trace backend     $trace_backend"
>  echo "Trace output file $trace_file-<pid>"
>  echo "spice support     $spice"
> +echo "smartcard support $smartcard"
>  
>  if test $sdl_too_old = "yes"; then
>  echo "-> Your SDL version is too old - please upgrade to have SDL support"
> @@ -2601,6 +2609,10 @@ if test "$spice" = "yes" ; then
>    echo "CONFIG_SPICE=y" >> $config_host_mak
>  fi
>  
> +if test "$smartcard" = "yes" ; then
> +  echo "CONFIG_SMARTCARD=y" >> $config_host_mak
> +fi
> +
>  # XXX: suppress that
>  if [ "$bsd" = "yes" ] ; then
>    echo "CONFIG_BSD=y" >> $config_host_mak
> diff --git a/hw/ccid.h b/hw/ccid.h
> new file mode 100644
> index 0000000..a38f971
> --- /dev/null
> +++ b/hw/ccid.h
> @@ -0,0 +1,34 @@
> +#ifndef __CCID_H__
> +#define __CCID_H__
> +
> +#include "qdev.h"
> +
> +typedef struct CCIDCardState CCIDCardState;
> +typedef struct CCIDCardInfo CCIDCardInfo;
> +
> +struct CCIDCardState {
> +    DeviceState qdev;
> +};
> +
> +struct CCIDCardInfo {
> +    DeviceInfo qdev;
> +    void (*print)(Monitor *mon, CCIDCardState *card, int indent);
> +    const uint8_t *(*get_atr)(CCIDCardState *card, uint32_t *len);
> +    void (*apdu_from_guest)(CCIDCardState *card, const uint8_t *apdu, uint32_t len);
> +    int (*exitfn)(CCIDCardState *card);
> +    int (*initfn)(CCIDCardState *card);
> +};
> +
> +void ccid_card_send_apdu_to_guest(CCIDCardState *card, uint8_t* apdu, uint32_t len);
> +void ccid_card_card_removed(CCIDCardState *card);
> +void ccid_card_card_inserted(CCIDCardState *card);
> +void ccid_card_card_error(CCIDCardState *card, uint64_t error);
> +void ccid_card_qdev_register(CCIDCardInfo *card);
> +
> +/* support guest visible insertion/removal of ccid devices based on actual
> + * devices connected/removed. Called by card implementation (passthru, local) */
> +int ccid_card_ccid_attach(CCIDCardState *card);
> +void ccid_card_ccid_detach(CCIDCardState *card);
> +
> +#endif // __CCID_H__
> +
> diff --git a/hw/usb-ccid.c b/hw/usb-ccid.c
> new file mode 100644
> index 0000000..157405a
> --- /dev/null
> +++ b/hw/usb-ccid.c
> @@ -0,0 +1,1346 @@
> +/*
> + * CCID Device emulation
> + *
> + * Based on usb-serial.c:
> + * Copyright (c) 2006 CodeSourcery.
> + * Copyright (c) 2008 Samuel Thibault <samuel.thibault@ens-lyon.org>
> + * Written by Paul Brook, reused for FTDI by Samuel Thibault,
> + * Reused for CCID by Alon Levy.
> + * Contributed to by Robert Relyea
> + * Copyright (c) 2010 Red Hat.
> + *
> + * This code is licenced under the LGPL.
> + */
> +
> +/* References:
> + *
> + * CCID Specification Revision 1.1 April 22nd 2005
> + *  "Universal Serial Bus, Device Class: Smart Card"
> + *  Specification for Integrated Circuit(s) Cards Interface Devices
> + *
> + * KNOWN BUGS
> + * 1. remove/insert can sometimes result in removed state instead of inserted.
> + * This is a result of the following:
> + *  symptom: dmesg shows ERMOTEIO (-121), pcscd shows -99. Thsi happens

Typo "thsi".

> + *  when we send a too short packet, seen in uhci-usb.c, resulting from
> + *  a urb requesting SPD and us returning a smaller packet.
> + *  Not sure which messages trigger this.
> + *
> + */
> +
> +#include "qemu-common.h"
> +#include "qemu-error.h"
> +#include "usb.h"
> +#include "monitor.h"
> +
> +#include "hw/ccid.h"
> +
> +//#define DEBUG_CCID
> +
> +#define DPRINTF(s, lvl, fmt, ...) \
> +do { if (lvl <= s->debug) { printf("usb-ccid: " fmt , ## __VA_ARGS__); } } while (0)
> +
> +#define CCID_DEV_NAME "usb-ccid"
> +
> +/* The two options for variable sized buffers:
> + * make them constant size, for large enough constant,
> + * or handle the migration complexity - VMState doesn't handle this case.
> + * sizes are expected never to be exceeded, unless client misbehaves. */

What happens when it misbehaves?

> +#define BULK_OUT_DATA_SIZE 65536
> +#define PENDING_ANSWERS_NUM 128
> +
> +#define BULK_IN_BUF_SIZE 384
> +#define BULK_IN_PENDING_NUM 8
> +
> +#define InterfaceOutClass    ((USB_DIR_OUT|USB_TYPE_CLASS|USB_RECIP_INTERFACE)<<8)
> +#define InterfaceInClass     ((USB_DIR_IN |USB_TYPE_CLASS|USB_RECIP_INTERFACE)<<8)
> +
> +#define CCID_CONTROL_ABORT                  0x1
> +#define CCID_CONTROL_GET_CLOCK_FREQUENCIES  0x2
> +#define CCID_CONTROL_GET_DATA_RATES         0x3
> +
> +#define CCID_PRODUCT_DESCRIPTION        "QEMU USB CCID"
> +#define CCID_VENDOR_DESCRIPTION         "QEMU " QEMU_VERSION
> +#define CCID_INTERFACE_NAME             "CCID Interface"
> +#define CCID_SERIAL_NUMBER_STRING       "1"
> +/* Using Gemplus Vendor and Product id
> +  Effect on various drivers:
> +  * usbccid.sys (winxp, others untested) is a class driver so it doesn't care.
> +  * linux has a number of class drivers, but openct filters based on
> +    vendor/product (/etc/openct.conf under fedora), hence Gemplus.
> + */
> +#define CCID_VENDOR_ID                  0x08e6
> +#define CCID_PRODUCT_ID                 0x4433
> +#define CCID_DEVICE_VERSION             0x0000
> +
> +/* BULK_OUT messages from PC to Reader
> +   Defined in CCID Rev 1.1 6.1 (page 26)
> + */
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn              0x62
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff             0x63
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus           0x65
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock                0x6f
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters           0x6c
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters         0x6d
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters           0x61
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_Escape                  0x6b
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_IccClock                0x6e
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_T0APDU                  0x6a
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_Secure                  0x69
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical              0x71
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_Abort                   0x72
> +#define CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency 0x73
> +
> +/* BULK_IN messages from Reader to PC
> +   Defined in CCID Rev 1.1 6.2 (page 48)
> + */
> +#define CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock               0x80
> +#define CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus              0x81
> +#define CCID_MESSAGE_TYPE_RDR_to_PC_Parameters              0x82
> +#define CCID_MESSAGE_TYPE_RDR_to_PC_Escape                  0x83
> +#define CCID_MESSAGE_TYPE_RDR_to_PC_DataRateAndClockFrequency 0x84
> +
> +/* INTERRUPT_IN messages from Reader to PC
> +   Defined in CCID Rev 1.1 6.3 (page 56)
> + */
> +#define CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange        0x50
> +#define CCID_MESSAGE_TYPE_RDR_to_PC_HardwareError           0x51
> +
> +/* Endpoints for CCID - addresses are up to us to decide.
> +   To support slot insertion and removal we must have an interrupt in ep
> +   in addition we need a bulk in and bulk out ep
> +   5.2, page 20
> + */
> +#define CCID_INT_IN_EP       1
> +#define CCID_BULK_IN_EP      2
> +#define CCID_BULK_OUT_EP     3
> +
> +/* bmSlotICCState masks */
> +#define SLOT_0_STATE_MASK    1
> +#define SLOT_0_CHANGED_MASK  2
> +
> +/* Status codes that go in bStatus (see 6.2.6) */
> +enum {
> +    ICC_STATUS_PRESENT_ACTIVE = 0,
> +    ICC_STATUS_PRESENT_INACTIVE,
> +    ICC_STATUS_NOT_PRESENT
> +};
> +
> +enum {
> +    COMMAND_STATUS_NO_ERROR = 0,
> +    COMMAND_STATUS_FAILED,
> +    COMMAND_STATUS_TIME_EXTENSION_REQUIRED
> +};
> +
> +/* Error codes that go in bError (see 6.2.6)
> + */
> +enum {
> +    ERROR_CMD_NOT_SUPPORTED = 0,
> +    ERROR_CMD_ABORTED       = -1,
> +    ERROR_ICC_MUTE          = -2,
> +    ERROR_XFR_PARITY_ERROR  = -3,
> +    ERROR_XFR_OVERRUN       = -4,
> +    ERROR_HW_ERROR          = -5,
> +};
> +
> +/* 6.2.6 RDR_to_PC_SlotStatus definitions */
> +enum {
> +    CLOCK_STATUS_RUNNING = 0,
> +    /* 0 - Clock Running, 1 - Clock stopped in State L, 2 - H,
> +       3 - unkonwn state. rest are RFU
> +     */
> +};
> +
> +typedef struct __attribute__ ((__packed__)) {
> +    uint8_t     bMessageType;
> +    uint32_t    dwLength;
> +    uint8_t     bSlot;
> +    uint8_t     bSeq;
> +} CCID_Header;
> +
> +typedef struct __attribute__ ((__packed__)) {
> +    CCID_Header hdr;
> +    uint8_t     bStatus;        /* Only used in BULK_IN */
> +    uint8_t     bError;         /* Only used in BULK_IN */
> +} CCID_BULK_IN;
> +
> +typedef struct __attribute__ ((__packed__)) {
> +    CCID_BULK_IN b;
> +    uint8_t     bClockStatus;
> +} CCID_SlotStatus;
> +
> +typedef struct __attribute__ ((__packed__)) {
> +    CCID_BULK_IN b;
> +    uint8_t     bProtocolNum;
> +    uint8_t     abProtocolDataStructure[0];
> +} CCID_Parameter;
> +
> +typedef struct __attribute__ ((__packed__)) {
> +    CCID_BULK_IN b;
> +    uint8_t      bChainParameter;
> +    uint8_t      abData[0];
> +} CCID_DataBlock;
> +
> +/* 6.1.4 PC_to_RDR_XfrBlock */
> +typedef struct __attribute__ ((__packed__)) {
> +    CCID_Header  hdr;
> +    uint8_t      bBWI; /* Block Waiting Timeout */
> +    uint16_t     wLevelParameter;
> +    uint8_t      abData[0];
> +} CCID_XferBlock;
> +
> +typedef struct __attribute__ ((__packed__)) {
> +    CCID_Header hdr;
> +    uint8_t     bPowerSelect;
> +    uint16_t    abRFU;
> +} CCID_IccPowerOn;
> +
> +typedef struct __attribute__ ((__packed__)) {
> +    CCID_Header hdr;
> +    uint16_t    abRFU;
> +} CCID_IccPowerOff;
> +
> +typedef struct __attribute__ ((__packed__)) {
> +    CCID_Header hdr;
> +    uint8_t     bProtocolNum;
> +    uint8_t    abProtocolDataStructure[0];
> +} CCID_SetParameter;
> +
> +typedef struct {
> +    uint8_t     bMessageType; /* CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange */
> +    uint8_t     bmSlotICCState;
> +} CCID_Notify_Slot_Change;
> +
> +/* used for DataBlock response to XferBlock */
> +typedef struct answer_t {
> +    uint8_t slot;
> +    uint8_t seq;
> +} answer_t;
> +
> +/* pending BULK_IN messages */
> +typedef struct bulk_in_t {
> +    uint8_t  data[BULK_IN_BUF_SIZE];
> +    uint32_t len;
> +    uint32_t pos;
> +} bulk_in_t;
> +
> +enum {
> +    MIGRATION_NONE,
> +    MIGRATION_MIGRATED,
> +};
> +
> +typedef struct CCIDBus CCIDBus;
> +typedef struct USBCCIDState USBCCIDState;
> +
> +#define MAX_PROTOCOL_SIZE   7
> +
> +/**
> + * powered - defaults to true, changed by PowerOn/PowerOff messages
> + */
> +struct USBCCIDState {
> +    USBDevice dev;
> +    CCIDBus *bus;
> +    CCIDCardState *card;
> +    CCIDCardInfo *cardinfo; /* caching the info pointer */
> +    uint8_t  debug;
> +    uint8_t  auto_attach;
> +    bulk_in_t bulk_in_pending[BULK_IN_PENDING_NUM]; /* circular */
> +    uint32_t bulk_in_pending_start;
> +    uint32_t bulk_in_pending_end; /* first free */
> +    uint32_t bulk_in_pending_num;
> +    bulk_in_t *current_bulk_in;
> +    uint8_t  bulk_out_data[BULK_OUT_DATA_SIZE];
> +    uint32_t bulk_out_pos;
> +    uint8_t  bmSlotICCState;
> +    uint8_t  powered;
> +    uint8_t  notify_slot_change;
> +    uint64_t last_answer_error;
> +    answer_t pending_answers[PENDING_ANSWERS_NUM];
> +    uint32_t pending_answers_start;
> +    uint32_t pending_answers_end;
> +    uint32_t pending_answers_num;
> +    uint8_t  bError;
> +    uint8_t  bmCommandStatus;
> +    uint8_t  bProtocolNum;
> +    uint8_t  abProtocolDataStructure[MAX_PROTOCOL_SIZE];
> +    uint32_t ulProtocolDataStructureSize;
> +    uint8_t  attached_vmstate;
> +    uint32_t state_vmstate;
> +    uint8_t  migration_state;
> +    uint32_t migration_target_ip;
> +    uint16_t migration_target_port;
> +};
> +
> +/* Slot specific variables. We emulate a single slot card reader.
> + */
> +
> +
> +/* CCID Spec chapter 4: CCID uses a standard device descriptor per Chapter 9,
> + * "USB Device Framework", section 9.6.1, in the Universal Serial Bus
> + * Specification.
> + *
> + * This device implemented based on the spec and with an Athena Smart Card
> + * Reader as reference:
> + *   0dc3:1004 Athena Smartcard Solutions, Inc.
> + */
> +
> +static const uint8_t qemu_ccid_dev_descriptor[] = {
> +        0x12,       /*  u8 bLength; */
> +        USB_DT_DEVICE, /*  u8 bDescriptorType; Device */
> +        0x10, 0x01, /*  u16 bcdUSB; v1.1 */
> +
> +        0x00,       /*  u8  bDeviceClass; */
> +        0x00,       /*  u8  bDeviceSubClass; */
> +        0x00,       /*  u8  bDeviceProtocol; [ low/full speeds only ] */
> +        0x40,       /*  u8  bMaxPacketSize0; 8 Bytes (valid: 8,16,32,64) */
> +
> +        /* Vendor and product id are arbitrary.  */
> +                    /*  u16 idVendor  */
> +        CCID_VENDOR_ID & 0xff, CCID_VENDOR_ID >> 8,
> +                    /*  u16 idProduct */
> +        CCID_PRODUCT_ID & 0xff, CCID_PRODUCT_ID >> 8,
> +                    /*  u16 bcdDevice */
> +        CCID_DEVICE_VERSION & 0xff, CCID_DEVICE_VERSION >> 8,
> +        0x01,       /*  u8  iManufacturer; */
> +        0x02,       /*  u8  iProduct; */
> +        0x03,       /*  u8  iSerialNumber; */
> +        0x01,       /*  u8  bNumConfigurations; */
> +};
> +
> +static const uint8_t qemu_ccid_config_descriptor[] = {
> +
> +        /* one configuration */
> +        0x09,       /*  u8  bLength; */
> +        USB_DT_CONFIG, /*  u8  bDescriptorType; Configuration */
> +        0x5d, 0x00, /*  u16 wTotalLength; 9+9+54+7+7+7 */
> +        0x01,       /*  u8  bNumInterfaces; (1) */
> +        0x01,       /*  u8  bConfigurationValue; */
> +        0x00,       /*  u8  iConfiguration; */
> +        0xe0,       /*  u8  bmAttributes;
> +                                 Bit 7: must be set,
> +                                     6: Self-powered,
> +                                     5: Remote wakeup,
> +                                     4..0: resvd */
> +        100/2,      /*  u8  MaxPower; 50 == 100mA */
> +
> +        /* one interface */
> +        0x09,       /*  u8  if_bLength; */
> +        USB_DT_INTERFACE, /*  u8  if_bDescriptorType; Interface */
> +        0x00,       /*  u8  if_bInterfaceNumber; */
> +        0x00,       /*  u8  if_bAlternateSetting; */
> +        0x03,       /*  u8  if_bNumEndpoints; */
> +        0x0b,       /*  u8  if_bInterfaceClass; Smart Card Device Class */
> +        0x00,       /*  u8  if_bInterfaceSubClass; Subclass code */
> +        0x00,       /*  u8  if_bInterfaceProtocol; Protocol code */
> +        0x04,       /*  u8  if_iInterface; Index of string descriptor */
> +
> +        /* Smart Card Device Class Descriptor */
> +        0x36,       /*  u8  bLength; */
> +        0x21,       /*  u8  bDescriptorType; Functional */
> +        0x10, 0x01, /*  u16 bcdCCID; CCID Specification Release Number. */
> +        0x00,       /*  u8  bMaxSlotIndex; The index of the highest available
> +                        slot on this device. All slots are consecutive starting
> +                        at 00h. */
> +        0x07,       /*  u8  bVoltageSupport; 01h - 5.0v, 02h - 3.0, 03 - 1.8 */
> +
> +        0x03, 0x00, /*  u32 dwProtocols; RRRR PPPP. RRRR = 0000h.*/
> +        0x00, 0x00, /*  PPPP: 0001h = Protocol T=0, 0002h = Protocol T=1 */
> +                    /*  u32 dwDefaultClock; in kHZ (0x0fa0 is 4 MHz) */
> +        0xa0, 0x0f, 0x00, 0x00,
> +                    /*  u32 dwMaximumClock; */
> +        0x00, 0x00, 0x01, 0x00,
> +        0x00,       /*  u8 bNumClockSupported; 0 means just the default and max. */
> +                    /*  u32 dwDataRate ;bps. 9600 == 00002580h */
> +        0x80, 0x25, 0x00, 0x00,
> +                    /*  u32 dwMaxDataRate ; 11520 bps == 0001C200h */
> +        0x00, 0xC2, 0x01, 0x00,
> +        0x00,       /*  u8  bNumDataRatesSupported; 00 means all rates between
> +                     *      default and max */
> +                    /*  u32 dwMaxIFSD; maximum IFSD supported by CCID for protocol
> +                     *      T=1 (Maximum seen from various cards) */
> +        0xfe, 0x00, 0x00, 0x00,
> +                    /*  u32 dwSyncProtocols; 1 - 2-wire, 2 - 3-wire, 4 - I2C */
> +        0x00, 0x00, 0x00, 0x00,
> +                    /*  u32 dwMechanical;  0 - no special characteristics. */
> +        0x00, 0x00, 0x00, 0x00,
> +                    /*  u32 dwFeatures;
> +                     *  0 - No special characteristics
> +                     *  + 2 Automatic parameter configuration based on ATR data
> +                     *  + 4 Automatic activation of ICC on inserting
> +                     *  + 8 Automatic ICC voltage selection
> +                     *  + 10 Automatic ICC clock frequency change
> +                     *  + 20 Automatic baud rate change
> +                     *  + 40 Automatic parameters negotiation made by the CCID
> +                     *  + 80 automatic PPS made by the CCID
> +                     *  100 CCID can set ICC in clock stop mode
> +                     *  200 NAD value other then 00 accepted (T=1 protocol)
> +                     *  + 400 Automatic IFSD exchange as first exchange (T=1)
> +                     *  One of the following only:
> +                     *  + 10000 TPDU level exchanges with CCID
> +                     *  20000 Short APDU level exchange with CCID
> +                     *  40000 Short and Extended APDU level exchange with CCID
> +                     *
> +                     *  + 100000 USB Wake up signaling supported on card insertion
> +                     *  and removal. Must set bit 5 in bmAttributes in Configuration
> +                     *  descriptor if 100000 is set.*/
> +        0xfe, 0x04, 0x11, 0x00,
> +                    /*  u32 dwMaxCCIDMessageLength; For extended APDU in [261 + 10
> +                     *  , 65544 + 10]. Otherwise the minimum is wMaxPacketSize of
> +                     *  the Bulk-OUT endpoint */
> +        0x12, 0x00, 0x01, 0x00,
> +        0xFF,       /*  u8  bClassGetResponse; Significant only for CCID that
> +                     *  offers an APDU level for exchanges. Indicates the default
> +                     *  class value used by the CCID when it sends a Get Response
> +                     *  command to perform the transportation of an APDU by T=0
> +                     *  protocol
> +                     *  FFh indicates that the CCID echos the class of the APDU.
> +                     */
> +        0xFF,       /*  u8  bClassEnvelope; EAPDU only. Envelope command for T=0 */
> +        0x00, 0x00, /*  u16 wLcdLayout; XXYY Number of lines (XX) and chars per
> +                     *  line for LCD display used for PIN entry. 0000 - no LCD */
> +        0x01,       /*  u8  bPINSupport; 01h PIN Verification,
> +                     *                   02h PIN Modification */
> +        0x01,       /*  u8  bMaxCCIDBusySlots; */
> +
> +        /* Interrupt-IN endpoint */
> +        0x07,       /*  u8  ep_bLength; */
> +                    /*  u8  ep_bDescriptorType; Endpoint */
> +        USB_DT_ENDPOINT,
> +                    /*  u8  ep_bEndpointAddress; IN Endpoint 1 */
> +        0x80 | CCID_INT_IN_EP,
> +        0x03,       /*  u8  ep_bmAttributes; Interrupt */
> +        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
> +        0xff,       /*  u8  ep_bInterval; */
> +
> +        /* Bulk-In endpoint */
> +        0x07,       /*  u8  ep_bLength; */
> +                    /*  u8  ep_bDescriptorType; Endpoint */
> +        USB_DT_ENDPOINT,
> +                    /*  u8  ep_bEndpointAddress; IN Endpoint 2 */
> +        0x80 | CCID_BULK_IN_EP,
> +        0x02,       /*  u8  ep_bmAttributes; Bulk */
> +        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
> +        0x00,       /*  u8  ep_bInterval; */
> +
> +        /* Bulk-Out endpoint */
> +        0x07,       /*  u8  ep_bLength; */
> +                    /*  u8  ep_bDescriptorType; Endpoint */
> +        USB_DT_ENDPOINT,
> +                    /*  u8  ep_bEndpointAddress; OUT Endpoint 3 */
> +        CCID_BULK_OUT_EP,
> +        0x02,       /*  u8  ep_bmAttributes; Bulk */
> +        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
> +        0x00,       /*  u8  ep_bInterval; */
> +
> +};
> +
> +static bool ccid_has_pending_answers(USBCCIDState *s)
> +{
> +    return s->pending_answers_num > 0;
> +}
> +
> +static void ccid_clear_pending_answers(USBCCIDState *s)
> +{
> +    s->pending_answers_num = 0;
> +    s->pending_answers_start = 0;
> +    s->pending_answers_end = 0;
> +}
> +
> +static void ccid_print_pending_answers(USBCCIDState *s)
> +{
> +#ifdef DEBUG_CCID
> +    answer_t *answer;
> +    int i, count;
> +
> +    printf("usb-ccid: pending answers:");
> +    if (!ccid_has_pending_answers(s)) {
> +        printf(" empty\n");
> +        return;
> +    }
> +    for (i = s->pending_answers_start, count=s->pending_answers_num ;
> +         count > 0; count--, i++) {
> +        answer = &s->pending_answers[i % PENDING_ANSWERS_NUM];
> +        if (count == 1) {
> +            printf("%d:%d\n", answer->slot, answer->seq);
> +        } else {
> +            printf("%d:%d,", answer->slot, answer->seq);
> +        }
> +    }
> +#endif
> +}
> +
> +static void ccid_add_pending_answer(USBCCIDState *s, CCID_Header *hdr)
> +{
> +    answer_t* answer;
> +
> +    assert(s->pending_answers_num++ < PENDING_ANSWERS_NUM);
> +    answer = &s->pending_answers[(s->pending_answers_end++) % PENDING_ANSWERS_NUM];
> +    answer->slot = hdr->bSlot;
> +    answer->seq = hdr->bSeq;
> +    ccid_print_pending_answers(s);
> +}
> +
> +static void ccid_remove_pending_answer(USBCCIDState *s,
> +    uint8_t *slot, uint8_t *seq)
> +{
> +    answer_t *answer;
> +
> +    assert(s->pending_answers_num-- > 0);
> +    answer = &s->pending_answers[(s->pending_answers_start++) % PENDING_ANSWERS_NUM];
> +    *slot = answer->slot;
> +    *seq = answer->seq;
> +    ccid_print_pending_answers(s);
> +}
> +
> +static void ccid_bulk_in_clear(USBCCIDState *s)
> +{
> +    s->bulk_in_pending_start = 0;
> +    s->bulk_in_pending_end = 0;
> +    s->bulk_in_pending_num = 0;
> +}
> +
> +static void ccid_bulk_in_release(USBCCIDState *s)
> +{
> +    assert(s->current_bulk_in != NULL);
> +    s->current_bulk_in->pos = 0;
> +    s->current_bulk_in = NULL;
> +}
> +
> +static void ccid_bulk_in_get(USBCCIDState *s)
> +{
> +    if (s->current_bulk_in != NULL || s->bulk_in_pending_num == 0) {
> +        return;
> +    }
> +    assert(s->bulk_in_pending_num > 0);
> +    s->bulk_in_pending_num--;
> +    s->current_bulk_in = &s->bulk_in_pending[
> +        (s->bulk_in_pending_start++) % BULK_IN_PENDING_NUM];
> +}
> +
> +static uint8_t* ccid_reserve_recv_buf(USBCCIDState* s, uint16_t len)

Return void * and save the ugly casts in callers.

> +{
> +    bulk_in_t* bulk_in;
> +
> +    DPRINTF(s, 4, "%s: QUEUE: reserve %d bytes\n", __func__, len);
> +
> +    /* look for an existing element */
> +    if (len > BULK_IN_BUF_SIZE) {
> +        printf("usb-ccid.c: %s: len larger then max (%d>%d). bailing out.\n",
> +            __func__, len, BULK_IN_BUF_SIZE);
> +        exit(-1);

Is this guest-triggerable?  If yes, then exit() is wrong.  If no, is it
a symptom of a programming error?  Then use assert().  If no, what is
it?

Aside: I prefer exit(1) over exit(-1).

> +    }
> +    if (s->bulk_in_pending_num >= BULK_IN_PENDING_NUM) {
> +        printf("usb-ccid.c: %s: No free bulk_in buffers. discarding message.\n",
> +                __func__);
> +        return NULL;
> +    }
> +    bulk_in = &s->bulk_in_pending[(s->bulk_in_pending_end++) % BULK_IN_PENDING_NUM];
> +    s->bulk_in_pending_num++;
> +    bulk_in->len = len;
> +    return bulk_in->data;
> +}
> +
> +static void ccid_reset(USBCCIDState *s)
> +{
> +    ccid_bulk_in_clear(s);
> +    ccid_clear_pending_answers(s);
> +}
> +
> +static void ccid_detach(USBCCIDState *s)
> +{
> +    ccid_reset(s);
> +    if (s->auto_attach == 0 && s->dev.attached) {
> +        usb_device_detach(&s->dev);
> +    }
> +}
> +
> +static void ccid_handle_reset(USBDevice *dev)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> +
> +    DPRINTF(s, 1, "Reset\n");
> +
> +    ccid_reset(s);
> +}
> +
> +static int ccid_handle_control(USBDevice *dev, int request, int value,
> +                                  int index, int length, uint8_t *data)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> +    int ret = 0;
> +
> +    DPRINTF(s, 1, "got control %x, value %x\n",request, value);
> +    switch (request) {
> +    case DeviceRequest | USB_REQ_GET_STATUS:
> +        data[0] = (0 << USB_DEVICE_SELF_POWERED) |
> +            (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);
> +        data[1] = 0x00;
> +        ret = 2;
> +        break;
> +    case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
> +        if (value == USB_DEVICE_REMOTE_WAKEUP) {
> +            dev->remote_wakeup = 0;
> +        } else {
> +            goto fail;
> +        }
> +        ret = 0;
> +        break;
> +    case DeviceOutRequest | USB_REQ_SET_FEATURE:
> +        if (value == USB_DEVICE_REMOTE_WAKEUP) {
> +            dev->remote_wakeup = 1;
> +        } else {
> +            goto fail;
> +        }
> +        ret = 0;
> +        break;
> +    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
> +        dev->addr = value;
> +        ret = 0;
> +        break;
> +    case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
> +        switch(value >> 8) {
> +        case USB_DT_DEVICE:
> +            memcpy(data, qemu_ccid_dev_descriptor,
> +                   sizeof(qemu_ccid_dev_descriptor));
> +            ret = sizeof(qemu_ccid_dev_descriptor);
> +            break;
> +        case USB_DT_CONFIG:
> +            memcpy(data, qemu_ccid_config_descriptor,
> +                   sizeof(qemu_ccid_config_descriptor));
> +            ret = sizeof(qemu_ccid_config_descriptor);
> +            break;
> +        case USB_DT_STRING:
> +            switch(value & 0xff) {
> +            case 0:
> +                /* language ids */
> +                data[0] = 4;
> +                data[1] = 3;
> +                data[2] = 0x09;
> +                data[3] = 0x04;
> +                ret = 4;
> +                break;
> +            case 1:
> +                /* vendor description */
> +                ret = set_usb_string(data, CCID_VENDOR_DESCRIPTION);
> +                break;
> +            case 2:
> +                /* product description */
> +                ret = set_usb_string(data, CCID_PRODUCT_DESCRIPTION);
> +                break;
> +            case 3:
> +                /* serial number */
> +                ret = set_usb_string(data, CCID_SERIAL_NUMBER_STRING);
> +                break;
> +            case 4:
> +                /* interface name */
> +                ret = set_usb_string(data, CCID_INTERFACE_NAME);
> +                break;
> +            default:
> +                goto fail;
> +            }
> +            break;
> +        default:
> +            goto fail;
> +        }
> +        break;
> +    case DeviceRequest | USB_REQ_GET_CONFIGURATION:
> +        data[0] = 1;
> +        ret = 1;
> +        break;
> +    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
> +        /* Only one configuration - we just ignore the request */
> +        ret = 0;
> +        break;
> +    case DeviceRequest | USB_REQ_GET_INTERFACE:
> +        data[0] = 0;
> +        ret = 1;
> +        break;
> +    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
> +        ret = 0;
> +        break;
> +    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
> +        ret = 0;
> +        break;
> +
> +        /* Class specific requests.  */
> +    case InterfaceOutClass | CCID_CONTROL_ABORT:
> +        DPRINTF(s, 1, "ccid_control abort UNIMPLEMENTED\n");
> +        ret = USB_RET_STALL;
> +        break;
> +    case InterfaceInClass | CCID_CONTROL_GET_CLOCK_FREQUENCIES:
> +        DPRINTF(s, 1, "ccid_control get clock frequencies UNIMPLEMENTED\n");
> +        ret = USB_RET_STALL;
> +        break;
> +    case InterfaceInClass | CCID_CONTROL_GET_DATA_RATES:
> +        DPRINTF(s, 1, "ccid_control get data rates UNIMPLEMENTED\n");
> +        ret = USB_RET_STALL;
> +        break;
> +    default:
> +    fail:
> +        DPRINTF(s, 1, "got unsupported/bogus control %x, value %x\n", request, value);
> +        ret = USB_RET_STALL;
> +        break;
> +    }
> +    return ret;
> +}
> +
> +static bool ccid_card_inserted(USBCCIDState *s)
> +{
> +    return s->bmSlotICCState & SLOT_0_STATE_MASK;
> +}
> +
> +static uint8_t ccid_card_status(USBCCIDState *s)
> +{
> +    return ccid_card_inserted(s)
> +            ? (s->powered ?
> +                ICC_STATUS_PRESENT_ACTIVE
> +              : ICC_STATUS_PRESENT_INACTIVE
> +              )
> +            : ICC_STATUS_NOT_PRESENT;
> +}
> +
> +static uint8_t ccid_calc_status(USBCCIDState *s)
> +{
> +    /* page 55, 6.2.6, calculation of bStatus from bmICCStatus and
> +       bmCommandStatus
> +     */
> +    uint8_t ret = ccid_card_status(s) | (s->bmCommandStatus << 6);
> +    DPRINTF(s, 4, "status = %d\n", ret);
> +    return ret;
> +}
> +
> +static void ccid_reset_error_status(USBCCIDState* s)
> +{
> +    s->bError = ERROR_CMD_NOT_SUPPORTED;
> +    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
> +}
> +
> +static void ccid_write_slot_status(USBCCIDState* s, CCID_Header* recv)
> +{
> +    CCID_SlotStatus *h = (CCID_SlotStatus*)ccid_reserve_recv_buf(s, sizeof(CCID_SlotStatus));
> +    if (h == NULL) {
> +        return;
> +    }
> +    h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus;
> +    h->b.hdr.dwLength = 0;
> +    h->b.hdr.bSlot = recv->bSlot;
> +    h->b.hdr.bSeq = recv->bSeq;
> +    h->b.bStatus = ccid_calc_status(s);
> +    h->b.bError = s->bError;
> +    h->bClockStatus = CLOCK_STATUS_RUNNING;
> +    ccid_reset_error_status(s);
> +}
> +
> +static void ccid_write_parameters(USBCCIDState* s, CCID_Header* recv)
> +{
> +    CCID_Parameter *h;
> +    uint32_t len = s->ulProtocolDataStructureSize;
> +
> +    h = (CCID_Parameter *)ccid_reserve_recv_buf(s, sizeof(CCID_Parameter) + len);
> +    if (h == NULL) {
> +        return;
> +    }
> +    h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_Parameters;
> +    h->b.hdr.dwLength = 0;
> +    h->b.hdr.bSlot = recv->bSlot;
> +    h->b.hdr.bSeq = recv->bSeq;
> +    h->b.bStatus = ccid_calc_status(s);
> +    h->b.bError = s->bError;
> +    h->bProtocolNum = s->bProtocolNum;
> +    memcpy(h->abProtocolDataStructure, s->abProtocolDataStructure, len);
> +    ccid_reset_error_status(s);
> +}
> +
> +static void ccid_write_data_block(
> +    USBCCIDState* s, uint8_t slot, uint8_t seq,
> +    const uint8_t* data, uint32_t len)
> +{
> +    CCID_DataBlock *p;
> +
> +    p = (CCID_DataBlock*)ccid_reserve_recv_buf(s, sizeof(*p) + len);
> +    if (p == NULL) {
> +        return;
> +    }
> +    p->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock;
> +    p->b.hdr.dwLength = len;
> +    p->b.hdr.bSlot = slot;
> +    p->b.hdr.bSeq = seq;
> +    p->b.bStatus = ccid_calc_status(s);
> +    p->b.bError = s->bError;
> +#ifdef DEBUG_CCID
> +    if (p->b.bError) {
> +        DPRINTF(s, 4, "error %d", p->b.bError);
> +    }
> +#endif
> +    memcpy(p->abData, data, len);
> +    ccid_reset_error_status(s);
> +}
> +
> +static void ccid_write_data_block_answer(USBCCIDState* s,
> +    const uint8_t* data, uint32_t len)
> +{
> +    uint8_t seq;
> +    uint8_t slot;
> +
> +    if (!ccid_has_pending_answers(s)) {
> +        abort();
> +    }
> +    ccid_remove_pending_answer(s, &slot, &seq);
> +    ccid_write_data_block(s, slot, seq, data, len);
> +}
> +
> +static void ccid_write_data_block_atr(USBCCIDState* s, CCID_Header* recv)
> +{
> +    const uint8_t *atr = NULL;
> +    uint32_t len = 0;
> +
> +    if (s->card) {
> +        atr = s->cardinfo->get_atr(s->card, &len);
> +    }
> +    ccid_write_data_block(s, recv->bSlot, recv->bSeq, atr, len);
> +}
> +
> +static void ccid_set_parameters(USBCCIDState *s, CCID_Header *recv)
> +{
> +    CCID_SetParameter *ph = (CCID_SetParameter *) recv;
> +    uint32_t len = 0;
> +    if (ph->bProtocolNum == 0) {
> +        len = 5;
> +    }
> +    if (ph->bProtocolNum == 1) {
> +        len = 7;
> +    }
> +    if (len == 0) {
> +        s->bmCommandStatus = COMMAND_STATUS_FAILED;
> +        s->bError = 7; /* Protocol invalid or not supported */
> +        return;
> +    }
> +    s->bProtocolNum = ph->bProtocolNum;
> +    memcpy(s->abProtocolDataStructure, ph->abProtocolDataStructure, len);
> +    s->ulProtocolDataStructureSize = len;
> +    DPRINTF(s, 1, "%s: using len %d\n", __func__, len);
> +}
> +
> +/* must be 5 bytes for T=0, 7 bytes for T=1
> + * See page 52 */
> +static const uint8_t abDefaultProtocolDataStructure[7] =
> +    { 0x77, 0x00, 0x00, 0x00, 0x00, 0xfe /*IFSC*/, 0x00 /*NAD*/ };
> +
> +static void ccid_reset_parameters(USBCCIDState *s)
> +{
> +   uint32_t len = sizeof(abDefaultProtocolDataStructure);
> +
> +   s->bProtocolNum = 1; /* T=1 */
> +   s->ulProtocolDataStructureSize = len;
> +   memcpy(s->abProtocolDataStructure, abDefaultProtocolDataStructure, len);
> +}
> +
> +static void ccid_report_error_failed(USBCCIDState *s, uint8_t error)
> +{
> +    s->bmCommandStatus = COMMAND_STATUS_FAILED;
> +    s->bError = error;
> +}
> +
> +/* NOTE: only a single slot is supported (SLOT_0)
> + */
> +static void ccid_on_slot_change(USBCCIDState* s, bool full)
> +{
> +    /* RDR_to_PC_NotifySlotChange, 6.3.1 page 56
> +     */
> +    uint8_t current = s->bmSlotICCState;
> +    if (full) {
> +        s->bmSlotICCState |= SLOT_0_STATE_MASK;
> +    } else {
> +        s->bmSlotICCState &= ~SLOT_0_STATE_MASK;
> +    }
> +    if (current != s->bmSlotICCState) {
> +        s->bmSlotICCState |= SLOT_0_CHANGED_MASK;
> +    }
> +    s->notify_slot_change = true;
> +}
> +
> +static void ccid_write_data_block_error(
> +    USBCCIDState *s, uint8_t slot, uint8_t seq)
> +{
> +    ccid_write_data_block(s, slot, seq, NULL, 0);
> +}
> +
> +static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
> +{
> +    if (ccid_card_status(s) != ICC_STATUS_PRESENT_ACTIVE) {
> +        DPRINTF(s, 1, "usb-ccid: not sending apdu to client, no card connected\n");
> +        ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);
> +        return;
> +    }
> +    DPRINTF(s, 1, "%s: seq %d, len %d\n", __FUNCTION__,
> +                recv->hdr.bSeq, recv->hdr.dwLength);
> +    ccid_add_pending_answer(s, (CCID_Header*)recv);
> +    if (s->card) {
> +        s->cardinfo->apdu_from_guest(s->card, recv->abData, recv->hdr.dwLength);
> +    } else {
> +        printf("warning: discarded apdu\n");
> +    }
> +}
> +
> +static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
> +{
> +    CCID_Header* ccid_header;
> +
> +    assert(p->len + s->bulk_out_pos <= BULK_OUT_DATA_SIZE);
> +    ccid_header = (CCID_Header*)s->bulk_out_data;
> +    memcpy(s->bulk_out_data + s->bulk_out_pos, p->data, p->len);
> +    s->bulk_out_pos += p->len;
> +    if (p->len == 64) {
> +        DPRINTF(s, 4, "usb-ccid: bulk_in: expecting more packets (%d/%d)\n",
> +            p->len, ccid_header->dwLength);
> +        return;
> +    }
> +    if (s->bulk_out_pos < 10) {
> +        DPRINTF(s, 1, "%s: bad USB_TOKEN_OUT length, should be at least 10 bytes\n", __func__);
> +    } else {
> +        DPRINTF(s, 3, "%s %x\n", __func__, ccid_header->bMessageType);
> +        switch (ccid_header->bMessageType) {
> +            case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus:
> +                ccid_write_slot_status(s, ccid_header);
> +                break;
> +            case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:
> +                DPRINTF(s, 1, "PowerOn: %d\n",
> +                    ((CCID_IccPowerOn*)(ccid_header))->bPowerSelect);
> +                s->powered = true;
> +                if (!ccid_card_inserted(s)) {
> +                    ccid_report_error_failed(s, ERROR_ICC_MUTE);
> +                }
> +                /* atr is written regardless of error. */
> +                ccid_write_data_block_atr(s, ccid_header);
> +                break;
> +            case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff:
> +                DPRINTF(s, 1, "PowerOff\n");
> +                ccid_reset_error_status(s);
> +                s->powered = false;
> +                ccid_write_slot_status(s, ccid_header);
> +                break;
> +            case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:
> +                ccid_on_apdu_from_guest(s, (CCID_XferBlock*)s->bulk_out_data);
> +                break;
> +            case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters:
> +                ccid_reset_error_status(s);
> +                ccid_set_parameters(s, ccid_header);
> +                ccid_write_parameters(s, ccid_header);
> +                break;
> +            case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters:
> +                ccid_reset_error_status(s);
> +                ccid_reset_parameters(s);
> +                ccid_write_parameters(s, ccid_header);
> +                break;
> +            case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters:
> +                ccid_reset_error_status(s);
> +                ccid_write_parameters(s, ccid_header);
> +                break;
> +            default:
> +                DPRINTF(s, 1, "handle_data: ERROR: unhandled message type %Xh\n",
> +                    ccid_header->bMessageType);
> +                /* the caller is expecting the device to respond, tell it we
> +                 * do't support the operation */
> +                ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
> +                ccid_write_slot_status(s, ccid_header);
> +                break;
> +        }
> +    }
> +    s->bulk_out_pos = 0;
> +}
> +
> +static int ccid_bulk_in_copy_out(USBCCIDState *s, uint8_t *data, int len)
> +{
> +    int ret = 0;
> +
> +    assert(len>0);
> +    ccid_bulk_in_get(s);
> +    if (s->current_bulk_in != NULL) {
> +        ret = MIN(s->current_bulk_in->len - s->current_bulk_in->pos, len);
> +        memcpy(data, s->current_bulk_in->data + s->current_bulk_in->pos, ret);
> +        s->current_bulk_in->pos += ret;
> +        if (s->current_bulk_in->pos == s->current_bulk_in->len) {
> +            ccid_bulk_in_release(s);
> +        }
> +    } else {
> +        ret = USB_RET_NAK; /* return when device has no data - usb 2.0 spec Table 8-4 */
> +    }
> +    if (ret > 0) {
> +        DPRINTF(s, 3, "%s: %d/%d req/act to guest (BULK_IN)\n", __func__, len, ret);
> +    }
> +    if (ret != USB_RET_NAK && ret < len) {
> +        DPRINTF(s, 1, "%s: returning short (EREMOTEIO) %d < %d\n", __func__, ret, len);
> +    }
> +    return ret;
> +}
> +
> +static int ccid_handle_data(USBDevice *dev, USBPacket *p)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> +    int ret = 0;
> +    uint8_t *data = p->data;
> +    int len = p->len;
> +
> +    switch (p->pid) {
> +    case USB_TOKEN_OUT:
> +        ccid_handle_bulk_out(s, p);
> +        break;
> +
> +    case USB_TOKEN_IN:
> +        switch (p->devep & 0xf) {
> +            case CCID_BULK_IN_EP:
> +                if (!len) {
> +                    ret = USB_RET_NAK;
> +                } else {
> +                    ret = ccid_bulk_in_copy_out(s, data, len);
> +                }
> +                break;
> +            case CCID_INT_IN_EP:
> +                if (s->notify_slot_change) {
> +                    /* page 56, RDR_to_PC_NotifySlotChange */
> +                    data[0] = CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange;
> +                    data[1] = s->bmSlotICCState;
> +                    ret = 2;
> +                    s->notify_slot_change = false;
> +                    s->bmSlotICCState &= ~SLOT_0_CHANGED_MASK;
> +                    DPRINTF(s, 2, "handle_data: int_in: notify_slot_change %X, requested len %d\n",
> +                            s->bmSlotICCState, len);
> +                }
> +                break;
> +            default:
> +                DPRINTF(s, 1, "Bad endpoint\n");
> +                break;
> +        }
> +        break;
> +    default:
> +        DPRINTF(s, 1, "Bad token\n");
> +        ret = USB_RET_STALL;
> +        break;
> +    }
> +
> +    return ret;
> +}
> +
> +static void ccid_handle_destroy(USBDevice *dev)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> +
> +    ccid_bulk_in_clear(s);
> +}
> +
> +static void ccid_flush_pending_answers(USBCCIDState *s) {
> +    while (ccid_has_pending_answers(s)) {
> +        ccid_write_data_block_answer(s, NULL, 0);
> +    }
> +}
> +
> +static answer_t *ccid_peek_next_answer(USBCCIDState *s)
> +{
> +    return s->pending_answers_num == 0
> +        ? NULL
> +        : &s->pending_answers[s->pending_answers_start % PENDING_ANSWERS_NUM];
> +}
> +
> +static void ccid_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent)
> +{
> +    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
> +    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, qdev->info);
> +
> +    if (info->print) {
> +        info->print(mon, card, indent);
> +    }
> +}
> +
> +struct CCIDBus {
> +    BusState qbus;
> +};
> +
> +static struct BusInfo ccid_bus_info = {
> +    .name = "ccid-bus",
> +    .size = sizeof(CCIDBus),
> +    .print_dev = ccid_bus_dev_print,
> +};
> +
> +static CCIDBus *ccid_bus_new(DeviceState *dev)
> +{
> +    CCIDBus *bus;
> +
> +    bus = FROM_QBUS(CCIDBus, qbus_create(&ccid_bus_info, dev, NULL));
> +    bus->qbus.allow_hotplug = 1;
> +
> +    return bus;
> +}
> +
> +void ccid_card_send_apdu_to_guest(CCIDCardState *card, uint8_t* apdu, uint32_t len)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> +    answer_t *answer;
> +
> +    if (!ccid_has_pending_answers(s)) {
> +        DPRINTF(s, 1, "CCID ERROR: got an APDU without pending answers\n");
> +        return;
> +    }
> +    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
> +    answer = ccid_peek_next_answer(s);
> +    if (answer == NULL) {
> +        abort();
> +    }
> +    DPRINTF(s, 1, "APDU returned to guest %d (answer seq %d, slot %d)\n",
> +        len, answer->seq, answer->slot);
> +    ccid_write_data_block_answer(s, apdu, len);
> +}
> +
> +void ccid_card_card_removed(CCIDCardState *card)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> +
> +    ccid_on_slot_change(s, false);
> +    ccid_flush_pending_answers(s);
> +    ccid_reset(s);
> +}
> +
> +int ccid_card_ccid_attach(CCIDCardState *card)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> +
> +    DPRINTF(s, 1, "CCID Attach\n");
> +    if (s->auto_attach==0 && !s->dev.attached) {
> +        usb_device_attach(&s->dev);
> +        return 0;
> +    } else {
> +        if (s->migration_state == MIGRATION_MIGRATED) {
> +            s->migration_state = MIGRATION_NONE;
> +            return 0;
> +        } else {
> +            return -1;
> +        }
> +    }
> +}
> +
> +void ccid_card_ccid_detach(CCIDCardState *card)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> +
> +    DPRINTF(s, 1, "CCID Detach\n");
> +    if (ccid_card_inserted(s)) {
> +        ccid_on_slot_change(s, false);
> +    }
> +    ccid_detach(s);
> +}
> +
> +void ccid_card_card_error(CCIDCardState *card, uint64_t error)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> +
> +    s->bmCommandStatus = COMMAND_STATUS_FAILED;
> +    s->last_answer_error = error;
> +    DPRINTF(s, 1, "VSC_Error: %lX\n", s->last_answer_error);
> +    /* TODO: these error's should be more verbose and propogated to the guest.
> +     * */

Impact of not propagating them?

> +    ccid_write_data_block_answer(s, NULL, 0);
> +}
> +
> +void ccid_card_card_inserted(CCIDCardState *card)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> +
> +    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
> +    ccid_flush_pending_answers(s);
> +    ccid_on_slot_change(s, true);
> +}
> +
> +static int ccid_card_exit(DeviceState *qdev)
> +{
> +    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
> +    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, qdev->info);
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> +
> +    if (ccid_card_inserted(s)) {
> +        ccid_card_card_removed(card);
> +    }
> +    if (info->exitfn) {
> +        return info->exitfn(card);
> +    }
> +    return 0;
> +}
> +
> +static int ccid_card_init(DeviceState *qdev, DeviceInfo *base)
> +{
> +    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
> +    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, base);
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> +
> +    s->card = card;
> +    s->cardinfo = info;
> +    if (info->initfn) {
> +        return info->initfn(card);
> +    }
> +    return 0;
> +}
> +
> +void ccid_card_qdev_register(CCIDCardInfo *card)
> +{
> +    card->qdev.bus_info = &ccid_bus_info;
> +    card->qdev.init = ccid_card_init;
> +    card->qdev.exit = ccid_card_exit;
> +    qdev_register(&card->qdev);
> +}
> +
> +static int ccid_initfn(USBDevice *dev)
> +{
> +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> +
> +    s->bus = ccid_bus_new(&dev->qdev);
> +    s->card = NULL;
> +    s->cardinfo = NULL;
> +    s->migration_state = MIGRATION_NONE;
> +    dev->auto_attach = s->auto_attach;
> +    s->migration_target_ip = 0;
> +    s->migration_target_port = 0;
> +    s->dev.speed = USB_SPEED_FULL;
> +    s->notify_slot_change = false;
> +    s->powered = true;
> +    s->pending_answers_num = 0;
> +    s->last_answer_error = 0;
> +    s->bulk_in_pending_start = 0;
> +    s->bulk_in_pending_end = 0;
> +    s->current_bulk_in = NULL;
> +    ccid_reset_error_status(s);
> +    s->bulk_out_pos = 0;
> +    ccid_reset_parameters(s);
> +    ccid_reset(s);
> +    return 0;
> +}
> +
> +static int ccid_post_load(void *opaque, int version_id)
> +{
> +    USBCCIDState *s = opaque;
> +
> +    if (s->auto_attach == 0 && s->attached_vmstate && !s->dev.attached) {
> +        usb_device_attach(&s->dev);
> +    }
> +    // This must be done after usb_device_attach, which sets state to ATTACHED,
> +    // while it must be DEFAULT in order to accept packets (like it is after
> +    // reset, but reset will reset our addr and call our reset handler which
> +    // may change state, and we don't want to do that when migrating).
> +    s->dev.state = s->state_vmstate;
> +    return 0;
> +}
> +
> +static void ccid_pre_save(void *opaque)
> +{
> +    USBCCIDState *s = opaque;
> +
> +    s->attached_vmstate = s->dev.attached;
> +    s->state_vmstate = s->dev.state;
> +    if (s->dev.attached) {
> +        // migrating an open device, ignore reconnection CHR_EVENT to avoid an
> +        // erronous detach.
> +        s->migration_state = MIGRATION_MIGRATED;
> +    }
> +}
> +
> +static VMStateDescription bulk_in_t_vmstate = {
> +    .name = "bulk_in_t",
> +    .version_id = 1,
> +    .minimum_version_id = 1,
> +    .fields = (VMStateField []) {
> +        VMSTATE_BUFFER(data, bulk_in_t),
> +        VMSTATE_UINT32(len, bulk_in_t),
> +        VMSTATE_UINT32(pos, bulk_in_t),
> +        VMSTATE_END_OF_LIST()
> +    }
> +};
> +
> +static VMStateDescription answer_t_vmstate = {
> +    .name = "answer_t",
> +    .version_id = 1,
> +    .minimum_version_id = 1,
> +    .fields = (VMStateField []) {
> +        VMSTATE_UINT8(slot, answer_t),
> +        VMSTATE_UINT8(seq, answer_t),
> +        VMSTATE_END_OF_LIST()
> +    }
> +};
> +
> +static VMStateDescription usb_device_vmstate = {
> +    .name = "usb_device",
> +    .version_id = 1,
> +    .minimum_version_id = 1,
> +    .fields = (VMStateField []) {
> +        //int speed;
> +        VMSTATE_UINT8(addr, USBDevice),
> +        //VMSTATE_BUFFER(product_desc, USBDevice), // char, not uint8_t - casting error

Can't see char nor uint8_t here.  Please explain.

> +        //int auto_attach;
> +        //int attached;
> +        //int state;
> +        VMSTATE_BUFFER(setup_buf, USBDevice),
> +        VMSTATE_BUFFER(data_buf, USBDevice),
> +        // int remote_wakeup;
> +        // int setup_state;
> +        // int setup_len;
> +        // int setup_index;
> +        VMSTATE_END_OF_LIST()
> +    }

What's the commented out code good for?

> +};
> +
> +static VMStateDescription ccid_vmstate = {
> +    .name = CCID_DEV_NAME,
> +    .version_id = 1,
> +    .minimum_version_id = 1,
> +    .post_load = ccid_post_load,
> +    .pre_save = ccid_pre_save,
> +    .fields = (VMStateField []) {
> +        VMSTATE_STRUCT(dev, USBCCIDState, 1, usb_device_vmstate, USBDevice),
> +        VMSTATE_UINT8(debug, USBCCIDState),
> +        VMSTATE_UINT8(auto_attach, USBCCIDState),
> +        VMSTATE_BUFFER(bulk_out_data, USBCCIDState),
> +        VMSTATE_UINT32(bulk_out_pos, USBCCIDState),
> +        VMSTATE_UINT8(bmSlotICCState, USBCCIDState),
> +        VMSTATE_UINT8(powered, USBCCIDState),
> +        VMSTATE_UINT8(notify_slot_change, USBCCIDState),
> +        VMSTATE_UINT64(last_answer_error, USBCCIDState),
> +        VMSTATE_UINT8(bError, USBCCIDState),
> +        VMSTATE_UINT8(bmCommandStatus, USBCCIDState),
> +        VMSTATE_UINT8(bProtocolNum, USBCCIDState),
> +        VMSTATE_BUFFER(abProtocolDataStructure, USBCCIDState),
> +        VMSTATE_UINT32(ulProtocolDataStructureSize, USBCCIDState),
> +        VMSTATE_STRUCT_ARRAY(bulk_in_pending, USBCCIDState,
> +                       BULK_IN_PENDING_NUM, 1, bulk_in_t_vmstate, bulk_in_t),
> +        VMSTATE_UINT32(bulk_in_pending_start, USBCCIDState),
> +        VMSTATE_UINT32(bulk_in_pending_end, USBCCIDState),
> +        VMSTATE_STRUCT_ARRAY(pending_answers, USBCCIDState,
> +                        PENDING_ANSWERS_NUM, 1, answer_t_vmstate, answer_t),
> +        VMSTATE_UINT32(pending_answers_num, USBCCIDState),
> +        VMSTATE_UINT8(migration_state, USBCCIDState),
> +        VMSTATE_UINT8(attached_vmstate, USBCCIDState),
> +        VMSTATE_UINT32(state_vmstate, USBCCIDState),
> +        VMSTATE_END_OF_LIST()
> +    }
> +};
> +
> +static struct USBDeviceInfo ccid_info = {
> +    .product_desc   = "QEMU USB CCID",
> +    .qdev.name      = CCID_DEV_NAME,
> +    .qdev.size      = sizeof(USBCCIDState),
> +    .qdev.vmsd      = &ccid_vmstate,
> +    .init           = ccid_initfn,
> +    .handle_packet  = usb_generic_handle_packet,
> +    .handle_reset   = ccid_handle_reset,
> +    .handle_control = ccid_handle_control,
> +    .handle_data    = ccid_handle_data,
> +    .handle_destroy = ccid_handle_destroy,
> +    .usbdevice_name = "ccid",
> +    .qdev.props     = (Property[]) {
> +        DEFINE_PROP_UINT8("auto_attach", USBCCIDState, auto_attach, 0),
> +        DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
> +        DEFINE_PROP_END_OF_LIST(),
> +    },
> +};
> +
> +
> +static void ccid_register_devices(void)
> +{
> +    usb_qdev_register(&ccid_info);
> +}
> +device_init(ccid_register_devices)

^ permalink raw reply	[flat|nested] 10+ messages in thread

* Re: [Qemu-devel] [PATCH 0/4] usb-ccid (v4)
  2010-10-24 13:18 [Qemu-devel] [PATCH 0/4] usb-ccid (v4) Alon Levy
                   ` (3 preceding siblings ...)
  2010-10-24 13:18 ` [Qemu-devel] [PATCH 4/4] ccid: add docs Alon Levy
@ 2010-11-09 10:14 ` Markus Armbruster
  4 siblings, 0 replies; 10+ messages in thread
From: Markus Armbruster @ 2010-11-09 10:14 UTC (permalink / raw)
  To: Alon Levy; +Cc: qemu-devel

Patches 3 and 4 have a number of TODO comments.  That doesn't have to
mean the code isn't ready for merging.  But I'd like to see any missing
bits clearly documented in the commit messages.

^ permalink raw reply	[flat|nested] 10+ messages in thread

* Re: [Qemu-devel] [PATCH 1/4] usb-ccid: add CCID bus
  2010-11-09 10:11   ` Markus Armbruster
@ 2010-11-09 10:58     ` Alon Levy
  0 siblings, 0 replies; 10+ messages in thread
From: Alon Levy @ 2010-11-09 10:58 UTC (permalink / raw)
  To: Markus Armbruster; +Cc: qemu-devel

On Tue, Nov 09, 2010 at 11:11:21AM +0100, Markus Armbruster wrote:
> Alon Levy <alevy@redhat.com> writes:
> 
> > A CCID device is a smart card reader. It is a USB device, defined at [1].
> > This patch introduces the usb-ccid device that is a ccid bus. Next patches will
> > introduce two card types to use it, a passthru card and an emulated card.
> >
> >  [1] http://www.usb.org/developers/devclass_docs/DWG_Smart-Card_CCID_Rev110.
> 
> The issues I had with v3's PATCH 1/4 have been addressed satisfactorily.
> 
> However, 2+3/4 still have the same static debug issue I pointed out for
> 1/4:
> 
>     Wait a sec!  Each CCID device has its own property "debug" (defined
>     below), but they all copy to the same static debug on
>     initialization.  In other words, the device initialized last wins.
>     Ugh.

Major oops. I'll correct that. Rest of the comments addressed below.
(actually I seem to have corrected it locally but never sent it since
I expected a review of v4 to notice other issues too).

> 
> A few more remarks inline.  Not a thorough review, as I'm not familiar
> enough with our USB code to do that with reasonable efficiency.
> 
> > Signed-off-by: Alon Levy <alevy@redhat.com>
> > ---
> >  Makefile.objs |    1 +
> >  configure     |   12 +
> >  hw/ccid.h     |   34 ++
> >  hw/usb-ccid.c | 1346 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> >  4 files changed, 1393 insertions(+), 0 deletions(-)
> >  create mode 100644 hw/ccid.h
> >  create mode 100644 hw/usb-ccid.c
> >
> > diff --git a/Makefile.objs b/Makefile.objs
> > index f07fb01..5b52625 100644
> > --- a/Makefile.objs
> > +++ b/Makefile.objs
> > @@ -174,6 +174,7 @@ hw-obj-$(CONFIG_FDC) += fdc.o
> >  hw-obj-$(CONFIG_ACPI) += acpi.o acpi_piix4.o
> >  hw-obj-$(CONFIG_APM) += pm_smbus.o apm.o
> >  hw-obj-$(CONFIG_DMA) += dma.o
> > +hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o
> >  
> >  # PPC devices
> >  hw-obj-$(CONFIG_OPENPIC) += openpic.o
> > diff --git a/configure b/configure
> > index f62c1fe..15aee9e 100755
> > --- a/configure
> > +++ b/configure
> > @@ -332,6 +332,7 @@ zero_malloc=""
> >  trace_backend="nop"
> >  trace_file="trace"
> >  spice=""
> > +smartcard="no"
> >  
> >  # OS specific
> >  if check_define __linux__ ; then
> > @@ -739,6 +740,10 @@ for opt do
> >    ;;
> >    --enable-vhost-net) vhost_net="yes"
> >    ;;
> > +  --disable-smartcard) smartcard="no"
> > +  ;;
> > +  --enable-smartcard) smartcard="yes"
> > +  ;;
> >    --*dir)
> >    ;;
> >    *) echo "ERROR: unknown option $opt"; show_help="yes"
> > @@ -934,6 +939,8 @@ echo "  --trace-file=NAME        Full PATH,NAME of file to store traces"
> >  echo "                           Default:trace-<pid>"
> >  echo "  --disable-spice          disable spice"
> >  echo "  --enable-spice           enable spice"
> > +echo "  --disable-smartcard      disable smartcard support"
> > +echo "  --enable-smartcard       enable smartcard support"
> >  echo ""
> >  echo "NOTE: The object files are built at the place where configure is launched"
> >  exit 1
> > @@ -2338,6 +2345,7 @@ echo "vhost-net support $vhost_net"
> >  echo "Trace backend     $trace_backend"
> >  echo "Trace output file $trace_file-<pid>"
> >  echo "spice support     $spice"
> > +echo "smartcard support $smartcard"
> >  
> >  if test $sdl_too_old = "yes"; then
> >  echo "-> Your SDL version is too old - please upgrade to have SDL support"
> > @@ -2601,6 +2609,10 @@ if test "$spice" = "yes" ; then
> >    echo "CONFIG_SPICE=y" >> $config_host_mak
> >  fi
> >  
> > +if test "$smartcard" = "yes" ; then
> > +  echo "CONFIG_SMARTCARD=y" >> $config_host_mak
> > +fi
> > +
> >  # XXX: suppress that
> >  if [ "$bsd" = "yes" ] ; then
> >    echo "CONFIG_BSD=y" >> $config_host_mak
> > diff --git a/hw/ccid.h b/hw/ccid.h
> > new file mode 100644
> > index 0000000..a38f971
> > --- /dev/null
> > +++ b/hw/ccid.h
> > @@ -0,0 +1,34 @@
> > +#ifndef __CCID_H__
> > +#define __CCID_H__
> > +
> > +#include "qdev.h"
> > +
> > +typedef struct CCIDCardState CCIDCardState;
> > +typedef struct CCIDCardInfo CCIDCardInfo;
> > +
> > +struct CCIDCardState {
> > +    DeviceState qdev;
> > +};
> > +
> > +struct CCIDCardInfo {
> > +    DeviceInfo qdev;
> > +    void (*print)(Monitor *mon, CCIDCardState *card, int indent);
> > +    const uint8_t *(*get_atr)(CCIDCardState *card, uint32_t *len);
> > +    void (*apdu_from_guest)(CCIDCardState *card, const uint8_t *apdu, uint32_t len);
> > +    int (*exitfn)(CCIDCardState *card);
> > +    int (*initfn)(CCIDCardState *card);
> > +};
> > +
> > +void ccid_card_send_apdu_to_guest(CCIDCardState *card, uint8_t* apdu, uint32_t len);
> > +void ccid_card_card_removed(CCIDCardState *card);
> > +void ccid_card_card_inserted(CCIDCardState *card);
> > +void ccid_card_card_error(CCIDCardState *card, uint64_t error);
> > +void ccid_card_qdev_register(CCIDCardInfo *card);
> > +
> > +/* support guest visible insertion/removal of ccid devices based on actual
> > + * devices connected/removed. Called by card implementation (passthru, local) */
> > +int ccid_card_ccid_attach(CCIDCardState *card);
> > +void ccid_card_ccid_detach(CCIDCardState *card);
> > +
> > +#endif // __CCID_H__
> > +
> > diff --git a/hw/usb-ccid.c b/hw/usb-ccid.c
> > new file mode 100644
> > index 0000000..157405a
> > --- /dev/null
> > +++ b/hw/usb-ccid.c
> > @@ -0,0 +1,1346 @@
> > +/*
> > + * CCID Device emulation
> > + *
> > + * Based on usb-serial.c:
> > + * Copyright (c) 2006 CodeSourcery.
> > + * Copyright (c) 2008 Samuel Thibault <samuel.thibault@ens-lyon.org>
> > + * Written by Paul Brook, reused for FTDI by Samuel Thibault,
> > + * Reused for CCID by Alon Levy.
> > + * Contributed to by Robert Relyea
> > + * Copyright (c) 2010 Red Hat.
> > + *
> > + * This code is licenced under the LGPL.
> > + */
> > +
> > +/* References:
> > + *
> > + * CCID Specification Revision 1.1 April 22nd 2005
> > + *  "Universal Serial Bus, Device Class: Smart Card"
> > + *  Specification for Integrated Circuit(s) Cards Interface Devices
> > + *
> > + * KNOWN BUGS
> > + * 1. remove/insert can sometimes result in removed state instead of inserted.
> > + * This is a result of the following:
> > + *  symptom: dmesg shows ERMOTEIO (-121), pcscd shows -99. Thsi happens
> 
> Typo "thsi".
will fix.

> 
> > + *  when we send a too short packet, seen in uhci-usb.c, resulting from
> > + *  a urb requesting SPD and us returning a smaller packet.
> > + *  Not sure which messages trigger this.
> > + *
> > + */
> > +
> > +#include "qemu-common.h"
> > +#include "qemu-error.h"
> > +#include "usb.h"
> > +#include "monitor.h"
> > +
> > +#include "hw/ccid.h"
> > +
> > +//#define DEBUG_CCID
> > +
> > +#define DPRINTF(s, lvl, fmt, ...) \
> > +do { if (lvl <= s->debug) { printf("usb-ccid: " fmt , ## __VA_ARGS__); } } while (0)
> > +
> > +#define CCID_DEV_NAME "usb-ccid"
> > +
> > +/* The two options for variable sized buffers:
> > + * make them constant size, for large enough constant,
> > + * or handle the migration complexity - VMState doesn't handle this case.
> > + * sizes are expected never to be exceeded, unless client misbehaves. */
> 
> What happens when it misbehaves?
I assert :( My comment is incorrect, it should say guest instead of client - this
bulk_out data is filled from guest messages. So I could detach the device, but
simplest and possibly more correct is to NACK the USB_TOKEN_OUT. Mind you I haven't
tested this code path at all (I'll have to rig a misbehaving driver in the guest, or test
it outside of qemu).

> 
> > +#define BULK_OUT_DATA_SIZE 65536
> > +#define PENDING_ANSWERS_NUM 128
> > +
> > +#define BULK_IN_BUF_SIZE 384
> > +#define BULK_IN_PENDING_NUM 8
> > +
> > +#define InterfaceOutClass    ((USB_DIR_OUT|USB_TYPE_CLASS|USB_RECIP_INTERFACE)<<8)
> > +#define InterfaceInClass     ((USB_DIR_IN |USB_TYPE_CLASS|USB_RECIP_INTERFACE)<<8)
> > +
> > +#define CCID_CONTROL_ABORT                  0x1
> > +#define CCID_CONTROL_GET_CLOCK_FREQUENCIES  0x2
> > +#define CCID_CONTROL_GET_DATA_RATES         0x3
> > +
> > +#define CCID_PRODUCT_DESCRIPTION        "QEMU USB CCID"
> > +#define CCID_VENDOR_DESCRIPTION         "QEMU " QEMU_VERSION
> > +#define CCID_INTERFACE_NAME             "CCID Interface"
> > +#define CCID_SERIAL_NUMBER_STRING       "1"
> > +/* Using Gemplus Vendor and Product id
> > +  Effect on various drivers:
> > +  * usbccid.sys (winxp, others untested) is a class driver so it doesn't care.
> > +  * linux has a number of class drivers, but openct filters based on
> > +    vendor/product (/etc/openct.conf under fedora), hence Gemplus.
> > + */
> > +#define CCID_VENDOR_ID                  0x08e6
> > +#define CCID_PRODUCT_ID                 0x4433
> > +#define CCID_DEVICE_VERSION             0x0000
> > +
> > +/* BULK_OUT messages from PC to Reader
> > +   Defined in CCID Rev 1.1 6.1 (page 26)
> > + */
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn              0x62
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff             0x63
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus           0x65
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock                0x6f
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters           0x6c
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters         0x6d
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters           0x61
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_Escape                  0x6b
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_IccClock                0x6e
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_T0APDU                  0x6a
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_Secure                  0x69
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical              0x71
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_Abort                   0x72
> > +#define CCID_MESSAGE_TYPE_PC_to_RDR_SetDataRateAndClockFrequency 0x73
> > +
> > +/* BULK_IN messages from Reader to PC
> > +   Defined in CCID Rev 1.1 6.2 (page 48)
> > + */
> > +#define CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock               0x80
> > +#define CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus              0x81
> > +#define CCID_MESSAGE_TYPE_RDR_to_PC_Parameters              0x82
> > +#define CCID_MESSAGE_TYPE_RDR_to_PC_Escape                  0x83
> > +#define CCID_MESSAGE_TYPE_RDR_to_PC_DataRateAndClockFrequency 0x84
> > +
> > +/* INTERRUPT_IN messages from Reader to PC
> > +   Defined in CCID Rev 1.1 6.3 (page 56)
> > + */
> > +#define CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange        0x50
> > +#define CCID_MESSAGE_TYPE_RDR_to_PC_HardwareError           0x51
> > +
> > +/* Endpoints for CCID - addresses are up to us to decide.
> > +   To support slot insertion and removal we must have an interrupt in ep
> > +   in addition we need a bulk in and bulk out ep
> > +   5.2, page 20
> > + */
> > +#define CCID_INT_IN_EP       1
> > +#define CCID_BULK_IN_EP      2
> > +#define CCID_BULK_OUT_EP     3
> > +
> > +/* bmSlotICCState masks */
> > +#define SLOT_0_STATE_MASK    1
> > +#define SLOT_0_CHANGED_MASK  2
> > +
> > +/* Status codes that go in bStatus (see 6.2.6) */
> > +enum {
> > +    ICC_STATUS_PRESENT_ACTIVE = 0,
> > +    ICC_STATUS_PRESENT_INACTIVE,
> > +    ICC_STATUS_NOT_PRESENT
> > +};
> > +
> > +enum {
> > +    COMMAND_STATUS_NO_ERROR = 0,
> > +    COMMAND_STATUS_FAILED,
> > +    COMMAND_STATUS_TIME_EXTENSION_REQUIRED
> > +};
> > +
> > +/* Error codes that go in bError (see 6.2.6)
> > + */
> > +enum {
> > +    ERROR_CMD_NOT_SUPPORTED = 0,
> > +    ERROR_CMD_ABORTED       = -1,
> > +    ERROR_ICC_MUTE          = -2,
> > +    ERROR_XFR_PARITY_ERROR  = -3,
> > +    ERROR_XFR_OVERRUN       = -4,
> > +    ERROR_HW_ERROR          = -5,
> > +};
> > +
> > +/* 6.2.6 RDR_to_PC_SlotStatus definitions */
> > +enum {
> > +    CLOCK_STATUS_RUNNING = 0,
> > +    /* 0 - Clock Running, 1 - Clock stopped in State L, 2 - H,
> > +       3 - unkonwn state. rest are RFU
> > +     */
> > +};
> > +
> > +typedef struct __attribute__ ((__packed__)) {
> > +    uint8_t     bMessageType;
> > +    uint32_t    dwLength;
> > +    uint8_t     bSlot;
> > +    uint8_t     bSeq;
> > +} CCID_Header;
> > +
> > +typedef struct __attribute__ ((__packed__)) {
> > +    CCID_Header hdr;
> > +    uint8_t     bStatus;        /* Only used in BULK_IN */
> > +    uint8_t     bError;         /* Only used in BULK_IN */
> > +} CCID_BULK_IN;
> > +
> > +typedef struct __attribute__ ((__packed__)) {
> > +    CCID_BULK_IN b;
> > +    uint8_t     bClockStatus;
> > +} CCID_SlotStatus;
> > +
> > +typedef struct __attribute__ ((__packed__)) {
> > +    CCID_BULK_IN b;
> > +    uint8_t     bProtocolNum;
> > +    uint8_t     abProtocolDataStructure[0];
> > +} CCID_Parameter;
> > +
> > +typedef struct __attribute__ ((__packed__)) {
> > +    CCID_BULK_IN b;
> > +    uint8_t      bChainParameter;
> > +    uint8_t      abData[0];
> > +} CCID_DataBlock;
> > +
> > +/* 6.1.4 PC_to_RDR_XfrBlock */
> > +typedef struct __attribute__ ((__packed__)) {
> > +    CCID_Header  hdr;
> > +    uint8_t      bBWI; /* Block Waiting Timeout */
> > +    uint16_t     wLevelParameter;
> > +    uint8_t      abData[0];
> > +} CCID_XferBlock;
> > +
> > +typedef struct __attribute__ ((__packed__)) {
> > +    CCID_Header hdr;
> > +    uint8_t     bPowerSelect;
> > +    uint16_t    abRFU;
> > +} CCID_IccPowerOn;
> > +
> > +typedef struct __attribute__ ((__packed__)) {
> > +    CCID_Header hdr;
> > +    uint16_t    abRFU;
> > +} CCID_IccPowerOff;
> > +
> > +typedef struct __attribute__ ((__packed__)) {
> > +    CCID_Header hdr;
> > +    uint8_t     bProtocolNum;
> > +    uint8_t    abProtocolDataStructure[0];
> > +} CCID_SetParameter;
> > +
> > +typedef struct {
> > +    uint8_t     bMessageType; /* CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange */
> > +    uint8_t     bmSlotICCState;
> > +} CCID_Notify_Slot_Change;
> > +
> > +/* used for DataBlock response to XferBlock */
> > +typedef struct answer_t {
> > +    uint8_t slot;
> > +    uint8_t seq;
> > +} answer_t;
> > +
> > +/* pending BULK_IN messages */
> > +typedef struct bulk_in_t {
> > +    uint8_t  data[BULK_IN_BUF_SIZE];
> > +    uint32_t len;
> > +    uint32_t pos;
> > +} bulk_in_t;
> > +
> > +enum {
> > +    MIGRATION_NONE,
> > +    MIGRATION_MIGRATED,
> > +};
> > +
> > +typedef struct CCIDBus CCIDBus;
> > +typedef struct USBCCIDState USBCCIDState;
> > +
> > +#define MAX_PROTOCOL_SIZE   7
> > +
> > +/**
> > + * powered - defaults to true, changed by PowerOn/PowerOff messages
> > + */
> > +struct USBCCIDState {
> > +    USBDevice dev;
> > +    CCIDBus *bus;
> > +    CCIDCardState *card;
> > +    CCIDCardInfo *cardinfo; /* caching the info pointer */
> > +    uint8_t  debug;
> > +    uint8_t  auto_attach;
> > +    bulk_in_t bulk_in_pending[BULK_IN_PENDING_NUM]; /* circular */
> > +    uint32_t bulk_in_pending_start;
> > +    uint32_t bulk_in_pending_end; /* first free */
> > +    uint32_t bulk_in_pending_num;
> > +    bulk_in_t *current_bulk_in;
> > +    uint8_t  bulk_out_data[BULK_OUT_DATA_SIZE];
> > +    uint32_t bulk_out_pos;
> > +    uint8_t  bmSlotICCState;
> > +    uint8_t  powered;
> > +    uint8_t  notify_slot_change;
> > +    uint64_t last_answer_error;
> > +    answer_t pending_answers[PENDING_ANSWERS_NUM];
> > +    uint32_t pending_answers_start;
> > +    uint32_t pending_answers_end;
> > +    uint32_t pending_answers_num;
> > +    uint8_t  bError;
> > +    uint8_t  bmCommandStatus;
> > +    uint8_t  bProtocolNum;
> > +    uint8_t  abProtocolDataStructure[MAX_PROTOCOL_SIZE];
> > +    uint32_t ulProtocolDataStructureSize;
> > +    uint8_t  attached_vmstate;
> > +    uint32_t state_vmstate;
> > +    uint8_t  migration_state;
> > +    uint32_t migration_target_ip;
> > +    uint16_t migration_target_port;
> > +};
> > +
> > +/* Slot specific variables. We emulate a single slot card reader.
> > + */
> > +
> > +
> > +/* CCID Spec chapter 4: CCID uses a standard device descriptor per Chapter 9,
> > + * "USB Device Framework", section 9.6.1, in the Universal Serial Bus
> > + * Specification.
> > + *
> > + * This device implemented based on the spec and with an Athena Smart Card
> > + * Reader as reference:
> > + *   0dc3:1004 Athena Smartcard Solutions, Inc.
> > + */
> > +
> > +static const uint8_t qemu_ccid_dev_descriptor[] = {
> > +        0x12,       /*  u8 bLength; */
> > +        USB_DT_DEVICE, /*  u8 bDescriptorType; Device */
> > +        0x10, 0x01, /*  u16 bcdUSB; v1.1 */
> > +
> > +        0x00,       /*  u8  bDeviceClass; */
> > +        0x00,       /*  u8  bDeviceSubClass; */
> > +        0x00,       /*  u8  bDeviceProtocol; [ low/full speeds only ] */
> > +        0x40,       /*  u8  bMaxPacketSize0; 8 Bytes (valid: 8,16,32,64) */
> > +
> > +        /* Vendor and product id are arbitrary.  */
> > +                    /*  u16 idVendor  */
> > +        CCID_VENDOR_ID & 0xff, CCID_VENDOR_ID >> 8,
> > +                    /*  u16 idProduct */
> > +        CCID_PRODUCT_ID & 0xff, CCID_PRODUCT_ID >> 8,
> > +                    /*  u16 bcdDevice */
> > +        CCID_DEVICE_VERSION & 0xff, CCID_DEVICE_VERSION >> 8,
> > +        0x01,       /*  u8  iManufacturer; */
> > +        0x02,       /*  u8  iProduct; */
> > +        0x03,       /*  u8  iSerialNumber; */
> > +        0x01,       /*  u8  bNumConfigurations; */
> > +};
> > +
> > +static const uint8_t qemu_ccid_config_descriptor[] = {
> > +
> > +        /* one configuration */
> > +        0x09,       /*  u8  bLength; */
> > +        USB_DT_CONFIG, /*  u8  bDescriptorType; Configuration */
> > +        0x5d, 0x00, /*  u16 wTotalLength; 9+9+54+7+7+7 */
> > +        0x01,       /*  u8  bNumInterfaces; (1) */
> > +        0x01,       /*  u8  bConfigurationValue; */
> > +        0x00,       /*  u8  iConfiguration; */
> > +        0xe0,       /*  u8  bmAttributes;
> > +                                 Bit 7: must be set,
> > +                                     6: Self-powered,
> > +                                     5: Remote wakeup,
> > +                                     4..0: resvd */
> > +        100/2,      /*  u8  MaxPower; 50 == 100mA */
> > +
> > +        /* one interface */
> > +        0x09,       /*  u8  if_bLength; */
> > +        USB_DT_INTERFACE, /*  u8  if_bDescriptorType; Interface */
> > +        0x00,       /*  u8  if_bInterfaceNumber; */
> > +        0x00,       /*  u8  if_bAlternateSetting; */
> > +        0x03,       /*  u8  if_bNumEndpoints; */
> > +        0x0b,       /*  u8  if_bInterfaceClass; Smart Card Device Class */
> > +        0x00,       /*  u8  if_bInterfaceSubClass; Subclass code */
> > +        0x00,       /*  u8  if_bInterfaceProtocol; Protocol code */
> > +        0x04,       /*  u8  if_iInterface; Index of string descriptor */
> > +
> > +        /* Smart Card Device Class Descriptor */
> > +        0x36,       /*  u8  bLength; */
> > +        0x21,       /*  u8  bDescriptorType; Functional */
> > +        0x10, 0x01, /*  u16 bcdCCID; CCID Specification Release Number. */
> > +        0x00,       /*  u8  bMaxSlotIndex; The index of the highest available
> > +                        slot on this device. All slots are consecutive starting
> > +                        at 00h. */
> > +        0x07,       /*  u8  bVoltageSupport; 01h - 5.0v, 02h - 3.0, 03 - 1.8 */
> > +
> > +        0x03, 0x00, /*  u32 dwProtocols; RRRR PPPP. RRRR = 0000h.*/
> > +        0x00, 0x00, /*  PPPP: 0001h = Protocol T=0, 0002h = Protocol T=1 */
> > +                    /*  u32 dwDefaultClock; in kHZ (0x0fa0 is 4 MHz) */
> > +        0xa0, 0x0f, 0x00, 0x00,
> > +                    /*  u32 dwMaximumClock; */
> > +        0x00, 0x00, 0x01, 0x00,
> > +        0x00,       /*  u8 bNumClockSupported; 0 means just the default and max. */
> > +                    /*  u32 dwDataRate ;bps. 9600 == 00002580h */
> > +        0x80, 0x25, 0x00, 0x00,
> > +                    /*  u32 dwMaxDataRate ; 11520 bps == 0001C200h */
> > +        0x00, 0xC2, 0x01, 0x00,
> > +        0x00,       /*  u8  bNumDataRatesSupported; 00 means all rates between
> > +                     *      default and max */
> > +                    /*  u32 dwMaxIFSD; maximum IFSD supported by CCID for protocol
> > +                     *      T=1 (Maximum seen from various cards) */
> > +        0xfe, 0x00, 0x00, 0x00,
> > +                    /*  u32 dwSyncProtocols; 1 - 2-wire, 2 - 3-wire, 4 - I2C */
> > +        0x00, 0x00, 0x00, 0x00,
> > +                    /*  u32 dwMechanical;  0 - no special characteristics. */
> > +        0x00, 0x00, 0x00, 0x00,
> > +                    /*  u32 dwFeatures;
> > +                     *  0 - No special characteristics
> > +                     *  + 2 Automatic parameter configuration based on ATR data
> > +                     *  + 4 Automatic activation of ICC on inserting
> > +                     *  + 8 Automatic ICC voltage selection
> > +                     *  + 10 Automatic ICC clock frequency change
> > +                     *  + 20 Automatic baud rate change
> > +                     *  + 40 Automatic parameters negotiation made by the CCID
> > +                     *  + 80 automatic PPS made by the CCID
> > +                     *  100 CCID can set ICC in clock stop mode
> > +                     *  200 NAD value other then 00 accepted (T=1 protocol)
> > +                     *  + 400 Automatic IFSD exchange as first exchange (T=1)
> > +                     *  One of the following only:
> > +                     *  + 10000 TPDU level exchanges with CCID
> > +                     *  20000 Short APDU level exchange with CCID
> > +                     *  40000 Short and Extended APDU level exchange with CCID
> > +                     *
> > +                     *  + 100000 USB Wake up signaling supported on card insertion
> > +                     *  and removal. Must set bit 5 in bmAttributes in Configuration
> > +                     *  descriptor if 100000 is set.*/
> > +        0xfe, 0x04, 0x11, 0x00,
> > +                    /*  u32 dwMaxCCIDMessageLength; For extended APDU in [261 + 10
> > +                     *  , 65544 + 10]. Otherwise the minimum is wMaxPacketSize of
> > +                     *  the Bulk-OUT endpoint */
> > +        0x12, 0x00, 0x01, 0x00,
> > +        0xFF,       /*  u8  bClassGetResponse; Significant only for CCID that
> > +                     *  offers an APDU level for exchanges. Indicates the default
> > +                     *  class value used by the CCID when it sends a Get Response
> > +                     *  command to perform the transportation of an APDU by T=0
> > +                     *  protocol
> > +                     *  FFh indicates that the CCID echos the class of the APDU.
> > +                     */
> > +        0xFF,       /*  u8  bClassEnvelope; EAPDU only. Envelope command for T=0 */
> > +        0x00, 0x00, /*  u16 wLcdLayout; XXYY Number of lines (XX) and chars per
> > +                     *  line for LCD display used for PIN entry. 0000 - no LCD */
> > +        0x01,       /*  u8  bPINSupport; 01h PIN Verification,
> > +                     *                   02h PIN Modification */
> > +        0x01,       /*  u8  bMaxCCIDBusySlots; */
> > +
> > +        /* Interrupt-IN endpoint */
> > +        0x07,       /*  u8  ep_bLength; */
> > +                    /*  u8  ep_bDescriptorType; Endpoint */
> > +        USB_DT_ENDPOINT,
> > +                    /*  u8  ep_bEndpointAddress; IN Endpoint 1 */
> > +        0x80 | CCID_INT_IN_EP,
> > +        0x03,       /*  u8  ep_bmAttributes; Interrupt */
> > +        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
> > +        0xff,       /*  u8  ep_bInterval; */
> > +
> > +        /* Bulk-In endpoint */
> > +        0x07,       /*  u8  ep_bLength; */
> > +                    /*  u8  ep_bDescriptorType; Endpoint */
> > +        USB_DT_ENDPOINT,
> > +                    /*  u8  ep_bEndpointAddress; IN Endpoint 2 */
> > +        0x80 | CCID_BULK_IN_EP,
> > +        0x02,       /*  u8  ep_bmAttributes; Bulk */
> > +        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
> > +        0x00,       /*  u8  ep_bInterval; */
> > +
> > +        /* Bulk-Out endpoint */
> > +        0x07,       /*  u8  ep_bLength; */
> > +                    /*  u8  ep_bDescriptorType; Endpoint */
> > +        USB_DT_ENDPOINT,
> > +                    /*  u8  ep_bEndpointAddress; OUT Endpoint 3 */
> > +        CCID_BULK_OUT_EP,
> > +        0x02,       /*  u8  ep_bmAttributes; Bulk */
> > +        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
> > +        0x00,       /*  u8  ep_bInterval; */
> > +
> > +};
> > +
> > +static bool ccid_has_pending_answers(USBCCIDState *s)
> > +{
> > +    return s->pending_answers_num > 0;
> > +}
> > +
> > +static void ccid_clear_pending_answers(USBCCIDState *s)
> > +{
> > +    s->pending_answers_num = 0;
> > +    s->pending_answers_start = 0;
> > +    s->pending_answers_end = 0;
> > +}
> > +
> > +static void ccid_print_pending_answers(USBCCIDState *s)
> > +{
> > +#ifdef DEBUG_CCID
> > +    answer_t *answer;
> > +    int i, count;
> > +
> > +    printf("usb-ccid: pending answers:");
> > +    if (!ccid_has_pending_answers(s)) {
> > +        printf(" empty\n");
> > +        return;
> > +    }
> > +    for (i = s->pending_answers_start, count=s->pending_answers_num ;
> > +         count > 0; count--, i++) {
> > +        answer = &s->pending_answers[i % PENDING_ANSWERS_NUM];
> > +        if (count == 1) {
> > +            printf("%d:%d\n", answer->slot, answer->seq);
> > +        } else {
> > +            printf("%d:%d,", answer->slot, answer->seq);
> > +        }
> > +    }
> > +#endif
> > +}
> > +
> > +static void ccid_add_pending_answer(USBCCIDState *s, CCID_Header *hdr)
> > +{
> > +    answer_t* answer;
> > +
> > +    assert(s->pending_answers_num++ < PENDING_ANSWERS_NUM);
> > +    answer = &s->pending_answers[(s->pending_answers_end++) % PENDING_ANSWERS_NUM];
> > +    answer->slot = hdr->bSlot;
> > +    answer->seq = hdr->bSeq;
> > +    ccid_print_pending_answers(s);
> > +}
> > +
> > +static void ccid_remove_pending_answer(USBCCIDState *s,
> > +    uint8_t *slot, uint8_t *seq)
> > +{
> > +    answer_t *answer;
> > +
> > +    assert(s->pending_answers_num-- > 0);
> > +    answer = &s->pending_answers[(s->pending_answers_start++) % PENDING_ANSWERS_NUM];
> > +    *slot = answer->slot;
> > +    *seq = answer->seq;
> > +    ccid_print_pending_answers(s);
> > +}
> > +
> > +static void ccid_bulk_in_clear(USBCCIDState *s)
> > +{
> > +    s->bulk_in_pending_start = 0;
> > +    s->bulk_in_pending_end = 0;
> > +    s->bulk_in_pending_num = 0;
> > +}
> > +
> > +static void ccid_bulk_in_release(USBCCIDState *s)
> > +{
> > +    assert(s->current_bulk_in != NULL);
> > +    s->current_bulk_in->pos = 0;
> > +    s->current_bulk_in = NULL;
> > +}
> > +
> > +static void ccid_bulk_in_get(USBCCIDState *s)
> > +{
> > +    if (s->current_bulk_in != NULL || s->bulk_in_pending_num == 0) {
> > +        return;
> > +    }
> > +    assert(s->bulk_in_pending_num > 0);
> > +    s->bulk_in_pending_num--;
> > +    s->current_bulk_in = &s->bulk_in_pending[
> > +        (s->bulk_in_pending_start++) % BULK_IN_PENDING_NUM];
> > +}
> > +
> > +static uint8_t* ccid_reserve_recv_buf(USBCCIDState* s, uint16_t len)
> 
> Return void * and save the ugly casts in callers.
will fix.

> 
> > +{
> > +    bulk_in_t* bulk_in;
> > +
> > +    DPRINTF(s, 4, "%s: QUEUE: reserve %d bytes\n", __func__, len);
> > +
> > +    /* look for an existing element */
> > +    if (len > BULK_IN_BUF_SIZE) {
> > +        printf("usb-ccid.c: %s: len larger then max (%d>%d). bailing out.\n",
> > +            __func__, len, BULK_IN_BUF_SIZE);
> > +        exit(-1);
> 
> Is this guest-triggerable?  If yes, then exit() is wrong.  If no, is it
> a symptom of a programming error?  Then use assert().  If no, what is
> it?
It could be client triggered (this is invoked on messages coming from the ccid
card, emulated or passthrough). I'll change it to a discard of the message.

> 
> Aside: I prefer exit(1) over exit(-1).
> 
> > +    }
> > +    if (s->bulk_in_pending_num >= BULK_IN_PENDING_NUM) {
> > +        printf("usb-ccid.c: %s: No free bulk_in buffers. discarding message.\n",
> > +                __func__);
> > +        return NULL;
> > +    }
> > +    bulk_in = &s->bulk_in_pending[(s->bulk_in_pending_end++) % BULK_IN_PENDING_NUM];
> > +    s->bulk_in_pending_num++;
> > +    bulk_in->len = len;
> > +    return bulk_in->data;
> > +}
> > +
> > +static void ccid_reset(USBCCIDState *s)
> > +{
> > +    ccid_bulk_in_clear(s);
> > +    ccid_clear_pending_answers(s);
> > +}
> > +
> > +static void ccid_detach(USBCCIDState *s)
> > +{
> > +    ccid_reset(s);
> > +    if (s->auto_attach == 0 && s->dev.attached) {
> > +        usb_device_detach(&s->dev);
> > +    }
> > +}
> > +
> > +static void ccid_handle_reset(USBDevice *dev)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> > +
> > +    DPRINTF(s, 1, "Reset\n");
> > +
> > +    ccid_reset(s);
> > +}
> > +
> > +static int ccid_handle_control(USBDevice *dev, int request, int value,
> > +                                  int index, int length, uint8_t *data)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> > +    int ret = 0;
> > +
> > +    DPRINTF(s, 1, "got control %x, value %x\n",request, value);
> > +    switch (request) {
> > +    case DeviceRequest | USB_REQ_GET_STATUS:
> > +        data[0] = (0 << USB_DEVICE_SELF_POWERED) |
> > +            (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);
> > +        data[1] = 0x00;
> > +        ret = 2;
> > +        break;
> > +    case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
> > +        if (value == USB_DEVICE_REMOTE_WAKEUP) {
> > +            dev->remote_wakeup = 0;
> > +        } else {
> > +            goto fail;
> > +        }
> > +        ret = 0;
> > +        break;
> > +    case DeviceOutRequest | USB_REQ_SET_FEATURE:
> > +        if (value == USB_DEVICE_REMOTE_WAKEUP) {
> > +            dev->remote_wakeup = 1;
> > +        } else {
> > +            goto fail;
> > +        }
> > +        ret = 0;
> > +        break;
> > +    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
> > +        dev->addr = value;
> > +        ret = 0;
> > +        break;
> > +    case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
> > +        switch(value >> 8) {
> > +        case USB_DT_DEVICE:
> > +            memcpy(data, qemu_ccid_dev_descriptor,
> > +                   sizeof(qemu_ccid_dev_descriptor));
> > +            ret = sizeof(qemu_ccid_dev_descriptor);
> > +            break;
> > +        case USB_DT_CONFIG:
> > +            memcpy(data, qemu_ccid_config_descriptor,
> > +                   sizeof(qemu_ccid_config_descriptor));
> > +            ret = sizeof(qemu_ccid_config_descriptor);
> > +            break;
> > +        case USB_DT_STRING:
> > +            switch(value & 0xff) {
> > +            case 0:
> > +                /* language ids */
> > +                data[0] = 4;
> > +                data[1] = 3;
> > +                data[2] = 0x09;
> > +                data[3] = 0x04;
> > +                ret = 4;
> > +                break;
> > +            case 1:
> > +                /* vendor description */
> > +                ret = set_usb_string(data, CCID_VENDOR_DESCRIPTION);
> > +                break;
> > +            case 2:
> > +                /* product description */
> > +                ret = set_usb_string(data, CCID_PRODUCT_DESCRIPTION);
> > +                break;
> > +            case 3:
> > +                /* serial number */
> > +                ret = set_usb_string(data, CCID_SERIAL_NUMBER_STRING);
> > +                break;
> > +            case 4:
> > +                /* interface name */
> > +                ret = set_usb_string(data, CCID_INTERFACE_NAME);
> > +                break;
> > +            default:
> > +                goto fail;
> > +            }
> > +            break;
> > +        default:
> > +            goto fail;
> > +        }
> > +        break;
> > +    case DeviceRequest | USB_REQ_GET_CONFIGURATION:
> > +        data[0] = 1;
> > +        ret = 1;
> > +        break;
> > +    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
> > +        /* Only one configuration - we just ignore the request */
> > +        ret = 0;
> > +        break;
> > +    case DeviceRequest | USB_REQ_GET_INTERFACE:
> > +        data[0] = 0;
> > +        ret = 1;
> > +        break;
> > +    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
> > +        ret = 0;
> > +        break;
> > +    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
> > +        ret = 0;
> > +        break;
> > +
> > +        /* Class specific requests.  */
> > +    case InterfaceOutClass | CCID_CONTROL_ABORT:
> > +        DPRINTF(s, 1, "ccid_control abort UNIMPLEMENTED\n");
> > +        ret = USB_RET_STALL;
> > +        break;
> > +    case InterfaceInClass | CCID_CONTROL_GET_CLOCK_FREQUENCIES:
> > +        DPRINTF(s, 1, "ccid_control get clock frequencies UNIMPLEMENTED\n");
> > +        ret = USB_RET_STALL;
> > +        break;
> > +    case InterfaceInClass | CCID_CONTROL_GET_DATA_RATES:
> > +        DPRINTF(s, 1, "ccid_control get data rates UNIMPLEMENTED\n");
> > +        ret = USB_RET_STALL;
> > +        break;
> > +    default:
> > +    fail:
> > +        DPRINTF(s, 1, "got unsupported/bogus control %x, value %x\n", request, value);
> > +        ret = USB_RET_STALL;
> > +        break;
> > +    }
> > +    return ret;
> > +}
> > +
> > +static bool ccid_card_inserted(USBCCIDState *s)
> > +{
> > +    return s->bmSlotICCState & SLOT_0_STATE_MASK;
> > +}
> > +
> > +static uint8_t ccid_card_status(USBCCIDState *s)
> > +{
> > +    return ccid_card_inserted(s)
> > +            ? (s->powered ?
> > +                ICC_STATUS_PRESENT_ACTIVE
> > +              : ICC_STATUS_PRESENT_INACTIVE
> > +              )
> > +            : ICC_STATUS_NOT_PRESENT;
> > +}
> > +
> > +static uint8_t ccid_calc_status(USBCCIDState *s)
> > +{
> > +    /* page 55, 6.2.6, calculation of bStatus from bmICCStatus and
> > +       bmCommandStatus
> > +     */
> > +    uint8_t ret = ccid_card_status(s) | (s->bmCommandStatus << 6);
> > +    DPRINTF(s, 4, "status = %d\n", ret);
> > +    return ret;
> > +}
> > +
> > +static void ccid_reset_error_status(USBCCIDState* s)
> > +{
> > +    s->bError = ERROR_CMD_NOT_SUPPORTED;
> > +    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
> > +}
> > +
> > +static void ccid_write_slot_status(USBCCIDState* s, CCID_Header* recv)
> > +{
> > +    CCID_SlotStatus *h = (CCID_SlotStatus*)ccid_reserve_recv_buf(s, sizeof(CCID_SlotStatus));
> > +    if (h == NULL) {
> > +        return;
> > +    }
> > +    h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_SlotStatus;
> > +    h->b.hdr.dwLength = 0;
> > +    h->b.hdr.bSlot = recv->bSlot;
> > +    h->b.hdr.bSeq = recv->bSeq;
> > +    h->b.bStatus = ccid_calc_status(s);
> > +    h->b.bError = s->bError;
> > +    h->bClockStatus = CLOCK_STATUS_RUNNING;
> > +    ccid_reset_error_status(s);
> > +}
> > +
> > +static void ccid_write_parameters(USBCCIDState* s, CCID_Header* recv)
> > +{
> > +    CCID_Parameter *h;
> > +    uint32_t len = s->ulProtocolDataStructureSize;
> > +
> > +    h = (CCID_Parameter *)ccid_reserve_recv_buf(s, sizeof(CCID_Parameter) + len);
> > +    if (h == NULL) {
> > +        return;
> > +    }
> > +    h->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_Parameters;
> > +    h->b.hdr.dwLength = 0;
> > +    h->b.hdr.bSlot = recv->bSlot;
> > +    h->b.hdr.bSeq = recv->bSeq;
> > +    h->b.bStatus = ccid_calc_status(s);
> > +    h->b.bError = s->bError;
> > +    h->bProtocolNum = s->bProtocolNum;
> > +    memcpy(h->abProtocolDataStructure, s->abProtocolDataStructure, len);
> > +    ccid_reset_error_status(s);
> > +}
> > +
> > +static void ccid_write_data_block(
> > +    USBCCIDState* s, uint8_t slot, uint8_t seq,
> > +    const uint8_t* data, uint32_t len)
> > +{
> > +    CCID_DataBlock *p;
> > +
> > +    p = (CCID_DataBlock*)ccid_reserve_recv_buf(s, sizeof(*p) + len);
> > +    if (p == NULL) {
> > +        return;
> > +    }
> > +    p->b.hdr.bMessageType = CCID_MESSAGE_TYPE_RDR_to_PC_DataBlock;
> > +    p->b.hdr.dwLength = len;
> > +    p->b.hdr.bSlot = slot;
> > +    p->b.hdr.bSeq = seq;
> > +    p->b.bStatus = ccid_calc_status(s);
> > +    p->b.bError = s->bError;
> > +#ifdef DEBUG_CCID
> > +    if (p->b.bError) {
> > +        DPRINTF(s, 4, "error %d", p->b.bError);
> > +    }
> > +#endif
> > +    memcpy(p->abData, data, len);
> > +    ccid_reset_error_status(s);
> > +}
> > +
> > +static void ccid_write_data_block_answer(USBCCIDState* s,
> > +    const uint8_t* data, uint32_t len)
> > +{
> > +    uint8_t seq;
> > +    uint8_t slot;
> > +
> > +    if (!ccid_has_pending_answers(s)) {
> > +        abort();
> > +    }
> > +    ccid_remove_pending_answer(s, &slot, &seq);
> > +    ccid_write_data_block(s, slot, seq, data, len);
> > +}
> > +
> > +static void ccid_write_data_block_atr(USBCCIDState* s, CCID_Header* recv)
> > +{
> > +    const uint8_t *atr = NULL;
> > +    uint32_t len = 0;
> > +
> > +    if (s->card) {
> > +        atr = s->cardinfo->get_atr(s->card, &len);
> > +    }
> > +    ccid_write_data_block(s, recv->bSlot, recv->bSeq, atr, len);
> > +}
> > +
> > +static void ccid_set_parameters(USBCCIDState *s, CCID_Header *recv)
> > +{
> > +    CCID_SetParameter *ph = (CCID_SetParameter *) recv;
> > +    uint32_t len = 0;
> > +    if (ph->bProtocolNum == 0) {
> > +        len = 5;
> > +    }
> > +    if (ph->bProtocolNum == 1) {
> > +        len = 7;
> > +    }
> > +    if (len == 0) {
> > +        s->bmCommandStatus = COMMAND_STATUS_FAILED;
> > +        s->bError = 7; /* Protocol invalid or not supported */
> > +        return;
> > +    }
> > +    s->bProtocolNum = ph->bProtocolNum;
> > +    memcpy(s->abProtocolDataStructure, ph->abProtocolDataStructure, len);
> > +    s->ulProtocolDataStructureSize = len;
> > +    DPRINTF(s, 1, "%s: using len %d\n", __func__, len);
> > +}
> > +
> > +/* must be 5 bytes for T=0, 7 bytes for T=1
> > + * See page 52 */
> > +static const uint8_t abDefaultProtocolDataStructure[7] =
> > +    { 0x77, 0x00, 0x00, 0x00, 0x00, 0xfe /*IFSC*/, 0x00 /*NAD*/ };
> > +
> > +static void ccid_reset_parameters(USBCCIDState *s)
> > +{
> > +   uint32_t len = sizeof(abDefaultProtocolDataStructure);
> > +
> > +   s->bProtocolNum = 1; /* T=1 */
> > +   s->ulProtocolDataStructureSize = len;
> > +   memcpy(s->abProtocolDataStructure, abDefaultProtocolDataStructure, len);
> > +}
> > +
> > +static void ccid_report_error_failed(USBCCIDState *s, uint8_t error)
> > +{
> > +    s->bmCommandStatus = COMMAND_STATUS_FAILED;
> > +    s->bError = error;
> > +}
> > +
> > +/* NOTE: only a single slot is supported (SLOT_0)
> > + */
> > +static void ccid_on_slot_change(USBCCIDState* s, bool full)
> > +{
> > +    /* RDR_to_PC_NotifySlotChange, 6.3.1 page 56
> > +     */
> > +    uint8_t current = s->bmSlotICCState;
> > +    if (full) {
> > +        s->bmSlotICCState |= SLOT_0_STATE_MASK;
> > +    } else {
> > +        s->bmSlotICCState &= ~SLOT_0_STATE_MASK;
> > +    }
> > +    if (current != s->bmSlotICCState) {
> > +        s->bmSlotICCState |= SLOT_0_CHANGED_MASK;
> > +    }
> > +    s->notify_slot_change = true;
> > +}
> > +
> > +static void ccid_write_data_block_error(
> > +    USBCCIDState *s, uint8_t slot, uint8_t seq)
> > +{
> > +    ccid_write_data_block(s, slot, seq, NULL, 0);
> > +}
> > +
> > +static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
> > +{
> > +    if (ccid_card_status(s) != ICC_STATUS_PRESENT_ACTIVE) {
> > +        DPRINTF(s, 1, "usb-ccid: not sending apdu to client, no card connected\n");
> > +        ccid_write_data_block_error(s, recv->hdr.bSlot, recv->hdr.bSeq);
> > +        return;
> > +    }
> > +    DPRINTF(s, 1, "%s: seq %d, len %d\n", __FUNCTION__,
> > +                recv->hdr.bSeq, recv->hdr.dwLength);
> > +    ccid_add_pending_answer(s, (CCID_Header*)recv);
> > +    if (s->card) {
> > +        s->cardinfo->apdu_from_guest(s->card, recv->abData, recv->hdr.dwLength);
> > +    } else {
> > +        printf("warning: discarded apdu\n");
> > +    }
> > +}
> > +
> > +static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
> > +{
> > +    CCID_Header* ccid_header;
> > +
> > +    assert(p->len + s->bulk_out_pos <= BULK_OUT_DATA_SIZE);
> > +    ccid_header = (CCID_Header*)s->bulk_out_data;
> > +    memcpy(s->bulk_out_data + s->bulk_out_pos, p->data, p->len);
> > +    s->bulk_out_pos += p->len;
> > +    if (p->len == 64) {
> > +        DPRINTF(s, 4, "usb-ccid: bulk_in: expecting more packets (%d/%d)\n",
> > +            p->len, ccid_header->dwLength);
> > +        return;
> > +    }
> > +    if (s->bulk_out_pos < 10) {
> > +        DPRINTF(s, 1, "%s: bad USB_TOKEN_OUT length, should be at least 10 bytes\n", __func__);
> > +    } else {
> > +        DPRINTF(s, 3, "%s %x\n", __func__, ccid_header->bMessageType);
> > +        switch (ccid_header->bMessageType) {
> > +            case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus:
> > +                ccid_write_slot_status(s, ccid_header);
> > +                break;
> > +            case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:
> > +                DPRINTF(s, 1, "PowerOn: %d\n",
> > +                    ((CCID_IccPowerOn*)(ccid_header))->bPowerSelect);
> > +                s->powered = true;
> > +                if (!ccid_card_inserted(s)) {
> > +                    ccid_report_error_failed(s, ERROR_ICC_MUTE);
> > +                }
> > +                /* atr is written regardless of error. */
> > +                ccid_write_data_block_atr(s, ccid_header);
> > +                break;
> > +            case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff:
> > +                DPRINTF(s, 1, "PowerOff\n");
> > +                ccid_reset_error_status(s);
> > +                s->powered = false;
> > +                ccid_write_slot_status(s, ccid_header);
> > +                break;
> > +            case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:
> > +                ccid_on_apdu_from_guest(s, (CCID_XferBlock*)s->bulk_out_data);
> > +                break;
> > +            case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters:
> > +                ccid_reset_error_status(s);
> > +                ccid_set_parameters(s, ccid_header);
> > +                ccid_write_parameters(s, ccid_header);
> > +                break;
> > +            case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters:
> > +                ccid_reset_error_status(s);
> > +                ccid_reset_parameters(s);
> > +                ccid_write_parameters(s, ccid_header);
> > +                break;
> > +            case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters:
> > +                ccid_reset_error_status(s);
> > +                ccid_write_parameters(s, ccid_header);
> > +                break;
> > +            default:
> > +                DPRINTF(s, 1, "handle_data: ERROR: unhandled message type %Xh\n",
> > +                    ccid_header->bMessageType);
> > +                /* the caller is expecting the device to respond, tell it we
> > +                 * do't support the operation */
> > +                ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);
> > +                ccid_write_slot_status(s, ccid_header);
> > +                break;
> > +        }
> > +    }
> > +    s->bulk_out_pos = 0;
> > +}
> > +
> > +static int ccid_bulk_in_copy_out(USBCCIDState *s, uint8_t *data, int len)
> > +{
> > +    int ret = 0;
> > +
> > +    assert(len>0);
> > +    ccid_bulk_in_get(s);
> > +    if (s->current_bulk_in != NULL) {
> > +        ret = MIN(s->current_bulk_in->len - s->current_bulk_in->pos, len);
> > +        memcpy(data, s->current_bulk_in->data + s->current_bulk_in->pos, ret);
> > +        s->current_bulk_in->pos += ret;
> > +        if (s->current_bulk_in->pos == s->current_bulk_in->len) {
> > +            ccid_bulk_in_release(s);
> > +        }
> > +    } else {
> > +        ret = USB_RET_NAK; /* return when device has no data - usb 2.0 spec Table 8-4 */
> > +    }
> > +    if (ret > 0) {
> > +        DPRINTF(s, 3, "%s: %d/%d req/act to guest (BULK_IN)\n", __func__, len, ret);
> > +    }
> > +    if (ret != USB_RET_NAK && ret < len) {
> > +        DPRINTF(s, 1, "%s: returning short (EREMOTEIO) %d < %d\n", __func__, ret, len);
> > +    }
> > +    return ret;
> > +}
> > +
> > +static int ccid_handle_data(USBDevice *dev, USBPacket *p)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> > +    int ret = 0;
> > +    uint8_t *data = p->data;
> > +    int len = p->len;
> > +
> > +    switch (p->pid) {
> > +    case USB_TOKEN_OUT:
> > +        ccid_handle_bulk_out(s, p);
> > +        break;
> > +
> > +    case USB_TOKEN_IN:
> > +        switch (p->devep & 0xf) {
> > +            case CCID_BULK_IN_EP:
> > +                if (!len) {
> > +                    ret = USB_RET_NAK;
> > +                } else {
> > +                    ret = ccid_bulk_in_copy_out(s, data, len);
> > +                }
> > +                break;
> > +            case CCID_INT_IN_EP:
> > +                if (s->notify_slot_change) {
> > +                    /* page 56, RDR_to_PC_NotifySlotChange */
> > +                    data[0] = CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange;
> > +                    data[1] = s->bmSlotICCState;
> > +                    ret = 2;
> > +                    s->notify_slot_change = false;
> > +                    s->bmSlotICCState &= ~SLOT_0_CHANGED_MASK;
> > +                    DPRINTF(s, 2, "handle_data: int_in: notify_slot_change %X, requested len %d\n",
> > +                            s->bmSlotICCState, len);
> > +                }
> > +                break;
> > +            default:
> > +                DPRINTF(s, 1, "Bad endpoint\n");
> > +                break;
> > +        }
> > +        break;
> > +    default:
> > +        DPRINTF(s, 1, "Bad token\n");
> > +        ret = USB_RET_STALL;
> > +        break;
> > +    }
> > +
> > +    return ret;
> > +}
> > +
> > +static void ccid_handle_destroy(USBDevice *dev)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> > +
> > +    ccid_bulk_in_clear(s);
> > +}
> > +
> > +static void ccid_flush_pending_answers(USBCCIDState *s) {
> > +    while (ccid_has_pending_answers(s)) {
> > +        ccid_write_data_block_answer(s, NULL, 0);
> > +    }
> > +}
> > +
> > +static answer_t *ccid_peek_next_answer(USBCCIDState *s)
> > +{
> > +    return s->pending_answers_num == 0
> > +        ? NULL
> > +        : &s->pending_answers[s->pending_answers_start % PENDING_ANSWERS_NUM];
> > +}
> > +
> > +static void ccid_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent)
> > +{
> > +    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
> > +    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, qdev->info);
> > +
> > +    if (info->print) {
> > +        info->print(mon, card, indent);
> > +    }
> > +}
> > +
> > +struct CCIDBus {
> > +    BusState qbus;
> > +};
> > +
> > +static struct BusInfo ccid_bus_info = {
> > +    .name = "ccid-bus",
> > +    .size = sizeof(CCIDBus),
> > +    .print_dev = ccid_bus_dev_print,
> > +};
> > +
> > +static CCIDBus *ccid_bus_new(DeviceState *dev)
> > +{
> > +    CCIDBus *bus;
> > +
> > +    bus = FROM_QBUS(CCIDBus, qbus_create(&ccid_bus_info, dev, NULL));
> > +    bus->qbus.allow_hotplug = 1;
> > +
> > +    return bus;
> > +}
> > +
> > +void ccid_card_send_apdu_to_guest(CCIDCardState *card, uint8_t* apdu, uint32_t len)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> > +    answer_t *answer;
> > +
> > +    if (!ccid_has_pending_answers(s)) {
> > +        DPRINTF(s, 1, "CCID ERROR: got an APDU without pending answers\n");
> > +        return;
> > +    }
> > +    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
> > +    answer = ccid_peek_next_answer(s);
> > +    if (answer == NULL) {
> > +        abort();
> > +    }
> > +    DPRINTF(s, 1, "APDU returned to guest %d (answer seq %d, slot %d)\n",
> > +        len, answer->seq, answer->slot);
> > +    ccid_write_data_block_answer(s, apdu, len);
> > +}
> > +
> > +void ccid_card_card_removed(CCIDCardState *card)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> > +
> > +    ccid_on_slot_change(s, false);
> > +    ccid_flush_pending_answers(s);
> > +    ccid_reset(s);
> > +}
> > +
> > +int ccid_card_ccid_attach(CCIDCardState *card)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> > +
> > +    DPRINTF(s, 1, "CCID Attach\n");
> > +    if (s->auto_attach==0 && !s->dev.attached) {
> > +        usb_device_attach(&s->dev);
> > +        return 0;
> > +    } else {
> > +        if (s->migration_state == MIGRATION_MIGRATED) {
> > +            s->migration_state = MIGRATION_NONE;
> > +            return 0;
> > +        } else {
> > +            return -1;
> > +        }
> > +    }
> > +}
> > +
> > +void ccid_card_ccid_detach(CCIDCardState *card)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> > +
> > +    DPRINTF(s, 1, "CCID Detach\n");
> > +    if (ccid_card_inserted(s)) {
> > +        ccid_on_slot_change(s, false);
> > +    }
> > +    ccid_detach(s);
> > +}
> > +
> > +void ccid_card_card_error(CCIDCardState *card, uint64_t error)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> > +
> > +    s->bmCommandStatus = COMMAND_STATUS_FAILED;
> > +    s->last_answer_error = error;
> > +    DPRINTF(s, 1, "VSC_Error: %lX\n", s->last_answer_error);
> > +    /* TODO: these error's should be more verbose and propogated to the guest.
> > +     * */
> 
> Impact of not propagating them?
Comment is wrong on the propogation part - bmCommandStatus is set to an error state.
I'll fix the comment. Verbosity would just be nicert (i.e., not using COMMAND_STATUS_FAILED
for all possible error values, but switching on it and matching error for error).

> 
> > +    ccid_write_data_block_answer(s, NULL, 0);
> > +}
> > +
> > +void ccid_card_card_inserted(CCIDCardState *card)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> > +
> > +    s->bmCommandStatus = COMMAND_STATUS_NO_ERROR;
> > +    ccid_flush_pending_answers(s);
> > +    ccid_on_slot_change(s, true);
> > +}
> > +
> > +static int ccid_card_exit(DeviceState *qdev)
> > +{
> > +    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
> > +    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, qdev->info);
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> > +
> > +    if (ccid_card_inserted(s)) {
> > +        ccid_card_card_removed(card);
> > +    }
> > +    if (info->exitfn) {
> > +        return info->exitfn(card);
> > +    }
> > +    return 0;
> > +}
> > +
> > +static int ccid_card_init(DeviceState *qdev, DeviceInfo *base)
> > +{
> > +    CCIDCardState *card = DO_UPCAST(CCIDCardState, qdev, qdev);
> > +    CCIDCardInfo *info = DO_UPCAST(CCIDCardInfo, qdev, base);
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev.qdev, card->qdev.parent_bus->parent);
> > +
> > +    s->card = card;
> > +    s->cardinfo = info;
> > +    if (info->initfn) {
> > +        return info->initfn(card);
> > +    }
> > +    return 0;
> > +}
> > +
> > +void ccid_card_qdev_register(CCIDCardInfo *card)
> > +{
> > +    card->qdev.bus_info = &ccid_bus_info;
> > +    card->qdev.init = ccid_card_init;
> > +    card->qdev.exit = ccid_card_exit;
> > +    qdev_register(&card->qdev);
> > +}
> > +
> > +static int ccid_initfn(USBDevice *dev)
> > +{
> > +    USBCCIDState *s = DO_UPCAST(USBCCIDState, dev, dev);
> > +
> > +    s->bus = ccid_bus_new(&dev->qdev);
> > +    s->card = NULL;
> > +    s->cardinfo = NULL;
> > +    s->migration_state = MIGRATION_NONE;
> > +    dev->auto_attach = s->auto_attach;
> > +    s->migration_target_ip = 0;
> > +    s->migration_target_port = 0;
> > +    s->dev.speed = USB_SPEED_FULL;
> > +    s->notify_slot_change = false;
> > +    s->powered = true;
> > +    s->pending_answers_num = 0;
> > +    s->last_answer_error = 0;
> > +    s->bulk_in_pending_start = 0;
> > +    s->bulk_in_pending_end = 0;
> > +    s->current_bulk_in = NULL;
> > +    ccid_reset_error_status(s);
> > +    s->bulk_out_pos = 0;
> > +    ccid_reset_parameters(s);
> > +    ccid_reset(s);
> > +    return 0;
> > +}
> > +
> > +static int ccid_post_load(void *opaque, int version_id)
> > +{
> > +    USBCCIDState *s = opaque;
> > +
> > +    if (s->auto_attach == 0 && s->attached_vmstate && !s->dev.attached) {
> > +        usb_device_attach(&s->dev);
> > +    }
> > +    // This must be done after usb_device_attach, which sets state to ATTACHED,
> > +    // while it must be DEFAULT in order to accept packets (like it is after
> > +    // reset, but reset will reset our addr and call our reset handler which
> > +    // may change state, and we don't want to do that when migrating).
> > +    s->dev.state = s->state_vmstate;
> > +    return 0;
> > +}
> > +
> > +static void ccid_pre_save(void *opaque)
> > +{
> > +    USBCCIDState *s = opaque;
> > +
> > +    s->attached_vmstate = s->dev.attached;
> > +    s->state_vmstate = s->dev.state;
> > +    if (s->dev.attached) {
> > +        // migrating an open device, ignore reconnection CHR_EVENT to avoid an
> > +        // erronous detach.
> > +        s->migration_state = MIGRATION_MIGRATED;
> > +    }
> > +}
> > +
> > +static VMStateDescription bulk_in_t_vmstate = {
> > +    .name = "bulk_in_t",
> > +    .version_id = 1,
> > +    .minimum_version_id = 1,
> > +    .fields = (VMStateField []) {
> > +        VMSTATE_BUFFER(data, bulk_in_t),
> > +        VMSTATE_UINT32(len, bulk_in_t),
> > +        VMSTATE_UINT32(pos, bulk_in_t),
> > +        VMSTATE_END_OF_LIST()
> > +    }
> > +};
> > +
> > +static VMStateDescription answer_t_vmstate = {
> > +    .name = "answer_t",
> > +    .version_id = 1,
> > +    .minimum_version_id = 1,
> > +    .fields = (VMStateField []) {
> > +        VMSTATE_UINT8(slot, answer_t),
> > +        VMSTATE_UINT8(seq, answer_t),
> > +        VMSTATE_END_OF_LIST()
> > +    }
> > +};
> > +
> > +static VMStateDescription usb_device_vmstate = {
> > +    .name = "usb_device",
> > +    .version_id = 1,
> > +    .minimum_version_id = 1,
> > +    .fields = (VMStateField []) {
> > +        //int speed;
> > +        VMSTATE_UINT8(addr, USBDevice),
> > +        //VMSTATE_BUFFER(product_desc, USBDevice), // char, not uint8_t - casting error
> 
> Can't see char nor uint8_t here.  Please explain.
It's not being migrated. Comment should be removed. The product_desc doesn't
need to be migrated, it isn't changed and so the target and source have the same
contents.
> 
> > +        //int auto_attach;
> > +        //int attached;
> > +        //int state;
> > +        VMSTATE_BUFFER(setup_buf, USBDevice),
> > +        VMSTATE_BUFFER(data_buf, USBDevice),
> > +        // int remote_wakeup;
> > +        // int setup_state;
> > +        // int setup_len;
> > +        // int setup_index;
> > +        VMSTATE_END_OF_LIST()
> > +    }
> 
> What's the commented out code good for?
my bad, will remove. basically stuff I thought I should migrate, but
didn't seem to need to (I am not 100% sure about it, but It worked in
my tess).

> 
> > +};
> > +
> > +static VMStateDescription ccid_vmstate = {
> > +    .name = CCID_DEV_NAME,
> > +    .version_id = 1,
> > +    .minimum_version_id = 1,
> > +    .post_load = ccid_post_load,
> > +    .pre_save = ccid_pre_save,
> > +    .fields = (VMStateField []) {
> > +        VMSTATE_STRUCT(dev, USBCCIDState, 1, usb_device_vmstate, USBDevice),
> > +        VMSTATE_UINT8(debug, USBCCIDState),
> > +        VMSTATE_UINT8(auto_attach, USBCCIDState),
> > +        VMSTATE_BUFFER(bulk_out_data, USBCCIDState),
> > +        VMSTATE_UINT32(bulk_out_pos, USBCCIDState),
> > +        VMSTATE_UINT8(bmSlotICCState, USBCCIDState),
> > +        VMSTATE_UINT8(powered, USBCCIDState),
> > +        VMSTATE_UINT8(notify_slot_change, USBCCIDState),
> > +        VMSTATE_UINT64(last_answer_error, USBCCIDState),
> > +        VMSTATE_UINT8(bError, USBCCIDState),
> > +        VMSTATE_UINT8(bmCommandStatus, USBCCIDState),
> > +        VMSTATE_UINT8(bProtocolNum, USBCCIDState),
> > +        VMSTATE_BUFFER(abProtocolDataStructure, USBCCIDState),
> > +        VMSTATE_UINT32(ulProtocolDataStructureSize, USBCCIDState),
> > +        VMSTATE_STRUCT_ARRAY(bulk_in_pending, USBCCIDState,
> > +                       BULK_IN_PENDING_NUM, 1, bulk_in_t_vmstate, bulk_in_t),
> > +        VMSTATE_UINT32(bulk_in_pending_start, USBCCIDState),
> > +        VMSTATE_UINT32(bulk_in_pending_end, USBCCIDState),
> > +        VMSTATE_STRUCT_ARRAY(pending_answers, USBCCIDState,
> > +                        PENDING_ANSWERS_NUM, 1, answer_t_vmstate, answer_t),
> > +        VMSTATE_UINT32(pending_answers_num, USBCCIDState),
> > +        VMSTATE_UINT8(migration_state, USBCCIDState),
> > +        VMSTATE_UINT8(attached_vmstate, USBCCIDState),
> > +        VMSTATE_UINT32(state_vmstate, USBCCIDState),
> > +        VMSTATE_END_OF_LIST()
> > +    }
> > +};
> > +
> > +static struct USBDeviceInfo ccid_info = {
> > +    .product_desc   = "QEMU USB CCID",
> > +    .qdev.name      = CCID_DEV_NAME,
> > +    .qdev.size      = sizeof(USBCCIDState),
> > +    .qdev.vmsd      = &ccid_vmstate,
> > +    .init           = ccid_initfn,
> > +    .handle_packet  = usb_generic_handle_packet,
> > +    .handle_reset   = ccid_handle_reset,
> > +    .handle_control = ccid_handle_control,
> > +    .handle_data    = ccid_handle_data,
> > +    .handle_destroy = ccid_handle_destroy,
> > +    .usbdevice_name = "ccid",
> > +    .qdev.props     = (Property[]) {
> > +        DEFINE_PROP_UINT8("auto_attach", USBCCIDState, auto_attach, 0),
> > +        DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
> > +        DEFINE_PROP_END_OF_LIST(),
> > +    },
> > +};
> > +
> > +
> > +static void ccid_register_devices(void)
> > +{
> > +    usb_qdev_register(&ccid_info);
> > +}
> > +device_init(ccid_register_devices)

^ permalink raw reply	[flat|nested] 10+ messages in thread

* [Qemu-devel] [PATCH 4/4] ccid: add docs
  2010-11-09 12:22 [Qemu-devel] [PATCH 0/4] usb-ccid (v6) Alon Levy
@ 2010-11-09 12:22 ` Alon Levy
  0 siblings, 0 replies; 10+ messages in thread
From: Alon Levy @ 2010-11-09 12:22 UTC (permalink / raw)
  To: qemu-devel; +Cc: armbru

---
 docs/ccid.txt |  133 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 133 insertions(+), 0 deletions(-)
 create mode 100644 docs/ccid.txt

diff --git a/docs/ccid.txt b/docs/ccid.txt
new file mode 100644
index 0000000..5eac611
--- /dev/null
+++ b/docs/ccid.txt
@@ -0,0 +1,133 @@
+Qemu CCID Device Documentation.
+
+Contents
+1. USB CCID device
+2. Building
+3. Using ccid-card-emulated with hardware
+4. Using ccid-card-emulated with certificates
+5. Using ccid-card-passthru with client side hardware
+6. Using ccid-card-passthru with client side certificates
+7. Passthrough protocol scenario
+8. libcaccard
+
+1. USB CCID device
+
+The USB CCID device is a USB device implementing the CCID specification, which
+lets one connect smart card readers that implement the same spec. For more
+information see the specification:
+
+ Universal Serial Bus
+ Device Class: Smart Card
+ CCID
+ Specification for
+ Integrated Circuit(s) Cards Interface Devices
+ Revision 1.1
+ April 22rd, 2005
+
+Smartcard are used for authentication, single sign on, decryption in
+public/private schemes and digital signatures. A smartcard reader on the client
+cannot be used on a guest with simple usb passthrough since it will then not be
+available on the client, possibly locking the computer when it is "removed". On
+the other hand this device can let you use the smartcard on both the client and
+the guest machine. It is also possible to have a completely virtual smart card
+reader and smart card (i.e. not backed by a physical device) using this device.
+
+2. Building
+
+prerequisites:
+ libcaccard
+
+At the moment there are no binary or source releases, so it has to be retrieved
+from source control:
+
+    git clone git://anongit.freedesktop.org/~alon/cac_card
+
+fedora:
+    yum install nss-devel
+ubuntu:
+    apt-get install libnss3-dev
+    (not tested on ubuntu)
+
+build cac_card:
+    cd cac_card
+    ./configure && make && sudo make install
+
+qemu:
+    ./configure --enable-smartcard && make
+
+Note that if you install to a non default prefix you need to set
+PKG_CONFIG_PATH to compile qemu successfully.
+
+3. Using ccid-card-emulated with hardware
+
+Assuming you have a working smartcard on the host with the current
+user, using NSS, qemu acts as another NSS client using ccid-card-emulated:
+
+    qemu -usb -device usb-ccid -device ccid-card-emualated
+
+4. Using ccid-card-emulated with certificates
+
+You must create the certificates. This is a one time process. We use NSS certificates:
+
+    certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=cert1" -n cert1
+
+Note: you must have exactly three certificates.
+
+Assuming the current user can access the certificates (use certutil -L to verify),
+you can use the emulated card type with the certificates backend:
+
+    qemu -usb -device usb-ccid -device ccid-card-emulated,backend=certificates,cert1=cert1,cert2=cert2,cert3=cert3
+
+5. Using ccid-card-passthru with client side hardware
+
+on the host specify the ccid-card-passthru device with a suitable chardev:
+
+    qemu -chardev socket,server,host=0.0.0.0,port=2001,id=ccid,nowait -usb -device usb-ccid -device ccid-card-passthru,chardev=ccid
+
+on the client run vscclient, built when you built the libcaccard library:
+    vscclient <qemu-host> 2001
+
+6. Using ccid-card-passthru with client side certificates
+
+Run qemu as per #5, and run vscclient as follows:
+(Note: vscclient command line interface is in a state of change)
+
+    ./vscclient -e "db=\"/etc/pki/nssdb\" use_hw=no soft=(,Test,CAC,,cert1,cert2,cert3)" <qemu-host> 2001
+
+7. Passthrough protocol scenario
+
+This is a typical interchange of messages when using the passthru card device.
+usb-ccid is a usb device. It defaults to an unattached usb device on startup.
+usb-ccid expects a chardev and expects the protocol defined in cac_card/vscard_common.h to be passed over that.
+A typical interchange is:
+
+client event      |      vscclient           |    passthru    |     usb-ccid  |  guest event
+----------------------------------------------------------------------------------------------
+                  |      VSC_Init            |                |               |
+                  |      VSC_ReaderAdd       |                |     attach    |
+                  |                          |                |               |  sees new usb device.
+card inserted     |                          |                |               |
+                  |      VSC_ATR             |                |               |
+                  |                          |                |               |  guest operation, APDU transfer via CCID
+                  |                          |   VSC_APDU     |               |
+                  |      VSC_APDU            |                |               |
+client<->physical |                          |                |               |
+card APDU exchange|                          |                |               |
+                            [APDU<->APDU repeats several times]              
+card removed      |                          |                |               |
+                  |      VSC_CardRemove      |                |               |
+kill/quit         |                          |                |               |
+  vscclient       |                          |                |               |
+                  |      VSC_ReaderRemove    |                |    detach     |
+                  |                          |                |               |   usb device removed.
+
+
+8. libcaccard
+
+ccid-card-passthru and vscclient use libcaccard as the card emulator.
+libcaccard implements a completely virtual CAC (DoD standard for smart cards)
+compliant card and uses NSS to actually retrive certificates and do any
+encryption using the backend (real reader + card or file backed certificates).
+
+For documentation of cac_card see README in libcac_card package.
+
-- 
1.7.3.2

^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [Qemu-devel] [PATCH 4/4] ccid: add docs
  2010-11-09 11:40 [Qemu-devel] [PATCH 0/4] usb-ccid (v5) Alon Levy
@ 2010-11-09 11:40 ` Alon Levy
  0 siblings, 0 replies; 10+ messages in thread
From: Alon Levy @ 2010-11-09 11:40 UTC (permalink / raw)
  To: qemu-devel; +Cc: armbru

---
 docs/ccid.txt |  133 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 133 insertions(+), 0 deletions(-)
 create mode 100644 docs/ccid.txt

diff --git a/docs/ccid.txt b/docs/ccid.txt
new file mode 100644
index 0000000..5eac611
--- /dev/null
+++ b/docs/ccid.txt
@@ -0,0 +1,133 @@
+Qemu CCID Device Documentation.
+
+Contents
+1. USB CCID device
+2. Building
+3. Using ccid-card-emulated with hardware
+4. Using ccid-card-emulated with certificates
+5. Using ccid-card-passthru with client side hardware
+6. Using ccid-card-passthru with client side certificates
+7. Passthrough protocol scenario
+8. libcaccard
+
+1. USB CCID device
+
+The USB CCID device is a USB device implementing the CCID specification, which
+lets one connect smart card readers that implement the same spec. For more
+information see the specification:
+
+ Universal Serial Bus
+ Device Class: Smart Card
+ CCID
+ Specification for
+ Integrated Circuit(s) Cards Interface Devices
+ Revision 1.1
+ April 22rd, 2005
+
+Smartcard are used for authentication, single sign on, decryption in
+public/private schemes and digital signatures. A smartcard reader on the client
+cannot be used on a guest with simple usb passthrough since it will then not be
+available on the client, possibly locking the computer when it is "removed". On
+the other hand this device can let you use the smartcard on both the client and
+the guest machine. It is also possible to have a completely virtual smart card
+reader and smart card (i.e. not backed by a physical device) using this device.
+
+2. Building
+
+prerequisites:
+ libcaccard
+
+At the moment there are no binary or source releases, so it has to be retrieved
+from source control:
+
+    git clone git://anongit.freedesktop.org/~alon/cac_card
+
+fedora:
+    yum install nss-devel
+ubuntu:
+    apt-get install libnss3-dev
+    (not tested on ubuntu)
+
+build cac_card:
+    cd cac_card
+    ./configure && make && sudo make install
+
+qemu:
+    ./configure --enable-smartcard && make
+
+Note that if you install to a non default prefix you need to set
+PKG_CONFIG_PATH to compile qemu successfully.
+
+3. Using ccid-card-emulated with hardware
+
+Assuming you have a working smartcard on the host with the current
+user, using NSS, qemu acts as another NSS client using ccid-card-emulated:
+
+    qemu -usb -device usb-ccid -device ccid-card-emualated
+
+4. Using ccid-card-emulated with certificates
+
+You must create the certificates. This is a one time process. We use NSS certificates:
+
+    certutil -d /etc/pki/nssdb -x -t "CT,CT,CT" -S -s "CN=cert1" -n cert1
+
+Note: you must have exactly three certificates.
+
+Assuming the current user can access the certificates (use certutil -L to verify),
+you can use the emulated card type with the certificates backend:
+
+    qemu -usb -device usb-ccid -device ccid-card-emulated,backend=certificates,cert1=cert1,cert2=cert2,cert3=cert3
+
+5. Using ccid-card-passthru with client side hardware
+
+on the host specify the ccid-card-passthru device with a suitable chardev:
+
+    qemu -chardev socket,server,host=0.0.0.0,port=2001,id=ccid,nowait -usb -device usb-ccid -device ccid-card-passthru,chardev=ccid
+
+on the client run vscclient, built when you built the libcaccard library:
+    vscclient <qemu-host> 2001
+
+6. Using ccid-card-passthru with client side certificates
+
+Run qemu as per #5, and run vscclient as follows:
+(Note: vscclient command line interface is in a state of change)
+
+    ./vscclient -e "db=\"/etc/pki/nssdb\" use_hw=no soft=(,Test,CAC,,cert1,cert2,cert3)" <qemu-host> 2001
+
+7. Passthrough protocol scenario
+
+This is a typical interchange of messages when using the passthru card device.
+usb-ccid is a usb device. It defaults to an unattached usb device on startup.
+usb-ccid expects a chardev and expects the protocol defined in cac_card/vscard_common.h to be passed over that.
+A typical interchange is:
+
+client event      |      vscclient           |    passthru    |     usb-ccid  |  guest event
+----------------------------------------------------------------------------------------------
+                  |      VSC_Init            |                |               |
+                  |      VSC_ReaderAdd       |                |     attach    |
+                  |                          |                |               |  sees new usb device.
+card inserted     |                          |                |               |
+                  |      VSC_ATR             |                |               |
+                  |                          |                |               |  guest operation, APDU transfer via CCID
+                  |                          |   VSC_APDU     |               |
+                  |      VSC_APDU            |                |               |
+client<->physical |                          |                |               |
+card APDU exchange|                          |                |               |
+                            [APDU<->APDU repeats several times]              
+card removed      |                          |                |               |
+                  |      VSC_CardRemove      |                |               |
+kill/quit         |                          |                |               |
+  vscclient       |                          |                |               |
+                  |      VSC_ReaderRemove    |                |    detach     |
+                  |                          |                |               |   usb device removed.
+
+
+8. libcaccard
+
+ccid-card-passthru and vscclient use libcaccard as the card emulator.
+libcaccard implements a completely virtual CAC (DoD standard for smart cards)
+compliant card and uses NSS to actually retrive certificates and do any
+encryption using the backend (real reader + card or file backed certificates).
+
+For documentation of cac_card see README in libcac_card package.
+
-- 
1.7.3.2

^ permalink raw reply related	[flat|nested] 10+ messages in thread

end of thread, other threads:[~2010-11-09 12:22 UTC | newest]

Thread overview: 10+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2010-10-24 13:18 [Qemu-devel] [PATCH 0/4] usb-ccid (v4) Alon Levy
2010-10-24 13:18 ` [Qemu-devel] [PATCH 1/4] usb-ccid: add CCID bus Alon Levy
2010-11-09 10:11   ` Markus Armbruster
2010-11-09 10:58     ` Alon Levy
2010-10-24 13:18 ` [Qemu-devel] [PATCH 2/4] ccid: add passthru card device Alon Levy
2010-10-24 13:18 ` [Qemu-devel] [PATCH 3/4] add ccid-card-emulated device (v2) Alon Levy
2010-10-24 13:18 ` [Qemu-devel] [PATCH 4/4] ccid: add docs Alon Levy
2010-11-09 10:14 ` [Qemu-devel] [PATCH 0/4] usb-ccid (v4) Markus Armbruster
2010-11-09 11:40 [Qemu-devel] [PATCH 0/4] usb-ccid (v5) Alon Levy
2010-11-09 11:40 ` [Qemu-devel] [PATCH 4/4] ccid: add docs Alon Levy
2010-11-09 12:22 [Qemu-devel] [PATCH 0/4] usb-ccid (v6) Alon Levy
2010-11-09 12:22 ` [Qemu-devel] [PATCH 4/4] ccid: add docs Alon Levy

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.