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