xref: /rk3399_rockchip-uboot/drivers/usb/gadget/f_thor.c (revision 57086a026ffbc480d4e89b2e58cdf63d57a1ec28)
1 /*
2  * f_thor.c -- USB TIZEN THOR Downloader gadget function
3  *
4  * Copyright (C) 2013 Samsung Electronics
5  * Lukasz Majewski <l.majewski@samsung.com>
6  *
7  * Based on code from:
8  * git://review.tizen.org/kernel/u-boot
9  *
10  * Developed by:
11  * Copyright (C) 2009 Samsung Electronics
12  * Minkyu Kang <mk7.kang@samsung.com>
13  * Sanghee Kim <sh0130.kim@samsung.com>
14  *
15  * SPDX-License-Identifier:	GPL-2.0+
16  */
17 
18 #include <errno.h>
19 #include <common.h>
20 #include <console.h>
21 #include <malloc.h>
22 #include <memalign.h>
23 #include <version.h>
24 #include <linux/usb/ch9.h>
25 #include <linux/usb/gadget.h>
26 #include <linux/usb/composite.h>
27 #include <linux/usb/cdc.h>
28 #include <g_dnl.h>
29 #include <dfu.h>
30 
31 #include "f_thor.h"
32 
33 static void thor_tx_data(unsigned char *data, int len);
34 static void thor_set_dma(void *addr, int len);
35 static int thor_rx_data(void);
36 
37 static struct f_thor *thor_func;
38 static inline struct f_thor *func_to_thor(struct usb_function *f)
39 {
40 	return container_of(f, struct f_thor, usb_function);
41 }
42 
43 DEFINE_CACHE_ALIGN_BUFFER(unsigned char, thor_tx_data_buf,
44 			  sizeof(struct rsp_box));
45 DEFINE_CACHE_ALIGN_BUFFER(unsigned char, thor_rx_data_buf,
46 			  sizeof(struct rqt_box));
47 
48 /* ********************************************************** */
49 /*         THOR protocol - transmission handling	      */
50 /* ********************************************************** */
51 DEFINE_CACHE_ALIGN_BUFFER(char, f_name, F_NAME_BUF_SIZE + 1);
52 static unsigned long long int thor_file_size;
53 static int alt_setting_num;
54 
55 static void send_rsp(const struct rsp_box *rsp)
56 {
57 	memcpy(thor_tx_data_buf, rsp, sizeof(struct rsp_box));
58 	thor_tx_data(thor_tx_data_buf, sizeof(struct rsp_box));
59 
60 	debug("-RSP: %d, %d\n", rsp->rsp, rsp->rsp_data);
61 }
62 
63 static void send_data_rsp(s32 ack, s32 count)
64 {
65 	ALLOC_CACHE_ALIGN_BUFFER(struct data_rsp_box, rsp,
66 				 sizeof(struct data_rsp_box));
67 
68 	rsp->ack = ack;
69 	rsp->count = count;
70 
71 	memcpy(thor_tx_data_buf, rsp, sizeof(struct data_rsp_box));
72 	thor_tx_data(thor_tx_data_buf, sizeof(struct data_rsp_box));
73 
74 	debug("-DATA RSP: %d, %d\n", ack, count);
75 }
76 
77 static int process_rqt_info(const struct rqt_box *rqt)
78 {
79 	ALLOC_CACHE_ALIGN_BUFFER(struct rsp_box, rsp, sizeof(struct rsp_box));
80 	memset(rsp, 0, sizeof(struct rsp_box));
81 
82 	rsp->rsp = rqt->rqt;
83 	rsp->rsp_data = rqt->rqt_data;
84 
85 	switch (rqt->rqt_data) {
86 	case RQT_INFO_VER_PROTOCOL:
87 		rsp->int_data[0] = VER_PROTOCOL_MAJOR;
88 		rsp->int_data[1] = VER_PROTOCOL_MINOR;
89 		break;
90 	case RQT_INIT_VER_HW:
91 		snprintf(rsp->str_data[0], sizeof(rsp->str_data[0]),
92 			 "%x", checkboard());
93 		break;
94 	case RQT_INIT_VER_BOOT:
95 		sprintf(rsp->str_data[0], "%s", U_BOOT_VERSION);
96 		break;
97 	case RQT_INIT_VER_KERNEL:
98 		sprintf(rsp->str_data[0], "%s", "k unknown");
99 		break;
100 	case RQT_INIT_VER_PLATFORM:
101 		sprintf(rsp->str_data[0], "%s", "p unknown");
102 		break;
103 	case RQT_INIT_VER_CSC:
104 		sprintf(rsp->str_data[0], "%s", "c unknown");
105 		break;
106 	default:
107 		return -EINVAL;
108 	}
109 
110 	send_rsp(rsp);
111 	return true;
112 }
113 
114 static int process_rqt_cmd(const struct rqt_box *rqt)
115 {
116 	ALLOC_CACHE_ALIGN_BUFFER(struct rsp_box, rsp, sizeof(struct rsp_box));
117 	memset(rsp, 0, sizeof(struct rsp_box));
118 
119 	rsp->rsp = rqt->rqt;
120 	rsp->rsp_data = rqt->rqt_data;
121 
122 	switch (rqt->rqt_data) {
123 	case RQT_CMD_REBOOT:
124 		debug("TARGET RESET\n");
125 		send_rsp(rsp);
126 		g_dnl_unregister();
127 		dfu_free_entities();
128 #ifdef CONFIG_THOR_RESET_OFF
129 		return RESET_DONE;
130 #endif
131 		run_command("reset", 0);
132 		break;
133 	case RQT_CMD_POWEROFF:
134 	case RQT_CMD_EFSCLEAR:
135 		send_rsp(rsp);
136 	default:
137 		printf("Command not supported -> cmd: %d\n", rqt->rqt_data);
138 		return -EINVAL;
139 	}
140 
141 	return true;
142 }
143 
144 static long long int download_head(unsigned long long total,
145 				   unsigned int packet_size,
146 				   long long int *left,
147 				   int *cnt)
148 {
149 	long long int rcv_cnt = 0, left_to_rcv, ret_rcv;
150 	struct dfu_entity *dfu_entity = dfu_get_entity(alt_setting_num);
151 	void *transfer_buffer = dfu_get_buf(dfu_entity);
152 	void *buf = transfer_buffer;
153 	int usb_pkt_cnt = 0, ret;
154 
155 	/*
156 	 * Files smaller than THOR_STORE_UNIT_SIZE (now 32 MiB) are stored on
157 	 * the medium.
158 	 * The packet response is sent on the purpose after successful data
159 	 * chunk write. There is a room for improvement when asynchronous write
160 	 * is performed.
161 	 */
162 	while (total - rcv_cnt >= packet_size) {
163 		thor_set_dma(buf, packet_size);
164 		buf += packet_size;
165 		ret_rcv = thor_rx_data();
166 		if (ret_rcv < 0)
167 			return ret_rcv;
168 		rcv_cnt += ret_rcv;
169 		debug("%d: RCV data count: %llu cnt: %d\n", usb_pkt_cnt,
170 		      rcv_cnt, *cnt);
171 
172 		if ((rcv_cnt % THOR_STORE_UNIT_SIZE) == 0) {
173 			ret = dfu_write(dfu_get_entity(alt_setting_num),
174 					transfer_buffer, THOR_STORE_UNIT_SIZE,
175 					(*cnt)++);
176 			if (ret) {
177 				pr_err("DFU write failed [%d] cnt: %d",
178 				      ret, *cnt);
179 				return ret;
180 			}
181 			buf = transfer_buffer;
182 		}
183 		send_data_rsp(0, ++usb_pkt_cnt);
184 	}
185 
186 	/* Calculate the amount of data to arrive from PC (in bytes) */
187 	left_to_rcv = total - rcv_cnt;
188 
189 	/*
190 	 * Calculate number of data already received. but not yet stored
191 	 * on the medium (they are smaller than THOR_STORE_UNIT_SIZE)
192 	 */
193 	*left = left_to_rcv + buf - transfer_buffer;
194 	debug("%s: left: %llu left_to_rcv: %llu buf: 0x%p\n", __func__,
195 	      *left, left_to_rcv, buf);
196 
197 	if (left_to_rcv) {
198 		thor_set_dma(buf, packet_size);
199 		ret_rcv = thor_rx_data();
200 		if (ret_rcv < 0)
201 			return ret_rcv;
202 		rcv_cnt += ret_rcv;
203 		send_data_rsp(0, ++usb_pkt_cnt);
204 	}
205 
206 	debug("%s: %llu total: %llu cnt: %d\n", __func__, rcv_cnt, total, *cnt);
207 
208 	return rcv_cnt;
209 }
210 
211 static int download_tail(long long int left, int cnt)
212 {
213 	struct dfu_entity *dfu_entity;
214 	void *transfer_buffer;
215 	int ret;
216 
217 	debug("%s: left: %llu cnt: %d\n", __func__, left, cnt);
218 
219 	dfu_entity = dfu_get_entity(alt_setting_num);
220 	if (!dfu_entity) {
221 		pr_err("Alt setting: %d entity not found!\n", alt_setting_num);
222 		return -ENOENT;
223 	}
224 
225 	transfer_buffer = dfu_get_buf(dfu_entity);
226 	if (!transfer_buffer) {
227 		pr_err("Transfer buffer not allocated!");
228 		return -ENXIO;
229 	}
230 
231 	if (left) {
232 		ret = dfu_write(dfu_entity, transfer_buffer, left, cnt++);
233 		if (ret) {
234 			pr_err("DFU write failed [%d]: left: %llu", ret, left);
235 			return ret;
236 		}
237 	}
238 
239 	/*
240 	 * To store last "packet" or write file from buffer to filesystem
241 	 * DFU storage backend requires dfu_flush
242 	 *
243 	 * This also frees memory malloc'ed by dfu_get_buf(), so no explicit
244 	 * need fo call dfu_free_buf() is needed.
245 	 */
246 	ret = dfu_flush(dfu_entity, transfer_buffer, 0, cnt);
247 	if (ret)
248 		pr_err("DFU flush failed!");
249 
250 	return ret;
251 }
252 
253 static long long int process_rqt_download(const struct rqt_box *rqt)
254 {
255 	ALLOC_CACHE_ALIGN_BUFFER(struct rsp_box, rsp, sizeof(struct rsp_box));
256 	static long long int left, ret_head;
257 	int file_type, ret = 0;
258 	static int cnt;
259 
260 	memset(rsp, 0, sizeof(struct rsp_box));
261 	rsp->rsp = rqt->rqt;
262 	rsp->rsp_data = rqt->rqt_data;
263 
264 	switch (rqt->rqt_data) {
265 	case RQT_DL_INIT:
266 		thor_file_size = rqt->int_data[0];
267 		debug("INIT: total %d bytes\n", rqt->int_data[0]);
268 		break;
269 	case RQT_DL_FILE_INFO:
270 		file_type = rqt->int_data[0];
271 		if (file_type == FILE_TYPE_PIT) {
272 			puts("PIT table file - not supported\n");
273 			rsp->ack = -ENOTSUPP;
274 			ret = rsp->ack;
275 			break;
276 		}
277 
278 		thor_file_size = rqt->int_data[1];
279 		memcpy(f_name, rqt->str_data[0], F_NAME_BUF_SIZE);
280 		f_name[F_NAME_BUF_SIZE] = '\0';
281 
282 		debug("INFO: name(%s, %d), size(%llu), type(%d)\n",
283 		      f_name, 0, thor_file_size, file_type);
284 
285 		rsp->int_data[0] = THOR_PACKET_SIZE;
286 
287 		alt_setting_num = dfu_get_alt(f_name);
288 		if (alt_setting_num < 0) {
289 			pr_err("Alt setting [%d] to write not found!",
290 			      alt_setting_num);
291 			rsp->ack = -ENODEV;
292 			ret = rsp->ack;
293 		}
294 		break;
295 	case RQT_DL_FILE_START:
296 		send_rsp(rsp);
297 		ret_head = download_head(thor_file_size, THOR_PACKET_SIZE,
298 					 &left, &cnt);
299 		if (ret_head < 0) {
300 			left = 0;
301 			cnt = 0;
302 		}
303 		return ret_head;
304 	case RQT_DL_FILE_END:
305 		debug("DL FILE_END\n");
306 		rsp->ack = download_tail(left, cnt);
307 		ret = rsp->ack;
308 		left = 0;
309 		cnt = 0;
310 		break;
311 	case RQT_DL_EXIT:
312 		debug("DL EXIT\n");
313 		break;
314 	default:
315 		pr_err("Operation not supported: %d", rqt->rqt_data);
316 		ret = -ENOTSUPP;
317 	}
318 
319 	send_rsp(rsp);
320 	return ret;
321 }
322 
323 static int process_data(void)
324 {
325 	ALLOC_CACHE_ALIGN_BUFFER(struct rqt_box, rqt, sizeof(struct rqt_box));
326 	int ret = -EINVAL;
327 
328 	memcpy(rqt, thor_rx_data_buf, sizeof(struct rqt_box));
329 
330 	debug("+RQT: %d, %d\n", rqt->rqt, rqt->rqt_data);
331 
332 	switch (rqt->rqt) {
333 	case RQT_INFO:
334 		ret = process_rqt_info(rqt);
335 		break;
336 	case RQT_CMD:
337 		ret = process_rqt_cmd(rqt);
338 		break;
339 	case RQT_DL:
340 		ret = (int) process_rqt_download(rqt);
341 		break;
342 	case RQT_UL:
343 		puts("RQT: UPLOAD not supported!\n");
344 		break;
345 	default:
346 		pr_err("unknown request (%d)", rqt->rqt);
347 	}
348 
349 	return ret;
350 }
351 
352 /* ********************************************************** */
353 /*         THOR USB Function				      */
354 /* ********************************************************** */
355 
356 static inline struct usb_endpoint_descriptor *
357 ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *hs,
358 	struct usb_endpoint_descriptor *fs)
359 {
360 	if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
361 		return hs;
362 	return fs;
363 }
364 
365 static struct usb_interface_descriptor thor_downloader_intf_data = {
366 	.bLength =		sizeof(thor_downloader_intf_data),
367 	.bDescriptorType =	USB_DT_INTERFACE,
368 
369 	.bNumEndpoints =	2,
370 	.bInterfaceClass =	USB_CLASS_CDC_DATA,
371 };
372 
373 static struct usb_endpoint_descriptor fs_in_desc = {
374 	.bLength =		USB_DT_ENDPOINT_SIZE,
375 	.bDescriptorType =	USB_DT_ENDPOINT,
376 
377 	.bEndpointAddress =	USB_DIR_IN,
378 	.bmAttributes =	USB_ENDPOINT_XFER_BULK,
379 };
380 
381 static struct usb_endpoint_descriptor fs_out_desc = {
382 	.bLength =		USB_DT_ENDPOINT_SIZE,
383 	.bDescriptorType =	USB_DT_ENDPOINT,
384 
385 	.bEndpointAddress =	USB_DIR_OUT,
386 	.bmAttributes =	USB_ENDPOINT_XFER_BULK,
387 };
388 
389 /* CDC configuration */
390 static struct usb_interface_descriptor thor_downloader_intf_int = {
391 	.bLength =		sizeof(thor_downloader_intf_int),
392 	.bDescriptorType =	USB_DT_INTERFACE,
393 
394 	.bNumEndpoints =	1,
395 	.bInterfaceClass =	USB_CLASS_COMM,
396 	 /* 0x02 Abstract Line Control Model */
397 	.bInterfaceSubClass =   USB_CDC_SUBCLASS_ACM,
398 	/* 0x01 Common AT commands */
399 	.bInterfaceProtocol =   USB_CDC_ACM_PROTO_AT_V25TER,
400 };
401 
402 static struct usb_cdc_header_desc thor_downloader_cdc_header = {
403 	.bLength         =    sizeof(thor_downloader_cdc_header),
404 	.bDescriptorType =    0x24, /* CS_INTERFACE */
405 	.bDescriptorSubType = 0x00,
406 	.bcdCDC =             0x0110,
407 };
408 
409 static struct usb_cdc_call_mgmt_descriptor thor_downloader_cdc_call = {
410 	.bLength         =    sizeof(thor_downloader_cdc_call),
411 	.bDescriptorType =    0x24, /* CS_INTERFACE */
412 	.bDescriptorSubType = 0x01,
413 	.bmCapabilities =     0x00,
414 	.bDataInterface =     0x01,
415 };
416 
417 static struct usb_cdc_acm_descriptor thor_downloader_cdc_abstract = {
418 	.bLength         =    sizeof(thor_downloader_cdc_abstract),
419 	.bDescriptorType =    0x24, /* CS_INTERFACE */
420 	.bDescriptorSubType = 0x02,
421 	.bmCapabilities =     0x00,
422 };
423 
424 static struct usb_cdc_union_desc thor_downloader_cdc_union = {
425 	.bLength         =     sizeof(thor_downloader_cdc_union),
426 	.bDescriptorType =     0x24, /* CS_INTERFACE */
427 	.bDescriptorSubType =  USB_CDC_UNION_TYPE,
428 };
429 
430 static struct usb_endpoint_descriptor fs_int_desc = {
431 	.bLength = USB_DT_ENDPOINT_SIZE,
432 	.bDescriptorType = USB_DT_ENDPOINT,
433 
434 	.bEndpointAddress = 3 | USB_DIR_IN,
435 	.bmAttributes = USB_ENDPOINT_XFER_INT,
436 	.wMaxPacketSize = __constant_cpu_to_le16(16),
437 
438 	.bInterval = 0x9,
439 };
440 
441 static struct usb_interface_assoc_descriptor
442 thor_iad_descriptor = {
443 	.bLength =		sizeof(thor_iad_descriptor),
444 	.bDescriptorType =	USB_DT_INTERFACE_ASSOCIATION,
445 
446 	.bFirstInterface =	0,
447 	.bInterfaceCount =	2,	/* control + data */
448 	.bFunctionClass =	USB_CLASS_COMM,
449 	.bFunctionSubClass =	USB_CDC_SUBCLASS_ACM,
450 	.bFunctionProtocol =	USB_CDC_PROTO_NONE,
451 };
452 
453 static struct usb_endpoint_descriptor hs_in_desc = {
454 	.bLength =		USB_DT_ENDPOINT_SIZE,
455 	.bDescriptorType =	USB_DT_ENDPOINT,
456 
457 	.bmAttributes =	USB_ENDPOINT_XFER_BULK,
458 	.wMaxPacketSize =	__constant_cpu_to_le16(512),
459 };
460 
461 static struct usb_endpoint_descriptor hs_out_desc = {
462 	.bLength =		USB_DT_ENDPOINT_SIZE,
463 	.bDescriptorType =	USB_DT_ENDPOINT,
464 
465 	.bmAttributes =	USB_ENDPOINT_XFER_BULK,
466 	.wMaxPacketSize =	__constant_cpu_to_le16(512),
467 };
468 
469 static struct usb_endpoint_descriptor hs_int_desc = {
470 	.bLength = USB_DT_ENDPOINT_SIZE,
471 	.bDescriptorType = USB_DT_ENDPOINT,
472 
473 	.bmAttributes = USB_ENDPOINT_XFER_INT,
474 	.wMaxPacketSize = __constant_cpu_to_le16(16),
475 
476 	.bInterval = 0x9,
477 };
478 
479 /*
480  * This attribute vendor descriptor is necessary for correct operation with
481  * Windows version of THOR download program
482  *
483  * It prevents windows driver from sending zero lenght packet (ZLP) after
484  * each THOR_PACKET_SIZE. This assures consistent behaviour with libusb
485  */
486 static struct usb_cdc_attribute_vendor_descriptor thor_downloader_cdc_av = {
487 	.bLength =              sizeof(thor_downloader_cdc_av),
488 	.bDescriptorType =      0x24,
489 	.bDescriptorSubType =   0x80,
490 	.DAUType =              0x0002,
491 	.DAULength =            0x0001,
492 	.DAUValue =             0x00,
493 };
494 
495 static const struct usb_descriptor_header *hs_thor_downloader_function[] = {
496 	(struct usb_descriptor_header *)&thor_iad_descriptor,
497 
498 	(struct usb_descriptor_header *)&thor_downloader_intf_int,
499 	(struct usb_descriptor_header *)&thor_downloader_cdc_header,
500 	(struct usb_descriptor_header *)&thor_downloader_cdc_call,
501 	(struct usb_descriptor_header *)&thor_downloader_cdc_abstract,
502 	(struct usb_descriptor_header *)&thor_downloader_cdc_union,
503 	(struct usb_descriptor_header *)&hs_int_desc,
504 
505 	(struct usb_descriptor_header *)&thor_downloader_intf_data,
506 	(struct usb_descriptor_header *)&thor_downloader_cdc_av,
507 	(struct usb_descriptor_header *)&hs_in_desc,
508 	(struct usb_descriptor_header *)&hs_out_desc,
509 	NULL,
510 };
511 
512 /*-------------------------------------------------------------------------*/
513 static struct usb_request *alloc_ep_req(struct usb_ep *ep, unsigned length)
514 {
515 	struct usb_request *req;
516 
517 	req = usb_ep_alloc_request(ep, 0);
518 	if (!req)
519 		return req;
520 
521 	req->length = length;
522 	req->buf = memalign(CONFIG_SYS_CACHELINE_SIZE, length);
523 	if (!req->buf) {
524 		usb_ep_free_request(ep, req);
525 		req = NULL;
526 	}
527 
528 	return req;
529 }
530 
531 static int thor_rx_data(void)
532 {
533 	struct thor_dev *dev = thor_func->dev;
534 	int data_to_rx, tmp, status;
535 
536 	data_to_rx = dev->out_req->length;
537 	tmp = data_to_rx;
538 	do {
539 		dev->out_req->length = data_to_rx;
540 		debug("dev->out_req->length:%d dev->rxdata:%d\n",
541 		      dev->out_req->length, dev->rxdata);
542 
543 		status = usb_ep_queue(dev->out_ep, dev->out_req, 0);
544 		if (status) {
545 			pr_err("kill %s:  resubmit %d bytes --> %d",
546 			      dev->out_ep->name, dev->out_req->length, status);
547 			usb_ep_set_halt(dev->out_ep);
548 			return -EAGAIN;
549 		}
550 
551 		while (!dev->rxdata) {
552 			usb_gadget_handle_interrupts(0);
553 			if (ctrlc())
554 				return -1;
555 		}
556 		dev->rxdata = 0;
557 		data_to_rx -= dev->out_req->actual;
558 	} while (data_to_rx);
559 
560 	return tmp;
561 }
562 
563 static void thor_tx_data(unsigned char *data, int len)
564 {
565 	struct thor_dev *dev = thor_func->dev;
566 	unsigned char *ptr = dev->in_req->buf;
567 	int status;
568 
569 	memset(ptr, 0, len);
570 	memcpy(ptr, data, len);
571 
572 	dev->in_req->length = len;
573 
574 	debug("%s: dev->in_req->length:%d to_cpy:%zd\n", __func__,
575 	      dev->in_req->length, sizeof(data));
576 
577 	status = usb_ep_queue(dev->in_ep, dev->in_req, 0);
578 	if (status) {
579 		pr_err("kill %s:  resubmit %d bytes --> %d",
580 		      dev->in_ep->name, dev->in_req->length, status);
581 		usb_ep_set_halt(dev->in_ep);
582 	}
583 
584 	/* Wait until tx interrupt received */
585 	while (!dev->txdata)
586 		usb_gadget_handle_interrupts(0);
587 
588 	dev->txdata = 0;
589 }
590 
591 static void thor_rx_tx_complete(struct usb_ep *ep, struct usb_request *req)
592 {
593 	struct thor_dev *dev = thor_func->dev;
594 	int status = req->status;
595 
596 	debug("%s: ep_ptr:%p, req_ptr:%p\n", __func__, ep, req);
597 	switch (status) {
598 	case 0:
599 		if (ep == dev->out_ep)
600 			dev->rxdata = 1;
601 		else
602 			dev->txdata = 1;
603 
604 		break;
605 
606 	/* this endpoint is normally active while we're configured */
607 	case -ECONNABORTED:		/* hardware forced ep reset */
608 	case -ECONNRESET:		/* request dequeued */
609 	case -ESHUTDOWN:		/* disconnect from host */
610 	case -EREMOTEIO:                /* short read */
611 	case -EOVERFLOW:
612 		pr_err("ERROR:%d", status);
613 		break;
614 	}
615 
616 	debug("%s complete --> %d, %d/%d\n", ep->name,
617 	      status, req->actual, req->length);
618 }
619 
620 static struct usb_request *thor_start_ep(struct usb_ep *ep)
621 {
622 	struct usb_request *req;
623 
624 	req = alloc_ep_req(ep, THOR_PACKET_SIZE);
625 	debug("%s: ep:%p req:%p\n", __func__, ep, req);
626 
627 	if (!req)
628 		return NULL;
629 
630 	memset(req->buf, 0, req->length);
631 	req->complete = thor_rx_tx_complete;
632 
633 	return req;
634 }
635 
636 static void thor_setup_complete(struct usb_ep *ep, struct usb_request *req)
637 {
638 	if (req->status || req->actual != req->length)
639 		debug("setup complete --> %d, %d/%d\n",
640 		      req->status, req->actual, req->length);
641 }
642 
643 static int
644 thor_func_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
645 {
646 	struct thor_dev *dev = thor_func->dev;
647 	struct usb_request *req = dev->req;
648 	struct usb_gadget *gadget = dev->gadget;
649 	int value = 0;
650 
651 	u16 len = le16_to_cpu(ctrl->wLength);
652 
653 	debug("Req_Type: 0x%x Req: 0x%x wValue: 0x%x wIndex: 0x%x wLen: 0x%x\n",
654 	      ctrl->bRequestType, ctrl->bRequest, ctrl->wValue, ctrl->wIndex,
655 	      ctrl->wLength);
656 
657 	switch (ctrl->bRequest) {
658 	case USB_CDC_REQ_SET_CONTROL_LINE_STATE:
659 		value = 0;
660 		break;
661 	case USB_CDC_REQ_SET_LINE_CODING:
662 		value = len;
663 		/* Line Coding set done = configuration done */
664 		thor_func->dev->configuration_done = 1;
665 		break;
666 
667 	default:
668 		pr_err("thor_setup: unknown request: %d", ctrl->bRequest);
669 	}
670 
671 	if (value >= 0) {
672 		req->length = value;
673 		req->zero = value < len;
674 		value = usb_ep_queue(gadget->ep0, req, 0);
675 		if (value < 0) {
676 			debug("%s: ep_queue: %d\n", __func__, value);
677 			req->status = 0;
678 		}
679 	}
680 
681 	return value;
682 }
683 
684 /* Specific to the THOR protocol */
685 static void thor_set_dma(void *addr, int len)
686 {
687 	struct thor_dev *dev = thor_func->dev;
688 
689 	debug("in_req:%p, out_req:%p\n", dev->in_req, dev->out_req);
690 	debug("addr:%p, len:%d\n", addr, len);
691 
692 	dev->out_req->buf = addr;
693 	dev->out_req->length = len;
694 }
695 
696 int thor_init(void)
697 {
698 	struct thor_dev *dev = thor_func->dev;
699 
700 	/* Wait for a device enumeration and configuration settings */
701 	debug("THOR enumeration/configuration setting....\n");
702 	while (!dev->configuration_done)
703 		usb_gadget_handle_interrupts(0);
704 
705 	thor_set_dma(thor_rx_data_buf, strlen("THOR"));
706 	/* detect the download request from Host PC */
707 	if (thor_rx_data() < 0) {
708 		printf("%s: Data not received!\n", __func__);
709 		return -1;
710 	}
711 
712 	if (!strncmp((char *)thor_rx_data_buf, "THOR", strlen("THOR"))) {
713 		puts("Download request from the Host PC\n");
714 		udelay(30 * 1000); /* 30 ms */
715 
716 		strcpy((char *)thor_tx_data_buf, "ROHT");
717 		thor_tx_data(thor_tx_data_buf, strlen("ROHT"));
718 	} else {
719 		puts("Wrong reply information\n");
720 		return -1;
721 	}
722 
723 	return 0;
724 }
725 
726 int thor_handle(void)
727 {
728 	int ret;
729 
730 	/* receive the data from Host PC */
731 	while (1) {
732 		thor_set_dma(thor_rx_data_buf, sizeof(struct rqt_box));
733 		ret = thor_rx_data();
734 
735 		if (ret > 0) {
736 			ret = process_data();
737 #ifdef CONFIG_THOR_RESET_OFF
738 			if (ret == RESET_DONE)
739 				break;
740 #endif
741 			if (ret < 0)
742 				return ret;
743 		} else {
744 			printf("%s: No data received!\n", __func__);
745 			break;
746 		}
747 	}
748 
749 	return 0;
750 }
751 
752 static int thor_func_bind(struct usb_configuration *c, struct usb_function *f)
753 {
754 	struct usb_gadget *gadget = c->cdev->gadget;
755 	struct f_thor *f_thor = func_to_thor(f);
756 	struct thor_dev *dev;
757 	struct usb_ep *ep;
758 	int status;
759 
760 	thor_func = f_thor;
761 	dev = memalign(CONFIG_SYS_CACHELINE_SIZE, sizeof(*dev));
762 	if (!dev)
763 		return -ENOMEM;
764 
765 	memset(dev, 0, sizeof(*dev));
766 	dev->gadget = gadget;
767 	f_thor->dev = dev;
768 
769 	debug("%s: usb_configuration: 0x%p usb_function: 0x%p\n",
770 	      __func__, c, f);
771 	debug("f_thor: 0x%p thor: 0x%p\n", f_thor, dev);
772 
773 	/* EP0  */
774 	/* preallocate control response and buffer */
775 	dev->req = usb_ep_alloc_request(gadget->ep0, 0);
776 	if (!dev->req) {
777 		status = -ENOMEM;
778 		goto fail;
779 	}
780 	dev->req->buf = memalign(CONFIG_SYS_CACHELINE_SIZE,
781 				 THOR_PACKET_SIZE);
782 	if (!dev->req->buf) {
783 		status = -ENOMEM;
784 		goto fail;
785 	}
786 
787 	dev->req->complete = thor_setup_complete;
788 
789 	/* DYNAMIC interface numbers assignments */
790 	status = usb_interface_id(c, f);
791 
792 	if (status < 0)
793 		goto fail;
794 
795 	thor_downloader_intf_int.bInterfaceNumber = status;
796 	thor_downloader_cdc_union.bMasterInterface0 = status;
797 
798 	status = usb_interface_id(c, f);
799 
800 	if (status < 0)
801 		goto fail;
802 
803 	thor_downloader_intf_data.bInterfaceNumber = status;
804 	thor_downloader_cdc_union.bSlaveInterface0 = status;
805 
806 	/* allocate instance-specific endpoints */
807 	ep = usb_ep_autoconfig(gadget, &fs_in_desc);
808 	if (!ep) {
809 		status = -ENODEV;
810 		goto fail;
811 	}
812 
813 	if (gadget_is_dualspeed(gadget)) {
814 		hs_in_desc.bEndpointAddress =
815 				fs_in_desc.bEndpointAddress;
816 	}
817 
818 	dev->in_ep = ep; /* Store IN EP for enabling @ setup */
819 	ep->driver_data = dev;
820 
821 	ep = usb_ep_autoconfig(gadget, &fs_out_desc);
822 	if (!ep) {
823 		status = -ENODEV;
824 		goto fail;
825 	}
826 
827 	if (gadget_is_dualspeed(gadget))
828 		hs_out_desc.bEndpointAddress =
829 				fs_out_desc.bEndpointAddress;
830 
831 	dev->out_ep = ep; /* Store OUT EP for enabling @ setup */
832 	ep->driver_data = dev;
833 
834 	ep = usb_ep_autoconfig(gadget, &fs_int_desc);
835 	if (!ep) {
836 		status = -ENODEV;
837 		goto fail;
838 	}
839 
840 	dev->int_ep = ep;
841 	ep->driver_data = dev;
842 
843 	if (gadget_is_dualspeed(gadget)) {
844 		hs_int_desc.bEndpointAddress =
845 				fs_int_desc.bEndpointAddress;
846 
847 		f->hs_descriptors = (struct usb_descriptor_header **)
848 			&hs_thor_downloader_function;
849 
850 		if (!f->hs_descriptors)
851 			goto fail;
852 	}
853 
854 	debug("%s: out_ep:%p out_req:%p\n", __func__,
855 	      dev->out_ep, dev->out_req);
856 
857 	return 0;
858 
859  fail:
860 	free(dev);
861 	return status;
862 }
863 
864 static void free_ep_req(struct usb_ep *ep, struct usb_request *req)
865 {
866 	free(req->buf);
867 	usb_ep_free_request(ep, req);
868 }
869 
870 static void thor_unbind(struct usb_configuration *c, struct usb_function *f)
871 {
872 	struct f_thor *f_thor = func_to_thor(f);
873 	struct thor_dev *dev = f_thor->dev;
874 
875 	free(dev);
876 	memset(thor_func, 0, sizeof(*thor_func));
877 	thor_func = NULL;
878 }
879 
880 static void thor_func_disable(struct usb_function *f)
881 {
882 	struct f_thor *f_thor = func_to_thor(f);
883 	struct thor_dev *dev = f_thor->dev;
884 
885 	debug("%s:\n", __func__);
886 
887 	/* Avoid freeing memory when ep is still claimed */
888 	if (dev->in_ep->driver_data) {
889 		free_ep_req(dev->in_ep, dev->in_req);
890 		usb_ep_disable(dev->in_ep);
891 		dev->in_ep->driver_data = NULL;
892 	}
893 
894 	if (dev->out_ep->driver_data) {
895 		free(dev->out_req->buf);
896 		dev->out_req->buf = NULL;
897 		usb_ep_free_request(dev->out_ep, dev->out_req);
898 		usb_ep_disable(dev->out_ep);
899 		dev->out_ep->driver_data = NULL;
900 	}
901 
902 	if (dev->int_ep->driver_data) {
903 		usb_ep_disable(dev->int_ep);
904 		dev->int_ep->driver_data = NULL;
905 	}
906 }
907 
908 static int thor_eps_setup(struct usb_function *f)
909 {
910 	struct usb_composite_dev *cdev = f->config->cdev;
911 	struct usb_gadget *gadget = cdev->gadget;
912 	struct thor_dev *dev = thor_func->dev;
913 	struct usb_endpoint_descriptor *d;
914 	struct usb_request *req;
915 	struct usb_ep *ep;
916 	int result;
917 
918 	ep = dev->in_ep;
919 	d = ep_desc(gadget, &hs_in_desc, &fs_in_desc);
920 	debug("(d)bEndpointAddress: 0x%x\n", d->bEndpointAddress);
921 
922 	result = usb_ep_enable(ep, d);
923 	if (result)
924 		goto exit;
925 
926 	ep->driver_data = cdev; /* claim */
927 	req = thor_start_ep(ep);
928 	if (!req) {
929 		usb_ep_disable(ep);
930 		result = -EIO;
931 		goto exit;
932 	}
933 
934 	dev->in_req = req;
935 	ep = dev->out_ep;
936 	d = ep_desc(gadget, &hs_out_desc, &fs_out_desc);
937 	debug("(d)bEndpointAddress: 0x%x\n", d->bEndpointAddress);
938 
939 	result = usb_ep_enable(ep, d);
940 	if (result)
941 		goto exit;
942 
943 	ep->driver_data = cdev; /* claim */
944 	req = thor_start_ep(ep);
945 	if (!req) {
946 		usb_ep_disable(ep);
947 		result = -EIO;
948 		goto exit;
949 	}
950 
951 	dev->out_req = req;
952 	/* ACM control EP */
953 	ep = dev->int_ep;
954 	ep->driver_data = cdev;	/* claim */
955 
956  exit:
957 	return result;
958 }
959 
960 static int thor_func_set_alt(struct usb_function *f,
961 			     unsigned intf, unsigned alt)
962 {
963 	struct thor_dev *dev = thor_func->dev;
964 	int result;
965 
966 	debug("%s: func: %s intf: %d alt: %d\n",
967 	      __func__, f->name, intf, alt);
968 
969 	switch (intf) {
970 	case 0:
971 		debug("ACM INTR interface\n");
972 		break;
973 	case 1:
974 		debug("Communication Data interface\n");
975 		result = thor_eps_setup(f);
976 		if (result)
977 			pr_err("%s: EPs setup failed!", __func__);
978 		dev->configuration_done = 1;
979 		break;
980 	}
981 
982 	return 0;
983 }
984 
985 static int thor_func_init(struct usb_configuration *c)
986 {
987 	struct f_thor *f_thor;
988 	int status;
989 
990 	debug("%s: cdev: 0x%p\n", __func__, c->cdev);
991 
992 	f_thor = memalign(CONFIG_SYS_CACHELINE_SIZE, sizeof(*f_thor));
993 	if (!f_thor)
994 		return -ENOMEM;
995 
996 	memset(f_thor, 0, sizeof(*f_thor));
997 
998 	f_thor->usb_function.name = "f_thor";
999 	f_thor->usb_function.bind = thor_func_bind;
1000 	f_thor->usb_function.unbind = thor_unbind;
1001 	f_thor->usb_function.setup = thor_func_setup;
1002 	f_thor->usb_function.set_alt = thor_func_set_alt;
1003 	f_thor->usb_function.disable = thor_func_disable;
1004 
1005 	status = usb_add_function(c, &f_thor->usb_function);
1006 	if (status)
1007 		free(f_thor);
1008 
1009 	return status;
1010 }
1011 
1012 int thor_add(struct usb_configuration *c)
1013 {
1014 	debug("%s:\n", __func__);
1015 	return thor_func_init(c);
1016 }
1017 
1018 DECLARE_GADGET_BIND_CALLBACK(usb_dnl_thor, thor_add);
1019