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