1 /*
2 *******************************************************************************
3 *                                              usb host module
4 *
5 *                             Copyright(C), 2006-2008, SoftWinners Co., Ltd.
6 *                                                  All Rights Reserved
7 *
8 * File Name :
9 *
10 * Author : GLHuang(HoLiGun)
11 *
12 * Version : 1.0
13 *
14 * Date : 2008.07.xx
15 *
16 * Description :
17 *
18 * History :
19 *******************************************************************************
20 */
21 
22 //#include "usb_host_config.h"
23 
24 //#include "usb_os_platform.h"
25 //#include "usb_host_base_types.h"
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <log.h>
30 #include <usb_list.h>
31 
32 #include <usb_host_common.h>
33 #include "usb_core_base.h"
34 #include "usb_gen_hub.h"
35 #include "usb_msg.h"
36 #include "usb_gen_hub.h"
37 #include "usb_virt_bus.h"
38 #include "usb_msg_base.h"
39 
40 
41 
42 /**
43  *  usb_control_msg - Builds a control urb, sends it off and waits for completion
44  *  @dev: pointer to the usb device to send the message to
45  *  @pipe: endpoint "pipe" to send the message to
46  *  @request: USB message request value
47  *  @requesttype: USB message request type value
48  *  @value: USB message value
49  *  @index: USB message index value
50  *  @data: pointer to the data to send
51  *  @size: length in bytes of the data to send
52  *  @timeout: time in msecs to wait for the message to complete before
53  *      timing out (if 0 the wait is forever)
54  *  Context: !in_interrupt ()
55  *
56  *  This function sends a simple control message to a specified endpoint
57  *  and waits for the message to complete, or timeout.
58  *
59  *  If successful, it returns the number of bytes transferred, otherwise a negative error number.
60  *
61  *  Don't use this function from within an interrupt context, like a
62  *  bottom half handler.  If you need an asynchronous message, or need to send
63  *  a message from within interrupt context, use usb_submit_urb()
64  *      If a thread in your driver uses this call, make sure your disconnect()
65  *      method can wait for it to complete.  Since you don't have a handle on
66  *      the URB used, you can't cancel the request.
67  */
usb_control_msg(struct usb_host_virt_dev * dev,u32 pipe,u8 request,u8 requesttype,u16 value,u16 index,void * data,u16 size,s32 timeout)68 int usb_control_msg(struct usb_host_virt_dev *dev, u32 pipe, u8 request, u8 requesttype,
69                     u16 value, u16 index, void *data, u16 size, s32 timeout)
70 {
71     int ret  = 0;
72     struct usb_ctrlrequest *dr = NULL;
73     dr = malloc(sizeof(struct usb_ctrlrequest));
74 
75     if (!dr)
76     {
77         hal_log_err("ERR: malloc failed");
78         return -ENOMEM;
79     }
80 
81     memset(dr, 0, sizeof(struct usb_ctrlrequest));
82     dr->bRequestType    = requesttype;
83     dr->bRequest        = request;
84     //dr->wValue          = cpu_to_le16(value);
85     //dr->wIndex          = cpu_to_le16(index);
86     //dr->wLength         = cpu_to_le16(size);
87     dr->wValue          = value;
88     dr->wIndex          = index;
89     dr->wLength         = size;
90     ret = _usb_internal_ctrll_msg(dev, pipe, dr, data, size, timeout);
91 
92     if (dr)
93     {
94         free((void *)dr);
95         dr = NULL;
96     }
97     else
98     {
99        hal_log_err("ERR: parameter is NULL, can't free");
100     }
101 
102     return ret;
103 }
104 
105 /**
106  *  usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
107  *  @usb_dev: pointer to the usb device to send the message to
108  *  @pipe: endpoint "pipe" to send the message to
109  *  @data: pointer to the data to send
110  *  @len: length in bytes of the data to send
111  *  @actual_length: pointer to a location to put the actual length transferred in bytes,实际收发的长度
112  *  @timeout: time in msecs to wait for the message to complete before
113  *      timing out (if 0 the wait is forever)
114  *  Context: !in_interrupt ()
115  *
116  *  This function sends a simple bulk message to a specified endpoint
117  *  and waits for the message to complete, or timeout.
118  *
119  *  If successful, it returns 0, otherwise a negative error number.
120  *  The number of actual bytes transferred will be stored in the
121  *  actual_length paramater.
122  *
123  *  Don't use this function from within an interrupt context, like a
124  *  bottom half handler.  If you need an asynchronous message, or need to
125  *  send a message from within interrupt context, use usb_submit_urb()
126  *      If a thread in your driver uses this call, make sure your disconnect()
127  *      method can wait for it to complete.  Since you don't have a handle on
128  *      the URB used, you can't cancel the request.
129  */
usb_bulk_msg(struct usb_host_virt_dev * usb_dev,unsigned int pipe,void * data,int len,int * actual_length,int timeout)130 int usb_bulk_msg(struct usb_host_virt_dev *usb_dev, unsigned int pipe,
131                  void *data, int len, int *actual_length, int timeout)
132 {
133     if (usb_dev == NULL || data == NULL || len < 0)
134     {
135         return -EINVAL;
136     }
137 
138     return _usb_internal_bulk_msg(usb_dev,
139                                   pipe,
140                                   data,
141                                   len,
142                                   actual_length,
143                                   timeout);
144 }
145 
146 /**
147  * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
148  * @dev: the device whose descriptor is being retrieved
149  * @type: the descriptor type (USB_DT_*)
150  * @index: the number of the descriptor
151  * @buf: where to put the descriptor
152  * @size: how big is "buf"?
153  * Context: !in_interrupt ()
154  *
155  * Gets a USB descriptor.  Convenience functions exist to simplify
156  * getting some types of descriptors.  Use
157  * usb_get_string() or usb_string() for USB_DT_STRING.
158  * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
159  * are part of the device structure.
160  * In addition to a number of USB-standard descriptors, some
161  * devices also use class-specific or vendor-specific descriptors.
162  *
163  * This call is synchronous, and may not be used in an interrupt context.
164  *
165  * Returns the number of bytes received on success, or else the status code
166  * returned by the underlying usb_control_msg() call.
167  */
168 /* 带重试的ctrl传输,的desc */
usb_get_descriptor(struct usb_host_virt_dev * dev,u8 type,u8 index,void * buf,s32 size)169 s32 usb_get_descriptor(struct usb_host_virt_dev *dev, u8 type, u8 index, void *buf, s32 size)
170 {
171     int i = 0;
172     int result = 0;
173     memset(buf, 0, size); // Make sure we parse really received data
174 
175     for (i = 0; i < 3; ++i)
176     {
177         /* retry on length 0 or stall; some devices are flakey */
178         result = usb_control_msg(dev,
179                                  usb_rcvctrlpipe(dev, 0),
180                                  USB_REQ_GET_DESCRIPTOR,
181                                  USB_DIR_IN,
182                                  (type << 8) + index,
183                                  0,
184                                  buf,
185                                  size,
186                                  USB_CTRL_GET_TIMEOUT);
187 
188         if (result == 0 || result == -EPIPE)
189         {
190             hal_log_err("get_descriptor faile 1");
191             continue;
192         }
193 
194         if (result > 1 && ((u8 *)buf)[1] != type)
195         {
196             hal_log_err("get_descriptor faile 2");
197             result = -EPROTO;
198             continue;
199         }
200 
201         break;
202     }
203 
204     return result;
205 }
206 
207 /*
208 *******************************************************************************
209 *                     usb_get_extra_descriptor
210 *
211 * Description:
212 *     在已得到的全部描述符里找到想要的描述符。
213 *
214 * Parameters:
215 *     buffer  :  input. 已经得到的全部描述符
216 *     size    :  input. 全部描述符的长度
217 *     type    :  input. 想要的描述符类型
218 *     ptr     :  input. 想要的描述符的起始位置
219 *
220 * Return value:
221 *
222 *
223 * note:
224 *    无
225 *
226 *******************************************************************************
227 */
__usb_get_extra_descriptor(unsigned char * buffer,unsigned size,unsigned char type,void ** ptr)228 int __usb_get_extra_descriptor(unsigned char *buffer,
229                                unsigned size,
230                                unsigned char type,
231                                void **ptr)
232 {
233     struct usb_descriptor_header *header;
234 
235     while (size >= sizeof(struct usb_descriptor_header))
236     {
237         header = (struct usb_descriptor_header *)buffer;
238 
239         if (header->bLength < 2)
240         {
241             __err("bogus descriptor, type %d length %d",
242                        header->bDescriptorType,
243                        header->bLength);
244             return -1;
245         }
246 
247         if (header->bDescriptorType == type)
248         {
249             *ptr = header;
250             return 0;
251         }
252 
253         buffer += header->bLength;
254         size -= header->bLength;
255     }
256 
257     return -1;
258 }
259 
260 
261 /**
262  * usb_string - returns ISO 8859-1 version of a string descriptor
263  * @dev: the device whose string descriptor is being retrieved
264  * @index: the number of the descriptor
265  * @buf: where to put the string
266  * @size: how big is "buf"?
267  * Context: !in_interrupt ()
268  *
269  * This converts the UTF-16LE encoded strings returned by devices, from
270  * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
271  * that are more usable in most kernel contexts.  Note that all characters
272  * in the chosen descriptor that can't be encoded using ISO-8859-1
273  * are converted to the question mark ("?") character, and this function
274  * chooses strings in the first language supported by the device.
275  *
276  * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
277  * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
278  * and is appropriate for use many uses of English and several other
279  * Western European languages.  (But it doesn't include the "Euro" symbol.)
280  *
281  * This call is synchronous, and may not be used in an interrupt context.
282  *
283  * Returns length of the string (>= 0) or usb_control_msg status (< 0).
284  */
usb_string(struct usb_host_virt_dev * dev,int index,char * buf,u32 size)285 int usb_string(struct usb_host_virt_dev *dev, int index, char *buf, u32 size)
286 {
287     unsigned char *tbuf = NULL;
288     s32 err = 0;
289     u32 u = 0, idx = 0;
290 
291     if (dev->state == USB_STATE_SUSPENDED)
292     {
293         __err("ERR: usb_string, status is invalid");
294         return -EHOSTUNREACH;
295     }
296 
297     if (((s32)size) <= 0 || !buf || !index)
298     {
299         __err("ERR: usb_string, input error");
300         return -EINVAL;
301     }
302 
303     buf[0] = 0;
304     tbuf = malloc(256);
305 
306     if (!tbuf)
307     {
308         __err("ERR: usb_string, malloc failed");
309         return -ENOMEM;
310     }
311 
312     memset(tbuf, 0, 256);
313 
314     // get langid for strings if it's not yet known //
315     if (!dev->have_langid)
316     {
317         err = _usb_string_sub(dev, 0, 0, tbuf);
318 
319         if (err < 0)
320         {
321             __err("PANIC : string descriptor 0 read error: %d", err);
322             goto errout;
323         }
324         else if (err < 4)
325         {
326             __err("PANIC : string descriptor 0 too short");
327             err = -EINVAL;
328             goto errout;
329         }
330         else
331         {
332             dev->have_langid = -1;
333             dev->string_langid = tbuf[2] | (tbuf[3] << 8);
334         }
335     }
336 
337     err = _usb_string_sub(dev, dev->string_langid, index, tbuf);
338 
339     if (err < 0)
340     {
341         goto errout;
342     }
343 
344     //leave room for trailing NULL char in output buffer//
345     size--;
346 
347     for (idx = 0, u = 2; u < err; u += 2)
348     {
349         if (idx >= size)
350         {
351             break;
352         }
353 
354         if (tbuf[u + 1])        //high byte
355         {
356             buf[idx++] = '?';  // non ISO-8859-1 character //
357         }
358         else
359         {
360             buf[idx++] = tbuf[u];
361         }
362     }
363 
364     buf[idx] = 0;
365     err = idx;
366 
367     if (tbuf[1] != USB_DT_STRING)
368     {
369         __inf("wrong descriptor type %02x for string %d (\"%s\")", tbuf[1], index, buf);
370     }
371 
372 errout:
373 
374     if (tbuf)
375     {
376         free(tbuf);
377         tbuf = NULL;
378     }
379     else
380     {
381         __err("ERR: parameter is NULL, can't free");
382     }
383 
384     return err;
385 }
386 
387 
388 
389 
390 
391 /*
392  * usb_enable_endpoint - Enable an endpoint for USB communications
393  * @dev: the device whose interface is being enabled
394  * @ep: the endpoint
395  *
396  * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
397  * For control endpoints, both the input and output sides are handled.
398  */
usb_enable_endpoint(struct usb_host_virt_dev * dev,struct usb_host_virt_endpoint * ep)399 static void usb_enable_endpoint(struct usb_host_virt_dev *dev, struct usb_host_virt_endpoint *ep)
400 {
401     unsigned int epaddr = ep->desc.bEndpointAddress;
402     unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
403     int is_control = 0;
404     is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_CONTROL);
405 
406     if (usb_endpoint_out(epaddr) || is_control)
407     {
408         usb_settoggle(dev, epnum, 1, 0);
409         dev->ep_out[epnum] = ep;
410     }
411 
412     if (!usb_endpoint_out(epaddr) || is_control)
413     {
414         usb_settoggle(dev, epnum, 0, 0);
415         dev->ep_in[epnum] = ep;
416     }
417 
418     return;
419 }
420 
421 
422 
423 /*
424  * usb_enable_interface - Enable all the endpoints for an interface
425  * @dev: the device whose interface is being enabled
426  * @intf: pointer to the interface descriptor
427  *
428  * Enables all the endpoints for the interface's current altsetting.
429  */
usb_enable_interface(struct usb_host_virt_dev * dev,struct usb_interface * intf)430 static void usb_enable_interface(struct usb_host_virt_dev *dev,
431                                  struct usb_interface *intf)
432 {
433     struct usb_host_virt_interface *alt = intf->cur_altsetting;
434     int i;
435 
436     for (i = 0; i < alt->desc.bNumEndpoints; ++i)
437     {
438         usb_enable_endpoint(dev, &alt->endpoint[i]);
439     }
440 }
441 
442 
443 
444 /*
445  * usb_set_configuration - Makes a particular device setting be current
446  * @dev: the device whose configuration is being updated
447  * @configuration: the configuration being chosen.
448  * Context: !in_interrupt(), caller owns the device lock
449  *
450  * This is used to enable non-default device modes.  Not all devices
451  * use this kind of configurability; many devices only have one
452  * configuration.
453  *
454  * USB device configurations may affect Linux interoperability,
455  * power consumption and the functionality available.  For example,
456  * the default configuration is limited to using 100mA of bus power,
457  * so that when certain device functionality requires more power,
458  * and the device is bus powered, that functionality should be in some
459  * non-default device configuration.  Other device modes may also be
460  * reflected as configuration options, such as whether two ISDN
461  * channels are available independently; and choosing between open
462  * standard device protocols (like CDC) or proprietary ones.
463  *
464  * Note that USB has an additional level of device configurability,
465  * associated with interfaces.  That configurability is accessed using
466  * usb_set_interface().
467  *
468  * This call is synchronous. The calling context must be able to sleep,
469  * must own the device lock, and must not hold the driver model's USB
470  * bus rwsem; usb device driver probe() methods cannot use this routine.
471  *
472  * Returns zero on success, or else the status code returned by the
473  * underlying call that failed.  On successful completion, each interface
474  * in the original device configuration has been destroyed, and each one
475  * in the new configuration has been probed by all relevant usb device
476  * drivers currently known to the kernel.
477  */
478 
479 
480 //virt_father_dev   :   与物理设备对应的
481 //configuration :   要设置的config的index
usb_set_configuration(struct usb_host_virt_dev * virt_father_dev,s32 configuration)482 s32 usb_set_configuration(struct usb_host_virt_dev *virt_father_dev, s32 configuration)
483 {
484     int i = 0, ret = 0;
485     struct usb_host_virt_config *virt_confg = NULL;
486     struct usb_interface **new_interfaces = NULL;       //记录分配的usb_interface的地址
487     s32 n = 0;
488     s32 nintf = 0;      //该config的interface数目
489 
490     //--<1>--根据具体的config index,获得其virt_config结构
491     for (i = 0; i < virt_father_dev->descriptor.bNumConfigurations; i++)
492     {
493         if (virt_father_dev->config[i].desc.bConfigurationValue == configuration)
494         {
495             virt_confg = &virt_father_dev->config[i];
496             break;
497         }
498     }
499 
500     if ((!virt_confg && configuration != 0))
501     {
502         __err("ERR : set config fail");
503         return -EINVAL;
504     }
505 
506     /* The USB spec says configuration 0 means unconfigured.
507      * But if a device includes a configuration numbered 0,
508      * we will accept it as a correctly configured state.
509      */
510     if (virt_confg && configuration == 0)
511     {
512         __err("ERR : config 0 descriptor??");
513     }
514 
515     if (virt_father_dev->state == USB_STATE_SUSPENDED)
516     {
517         __err("ERR: usb_set_configuration: device is suspended");
518         return -EHOSTUNREACH;
519     }
520 
521     //--<2>--创建cp->desc.bNumInterfaces个usb_interface结构
522     /* Allocate memory for new interfaces before doing anything else,
523      * so that if we run out then nothing will have changed. */
524     n = nintf = 0;
525 
526     if (virt_confg)
527     {
528         nintf = virt_confg->desc.bNumInterfaces;
529 
530         if (nintf > USB_MAX_VIRT_SUB_DEV_NR)
531         {
532             __err("PANIC : Set_Conifg : too many interface,now we only support %d interfaces", USB_MAX_VIRT_SUB_DEV_NR);
533             return -EINVAL;
534         }
535 
536         new_interfaces = malloc(nintf * (sizeof(struct usb_interface *)));
537 
538         if (!new_interfaces)
539         {
540             __err("PANIC : Out of memory");
541             return -ENOMEM;
542         }
543 
544         memset(new_interfaces, 0, nintf * (sizeof(struct usb_interface *)));
545 
546         for (; n < nintf; ++n)
547         {
548             new_interfaces[n] = malloc(sizeof(struct usb_interface));
549 
550             if (!new_interfaces[n])
551             {
552                 __err("PANIC : Out of memory");
553                 ret = -ENOMEM;
554 free_interfaces:
555 
556                 while (--n >= 0)
557                 {
558                     if (new_interfaces[n])
559                     {
560                         free(new_interfaces[n]);
561                         new_interfaces[n] = NULL;
562                     }
563                     else
564                     {
565                         __err("ERR: parameter is NULL, can't free");
566                     }
567                 }
568 
569                 if (new_interfaces)
570                 {
571                     free(new_interfaces);
572                     new_interfaces = NULL;
573                 }
574                 else
575                 {
576                     __err("ERR: parameter is NULL, can't free");
577                 }
578 
579                 return ret;
580             }
581 
582             memset(new_interfaces[n], 0, sizeof(struct usb_interface));
583         }
584     }
585 
586     /* if it's already configured, clear out old state first.
587      * getting rid of old interfaces means unbinding their drivers.
588      */
589     if (virt_father_dev->state != USB_STATE_ADDRESS)
590     {
591         usb_disable_device(virt_father_dev, 1);     // Skip ep0
592     }
593 
594     //--<3>--发送set config
595     if ((ret = usb_control_msg(virt_father_dev, usb_sndctrlpipe(virt_father_dev, 0),
596                                USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
597                                NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0)
598     {
599         goto free_interfaces;
600     }
601 
602     //--<4>--记录当前active的ep
603     virt_father_dev->actconfig = virt_confg;
604 
605     //--<5>--配置该config旗下的 interface
606     if (!virt_confg)
607     {
608         usb_set_device_state(virt_father_dev, USB_STATE_ADDRESS);
609     }
610     else
611     {
612         usb_set_device_state(virt_father_dev, USB_STATE_CONFIGURED);
613 
614         /* Initialize the new interface structures and the
615          * hc/hcd/usbcore interface/endpoint state.
616          */
617         for (i = 0; i < nintf; ++i)
618         {
619             struct usb_interface_cache *intf_cache;
620             struct usb_interface *intf;
621             struct usb_host_virt_interface *alt;
622             //从interface cache中获取,并初始化usb_interface
623             virt_confg->interfac[i] = intf = new_interfaces[i];
624             memset(intf, 0, sizeof(struct usb_interface));
625             intf_cache = virt_confg->intf_cache[i];
626             intf->altsetting = intf_cache->altsetting_array;
627             intf->num_altsetting = intf_cache->num_altsetting;
628             alt = usb_altnum_to_altsetting(intf, 0);
629 
630             /* No altsetting 0?  We'll assume the first altsetting.
631              * We could use a GetInterface call, but if a device is
632              * so non-compliant that it doesn't have altsetting 0
633              * then I wouldn't trust its reply anyway.
634              */
635             if (!alt)
636             {
637                 alt = &intf->altsetting[0];
638             }
639 
640             intf->cur_altsetting = alt;
641             usb_enable_interface(virt_father_dev, intf);
642             //完成virt_dev,virt_sub_dev,intf互相指
643             intf->virt_sub_dev = &(virt_father_dev->virt_sub_dev_array[i]);
644             intf->virt_sub_dev->father_dev = virt_father_dev;   //指向父亲
645             intf->virt_sub_dev->sub_dev_interface = intf;
646         }
647 
648         if (new_interfaces)
649         {
650             free(new_interfaces);
651             new_interfaces = NULL;
652         }
653         else
654         {
655             __err("ERR: parameter is NULL, can't free");
656         }
657 
658         if ((virt_confg->desc.iConfiguration) && (virt_confg->string == NULL))
659         {
660             virt_confg->string = malloc(256);
661 
662             if (virt_confg->string)
663             {
664                 memset(virt_confg->string, 0, 256);
665                 usb_string(virt_father_dev, virt_confg->desc.iConfiguration, virt_confg->string, 256);
666             }
667         }
668 
669         /* Now that all the interfaces are set up, register them
670          * to trigger binding of drivers to interfaces.  probe()
671          * routines may install different altsettings and may
672          * claim() any interfaces not yet bound.  Many class drivers
673          * need that: CDC, audio, video, etc.
674          */
675         //--<5_2>--将创建的usb_host_virt_sub_dev添加到bus
676         for (i = 0; i < nintf; ++i)
677         {
678             struct usb_interface *intf = virt_confg->interfac[i];
679             __inf("[usbh core]: adding sub dev  (config #%d, interface %d)", configuration, intf->altsetting [0].desc.bInterfaceNumber);
680 
681             /* msc在扫描盘符的时候,这里发get_interface, 两个urb会造成suni的hcd混乱,
682               因此, 这里只识别device的第一个interface */
683             if (!i)
684             {
685                 if ((intf->cur_altsetting->desc.iInterface) && (intf->cur_altsetting->string == NULL))
686                 {
687                     intf->cur_altsetting->string = malloc(256);
688 
689                     if (intf->cur_altsetting->string)
690                     {
691                         memset(intf->cur_altsetting->string, 0, 256);
692                         usb_string(virt_father_dev,
693                                    intf->cur_altsetting->desc.iInterface,
694                                    intf->cur_altsetting->string,
695                                    256);
696                     }
697                     else
698                     {
699                         __err("ERR: malloc failed");
700                     }
701                 }
702             }
703 
704             ret = usb_virt_bus_dev_add(intf->virt_sub_dev);
705 
706             if (ret != 0)
707             {
708                 __err("PANIC : usb_virt_bus_dev_add() fail ret = %d", ret);
709 
710                 if (intf->cur_altsetting->string)
711                 {
712                     free(intf->cur_altsetting->string);
713                     intf->cur_altsetting->string = NULL;
714                 }
715                 else
716                 {
717                     __err("ERR: parameter is NULL, can't free");
718                 }
719 
720                 continue;
721             }
722         }
723     }
724 
725     return 0;
726 }
727 
728 
729 
730 
731 /*
732  * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
733  * @dev: the device whose device descriptor is being updated
734  * @size: how much of the descriptor to read
735  * Context: !in_interrupt ()
736  *
737  * Updates the copy of the device descriptor stored in the device structure,
738  * which dedicates space for this purpose.  Note that several fields are
739  * converted to the host CPU's byte order:  the USB version (bcdUSB), and
740  * vendors product and version fields (idVendor, idProduct, and bcdDevice).
741  * That lets device drivers compare against non-byteswapped constants.
742  *
743  * Not exported, only for use by the core.  If drivers really want to read
744  * the device descriptor directly, they can call usb_get_descriptor() with
745  * type = USB_DT_DEVICE and index = 0.
746  *
747  * This call is synchronous, and may not be used in an interrupt context.
748  *
749  * Returns the number of bytes received on success, or else the status code
750  * returned by the underlying usb_control_msg() call.
751  */
752 /* 获得设备desc,会自动拷贝到usb_host_virt_dev->设备描述符中 */
753 #if 0
754 s32 usb_get_device_descriptor(struct usb_host_virt_dev *dev, u32 size)
755 {
756     struct usb_device_descriptor *desc = NULL;
757     s32 ret = 0;
758 
759     if (size > sizeof(struct usb_device_descriptor))
760     {
761         return -EINVAL;
762     }
763 
764     desc = malloc(sizeof(struct usb_device_descriptor), USB_MEM_FILE_TRIGGER, USB_MEM_LINE_TRIGGER);
765 
766     if (!desc)
767     {
768         __err("ERR: malloc failed");
769         return -ENOMEM;
770     }
771 
772     memset(desc, 0, sizeof(struct usb_device_descriptor));
773     ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, (void *)desc, size);
774 
775     if (ret >= 0)
776     {
777         USB_OS_MEMCPY((void *)(&dev->descriptor), (void *)desc, size);
778     }
779 
780     if (desc)
781     {
782         free((void *)desc);
783         desc = NULL;
784     }
785     else
786     {
787         __err("ERR: parameter is NULL, can't free");
788     }
789 
790     return ret;
791 }
792 #else
usb_get_device_descriptor(struct usb_host_virt_dev * dev,u32 size)793 s32 usb_get_device_descriptor(struct usb_host_virt_dev *dev, u32 size)
794 {
795     struct usb_device_descriptor desc __attribute__((aligned(4)));
796     s32 ret = 0;
797     hal_log_info("---usb_get_device_descriptor---1--\n");
798     if (size > sizeof(struct usb_device_descriptor))
799     {
800         return -EINVAL;
801     }
802 
803     memset(&desc, 0, sizeof(struct usb_device_descriptor));
804     hal_log_info("---usb_get_device_descriptor---2--\n");
805     ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, (void *)&desc, size);
806 
807     hal_log_info("---usb_get_device_descriptor---3--\n");
808     if (ret >= 0)
809     {
810         memcpy((void *)(&dev->descriptor), (void *)&desc, size);
811     }
812 
813     return ret;
814 }
815 #endif
816 
817 
818 /**
819  * usb_get_status - issues a GET_STATUS call
820  * @dev: the device whose status is being checked
821  * @type: USB_RECIP_*; for device, interface, or endpoint
822  * @target: zero (for device), else interface or endpoint number
823  * @data: pointer to two bytes of bitmap data
824  * Context: !in_interrupt ()
825  *
826  * Returns device, interface, or endpoint status.  Normally only of
827  * interest to see if the device is self powered, or has enabled the
828  * remote wakeup facility; or whether a bulk or interrupt endpoint
829  * is halted ("stalled").
830  *
831  * Bits in these status bitmaps are set using the SET_FEATURE request,
832  * and cleared using the CLEAR_FEATURE request.  The usb_clear_halt()
833  * function should be used to clear halt ("stall") status.
834  *
835  * This call is synchronous, and may not be used in an interrupt context.
836  *
837  * Returns the number of bytes received on success, or else the status code
838  * returned by the underlying usb_control_msg() call.
839  */
840 /* 发送到hub的get status的ctrl传输 */
usb_get_status(struct usb_host_virt_dev * dev,s32 type,s32 target,void * data)841 int usb_get_status(struct usb_host_virt_dev *dev, s32 type, s32 target, void *data)
842 {
843     s32 ret = 0;
844     u16 *status = malloc(sizeof(*status));
845 
846     if (!status)
847     {
848         __err("ERR: usb_get_status, malloc failed");
849         return -ENOMEM;
850     }
851 
852     memset(status, 0, sizeof(*status));
853     ret = usb_control_msg(dev,
854                           usb_rcvctrlpipe(dev, 0),
855                           USB_REQ_GET_STATUS, USB_DIR_IN | type,
856                           0,
857                           target,
858                           status,
859                           sizeof(*status), USB_CTRL_GET_TIMEOUT);
860     *(u16 *)data = *status;
861 
862     if (status)
863     {
864         free(status);
865         status = NULL;
866     }
867     else
868     {
869         __err("ERR: parameter is NULL, can't free");
870     }
871 
872     return ret;
873 }
874 
875 /**
876  * usb_clear_halt - tells device to clear endpoint halt/stall condition
877  * @dev: device whose endpoint is halted
878  * @pipe: endpoint "pipe" being cleared
879  * Context: !in_interrupt ()
880  *
881  * This is used to clear halt conditions for bulk and interrupt endpoints,
882  * as reported by URB completion status.  Endpoints that are halted are
883  * sometimes referred to as being "stalled".  Such endpoints are unable
884  * to transmit or receive data until the halt status is cleared.  Any URBs
885  * queued for such an endpoint should normally be unlinked by the driver
886  * before clearing the halt condition, as described in sections 5.7.5
887  * and 5.8.5 of the USB 2.0 spec.
888  *
889  * Note that control and isochronous endpoints don't halt, although control
890  * endpoints report "protocol stall" (for unsupported requests) using the
891  * same status code used to report a true stall.
892  *
893  * This call is synchronous, and may not be used in an interrupt context.
894  *
895  * Returns zero on success, or else the status code returned by the
896  * underlying usb_control_msg() call.
897  */
usb_clear_halt(struct usb_host_virt_dev * dev,int pipe)898 int usb_clear_halt(struct usb_host_virt_dev *dev, int pipe)
899 {
900     int result;
901     int endp = usb_pipeendpoint(pipe);
902 
903     if (usb_pipein(pipe))
904     {
905         endp |= USB_DIR_IN;
906     }
907 
908     /* we don't care if it wasn't halted first. in fact some devices
909      * (like some ibmcam model 1 units) seem to expect hosts to make
910      * this request for iso endpoints, which can't halt!
911      */
912     result = usb_control_msg(dev,
913                              usb_sndctrlpipe(dev, 0),
914                              USB_REQ_CLEAR_FEATURE,
915                              USB_RECIP_ENDPOINT,
916                              USB_ENDPOINT_HALT,
917                              endp,
918                              NULL,
919                              0,
920                              USB_CTRL_SET_TIMEOUT);
921 
922     /* don't un-halt or force to DATA0 except on success */
923     if (result < 0)
924     {
925         return result;
926     }
927 
928     /* NOTE:  seems like Microsoft and Apple don't bother verifying
929      * the clear "took", so some devices could lock up if you check...
930      * such as the Hagiwara FlashGate DUAL.  So we won't bother.
931      *
932      * NOTE:  make sure the logic here doesn't diverge much from
933      * the copy in usb-storage, for as long as we need two copies.
934      */
935     /* toggle was reset by the clear */
936     usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
937     return 0;
938 }
939 
940 
941 
942 /**
943  * usb_set_interface - Makes a particular alternate setting be current
944  * @dev: the device whose interface is being updated
945  * @interface: the interface being updated
946  * @alternate: the setting being chosen.
947  * Context: !in_interrupt ()
948  *
949  * This is used to enable data transfers on interfaces that may not
950  * be enabled by default.  Not all devices support such configurability.
951  * Only the driver bound to an interface may change its setting.
952  *
953  * Within any given configuration, each interface may have several
954  * alternative settings.  These are often used to control levels of
955  * bandwidth consumption.  For example, the default setting for a high
956  * speed interrupt endpoint may not send more than 64 bytes per microframe,
957  * while interrupt transfers of up to 3KBytes per microframe are legal.
958  * Also, isochronous endpoints may never be part of an
959  * interface's default setting.  To access such bandwidth, alternate
960  * interface settings must be made current.
961  *
962  * Note that in the Linux USB subsystem, bandwidth associated with
963  * an endpoint in a given alternate setting is not reserved until an URB
964  * is submitted that needs that bandwidth.  Some other operating systems
965  * allocate bandwidth early, when a configuration is chosen.
966  *
967  * This call is synchronous, and may not be used in an interrupt context.
968  * Also, drivers must not change altsettings while urbs are scheduled for
969  * endpoints in that interface; all such urbs must first be completed
970  * (perhaps forced by unlinking).
971  *
972  * Returns zero on success, or else the status code returned by the
973  * underlying usb_control_msg() call.
974  */
usb_set_interface(struct usb_host_virt_dev * dev,int interface,int alternate)975 int usb_set_interface(struct usb_host_virt_dev  *dev, int interface, int alternate)
976 {
977     struct usb_interface *iface;
978     struct usb_host_virt_interface *alt;
979     int ret;
980     int manual = 0;
981 
982     if (dev == NULL)
983     {
984         __err("ERR: invalid argment");
985         return -1;
986     }
987 
988     if (dev->state == USB_STATE_SUSPENDED)
989     {
990         return -EHOSTUNREACH;
991     }
992 
993     iface = usb_ifnum_to_if(dev, interface);
994 
995     if (!iface)
996     {
997         __err("selecting invalid interface %d", interface);
998         return -EINVAL;
999     }
1000 
1001     alt = usb_altnum_to_altsetting(iface, alternate);
1002 
1003     if (!alt)
1004     {
1005         __err("selecting invalid altsetting %d", alternate);
1006         return -EINVAL;
1007     }
1008 
1009     ret = usb_control_msg(dev,
1010                           usb_sndctrlpipe(dev, 0),
1011                           USB_REQ_SET_INTERFACE,
1012                           USB_RECIP_INTERFACE,
1013                           alternate,
1014                           interface,
1015                           NULL,
1016                           0,
1017                           5000);
1018 
1019     /* 9.4.10 says devices don't need this and are free to STALL the
1020      * request if the interface only has one alternate setting.
1021      */
1022     if (ret == -EPIPE && iface->num_altsetting == 1)
1023     {
1024         __err("manual set_interface for iface %d, alt %d", interface, alternate);
1025         manual = 1;
1026     }
1027     else if (ret < 0)
1028     {
1029         return ret;
1030     }
1031 
1032     /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1033      * when they implement async or easily-killable versions of this or
1034      * other "should-be-internal" functions (like clear_halt).
1035      * should hcd+usbcore postprocess control requests?
1036      */
1037     /* prevent submissions using previous endpoint settings */
1038     usb_disable_interface(dev, iface);
1039     iface->cur_altsetting = alt;
1040 
1041     /* If the interface only has one altsetting and the device didn't
1042      * accept the request, we attempt to carry out the equivalent action
1043      * by manually clearing the HALT feature for each endpoint in the
1044      * new altsetting.
1045      */
1046     if (manual)
1047     {
1048         int i = 0;
1049 
1050         for (i = 0; i < alt->desc.bNumEndpoints; i++)
1051         {
1052             u32 epaddr = alt->endpoint[i].desc.bEndpointAddress;
1053             u32 pipe = __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr) | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1054             usb_clear_halt(dev, pipe);
1055         }
1056     }
1057 
1058     /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1059      *
1060      * Note:
1061      * Despite EP0 is always present in all interfaces/AS, the list of
1062      * endpoints from the descriptor does not contain EP0. Due to its
1063      * omnipresence one might expect EP0 being considered "affected" by
1064      * any SetInterface request and hence assume toggles need to be reset.
1065      * However, EP0 toggles are re-synced for every individual transfer
1066      * during the SETUP stage - hence EP0 toggles are "don't care" here.
1067      * (Likewise, EP0 never "halts" on well designed devices.)
1068      */
1069     usb_enable_interface(dev, iface);
1070     return 0;
1071 }
1072 
1073 
1074 /**
1075  * usb_disable_interface -- Disable all endpoints for an interface
1076  * @dev: the device whose interface is being disabled
1077  * @intf: pointer to the interface descriptor
1078  *
1079  * Disables all the endpoints for the interface's current altsetting.
1080  */
usb_disable_interface(struct usb_host_virt_dev * dev,struct usb_interface * intf)1081 void usb_disable_interface(struct usb_host_virt_dev *dev, struct usb_interface *intf)
1082 {
1083     struct usb_host_virt_interface *alt = intf->cur_altsetting;
1084     int i;
1085 
1086     for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1087     {
1088         usb_disable_endpoint(dev, alt->endpoint[i].desc.bEndpointAddress);
1089     }
1090 }
1091 
1092 
1093