1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "liteos_adapter.h"
17 #include "los_spinlock.h"
18 #ifdef LOSCFG_DRIVERS_HDF_USB_PNP_NOTIFY
19 #include "usb_pnp_notify.h"
20 #endif
21 #include "usbd_wrapper.h"
22 
23 #define HDF_LOG_TAG USB_LITEOS_ADAPTER
24 
25 #define PATH_LEN      24
26 #define DESC_READ_LEN 256
27 #define EP_NUM_MAX    30
28 
29 static bool g_CompleteExit;
30 
31 enum UrbState {
32     URB_INIT_STATE,
33     URB_SUBMIT_STATE,
34     URB_REAP_STATE,
35 };
36 
37 struct Async {
38     struct DListHead asynclist;
39     enum UrbState state;
40     struct UsbDevice *dev;
41     UsbAdapterUrb urb;
42 };
43 
44 struct OsDev {
45     struct DListHead asyncCompleted;
46     UsbAdapterDevice *adapterDevice;
47     SPIN_LOCK_S completeLock;
48     struct OsalMutex completeMux;
49     struct OsalSem cvWait;
50 };
51 
OsAdapterRealloc(void * ptr,size_t oldSize,size_t newSize)52 static void *OsAdapterRealloc(void *ptr, size_t oldSize, size_t newSize)
53 {
54     void *mem;
55 
56     mem = RawUsbMemAlloc(newSize);
57     if (mem == NULL) {
58         HDF_LOGE("%{public}s:%{public}d", __func__, __LINE__);
59         goto OUT;
60     }
61 
62     if (oldSize > 0) {
63         if (memmove_s(mem, newSize, ptr, oldSize) != HDF_SUCCESS) {
64             HDF_LOGE("%{public}s:%{public}d", __func__, __LINE__);
65             RawUsbMemFree(mem);
66             mem = NULL;
67             goto OUT;
68         }
69     }
70 
71     RawUsbMemFree(ptr);
72     ptr = NULL;
73 OUT:
74     return mem;
75 }
76 
UsbFindUrb(const struct Async * urb,struct DListHead * list)77 static bool UsbFindUrb(const struct Async *urb, struct DListHead *list)
78 {
79     bool findFlag = false;
80     struct OsDev *osDev = CONTAINER_OF(list, struct OsDev, asyncCompleted);
81     struct Async *asPos = NULL;
82     struct Async *asTemp = NULL;
83     if (DListIsEmpty(&osDev->asyncCompleted)) {
84         return false;
85     }
86     DLIST_FOR_EACH_ENTRY_SAFE(asPos, asTemp, list, struct Async, asynclist) {
87         if (asPos == urb) {
88             findFlag = true;
89             break;
90         }
91     }
92     return findFlag;
93 }
94 
OsUrbComplete(UsbAdapterUrb * urb)95 static void OsUrbComplete(UsbAdapterUrb *urb)
96 {
97     uint32_t save;
98     struct Async *as = CONTAINER_OF(urb, struct Async, urb);
99     struct UsbDevice *dev = as->dev;
100     if (dev == NULL) {
101         DPRINTFN(0, "dev is null\n");
102         return;
103     }
104     struct OsDev *osDev = (struct OsDev *)dev->privateData;
105     if (osDev == NULL) {
106         DPRINTFN(0, "osDev is null\n");
107         return;
108     }
109     as->state = URB_REAP_STATE;
110     LOS_SpinLockSave(&osDev->completeLock, &save);
111     if (UsbFindUrb(as, &osDev->asyncCompleted) == false) {
112         DListInsertTail(&as->asynclist, &osDev->asyncCompleted);
113         LOS_SpinUnlockRestore(&osDev->completeLock, save);
114         OsalSemPost(&osDev->cvWait);
115     } else {
116         LOS_SpinUnlockRestore(&osDev->completeLock, save);
117     }
118 }
119 
OsSubmitUrb(UsbAdapterUrb * urb,UsbAdapterDevice * adapterDevice,UsbAdapterHostEndpoint * uhe)120 static int32_t OsSubmitUrb(UsbAdapterUrb *urb, UsbAdapterDevice *adapterDevice, UsbAdapterHostEndpoint *uhe)
121 {
122     int32_t err;
123 
124     if ((uhe == NULL) || (urb == NULL) || (adapterDevice == NULL)) {
125         DPRINTFN(0, "invalid param\n");
126         return (-EINVAL);
127     }
128 
129     err = usb_setup_endpoint(adapterDevice, uhe, 1024);
130     if (err < 0) {
131         DPRINTFN(0, "setup failed err:%d\n", err);
132         return (err);
133     }
134     err = usb_submit_urb(urb, 0);
135     return (err);
136 }
137 
OsControlMsg(UsbAdapterUrb * urb)138 static int32_t OsControlMsg(UsbAdapterUrb *urb)
139 {
140     uint16_t actLen = 0;
141     UsbAdapterDevice *adapterDevice = urb->dev;
142     void *buffer = urb->transfer_buffer;
143     UsbAdapterDeviceRequest req;
144 
145     int32_t err = memcpy_s(&req, sizeof(UsbAdapterDeviceRequest), buffer, sizeof(UsbAdapterDeviceRequest));
146     if (err != EOK) {
147         DPRINTFN(0, "%s:%d err=%d\n", __func__, __LINE__, err);
148         err = HDF_ERR_IO;
149         return err;
150     }
151     err = usbd_do_request_flags(
152         adapterDevice, NULL, &req, (char *)buffer + sizeof(req), USB_SHORT_XFER_OK, &actLen, urb->timeout);
153     if (err) {
154         DPRINTFN(1, "OsControlMsg!err:%d\n", err);
155     }
156     urb->actual_length = actLen;
157     if (urb->complete) {
158         (urb->complete)(urb);
159     }
160     return err;
161 }
162 
OsWaitUrb(struct OsDev * osDev)163 static int32_t OsWaitUrb(struct OsDev *osDev)
164 {
165     if (osDev == NULL) {
166         return HDF_FAILURE;
167     }
168     do {
169         OsalSemWait(&osDev->cvWait, HDF_WAIT_FOREVER);
170     } while (!g_CompleteExit && DListIsEmpty(&osDev->asyncCompleted));
171     return HDF_SUCCESS;
172 }
173 
OsReapUrb(const struct UsbDeviceHandle * handle,struct Async ** urb)174 static int32_t OsReapUrb(const struct UsbDeviceHandle *handle, struct Async **urb)
175 {
176     if ((handle == NULL) || (handle->dev == NULL) || (handle->dev->privateData == NULL)) {
177         PRINTK("invalid parmater\n");
178         return HDF_ERR_INVALID_PARAM;
179     }
180     int32_t err = 0;
181     uint32_t save;
182     struct Async *as = NULL;
183     struct UsbDevice *dev = handle->dev;
184     if (dev->privateData == NULL) {
185         PRINTK("invalid parmater\n");
186         return HDF_ERR_INVALID_PARAM;
187     }
188     struct OsDev *osDev = (struct OsDev *)dev->privateData;
189     err = OsWaitUrb(osDev);
190     LOS_SpinLockSave(&osDev->completeLock, &save);
191     if (!DListIsEmpty(&osDev->asyncCompleted)) {
192         as = DLIST_FIRST_ENTRY(&osDev->asyncCompleted, struct Async, asynclist);
193         DListRemove(&as->asynclist);
194     }
195     LOS_SpinUnlockRestore(&osDev->completeLock, save);
196     *urb = as;
197     return err;
198 }
199 
OsDeviceCompare(struct HdfSListNode * listEntry,uint32_t searchKey)200 static bool OsDeviceCompare(struct HdfSListNode *listEntry, uint32_t searchKey)
201 {
202     struct UsbDevice *dev = (struct UsbDevice *)listEntry;
203     if (dev == NULL) {
204         return false;
205     }
206 
207     if ((dev->busNum == (searchKey >> BUS_OFFSET)) && (dev->devAddr == (searchKey & 0xFF))) {
208         return true;
209     }
210 
211     return false;
212 }
213 
OsGetDeviceHandle(struct UsbSession * session,uint8_t busNum,uint8_t usbAddr)214 static struct UsbDeviceHandle *OsGetDeviceHandle(struct UsbSession *session, uint8_t busNum, uint8_t usbAddr)
215 {
216     struct UsbDevice *dev = NULL;
217     struct UsbDeviceHandle *handle = NULL;
218 
219     if (session == NULL) {
220         DPRINTFN(0, "%s:invalid param\n", __func__);
221         return NULL;
222     }
223 
224     OsalMutexLock(&session->lock);
225     dev = (struct UsbDevice *)HdfSListSearch(&session->usbDevs, (busNum << BUS_OFFSET) | usbAddr, OsDeviceCompare);
226     if (dev != NULL) {
227         handle = dev->devHandle;
228         AdapterAtomicInc(&dev->refcnt);
229     }
230     OsalMutexUnlock(&session->lock);
231 
232     return handle;
233 }
234 
OsCallocDeviceHandle(void)235 static struct UsbDeviceHandle *OsCallocDeviceHandle(void)
236 {
237     struct UsbDeviceHandle *handle = NULL;
238 
239     handle = RawUsbMemCalloc(sizeof(*handle));
240     if (handle == NULL) {
241         DPRINTFN(0, "%s: allocate handle failed", __func__);
242         return NULL;
243     }
244 
245     OsalMutexInit(&handle->lock);
246 
247     return handle;
248 }
249 
OsAllocDevice(struct UsbSession * session,struct UsbDeviceHandle * handle)250 static struct UsbDevice *OsAllocDevice(struct UsbSession *session, struct UsbDeviceHandle *handle)
251 {
252     struct UsbDevice *dev = RawUsbMemCalloc(sizeof(*dev));
253     if (dev == NULL) {
254         DPRINTFN(0, "%s:%d no memory", __func__, __LINE__);
255         return NULL;
256     }
257 
258     dev->session = session;
259     dev->devHandle = handle;
260 
261     RawRequestListInit(dev);
262 
263     handle->dev = dev;
264     return dev;
265 }
266 
OsReadDescriptors(struct UsbDevice * dev)267 static int32_t OsReadDescriptors(struct UsbDevice *dev)
268 {
269     size_t allocLen = 0;
270     int32_t ret;
271     if (dev == NULL) {
272         HDF_LOGE("%{public}s:%{public}d dev is NULL!", __func__, __LINE__);
273         return HDF_ERR_INVALID_PARAM;
274     }
275     struct OsDev *osDev = (struct OsDev *)dev->privateData;
276     if ((osDev == NULL) || (osDev->adapterDevice == NULL) || (osDev->adapterDevice->cdesc == NULL)) {
277         HDF_LOGE("%{public}s:%{public}d is NULL!", __func__, __LINE__);
278         return HDF_ERR_INVALID_PARAM;
279     }
280 
281     do {
282         size_t oldLen = allocLen;
283         allocLen += DESC_READ_LEN;
284         dev->descriptors = OsAdapterRealloc(dev->descriptors, oldLen, allocLen);
285         if ((dev->descriptors == NULL) || (dev->descriptorsLength > allocLen)) {
286             DPRINTFN(0, "%s:%d\n", __func__, __LINE__);
287             return HDF_ERR_MALLOC_FAIL;
288         }
289         uint8_t *ptr = (uint8_t *)dev->descriptors + dev->descriptorsLength;
290         if (ptr == NULL) {
291             DPRINTFN(0, "%s:%d ptr is NULL\n", __func__, __LINE__);
292             ret = HDF_ERR_INVALID_PARAM;
293             return ret;
294         }
295         ret = memset_s(ptr, DESC_READ_LEN, 0, DESC_READ_LEN);
296         if (ret != HDF_SUCCESS) {
297             HDF_LOGE("%{public}s:%{public}d memset_s failed", __func__, __LINE__);
298             return HDF_FAILURE;
299         }
300 
301         size_t count = UGETW(osDev->adapterDevice->cdesc->wTotalLength);
302         if (count > DESC_READ_LEN) {
303             ret = HDF_ERR_IO;
304             return ret;
305         }
306         ret = memcpy_s(ptr, DESC_READ_LEN, osDev->adapterDevice->cdesc, count);
307         if (ret != EOK) {
308             DPRINTFN(0, "%s:%d ret=%d\n", __func__, __LINE__, ret);
309             ret = HDF_ERR_IO;
310             return ret;
311         }
312         DPRINTFN(0, "%s:+configdes_size:%d+type:%d\n", __func__, UGETW(osDev->adapterDevice->cdesc->wTotalLength),
313             osDev->adapterDevice->cdesc->bDescriptorType);
314         dev->descriptorsLength += count;
315     } while (dev->descriptorsLength == allocLen);
316 
317     return HDF_SUCCESS;
318 }
319 
OsParseConfigDescriptors(struct UsbDevice * dev)320 static int32_t OsParseConfigDescriptors(struct UsbDevice *dev)
321 {
322     uint8_t i;
323     uint8_t *buffer = NULL;
324     size_t descLen;
325     UsbAdapterDeviceDescriptor *deviceDesc = NULL;
326     struct OsDev *osDev = (struct OsDev *)dev->privateData;
327     deviceDesc = &osDev->adapterDevice->ddesc;
328     uint8_t numConfigs = deviceDesc->bNumConfigurations;
329     if (numConfigs == 0) {
330         return HDF_SUCCESS;
331     }
332     dev->configDescriptors = RawUsbMemAlloc(numConfigs * sizeof(struct UsbDeviceConfigDescriptor));
333     if (dev->configDescriptors == NULL) {
334         DPRINTFN(0, "%s:%d\n", __func__, __LINE__);
335         return HDF_ERR_MALLOC_FAIL;
336     }
337     buffer = (uint8_t *)dev->descriptors;
338     descLen = dev->descriptorsLength;
339 
340     for (i = 0; i < numConfigs; i++) {
341         struct UsbConfigDescriptor *configDesc = NULL;
342         uint16_t configLen;
343 
344         if (descLen < USB_DDK_DT_CONFIG_SIZE) {
345             DPRINTFN(0, "%s:%d read %zu", __func__, __LINE__, descLen);
346             RawUsbMemFree(dev->configDescriptors);
347             return HDF_ERR_IO;
348         }
349         configDesc = (struct UsbConfigDescriptor *)buffer;
350         if ((configDesc->bDescriptorType != USB_DDK_DT_CONFIG) || (configDesc->bLength < USB_DDK_DT_CONFIG_SIZE)) {
351             DPRINTFN(0, "%s:%d config desc error: type 0x%02x, length %u\n", __func__, __LINE__,
352                 configDesc->bDescriptorType, configDesc->bLength);
353             RawUsbMemFree(dev->configDescriptors);
354             return HDF_ERR_IO;
355         }
356         configLen = LE16_TO_CPU(configDesc->wTotalLength);
357         if (configLen < USB_DDK_DT_CONFIG_SIZE) {
358             DPRINTFN(0, "invalid wTotalLength value %u\n", configLen);
359             RawUsbMemFree(dev->configDescriptors);
360             return HDF_ERR_IO;
361         }
362         if (configLen > descLen) {
363             DPRINTFN(0, "%s:%d read %zu/%u\n", __func__, __LINE__, descLen, configLen);
364             configLen = (uint16_t)descLen;
365         }
366         dev->configDescriptors[i].desc = configDesc;
367         dev->configDescriptors[i].actualLen = configLen;
368         buffer += configLen;
369         descLen -= configLen;
370     }
371     return HDF_SUCCESS;
372 }
373 
OsDevAllocInit(void)374 static struct OsDev *OsDevAllocInit(void)
375 {
376     struct OsDev *osDev = NULL;
377     osDev = RawUsbMemCalloc(sizeof(*osDev));
378     if (osDev == NULL) {
379         return NULL;
380     }
381     DListHeadInit(&osDev->asyncCompleted);
382     OsalSemInit(&osDev->cvWait, 0);
383     LOS_SpinInit(&osDev->completeLock);
384     OsalMutexInit(&osDev->completeMux);
385     return osDev;
386 }
387 
OsDevDestory(struct OsDev * osDev)388 static void OsDevDestory(struct OsDev *osDev)
389 {
390     if (osDev == NULL) {
391         DPRINTFN(0, "invalid parma\n");
392         return;
393     }
394     OsalSemDestroy(&osDev->cvWait);
395     OsalMutexDestroy(&osDev->completeMux);
396     RawUsbMemFree(osDev);
397 }
398 
OsInitDevice(struct UsbDevice * dev,uint8_t busNum,uint8_t devAddr)399 static int32_t OsInitDevice(struct UsbDevice *dev, uint8_t busNum, uint8_t devAddr)
400 {
401     struct OsDev *osDev = NULL;
402     int32_t ret;
403 
404     dev->busNum = busNum;
405     dev->devAddr = devAddr;
406     osDev = OsDevAllocInit();
407     if (osDev == NULL) {
408         DPRINTFN(0, "%s:%d osDev  is NULL\n", __func__, __LINE__);
409         return HDF_DEV_ERR_NO_DEVICE;
410     }
411     g_CompleteExit = false;
412 #ifdef LOSCFG_DRIVERS_HDF_USB_PNP_NOTIFY
413     struct UsbGetDevicePara paraData;
414     paraData.type = USB_PNP_DEVICE_ADDRESS_TYPE;
415     paraData.busNum = dev->busNum;
416     paraData.devNum = dev->devAddr;
417     osDev->adapterDevice = UsbPnpNotifyGetUsbDevice(paraData);
418 #else
419     osDev->adapterDevice = NULL;
420 #endif
421     if (osDev->adapterDevice == NULL) {
422         DPRINTFN(0, "%s:%d osDev->adapterDevice is NULL\n", __func__, __LINE__);
423         return HDF_DEV_ERR_NO_DEVICE;
424     }
425 
426     dev->privateData = (void *)osDev;
427     dev->descriptorsLength = 0;
428     ret = OsReadDescriptors(dev);
429     if (ret != HDF_SUCCESS) {
430         DPRINTFN(0, "%s:%d ret=%d\n", __func__, __LINE__, ret);
431         return ret;
432     }
433     ret = OsParseConfigDescriptors(dev);
434     if (ret != HDF_SUCCESS) {
435         DPRINTFN(0, "%s:%d ret=%d\n", __func__, __LINE__, ret);
436         return ret;
437     }
438     ret = memcpy_s(&dev->deviceDescriptor, sizeof(struct UsbDeviceDescriptor), &osDev->adapterDevice->ddesc,
439         USB_DDK_DT_DEVICE_SIZE);
440     if (ret != HDF_SUCCESS) {
441         DPRINTFN(0, "%s:%d ret=%d\n", __func__, __LINE__, ret);
442         ret = HDF_ERR_IO;
443     }
444     return ret;
445 }
446 
OsFreeIsoUrbs(struct UsbHostRequest * request)447 static void OsFreeIsoUrbs(struct UsbHostRequest *request)
448 {
449     struct Async *urb = NULL;
450 
451     for (int32_t i = 0; i < request->numUrbs; i++) {
452         urb = request->isoUrbs[i];
453         if (urb == NULL) {
454             break;
455         }
456         RawUsbMemFree(urb);
457         request->isoUrbs[i] = NULL;
458     }
459 
460     RawUsbMemFree(request->isoUrbs);
461     request->isoUrbs = NULL;
462 }
463 
OsDiscardUrbs(const struct UsbHostRequest * request,int32_t first,int32_t last)464 static void OsDiscardUrbs(const struct UsbHostRequest *request, int32_t first, int32_t last)
465 {
466     UsbAdapterUrb *urb = NULL;
467     struct Async *as = NULL;
468 
469     if ((request == NULL) || (request->devHandle == NULL) || (first > URBS_PER_REQUEST) || (first > last)) {
470         DPRINTFN(0, "%s:%d invalid param", __func__, __LINE__);
471         return;
472     }
473 
474     for (int32_t i = last - 1; i >= first; i--) {
475         if (request->requestType == USB_REQUEST_TYPE_ISOCHRONOUS) {
476             as = (struct Async *)request->isoUrbs[i];
477         } else {
478             as = &(((struct Async *)request->urbs)[i]);
479         }
480         if (as == NULL) {
481             DPRINTFN(0, "discard as null\n");
482             return;
483         }
484         urb = &as->urb;
485         if (as->state == URB_SUBMIT_STATE) {
486             DPRINTFN(0, "usb kill urb\n");
487             usb_kill_urb(urb);
488             DPRINTFN(0, "%s:%d discard request\n", __func__, __LINE__);
489         }
490     }
491 }
492 
OsSubmitControlMsg(struct UsbHostRequest * const request,const UsbAdapterDevice * adapterDevice,const struct UsbDevice * dev)493 static int32_t OsSubmitControlMsg(
494     struct UsbHostRequest * const request, const UsbAdapterDevice *adapterDevice, const struct UsbDevice *dev)
495 {
496     int32_t ret;
497     struct Async *as = NULL;
498     UsbAdapterUrb *urb = NULL;
499     UsbAdapterHostEndpoint *uhe = NULL;
500     if ((request == NULL) || (request->length > MAX_BULK_DATA_BUFFER_LENGTH) || (request->buffer == NULL) ||
501         (adapterDevice == NULL) || (dev == NULL)) {
502         return HDF_ERR_INVALID_PARAM;
503     }
504     uhe = usb_find_host_endpoint((UsbAdapterDevice *)adapterDevice, request->requestType, request->endPoint);
505     if (uhe == NULL) {
506         DPRINTFN(0, "no found endpoint\n");
507         return -1;
508     }
509     if (request->urbs == NULL) {
510         as = RawUsbMemCalloc(sizeof(*as));
511         request->urbs = (void *)as;
512         request->numUrbs = 1;
513     }
514 
515     if (request->urbs == NULL) {
516         DPRINTFN(0, "%s:%d no mem", __func__, __LINE__);
517         return HDF_ERR_MALLOC_FAIL;
518     }
519     as = (struct Async *)request->urbs;
520     DListHeadInit(&as->asynclist);
521     as->dev = (struct UsbDevice *)dev;
522     as->state = URB_SUBMIT_STATE;
523     urb = &as->urb;
524     ret = memset_s(urb, sizeof(*urb), 0, sizeof(*urb));
525     if (ret != HDF_SUCCESS) {
526         HDF_LOGE("%{public}s:%{public}d memset_s failed", __func__, __LINE__);
527         return HDF_FAILURE;
528     }
529 
530     urb->dev = (UsbAdapterDevice *)adapterDevice;
531     urb->endpoint = uhe;
532     urb->timeout = 500;
533     urb->transfer_buffer = request->buffer;
534     urb->context = (void *)request;
535     urb->complete = OsUrbComplete;
536     ret = OsControlMsg(urb);
537     DPRINTFN(0, "OsSubmitControlRequest:ret:%d\n", ret);
538     if (ret) {
539         DPRINTFN(0, "submiturb failed, errno=%d\n", errno);
540         return HDF_ERR_IO;
541     }
542 
543     return HDF_SUCCESS;
544 }
545 
OsSubmitControlRequest(struct UsbHostRequest * request)546 static int32_t OsSubmitControlRequest(struct UsbHostRequest *request)
547 {
548     struct OsDev *osDev = NULL;
549     UsbAdapterDevice *adapterDevice = NULL;
550 
551     if ((request == NULL) || (request->length > MAX_BULK_DATA_BUFFER_LENGTH) || (request->devHandle == NULL) ||
552         (request->buffer == NULL)) {
553         return HDF_ERR_INVALID_PARAM;
554     }
555     struct UsbDeviceHandle *handle = request->devHandle;
556     struct UsbDevice *dev = handle->dev;
557     if (dev) {
558         osDev = (struct OsDev *)dev->privateData;
559     }
560     if (osDev) {
561         adapterDevice = osDev->adapterDevice;
562     }
563 
564     return OsSubmitControlMsg(request, adapterDevice, dev);
565 }
566 
OsSubmitBulkRequestHandleUrb(struct Async * pas,struct UsbHostRequest * request,int32_t bulkBufferLen,int32_t number)567 static int32_t OsSubmitBulkRequestHandleUrb(
568     struct Async *pas, struct UsbHostRequest *request, int32_t bulkBufferLen, int32_t number)
569 {
570     UsbAdapterUrb *urb = NULL;
571 
572     if (bulkBufferLen == 0) {
573         HDF_LOGE("%{public}s:%{public}d bulkBufferLen can not be zero", __func__, __LINE__);
574         return HDF_ERR_INVALID_PARAM;
575     }
576 
577     urb = &pas->urb;
578     urb->context = (void *)request;
579     switch (request->requestType) {
580         case USB_REQUEST_TYPE_BULK:
581             break;
582         case USB_REQUEST_TYPE_INTERRUPT:
583             urb->interval = 50;
584             break;
585         default:
586             DPRINTFN(0, "%s:%d unknown requestType=%u\n", __func__, __LINE__, request->requestType);
587             return HDF_ERR_INVALID_PARAM;
588     }
589     urb->transfer_buffer = request->buffer + (number * bulkBufferLen);
590     urb->complete = OsUrbComplete;
591     if (number == request->numUrbs - 1) {
592         uint32_t len = (uint32_t)(request->length % bulkBufferLen);
593         urb->transfer_buffer_length = (len == 0) ? (uint32_t)bulkBufferLen : len;
594     } else {
595         urb->transfer_buffer_length = (uint32_t)bulkBufferLen;
596     }
597 
598     return HDF_SUCCESS;
599 }
600 
OsSubmitBulkRequestHandle(struct UsbHostRequest * const request,struct Async * const as,int32_t bulkBufferLen)601 static int32_t OsSubmitBulkRequestHandle(
602     struct UsbHostRequest * const request, struct Async * const as, int32_t bulkBufferLen)
603 {
604     struct Async *pas = NULL;
605     int32_t numUrbs = request->numUrbs;
606     struct UsbDevice *dev = request->devHandle->dev;
607     struct OsDev *osDev = (struct OsDev *)dev->privateData;
608     UsbAdapterDevice *adapterDevice = osDev->adapterDevice;
609     UsbAdapterUrb *urb = NULL;
610 
611     UsbAdapterHostEndpoint *uhe = usb_find_host_endpoint(adapterDevice, request->requestType, request->endPoint);
612     if (uhe == NULL) {
613         DPRINTFN(0, "no found endpoint\n");
614         return HDF_DEV_ERR_NO_DEVICE;
615     }
616 
617     int32_t i;
618     for (i = 0, pas = as; i < numUrbs; i++, pas++) {
619         urb = &pas->urb;
620         int32_t ret = memset_s(urb, sizeof(*urb), 0, sizeof(*urb));
621         if (ret != HDF_SUCCESS) {
622             HDF_LOGE("%{public}s:%{public}d memset_s failed", __func__, __LINE__);
623             return HDF_FAILURE;
624         }
625 
626         ret = OsSubmitBulkRequestHandleUrb(pas, request, bulkBufferLen, i);
627         if (ret != HDF_SUCCESS) {
628             return ret;
629         }
630         pas->state = URB_SUBMIT_STATE;
631         DListHeadInit(&pas->asynclist);
632         pas->dev = dev;
633         urb->dev = adapterDevice;
634         urb->endpoint = uhe;
635 
636         ret = OsSubmitUrb(urb, urb->dev, urb->endpoint);
637         if (ret == 0) {
638             continue;
639         }
640         if (i == 0) {
641             DPRINTFN(0, "the first urb failed\n");
642             return HDF_ERR_IO;
643         }
644         OsalMutexLock(&request->lock);
645         request->numRetired += numUrbs - i;
646         if (errno != EREMOTEIO) {
647             request->reqStatus = USB_REQUEST_ERROR;
648         }
649         OsDiscardUrbs(request, 0, i);
650         OsalMutexUnlock(&request->lock);
651         return HDF_SUCCESS;
652     }
653 
654     return HDF_SUCCESS;
655 }
656 
OsSubmitBulkRequest(struct UsbHostRequest * const request)657 static int32_t OsSubmitBulkRequest(struct UsbHostRequest * const request)
658 {
659     struct Async *as = NULL;
660     uint32_t bulkBufferLen;
661     int32_t numUrbs;
662 
663     if ((request == NULL) || (request->devHandle == NULL)) {
664         DPRINTFN(0, "%s: invalid param", __func__);
665         return HDF_ERR_INVALID_PARAM;
666     }
667 
668     if (request->length > MAX_BULK_DATA_BUFFER_LENGTH || request->length <= 0) {
669         DPRINTFN(0, "Bulk request size err\n");
670         return HDF_FAILURE;
671     }
672 
673     if (request->devHandle->caps & USB_ADAPTER_CAP_BULK_SCATTER_GATHER) {
674         bulkBufferLen = request->length ? request->length : 1;
675     } else {
676         bulkBufferLen = MAX_BULK_DATA_BUFFER_LENGTH;
677     }
678     if (request->length < bulkBufferLen) {
679         numUrbs = 1;
680     } else {
681         numUrbs = (request->length + bulkBufferLen - 1) / bulkBufferLen;
682     }
683     if (request->urbs == NULL) {
684         as = RawUsbMemCalloc(sizeof(*as));
685         request->urbs = (void *)as;
686     } else if (numUrbs > 1) {
687         RawUsbMemFree(request->urbs);
688         as = RawUsbMemCalloc(numUrbs * sizeof(*as));
689         request->urbs = (void *)as;
690     }
691     if (request->urbs == NULL) {
692         DPRINTFN(0, "%s:%d no mem", __func__, __LINE__);
693         return HDF_ERR_MALLOC_FAIL;
694     }
695     as = (struct Async *)request->urbs;
696     request->numUrbs = numUrbs;
697     request->numRetired = 0;
698     request->reqStatus = USB_REQUEST_COMPLETED;
699 
700     return OsSubmitBulkRequestHandle(request, as, bulkBufferLen);
701 }
702 
OsAllocIsoUrbs(struct UsbHostRequest * request,int32_t numUrbs,struct Async ** ass)703 static int32_t OsAllocIsoUrbs(struct UsbHostRequest *request, int32_t numUrbs, struct Async **ass)
704 {
705     struct Async *as = NULL;
706     unsigned char *urbBuffer = request->buffer;
707     int32_t numPacketsLeft = request->numIsoPackets;
708     int32_t packetIdx = 0;
709     int32_t i, j;
710 
711     UsbPipeType pipeType = request->requestType;
712     unsigned char endPoint = request->endPoint;
713     struct UsbDeviceHandle *handle = request->devHandle;
714     struct UsbDevice *dev = handle->dev;
715     struct OsDev *osDev = (struct OsDev *)dev->privateData;
716     UsbAdapterDevice *adapterDevice = osDev->adapterDevice;
717     UsbAdapterHostEndpoint *uhe = NULL;
718     uhe = usb_find_host_endpoint(adapterDevice, pipeType, endPoint);
719     if (uhe == NULL) {
720         DPRINTFN(0, "no found endpoint\n");
721         return HDF_DEV_ERR_NO_DEVICE;
722     }
723 
724     for (i = 0; i < numUrbs; i++) {
725         UsbAdapterUrb *urb = NULL;
726         int32_t numPackets = MIN(numPacketsLeft, MAX_ISO_PACKETS_PER_URB);
727         as = RawUsbMemCalloc(sizeof(struct Async));
728         if (as == NULL) {
729             OsFreeIsoUrbs(request);
730             return HDF_ERR_MALLOC_FAIL;
731         }
732         ass[i] = as;
733         urb = &as->urb;
734         for (j = 0; j < numPackets; j++) {
735             unsigned int packetLen = request->isoPacketDesc[packetIdx++].length;
736             urb->transfer_buffer_length += packetLen;
737             urb->iso_frame_desc[j].length = packetLen;
738         }
739         urb->endpoint = uhe;
740         urb->number_of_packets = (unsigned int)numPackets;
741         urb->transfer_buffer = urbBuffer;
742         urb->context = request;
743         urbBuffer += urb->transfer_buffer_length;
744         numPacketsLeft -= numPackets;
745     }
746 
747     return HDF_SUCCESS;
748 }
749 
OsSubmitIsoUrbs(struct UsbHostRequest * request,int32_t numUrbs,struct Async ** pUrbs)750 static int32_t OsSubmitIsoUrbs(struct UsbHostRequest *request, int32_t numUrbs, struct Async **pUrbs)
751 {
752     for (int32_t i = 0; i < numUrbs; i++) {
753         UsbAdapterUrb *urb = &(pUrbs[i]->urb);
754         int32_t ret = OsSubmitUrb(urb, urb->dev, urb->endpoint);
755         DPRINTFN(0, "submitUrb:%d errno=%d\n", ret, errno);
756         if (ret == 0) {
757             continue;
758         }
759 
760         if (errno == ENODEV) {
761             ret = HDF_DEV_ERR_NO_DEVICE;
762         } else {
763             DPRINTFN(0, "%s:%d submit iso urb failed errno=%d\n", __func__, __LINE__, errno);
764             ret = HDF_ERR_IO;
765         }
766 
767         if (i == 0) {
768             DPRINTFN(0, "first URB failed");
769             OsFreeIsoUrbs(request);
770             return ret;
771         }
772 
773         OsalMutexLock(&request->lock);
774         request->reqStatus = USB_REQUEST_ERROR;
775         request->numRetired += numUrbs - i;
776         if (request->numRetired == numUrbs) {
777             RawUsbMemFree(pUrbs);
778             request->isoUrbs = NULL;
779         }
780         OsalMutexUnlock(&request->lock);
781 
782         break;
783     }
784 
785     return HDF_SUCCESS;
786 }
787 
OsSubmitIsoRequest(struct UsbHostRequest * request)788 static int32_t OsSubmitIsoRequest(struct UsbHostRequest *request)
789 {
790     unsigned int totalLen = 0;
791 
792     if ((request == NULL) || (request->devHandle == NULL) || (request->numIsoPackets < 1)) {
793         DPRINTFN(0, "%s:%d invalid param", __func__, __LINE__);
794         return HDF_ERR_INVALID_PARAM;
795     }
796 
797     if (request->length > MAX_ISO_DATA_BUFFER_LEN) {
798         DPRINTFN(0, "%s:%d request length exceed the maximum", __func__, __LINE__);
799         return HDF_ERR_NOT_SUPPORT;
800     }
801 
802     for (int32_t i = 0; i < request->numIsoPackets; i++) {
803         unsigned int packetLen = request->isoPacketDesc[i].length;
804         if (packetLen > MAX_ISO_DATA_BUFFER_LEN) {
805             DPRINTFN(0, "%s:%d packet length: %u exceeds maximum: %u\n", __func__, __LINE__, packetLen,
806                 MAX_ISO_DATA_BUFFER_LEN);
807             return HDF_ERR_INVALID_PARAM;
808         }
809         totalLen += packetLen;
810     }
811     if (request->length < totalLen) {
812         DPRINTFN(0, "%s:%d invalid param", __func__, __LINE__);
813         return HDF_ERR_INVALID_PARAM;
814     }
815     int32_t numUrbs = (request->numIsoPackets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
816     struct Async **pUrbs = RawUsbMemCalloc(numUrbs * sizeof(struct Async *));
817     if (pUrbs == NULL) {
818         DPRINTFN(0, "%s:%d RawUsbMemCalloc pUrbs failed", __func__, __LINE__);
819         return HDF_ERR_MALLOC_FAIL;
820     }
821     request->isoUrbs = (void **)pUrbs;
822     request->numUrbs = numUrbs;
823     request->numRetired = 0;
824     request->isoPacketOffset = 0;
825     int32_t ret = OsAllocIsoUrbs(request, numUrbs, pUrbs);
826     if (ret != HDF_SUCCESS) {
827         DPRINTFN(0, "%s:%d alloc iso urbs failed", __func__, __LINE__);
828         return ret;
829     }
830 
831     return OsSubmitIsoUrbs(request, numUrbs, pUrbs);
832 }
833 
OsControlCompletion(struct UsbHostRequest * request,struct Async * as)834 static int32_t OsControlCompletion(struct UsbHostRequest *request, struct Async *as)
835 {
836     int32_t status;
837     UsbAdapterUrb *urb = &as->urb;
838 
839     OsalMutexLock(&request->lock);
840     request->numRetired++;
841     request->actualLength += (int)urb->actual_length;
842     if (request->reqStatus == USB_REQUEST_CANCELLED) {
843         OsalMutexUnlock(&request->lock);
844         as->state = URB_INIT_STATE;
845         return RawHandleRequestCompletion(request, USB_REQUEST_CANCELLED);
846     }
847 
848     switch (urb->status) {
849         case 0:
850             status = USB_REQUEST_COMPLETED;
851             break;
852         case -ENOENT:
853             status = USB_REQUEST_CANCELLED;
854             break;
855         case -EPIPE:
856             DPRINTFN(0, "%s:%d unsupported control request", __func__, __LINE__);
857             status = USB_REQUEST_STALL;
858             break;
859         case -EOVERFLOW:
860             DPRINTFN(0, "%s:%d overflow actualLength=%d\n", __func__, __LINE__, urb->actual_length);
861             status = USB_REQUEST_OVERFLOW;
862             break;
863         case -ENODEV:
864         case -ESHUTDOWN:
865             DPRINTFN(0, "device removed");
866             status = USB_REQUEST_NO_DEVICE;
867             break;
868         default:
869             DPRINTFN(0, "%s:%d urb status=%d\n", __func__, __LINE__, urb->status);
870             status = USB_REQUEST_ERROR;
871             break;
872     }
873     OsalMutexUnlock(&request->lock);
874     as->state = URB_INIT_STATE;
875     return RawHandleRequestCompletion(request, status);
876 }
877 
OsIsoRequestDesStatus(struct UsbHostRequest * request,UsbAdapterUrb * urb)878 static void OsIsoRequestDesStatus(struct UsbHostRequest *request, UsbAdapterUrb *urb)
879 {
880     uint32_t i;
881     UsbAdapterIsoPacketDescriptor *urbDesc = NULL;
882     struct UsbIsoPacketDesc *requestDesc = NULL;
883 
884     for (i = 0; i < urb->number_of_packets; i++) {
885         urbDesc = &urb->iso_frame_desc[i];
886         requestDesc = &request->isoPacketDesc[request->isoPacketOffset++];
887 
888         switch (urbDesc->status) {
889             case HDF_SUCCESS:
890                 requestDesc->status = USB_REQUEST_COMPLETED;
891                 break;
892             case -ENODEV:
893             case -ESHUTDOWN:
894                 requestDesc->status = USB_REQUEST_NO_DEVICE;
895                 break;
896             case -EPIPE:
897                 requestDesc->status = USB_REQUEST_STALL;
898                 break;
899             case -EOVERFLOW:
900                 requestDesc->status = USB_REQUEST_OVERFLOW;
901                 break;
902             default:
903                 requestDesc->status = USB_REQUEST_ERROR;
904                 break;
905         }
906         DPRINTFN(0, "%s:%d urb status=%d-%d\n", __func__, __LINE__, i, urbDesc->status);
907 
908         requestDesc->actualLength = urbDesc->actual_length;
909     }
910 }
911 
OsIsoCompletion(struct UsbHostRequest * request,struct Async * as)912 static int32_t OsIsoCompletion(struct UsbHostRequest *request, struct Async *as)
913 {
914     UsbRequestStatus status;
915     int32_t urbIndex = 0;
916     int32_t numUrbs;
917     UsbAdapterUrb *urb = &as->urb;
918 
919     if (request == NULL) {
920         DPRINTFN(0, "%s:%d invalid param", __func__, __LINE__);
921         return HDF_ERR_INVALID_PARAM;
922     }
923 
924     numUrbs = request->numUrbs;
925     OsalMutexLock(&request->lock);
926     for (int32_t i = 0; i < numUrbs; i++) {
927         if (urb == request->isoUrbs[i]) {
928             urbIndex = i + 1;
929             break;
930         }
931     }
932     if (urbIndex == 0) {
933         DPRINTFN(0, "%s:%d urbIndex is zero", __func__, __LINE__);
934         OsalMutexUnlock(&request->lock);
935         return HDF_ERR_BAD_FD;
936     }
937 
938     OsIsoRequestDesStatus(request, urb);
939     request->numRetired++;
940     if (request->reqStatus != USB_REQUEST_COMPLETED) {
941         if (request->numRetired == numUrbs) {
942             OsFreeIsoUrbs(request);
943             OsalMutexUnlock(&request->lock);
944             return RawHandleRequestCompletion(request, USB_REQUEST_ERROR);
945         }
946         goto OUT;
947     }
948 
949     status = USB_REQUEST_COMPLETED;
950     if (urb->status == -ESHUTDOWN) {
951         status = USB_REQUEST_NO_DEVICE;
952     } else if (!((urb->status == HDF_SUCCESS) || (urb->status == -ENOENT) || (urb->status == -ECONNRESET))) {
953         status = USB_REQUEST_ERROR;
954     }
955 
956     if (request->numRetired == numUrbs) {
957         DPRINTFN(0, "%s:%d all URBs reaped for complete", __func__, __LINE__);
958         OsFreeIsoUrbs(request);
959         OsalMutexUnlock(&request->lock);
960         return RawHandleRequestCompletion(request, status);
961     }
962 OUT:
963     OsalMutexUnlock(&request->lock);
964     return HDF_SUCCESS;
965 }
966 
OsProcessAbnormalReap(struct UsbHostRequest * request,const UsbAdapterUrb * urb)967 static int32_t OsProcessAbnormalReap(struct UsbHostRequest *request, const UsbAdapterUrb *urb)
968 {
969     if (urb->actual_length > 0) {
970         unsigned char *target = request->buffer + request->actualLength;
971         if (urb->transfer_buffer != target) {
972             if (memmove_s(target, urb->actual_length, urb->transfer_buffer, urb->actual_length) != EOK) {
973                 DPRINTFN(0, "%s: memmove_s failed, ret=%d", __func__, ret);
974             }
975         }
976         request->actualLength += urb->actual_length;
977     }
978     if (request->numRetired == request->numUrbs) {
979         return HDF_SUCCESS;
980     }
981 
982     return HDF_ERR_IO;
983 }
984 
OsUrbStatusToRequestStatus(struct UsbHostRequest * request,const UsbAdapterUrb * urb)985 static int32_t OsUrbStatusToRequestStatus(struct UsbHostRequest *request, const UsbAdapterUrb *urb)
986 {
987     int32_t ret;
988 
989     switch (urb->status) {
990         case 0:
991             ret = HDF_SUCCESS;
992             break;
993         case -ESHUTDOWN:
994             DPRINTFN(0, "%s:%d device is removed", __func__, __LINE__);
995             request->reqStatus = USB_REQUEST_NO_DEVICE;
996             ret = HDF_DEV_ERR_NO_DEVICE;
997             break;
998         case -EPIPE:
999             if (request->reqStatus == USB_REQUEST_COMPLETED) {
1000                 request->reqStatus = USB_REQUEST_STALL;
1001             }
1002             ret = HDF_DEV_ERR_NO_DEVICE;
1003             break;
1004         case -EOVERFLOW:
1005             DPRINTFN(0, "%s:%d overflow error, actualLength=%d\n", __func__, __LINE__, urb->actual_length);
1006             if (request->reqStatus == USB_REQUEST_COMPLETED) {
1007                 request->reqStatus = USB_REQUEST_OVERFLOW;
1008             }
1009             ret = HDF_FAILURE;
1010             break;
1011         case -ECONNRESET:
1012             ret = HDF_DEV_ERR_OP;
1013             if (request->reqStatus == USB_REQUEST_COMPLETED) {
1014                 request->reqStatus = USB_REQUEST_CANCELLED;
1015             }
1016             break;
1017         default:
1018             DPRINTFN(0, "unknown urb status %d\n", urb->status);
1019             if (request->reqStatus == USB_REQUEST_COMPLETED) {
1020                 request->reqStatus = USB_REQUEST_ERROR;
1021             }
1022             ret = HDF_FAILURE;
1023             break;
1024     }
1025 
1026     return ret;
1027 }
1028 
OsBulkCompletion(struct UsbHostRequest * const request,struct Async * const as)1029 static int32_t OsBulkCompletion(struct UsbHostRequest * const request, struct Async * const as)
1030 {
1031     int32_t ret;
1032     int32_t urbIdx = as - (struct Async *)request->urbs;
1033     const UsbAdapterUrb *urb = &as->urb;
1034 
1035     OsalMutexLock(&request->lock);
1036     request->numRetired++;
1037     if (request->reqStatus != USB_REQUEST_COMPLETED) {
1038         if (OsProcessAbnormalReap(request, urb) == HDF_SUCCESS) {
1039             goto COMPLETED;
1040         } else {
1041             goto OUT;
1042         }
1043     }
1044     request->actualLength += urb->actual_length;
1045     ret = OsUrbStatusToRequestStatus(request, urb);
1046     if (ret == HDF_DEV_ERR_NO_DEVICE) {
1047         goto CANCEL;
1048     } else if (ret == HDF_FAILURE) {
1049         goto COMPLETED;
1050     }
1051 
1052     if (request->numRetired == request->numUrbs) {
1053         goto COMPLETED;
1054     } else if (urb->actual_length < urb->transfer_buffer_length) {
1055         if (request->reqStatus == USB_REQUEST_COMPLETED) {
1056             request->reqStatus = USB_REQUEST_COMPLETED_SHORT;
1057         }
1058     } else {
1059         goto OUT;
1060     }
1061 
1062 CANCEL:
1063     if (request->numRetired == request->numUrbs) {
1064         goto COMPLETED;
1065     }
1066     OsDiscardUrbs(request, urbIdx + 1, request->numUrbs);
1067 
1068 OUT:
1069     OsalMutexUnlock(&request->lock);
1070     return HDF_SUCCESS;
1071 
1072 COMPLETED:
1073     OsalMutexUnlock(&request->lock);
1074     as->state = URB_INIT_STATE;
1075     return RawHandleRequestCompletion(request, request->reqStatus);
1076 }
1077 
OsFreeRequest(const struct UsbHostRequest * request)1078 static int32_t OsFreeRequest(const struct UsbHostRequest *request)
1079 {
1080     int32_t retry = 0;
1081     if (request == NULL) {
1082         DPRINTFN(0, "%s:%d invalid param", __func__, __LINE__);
1083         return HDF_ERR_INVALID_PARAM;
1084     }
1085 
1086     while (true) {
1087         OsalMSleep(20);
1088         if (request->numUrbs != request->numRetired) {
1089             if (++retry > 10) {
1090                 DPRINTFN(0, "request busy numUrbs:%d+numretired:%d\n", request->numUrbs, request->numRetired);
1091                 return HDF_ERR_DEVICE_BUSY;
1092             }
1093             continue;
1094         } else {
1095             break;
1096         }
1097     }
1098 
1099     return HDF_SUCCESS;
1100 }
1101 
AdapterInit(const struct UsbSession * session)1102 static int32_t AdapterInit(const struct UsbSession *session)
1103 {
1104     (void)session;
1105     return HDF_SUCCESS;
1106 }
1107 
AdapterExit(const struct UsbSession * session)1108 static void AdapterExit(const struct UsbSession *session)
1109 {
1110     (void)session;
1111     return;
1112 }
1113 
AdapterOpenDevice(struct UsbSession * session,uint8_t busNum,uint8_t usbAddr)1114 static struct UsbDeviceHandle *AdapterOpenDevice(struct UsbSession *session, uint8_t busNum, uint8_t usbAddr)
1115 {
1116     int32_t ret;
1117     struct UsbDevice *dev = NULL;
1118     struct UsbDeviceHandle *handle = NULL;
1119 
1120     handle = OsGetDeviceHandle(session, busNum, usbAddr);
1121     if (handle != NULL) {
1122         return handle;
1123     }
1124     handle = OsCallocDeviceHandle();
1125     if (handle == NULL) {
1126         DPRINTFN(0, "%s: Calloc Device Handle failed", __func__);
1127         return NULL;
1128     }
1129     dev = OsAllocDevice(session, handle);
1130     if (dev == NULL) {
1131         DPRINTFN(0, "%s: OsAllocDevice failed\n", __func__);
1132         goto ERR;
1133     }
1134     ret = OsInitDevice(dev, busNum, usbAddr);
1135     if (ret) {
1136         DPRINTFN(0, "%s: OsInitDevice failed ret=%d\n", __func__, ret);
1137         RawUsbMemFree(dev->privateData);
1138         RawUsbMemFree(dev);
1139         goto ERR;
1140     }
1141     OsalAtomicSet(&dev->refcnt, 1);
1142     OsalMutexLock(&session->lock);
1143     HdfSListAdd(&session->usbDevs, &dev->list);
1144     OsalMutexUnlock(&session->lock);
1145     return handle;
1146 ERR:
1147     OsalMutexDestroy(&handle->lock);
1148     RawUsbMemFree(handle);
1149     return NULL;
1150 }
1151 
AdapterCloseDevice(struct UsbDeviceHandle * handle)1152 static void AdapterCloseDevice(struct UsbDeviceHandle *handle)
1153 {
1154     struct UsbDevice *dev = NULL;
1155 
1156     if ((handle == NULL) || (handle->dev == NULL)) {
1157         DPRINTFN(0, "%s:%d invalid param", __func__, __LINE__);
1158         return;
1159     }
1160     if (RawKillSignal(handle, 0) != HDF_SUCCESS) {
1161         HDF_LOGE("%{public}s:%{public}d RawKillSignal failed", __func__, __LINE__);
1162     }
1163     dev = handle->dev;
1164     if (AdapterAtomicDec(&dev->refcnt)) {
1165         return;
1166     }
1167     if (dev->session == NULL) {
1168         return;
1169     }
1170     OsalMutexLock(&dev->session->lock);
1171     HdfSListRemove(&dev->session->usbDevs, &dev->list);
1172     OsalMutexUnlock(&dev->session->lock);
1173 
1174     if (dev->configDescriptors) {
1175         RawUsbMemFree(dev->configDescriptors);
1176     }
1177     if (dev->descriptors) {
1178         RawUsbMemFree(dev->descriptors);
1179     }
1180     if (dev->privateData) {
1181         OsDevDestory(dev->privateData);
1182         dev->privateData = NULL;
1183     }
1184     RawUsbMemFree(dev);
1185 
1186     OsalMutexDestroy(&handle->lock);
1187     RawUsbMemFree(handle);
1188     handle = NULL;
1189 }
1190 
AdapterGetConfigDescriptor(const struct UsbDevice * dev,uint8_t configIndex,void * buffer,size_t len)1191 static int32_t AdapterGetConfigDescriptor(const struct UsbDevice *dev, uint8_t configIndex, void *buffer, size_t len)
1192 {
1193     struct OsDev *osDev = (struct OsDev *)dev->privateData;
1194     UsbAdapterDevice *adapterDevice = osDev->adapterDevice;
1195     size_t count;
1196     if ((buffer == NULL) || (len == 0) || (adapterDevice == NULL) || (adapterDevice->cdesc == NULL)) {
1197         DPRINTFN(0, "invalid param is NULL");
1198         return HDF_ERR_INVALID_PARAM;
1199     }
1200     count = UGETW(adapterDevice->cdesc->wTotalLength);
1201     if (count > len) {
1202         DPRINTFN(0, "count length is error");
1203         return HDF_ERR_IO;
1204     }
1205     if (memcpy_s(buffer, len, adapterDevice->cdesc, count) != EOK) {
1206         DPRINTFN(0, "memcpy_s fail");
1207         return HDF_ERR_IO;
1208     }
1209     return (int32_t)len;
1210 }
1211 
AdapterGetConfiguration(const struct UsbDeviceHandle * handle,uint8_t * activeConfig)1212 static int32_t AdapterGetConfiguration(const struct UsbDeviceHandle *handle, uint8_t *activeConfig)
1213 {
1214     struct UsbDevice *dev = handle->dev;
1215     struct OsDev *osDev = (struct OsDev *)dev->privateData;
1216     UsbAdapterDevice *adapterDevice = osDev->adapterDevice;
1217 
1218     if (adapterDevice != NULL) {
1219         *activeConfig = adapterDevice->curr_config_index;
1220     }
1221 
1222     return HDF_SUCCESS;
1223 }
1224 
AdapterSetConfiguration(struct UsbDeviceHandle * handle,int32_t activeConfig)1225 static int32_t AdapterSetConfiguration(struct UsbDeviceHandle *handle, int32_t activeConfig)
1226 {
1227     struct UsbDevice *dev = handle->dev;
1228     struct OsDev *osDev = (struct OsDev *)dev->privateData;
1229     UsbAdapterDevice *adapterDevice = osDev->adapterDevice;
1230 
1231     if (adapterDevice->flags.usb_mode != USB_MODE_HOST) {
1232         return HDF_DEV_ERR_DEV_INIT_FAIL;
1233     }
1234     if ((activeConfig < 0) || (activeConfig >= (int)adapterDevice->curr_config_no)) {
1235         return HDF_ERR_INVALID_PARAM;
1236     }
1237     if (activeConfig == adapterDevice->curr_config_index) {
1238         return HDF_SUCCESS;
1239     }
1240     if (usbd_set_config_index(adapterDevice, activeConfig) != 0) {
1241         return HDF_ERR_IO;
1242     }
1243 
1244     return HDF_SUCCESS;
1245 }
1246 
AdapterClaimInterface(const struct UsbDeviceHandle * handle,unsigned int interfaceNumber)1247 static int32_t AdapterClaimInterface(const struct UsbDeviceHandle *handle, unsigned int interfaceNumber)
1248 {
1249     (void)handle;
1250     (void)interfaceNumber;
1251     return HDF_SUCCESS;
1252 }
1253 
AdapterReleaseInterface(const struct UsbDeviceHandle * handle,unsigned int interfaceNumber)1254 static int32_t AdapterReleaseInterface(const struct UsbDeviceHandle *handle, unsigned int interfaceNumber)
1255 {
1256     (void)handle;
1257     (void)interfaceNumber;
1258     return HDF_SUCCESS;
1259 }
1260 
AdapterSetInterface(const struct UsbDeviceHandle * handle,uint8_t interface,uint8_t altSetting)1261 static int32_t AdapterSetInterface(const struct UsbDeviceHandle *handle, uint8_t interface, uint8_t altSetting)
1262 {
1263     struct UsbDevice *dev = handle->dev;
1264     struct OsDev *osDev = (struct OsDev *)dev->privateData;
1265     UsbAdapterDevice *adapterDevice = osDev->adapterDevice;
1266 
1267     if (adapterDevice->flags.usb_mode != USB_MODE_HOST) {
1268         return HDF_DEV_ERR_DEV_INIT_FAIL;
1269     }
1270     DPRINTFN(0, "altSetting interfaceId:%d+altSetting:%d\n", interface, altSetting);
1271     if (usb_set_interface(adapterDevice, interface, altSetting)) {
1272         return HDF_ERR_IO;
1273     }
1274 
1275     return HDF_SUCCESS;
1276 }
1277 
AdapterClearHalt(const struct UsbDeviceHandle * handle,unsigned int endPoint)1278 static int32_t AdapterClearHalt(const struct UsbDeviceHandle *handle, unsigned int endPoint)
1279 {
1280     struct UsbDevice *dev = handle->dev;
1281     struct OsDev *osDev = (struct OsDev *)dev->privateData;
1282     UsbAdapterDevice *adapterDevice = osDev->adapterDevice;
1283     int32_t ret;
1284     UsbAdapterHostEndpoint *uhe = usb_find_host_endpoint(adapterDevice, PIPE_BULK, endPoint);
1285     if (uhe == NULL) {
1286         printf("no found uhe\n");
1287         return -1;
1288     }
1289     ret = usb_clear_halt(adapterDevice, uhe);
1290     return ret;
1291 }
1292 
AdapterResetDevice(const struct UsbDeviceHandle * handle)1293 static int32_t AdapterResetDevice(const struct UsbDeviceHandle *handle)
1294 {
1295     (void)handle;
1296     return HDF_SUCCESS;
1297 }
1298 
AdapterAllocRequest(const struct UsbDeviceHandle * handle,int32_t isoPackets,size_t length)1299 static struct UsbHostRequest *AdapterAllocRequest(
1300     const struct UsbDeviceHandle *handle, int32_t isoPackets, size_t length)
1301 {
1302     (void)handle;
1303     size_t allocSize;
1304     struct UsbHostRequest *request = NULL;
1305 
1306     allocSize = sizeof(struct UsbHostRequest) + (sizeof(struct UsbIsoPacketDesc) * (size_t)isoPackets) +
1307         (sizeof(unsigned char) * length);
1308     request = RawUsbMemCalloc(allocSize);
1309     if (request == NULL) {
1310         HDF_LOGE("%{public}s RawMemAlloc fail", __func__);
1311         return NULL;
1312     }
1313     request->numIsoPackets = isoPackets;
1314     request->buffer = (unsigned char *)request + allocSize - length;
1315     request->bufLen = (int)length;
1316     return request;
1317 }
1318 
AdapterFreeRequest(struct UsbHostRequest * request)1319 static int32_t AdapterFreeRequest(struct UsbHostRequest *request)
1320 {
1321     if (request == NULL) {
1322         DPRINTFN(0, "%s:%d invalid param", __func__, __LINE__);
1323         return HDF_ERR_INVALID_PARAM;
1324     }
1325     if (request->numUrbs > request->numRetired) {
1326         OsDiscardUrbs(request, request->numRetired, request->numUrbs);
1327         int32_t ret = OsFreeRequest(request);
1328         if (ret != HDF_SUCCESS) {
1329             return ret;
1330         }
1331     }
1332     if (request->urbs) {
1333         RawUsbMemFree(request->urbs);
1334         request->urbs = NULL;
1335     }
1336     RawUsbMemFree((void *)request);
1337     return HDF_SUCCESS;
1338 }
1339 
AdapterSubmitRequest(struct UsbHostRequest * request)1340 static int32_t AdapterSubmitRequest(struct UsbHostRequest *request)
1341 {
1342     int32_t ret;
1343 
1344     if (request == NULL) {
1345         DPRINTFN(0, "%s:%d request is NULL", __func__, __LINE__);
1346         return HDF_FAILURE;
1347     }
1348     OsalMutexInit(&(request->lock));
1349     request->actualLength = 0;
1350     request->numRetired = 0;
1351     request->numUrbs = 0;
1352     switch (request->requestType) {
1353         case USB_REQUEST_TYPE_CONTROL:
1354             ret = OsSubmitControlRequest(request);
1355             break;
1356         case USB_REQUEST_TYPE_ISOCHRONOUS:
1357             ret = OsSubmitIsoRequest(request);
1358             break;
1359         case USB_REQUEST_TYPE_BULK:
1360         case USB_REQUEST_TYPE_INTERRUPT:
1361             ret = OsSubmitBulkRequest(request);
1362             break;
1363         default:
1364             DPRINTFN(0, "%s:%d unknown requestType=%u\n", __func__, __LINE__, request->requestType);
1365             ret = HDF_ERR_INVALID_PARAM;
1366             break;
1367     }
1368 
1369     return ret;
1370 }
1371 
AdapterCancelRequest(const struct UsbHostRequest * request)1372 static int32_t AdapterCancelRequest(const struct UsbHostRequest *request)
1373 {
1374     if (!request->urbs) {
1375         DPRINTFN(0, "adapter cancel urb null\n");
1376         goto END;
1377     }
1378 
1379     OsDiscardUrbs(request, 0, request->numUrbs);
1380 END:
1381     return HDF_SUCCESS;
1382 }
1383 
AdapterUrbCompleteHandle(const struct UsbDeviceHandle * devHandle)1384 static int32_t AdapterUrbCompleteHandle(const struct UsbDeviceHandle *devHandle)
1385 {
1386     int32_t ret;
1387     struct UsbDevice *dev = NULL;
1388     struct OsDev *osDev = NULL;
1389     UsbAdapterUrb *urb = NULL;
1390     struct Async *as = NULL;
1391     struct UsbHostRequest *request = NULL;
1392     if ((devHandle == NULL) || (devHandle->dev == NULL) || (devHandle->dev->privateData == NULL)) {
1393         HDF_LOGE("%{public}s:%{public}d invalid parameter", __func__, __LINE__);
1394         return HDF_ERR_INVALID_PARAM;
1395     }
1396     dev = devHandle->dev;
1397     osDev = (struct OsDev *)dev->privateData;
1398     ret = OsReapUrb(devHandle, &as);
1399     if (as == NULL) {
1400         HDF_LOGE("as is null\n");
1401         return HDF_FAILURE;
1402     }
1403     urb = &as->urb;
1404     request = urb->context;
1405     switch (request->requestType) {
1406         case USB_REQUEST_TYPE_CONTROL:
1407             ret = OsControlCompletion(request, as);
1408             break;
1409         case USB_REQUEST_TYPE_ISOCHRONOUS:
1410             ret = OsIsoCompletion(request, as);
1411             break;
1412         case USB_REQUEST_TYPE_BULK:
1413         case USB_REQUEST_TYPE_INTERRUPT:
1414             ret = OsBulkCompletion(request, as);
1415             break;
1416         default:
1417             DPRINTFN(0, "%s:%d unrecognised requestType %u\n", __func__, __LINE__, request->requestType);
1418             ret = HDF_FAILURE;
1419             break;
1420     }
1421     return ret;
1422 }
1423 
1424 static struct UsbOsAdapterOps g_usbAdapter = {
1425     .init = AdapterInit,
1426     .exit = AdapterExit,
1427     .openDevice = AdapterOpenDevice,
1428     .closeDevice = AdapterCloseDevice,
1429     .getConfigDescriptor = AdapterGetConfigDescriptor,
1430     .getConfiguration = AdapterGetConfiguration,
1431     .setConfiguration = AdapterSetConfiguration,
1432     .claimInterface = AdapterClaimInterface,
1433     .releaseInterface = AdapterReleaseInterface,
1434     .setInterfaceAltsetting = AdapterSetInterface,
1435     .clearHalt = AdapterClearHalt,
1436     .resetDevice = AdapterResetDevice,
1437     .allocRequest = AdapterAllocRequest,
1438     .freeRequest = AdapterFreeRequest,
1439     .submitRequest = AdapterSubmitRequest,
1440     .cancelRequest = AdapterCancelRequest,
1441     .urbCompleteHandle = AdapterUrbCompleteHandle,
1442 };
1443 
UsbAdapterGetOps(void)1444 struct UsbOsAdapterOps *UsbAdapterGetOps(void)
1445 {
1446     return &g_usbAdapter;
1447 }
1448 
UsbAdapterGetTid(void)1449 UsbRawTidType UsbAdapterGetTid(void)
1450 {
1451     return HDF_FAILURE;
1452 }
1453 
UsbAdapterRegisterSignal(void)1454 int32_t UsbAdapterRegisterSignal(void)
1455 {
1456     return HDF_SUCCESS;
1457 }
1458 
UsbAdapterKillSignal(struct UsbDeviceHandle * handle,UsbRawTidType tid)1459 int32_t UsbAdapterKillSignal(struct UsbDeviceHandle *handle, UsbRawTidType tid)
1460 {
1461     if ((handle != NULL) && (handle->dev != NULL)) {
1462         struct UsbDevice *dev = handle->dev;
1463         struct OsDev *osDev = (struct OsDev *)dev->privateData;
1464         if (osDev != NULL) {
1465             g_CompleteExit = true;
1466             OsalSemPost(&osDev->cvWait);
1467             HDF_LOGD("%{public}s:%{public}d signal post", __func__, __LINE__);
1468             return HDF_SUCCESS;
1469         } else {
1470             return HDF_FAILURE;
1471         }
1472     } else {
1473         return HDF_FAILURE;
1474     }
1475 }
1476 
AdapterAtomicInc(OsalAtomic * v)1477 int32_t AdapterAtomicInc(OsalAtomic *v)
1478 {
1479     int32_t valOld;
1480     int32_t val;
1481     uint32_t status = 0;
1482     Atomic *p = NULL;
1483     if (v) {
1484         p = (Atomic *)&(v)->counter;
1485     } else {
1486         return HDF_FAILURE;
1487     }
1488     do {
1489         __asm__ __volatile__("ldrex   %1, [%4]\n"
1490                              "mov   %0, %1\n"
1491                              "add   %1, %1, #1\n"
1492                              "strex   %2, %1, [%4]"
1493                              : "=&r"(valOld), "=&r"(val), "=&r"(status), "+m"(*p)
1494                              : "r"(p)
1495                              : "cc");
1496     } while (__builtin_expect(status != 0, 0));
1497 
1498     return valOld;
1499 }
1500 
AdapterAtomicDec(OsalAtomic * v)1501 int32_t AdapterAtomicDec(OsalAtomic *v)
1502 {
1503     if (v) {
1504         return LOS_AtomicDecRet((Atomic *)&(v)->counter);
1505     } else {
1506         return HDF_FAILURE;
1507     }
1508 }
1509