Fixed tools/env utilities
[u-boot-openmoko/mini2440.git] / common / usb.c
blob4df01eabe513163eeb80475f9495b72ea504ac80
1 /*
3 * Most of this source has been derived from the Linux USB
4 * project:
5 * (C) Copyright Linus Torvalds 1999
6 * (C) Copyright Johannes Erdfelt 1999-2001
7 * (C) Copyright Andreas Gal 1999
8 * (C) Copyright Gregory P. Smith 1999
9 * (C) Copyright Deti Fliegl 1999 (new USB architecture)
10 * (C) Copyright Randy Dunlap 2000
11 * (C) Copyright David Brownell 2000 (kernel hotplug, usb_device_id)
12 * (C) Copyright Yggdrasil Computing, Inc. 2000
13 * (usb_device_id matching changes by Adam J. Richter)
15 * Adapted for U-Boot:
16 * (C) Copyright 2001 Denis Peter, MPL AG Switzerland
18 * See file CREDITS for list of people who contributed to this
19 * project.
21 * This program is free software; you can redistribute it and/or
22 * modify it under the terms of the GNU General Public License as
23 * published by the Free Software Foundation; either version 2 of
24 * the License, or (at your option) any later version.
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public License
32 * along with this program; if not, write to the Free Software
33 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
34 * MA 02111-1307 USA
39 * How it works:
41 * Since this is a bootloader, the devices will not be automatic
42 * (re)configured on hotplug, but after a restart of the USB the
43 * device should work.
45 * For each transfer (except "Interrupt") we wait for completion.
47 #include <common.h>
48 #include <command.h>
49 #include <asm/processor.h>
50 #include <linux/ctype.h>
52 #if defined(CONFIG_CMD_USB)
54 #include <usb.h>
55 #ifdef CONFIG_4xx
56 #include <asm/4xx_pci.h>
57 #endif
59 #undef USB_DEBUG
61 #ifdef USB_DEBUG
62 #define USB_PRINTF(fmt,args...) printf (fmt ,##args)
63 #else
64 #define USB_PRINTF(fmt,args...)
65 #endif
67 #define USB_BUFSIZ 512
69 static struct usb_device usb_dev[USB_MAX_DEVICE];
70 static int dev_index;
71 static int running;
72 static int asynch_allowed;
73 static struct devrequest setup_packet;
75 char usb_started; /* flag for the started/stopped USB status */
77 /**********************************************************************
78 * some forward declerations...
80 void usb_scan_devices(void);
82 int usb_hub_probe(struct usb_device *dev, int ifnum);
83 void usb_hub_reset(void);
86 /***********************************************************************
87 * wait_ms
90 void __inline__ wait_ms(unsigned long ms)
92 while(ms-->0)
93 udelay(1000);
95 /***************************************************************************
96 * Init USB Device
99 int usb_init(void)
101 int result;
103 running=0;
104 dev_index=0;
105 asynch_allowed=1;
106 usb_hub_reset();
107 /* init low_level USB */
108 printf("USB: ");
109 result = usb_lowlevel_init();
110 /* if lowlevel init is OK, scan the bus for devices i.e. search HUBs and configure them */
111 if(result==0) {
112 printf("scanning bus for devices... ");
113 running=1;
114 usb_scan_devices();
115 usb_started = 1;
116 return 0;
118 else {
119 printf("Error, couldn't init Lowlevel part\n");
120 usb_started = 0;
121 return -1;
125 /******************************************************************************
126 * Stop USB this stops the LowLevel Part and deregisters USB devices.
128 int usb_stop(void)
130 asynch_allowed=1;
131 usb_started = 0;
132 usb_hub_reset();
133 return usb_lowlevel_stop();
137 * disables the asynch behaviour of the control message. This is used for data
138 * transfers that uses the exclusiv access to the control and bulk messages.
140 void usb_disable_asynch(int disable)
142 asynch_allowed=!disable;
146 /*-------------------------------------------------------------------
147 * Message wrappers.
152 * submits an Interrupt Message
154 int usb_submit_int_msg(struct usb_device *dev, unsigned long pipe,
155 void *buffer,int transfer_len, int interval)
157 return submit_int_msg(dev,pipe,buffer,transfer_len,interval);
161 * submits a control message and waits for comletion (at least timeout * 1ms)
162 * If timeout is 0, we don't wait for completion (used as example to set and
163 * clear keyboards LEDs). For data transfers, (storage transfers) we don't
164 * allow control messages with 0 timeout, by previousely resetting the flag
165 * asynch_allowed (usb_disable_asynch(1)).
166 * returns the transfered length if OK or -1 if error. The transfered length
167 * and the current status are stored in the dev->act_len and dev->status.
169 int usb_control_msg(struct usb_device *dev, unsigned int pipe,
170 unsigned char request, unsigned char requesttype,
171 unsigned short value, unsigned short index,
172 void *data, unsigned short size, int timeout)
174 if((timeout==0)&&(!asynch_allowed)) /* request for a asynch control pipe is not allowed */
175 return -1;
177 /* set setup command */
178 setup_packet.requesttype = requesttype;
179 setup_packet.request = request;
180 setup_packet.value = swap_16(value);
181 setup_packet.index = swap_16(index);
182 setup_packet.length = swap_16(size);
183 USB_PRINTF("usb_control_msg: request: 0x%X, requesttype: 0x%X\nvalue 0x%X index 0x%X length 0x%X\n",
184 request,requesttype,value,index,size);
185 dev->status=USB_ST_NOT_PROC; /*not yet processed */
187 submit_control_msg(dev,pipe,data,size,&setup_packet);
188 if(timeout==0) {
189 return (int)size;
191 while(timeout--) {
192 if(!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
193 break;
194 wait_ms(1);
196 if(dev->status==0)
197 return dev->act_len;
198 else {
199 return -1;
203 /*-------------------------------------------------------------------
204 * submits bulk message, and waits for completion. returns 0 if Ok or
205 * -1 if Error.
206 * synchronous behavior
208 int usb_bulk_msg(struct usb_device *dev, unsigned int pipe,
209 void *data, int len, int *actual_length, int timeout)
211 if (len < 0)
212 return -1;
213 dev->status=USB_ST_NOT_PROC; /*not yet processed */
214 submit_bulk_msg(dev,pipe,data,len);
215 while(timeout--) {
216 if(!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
217 break;
218 wait_ms(1);
220 *actual_length=dev->act_len;
221 if(dev->status==0)
222 return 0;
223 else
224 return -1;
228 /*-------------------------------------------------------------------
229 * Max Packet stuff
233 * returns the max packet size, depending on the pipe direction and
234 * the configurations values
236 int usb_maxpacket(struct usb_device *dev,unsigned long pipe)
238 if((pipe & USB_DIR_IN)==0) /* direction is out -> use emaxpacket out */
239 return(dev->epmaxpacketout[((pipe>>15) & 0xf)]);
240 else
241 return(dev->epmaxpacketin[((pipe>>15) & 0xf)]);
245 * set the max packed value of all endpoints in the given configuration
247 int usb_set_maxpacket(struct usb_device *dev)
249 int i,ii,b;
250 struct usb_endpoint_descriptor *ep;
252 for(i=0; i<dev->config.bNumInterfaces;i++) {
253 for(ii=0; ii<dev->config.if_desc[i].bNumEndpoints; ii++) {
254 ep=&dev->config.if_desc[i].ep_desc[ii];
255 b=ep->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
257 if((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)==USB_ENDPOINT_XFER_CONTROL) { /* Control => bidirectional */
258 dev->epmaxpacketout[b] = ep->wMaxPacketSize;
259 dev->epmaxpacketin [b] = ep->wMaxPacketSize;
260 USB_PRINTF("##Control EP epmaxpacketout/in[%d] = %d\n",b,dev->epmaxpacketin[b]);
262 else {
263 if ((ep->bEndpointAddress & 0x80)==0) { /* OUT Endpoint */
264 if(ep->wMaxPacketSize > dev->epmaxpacketout[b]) {
265 dev->epmaxpacketout[b] = ep->wMaxPacketSize;
266 USB_PRINTF("##EP epmaxpacketout[%d] = %d\n",b,dev->epmaxpacketout[b]);
269 else { /* IN Endpoint */
270 if(ep->wMaxPacketSize > dev->epmaxpacketin[b]) {
271 dev->epmaxpacketin[b] = ep->wMaxPacketSize;
272 USB_PRINTF("##EP epmaxpacketin[%d] = %d\n",b,dev->epmaxpacketin[b]);
274 } /* if out */
275 } /* if control */
276 } /* for each endpoint */
278 return 0;
281 /*******************************************************************************
282 * Parse the config, located in buffer, and fills the dev->config structure.
283 * Note that all little/big endian swapping are done automatically.
285 int usb_parse_config(struct usb_device *dev, unsigned char *buffer, int cfgno)
287 struct usb_descriptor_header *head;
288 int index, ifno, epno, curr_if_num;
289 int i;
290 unsigned char *ch;
292 ifno = -1;
293 epno = -1;
294 curr_if_num = -1;
296 dev->configno = cfgno;
297 head = (struct usb_descriptor_header *) &buffer[0];
298 if(head->bDescriptorType != USB_DT_CONFIG) {
299 printf(" ERROR: NOT USB_CONFIG_DESC %x\n", head->bDescriptorType);
300 return -1;
302 memcpy(&dev->config, buffer, buffer[0]);
303 dev->config.wTotalLength = swap_16(dev->config.wTotalLength);
304 dev->config.no_of_if = 0;
306 index = dev->config.bLength;
307 /* Ok the first entry must be a configuration entry, now process the others */
308 head = (struct usb_descriptor_header *) &buffer[index];
309 while(index + 1 < dev->config.wTotalLength) {
310 switch(head->bDescriptorType) {
311 case USB_DT_INTERFACE:
312 if(((struct usb_interface_descriptor *) &buffer[index])->
313 bInterfaceNumber != curr_if_num) {
314 /* this is a new interface, copy new desc */
315 ifno = dev->config.no_of_if;
316 dev->config.no_of_if++;
317 memcpy(&dev->config.if_desc[ifno],
318 &buffer[index], buffer[index]);
319 dev->config.if_desc[ifno].no_of_ep = 0;
320 dev->config.if_desc[ifno].num_altsetting = 1;
321 curr_if_num = dev->config.if_desc[ifno].bInterfaceNumber;
322 } else {
323 /* found alternate setting for the interface */
324 dev->config.if_desc[ifno].num_altsetting++;
326 break;
327 case USB_DT_ENDPOINT:
328 epno = dev->config.if_desc[ifno].no_of_ep;
329 dev->config.if_desc[ifno].no_of_ep++; /* found an endpoint */
330 memcpy(&dev->config.if_desc[ifno].ep_desc[epno],
331 &buffer[index], buffer[index]);
332 dev->config.if_desc[ifno].ep_desc[epno].wMaxPacketSize =
333 swap_16(dev->config.if_desc[ifno].ep_desc[epno].wMaxPacketSize);
334 USB_PRINTF("if %d, ep %d\n", ifno, epno);
335 break;
336 default:
337 if(head->bLength == 0)
338 return 1;
339 USB_PRINTF("unknown Description Type : %x\n", head->bDescriptorType);
341 ch = (unsigned char *)head;
342 for(i = 0; i < head->bLength; i++)
343 USB_PRINTF("%02X ", *ch++);
344 USB_PRINTF("\n\n\n");
346 break;
348 index += head->bLength;
349 head = (struct usb_descriptor_header *)&buffer[index];
351 return 1;
354 /***********************************************************************
355 * Clears an endpoint
356 * endp: endpoint number in bits 0-3;
357 * direction flag in bit 7 (1 = IN, 0 = OUT)
359 int usb_clear_halt(struct usb_device *dev, int pipe)
361 int result;
362 int endp = usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
364 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
365 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0, endp, NULL, 0, USB_CNTL_TIMEOUT * 3);
367 /* don't clear if failed */
368 if (result < 0)
369 return result;
372 * NOTE: we do not get status and verify reset was successful
373 * as some devices are reported to lock up upon this check..
376 usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
378 /* toggle is reset on clear */
379 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
380 return 0;
384 /**********************************************************************
385 * get_descriptor type
387 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
389 int res;
390 res = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
391 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
392 (type << 8) + index, 0,
393 buf, size, USB_CNTL_TIMEOUT);
394 return res;
397 /**********************************************************************
398 * gets configuration cfgno and store it in the buffer
400 int usb_get_configuration_no(struct usb_device *dev,unsigned char *buffer,int cfgno)
402 int result;
403 unsigned int tmp;
404 struct usb_config_descriptor *config;
407 config=(struct usb_config_descriptor *)&buffer[0];
408 result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 8);
409 if (result < 8) {
410 if (result < 0)
411 printf("unable to get descriptor, error %lX\n",dev->status);
412 else
413 printf("config descriptor too short (expected %i, got %i)\n",8,result);
414 return -1;
416 tmp=swap_16(config->wTotalLength);
418 if (tmp > USB_BUFSIZ) {
419 USB_PRINTF("usb_get_configuration_no: failed to get descriptor - too long: %d\n",
420 tmp);
421 return -1;
424 result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, tmp);
425 USB_PRINTF("get_conf_no %d Result %d, wLength %d\n",cfgno,result,tmp);
426 return result;
429 /********************************************************************
430 * set address of a device to the value in dev->devnum.
431 * This can only be done by addressing the device via the default address (0)
433 int usb_set_address(struct usb_device *dev)
435 int res;
437 USB_PRINTF("set address %d\n",dev->devnum);
438 res=usb_control_msg(dev, usb_snddefctrl(dev),
439 USB_REQ_SET_ADDRESS, 0,
440 (dev->devnum),0,
441 NULL,0, USB_CNTL_TIMEOUT);
442 return res;
445 /********************************************************************
446 * set interface number to interface
448 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
450 struct usb_interface_descriptor *if_face = NULL;
451 int ret, i;
453 for (i = 0; i < dev->config.bNumInterfaces; i++) {
454 if (dev->config.if_desc[i].bInterfaceNumber == interface) {
455 if_face = &dev->config.if_desc[i];
456 break;
459 if (!if_face) {
460 printf("selecting invalid interface %d", interface);
461 return -1;
464 * We should return now for devices with only one alternate setting.
465 * According to 9.4.10 of the Universal Serial Bus Specification Revision 2.0
466 * such devices can return with a STALL. This results in some USB sticks
467 * timeouting during initialization and then being unusable in U-Boot.
469 if (if_face->num_altsetting == 1)
470 return 0;
472 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
473 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE, alternate,
474 interface, NULL, 0, USB_CNTL_TIMEOUT * 5)) < 0)
475 return ret;
477 return 0;
480 /********************************************************************
481 * set configuration number to configuration
483 int usb_set_configuration(struct usb_device *dev, int configuration)
485 int res;
486 USB_PRINTF("set configuration %d\n",configuration);
487 /* set setup command */
488 res=usb_control_msg(dev, usb_sndctrlpipe(dev,0),
489 USB_REQ_SET_CONFIGURATION, 0,
490 configuration,0,
491 NULL,0, USB_CNTL_TIMEOUT);
492 if(res==0) {
493 dev->toggle[0] = 0;
494 dev->toggle[1] = 0;
495 return 0;
497 else
498 return -1;
501 /********************************************************************
502 * set protocol to protocol
504 int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
506 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
507 USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
508 protocol, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
511 /********************************************************************
512 * set idle
514 int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
516 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
517 USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
518 (duration << 8) | report_id, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
521 /********************************************************************
522 * get report
524 int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type, unsigned char id, void *buf, int size)
526 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
527 USB_REQ_GET_REPORT, USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
528 (type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
531 /********************************************************************
532 * get class descriptor
534 int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
535 unsigned char type, unsigned char id, void *buf, int size)
537 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
538 USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
539 (type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
542 /********************************************************************
543 * get string index in buffer
545 int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
547 int i;
548 int result;
550 for (i = 0; i < 3; ++i) {
551 /* some devices are flaky */
552 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
553 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
554 (USB_DT_STRING << 8) + index, langid, buf, size,
555 USB_CNTL_TIMEOUT);
557 if (result > 0)
558 break;
561 return result;
565 static void usb_try_string_workarounds(unsigned char *buf, int *length)
567 int newlength, oldlength = *length;
569 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
570 if (!isprint(buf[newlength]) || buf[newlength + 1])
571 break;
573 if (newlength > 2) {
574 buf[0] = newlength;
575 *length = newlength;
580 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
581 unsigned int index, unsigned char *buf)
583 int rc;
585 /* Try to read the string descriptor by asking for the maximum
586 * possible number of bytes */
587 rc = usb_get_string(dev, langid, index, buf, 255);
589 /* If that failed try to read the descriptor length, then
590 * ask for just that many bytes */
591 if (rc < 2) {
592 rc = usb_get_string(dev, langid, index, buf, 2);
593 if (rc == 2)
594 rc = usb_get_string(dev, langid, index, buf, buf[0]);
597 if (rc >= 2) {
598 if (!buf[0] && !buf[1])
599 usb_try_string_workarounds(buf, &rc);
601 /* There might be extra junk at the end of the descriptor */
602 if (buf[0] < rc)
603 rc = buf[0];
605 rc = rc - (rc & 1); /* force a multiple of two */
608 if (rc < 2)
609 rc = -1;
611 return rc;
615 /********************************************************************
616 * usb_string:
617 * Get string index and translate it to ascii.
618 * returns string length (> 0) or error (< 0)
620 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
622 unsigned char mybuf[USB_BUFSIZ];
623 unsigned char *tbuf;
624 int err;
625 unsigned int u, idx;
627 if (size <= 0 || !buf || !index)
628 return -1;
629 buf[0] = 0;
630 tbuf=&mybuf[0];
632 /* get langid for strings if it's not yet known */
633 if (!dev->have_langid) {
634 err = usb_string_sub(dev, 0, 0, tbuf);
635 if (err < 0) {
636 USB_PRINTF("error getting string descriptor 0 (error=%x)\n",dev->status);
637 return -1;
638 } else if (tbuf[0] < 4) {
639 USB_PRINTF("string descriptor 0 too short\n");
640 return -1;
641 } else {
642 dev->have_langid = -1;
643 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
644 /* always use the first langid listed */
645 USB_PRINTF("USB device number %d default language ID 0x%x\n",
646 dev->devnum, dev->string_langid);
650 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
651 if (err < 0)
652 return err;
654 size--; /* leave room for trailing NULL char in output buffer */
655 for (idx = 0, u = 2; u < err; u += 2) {
656 if (idx >= size)
657 break;
658 if (tbuf[u+1]) /* high byte */
659 buf[idx++] = '?'; /* non-ASCII character */
660 else
661 buf[idx++] = tbuf[u];
663 buf[idx] = 0;
664 err = idx;
665 return err;
669 /********************************************************************
670 * USB device handling:
671 * the USB device are static allocated [USB_MAX_DEVICE].
675 /* returns a pointer to the device with the index [index].
676 * if the device is not assigned (dev->devnum==-1) returns NULL
678 struct usb_device * usb_get_dev_index(int index)
680 if(usb_dev[index].devnum==-1)
681 return NULL;
682 else
683 return &usb_dev[index];
687 /* returns a pointer of a new device structure or NULL, if
688 * no device struct is available
690 struct usb_device * usb_alloc_new_device(void)
692 int i;
693 USB_PRINTF("New Device %d\n",dev_index);
694 if(dev_index==USB_MAX_DEVICE) {
695 printf("ERROR, too many USB Devices, max=%d\n",USB_MAX_DEVICE);
696 return NULL;
698 usb_dev[dev_index].devnum=dev_index+1; /* default Address is 0, real addresses start with 1 */
699 usb_dev[dev_index].maxchild=0;
700 for(i=0;i<USB_MAXCHILDREN;i++)
701 usb_dev[dev_index].children[i]=NULL;
702 usb_dev[dev_index].parent=NULL;
703 dev_index++;
704 return &usb_dev[dev_index-1];
709 * By the time we get here, the device has gotten a new device ID
710 * and is in the default state. We need to identify the thing and
711 * get the ball rolling..
713 * Returns 0 for success, != 0 for error.
715 int usb_new_device(struct usb_device *dev)
717 int addr, err;
718 int tmp;
719 unsigned char tmpbuf[USB_BUFSIZ];
721 dev->descriptor.bMaxPacketSize0 = 8; /* Start off at 8 bytes */
722 dev->maxpacketsize = 0; /* Default to 8 byte max packet size */
723 dev->epmaxpacketin [0] = 8;
724 dev->epmaxpacketout[0] = 8;
726 /* We still haven't set the Address yet */
727 addr = dev->devnum;
728 dev->devnum = 0;
730 #undef NEW_INIT_SEQ
731 #ifdef NEW_INIT_SEQ
732 /* this is a Windows scheme of initialization sequence, with double
733 * reset of the device. Some equipment is said to work only with such
734 * init sequence; this patch is based on the work by Alan Stern:
735 * http://sourceforge.net/mailarchive/forum.php?thread_id=5729457&forum_id=5398
737 int j;
738 struct usb_device_descriptor *desc;
739 int port = -1;
740 struct usb_device *parent = dev->parent;
741 unsigned short portstatus;
743 /* send 64-byte GET-DEVICE-DESCRIPTOR request. Since the descriptor is
744 * only 18 bytes long, this will terminate with a short packet. But if
745 * the maxpacket size is 8 or 16 the device may be waiting to transmit
746 * some more. */
748 desc = (struct usb_device_descriptor *)tmpbuf;
749 desc->bMaxPacketSize0 = 0;
750 for (j = 0; j < 3; ++j) {
751 err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, 64);
752 if (err < 0) {
753 USB_PRINTF("usb_new_device: 64 byte descr\n");
754 break;
757 dev->descriptor.bMaxPacketSize0 = desc->bMaxPacketSize0;
759 /* find the port number we're at */
760 if (parent) {
762 for (j = 0; j < parent->maxchild; j++) {
763 if (parent->children[j] == dev) {
764 port = j;
765 break;
768 if (port < 0) {
769 printf("usb_new_device: cannot locate device's port..\n");
770 return 1;
773 /* reset the port for the second time */
774 err = hub_port_reset(dev->parent, port, &portstatus);
775 if (err < 0) {
776 printf("\n Couldn't reset port %i\n", port);
777 return 1;
780 #else
781 /* and this is the old and known way of initializing devices */
782 err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, 8);
783 if (err < 8) {
784 printf("\n USB device not responding, giving up (status=%lX)\n",dev->status);
785 return 1;
787 #endif
789 dev->epmaxpacketin [0] = dev->descriptor.bMaxPacketSize0;
790 dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
791 switch (dev->descriptor.bMaxPacketSize0) {
792 case 8: dev->maxpacketsize = 0; break;
793 case 16: dev->maxpacketsize = 1; break;
794 case 32: dev->maxpacketsize = 2; break;
795 case 64: dev->maxpacketsize = 3; break;
797 dev->devnum = addr;
799 err = usb_set_address(dev); /* set address */
801 if (err < 0) {
802 printf("\n USB device not accepting new address (error=%lX)\n", dev->status);
803 return 1;
806 wait_ms(10); /* Let the SET_ADDRESS settle */
808 tmp = sizeof(dev->descriptor);
810 err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor, sizeof(dev->descriptor));
811 if (err < tmp) {
812 if (err < 0)
813 printf("unable to get device descriptor (error=%d)\n",err);
814 else
815 printf("USB device descriptor short read (expected %i, got %i)\n",tmp,err);
816 return 1;
818 /* correct le values */
819 dev->descriptor.bcdUSB=swap_16(dev->descriptor.bcdUSB);
820 dev->descriptor.idVendor=swap_16(dev->descriptor.idVendor);
821 dev->descriptor.idProduct=swap_16(dev->descriptor.idProduct);
822 dev->descriptor.bcdDevice=swap_16(dev->descriptor.bcdDevice);
823 /* only support for one config for now */
824 usb_get_configuration_no(dev,&tmpbuf[0],0);
825 usb_parse_config(dev,&tmpbuf[0],0);
826 usb_set_maxpacket(dev);
827 /* we set the default configuration here */
828 if (usb_set_configuration(dev, dev->config.bConfigurationValue)) {
829 printf("failed to set default configuration len %d, status %lX\n",dev->act_len,dev->status);
830 return -1;
832 USB_PRINTF("new device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
833 dev->descriptor.iManufacturer, dev->descriptor.iProduct, dev->descriptor.iSerialNumber);
834 memset(dev->mf, 0, sizeof(dev->mf));
835 memset(dev->prod, 0, sizeof(dev->prod));
836 memset(dev->serial, 0, sizeof(dev->serial));
837 if (dev->descriptor.iManufacturer)
838 usb_string(dev, dev->descriptor.iManufacturer, dev->mf, sizeof(dev->mf));
839 if (dev->descriptor.iProduct)
840 usb_string(dev, dev->descriptor.iProduct, dev->prod, sizeof(dev->prod));
841 if (dev->descriptor.iSerialNumber)
842 usb_string(dev, dev->descriptor.iSerialNumber, dev->serial, sizeof(dev->serial));
843 USB_PRINTF("Manufacturer %s\n", dev->mf);
844 USB_PRINTF("Product %s\n", dev->prod);
845 USB_PRINTF("SerialNumber %s\n", dev->serial);
846 /* now prode if the device is a hub */
847 usb_hub_probe(dev,0);
848 return 0;
851 /* build device Tree */
852 void usb_scan_devices(void)
854 int i;
855 struct usb_device *dev;
857 /* first make all devices unknown */
858 for(i=0;i<USB_MAX_DEVICE;i++) {
859 memset(&usb_dev[i],0,sizeof(struct usb_device));
860 usb_dev[i].devnum=-1;
862 dev_index=0;
863 /* device 0 is always present (root hub, so let it analyze) */
864 dev=usb_alloc_new_device();
865 usb_new_device(dev);
866 printf("%d USB Device(s) found\n",dev_index);
867 /* insert "driver" if possible */
868 #ifdef CONFIG_USB_KEYBOARD
869 drv_usb_kbd_init();
870 USB_PRINTF("scan end\n");
871 #endif
875 /****************************************************************************
876 * HUB "Driver"
877 * Probes device for being a hub and configurate it
880 #undef USB_HUB_DEBUG
882 #ifdef USB_HUB_DEBUG
883 #define USB_HUB_PRINTF(fmt,args...) printf (fmt ,##args)
884 #else
885 #define USB_HUB_PRINTF(fmt,args...)
886 #endif
889 static struct usb_hub_device hub_dev[USB_MAX_HUB];
890 static int usb_hub_index;
893 int usb_get_hub_descriptor(struct usb_device *dev, void *data, int size)
895 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
896 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
897 USB_DT_HUB << 8, 0, data, size, USB_CNTL_TIMEOUT);
900 int usb_clear_hub_feature(struct usb_device *dev, int feature)
902 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
903 USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, USB_CNTL_TIMEOUT);
906 int usb_clear_port_feature(struct usb_device *dev, int port, int feature)
908 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
909 USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port, NULL, 0, USB_CNTL_TIMEOUT);
912 int usb_set_port_feature(struct usb_device *dev, int port, int feature)
914 return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
915 USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port, NULL, 0, USB_CNTL_TIMEOUT);
918 int usb_get_hub_status(struct usb_device *dev, void *data)
920 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
921 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
922 data, sizeof(struct usb_hub_status), USB_CNTL_TIMEOUT);
925 int usb_get_port_status(struct usb_device *dev, int port, void *data)
927 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
928 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port,
929 data, sizeof(struct usb_hub_status), USB_CNTL_TIMEOUT);
933 static void usb_hub_power_on(struct usb_hub_device *hub)
935 int i;
936 struct usb_device *dev;
938 dev=hub->pusb_dev;
939 /* Enable power to the ports */
940 USB_HUB_PRINTF("enabling power on all ports\n");
941 for (i = 0; i < dev->maxchild; i++) {
942 usb_set_port_feature(dev, i + 1, USB_PORT_FEAT_POWER);
943 USB_HUB_PRINTF("port %d returns %lX\n",i+1,dev->status);
944 wait_ms(hub->desc.bPwrOn2PwrGood * 2);
948 void usb_hub_reset(void)
950 usb_hub_index=0;
953 struct usb_hub_device *usb_hub_allocate(void)
955 if(usb_hub_index<USB_MAX_HUB) {
956 return &hub_dev[usb_hub_index++];
958 printf("ERROR: USB_MAX_HUB (%d) reached\n",USB_MAX_HUB);
959 return NULL;
962 #define MAX_TRIES 5
964 static int hub_port_reset(struct usb_device *dev, int port,
965 unsigned short *portstat)
967 int tries;
968 struct usb_port_status portsts;
969 unsigned short portstatus, portchange;
972 USB_HUB_PRINTF("hub_port_reset: resetting port %d...\n", port);
973 for(tries=0;tries<MAX_TRIES;tries++) {
975 usb_set_port_feature(dev, port + 1, USB_PORT_FEAT_RESET);
976 wait_ms(200);
978 if (usb_get_port_status(dev, port + 1, &portsts)<0) {
979 USB_HUB_PRINTF("get_port_status failed status %lX\n",dev->status);
980 return -1;
982 portstatus = swap_16(portsts.wPortStatus);
983 portchange = swap_16(portsts.wPortChange);
984 USB_HUB_PRINTF("portstatus %x, change %x, %s\n", portstatus ,portchange,
985 portstatus&(1<<USB_PORT_FEAT_LOWSPEED) ? "Low Speed" : "High Speed");
986 USB_HUB_PRINTF("STAT_C_CONNECTION = %d STAT_CONNECTION = %d USB_PORT_STAT_ENABLE %d\n",
987 (portchange & USB_PORT_STAT_C_CONNECTION) ? 1 : 0,
988 (portstatus & USB_PORT_STAT_CONNECTION) ? 1 : 0,
989 (portstatus & USB_PORT_STAT_ENABLE) ? 1 : 0);
990 if ((portchange & USB_PORT_STAT_C_CONNECTION) ||
991 !(portstatus & USB_PORT_STAT_CONNECTION))
992 return -1;
994 if (portstatus & USB_PORT_STAT_ENABLE) {
996 break;
999 wait_ms(200);
1002 if (tries==MAX_TRIES) {
1003 USB_HUB_PRINTF("Cannot enable port %i after %i retries, disabling port.\n", port+1, MAX_TRIES);
1004 USB_HUB_PRINTF("Maybe the USB cable is bad?\n");
1005 return -1;
1008 usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_RESET);
1009 *portstat = portstatus;
1010 return 0;
1015 void usb_hub_port_connect_change(struct usb_device *dev, int port)
1017 struct usb_device *usb;
1018 struct usb_port_status portsts;
1019 unsigned short portstatus, portchange;
1021 /* Check status */
1022 if (usb_get_port_status(dev, port + 1, &portsts)<0) {
1023 USB_HUB_PRINTF("get_port_status failed\n");
1024 return;
1027 portstatus = swap_16(portsts.wPortStatus);
1028 portchange = swap_16(portsts.wPortChange);
1029 USB_HUB_PRINTF("portstatus %x, change %x, %s\n", portstatus, portchange,
1030 portstatus&(1<<USB_PORT_FEAT_LOWSPEED) ? "Low Speed" : "High Speed");
1032 /* Clear the connection change status */
1033 usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_CONNECTION);
1035 /* Disconnect any existing devices under this port */
1036 if (((!(portstatus & USB_PORT_STAT_CONNECTION)) &&
1037 (!(portstatus & USB_PORT_STAT_ENABLE)))|| (dev->children[port])) {
1038 USB_HUB_PRINTF("usb_disconnect(&hub->children[port]);\n");
1039 /* Return now if nothing is connected */
1040 if (!(portstatus & USB_PORT_STAT_CONNECTION))
1041 return;
1043 wait_ms(200);
1045 /* Reset the port */
1046 if (hub_port_reset(dev, port, &portstatus) < 0) {
1047 printf("cannot reset port %i!?\n", port + 1);
1048 return;
1051 wait_ms(200);
1053 /* Allocate a new device struct for it */
1054 usb=usb_alloc_new_device();
1055 usb->slow = (portstatus & USB_PORT_STAT_LOW_SPEED) ? 1 : 0;
1057 dev->children[port] = usb;
1058 usb->parent=dev;
1059 /* Run it through the hoops (find a driver, etc) */
1060 if (usb_new_device(usb)) {
1061 /* Woops, disable the port */
1062 USB_HUB_PRINTF("hub: disabling port %d\n", port + 1);
1063 usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_ENABLE);
1068 int usb_hub_configure(struct usb_device *dev)
1070 unsigned char buffer[USB_BUFSIZ], *bitmap;
1071 struct usb_hub_descriptor *descriptor;
1072 struct usb_hub_status *hubsts;
1073 int i;
1074 struct usb_hub_device *hub;
1076 /* "allocate" Hub device */
1077 hub=usb_hub_allocate();
1078 if(hub==NULL)
1079 return -1;
1080 hub->pusb_dev=dev;
1081 /* Get the the hub descriptor */
1082 if (usb_get_hub_descriptor(dev, buffer, 4) < 0) {
1083 USB_HUB_PRINTF("usb_hub_configure: failed to get hub descriptor, giving up %lX\n",dev->status);
1084 return -1;
1086 descriptor = (struct usb_hub_descriptor *)buffer;
1088 /* silence compiler warning if USB_BUFSIZ is > 256 [= sizeof(char)] */
1089 i = descriptor->bLength;
1090 if (i > USB_BUFSIZ) {
1091 USB_HUB_PRINTF("usb_hub_configure: failed to get hub descriptor - too long: %d\N",
1092 descriptor->bLength);
1093 return -1;
1096 if (usb_get_hub_descriptor(dev, buffer, descriptor->bLength) < 0) {
1097 USB_HUB_PRINTF("usb_hub_configure: failed to get hub descriptor 2nd giving up %lX\n",dev->status);
1098 return -1;
1100 memcpy((unsigned char *)&hub->desc,buffer,descriptor->bLength);
1101 /* adjust 16bit values */
1102 hub->desc.wHubCharacteristics=swap_16(descriptor->wHubCharacteristics);
1103 /* set the bitmap */
1104 bitmap=(unsigned char *)&hub->desc.DeviceRemovable[0];
1105 memset(bitmap,0xff,(USB_MAXCHILDREN+1+7)/8); /* devices not removable by default */
1106 bitmap=(unsigned char *)&hub->desc.PortPowerCtrlMask[0];
1107 memset(bitmap,0xff,(USB_MAXCHILDREN+1+7)/8); /* PowerMask = 1B */
1108 for(i=0;i<((hub->desc.bNbrPorts + 1 + 7)/8);i++) {
1109 hub->desc.DeviceRemovable[i]=descriptor->DeviceRemovable[i];
1111 for(i=0;i<((hub->desc.bNbrPorts + 1 + 7)/8);i++) {
1112 hub->desc.DeviceRemovable[i]=descriptor->PortPowerCtrlMask[i];
1114 dev->maxchild = descriptor->bNbrPorts;
1115 USB_HUB_PRINTF("%d ports detected\n", dev->maxchild);
1117 switch (hub->desc.wHubCharacteristics & HUB_CHAR_LPSM) {
1118 case 0x00:
1119 USB_HUB_PRINTF("ganged power switching\n");
1120 break;
1121 case 0x01:
1122 USB_HUB_PRINTF("individual port power switching\n");
1123 break;
1124 case 0x02:
1125 case 0x03:
1126 USB_HUB_PRINTF("unknown reserved power switching mode\n");
1127 break;
1130 if (hub->desc.wHubCharacteristics & HUB_CHAR_COMPOUND)
1131 USB_HUB_PRINTF("part of a compound device\n");
1132 else
1133 USB_HUB_PRINTF("standalone hub\n");
1135 switch (hub->desc.wHubCharacteristics & HUB_CHAR_OCPM) {
1136 case 0x00:
1137 USB_HUB_PRINTF("global over-current protection\n");
1138 break;
1139 case 0x08:
1140 USB_HUB_PRINTF("individual port over-current protection\n");
1141 break;
1142 case 0x10:
1143 case 0x18:
1144 USB_HUB_PRINTF("no over-current protection\n");
1145 break;
1147 USB_HUB_PRINTF("power on to power good time: %dms\n", descriptor->bPwrOn2PwrGood * 2);
1148 USB_HUB_PRINTF("hub controller current requirement: %dmA\n", descriptor->bHubContrCurrent);
1149 for (i = 0; i < dev->maxchild; i++)
1150 USB_HUB_PRINTF("port %d is%s removable\n", i + 1,
1151 hub->desc.DeviceRemovable[(i + 1)/8] & (1 << ((i + 1)%8)) ? " not" : "");
1152 if (sizeof(struct usb_hub_status) > USB_BUFSIZ) {
1153 USB_HUB_PRINTF("usb_hub_configure: failed to get Status - too long: %d\n",
1154 descriptor->bLength);
1155 return -1;
1158 if (usb_get_hub_status(dev, buffer) < 0) {
1159 USB_HUB_PRINTF("usb_hub_configure: failed to get Status %lX\n",dev->status);
1160 return -1;
1162 hubsts = (struct usb_hub_status *)buffer;
1163 USB_HUB_PRINTF("get_hub_status returned status %X, change %X\n",
1164 swap_16(hubsts->wHubStatus),swap_16(hubsts->wHubChange));
1165 USB_HUB_PRINTF("local power source is %s\n",
1166 (swap_16(hubsts->wHubStatus) & HUB_STATUS_LOCAL_POWER) ? "lost (inactive)" : "good");
1167 USB_HUB_PRINTF("%sover-current condition exists\n",
1168 (swap_16(hubsts->wHubStatus) & HUB_STATUS_OVERCURRENT) ? "" : "no ");
1169 usb_hub_power_on(hub);
1170 for (i = 0; i < dev->maxchild; i++) {
1171 struct usb_port_status portsts;
1172 unsigned short portstatus, portchange;
1174 if (usb_get_port_status(dev, i + 1, &portsts) < 0) {
1175 USB_HUB_PRINTF("get_port_status failed\n");
1176 continue;
1178 portstatus = swap_16(portsts.wPortStatus);
1179 portchange = swap_16(portsts.wPortChange);
1180 USB_HUB_PRINTF("Port %d Status %X Change %X\n",i+1,portstatus,portchange);
1181 if (portchange & USB_PORT_STAT_C_CONNECTION) {
1182 USB_HUB_PRINTF("port %d connection change\n", i + 1);
1183 usb_hub_port_connect_change(dev, i);
1185 if (portchange & USB_PORT_STAT_C_ENABLE) {
1186 USB_HUB_PRINTF("port %d enable change, status %x\n", i + 1, portstatus);
1187 usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_ENABLE);
1189 /* EM interference sometimes causes bad shielded USB devices to
1190 * be shutdown by the hub, this hack enables them again.
1191 * Works at least with mouse driver */
1192 if (!(portstatus & USB_PORT_STAT_ENABLE) &&
1193 (portstatus & USB_PORT_STAT_CONNECTION) && (dev->children[i])) {
1194 USB_HUB_PRINTF("already running port %i disabled by hub (EMI?), re-enabling...\n",
1195 i + 1);
1196 usb_hub_port_connect_change(dev, i);
1199 if (portstatus & USB_PORT_STAT_SUSPEND) {
1200 USB_HUB_PRINTF("port %d suspend change\n", i + 1);
1201 usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_SUSPEND);
1204 if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
1205 USB_HUB_PRINTF("port %d over-current change\n", i + 1);
1206 usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_OVER_CURRENT);
1207 usb_hub_power_on(hub);
1210 if (portchange & USB_PORT_STAT_C_RESET) {
1211 USB_HUB_PRINTF("port %d reset change\n", i + 1);
1212 usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_RESET);
1214 } /* end for i all ports */
1216 return 0;
1219 int usb_hub_probe(struct usb_device *dev, int ifnum)
1221 struct usb_interface_descriptor *iface;
1222 struct usb_endpoint_descriptor *ep;
1223 int ret;
1225 iface = &dev->config.if_desc[ifnum];
1226 /* Is it a hub? */
1227 if (iface->bInterfaceClass != USB_CLASS_HUB)
1228 return 0;
1229 /* Some hubs have a subclass of 1, which AFAICT according to the */
1230 /* specs is not defined, but it works */
1231 if ((iface->bInterfaceSubClass != 0) &&
1232 (iface->bInterfaceSubClass != 1))
1233 return 0;
1234 /* Multiple endpoints? What kind of mutant ninja-hub is this? */
1235 if (iface->bNumEndpoints != 1)
1236 return 0;
1237 ep = &iface->ep_desc[0];
1238 /* Output endpoint? Curiousier and curiousier.. */
1239 if (!(ep->bEndpointAddress & USB_DIR_IN))
1240 return 0;
1241 /* If it's not an interrupt endpoint, we'd better punt! */
1242 if ((ep->bmAttributes & 3) != 3)
1243 return 0;
1244 /* We found a hub */
1245 USB_HUB_PRINTF("USB hub found\n");
1246 ret=usb_hub_configure(dev);
1247 return ret;
1250 #endif
1252 /* EOF */