xref: /linux/drivers/usb/chipidea/udc.c (revision 6e7fd890f1d6ac83805409e9c346240de2705584)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * udc.c - ChipIdea UDC driver
4  *
5  * Copyright (C) 2008 Chipidea - MIPS Technologies, Inc. All rights reserved.
6  *
7  * Author: David Lopo
8  */
9 
10 #include <linux/delay.h>
11 #include <linux/device.h>
12 #include <linux/dmapool.h>
13 #include <linux/err.h>
14 #include <linux/irqreturn.h>
15 #include <linux/kernel.h>
16 #include <linux/slab.h>
17 #include <linux/pm_runtime.h>
18 #include <linux/pinctrl/consumer.h>
19 #include <linux/usb/ch9.h>
20 #include <linux/usb/gadget.h>
21 #include <linux/usb/otg-fsm.h>
22 #include <linux/usb/chipidea.h>
23 
24 #include "ci.h"
25 #include "udc.h"
26 #include "bits.h"
27 #include "otg.h"
28 #include "otg_fsm.h"
29 #include "trace.h"
30 
31 /* control endpoint description */
32 static const struct usb_endpoint_descriptor
33 ctrl_endpt_out_desc = {
34 	.bLength         = USB_DT_ENDPOINT_SIZE,
35 	.bDescriptorType = USB_DT_ENDPOINT,
36 
37 	.bEndpointAddress = USB_DIR_OUT,
38 	.bmAttributes    = USB_ENDPOINT_XFER_CONTROL,
39 	.wMaxPacketSize  = cpu_to_le16(CTRL_PAYLOAD_MAX),
40 };
41 
42 static const struct usb_endpoint_descriptor
43 ctrl_endpt_in_desc = {
44 	.bLength         = USB_DT_ENDPOINT_SIZE,
45 	.bDescriptorType = USB_DT_ENDPOINT,
46 
47 	.bEndpointAddress = USB_DIR_IN,
48 	.bmAttributes    = USB_ENDPOINT_XFER_CONTROL,
49 	.wMaxPacketSize  = cpu_to_le16(CTRL_PAYLOAD_MAX),
50 };
51 
52 static int reprime_dtd(struct ci_hdrc *ci, struct ci_hw_ep *hwep,
53 		       struct td_node *node);
54 /**
55  * hw_ep_bit: calculates the bit number
56  * @num: endpoint number
57  * @dir: endpoint direction
58  *
59  * This function returns bit number
60  */
61 static inline int hw_ep_bit(int num, int dir)
62 {
63 	return num + ((dir == TX) ? 16 : 0);
64 }
65 
66 static inline int ep_to_bit(struct ci_hdrc *ci, int n)
67 {
68 	int fill = 16 - ci->hw_ep_max / 2;
69 
70 	if (n >= ci->hw_ep_max / 2)
71 		n += fill;
72 
73 	return n;
74 }
75 
76 /**
77  * hw_device_state: enables/disables interrupts (execute without interruption)
78  * @ci: the controller
79  * @dma: 0 => disable, !0 => enable and set dma engine
80  *
81  * This function returns an error code
82  */
83 static int hw_device_state(struct ci_hdrc *ci, u32 dma)
84 {
85 	if (dma) {
86 		hw_write(ci, OP_ENDPTLISTADDR, ~0, dma);
87 		/* interrupt, error, port change, reset, sleep/suspend */
88 		hw_write(ci, OP_USBINTR, ~0,
89 			     USBi_UI|USBi_UEI|USBi_PCI|USBi_URI|USBi_SLI);
90 	} else {
91 		hw_write(ci, OP_USBINTR, ~0, 0);
92 	}
93 	return 0;
94 }
95 
96 /**
97  * hw_ep_flush: flush endpoint fifo (execute without interruption)
98  * @ci: the controller
99  * @num: endpoint number
100  * @dir: endpoint direction
101  *
102  * This function returns an error code
103  */
104 static int hw_ep_flush(struct ci_hdrc *ci, int num, int dir)
105 {
106 	int n = hw_ep_bit(num, dir);
107 
108 	do {
109 		/* flush any pending transfer */
110 		hw_write(ci, OP_ENDPTFLUSH, ~0, BIT(n));
111 		while (hw_read(ci, OP_ENDPTFLUSH, BIT(n)))
112 			cpu_relax();
113 	} while (hw_read(ci, OP_ENDPTSTAT, BIT(n)));
114 
115 	return 0;
116 }
117 
118 /**
119  * hw_ep_disable: disables endpoint (execute without interruption)
120  * @ci: the controller
121  * @num: endpoint number
122  * @dir: endpoint direction
123  *
124  * This function returns an error code
125  */
126 static int hw_ep_disable(struct ci_hdrc *ci, int num, int dir)
127 {
128 	hw_write(ci, OP_ENDPTCTRL + num,
129 		 (dir == TX) ? ENDPTCTRL_TXE : ENDPTCTRL_RXE, 0);
130 	return 0;
131 }
132 
133 /**
134  * hw_ep_enable: enables endpoint (execute without interruption)
135  * @ci: the controller
136  * @num:  endpoint number
137  * @dir:  endpoint direction
138  * @type: endpoint type
139  *
140  * This function returns an error code
141  */
142 static int hw_ep_enable(struct ci_hdrc *ci, int num, int dir, int type)
143 {
144 	u32 mask, data;
145 
146 	if (dir == TX) {
147 		mask  = ENDPTCTRL_TXT;  /* type    */
148 		data  = type << __ffs(mask);
149 
150 		mask |= ENDPTCTRL_TXS;  /* unstall */
151 		mask |= ENDPTCTRL_TXR;  /* reset data toggle */
152 		data |= ENDPTCTRL_TXR;
153 		mask |= ENDPTCTRL_TXE;  /* enable  */
154 		data |= ENDPTCTRL_TXE;
155 	} else {
156 		mask  = ENDPTCTRL_RXT;  /* type    */
157 		data  = type << __ffs(mask);
158 
159 		mask |= ENDPTCTRL_RXS;  /* unstall */
160 		mask |= ENDPTCTRL_RXR;  /* reset data toggle */
161 		data |= ENDPTCTRL_RXR;
162 		mask |= ENDPTCTRL_RXE;  /* enable  */
163 		data |= ENDPTCTRL_RXE;
164 	}
165 	hw_write(ci, OP_ENDPTCTRL + num, mask, data);
166 	return 0;
167 }
168 
169 /**
170  * hw_ep_get_halt: return endpoint halt status
171  * @ci: the controller
172  * @num: endpoint number
173  * @dir: endpoint direction
174  *
175  * This function returns 1 if endpoint halted
176  */
177 static int hw_ep_get_halt(struct ci_hdrc *ci, int num, int dir)
178 {
179 	u32 mask = (dir == TX) ? ENDPTCTRL_TXS : ENDPTCTRL_RXS;
180 
181 	return hw_read(ci, OP_ENDPTCTRL + num, mask) ? 1 : 0;
182 }
183 
184 /**
185  * hw_ep_prime: primes endpoint (execute without interruption)
186  * @ci: the controller
187  * @num:     endpoint number
188  * @dir:     endpoint direction
189  * @is_ctrl: true if control endpoint
190  *
191  * This function returns an error code
192  */
193 static int hw_ep_prime(struct ci_hdrc *ci, int num, int dir, int is_ctrl)
194 {
195 	int n = hw_ep_bit(num, dir);
196 
197 	/* Synchronize before ep prime */
198 	wmb();
199 
200 	if (is_ctrl && dir == RX && hw_read(ci, OP_ENDPTSETUPSTAT, BIT(num)))
201 		return -EAGAIN;
202 
203 	hw_write(ci, OP_ENDPTPRIME, ~0, BIT(n));
204 
205 	while (hw_read(ci, OP_ENDPTPRIME, BIT(n)))
206 		cpu_relax();
207 	if (is_ctrl && dir == RX && hw_read(ci, OP_ENDPTSETUPSTAT, BIT(num)))
208 		return -EAGAIN;
209 
210 	/* status shoult be tested according with manual but it doesn't work */
211 	return 0;
212 }
213 
214 /**
215  * hw_ep_set_halt: configures ep halt & resets data toggle after clear (execute
216  *                 without interruption)
217  * @ci: the controller
218  * @num:   endpoint number
219  * @dir:   endpoint direction
220  * @value: true => stall, false => unstall
221  *
222  * This function returns an error code
223  */
224 static int hw_ep_set_halt(struct ci_hdrc *ci, int num, int dir, int value)
225 {
226 	if (value != 0 && value != 1)
227 		return -EINVAL;
228 
229 	do {
230 		enum ci_hw_regs reg = OP_ENDPTCTRL + num;
231 		u32 mask_xs = (dir == TX) ? ENDPTCTRL_TXS : ENDPTCTRL_RXS;
232 		u32 mask_xr = (dir == TX) ? ENDPTCTRL_TXR : ENDPTCTRL_RXR;
233 
234 		/* data toggle - reserved for EP0 but it's in ESS */
235 		hw_write(ci, reg, mask_xs|mask_xr,
236 			  value ? mask_xs : mask_xr);
237 	} while (value != hw_ep_get_halt(ci, num, dir));
238 
239 	return 0;
240 }
241 
242 /**
243  * hw_port_is_high_speed: test if port is high speed
244  * @ci: the controller
245  *
246  * This function returns true if high speed port
247  */
248 static int hw_port_is_high_speed(struct ci_hdrc *ci)
249 {
250 	return ci->hw_bank.lpm ? hw_read(ci, OP_DEVLC, DEVLC_PSPD) :
251 		hw_read(ci, OP_PORTSC, PORTSC_HSP);
252 }
253 
254 /**
255  * hw_test_and_clear_complete: test & clear complete status (execute without
256  *                             interruption)
257  * @ci: the controller
258  * @n: endpoint number
259  *
260  * This function returns complete status
261  */
262 static int hw_test_and_clear_complete(struct ci_hdrc *ci, int n)
263 {
264 	n = ep_to_bit(ci, n);
265 	return hw_test_and_clear(ci, OP_ENDPTCOMPLETE, BIT(n));
266 }
267 
268 /**
269  * hw_test_and_clear_intr_active: test & clear active interrupts (execute
270  *                                without interruption)
271  * @ci: the controller
272  *
273  * This function returns active interrutps
274  */
275 static u32 hw_test_and_clear_intr_active(struct ci_hdrc *ci)
276 {
277 	u32 reg = hw_read_intr_status(ci) & hw_read_intr_enable(ci);
278 
279 	hw_write(ci, OP_USBSTS, ~0, reg);
280 	return reg;
281 }
282 
283 /**
284  * hw_test_and_clear_setup_guard: test & clear setup guard (execute without
285  *                                interruption)
286  * @ci: the controller
287  *
288  * This function returns guard value
289  */
290 static int hw_test_and_clear_setup_guard(struct ci_hdrc *ci)
291 {
292 	return hw_test_and_write(ci, OP_USBCMD, USBCMD_SUTW, 0);
293 }
294 
295 /**
296  * hw_test_and_set_setup_guard: test & set setup guard (execute without
297  *                              interruption)
298  * @ci: the controller
299  *
300  * This function returns guard value
301  */
302 static int hw_test_and_set_setup_guard(struct ci_hdrc *ci)
303 {
304 	return hw_test_and_write(ci, OP_USBCMD, USBCMD_SUTW, USBCMD_SUTW);
305 }
306 
307 /**
308  * hw_usb_set_address: configures USB address (execute without interruption)
309  * @ci: the controller
310  * @value: new USB address
311  *
312  * This function explicitly sets the address, without the "USBADRA" (advance)
313  * feature, which is not supported by older versions of the controller.
314  */
315 static void hw_usb_set_address(struct ci_hdrc *ci, u8 value)
316 {
317 	hw_write(ci, OP_DEVICEADDR, DEVICEADDR_USBADR,
318 		 value << __ffs(DEVICEADDR_USBADR));
319 }
320 
321 /**
322  * hw_usb_reset: restart device after a bus reset (execute without
323  *               interruption)
324  * @ci: the controller
325  *
326  * This function returns an error code
327  */
328 static int hw_usb_reset(struct ci_hdrc *ci)
329 {
330 	hw_usb_set_address(ci, 0);
331 
332 	/* ESS flushes only at end?!? */
333 	hw_write(ci, OP_ENDPTFLUSH,    ~0, ~0);
334 
335 	/* clear setup token semaphores */
336 	hw_write(ci, OP_ENDPTSETUPSTAT, 0,  0);
337 
338 	/* clear complete status */
339 	hw_write(ci, OP_ENDPTCOMPLETE,  0,  0);
340 
341 	/* wait until all bits cleared */
342 	while (hw_read(ci, OP_ENDPTPRIME, ~0))
343 		udelay(10);             /* not RTOS friendly */
344 
345 	/* reset all endpoints ? */
346 
347 	/* reset internal status and wait for further instructions
348 	   no need to verify the port reset status (ESS does it) */
349 
350 	return 0;
351 }
352 
353 /******************************************************************************
354  * UTIL block
355  *****************************************************************************/
356 
357 static int add_td_to_list(struct ci_hw_ep *hwep, struct ci_hw_req *hwreq,
358 			unsigned int length, struct scatterlist *s)
359 {
360 	int i;
361 	u32 temp;
362 	struct td_node *lastnode, *node = kzalloc(sizeof(struct td_node),
363 						  GFP_ATOMIC);
364 
365 	if (node == NULL)
366 		return -ENOMEM;
367 
368 	node->ptr = dma_pool_zalloc(hwep->td_pool, GFP_ATOMIC, &node->dma);
369 	if (node->ptr == NULL) {
370 		kfree(node);
371 		return -ENOMEM;
372 	}
373 
374 	node->ptr->token = cpu_to_le32(length << __ffs(TD_TOTAL_BYTES));
375 	node->ptr->token &= cpu_to_le32(TD_TOTAL_BYTES);
376 	node->ptr->token |= cpu_to_le32(TD_STATUS_ACTIVE);
377 	if (hwep->type == USB_ENDPOINT_XFER_ISOC && hwep->dir == TX) {
378 		u32 mul = hwreq->req.length / hwep->ep.maxpacket;
379 
380 		if (hwreq->req.length == 0
381 				|| hwreq->req.length % hwep->ep.maxpacket)
382 			mul++;
383 		node->ptr->token |= cpu_to_le32(mul << __ffs(TD_MULTO));
384 	}
385 
386 	if (s) {
387 		temp = (u32) (sg_dma_address(s) + hwreq->req.actual);
388 		node->td_remaining_size = CI_MAX_BUF_SIZE - length;
389 	} else {
390 		temp = (u32) (hwreq->req.dma + hwreq->req.actual);
391 	}
392 
393 	if (length) {
394 		node->ptr->page[0] = cpu_to_le32(temp);
395 		for (i = 1; i < TD_PAGE_COUNT; i++) {
396 			u32 page = temp + i * CI_HDRC_PAGE_SIZE;
397 			page &= ~TD_RESERVED_MASK;
398 			node->ptr->page[i] = cpu_to_le32(page);
399 		}
400 	}
401 
402 	hwreq->req.actual += length;
403 
404 	if (!list_empty(&hwreq->tds)) {
405 		/* get the last entry */
406 		lastnode = list_entry(hwreq->tds.prev,
407 				struct td_node, td);
408 		lastnode->ptr->next = cpu_to_le32(node->dma);
409 	}
410 
411 	INIT_LIST_HEAD(&node->td);
412 	list_add_tail(&node->td, &hwreq->tds);
413 
414 	return 0;
415 }
416 
417 /**
418  * _usb_addr: calculates endpoint address from direction & number
419  * @ep:  endpoint
420  */
421 static inline u8 _usb_addr(struct ci_hw_ep *ep)
422 {
423 	return ((ep->dir == TX) ? USB_ENDPOINT_DIR_MASK : 0) | ep->num;
424 }
425 
426 static int prepare_td_for_non_sg(struct ci_hw_ep *hwep,
427 		struct ci_hw_req *hwreq)
428 {
429 	unsigned int rest = hwreq->req.length;
430 	int pages = TD_PAGE_COUNT;
431 	int ret = 0;
432 
433 	if (rest == 0) {
434 		ret = add_td_to_list(hwep, hwreq, 0, NULL);
435 		if (ret < 0)
436 			return ret;
437 	}
438 
439 	/*
440 	 * The first buffer could be not page aligned.
441 	 * In that case we have to span into one extra td.
442 	 */
443 	if (hwreq->req.dma % PAGE_SIZE)
444 		pages--;
445 
446 	while (rest > 0) {
447 		unsigned int count = min(hwreq->req.length - hwreq->req.actual,
448 			(unsigned int)(pages * CI_HDRC_PAGE_SIZE));
449 
450 		ret = add_td_to_list(hwep, hwreq, count, NULL);
451 		if (ret < 0)
452 			return ret;
453 
454 		rest -= count;
455 	}
456 
457 	if (hwreq->req.zero && hwreq->req.length && hwep->dir == TX
458 	    && (hwreq->req.length % hwep->ep.maxpacket == 0)) {
459 		ret = add_td_to_list(hwep, hwreq, 0, NULL);
460 		if (ret < 0)
461 			return ret;
462 	}
463 
464 	return ret;
465 }
466 
467 static int prepare_td_per_sg(struct ci_hw_ep *hwep, struct ci_hw_req *hwreq,
468 		struct scatterlist *s)
469 {
470 	unsigned int rest = sg_dma_len(s);
471 	int ret = 0;
472 
473 	hwreq->req.actual = 0;
474 	while (rest > 0) {
475 		unsigned int count = min_t(unsigned int, rest,
476 				CI_MAX_BUF_SIZE);
477 
478 		ret = add_td_to_list(hwep, hwreq, count, s);
479 		if (ret < 0)
480 			return ret;
481 
482 		rest -= count;
483 	}
484 
485 	return ret;
486 }
487 
488 static void ci_add_buffer_entry(struct td_node *node, struct scatterlist *s)
489 {
490 	int empty_td_slot_index = (CI_MAX_BUF_SIZE - node->td_remaining_size)
491 			/ CI_HDRC_PAGE_SIZE;
492 	int i;
493 	u32 token;
494 
495 	token = le32_to_cpu(node->ptr->token) + (sg_dma_len(s) << __ffs(TD_TOTAL_BYTES));
496 	node->ptr->token = cpu_to_le32(token);
497 
498 	for (i = empty_td_slot_index; i < TD_PAGE_COUNT; i++) {
499 		u32 page = (u32) sg_dma_address(s) +
500 			(i - empty_td_slot_index) * CI_HDRC_PAGE_SIZE;
501 
502 		page &= ~TD_RESERVED_MASK;
503 		node->ptr->page[i] = cpu_to_le32(page);
504 	}
505 }
506 
507 static int prepare_td_for_sg(struct ci_hw_ep *hwep, struct ci_hw_req *hwreq)
508 {
509 	struct usb_request *req = &hwreq->req;
510 	struct scatterlist *s = req->sg;
511 	int ret = 0, i = 0;
512 	struct td_node *node = NULL;
513 
514 	if (!s || req->zero || req->length == 0) {
515 		dev_err(hwep->ci->dev, "not supported operation for sg\n");
516 		return -EINVAL;
517 	}
518 
519 	while (i++ < req->num_mapped_sgs) {
520 		if (sg_dma_address(s) % PAGE_SIZE) {
521 			dev_err(hwep->ci->dev, "not page aligned sg buffer\n");
522 			return -EINVAL;
523 		}
524 
525 		if (node && (node->td_remaining_size >= sg_dma_len(s))) {
526 			ci_add_buffer_entry(node, s);
527 			node->td_remaining_size -= sg_dma_len(s);
528 		} else {
529 			ret = prepare_td_per_sg(hwep, hwreq, s);
530 			if (ret)
531 				return ret;
532 
533 			node = list_entry(hwreq->tds.prev,
534 				struct td_node, td);
535 		}
536 
537 		s = sg_next(s);
538 	}
539 
540 	return ret;
541 }
542 
543 /**
544  * _hardware_enqueue: configures a request at hardware level
545  * @hwep:   endpoint
546  * @hwreq:  request
547  *
548  * This function returns an error code
549  */
550 static int _hardware_enqueue(struct ci_hw_ep *hwep, struct ci_hw_req *hwreq)
551 {
552 	struct ci_hdrc *ci = hwep->ci;
553 	int ret = 0;
554 	struct td_node *firstnode, *lastnode;
555 
556 	/* don't queue twice */
557 	if (hwreq->req.status == -EALREADY)
558 		return -EALREADY;
559 
560 	hwreq->req.status = -EALREADY;
561 
562 	ret = usb_gadget_map_request_by_dev(ci->dev->parent,
563 					    &hwreq->req, hwep->dir);
564 	if (ret)
565 		return ret;
566 
567 	if (hwreq->req.num_mapped_sgs)
568 		ret = prepare_td_for_sg(hwep, hwreq);
569 	else
570 		ret = prepare_td_for_non_sg(hwep, hwreq);
571 
572 	if (ret)
573 		return ret;
574 
575 	lastnode = list_entry(hwreq->tds.prev,
576 		struct td_node, td);
577 
578 	lastnode->ptr->next = cpu_to_le32(TD_TERMINATE);
579 	if (!hwreq->req.no_interrupt)
580 		lastnode->ptr->token |= cpu_to_le32(TD_IOC);
581 
582 	list_for_each_entry_safe(firstnode, lastnode, &hwreq->tds, td)
583 		trace_ci_prepare_td(hwep, hwreq, firstnode);
584 
585 	firstnode = list_first_entry(&hwreq->tds, struct td_node, td);
586 
587 	wmb();
588 
589 	hwreq->req.actual = 0;
590 	if (!list_empty(&hwep->qh.queue)) {
591 		struct ci_hw_req *hwreqprev;
592 		int n = hw_ep_bit(hwep->num, hwep->dir);
593 		int tmp_stat;
594 		struct td_node *prevlastnode;
595 		u32 next = firstnode->dma & TD_ADDR_MASK;
596 
597 		hwreqprev = list_entry(hwep->qh.queue.prev,
598 				struct ci_hw_req, queue);
599 		prevlastnode = list_entry(hwreqprev->tds.prev,
600 				struct td_node, td);
601 
602 		prevlastnode->ptr->next = cpu_to_le32(next);
603 		wmb();
604 
605 		if (ci->rev == CI_REVISION_22) {
606 			if (!hw_read(ci, OP_ENDPTSTAT, BIT(n)))
607 				reprime_dtd(ci, hwep, prevlastnode);
608 		}
609 
610 		if (hw_read(ci, OP_ENDPTPRIME, BIT(n)))
611 			goto done;
612 		do {
613 			hw_write(ci, OP_USBCMD, USBCMD_ATDTW, USBCMD_ATDTW);
614 			tmp_stat = hw_read(ci, OP_ENDPTSTAT, BIT(n));
615 		} while (!hw_read(ci, OP_USBCMD, USBCMD_ATDTW));
616 		hw_write(ci, OP_USBCMD, USBCMD_ATDTW, 0);
617 		if (tmp_stat)
618 			goto done;
619 	}
620 
621 	/*  QH configuration */
622 	hwep->qh.ptr->td.next = cpu_to_le32(firstnode->dma);
623 	hwep->qh.ptr->td.token &=
624 		cpu_to_le32(~(TD_STATUS_HALTED|TD_STATUS_ACTIVE));
625 
626 	if (hwep->type == USB_ENDPOINT_XFER_ISOC && hwep->dir == RX) {
627 		u32 mul = hwreq->req.length / hwep->ep.maxpacket;
628 
629 		if (hwreq->req.length == 0
630 				|| hwreq->req.length % hwep->ep.maxpacket)
631 			mul++;
632 		hwep->qh.ptr->cap |= cpu_to_le32(mul << __ffs(QH_MULT));
633 	}
634 
635 	ret = hw_ep_prime(ci, hwep->num, hwep->dir,
636 			   hwep->type == USB_ENDPOINT_XFER_CONTROL);
637 done:
638 	return ret;
639 }
640 
641 /**
642  * free_pending_td: remove a pending request for the endpoint
643  * @hwep: endpoint
644  */
645 static void free_pending_td(struct ci_hw_ep *hwep)
646 {
647 	struct td_node *pending = hwep->pending_td;
648 
649 	dma_pool_free(hwep->td_pool, pending->ptr, pending->dma);
650 	hwep->pending_td = NULL;
651 	kfree(pending);
652 }
653 
654 static int reprime_dtd(struct ci_hdrc *ci, struct ci_hw_ep *hwep,
655 					   struct td_node *node)
656 {
657 	hwep->qh.ptr->td.next = cpu_to_le32(node->dma);
658 	hwep->qh.ptr->td.token &=
659 		cpu_to_le32(~(TD_STATUS_HALTED | TD_STATUS_ACTIVE));
660 
661 	return hw_ep_prime(ci, hwep->num, hwep->dir,
662 				hwep->type == USB_ENDPOINT_XFER_CONTROL);
663 }
664 
665 /**
666  * _hardware_dequeue: handles a request at hardware level
667  * @hwep: endpoint
668  * @hwreq:  request
669  *
670  * This function returns an error code
671  */
672 static int _hardware_dequeue(struct ci_hw_ep *hwep, struct ci_hw_req *hwreq)
673 {
674 	u32 tmptoken;
675 	struct td_node *node, *tmpnode;
676 	unsigned remaining_length;
677 	unsigned actual = hwreq->req.length;
678 	struct ci_hdrc *ci = hwep->ci;
679 
680 	if (hwreq->req.status != -EALREADY)
681 		return -EINVAL;
682 
683 	hwreq->req.status = 0;
684 
685 	list_for_each_entry_safe(node, tmpnode, &hwreq->tds, td) {
686 		tmptoken = le32_to_cpu(node->ptr->token);
687 		trace_ci_complete_td(hwep, hwreq, node);
688 		if ((TD_STATUS_ACTIVE & tmptoken) != 0) {
689 			int n = hw_ep_bit(hwep->num, hwep->dir);
690 
691 			if (ci->rev == CI_REVISION_24 ||
692 			    ci->rev == CI_REVISION_22)
693 				if (!hw_read(ci, OP_ENDPTSTAT, BIT(n)))
694 					reprime_dtd(ci, hwep, node);
695 			hwreq->req.status = -EALREADY;
696 			return -EBUSY;
697 		}
698 
699 		remaining_length = (tmptoken & TD_TOTAL_BYTES);
700 		remaining_length >>= __ffs(TD_TOTAL_BYTES);
701 		actual -= remaining_length;
702 
703 		hwreq->req.status = tmptoken & TD_STATUS;
704 		if ((TD_STATUS_HALTED & hwreq->req.status)) {
705 			hwreq->req.status = -EPIPE;
706 			break;
707 		} else if ((TD_STATUS_DT_ERR & hwreq->req.status)) {
708 			hwreq->req.status = -EPROTO;
709 			break;
710 		} else if ((TD_STATUS_TR_ERR & hwreq->req.status)) {
711 			hwreq->req.status = -EILSEQ;
712 			break;
713 		}
714 
715 		if (remaining_length) {
716 			if (hwep->dir == TX) {
717 				hwreq->req.status = -EPROTO;
718 				break;
719 			}
720 		}
721 		/*
722 		 * As the hardware could still address the freed td
723 		 * which will run the udc unusable, the cleanup of the
724 		 * td has to be delayed by one.
725 		 */
726 		if (hwep->pending_td)
727 			free_pending_td(hwep);
728 
729 		hwep->pending_td = node;
730 		list_del_init(&node->td);
731 	}
732 
733 	usb_gadget_unmap_request_by_dev(hwep->ci->dev->parent,
734 					&hwreq->req, hwep->dir);
735 
736 	hwreq->req.actual += actual;
737 
738 	if (hwreq->req.status)
739 		return hwreq->req.status;
740 
741 	return hwreq->req.actual;
742 }
743 
744 /**
745  * _ep_nuke: dequeues all endpoint requests
746  * @hwep: endpoint
747  *
748  * This function returns an error code
749  * Caller must hold lock
750  */
751 static int _ep_nuke(struct ci_hw_ep *hwep)
752 __releases(hwep->lock)
753 __acquires(hwep->lock)
754 {
755 	struct td_node *node, *tmpnode;
756 	if (hwep == NULL)
757 		return -EINVAL;
758 
759 	hw_ep_flush(hwep->ci, hwep->num, hwep->dir);
760 
761 	while (!list_empty(&hwep->qh.queue)) {
762 
763 		/* pop oldest request */
764 		struct ci_hw_req *hwreq = list_entry(hwep->qh.queue.next,
765 						     struct ci_hw_req, queue);
766 
767 		list_for_each_entry_safe(node, tmpnode, &hwreq->tds, td) {
768 			dma_pool_free(hwep->td_pool, node->ptr, node->dma);
769 			list_del_init(&node->td);
770 			node->ptr = NULL;
771 			kfree(node);
772 		}
773 
774 		list_del_init(&hwreq->queue);
775 		hwreq->req.status = -ESHUTDOWN;
776 
777 		if (hwreq->req.complete != NULL) {
778 			spin_unlock(hwep->lock);
779 			usb_gadget_giveback_request(&hwep->ep, &hwreq->req);
780 			spin_lock(hwep->lock);
781 		}
782 	}
783 
784 	if (hwep->pending_td)
785 		free_pending_td(hwep);
786 
787 	return 0;
788 }
789 
790 static int _ep_set_halt(struct usb_ep *ep, int value, bool check_transfer)
791 {
792 	struct ci_hw_ep *hwep = container_of(ep, struct ci_hw_ep, ep);
793 	int direction, retval = 0;
794 	unsigned long flags;
795 
796 	if (ep == NULL || hwep->ep.desc == NULL)
797 		return -EINVAL;
798 
799 	if (usb_endpoint_xfer_isoc(hwep->ep.desc))
800 		return -EOPNOTSUPP;
801 
802 	spin_lock_irqsave(hwep->lock, flags);
803 
804 	if (value && hwep->dir == TX && check_transfer &&
805 		!list_empty(&hwep->qh.queue) &&
806 			!usb_endpoint_xfer_control(hwep->ep.desc)) {
807 		spin_unlock_irqrestore(hwep->lock, flags);
808 		return -EAGAIN;
809 	}
810 
811 	direction = hwep->dir;
812 	do {
813 		retval |= hw_ep_set_halt(hwep->ci, hwep->num, hwep->dir, value);
814 
815 		if (!value)
816 			hwep->wedge = 0;
817 
818 		if (hwep->type == USB_ENDPOINT_XFER_CONTROL)
819 			hwep->dir = (hwep->dir == TX) ? RX : TX;
820 
821 	} while (hwep->dir != direction);
822 
823 	spin_unlock_irqrestore(hwep->lock, flags);
824 	return retval;
825 }
826 
827 
828 /**
829  * _gadget_stop_activity: stops all USB activity, flushes & disables all endpts
830  * @gadget: gadget
831  *
832  * This function returns an error code
833  */
834 static int _gadget_stop_activity(struct usb_gadget *gadget)
835 {
836 	struct usb_ep *ep;
837 	struct ci_hdrc    *ci = container_of(gadget, struct ci_hdrc, gadget);
838 	unsigned long flags;
839 
840 	/* flush all endpoints */
841 	gadget_for_each_ep(ep, gadget) {
842 		usb_ep_fifo_flush(ep);
843 	}
844 	usb_ep_fifo_flush(&ci->ep0out->ep);
845 	usb_ep_fifo_flush(&ci->ep0in->ep);
846 
847 	/* make sure to disable all endpoints */
848 	gadget_for_each_ep(ep, gadget) {
849 		usb_ep_disable(ep);
850 	}
851 
852 	if (ci->status != NULL) {
853 		usb_ep_free_request(&ci->ep0in->ep, ci->status);
854 		ci->status = NULL;
855 	}
856 
857 	spin_lock_irqsave(&ci->lock, flags);
858 	ci->gadget.speed = USB_SPEED_UNKNOWN;
859 	ci->remote_wakeup = 0;
860 	ci->suspended = 0;
861 	spin_unlock_irqrestore(&ci->lock, flags);
862 
863 	return 0;
864 }
865 
866 /******************************************************************************
867  * ISR block
868  *****************************************************************************/
869 /**
870  * isr_reset_handler: USB reset interrupt handler
871  * @ci: UDC device
872  *
873  * This function resets USB engine after a bus reset occurred
874  */
875 static void isr_reset_handler(struct ci_hdrc *ci)
876 __releases(ci->lock)
877 __acquires(ci->lock)
878 {
879 	int retval;
880 
881 	spin_unlock(&ci->lock);
882 	if (ci->gadget.speed != USB_SPEED_UNKNOWN)
883 		usb_gadget_udc_reset(&ci->gadget, ci->driver);
884 
885 	retval = _gadget_stop_activity(&ci->gadget);
886 	if (retval)
887 		goto done;
888 
889 	retval = hw_usb_reset(ci);
890 	if (retval)
891 		goto done;
892 
893 	ci->status = usb_ep_alloc_request(&ci->ep0in->ep, GFP_ATOMIC);
894 	if (ci->status == NULL)
895 		retval = -ENOMEM;
896 
897 done:
898 	spin_lock(&ci->lock);
899 
900 	if (retval)
901 		dev_err(ci->dev, "error: %i\n", retval);
902 }
903 
904 /**
905  * isr_get_status_complete: get_status request complete function
906  * @ep:  endpoint
907  * @req: request handled
908  *
909  * Caller must release lock
910  */
911 static void isr_get_status_complete(struct usb_ep *ep, struct usb_request *req)
912 {
913 	if (ep == NULL || req == NULL)
914 		return;
915 
916 	kfree(req->buf);
917 	usb_ep_free_request(ep, req);
918 }
919 
920 /**
921  * _ep_queue: queues (submits) an I/O request to an endpoint
922  * @ep:        endpoint
923  * @req:       request
924  * @gfp_flags: GFP flags (not used)
925  *
926  * Caller must hold lock
927  * This function returns an error code
928  */
929 static int _ep_queue(struct usb_ep *ep, struct usb_request *req,
930 		    gfp_t __maybe_unused gfp_flags)
931 {
932 	struct ci_hw_ep  *hwep  = container_of(ep,  struct ci_hw_ep, ep);
933 	struct ci_hw_req *hwreq = container_of(req, struct ci_hw_req, req);
934 	struct ci_hdrc *ci = hwep->ci;
935 	int retval = 0;
936 
937 	if (ep == NULL || req == NULL || hwep->ep.desc == NULL)
938 		return -EINVAL;
939 
940 	if (hwep->type == USB_ENDPOINT_XFER_CONTROL) {
941 		if (req->length)
942 			hwep = (ci->ep0_dir == RX) ?
943 			       ci->ep0out : ci->ep0in;
944 		if (!list_empty(&hwep->qh.queue)) {
945 			_ep_nuke(hwep);
946 			dev_warn(hwep->ci->dev, "endpoint ctrl %X nuked\n",
947 				 _usb_addr(hwep));
948 		}
949 	}
950 
951 	if (usb_endpoint_xfer_isoc(hwep->ep.desc) &&
952 	    hwreq->req.length > hwep->ep.mult * hwep->ep.maxpacket) {
953 		dev_err(hwep->ci->dev, "request length too big for isochronous\n");
954 		return -EMSGSIZE;
955 	}
956 
957 	/* first nuke then test link, e.g. previous status has not sent */
958 	if (!list_empty(&hwreq->queue)) {
959 		dev_err(hwep->ci->dev, "request already in queue\n");
960 		return -EBUSY;
961 	}
962 
963 	/* push request */
964 	hwreq->req.status = -EINPROGRESS;
965 	hwreq->req.actual = 0;
966 
967 	retval = _hardware_enqueue(hwep, hwreq);
968 
969 	if (retval == -EALREADY)
970 		retval = 0;
971 	if (!retval)
972 		list_add_tail(&hwreq->queue, &hwep->qh.queue);
973 
974 	return retval;
975 }
976 
977 /**
978  * isr_get_status_response: get_status request response
979  * @ci: ci struct
980  * @setup: setup request packet
981  *
982  * This function returns an error code
983  */
984 static int isr_get_status_response(struct ci_hdrc *ci,
985 				   struct usb_ctrlrequest *setup)
986 __releases(hwep->lock)
987 __acquires(hwep->lock)
988 {
989 	struct ci_hw_ep *hwep = ci->ep0in;
990 	struct usb_request *req = NULL;
991 	gfp_t gfp_flags = GFP_ATOMIC;
992 	int dir, num, retval;
993 
994 	if (hwep == NULL || setup == NULL)
995 		return -EINVAL;
996 
997 	spin_unlock(hwep->lock);
998 	req = usb_ep_alloc_request(&hwep->ep, gfp_flags);
999 	spin_lock(hwep->lock);
1000 	if (req == NULL)
1001 		return -ENOMEM;
1002 
1003 	req->complete = isr_get_status_complete;
1004 	req->length   = 2;
1005 	req->buf      = kzalloc(req->length, gfp_flags);
1006 	if (req->buf == NULL) {
1007 		retval = -ENOMEM;
1008 		goto err_free_req;
1009 	}
1010 
1011 	if ((setup->bRequestType & USB_RECIP_MASK) == USB_RECIP_DEVICE) {
1012 		*(u16 *)req->buf = (ci->remote_wakeup << 1) |
1013 			ci->gadget.is_selfpowered;
1014 	} else if ((setup->bRequestType & USB_RECIP_MASK) \
1015 		   == USB_RECIP_ENDPOINT) {
1016 		dir = (le16_to_cpu(setup->wIndex) & USB_ENDPOINT_DIR_MASK) ?
1017 			TX : RX;
1018 		num =  le16_to_cpu(setup->wIndex) & USB_ENDPOINT_NUMBER_MASK;
1019 		*(u16 *)req->buf = hw_ep_get_halt(ci, num, dir);
1020 	}
1021 	/* else do nothing; reserved for future use */
1022 
1023 	retval = _ep_queue(&hwep->ep, req, gfp_flags);
1024 	if (retval)
1025 		goto err_free_buf;
1026 
1027 	return 0;
1028 
1029  err_free_buf:
1030 	kfree(req->buf);
1031  err_free_req:
1032 	spin_unlock(hwep->lock);
1033 	usb_ep_free_request(&hwep->ep, req);
1034 	spin_lock(hwep->lock);
1035 	return retval;
1036 }
1037 
1038 /**
1039  * isr_setup_status_complete: setup_status request complete function
1040  * @ep:  endpoint
1041  * @req: request handled
1042  *
1043  * Caller must release lock. Put the port in test mode if test mode
1044  * feature is selected.
1045  */
1046 static void
1047 isr_setup_status_complete(struct usb_ep *ep, struct usb_request *req)
1048 {
1049 	struct ci_hdrc *ci = req->context;
1050 	unsigned long flags;
1051 
1052 	if (req->status < 0)
1053 		return;
1054 
1055 	if (ci->setaddr) {
1056 		hw_usb_set_address(ci, ci->address);
1057 		ci->setaddr = false;
1058 		if (ci->address)
1059 			usb_gadget_set_state(&ci->gadget, USB_STATE_ADDRESS);
1060 	}
1061 
1062 	spin_lock_irqsave(&ci->lock, flags);
1063 	if (ci->test_mode)
1064 		hw_port_test_set(ci, ci->test_mode);
1065 	spin_unlock_irqrestore(&ci->lock, flags);
1066 }
1067 
1068 /**
1069  * isr_setup_status_phase: queues the status phase of a setup transation
1070  * @ci: ci struct
1071  *
1072  * This function returns an error code
1073  */
1074 static int isr_setup_status_phase(struct ci_hdrc *ci)
1075 {
1076 	struct ci_hw_ep *hwep;
1077 
1078 	/*
1079 	 * Unexpected USB controller behavior, caused by bad signal integrity
1080 	 * or ground reference problems, can lead to isr_setup_status_phase
1081 	 * being called with ci->status equal to NULL.
1082 	 * If this situation occurs, you should review your USB hardware design.
1083 	 */
1084 	if (WARN_ON_ONCE(!ci->status))
1085 		return -EPIPE;
1086 
1087 	hwep = (ci->ep0_dir == TX) ? ci->ep0out : ci->ep0in;
1088 	ci->status->context = ci;
1089 	ci->status->complete = isr_setup_status_complete;
1090 
1091 	return _ep_queue(&hwep->ep, ci->status, GFP_ATOMIC);
1092 }
1093 
1094 /**
1095  * isr_tr_complete_low: transaction complete low level handler
1096  * @hwep: endpoint
1097  *
1098  * This function returns an error code
1099  * Caller must hold lock
1100  */
1101 static int isr_tr_complete_low(struct ci_hw_ep *hwep)
1102 __releases(hwep->lock)
1103 __acquires(hwep->lock)
1104 {
1105 	struct ci_hw_req *hwreq, *hwreqtemp;
1106 	struct ci_hw_ep *hweptemp = hwep;
1107 	int retval = 0;
1108 
1109 	list_for_each_entry_safe(hwreq, hwreqtemp, &hwep->qh.queue,
1110 			queue) {
1111 		retval = _hardware_dequeue(hwep, hwreq);
1112 		if (retval < 0)
1113 			break;
1114 		list_del_init(&hwreq->queue);
1115 		if (hwreq->req.complete != NULL) {
1116 			spin_unlock(hwep->lock);
1117 			if ((hwep->type == USB_ENDPOINT_XFER_CONTROL) &&
1118 					hwreq->req.length)
1119 				hweptemp = hwep->ci->ep0in;
1120 			usb_gadget_giveback_request(&hweptemp->ep, &hwreq->req);
1121 			spin_lock(hwep->lock);
1122 		}
1123 	}
1124 
1125 	if (retval == -EBUSY)
1126 		retval = 0;
1127 
1128 	return retval;
1129 }
1130 
1131 static int otg_a_alt_hnp_support(struct ci_hdrc *ci)
1132 {
1133 	dev_warn(&ci->gadget.dev,
1134 		"connect the device to an alternate port if you want HNP\n");
1135 	return isr_setup_status_phase(ci);
1136 }
1137 
1138 /**
1139  * isr_setup_packet_handler: setup packet handler
1140  * @ci: UDC descriptor
1141  *
1142  * This function handles setup packet
1143  */
1144 static void isr_setup_packet_handler(struct ci_hdrc *ci)
1145 __releases(ci->lock)
1146 __acquires(ci->lock)
1147 {
1148 	struct ci_hw_ep *hwep = &ci->ci_hw_ep[0];
1149 	struct usb_ctrlrequest req;
1150 	int type, num, dir, err = -EINVAL;
1151 	u8 tmode = 0;
1152 
1153 	/*
1154 	 * Flush data and handshake transactions of previous
1155 	 * setup packet.
1156 	 */
1157 	_ep_nuke(ci->ep0out);
1158 	_ep_nuke(ci->ep0in);
1159 
1160 	/* read_setup_packet */
1161 	do {
1162 		hw_test_and_set_setup_guard(ci);
1163 		memcpy(&req, &hwep->qh.ptr->setup, sizeof(req));
1164 	} while (!hw_test_and_clear_setup_guard(ci));
1165 
1166 	type = req.bRequestType;
1167 
1168 	ci->ep0_dir = (type & USB_DIR_IN) ? TX : RX;
1169 
1170 	switch (req.bRequest) {
1171 	case USB_REQ_CLEAR_FEATURE:
1172 		if (type == (USB_DIR_OUT|USB_RECIP_ENDPOINT) &&
1173 				le16_to_cpu(req.wValue) ==
1174 				USB_ENDPOINT_HALT) {
1175 			if (req.wLength != 0)
1176 				break;
1177 			num  = le16_to_cpu(req.wIndex);
1178 			dir = (num & USB_ENDPOINT_DIR_MASK) ? TX : RX;
1179 			num &= USB_ENDPOINT_NUMBER_MASK;
1180 			if (dir == TX)
1181 				num += ci->hw_ep_max / 2;
1182 			if (!ci->ci_hw_ep[num].wedge) {
1183 				spin_unlock(&ci->lock);
1184 				err = usb_ep_clear_halt(
1185 					&ci->ci_hw_ep[num].ep);
1186 				spin_lock(&ci->lock);
1187 				if (err)
1188 					break;
1189 			}
1190 			err = isr_setup_status_phase(ci);
1191 		} else if (type == (USB_DIR_OUT|USB_RECIP_DEVICE) &&
1192 				le16_to_cpu(req.wValue) ==
1193 				USB_DEVICE_REMOTE_WAKEUP) {
1194 			if (req.wLength != 0)
1195 				break;
1196 			ci->remote_wakeup = 0;
1197 			err = isr_setup_status_phase(ci);
1198 		} else {
1199 			goto delegate;
1200 		}
1201 		break;
1202 	case USB_REQ_GET_STATUS:
1203 		if ((type != (USB_DIR_IN|USB_RECIP_DEVICE) ||
1204 			le16_to_cpu(req.wIndex) == OTG_STS_SELECTOR) &&
1205 		    type != (USB_DIR_IN|USB_RECIP_ENDPOINT) &&
1206 		    type != (USB_DIR_IN|USB_RECIP_INTERFACE))
1207 			goto delegate;
1208 		if (le16_to_cpu(req.wLength) != 2 ||
1209 		    le16_to_cpu(req.wValue)  != 0)
1210 			break;
1211 		err = isr_get_status_response(ci, &req);
1212 		break;
1213 	case USB_REQ_SET_ADDRESS:
1214 		if (type != (USB_DIR_OUT|USB_RECIP_DEVICE))
1215 			goto delegate;
1216 		if (le16_to_cpu(req.wLength) != 0 ||
1217 		    le16_to_cpu(req.wIndex)  != 0)
1218 			break;
1219 		ci->address = (u8)le16_to_cpu(req.wValue);
1220 		ci->setaddr = true;
1221 		err = isr_setup_status_phase(ci);
1222 		break;
1223 	case USB_REQ_SET_FEATURE:
1224 		if (type == (USB_DIR_OUT|USB_RECIP_ENDPOINT) &&
1225 				le16_to_cpu(req.wValue) ==
1226 				USB_ENDPOINT_HALT) {
1227 			if (req.wLength != 0)
1228 				break;
1229 			num  = le16_to_cpu(req.wIndex);
1230 			dir = (num & USB_ENDPOINT_DIR_MASK) ? TX : RX;
1231 			num &= USB_ENDPOINT_NUMBER_MASK;
1232 			if (dir == TX)
1233 				num += ci->hw_ep_max / 2;
1234 
1235 			spin_unlock(&ci->lock);
1236 			err = _ep_set_halt(&ci->ci_hw_ep[num].ep, 1, false);
1237 			spin_lock(&ci->lock);
1238 			if (!err)
1239 				isr_setup_status_phase(ci);
1240 		} else if (type == (USB_DIR_OUT|USB_RECIP_DEVICE)) {
1241 			if (req.wLength != 0)
1242 				break;
1243 			switch (le16_to_cpu(req.wValue)) {
1244 			case USB_DEVICE_REMOTE_WAKEUP:
1245 				ci->remote_wakeup = 1;
1246 				err = isr_setup_status_phase(ci);
1247 				break;
1248 			case USB_DEVICE_TEST_MODE:
1249 				tmode = le16_to_cpu(req.wIndex) >> 8;
1250 				switch (tmode) {
1251 				case USB_TEST_J:
1252 				case USB_TEST_K:
1253 				case USB_TEST_SE0_NAK:
1254 				case USB_TEST_PACKET:
1255 				case USB_TEST_FORCE_ENABLE:
1256 					ci->test_mode = tmode;
1257 					err = isr_setup_status_phase(
1258 							ci);
1259 					break;
1260 				default:
1261 					break;
1262 				}
1263 				break;
1264 			case USB_DEVICE_B_HNP_ENABLE:
1265 				if (ci_otg_is_fsm_mode(ci)) {
1266 					ci->gadget.b_hnp_enable = 1;
1267 					err = isr_setup_status_phase(
1268 							ci);
1269 				}
1270 				break;
1271 			case USB_DEVICE_A_ALT_HNP_SUPPORT:
1272 				if (ci_otg_is_fsm_mode(ci))
1273 					err = otg_a_alt_hnp_support(ci);
1274 				break;
1275 			case USB_DEVICE_A_HNP_SUPPORT:
1276 				if (ci_otg_is_fsm_mode(ci)) {
1277 					ci->gadget.a_hnp_support = 1;
1278 					err = isr_setup_status_phase(
1279 							ci);
1280 				}
1281 				break;
1282 			default:
1283 				goto delegate;
1284 			}
1285 		} else {
1286 			goto delegate;
1287 		}
1288 		break;
1289 	default:
1290 delegate:
1291 		if (req.wLength == 0)   /* no data phase */
1292 			ci->ep0_dir = TX;
1293 
1294 		spin_unlock(&ci->lock);
1295 		err = ci->driver->setup(&ci->gadget, &req);
1296 		spin_lock(&ci->lock);
1297 		break;
1298 	}
1299 
1300 	if (err < 0) {
1301 		spin_unlock(&ci->lock);
1302 		if (_ep_set_halt(&hwep->ep, 1, false))
1303 			dev_err(ci->dev, "error: _ep_set_halt\n");
1304 		spin_lock(&ci->lock);
1305 	}
1306 }
1307 
1308 /**
1309  * isr_tr_complete_handler: transaction complete interrupt handler
1310  * @ci: UDC descriptor
1311  *
1312  * This function handles traffic events
1313  */
1314 static void isr_tr_complete_handler(struct ci_hdrc *ci)
1315 __releases(ci->lock)
1316 __acquires(ci->lock)
1317 {
1318 	unsigned i;
1319 	int err;
1320 
1321 	for (i = 0; i < ci->hw_ep_max; i++) {
1322 		struct ci_hw_ep *hwep  = &ci->ci_hw_ep[i];
1323 
1324 		if (hwep->ep.desc == NULL)
1325 			continue;   /* not configured */
1326 
1327 		if (hw_test_and_clear_complete(ci, i)) {
1328 			err = isr_tr_complete_low(hwep);
1329 			if (hwep->type == USB_ENDPOINT_XFER_CONTROL) {
1330 				if (err > 0)   /* needs status phase */
1331 					err = isr_setup_status_phase(ci);
1332 				if (err < 0) {
1333 					spin_unlock(&ci->lock);
1334 					if (_ep_set_halt(&hwep->ep, 1, false))
1335 						dev_err(ci->dev,
1336 						"error: _ep_set_halt\n");
1337 					spin_lock(&ci->lock);
1338 				}
1339 			}
1340 		}
1341 
1342 		/* Only handle setup packet below */
1343 		if (i == 0 &&
1344 			hw_test_and_clear(ci, OP_ENDPTSETUPSTAT, BIT(0)))
1345 			isr_setup_packet_handler(ci);
1346 	}
1347 }
1348 
1349 /******************************************************************************
1350  * ENDPT block
1351  *****************************************************************************/
1352 /*
1353  * ep_enable: configure endpoint, making it usable
1354  *
1355  * Check usb_ep_enable() at "usb_gadget.h" for details
1356  */
1357 static int ep_enable(struct usb_ep *ep,
1358 		     const struct usb_endpoint_descriptor *desc)
1359 {
1360 	struct ci_hw_ep *hwep = container_of(ep, struct ci_hw_ep, ep);
1361 	int retval = 0;
1362 	unsigned long flags;
1363 	u32 cap = 0;
1364 
1365 	if (ep == NULL || desc == NULL)
1366 		return -EINVAL;
1367 
1368 	spin_lock_irqsave(hwep->lock, flags);
1369 
1370 	/* only internal SW should enable ctrl endpts */
1371 
1372 	if (!list_empty(&hwep->qh.queue)) {
1373 		dev_warn(hwep->ci->dev, "enabling a non-empty endpoint!\n");
1374 		spin_unlock_irqrestore(hwep->lock, flags);
1375 		return -EBUSY;
1376 	}
1377 
1378 	hwep->ep.desc = desc;
1379 
1380 	hwep->dir  = usb_endpoint_dir_in(desc) ? TX : RX;
1381 	hwep->num  = usb_endpoint_num(desc);
1382 	hwep->type = usb_endpoint_type(desc);
1383 
1384 	hwep->ep.maxpacket = usb_endpoint_maxp(desc);
1385 	hwep->ep.mult = usb_endpoint_maxp_mult(desc);
1386 
1387 	if (hwep->type == USB_ENDPOINT_XFER_CONTROL)
1388 		cap |= QH_IOS;
1389 
1390 	cap |= QH_ZLT;
1391 	cap |= (hwep->ep.maxpacket << __ffs(QH_MAX_PKT)) & QH_MAX_PKT;
1392 	/*
1393 	 * For ISO-TX, we set mult at QH as the largest value, and use
1394 	 * MultO at TD as real mult value.
1395 	 */
1396 	if (hwep->type == USB_ENDPOINT_XFER_ISOC && hwep->dir == TX)
1397 		cap |= 3 << __ffs(QH_MULT);
1398 
1399 	hwep->qh.ptr->cap = cpu_to_le32(cap);
1400 
1401 	hwep->qh.ptr->td.next |= cpu_to_le32(TD_TERMINATE);   /* needed? */
1402 
1403 	if (hwep->num != 0 && hwep->type == USB_ENDPOINT_XFER_CONTROL) {
1404 		dev_err(hwep->ci->dev, "Set control xfer at non-ep0\n");
1405 		retval = -EINVAL;
1406 	}
1407 
1408 	/*
1409 	 * Enable endpoints in the HW other than ep0 as ep0
1410 	 * is always enabled
1411 	 */
1412 	if (hwep->num)
1413 		retval |= hw_ep_enable(hwep->ci, hwep->num, hwep->dir,
1414 				       hwep->type);
1415 
1416 	spin_unlock_irqrestore(hwep->lock, flags);
1417 	return retval;
1418 }
1419 
1420 /*
1421  * ep_disable: endpoint is no longer usable
1422  *
1423  * Check usb_ep_disable() at "usb_gadget.h" for details
1424  */
1425 static int ep_disable(struct usb_ep *ep)
1426 {
1427 	struct ci_hw_ep *hwep = container_of(ep, struct ci_hw_ep, ep);
1428 	int direction, retval = 0;
1429 	unsigned long flags;
1430 
1431 	if (ep == NULL)
1432 		return -EINVAL;
1433 	else if (hwep->ep.desc == NULL)
1434 		return -EBUSY;
1435 
1436 	spin_lock_irqsave(hwep->lock, flags);
1437 	if (hwep->ci->gadget.speed == USB_SPEED_UNKNOWN) {
1438 		spin_unlock_irqrestore(hwep->lock, flags);
1439 		return 0;
1440 	}
1441 
1442 	/* only internal SW should disable ctrl endpts */
1443 
1444 	direction = hwep->dir;
1445 	do {
1446 		retval |= _ep_nuke(hwep);
1447 		retval |= hw_ep_disable(hwep->ci, hwep->num, hwep->dir);
1448 
1449 		if (hwep->type == USB_ENDPOINT_XFER_CONTROL)
1450 			hwep->dir = (hwep->dir == TX) ? RX : TX;
1451 
1452 	} while (hwep->dir != direction);
1453 
1454 	hwep->ep.desc = NULL;
1455 
1456 	spin_unlock_irqrestore(hwep->lock, flags);
1457 	return retval;
1458 }
1459 
1460 /*
1461  * ep_alloc_request: allocate a request object to use with this endpoint
1462  *
1463  * Check usb_ep_alloc_request() at "usb_gadget.h" for details
1464  */
1465 static struct usb_request *ep_alloc_request(struct usb_ep *ep, gfp_t gfp_flags)
1466 {
1467 	struct ci_hw_req *hwreq;
1468 
1469 	if (ep == NULL)
1470 		return NULL;
1471 
1472 	hwreq = kzalloc(sizeof(struct ci_hw_req), gfp_flags);
1473 	if (hwreq != NULL) {
1474 		INIT_LIST_HEAD(&hwreq->queue);
1475 		INIT_LIST_HEAD(&hwreq->tds);
1476 	}
1477 
1478 	return (hwreq == NULL) ? NULL : &hwreq->req;
1479 }
1480 
1481 /*
1482  * ep_free_request: frees a request object
1483  *
1484  * Check usb_ep_free_request() at "usb_gadget.h" for details
1485  */
1486 static void ep_free_request(struct usb_ep *ep, struct usb_request *req)
1487 {
1488 	struct ci_hw_ep  *hwep  = container_of(ep,  struct ci_hw_ep, ep);
1489 	struct ci_hw_req *hwreq = container_of(req, struct ci_hw_req, req);
1490 	struct td_node *node, *tmpnode;
1491 	unsigned long flags;
1492 
1493 	if (ep == NULL || req == NULL) {
1494 		return;
1495 	} else if (!list_empty(&hwreq->queue)) {
1496 		dev_err(hwep->ci->dev, "freeing queued request\n");
1497 		return;
1498 	}
1499 
1500 	spin_lock_irqsave(hwep->lock, flags);
1501 
1502 	list_for_each_entry_safe(node, tmpnode, &hwreq->tds, td) {
1503 		dma_pool_free(hwep->td_pool, node->ptr, node->dma);
1504 		list_del_init(&node->td);
1505 		node->ptr = NULL;
1506 		kfree(node);
1507 	}
1508 
1509 	kfree(hwreq);
1510 
1511 	spin_unlock_irqrestore(hwep->lock, flags);
1512 }
1513 
1514 /*
1515  * ep_queue: queues (submits) an I/O request to an endpoint
1516  *
1517  * Check usb_ep_queue()* at usb_gadget.h" for details
1518  */
1519 static int ep_queue(struct usb_ep *ep, struct usb_request *req,
1520 		    gfp_t __maybe_unused gfp_flags)
1521 {
1522 	struct ci_hw_ep  *hwep  = container_of(ep,  struct ci_hw_ep, ep);
1523 	int retval = 0;
1524 	unsigned long flags;
1525 
1526 	if (ep == NULL || req == NULL || hwep->ep.desc == NULL)
1527 		return -EINVAL;
1528 
1529 	spin_lock_irqsave(hwep->lock, flags);
1530 	if (hwep->ci->gadget.speed == USB_SPEED_UNKNOWN) {
1531 		spin_unlock_irqrestore(hwep->lock, flags);
1532 		return 0;
1533 	}
1534 	retval = _ep_queue(ep, req, gfp_flags);
1535 	spin_unlock_irqrestore(hwep->lock, flags);
1536 	return retval;
1537 }
1538 
1539 /*
1540  * ep_dequeue: dequeues (cancels, unlinks) an I/O request from an endpoint
1541  *
1542  * Check usb_ep_dequeue() at "usb_gadget.h" for details
1543  */
1544 static int ep_dequeue(struct usb_ep *ep, struct usb_request *req)
1545 {
1546 	struct ci_hw_ep  *hwep  = container_of(ep,  struct ci_hw_ep, ep);
1547 	struct ci_hw_req *hwreq = container_of(req, struct ci_hw_req, req);
1548 	unsigned long flags;
1549 	struct td_node *node, *tmpnode;
1550 
1551 	if (ep == NULL || req == NULL || hwreq->req.status != -EALREADY ||
1552 		hwep->ep.desc == NULL || list_empty(&hwreq->queue) ||
1553 		list_empty(&hwep->qh.queue))
1554 		return -EINVAL;
1555 
1556 	spin_lock_irqsave(hwep->lock, flags);
1557 	if (hwep->ci->gadget.speed != USB_SPEED_UNKNOWN)
1558 		hw_ep_flush(hwep->ci, hwep->num, hwep->dir);
1559 
1560 	list_for_each_entry_safe(node, tmpnode, &hwreq->tds, td) {
1561 		dma_pool_free(hwep->td_pool, node->ptr, node->dma);
1562 		list_del(&node->td);
1563 		kfree(node);
1564 	}
1565 
1566 	/* pop request */
1567 	list_del_init(&hwreq->queue);
1568 
1569 	usb_gadget_unmap_request(&hwep->ci->gadget, req, hwep->dir);
1570 
1571 	req->status = -ECONNRESET;
1572 
1573 	if (hwreq->req.complete != NULL) {
1574 		spin_unlock(hwep->lock);
1575 		usb_gadget_giveback_request(&hwep->ep, &hwreq->req);
1576 		spin_lock(hwep->lock);
1577 	}
1578 
1579 	spin_unlock_irqrestore(hwep->lock, flags);
1580 	return 0;
1581 }
1582 
1583 /*
1584  * ep_set_halt: sets the endpoint halt feature
1585  *
1586  * Check usb_ep_set_halt() at "usb_gadget.h" for details
1587  */
1588 static int ep_set_halt(struct usb_ep *ep, int value)
1589 {
1590 	return _ep_set_halt(ep, value, true);
1591 }
1592 
1593 /*
1594  * ep_set_wedge: sets the halt feature and ignores clear requests
1595  *
1596  * Check usb_ep_set_wedge() at "usb_gadget.h" for details
1597  */
1598 static int ep_set_wedge(struct usb_ep *ep)
1599 {
1600 	struct ci_hw_ep *hwep = container_of(ep, struct ci_hw_ep, ep);
1601 	unsigned long flags;
1602 
1603 	if (ep == NULL || hwep->ep.desc == NULL)
1604 		return -EINVAL;
1605 
1606 	spin_lock_irqsave(hwep->lock, flags);
1607 	hwep->wedge = 1;
1608 	spin_unlock_irqrestore(hwep->lock, flags);
1609 
1610 	return usb_ep_set_halt(ep);
1611 }
1612 
1613 /*
1614  * ep_fifo_flush: flushes contents of a fifo
1615  *
1616  * Check usb_ep_fifo_flush() at "usb_gadget.h" for details
1617  */
1618 static void ep_fifo_flush(struct usb_ep *ep)
1619 {
1620 	struct ci_hw_ep *hwep = container_of(ep, struct ci_hw_ep, ep);
1621 	unsigned long flags;
1622 
1623 	if (ep == NULL) {
1624 		dev_err(hwep->ci->dev, "%02X: -EINVAL\n", _usb_addr(hwep));
1625 		return;
1626 	}
1627 
1628 	spin_lock_irqsave(hwep->lock, flags);
1629 	if (hwep->ci->gadget.speed == USB_SPEED_UNKNOWN) {
1630 		spin_unlock_irqrestore(hwep->lock, flags);
1631 		return;
1632 	}
1633 
1634 	hw_ep_flush(hwep->ci, hwep->num, hwep->dir);
1635 
1636 	spin_unlock_irqrestore(hwep->lock, flags);
1637 }
1638 
1639 /*
1640  * Endpoint-specific part of the API to the USB controller hardware
1641  * Check "usb_gadget.h" for details
1642  */
1643 static const struct usb_ep_ops usb_ep_ops = {
1644 	.enable	       = ep_enable,
1645 	.disable       = ep_disable,
1646 	.alloc_request = ep_alloc_request,
1647 	.free_request  = ep_free_request,
1648 	.queue	       = ep_queue,
1649 	.dequeue       = ep_dequeue,
1650 	.set_halt      = ep_set_halt,
1651 	.set_wedge     = ep_set_wedge,
1652 	.fifo_flush    = ep_fifo_flush,
1653 };
1654 
1655 /******************************************************************************
1656  * GADGET block
1657  *****************************************************************************/
1658 
1659 static int ci_udc_get_frame(struct usb_gadget *_gadget)
1660 {
1661 	struct ci_hdrc *ci = container_of(_gadget, struct ci_hdrc, gadget);
1662 	unsigned long flags;
1663 	int ret;
1664 
1665 	spin_lock_irqsave(&ci->lock, flags);
1666 	ret = hw_read(ci, OP_FRINDEX, 0x3fff);
1667 	spin_unlock_irqrestore(&ci->lock, flags);
1668 	return ret >> 3;
1669 }
1670 
1671 /*
1672  * ci_hdrc_gadget_connect: caller makes sure gadget driver is binded
1673  */
1674 static void ci_hdrc_gadget_connect(struct usb_gadget *_gadget, int is_active)
1675 {
1676 	struct ci_hdrc *ci = container_of(_gadget, struct ci_hdrc, gadget);
1677 
1678 	if (is_active) {
1679 		pm_runtime_get_sync(ci->dev);
1680 		hw_device_reset(ci);
1681 		spin_lock_irq(&ci->lock);
1682 		if (ci->driver) {
1683 			hw_device_state(ci, ci->ep0out->qh.dma);
1684 			usb_gadget_set_state(_gadget, USB_STATE_POWERED);
1685 			spin_unlock_irq(&ci->lock);
1686 			usb_udc_vbus_handler(_gadget, true);
1687 		} else {
1688 			spin_unlock_irq(&ci->lock);
1689 		}
1690 	} else {
1691 		usb_udc_vbus_handler(_gadget, false);
1692 		if (ci->driver)
1693 			ci->driver->disconnect(&ci->gadget);
1694 		hw_device_state(ci, 0);
1695 		if (ci->platdata->notify_event)
1696 			ci->platdata->notify_event(ci,
1697 			CI_HDRC_CONTROLLER_STOPPED_EVENT);
1698 		_gadget_stop_activity(&ci->gadget);
1699 		pm_runtime_put_sync(ci->dev);
1700 		usb_gadget_set_state(_gadget, USB_STATE_NOTATTACHED);
1701 	}
1702 }
1703 
1704 static int ci_udc_vbus_session(struct usb_gadget *_gadget, int is_active)
1705 {
1706 	struct ci_hdrc *ci = container_of(_gadget, struct ci_hdrc, gadget);
1707 	unsigned long flags;
1708 	int ret = 0;
1709 
1710 	spin_lock_irqsave(&ci->lock, flags);
1711 	ci->vbus_active = is_active;
1712 	spin_unlock_irqrestore(&ci->lock, flags);
1713 
1714 	if (ci->usb_phy)
1715 		usb_phy_set_charger_state(ci->usb_phy, is_active ?
1716 			USB_CHARGER_PRESENT : USB_CHARGER_ABSENT);
1717 
1718 	if (ci->platdata->notify_event)
1719 		ret = ci->platdata->notify_event(ci,
1720 				CI_HDRC_CONTROLLER_VBUS_EVENT);
1721 
1722 	if (ci->usb_phy) {
1723 		if (is_active)
1724 			usb_phy_set_event(ci->usb_phy, USB_EVENT_VBUS);
1725 		else
1726 			usb_phy_set_event(ci->usb_phy, USB_EVENT_NONE);
1727 	}
1728 
1729 	if (ci->driver)
1730 		ci_hdrc_gadget_connect(_gadget, is_active);
1731 
1732 	return ret;
1733 }
1734 
1735 static int ci_udc_wakeup(struct usb_gadget *_gadget)
1736 {
1737 	struct ci_hdrc *ci = container_of(_gadget, struct ci_hdrc, gadget);
1738 	unsigned long flags;
1739 	int ret = 0;
1740 
1741 	spin_lock_irqsave(&ci->lock, flags);
1742 	if (ci->gadget.speed == USB_SPEED_UNKNOWN) {
1743 		spin_unlock_irqrestore(&ci->lock, flags);
1744 		return 0;
1745 	}
1746 	if (!ci->remote_wakeup) {
1747 		ret = -EOPNOTSUPP;
1748 		goto out;
1749 	}
1750 	if (!hw_read(ci, OP_PORTSC, PORTSC_SUSP)) {
1751 		ret = -EINVAL;
1752 		goto out;
1753 	}
1754 	hw_write(ci, OP_PORTSC, PORTSC_FPR, PORTSC_FPR);
1755 out:
1756 	spin_unlock_irqrestore(&ci->lock, flags);
1757 	return ret;
1758 }
1759 
1760 static int ci_udc_vbus_draw(struct usb_gadget *_gadget, unsigned ma)
1761 {
1762 	struct ci_hdrc *ci = container_of(_gadget, struct ci_hdrc, gadget);
1763 
1764 	if (ci->usb_phy)
1765 		return usb_phy_set_power(ci->usb_phy, ma);
1766 	return -ENOTSUPP;
1767 }
1768 
1769 static int ci_udc_selfpowered(struct usb_gadget *_gadget, int is_on)
1770 {
1771 	struct ci_hdrc *ci = container_of(_gadget, struct ci_hdrc, gadget);
1772 	struct ci_hw_ep *hwep = ci->ep0in;
1773 	unsigned long flags;
1774 
1775 	spin_lock_irqsave(hwep->lock, flags);
1776 	_gadget->is_selfpowered = (is_on != 0);
1777 	spin_unlock_irqrestore(hwep->lock, flags);
1778 
1779 	return 0;
1780 }
1781 
1782 /* Change Data+ pullup status
1783  * this func is used by usb_gadget_connect/disconnect
1784  */
1785 static int ci_udc_pullup(struct usb_gadget *_gadget, int is_on)
1786 {
1787 	struct ci_hdrc *ci = container_of(_gadget, struct ci_hdrc, gadget);
1788 
1789 	/*
1790 	 * Data+ pullup controlled by OTG state machine in OTG fsm mode;
1791 	 * and don't touch Data+ in host mode for dual role config.
1792 	 */
1793 	if (ci_otg_is_fsm_mode(ci) || ci->role == CI_ROLE_HOST)
1794 		return 0;
1795 
1796 	pm_runtime_get_sync(ci->dev);
1797 	if (is_on)
1798 		hw_write(ci, OP_USBCMD, USBCMD_RS, USBCMD_RS);
1799 	else
1800 		hw_write(ci, OP_USBCMD, USBCMD_RS, 0);
1801 	pm_runtime_put_sync(ci->dev);
1802 
1803 	return 0;
1804 }
1805 
1806 static int ci_udc_start(struct usb_gadget *gadget,
1807 			 struct usb_gadget_driver *driver);
1808 static int ci_udc_stop(struct usb_gadget *gadget);
1809 
1810 /* Match ISOC IN from the highest endpoint */
1811 static struct usb_ep *ci_udc_match_ep(struct usb_gadget *gadget,
1812 			      struct usb_endpoint_descriptor *desc,
1813 			      struct usb_ss_ep_comp_descriptor *comp_desc)
1814 {
1815 	struct ci_hdrc *ci = container_of(gadget, struct ci_hdrc, gadget);
1816 	struct usb_ep *ep;
1817 
1818 	if (usb_endpoint_xfer_isoc(desc) && usb_endpoint_dir_in(desc)) {
1819 		list_for_each_entry_reverse(ep, &ci->gadget.ep_list, ep_list) {
1820 			if (ep->caps.dir_in && !ep->claimed)
1821 				return ep;
1822 		}
1823 	}
1824 
1825 	return NULL;
1826 }
1827 
1828 /*
1829  * Device operations part of the API to the USB controller hardware,
1830  * which don't involve endpoints (or i/o)
1831  * Check  "usb_gadget.h" for details
1832  */
1833 static const struct usb_gadget_ops usb_gadget_ops = {
1834 	.get_frame	= ci_udc_get_frame,
1835 	.vbus_session	= ci_udc_vbus_session,
1836 	.wakeup		= ci_udc_wakeup,
1837 	.set_selfpowered	= ci_udc_selfpowered,
1838 	.pullup		= ci_udc_pullup,
1839 	.vbus_draw	= ci_udc_vbus_draw,
1840 	.udc_start	= ci_udc_start,
1841 	.udc_stop	= ci_udc_stop,
1842 	.match_ep 	= ci_udc_match_ep,
1843 };
1844 
1845 static int init_eps(struct ci_hdrc *ci)
1846 {
1847 	int retval = 0, i, j;
1848 
1849 	for (i = 0; i < ci->hw_ep_max/2; i++)
1850 		for (j = RX; j <= TX; j++) {
1851 			int k = i + j * ci->hw_ep_max/2;
1852 			struct ci_hw_ep *hwep = &ci->ci_hw_ep[k];
1853 
1854 			scnprintf(hwep->name, sizeof(hwep->name), "ep%i%s", i,
1855 					(j == TX)  ? "in" : "out");
1856 
1857 			hwep->ci          = ci;
1858 			hwep->lock         = &ci->lock;
1859 			hwep->td_pool      = ci->td_pool;
1860 
1861 			hwep->ep.name      = hwep->name;
1862 			hwep->ep.ops       = &usb_ep_ops;
1863 
1864 			if (i == 0) {
1865 				hwep->ep.caps.type_control = true;
1866 			} else {
1867 				hwep->ep.caps.type_iso = true;
1868 				hwep->ep.caps.type_bulk = true;
1869 				hwep->ep.caps.type_int = true;
1870 			}
1871 
1872 			if (j == TX)
1873 				hwep->ep.caps.dir_in = true;
1874 			else
1875 				hwep->ep.caps.dir_out = true;
1876 
1877 			/*
1878 			 * for ep0: maxP defined in desc, for other
1879 			 * eps, maxP is set by epautoconfig() called
1880 			 * by gadget layer
1881 			 */
1882 			usb_ep_set_maxpacket_limit(&hwep->ep, (unsigned short)~0);
1883 
1884 			INIT_LIST_HEAD(&hwep->qh.queue);
1885 			hwep->qh.ptr = dma_pool_zalloc(ci->qh_pool, GFP_KERNEL,
1886 						       &hwep->qh.dma);
1887 			if (hwep->qh.ptr == NULL)
1888 				retval = -ENOMEM;
1889 
1890 			/*
1891 			 * set up shorthands for ep0 out and in endpoints,
1892 			 * don't add to gadget's ep_list
1893 			 */
1894 			if (i == 0) {
1895 				if (j == RX)
1896 					ci->ep0out = hwep;
1897 				else
1898 					ci->ep0in = hwep;
1899 
1900 				usb_ep_set_maxpacket_limit(&hwep->ep, CTRL_PAYLOAD_MAX);
1901 				continue;
1902 			}
1903 
1904 			list_add_tail(&hwep->ep.ep_list, &ci->gadget.ep_list);
1905 		}
1906 
1907 	return retval;
1908 }
1909 
1910 static void destroy_eps(struct ci_hdrc *ci)
1911 {
1912 	int i;
1913 
1914 	for (i = 0; i < ci->hw_ep_max; i++) {
1915 		struct ci_hw_ep *hwep = &ci->ci_hw_ep[i];
1916 
1917 		if (hwep->pending_td)
1918 			free_pending_td(hwep);
1919 		dma_pool_free(ci->qh_pool, hwep->qh.ptr, hwep->qh.dma);
1920 	}
1921 }
1922 
1923 /**
1924  * ci_udc_start: register a gadget driver
1925  * @gadget: our gadget
1926  * @driver: the driver being registered
1927  *
1928  * Interrupts are enabled here.
1929  */
1930 static int ci_udc_start(struct usb_gadget *gadget,
1931 			 struct usb_gadget_driver *driver)
1932 {
1933 	struct ci_hdrc *ci = container_of(gadget, struct ci_hdrc, gadget);
1934 	int retval;
1935 
1936 	if (driver->disconnect == NULL)
1937 		return -EINVAL;
1938 
1939 	ci->ep0out->ep.desc = &ctrl_endpt_out_desc;
1940 	retval = usb_ep_enable(&ci->ep0out->ep);
1941 	if (retval)
1942 		return retval;
1943 
1944 	ci->ep0in->ep.desc = &ctrl_endpt_in_desc;
1945 	retval = usb_ep_enable(&ci->ep0in->ep);
1946 	if (retval)
1947 		return retval;
1948 
1949 	ci->driver = driver;
1950 
1951 	/* Start otg fsm for B-device */
1952 	if (ci_otg_is_fsm_mode(ci) && ci->fsm.id) {
1953 		ci_hdrc_otg_fsm_start(ci);
1954 		return retval;
1955 	}
1956 
1957 	if (ci->vbus_active)
1958 		ci_hdrc_gadget_connect(gadget, 1);
1959 	else
1960 		usb_udc_vbus_handler(&ci->gadget, false);
1961 
1962 	return retval;
1963 }
1964 
1965 static void ci_udc_stop_for_otg_fsm(struct ci_hdrc *ci)
1966 {
1967 	if (!ci_otg_is_fsm_mode(ci))
1968 		return;
1969 
1970 	mutex_lock(&ci->fsm.lock);
1971 	if (ci->fsm.otg->state == OTG_STATE_A_PERIPHERAL) {
1972 		ci->fsm.a_bidl_adis_tmout = 1;
1973 		ci_hdrc_otg_fsm_start(ci);
1974 	} else if (ci->fsm.otg->state == OTG_STATE_B_PERIPHERAL) {
1975 		ci->fsm.protocol = PROTO_UNDEF;
1976 		ci->fsm.otg->state = OTG_STATE_UNDEFINED;
1977 	}
1978 	mutex_unlock(&ci->fsm.lock);
1979 }
1980 
1981 /*
1982  * ci_udc_stop: unregister a gadget driver
1983  */
1984 static int ci_udc_stop(struct usb_gadget *gadget)
1985 {
1986 	struct ci_hdrc *ci = container_of(gadget, struct ci_hdrc, gadget);
1987 	unsigned long flags;
1988 
1989 	spin_lock_irqsave(&ci->lock, flags);
1990 	ci->driver = NULL;
1991 
1992 	if (ci->vbus_active) {
1993 		hw_device_state(ci, 0);
1994 		spin_unlock_irqrestore(&ci->lock, flags);
1995 		if (ci->platdata->notify_event)
1996 			ci->platdata->notify_event(ci,
1997 			CI_HDRC_CONTROLLER_STOPPED_EVENT);
1998 		_gadget_stop_activity(&ci->gadget);
1999 		spin_lock_irqsave(&ci->lock, flags);
2000 		pm_runtime_put(ci->dev);
2001 	}
2002 
2003 	spin_unlock_irqrestore(&ci->lock, flags);
2004 
2005 	ci_udc_stop_for_otg_fsm(ci);
2006 	return 0;
2007 }
2008 
2009 /******************************************************************************
2010  * BUS block
2011  *****************************************************************************/
2012 /*
2013  * udc_irq: ci interrupt handler
2014  *
2015  * This function returns IRQ_HANDLED if the IRQ has been handled
2016  * It locks access to registers
2017  */
2018 static irqreturn_t udc_irq(struct ci_hdrc *ci)
2019 {
2020 	irqreturn_t retval;
2021 	u32 intr;
2022 
2023 	if (ci == NULL)
2024 		return IRQ_HANDLED;
2025 
2026 	spin_lock(&ci->lock);
2027 
2028 	if (ci->platdata->flags & CI_HDRC_REGS_SHARED) {
2029 		if (hw_read(ci, OP_USBMODE, USBMODE_CM) !=
2030 				USBMODE_CM_DC) {
2031 			spin_unlock(&ci->lock);
2032 			return IRQ_NONE;
2033 		}
2034 	}
2035 	intr = hw_test_and_clear_intr_active(ci);
2036 
2037 	if (intr) {
2038 		/* order defines priority - do NOT change it */
2039 		if (USBi_URI & intr)
2040 			isr_reset_handler(ci);
2041 
2042 		if (USBi_PCI & intr) {
2043 			ci->gadget.speed = hw_port_is_high_speed(ci) ?
2044 				USB_SPEED_HIGH : USB_SPEED_FULL;
2045 			if (ci->usb_phy)
2046 				usb_phy_set_event(ci->usb_phy,
2047 					USB_EVENT_ENUMERATED);
2048 			if (ci->suspended) {
2049 				if (ci->driver->resume) {
2050 					spin_unlock(&ci->lock);
2051 					ci->driver->resume(&ci->gadget);
2052 					spin_lock(&ci->lock);
2053 				}
2054 				ci->suspended = 0;
2055 				usb_gadget_set_state(&ci->gadget,
2056 						ci->resume_state);
2057 			}
2058 		}
2059 
2060 		if (USBi_UI  & intr)
2061 			isr_tr_complete_handler(ci);
2062 
2063 		if ((USBi_SLI & intr) && !(ci->suspended)) {
2064 			ci->suspended = 1;
2065 			ci->resume_state = ci->gadget.state;
2066 			if (ci->gadget.speed != USB_SPEED_UNKNOWN &&
2067 			    ci->driver->suspend) {
2068 				spin_unlock(&ci->lock);
2069 				ci->driver->suspend(&ci->gadget);
2070 				spin_lock(&ci->lock);
2071 			}
2072 			usb_gadget_set_state(&ci->gadget,
2073 					USB_STATE_SUSPENDED);
2074 		}
2075 		retval = IRQ_HANDLED;
2076 	} else {
2077 		retval = IRQ_NONE;
2078 	}
2079 	spin_unlock(&ci->lock);
2080 
2081 	return retval;
2082 }
2083 
2084 /**
2085  * udc_start: initialize gadget role
2086  * @ci: chipidea controller
2087  */
2088 static int udc_start(struct ci_hdrc *ci)
2089 {
2090 	struct device *dev = ci->dev;
2091 	struct usb_otg_caps *otg_caps = &ci->platdata->ci_otg_caps;
2092 	int retval = 0;
2093 
2094 	ci->gadget.ops          = &usb_gadget_ops;
2095 	ci->gadget.speed        = USB_SPEED_UNKNOWN;
2096 	ci->gadget.max_speed    = USB_SPEED_HIGH;
2097 	ci->gadget.name         = ci->platdata->name;
2098 	ci->gadget.otg_caps	= otg_caps;
2099 	ci->gadget.sg_supported = 1;
2100 	ci->gadget.irq		= ci->irq;
2101 
2102 	if (ci->platdata->flags & CI_HDRC_REQUIRES_ALIGNED_DMA)
2103 		ci->gadget.quirk_avoids_skb_reserve = 1;
2104 
2105 	if (ci->is_otg && (otg_caps->hnp_support || otg_caps->srp_support ||
2106 						otg_caps->adp_support))
2107 		ci->gadget.is_otg = 1;
2108 
2109 	INIT_LIST_HEAD(&ci->gadget.ep_list);
2110 
2111 	/* alloc resources */
2112 	ci->qh_pool = dma_pool_create("ci_hw_qh", dev->parent,
2113 				       sizeof(struct ci_hw_qh),
2114 				       64, CI_HDRC_PAGE_SIZE);
2115 	if (ci->qh_pool == NULL)
2116 		return -ENOMEM;
2117 
2118 	ci->td_pool = dma_pool_create("ci_hw_td", dev->parent,
2119 				       sizeof(struct ci_hw_td),
2120 				       64, CI_HDRC_PAGE_SIZE);
2121 	if (ci->td_pool == NULL) {
2122 		retval = -ENOMEM;
2123 		goto free_qh_pool;
2124 	}
2125 
2126 	retval = init_eps(ci);
2127 	if (retval)
2128 		goto free_pools;
2129 
2130 	ci->gadget.ep0 = &ci->ep0in->ep;
2131 
2132 	retval = usb_add_gadget_udc(dev, &ci->gadget);
2133 	if (retval)
2134 		goto destroy_eps;
2135 
2136 	return retval;
2137 
2138 destroy_eps:
2139 	destroy_eps(ci);
2140 free_pools:
2141 	dma_pool_destroy(ci->td_pool);
2142 free_qh_pool:
2143 	dma_pool_destroy(ci->qh_pool);
2144 	return retval;
2145 }
2146 
2147 /*
2148  * ci_hdrc_gadget_destroy: parent remove must call this to remove UDC
2149  *
2150  * No interrupts active, the IRQ has been released
2151  */
2152 void ci_hdrc_gadget_destroy(struct ci_hdrc *ci)
2153 {
2154 	if (!ci->roles[CI_ROLE_GADGET])
2155 		return;
2156 
2157 	usb_del_gadget_udc(&ci->gadget);
2158 
2159 	destroy_eps(ci);
2160 
2161 	dma_pool_destroy(ci->td_pool);
2162 	dma_pool_destroy(ci->qh_pool);
2163 }
2164 
2165 static int udc_id_switch_for_device(struct ci_hdrc *ci)
2166 {
2167 	if (ci->platdata->pins_device)
2168 		pinctrl_select_state(ci->platdata->pctl,
2169 				     ci->platdata->pins_device);
2170 
2171 	if (ci->is_otg)
2172 		/* Clear and enable BSV irq */
2173 		hw_write_otgsc(ci, OTGSC_BSVIS | OTGSC_BSVIE,
2174 					OTGSC_BSVIS | OTGSC_BSVIE);
2175 
2176 	return 0;
2177 }
2178 
2179 static void udc_id_switch_for_host(struct ci_hdrc *ci)
2180 {
2181 	/*
2182 	 * host doesn't care B_SESSION_VALID event
2183 	 * so clear and disable BSV irq
2184 	 */
2185 	if (ci->is_otg)
2186 		hw_write_otgsc(ci, OTGSC_BSVIE | OTGSC_BSVIS, OTGSC_BSVIS);
2187 
2188 	ci->vbus_active = 0;
2189 
2190 	if (ci->platdata->pins_device && ci->platdata->pins_default)
2191 		pinctrl_select_state(ci->platdata->pctl,
2192 				     ci->platdata->pins_default);
2193 }
2194 
2195 #ifdef CONFIG_PM_SLEEP
2196 static void udc_suspend(struct ci_hdrc *ci)
2197 {
2198 	/*
2199 	 * Set OP_ENDPTLISTADDR to be non-zero for
2200 	 * checking if controller resume from power lost
2201 	 * in non-host mode.
2202 	 */
2203 	if (hw_read(ci, OP_ENDPTLISTADDR, ~0) == 0)
2204 		hw_write(ci, OP_ENDPTLISTADDR, ~0, ~0);
2205 }
2206 
2207 static void udc_resume(struct ci_hdrc *ci, bool power_lost)
2208 {
2209 	if (power_lost) {
2210 		if (ci->is_otg)
2211 			hw_write_otgsc(ci, OTGSC_BSVIS | OTGSC_BSVIE,
2212 					OTGSC_BSVIS | OTGSC_BSVIE);
2213 		if (ci->vbus_active)
2214 			usb_gadget_vbus_disconnect(&ci->gadget);
2215 	}
2216 
2217 	/* Restore value 0 if it was set for power lost check */
2218 	if (hw_read(ci, OP_ENDPTLISTADDR, ~0) == 0xFFFFFFFF)
2219 		hw_write(ci, OP_ENDPTLISTADDR, ~0, 0);
2220 }
2221 #endif
2222 
2223 /**
2224  * ci_hdrc_gadget_init - initialize device related bits
2225  * @ci: the controller
2226  *
2227  * This function initializes the gadget, if the device is "device capable".
2228  */
2229 int ci_hdrc_gadget_init(struct ci_hdrc *ci)
2230 {
2231 	struct ci_role_driver *rdrv;
2232 	int ret;
2233 
2234 	if (!hw_read(ci, CAP_DCCPARAMS, DCCPARAMS_DC))
2235 		return -ENXIO;
2236 
2237 	rdrv = devm_kzalloc(ci->dev, sizeof(*rdrv), GFP_KERNEL);
2238 	if (!rdrv)
2239 		return -ENOMEM;
2240 
2241 	rdrv->start	= udc_id_switch_for_device;
2242 	rdrv->stop	= udc_id_switch_for_host;
2243 #ifdef CONFIG_PM_SLEEP
2244 	rdrv->suspend	= udc_suspend;
2245 	rdrv->resume	= udc_resume;
2246 #endif
2247 	rdrv->irq	= udc_irq;
2248 	rdrv->name	= "gadget";
2249 
2250 	ret = udc_start(ci);
2251 	if (!ret)
2252 		ci->roles[CI_ROLE_GADGET] = rdrv;
2253 
2254 	return ret;
2255 }
2256