From 94f92d54d62c745cb9d4528bb5b340859f343b43 Mon Sep 17 00:00:00 2001 From: Jochen Hoenicke Date: Sun, 10 Jul 2016 14:15:00 +0200 Subject: [PATCH] stmfx07: usb: keep better track of rxbcnt When reading a portion of the packet that is not divisible by 4 and not equal to rxbcnt the count could get off, since 4 bytes are read from the fifo in the last step but rxbcnt was only updated by the number of bytes the caller requested. We fix this by always subtracting four bytes (the number of bytes read from the fifo) when we read a word from the fifo. Care has to be taken in the last step so that rxbcnt doesn't underflow (it is an unsigned number). Note that reading in several small chunks not divisible by 4 doesn't work as the extra bytes read in the last step are always discarded. --- lib/usb/usb_fx07_common.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/usb/usb_fx07_common.c b/lib/usb/usb_fx07_common.c index 8e57f167..2fb856a9 100644 --- a/lib/usb/usb_fx07_common.c +++ b/lib/usb/usb_fx07_common.c @@ -228,15 +228,22 @@ uint16_t stm32fx07_ep_read_packet(usbd_device *usbd_dev, uint8_t addr, uint32_t extra; len = MIN(len, usbd_dev->rxbcnt); - usbd_dev->rxbcnt -= len; volatile uint32_t *fifo = REBASE_FIFO(addr); for (i = len; i >= 4; i -= 4) { *buf32++ = *fifo++; + usbd_dev->rxbcnt -= 4; } if (i) { extra = *fifo++; + /* we read 4 bytes from the fifo, so update rxbcnt */ + if (usbd_dev->rxbcnt < 4) { + /* Be careful not to underflow (rxbcnt is unsigned) */ + usbd_dev->rxbcnt = 0; + } else { + usbd_dev->rxbcnt -= 4; + } memcpy(buf32, &extra, i); }