Merge branch 'release-2.6.27' of git://git.kernel.org/pub/scm/linux/kernel/git/ak...
[pandora-kernel.git] / drivers / usb / gadget / at91_udc.c
1 /*
2  * at91_udc -- driver for at91-series USB peripheral controller
3  *
4  * Copyright (C) 2004 by Thomas Rathbone
5  * Copyright (C) 2005 by HP Labs
6  * Copyright (C) 2005 by David Brownell
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA  02111-1307, USA.
22  */
23
24 #undef  VERBOSE_DEBUG
25 #undef  PACKET_TRACE
26
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/platform_device.h>
30 #include <linux/delay.h>
31 #include <linux/ioport.h>
32 #include <linux/slab.h>
33 #include <linux/errno.h>
34 #include <linux/init.h>
35 #include <linux/list.h>
36 #include <linux/interrupt.h>
37 #include <linux/proc_fs.h>
38 #include <linux/clk.h>
39 #include <linux/usb/ch9.h>
40 #include <linux/usb/gadget.h>
41
42 #include <asm/byteorder.h>
43 #include <asm/hardware.h>
44 #include <asm/io.h>
45 #include <asm/irq.h>
46 #include <asm/system.h>
47 #include <asm/mach-types.h>
48 #include <asm/gpio.h>
49
50 #include <asm/arch/board.h>
51 #include <asm/arch/cpu.h>
52 #include <asm/arch/at91sam9261_matrix.h>
53
54 #include "at91_udc.h"
55
56
57 /*
58  * This controller is simple and PIO-only.  It's used in many AT91-series
59  * full speed USB controllers, including the at91rm9200 (arm920T, with MMU),
60  * at91sam926x (arm926ejs, with MMU), and several no-mmu versions.
61  *
62  * This driver expects the board has been wired with two GPIOs suppporting
63  * a VBUS sensing IRQ, and a D+ pullup.  (They may be omitted, but the
64  * testing hasn't covered such cases.)
65  *
66  * The pullup is most important (so it's integrated on sam926x parts).  It
67  * provides software control over whether the host enumerates the device.
68  *
69  * The VBUS sensing helps during enumeration, and allows both USB clocks
70  * (and the transceiver) to stay gated off until they're necessary, saving
71  * power.  During USB suspend, the 48 MHz clock is gated off in hardware;
72  * it may also be gated off by software during some Linux sleep states.
73  */
74
75 #define DRIVER_VERSION  "3 May 2006"
76
77 static const char driver_name [] = "at91_udc";
78 static const char ep0name[] = "ep0";
79
80
81 #define at91_udp_read(dev, reg) \
82         __raw_readl((dev)->udp_baseaddr + (reg))
83 #define at91_udp_write(dev, reg, val) \
84         __raw_writel((val), (dev)->udp_baseaddr + (reg))
85
86 /*-------------------------------------------------------------------------*/
87
88 #ifdef CONFIG_USB_GADGET_DEBUG_FILES
89
90 #include <linux/seq_file.h>
91
92 static const char debug_filename[] = "driver/udc";
93
94 #define FOURBITS "%s%s%s%s"
95 #define EIGHTBITS FOURBITS FOURBITS
96
97 static void proc_ep_show(struct seq_file *s, struct at91_ep *ep)
98 {
99         static char             *types[] = {
100                 "control", "out-iso", "out-bulk", "out-int",
101                 "BOGUS",   "in-iso",  "in-bulk",  "in-int"};
102
103         u32                     csr;
104         struct at91_request     *req;
105         unsigned long   flags;
106
107         local_irq_save(flags);
108
109         csr = __raw_readl(ep->creg);
110
111         /* NOTE:  not collecting per-endpoint irq statistics... */
112
113         seq_printf(s, "\n");
114         seq_printf(s, "%s, maxpacket %d %s%s %s%s\n",
115                         ep->ep.name, ep->ep.maxpacket,
116                         ep->is_in ? "in" : "out",
117                         ep->is_iso ? " iso" : "",
118                         ep->is_pingpong
119                                 ? (ep->fifo_bank ? "pong" : "ping")
120                                 : "",
121                         ep->stopped ? " stopped" : "");
122         seq_printf(s, "csr %08x rxbytes=%d %s %s %s" EIGHTBITS "\n",
123                 csr,
124                 (csr & 0x07ff0000) >> 16,
125                 (csr & (1 << 15)) ? "enabled" : "disabled",
126                 (csr & (1 << 11)) ? "DATA1" : "DATA0",
127                 types[(csr & 0x700) >> 8],
128
129                 /* iff type is control then print current direction */
130                 (!(csr & 0x700))
131                         ? ((csr & (1 << 7)) ? " IN" : " OUT")
132                         : "",
133                 (csr & (1 << 6)) ? " rxdatabk1" : "",
134                 (csr & (1 << 5)) ? " forcestall" : "",
135                 (csr & (1 << 4)) ? " txpktrdy" : "",
136
137                 (csr & (1 << 3)) ? " stallsent" : "",
138                 (csr & (1 << 2)) ? " rxsetup" : "",
139                 (csr & (1 << 1)) ? " rxdatabk0" : "",
140                 (csr & (1 << 0)) ? " txcomp" : "");
141         if (list_empty (&ep->queue))
142                 seq_printf(s, "\t(queue empty)\n");
143
144         else list_for_each_entry (req, &ep->queue, queue) {
145                 unsigned        length = req->req.actual;
146
147                 seq_printf(s, "\treq %p len %d/%d buf %p\n",
148                                 &req->req, length,
149                                 req->req.length, req->req.buf);
150         }
151         local_irq_restore(flags);
152 }
153
154 static void proc_irq_show(struct seq_file *s, const char *label, u32 mask)
155 {
156         int i;
157
158         seq_printf(s, "%s %04x:%s%s" FOURBITS, label, mask,
159                 (mask & (1 << 13)) ? " wakeup" : "",
160                 (mask & (1 << 12)) ? " endbusres" : "",
161
162                 (mask & (1 << 11)) ? " sofint" : "",
163                 (mask & (1 << 10)) ? " extrsm" : "",
164                 (mask & (1 << 9)) ? " rxrsm" : "",
165                 (mask & (1 << 8)) ? " rxsusp" : "");
166         for (i = 0; i < 8; i++) {
167                 if (mask & (1 << i))
168                         seq_printf(s, " ep%d", i);
169         }
170         seq_printf(s, "\n");
171 }
172
173 static int proc_udc_show(struct seq_file *s, void *unused)
174 {
175         struct at91_udc *udc = s->private;
176         struct at91_ep  *ep;
177         u32             tmp;
178
179         seq_printf(s, "%s: version %s\n", driver_name, DRIVER_VERSION);
180
181         seq_printf(s, "vbus %s, pullup %s, %s powered%s, gadget %s\n\n",
182                 udc->vbus ? "present" : "off",
183                 udc->enabled
184                         ? (udc->vbus ? "active" : "enabled")
185                         : "disabled",
186                 udc->selfpowered ? "self" : "VBUS",
187                 udc->suspended ? ", suspended" : "",
188                 udc->driver ? udc->driver->driver.name : "(none)");
189
190         /* don't access registers when interface isn't clocked */
191         if (!udc->clocked) {
192                 seq_printf(s, "(not clocked)\n");
193                 return 0;
194         }
195
196         tmp = at91_udp_read(udc, AT91_UDP_FRM_NUM);
197         seq_printf(s, "frame %05x:%s%s frame=%d\n", tmp,
198                 (tmp & AT91_UDP_FRM_OK) ? " ok" : "",
199                 (tmp & AT91_UDP_FRM_ERR) ? " err" : "",
200                 (tmp & AT91_UDP_NUM));
201
202         tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT);
203         seq_printf(s, "glbstate %02x:%s" FOURBITS "\n", tmp,
204                 (tmp & AT91_UDP_RMWUPE) ? " rmwupe" : "",
205                 (tmp & AT91_UDP_RSMINPR) ? " rsminpr" : "",
206                 (tmp & AT91_UDP_ESR) ? " esr" : "",
207                 (tmp & AT91_UDP_CONFG) ? " confg" : "",
208                 (tmp & AT91_UDP_FADDEN) ? " fadden" : "");
209
210         tmp = at91_udp_read(udc, AT91_UDP_FADDR);
211         seq_printf(s, "faddr   %03x:%s fadd=%d\n", tmp,
212                 (tmp & AT91_UDP_FEN) ? " fen" : "",
213                 (tmp & AT91_UDP_FADD));
214
215         proc_irq_show(s, "imr   ", at91_udp_read(udc, AT91_UDP_IMR));
216         proc_irq_show(s, "isr   ", at91_udp_read(udc, AT91_UDP_ISR));
217
218         if (udc->enabled && udc->vbus) {
219                 proc_ep_show(s, &udc->ep[0]);
220                 list_for_each_entry (ep, &udc->gadget.ep_list, ep.ep_list) {
221                         if (ep->desc)
222                                 proc_ep_show(s, ep);
223                 }
224         }
225         return 0;
226 }
227
228 static int proc_udc_open(struct inode *inode, struct file *file)
229 {
230         return single_open(file, proc_udc_show, PDE(inode)->data);
231 }
232
233 static const struct file_operations proc_ops = {
234         .owner          = THIS_MODULE,
235         .open           = proc_udc_open,
236         .read           = seq_read,
237         .llseek         = seq_lseek,
238         .release        = single_release,
239 };
240
241 static void create_debug_file(struct at91_udc *udc)
242 {
243         udc->pde = proc_create_data(debug_filename, 0, NULL, &proc_ops, udc);
244 }
245
246 static void remove_debug_file(struct at91_udc *udc)
247 {
248         if (udc->pde)
249                 remove_proc_entry(debug_filename, NULL);
250 }
251
252 #else
253
254 static inline void create_debug_file(struct at91_udc *udc) {}
255 static inline void remove_debug_file(struct at91_udc *udc) {}
256
257 #endif
258
259
260 /*-------------------------------------------------------------------------*/
261
262 static void done(struct at91_ep *ep, struct at91_request *req, int status)
263 {
264         unsigned        stopped = ep->stopped;
265         struct at91_udc *udc = ep->udc;
266
267         list_del_init(&req->queue);
268         if (req->req.status == -EINPROGRESS)
269                 req->req.status = status;
270         else
271                 status = req->req.status;
272         if (status && status != -ESHUTDOWN)
273                 VDBG("%s done %p, status %d\n", ep->ep.name, req, status);
274
275         ep->stopped = 1;
276         req->req.complete(&ep->ep, &req->req);
277         ep->stopped = stopped;
278
279         /* ep0 is always ready; other endpoints need a non-empty queue */
280         if (list_empty(&ep->queue) && ep->int_mask != (1 << 0))
281                 at91_udp_write(udc, AT91_UDP_IDR, ep->int_mask);
282 }
283
284 /*-------------------------------------------------------------------------*/
285
286 /* bits indicating OUT fifo has data ready */
287 #define RX_DATA_READY   (AT91_UDP_RX_DATA_BK0 | AT91_UDP_RX_DATA_BK1)
288
289 /*
290  * Endpoint FIFO CSR bits have a mix of bits, making it unsafe to just write
291  * back most of the value you just read (because of side effects, including
292  * bits that may change after reading and before writing).
293  *
294  * Except when changing a specific bit, always write values which:
295  *  - clear SET_FX bits (setting them could change something)
296  *  - set CLR_FX bits (clearing them could change something)
297  *
298  * There are also state bits like FORCESTALL, EPEDS, DIR, and EPTYPE
299  * that shouldn't normally be changed.
300  *
301  * NOTE at91sam9260 docs mention synch between UDPCK and MCK clock domains,
302  * implying a need to wait for one write to complete (test relevant bits)
303  * before starting the next write.  This shouldn't be an issue given how
304  * infrequently we write, except maybe for write-then-read idioms.
305  */
306 #define SET_FX  (AT91_UDP_TXPKTRDY)
307 #define CLR_FX  (RX_DATA_READY | AT91_UDP_RXSETUP \
308                 | AT91_UDP_STALLSENT | AT91_UDP_TXCOMP)
309
310 /* pull OUT packet data from the endpoint's fifo */
311 static int read_fifo (struct at91_ep *ep, struct at91_request *req)
312 {
313         u32 __iomem     *creg = ep->creg;
314         u8 __iomem      *dreg = ep->creg + (AT91_UDP_FDR(0) - AT91_UDP_CSR(0));
315         u32             csr;
316         u8              *buf;
317         unsigned int    count, bufferspace, is_done;
318
319         buf = req->req.buf + req->req.actual;
320         bufferspace = req->req.length - req->req.actual;
321
322         /*
323          * there might be nothing to read if ep_queue() calls us,
324          * or if we already emptied both pingpong buffers
325          */
326 rescan:
327         csr = __raw_readl(creg);
328         if ((csr & RX_DATA_READY) == 0)
329                 return 0;
330
331         count = (csr & AT91_UDP_RXBYTECNT) >> 16;
332         if (count > ep->ep.maxpacket)
333                 count = ep->ep.maxpacket;
334         if (count > bufferspace) {
335                 DBG("%s buffer overflow\n", ep->ep.name);
336                 req->req.status = -EOVERFLOW;
337                 count = bufferspace;
338         }
339         __raw_readsb(dreg, buf, count);
340
341         /* release and swap pingpong mem bank */
342         csr |= CLR_FX;
343         if (ep->is_pingpong) {
344                 if (ep->fifo_bank == 0) {
345                         csr &= ~(SET_FX | AT91_UDP_RX_DATA_BK0);
346                         ep->fifo_bank = 1;
347                 } else {
348                         csr &= ~(SET_FX | AT91_UDP_RX_DATA_BK1);
349                         ep->fifo_bank = 0;
350                 }
351         } else
352                 csr &= ~(SET_FX | AT91_UDP_RX_DATA_BK0);
353         __raw_writel(csr, creg);
354
355         req->req.actual += count;
356         is_done = (count < ep->ep.maxpacket);
357         if (count == bufferspace)
358                 is_done = 1;
359
360         PACKET("%s %p out/%d%s\n", ep->ep.name, &req->req, count,
361                         is_done ? " (done)" : "");
362
363         /*
364          * avoid extra trips through IRQ logic for packets already in
365          * the fifo ... maybe preventing an extra (expensive) OUT-NAK
366          */
367         if (is_done)
368                 done(ep, req, 0);
369         else if (ep->is_pingpong) {
370                 bufferspace -= count;
371                 buf += count;
372                 goto rescan;
373         }
374
375         return is_done;
376 }
377
378 /* load fifo for an IN packet */
379 static int write_fifo(struct at91_ep *ep, struct at91_request *req)
380 {
381         u32 __iomem     *creg = ep->creg;
382         u32             csr = __raw_readl(creg);
383         u8 __iomem      *dreg = ep->creg + (AT91_UDP_FDR(0) - AT91_UDP_CSR(0));
384         unsigned        total, count, is_last;
385         u8              *buf;
386
387         /*
388          * TODO: allow for writing two packets to the fifo ... that'll
389          * reduce the amount of IN-NAKing, but probably won't affect
390          * throughput much.  (Unlike preventing OUT-NAKing!)
391          */
392
393         /*
394          * If ep_queue() calls us, the queue is empty and possibly in
395          * odd states like TXCOMP not yet cleared (we do it, saving at
396          * least one IRQ) or the fifo not yet being free.  Those aren't
397          * issues normally (IRQ handler fast path).
398          */
399         if (unlikely(csr & (AT91_UDP_TXCOMP | AT91_UDP_TXPKTRDY))) {
400                 if (csr & AT91_UDP_TXCOMP) {
401                         csr |= CLR_FX;
402                         csr &= ~(SET_FX | AT91_UDP_TXCOMP);
403                         __raw_writel(csr, creg);
404                         csr = __raw_readl(creg);
405                 }
406                 if (csr & AT91_UDP_TXPKTRDY)
407                         return 0;
408         }
409
410         buf = req->req.buf + req->req.actual;
411         prefetch(buf);
412         total = req->req.length - req->req.actual;
413         if (ep->ep.maxpacket < total) {
414                 count = ep->ep.maxpacket;
415                 is_last = 0;
416         } else {
417                 count = total;
418                 is_last = (count < ep->ep.maxpacket) || !req->req.zero;
419         }
420
421         /*
422          * Write the packet, maybe it's a ZLP.
423          *
424          * NOTE:  incrementing req->actual before we receive the ACK means
425          * gadget driver IN bytecounts can be wrong in fault cases.  That's
426          * fixable with PIO drivers like this one (save "count" here, and
427          * do the increment later on TX irq), but not for most DMA hardware.
428          *
429          * So all gadget drivers must accept that potential error.  Some
430          * hardware supports precise fifo status reporting, letting them
431          * recover when the actual bytecount matters (e.g. for USB Test
432          * and Measurement Class devices).
433          */
434         __raw_writesb(dreg, buf, count);
435         csr &= ~SET_FX;
436         csr |= CLR_FX | AT91_UDP_TXPKTRDY;
437         __raw_writel(csr, creg);
438         req->req.actual += count;
439
440         PACKET("%s %p in/%d%s\n", ep->ep.name, &req->req, count,
441                         is_last ? " (done)" : "");
442         if (is_last)
443                 done(ep, req, 0);
444         return is_last;
445 }
446
447 static void nuke(struct at91_ep *ep, int status)
448 {
449         struct at91_request *req;
450
451         // terminer chaque requete dans la queue
452         ep->stopped = 1;
453         if (list_empty(&ep->queue))
454                 return;
455
456         VDBG("%s %s\n", __func__, ep->ep.name);
457         while (!list_empty(&ep->queue)) {
458                 req = list_entry(ep->queue.next, struct at91_request, queue);
459                 done(ep, req, status);
460         }
461 }
462
463 /*-------------------------------------------------------------------------*/
464
465 static int at91_ep_enable(struct usb_ep *_ep,
466                                 const struct usb_endpoint_descriptor *desc)
467 {
468         struct at91_ep  *ep = container_of(_ep, struct at91_ep, ep);
469         struct at91_udc *dev = ep->udc;
470         u16             maxpacket;
471         u32             tmp;
472         unsigned long   flags;
473
474         if (!_ep || !ep
475                         || !desc || ep->desc
476                         || _ep->name == ep0name
477                         || desc->bDescriptorType != USB_DT_ENDPOINT
478                         || (maxpacket = le16_to_cpu(desc->wMaxPacketSize)) == 0
479                         || maxpacket > ep->maxpacket) {
480                 DBG("bad ep or descriptor\n");
481                 return -EINVAL;
482         }
483
484         if (!dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN) {
485                 DBG("bogus device state\n");
486                 return -ESHUTDOWN;
487         }
488
489         tmp = desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
490         switch (tmp) {
491         case USB_ENDPOINT_XFER_CONTROL:
492                 DBG("only one control endpoint\n");
493                 return -EINVAL;
494         case USB_ENDPOINT_XFER_INT:
495                 if (maxpacket > 64)
496                         goto bogus_max;
497                 break;
498         case USB_ENDPOINT_XFER_BULK:
499                 switch (maxpacket) {
500                 case 8:
501                 case 16:
502                 case 32:
503                 case 64:
504                         goto ok;
505                 }
506 bogus_max:
507                 DBG("bogus maxpacket %d\n", maxpacket);
508                 return -EINVAL;
509         case USB_ENDPOINT_XFER_ISOC:
510                 if (!ep->is_pingpong) {
511                         DBG("iso requires double buffering\n");
512                         return -EINVAL;
513                 }
514                 break;
515         }
516
517 ok:
518         local_irq_save(flags);
519
520         /* initialize endpoint to match this descriptor */
521         ep->is_in = (desc->bEndpointAddress & USB_DIR_IN) != 0;
522         ep->is_iso = (tmp == USB_ENDPOINT_XFER_ISOC);
523         ep->stopped = 0;
524         if (ep->is_in)
525                 tmp |= 0x04;
526         tmp <<= 8;
527         tmp |= AT91_UDP_EPEDS;
528         __raw_writel(tmp, ep->creg);
529
530         ep->desc = desc;
531         ep->ep.maxpacket = maxpacket;
532
533         /*
534          * reset/init endpoint fifo.  NOTE:  leaves fifo_bank alone,
535          * since endpoint resets don't reset hw pingpong state.
536          */
537         at91_udp_write(dev, AT91_UDP_RST_EP, ep->int_mask);
538         at91_udp_write(dev, AT91_UDP_RST_EP, 0);
539
540         local_irq_restore(flags);
541         return 0;
542 }
543
544 static int at91_ep_disable (struct usb_ep * _ep)
545 {
546         struct at91_ep  *ep = container_of(_ep, struct at91_ep, ep);
547         struct at91_udc *udc = ep->udc;
548         unsigned long   flags;
549
550         if (ep == &ep->udc->ep[0])
551                 return -EINVAL;
552
553         local_irq_save(flags);
554
555         nuke(ep, -ESHUTDOWN);
556
557         /* restore the endpoint's pristine config */
558         ep->desc = NULL;
559         ep->ep.maxpacket = ep->maxpacket;
560
561         /* reset fifos and endpoint */
562         if (ep->udc->clocked) {
563                 at91_udp_write(udc, AT91_UDP_RST_EP, ep->int_mask);
564                 at91_udp_write(udc, AT91_UDP_RST_EP, 0);
565                 __raw_writel(0, ep->creg);
566         }
567
568         local_irq_restore(flags);
569         return 0;
570 }
571
572 /*
573  * this is a PIO-only driver, so there's nothing
574  * interesting for request or buffer allocation.
575  */
576
577 static struct usb_request *
578 at91_ep_alloc_request(struct usb_ep *_ep, gfp_t gfp_flags)
579 {
580         struct at91_request *req;
581
582         req = kzalloc(sizeof (struct at91_request), gfp_flags);
583         if (!req)
584                 return NULL;
585
586         INIT_LIST_HEAD(&req->queue);
587         return &req->req;
588 }
589
590 static void at91_ep_free_request(struct usb_ep *_ep, struct usb_request *_req)
591 {
592         struct at91_request *req;
593
594         req = container_of(_req, struct at91_request, req);
595         BUG_ON(!list_empty(&req->queue));
596         kfree(req);
597 }
598
599 static int at91_ep_queue(struct usb_ep *_ep,
600                         struct usb_request *_req, gfp_t gfp_flags)
601 {
602         struct at91_request     *req;
603         struct at91_ep          *ep;
604         struct at91_udc         *dev;
605         int                     status;
606         unsigned long           flags;
607
608         req = container_of(_req, struct at91_request, req);
609         ep = container_of(_ep, struct at91_ep, ep);
610
611         if (!_req || !_req->complete
612                         || !_req->buf || !list_empty(&req->queue)) {
613                 DBG("invalid request\n");
614                 return -EINVAL;
615         }
616
617         if (!_ep || (!ep->desc && ep->ep.name != ep0name)) {
618                 DBG("invalid ep\n");
619                 return -EINVAL;
620         }
621
622         dev = ep->udc;
623
624         if (!dev || !dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN) {
625                 DBG("invalid device\n");
626                 return -EINVAL;
627         }
628
629         _req->status = -EINPROGRESS;
630         _req->actual = 0;
631
632         local_irq_save(flags);
633
634         /* try to kickstart any empty and idle queue */
635         if (list_empty(&ep->queue) && !ep->stopped) {
636                 int     is_ep0;
637
638                 /*
639                  * If this control request has a non-empty DATA stage, this
640                  * will start that stage.  It works just like a non-control
641                  * request (until the status stage starts, maybe early).
642                  *
643                  * If the data stage is empty, then this starts a successful
644                  * IN/STATUS stage.  (Unsuccessful ones use set_halt.)
645                  */
646                 is_ep0 = (ep->ep.name == ep0name);
647                 if (is_ep0) {
648                         u32     tmp;
649
650                         if (!dev->req_pending) {
651                                 status = -EINVAL;
652                                 goto done;
653                         }
654
655                         /*
656                          * defer changing CONFG until after the gadget driver
657                          * reconfigures the endpoints.
658                          */
659                         if (dev->wait_for_config_ack) {
660                                 tmp = at91_udp_read(dev, AT91_UDP_GLB_STAT);
661                                 tmp ^= AT91_UDP_CONFG;
662                                 VDBG("toggle config\n");
663                                 at91_udp_write(dev, AT91_UDP_GLB_STAT, tmp);
664                         }
665                         if (req->req.length == 0) {
666 ep0_in_status:
667                                 PACKET("ep0 in/status\n");
668                                 status = 0;
669                                 tmp = __raw_readl(ep->creg);
670                                 tmp &= ~SET_FX;
671                                 tmp |= CLR_FX | AT91_UDP_TXPKTRDY;
672                                 __raw_writel(tmp, ep->creg);
673                                 dev->req_pending = 0;
674                                 goto done;
675                         }
676                 }
677
678                 if (ep->is_in)
679                         status = write_fifo(ep, req);
680                 else {
681                         status = read_fifo(ep, req);
682
683                         /* IN/STATUS stage is otherwise triggered by irq */
684                         if (status && is_ep0)
685                                 goto ep0_in_status;
686                 }
687         } else
688                 status = 0;
689
690         if (req && !status) {
691                 list_add_tail (&req->queue, &ep->queue);
692                 at91_udp_write(dev, AT91_UDP_IER, ep->int_mask);
693         }
694 done:
695         local_irq_restore(flags);
696         return (status < 0) ? status : 0;
697 }
698
699 static int at91_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req)
700 {
701         struct at91_ep  *ep;
702         struct at91_request     *req;
703
704         ep = container_of(_ep, struct at91_ep, ep);
705         if (!_ep || ep->ep.name == ep0name)
706                 return -EINVAL;
707
708         /* make sure it's actually queued on this endpoint */
709         list_for_each_entry (req, &ep->queue, queue) {
710                 if (&req->req == _req)
711                         break;
712         }
713         if (&req->req != _req)
714                 return -EINVAL;
715
716         done(ep, req, -ECONNRESET);
717         return 0;
718 }
719
720 static int at91_ep_set_halt(struct usb_ep *_ep, int value)
721 {
722         struct at91_ep  *ep = container_of(_ep, struct at91_ep, ep);
723         struct at91_udc *udc = ep->udc;
724         u32 __iomem     *creg;
725         u32             csr;
726         unsigned long   flags;
727         int             status = 0;
728
729         if (!_ep || ep->is_iso || !ep->udc->clocked)
730                 return -EINVAL;
731
732         creg = ep->creg;
733         local_irq_save(flags);
734
735         csr = __raw_readl(creg);
736
737         /*
738          * fail with still-busy IN endpoints, ensuring correct sequencing
739          * of data tx then stall.  note that the fifo rx bytecount isn't
740          * completely accurate as a tx bytecount.
741          */
742         if (ep->is_in && (!list_empty(&ep->queue) || (csr >> 16) != 0))
743                 status = -EAGAIN;
744         else {
745                 csr |= CLR_FX;
746                 csr &= ~SET_FX;
747                 if (value) {
748                         csr |= AT91_UDP_FORCESTALL;
749                         VDBG("halt %s\n", ep->ep.name);
750                 } else {
751                         at91_udp_write(udc, AT91_UDP_RST_EP, ep->int_mask);
752                         at91_udp_write(udc, AT91_UDP_RST_EP, 0);
753                         csr &= ~AT91_UDP_FORCESTALL;
754                 }
755                 __raw_writel(csr, creg);
756         }
757
758         local_irq_restore(flags);
759         return status;
760 }
761
762 static const struct usb_ep_ops at91_ep_ops = {
763         .enable         = at91_ep_enable,
764         .disable        = at91_ep_disable,
765         .alloc_request  = at91_ep_alloc_request,
766         .free_request   = at91_ep_free_request,
767         .queue          = at91_ep_queue,
768         .dequeue        = at91_ep_dequeue,
769         .set_halt       = at91_ep_set_halt,
770         // there's only imprecise fifo status reporting
771 };
772
773 /*-------------------------------------------------------------------------*/
774
775 static int at91_get_frame(struct usb_gadget *gadget)
776 {
777         struct at91_udc *udc = to_udc(gadget);
778
779         if (!to_udc(gadget)->clocked)
780                 return -EINVAL;
781         return at91_udp_read(udc, AT91_UDP_FRM_NUM) & AT91_UDP_NUM;
782 }
783
784 static int at91_wakeup(struct usb_gadget *gadget)
785 {
786         struct at91_udc *udc = to_udc(gadget);
787         u32             glbstate;
788         int             status = -EINVAL;
789         unsigned long   flags;
790
791         DBG("%s\n", __func__ );
792         local_irq_save(flags);
793
794         if (!udc->clocked || !udc->suspended)
795                 goto done;
796
797         /* NOTE:  some "early versions" handle ESR differently ... */
798
799         glbstate = at91_udp_read(udc, AT91_UDP_GLB_STAT);
800         if (!(glbstate & AT91_UDP_ESR))
801                 goto done;
802         glbstate |= AT91_UDP_ESR;
803         at91_udp_write(udc, AT91_UDP_GLB_STAT, glbstate);
804
805 done:
806         local_irq_restore(flags);
807         return status;
808 }
809
810 /* reinit == restore inital software state */
811 static void udc_reinit(struct at91_udc *udc)
812 {
813         u32 i;
814
815         INIT_LIST_HEAD(&udc->gadget.ep_list);
816         INIT_LIST_HEAD(&udc->gadget.ep0->ep_list);
817
818         for (i = 0; i < NUM_ENDPOINTS; i++) {
819                 struct at91_ep *ep = &udc->ep[i];
820
821                 if (i != 0)
822                         list_add_tail(&ep->ep.ep_list, &udc->gadget.ep_list);
823                 ep->desc = NULL;
824                 ep->stopped = 0;
825                 ep->fifo_bank = 0;
826                 ep->ep.maxpacket = ep->maxpacket;
827                 ep->creg = (void __iomem *) udc->udp_baseaddr + AT91_UDP_CSR(i);
828                 // initialiser une queue par endpoint
829                 INIT_LIST_HEAD(&ep->queue);
830         }
831 }
832
833 static void stop_activity(struct at91_udc *udc)
834 {
835         struct usb_gadget_driver *driver = udc->driver;
836         int i;
837
838         if (udc->gadget.speed == USB_SPEED_UNKNOWN)
839                 driver = NULL;
840         udc->gadget.speed = USB_SPEED_UNKNOWN;
841         udc->suspended = 0;
842
843         for (i = 0; i < NUM_ENDPOINTS; i++) {
844                 struct at91_ep *ep = &udc->ep[i];
845                 ep->stopped = 1;
846                 nuke(ep, -ESHUTDOWN);
847         }
848         if (driver)
849                 driver->disconnect(&udc->gadget);
850
851         udc_reinit(udc);
852 }
853
854 static void clk_on(struct at91_udc *udc)
855 {
856         if (udc->clocked)
857                 return;
858         udc->clocked = 1;
859         clk_enable(udc->iclk);
860         clk_enable(udc->fclk);
861 }
862
863 static void clk_off(struct at91_udc *udc)
864 {
865         if (!udc->clocked)
866                 return;
867         udc->clocked = 0;
868         udc->gadget.speed = USB_SPEED_UNKNOWN;
869         clk_disable(udc->fclk);
870         clk_disable(udc->iclk);
871 }
872
873 /*
874  * activate/deactivate link with host; minimize power usage for
875  * inactive links by cutting clocks and transceiver power.
876  */
877 static void pullup(struct at91_udc *udc, int is_on)
878 {
879         int     active = !udc->board.pullup_active_low;
880
881         if (!udc->enabled || !udc->vbus)
882                 is_on = 0;
883         DBG("%sactive\n", is_on ? "" : "in");
884
885         if (is_on) {
886                 clk_on(udc);
887                 at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_RXRSM);
888                 at91_udp_write(udc, AT91_UDP_TXVC, 0);
889                 if (cpu_is_at91rm9200())
890                         gpio_set_value(udc->board.pullup_pin, active);
891                 else if (cpu_is_at91sam9260() || cpu_is_at91sam9263() || cpu_is_at91sam9g20()) {
892                         u32     txvc = at91_udp_read(udc, AT91_UDP_TXVC);
893
894                         txvc |= AT91_UDP_TXVC_PUON;
895                         at91_udp_write(udc, AT91_UDP_TXVC, txvc);
896                 } else if (cpu_is_at91sam9261()) {
897                         u32     usbpucr;
898
899                         usbpucr = at91_sys_read(AT91_MATRIX_USBPUCR);
900                         usbpucr |= AT91_MATRIX_USBPUCR_PUON;
901                         at91_sys_write(AT91_MATRIX_USBPUCR, usbpucr);
902                 }
903         } else {
904                 stop_activity(udc);
905                 at91_udp_write(udc, AT91_UDP_IDR, AT91_UDP_RXRSM);
906                 at91_udp_write(udc, AT91_UDP_TXVC, AT91_UDP_TXVC_TXVDIS);
907                 if (cpu_is_at91rm9200())
908                         gpio_set_value(udc->board.pullup_pin, !active);
909                 else if (cpu_is_at91sam9260() || cpu_is_at91sam9263() || cpu_is_at91sam9g20()) {
910                         u32     txvc = at91_udp_read(udc, AT91_UDP_TXVC);
911
912                         txvc &= ~AT91_UDP_TXVC_PUON;
913                         at91_udp_write(udc, AT91_UDP_TXVC, txvc);
914                 } else if (cpu_is_at91sam9261()) {
915                         u32     usbpucr;
916
917                         usbpucr = at91_sys_read(AT91_MATRIX_USBPUCR);
918                         usbpucr &= ~AT91_MATRIX_USBPUCR_PUON;
919                         at91_sys_write(AT91_MATRIX_USBPUCR, usbpucr);
920                 }
921                 clk_off(udc);
922         }
923 }
924
925 /* vbus is here!  turn everything on that's ready */
926 static int at91_vbus_session(struct usb_gadget *gadget, int is_active)
927 {
928         struct at91_udc *udc = to_udc(gadget);
929         unsigned long   flags;
930
931         // VDBG("vbus %s\n", is_active ? "on" : "off");
932         local_irq_save(flags);
933         udc->vbus = (is_active != 0);
934         if (udc->driver)
935                 pullup(udc, is_active);
936         else
937                 pullup(udc, 0);
938         local_irq_restore(flags);
939         return 0;
940 }
941
942 static int at91_pullup(struct usb_gadget *gadget, int is_on)
943 {
944         struct at91_udc *udc = to_udc(gadget);
945         unsigned long   flags;
946
947         local_irq_save(flags);
948         udc->enabled = is_on = !!is_on;
949         pullup(udc, is_on);
950         local_irq_restore(flags);
951         return 0;
952 }
953
954 static int at91_set_selfpowered(struct usb_gadget *gadget, int is_on)
955 {
956         struct at91_udc *udc = to_udc(gadget);
957         unsigned long   flags;
958
959         local_irq_save(flags);
960         udc->selfpowered = (is_on != 0);
961         local_irq_restore(flags);
962         return 0;
963 }
964
965 static const struct usb_gadget_ops at91_udc_ops = {
966         .get_frame              = at91_get_frame,
967         .wakeup                 = at91_wakeup,
968         .set_selfpowered        = at91_set_selfpowered,
969         .vbus_session           = at91_vbus_session,
970         .pullup                 = at91_pullup,
971
972         /*
973          * VBUS-powered devices may also also want to support bigger
974          * power budgets after an appropriate SET_CONFIGURATION.
975          */
976         // .vbus_power          = at91_vbus_power,
977 };
978
979 /*-------------------------------------------------------------------------*/
980
981 static int handle_ep(struct at91_ep *ep)
982 {
983         struct at91_request     *req;
984         u32 __iomem             *creg = ep->creg;
985         u32                     csr = __raw_readl(creg);
986
987         if (!list_empty(&ep->queue))
988                 req = list_entry(ep->queue.next,
989                         struct at91_request, queue);
990         else
991                 req = NULL;
992
993         if (ep->is_in) {
994                 if (csr & (AT91_UDP_STALLSENT | AT91_UDP_TXCOMP)) {
995                         csr |= CLR_FX;
996                         csr &= ~(SET_FX | AT91_UDP_STALLSENT | AT91_UDP_TXCOMP);
997                         __raw_writel(csr, creg);
998                 }
999                 if (req)
1000                         return write_fifo(ep, req);
1001
1002         } else {
1003                 if (csr & AT91_UDP_STALLSENT) {
1004                         /* STALLSENT bit == ISOERR */
1005                         if (ep->is_iso && req)
1006                                 req->req.status = -EILSEQ;
1007                         csr |= CLR_FX;
1008                         csr &= ~(SET_FX | AT91_UDP_STALLSENT);
1009                         __raw_writel(csr, creg);
1010                         csr = __raw_readl(creg);
1011                 }
1012                 if (req && (csr & RX_DATA_READY))
1013                         return read_fifo(ep, req);
1014         }
1015         return 0;
1016 }
1017
1018 union setup {
1019         u8                      raw[8];
1020         struct usb_ctrlrequest  r;
1021 };
1022
1023 static void handle_setup(struct at91_udc *udc, struct at91_ep *ep, u32 csr)
1024 {
1025         u32 __iomem     *creg = ep->creg;
1026         u8 __iomem      *dreg = ep->creg + (AT91_UDP_FDR(0) - AT91_UDP_CSR(0));
1027         unsigned        rxcount, i = 0;
1028         u32             tmp;
1029         union setup     pkt;
1030         int             status = 0;
1031
1032         /* read and ack SETUP; hard-fail for bogus packets */
1033         rxcount = (csr & AT91_UDP_RXBYTECNT) >> 16;
1034         if (likely(rxcount == 8)) {
1035                 while (rxcount--)
1036                         pkt.raw[i++] = __raw_readb(dreg);
1037                 if (pkt.r.bRequestType & USB_DIR_IN) {
1038                         csr |= AT91_UDP_DIR;
1039                         ep->is_in = 1;
1040                 } else {
1041                         csr &= ~AT91_UDP_DIR;
1042                         ep->is_in = 0;
1043                 }
1044         } else {
1045                 // REVISIT this happens sometimes under load; why??
1046                 ERR("SETUP len %d, csr %08x\n", rxcount, csr);
1047                 status = -EINVAL;
1048         }
1049         csr |= CLR_FX;
1050         csr &= ~(SET_FX | AT91_UDP_RXSETUP);
1051         __raw_writel(csr, creg);
1052         udc->wait_for_addr_ack = 0;
1053         udc->wait_for_config_ack = 0;
1054         ep->stopped = 0;
1055         if (unlikely(status != 0))
1056                 goto stall;
1057
1058 #define w_index         le16_to_cpu(pkt.r.wIndex)
1059 #define w_value         le16_to_cpu(pkt.r.wValue)
1060 #define w_length        le16_to_cpu(pkt.r.wLength)
1061
1062         VDBG("SETUP %02x.%02x v%04x i%04x l%04x\n",
1063                         pkt.r.bRequestType, pkt.r.bRequest,
1064                         w_value, w_index, w_length);
1065
1066         /*
1067          * A few standard requests get handled here, ones that touch
1068          * hardware ... notably for device and endpoint features.
1069          */
1070         udc->req_pending = 1;
1071         csr = __raw_readl(creg);
1072         csr |= CLR_FX;
1073         csr &= ~SET_FX;
1074         switch ((pkt.r.bRequestType << 8) | pkt.r.bRequest) {
1075
1076         case ((USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
1077                         | USB_REQ_SET_ADDRESS:
1078                 __raw_writel(csr | AT91_UDP_TXPKTRDY, creg);
1079                 udc->addr = w_value;
1080                 udc->wait_for_addr_ack = 1;
1081                 udc->req_pending = 0;
1082                 /* FADDR is set later, when we ack host STATUS */
1083                 return;
1084
1085         case ((USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
1086                         | USB_REQ_SET_CONFIGURATION:
1087                 tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT) & AT91_UDP_CONFG;
1088                 if (pkt.r.wValue)
1089                         udc->wait_for_config_ack = (tmp == 0);
1090                 else
1091                         udc->wait_for_config_ack = (tmp != 0);
1092                 if (udc->wait_for_config_ack)
1093                         VDBG("wait for config\n");
1094                 /* CONFG is toggled later, if gadget driver succeeds */
1095                 break;
1096
1097         /*
1098          * Hosts may set or clear remote wakeup status, and
1099          * devices may report they're VBUS powered.
1100          */
1101         case ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
1102                         | USB_REQ_GET_STATUS:
1103                 tmp = (udc->selfpowered << USB_DEVICE_SELF_POWERED);
1104                 if (at91_udp_read(udc, AT91_UDP_GLB_STAT) & AT91_UDP_ESR)
1105                         tmp |= (1 << USB_DEVICE_REMOTE_WAKEUP);
1106                 PACKET("get device status\n");
1107                 __raw_writeb(tmp, dreg);
1108                 __raw_writeb(0, dreg);
1109                 goto write_in;
1110                 /* then STATUS starts later, automatically */
1111         case ((USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
1112                         | USB_REQ_SET_FEATURE:
1113                 if (w_value != USB_DEVICE_REMOTE_WAKEUP)
1114                         goto stall;
1115                 tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT);
1116                 tmp |= AT91_UDP_ESR;
1117                 at91_udp_write(udc, AT91_UDP_GLB_STAT, tmp);
1118                 goto succeed;
1119         case ((USB_TYPE_STANDARD|USB_RECIP_DEVICE) << 8)
1120                         | USB_REQ_CLEAR_FEATURE:
1121                 if (w_value != USB_DEVICE_REMOTE_WAKEUP)
1122                         goto stall;
1123                 tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT);
1124                 tmp &= ~AT91_UDP_ESR;
1125                 at91_udp_write(udc, AT91_UDP_GLB_STAT, tmp);
1126                 goto succeed;
1127
1128         /*
1129          * Interfaces have no feature settings; this is pretty useless.
1130          * we won't even insist the interface exists...
1131          */
1132         case ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE) << 8)
1133                         | USB_REQ_GET_STATUS:
1134                 PACKET("get interface status\n");
1135                 __raw_writeb(0, dreg);
1136                 __raw_writeb(0, dreg);
1137                 goto write_in;
1138                 /* then STATUS starts later, automatically */
1139         case ((USB_TYPE_STANDARD|USB_RECIP_INTERFACE) << 8)
1140                         | USB_REQ_SET_FEATURE:
1141         case ((USB_TYPE_STANDARD|USB_RECIP_INTERFACE) << 8)
1142                         | USB_REQ_CLEAR_FEATURE:
1143                 goto stall;
1144
1145         /*
1146          * Hosts may clear bulk/intr endpoint halt after the gadget
1147          * driver sets it (not widely used); or set it (for testing)
1148          */
1149         case ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_ENDPOINT) << 8)
1150                         | USB_REQ_GET_STATUS:
1151                 tmp = w_index & USB_ENDPOINT_NUMBER_MASK;
1152                 ep = &udc->ep[tmp];
1153                 if (tmp >= NUM_ENDPOINTS || (tmp && !ep->desc))
1154                         goto stall;
1155
1156                 if (tmp) {
1157                         if ((w_index & USB_DIR_IN)) {
1158                                 if (!ep->is_in)
1159                                         goto stall;
1160                         } else if (ep->is_in)
1161                                 goto stall;
1162                 }
1163                 PACKET("get %s status\n", ep->ep.name);
1164                 if (__raw_readl(ep->creg) & AT91_UDP_FORCESTALL)
1165                         tmp = (1 << USB_ENDPOINT_HALT);
1166                 else
1167                         tmp = 0;
1168                 __raw_writeb(tmp, dreg);
1169                 __raw_writeb(0, dreg);
1170                 goto write_in;
1171                 /* then STATUS starts later, automatically */
1172         case ((USB_TYPE_STANDARD|USB_RECIP_ENDPOINT) << 8)
1173                         | USB_REQ_SET_FEATURE:
1174                 tmp = w_index & USB_ENDPOINT_NUMBER_MASK;
1175                 ep = &udc->ep[tmp];
1176                 if (w_value != USB_ENDPOINT_HALT || tmp >= NUM_ENDPOINTS)
1177                         goto stall;
1178                 if (!ep->desc || ep->is_iso)
1179                         goto stall;
1180                 if ((w_index & USB_DIR_IN)) {
1181                         if (!ep->is_in)
1182                                 goto stall;
1183                 } else if (ep->is_in)
1184                         goto stall;
1185
1186                 tmp = __raw_readl(ep->creg);
1187                 tmp &= ~SET_FX;
1188                 tmp |= CLR_FX | AT91_UDP_FORCESTALL;
1189                 __raw_writel(tmp, ep->creg);
1190                 goto succeed;
1191         case ((USB_TYPE_STANDARD|USB_RECIP_ENDPOINT) << 8)
1192                         | USB_REQ_CLEAR_FEATURE:
1193                 tmp = w_index & USB_ENDPOINT_NUMBER_MASK;
1194                 ep = &udc->ep[tmp];
1195                 if (w_value != USB_ENDPOINT_HALT || tmp >= NUM_ENDPOINTS)
1196                         goto stall;
1197                 if (tmp == 0)
1198                         goto succeed;
1199                 if (!ep->desc || ep->is_iso)
1200                         goto stall;
1201                 if ((w_index & USB_DIR_IN)) {
1202                         if (!ep->is_in)
1203                                 goto stall;
1204                 } else if (ep->is_in)
1205                         goto stall;
1206
1207                 at91_udp_write(udc, AT91_UDP_RST_EP, ep->int_mask);
1208                 at91_udp_write(udc, AT91_UDP_RST_EP, 0);
1209                 tmp = __raw_readl(ep->creg);
1210                 tmp |= CLR_FX;
1211                 tmp &= ~(SET_FX | AT91_UDP_FORCESTALL);
1212                 __raw_writel(tmp, ep->creg);
1213                 if (!list_empty(&ep->queue))
1214                         handle_ep(ep);
1215                 goto succeed;
1216         }
1217
1218 #undef w_value
1219 #undef w_index
1220 #undef w_length
1221
1222         /* pass request up to the gadget driver */
1223         if (udc->driver)
1224                 status = udc->driver->setup(&udc->gadget, &pkt.r);
1225         else
1226                 status = -ENODEV;
1227         if (status < 0) {
1228 stall:
1229                 VDBG("req %02x.%02x protocol STALL; stat %d\n",
1230                                 pkt.r.bRequestType, pkt.r.bRequest, status);
1231                 csr |= AT91_UDP_FORCESTALL;
1232                 __raw_writel(csr, creg);
1233                 udc->req_pending = 0;
1234         }
1235         return;
1236
1237 succeed:
1238         /* immediate successful (IN) STATUS after zero length DATA */
1239         PACKET("ep0 in/status\n");
1240 write_in:
1241         csr |= AT91_UDP_TXPKTRDY;
1242         __raw_writel(csr, creg);
1243         udc->req_pending = 0;
1244         return;
1245 }
1246
1247 static void handle_ep0(struct at91_udc *udc)
1248 {
1249         struct at91_ep          *ep0 = &udc->ep[0];
1250         u32 __iomem             *creg = ep0->creg;
1251         u32                     csr = __raw_readl(creg);
1252         struct at91_request     *req;
1253
1254         if (unlikely(csr & AT91_UDP_STALLSENT)) {
1255                 nuke(ep0, -EPROTO);
1256                 udc->req_pending = 0;
1257                 csr |= CLR_FX;
1258                 csr &= ~(SET_FX | AT91_UDP_STALLSENT | AT91_UDP_FORCESTALL);
1259                 __raw_writel(csr, creg);
1260                 VDBG("ep0 stalled\n");
1261                 csr = __raw_readl(creg);
1262         }
1263         if (csr & AT91_UDP_RXSETUP) {
1264                 nuke(ep0, 0);
1265                 udc->req_pending = 0;
1266                 handle_setup(udc, ep0, csr);
1267                 return;
1268         }
1269
1270         if (list_empty(&ep0->queue))
1271                 req = NULL;
1272         else
1273                 req = list_entry(ep0->queue.next, struct at91_request, queue);
1274
1275         /* host ACKed an IN packet that we sent */
1276         if (csr & AT91_UDP_TXCOMP) {
1277                 csr |= CLR_FX;
1278                 csr &= ~(SET_FX | AT91_UDP_TXCOMP);
1279
1280                 /* write more IN DATA? */
1281                 if (req && ep0->is_in) {
1282                         if (handle_ep(ep0))
1283                                 udc->req_pending = 0;
1284
1285                 /*
1286                  * Ack after:
1287                  *  - last IN DATA packet (including GET_STATUS)
1288                  *  - IN/STATUS for OUT DATA
1289                  *  - IN/STATUS for any zero-length DATA stage
1290                  * except for the IN DATA case, the host should send
1291                  * an OUT status later, which we'll ack.
1292                  */
1293                 } else {
1294                         udc->req_pending = 0;
1295                         __raw_writel(csr, creg);
1296
1297                         /*
1298                          * SET_ADDRESS takes effect only after the STATUS
1299                          * (to the original address) gets acked.
1300                          */
1301                         if (udc->wait_for_addr_ack) {
1302                                 u32     tmp;
1303
1304                                 at91_udp_write(udc, AT91_UDP_FADDR,
1305                                                 AT91_UDP_FEN | udc->addr);
1306                                 tmp = at91_udp_read(udc, AT91_UDP_GLB_STAT);
1307                                 tmp &= ~AT91_UDP_FADDEN;
1308                                 if (udc->addr)
1309                                         tmp |= AT91_UDP_FADDEN;
1310                                 at91_udp_write(udc, AT91_UDP_GLB_STAT, tmp);
1311
1312                                 udc->wait_for_addr_ack = 0;
1313                                 VDBG("address %d\n", udc->addr);
1314                         }
1315                 }
1316         }
1317
1318         /* OUT packet arrived ... */
1319         else if (csr & AT91_UDP_RX_DATA_BK0) {
1320                 csr |= CLR_FX;
1321                 csr &= ~(SET_FX | AT91_UDP_RX_DATA_BK0);
1322
1323                 /* OUT DATA stage */
1324                 if (!ep0->is_in) {
1325                         if (req) {
1326                                 if (handle_ep(ep0)) {
1327                                         /* send IN/STATUS */
1328                                         PACKET("ep0 in/status\n");
1329                                         csr = __raw_readl(creg);
1330                                         csr &= ~SET_FX;
1331                                         csr |= CLR_FX | AT91_UDP_TXPKTRDY;
1332                                         __raw_writel(csr, creg);
1333                                         udc->req_pending = 0;
1334                                 }
1335                         } else if (udc->req_pending) {
1336                                 /*
1337                                  * AT91 hardware has a hard time with this
1338                                  * "deferred response" mode for control-OUT
1339                                  * transfers.  (For control-IN it's fine.)
1340                                  *
1341                                  * The normal solution leaves OUT data in the
1342                                  * fifo until the gadget driver is ready.
1343                                  * We couldn't do that here without disabling
1344                                  * the IRQ that tells about SETUP packets,
1345                                  * e.g. when the host gets impatient...
1346                                  *
1347                                  * Working around it by copying into a buffer
1348                                  * would almost be a non-deferred response,
1349                                  * except that it wouldn't permit reliable
1350                                  * stalling of the request.  Instead, demand
1351                                  * that gadget drivers not use this mode.
1352                                  */
1353                                 DBG("no control-OUT deferred responses!\n");
1354                                 __raw_writel(csr | AT91_UDP_FORCESTALL, creg);
1355                                 udc->req_pending = 0;
1356                         }
1357
1358                 /* STATUS stage for control-IN; ack.  */
1359                 } else {
1360                         PACKET("ep0 out/status ACK\n");
1361                         __raw_writel(csr, creg);
1362
1363                         /* "early" status stage */
1364                         if (req)
1365                                 done(ep0, req, 0);
1366                 }
1367         }
1368 }
1369
1370 static irqreturn_t at91_udc_irq (int irq, void *_udc)
1371 {
1372         struct at91_udc         *udc = _udc;
1373         u32                     rescans = 5;
1374
1375         while (rescans--) {
1376                 u32 status;
1377
1378                 status = at91_udp_read(udc, AT91_UDP_ISR)
1379                         & at91_udp_read(udc, AT91_UDP_IMR);
1380                 if (!status)
1381                         break;
1382
1383                 /* USB reset irq:  not maskable */
1384                 if (status & AT91_UDP_ENDBUSRES) {
1385                         at91_udp_write(udc, AT91_UDP_IDR, ~MINIMUS_INTERRUPTUS);
1386                         at91_udp_write(udc, AT91_UDP_IER, MINIMUS_INTERRUPTUS);
1387                         /* Atmel code clears this irq twice */
1388                         at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_ENDBUSRES);
1389                         at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_ENDBUSRES);
1390                         VDBG("end bus reset\n");
1391                         udc->addr = 0;
1392                         stop_activity(udc);
1393
1394                         /* enable ep0 */
1395                         at91_udp_write(udc, AT91_UDP_CSR(0),
1396                                         AT91_UDP_EPEDS | AT91_UDP_EPTYPE_CTRL);
1397                         udc->gadget.speed = USB_SPEED_FULL;
1398                         udc->suspended = 0;
1399                         at91_udp_write(udc, AT91_UDP_IER, AT91_UDP_EP(0));
1400
1401                         /*
1402                          * NOTE:  this driver keeps clocks off unless the
1403                          * USB host is present.  That saves power, but for
1404                          * boards that don't support VBUS detection, both
1405                          * clocks need to be active most of the time.
1406                          */
1407
1408                 /* host initiated suspend (3+ms bus idle) */
1409                 } else if (status & AT91_UDP_RXSUSP) {
1410                         at91_udp_write(udc, AT91_UDP_IDR, AT91_UDP_RXSUSP);
1411                         at91_udp_write(udc, AT91_UDP_IER, AT91_UDP_RXRSM);
1412                         at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_RXSUSP);
1413                         // VDBG("bus suspend\n");
1414                         if (udc->suspended)
1415                                 continue;
1416                         udc->suspended = 1;
1417
1418                         /*
1419                          * NOTE:  when suspending a VBUS-powered device, the
1420                          * gadget driver should switch into slow clock mode
1421                          * and then into standby to avoid drawing more than
1422                          * 500uA power (2500uA for some high-power configs).
1423                          */
1424                         if (udc->driver && udc->driver->suspend)
1425                                 udc->driver->suspend(&udc->gadget);
1426
1427                 /* host initiated resume */
1428                 } else if (status & AT91_UDP_RXRSM) {
1429                         at91_udp_write(udc, AT91_UDP_IDR, AT91_UDP_RXRSM);
1430                         at91_udp_write(udc, AT91_UDP_IER, AT91_UDP_RXSUSP);
1431                         at91_udp_write(udc, AT91_UDP_ICR, AT91_UDP_RXRSM);
1432                         // VDBG("bus resume\n");
1433                         if (!udc->suspended)
1434                                 continue;
1435                         udc->suspended = 0;
1436
1437                         /*
1438                          * NOTE:  for a VBUS-powered device, the gadget driver
1439                          * would normally want to switch out of slow clock
1440                          * mode into normal mode.
1441                          */
1442                         if (udc->driver && udc->driver->resume)
1443                                 udc->driver->resume(&udc->gadget);
1444
1445                 /* endpoint IRQs are cleared by handling them */
1446                 } else {
1447                         int             i;
1448                         unsigned        mask = 1;
1449                         struct at91_ep  *ep = &udc->ep[1];
1450
1451                         if (status & mask)
1452                                 handle_ep0(udc);
1453                         for (i = 1; i < NUM_ENDPOINTS; i++) {
1454                                 mask <<= 1;
1455                                 if (status & mask)
1456                                         handle_ep(ep);
1457                                 ep++;
1458                         }
1459                 }
1460         }
1461
1462         return IRQ_HANDLED;
1463 }
1464
1465 /*-------------------------------------------------------------------------*/
1466
1467 static void nop_release(struct device *dev)
1468 {
1469         /* nothing to free */
1470 }
1471
1472 static struct at91_udc controller = {
1473         .gadget = {
1474                 .ops    = &at91_udc_ops,
1475                 .ep0    = &controller.ep[0].ep,
1476                 .name   = driver_name,
1477                 .dev    = {
1478                         .bus_id = "gadget",
1479                         .release = nop_release,
1480                 }
1481         },
1482         .ep[0] = {
1483                 .ep = {
1484                         .name   = ep0name,
1485                         .ops    = &at91_ep_ops,
1486                 },
1487                 .udc            = &controller,
1488                 .maxpacket      = 8,
1489                 .int_mask       = 1 << 0,
1490         },
1491         .ep[1] = {
1492                 .ep = {
1493                         .name   = "ep1",
1494                         .ops    = &at91_ep_ops,
1495                 },
1496                 .udc            = &controller,
1497                 .is_pingpong    = 1,
1498                 .maxpacket      = 64,
1499                 .int_mask       = 1 << 1,
1500         },
1501         .ep[2] = {
1502                 .ep = {
1503                         .name   = "ep2",
1504                         .ops    = &at91_ep_ops,
1505                 },
1506                 .udc            = &controller,
1507                 .is_pingpong    = 1,
1508                 .maxpacket      = 64,
1509                 .int_mask       = 1 << 2,
1510         },
1511         .ep[3] = {
1512                 .ep = {
1513                         /* could actually do bulk too */
1514                         .name   = "ep3-int",
1515                         .ops    = &at91_ep_ops,
1516                 },
1517                 .udc            = &controller,
1518                 .maxpacket      = 8,
1519                 .int_mask       = 1 << 3,
1520         },
1521         .ep[4] = {
1522                 .ep = {
1523                         .name   = "ep4",
1524                         .ops    = &at91_ep_ops,
1525                 },
1526                 .udc            = &controller,
1527                 .is_pingpong    = 1,
1528                 .maxpacket      = 256,
1529                 .int_mask       = 1 << 4,
1530         },
1531         .ep[5] = {
1532                 .ep = {
1533                         .name   = "ep5",
1534                         .ops    = &at91_ep_ops,
1535                 },
1536                 .udc            = &controller,
1537                 .is_pingpong    = 1,
1538                 .maxpacket      = 256,
1539                 .int_mask       = 1 << 5,
1540         },
1541         /* ep6 and ep7 are also reserved (custom silicon might use them) */
1542 };
1543
1544 static irqreturn_t at91_vbus_irq(int irq, void *_udc)
1545 {
1546         struct at91_udc *udc = _udc;
1547         unsigned        value;
1548
1549         /* vbus needs at least brief debouncing */
1550         udelay(10);
1551         value = gpio_get_value(udc->board.vbus_pin);
1552         if (value != udc->vbus)
1553                 at91_vbus_session(&udc->gadget, value);
1554
1555         return IRQ_HANDLED;
1556 }
1557
1558 int usb_gadget_register_driver (struct usb_gadget_driver *driver)
1559 {
1560         struct at91_udc *udc = &controller;
1561         int             retval;
1562
1563         if (!driver
1564                         || driver->speed < USB_SPEED_FULL
1565                         || !driver->bind
1566                         || !driver->setup) {
1567                 DBG("bad parameter.\n");
1568                 return -EINVAL;
1569         }
1570
1571         if (udc->driver) {
1572                 DBG("UDC already has a gadget driver\n");
1573                 return -EBUSY;
1574         }
1575
1576         udc->driver = driver;
1577         udc->gadget.dev.driver = &driver->driver;
1578         udc->gadget.dev.driver_data = &driver->driver;
1579         udc->enabled = 1;
1580         udc->selfpowered = 1;
1581
1582         retval = driver->bind(&udc->gadget);
1583         if (retval) {
1584                 DBG("driver->bind() returned %d\n", retval);
1585                 udc->driver = NULL;
1586                 udc->gadget.dev.driver = NULL;
1587                 udc->gadget.dev.driver_data = NULL;
1588                 udc->enabled = 0;
1589                 udc->selfpowered = 0;
1590                 return retval;
1591         }
1592
1593         local_irq_disable();
1594         pullup(udc, 1);
1595         local_irq_enable();
1596
1597         DBG("bound to %s\n", driver->driver.name);
1598         return 0;
1599 }
1600 EXPORT_SYMBOL (usb_gadget_register_driver);
1601
1602 int usb_gadget_unregister_driver (struct usb_gadget_driver *driver)
1603 {
1604         struct at91_udc *udc = &controller;
1605
1606         if (!driver || driver != udc->driver || !driver->unbind)
1607                 return -EINVAL;
1608
1609         local_irq_disable();
1610         udc->enabled = 0;
1611         at91_udp_write(udc, AT91_UDP_IDR, ~0);
1612         pullup(udc, 0);
1613         local_irq_enable();
1614
1615         driver->unbind(&udc->gadget);
1616         udc->gadget.dev.driver = NULL;
1617         udc->gadget.dev.driver_data = NULL;
1618         udc->driver = NULL;
1619
1620         DBG("unbound from %s\n", driver->driver.name);
1621         return 0;
1622 }
1623 EXPORT_SYMBOL (usb_gadget_unregister_driver);
1624
1625 /*-------------------------------------------------------------------------*/
1626
1627 static void at91udc_shutdown(struct platform_device *dev)
1628 {
1629         /* force disconnect on reboot */
1630         pullup(platform_get_drvdata(dev), 0);
1631 }
1632
1633 static int __init at91udc_probe(struct platform_device *pdev)
1634 {
1635         struct device   *dev = &pdev->dev;
1636         struct at91_udc *udc;
1637         int             retval;
1638         struct resource *res;
1639
1640         if (!dev->platform_data) {
1641                 /* small (so we copy it) but critical! */
1642                 DBG("missing platform_data\n");
1643                 return -ENODEV;
1644         }
1645
1646         if (pdev->num_resources != 2) {
1647                 DBG("invalid num_resources\n");
1648                 return -ENODEV;
1649         }
1650         if ((pdev->resource[0].flags != IORESOURCE_MEM)
1651                         || (pdev->resource[1].flags != IORESOURCE_IRQ)) {
1652                 DBG("invalid resource type\n");
1653                 return -ENODEV;
1654         }
1655
1656         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1657         if (!res)
1658                 return -ENXIO;
1659
1660         if (!request_mem_region(res->start,
1661                         res->end - res->start + 1,
1662                         driver_name)) {
1663                 DBG("someone's using UDC memory\n");
1664                 return -EBUSY;
1665         }
1666
1667         /* init software state */
1668         udc = &controller;
1669         udc->gadget.dev.parent = dev;
1670         udc->board = *(struct at91_udc_data *) dev->platform_data;
1671         udc->pdev = pdev;
1672         udc->enabled = 0;
1673
1674         /* rm9200 needs manual D+ pullup; off by default */
1675         if (cpu_is_at91rm9200()) {
1676                 if (udc->board.pullup_pin <= 0) {
1677                         DBG("no D+ pullup?\n");
1678                         retval = -ENODEV;
1679                         goto fail0;
1680                 }
1681                 retval = gpio_request(udc->board.pullup_pin, "udc_pullup");
1682                 if (retval) {
1683                         DBG("D+ pullup is busy\n");
1684                         goto fail0;
1685                 }
1686                 gpio_direction_output(udc->board.pullup_pin,
1687                                 udc->board.pullup_active_low);
1688         }
1689
1690         /* newer chips have more FIFO memory than rm9200 */
1691         if (cpu_is_at91sam9260()) {
1692                 udc->ep[0].maxpacket = 64;
1693                 udc->ep[3].maxpacket = 64;
1694                 udc->ep[4].maxpacket = 512;
1695                 udc->ep[5].maxpacket = 512;
1696         } else if (cpu_is_at91sam9261()) {
1697                 udc->ep[3].maxpacket = 64;
1698         } else if (cpu_is_at91sam9263()) {
1699                 udc->ep[0].maxpacket = 64;
1700                 udc->ep[3].maxpacket = 64;
1701         }
1702
1703         udc->udp_baseaddr = ioremap(res->start, res->end - res->start + 1);
1704         if (!udc->udp_baseaddr) {
1705                 retval = -ENOMEM;
1706                 goto fail0a;
1707         }
1708
1709         udc_reinit(udc);
1710
1711         /* get interface and function clocks */
1712         udc->iclk = clk_get(dev, "udc_clk");
1713         udc->fclk = clk_get(dev, "udpck");
1714         if (IS_ERR(udc->iclk) || IS_ERR(udc->fclk)) {
1715                 DBG("clocks missing\n");
1716                 retval = -ENODEV;
1717                 /* NOTE: we "know" here that refcounts on these are NOPs */
1718                 goto fail0b;
1719         }
1720
1721         retval = device_register(&udc->gadget.dev);
1722         if (retval < 0)
1723                 goto fail0b;
1724
1725         /* don't do anything until we have both gadget driver and VBUS */
1726         clk_enable(udc->iclk);
1727         at91_udp_write(udc, AT91_UDP_TXVC, AT91_UDP_TXVC_TXVDIS);
1728         at91_udp_write(udc, AT91_UDP_IDR, 0xffffffff);
1729         /* Clear all pending interrupts - UDP may be used by bootloader. */
1730         at91_udp_write(udc, AT91_UDP_ICR, 0xffffffff);
1731         clk_disable(udc->iclk);
1732
1733         /* request UDC and maybe VBUS irqs */
1734         udc->udp_irq = platform_get_irq(pdev, 0);
1735         retval = request_irq(udc->udp_irq, at91_udc_irq,
1736                         IRQF_DISABLED, driver_name, udc);
1737         if (retval < 0) {
1738                 DBG("request irq %d failed\n", udc->udp_irq);
1739                 goto fail1;
1740         }
1741         if (udc->board.vbus_pin > 0) {
1742                 retval = gpio_request(udc->board.vbus_pin, "udc_vbus");
1743                 if (retval < 0) {
1744                         DBG("request vbus pin failed\n");
1745                         goto fail2;
1746                 }
1747                 gpio_direction_input(udc->board.vbus_pin);
1748
1749                 /*
1750                  * Get the initial state of VBUS - we cannot expect
1751                  * a pending interrupt.
1752                  */
1753                 udc->vbus = gpio_get_value(udc->board.vbus_pin);
1754                 if (request_irq(udc->board.vbus_pin, at91_vbus_irq,
1755                                 IRQF_DISABLED, driver_name, udc)) {
1756                         DBG("request vbus irq %d failed\n",
1757                                         udc->board.vbus_pin);
1758                         free_irq(udc->udp_irq, udc);
1759                         retval = -EBUSY;
1760                         goto fail3;
1761                 }
1762         } else {
1763                 DBG("no VBUS detection, assuming always-on\n");
1764                 udc->vbus = 1;
1765         }
1766         dev_set_drvdata(dev, udc);
1767         device_init_wakeup(dev, 1);
1768         create_debug_file(udc);
1769
1770         INFO("%s version %s\n", driver_name, DRIVER_VERSION);
1771         return 0;
1772
1773 fail3:
1774         if (udc->board.vbus_pin > 0)
1775                 gpio_free(udc->board.vbus_pin);
1776 fail2:
1777         free_irq(udc->udp_irq, udc);
1778 fail1:
1779         device_unregister(&udc->gadget.dev);
1780 fail0b:
1781         iounmap(udc->udp_baseaddr);
1782 fail0a:
1783         if (cpu_is_at91rm9200())
1784                 gpio_free(udc->board.pullup_pin);
1785 fail0:
1786         release_mem_region(res->start, res->end - res->start + 1);
1787         DBG("%s probe failed, %d\n", driver_name, retval);
1788         return retval;
1789 }
1790
1791 static int __exit at91udc_remove(struct platform_device *pdev)
1792 {
1793         struct at91_udc *udc = platform_get_drvdata(pdev);
1794         struct resource *res;
1795
1796         DBG("remove\n");
1797
1798         if (udc->driver)
1799                 return -EBUSY;
1800
1801         pullup(udc, 0);
1802
1803         device_init_wakeup(&pdev->dev, 0);
1804         remove_debug_file(udc);
1805         if (udc->board.vbus_pin > 0) {
1806                 free_irq(udc->board.vbus_pin, udc);
1807                 gpio_free(udc->board.vbus_pin);
1808         }
1809         free_irq(udc->udp_irq, udc);
1810         device_unregister(&udc->gadget.dev);
1811
1812         iounmap(udc->udp_baseaddr);
1813
1814         if (cpu_is_at91rm9200())
1815                 gpio_free(udc->board.pullup_pin);
1816
1817         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1818         release_mem_region(res->start, res->end - res->start + 1);
1819
1820         clk_put(udc->iclk);
1821         clk_put(udc->fclk);
1822
1823         return 0;
1824 }
1825
1826 #ifdef CONFIG_PM
1827 static int at91udc_suspend(struct platform_device *pdev, pm_message_t mesg)
1828 {
1829         struct at91_udc *udc = platform_get_drvdata(pdev);
1830         int             wake = udc->driver && device_may_wakeup(&pdev->dev);
1831
1832         /* Unless we can act normally to the host (letting it wake us up
1833          * whenever it has work for us) force disconnect.  Wakeup requires
1834          * PLLB for USB events (signaling for reset, wakeup, or incoming
1835          * tokens) and VBUS irqs (on systems which support them).
1836          */
1837         if ((!udc->suspended && udc->addr)
1838                         || !wake
1839                         || at91_suspend_entering_slow_clock()) {
1840                 pullup(udc, 0);
1841                 wake = 0;
1842         } else
1843                 enable_irq_wake(udc->udp_irq);
1844
1845         udc->active_suspend = wake;
1846         if (udc->board.vbus_pin > 0 && wake)
1847                 enable_irq_wake(udc->board.vbus_pin);
1848         return 0;
1849 }
1850
1851 static int at91udc_resume(struct platform_device *pdev)
1852 {
1853         struct at91_udc *udc = platform_get_drvdata(pdev);
1854
1855         if (udc->board.vbus_pin > 0 && udc->active_suspend)
1856                 disable_irq_wake(udc->board.vbus_pin);
1857
1858         /* maybe reconnect to host; if so, clocks on */
1859         if (udc->active_suspend)
1860                 disable_irq_wake(udc->udp_irq);
1861         else
1862                 pullup(udc, 1);
1863         return 0;
1864 }
1865 #else
1866 #define at91udc_suspend NULL
1867 #define at91udc_resume  NULL
1868 #endif
1869
1870 static struct platform_driver at91_udc_driver = {
1871         .remove         = __exit_p(at91udc_remove),
1872         .shutdown       = at91udc_shutdown,
1873         .suspend        = at91udc_suspend,
1874         .resume         = at91udc_resume,
1875         .driver         = {
1876                 .name   = (char *) driver_name,
1877                 .owner  = THIS_MODULE,
1878         },
1879 };
1880
1881 static int __init udc_init_module(void)
1882 {
1883         return platform_driver_probe(&at91_udc_driver, at91udc_probe);
1884 }
1885 module_init(udc_init_module);
1886
1887 static void __exit udc_exit_module(void)
1888 {
1889         platform_driver_unregister(&at91_udc_driver);
1890 }
1891 module_exit(udc_exit_module);
1892
1893 MODULE_DESCRIPTION("AT91 udc driver");
1894 MODULE_AUTHOR("Thomas Rathbone, David Brownell");
1895 MODULE_LICENSE("GPL");
1896 MODULE_ALIAS("platform:at91_udc");