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