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