Skip to contentSkip to conversation

usb-ccid (v16)

PATCH In review Alon Levy 2 participants 30 messages Feb 2, 2011 – Feb 3, 2011 Kbuild

lore
Share & tools
lore

Alon Levy

author
#0 lore raw

cover usb-ccid (v16)

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.

It also introduces a new directory libcaccard with CAC card emulation, CAC is a type of ISO 7816 smart card.

Tree for pull: git://anongit.freedesktop.org/~alon/qemu usb_ccid.v16

v15-v16 changes:
* split vscard_common introducing patch for ease of review
* sum of commit logs for the v15-v16 commits: (whitespace fixes
removed for space, see original commit messages in later patches)
* usb-ccid:
* fix abort on client answer after card remove
* enable migration
* remove side affect code from asserts
* return consistent self-powered state
* mask out reserved bits in ccid_set_parameters
* add missing abRFU in SetParameters (no affect on linux guest)
* vscard_common.h protocol change:
* VSCMsgInit capabilities and magic
* removed ReaderResponse, will use Error instead with code==VSC_SUCCESS.
* added Flush and FlushComplete, remove Reconnect.
* define VSCARD_MAGIC
* added error code VSC_SUCCESS.
* ccid-card-passthru
* return correct size
* return error instead of assert if client sent too large ATR
* don't assert if client sent too large a size, but add asserts for indices to buffer
* reset vscard_in indices on chardev disconnect
* handle init from client
* error if no chardev supplied
* use ntoh, hton
* eradicate reader_id_t
* remove Reconnect usage (removed from VSCARD protocol)
* send VSC_SUCCESS on card insert/remove and reader add/remove
* ccid-card-emulated
* fix error reporting in initfn

v14-v15 changes:
* add patch with --enable-smartcard and --disable-smartcard and only disable ccid-card-emulated if nss not found.
* add patch with description strings
* s/libcaccard/libcacard/ in docs/ccid.txt

v13-v14 changes:
- support device_del/device_add on ccid-card-* and usb-ccid
* usb-ccid:
* lose card reference when card device deleted
* check slot number and deny adding a slot if one is already added.
* ccid-card-*: use qdev_simple_unplug_cb in both emulated and passthru ccid cards, the exitfn already takes care of triggering card removal in the usb dev.
* libcacard:
* remove double include of config-host.mak
* add replay of card events to libcacard to support second and more emulation
* don't initialize more then once (doesn't support it right now, so one thread, NSS thread, is left when device_del is done)
* add VCARD_EMUL_INIT_ALREADY_INITED
* ccid-card-emulated:
* take correct mutexes on signaling to fix deadlocks on device_del
* allow card insertion/removal event without proper reader insertion event

v12-v13 changes:
* libcacard:
* fix Makefile clean to remove vscclient
* fix double include of config-host in Makefile
* usb-ccid: remove attach/detach logic, usb is always attached. Guest doesn't care if there is a reader attached with no card anyway.
* ccid-card-passthru: don't close chr_dev on removal, makes it possible to use device_del/device_add to create remove/insertion for debugging.

v11-v12 changes:
* fix out of tree build

v10-v11 changes:
* fix last patch that removed one of the doc files.
* updated flow table in docs/ccid.txt

v8-v10 changes:
* usb-ccid:
* add slot for future use (Gerd)
* ifdef ENABLE_MIGRATION for migration support on account of usb migration not being ready in general. (Gerd)
* verbosified commit messages. (Gerd)
* put libcacard docs in libcacard commit. (Gerd)

v8-v9 changes:
* Blue Swirl comments:
* white space fixes
* enabled by default, disabled only if missing nss
* forgotten fix from v8 (don't build libcacard.so)
* added a note about device being little endian
* library renamed from libcaccard to libcacard
* squashed both of libcacard patches, they touched different files anyway.

v7-v8 changes:
* Blue Swirl comments:
* usb-ccid: deannonymize some structs
* usb-ccid: coding style change - answer_t and bulk_in_t fixed
* usb-ccid: handle endianess conversion between guest and host
* usb-ccid: s/ccid_bulk_in_copy_out/ccid_bulk_in_copy_to_guest/
* ccid-card-emulated: fix segfault if backend not specified
* ccid-card-emulated: let last reader inserted win
* libcaccard: remove double vscard_common.h

v6->v7 changes:
* external libcaccard became internal directory libcaccard
* statically link object files into qemu
* produce libcaccard.so for usage by external projects
* applied coding style to new code (please check me)
- did not use the qemu options parsing for libcaccard, since it seems to draw large amounts of qemu code (monitor for instance).

v5->v6 changes:
* really remove static debug (I apologize for claiming to have done so before)

v4->v5 changes:
* rebased to latest
* remove static debug in card devices
* fix --enable-smartcard to link
* stall instead of assert when exceeding BULK_OUT_DATA_SIZE
* make ccid_reserve_recv_buf for too large len discard message, not exit
* make ccid_reserve_recv_buf return void*
* fix typo
* remove commented code in VMState

v3->v4:
* remove ccid field in CCIDBus
* remove static debug in bus
* 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 (19):
qdev: add print_options callback
qdev: add data pointer to Property
qdev-properties: add PROP_TYPE_ENUM
qdev-properties: parse_enum: don't cast a void*
usb-ccid: add CCID bus
usb-ccid: review fixes (v15-v16)
introduce libcacard/vscard_common.h libcacard/vscard_common.h update (v15->v16)
ccid: add passthru card device
ccid-card-passthru: review fixes (v15->v16)
libcacard: fixes from review (v15->v16)
ccid: add ccid-card-emulated device (v2)
ccid-card-emulated: use PROP_TYPE_ENUM for backend
ccid-card-emulated: review fixes (v15->v16)
ccid: add docs
ccid: configure: add --enable/disable and nss only disable
ccid: add qdev description strings smartcard,configure: add --enable-smartcard-nss, report only nss smartcard,configure: report only nss

Robert Relyea (1):
libcacard: initial commit after coding style fixes

 Makefile                    |    6 +-
 Makefile.objs               |    7 +
 Makefile.target             |    2 +
 configure                   |   59 ++
 docs/ccid.txt               |  135 +++++
 docs/libcacard.txt          |  483 +++++++++++++++
 hw/ccid-card-emulated.c     |  551 ++++++++++++++++++
 hw/ccid-card-passthru.c     |  328 +++++++++++
 hw/ccid.h                   |   42 ++
 hw/qdev-properties.c        |   60 ++
 hw/qdev.c                   |   10 +-
 hw/qdev.h                   |   17 +
 hw/usb-ccid.c               | 1353 +++++++++++++++++++++++++++++++++++++++++++
 libcacard/Makefile          |   14 +
 libcacard/cac.c             |  411 +++++++++++++
 libcacard/cac.h             |   20 +
 libcacard/card_7816.c       |  780 +++++++++++++++++++++++++
 libcacard/card_7816.h       |   60 ++
 libcacard/card_7816t.h      |  163 ++++++
 libcacard/event.c           |  112 ++++
 libcacard/eventt.h          |   28 +
 libcacard/link_test.c       |   20 +
 libcacard/mutex.h           |   59 ++
 libcacard/passthru.c        |  612 +++++++++++++++++++
 libcacard/passthru.h        |   50 ++
 libcacard/vcard.c           |  350 +++++++++++
 libcacard/vcard.h           |   85 +++
 libcacard/vcard_emul.h      |   62 ++
 libcacard/vcard_emul_nss.c  | 1192 +++++++++++++++++++++++++++++++++++++
 libcacard/vcard_emul_type.c |   60 ++
 libcacard/vcard_emul_type.h |   29 +
 libcacard/vcardt.h          |   66 +++
 libcacard/vevent.h          |   26 +
 libcacard/vreader.c         |  526 +++++++++++++++++
 libcacard/vreader.h         |   54 ++
 libcacard/vreadert.h        |   23 +
 libcacard/vscard_common.h   |  167 ++++++
 libcacard/vscclient.c       |  743 ++++++++++++++++++++++++
 38 files changed, 8762 insertions(+), 3 deletions(-)
 create mode 100644 docs/ccid.txt
 create mode 100644 docs/libcacard.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 libcacard/Makefile
 create mode 100644 libcacard/cac.c
 create mode 100644 libcacard/cac.h
 create mode 100644 libcacard/card_7816.c
 create mode 100644 libcacard/card_7816.h
 create mode 100644 libcacard/card_7816t.h
 create mode 100644 libcacard/event.c
 create mode 100644 libcacard/eventt.h
 create mode 100644 libcacard/link_test.c
 create mode 100644 libcacard/mutex.h
 create mode 100644 libcacard/passthru.c
 create mode 100644 libcacard/passthru.h
 create mode 100644 libcacard/vcard.c
 create mode 100644 libcacard/vcard.h
 create mode 100644 libcacard/vcard_emul.h
 create mode 100644 libcacard/vcard_emul_nss.c
 create mode 100644 libcacard/vcard_emul_type.c
 create mode 100644 libcacard/vcard_emul_type.h
 create mode 100644 libcacard/vcardt.h
 create mode 100644 libcacard/vevent.h
 create mode 100644 libcacard/vreader.c
 create mode 100644 libcacard/vreader.h
 create mode 100644 libcacard/vreadert.h
 create mode 100644 libcacard/vscard_common.h
 create mode 100644 libcacard/vscclient.c
Signature · 1 line
1.7.4
author
#1 lore raw

PATCH 1/20 qdev: add print_options callback

another callback added to PropertyInfo, for later use by PROP_TYPE_ENUM. Allows printing of runtime computed options when doing:
qemu -device foo,?

---
 hw/qdev.c |   10 +++++++++-
 hw/qdev.h |    1 +
 2 files changed, 10 insertions(+), 1 deletions(-)
hw/qdev.c +9 -1
index c7fec44..0b2ad3d 100644
@@ -187,7 +187,15 @@ int qdev_device_help(QemuOpts *opts)
         if (!prop->info->parse) {
             continue;           /* no way to set it, don't show */
         }
-        error_printf("%s.%s=%s\n", info->name, prop->name, prop->info->name);
+        if (prop->info->print_options) {
+            char buf[256];
+            int ret;
+            ret = prop->info->print_options(info, prop, buf, sizeof(buf) - 3);
+            error_printf("%s.%s=%s%s\n", info->name, prop->name, buf,
+                ret == sizeof(buf) - 3 ? "..." : "" );
+        } else {
+            error_printf("%s.%s=%s\n", info->name, prop->name, prop->info->name);
+        }
     }
     return 1;
 }
hw/qdev.h +1 -0
index 9808f85..fa3221b 100644
@@ -109,6 +109,7 @@ struct PropertyInfo {
     enum PropertyType type;
     int (*parse)(DeviceState *dev, Property *prop, const char *str);
     int (*print)(DeviceState *dev, Property *prop, char *dest, size_t len);
+    int (*print_options)(DeviceInfo *info, Property *prop, char *dest, size_t len);
     void (*free)(DeviceState *dev, Property *prop);
 };
 
Signature · 1 line
1.7.4
#2 lore raw

Re: [Qemu-devel] [PATCH 01/20] qdev: add print_options callback

Quoted 34 lines · Alon Levy

another callback added to PropertyInfo, for later use by PROP_TYPE_ENUM. Allows printing of runtime computed options when doing:
qemu -device foo,?

---
  hw/qdev.c |   10 +++++++++-
  hw/qdev.h |    1 +
  2 files changed, 10 insertions(+), 1 deletions(-)
hw/qdev.c +9 -1
index c7fec44..0b2ad3d 100644
@@ -187,7 +187,15 @@ int qdev_device_help(QemuOpts *opts)
          if (!prop->info->parse) {
              continue;           /* no way to set it, don't show */
          }
-        error_printf("%s.%s=%s\n", info->name, prop->name, prop->info->name);
+        if (prop->info->print_options) {
+            char buf[256];
+            int ret;
+            ret = prop->info->print_options(info, prop, buf, sizeof(buf) - 3);
+            error_printf("%s.%s=%s%s\n", info->name, prop->name, buf,
+                ret == sizeof(buf) - 3 ? "..." : "" );
+        } else {
+            error_printf("%s.%s=%s\n", info->name, prop->name, prop->info->name);
+        }
      }
      return 1;
  }
hw/qdev.h +0 -0
index 9808f85..fa3221b 100644

hw/qdev.h struct PropertyInfo { · line 113

Quoted 5 lines
hw/qdev.h +1 -0
@@ -109,6 +109,7 @@ struct PropertyInfo {
      enum PropertyType type;
      int (*parse)(DeviceState *dev, Property *prop, const char *str);
      int (*print)(DeviceState *dev, Property *prop, char *dest, size_t len);
+    int (*print_options)(DeviceInfo *info, Property *prop, char *dest, size_t len);
 

I'm not clear what the different between print and print_options is and why two callbacks are needed. Can you explain and comments to the patch clarifying why two interfaces are needed. Even better would be if one interface could handle it.

Regards,

Anthony Liguori

Quoted 4 lines
hw/qdev.h +0 -0
      void (*free)(DeviceState *dev, Property *prop);
  };
author
#3 lore raw

Re: [Qemu-devel] [PATCH 01/20] qdev: add print_options callback

Quoted 34 lines · Anthony Liguori
Quoted 33 lines · Alon Levy

another callback added to PropertyInfo, for later use by PROP_TYPE_ENUM. Allows printing of runtime computed options when doing:
qemu -device foo,?

---
 hw/qdev.c |   10 +++++++++-
 hw/qdev.h |    1 +
 2 files changed, 10 insertions(+), 1 deletions(-)
hw/qdev.c +9 -1
index c7fec44..0b2ad3d 100644
@@ -187,7 +187,15 @@ int qdev_device_help(QemuOpts *opts)
         if (!prop->info->parse) {
             continue;           /* no way to set it, don't show */
         }
-        error_printf("%s.%s=%s\n", info->name, prop->name, prop->info->name);
+        if (prop->info->print_options) {
+            char buf[256];
+            int ret;
+            ret = prop->info->print_options(info, prop, buf, sizeof(buf) - 3);
+            error_printf("%s.%s=%s%s\n", info->name, prop->name, buf,
+                ret == sizeof(buf) - 3 ? "..." : "" );
+        } else {
+            error_printf("%s.%s=%s\n", info->name, prop->name, prop->info->name);
+        }
     }
     return 1;
 }
hw/qdev.h +0 -0
index 9808f85..fa3221b 100644
Quoted 8 lines

hw/qdev.h struct PropertyInfo { · line 112

Quoted 5 lines
hw/qdev.h +1 -0
@@ -109,6 +109,7 @@ struct PropertyInfo {
     enum PropertyType type;
     int (*parse)(DeviceState *dev, Property *prop, const char *str);
     int (*print)(DeviceState *dev, Property *prop, char *dest, size_t len);
+    int (*print_options)(DeviceInfo *info, Property *prop, char *dest, size_t len);

I'm not clear what the different between print and print_options is and why two callbacks are needed. Can you explain and comments to

There is a difference in usage - the existing print is called when we do info during execution, it shows the status of the device. print_options is given a DeviceInfo and not a DeviceState and responds with the list we print for a command line invocation:
"qemu -device foo,? ", It is used to allow possible options that depend on available runtime libraries or other resources. It also allows relatively easy implementation for data that could be known at compile time, like names for enums, used by the next patches.

Quoted 12 lines

the patch clarifying why two interfaces are needed. Even better would be if one interface could handle it.

Regards,

Anthony Liguori

Quoted 3 lines
hw/qdev.h +0 -0
     void (*free)(DeviceState *dev, Property *prop);
 };
 
author
#4 lore raw

PATCH 2/20 qdev: add data pointer to Property

In reply to Alon Levy

For later use by PROP_TYPE_ENUM, will store enumeration name/value table there.

---
 hw/qdev.h |    1 +
 1 files changed, 1 insertions(+), 0 deletions(-)
hw/qdev.h +1 -0
index fa3221b..3d9acd7 100644
@@ -83,6 +83,7 @@ struct Property {
     int          offset;
     int          bitnr;
     void         *defval;
+    void         *data;
 };
 
 enum PropertyType {
Signature · 1 line
1.7.4
author
#5 lore raw

PATCH 3/20 qdev-properties: add PROP_TYPE_ENUM

In reply to Alon Levy

Example usage:

EnumTable foo_enum_table[] = {
    {"bar", 1},
    {"buz", 2},
    {NULL, 0},
};

DEFINE_PROP_ENUM("foo", State, foo, 1, foo_enum_table)

When using qemu -device foodev,? it will appear as:
foodev.foo=bar/buz

---
 hw/qdev-properties.c |   60 ++++++++++++++++++++++++++++++++++++++++++++++++++
 hw/qdev.h            |   15 ++++++++++++
 2 files changed, 75 insertions(+), 0 deletions(-)
hw/qdev-properties.c +60 -0
index a493087..3157721 100644
@@ -63,6 +63,66 @@ PropertyInfo qdev_prop_bit = {
     .print = print_bit,
 };
 
+/* --- Enumeration --- */
+/* Example usage:
+EnumTable foo_enum_table[] = {
+    {"bar", 1},
+    {"buz", 2},
+    {NULL, 0},
+};
+DEFINE_PROP_ENUM("foo", State, foo, 1, foo_enum_table),
+ */
+static int parse_enum(DeviceState *dev, Property *prop, const char *str)
+{
+    uint8_t *ptr = qdev_get_prop_ptr(dev, prop);
+    EnumTable *option = (EnumTable*)prop->data;
+
+    while (option->name != NULL) {
+        if (!strncmp(str, option->name, strlen(option->name))) {
+            *ptr = option->value;
+            return 0;
+        }
+        option++;
+    }
+    return -EINVAL;
+}
+
+static int print_enum(DeviceState *dev, Property *prop, char *dest, size_t len)
+{
+    uint32_t *p = qdev_get_prop_ptr(dev, prop);
+    EnumTable *option = (EnumTable*)prop->data;
+    while (option->name != NULL) {
+        if (*p == option->value) {
+            return snprintf(dest, len, "%s", option->name);
+        }
+        option++;
+    }
+    return 0;
+}
+
+static int print_enum_options(DeviceInfo *info, Property *prop, char *dest, size_t len)
+{
+    int ret = 0;
+    EnumTable *option = (EnumTable*)prop->data;
+    while (option->name != NULL) {
+        ret += snprintf(dest + ret, len - ret, "%s", option->name);
+        if (option[1].name != NULL) {
+            ret += snprintf(dest + ret, len - ret, "/");
+        }
+        option++;
+    }
+    return ret;
+}
+
+PropertyInfo qdev_prop_enum = {
+    .name  = "enum",
+    .type  = PROP_TYPE_ENUM,
+    .size  = sizeof(uint32_t),
+    .parse = parse_enum,
+    .print = print_enum,
+    .print_options = print_enum_options,
+};
+
 /* --- 8bit integer --- */
 
 static int parse_uint8(DeviceState *dev, Property *prop, const char *str)
hw/qdev.h +15 -0
index 3d9acd7..3701d83 100644
@@ -102,6 +102,7 @@ enum PropertyType {
     PROP_TYPE_VLAN,
     PROP_TYPE_PTR,
     PROP_TYPE_BIT,
+    PROP_TYPE_ENUM,
 };
 
 struct PropertyInfo {
@@ -121,6 +122,11 @@ typedef struct GlobalProperty {
     QTAILQ_ENTRY(GlobalProperty) next;
 } GlobalProperty;
 
+typedef struct EnumTable {
+    const char *name;
+    uint32_t    value;
+} EnumTable;
+
 /*** Board API.  This should go away once we have a machine config file.  ***/
 
 DeviceState *qdev_create(BusState *bus, const char *name);
@@ -235,6 +241,7 @@ extern PropertyInfo qdev_prop_drive;
 extern PropertyInfo qdev_prop_netdev;
 extern PropertyInfo qdev_prop_vlan;
 extern PropertyInfo qdev_prop_pci_devfn;
+extern PropertyInfo qdev_prop_enum;
 
 #define DEFINE_PROP(_name, _state, _field, _prop, _type) { \
         .name      = (_name),                                    \
@@ -257,6 +264,14 @@ extern PropertyInfo qdev_prop_pci_devfn;
             + type_check(uint32_t,typeof_field(_state, _field)), \
         .defval    = (bool[]) { (_defval) },                     \
         }
+#define DEFINE_PROP_ENUM(_name, _state, _field, _defval, _options) {    \
+        .name      = (_name),                                           \
+        .info      = &(qdev_prop_enum),                                 \
+        .offset    = offsetof(_state, _field)                           \
+            + type_check(uint32_t,typeof_field(_state, _field)),        \
+        .defval    = (uint32_t[]) { (_defval) },                        \
+        .data      = (void*)(_options),                                 \
+        }
 
 #define DEFINE_PROP_UINT8(_n, _s, _f, _d)                       \
     DEFINE_PROP_DEFAULT(_n, _s, _f, _d, qdev_prop_uint8, uint8_t)
Signature · 1 line
1.7.4
#6 lore raw

Re: [Qemu-devel] [PATCH 03/20] qdev-properties: add PROP_TYPE_ENUM

Quoted 8 lines · Alon Levy

Example usage:

EnumTable foo_enum_table[] = {
     {"bar", 1},
     {"buz", 2},
     {NULL, 0},
};
Quoted 9 lines

DEFINE_PROP_ENUM("foo", State, foo, 1, foo_enum_table)

When using qemu -device foodev,? it will appear as:
foodev.foo=bar/buz

---
  hw/qdev-properties.c |   60 ++++++++++++++++++++++++++++++++++++++++++++++++++
  hw/qdev.h            |   15 ++++++++++++
  2 files changed, 75 insertions(+), 0 deletions(-)

Missing Signed-off-by.

Is it really necessary to introduce this in this series? There's a lot missing here like the ability to determine which values are valid for an enum through QMP.

I think this will also unexpected break the device_add QMP interface since there's some special logic to handle types. It's unclear to me whether we should be sending the symbolic name or the value through QMP.

Regards,

Anthony Liguori

Quoted 119 lines
hw/qdev-properties.c +60 -0
index a493087..3157721 100644
@@ -63,6 +63,66 @@ PropertyInfo qdev_prop_bit = {
      .print = print_bit,
  };
 
+/* --- Enumeration --- */
+/* Example usage:
+EnumTable foo_enum_table[] = {
+    {"bar", 1},
+    {"buz", 2},
+    {NULL, 0},
+};
+DEFINE_PROP_ENUM("foo", State, foo, 1, foo_enum_table),
+ */
+static int parse_enum(DeviceState *dev, Property *prop, const char *str)
+{
+    uint8_t *ptr = qdev_get_prop_ptr(dev, prop);
+    EnumTable *option = (EnumTable*)prop->data;
+
+    while (option->name != NULL) {
+        if (!strncmp(str, option->name, strlen(option->name))) {
+            *ptr = option->value;
+            return 0;
+        }
+        option++;
+    }
+    return -EINVAL;
+}
+
+static int print_enum(DeviceState *dev, Property *prop, char *dest, size_t len)
+{
+    uint32_t *p = qdev_get_prop_ptr(dev, prop);
+    EnumTable *option = (EnumTable*)prop->data;
+    while (option->name != NULL) {
+        if (*p == option->value) {
+            return snprintf(dest, len, "%s", option->name);
+        }
+        option++;
+    }
+    return 0;
+}
+
+static int print_enum_options(DeviceInfo *info, Property *prop, char *dest, size_t len)
+{
+    int ret = 0;
+    EnumTable *option = (EnumTable*)prop->data;
+    while (option->name != NULL) {
+        ret += snprintf(dest + ret, len - ret, "%s", option->name);
+        if (option[1].name != NULL) {
+            ret += snprintf(dest + ret, len - ret, "/");
+        }
+        option++;
+    }
+    return ret;
+}
+
+PropertyInfo qdev_prop_enum = {
+    .name  = "enum",
+    .type  = PROP_TYPE_ENUM,
+    .size  = sizeof(uint32_t),
+    .parse = parse_enum,
+    .print = print_enum,
+    .print_options = print_enum_options,
+};
+
  /* --- 8bit integer --- */
 
  static int parse_uint8(DeviceState *dev, Property *prop, const char *str)
hw/qdev.h +15 -0
index 3d9acd7..3701d83 100644
@@ -102,6 +102,7 @@ enum PropertyType {
      PROP_TYPE_VLAN,
      PROP_TYPE_PTR,
      PROP_TYPE_BIT,
+    PROP_TYPE_ENUM,
  };
 
  struct PropertyInfo {
@@ -121,6 +122,11 @@ typedef struct GlobalProperty {
      QTAILQ_ENTRY(GlobalProperty) next;
  } GlobalProperty;
 
+typedef struct EnumTable {
+    const char *name;
+    uint32_t    value;
+} EnumTable;
+
  /*** Board API.  This should go away once we have a machine config file.  ***/
 
  DeviceState *qdev_create(BusState *bus, const char *name);
@@ -235,6 +241,7 @@ extern PropertyInfo qdev_prop_drive;
  extern PropertyInfo qdev_prop_netdev;
  extern PropertyInfo qdev_prop_vlan;
  extern PropertyInfo qdev_prop_pci_devfn;
+extern PropertyInfo qdev_prop_enum;
 
  #define DEFINE_PROP(_name, _state, _field, _prop, _type) { \
          .name      = (_name),                                    \
@@ -257,6 +264,14 @@ extern PropertyInfo qdev_prop_pci_devfn;
              + type_check(uint32_t,typeof_field(_state, _field)), \
          .defval    = (bool[]) { (_defval) },                     \
          }
+#define DEFINE_PROP_ENUM(_name, _state, _field, _defval, _options) {    \
+        .name      = (_name),                                           \
+        .info      =&(qdev_prop_enum),                                 \
+        .offset    = offsetof(_state, _field)                           \
+            + type_check(uint32_t,typeof_field(_state, _field)),        \
+        .defval    = (uint32_t[]) { (_defval) },                        \
+        .data      = (void*)(_options),                                 \
+        }
 
  #define DEFINE_PROP_UINT8(_n, _s, _f, _d)                       \
      DEFINE_PROP_DEFAULT(_n, _s, _f, _d, qdev_prop_uint8, uint8_t)
author
#7 lore raw

Re: [Qemu-devel] [PATCH 03/20] qdev-properties: add PROP_TYPE_ENUM

Quoted 18 lines · Anthony Liguori
Quoted 8 lines · Alon Levy

Example usage:

EnumTable foo_enum_table[] = {
    {"bar", 1},
    {"buz", 2},
    {NULL, 0},
};
Quoted 8 lines

DEFINE_PROP_ENUM("foo", State, foo, 1, foo_enum_table)

When using qemu -device foodev,? it will appear as:
foodev.foo=bar/buz

---
 hw/qdev-properties.c |   60 ++++++++++++++++++++++++++++++++++++++++++++++++++
 hw/qdev.h            |   15 ++++++++++++
 2 files changed, 75 insertions(+), 0 deletions(-)
Quoted 6 lines

Missing Signed-off-by.

Is it really necessary to introduce this in this series? There's a lot missing here like the ability to determine which values are valid for an enum through QMP.

I currently added this for command line querying of the backends supplied by the ccid-card-emulated for libvirt. I can add QMP support. Are you talking about a single "query-options device property" jsonified?

Quoted 4 lines

I think this will also unexpected break the device_add QMP interface since there's some special logic to handle types. It's unclear to me whether we should be sending the symbolic name or the value through QMP.

I don't understand where this could happen. QMP won't break if it keeps sending the value like it always did. I could add support for sending the name in a later patch (they are easily distinguished as json would be 1 and "something" with the quotation marks for integer and string respectively).

Quoted 124 lines

Regards,

Anthony Liguori

Quoted 118 lines
hw/qdev-properties.c +60 -0
index a493087..3157721 100644
@@ -63,6 +63,66 @@ PropertyInfo qdev_prop_bit = {
     .print = print_bit,
 };
 
+/* --- Enumeration --- */
+/* Example usage:
+EnumTable foo_enum_table[] = {
+    {"bar", 1},
+    {"buz", 2},
+    {NULL, 0},
+};
+DEFINE_PROP_ENUM("foo", State, foo, 1, foo_enum_table),
+ */
+static int parse_enum(DeviceState *dev, Property *prop, const char *str)
+{
+    uint8_t *ptr = qdev_get_prop_ptr(dev, prop);
+    EnumTable *option = (EnumTable*)prop->data;
+
+    while (option->name != NULL) {
+        if (!strncmp(str, option->name, strlen(option->name))) {
+            *ptr = option->value;
+            return 0;
+        }
+        option++;
+    }
+    return -EINVAL;
+}
+
+static int print_enum(DeviceState *dev, Property *prop, char *dest, size_t len)
+{
+    uint32_t *p = qdev_get_prop_ptr(dev, prop);
+    EnumTable *option = (EnumTable*)prop->data;
+    while (option->name != NULL) {
+        if (*p == option->value) {
+            return snprintf(dest, len, "%s", option->name);
+        }
+        option++;
+    }
+    return 0;
+}
+
+static int print_enum_options(DeviceInfo *info, Property *prop, char *dest, size_t len)
+{
+    int ret = 0;
+    EnumTable *option = (EnumTable*)prop->data;
+    while (option->name != NULL) {
+        ret += snprintf(dest + ret, len - ret, "%s", option->name);
+        if (option[1].name != NULL) {
+            ret += snprintf(dest + ret, len - ret, "/");
+        }
+        option++;
+    }
+    return ret;
+}
+
+PropertyInfo qdev_prop_enum = {
+    .name  = "enum",
+    .type  = PROP_TYPE_ENUM,
+    .size  = sizeof(uint32_t),
+    .parse = parse_enum,
+    .print = print_enum,
+    .print_options = print_enum_options,
+};
+
 /* --- 8bit integer --- */
 
 static int parse_uint8(DeviceState *dev, Property *prop, const char *str)
hw/qdev.h +15 -0
index 3d9acd7..3701d83 100644
@@ -102,6 +102,7 @@ enum PropertyType {
     PROP_TYPE_VLAN,
     PROP_TYPE_PTR,
     PROP_TYPE_BIT,
+    PROP_TYPE_ENUM,
 };
 
 struct PropertyInfo {
@@ -121,6 +122,11 @@ typedef struct GlobalProperty {
     QTAILQ_ENTRY(GlobalProperty) next;
 } GlobalProperty;
 
+typedef struct EnumTable {
+    const char *name;
+    uint32_t    value;
+} EnumTable;
+
 /*** Board API.  This should go away once we have a machine config file.  ***/
 
 DeviceState *qdev_create(BusState *bus, const char *name);
@@ -235,6 +241,7 @@ extern PropertyInfo qdev_prop_drive;
 extern PropertyInfo qdev_prop_netdev;
 extern PropertyInfo qdev_prop_vlan;
 extern PropertyInfo qdev_prop_pci_devfn;
+extern PropertyInfo qdev_prop_enum;
 
 #define DEFINE_PROP(_name, _state, _field, _prop, _type) { \
         .name      = (_name),                                    \
@@ -257,6 +264,14 @@ extern PropertyInfo qdev_prop_pci_devfn;
             + type_check(uint32_t,typeof_field(_state, _field)), \
         .defval    = (bool[]) { (_defval) },                     \
         }
+#define DEFINE_PROP_ENUM(_name, _state, _field, _defval, _options) {    \
+        .name      = (_name),                                           \
+        .info      =&(qdev_prop_enum),                                 \
+        .offset    = offsetof(_state, _field)                           \
+            + type_check(uint32_t,typeof_field(_state, _field)),        \
+        .defval    = (uint32_t[]) { (_defval) },                        \
+        .data      = (void*)(_options),                                 \
+        }
 
 #define DEFINE_PROP_UINT8(_n, _s, _f, _d)                       \
     DEFINE_PROP_DEFAULT(_n, _s, _f, _d, qdev_prop_uint8, uint8_t)
author
#8 lore raw

PATCH 4/20 qdev-properties: parse_enum: don't cast a void*

In reply to Alon Levy
---
 hw/qdev-properties.c |    2 +-
 1 files changed, 1 insertions(+), 1 deletions(-)
hw/qdev-properties.c +1 -1
index 3157721..9108f18 100644
@@ -75,7 +75,7 @@ DEFINE_PROP_ENUM("foo", State, foo, 1, foo_enum_table),
 static int parse_enum(DeviceState *dev, Property *prop, const char *str)
 {
     uint8_t *ptr = qdev_get_prop_ptr(dev, prop);
-    EnumTable *option = (EnumTable*)prop->data;
+    EnumTable *option = prop->data;
 
     while (option->name != NULL) {
         if (!strncmp(str, option->name, strlen(option->name))) {
Signature · 1 line
1.7.4
author
#9 lore raw

PATCH 5/20 usb-ccid: add CCID bus

In reply to Alon Levy

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.

---
 Makefile.objs |    1 +
 configure     |    6 +
 hw/ccid.h     |   35 ++
 hw/usb-ccid.c | 1355 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1397 insertions(+), 0 deletions(-)
 create mode 100644 hw/ccid.h
 create mode 100644 hw/usb-ccid.c
Makefile.objs +1 -0
index f1c7bfe..a1f3853 100644
@@ -195,6 +195,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
configure +6 -0
index 598e8e1..14a035a 100755
@@ -174,6 +174,7 @@ trace_backend="nop"
 trace_file="trace"
 spice=""
 rbd=""
+smartcard="yes"
 
 # parse CC options first
 for opt do
@@ -2472,6 +2473,7 @@ echo "Trace output file $trace_file-<pid>"
 echo "spice support     $spice"
 echo "rbd support       $rbd"
 echo "xfsctl support    $xfs"
+echo "smartcard support $smartcard"
 
 if test $sdl_too_old = "yes"; then
 echo "-> Your SDL version is too old - please upgrade to have SDL support"
@@ -2744,6 +2746,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
hw/ccid.h new file +35 -0
new file mode 100644
index 0000000..af59070
@@ -0,0 +1,35 @@
+#ifndef __CCID_H__
+#define __CCID_H__
+
+#include "qdev.h"
+
+typedef struct CCIDCardState CCIDCardState;
+typedef struct CCIDCardInfo CCIDCardInfo;
+
+struct CCIDCardState {
+    DeviceState qdev;
+    uint32_t    slot; // For future use with multiple slot reader.
+};
+
+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__
+
hw/usb-ccid.c new file +1355 -0

1,355 lines not on this page · raw message

Signature · 1 line
1.7.4
#10 lore raw

Re: [Qemu-devel] [PATCH 05/20] usb-ccid: add CCID bus

Quoted 66 lines · Alon Levy

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.

---
  Makefile.objs |    1 +
  configure     |    6 +
  hw/ccid.h     |   35 ++
  hw/usb-ccid.c | 1355 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  4 files changed, 1397 insertions(+), 0 deletions(-)

create mode 100644 hw/ccid.h
create mode 100644 hw/usb-ccid.c

Makefile.objs +1 -0
index f1c7bfe..a1f3853 100644
@@ -195,6 +195,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
configure +6 -0
index 598e8e1..14a035a 100755
@@ -174,6 +174,7 @@ trace_backend="nop"
  trace_file="trace"
  spice=""
  rbd=""
+smartcard="yes"
 
  # parse CC options first
  for opt do
@@ -2472,6 +2473,7 @@ echo "Trace output file $trace_file-<pid>"
  echo "spice support     $spice"
  echo "rbd support       $rbd"
  echo "xfsctl support    $xfs"
+echo "smartcard support $smartcard"
 
  if test $sdl_too_old = "yes"; then
  echo "->  Your SDL version is too old - please upgrade to have SDL support"
@@ -2744,6 +2746,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
hw/ccid.h new file +0 -0
new file mode 100644
index 0000000..af59070

hw/ccid.h line 2

Quoted 2 lines
hw/ccid.h new file +2 -0
@@ -0,0 +1,35 @@
+#ifndef __CCID_H__
+#define __CCID_H__

Missing copyright, plus identifiers can't start with __.

hw/ccid.h line 12

Quoted 11 lines
hw/ccid.h new file +10 -0
+
+#include "qdev.h"
+
+typedef struct CCIDCardState CCIDCardState;
+typedef struct CCIDCardInfo CCIDCardInfo;
+
+struct CCIDCardState {
+    DeviceState qdev;
+    uint32_t    slot; // For future use with multiple slot reader.
+};

Please stick to C89 comments.

Quoted 1,368 lines
hw/ccid.h new file +23 -0
+
+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__
+
hw/usb-ccid.c new file +1338 -0
new file mode 100644
index 0000000..58f69a6
@@ -0,0 +1,1355 @@
+/*
+ * CCID Device emulation
+ *
+ * Based on usb-serial.c:
+ * Copyright (c) 2006 CodeSourcery.
+ * Copyright (c) 2008 Samuel Thibault<[email protected]>
+ * 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
+ *
+ * Endianess note: from the spec (1.3)
+ *  "Fields that are larger than a byte are stored in little endian
+ *
+ * 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. This 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.
+ *
+ * Migration note:
+ *
+ * All the VMStateDescription's are left here for future use, but
+ * not enabled right now since there is no support for USB migration.
+ *
+ * To enable define ENABLE_MIGRATION
+ */
+
+#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 guest 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__)) CCID_Header {
+    uint8_t     bMessageType;
+    uint32_t    dwLength;
+    uint8_t     bSlot;
+    uint8_t     bSeq;
+} CCID_Header;
+
+typedef struct __attribute__ ((__packed__)) CCID_BULK_IN {
+    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_SlotStatus {
+    CCID_BULK_IN b;
+    uint8_t     bClockStatus;
+} CCID_SlotStatus;
+
+typedef struct __attribute__ ((__packed__)) CCID_Parameter {
+    CCID_BULK_IN b;
+    uint8_t     bProtocolNum;
+    uint8_t     abProtocolDataStructure[0];
+} CCID_Parameter;
+
+typedef struct __attribute__ ((__packed__)) CCID_DataBlock {
+    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_XferBlock {
+    CCID_Header  hdr;
+    uint8_t      bBWI; /* Block Waiting Timeout */
+    uint16_t     wLevelParameter; /* XXX currently unused */
+    uint8_t      abData[0];
+} CCID_XferBlock;
+
+typedef struct __attribute__ ((__packed__)) CCID_IccPowerOn {
+    CCID_Header hdr;
+    uint8_t     bPowerSelect;
+    uint16_t    abRFU;
+} CCID_IccPowerOn;
+
+typedef struct __attribute__ ((__packed__)) CCID_IccPowerOff {
+    CCID_Header hdr;
+    uint16_t    abRFU;
+} CCID_IccPowerOff;
+
+typedef struct __attribute__ ((__packed__)) CCID_SetParameter {
+    CCID_Header hdr;
+    uint8_t     bProtocolNum;
+    uint8_t    abProtocolDataStructure[0];
+} CCID_SetParameter;
+
+typedef struct CCID_Notify_Slot_Change {
+    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 {
+    uint8_t slot;
+    uint8_t seq;
+} Answer;
+
+/* pending BULK_IN messages */
+typedef struct BulkIn {
+    uint8_t  data[BULK_IN_BUF_SIZE];
+    uint32_t len;
+    uint32_t pos;
+} BulkIn;
+
+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;
+    BulkIn 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;
+    BulkIn *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 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;
+    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 *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* 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 *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 void* ccid_reserve_recv_buf(USBCCIDState* s, uint16_t len)
+{
+    BulkIn* 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). discarding message.\n",
+            __func__, len, BULK_IN_BUF_SIZE);
+        return NULL;
+    }
+    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);
+}
+
+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_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_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 = 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 = cpu_to_le32(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)
+{
+    uint32_t len;
+
+    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;
+    }
+    len = le32_to_cpu(recv->hdr.dwLength);
+    DPRINTF(s, 1, "%s: seq %d, len %d\n", __FUNCTION__,
+                recv->hdr.bSeq, len);
+    ccid_add_pending_answer(s, (CCID_Header*)recv);
+    if (s->card) {
+        s->cardinfo->apdu_from_guest(s->card, recv->abData, len);
+    } else {
+        printf("warning: discarded apdu\n");
+    }
+}
+
+/* handle a single USB_TOKEN_OUT, return value returned to guest.
+ * 0 - all ok
+ * USB_RET_STALL - failed to handle packet */
+static int ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
+{
+    CCID_Header* ccid_header;
+
+    if (p->len + s->bulk_out_pos>  BULK_OUT_DATA_SIZE) {
+        return USB_RET_STALL;
+    }
+    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 0;
+    }
+    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;
+    return 0;
+}
+
+static int ccid_bulk_in_copy_to_guest(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:
+        ret = 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_to_guest(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 *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,
+    .props = (Property[]) {
+        DEFINE_PROP_UINT32("slot", struct CCIDCardState, slot, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    }
+};
+
+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 *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->migration_state == MIGRATION_MIGRATED) {
+        s->migration_state = MIGRATION_NONE;
+    }
+    return 0;
+}
+
+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)
+{
+    int ret = 0;
+    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) {
+        ret = info->exitfn(card);
+    }
+    s->card = NULL;
+    s->cardinfo = NULL;
+    return ret;
+}
+
+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);
+    int ret = 0;
+
+    if (card->slot != 0) {
+        fprintf(stderr, "Warning: usb-ccid supports one slot, can't add %d",
+                card->slot);
+        return -1;
+    }
+    if (s->card != NULL) {
+        fprintf(stderr, "Warning: usb-ccid card already full, not adding\n");
+        return -1;
+    }
+    ret = info->initfn ? info->initfn(card) : ret;
+    if (ret == 0) {
+        s->card = card;
+        s->cardinfo = info;
+    }
+    return ret;
+}
+
+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;
+    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;
+}
+
+#ifdef ENABLE_MIGRATION
+static int ccid_post_load(void *opaque, int version_id)
+{
+    USBCCIDState *s = opaque;
+
+    // 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->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_vmstate = {
+    .name = "CCID BulkIn state",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_BUFFER(data, BulkIn),
+        VMSTATE_UINT32(len, BulkIn),
+        VMSTATE_UINT32(pos, BulkIn),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static VMStateDescription answer_vmstate = {
+    .name = "CCID Answer state",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_UINT8(slot, Answer),
+        VMSTATE_UINT8(seq, Answer),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static VMStateDescription usb_device_vmstate = {
+    .name = "usb_device",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_UINT8(addr, USBDevice),
+        VMSTATE_BUFFER(setup_buf, USBDevice),
+        VMSTATE_BUFFER(data_buf, USBDevice),
+        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_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_vmstate, BulkIn),
+        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_vmstate, Answer),
+        VMSTATE_UINT32(pending_answers_num, USBCCIDState),
+        VMSTATE_UINT8(migration_state, USBCCIDState),
+        VMSTATE_UINT32(state_vmstate, USBCCIDState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+#endif // ENABLE_MIGRATION
+
+static struct USBDeviceInfo ccid_info = {
+    .product_desc   = "QEMU USB CCID",
+    .qdev.name      = CCID_DEV_NAME,
+    .qdev.size      = sizeof(USBCCIDState),
+    .init           = ccid_initfn,
+    .handle_packet  = usb_generic_handle_packet,
+    .handle_reset   = ccid_handle_reset,
+    .handle_control = ccid_handle_control,
+    .handle_data    = ccid_handle_data,

hw/usb-ccid.c line 1348

Quoted 10 lines
hw/usb-ccid.c new file +10 -0
+    .handle_destroy = ccid_handle_destroy,
+    .usbdevice_name = "ccid",
+    .qdev.props     = (Property[]) {
+        DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    },
+#ifdef ENABLE_MIGRATION
+    .qdev.vmsd      =&ccid_vmstate,
+#endif
+};

Why is ENABLE_MIGRATION conditional?

Regards,

ANthony Liguori

Quoted 8 lines
hw/usb-ccid.c new file +7 -0
+
+
+static void ccid_register_devices(void)
+{
+    usb_qdev_register(&ccid_info);
+}
+device_init(ccid_register_devices)
author
#11 lore raw

Re: [Qemu-devel] [PATCH 05/20] usb-ccid: add CCID bus

Quoted 62 lines · Anthony Liguori
Quoted 61 lines · Alon Levy

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.

---
 Makefile.objs |    1 +
 configure     |    6 +
 hw/ccid.h     |   35 ++
 hw/usb-ccid.c | 1355 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1397 insertions(+), 0 deletions(-)
 create mode 100644 hw/ccid.h
 create mode 100644 hw/usb-ccid.c
Makefile.objs +1 -0
index f1c7bfe..a1f3853 100644
@@ -195,6 +195,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
configure +6 -0
index 598e8e1..14a035a 100755
@@ -174,6 +174,7 @@ trace_backend="nop"
 trace_file="trace"
 spice=""
 rbd=""
+smartcard="yes"
 
 # parse CC options first
 for opt do
@@ -2472,6 +2473,7 @@ echo "Trace output file $trace_file-<pid>"
 echo "spice support     $spice"
 echo "rbd support       $rbd"
 echo "xfsctl support    $xfs"
+echo "smartcard support $smartcard"
 
 if test $sdl_too_old = "yes"; then
 echo "->  Your SDL version is too old - please upgrade to have SDL support"
@@ -2744,6 +2746,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
hw/ccid.h new file +0 -0
new file mode 100644
Quoted 8 lines

hw/ccid.h line 2

Quoted 6 lines

index 0000000..af59070

hw/ccid.h new file +2 -0
@@ -0,0 +1,35 @@
+#ifndef __CCID_H__
+#define __CCID_H__

Missing copyright, plus identifiers can't start with __.

Will fix. Again.

Quoted 14 lines

hw/ccid.h line 12

Quoted 11 lines
hw/ccid.h new file +10 -0
+
+#include "qdev.h"
+
+typedef struct CCIDCardState CCIDCardState;
+typedef struct CCIDCardInfo CCIDCardInfo;
+
+struct CCIDCardState {
+    DeviceState qdev;
+    uint32_t    slot; // For future use with multiple slot reader.
+};

Please stick to C89 comments.

Another oops.

Quoted 1,371 lines
Quoted 1,371 lines
hw/ccid.h new file +23 -0
+
+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__
+
hw/usb-ccid.c new file +1342 -0
new file mode 100644
index 0000000..58f69a6
@@ -0,0 +1,1355 @@
+/*
+ * CCID Device emulation
+ *
+ * Based on usb-serial.c:
+ * Copyright (c) 2006 CodeSourcery.
+ * Copyright (c) 2008 Samuel Thibault<[email protected]>
+ * 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
+ *
+ * Endianess note: from the spec (1.3)
+ *  "Fields that are larger than a byte are stored in little endian
+ *
+ * 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. This 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.
+ *
+ * Migration note:
+ *
+ * All the VMStateDescription's are left here for future use, but
+ * not enabled right now since there is no support for USB migration.
+ *
+ * To enable define ENABLE_MIGRATION
+ */
+
+#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 guest 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__)) CCID_Header {
+    uint8_t     bMessageType;
+    uint32_t    dwLength;
+    uint8_t     bSlot;
+    uint8_t     bSeq;
+} CCID_Header;
+
+typedef struct __attribute__ ((__packed__)) CCID_BULK_IN {
+    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_SlotStatus {
+    CCID_BULK_IN b;
+    uint8_t     bClockStatus;
+} CCID_SlotStatus;
+
+typedef struct __attribute__ ((__packed__)) CCID_Parameter {
+    CCID_BULK_IN b;
+    uint8_t     bProtocolNum;
+    uint8_t     abProtocolDataStructure[0];
+} CCID_Parameter;
+
+typedef struct __attribute__ ((__packed__)) CCID_DataBlock {
+    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_XferBlock {
+    CCID_Header  hdr;
+    uint8_t      bBWI; /* Block Waiting Timeout */
+    uint16_t     wLevelParameter; /* XXX currently unused */
+    uint8_t      abData[0];
+} CCID_XferBlock;
+
+typedef struct __attribute__ ((__packed__)) CCID_IccPowerOn {
+    CCID_Header hdr;
+    uint8_t     bPowerSelect;
+    uint16_t    abRFU;
+} CCID_IccPowerOn;
+
+typedef struct __attribute__ ((__packed__)) CCID_IccPowerOff {
+    CCID_Header hdr;
+    uint16_t    abRFU;
+} CCID_IccPowerOff;
+
+typedef struct __attribute__ ((__packed__)) CCID_SetParameter {
+    CCID_Header hdr;
+    uint8_t     bProtocolNum;
+    uint8_t    abProtocolDataStructure[0];
+} CCID_SetParameter;
+
+typedef struct CCID_Notify_Slot_Change {
+    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 {
+    uint8_t slot;
+    uint8_t seq;
+} Answer;
+
+/* pending BULK_IN messages */
+typedef struct BulkIn {
+    uint8_t  data[BULK_IN_BUF_SIZE];
+    uint32_t len;
+    uint32_t pos;
+} BulkIn;
+
+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;
+    BulkIn 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;
+    BulkIn *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 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;
+    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 *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* 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 *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 void* ccid_reserve_recv_buf(USBCCIDState* s, uint16_t len)
+{
+    BulkIn* 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). discarding message.\n",
+            __func__, len, BULK_IN_BUF_SIZE);
+        return NULL;
+    }
+    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);
+}
+
+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_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_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 = 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 = cpu_to_le32(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)
+{
+    uint32_t len;
+
+    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;
+    }
+    len = le32_to_cpu(recv->hdr.dwLength);
+    DPRINTF(s, 1, "%s: seq %d, len %d\n", __FUNCTION__,
+                recv->hdr.bSeq, len);
+    ccid_add_pending_answer(s, (CCID_Header*)recv);
+    if (s->card) {
+        s->cardinfo->apdu_from_guest(s->card, recv->abData, len);
+    } else {
+        printf("warning: discarded apdu\n");
+    }
+}
+
+/* handle a single USB_TOKEN_OUT, return value returned to guest.
+ * 0 - all ok
+ * USB_RET_STALL - failed to handle packet */
+static int ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
+{
+    CCID_Header* ccid_header;
+
+    if (p->len + s->bulk_out_pos>  BULK_OUT_DATA_SIZE) {
+        return USB_RET_STALL;
+    }
+    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 0;
+    }
+    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;
+    return 0;
+}
+
+static int ccid_bulk_in_copy_to_guest(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:
+        ret = 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_to_guest(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 *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,
+    .props = (Property[]) {
+        DEFINE_PROP_UINT32("slot", struct CCIDCardState, slot, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    }
+};
+
+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 *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->migration_state == MIGRATION_MIGRATED) {
+        s->migration_state = MIGRATION_NONE;
+    }
+    return 0;
+}
+
+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)
+{
+    int ret = 0;
+    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) {
+        ret = info->exitfn(card);
+    }
+    s->card = NULL;
+    s->cardinfo = NULL;
+    return ret;
+}
+
+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);
+    int ret = 0;
+
+    if (card->slot != 0) {
+        fprintf(stderr, "Warning: usb-ccid supports one slot, can't add %d",
+                card->slot);
+        return -1;
+    }
+    if (s->card != NULL) {
+        fprintf(stderr, "Warning: usb-ccid card already full, not adding\n");
+        return -1;
+    }
+    ret = info->initfn ? info->initfn(card) : ret;
+    if (ret == 0) {
+        s->card = card;
+        s->cardinfo = info;
+    }
+    return ret;
+}
+
+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;
+    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;
+}
+
+#ifdef ENABLE_MIGRATION
+static int ccid_post_load(void *opaque, int version_id)
+{
+    USBCCIDState *s = opaque;
+
+    // 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->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_vmstate = {
+    .name = "CCID BulkIn state",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_BUFFER(data, BulkIn),
+        VMSTATE_UINT32(len, BulkIn),
+        VMSTATE_UINT32(pos, BulkIn),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static VMStateDescription answer_vmstate = {
+    .name = "CCID Answer state",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_UINT8(slot, Answer),
+        VMSTATE_UINT8(seq, Answer),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static VMStateDescription usb_device_vmstate = {
+    .name = "usb_device",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_UINT8(addr, USBDevice),
+        VMSTATE_BUFFER(setup_buf, USBDevice),
+        VMSTATE_BUFFER(data_buf, USBDevice),
+        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_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_vmstate, BulkIn),
+        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_vmstate, Answer),
+        VMSTATE_UINT32(pending_answers_num, USBCCIDState),
+        VMSTATE_UINT8(migration_state, USBCCIDState),
+        VMSTATE_UINT32(state_vmstate, USBCCIDState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+#endif // ENABLE_MIGRATION
+
+static struct USBDeviceInfo ccid_info = {
+    .product_desc   = "QEMU USB CCID",
+    .qdev.name      = CCID_DEV_NAME,
+    .qdev.size      = sizeof(USBCCIDState),
+    .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("debug", USBCCIDState, debug, 0),
Quoted 9 lines

hw/usb-ccid.c line 1348

Quoted 6 lines
hw/usb-ccid.c new file +6 -0
+        DEFINE_PROP_END_OF_LIST(),
+    },
+#ifdef ENABLE_MIGRATION
+    .qdev.vmsd      =&ccid_vmstate,
+#endif
+};

Why is ENABLE_MIGRATION conditional?

A third oops. Will fix.

Quoted 13 lines

Regards,

ANthony Liguori

Quoted 7 lines
hw/usb-ccid.c new file +7 -0
+
+
+static void ccid_register_devices(void)
+{
+    usb_qdev_register(&ccid_info);
+}
+device_init(ccid_register_devices)
author
#12 lore raw

Re: [Qemu-devel] [PATCH 05/20] usb-ccid: add CCID bus

Quoted 1,472 lines · Alon Levy
Quoted 62 lines · Anthony Liguori
Quoted 61 lines · Alon Levy

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.

---
 Makefile.objs |    1 +
 configure     |    6 +
 hw/ccid.h     |   35 ++
 hw/usb-ccid.c | 1355 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 1397 insertions(+), 0 deletions(-)
 create mode 100644 hw/ccid.h
 create mode 100644 hw/usb-ccid.c
Makefile.objs +1 -0
index f1c7bfe..a1f3853 100644
@@ -195,6 +195,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
configure +6 -0
index 598e8e1..14a035a 100755
@@ -174,6 +174,7 @@ trace_backend="nop"
 trace_file="trace"
 spice=""
 rbd=""
+smartcard="yes"
 
 # parse CC options first
 for opt do
@@ -2472,6 +2473,7 @@ echo "Trace output file $trace_file-<pid>"
 echo "spice support     $spice"
 echo "rbd support       $rbd"
 echo "xfsctl support    $xfs"
+echo "smartcard support $smartcard"
 
 if test $sdl_too_old = "yes"; then
 echo "->  Your SDL version is too old - please upgrade to have SDL support"
@@ -2744,6 +2746,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
hw/ccid.h new file +0 -0
new file mode 100644
Quoted 8 lines

hw/ccid.h line 2

Quoted 6 lines

index 0000000..af59070

hw/ccid.h new file +2 -0
@@ -0,0 +1,35 @@
+#ifndef __CCID_H__
+#define __CCID_H__

Missing copyright, plus identifiers can't start with __.

Will fix. Again.

Quoted 14 lines

hw/ccid.h line 12

Quoted 11 lines
hw/ccid.h new file +10 -0
+
+#include "qdev.h"
+
+typedef struct CCIDCardState CCIDCardState;
+typedef struct CCIDCardInfo CCIDCardInfo;
+
+struct CCIDCardState {
+    DeviceState qdev;
+    uint32_t    slot; // For future use with multiple slot reader.
+};

Please stick to C89 comments.

Another oops.

Quoted 1,371 lines
Quoted 1,371 lines
hw/ccid.h new file +23 -0
+
+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__
+
hw/usb-ccid.c new file +1342 -0
new file mode 100644
index 0000000..58f69a6
@@ -0,0 +1,1355 @@
+/*
+ * CCID Device emulation
+ *
+ * Based on usb-serial.c:
+ * Copyright (c) 2006 CodeSourcery.
+ * Copyright (c) 2008 Samuel Thibault<[email protected]>
+ * 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
+ *
+ * Endianess note: from the spec (1.3)
+ *  "Fields that are larger than a byte are stored in little endian
+ *
+ * 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. This 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.
+ *
+ * Migration note:
+ *
+ * All the VMStateDescription's are left here for future use, but
+ * not enabled right now since there is no support for USB migration.
+ *
+ * To enable define ENABLE_MIGRATION
+ */
+
+#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 guest 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__)) CCID_Header {
+    uint8_t     bMessageType;
+    uint32_t    dwLength;
+    uint8_t     bSlot;
+    uint8_t     bSeq;
+} CCID_Header;
+
+typedef struct __attribute__ ((__packed__)) CCID_BULK_IN {
+    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_SlotStatus {
+    CCID_BULK_IN b;
+    uint8_t     bClockStatus;
+} CCID_SlotStatus;
+
+typedef struct __attribute__ ((__packed__)) CCID_Parameter {
+    CCID_BULK_IN b;
+    uint8_t     bProtocolNum;
+    uint8_t     abProtocolDataStructure[0];
+} CCID_Parameter;
+
+typedef struct __attribute__ ((__packed__)) CCID_DataBlock {
+    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_XferBlock {
+    CCID_Header  hdr;
+    uint8_t      bBWI; /* Block Waiting Timeout */
+    uint16_t     wLevelParameter; /* XXX currently unused */
+    uint8_t      abData[0];
+} CCID_XferBlock;
+
+typedef struct __attribute__ ((__packed__)) CCID_IccPowerOn {
+    CCID_Header hdr;
+    uint8_t     bPowerSelect;
+    uint16_t    abRFU;
+} CCID_IccPowerOn;
+
+typedef struct __attribute__ ((__packed__)) CCID_IccPowerOff {
+    CCID_Header hdr;
+    uint16_t    abRFU;
+} CCID_IccPowerOff;
+
+typedef struct __attribute__ ((__packed__)) CCID_SetParameter {
+    CCID_Header hdr;
+    uint8_t     bProtocolNum;
+    uint8_t    abProtocolDataStructure[0];
+} CCID_SetParameter;
+
+typedef struct CCID_Notify_Slot_Change {
+    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 {
+    uint8_t slot;
+    uint8_t seq;
+} Answer;
+
+/* pending BULK_IN messages */
+typedef struct BulkIn {
+    uint8_t  data[BULK_IN_BUF_SIZE];
+    uint32_t len;
+    uint32_t pos;
+} BulkIn;
+
+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;
+    BulkIn 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;
+    BulkIn *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 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;
+    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 *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* 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 *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 void* ccid_reserve_recv_buf(USBCCIDState* s, uint16_t len)
+{
+    BulkIn* 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). discarding message.\n",
+            __func__, len, BULK_IN_BUF_SIZE);
+        return NULL;
+    }
+    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);
+}
+
+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_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_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 = 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 = cpu_to_le32(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)
+{
+    uint32_t len;
+
+    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;
+    }
+    len = le32_to_cpu(recv->hdr.dwLength);
+    DPRINTF(s, 1, "%s: seq %d, len %d\n", __FUNCTION__,
+                recv->hdr.bSeq, len);
+    ccid_add_pending_answer(s, (CCID_Header*)recv);
+    if (s->card) {
+        s->cardinfo->apdu_from_guest(s->card, recv->abData, len);
+    } else {
+        printf("warning: discarded apdu\n");
+    }
+}
+
+/* handle a single USB_TOKEN_OUT, return value returned to guest.
+ * 0 - all ok
+ * USB_RET_STALL - failed to handle packet */
+static int ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
+{
+    CCID_Header* ccid_header;
+
+    if (p->len + s->bulk_out_pos>  BULK_OUT_DATA_SIZE) {
+        return USB_RET_STALL;
+    }
+    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 0;
+    }
+    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;
+    return 0;
+}
+
+static int ccid_bulk_in_copy_to_guest(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:
+        ret = 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_to_guest(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 *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,
+    .props = (Property[]) {
+        DEFINE_PROP_UINT32("slot", struct CCIDCardState, slot, 0),
+        DEFINE_PROP_END_OF_LIST(),
+    }
+};
+
+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 *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->migration_state == MIGRATION_MIGRATED) {
+        s->migration_state = MIGRATION_NONE;
+    }
+    return 0;
+}
+
+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)
+{
+    int ret = 0;
+    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) {
+        ret = info->exitfn(card);
+    }
+    s->card = NULL;
+    s->cardinfo = NULL;
+    return ret;
+}
+
+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);
+    int ret = 0;
+
+    if (card->slot != 0) {
+        fprintf(stderr, "Warning: usb-ccid supports one slot, can't add %d",
+                card->slot);
+        return -1;
+    }
+    if (s->card != NULL) {
+        fprintf(stderr, "Warning: usb-ccid card already full, not adding\n");
+        return -1;
+    }
+    ret = info->initfn ? info->initfn(card) : ret;
+    if (ret == 0) {
+        s->card = card;
+        s->cardinfo = info;
+    }
+    return ret;
+}
+
+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;
+    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;
+}
+
+#ifdef ENABLE_MIGRATION
+static int ccid_post_load(void *opaque, int version_id)
+{
+    USBCCIDState *s = opaque;
+
+    // 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->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_vmstate = {
+    .name = "CCID BulkIn state",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_BUFFER(data, BulkIn),
+        VMSTATE_UINT32(len, BulkIn),
+        VMSTATE_UINT32(pos, BulkIn),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static VMStateDescription answer_vmstate = {
+    .name = "CCID Answer state",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_UINT8(slot, Answer),
+        VMSTATE_UINT8(seq, Answer),
+        VMSTATE_END_OF_LIST()
+    }
+};
+
+static VMStateDescription usb_device_vmstate = {
+    .name = "usb_device",
+    .version_id = 1,
+    .minimum_version_id = 1,
+    .fields = (VMStateField []) {
+        VMSTATE_UINT8(addr, USBDevice),
+        VMSTATE_BUFFER(setup_buf, USBDevice),
+        VMSTATE_BUFFER(data_buf, USBDevice),
+        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_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_vmstate, BulkIn),
+        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_vmstate, Answer),
+        VMSTATE_UINT32(pending_answers_num, USBCCIDState),
+        VMSTATE_UINT8(migration_state, USBCCIDState),
+        VMSTATE_UINT32(state_vmstate, USBCCIDState),
+        VMSTATE_END_OF_LIST()
+    }
+};
+#endif // ENABLE_MIGRATION
+
+static struct USBDeviceInfo ccid_info = {
+    .product_desc   = "QEMU USB CCID",
+    .qdev.name      = CCID_DEV_NAME,
+    .qdev.size      = sizeof(USBCCIDState),
+    .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("debug", USBCCIDState, debug, 0),
Quoted 9 lines

hw/usb-ccid.c line 1348

Quoted 6 lines
hw/usb-ccid.c new file +6 -0
+        DEFINE_PROP_END_OF_LIST(),
+    },
+#ifdef ENABLE_MIGRATION
+    .qdev.vmsd      =&ccid_vmstate,
+#endif
+};

Why is ENABLE_MIGRATION conditional?

Quoted 2 lines

A third oops. Will fix.

Actually it was fixed, just in the "v15->v16" corrections.

Will be easier to spot in v17.

Quoted 14 lines
Quoted 13 lines

Regards,

ANthony Liguori

Quoted 7 lines
hw/usb-ccid.c new file +7 -0
+
+
+static void ccid_register_devices(void)
+{
+    usb_qdev_register(&ccid_info);
+}
+device_init(ccid_register_devices)
author
#13 lore raw

PATCH 6/20 usb-ccid: review fixes (v15-v16)

In reply to Alon Levy

I'll fold it before submitting the version to be applied, but I hope keeping it as a separate patch will make reviewing easier.

Behavioral changes:
* fix abort on client answer after card remove
* enable migration
* remove side affect code from asserts
* return consistent self-powered state
* mask out reserved bits in ccid_set_parameters
* add missing abRFU in SetParameters (no affect on linux guest)

whitefixes / comments / consts defines:
* remove stale comment
* remove ccid_print_pending_answers if no DEBUG_CCID
* replace printf's with DPRINTF, remove DEBUG_CCID, add verbosity defines
* use error_report
* update copyright (most of the code is not original)
* reword known bug comment
* add missing closing quote in comment
* add missing whitespace on one line
* s/CCID_SetParameter/CCID_SetParameters/
* add comments
* use define for max packet size

Comment for "return consistent self-powered state":

the Configuration Descriptor bmAttributes claims we are self powered, but we were returning not self powered to USB_REQ_GET_STATUS control message.

In practice, this message is not sent by a linux 2.6.35.10-74.fc14.x86_64 guest (not tested on other guests), unless you issue lsusb -v as root (for example).

---
 hw/ccid.h     |    7 +++
 hw/usb-ccid.c |  115 ++++++++++++++++++++++++++++-----------------------------
 2 files changed, 63 insertions(+), 59 deletions(-)
hw/ccid.h +7 -0
index af59070..f5dcfae 100644
@@ -6,11 +6,16 @@
 typedef struct CCIDCardState CCIDCardState;
 typedef struct CCIDCardInfo CCIDCardInfo;
 
+/* state of the CCID Card device (i.e. hw/ccid-card-*.c)
+ */
 struct CCIDCardState {
     DeviceState qdev;
     uint32_t    slot; // For future use with multiple slot reader.
 };
 
+/* callbacks to be used by the CCID device (hw/usb-ccid.c) to call
+ * into the smartcard device (hw/ccid-card-*.c)
+ */
 struct CCIDCardInfo {
     DeviceInfo qdev;
     void (*print)(Monitor *mon, CCIDCardState *card, int indent);
@@ -20,6 +25,8 @@ struct CCIDCardInfo {
     int (*initfn)(CCIDCardState *card);
 };
 
+/* API for smartcard calling the CCID device (used by hw/ccid-card-*.c)
+ */
 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);
hw/usb-ccid.c +56 -59

318 lines not on this page · raw message

Signature · 1 line
1.7.4
#14 lore raw

Re: [Qemu-devel] [PATCH 06/20] usb-ccid: review fixes (v15-v16)

Quoted 3 lines · Alon Levy

I'll fold it before submitting the version to be applied, but I hope keeping it as a separate patch will make reviewing easier.

Hrm, can you just send out the new patches? It's actually harder to review like this.

Regards,

Anthony Liguori

Quoted 413 lines

Behavioral changes:
* fix abort on client answer after card remove
* enable migration
* remove side affect code from asserts
* return consistent self-powered state
* mask out reserved bits in ccid_set_parameters
* add missing abRFU in SetParameters (no affect on linux guest)

whitefixes / comments / consts defines:
* remove stale comment
* remove ccid_print_pending_answers if no DEBUG_CCID
* replace printf's with DPRINTF, remove DEBUG_CCID, add verbosity defines
* use error_report
* update copyright (most of the code is not original)
* reword known bug comment
* add missing closing quote in comment
* add missing whitespace on one line
* s/CCID_SetParameter/CCID_SetParameters/
* add comments
* use define for max packet size

Comment for "return consistent self-powered state":

the Configuration Descriptor bmAttributes claims we are self powered, but we were returning not self powered to USB_REQ_GET_STATUS control message.

In practice, this message is not sent by a linux 2.6.35.10-74.fc14.x86_64 guest (not tested on other guests), unless you issue lsusb -v as root (for example).

---
  hw/ccid.h     |    7 +++
  hw/usb-ccid.c |  115 ++++++++++++++++++++++++++++-----------------------------
  2 files changed, 63 insertions(+), 59 deletions(-)
hw/ccid.h +7 -0
index af59070..f5dcfae 100644
@@ -6,11 +6,16 @@
  typedef struct CCIDCardState CCIDCardState;
  typedef struct CCIDCardInfo CCIDCardInfo;
 
+/* state of the CCID Card device (i.e. hw/ccid-card-*.c)
+ */
  struct CCIDCardState {
      DeviceState qdev;
      uint32_t    slot; // For future use with multiple slot reader.
  };
 
+/* callbacks to be used by the CCID device (hw/usb-ccid.c) to call
+ * into the smartcard device (hw/ccid-card-*.c)
+ */
  struct CCIDCardInfo {
      DeviceInfo qdev;
      void (*print)(Monitor *mon, CCIDCardState *card, int indent);
@@ -20,6 +25,8 @@ struct CCIDCardInfo {
      int (*initfn)(CCIDCardState *card);
  };
 
+/* API for smartcard calling the CCID device (used by hw/ccid-card-*.c)
+ */
  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);
hw/usb-ccid.c +56 -59
index 58f69a6..09e39ac 100644
@@ -1,15 +1,18 @@
  /*
   * CCID Device emulation
   *
- * Based on usb-serial.c:
+ * Written by Alon Levy, with contributions from Robert Relyea.
+ *
+ * Based on usb-serial.c, see it's copyright and attributions below.
+ *
+ * This code is licenced under the GNU LGPL, version 2 or later.
+ *
+ * -------
+ *
+ * usb-serial.c copyright and attribution:
   * Copyright (c) 2006 CodeSourcery.
   * Copyright (c) 2008 Samuel Thibault<[email protected]>
   * 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:
@@ -19,22 +22,16 @@
   *  Specification for Integrated Circuit(s) Cards Interface Devices
   *
   * Endianess note: from the spec (1.3)
- *  "Fields that are larger than a byte are stored in little endian
+ *  "Fields that are larger than a byte are stored in little endian"
   *
   * 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. This 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.
+ *  symptom: dmesg shows ERMOTEIO (-121), pcscd shows -99. This can happen
+ *  when a short packet is sent, as seen in uhci-usb.c, resulting from a urb
+ *  from the guest requesting SPD and us returning a smaller packet.
   *  Not sure which messages trigger this.
   *
- * Migration note:
- *
- * All the VMStateDescription's are left here for future use, but
- * not enabled right now since there is no support for USB migration.
- *
- * To enable define ENABLE_MIGRATION
   */
 
  #include "qemu-common.h"
@@ -44,11 +41,14 @@
 
  #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 D_WARN 1
+#define D_INFO 2
+#define D_MORE_INFO 3
+#define D_VERBOSE 4
+
  #define CCID_DEV_NAME "usb-ccid"
 
  /* The two options for variable sized buffers:
@@ -64,6 +64,8 @@ do { if (lvl<= s->debug) { printf("usb-ccid: " fmt , ## __VA_ARGS__); } } while
  #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_MAX_PACKET_SIZE                64
+
  #define CCID_CONTROL_ABORT                  0x1
  #define CCID_CONTROL_GET_CLOCK_FREQUENCIES  0x2
  #define CCID_CONTROL_GET_DATA_RATES         0x3
@@ -209,11 +211,12 @@ typedef struct __attribute__ ((__packed__)) CCID_IccPowerOff {
      uint16_t    abRFU;
  } CCID_IccPowerOff;
 
-typedef struct __attribute__ ((__packed__)) CCID_SetParameter {
+typedef struct __attribute__ ((__packed__)) CCID_SetParameters {
      CCID_Header hdr;
      uint8_t     bProtocolNum;
+    uint16_t   abRFU;
      uint8_t    abProtocolDataStructure[0];
-} CCID_SetParameter;
+} CCID_SetParameters;
 
  typedef struct CCID_Notify_Slot_Change {
      uint8_t     bMessageType; /* CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange */
@@ -278,10 +281,6 @@ struct USBCCIDState {
      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.
@@ -416,7 +415,8 @@ static const uint8_t qemu_ccid_config_descriptor[] = {
                      /*  u8  ep_bEndpointAddress; IN Endpoint 1 */
          0x80 | CCID_INT_IN_EP,
          0x03,       /*  u8  ep_bmAttributes; Interrupt */
-        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
+                    /*  u16 ep_wMaxPacketSize; */
+        CCID_MAX_PACKET_SIZE&  0xff, (CCID_MAX_PACKET_SIZE>>  8),
          0xff,       /*  u8  ep_bInterval; */
 
          /* Bulk-In endpoint */
@@ -455,32 +455,31 @@ static void ccid_clear_pending_answers(USBCCIDState *s)
 
  static void ccid_print_pending_answers(USBCCIDState *s)
  {
-#ifdef DEBUG_CCID
      Answer *answer;
      int i, count;
 
-    printf("usb-ccid: pending answers:");
+    DPRINTF(s, D_VERBOSE, "usb-ccid: pending answers:");
      if (!ccid_has_pending_answers(s)) {
-        printf(" empty\n");
+        DPRINTF(s, D_VERBOSE, " 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);
+            DPRINTF(s, D_VERBOSE, "%d:%d\n", answer->slot, answer->seq);
          } else {
-            printf("%d:%d,", answer->slot, answer->seq);
+            DPRINTF(s, D_VERBOSE, "%d:%d,", answer->slot, answer->seq);
          }
      }
-#endif
  }
 
  static void ccid_add_pending_answer(USBCCIDState *s, CCID_Header *hdr)
  {
      Answer* answer;
 
-    assert(s->pending_answers_num++<  PENDING_ANSWERS_NUM);
+    assert(s->pending_answers_num<  PENDING_ANSWERS_NUM);
+    s->pending_answers_num++;
      answer =&s->pending_answers[(s->pending_answers_end++) % PENDING_ANSWERS_NUM];
      answer->slot = hdr->bSlot;
      answer->seq = hdr->bSeq;
@@ -492,7 +491,8 @@ static void ccid_remove_pending_answer(USBCCIDState *s,
  {
      Answer *answer;
 
-    assert(s->pending_answers_num-->  0);
+    assert(s->pending_answers_num>  0);
+    s->pending_answers_num--;
      answer =&s->pending_answers[(s->pending_answers_start++) % PENDING_ANSWERS_NUM];
      *slot = answer->slot;
      *seq = answer->seq;
@@ -528,16 +528,16 @@ static void* ccid_reserve_recv_buf(USBCCIDState* s, uint16_t len)
  {
      BulkIn* bulk_in;
 
-    DPRINTF(s, 4, "%s: QUEUE: reserve %d bytes\n", __func__, len);
+    DPRINTF(s, D_VERBOSE, "%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). discarding message.\n",
+        DPRINTF(s, D_WARN, "usb-ccid.c: %s: len larger then max (%d>%d). discarding message.\n",
              __func__, len, BULK_IN_BUF_SIZE);
          return NULL;
      }
      if (s->bulk_in_pending_num>= BULK_IN_PENDING_NUM) {
-        printf("usb-ccid.c: %s: No free bulk_in buffers. discarding message.\n",
+        DPRINTF(s, D_WARN, "usb-ccid.c: %s: No free bulk_in buffers. discarding message.\n",
                  __func__);
          return NULL;
      }
@@ -576,7 +576,7 @@ static int ccid_handle_control(USBDevice *dev, int request, int value,
      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) |
+        data[0] = (1<<  USB_DEVICE_SELF_POWERED) |
              (dev->remote_wakeup<<  USB_DEVICE_REMOTE_WAKEUP);
          data[1] = 0x00;
          ret = 2;
@@ -709,7 +709,7 @@ static uint8_t ccid_calc_status(USBCCIDState *s)
         bmCommandStatus
       */
      uint8_t ret = ccid_card_status(s) | (s->bmCommandStatus<<  6);
-    DPRINTF(s, 4, "status = %d\n", ret);
+    DPRINTF(s, D_VERBOSE, "status = %d\n", ret);
      return ret;
  }
 
@@ -770,11 +770,9 @@ static void ccid_write_data_block(
      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);
+        DPRINTF(s, D_VERBOSE, "error %d", p->b.bError);
      }
-#endif
      memcpy(p->abData, data, len);
      ccid_reset_error_status(s);
  }
@@ -805,12 +803,12 @@ static void ccid_write_data_block_atr(USBCCIDState* s, CCID_Header* recv)
 
  static void ccid_set_parameters(USBCCIDState *s, CCID_Header *recv)
  {
-    CCID_SetParameter *ph = (CCID_SetParameter *) recv;
+    CCID_SetParameters *ph = (CCID_SetParameters *) recv;
      uint32_t len = 0;
-    if (ph->bProtocolNum == 0) {
+    if ((ph->bProtocolNum&  3) == 0) {
          len = 5;
      }
-    if (ph->bProtocolNum == 1) {
+    if ((ph->bProtocolNum&  3) == 1) {
          len = 7;
      }
      if (len == 0) {
@@ -884,7 +882,7 @@ static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
      if (s->card) {
          s->cardinfo->apdu_from_guest(s->card, recv->abData, len);
      } else {
-        printf("warning: discarded apdu\n");
+        DPRINTF(s, D_WARN, "warning: discarded apdu\n");
      }
  }
 
@@ -901,15 +899,15 @@ static int ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
      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",
+    if (p->len == CCID_MAX_PACKET_SIZE) {
+        DPRINTF(s, D_VERBOSE, "usb-ccid: bulk_in: expecting more packets (%d/%d)\n",
              p->len, ccid_header->dwLength);
          return 0;
      }
      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);
+        DPRINTF(s, D_MORE_INFO, "%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);
@@ -965,7 +963,7 @@ static int ccid_bulk_in_copy_to_guest(USBCCIDState *s, uint8_t *data, int len)
  {
      int ret = 0;
 
-    assert(len>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);
@@ -978,7 +976,7 @@ static int ccid_bulk_in_copy_to_guest(USBCCIDState *s, uint8_t *data, int len)
          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);
+        DPRINTF(s, D_MORE_INFO, "%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);
@@ -1015,7 +1013,7 @@ static int ccid_handle_data(USBDevice *dev, USBPacket *p)
                      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",
+                    DPRINTF(s, D_INFO, "handle_data: int_in: notify_slot_change %X, requested len %d\n",
                              s->bmSlotICCState, len);
                  }
                  break;
@@ -1146,7 +1144,11 @@ void ccid_card_card_error(CCIDCardState *card, uint64_t 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);
+    /* we flush all pending answers on CardRemove message in ccid-card-passthru,
+     * so check that first to not trigger abort */
+    if (ccid_has_pending_answers(s)) {
+        ccid_write_data_block_answer(s, NULL, 0);
+    }
  }
 
  void ccid_card_card_inserted(CCIDCardState *card)
@@ -1184,12 +1186,12 @@ static int ccid_card_init(DeviceState *qdev, DeviceInfo *base)
      int ret = 0;
 
      if (card->slot != 0) {
-        fprintf(stderr, "Warning: usb-ccid supports one slot, can't add %d",
+        error_report("Warning: usb-ccid supports one slot, can't add %d",
                  card->slot);
          return -1;
      }
      if (s->card != NULL) {
-        fprintf(stderr, "Warning: usb-ccid card already full, not adding\n");
+        error_report("Warning: usb-ccid card already full, not adding\n");
          return -1;
      }
      ret = info->initfn ? info->initfn(card) : ret;
@@ -1233,7 +1235,6 @@ static int ccid_initfn(USBDevice *dev)
      return 0;
  }
 
-#ifdef ENABLE_MIGRATION
  static int ccid_post_load(void *opaque, int version_id)
  {
      USBCCIDState *s = opaque;
@@ -1325,7 +1326,6 @@ static VMStateDescription ccid_vmstate = {
          VMSTATE_END_OF_LIST()
      }
  };
-#endif // ENABLE_MIGRATION
 
  static struct USBDeviceInfo ccid_info = {
      .product_desc   = "QEMU USB CCID",
@@ -1342,12 +1342,9 @@ static struct USBDeviceInfo ccid_info = {
          DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
          DEFINE_PROP_END_OF_LIST(),
      },
-#ifdef ENABLE_MIGRATION
      .qdev.vmsd      =&ccid_vmstate,
-#endif
  };
 
-
  static void ccid_register_devices(void)
  {
      usb_qdev_register(&ccid_info);
author
#15 lore raw

Re: [Qemu-devel] [PATCH 06/20] usb-ccid: review fixes (v15-v16)

Quoted 6 lines · Anthony Liguori
Quoted 2 lines · Alon Levy

I'll fold it before submitting the version to be applied, but I hope keeping it as a separate patch will make reviewing easier.

Hrm, can you just send out the new patches? It's actually harder
to review like this.

Yes.

Quoted 418 lines

Regards,

Anthony Liguori

Quoted 412 lines

Behavioral changes:
* fix abort on client answer after card remove
* enable migration
* remove side affect code from asserts
* return consistent self-powered state
* mask out reserved bits in ccid_set_parameters
* add missing abRFU in SetParameters (no affect on linux guest)

whitefixes / comments / consts defines:
* remove stale comment
* remove ccid_print_pending_answers if no DEBUG_CCID
* replace printf's with DPRINTF, remove DEBUG_CCID, add verbosity defines
* use error_report
* update copyright (most of the code is not original)
* reword known bug comment
* add missing closing quote in comment
* add missing whitespace on one line
* s/CCID_SetParameter/CCID_SetParameters/
* add comments
* use define for max packet size

Comment for "return consistent self-powered state":

the Configuration Descriptor bmAttributes claims we are self powered, but we were returning not self powered to USB_REQ_GET_STATUS control message.

In practice, this message is not sent by a linux 2.6.35.10-74.fc14.x86_64 guest (not tested on other guests), unless you issue lsusb -v as root (for example).

---
 hw/ccid.h     |    7 +++
 hw/usb-ccid.c |  115 ++++++++++++++++++++++++++++-----------------------------
 2 files changed, 63 insertions(+), 59 deletions(-)
hw/ccid.h +7 -0
index af59070..f5dcfae 100644
@@ -6,11 +6,16 @@
 typedef struct CCIDCardState CCIDCardState;
 typedef struct CCIDCardInfo CCIDCardInfo;
 
+/* state of the CCID Card device (i.e. hw/ccid-card-*.c)
+ */
 struct CCIDCardState {
     DeviceState qdev;
     uint32_t    slot; // For future use with multiple slot reader.
 };
 
+/* callbacks to be used by the CCID device (hw/usb-ccid.c) to call
+ * into the smartcard device (hw/ccid-card-*.c)
+ */
 struct CCIDCardInfo {
     DeviceInfo qdev;
     void (*print)(Monitor *mon, CCIDCardState *card, int indent);
@@ -20,6 +25,8 @@ struct CCIDCardInfo {
     int (*initfn)(CCIDCardState *card);
 };
 
+/* API for smartcard calling the CCID device (used by hw/ccid-card-*.c)
+ */
 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);
hw/usb-ccid.c +56 -59
index 58f69a6..09e39ac 100644
@@ -1,15 +1,18 @@
 /*
  * CCID Device emulation
  *
- * Based on usb-serial.c:
+ * Written by Alon Levy, with contributions from Robert Relyea.
+ *
+ * Based on usb-serial.c, see it's copyright and attributions below.
+ *
+ * This code is licenced under the GNU LGPL, version 2 or later.
+ *
+ * -------
+ *
+ * usb-serial.c copyright and attribution:
  * Copyright (c) 2006 CodeSourcery.
  * Copyright (c) 2008 Samuel Thibault<[email protected]>
  * 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:
@@ -19,22 +22,16 @@
  *  Specification for Integrated Circuit(s) Cards Interface Devices
  *
  * Endianess note: from the spec (1.3)
- *  "Fields that are larger than a byte are stored in little endian
+ *  "Fields that are larger than a byte are stored in little endian"
  *
  * 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. This 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.
+ *  symptom: dmesg shows ERMOTEIO (-121), pcscd shows -99. This can happen
+ *  when a short packet is sent, as seen in uhci-usb.c, resulting from a urb
+ *  from the guest requesting SPD and us returning a smaller packet.
  *  Not sure which messages trigger this.
  *
- * Migration note:
- *
- * All the VMStateDescription's are left here for future use, but
- * not enabled right now since there is no support for USB migration.
- *
- * To enable define ENABLE_MIGRATION
  */
 
 #include "qemu-common.h"
@@ -44,11 +41,14 @@
 
 #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 D_WARN 1
+#define D_INFO 2
+#define D_MORE_INFO 3
+#define D_VERBOSE 4
+
 #define CCID_DEV_NAME "usb-ccid"
 
 /* The two options for variable sized buffers:
@@ -64,6 +64,8 @@ do { if (lvl<= s->debug) { printf("usb-ccid: " fmt , ## __VA_ARGS__); } } while
 #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_MAX_PACKET_SIZE                64
+
 #define CCID_CONTROL_ABORT                  0x1
 #define CCID_CONTROL_GET_CLOCK_FREQUENCIES  0x2
 #define CCID_CONTROL_GET_DATA_RATES         0x3
@@ -209,11 +211,12 @@ typedef struct __attribute__ ((__packed__)) CCID_IccPowerOff {
     uint16_t    abRFU;
 } CCID_IccPowerOff;
 
-typedef struct __attribute__ ((__packed__)) CCID_SetParameter {
+typedef struct __attribute__ ((__packed__)) CCID_SetParameters {
     CCID_Header hdr;
     uint8_t     bProtocolNum;
+    uint16_t   abRFU;
     uint8_t    abProtocolDataStructure[0];
-} CCID_SetParameter;
+} CCID_SetParameters;
 
 typedef struct CCID_Notify_Slot_Change {
     uint8_t     bMessageType; /* CCID_MESSAGE_TYPE_RDR_to_PC_NotifySlotChange */
@@ -278,10 +281,6 @@ struct USBCCIDState {
     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.
@@ -416,7 +415,8 @@ static const uint8_t qemu_ccid_config_descriptor[] = {
                     /*  u8  ep_bEndpointAddress; IN Endpoint 1 */
         0x80 | CCID_INT_IN_EP,
         0x03,       /*  u8  ep_bmAttributes; Interrupt */
-        0x40, 0x00, /*  u16 ep_wMaxPacketSize; */
+                    /*  u16 ep_wMaxPacketSize; */
+        CCID_MAX_PACKET_SIZE&  0xff, (CCID_MAX_PACKET_SIZE>>  8),
         0xff,       /*  u8  ep_bInterval; */
 
         /* Bulk-In endpoint */
@@ -455,32 +455,31 @@ static void ccid_clear_pending_answers(USBCCIDState *s)
 
 static void ccid_print_pending_answers(USBCCIDState *s)
 {
-#ifdef DEBUG_CCID
     Answer *answer;
     int i, count;
 
-    printf("usb-ccid: pending answers:");
+    DPRINTF(s, D_VERBOSE, "usb-ccid: pending answers:");
     if (!ccid_has_pending_answers(s)) {
-        printf(" empty\n");
+        DPRINTF(s, D_VERBOSE, " 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);
+            DPRINTF(s, D_VERBOSE, "%d:%d\n", answer->slot, answer->seq);
         } else {
-            printf("%d:%d,", answer->slot, answer->seq);
+            DPRINTF(s, D_VERBOSE, "%d:%d,", answer->slot, answer->seq);
         }
     }
-#endif
 }
 
 static void ccid_add_pending_answer(USBCCIDState *s, CCID_Header *hdr)
 {
     Answer* answer;
 
-    assert(s->pending_answers_num++<  PENDING_ANSWERS_NUM);
+    assert(s->pending_answers_num<  PENDING_ANSWERS_NUM);
+    s->pending_answers_num++;
     answer =&s->pending_answers[(s->pending_answers_end++) % PENDING_ANSWERS_NUM];
     answer->slot = hdr->bSlot;
     answer->seq = hdr->bSeq;
@@ -492,7 +491,8 @@ static void ccid_remove_pending_answer(USBCCIDState *s,
 {
     Answer *answer;
 
-    assert(s->pending_answers_num-->  0);
+    assert(s->pending_answers_num>  0);
+    s->pending_answers_num--;
     answer =&s->pending_answers[(s->pending_answers_start++) % PENDING_ANSWERS_NUM];
     *slot = answer->slot;
     *seq = answer->seq;
@@ -528,16 +528,16 @@ static void* ccid_reserve_recv_buf(USBCCIDState* s, uint16_t len)
 {
     BulkIn* bulk_in;
 
-    DPRINTF(s, 4, "%s: QUEUE: reserve %d bytes\n", __func__, len);
+    DPRINTF(s, D_VERBOSE, "%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). discarding message.\n",
+        DPRINTF(s, D_WARN, "usb-ccid.c: %s: len larger then max (%d>%d). discarding message.\n",
             __func__, len, BULK_IN_BUF_SIZE);
         return NULL;
     }
     if (s->bulk_in_pending_num>= BULK_IN_PENDING_NUM) {
-        printf("usb-ccid.c: %s: No free bulk_in buffers. discarding message.\n",
+        DPRINTF(s, D_WARN, "usb-ccid.c: %s: No free bulk_in buffers. discarding message.\n",
                 __func__);
         return NULL;
     }
@@ -576,7 +576,7 @@ static int ccid_handle_control(USBDevice *dev, int request, int value,
     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) |
+        data[0] = (1<<  USB_DEVICE_SELF_POWERED) |
             (dev->remote_wakeup<<  USB_DEVICE_REMOTE_WAKEUP);
         data[1] = 0x00;
         ret = 2;
@@ -709,7 +709,7 @@ static uint8_t ccid_calc_status(USBCCIDState *s)
        bmCommandStatus
      */
     uint8_t ret = ccid_card_status(s) | (s->bmCommandStatus<<  6);
-    DPRINTF(s, 4, "status = %d\n", ret);
+    DPRINTF(s, D_VERBOSE, "status = %d\n", ret);
     return ret;
 }
 
@@ -770,11 +770,9 @@ static void ccid_write_data_block(
     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);
+        DPRINTF(s, D_VERBOSE, "error %d", p->b.bError);
     }
-#endif
     memcpy(p->abData, data, len);
     ccid_reset_error_status(s);
 }
@@ -805,12 +803,12 @@ static void ccid_write_data_block_atr(USBCCIDState* s, CCID_Header* recv)
 
 static void ccid_set_parameters(USBCCIDState *s, CCID_Header *recv)
 {
-    CCID_SetParameter *ph = (CCID_SetParameter *) recv;
+    CCID_SetParameters *ph = (CCID_SetParameters *) recv;
     uint32_t len = 0;
-    if (ph->bProtocolNum == 0) {
+    if ((ph->bProtocolNum&  3) == 0) {
         len = 5;
     }
-    if (ph->bProtocolNum == 1) {
+    if ((ph->bProtocolNum&  3) == 1) {
         len = 7;
     }
     if (len == 0) {
@@ -884,7 +882,7 @@ static void ccid_on_apdu_from_guest(USBCCIDState *s, CCID_XferBlock *recv)
     if (s->card) {
         s->cardinfo->apdu_from_guest(s->card, recv->abData, len);
     } else {
-        printf("warning: discarded apdu\n");
+        DPRINTF(s, D_WARN, "warning: discarded apdu\n");
     }
 }
 
@@ -901,15 +899,15 @@ static int ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)
     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",
+    if (p->len == CCID_MAX_PACKET_SIZE) {
+        DPRINTF(s, D_VERBOSE, "usb-ccid: bulk_in: expecting more packets (%d/%d)\n",
             p->len, ccid_header->dwLength);
         return 0;
     }
     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);
+        DPRINTF(s, D_MORE_INFO, "%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);
@@ -965,7 +963,7 @@ static int ccid_bulk_in_copy_to_guest(USBCCIDState *s, uint8_t *data, int len)
 {
     int ret = 0;
 
-    assert(len>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);
@@ -978,7 +976,7 @@ static int ccid_bulk_in_copy_to_guest(USBCCIDState *s, uint8_t *data, int len)
         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);
+        DPRINTF(s, D_MORE_INFO, "%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);
@@ -1015,7 +1013,7 @@ static int ccid_handle_data(USBDevice *dev, USBPacket *p)
                     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",
+                    DPRINTF(s, D_INFO, "handle_data: int_in: notify_slot_change %X, requested len %d\n",
                             s->bmSlotICCState, len);
                 }
                 break;
@@ -1146,7 +1144,11 @@ void ccid_card_card_error(CCIDCardState *card, uint64_t 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);
+    /* we flush all pending answers on CardRemove message in ccid-card-passthru,
+     * so check that first to not trigger abort */
+    if (ccid_has_pending_answers(s)) {
+        ccid_write_data_block_answer(s, NULL, 0);
+    }
 }
 
 void ccid_card_card_inserted(CCIDCardState *card)
@@ -1184,12 +1186,12 @@ static int ccid_card_init(DeviceState *qdev, DeviceInfo *base)
     int ret = 0;
 
     if (card->slot != 0) {
-        fprintf(stderr, "Warning: usb-ccid supports one slot, can't add %d",
+        error_report("Warning: usb-ccid supports one slot, can't add %d",
                 card->slot);
         return -1;
     }
     if (s->card != NULL) {
-        fprintf(stderr, "Warning: usb-ccid card already full, not adding\n");
+        error_report("Warning: usb-ccid card already full, not adding\n");
         return -1;
     }
     ret = info->initfn ? info->initfn(card) : ret;
@@ -1233,7 +1235,6 @@ static int ccid_initfn(USBDevice *dev)
     return 0;
 }
 
-#ifdef ENABLE_MIGRATION
 static int ccid_post_load(void *opaque, int version_id)
 {
     USBCCIDState *s = opaque;
@@ -1325,7 +1326,6 @@ static VMStateDescription ccid_vmstate = {
         VMSTATE_END_OF_LIST()
     }
 };
-#endif // ENABLE_MIGRATION
 
 static struct USBDeviceInfo ccid_info = {
     .product_desc   = "QEMU USB CCID",
@@ -1342,12 +1342,9 @@ static struct USBDeviceInfo ccid_info = {
         DEFINE_PROP_UINT8("debug", USBCCIDState, debug, 0),
         DEFINE_PROP_END_OF_LIST(),
     },
-#ifdef ENABLE_MIGRATION
     .qdev.vmsd      =&ccid_vmstate,
-#endif
 };
 
-
 static void ccid_register_devices(void)
 {
     usb_qdev_register(&ccid_info);
author
#16 lore raw

PATCH 7/20 introduce libcacard/vscard_common.h

In reply to Alon Levy
---
 libcacard/vscard_common.h |  130 +++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 130 insertions(+), 0 deletions(-)
 create mode 100644 libcacard/vscard_common.h
libcacard/vscard_common.h new file +130 -0
new file mode 100644
index 0000000..9ff1295
@@ -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 0xffffffff
+#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
Signature · 1 line
1.7.4
author
#17 lore raw

PATCH 8/20 libcacard/vscard_common.h update (v15->v16)

In reply to Alon Levy

Protocol change:
* VSCMsgInit capabilities and magic
* removed ReaderResponse, will use Error instead with code==VSC_SUCCESS.
* adaded Flush and FlushComplete, remove Reconnect.
* define VSCARD_MAGIC
* added error code VSC_SUCCESS.

Fixes:
* update VSCMsgInit comment
* fix message type enum
* remove underscore from wrapping define
* update copyright
* updated comments.
* Header comment updated
* remove C++ style comment
* fix comment for VSCMsgError
* give names to enums in typedefs

---
 libcacard/vscard_common.h |  103 ++++++++++++++++++++++++++++++--------------
 1 files changed, 70 insertions(+), 33 deletions(-)
libcacard/vscard_common.h +70 -33
index 9ff1295..5cb6eb5 100644
@@ -1,20 +1,25 @@
 /* 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.
+ * This protocol is between a host using virtual smart card readers,
+ * and a client providing the smart cards, perhaps by emulating them or by
+ * access to real cards.
+ *
+ * Definitions for this protocol:
+ *  Host   - user of the card
+ *  Client - owner of the 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.
+ * removal of cards, negotiate the protocol via capabilities and provide
+ * for error responses.
  *
- * Copyright (c) 2010 Red Hat.
+ * Copyright (c) 2011 Red Hat.
  *
  * This code is licensed under the LGPL.
  */
 
-#ifndef _VSCARD_COMMON_H
-#define _VSCARD_COMMON_H
+#ifndef VSCARD_COMMON_H
+#define VSCARD_COMMON_H
 
 #include <stdint.h>
 
@@ -40,91 +45,123 @@
  * something that cannot be accomodated with the existing protocol.
  */
 
-#define VSCARD_VERSION MAKE_VERSION(0,0,1)
+#define VSCARD_VERSION MAKE_VERSION(0,0,2)
 
-typedef enum {
-    VSC_Init,
+typedef enum VSCMsgType {
+    VSC_Init = 1,
     VSC_Error,
     VSC_ReaderAdd,
-    VSC_ReaderAddResponse,
     VSC_ReaderRemove,
     VSC_ATR,
     VSC_CardRemove,
     VSC_APDU,
-    VSC_Reconnect
+    VSC_Flush,
+    VSC_FlushComplete
 } VSCMsgType;
 
-typedef enum {
+typedef enum VSCErrorCode {
+    VSC_SUCCESS=0,
     VSC_GENERAL_ERROR=1,
     VSC_CANNOT_ADD_MORE_READERS,
+    VSC_CARD_ALREAY_INSERTED,
 } VSCErrorCode;
 
-typedef uint32_t reader_id_t;
-#define VSCARD_UNDEFINED_READER_ID 0xffffffff
+#define VSCARD_UNDEFINED_READER_ID  0xffffffff
 #define VSCARD_MINIMAL_READER_ID    0
 
+#define VSCARD_MAGIC (*(uint32_t*)"VSCD")
+
+/* Header
+ * Each message starts with the header.
+ * type - message type
+ * reader_id - used by messages that are reader specific
+ * length - length of payload (not including header, i.e. zero for
+ *  messages containing empty payloads)
+ */
 typedef struct VSCMsgHeader {
-    VSCMsgType type;
-    reader_id_t   reader_id;
+    uint32_t   type;
+    uint32_t   reader_id;
     uint32_t   length;
     uint8_t    data[0];
 } VSCMsgHeader;
 
 /* VSCMsgInit               Client <-> Host
- * Host replies with allocated reader id in ReaderAddResponse
+ * Client sends it on connection, with its own capabilities.
+ * Host replies with VSCMsgInit filling in its capabilities.
+ *
+ * It is not meant to be used for negotiation, i.e. sending more then
+ * once from any side, but could be used for that in the future.
  * */
 typedef struct VSCMsgInit {
+    uint32_t   magic;
     uint32_t   version;
+    uint32_t   capabilities[1]; /* receiver must check length,
+                                   array may grow in the future*/
 } VSCMsgInit;
 
 /* VSCMsgError              Client <-> Host
+ * This message is a response to any of:
+ *  Reader Add
+ *  Reader Remove
+ *  Card Remove
+ * If the operation was successful then VSC_SUCCESS
+ * is returned, other wise a specific error code.
  * */
 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.
+ * Host replies with allocated reader id in VSCMsgError with code==SUCCESS.
+ *
+ * name - name of the reader on client side, UTF-8 encoded. Only used
+ *  for client presentation (may be translated to the device presented to the
+ *  guest), protocol wise only reader_id is important.
  * */
 typedef struct VSCMsgReaderAdd {
     uint8_t    name[0];
 } VSCMsgReaderAdd;
 
-/* VSCMsgReaderAddResponse  Host -> Client
- * Reply to ReaderAdd
- * */
-typedef struct VSCMsgReaderAddResponse {
-} VSCMsgReaderAddResponse;
-
 /* VSCMsgReaderRemove       Client -> Host
+ * The client's reader has been removed.
  * */
 typedef struct VSCMsgReaderRemove {
 } VSCMsgReaderRemove;
 
 /* VSCMsgATR                Client -> Host
- * Answer to reset. Sent for card insertion or card reset.
+ * Answer to reset. Sent for card insertion or card reset. The reset/insertion
+ * happens on the client side, they do not require any action from the host.
  * */
 typedef struct VSCMsgATR {
     uint8_t     atr[0];
 } VSCMsgATR;
 
 /* VSCMsgCardRemove         Client -> Host
+ * The client card has been removed.
  * */
 typedef struct VSCMsgCardRemove {
 } VSCMsgCardRemove;
 
 /* VSCMsgAPDU               Client <-> Host
+ * Main reason of existance. Transfer a single APDU in either direction.
  * */
 typedef struct VSCMsgAPDU {
     uint8_t    data[0];
 } VSCMsgAPDU;
 
-/* VSCMsgReconnect          Host -> Client
+/* VSCMsgFlush               Host -> Client
+ * Request client to send a FlushComplete message when it is done
+ * servicing all outstanding APDUs
  * */
-typedef struct VSCMsgReconnect {
-    uint32_t   ip;
-    uint16_t   port;
-} VSCMsgReconnect;
+typedef struct VSCMsgFlush {
+} VSCMsgFlush;
+
+/* VSCMsgFlush               Client -> Host
+ * Client response to Flush after all APDUs have been processed and
+ * responses sent.
+ * */
+typedef struct VSCMsgFlushComplete {
+} VSCMsgFlushComplete;
+
+#endif /* VSCARD_COMMON_H */
 
-#endif
Signature · 1 line
1.7.4
author
#18 lore raw

PATCH 9/20 ccid: add passthru card device

In reply to Alon Levy

The passthru ccid card is a device sitting on the usb-ccid bus and using a chardevice to communicate with a remote device using the VSCard protocol defined in libcacard/vscard_common.h

Usage docs available in following patch in docs/ccid.txt

---
 Makefile.objs           |    2 +-
 hw/ccid-card-passthru.c |  273 +++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 274 insertions(+), 1 deletions(-)
 create mode 100644 hw/ccid-card-passthru.c
Makefile.objs +1 -1
index a1f3853..94c36a2 100644
@@ -195,7 +195,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
hw/ccid-card-passthru.c new file +273 -0

273 lines not on this page · raw message

Signature · 1 line
1.7.4
author
#19 lore raw

PATCH 10/20 ccid-card-passthru: review fixes (v15->v16)

In reply to Alon Levy

For review I hope presenting this as a separate patch (and the same for the rest of the files) will be easier. For the final round I'll send it folded into the introducing commit.

There are a few bug fixes here that are not directly from the review.

Behavioral changes:
* return correct size
* return error instead of assert if client sent too large ATR
* don't assert if client sent too large a size, but add asserts for indices to buffer
* reset vscard_in indices on chardev disconnect
* handle init from client
* error if no chardev supplied
* use ntoh, hton
* eradicate reader_id_t
* remove Reconnect usage (removed from VSCARD protocol)
* send VSC_SUCCESS on card insert/remove and reader add/remove

Style fixes:
* width of line fix
* update copyright
* remove old TODO's
* update file header comment
* use macros for debug levels
* c++ style comment replacement
* update copyright license
* fix ATR size comment
* fix whitespace in struct def
* fix DPRINTF prefix
* line width fix

---
 hw/ccid-card-passthru.c |  147 ++++++++++++++++++++++++++++++++---------------
 1 files changed, 101 insertions(+), 46 deletions(-)
hw/ccid-card-passthru.c +101 -46
index 6ec4f21..71d3a53 100644
@@ -1,24 +1,32 @@
 /*
- * CCID Card Device emulation
+ * CCID Passthru Card Device emulation
  *
- * Copyright (c) 2010 Red Hat.
+ * Copyright (c) 2011 Red Hat.
  * Written by Alon Levy.
  *
- * This code is licenced under the LGPL.
+ * This code is licenced under the GNU LGPL, version 2 or later.
  */
 
+#include <arpa/inet.h>
+
 #include "qemu-char.h"
 #include "monitor.h"
 #include "hw/ccid.h"
 #include "libcacard/vscard_common.h"
 
-#define DPRINTF(card, lvl, fmt, ...) \
-do { if (lvl <= card->debug) { printf("ccid-card: " fmt , ## __VA_ARGS__); } } while (0)
-
-/* Passthru card */
+#define DPRINTF(card, lvl, fmt, ...)                    \
+do {                                                    \
+    if (lvl <= card->debug) {                           \
+        printf("ccid-card-passthru: " fmt , ## __VA_ARGS__);     \
+    }                                                   \
+} while (0)
 
+#define D_WARN 1
+#define D_INFO 2
+#define D_MORE_INFO 3
+#define D_VERBOSE 4
 
-// TODO: do we still need this?
+/* 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
@@ -27,11 +35,13 @@ uint8_t DEFAULT_ATR[] = {
 /* 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
+
+/* maximum size of ATR - from 7816-3 */
 #define MAX_ATR_SIZE        40
 
 typedef struct PassthruState PassthruState;
@@ -44,7 +54,7 @@ struct PassthruState {
     uint32_t vscard_in_hdr;
     uint8_t  atr[MAX_ATR_SIZE];
     uint8_t  atr_length;
-    uint8_t debug;
+    uint8_t  debug;
 };
 
 /* VSCard protocol over chardev
@@ -52,14 +62,14 @@ struct PassthruState {
  * */
 
 static void ccid_card_vscard_send_msg(
-    PassthruState *s, VSCMsgType type, reader_id_t reader_id,
+    PassthruState *s, VSCMsgType type, uint32_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;
+    scr_msg_header.type = htonl(type);
+    scr_msg_header.reader_id = htonl(reader_id);
+    scr_msg_header.length = htonl(length);
     qemu_chr_write(s->cs, (uint8_t*)&scr_msg_header, sizeof(VSCMsgHeader));
     qemu_chr_write(s->cs, payload, length);
 }
@@ -71,16 +81,20 @@ static void ccid_card_vscard_send_apdu(
 }
 
 static void ccid_card_vscard_send_error(
-    PassthruState *s, reader_id_t reader_id, VSCErrorCode code)
+    PassthruState *s, uint32_t reader_id, VSCErrorCode code)
 {
-    VSCMsgError msg = {.code=code};
+    VSCMsgError msg = {.code=htonl(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};
+    VSCMsgInit msg = {
+        .version=htonl(VSCARD_VERSION),
+        .magic=VSCARD_MAGIC,
+        .capabilities={0}
+    };
 
     ccid_card_vscard_send_msg(s, VSC_Init, VSCARD_UNDEFINED_READER_ID,
                          (uint8_t*)&msg, sizeof(msg));
@@ -88,7 +102,33 @@ static void ccid_card_vscard_send_init(PassthruState *s)
 
 static int ccid_card_vscard_can_read(void *opaque)
 {
-    return 65535;
+    PassthruState *card = opaque;
+
+    return VSCARD_IN_SIZE >= card->vscard_in_pos ?
+           VSCARD_IN_SIZE - card->vscard_in_pos : 0;
+}
+
+static void ccid_card_vscard_handle_init(PassthruState *card, VSCMsgHeader *hdr, VSCMsgInit *init)
+{
+    uint32_t *capabilities;
+    int num_capabilities;
+    int i;
+
+    capabilities = init->capabilities;
+    num_capabilities = 1 + ((hdr->length - sizeof(VSCMsgInit)) / sizeof(uint32_t));
+    init->version = ntohl(init->version);
+    for (i = 0 ; i < num_capabilities; ++i) {
+        capabilities[i] = ntohl(capabilities[i]);
+    }
+    if (init->magic != VSCARD_MAGIC) {
+        error_report("wrong magic");
+        /* we can't disconnect the chardev */
+    }
+    if (init->version != VSCARD_VERSION) {
+        DPRINTF(card, D_WARN, "got version %d, have %d", init->version, VSCARD_VERSION);
+    }
+    /* future handling of capabilities, none exist atm */
+    ccid_card_vscard_send_init(card);
 }
 
 static void ccid_card_vscard_handle_message(PassthruState *card,
@@ -98,20 +138,30 @@ static void ccid_card_vscard_handle_message(PassthruState *card,
 
     switch (scr_msg_header->type) {
         case VSC_ATR:
-            DPRINTF(card, 1, "VSC_ATR %d\n", scr_msg_header->length);
-            assert(scr_msg_header->length <= MAX_ATR_SIZE);
+            DPRINTF(card, D_INFO, "VSC_ATR %d\n", scr_msg_header->length);
+            if (scr_msg_header->length > MAX_ATR_SIZE) {
+                error_report("ATR size exceeds spec, ignoring");
+                ccid_card_vscard_send_error(card, scr_msg_header->reader_id,
+                                            VSC_GENERAL_ERROR);
+            }
             memcpy(card->atr, data, scr_msg_header->length);
             card->atr_length = scr_msg_header->length;
             ccid_card_card_inserted(&card->base);
+            ccid_card_vscard_send_error(card, scr_msg_header->reader_id,
+                                        VSC_SUCCESS);
             break;
         case VSC_APDU:
             ccid_card_send_apdu_to_guest(&card->base, data, scr_msg_header->length);
             break;
         case VSC_CardRemove:
-            DPRINTF(card, 1, "VSC_CardRemove\n");
+            DPRINTF(card, D_INFO, "VSC_CardRemove\n");
             ccid_card_card_removed(&card->base);
+            ccid_card_vscard_send_error(card,
+                scr_msg_header->reader_id, VSC_SUCCESS);
             break;
         case VSC_Init:
+            ccid_card_vscard_handle_init(
+                card, scr_msg_header, (VSCMsgInit *)data);
             break;
         case VSC_Error:
             ccid_card_card_error(&card->base, *(uint64_t*)data);
@@ -121,12 +171,14 @@ static void ccid_card_vscard_handle_message(PassthruState *card,
                 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);
+                ccid_card_vscard_send_error(card, VSCARD_MINIMAL_READER_ID,
+                                            VSC_SUCCESS);
             }
             break;
         case VSC_ReaderRemove:
             ccid_card_ccid_detach(&card->base);
+            ccid_card_vscard_send_error(card,
+                scr_msg_header->reader_id, VSC_SUCCESS);
             break;
         default:
             printf("usb-ccid: chardev: unexpected message of type %X\n",
@@ -136,19 +188,35 @@ static void ccid_card_vscard_handle_message(PassthruState *card,
     }
 }
 
+static void ccid_card_vscard_drop_connection(PassthruState *card)
+{
+    qemu_chr_close(card->cs);
+    card->vscard_in_pos = card->vscard_in_hdr = 0;
+}
+
 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);
+    if (card->vscard_in_pos + size > VSCARD_IN_SIZE) {
+        error_report("no room for data: pos %d +  size %d > %d. dropping connection.",
+            card->vscard_in_pos, size, VSCARD_IN_SIZE);
+        ccid_card_vscard_drop_connection(card);
+        return;
+    }
+    assert(card->vscard_in_pos < VSCARD_IN_SIZE);
+    assert(card->vscard_in_hdr < 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)) {
+    while ((card->vscard_in_pos - card->vscard_in_hdr >= sizeof(VSCMsgHeader))
+        && (card->vscard_in_pos - card->vscard_in_hdr >=
+                                  sizeof(VSCMsgHeader) + ntohl(hdr->length))) {
+        hdr->reader_id = ntohl(hdr->reader_id);
+        hdr->length = ntohl(hdr->length);
+        hdr->type = ntohl(hdr->type);
         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);
@@ -164,11 +232,12 @@ static void ccid_card_vscard_event(void *opaque, int event)
 
     switch (event) {
         case CHR_EVENT_BREAK:
+            card->vscard_in_pos = card->vscard_in_hdr = 0;
             break;
         case CHR_EVENT_FOCUS:
             break;
         case CHR_EVENT_OPENED:
-            DPRINTF(card, 1, "%s: CHR_EVENT_OPENED\n", __func__);
+            DPRINTF(card, D_INFO, "%s: CHR_EVENT_OPENED\n", __func__);
             break;
     }
 }
@@ -201,12 +270,14 @@ static int passthru_initfn(CCIDCardState *base)
     card->vscard_in_pos = 0;
     card->vscard_in_hdr = 0;
     if (card->cs) {
-        DPRINTF(card, 1, "initing chardev\n");
+        DPRINTF(card, D_INFO, "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);
+    } else {
+        error_report("missing chardev");
+        return -1;
     }
     assert(sizeof(DEFAULT_ATR) <= MAX_ATR_SIZE);
     memcpy(card->atr, DEFAULT_ATR, sizeof(DEFAULT_ATR));
@@ -219,22 +290,10 @@ static int passthru_exitfn(CCIDCardState *base)
     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),
@@ -264,10 +323,6 @@ static CCIDCardInfo passthru_card_info = {
 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)
Signature · 1 line
1.7.4
author
#20 lore raw

PATCH 11/20 libcacard: initial commit after coding style fixes

In reply to Alon Levy

From: Robert Relyea <[email protected]>

libcacard emulates a Common Access Card (CAC) which is a standard for smartcards. It is used by the emulated ccid card introduced in a following patch. Docs are available in docs/libcacard.txt

---
 Makefile                    |    6 +-
 Makefile.objs               |    5 +
 Makefile.target             |    2 +
 configure                   |   25 +
 docs/libcacard.txt          |  483 ++++++++++++++++++
 libcacard/Makefile          |   14 +
 libcacard/cac.c             |  411 +++++++++++++++
 libcacard/cac.h             |   20 +
 libcacard/card_7816.c       |  780 ++++++++++++++++++++++++++++
 libcacard/card_7816.h       |   60 +++
 libcacard/card_7816t.h      |  163 ++++++
 libcacard/event.c           |  112 ++++
 libcacard/eventt.h          |   28 +
 libcacard/link_test.c       |   20 +
 libcacard/mutex.h           |   59 +++
 libcacard/passthru.c        |  612 ++++++++++++++++++++++
 libcacard/passthru.h        |   50 ++
 libcacard/vcard.c           |  350 +++++++++++++
 libcacard/vcard.h           |   85 ++++
 libcacard/vcard_emul.h      |   62 +++
 libcacard/vcard_emul_nss.c  | 1171 +++++++++++++++++++++++++++++++++++++++++++
 libcacard/vcard_emul_type.c |   60 +++
 libcacard/vcard_emul_type.h |   29 ++
 libcacard/vcardt.h          |   66 +++
 libcacard/vevent.h          |   26 +
 libcacard/vreader.c         |  526 +++++++++++++++++++
 libcacard/vreader.h         |   54 ++
 libcacard/vreadert.h        |   23 +
 libcacard/vscclient.c       |  710 ++++++++++++++++++++++++++
 29 files changed, 6010 insertions(+), 2 deletions(-)
 create mode 100644 docs/libcacard.txt
 create mode 100644 libcacard/Makefile
 create mode 100644 libcacard/cac.c
 create mode 100644 libcacard/cac.h
 create mode 100644 libcacard/card_7816.c
 create mode 100644 libcacard/card_7816.h
 create mode 100644 libcacard/card_7816t.h
 create mode 100644 libcacard/event.c
 create mode 100644 libcacard/eventt.h
 create mode 100644 libcacard/link_test.c
 create mode 100644 libcacard/mutex.h
 create mode 100644 libcacard/passthru.c
 create mode 100644 libcacard/passthru.h
 create mode 100644 libcacard/vcard.c
 create mode 100644 libcacard/vcard.h
 create mode 100644 libcacard/vcard_emul.h
 create mode 100644 libcacard/vcard_emul_nss.c
 create mode 100644 libcacard/vcard_emul_type.c
 create mode 100644 libcacard/vcard_emul_type.h
 create mode 100644 libcacard/vcardt.h
 create mode 100644 libcacard/vevent.h
 create mode 100644 libcacard/vreader.c
 create mode 100644 libcacard/vreader.h
 create mode 100644 libcacard/vreadert.h
 create mode 100644 libcacard/vscclient.c
Makefile +4 -2
index eca4c76..e1c4aa5 100644
@@ -173,6 +173,8 @@ check-qlist: check-qlist.o qlist.o qint.o $(CHECK_PROG_DEPS)
 check-qfloat: check-qfloat.o qfloat.o $(CHECK_PROG_DEPS)
 check-qjson: check-qjson.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o qjson.o json-streamer.o json-lexer.o json-parser.o $(CHECK_PROG_DEPS)
 
+QEMULIBS=libhw32 libhw64 libuser libdis libdis-user libcacard
+
 clean:
 # avoid old build problems by removing potentially incorrect old files
 	rm -f config.mak op-i386.h opc-i386.h gen-op-i386.h op-arm.h opc-arm.h gen-op-arm.h
@@ -184,7 +186,7 @@ clean:
 	rm -f trace-dtrace.dtrace trace-dtrace.dtrace-timestamp
 	rm -f trace-dtrace.h trace-dtrace.h-timestamp
 	$(MAKE) -C tests clean
-	for d in $(ALL_SUBDIRS) libhw32 libhw64 libuser libdis libdis-user; do \
+	for d in $(ALL_SUBDIRS) $(QEMULIBS); do \
 	if test -d $$d; then $(MAKE) -C $$d $@ || exit 1; fi; \
 	rm -f $$d/qemu-options.def; \
         done
@@ -195,7 +197,7 @@ distclean: clean
 	rm -f roms/seabios/config.mak roms/vgabios/config.mak
 	rm -f qemu-doc.info qemu-doc.aux qemu-doc.cp qemu-doc.dvi qemu-doc.fn qemu-doc.info qemu-doc.ky qemu-doc.log qemu-doc.pdf qemu-doc.pg qemu-doc.toc qemu-doc.tp qemu-doc.vr
 	rm -f qemu-tech.info qemu-tech.aux qemu-tech.cp qemu-tech.dvi qemu-tech.fn qemu-tech.info qemu-tech.ky qemu-tech.log qemu-tech.pdf qemu-tech.pg qemu-tech.toc qemu-tech.tp qemu-tech.vr
-	for d in $(TARGET_DIRS) libhw32 libhw64 libuser libdis libdis-user; do \
+	for d in $(TARGET_DIRS) $(QEMULIBS); do \
 	rm -rf $$d || exit 1 ; \
         done
 
Makefile.objs +5 -0
index 94c36a2..3fba145 100644
@@ -313,6 +313,11 @@ user-obj-y += qemu-timer-common.o
 endif
 endif
 
+######################################################################
+# smartcard
+
+libcacard-y = cac.o event.o passthru.o vcard.o vreader.o vcard_emul_nss.o vcard_emul_type.o card_7816.o
+
 vl.o: QEMU_CFLAGS+=$(GPROF_CFLAGS)
 
 vl.o: QEMU_CFLAGS+=$(SDL_CFLAGS)
Makefile.target +2 -0
index b0ba95f..902e15d 100644
@@ -340,6 +340,8 @@ obj-y += $(addprefix $(HWDIR)/, $(hw-obj-y))
 
 endif # CONFIG_SOFTMMU
 
+obj-y += $(addprefix ../libcacard/, $(libcacard-$(CONFIG_SMARTCARD)))
+
 obj-y += $(addprefix ../, $(trace-obj-y))
 obj-$(CONFIG_GDBSTUB_XML) += gdbstub-xml.o
 
configure +25 -0
index 14a035a..9926ed4 100755
@@ -2240,6 +2240,19 @@ EOF
   fi
 fi
 
+# check for libcacard for smartcard support
+smartcard_cflags="-I\$(SRC_PATH)/libcacard"
+libcacard_libs=$($pkgconfig --libs nss 2>/dev/null)
+libcacard_cflags=$($pkgconfig --cflags nss)
+# TODO - what's the minimal nss version we support?
+if $pkgconfig --atleast-version=3.12.8 nss; then
+    smartcard="yes"
+    QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
+    LIBS="$libcacard_libs $LIBS"
+else
+    smartcard="no"
+fi
+
 ##########################################
 
 ##########################################
@@ -3075,6 +3088,11 @@ fi
 if test "$target_darwin_user" = "yes" ; then
   echo "CONFIG_DARWIN_USER=y" >> $config_target_mak
 fi
+if test "$smartcard" = "yes" ; then
+  echo "subdir-$target: subdir-libcacard" >> $config_host_mak
+  echo "libcacard_libs=$libcacard_libs" >> $config_host_mak
+  echo "libcacard_cflags=$libcacard_cflags" >> $config_host_mak
+fi
 list=""
 if test ! -z "$gdb_xml_files" ; then
   for x in $gdb_xml_files; do
@@ -3288,6 +3306,13 @@ for hwlib in 32 64; do
   echo "QEMU_CFLAGS+=-DTARGET_PHYS_ADDR_BITS=$hwlib" > $d/config.mak
 done
 
+if [ $source_path != $workdir ]; then
+    # out of tree build
+    mkdir -p libcacard
+    rm -f libcacard/Makefile
+    ln -s $source_path/libcacard/Makefile libcacard/Makefile
+fi
+
 d=libuser
 mkdir -p $d
 symlink $source_path/Makefile.user $d/Makefile
docs/libcacard.txt new file +483 -0

483 lines not on this page · raw message

libcacard/Makefile new file +14 -0
new file mode 100644
index 0000000..b146779
@@ -0,0 +1,14 @@
+include ../config-host.mak
+include $(SRC_PATH)/Makefile.objs
+include $(SRC_PATH)/rules.mak
+
+$(call set-vpath, $(SRC_PATH):$(SRC_PATH)/libcacard)
+
+vscclient: $(libcacard-y) vscclient.o
+	gcc $(libcacard_libs) -o $@ $^
+
+all: vscclient
+
+clean:
+	rm -f *.o */*.o *.d */*.d *.a */*.a *~ */*~ vscclient
+
libcacard/cac.c new file +411 -0

411 lines not on this page · raw message

libcacard/cac.h new file +20 -0
new file mode 100644
index 0000000..bb2a9f0
@@ -0,0 +1,20 @@
+/*
+ * defines the entry point for the cac card. Only used by cac.c anc
+ * vcard_emul_type.c
+ */
+#ifndef CAC_H
+#define CAC_H 1
+#include "vcard.h"
+#include "vreader.h"
+/*
+ * Initialize the cac card. This is the only public function in this file. All
+ * the rest are connected through function pointers.
+ */
+VCardStatus cac_card_init(VReader *reader, VCard *card, const char *params,
+              unsigned char * const *cert, int cert_len[],
+              VCardKey *key[] /* adopt the keys*/,
+              int cert_count);
+
+/* not yet implemented */
+VCardStatus cac_is_cac_card(VReader *reader);
+#endif
libcacard/card_7816.c new file +780 -0

780 lines not on this page · raw message

libcacard/card_7816.h new file +60 -0

60 lines not on this page · raw message

libcacard/card_7816t.h new file +163 -0

163 lines not on this page · raw message

libcacard/event.c new file +112 -0

112 lines not on this page · raw message

libcacard/eventt.h new file +28 -0
new file mode 100644
index 0000000..4c3df4f
@@ -0,0 +1,28 @@
+/*
+ *
+ */
+
+#ifndef EVENTT_H
+#define EVENTT_H 1
+#include "vreadert.h"
+#include "vcardt.h"
+
+typedef struct VEventStruct VEvent;
+
+typedef enum {
+    VEVENT_READER_INSERT,
+    VEVENT_READER_REMOVE,
+    VEVENT_CARD_INSERT,
+    VEVENT_CARD_REMOVE,
+    VEVENT_LAST,
+} VEventType;
+
+struct VEventStruct {
+    VEvent *next;
+    VEventType type;
+    VReader *reader;
+    VCard *card;
+};
+#endif
+
+
libcacard/link_test.c new file +20 -0
new file mode 100644
index 0000000..40d2c6d
@@ -0,0 +1,20 @@
+/*
+ *
+ */
+#include <stdio.h>
+#include "vcard.h"
+
+VCardStatus cac_card_init(const char *flags, VCard *card,
+                const unsigned char *cert[],
+                int cert_len[], VCardKey *key[] /* adopt the keys*/,
+                int cert_count);
+/*
+ * this will crash... just test the linkage right now
+ */
+
+main(int argc, char **argv)
+{
+    VCard *card; /* no constructor yet */
+    cac_card_init("", card, NULL, 0, NULL, 0);
+}
+
libcacard/mutex.h new file +59 -0

59 lines not on this page · raw message

libcacard/passthru.c new file +612 -0

612 lines not on this page · raw message

libcacard/passthru.h new file +50 -0

50 lines not on this page · raw message

libcacard/vcard.c new file +350 -0

102 lines not on this page · raw message

libcacard/vcard.h new file +85 -0

85 lines not on this page · raw message

libcacard/vcard_emul.h new file +62 -0

62 lines not on this page · raw message

libcacard/vcard_emul_nss.c new file +1171 -0

1,171 lines not on this page · raw message

libcacard/vcard_emul_type.c new file +60 -0

60 lines not on this page · raw message

libcacard/vcard_emul_type.h new file +29 -0
new file mode 100644
index 0000000..da15528

Lines of this file are not shown. View the raw message.

libcacard/vcardt.h new file +66 -0

66 lines not on this page · raw message

libcacard/vevent.h new file +26 -0
new file mode 100644
index 0000000..f202ea8

Lines of this file are not shown. View the raw message.

libcacard/vreader.c new file +526 -0

526 lines not on this page · raw message

libcacard/vreader.h new file +54 -0

54 lines not on this page · raw message

libcacard/vreadert.h new file +23 -0
new file mode 100644
index 0000000..4c01259

Lines of this file are not shown. View the raw message.

libcacard/vscclient.c new file +710 -0

710 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
1.7.4

Part of the diff is not shown here. View the raw message.

author
#21 lore raw

PATCH 12/20 libcacard: fixes from review (v15->v16)

In reply to Alon Levy

Build:
* don't erase self with distclean
* fix make clean after make distclean
* Makefile: make vscclient link quiet

Behavioral:
* vcard_emul_nss: load coolkey in more situations
* vscclient:
* use hton,ntoh
* send init on connect, only start vevent thread on response
* read payload after header check, before type switch
* remove Reconnect
* update for vscard_common changes, empty Flush implementation

Style/Whitespace:
* fix wrong variable usage
* remove unused variable
* use only C style comments
* add copyright header
* fix tabulation

---
 Makefile                   |    4 +-
 libcacard/Makefile         |    8 +-
 libcacard/mutex.h          |    2 +-
 libcacard/vcard_emul.h     |    2 +-
 libcacard/vcard_emul_nss.c |   39 ++++++--
 libcacard/vscclient.c      |  219 +++++++++++++++++++++++++-------------------
 6 files changed, 164 insertions(+), 110 deletions(-)
Makefile +2 -2
index e1c4aa5..9286eb1 100644
@@ -173,7 +173,7 @@ check-qlist: check-qlist.o qlist.o qint.o $(CHECK_PROG_DEPS)
 check-qfloat: check-qfloat.o qfloat.o $(CHECK_PROG_DEPS)
 check-qjson: check-qjson.o qfloat.o qint.o qdict.o qstring.o qlist.o qbool.o qjson.o json-streamer.o json-lexer.o json-parser.o $(CHECK_PROG_DEPS)
 
-QEMULIBS=libhw32 libhw64 libuser libdis libdis-user libcacard
+QEMULIBS=libhw32 libhw64 libuser libdis libdis-user
 
 clean:
 # avoid old build problems by removing potentially incorrect old files
@@ -186,7 +186,7 @@ clean:
 	rm -f trace-dtrace.dtrace trace-dtrace.dtrace-timestamp
 	rm -f trace-dtrace.h trace-dtrace.h-timestamp
 	$(MAKE) -C tests clean
-	for d in $(ALL_SUBDIRS) $(QEMULIBS); do \
+	for d in $(ALL_SUBDIRS) $(QEMULIBS) libcacard; do \
 	if test -d $$d; then $(MAKE) -C $$d $@ || exit 1; fi; \
 	rm -f $$d/qemu-options.def; \
         done
libcacard/Makefile +4 -4
index b146779..554c6ea 100644
@@ -1,11 +1,11 @@
-include ../config-host.mak
-include $(SRC_PATH)/Makefile.objs
-include $(SRC_PATH)/rules.mak
+-include ../config-host.mak
+-include $(SRC_PATH)/Makefile.objs
+-include $(SRC_PATH)/rules.mak
 
 $(call set-vpath, $(SRC_PATH):$(SRC_PATH)/libcacard)
 
 vscclient: $(libcacard-y) vscclient.o
-	gcc $(libcacard_libs) -o $@ $^
+	$(call quiet-command,$(CC) $(libcacard_libs) -o $@ $^,"  LINK  $(TARGET_DIR)$@")
 
 all: vscclient
 
libcacard/mutex.h +1 -1
index db44814..ffbdb31 100644
@@ -56,4 +56,4 @@ typedef int thread_status_t;
 #define THREAD_SUCCESS(status)  ((status) == 0)
 #endif
 
-#endif // _H_MUTEX
+#endif /* _H_MUTEX */
libcacard/vcard_emul.h +1 -1
index 5df01a8..05fb57e 100644
@@ -20,7 +20,7 @@
 typedef enum {
     VCARD_EMUL_OK =0,
     VCARD_EMUL_FAIL,
-    // return values by vcard_emul_init
+    /* return values by vcard_emul_init */
     VCARD_EMUL_INIT_ALREADY_INITED,
 } VCardEmulError;
 
libcacard/vcard_emul_nss.c +30 -9
index 33404c2..6887cf6 100644
@@ -29,7 +29,6 @@
 #include <stdlib.h>
 #include <string.h>
 
-
 struct VCardKeyStruct {
     CERTCertificate *cert;
     PK11SlotInfo *slot;
@@ -718,6 +717,30 @@ vcard_emul_force_card_insert(VReader *vreader)
     return VCARD_EMUL_OK;
 }
 
+
+static PRBool
+module_has_removable_hw_slots(SECMODModule *mod)
+{
+    int i;
+    PRBool ret = PR_FALSE;
+    SECMODListLock *moduleLock = SECMOD_GetDefaultModuleListLock();
+
+    if (!moduleLock) {
+        PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
+        return ret;
+    }
+    SECMOD_GetReadLock(moduleLock);
+    for (i=0; i < mod->slotCount; i++) {
+        PK11SlotInfo *slot = mod->slots[i];
+        if (PK11_IsRemovable(slot) && PK11_IsHW(slot)) {
+            ret = PR_TRUE;
+            break;
+        }
+    }
+    SECMOD_ReleaseReadLock(moduleLock);
+    return ret;
+}
+
 /* Previously we returned FAIL if no readers found. This makes
  * no sense when using hardware, since there may be no readers connected
  * at the time vcard_emul_init is called, but they will be properly
@@ -730,7 +753,7 @@ VCardEmulError
 vcard_emul_init(const VCardEmulOptions *options)
 {
     SECStatus rv;
-    PRBool ret, has_readers=PR_FALSE, need_module;
+    PRBool ret, has_readers=PR_FALSE, need_coolkey_module;
     VReader *vreader;
     VReaderEmul *vreader_emul;
     SECMODListLock *module_lock;
@@ -826,18 +849,18 @@ vcard_emul_init(const VCardEmulOptions *options)
     /* make sure we have some PKCS #11 module loaded */
     module_lock = SECMOD_GetDefaultModuleListLock();
     module_list = SECMOD_GetDefaultModuleList();
-    need_module = !has_readers;
+    need_coolkey_module = !has_readers;
     SECMOD_GetReadLock(module_lock);
     for (mlp = module_list; mlp; mlp = mlp->next) {
         SECMODModule * module = mlp->module;
-        if (SECMOD_HasRemovableSlots(module)) {
-            need_module = PR_FALSE;
+        if (module_has_removable_hw_slots(module)) {
+            need_coolkey_module = PR_FALSE;
             break;
         }
     }
     SECMOD_ReleaseReadLock(module_lock);
 
-    if (need_module) {
+    if (need_coolkey_module) {
         SECMODModule *module;
         module = SECMOD_LoadUserModule(
                     (char*)"library=libcoolkeypk11.so name=Coolkey",
@@ -882,9 +905,7 @@ vcard_emul_init(const VCardEmulOptions *options)
             has_emul_slots = PR_TRUE;
 
             if (PK11_IsPresent(slot)) {
-                VCardEmulType type;
                 VCard *vcard;
-                type = vcard_emul_get_type(vreader);
                 vcard = vcard_emul_mirror_card(vreader);
                 vreader_insert_card(vreader, vcard);
                 vcard_emul_init_series(vreader, vcard);
@@ -1087,7 +1108,7 @@ vcard_emul_options(const char *args)
             vreaderOpt->name = copy_string(name, name_length);
             vreaderOpt->vname = copy_string(vname, vname_length);
             vreaderOpt->card_type = type;
-            vreaderOpt->type_params = copy_string(name, name_length);
+            vreaderOpt->type_params = copy_string(type_params, type_params_length);
             count = count_tokens(args,',',')');
             vreaderOpt->cert_count = count;
             vreaderOpt->cert_name = (char **)malloc(count*sizeof(char *));
libcacard/vscclient.c +126 -93

348 lines not on this page · raw message

Signature · 1 line
1.7.4
author
#22 lore raw

PATCH 13/20 ccid: add ccid-card-emulated device (v2)

In reply to Alon Levy

This devices uses libcacard (internal) to emulate a smartcard conforming to the CAC standard. It attaches to the usb-ccid bus. Usage instructions (example command lines) are in the following patch in docs/ccid.txt. It uses libcacard which uses nss, so it can work with both hw cards and certificates (files).

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

---
 Makefile.objs           |    2 +-
 hw/ccid-card-emulated.c |  534 +++++++++++++++++++++++++++++++++++++++++++++++
 hw/ccid-card-passthru.c |    1 -
 3 files changed, 535 insertions(+), 2 deletions(-)
 create mode 100644 hw/ccid-card-emulated.c
Makefile.objs +1 -1
index 3fba145..459bbdb 100644
@@ -195,7 +195,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
hw/ccid-card-emulated.c new file +534 -0

534 lines not on this page · raw message

hw/ccid-card-passthru.c +0 -1
index 71d3a53..f3f3da9 100644
@@ -312,7 +312,6 @@ static CCIDCardInfo passthru_card_info = {
     .exitfn = passthru_exitfn,
     .get_atr = passthru_get_atr,
     .apdu_from_guest = passthru_apdu_from_guest,
-    .qdev.unplug    = qdev_simple_unplug_cb,
     .qdev.props     = (Property[]) {
         DEFINE_PROP_CHR("chardev", PassthruState, cs),
         DEFINE_PROP_UINT8("debug", PassthruState, debug, 0),
Signature · 1 line
1.7.4
author
#23 lore raw

PATCH 14/20 ccid-card-emulated: use PROP_TYPE_ENUM for backend

In reply to Alon Levy
---
 hw/ccid-card-emulated.c |   33 ++++++++++++++++++++++-----------
 1 files changed, 22 insertions(+), 11 deletions(-)
hw/ccid-card-emulated.c +22 -11
index 5531ce1..3c5bf6c 100644
@@ -35,8 +35,15 @@ do { if (lvl <= card->debug) { printf("ccid-card-emul: %s: " fmt , __func__, ##
 
 #define EMULATED_DEV_NAME "ccid-card-emulated"
 
-#define BACKEND_NSS_EMULATED "nss-emulated" /* the default */
-#define BACKEND_CERTIFICATES "certificates"
+#define BACKEND_NSS_EMULATED_NAME "nss-emulated"
+#define BACKEND_CERTIFICATES_NAME "certificates"
+
+enum {
+    BACKEND_NSS_EMULATED=1,
+    BACKEND_CERTIFICATES
+};
+
+#define DEFAULT_BACKEND BACKEND_NSS_EMULATED
 
 typedef struct EmulatedState EmulatedState;
 
@@ -88,7 +95,7 @@ typedef struct EmulEvent {
 struct EmulatedState {
     CCIDCardState base;
     uint8_t  debug;
-    char*    backend;
+    uint32_t backend;
     char*    cert1;
     char*    cert2;
     char*    cert3;
@@ -449,22 +456,20 @@ static int emulated_initfn(CCIDCardState *base)
     if (init_pipe_signaling(card) < 0) {
         return -1;
     }
-    if (!card->backend) {
-        card->backend = strdup((char*)BACKEND_NSS_EMULATED);
-    }
+    ASSERT(card->backend); /* 0 is not a value in the enumeration */
     /* TODO: a passthru backened that works on local machine. third card type? */
-    if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0
+    if (card->backend == BACKEND_CERTIFICATES
         && card->cert1 != NULL && card->cert2 != NULL && card->cert3 != NULL) {
         ret = emulated_initialize_vcard_from_certificates(card);
     } else {
-        if (strcmp(BACKEND_CERTIFICATES, card->backend) == 0) {
+        if (card->backend != BACKEND_CERTIFICATES) {
             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) {
+        if (card->backend != BACKEND_NSS_EMULATED) {
             printf("%s: bad backend specified. The options are:\n%s (default), %s.\n",
-                EMULATED_DEV_NAME, BACKEND_NSS_EMULATED, BACKEND_CERTIFICATES);
+                EMULATED_DEV_NAME, BACKEND_NSS_EMULATED_NAME, BACKEND_CERTIFICATES_NAME);
             return -1;
         }
         /* default to mirroring the local hardware readers */
@@ -507,6 +512,12 @@ static int emulated_exitfn(CCIDCardState *base)
     return 0;
 }
 
+EnumTable backend_enum_table[] = {
+    {BACKEND_NSS_EMULATED_NAME, BACKEND_NSS_EMULATED},
+    {BACKEND_CERTIFICATES_NAME, BACKEND_CERTIFICATES},
+    {NULL, 0},
+};
+
 static CCIDCardInfo emulated_card_info = {
     .qdev.name = EMULATED_DEV_NAME,
     .qdev.size = sizeof(EmulatedState),
@@ -516,7 +527,7 @@ static CCIDCardInfo emulated_card_info = {
     .apdu_from_guest = emulated_apdu_from_guest,
     .qdev.unplug    = qdev_simple_unplug_cb,
     .qdev.props     = (Property[]) {
-        DEFINE_PROP_STRING("backend", EmulatedState, backend),
+        DEFINE_PROP_ENUM("backend", EmulatedState, backend, DEFAULT_BACKEND, backend_enum_table),
         DEFINE_PROP_STRING("cert1", EmulatedState, cert1),
         DEFINE_PROP_STRING("cert2", EmulatedState, cert2),
         DEFINE_PROP_STRING("cert3", EmulatedState, cert3),
Signature · 1 line
1.7.4
author
#24 lore raw

PATCH 15/20 ccid-card-emulated: review fixes (v15->v16)

In reply to Alon Levy

* fix error reporting in initfn
* bump copyright year
* update copyright license

---
 hw/ccid-card-emulated.c |   19 ++++++++++++-------
 1 files changed, 12 insertions(+), 7 deletions(-)
hw/ccid-card-emulated.c +12 -7
index 3c5bf6c..09ce770 100644
@@ -15,10 +15,10 @@
  * If you use a non default db for the certificates you can specify it using the db parameter.
  *
  *
- * Copyright (c) 2010 Red Hat.
+ * Copyright (c) 2011 Red Hat.
  * Written by Alon Levy.
  *
- * This code is licenced under the LGPL.
+ * This code is licenced under the GNU LGPL, version 2 or later.
  */
 
 #include <pthread.h>
@@ -458,20 +458,25 @@ static int emulated_initfn(CCIDCardState *base)
     }
     ASSERT(card->backend); /* 0 is not a value in the enumeration */
     /* TODO: a passthru backened that works on local machine. third card type? */
-    if (card->backend == BACKEND_CERTIFICATES
-        && card->cert1 != NULL && card->cert2 != NULL && card->cert3 != NULL) {
-        ret = emulated_initialize_vcard_from_certificates(card);
-    } else {
-        if (card->backend != BACKEND_CERTIFICATES) {
+    if (card->backend == BACKEND_CERTIFICATES) {
+        if (card->cert1 != NULL && card->cert2 != NULL && card->cert3 != NULL) {
+            ret = emulated_initialize_vcard_from_certificates(card);
+        } else {
             printf("%s: you must provide all three certs for certificates backend\n",
                 EMULATED_DEV_NAME);
             return -1;
         }
+    } else {
         if (card->backend != BACKEND_NSS_EMULATED) {
             printf("%s: bad backend specified. The options are:\n%s (default), %s.\n",
                 EMULATED_DEV_NAME, BACKEND_NSS_EMULATED_NAME, BACKEND_CERTIFICATES_NAME);
             return -1;
         }
+        if (card->cert1 != NULL || card->cert2 != NULL || card->cert3 != NULL) {
+            printf("%s: unexpected cert parameters to nss emulated backend\n",
+                   EMULATED_DEV_NAME);
+            return -1;
+        }
         /* default to mirroring the local hardware readers */
         ret = wrap_vcard_emul_init(NULL);
     }
Signature · 1 line
1.7.4
author
#25 lore raw

PATCH 16/20 ccid: add docs

In reply to Alon Levy

Add documentation for the usb-ccid device and accompanying two card devices, ccid-card-emulated and ccid-card-passthru.

---
 docs/ccid.txt |  135 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 135 insertions(+), 0 deletions(-)
 create mode 100644 docs/ccid.txt
docs/ccid.txt new file +135 -0
new file mode 100644
index 0000000..b8e504a
@@ -0,0 +1,135 @@
+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. libcacard
+
+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
+
+The cryptographic functions and access to the physical card is done via NSS.
+
+Installing NSS:
+
+In redhat/fedora:
+    yum install nss-devel
+In ubuntu/debian:
+    apt-get install libnss3-dev
+    (not tested on ubuntu)
+
+Configuring and building:
+    ./configure --enable-smartcard && make
+
+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 libcacard library:
+    libcacard/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)
+
+    libcacard/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.
+The usb-ccid device can be in one of three modes:
+ * detached
+ * attached with no card
+ * attached with card
+
+A typical interchange is: (the arrow shows who started each exchange, it can be client
+originated or guest originated)
+
+client event      |      vscclient           |    passthru    |     usb-ccid  |  guest event
+----------------------------------------------------------------------------------------------
+                  |      VSC_Init            |                |               |
+                  |      VSC_ReaderAdd       |                |     attach    |
+                  |                          |                |               |  sees new usb device.
+card inserted ->  |                          |                |               |
+                  |      VSC_ATR             |   insert       |     insert    |  see new card
+                  |                          |                |               |
+                  |      VSC_APDU            |   VSC_APDU     |               | <- guest sends APDU
+client<->physical |                          |                |               |
+card APDU exchange|                          |                |               |
+client response ->|      VSC_APDU            |   VSC_APDU     |               |  receive APDU response
+                                                    ...
+                                    [APDU<->APDU repeats several times]
+                                                    ...
+card removed  ->  |                          |                |               |
+                  |      VSC_CardRemove      |   remove       |    remove     |   card removed
+                                                    ...
+                                    [(card insert, apdu's, card remove) repeat]
+                                                    ...
+kill/quit         |                          |                |               |
+  vscclient       |                          |                |               |
+                  |      VSC_ReaderRemove    |                |    detach     |
+                  |                          |                |               |   usb device removed.
+
+
+8. libcacard
+
+ccid-card-passthru and vscclient use libcacard as the card emulator.
+libcacard 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 libcacard subdirectory.
+
Signature · 1 line
1.7.4
author
#26 lore raw

PATCH 17/20 ccid: configure: add --enable/disable and nss only disable

In reply to Alon Levy

add --enable-smartcard and --disable-smartcard flags, and let the nss check only disable building the ccid-card-emulated device, since both the usb-ccid and ccid-card-passthru don't depend on it.

---
 Makefile.objs   |    3 ++-
 Makefile.target |    2 +-
 configure       |   41 +++++++++++++++++++++++++++++------------
 3 files changed, 32 insertions(+), 14 deletions(-)
Makefile.objs +2 -1
index 459bbdb..dc95f23 100644
@@ -195,7 +195,8 @@ 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 ccid-card-emulated.o
+hw-obj-$(CONFIG_SMARTCARD) += usb-ccid.o ccid-card-passthru.o
+hw-obj-$(CONFIG_SMARTCARD_NSS) += ccid-card-emulated.o
 
 # PPC devices
 hw-obj-$(CONFIG_OPENPIC) += openpic.o
Makefile.target +1 -1
index 902e15d..5135bec 100644
@@ -340,7 +340,7 @@ obj-y += $(addprefix $(HWDIR)/, $(hw-obj-y))
 
 endif # CONFIG_SOFTMMU
 
-obj-y += $(addprefix ../libcacard/, $(libcacard-$(CONFIG_SMARTCARD)))
+obj-y += $(addprefix ../libcacard/, $(libcacard-$(CONFIG_SMARTCARD_NSS)))
 
 obj-y += $(addprefix ../, $(trace-obj-y))
 obj-$(CONFIG_GDBSTUB_XML) += gdbstub-xml.o
configure +29 -12

89 lines not on this page · raw message

Signature · 1 line
1.7.4
author
#27 lore raw

PATCH 18/20 ccid: add qdev description strings

In reply to Alon Levy
---
 hw/ccid-card-emulated.c |    1 +
 hw/ccid-card-passthru.c |    1 +
 hw/usb-ccid.c           |    1 +
 3 files changed, 3 insertions(+), 0 deletions(-)
hw/ccid-card-emulated.c +1 -0
index 09ce770..2e25daa 100644
@@ -525,6 +525,7 @@ EnumTable backend_enum_table[] = {
 
 static CCIDCardInfo emulated_card_info = {
     .qdev.name = EMULATED_DEV_NAME,
+    .qdev.desc = "emulated smartcard",
     .qdev.size = sizeof(EmulatedState),
     .initfn = emulated_initfn,
     .exitfn = emulated_exitfn,
hw/ccid-card-passthru.c +1 -0
index f3f3da9..f290bea 100644
@@ -306,6 +306,7 @@ static VMStateDescription passthru_vmstate = {
 
 static CCIDCardInfo passthru_card_info = {
     .qdev.name = PASSTHRU_DEV_NAME,
+    .qdev.desc = "passthrough smartcard",
     .qdev.size = sizeof(PassthruState),
     .qdev.vmsd = &passthru_vmstate,
     .initfn = passthru_initfn,
hw/usb-ccid.c +1 -0
index 09e39ac..27a7103 100644
@@ -1330,6 +1330,7 @@ static VMStateDescription ccid_vmstate = {
 static struct USBDeviceInfo ccid_info = {
     .product_desc   = "QEMU USB CCID",
     .qdev.name      = CCID_DEV_NAME,
+    .qdev.desc      = "CCID Rev 1.1 smartcard reader",
     .qdev.size      = sizeof(USBCCIDState),
     .init           = ccid_initfn,
     .handle_packet  = usb_generic_handle_packet,
Signature · 1 line
1.7.4
author
#28 lore raw

PATCH 19/20 smartcard, configure: add --enable-smartcard-nss, report only nss

In reply to Alon Levy
---
 configure |   28 ++++++++++++++++++++--------
 1 files changed, 20 insertions(+), 8 deletions(-)
configure +20 -8
index 8b86c9a..27e5488 100755
@@ -174,8 +174,8 @@ trace_backend="nop"
 trace_file="trace"
 spice=""
 rbd=""
-smartcard="yes"
-smartcard_nss="yes"
+smartcard=""
+smartcard_nss=""
 
 # parse CC options first
 for opt do
@@ -725,6 +725,10 @@ for opt do
   ;;
   --enable-smartcard) smartcard="yes"
   ;;
+  --disable-smartcard-nss) smartcard_nss="no"
+  ;;
+  --enable-smartcard-nss) smartcard_nss="yes"
+  ;;
   *) echo "ERROR: unknown option $opt"; show_help="yes"
   ;;
   esac
@@ -922,6 +926,8 @@ echo "  --enable-spice           enable spice"
 echo "  --enable-rbd             enable building the rados block device (rbd)"
 echo "  --disable-smartcard      disable smartcard support"
 echo "  --enable-smartcard       enable smartcard support"
+echo "  --disable-smartcard-nss  disable smartcard nss support"
+echo "  --enable-smartcard-nss   enable smartcard nss support"
 echo ""
 echo "NOTE: The object files are built at the place where configure is launched"
 exit 1
@@ -2249,16 +2255,22 @@ fi
 
 # check for libcacard for smartcard support
 if test "$smartcard" != "no" ; then
+    smartcard="yes"
     smartcard_cflags="-I\$(SRC_PATH)/libcacard"
     libcacard_libs=$($pkg_config --libs nss 2>/dev/null)
     libcacard_cflags=$($pkg_config --cflags nss 2>/dev/null)
     # TODO - what's the minimal nss version we support?
-    if $pkg_config --atleast-version=3.12.8 nss >/dev/null 2>&1 ; then
-        smartcard_nss="yes"
-        QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
-        LIBS="$libcacard_libs $LIBS"
-    else
-        smartcard_nss="no"
+    if test "$smartcard_nss" != "no"; then
+        if $pkg_config --atleast-version=3.12.8 nss >/dev/null 2>&1 ; then
+            smartcard_nss="yes"
+            QEMU_CFLAGS="$QEMU_CFLAGS $smartcard_cflags $libcacard_cflags"
+            LIBS="$libcacard_libs $LIBS"
+        else
+            if test "$smartcard_nss" == "yes"; then
+                feature_not_found "nss"
+            fi
+            smartcard_nss="no"
+        fi
     fi
 fi
 if test "$smartcard" == "no" ; then
Signature · 1 line
1.7.4
author
#29 lore raw

PATCH 20/20 smartcard,configure: report only nss

In reply to Alon Levy
---
 configure |    3 +--
 1 files changed, 1 insertions(+), 2 deletions(-)
configure +1 -2
index 27e5488..2cd73b4 100755
@@ -2510,8 +2510,7 @@ echo "Trace output file $trace_file-<pid>"
 echo "spice support     $spice"
 echo "rbd support       $rbd"
 echo "xfsctl support    $xfs"
-echo "smartcard support $smartcard"
-echo "   \_ nss support $smartcard_nss"
+echo "nss used          $smartcard_nss"
 
 if test $sdl_too_old = "yes"; then
 echo "-> Your SDL version is too old - please upgrade to have SDL support"
Signature · 1 line
1.7.4