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