Merge branch 'fixes' of http://ftp.arm.linux.org.uk/pub/linux/arm/kernel/git-cur...
[pandora-kernel.git] / drivers / usb / gadget / fsl_udc_core.c
1 /*
2  * Copyright (C) 2004-2007,2011 Freescale Semiconductor, Inc.
3  * All rights reserved.
4  *
5  * Author: Li Yang <leoli@freescale.com>
6  *         Jiang Bo <tanya.jiang@freescale.com>
7  *
8  * Description:
9  * Freescale high-speed USB SOC DR module device controller driver.
10  * This can be found on MPC8349E/MPC8313E/MPC5121E cpus.
11  * The driver is previously named as mpc_udc.  Based on bare board
12  * code from Dave Liu and Shlomi Gridish.
13  *
14  * This program is free software; you can redistribute  it and/or modify it
15  * under  the terms of  the GNU General  Public License as published by the
16  * Free Software Foundation;  either version 2 of the  License, or (at your
17  * option) any later version.
18  */
19
20 #undef VERBOSE
21
22 #include <linux/module.h>
23 #include <linux/kernel.h>
24 #include <linux/ioport.h>
25 #include <linux/types.h>
26 #include <linux/errno.h>
27 #include <linux/slab.h>
28 #include <linux/init.h>
29 #include <linux/list.h>
30 #include <linux/interrupt.h>
31 #include <linux/proc_fs.h>
32 #include <linux/mm.h>
33 #include <linux/moduleparam.h>
34 #include <linux/device.h>
35 #include <linux/usb/ch9.h>
36 #include <linux/usb/gadget.h>
37 #include <linux/usb/otg.h>
38 #include <linux/dma-mapping.h>
39 #include <linux/platform_device.h>
40 #include <linux/fsl_devices.h>
41 #include <linux/dmapool.h>
42 #include <linux/delay.h>
43
44 #include <asm/byteorder.h>
45 #include <asm/io.h>
46 #include <asm/system.h>
47 #include <asm/unaligned.h>
48 #include <asm/dma.h>
49
50 #include "fsl_usb2_udc.h"
51
52 #define DRIVER_DESC     "Freescale High-Speed USB SOC Device Controller driver"
53 #define DRIVER_AUTHOR   "Li Yang/Jiang Bo"
54 #define DRIVER_VERSION  "Apr 20, 2007"
55
56 #define DMA_ADDR_INVALID        (~(dma_addr_t)0)
57
58 static const char driver_name[] = "fsl-usb2-udc";
59 static const char driver_desc[] = DRIVER_DESC;
60
61 static struct usb_dr_device *dr_regs;
62 #ifndef CONFIG_ARCH_MXC
63 static struct usb_sys_interface *usb_sys_regs;
64 #endif
65
66 /* it is initialized in probe()  */
67 static struct fsl_udc *udc_controller = NULL;
68
69 static const struct usb_endpoint_descriptor
70 fsl_ep0_desc = {
71         .bLength =              USB_DT_ENDPOINT_SIZE,
72         .bDescriptorType =      USB_DT_ENDPOINT,
73         .bEndpointAddress =     0,
74         .bmAttributes =         USB_ENDPOINT_XFER_CONTROL,
75         .wMaxPacketSize =       USB_MAX_CTRL_PAYLOAD,
76 };
77
78 static void fsl_ep_fifo_flush(struct usb_ep *_ep);
79
80 #ifdef CONFIG_PPC32
81 /*
82  * On some SoCs, the USB controller registers can be big or little endian,
83  * depending on the version of the chip. In order to be able to run the
84  * same kernel binary on 2 different versions of an SoC, the BE/LE decision
85  * must be made at run time. _fsl_readl and fsl_writel are pointers to the
86  * BE or LE readl() and writel() functions, and fsl_readl() and fsl_writel()
87  * call through those pointers. Platform code for SoCs that have BE USB
88  * registers should set pdata->big_endian_mmio flag.
89  *
90  * This also applies to controller-to-cpu accessors for the USB descriptors,
91  * since their endianness is also SoC dependant. Platform code for SoCs that
92  * have BE USB descriptors should set pdata->big_endian_desc flag.
93  */
94 static u32 _fsl_readl_be(const unsigned __iomem *p)
95 {
96         return in_be32(p);
97 }
98
99 static u32 _fsl_readl_le(const unsigned __iomem *p)
100 {
101         return in_le32(p);
102 }
103
104 static void _fsl_writel_be(u32 v, unsigned __iomem *p)
105 {
106         out_be32(p, v);
107 }
108
109 static void _fsl_writel_le(u32 v, unsigned __iomem *p)
110 {
111         out_le32(p, v);
112 }
113
114 static u32 (*_fsl_readl)(const unsigned __iomem *p);
115 static void (*_fsl_writel)(u32 v, unsigned __iomem *p);
116
117 #define fsl_readl(p)            (*_fsl_readl)((p))
118 #define fsl_writel(v, p)        (*_fsl_writel)((v), (p))
119
120 static inline void fsl_set_accessors(struct fsl_usb2_platform_data *pdata)
121 {
122         if (pdata->big_endian_mmio) {
123                 _fsl_readl = _fsl_readl_be;
124                 _fsl_writel = _fsl_writel_be;
125         } else {
126                 _fsl_readl = _fsl_readl_le;
127                 _fsl_writel = _fsl_writel_le;
128         }
129 }
130
131 static inline u32 cpu_to_hc32(const u32 x)
132 {
133         return udc_controller->pdata->big_endian_desc
134                 ? (__force u32)cpu_to_be32(x)
135                 : (__force u32)cpu_to_le32(x);
136 }
137
138 static inline u32 hc32_to_cpu(const u32 x)
139 {
140         return udc_controller->pdata->big_endian_desc
141                 ? be32_to_cpu((__force __be32)x)
142                 : le32_to_cpu((__force __le32)x);
143 }
144 #else /* !CONFIG_PPC32 */
145 static inline void fsl_set_accessors(struct fsl_usb2_platform_data *pdata) {}
146
147 #define fsl_readl(addr)         readl(addr)
148 #define fsl_writel(val32, addr) writel(val32, addr)
149 #define cpu_to_hc32(x)          cpu_to_le32(x)
150 #define hc32_to_cpu(x)          le32_to_cpu(x)
151 #endif /* CONFIG_PPC32 */
152
153 /********************************************************************
154  *      Internal Used Function
155 ********************************************************************/
156 /*-----------------------------------------------------------------
157  * done() - retire a request; caller blocked irqs
158  * @status : request status to be set, only works when
159  *      request is still in progress.
160  *--------------------------------------------------------------*/
161 static void done(struct fsl_ep *ep, struct fsl_req *req, int status)
162 {
163         struct fsl_udc *udc = NULL;
164         unsigned char stopped = ep->stopped;
165         struct ep_td_struct *curr_td, *next_td;
166         int j;
167
168         udc = (struct fsl_udc *)ep->udc;
169         /* Removed the req from fsl_ep->queue */
170         list_del_init(&req->queue);
171
172         /* req.status should be set as -EINPROGRESS in ep_queue() */
173         if (req->req.status == -EINPROGRESS)
174                 req->req.status = status;
175         else
176                 status = req->req.status;
177
178         /* Free dtd for the request */
179         next_td = req->head;
180         for (j = 0; j < req->dtd_count; j++) {
181                 curr_td = next_td;
182                 if (j != req->dtd_count - 1) {
183                         next_td = curr_td->next_td_virt;
184                 }
185                 dma_pool_free(udc->td_pool, curr_td, curr_td->td_dma);
186         }
187
188         if (req->mapped) {
189                 dma_unmap_single(ep->udc->gadget.dev.parent,
190                         req->req.dma, req->req.length,
191                         ep_is_in(ep)
192                                 ? DMA_TO_DEVICE
193                                 : DMA_FROM_DEVICE);
194                 req->req.dma = DMA_ADDR_INVALID;
195                 req->mapped = 0;
196         } else
197                 dma_sync_single_for_cpu(ep->udc->gadget.dev.parent,
198                         req->req.dma, req->req.length,
199                         ep_is_in(ep)
200                                 ? DMA_TO_DEVICE
201                                 : DMA_FROM_DEVICE);
202
203         if (status && (status != -ESHUTDOWN))
204                 VDBG("complete %s req %p stat %d len %u/%u",
205                         ep->ep.name, &req->req, status,
206                         req->req.actual, req->req.length);
207
208         ep->stopped = 1;
209
210         spin_unlock(&ep->udc->lock);
211         /* complete() is from gadget layer,
212          * eg fsg->bulk_in_complete() */
213         if (req->req.complete)
214                 req->req.complete(&ep->ep, &req->req);
215
216         spin_lock(&ep->udc->lock);
217         ep->stopped = stopped;
218 }
219
220 /*-----------------------------------------------------------------
221  * nuke(): delete all requests related to this ep
222  * called with spinlock held
223  *--------------------------------------------------------------*/
224 static void nuke(struct fsl_ep *ep, int status)
225 {
226         ep->stopped = 1;
227
228         /* Flush fifo */
229         fsl_ep_fifo_flush(&ep->ep);
230
231         /* Whether this eq has request linked */
232         while (!list_empty(&ep->queue)) {
233                 struct fsl_req *req = NULL;
234
235                 req = list_entry(ep->queue.next, struct fsl_req, queue);
236                 done(ep, req, status);
237         }
238 }
239
240 /*------------------------------------------------------------------
241         Internal Hardware related function
242  ------------------------------------------------------------------*/
243
244 static int dr_controller_setup(struct fsl_udc *udc)
245 {
246         unsigned int tmp, portctrl, ep_num;
247         unsigned int max_no_of_ep;
248 #ifndef CONFIG_ARCH_MXC
249         unsigned int ctrl;
250 #endif
251         unsigned long timeout;
252 #define FSL_UDC_RESET_TIMEOUT 1000
253
254         /* Config PHY interface */
255         portctrl = fsl_readl(&dr_regs->portsc1);
256         portctrl &= ~(PORTSCX_PHY_TYPE_SEL | PORTSCX_PORT_WIDTH);
257         switch (udc->phy_mode) {
258         case FSL_USB2_PHY_ULPI:
259                 portctrl |= PORTSCX_PTS_ULPI;
260                 break;
261         case FSL_USB2_PHY_UTMI_WIDE:
262                 portctrl |= PORTSCX_PTW_16BIT;
263                 /* fall through */
264         case FSL_USB2_PHY_UTMI:
265                 portctrl |= PORTSCX_PTS_UTMI;
266                 break;
267         case FSL_USB2_PHY_SERIAL:
268                 portctrl |= PORTSCX_PTS_FSLS;
269                 break;
270         default:
271                 return -EINVAL;
272         }
273         fsl_writel(portctrl, &dr_regs->portsc1);
274
275         /* Stop and reset the usb controller */
276         tmp = fsl_readl(&dr_regs->usbcmd);
277         tmp &= ~USB_CMD_RUN_STOP;
278         fsl_writel(tmp, &dr_regs->usbcmd);
279
280         tmp = fsl_readl(&dr_regs->usbcmd);
281         tmp |= USB_CMD_CTRL_RESET;
282         fsl_writel(tmp, &dr_regs->usbcmd);
283
284         /* Wait for reset to complete */
285         timeout = jiffies + FSL_UDC_RESET_TIMEOUT;
286         while (fsl_readl(&dr_regs->usbcmd) & USB_CMD_CTRL_RESET) {
287                 if (time_after(jiffies, timeout)) {
288                         ERR("udc reset timeout!\n");
289                         return -ETIMEDOUT;
290                 }
291                 cpu_relax();
292         }
293
294         /* Set the controller as device mode */
295         tmp = fsl_readl(&dr_regs->usbmode);
296         tmp &= ~USB_MODE_CTRL_MODE_MASK;        /* clear mode bits */
297         tmp |= USB_MODE_CTRL_MODE_DEVICE;
298         /* Disable Setup Lockout */
299         tmp |= USB_MODE_SETUP_LOCK_OFF;
300         if (udc->pdata->es)
301                 tmp |= USB_MODE_ES;
302         fsl_writel(tmp, &dr_regs->usbmode);
303
304         /* Clear the setup status */
305         fsl_writel(0, &dr_regs->usbsts);
306
307         tmp = udc->ep_qh_dma;
308         tmp &= USB_EP_LIST_ADDRESS_MASK;
309         fsl_writel(tmp, &dr_regs->endpointlistaddr);
310
311         VDBG("vir[qh_base] is %p phy[qh_base] is 0x%8x reg is 0x%8x",
312                 udc->ep_qh, (int)tmp,
313                 fsl_readl(&dr_regs->endpointlistaddr));
314
315         max_no_of_ep = (0x0000001F & fsl_readl(&dr_regs->dccparams));
316         for (ep_num = 1; ep_num < max_no_of_ep; ep_num++) {
317                 tmp = fsl_readl(&dr_regs->endptctrl[ep_num]);
318                 tmp &= ~(EPCTRL_TX_TYPE | EPCTRL_RX_TYPE);
319                 tmp |= (EPCTRL_EP_TYPE_BULK << EPCTRL_TX_EP_TYPE_SHIFT)
320                 | (EPCTRL_EP_TYPE_BULK << EPCTRL_RX_EP_TYPE_SHIFT);
321                 fsl_writel(tmp, &dr_regs->endptctrl[ep_num]);
322         }
323         /* Config control enable i/o output, cpu endian register */
324 #ifndef CONFIG_ARCH_MXC
325         if (udc->pdata->have_sysif_regs) {
326                 ctrl = __raw_readl(&usb_sys_regs->control);
327                 ctrl |= USB_CTRL_IOENB;
328                 __raw_writel(ctrl, &usb_sys_regs->control);
329         }
330 #endif
331
332 #if defined(CONFIG_PPC32) && !defined(CONFIG_NOT_COHERENT_CACHE)
333         /* Turn on cache snooping hardware, since some PowerPC platforms
334          * wholly rely on hardware to deal with cache coherent. */
335
336         if (udc->pdata->have_sysif_regs) {
337                 /* Setup Snooping for all the 4GB space */
338                 tmp = SNOOP_SIZE_2GB;   /* starts from 0x0, size 2G */
339                 __raw_writel(tmp, &usb_sys_regs->snoop1);
340                 tmp |= 0x80000000;      /* starts from 0x8000000, size 2G */
341                 __raw_writel(tmp, &usb_sys_regs->snoop2);
342         }
343 #endif
344
345         return 0;
346 }
347
348 /* Enable DR irq and set controller to run state */
349 static void dr_controller_run(struct fsl_udc *udc)
350 {
351         u32 temp;
352
353         /* Enable DR irq reg */
354         temp = USB_INTR_INT_EN | USB_INTR_ERR_INT_EN
355                 | USB_INTR_PTC_DETECT_EN | USB_INTR_RESET_EN
356                 | USB_INTR_DEVICE_SUSPEND | USB_INTR_SYS_ERR_EN;
357
358         fsl_writel(temp, &dr_regs->usbintr);
359
360         /* Clear stopped bit */
361         udc->stopped = 0;
362
363         /* Set the controller as device mode */
364         temp = fsl_readl(&dr_regs->usbmode);
365         temp |= USB_MODE_CTRL_MODE_DEVICE;
366         fsl_writel(temp, &dr_regs->usbmode);
367
368         /* Set controller to Run */
369         temp = fsl_readl(&dr_regs->usbcmd);
370         temp |= USB_CMD_RUN_STOP;
371         fsl_writel(temp, &dr_regs->usbcmd);
372 }
373
374 static void dr_controller_stop(struct fsl_udc *udc)
375 {
376         unsigned int tmp;
377
378         pr_debug("%s\n", __func__);
379
380         /* if we're in OTG mode, and the Host is currently using the port,
381          * stop now and don't rip the controller out from under the
382          * ehci driver
383          */
384         if (udc->gadget.is_otg) {
385                 if (!(fsl_readl(&dr_regs->otgsc) & OTGSC_STS_USB_ID)) {
386                         pr_debug("udc: Leaving early\n");
387                         return;
388                 }
389         }
390
391         /* disable all INTR */
392         fsl_writel(0, &dr_regs->usbintr);
393
394         /* Set stopped bit for isr */
395         udc->stopped = 1;
396
397         /* disable IO output */
398 /*      usb_sys_regs->control = 0; */
399
400         /* set controller to Stop */
401         tmp = fsl_readl(&dr_regs->usbcmd);
402         tmp &= ~USB_CMD_RUN_STOP;
403         fsl_writel(tmp, &dr_regs->usbcmd);
404 }
405
406 static void dr_ep_setup(unsigned char ep_num, unsigned char dir,
407                         unsigned char ep_type)
408 {
409         unsigned int tmp_epctrl = 0;
410
411         tmp_epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]);
412         if (dir) {
413                 if (ep_num)
414                         tmp_epctrl |= EPCTRL_TX_DATA_TOGGLE_RST;
415                 tmp_epctrl |= EPCTRL_TX_ENABLE;
416                 tmp_epctrl &= ~EPCTRL_TX_TYPE;
417                 tmp_epctrl |= ((unsigned int)(ep_type)
418                                 << EPCTRL_TX_EP_TYPE_SHIFT);
419         } else {
420                 if (ep_num)
421                         tmp_epctrl |= EPCTRL_RX_DATA_TOGGLE_RST;
422                 tmp_epctrl |= EPCTRL_RX_ENABLE;
423                 tmp_epctrl &= ~EPCTRL_RX_TYPE;
424                 tmp_epctrl |= ((unsigned int)(ep_type)
425                                 << EPCTRL_RX_EP_TYPE_SHIFT);
426         }
427
428         fsl_writel(tmp_epctrl, &dr_regs->endptctrl[ep_num]);
429 }
430
431 static void
432 dr_ep_change_stall(unsigned char ep_num, unsigned char dir, int value)
433 {
434         u32 tmp_epctrl = 0;
435
436         tmp_epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]);
437
438         if (value) {
439                 /* set the stall bit */
440                 if (dir)
441                         tmp_epctrl |= EPCTRL_TX_EP_STALL;
442                 else
443                         tmp_epctrl |= EPCTRL_RX_EP_STALL;
444         } else {
445                 /* clear the stall bit and reset data toggle */
446                 if (dir) {
447                         tmp_epctrl &= ~EPCTRL_TX_EP_STALL;
448                         tmp_epctrl |= EPCTRL_TX_DATA_TOGGLE_RST;
449                 } else {
450                         tmp_epctrl &= ~EPCTRL_RX_EP_STALL;
451                         tmp_epctrl |= EPCTRL_RX_DATA_TOGGLE_RST;
452                 }
453         }
454         fsl_writel(tmp_epctrl, &dr_regs->endptctrl[ep_num]);
455 }
456
457 /* Get stall status of a specific ep
458    Return: 0: not stalled; 1:stalled */
459 static int dr_ep_get_stall(unsigned char ep_num, unsigned char dir)
460 {
461         u32 epctrl;
462
463         epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]);
464         if (dir)
465                 return (epctrl & EPCTRL_TX_EP_STALL) ? 1 : 0;
466         else
467                 return (epctrl & EPCTRL_RX_EP_STALL) ? 1 : 0;
468 }
469
470 /********************************************************************
471         Internal Structure Build up functions
472 ********************************************************************/
473
474 /*------------------------------------------------------------------
475 * struct_ep_qh_setup(): set the Endpoint Capabilites field of QH
476  * @zlt: Zero Length Termination Select (1: disable; 0: enable)
477  * @mult: Mult field
478  ------------------------------------------------------------------*/
479 static void struct_ep_qh_setup(struct fsl_udc *udc, unsigned char ep_num,
480                 unsigned char dir, unsigned char ep_type,
481                 unsigned int max_pkt_len,
482                 unsigned int zlt, unsigned char mult)
483 {
484         struct ep_queue_head *p_QH = &udc->ep_qh[2 * ep_num + dir];
485         unsigned int tmp = 0;
486
487         /* set the Endpoint Capabilites in QH */
488         switch (ep_type) {
489         case USB_ENDPOINT_XFER_CONTROL:
490                 /* Interrupt On Setup (IOS). for control ep  */
491                 tmp = (max_pkt_len << EP_QUEUE_HEAD_MAX_PKT_LEN_POS)
492                         | EP_QUEUE_HEAD_IOS;
493                 break;
494         case USB_ENDPOINT_XFER_ISOC:
495                 tmp = (max_pkt_len << EP_QUEUE_HEAD_MAX_PKT_LEN_POS)
496                         | (mult << EP_QUEUE_HEAD_MULT_POS);
497                 break;
498         case USB_ENDPOINT_XFER_BULK:
499         case USB_ENDPOINT_XFER_INT:
500                 tmp = max_pkt_len << EP_QUEUE_HEAD_MAX_PKT_LEN_POS;
501                 break;
502         default:
503                 VDBG("error ep type is %d", ep_type);
504                 return;
505         }
506         if (zlt)
507                 tmp |= EP_QUEUE_HEAD_ZLT_SEL;
508
509         p_QH->max_pkt_length = cpu_to_hc32(tmp);
510         p_QH->next_dtd_ptr = 1;
511         p_QH->size_ioc_int_sts = 0;
512 }
513
514 /* Setup qh structure and ep register for ep0. */
515 static void ep0_setup(struct fsl_udc *udc)
516 {
517         /* the intialization of an ep includes: fields in QH, Regs,
518          * fsl_ep struct */
519         struct_ep_qh_setup(udc, 0, USB_RECV, USB_ENDPOINT_XFER_CONTROL,
520                         USB_MAX_CTRL_PAYLOAD, 0, 0);
521         struct_ep_qh_setup(udc, 0, USB_SEND, USB_ENDPOINT_XFER_CONTROL,
522                         USB_MAX_CTRL_PAYLOAD, 0, 0);
523         dr_ep_setup(0, USB_RECV, USB_ENDPOINT_XFER_CONTROL);
524         dr_ep_setup(0, USB_SEND, USB_ENDPOINT_XFER_CONTROL);
525
526         return;
527
528 }
529
530 /***********************************************************************
531                 Endpoint Management Functions
532 ***********************************************************************/
533
534 /*-------------------------------------------------------------------------
535  * when configurations are set, or when interface settings change
536  * for example the do_set_interface() in gadget layer,
537  * the driver will enable or disable the relevant endpoints
538  * ep0 doesn't use this routine. It is always enabled.
539 -------------------------------------------------------------------------*/
540 static int fsl_ep_enable(struct usb_ep *_ep,
541                 const struct usb_endpoint_descriptor *desc)
542 {
543         struct fsl_udc *udc = NULL;
544         struct fsl_ep *ep = NULL;
545         unsigned short max = 0;
546         unsigned char mult = 0, zlt;
547         int retval = -EINVAL;
548         unsigned long flags = 0;
549
550         ep = container_of(_ep, struct fsl_ep, ep);
551
552         /* catch various bogus parameters */
553         if (!_ep || !desc || ep->desc
554                         || (desc->bDescriptorType != USB_DT_ENDPOINT))
555                 return -EINVAL;
556
557         udc = ep->udc;
558
559         if (!udc->driver || (udc->gadget.speed == USB_SPEED_UNKNOWN))
560                 return -ESHUTDOWN;
561
562         max = usb_endpoint_maxp(desc);
563
564         /* Disable automatic zlp generation.  Driver is responsible to indicate
565          * explicitly through req->req.zero.  This is needed to enable multi-td
566          * request. */
567         zlt = 1;
568
569         /* Assume the max packet size from gadget is always correct */
570         switch (desc->bmAttributes & 0x03) {
571         case USB_ENDPOINT_XFER_CONTROL:
572         case USB_ENDPOINT_XFER_BULK:
573         case USB_ENDPOINT_XFER_INT:
574                 /* mult = 0.  Execute N Transactions as demonstrated by
575                  * the USB variable length packet protocol where N is
576                  * computed using the Maximum Packet Length (dQH) and
577                  * the Total Bytes field (dTD) */
578                 mult = 0;
579                 break;
580         case USB_ENDPOINT_XFER_ISOC:
581                 /* Calculate transactions needed for high bandwidth iso */
582                 mult = (unsigned char)(1 + ((max >> 11) & 0x03));
583                 max = max & 0x7ff;      /* bit 0~10 */
584                 /* 3 transactions at most */
585                 if (mult > 3)
586                         goto en_done;
587                 break;
588         default:
589                 goto en_done;
590         }
591
592         spin_lock_irqsave(&udc->lock, flags);
593         ep->ep.maxpacket = max;
594         ep->desc = desc;
595         ep->stopped = 0;
596
597         /* Controller related setup */
598         /* Init EPx Queue Head (Ep Capabilites field in QH
599          * according to max, zlt, mult) */
600         struct_ep_qh_setup(udc, (unsigned char) ep_index(ep),
601                         (unsigned char) ((desc->bEndpointAddress & USB_DIR_IN)
602                                         ?  USB_SEND : USB_RECV),
603                         (unsigned char) (desc->bmAttributes
604                                         & USB_ENDPOINT_XFERTYPE_MASK),
605                         max, zlt, mult);
606
607         /* Init endpoint ctrl register */
608         dr_ep_setup((unsigned char) ep_index(ep),
609                         (unsigned char) ((desc->bEndpointAddress & USB_DIR_IN)
610                                         ? USB_SEND : USB_RECV),
611                         (unsigned char) (desc->bmAttributes
612                                         & USB_ENDPOINT_XFERTYPE_MASK));
613
614         spin_unlock_irqrestore(&udc->lock, flags);
615         retval = 0;
616
617         VDBG("enabled %s (ep%d%s) maxpacket %d",ep->ep.name,
618                         ep->desc->bEndpointAddress & 0x0f,
619                         (desc->bEndpointAddress & USB_DIR_IN)
620                                 ? "in" : "out", max);
621 en_done:
622         return retval;
623 }
624
625 /*---------------------------------------------------------------------
626  * @ep : the ep being unconfigured. May not be ep0
627  * Any pending and uncomplete req will complete with status (-ESHUTDOWN)
628 *---------------------------------------------------------------------*/
629 static int fsl_ep_disable(struct usb_ep *_ep)
630 {
631         struct fsl_udc *udc = NULL;
632         struct fsl_ep *ep = NULL;
633         unsigned long flags = 0;
634         u32 epctrl;
635         int ep_num;
636
637         ep = container_of(_ep, struct fsl_ep, ep);
638         if (!_ep || !ep->desc) {
639                 VDBG("%s not enabled", _ep ? ep->ep.name : NULL);
640                 return -EINVAL;
641         }
642
643         /* disable ep on controller */
644         ep_num = ep_index(ep);
645         epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]);
646         if (ep_is_in(ep)) {
647                 epctrl &= ~(EPCTRL_TX_ENABLE | EPCTRL_TX_TYPE);
648                 epctrl |= EPCTRL_EP_TYPE_BULK << EPCTRL_TX_EP_TYPE_SHIFT;
649         } else {
650                 epctrl &= ~(EPCTRL_RX_ENABLE | EPCTRL_TX_TYPE);
651                 epctrl |= EPCTRL_EP_TYPE_BULK << EPCTRL_RX_EP_TYPE_SHIFT;
652         }
653         fsl_writel(epctrl, &dr_regs->endptctrl[ep_num]);
654
655         udc = (struct fsl_udc *)ep->udc;
656         spin_lock_irqsave(&udc->lock, flags);
657
658         /* nuke all pending requests (does flush) */
659         nuke(ep, -ESHUTDOWN);
660
661         ep->desc = NULL;
662         ep->stopped = 1;
663         spin_unlock_irqrestore(&udc->lock, flags);
664
665         VDBG("disabled %s OK", _ep->name);
666         return 0;
667 }
668
669 /*---------------------------------------------------------------------
670  * allocate a request object used by this endpoint
671  * the main operation is to insert the req->queue to the eq->queue
672  * Returns the request, or null if one could not be allocated
673 *---------------------------------------------------------------------*/
674 static struct usb_request *
675 fsl_alloc_request(struct usb_ep *_ep, gfp_t gfp_flags)
676 {
677         struct fsl_req *req = NULL;
678
679         req = kzalloc(sizeof *req, gfp_flags);
680         if (!req)
681                 return NULL;
682
683         req->req.dma = DMA_ADDR_INVALID;
684         INIT_LIST_HEAD(&req->queue);
685
686         return &req->req;
687 }
688
689 static void fsl_free_request(struct usb_ep *_ep, struct usb_request *_req)
690 {
691         struct fsl_req *req = NULL;
692
693         req = container_of(_req, struct fsl_req, req);
694
695         if (_req)
696                 kfree(req);
697 }
698
699 /*-------------------------------------------------------------------------*/
700 static void fsl_queue_td(struct fsl_ep *ep, struct fsl_req *req)
701 {
702         int i = ep_index(ep) * 2 + ep_is_in(ep);
703         u32 temp, bitmask, tmp_stat;
704         struct ep_queue_head *dQH = &ep->udc->ep_qh[i];
705
706         /* VDBG("QH addr Register 0x%8x", dr_regs->endpointlistaddr);
707         VDBG("ep_qh[%d] addr is 0x%8x", i, (u32)&(ep->udc->ep_qh[i])); */
708
709         bitmask = ep_is_in(ep)
710                 ? (1 << (ep_index(ep) + 16))
711                 : (1 << (ep_index(ep)));
712
713         /* check if the pipe is empty */
714         if (!(list_empty(&ep->queue))) {
715                 /* Add td to the end */
716                 struct fsl_req *lastreq;
717                 lastreq = list_entry(ep->queue.prev, struct fsl_req, queue);
718                 lastreq->tail->next_td_ptr =
719                         cpu_to_hc32(req->head->td_dma & DTD_ADDR_MASK);
720                 /* Read prime bit, if 1 goto done */
721                 if (fsl_readl(&dr_regs->endpointprime) & bitmask)
722                         goto out;
723
724                 do {
725                         /* Set ATDTW bit in USBCMD */
726                         temp = fsl_readl(&dr_regs->usbcmd);
727                         fsl_writel(temp | USB_CMD_ATDTW, &dr_regs->usbcmd);
728
729                         /* Read correct status bit */
730                         tmp_stat = fsl_readl(&dr_regs->endptstatus) & bitmask;
731
732                 } while (!(fsl_readl(&dr_regs->usbcmd) & USB_CMD_ATDTW));
733
734                 /* Write ATDTW bit to 0 */
735                 temp = fsl_readl(&dr_regs->usbcmd);
736                 fsl_writel(temp & ~USB_CMD_ATDTW, &dr_regs->usbcmd);
737
738                 if (tmp_stat)
739                         goto out;
740         }
741
742         /* Write dQH next pointer and terminate bit to 0 */
743         temp = req->head->td_dma & EP_QUEUE_HEAD_NEXT_POINTER_MASK;
744         dQH->next_dtd_ptr = cpu_to_hc32(temp);
745
746         /* Clear active and halt bit */
747         temp = cpu_to_hc32(~(EP_QUEUE_HEAD_STATUS_ACTIVE
748                         | EP_QUEUE_HEAD_STATUS_HALT));
749         dQH->size_ioc_int_sts &= temp;
750
751         /* Ensure that updates to the QH will occur before priming. */
752         wmb();
753
754         /* Prime endpoint by writing 1 to ENDPTPRIME */
755         temp = ep_is_in(ep)
756                 ? (1 << (ep_index(ep) + 16))
757                 : (1 << (ep_index(ep)));
758         fsl_writel(temp, &dr_regs->endpointprime);
759 out:
760         return;
761 }
762
763 /* Fill in the dTD structure
764  * @req: request that the transfer belongs to
765  * @length: return actually data length of the dTD
766  * @dma: return dma address of the dTD
767  * @is_last: return flag if it is the last dTD of the request
768  * return: pointer to the built dTD */
769 static struct ep_td_struct *fsl_build_dtd(struct fsl_req *req, unsigned *length,
770                 dma_addr_t *dma, int *is_last)
771 {
772         u32 swap_temp;
773         struct ep_td_struct *dtd;
774
775         /* how big will this transfer be? */
776         *length = min(req->req.length - req->req.actual,
777                         (unsigned)EP_MAX_LENGTH_TRANSFER);
778
779         dtd = dma_pool_alloc(udc_controller->td_pool, GFP_KERNEL, dma);
780         if (dtd == NULL)
781                 return dtd;
782
783         dtd->td_dma = *dma;
784         /* Clear reserved field */
785         swap_temp = hc32_to_cpu(dtd->size_ioc_sts);
786         swap_temp &= ~DTD_RESERVED_FIELDS;
787         dtd->size_ioc_sts = cpu_to_hc32(swap_temp);
788
789         /* Init all of buffer page pointers */
790         swap_temp = (u32) (req->req.dma + req->req.actual);
791         dtd->buff_ptr0 = cpu_to_hc32(swap_temp);
792         dtd->buff_ptr1 = cpu_to_hc32(swap_temp + 0x1000);
793         dtd->buff_ptr2 = cpu_to_hc32(swap_temp + 0x2000);
794         dtd->buff_ptr3 = cpu_to_hc32(swap_temp + 0x3000);
795         dtd->buff_ptr4 = cpu_to_hc32(swap_temp + 0x4000);
796
797         req->req.actual += *length;
798
799         /* zlp is needed if req->req.zero is set */
800         if (req->req.zero) {
801                 if (*length == 0 || (*length % req->ep->ep.maxpacket) != 0)
802                         *is_last = 1;
803                 else
804                         *is_last = 0;
805         } else if (req->req.length == req->req.actual)
806                 *is_last = 1;
807         else
808                 *is_last = 0;
809
810         if ((*is_last) == 0)
811                 VDBG("multi-dtd request!");
812         /* Fill in the transfer size; set active bit */
813         swap_temp = ((*length << DTD_LENGTH_BIT_POS) | DTD_STATUS_ACTIVE);
814
815         /* Enable interrupt for the last dtd of a request */
816         if (*is_last && !req->req.no_interrupt)
817                 swap_temp |= DTD_IOC;
818
819         dtd->size_ioc_sts = cpu_to_hc32(swap_temp);
820
821         mb();
822
823         VDBG("length = %d address= 0x%x", *length, (int)*dma);
824
825         return dtd;
826 }
827
828 /* Generate dtd chain for a request */
829 static int fsl_req_to_dtd(struct fsl_req *req)
830 {
831         unsigned        count;
832         int             is_last;
833         int             is_first =1;
834         struct ep_td_struct     *last_dtd = NULL, *dtd;
835         dma_addr_t dma;
836
837         do {
838                 dtd = fsl_build_dtd(req, &count, &dma, &is_last);
839                 if (dtd == NULL)
840                         return -ENOMEM;
841
842                 if (is_first) {
843                         is_first = 0;
844                         req->head = dtd;
845                 } else {
846                         last_dtd->next_td_ptr = cpu_to_hc32(dma);
847                         last_dtd->next_td_virt = dtd;
848                 }
849                 last_dtd = dtd;
850
851                 req->dtd_count++;
852         } while (!is_last);
853
854         dtd->next_td_ptr = cpu_to_hc32(DTD_NEXT_TERMINATE);
855
856         req->tail = dtd;
857
858         return 0;
859 }
860
861 /* queues (submits) an I/O request to an endpoint */
862 static int
863 fsl_ep_queue(struct usb_ep *_ep, struct usb_request *_req, gfp_t gfp_flags)
864 {
865         struct fsl_ep *ep = container_of(_ep, struct fsl_ep, ep);
866         struct fsl_req *req = container_of(_req, struct fsl_req, req);
867         struct fsl_udc *udc;
868         unsigned long flags;
869
870         /* catch various bogus parameters */
871         if (!_req || !req->req.complete || !req->req.buf
872                         || !list_empty(&req->queue)) {
873                 VDBG("%s, bad params", __func__);
874                 return -EINVAL;
875         }
876         if (unlikely(!_ep || !ep->desc)) {
877                 VDBG("%s, bad ep", __func__);
878                 return -EINVAL;
879         }
880         if (ep->desc->bmAttributes == USB_ENDPOINT_XFER_ISOC) {
881                 if (req->req.length > ep->ep.maxpacket)
882                         return -EMSGSIZE;
883         }
884
885         udc = ep->udc;
886         if (!udc->driver || udc->gadget.speed == USB_SPEED_UNKNOWN)
887                 return -ESHUTDOWN;
888
889         req->ep = ep;
890
891         /* map virtual address to hardware */
892         if (req->req.dma == DMA_ADDR_INVALID) {
893                 req->req.dma = dma_map_single(ep->udc->gadget.dev.parent,
894                                         req->req.buf,
895                                         req->req.length, ep_is_in(ep)
896                                                 ? DMA_TO_DEVICE
897                                                 : DMA_FROM_DEVICE);
898                 req->mapped = 1;
899         } else {
900                 dma_sync_single_for_device(ep->udc->gadget.dev.parent,
901                                         req->req.dma, req->req.length,
902                                         ep_is_in(ep)
903                                                 ? DMA_TO_DEVICE
904                                                 : DMA_FROM_DEVICE);
905                 req->mapped = 0;
906         }
907
908         req->req.status = -EINPROGRESS;
909         req->req.actual = 0;
910         req->dtd_count = 0;
911
912         spin_lock_irqsave(&udc->lock, flags);
913
914         /* build dtds and push them to device queue */
915         if (!fsl_req_to_dtd(req)) {
916                 fsl_queue_td(ep, req);
917         } else {
918                 spin_unlock_irqrestore(&udc->lock, flags);
919                 return -ENOMEM;
920         }
921
922         /* Update ep0 state */
923         if ((ep_index(ep) == 0))
924                 udc->ep0_state = DATA_STATE_XMIT;
925
926         /* irq handler advances the queue */
927         if (req != NULL)
928                 list_add_tail(&req->queue, &ep->queue);
929         spin_unlock_irqrestore(&udc->lock, flags);
930
931         return 0;
932 }
933
934 /* dequeues (cancels, unlinks) an I/O request from an endpoint */
935 static int fsl_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req)
936 {
937         struct fsl_ep *ep = container_of(_ep, struct fsl_ep, ep);
938         struct fsl_req *req;
939         unsigned long flags;
940         int ep_num, stopped, ret = 0;
941         u32 epctrl;
942
943         if (!_ep || !_req)
944                 return -EINVAL;
945
946         spin_lock_irqsave(&ep->udc->lock, flags);
947         stopped = ep->stopped;
948
949         /* Stop the ep before we deal with the queue */
950         ep->stopped = 1;
951         ep_num = ep_index(ep);
952         epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]);
953         if (ep_is_in(ep))
954                 epctrl &= ~EPCTRL_TX_ENABLE;
955         else
956                 epctrl &= ~EPCTRL_RX_ENABLE;
957         fsl_writel(epctrl, &dr_regs->endptctrl[ep_num]);
958
959         /* make sure it's actually queued on this endpoint */
960         list_for_each_entry(req, &ep->queue, queue) {
961                 if (&req->req == _req)
962                         break;
963         }
964         if (&req->req != _req) {
965                 ret = -EINVAL;
966                 goto out;
967         }
968
969         /* The request is in progress, or completed but not dequeued */
970         if (ep->queue.next == &req->queue) {
971                 _req->status = -ECONNRESET;
972                 fsl_ep_fifo_flush(_ep); /* flush current transfer */
973
974                 /* The request isn't the last request in this ep queue */
975                 if (req->queue.next != &ep->queue) {
976                         struct ep_queue_head *qh;
977                         struct fsl_req *next_req;
978
979                         qh = ep->qh;
980                         next_req = list_entry(req->queue.next, struct fsl_req,
981                                         queue);
982
983                         /* Point the QH to the first TD of next request */
984                         fsl_writel((u32) next_req->head, &qh->curr_dtd_ptr);
985                 }
986
987                 /* The request hasn't been processed, patch up the TD chain */
988         } else {
989                 struct fsl_req *prev_req;
990
991                 prev_req = list_entry(req->queue.prev, struct fsl_req, queue);
992                 fsl_writel(fsl_readl(&req->tail->next_td_ptr),
993                                 &prev_req->tail->next_td_ptr);
994
995         }
996
997         done(ep, req, -ECONNRESET);
998
999         /* Enable EP */
1000 out:    epctrl = fsl_readl(&dr_regs->endptctrl[ep_num]);
1001         if (ep_is_in(ep))
1002                 epctrl |= EPCTRL_TX_ENABLE;
1003         else
1004                 epctrl |= EPCTRL_RX_ENABLE;
1005         fsl_writel(epctrl, &dr_regs->endptctrl[ep_num]);
1006         ep->stopped = stopped;
1007
1008         spin_unlock_irqrestore(&ep->udc->lock, flags);
1009         return ret;
1010 }
1011
1012 /*-------------------------------------------------------------------------*/
1013
1014 /*-----------------------------------------------------------------
1015  * modify the endpoint halt feature
1016  * @ep: the non-isochronous endpoint being stalled
1017  * @value: 1--set halt  0--clear halt
1018  * Returns zero, or a negative error code.
1019 *----------------------------------------------------------------*/
1020 static int fsl_ep_set_halt(struct usb_ep *_ep, int value)
1021 {
1022         struct fsl_ep *ep = NULL;
1023         unsigned long flags = 0;
1024         int status = -EOPNOTSUPP;       /* operation not supported */
1025         unsigned char ep_dir = 0, ep_num = 0;
1026         struct fsl_udc *udc = NULL;
1027
1028         ep = container_of(_ep, struct fsl_ep, ep);
1029         udc = ep->udc;
1030         if (!_ep || !ep->desc) {
1031                 status = -EINVAL;
1032                 goto out;
1033         }
1034
1035         if (ep->desc->bmAttributes == USB_ENDPOINT_XFER_ISOC) {
1036                 status = -EOPNOTSUPP;
1037                 goto out;
1038         }
1039
1040         /* Attempt to halt IN ep will fail if any transfer requests
1041          * are still queue */
1042         if (value && ep_is_in(ep) && !list_empty(&ep->queue)) {
1043                 status = -EAGAIN;
1044                 goto out;
1045         }
1046
1047         status = 0;
1048         ep_dir = ep_is_in(ep) ? USB_SEND : USB_RECV;
1049         ep_num = (unsigned char)(ep_index(ep));
1050         spin_lock_irqsave(&ep->udc->lock, flags);
1051         dr_ep_change_stall(ep_num, ep_dir, value);
1052         spin_unlock_irqrestore(&ep->udc->lock, flags);
1053
1054         if (ep_index(ep) == 0) {
1055                 udc->ep0_state = WAIT_FOR_SETUP;
1056                 udc->ep0_dir = 0;
1057         }
1058 out:
1059         VDBG(" %s %s halt stat %d", ep->ep.name,
1060                         value ?  "set" : "clear", status);
1061
1062         return status;
1063 }
1064
1065 static int fsl_ep_fifo_status(struct usb_ep *_ep)
1066 {
1067         struct fsl_ep *ep;
1068         struct fsl_udc *udc;
1069         int size = 0;
1070         u32 bitmask;
1071         struct ep_queue_head *d_qh;
1072
1073         ep = container_of(_ep, struct fsl_ep, ep);
1074         if (!_ep || (!ep->desc && ep_index(ep) != 0))
1075                 return -ENODEV;
1076
1077         udc = (struct fsl_udc *)ep->udc;
1078
1079         if (!udc->driver || udc->gadget.speed == USB_SPEED_UNKNOWN)
1080                 return -ESHUTDOWN;
1081
1082         d_qh = &ep->udc->ep_qh[ep_index(ep) * 2 + ep_is_in(ep)];
1083
1084         bitmask = (ep_is_in(ep)) ? (1 << (ep_index(ep) + 16)) :
1085             (1 << (ep_index(ep)));
1086
1087         if (fsl_readl(&dr_regs->endptstatus) & bitmask)
1088                 size = (d_qh->size_ioc_int_sts & DTD_PACKET_SIZE)
1089                     >> DTD_LENGTH_BIT_POS;
1090
1091         pr_debug("%s %u\n", __func__, size);
1092         return size;
1093 }
1094
1095 static void fsl_ep_fifo_flush(struct usb_ep *_ep)
1096 {
1097         struct fsl_ep *ep;
1098         int ep_num, ep_dir;
1099         u32 bits;
1100         unsigned long timeout;
1101 #define FSL_UDC_FLUSH_TIMEOUT 1000
1102
1103         if (!_ep) {
1104                 return;
1105         } else {
1106                 ep = container_of(_ep, struct fsl_ep, ep);
1107                 if (!ep->desc)
1108                         return;
1109         }
1110         ep_num = ep_index(ep);
1111         ep_dir = ep_is_in(ep) ? USB_SEND : USB_RECV;
1112
1113         if (ep_num == 0)
1114                 bits = (1 << 16) | 1;
1115         else if (ep_dir == USB_SEND)
1116                 bits = 1 << (16 + ep_num);
1117         else
1118                 bits = 1 << ep_num;
1119
1120         timeout = jiffies + FSL_UDC_FLUSH_TIMEOUT;
1121         do {
1122                 fsl_writel(bits, &dr_regs->endptflush);
1123
1124                 /* Wait until flush complete */
1125                 while (fsl_readl(&dr_regs->endptflush)) {
1126                         if (time_after(jiffies, timeout)) {
1127                                 ERR("ep flush timeout\n");
1128                                 return;
1129                         }
1130                         cpu_relax();
1131                 }
1132                 /* See if we need to flush again */
1133         } while (fsl_readl(&dr_regs->endptstatus) & bits);
1134 }
1135
1136 static struct usb_ep_ops fsl_ep_ops = {
1137         .enable = fsl_ep_enable,
1138         .disable = fsl_ep_disable,
1139
1140         .alloc_request = fsl_alloc_request,
1141         .free_request = fsl_free_request,
1142
1143         .queue = fsl_ep_queue,
1144         .dequeue = fsl_ep_dequeue,
1145
1146         .set_halt = fsl_ep_set_halt,
1147         .fifo_status = fsl_ep_fifo_status,
1148         .fifo_flush = fsl_ep_fifo_flush,        /* flush fifo */
1149 };
1150
1151 /*-------------------------------------------------------------------------
1152                 Gadget Driver Layer Operations
1153 -------------------------------------------------------------------------*/
1154
1155 /*----------------------------------------------------------------------
1156  * Get the current frame number (from DR frame_index Reg )
1157  *----------------------------------------------------------------------*/
1158 static int fsl_get_frame(struct usb_gadget *gadget)
1159 {
1160         return (int)(fsl_readl(&dr_regs->frindex) & USB_FRINDEX_MASKS);
1161 }
1162
1163 /*-----------------------------------------------------------------------
1164  * Tries to wake up the host connected to this gadget
1165  -----------------------------------------------------------------------*/
1166 static int fsl_wakeup(struct usb_gadget *gadget)
1167 {
1168         struct fsl_udc *udc = container_of(gadget, struct fsl_udc, gadget);
1169         u32 portsc;
1170
1171         /* Remote wakeup feature not enabled by host */
1172         if (!udc->remote_wakeup)
1173                 return -ENOTSUPP;
1174
1175         portsc = fsl_readl(&dr_regs->portsc1);
1176         /* not suspended? */
1177         if (!(portsc & PORTSCX_PORT_SUSPEND))
1178                 return 0;
1179         /* trigger force resume */
1180         portsc |= PORTSCX_PORT_FORCE_RESUME;
1181         fsl_writel(portsc, &dr_regs->portsc1);
1182         return 0;
1183 }
1184
1185 static int can_pullup(struct fsl_udc *udc)
1186 {
1187         return udc->driver && udc->softconnect && udc->vbus_active;
1188 }
1189
1190 /* Notify controller that VBUS is powered, Called by whatever
1191    detects VBUS sessions */
1192 static int fsl_vbus_session(struct usb_gadget *gadget, int is_active)
1193 {
1194         struct fsl_udc  *udc;
1195         unsigned long   flags;
1196
1197         udc = container_of(gadget, struct fsl_udc, gadget);
1198         spin_lock_irqsave(&udc->lock, flags);
1199         VDBG("VBUS %s", is_active ? "on" : "off");
1200         udc->vbus_active = (is_active != 0);
1201         if (can_pullup(udc))
1202                 fsl_writel((fsl_readl(&dr_regs->usbcmd) | USB_CMD_RUN_STOP),
1203                                 &dr_regs->usbcmd);
1204         else
1205                 fsl_writel((fsl_readl(&dr_regs->usbcmd) & ~USB_CMD_RUN_STOP),
1206                                 &dr_regs->usbcmd);
1207         spin_unlock_irqrestore(&udc->lock, flags);
1208         return 0;
1209 }
1210
1211 /* constrain controller's VBUS power usage
1212  * This call is used by gadget drivers during SET_CONFIGURATION calls,
1213  * reporting how much power the device may consume.  For example, this
1214  * could affect how quickly batteries are recharged.
1215  *
1216  * Returns zero on success, else negative errno.
1217  */
1218 static int fsl_vbus_draw(struct usb_gadget *gadget, unsigned mA)
1219 {
1220         struct fsl_udc *udc;
1221
1222         udc = container_of(gadget, struct fsl_udc, gadget);
1223         if (udc->transceiver)
1224                 return otg_set_power(udc->transceiver, mA);
1225         return -ENOTSUPP;
1226 }
1227
1228 /* Change Data+ pullup status
1229  * this func is used by usb_gadget_connect/disconnet
1230  */
1231 static int fsl_pullup(struct usb_gadget *gadget, int is_on)
1232 {
1233         struct fsl_udc *udc;
1234
1235         udc = container_of(gadget, struct fsl_udc, gadget);
1236         udc->softconnect = (is_on != 0);
1237         if (can_pullup(udc))
1238                 fsl_writel((fsl_readl(&dr_regs->usbcmd) | USB_CMD_RUN_STOP),
1239                                 &dr_regs->usbcmd);
1240         else
1241                 fsl_writel((fsl_readl(&dr_regs->usbcmd) & ~USB_CMD_RUN_STOP),
1242                                 &dr_regs->usbcmd);
1243
1244         return 0;
1245 }
1246
1247 static int fsl_start(struct usb_gadget_driver *driver,
1248                 int (*bind)(struct usb_gadget *));
1249 static int fsl_stop(struct usb_gadget_driver *driver);
1250 /* defined in gadget.h */
1251 static struct usb_gadget_ops fsl_gadget_ops = {
1252         .get_frame = fsl_get_frame,
1253         .wakeup = fsl_wakeup,
1254 /*      .set_selfpowered = fsl_set_selfpowered, */ /* Always selfpowered */
1255         .vbus_session = fsl_vbus_session,
1256         .vbus_draw = fsl_vbus_draw,
1257         .pullup = fsl_pullup,
1258         .start = fsl_start,
1259         .stop = fsl_stop,
1260 };
1261
1262 /* Set protocol stall on ep0, protocol stall will automatically be cleared
1263    on new transaction */
1264 static void ep0stall(struct fsl_udc *udc)
1265 {
1266         u32 tmp;
1267
1268         /* must set tx and rx to stall at the same time */
1269         tmp = fsl_readl(&dr_regs->endptctrl[0]);
1270         tmp |= EPCTRL_TX_EP_STALL | EPCTRL_RX_EP_STALL;
1271         fsl_writel(tmp, &dr_regs->endptctrl[0]);
1272         udc->ep0_state = WAIT_FOR_SETUP;
1273         udc->ep0_dir = 0;
1274 }
1275
1276 /* Prime a status phase for ep0 */
1277 static int ep0_prime_status(struct fsl_udc *udc, int direction)
1278 {
1279         struct fsl_req *req = udc->status_req;
1280         struct fsl_ep *ep;
1281
1282         if (direction == EP_DIR_IN)
1283                 udc->ep0_dir = USB_DIR_IN;
1284         else
1285                 udc->ep0_dir = USB_DIR_OUT;
1286
1287         ep = &udc->eps[0];
1288         udc->ep0_state = WAIT_FOR_OUT_STATUS;
1289
1290         req->ep = ep;
1291         req->req.length = 0;
1292         req->req.status = -EINPROGRESS;
1293         req->req.actual = 0;
1294         req->req.complete = NULL;
1295         req->dtd_count = 0;
1296
1297         req->req.dma = dma_map_single(ep->udc->gadget.dev.parent,
1298                         req->req.buf, req->req.length,
1299                         ep_is_in(ep) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1300         req->mapped = 1;
1301
1302         if (fsl_req_to_dtd(req) == 0)
1303                 fsl_queue_td(ep, req);
1304         else
1305                 return -ENOMEM;
1306
1307         list_add_tail(&req->queue, &ep->queue);
1308
1309         return 0;
1310 }
1311
1312 static void udc_reset_ep_queue(struct fsl_udc *udc, u8 pipe)
1313 {
1314         struct fsl_ep *ep = get_ep_by_pipe(udc, pipe);
1315
1316         if (ep->name)
1317                 nuke(ep, -ESHUTDOWN);
1318 }
1319
1320 /*
1321  * ch9 Set address
1322  */
1323 static void ch9setaddress(struct fsl_udc *udc, u16 value, u16 index, u16 length)
1324 {
1325         /* Save the new address to device struct */
1326         udc->device_address = (u8) value;
1327         /* Update usb state */
1328         udc->usb_state = USB_STATE_ADDRESS;
1329         /* Status phase */
1330         if (ep0_prime_status(udc, EP_DIR_IN))
1331                 ep0stall(udc);
1332 }
1333
1334 /*
1335  * ch9 Get status
1336  */
1337 static void ch9getstatus(struct fsl_udc *udc, u8 request_type, u16 value,
1338                 u16 index, u16 length)
1339 {
1340         u16 tmp = 0;            /* Status, cpu endian */
1341         struct fsl_req *req;
1342         struct fsl_ep *ep;
1343
1344         ep = &udc->eps[0];
1345
1346         if ((request_type & USB_RECIP_MASK) == USB_RECIP_DEVICE) {
1347                 /* Get device status */
1348                 tmp = 1 << USB_DEVICE_SELF_POWERED;
1349                 tmp |= udc->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP;
1350         } else if ((request_type & USB_RECIP_MASK) == USB_RECIP_INTERFACE) {
1351                 /* Get interface status */
1352                 /* We don't have interface information in udc driver */
1353                 tmp = 0;
1354         } else if ((request_type & USB_RECIP_MASK) == USB_RECIP_ENDPOINT) {
1355                 /* Get endpoint status */
1356                 struct fsl_ep *target_ep;
1357
1358                 target_ep = get_ep_by_pipe(udc, get_pipe_by_windex(index));
1359
1360                 /* stall if endpoint doesn't exist */
1361                 if (!target_ep->desc)
1362                         goto stall;
1363                 tmp = dr_ep_get_stall(ep_index(target_ep), ep_is_in(target_ep))
1364                                 << USB_ENDPOINT_HALT;
1365         }
1366
1367         udc->ep0_dir = USB_DIR_IN;
1368         /* Borrow the per device status_req */
1369         req = udc->status_req;
1370         /* Fill in the reqest structure */
1371         *((u16 *) req->req.buf) = cpu_to_le16(tmp);
1372
1373         req->ep = ep;
1374         req->req.length = 2;
1375         req->req.status = -EINPROGRESS;
1376         req->req.actual = 0;
1377         req->req.complete = NULL;
1378         req->dtd_count = 0;
1379
1380         req->req.dma = dma_map_single(ep->udc->gadget.dev.parent,
1381                                 req->req.buf, req->req.length,
1382                                 ep_is_in(ep) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1383         req->mapped = 1;
1384
1385         /* prime the data phase */
1386         if ((fsl_req_to_dtd(req) == 0))
1387                 fsl_queue_td(ep, req);
1388         else                    /* no mem */
1389                 goto stall;
1390
1391         list_add_tail(&req->queue, &ep->queue);
1392         udc->ep0_state = DATA_STATE_XMIT;
1393         return;
1394 stall:
1395         ep0stall(udc);
1396 }
1397
1398 static void setup_received_irq(struct fsl_udc *udc,
1399                 struct usb_ctrlrequest *setup)
1400 {
1401         u16 wValue = le16_to_cpu(setup->wValue);
1402         u16 wIndex = le16_to_cpu(setup->wIndex);
1403         u16 wLength = le16_to_cpu(setup->wLength);
1404
1405         udc_reset_ep_queue(udc, 0);
1406
1407         /* We process some stardard setup requests here */
1408         switch (setup->bRequest) {
1409         case USB_REQ_GET_STATUS:
1410                 /* Data+Status phase from udc */
1411                 if ((setup->bRequestType & (USB_DIR_IN | USB_TYPE_MASK))
1412                                         != (USB_DIR_IN | USB_TYPE_STANDARD))
1413                         break;
1414                 ch9getstatus(udc, setup->bRequestType, wValue, wIndex, wLength);
1415                 return;
1416
1417         case USB_REQ_SET_ADDRESS:
1418                 /* Status phase from udc */
1419                 if (setup->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD
1420                                                 | USB_RECIP_DEVICE))
1421                         break;
1422                 ch9setaddress(udc, wValue, wIndex, wLength);
1423                 return;
1424
1425         case USB_REQ_CLEAR_FEATURE:
1426         case USB_REQ_SET_FEATURE:
1427                 /* Status phase from udc */
1428         {
1429                 int rc = -EOPNOTSUPP;
1430                 u16 ptc = 0;
1431
1432                 if ((setup->bRequestType & (USB_RECIP_MASK | USB_TYPE_MASK))
1433                                 == (USB_RECIP_ENDPOINT | USB_TYPE_STANDARD)) {
1434                         int pipe = get_pipe_by_windex(wIndex);
1435                         struct fsl_ep *ep;
1436
1437                         if (wValue != 0 || wLength != 0 || pipe > udc->max_ep)
1438                                 break;
1439                         ep = get_ep_by_pipe(udc, pipe);
1440
1441                         spin_unlock(&udc->lock);
1442                         rc = fsl_ep_set_halt(&ep->ep,
1443                                         (setup->bRequest == USB_REQ_SET_FEATURE)
1444                                                 ? 1 : 0);
1445                         spin_lock(&udc->lock);
1446
1447                 } else if ((setup->bRequestType & (USB_RECIP_MASK
1448                                 | USB_TYPE_MASK)) == (USB_RECIP_DEVICE
1449                                 | USB_TYPE_STANDARD)) {
1450                         /* Note: The driver has not include OTG support yet.
1451                          * This will be set when OTG support is added */
1452                         if (wValue == USB_DEVICE_TEST_MODE)
1453                                 ptc = wIndex >> 8;
1454                         else if (gadget_is_otg(&udc->gadget)) {
1455                                 if (setup->bRequest ==
1456                                     USB_DEVICE_B_HNP_ENABLE)
1457                                         udc->gadget.b_hnp_enable = 1;
1458                                 else if (setup->bRequest ==
1459                                          USB_DEVICE_A_HNP_SUPPORT)
1460                                         udc->gadget.a_hnp_support = 1;
1461                                 else if (setup->bRequest ==
1462                                          USB_DEVICE_A_ALT_HNP_SUPPORT)
1463                                         udc->gadget.a_alt_hnp_support = 1;
1464                         }
1465                         rc = 0;
1466                 } else
1467                         break;
1468
1469                 if (rc == 0) {
1470                         if (ep0_prime_status(udc, EP_DIR_IN))
1471                                 ep0stall(udc);
1472                 }
1473                 if (ptc) {
1474                         u32 tmp;
1475
1476                         mdelay(10);
1477                         tmp = fsl_readl(&dr_regs->portsc1) | (ptc << 16);
1478                         fsl_writel(tmp, &dr_regs->portsc1);
1479                         printk(KERN_INFO "udc: switch to test mode %d.\n", ptc);
1480                 }
1481
1482                 return;
1483         }
1484
1485         default:
1486                 break;
1487         }
1488
1489         /* Requests handled by gadget */
1490         if (wLength) {
1491                 /* Data phase from gadget, status phase from udc */
1492                 udc->ep0_dir = (setup->bRequestType & USB_DIR_IN)
1493                                 ?  USB_DIR_IN : USB_DIR_OUT;
1494                 spin_unlock(&udc->lock);
1495                 if (udc->driver->setup(&udc->gadget,
1496                                 &udc->local_setup_buff) < 0)
1497                         ep0stall(udc);
1498                 spin_lock(&udc->lock);
1499                 udc->ep0_state = (setup->bRequestType & USB_DIR_IN)
1500                                 ?  DATA_STATE_XMIT : DATA_STATE_RECV;
1501         } else {
1502                 /* No data phase, IN status from gadget */
1503                 udc->ep0_dir = USB_DIR_IN;
1504                 spin_unlock(&udc->lock);
1505                 if (udc->driver->setup(&udc->gadget,
1506                                 &udc->local_setup_buff) < 0)
1507                         ep0stall(udc);
1508                 spin_lock(&udc->lock);
1509                 udc->ep0_state = WAIT_FOR_OUT_STATUS;
1510         }
1511 }
1512
1513 /* Process request for Data or Status phase of ep0
1514  * prime status phase if needed */
1515 static void ep0_req_complete(struct fsl_udc *udc, struct fsl_ep *ep0,
1516                 struct fsl_req *req)
1517 {
1518         if (udc->usb_state == USB_STATE_ADDRESS) {
1519                 /* Set the new address */
1520                 u32 new_address = (u32) udc->device_address;
1521                 fsl_writel(new_address << USB_DEVICE_ADDRESS_BIT_POS,
1522                                 &dr_regs->deviceaddr);
1523         }
1524
1525         done(ep0, req, 0);
1526
1527         switch (udc->ep0_state) {
1528         case DATA_STATE_XMIT:
1529                 /* receive status phase */
1530                 if (ep0_prime_status(udc, EP_DIR_OUT))
1531                         ep0stall(udc);
1532                 break;
1533         case DATA_STATE_RECV:
1534                 /* send status phase */
1535                 if (ep0_prime_status(udc, EP_DIR_IN))
1536                         ep0stall(udc);
1537                 break;
1538         case WAIT_FOR_OUT_STATUS:
1539                 udc->ep0_state = WAIT_FOR_SETUP;
1540                 break;
1541         case WAIT_FOR_SETUP:
1542                 ERR("Unexpect ep0 packets\n");
1543                 break;
1544         default:
1545                 ep0stall(udc);
1546                 break;
1547         }
1548 }
1549
1550 /* Tripwire mechanism to ensure a setup packet payload is extracted without
1551  * being corrupted by another incoming setup packet */
1552 static void tripwire_handler(struct fsl_udc *udc, u8 ep_num, u8 *buffer_ptr)
1553 {
1554         u32 temp;
1555         struct ep_queue_head *qh;
1556         struct fsl_usb2_platform_data *pdata = udc->pdata;
1557
1558         qh = &udc->ep_qh[ep_num * 2 + EP_DIR_OUT];
1559
1560         /* Clear bit in ENDPTSETUPSTAT */
1561         temp = fsl_readl(&dr_regs->endptsetupstat);
1562         fsl_writel(temp | (1 << ep_num), &dr_regs->endptsetupstat);
1563
1564         /* while a hazard exists when setup package arrives */
1565         do {
1566                 /* Set Setup Tripwire */
1567                 temp = fsl_readl(&dr_regs->usbcmd);
1568                 fsl_writel(temp | USB_CMD_SUTW, &dr_regs->usbcmd);
1569
1570                 /* Copy the setup packet to local buffer */
1571                 if (pdata->le_setup_buf) {
1572                         u32 *p = (u32 *)buffer_ptr;
1573                         u32 *s = (u32 *)qh->setup_buffer;
1574
1575                         /* Convert little endian setup buffer to CPU endian */
1576                         *p++ = le32_to_cpu(*s++);
1577                         *p = le32_to_cpu(*s);
1578                 } else {
1579                         memcpy(buffer_ptr, (u8 *) qh->setup_buffer, 8);
1580                 }
1581         } while (!(fsl_readl(&dr_regs->usbcmd) & USB_CMD_SUTW));
1582
1583         /* Clear Setup Tripwire */
1584         temp = fsl_readl(&dr_regs->usbcmd);
1585         fsl_writel(temp & ~USB_CMD_SUTW, &dr_regs->usbcmd);
1586 }
1587
1588 /* process-ep_req(): free the completed Tds for this req */
1589 static int process_ep_req(struct fsl_udc *udc, int pipe,
1590                 struct fsl_req *curr_req)
1591 {
1592         struct ep_td_struct *curr_td;
1593         int     td_complete, actual, remaining_length, j, tmp;
1594         int     status = 0;
1595         int     errors = 0;
1596         struct  ep_queue_head *curr_qh = &udc->ep_qh[pipe];
1597         int direction = pipe % 2;
1598
1599         curr_td = curr_req->head;
1600         td_complete = 0;
1601         actual = curr_req->req.length;
1602
1603         for (j = 0; j < curr_req->dtd_count; j++) {
1604                 remaining_length = (hc32_to_cpu(curr_td->size_ioc_sts)
1605                                         & DTD_PACKET_SIZE)
1606                                 >> DTD_LENGTH_BIT_POS;
1607                 actual -= remaining_length;
1608
1609                 errors = hc32_to_cpu(curr_td->size_ioc_sts);
1610                 if (errors & DTD_ERROR_MASK) {
1611                         if (errors & DTD_STATUS_HALTED) {
1612                                 ERR("dTD error %08x QH=%d\n", errors, pipe);
1613                                 /* Clear the errors and Halt condition */
1614                                 tmp = hc32_to_cpu(curr_qh->size_ioc_int_sts);
1615                                 tmp &= ~errors;
1616                                 curr_qh->size_ioc_int_sts = cpu_to_hc32(tmp);
1617                                 status = -EPIPE;
1618                                 /* FIXME: continue with next queued TD? */
1619
1620                                 break;
1621                         }
1622                         if (errors & DTD_STATUS_DATA_BUFF_ERR) {
1623                                 VDBG("Transfer overflow");
1624                                 status = -EPROTO;
1625                                 break;
1626                         } else if (errors & DTD_STATUS_TRANSACTION_ERR) {
1627                                 VDBG("ISO error");
1628                                 status = -EILSEQ;
1629                                 break;
1630                         } else
1631                                 ERR("Unknown error has occurred (0x%x)!\n",
1632                                         errors);
1633
1634                 } else if (hc32_to_cpu(curr_td->size_ioc_sts)
1635                                 & DTD_STATUS_ACTIVE) {
1636                         VDBG("Request not complete");
1637                         status = REQ_UNCOMPLETE;
1638                         return status;
1639                 } else if (remaining_length) {
1640                         if (direction) {
1641                                 VDBG("Transmit dTD remaining length not zero");
1642                                 status = -EPROTO;
1643                                 break;
1644                         } else {
1645                                 td_complete++;
1646                                 break;
1647                         }
1648                 } else {
1649                         td_complete++;
1650                         VDBG("dTD transmitted successful");
1651                 }
1652
1653                 if (j != curr_req->dtd_count - 1)
1654                         curr_td = (struct ep_td_struct *)curr_td->next_td_virt;
1655         }
1656
1657         if (status)
1658                 return status;
1659
1660         curr_req->req.actual = actual;
1661
1662         return 0;
1663 }
1664
1665 /* Process a DTD completion interrupt */
1666 static void dtd_complete_irq(struct fsl_udc *udc)
1667 {
1668         u32 bit_pos;
1669         int i, ep_num, direction, bit_mask, status;
1670         struct fsl_ep *curr_ep;
1671         struct fsl_req *curr_req, *temp_req;
1672
1673         /* Clear the bits in the register */
1674         bit_pos = fsl_readl(&dr_regs->endptcomplete);
1675         fsl_writel(bit_pos, &dr_regs->endptcomplete);
1676
1677         if (!bit_pos)
1678                 return;
1679
1680         for (i = 0; i < udc->max_ep * 2; i++) {
1681                 ep_num = i >> 1;
1682                 direction = i % 2;
1683
1684                 bit_mask = 1 << (ep_num + 16 * direction);
1685
1686                 if (!(bit_pos & bit_mask))
1687                         continue;
1688
1689                 curr_ep = get_ep_by_pipe(udc, i);
1690
1691                 /* If the ep is configured */
1692                 if (curr_ep->name == NULL) {
1693                         WARNING("Invalid EP?");
1694                         continue;
1695                 }
1696
1697                 /* process the req queue until an uncomplete request */
1698                 list_for_each_entry_safe(curr_req, temp_req, &curr_ep->queue,
1699                                 queue) {
1700                         status = process_ep_req(udc, i, curr_req);
1701
1702                         VDBG("status of process_ep_req= %d, ep = %d",
1703                                         status, ep_num);
1704                         if (status == REQ_UNCOMPLETE)
1705                                 break;
1706                         /* write back status to req */
1707                         curr_req->req.status = status;
1708
1709                         if (ep_num == 0) {
1710                                 ep0_req_complete(udc, curr_ep, curr_req);
1711                                 break;
1712                         } else
1713                                 done(curr_ep, curr_req, status);
1714                 }
1715         }
1716 }
1717
1718 static inline enum usb_device_speed portscx_device_speed(u32 reg)
1719 {
1720         switch (reg & PORTSCX_PORT_SPEED_MASK) {
1721         case PORTSCX_PORT_SPEED_HIGH:
1722                 return USB_SPEED_HIGH;
1723         case PORTSCX_PORT_SPEED_FULL:
1724                 return USB_SPEED_FULL;
1725         case PORTSCX_PORT_SPEED_LOW:
1726                 return USB_SPEED_LOW;
1727         default:
1728                 return USB_SPEED_UNKNOWN;
1729         }
1730 }
1731
1732 /* Process a port change interrupt */
1733 static void port_change_irq(struct fsl_udc *udc)
1734 {
1735         if (udc->bus_reset)
1736                 udc->bus_reset = 0;
1737
1738         /* Bus resetting is finished */
1739         if (!(fsl_readl(&dr_regs->portsc1) & PORTSCX_PORT_RESET))
1740                 /* Get the speed */
1741                 udc->gadget.speed =
1742                         portscx_device_speed(fsl_readl(&dr_regs->portsc1));
1743
1744         /* Update USB state */
1745         if (!udc->resume_state)
1746                 udc->usb_state = USB_STATE_DEFAULT;
1747 }
1748
1749 /* Process suspend interrupt */
1750 static void suspend_irq(struct fsl_udc *udc)
1751 {
1752         udc->resume_state = udc->usb_state;
1753         udc->usb_state = USB_STATE_SUSPENDED;
1754
1755         /* report suspend to the driver, serial.c does not support this */
1756         if (udc->driver->suspend)
1757                 udc->driver->suspend(&udc->gadget);
1758 }
1759
1760 static void bus_resume(struct fsl_udc *udc)
1761 {
1762         udc->usb_state = udc->resume_state;
1763         udc->resume_state = 0;
1764
1765         /* report resume to the driver, serial.c does not support this */
1766         if (udc->driver->resume)
1767                 udc->driver->resume(&udc->gadget);
1768 }
1769
1770 /* Clear up all ep queues */
1771 static int reset_queues(struct fsl_udc *udc)
1772 {
1773         u8 pipe;
1774
1775         for (pipe = 0; pipe < udc->max_pipes; pipe++)
1776                 udc_reset_ep_queue(udc, pipe);
1777
1778         /* report disconnect; the driver is already quiesced */
1779         spin_unlock(&udc->lock);
1780         udc->driver->disconnect(&udc->gadget);
1781         spin_lock(&udc->lock);
1782
1783         return 0;
1784 }
1785
1786 /* Process reset interrupt */
1787 static void reset_irq(struct fsl_udc *udc)
1788 {
1789         u32 temp;
1790         unsigned long timeout;
1791
1792         /* Clear the device address */
1793         temp = fsl_readl(&dr_regs->deviceaddr);
1794         fsl_writel(temp & ~USB_DEVICE_ADDRESS_MASK, &dr_regs->deviceaddr);
1795
1796         udc->device_address = 0;
1797
1798         /* Clear usb state */
1799         udc->resume_state = 0;
1800         udc->ep0_dir = 0;
1801         udc->ep0_state = WAIT_FOR_SETUP;
1802         udc->remote_wakeup = 0; /* default to 0 on reset */
1803         udc->gadget.b_hnp_enable = 0;
1804         udc->gadget.a_hnp_support = 0;
1805         udc->gadget.a_alt_hnp_support = 0;
1806
1807         /* Clear all the setup token semaphores */
1808         temp = fsl_readl(&dr_regs->endptsetupstat);
1809         fsl_writel(temp, &dr_regs->endptsetupstat);
1810
1811         /* Clear all the endpoint complete status bits */
1812         temp = fsl_readl(&dr_regs->endptcomplete);
1813         fsl_writel(temp, &dr_regs->endptcomplete);
1814
1815         timeout = jiffies + 100;
1816         while (fsl_readl(&dr_regs->endpointprime)) {
1817                 /* Wait until all endptprime bits cleared */
1818                 if (time_after(jiffies, timeout)) {
1819                         ERR("Timeout for reset\n");
1820                         break;
1821                 }
1822                 cpu_relax();
1823         }
1824
1825         /* Write 1s to the flush register */
1826         fsl_writel(0xffffffff, &dr_regs->endptflush);
1827
1828         if (fsl_readl(&dr_regs->portsc1) & PORTSCX_PORT_RESET) {
1829                 VDBG("Bus reset");
1830                 /* Bus is reseting */
1831                 udc->bus_reset = 1;
1832                 /* Reset all the queues, include XD, dTD, EP queue
1833                  * head and TR Queue */
1834                 reset_queues(udc);
1835                 udc->usb_state = USB_STATE_DEFAULT;
1836         } else {
1837                 VDBG("Controller reset");
1838                 /* initialize usb hw reg except for regs for EP, not
1839                  * touch usbintr reg */
1840                 dr_controller_setup(udc);
1841
1842                 /* Reset all internal used Queues */
1843                 reset_queues(udc);
1844
1845                 ep0_setup(udc);
1846
1847                 /* Enable DR IRQ reg, Set Run bit, change udc state */
1848                 dr_controller_run(udc);
1849                 udc->usb_state = USB_STATE_ATTACHED;
1850         }
1851 }
1852
1853 /*
1854  * USB device controller interrupt handler
1855  */
1856 static irqreturn_t fsl_udc_irq(int irq, void *_udc)
1857 {
1858         struct fsl_udc *udc = _udc;
1859         u32 irq_src;
1860         irqreturn_t status = IRQ_NONE;
1861         unsigned long flags;
1862
1863         /* Disable ISR for OTG host mode */
1864         if (udc->stopped)
1865                 return IRQ_NONE;
1866         spin_lock_irqsave(&udc->lock, flags);
1867         irq_src = fsl_readl(&dr_regs->usbsts) & fsl_readl(&dr_regs->usbintr);
1868         /* Clear notification bits */
1869         fsl_writel(irq_src, &dr_regs->usbsts);
1870
1871         /* VDBG("irq_src [0x%8x]", irq_src); */
1872
1873         /* Need to resume? */
1874         if (udc->usb_state == USB_STATE_SUSPENDED)
1875                 if ((fsl_readl(&dr_regs->portsc1) & PORTSCX_PORT_SUSPEND) == 0)
1876                         bus_resume(udc);
1877
1878         /* USB Interrupt */
1879         if (irq_src & USB_STS_INT) {
1880                 VDBG("Packet int");
1881                 /* Setup package, we only support ep0 as control ep */
1882                 if (fsl_readl(&dr_regs->endptsetupstat) & EP_SETUP_STATUS_EP0) {
1883                         tripwire_handler(udc, 0,
1884                                         (u8 *) (&udc->local_setup_buff));
1885                         setup_received_irq(udc, &udc->local_setup_buff);
1886                         status = IRQ_HANDLED;
1887                 }
1888
1889                 /* completion of dtd */
1890                 if (fsl_readl(&dr_regs->endptcomplete)) {
1891                         dtd_complete_irq(udc);
1892                         status = IRQ_HANDLED;
1893                 }
1894         }
1895
1896         /* SOF (for ISO transfer) */
1897         if (irq_src & USB_STS_SOF) {
1898                 status = IRQ_HANDLED;
1899         }
1900
1901         /* Port Change */
1902         if (irq_src & USB_STS_PORT_CHANGE) {
1903                 port_change_irq(udc);
1904                 status = IRQ_HANDLED;
1905         }
1906
1907         /* Reset Received */
1908         if (irq_src & USB_STS_RESET) {
1909                 VDBG("reset int");
1910                 reset_irq(udc);
1911                 status = IRQ_HANDLED;
1912         }
1913
1914         /* Sleep Enable (Suspend) */
1915         if (irq_src & USB_STS_SUSPEND) {
1916                 suspend_irq(udc);
1917                 status = IRQ_HANDLED;
1918         }
1919
1920         if (irq_src & (USB_STS_ERR | USB_STS_SYS_ERR)) {
1921                 VDBG("Error IRQ %x", irq_src);
1922         }
1923
1924         spin_unlock_irqrestore(&udc->lock, flags);
1925         return status;
1926 }
1927
1928 /*----------------------------------------------------------------*
1929  * Hook to gadget drivers
1930  * Called by initialization code of gadget drivers
1931 *----------------------------------------------------------------*/
1932 static int fsl_start(struct usb_gadget_driver *driver,
1933                 int (*bind)(struct usb_gadget *))
1934 {
1935         int retval = -ENODEV;
1936         unsigned long flags = 0;
1937
1938         if (!udc_controller)
1939                 return -ENODEV;
1940
1941         if (!driver || (driver->speed != USB_SPEED_FULL
1942                                 && driver->speed != USB_SPEED_HIGH)
1943                         || !bind || !driver->disconnect || !driver->setup)
1944                 return -EINVAL;
1945
1946         if (udc_controller->driver)
1947                 return -EBUSY;
1948
1949         /* lock is needed but whether should use this lock or another */
1950         spin_lock_irqsave(&udc_controller->lock, flags);
1951
1952         driver->driver.bus = NULL;
1953         /* hook up the driver */
1954         udc_controller->driver = driver;
1955         udc_controller->gadget.dev.driver = &driver->driver;
1956         spin_unlock_irqrestore(&udc_controller->lock, flags);
1957
1958         /* bind udc driver to gadget driver */
1959         retval = bind(&udc_controller->gadget);
1960         if (retval) {
1961                 VDBG("bind to %s --> %d", driver->driver.name, retval);
1962                 udc_controller->gadget.dev.driver = NULL;
1963                 udc_controller->driver = NULL;
1964                 goto out;
1965         }
1966
1967         if (udc_controller->transceiver) {
1968                 /* Suspend the controller until OTG enable it */
1969                 udc_controller->stopped = 1;
1970                 printk(KERN_INFO "Suspend udc for OTG auto detect\n");
1971
1972                 /* connect to bus through transceiver */
1973                 if (udc_controller->transceiver) {
1974                         retval = otg_set_peripheral(udc_controller->transceiver,
1975                                                     &udc_controller->gadget);
1976                         if (retval < 0) {
1977                                 ERR("can't bind to transceiver\n");
1978                                 driver->unbind(&udc_controller->gadget);
1979                                 udc_controller->gadget.dev.driver = 0;
1980                                 udc_controller->driver = 0;
1981                                 return retval;
1982                         }
1983                 }
1984         } else {
1985                 /* Enable DR IRQ reg and set USBCMD reg Run bit */
1986                 dr_controller_run(udc_controller);
1987                 udc_controller->usb_state = USB_STATE_ATTACHED;
1988                 udc_controller->ep0_state = WAIT_FOR_SETUP;
1989                 udc_controller->ep0_dir = 0;
1990         }
1991         printk(KERN_INFO "%s: bind to driver %s\n",
1992                         udc_controller->gadget.name, driver->driver.name);
1993
1994 out:
1995         if (retval)
1996                 printk(KERN_WARNING "gadget driver register failed %d\n",
1997                        retval);
1998         return retval;
1999 }
2000
2001 /* Disconnect from gadget driver */
2002 static int fsl_stop(struct usb_gadget_driver *driver)
2003 {
2004         struct fsl_ep *loop_ep;
2005         unsigned long flags;
2006
2007         if (!udc_controller)
2008                 return -ENODEV;
2009
2010         if (!driver || driver != udc_controller->driver || !driver->unbind)
2011                 return -EINVAL;
2012
2013         if (udc_controller->transceiver)
2014                 otg_set_peripheral(udc_controller->transceiver, NULL);
2015
2016         /* stop DR, disable intr */
2017         dr_controller_stop(udc_controller);
2018
2019         /* in fact, no needed */
2020         udc_controller->usb_state = USB_STATE_ATTACHED;
2021         udc_controller->ep0_state = WAIT_FOR_SETUP;
2022         udc_controller->ep0_dir = 0;
2023
2024         /* stand operation */
2025         spin_lock_irqsave(&udc_controller->lock, flags);
2026         udc_controller->gadget.speed = USB_SPEED_UNKNOWN;
2027         nuke(&udc_controller->eps[0], -ESHUTDOWN);
2028         list_for_each_entry(loop_ep, &udc_controller->gadget.ep_list,
2029                         ep.ep_list)
2030                 nuke(loop_ep, -ESHUTDOWN);
2031         spin_unlock_irqrestore(&udc_controller->lock, flags);
2032
2033         /* report disconnect; the controller is already quiesced */
2034         driver->disconnect(&udc_controller->gadget);
2035
2036         /* unbind gadget and unhook driver. */
2037         driver->unbind(&udc_controller->gadget);
2038         udc_controller->gadget.dev.driver = NULL;
2039         udc_controller->driver = NULL;
2040
2041         printk(KERN_WARNING "unregistered gadget driver '%s'\n",
2042                driver->driver.name);
2043         return 0;
2044 }
2045
2046 /*-------------------------------------------------------------------------
2047                 PROC File System Support
2048 -------------------------------------------------------------------------*/
2049 #ifdef CONFIG_USB_GADGET_DEBUG_FILES
2050
2051 #include <linux/seq_file.h>
2052
2053 static const char proc_filename[] = "driver/fsl_usb2_udc";
2054
2055 static int fsl_proc_read(char *page, char **start, off_t off, int count,
2056                 int *eof, void *_dev)
2057 {
2058         char *buf = page;
2059         char *next = buf;
2060         unsigned size = count;
2061         unsigned long flags;
2062         int t, i;
2063         u32 tmp_reg;
2064         struct fsl_ep *ep = NULL;
2065         struct fsl_req *req;
2066
2067         struct fsl_udc *udc = udc_controller;
2068         if (off != 0)
2069                 return 0;
2070
2071         spin_lock_irqsave(&udc->lock, flags);
2072
2073         /* ------basic driver information ---- */
2074         t = scnprintf(next, size,
2075                         DRIVER_DESC "\n"
2076                         "%s version: %s\n"
2077                         "Gadget driver: %s\n\n",
2078                         driver_name, DRIVER_VERSION,
2079                         udc->driver ? udc->driver->driver.name : "(none)");
2080         size -= t;
2081         next += t;
2082
2083         /* ------ DR Registers ----- */
2084         tmp_reg = fsl_readl(&dr_regs->usbcmd);
2085         t = scnprintf(next, size,
2086                         "USBCMD reg:\n"
2087                         "SetupTW: %d\n"
2088                         "Run/Stop: %s\n\n",
2089                         (tmp_reg & USB_CMD_SUTW) ? 1 : 0,
2090                         (tmp_reg & USB_CMD_RUN_STOP) ? "Run" : "Stop");
2091         size -= t;
2092         next += t;
2093
2094         tmp_reg = fsl_readl(&dr_regs->usbsts);
2095         t = scnprintf(next, size,
2096                         "USB Status Reg:\n"
2097                         "Dr Suspend: %d Reset Received: %d System Error: %s "
2098                         "USB Error Interrupt: %s\n\n",
2099                         (tmp_reg & USB_STS_SUSPEND) ? 1 : 0,
2100                         (tmp_reg & USB_STS_RESET) ? 1 : 0,
2101                         (tmp_reg & USB_STS_SYS_ERR) ? "Err" : "Normal",
2102                         (tmp_reg & USB_STS_ERR) ? "Err detected" : "No err");
2103         size -= t;
2104         next += t;
2105
2106         tmp_reg = fsl_readl(&dr_regs->usbintr);
2107         t = scnprintf(next, size,
2108                         "USB Intrrupt Enable Reg:\n"
2109                         "Sleep Enable: %d SOF Received Enable: %d "
2110                         "Reset Enable: %d\n"
2111                         "System Error Enable: %d "
2112                         "Port Change Dectected Enable: %d\n"
2113                         "USB Error Intr Enable: %d USB Intr Enable: %d\n\n",
2114                         (tmp_reg & USB_INTR_DEVICE_SUSPEND) ? 1 : 0,
2115                         (tmp_reg & USB_INTR_SOF_EN) ? 1 : 0,
2116                         (tmp_reg & USB_INTR_RESET_EN) ? 1 : 0,
2117                         (tmp_reg & USB_INTR_SYS_ERR_EN) ? 1 : 0,
2118                         (tmp_reg & USB_INTR_PTC_DETECT_EN) ? 1 : 0,
2119                         (tmp_reg & USB_INTR_ERR_INT_EN) ? 1 : 0,
2120                         (tmp_reg & USB_INTR_INT_EN) ? 1 : 0);
2121         size -= t;
2122         next += t;
2123
2124         tmp_reg = fsl_readl(&dr_regs->frindex);
2125         t = scnprintf(next, size,
2126                         "USB Frame Index Reg: Frame Number is 0x%x\n\n",
2127                         (tmp_reg & USB_FRINDEX_MASKS));
2128         size -= t;
2129         next += t;
2130
2131         tmp_reg = fsl_readl(&dr_regs->deviceaddr);
2132         t = scnprintf(next, size,
2133                         "USB Device Address Reg: Device Addr is 0x%x\n\n",
2134                         (tmp_reg & USB_DEVICE_ADDRESS_MASK));
2135         size -= t;
2136         next += t;
2137
2138         tmp_reg = fsl_readl(&dr_regs->endpointlistaddr);
2139         t = scnprintf(next, size,
2140                         "USB Endpoint List Address Reg: "
2141                         "Device Addr is 0x%x\n\n",
2142                         (tmp_reg & USB_EP_LIST_ADDRESS_MASK));
2143         size -= t;
2144         next += t;
2145
2146         tmp_reg = fsl_readl(&dr_regs->portsc1);
2147         t = scnprintf(next, size,
2148                 "USB Port Status&Control Reg:\n"
2149                 "Port Transceiver Type : %s Port Speed: %s\n"
2150                 "PHY Low Power Suspend: %s Port Reset: %s "
2151                 "Port Suspend Mode: %s\n"
2152                 "Over-current Change: %s "
2153                 "Port Enable/Disable Change: %s\n"
2154                 "Port Enabled/Disabled: %s "
2155                 "Current Connect Status: %s\n\n", ( {
2156                         char *s;
2157                         switch (tmp_reg & PORTSCX_PTS_FSLS) {
2158                         case PORTSCX_PTS_UTMI:
2159                                 s = "UTMI"; break;
2160                         case PORTSCX_PTS_ULPI:
2161                                 s = "ULPI "; break;
2162                         case PORTSCX_PTS_FSLS:
2163                                 s = "FS/LS Serial"; break;
2164                         default:
2165                                 s = "None"; break;
2166                         }
2167                         s;} ),
2168                 usb_speed_string(portscx_device_speed(tmp_reg)),
2169                 (tmp_reg & PORTSCX_PHY_LOW_POWER_SPD) ?
2170                 "Normal PHY mode" : "Low power mode",
2171                 (tmp_reg & PORTSCX_PORT_RESET) ? "In Reset" :
2172                 "Not in Reset",
2173                 (tmp_reg & PORTSCX_PORT_SUSPEND) ? "In " : "Not in",
2174                 (tmp_reg & PORTSCX_OVER_CURRENT_CHG) ? "Dected" :
2175                 "No",
2176                 (tmp_reg & PORTSCX_PORT_EN_DIS_CHANGE) ? "Disable" :
2177                 "Not change",
2178                 (tmp_reg & PORTSCX_PORT_ENABLE) ? "Enable" :
2179                 "Not correct",
2180                 (tmp_reg & PORTSCX_CURRENT_CONNECT_STATUS) ?
2181                 "Attached" : "Not-Att");
2182         size -= t;
2183         next += t;
2184
2185         tmp_reg = fsl_readl(&dr_regs->usbmode);
2186         t = scnprintf(next, size,
2187                         "USB Mode Reg: Controller Mode is: %s\n\n", ( {
2188                                 char *s;
2189                                 switch (tmp_reg & USB_MODE_CTRL_MODE_HOST) {
2190                                 case USB_MODE_CTRL_MODE_IDLE:
2191                                         s = "Idle"; break;
2192                                 case USB_MODE_CTRL_MODE_DEVICE:
2193                                         s = "Device Controller"; break;
2194                                 case USB_MODE_CTRL_MODE_HOST:
2195                                         s = "Host Controller"; break;
2196                                 default:
2197                                         s = "None"; break;
2198                                 }
2199                                 s;
2200                         } ));
2201         size -= t;
2202         next += t;
2203
2204         tmp_reg = fsl_readl(&dr_regs->endptsetupstat);
2205         t = scnprintf(next, size,
2206                         "Endpoint Setup Status Reg: SETUP on ep 0x%x\n\n",
2207                         (tmp_reg & EP_SETUP_STATUS_MASK));
2208         size -= t;
2209         next += t;
2210
2211         for (i = 0; i < udc->max_ep / 2; i++) {
2212                 tmp_reg = fsl_readl(&dr_regs->endptctrl[i]);
2213                 t = scnprintf(next, size, "EP Ctrl Reg [0x%x]: = [0x%x]\n",
2214                                 i, tmp_reg);
2215                 size -= t;
2216                 next += t;
2217         }
2218         tmp_reg = fsl_readl(&dr_regs->endpointprime);
2219         t = scnprintf(next, size, "EP Prime Reg = [0x%x]\n\n", tmp_reg);
2220         size -= t;
2221         next += t;
2222
2223 #ifndef CONFIG_ARCH_MXC
2224         if (udc->pdata->have_sysif_regs) {
2225                 tmp_reg = usb_sys_regs->snoop1;
2226                 t = scnprintf(next, size, "Snoop1 Reg : = [0x%x]\n\n", tmp_reg);
2227                 size -= t;
2228                 next += t;
2229
2230                 tmp_reg = usb_sys_regs->control;
2231                 t = scnprintf(next, size, "General Control Reg : = [0x%x]\n\n",
2232                                 tmp_reg);
2233                 size -= t;
2234                 next += t;
2235         }
2236 #endif
2237
2238         /* ------fsl_udc, fsl_ep, fsl_request structure information ----- */
2239         ep = &udc->eps[0];
2240         t = scnprintf(next, size, "For %s Maxpkt is 0x%x index is 0x%x\n",
2241                         ep->ep.name, ep_maxpacket(ep), ep_index(ep));
2242         size -= t;
2243         next += t;
2244
2245         if (list_empty(&ep->queue)) {
2246                 t = scnprintf(next, size, "its req queue is empty\n\n");
2247                 size -= t;
2248                 next += t;
2249         } else {
2250                 list_for_each_entry(req, &ep->queue, queue) {
2251                         t = scnprintf(next, size,
2252                                 "req %p actual 0x%x length 0x%x buf %p\n",
2253                                 &req->req, req->req.actual,
2254                                 req->req.length, req->req.buf);
2255                         size -= t;
2256                         next += t;
2257                 }
2258         }
2259         /* other gadget->eplist ep */
2260         list_for_each_entry(ep, &udc->gadget.ep_list, ep.ep_list) {
2261                 if (ep->desc) {
2262                         t = scnprintf(next, size,
2263                                         "\nFor %s Maxpkt is 0x%x "
2264                                         "index is 0x%x\n",
2265                                         ep->ep.name, ep_maxpacket(ep),
2266                                         ep_index(ep));
2267                         size -= t;
2268                         next += t;
2269
2270                         if (list_empty(&ep->queue)) {
2271                                 t = scnprintf(next, size,
2272                                                 "its req queue is empty\n\n");
2273                                 size -= t;
2274                                 next += t;
2275                         } else {
2276                                 list_for_each_entry(req, &ep->queue, queue) {
2277                                         t = scnprintf(next, size,
2278                                                 "req %p actual 0x%x length "
2279                                                 "0x%x  buf %p\n",
2280                                                 &req->req, req->req.actual,
2281                                                 req->req.length, req->req.buf);
2282                                         size -= t;
2283                                         next += t;
2284                                         }       /* end for each_entry of ep req */
2285                                 }       /* end for else */
2286                         }       /* end for if(ep->queue) */
2287                 }               /* end (ep->desc) */
2288
2289         spin_unlock_irqrestore(&udc->lock, flags);
2290
2291         *eof = 1;
2292         return count - size;
2293 }
2294
2295 #define create_proc_file()      create_proc_read_entry(proc_filename, \
2296                                 0, NULL, fsl_proc_read, NULL)
2297
2298 #define remove_proc_file()      remove_proc_entry(proc_filename, NULL)
2299
2300 #else                           /* !CONFIG_USB_GADGET_DEBUG_FILES */
2301
2302 #define create_proc_file()      do {} while (0)
2303 #define remove_proc_file()      do {} while (0)
2304
2305 #endif                          /* CONFIG_USB_GADGET_DEBUG_FILES */
2306
2307 /*-------------------------------------------------------------------------*/
2308
2309 /* Release udc structures */
2310 static void fsl_udc_release(struct device *dev)
2311 {
2312         complete(udc_controller->done);
2313         dma_free_coherent(dev->parent, udc_controller->ep_qh_size,
2314                         udc_controller->ep_qh, udc_controller->ep_qh_dma);
2315         kfree(udc_controller);
2316 }
2317
2318 /******************************************************************
2319         Internal structure setup functions
2320 *******************************************************************/
2321 /*------------------------------------------------------------------
2322  * init resource for globle controller
2323  * Return the udc handle on success or NULL on failure
2324  ------------------------------------------------------------------*/
2325 static int __init struct_udc_setup(struct fsl_udc *udc,
2326                 struct platform_device *pdev)
2327 {
2328         struct fsl_usb2_platform_data *pdata;
2329         size_t size;
2330
2331         pdata = pdev->dev.platform_data;
2332         udc->phy_mode = pdata->phy_mode;
2333
2334         udc->eps = kzalloc(sizeof(struct fsl_ep) * udc->max_ep, GFP_KERNEL);
2335         if (!udc->eps) {
2336                 ERR("malloc fsl_ep failed\n");
2337                 return -1;
2338         }
2339
2340         /* initialized QHs, take care of alignment */
2341         size = udc->max_ep * sizeof(struct ep_queue_head);
2342         if (size < QH_ALIGNMENT)
2343                 size = QH_ALIGNMENT;
2344         else if ((size % QH_ALIGNMENT) != 0) {
2345                 size += QH_ALIGNMENT + 1;
2346                 size &= ~(QH_ALIGNMENT - 1);
2347         }
2348         udc->ep_qh = dma_alloc_coherent(&pdev->dev, size,
2349                                         &udc->ep_qh_dma, GFP_KERNEL);
2350         if (!udc->ep_qh) {
2351                 ERR("malloc QHs for udc failed\n");
2352                 kfree(udc->eps);
2353                 return -1;
2354         }
2355
2356         udc->ep_qh_size = size;
2357
2358         /* Initialize ep0 status request structure */
2359         /* FIXME: fsl_alloc_request() ignores ep argument */
2360         udc->status_req = container_of(fsl_alloc_request(NULL, GFP_KERNEL),
2361                         struct fsl_req, req);
2362         /* allocate a small amount of memory to get valid address */
2363         udc->status_req->req.buf = kmalloc(8, GFP_KERNEL);
2364
2365         udc->resume_state = USB_STATE_NOTATTACHED;
2366         udc->usb_state = USB_STATE_POWERED;
2367         udc->ep0_dir = 0;
2368         udc->remote_wakeup = 0; /* default to 0 on reset */
2369
2370         return 0;
2371 }
2372
2373 /*----------------------------------------------------------------
2374  * Setup the fsl_ep struct for eps
2375  * Link fsl_ep->ep to gadget->ep_list
2376  * ep0out is not used so do nothing here
2377  * ep0in should be taken care
2378  *--------------------------------------------------------------*/
2379 static int __init struct_ep_setup(struct fsl_udc *udc, unsigned char index,
2380                 char *name, int link)
2381 {
2382         struct fsl_ep *ep = &udc->eps[index];
2383
2384         ep->udc = udc;
2385         strcpy(ep->name, name);
2386         ep->ep.name = ep->name;
2387
2388         ep->ep.ops = &fsl_ep_ops;
2389         ep->stopped = 0;
2390
2391         /* for ep0: maxP defined in desc
2392          * for other eps, maxP is set by epautoconfig() called by gadget layer
2393          */
2394         ep->ep.maxpacket = (unsigned short) ~0;
2395
2396         /* the queue lists any req for this ep */
2397         INIT_LIST_HEAD(&ep->queue);
2398
2399         /* gagdet.ep_list used for ep_autoconfig so no ep0 */
2400         if (link)
2401                 list_add_tail(&ep->ep.ep_list, &udc->gadget.ep_list);
2402         ep->gadget = &udc->gadget;
2403         ep->qh = &udc->ep_qh[index];
2404
2405         return 0;
2406 }
2407
2408 /* Driver probe function
2409  * all intialization operations implemented here except enabling usb_intr reg
2410  * board setup should have been done in the platform code
2411  */
2412 static int __init fsl_udc_probe(struct platform_device *pdev)
2413 {
2414         struct fsl_usb2_platform_data *pdata;
2415         struct resource *res;
2416         int ret = -ENODEV;
2417         unsigned int i;
2418         u32 dccparams;
2419
2420         if (strcmp(pdev->name, driver_name)) {
2421                 VDBG("Wrong device");
2422                 return -ENODEV;
2423         }
2424
2425         udc_controller = kzalloc(sizeof(struct fsl_udc), GFP_KERNEL);
2426         if (udc_controller == NULL) {
2427                 ERR("malloc udc failed\n");
2428                 return -ENOMEM;
2429         }
2430
2431         pdata = pdev->dev.platform_data;
2432         udc_controller->pdata = pdata;
2433         spin_lock_init(&udc_controller->lock);
2434         udc_controller->stopped = 1;
2435
2436 #ifdef CONFIG_USB_OTG
2437         if (pdata->operating_mode == FSL_USB2_DR_OTG) {
2438                 udc_controller->transceiver = otg_get_transceiver();
2439                 if (!udc_controller->transceiver) {
2440                         ERR("Can't find OTG driver!\n");
2441                         ret = -ENODEV;
2442                         goto err_kfree;
2443                 }
2444         }
2445 #endif
2446
2447         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2448         if (!res) {
2449                 ret = -ENXIO;
2450                 goto err_kfree;
2451         }
2452
2453         if (pdata->operating_mode == FSL_USB2_DR_DEVICE) {
2454                 if (!request_mem_region(res->start, resource_size(res),
2455                                         driver_name)) {
2456                         ERR("request mem region for %s failed\n", pdev->name);
2457                         ret = -EBUSY;
2458                         goto err_kfree;
2459                 }
2460         }
2461
2462         dr_regs = ioremap(res->start, resource_size(res));
2463         if (!dr_regs) {
2464                 ret = -ENOMEM;
2465                 goto err_release_mem_region;
2466         }
2467
2468         pdata->regs = (void *)dr_regs;
2469
2470         /*
2471          * do platform specific init: check the clock, grab/config pins, etc.
2472          */
2473         if (pdata->init && pdata->init(pdev)) {
2474                 ret = -ENODEV;
2475                 goto err_iounmap_noclk;
2476         }
2477
2478         /* Set accessors only after pdata->init() ! */
2479         fsl_set_accessors(pdata);
2480
2481 #ifndef CONFIG_ARCH_MXC
2482         if (pdata->have_sysif_regs)
2483                 usb_sys_regs = (struct usb_sys_interface *)
2484                                 ((u32)dr_regs + USB_DR_SYS_OFFSET);
2485 #endif
2486
2487         /* Initialize USB clocks */
2488         ret = fsl_udc_clk_init(pdev);
2489         if (ret < 0)
2490                 goto err_iounmap_noclk;
2491
2492         /* Read Device Controller Capability Parameters register */
2493         dccparams = fsl_readl(&dr_regs->dccparams);
2494         if (!(dccparams & DCCPARAMS_DC)) {
2495                 ERR("This SOC doesn't support device role\n");
2496                 ret = -ENODEV;
2497                 goto err_iounmap;
2498         }
2499         /* Get max device endpoints */
2500         /* DEN is bidirectional ep number, max_ep doubles the number */
2501         udc_controller->max_ep = (dccparams & DCCPARAMS_DEN_MASK) * 2;
2502
2503         udc_controller->irq = platform_get_irq(pdev, 0);
2504         if (!udc_controller->irq) {
2505                 ret = -ENODEV;
2506                 goto err_iounmap;
2507         }
2508
2509         ret = request_irq(udc_controller->irq, fsl_udc_irq, IRQF_SHARED,
2510                         driver_name, udc_controller);
2511         if (ret != 0) {
2512                 ERR("cannot request irq %d err %d\n",
2513                                 udc_controller->irq, ret);
2514                 goto err_iounmap;
2515         }
2516
2517         /* Initialize the udc structure including QH member and other member */
2518         if (struct_udc_setup(udc_controller, pdev)) {
2519                 ERR("Can't initialize udc data structure\n");
2520                 ret = -ENOMEM;
2521                 goto err_free_irq;
2522         }
2523
2524         if (!udc_controller->transceiver) {
2525                 /* initialize usb hw reg except for regs for EP,
2526                  * leave usbintr reg untouched */
2527                 dr_controller_setup(udc_controller);
2528         }
2529
2530         fsl_udc_clk_finalize(pdev);
2531
2532         /* Setup gadget structure */
2533         udc_controller->gadget.ops = &fsl_gadget_ops;
2534         udc_controller->gadget.is_dualspeed = 1;
2535         udc_controller->gadget.ep0 = &udc_controller->eps[0].ep;
2536         INIT_LIST_HEAD(&udc_controller->gadget.ep_list);
2537         udc_controller->gadget.speed = USB_SPEED_UNKNOWN;
2538         udc_controller->gadget.name = driver_name;
2539
2540         /* Setup gadget.dev and register with kernel */
2541         dev_set_name(&udc_controller->gadget.dev, "gadget");
2542         udc_controller->gadget.dev.release = fsl_udc_release;
2543         udc_controller->gadget.dev.parent = &pdev->dev;
2544         ret = device_register(&udc_controller->gadget.dev);
2545         if (ret < 0)
2546                 goto err_free_irq;
2547
2548         if (udc_controller->transceiver)
2549                 udc_controller->gadget.is_otg = 1;
2550
2551         /* setup QH and epctrl for ep0 */
2552         ep0_setup(udc_controller);
2553
2554         /* setup udc->eps[] for ep0 */
2555         struct_ep_setup(udc_controller, 0, "ep0", 0);
2556         /* for ep0: the desc defined here;
2557          * for other eps, gadget layer called ep_enable with defined desc
2558          */
2559         udc_controller->eps[0].desc = &fsl_ep0_desc;
2560         udc_controller->eps[0].ep.maxpacket = USB_MAX_CTRL_PAYLOAD;
2561
2562         /* setup the udc->eps[] for non-control endpoints and link
2563          * to gadget.ep_list */
2564         for (i = 1; i < (int)(udc_controller->max_ep / 2); i++) {
2565                 char name[14];
2566
2567                 sprintf(name, "ep%dout", i);
2568                 struct_ep_setup(udc_controller, i * 2, name, 1);
2569                 sprintf(name, "ep%din", i);
2570                 struct_ep_setup(udc_controller, i * 2 + 1, name, 1);
2571         }
2572
2573         /* use dma_pool for TD management */
2574         udc_controller->td_pool = dma_pool_create("udc_td", &pdev->dev,
2575                         sizeof(struct ep_td_struct),
2576                         DTD_ALIGNMENT, UDC_DMA_BOUNDARY);
2577         if (udc_controller->td_pool == NULL) {
2578                 ret = -ENOMEM;
2579                 goto err_unregister;
2580         }
2581
2582         ret = usb_add_gadget_udc(&pdev->dev, &udc_controller->gadget);
2583         if (ret)
2584                 goto err_del_udc;
2585
2586         create_proc_file();
2587         return 0;
2588
2589 err_del_udc:
2590         dma_pool_destroy(udc_controller->td_pool);
2591 err_unregister:
2592         device_unregister(&udc_controller->gadget.dev);
2593 err_free_irq:
2594         free_irq(udc_controller->irq, udc_controller);
2595 err_iounmap:
2596         if (pdata->exit)
2597                 pdata->exit(pdev);
2598         fsl_udc_clk_release();
2599 err_iounmap_noclk:
2600         iounmap(dr_regs);
2601 err_release_mem_region:
2602         if (pdata->operating_mode == FSL_USB2_DR_DEVICE)
2603                 release_mem_region(res->start, resource_size(res));
2604 err_kfree:
2605         kfree(udc_controller);
2606         udc_controller = NULL;
2607         return ret;
2608 }
2609
2610 /* Driver removal function
2611  * Free resources and finish pending transactions
2612  */
2613 static int __exit fsl_udc_remove(struct platform_device *pdev)
2614 {
2615         struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2616         struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data;
2617
2618         DECLARE_COMPLETION(done);
2619
2620         if (!udc_controller)
2621                 return -ENODEV;
2622
2623         usb_del_gadget_udc(&udc_controller->gadget);
2624         udc_controller->done = &done;
2625
2626         fsl_udc_clk_release();
2627
2628         /* DR has been stopped in usb_gadget_unregister_driver() */
2629         remove_proc_file();
2630
2631         /* Free allocated memory */
2632         kfree(udc_controller->status_req->req.buf);
2633         kfree(udc_controller->status_req);
2634         kfree(udc_controller->eps);
2635
2636         dma_pool_destroy(udc_controller->td_pool);
2637         free_irq(udc_controller->irq, udc_controller);
2638         iounmap(dr_regs);
2639         if (pdata->operating_mode == FSL_USB2_DR_DEVICE)
2640                 release_mem_region(res->start, resource_size(res));
2641
2642         device_unregister(&udc_controller->gadget.dev);
2643         /* free udc --wait for the release() finished */
2644         wait_for_completion(&done);
2645
2646         /*
2647          * do platform specific un-initialization:
2648          * release iomux pins, etc.
2649          */
2650         if (pdata->exit)
2651                 pdata->exit(pdev);
2652
2653         return 0;
2654 }
2655
2656 /*-----------------------------------------------------------------
2657  * Modify Power management attributes
2658  * Used by OTG statemachine to disable gadget temporarily
2659  -----------------------------------------------------------------*/
2660 static int fsl_udc_suspend(struct platform_device *pdev, pm_message_t state)
2661 {
2662         dr_controller_stop(udc_controller);
2663         return 0;
2664 }
2665
2666 /*-----------------------------------------------------------------
2667  * Invoked on USB resume. May be called in_interrupt.
2668  * Here we start the DR controller and enable the irq
2669  *-----------------------------------------------------------------*/
2670 static int fsl_udc_resume(struct platform_device *pdev)
2671 {
2672         /* Enable DR irq reg and set controller Run */
2673         if (udc_controller->stopped) {
2674                 dr_controller_setup(udc_controller);
2675                 dr_controller_run(udc_controller);
2676         }
2677         udc_controller->usb_state = USB_STATE_ATTACHED;
2678         udc_controller->ep0_state = WAIT_FOR_SETUP;
2679         udc_controller->ep0_dir = 0;
2680         return 0;
2681 }
2682
2683 static int fsl_udc_otg_suspend(struct device *dev, pm_message_t state)
2684 {
2685         struct fsl_udc *udc = udc_controller;
2686         u32 mode, usbcmd;
2687
2688         mode = fsl_readl(&dr_regs->usbmode) & USB_MODE_CTRL_MODE_MASK;
2689
2690         pr_debug("%s(): mode 0x%x stopped %d\n", __func__, mode, udc->stopped);
2691
2692         /*
2693          * If the controller is already stopped, then this must be a
2694          * PM suspend.  Remember this fact, so that we will leave the
2695          * controller stopped at PM resume time.
2696          */
2697         if (udc->stopped) {
2698                 pr_debug("gadget already stopped, leaving early\n");
2699                 udc->already_stopped = 1;
2700                 return 0;
2701         }
2702
2703         if (mode != USB_MODE_CTRL_MODE_DEVICE) {
2704                 pr_debug("gadget not in device mode, leaving early\n");
2705                 return 0;
2706         }
2707
2708         /* stop the controller */
2709         usbcmd = fsl_readl(&dr_regs->usbcmd) & ~USB_CMD_RUN_STOP;
2710         fsl_writel(usbcmd, &dr_regs->usbcmd);
2711
2712         udc->stopped = 1;
2713
2714         pr_info("USB Gadget suspended\n");
2715
2716         return 0;
2717 }
2718
2719 static int fsl_udc_otg_resume(struct device *dev)
2720 {
2721         pr_debug("%s(): stopped %d  already_stopped %d\n", __func__,
2722                  udc_controller->stopped, udc_controller->already_stopped);
2723
2724         /*
2725          * If the controller was stopped at suspend time, then
2726          * don't resume it now.
2727          */
2728         if (udc_controller->already_stopped) {
2729                 udc_controller->already_stopped = 0;
2730                 pr_debug("gadget was already stopped, leaving early\n");
2731                 return 0;
2732         }
2733
2734         pr_info("USB Gadget resume\n");
2735
2736         return fsl_udc_resume(NULL);
2737 }
2738
2739 /*-------------------------------------------------------------------------
2740         Register entry point for the peripheral controller driver
2741 --------------------------------------------------------------------------*/
2742
2743 static struct platform_driver udc_driver = {
2744         .remove  = __exit_p(fsl_udc_remove),
2745         /* these suspend and resume are not usb suspend and resume */
2746         .suspend = fsl_udc_suspend,
2747         .resume  = fsl_udc_resume,
2748         .driver  = {
2749                 .name = (char *)driver_name,
2750                 .owner = THIS_MODULE,
2751                 /* udc suspend/resume called from OTG driver */
2752                 .suspend = fsl_udc_otg_suspend,
2753                 .resume  = fsl_udc_otg_resume,
2754         },
2755 };
2756
2757 static int __init udc_init(void)
2758 {
2759         printk(KERN_INFO "%s (%s)\n", driver_desc, DRIVER_VERSION);
2760         return platform_driver_probe(&udc_driver, fsl_udc_probe);
2761 }
2762
2763 module_init(udc_init);
2764
2765 static void __exit udc_exit(void)
2766 {
2767         platform_driver_unregister(&udc_driver);
2768         printk(KERN_WARNING "%s unregistered\n", driver_desc);
2769 }
2770
2771 module_exit(udc_exit);
2772
2773 MODULE_DESCRIPTION(DRIVER_DESC);
2774 MODULE_AUTHOR(DRIVER_AUTHOR);
2775 MODULE_LICENSE("GPL");
2776 MODULE_ALIAS("platform:fsl-usb2-udc");