Merge with rsync://git-user@source.denx.net/git/u-boot.git
[platform/kernel/u-boot.git] / common / usb.c
1 /*
2  * (C) Copyright 2001
3  * Denis Peter, MPL AG Switzerland
4  *
5  * Most of this source has been derived from the Linux USB
6  * project.
7  *
8  * See file CREDITS for list of people who contributed to this
9  * project.
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License as
13  * published by the Free Software Foundation; either version 2 of
14  * the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
24  * MA 02111-1307 USA
25  *
26  */
27
28 /*
29  * How it works:
30  *
31  * Since this is a bootloader, the devices will not be automatic
32  * (re)configured on hotplug, but after a restart of the USB the
33  * device should work.
34  *
35  * For each transfer (except "Interrupt") we wait for completion.
36  */
37 #include <common.h>
38 #include <command.h>
39 #include <asm/processor.h>
40 #include <linux/ctype.h>
41
42 #if (CONFIG_COMMANDS & CFG_CMD_USB)
43
44 #include <usb.h>
45 #ifdef CONFIG_4xx
46 #include <405gp_pci.h>
47 #endif
48
49 #undef USB_DEBUG
50
51 #ifdef  USB_DEBUG
52 #define USB_PRINTF(fmt,args...) printf (fmt ,##args)
53 #else
54 #define USB_PRINTF(fmt,args...)
55 #endif
56
57 #define USB_BUFSIZ      512
58
59 static struct usb_device usb_dev[USB_MAX_DEVICE];
60 static int dev_index;
61 static int running;
62 static int asynch_allowed;
63 static struct devrequest setup_packet;
64
65 /**********************************************************************
66  * some forward declerations...
67  */
68 void usb_scan_devices(void);
69
70 int usb_hub_probe(struct usb_device *dev, int ifnum);
71 void usb_hub_reset(void);
72
73
74 /***********************************************************************
75  * wait_ms
76  */
77
78 void __inline__ wait_ms(unsigned long ms)
79 {
80         while(ms-->0)
81                 udelay(1000);
82 }
83 /***************************************************************************
84  * Init USB Device
85  */
86
87 int usb_init(void)
88 {
89         int result;
90
91         running=0;
92         dev_index=0;
93         asynch_allowed=1;
94         usb_hub_reset();
95         /* init low_level USB */
96         printf("USB:   ");
97         result = usb_lowlevel_init();
98         /* if lowlevel init is OK, scan the bus for devices i.e. search HUBs and configure them */
99         if(result==0) {
100                 printf("scanning bus for devices... ");
101                 running=1;
102                 usb_scan_devices();
103                 return 0;
104         }
105         else {
106                 printf("Error, couldn't init Lowlevel part\n");
107                 return -1;
108         }
109 }
110
111 /******************************************************************************
112  * Stop USB this stops the LowLevel Part and deregisters USB devices.
113  */
114 int usb_stop(void)
115 {
116         asynch_allowed=1;
117         usb_hub_reset();
118         return usb_lowlevel_stop();
119 }
120
121 /*
122  * disables the asynch behaviour of the control message. This is used for data
123  * transfers that uses the exclusiv access to the control and bulk messages.
124  */
125 void usb_disable_asynch(int disable)
126 {
127         asynch_allowed=!disable;
128 }
129
130
131 /*-------------------------------------------------------------------
132  * Message wrappers.
133  *
134  */
135
136 /*
137  * submits an Interrupt Message
138  */
139 int usb_submit_int_msg(struct usb_device *dev, unsigned long pipe,
140                         void *buffer,int transfer_len, int interval)
141 {
142         return submit_int_msg(dev,pipe,buffer,transfer_len,interval);
143 }
144
145 /*
146  * submits a control message and waits for comletion (at least timeout * 1ms)
147  * If timeout is 0, we don't wait for completion (used as example to set and
148  * clear keyboards LEDs). For data transfers, (storage transfers) we don't
149  * allow control messages with 0 timeout, by previousely resetting the flag
150  * asynch_allowed (usb_disable_asynch(1)).
151  * returns the transfered length if OK or -1 if error. The transfered length
152  * and the current status are stored in the dev->act_len and dev->status.
153  */
154 int usb_control_msg(struct usb_device *dev, unsigned int pipe,
155                         unsigned char request, unsigned char requesttype,
156                         unsigned short value, unsigned short index,
157                         void *data, unsigned short size, int timeout)
158 {
159         if((timeout==0)&&(!asynch_allowed)) /* request for a asynch control pipe is not allowed */
160                 return -1;
161
162         /* set setup command */
163         setup_packet.requesttype = requesttype;
164         setup_packet.request = request;
165         setup_packet.value = swap_16(value);
166         setup_packet.index = swap_16(index);
167         setup_packet.length = swap_16(size);
168         USB_PRINTF("usb_control_msg: request: 0x%X, requesttype: 0x%X\nvalue 0x%X index 0x%X length 0x%X\n",
169                 request,requesttype,value,index,size);
170         dev->status=USB_ST_NOT_PROC; /*not yet processed */
171
172         submit_control_msg(dev,pipe,data,size,&setup_packet);
173         if(timeout==0) {
174                 return (int)size;
175         }
176         while(timeout--) {
177                 if(!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
178                         break;
179                 wait_ms(1);
180         }
181         if(dev->status==0)
182                 return dev->act_len;
183         else {
184                 return -1;
185         }
186 }
187
188 /*-------------------------------------------------------------------
189  * submits bulk message, and waits for completion. returns 0 if Ok or
190  * -1 if Error.
191  * synchronous behavior
192  */
193 int usb_bulk_msg(struct usb_device *dev, unsigned int pipe,
194                         void *data, int len, int *actual_length, int timeout)
195 {
196         if (len < 0)
197                 return -1;
198         dev->status=USB_ST_NOT_PROC; /*not yet processed */
199         submit_bulk_msg(dev,pipe,data,len);
200         while(timeout--) {
201                 if(!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
202                         break;
203                 wait_ms(1);
204         }
205         *actual_length=dev->act_len;
206         if(dev->status==0)
207                 return 0;
208         else
209                 return -1;
210 }
211
212
213 /*-------------------------------------------------------------------
214  * Max Packet stuff
215  */
216
217 /*
218  * returns the max packet size, depending on the pipe direction and
219  * the configurations values
220  */
221 int usb_maxpacket(struct usb_device *dev,unsigned long pipe)
222 {
223         if((pipe & USB_DIR_IN)==0) /* direction is out -> use emaxpacket out */
224                 return(dev->epmaxpacketout[((pipe>>15) & 0xf)]);
225         else
226                 return(dev->epmaxpacketin[((pipe>>15) & 0xf)]);
227 }
228
229 /*
230  * set the max packed value of all endpoints in the given configuration
231  */
232 int usb_set_maxpacket(struct usb_device *dev)
233 {
234         int i,ii,b;
235         struct usb_endpoint_descriptor *ep;
236
237         for(i=0; i<dev->config.bNumInterfaces;i++) {
238                 for(ii=0; ii<dev->config.if_desc[i].bNumEndpoints; ii++) {
239                         ep=&dev->config.if_desc[i].ep_desc[ii];
240                         b=ep->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
241
242                         if((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)==USB_ENDPOINT_XFER_CONTROL) {        /* Control => bidirectional */
243                                 dev->epmaxpacketout[b] = ep->wMaxPacketSize;
244                                 dev->epmaxpacketin [b] = ep->wMaxPacketSize;
245                                 USB_PRINTF("##Control EP epmaxpacketout/in[%d] = %d\n",b,dev->epmaxpacketin[b]);
246                         }
247                         else {
248                                 if ((ep->bEndpointAddress & 0x80)==0) { /* OUT Endpoint */
249                                         if(ep->wMaxPacketSize > dev->epmaxpacketout[b]) {
250                                                 dev->epmaxpacketout[b] = ep->wMaxPacketSize;
251                                                 USB_PRINTF("##EP epmaxpacketout[%d] = %d\n",b,dev->epmaxpacketout[b]);
252                                         }
253                                 }
254                                 else  { /* IN Endpoint */
255                                         if(ep->wMaxPacketSize > dev->epmaxpacketin[b]) {
256                                                 dev->epmaxpacketin[b] = ep->wMaxPacketSize;
257                                                 USB_PRINTF("##EP epmaxpacketin[%d] = %d\n",b,dev->epmaxpacketin[b]);
258                                         }
259                                 } /* if out */
260                         } /* if control */
261                 } /* for each endpoint */
262         }
263         return 0;
264 }
265
266 /*******************************************************************************
267  * Parse the config, located in buffer, and fills the dev->config structure.
268  * Note that all little/big endian swapping are done automatically.
269  */
270 int usb_parse_config(struct usb_device *dev, unsigned char *buffer, int cfgno)
271 {
272         struct usb_descriptor_header *head;
273         int index,ifno,epno;
274         ifno=-1;
275         epno=-1;
276
277         dev->configno=cfgno;
278         head =(struct usb_descriptor_header *)&buffer[0];
279         if(head->bDescriptorType!=USB_DT_CONFIG) {
280                 printf(" ERROR: NOT USB_CONFIG_DESC %x\n",head->bDescriptorType);
281                 return -1;
282         }
283         memcpy(&dev->config,buffer,buffer[0]);
284         dev->config.wTotalLength=swap_16(dev->config.wTotalLength);
285         dev->config.no_of_if=0;
286
287         index=dev->config.bLength;
288         /* Ok the first entry must be a configuration entry, now process the others */
289         head=(struct usb_descriptor_header *)&buffer[index];
290         while(index+1 < dev->config.wTotalLength) {
291                 switch(head->bDescriptorType) {
292                         case USB_DT_INTERFACE:
293                                 ifno=dev->config.no_of_if;
294                                 dev->config.no_of_if++; /* found an interface desc, increase numbers */
295                                 memcpy(&dev->config.if_desc[ifno],&buffer[index],buffer[index]); /* copy new desc */
296                                 dev->config.if_desc[ifno].no_of_ep=0;
297
298                                 break;
299                         case USB_DT_ENDPOINT:
300                                 epno=dev->config.if_desc[ifno].no_of_ep;
301                                 dev->config.if_desc[ifno].no_of_ep++; /* found an endpoint */
302                                 memcpy(&dev->config.if_desc[ifno].ep_desc[epno],&buffer[index],buffer[index]);
303                                 dev->config.if_desc[ifno].ep_desc[epno].wMaxPacketSize
304                                         =swap_16(dev->config.if_desc[ifno].ep_desc[epno].wMaxPacketSize);
305                                 USB_PRINTF("if %d, ep %d\n",ifno,epno);
306                                 break;
307                         default:
308                                 if(head->bLength==0)
309                                         return 1;
310                                 USB_PRINTF("unknown Description Type : %x\n",head->bDescriptorType);
311                                 {
312                                         int i;
313                                         unsigned char *ch;
314                                         ch=(unsigned char *)head;
315                                         for(i=0;i<head->bLength; i++)
316                                                 USB_PRINTF("%02X ",*ch++);
317                                         USB_PRINTF("\n\n\n");
318                                 }
319                                 break;
320                 }
321                 index+=head->bLength;
322                 head=(struct usb_descriptor_header *)&buffer[index];
323         }
324         return 1;
325 }
326
327 /***********************************************************************
328  * Clears an endpoint
329  * endp: endpoint number in bits 0-3;
330  * direction flag in bit 7 (1 = IN, 0 = OUT)
331  */
332 int usb_clear_halt(struct usb_device *dev, int pipe)
333 {
334         int result;
335         int endp = usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
336
337         result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
338                 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0, endp, NULL, 0, USB_CNTL_TIMEOUT * 3);
339
340         /* don't clear if failed */
341         if (result < 0)
342                 return result;
343
344         /*
345          * NOTE: we do not get status and verify reset was successful
346          * as some devices are reported to lock up upon this check..
347          */
348
349         usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
350
351         /* toggle is reset on clear */
352         usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
353         return 0;
354 }
355
356
357 /**********************************************************************
358  * get_descriptor type
359  */
360 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
361 {
362         int res;
363         res = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
364                         USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
365                         (type << 8) + index, 0,
366                         buf, size, USB_CNTL_TIMEOUT);
367         return res;
368 }
369
370 /**********************************************************************
371  * gets configuration cfgno and store it in the buffer
372  */
373 int usb_get_configuration_no(struct usb_device *dev,unsigned char *buffer,int cfgno)
374 {
375         int result;
376         unsigned int tmp;
377         struct usb_config_descriptor *config;
378
379
380         config=(struct usb_config_descriptor *)&buffer[0];
381         result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 8);
382         if (result < 8) {
383                 if (result < 0)
384                         printf("unable to get descriptor, error %lX\n",dev->status);
385                 else
386                         printf("config descriptor too short (expected %i, got %i)\n",8,result);
387                 return -1;
388         }
389         tmp=swap_16(config->wTotalLength);
390
391         if (tmp > USB_BUFSIZ) {
392                 USB_PRINTF("usb_get_configuration_no: failed to get descriptor - too long: %d\n",
393                         tmp);
394                 return -1;
395         }
396
397         result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, tmp);
398         USB_PRINTF("get_conf_no %d Result %d, wLength %d\n",cfgno,result,tmp);
399         return result;
400 }
401
402 /********************************************************************
403  * set address of a device to the value in dev->devnum.
404  * This can only be done by addressing the device via the default address (0)
405  */
406 int usb_set_address(struct usb_device *dev)
407 {
408         int res;
409
410         USB_PRINTF("set address %d\n",dev->devnum);
411         res=usb_control_msg(dev, usb_snddefctrl(dev),
412                 USB_REQ_SET_ADDRESS, 0,
413                 (dev->devnum),0,
414                 NULL,0, USB_CNTL_TIMEOUT);
415         return res;
416 }
417
418 /********************************************************************
419  * set interface number to interface
420  */
421 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
422 {
423         struct usb_interface_descriptor *if_face = NULL;
424         int ret, i;
425
426         for (i = 0; i < dev->config.bNumInterfaces; i++) {
427                 if (dev->config.if_desc[i].bInterfaceNumber == interface) {
428                         if_face = &dev->config.if_desc[i];
429                         break;
430                 }
431         }
432         if (!if_face) {
433                 printf("selecting invalid interface %d", interface);
434                 return -1;
435         }
436
437         if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
438             USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE, alternate,
439             interface, NULL, 0, USB_CNTL_TIMEOUT * 5)) < 0)
440                 return ret;
441
442         return 0;
443 }
444
445 /********************************************************************
446  * set configuration number to configuration
447  */
448 int usb_set_configuration(struct usb_device *dev, int configuration)
449 {
450         int res;
451         USB_PRINTF("set configuration %d\n",configuration);
452         /* set setup command */
453         res=usb_control_msg(dev, usb_sndctrlpipe(dev,0),
454                 USB_REQ_SET_CONFIGURATION, 0,
455                 configuration,0,
456                 NULL,0, USB_CNTL_TIMEOUT);
457         if(res==0) {
458                 dev->toggle[0] = 0;
459                 dev->toggle[1] = 0;
460                 return 0;
461         }
462         else
463                 return -1;
464 }
465
466 /********************************************************************
467  * set protocol to protocol
468  */
469 int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
470 {
471         return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
472                 USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
473                 protocol, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
474 }
475
476 /********************************************************************
477  * set idle
478  */
479 int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
480 {
481         return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
482                 USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
483                 (duration << 8) | report_id, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
484 }
485
486 /********************************************************************
487  * get report
488  */
489 int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
490 {
491         return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
492                 USB_REQ_GET_REPORT, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
493                 (type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
494 }
495
496 /********************************************************************
497  * get class descriptor
498  */
499 int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
500                 unsigned char type, unsigned char id, void *buf, int size)
501 {
502         return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
503                 USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
504                 (type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
505 }
506
507 /********************************************************************
508  * get string index in buffer
509  */
510 int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
511 {
512         int i;
513         int result;
514
515         for (i = 0; i < 3; ++i) {
516                 /* some devices are flaky */
517                 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
518                         USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
519                         (USB_DT_STRING << 8) + index, langid, buf, size,
520                         USB_CNTL_TIMEOUT);
521
522                 if (result > 0)
523                         break;
524         }
525
526         return result;
527 }
528
529
530 static void usb_try_string_workarounds(unsigned char *buf, int *length)
531 {
532         int newlength, oldlength = *length;
533
534         for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
535                 if (!isprint(buf[newlength]) || buf[newlength + 1])
536                         break;
537
538         if (newlength > 2) {
539                 buf[0] = newlength;
540                 *length = newlength;
541         }
542 }
543
544
545 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
546                 unsigned int index, unsigned char *buf)
547 {
548         int rc;
549
550         /* Try to read the string descriptor by asking for the maximum
551          * possible number of bytes */
552         rc = usb_get_string(dev, langid, index, buf, 255);
553
554         /* If that failed try to read the descriptor length, then
555          * ask for just that many bytes */
556         if (rc < 2) {
557                 rc = usb_get_string(dev, langid, index, buf, 2);
558                 if (rc == 2)
559                         rc = usb_get_string(dev, langid, index, buf, buf[0]);
560         }
561
562         if (rc >= 2) {
563                 if (!buf[0] && !buf[1])
564                         usb_try_string_workarounds(buf, &rc);
565
566                 /* There might be extra junk at the end of the descriptor */
567                 if (buf[0] < rc)
568                         rc = buf[0];
569
570                 rc = rc - (rc & 1); /* force a multiple of two */
571         }
572
573         if (rc < 2)
574                 rc = -1;
575
576         return rc;
577 }
578
579
580 /********************************************************************
581  * usb_string:
582  * Get string index and translate it to ascii.
583  * returns string length (> 0) or error (< 0)
584  */
585 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
586 {
587         unsigned char mybuf[USB_BUFSIZ];
588         unsigned char *tbuf;
589         int err;
590         unsigned int u, idx;
591
592         if (size <= 0 || !buf || !index)
593                 return -1;
594         buf[0] = 0;
595         tbuf=&mybuf[0];
596
597         /* get langid for strings if it's not yet known */
598         if (!dev->have_langid) {
599                 err = usb_string_sub(dev, 0, 0, tbuf);
600                 if (err < 0) {
601                         USB_PRINTF("error getting string descriptor 0 (error=%x)\n",dev->status);
602                         return -1;
603                 } else if (tbuf[0] < 4) {
604                         USB_PRINTF("string descriptor 0 too short\n");
605                         return -1;
606                 } else {
607                         dev->have_langid = -1;
608                         dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
609                                 /* always use the first langid listed */
610                         USB_PRINTF("USB device number %d default language ID 0x%x\n",
611                                 dev->devnum, dev->string_langid);
612                 }
613         }
614
615         err = usb_string_sub(dev, dev->string_langid, index, tbuf);
616         if (err < 0)
617                 return err;
618
619         size--;         /* leave room for trailing NULL char in output buffer */
620         for (idx = 0, u = 2; u < err; u += 2) {
621                 if (idx >= size)
622                         break;
623                 if (tbuf[u+1])                  /* high byte */
624                         buf[idx++] = '?';  /* non-ASCII character */
625                 else
626                         buf[idx++] = tbuf[u];
627         }
628         buf[idx] = 0;
629         err = idx;
630         return err;
631 }
632
633
634 /********************************************************************
635  * USB device handling:
636  * the USB device are static allocated [USB_MAX_DEVICE].
637  */
638
639
640 /* returns a pointer to the device with the index [index].
641  * if the device is not assigned (dev->devnum==-1) returns NULL
642  */
643 struct usb_device * usb_get_dev_index(int index)
644 {
645         if(usb_dev[index].devnum==-1)
646                 return NULL;
647         else
648                 return &usb_dev[index];
649 }
650
651
652 /* returns a pointer of a new device structure or NULL, if
653  * no device struct is available
654  */
655 struct usb_device * usb_alloc_new_device(void)
656 {
657         int i;
658         USB_PRINTF("New Device %d\n",dev_index);
659         if(dev_index==USB_MAX_DEVICE) {
660                 printf("ERROR, too many USB Devices, max=%d\n",USB_MAX_DEVICE);
661                 return NULL;
662         }
663         usb_dev[dev_index].devnum=dev_index+1; /* default Address is 0, real addresses start with 1 */
664         usb_dev[dev_index].maxchild=0;
665         for(i=0;i<USB_MAXCHILDREN;i++)
666                 usb_dev[dev_index].children[i]=NULL;
667         usb_dev[dev_index].parent=NULL;
668         dev_index++;
669         return &usb_dev[dev_index-1];
670 }
671
672
673 /*
674  * By the time we get here, the device has gotten a new device ID
675  * and is in the default state. We need to identify the thing and
676  * get the ball rolling..
677  *
678  * Returns 0 for success, != 0 for error.
679  */
680 int usb_new_device(struct usb_device *dev)
681 {
682         int addr, err;
683         int tmp;
684         unsigned char tmpbuf[USB_BUFSIZ];
685
686         dev->descriptor.bMaxPacketSize0 = 8;  /* Start off at 8 bytes  */
687         dev->maxpacketsize = 0;         /* Default to 8 byte max packet size */
688         dev->epmaxpacketin [0] = 8;
689         dev->epmaxpacketout[0] = 8;
690
691         /* We still haven't set the Address yet */
692         addr = dev->devnum;
693         dev->devnum = 0;
694
695 #undef NEW_INIT_SEQ
696 #ifdef NEW_INIT_SEQ
697         /* this is a Windows scheme of initialization sequence, with double
698          * reset of the device. Some equipment is said to work only with such
699          * init sequence; this patch is based on the work by Alan Stern:
700          * http://sourceforge.net/mailarchive/forum.php?thread_id=5729457&forum_id=5398
701          */
702         int j;
703         struct usb_device_descriptor *desc;
704         int port = -1;
705         struct usb_device *parent = dev->parent;
706         unsigned short portstatus;
707
708         /* send 64-byte GET-DEVICE-DESCRIPTOR request.  Since the descriptor is
709          * only 18 bytes long, this will terminate with a short packet.  But if
710          * the maxpacket size is 8 or 16 the device may be waiting to transmit
711          * some more. */
712
713         desc = (struct usb_device_descriptor *)tmpbuf;
714         desc->bMaxPacketSize0 = 0;
715         for (j = 0; j < 3; ++j) {
716                 err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, 64);
717                 if (err < 0) {
718                         USB_PRINTF("usb_new_device: 64 byte descr\n");
719                         break;
720                 }
721         }
722         dev->descriptor.bMaxPacketSize0 = desc->bMaxPacketSize0;
723
724         /* find the port number we're at */
725         if (parent) {
726
727                 for (j = 0; j < parent->maxchild; j++) {
728                         if (parent->children[j] == dev) {
729                                 port = j;
730                                 break;
731                         }
732                 }
733                 if (port < 0) {
734                         printf("usb_new_device: cannot locate device's port..\n");
735                         return 1;
736                 }
737
738                 /* reset the port for the second time */
739                 err = hub_port_reset(dev->parent, port, &portstatus);
740                 if (err < 0) {
741                         printf("\n     Couldn't reset port %i\n", port);
742                         return 1;
743                 }
744         }
745 #else
746         /* and this is the old and known way of initializing devices */
747         err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, 8);
748         if (err < 8) {
749                 printf("\n      USB device not responding, giving up (status=%lX)\n",dev->status);
750                 return 1;
751         }
752 #endif
753
754         dev->epmaxpacketin [0] = dev->descriptor.bMaxPacketSize0;
755         dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
756         switch (dev->descriptor.bMaxPacketSize0) {
757                 case 8: dev->maxpacketsize = 0; break;
758                 case 16: dev->maxpacketsize = 1; break;
759                 case 32: dev->maxpacketsize = 2; break;
760                 case 64: dev->maxpacketsize = 3; break;
761         }
762         dev->devnum = addr;
763
764         err = usb_set_address(dev); /* set address */
765
766         if (err < 0) {
767                 printf("\n      USB device not accepting new address (error=%lX)\n", dev->status);
768                 return 1;
769         }
770
771         wait_ms(10);    /* Let the SET_ADDRESS settle */
772
773         tmp = sizeof(dev->descriptor);
774
775         err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, sizeof(dev->descriptor));
776         if (err < tmp) {
777                 if (err < 0)
778                         printf("unable to get device descriptor (error=%d)\n",err);
779                 else
780                         printf("USB device descriptor short read (expected %i, got %i)\n",tmp,err);
781                 return 1;
782         }
783         /* correct le values */
784         dev->descriptor.bcdUSB=swap_16(dev->descriptor.bcdUSB);
785         dev->descriptor.idVendor=swap_16(dev->descriptor.idVendor);
786         dev->descriptor.idProduct=swap_16(dev->descriptor.idProduct);
787         dev->descriptor.bcdDevice=swap_16(dev->descriptor.bcdDevice);
788         /* only support for one config for now */
789         usb_get_configuration_no(dev,&tmpbuf[0],0);
790         usb_parse_config(dev,&tmpbuf[0],0);
791         usb_set_maxpacket(dev);
792         /* we set the default configuration here */
793         if (usb_set_configuration(dev, dev->config.bConfigurationValue)) {
794                 printf("failed to set default configuration len %d, status %lX\n",dev->act_len,dev->status);
795                 return -1;
796         }
797         USB_PRINTF("new device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
798                 dev->descriptor.iManufacturer, dev->descriptor.iProduct, dev->descriptor.iSerialNumber);
799         memset(dev->mf, 0, sizeof(dev->mf));
800         memset(dev->prod, 0, sizeof(dev->prod));
801         memset(dev->serial, 0, sizeof(dev->serial));
802         if (dev->descriptor.iManufacturer)
803                 usb_string(dev, dev->descriptor.iManufacturer, dev->mf, sizeof(dev->mf));
804         if (dev->descriptor.iProduct)
805                 usb_string(dev, dev->descriptor.iProduct, dev->prod, sizeof(dev->prod));
806         if (dev->descriptor.iSerialNumber)
807                 usb_string(dev, dev->descriptor.iSerialNumber, dev->serial, sizeof(dev->serial));
808         USB_PRINTF("Manufacturer %s\n", dev->mf);
809         USB_PRINTF("Product      %s\n", dev->prod);
810         USB_PRINTF("SerialNumber %s\n", dev->serial);
811         /* now prode if the device is a hub */
812         usb_hub_probe(dev,0);
813         return 0;
814 }
815
816 /* build device Tree  */
817 void usb_scan_devices(void)
818 {
819         int i;
820         struct usb_device *dev;
821
822         /* first make all devices unknown */
823         for(i=0;i<USB_MAX_DEVICE;i++) {
824                 memset(&usb_dev[i],0,sizeof(struct usb_device));
825                 usb_dev[i].devnum=-1;
826         }
827         dev_index=0;
828         /* device 0 is always present (root hub, so let it analyze) */
829         dev=usb_alloc_new_device();
830         usb_new_device(dev);
831         printf("%d USB Device(s) found\n",dev_index);
832         /* insert "driver" if possible */
833 #ifdef CONFIG_USB_KEYBOARD
834         drv_usb_kbd_init();
835         USB_PRINTF("scan end\n");
836 #endif
837 }
838
839
840 /****************************************************************************
841  * HUB "Driver"
842  * Probes device for being a hub and configurate it
843  */
844
845 #undef  USB_HUB_DEBUG
846
847 #ifdef  USB_HUB_DEBUG
848 #define USB_HUB_PRINTF(fmt,args...)     printf (fmt ,##args)
849 #else
850 #define USB_HUB_PRINTF(fmt,args...)
851 #endif
852
853
854 static struct usb_hub_device hub_dev[USB_MAX_HUB];
855 static int usb_hub_index;
856
857
858 int usb_get_hub_descriptor(struct usb_device *dev, void *data, int size)
859 {
860         return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
861                 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
862                 USB_DT_HUB << 8, 0, data, size, USB_CNTL_TIMEOUT);
863 }
864
865 int usb_clear_hub_feature(struct usb_device *dev, int feature)
866 {
867         return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
868                 USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, USB_CNTL_TIMEOUT);
869 }
870
871 int usb_clear_port_feature(struct usb_device *dev, int port, int feature)
872 {
873         return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
874                 USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port, NULL, 0, USB_CNTL_TIMEOUT);
875 }
876
877 int usb_set_port_feature(struct usb_device *dev, int port, int feature)
878 {
879         return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
880                 USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port, NULL, 0, USB_CNTL_TIMEOUT);
881 }
882
883 int usb_get_hub_status(struct usb_device *dev, void *data)
884 {
885         return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
886                         USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
887                         data, sizeof(struct usb_hub_status), USB_CNTL_TIMEOUT);
888 }
889
890 int usb_get_port_status(struct usb_device *dev, int port, void *data)
891 {
892         return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
893                         USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port,
894                         data, sizeof(struct usb_hub_status), USB_CNTL_TIMEOUT);
895 }
896
897
898 static void usb_hub_power_on(struct usb_hub_device *hub)
899 {
900         int i;
901         struct usb_device *dev;
902
903         dev=hub->pusb_dev;
904         /* Enable power to the ports */
905         USB_HUB_PRINTF("enabling power on all ports\n");
906         for (i = 0; i < dev->maxchild; i++) {
907                 usb_set_port_feature(dev, i + 1, USB_PORT_FEAT_POWER);
908                 USB_HUB_PRINTF("port %d returns %lX\n",i+1,dev->status);
909                 wait_ms(hub->desc.bPwrOn2PwrGood * 2);
910         }
911 }
912
913 void usb_hub_reset(void)
914 {
915         usb_hub_index=0;
916 }
917
918 struct usb_hub_device *usb_hub_allocate(void)
919 {
920         if(usb_hub_index<USB_MAX_HUB) {
921                 return &hub_dev[usb_hub_index++];
922         }
923         printf("ERROR: USB_MAX_HUB (%d) reached\n",USB_MAX_HUB);
924         return NULL;
925 }
926
927 #define MAX_TRIES 5
928
929 static int hub_port_reset(struct usb_device *dev, int port,
930                         unsigned short *portstat)
931 {
932         int tries;
933         struct usb_port_status portsts;
934         unsigned short portstatus, portchange;
935
936
937         USB_HUB_PRINTF("hub_port_reset: resetting port %d...\n", port);
938         for(tries=0;tries<MAX_TRIES;tries++) {
939
940                 usb_set_port_feature(dev, port + 1, USB_PORT_FEAT_RESET);
941                 wait_ms(200);
942
943                 if (usb_get_port_status(dev, port + 1, &portsts)<0) {
944                         USB_HUB_PRINTF("get_port_status failed status %lX\n",dev->status);
945                         return -1;
946                 }
947                 portstatus = swap_16(portsts.wPortStatus);
948                 portchange = swap_16(portsts.wPortChange);
949                 USB_HUB_PRINTF("portstatus %x, change %x, %s\n", portstatus ,portchange,
950                         portstatus&(1<<USB_PORT_FEAT_LOWSPEED) ? "Low Speed" : "High Speed");
951                 USB_HUB_PRINTF("STAT_C_CONNECTION = %d STAT_CONNECTION = %d  USB_PORT_STAT_ENABLE %d\n",
952                         (portchange & USB_PORT_STAT_C_CONNECTION) ? 1 : 0,
953                         (portstatus & USB_PORT_STAT_CONNECTION) ? 1 : 0,
954                         (portstatus & USB_PORT_STAT_ENABLE) ? 1 : 0);
955                 if ((portchange & USB_PORT_STAT_C_CONNECTION) ||
956                     !(portstatus & USB_PORT_STAT_CONNECTION))
957                         return -1;
958
959                 if (portstatus & USB_PORT_STAT_ENABLE) {
960
961                         break;
962                 }
963
964                 wait_ms(200);
965         }
966
967         if (tries==MAX_TRIES) {
968                 USB_HUB_PRINTF("Cannot enable port %i after %i retries, disabling port.\n", port+1, MAX_TRIES);
969                 USB_HUB_PRINTF("Maybe the USB cable is bad?\n");
970                 return -1;
971         }
972
973         usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_RESET);
974         *portstat = portstatus;
975         return 0;
976
977 }
978
979
980 void usb_hub_port_connect_change(struct usb_device *dev, int port)
981 {
982         struct usb_device *usb;
983         struct usb_port_status portsts;
984         unsigned short portstatus, portchange;
985
986         /* Check status */
987         if (usb_get_port_status(dev, port + 1, &portsts)<0) {
988                 USB_HUB_PRINTF("get_port_status failed\n");
989                 return;
990         }
991
992         portstatus = swap_16(portsts.wPortStatus);
993         portchange = swap_16(portsts.wPortChange);
994         USB_HUB_PRINTF("portstatus %x, change %x, %s\n", portstatus, portchange,
995                 portstatus&(1<<USB_PORT_FEAT_LOWSPEED) ? "Low Speed" : "High Speed");
996
997         /* Clear the connection change status */
998         usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_CONNECTION);
999
1000         /* Disconnect any existing devices under this port */
1001         if (((!(portstatus & USB_PORT_STAT_CONNECTION)) &&
1002              (!(portstatus & USB_PORT_STAT_ENABLE)))|| (dev->children[port])) {
1003                 USB_HUB_PRINTF("usb_disconnect(&hub->children[port]);\n");
1004                 /* Return now if nothing is connected */
1005                 if (!(portstatus & USB_PORT_STAT_CONNECTION))
1006                         return;
1007         }
1008         wait_ms(200);
1009
1010         /* Reset the port */
1011         if (hub_port_reset(dev, port, &portstatus) < 0) {
1012                 printf("cannot reset port %i!?\n", port + 1);
1013                 return;
1014         }
1015
1016         wait_ms(200);
1017
1018         /* Allocate a new device struct for it */
1019         usb=usb_alloc_new_device();
1020         usb->slow = (portstatus & USB_PORT_STAT_LOW_SPEED) ? 1 : 0;
1021
1022         dev->children[port] = usb;
1023         usb->parent=dev;
1024         /* Run it through the hoops (find a driver, etc) */
1025         if (usb_new_device(usb)) {
1026                 /* Woops, disable the port */
1027                 USB_HUB_PRINTF("hub: disabling port %d\n", port + 1);
1028                 usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_ENABLE);
1029         }
1030 }
1031
1032
1033 int usb_hub_configure(struct usb_device *dev)
1034 {
1035         unsigned char buffer[USB_BUFSIZ], *bitmap;
1036         struct usb_hub_descriptor *descriptor;
1037         struct usb_hub_status *hubsts;
1038         int i;
1039         struct usb_hub_device *hub;
1040
1041         /* "allocate" Hub device */
1042         hub=usb_hub_allocate();
1043         if(hub==NULL)
1044                 return -1;
1045         hub->pusb_dev=dev;
1046         /* Get the the hub descriptor */
1047         if (usb_get_hub_descriptor(dev, buffer, 4) < 0) {
1048                 USB_HUB_PRINTF("usb_hub_configure: failed to get hub descriptor, giving up %lX\n",dev->status);
1049                 return -1;
1050         }
1051         descriptor = (struct usb_hub_descriptor *)buffer;
1052
1053         /* silence compiler warning if USB_BUFSIZ is > 256 [= sizeof(char)] */
1054         i = descriptor->bLength;
1055         if (i > USB_BUFSIZ) {
1056                 USB_HUB_PRINTF("usb_hub_configure: failed to get hub descriptor - too long: %d\N",
1057                         descriptor->bLength);
1058                 return -1;
1059         }
1060
1061         if (usb_get_hub_descriptor(dev, buffer, descriptor->bLength) < 0) {
1062                 USB_HUB_PRINTF("usb_hub_configure: failed to get hub descriptor 2nd giving up %lX\n",dev->status);
1063                 return -1;
1064         }
1065         memcpy((unsigned char *)&hub->desc,buffer,descriptor->bLength);
1066         /* adjust 16bit values */
1067         hub->desc.wHubCharacteristics=swap_16(descriptor->wHubCharacteristics);
1068         /* set the bitmap */
1069         bitmap=(unsigned char *)&hub->desc.DeviceRemovable[0];
1070         memset(bitmap,0xff,(USB_MAXCHILDREN+1+7)/8); /* devices not removable by default */
1071         bitmap=(unsigned char *)&hub->desc.PortPowerCtrlMask[0];
1072         memset(bitmap,0xff,(USB_MAXCHILDREN+1+7)/8); /* PowerMask = 1B */
1073         for(i=0;i<((hub->desc.bNbrPorts + 1 + 7)/8);i++) {
1074                 hub->desc.DeviceRemovable[i]=descriptor->DeviceRemovable[i];
1075         }
1076         for(i=0;i<((hub->desc.bNbrPorts + 1 + 7)/8);i++) {
1077                 hub->desc.DeviceRemovable[i]=descriptor->PortPowerCtrlMask[i];
1078         }
1079         dev->maxchild = descriptor->bNbrPorts;
1080         USB_HUB_PRINTF("%d ports detected\n", dev->maxchild);
1081
1082         switch (hub->desc.wHubCharacteristics & HUB_CHAR_LPSM) {
1083                 case 0x00:
1084                         USB_HUB_PRINTF("ganged power switching\n");
1085                         break;
1086                 case 0x01:
1087                         USB_HUB_PRINTF("individual port power switching\n");
1088                         break;
1089                 case 0x02:
1090                 case 0x03:
1091                         USB_HUB_PRINTF("unknown reserved power switching mode\n");
1092                         break;
1093         }
1094
1095         if (hub->desc.wHubCharacteristics & HUB_CHAR_COMPOUND)
1096                 USB_HUB_PRINTF("part of a compound device\n");
1097         else
1098                 USB_HUB_PRINTF("standalone hub\n");
1099
1100         switch (hub->desc.wHubCharacteristics & HUB_CHAR_OCPM) {
1101                 case 0x00:
1102                         USB_HUB_PRINTF("global over-current protection\n");
1103                         break;
1104                 case 0x08:
1105                         USB_HUB_PRINTF("individual port over-current protection\n");
1106                         break;
1107                 case 0x10:
1108                 case 0x18:
1109                         USB_HUB_PRINTF("no over-current protection\n");
1110       break;
1111         }
1112         USB_HUB_PRINTF("power on to power good time: %dms\n", descriptor->bPwrOn2PwrGood * 2);
1113         USB_HUB_PRINTF("hub controller current requirement: %dmA\n", descriptor->bHubContrCurrent);
1114         for (i = 0; i < dev->maxchild; i++)
1115                 USB_HUB_PRINTF("port %d is%s removable\n", i + 1,
1116                         hub->desc.DeviceRemovable[(i + 1)/8] & (1 << ((i + 1)%8)) ? " not" : "");
1117         if (sizeof(struct usb_hub_status) > USB_BUFSIZ) {
1118                 USB_HUB_PRINTF("usb_hub_configure: failed to get Status - too long: %d\n",
1119                         descriptor->bLength);
1120                 return -1;
1121         }
1122
1123         if (usb_get_hub_status(dev, buffer) < 0) {
1124                 USB_HUB_PRINTF("usb_hub_configure: failed to get Status %lX\n",dev->status);
1125                 return -1;
1126         }
1127         hubsts = (struct usb_hub_status *)buffer;
1128         USB_HUB_PRINTF("get_hub_status returned status %X, change %X\n",
1129                 swap_16(hubsts->wHubStatus),swap_16(hubsts->wHubChange));
1130         USB_HUB_PRINTF("local power source is %s\n",
1131                 (swap_16(hubsts->wHubStatus) & HUB_STATUS_LOCAL_POWER) ? "lost (inactive)" : "good");
1132         USB_HUB_PRINTF("%sover-current condition exists\n",
1133                 (swap_16(hubsts->wHubStatus) & HUB_STATUS_OVERCURRENT) ? "" : "no ");
1134         usb_hub_power_on(hub);
1135         for (i = 0; i < dev->maxchild; i++) {
1136                 struct usb_port_status portsts;
1137                 unsigned short portstatus, portchange;
1138
1139                 if (usb_get_port_status(dev, i + 1, &portsts) < 0) {
1140                         USB_HUB_PRINTF("get_port_status failed\n");
1141                         continue;
1142                 }
1143                 portstatus = swap_16(portsts.wPortStatus);
1144                 portchange = swap_16(portsts.wPortChange);
1145                 USB_HUB_PRINTF("Port %d Status %X Change %X\n",i+1,portstatus,portchange);
1146                 if (portchange & USB_PORT_STAT_C_CONNECTION) {
1147                         USB_HUB_PRINTF("port %d connection change\n", i + 1);
1148                         usb_hub_port_connect_change(dev, i);
1149                 }
1150                 if (portchange & USB_PORT_STAT_C_ENABLE) {
1151                         USB_HUB_PRINTF("port %d enable change, status %x\n", i + 1, portstatus);
1152                         usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_ENABLE);
1153
1154                         /* EM interference sometimes causes bad shielded USB devices to
1155                          * be shutdown by the hub, this hack enables them again.
1156                          * Works at least with mouse driver */
1157                         if (!(portstatus & USB_PORT_STAT_ENABLE) &&
1158                                 (portstatus & USB_PORT_STAT_CONNECTION) && (dev->children[i])) {
1159                                 USB_HUB_PRINTF("already running port %i disabled by hub (EMI?), re-enabling...\n",
1160                                         i + 1);
1161                                         usb_hub_port_connect_change(dev, i);
1162                         }
1163                 }
1164                 if (portstatus & USB_PORT_STAT_SUSPEND) {
1165                         USB_HUB_PRINTF("port %d suspend change\n", i + 1);
1166                         usb_clear_port_feature(dev, i + 1,  USB_PORT_FEAT_SUSPEND);
1167                 }
1168
1169                 if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
1170                         USB_HUB_PRINTF("port %d over-current change\n", i + 1);
1171                         usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_OVER_CURRENT);
1172                         usb_hub_power_on(hub);
1173                 }
1174
1175                 if (portchange & USB_PORT_STAT_C_RESET) {
1176                         USB_HUB_PRINTF("port %d reset change\n", i + 1);
1177                         usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_RESET);
1178                 }
1179         } /* end for i all ports */
1180
1181         return 0;
1182 }
1183
1184 int usb_hub_probe(struct usb_device *dev, int ifnum)
1185 {
1186         struct usb_interface_descriptor *iface;
1187         struct usb_endpoint_descriptor *ep;
1188         int ret;
1189
1190         iface = &dev->config.if_desc[ifnum];
1191         /* Is it a hub? */
1192         if (iface->bInterfaceClass != USB_CLASS_HUB)
1193                 return 0;
1194         /* Some hubs have a subclass of 1, which AFAICT according to the */
1195         /*  specs is not defined, but it works */
1196         if ((iface->bInterfaceSubClass != 0) &&
1197             (iface->bInterfaceSubClass != 1))
1198                 return 0;
1199         /* Multiple endpoints? What kind of mutant ninja-hub is this? */
1200         if (iface->bNumEndpoints != 1)
1201                 return 0;
1202         ep = &iface->ep_desc[0];
1203         /* Output endpoint? Curiousier and curiousier.. */
1204         if (!(ep->bEndpointAddress & USB_DIR_IN))
1205                 return 0;
1206         /* If it's not an interrupt endpoint, we'd better punt! */
1207         if ((ep->bmAttributes & 3) != 3)
1208                 return 0;
1209         /* We found a hub */
1210         USB_HUB_PRINTF("USB hub found\n");
1211         ret=usb_hub_configure(dev);
1212         return ret;
1213 }
1214
1215 #endif /* (CONFIG_COMMANDS & CFG_CMD_USB) */
1216
1217 /* EOF */