ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / usb / gadget / zero.c
1 /*
2  * zero.c -- Gadget Zero, for USB development
3  *
4  * Copyright (C) 2003-2004 David Brownell
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, and the following disclaimer,
12  *    without modification.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The names of the above-listed copyright holders may not be used
17  *    to endorse or promote products derived from this software without
18  *    specific prior written permission.
19  *
20  * ALTERNATIVELY, this software may be distributed under the terms of the
21  * GNU General Public License ("GPL") as published by the Free Software
22  * Foundation, either version 2 of that License or (at your option) any
23  * later version.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
26  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
27  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
29  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37
38
39 /*
40  * Gadget Zero only needs two bulk endpoints, and is an example of how you
41  * can write a hardware-agnostic gadget driver running inside a USB device.
42  *
43  * Hardware details are visible (see CONFIG_USB_ZERO_* below) but don't
44  * affect most of the driver.
45  *
46  * Use it with the Linux host/master side "usbtest" driver to get a basic
47  * functional test of your device-side usb stack, or with "usb-skeleton".
48  *
49  * It supports two similar configurations.  One sinks whatever the usb host
50  * writes, and in return sources zeroes.  The other loops whatever the host
51  * writes back, so the host can read it.  Module options include:
52  *
53  *   buflen=N           default N=4096, buffer size used
54  *   qlen=N             default N=32, how many buffers in the loopback queue
55  *   loopdefault        default false, list loopback config first
56  *
57  * Many drivers will only have one configuration, letting them be much
58  * simpler if they also don't support high speed operation (like this
59  * driver does).
60  */
61
62 #define DEBUG 1
63 // #define VERBOSE
64
65 #include <linux/config.h>
66 #include <linux/module.h>
67 #include <linux/kernel.h>
68 #include <linux/delay.h>
69 #include <linux/ioport.h>
70 #include <linux/sched.h>
71 #include <linux/slab.h>
72 #include <linux/smp_lock.h>
73 #include <linux/errno.h>
74 #include <linux/init.h>
75 #include <linux/timer.h>
76 #include <linux/list.h>
77 #include <linux/interrupt.h>
78 #include <linux/uts.h>
79 #include <linux/version.h>
80 #include <linux/device.h>
81 #include <linux/moduleparam.h>
82
83 #include <asm/byteorder.h>
84 #include <asm/io.h>
85 #include <asm/irq.h>
86 #include <asm/system.h>
87 #include <asm/unaligned.h>
88
89 #include <linux/usb_ch9.h>
90 #include <linux/usb_gadget.h>
91
92 #include "gadget_chips.h"
93
94
95 /*-------------------------------------------------------------------------*/
96
97 #define DRIVER_VERSION          "St Patrick's Day 2004"
98
99 static const char shortname [] = "zero";
100 static const char longname [] = "Gadget Zero";
101
102 static const char source_sink [] = "source and sink data";
103 static const char loopback [] = "loop input to output";
104
105 /*-------------------------------------------------------------------------*/
106
107 /*
108  * driver assumes self-powered hardware, and
109  * has no way for users to trigger remote wakeup.
110  *
111  * this version autoconfigures as much as possible,
112  * which is reasonable for most "bulk-only" drivers.
113  */
114 static const char *EP_IN_NAME;          /* source */
115 static const char *EP_OUT_NAME;         /* sink */
116
117 /*-------------------------------------------------------------------------*/
118
119 /* big enough to hold our biggest descriptor */
120 #define USB_BUFSIZ      256
121
122 struct zero_dev {
123         spinlock_t              lock;
124         struct usb_gadget       *gadget;
125         struct usb_request      *req;           /* for control responses */
126
127         /* when configured, we have one of two configs:
128          * - source data (in to host) and sink it (out from host)
129          * - or loop it back (out from host back in to host)
130          */
131         u8                      config;
132         struct usb_ep           *in_ep, *out_ep;
133 };
134
135 #define xprintk(d,level,fmt,args...) \
136         dev_printk(level , &(d)->gadget->dev , fmt , ## args)
137
138 #ifdef DEBUG
139 #define DBG(dev,fmt,args...) \
140         xprintk(dev , KERN_DEBUG , fmt , ## args)
141 #else
142 #define DBG(dev,fmt,args...) \
143         do { } while (0)
144 #endif /* DEBUG */
145
146 #ifdef VERBOSE
147 #define VDBG    DBG
148 #else
149 #define VDBG(dev,fmt,args...) \
150         do { } while (0)
151 #endif /* VERBOSE */
152
153 #define ERROR(dev,fmt,args...) \
154         xprintk(dev , KERN_ERR , fmt , ## args)
155 #define WARN(dev,fmt,args...) \
156         xprintk(dev , KERN_WARNING , fmt , ## args)
157 #define INFO(dev,fmt,args...) \
158         xprintk(dev , KERN_INFO , fmt , ## args)
159
160 /*-------------------------------------------------------------------------*/
161
162 static unsigned buflen = 4096;
163 static unsigned qlen = 32;
164 static unsigned pattern = 0;
165
166 module_param (buflen, uint, S_IRUGO|S_IWUSR);
167 module_param (qlen, uint, S_IRUGO|S_IWUSR);
168 module_param (pattern, uint, S_IRUGO|S_IWUSR);
169
170
171 /*
172  * Normally the "loopback" configuration is second (index 1) so
173  * it's not the default.  Here's where to change that order, to
174  * work better with hosts where config changes are problematic.
175  * Or controllers (like superh) that only support one config.
176  */
177 static int loopdefault = 0;
178
179 module_param (loopdefault, bool, S_IRUGO|S_IWUSR);
180
181 /*-------------------------------------------------------------------------*/
182
183 /* Thanks to NetChip Technologies for donating this product ID.
184  *
185  * DO NOT REUSE THESE IDs with a protocol-incompatible driver!!  Ever!!
186  * Instead:  allocate your own, using normal USB-IF procedures.
187  */
188 #define DRIVER_VENDOR_NUM       0x0525          /* NetChip */
189 #define DRIVER_PRODUCT_NUM      0xa4a0          /* Linux-USB "Gadget Zero" */
190
191 /*-------------------------------------------------------------------------*/
192
193 /*
194  * DESCRIPTORS ... most are static, but strings and (full)
195  * configuration descriptors are built on demand.
196  */
197
198 #define STRING_MANUFACTURER             25
199 #define STRING_PRODUCT                  42
200 #define STRING_SERIAL                   101
201 #define STRING_SOURCE_SINK              250
202 #define STRING_LOOPBACK                 251
203
204 /*
205  * This device advertises two configurations; these numbers work
206  * on a pxa250 as well as more flexible hardware.
207  */
208 #define CONFIG_SOURCE_SINK      3
209 #define CONFIG_LOOPBACK         2
210
211 static struct usb_device_descriptor
212 device_desc = {
213         .bLength =              sizeof device_desc,
214         .bDescriptorType =      USB_DT_DEVICE,
215
216         .bcdUSB =               __constant_cpu_to_le16 (0x0200),
217         .bDeviceClass =         USB_CLASS_VENDOR_SPEC,
218
219         .idVendor =             __constant_cpu_to_le16 (DRIVER_VENDOR_NUM),
220         .idProduct =            __constant_cpu_to_le16 (DRIVER_PRODUCT_NUM),
221         .iManufacturer =        STRING_MANUFACTURER,
222         .iProduct =             STRING_PRODUCT,
223         .iSerialNumber =        STRING_SERIAL,
224         .bNumConfigurations =   2,
225 };
226
227 static const struct usb_config_descriptor
228 source_sink_config = {
229         .bLength =              sizeof source_sink_config,
230         .bDescriptorType =      USB_DT_CONFIG,
231
232         /* compute wTotalLength on the fly */
233         .bNumInterfaces =       1,
234         .bConfigurationValue =  CONFIG_SOURCE_SINK,
235         .iConfiguration =       STRING_SOURCE_SINK,
236         .bmAttributes =         USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
237         .bMaxPower =            1,      /* self-powered */
238 };
239
240 static const struct usb_config_descriptor
241 loopback_config = {
242         .bLength =              sizeof loopback_config,
243         .bDescriptorType =      USB_DT_CONFIG,
244
245         /* compute wTotalLength on the fly */
246         .bNumInterfaces =       1,
247         .bConfigurationValue =  CONFIG_LOOPBACK,
248         .iConfiguration =       STRING_LOOPBACK,
249         .bmAttributes =         USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
250         .bMaxPower =            1,      /* self-powered */
251 };
252
253 /* one interface in each configuration */
254
255 static const struct usb_interface_descriptor
256 source_sink_intf = {
257         .bLength =              sizeof source_sink_intf,
258         .bDescriptorType =      USB_DT_INTERFACE,
259
260         .bNumEndpoints =        2,
261         .bInterfaceClass =      USB_CLASS_VENDOR_SPEC,
262         .iInterface =           STRING_SOURCE_SINK,
263 };
264
265 static const struct usb_interface_descriptor
266 loopback_intf = {
267         .bLength =              sizeof loopback_intf,
268         .bDescriptorType =      USB_DT_INTERFACE,
269
270         .bNumEndpoints =        2,
271         .bInterfaceClass =      USB_CLASS_VENDOR_SPEC,
272         .iInterface =           STRING_LOOPBACK,
273 };
274
275 /* two full speed bulk endpoints; their use is config-dependent */
276
277 static struct usb_endpoint_descriptor
278 fs_source_desc = {
279         .bLength =              USB_DT_ENDPOINT_SIZE,
280         .bDescriptorType =      USB_DT_ENDPOINT,
281
282         .bEndpointAddress =     USB_DIR_IN,
283         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
284 };
285
286 static struct usb_endpoint_descriptor
287 fs_sink_desc = {
288         .bLength =              USB_DT_ENDPOINT_SIZE,
289         .bDescriptorType =      USB_DT_ENDPOINT,
290
291         .bEndpointAddress =     USB_DIR_OUT,
292         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
293 };
294
295 static const struct usb_descriptor_header *fs_source_sink_function [] = {
296         (struct usb_descriptor_header *) &source_sink_intf,
297         (struct usb_descriptor_header *) &fs_sink_desc,
298         (struct usb_descriptor_header *) &fs_source_desc,
299         0,
300 };
301
302 static const struct usb_descriptor_header *fs_loopback_function [] = {
303         (struct usb_descriptor_header *) &loopback_intf,
304         (struct usb_descriptor_header *) &fs_sink_desc,
305         (struct usb_descriptor_header *) &fs_source_desc,
306         0,
307 };
308
309 #ifdef  CONFIG_USB_GADGET_DUALSPEED
310
311 /*
312  * usb 2.0 devices need to expose both high speed and full speed
313  * descriptors, unless they only run at full speed.
314  *
315  * that means alternate endpoint descriptors (bigger packets)
316  * and a "device qualifier" ... plus more construction options
317  * for the config descriptor.
318  */
319
320 static struct usb_endpoint_descriptor
321 hs_source_desc = {
322         .bLength =              USB_DT_ENDPOINT_SIZE,
323         .bDescriptorType =      USB_DT_ENDPOINT,
324
325         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
326         .wMaxPacketSize =       __constant_cpu_to_le16 (512),
327 };
328
329 static struct usb_endpoint_descriptor
330 hs_sink_desc = {
331         .bLength =              USB_DT_ENDPOINT_SIZE,
332         .bDescriptorType =      USB_DT_ENDPOINT,
333
334         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
335         .wMaxPacketSize =       __constant_cpu_to_le16 (512),
336 };
337
338 static struct usb_qualifier_descriptor
339 dev_qualifier = {
340         .bLength =              sizeof dev_qualifier,
341         .bDescriptorType =      USB_DT_DEVICE_QUALIFIER,
342
343         .bcdUSB =               __constant_cpu_to_le16 (0x0200),
344         .bDeviceClass =         USB_CLASS_VENDOR_SPEC,
345
346         .bNumConfigurations =   2,
347 };
348
349 static const struct usb_descriptor_header *hs_source_sink_function [] = {
350         (struct usb_descriptor_header *) &source_sink_intf,
351         (struct usb_descriptor_header *) &hs_source_desc,
352         (struct usb_descriptor_header *) &hs_sink_desc,
353         0,
354 };
355
356 static const struct usb_descriptor_header *hs_loopback_function [] = {
357         (struct usb_descriptor_header *) &loopback_intf,
358         (struct usb_descriptor_header *) &hs_source_desc,
359         (struct usb_descriptor_header *) &hs_sink_desc,
360         0,
361 };
362
363 /* maxpacket and other transfer characteristics vary by speed. */
364 #define ep_desc(g,hs,fs) (((g)->speed==USB_SPEED_HIGH)?(hs):(fs))
365
366 #else
367
368 /* if there's no high speed support, maxpacket doesn't change. */
369 #define ep_desc(g,hs,fs) fs
370
371 #endif  /* !CONFIG_USB_GADGET_DUALSPEED */
372
373 static char                             manufacturer [40];
374 static char                             serial [40];
375
376 /* static strings, in iso 8859/1 */
377 static struct usb_string                strings [] = {
378         { STRING_MANUFACTURER, manufacturer, },
379         { STRING_PRODUCT, longname, },
380         { STRING_SERIAL, serial, },
381         { STRING_LOOPBACK, loopback, },
382         { STRING_SOURCE_SINK, source_sink, },
383         {  }                    /* end of list */
384 };
385
386 static struct usb_gadget_strings        stringtab = {
387         .language       = 0x0409,       /* en-us */
388         .strings        = strings,
389 };
390
391 /*
392  * config descriptors are also handcrafted.  these must agree with code
393  * that sets configurations, and with code managing interfaces and their
394  * altsettings.  other complexity may come from:
395  *
396  *  - high speed support, including "other speed config" rules
397  *  - multiple configurations
398  *  - interfaces with alternate settings
399  *  - embedded class or vendor-specific descriptors
400  *
401  * this handles high speed, and has a second config that could as easily
402  * have been an alternate interface setting (on most hardware).
403  *
404  * NOTE:  to demonstrate (and test) more USB capabilities, this driver
405  * should include an altsetting to test interrupt transfers, including
406  * high bandwidth modes at high speed.  (Maybe work like Intel's test
407  * device?)
408  */
409 static int
410 config_buf (struct usb_gadget *gadget,
411                 u8 *buf, u8 type, unsigned index)
412 {
413         int                             is_source_sink;
414         int                             len;
415         const struct usb_descriptor_header **function;
416 #ifdef CONFIG_USB_GADGET_DUALSPEED
417         int                             hs = (gadget->speed == USB_SPEED_HIGH);
418 #endif
419
420         /* two configurations will always be index 0 and index 1 */
421         if (index > 1)
422                 return -EINVAL;
423         is_source_sink = loopdefault ? (index == 1) : (index == 0);
424
425 #ifdef CONFIG_USB_GADGET_DUALSPEED
426         if (type == USB_DT_OTHER_SPEED_CONFIG)
427                 hs = !hs;
428         if (hs)
429                 function = is_source_sink
430                         ? hs_source_sink_function
431                         : hs_loopback_function;
432         else
433 #endif
434                 function = is_source_sink
435                         ? fs_source_sink_function
436                         : fs_loopback_function;
437
438         len = usb_gadget_config_buf (is_source_sink
439                                         ? &source_sink_config
440                                         : &loopback_config,
441                         buf, USB_BUFSIZ, function);
442         if (len < 0)
443                 return len;
444         ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
445         return len;
446 }
447
448 /*-------------------------------------------------------------------------*/
449
450 static struct usb_request *
451 alloc_ep_req (struct usb_ep *ep, unsigned length)
452 {
453         struct usb_request      *req;
454
455         req = usb_ep_alloc_request (ep, GFP_ATOMIC);
456         if (req) {
457                 req->length = length;
458                 req->buf = usb_ep_alloc_buffer (ep, length,
459                                 &req->dma, GFP_ATOMIC);
460                 if (!req->buf) {
461                         usb_ep_free_request (ep, req);
462                         req = 0;
463                 }
464         }
465         return req;
466 }
467
468 static void free_ep_req (struct usb_ep *ep, struct usb_request *req)
469 {
470         if (req->buf)
471                 usb_ep_free_buffer (ep, req->buf, req->dma, req->length);
472         usb_ep_free_request (ep, req);
473 }
474
475 /*-------------------------------------------------------------------------*/
476
477 /* optionally require specific source/sink data patterns  */
478
479 static inline int
480 check_read_data (
481         struct zero_dev         *dev,
482         struct usb_ep           *ep,
483         struct usb_request      *req
484 )
485 {
486         unsigned        i;
487         u8              *buf = req->buf;
488
489         for (i = 0; i < req->actual; i++, buf++) {
490                 switch (pattern) {
491                 /* all-zeroes has no synchronization issues */
492                 case 0:
493                         if (*buf == 0)
494                                 continue;
495                         break;
496                 /* mod63 stays in sync with short-terminated transfers,
497                  * or otherwise when host and gadget agree on how large
498                  * each usb transfer request should be.  resync is done
499                  * with set_interface or set_config.
500                  */
501                 case 1:
502                         if (*buf == (u8)(i % 63))
503                                 continue;
504                         break;
505                 }
506                 ERROR (dev, "bad OUT byte, buf [%d] = %d\n", i, *buf);
507                 usb_ep_set_halt (ep);
508                 return -EINVAL;
509         }
510         return 0;
511 }
512
513 static inline void
514 reinit_write_data (
515         struct zero_dev         *dev,
516         struct usb_ep           *ep,
517         struct usb_request      *req
518 )
519 {
520         unsigned        i;
521         u8              *buf = req->buf;
522
523         switch (pattern) {
524         case 0:
525                 memset (req->buf, 0, req->length);
526                 break;
527         case 1:
528                 for  (i = 0; i < req->length; i++)
529                         *buf++ = (u8) (i % 63);
530                 break;
531         }
532 }
533
534 /* if there is only one request in the queue, there'll always be an
535  * irq delay between end of one request and start of the next.
536  * that prevents using hardware dma queues.
537  */
538 static void source_sink_complete (struct usb_ep *ep, struct usb_request *req)
539 {
540         struct zero_dev *dev = ep->driver_data;
541         int             status = req->status;
542
543         switch (status) {
544
545         case 0:                         /* normal completion? */
546                 if (ep == dev->out_ep)
547                         check_read_data (dev, ep, req);
548                 else
549                         reinit_write_data (dev, ep, req);
550                 break;
551
552         /* this endpoint is normally active while we're configured */
553         case -ECONNABORTED:             /* hardware forced ep reset */
554         case -ECONNRESET:               /* request dequeued */
555         case -ESHUTDOWN:                /* disconnect from host */
556                 VDBG (dev, "%s gone (%d), %d/%d\n", ep->name, status,
557                                 req->actual, req->length);
558                 if (ep == dev->out_ep)
559                         check_read_data (dev, ep, req);
560                 free_ep_req (ep, req);
561                 return;
562
563         case -EOVERFLOW:                /* buffer overrun on read means that
564                                          * we didn't provide a big enough
565                                          * buffer.
566                                          */
567         default:
568 #if 1
569                 DBG (dev, "%s complete --> %d, %d/%d\n", ep->name,
570                                 status, req->actual, req->length);
571 #endif
572         case -EREMOTEIO:                /* short read */
573                 break;
574         }
575
576         status = usb_ep_queue (ep, req, GFP_ATOMIC);
577         if (status) {
578                 ERROR (dev, "kill %s:  resubmit %d bytes --> %d\n",
579                                 ep->name, req->length, status);
580                 usb_ep_set_halt (ep);
581                 /* FIXME recover later ... somehow */
582         }
583 }
584
585 static struct usb_request *
586 source_sink_start_ep (struct usb_ep *ep, int gfp_flags)
587 {
588         struct usb_request      *req;
589         int                     status;
590
591         req = alloc_ep_req (ep, buflen);
592         if (!req)
593                 return 0;
594
595         memset (req->buf, 0, req->length);
596         req->complete = source_sink_complete;
597
598         if (strcmp (ep->name, EP_IN_NAME) == 0)
599                 reinit_write_data (ep->driver_data, ep, req);
600
601         status = usb_ep_queue (ep, req, gfp_flags);
602         if (status) {
603                 struct zero_dev *dev = ep->driver_data;
604
605                 ERROR (dev, "start %s --> %d\n", ep->name, status);
606                 free_ep_req (ep, req);
607                 req = 0;
608         }
609
610         return req;
611 }
612
613 static int
614 set_source_sink_config (struct zero_dev *dev, int gfp_flags)
615 {
616         int                     result = 0;
617         struct usb_ep           *ep;
618         struct usb_gadget       *gadget = dev->gadget;
619
620         gadget_for_each_ep (ep, gadget) {
621                 const struct usb_endpoint_descriptor    *d;
622
623                 /* one endpoint writes (sources) zeroes in (to the host) */
624                 if (strcmp (ep->name, EP_IN_NAME) == 0) {
625                         d = ep_desc (gadget, &hs_source_desc, &fs_source_desc);
626                         result = usb_ep_enable (ep, d);
627                         if (result == 0) {
628                                 ep->driver_data = dev;
629                                 if (source_sink_start_ep (ep, gfp_flags) != 0) {
630                                         dev->in_ep = ep;
631                                         continue;
632                                 }
633                                 usb_ep_disable (ep);
634                                 result = -EIO;
635                         }
636
637                 /* one endpoint reads (sinks) anything out (from the host) */
638                 } else if (strcmp (ep->name, EP_OUT_NAME) == 0) {
639                         d = ep_desc (gadget, &hs_sink_desc, &fs_sink_desc);
640                         result = usb_ep_enable (ep, d);
641                         if (result == 0) {
642                                 ep->driver_data = dev;
643                                 if (source_sink_start_ep (ep, gfp_flags) != 0) {
644                                         dev->out_ep = ep;
645                                         continue;
646                                 }
647                                 usb_ep_disable (ep);
648                                 result = -EIO;
649                         }
650
651                 /* ignore any other endpoints */
652                 } else
653                         continue;
654
655                 /* stop on error */
656                 ERROR (dev, "can't start %s, result %d\n", ep->name, result);
657                 break;
658         }
659         if (result == 0)
660                 DBG (dev, "buflen %d\n", buflen);
661
662         /* caller is responsible for cleanup on error */
663         return result;
664 }
665
666 /*-------------------------------------------------------------------------*/
667
668 static void loopback_complete (struct usb_ep *ep, struct usb_request *req)
669 {
670         struct zero_dev *dev = ep->driver_data;
671         int             status = req->status;
672
673         switch (status) {
674
675         case 0:                         /* normal completion? */
676                 if (ep == dev->out_ep) {
677                         /* loop this OUT packet back IN to the host */
678                         req->zero = (req->actual < req->length);
679                         req->length = req->actual;
680                         status = usb_ep_queue (dev->in_ep, req, GFP_ATOMIC);
681                         if (status == 0)
682                                 return;
683
684                         /* "should never get here" */
685                         ERROR (dev, "can't loop %s to %s: %d\n",
686                                 ep->name, dev->in_ep->name,
687                                 status);
688                 }
689
690                 /* queue the buffer for some later OUT packet */
691                 req->length = buflen;
692                 status = usb_ep_queue (dev->out_ep, req, GFP_ATOMIC);
693                 if (status == 0)
694                         return;
695
696                 /* "should never get here" */
697                 /* FALLTHROUGH */
698
699         default:
700                 ERROR (dev, "%s loop complete --> %d, %d/%d\n", ep->name,
701                                 status, req->actual, req->length);
702                 /* FALLTHROUGH */
703
704         /* NOTE:  since this driver doesn't maintain an explicit record
705          * of requests it submitted (just maintains qlen count), we
706          * rely on the hardware driver to clean up on disconnect or
707          * endpoint disable.
708          */
709         case -ECONNABORTED:             /* hardware forced ep reset */
710         case -ECONNRESET:               /* request dequeued */
711         case -ESHUTDOWN:                /* disconnect from host */
712                 free_ep_req (ep, req);
713                 return;
714         }
715 }
716
717 static int
718 set_loopback_config (struct zero_dev *dev, int gfp_flags)
719 {
720         int                     result = 0;
721         struct usb_ep           *ep;
722         struct usb_gadget       *gadget = dev->gadget;
723
724         gadget_for_each_ep (ep, gadget) {
725                 const struct usb_endpoint_descriptor    *d;
726
727                 /* one endpoint writes data back IN to the host */
728                 if (strcmp (ep->name, EP_IN_NAME) == 0) {
729                         d = ep_desc (gadget, &hs_source_desc, &fs_source_desc);
730                         result = usb_ep_enable (ep, d);
731                         if (result == 0) {
732                                 ep->driver_data = dev;
733                                 dev->in_ep = ep;
734                                 continue;
735                         }
736
737                 /* one endpoint just reads OUT packets */
738                 } else if (strcmp (ep->name, EP_OUT_NAME) == 0) {
739                         d = ep_desc (gadget, &hs_sink_desc, &fs_sink_desc);
740                         result = usb_ep_enable (ep, d);
741                         if (result == 0) {
742                                 ep->driver_data = dev;
743                                 dev->out_ep = ep;
744                                 continue;
745                         }
746
747                 /* ignore any other endpoints */
748                 } else
749                         continue;
750
751                 /* stop on error */
752                 ERROR (dev, "can't enable %s, result %d\n", ep->name, result);
753                 break;
754         }
755
756         /* allocate a bunch of read buffers and queue them all at once.
757          * we buffer at most 'qlen' transfers; fewer if any need more
758          * than 'buflen' bytes each.
759          */
760         if (result == 0) {
761                 struct usb_request      *req;
762                 unsigned                i;
763
764                 ep = dev->out_ep;
765                 for (i = 0; i < qlen && result == 0; i++) {
766                         req = alloc_ep_req (ep, buflen);
767                         if (req) {
768                                 req->complete = loopback_complete;
769                                 result = usb_ep_queue (ep, req, GFP_ATOMIC);
770                                 if (result)
771                                         DBG (dev, "%s queue req --> %d\n",
772                                                         ep->name, result);
773                         } else
774                                 result = -ENOMEM;
775                 }
776         }
777         if (result == 0)
778                 DBG (dev, "qlen %d, buflen %d\n", qlen, buflen);
779
780         /* caller is responsible for cleanup on error */
781         return result;
782 }
783
784 /*-------------------------------------------------------------------------*/
785
786 static void zero_reset_config (struct zero_dev *dev)
787 {
788         if (dev->config == 0)
789                 return;
790
791         DBG (dev, "reset config\n");
792
793         /* just disable endpoints, forcing completion of pending i/o.
794          * all our completion handlers free their requests in this case.
795          */
796         if (dev->in_ep) {
797                 usb_ep_disable (dev->in_ep);
798                 dev->in_ep = 0;
799         }
800         if (dev->out_ep) {
801                 usb_ep_disable (dev->out_ep);
802                 dev->out_ep = 0;
803         }
804         dev->config = 0;
805 }
806
807 /* change our operational config.  this code must agree with the code
808  * that returns config descriptors, and altsetting code.
809  *
810  * it's also responsible for power management interactions. some
811  * configurations might not work with our current power sources.
812  *
813  * note that some device controller hardware will constrain what this
814  * code can do, perhaps by disallowing more than one configuration or
815  * by limiting configuration choices (like the pxa2xx).
816  */
817 static int
818 zero_set_config (struct zero_dev *dev, unsigned number, int gfp_flags)
819 {
820         int                     result = 0;
821         struct usb_gadget       *gadget = dev->gadget;
822
823         if (number == dev->config)
824                 return 0;
825
826         if (gadget_is_sa1100 (gadget) && dev->config) {
827                 /* tx fifo is full, but we can't clear it...*/
828                 INFO (dev, "can't change configurations\n");
829                 return -ESPIPE;
830         }
831         zero_reset_config (dev);
832
833         switch (number) {
834         case CONFIG_SOURCE_SINK:
835                 result = set_source_sink_config (dev, gfp_flags);
836                 break;
837         case CONFIG_LOOPBACK:
838                 result = set_loopback_config (dev, gfp_flags);
839                 break;
840         default:
841                 result = -EINVAL;
842                 /* FALL THROUGH */
843         case 0:
844                 return result;
845         }
846
847         if (!result && (!dev->in_ep || !dev->out_ep))
848                 result = -ENODEV;
849         if (result)
850                 zero_reset_config (dev);
851         else {
852                 char *speed;
853
854                 switch (gadget->speed) {
855                 case USB_SPEED_LOW:     speed = "low"; break;
856                 case USB_SPEED_FULL:    speed = "full"; break;
857                 case USB_SPEED_HIGH:    speed = "high"; break;
858                 default:                speed = "?"; break;
859                 }
860
861                 dev->config = number;
862                 INFO (dev, "%s speed config #%d: %s\n", speed, number,
863                                 (number == CONFIG_SOURCE_SINK)
864                                         ? source_sink : loopback);
865         }
866         return result;
867 }
868
869 /*-------------------------------------------------------------------------*/
870
871 static void zero_setup_complete (struct usb_ep *ep, struct usb_request *req)
872 {
873         if (req->status || req->actual != req->length)
874                 DBG ((struct zero_dev *) ep->driver_data,
875                                 "setup complete --> %d, %d/%d\n",
876                                 req->status, req->actual, req->length);
877 }
878
879 /*
880  * The setup() callback implements all the ep0 functionality that's
881  * not handled lower down, in hardware or the hardware driver (like
882  * device and endpoint feature flags, and their status).  It's all
883  * housekeeping for the gadget function we're implementing.  Most of
884  * the work is in config-specific setup.
885  */
886 static int
887 zero_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
888 {
889         struct zero_dev         *dev = get_gadget_data (gadget);
890         struct usb_request      *req = dev->req;
891         int                     value = -EOPNOTSUPP;
892
893         /* usually this stores reply data in the pre-allocated ep0 buffer,
894          * but config change events will reconfigure hardware.
895          */
896         switch (ctrl->bRequest) {
897
898         case USB_REQ_GET_DESCRIPTOR:
899                 if (ctrl->bRequestType != USB_DIR_IN)
900                         goto unknown;
901                 switch (ctrl->wValue >> 8) {
902
903                 case USB_DT_DEVICE:
904                         value = min (ctrl->wLength, (u16) sizeof device_desc);
905                         memcpy (req->buf, &device_desc, value);
906                         break;
907 #ifdef CONFIG_USB_GADGET_DUALSPEED
908                 case USB_DT_DEVICE_QUALIFIER:
909                         if (!gadget->is_dualspeed)
910                                 break;
911                         value = min (ctrl->wLength, (u16) sizeof dev_qualifier);
912                         memcpy (req->buf, &dev_qualifier, value);
913                         break;
914
915                 case USB_DT_OTHER_SPEED_CONFIG:
916                         if (!gadget->is_dualspeed)
917                                 break;
918                         // FALLTHROUGH
919 #endif /* CONFIG_USB_GADGET_DUALSPEED */
920                 case USB_DT_CONFIG:
921                         value = config_buf (gadget, req->buf,
922                                         ctrl->wValue >> 8,
923                                         ctrl->wValue & 0xff);
924                         if (value >= 0)
925                                 value = min (ctrl->wLength, (u16) value);
926                         break;
927
928                 case USB_DT_STRING:
929                         /* wIndex == language code.
930                          * this driver only handles one language, you can
931                          * add others even if they don't use iso8859/1
932                          */
933                         value = usb_gadget_get_string (&stringtab,
934                                         ctrl->wValue & 0xff, req->buf);
935                         if (value >= 0)
936                                 value = min (ctrl->wLength, (u16) value);
937                         break;
938                 }
939                 break;
940
941         /* currently two configs, two speeds */
942         case USB_REQ_SET_CONFIGURATION:
943                 if (ctrl->bRequestType != 0)
944                         goto unknown;
945                 spin_lock (&dev->lock);
946                 value = zero_set_config (dev, ctrl->wValue, GFP_ATOMIC);
947                 spin_unlock (&dev->lock);
948                 break;
949         case USB_REQ_GET_CONFIGURATION:
950                 if (ctrl->bRequestType != USB_DIR_IN)
951                         goto unknown;
952                 *(u8 *)req->buf = dev->config;
953                 value = min (ctrl->wLength, (u16) 1);
954                 break;
955
956         /* until we add altsetting support, or other interfaces,
957          * only 0/0 are possible.  pxa2xx only supports 0/0 (poorly)
958          * and already killed pending endpoint I/O.
959          */
960         case USB_REQ_SET_INTERFACE:
961                 if (ctrl->bRequestType != USB_RECIP_INTERFACE)
962                         goto unknown;
963                 spin_lock (&dev->lock);
964                 if (dev->config && ctrl->wIndex == 0 && ctrl->wValue == 0) {
965                         u8              config = dev->config;
966
967                         /* resets interface configuration, forgets about
968                          * previous transaction state (queued bufs, etc)
969                          * and re-inits endpoint state (toggle etc)
970                          * no response queued, just zero status == success.
971                          * if we had more than one interface we couldn't
972                          * use this "reset the config" shortcut.
973                          */
974                         zero_reset_config (dev);
975                         zero_set_config (dev, config, GFP_ATOMIC);
976                         value = 0;
977                 }
978                 spin_unlock (&dev->lock);
979                 break;
980         case USB_REQ_GET_INTERFACE:
981                 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE))
982                         goto unknown;
983                 if (!dev->config)
984                         break;
985                 if (ctrl->wIndex != 0) {
986                         value = -EDOM;
987                         break;
988                 }
989                 *(u8 *)req->buf = 0;
990                 value = min (ctrl->wLength, (u16) 1);
991                 break;
992
993         /*
994          * These are the same vendor-specific requests supported by
995          * Intel's USB 2.0 compliance test devices.  We exceed that
996          * device spec by allowing multiple-packet requests.
997          */
998         case 0x5b:      /* control WRITE test -- fill the buffer */
999                 if (ctrl->bRequestType != (USB_DIR_OUT|USB_TYPE_VENDOR))
1000                         goto unknown;
1001                 if (ctrl->wValue || ctrl->wIndex)
1002                         break;
1003                 /* just read that many bytes into the buffer */
1004                 if (ctrl->wLength > USB_BUFSIZ)
1005                         break;
1006                 value = ctrl->wLength;
1007                 break;
1008         case 0x5c:      /* control READ test -- return the buffer */
1009                 if (ctrl->bRequestType != (USB_DIR_IN|USB_TYPE_VENDOR))
1010                         goto unknown;
1011                 if (ctrl->wValue || ctrl->wIndex)
1012                         break;
1013                 /* expect those bytes are still in the buffer; send back */
1014                 if (ctrl->wLength > USB_BUFSIZ
1015                                 || ctrl->wLength != req->length)
1016                         break;
1017                 value = ctrl->wLength;
1018                 break;
1019
1020         default:
1021 unknown:
1022                 VDBG (dev,
1023                         "unknown control req%02x.%02x v%04x i%04x l%d\n",
1024                         ctrl->bRequestType, ctrl->bRequest,
1025                         ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1026         }
1027
1028         /* respond with data transfer before status phase? */
1029         if (value >= 0) {
1030                 req->length = value;
1031                 value = usb_ep_queue (gadget->ep0, req, GFP_ATOMIC);
1032                 if (value < 0) {
1033                         DBG (dev, "ep_queue --> %d\n", value);
1034                         req->status = 0;
1035                         zero_setup_complete (gadget->ep0, req);
1036                 }
1037         }
1038
1039         /* device either stalls (value < 0) or reports success */
1040         return value;
1041 }
1042
1043 static void
1044 zero_disconnect (struct usb_gadget *gadget)
1045 {
1046         struct zero_dev         *dev = get_gadget_data (gadget);
1047         unsigned long           flags;
1048
1049         spin_lock_irqsave (&dev->lock, flags);
1050         zero_reset_config (dev);
1051
1052         /* a more significant application might have some non-usb
1053          * activities to quiesce here, saving resources like power
1054          * or pushing the notification up a network stack.
1055          */
1056         spin_unlock_irqrestore (&dev->lock, flags);
1057
1058         /* next we may get setup() calls to enumerate new connections;
1059          * or an unbind() during shutdown (including removing module).
1060          */
1061 }
1062
1063 /*-------------------------------------------------------------------------*/
1064
1065 static void
1066 zero_unbind (struct usb_gadget *gadget)
1067 {
1068         struct zero_dev         *dev = get_gadget_data (gadget);
1069
1070         DBG (dev, "unbind\n");
1071
1072         /* we've already been disconnected ... no i/o is active */
1073         if (dev->req)
1074                 free_ep_req (gadget->ep0, dev->req);
1075         kfree (dev);
1076         set_gadget_data (gadget, 0);
1077 }
1078
1079 static int
1080 zero_bind (struct usb_gadget *gadget)
1081 {
1082         struct zero_dev         *dev;
1083         struct usb_ep           *ep;
1084
1085         /* Bulk-only drivers like this one SHOULD be able to
1086          * autoconfigure on any sane usb controller driver,
1087          * but there may also be important quirks to address.
1088          */
1089         usb_ep_autoconfig_reset (gadget);
1090         ep = usb_ep_autoconfig (gadget, &fs_source_desc);
1091         if (!ep) {
1092 autoconf_fail:
1093                 printk (KERN_ERR "%s: can't autoconfigure on %s\n",
1094                         shortname, gadget->name);
1095                 return -ENODEV;
1096         }
1097         EP_IN_NAME = ep->name;
1098         ep->driver_data = ep;   /* claim */
1099         
1100         ep = usb_ep_autoconfig (gadget, &fs_sink_desc);
1101         if (!ep)
1102                 goto autoconf_fail;
1103         EP_OUT_NAME = ep->name;
1104         ep->driver_data = ep;   /* claim */
1105
1106
1107         /*
1108          * DRIVER POLICY CHOICE:  you may want to do this differently.
1109          * One thing to avoid is reusing a bcdDevice revision code
1110          * with different host-visible configurations or behavior
1111          * restrictions -- using ep1in/ep2out vs ep1out/ep3in, etc
1112          */
1113         if (gadget_is_net2280 (gadget)) {
1114                 device_desc.bcdDevice = __constant_cpu_to_le16 (0x0201);
1115         } else if (gadget_is_pxa (gadget)) {
1116                 device_desc.bcdDevice = __constant_cpu_to_le16 (0x0203);
1117 #if 0
1118         } else if (gadget_is_sh(gadget)) {
1119                 device_desc.bcdDevice = __constant_cpu_to_le16 (0x0204);
1120                 /* SH has only one configuration; see "loopdefault" */
1121                 device_desc.bNumConfigurations = 1;
1122                 /* FIXME make 1 == default.bConfigurationValue */
1123 #endif
1124         } else if (gadget_is_sa1100 (gadget)) {
1125                 device_desc.bcdDevice = __constant_cpu_to_le16 (0x0205);
1126         } else if (gadget_is_goku (gadget)) {
1127                 device_desc.bcdDevice = __constant_cpu_to_le16 (0x0206);
1128         } else if (gadget_is_mq11xx (gadget)) {
1129                 device_desc.bcdDevice = __constant_cpu_to_le16 (0x0207);
1130         } else if (gadget_is_omap (gadget)) {
1131                 device_desc.bcdDevice = __constant_cpu_to_le16 (0x0208);
1132         } else {
1133                 /* gadget zero is so simple (for now, no altsettings) that
1134                  * it SHOULD NOT have problems with bulk-capable hardware.
1135                  * so warn about unrcognized controllers, don't panic.
1136                  *
1137                  * things like configuration and altsetting numbering
1138                  * can need hardware-specific attention though.
1139                  */
1140                 printk (KERN_WARNING "%s: controller '%s' not recognized\n",
1141                         shortname, gadget->name);
1142                 device_desc.bcdDevice = __constant_cpu_to_le16 (0x9999);
1143         }
1144
1145
1146         /* ok, we made sense of the hardware ... */
1147         dev = kmalloc (sizeof *dev, SLAB_KERNEL);
1148         if (!dev)
1149                 return -ENOMEM;
1150         memset (dev, 0, sizeof *dev);
1151         spin_lock_init (&dev->lock);
1152         dev->gadget = gadget;
1153         set_gadget_data (gadget, dev);
1154
1155         /* preallocate control response and buffer */
1156         dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1157         if (!dev->req)
1158                 goto enomem;
1159         dev->req->buf = usb_ep_alloc_buffer (gadget->ep0, USB_BUFSIZ,
1160                                 &dev->req->dma, GFP_KERNEL);
1161         if (!dev->req->buf)
1162                 goto enomem;
1163
1164         dev->req->complete = zero_setup_complete;
1165
1166         device_desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1167
1168 #ifdef CONFIG_USB_GADGET_DUALSPEED
1169         /* assume ep0 uses the same value for both speeds ... */
1170         dev_qualifier.bMaxPacketSize0 = device_desc.bMaxPacketSize0;
1171
1172         /* and that all endpoints are dual-speed */
1173         hs_source_desc.bEndpointAddress = fs_source_desc.bEndpointAddress;
1174         hs_sink_desc.bEndpointAddress = fs_sink_desc.bEndpointAddress;
1175 #endif
1176
1177         usb_gadget_set_selfpowered (gadget);
1178
1179         gadget->ep0->driver_data = dev;
1180
1181         INFO (dev, "%s, version: " DRIVER_VERSION "\n", longname);
1182         INFO (dev, "using %s, OUT %s IN %s\n", gadget->name,
1183                 EP_OUT_NAME, EP_IN_NAME);
1184
1185         snprintf (manufacturer, sizeof manufacturer,
1186                 UTS_SYSNAME " " UTS_RELEASE " with %s",
1187                 gadget->name);
1188
1189         return 0;
1190
1191 enomem:
1192         zero_unbind (gadget);
1193         return -ENOMEM;
1194 }
1195
1196 /*-------------------------------------------------------------------------*/
1197
1198 static struct usb_gadget_driver zero_driver = {
1199 #ifdef CONFIG_USB_GADGET_DUALSPEED
1200         .speed          = USB_SPEED_HIGH,
1201 #else
1202         .speed          = USB_SPEED_FULL,
1203 #endif
1204         .function       = (char *) longname,
1205         .bind           = zero_bind,
1206         .unbind         = zero_unbind,
1207
1208         .setup          = zero_setup,
1209         .disconnect     = zero_disconnect,
1210
1211         .driver         = {
1212                 .name           = (char *) shortname,
1213                 // .shutdown = ...
1214                 // .suspend = ...
1215                 // .resume = ...
1216         },
1217 };
1218
1219 MODULE_AUTHOR ("David Brownell");
1220 MODULE_LICENSE ("Dual BSD/GPL");
1221
1222
1223 static int __init init (void)
1224 {
1225         /* a real value would likely come through some id prom
1226          * or module option.  this one takes at least two packets.
1227          */
1228         strlcpy (serial, "0123456789.0123456789.0123456789", sizeof serial);
1229
1230         return usb_gadget_register_driver (&zero_driver);
1231 }
1232 module_init (init);
1233
1234 static void __exit cleanup (void)
1235 {
1236         usb_gadget_unregister_driver (&zero_driver);
1237 }
1238 module_exit (cleanup);
1239