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