header cleaning: don't include smp_lock.h when not used
[linux-3.10.git] / drivers / usb / gadget / goku_udc.c
1 /*
2  * Toshiba TC86C001 ("Goku-S") USB Device Controller driver
3  *
4  * Copyright (C) 2000-2002 Lineo
5  *      by Stuart Lynne, Tom Rushworth, and Bruce Balden
6  * Copyright (C) 2002 Toshiba Corporation
7  * Copyright (C) 2003 MontaVista Software (source@mvista.com)
8  *
9  * This file is licensed under the terms of the GNU General Public
10  * License version 2.  This program is licensed "as is" without any
11  * warranty of any kind, whether express or implied.
12  */
13
14 /*
15  * This device has ep0 and three semi-configurable bulk/interrupt endpoints.
16  *
17  *  - Endpoint numbering is fixed: ep{1,2,3}-bulk
18  *  - Gadget drivers can choose ep maxpacket (8/16/32/64)
19  *  - Gadget drivers can choose direction (IN, OUT)
20  *  - DMA works with ep1 (OUT transfers) and ep2 (IN transfers).
21  */
22
23 #undef DEBUG
24 // #define      VERBOSE         /* extra debug messages (success too) */
25 // #define      USB_TRACE       /* packet-level success messages */
26
27 #include <linux/kernel.h>
28 #include <linux/module.h>
29 #include <linux/pci.h>
30 #include <linux/delay.h>
31 #include <linux/ioport.h>
32 #include <linux/slab.h>
33 #include <linux/errno.h>
34 #include <linux/init.h>
35 #include <linux/timer.h>
36 #include <linux/list.h>
37 #include <linux/interrupt.h>
38 #include <linux/proc_fs.h>
39 #include <linux/device.h>
40 #include <linux/usb/ch9.h>
41 #include <linux/usb_gadget.h>
42
43 #include <asm/byteorder.h>
44 #include <asm/io.h>
45 #include <asm/irq.h>
46 #include <asm/system.h>
47 #include <asm/unaligned.h>
48
49
50 #include "goku_udc.h"
51
52 #define DRIVER_DESC             "TC86C001 USB Device Controller"
53 #define DRIVER_VERSION          "30-Oct 2003"
54
55 #define DMA_ADDR_INVALID        (~(dma_addr_t)0)
56
57 static const char driver_name [] = "goku_udc";
58 static const char driver_desc [] = DRIVER_DESC;
59
60 MODULE_AUTHOR("source@mvista.com");
61 MODULE_DESCRIPTION(DRIVER_DESC);
62 MODULE_LICENSE("GPL");
63
64
65 /*
66  * IN dma behaves ok under testing, though the IN-dma abort paths don't
67  * seem to behave quite as expected.  Used by default.
68  *
69  * OUT dma documents design problems handling the common "short packet"
70  * transfer termination policy; it couldn't be enabled by default, even
71  * if the OUT-dma abort problems had a resolution.
72  */
73 static unsigned use_dma = 1;
74
75 #if 0
76 //#include <linux/moduleparam.h>
77 /* "modprobe goku_udc use_dma=1" etc
78  *      0 to disable dma
79  *      1 to use IN dma only (normal operation)
80  *      2 to use IN and OUT dma
81  */
82 module_param(use_dma, uint, S_IRUGO);
83 #endif
84
85 /*-------------------------------------------------------------------------*/
86
87 static void nuke(struct goku_ep *, int status);
88
89 static inline void
90 command(struct goku_udc_regs __iomem *regs, int command, unsigned epnum)
91 {
92         writel(COMMAND_EP(epnum) | command, &regs->Command);
93         udelay(300);
94 }
95
96 static int
97 goku_ep_enable(struct usb_ep *_ep, const struct usb_endpoint_descriptor *desc)
98 {
99         struct goku_udc *dev;
100         struct goku_ep  *ep;
101         u32             mode;
102         u16             max;
103         unsigned long   flags;
104
105         ep = container_of(_ep, struct goku_ep, ep);
106         if (!_ep || !desc || ep->desc
107                         || desc->bDescriptorType != USB_DT_ENDPOINT)
108                 return -EINVAL;
109         dev = ep->dev;
110         if (ep == &dev->ep[0])
111                 return -EINVAL;
112         if (!dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN)
113                 return -ESHUTDOWN;
114         if (ep->num != (desc->bEndpointAddress & 0x0f))
115                 return -EINVAL;
116
117         switch (desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
118         case USB_ENDPOINT_XFER_BULK:
119         case USB_ENDPOINT_XFER_INT:
120                 break;
121         default:
122                 return -EINVAL;
123         }
124
125         if ((readl(ep->reg_status) & EPxSTATUS_EP_MASK)
126                         != EPxSTATUS_EP_INVALID)
127                 return -EBUSY;
128
129         /* enabling the no-toggle interrupt mode would need an api hook */
130         mode = 0;
131         max = le16_to_cpu(get_unaligned(&desc->wMaxPacketSize));
132         switch (max) {
133         case 64:        mode++;
134         case 32:        mode++;
135         case 16:        mode++;
136         case 8:         mode <<= 3;
137                         break;
138         default:
139                 return -EINVAL;
140         }
141         mode |= 2 << 1;         /* bulk, or intr-with-toggle */
142
143         /* ep1/ep2 dma direction is chosen early; it works in the other
144          * direction, with pio.  be cautious with out-dma.
145          */
146         ep->is_in = (USB_DIR_IN & desc->bEndpointAddress) != 0;
147         if (ep->is_in) {
148                 mode |= 1;
149                 ep->dma = (use_dma != 0) && (ep->num == UDC_MSTRD_ENDPOINT);
150         } else {
151                 ep->dma = (use_dma == 2) && (ep->num == UDC_MSTWR_ENDPOINT);
152                 if (ep->dma)
153                         DBG(dev, "%s out-dma hides short packets\n",
154                                 ep->ep.name);
155         }
156
157         spin_lock_irqsave(&ep->dev->lock, flags);
158
159         /* ep1 and ep2 can do double buffering and/or dma */
160         if (ep->num < 3) {
161                 struct goku_udc_regs __iomem    *regs = ep->dev->regs;
162                 u32                             tmp;
163
164                 /* double buffer except (for now) with pio in */
165                 tmp = ((ep->dma || !ep->is_in)
166                                 ? 0x10  /* double buffered */
167                                 : 0x11  /* single buffer */
168                         ) << ep->num;
169                 tmp |= readl(&regs->EPxSingle);
170                 writel(tmp, &regs->EPxSingle);
171
172                 tmp = (ep->dma ? 0x10/*dma*/ : 0x11/*pio*/) << ep->num;
173                 tmp |= readl(&regs->EPxBCS);
174                 writel(tmp, &regs->EPxBCS);
175         }
176         writel(mode, ep->reg_mode);
177         command(ep->dev->regs, COMMAND_RESET, ep->num);
178         ep->ep.maxpacket = max;
179         ep->stopped = 0;
180         ep->desc = desc;
181         spin_unlock_irqrestore(&ep->dev->lock, flags);
182
183         DBG(dev, "enable %s %s %s maxpacket %u\n", ep->ep.name,
184                 ep->is_in ? "IN" : "OUT",
185                 ep->dma ? "dma" : "pio",
186                 max);
187
188         return 0;
189 }
190
191 static void ep_reset(struct goku_udc_regs __iomem *regs, struct goku_ep *ep)
192 {
193         struct goku_udc         *dev = ep->dev;
194
195         if (regs) {
196                 command(regs, COMMAND_INVALID, ep->num);
197                 if (ep->num) {
198                         if (ep->num == UDC_MSTWR_ENDPOINT)
199                                 dev->int_enable &= ~(INT_MSTWREND
200                                                         |INT_MSTWRTMOUT);
201                         else if (ep->num == UDC_MSTRD_ENDPOINT)
202                                 dev->int_enable &= ~INT_MSTRDEND;
203                         dev->int_enable &= ~INT_EPxDATASET (ep->num);
204                 } else
205                         dev->int_enable &= ~INT_EP0;
206                 writel(dev->int_enable, &regs->int_enable);
207                 readl(&regs->int_enable);
208                 if (ep->num < 3) {
209                         struct goku_udc_regs __iomem    *r = ep->dev->regs;
210                         u32                             tmp;
211
212                         tmp = readl(&r->EPxSingle);
213                         tmp &= ~(0x11 << ep->num);
214                         writel(tmp, &r->EPxSingle);
215
216                         tmp = readl(&r->EPxBCS);
217                         tmp &= ~(0x11 << ep->num);
218                         writel(tmp, &r->EPxBCS);
219                 }
220                 /* reset dma in case we're still using it */
221                 if (ep->dma) {
222                         u32     master;
223
224                         master = readl(&regs->dma_master) & MST_RW_BITS;
225                         if (ep->num == UDC_MSTWR_ENDPOINT) {
226                                 master &= ~MST_W_BITS;
227                                 master |= MST_WR_RESET;
228                         } else {
229                                 master &= ~MST_R_BITS;
230                                 master |= MST_RD_RESET;
231                         }
232                         writel(master, &regs->dma_master);
233                 }
234         }
235
236         ep->ep.maxpacket = MAX_FIFO_SIZE;
237         ep->desc = NULL;
238         ep->stopped = 1;
239         ep->irqs = 0;
240         ep->dma = 0;
241 }
242
243 static int goku_ep_disable(struct usb_ep *_ep)
244 {
245         struct goku_ep  *ep;
246         struct goku_udc *dev;
247         unsigned long   flags;
248
249         ep = container_of(_ep, struct goku_ep, ep);
250         if (!_ep || !ep->desc)
251                 return -ENODEV;
252         dev = ep->dev;
253         if (dev->ep0state == EP0_SUSPEND)
254                 return -EBUSY;
255
256         VDBG(dev, "disable %s\n", _ep->name);
257
258         spin_lock_irqsave(&dev->lock, flags);
259         nuke(ep, -ESHUTDOWN);
260         ep_reset(dev->regs, ep);
261         spin_unlock_irqrestore(&dev->lock, flags);
262
263         return 0;
264 }
265
266 /*-------------------------------------------------------------------------*/
267
268 static struct usb_request *
269 goku_alloc_request(struct usb_ep *_ep, gfp_t gfp_flags)
270 {
271         struct goku_request     *req;
272
273         if (!_ep)
274                 return NULL;
275         req = kzalloc(sizeof *req, gfp_flags);
276         if (!req)
277                 return NULL;
278
279         req->req.dma = DMA_ADDR_INVALID;
280         INIT_LIST_HEAD(&req->queue);
281         return &req->req;
282 }
283
284 static void
285 goku_free_request(struct usb_ep *_ep, struct usb_request *_req)
286 {
287         struct goku_request     *req;
288
289         if (!_ep || !_req)
290                 return;
291
292         req = container_of(_req, struct goku_request, req);
293         WARN_ON(!list_empty(&req->queue));
294         kfree(req);
295 }
296
297 /*-------------------------------------------------------------------------*/
298
299 /* allocating buffers this way eliminates dma mapping overhead, which
300  * on some platforms will mean eliminating a per-io buffer copy.  with
301  * some kinds of system caches, further tweaks may still be needed.
302  */
303 static void *
304 goku_alloc_buffer(struct usb_ep *_ep, unsigned bytes,
305                         dma_addr_t *dma, gfp_t gfp_flags)
306 {
307         void            *retval;
308         struct goku_ep  *ep;
309
310         ep = container_of(_ep, struct goku_ep, ep);
311         if (!_ep)
312                 return NULL;
313         *dma = DMA_ADDR_INVALID;
314
315         if (ep->dma) {
316                 /* the main problem with this call is that it wastes memory
317                  * on typical 1/N page allocations: it allocates 1-N pages.
318                  */
319 #warning Using dma_alloc_coherent even with buffers smaller than a page.
320                 retval = dma_alloc_coherent(&ep->dev->pdev->dev,
321                                 bytes, dma, gfp_flags);
322         } else
323                 retval = kmalloc(bytes, gfp_flags);
324         return retval;
325 }
326
327 static void
328 goku_free_buffer(struct usb_ep *_ep, void *buf, dma_addr_t dma, unsigned bytes)
329 {
330         /* free memory into the right allocator */
331         if (dma != DMA_ADDR_INVALID) {
332                 struct goku_ep  *ep;
333
334                 ep = container_of(_ep, struct goku_ep, ep);
335                 if (!_ep)
336                         return;
337                 dma_free_coherent(&ep->dev->pdev->dev, bytes, buf, dma);
338         } else
339                 kfree (buf);
340 }
341
342 /*-------------------------------------------------------------------------*/
343
344 static void
345 done(struct goku_ep *ep, struct goku_request *req, int status)
346 {
347         struct goku_udc         *dev;
348         unsigned                stopped = ep->stopped;
349
350         list_del_init(&req->queue);
351
352         if (likely(req->req.status == -EINPROGRESS))
353                 req->req.status = status;
354         else
355                 status = req->req.status;
356
357         dev = ep->dev;
358         if (req->mapped) {
359                 pci_unmap_single(dev->pdev, req->req.dma, req->req.length,
360                         ep->is_in ? PCI_DMA_TODEVICE : PCI_DMA_FROMDEVICE);
361                 req->req.dma = DMA_ADDR_INVALID;
362                 req->mapped = 0;
363         }
364
365 #ifndef USB_TRACE
366         if (status && status != -ESHUTDOWN)
367 #endif
368                 VDBG(dev, "complete %s req %p stat %d len %u/%u\n",
369                         ep->ep.name, &req->req, status,
370                         req->req.actual, req->req.length);
371
372         /* don't modify queue heads during completion callback */
373         ep->stopped = 1;
374         spin_unlock(&dev->lock);
375         req->req.complete(&ep->ep, &req->req);
376         spin_lock(&dev->lock);
377         ep->stopped = stopped;
378 }
379
380 /*-------------------------------------------------------------------------*/
381
382 static inline int
383 write_packet(u32 __iomem *fifo, u8 *buf, struct goku_request *req, unsigned max)
384 {
385         unsigned        length, count;
386
387         length = min(req->req.length - req->req.actual, max);
388         req->req.actual += length;
389
390         count = length;
391         while (likely(count--))
392                 writel(*buf++, fifo);
393         return length;
394 }
395
396 // return:  0 = still running, 1 = completed, negative = errno
397 static int write_fifo(struct goku_ep *ep, struct goku_request *req)
398 {
399         struct goku_udc *dev = ep->dev;
400         u32             tmp;
401         u8              *buf;
402         unsigned        count;
403         int             is_last;
404
405         tmp = readl(&dev->regs->DataSet);
406         buf = req->req.buf + req->req.actual;
407         prefetch(buf);
408
409         dev = ep->dev;
410         if (unlikely(ep->num == 0 && dev->ep0state != EP0_IN))
411                 return -EL2HLT;
412
413         /* NOTE:  just single-buffered PIO-IN for now.  */
414         if (unlikely((tmp & DATASET_A(ep->num)) != 0))
415                 return 0;
416
417         /* clear our "packet available" irq */
418         if (ep->num != 0)
419                 writel(~INT_EPxDATASET(ep->num), &dev->regs->int_status);
420
421         count = write_packet(ep->reg_fifo, buf, req, ep->ep.maxpacket);
422
423         /* last packet often short (sometimes a zlp, especially on ep0) */
424         if (unlikely(count != ep->ep.maxpacket)) {
425                 writel(~(1<<ep->num), &dev->regs->EOP);
426                 if (ep->num == 0) {
427                         dev->ep[0].stopped = 1;
428                         dev->ep0state = EP0_STATUS;
429                 }
430                 is_last = 1;
431         } else {
432                 if (likely(req->req.length != req->req.actual)
433                                 || req->req.zero)
434                         is_last = 0;
435                 else
436                         is_last = 1;
437         }
438 #if 0           /* printk seemed to trash is_last...*/
439 //#ifdef USB_TRACE
440         VDBG(dev, "wrote %s %u bytes%s IN %u left %p\n",
441                 ep->ep.name, count, is_last ? "/last" : "",
442                 req->req.length - req->req.actual, req);
443 #endif
444
445         /* requests complete when all IN data is in the FIFO,
446          * or sometimes later, if a zlp was needed.
447          */
448         if (is_last) {
449                 done(ep, req, 0);
450                 return 1;
451         }
452
453         return 0;
454 }
455
456 static int read_fifo(struct goku_ep *ep, struct goku_request *req)
457 {
458         struct goku_udc_regs __iomem    *regs;
459         u32                             size, set;
460         u8                              *buf;
461         unsigned                        bufferspace, is_short, dbuff;
462
463         regs = ep->dev->regs;
464 top:
465         buf = req->req.buf + req->req.actual;
466         prefetchw(buf);
467
468         if (unlikely(ep->num == 0 && ep->dev->ep0state != EP0_OUT))
469                 return -EL2HLT;
470
471         dbuff = (ep->num == 1 || ep->num == 2);
472         do {
473                 /* ack dataset irq matching the status we'll handle */
474                 if (ep->num != 0)
475                         writel(~INT_EPxDATASET(ep->num), &regs->int_status);
476
477                 set = readl(&regs->DataSet) & DATASET_AB(ep->num);
478                 size = readl(&regs->EPxSizeLA[ep->num]);
479                 bufferspace = req->req.length - req->req.actual;
480
481                 /* usually do nothing without an OUT packet */
482                 if (likely(ep->num != 0 || bufferspace != 0)) {
483                         if (unlikely(set == 0))
484                                 break;
485                         /* use ep1/ep2 double-buffering for OUT */
486                         if (!(size & PACKET_ACTIVE))
487                                 size = readl(&regs->EPxSizeLB[ep->num]);
488                         if (!(size & PACKET_ACTIVE))    // "can't happen"
489                                 break;
490                         size &= DATASIZE;       /* EPxSizeH == 0 */
491
492                 /* ep0out no-out-data case for set_config, etc */
493                 } else
494                         size = 0;
495
496                 /* read all bytes from this packet */
497                 req->req.actual += size;
498                 is_short = (size < ep->ep.maxpacket);
499 #ifdef USB_TRACE
500                 VDBG(ep->dev, "read %s %u bytes%s OUT req %p %u/%u\n",
501                         ep->ep.name, size, is_short ? "/S" : "",
502                         req, req->req.actual, req->req.length);
503 #endif
504                 while (likely(size-- != 0)) {
505                         u8      byte = (u8) readl(ep->reg_fifo);
506
507                         if (unlikely(bufferspace == 0)) {
508                                 /* this happens when the driver's buffer
509                                  * is smaller than what the host sent.
510                                  * discard the extra data in this packet.
511                                  */
512                                 if (req->req.status != -EOVERFLOW)
513                                         DBG(ep->dev, "%s overflow %u\n",
514                                                 ep->ep.name, size);
515                                 req->req.status = -EOVERFLOW;
516                         } else {
517                                 *buf++ = byte;
518                                 bufferspace--;
519                         }
520                 }
521
522                 /* completion */
523                 if (unlikely(is_short || req->req.actual == req->req.length)) {
524                         if (unlikely(ep->num == 0)) {
525                                 /* non-control endpoints now usable? */
526                                 if (ep->dev->req_config)
527                                         writel(ep->dev->configured
528                                                         ? USBSTATE_CONFIGURED
529                                                         : 0,
530                                                 &regs->UsbState);
531                                 /* ep0out status stage */
532                                 writel(~(1<<0), &regs->EOP);
533                                 ep->stopped = 1;
534                                 ep->dev->ep0state = EP0_STATUS;
535                         }
536                         done(ep, req, 0);
537
538                         /* empty the second buffer asap */
539                         if (dbuff && !list_empty(&ep->queue)) {
540                                 req = list_entry(ep->queue.next,
541                                                 struct goku_request, queue);
542                                 goto top;
543                         }
544                         return 1;
545                 }
546         } while (dbuff);
547         return 0;
548 }
549
550 static inline void
551 pio_irq_enable(struct goku_udc *dev,
552                 struct goku_udc_regs __iomem *regs, int epnum)
553 {
554         dev->int_enable |= INT_EPxDATASET (epnum);
555         writel(dev->int_enable, &regs->int_enable);
556         /* write may still be posted */
557 }
558
559 static inline void
560 pio_irq_disable(struct goku_udc *dev,
561                 struct goku_udc_regs __iomem *regs, int epnum)
562 {
563         dev->int_enable &= ~INT_EPxDATASET (epnum);
564         writel(dev->int_enable, &regs->int_enable);
565         /* write may still be posted */
566 }
567
568 static inline void
569 pio_advance(struct goku_ep *ep)
570 {
571         struct goku_request     *req;
572
573         if (unlikely(list_empty (&ep->queue)))
574                 return;
575         req = list_entry(ep->queue.next, struct goku_request, queue);
576         (ep->is_in ? write_fifo : read_fifo)(ep, req);
577 }
578
579
580 /*-------------------------------------------------------------------------*/
581
582 // return:  0 = q running, 1 = q stopped, negative = errno
583 static int start_dma(struct goku_ep *ep, struct goku_request *req)
584 {
585         struct goku_udc_regs __iomem    *regs = ep->dev->regs;
586         u32                             master;
587         u32                             start = req->req.dma;
588         u32                             end = start + req->req.length - 1;
589
590         master = readl(&regs->dma_master) & MST_RW_BITS;
591
592         /* re-init the bits affecting IN dma; careful with zlps */
593         if (likely(ep->is_in)) {
594                 if (unlikely(master & MST_RD_ENA)) {
595                         DBG (ep->dev, "start, IN active dma %03x!!\n",
596                                 master);
597 //                      return -EL2HLT;
598                 }
599                 writel(end, &regs->in_dma_end);
600                 writel(start, &regs->in_dma_start);
601
602                 master &= ~MST_R_BITS;
603                 if (unlikely(req->req.length == 0))
604                         master = MST_RD_ENA | MST_RD_EOPB;
605                 else if ((req->req.length % ep->ep.maxpacket) != 0
606                                         || req->req.zero)
607                         master = MST_RD_ENA | MST_EOPB_ENA;
608                 else
609                         master = MST_RD_ENA | MST_EOPB_DIS;
610
611                 ep->dev->int_enable |= INT_MSTRDEND;
612
613         /* Goku DMA-OUT merges short packets, which plays poorly with
614          * protocols where short packets mark the transfer boundaries.
615          * The chip supports a nonstandard policy with INT_MSTWRTMOUT,
616          * ending transfers after 3 SOFs; we don't turn it on.
617          */
618         } else {
619                 if (unlikely(master & MST_WR_ENA)) {
620                         DBG (ep->dev, "start, OUT active dma %03x!!\n",
621                                 master);
622 //                      return -EL2HLT;
623                 }
624                 writel(end, &regs->out_dma_end);
625                 writel(start, &regs->out_dma_start);
626
627                 master &= ~MST_W_BITS;
628                 master |= MST_WR_ENA | MST_TIMEOUT_DIS;
629
630                 ep->dev->int_enable |= INT_MSTWREND|INT_MSTWRTMOUT;
631         }
632
633         writel(master, &regs->dma_master);
634         writel(ep->dev->int_enable, &regs->int_enable);
635         return 0;
636 }
637
638 static void dma_advance(struct goku_udc *dev, struct goku_ep *ep)
639 {
640         struct goku_request             *req;
641         struct goku_udc_regs __iomem    *regs = ep->dev->regs;
642         u32                             master;
643
644         master = readl(&regs->dma_master);
645
646         if (unlikely(list_empty(&ep->queue))) {
647 stop:
648                 if (ep->is_in)
649                         dev->int_enable &= ~INT_MSTRDEND;
650                 else
651                         dev->int_enable &= ~(INT_MSTWREND|INT_MSTWRTMOUT);
652                 writel(dev->int_enable, &regs->int_enable);
653                 return;
654         }
655         req = list_entry(ep->queue.next, struct goku_request, queue);
656
657         /* normal hw dma completion (not abort) */
658         if (likely(ep->is_in)) {
659                 if (unlikely(master & MST_RD_ENA))
660                         return;
661                 req->req.actual = readl(&regs->in_dma_current);
662         } else {
663                 if (unlikely(master & MST_WR_ENA))
664                         return;
665
666                 /* hardware merges short packets, and also hides packet
667                  * overruns.  a partial packet MAY be in the fifo here.
668                  */
669                 req->req.actual = readl(&regs->out_dma_current);
670         }
671         req->req.actual -= req->req.dma;
672         req->req.actual++;
673
674 #ifdef USB_TRACE
675         VDBG(dev, "done %s %s dma, %u/%u bytes, req %p\n",
676                 ep->ep.name, ep->is_in ? "IN" : "OUT",
677                 req->req.actual, req->req.length, req);
678 #endif
679         done(ep, req, 0);
680         if (list_empty(&ep->queue))
681                 goto stop;
682         req = list_entry(ep->queue.next, struct goku_request, queue);
683         (void) start_dma(ep, req);
684 }
685
686 static void abort_dma(struct goku_ep *ep, int status)
687 {
688         struct goku_udc_regs __iomem    *regs = ep->dev->regs;
689         struct goku_request             *req;
690         u32                             curr, master;
691
692         /* NAK future host requests, hoping the implicit delay lets the
693          * dma engine finish reading (or writing) its latest packet and
694          * empty the dma buffer (up to 16 bytes).
695          *
696          * This avoids needing to clean up a partial packet in the fifo;
697          * we can't do that for IN without side effects to HALT and TOGGLE.
698          */
699         command(regs, COMMAND_FIFO_DISABLE, ep->num);
700         req = list_entry(ep->queue.next, struct goku_request, queue);
701         master = readl(&regs->dma_master) & MST_RW_BITS;
702
703         /* FIXME using these resets isn't usably documented. this may
704          * not work unless it's followed by disabling the endpoint.
705          *
706          * FIXME the OUT reset path doesn't even behave consistently.
707          */
708         if (ep->is_in) {
709                 if (unlikely((readl(&regs->dma_master) & MST_RD_ENA) == 0))
710                         goto finished;
711                 curr = readl(&regs->in_dma_current);
712
713                 writel(curr, &regs->in_dma_end);
714                 writel(curr, &regs->in_dma_start);
715
716                 master &= ~MST_R_BITS;
717                 master |= MST_RD_RESET;
718                 writel(master, &regs->dma_master);
719
720                 if (readl(&regs->dma_master) & MST_RD_ENA)
721                         DBG(ep->dev, "IN dma active after reset!\n");
722
723         } else {
724                 if (unlikely((readl(&regs->dma_master) & MST_WR_ENA) == 0))
725                         goto finished;
726                 curr = readl(&regs->out_dma_current);
727
728                 writel(curr, &regs->out_dma_end);
729                 writel(curr, &regs->out_dma_start);
730
731                 master &= ~MST_W_BITS;
732                 master |= MST_WR_RESET;
733                 writel(master, &regs->dma_master);
734
735                 if (readl(&regs->dma_master) & MST_WR_ENA)
736                         DBG(ep->dev, "OUT dma active after reset!\n");
737         }
738         req->req.actual = (curr - req->req.dma) + 1;
739         req->req.status = status;
740
741         VDBG(ep->dev, "%s %s %s %d/%d\n", __FUNCTION__, ep->ep.name,
742                 ep->is_in ? "IN" : "OUT",
743                 req->req.actual, req->req.length);
744
745         command(regs, COMMAND_FIFO_ENABLE, ep->num);
746
747         return;
748
749 finished:
750         /* dma already completed; no abort needed */
751         command(regs, COMMAND_FIFO_ENABLE, ep->num);
752         req->req.actual = req->req.length;
753         req->req.status = 0;
754 }
755
756 /*-------------------------------------------------------------------------*/
757
758 static int
759 goku_queue(struct usb_ep *_ep, struct usb_request *_req, gfp_t gfp_flags)
760 {
761         struct goku_request     *req;
762         struct goku_ep          *ep;
763         struct goku_udc         *dev;
764         unsigned long           flags;
765         int                     status;
766
767         /* always require a cpu-view buffer so pio works */
768         req = container_of(_req, struct goku_request, req);
769         if (unlikely(!_req || !_req->complete
770                         || !_req->buf || !list_empty(&req->queue)))
771                 return -EINVAL;
772         ep = container_of(_ep, struct goku_ep, ep);
773         if (unlikely(!_ep || (!ep->desc && ep->num != 0)))
774                 return -EINVAL;
775         dev = ep->dev;
776         if (unlikely(!dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN))
777                 return -ESHUTDOWN;
778
779         /* can't touch registers when suspended */
780         if (dev->ep0state == EP0_SUSPEND)
781                 return -EBUSY;
782
783         /* set up dma mapping in case the caller didn't */
784         if (ep->dma && _req->dma == DMA_ADDR_INVALID) {
785                 _req->dma = pci_map_single(dev->pdev, _req->buf, _req->length,
786                         ep->is_in ? PCI_DMA_TODEVICE : PCI_DMA_FROMDEVICE);
787                 req->mapped = 1;
788         }
789
790 #ifdef USB_TRACE
791         VDBG(dev, "%s queue req %p, len %u buf %p\n",
792                         _ep->name, _req, _req->length, _req->buf);
793 #endif
794
795         spin_lock_irqsave(&dev->lock, flags);
796
797         _req->status = -EINPROGRESS;
798         _req->actual = 0;
799
800         /* for ep0 IN without premature status, zlp is required and
801          * writing EOP starts the status stage (OUT).
802          */
803         if (unlikely(ep->num == 0 && ep->is_in))
804                 _req->zero = 1;
805
806         /* kickstart this i/o queue? */
807         status = 0;
808         if (list_empty(&ep->queue) && likely(!ep->stopped)) {
809                 /* dma:  done after dma completion IRQ (or error)
810                  * pio:  done after last fifo operation
811                  */
812                 if (ep->dma)
813                         status = start_dma(ep, req);
814                 else
815                         status = (ep->is_in ? write_fifo : read_fifo)(ep, req);
816
817                 if (unlikely(status != 0)) {
818                         if (status > 0)
819                                 status = 0;
820                         req = NULL;
821                 }
822
823         } /* else pio or dma irq handler advances the queue. */
824
825         if (likely(req != 0))
826                 list_add_tail(&req->queue, &ep->queue);
827
828         if (likely(!list_empty(&ep->queue))
829                         && likely(ep->num != 0)
830                         && !ep->dma
831                         && !(dev->int_enable & INT_EPxDATASET (ep->num)))
832                 pio_irq_enable(dev, dev->regs, ep->num);
833
834         spin_unlock_irqrestore(&dev->lock, flags);
835
836         /* pci writes may still be posted */
837         return status;
838 }
839
840 /* dequeue ALL requests */
841 static void nuke(struct goku_ep *ep, int status)
842 {
843         struct goku_request     *req;
844
845         ep->stopped = 1;
846         if (list_empty(&ep->queue))
847                 return;
848         if (ep->dma)
849                 abort_dma(ep, status);
850         while (!list_empty(&ep->queue)) {
851                 req = list_entry(ep->queue.next, struct goku_request, queue);
852                 done(ep, req, status);
853         }
854 }
855
856 /* dequeue JUST ONE request */
857 static int goku_dequeue(struct usb_ep *_ep, struct usb_request *_req)
858 {
859         struct goku_request     *req;
860         struct goku_ep          *ep;
861         struct goku_udc         *dev;
862         unsigned long           flags;
863
864         ep = container_of(_ep, struct goku_ep, ep);
865         if (!_ep || !_req || (!ep->desc && ep->num != 0))
866                 return -EINVAL;
867         dev = ep->dev;
868         if (!dev->driver)
869                 return -ESHUTDOWN;
870
871         /* we can't touch (dma) registers when suspended */
872         if (dev->ep0state == EP0_SUSPEND)
873                 return -EBUSY;
874
875         VDBG(dev, "%s %s %s %s %p\n", __FUNCTION__, _ep->name,
876                 ep->is_in ? "IN" : "OUT",
877                 ep->dma ? "dma" : "pio",
878                 _req);
879
880         spin_lock_irqsave(&dev->lock, flags);
881
882         /* make sure it's actually queued on this endpoint */
883         list_for_each_entry (req, &ep->queue, queue) {
884                 if (&req->req == _req)
885                         break;
886         }
887         if (&req->req != _req) {
888                 spin_unlock_irqrestore (&dev->lock, flags);
889                 return -EINVAL;
890         }
891
892         if (ep->dma && ep->queue.next == &req->queue && !ep->stopped) {
893                 abort_dma(ep, -ECONNRESET);
894                 done(ep, req, -ECONNRESET);
895                 dma_advance(dev, ep);
896         } else if (!list_empty(&req->queue))
897                 done(ep, req, -ECONNRESET);
898         else
899                 req = NULL;
900         spin_unlock_irqrestore(&dev->lock, flags);
901
902         return req ? 0 : -EOPNOTSUPP;
903 }
904
905 /*-------------------------------------------------------------------------*/
906
907 static void goku_clear_halt(struct goku_ep *ep)
908 {
909         // assert (ep->num !=0)
910         VDBG(ep->dev, "%s clear halt\n", ep->ep.name);
911         command(ep->dev->regs, COMMAND_SETDATA0, ep->num);
912         command(ep->dev->regs, COMMAND_STALL_CLEAR, ep->num);
913         if (ep->stopped) {
914                 ep->stopped = 0;
915                 if (ep->dma) {
916                         struct goku_request     *req;
917
918                         if (list_empty(&ep->queue))
919                                 return;
920                         req = list_entry(ep->queue.next, struct goku_request,
921                                                 queue);
922                         (void) start_dma(ep, req);
923                 } else
924                         pio_advance(ep);
925         }
926 }
927
928 static int goku_set_halt(struct usb_ep *_ep, int value)
929 {
930         struct goku_ep  *ep;
931         unsigned long   flags;
932         int             retval = 0;
933
934         if (!_ep)
935                 return -ENODEV;
936         ep = container_of (_ep, struct goku_ep, ep);
937
938         if (ep->num == 0) {
939                 if (value) {
940                         ep->dev->ep0state = EP0_STALL;
941                         ep->dev->ep[0].stopped = 1;
942                 } else
943                         return -EINVAL;
944
945         /* don't change EPxSTATUS_EP_INVALID to READY */
946         } else if (!ep->desc) {
947                 DBG(ep->dev, "%s %s inactive?\n", __FUNCTION__, ep->ep.name);
948                 return -EINVAL;
949         }
950
951         spin_lock_irqsave(&ep->dev->lock, flags);
952         if (!list_empty(&ep->queue))
953                 retval = -EAGAIN;
954         else if (ep->is_in && value
955                         /* data in (either) packet buffer? */
956                         && (readl(&ep->dev->regs->DataSet)
957                                         & DATASET_AB(ep->num)))
958                 retval = -EAGAIN;
959         else if (!value)
960                 goku_clear_halt(ep);
961         else {
962                 ep->stopped = 1;
963                 VDBG(ep->dev, "%s set halt\n", ep->ep.name);
964                 command(ep->dev->regs, COMMAND_STALL, ep->num);
965                 readl(ep->reg_status);
966         }
967         spin_unlock_irqrestore(&ep->dev->lock, flags);
968         return retval;
969 }
970
971 static int goku_fifo_status(struct usb_ep *_ep)
972 {
973         struct goku_ep                  *ep;
974         struct goku_udc_regs __iomem    *regs;
975         u32                             size;
976
977         if (!_ep)
978                 return -ENODEV;
979         ep = container_of(_ep, struct goku_ep, ep);
980
981         /* size is only reported sanely for OUT */
982         if (ep->is_in)
983                 return -EOPNOTSUPP;
984
985         /* ignores 16-byte dma buffer; SizeH == 0 */
986         regs = ep->dev->regs;
987         size = readl(&regs->EPxSizeLA[ep->num]) & DATASIZE;
988         size += readl(&regs->EPxSizeLB[ep->num]) & DATASIZE;
989         VDBG(ep->dev, "%s %s %u\n", __FUNCTION__, ep->ep.name, size);
990         return size;
991 }
992
993 static void goku_fifo_flush(struct usb_ep *_ep)
994 {
995         struct goku_ep                  *ep;
996         struct goku_udc_regs __iomem    *regs;
997         u32                             size;
998
999         if (!_ep)
1000                 return;
1001         ep = container_of(_ep, struct goku_ep, ep);
1002         VDBG(ep->dev, "%s %s\n", __FUNCTION__, ep->ep.name);
1003
1004         /* don't change EPxSTATUS_EP_INVALID to READY */
1005         if (!ep->desc && ep->num != 0) {
1006                 DBG(ep->dev, "%s %s inactive?\n", __FUNCTION__, ep->ep.name);
1007                 return;
1008         }
1009
1010         regs = ep->dev->regs;
1011         size = readl(&regs->EPxSizeLA[ep->num]);
1012         size &= DATASIZE;
1013
1014         /* Non-desirable behavior:  FIFO_CLEAR also clears the
1015          * endpoint halt feature.  For OUT, we _could_ just read
1016          * the bytes out (PIO, if !ep->dma); for in, no choice.
1017          */
1018         if (size)
1019                 command(regs, COMMAND_FIFO_CLEAR, ep->num);
1020 }
1021
1022 static struct usb_ep_ops goku_ep_ops = {
1023         .enable         = goku_ep_enable,
1024         .disable        = goku_ep_disable,
1025
1026         .alloc_request  = goku_alloc_request,
1027         .free_request   = goku_free_request,
1028
1029         .alloc_buffer   = goku_alloc_buffer,
1030         .free_buffer    = goku_free_buffer,
1031
1032         .queue          = goku_queue,
1033         .dequeue        = goku_dequeue,
1034
1035         .set_halt       = goku_set_halt,
1036         .fifo_status    = goku_fifo_status,
1037         .fifo_flush     = goku_fifo_flush,
1038 };
1039
1040 /*-------------------------------------------------------------------------*/
1041
1042 static int goku_get_frame(struct usb_gadget *_gadget)
1043 {
1044         return -EOPNOTSUPP;
1045 }
1046
1047 static const struct usb_gadget_ops goku_ops = {
1048         .get_frame      = goku_get_frame,
1049         // no remote wakeup
1050         // not selfpowered
1051 };
1052
1053 /*-------------------------------------------------------------------------*/
1054
1055 static inline char *dmastr(void)
1056 {
1057         if (use_dma == 0)
1058                 return "(dma disabled)";
1059         else if (use_dma == 2)
1060                 return "(dma IN and OUT)";
1061         else
1062                 return "(dma IN)";
1063 }
1064
1065 #ifdef CONFIG_USB_GADGET_DEBUG_FILES
1066
1067 static const char proc_node_name [] = "driver/udc";
1068
1069 #define FOURBITS "%s%s%s%s"
1070 #define EIGHTBITS FOURBITS FOURBITS
1071
1072 static void
1073 dump_intmask(const char *label, u32 mask, char **next, unsigned *size)
1074 {
1075         int t;
1076
1077         /* int_status is the same format ... */
1078         t = scnprintf(*next, *size,
1079                 "%s %05X =" FOURBITS EIGHTBITS EIGHTBITS "\n",
1080                 label, mask,
1081                 (mask & INT_PWRDETECT) ? " power" : "",
1082                 (mask & INT_SYSERROR) ? " sys" : "",
1083                 (mask & INT_MSTRDEND) ? " in-dma" : "",
1084                 (mask & INT_MSTWRTMOUT) ? " wrtmo" : "",
1085
1086                 (mask & INT_MSTWREND) ? " out-dma" : "",
1087                 (mask & INT_MSTWRSET) ? " wrset" : "",
1088                 (mask & INT_ERR) ? " err" : "",
1089                 (mask & INT_SOF) ? " sof" : "",
1090
1091                 (mask & INT_EP3NAK) ? " ep3nak" : "",
1092                 (mask & INT_EP2NAK) ? " ep2nak" : "",
1093                 (mask & INT_EP1NAK) ? " ep1nak" : "",
1094                 (mask & INT_EP3DATASET) ? " ep3" : "",
1095
1096                 (mask & INT_EP2DATASET) ? " ep2" : "",
1097                 (mask & INT_EP1DATASET) ? " ep1" : "",
1098                 (mask & INT_STATUSNAK) ? " ep0snak" : "",
1099                 (mask & INT_STATUS) ? " ep0status" : "",
1100
1101                 (mask & INT_SETUP) ? " setup" : "",
1102                 (mask & INT_ENDPOINT0) ? " ep0" : "",
1103                 (mask & INT_USBRESET) ? " reset" : "",
1104                 (mask & INT_SUSPEND) ? " suspend" : "");
1105         *size -= t;
1106         *next += t;
1107 }
1108
1109
1110 static int
1111 udc_proc_read(char *buffer, char **start, off_t off, int count,
1112                 int *eof, void *_dev)
1113 {
1114         char                            *buf = buffer;
1115         struct goku_udc                 *dev = _dev;
1116         struct goku_udc_regs __iomem    *regs = dev->regs;
1117         char                            *next = buf;
1118         unsigned                        size = count;
1119         unsigned long                   flags;
1120         int                             i, t, is_usb_connected;
1121         u32                             tmp;
1122
1123         if (off != 0)
1124                 return 0;
1125
1126         local_irq_save(flags);
1127
1128         /* basic device status */
1129         tmp = readl(&regs->power_detect);
1130         is_usb_connected = tmp & PW_DETECT;
1131         t = scnprintf(next, size,
1132                 "%s - %s\n"
1133                 "%s version: %s %s\n"
1134                 "Gadget driver: %s\n"
1135                 "Host %s, %s\n"
1136                 "\n",
1137                 pci_name(dev->pdev), driver_desc,
1138                 driver_name, DRIVER_VERSION, dmastr(),
1139                 dev->driver ? dev->driver->driver.name : "(none)",
1140                 is_usb_connected
1141                         ? ((tmp & PW_PULLUP) ? "full speed" : "powered")
1142                         : "disconnected",
1143                 ({char *tmp;
1144                 switch(dev->ep0state){
1145                 case EP0_DISCONNECT:    tmp = "ep0_disconnect"; break;
1146                 case EP0_IDLE:          tmp = "ep0_idle"; break;
1147                 case EP0_IN:            tmp = "ep0_in"; break;
1148                 case EP0_OUT:           tmp = "ep0_out"; break;
1149                 case EP0_STATUS:        tmp = "ep0_status"; break;
1150                 case EP0_STALL:         tmp = "ep0_stall"; break;
1151                 case EP0_SUSPEND:       tmp = "ep0_suspend"; break;
1152                 default:                tmp = "ep0_?"; break;
1153                 } tmp; })
1154                 );
1155         size -= t;
1156         next += t;
1157
1158         dump_intmask("int_status", readl(&regs->int_status), &next, &size);
1159         dump_intmask("int_enable", readl(&regs->int_enable), &next, &size);
1160
1161         if (!is_usb_connected || !dev->driver || (tmp & PW_PULLUP) == 0)
1162                 goto done;
1163
1164         /* registers for (active) device and ep0 */
1165         t = scnprintf(next, size, "\nirqs %lu\ndataset %02x "
1166                         "single.bcs %02x.%02x state %x addr %u\n",
1167                         dev->irqs, readl(&regs->DataSet),
1168                         readl(&regs->EPxSingle), readl(&regs->EPxBCS),
1169                         readl(&regs->UsbState),
1170                         readl(&regs->address));
1171         size -= t;
1172         next += t;
1173
1174         tmp = readl(&regs->dma_master);
1175         t = scnprintf(next, size,
1176                 "dma %03X =" EIGHTBITS "%s %s\n", tmp,
1177                 (tmp & MST_EOPB_DIS) ? " eopb-" : "",
1178                 (tmp & MST_EOPB_ENA) ? " eopb+" : "",
1179                 (tmp & MST_TIMEOUT_DIS) ? " tmo-" : "",
1180                 (tmp & MST_TIMEOUT_ENA) ? " tmo+" : "",
1181
1182                 (tmp & MST_RD_EOPB) ? " eopb" : "",
1183                 (tmp & MST_RD_RESET) ? " in_reset" : "",
1184                 (tmp & MST_WR_RESET) ? " out_reset" : "",
1185                 (tmp & MST_RD_ENA) ? " IN" : "",
1186
1187                 (tmp & MST_WR_ENA) ? " OUT" : "",
1188                 (tmp & MST_CONNECTION)
1189                         ? "ep1in/ep2out"
1190                         : "ep1out/ep2in");
1191         size -= t;
1192         next += t;
1193
1194         /* dump endpoint queues */
1195         for (i = 0; i < 4; i++) {
1196                 struct goku_ep          *ep = &dev->ep [i];
1197                 struct goku_request     *req;
1198                 int                     t;
1199
1200                 if (i && !ep->desc)
1201                         continue;
1202
1203                 tmp = readl(ep->reg_status);
1204                 t = scnprintf(next, size,
1205                         "%s %s max %u %s, irqs %lu, "
1206                         "status %02x (%s) " FOURBITS "\n",
1207                         ep->ep.name,
1208                         ep->is_in ? "in" : "out",
1209                         ep->ep.maxpacket,
1210                         ep->dma ? "dma" : "pio",
1211                         ep->irqs,
1212                         tmp, ({ char *s;
1213                         switch (tmp & EPxSTATUS_EP_MASK) {
1214                         case EPxSTATUS_EP_READY:
1215                                 s = "ready"; break;
1216                         case EPxSTATUS_EP_DATAIN:
1217                                 s = "packet"; break;
1218                         case EPxSTATUS_EP_FULL:
1219                                 s = "full"; break;
1220                         case EPxSTATUS_EP_TX_ERR:       // host will retry
1221                                 s = "tx_err"; break;
1222                         case EPxSTATUS_EP_RX_ERR:
1223                                 s = "rx_err"; break;
1224                         case EPxSTATUS_EP_BUSY:         /* ep0 only */
1225                                 s = "busy"; break;
1226                         case EPxSTATUS_EP_STALL:
1227                                 s = "stall"; break;
1228                         case EPxSTATUS_EP_INVALID:      // these "can't happen"
1229                                 s = "invalid"; break;
1230                         default:
1231                                 s = "?"; break;
1232                         }; s; }),
1233                         (tmp & EPxSTATUS_TOGGLE) ? "data1" : "data0",
1234                         (tmp & EPxSTATUS_SUSPEND) ? " suspend" : "",
1235                         (tmp & EPxSTATUS_FIFO_DISABLE) ? " disable" : "",
1236                         (tmp & EPxSTATUS_STAGE_ERROR) ? " ep0stat" : ""
1237                         );
1238                 if (t <= 0 || t > size)
1239                         goto done;
1240                 size -= t;
1241                 next += t;
1242
1243                 if (list_empty(&ep->queue)) {
1244                         t = scnprintf(next, size, "\t(nothing queued)\n");
1245                         if (t <= 0 || t > size)
1246                                 goto done;
1247                         size -= t;
1248                         next += t;
1249                         continue;
1250                 }
1251                 list_for_each_entry(req, &ep->queue, queue) {
1252                         if (ep->dma && req->queue.prev == &ep->queue) {
1253                                 if (i == UDC_MSTRD_ENDPOINT)
1254                                         tmp = readl(&regs->in_dma_current);
1255                                 else
1256                                         tmp = readl(&regs->out_dma_current);
1257                                 tmp -= req->req.dma;
1258                                 tmp++;
1259                         } else
1260                                 tmp = req->req.actual;
1261
1262                         t = scnprintf(next, size,
1263                                 "\treq %p len %u/%u buf %p\n",
1264                                 &req->req, tmp, req->req.length,
1265                                 req->req.buf);
1266                         if (t <= 0 || t > size)
1267                                 goto done;
1268                         size -= t;
1269                         next += t;
1270                 }
1271         }
1272
1273 done:
1274         local_irq_restore(flags);
1275         *eof = 1;
1276         return count - size;
1277 }
1278
1279 #endif  /* CONFIG_USB_GADGET_DEBUG_FILES */
1280
1281 /*-------------------------------------------------------------------------*/
1282
1283 static void udc_reinit (struct goku_udc *dev)
1284 {
1285         static char *names [] = { "ep0", "ep1-bulk", "ep2-bulk", "ep3-bulk" };
1286         
1287         unsigned i;
1288
1289         INIT_LIST_HEAD (&dev->gadget.ep_list);
1290         dev->gadget.ep0 = &dev->ep [0].ep;
1291         dev->gadget.speed = USB_SPEED_UNKNOWN;
1292         dev->ep0state = EP0_DISCONNECT;
1293         dev->irqs = 0;
1294
1295         for (i = 0; i < 4; i++) {
1296                 struct goku_ep  *ep = &dev->ep[i];
1297
1298                 ep->num = i;
1299                 ep->ep.name = names[i];
1300                 ep->reg_fifo = &dev->regs->ep_fifo [i];
1301                 ep->reg_status = &dev->regs->ep_status [i];
1302                 ep->reg_mode = &dev->regs->ep_mode[i];
1303
1304                 ep->ep.ops = &goku_ep_ops;
1305                 list_add_tail (&ep->ep.ep_list, &dev->gadget.ep_list);
1306                 ep->dev = dev;
1307                 INIT_LIST_HEAD (&ep->queue);
1308
1309                 ep_reset(NULL, ep);
1310         }
1311
1312         dev->ep[0].reg_mode = NULL;
1313         dev->ep[0].ep.maxpacket = MAX_EP0_SIZE;
1314         list_del_init (&dev->ep[0].ep.ep_list);
1315 }
1316
1317 static void udc_reset(struct goku_udc *dev)
1318 {
1319         struct goku_udc_regs __iomem    *regs = dev->regs;
1320
1321         writel(0, &regs->power_detect);
1322         writel(0, &regs->int_enable);
1323         readl(&regs->int_enable);
1324         dev->int_enable = 0;
1325
1326         /* deassert reset, leave USB D+ at hi-Z (no pullup)
1327          * don't let INT_PWRDETECT sequence begin
1328          */
1329         udelay(250);
1330         writel(PW_RESETB, &regs->power_detect);
1331         readl(&regs->int_enable);
1332 }
1333
1334 static void ep0_start(struct goku_udc *dev)
1335 {
1336         struct goku_udc_regs __iomem    *regs = dev->regs;
1337         unsigned                        i;
1338
1339         VDBG(dev, "%s\n", __FUNCTION__);
1340
1341         udc_reset(dev);
1342         udc_reinit (dev);
1343         //writel(MST_EOPB_ENA | MST_TIMEOUT_ENA, &regs->dma_master);
1344
1345         /* hw handles set_address, set_feature, get_status; maybe more */
1346         writel(   G_REQMODE_SET_INTF | G_REQMODE_GET_INTF
1347                 | G_REQMODE_SET_CONF | G_REQMODE_GET_CONF
1348                 | G_REQMODE_GET_DESC
1349                 | G_REQMODE_CLEAR_FEAT
1350                 , &regs->reqmode);
1351
1352         for (i = 0; i < 4; i++)
1353                 dev->ep[i].irqs = 0;
1354
1355         /* can't modify descriptors after writing UsbReady */
1356         for (i = 0; i < DESC_LEN; i++)
1357                 writel(0, &regs->descriptors[i]);
1358         writel(0, &regs->UsbReady);
1359
1360         /* expect ep0 requests when the host drops reset */
1361         writel(PW_RESETB | PW_PULLUP, &regs->power_detect);
1362         dev->int_enable = INT_DEVWIDE | INT_EP0;
1363         writel(dev->int_enable, &dev->regs->int_enable);
1364         readl(&regs->int_enable);
1365         dev->gadget.speed = USB_SPEED_FULL;
1366         dev->ep0state = EP0_IDLE;
1367 }
1368
1369 static void udc_enable(struct goku_udc *dev)
1370 {
1371         /* start enumeration now, or after power detect irq */
1372         if (readl(&dev->regs->power_detect) & PW_DETECT)
1373                 ep0_start(dev);
1374         else {
1375                 DBG(dev, "%s\n", __FUNCTION__);
1376                 dev->int_enable = INT_PWRDETECT;
1377                 writel(dev->int_enable, &dev->regs->int_enable);
1378         }
1379 }
1380
1381 /*-------------------------------------------------------------------------*/
1382
1383 /* keeping it simple:
1384  * - one bus driver, initted first;
1385  * - one function driver, initted second
1386  */
1387
1388 static struct goku_udc  *the_controller;
1389
1390 /* when a driver is successfully registered, it will receive
1391  * control requests including set_configuration(), which enables
1392  * non-control requests.  then usb traffic follows until a
1393  * disconnect is reported.  then a host may connect again, or
1394  * the driver might get unbound.
1395  */
1396 int usb_gadget_register_driver(struct usb_gadget_driver *driver)
1397 {
1398         struct goku_udc *dev = the_controller;
1399         int                     retval;
1400
1401         if (!driver
1402                         || driver->speed != USB_SPEED_FULL
1403                         || !driver->bind
1404                         || !driver->disconnect
1405                         || !driver->setup)
1406                 return -EINVAL;
1407         if (!dev)
1408                 return -ENODEV;
1409         if (dev->driver)
1410                 return -EBUSY;
1411
1412         /* hook up the driver */
1413         driver->driver.bus = NULL;
1414         dev->driver = driver;
1415         dev->gadget.dev.driver = &driver->driver;
1416         retval = driver->bind(&dev->gadget);
1417         if (retval) {
1418                 DBG(dev, "bind to driver %s --> error %d\n",
1419                                 driver->driver.name, retval);
1420                 dev->driver = NULL;
1421                 dev->gadget.dev.driver = NULL;
1422                 return retval;
1423         }
1424
1425         /* then enable host detection and ep0; and we're ready
1426          * for set_configuration as well as eventual disconnect.
1427          */
1428         udc_enable(dev);
1429
1430         DBG(dev, "registered gadget driver '%s'\n", driver->driver.name);
1431         return 0;
1432 }
1433 EXPORT_SYMBOL(usb_gadget_register_driver);
1434
1435 static void
1436 stop_activity(struct goku_udc *dev, struct usb_gadget_driver *driver)
1437 {
1438         unsigned        i;
1439
1440         DBG (dev, "%s\n", __FUNCTION__);
1441
1442         if (dev->gadget.speed == USB_SPEED_UNKNOWN)
1443                 driver = NULL;
1444
1445         /* disconnect gadget driver after quiesceing hw and the driver */
1446         udc_reset (dev);
1447         for (i = 0; i < 4; i++)
1448                 nuke(&dev->ep [i], -ESHUTDOWN);
1449         if (driver) {
1450                 spin_unlock(&dev->lock);
1451                 driver->disconnect(&dev->gadget);
1452                 spin_lock(&dev->lock);
1453         }
1454
1455         if (dev->driver)
1456                 udc_enable(dev);
1457 }
1458
1459 int usb_gadget_unregister_driver(struct usb_gadget_driver *driver)
1460 {
1461         struct goku_udc *dev = the_controller;
1462         unsigned long   flags;
1463
1464         if (!dev)
1465                 return -ENODEV;
1466         if (!driver || driver != dev->driver || !driver->unbind)
1467                 return -EINVAL;
1468
1469         spin_lock_irqsave(&dev->lock, flags);
1470         dev->driver = NULL;
1471         stop_activity(dev, driver);
1472         spin_unlock_irqrestore(&dev->lock, flags);
1473
1474         driver->unbind(&dev->gadget);
1475
1476         DBG(dev, "unregistered driver '%s'\n", driver->driver.name);
1477         return 0;
1478 }
1479 EXPORT_SYMBOL(usb_gadget_unregister_driver);
1480
1481
1482 /*-------------------------------------------------------------------------*/
1483
1484 static void ep0_setup(struct goku_udc *dev)
1485 {
1486         struct goku_udc_regs __iomem    *regs = dev->regs;
1487         struct usb_ctrlrequest          ctrl;
1488         int                             tmp;
1489
1490         /* read SETUP packet and enter DATA stage */
1491         ctrl.bRequestType = readl(&regs->bRequestType);
1492         ctrl.bRequest = readl(&regs->bRequest);
1493         ctrl.wValue  = cpu_to_le16((readl(&regs->wValueH)  << 8)
1494                                         | readl(&regs->wValueL));
1495         ctrl.wIndex  = cpu_to_le16((readl(&regs->wIndexH)  << 8)
1496                                         | readl(&regs->wIndexL));
1497         ctrl.wLength = cpu_to_le16((readl(&regs->wLengthH) << 8)
1498                                         | readl(&regs->wLengthL));
1499         writel(0, &regs->SetupRecv);
1500
1501         nuke(&dev->ep[0], 0);
1502         dev->ep[0].stopped = 0;
1503         if (likely(ctrl.bRequestType & USB_DIR_IN)) {
1504                 dev->ep[0].is_in = 1;
1505                 dev->ep0state = EP0_IN;
1506                 /* detect early status stages */
1507                 writel(ICONTROL_STATUSNAK, &dev->regs->IntControl);
1508         } else {
1509                 dev->ep[0].is_in = 0;
1510                 dev->ep0state = EP0_OUT;
1511
1512                 /* NOTE:  CLEAR_FEATURE is done in software so that we can
1513                  * synchronize transfer restarts after bulk IN stalls.  data
1514                  * won't even enter the fifo until the halt is cleared.
1515                  */
1516                 switch (ctrl.bRequest) {
1517                 case USB_REQ_CLEAR_FEATURE:
1518                         switch (ctrl.bRequestType) {
1519                         case USB_RECIP_ENDPOINT:
1520                                 tmp = le16_to_cpu(ctrl.wIndex) & 0x0f;
1521                                 /* active endpoint */
1522                                 if (tmp > 3 || (!dev->ep[tmp].desc && tmp != 0))
1523                                         goto stall;
1524                                 if (ctrl.wIndex & __constant_cpu_to_le16(
1525                                                 USB_DIR_IN)) {
1526                                         if (!dev->ep[tmp].is_in)
1527                                                 goto stall;
1528                                 } else {
1529                                         if (dev->ep[tmp].is_in)
1530                                                 goto stall;
1531                                 }
1532                                 if (ctrl.wValue != __constant_cpu_to_le16(
1533                                                 USB_ENDPOINT_HALT))
1534                                         goto stall;
1535                                 if (tmp)
1536                                         goku_clear_halt(&dev->ep[tmp]);
1537 succeed:
1538                                 /* start ep0out status stage */
1539                                 writel(~(1<<0), &regs->EOP);
1540                                 dev->ep[0].stopped = 1;
1541                                 dev->ep0state = EP0_STATUS;
1542                                 return;
1543                         case USB_RECIP_DEVICE:
1544                                 /* device remote wakeup: always clear */
1545                                 if (ctrl.wValue != __constant_cpu_to_le16(1))
1546                                         goto stall;
1547                                 VDBG(dev, "clear dev remote wakeup\n");
1548                                 goto succeed;
1549                         case USB_RECIP_INTERFACE:
1550                                 goto stall;
1551                         default:                /* pass to gadget driver */
1552                                 break;
1553                         }
1554                         break;
1555                 default:
1556                         break;
1557                 }
1558         }
1559
1560 #ifdef USB_TRACE
1561         VDBG(dev, "SETUP %02x.%02x v%04x i%04x l%04x\n",
1562                 ctrl.bRequestType, ctrl.bRequest,
1563                 le16_to_cpu(ctrl.wValue), le16_to_cpu(ctrl.wIndex),
1564                 le16_to_cpu(ctrl.wLength));
1565 #endif
1566
1567         /* hw wants to know when we're configured (or not) */
1568         dev->req_config = (ctrl.bRequest == USB_REQ_SET_CONFIGURATION
1569                                 && ctrl.bRequestType == USB_RECIP_DEVICE);
1570         if (unlikely(dev->req_config))
1571                 dev->configured = (ctrl.wValue != __constant_cpu_to_le16(0));
1572
1573         /* delegate everything to the gadget driver.
1574          * it may respond after this irq handler returns.
1575          */
1576         spin_unlock (&dev->lock);
1577         tmp = dev->driver->setup(&dev->gadget, &ctrl);
1578         spin_lock (&dev->lock);
1579         if (unlikely(tmp < 0)) {
1580 stall:
1581 #ifdef USB_TRACE
1582                 VDBG(dev, "req %02x.%02x protocol STALL; err %d\n",
1583                                 ctrl.bRequestType, ctrl.bRequest, tmp);
1584 #endif
1585                 command(regs, COMMAND_STALL, 0);
1586                 dev->ep[0].stopped = 1;
1587                 dev->ep0state = EP0_STALL;
1588         }
1589
1590         /* expect at least one data or status stage irq */
1591 }
1592
1593 #define ACK(irqbit) { \
1594                 stat &= ~irqbit; \
1595                 writel(~irqbit, &regs->int_status); \
1596                 handled = 1; \
1597                 }
1598
1599 static irqreturn_t goku_irq(int irq, void *_dev)
1600 {
1601         struct goku_udc                 *dev = _dev;
1602         struct goku_udc_regs __iomem    *regs = dev->regs;
1603         struct goku_ep                  *ep;
1604         u32                             stat, handled = 0;
1605         unsigned                        i, rescans = 5;
1606
1607         spin_lock(&dev->lock);
1608
1609 rescan:
1610         stat = readl(&regs->int_status) & dev->int_enable;
1611         if (!stat)
1612                 goto done;
1613         dev->irqs++;
1614
1615         /* device-wide irqs */
1616         if (unlikely(stat & INT_DEVWIDE)) {
1617                 if (stat & INT_SYSERROR) {
1618                         ERROR(dev, "system error\n");
1619                         stop_activity(dev, dev->driver);
1620                         stat = 0;
1621                         handled = 1;
1622                         // FIXME have a neater way to prevent re-enumeration
1623                         dev->driver = NULL;
1624                         goto done;
1625                 }
1626                 if (stat & INT_PWRDETECT) {
1627                         writel(~stat, &regs->int_status);
1628                         if (readl(&dev->regs->power_detect) & PW_DETECT) {
1629                                 VDBG(dev, "connect\n");
1630                                 ep0_start(dev);
1631                         } else {
1632                                 DBG(dev, "disconnect\n");
1633                                 if (dev->gadget.speed == USB_SPEED_FULL)
1634                                         stop_activity(dev, dev->driver);
1635                                 dev->ep0state = EP0_DISCONNECT;
1636                                 dev->int_enable = INT_DEVWIDE;
1637                                 writel(dev->int_enable, &dev->regs->int_enable);
1638                         }
1639                         stat = 0;
1640                         handled = 1;
1641                         goto done;
1642                 }
1643                 if (stat & INT_SUSPEND) {
1644                         ACK(INT_SUSPEND);
1645                         if (readl(&regs->ep_status[0]) & EPxSTATUS_SUSPEND) {
1646                                 switch (dev->ep0state) {
1647                                 case EP0_DISCONNECT:
1648                                 case EP0_SUSPEND:
1649                                         goto pm_next;
1650                                 default:
1651                                         break;
1652                                 }
1653                                 DBG(dev, "USB suspend\n");
1654                                 dev->ep0state = EP0_SUSPEND;
1655                                 if (dev->gadget.speed != USB_SPEED_UNKNOWN
1656                                                 && dev->driver
1657                                                 && dev->driver->suspend) {
1658                                         spin_unlock(&dev->lock);
1659                                         dev->driver->suspend(&dev->gadget);
1660                                         spin_lock(&dev->lock);
1661                                 }
1662                         } else {
1663                                 if (dev->ep0state != EP0_SUSPEND) {
1664                                         DBG(dev, "bogus USB resume %d\n",
1665                                                 dev->ep0state);
1666                                         goto pm_next;
1667                                 }
1668                                 DBG(dev, "USB resume\n");
1669                                 dev->ep0state = EP0_IDLE;
1670                                 if (dev->gadget.speed != USB_SPEED_UNKNOWN
1671                                                 && dev->driver
1672                                                 && dev->driver->resume) {
1673                                         spin_unlock(&dev->lock);
1674                                         dev->driver->resume(&dev->gadget);
1675                                         spin_lock(&dev->lock);
1676                                 }
1677                         }
1678                 }
1679 pm_next:
1680                 if (stat & INT_USBRESET) {              /* hub reset done */
1681                         ACK(INT_USBRESET);
1682                         INFO(dev, "USB reset done, gadget %s\n",
1683                                 dev->driver->driver.name);
1684                 }
1685                 // and INT_ERR on some endpoint's crc/bitstuff/... problem
1686         }
1687
1688         /* progress ep0 setup, data, or status stages.
1689          * no transition {EP0_STATUS, EP0_STALL} --> EP0_IDLE; saves irqs
1690          */
1691         if (stat & INT_SETUP) {
1692                 ACK(INT_SETUP);
1693                 dev->ep[0].irqs++;
1694                 ep0_setup(dev);
1695         }
1696         if (stat & INT_STATUSNAK) {
1697                 ACK(INT_STATUSNAK|INT_ENDPOINT0);
1698                 if (dev->ep0state == EP0_IN) {
1699                         ep = &dev->ep[0];
1700                         ep->irqs++;
1701                         nuke(ep, 0);
1702                         writel(~(1<<0), &regs->EOP);
1703                         dev->ep0state = EP0_STATUS;
1704                 }
1705         }
1706         if (stat & INT_ENDPOINT0) {
1707                 ACK(INT_ENDPOINT0);
1708                 ep = &dev->ep[0];
1709                 ep->irqs++;
1710                 pio_advance(ep);
1711         }
1712
1713         /* dma completion */
1714         if (stat & INT_MSTRDEND) {      /* IN */
1715                 ACK(INT_MSTRDEND);
1716                 ep = &dev->ep[UDC_MSTRD_ENDPOINT];
1717                 ep->irqs++;
1718                 dma_advance(dev, ep);
1719         }
1720         if (stat & INT_MSTWREND) {      /* OUT */
1721                 ACK(INT_MSTWREND);
1722                 ep = &dev->ep[UDC_MSTWR_ENDPOINT];
1723                 ep->irqs++;
1724                 dma_advance(dev, ep);
1725         }
1726         if (stat & INT_MSTWRTMOUT) {    /* OUT */
1727                 ACK(INT_MSTWRTMOUT);
1728                 ep = &dev->ep[UDC_MSTWR_ENDPOINT];
1729                 ep->irqs++;
1730                 ERROR(dev, "%s write timeout ?\n", ep->ep.name);
1731                 // reset dma? then dma_advance()
1732         }
1733
1734         /* pio */
1735         for (i = 1; i < 4; i++) {
1736                 u32             tmp = INT_EPxDATASET(i);
1737
1738                 if (!(stat & tmp))
1739                         continue;
1740                 ep = &dev->ep[i];
1741                 pio_advance(ep);
1742                 if (list_empty (&ep->queue))
1743                         pio_irq_disable(dev, regs, i);
1744                 stat &= ~tmp;
1745                 handled = 1;
1746                 ep->irqs++;
1747         }
1748
1749         if (rescans--)
1750                 goto rescan;
1751
1752 done:
1753         (void)readl(&regs->int_enable);
1754         spin_unlock(&dev->lock);
1755         if (stat)
1756                 DBG(dev, "unhandled irq status: %05x (%05x, %05x)\n", stat,
1757                                 readl(&regs->int_status), dev->int_enable);
1758         return IRQ_RETVAL(handled);
1759 }
1760
1761 #undef ACK
1762
1763 /*-------------------------------------------------------------------------*/
1764
1765 static void gadget_release(struct device *_dev)
1766 {
1767         struct goku_udc *dev = dev_get_drvdata(_dev);
1768
1769         kfree(dev);
1770 }
1771
1772 /* tear down the binding between this driver and the pci device */
1773
1774 static void goku_remove(struct pci_dev *pdev)
1775 {
1776         struct goku_udc         *dev = pci_get_drvdata(pdev);
1777
1778         DBG(dev, "%s\n", __FUNCTION__);
1779
1780         BUG_ON(dev->driver);
1781
1782 #ifdef CONFIG_USB_GADGET_DEBUG_FILES
1783         remove_proc_entry(proc_node_name, NULL);
1784 #endif
1785         if (dev->regs)
1786                 udc_reset(dev);
1787         if (dev->got_irq)
1788                 free_irq(pdev->irq, dev);
1789         if (dev->regs)
1790                 iounmap(dev->regs);
1791         if (dev->got_region)
1792                 release_mem_region(pci_resource_start (pdev, 0),
1793                                 pci_resource_len (pdev, 0));
1794         if (dev->enabled)
1795                 pci_disable_device(pdev);
1796         device_unregister(&dev->gadget.dev);
1797
1798         pci_set_drvdata(pdev, NULL);
1799         dev->regs = NULL;
1800         the_controller = NULL;
1801
1802         INFO(dev, "unbind\n");
1803 }
1804
1805 /* wrap this driver around the specified pci device, but
1806  * don't respond over USB until a gadget driver binds to us.
1807  */
1808
1809 static int goku_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1810 {
1811         struct goku_udc         *dev = NULL;
1812         unsigned long           resource, len;
1813         void __iomem            *base = NULL;
1814         int                     retval;
1815
1816         /* if you want to support more than one controller in a system,
1817          * usb_gadget_driver_{register,unregister}() must change.
1818          */
1819         if (the_controller) {
1820                 WARN(dev, "ignoring %s\n", pci_name(pdev));
1821                 return -EBUSY;
1822         }
1823         if (!pdev->irq) {
1824                 printk(KERN_ERR "Check PCI %s IRQ setup!\n", pci_name(pdev));
1825                 retval = -ENODEV;
1826                 goto done;
1827         }
1828
1829         /* alloc, and start init */
1830         dev = kmalloc (sizeof *dev, GFP_KERNEL);
1831         if (dev == NULL){
1832                 pr_debug("enomem %s\n", pci_name(pdev));
1833                 retval = -ENOMEM;
1834                 goto done;
1835         }
1836
1837         memset(dev, 0, sizeof *dev);
1838         spin_lock_init(&dev->lock);
1839         dev->pdev = pdev;
1840         dev->gadget.ops = &goku_ops;
1841
1842         /* the "gadget" abstracts/virtualizes the controller */
1843         strcpy(dev->gadget.dev.bus_id, "gadget");
1844         dev->gadget.dev.parent = &pdev->dev;
1845         dev->gadget.dev.dma_mask = pdev->dev.dma_mask;
1846         dev->gadget.dev.release = gadget_release;
1847         dev->gadget.name = driver_name;
1848
1849         /* now all the pci goodies ... */
1850         retval = pci_enable_device(pdev);
1851         if (retval < 0) {
1852                 DBG(dev, "can't enable, %d\n", retval);
1853                 goto done;
1854         }
1855         dev->enabled = 1;
1856
1857         resource = pci_resource_start(pdev, 0);
1858         len = pci_resource_len(pdev, 0);
1859         if (!request_mem_region(resource, len, driver_name)) {
1860                 DBG(dev, "controller already in use\n");
1861                 retval = -EBUSY;
1862                 goto done;
1863         }
1864         dev->got_region = 1;
1865
1866         base = ioremap_nocache(resource, len);
1867         if (base == NULL) {
1868                 DBG(dev, "can't map memory\n");
1869                 retval = -EFAULT;
1870                 goto done;
1871         }
1872         dev->regs = (struct goku_udc_regs __iomem *) base;
1873
1874         pci_set_drvdata(pdev, dev);
1875         INFO(dev, "%s\n", driver_desc);
1876         INFO(dev, "version: " DRIVER_VERSION " %s\n", dmastr());
1877         INFO(dev, "irq %d, pci mem %p\n", pdev->irq, base);
1878
1879         /* init to known state, then setup irqs */
1880         udc_reset(dev);
1881         udc_reinit (dev);
1882         if (request_irq(pdev->irq, goku_irq, IRQF_SHARED/*|IRQF_SAMPLE_RANDOM*/,
1883                         driver_name, dev) != 0) {
1884                 DBG(dev, "request interrupt %d failed\n", pdev->irq);
1885                 retval = -EBUSY;
1886                 goto done;
1887         }
1888         dev->got_irq = 1;
1889         if (use_dma)
1890                 pci_set_master(pdev);
1891
1892
1893 #ifdef CONFIG_USB_GADGET_DEBUG_FILES
1894         create_proc_read_entry(proc_node_name, 0, NULL, udc_proc_read, dev);
1895 #endif
1896
1897         /* done */
1898         the_controller = dev;
1899         device_register(&dev->gadget.dev);
1900
1901         return 0;
1902
1903 done:
1904         if (dev)
1905                 goku_remove (pdev);
1906         return retval;
1907 }
1908
1909
1910 /*-------------------------------------------------------------------------*/
1911
1912 static struct pci_device_id pci_ids [] = { {
1913         .class =        ((PCI_CLASS_SERIAL_USB << 8) | 0xfe),
1914         .class_mask =   ~0,
1915         .vendor =       0x102f,         /* Toshiba */
1916         .device =       0x0107,         /* this UDC */
1917         .subvendor =    PCI_ANY_ID,
1918         .subdevice =    PCI_ANY_ID,
1919
1920 }, { /* end: all zeroes */ }
1921 };
1922 MODULE_DEVICE_TABLE (pci, pci_ids);
1923
1924 static struct pci_driver goku_pci_driver = {
1925         .name =         (char *) driver_name,
1926         .id_table =     pci_ids,
1927
1928         .probe =        goku_probe,
1929         .remove =       goku_remove,
1930
1931         /* FIXME add power management support */
1932 };
1933
1934 static int __init init (void)
1935 {
1936         return pci_register_driver (&goku_pci_driver);
1937 }
1938 module_init (init);
1939
1940 static void __exit cleanup (void)
1941 {
1942         pci_unregister_driver (&goku_pci_driver);
1943 }
1944 module_exit (cleanup);