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