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