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