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