USB device stack, with KL25Z fixes for USB 3.0 hosts and sleep/resume interrupt handling

Dependents:   frdm_Slider_Keyboard idd_hw2_figlax_PanType idd_hw2_appachu_finger_chording idd_hw3_AngieWangAntonioDeLimaFernandesDanielLim_BladeSymphony ... more

Fork of USBDevice by mbed official

This is an overhauled version of the standard mbed USB device-side driver library, with bug fixes for KL25Z devices. It greatly improves reliability and stability of USB on the KL25Z, especially with devices using multiple endpoints concurrently.

I've had some nagging problems with the base mbed implementation for a long time, manifesting as occasional random disconnects that required rebooting the device. Recently (late 2015), I started implementing a USB device on the KL25Z that used multiple endpoints, and suddenly the nagging, occasional problems turned into frequent and predictable crashes. This forced me to delve into the USB stack and figure out what was really going on. Happily, the frequent crashes made it possible to track down and fix the problems. This new version is working very reliably in my testing - the random disconnects seem completely eradicated, even under very stressful conditions for the device.

Summary

  • Overall stability improvements
  • USB 3.0 host support
  • Stalled endpoint fixes
  • Sleep/resume notifications
  • Smaller memory footprint
  • General code cleanup

Update - 2/15/2016

My recent fixes introduced a new problem that made the initial connection fail most of the time on certain hosts. It's not clear if the common thread was a particular type of motherboard or USB chip set, or a specific version of Windows, or what, but several people ran into it. We tracked the problem down to the "stall" fixes in the earlier updates, which we now know weren't quite the right fixes after all. The latest update (2/15/2016) fixes this. It has new and improved "unstall" handling that so far works well with diverse hosts.

Race conditions and overall stability

The base mbed KL25Z implementation has a lot of problems with "race conditions" - timing problems that can happen when hardware interrupts occur at inopportune moments. The library shares a bunch of static variable data between interrupt handler context and regular application context. This isn't automatically a bad thing, but it does require careful coordination to make sure that the interrupt handler doesn't corrupt data that the other code was in the middle of updating when an interrupt occurs. The base mbed code, though, doesn't do any of the necessary coordination. This makes it kind of amazing that the base code worked at all for anyone, but I guess the interrupt rate is low enough in most applications that the glitch rate was below anyone's threshold to seriously investigate.

This overhaul adds the necessary coordination for the interrupt handlers to protect against these data corruptions. I think it's very solid now, and hopefully entirely free of the numerous race conditions in the old code. It's always hard to be certain that you've fixed every possible bug like this because they strike (effectively) at random, but I'm pretty confident: my test application was reliably able to trigger glitches in the base code in a matter of minutes, but the same application (with the overhauled library) now runs for days on end without dropping the connection.

Stalled endpoint fixes

USB has a standard way of handling communications errors called a "stall", which basically puts the connection into an error mode to let both sides know that they need to reset their internal states and sync up again. The original mbed version of the USB device library doesn't seem to have the necessary code to recover from this condition properly. The KL25Z hardware does some of the work, but it also seems to require the software to take some steps to "un-stall" the connection. (I keep saying "seems to" because the hardware reference material is very sketchy about all of this. Most of what I've figured out is from observing the device in action with a Windows host.) This new version adds code to do the necessary re-syncing and get the connection going again, automatically, and transparently to the user.

USB 3.0 Hosts

The original mbed code sometimes didn't work when connecting to hosts with USB 3.0 ports. This didn't affect every host, but it affected many of them. The common element seemed to be the Intel Haswell chip set on the host, but there may be other chip sets affected as well. In any case, the problem affected many PCs from the Windows 7 and 8 generation, as well as many Macs. It was possible to work around the problem by avoiding USB 3.0 ports - you could use a USB 2 port on the host, or plug a USB 2 hub between the host and device. But I wanted to just fix the problem and eliminate the need for such workarounds. This modified version of the library has such a fix, which so far has worked for everyone who's tried.

Sleep/resume notifications

This modified version also contains an innocuous change to the KL25Z USB HAL code to handle sleep and resume interrupts with calls to suspendStateChanged(). The original KL25Z code omitted these calls (and in fact didn't even enable the interrupts), but I think this was an unintentional oversight - the notifier function is part of the generic API, and other supported boards all implement it. I use this feature in my own application so that I can distinguish sleep mode from actual disconnects and handle the two conditions correctly.

Smaller memory footprint

The base mbed version of the code allocates twice as much memory for USB buffers as it really needed to. It looks like the original developers intended to implement the KL25Z USB hardware's built-in double-buffering mechanism, but they ultimately abandoned that effort. But they left in the double memory allocation. This version removes that and allocates only what's actually needed. The USB buffers aren't that big (128 bytes per endpoint), so this doesn't save a ton of memory, but even a little memory is pretty precious on this machine given that it only has 16K.

(I did look into adding the double-buffering support that the original developers abandoned, but after some experimentation I decided they were right to skip it. It just doesn't seem to mesh well with the design of the rest of the mbed USB code. I think it would take a major rewrite to make it work, and it doesn't seem worth the effort given that most applications don't need it - it would only benefit applications that are moving so much data through USB that they're pushing the limits of the CPU. And even for those, I think it would be a lot simpler to build a purely software-based buffer rotation mechanism.)

General code cleanup

The KL25Z HAL code in this version has greatly expanded commentary and a lot of general cleanup. Some of the hardware constants were given the wrong symbolic names (e.g., EVEN and ODD were reversed), and many were just missing (written as hard-coded numbers without explanation). I fixed the misnomers and added symbolic names for formerly anonymous numbers. Hopefully the next person who has to overhaul this code will at least have an easier time understanding what I thought I was doing!

USBDevice/USBDevice.cpp

Committer:
mjr
Date:
2017-03-17
Revision:
54:2e181d51495a
Parent:
53:c8110529c24b

File content as of revision 54:2e181d51495a:

/* Copyright (c) 2010-2011 mbed.org, MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include "stdint.h"

#include "USBEndpoints.h"
#include "USBDevice.h"
#include "USBDescriptor.h"

//#define DEBUG_WITH_PRINTF
#ifdef DEBUG_WITH_PRINTF
// debug printf; does a regular printf() in debug mode, nothing in
// normal mode.  Note that many of our routines are called in ISR
// context, so printf should really never be used here.  But in
// practice we can get away with it enough that it can be helpful
// as a limited debugging tool.
#define printd(fmt, ...)  printf(fmt, __VA_ARGS__)
#else
#define printd(fmt, ...)
#endif

// Makeshift HAL debug instrumentation.  This is a safer and better
// alternative to printf() that gathers event information in a 
// circular buffer for later useoutside of interrupt context, such 
// as printf() display at intervals in the main program loop.  
//
// Timing is critical to USB, so debug instrumentation is inherently 
// problematic in that it can affect the timing and thereby change 
// the behavior of what we're trying to debug.  Small timing changes
// can create new errors that wouldn't be there otherwise, or even
// accidentally fix the bug were trying to find (e.g., by changing
// the timing enough to avoid a race condition).  To minimize these 
// effects, we use a small buffer and very terse event codes - 
// generally one character per event.  That makes for a cryptic 
// debug log, but it results in almost zero timing effects, allowing
// us to see a more faithful version of the subject program.
//
// NB: Implemented only for KL25Z.
//#define DEBUG_WITH_EVENTS
#ifdef DEBUG_WITH_EVENTS
extern void HAL_DEBUG_EVENT(char c);
extern void HAL_DEBUG_EVENT(char a, char b);
extern void HAL_DEBUG_EVENT(char a, char b, char c);
extern void HAL_DEBUG_EVENT(const char *s);
extern void HAL_DEBUG_EVENTF(const char *f, ...);
#else
#define HAL_DEBUG_EVENT(...)
#define HAL_DEBUG_EVENTF(...)
#endif

/* Device status */
#define DEVICE_STATUS_SELF_POWERED  (1U<<0)
#define DEVICE_STATUS_REMOTE_WAKEUP (1U<<1)

/* Endpoint status */
#define ENDPOINT_STATUS_HALT        (1U<<0)

/* Standard feature selectors */
#define DEVICE_REMOTE_WAKEUP        (1)
#define ENDPOINT_HALT               (0)

/* Macro to convert wIndex endpoint number to physical endpoint number */
#define WINDEX_TO_PHYSICAL(endpoint) (((endpoint & 0x0f) << 1) + \
    ((endpoint & 0x80) ? 1 : 0))

bool USBDevice::requestGetDescriptor(void)
{
    const uint8_t *p;
    bool success = false;
    printd("get descr: type: %d\r\n", DESCRIPTOR_TYPE(transfer.setup.wValue));
    switch (DESCRIPTOR_TYPE(transfer.setup.wValue))
    {
    case DEVICE_DESCRIPTOR:
        if ((p = deviceDesc()) != NULL)
        {
            if (p[0] == DEVICE_DESCRIPTOR_LENGTH && p[1] == DEVICE_DESCRIPTOR)
            {
                printd("device descr\r\n");
                transfer.remaining = DEVICE_DESCRIPTOR_LENGTH;
                transfer.ptr = p;
                transfer.direction = DEVICE_TO_HOST;
                success = true;
            }
        }
        break;

    case CONFIGURATION_DESCRIPTOR:
        if ((p = configurationDesc()) != NULL)
        {
            if (p[0] == CONFIGURATION_DESCRIPTOR_LENGTH && p[1] == CONFIGURATION_DESCRIPTOR)
            {
                printd("conf descr request\r\n");

                /* Get wTotalLength */
                transfer.remaining = p[2] | (p[3] << 8);
                transfer.ptr = p;
                transfer.direction = DEVICE_TO_HOST;
                success = true;
            }
        }
        break;

    case STRING_DESCRIPTOR:
        printd("str descriptor\r\n");
        switch (DESCRIPTOR_INDEX(transfer.setup.wValue))
        {
        case STRING_OFFSET_LANGID:
            printd("1\r\n");
            transfer.ptr = stringLangidDesc();
            transfer.remaining = transfer.ptr[0];
            transfer.direction = DEVICE_TO_HOST;
            success = true;
            break;

        case STRING_OFFSET_IMANUFACTURER:
            printd("2\r\n");
            transfer.ptr = stringImanufacturerDesc();
            transfer.remaining = transfer.ptr[0];
            transfer.direction = DEVICE_TO_HOST;
            success = true;
            break;

        case STRING_OFFSET_IPRODUCT:
            printd("3\r\n");
            transfer.ptr = stringIproductDesc();
            transfer.remaining = transfer.ptr[0];
            transfer.direction = DEVICE_TO_HOST;
            success = true;
            break;

        case STRING_OFFSET_ISERIAL:
            printd("4\r\n");
            transfer.ptr = stringIserialDesc();
            transfer.remaining = transfer.ptr[0];
            transfer.direction = DEVICE_TO_HOST;
            success = true;
            break;

        case STRING_OFFSET_ICONFIGURATION:
            printd("5\r\n");
            transfer.ptr = stringIConfigurationDesc();
            transfer.remaining = transfer.ptr[0];
            transfer.direction = DEVICE_TO_HOST;
            success = true;
            break;

        case STRING_OFFSET_IINTERFACE:
            printd("6\r\n");
            transfer.ptr = stringIinterfaceDesc();
            transfer.remaining = transfer.ptr[0];
            transfer.direction = DEVICE_TO_HOST;
            success = true;
            break;
        }
        break;
        
    case INTERFACE_DESCRIPTOR:
        printd("interface descr\r\n");
        break;

    case ENDPOINT_DESCRIPTOR:
        /* TODO: Support is optional, not implemented here */
        printd("endpoint descr\r\n");
        break;

    default:
        printd("ERROR - unknown descriptor type in GET DESCRIPTOR\r\n");
        break;
    }

    return success;
}

void USBDevice::decodeSetupPacket(uint8_t *data, SETUP_PACKET *packet)
{
    /* Fill in the elements of a SETUP_PACKET structure from raw data */
    packet->bmRequestType.dataTransferDirection = (data[0] & 0x80) >> 7;
    packet->bmRequestType.Type = (data[0] & 0x60) >> 5;
    packet->bmRequestType.Recipient = data[0] & 0x1f;
    packet->bRequest = data[1];
    packet->wValue = (data[2] | (uint16_t)data[3] << 8);
    packet->wIndex = (data[4] | (uint16_t)data[5] << 8);
    packet->wLength = (data[6] | (uint16_t)data[7] << 8);
}


bool USBDevice::controlOut(void)
{
    /* Control transfer data OUT stage */
    uint8_t buffer[MAX_PACKET_SIZE_EP0];
    uint32_t packetSize;

    /* Check we should be transferring data OUT */
    if (transfer.direction != HOST_TO_DEVICE)
    {
#if defined(TARGET_KL25Z) | defined(TARGET_KL46Z) | defined(TARGET_K20D5M) | defined(TARGET_K64F)
        /*
         * We seem to have a pending device-to-host transfer.  The host must have
         * sent a new control request without waiting for us to finish processing
         * the previous one.  This appears to happen when we're connected to certain 
         * USB 3.0 host chip sets.  Do a zero-length send and return failure to tell 
         * the host we're not ready for the new request.  That'll make it resend.
         */
        EP0write(NULL, 0);
                  
        /* execute our pending transfer */
        controlIn();

        /* indicate failure */
        return false;
 #else
        /* for other platforms, count on the HAL to handle this case */
        return false;
 #endif
    }

    /* Read from endpoint */
    packetSize = EP0getReadResult(buffer);

    /* Check if transfer size is valid */
    if (packetSize > transfer.remaining)
    {
        /* Too big */
        return false;
    }

    /* Update transfer */
    transfer.ptr += packetSize;
    transfer.remaining -= packetSize;

    /* Check if transfer has completed */
    if (transfer.remaining == 0)
    {
        /* Transfer completed */
        if (transfer.notify)
        {
            /* Notify class layer. */
            USBCallback_requestCompleted(buffer, packetSize);
            transfer.notify = false;
        }

        /* Status stage */
        EP0write(NULL, 0);
    }
    else
    {
        EP0read();
    }

    return true;
}

bool USBDevice::controlIn(void)
{
    /* Control transfer data IN stage */
    uint32_t packetSize;

    /* Check if transfer has completed (status stage transactions */
    /* also have transfer.remaining == 0) */
    if (transfer.remaining == 0)
    {
        if (transfer.zlp)
        {
            /* Send zero length packet */
            EP0write(NULL, 0);
            transfer.zlp = false;
        }

        /* Transfer completed */
        if (transfer.notify)
        {
            /* Notify class layer. */
            USBCallback_requestCompleted(NULL, 0);
            transfer.notify = false;
        }

        EP0read();
        EP0readStage();

        /* Completed */
        return true;
    }

    /* Check we should be transferring data IN */
    if (transfer.direction != DEVICE_TO_HOST)
    {
        return false;
    }

    packetSize = transfer.remaining;

    if (packetSize > MAX_PACKET_SIZE_EP0)
    {
        packetSize = MAX_PACKET_SIZE_EP0;
    }

    /* Write to endpoint */
    EP0write(transfer.ptr, packetSize);

    /* Update transfer */
    transfer.ptr += packetSize;
    transfer.remaining -= packetSize;
    
    /* success */
    return true;
}

bool USBDevice::requestSetAddress(void)
{
    /* Set the device address */
    setAddress(transfer.setup.wValue);

    if (transfer.setup.wValue == 0)
    {
        setDeviceState(DEFAULT);
    }
    else
    {
        setDeviceState(ADDRESS);
    }

    return true;
}

bool USBDevice::requestSetConfiguration(void)
{
    /* Set the device configuration */
    device.configuration = transfer.setup.wValue;
    if (device.configuration == 0)
    {
        /* Not configured */
        unconfigureDevice();
        setDeviceState(ADDRESS);
    }
    else
    {
        if (USBCallback_setConfiguration(device.configuration))
        {
            /* Valid configuration */
            configureDevice();
            setDeviceState(CONFIGURED);
        }
        else
        {
            return false;
        }
    }

    return true;
}

bool USBDevice::requestGetConfiguration(void)
{
    /* Send the device configuration */
    transfer.ptr = &device.configuration;
    transfer.remaining = sizeof(device.configuration);
    transfer.direction = DEVICE_TO_HOST;
    return true;
}

/* Return the currently selected alternate for an interface */
bool USBDevice::requestGetInterface(void)
{
    /* we must be configured first */
    if (device.state != CONFIGURED)
        return false;
        
    /* ask the callback for an alternate; use 0 by default */
    static uint8_t alt;
    if (!USBCallback_getInterface(transfer.setup.wIndex, &alt))
        alt = 0;
        
    /* return the alternate */
    transfer.ptr = &alt;
    transfer.remaining = sizeof(alt);
    transfer.direction = DEVICE_TO_HOST;
    return true;
}

/* Set the current alternate for an interface */
bool USBDevice::requestSetInterface(void)
{
    /* handle it through the callback */
    return USBCallback_setInterface(transfer.setup.wIndex, transfer.setup.wValue);
}

bool USBDevice::requestSetFeature()
{
    bool success = false;

    if (device.state != CONFIGURED)
    {
        /* Endpoint or interface must be zero */
        if (transfer.setup.wIndex != 0)
        {
            return false;
        }
    }

    switch (transfer.setup.bmRequestType.Recipient)
    {
        case DEVICE_RECIPIENT:
            /* TODO: Remote wakeup feature not supported */
            break;
        case ENDPOINT_RECIPIENT:
            if (transfer.setup.wValue == ENDPOINT_HALT)
            {
                /* TODO: We should check that the endpoint number is valid */
                stallEndpoint(
                    WINDEX_TO_PHYSICAL(transfer.setup.wIndex));
                success = true;
            }
            break;
        default:
            break;
    }

    return success;
}

bool USBDevice::requestClearFeature()
{
    bool success = false;

    if (device.state != CONFIGURED)
    {
        /* Endpoint or interface must be zero */
        if (transfer.setup.wIndex != 0)
        {
            return false;
        }
    }

    switch (transfer.setup.bmRequestType.Recipient)
    {
        case DEVICE_RECIPIENT:
            /* TODO: Remote wakeup feature not supported */
            break;
        case ENDPOINT_RECIPIENT:
            /* TODO: We should check that the endpoint number is valid */
            if (transfer.setup.wValue == ENDPOINT_HALT)
            {
                unstallEndpoint( WINDEX_TO_PHYSICAL(transfer.setup.wIndex));
                success = true;
            }
            break;
        default:
            break;
    }

    return success;
}

bool USBDevice::requestGetStatus(void)
{
    static uint16_t status;
    bool success = false;

    if (device.state != CONFIGURED)
    {
        /* Endpoint or interface must be zero */
        if (transfer.setup.wIndex != 0)
            return false;
    }

    switch (transfer.setup.bmRequestType.Recipient)
    {
    case DEVICE_RECIPIENT:
        /* TODO: Currently only supports self powered devices */
        status = DEVICE_STATUS_SELF_POWERED;
        success = true;
        break;

    case INTERFACE_RECIPIENT:
        status = 0;
        success = true;
        break;

    case ENDPOINT_RECIPIENT:
        /* TODO: We should check that the endpoint number is valid */
        if (getEndpointStallState(WINDEX_TO_PHYSICAL(transfer.setup.wIndex)))
        {
            status = ENDPOINT_STATUS_HALT;
        }
        else
        {
            status = 0;
        }
        success = true;
        break;
        
    default:
        break;
    }

    if (success)
    {
        /* Send the status */
        transfer.ptr = (uint8_t *)&status; /* Assumes little endian */
        transfer.remaining = sizeof(status);
        transfer.direction = DEVICE_TO_HOST;
    }

    return success;
}

bool USBDevice::requestSetup(void)
{
    bool success = false;

    /* Process standard requests */
    if ((transfer.setup.bmRequestType.Type == STANDARD_TYPE))
    {
        switch (transfer.setup.bRequest)
        {
        case GET_STATUS:
            success = requestGetStatus();
            break;
            
        case CLEAR_FEATURE:
            success = requestClearFeature();
            break;
            
        case SET_FEATURE:
            success = requestSetFeature();
            break;
            
        case SET_ADDRESS:
            success = requestSetAddress();
            break;
            
        case GET_DESCRIPTOR:
            success = requestGetDescriptor();
            break;
            
        case SET_DESCRIPTOR:
            /* TODO: Support is optional, not implemented here */
            success = false;
            break;
            
        case GET_CONFIGURATION:
            success = requestGetConfiguration();
            break;
            
        case SET_CONFIGURATION:
            success = requestSetConfiguration();
            break;
            
        case GET_INTERFACE:
            success = requestGetInterface();
            break;
            
        case SET_INTERFACE:
            success = requestSetInterface();
            break;
            
        default:
            break;
        }
    }

    return success;
}

bool USBDevice::controlSetup(void)
{
    bool success = false;

    /* Control transfer setup stage */
    uint8_t buffer[MAX_PACKET_SIZE_EP0];

    EP0setup(buffer);

    /* Initialise control transfer state */
    decodeSetupPacket(buffer, &transfer.setup);
    transfer.ptr = NULL;
    transfer.remaining = 0;
    transfer.direction = HOST_TO_DEVICE;
    transfer.zlp = false;
    transfer.notify = false;

    printd("dataTransferDirection: %d\r\nType: %d\r\nRecipient: %d\r\nbRequest: %d\r\nwValue: %d\r\nwIndex: %d\r\nwLength: %d\r\n",
        transfer.setup.bmRequestType.dataTransferDirection,
        transfer.setup.bmRequestType.Type,
        transfer.setup.bmRequestType.Recipient,
        transfer.setup.bRequest,
        transfer.setup.wValue,
        transfer.setup.wIndex,
        transfer.setup.wLength);

    /* Class / vendor specific */
    success = USBCallback_request();

    if (!success)
    {
        /* Standard requests */
        if (!requestSetup())
        {
            printd("requestSetup() failed: type=%d, req=%d\r\n", (int)transfer.setup.bmRequestType.Type, (int)transfer.setup.bRequest);
            return false;
        }
    }

    /* Check transfer size and direction */
    if (transfer.setup.wLength > 0)
    {
        if (transfer.setup.bmRequestType.dataTransferDirection == DEVICE_TO_HOST)
        {
            /* IN data stage is required */
            if (transfer.direction != DEVICE_TO_HOST)
            {
                printd("controlSetup transfer direction wrong 1\r\n");
                return false;
            }

            /* Transfer must be less than or equal to the size */
            /* requested by the host */
            if (transfer.remaining > transfer.setup.wLength)
                transfer.remaining = transfer.setup.wLength;
        }
        else
        {

            /* OUT data stage is required */
            if (transfer.direction != HOST_TO_DEVICE)
            {
                printd("controlSetup transfer direction wrong 2: type=%d, req=%d\r\n", (int)transfer.setup.bmRequestType.Type, (int)transfer.setup.bRequest);
                return false;
            }

            /* Transfer must be equal to the size requested by the host */
            if (transfer.remaining != transfer.setup.wLength)
            {
                printd("controlSetup remaining length wrong: return len=%d, type=%d, req=%d, wvalue=%d, windex=%x, wlength=%d\r\n", 
                    transfer.remaining, transfer.setup.bmRequestType.Type, transfer.setup.bRequest, transfer.setup.wValue, transfer.setup.wIndex, transfer.setup.wLength);
                return false;
            }
        }
    }
    else
    {
        /* No data stage; transfer size must be zero */
        if (transfer.remaining != 0)
        {
            printd("controlSetup remaining length must be zero: return len=%d, type=%d, req=%d, wvalue=%d, windex=%x, wlength=%d\r\n", 
               (int)transfer.remaining, (int)transfer.setup.bmRequestType.Type, (int)transfer.setup.bRequest, (int)transfer.setup.wValue, (int)transfer.setup.wIndex, (int)transfer.setup.wLength);
            return false;
        }
    }

    /* Data or status stage if applicable */
    if (transfer.setup.wLength > 0)
    {
        if (transfer.setup.bmRequestType.dataTransferDirection == DEVICE_TO_HOST)
        {
            /* Check if we'll need to send a zero length packet at */
            /* the end of this transfer */
            if (transfer.setup.wLength >= transfer.remaining)
            {
                /* Device wishes to transfer less than host requested */
                if ((transfer.remaining % MAX_PACKET_SIZE_EP0) == 0)
                {
                    /* Transfer is a multiple of EP0 max packet size */
                    transfer.zlp = true;
                }
            }

            /* IN stage */
            controlIn();
        }
        else
        {
            /* OUT stage */
            EP0read();
        }
    }
    else
    {
        /* Status stage */
        EP0write(NULL, 0);
    }

    return true;
}

void USBDevice::busReset(void)
{
    // reset the device state
    memset(&device, 0, sizeof(device));
    setDeviceState(DEFAULT);
    device.configuration = 0;
    device.suspended = false;

    // reset the transfer state
    memset(&transfer, 0, sizeof(transfer));
    
    /* Call class / vendor specific busReset function */
    USBCallback_busReset();
}

void USBDevice::EP0setupCallback(void)
{
    /* Endpoint 0 setup event */
    if (!controlSetup())
    {
        /* Protocol stall */
        EP0stall();
    }
}

void USBDevice::EP0out(void)
{
    /* Endpoint 0 OUT data event */
    if (!controlOut())
    {
        /* Protocol stall; this will stall both endpoints */
        EP0stall();
    }
}

void USBDevice::EP0in(void)
{
    /* Endpoint 0 IN data event */
    printd("EP0IN\r\n");
    if (!controlIn())
    {
        /* Protocol stall; this will stall both endpoints */
        EP0stall();
    }
}

bool USBDevice::configured(void)
{
    /* Returns true if device is in the CONFIGURED state */
    return (device.state == CONFIGURED);
}

void USBDevice::connect(bool blocking)
{
    /* Connect device */
    USBHAL::connect();

    if (blocking) {
        /* Block until configured */
        while (!configured()) { }
    }
}

void USBDevice::disconnect(void)
{
    /* Disconnect device */
    USBHAL::disconnect();
    
    /* Set initial device state */
    setDeviceState(POWERED);
    device.configuration = 0;
    device.suspended = false;
}

CONTROL_TRANSFER * USBDevice::getTransferPtr(void)
{
    return &transfer;
}

bool USBDevice::addEndpoint(uint8_t endpoint, uint32_t maxPacket)
{
    return realiseEndpoint(endpoint, maxPacket, 0);
}

bool USBDevice::addRateFeedbackEndpoint(uint8_t endpoint, uint32_t maxPacket)
{
    /* For interrupt endpoints only */
    return realiseEndpoint(endpoint, maxPacket, RATE_FEEDBACK_MODE);
}

/*
 *  Find a descriptor within the list of descriptors following a 
 *  configuration descriptor
 */
const uint8_t *USBDevice::findDescriptor(uint8_t descriptorType, int idx)
{
    /* get the start of the configuration descriptor */
    const uint8_t *ptr = configurationDesc();
    if (ptr == NULL)
        return NULL;

    /* make sure it matches the expected length for a config descriptor */
    if (ptr[0] != CONFIGURATION_DESCRIPTOR_LENGTH 
        || ptr[1] != CONFIGURATION_DESCRIPTOR)
        return NULL;

    /* figure the total length of the descriptor */
    uint16_t wTotalLength = ptr[2] | (ptr[3] << 8);
    const uint8_t *endPtr = ptr + wTotalLength;

    /* Check there are some more descriptors to follow */
    /* (+2 is for bLength and bDescriptorType of next descriptor) */
    if (wTotalLength <= (CONFIGURATION_DESCRIPTOR_LENGTH + 2))
        return NULL;

    /* Start at first descriptor after the configuration descriptor */
    ptr += CONFIGURATION_DESCRIPTOR_LENGTH;

    /* Scan until we find the idx'th descriptor of the specified type */
    do {
        if (ptr[1] /* bDescriptorType */ == descriptorType)
        {
            // Found - if the index has reached zero, it's the one we're
            // looking for; if not, just decrement the index and keep looking.
            if (idx == 0)
                return ptr;
            else
                --idx;
        }

        /* Skip to next descriptor */
        ptr += ptr[0]; /* bLength */
    } while (ptr < endPtr);

    /* Reached end of the descriptors - not found */
    return NULL;
}


void USBDevice::connectStateChanged(unsigned int connected)
{
}

void USBDevice::suspendStateChanged(unsigned int suspended)
{
}

void USBDevice::sleepStateChanged(unsigned int sleep)
{
}


USBDevice::USBDevice(uint16_t vendor_id, uint16_t product_id, uint16_t product_release){
    VENDOR_ID = vendor_id;
    PRODUCT_ID = product_id;
    PRODUCT_RELEASE = product_release;

    /* Set initial device state */
    setDeviceState(POWERED);
    device.configuration = 0;
    device.suspended = false;
};


bool USBDevice::readStart(uint8_t endpoint, uint32_t maxSize)
{
    return endpointRead(endpoint, maxSize) == EP_PENDING;
}


bool USBDevice::write(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_t maxSize)
{
    EP_STATUS result;

    if (size > maxSize)
    {
        return false;
    }


    if(!configured()) {
        return false;
    }

    /* Send report */
    result = endpointWrite(endpoint, buffer, size);

    if (result != EP_PENDING)
    {
        return false;
    }

    /* Wait for completion */
    do {
        result = endpointWriteResult(endpoint);
    } while ((result == EP_PENDING) && configured());

    return (result == EP_COMPLETED);
}


bool USBDevice::writeNB(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_t maxSize)
{
    EP_STATUS result;

    if (size > maxSize)
    {
        return false;
    }

    if(!configured()) {
        return false;
    }

    /* Send report */
    result = endpointWrite(endpoint, buffer, size);

    if (result != EP_PENDING)
    {
        return false;
    }

    result = endpointWriteResult(endpoint);

    return (result == EP_COMPLETED);
}

bool USBDevice::writeTO(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_t maxSize, int timeout_ms)
{
    EP_STATUS result;

    if (size > maxSize)
    {
        return false;
    }

    if(!configured()) {
        return false;
    }

    /* Send report */
    result = endpointWrite(endpoint, buffer, size);
    
    if (result != EP_PENDING)
    {
        return false;
    }
    
    /* set up a timer for monitoring the timeout period */
    Timer t;
    t.start();

    /* Wait for completion or timeout */
    do {
        result = endpointWriteResult(endpoint);
    } while ((result == EP_PENDING) && configured() && t.read_ms() < timeout_ms);

    return (result == EP_COMPLETED);
}

bool USBDevice::readEP(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize)
{
    EP_STATUS result;

    if(!configured()) {
        return false;
    }

    /* Wait for completion */
    do {
        result = endpointReadResult(endpoint, buffer, size);
    } while ((result == EP_PENDING) && configured());

    return (result == EP_COMPLETED);
}


bool USBDevice::readEP_NB(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize)
{
    EP_STATUS result;

    if(!configured()) {
        return false;
    }

    result = endpointReadResult(endpoint, buffer, size);

    return (result == EP_COMPLETED);
}



const uint8_t *USBDevice::deviceDesc() {
    static const uint8_t deviceDescriptor[] = {
        DEVICE_DESCRIPTOR_LENGTH,       /* bLength */
        DEVICE_DESCRIPTOR,              /* bDescriptorType */
        LSB(USB_VERSION_2_0),           /* bcdUSB (LSB) */
        MSB(USB_VERSION_2_0),           /* bcdUSB (MSB) */
        0x00,                           /* bDeviceClass */
        0x00,                           /* bDeviceSubClass */
        0x00,                           /* bDeviceprotocol */
        MAX_PACKET_SIZE_EP0,            /* bMaxPacketSize0 */
        (uint8_t)(LSB(VENDOR_ID)),                 /* idVendor (LSB) */
        (uint8_t)(MSB(VENDOR_ID)),                 /* idVendor (MSB) */
        (uint8_t)(LSB(PRODUCT_ID)),                /* idProduct (LSB) */
        (uint8_t)(MSB(PRODUCT_ID)),                /* idProduct (MSB) */
        (uint8_t)(LSB(PRODUCT_RELEASE)),           /* bcdDevice (LSB) */
        (uint8_t)(MSB(PRODUCT_RELEASE)),           /* bcdDevice (MSB) */
        STRING_OFFSET_IMANUFACTURER,    /* iManufacturer */
        STRING_OFFSET_IPRODUCT,         /* iProduct */
        STRING_OFFSET_ISERIAL,          /* iSerialNumber */
        0x01                            /* bNumConfigurations */
    };
    return deviceDescriptor;
}

const uint8_t *USBDevice::stringLangidDesc() {
    static const uint8_t stringLangidDescriptor[] = {
        0x04,               /*bLength*/
        STRING_DESCRIPTOR,  /*bDescriptorType 0x03*/
        0x09,0x04,          /*bString Lang ID - 0x0409 - English*/
    };
    return stringLangidDescriptor;
}

const uint8_t *USBDevice::stringImanufacturerDesc() {
    static const uint8_t stringImanufacturerDescriptor[] = {
        0x12,                                            /*bLength*/
        STRING_DESCRIPTOR,                               /*bDescriptorType 0x03*/
        'm',0,'b',0,'e',0,'d',0,'.',0,'o',0,'r',0,'g',0, /*bString iManufacturer - mbed.org*/
    };
    return stringImanufacturerDescriptor;
}

const uint8_t *USBDevice::stringIserialDesc() {
    static const uint8_t stringIserialDescriptor[] = {
        0x16,                                                           /*bLength*/
        STRING_DESCRIPTOR,                                              /*bDescriptorType 0x03*/
        '0',0,'1',0,'2',0,'3',0,'4',0,'5',0,'6',0,'7',0,'8',0,'9',0,    /*bString iSerial - 0123456789*/
    };
    return stringIserialDescriptor;
}

const uint8_t *USBDevice::stringIConfigurationDesc() {
    static const uint8_t stringIconfigurationDescriptor[] = {
        0x06,               /*bLength*/
        STRING_DESCRIPTOR,  /*bDescriptorType 0x03*/
        '0',0,'1',0,        /*bString iConfiguration - 01*/
    };
    return stringIconfigurationDescriptor;
}

const uint8_t *USBDevice::stringIinterfaceDesc() {
    static const uint8_t stringIinterfaceDescriptor[] = {
        0x08,               /*bLength*/
        STRING_DESCRIPTOR,  /*bDescriptorType 0x03*/
        'U',0,'S',0,'B',0,  /*bString iInterface - USB*/
    };
    return stringIinterfaceDescriptor;
}

const uint8_t *USBDevice::stringIproductDesc() {
    static const uint8_t stringIproductDescriptor[] = {
        0x16,                                                       /*bLength*/
        STRING_DESCRIPTOR,                                          /*bDescriptorType 0x03*/
        'U',0,'S',0,'B',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0 /*bString iProduct - USB DEVICE*/
    };
    return stringIproductDescriptor;
}