usb_host_devices.c 52.6 KB
Newer Older
T
tyustli 已提交
1 2
/*
 * Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc.
3
 * Copyright 2016 NXP
T
tyustli 已提交
4
 *
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * o Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
T
tyustli 已提交
29 30
 */

31
#include <usb/include/usb_device_config.h>
T
tyustli 已提交
32 33 34
#include "usb_host.h"
#include "usb_host_hci.h"
#include "usb_host_devices.h"
35

T
tyustli 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
#include "usb_host_hub.h"
#endif /* USB_HOST_CONFIG_HUB */

/*******************************************************************************
 * Definitions
 ******************************************************************************/

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/*!
 * @brief enumeration transfer callback function.
 *
 * @param param      callback parameter.
 * @param transfer   the transfer.
 * @param status     transfer result status.
 */
static void USB_HostEnumerationTransferCallback(void *param, usb_host_transfer_t *transfer, usb_status_t status);

/*!
 * @brief process the new step state.
 *
 * @param deviceInstance    device instance pointer.
 *
 * @return kStatus_USB_Success or error codes
 */
static usb_status_t USB_HostProcessState(usb_host_device_instance_t *deviceInstance);

/*!
 * @brief process the previous step transfer result.
 *
 * @param deviceInstance    device instance pointer.
 *
 * @return kStatus_USB_Success or error codes
 */
73
static usb_status_t USB_HostProcessCallback(usb_host_device_instance_t *deviceInstance);
T
tyustli 已提交
74 75 76 77 78 79 80 81 82

/*!
 * @brief notify the application event, the callback is registered when initializing host.
 *
 * @param deviceInstance   device instance pointer.
 * @param eventCode        event code.
 *
 * @return kStatus_USB_Success or error codes
 */
83
static usb_status_t USB_HostNotifyDevice(usb_host_device_instance_t *deviceInstance, uint32_t eventCode);
T
tyustli 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

/*!
 * @brief allocate one address.
 *
 * @param hostInstance    host instance pointer.
 *
 * @return address, 0 is invalid.
 */
static uint8_t USB_HostAllocateDeviceAddress(usb_host_instance_t *hostInstance);

/*!
 * @brief release one address.
 *
 * @param hostInstance    host instance pointer.
 * @param address     releasing address.
 */
static void USB_HostReleaseDeviceAddress(usb_host_instance_t *hostInstance, uint8_t address);

/*!
 * @brief release device resource.
 *
 * @param hostInstance   host instance pointer.
 * @param deviceInstance    device instance pointer.
 */
static void USB_HostReleaseDeviceResource(usb_host_instance_t *hostInstance,
                                          usb_host_device_instance_t *deviceInstance);

/*!
 * @brief parse device configuration descriptor.
 *
 * @param deviceHandle    device handle.
 *
 * @return kStatus_USB_Success or error codes.
 */
static usb_status_t USB_HostParseDeviceConfigurationDescriptor(usb_device_handle deviceHandle);

/*!
 * @brief remove device instance from host device list.
 *
 * @param hostHandle   host instance handle.
 * @param deviceHandle    device handle.
 *
 * @return kStatus_USB_Success or error codes.
 */
static usb_status_t USB_HostRemoveDeviceInstance(usb_host_handle hostHandle, usb_device_handle deviceHandle);

/*!
 * @brief control the bus.
 *
 * This function control the host bus.
 *
 * @param[in] hostHandle     the host handle.
 * @param[in] controlType    the control code, please reference to bus_event_t.
 *
 * @retval kStatus_USB_Success              control successfully.
 * @retval kStatus_USB_InvalidHandle        The hostHandle is a NULL pointer.
 */
static usb_status_t USB_HostControlBus(usb_host_handle hostHandle, uint8_t controlType);

143 144 145 146 147 148 149 150 151 152 153
extern usb_status_t USB_HostStandardSetGetDescriptor(usb_host_device_instance_t *deviceInstance,
                                                     usb_host_transfer_t *transfer,
                                                     void *param);
extern usb_status_t USB_HostStandardSetAddress(usb_host_device_instance_t *deviceInstance,
                                               usb_host_transfer_t *transfer,
                                               void *param);
extern usb_status_t USB_HostCh9RequestCommon(usb_host_device_instance_t *deviceInstance,
                                             usb_host_transfer_t *transfer,
                                             uint8_t *buffer,
                                             uint32_t bufferLen);

T
tyustli 已提交
154 155
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))

156 157 158 159 160 161 162 163 164 165 166
extern usb_status_t USB_HostHubDeviceEvent(usb_host_handle hostHandle,
                                           usb_device_handle deviceHandle,
                                           usb_host_configuration_handle configurationHandle,
                                           uint32_t eventCode);

extern uint32_t USB_HostHubGetHsHubNumber(usb_host_handle hostHandle, uint8_t parentHubNo);

extern uint32_t USB_HostHubGetHsHubPort(usb_host_handle hostHandle, uint8_t parentHubNo, uint8_t parentPortNo);

extern usb_status_t USB_HostHubRemovePort(usb_host_handle hostHandle, uint8_t hubNumber, uint8_t portNumber);

T
tyustli 已提交
167 168 169 170 171 172
#endif

/*******************************************************************************
 * Variables
 ******************************************************************************/

173 174
extern usb_host_instance_t g_UsbHostInstance[USB_HOST_CONFIG_MAX_HOST];

T
tyustli 已提交
175
/*! @brief enumeration step process array */
176 177
static const usb_host_enum_process_entry_t s_EnumEntries[] = \
{
T
tyustli 已提交
178 179
    /* kStatus_dev_initial */
    {
180
        0, 0, NULL,
T
tyustli 已提交
181 182 183
    },
    /* kStatus_DEV_GetDes8 */
    {
184
        kStatus_DEV_SetAddress, kStatus_DEV_GetDes8, USB_HostProcessCallback,
T
tyustli 已提交
185 186 187
    },
    /* kStatus_DEV_SetAddress */
    {
188
        kStatus_DEV_GetDes, kStatus_DEV_SetAddress, USB_HostProcessCallback,
T
tyustli 已提交
189 190 191
    },
    /* kStatus_DEV_GetDes */
    {
192
        kStatus_DEV_GetCfg9, kStatus_DEV_GetDes, NULL,
T
tyustli 已提交
193 194 195
    },
    /* kStatus_DEV_GetCfg9 */
    {
196
        kStatus_DEV_GetCfg, kStatus_DEV_GetCfg9, USB_HostProcessCallback,
T
tyustli 已提交
197 198 199
    },
    /* kStatus_DEV_GetCfg */
    {
200
        kStatus_DEV_SetCfg, kStatus_DEV_GetCfg9, USB_HostProcessCallback,
T
tyustli 已提交
201 202 203
    },
    /* kStatus_DEV_SetCfg */
    {
204
        kStatus_DEV_EnumDone, kStatus_DEV_SetCfg, NULL,
T
tyustli 已提交
205 206 207 208 209 210 211 212 213
    },
};

/*******************************************************************************
 * Code
 ******************************************************************************/

static void USB_HostEnumerationTransferCallback(void *param, usb_host_transfer_t *transfer, usb_status_t status)
{
214
    uint8_t nextStep = 0;
T
tyustli 已提交
215 216
    usb_host_device_instance_t *deviceInstance = (usb_host_device_instance_t *)param;

217
    USB_HostFreeTransfer(deviceInstance->hostHandle, transfer); /* free transfer */
T
tyustli 已提交
218 219 220

    if (status == kStatus_USB_Success)
    {
221
        nextStep = 1;
T
tyustli 已提交
222 223 224 225
    }
    else if (status == kStatus_USB_TransferStall)
    {
#if ((defined USB_HOST_CONFIG_COMPLIANCE_TEST) && (USB_HOST_CONFIG_COMPLIANCE_TEST))
226 227 228
        usb_echo("no response from device\r\n");
#endif                                        /* USB_HOST_CONFIG_COMPLIANCE_TEST */
        if (deviceInstance->stallRetries > 0) /* retry same transfer when stall */
T
tyustli 已提交
229 230 231
        {
            deviceInstance->stallRetries--;
        }
232
        else /* process next state when all retries stall */
T
tyustli 已提交
233
        {
234
            nextStep = 1;
T
tyustli 已提交
235 236 237 238
        }
    }
    else if (status == kStatus_USB_TransferCancel)
    {
239
        return;
T
tyustli 已提交
240 241 242
    }
    else
    {
243 244 245 246 247 248 249 250 251 252 253 254 255 256
        if (deviceInstance->enumRetries > 0) /* next whole retry */
        {
            deviceInstance->enumRetries--;
            deviceInstance->stallRetries = USB_HOST_CONFIG_ENUMERATION_MAX_STALL_RETRIES;
            deviceInstance->configurationValue = 0;
            deviceInstance->state = kStatus_DEV_GetDes8;
        }
        else
        {
#if ((defined USB_HOST_CONFIG_COMPLIANCE_TEST) && (USB_HOST_CONFIG_COMPLIANCE_TEST))
            usb_echo("Device No Response\r\n");
#endif
            return;
        }
T
tyustli 已提交
257 258
    }

259
    if (nextStep == 1)
T
tyustli 已提交
260 261
    {
        deviceInstance->stallRetries = USB_HOST_CONFIG_ENUMERATION_MAX_STALL_RETRIES;
262
        if (s_EnumEntries[deviceInstance->state - 1].process == NULL)
T
tyustli 已提交
263
        {
264
            deviceInstance->state = s_EnumEntries[deviceInstance->state - 1].successState; /* next state */
T
tyustli 已提交
265 266 267
        }
        else
        {
268 269
            status = s_EnumEntries[deviceInstance->state - 1].process(
                deviceInstance);               /* process the previous state result */
T
tyustli 已提交
270 271
            if (status == kStatus_USB_Success) /* process success */
            {
272
                deviceInstance->state = s_EnumEntries[deviceInstance->state - 1].successState;
T
tyustli 已提交
273 274 275
            }
            else if (status == kStatus_USB_Retry) /* need retry */
            {
276
                deviceInstance->state = s_EnumEntries[deviceInstance->state - 1].retryState;
T
tyustli 已提交
277 278 279 280 281 282 283
            }
            else if (status == kStatus_USB_NotSupported) /* device don't suport by the application */
            {
                return; /* unrecoverable fail */
            }
            else /* process error, next retry */
            {
284 285 286 287 288 289 290 291 292
                if (deviceInstance->enumRetries > 0) /* next whole retry */
                {
                    deviceInstance->enumRetries--;
                    deviceInstance->stallRetries = USB_HOST_CONFIG_ENUMERATION_MAX_STALL_RETRIES;
                    deviceInstance->configurationValue = 0;
                    deviceInstance->state = kStatus_DEV_GetDes8;
                }
                else
                {
T
tyustli 已提交
293
#if ((defined USB_HOST_CONFIG_COMPLIANCE_TEST) && (USB_HOST_CONFIG_COMPLIANCE_TEST))
294
                    usb_echo("Device No Response\r\n");
T
tyustli 已提交
295
#endif
296 297 298
                    return; /* unrecoverable fail */
                }
            }
T
tyustli 已提交
299 300 301
        }
    }

302
    if (USB_HostProcessState(deviceInstance) != kStatus_USB_Success) /* process the new state */
T
tyustli 已提交
303 304
    {
#ifdef HOST_ECHO
305
        usb_echo("enumation setup error\r\n");
T
tyustli 已提交
306
#endif
307
        return;
T
tyustli 已提交
308 309 310 311 312 313 314 315 316 317
    }
}

static usb_status_t USB_HostProcessState(usb_host_device_instance_t *deviceInstance)
{
    usb_status_t status = kStatus_USB_Success;
    usb_host_process_descriptor_param_t getDescriptorParam;
    usb_host_transfer_t *transfer;

    /* malloc transfer */
318
    if (deviceInstance->state != kStatus_DEV_EnumDone)
T
tyustli 已提交
319 320 321 322 323 324 325 326
    {
        if (USB_HostMallocTransfer(deviceInstance->hostHandle, &transfer) != kStatus_USB_Success)
        {
#ifdef HOST_ECHO
            usb_echo("error to get transfer\r\n");
#endif
            return kStatus_USB_Error;
        }
327
        transfer->callbackFn = USB_HostEnumerationTransferCallback;
T
tyustli 已提交
328 329 330
        transfer->callbackParam = deviceInstance;

        /* reset transfer fields */
331 332 333 334
        transfer->setupPacket->bmRequestType = 0x00;
        transfer->setupPacket->wIndex = 0;
        transfer->setupPacket->wLength = 0;
        transfer->setupPacket->wValue = 0;
T
tyustli 已提交
335 336
    }

337
    switch (deviceInstance->state)
T
tyustli 已提交
338 339 340 341
    {
        case kStatus_DEV_GetDes8:
        case kStatus_DEV_GetDes: /* get descriptor state */
            getDescriptorParam.descriptorLength = sizeof(usb_descriptor_device_t);
342
            if (deviceInstance->state == kStatus_DEV_GetDes8)
T
tyustli 已提交
343
            {
344
                getDescriptorParam.descriptorLength = 8;
T
tyustli 已提交
345 346
            }
            getDescriptorParam.descriptorBuffer = (uint8_t *)deviceInstance->deviceDescriptor;
347 348 349
            getDescriptorParam.descriptorType = USB_DESCRIPTOR_TYPE_DEVICE;
            getDescriptorParam.descriptorIndex = 0;
            getDescriptorParam.languageId = 0;
T
tyustli 已提交
350 351 352 353 354 355 356 357 358 359 360 361

            transfer->setupPacket->bmRequestType |= USB_REQUEST_TYPE_DIR_IN;
            transfer->setupPacket->bRequest = USB_REQUEST_STANDARD_GET_DESCRIPTOR;
            status = USB_HostStandardSetGetDescriptor(deviceInstance, transfer, &getDescriptorParam);
            break;
        case kStatus_DEV_SetAddress: /* set address state */
            transfer->setupPacket->bRequest = USB_REQUEST_STANDARD_SET_ADDRESS;
            status = USB_HostStandardSetAddress(deviceInstance, transfer, &deviceInstance->allocatedAddress);
            break;

        case kStatus_DEV_GetCfg9: /* get 9 bytes configuration state */
            getDescriptorParam.descriptorBuffer = deviceInstance->enumBuffer;
362 363
            getDescriptorParam.descriptorType = USB_DESCRIPTOR_TYPE_CONFIGURE;
            getDescriptorParam.descriptorIndex = deviceInstance->configurationValue;
T
tyustli 已提交
364
            getDescriptorParam.descriptorLength = 9;
365
            getDescriptorParam.languageId = 0;
T
tyustli 已提交
366 367 368 369 370 371 372 373

            transfer->setupPacket->bmRequestType |= USB_REQUEST_TYPE_DIR_IN;
            transfer->setupPacket->bRequest = USB_REQUEST_STANDARD_GET_DESCRIPTOR;
            status = USB_HostStandardSetGetDescriptor(deviceInstance, transfer, &getDescriptorParam);
            break;

        case kStatus_DEV_GetCfg: /* get configuration state */
            getDescriptorParam.descriptorBuffer = deviceInstance->configurationDesc;
374 375
            getDescriptorParam.descriptorType = USB_DESCRIPTOR_TYPE_CONFIGURE;
            getDescriptorParam.descriptorIndex = deviceInstance->configurationValue;
T
tyustli 已提交
376
            getDescriptorParam.descriptorLength = deviceInstance->configurationLen;
377
            getDescriptorParam.languageId = 0;
T
tyustli 已提交
378 379 380 381 382 383 384 385 386 387

            transfer->setupPacket->bmRequestType |= USB_REQUEST_TYPE_DIR_IN;
            transfer->setupPacket->bRequest = USB_REQUEST_STANDARD_GET_DESCRIPTOR;
            status = USB_HostStandardSetGetDescriptor(deviceInstance, transfer, &getDescriptorParam);
            break;

        case kStatus_DEV_SetCfg: /* set configuration state */
            transfer->setupPacket->wValue =
                USB_SHORT_TO_LITTLE_ENDIAN(deviceInstance->configuration.configurationDesc->bConfigurationValue);
            transfer->setupPacket->bRequest = USB_REQUEST_STANDARD_SET_CONFIGURATION;
388
            status = USB_HostCh9RequestCommon(deviceInstance, transfer, NULL, 0);
T
tyustli 已提交
389 390 391
            break;

        case kStatus_DEV_EnumDone: /* enumeration done state */
392 393
            status = USB_HostNotifyDevice(deviceInstance,
                                          kUSB_HostEventEnumerationDone); /* notify device enumeration done */
T
tyustli 已提交
394 395
            if (status == kStatus_USB_Success)
            {
396
                deviceInstance->state = kStatus_DEV_AppUsed;
T
tyustli 已提交
397 398 399 400 401 402 403 404 405 406
            }
            break;

        default:
            break;
    }

    return status;
}

407
static usb_status_t USB_HostProcessCallback(usb_host_device_instance_t *deviceInstance)
T
tyustli 已提交
408 409
{
    usb_host_pipe_t *pipe = (usb_host_pipe_t *)deviceInstance->controlPipe;
410
    usb_status_t status = kStatus_USB_Success;
T
tyustli 已提交
411 412 413
    usb_descriptor_configuration_t *configureDesc;
    usb_host_instance_t *hostInstance = (usb_host_instance_t *)deviceInstance->hostHandle;

414
    switch (deviceInstance->state)
T
tyustli 已提交
415 416 417
    {
        case kStatus_DEV_GetDes8: /* process get 8 bytes descriptor result */
            pipe->maxPacketSize = deviceInstance->deviceDescriptor->bMaxPacketSize0;
418
            hostInstance->controllerTable->controllerIoctl(
T
tyustli 已提交
419 420 421 422 423
                hostInstance->controllerHandle, kUSB_HostUpdateControlPacketSize, deviceInstance->controlPipe);
            break;

        case kStatus_DEV_SetAddress: /* process set address result */
            deviceInstance->setAddress = deviceInstance->allocatedAddress;
424
            hostInstance->controllerTable->controllerIoctl(
T
tyustli 已提交
425 426 427
                hostInstance->controllerHandle, kUSB_HostUpdateControlEndpointAddress, deviceInstance->controlPipe);
            break;

428 429
        case kStatus_DEV_GetDes: /* process set address result */
            /* NULL */
T
tyustli 已提交
430 431 432
            break;

        case kStatus_DEV_GetCfg9: /* process get 9 bytes configuration result */
433
            configureDesc = (usb_descriptor_configuration_t *)&deviceInstance->enumBuffer[0];
T
tyustli 已提交
434 435 436 437 438 439 440

            deviceInstance->configurationLen = USB_SHORT_FROM_LITTLE_ENDIAN_ADDRESS(configureDesc->wTotalLength);
            if (deviceInstance->configurationDesc != NULL)
            {
#if ((defined(USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE)) && (USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE > 0U))
                SDK_Free(deviceInstance->configurationDesc);
#else
441
                USB_OsaMemoryFree(deviceInstance->configurationDesc);
T
tyustli 已提交
442 443 444 445
#endif
                deviceInstance->configurationDesc = NULL;
            }
            /* for KHCI, the start address and the length should be 4 byte align */
446
            if ((deviceInstance->configurationLen & 0x03) != 0)
T
tyustli 已提交
447 448 449
            {
#if ((defined(USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE)) && (USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE > 0U))
                deviceInstance->configurationDesc =
450
                    (uint8_t *)SDK_Malloc((deviceInstance->configurationLen & 0xFFFFFFFCu) + 4, USB_CACHE_LINESIZE);
T
tyustli 已提交
451 452
#else
                deviceInstance->configurationDesc =
453
                    (uint8_t *)USB_OsaMemoryAllocate((deviceInstance->configurationLen & 0xFFFFFFFCu) + 4);
T
tyustli 已提交
454 455 456 457 458 459 460 461
#endif
            }
            else
            {
#if ((defined(USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE)) && (USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE > 0U))
                deviceInstance->configurationDesc =
                    (uint8_t *)SDK_Malloc(deviceInstance->configurationLen, USB_CACHE_LINESIZE);
#else
462
                deviceInstance->configurationDesc = (uint8_t *)USB_OsaMemoryAllocate(deviceInstance->configurationLen);
T
tyustli 已提交
463 464 465 466
#endif
            }
            if (deviceInstance->configurationDesc == NULL)
            {
467
                return kStatus_USB_Error;
T
tyustli 已提交
468 469 470
            }
            break;

471 472 473
        case kStatus_DEV_GetCfg: /* process get cofiguration result */
            if (((usb_descriptor_configuration_t *)deviceInstance->configurationDesc)->bMaxPower >
                USB_HOST_CONFIG_MAX_POWER)
T
tyustli 已提交
474 475 476 477 478 479 480 481 482 483
            {
                return kStatus_USB_Error;
            }
            deviceInstance->configurationValue++;
            if (USB_HostParseDeviceConfigurationDescriptor(deviceInstance) !=
                kStatus_USB_Success) /* parse configuration descriptor */
            {
                return kStatus_USB_Error;
            }

484
            status = USB_HostNotifyDevice(deviceInstance, kUSB_HostEventAttach);
T
tyustli 已提交
485 486 487 488 489 490 491 492 493 494

            if (status != kStatus_USB_Success)
            {
                /* next configuration */
                if (deviceInstance->configurationValue < deviceInstance->deviceDescriptor->bNumConfigurations)
                {
                    return kStatus_USB_Retry;
                }
                else
                {
495 496
                    USB_HostNotifyDevice(deviceInstance,
                                         kUSB_HostEventNotSupported); /* notify application device is not supported */
T
tyustli 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
                    return kStatus_USB_NotSupported;
                }
            }
            break;

        case kStatus_DEV_SetCfg:
            /* NULL */
            break;

        default:
            break;
    }

    return status;
}

513
static usb_status_t USB_HostNotifyDevice(usb_host_device_instance_t *deviceInstance, uint32_t eventCode)
T
tyustli 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527
{
    usb_host_instance_t *hostInstance;
    usb_status_t status1 = kStatus_USB_Error;
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
    usb_status_t status2 = kStatus_USB_Error;
    uint8_t haveHub;
    uint8_t haveNoHub;
    uint8_t interfaceIndex;
#endif /* USB_HOST_CONFIG_HUB */

    if (deviceInstance == NULL)
    {
        return kStatus_USB_InvalidHandle;
    }
528
    hostInstance = (usb_host_instance_t *)deviceInstance->hostHandle;
T
tyustli 已提交
529 530

#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
531 532 533
    haveHub = 0;
    haveNoHub = 0;
    for (interfaceIndex = 0; interfaceIndex < deviceInstance->configuration.interfaceCount; ++interfaceIndex)
T
tyustli 已提交
534 535 536 537
    {
        if (((usb_descriptor_interface_t *)deviceInstance->configuration.interfaceList[interfaceIndex].interfaceDesc)
                ->bInterfaceClass == USB_HOST_HUB_CLASS_CODE)
        {
538
            haveHub = 1;
T
tyustli 已提交
539 540 541
        }
        else
        {
542
            haveNoHub = 1;
T
tyustli 已提交
543 544 545
        }
    }

546
    if ((haveNoHub == 1) && (hostInstance->deviceCallback != NULL))
T
tyustli 已提交
547
    {
548 549
        status1 = hostInstance->deviceCallback(deviceInstance, &deviceInstance->configuration,
                                               eventCode); /* notify application event */
T
tyustli 已提交
550
    }
551
    if (haveHub)
T
tyustli 已提交
552 553 554 555 556 557 558 559 560
    {
        status2 = USB_HostHubDeviceEvent(hostInstance, deviceInstance, &deviceInstance->configuration,
                                         eventCode); /* notify hub event */
    }

    if ((status1 == kStatus_USB_Success) || (status2 == kStatus_USB_Success)) /* the device is supported */
    {
        return kStatus_USB_Success;
    }
561
    else if (eventCode == kUSB_HostEventAttach) /* attach event */
T
tyustli 已提交
562 563 564 565 566 567 568 569 570 571
    {
        status1 = kStatus_USB_NotSupported;
    }
    else
    {
        status1 = kStatus_USB_Error;
    }
#else
    if (hostInstance->deviceCallback != NULL)
    {
572 573
        status1 = hostInstance->deviceCallback(deviceInstance, &deviceInstance->configuration,
                                               eventCode); /* call host callback function */
T
tyustli 已提交
574 575 576 577 578 579 580
    }
#endif
    return status1;
}

static uint8_t USB_HostAllocateDeviceAddress(usb_host_instance_t *hostInstance)
{
581
    uint8_t address = 0;
T
tyustli 已提交
582 583
    uint8_t addressIndex;
    uint8_t addressBitIndex;
584
    for (addressIndex = 0; addressIndex < 8; ++addressIndex) /* find the idle address postion byte */
T
tyustli 已提交
585
    {
586
        if (hostInstance->addressBitMap[addressIndex] != 0xFF)
T
tyustli 已提交
587 588 589 590
        {
            break;
        }
    }
591
    if (addressIndex < 8)
T
tyustli 已提交
592
    {
593
        for (addressBitIndex = 0; addressBitIndex < 8; ++addressBitIndex) /* find the idle address position bit */
T
tyustli 已提交
594
        {
595
            if (!(hostInstance->addressBitMap[addressIndex] & (0x01u << addressBitIndex)))
T
tyustli 已提交
596
            {
597 598
                hostInstance->addressBitMap[addressIndex] |= (0x01u << addressBitIndex); /* set the allocated bit */
                address = addressIndex * 8 + addressBitIndex + 1;                        /* the address minimum is 1 */
T
tyustli 已提交
599 600 601 602 603 604 605 606 607
                break;
            }
        }
    }
    return address;
}

static void USB_HostReleaseDeviceAddress(usb_host_instance_t *hostInstance, uint8_t address)
{
608 609 610 611
    USB_HostLock();
    hostInstance->addressBitMap[(uint32_t)(address - 1) >> 3] &=
        (~(0x01u << (((uint32_t)address - 1) & 0x07U))); /* reset the allocated bit */
    USB_HostUnlock();
T
tyustli 已提交
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
}

static usb_status_t USB_HostRemoveDeviceInstance(usb_host_handle hostHandle, usb_device_handle deviceHandle)
{
    usb_host_instance_t *hostInstance = (usb_host_instance_t *)hostHandle;
    usb_host_device_instance_t *currentInstance;
    usb_host_device_instance_t *prevInstance;
    if ((hostHandle == NULL) || (deviceHandle == NULL))
    {
        return kStatus_USB_InvalidHandle;
    }

    /* search and remove device instance */
    prevInstance = (usb_host_device_instance_t *)hostInstance->deviceList;
    if (prevInstance == deviceHandle)
    {
        hostInstance->deviceList = prevInstance->next;
        return kStatus_USB_Success;
    }
    else
    {
        currentInstance = prevInstance->next;
    }

    while (currentInstance != NULL)
    {
        if (currentInstance == deviceHandle)
        {
            prevInstance->next = currentInstance->next;
            return kStatus_USB_Success;
        }
643
        prevInstance = currentInstance;
T
tyustli 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
        currentInstance = currentInstance->next;
    }

    return kStatus_USB_Success;
}

static void USB_HostReleaseDeviceResource(usb_host_instance_t *hostInstance, usb_host_device_instance_t *deviceInstance)
{
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
    uint8_t level = 0;
#endif

#if ((defined(USB_HOST_CONFIG_LOW_POWER_MODE)) && (USB_HOST_CONFIG_LOW_POWER_MODE > 0U))
    if (deviceInstance == hostInstance->suspendedDevice)
    {
        hostInstance->suspendedDevice = NULL;
    }
#endif
    /* release device's address */
663
    if (deviceInstance->setAddress != 0)
T
tyustli 已提交
664 665 666 667 668
    {
        USB_HostReleaseDeviceAddress(hostInstance, deviceInstance->setAddress);
    }
    else
    {
669
        if (deviceInstance->allocatedAddress != 0)
T
tyustli 已提交
670 671 672 673 674 675 676 677
        {
            USB_HostReleaseDeviceAddress(hostInstance, deviceInstance->allocatedAddress);
        }
    }

    /* close control pipe */
    if (deviceInstance->controlPipe != NULL)
    {
678
        USB_HostCancelTransfer(hostInstance, deviceInstance->controlPipe, NULL);
T
tyustli 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
        if (USB_HostClosePipe(hostInstance, deviceInstance->controlPipe) != kStatus_USB_Success)
        {
#ifdef HOST_ECHO
            usb_echo("error when close pipe\r\n");
#endif
        }
        deviceInstance->controlPipe = NULL;
    }

    /* free configuration buffer */
    if (deviceInstance->configurationDesc != NULL)
    {
#if ((defined(USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE)) && (USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE > 0U))
        SDK_Free(deviceInstance->configurationDesc);
#else
694
        USB_OsaMemoryFree(deviceInstance->configurationDesc);
T
tyustli 已提交
695 696 697 698 699 700 701 702 703
#endif
    }

#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
    level = deviceInstance->level;
#endif
#if ((defined(USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE)) && (USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE > 0U))
    SDK_Free(deviceInstance->deviceDescriptor);
#else
704
    USB_OsaMemoryFree(deviceInstance->deviceDescriptor);
T
tyustli 已提交
705 706
#endif
    /* free device instance buffer */
707
    USB_OsaMemoryFree(deviceInstance);
T
tyustli 已提交
708 709 710

#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
    /* enable controller attach if root hub */
711
    if (level == 1)
T
tyustli 已提交
712
    {
713
        USB_HostControlBus(hostInstance, kUSB_HostBusEnableAttach);
T
tyustli 已提交
714 715 716
    }
#else
    /* enable controller attach */
717
    USB_HostControlBus(hostInstance, kUSB_HostBusEnableAttach);
T
tyustli 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
#endif
}

static usb_status_t USB_HostParseDeviceConfigurationDescriptor(usb_device_handle deviceHandle)
{
    usb_host_device_instance_t *deviceInstance = (usb_host_device_instance_t *)deviceHandle;
    uint32_t endPos;
    usb_descriptor_union_t *unionDes;
    usb_host_interface_t *interfaceParse = NULL;
    usb_host_ep_t *epParse;
    uint8_t *buffer;

    if (deviceHandle == NULL)
    {
        return kStatus_USB_InvalidParameter;
    }

735
    buffer = (uint8_t *)&deviceInstance->configuration;
T
tyustli 已提交
736
    /* clear the previous parse result, note: end_pos means buffer index here*/
737
    for (endPos = 0; endPos < sizeof(usb_host_configuration_t); endPos++)
T
tyustli 已提交
738
    {
739
        buffer[endPos] = 0;
T
tyustli 已提交
740
    }
741
    for (endPos = 0; endPos < USB_HOST_CONFIG_CONFIGURATION_MAX_INTERFACE; ++endPos)
T
tyustli 已提交
742
    {
743
        deviceInstance->interfaceStatus[endPos] = 0;
T
tyustli 已提交
744 745 746
    }

    /* parse configuration descriptor */
747 748
    unionDes = (usb_descriptor_union_t *)deviceInstance->configurationDesc;
    endPos = (uint32_t)(deviceInstance->configurationDesc + deviceInstance->configurationLen);
T
tyustli 已提交
749 750 751 752 753

    if ((unionDes->common.bLength == USB_DESCRIPTOR_LENGTH_CONFIGURE) &&
        (unionDes->common.bDescriptorType == USB_DESCRIPTOR_TYPE_CONFIGURE))
    {
        /* configuration descriptor */
754
        deviceInstance->configuration.configurationDesc = (usb_descriptor_configuration_t *)unionDes;
T
tyustli 已提交
755
        deviceInstance->configuration.configurationExtensionLength = 0;
756 757
        deviceInstance->configuration.configurationExtension = NULL;
        deviceInstance->configuration.interfaceCount = 0;
T
tyustli 已提交
758 759 760 761 762 763 764 765 766
        unionDes = (usb_descriptor_union_t *)((uint32_t)unionDes + unionDes->common.bLength);
        while ((uint32_t)unionDes < endPos)
        {
            if (unionDes->common.bDescriptorType != USB_DESCRIPTOR_TYPE_INTERFACE)
            {
                if (deviceInstance->configuration.configurationExtension == NULL)
                {
                    deviceInstance->configuration.configurationExtension = (uint8_t *)unionDes;
                }
767 768
                if ((unionDes->common.bDescriptorType == 0x00) ||
                    (unionDes->common.bLength == 0x00)) /* the descriptor data is wrong */
T
tyustli 已提交
769 770 771 772 773 774 775 776 777 778 779 780 781
                {
                    return kStatus_USB_Error;
                }
                deviceInstance->configuration.configurationExtensionLength += unionDes->common.bLength;
                unionDes = (usb_descriptor_union_t *)((uint32_t)unionDes + unionDes->common.bLength);
            }
            else
            {
                break;
            }
        }

        /* interface descriptor */
782
        deviceInstance->configuration.interfaceCount = 0;
T
tyustli 已提交
783 784 785 786
        while ((uint32_t)unionDes < endPos)
        {
            if (unionDes->common.bDescriptorType == USB_DESCRIPTOR_TYPE_INTERFACE)
            {
787
                if (unionDes->interface.bAlternateSetting == 0x00)
T
tyustli 已提交
788 789 790
                {
                    if (deviceInstance->configuration.interfaceCount >= USB_HOST_CONFIG_CONFIGURATION_MAX_INTERFACE)
                    {
791 792
#ifdef HOST_ECHO
                        usb_echo(
T
tyustli 已提交
793 794 795 796 797 798 799 800
                            "Unsupported Device attached\r\n too many interfaces in one configuration, please increase "
                            "the USB_HOST_CONFIG_CONFIGURATION_MAX_INTERFACE value\n");
#endif
                        return kStatus_USB_Error;
                    }
                    interfaceParse =
                        &deviceInstance->configuration.interfaceList[deviceInstance->configuration.interfaceCount];
                    deviceInstance->configuration.interfaceCount++;
801 802 803
                    interfaceParse->alternateSettingNumber = 0;
                    interfaceParse->epCount = 0;
                    interfaceParse->interfaceDesc = &unionDes->interface;
T
tyustli 已提交
804
                    interfaceParse->interfaceExtensionLength = 0;
805 806 807
                    interfaceParse->interfaceExtension = NULL;
                    interfaceParse->interfaceIndex = unionDes->interface.bInterfaceNumber;
                    if (unionDes->common.bLength == 0x00) /* the descriptor data is wrong */
T
tyustli 已提交
808 809 810 811 812 813 814 815 816 817 818 819 820
                    {
                        return kStatus_USB_Error;
                    }
                    unionDes = (usb_descriptor_union_t *)((uint32_t)unionDes + unionDes->common.bLength);
                    while ((uint32_t)unionDes < endPos)
                    {
                        if ((unionDes->common.bDescriptorType != USB_DESCRIPTOR_TYPE_INTERFACE) &&
                            (unionDes->common.bDescriptorType != USB_DESCRIPTOR_TYPE_ENDPOINT))
                        {
                            if (interfaceParse->interfaceExtension == NULL)
                            {
                                interfaceParse->interfaceExtension = (uint8_t *)unionDes;
                            }
821 822
                            if ((unionDes->common.bDescriptorType == 0x00) ||
                                (unionDes->common.bLength == 0x00)) /* the descriptor data is wrong */
T
tyustli 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835
                            {
                                return kStatus_USB_Error;
                            }
                            interfaceParse->interfaceExtensionLength += unionDes->common.bLength;
                            unionDes = (usb_descriptor_union_t *)((uint32_t)unionDes + unionDes->common.bLength);
                        }
                        else
                        {
                            break;
                        }
                    }

                    /* endpoint descriptor */
836
                    if (interfaceParse->interfaceDesc->bNumEndpoints != 0)
T
tyustli 已提交
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
                    {
                        if ((unionDes->common.bDescriptorType != USB_DESCRIPTOR_TYPE_ENDPOINT) ||
                            (interfaceParse->interfaceDesc->bNumEndpoints > USB_HOST_CONFIG_INTERFACE_MAX_EP))
                        {
#ifdef HOST_ECHO
                            usb_echo("interface descriptor error\n");
#endif
                            return kStatus_USB_Error;
                        }
                        for (; interfaceParse->epCount < interfaceParse->interfaceDesc->bNumEndpoints;
                             (interfaceParse->epCount)++)
                        {
                            if (((uint32_t)unionDes >= endPos) ||
                                (unionDes->common.bDescriptorType != USB_DESCRIPTOR_TYPE_ENDPOINT))
                            {
#ifdef HOST_ECHO
                                usb_echo("endpoint descriptor error\n");
#endif
                                return kStatus_USB_Error;
                            }
857 858 859 860 861
                            epParse = (usb_host_ep_t *)&interfaceParse->epList[interfaceParse->epCount];
                            epParse->epDesc = (usb_descriptor_endpoint_t *)unionDes;
                            epParse->epExtensionLength = 0;
                            epParse->epExtension = NULL;
                            if (unionDes->common.bLength == 0x00) /* the descriptor data is wrong */
T
tyustli 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874
                            {
                                return kStatus_USB_Error;
                            }
                            unionDes = (usb_descriptor_union_t *)((uint32_t)unionDes + unionDes->common.bLength);
                            while ((uint32_t)unionDes < endPos)
                            {
                                if ((unionDes->common.bDescriptorType != USB_DESCRIPTOR_TYPE_ENDPOINT) &&
                                    (unionDes->common.bDescriptorType != USB_DESCRIPTOR_TYPE_INTERFACE))
                                {
                                    if (epParse->epExtension == NULL)
                                    {
                                        epParse->epExtension = (uint8_t *)unionDes;
                                    }
875 876
                                    if ((unionDes->common.bDescriptorType == 0x00) ||
                                        (unionDes->common.bLength == 0x00)) /* the descriptor data is wrong */
T
tyustli 已提交
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
                                    {
                                        return kStatus_USB_Error;
                                    }
                                    epParse->epExtensionLength += unionDes->common.bLength;
                                    unionDes =
                                        (usb_descriptor_union_t *)((uint32_t)unionDes + unionDes->common.bLength);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (interfaceParse == NULL)
                    {
                        return kStatus_USB_Error; /* in normal situation this cannot reach */
                    }
                    interfaceParse->alternateSettingNumber++;
                    if (interfaceParse->interfaceExtension == NULL)
                    {
                        interfaceParse->interfaceExtension = (uint8_t *)unionDes;
                    }
903
                    if (unionDes->common.bLength == 0x00) /* the descriptor data is wrong */
T
tyustli 已提交
904 905 906 907 908 909 910 911 912
                    {
                        return kStatus_USB_Error;
                    }
                    interfaceParse->interfaceExtensionLength += unionDes->common.bLength;
                    unionDes = (usb_descriptor_union_t *)((uint32_t)unionDes + unionDes->common.bLength);
                    while ((uint32_t)unionDes < endPos)
                    {
                        if (unionDes->common.bDescriptorType != USB_DESCRIPTOR_TYPE_INTERFACE)
                        {
913 914
                            if ((unionDes->common.bDescriptorType == 0x00) ||
                                (unionDes->common.bLength == 0x00)) /* the descriptor data is wrong */
T
tyustli 已提交
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
                            {
                                return kStatus_USB_Error;
                            }
                            interfaceParse->interfaceExtensionLength += unionDes->common.bLength;
                            unionDes = (usb_descriptor_union_t *)((uint32_t)unionDes + unionDes->common.bLength);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                return kStatus_USB_Error;
            }
        }
    }

935
    for (endPos = 0; endPos < deviceInstance->configuration.interfaceCount; ++endPos)
T
tyustli 已提交
936
    {
937
        deviceInstance->interfaceStatus[endPos] = kStatus_interface_Attached;
T
tyustli 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
    }

    return kStatus_USB_Success;
}

usb_status_t USB_HostAttachDevice(usb_host_handle hostHandle,
                                  uint8_t speed,
                                  uint8_t hubNumber,
                                  uint8_t portNumber,
                                  uint8_t level,
                                  usb_device_handle *deviceHandle)
{
    usb_host_instance_t *hostInstance = (usb_host_instance_t *)hostHandle;
    usb_host_device_instance_t *newInstance;
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
    usb_host_device_instance_t *currentInstance;
#endif
    uint8_t address;
    usb_host_pipe_init_t pipeInit;

    if (hostHandle == NULL)
    {
        return kStatus_USB_InvalidHandle;
    }

/* check whether is the device attached? */
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
    currentInstance = (usb_host_device_instance_t *)hostInstance->deviceList;
    while (currentInstance != NULL)
    {
        if ((currentInstance->hubNumber == hubNumber) && (currentInstance->portNumber == portNumber))
        {
            *deviceHandle = NULL;
#ifdef HOST_ECHO
            usb_echo("device has attached\r\n");
#endif
            return kStatus_USB_Busy;
        }
        else
        {
            currentInstance = currentInstance->next;
        }
    }
#else
    if (hostInstance->deviceList != NULL)
    {
        *deviceHandle = NULL;
        usb_echo("device has attached\r\n");
        return kStatus_USB_Busy;
    }
#endif

    /* Allocate new device instance */
991
    newInstance = (usb_host_device_instance_t *)USB_OsaMemoryAllocate(sizeof(usb_host_device_instance_t));
T
tyustli 已提交
992 993 994 995 996 997 998 999 1000
    if (newInstance == NULL)
    {
#ifdef HOST_ECHO
        usb_echo("allocate dev instance fail\r\n");
#endif
        return kStatus_USB_AllocFail;
    }

    /* new instance fields init */
1001 1002 1003 1004 1005 1006
    newInstance->hostHandle = hostHandle;
    newInstance->speed = speed;
    newInstance->stallRetries = USB_HOST_CONFIG_ENUMERATION_MAX_STALL_RETRIES;
    newInstance->enumRetries = USB_HOST_CONFIG_ENUMERATION_MAX_RETRIES;
    newInstance->setAddress = 0;
    newInstance->deviceAttachState = kStatus_device_Attached;
T
tyustli 已提交
1007 1008 1009 1010
#if ((defined(USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE)) && (USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE > 0U))
    newInstance->deviceDescriptor =
        (usb_descriptor_device_t *)SDK_Malloc(sizeof(usb_descriptor_device_t) + 9, USB_CACHE_LINESIZE);
#else
1011 1012
    newInstance->deviceDescriptor =
        (usb_descriptor_device_t *)USB_OsaMemoryAllocate(sizeof(usb_descriptor_device_t) + 9);
T
tyustli 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021
#endif
    if (newInstance->deviceDescriptor == NULL)
    {
#ifdef HOST_ECHO
        usb_echo("allocate newInstance->deviceDescriptor fail\r\n");
#endif
#if ((defined(USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE)) && (USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE > 0U))
        SDK_Free(newInstance->deviceDescriptor);
#else
1022
        USB_OsaMemoryFree(newInstance->deviceDescriptor);
T
tyustli 已提交
1023
#endif
1024
        USB_OsaMemoryFree(newInstance);
T
tyustli 已提交
1025 1026 1027 1028
        return kStatus_USB_AllocFail;
    }
    newInstance->enumBuffer = (uint8_t *)((uint8_t *)newInstance->deviceDescriptor + sizeof(usb_descriptor_device_t));
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
1029
    newInstance->hubNumber = hubNumber;
T
tyustli 已提交
1030
    newInstance->portNumber = portNumber;
1031
    newInstance->level = level;
T
tyustli 已提交
1032

1033
    if ((speed != USB_SPEED_HIGH) && (level > 1))
T
tyustli 已提交
1034
    {
1035 1036
        newInstance->hsHubNumber = USB_HostHubGetHsHubNumber(hostHandle, hubNumber);
        newInstance->hsHubPort = USB_HostHubGetHsHubPort(hostHandle, hubNumber, portNumber);
T
tyustli 已提交
1037 1038 1039 1040
    }
    else
    {
        newInstance->hsHubNumber = hubNumber;
1041
        newInstance->hsHubPort = portNumber;
T
tyustli 已提交
1042 1043 1044
    }
#endif /* USB_HOST_CONFIG_HUB */

1045
    USB_HostLock();
T
tyustli 已提交
1046 1047
    /* allocate address && insert to the dev list */
    address = USB_HostAllocateDeviceAddress(hostInstance);
1048
    if (address == 0)
T
tyustli 已提交
1049 1050 1051 1052
    {
#ifdef HOST_ECHO
        usb_echo("allocate address fail\r\n");
#endif
1053
        USB_HostUnlock();
T
tyustli 已提交
1054 1055 1056
#if ((defined(USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE)) && (USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE > 0U))
        SDK_Free(newInstance->deviceDescriptor);
#else
1057
        USB_OsaMemoryFree(newInstance->deviceDescriptor);
T
tyustli 已提交
1058
#endif
1059
        USB_OsaMemoryFree(newInstance);
T
tyustli 已提交
1060 1061 1062 1063
        return kStatus_USB_Error;
    }
    newInstance->allocatedAddress = address;

1064
    newInstance->next = (usb_host_device_instance_t *)hostInstance->deviceList;
T
tyustli 已提交
1065
    hostInstance->deviceList = newInstance;
1066 1067
    newInstance->state = kStatus_DEV_Initial;
    USB_HostUnlock();
T
tyustli 已提交
1068 1069

    /* open control pipe */
1070 1071 1072
    pipeInit.devInstance = newInstance;
    pipeInit.pipeType = USB_ENDPOINT_CONTROL;
    pipeInit.direction = 0;
T
tyustli 已提交
1073
    pipeInit.endpointAddress = 0;
1074 1075
    pipeInit.interval = 0;
    pipeInit.maxPacketSize = 8;
T
tyustli 已提交
1076
    pipeInit.numberPerUframe = 0;
1077
    pipeInit.nakCount = USB_HOST_CONFIG_MAX_NAK;
T
tyustli 已提交
1078 1079 1080 1081 1082 1083 1084
    if (USB_HostOpenPipe(hostHandle, &newInstance->controlPipe, &pipeInit) != kStatus_USB_Success)
    {
        /* don't need release resource, resource is released when detach */
        *deviceHandle = newInstance;
#if ((defined(USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE)) && (USB_HOST_CONFIG_BUFFER_PROPERTY_CACHEABLE > 0U))
        SDK_Free(newInstance->deviceDescriptor);
#else
1085
        USB_OsaMemoryFree(newInstance->deviceDescriptor);
T
tyustli 已提交
1086
#endif
1087
        USB_OsaMemoryFree(newInstance);
T
tyustli 已提交
1088 1089 1090 1091
        return kStatus_USB_Error;
    }

    /* start enumeration */
1092 1093
    newInstance->state = kStatus_DEV_GetDes8;
    USB_HostProcessState(newInstance); /* process enumeration state machine */
T
tyustli 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108

    *deviceHandle = newInstance;
    return kStatus_USB_Success;
}

usb_status_t USB_HostDetachDevice(usb_host_handle hostHandle, uint8_t hubNumber, uint8_t portNumber)
{
    usb_host_device_instance_t *deviceInstance;
    usb_host_instance_t *hostInstance = (usb_host_instance_t *)hostHandle;

    if (hostHandle == NULL)
    {
        return kStatus_USB_InvalidHandle;
    }

1109
    USB_HostLock();
T
tyustli 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
/* search for device instance handle */
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
    deviceInstance = (usb_host_device_instance_t *)hostInstance->deviceList;
    while (deviceInstance != NULL)
    {
        if ((deviceInstance->hubNumber == hubNumber) && (deviceInstance->portNumber == portNumber))
        {
            break;
        }
        deviceInstance = deviceInstance->next;
    }
#else
    deviceInstance = (usb_host_device_instance_t *)hostInstance->deviceList;
#endif
1124
    USB_HostUnlock();
T
tyustli 已提交
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
    if (deviceInstance != NULL)
    {
        return USB_HostDetachDeviceInternal(hostHandle, deviceInstance); /* device instance detach */
    }
    return kStatus_USB_Success;
}

usb_status_t USB_HostDetachDeviceInternal(usb_host_handle hostHandle, usb_device_handle deviceHandle)
{
    usb_host_device_instance_t *deviceInstance = (usb_host_device_instance_t *)deviceHandle;
1135
    usb_host_instance_t *hostInstance = (usb_host_instance_t *)hostHandle;
T
tyustli 已提交
1136 1137 1138 1139 1140
    if ((hostHandle == NULL) || (deviceHandle == NULL))
    {
        return kStatus_USB_InvalidHandle;
    }

1141
    deviceInstance->deviceAttachState = kStatus_device_Detached; /* mark the device is detached from host */
T
tyustli 已提交
1142

1143
    if (deviceInstance->state >= kStatus_DEV_Initial) /* device instance is valid */
T
tyustli 已提交
1144 1145
    {
        /* detach internally */
1146
        if (deviceInstance->state < kStatus_DEV_AppUsed) /* enumeration is not done */
T
tyustli 已提交
1147 1148 1149
        {
            if (deviceInstance->controlPipe != NULL)
            {
1150
                USB_HostCancelTransfer(hostInstance, deviceInstance->controlPipe, NULL);
T
tyustli 已提交
1151 1152 1153
            }

            /* remove device instance from host */
1154
            USB_HostRemoveDeviceInstance(hostInstance, deviceInstance);
T
tyustli 已提交
1155 1156
            USB_HostReleaseDeviceResource(hostInstance, deviceInstance);
        }
1157
        else /* enumeration has be done and notifed application */
T
tyustli 已提交
1158
        {
1159
            USB_HostNotifyDevice(deviceInstance, kUSB_HostEventDetach); /* notify application device detach */
T
tyustli 已提交
1160 1161 1162 1163 1164 1165 1166 1167
        }
    }

    return kStatus_USB_Success;
}

uint8_t USB_HostGetDeviceAttachState(usb_device_handle deviceHandle)
{
1168
    return deviceHandle ? ((usb_host_device_instance_t *)deviceHandle)->deviceAttachState : 0x0;
T
tyustli 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
}

usb_status_t USB_HostValidateDevice(usb_host_handle hostHandle, usb_device_handle deviceHandle)
{
    usb_host_device_instance_t *searchDev;

    if (deviceHandle == NULL)
    {
        return kStatus_USB_InvalidParameter;
    }
    /* search for the device */
    searchDev = (usb_host_device_instance_t *)((usb_host_instance_t *)hostHandle)->deviceList;
    while ((searchDev != NULL) && ((usb_device_handle)searchDev != deviceHandle))
    {
        searchDev = searchDev->next;
    }

1186
    if (searchDev)
T
tyustli 已提交
1187 1188 1189 1190 1191 1192 1193 1194
    {
        return kStatus_USB_Success;
    }
    return kStatus_USB_Error;
}

static usb_status_t USB_HostControlBus(usb_host_handle hostHandle, uint8_t controlType)
{
1195
    usb_status_t status = kStatus_USB_Success;
T
tyustli 已提交
1196 1197 1198 1199 1200 1201
    usb_host_instance_t *hostInstance = (usb_host_instance_t *)hostHandle;

    if (hostHandle == NULL)
    {
        return kStatus_USB_InvalidHandle;
    }
1202

T
tyustli 已提交
1203 1204 1205 1206 1207 1208 1209 1210 1211
    status = hostInstance->controllerTable->controllerIoctl(hostInstance->controllerHandle, kUSB_HostBusControl,
                                                            &controlType);

    return status;
}

usb_status_t USB_HostOpenDeviceInterface(usb_device_handle deviceHandle, usb_host_interface_handle interfaceHandle)
{
    usb_host_device_instance_t *deviceInstance = (usb_host_device_instance_t *)deviceHandle;
1212
    usb_host_instance_t *hostInstance = NULL;
T
tyustli 已提交
1213 1214 1215 1216 1217 1218 1219 1220 1221
    uint8_t interfaceIndex;
    uint8_t index = 0;

    if ((deviceHandle == NULL) || (interfaceHandle == NULL))
    {
        return kStatus_USB_InvalidHandle;
    }

    hostInstance = (usb_host_instance_t *)deviceInstance->hostHandle;
1222
    USB_HostLock();
T
tyustli 已提交
1223 1224 1225
    /* check host_instance valid? */
    for (; index < USB_HOST_CONFIG_MAX_HOST; ++index)
    {
1226
        if ((g_UsbHostInstance[index].occupied == 1) &&
T
tyustli 已提交
1227 1228 1229 1230 1231 1232 1233
            ((usb_host_instance_t *)(&g_UsbHostInstance[index]) == (hostInstance)))
        {
            break;
        }
    }
    if (index >= USB_HOST_CONFIG_MAX_HOST)
    {
1234
        USB_HostUnlock();
T
tyustli 已提交
1235 1236 1237 1238 1239 1240
        return kStatus_USB_Error;
    }

    /* check deviceHandle valid? */
    if (USB_HostValidateDevice(hostInstance, deviceHandle) != kStatus_USB_Success)
    {
1241
        USB_HostUnlock();
T
tyustli 已提交
1242 1243 1244 1245 1246 1247 1248 1249
        return kStatus_USB_Error;
    }

    /* search interface and set the interface as opened */
    for (interfaceIndex = 0; interfaceIndex < deviceInstance->configuration.interfaceCount; ++interfaceIndex)
    {
        if (&deviceInstance->configuration.interfaceList[interfaceIndex] == interfaceHandle)
        {
1250
            deviceInstance->interfaceStatus[interfaceIndex] = kStatus_interface_Opened;
T
tyustli 已提交
1251 1252 1253
            break;
        }
    }
1254
    USB_HostUnlock();
T
tyustli 已提交
1255 1256 1257 1258 1259 1260 1261

    return kStatus_USB_Success;
}

usb_status_t USB_HostCloseDeviceInterface(usb_device_handle deviceHandle, usb_host_interface_handle interfaceHandle)
{
    usb_host_device_instance_t *deviceInstance = (usb_host_device_instance_t *)deviceHandle;
1262
    usb_host_instance_t *hostInstance = NULL;
T
tyustli 已提交
1263 1264
    uint8_t interfaceIndex;
    uint8_t removeLabel = 1;
1265
    uint8_t index = 0;
T
tyustli 已提交
1266 1267 1268 1269 1270 1271 1272

    if (deviceHandle == NULL)
    {
        return kStatus_USB_InvalidHandle;
    }

    hostInstance = (usb_host_instance_t *)deviceInstance->hostHandle;
1273
    USB_HostLock();
T
tyustli 已提交
1274 1275 1276
    /* check host_instance valid? */
    for (; index < USB_HOST_CONFIG_MAX_HOST; ++index)
    {
1277
        if ((g_UsbHostInstance[index].occupied == 1) &&
T
tyustli 已提交
1278 1279 1280 1281 1282 1283 1284
            ((usb_host_instance_t *)(&g_UsbHostInstance[index]) == (hostInstance)))
        {
            break;
        }
    }
    if (index >= USB_HOST_CONFIG_MAX_HOST)
    {
1285
        USB_HostUnlock();
T
tyustli 已提交
1286 1287 1288 1289 1290 1291
        return kStatus_USB_Error;
    }

    /* check deviceHandle valid? */
    if (USB_HostValidateDevice(hostInstance, deviceHandle) != kStatus_USB_Success)
    {
1292
        USB_HostUnlock();
T
tyustli 已提交
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
        return kStatus_USB_Error;
    }

    if (interfaceHandle != NULL)
    {
        /* search interface and set the interface as detached */
        for (interfaceIndex = 0; interfaceIndex < deviceInstance->configuration.interfaceCount; ++interfaceIndex)
        {
            if (&deviceInstance->configuration.interfaceList[interfaceIndex] == interfaceHandle)
            {
1303
                deviceInstance->interfaceStatus[interfaceIndex] = kStatus_interface_Detached;
T
tyustli 已提交
1304 1305 1306 1307 1308
                break;
            }
        }
    }

1309
    if (deviceInstance->deviceAttachState == kStatus_device_Detached) /* device is removed from host */
T
tyustli 已提交
1310 1311 1312 1313 1314
    {
        removeLabel = 1;
        /* check all the interfaces of the device are not opened */
        for (interfaceIndex = 0; interfaceIndex < deviceInstance->configuration.interfaceCount; ++interfaceIndex)
        {
1315
            if (deviceInstance->interfaceStatus[interfaceIndex] == kStatus_interface_Opened)
T
tyustli 已提交
1316
            {
1317
                removeLabel = 0;
T
tyustli 已提交
1318 1319 1320
                break;
            }
        }
1321
        if (removeLabel == 1)
T
tyustli 已提交
1322 1323
        {
            /* remove device instance from host */
1324
            USB_HostRemoveDeviceInstance(hostInstance, deviceInstance);
T
tyustli 已提交
1325
        }
1326
        USB_HostUnlock();
T
tyustli 已提交
1327

1328
        if (removeLabel == 1)
T
tyustli 已提交
1329 1330 1331 1332 1333 1334 1335
        {
            USB_HostReleaseDeviceResource((usb_host_instance_t *)deviceInstance->hostHandle,
                                          deviceInstance); /* release device resource */
        }
    }
    else
    {
1336
        USB_HostUnlock();
T
tyustli 已提交
1337 1338 1339 1340 1341 1342 1343
    }

    return kStatus_USB_Success;
}

usb_status_t USB_HostRemoveDevice(usb_host_handle hostHandle, usb_device_handle deviceHandle)
{
1344
    usb_host_instance_t *hostInstance = (usb_host_instance_t *)hostHandle;
T
tyustli 已提交
1345
    usb_host_device_instance_t *deviceInstance = (usb_host_device_instance_t *)deviceHandle;
1346
    uint8_t interfaceIndex = 0;
T
tyustli 已提交
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
    uint8_t level = 0;
    uint8_t devHubNo;
    uint8_t devPortNo;
#endif

    if ((hostHandle == NULL) || (deviceHandle == NULL))
    {
        return kStatus_USB_InvalidHandle;
    }
    if (deviceInstance->hostHandle != hostHandle)
    {
        return kStatus_USB_InvalidParameter;
    }

    if (USB_HostValidateDevice(hostInstance, deviceInstance) == kStatus_USB_Success) /* device is valid */
    {
#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
1365
        devHubNo = deviceInstance->hubNumber;
T
tyustli 已提交
1366
        devPortNo = deviceInstance->portNumber;
1367
        level = deviceInstance->level;
T
tyustli 已提交
1368 1369
#endif

1370 1371
        deviceInstance->deviceAttachState = kStatus_device_Detached;
        if (deviceInstance->state >= kStatus_DEV_Initial) /* device is valid */
T
tyustli 已提交
1372
        {
1373
            if (deviceInstance->state < kStatus_DEV_AppUsed) /* enumeraion is not done or application don't use */
T
tyustli 已提交
1374 1375
            {
                /* detach internally */
1376
                USB_HostDetachDeviceInternal(hostHandle, deviceHandle);
T
tyustli 已提交
1377 1378 1379
            }
            else /* application use the device */
            {
1380
                for (interfaceIndex = 0; interfaceIndex < deviceInstance->configuration.interfaceCount;
T
tyustli 已提交
1381 1382
                     ++interfaceIndex)
                {
1383
                    if (deviceInstance->interfaceStatus[interfaceIndex] == kStatus_interface_Opened)
T
tyustli 已提交
1384 1385 1386 1387 1388 1389 1390 1391
                    {
#ifdef HOST_ECHO
                        usb_echo("error: there is class instance that is not deinited\r\n");
#endif
                        break;
                    }
                }
                /* remove device instance from host */
1392
                USB_HostRemoveDeviceInstance(hostInstance, deviceInstance);
T
tyustli 已提交
1393 1394 1395 1396 1397
                USB_HostReleaseDeviceResource(hostInstance, deviceInstance); /* release resource */
            }
        }

#if ((defined USB_HOST_CONFIG_HUB) && (USB_HOST_CONFIG_HUB))
1398
        if (level == 1)
T
tyustli 已提交
1399
        {
1400 1401
            USB_HostControlBus(hostHandle, kUSB_HostBusReset);   /* reset controller port */
            USB_HostControlBus(hostHandle, kUSB_HostBusRestart); /* restart controller port */
T
tyustli 已提交
1402 1403 1404
        }
        else
        {
1405
            USB_HostHubRemovePort(hostHandle, devHubNo, devPortNo); /* reset hub port */
T
tyustli 已提交
1406 1407 1408 1409 1410 1411 1412 1413 1414
        }
#else
        USB_HostControlBus(hostHandle, kUSB_HostBusReset);   /* reset controller port */
        USB_HostControlBus(hostHandle, kUSB_HostBusRestart); /* restart controller port */
#endif /* USB_HOST_CONFIG_HUB */
    }

    return kStatus_USB_Success;
}