xref: /openbmc/u-boot/common/usb.c (revision a2ac1b3a)
1 /*
2  *
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)
14  *
15  * Adapted for U-Boot:
16  * (C) Copyright 2001 Denis Peter, MPL AG Switzerland
17  *
18  * See file CREDITS for list of people who contributed to this
19  * project.
20  *
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.
25  *
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.
30  *
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
35  *
36  */
37 
38 /*
39  * How it works:
40  *
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.
44  *
45  * For each transfer (except "Interrupt") we wait for completion.
46  */
47 #include <common.h>
48 #include <command.h>
49 #include <asm/processor.h>
50 #include <linux/compiler.h>
51 #include <linux/ctype.h>
52 #include <asm/byteorder.h>
53 #include <asm/unaligned.h>
54 
55 #include <usb.h>
56 #ifdef CONFIG_4xx
57 #include <asm/4xx_pci.h>
58 #endif
59 
60 #ifdef DEBUG
61 #define USB_DEBUG	1
62 #define USB_HUB_DEBUG	1
63 #else
64 #define USB_DEBUG	0
65 #define USB_HUB_DEBUG	0
66 #endif
67 
68 #define USB_PRINTF(fmt, args...)	debug_cond(USB_DEBUG, fmt, ##args)
69 #define USB_HUB_PRINTF(fmt, args...)	debug_cond(USB_HUB_DEBUG, fmt, ##args)
70 
71 #define USB_BUFSIZ	512
72 
73 static struct usb_device usb_dev[USB_MAX_DEVICE];
74 static int dev_index;
75 static int asynch_allowed;
76 
77 char usb_started; /* flag for the started/stopped USB status */
78 
79 #ifndef CONFIG_USB_MAX_CONTROLLER_COUNT
80 #define CONFIG_USB_MAX_CONTROLLER_COUNT 1
81 #endif
82 
83 /***************************************************************************
84  * Init USB Device
85  */
86 int usb_init(void)
87 {
88 	void *ctrl;
89 	struct usb_device *dev;
90 	int i, start_index = 0;
91 
92 	dev_index = 0;
93 	asynch_allowed = 1;
94 	usb_hub_reset();
95 
96 	/* first make all devices unknown */
97 	for (i = 0; i < USB_MAX_DEVICE; i++) {
98 		memset(&usb_dev[i], 0, sizeof(struct usb_device));
99 		usb_dev[i].devnum = -1;
100 	}
101 
102 	/* init low_level USB */
103 	for (i = 0; i < CONFIG_USB_MAX_CONTROLLER_COUNT; i++) {
104 		/* init low_level USB */
105 		printf("USB%d:   ", i);
106 		if (usb_lowlevel_init(i, &ctrl)) {
107 			puts("lowlevel init failed\n");
108 			continue;
109 		}
110 		/*
111 		 * lowlevel init is OK, now scan the bus for devices
112 		 * i.e. search HUBs and configure them
113 		 */
114 		start_index = dev_index;
115 		printf("scanning bus %d for devices... ", i);
116 		dev = usb_alloc_new_device(ctrl);
117 		/*
118 		 * device 0 is always present
119 		 * (root hub, so let it analyze)
120 		 */
121 		if (dev)
122 			usb_new_device(dev);
123 
124 		if (start_index == dev_index)
125 			puts("No USB Device found\n");
126 		else
127 			printf("%d USB Device(s) found\n",
128 				dev_index - start_index);
129 
130 		usb_started = 1;
131 	}
132 
133 	USB_PRINTF("scan end\n");
134 	/* if we were not able to find at least one working bus, bail out */
135 	if (!usb_started) {
136 		puts("USB error: all controllers failed lowlevel init\n");
137 		return -1;
138 	}
139 
140 	return 0;
141 }
142 
143 /******************************************************************************
144  * Stop USB this stops the LowLevel Part and deregisters USB devices.
145  */
146 int usb_stop(void)
147 {
148 	int i;
149 
150 	if (usb_started) {
151 		asynch_allowed = 1;
152 		usb_started = 0;
153 		usb_hub_reset();
154 
155 		for (i = 0; i < CONFIG_USB_MAX_CONTROLLER_COUNT; i++) {
156 			if (usb_lowlevel_stop(i))
157 				printf("failed to stop USB controller %d\n", i);
158 		}
159 	}
160 
161 	return 0;
162 }
163 
164 /*
165  * disables the asynch behaviour of the control message. This is used for data
166  * transfers that uses the exclusiv access to the control and bulk messages.
167  * Returns the old value so it can be restored later.
168  */
169 int usb_disable_asynch(int disable)
170 {
171 	int old_value = asynch_allowed;
172 
173 	asynch_allowed = !disable;
174 	return old_value;
175 }
176 
177 
178 /*-------------------------------------------------------------------
179  * Message wrappers.
180  *
181  */
182 
183 /*
184  * submits an Interrupt Message
185  */
186 int usb_submit_int_msg(struct usb_device *dev, unsigned long pipe,
187 			void *buffer, int transfer_len, int interval)
188 {
189 	return submit_int_msg(dev, pipe, buffer, transfer_len, interval);
190 }
191 
192 /*
193  * submits a control message and waits for comletion (at least timeout * 1ms)
194  * If timeout is 0, we don't wait for completion (used as example to set and
195  * clear keyboards LEDs). For data transfers, (storage transfers) we don't
196  * allow control messages with 0 timeout, by previousely resetting the flag
197  * asynch_allowed (usb_disable_asynch(1)).
198  * returns the transfered length if OK or -1 if error. The transfered length
199  * and the current status are stored in the dev->act_len and dev->status.
200  */
201 int usb_control_msg(struct usb_device *dev, unsigned int pipe,
202 			unsigned char request, unsigned char requesttype,
203 			unsigned short value, unsigned short index,
204 			void *data, unsigned short size, int timeout)
205 {
206 	ALLOC_CACHE_ALIGN_BUFFER(struct devrequest, setup_packet, 1);
207 
208 	if ((timeout == 0) && (!asynch_allowed)) {
209 		/* request for a asynch control pipe is not allowed */
210 		return -1;
211 	}
212 
213 	/* set setup command */
214 	setup_packet->requesttype = requesttype;
215 	setup_packet->request = request;
216 	setup_packet->value = cpu_to_le16(value);
217 	setup_packet->index = cpu_to_le16(index);
218 	setup_packet->length = cpu_to_le16(size);
219 	USB_PRINTF("usb_control_msg: request: 0x%X, requesttype: 0x%X, " \
220 		   "value 0x%X index 0x%X length 0x%X\n",
221 		   request, requesttype, value, index, size);
222 	dev->status = USB_ST_NOT_PROC; /*not yet processed */
223 
224 	if (submit_control_msg(dev, pipe, data, size, setup_packet) < 0)
225 		return -1;
226 	if (timeout == 0)
227 		return (int)size;
228 
229 	/*
230 	 * Wait for status to update until timeout expires, USB driver
231 	 * interrupt handler may set the status when the USB operation has
232 	 * been completed.
233 	 */
234 	while (timeout--) {
235 		if (!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
236 			break;
237 		mdelay(1);
238 	}
239 	if (dev->status)
240 		return -1;
241 
242 	return dev->act_len;
243 
244 }
245 
246 /*-------------------------------------------------------------------
247  * submits bulk message, and waits for completion. returns 0 if Ok or
248  * -1 if Error.
249  * synchronous behavior
250  */
251 int usb_bulk_msg(struct usb_device *dev, unsigned int pipe,
252 			void *data, int len, int *actual_length, int timeout)
253 {
254 	if (len < 0)
255 		return -1;
256 	dev->status = USB_ST_NOT_PROC; /*not yet processed */
257 	if (submit_bulk_msg(dev, pipe, data, len) < 0)
258 		return -1;
259 	while (timeout--) {
260 		if (!((volatile unsigned long)dev->status & USB_ST_NOT_PROC))
261 			break;
262 		mdelay(1);
263 	}
264 	*actual_length = dev->act_len;
265 	if (dev->status == 0)
266 		return 0;
267 	else
268 		return -1;
269 }
270 
271 
272 /*-------------------------------------------------------------------
273  * Max Packet stuff
274  */
275 
276 /*
277  * returns the max packet size, depending on the pipe direction and
278  * the configurations values
279  */
280 int usb_maxpacket(struct usb_device *dev, unsigned long pipe)
281 {
282 	/* direction is out -> use emaxpacket out */
283 	if ((pipe & USB_DIR_IN) == 0)
284 		return dev->epmaxpacketout[((pipe>>15) & 0xf)];
285 	else
286 		return dev->epmaxpacketin[((pipe>>15) & 0xf)];
287 }
288 
289 /*
290  * The routine usb_set_maxpacket_ep() is extracted from the loop of routine
291  * usb_set_maxpacket(), because the optimizer of GCC 4.x chokes on this routine
292  * when it is inlined in 1 single routine. What happens is that the register r3
293  * is used as loop-count 'i', but gets overwritten later on.
294  * This is clearly a compiler bug, but it is easier to workaround it here than
295  * to update the compiler (Occurs with at least several GCC 4.{1,2},x
296  * CodeSourcery compilers like e.g. 2007q3, 2008q1, 2008q3 lite editions on ARM)
297  *
298  * NOTE: Similar behaviour was observed with GCC4.6 on ARMv5.
299  */
300 static void noinline
301 usb_set_maxpacket_ep(struct usb_device *dev, int if_idx, int ep_idx)
302 {
303 	int b;
304 	struct usb_endpoint_descriptor *ep;
305 	u16 ep_wMaxPacketSize;
306 
307 	ep = &dev->config.if_desc[if_idx].ep_desc[ep_idx];
308 
309 	b = ep->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
310 	ep_wMaxPacketSize = get_unaligned(&ep->wMaxPacketSize);
311 
312 	if ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
313 						USB_ENDPOINT_XFER_CONTROL) {
314 		/* Control => bidirectional */
315 		dev->epmaxpacketout[b] = ep_wMaxPacketSize;
316 		dev->epmaxpacketin[b] = ep_wMaxPacketSize;
317 		USB_PRINTF("##Control EP epmaxpacketout/in[%d] = %d\n",
318 			   b, dev->epmaxpacketin[b]);
319 	} else {
320 		if ((ep->bEndpointAddress & 0x80) == 0) {
321 			/* OUT Endpoint */
322 			if (ep_wMaxPacketSize > dev->epmaxpacketout[b]) {
323 				dev->epmaxpacketout[b] = ep_wMaxPacketSize;
324 				USB_PRINTF("##EP epmaxpacketout[%d] = %d\n",
325 					   b, dev->epmaxpacketout[b]);
326 			}
327 		} else {
328 			/* IN Endpoint */
329 			if (ep_wMaxPacketSize > dev->epmaxpacketin[b]) {
330 				dev->epmaxpacketin[b] = ep_wMaxPacketSize;
331 				USB_PRINTF("##EP epmaxpacketin[%d] = %d\n",
332 					   b, dev->epmaxpacketin[b]);
333 			}
334 		} /* if out */
335 	} /* if control */
336 }
337 
338 /*
339  * set the max packed value of all endpoints in the given configuration
340  */
341 static int usb_set_maxpacket(struct usb_device *dev)
342 {
343 	int i, ii;
344 
345 	for (i = 0; i < dev->config.desc.bNumInterfaces; i++)
346 		for (ii = 0; ii < dev->config.if_desc[i].desc.bNumEndpoints; ii++)
347 			usb_set_maxpacket_ep(dev, i, ii);
348 
349 	return 0;
350 }
351 
352 /*******************************************************************************
353  * Parse the config, located in buffer, and fills the dev->config structure.
354  * Note that all little/big endian swapping are done automatically.
355  */
356 static int usb_parse_config(struct usb_device *dev,
357 			unsigned char *buffer, int cfgno)
358 {
359 	struct usb_descriptor_header *head;
360 	int index, ifno, epno, curr_if_num;
361 	int i;
362 	u16 ep_wMaxPacketSize;
363 
364 	ifno = -1;
365 	epno = -1;
366 	curr_if_num = -1;
367 
368 	dev->configno = cfgno;
369 	head = (struct usb_descriptor_header *) &buffer[0];
370 	if (head->bDescriptorType != USB_DT_CONFIG) {
371 		printf(" ERROR: NOT USB_CONFIG_DESC %x\n",
372 			head->bDescriptorType);
373 		return -1;
374 	}
375 	memcpy(&dev->config, buffer, buffer[0]);
376 	le16_to_cpus(&(dev->config.desc.wTotalLength));
377 	dev->config.no_of_if = 0;
378 
379 	index = dev->config.desc.bLength;
380 	/* Ok the first entry must be a configuration entry,
381 	 * now process the others */
382 	head = (struct usb_descriptor_header *) &buffer[index];
383 	while (index + 1 < dev->config.desc.wTotalLength) {
384 		switch (head->bDescriptorType) {
385 		case USB_DT_INTERFACE:
386 			if (((struct usb_interface_descriptor *) \
387 			     &buffer[index])->bInterfaceNumber != curr_if_num) {
388 				/* this is a new interface, copy new desc */
389 				ifno = dev->config.no_of_if;
390 				dev->config.no_of_if++;
391 				memcpy(&dev->config.if_desc[ifno],
392 					&buffer[index], buffer[index]);
393 				dev->config.if_desc[ifno].no_of_ep = 0;
394 				dev->config.if_desc[ifno].num_altsetting = 1;
395 				curr_if_num =
396 				     dev->config.if_desc[ifno].desc.bInterfaceNumber;
397 			} else {
398 				/* found alternate setting for the interface */
399 				dev->config.if_desc[ifno].num_altsetting++;
400 			}
401 			break;
402 		case USB_DT_ENDPOINT:
403 			epno = dev->config.if_desc[ifno].no_of_ep;
404 			/* found an endpoint */
405 			dev->config.if_desc[ifno].no_of_ep++;
406 			memcpy(&dev->config.if_desc[ifno].ep_desc[epno],
407 				&buffer[index], buffer[index]);
408 			ep_wMaxPacketSize = get_unaligned(&dev->config.\
409 							if_desc[ifno].\
410 							ep_desc[epno].\
411 							wMaxPacketSize);
412 			put_unaligned(le16_to_cpu(ep_wMaxPacketSize),
413 					&dev->config.\
414 					if_desc[ifno].\
415 					ep_desc[epno].\
416 					wMaxPacketSize);
417 			USB_PRINTF("if %d, ep %d\n", ifno, epno);
418 			break;
419 		default:
420 			if (head->bLength == 0)
421 				return 1;
422 
423 			USB_PRINTF("unknown Description Type : %x\n",
424 				   head->bDescriptorType);
425 
426 			{
427 #ifdef USB_DEBUG
428 				unsigned char *ch = (unsigned char *)head;
429 #endif
430 				for (i = 0; i < head->bLength; i++)
431 					USB_PRINTF("%02X ", *ch++);
432 				USB_PRINTF("\n\n\n");
433 			}
434 			break;
435 		}
436 		index += head->bLength;
437 		head = (struct usb_descriptor_header *)&buffer[index];
438 	}
439 	return 1;
440 }
441 
442 /***********************************************************************
443  * Clears an endpoint
444  * endp: endpoint number in bits 0-3;
445  * direction flag in bit 7 (1 = IN, 0 = OUT)
446  */
447 int usb_clear_halt(struct usb_device *dev, int pipe)
448 {
449 	int result;
450 	int endp = usb_pipeendpoint(pipe)|(usb_pipein(pipe)<<7);
451 
452 	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
453 				 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0,
454 				 endp, NULL, 0, USB_CNTL_TIMEOUT * 3);
455 
456 	/* don't clear if failed */
457 	if (result < 0)
458 		return result;
459 
460 	/*
461 	 * NOTE: we do not get status and verify reset was successful
462 	 * as some devices are reported to lock up upon this check..
463 	 */
464 
465 	usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
466 
467 	/* toggle is reset on clear */
468 	usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
469 	return 0;
470 }
471 
472 
473 /**********************************************************************
474  * get_descriptor type
475  */
476 static int usb_get_descriptor(struct usb_device *dev, unsigned char type,
477 			unsigned char index, void *buf, int size)
478 {
479 	int res;
480 	res = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
481 			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
482 			(type << 8) + index, 0,
483 			buf, size, USB_CNTL_TIMEOUT);
484 	return res;
485 }
486 
487 /**********************************************************************
488  * gets configuration cfgno and store it in the buffer
489  */
490 int usb_get_configuration_no(struct usb_device *dev,
491 			     unsigned char *buffer, int cfgno)
492 {
493 	int result;
494 	unsigned int tmp;
495 	struct usb_configuration_descriptor *config;
496 
497 	config = (struct usb_configuration_descriptor *)&buffer[0];
498 	result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, 9);
499 	if (result < 9) {
500 		if (result < 0)
501 			printf("unable to get descriptor, error %lX\n",
502 				dev->status);
503 		else
504 			printf("config descriptor too short " \
505 				"(expected %i, got %i)\n", 9, result);
506 		return -1;
507 	}
508 	tmp = le16_to_cpu(config->wTotalLength);
509 
510 	if (tmp > USB_BUFSIZ) {
511 		USB_PRINTF("usb_get_configuration_no: failed to get " \
512 			   "descriptor - too long: %d\n", tmp);
513 		return -1;
514 	}
515 
516 	result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno, buffer, tmp);
517 	USB_PRINTF("get_conf_no %d Result %d, wLength %d\n",
518 		   cfgno, result, tmp);
519 	return result;
520 }
521 
522 /********************************************************************
523  * set address of a device to the value in dev->devnum.
524  * This can only be done by addressing the device via the default address (0)
525  */
526 static int usb_set_address(struct usb_device *dev)
527 {
528 	int res;
529 
530 	USB_PRINTF("set address %d\n", dev->devnum);
531 	res = usb_control_msg(dev, usb_snddefctrl(dev),
532 				USB_REQ_SET_ADDRESS, 0,
533 				(dev->devnum), 0,
534 				NULL, 0, USB_CNTL_TIMEOUT);
535 	return res;
536 }
537 
538 /********************************************************************
539  * set interface number to interface
540  */
541 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
542 {
543 	struct usb_interface *if_face = NULL;
544 	int ret, i;
545 
546 	for (i = 0; i < dev->config.desc.bNumInterfaces; i++) {
547 		if (dev->config.if_desc[i].desc.bInterfaceNumber == interface) {
548 			if_face = &dev->config.if_desc[i];
549 			break;
550 		}
551 	}
552 	if (!if_face) {
553 		printf("selecting invalid interface %d", interface);
554 		return -1;
555 	}
556 	/*
557 	 * We should return now for devices with only one alternate setting.
558 	 * According to 9.4.10 of the Universal Serial Bus Specification
559 	 * Revision 2.0 such devices can return with a STALL. This results in
560 	 * some USB sticks timeouting during initialization and then being
561 	 * unusable in U-Boot.
562 	 */
563 	if (if_face->num_altsetting == 1)
564 		return 0;
565 
566 	ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
567 				USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
568 				alternate, interface, NULL, 0,
569 				USB_CNTL_TIMEOUT * 5);
570 	if (ret < 0)
571 		return ret;
572 
573 	return 0;
574 }
575 
576 /********************************************************************
577  * set configuration number to configuration
578  */
579 static int usb_set_configuration(struct usb_device *dev, int configuration)
580 {
581 	int res;
582 	USB_PRINTF("set configuration %d\n", configuration);
583 	/* set setup command */
584 	res = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
585 				USB_REQ_SET_CONFIGURATION, 0,
586 				configuration, 0,
587 				NULL, 0, USB_CNTL_TIMEOUT);
588 	if (res == 0) {
589 		dev->toggle[0] = 0;
590 		dev->toggle[1] = 0;
591 		return 0;
592 	} else
593 		return -1;
594 }
595 
596 /********************************************************************
597  * set protocol to protocol
598  */
599 int usb_set_protocol(struct usb_device *dev, int ifnum, int protocol)
600 {
601 	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
602 		USB_REQ_SET_PROTOCOL, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
603 		protocol, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
604 }
605 
606 /********************************************************************
607  * set idle
608  */
609 int usb_set_idle(struct usb_device *dev, int ifnum, int duration, int report_id)
610 {
611 	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
612 		USB_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE,
613 		(duration << 8) | report_id, ifnum, NULL, 0, USB_CNTL_TIMEOUT);
614 }
615 
616 /********************************************************************
617  * get report
618  */
619 int usb_get_report(struct usb_device *dev, int ifnum, unsigned char type,
620 		   unsigned char id, void *buf, int size)
621 {
622 	return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
623 			USB_REQ_GET_REPORT,
624 			USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
625 			(type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
626 }
627 
628 /********************************************************************
629  * get class descriptor
630  */
631 int usb_get_class_descriptor(struct usb_device *dev, int ifnum,
632 		unsigned char type, unsigned char id, void *buf, int size)
633 {
634 	return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
635 		USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
636 		(type << 8) + id, ifnum, buf, size, USB_CNTL_TIMEOUT);
637 }
638 
639 /********************************************************************
640  * get string index in buffer
641  */
642 static int usb_get_string(struct usb_device *dev, unsigned short langid,
643 		   unsigned char index, void *buf, int size)
644 {
645 	int i;
646 	int result;
647 
648 	for (i = 0; i < 3; ++i) {
649 		/* some devices are flaky */
650 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
651 			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
652 			(USB_DT_STRING << 8) + index, langid, buf, size,
653 			USB_CNTL_TIMEOUT);
654 
655 		if (result > 0)
656 			break;
657 	}
658 
659 	return result;
660 }
661 
662 
663 static void usb_try_string_workarounds(unsigned char *buf, int *length)
664 {
665 	int newlength, oldlength = *length;
666 
667 	for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
668 		if (!isprint(buf[newlength]) || buf[newlength + 1])
669 			break;
670 
671 	if (newlength > 2) {
672 		buf[0] = newlength;
673 		*length = newlength;
674 	}
675 }
676 
677 
678 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
679 		unsigned int index, unsigned char *buf)
680 {
681 	int rc;
682 
683 	/* Try to read the string descriptor by asking for the maximum
684 	 * possible number of bytes */
685 	rc = usb_get_string(dev, langid, index, buf, 255);
686 
687 	/* If that failed try to read the descriptor length, then
688 	 * ask for just that many bytes */
689 	if (rc < 2) {
690 		rc = usb_get_string(dev, langid, index, buf, 2);
691 		if (rc == 2)
692 			rc = usb_get_string(dev, langid, index, buf, buf[0]);
693 	}
694 
695 	if (rc >= 2) {
696 		if (!buf[0] && !buf[1])
697 			usb_try_string_workarounds(buf, &rc);
698 
699 		/* There might be extra junk at the end of the descriptor */
700 		if (buf[0] < rc)
701 			rc = buf[0];
702 
703 		rc = rc - (rc & 1); /* force a multiple of two */
704 	}
705 
706 	if (rc < 2)
707 		rc = -1;
708 
709 	return rc;
710 }
711 
712 
713 /********************************************************************
714  * usb_string:
715  * Get string index and translate it to ascii.
716  * returns string length (> 0) or error (< 0)
717  */
718 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
719 {
720 	ALLOC_CACHE_ALIGN_BUFFER(unsigned char, mybuf, USB_BUFSIZ);
721 	unsigned char *tbuf;
722 	int err;
723 	unsigned int u, idx;
724 
725 	if (size <= 0 || !buf || !index)
726 		return -1;
727 	buf[0] = 0;
728 	tbuf = &mybuf[0];
729 
730 	/* get langid for strings if it's not yet known */
731 	if (!dev->have_langid) {
732 		err = usb_string_sub(dev, 0, 0, tbuf);
733 		if (err < 0) {
734 			USB_PRINTF("error getting string descriptor 0 " \
735 				   "(error=%lx)\n", dev->status);
736 			return -1;
737 		} else if (tbuf[0] < 4) {
738 			USB_PRINTF("string descriptor 0 too short\n");
739 			return -1;
740 		} else {
741 			dev->have_langid = -1;
742 			dev->string_langid = tbuf[2] | (tbuf[3] << 8);
743 				/* always use the first langid listed */
744 			USB_PRINTF("USB device number %d default " \
745 				   "language ID 0x%x\n",
746 				   dev->devnum, dev->string_langid);
747 		}
748 	}
749 
750 	err = usb_string_sub(dev, dev->string_langid, index, tbuf);
751 	if (err < 0)
752 		return err;
753 
754 	size--;		/* leave room for trailing NULL char in output buffer */
755 	for (idx = 0, u = 2; u < err; u += 2) {
756 		if (idx >= size)
757 			break;
758 		if (tbuf[u+1])			/* high byte */
759 			buf[idx++] = '?';  /* non-ASCII character */
760 		else
761 			buf[idx++] = tbuf[u];
762 	}
763 	buf[idx] = 0;
764 	err = idx;
765 	return err;
766 }
767 
768 
769 /********************************************************************
770  * USB device handling:
771  * the USB device are static allocated [USB_MAX_DEVICE].
772  */
773 
774 
775 /* returns a pointer to the device with the index [index].
776  * if the device is not assigned (dev->devnum==-1) returns NULL
777  */
778 struct usb_device *usb_get_dev_index(int index)
779 {
780 	if (usb_dev[index].devnum == -1)
781 		return NULL;
782 	else
783 		return &usb_dev[index];
784 }
785 
786 /* returns a pointer of a new device structure or NULL, if
787  * no device struct is available
788  */
789 struct usb_device *usb_alloc_new_device(void *controller)
790 {
791 	int i;
792 	USB_PRINTF("New Device %d\n", dev_index);
793 	if (dev_index == USB_MAX_DEVICE) {
794 		printf("ERROR, too many USB Devices, max=%d\n", USB_MAX_DEVICE);
795 		return NULL;
796 	}
797 	/* default Address is 0, real addresses start with 1 */
798 	usb_dev[dev_index].devnum = dev_index + 1;
799 	usb_dev[dev_index].maxchild = 0;
800 	for (i = 0; i < USB_MAXCHILDREN; i++)
801 		usb_dev[dev_index].children[i] = NULL;
802 	usb_dev[dev_index].parent = NULL;
803 	usb_dev[dev_index].controller = controller;
804 	dev_index++;
805 	return &usb_dev[dev_index - 1];
806 }
807 
808 
809 /*
810  * By the time we get here, the device has gotten a new device ID
811  * and is in the default state. We need to identify the thing and
812  * get the ball rolling..
813  *
814  * Returns 0 for success, != 0 for error.
815  */
816 int usb_new_device(struct usb_device *dev)
817 {
818 	int addr, err;
819 	int tmp;
820 	ALLOC_CACHE_ALIGN_BUFFER(unsigned char, tmpbuf, USB_BUFSIZ);
821 
822 	/* We still haven't set the Address yet */
823 	addr = dev->devnum;
824 	dev->devnum = 0;
825 
826 #ifdef CONFIG_LEGACY_USB_INIT_SEQ
827 	/* this is the old and known way of initializing devices, it is
828 	 * different than what Windows and Linux are doing. Windows and Linux
829 	 * both retrieve 64 bytes while reading the device descriptor
830 	 * Several USB stick devices report ERR: CTL_TIMEOUT, caused by an
831 	 * invalid header while reading 8 bytes as device descriptor. */
832 	dev->descriptor.bMaxPacketSize0 = 8;	    /* Start off at 8 bytes  */
833 	dev->maxpacketsize = PACKET_SIZE_8;
834 	dev->epmaxpacketin[0] = 8;
835 	dev->epmaxpacketout[0] = 8;
836 
837 	err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, tmpbuf, 8);
838 	if (err < 8) {
839 		printf("\n      USB device not responding, " \
840 		       "giving up (status=%lX)\n", dev->status);
841 		return 1;
842 	}
843 	memcpy(&dev->descriptor, tmpbuf, 8);
844 #else
845 	/* This is a Windows scheme of initialization sequence, with double
846 	 * reset of the device (Linux uses the same sequence)
847 	 * Some equipment is said to work only with such init sequence; this
848 	 * patch is based on the work by Alan Stern:
849 	 * http://sourceforge.net/mailarchive/forum.php?
850 	 * thread_id=5729457&forum_id=5398
851 	 */
852 	struct usb_device_descriptor *desc;
853 	int port = -1;
854 	struct usb_device *parent = dev->parent;
855 	unsigned short portstatus;
856 
857 	/* send 64-byte GET-DEVICE-DESCRIPTOR request.  Since the descriptor is
858 	 * only 18 bytes long, this will terminate with a short packet.  But if
859 	 * the maxpacket size is 8 or 16 the device may be waiting to transmit
860 	 * some more, or keeps on retransmitting the 8 byte header. */
861 
862 	desc = (struct usb_device_descriptor *)tmpbuf;
863 	dev->descriptor.bMaxPacketSize0 = 64;	    /* Start off at 64 bytes  */
864 	/* Default to 64 byte max packet size */
865 	dev->maxpacketsize = PACKET_SIZE_64;
866 	dev->epmaxpacketin[0] = 64;
867 	dev->epmaxpacketout[0] = 64;
868 
869 	err = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, 64);
870 	if (err < 0) {
871 		USB_PRINTF("usb_new_device: usb_get_descriptor() failed\n");
872 		return 1;
873 	}
874 
875 	dev->descriptor.bMaxPacketSize0 = desc->bMaxPacketSize0;
876 
877 	/* find the port number we're at */
878 	if (parent) {
879 		int j;
880 
881 		for (j = 0; j < parent->maxchild; j++) {
882 			if (parent->children[j] == dev) {
883 				port = j;
884 				break;
885 			}
886 		}
887 		if (port < 0) {
888 			printf("usb_new_device:cannot locate device's port.\n");
889 			return 1;
890 		}
891 
892 		/* reset the port for the second time */
893 		err = hub_port_reset(dev->parent, port, &portstatus);
894 		if (err < 0) {
895 			printf("\n     Couldn't reset port %i\n", port);
896 			return 1;
897 		}
898 	}
899 #endif
900 
901 	dev->epmaxpacketin[0] = dev->descriptor.bMaxPacketSize0;
902 	dev->epmaxpacketout[0] = dev->descriptor.bMaxPacketSize0;
903 	switch (dev->descriptor.bMaxPacketSize0) {
904 	case 8:
905 		dev->maxpacketsize  = PACKET_SIZE_8;
906 		break;
907 	case 16:
908 		dev->maxpacketsize = PACKET_SIZE_16;
909 		break;
910 	case 32:
911 		dev->maxpacketsize = PACKET_SIZE_32;
912 		break;
913 	case 64:
914 		dev->maxpacketsize = PACKET_SIZE_64;
915 		break;
916 	}
917 	dev->devnum = addr;
918 
919 	err = usb_set_address(dev); /* set address */
920 
921 	if (err < 0) {
922 		printf("\n      USB device not accepting new address " \
923 			"(error=%lX)\n", dev->status);
924 		return 1;
925 	}
926 
927 	mdelay(10);	/* Let the SET_ADDRESS settle */
928 
929 	tmp = sizeof(dev->descriptor);
930 
931 	err = usb_get_descriptor(dev, USB_DT_DEVICE, 0,
932 				 tmpbuf, sizeof(dev->descriptor));
933 	if (err < tmp) {
934 		if (err < 0)
935 			printf("unable to get device descriptor (error=%d)\n",
936 			       err);
937 		else
938 			printf("USB device descriptor short read " \
939 				"(expected %i, got %i)\n", tmp, err);
940 		return 1;
941 	}
942 	memcpy(&dev->descriptor, tmpbuf, sizeof(dev->descriptor));
943 	/* correct le values */
944 	le16_to_cpus(&dev->descriptor.bcdUSB);
945 	le16_to_cpus(&dev->descriptor.idVendor);
946 	le16_to_cpus(&dev->descriptor.idProduct);
947 	le16_to_cpus(&dev->descriptor.bcdDevice);
948 	/* only support for one config for now */
949 	usb_get_configuration_no(dev, tmpbuf, 0);
950 	usb_parse_config(dev, tmpbuf, 0);
951 	usb_set_maxpacket(dev);
952 	/* we set the default configuration here */
953 	if (usb_set_configuration(dev, dev->config.desc.bConfigurationValue)) {
954 		printf("failed to set default configuration " \
955 			"len %d, status %lX\n", dev->act_len, dev->status);
956 		return -1;
957 	}
958 	USB_PRINTF("new device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
959 		   dev->descriptor.iManufacturer, dev->descriptor.iProduct,
960 		   dev->descriptor.iSerialNumber);
961 	memset(dev->mf, 0, sizeof(dev->mf));
962 	memset(dev->prod, 0, sizeof(dev->prod));
963 	memset(dev->serial, 0, sizeof(dev->serial));
964 	if (dev->descriptor.iManufacturer)
965 		usb_string(dev, dev->descriptor.iManufacturer,
966 			   dev->mf, sizeof(dev->mf));
967 	if (dev->descriptor.iProduct)
968 		usb_string(dev, dev->descriptor.iProduct,
969 			   dev->prod, sizeof(dev->prod));
970 	if (dev->descriptor.iSerialNumber)
971 		usb_string(dev, dev->descriptor.iSerialNumber,
972 			   dev->serial, sizeof(dev->serial));
973 	USB_PRINTF("Manufacturer %s\n", dev->mf);
974 	USB_PRINTF("Product      %s\n", dev->prod);
975 	USB_PRINTF("SerialNumber %s\n", dev->serial);
976 	/* now prode if the device is a hub */
977 	usb_hub_probe(dev, 0);
978 	return 0;
979 }
980 
981 /* EOF */
982