]> rtime.felk.cvut.cz Git - sojka/nv-tegra/linux-3.10.git/blob - drivers/usb/gadget/tegra_udc.c
36deb861cc3a36e606ec5e5aa56f97dab94aea5c
[sojka/nv-tegra/linux-3.10.git] / drivers / usb / gadget / tegra_udc.c
1 /*
2  * Copyright (c) 2012-2014, NVIDIA CORPORATION.  All rights reserved.
3  *
4  * Description:
5  * High-speed USB device controller driver.
6  * The driver is based on Freescale driver code from Li Yang and Jiang Bo.
7  *
8  * This program is free software; you can redistribute  it and/or modify it
9  * under  the terms of  the GNU General  Public License as published by the
10  * Free Software Foundation;  either version 2 of the  License, or (at your
11  * option) any later version.
12  */
13
14 #undef VERBOSE
15
16 #include <linux/module.h>
17 #include <linux/kernel.h>
18 #include <linux/ioport.h>
19 #include <linux/types.h>
20 #include <linux/errno.h>
21 #include <linux/slab.h>
22 #include <linux/init.h>
23 #include <linux/list.h>
24 #include <linux/interrupt.h>
25 #include <linux/proc_fs.h>
26 #include <linux/mm.h>
27 #include <linux/moduleparam.h>
28 #include <linux/device.h>
29 #include <linux/usb/ch9.h>
30 #include <linux/usb/gadget.h>
31 #include <linux/usb/otg.h>
32 #include <linux/dma-mapping.h>
33 #include <linux/platform_device.h>
34 #include <linux/dmapool.h>
35 #include <linux/delay.h>
36 #include <linux/regulator/consumer.h>
37 #include <linux/extcon.h>
38 #include <linux/workqueue.h>
39 #include <linux/err.h>
40 #include <linux/io.h>
41 #include <linux/pm_qos.h>
42 #include <linux/usb/tegra_usb_phy.h>
43 #include <linux/platform_data/tegra_usb.h>
44 #include <linux/timer.h>
45 #include <linux/tegra-soc.h>
46
47 #include <asm/byteorder.h>
48 #include <asm/io.h>
49 #include <asm/unaligned.h>
50 #include <asm/dma.h>
51
52 /* HACK! This needs to come from DT */
53 #include "../../../arch/arm/mach-tegra/iomap.h"
54
55 #include "tegra_udc.h"
56
57
58 #define DRIVER_DESC     "Nvidia Tegra High-Speed USB Device Controller driver"
59
60 #define DRIVER_AUTHOR   "Venkat Moganty/Rakesh Bodla"
61 #define DRIVER_VERSION  "Apr 30, 2012"
62
63 #define USB1_PREFETCH_ID        6
64
65 #define AHB_PREFETCH_BUFFER     SZ_128
66
67 #define get_ep_by_pipe(udc, pipe)       ((pipe == 1) ? &udc->eps[0] : \
68                                                 &udc->eps[pipe])
69 #define get_pipe_by_windex(windex)      ((windex & USB_ENDPOINT_NUMBER_MASK) \
70                                         * 2 + ((windex & USB_DIR_IN) ? 1 : 0))
71
72 #define ep_index(EP)    ((EP)->desc->bEndpointAddress&0xF)
73 #define ep_is_in(EP)    ((ep_index(EP) == 0) ? (EP->udc->ep0_dir == \
74                                 USB_DIR_IN) : ((EP)->desc->bEndpointAddress \
75                                 & USB_DIR_IN) == USB_DIR_IN)
76
77
78 static const char driver_name[] = "tegra-udc";
79 static const char driver_desc[] = DRIVER_DESC;
80
81 static void tegra_ep_fifo_flush(struct usb_ep *_ep);
82 static int reset_queues(struct tegra_udc *udc);
83
84 /*
85  * High speed test mode packet(53 bytes).
86  * See USB 2.0 spec, section 7.1.20.
87  */
88 static const u8 tegra_udc_test_packet[53] = {
89         /* JKJKJKJK x9 */
90         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
91         /* JJKKJJKK x8 */
92         0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
93         /* JJJJKKKK x8 */
94         0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee,
95         /* JJJJJJJKKKKKKK x8 */
96         0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
97         /* JJJJJJJK x8 */
98         0x7f, 0xbf, 0xdf, 0xef, 0xf7, 0xfb, 0xfd,
99         /* JKKKKKKK x10, JK */
100         0xfc, 0x7e, 0xbf, 0xdf, 0xef, 0xf7, 0xfb, 0xfd, 0x7e
101 };
102
103 static struct tegra_udc *the_udc;
104
105 #ifdef CONFIG_TEGRA_GADGET_BOOST_CPU_FREQ
106 static struct pm_qos_request boost_cpu_freq_req;
107 static u32 ep_queue_request_count;
108 static u8 boost_cpufreq_work_flag, set_cpufreq_normal_flag;
109 static struct timer_list boost_timer;
110 static bool boost_enable = true;
111 static int boost_enable_set(const char *arg, const struct kernel_param *kp)
112 {
113         bool old_boost = boost_enable;
114         int ret = param_set_bool(arg, kp);
115         if (ret == 0 && old_boost && !boost_enable)
116                 pm_qos_update_request(&boost_cpu_freq_req,
117                                       PM_QOS_DEFAULT_VALUE);
118         return ret;
119 }
120 static int boost_enable_get(char *buffer, const struct kernel_param *kp)
121 {
122         return param_get_bool(buffer, kp);
123 }
124 static struct kernel_param_ops boost_enable_ops = {
125         .set = boost_enable_set,
126         .get = boost_enable_get,
127 };
128 module_param_cb(boost_enable, &boost_enable_ops, &boost_enable, 0644);
129 #endif
130
131 static char *const tegra_udc_extcon_cable[] = {
132         [CONNECT_TYPE_NONE] = "",
133         [CONNECT_TYPE_SDP] = "USB",
134         [CONNECT_TYPE_DCP] = "TA",
135         [CONNECT_TYPE_DCP_QC2] = "QC2",
136         [CONNECT_TYPE_DCP_MAXIM] = "MAXIM",
137         [CONNECT_TYPE_CDP] = "Charge-downstream",
138         [CONNECT_TYPE_NV_CHARGER] = "Fast-charger",
139         [CONNECT_TYPE_NON_STANDARD_CHARGER] = "Slow-charger",
140         [CONNECT_TYPE_APPLE_500MA]  = "Apple 500mA-charger",
141         [CONNECT_TYPE_APPLE_1000MA] = "Apple 1A-charger",
142         [CONNECT_TYPE_APPLE_2000MA] = "Apple 2A-charger",
143         NULL,
144 };
145
146 static inline void udc_writel(struct tegra_udc *udc, u32 val, u32 offset)
147 {
148         writel(val, udc->regs + offset);
149 }
150
151 static inline unsigned int udc_readl(struct tegra_udc *udc, u32 offset)
152 {
153         return readl(udc->regs + offset);
154 }
155
156 /* checks vbus status */
157 static inline bool vbus_enabled(struct tegra_udc *udc)
158 {
159         bool status = false;
160         if (tegra_platform_is_fpga()) {
161                 /* On FPGA VBUS is detected through VBUS A Session instead
162                  * of VBUS status.*/
163                 status = (udc_readl(udc, VBUS_SENSOR_REG_OFFSET)
164                                                 & USB_SYS_VBUS_ASESSION);
165         } else if (!udc->support_pmu_vbus) {
166                 status = (udc_readl(udc, VBUS_WAKEUP_REG_OFFSET)
167                                                 & USB_SYS_VBUS_STATUS);
168         }
169
170         return status;
171 }
172
173 /**
174  * done() - retire a request; caller blocked irqs
175  * @status : request status to be set, only works when
176  * request is still in progress.
177  */
178 static void done(struct tegra_ep *ep, struct tegra_req *req, int status)
179 {
180         struct tegra_udc *udc = NULL;
181         unsigned char stopped = ep->stopped;
182         struct ep_td_struct *curr_td, *next_td = 0;
183         int j;
184         int count;
185
186         BUG_ON(!(in_irq() || irqs_disabled()));
187         udc = (struct tegra_udc *)ep->udc;
188         /* Removed the req from tegra_ep->queue */
189         list_del_init(&req->queue);
190
191         /* req.status should be set as -EINPROGRESS in ep_queue() */
192         if (req->req.status == -EINPROGRESS)
193                 req->req.status = status;
194         else
195                 status = req->req.status;
196
197         /* Free dtd for the request */
198         count = 0;
199         if (ep->last_td) {
200                 next_td = ep->last_td;
201                 count = ep->last_dtd_count;
202         }
203         ep->last_td = req->head;
204         ep->last_dtd_count = req->dtd_count;
205
206         for (j = 0; j < count; j++) {
207                 curr_td = next_td;
208                 if (j != count - 1) {
209                         next_td = curr_td->next_td_virt;
210                 }
211                 dma_pool_free(udc->td_pool, curr_td, curr_td->td_dma);
212         }
213
214         if (req->mapped) {
215                 DEFINE_DMA_ATTRS(attrs);
216                 struct device *dev = ep->udc->gadget.dev.parent;
217                 size_t orig = req->req.length;
218                 size_t ext = orig + AHB_PREFETCH_BUFFER;
219                 enum dma_data_direction dir =
220                         ep_is_in(ep) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
221
222                 dma_sync_single_for_cpu(dev, req->req.dma, orig, dir);
223                 dma_set_attr(DMA_ATTR_SKIP_CPU_SYNC, &attrs);
224                 dma_unmap_single_attrs(dev, req->req.dma, ext, dir, &attrs);
225
226                 req->req.dma = DMA_ADDR_INVALID;
227                 req->mapped = 0;
228         } else
229                 dma_sync_single_for_cpu(ep->udc->gadget.dev.parent,
230                         req->req.dma, req->req.length,
231                         ep_is_in(ep)
232                                 ? DMA_TO_DEVICE
233                                 : DMA_FROM_DEVICE);
234
235         if (status && (status != -ESHUTDOWN))
236                 VDBG("complete %s req %p stat %d len %u/%u",
237                         ep->ep.name, &req->req, status,
238                         req->req.actual, req->req.length);
239
240         ep->stopped = 1;
241 #ifdef CONFIG_TEGRA_GADGET_BOOST_CPU_FREQ
242         if (req->req.complete && req->req.length >= BOOST_TRIGGER_SIZE)
243                 ep_queue_request_count--;
244 #endif
245
246         /* complete() is from gadget layer,
247          * eg fsg->bulk_in_complete() */
248         if (req->req.complete) {
249                 spin_unlock(&ep->udc->lock);
250                 req->req.complete(&ep->ep, &req->req);
251                 spin_lock(&ep->udc->lock);
252         }
253
254         ep->stopped = stopped;
255 }
256
257 /*
258  * nuke(): delete all requests related to this ep
259  * Must be called with spinlock held and interrupt disabled
260  */
261 static void nuke(struct tegra_ep *ep, int status)
262 {
263         ep->stopped = 1;
264
265         /* Flush fifo */
266         tegra_ep_fifo_flush(&ep->ep);
267
268         /* Whether this eq has request linked */
269         while (!list_empty(&ep->queue)) {
270                 struct tegra_req *req = NULL;
271
272                 req = list_entry(ep->queue.next, struct tegra_req, queue);
273                 done(ep, req, status);
274         }
275 }
276
277 static int can_pullup(struct tegra_udc *udc)
278 {
279         DBG("%s(%d) driver = %d softconnect = %d vbus_active = %d\n", __func__,
280                 __LINE__, udc->driver ? 1 : 0, udc->softconnect,
281                 udc->vbus_active);
282         return udc->driver && udc->softconnect && udc->vbus_active;
283 }
284
285 static int dr_controller_reset(struct tegra_udc *udc)
286 {
287         unsigned int tmp;
288         unsigned long timeout;
289         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
290
291         /* Stop and reset the usb controller */
292         tmp = udc_readl(udc, USB_CMD_REG_OFFSET);
293         tmp &= ~USB_CMD_RUN_STOP;
294         udc_writel(udc, tmp, USB_CMD_REG_OFFSET);
295
296         tmp = udc_readl(udc, USB_CMD_REG_OFFSET);
297         tmp |= USB_CMD_CTRL_RESET;
298         udc_writel(udc, tmp, USB_CMD_REG_OFFSET);
299
300         /* Wait for reset to complete */
301         timeout = jiffies + UDC_RESET_TIMEOUT_MS;
302         while (udc_readl(udc, USB_CMD_REG_OFFSET) & USB_CMD_CTRL_RESET) {
303                 if (time_after(jiffies, timeout)) {
304                         ERR("udc reset timeout!\n");
305                         return -ETIMEDOUT;
306                 }
307                 cpu_relax();
308         }
309
310         DBG("%s(%d) END\n", __func__, __LINE__);
311         return 0;
312 }
313
314 static int dr_controller_setup(struct tegra_udc *udc)
315 {
316         unsigned int tmp, portctrl;
317         unsigned long timeout;
318         int status;
319         unsigned int port_control_reg_offset;
320         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
321
322         if (udc->has_hostpc)
323                 port_control_reg_offset = USB_HOSTPCX_DEVLC_REG_OFFSET;
324         else
325                 port_control_reg_offset = PORTSCX_REG_OFFSET;
326
327         /* Config PHY interface */
328         portctrl = udc_readl(udc, port_control_reg_offset);
329         portctrl &= ~(PORTSCX_PHY_TYPE_SEL | PORTSCX_PORT_WIDTH);
330         portctrl |= PORTSCX_PTS_UTMI;
331         udc_writel(udc, portctrl, port_control_reg_offset);
332
333         status = dr_controller_reset(udc);
334         if (status)
335                 return status;
336
337         /* Set the controller as device mode */
338         tmp = udc_readl(udc, USB_MODE_REG_OFFSET);
339         tmp |= USB_MODE_CTRL_MODE_DEVICE;
340         /* Disable Setup Lockout */
341         tmp |= USB_MODE_SETUP_LOCK_OFF;
342         udc_writel(udc, tmp, USB_MODE_REG_OFFSET);
343
344         /* Wait for controller to switch to device mode */
345         timeout = jiffies + UDC_RESET_TIMEOUT_MS;
346         while ((udc_readl(udc, USB_MODE_REG_OFFSET) &
347                 USB_MODE_CTRL_MODE_DEVICE) != USB_MODE_CTRL_MODE_DEVICE) {
348                 if (time_after(jiffies, timeout)) {
349                         ERR("udc device mode setup timeout!\n");
350                         return -ETIMEDOUT;
351                 }
352                 cpu_relax();
353         }
354
355         /* Clear the setup status */
356         udc_writel(udc, 0, USB_STS_REG_OFFSET);
357
358         tmp = udc->ep_qh_dma;
359         tmp &= USB_EP_LIST_ADDRESS_MASK;
360         udc_writel(udc, tmp, USB_EP_LIST_ADDRESS_REG_OFFSET);
361
362         VDBG("vir[qh_base] is %p phy[qh_base] is 0x%8x reg is 0x%8x",
363                 udc->ep_qh, (int)tmp,
364                 udc_readl(udc, USB_EP_LIST_ADDRESS_REG_OFFSET));
365
366         DBG("%s(%d) END\n", __func__, __LINE__);
367         return 0;
368 }
369
370 /* Enable DR irq and set controller to run state */
371 static void dr_controller_run(struct tegra_udc *udc)
372 {
373         u32 temp;
374         unsigned long timeout;
375         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
376
377         /* Clear stopped bit */
378         udc->stopped = 0;
379
380         /* If OTG transceiver is available, then it handles the VBUS detection*/
381         if (!udc->transceiver) {
382                 if (tegra_platform_is_fpga()) {
383                         /* On FPGA VBUS is detected through VBUS A Session
384                          * instead of VBUS status.*/
385                         temp = udc_readl(udc, VBUS_SENSOR_REG_OFFSET);
386                         temp |= USB_SYS_VBUS_ASESSION_INT_EN;
387                         temp &= ~USB_SYS_VBUS_ASESSION_CHANGED;
388                         udc_writel(udc, temp, VBUS_SENSOR_REG_OFFSET);
389                 } else {
390                         /* Enable cable detection interrupt, without setting the
391                          * USB_SYS_VBUS_WAKEUP_INT bit. USB_SYS_VBUS_WAKEUP_INT
392                          * is clear on write */
393                         temp = udc_readl(udc, VBUS_WAKEUP_REG_OFFSET);
394                         temp |= (USB_SYS_VBUS_WAKEUP_INT_ENABLE
395                                         | USB_SYS_VBUS_WAKEUP_ENABLE);
396                         temp &= ~USB_SYS_VBUS_WAKEUP_INT_STATUS;
397                         udc_writel(udc, temp, VBUS_WAKEUP_REG_OFFSET);
398                 }
399         } else
400                 udc_writel(udc, 0, VBUS_SENSOR_REG_OFFSET);
401
402         /* Enable DR irq reg */
403         temp = USB_INTR_INT_EN | USB_INTR_ERR_INT_EN
404                 | USB_INTR_PTC_DETECT_EN | USB_INTR_RESET_EN
405                 | USB_INTR_DEVICE_SUSPEND | USB_INTR_SYS_ERR_EN;
406
407         udc_writel(udc, temp, USB_INTR_REG_OFFSET);
408
409         /* Set the controller as device mode */
410         temp = udc_readl(udc, USB_MODE_REG_OFFSET);
411         temp |= USB_MODE_CTRL_MODE_DEVICE;
412         udc_writel(udc, temp, USB_MODE_REG_OFFSET);
413
414         if (udc->support_pmu_vbus) {
415                 temp = udc_readl(udc, VBUS_SENSOR_REG_OFFSET);
416                 temp |= (USB_SYS_VBUS_A_VLD_SW_VALUE |
417                                         USB_SYS_VBUS_A_VLD_SW_EN |
418                                         USB_SYS_VBUS_ASESSION_VLD_SW_VALUE |
419                                         USB_SYS_VBUS_ASESSION_VLD_SW_EN);
420                 udc_writel(udc, temp, VBUS_SENSOR_REG_OFFSET);
421         }
422
423         /* set interrupt latency to 125 uS (1 uFrame) */
424         /* Set controller to Run */
425         temp = udc_readl(udc, USB_CMD_REG_OFFSET);
426         temp &= ~USB_CMD_ITC;
427         temp |= USB_CMD_ITC_1_MICRO_FRM;
428         if (can_pullup(udc)) {
429                 temp |= USB_CMD_RUN_STOP;
430                 if (udc->charging_supported &&
431                         (udc->connect_type == CONNECT_TYPE_SDP))
432                         schedule_delayed_work(&udc->non_std_charger_work,
433                                 msecs_to_jiffies(NON_STD_CHARGER_DET_TIME_MS));
434         }
435         else
436                 temp &= ~USB_CMD_RUN_STOP;
437         udc_writel(udc, temp, USB_CMD_REG_OFFSET);
438
439         if (can_pullup(udc)) {
440                 /* Wait for controller to start */
441                 timeout = jiffies + UDC_RUN_TIMEOUT_MS;
442                 while ((udc_readl(udc, USB_CMD_REG_OFFSET) & USB_CMD_RUN_STOP)
443                         != USB_CMD_RUN_STOP) {
444                         if (time_after(jiffies, timeout)) {
445                                 ERR("udc start timeout!\n");
446                                 return;
447                         }
448                         cpu_relax();
449                 }
450         }
451
452         DBG("%s(%d) END\n", __func__, __LINE__);
453         return;
454 }
455
456 static void dr_controller_stop(struct tegra_udc *udc)
457 {
458         unsigned int tmp;
459         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
460
461         /* Clear pending interrupt status bits */
462         tmp = udc_readl(udc, USB_STS_REG_OFFSET);
463         udc_writel(udc, tmp, USB_STS_REG_OFFSET);
464
465         /* disable all INTR */
466         udc_writel(udc, 0, USB_INTR_REG_OFFSET);
467
468         /* Set stopped bit for isr */
469         udc->stopped = 1;
470
471         /* set controller to Stop */
472         tmp = udc_readl(udc, USB_CMD_REG_OFFSET);
473         tmp &= ~USB_CMD_RUN_STOP;
474         udc_writel(udc, tmp, USB_CMD_REG_OFFSET);
475
476         DBG("%s(%d) END\n", __func__, __LINE__);
477         return;
478 }
479
480 static void dr_ep_setup(struct tegra_udc *udc, unsigned char ep_num,
481                         unsigned char dir, unsigned char ep_type)
482 {
483         unsigned int tmp_epctrl = 0;
484
485         tmp_epctrl = udc_readl(udc, EP_CONTROL_REG_OFFSET + (ep_num * 4));
486         if (dir) {
487                 if (ep_num)
488                         tmp_epctrl |= EPCTRL_TX_DATA_TOGGLE_RST;
489                 tmp_epctrl |= EPCTRL_TX_ENABLE;
490                 tmp_epctrl |= ((unsigned int)(ep_type)
491                                 << EPCTRL_TX_EP_TYPE_SHIFT);
492         } else {
493                 if (ep_num)
494                         tmp_epctrl |= EPCTRL_RX_DATA_TOGGLE_RST;
495                 tmp_epctrl |= EPCTRL_RX_ENABLE;
496                 tmp_epctrl |= ((unsigned int)(ep_type)
497                                 << EPCTRL_RX_EP_TYPE_SHIFT);
498         }
499
500         udc_writel(udc, tmp_epctrl, EP_CONTROL_REG_OFFSET + (ep_num * 4));
501 }
502
503 static void dr_ep_change_stall(struct tegra_udc *udc, unsigned char ep_num,
504                         unsigned char dir, int value)
505 {
506         u32 tmp_epctrl = 0;
507
508         tmp_epctrl = udc_readl(udc, EP_CONTROL_REG_OFFSET + (ep_num * 4));
509         if (value) {
510                 /* set the stall bit */
511                 if (dir)
512                         tmp_epctrl |= EPCTRL_TX_EP_STALL;
513                 else
514                         tmp_epctrl |= EPCTRL_RX_EP_STALL;
515         } else {
516                 /* clear the stall bit and reset data toggle */
517                 if (dir) {
518                         tmp_epctrl &= ~EPCTRL_TX_EP_STALL;
519                         tmp_epctrl |= EPCTRL_TX_DATA_TOGGLE_RST;
520                 } else {
521                         tmp_epctrl &= ~EPCTRL_RX_EP_STALL;
522                         tmp_epctrl |= EPCTRL_RX_DATA_TOGGLE_RST;
523                 }
524         }
525         udc_writel(udc, tmp_epctrl, EP_CONTROL_REG_OFFSET + (ep_num * 4));
526 }
527
528 /* Get stall status of a specific ep
529    Return: 0: not stalled; 1:stalled */
530 static int dr_ep_get_stall(struct tegra_udc *udc, unsigned char ep_num,
531                 unsigned char dir)
532 {
533         u32 epctrl;
534
535         epctrl = udc_readl(udc, EP_CONTROL_REG_OFFSET + (ep_num * 4));
536         if (dir)
537                 return (epctrl & EPCTRL_TX_EP_STALL) ? 1 : 0;
538         else
539                 return (epctrl & EPCTRL_RX_EP_STALL) ? 1 : 0;
540 }
541
542 /**
543  * struct_ep_qh_setup(): set the Endpoint Capabilites field of QH
544  * @zlt: Zero Length Termination Select (1: disable; 0: enable)
545  * @mult: Mult field
546  */
547 static void struct_ep_qh_setup(struct tegra_udc *udc, unsigned char ep_num,
548                 unsigned char dir, unsigned char ep_type,
549                 unsigned int max_pkt_len, unsigned int zlt, unsigned char mult)
550 {
551         struct ep_queue_head *p_QH = &udc->ep_qh[2 * ep_num + dir];
552         unsigned int tmp = 0;
553
554         /* set the Endpoint Capabilites in QH */
555         switch (ep_type) {
556         case USB_ENDPOINT_XFER_CONTROL:
557                 /* Interrupt On Setup (IOS). for control ep  */
558                 tmp = (max_pkt_len << EP_QUEUE_HEAD_MAX_PKT_LEN_POS)
559                         | EP_QUEUE_HEAD_IOS;
560                 break;
561         case USB_ENDPOINT_XFER_ISOC:
562                 tmp = (max_pkt_len << EP_QUEUE_HEAD_MAX_PKT_LEN_POS)
563                         | (mult << EP_QUEUE_HEAD_MULT_POS);
564                 break;
565         case USB_ENDPOINT_XFER_BULK:
566         case USB_ENDPOINT_XFER_INT:
567                 tmp = max_pkt_len << EP_QUEUE_HEAD_MAX_PKT_LEN_POS;
568                 break;
569         default:
570                 VDBG("error ep type is %d", ep_type);
571                 return;
572         }
573         if (zlt)
574                 tmp |= EP_QUEUE_HEAD_ZLT_SEL;
575
576         p_QH->max_pkt_length = cpu_to_le32(tmp);
577         p_QH->next_dtd_ptr = 1;
578         p_QH->size_ioc_int_sts = 0;
579
580         return;
581 }
582
583 /* Setup qh structure and ep register for ep0. */
584 static void ep0_setup(struct tegra_udc *udc)
585 {
586         /* the intialization of an ep includes: fields in QH, Regs,
587          * tegra_ep struct */
588         struct_ep_qh_setup(udc, 0, USB_RECV, USB_ENDPOINT_XFER_CONTROL,
589                         USB_MAX_CTRL_PAYLOAD, 1, 0);
590         struct_ep_qh_setup(udc, 0, USB_SEND, USB_ENDPOINT_XFER_CONTROL,
591                         USB_MAX_CTRL_PAYLOAD, 1, 0);
592         dr_ep_setup(udc, 0, USB_RECV, USB_ENDPOINT_XFER_CONTROL);
593         dr_ep_setup(udc, 0, USB_SEND, USB_ENDPOINT_XFER_CONTROL);
594
595         return;
596
597 }
598
599 /**
600  * when configurations are set, or when interface settings change
601  * for example the do_set_interface() in gadget layer,
602  * the driver will enable or disable the relevant endpoints
603  * ep0 doesn't use this routine. It is always enabled.
604  */
605 static int tegra_ep_enable(struct usb_ep *_ep,
606                 const struct usb_endpoint_descriptor *desc)
607 {
608         struct tegra_udc *udc = NULL;
609         struct tegra_ep *ep = NULL;
610         unsigned short max = 0;
611         unsigned char mult = 0, zlt;
612         int retval = -EINVAL;
613         unsigned long flags = 0;
614
615         ep = container_of(_ep, struct tegra_ep, ep);
616
617         /* catch various bogus parameters */
618         if (!_ep || !desc || ep->desc
619                         || (desc->bDescriptorType != USB_DT_ENDPOINT))
620                 return -EINVAL;
621
622         udc = ep->udc;
623
624         if (!udc->driver || (udc->gadget.speed == USB_SPEED_UNKNOWN))
625                 return -ESHUTDOWN;
626
627         max = le16_to_cpu(desc->wMaxPacketSize);
628
629         /* Disable automatic zlp generation.  Driver is responsible to indicate
630          * explicitly through req->req.zero.  This is needed to enable multi-td
631          * request.
632          */
633         zlt = 1;
634
635         /* Assume the max packet size from gadget is always correct */
636         switch (desc->bmAttributes & 0x03) {
637         case USB_ENDPOINT_XFER_CONTROL:
638         case USB_ENDPOINT_XFER_BULK:
639         case USB_ENDPOINT_XFER_INT:
640                 /* mult = 0.  Execute N Transactions as demonstrated by
641                  * the USB variable length packet protocol where N is
642                  * computed using the Maximum Packet Length (dQH) and
643                  * the Total Bytes field (dTD) */
644                 mult = 0;
645                 break;
646         case USB_ENDPOINT_XFER_ISOC:
647                 /* Calculate transactions needed for high bandwidth iso */
648                 mult = (unsigned char)(1 + ((max >> 11) & 0x03));
649                 max = max & 0x7ff;      /* bit 0~10 */
650                 /* 3 transactions at most */
651                 if (mult > 3)
652                         goto en_done;
653                 break;
654         default:
655                 goto en_done;
656         }
657
658         spin_lock_irqsave(&udc->lock, flags);
659         ep->ep.maxpacket = max;
660         ep->desc = desc;
661         ep->stopped = 0;
662         ep->last_td = 0;
663         ep->last_dtd_count = 0;
664
665         /* Controller related setup
666          * Init EPx Queue Head (Ep Capabilites field in QH
667          * according to max, zlt, mult)
668          */
669         struct_ep_qh_setup(udc, (unsigned char) ep_index(ep),
670                         (unsigned char) ((desc->bEndpointAddress & USB_DIR_IN)
671                                         ?  USB_SEND : USB_RECV),
672                         (unsigned char) (desc->bmAttributes
673                                         & USB_ENDPOINT_XFERTYPE_MASK),
674                         max, zlt, mult);
675
676         /* Init endpoint ctrl register */
677         dr_ep_setup(udc, (unsigned char) ep_index(ep),
678                         (unsigned char) ((desc->bEndpointAddress & USB_DIR_IN)
679                                         ? USB_SEND : USB_RECV),
680                         (unsigned char) (desc->bmAttributes
681                                         & USB_ENDPOINT_XFERTYPE_MASK));
682
683         spin_unlock_irqrestore(&udc->lock, flags);
684         retval = 0;
685
686         VDBG("enabled %s (ep%d%s) maxpacket %d", ep->ep.name,
687                         ep->desc->bEndpointAddress & 0x0f,
688                         (desc->bEndpointAddress & USB_DIR_IN)
689                                 ? "in" : "out", max);
690 en_done:
691         return retval;
692 }
693
694 /**
695  * @ep : the ep being unconfigured. May not be ep0
696  * Any pending and uncomplete req will complete with status (-ESHUTDOWN)
697  */
698 static int tegra_ep_disable(struct usb_ep *_ep)
699 {
700         struct tegra_udc *udc = NULL;
701         struct tegra_ep *ep = NULL;
702
703         unsigned long flags = 0;
704         u32 epctrl;
705         int ep_num;
706         struct ep_td_struct *curr_td, *next_td;
707         int j;
708
709         ep = container_of(_ep, struct tegra_ep, ep);
710         if (!_ep || !ep->desc) {
711                 VDBG("%s not enabled", _ep ? ep->ep.name : NULL);
712                 return -EINVAL;
713         }
714         udc = (struct tegra_udc *)ep->udc;
715
716         /* disable ep on controller */
717         ep_num = ep_index(ep);
718
719         /* Touch the registers if cable is connected and phy is on */
720         if (udc->vbus_active) {
721                 epctrl = udc_readl(udc, EP_CONTROL_REG_OFFSET + (ep_num * 4));
722                 if (ep_is_in(ep))
723                         epctrl &= ~EPCTRL_TX_ENABLE;
724                 else
725                         epctrl &= ~EPCTRL_RX_ENABLE;
726                 udc_writel(udc, epctrl, EP_CONTROL_REG_OFFSET + (ep_num * 4));
727         }
728
729         spin_lock_irqsave(&udc->lock, flags);
730
731         /* nuke all pending requests (does flush) */
732         nuke(ep, -ESHUTDOWN);
733
734         ep->desc = NULL;
735         ep->stopped = 1;
736         if (ep->last_td) {
737                 next_td = ep->last_td;
738                 for (j = 0; j < ep->last_dtd_count; j++) {
739                         curr_td = next_td;
740                         dma_pool_free(udc->td_pool, curr_td, curr_td->td_dma);
741                         if (j != ep->last_dtd_count - 1) {
742                                 next_td = curr_td->next_td_virt;
743                         }
744                 }
745         }
746         ep->last_td =0;
747         ep->last_dtd_count = 0;
748         spin_unlock_irqrestore(&udc->lock, flags);
749
750         VDBG("disabled %s OK", _ep->name);
751         return 0;
752 }
753
754 /**
755  * Allocate a request object used by this endpoint
756  * the main operation is to insert the req->queue to the eq->queue
757  * Returns the request, or null if one could not be allocated
758  */
759 static struct usb_request *
760 tegra_alloc_request(struct usb_ep *_ep, gfp_t gfp_flags)
761 {
762         struct tegra_req *req = NULL;
763
764         req = kzalloc(sizeof *req, gfp_flags);
765         if (!req)
766                 return NULL;
767
768         req->req.dma = DMA_ADDR_INVALID;
769         INIT_LIST_HEAD(&req->queue);
770
771         return &req->req;
772 }
773
774 static void tegra_free_request(struct usb_ep *_ep, struct usb_request *_req)
775 {
776         struct tegra_req *req = NULL;
777
778         req = container_of(_req, struct tegra_req, req);
779
780         if (_req)
781                 kfree(req);
782 }
783
784 static void tegra_queue_td(struct tegra_ep *ep, struct tegra_req *req)
785 {
786         int i = ep_index(ep) * 2 + ep_is_in(ep);
787         u32 temp, bitmask, tmp_stat;
788         struct ep_queue_head *dQH = &ep->udc->ep_qh[i];
789         struct tegra_udc *udc = ep->udc;
790
791         bitmask = ep_is_in(ep)
792                 ? (1 << (ep_index(ep) + 16))
793                 : (1 << (ep_index(ep)));
794
795         /* Flush all the dTD structs out to memory */
796         wmb();
797
798         /* check if the pipe is empty */
799         if (!(list_empty(&ep->queue))) {
800                 /* Add td to the end */
801                 struct tegra_req *lastreq;
802                 lastreq = list_entry(ep->queue.prev, struct tegra_req, queue);
803                 lastreq->tail->next_td_ptr =
804                         cpu_to_le32(req->head->td_dma & DTD_ADDR_MASK);
805                 wmb();
806                 /* Read prime bit, if 1 goto done */
807                 if (udc_readl(udc, EP_PRIME_REG_OFFSET) & bitmask)
808                         goto out;
809
810                 do {
811                         /* Set ATDTW bit in USBCMD */
812                         temp = udc_readl(udc, USB_CMD_REG_OFFSET);
813                         temp |= USB_CMD_ATDTW;
814                         udc_writel(udc, temp, USB_CMD_REG_OFFSET);
815
816                         /* Read correct status bit */
817                         tmp_stat = udc_readl(udc, EP_STATUS_REG_OFFSET)
818                                                 & bitmask;
819
820                 } while (!(udc_readl(udc, USB_CMD_REG_OFFSET) & USB_CMD_ATDTW));
821
822                 /* Write ATDTW bit to 0 */
823                 temp = udc_readl(udc, USB_CMD_REG_OFFSET);
824                 udc_writel(udc, temp & ~USB_CMD_ATDTW, USB_CMD_REG_OFFSET);
825
826                 if (tmp_stat)
827                         goto out;
828         }
829
830         /* Write dQH next pointer and terminate bit to 0 */
831         temp = req->head->td_dma & EP_QUEUE_HEAD_NEXT_POINTER_MASK;
832         dQH->next_dtd_ptr = cpu_to_le32(temp);
833
834         /* Clear active and halt bit */
835         temp = cpu_to_le32(~(EP_QUEUE_HEAD_STATUS_ACTIVE
836                         | EP_QUEUE_HEAD_STATUS_HALT));
837         dQH->size_ioc_int_sts &= temp;
838
839         tegra_usb_phy_memory_prefetch_on(udc->phy);
840
841         /* Ensure that updates to the QH will occur before priming. */
842         wmb();
843
844         /* Prime endpoint by writing 1 to ENDPTPRIME */
845         temp = ep_is_in(ep)
846                 ? (1 << (ep_index(ep) + 16))
847                 : (1 << (ep_index(ep)));
848         udc_writel(udc, temp, EP_PRIME_REG_OFFSET);
849 out:
850         return;
851 }
852
853 /**
854  * Fill in the dTD structure
855  * @req     : request that the transfer belongs to
856  * @length  : return actually data length of the dTD
857  * @dma     : return dma address of the dTD
858  * @is_last : return flag if it is the last dTD of the request
859  * return   : pointer to the built dTD
860  */
861 static struct ep_td_struct *tegra_build_dtd(struct tegra_req *req,
862         unsigned *length, dma_addr_t *dma, int *is_last, gfp_t gfp_flags)
863 {
864         u32 swap_temp;
865         struct ep_td_struct *dtd;
866
867         /* how big will this transfer be? */
868         *length = min(req->req.length - req->req.actual,
869                         (unsigned)EP_MAX_LENGTH_TRANSFER);
870
871         dtd = dma_pool_alloc(the_udc->td_pool, gfp_flags, dma);
872         if (dtd == NULL)
873                 return dtd;
874
875         dtd->td_dma = *dma;
876         /* Clear reserved field */
877         swap_temp = cpu_to_le32(dtd->size_ioc_sts);
878         swap_temp &= ~DTD_RESERVED_FIELDS;
879         dtd->size_ioc_sts = cpu_to_le32(swap_temp);
880
881         /* Init all of buffer page pointers */
882         swap_temp = (u32) (req->req.dma + req->req.actual);
883         dtd->buff_ptr0 = cpu_to_le32(swap_temp);
884         dtd->buff_ptr1 = cpu_to_le32(swap_temp + 0x1000);
885         dtd->buff_ptr2 = cpu_to_le32(swap_temp + 0x2000);
886         dtd->buff_ptr3 = cpu_to_le32(swap_temp + 0x3000);
887         dtd->buff_ptr4 = cpu_to_le32(swap_temp + 0x4000);
888
889         req->req.actual += *length;
890
891         /* zlp is needed if req->req.zero is set */
892         if (req->req.zero) {
893                 if (*length == 0 || (*length % req->ep->ep.maxpacket) != 0)
894                         *is_last = 1;
895                 else
896                         *is_last = 0;
897         } else if (req->req.length == req->req.actual)
898                 *is_last = 1;
899         else
900                 *is_last = 0;
901
902         if ((*is_last) == 0)
903                 VDBG("multi-dtd request!");
904
905         /* Fill in the transfer size; set active bit */
906         swap_temp = ((*length << DTD_LENGTH_BIT_POS) | DTD_STATUS_ACTIVE);
907
908         /* Enable interrupt for the last dtd of a request */
909         if (*is_last && !req->req.no_interrupt)
910                 swap_temp |= DTD_IOC;
911
912         dtd->size_ioc_sts = cpu_to_le32(swap_temp);
913
914         mb();
915
916         VDBG("length = %d address= 0x%x", *length, (int)*dma);
917
918         return dtd;
919 }
920
921 /* Generate dtd chain for a request */
922 static int tegra_req_to_dtd(struct tegra_req *req, gfp_t gfp_flags)
923 {
924         unsigned        count;
925         int             is_last;
926         int             is_first = 1;
927         struct ep_td_struct     *last_dtd = NULL, *dtd;
928         dma_addr_t dma;
929
930         tegra_usb_phy_memory_prefetch_off(the_udc->phy);
931
932         do {
933                 dtd = tegra_build_dtd(req, &count, &dma, &is_last, gfp_flags);
934                 if (dtd == NULL)
935                         return -ENOMEM;
936
937                 if (is_first) {
938                         is_first = 0;
939                         req->head = dtd;
940                 } else {
941                         last_dtd->next_td_ptr = cpu_to_le32(dma);
942                         last_dtd->next_td_virt = dtd;
943                 }
944                 last_dtd = dtd;
945
946                 req->dtd_count++;
947         } while (!is_last);
948
949         dtd->next_td_ptr = cpu_to_le32(DTD_NEXT_TERMINATE);
950
951         req->tail = dtd;
952
953         return 0;
954 }
955
956 /* queues (submits) an I/O request to an endpoint */
957 static int
958 tegra_ep_queue(struct usb_ep *_ep, struct usb_request *_req, gfp_t gfp_flags)
959 {
960         struct tegra_ep *ep = container_of(_ep, struct tegra_ep, ep);
961         struct tegra_req *req = container_of(_req, struct tegra_req, req);
962         struct tegra_udc *udc = ep->udc;
963         unsigned long flags;
964         enum dma_data_direction dir;
965         int status;
966
967         /* catch various bogus parameters */
968         if (!_req || !req->req.complete || !req->req.buf
969                         || !list_empty(&req->queue)) {
970                 VDBG("%s, bad params", __func__);
971                 return -EINVAL;
972         }
973
974         spin_lock_irqsave(&udc->lock, flags);
975
976         if (unlikely(!ep->desc)) {
977                 VDBG("%s, bad ep", __func__);
978                 spin_unlock_irqrestore(&udc->lock, flags);
979                 return -EINVAL;
980         }
981
982         if (ep->desc->bmAttributes == USB_ENDPOINT_XFER_ISOC) {
983                 if (req->req.length > ep->ep.maxpacket) {
984                         spin_unlock_irqrestore(&udc->lock, flags);
985                         return -EMSGSIZE;
986                 }
987         }
988
989 #ifdef CONFIG_TEGRA_GADGET_BOOST_CPU_FREQ
990         if (req->req.length >= BOOST_TRIGGER_SIZE) {
991                 ep_queue_request_count++;
992                 schedule_work(&udc->boost_cpufreq_work);
993         }
994 #endif
995
996         dir = ep_is_in(ep) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
997
998         if (!udc->driver || udc->gadget.speed == USB_SPEED_UNKNOWN) {
999                 spin_unlock_irqrestore(&udc->lock, flags);
1000                 return -ESHUTDOWN;
1001         }
1002
1003         req->ep = ep;
1004
1005         /* map virtual address to hardware */
1006         if (req->req.dma == DMA_ADDR_INVALID) {
1007                 DEFINE_DMA_ATTRS(attrs);
1008                 struct device *dev = udc->gadget.dev.parent;
1009                 size_t orig = req->req.length;
1010                 size_t ext = orig + AHB_PREFETCH_BUFFER;
1011
1012                 dma_set_attr(DMA_ATTR_SKIP_CPU_SYNC, &attrs);
1013                 req->req.dma = dma_map_single_attrs(dev, req->req.buf, ext, dir,
1014                                                     &attrs);
1015                 if (dma_mapping_error(dev, req->req.dma)) {
1016                         spin_unlock_irqrestore(&udc->lock, flags);
1017                         return -EAGAIN;
1018                 }
1019
1020                 dma_sync_single_for_device(dev, req->req.dma, orig, dir);
1021
1022                 req->mapped = 1;
1023         } else {
1024                 dma_sync_single_for_device(udc->gadget.dev.parent,
1025                                         req->req.dma, req->req.length, dir);
1026                 req->mapped = 0;
1027         }
1028
1029         req->req.status = -EINPROGRESS;
1030         req->req.actual = 0;
1031         req->dtd_count = 0;
1032
1033
1034         /* build dtds and push them to device queue */
1035         status = tegra_req_to_dtd(req, GFP_ATOMIC);
1036         if (status) {
1037                 spin_unlock_irqrestore(&udc->lock, flags);
1038                 goto err_unmap;
1039         }
1040
1041         /* re-check if the ep has not been disabled */
1042         if (unlikely(!ep->desc)) {
1043                 spin_unlock_irqrestore(&udc->lock, flags);
1044                 status = -EINVAL;
1045                 goto err_unmap;
1046         }
1047
1048         tegra_queue_td(ep, req);
1049
1050         /* Update ep0 state */
1051         if ((ep_index(ep) == 0))
1052                 udc->ep0_state = DATA_STATE_XMIT;
1053
1054         /* irq handler advances the queue */
1055         list_add_tail(&req->queue, &ep->queue);
1056         spin_unlock_irqrestore(&udc->lock, flags);
1057
1058         return 0;
1059
1060 err_unmap:
1061         if (req->mapped) {
1062                 DEFINE_DMA_ATTRS(attrs);
1063                 struct device *dev = udc->gadget.dev.parent;
1064                 size_t orig = req->req.length;
1065                 size_t ext = orig + AHB_PREFETCH_BUFFER;
1066
1067                 dma_sync_single_for_cpu(dev, req->req.dma, orig, dir);
1068                 dma_set_attr(DMA_ATTR_SKIP_CPU_SYNC, &attrs);
1069                 dma_unmap_single_attrs(dev, req->req.dma, ext, dir, &attrs);
1070
1071                 req->req.dma = DMA_ADDR_INVALID;
1072                 req->mapped = 0;
1073         }
1074         return status;
1075 }
1076
1077 /* dequeues (cancels, unlinks) an I/O request from an endpoint */
1078 static int tegra_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req)
1079 {
1080         struct tegra_ep *ep = container_of(_ep, struct tegra_ep, ep);
1081         struct tegra_req *req;
1082         struct tegra_udc *udc = ep->udc;
1083         unsigned long flags;
1084         int ep_num, stopped, ret = 0;
1085         u32 epctrl;
1086
1087         if (!_ep || !_req)
1088                 return -EINVAL;
1089
1090         spin_lock_irqsave(&ep->udc->lock, flags);
1091         if (!ep->desc) {
1092                 spin_unlock_irqrestore(&ep->udc->lock, flags);
1093                 return -EINVAL;
1094         }
1095         stopped = ep->stopped;
1096
1097         /* Stop the ep before we deal with the queue */
1098         ep->stopped = 1;
1099         ep_num = ep_index(ep);
1100
1101         /* Touch the registers if cable is connected and phy is on */
1102         if (udc->vbus_active) {
1103                 epctrl = udc_readl(udc, EP_CONTROL_REG_OFFSET + (ep_num * 4));
1104                 if (ep_is_in(ep))
1105                         epctrl &= ~EPCTRL_TX_ENABLE;
1106                 else
1107                         epctrl &= ~EPCTRL_RX_ENABLE;
1108                 udc_writel(udc, epctrl, EP_CONTROL_REG_OFFSET + (ep_num * 4));
1109         }
1110
1111         /* make sure it's actually queued on this endpoint */
1112         list_for_each_entry(req, &ep->queue, queue) {
1113                 if (&req->req == _req)
1114                         break;
1115         }
1116         if (&req->req != _req) {
1117                 ret = -EINVAL;
1118                 goto out;
1119         }
1120
1121         /* The request is in progress, or completed but not dequeued */
1122         if (ep->queue.next == &req->queue) {
1123                 _req->status = -ECONNRESET;
1124                 tegra_ep_fifo_flush(_ep);       /* flush current transfer */
1125
1126                 /* The request isn't the last request in this ep queue */
1127                 if (req->queue.next != &ep->queue) {
1128                         struct ep_queue_head *qh;
1129                         struct tegra_req *next_req;
1130
1131                         qh = ep->qh;
1132                         next_req = list_entry(req->queue.next, struct tegra_req,
1133                                         queue);
1134
1135                         /* Point the QH to the first TD of next request */
1136                         writel((u32) (uintptr_t) next_req->head,
1137                                         &qh->curr_dtd_ptr);
1138                 }
1139
1140                 /* The request hasn't been processed, patch up the TD chain */
1141         } else {
1142                 struct tegra_req *prev_req;
1143
1144                 prev_req = list_entry(req->queue.prev, struct tegra_req, queue);
1145                 writel(readl(&req->tail->next_td_ptr),
1146                                 &prev_req->tail->next_td_ptr);
1147         }
1148
1149         done(ep, req, -ECONNRESET);
1150
1151         /* Enable EP */
1152 out:
1153         /* Touch the registers if cable is connected and phy is on */
1154         if (udc->vbus_active && ep->desc) {
1155                 epctrl = udc_readl(udc, EP_CONTROL_REG_OFFSET + (ep_num * 4));
1156                 if (ep_is_in(ep))
1157                         epctrl |= EPCTRL_TX_ENABLE;
1158                 else
1159                         epctrl |= EPCTRL_RX_ENABLE;
1160                 udc_writel(udc, epctrl, EP_CONTROL_REG_OFFSET + (ep_num * 4));
1161         }
1162         ep->stopped = stopped;
1163
1164         spin_unlock_irqrestore(&ep->udc->lock, flags);
1165         return ret;
1166 }
1167
1168 /**
1169  * modify the endpoint halt feature
1170  * @ep: the non-isochronous endpoint being stalled
1171  * @value: 1--set halt  0--clear halt
1172  * Returns zero, or a negative error code.
1173  */
1174 static int tegra_ep_set_halt(struct usb_ep *_ep, int value)
1175 {
1176         struct tegra_ep *ep = NULL;
1177         unsigned long flags = 0;
1178         int status = -EOPNOTSUPP;       /* operation not supported */
1179         unsigned char ep_dir = 0, ep_num = 0;
1180         struct tegra_udc *udc = NULL;
1181
1182         ep = container_of(_ep, struct tegra_ep, ep);
1183         udc = ep->udc;
1184         if (!_ep || !ep->desc) {
1185                 status = -EINVAL;
1186                 goto out;
1187         }
1188
1189         if (ep->desc->bmAttributes == USB_ENDPOINT_XFER_ISOC) {
1190                 status = -EOPNOTSUPP;
1191                 goto out;
1192         }
1193
1194         /* Attempt to halt IN ep will fail if any transfer requests
1195          * are still queue */
1196         if (value && ep_is_in(ep) && !list_empty(&ep->queue)) {
1197                 status = -EAGAIN;
1198                 goto out;
1199         }
1200
1201         status = 0;
1202         ep_dir = ep_is_in(ep) ? USB_SEND : USB_RECV;
1203         ep_num = (unsigned char)(ep_index(ep));
1204         spin_lock_irqsave(&ep->udc->lock, flags);
1205         dr_ep_change_stall(udc, ep_num, ep_dir, value);
1206         spin_unlock_irqrestore(&ep->udc->lock, flags);
1207
1208         if (ep_index(ep) == 0) {
1209                 udc->ep0_state = WAIT_FOR_SETUP;
1210                 udc->ep0_dir = 0;
1211         }
1212 out:
1213         VDBG(" %s %s halt stat %d", ep->ep.name,
1214                         value ?  "set" : "clear", status);
1215
1216         return status;
1217 }
1218
1219 static int tegra_ep_fifo_status(struct usb_ep *_ep)
1220 {
1221         struct tegra_ep *ep;
1222         struct tegra_udc *udc;
1223         int size = 0;
1224         u32 bitmask;
1225         struct ep_queue_head *d_qh;
1226
1227         ep = container_of(_ep, struct tegra_ep, ep);
1228         if (!_ep || (!ep->desc && ep_index(ep) != 0))
1229                 return -ENODEV;
1230
1231         udc = (struct tegra_udc *)ep->udc;
1232
1233         if (!udc->driver || udc->gadget.speed == USB_SPEED_UNKNOWN)
1234                 return -ESHUTDOWN;
1235
1236         d_qh = &ep->udc->ep_qh[ep_index(ep) * 2 + ep_is_in(ep)];
1237
1238         bitmask = (ep_is_in(ep)) ? (1 << (ep_index(ep) + 16)) :
1239             (1 << (ep_index(ep)));
1240
1241         if (udc_readl(udc, EP_STATUS_REG_OFFSET) & bitmask)
1242                 size = (d_qh->size_ioc_int_sts & DTD_PACKET_SIZE)
1243                     >> DTD_LENGTH_BIT_POS;
1244
1245         pr_debug("%s %u\n", __func__, size);
1246         return size;
1247 }
1248
1249 static void tegra_ep_fifo_flush(struct usb_ep *_ep)
1250 {
1251         struct tegra_ep *ep;
1252         struct tegra_udc *udc;
1253         int ep_num, ep_dir;
1254         u32 bits;
1255         unsigned long timeout;
1256
1257         if (!_ep) {
1258                 return;
1259         } else {
1260                 ep = container_of(_ep, struct tegra_ep, ep);
1261                 if (!ep->desc)
1262                         return;
1263         }
1264         ep_num = ep_index(ep);
1265         ep_dir = ep_is_in(ep) ? USB_SEND : USB_RECV;
1266         udc = ep->udc;
1267
1268         if (ep_num == 0)
1269                 bits = (1 << 16) | 1;
1270         else if (ep_dir == USB_SEND)
1271                 bits = 1 << (16 + ep_num);
1272         else
1273                 bits = 1 << ep_num;
1274
1275         /* Touch the registers if cable is connected and phy is on */
1276         if (!udc->vbus_active)
1277                 return;
1278
1279         timeout = jiffies + UDC_FLUSH_TIMEOUT_MS;
1280         do {
1281                 udc_writel(udc, bits, EPFLUSH_REG_OFFSET);
1282
1283                 /* Wait until flush complete */
1284                 while (udc_readl(udc, EPFLUSH_REG_OFFSET)) {
1285                         if (time_after(jiffies, timeout)) {
1286                                 ERR("ep flush timeout\n");
1287                                 return;
1288                         }
1289                         cpu_relax();
1290                 }
1291                 /* See if we need to flush again */
1292         } while (udc_readl(udc, EP_STATUS_REG_OFFSET) & bits);
1293 }
1294
1295 static struct usb_ep_ops tegra_ep_ops = {
1296         .enable = tegra_ep_enable,
1297         .disable = tegra_ep_disable,
1298
1299         .alloc_request = tegra_alloc_request,
1300         .free_request = tegra_free_request,
1301
1302         .queue = tegra_ep_queue,
1303         .dequeue = tegra_ep_dequeue,
1304
1305         .set_halt = tegra_ep_set_halt,
1306         .fifo_status = tegra_ep_fifo_status,
1307         .fifo_flush = tegra_ep_fifo_flush,      /* flush fifo */
1308 };
1309
1310
1311 static struct usb_phy *get_usb_phy(struct tegra_usb_phy *x)
1312 {
1313         return (struct usb_phy *)x;
1314 }
1315
1316 /* Get the current frame number (from DR frame_index Reg ) */
1317 static int tegra_get_frame(struct usb_gadget *gadget)
1318 {
1319         struct tegra_udc *udc = container_of(gadget, struct tegra_udc, gadget);
1320         return (int)(udc_readl(udc, USB_FRINDEX_REG_OFFSET)
1321                                                 & USB_FRINDEX_MASKS);
1322 }
1323
1324 #ifndef CONFIG_USB_ANDROID
1325 /* Tries to wake up the host connected to this gadget */
1326 static int tegra_wakeup(struct usb_gadget *gadget)
1327 {
1328         struct tegra_udc *udc = container_of(gadget, struct tegra_udc, gadget);
1329         u32 portsc;
1330
1331         /* Remote wakeup feature not enabled by host */
1332         if (!udc->remote_wakeup)
1333                 return -ENOTSUPP;
1334
1335         portsc = udc_readl(udc, PORTSCX_REG_OFFSET);
1336         /* not suspended? */
1337         if (!(portsc & PORTSCX_PORT_SUSPEND))
1338                 return 0;
1339
1340         /* trigger force resume */
1341         portsc |= PORTSCX_PORT_FORCE_RESUME;
1342         udc_writel(udc, portsc, PORTSCX_REG_OFFSET);
1343         return 0;
1344 }
1345 #endif
1346
1347 static int tegra_set_selfpowered(struct usb_gadget *gadget, int is_on)
1348 {
1349         struct tegra_udc *udc;
1350         udc = container_of(gadget, struct tegra_udc, gadget);
1351         udc->selfpowered = (is_on != 0);
1352         return 0;
1353 }
1354
1355 static void tegra_udc_set_charger_type(struct tegra_udc *udc,
1356                 enum tegra_connect_type type)
1357 {
1358         udc->prev_connect_type = udc->connect_type;
1359         udc->connect_type = type;
1360 }
1361
1362 static void tegra_udc_set_extcon_state(struct tegra_udc *udc)
1363 {
1364         const char **cables;
1365         struct extcon_dev *edev;
1366
1367         if (udc->edev == NULL || udc->edev->supported_cable == NULL)
1368                 return;
1369         edev = udc->edev;
1370         cables = udc->edev->supported_cable;
1371         /* set previous cable type to false, then set current type to true */
1372         if (udc->prev_connect_type != CONNECT_TYPE_NONE)
1373                 extcon_set_state(edev, 0x0);
1374         if (udc->connect_type != udc->connect_type_lp0
1375                         && udc->connect_type != CONNECT_TYPE_NONE)
1376                 extcon_set_cable_state(edev, cables[udc->connect_type], true);
1377 }
1378
1379 static void tegra_udc_notify_event(struct tegra_udc *udc, int event)
1380 {
1381         if (udc->transceiver) {
1382                 udc->transceiver->last_event = event;
1383                 atomic_notifier_call_chain(&udc->transceiver->notifier,
1384                                 event, udc->transceiver->otg->gadget);
1385         }
1386 }
1387
1388 static int tegra_usb_set_charging_current(struct tegra_udc *udc)
1389 {
1390         int max_ua;
1391         struct device *dev;
1392         int ret;
1393
1394         dev = &udc->pdev->dev;
1395         switch (udc->connect_type) {
1396         case CONNECT_TYPE_NONE:
1397                 dev_info(dev, "USB cable/charger disconnected\n");
1398                 max_ua = 0;
1399                 /* Notify if HOST(SDP/CDP) is connected */
1400                 if ((udc->prev_connect_type == CONNECT_TYPE_SDP) ||
1401                         (udc->prev_connect_type == CONNECT_TYPE_CDP))
1402                         tegra_udc_notify_event(udc, USB_EVENT_NONE);
1403                 break;
1404         case CONNECT_TYPE_SDP:
1405                 if (udc->current_limit > 2)
1406                         dev_info(dev, "connected to SDP\n");
1407                 max_ua = min(udc->current_limit * 1000,
1408                                 USB_CHARGING_SDP_CURRENT_LIMIT_UA);
1409                 tegra_udc_notify_event(udc, USB_EVENT_VBUS);
1410                 break;
1411         case CONNECT_TYPE_DCP:
1412                 dev_info(dev, "connected to DCP(wall charger)\n");
1413                 max_ua = udc->dcp_current_limit;
1414                 tegra_udc_notify_event(udc, USB_EVENT_CHARGER);
1415                 break;
1416         case CONNECT_TYPE_DCP_QC2:
1417                 dev_info(dev, "connected to QuickCharge 2(wall charger)\n");
1418                 max_ua = udc->qc2_current_limit;
1419                 tegra_udc_notify_event(udc, USB_EVENT_CHARGER);
1420                 break;
1421         case CONNECT_TYPE_DCP_MAXIM:
1422                 dev_info(dev, "connected to Maxim(wall charger)\n");
1423                 max_ua = udc->dcp_current_limit;
1424                 tegra_udc_notify_event(udc, USB_EVENT_CHARGER);
1425                 break;
1426         case CONNECT_TYPE_CDP:
1427                 dev_info(dev, "connected to CDP(1.5A)\n");
1428                 /*
1429                  * if current is more than VBUS suspend current, we draw CDP
1430                  * allowed maximum current (override SDP max current which is
1431                  * set by the upper level driver).
1432                  */
1433                 if (udc->current_limit > 2)
1434                         max_ua = USB_CHARGING_CDP_CURRENT_LIMIT_UA;
1435                 else
1436                         max_ua = udc->current_limit * 1000;
1437                 tegra_udc_notify_event(udc, USB_EVENT_VBUS);
1438                 break;
1439         case CONNECT_TYPE_NV_CHARGER:
1440                 dev_info(dev, "connected to NV charger\n");
1441                 max_ua = USB_CHARGING_NV_CHARGER_CURRENT_LIMIT_UA;
1442                 tegra_udc_notify_event(udc, USB_EVENT_CHARGER);
1443                 break;
1444         case CONNECT_TYPE_NON_STANDARD_CHARGER:
1445                 dev_info(dev, "connected to non-standard charger\n");
1446                 max_ua = USB_CHARGING_NON_STANDARD_CHARGER_CURRENT_LIMIT_UA;
1447                 tegra_udc_notify_event(udc, USB_EVENT_CHARGER);
1448                 break;
1449         case CONNECT_TYPE_APPLE_500MA:
1450                 dev_info(dev, "connected to Apple/Other 0.5A custom charger\n");
1451                 max_ua = USB_CHARGING_APPLE_CHARGER_500mA_CURRENT_LIMIT_UA;
1452                 tegra_udc_notify_event(udc, USB_EVENT_CHARGER);
1453                 break;
1454         case CONNECT_TYPE_APPLE_1000MA:
1455                 dev_info(dev, "connected to Apple/Other 1A custom charger\n");
1456                 max_ua = USB_CHARGING_APPLE_CHARGER_1000mA_CURRENT_LIMIT_UA;
1457                 tegra_udc_notify_event(udc, USB_EVENT_CHARGER);
1458                 break;
1459         case CONNECT_TYPE_APPLE_2000MA:
1460                 dev_info(dev, "connected to Apple/Other/NV 2A custom charger\n");
1461                 max_ua = USB_CHARGING_APPLE_CHARGER_2000mA_CURRENT_LIMIT_UA;
1462                 tegra_udc_notify_event(udc, USB_EVENT_CHARGER);
1463                 break;
1464         default:
1465                 dev_info(dev, "connected to unknown USB port\n");
1466                 max_ua = 0;
1467         }
1468
1469         ret = 0;
1470         /*
1471          * we set charging regulator's maximum charging current 1st, then
1472          * notify the charging type.
1473          */
1474         if (NULL != udc->vbus_reg && !udc->vbus_in_lp0) {
1475                 if (udc->connect_type != udc->connect_type_lp0 ||
1476                                         udc->connect_type == CONNECT_TYPE_NONE)
1477                         ret = regulator_set_current_limit(udc->vbus_reg,
1478                                                                  0, max_ua);
1479         }
1480
1481
1482         if (!udc->vbus_in_lp0) {
1483                 tegra_udc_set_extcon_state(udc);
1484                 udc->connect_type_lp0 = CONNECT_TYPE_NONE;
1485         }
1486         return ret;
1487 }
1488
1489 static int tegra_detect_cable_type(struct tegra_udc *udc)
1490 {
1491         if (!udc->charging_supported) {
1492                 tegra_udc_set_charger_type(udc, CONNECT_TYPE_SDP);
1493                 return 0;
1494         }
1495
1496         if (tegra_usb_phy_charger_detected(udc->phy)) {
1497                 if (tegra_usb_phy_cdp_charger_detected(udc->phy))
1498                         tegra_udc_set_charger_type(udc, CONNECT_TYPE_CDP);
1499                 else if (tegra_usb_phy_maxim_charger_detected(udc->phy))
1500                         tegra_udc_set_charger_type(udc,
1501                                                 CONNECT_TYPE_DCP_MAXIM);
1502                 else if (udc->qc2_voltage) {
1503                         /* Must be DCP -- figure out if Quick Charge 2 or DCP.
1504                          * Initially set low current since QC2 will reset to
1505                          * 5V if current is too high when it changes to higher
1506                          * voltage during detection. So setting to non-standard
1507                          * which sets for low current. Also, setting current
1508                          * early allows the charging icon to show up on UI.
1509                          */
1510                         tegra_udc_set_charger_type(udc,
1511                                         CONNECT_TYPE_NON_STANDARD_CHARGER);
1512                         tegra_usb_set_charging_current(udc);
1513
1514                         if (tegra_usb_phy_qc2_charger_detected(udc->phy,
1515                                         udc->qc2_voltage))
1516                                 tegra_udc_set_charger_type(udc,
1517                                         CONNECT_TYPE_DCP_QC2);
1518                         else
1519                                 tegra_udc_set_charger_type(udc,
1520                                         CONNECT_TYPE_DCP);
1521                 } else
1522                         tegra_udc_set_charger_type(udc, CONNECT_TYPE_DCP);
1523         }
1524 #if !defined(CONFIG_ARCH_TEGRA_11x_SOC) && !defined(CONFIG_ARCH_TEGRA_14x_SOC)
1525         else if (tegra_usb_phy_apple_500ma_charger_detected(udc->phy))
1526                 tegra_udc_set_charger_type(udc, CONNECT_TYPE_APPLE_500MA);
1527         else if (tegra_usb_phy_apple_1000ma_charger_detected(udc->phy))
1528                 tegra_udc_set_charger_type(udc, CONNECT_TYPE_APPLE_1000MA);
1529         else if (tegra_usb_phy_apple_2000ma_charger_detected(udc->phy))
1530                 tegra_udc_set_charger_type(udc, CONNECT_TYPE_APPLE_2000MA);
1531 #endif
1532         else if (tegra_usb_phy_nv_charger_detected(udc->phy))
1533                 tegra_udc_set_charger_type(udc, CONNECT_TYPE_NV_CHARGER);
1534         else
1535                 tegra_udc_set_charger_type(udc, CONNECT_TYPE_SDP);
1536
1537         /*
1538          * If it is charger type, we start charging now. If it is connected to
1539          * USB host(CDP/SDP), we let upper gadget driver to decide the current
1540          * capability.
1541          */
1542         if ((udc->connect_type != CONNECT_TYPE_SDP) &&
1543                 (udc->connect_type != CONNECT_TYPE_CDP))
1544                 tegra_usb_set_charging_current(udc);
1545
1546         return 0;
1547 }
1548
1549 /**
1550  * Notify controller that VBUS is powered, called by whatever
1551  * detects VBUS sessions
1552  */
1553 static int tegra_vbus_session(struct usb_gadget *gadget, int is_active)
1554 {
1555         struct tegra_udc *udc = container_of(gadget, struct tegra_udc, gadget);
1556         unsigned long flags;
1557
1558         mutex_lock(&udc->sync_lock);
1559         DBG("%s(%d) turn VBUS state from %s to %s", __func__, __LINE__,
1560                 udc->vbus_active ? "on" : "off", is_active ? "on" : "off");
1561
1562         if (udc->vbus_active && !is_active) {
1563                 /* If cable disconnected, cancel any delayed work */
1564                 cancel_delayed_work_sync(&udc->non_std_charger_work);
1565                 spin_lock_irqsave(&udc->lock, flags);
1566                 /* reset all internal Queues and inform client driver */
1567                 reset_queues(udc);
1568                 /* stop the controller and turn off the clocks */
1569                 dr_controller_stop(udc);
1570                 dr_controller_reset(udc);
1571                 udc->vbus_active = 0;
1572                 udc->usb_state = USB_STATE_DEFAULT;
1573                 tegra_udc_set_charger_type(udc, CONNECT_TYPE_NONE);
1574                 spin_unlock_irqrestore(&udc->lock, flags);
1575                 tegra_usb_phy_power_off(udc->phy);
1576                 tegra_usb_set_charging_current(udc);
1577         } else if (!udc->vbus_active && is_active) {
1578                 tegra_usb_phy_power_on(udc->phy);
1579                 /* setup the controller in the device mode */
1580                 dr_controller_setup(udc);
1581                 /* setup EP0 for setup packet */
1582                 ep0_setup(udc);
1583                 /* initialize the USB and EP states */
1584                 udc->usb_state = USB_STATE_ATTACHED;
1585                 udc->ep0_state = WAIT_FOR_SETUP;
1586                 udc->ep0_dir = 0;
1587                 udc->vbus_active = 1;
1588                 tegra_detect_cable_type(udc);
1589                 /* start the controller if USB host detected */
1590                 if ((udc->connect_type == CONNECT_TYPE_SDP) ||
1591                     (udc->connect_type == CONNECT_TYPE_CDP) ||
1592                     (udc->connect_type == CONNECT_TYPE_DCP_MAXIM))
1593                         dr_controller_run(udc);
1594         }
1595         mutex_unlock(&udc->sync_lock);
1596
1597         return 0;
1598 }
1599
1600 /**
1601  * Constrain controller's VBUS power usage.
1602  * This call is used by gadget drivers during SET_CONFIGURATION calls,
1603  * reporting how much power the device may consume. For example, this
1604  * could affect how quickly batteries are recharged.
1605  *
1606  * Returns zero on success, else negative errno.
1607  */
1608 static int tegra_vbus_draw(struct usb_gadget *gadget, unsigned mA)
1609 {
1610         struct tegra_udc *udc;
1611
1612         udc = container_of(gadget, struct tegra_udc, gadget);
1613
1614         udc->current_limit = mA;
1615         schedule_work(&udc->current_work);
1616
1617         if (udc->transceiver)
1618                 return usb_phy_set_power(udc->transceiver, mA);
1619         return -ENOTSUPP;
1620 }
1621
1622 /**
1623  * Change Data+ pullup status
1624  * this func is used by usb_gadget_connect/disconnect
1625  */
1626 static int tegra_pullup(struct usb_gadget *gadget, int is_on)
1627 {
1628         struct tegra_udc *udc;
1629         u32 tmp;
1630         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
1631
1632         udc = container_of(gadget, struct tegra_udc, gadget);
1633         udc->softconnect = (is_on != 0);
1634         if (udc->transceiver && udc->transceiver->state !=
1635                         OTG_STATE_B_PERIPHERAL)
1636                         return 0;
1637
1638         /* set interrupt latency to 125 uS (1 uFrame) */
1639         tmp = udc_readl(udc, USB_CMD_REG_OFFSET);
1640         tmp &= ~USB_CMD_ITC;
1641         tmp |= USB_CMD_ITC_1_MICRO_FRM;
1642         if (can_pullup(udc)) {
1643                 udc_writel(udc, tmp | USB_CMD_RUN_STOP, USB_CMD_REG_OFFSET);
1644                 /*
1645                  * We cannot tell difference between a SDP and non-standard
1646                  * charger (which has D+/D- line floating) based on line status
1647                  * at the time VBUS is detected.
1648                  *
1649                  * We can schedule a 4s delayed work and verify it is an
1650                  * non-standard charger if no setup packet is received after
1651                  * enumeration started.
1652                  */
1653                 if (udc->charging_supported &&
1654                         (udc->connect_type == CONNECT_TYPE_SDP))
1655                         schedule_delayed_work(&udc->non_std_charger_work,
1656                                 msecs_to_jiffies(NON_STD_CHARGER_DET_TIME_MS));
1657         } else {
1658                 cancel_delayed_work(&udc->non_std_charger_work);
1659                 udc_writel(udc, (tmp & ~USB_CMD_RUN_STOP), USB_CMD_REG_OFFSET);
1660         }
1661
1662         DBG("%s(%d) END\n", __func__, __LINE__);
1663         return 0;
1664 }
1665
1666 /* Release udc structures */
1667 static void tegra_udc_release(struct device *dev)
1668 {
1669         struct platform_device *pdev = to_platform_device(dev);
1670         struct tegra_udc *udc = platform_get_drvdata(pdev);
1671
1672         complete(udc->done);
1673         usb_phy_shutdown(get_usb_phy(udc->phy));
1674         kfree(udc);
1675 }
1676
1677 static int tegra_udc_start(struct usb_gadget *g,
1678                 struct usb_gadget_driver *driver);
1679 static int tegra_udc_stop(struct usb_gadget *g,
1680                 struct usb_gadget_driver *driver);
1681 /* defined in gadget.h */
1682 static const struct usb_gadget_ops tegra_gadget_ops = {
1683         .get_frame = tegra_get_frame,
1684 #ifndef CONFIG_USB_ANDROID
1685         .wakeup = tegra_wakeup,
1686 #endif
1687         .set_selfpowered = tegra_set_selfpowered,
1688         .vbus_session = tegra_vbus_session,
1689         .vbus_draw = tegra_vbus_draw,
1690         .pullup = tegra_pullup,
1691         .udc_start = tegra_udc_start,
1692         .udc_stop = tegra_udc_stop,
1693 };
1694
1695 /**
1696  * Set protocol stall on ep0, protocol stall will automatically be cleared
1697  * on new transaction.
1698  */
1699 static void ep0stall(struct tegra_udc *udc)
1700 {
1701         u32 tmp;
1702
1703         /* must set tx and rx to stall at the same time */
1704         tmp = udc_readl(udc, EP_CONTROL_REG_OFFSET);
1705         tmp |= EPCTRL_TX_EP_STALL | EPCTRL_RX_EP_STALL;
1706         udc_writel(udc, tmp, EP_CONTROL_REG_OFFSET);
1707         udc->ep0_state = WAIT_FOR_SETUP;
1708         udc->ep0_dir = 0;
1709 }
1710
1711 /* Prime a status phase for ep0 */
1712 static int ep0_prime_status(struct tegra_udc *udc, int direction)
1713 {
1714         struct tegra_req *req = udc->status_req;
1715         struct tegra_ep *ep;
1716
1717         if (direction == EP_DIR_IN)
1718                 udc->ep0_dir = USB_DIR_IN;
1719         else
1720                 udc->ep0_dir = USB_DIR_OUT;
1721
1722         ep = &udc->eps[0];
1723         udc->ep0_state = WAIT_FOR_OUT_STATUS;
1724
1725         req->ep = ep;
1726         req->req.length = 0;
1727         req->req.status = -EINPROGRESS;
1728         req->req.actual = 0;
1729         req->req.complete = NULL;
1730         req->dtd_count = 0;
1731
1732         if (tegra_req_to_dtd(req, GFP_ATOMIC) == 0)
1733                 tegra_queue_td(ep, req);
1734         else
1735                 return -ENOMEM;
1736
1737         list_add_tail(&req->queue, &ep->queue);
1738
1739         return 0;
1740 }
1741
1742 static void udc_reset_ep_queue(struct tegra_udc *udc, u8 pipe)
1743 {
1744         struct tegra_ep *ep = get_ep_by_pipe(udc, pipe);
1745
1746         if (ep->name[0])
1747                 nuke(ep, -ESHUTDOWN);
1748 }
1749
1750 /* ch9 Set address */
1751 static void ch9setaddress(struct tegra_udc *udc, u16 value, u16 index,
1752                 u16 length)
1753 {
1754         /* Save the new address to device struct */
1755         udc->device_address = (u8) value;
1756         /* Update usb state */
1757         udc->usb_state = USB_STATE_ADDRESS;
1758         /* Status phase */
1759         if (ep0_prime_status(udc, EP_DIR_IN))
1760                 ep0stall(udc);
1761 }
1762
1763 /* ch9 Get status */
1764 static void ch9getstatus(struct tegra_udc *udc, u8 request_type, u16 value,
1765                 u16 index, u16 length)
1766 {
1767         u16 tmp = 0;            /* Status, cpu endian */
1768         struct tegra_req *req;
1769         struct tegra_ep *ep;
1770
1771         ep = &udc->eps[0];
1772
1773         if ((request_type & USB_RECIP_MASK) == USB_RECIP_DEVICE) {
1774                 /* Get device status */
1775                 if (udc->selfpowered)
1776                         tmp = 1 << USB_DEVICE_SELF_POWERED;
1777                 tmp |= udc->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP;
1778         } else if ((request_type & USB_RECIP_MASK) == USB_RECIP_INTERFACE) {
1779                 /* Get interface status
1780                  * We don't have interface information in udc driver */
1781                 tmp = 0;
1782         } else if ((request_type & USB_RECIP_MASK) == USB_RECIP_ENDPOINT) {
1783                 /* Get endpoint status */
1784                 struct tegra_ep *target_ep;
1785
1786                 target_ep = get_ep_by_pipe(udc, get_pipe_by_windex(index));
1787
1788                 /* stall if endpoint doesn't exist */
1789                 if (!target_ep->desc)
1790                         goto stall;
1791                 tmp = dr_ep_get_stall(udc, ep_index(target_ep),
1792                                 ep_is_in(target_ep)) << USB_ENDPOINT_HALT;
1793         }
1794
1795         udc->ep0_dir = USB_DIR_IN;
1796         /* Borrow the per device status_req */
1797         req = udc->status_req;
1798         /* Fill in the reqest structure */
1799         *((u16 *) req->req.buf) = cpu_to_le16(tmp);
1800         req->ep = ep;
1801         req->req.length = 2;
1802         req->req.status = -EINPROGRESS;
1803         req->req.actual = 0;
1804         req->req.complete = NULL;
1805         req->dtd_count = 0;
1806
1807         /* map virtual address to hardware */
1808         if (req->req.dma == DMA_ADDR_INVALID) {
1809                 DEFINE_DMA_ATTRS(attrs);
1810                 struct device *dev = ep->udc->gadget.dev.parent;
1811                 size_t orig = req->req.length;
1812                 size_t ext = orig + AHB_PREFETCH_BUFFER;
1813                 enum dma_data_direction dir =
1814                         ep_is_in(ep) ? DMA_TO_DEVICE : DMA_FROM_DEVICE;
1815
1816                 dma_set_attr(DMA_ATTR_SKIP_CPU_SYNC, &attrs);
1817                 req->req.dma = dma_map_single_attrs(dev, req->req.buf, ext, dir,
1818                                                     &attrs);
1819                 if (dma_mapping_error(dev, req->req.dma))
1820                         return;
1821
1822                 dma_sync_single_for_device(dev, req->req.dma, orig, dir);
1823
1824                 req->mapped = 1;
1825         } else {
1826                 dma_sync_single_for_device(ep->udc->gadget.dev.parent,
1827                                         req->req.dma, req->req.length,
1828                                         ep_is_in(ep)
1829                                                 ? DMA_TO_DEVICE
1830                                                 : DMA_FROM_DEVICE);
1831                 req->mapped = 0;
1832         }
1833
1834         /* prime the data phase */
1835         if ((tegra_req_to_dtd(req, GFP_ATOMIC) == 0))
1836                 tegra_queue_td(ep, req);
1837         else                    /* no mem */
1838                 goto stall;
1839
1840         list_add_tail(&req->queue, &ep->queue);
1841         udc->ep0_state = DATA_STATE_XMIT;
1842         return;
1843 stall:
1844         ep0stall(udc);
1845 }
1846
1847 static void udc_test_mode(struct tegra_udc *udc, u32 test_mode)
1848 {
1849         struct tegra_req *req = NULL;
1850         struct tegra_ep *ep;
1851         u32 portsc, bitmask;
1852         unsigned long timeout;
1853
1854         /* Ack the ep0 IN */
1855         if (ep0_prime_status(udc, EP_DIR_IN))
1856                 ep0stall(udc);
1857
1858         /* get the ep0 */
1859         ep = &udc->eps[0];
1860         bitmask = ep_is_in(ep)
1861                 ? (1 << (ep_index(ep) + 16))
1862                 : (1 << (ep_index(ep)));
1863
1864         timeout = jiffies + HZ;
1865         /* Wait until ep0 IN endpoint txfr is complete */
1866         while (!(udc_readl(udc, EP_COMPLETE_REG_OFFSET) & bitmask)) {
1867                 if (time_after(jiffies, timeout)) {
1868                         pr_err("Timeout for Ep0 IN Ack\n");
1869                         break;
1870                 }
1871                 cpu_relax();
1872         }
1873
1874         switch (test_mode << PORTSCX_PTC_BIT_POS) {
1875         case PORTSCX_PTC_JSTATE:
1876                 udc->current_limit = USB_CHARGING_TEST_MODE_CURRENT_LIMIT_MA;
1877                 schedule_work(&udc->current_work);
1878                 VDBG("TEST_J\n");
1879                 break;
1880         case PORTSCX_PTC_KSTATE:
1881                 udc->current_limit = USB_CHARGING_TEST_MODE_CURRENT_LIMIT_MA;
1882                 schedule_work(&udc->current_work);
1883                 VDBG("TEST_K\n");
1884                 break;
1885         case PORTSCX_PTC_SEQNAK:
1886                 udc->current_limit = USB_CHARGING_TEST_MODE_CURRENT_LIMIT_MA;
1887                 schedule_work(&udc->current_work);
1888                 VDBG("TEST_SE0_NAK\n");
1889                 break;
1890         case PORTSCX_PTC_PACKET:
1891                 VDBG("TEST_PACKET\n");
1892
1893                 /* get the ep and configure for IN direction */
1894                 ep = &udc->eps[0];
1895                 udc->ep0_dir = USB_DIR_IN;
1896
1897                 /* Initialize ep0 status request structure */
1898                 req = container_of(tegra_alloc_request(NULL, GFP_ATOMIC),
1899                                 struct tegra_req, req);
1900                 /* allocate a small amount of memory to get valid address */
1901                 req->req.buf = kmalloc(sizeof(tegra_udc_test_packet),
1902                                         GFP_ATOMIC);
1903                 req->req.dma = virt_to_phys(req->req.buf);
1904
1905                 /* Fill in the reqest structure */
1906                 memcpy(req->req.buf, tegra_udc_test_packet,
1907                                         sizeof(tegra_udc_test_packet));
1908                 req->ep = ep;
1909                 req->req.length = sizeof(tegra_udc_test_packet);
1910                 req->req.status = -EINPROGRESS;
1911                 req->req.actual = 0;
1912                 req->req.complete = NULL;
1913                 req->dtd_count = 0;
1914                 req->mapped = 0;
1915
1916                 dma_sync_single_for_device(ep->udc->gadget.dev.parent,
1917                                         req->req.dma, req->req.length,
1918                                         ep_is_in(ep)
1919                                                 ? DMA_TO_DEVICE
1920                                                 : DMA_FROM_DEVICE);
1921
1922                 /* prime the data phase */
1923                 if ((tegra_req_to_dtd(req, GFP_ATOMIC) == 0))
1924                         tegra_queue_td(ep, req);
1925                 else                    /* no mem */
1926                         goto stall;
1927
1928                 list_add_tail(&req->queue, &ep->queue);
1929                 udc->ep0_state = DATA_STATE_XMIT;
1930                 break;
1931         case PORTSCX_PTC_FORCE_EN:
1932                 VDBG("TEST_FORCE_EN\n");
1933                 break;
1934         default:
1935                 ERR("udc unknown test mode[%d]!\n", test_mode);
1936                 goto stall;
1937         }
1938
1939         /* read the portsc register */
1940         portsc = udc_readl(udc, PORTSCX_REG_OFFSET);
1941         /* set the test mode selector */
1942         portsc |= test_mode << PORTSCX_PTC_BIT_POS;
1943         udc_writel(udc, portsc, PORTSCX_REG_OFFSET);
1944
1945         /*
1946          * The device must have its power cycled to exit test mode.
1947          * See USB 2.0 spec, section 9.4.9 for test modes operation
1948          * in "Set Feature".
1949          * See USB 2.0 spec, section 7.1.20 for test modes.
1950          */
1951         pr_info("udc entering the test mode, power cycle to exit test mode\n");
1952         return;
1953 stall:
1954         ep0stall(udc);
1955         if (req) {
1956                 kfree(req->req.buf);
1957                 tegra_free_request(NULL, &req->req);
1958         }
1959 }
1960
1961 static void setup_received_irq(struct tegra_udc *udc,
1962                 struct usb_ctrlrequest *setup)
1963 {
1964         u16 wValue = le16_to_cpu(setup->wValue);
1965         u16 wIndex = le16_to_cpu(setup->wIndex);
1966         u16 wLength = le16_to_cpu(setup->wLength);
1967
1968         udc_reset_ep_queue(udc, 0);
1969
1970         /* We process some stardard setup requests here */
1971         switch (setup->bRequest) {
1972         case USB_REQ_GET_STATUS:
1973                 /* Data+Status phase from udc */
1974                 if ((setup->bRequestType & (USB_DIR_IN | USB_TYPE_MASK))
1975                                         != (USB_DIR_IN | USB_TYPE_STANDARD))
1976                         break;
1977                 ch9getstatus(udc, setup->bRequestType, wValue, wIndex, wLength);
1978                 return;
1979
1980         case USB_REQ_SET_ADDRESS:
1981                 /* Status phase from udc */
1982                 if (setup->bRequestType != (USB_DIR_OUT | USB_TYPE_STANDARD
1983                                                 | USB_RECIP_DEVICE))
1984                         break;
1985                 /* This delay is necessary for some windows drivers to
1986                  * properly recognize the device */
1987                 mdelay(1);
1988                 ch9setaddress(udc, wValue, wIndex, wLength);
1989                 return;
1990
1991         case USB_REQ_CLEAR_FEATURE:
1992         case USB_REQ_SET_FEATURE:
1993                 /* Status phase from udc */
1994         {
1995                 int rc = -EOPNOTSUPP;
1996
1997                 if (setup->bRequestType == USB_RECIP_DEVICE &&
1998                                  wValue == USB_DEVICE_TEST_MODE) {
1999                         /*
2000                          * If the feature selector is TEST_MODE, then the most
2001                          * significant byte of wIndex is used to specify the
2002                          * specific test mode and the lower byte of wIndex must
2003                          * be zero.
2004                          */
2005                         udc_test_mode(udc, wIndex >> 8);
2006                         return;
2007
2008                 } else if ((setup->bRequestType &
2009                                 (USB_RECIP_MASK | USB_TYPE_MASK)) ==
2010                                 (USB_RECIP_ENDPOINT | USB_TYPE_STANDARD)) {
2011                         int pipe = get_pipe_by_windex(wIndex);
2012                         struct tegra_ep *ep;
2013
2014                         if (wValue != 0 || wLength != 0 || pipe > udc->max_ep)
2015                                 break;
2016                         ep = get_ep_by_pipe(udc, pipe);
2017
2018                         spin_unlock(&udc->lock);
2019                         rc = tegra_ep_set_halt(&ep->ep,
2020                                         (setup->bRequest == USB_REQ_SET_FEATURE)
2021                                                 ? 1 : 0);
2022                         spin_lock(&udc->lock);
2023
2024                 } else if ((setup->bRequestType & (USB_RECIP_MASK
2025                                 | USB_TYPE_MASK)) == (USB_RECIP_DEVICE
2026                                 | USB_TYPE_STANDARD)) {
2027                         /* Note: The driver has not include OTG support yet.
2028                          * This will be set when OTG support is added */
2029                         if (!gadget_is_otg(&udc->gadget))
2030                                 break;
2031                         else if (setup->bRequest == USB_DEVICE_B_HNP_ENABLE)
2032                                 udc->gadget.b_hnp_enable = 1;
2033                         else if (setup->bRequest == USB_DEVICE_A_HNP_SUPPORT)
2034                                 udc->gadget.a_hnp_support = 1;
2035                         else if (setup->bRequest ==
2036                                         USB_DEVICE_A_ALT_HNP_SUPPORT)
2037                                 udc->gadget.a_alt_hnp_support = 1;
2038                         else
2039                                 break;
2040                         rc = 0;
2041                 } else
2042                         break;
2043
2044                 if (rc == 0) {
2045                         if (ep0_prime_status(udc, EP_DIR_IN))
2046                                 ep0stall(udc);
2047                 }
2048                 return;
2049         }
2050
2051         default:
2052                 break;
2053         }
2054
2055         /* Requests handled by gadget */
2056         if (wLength) {
2057                 /* Data phase from gadget, status phase from udc */
2058                 udc->ep0_dir = (setup->bRequestType & USB_DIR_IN)
2059                                 ?  USB_DIR_IN : USB_DIR_OUT;
2060                 spin_unlock(&udc->lock);
2061                 if (udc->driver && udc->driver->setup(&udc->gadget,
2062                                 &udc->local_setup_buff) < 0)
2063                         ep0stall(udc);
2064                 spin_lock(&udc->lock);
2065                 udc->ep0_state = (setup->bRequestType & USB_DIR_IN)
2066                                 ?  DATA_STATE_XMIT : DATA_STATE_RECV;
2067         } else {
2068                 /* No data phase, IN status from gadget */
2069                 udc->ep0_dir = USB_DIR_IN;
2070                 spin_unlock(&udc->lock);
2071                 if (udc->driver && udc->driver->setup(&udc->gadget,
2072                                 &udc->local_setup_buff) < 0)
2073                         ep0stall(udc);
2074                 spin_lock(&udc->lock);
2075                 udc->ep0_state = WAIT_FOR_OUT_STATUS;
2076         }
2077 }
2078
2079 /* Process request for Data or Status phase of ep0
2080  * prime status phase if needed */
2081 static void ep0_req_complete(struct tegra_udc *udc, struct tegra_ep *ep0,
2082                 struct tegra_req *req)
2083 {
2084         if (udc->usb_state == USB_STATE_ADDRESS) {
2085                 /* Set the new address */
2086                 u32 new_address = (u32) udc->device_address;
2087                 udc_writel(udc, new_address << USB_DEVICE_ADDRESS_BIT_POS,
2088                                 USB_DEVICE_ADDR_REG_OFFSET);
2089         }
2090
2091         done(ep0, req, 0);
2092
2093         switch (udc->ep0_state) {
2094         case DATA_STATE_XMIT:
2095                 /* receive status phase */
2096                 if (ep0_prime_status(udc, EP_DIR_OUT))
2097                         ep0stall(udc);
2098                 break;
2099         case DATA_STATE_RECV:
2100                 /* send status phase */
2101                 if (ep0_prime_status(udc, EP_DIR_IN))
2102                         ep0stall(udc);
2103                 break;
2104         case WAIT_FOR_OUT_STATUS:
2105                 udc->ep0_state = WAIT_FOR_SETUP;
2106                 break;
2107         case WAIT_FOR_SETUP:
2108                 ERR("Unexpect ep0 packets\n");
2109                 break;
2110         default:
2111                 ep0stall(udc);
2112                 break;
2113         }
2114 }
2115
2116 /* Tripwire mechanism to ensure a setup packet payload is extracted without
2117  * being corrupted by another incoming setup packet */
2118 static void tripwire_handler(struct tegra_udc *udc, u8 ep_num, u8 *buffer_ptr)
2119 {
2120         u32 temp;
2121         struct ep_queue_head *qh;
2122
2123         qh = &udc->ep_qh[ep_num * 2 + EP_DIR_OUT];
2124
2125         /* Clear bit in ENDPTSETUPSTAT */
2126         temp = udc_readl(udc, EP_SETUP_STATUS_REG_OFFSET);
2127         udc_writel(udc, temp | (1 << ep_num), EP_SETUP_STATUS_REG_OFFSET);
2128
2129         /* while a hazard exists when setup package arrives */
2130         do {
2131                 /* Set Setup Tripwire */
2132                 temp = udc_readl(udc, USB_CMD_REG_OFFSET);
2133                 udc_writel(udc, temp | USB_CMD_SUTW, USB_CMD_REG_OFFSET);
2134
2135                 /* Copy the setup packet to local buffer */
2136                 memcpy(buffer_ptr, (u8 *) qh->setup_buffer, 8);
2137         } while (!(udc_readl(udc, USB_CMD_REG_OFFSET) & USB_CMD_SUTW));
2138
2139         /* Clear Setup Tripwire */
2140         temp = udc_readl(udc, USB_CMD_REG_OFFSET);
2141         udc_writel(udc, temp & ~USB_CMD_SUTW, USB_CMD_REG_OFFSET);
2142 }
2143
2144 /* process-ep_req(): free the completed Tds for this req */
2145 static int process_ep_req(struct tegra_udc *udc, int pipe,
2146                 struct tegra_req *curr_req)
2147 {
2148         struct ep_td_struct *curr_td;
2149         int     td_complete, actual, remaining_length, j, tmp;
2150         int     status = 0;
2151         int     errors = 0;
2152         struct  ep_queue_head *curr_qh = &udc->ep_qh[pipe];
2153         int direction = pipe % 2;
2154
2155         curr_td = curr_req->head;
2156         td_complete = 0;
2157         actual = curr_req->req.length;
2158
2159         for (j = 0; j < curr_req->dtd_count; j++) {
2160                 /* Fence read for coherency of AHB master intiated writes */
2161                 if (udc->fence_read)
2162                         readb(IO_ADDRESS(IO_PPCS_PHYS + USB1_PREFETCH_ID));
2163
2164                 dma_sync_single_for_cpu(udc->gadget.dev.parent, curr_td->td_dma,
2165                                 sizeof(struct ep_td_struct), DMA_FROM_DEVICE);
2166
2167                 remaining_length = (le32_to_cpu(curr_td->size_ioc_sts)
2168                                         & DTD_PACKET_SIZE)
2169                                 >> DTD_LENGTH_BIT_POS;
2170                 actual -= remaining_length;
2171                 errors = le32_to_cpu(curr_td->size_ioc_sts);
2172                 if (errors & DTD_ERROR_MASK) {
2173                         if (errors & DTD_STATUS_HALTED) {
2174                                 ERR("dTD error %08x QH=%d\n", errors, pipe);
2175                                 /* Clear the errors and Halt condition */
2176                                 tmp = le32_to_cpu(curr_qh->size_ioc_int_sts);
2177                                 tmp &= ~errors;
2178                                 curr_qh->size_ioc_int_sts = cpu_to_le32(tmp);
2179                                 status = -EPIPE;
2180                                 /* FIXME: continue with next queued TD? */
2181
2182                                 break;
2183                         }
2184                         if (errors & DTD_STATUS_DATA_BUFF_ERR) {
2185                                 VDBG("Transfer overflow");
2186                                 status = -EPROTO;
2187                                 break;
2188                         } else if (errors & DTD_STATUS_TRANSACTION_ERR) {
2189                                 VDBG("ISO error");
2190                                 status = -EILSEQ;
2191                                 break;
2192                         } else
2193                                 ERR("Unknown error has occurred (0x%x)!\n",
2194                                         errors);
2195
2196                 } else if (le32_to_cpu(curr_td->size_ioc_sts)
2197                                 & DTD_STATUS_ACTIVE) {
2198                         VDBG("Request not complete");
2199                         status = REQ_UNCOMPLETE;
2200                         return status;
2201                 } else if (remaining_length) {
2202                         if (direction) {
2203                                 VDBG("Transmit dTD remaining length not zero");
2204                                 status = -EPROTO;
2205                                 break;
2206                         } else {
2207                                 td_complete++;
2208                                 break;
2209                         }
2210                 } else {
2211                         td_complete++;
2212                         VDBG("dTD transmitted successful");
2213                 }
2214
2215                 if (j != curr_req->dtd_count - 1)
2216                         curr_td = (struct ep_td_struct *)curr_td->next_td_virt;
2217         }
2218
2219         if (status)
2220                 return status;
2221
2222         curr_req->req.actual = actual;
2223
2224         return 0;
2225 }
2226
2227 /* Process a DTD completion interrupt */
2228 static void dtd_complete_irq(struct tegra_udc *udc)
2229 {
2230         u32 bit_pos;
2231         int i, ep_num, direction, bit_mask, status;
2232         struct tegra_ep *curr_ep;
2233         struct tegra_req *curr_req, *temp_req;
2234
2235         /* Clear the bits in the register */
2236         bit_pos = udc_readl(udc, EP_COMPLETE_REG_OFFSET);
2237         udc_writel(udc, bit_pos, EP_COMPLETE_REG_OFFSET);
2238
2239         if (!bit_pos)
2240                 return;
2241
2242         for (i = 0; i < udc->max_ep; i++) {
2243                 ep_num = i >> 1;
2244                 direction = i % 2;
2245
2246                 bit_mask = 1 << (ep_num + 16 * direction);
2247
2248                 if (!(bit_pos & bit_mask))
2249                         continue;
2250
2251                 curr_ep = get_ep_by_pipe(udc, i);
2252
2253                 /* If the ep is configured */
2254                 if (curr_ep->name[0] == '\0') {
2255                         WARNING("Invalid EP?");
2256                         continue;
2257                 }
2258
2259                 /* process the req queue until an uncomplete request */
2260                 list_for_each_entry_safe(curr_req, temp_req, &curr_ep->queue,
2261                                 queue) {
2262                         status = process_ep_req(udc, i, curr_req);
2263
2264                         VDBG("status of process_ep_req= %d, ep = %d",
2265                                         status, ep_num);
2266                         if (status == REQ_UNCOMPLETE)
2267                                 break;
2268                         /* write back status to req */
2269                         curr_req->req.status = status;
2270
2271                         if (ep_num == 0) {
2272                                 ep0_req_complete(udc, curr_ep, curr_req);
2273                                 break;
2274                         } else
2275                                 done(curr_ep, curr_req, status);
2276                 }
2277         }
2278 }
2279
2280 /* Process a port change interrupt */
2281 static void port_change_irq(struct tegra_udc *udc)
2282 {
2283         u32 speed;
2284         unsigned int port_control_reg_offset;
2285
2286         if (udc->has_hostpc)
2287                 port_control_reg_offset = USB_HOSTPCX_DEVLC_REG_OFFSET;
2288         else
2289                 port_control_reg_offset = PORTSCX_REG_OFFSET;
2290
2291         /* Bus resetting is finished */
2292         if (!(udc_readl(udc, port_control_reg_offset) & PORTSCX_PORT_RESET)) {
2293                 /* Get the speed */
2294                 speed = (udc_readl(udc, port_control_reg_offset)
2295                                 & PORTSCX_PORT_SPEED_MASK);
2296                 if (speed == PORTSCX_PORT_SPEED_HIGH)
2297                         udc->gadget.speed = USB_SPEED_HIGH;
2298                 else if (speed == PORTSCX_PORT_SPEED_FULL)
2299                         udc->gadget.speed = USB_SPEED_FULL;
2300                 else if (speed == PORTSCX_PORT_SPEED_LOW)
2301                         udc->gadget.speed = USB_SPEED_LOW;
2302                 else
2303                         udc->gadget.speed = USB_SPEED_UNKNOWN;
2304         }
2305
2306         /* Update USB state */
2307         if (!udc->resume_state)
2308                 udc->usb_state = USB_STATE_DEFAULT;
2309 }
2310
2311 /* Process suspend interrupt */
2312 static void suspend_irq(struct tegra_udc *udc)
2313 {
2314         udc->resume_state = udc->usb_state;
2315         udc->usb_state = USB_STATE_SUSPENDED;
2316
2317         /* report suspend to the driver, serial.c does not support this */
2318         if (udc->driver && udc->driver->suspend)
2319                 udc->driver->suspend(&udc->gadget);
2320 }
2321
2322 static void bus_resume(struct tegra_udc *udc)
2323 {
2324         udc->usb_state = udc->resume_state;
2325         udc->resume_state = 0;
2326
2327         /* report resume to the driver, serial.c does not support this */
2328         if (udc->driver && udc->driver->resume)
2329                 udc->driver->resume(&udc->gadget);
2330 }
2331
2332 /* Clear up all ep queues */
2333 static int reset_queues(struct tegra_udc *udc)
2334 {
2335         u8 pipe;
2336
2337         for (pipe = 0; pipe < udc->max_pipes; pipe++)
2338                 udc_reset_ep_queue(udc, pipe);
2339
2340         /* report disconnect; the driver is already quiesced */
2341         spin_unlock(&udc->lock);
2342         if (udc->driver && udc->driver->disconnect)
2343                 udc->driver->disconnect(&udc->gadget);
2344         spin_lock(&udc->lock);
2345
2346         return 0;
2347 }
2348
2349 /* Process reset interrupt */
2350 static void reset_irq(struct tegra_udc *udc)
2351 {
2352         u32 temp;
2353         unsigned long timeout;
2354
2355         /* Clear the device address */
2356         temp = udc_readl(udc, USB_DEVICE_ADDR_REG_OFFSET);
2357         udc_writel(udc, temp & ~USB_DEVICE_ADDRESS_MASK,
2358                                 USB_DEVICE_ADDR_REG_OFFSET);
2359
2360         udc->device_address = 0;
2361
2362         /* Clear usb state */
2363         udc->resume_state = 0;
2364         udc->ep0_dir = 0;
2365         udc->ep0_state = WAIT_FOR_SETUP;
2366         udc->remote_wakeup = 0; /* default to 0 on reset */
2367         udc->gadget.b_hnp_enable = 0;
2368         udc->gadget.a_hnp_support = 0;
2369         udc->gadget.a_alt_hnp_support = 0;
2370
2371         /* Clear all the setup token semaphores */
2372         temp = udc_readl(udc, EP_SETUP_STATUS_REG_OFFSET);
2373         udc_writel(udc, temp, EP_SETUP_STATUS_REG_OFFSET);
2374
2375         /* Clear all the endpoint complete status bits */
2376         temp = udc_readl(udc, EP_COMPLETE_REG_OFFSET);
2377         udc_writel(udc, temp, EP_COMPLETE_REG_OFFSET);
2378
2379         timeout = jiffies + 100;
2380         while (udc_readl(udc, EP_PRIME_REG_OFFSET)) {
2381                 /* Wait until all endptprime bits cleared */
2382                 if (time_after(jiffies, timeout)) {
2383                         ERR("Timeout for reset\n");
2384                         break;
2385                 }
2386                 cpu_relax();
2387         }
2388
2389         /* Write 1s to the flush register */
2390         udc_writel(udc, 0xffffffff, EPFLUSH_REG_OFFSET);
2391
2392         /* When the bus reset is seen on Tegra, the PORTSCX_PORT_RESET bit
2393          * is not set. Reset all the queues, include XD, dTD, EP queue
2394          * head and TR Queue */
2395         VDBG("Bus reset");
2396         reset_queues(udc);
2397         udc->usb_state = USB_STATE_DEFAULT;
2398 }
2399
2400 static void tegra_udc_set_current_limit_work(struct work_struct *work)
2401 {
2402         struct tegra_udc *udc = container_of(work, struct tegra_udc,
2403                                                 current_work);
2404         tegra_usb_set_charging_current(udc);
2405 }
2406
2407 #ifdef CONFIG_TEGRA_GADGET_BOOST_CPU_FREQ
2408 void tegra_udc_set_cpu_freq_normal(unsigned long data)
2409 {
2410         set_cpufreq_normal_flag = 1;
2411         schedule_work(&the_udc->boost_cpufreq_work);
2412 }
2413
2414 static void tegra_udc_boost_cpu_frequency_work(struct work_struct *work)
2415 {
2416         if (set_cpufreq_normal_flag) {
2417                 pm_qos_update_request(&boost_cpu_freq_req,
2418                                         PM_QOS_DEFAULT_VALUE);
2419                 boost_cpufreq_work_flag = 1;
2420                 set_cpufreq_normal_flag = 0;
2421                 DBG("%s(%d) set CPU frequency to normal\n", __func__,
2422                                                         __LINE__);
2423                 return ;
2424         }
2425
2426         /* If CPU frequency is not boosted earlier boost it, and modify
2427          * timer expiry time to 2sec */
2428         if (boost_cpufreq_work_flag) {
2429                 if (boost_enable)
2430                         pm_qos_update_request(
2431                                 &boost_cpu_freq_req,
2432                                 (s32)(CONFIG_TEGRA_GADGET_BOOST_CPU_FREQ
2433                                       * 1000));
2434                 boost_cpufreq_work_flag = 0;
2435                 DBG("%s(%d) boost CPU frequency\n", __func__, __LINE__);
2436         }
2437         mod_timer(&boost_timer, jiffies + msecs_to_jiffies(2000));
2438 }
2439 #endif
2440
2441 static void tegra_udc_irq_work(struct work_struct *irq_work)
2442 {
2443         struct tegra_udc *udc = container_of(irq_work, struct tegra_udc,
2444                                                  irq_work);
2445         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
2446
2447         /* Check whether cable is connected*/
2448         if (vbus_enabled(udc))
2449                 tegra_vbus_session(&udc->gadget, 1);
2450         else
2451                 tegra_vbus_session(&udc->gadget, 0);
2452
2453         DBG("%s(%d) END\n", __func__, __LINE__);
2454 }
2455
2456 /*
2457  * When VBUS is detected we already know it is DCP/SDP/CDP devices if it is a
2458  * standard device. If we did not receive EP0 setup packet, we can assume it
2459  * as a non-standard charger.
2460  */
2461 static void tegra_udc_non_std_charger_detect_work(struct work_struct *work)
2462 {
2463         struct tegra_udc *udc = container_of(work, struct tegra_udc,
2464                                         non_std_charger_work.work);
2465         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
2466
2467         tegra_udc_set_charger_type(udc, CONNECT_TYPE_NON_STANDARD_CHARGER);
2468         tegra_usb_set_charging_current(udc);
2469
2470         DBG("%s(%d) END\n", __func__, __LINE__);
2471 }
2472
2473 /* Restart device controller in the OTG mode on VBUS detection */
2474 static void tegra_udc_restart(struct tegra_udc *udc)
2475 {
2476         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
2477
2478         /* setup the controller in the device mode */
2479         dr_controller_setup(udc);
2480         /* setup EP0 for setup packet */
2481         ep0_setup(udc);
2482         udc->vbus_active = 1;
2483         /* start the controller */
2484         dr_controller_run(udc);
2485         /* initialize the USB and EP states */
2486         udc->usb_state = USB_STATE_ATTACHED;
2487         udc->ep0_state = WAIT_FOR_SETUP;
2488         udc->ep0_dir = 0;
2489
2490         DBG("%s(%d) END\n", __func__, __LINE__);
2491 }
2492
2493 /* USB device controller interrupt handler */
2494 static irqreturn_t tegra_udc_irq(int irq, void *_udc)
2495 {
2496         struct tegra_udc *udc = _udc;
2497         u32 irq_src, temp;
2498         irqreturn_t status = IRQ_NONE;
2499         unsigned long flags;
2500
2501         spin_lock_irqsave(&udc->lock, flags);
2502
2503         if (!udc->transceiver) {
2504                 if (tegra_platform_is_fpga()) {
2505                         temp = udc_readl(udc, VBUS_SENSOR_REG_OFFSET);
2506                         /* write back the register to clear the interrupt */
2507                         udc_writel(udc, temp, VBUS_SENSOR_REG_OFFSET);
2508                         if (temp & USB_SYS_VBUS_ASESSION_CHANGED)
2509                                 schedule_work(&udc->irq_work);
2510                         status = IRQ_HANDLED;
2511                 } else {
2512                         temp = udc_readl(udc, VBUS_WAKEUP_REG_OFFSET);
2513                         /* write back the register to clear the interrupt */
2514                         udc_writel(udc, temp, VBUS_WAKEUP_REG_OFFSET);
2515                         if (temp & USB_SYS_VBUS_WAKEUP_INT_STATUS)
2516                                 schedule_work(&udc->irq_work);
2517                         status = IRQ_HANDLED;
2518                 }
2519         }
2520
2521         /* Disable ISR for OTG host mode */
2522         if (udc->stopped)
2523                 goto done;
2524
2525         /* Fence read for coherency of AHB master intiated writes */
2526         if (udc->fence_read)
2527                 readb(IO_ADDRESS(IO_PPCS_PHYS + USB1_PREFETCH_ID));
2528
2529         irq_src = udc_readl(udc, USB_STS_REG_OFFSET) &
2530                                 udc_readl(udc, USB_INTR_REG_OFFSET);
2531
2532         if (irq_src == 0)
2533                 goto done;
2534
2535         /* Clear notification bits */
2536         udc_writel(udc, irq_src, USB_STS_REG_OFFSET);
2537
2538         /* Need to resume? */
2539         if (udc->usb_state == USB_STATE_SUSPENDED)
2540                 if (!(udc_readl(udc, PORTSCX_REG_OFFSET)
2541                                 & PORTSCX_PORT_SUSPEND))
2542                         bus_resume(udc);
2543
2544         /* USB Interrupt */
2545         if (irq_src & USB_STS_INT) {
2546                 VDBG("Packet int");
2547                 /* Setup package, we only support ep0 as control ep */
2548                 if (udc_readl(udc, EP_SETUP_STATUS_REG_OFFSET) &
2549                                 EP_SETUP_STATUS_EP0) {
2550                         /* Setup packet received, we are connected to host
2551                          * and not to charger. Cancel any delayed work */
2552                         cancel_delayed_work(&udc->non_std_charger_work);
2553                         tripwire_handler(udc, 0,
2554                                         (u8 *) (&udc->local_setup_buff));
2555                         setup_received_irq(udc, &udc->local_setup_buff);
2556                         status = IRQ_HANDLED;
2557                 }
2558
2559                 /* completion of dtd */
2560                 if (udc_readl(udc, EP_COMPLETE_REG_OFFSET)) {
2561                         dtd_complete_irq(udc);
2562                         status = IRQ_HANDLED;
2563                 }
2564         }
2565
2566         /* SOF (for ISO transfer) */
2567         if (irq_src & USB_STS_SOF)
2568                 status = IRQ_HANDLED;
2569
2570         /* Port Change */
2571         if (irq_src & USB_STS_PORT_CHANGE) {
2572                 port_change_irq(udc);
2573                 status = IRQ_HANDLED;
2574         }
2575
2576         /* Reset Received */
2577         if (irq_src & USB_STS_RESET) {
2578                 reset_irq(udc);
2579                 status = IRQ_HANDLED;
2580         }
2581
2582         /* Sleep Enable (Suspend) */
2583         if (irq_src & USB_STS_SUSPEND) {
2584                 suspend_irq(udc);
2585                 status = IRQ_HANDLED;
2586         }
2587
2588         if (irq_src & (USB_STS_ERR | USB_STS_SYS_ERR))
2589                 VDBG("Error IRQ %x", irq_src);
2590
2591 done:
2592         spin_unlock_irqrestore(&udc->lock, flags);
2593         return status;
2594 }
2595
2596 /**
2597  * Hook to gadget drivers
2598  * Called by initialization code of gadget drivers
2599  */
2600 static int tegra_udc_start(struct usb_gadget *g,
2601                 struct usb_gadget_driver *driver)
2602 {
2603         struct tegra_udc *udc = the_udc;
2604         unsigned long flags = 0;
2605         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
2606
2607         /* lock is needed but whether should use this lock or another */
2608         spin_lock_irqsave(&udc->lock, flags);
2609
2610         driver->driver.bus = NULL;
2611         /* hook up the driver */
2612         udc->driver = driver;
2613         spin_unlock_irqrestore(&udc->lock, flags);
2614
2615         /* Enable DR IRQ reg and Set usbcmd reg  Run bit */
2616         if (vbus_enabled(udc) && !(udc->transceiver
2617                         && udc->transceiver->state != OTG_STATE_B_PERIPHERAL))
2618                 tegra_vbus_session(&udc->gadget, 1);
2619
2620         printk(KERN_INFO "%s: bind to driver %s\n",
2621                         udc->gadget.name, driver->driver.name);
2622
2623         DBG("%s(%d) END\n", __func__, __LINE__);
2624         return 0;
2625 }
2626
2627 /* Disconnect from gadget driver */
2628 static int tegra_udc_stop(struct usb_gadget *g,
2629                 struct usb_gadget_driver *driver)
2630 {
2631         struct tegra_udc *udc = the_udc;
2632         struct tegra_ep *loop_ep;
2633         unsigned long flags;
2634
2635         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
2636
2637         tegra_vbus_session(&udc->gadget, 0);
2638
2639         /* stand operation */
2640         spin_lock_irqsave(&udc->lock, flags);
2641         udc->gadget.speed = USB_SPEED_UNKNOWN;
2642         nuke(&udc->eps[0], -ESHUTDOWN);
2643         list_for_each_entry(loop_ep, &udc->gadget.ep_list,
2644                         ep.ep_list)
2645                 nuke(loop_ep, -ESHUTDOWN);
2646         spin_unlock_irqrestore(&udc->lock, flags);
2647
2648         udc->gadget.dev.driver = NULL;
2649         udc->driver = NULL;
2650
2651         if (driver)
2652                 DBG("%s(%d) unregistered gadget driver '%s'\n",
2653                          __func__, __LINE__, driver->driver.name);
2654
2655         DBG("%s(%d) END\n", __func__, __LINE__);
2656
2657         return 0;
2658 }
2659
2660
2661 /* Internal structure setup functions */
2662 static int tegra_udc_setup_qh(struct tegra_udc *udc)
2663 {
2664         u32 dccparams;
2665         size_t size;
2666         struct resource *res;
2667
2668         /* Read Device Controller Capability Parameters register */
2669         dccparams = udc_readl(udc, DCCPARAMS_REG_OFFSET);
2670         if (!(dccparams & DCCPARAMS_DC)) {
2671                 ERR("This SOC doesn't support device role\n");
2672                 return -ENODEV;
2673         }
2674
2675         /* Get max device endpoints */
2676         /* DEN is bidirectional ep number, max_ep doubles the number */
2677         udc->max_ep = (dccparams & DCCPARAMS_DEN_MASK) * 2;
2678
2679         udc->eps = kzalloc(sizeof(struct tegra_ep) * udc->max_ep, GFP_KERNEL);
2680         if (!udc->eps) {
2681                 ERR("malloc tegra_ep failed\n");
2682                 return -1;
2683         }
2684
2685         /* Setup hardware queue heads */
2686         size = udc->max_ep * sizeof(struct ep_queue_head);
2687         udc->ep_qh = (struct ep_queue_head *)((u8 *)(udc->regs) + QH_OFFSET);
2688         res = platform_get_resource(udc->pdev, IORESOURCE_MEM, 0);
2689         if (!res) {
2690                 ERR("resource request failed\n");
2691                 kfree(udc->eps);
2692                 return -ENODEV;
2693         }
2694         udc->ep_qh_dma = res->start + QH_OFFSET;
2695         udc->ep_qh_size = size;
2696
2697         /* Initialize ep0 status request structure */
2698         /* FIXME: tegra_alloc_request() ignores ep argument */
2699         udc->status_req = container_of(tegra_alloc_request(NULL, GFP_KERNEL),
2700                         struct tegra_req, req);
2701         /* Allocate a small amount of memory to get valid address */
2702         udc->status_req->req.buf = dma_alloc_coherent(&udc->pdev->dev,
2703                                 STATUS_BUFFER_SIZE, &udc->status_req->req.dma,
2704                                 GFP_KERNEL);
2705         if (!udc->status_req->req.buf) {
2706                 ERR("alloc status_req buffer failed\n");
2707                 kfree(udc->eps);
2708                 return -ENOMEM;
2709         }
2710
2711         udc->resume_state = USB_STATE_NOTATTACHED;
2712         udc->usb_state = USB_STATE_POWERED;
2713         udc->ep0_dir = 0;
2714         udc->remote_wakeup = 0; /* default to 0 on reset */
2715
2716         return 0;
2717 }
2718
2719 /**
2720  * Setup the tegra_ep struct for eps
2721  * Link tegra_ep->ep to gadget->ep_list
2722  * ep0out is not used so do nothing here
2723  * ep0in should be taken care
2724  */
2725 static int __init struct_ep_setup(struct tegra_udc *udc, unsigned char index,
2726                 char *name, int link)
2727 {
2728         struct tegra_ep *ep = &udc->eps[index];
2729
2730         ep->udc = udc;
2731         strcpy(ep->name, name);
2732         ep->ep.name = ep->name;
2733
2734         ep->ep.ops = &tegra_ep_ops;
2735         ep->stopped = 0;
2736
2737         /* for ep0: maxP defined in desc
2738          * for other eps, maxP is set by epautoconfig() called by gadget layer
2739          */
2740         ep->ep.maxpacket = (unsigned short) ~0;
2741
2742         /* the queue lists any req for this ep */
2743         INIT_LIST_HEAD(&ep->queue);
2744
2745         /* gagdet.ep_list used for ep_autoconfig so no ep0 */
2746         if (link)
2747                 list_add_tail(&ep->ep.ep_list, &udc->gadget.ep_list);
2748         ep->gadget = &udc->gadget;
2749         ep->qh = &udc->ep_qh[index];
2750
2751         return 0;
2752 }
2753
2754 static int tegra_udc_ep_setup(struct tegra_udc *udc)
2755 {
2756         /* initialize EP0 descriptor */
2757         static const struct usb_endpoint_descriptor tegra_ep0_desc = {
2758                 .bLength =              USB_DT_ENDPOINT_SIZE,
2759                 .bDescriptorType =      USB_DT_ENDPOINT,
2760                 .bEndpointAddress = 0,
2761                 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
2762                 .wMaxPacketSize =       USB_MAX_CTRL_PAYLOAD,
2763         };
2764         int i;
2765
2766         /* setup QH and epctrl for ep0 */
2767         ep0_setup(udc);
2768
2769         /* setup udc->eps[] for ep0 */
2770         struct_ep_setup(udc, 0, "ep0", 0);
2771         /* for ep0: the desc defined here;
2772          * for other eps, gadget layer called ep_enable with defined desc
2773          */
2774         udc->eps[0].desc = &tegra_ep0_desc;
2775         udc->eps[0].ep.maxpacket = USB_MAX_CTRL_PAYLOAD;
2776
2777         /* setup the udc->eps[] for non-control endpoints and link
2778          * to gadget.ep_list */
2779         for (i = 1; i < (int)(udc->max_ep / 2); i++) {
2780                 char name[14];
2781
2782                 sprintf(name, "ep%dout", i);
2783                 struct_ep_setup(udc, i * 2, name, 1);
2784                 sprintf(name, "ep%din", i);
2785                 struct_ep_setup(udc, i * 2 + 1, name, 1);
2786         }
2787
2788         return 0;
2789 }
2790
2791
2792 /* Driver probe function
2793  * all intialization operations implemented here except enabling usb_intr reg
2794  * board setup should have been done in the platform code
2795  */
2796 static int __init tegra_udc_probe(struct platform_device *pdev)
2797 {
2798         struct tegra_udc *udc;
2799         struct resource *res;
2800         struct tegra_usb_platform_data *pdata;
2801         int err = -ENODEV;
2802         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
2803
2804         if (strcmp(pdev->name, driver_name)) {
2805                 VDBG("Wrong device");
2806                 return -ENODEV;
2807         }
2808
2809         the_udc = udc = kzalloc(sizeof(struct tegra_udc), GFP_KERNEL);
2810         if (udc == NULL) {
2811                 ERR("malloc udc failed\n");
2812                 return -ENOMEM;
2813         }
2814
2815         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2816         if (!res) {
2817                 err = -ENXIO;
2818                 ERR("failed to get platform resources\n");
2819                 goto err_kfree;
2820         }
2821
2822         if (!request_mem_region(res->start, res->end - res->start + 1,
2823                                 driver_name)) {
2824                 ERR("request mem region failed\n");
2825                 err = -EBUSY;
2826                 goto err_kfree;
2827         }
2828
2829         udc->regs = ioremap(res->start, resource_size(res));
2830         if (!udc->regs) {
2831                 err = -ENOMEM;
2832                 ERR("failed to map mem region\n");
2833                 goto err_rel_mem_region;
2834         }
2835
2836         udc->irq = platform_get_irq(pdev, 0);
2837         if (!udc->irq) {
2838                 err = -ENODEV;
2839                 ERR("failed to get platform irq resources\n");
2840                 goto err_iounmap;
2841         }
2842
2843         err = request_irq(udc->irq, tegra_udc_irq,
2844                                 IRQF_SHARED | IRQF_TRIGGER_HIGH,
2845                                 driver_name, udc);
2846         if (err) {
2847                 ERR("cannot request irq %d err %d\n", udc->irq, err);
2848                 goto err_iounmap;
2849         }
2850
2851         /*Disable fence read if H/W support is disabled*/
2852         pdata = dev_get_platdata(&pdev->dev);
2853         if (pdata) {
2854                 if (pdata->unaligned_dma_buf_supported)
2855                         udc->fence_read = false;
2856                 else
2857                         udc->fence_read = true;
2858
2859                 udc->charging_supported = pdata->u_data.dev.charging_supported;
2860                 udc->qc2_voltage = pdata->qc2_voltage;
2861
2862                 udc->qc2_current_limit =
2863                         pdata->u_data.dev.qc2_current_limit_ma * 1000;
2864
2865                 DBG("%s: QC2 voltage = %d, current = %d\n",
2866                         __func__,
2867                         udc->qc2_voltage,
2868                         udc->qc2_current_limit);
2869
2870                 if (pdata->u_data.dev.dcp_current_limit_ma)
2871                         udc->dcp_current_limit =
2872                                 pdata->u_data.dev.dcp_current_limit_ma * 1000;
2873                 else
2874                         udc->dcp_current_limit =
2875                                 USB_CHARGING_DCP_CURRENT_LIMIT_UA;
2876         } else {
2877                 dev_err(&pdev->dev, "failed to get platform_data\n");
2878                 err = -ENODATA;
2879                 goto err_irq;
2880         }
2881
2882         udc->phy = tegra_usb_phy_open(pdev);
2883         if (IS_ERR(udc->phy)) {
2884                 dev_err(&pdev->dev, "failed to open USB phy\n");
2885                 err = -ENXIO;
2886                 goto err_irq;
2887         }
2888
2889         err = tegra_usb_phy_power_on(udc->phy);
2890         if (err) {
2891                 dev_err(&pdev->dev, "failed to power on the phy\n");
2892                 goto err_phy;
2893         }
2894
2895         err = usb_phy_init(get_usb_phy(udc->phy));
2896         if (err) {
2897                 dev_err(&pdev->dev, "failed to init the phy\n");
2898                 goto err_phy;
2899         }
2900         spin_lock_init(&udc->lock);
2901         mutex_init(&udc->sync_lock);
2902         udc->stopped = 1;
2903         udc->pdev = pdev;
2904         udc->has_hostpc = pdata->has_hostpc;
2905         udc->support_pmu_vbus = pdata->support_pmu_vbus;
2906         udc->connect_type_lp0 = CONNECT_TYPE_NONE;
2907         platform_set_drvdata(pdev, udc);
2908
2909         /* Initialize the udc structure including QH members */
2910         err = tegra_udc_setup_qh(udc);
2911         if (err) {
2912                 dev_err(&pdev->dev, "failed to setup udc QH\n");
2913                 goto err_phy;
2914         }
2915
2916         /* Initialize usb hw reg except for regs for EP,
2917          * leave usbintr reg untouched */
2918         err = dr_controller_setup(udc);
2919         if (err) {
2920                 dev_err(&pdev->dev, "failed to setup udc controller\n");
2921                 goto err_phy;
2922         }
2923
2924         /* Setup gadget structure */
2925         udc->gadget.ops = &tegra_gadget_ops;
2926         udc->gadget.max_speed = USB_SPEED_HIGH;
2927         udc->gadget.ep0 = &udc->eps[0].ep;
2928         INIT_LIST_HEAD(&udc->gadget.ep_list);
2929         udc->gadget.speed = USB_SPEED_UNKNOWN;
2930         udc->gadget.name = driver_name;
2931
2932         err = tegra_udc_ep_setup(udc);
2933         if (err) {
2934                 dev_err(&pdev->dev, "failed to setup end points\n");
2935                 goto err_phy;
2936         }
2937
2938         /* Use dma_pool for TD management */
2939         udc->td_pool = dma_pool_create("udc_td", &pdev->dev,
2940                         sizeof(struct ep_td_struct),
2941                         DTD_ALIGNMENT, UDC_DMA_BOUNDARY);
2942         if (!udc->td_pool) {
2943                 err = -ENOMEM;
2944                 goto err_phy;
2945         }
2946
2947         err = usb_add_gadget_udc_release(&pdev->dev, &udc->gadget,
2948                 tegra_udc_release);
2949         if (err)
2950                 goto err_del_udc;
2951 #ifdef CONFIG_TEGRA_GADGET_BOOST_CPU_FREQ
2952         boost_cpufreq_work_flag = 1;
2953         ep_queue_request_count = 0;
2954         INIT_WORK(&udc->boost_cpufreq_work,
2955                                         tegra_udc_boost_cpu_frequency_work);
2956         pm_qos_add_request(&boost_cpu_freq_req, PM_QOS_CPU_FREQ_MIN,
2957                                         PM_QOS_DEFAULT_VALUE);
2958         setup_timer(&boost_timer, tegra_udc_set_cpu_freq_normal, 0);
2959 #endif
2960
2961         /* External connector */
2962         udc->edev = kzalloc(sizeof(struct extcon_dev), GFP_KERNEL);
2963         if (!udc->edev) {
2964                 dev_err(&pdev->dev, "failed to allocate memory for extcon\n");
2965                 err = -ENOMEM;
2966                 goto err_del_udc;
2967         }
2968
2969         udc->edev->name = driver_name;
2970         udc->edev->supported_cable = (const char **) tegra_udc_extcon_cable;
2971         err = extcon_dev_register(udc->edev, &pdev->dev);
2972         if (err) {
2973                 dev_err(&pdev->dev, "failed to register extcon device\n");
2974                 kfree(udc->edev);
2975                 udc->edev = NULL;
2976         }
2977
2978         if (udc->support_pmu_vbus && pdata->vbus_extcon_dev_name)
2979                 udc->vbus_extcon_dev =
2980                         extcon_get_extcon_dev(pdata->vbus_extcon_dev_name);
2981
2982         /* Create work for controlling clocks to the phy if otg is disabled */
2983         INIT_WORK(&udc->irq_work, tegra_udc_irq_work);
2984         INIT_DELAYED_WORK(&udc->non_std_charger_work,
2985                         tegra_udc_non_std_charger_detect_work);
2986         INIT_WORK(&udc->current_work, tegra_udc_set_current_limit_work);
2987         /* Get the regulator for drawing the vbus current in udc driver */
2988         udc->vbus_reg = regulator_get(&pdev->dev, "usb_bat_chg");
2989         if (IS_ERR(udc->vbus_reg)) {
2990                 dev_info(&pdev->dev,
2991                         "usb_bat_chg regulator not registered:"
2992                                 " USB charging will not be enabled\n");
2993                 udc->vbus_reg = NULL;
2994         }
2995
2996         if (pdata->port_otg)
2997                 udc->transceiver = usb_get_phy(USB_PHY_TYPE_USB2);
2998
2999         if (IS_ERR_OR_NULL(udc->transceiver))
3000                 udc->transceiver = NULL;
3001
3002         if (udc->transceiver) {
3003                 dr_controller_stop(udc);
3004                 dr_controller_reset(udc);
3005                 tegra_usb_phy_power_off(udc->phy);
3006                 udc->vbus_active = 0;
3007                 udc->usb_state = USB_STATE_DEFAULT;
3008                 otg_set_peripheral(udc->transceiver->otg, &udc->gadget);
3009         }
3010
3011         DBG("%s(%d) END\n", __func__, __LINE__);
3012         return 0;
3013
3014 err_del_udc:
3015         dma_pool_destroy(udc->td_pool);
3016
3017 err_phy:
3018         usb_phy_shutdown(get_usb_phy(udc->phy));
3019
3020 err_irq:
3021         free_irq(udc->irq, udc);
3022
3023 err_iounmap:
3024         iounmap(udc->regs);
3025
3026 err_rel_mem_region:
3027         release_mem_region(res->start, res->end - res->start + 1);
3028
3029 err_kfree:
3030         kfree(udc);
3031
3032         return err;
3033 }
3034
3035 /* Driver removal function
3036  * Free resources and finish pending transactions
3037  */
3038 static int __exit tegra_udc_remove(struct platform_device *pdev)
3039 {
3040         struct tegra_udc *udc = platform_get_drvdata(pdev);
3041         struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
3042
3043         DECLARE_COMPLETION(done);
3044
3045         if (!udc)
3046                 return -ENODEV;
3047         if (!res) {
3048                 ERR("resource request failed\n");
3049                 return -ENODEV;
3050         }
3051
3052         if (udc->edev != NULL) {
3053                 extcon_dev_unregister(udc->edev);
3054                 kfree(udc->edev);
3055         }
3056
3057         usb_del_gadget_udc(&udc->gadget);
3058         udc->done = &done;
3059
3060         cancel_delayed_work(&udc->non_std_charger_work);
3061         cancel_work_sync(&udc->irq_work);
3062 #ifdef CONFIG_TEGRA_GADGET_BOOST_CPU_FREQ
3063         cancel_work_sync(&udc->boost_cpufreq_work);
3064         pm_qos_remove_request(&boost_cpu_freq_req);
3065         del_timer(&boost_timer);
3066 #endif
3067
3068         if (udc->vbus_reg)
3069                 regulator_put(udc->vbus_reg);
3070
3071         if (udc->transceiver)
3072                 otg_set_peripheral(udc->transceiver->otg, NULL);
3073
3074         /* Free allocated memory */
3075         dma_free_coherent(&pdev->dev, STATUS_BUFFER_SIZE,
3076                                 udc->status_req->req.buf,
3077                                 udc->status_req->req.dma);
3078         kfree(udc->status_req);
3079         kfree(udc->eps);
3080
3081         dma_pool_destroy(udc->td_pool);
3082         free_irq(udc->irq, udc);
3083         iounmap(udc->regs);
3084         release_mem_region(res->start, res->end - res->start + 1);
3085
3086         mutex_destroy(&udc->sync_lock);
3087         /* Free udc -- wait for the release() finished */
3088         wait_for_completion(&done);
3089
3090         return 0;
3091 }
3092
3093 static int tegra_udc_suspend(struct platform_device *pdev, pm_message_t state)
3094 {
3095         struct tegra_udc *udc = platform_get_drvdata(pdev);
3096         unsigned long flags;
3097         u32 temp;
3098
3099         int err = 0;
3100         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
3101
3102         if (udc->support_pmu_vbus) {
3103                 if (extcon_get_cable_state(udc->vbus_extcon_dev, "USB"))
3104                         udc->vbus_in_lp0 = true;
3105         } else {
3106                 temp = udc_readl(udc, VBUS_WAKEUP_REG_OFFSET);
3107                 if (temp & USB_SYS_VBUS_STATUS)
3108                         udc->vbus_in_lp0 = true;
3109         }
3110         udc->connect_type_lp0 = udc->connect_type;
3111
3112         /* If the controller is in otg mode, return */
3113         if (udc->transceiver)
3114                 return 0;
3115
3116         if (udc->irq) {
3117                 err = enable_irq_wake(udc->irq);
3118                 if (err < 0)
3119                         dev_err(&pdev->dev,
3120                         "Couldn't enable USB udc mode wakeup,"
3121                         " irq=%d, error=%d\n", udc->irq, err);
3122         }
3123
3124         if (udc->vbus_active) {
3125                 spin_lock_irqsave(&udc->lock, flags);
3126                 /* Reset all internal Queues and inform client driver */
3127                 reset_queues(udc);
3128                 udc->vbus_active = 0;
3129                 udc->usb_state = USB_STATE_DEFAULT;
3130                 spin_unlock_irqrestore(&udc->lock, flags);
3131         }
3132         /* Stop the controller and turn off the clocks */
3133         dr_controller_stop(udc);
3134
3135         tegra_usb_phy_power_off(udc->phy);
3136
3137         DBG("%s(%d) END\n", __func__, __LINE__);
3138         return 0;
3139 }
3140
3141 static int tegra_udc_resume(struct platform_device *pdev)
3142 {
3143         struct tegra_udc *udc = platform_get_drvdata(pdev);
3144         u32 temp;
3145
3146         int err = 0;
3147         DBG("%s(%d) BEGIN\n", __func__, __LINE__);
3148
3149         udc->vbus_in_lp0 = false;
3150
3151         /* Set Current limit to 0 if charger is disconnected in LP0 */
3152         if (udc->vbus_reg != NULL) {
3153                 if (udc->support_pmu_vbus) {
3154                         if ((udc->connect_type_lp0 != CONNECT_TYPE_NONE) &&
3155                         !extcon_get_cable_state(udc->vbus_extcon_dev, "USB")) {
3156                                 tegra_udc_set_extcon_state(udc);
3157                                 udc->connect_type_lp0 = CONNECT_TYPE_NONE;
3158                                 regulator_set_current_limit(udc->vbus_reg,
3159                                                                          0, 0);
3160                         }
3161                 } else {
3162                         temp = udc_readl(udc, VBUS_WAKEUP_REG_OFFSET);
3163                         if ((udc->connect_type_lp0 != CONNECT_TYPE_NONE) &&
3164                                         !(temp & USB_SYS_VBUS_STATUS)) {
3165                                 tegra_udc_set_extcon_state(udc);
3166                                 udc->connect_type_lp0 = CONNECT_TYPE_NONE;
3167                                 regulator_set_current_limit(udc->vbus_reg,
3168                                                                          0, 0);
3169                         }
3170                 }
3171         }
3172
3173         if (udc->transceiver)
3174                 return 0;
3175
3176         if (udc->irq) {
3177                 err = disable_irq_wake(udc->irq);
3178                 if (err < 0)
3179                         dev_err(&pdev->dev,
3180                                 "Couldn't disable USB udc mode wakeup, "
3181                                 "irq=%d, error=%d\n", udc->irq, err);
3182         }
3183
3184         tegra_usb_phy_power_on(udc->phy);
3185         tegra_udc_restart(udc);
3186
3187         /* Power down the phy if cable is not connected */
3188         if (!vbus_enabled(udc)) {
3189                 udc->vbus_active = 0;
3190                 tegra_usb_phy_power_off(udc->phy);
3191         }
3192
3193         DBG("%s(%d) END\n", __func__, __LINE__);
3194         return 0;
3195 }
3196
3197
3198 static struct platform_driver tegra_udc_driver = {
3199         .remove  = __exit_p(tegra_udc_remove),
3200         .suspend = tegra_udc_suspend,
3201         .resume  = tegra_udc_resume,
3202         .driver  = {
3203                 .name = (char *)driver_name,
3204                 .owner = THIS_MODULE,
3205         },
3206 };
3207
3208 static int __init udc_init(void)
3209 {
3210         printk(KERN_INFO "%s (%s)\n", driver_desc, DRIVER_VERSION);
3211         return platform_driver_probe(&tegra_udc_driver, tegra_udc_probe);
3212 }
3213 module_init(udc_init);
3214 static void __exit udc_exit(void)
3215 {
3216         platform_driver_unregister(&tegra_udc_driver);
3217         printk(KERN_WARNING "%s unregistered\n", driver_desc);
3218 }
3219 module_exit(udc_exit);
3220
3221 MODULE_DESCRIPTION(DRIVER_DESC);
3222 MODULE_AUTHOR(DRIVER_AUTHOR);
3223 MODULE_LICENSE("GPL");
3224 MODULE_ALIAS("platform:tegra-udc");