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