xref: /openbmc/u-boot/drivers/serial/usbtty.c (revision e4430779)
1 /*
2  * (C) Copyright 2003
3  * Gerry Hamel, geh@ti.com, Texas Instruments
4  *
5  * (C) Copyright 2006
6  * Bryan O'Donoghue, bodonoghue@codehermit.ie
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307	 USA
21  *
22  */
23 
24 #include <common.h>
25 #include <config.h>
26 #include <circbuf.h>
27 #include <devices.h>
28 #include "usbtty.h"
29 #include "usb_cdc_acm.h"
30 #include "usbdescriptors.h"
31 
32 #ifdef DEBUG
33 #define TTYDBG(fmt,args...)\
34 	serial_printf("[%s] %s %d: "fmt, __FILE__,__FUNCTION__,__LINE__,##args)
35 #else
36 #define TTYDBG(fmt,args...) do{}while(0)
37 #endif
38 
39 #if 1
40 #define TTYERR(fmt,args...)\
41 	serial_printf("ERROR![%s] %s %d: "fmt, __FILE__,__FUNCTION__,\
42 	__LINE__,##args)
43 #else
44 #define TTYERR(fmt,args...) do{}while(0)
45 #endif
46 
47 /*
48  * Defines
49  */
50 #define NUM_CONFIGS    1
51 #define MAX_INTERFACES 2
52 #define NUM_ENDPOINTS  3
53 #define ACM_TX_ENDPOINT 3
54 #define ACM_RX_ENDPOINT 2
55 #define GSERIAL_TX_ENDPOINT 2
56 #define GSERIAL_RX_ENDPOINT 1
57 #define NUM_ACM_INTERFACES 2
58 #define NUM_GSERIAL_INTERFACES 1
59 #define CONFIG_USBD_DATA_INTERFACE_STR "Bulk Data Interface"
60 #define CONFIG_USBD_CTRL_INTERFACE_STR "Control Interface"
61 
62 /*
63  * Buffers to hold input and output data
64  */
65 #define USBTTY_BUFFER_SIZE 256
66 static circbuf_t usbtty_input;
67 static circbuf_t usbtty_output;
68 
69 
70 /*
71  * Instance variables
72  */
73 static device_t usbttydev;
74 static struct usb_device_instance device_instance[1];
75 static struct usb_bus_instance bus_instance[1];
76 static struct usb_configuration_instance config_instance[NUM_CONFIGS];
77 static struct usb_interface_instance interface_instance[MAX_INTERFACES];
78 static struct usb_alternate_instance alternate_instance[MAX_INTERFACES];
79 /* one extra for control endpoint */
80 static struct usb_endpoint_instance endpoint_instance[NUM_ENDPOINTS+1];
81 
82 /*
83  * Global flag
84  */
85 int usbtty_configured_flag = 0;
86 
87 /*
88  * Serial number
89  */
90 static char serial_number[16];
91 
92 
93 /*
94  * Descriptors, Strings, Local variables.
95  */
96 
97 /* defined and used by usbdcore_ep0.c */
98 extern struct usb_string_descriptor **usb_strings;
99 
100 /* Indicies, References */
101 static unsigned short rx_endpoint = 0;
102 static unsigned short tx_endpoint = 0;
103 static unsigned short interface_count = 0;
104 static struct usb_string_descriptor *usbtty_string_table[STR_COUNT];
105 
106 /* USB Descriptor Strings */
107 static u8 wstrLang[4] = {4,USB_DT_STRING,0x9,0x4};
108 static u8 wstrManufacturer[2 + 2*(sizeof(CONFIG_USBD_MANUFACTURER)-1)];
109 static u8 wstrProduct[2 + 2*(sizeof(CONFIG_USBD_PRODUCT_NAME)-1)];
110 static u8 wstrSerial[2 + 2*(sizeof(serial_number) - 1)];
111 static u8 wstrConfiguration[2 + 2*(sizeof(CONFIG_USBD_CONFIGURATION_STR)-1)];
112 static u8 wstrDataInterface[2 + 2*(sizeof(CONFIG_USBD_DATA_INTERFACE_STR)-1)];
113 static u8 wstrCtrlInterface[2 + 2*(sizeof(CONFIG_USBD_DATA_INTERFACE_STR)-1)];
114 
115 /* Standard USB Data Structures */
116 static struct usb_interface_descriptor interface_descriptors[MAX_INTERFACES];
117 static struct usb_endpoint_descriptor *ep_descriptor_ptrs[NUM_ENDPOINTS];
118 static struct usb_configuration_descriptor	*configuration_descriptor = 0;
119 static struct usb_device_descriptor device_descriptor = {
120 	.bLength = sizeof(struct usb_device_descriptor),
121 	.bDescriptorType =	USB_DT_DEVICE,
122 	.bcdUSB =		cpu_to_le16(USB_BCD_VERSION),
123 	.bDeviceSubClass =	0x00,
124 	.bDeviceProtocol =	0x00,
125 	.bMaxPacketSize0 =	EP0_MAX_PACKET_SIZE,
126 	.idVendor =		cpu_to_le16(CONFIG_USBD_VENDORID),
127 	.bcdDevice =		cpu_to_le16(USBTTY_BCD_DEVICE),
128 	.iManufacturer =	STR_MANUFACTURER,
129 	.iProduct =		STR_PRODUCT,
130 	.iSerialNumber =	STR_SERIAL,
131 	.bNumConfigurations =	NUM_CONFIGS
132 };
133 
134 
135 /*
136  * Static CDC ACM specific descriptors
137  */
138 
139 struct acm_config_desc {
140 	struct usb_configuration_descriptor configuration_desc;
141 
142 	/* Master Interface */
143 	struct usb_interface_descriptor interface_desc;
144 
145 	struct usb_class_header_function_descriptor usb_class_header;
146 	struct usb_class_call_management_descriptor usb_class_call_mgt;
147 	struct usb_class_abstract_control_descriptor usb_class_acm;
148 	struct usb_class_union_function_descriptor usb_class_union;
149 	struct usb_endpoint_descriptor notification_endpoint;
150 
151 	/* Slave Interface */
152 	struct usb_interface_descriptor data_class_interface;
153 	struct usb_endpoint_descriptor
154 		data_endpoints[NUM_ENDPOINTS-1] __attribute__((packed));
155 } __attribute__((packed));
156 
157 static struct acm_config_desc acm_configuration_descriptors[NUM_CONFIGS] = {
158 	{
159 		.configuration_desc ={
160 			.bLength =
161 				sizeof(struct usb_configuration_descriptor),
162 			.bDescriptorType = USB_DT_CONFIG,
163 			.wTotalLength =
164 				cpu_to_le16(sizeof(struct acm_config_desc)),
165 			.bNumInterfaces = NUM_ACM_INTERFACES,
166 			.bConfigurationValue = 1,
167 			.iConfiguration = STR_CONFIG,
168 			.bmAttributes =
169 				BMATTRIBUTE_SELF_POWERED|BMATTRIBUTE_RESERVED,
170 			.bMaxPower = USBTTY_MAXPOWER
171 		},
172 		/* Interface 1 */
173 		.interface_desc = {
174 			.bLength  = sizeof(struct usb_interface_descriptor),
175 			.bDescriptorType = USB_DT_INTERFACE,
176 			.bInterfaceNumber = 0,
177 			.bAlternateSetting = 0,
178 			.bNumEndpoints = 0x01,
179 			.bInterfaceClass =
180 				COMMUNICATIONS_INTERFACE_CLASS_CONTROL,
181 			.bInterfaceSubClass = COMMUNICATIONS_ACM_SUBCLASS,
182 			.bInterfaceProtocol = COMMUNICATIONS_V25TER_PROTOCOL,
183 			.iInterface = STR_CTRL_INTERFACE,
184 		},
185 		.usb_class_header = {
186 			.bFunctionLength	=
187 				sizeof(struct usb_class_header_function_descriptor),
188 			.bDescriptorType	= CS_INTERFACE,
189 			.bDescriptorSubtype	= USB_ST_HEADER,
190 			.bcdCDC	= cpu_to_le16(110),
191 		},
192 		.usb_class_call_mgt = {
193 			.bFunctionLength	=
194 				sizeof(struct usb_class_call_management_descriptor),
195 			.bDescriptorType	= CS_INTERFACE,
196 			.bDescriptorSubtype	= USB_ST_CMF,
197 			.bmCapabilities		= 0x00,
198 			.bDataInterface		= 0x01,
199 		},
200 		.usb_class_acm = {
201 			.bFunctionLength	=
202 				sizeof(struct usb_class_abstract_control_descriptor),
203 			.bDescriptorType	= CS_INTERFACE,
204 			.bDescriptorSubtype	= USB_ST_ACMF,
205 			.bmCapabilities		= 0x00,
206 		},
207 		.usb_class_union = {
208 			.bFunctionLength	=
209 				sizeof(struct usb_class_union_function_descriptor),
210 			.bDescriptorType	= CS_INTERFACE,
211 			.bDescriptorSubtype	= USB_ST_UF,
212 			.bMasterInterface	= 0x00,
213 			.bSlaveInterface0	= 0x01,
214 		},
215 		.notification_endpoint = {
216 			.bLength =
217 				sizeof(struct usb_endpoint_descriptor),
218 			.bDescriptorType	= USB_DT_ENDPOINT,
219 			.bEndpointAddress	= 0x01 | USB_DIR_IN,
220 			.bmAttributes		= USB_ENDPOINT_XFER_INT,
221 			.wMaxPacketSize
222 				= cpu_to_le16(CONFIG_USBD_SERIAL_INT_PKTSIZE),
223 			.bInterval		= 0xFF,
224 		},
225 
226 		/* Interface 2 */
227 		.data_class_interface = {
228 			.bLength		=
229 				sizeof(struct usb_interface_descriptor),
230 			.bDescriptorType	= USB_DT_INTERFACE,
231 			.bInterfaceNumber	= 0x01,
232 			.bAlternateSetting	= 0x00,
233 			.bNumEndpoints		= 0x02,
234 			.bInterfaceClass	=
235 				COMMUNICATIONS_INTERFACE_CLASS_DATA,
236 			.bInterfaceSubClass	= DATA_INTERFACE_SUBCLASS_NONE,
237 			.bInterfaceProtocol	= DATA_INTERFACE_PROTOCOL_NONE,
238 			.iInterface		= STR_DATA_INTERFACE,
239 		},
240 		.data_endpoints = {
241 			{
242 				.bLength		=
243 					sizeof(struct usb_endpoint_descriptor),
244 				.bDescriptorType	= USB_DT_ENDPOINT,
245 				.bEndpointAddress	= 0x02 | USB_DIR_OUT,
246 				.bmAttributes		=
247 					USB_ENDPOINT_XFER_BULK,
248 				.wMaxPacketSize		=
249 					cpu_to_le16(CONFIG_USBD_SERIAL_BULK_PKTSIZE),
250 				.bInterval		= 0xFF,
251 			},
252 			{
253 				.bLength		=
254 					sizeof(struct usb_endpoint_descriptor),
255 				.bDescriptorType	= USB_DT_ENDPOINT,
256 				.bEndpointAddress	= 0x03 | USB_DIR_IN,
257 				.bmAttributes		=
258 					USB_ENDPOINT_XFER_BULK,
259 				.wMaxPacketSize		=
260 					cpu_to_le16(CONFIG_USBD_SERIAL_BULK_PKTSIZE),
261 				.bInterval		= 0xFF,
262 			},
263 		},
264 	},
265 };
266 
267 static struct rs232_emu rs232_desc={
268 		.dter		=	115200,
269 		.stop_bits	=	0x00,
270 		.parity		=	0x00,
271 		.data_bits	=	0x08
272 };
273 
274 
275 /*
276  * Static Generic Serial specific data
277  */
278 
279 
280 struct gserial_config_desc {
281 
282 	struct usb_configuration_descriptor configuration_desc;
283 	struct usb_interface_descriptor
284 		interface_desc[NUM_GSERIAL_INTERFACES] __attribute__((packed));
285 	struct usb_endpoint_descriptor
286 		data_endpoints[NUM_ENDPOINTS] __attribute__((packed));
287 
288 } __attribute__((packed));
289 
290 static struct gserial_config_desc
291 gserial_configuration_descriptors[NUM_CONFIGS] ={
292 	{
293 		.configuration_desc ={
294 			.bLength = sizeof(struct usb_configuration_descriptor),
295 			.bDescriptorType = USB_DT_CONFIG,
296 			.wTotalLength =
297 				cpu_to_le16(sizeof(struct gserial_config_desc)),
298 			.bNumInterfaces = NUM_GSERIAL_INTERFACES,
299 			.bConfigurationValue = 1,
300 			.iConfiguration = STR_CONFIG,
301 			.bmAttributes =
302 				BMATTRIBUTE_SELF_POWERED|BMATTRIBUTE_RESERVED,
303 			.bMaxPower = USBTTY_MAXPOWER
304 		},
305 		.interface_desc = {
306 			{
307 				.bLength  =
308 					sizeof(struct usb_interface_descriptor),
309 				.bDescriptorType = USB_DT_INTERFACE,
310 				.bInterfaceNumber = 0,
311 				.bAlternateSetting = 0,
312 				.bNumEndpoints = NUM_ENDPOINTS,
313 				.bInterfaceClass =
314 					COMMUNICATIONS_INTERFACE_CLASS_VENDOR,
315 				.bInterfaceSubClass =
316 					COMMUNICATIONS_NO_SUBCLASS,
317 				.bInterfaceProtocol =
318 					COMMUNICATIONS_NO_PROTOCOL,
319 				.iInterface = STR_DATA_INTERFACE
320 			},
321 		},
322 		.data_endpoints  = {
323 			{
324 				.bLength =
325 					sizeof(struct usb_endpoint_descriptor),
326 				.bDescriptorType =	USB_DT_ENDPOINT,
327 				.bEndpointAddress =	0x01 | USB_DIR_OUT,
328 				.bmAttributes =		USB_ENDPOINT_XFER_BULK,
329 				.wMaxPacketSize =
330 					cpu_to_le16(CONFIG_USBD_SERIAL_OUT_PKTSIZE),
331 				.bInterval=		0xFF,
332 			},
333 			{
334 				.bLength =
335 					sizeof(struct usb_endpoint_descriptor),
336 				.bDescriptorType =	USB_DT_ENDPOINT,
337 				.bEndpointAddress =	0x02 | USB_DIR_IN,
338 				.bmAttributes =		USB_ENDPOINT_XFER_BULK,
339 				.wMaxPacketSize =
340 					cpu_to_le16(CONFIG_USBD_SERIAL_IN_PKTSIZE),
341 				.bInterval =		0xFF,
342 			},
343 			{
344 				.bLength =
345 					sizeof(struct usb_endpoint_descriptor),
346 				.bDescriptorType =	USB_DT_ENDPOINT,
347 				.bEndpointAddress =	0x03 | USB_DIR_IN,
348 				.bmAttributes =		USB_ENDPOINT_XFER_INT,
349 				.wMaxPacketSize =
350 					cpu_to_le16(CONFIG_USBD_SERIAL_INT_PKTSIZE),
351 				.bInterval =		0xFF,
352 			},
353 		},
354 	},
355 };
356 
357 /*
358  * Static Function Prototypes
359  */
360 
361 static void usbtty_init_strings (void);
362 static void usbtty_init_instances (void);
363 static void usbtty_init_endpoints (void);
364 static void usbtty_init_terminal_type(short type);
365 static void usbtty_event_handler (struct usb_device_instance *device,
366 				usb_device_event_t event, int data);
367 static int usbtty_cdc_setup(struct usb_device_request *request,
368 				struct urb *urb);
369 static int usbtty_configured (void);
370 static int write_buffer (circbuf_t * buf);
371 static int fill_buffer (circbuf_t * buf);
372 
373 void usbtty_poll (void);
374 
375 /* utility function for converting char* to wide string used by USB */
376 static void str2wide (char *str, u16 * wide)
377 {
378 	int i;
379 	for (i = 0; i < strlen (str) && str[i]; i++){
380 		#if defined(__LITTLE_ENDIAN)
381 			wide[i] = (u16) str[i];
382 		#elif defined(__BIG_ENDIAN)
383 			wide[i] = ((u16)(str[i])<<8);
384 		#else
385 			#error "__LITTLE_ENDIAN or __BIG_ENDIAN undefined"
386 		#endif
387 	}
388 }
389 
390 /*
391  * Test whether a character is in the RX buffer
392  */
393 
394 int usbtty_tstc (void)
395 {
396 	struct usb_endpoint_instance *endpoint =
397 		&endpoint_instance[rx_endpoint];
398 
399 	/* If no input data exists, allow more RX to be accepted */
400 	if(usbtty_input.size <= 0){
401 		udc_unset_nak(endpoint->endpoint_address&0x03);
402 	}
403 
404 	usbtty_poll ();
405 	return (usbtty_input.size > 0);
406 }
407 
408 /*
409  * Read a single byte from the usb client port. Returns 1 on success, 0
410  * otherwise. When the function is succesfull, the character read is
411  * written into its argument c.
412  */
413 
414 int usbtty_getc (void)
415 {
416 	char c;
417 	struct usb_endpoint_instance *endpoint =
418 		&endpoint_instance[rx_endpoint];
419 
420 	while (usbtty_input.size <= 0) {
421 		udc_unset_nak(endpoint->endpoint_address&0x03);
422 		usbtty_poll ();
423 	}
424 
425 	buf_pop (&usbtty_input, &c, 1);
426 	udc_set_nak(endpoint->endpoint_address&0x03);
427 
428 	return c;
429 }
430 
431 /*
432  * Output a single byte to the usb client port.
433  */
434 void usbtty_putc (const char c)
435 {
436 	buf_push (&usbtty_output, &c, 1);
437 	/* If \n, also do \r */
438 	if (c == '\n')
439 		buf_push (&usbtty_output, "\r", 1);
440 
441 	/* Poll at end to handle new data... */
442 	if ((usbtty_output.size + 2) >= usbtty_output.totalsize) {
443 		usbtty_poll ();
444 	}
445 }
446 
447 /* usbtty_puts() helper function for finding the next '\n' in a string */
448 static int next_nl_pos (const char *s)
449 {
450 	int i;
451 
452 	for (i = 0; s[i] != '\0'; i++) {
453 		if (s[i] == '\n')
454 			return i;
455 	}
456 	return i;
457 }
458 
459 /*
460  * Output a string to the usb client port - implementing flow control
461  */
462 
463 static void __usbtty_puts (const char *str, int len)
464 {
465 	int maxlen = usbtty_output.totalsize;
466 	int space, n;
467 
468 	/* break str into chunks < buffer size, if needed */
469 	while (len > 0) {
470 		usbtty_poll ();
471 
472 		space = maxlen - usbtty_output.size;
473 		/* Empty buffer here, if needed, to ensure space... */
474 		if (space) {
475 			write_buffer (&usbtty_output);
476 
477 			n = MIN (space, MIN (len, maxlen));
478 			buf_push (&usbtty_output, str, n);
479 
480 			str += n;
481 			len -= n;
482 		}
483 	}
484 }
485 
486 void usbtty_puts (const char *str)
487 {
488 	int n;
489 	int len = strlen (str);
490 
491 	/* add '\r' for each '\n' */
492 	while (len > 0) {
493 		n = next_nl_pos (str);
494 
495 		if (str[n] == '\n') {
496 			__usbtty_puts (str, n + 1);
497 			__usbtty_puts ("\r", 1);
498 			str += (n + 1);
499 			len -= (n + 1);
500 		} else {
501 			/* No \n found.	 All done. */
502 			__usbtty_puts (str, n);
503 			break;
504 		}
505 	}
506 
507 	/* Poll at end to handle new data... */
508 	usbtty_poll ();
509 }
510 
511 /*
512  * Initialize the usb client port.
513  *
514  */
515 int drv_usbtty_init (void)
516 {
517 	int rc;
518 	char * sn;
519 	char * tt;
520 	int snlen;
521 
522 	/* Ger seiral number */
523 	if (!(sn = getenv("serial#"))) {
524 		sn = "000000000000";
525 	}
526 	snlen = strlen(sn);
527 	if (snlen > sizeof(serial_number) - 1) {
528 		printf ("Warning: serial number %s is too long (%d > %lu)\n",
529 			sn, snlen, (ulong)(sizeof(serial_number) - 1));
530 		snlen = sizeof(serial_number) - 1;
531 	}
532 	memcpy (serial_number, sn, snlen);
533 	serial_number[snlen] = '\0';
534 
535 	/* Decide on which type of UDC device to be.
536 	 */
537 
538 	if(!(tt = getenv("usbtty"))) {
539 		tt = "generic";
540 	}
541 	usbtty_init_terminal_type(strcmp(tt,"cdc_acm"));
542 
543 	/* prepare buffers... */
544 	buf_init (&usbtty_input, USBTTY_BUFFER_SIZE);
545 	buf_init (&usbtty_output, USBTTY_BUFFER_SIZE);
546 
547 	/* Now, set up USB controller and infrastructure */
548 	udc_init ();		/* Basic USB initialization */
549 
550 	usbtty_init_strings ();
551 	usbtty_init_instances ();
552 
553 	udc_startup_events (device_instance);/* Enable dev, init udc pointers */
554 	udc_connect ();		/* Enable pullup for host detection */
555 
556 	usbtty_init_endpoints ();
557 
558 	/* Device initialization */
559 	memset (&usbttydev, 0, sizeof (usbttydev));
560 
561 	strcpy (usbttydev.name, "usbtty");
562 	usbttydev.ext = 0;	/* No extensions */
563 	usbttydev.flags = DEV_FLAGS_INPUT | DEV_FLAGS_OUTPUT;
564 	usbttydev.tstc = usbtty_tstc;	/* 'tstc' function */
565 	usbttydev.getc = usbtty_getc;	/* 'getc' function */
566 	usbttydev.putc = usbtty_putc;	/* 'putc' function */
567 	usbttydev.puts = usbtty_puts;	/* 'puts' function */
568 
569 	rc = device_register (&usbttydev);
570 
571 	return (rc == 0) ? 1 : rc;
572 }
573 
574 static void usbtty_init_strings (void)
575 {
576 	struct usb_string_descriptor *string;
577 
578 	usbtty_string_table[STR_LANG] =
579 		(struct usb_string_descriptor*)wstrLang;
580 
581 	string = (struct usb_string_descriptor *) wstrManufacturer;
582 	string->bLength = sizeof(wstrManufacturer);
583 	string->bDescriptorType = USB_DT_STRING;
584 	str2wide (CONFIG_USBD_MANUFACTURER, string->wData);
585 	usbtty_string_table[STR_MANUFACTURER]=string;
586 
587 
588 	string = (struct usb_string_descriptor *) wstrProduct;
589 	string->bLength = sizeof(wstrProduct);
590 	string->bDescriptorType = USB_DT_STRING;
591 	str2wide (CONFIG_USBD_PRODUCT_NAME, string->wData);
592 	usbtty_string_table[STR_PRODUCT]=string;
593 
594 
595 	string = (struct usb_string_descriptor *) wstrSerial;
596 	string->bLength = sizeof(serial_number);
597 	string->bDescriptorType = USB_DT_STRING;
598 	str2wide (serial_number, string->wData);
599 	usbtty_string_table[STR_SERIAL]=string;
600 
601 
602 	string = (struct usb_string_descriptor *) wstrConfiguration;
603 	string->bLength = sizeof(wstrConfiguration);
604 	string->bDescriptorType = USB_DT_STRING;
605 	str2wide (CONFIG_USBD_CONFIGURATION_STR, string->wData);
606 	usbtty_string_table[STR_CONFIG]=string;
607 
608 
609 	string = (struct usb_string_descriptor *) wstrDataInterface;
610 	string->bLength = sizeof(wstrDataInterface);
611 	string->bDescriptorType = USB_DT_STRING;
612 	str2wide (CONFIG_USBD_DATA_INTERFACE_STR, string->wData);
613 	usbtty_string_table[STR_DATA_INTERFACE]=string;
614 
615 	string = (struct usb_string_descriptor *) wstrCtrlInterface;
616 	string->bLength = sizeof(wstrCtrlInterface);
617 	string->bDescriptorType = USB_DT_STRING;
618 	str2wide (CONFIG_USBD_CTRL_INTERFACE_STR, string->wData);
619 	usbtty_string_table[STR_CTRL_INTERFACE]=string;
620 
621 	/* Now, initialize the string table for ep0 handling */
622 	usb_strings = usbtty_string_table;
623 }
624 
625 static void usbtty_init_instances (void)
626 {
627 	int i;
628 
629 	/* initialize device instance */
630 	memset (device_instance, 0, sizeof (struct usb_device_instance));
631 	device_instance->device_state = STATE_INIT;
632 	device_instance->device_descriptor = &device_descriptor;
633 	device_instance->event = usbtty_event_handler;
634 	device_instance->cdc_recv_setup = usbtty_cdc_setup;
635 	device_instance->bus = bus_instance;
636 	device_instance->configurations = NUM_CONFIGS;
637 	device_instance->configuration_instance_array = config_instance;
638 
639 	/* initialize bus instance */
640 	memset (bus_instance, 0, sizeof (struct usb_bus_instance));
641 	bus_instance->device = device_instance;
642 	bus_instance->endpoint_array = endpoint_instance;
643 	bus_instance->max_endpoints = 1;
644 	bus_instance->maxpacketsize = 64;
645 	bus_instance->serial_number_str = serial_number;
646 
647 	/* configuration instance */
648 	memset (config_instance, 0,
649 		sizeof (struct usb_configuration_instance));
650 	config_instance->interfaces = interface_count;
651 	config_instance->configuration_descriptor = configuration_descriptor;
652 	config_instance->interface_instance_array = interface_instance;
653 
654 	/* interface instance */
655 	memset (interface_instance, 0,
656 		sizeof (struct usb_interface_instance));
657 	interface_instance->alternates = 1;
658 	interface_instance->alternates_instance_array = alternate_instance;
659 
660 	/* alternates instance */
661 	memset (alternate_instance, 0,
662 		sizeof (struct usb_alternate_instance));
663 	alternate_instance->interface_descriptor = interface_descriptors;
664 	alternate_instance->endpoints = NUM_ENDPOINTS;
665 	alternate_instance->endpoints_descriptor_array = ep_descriptor_ptrs;
666 
667 	/* endpoint instances */
668 	memset (&endpoint_instance[0], 0,
669 		sizeof (struct usb_endpoint_instance));
670 	endpoint_instance[0].endpoint_address = 0;
671 	endpoint_instance[0].rcv_packetSize = EP0_MAX_PACKET_SIZE;
672 	endpoint_instance[0].rcv_attributes = USB_ENDPOINT_XFER_CONTROL;
673 	endpoint_instance[0].tx_packetSize = EP0_MAX_PACKET_SIZE;
674 	endpoint_instance[0].tx_attributes = USB_ENDPOINT_XFER_CONTROL;
675 	udc_setup_ep (device_instance, 0, &endpoint_instance[0]);
676 
677 	for (i = 1; i <= NUM_ENDPOINTS; i++) {
678 		memset (&endpoint_instance[i], 0,
679 			sizeof (struct usb_endpoint_instance));
680 
681 		endpoint_instance[i].endpoint_address =
682 			ep_descriptor_ptrs[i - 1]->bEndpointAddress;
683 
684 		endpoint_instance[i].rcv_attributes =
685 			ep_descriptor_ptrs[i - 1]->bmAttributes;
686 
687 		endpoint_instance[i].rcv_packetSize =
688 			le16_to_cpu(ep_descriptor_ptrs[i - 1]->wMaxPacketSize);
689 
690 		endpoint_instance[i].tx_attributes =
691 			ep_descriptor_ptrs[i - 1]->bmAttributes;
692 
693 		endpoint_instance[i].tx_packetSize =
694 			le16_to_cpu(ep_descriptor_ptrs[i - 1]->wMaxPacketSize);
695 
696 		endpoint_instance[i].tx_attributes =
697 			ep_descriptor_ptrs[i - 1]->bmAttributes;
698 
699 		urb_link_init (&endpoint_instance[i].rcv);
700 		urb_link_init (&endpoint_instance[i].rdy);
701 		urb_link_init (&endpoint_instance[i].tx);
702 		urb_link_init (&endpoint_instance[i].done);
703 
704 		if (endpoint_instance[i].endpoint_address & USB_DIR_IN)
705 			endpoint_instance[i].tx_urb =
706 				usbd_alloc_urb (device_instance,
707 						&endpoint_instance[i]);
708 		else
709 			endpoint_instance[i].rcv_urb =
710 				usbd_alloc_urb (device_instance,
711 						&endpoint_instance[i]);
712 	}
713 }
714 
715 static void usbtty_init_endpoints (void)
716 {
717 	int i;
718 
719 	bus_instance->max_endpoints = NUM_ENDPOINTS + 1;
720 	for (i = 1; i <= NUM_ENDPOINTS; i++) {
721 		udc_setup_ep (device_instance, i, &endpoint_instance[i]);
722 	}
723 }
724 
725 /* usbtty_init_terminal_type
726  *
727  * Do some late binding for our device type.
728  */
729 static void usbtty_init_terminal_type(short type)
730 {
731 	switch(type){
732 		/* CDC ACM */
733 		case 0:
734 			/* Assign endpoint descriptors */
735 			ep_descriptor_ptrs[0] =
736 				&acm_configuration_descriptors[0].notification_endpoint;
737 			ep_descriptor_ptrs[1] =
738 				&acm_configuration_descriptors[0].data_endpoints[0];
739 			ep_descriptor_ptrs[2] =
740 				&acm_configuration_descriptors[0].data_endpoints[1];
741 
742 			/* Enumerate Device Descriptor */
743 			device_descriptor.bDeviceClass =
744 				COMMUNICATIONS_DEVICE_CLASS;
745 			device_descriptor.idProduct =
746 				cpu_to_le16(CONFIG_USBD_PRODUCTID_CDCACM);
747 
748 			/* Assign endpoint indices */
749 			tx_endpoint = ACM_TX_ENDPOINT;
750 			rx_endpoint = ACM_RX_ENDPOINT;
751 
752 			/* Configuration Descriptor */
753 			configuration_descriptor =
754 				(struct usb_configuration_descriptor*)
755 				&acm_configuration_descriptors;
756 
757 			/* Interface count */
758 			interface_count = NUM_ACM_INTERFACES;
759 		break;
760 
761 		/* BULK IN/OUT & Default */
762 		case 1:
763 		default:
764 			/* Assign endpoint descriptors */
765 			ep_descriptor_ptrs[0] =
766 				&gserial_configuration_descriptors[0].data_endpoints[0];
767 			ep_descriptor_ptrs[1] =
768 				&gserial_configuration_descriptors[0].data_endpoints[1];
769 			ep_descriptor_ptrs[2] =
770 				&gserial_configuration_descriptors[0].data_endpoints[2];
771 
772 			/* Enumerate Device Descriptor */
773 			device_descriptor.bDeviceClass = 0xFF;
774 			device_descriptor.idProduct =
775 				cpu_to_le16(CONFIG_USBD_PRODUCTID_GSERIAL);
776 
777 			/* Assign endpoint indices */
778 			tx_endpoint = GSERIAL_TX_ENDPOINT;
779 			rx_endpoint = GSERIAL_RX_ENDPOINT;
780 
781 			/* Configuration Descriptor */
782 			configuration_descriptor =
783 				(struct usb_configuration_descriptor*)
784 				&gserial_configuration_descriptors;
785 
786 			/* Interface count */
787 			interface_count = NUM_GSERIAL_INTERFACES;
788 		break;
789 	}
790 }
791 
792 /******************************************************************************/
793 
794 static struct urb *next_urb (struct usb_device_instance *device,
795 			     struct usb_endpoint_instance *endpoint)
796 {
797 	struct urb *current_urb = NULL;
798 	int space;
799 
800 	/* If there's a queue, then we should add to the last urb */
801 	if (!endpoint->tx_queue) {
802 		current_urb = endpoint->tx_urb;
803 	} else {
804 		/* Last urb from tx chain */
805 		current_urb =
806 			p2surround (struct urb, link, endpoint->tx.prev);
807 	}
808 
809 	/* Make sure this one has enough room */
810 	space = current_urb->buffer_length - current_urb->actual_length;
811 	if (space > 0) {
812 		return current_urb;
813 	} else {		/* No space here */
814 		/* First look at done list */
815 		current_urb = first_urb_detached (&endpoint->done);
816 		if (!current_urb) {
817 			current_urb = usbd_alloc_urb (device, endpoint);
818 		}
819 
820 		urb_append (&endpoint->tx, current_urb);
821 		endpoint->tx_queue++;
822 	}
823 	return current_urb;
824 }
825 
826 static int write_buffer (circbuf_t * buf)
827 {
828 	if (!usbtty_configured ()) {
829 		return 0;
830 	}
831 
832 	struct usb_endpoint_instance *endpoint =
833 			&endpoint_instance[tx_endpoint];
834 	struct urb *current_urb = NULL;
835 
836 	current_urb = next_urb (device_instance, endpoint);
837 	/* TX data still exists - send it now
838 	 */
839 	if(endpoint->sent < current_urb->actual_length){
840 		if(udc_endpoint_write (endpoint)){
841 			/* Write pre-empted by RX */
842 			return -1;
843 		}
844 	}
845 
846 	if (buf->size) {
847 		char *dest;
848 
849 		int space_avail;
850 		int popnum, popped;
851 		int total = 0;
852 
853 		/* Break buffer into urb sized pieces,
854 		 * and link each to the endpoint
855 		 */
856 		while (buf->size > 0) {
857 
858 			if (!current_urb) {
859 				TTYERR ("current_urb is NULL, buf->size %d\n",
860 					buf->size);
861 				return total;
862 			}
863 
864 			dest = (char*)current_urb->buffer +
865 				current_urb->actual_length;
866 
867 			space_avail =
868 				current_urb->buffer_length -
869 				current_urb->actual_length;
870 			popnum = MIN (space_avail, buf->size);
871 			if (popnum == 0)
872 				break;
873 
874 			popped = buf_pop (buf, dest, popnum);
875 			if (popped == 0)
876 				break;
877 			current_urb->actual_length += popped;
878 			total += popped;
879 
880 			/* If endpoint->last == 0, then transfers have
881 			 * not started on this endpoint
882 			 */
883 			if (endpoint->last == 0) {
884 				if(udc_endpoint_write (endpoint)){
885 					/* Write pre-empted by RX */
886 					return -1;
887 				}
888 			}
889 
890 		}/* end while */
891 		return total;
892 	}
893 
894 	return 0;
895 }
896 
897 static int fill_buffer (circbuf_t * buf)
898 {
899 	struct usb_endpoint_instance *endpoint =
900 		&endpoint_instance[rx_endpoint];
901 
902 	if (endpoint->rcv_urb && endpoint->rcv_urb->actual_length) {
903 		unsigned int nb = 0;
904 		char *src = (char *) endpoint->rcv_urb->buffer;
905 		unsigned int rx_avail = buf->totalsize - buf->size;
906 
907 		if(rx_avail >= endpoint->rcv_urb->actual_length){
908 
909 			nb = endpoint->rcv_urb->actual_length;
910 			buf_push (buf, src, nb);
911 			endpoint->rcv_urb->actual_length = 0;
912 
913 		}
914 		return nb;
915 	}
916 	return 0;
917 }
918 
919 static int usbtty_configured (void)
920 {
921 	return usbtty_configured_flag;
922 }
923 
924 /******************************************************************************/
925 
926 static void usbtty_event_handler (struct usb_device_instance *device,
927 				  usb_device_event_t event, int data)
928 {
929 	switch (event) {
930 	case DEVICE_RESET:
931 	case DEVICE_BUS_INACTIVE:
932 		usbtty_configured_flag = 0;
933 		break;
934 	case DEVICE_CONFIGURED:
935 		usbtty_configured_flag = 1;
936 		break;
937 
938 	case DEVICE_ADDRESS_ASSIGNED:
939 		usbtty_init_endpoints ();
940 
941 	default:
942 		break;
943 	}
944 }
945 
946 /******************************************************************************/
947 
948 int usbtty_cdc_setup(struct usb_device_request *request, struct urb *urb)
949 {
950 	switch (request->bRequest){
951 
952 		case ACM_SET_CONTROL_LINE_STATE:	/* Implies DTE ready */
953 			break;
954 		case ACM_SEND_ENCAPSULATED_COMMAND :	/* Required */
955 			break;
956 		case ACM_SET_LINE_ENCODING :		/* DTE stop/parity bits
957 							 * per character */
958 			break;
959 		case ACM_GET_ENCAPSULATED_RESPONSE :	/* request response */
960 			break;
961 		case ACM_GET_LINE_ENCODING :		/* request DTE rate,
962 							 * stop/parity bits */
963 			memcpy (urb->buffer , &rs232_desc, sizeof(rs232_desc));
964 			urb->actual_length = sizeof(rs232_desc);
965 
966 			break;
967 		default:
968 			return 1;
969 	}
970 	return 0;
971 }
972 
973 /******************************************************************************/
974 
975 /*
976  * Since interrupt handling has not yet been implemented, we use this function
977  * to handle polling.  This is called by the tstc,getc,putc,puts routines to
978  * update the USB state.
979  */
980 void usbtty_poll (void)
981 {
982 	/* New interrupts? */
983 	udc_irq();
984 
985 	/* Write any output data to host buffer
986 	 * (do this before checking interrupts to avoid missing one)
987 	 */
988 	if (usbtty_configured ()) {
989 		write_buffer (&usbtty_output);
990 	}
991 
992 	/* New interrupts? */
993 	udc_irq();
994 
995 	/* Check for new data from host..
996 	 * (do this after checking interrupts to get latest data)
997 	 */
998 	if (usbtty_configured ()) {
999 		fill_buffer (&usbtty_input);
1000 	}
1001 
1002 	/* New interrupts? */
1003 	udc_irq();
1004 
1005 }
1006