1 /*
2  * Copyright (C) 2011 Marvell International Ltd. All rights reserved.
3  * Author: Chao Xie <chao.xie@marvell.com>
4  *	   Neil Zhang <zhangwm@marvell.com>
5  *
6  * This program is free software; you can redistribute  it and/or modify it
7  * under  the terms of  the GNU General  Public License as published by the
8  * Free Software Foundation;  either version 2 of the  License, or (at your
9  * option) any later version.
10  */
11 
12 #include <linux/module.h>
13 #include <linux/pci.h>
14 #include <linux/dma-mapping.h>
15 #include <linux/dmapool.h>
16 #include <linux/kernel.h>
17 #include <linux/delay.h>
18 #include <linux/ioport.h>
19 #include <linux/sched.h>
20 #include <linux/slab.h>
21 #include <linux/errno.h>
22 #include <linux/err.h>
23 #include <linux/timer.h>
24 #include <linux/list.h>
25 #include <linux/interrupt.h>
26 #include <linux/moduleparam.h>
27 #include <linux/device.h>
28 #include <linux/usb/ch9.h>
29 #include <linux/usb/gadget.h>
30 #include <linux/usb/otg.h>
31 #include <linux/pm.h>
32 #include <linux/io.h>
33 #include <linux/irq.h>
34 #include <linux/platform_device.h>
35 #include <linux/clk.h>
36 #include <linux/platform_data/mv_usb.h>
37 #include <asm/unaligned.h>
38 
39 #include "mv_udc.h"
40 
41 #define DRIVER_DESC		"Marvell PXA USB Device Controller driver"
42 #define DRIVER_VERSION		"8 Nov 2010"
43 
44 #define ep_dir(ep)	(((ep)->ep_num == 0) ? \
45 				((ep)->udc->ep0_dir) : ((ep)->direction))
46 
47 /* timeout value -- usec */
48 #define RESET_TIMEOUT		10000
49 #define FLUSH_TIMEOUT		10000
50 #define EPSTATUS_TIMEOUT	10000
51 #define PRIME_TIMEOUT		10000
52 #define READSAFE_TIMEOUT	1000
53 
54 #define LOOPS_USEC_SHIFT	1
55 #define LOOPS_USEC		(1 << LOOPS_USEC_SHIFT)
56 #define LOOPS(timeout)		((timeout) >> LOOPS_USEC_SHIFT)
57 
58 static DECLARE_COMPLETION(release_done);
59 
60 static const char driver_name[] = "mv_udc";
61 static const char driver_desc[] = DRIVER_DESC;
62 
63 static void nuke(struct mv_ep *ep, int status);
64 static void stop_activity(struct mv_udc *udc, struct usb_gadget_driver *driver);
65 
66 /* for endpoint 0 operations */
67 static const struct usb_endpoint_descriptor mv_ep0_desc = {
68 	.bLength =		USB_DT_ENDPOINT_SIZE,
69 	.bDescriptorType =	USB_DT_ENDPOINT,
70 	.bEndpointAddress =	0,
71 	.bmAttributes =		USB_ENDPOINT_XFER_CONTROL,
72 	.wMaxPacketSize =	EP0_MAX_PKT_SIZE,
73 };
74 
75 static void ep0_reset(struct mv_udc *udc)
76 {
77 	struct mv_ep *ep;
78 	u32 epctrlx;
79 	int i = 0;
80 
81 	/* ep0 in and out */
82 	for (i = 0; i < 2; i++) {
83 		ep = &udc->eps[i];
84 		ep->udc = udc;
85 
86 		/* ep0 dQH */
87 		ep->dqh = &udc->ep_dqh[i];
88 
89 		/* configure ep0 endpoint capabilities in dQH */
90 		ep->dqh->max_packet_length =
91 			(EP0_MAX_PKT_SIZE << EP_QUEUE_HEAD_MAX_PKT_LEN_POS)
92 			| EP_QUEUE_HEAD_IOS;
93 
94 		ep->dqh->next_dtd_ptr = EP_QUEUE_HEAD_NEXT_TERMINATE;
95 
96 		epctrlx = readl(&udc->op_regs->epctrlx[0]);
97 		if (i) {	/* TX */
98 			epctrlx |= EPCTRL_TX_ENABLE
99 				| (USB_ENDPOINT_XFER_CONTROL
100 					<< EPCTRL_TX_EP_TYPE_SHIFT);
101 
102 		} else {	/* RX */
103 			epctrlx |= EPCTRL_RX_ENABLE
104 				| (USB_ENDPOINT_XFER_CONTROL
105 					<< EPCTRL_RX_EP_TYPE_SHIFT);
106 		}
107 
108 		writel(epctrlx, &udc->op_regs->epctrlx[0]);
109 	}
110 }
111 
112 /* protocol ep0 stall, will automatically be cleared on new transaction */
113 static void ep0_stall(struct mv_udc *udc)
114 {
115 	u32	epctrlx;
116 
117 	/* set TX and RX to stall */
118 	epctrlx = readl(&udc->op_regs->epctrlx[0]);
119 	epctrlx |= EPCTRL_RX_EP_STALL | EPCTRL_TX_EP_STALL;
120 	writel(epctrlx, &udc->op_regs->epctrlx[0]);
121 
122 	/* update ep0 state */
123 	udc->ep0_state = WAIT_FOR_SETUP;
124 	udc->ep0_dir = EP_DIR_OUT;
125 }
126 
127 static int process_ep_req(struct mv_udc *udc, int index,
128 	struct mv_req *curr_req)
129 {
130 	struct mv_dtd	*curr_dtd;
131 	struct mv_dqh	*curr_dqh;
132 	int actual, remaining_length;
133 	int i, direction;
134 	int retval = 0;
135 	u32 errors;
136 	u32 bit_pos;
137 
138 	curr_dqh = &udc->ep_dqh[index];
139 	direction = index % 2;
140 
141 	curr_dtd = curr_req->head;
142 	actual = curr_req->req.length;
143 
144 	for (i = 0; i < curr_req->dtd_count; i++) {
145 		if (curr_dtd->size_ioc_sts & DTD_STATUS_ACTIVE) {
146 			dev_dbg(&udc->dev->dev, "%s, dTD not completed\n",
147 				udc->eps[index].name);
148 			return 1;
149 		}
150 
151 		errors = curr_dtd->size_ioc_sts & DTD_ERROR_MASK;
152 		if (!errors) {
153 			remaining_length =
154 				(curr_dtd->size_ioc_sts	& DTD_PACKET_SIZE)
155 					>> DTD_LENGTH_BIT_POS;
156 			actual -= remaining_length;
157 
158 			if (remaining_length) {
159 				if (direction) {
160 					dev_dbg(&udc->dev->dev,
161 						"TX dTD remains data\n");
162 					retval = -EPROTO;
163 					break;
164 				} else
165 					break;
166 			}
167 		} else {
168 			dev_info(&udc->dev->dev,
169 				"complete_tr error: ep=%d %s: error = 0x%x\n",
170 				index >> 1, direction ? "SEND" : "RECV",
171 				errors);
172 			if (errors & DTD_STATUS_HALTED) {
173 				/* Clear the errors and Halt condition */
174 				curr_dqh->size_ioc_int_sts &= ~errors;
175 				retval = -EPIPE;
176 			} else if (errors & DTD_STATUS_DATA_BUFF_ERR) {
177 				retval = -EPROTO;
178 			} else if (errors & DTD_STATUS_TRANSACTION_ERR) {
179 				retval = -EILSEQ;
180 			}
181 		}
182 		if (i != curr_req->dtd_count - 1)
183 			curr_dtd = (struct mv_dtd *)curr_dtd->next_dtd_virt;
184 	}
185 	if (retval)
186 		return retval;
187 
188 	if (direction == EP_DIR_OUT)
189 		bit_pos = 1 << curr_req->ep->ep_num;
190 	else
191 		bit_pos = 1 << (16 + curr_req->ep->ep_num);
192 
193 	while ((curr_dqh->curr_dtd_ptr == curr_dtd->td_dma)) {
194 		if (curr_dtd->dtd_next == EP_QUEUE_HEAD_NEXT_TERMINATE) {
195 			while (readl(&udc->op_regs->epstatus) & bit_pos)
196 				udelay(1);
197 			break;
198 		}
199 		udelay(1);
200 	}
201 
202 	curr_req->req.actual = actual;
203 
204 	return 0;
205 }
206 
207 /*
208  * done() - retire a request; caller blocked irqs
209  * @status : request status to be set, only works when
210  * request is still in progress.
211  */
212 static void done(struct mv_ep *ep, struct mv_req *req, int status)
213 	__releases(&ep->udc->lock)
214 	__acquires(&ep->udc->lock)
215 {
216 	struct mv_udc *udc = NULL;
217 	unsigned char stopped = ep->stopped;
218 	struct mv_dtd *curr_td, *next_td;
219 	int j;
220 
221 	udc = (struct mv_udc *)ep->udc;
222 	/* Removed the req from fsl_ep->queue */
223 	list_del_init(&req->queue);
224 
225 	/* req.status should be set as -EINPROGRESS in ep_queue() */
226 	if (req->req.status == -EINPROGRESS)
227 		req->req.status = status;
228 	else
229 		status = req->req.status;
230 
231 	/* Free dtd for the request */
232 	next_td = req->head;
233 	for (j = 0; j < req->dtd_count; j++) {
234 		curr_td = next_td;
235 		if (j != req->dtd_count - 1)
236 			next_td = curr_td->next_dtd_virt;
237 		dma_pool_free(udc->dtd_pool, curr_td, curr_td->td_dma);
238 	}
239 
240 	usb_gadget_unmap_request(&udc->gadget, &req->req, ep_dir(ep));
241 
242 	if (status && (status != -ESHUTDOWN))
243 		dev_info(&udc->dev->dev, "complete %s req %p stat %d len %u/%u",
244 			ep->ep.name, &req->req, status,
245 			req->req.actual, req->req.length);
246 
247 	ep->stopped = 1;
248 
249 	spin_unlock(&ep->udc->lock);
250 
251 	usb_gadget_giveback_request(&ep->ep, &req->req);
252 
253 	spin_lock(&ep->udc->lock);
254 	ep->stopped = stopped;
255 }
256 
257 static int queue_dtd(struct mv_ep *ep, struct mv_req *req)
258 {
259 	struct mv_udc *udc;
260 	struct mv_dqh *dqh;
261 	u32 bit_pos, direction;
262 	u32 usbcmd, epstatus;
263 	unsigned int loops;
264 	int retval = 0;
265 
266 	udc = ep->udc;
267 	direction = ep_dir(ep);
268 	dqh = &(udc->ep_dqh[ep->ep_num * 2 + direction]);
269 	bit_pos = 1 << (((direction == EP_DIR_OUT) ? 0 : 16) + ep->ep_num);
270 
271 	/* check if the pipe is empty */
272 	if (!(list_empty(&ep->queue))) {
273 		struct mv_req *lastreq;
274 		lastreq = list_entry(ep->queue.prev, struct mv_req, queue);
275 		lastreq->tail->dtd_next =
276 			req->head->td_dma & EP_QUEUE_HEAD_NEXT_POINTER_MASK;
277 
278 		wmb();
279 
280 		if (readl(&udc->op_regs->epprime) & bit_pos)
281 			goto done;
282 
283 		loops = LOOPS(READSAFE_TIMEOUT);
284 		while (1) {
285 			/* start with setting the semaphores */
286 			usbcmd = readl(&udc->op_regs->usbcmd);
287 			usbcmd |= USBCMD_ATDTW_TRIPWIRE_SET;
288 			writel(usbcmd, &udc->op_regs->usbcmd);
289 
290 			/* read the endpoint status */
291 			epstatus = readl(&udc->op_regs->epstatus) & bit_pos;
292 
293 			/*
294 			 * Reread the ATDTW semaphore bit to check if it is
295 			 * cleared. When hardware see a hazard, it will clear
296 			 * the bit or else we remain set to 1 and we can
297 			 * proceed with priming of endpoint if not already
298 			 * primed.
299 			 */
300 			if (readl(&udc->op_regs->usbcmd)
301 				& USBCMD_ATDTW_TRIPWIRE_SET)
302 				break;
303 
304 			loops--;
305 			if (loops == 0) {
306 				dev_err(&udc->dev->dev,
307 					"Timeout for ATDTW_TRIPWIRE...\n");
308 				retval = -ETIME;
309 				goto done;
310 			}
311 			udelay(LOOPS_USEC);
312 		}
313 
314 		/* Clear the semaphore */
315 		usbcmd = readl(&udc->op_regs->usbcmd);
316 		usbcmd &= USBCMD_ATDTW_TRIPWIRE_CLEAR;
317 		writel(usbcmd, &udc->op_regs->usbcmd);
318 
319 		if (epstatus)
320 			goto done;
321 	}
322 
323 	/* Write dQH next pointer and terminate bit to 0 */
324 	dqh->next_dtd_ptr = req->head->td_dma
325 				& EP_QUEUE_HEAD_NEXT_POINTER_MASK;
326 
327 	/* clear active and halt bit, in case set from a previous error */
328 	dqh->size_ioc_int_sts &= ~(DTD_STATUS_ACTIVE | DTD_STATUS_HALTED);
329 
330 	/* Ensure that updates to the QH will occur before priming. */
331 	wmb();
332 
333 	/* Prime the Endpoint */
334 	writel(bit_pos, &udc->op_regs->epprime);
335 
336 done:
337 	return retval;
338 }
339 
340 static struct mv_dtd *build_dtd(struct mv_req *req, unsigned *length,
341 		dma_addr_t *dma, int *is_last)
342 {
343 	struct mv_dtd *dtd;
344 	struct mv_udc *udc;
345 	struct mv_dqh *dqh;
346 	u32 temp, mult = 0;
347 
348 	/* how big will this transfer be? */
349 	if (usb_endpoint_xfer_isoc(req->ep->ep.desc)) {
350 		dqh = req->ep->dqh;
351 		mult = (dqh->max_packet_length >> EP_QUEUE_HEAD_MULT_POS)
352 				& 0x3;
353 		*length = min(req->req.length - req->req.actual,
354 				(unsigned)(mult * req->ep->ep.maxpacket));
355 	} else
356 		*length = min(req->req.length - req->req.actual,
357 				(unsigned)EP_MAX_LENGTH_TRANSFER);
358 
359 	udc = req->ep->udc;
360 
361 	/*
362 	 * Be careful that no _GFP_HIGHMEM is set,
363 	 * or we can not use dma_to_virt
364 	 */
365 	dtd = dma_pool_alloc(udc->dtd_pool, GFP_ATOMIC, dma);
366 	if (dtd == NULL)
367 		return dtd;
368 
369 	dtd->td_dma = *dma;
370 	/* initialize buffer page pointers */
371 	temp = (u32)(req->req.dma + req->req.actual);
372 	dtd->buff_ptr0 = cpu_to_le32(temp);
373 	temp &= ~0xFFF;
374 	dtd->buff_ptr1 = cpu_to_le32(temp + 0x1000);
375 	dtd->buff_ptr2 = cpu_to_le32(temp + 0x2000);
376 	dtd->buff_ptr3 = cpu_to_le32(temp + 0x3000);
377 	dtd->buff_ptr4 = cpu_to_le32(temp + 0x4000);
378 
379 	req->req.actual += *length;
380 
381 	/* zlp is needed if req->req.zero is set */
382 	if (req->req.zero) {
383 		if (*length == 0 || (*length % req->ep->ep.maxpacket) != 0)
384 			*is_last = 1;
385 		else
386 			*is_last = 0;
387 	} else if (req->req.length == req->req.actual)
388 		*is_last = 1;
389 	else
390 		*is_last = 0;
391 
392 	/* Fill in the transfer size; set active bit */
393 	temp = ((*length << DTD_LENGTH_BIT_POS) | DTD_STATUS_ACTIVE);
394 
395 	/* Enable interrupt for the last dtd of a request */
396 	if (*is_last && !req->req.no_interrupt)
397 		temp |= DTD_IOC;
398 
399 	temp |= mult << 10;
400 
401 	dtd->size_ioc_sts = temp;
402 
403 	mb();
404 
405 	return dtd;
406 }
407 
408 /* generate dTD linked list for a request */
409 static int req_to_dtd(struct mv_req *req)
410 {
411 	unsigned count;
412 	int is_last, is_first = 1;
413 	struct mv_dtd *dtd, *last_dtd = NULL;
414 	dma_addr_t dma;
415 
416 	do {
417 		dtd = build_dtd(req, &count, &dma, &is_last);
418 		if (dtd == NULL)
419 			return -ENOMEM;
420 
421 		if (is_first) {
422 			is_first = 0;
423 			req->head = dtd;
424 		} else {
425 			last_dtd->dtd_next = dma;
426 			last_dtd->next_dtd_virt = dtd;
427 		}
428 		last_dtd = dtd;
429 		req->dtd_count++;
430 	} while (!is_last);
431 
432 	/* set terminate bit to 1 for the last dTD */
433 	dtd->dtd_next = DTD_NEXT_TERMINATE;
434 
435 	req->tail = dtd;
436 
437 	return 0;
438 }
439 
440 static int mv_ep_enable(struct usb_ep *_ep,
441 		const struct usb_endpoint_descriptor *desc)
442 {
443 	struct mv_udc *udc;
444 	struct mv_ep *ep;
445 	struct mv_dqh *dqh;
446 	u16 max = 0;
447 	u32 bit_pos, epctrlx, direction;
448 	const unsigned char zlt = 1;
449 	unsigned char ios, mult;
450 	unsigned long flags;
451 
452 	ep = container_of(_ep, struct mv_ep, ep);
453 	udc = ep->udc;
454 
455 	if (!_ep || !desc
456 			|| desc->bDescriptorType != USB_DT_ENDPOINT)
457 		return -EINVAL;
458 
459 	if (!udc->driver || udc->gadget.speed == USB_SPEED_UNKNOWN)
460 		return -ESHUTDOWN;
461 
462 	direction = ep_dir(ep);
463 	max = usb_endpoint_maxp(desc);
464 
465 	/*
466 	 * disable HW zero length termination select
467 	 * driver handles zero length packet through req->req.zero
468 	 */
469 	bit_pos = 1 << ((direction == EP_DIR_OUT ? 0 : 16) + ep->ep_num);
470 
471 	/* Check if the Endpoint is Primed */
472 	if ((readl(&udc->op_regs->epprime) & bit_pos)
473 		|| (readl(&udc->op_regs->epstatus) & bit_pos)) {
474 		dev_info(&udc->dev->dev,
475 			"ep=%d %s: Init ERROR: ENDPTPRIME=0x%x,"
476 			" ENDPTSTATUS=0x%x, bit_pos=0x%x\n",
477 			(unsigned)ep->ep_num, direction ? "SEND" : "RECV",
478 			(unsigned)readl(&udc->op_regs->epprime),
479 			(unsigned)readl(&udc->op_regs->epstatus),
480 			(unsigned)bit_pos);
481 		goto en_done;
482 	}
483 
484 	/* Set the max packet length, interrupt on Setup and Mult fields */
485 	ios = 0;
486 	mult = 0;
487 	switch (desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
488 	case USB_ENDPOINT_XFER_BULK:
489 	case USB_ENDPOINT_XFER_INT:
490 		break;
491 	case USB_ENDPOINT_XFER_CONTROL:
492 		ios = 1;
493 		break;
494 	case USB_ENDPOINT_XFER_ISOC:
495 		/* Calculate transactions needed for high bandwidth iso */
496 		mult = usb_endpoint_maxp_mult(desc);
497 		/* 3 transactions at most */
498 		if (mult > 3)
499 			goto en_done;
500 		break;
501 	default:
502 		goto en_done;
503 	}
504 
505 	spin_lock_irqsave(&udc->lock, flags);
506 	/* Get the endpoint queue head address */
507 	dqh = ep->dqh;
508 	dqh->max_packet_length = (max << EP_QUEUE_HEAD_MAX_PKT_LEN_POS)
509 		| (mult << EP_QUEUE_HEAD_MULT_POS)
510 		| (zlt ? EP_QUEUE_HEAD_ZLT_SEL : 0)
511 		| (ios ? EP_QUEUE_HEAD_IOS : 0);
512 	dqh->next_dtd_ptr = 1;
513 	dqh->size_ioc_int_sts = 0;
514 
515 	ep->ep.maxpacket = max;
516 	ep->ep.desc = desc;
517 	ep->stopped = 0;
518 
519 	/* Enable the endpoint for Rx or Tx and set the endpoint type */
520 	epctrlx = readl(&udc->op_regs->epctrlx[ep->ep_num]);
521 	if (direction == EP_DIR_IN) {
522 		epctrlx &= ~EPCTRL_TX_ALL_MASK;
523 		epctrlx |= EPCTRL_TX_ENABLE | EPCTRL_TX_DATA_TOGGLE_RST
524 			| ((desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
525 				<< EPCTRL_TX_EP_TYPE_SHIFT);
526 	} else {
527 		epctrlx &= ~EPCTRL_RX_ALL_MASK;
528 		epctrlx |= EPCTRL_RX_ENABLE | EPCTRL_RX_DATA_TOGGLE_RST
529 			| ((desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
530 				<< EPCTRL_RX_EP_TYPE_SHIFT);
531 	}
532 	writel(epctrlx, &udc->op_regs->epctrlx[ep->ep_num]);
533 
534 	/*
535 	 * Implement Guideline (GL# USB-7) The unused endpoint type must
536 	 * be programmed to bulk.
537 	 */
538 	epctrlx = readl(&udc->op_regs->epctrlx[ep->ep_num]);
539 	if ((epctrlx & EPCTRL_RX_ENABLE) == 0) {
540 		epctrlx |= (USB_ENDPOINT_XFER_BULK
541 				<< EPCTRL_RX_EP_TYPE_SHIFT);
542 		writel(epctrlx, &udc->op_regs->epctrlx[ep->ep_num]);
543 	}
544 
545 	epctrlx = readl(&udc->op_regs->epctrlx[ep->ep_num]);
546 	if ((epctrlx & EPCTRL_TX_ENABLE) == 0) {
547 		epctrlx |= (USB_ENDPOINT_XFER_BULK
548 				<< EPCTRL_TX_EP_TYPE_SHIFT);
549 		writel(epctrlx, &udc->op_regs->epctrlx[ep->ep_num]);
550 	}
551 
552 	spin_unlock_irqrestore(&udc->lock, flags);
553 
554 	return 0;
555 en_done:
556 	return -EINVAL;
557 }
558 
559 static int  mv_ep_disable(struct usb_ep *_ep)
560 {
561 	struct mv_udc *udc;
562 	struct mv_ep *ep;
563 	struct mv_dqh *dqh;
564 	u32 epctrlx, direction;
565 	unsigned long flags;
566 
567 	ep = container_of(_ep, struct mv_ep, ep);
568 	if ((_ep == NULL) || !ep->ep.desc)
569 		return -EINVAL;
570 
571 	udc = ep->udc;
572 
573 	/* Get the endpoint queue head address */
574 	dqh = ep->dqh;
575 
576 	spin_lock_irqsave(&udc->lock, flags);
577 
578 	direction = ep_dir(ep);
579 
580 	/* Reset the max packet length and the interrupt on Setup */
581 	dqh->max_packet_length = 0;
582 
583 	/* Disable the endpoint for Rx or Tx and reset the endpoint type */
584 	epctrlx = readl(&udc->op_regs->epctrlx[ep->ep_num]);
585 	epctrlx &= ~((direction == EP_DIR_IN)
586 			? (EPCTRL_TX_ENABLE | EPCTRL_TX_TYPE)
587 			: (EPCTRL_RX_ENABLE | EPCTRL_RX_TYPE));
588 	writel(epctrlx, &udc->op_regs->epctrlx[ep->ep_num]);
589 
590 	/* nuke all pending requests (does flush) */
591 	nuke(ep, -ESHUTDOWN);
592 
593 	ep->ep.desc = NULL;
594 	ep->stopped = 1;
595 
596 	spin_unlock_irqrestore(&udc->lock, flags);
597 
598 	return 0;
599 }
600 
601 static struct usb_request *
602 mv_alloc_request(struct usb_ep *_ep, gfp_t gfp_flags)
603 {
604 	struct mv_req *req = NULL;
605 
606 	req = kzalloc(sizeof *req, gfp_flags);
607 	if (!req)
608 		return NULL;
609 
610 	req->req.dma = DMA_ADDR_INVALID;
611 	INIT_LIST_HEAD(&req->queue);
612 
613 	return &req->req;
614 }
615 
616 static void mv_free_request(struct usb_ep *_ep, struct usb_request *_req)
617 {
618 	struct mv_req *req = NULL;
619 
620 	req = container_of(_req, struct mv_req, req);
621 
622 	if (_req)
623 		kfree(req);
624 }
625 
626 static void mv_ep_fifo_flush(struct usb_ep *_ep)
627 {
628 	struct mv_udc *udc;
629 	u32 bit_pos, direction;
630 	struct mv_ep *ep;
631 	unsigned int loops;
632 
633 	if (!_ep)
634 		return;
635 
636 	ep = container_of(_ep, struct mv_ep, ep);
637 	if (!ep->ep.desc)
638 		return;
639 
640 	udc = ep->udc;
641 	direction = ep_dir(ep);
642 
643 	if (ep->ep_num == 0)
644 		bit_pos = (1 << 16) | 1;
645 	else if (direction == EP_DIR_OUT)
646 		bit_pos = 1 << ep->ep_num;
647 	else
648 		bit_pos = 1 << (16 + ep->ep_num);
649 
650 	loops = LOOPS(EPSTATUS_TIMEOUT);
651 	do {
652 		unsigned int inter_loops;
653 
654 		if (loops == 0) {
655 			dev_err(&udc->dev->dev,
656 				"TIMEOUT for ENDPTSTATUS=0x%x, bit_pos=0x%x\n",
657 				(unsigned)readl(&udc->op_regs->epstatus),
658 				(unsigned)bit_pos);
659 			return;
660 		}
661 		/* Write 1 to the Flush register */
662 		writel(bit_pos, &udc->op_regs->epflush);
663 
664 		/* Wait until flushing completed */
665 		inter_loops = LOOPS(FLUSH_TIMEOUT);
666 		while (readl(&udc->op_regs->epflush)) {
667 			/*
668 			 * ENDPTFLUSH bit should be cleared to indicate this
669 			 * operation is complete
670 			 */
671 			if (inter_loops == 0) {
672 				dev_err(&udc->dev->dev,
673 					"TIMEOUT for ENDPTFLUSH=0x%x,"
674 					"bit_pos=0x%x\n",
675 					(unsigned)readl(&udc->op_regs->epflush),
676 					(unsigned)bit_pos);
677 				return;
678 			}
679 			inter_loops--;
680 			udelay(LOOPS_USEC);
681 		}
682 		loops--;
683 	} while (readl(&udc->op_regs->epstatus) & bit_pos);
684 }
685 
686 /* queues (submits) an I/O request to an endpoint */
687 static int
688 mv_ep_queue(struct usb_ep *_ep, struct usb_request *_req, gfp_t gfp_flags)
689 {
690 	struct mv_ep *ep = container_of(_ep, struct mv_ep, ep);
691 	struct mv_req *req = container_of(_req, struct mv_req, req);
692 	struct mv_udc *udc = ep->udc;
693 	unsigned long flags;
694 	int retval;
695 
696 	/* catch various bogus parameters */
697 	if (!_req || !req->req.complete || !req->req.buf
698 			|| !list_empty(&req->queue)) {
699 		dev_err(&udc->dev->dev, "%s, bad params", __func__);
700 		return -EINVAL;
701 	}
702 	if (unlikely(!_ep || !ep->ep.desc)) {
703 		dev_err(&udc->dev->dev, "%s, bad ep", __func__);
704 		return -EINVAL;
705 	}
706 
707 	udc = ep->udc;
708 	if (!udc->driver || udc->gadget.speed == USB_SPEED_UNKNOWN)
709 		return -ESHUTDOWN;
710 
711 	req->ep = ep;
712 
713 	/* map virtual address to hardware */
714 	retval = usb_gadget_map_request(&udc->gadget, _req, ep_dir(ep));
715 	if (retval)
716 		return retval;
717 
718 	req->req.status = -EINPROGRESS;
719 	req->req.actual = 0;
720 	req->dtd_count = 0;
721 
722 	spin_lock_irqsave(&udc->lock, flags);
723 
724 	/* build dtds and push them to device queue */
725 	if (!req_to_dtd(req)) {
726 		retval = queue_dtd(ep, req);
727 		if (retval) {
728 			spin_unlock_irqrestore(&udc->lock, flags);
729 			dev_err(&udc->dev->dev, "Failed to queue dtd\n");
730 			goto err_unmap_dma;
731 		}
732 	} else {
733 		spin_unlock_irqrestore(&udc->lock, flags);
734 		dev_err(&udc->dev->dev, "Failed to dma_pool_alloc\n");
735 		retval = -ENOMEM;
736 		goto err_unmap_dma;
737 	}
738 
739 	/* Update ep0 state */
740 	if (ep->ep_num == 0)
741 		udc->ep0_state = DATA_STATE_XMIT;
742 
743 	/* irq handler advances the queue */
744 	list_add_tail(&req->queue, &ep->queue);
745 	spin_unlock_irqrestore(&udc->lock, flags);
746 
747 	return 0;
748 
749 err_unmap_dma:
750 	usb_gadget_unmap_request(&udc->gadget, _req, ep_dir(ep));
751 
752 	return retval;
753 }
754 
755 static void mv_prime_ep(struct mv_ep *ep, struct mv_req *req)
756 {
757 	struct mv_dqh *dqh = ep->dqh;
758 	u32 bit_pos;
759 
760 	/* Write dQH next pointer and terminate bit to 0 */
761 	dqh->next_dtd_ptr = req->head->td_dma
762 		& EP_QUEUE_HEAD_NEXT_POINTER_MASK;
763 
764 	/* clear active and halt bit, in case set from a previous error */
765 	dqh->size_ioc_int_sts &= ~(DTD_STATUS_ACTIVE | DTD_STATUS_HALTED);
766 
767 	/* Ensure that updates to the QH will occure before priming. */
768 	wmb();
769 
770 	bit_pos = 1 << (((ep_dir(ep) == EP_DIR_OUT) ? 0 : 16) + ep->ep_num);
771 
772 	/* Prime the Endpoint */
773 	writel(bit_pos, &ep->udc->op_regs->epprime);
774 }
775 
776 /* dequeues (cancels, unlinks) an I/O request from an endpoint */
777 static int mv_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req)
778 {
779 	struct mv_ep *ep = container_of(_ep, struct mv_ep, ep);
780 	struct mv_req *req;
781 	struct mv_udc *udc = ep->udc;
782 	unsigned long flags;
783 	int stopped, ret = 0;
784 	u32 epctrlx;
785 
786 	if (!_ep || !_req)
787 		return -EINVAL;
788 
789 	spin_lock_irqsave(&ep->udc->lock, flags);
790 	stopped = ep->stopped;
791 
792 	/* Stop the ep before we deal with the queue */
793 	ep->stopped = 1;
794 	epctrlx = readl(&udc->op_regs->epctrlx[ep->ep_num]);
795 	if (ep_dir(ep) == EP_DIR_IN)
796 		epctrlx &= ~EPCTRL_TX_ENABLE;
797 	else
798 		epctrlx &= ~EPCTRL_RX_ENABLE;
799 	writel(epctrlx, &udc->op_regs->epctrlx[ep->ep_num]);
800 
801 	/* make sure it's actually queued on this endpoint */
802 	list_for_each_entry(req, &ep->queue, queue) {
803 		if (&req->req == _req)
804 			break;
805 	}
806 	if (&req->req != _req) {
807 		ret = -EINVAL;
808 		goto out;
809 	}
810 
811 	/* The request is in progress, or completed but not dequeued */
812 	if (ep->queue.next == &req->queue) {
813 		_req->status = -ECONNRESET;
814 		mv_ep_fifo_flush(_ep);	/* flush current transfer */
815 
816 		/* The request isn't the last request in this ep queue */
817 		if (req->queue.next != &ep->queue) {
818 			struct mv_req *next_req;
819 
820 			next_req = list_entry(req->queue.next,
821 				struct mv_req, queue);
822 
823 			/* Point the QH to the first TD of next request */
824 			mv_prime_ep(ep, next_req);
825 		} else {
826 			struct mv_dqh *qh;
827 
828 			qh = ep->dqh;
829 			qh->next_dtd_ptr = 1;
830 			qh->size_ioc_int_sts = 0;
831 		}
832 
833 		/* The request hasn't been processed, patch up the TD chain */
834 	} else {
835 		struct mv_req *prev_req;
836 
837 		prev_req = list_entry(req->queue.prev, struct mv_req, queue);
838 		writel(readl(&req->tail->dtd_next),
839 				&prev_req->tail->dtd_next);
840 
841 	}
842 
843 	done(ep, req, -ECONNRESET);
844 
845 	/* Enable EP */
846 out:
847 	epctrlx = readl(&udc->op_regs->epctrlx[ep->ep_num]);
848 	if (ep_dir(ep) == EP_DIR_IN)
849 		epctrlx |= EPCTRL_TX_ENABLE;
850 	else
851 		epctrlx |= EPCTRL_RX_ENABLE;
852 	writel(epctrlx, &udc->op_regs->epctrlx[ep->ep_num]);
853 	ep->stopped = stopped;
854 
855 	spin_unlock_irqrestore(&ep->udc->lock, flags);
856 	return ret;
857 }
858 
859 static void ep_set_stall(struct mv_udc *udc, u8 ep_num, u8 direction, int stall)
860 {
861 	u32 epctrlx;
862 
863 	epctrlx = readl(&udc->op_regs->epctrlx[ep_num]);
864 
865 	if (stall) {
866 		if (direction == EP_DIR_IN)
867 			epctrlx |= EPCTRL_TX_EP_STALL;
868 		else
869 			epctrlx |= EPCTRL_RX_EP_STALL;
870 	} else {
871 		if (direction == EP_DIR_IN) {
872 			epctrlx &= ~EPCTRL_TX_EP_STALL;
873 			epctrlx |= EPCTRL_TX_DATA_TOGGLE_RST;
874 		} else {
875 			epctrlx &= ~EPCTRL_RX_EP_STALL;
876 			epctrlx |= EPCTRL_RX_DATA_TOGGLE_RST;
877 		}
878 	}
879 	writel(epctrlx, &udc->op_regs->epctrlx[ep_num]);
880 }
881 
882 static int ep_is_stall(struct mv_udc *udc, u8 ep_num, u8 direction)
883 {
884 	u32 epctrlx;
885 
886 	epctrlx = readl(&udc->op_regs->epctrlx[ep_num]);
887 
888 	if (direction == EP_DIR_OUT)
889 		return (epctrlx & EPCTRL_RX_EP_STALL) ? 1 : 0;
890 	else
891 		return (epctrlx & EPCTRL_TX_EP_STALL) ? 1 : 0;
892 }
893 
894 static int mv_ep_set_halt_wedge(struct usb_ep *_ep, int halt, int wedge)
895 {
896 	struct mv_ep *ep;
897 	unsigned long flags = 0;
898 	int status = 0;
899 	struct mv_udc *udc;
900 
901 	ep = container_of(_ep, struct mv_ep, ep);
902 	udc = ep->udc;
903 	if (!_ep || !ep->ep.desc) {
904 		status = -EINVAL;
905 		goto out;
906 	}
907 
908 	if (ep->ep.desc->bmAttributes == USB_ENDPOINT_XFER_ISOC) {
909 		status = -EOPNOTSUPP;
910 		goto out;
911 	}
912 
913 	/*
914 	 * Attempt to halt IN ep will fail if any transfer requests
915 	 * are still queue
916 	 */
917 	if (halt && (ep_dir(ep) == EP_DIR_IN) && !list_empty(&ep->queue)) {
918 		status = -EAGAIN;
919 		goto out;
920 	}
921 
922 	spin_lock_irqsave(&ep->udc->lock, flags);
923 	ep_set_stall(udc, ep->ep_num, ep_dir(ep), halt);
924 	if (halt && wedge)
925 		ep->wedge = 1;
926 	else if (!halt)
927 		ep->wedge = 0;
928 	spin_unlock_irqrestore(&ep->udc->lock, flags);
929 
930 	if (ep->ep_num == 0) {
931 		udc->ep0_state = WAIT_FOR_SETUP;
932 		udc->ep0_dir = EP_DIR_OUT;
933 	}
934 out:
935 	return status;
936 }
937 
938 static int mv_ep_set_halt(struct usb_ep *_ep, int halt)
939 {
940 	return mv_ep_set_halt_wedge(_ep, halt, 0);
941 }
942 
943 static int mv_ep_set_wedge(struct usb_ep *_ep)
944 {
945 	return mv_ep_set_halt_wedge(_ep, 1, 1);
946 }
947 
948 static const struct usb_ep_ops mv_ep_ops = {
949 	.enable		= mv_ep_enable,
950 	.disable	= mv_ep_disable,
951 
952 	.alloc_request	= mv_alloc_request,
953 	.free_request	= mv_free_request,
954 
955 	.queue		= mv_ep_queue,
956 	.dequeue	= mv_ep_dequeue,
957 
958 	.set_wedge	= mv_ep_set_wedge,
959 	.set_halt	= mv_ep_set_halt,
960 	.fifo_flush	= mv_ep_fifo_flush,	/* flush fifo */
961 };
962 
963 static void udc_clock_enable(struct mv_udc *udc)
964 {
965 	clk_prepare_enable(udc->clk);
966 }
967 
968 static void udc_clock_disable(struct mv_udc *udc)
969 {
970 	clk_disable_unprepare(udc->clk);
971 }
972 
973 static void udc_stop(struct mv_udc *udc)
974 {
975 	u32 tmp;
976 
977 	/* Disable interrupts */
978 	tmp = readl(&udc->op_regs->usbintr);
979 	tmp &= ~(USBINTR_INT_EN | USBINTR_ERR_INT_EN |
980 		USBINTR_PORT_CHANGE_DETECT_EN | USBINTR_RESET_EN);
981 	writel(tmp, &udc->op_regs->usbintr);
982 
983 	udc->stopped = 1;
984 
985 	/* Reset the Run the bit in the command register to stop VUSB */
986 	tmp = readl(&udc->op_regs->usbcmd);
987 	tmp &= ~USBCMD_RUN_STOP;
988 	writel(tmp, &udc->op_regs->usbcmd);
989 }
990 
991 static void udc_start(struct mv_udc *udc)
992 {
993 	u32 usbintr;
994 
995 	usbintr = USBINTR_INT_EN | USBINTR_ERR_INT_EN
996 		| USBINTR_PORT_CHANGE_DETECT_EN
997 		| USBINTR_RESET_EN | USBINTR_DEVICE_SUSPEND;
998 	/* Enable interrupts */
999 	writel(usbintr, &udc->op_regs->usbintr);
1000 
1001 	udc->stopped = 0;
1002 
1003 	/* Set the Run bit in the command register */
1004 	writel(USBCMD_RUN_STOP, &udc->op_regs->usbcmd);
1005 }
1006 
1007 static int udc_reset(struct mv_udc *udc)
1008 {
1009 	unsigned int loops;
1010 	u32 tmp, portsc;
1011 
1012 	/* Stop the controller */
1013 	tmp = readl(&udc->op_regs->usbcmd);
1014 	tmp &= ~USBCMD_RUN_STOP;
1015 	writel(tmp, &udc->op_regs->usbcmd);
1016 
1017 	/* Reset the controller to get default values */
1018 	writel(USBCMD_CTRL_RESET, &udc->op_regs->usbcmd);
1019 
1020 	/* wait for reset to complete */
1021 	loops = LOOPS(RESET_TIMEOUT);
1022 	while (readl(&udc->op_regs->usbcmd) & USBCMD_CTRL_RESET) {
1023 		if (loops == 0) {
1024 			dev_err(&udc->dev->dev,
1025 				"Wait for RESET completed TIMEOUT\n");
1026 			return -ETIMEDOUT;
1027 		}
1028 		loops--;
1029 		udelay(LOOPS_USEC);
1030 	}
1031 
1032 	/* set controller to device mode */
1033 	tmp = readl(&udc->op_regs->usbmode);
1034 	tmp |= USBMODE_CTRL_MODE_DEVICE;
1035 
1036 	/* turn setup lockout off, require setup tripwire in usbcmd */
1037 	tmp |= USBMODE_SETUP_LOCK_OFF;
1038 
1039 	writel(tmp, &udc->op_regs->usbmode);
1040 
1041 	writel(0x0, &udc->op_regs->epsetupstat);
1042 
1043 	/* Configure the Endpoint List Address */
1044 	writel(udc->ep_dqh_dma & USB_EP_LIST_ADDRESS_MASK,
1045 		&udc->op_regs->eplistaddr);
1046 
1047 	portsc = readl(&udc->op_regs->portsc[0]);
1048 	if (readl(&udc->cap_regs->hcsparams) & HCSPARAMS_PPC)
1049 		portsc &= (~PORTSCX_W1C_BITS | ~PORTSCX_PORT_POWER);
1050 
1051 	if (udc->force_fs)
1052 		portsc |= PORTSCX_FORCE_FULL_SPEED_CONNECT;
1053 	else
1054 		portsc &= (~PORTSCX_FORCE_FULL_SPEED_CONNECT);
1055 
1056 	writel(portsc, &udc->op_regs->portsc[0]);
1057 
1058 	tmp = readl(&udc->op_regs->epctrlx[0]);
1059 	tmp &= ~(EPCTRL_TX_EP_STALL | EPCTRL_RX_EP_STALL);
1060 	writel(tmp, &udc->op_regs->epctrlx[0]);
1061 
1062 	return 0;
1063 }
1064 
1065 static int mv_udc_enable_internal(struct mv_udc *udc)
1066 {
1067 	int retval;
1068 
1069 	if (udc->active)
1070 		return 0;
1071 
1072 	dev_dbg(&udc->dev->dev, "enable udc\n");
1073 	udc_clock_enable(udc);
1074 	if (udc->pdata->phy_init) {
1075 		retval = udc->pdata->phy_init(udc->phy_regs);
1076 		if (retval) {
1077 			dev_err(&udc->dev->dev,
1078 				"init phy error %d\n", retval);
1079 			udc_clock_disable(udc);
1080 			return retval;
1081 		}
1082 	}
1083 	udc->active = 1;
1084 
1085 	return 0;
1086 }
1087 
1088 static int mv_udc_enable(struct mv_udc *udc)
1089 {
1090 	if (udc->clock_gating)
1091 		return mv_udc_enable_internal(udc);
1092 
1093 	return 0;
1094 }
1095 
1096 static void mv_udc_disable_internal(struct mv_udc *udc)
1097 {
1098 	if (udc->active) {
1099 		dev_dbg(&udc->dev->dev, "disable udc\n");
1100 		if (udc->pdata->phy_deinit)
1101 			udc->pdata->phy_deinit(udc->phy_regs);
1102 		udc_clock_disable(udc);
1103 		udc->active = 0;
1104 	}
1105 }
1106 
1107 static void mv_udc_disable(struct mv_udc *udc)
1108 {
1109 	if (udc->clock_gating)
1110 		mv_udc_disable_internal(udc);
1111 }
1112 
1113 static int mv_udc_get_frame(struct usb_gadget *gadget)
1114 {
1115 	struct mv_udc *udc;
1116 	u16	retval;
1117 
1118 	if (!gadget)
1119 		return -ENODEV;
1120 
1121 	udc = container_of(gadget, struct mv_udc, gadget);
1122 
1123 	retval = readl(&udc->op_regs->frindex) & USB_FRINDEX_MASKS;
1124 
1125 	return retval;
1126 }
1127 
1128 /* Tries to wake up the host connected to this gadget */
1129 static int mv_udc_wakeup(struct usb_gadget *gadget)
1130 {
1131 	struct mv_udc *udc = container_of(gadget, struct mv_udc, gadget);
1132 	u32 portsc;
1133 
1134 	/* Remote wakeup feature not enabled by host */
1135 	if (!udc->remote_wakeup)
1136 		return -ENOTSUPP;
1137 
1138 	portsc = readl(&udc->op_regs->portsc);
1139 	/* not suspended? */
1140 	if (!(portsc & PORTSCX_PORT_SUSPEND))
1141 		return 0;
1142 	/* trigger force resume */
1143 	portsc |= PORTSCX_PORT_FORCE_RESUME;
1144 	writel(portsc, &udc->op_regs->portsc[0]);
1145 	return 0;
1146 }
1147 
1148 static int mv_udc_vbus_session(struct usb_gadget *gadget, int is_active)
1149 {
1150 	struct mv_udc *udc;
1151 	unsigned long flags;
1152 	int retval = 0;
1153 
1154 	udc = container_of(gadget, struct mv_udc, gadget);
1155 	spin_lock_irqsave(&udc->lock, flags);
1156 
1157 	udc->vbus_active = (is_active != 0);
1158 
1159 	dev_dbg(&udc->dev->dev, "%s: softconnect %d, vbus_active %d\n",
1160 		__func__, udc->softconnect, udc->vbus_active);
1161 
1162 	if (udc->driver && udc->softconnect && udc->vbus_active) {
1163 		retval = mv_udc_enable(udc);
1164 		if (retval == 0) {
1165 			/* Clock is disabled, need re-init registers */
1166 			udc_reset(udc);
1167 			ep0_reset(udc);
1168 			udc_start(udc);
1169 		}
1170 	} else if (udc->driver && udc->softconnect) {
1171 		if (!udc->active)
1172 			goto out;
1173 
1174 		/* stop all the transfer in queue*/
1175 		stop_activity(udc, udc->driver);
1176 		udc_stop(udc);
1177 		mv_udc_disable(udc);
1178 	}
1179 
1180 out:
1181 	spin_unlock_irqrestore(&udc->lock, flags);
1182 	return retval;
1183 }
1184 
1185 static int mv_udc_pullup(struct usb_gadget *gadget, int is_on)
1186 {
1187 	struct mv_udc *udc;
1188 	unsigned long flags;
1189 	int retval = 0;
1190 
1191 	udc = container_of(gadget, struct mv_udc, gadget);
1192 	spin_lock_irqsave(&udc->lock, flags);
1193 
1194 	udc->softconnect = (is_on != 0);
1195 
1196 	dev_dbg(&udc->dev->dev, "%s: softconnect %d, vbus_active %d\n",
1197 			__func__, udc->softconnect, udc->vbus_active);
1198 
1199 	if (udc->driver && udc->softconnect && udc->vbus_active) {
1200 		retval = mv_udc_enable(udc);
1201 		if (retval == 0) {
1202 			/* Clock is disabled, need re-init registers */
1203 			udc_reset(udc);
1204 			ep0_reset(udc);
1205 			udc_start(udc);
1206 		}
1207 	} else if (udc->driver && udc->vbus_active) {
1208 		/* stop all the transfer in queue*/
1209 		stop_activity(udc, udc->driver);
1210 		udc_stop(udc);
1211 		mv_udc_disable(udc);
1212 	}
1213 
1214 	spin_unlock_irqrestore(&udc->lock, flags);
1215 	return retval;
1216 }
1217 
1218 static int mv_udc_start(struct usb_gadget *, struct usb_gadget_driver *);
1219 static int mv_udc_stop(struct usb_gadget *);
1220 /* device controller usb_gadget_ops structure */
1221 static const struct usb_gadget_ops mv_ops = {
1222 
1223 	/* returns the current frame number */
1224 	.get_frame	= mv_udc_get_frame,
1225 
1226 	/* tries to wake up the host connected to this gadget */
1227 	.wakeup		= mv_udc_wakeup,
1228 
1229 	/* notify controller that VBUS is powered or not */
1230 	.vbus_session	= mv_udc_vbus_session,
1231 
1232 	/* D+ pullup, software-controlled connect/disconnect to USB host */
1233 	.pullup		= mv_udc_pullup,
1234 	.udc_start	= mv_udc_start,
1235 	.udc_stop	= mv_udc_stop,
1236 };
1237 
1238 static int eps_init(struct mv_udc *udc)
1239 {
1240 	struct mv_ep	*ep;
1241 	char name[14];
1242 	int i;
1243 
1244 	/* initialize ep0 */
1245 	ep = &udc->eps[0];
1246 	ep->udc = udc;
1247 	strncpy(ep->name, "ep0", sizeof(ep->name));
1248 	ep->ep.name = ep->name;
1249 	ep->ep.ops = &mv_ep_ops;
1250 	ep->wedge = 0;
1251 	ep->stopped = 0;
1252 	usb_ep_set_maxpacket_limit(&ep->ep, EP0_MAX_PKT_SIZE);
1253 	ep->ep.caps.type_control = true;
1254 	ep->ep.caps.dir_in = true;
1255 	ep->ep.caps.dir_out = true;
1256 	ep->ep_num = 0;
1257 	ep->ep.desc = &mv_ep0_desc;
1258 	INIT_LIST_HEAD(&ep->queue);
1259 
1260 	ep->ep_type = USB_ENDPOINT_XFER_CONTROL;
1261 
1262 	/* initialize other endpoints */
1263 	for (i = 2; i < udc->max_eps * 2; i++) {
1264 		ep = &udc->eps[i];
1265 		if (i % 2) {
1266 			snprintf(name, sizeof(name), "ep%din", i / 2);
1267 			ep->direction = EP_DIR_IN;
1268 			ep->ep.caps.dir_in = true;
1269 		} else {
1270 			snprintf(name, sizeof(name), "ep%dout", i / 2);
1271 			ep->direction = EP_DIR_OUT;
1272 			ep->ep.caps.dir_out = true;
1273 		}
1274 		ep->udc = udc;
1275 		strncpy(ep->name, name, sizeof(ep->name));
1276 		ep->ep.name = ep->name;
1277 
1278 		ep->ep.caps.type_iso = true;
1279 		ep->ep.caps.type_bulk = true;
1280 		ep->ep.caps.type_int = true;
1281 
1282 		ep->ep.ops = &mv_ep_ops;
1283 		ep->stopped = 0;
1284 		usb_ep_set_maxpacket_limit(&ep->ep, (unsigned short) ~0);
1285 		ep->ep_num = i / 2;
1286 
1287 		INIT_LIST_HEAD(&ep->queue);
1288 		list_add_tail(&ep->ep.ep_list, &udc->gadget.ep_list);
1289 
1290 		ep->dqh = &udc->ep_dqh[i];
1291 	}
1292 
1293 	return 0;
1294 }
1295 
1296 /* delete all endpoint requests, called with spinlock held */
1297 static void nuke(struct mv_ep *ep, int status)
1298 {
1299 	/* called with spinlock held */
1300 	ep->stopped = 1;
1301 
1302 	/* endpoint fifo flush */
1303 	mv_ep_fifo_flush(&ep->ep);
1304 
1305 	while (!list_empty(&ep->queue)) {
1306 		struct mv_req *req = NULL;
1307 		req = list_entry(ep->queue.next, struct mv_req, queue);
1308 		done(ep, req, status);
1309 	}
1310 }
1311 
1312 static void gadget_reset(struct mv_udc *udc, struct usb_gadget_driver *driver)
1313 {
1314 	struct mv_ep	*ep;
1315 
1316 	nuke(&udc->eps[0], -ESHUTDOWN);
1317 
1318 	list_for_each_entry(ep, &udc->gadget.ep_list, ep.ep_list) {
1319 		nuke(ep, -ESHUTDOWN);
1320 	}
1321 
1322 	/* report reset; the driver is already quiesced */
1323 	if (driver) {
1324 		spin_unlock(&udc->lock);
1325 		usb_gadget_udc_reset(&udc->gadget, driver);
1326 		spin_lock(&udc->lock);
1327 	}
1328 }
1329 /* stop all USB activities */
1330 static void stop_activity(struct mv_udc *udc, struct usb_gadget_driver *driver)
1331 {
1332 	struct mv_ep	*ep;
1333 
1334 	nuke(&udc->eps[0], -ESHUTDOWN);
1335 
1336 	list_for_each_entry(ep, &udc->gadget.ep_list, ep.ep_list) {
1337 		nuke(ep, -ESHUTDOWN);
1338 	}
1339 
1340 	/* report disconnect; the driver is already quiesced */
1341 	if (driver) {
1342 		spin_unlock(&udc->lock);
1343 		driver->disconnect(&udc->gadget);
1344 		spin_lock(&udc->lock);
1345 	}
1346 }
1347 
1348 static int mv_udc_start(struct usb_gadget *gadget,
1349 		struct usb_gadget_driver *driver)
1350 {
1351 	struct mv_udc *udc;
1352 	int retval = 0;
1353 	unsigned long flags;
1354 
1355 	udc = container_of(gadget, struct mv_udc, gadget);
1356 
1357 	if (udc->driver)
1358 		return -EBUSY;
1359 
1360 	spin_lock_irqsave(&udc->lock, flags);
1361 
1362 	/* hook up the driver ... */
1363 	driver->driver.bus = NULL;
1364 	udc->driver = driver;
1365 
1366 	udc->usb_state = USB_STATE_ATTACHED;
1367 	udc->ep0_state = WAIT_FOR_SETUP;
1368 	udc->ep0_dir = EP_DIR_OUT;
1369 
1370 	spin_unlock_irqrestore(&udc->lock, flags);
1371 
1372 	if (udc->transceiver) {
1373 		retval = otg_set_peripheral(udc->transceiver->otg,
1374 					&udc->gadget);
1375 		if (retval) {
1376 			dev_err(&udc->dev->dev,
1377 				"unable to register peripheral to otg\n");
1378 			udc->driver = NULL;
1379 			return retval;
1380 		}
1381 	}
1382 
1383 	/* When boot with cable attached, there will be no vbus irq occurred */
1384 	if (udc->qwork)
1385 		queue_work(udc->qwork, &udc->vbus_work);
1386 
1387 	return 0;
1388 }
1389 
1390 static int mv_udc_stop(struct usb_gadget *gadget)
1391 {
1392 	struct mv_udc *udc;
1393 	unsigned long flags;
1394 
1395 	udc = container_of(gadget, struct mv_udc, gadget);
1396 
1397 	spin_lock_irqsave(&udc->lock, flags);
1398 
1399 	mv_udc_enable(udc);
1400 	udc_stop(udc);
1401 
1402 	/* stop all usb activities */
1403 	udc->gadget.speed = USB_SPEED_UNKNOWN;
1404 	stop_activity(udc, NULL);
1405 	mv_udc_disable(udc);
1406 
1407 	spin_unlock_irqrestore(&udc->lock, flags);
1408 
1409 	/* unbind gadget driver */
1410 	udc->driver = NULL;
1411 
1412 	return 0;
1413 }
1414 
1415 static void mv_set_ptc(struct mv_udc *udc, u32 mode)
1416 {
1417 	u32 portsc;
1418 
1419 	portsc = readl(&udc->op_regs->portsc[0]);
1420 	portsc |= mode << 16;
1421 	writel(portsc, &udc->op_regs->portsc[0]);
1422 }
1423 
1424 static void prime_status_complete(struct usb_ep *ep, struct usb_request *_req)
1425 {
1426 	struct mv_ep *mvep = container_of(ep, struct mv_ep, ep);
1427 	struct mv_req *req = container_of(_req, struct mv_req, req);
1428 	struct mv_udc *udc;
1429 	unsigned long flags;
1430 
1431 	udc = mvep->udc;
1432 
1433 	dev_info(&udc->dev->dev, "switch to test mode %d\n", req->test_mode);
1434 
1435 	spin_lock_irqsave(&udc->lock, flags);
1436 	if (req->test_mode) {
1437 		mv_set_ptc(udc, req->test_mode);
1438 		req->test_mode = 0;
1439 	}
1440 	spin_unlock_irqrestore(&udc->lock, flags);
1441 }
1442 
1443 static int
1444 udc_prime_status(struct mv_udc *udc, u8 direction, u16 status, bool empty)
1445 {
1446 	int retval = 0;
1447 	struct mv_req *req;
1448 	struct mv_ep *ep;
1449 
1450 	ep = &udc->eps[0];
1451 	udc->ep0_dir = direction;
1452 	udc->ep0_state = WAIT_FOR_OUT_STATUS;
1453 
1454 	req = udc->status_req;
1455 
1456 	/* fill in the reqest structure */
1457 	if (empty == false) {
1458 		*((u16 *) req->req.buf) = cpu_to_le16(status);
1459 		req->req.length = 2;
1460 	} else
1461 		req->req.length = 0;
1462 
1463 	req->ep = ep;
1464 	req->req.status = -EINPROGRESS;
1465 	req->req.actual = 0;
1466 	if (udc->test_mode) {
1467 		req->req.complete = prime_status_complete;
1468 		req->test_mode = udc->test_mode;
1469 		udc->test_mode = 0;
1470 	} else
1471 		req->req.complete = NULL;
1472 	req->dtd_count = 0;
1473 
1474 	if (req->req.dma == DMA_ADDR_INVALID) {
1475 		req->req.dma = dma_map_single(ep->udc->gadget.dev.parent,
1476 				req->req.buf, req->req.length,
1477 				ep_dir(ep) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1478 		req->mapped = 1;
1479 	}
1480 
1481 	/* prime the data phase */
1482 	if (!req_to_dtd(req)) {
1483 		retval = queue_dtd(ep, req);
1484 		if (retval) {
1485 			dev_err(&udc->dev->dev,
1486 				"Failed to queue dtd when prime status\n");
1487 			goto out;
1488 		}
1489 	} else{	/* no mem */
1490 		retval = -ENOMEM;
1491 		dev_err(&udc->dev->dev,
1492 			"Failed to dma_pool_alloc when prime status\n");
1493 		goto out;
1494 	}
1495 
1496 	list_add_tail(&req->queue, &ep->queue);
1497 
1498 	return 0;
1499 out:
1500 	usb_gadget_unmap_request(&udc->gadget, &req->req, ep_dir(ep));
1501 
1502 	return retval;
1503 }
1504 
1505 static void mv_udc_testmode(struct mv_udc *udc, u16 index)
1506 {
1507 	if (index <= TEST_FORCE_EN) {
1508 		udc->test_mode = index;
1509 		if (udc_prime_status(udc, EP_DIR_IN, 0, true))
1510 			ep0_stall(udc);
1511 	} else
1512 		dev_err(&udc->dev->dev,
1513 			"This test mode(%d) is not supported\n", index);
1514 }
1515 
1516 static void ch9setaddress(struct mv_udc *udc, struct usb_ctrlrequest *setup)
1517 {
1518 	udc->dev_addr = (u8)setup->wValue;
1519 
1520 	/* update usb state */
1521 	udc->usb_state = USB_STATE_ADDRESS;
1522 
1523 	if (udc_prime_status(udc, EP_DIR_IN, 0, true))
1524 		ep0_stall(udc);
1525 }
1526 
1527 static void ch9getstatus(struct mv_udc *udc, u8 ep_num,
1528 	struct usb_ctrlrequest *setup)
1529 {
1530 	u16 status = 0;
1531 	int retval;
1532 
1533 	if ((setup->bRequestType & (USB_DIR_IN | USB_TYPE_MASK))
1534 		!= (USB_DIR_IN | USB_TYPE_STANDARD))
1535 		return;
1536 
1537 	if ((setup->bRequestType & USB_RECIP_MASK) == USB_RECIP_DEVICE) {
1538 		status = 1 << USB_DEVICE_SELF_POWERED;
1539 		status |= udc->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP;
1540 	} else if ((setup->bRequestType & USB_RECIP_MASK)
1541 			== USB_RECIP_INTERFACE) {
1542 		/* get interface status */
1543 		status = 0;
1544 	} else if ((setup->bRequestType & USB_RECIP_MASK)
1545 			== USB_RECIP_ENDPOINT) {
1546 		u8 ep_num, direction;
1547 
1548 		ep_num = setup->wIndex & USB_ENDPOINT_NUMBER_MASK;
1549 		direction = (setup->wIndex & USB_ENDPOINT_DIR_MASK)
1550 				? EP_DIR_IN : EP_DIR_OUT;
1551 		status = ep_is_stall(udc, ep_num, direction)
1552 				<< USB_ENDPOINT_HALT;
1553 	}
1554 
1555 	retval = udc_prime_status(udc, EP_DIR_IN, status, false);
1556 	if (retval)
1557 		ep0_stall(udc);
1558 	else
1559 		udc->ep0_state = DATA_STATE_XMIT;
1560 }
1561 
1562 static void ch9clearfeature(struct mv_udc *udc, struct usb_ctrlrequest *setup)
1563 {
1564 	u8 ep_num;
1565 	u8 direction;
1566 	struct mv_ep *ep;
1567 
1568 	if ((setup->bRequestType & (USB_TYPE_MASK | USB_RECIP_MASK))
1569 		== ((USB_TYPE_STANDARD | USB_RECIP_DEVICE))) {
1570 		switch (setup->wValue) {
1571 		case USB_DEVICE_REMOTE_WAKEUP:
1572 			udc->remote_wakeup = 0;
1573 			break;
1574 		default:
1575 			goto out;
1576 		}
1577 	} else if ((setup->bRequestType & (USB_TYPE_MASK | USB_RECIP_MASK))
1578 		== ((USB_TYPE_STANDARD | USB_RECIP_ENDPOINT))) {
1579 		switch (setup->wValue) {
1580 		case USB_ENDPOINT_HALT:
1581 			ep_num = setup->wIndex & USB_ENDPOINT_NUMBER_MASK;
1582 			direction = (setup->wIndex & USB_ENDPOINT_DIR_MASK)
1583 				? EP_DIR_IN : EP_DIR_OUT;
1584 			if (setup->wValue != 0 || setup->wLength != 0
1585 				|| ep_num > udc->max_eps)
1586 				goto out;
1587 			ep = &udc->eps[ep_num * 2 + direction];
1588 			if (ep->wedge == 1)
1589 				break;
1590 			spin_unlock(&udc->lock);
1591 			ep_set_stall(udc, ep_num, direction, 0);
1592 			spin_lock(&udc->lock);
1593 			break;
1594 		default:
1595 			goto out;
1596 		}
1597 	} else
1598 		goto out;
1599 
1600 	if (udc_prime_status(udc, EP_DIR_IN, 0, true))
1601 		ep0_stall(udc);
1602 out:
1603 	return;
1604 }
1605 
1606 static void ch9setfeature(struct mv_udc *udc, struct usb_ctrlrequest *setup)
1607 {
1608 	u8 ep_num;
1609 	u8 direction;
1610 
1611 	if ((setup->bRequestType & (USB_TYPE_MASK | USB_RECIP_MASK))
1612 		== ((USB_TYPE_STANDARD | USB_RECIP_DEVICE))) {
1613 		switch (setup->wValue) {
1614 		case USB_DEVICE_REMOTE_WAKEUP:
1615 			udc->remote_wakeup = 1;
1616 			break;
1617 		case USB_DEVICE_TEST_MODE:
1618 			if (setup->wIndex & 0xFF
1619 				||  udc->gadget.speed != USB_SPEED_HIGH)
1620 				ep0_stall(udc);
1621 
1622 			if (udc->usb_state != USB_STATE_CONFIGURED
1623 				&& udc->usb_state != USB_STATE_ADDRESS
1624 				&& udc->usb_state != USB_STATE_DEFAULT)
1625 				ep0_stall(udc);
1626 
1627 			mv_udc_testmode(udc, (setup->wIndex >> 8));
1628 			goto out;
1629 		default:
1630 			goto out;
1631 		}
1632 	} else if ((setup->bRequestType & (USB_TYPE_MASK | USB_RECIP_MASK))
1633 		== ((USB_TYPE_STANDARD | USB_RECIP_ENDPOINT))) {
1634 		switch (setup->wValue) {
1635 		case USB_ENDPOINT_HALT:
1636 			ep_num = setup->wIndex & USB_ENDPOINT_NUMBER_MASK;
1637 			direction = (setup->wIndex & USB_ENDPOINT_DIR_MASK)
1638 				? EP_DIR_IN : EP_DIR_OUT;
1639 			if (setup->wValue != 0 || setup->wLength != 0
1640 				|| ep_num > udc->max_eps)
1641 				goto out;
1642 			spin_unlock(&udc->lock);
1643 			ep_set_stall(udc, ep_num, direction, 1);
1644 			spin_lock(&udc->lock);
1645 			break;
1646 		default:
1647 			goto out;
1648 		}
1649 	} else
1650 		goto out;
1651 
1652 	if (udc_prime_status(udc, EP_DIR_IN, 0, true))
1653 		ep0_stall(udc);
1654 out:
1655 	return;
1656 }
1657 
1658 static void handle_setup_packet(struct mv_udc *udc, u8 ep_num,
1659 	struct usb_ctrlrequest *setup)
1660 	__releases(&ep->udc->lock)
1661 	__acquires(&ep->udc->lock)
1662 {
1663 	bool delegate = false;
1664 
1665 	nuke(&udc->eps[ep_num * 2 + EP_DIR_OUT], -ESHUTDOWN);
1666 
1667 	dev_dbg(&udc->dev->dev, "SETUP %02x.%02x v%04x i%04x l%04x\n",
1668 			setup->bRequestType, setup->bRequest,
1669 			setup->wValue, setup->wIndex, setup->wLength);
1670 	/* We process some standard setup requests here */
1671 	if ((setup->bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
1672 		switch (setup->bRequest) {
1673 		case USB_REQ_GET_STATUS:
1674 			ch9getstatus(udc, ep_num, setup);
1675 			break;
1676 
1677 		case USB_REQ_SET_ADDRESS:
1678 			ch9setaddress(udc, setup);
1679 			break;
1680 
1681 		case USB_REQ_CLEAR_FEATURE:
1682 			ch9clearfeature(udc, setup);
1683 			break;
1684 
1685 		case USB_REQ_SET_FEATURE:
1686 			ch9setfeature(udc, setup);
1687 			break;
1688 
1689 		default:
1690 			delegate = true;
1691 		}
1692 	} else
1693 		delegate = true;
1694 
1695 	/* delegate USB standard requests to the gadget driver */
1696 	if (delegate == true) {
1697 		/* USB requests handled by gadget */
1698 		if (setup->wLength) {
1699 			/* DATA phase from gadget, STATUS phase from udc */
1700 			udc->ep0_dir = (setup->bRequestType & USB_DIR_IN)
1701 					?  EP_DIR_IN : EP_DIR_OUT;
1702 			spin_unlock(&udc->lock);
1703 			if (udc->driver->setup(&udc->gadget,
1704 				&udc->local_setup_buff) < 0)
1705 				ep0_stall(udc);
1706 			spin_lock(&udc->lock);
1707 			udc->ep0_state = (setup->bRequestType & USB_DIR_IN)
1708 					?  DATA_STATE_XMIT : DATA_STATE_RECV;
1709 		} else {
1710 			/* no DATA phase, IN STATUS phase from gadget */
1711 			udc->ep0_dir = EP_DIR_IN;
1712 			spin_unlock(&udc->lock);
1713 			if (udc->driver->setup(&udc->gadget,
1714 				&udc->local_setup_buff) < 0)
1715 				ep0_stall(udc);
1716 			spin_lock(&udc->lock);
1717 			udc->ep0_state = WAIT_FOR_OUT_STATUS;
1718 		}
1719 	}
1720 }
1721 
1722 /* complete DATA or STATUS phase of ep0 prime status phase if needed */
1723 static void ep0_req_complete(struct mv_udc *udc,
1724 	struct mv_ep *ep0, struct mv_req *req)
1725 {
1726 	u32 new_addr;
1727 
1728 	if (udc->usb_state == USB_STATE_ADDRESS) {
1729 		/* set the new address */
1730 		new_addr = (u32)udc->dev_addr;
1731 		writel(new_addr << USB_DEVICE_ADDRESS_BIT_SHIFT,
1732 			&udc->op_regs->deviceaddr);
1733 	}
1734 
1735 	done(ep0, req, 0);
1736 
1737 	switch (udc->ep0_state) {
1738 	case DATA_STATE_XMIT:
1739 		/* receive status phase */
1740 		if (udc_prime_status(udc, EP_DIR_OUT, 0, true))
1741 			ep0_stall(udc);
1742 		break;
1743 	case DATA_STATE_RECV:
1744 		/* send status phase */
1745 		if (udc_prime_status(udc, EP_DIR_IN, 0 , true))
1746 			ep0_stall(udc);
1747 		break;
1748 	case WAIT_FOR_OUT_STATUS:
1749 		udc->ep0_state = WAIT_FOR_SETUP;
1750 		break;
1751 	case WAIT_FOR_SETUP:
1752 		dev_err(&udc->dev->dev, "unexpect ep0 packets\n");
1753 		break;
1754 	default:
1755 		ep0_stall(udc);
1756 		break;
1757 	}
1758 }
1759 
1760 static void get_setup_data(struct mv_udc *udc, u8 ep_num, u8 *buffer_ptr)
1761 {
1762 	u32 temp;
1763 	struct mv_dqh *dqh;
1764 
1765 	dqh = &udc->ep_dqh[ep_num * 2 + EP_DIR_OUT];
1766 
1767 	/* Clear bit in ENDPTSETUPSTAT */
1768 	writel((1 << ep_num), &udc->op_regs->epsetupstat);
1769 
1770 	/* while a hazard exists when setup package arrives */
1771 	do {
1772 		/* Set Setup Tripwire */
1773 		temp = readl(&udc->op_regs->usbcmd);
1774 		writel(temp | USBCMD_SETUP_TRIPWIRE_SET, &udc->op_regs->usbcmd);
1775 
1776 		/* Copy the setup packet to local buffer */
1777 		memcpy(buffer_ptr, (u8 *) dqh->setup_buffer, 8);
1778 	} while (!(readl(&udc->op_regs->usbcmd) & USBCMD_SETUP_TRIPWIRE_SET));
1779 
1780 	/* Clear Setup Tripwire */
1781 	temp = readl(&udc->op_regs->usbcmd);
1782 	writel(temp & ~USBCMD_SETUP_TRIPWIRE_SET, &udc->op_regs->usbcmd);
1783 }
1784 
1785 static void irq_process_tr_complete(struct mv_udc *udc)
1786 {
1787 	u32 tmp, bit_pos;
1788 	int i, ep_num = 0, direction = 0;
1789 	struct mv_ep	*curr_ep;
1790 	struct mv_req *curr_req, *temp_req;
1791 	int status;
1792 
1793 	/*
1794 	 * We use separate loops for ENDPTSETUPSTAT and ENDPTCOMPLETE
1795 	 * because the setup packets are to be read ASAP
1796 	 */
1797 
1798 	/* Process all Setup packet received interrupts */
1799 	tmp = readl(&udc->op_regs->epsetupstat);
1800 
1801 	if (tmp) {
1802 		for (i = 0; i < udc->max_eps; i++) {
1803 			if (tmp & (1 << i)) {
1804 				get_setup_data(udc, i,
1805 					(u8 *)(&udc->local_setup_buff));
1806 				handle_setup_packet(udc, i,
1807 					&udc->local_setup_buff);
1808 			}
1809 		}
1810 	}
1811 
1812 	/* Don't clear the endpoint setup status register here.
1813 	 * It is cleared as a setup packet is read out of the buffer
1814 	 */
1815 
1816 	/* Process non-setup transaction complete interrupts */
1817 	tmp = readl(&udc->op_regs->epcomplete);
1818 
1819 	if (!tmp)
1820 		return;
1821 
1822 	writel(tmp, &udc->op_regs->epcomplete);
1823 
1824 	for (i = 0; i < udc->max_eps * 2; i++) {
1825 		ep_num = i >> 1;
1826 		direction = i % 2;
1827 
1828 		bit_pos = 1 << (ep_num + 16 * direction);
1829 
1830 		if (!(bit_pos & tmp))
1831 			continue;
1832 
1833 		if (i == 1)
1834 			curr_ep = &udc->eps[0];
1835 		else
1836 			curr_ep = &udc->eps[i];
1837 		/* process the req queue until an uncomplete request */
1838 		list_for_each_entry_safe(curr_req, temp_req,
1839 			&curr_ep->queue, queue) {
1840 			status = process_ep_req(udc, i, curr_req);
1841 			if (status)
1842 				break;
1843 
1844 			/* write back status to req */
1845 			curr_req->req.status = status;
1846 
1847 			/* ep0 request completion */
1848 			if (ep_num == 0) {
1849 				ep0_req_complete(udc, curr_ep, curr_req);
1850 				break;
1851 			} else {
1852 				done(curr_ep, curr_req, status);
1853 			}
1854 		}
1855 	}
1856 }
1857 
1858 static void irq_process_reset(struct mv_udc *udc)
1859 {
1860 	u32 tmp;
1861 	unsigned int loops;
1862 
1863 	udc->ep0_dir = EP_DIR_OUT;
1864 	udc->ep0_state = WAIT_FOR_SETUP;
1865 	udc->remote_wakeup = 0;		/* default to 0 on reset */
1866 
1867 	/* The address bits are past bit 25-31. Set the address */
1868 	tmp = readl(&udc->op_regs->deviceaddr);
1869 	tmp &= ~(USB_DEVICE_ADDRESS_MASK);
1870 	writel(tmp, &udc->op_regs->deviceaddr);
1871 
1872 	/* Clear all the setup token semaphores */
1873 	tmp = readl(&udc->op_regs->epsetupstat);
1874 	writel(tmp, &udc->op_regs->epsetupstat);
1875 
1876 	/* Clear all the endpoint complete status bits */
1877 	tmp = readl(&udc->op_regs->epcomplete);
1878 	writel(tmp, &udc->op_regs->epcomplete);
1879 
1880 	/* wait until all endptprime bits cleared */
1881 	loops = LOOPS(PRIME_TIMEOUT);
1882 	while (readl(&udc->op_regs->epprime) & 0xFFFFFFFF) {
1883 		if (loops == 0) {
1884 			dev_err(&udc->dev->dev,
1885 				"Timeout for ENDPTPRIME = 0x%x\n",
1886 				readl(&udc->op_regs->epprime));
1887 			break;
1888 		}
1889 		loops--;
1890 		udelay(LOOPS_USEC);
1891 	}
1892 
1893 	/* Write 1s to the Flush register */
1894 	writel((u32)~0, &udc->op_regs->epflush);
1895 
1896 	if (readl(&udc->op_regs->portsc[0]) & PORTSCX_PORT_RESET) {
1897 		dev_info(&udc->dev->dev, "usb bus reset\n");
1898 		udc->usb_state = USB_STATE_DEFAULT;
1899 		/* reset all the queues, stop all USB activities */
1900 		gadget_reset(udc, udc->driver);
1901 	} else {
1902 		dev_info(&udc->dev->dev, "USB reset portsc 0x%x\n",
1903 			readl(&udc->op_regs->portsc));
1904 
1905 		/*
1906 		 * re-initialize
1907 		 * controller reset
1908 		 */
1909 		udc_reset(udc);
1910 
1911 		/* reset all the queues, stop all USB activities */
1912 		stop_activity(udc, udc->driver);
1913 
1914 		/* reset ep0 dQH and endptctrl */
1915 		ep0_reset(udc);
1916 
1917 		/* enable interrupt and set controller to run state */
1918 		udc_start(udc);
1919 
1920 		udc->usb_state = USB_STATE_ATTACHED;
1921 	}
1922 }
1923 
1924 static void handle_bus_resume(struct mv_udc *udc)
1925 {
1926 	udc->usb_state = udc->resume_state;
1927 	udc->resume_state = 0;
1928 
1929 	/* report resume to the driver */
1930 	if (udc->driver) {
1931 		if (udc->driver->resume) {
1932 			spin_unlock(&udc->lock);
1933 			udc->driver->resume(&udc->gadget);
1934 			spin_lock(&udc->lock);
1935 		}
1936 	}
1937 }
1938 
1939 static void irq_process_suspend(struct mv_udc *udc)
1940 {
1941 	udc->resume_state = udc->usb_state;
1942 	udc->usb_state = USB_STATE_SUSPENDED;
1943 
1944 	if (udc->driver->suspend) {
1945 		spin_unlock(&udc->lock);
1946 		udc->driver->suspend(&udc->gadget);
1947 		spin_lock(&udc->lock);
1948 	}
1949 }
1950 
1951 static void irq_process_port_change(struct mv_udc *udc)
1952 {
1953 	u32 portsc;
1954 
1955 	portsc = readl(&udc->op_regs->portsc[0]);
1956 	if (!(portsc & PORTSCX_PORT_RESET)) {
1957 		/* Get the speed */
1958 		u32 speed = portsc & PORTSCX_PORT_SPEED_MASK;
1959 		switch (speed) {
1960 		case PORTSCX_PORT_SPEED_HIGH:
1961 			udc->gadget.speed = USB_SPEED_HIGH;
1962 			break;
1963 		case PORTSCX_PORT_SPEED_FULL:
1964 			udc->gadget.speed = USB_SPEED_FULL;
1965 			break;
1966 		case PORTSCX_PORT_SPEED_LOW:
1967 			udc->gadget.speed = USB_SPEED_LOW;
1968 			break;
1969 		default:
1970 			udc->gadget.speed = USB_SPEED_UNKNOWN;
1971 			break;
1972 		}
1973 	}
1974 
1975 	if (portsc & PORTSCX_PORT_SUSPEND) {
1976 		udc->resume_state = udc->usb_state;
1977 		udc->usb_state = USB_STATE_SUSPENDED;
1978 		if (udc->driver->suspend) {
1979 			spin_unlock(&udc->lock);
1980 			udc->driver->suspend(&udc->gadget);
1981 			spin_lock(&udc->lock);
1982 		}
1983 	}
1984 
1985 	if (!(portsc & PORTSCX_PORT_SUSPEND)
1986 		&& udc->usb_state == USB_STATE_SUSPENDED) {
1987 		handle_bus_resume(udc);
1988 	}
1989 
1990 	if (!udc->resume_state)
1991 		udc->usb_state = USB_STATE_DEFAULT;
1992 }
1993 
1994 static void irq_process_error(struct mv_udc *udc)
1995 {
1996 	/* Increment the error count */
1997 	udc->errors++;
1998 }
1999 
2000 static irqreturn_t mv_udc_irq(int irq, void *dev)
2001 {
2002 	struct mv_udc *udc = (struct mv_udc *)dev;
2003 	u32 status, intr;
2004 
2005 	/* Disable ISR when stopped bit is set */
2006 	if (udc->stopped)
2007 		return IRQ_NONE;
2008 
2009 	spin_lock(&udc->lock);
2010 
2011 	status = readl(&udc->op_regs->usbsts);
2012 	intr = readl(&udc->op_regs->usbintr);
2013 	status &= intr;
2014 
2015 	if (status == 0) {
2016 		spin_unlock(&udc->lock);
2017 		return IRQ_NONE;
2018 	}
2019 
2020 	/* Clear all the interrupts occurred */
2021 	writel(status, &udc->op_regs->usbsts);
2022 
2023 	if (status & USBSTS_ERR)
2024 		irq_process_error(udc);
2025 
2026 	if (status & USBSTS_RESET)
2027 		irq_process_reset(udc);
2028 
2029 	if (status & USBSTS_PORT_CHANGE)
2030 		irq_process_port_change(udc);
2031 
2032 	if (status & USBSTS_INT)
2033 		irq_process_tr_complete(udc);
2034 
2035 	if (status & USBSTS_SUSPEND)
2036 		irq_process_suspend(udc);
2037 
2038 	spin_unlock(&udc->lock);
2039 
2040 	return IRQ_HANDLED;
2041 }
2042 
2043 static irqreturn_t mv_udc_vbus_irq(int irq, void *dev)
2044 {
2045 	struct mv_udc *udc = (struct mv_udc *)dev;
2046 
2047 	/* polling VBUS and init phy may cause too much time*/
2048 	if (udc->qwork)
2049 		queue_work(udc->qwork, &udc->vbus_work);
2050 
2051 	return IRQ_HANDLED;
2052 }
2053 
2054 static void mv_udc_vbus_work(struct work_struct *work)
2055 {
2056 	struct mv_udc *udc;
2057 	unsigned int vbus;
2058 
2059 	udc = container_of(work, struct mv_udc, vbus_work);
2060 	if (!udc->pdata->vbus)
2061 		return;
2062 
2063 	vbus = udc->pdata->vbus->poll();
2064 	dev_info(&udc->dev->dev, "vbus is %d\n", vbus);
2065 
2066 	if (vbus == VBUS_HIGH)
2067 		mv_udc_vbus_session(&udc->gadget, 1);
2068 	else if (vbus == VBUS_LOW)
2069 		mv_udc_vbus_session(&udc->gadget, 0);
2070 }
2071 
2072 /* release device structure */
2073 static void gadget_release(struct device *_dev)
2074 {
2075 	struct mv_udc *udc;
2076 
2077 	udc = dev_get_drvdata(_dev);
2078 
2079 	complete(udc->done);
2080 }
2081 
2082 static int mv_udc_remove(struct platform_device *pdev)
2083 {
2084 	struct mv_udc *udc;
2085 
2086 	udc = platform_get_drvdata(pdev);
2087 
2088 	usb_del_gadget_udc(&udc->gadget);
2089 
2090 	if (udc->qwork) {
2091 		flush_workqueue(udc->qwork);
2092 		destroy_workqueue(udc->qwork);
2093 	}
2094 
2095 	/* free memory allocated in probe */
2096 	dma_pool_destroy(udc->dtd_pool);
2097 
2098 	if (udc->ep_dqh)
2099 		dma_free_coherent(&pdev->dev, udc->ep_dqh_size,
2100 			udc->ep_dqh, udc->ep_dqh_dma);
2101 
2102 	mv_udc_disable(udc);
2103 
2104 	/* free dev, wait for the release() finished */
2105 	wait_for_completion(udc->done);
2106 
2107 	return 0;
2108 }
2109 
2110 static int mv_udc_probe(struct platform_device *pdev)
2111 {
2112 	struct mv_usb_platform_data *pdata = dev_get_platdata(&pdev->dev);
2113 	struct mv_udc *udc;
2114 	int retval = 0;
2115 	struct resource *r;
2116 	size_t size;
2117 
2118 	if (pdata == NULL) {
2119 		dev_err(&pdev->dev, "missing platform_data\n");
2120 		return -ENODEV;
2121 	}
2122 
2123 	udc = devm_kzalloc(&pdev->dev, sizeof(*udc), GFP_KERNEL);
2124 	if (udc == NULL)
2125 		return -ENOMEM;
2126 
2127 	udc->done = &release_done;
2128 	udc->pdata = dev_get_platdata(&pdev->dev);
2129 	spin_lock_init(&udc->lock);
2130 
2131 	udc->dev = pdev;
2132 
2133 	if (pdata->mode == MV_USB_MODE_OTG) {
2134 		udc->transceiver = devm_usb_get_phy(&pdev->dev,
2135 					USB_PHY_TYPE_USB2);
2136 		if (IS_ERR(udc->transceiver)) {
2137 			retval = PTR_ERR(udc->transceiver);
2138 
2139 			if (retval == -ENXIO)
2140 				return retval;
2141 
2142 			udc->transceiver = NULL;
2143 			return -EPROBE_DEFER;
2144 		}
2145 	}
2146 
2147 	/* udc only have one sysclk. */
2148 	udc->clk = devm_clk_get(&pdev->dev, NULL);
2149 	if (IS_ERR(udc->clk))
2150 		return PTR_ERR(udc->clk);
2151 
2152 	r = platform_get_resource_byname(udc->dev, IORESOURCE_MEM, "capregs");
2153 	if (r == NULL) {
2154 		dev_err(&pdev->dev, "no I/O memory resource defined\n");
2155 		return -ENODEV;
2156 	}
2157 
2158 	udc->cap_regs = (struct mv_cap_regs __iomem *)
2159 		devm_ioremap(&pdev->dev, r->start, resource_size(r));
2160 	if (udc->cap_regs == NULL) {
2161 		dev_err(&pdev->dev, "failed to map I/O memory\n");
2162 		return -EBUSY;
2163 	}
2164 
2165 	r = platform_get_resource_byname(udc->dev, IORESOURCE_MEM, "phyregs");
2166 	if (r == NULL) {
2167 		dev_err(&pdev->dev, "no phy I/O memory resource defined\n");
2168 		return -ENODEV;
2169 	}
2170 
2171 	udc->phy_regs = devm_ioremap(&pdev->dev, r->start, resource_size(r));
2172 	if (udc->phy_regs == NULL) {
2173 		dev_err(&pdev->dev, "failed to map phy I/O memory\n");
2174 		return -EBUSY;
2175 	}
2176 
2177 	/* we will acces controller register, so enable the clk */
2178 	retval = mv_udc_enable_internal(udc);
2179 	if (retval)
2180 		return retval;
2181 
2182 	udc->op_regs =
2183 		(struct mv_op_regs __iomem *)((unsigned long)udc->cap_regs
2184 		+ (readl(&udc->cap_regs->caplength_hciversion)
2185 			& CAPLENGTH_MASK));
2186 	udc->max_eps = readl(&udc->cap_regs->dccparams) & DCCPARAMS_DEN_MASK;
2187 
2188 	/*
2189 	 * some platform will use usb to download image, it may not disconnect
2190 	 * usb gadget before loading kernel. So first stop udc here.
2191 	 */
2192 	udc_stop(udc);
2193 	writel(0xFFFFFFFF, &udc->op_regs->usbsts);
2194 
2195 	size = udc->max_eps * sizeof(struct mv_dqh) *2;
2196 	size = (size + DQH_ALIGNMENT - 1) & ~(DQH_ALIGNMENT - 1);
2197 	udc->ep_dqh = dma_alloc_coherent(&pdev->dev, size,
2198 					&udc->ep_dqh_dma, GFP_KERNEL);
2199 
2200 	if (udc->ep_dqh == NULL) {
2201 		dev_err(&pdev->dev, "allocate dQH memory failed\n");
2202 		retval = -ENOMEM;
2203 		goto err_disable_clock;
2204 	}
2205 	udc->ep_dqh_size = size;
2206 
2207 	/* create dTD dma_pool resource */
2208 	udc->dtd_pool = dma_pool_create("mv_dtd",
2209 			&pdev->dev,
2210 			sizeof(struct mv_dtd),
2211 			DTD_ALIGNMENT,
2212 			DMA_BOUNDARY);
2213 
2214 	if (!udc->dtd_pool) {
2215 		retval = -ENOMEM;
2216 		goto err_free_dma;
2217 	}
2218 
2219 	size = udc->max_eps * sizeof(struct mv_ep) *2;
2220 	udc->eps = devm_kzalloc(&pdev->dev, size, GFP_KERNEL);
2221 	if (udc->eps == NULL) {
2222 		retval = -ENOMEM;
2223 		goto err_destroy_dma;
2224 	}
2225 
2226 	/* initialize ep0 status request structure */
2227 	udc->status_req = devm_kzalloc(&pdev->dev, sizeof(struct mv_req),
2228 					GFP_KERNEL);
2229 	if (!udc->status_req) {
2230 		retval = -ENOMEM;
2231 		goto err_destroy_dma;
2232 	}
2233 	INIT_LIST_HEAD(&udc->status_req->queue);
2234 
2235 	/* allocate a small amount of memory to get valid address */
2236 	udc->status_req->req.buf = kzalloc(8, GFP_KERNEL);
2237 	udc->status_req->req.dma = DMA_ADDR_INVALID;
2238 
2239 	udc->resume_state = USB_STATE_NOTATTACHED;
2240 	udc->usb_state = USB_STATE_POWERED;
2241 	udc->ep0_dir = EP_DIR_OUT;
2242 	udc->remote_wakeup = 0;
2243 
2244 	r = platform_get_resource(udc->dev, IORESOURCE_IRQ, 0);
2245 	if (r == NULL) {
2246 		dev_err(&pdev->dev, "no IRQ resource defined\n");
2247 		retval = -ENODEV;
2248 		goto err_destroy_dma;
2249 	}
2250 	udc->irq = r->start;
2251 	if (devm_request_irq(&pdev->dev, udc->irq, mv_udc_irq,
2252 		IRQF_SHARED, driver_name, udc)) {
2253 		dev_err(&pdev->dev, "Request irq %d for UDC failed\n",
2254 			udc->irq);
2255 		retval = -ENODEV;
2256 		goto err_destroy_dma;
2257 	}
2258 
2259 	/* initialize gadget structure */
2260 	udc->gadget.ops = &mv_ops;	/* usb_gadget_ops */
2261 	udc->gadget.ep0 = &udc->eps[0].ep;	/* gadget ep0 */
2262 	INIT_LIST_HEAD(&udc->gadget.ep_list);	/* ep_list */
2263 	udc->gadget.speed = USB_SPEED_UNKNOWN;	/* speed */
2264 	udc->gadget.max_speed = USB_SPEED_HIGH;	/* support dual speed */
2265 
2266 	/* the "gadget" abstracts/virtualizes the controller */
2267 	udc->gadget.name = driver_name;		/* gadget name */
2268 
2269 	eps_init(udc);
2270 
2271 	/* VBUS detect: we can disable/enable clock on demand.*/
2272 	if (udc->transceiver)
2273 		udc->clock_gating = 1;
2274 	else if (pdata->vbus) {
2275 		udc->clock_gating = 1;
2276 		retval = devm_request_threaded_irq(&pdev->dev,
2277 				pdata->vbus->irq, NULL,
2278 				mv_udc_vbus_irq, IRQF_ONESHOT, "vbus", udc);
2279 		if (retval) {
2280 			dev_info(&pdev->dev,
2281 				"Can not request irq for VBUS, "
2282 				"disable clock gating\n");
2283 			udc->clock_gating = 0;
2284 		}
2285 
2286 		udc->qwork = create_singlethread_workqueue("mv_udc_queue");
2287 		if (!udc->qwork) {
2288 			dev_err(&pdev->dev, "cannot create workqueue\n");
2289 			retval = -ENOMEM;
2290 			goto err_destroy_dma;
2291 		}
2292 
2293 		INIT_WORK(&udc->vbus_work, mv_udc_vbus_work);
2294 	}
2295 
2296 	/*
2297 	 * When clock gating is supported, we can disable clk and phy.
2298 	 * If not, it means that VBUS detection is not supported, we
2299 	 * have to enable vbus active all the time to let controller work.
2300 	 */
2301 	if (udc->clock_gating)
2302 		mv_udc_disable_internal(udc);
2303 	else
2304 		udc->vbus_active = 1;
2305 
2306 	retval = usb_add_gadget_udc_release(&pdev->dev, &udc->gadget,
2307 			gadget_release);
2308 	if (retval)
2309 		goto err_create_workqueue;
2310 
2311 	platform_set_drvdata(pdev, udc);
2312 	dev_info(&pdev->dev, "successful probe UDC device %s clock gating.\n",
2313 		udc->clock_gating ? "with" : "without");
2314 
2315 	return 0;
2316 
2317 err_create_workqueue:
2318 	destroy_workqueue(udc->qwork);
2319 err_destroy_dma:
2320 	dma_pool_destroy(udc->dtd_pool);
2321 err_free_dma:
2322 	dma_free_coherent(&pdev->dev, udc->ep_dqh_size,
2323 			udc->ep_dqh, udc->ep_dqh_dma);
2324 err_disable_clock:
2325 	mv_udc_disable_internal(udc);
2326 
2327 	return retval;
2328 }
2329 
2330 #ifdef CONFIG_PM
2331 static int mv_udc_suspend(struct device *dev)
2332 {
2333 	struct mv_udc *udc;
2334 
2335 	udc = dev_get_drvdata(dev);
2336 
2337 	/* if OTG is enabled, the following will be done in OTG driver*/
2338 	if (udc->transceiver)
2339 		return 0;
2340 
2341 	if (udc->pdata->vbus && udc->pdata->vbus->poll)
2342 		if (udc->pdata->vbus->poll() == VBUS_HIGH) {
2343 			dev_info(&udc->dev->dev, "USB cable is connected!\n");
2344 			return -EAGAIN;
2345 		}
2346 
2347 	/*
2348 	 * only cable is unplugged, udc can suspend.
2349 	 * So do not care about clock_gating == 1.
2350 	 */
2351 	if (!udc->clock_gating) {
2352 		udc_stop(udc);
2353 
2354 		spin_lock_irq(&udc->lock);
2355 		/* stop all usb activities */
2356 		stop_activity(udc, udc->driver);
2357 		spin_unlock_irq(&udc->lock);
2358 
2359 		mv_udc_disable_internal(udc);
2360 	}
2361 
2362 	return 0;
2363 }
2364 
2365 static int mv_udc_resume(struct device *dev)
2366 {
2367 	struct mv_udc *udc;
2368 	int retval;
2369 
2370 	udc = dev_get_drvdata(dev);
2371 
2372 	/* if OTG is enabled, the following will be done in OTG driver*/
2373 	if (udc->transceiver)
2374 		return 0;
2375 
2376 	if (!udc->clock_gating) {
2377 		retval = mv_udc_enable_internal(udc);
2378 		if (retval)
2379 			return retval;
2380 
2381 		if (udc->driver && udc->softconnect) {
2382 			udc_reset(udc);
2383 			ep0_reset(udc);
2384 			udc_start(udc);
2385 		}
2386 	}
2387 
2388 	return 0;
2389 }
2390 
2391 static const struct dev_pm_ops mv_udc_pm_ops = {
2392 	.suspend	= mv_udc_suspend,
2393 	.resume		= mv_udc_resume,
2394 };
2395 #endif
2396 
2397 static void mv_udc_shutdown(struct platform_device *pdev)
2398 {
2399 	struct mv_udc *udc;
2400 	u32 mode;
2401 
2402 	udc = platform_get_drvdata(pdev);
2403 	/* reset controller mode to IDLE */
2404 	mv_udc_enable(udc);
2405 	mode = readl(&udc->op_regs->usbmode);
2406 	mode &= ~3;
2407 	writel(mode, &udc->op_regs->usbmode);
2408 	mv_udc_disable(udc);
2409 }
2410 
2411 static struct platform_driver udc_driver = {
2412 	.probe		= mv_udc_probe,
2413 	.remove		= mv_udc_remove,
2414 	.shutdown	= mv_udc_shutdown,
2415 	.driver		= {
2416 		.name	= "mv-udc",
2417 #ifdef CONFIG_PM
2418 		.pm	= &mv_udc_pm_ops,
2419 #endif
2420 	},
2421 };
2422 
2423 module_platform_driver(udc_driver);
2424 MODULE_ALIAS("platform:mv-udc");
2425 MODULE_DESCRIPTION(DRIVER_DESC);
2426 MODULE_AUTHOR("Chao Xie <chao.xie@marvell.com>");
2427 MODULE_VERSION(DRIVER_VERSION);
2428 MODULE_LICENSE("GPL");
2429