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