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