Skip to contentSkip to conversation

usb: Hans' pending qemu usb patches

PATCH In review Hans de Goede 2 participants 39 messages Dec 14, 2012 – Dec 19, 2012

lore
Share & tools
lore
#0 lore raw

cover usb: Hans' pending qemu usb patches

As discussed a while back I've been holding back my patches till 1.3 was out the door. Since 1.3 is out the door now, here is my patch backlog + recent work.

This patch series includes:
-Various ehci sanity check patches (posted some time ago already) -Some more ehci speedups
-Various uhci fixes and speedups
-Change hid idle handling to use a timer
-Various usbredir fixes / improvement
-Buffered bulk in support for usbredir

The last one is what I've been working on for the past 2-3 weeks. This patch is both really nice in that it allows usb<->serial converters to work reliable even when we encounter large latency spikes, yet it also marks a point in the evolution of the usbredir code where I hoped we would never get as it introduces specific behavior for a certain class of devices (based on ubs-ids).

Regards,

Hans

#1 lore raw

PATCH 1/26 ehci: Add a ehci_writeback_async_complete_packet helper function

Also drop the warning printf, which was there mainly because this was an untested code path (as the previous bug fixes to it show), but that no longer is the case now :)

---
 hw/usb/hcd-ehci.c | 28 +++++++++++++++++-----------
 1 file changed, 17 insertions(+), 11 deletions(-)
hw/usb/hcd-ehci.c +17 -11
index 7536837..218b1d7 100644
@@ -438,6 +438,22 @@ static inline bool ehci_periodic_enabled(EHCIState *s)
     return ehci_enabled(s) && (s->usbcmd & USBCMD_PSE);
 }
 
+/* Finish executing and writeback a packet outside of the regular
+   fetchqh -> fetchqtd -> execute -> writeback cycle */
+static void ehci_writeback_async_complete_packet(EHCIPacket *p)
+{
+    EHCIQueue *q = p->queue;
+    int state;
+
+    state = ehci_get_state(q->ehci, q->async);
+    ehci_state_executing(q);
+    ehci_state_writeback(q); /* Frees the packet! */
+    if (!(q->qh.token & QTD_TOKEN_HALT)) {
+        ehci_state_advqueue(q);
+    }
+    ehci_set_state(q->ehci, q->async, state);
+}
+
 /* packet management */
 
 static EHCIPacket *ehci_alloc_packet(EHCIQueue *q)
@@ -455,17 +471,7 @@ static EHCIPacket *ehci_alloc_packet(EHCIQueue *q)
 static void ehci_free_packet(EHCIPacket *p)
 {
     if (p->async == EHCI_ASYNC_FINISHED) {
-        EHCIQueue *q = p->queue;
-        int state = ehci_get_state(q->ehci, q->async);
-        /* This is a normal, but rare condition (cancel racing completion) */
-        fprintf(stderr, "EHCI: Warning packet completed but not processed\n");
-        ehci_state_executing(q);
-        ehci_state_writeback(q);
-        if (!(q->qh.token & QTD_TOKEN_HALT)) {
-            ehci_state_advqueue(q);
-        }
-        ehci_set_state(q->ehci, q->async, state);
-        /* state_writeback recurses into us with async == EHCI_ASYNC_NONE!! */
+        ehci_writeback_async_complete_packet(p);
         return;
     }
     trace_usb_ehci_packet_action(p->queue, p, "free");
Signature · 1 line
1.8.0.1
#2 lore raw

PATCH 2/26 ehci: Add ehci_verify_qh and ehci_verify_qtd helper functions

In reply to Hans de Goede
---
 hw/usb/hcd-ehci.c | 51 +++++++++++++++++++++++++++++++++++----------------
 1 file changed, 35 insertions(+), 16 deletions(-)
hw/usb/hcd-ehci.c +35 -16
index 218b1d7..0d31597 100644
@@ -438,6 +438,36 @@ static inline bool ehci_periodic_enabled(EHCIState *s)
     return ehci_enabled(s) && (s->usbcmd & USBCMD_PSE);
 }
 
+static bool ehci_verify_qh(EHCIQueue *q, EHCIqh *qh)
+{
+    uint32_t devaddr = get_field(qh->epchar, QH_EPCHAR_DEVADDR);
+    uint32_t endp    = get_field(qh->epchar, QH_EPCHAR_EP);
+    if ((devaddr != get_field(q->qh.epchar, QH_EPCHAR_DEVADDR)) ||
+        (endp    != get_field(q->qh.epchar, QH_EPCHAR_EP)) ||
+        (qh->current_qtd != q->qh.current_qtd) ||
+        (q->async && qh->next_qtd != q->qh.next_qtd) ||
+        (memcmp(&qh->altnext_qtd, &q->qh.altnext_qtd,
+                                 7 * sizeof(uint32_t)) != 0) ||
+        (q->dev != NULL && q->dev->addr != devaddr)) {
+        return false;
+    } else {
+        return true;
+    }
+}
+
+static bool ehci_verify_qtd(EHCIPacket *p, EHCIqtd *qtd)
+{
+    if (p->qtdaddr != p->queue->qtdaddr ||
+        (p->queue->async && !NLPTR_TBIT(p->qtd.next) &&
+            (p->qtd.next != qtd->next)) ||
+        (!NLPTR_TBIT(p->qtd.altnext) && (p->qtd.altnext != qtd->altnext)) ||
+        p->qtd.bufptr[0] != qtd->bufptr[0]) {
+        return false;
+    } else {
+        return true;
+    }
+}
+
 /* Finish executing and writeback a packet outside of the regular
    fetchqh -> fetchqtd -> execute -> writeback cycle */
 static void ehci_writeback_async_complete_packet(EHCIPacket *p)
@@ -1557,8 +1587,8 @@ out:
 
 static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
 {
+    uint32_t entry;
     EHCIPacket *p;
-    uint32_t entry, devaddr, endp;
     EHCIQueue *q;
     EHCIqh qh;
 
@@ -1588,15 +1618,7 @@ static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
      * The overlay area of the qh should never be changed by the guest,
      * except when idle, in which case the reset is a nop.
      */
-    devaddr = get_field(qh.epchar, QH_EPCHAR_DEVADDR);
-    endp    = get_field(qh.epchar, QH_EPCHAR_EP);
-    if ((devaddr != get_field(q->qh.epchar, QH_EPCHAR_DEVADDR)) ||
-        (endp    != get_field(q->qh.epchar, QH_EPCHAR_EP)) ||
-        (qh.current_qtd != q->qh.current_qtd) ||
-        (q->async && qh.next_qtd != q->qh.next_qtd) ||
-        (memcmp(&qh.altnext_qtd, &q->qh.altnext_qtd,
-                                 7 * sizeof(uint32_t)) != 0) ||
-        (q->dev != NULL && q->dev->addr != devaddr)) {
+    if (!ehci_verify_qh(q, &qh)) {
         if (ehci_reset_queue(q) > 0) {
             ehci_trace_guest_bug(ehci, "guest updated active QH");
         }
@@ -1610,7 +1632,8 @@ static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
     }
 
     if (q->dev == NULL) {
-        q->dev = ehci_find_device(q->ehci, devaddr);
+        q->dev = ehci_find_device(q->ehci,
+                                  get_field(q->qh.epchar, QH_EPCHAR_DEVADDR));
     }
 
     if (p && p->async == EHCI_ASYNC_FINISHED) {
@@ -1768,11 +1791,7 @@ static int ehci_state_fetchqtd(EHCIQueue *q)
 
     p = QTAILQ_FIRST(&q->packets);
     if (p != NULL) {
-        if (p->qtdaddr != q->qtdaddr ||
-            (q->async && !NLPTR_TBIT(p->qtd.next) &&
-                (p->qtd.next != qtd.next)) ||
-            (!NLPTR_TBIT(p->qtd.altnext) && (p->qtd.altnext != qtd.altnext)) ||
-            p->qtd.bufptr[0] != qtd.bufptr[0]) {
+        if (!ehci_verify_qtd(p, &qtd)) {
             ehci_cancel_queue(q);
             ehci_trace_guest_bug(q->ehci, "guest updated active QH or qTD");
             p = NULL;
Signature · 1 line
1.8.0.1
#3 lore raw

PATCH 3/26 ehci: Verify guest does not change the token of inflight qtd-s

In reply to Hans de Goede

This is not allowed, except for clearing active on cancellation, so don't warn when the new token does not have its active bit set.

This unifies the cancellation path for modified qtd-s, and prepares ehci_verify_qtd to be used ad an extra check inside ehci_writeback_async_complete_packet().

---
 hw/usb/hcd-ehci.c | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
hw/usb/hcd-ehci.c +4 -6
index 0d31597..04301ce 100644
@@ -461,6 +461,7 @@ static bool ehci_verify_qtd(EHCIPacket *p, EHCIqtd *qtd)
         (p->queue->async && !NLPTR_TBIT(p->qtd.next) &&
             (p->qtd.next != qtd->next)) ||
         (!NLPTR_TBIT(p->qtd.altnext) && (p->qtd.altnext != qtd->altnext)) ||
+        p->qtd.token != qtd->token ||
         p->qtd.bufptr[0] != qtd->bufptr[0]) {
         return false;
     } else {
@@ -1793,7 +1794,9 @@ static int ehci_state_fetchqtd(EHCIQueue *q)
     if (p != NULL) {
         if (!ehci_verify_qtd(p, &qtd)) {
             ehci_cancel_queue(q);
-            ehci_trace_guest_bug(q->ehci, "guest updated active QH or qTD");
+            if (qtd.token & QTD_TOKEN_ACTIVE) {
+                ehci_trace_guest_bug(q->ehci, "guest updated active qTD");
+            }
             p = NULL;
         } else {
             p->qtd = qtd;
@@ -1802,11 +1805,6 @@ static int ehci_state_fetchqtd(EHCIQueue *q)
     }
 
     if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
-        if (p != NULL) {
-            /* transfer canceled by guest (clear active) */
-            ehci_cancel_queue(q);
-            p = NULL;
-        }
         ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
     } else if (p != NULL) {
         switch (p->async) {
Signature · 1 line
1.8.0.1
#4 lore raw

PATCH 4/26 ehci: Move get / put_dwords upwards

In reply to Hans de Goede

No other changes.

---
 hw/usb/hcd-ehci.c | 84 +++++++++++++++++++++++++++----------------------------
 1 file changed, 42 insertions(+), 42 deletions(-)
hw/usb/hcd-ehci.c +42 -42
index 04301ce..934af55 100644
@@ -438,6 +438,48 @@ static inline bool ehci_periodic_enabled(EHCIState *s)
     return ehci_enabled(s) && (s->usbcmd & USBCMD_PSE);
 }
 
+/* Get an array of dwords from main memory */
+static inline int get_dwords(EHCIState *ehci, uint32_t addr,
+                             uint32_t *buf, int num)
+{
+    int i;
+
+    if (!ehci->dma) {
+        ehci_raise_irq(ehci, USBSTS_HSE);
+        ehci->usbcmd &= ~USBCMD_RUNSTOP;
+        trace_usb_ehci_dma_error();
+        return -1;
+    }
+
+    for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
+        dma_memory_read(ehci->dma, addr, buf, sizeof(*buf));
+        *buf = le32_to_cpu(*buf);
+    }
+
+    return num;
+}
+
+/* Put an array of dwords in to main memory */
+static inline int put_dwords(EHCIState *ehci, uint32_t addr,
+                             uint32_t *buf, int num)
+{
+    int i;
+
+    if (!ehci->dma) {
+        ehci_raise_irq(ehci, USBSTS_HSE);
+        ehci->usbcmd &= ~USBCMD_RUNSTOP;
+        trace_usb_ehci_dma_error();
+        return -1;
+    }
+
+    for (i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
+        uint32_t tmp = cpu_to_le32(*buf);
+        dma_memory_write(ehci->dma, addr, &tmp, sizeof(tmp));
+    }
+
+    return num;
+}
+
 static bool ehci_verify_qh(EHCIQueue *q, EHCIqh *qh)
 {
     uint32_t devaddr = get_field(qh->epchar, QH_EPCHAR_DEVADDR);
@@ -1054,48 +1096,6 @@ static void ehci_opreg_write(void *ptr, hwaddr addr,
                                 *mmio, old);
 }
 
-/* Get an array of dwords from main memory */
-static inline int get_dwords(EHCIState *ehci, uint32_t addr,
-                             uint32_t *buf, int num)
-{
-    int i;
-
-    if (!ehci->dma) {
-        ehci_raise_irq(ehci, USBSTS_HSE);
-        ehci->usbcmd &= ~USBCMD_RUNSTOP;
-        trace_usb_ehci_dma_error();
-        return -1;
-    }
-
-    for(i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
-        dma_memory_read(ehci->dma, addr, buf, sizeof(*buf));
-        *buf = le32_to_cpu(*buf);
-    }
-
-    return num;
-}
-
-/* Put an array of dwords in to main memory */
-static inline int put_dwords(EHCIState *ehci, uint32_t addr,
-                             uint32_t *buf, int num)
-{
-    int i;
-
-    if (!ehci->dma) {
-        ehci_raise_irq(ehci, USBSTS_HSE);
-        ehci->usbcmd &= ~USBCMD_RUNSTOP;
-        trace_usb_ehci_dma_error();
-        return -1;
-    }
-
-    for(i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {
-        uint32_t tmp = cpu_to_le32(*buf);
-        dma_memory_write(ehci->dma, addr, &tmp, sizeof(tmp));
-    }
-
-    return num;
-}
-
 /*
  *  Write the qh back to guest physical memory.  This step isn't
  *  in the EHCI spec but we need to do it since we don't share
Signature · 1 line
1.8.0.1
#5 lore raw

PATCH 5/26 ehci: writeback_async_complete_packet: verify qh and qtd

In reply to Hans de Goede
---
 hw/usb/hcd-ehci.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
hw/usb/hcd-ehci.c +14 -0
index 934af55..96a0144 100644
@@ -192,6 +192,7 @@ static int ehci_state_executing(EHCIQueue *q);
 static int ehci_state_writeback(EHCIQueue *q);
 static int ehci_state_advqueue(EHCIQueue *q);
 static int ehci_fill_queue(EHCIPacket *p);
+static void ehci_free_packet(EHCIPacket *p);
 
 static const char *nr2str(const char **n, size_t len, uint32_t nr)
 {
@@ -516,8 +517,21 @@ static bool ehci_verify_qtd(EHCIPacket *p, EHCIqtd *qtd)
 static void ehci_writeback_async_complete_packet(EHCIPacket *p)
 {
     EHCIQueue *q = p->queue;
+    EHCIqtd qtd;
+    EHCIqh qh;
     int state;
 
+    /* Verify the qh + qtd, like we do when going through fetchqh & fetchqtd */
+    get_dwords(q->ehci, NLPTR_GET(q->qhaddr),
+               (uint32_t *) &qh, sizeof(EHCIqh) >> 2);
+    get_dwords(q->ehci, NLPTR_GET(q->qtdaddr),
+               (uint32_t *) &qtd, sizeof(EHCIqtd) >> 2);
+    if (!ehci_verify_qh(q, &qh) || !ehci_verify_qtd(p, &qtd)) {
+        p->async = EHCI_ASYNC_INITIALIZED;
+        ehci_free_packet(p);
+        return;
+    }
+
     state = ehci_get_state(q->ehci, q->async);
     ehci_state_executing(q);
     ehci_state_writeback(q); /* Frees the packet! */
Signature · 1 line
1.8.0.1
#6 lore raw

PATCH 6/26 ehci: Verify qtd for async completed packets

In reply to Hans de Goede

Remove the short-circuiting of fetchqtd in fetchqh, so that the qtd gets properly verified before completing the transaction.

---
 hw/usb/hcd-ehci.c | 15 +--------------
 1 file changed, 1 insertion(+), 14 deletions(-)
hw/usb/hcd-ehci.c +1 -14
index 96a0144..dde2ff3 100644
@@ -1603,7 +1603,6 @@ out:
 static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
 {
     uint32_t entry;
-    EHCIPacket *p;
     EHCIQueue *q;
     EHCIqh qh;
 
@@ -1612,7 +1611,6 @@ static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
     if (NULL == q) {
         q = ehci_alloc_queue(ehci, entry, async);
     }
-    p = QTAILQ_FIRST(&q->packets);
 
     q->seen++;
     if (q->seen > 1) {
@@ -1637,7 +1635,6 @@ static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
         if (ehci_reset_queue(q) > 0) {
             ehci_trace_guest_bug(ehci, "guest updated active QH");
         }
-        p = NULL;
     }
     q->qh = qh;
 
@@ -1651,13 +1648,6 @@ static EHCIQueue *ehci_state_fetchqh(EHCIState *ehci, int async)
                                   get_field(q->qh.epchar, QH_EPCHAR_DEVADDR));
     }
 
-    if (p && p->async == EHCI_ASYNC_FINISHED) {
-        /* I/O finished -- continue processing queue */
-        trace_usb_ehci_packet_action(p->queue, p, "complete");
-        ehci_set_state(ehci, async, EST_EXECUTING);
-        goto out;
-    }
-
     if (async && (q->qh.epchar & QH_EPCHAR_H)) {
 
         /*  EHCI spec version 1.0 Section 4.8.3 & 4.10.1 */
@@ -1834,10 +1824,7 @@ static int ehci_state_fetchqtd(EHCIQueue *q)
             ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);
             break;
         case EHCI_ASYNC_FINISHED:
-            /*
-             * We get here when advqueue moves to a packet which is already
-             * finished, which can happen with packets queued up by fill_queue
-             */
+            /* Complete executing of the packet */
             ehci_set_state(q->ehci, q->async, EST_EXECUTING);
             break;
         }
Signature · 1 line
1.8.0.1
#7 lore raw

PATCH 7/26 ehci: Add an ehci_get_pid helper function

In reply to Hans de Goede
---
 hw/usb/hcd-ehci.c | 32 ++++++++++++++++----------------
 1 file changed, 16 insertions(+), 16 deletions(-)
hw/usb/hcd-ehci.c +16 -16
index dde2ff3..dae414a 100644
@@ -481,6 +481,21 @@ static inline int put_dwords(EHCIState *ehci, uint32_t addr,
     return num;
 }
 
+static int ehci_get_pid(EHCIqtd *qtd)
+{
+    switch (get_field(qtd->token, QTD_TOKEN_PID)) {
+    case 0:
+        return USB_TOKEN_OUT;
+    case 1:
+        return USB_TOKEN_IN;
+    case 2:
+        return USB_TOKEN_SETUP;
+    default:
+        fprintf(stderr, "bad token\n");
+        return 0;
+    }
+}
+
 static bool ehci_verify_qh(EHCIQueue *q, EHCIqh *qh)
 {
     uint32_t devaddr = get_field(qh->epchar, QH_EPCHAR_DEVADDR);
@@ -1352,22 +1367,7 @@ static int ehci_execute(EHCIPacket *p, const char *action)
         return -1;
     }
 
-    p->pid = (p->qtd.token & QTD_TOKEN_PID_MASK) >> QTD_TOKEN_PID_SH;
-    switch (p->pid) {
-    case 0:
-        p->pid = USB_TOKEN_OUT;
-        break;
-    case 1:
-        p->pid = USB_TOKEN_IN;
-        break;
-    case 2:
-        p->pid = USB_TOKEN_SETUP;
-        break;
-    default:
-        fprintf(stderr, "bad token\n");
-        break;
-    }
-
+    p->pid = ehci_get_pid(&p->qtd);
     endp = get_field(p->queue->qh.epchar, QH_EPCHAR_EP);
     ep = usb_ep_get(p->queue->dev, p->pid, endp);
 
Signature · 1 line
1.8.0.1
#8 lore raw

PATCH 8/26 ehci: Verify a queue's ep direction does not change

In reply to Hans de Goede

ehci_fill_queue assumes that there is a one on one relationship between an ep and a qh, this patch adds a check to ensure this.

Note I don't expect this to ever trigger, this is just something I noticed the guest might do while working on other stuff. The only way this check can trigger is if a guest mixes in and out qtd-s in a single qh for a non control ep.

---
 hw/usb/hcd-ehci.c | 19 +++++++++++++++++++
 hw/usb/hcd-ehci.h |  1 +
 2 files changed, 20 insertions(+)
hw/usb/hcd-ehci.c +19 -0
index dae414a..5d314a0 100644
@@ -527,6 +527,19 @@ static bool ehci_verify_qtd(EHCIPacket *p, EHCIqtd *qtd)
     }
 }
 
+static bool ehci_verify_pid(EHCIQueue *q, EHCIqtd *qtd)
+{
+    int ep  = get_field(q->qh.epchar, QH_EPCHAR_EP);
+    int pid = ehci_get_pid(qtd);
+
+    /* Note the pid changing is normal for ep 0 (the control ep) */
+    if (q->last_pid && ep != 0 && pid != q->last_pid) {
+        return false;
+    } else {
+        return true;
+    }
+}
+
 /* Finish executing and writeback a packet outside of the regular
    fetchqh -> fetchqtd -> execute -> writeback cycle */
 static void ehci_writeback_async_complete_packet(EHCIPacket *p)
@@ -634,6 +647,7 @@ static int ehci_reset_queue(EHCIQueue *q)
     packets = ehci_cancel_queue(q);
     q->dev = NULL;
     q->qtdaddr = 0;
+    q->last_pid = 0;
     return packets;
 }
 
@@ -1368,6 +1382,7 @@ static int ehci_execute(EHCIPacket *p, const char *action)
     }
 
     p->pid = ehci_get_pid(&p->qtd);
+    p->queue->last_pid = p->pid;
     endp = get_field(p->queue->qh.epchar, QH_EPCHAR_EP);
     ep = usb_ep_get(p->queue->dev, p->pid, endp);
 
@@ -1883,6 +1898,10 @@ static int ehci_fill_queue(EHCIPacket *p)
         if (!(qtd.token & QTD_TOKEN_ACTIVE)) {
             break;
         }
+        if (!ehci_verify_pid(q, &qtd)) {
+            ehci_trace_guest_bug(q->ehci, "guest queued token with wrong pid");
+            break;
+        }
         p = ehci_alloc_packet(q);
         p->qtdaddr = qtdaddr;
         p->qtd = qtd;
hw/usb/hcd-ehci.h +1 -0
index 772870b..3c888a6 100644
@@ -246,6 +246,7 @@ struct EHCIQueue {
     EHCIqh qh;             /* copy of current QH (being worked on) */
     uint32_t qhaddr;       /* address QH read from                 */
     uint32_t qtdaddr;      /* address QTD read from                */
+    int last_pid;          /* pid of last packet executed          */
     USBDevice *dev;
     QTAILQ_HEAD(pkts_head, EHCIPacket) packets;
 };
Signature · 1 line
1.8.0.1
#9 lore raw

PATCH 9/26 ehci: Use uframe precision for interrupt threshold checking

In reply to Hans de Goede

Before this patch, the following could happen:
1) Transfer completes, raises interrupt
2) .5 ms later we check if the guest has queued up any new transfers
3) We find and execute a new transfer
4) .2 ms later the new transfer completes
5) We re-run our frame_timer to write back the completion, but less then 1 ms has passed since our last run, so frindex is not changed, so the interrupt threshold code delays the interrupt
6) 1 ms from the re-run our frame-timer runs again and finally delivers the interrupt

This leads to unnecessary large delays of interrupts, this code fixes this by keeping a shadow frindex variable which is incremented with uframe precision and using that for interrupt threshold control, making the interrupt fire at step 5 for guest which have low interrupt threshold settings (like Linux).

Note that a shadow variable is used instead of changing frindex to uframe accuracy because we must send a frindex which is a multiple of 8 during migration for migration compatibility, and rounding it down to a multiple of 8 pre-migration, can lead to frindex going backwards from the guest pov.

This boosts Linux read speed of a simple cheap USB thumb drive by 6 %.

---
 hw/usb/hcd-ehci.c | 69 ++++++++++++++++++++++++++++++++++++-------------------
 hw/usb/hcd-ehci.h |  3 +++
 2 files changed, 48 insertions(+), 24 deletions(-)
hw/usb/hcd-ehci.c +45 -24
index 5d314a0..ef3ab97 100644
@@ -109,12 +109,13 @@
 
 #define FRAME_TIMER_FREQ 1000
 #define FRAME_TIMER_NS   (1000000000 / FRAME_TIMER_FREQ)
+#define UFRAME_TIMER_NS  (FRAME_TIMER_NS / 8)
 
 #define NB_MAXINTRATE    8        // Max rate at which controller issues ints
 #define BUFF_SIZE        5*4096   // Max bytes to transfer per transaction
 #define MAX_QH           100      // Max allowable queue heads in a chain
-#define MIN_FR_PER_TICK  3        // Min frames to process when catching up
-#define PERIODIC_ACTIVE  64
+#define MIN_UFR_PER_TICK 24       /* Min frames to process when catching up */
+#define PERIODIC_ACTIVE  512      /* Micro-frames */
 
 /*  Internal periodic / asynchronous schedule state machine states
  */
@@ -277,7 +278,7 @@ static inline void ehci_update_irq(EHCIState *s)
         level = 1;
     }
 
-    trace_usb_ehci_irq(level, s->frindex, s->usbsts, s->usbintr);
+    trace_usb_ehci_irq(level, s->ufrindex, s->usbsts, s->usbintr);
     qemu_set_irq(s->irq, level);
 }
 
@@ -303,14 +304,14 @@ static inline void ehci_commit_irq(EHCIState *s)
     if (!s->usbsts_pending) {
         return;
     }
-    if (s->usbsts_frindex > s->frindex) {
+    if (s->usbsts_frindex > s->ufrindex) {
         return;
     }
 
     itc = (s->usbcmd >> 16) & 0xff;
     s->usbsts |= s->usbsts_pending;
     s->usbsts_pending = 0;
-    s->usbsts_frindex = s->frindex + itc;
+    s->usbsts_frindex = s->ufrindex + itc;
     ehci_update_irq(s);
 }
 
@@ -921,6 +922,7 @@ static void ehci_reset(void *opaque)
     s->usbsts = USBSTS_HALT;
     s->usbsts_pending = 0;
     s->usbsts_frindex = 0;
+    s->ufrindex = 0;
 
     s->astate = EST_INACTIVE;
     s->pstate = EST_INACTIVE;
@@ -1107,6 +1109,8 @@ static void ehci_opreg_write(void *ptr, hwaddr addr,
 
     case FRINDEX:
         val &= 0x00003ff8; /* frindex is 14bits and always a multiple of 8 */
+        s->usbsts_frindex = val;
+        s->ufrindex = val;
         break;
 
     case CONFIGFLAG:
@@ -2219,16 +2223,21 @@ static void ehci_advance_periodic_state(EHCIState *ehci)
     }
 }
 
-static void ehci_update_frindex(EHCIState *ehci, int frames)
+static void ehci_update_frindex(EHCIState *ehci, int uframes)
 {
     int i;
 
-    if (!ehci_enabled(ehci)) {
+    if (!ehci_enabled(ehci) && ehci->pstate == EST_INACTIVE) {
         return;
     }
 
-    for (i = 0; i < frames; i++) {
-        ehci->frindex += 8;
+    for (i = 0; i < uframes; i++) {
+        ehci->ufrindex++;
+
+        if (ehci->ufrindex & 7) {
+            continue;
+        }
+        ehci->frindex = ehci->ufrindex;
 
         if (ehci->frindex == 0x00002000) {
             ehci_raise_irq(ehci, USBSTS_FLR);
@@ -2237,6 +2246,7 @@ static void ehci_update_frindex(EHCIState *ehci, int frames)
         if (ehci->frindex == 0x00004000) {
             ehci_raise_irq(ehci, USBSTS_FLR);
             ehci->frindex = 0;
+            ehci->ufrindex = 0;
             if (ehci->usbsts_frindex >= 0x00004000) {
                 ehci->usbsts_frindex -= 0x00004000;
             } else {
@@ -2252,33 +2262,33 @@ static void ehci_frame_timer(void *opaque)
     int need_timer = 0;
     int64_t expire_time, t_now;
     uint64_t ns_elapsed;
-    int frames, skipped_frames;
+    int uframes, skipped_uframes;
     int i;
 
     t_now = qemu_get_clock_ns(vm_clock);
     ns_elapsed = t_now - ehci->last_run_ns;
-    frames = ns_elapsed / FRAME_TIMER_NS;
+    uframes = ns_elapsed / UFRAME_TIMER_NS;
 
     if (ehci_periodic_enabled(ehci) || ehci->pstate != EST_INACTIVE) {
         need_timer++;
 
-        if (frames > ehci->maxframes) {
-            skipped_frames = frames - ehci->maxframes;
-            ehci_update_frindex(ehci, skipped_frames);
-            ehci->last_run_ns += FRAME_TIMER_NS * skipped_frames;
-            frames -= skipped_frames;
-            DPRINTF("WARNING - EHCI skipped %d frames\n", skipped_frames);
+        if (uframes > (ehci->maxframes * 8)) {
+            skipped_uframes = uframes - (ehci->maxframes * 8);
+            ehci_update_frindex(ehci, skipped_uframes);
+            ehci->last_run_ns += UFRAME_TIMER_NS * skipped_uframes;
+            uframes -= skipped_uframes;
+            DPRINTF("WARNING - EHCI skipped %d uframes\n", skipped_uframes);
         }
 
-        for (i = 0; i < frames; i++) {
+        for (i = 0; i < uframes; i++) {
             /*
              * If we're running behind schedule, we should not catch up
              * too fast, as that will make some guests unhappy:
-             * 1) We must process a minimum of MIN_FR_PER_TICK frames,
+             * 1) We must process a minimum of MIN_UFR_PER_TICK frames,
              *    otherwise we will never catch up
              * 2) Process frames until the guest has requested an irq (IOC)
              */
-            if (i >= MIN_FR_PER_TICK) {
+            if (i >= MIN_UFR_PER_TICK) {
                 ehci_commit_irq(ehci);
                 if ((ehci->usbsts & USBINTR_MASK) & ehci->usbintr) {
                     break;
@@ -2288,13 +2298,15 @@ static void ehci_frame_timer(void *opaque)
                 ehci->periodic_sched_active--;
             }
             ehci_update_frindex(ehci, 1);
-            ehci_advance_periodic_state(ehci);
-            ehci->last_run_ns += FRAME_TIMER_NS;
+            if ((ehci->ufrindex & 7) == 0) {
+                ehci_advance_periodic_state(ehci);
+            }
+            ehci->last_run_ns += UFRAME_TIMER_NS;
         }
     } else {
         ehci->periodic_sched_active = 0;
-        ehci_update_frindex(ehci, frames);
-        ehci->last_run_ns += FRAME_TIMER_NS * frames;
+        ehci_update_frindex(ehci, uframes);
+        ehci->last_run_ns += UFRAME_TIMER_NS * uframes;
     }
 
     if (ehci->periodic_sched_active) {
@@ -2373,6 +2385,14 @@ static USBBusOps ehci_bus_ops = {
     .wakeup_endpoint = ehci_wakeup_endpoint,
 };
 
+static void usb_ehci_pre_save(void *opaque)
+{
+    EHCIState *ehci = opaque;
+
+    ehci->last_run_ns -= (ehci->ufrindex - ehci->frindex) * UFRAME_TIMER_NS;
+    ehci->ufrindex = ehci->frindex;
+}
+
 static int usb_ehci_post_load(void *opaque, int version_id)
 {
     EHCIState *s = opaque;
@@ -2423,6 +2443,7 @@ const VMStateDescription vmstate_ehci = {
     .name        = "ehci-core",
     .version_id  = 2,
     .minimum_version_id  = 1,
+    .pre_save    = usb_ehci_pre_save,
     .post_load   = usb_ehci_post_load,
     .fields      = (VMStateField[]) {
         /* mmio registers */
hw/usb/hcd-ehci.h +3 -0
index 3c888a6..d8fad41 100644
@@ -300,6 +300,9 @@ struct EHCIState {
     USBPort *companion_ports[NB_PORTS];
     uint32_t usbsts_pending;
     uint32_t usbsts_frindex;
+    /* frindex shadow in uframes precision, frindex moves in steps of 8
+     * (so whole frames) to avoid it going backwards when migrating */
+    uint32_t ufrindex;
     EHCIQueueHead aqueues;
     EHCIQueueHead pqueues;
 
Signature · 1 line
1.8.0.1
#10 lore raw

Re: [Qemu-devel] [PATCH 09/26] ehci: Use uframe precision for interrupt threshold checking

Quoted 5 lines · Hans de Goede

Note that a shadow variable is used instead of changing frindex to uframe accuracy because we must send a frindex which is a multiple of 8 during migration for migration compatibility, and rounding it down to a multiple of 8 pre-migration, can lead to frindex going backwards from the guest pov.

Jumping forward instead?

cheers,
Gerd

#11 lore raw

Re: [Qemu-devel] [PATCH 09/26] ehci: Use uframe precision for interrupt threshold checking

Hi,

Quoted 8 lines · Gerd Hoffmann
Quoted 5 lines · Hans de Goede

Note that a shadow variable is used instead of changing frindex to uframe accuracy because we must send a frindex which is a multiple of 8 during migration for migration compatibility, and rounding it down to a multiple of 8 pre-migration, can lead to frindex going backwards from the guest pov.

Jumping forward instead?

You mean rounding the send frindex up pre-migration, I didn't really consider that as it will cause us skipping processing an entry in the periodic frame list. I guess doing that on migration isn't too bad. OTOH giving the guest only frame accuracy like we've been doing till now also works fine...

Your choice :)

Regards,

Hans

#12 lore raw

Re: [Qemu-devel] [PATCH 09/26] ehci: Use uframe precision for interrupt threshold checking

Quoted 12 lines · Hans de Goede

Hi,

Quoted 8 lines · Gerd Hoffmann
Quoted 5 lines · Hans de Goede

Note that a shadow variable is used instead of changing frindex to uframe accuracy because we must send a frindex which is a multiple of 8 during migration for migration compatibility, and rounding it down to a multiple of 8 pre-migration, can lead to frindex going backwards from the guest pov.

Jumping forward instead?

Quoted 7 lines

You mean rounding the send frindex up pre-migration, I didn't really consider
that as it will cause us skipping processing an entry in the periodic frame list. I guess doing that on migration isn't too bad. OTOH giving the guest only frame accuracy like we've been doing till now also works fine...

Your choice :)

I'm looking for a way to avoid the shadow variable, but of course without breaking migration. giving the guest only frame accuracy looks good to me.

cheers,
Gerd

#13 lore raw

Re: [Qemu-devel] [PATCH 09/26] ehci: Use uframe precision for interrupt threshold checking

Hi,

Quoted 19 lines · Gerd Hoffmann
Quoted 18 lines · Hans de Goede

Hi,

Quoted 8 lines · Gerd Hoffmann
Quoted 5 lines · Hans de Goede

Note that a shadow variable is used instead of changing frindex to uframe accuracy because we must send a frindex which is a multiple of 8 during migration for migration compatibility, and rounding it down to a multiple of 8 pre-migration, can lead to frindex going backwards from the guest pov.

Jumping forward instead?

You mean rounding the send frindex up pre-migration, I didn't really consider
that as it will cause us skipping processing an entry in the periodic frame list. I guess doing that on migration isn't too bad. OTOH giving the guest only frame accuracy like we've been doing till now also works fine...

Quoted 5 lines
Quoted 1 line

Your choice :)

I'm looking for a way to avoid the shadow variable, but of course without breaking migration. giving the guest only frame accuracy looks good to me.

Ok, but then we need the shadow variable, iow then the patch stays as is ...

Regards,

Hans

#14 lore raw

Re: [Qemu-devel] [PATCH 09/26] ehci: Use uframe precision for interrupt threshold checking

Quoted 26 lines · Hans de Goede

Hi,

Quoted 23 lines · Gerd Hoffmann
Quoted 22 lines · Hans de Goede

Hi,

Quoted 10 lines · Gerd Hoffmann
Quoted 7 lines · Hans de Goede

Note that a shadow variable is used instead of changing frindex to uframe accuracy because we must send a frindex which is a multiple of 8
during migration for migration compatibility, and rounding it down to a multiple of 8 pre-migration, can lead to frindex going backwards from
the guest pov.

Jumping forward instead?

You mean rounding the send frindex up pre-migration, I didn't really consider
that as it will cause us skipping processing an entry in the periodic frame
list. I guess doing that on migration isn't too bad. OTOH giving the guest
only frame accuracy like we've been doing till now also works fine...

Quoted 8 lines
Quoted 5 lines
Quoted 1 line

Your choice :)

I'm looking for a way to avoid the shadow variable, but of course without breaking migration. giving the guest only frame accuracy looks good to me.

Ok, but then we need the shadow variable, iow then the patch stays as is
...

Can't we (a) switch frindex to microframe resolution, (b) round to frame resolution in pre_save and (c) return frindex & ~7 on guest register reads?

cheers,
Gerd

#15 lore raw

Re: [Qemu-devel] [PATCH 09/26] ehci: Use uframe precision for interrupt threshold checking

Hi,

Quoted 33 lines · Gerd Hoffmann
Quoted 32 lines · Hans de Goede

Hi,

Quoted 28 lines · Gerd Hoffmann
Quoted 22 lines · Hans de Goede

Hi,

Quoted 10 lines · Gerd Hoffmann
Quoted 7 lines · Hans de Goede

Note that a shadow variable is used instead of changing frindex to uframe accuracy because we must send a frindex which is a multiple of 8
during migration for migration compatibility, and rounding it down to a multiple of 8 pre-migration, can lead to frindex going backwards from
the guest pov.

Jumping forward instead?

You mean rounding the send frindex up pre-migration, I didn't really consider
that as it will cause us skipping processing an entry in the periodic frame
list. I guess doing that on migration isn't too bad. OTOH giving the guest
only frame accuracy like we've been doing till now also works fine...

Quoted 1 line

Your choice :)

I'm looking for a way to avoid the shadow variable, but of course without breaking migration. giving the guest only frame accuracy looks good to me.

Quoted 5 lines
Quoted 2 lines

Ok, but then we need the shadow variable, iow then the patch stays as is
...

Can't we (a) switch frindex to microframe resolution, (b) round to frame resolution in pre_save and (c) return frindex & ~7 on guest register reads?

Ah yes we can. I thought about that myself, but I was under the impression that we were using mmap tricks to allow the guest to read the ioregs directly without going through a vmexit. But it turns out we've:

static uint64_t ehci_opreg_read(void *ptr, hwaddr addr,
unsigned size)

{
    EHCIState *s = ptr;
    uint32_t val;

    val = s->opreg[addr >> 2];
    trace_usb_ehci_opreg_read(addr + s->opregbase, addr2str(addr), val);
    return val;
}

Can qemu not handle an mmio range where writes are trapped, but reads are not? That would force the use of the shadow variable, but should otherwise provide a nice speedup.

Regards,

Hans

#16 lore raw

Re: [Qemu-devel] [PATCH 09/26] ehci: Use uframe precision for interrupt threshold checking

Hi,

Quoted 3 lines

Can qemu not handle an mmio range where writes are trapped, but reads are not? That would force the use of the shadow variable, but should otherwise provide a nice speedup.

No. vmexit is needed anyway btw, but the round-trip to qemu userspace could be short-cutted in theory. It's non-trivial though. Alex had a talk about it at kvm forum (covering ide).

First a simple read directly + write via qemu isn't that useful. You need a policy per register.

For most reads it would work, but there are exceptions. Registers holding timers for example. frindex is actually an example of that. With async_stepdown active frindex updates are quite jumpy. We might want to update the register on guest reads (and maybe also reset async stepdown in that case).

Likewise the other way around: Not all register writes have some effect which qemu must emulate, some are just storage (like ehci frame list address).

Locking is an unsolved issue (in-kernel register reads/writes don't grab the qemu lock and thus would race with iothread accessing the register variables).

cheers,
Gerd

#17 lore raw

Re: [Qemu-devel] [PATCH 09/26] ehci: Use uframe precision for interrupt threshold checking

Hi,

Quoted 9 lines · Gerd Hoffmann
   Hi,
Quoted 3 lines

Can qemu not handle an mmio range where writes are trapped, but reads are not? That would force the use of the shadow variable, but should otherwise provide a nice speedup.

No. vmexit is needed anyway btw, but the round-trip to qemu userspace could be short-cutted in theory. It's non-trivial though. Alex had a talk about it at kvm forum (covering ide).

Ok, then I'll respin the patch getting rid of the shadow variable.

Regards,

Hans

#18 lore raw

PATCH 10/26 ehci: Further speedup rescanning if async schedule after raising an interrupt

In reply to Hans de Goede

I tried lowering the time between raising an interrupt and rescanning the async schedule to see if the guest has queued a new transfer before, but that did not have any positive effect. I now believe the cause for this is that lowering this time made it more likely to hit the 1 ms interrupt threshold penalty for the next packet, as described in my "ehci: Use uframe precision for interrupt threshold checking" commit.

Now that we do interrupt threshold handling with uframe precision, futher lowering this time from .5 to .25 ms gives an extra 15% improvement in speed (MB/s) reading from a simple USB-2.0 thumb-drive.

While at it also properly set the int_req_by_async flag for short packet completions.

---
 hw/usb/hcd-ehci.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
hw/usb/hcd-ehci.c +4 -1
index ef3ab97..c4d77bc 100644
@@ -1341,6 +1341,9 @@ static void ehci_execute_complete(EHCIQueue *q)
         if (tbytes) {
             /* 4.15.1.2 must raise int on a short input packet */
             ehci_raise_irq(q->ehci, USBSTS_INT);
+            if (q->async) {
+                q->ehci->int_req_by_async = true;
+            }
         }
     } else {
         tbytes = 0;
@@ -2337,7 +2340,7 @@ static void ehci_frame_timer(void *opaque)
         /* If we've raised int, we speed up the timer, so that we quickly
          * notice any new packets queued up in response */
         if (ehci->int_req_by_async && (ehci->usbsts & USBSTS_INT)) {
-            expire_time = t_now + get_ticks_per_sec() / (FRAME_TIMER_FREQ * 2);
+            expire_time = t_now + get_ticks_per_sec() / (FRAME_TIMER_FREQ * 4);
             ehci->int_req_by_async = false;
         } else {
             expire_time = t_now + (get_ticks_per_sec()
Signature · 1 line
1.8.0.1
#19 lore raw

PATCH 11/26 ehci: Don't call commit_irq after raising PCD

In reply to Hans de Goede

ehci_raise_irq(s, USBSTS_PCD), gets applied immediately so there is no need to call commit_irq after it.

---
 hw/usb/hcd-ehci.c | 2 --
 1 file changed, 2 deletions(-)
hw/usb/hcd-ehci.c +0 -2
index c4d77bc..36165b0 100644
@@ -757,7 +757,6 @@ static void ehci_attach(USBPort *port)
     *portsc |= PORTSC_CSC;
 
     ehci_raise_irq(s, USBSTS_PCD);
-    ehci_commit_irq(s);
 }
 
 static void ehci_detach(USBPort *port)
@@ -787,7 +786,6 @@ static void ehci_detach(USBPort *port)
     *portsc |= PORTSC_CSC;
 
     ehci_raise_irq(s, USBSTS_PCD);
-    ehci_commit_irq(s);
 }
 
 static void ehci_child_detach(USBPort *port, USBDevice *child)
Signature · 1 line
1.8.0.1
#20 lore raw

PATCH 12/26 uhci: Fix 1 ms delay in interrupt reporting to the guest

In reply to Hans de Goede

Re-arrange how we process frames / increase frnum / report pending interrupts, to avoid a 1 ms delay in interrupt reporting to the guest. This increases the packet throughput for cases where the guest submits a single packet, then waits for its completion then re-submits from 500 pkts / sec to 1000 pkts / sec. This impacts for example the use of redirected / virtual usb to serial convertors.

---
 hw/usb/hcd-uhci.c | 24 +++++++++++++-----------
 1 file changed, 13 insertions(+), 11 deletions(-)
hw/usb/hcd-uhci.c +13 -11
index d053791..843927b 100644
@@ -1191,17 +1191,7 @@ static void uhci_frame_timer(void *opaque)
         return;
     }
 
-    /* Complete the previous frame */
-    if (s->pending_int_mask) {
-        s->status2 |= s->pending_int_mask;
-        s->status  |= UHCI_STS_USBINT;
-        uhci_update_irq(s);
-    }
-    s->pending_int_mask = 0;
-
-    /* Start new frame */
-    s->frnum = (s->frnum + 1) & 0x7ff;
-
+    /* Process the current frame */
     trace_usb_uhci_frame_start(s->frnum);
 
     uhci_async_validate_begin(s);
@@ -1210,6 +1200,18 @@ static void uhci_frame_timer(void *opaque)
 
     uhci_async_validate_end(s);
 
+    /* The uhci spec says frnum reflects the frame currently being processed,
+     * and the guest must look at frnum - 1 on interrupt, so inc frnum now */
+    s->frnum = (s->frnum + 1) & 0x7ff;
+
+    /* Complete the previous frame */
+    if (s->pending_int_mask) {
+        s->status2 |= s->pending_int_mask;
+        s->status  |= UHCI_STS_USBINT;
+        uhci_update_irq(s);
+    }
+    s->pending_int_mask = 0;
+
     qemu_mod_timer(s->frame_timer, s->expire_time);
 }
 
Signature · 1 line
1.8.0.1
#21 lore raw

PATCH 13/26 uhci: Fix pending interrupts getting lost on migration

In reply to Hans de Goede
---
 hw/usb/hcd-uhci.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
hw/usb/hcd-uhci.c +2 -1
index 843927b..1e32549 100644
@@ -433,7 +433,7 @@ static int uhci_post_load(void *opaque, int version_id)
 
 static const VMStateDescription vmstate_uhci = {
     .name = "uhci",
-    .version_id = 2,
+    .version_id = 3,
     .minimum_version_id = 1,
     .minimum_version_id_old = 1,
     .post_load = uhci_post_load,
@@ -451,6 +451,7 @@ static const VMStateDescription vmstate_uhci = {
         VMSTATE_UINT8(status2, UHCIState),
         VMSTATE_TIMER(frame_timer, UHCIState),
         VMSTATE_INT64_V(expire_time, UHCIState, 2),
+        VMSTATE_UINT32_V(pending_int_mask, UHCIState, 3),
         VMSTATE_END_OF_LIST()
     }
 };
Signature · 1 line
1.8.0.1
#22 lore raw

PATCH 14/26 uhci: Add a QH_VALID define

In reply to Hans de Goede

Rather then using the magic 32 value in various places.

---
 hw/usb/hcd-uhci.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
hw/usb/hcd-uhci.c +5 -4
index 1e32549..11ccdc8 100644
@@ -75,6 +75,9 @@
 
 #define FRAME_MAX_LOOPS  256
 
+/* Must be large enough to handle 10 frame delay for initial isoc requests */
+#define QH_VALID         32
+
 #define NB_PORTS 2
 
 enum {
@@ -206,9 +209,7 @@ static UHCIQueue *uhci_queue_new(UHCIState *s, uint32_t qh_addr, UHCI_TD *td,
     queue->ep = ep;
     QTAILQ_INIT(&queue->asyncs);
     QTAILQ_INSERT_HEAD(&s->queues, queue, next);
-    /* valid needs to be large enough to handle 10 frame delay
-     * for initial isochronous requests */
-    queue->valid = 32;
+    queue->valid = QH_VALID;
     trace_usb_uhci_queue_add(queue->token);
     return queue;
 }
@@ -854,7 +855,7 @@ static int uhci_handle_td(UHCIState *s, UHCIQueue *q, uint32_t qh_addr,
     }
 
     if (q) {
-        q->valid = 32;
+        q->valid = QH_VALID;
     }
 
     /* Is active ? */
Signature · 1 line
1.8.0.1
#23 lore raw

PATCH 15/26 uhci: Limit amount of frames processed in one go

In reply to Hans de Goede

Before this patch uhci would process an unlimited amount of frames when behind on schedule, by setting the timer to a time already past, causing the timer subsys to immediately recall the frame_timer function gain.

This would cause invalid cancellations of bulk queues when the catching up processed more then 32 frames at a moment when the bulk qh was temporarily unlinked (which the Linux uhci driver does).

This patch fixes this by processing maximum 16 frames in one go, and always setting the timer one ms later, making the code behave more like the ehci code.

---
 hw/usb/hcd-uhci.c | 43 +++++++++++++++++++++++++++----------------
 1 file changed, 27 insertions(+), 16 deletions(-)
hw/usb/hcd-uhci.c +27 -16
index 11ccdc8..2a5d4cc 100644
@@ -78,6 +78,8 @@
 /* Must be large enough to handle 10 frame delay for initial isoc requests */
 #define QH_VALID         32
 
+#define MAX_FRAMES_PER_TICK    (QH_VALID / 2)
+
 #define NB_PORTS 2
 
 enum {
@@ -500,7 +502,7 @@ static void uhci_ioport_writew(void *opaque, uint32_t addr, uint32_t val)
             trace_usb_uhci_schedule_start();
             s->expire_time = qemu_get_clock_ns(vm_clock) +
                 (get_ticks_per_sec() / FRAME_TIMER_FREQ);
-            qemu_mod_timer(s->frame_timer, qemu_get_clock_ns(vm_clock));
+            qemu_mod_timer(s->frame_timer, s->expire_time);
             s->status &= ~UHCI_STS_HCHALTED;
         } else if (!(val & UHCI_CMD_RS)) {
             s->status |= UHCI_STS_HCHALTED;
@@ -1176,10 +1178,10 @@ static void uhci_bh(void *opaque)
 static void uhci_frame_timer(void *opaque)
 {
     UHCIState *s = opaque;
+    uint64_t t_now, t_last_run;
+    int i, frames;
+    const uint64_t frame_t = get_ticks_per_sec() / FRAME_TIMER_FREQ;
 
-    /* prepare the timer for the next frame */
-    s->expire_time += (get_ticks_per_sec() / FRAME_TIMER_FREQ);
-    s->frame_bytes = 0;
     s->completions_only = false;
     qemu_bh_cancel(s->bh);
 
@@ -1193,20 +1195,29 @@ static void uhci_frame_timer(void *opaque)
         return;
     }
 
-    /* Process the current frame */
-    trace_usb_uhci_frame_start(s->frnum);
-
-    uhci_async_validate_begin(s);
-
-    uhci_process_frame(s);
+    /* We still store expire_time in our state, for migration */
+    t_last_run = s->expire_time - frame_t;
+    t_now = qemu_get_clock_ns(vm_clock);
 
-    uhci_async_validate_end(s);
+    /* Process up to MAX_FRAMES_PER_TICK frames */
+    frames = (t_now - t_last_run) / frame_t;
+    if (frames > MAX_FRAMES_PER_TICK) {
+        frames = MAX_FRAMES_PER_TICK;
+    }
 
-    /* The uhci spec says frnum reflects the frame currently being processed,
-     * and the guest must look at frnum - 1 on interrupt, so inc frnum now */
-    s->frnum = (s->frnum + 1) & 0x7ff;
+    for (i = 0; i < frames; i++) {
+        s->frame_bytes = 0;
+        trace_usb_uhci_frame_start(s->frnum);
+        uhci_async_validate_begin(s);
+        uhci_process_frame(s);
+        uhci_async_validate_end(s);
+        /* The spec says frnum is the frame currently being processed, and
+         * the guest must look at frnum - 1 on interrupt, so inc frnum now */
+        s->frnum = (s->frnum + 1) & 0x7ff;
+        s->expire_time += frame_t;
+    }
 
-    /* Complete the previous frame */
+    /* Complete the previous frame(s) */
     if (s->pending_int_mask) {
         s->status2 |= s->pending_int_mask;
         s->status  |= UHCI_STS_USBINT;
@@ -1214,7 +1225,7 @@ static void uhci_frame_timer(void *opaque)
     }
     s->pending_int_mask = 0;
 
-    qemu_mod_timer(s->frame_timer, s->expire_time);
+    qemu_mod_timer(s->frame_timer, t_now + frame_t);
 }
 
 static const MemoryRegionPortio uhci_portio[] = {
Signature · 1 line
1.8.0.1
#24 lore raw

PATCH 16/26 uhci: Maximize how many frames we catch up when behind

In reply to Hans de Goede

If somehow we've gotten behind a lot, simply skip ahead, like the ehci code does.

---
 hw/usb/hcd-uhci.c | 8 ++++++++
 1 file changed, 8 insertions(+)
hw/usb/hcd-uhci.c +8 -0
index 2a5d4cc..fa75a77 100644
@@ -171,6 +171,7 @@ struct UHCIState {
     /* Properties */
     char *masterbus;
     uint32_t firstport;
+    uint32_t maxframes;
 };
 
 typedef struct UHCI_TD {
@@ -1201,6 +1202,12 @@ static void uhci_frame_timer(void *opaque)
 
     /* Process up to MAX_FRAMES_PER_TICK frames */
     frames = (t_now - t_last_run) / frame_t;
+    if (frames > s->maxframes) {
+        int skipped = frames - s->maxframes;
+        s->expire_time += skipped * frame_t;
+        s->frnum = (s->frnum + skipped) & 0x7ff;
+        frames -= skipped;
+    }
     if (frames > MAX_FRAMES_PER_TICK) {
         frames = MAX_FRAMES_PER_TICK;
     }
@@ -1326,6 +1333,7 @@ static Property uhci_properties[] = {
     DEFINE_PROP_STRING("masterbus", UHCIState, masterbus),
     DEFINE_PROP_UINT32("firstport", UHCIState, firstport, 0),
     DEFINE_PROP_UINT32("bandwidth", UHCIState, frame_bandwidth, 1280),
+    DEFINE_PROP_UINT32("maxframes", UHCIState, maxframes, 128),
     DEFINE_PROP_END_OF_LIST(),
 };
 
Signature · 1 line
1.8.0.1
#25 lore raw

PATCH 17/26 hid: Change idle handling to use a timer

In reply to Hans de Goede

This leads to cleaner code in usb-hid, and removes up to a 1000 calls / sec to qemu_get_clock_ns(vm_clock) if idle-time is set to its default value of 0.

---
 hw/hid.c         | 43 +++++++++++++++++++++++++++++++++++++------
 hw/hid.h         |  5 +++--
 hw/usb/dev-hid.c |  8 +++-----
 3 files changed, 43 insertions(+), 13 deletions(-)
hw/hid.c +37 -6
index 03761ab..f8c5393 100644
@@ -71,12 +71,38 @@ static const uint8_t hid_usage_keys[0x100] = {
 
 bool hid_has_events(HIDState *hs)
 {
-    return hs->n > 0;
+    return hs->n > 0 || hs->idle_pending;
 }
 
-void hid_set_next_idle(HIDState *hs, int64_t curtime)
+static void hid_idle_timer(void *opaque)
 {
-    hs->next_idle_clock = curtime + (get_ticks_per_sec() * hs->idle * 4) / 1000;
+    HIDState *hs = opaque;
+
+    hs->idle_pending = true;
+    hs->event(hs);
+}
+
+static void hid_del_idle_timer(HIDState *hs)
+{
+    if (hs->idle_timer) {
+        qemu_del_timer(hs->idle_timer);
+        qemu_free_timer(hs->idle_timer);
+        hs->idle_timer = NULL;
+    }
+}
+
+void hid_set_next_idle(HIDState *hs)
+{
+    if (hs->idle) {
+        uint64_t expire_time = qemu_get_clock_ns(vm_clock) +
+                               get_ticks_per_sec() * hs->idle * 4 / 1000;
+        if (!hs->idle_timer) {
+            hs->idle_timer = qemu_new_timer_ns(vm_clock, hid_idle_timer, hs);
+        }
+        qemu_mod_timer_ns(hs->idle_timer, expire_time);
+    } else {
+        hid_del_idle_timer(hs);
+    }
 }
 
 static void hid_pointer_event_clear(HIDPointerEvent *e, int buttons)
@@ -232,6 +258,8 @@ int hid_pointer_poll(HIDState *hs, uint8_t *buf, int len)
     int index;
     HIDPointerEvent *e;
 
+    hs->idle_pending = false;
+
     hid_pointer_activate(hs);
 
     /* When the buffer is empty, return the last event.  Relative
@@ -319,6 +347,8 @@ int hid_pointer_poll(HIDState *hs, uint8_t *buf, int len)
 
 int hid_keyboard_poll(HIDState *hs, uint8_t *buf, int len)
 {
+    hs->idle_pending = false;
+
     if (len < 2) {
         return 0;
     }
@@ -377,6 +407,8 @@ void hid_reset(HIDState *hs)
     hs->n = 0;
     hs->protocol = 1;
     hs->idle = 0;
+    hs->idle_pending = false;
+    hid_del_idle_timer(hs);
 }
 
 void hid_free(HIDState *hs)
@@ -390,6 +422,7 @@ void hid_free(HIDState *hs)
         qemu_remove_mouse_event_handler(hs->ptr.eh_entry);
         break;
     }
+    hid_del_idle_timer(hs);
 }
 
 void hid_init(HIDState *hs, int kind, HIDEventFunc event)
@@ -412,9 +445,7 @@ static int hid_post_load(void *opaque, int version_id)
 {
     HIDState *s = opaque;
 
-    if (s->idle) {
-        hid_set_next_idle(s, qemu_get_clock_ns(vm_clock));
-    }
+    hid_set_next_idle(s);
     return 0;
 }
 
hw/hid.h +3 -2
index 5315cf7..1cae633 100644
@@ -43,7 +43,8 @@ struct HIDState {
     int kind;
     int32_t protocol;
     uint8_t idle;
-    int64_t next_idle_clock;
+    bool idle_pending;
+    QEMUTimer *idle_timer;
     HIDEventFunc event;
 };
 
@@ -52,7 +53,7 @@ void hid_reset(HIDState *hs);
 void hid_free(HIDState *hs);
 
 bool hid_has_events(HIDState *hs);
-void hid_set_next_idle(HIDState *hs, int64_t curtime);
+void hid_set_next_idle(HIDState *hs);
 void hid_pointer_activate(HIDState *hs);
 int hid_pointer_poll(HIDState *hs, uint8_t *buf, int len);
 int hid_keyboard_poll(HIDState *hs, uint8_t *buf, int len);
hw/usb/dev-hid.c +3 -5
index 8749128..c452a7e 100644
@@ -501,7 +501,7 @@ static void usb_hid_handle_control(USBDevice *dev, USBPacket *p,
         break;
     case SET_IDLE:
         hs->idle = (uint8_t) (value >> 8);
-        hid_set_next_idle(hs, qemu_get_clock_ns(vm_clock));
+        hid_set_next_idle(hs);
         if (hs->kind == HID_MOUSE || hs->kind == HID_TABLET) {
             hid_pointer_activate(hs);
         }
@@ -523,16 +523,14 @@ static void usb_hid_handle_data(USBDevice *dev, USBPacket *p)
     switch (p->pid) {
     case USB_TOKEN_IN:
         if (p->ep->nr == 1) {
-            int64_t curtime = qemu_get_clock_ns(vm_clock);
             if (hs->kind == HID_MOUSE || hs->kind == HID_TABLET) {
                 hid_pointer_activate(hs);
             }
-            if (!hid_has_events(hs) &&
-                (!hs->idle || hs->next_idle_clock - curtime > 0)) {
+            if (!hid_has_events(hs)) {
                 p->status = USB_RET_NAK;
                 return;
             }
-            hid_set_next_idle(hs, curtime);
+            hid_set_next_idle(hs);
             if (hs->kind == HID_MOUSE || hs->kind == HID_TABLET) {
                 len = hid_pointer_poll(hs, buf, p->iov.size);
             } else if (hs->kind == HID_KEYBOARD) {
Signature · 1 line
1.8.0.1
#26 lore raw

PATCH 18/26 usb: Fix usb_ep_find_packet_by_id

In reply to Hans de Goede

usb_ep_find_packet_by_id mistakenly only checks the first packet and if that is not a match, keeps trying the first packet! This patch fixes this.

---
 hw/usb/core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
hw/usb/core.c +1 -1
index 8e360d3..7ecb2a8 100644
@@ -761,7 +761,7 @@ USBPacket *usb_ep_find_packet_by_id(USBDevice *dev, int pid, int ep,
     struct USBEndpoint *uep = usb_ep_get(dev, pid, ep);
     USBPacket *p;
 
-    while ((p = QTAILQ_FIRST(&uep->queue)) != NULL) {
+    QTAILQ_FOREACH(p, &uep->queue, queue) {
         if (p->id == id) {
             return p;
         }
Signature · 1 line
1.8.0.1
#27 lore raw

PATCH 19/26 usb: Add an usb_device_ep_stopped USBDevice method

In reply to Hans de Goede

Some usb devices (host or network redirection) can benefit from knowing when the guest stops using an endpoint. Redirection may involve submitting packets independently from the guest (in combination with a fifo buffer between the redirection code and the guest), to ensure that buffers of the real usb device are timely emptied. This is done for example for isoc traffic and for interrupt input endpoints. But when the (re)submission of packets is done by the device code, then how does it know when to stop this?

For isoc endpoints this is handled by detecting a set interface (change alt setting) command, which works well for isoc endpoints. But for interrupt endpoints currently the redirection code never stops receiving data from the device, which is less then ideal.

However the controller emulation is aware when a guest looses interest, as then the qh for the endpoint gets unlinked (ehci, ohci, uhci) or the endpoint is explicitly stopped (xhci). This patch adds a new ep_stopped USBDevice method and modifies the hcd code to call this on queue unlink / ep stop.

This makes it possible for the redirection code to properly stop receiving interrupt input (*) data when the guest no longer has interest in it.

*) And in the future also buffered bulk input.

---
 hw/usb.h          |  8 ++++++++
 hw/usb/bus.c      |  8 ++++++++
 hw/usb/hcd-ehci.c | 19 ++++++++++++++++++-
 hw/usb/hcd-ohci.c | 30 ++++++++++++++++++++++++++----
 hw/usb/hcd-uhci.c |  1 +
 hw/usb/hcd-xhci.c |  7 +++++++
 6 files changed, 68 insertions(+), 5 deletions(-)
hw/usb.h +8 -0
index 268e653..21caa54 100644
@@ -307,6 +307,12 @@ typedef struct USBDeviceClass {
      */
     void (*flush_ep_queue)(USBDevice *dev, USBEndpoint *ep);
 
+    /*
+     * Called by the hcd to let the device know the queue for an endpoint
+     * has been unlinked / stopped. Optional may be NULL.
+     */
+    void (*ep_stopped)(USBDevice *dev, USBEndpoint *ep);
+
     const char *product_desc;
     const USBDesc *usb_desc;
 } USBDeviceClass;
@@ -539,6 +545,8 @@ void usb_device_set_interface(USBDevice *dev, int interface,
 
 void usb_device_flush_ep_queue(USBDevice *dev, USBEndpoint *ep);
 
+void usb_device_ep_stopped(USBDevice *dev, USBEndpoint *ep);
+
 const char *usb_device_get_product_desc(USBDevice *dev);
 
 const USBDesc *usb_device_get_usb_desc(USBDevice *dev);
hw/usb/bus.c +8 -0
index 8264c24..da69ec6 100644
@@ -189,6 +189,14 @@ void usb_device_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
     }
 }
 
+void usb_device_ep_stopped(USBDevice *dev, USBEndpoint *ep)
+{
+    USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
+    if (klass->ep_stopped) {
+        klass->ep_stopped(dev, ep);
+    }
+}
+
 static int usb_qdev_init(DeviceState *qdev)
 {
     USBDevice *dev = USB_DEVICE(qdev);
hw/usb/hcd-ehci.c +18 -1
index 36165b0..bf9b2b9 100644
@@ -622,6 +622,17 @@ static EHCIQueue *ehci_alloc_queue(EHCIState *ehci, uint32_t addr, int async)
     return q;
 }
 
+static void ehci_queue_stopped(EHCIQueue *q)
+{
+    int endp  = get_field(q->qh.epchar, QH_EPCHAR_EP);
+
+    if (!q->last_pid || !q->dev) {
+        return;
+    }
+
+    usb_device_ep_stopped(q->dev, usb_ep_get(q->dev, q->last_pid, endp));
+}
+
 static int ehci_cancel_queue(EHCIQueue *q)
 {
     EHCIPacket *p;
@@ -629,7 +640,7 @@ static int ehci_cancel_queue(EHCIQueue *q)
 
     p = QTAILQ_FIRST(&q->packets);
     if (p == NULL) {
-        return 0;
+        goto leave;
     }
 
     trace_usb_ehci_queue_action(q, "cancel");
@@ -637,6 +648,9 @@ static int ehci_cancel_queue(EHCIQueue *q)
         ehci_free_packet(p);
         packets++;
     } while ((p = QTAILQ_FIRST(&q->packets)) != NULL);
+
+leave:
+    ehci_queue_stopped(q);
     return packets;
 }
 
@@ -1386,6 +1400,9 @@ static int ehci_execute(EHCIPacket *p, const char *action)
         return -1;
     }
 
+    if (!ehci_verify_pid(p->queue, &p->qtd)) {
+        ehci_queue_stopped(p->queue); /* Mark the ep in the prev dir stopped */
+    }
     p->pid = ehci_get_pid(&p->qtd);
     p->queue->last_pid = p->pid;
     endp = get_field(p->queue->qh.epchar, QH_EPCHAR_EP);
hw/usb/hcd-ohci.c +26 -4
index e16a2ec..05e183d 100644
@@ -430,6 +430,23 @@ static USBDevice *ohci_find_device(OHCIState *ohci, uint8_t addr)
     return NULL;
 }
 
+static void ohci_stop_endpoints(OHCIState *ohci)
+{
+    USBDevice *dev;
+    int i, j;
+
+    for (i = 0; i < ohci->num_ports; i++) {
+        dev = ohci->rhport[i].port.dev;
+        if (dev && dev->attached) {
+            usb_device_ep_stopped(dev, &dev->ep_ctl);
+            for (j = 0; j < USB_MAX_ENDPOINTS; j++) {
+                usb_device_ep_stopped(dev, &dev->ep_in[j]);
+                usb_device_ep_stopped(dev, &dev->ep_out[j]);
+            }
+        }
+    }
+}
+
 /* Reset the controller */
 static void ohci_reset(void *opaque)
 {
@@ -478,6 +495,7 @@ static void ohci_reset(void *opaque)
         usb_cancel_packet(&ohci->usb_packet);
         ohci->async_td = 0;
     }
+    ohci_stop_endpoints(ohci);
     DPRINTF("usb-ohci: Reset %s\n", ohci->name);
 }
 
@@ -1147,6 +1165,8 @@ static int ohci_service_ed_list(OHCIState *ohci, uint32_t head, int completion)
             if (ohci->async_td && addr == ohci->async_td) {
                 usb_cancel_packet(&ohci->usb_packet);
                 ohci->async_td = 0;
+                usb_device_ep_stopped(ohci->usb_packet.ep->dev,
+                                      ohci->usb_packet.ep);
             }
             continue;
         }
@@ -1227,10 +1247,12 @@ static void ohci_frame_boundary(void *opaque)
     }
 
     /* Cancel all pending packets if either of the lists has been disabled.  */
-    if (ohci->async_td &&
-        ohci->old_ctl & (~ohci->ctl) & (OHCI_CTL_BLE | OHCI_CTL_CLE)) {
-        usb_cancel_packet(&ohci->usb_packet);
-        ohci->async_td = 0;
+    if (ohci->old_ctl & (~ohci->ctl) & (OHCI_CTL_BLE | OHCI_CTL_CLE)) {
+        if (ohci->async_td) {
+            usb_cancel_packet(&ohci->usb_packet);
+            ohci->async_td = 0;
+        }
+        ohci_stop_endpoints(ohci);
     }
     ohci->old_ctl = ohci->ctl;
     ohci_process_lists(ohci, 0);
hw/usb/hcd-uhci.c +1 -0
index fa75a77..9fa0735 100644
@@ -226,6 +226,7 @@ static void uhci_queue_free(UHCIQueue *queue, const char *reason)
         async = QTAILQ_FIRST(&queue->asyncs);
         uhci_async_cancel(async);
     }
+    usb_device_ep_stopped(queue->ep->dev, queue->ep);
 
     trace_usb_uhci_queue_del(queue->token, reason);
     QTAILQ_REMOVE(&s->queues, queue, next);
hw/usb/hcd-xhci.c +7 -0
index efb509e..430028b 100644
@@ -1177,6 +1177,7 @@ static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid,
     XHCISlot *slot;
     XHCIEPContext *epctx;
     int i, xferi, killed = 0;
+    USBEndpoint *ep = NULL;
     assert(slotid >= 1 && slotid <= xhci->numslots);
     assert(epid >= 1 && epid <= 31);
 
@@ -1192,9 +1193,15 @@ static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid,
 
     xferi = epctx->next_xfer;
     for (i = 0; i < TD_QUEUE; i++) {
+        if (epctx->transfers[xferi].packet.ep) {
+            ep = epctx->transfers[xferi].packet.ep;
+        }
         killed += xhci_ep_nuke_one_xfer(&epctx->transfers[xferi]);
         xferi = (xferi + 1) % TD_QUEUE;
     }
+    if (ep) {
+        usb_device_ep_stopped(ep->dev, ep);
+    }
     return killed;
 }
 
Signature · 1 line
1.8.0.1
#28 lore raw

PATCH 20/26 usbredir: Add an usbredir_stop_ep helper function

In reply to Hans de Goede
---
 hw/usb/redirect.c | 41 +++++++++++++++++++----------------------
 1 file changed, 19 insertions(+), 22 deletions(-)
hw/usb/redirect.c +19 -22
index a4d324f..4cf8780 100644
@@ -761,6 +761,23 @@ static void usbredir_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
     }
 }
 
+static void usbredir_stop_ep(USBRedirDevice *dev, int i)
+{
+    uint8_t ep = I2EP(i);
+
+    switch (dev->endpoint[i].type) {
+    case USB_ENDPOINT_XFER_ISOC:
+        usbredir_stop_iso_stream(dev, ep);
+        break;
+    case USB_ENDPOINT_XFER_INT:
+        if (ep & USB_DIR_IN) {
+            usbredir_stop_interrupt_receiving(dev, ep);
+        }
+        break;
+    }
+    usbredir_free_bufpq(dev, ep);
+}
+
 static void usbredir_set_config(USBRedirDevice *dev, USBPacket *p,
                                 int config)
 {
@@ -770,17 +787,7 @@ static void usbredir_set_config(USBRedirDevice *dev, USBPacket *p,
     DPRINTF("set config %d id %"PRIu64"\n", config, p->id);
 
     for (i = 0; i < MAX_ENDPOINTS; i++) {
-        switch (dev->endpoint[i].type) {
-        case USB_ENDPOINT_XFER_ISOC:
-            usbredir_stop_iso_stream(dev, I2EP(i));
-            break;
-        case USB_ENDPOINT_XFER_INT:
-            if (i & 0x10) {
-                usbredir_stop_interrupt_receiving(dev, I2EP(i));
-            }
-            break;
-        }
-        usbredir_free_bufpq(dev, I2EP(i));
+        usbredir_stop_ep(dev, i);
     }
 
     set_config.configuration = config;
@@ -808,17 +815,7 @@ static void usbredir_set_interface(USBRedirDevice *dev, USBPacket *p,
 
     for (i = 0; i < MAX_ENDPOINTS; i++) {
         if (dev->endpoint[i].interface == interface) {
-            switch (dev->endpoint[i].type) {
-            case USB_ENDPOINT_XFER_ISOC:
-                usbredir_stop_iso_stream(dev, I2EP(i));
-                break;
-            case USB_ENDPOINT_XFER_INT:
-                if (i & 0x10) {
-                    usbredir_stop_interrupt_receiving(dev, I2EP(i));
-                }
-                break;
-            }
-            usbredir_free_bufpq(dev, I2EP(i));
+            usbredir_stop_ep(dev, i);
         }
     }
 
Signature · 1 line
1.8.0.1
#29 lore raw

PATCH 21/26 usbredir: Add USBEP2I and I2USBEP helper macros

In reply to Hans de Goede
---
 hw/usb/redirect.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
hw/usb/redirect.c +7 -3
index 4cf8780..7b2cd8c 100644
@@ -43,6 +43,11 @@
 #define NO_INTERFACE_INFO 255 /* Valid interface_count always <= 32 */
 #define EP2I(ep_address) (((ep_address & 0x80) >> 3) | (ep_address & 0x0f))
 #define I2EP(i) (((i & 0x10) << 3) | (i & 0x0f))
+#define USBEP2I(usb_ep) (((usb_ep)->pid == USB_TOKEN_IN) ? \
+                         ((usb_ep)->nr | 0x10) : ((usb_ep)->nr))
+#define I2USBEP(d, i) (usb_ep_get(&(d)->dev, \
+                       ((i) & 0x10) ? USB_TOKEN_IN : USB_TOKEN_OUT, \
+                       (i) & 0x0f))
 
 typedef struct USBRedirDevice USBRedirDevice;
 
@@ -1373,11 +1378,10 @@ static void usbredir_set_pipeline(USBRedirDevice *dev, struct USBEndpoint *uep)
 static void usbredir_setup_usb_eps(USBRedirDevice *dev)
 {
     struct USBEndpoint *usb_ep;
-    int i, pid;
+    int i;
 
     for (i = 0; i < MAX_ENDPOINTS; i++) {
-        pid = (i & 0x10) ? USB_TOKEN_IN : USB_TOKEN_OUT;
-        usb_ep = usb_ep_get(&dev->dev, pid, i & 0x0f);
+        usb_ep = I2USBEP(dev, i);
         usb_ep->type = dev->endpoint[i].type;
         usb_ep->ifnum = dev->endpoint[i].interface;
         usb_ep->max_packet_size = dev->endpoint[i].max_packet_size;
Signature · 1 line
1.8.0.1
#30 lore raw

PATCH 22/26 usbredir: Add ep_stopped USBDevice method

In reply to Hans de Goede

To ensure that interrupt receiving is properly stopped when the guest is no longer interested in an interrupt endpoint.

---
 hw/usb/redirect.c | 9 +++++++++
 1 file changed, 9 insertions(+)
hw/usb/redirect.c +9 -0
index 7b2cd8c..ed2f427 100644
@@ -783,6 +783,14 @@ static void usbredir_stop_ep(USBRedirDevice *dev, int i)
     usbredir_free_bufpq(dev, ep);
 }
 
+static void usbredir_ep_stopped(USBDevice *udev, USBEndpoint *uep)
+{
+    USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
+
+    usbredir_stop_ep(dev, USBEP2I(uep));
+    usbredirparser_do_write(dev->parser);
+}
+
 static void usbredir_set_config(USBRedirDevice *dev, USBPacket *p,
                                 int config)
 {
@@ -2017,6 +2025,7 @@ static void usbredir_class_initfn(ObjectClass *klass, void *data)
     uc->handle_data    = usbredir_handle_data;
     uc->handle_control = usbredir_handle_control;
     uc->flush_ep_queue = usbredir_flush_ep_queue;
+    uc->ep_stopped     = usbredir_ep_stopped;
     dc->vmsd           = &usbredir_vmstate;
     dc->props          = usbredir_properties;
 }
Signature · 1 line
1.8.0.1
#31 lore raw

PATCH 23/26 usbredir: Verify we have 32 bits bulk length cap when redirecting to xhci

In reply to Hans de Goede

The xhci-hcd may submit bulk transfers > 65535 bytes even when not using bulk-in pipeling, so usbredir can only be used in combination with an xhci hcd if the client has the 32 bits bulk length capability.

---
 hw/usb/redirect.c | 2 ++
 1 file changed, 2 insertions(+)
hw/usb/redirect.c +2 -0
index ed2f427..f4715f3 100644
@@ -989,6 +989,8 @@ static void usbredir_do_attach(void *opaque)
         usbredirparser_peer_has_cap(dev->parser,
                                     usb_redir_cap_ep_info_max_packet_size) &&
         usbredirparser_peer_has_cap(dev->parser,
+                                    usb_redir_cap_32bits_bulk_length) &&
+        usbredirparser_peer_has_cap(dev->parser,
                                     usb_redir_cap_64bits_ids))) {
         ERROR("usb-redir-host lacks capabilities needed for use with XHCI\n");
         usbredir_reject_device(dev);
Signature · 1 line
1.8.0.1
#32 lore raw

PATCH 24/26 usbredir: Add usbredir_init_endpoints() helper

In reply to Hans de Goede
---
 hw/usb/redirect.c | 22 +++++++++++++---------
 1 file changed, 13 insertions(+), 9 deletions(-)
hw/usb/redirect.c +13 -9
index f4715f3..b3a96f7 100644
@@ -1086,6 +1086,17 @@ static void usbredir_vm_state_change(void *priv, int running, RunState state)
     }
 }
 
+static void usbredir_init_endpoints(USBRedirDevice *dev)
+{
+    int i;
+
+    usb_ep_init(&dev->dev);
+    memset(dev->endpoint, 0, sizeof(dev->endpoint));
+    for (i = 0; i < MAX_ENDPOINTS; i++) {
+        QTAILQ_INIT(&dev->endpoint[i].bufpq);
+    }
+}
+
 static int usbredir_initfn(USBDevice *udev)
 {
     USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);
@@ -1112,9 +1123,7 @@ static int usbredir_initfn(USBDevice *udev)
 
     packet_id_queue_init(&dev->cancelled, dev, "cancelled");
     packet_id_queue_init(&dev->already_in_flight, dev, "already-in-flight");
-    for (i = 0; i < MAX_ENDPOINTS; i++) {
-        QTAILQ_INIT(&dev->endpoint[i].bufpq);
-    }
+    usbredir_init_endpoints(dev);
 
     /* We'll do the attach once we receive the speed from the usb-host */
     udev->auto_attach = 0;
@@ -1317,7 +1326,6 @@ static void usbredir_device_connect(void *priv,
 static void usbredir_device_disconnect(void *priv)
 {
     USBRedirDevice *dev = priv;
-    int i;
 
     /* Stop any pending attaches */
     qemu_del_timer(dev->attach_timer);
@@ -1334,11 +1342,7 @@ static void usbredir_device_disconnect(void *priv)
 
     /* Reset state so that the next dev connected starts with a clean slate */
     usbredir_cleanup_device_queues(dev);
-    memset(dev->endpoint, 0, sizeof(dev->endpoint));
-    for (i = 0; i < MAX_ENDPOINTS; i++) {
-        QTAILQ_INIT(&dev->endpoint[i].bufpq);
-    }
-    usb_ep_init(&dev->dev);
+    usbredir_init_endpoints(dev);
     dev->interface_info.interface_count = NO_INTERFACE_INFO;
     dev->dev.addr = 0;
     dev->dev.speed = 0;
Signature · 1 line
1.8.0.1
#33 lore raw

PATCH 25/26 usb-redir: Add debugging to bufpq save / restore

In reply to Hans de Goede
---
 hw/usb/redirect.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
hw/usb/redirect.c +11 -3
index b3a96f7..bc36210 100644
@@ -60,6 +60,7 @@ struct buf_packet {
 };
 
 struct endp_data {
+    USBRedirDevice *dev;
     uint8_t type;
     uint8_t interval;
     uint8_t interface; /* bInterfaceNumber this ep belongs to */
@@ -1093,6 +1094,7 @@ static void usbredir_init_endpoints(USBRedirDevice *dev)
     usb_ep_init(&dev->dev);
     memset(dev->endpoint, 0, sizeof(dev->endpoint));
     for (i = 0; i < MAX_ENDPOINTS; i++) {
+        dev->endpoint[i].dev = dev;
         QTAILQ_INIT(&dev->endpoint[i].bufpq);
     }
 }
@@ -1805,22 +1807,26 @@ static const VMStateInfo usbredir_parser_vmstate_info = {
 static void usbredir_put_bufpq(QEMUFile *f, void *priv, size_t unused)
 {
     struct endp_data *endp = priv;
+    USBRedirDevice *dev = endp->dev;
     struct buf_packet *bufp;
-    int remain = endp->bufpq_size;
+    int i = 0;
 
     qemu_put_be32(f, endp->bufpq_size);
     QTAILQ_FOREACH(bufp, &endp->bufpq, next) {
+        DPRINTF("put_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,
+                bufp->len, bufp->status);
         qemu_put_be32(f, bufp->len);
         qemu_put_be32(f, bufp->status);
         qemu_put_buffer(f, bufp->data, bufp->len);
-        remain--;
+        i++;
     }
-    assert(remain == 0);
+    assert(i == endp->bufpq_size);
 }
 
 static int usbredir_get_bufpq(QEMUFile *f, void *priv, size_t unused)
 {
     struct endp_data *endp = priv;
+    USBRedirDevice *dev = endp->dev;
     struct buf_packet *bufp;
     int i;
 
@@ -1832,6 +1838,8 @@ static int usbredir_get_bufpq(QEMUFile *f, void *priv, size_t unused)
         bufp->data = qemu_oom_check(malloc(bufp->len)); /* regular malloc! */
         qemu_get_buffer(f, bufp->data, bufp->len);
         QTAILQ_INSERT_TAIL(&endp->bufpq, bufp, next);
+        DPRINTF("get_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,
+                bufp->len, bufp->status);
     }
     return 0;
 }
Signature · 1 line
1.8.0.1
#34 lore raw

PATCH 26/26 usbredir: Add support for buffered bulk input

In reply to Hans de Goede

Buffered bulk mode is intended for bulk *input* endpoints, where the data is of a streaming nature (not part of a command-response protocol). These endpoints' input buffer may overflow if data is not read quickly enough. So in buffered bulk mode the usb-host takes care of the submitting and re-submitting of bulk transfers.

Buffered bulk mode is necessary for reliable operation with the bulk in endpoints of usb to serial convertors. Unfortunatelty buffered bulk input mode will only work with certain devices, therefor this patch also adds a usb-id table to enable it for devices which need it, while leaving the bulk ep handling for other devices unmodified.

Note that the bumping of the required usbredir from 0.5.3 to 0.6 does not mean that we will now need a newer usbredir release then qemu-1.3, .pc files reporting 0.5.3 have only ever existed in usbredir builds directly from git, so qemu-1.3 needs the 0.6 release too.

---
 configure                    |    2 +-
 hw/usb/redirect-ftdi-ids.h   | 1255 ++++++++++++++++++++++++++++++++++++++++++
 hw/usb/redirect-pl2303-ids.h |  150 +++++
 hw/usb/redirect-usb-ids.h    |  910 ++++++++++++++++++++++++++++++
 hw/usb/redirect.c            |  371 ++++++++++++-
 5 files changed, 2669 insertions(+), 19 deletions(-)
 create mode 100644 hw/usb/redirect-ftdi-ids.h
 create mode 100644 hw/usb/redirect-pl2303-ids.h
 create mode 100644 hw/usb/redirect-usb-ids.h
configure +1 -1
index 994f731..e8ae685 100755
@@ -2802,7 +2802,7 @@ fi
 
 # check for usbredirparser for usb network redirection support
 if test "$usb_redir" != "no" ; then
-    if $pkg_config --atleast-version=0.5.3 libusbredirparser-0.5 >/dev/null 2>&1 ; then
+    if $pkg_config --atleast-version=0.6 libusbredirparser-0.5 >/dev/null 2>&1 ; then
         usb_redir="yes"
         usb_redir_cflags=$($pkg_config --cflags libusbredirparser-0.5 2>/dev/null)
         usb_redir_libs=$($pkg_config --libs libusbredirparser-0.5 2>/dev/null)
hw/usb/redirect-ftdi-ids.h new file +1255 -0

1,255 lines not on this page · raw message

hw/usb/redirect-pl2303-ids.h new file +150 -0

150 lines not on this page · raw message

hw/usb/redirect-usb-ids.h new file +910 -0

910 lines not on this page · raw message

hw/usb/redirect.c +353 -18

588 lines not on this page · raw message

Signature · 1 line
1.8.0.1
#35 lore raw

Re: [Qemu-devel] [PATCH 26/26] usbredir: Add support for buffered bulk input

Hi,

Added patches 1-25 to the usb queue (using v2 of patch 10).

Quoted 3 lines
 hw/usb/redirect-ftdi-ids.h   | 1255 ++++++++++++++++++++++++++++++++++++++++++
 hw/usb/redirect-pl2303-ids.h |  150 +++++
 hw/usb/redirect-usb-ids.h    |  910 ++++++++++++++++++++++++++++++

Where does this come from? Linux kernel I guess? What is the procedure to update them?

I also think this shouldn't be tied to redir, I think it is better to have a hw/usb/quirks.c file where the device id database and helper functions to match devices against the list are living.

cheers,
Gerd

#36 lore raw

Re: [Qemu-devel] [PATCH 26/26] usbredir: Add support for buffered bulk input

Hi,

Quoted 9 lines · Gerd Hoffmann
   Hi,

Added patches 1-25 to the usb queue (using v2 of patch 10).

Quoted 3 lines
  hw/usb/redirect-ftdi-ids.h   | 1255 ++++++++++++++++++++++++++++++++++++++++++
  hw/usb/redirect-pl2303-ids.h |  150 +++++
  hw/usb/redirect-usb-ids.h    |  910 ++++++++++++++++++++++++++++++

Where does this come from? Linux kernel I guess?

These 2 are 1 on 1 copies from the kernel:

hw/usb/redirect-ftdi-ids.h | 1255 ++++++++++++++++++++++++++++++++++++++++++
hw/usb/redirect-pl2303-ids.h | 150 +++++

They contain "boring" stuff like:

#define FTDI_8U232AM_PID 0x6001 /* Similar device to SIO above */ #define FTDI_8U232AM_ALT_PID 0x6006 /* FTDI's alternate PID for above */

Which allows me to easily copy the id tables from the kernel drivers (.c files).

This one:
hw/usb/redirect-usb-ids.h

Contains the usb-id tables copied from the kernel, as stated in the comments:

    /*
     * Silicon Laboratories CP210x USB to RS232 serial adapter ids
     * copied from linux/drivers/usb/serial/cp210x.c
     *
     * Copyright (C) 2005 Craig Shelley ([email protected])
     */
    { USB_DEVICE(0x045B, 0x0053) }, /* Renesas RX610 RX-Stick */
Quoted 1 line

What is the procedure to update them?

I've defined my own version of the USB_DEVICE macro, after that the tables are just 1 on 1 copies from the kernel tree, with
s/<tab>/ /

So updating them can be done by emptying the list and then copying in the new list from the latest kernel, this is an (easy) manual procedure for now.

Quoted 3 lines

I also think this shouldn't be tied to redir, I think it is better to have a hw/usb/quirks.c file where the device id database and helper functions to match devices against the list are living.

Makes sense, one problem I see though is that right now I've 2 id tables, named usbredir_raw_serial_ids and usbredir_ftdi_serial_ids since ftdi based adapters need some extra special handling (a quirk to the quirk).

Once we start working with quirk tables it makes sense to have 1 large table with an extra uint32_t field which contains the actual quirks as bitmask. All perfectly sensible, but this breaks the easy copy and paste syncing of the tables from the Linux kernel ...

So any good ideas for this from you ?

Regards,

Hans

#37 lore raw

Re: [Qemu-devel] [PATCH 26/26] usbredir: Add support for buffered bulk input

Hi,

Quoted 10 lines

These 2 are 1 on 1 copies from the kernel:

hw/usb/redirect-ftdi-ids.h | 1255
++++++++++++++++++++++++++++++++++++++++++
hw/usb/redirect-pl2303-ids.h | 150 +++++

They contain "boring" stuff like:

#define FTDI_8U232AM_PID 0x6001 /* Similar device to SIO above */ #define FTDI_8U232AM_ALT_PID 0x6006 /* FTDI's alternate PID for above */

We have header files copyed from linux already (linux-headers/), did you look into placing them there? Could be it doesn't work that easily due to internal / user interface split of the kernel headers, but worth checking ...

Quoted 5 lines

This one:
hw/usb/redirect-usb-ids.h

Contains the usb-id tables copied from the kernel, as stated in the comments:

Manual process or scripted? If case of the latter we should put the scripts into scripts/ for easy future updates.

Quoted 3 lines

So updating them can be done by emptying the list and then copying in the new list from the latest kernel, this is an (easy) manual procedure for now.

Ah, manual. ok.

Quoted 9 lines
Quoted 3 lines

I also think this shouldn't be tied to redir, I think it is better to have a hw/usb/quirks.c file where the device id database and helper functions to match devices against the list are living.

Makes sense, one problem I see though is that right now I've 2 id tables, named usbredir_raw_serial_ids and usbredir_ftdi_serial_ids since ftdi based adapters need some extra special handling (a quirk to the quirk).

Quoted 6 lines

Once we start working with quirk tables it makes sense to have 1 large table with an extra uint32_t field which contains the actual quirks as bitmask. All perfectly sensible, but this breaks the easy copy and paste syncing of the tables from the Linux kernel ...

So any good ideas for this from you ?

With a scripted update we could add the bitmask easily I guess.

But I think for now we can stick to two lists. Just make sure usb-quirks.c has a sensible interface. Pass in device ids+class, get back a quicks bitmask. Then we can create the bitmask by just checking which list has the device in question.

And when we figure some day this becomes too messy we can switch to a model where where we have the quirk bits next to the devices in the table and just do a lookup, without users noticing the change.

cheers,
Gerd

#38 lore raw

Re: [Qemu-devel] [PATCH 26/26] usbredir: Add support for buffered bulk input

Hi,

Quoted 10 lines · Gerd Hoffmann
   Hi,
Quoted 8 lines

These 2 are 1 on 1 copies from the kernel:

hw/usb/redirect-ftdi-ids.h | 1255
++++++++++++++++++++++++++++++++++++++++++
hw/usb/redirect-pl2303-ids.h | 150 +++++

They contain "boring" stuff like:

Quoted 7 lines
Quoted 2 lines

#define FTDI_8U232AM_PID 0x6001 /* Similar device to SIO above */ #define FTDI_8U232AM_ALT_PID 0x6006 /* FTDI's alternate PID for above */

We have header files copyed from linux already (linux-headers/), did you look into placing them there? Could be it doesn't work that easily due to internal / user interface split of the kernel headers, but worth checking ...

That seem to be only headers from under linux/include. And not from under linux/drivers/usb/.... like I'm doing, so for now I'm just going to leave the headers in hw/usb.

Quoted 34 lines
Quoted 6 lines

This one:
hw/usb/redirect-usb-ids.h

Contains the usb-id tables copied from the kernel, as stated in the comments:

Manual process or scripted? If case of the latter we should put the scripts into scripts/ for easy future updates.

Quoted 3 lines

So updating them can be done by emptying the list and then copying in the new list from the latest kernel, this is an (easy) manual procedure for now.

Ah, manual. ok.

Quoted 9 lines
Quoted 3 lines

I also think this shouldn't be tied to redir, I think it is better to have a hw/usb/quirks.c file where the device id database and helper functions to match devices against the list are living.

Makes sense, one problem I see though is that right now I've 2 id tables, named usbredir_raw_serial_ids and usbredir_ftdi_serial_ids since ftdi based adapters need some extra special handling (a quirk to the quirk).

Quoted 6 lines

Once we start working with quirk tables it makes sense to have 1 large table with an extra uint32_t field which contains the actual quirks as bitmask. All perfectly sensible, but this breaks the easy copy and paste syncing of the tables from the Linux kernel ...

So any good ideas for this from you ?

With a scripted update we could add the bitmask easily I guess.

Quoted 8 lines

But I think for now we can stick to two lists. Just make sure usb-quirks.c has a sensible interface. Pass in device ids+class, get back a quicks bitmask. Then we can create the bitmask by just checking which list has the device in question.

And when we figure some day this becomes too messy we can switch to a model where where we have the quirk bits next to the devices in the table and just do a lookup, without users noticing the change.

Ok, I'll send a new version with this implemented.

Regards,

Hans