added USB host

Dependencies:   FATFileSystem mbed-rtos

Dependents:   app-board-Speaker

Fork of USBHost by mbed official

USBHostMSD/USBHostMSD.cpp

Committer:
mbed_official
Date:
2013-03-06
Revision:
0:a554658735bf
Child:
4:b320d68e98e7

File content as of revision 0:a554658735bf:

/* Copyright (c) 2010-2012 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 "USBHostMSD.h"

#if USBHOST_MSD

#include "dbg.h"

#define CBW_SIGNATURE   0x43425355
#define CSW_SIGNATURE   0x53425355

#define DEVICE_TO_HOST  0x80
#define HOST_TO_DEVICE  0x00

#define GET_MAX_LUN     (0xFE)

USBHostMSD::USBHostMSD(const char * rootdir) : FATFileSystem(rootdir)
{
    host = USBHost::getHostInst();
    init();
}

void USBHostMSD::init() {
    dev_connected = false;
    dev = NULL;
    bulk_in = NULL;
    bulk_out = NULL;
    dev_connected = false;
    blockSize = 0;
    blockCount = 0;
    msd_intf = -1;
    msd_device_found = false;
    disk_init = false;
    dev_connected = false;
}


bool USBHostMSD::connected()
{
    return dev_connected;
}

bool USBHostMSD::connect()
{
    U8 i;

    if (dev_connected) {
        return true;
    }

    for (i = 0; i < MAX_DEVICE_CONNECTED; i++) {
        if ((dev = host->getDevice(i)) != NULL) {
            
            if(host->enumerate(dev, this))
                break;

            if (msd_device_found) {
                bulk_in = dev->getEndpoint(msd_intf, BULK_ENDPOINT, IN);
                bulk_out = dev->getEndpoint(msd_intf, BULK_ENDPOINT, OUT);
                
                if (!bulk_in || !bulk_out)
                    break;
                
                USB_INFO("New MSD device: VID:%04x PID:%04x [dev: %p]", dev->getVid(), dev->getPid(), dev);
                dev->setName("MSD");
                host->registerDriver(dev, msd_intf, this, &USBHostMSD::init);

                dev_connected = true;
                return true;
            }
        } //if()
    } //for()
    return false;
}

/*virtual*/ void USBHostMSD::setVidPid(uint16_t vid, uint16_t pid)
{
    // we don't check VID/PID for MSD driver
}

/*virtual*/ bool USBHostMSD::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed
{
    if ((msd_intf == -1) &&
        (intf_class == MSD_CLASS) &&
        (intf_subclass == 0x06) &&
        (intf_protocol == 0x50)) {
        msd_intf = intf_nb;
        return true;
    }
    return false;
}

/*virtual*/ bool USBHostMSD::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used
{
    if (intf_nb == msd_intf) {
        if (type == BULK_ENDPOINT) {
            msd_device_found = true;
            return true;
        }
    }
    return false;
}


int USBHostMSD::testUnitReady() {
    return SCSITransfer(NULL, 6, DEVICE_TO_HOST, 0, 0);
}

int USBHostMSD::readCapacity() {
    uint8_t cmd[10] = {0x25,0,0,0,0,0,0,0,0,0};
    uint8_t result[8];
    int status = SCSITransfer(cmd, 10, DEVICE_TO_HOST, result, 8);
    if (status == 0) {
        blockCount = (result[0] << 24) | (result[1] << 16) | (result[2] << 8) | result[3];
        blockSize = (result[4] << 24) | (result[5] << 16) | (result[6] << 8) | result[7];
        USB_INFO("MSD [dev: %p] - blockCount: %lld, blockSize: %d\r\n", dev, blockCount, blockSize);
    }
    return status;
}


int USBHostMSD::SCSIRequestSense() {
    uint8_t cmd[5] = {0x03,0,0,0,0x13};
    uint8_t result[19];
    int status = SCSITransfer(cmd, 5, DEVICE_TO_HOST, result, 19);
    return status;
}


int USBHostMSD::inquiry(uint8_t lun, uint8_t page_code) {
    uint8_t evpd = (page_code == 0) ? 0 : 1;
    uint8_t cmd[6] = {0x12, (lun << 5) | evpd, page_code, 0, 36, 0};
    uint8_t result[36];
    int status = SCSITransfer(cmd, 6, DEVICE_TO_HOST, result, 36);
    if (status == 0) {
        char vid_pid[9];
        memcpy(vid_pid, &result[8], 8);
        vid_pid[8] = 0;
        USB_INFO("MSD [dev: %p] - Vendor ID: %s", dev, vid_pid);

        memcpy(vid_pid, &result[16], 8);
        USB_INFO("MSD [dev: %p] - Produc ID: %s", dev, vid_pid);

        memcpy(vid_pid, &result[32], 4);
        vid_pid[4] = 0;
        USB_INFO("MSD [dev: %p] - Product rev: %s", dev, vid_pid);
    }
    return status;
}

int USBHostMSD::checkResult(uint8_t res, USBEndpoint * ep) {
    // if ep stalled: send clear feature
    if (res == USB_TYPE_STALL_ERROR) {
        res = host->controlWrite(   dev,
                                    USB_RECIPIENT_ENDPOINT | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_STANDARD,
                                    CLEAR_FEATURE,
                                    0,
                                    ep->getAddress(),
                                    NULL,
                                    0);
        // set state to IDLE if clear feature successful
        if (res == USB_TYPE_OK) {
            ep->setState(USB_TYPE_IDLE);
        }
    }

    if (res != USB_TYPE_OK)
        return -1;

    return 0;
}


int USBHostMSD::SCSITransfer(uint8_t * cmd, uint8_t cmd_len, int flags, uint8_t * data, uint32_t transfer_len) {

    int res = 0;

    cbw.Signature = CBW_SIGNATURE;
    cbw.Tag = 0;
    cbw.DataLength = transfer_len;
    cbw.Flags = flags;
    cbw.LUN = 0;
    cbw.CBLength = cmd_len;
    memset(cbw.CB,0,sizeof(cbw.CB));
    if (cmd) {
        memcpy(cbw.CB,cmd,cmd_len);
    }

    // send the cbw
    res = host->bulkWrite(dev, bulk_out,(uint8_t *)&cbw, 31);
    if (checkResult(res, bulk_out))
        return -1;

    // data stage if needed
    if (data) {
        if (flags == HOST_TO_DEVICE) {

            res = host->bulkWrite(dev, bulk_out, data, transfer_len);
            if (checkResult(res, bulk_out))
                return -1;

        } else if (flags == DEVICE_TO_HOST) {

            res = host->bulkRead(dev, bulk_in, data, transfer_len);
            if (checkResult(res, bulk_in))
                return -1;
        }
    }

    // status stage
    csw.Signature = 0;
    res = host->bulkRead(dev, bulk_in,(uint8_t *)&csw, 13);
    if (checkResult(res, bulk_in))
        return -1;

    if (csw.Signature != CSW_SIGNATURE) {
        return -1;
    }

    // ModeSense?
    if ((csw.Status == 1) && (cmd[0] != 0x03))
        return SCSIRequestSense();

    USB_DBG("recv csw: status: %d", csw.Status);
    return csw.Status;
}


int USBHostMSD::dataTransfer(uint8_t * buf, uint32_t block, uint8_t nbBlock, int direction) {
    uint8_t cmd[10];
    memset(cmd,0,10);
    cmd[0] = (direction == DEVICE_TO_HOST) ? 0x28 : 0x2A;

    cmd[2] = (block >> 24) & 0xff;
    cmd[3] = (block >> 16) & 0xff;
    cmd[4] = (block >> 8) & 0xff;
    cmd[5] =  block & 0xff;

    cmd[7] = (nbBlock >> 8) & 0xff;
    cmd[8] = nbBlock & 0xff;

    return SCSITransfer(cmd, 10, direction, buf, blockSize*nbBlock);
}


int USBHostMSD::disk_initialize() {
    USB_DBG("FILESYSTEM: init");
    U8 i, timeout = 10;
    
    for (i = 0; i < timeout; i++) {
        if (!testUnitReady())
            break;
    }
    
    if (i == timeout) {
        disk_init = false;
        return -1;
    }
    inquiry(0, 0);
    disk_init = 1;
    return readCapacity();
}

int USBHostMSD::disk_write(const uint8_t *buffer, uint64_t block_number) {
    USB_DBG("FILESYSTEM: write block: %lld", block_number);
    if (!disk_init) {
        disk_initialize();
    }
    if (!disk_init)
        return -1;
    return dataTransfer((uint8_t *)buffer, block_number, 1, HOST_TO_DEVICE);
}

int USBHostMSD::disk_read(uint8_t * buffer, uint64_t block_number) {
    USB_DBG("FILESYSTEM: read block %lld", block_number);
    if (!disk_init) {
        disk_initialize();
    }
    if (!disk_init)
        return -1;
    return dataTransfer((uint8_t *)buffer, block_number, 1, DEVICE_TO_HOST);
}

uint64_t USBHostMSD::disk_sectors() {
    USB_DBG("FILESYSTEM: sectors");
    if (!disk_init) {
        disk_initialize();
    }
    if (!disk_init)
        return 0;
    return blockCount;
}

#endif