[PATCH] USB: gadget-serial: fix a deadlock when closing the serial device
[powerpc.git] / drivers / usb / gadget / serial.c
1 /*
2  * g_serial.c -- USB gadget serial driver
3  *
4  * Copyright 2003 (C) Al Borchers (alborchers@steinerpoint.com)
5  *
6  * This code is based in part on the Gadget Zero driver, which
7  * is Copyright (C) 2003 by David Brownell, all rights reserved.
8  *
9  * This code also borrows from usbserial.c, which is
10  * Copyright (C) 1999 - 2002 Greg Kroah-Hartman (greg@kroah.com)
11  * Copyright (C) 2000 Peter Berger (pberger@brimson.com)
12  * Copyright (C) 2000 Al Borchers (alborchers@steinerpoint.com)
13  *
14  * This software is distributed under the terms of the GNU General
15  * Public License ("GPL") as published by the Free Software Foundation,
16  * either version 2 of that License or (at your option) any later version.
17  *
18  */
19
20 #include <linux/config.h>
21 #include <linux/module.h>
22 #include <linux/kernel.h>
23 #include <linux/delay.h>
24 #include <linux/ioport.h>
25 #include <linux/sched.h>
26 #include <linux/slab.h>
27 #include <linux/smp_lock.h>
28 #include <linux/errno.h>
29 #include <linux/init.h>
30 #include <linux/timer.h>
31 #include <linux/list.h>
32 #include <linux/interrupt.h>
33 #include <linux/utsname.h>
34 #include <linux/wait.h>
35 #include <linux/proc_fs.h>
36 #include <linux/device.h>
37 #include <linux/tty.h>
38 #include <linux/tty_flip.h>
39
40 #include <asm/byteorder.h>
41 #include <asm/io.h>
42 #include <asm/irq.h>
43 #include <asm/system.h>
44 #include <asm/unaligned.h>
45 #include <asm/uaccess.h>
46
47 #include <linux/usb_ch9.h>
48 #include <linux/usb_cdc.h>
49 #include <linux/usb_gadget.h>
50
51 #include "gadget_chips.h"
52
53
54 /* Defines */
55
56 #define GS_VERSION_STR                  "v2.1"
57 #define GS_VERSION_NUM                  0x0201
58
59 #define GS_LONG_NAME                    "Gadget Serial"
60 #define GS_SHORT_NAME                   "g_serial"
61
62 #define GS_MAJOR                        127
63 #define GS_MINOR_START                  0
64
65 #define GS_NUM_PORTS                    16
66
67 #define GS_NUM_CONFIGS                  1
68 #define GS_NO_CONFIG_ID                 0
69 #define GS_BULK_CONFIG_ID               1
70 #define GS_ACM_CONFIG_ID                2
71
72 #define GS_MAX_NUM_INTERFACES           2
73 #define GS_BULK_INTERFACE_ID            0
74 #define GS_CONTROL_INTERFACE_ID         0
75 #define GS_DATA_INTERFACE_ID            1
76
77 #define GS_MAX_DESC_LEN                 256
78
79 #define GS_DEFAULT_READ_Q_SIZE          32
80 #define GS_DEFAULT_WRITE_Q_SIZE         32
81
82 #define GS_DEFAULT_WRITE_BUF_SIZE       8192
83 #define GS_TMP_BUF_SIZE                 8192
84
85 #define GS_CLOSE_TIMEOUT                15
86
87 #define GS_DEFAULT_USE_ACM              0
88
89 #define GS_DEFAULT_DTE_RATE             9600
90 #define GS_DEFAULT_DATA_BITS            8
91 #define GS_DEFAULT_PARITY               USB_CDC_NO_PARITY
92 #define GS_DEFAULT_CHAR_FORMAT          USB_CDC_1_STOP_BITS
93
94 /* select highspeed/fullspeed, hiding highspeed if not configured */
95 #ifdef CONFIG_USB_GADGET_DUALSPEED
96 #define GS_SPEED_SELECT(is_hs,hs,fs) ((is_hs) ? (hs) : (fs))
97 #else
98 #define GS_SPEED_SELECT(is_hs,hs,fs) (fs)
99 #endif /* CONFIG_USB_GADGET_DUALSPEED */
100
101 /* debug settings */
102 #ifdef GS_DEBUG
103 static int debug = 1;
104
105 #define gs_debug(format, arg...) \
106         do { if (debug) printk(KERN_DEBUG format, ## arg); } while(0)
107 #define gs_debug_level(level, format, arg...) \
108         do { if (debug>=level) printk(KERN_DEBUG format, ## arg); } while(0)
109
110 #else
111
112 #define gs_debug(format, arg...) \
113         do { } while(0)
114 #define gs_debug_level(level, format, arg...) \
115         do { } while(0)
116
117 #endif /* GS_DEBUG */
118
119 /* Thanks to NetChip Technologies for donating this product ID.
120  *
121  * DO NOT REUSE THESE IDs with a protocol-incompatible driver!!  Ever!!
122  * Instead:  allocate your own, using normal USB-IF procedures.
123  */
124 #define GS_VENDOR_ID                    0x0525  /* NetChip */
125 #define GS_PRODUCT_ID                   0xa4a6  /* Linux-USB Serial Gadget */
126 #define GS_CDC_PRODUCT_ID               0xa4a7  /* ... as CDC-ACM */
127
128 #define GS_LOG2_NOTIFY_INTERVAL         5       /* 1 << 5 == 32 msec */
129 #define GS_NOTIFY_MAXPACKET             8
130
131
132 /* Structures */
133
134 struct gs_dev;
135
136 /* circular buffer */
137 struct gs_buf {
138         unsigned int            buf_size;
139         char                    *buf_buf;
140         char                    *buf_get;
141         char                    *buf_put;
142 };
143
144 /* list of requests */
145 struct gs_req_entry {
146         struct list_head        re_entry;
147         struct usb_request      *re_req;
148 };
149
150 /* the port structure holds info for each port, one for each minor number */
151 struct gs_port {
152         struct gs_dev           *port_dev;      /* pointer to device struct */
153         struct tty_struct       *port_tty;      /* pointer to tty struct */
154         spinlock_t              port_lock;
155         int                     port_num;
156         int                     port_open_count;
157         int                     port_in_use;    /* open/close in progress */
158         wait_queue_head_t       port_write_wait;/* waiting to write */
159         struct gs_buf           *port_write_buf;
160         struct usb_cdc_line_coding      port_line_coding;
161 };
162
163 /* the device structure holds info for the USB device */
164 struct gs_dev {
165         struct usb_gadget       *dev_gadget;    /* gadget device pointer */
166         spinlock_t              dev_lock;       /* lock for set/reset config */
167         int                     dev_config;     /* configuration number */
168         struct usb_ep           *dev_notify_ep; /* address of notify endpoint */
169         struct usb_ep           *dev_in_ep;     /* address of in endpoint */
170         struct usb_ep           *dev_out_ep;    /* address of out endpoint */
171         struct usb_endpoint_descriptor          /* descriptor of notify ep */
172                                 *dev_notify_ep_desc;
173         struct usb_endpoint_descriptor          /* descriptor of in endpoint */
174                                 *dev_in_ep_desc;
175         struct usb_endpoint_descriptor          /* descriptor of out endpoint */
176                                 *dev_out_ep_desc;
177         struct usb_request      *dev_ctrl_req;  /* control request */
178         struct list_head        dev_req_list;   /* list of write requests */
179         int                     dev_sched_port; /* round robin port scheduled */
180         struct gs_port          *dev_port[GS_NUM_PORTS]; /* the ports */
181 };
182
183
184 /* Functions */
185
186 /* module */
187 static int __init gs_module_init(void);
188 static void __exit gs_module_exit(void);
189
190 /* tty driver */
191 static int gs_open(struct tty_struct *tty, struct file *file);
192 static void gs_close(struct tty_struct *tty, struct file *file);
193 static int gs_write(struct tty_struct *tty, 
194         const unsigned char *buf, int count);
195 static void gs_put_char(struct tty_struct *tty, unsigned char ch);
196 static void gs_flush_chars(struct tty_struct *tty);
197 static int gs_write_room(struct tty_struct *tty);
198 static int gs_chars_in_buffer(struct tty_struct *tty);
199 static void gs_throttle(struct tty_struct * tty);
200 static void gs_unthrottle(struct tty_struct * tty);
201 static void gs_break(struct tty_struct *tty, int break_state);
202 static int  gs_ioctl(struct tty_struct *tty, struct file *file,
203         unsigned int cmd, unsigned long arg);
204 static void gs_set_termios(struct tty_struct *tty, struct termios *old);
205
206 static int gs_send(struct gs_dev *dev);
207 static int gs_send_packet(struct gs_dev *dev, char *packet,
208         unsigned int size);
209 static int gs_recv_packet(struct gs_dev *dev, char *packet,
210         unsigned int size);
211 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req);
212 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req);
213
214 /* gadget driver */
215 static int gs_bind(struct usb_gadget *gadget);
216 static void gs_unbind(struct usb_gadget *gadget);
217 static int gs_setup(struct usb_gadget *gadget,
218         const struct usb_ctrlrequest *ctrl);
219 static int gs_setup_standard(struct usb_gadget *gadget,
220         const struct usb_ctrlrequest *ctrl);
221 static int gs_setup_class(struct usb_gadget *gadget,
222         const struct usb_ctrlrequest *ctrl);
223 static void gs_setup_complete(struct usb_ep *ep, struct usb_request *req);
224 static void gs_disconnect(struct usb_gadget *gadget);
225 static int gs_set_config(struct gs_dev *dev, unsigned config);
226 static void gs_reset_config(struct gs_dev *dev);
227 static int gs_build_config_buf(u8 *buf, enum usb_device_speed speed,
228                 u8 type, unsigned int index, int is_otg);
229
230 static struct usb_request *gs_alloc_req(struct usb_ep *ep, unsigned int len,
231         gfp_t kmalloc_flags);
232 static void gs_free_req(struct usb_ep *ep, struct usb_request *req);
233
234 static struct gs_req_entry *gs_alloc_req_entry(struct usb_ep *ep, unsigned len,
235         gfp_t kmalloc_flags);
236 static void gs_free_req_entry(struct usb_ep *ep, struct gs_req_entry *req);
237
238 static int gs_alloc_ports(struct gs_dev *dev, gfp_t kmalloc_flags);
239 static void gs_free_ports(struct gs_dev *dev);
240
241 /* circular buffer */
242 static struct gs_buf *gs_buf_alloc(unsigned int size, gfp_t kmalloc_flags);
243 static void gs_buf_free(struct gs_buf *gb);
244 static void gs_buf_clear(struct gs_buf *gb);
245 static unsigned int gs_buf_data_avail(struct gs_buf *gb);
246 static unsigned int gs_buf_space_avail(struct gs_buf *gb);
247 static unsigned int gs_buf_put(struct gs_buf *gb, const char *buf,
248         unsigned int count);
249 static unsigned int gs_buf_get(struct gs_buf *gb, char *buf,
250         unsigned int count);
251
252 /* external functions */
253 extern int net2280_set_fifo_mode(struct usb_gadget *gadget, int mode);
254
255
256 /* Globals */
257
258 static struct gs_dev *gs_device;
259
260 static const char *EP_IN_NAME;
261 static const char *EP_OUT_NAME;
262 static const char *EP_NOTIFY_NAME;
263
264 static struct semaphore gs_open_close_sem[GS_NUM_PORTS];
265
266 static unsigned int read_q_size = GS_DEFAULT_READ_Q_SIZE;
267 static unsigned int write_q_size = GS_DEFAULT_WRITE_Q_SIZE;
268
269 static unsigned int write_buf_size = GS_DEFAULT_WRITE_BUF_SIZE;
270
271 static unsigned int use_acm = GS_DEFAULT_USE_ACM;
272
273
274 /* tty driver struct */
275 static struct tty_operations gs_tty_ops = {
276         .open =                 gs_open,
277         .close =                gs_close,
278         .write =                gs_write,
279         .put_char =             gs_put_char,
280         .flush_chars =          gs_flush_chars,
281         .write_room =           gs_write_room,
282         .ioctl =                gs_ioctl,
283         .set_termios =          gs_set_termios,
284         .throttle =             gs_throttle,
285         .unthrottle =           gs_unthrottle,
286         .break_ctl =            gs_break,
287         .chars_in_buffer =      gs_chars_in_buffer,
288 };
289 static struct tty_driver *gs_tty_driver;
290
291 /* gadget driver struct */
292 static struct usb_gadget_driver gs_gadget_driver = {
293 #ifdef CONFIG_USB_GADGET_DUALSPEED
294         .speed =                USB_SPEED_HIGH,
295 #else
296         .speed =                USB_SPEED_FULL,
297 #endif /* CONFIG_USB_GADGET_DUALSPEED */
298         .function =             GS_LONG_NAME,
299         .bind =                 gs_bind,
300         .unbind =               __exit_p(gs_unbind),
301         .setup =                gs_setup,
302         .disconnect =           gs_disconnect,
303         .driver = {
304                 .name =         GS_SHORT_NAME,
305         },
306 };
307
308
309 /* USB descriptors */
310
311 #define GS_MANUFACTURER_STR_ID  1
312 #define GS_PRODUCT_STR_ID       2
313 #define GS_SERIAL_STR_ID        3
314 #define GS_BULK_CONFIG_STR_ID   4
315 #define GS_ACM_CONFIG_STR_ID    5
316 #define GS_CONTROL_STR_ID       6
317 #define GS_DATA_STR_ID          7
318
319 /* static strings, in UTF-8 */
320 static char manufacturer[50];
321 static struct usb_string gs_strings[] = {
322         { GS_MANUFACTURER_STR_ID, manufacturer },
323         { GS_PRODUCT_STR_ID, GS_LONG_NAME },
324         { GS_SERIAL_STR_ID, "0" },
325         { GS_BULK_CONFIG_STR_ID, "Gadget Serial Bulk" },
326         { GS_ACM_CONFIG_STR_ID, "Gadget Serial CDC ACM" },
327         { GS_CONTROL_STR_ID, "Gadget Serial Control" },
328         { GS_DATA_STR_ID, "Gadget Serial Data" },
329         {  } /* end of list */
330 };
331
332 static struct usb_gadget_strings gs_string_table = {
333         .language =             0x0409, /* en-us */
334         .strings =              gs_strings,
335 };
336
337 static struct usb_device_descriptor gs_device_desc = {
338         .bLength =              USB_DT_DEVICE_SIZE,
339         .bDescriptorType =      USB_DT_DEVICE,
340         .bcdUSB =               __constant_cpu_to_le16(0x0200),
341         .bDeviceSubClass =      0,
342         .bDeviceProtocol =      0,
343         .idVendor =             __constant_cpu_to_le16(GS_VENDOR_ID),
344         .idProduct =            __constant_cpu_to_le16(GS_PRODUCT_ID),
345         .iManufacturer =        GS_MANUFACTURER_STR_ID,
346         .iProduct =             GS_PRODUCT_STR_ID,
347         .iSerialNumber =        GS_SERIAL_STR_ID,
348         .bNumConfigurations =   GS_NUM_CONFIGS,
349 };
350
351 static struct usb_otg_descriptor gs_otg_descriptor = {
352         .bLength =              sizeof(gs_otg_descriptor),
353         .bDescriptorType =      USB_DT_OTG,
354         .bmAttributes =         USB_OTG_SRP,
355 };
356
357 static struct usb_config_descriptor gs_bulk_config_desc = {
358         .bLength =              USB_DT_CONFIG_SIZE,
359         .bDescriptorType =      USB_DT_CONFIG,
360         /* .wTotalLength computed dynamically */
361         .bNumInterfaces =       1,
362         .bConfigurationValue =  GS_BULK_CONFIG_ID,
363         .iConfiguration =       GS_BULK_CONFIG_STR_ID,
364         .bmAttributes =         USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
365         .bMaxPower =            1,
366 };
367
368 static struct usb_config_descriptor gs_acm_config_desc = {
369         .bLength =              USB_DT_CONFIG_SIZE,
370         .bDescriptorType =      USB_DT_CONFIG,
371         /* .wTotalLength computed dynamically */
372         .bNumInterfaces =       2,
373         .bConfigurationValue =  GS_ACM_CONFIG_ID,
374         .iConfiguration =       GS_ACM_CONFIG_STR_ID,
375         .bmAttributes =         USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
376         .bMaxPower =            1,
377 };
378
379 static const struct usb_interface_descriptor gs_bulk_interface_desc = {
380         .bLength =              USB_DT_INTERFACE_SIZE,
381         .bDescriptorType =      USB_DT_INTERFACE,
382         .bInterfaceNumber =     GS_BULK_INTERFACE_ID,
383         .bNumEndpoints =        2,
384         .bInterfaceClass =      USB_CLASS_CDC_DATA,
385         .bInterfaceSubClass =   0,
386         .bInterfaceProtocol =   0,
387         .iInterface =           GS_DATA_STR_ID,
388 };
389
390 static const struct usb_interface_descriptor gs_control_interface_desc = {
391         .bLength =              USB_DT_INTERFACE_SIZE,
392         .bDescriptorType =      USB_DT_INTERFACE,
393         .bInterfaceNumber =     GS_CONTROL_INTERFACE_ID,
394         .bNumEndpoints =        1,
395         .bInterfaceClass =      USB_CLASS_COMM,
396         .bInterfaceSubClass =   USB_CDC_SUBCLASS_ACM,
397         .bInterfaceProtocol =   USB_CDC_ACM_PROTO_AT_V25TER,
398         .iInterface =           GS_CONTROL_STR_ID,
399 };
400
401 static const struct usb_interface_descriptor gs_data_interface_desc = {
402         .bLength =              USB_DT_INTERFACE_SIZE,
403         .bDescriptorType =      USB_DT_INTERFACE,
404         .bInterfaceNumber =     GS_DATA_INTERFACE_ID,
405         .bNumEndpoints =        2,
406         .bInterfaceClass =      USB_CLASS_CDC_DATA,
407         .bInterfaceSubClass =   0,
408         .bInterfaceProtocol =   0,
409         .iInterface =           GS_DATA_STR_ID,
410 };
411
412 static const struct usb_cdc_header_desc gs_header_desc = {
413         .bLength =              sizeof(gs_header_desc),
414         .bDescriptorType =      USB_DT_CS_INTERFACE,
415         .bDescriptorSubType =   USB_CDC_HEADER_TYPE,
416         .bcdCDC =               __constant_cpu_to_le16(0x0110),
417 };
418
419 static const struct usb_cdc_call_mgmt_descriptor gs_call_mgmt_descriptor = {
420         .bLength =              sizeof(gs_call_mgmt_descriptor),
421         .bDescriptorType =      USB_DT_CS_INTERFACE,
422         .bDescriptorSubType =   USB_CDC_CALL_MANAGEMENT_TYPE,
423         .bmCapabilities =       0,
424         .bDataInterface =       1,      /* index of data interface */
425 };
426
427 static struct usb_cdc_acm_descriptor gs_acm_descriptor = {
428         .bLength =              sizeof(gs_acm_descriptor),
429         .bDescriptorType =      USB_DT_CS_INTERFACE,
430         .bDescriptorSubType =   USB_CDC_ACM_TYPE,
431         .bmCapabilities =       0,
432 };
433
434 static const struct usb_cdc_union_desc gs_union_desc = {
435         .bLength =              sizeof(gs_union_desc),
436         .bDescriptorType =      USB_DT_CS_INTERFACE,
437         .bDescriptorSubType =   USB_CDC_UNION_TYPE,
438         .bMasterInterface0 =    0,      /* index of control interface */
439         .bSlaveInterface0 =     1,      /* index of data interface */
440 };
441  
442 static struct usb_endpoint_descriptor gs_fullspeed_notify_desc = {
443         .bLength =              USB_DT_ENDPOINT_SIZE,
444         .bDescriptorType =      USB_DT_ENDPOINT,
445         .bEndpointAddress =     USB_DIR_IN,
446         .bmAttributes =         USB_ENDPOINT_XFER_INT,
447         .wMaxPacketSize =       __constant_cpu_to_le16(GS_NOTIFY_MAXPACKET),
448         .bInterval =            1 << GS_LOG2_NOTIFY_INTERVAL,
449 };
450
451 static struct usb_endpoint_descriptor gs_fullspeed_in_desc = {
452         .bLength =              USB_DT_ENDPOINT_SIZE,
453         .bDescriptorType =      USB_DT_ENDPOINT,
454         .bEndpointAddress =     USB_DIR_IN,
455         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
456 };
457
458 static struct usb_endpoint_descriptor gs_fullspeed_out_desc = {
459         .bLength =              USB_DT_ENDPOINT_SIZE,
460         .bDescriptorType =      USB_DT_ENDPOINT,
461         .bEndpointAddress =     USB_DIR_OUT,
462         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
463 };
464
465 static const struct usb_descriptor_header *gs_bulk_fullspeed_function[] = {
466         (struct usb_descriptor_header *) &gs_otg_descriptor,
467         (struct usb_descriptor_header *) &gs_bulk_interface_desc,
468         (struct usb_descriptor_header *) &gs_fullspeed_in_desc,
469         (struct usb_descriptor_header *) &gs_fullspeed_out_desc,
470         NULL,
471 };
472
473 static const struct usb_descriptor_header *gs_acm_fullspeed_function[] = {
474         (struct usb_descriptor_header *) &gs_otg_descriptor,
475         (struct usb_descriptor_header *) &gs_control_interface_desc,
476         (struct usb_descriptor_header *) &gs_header_desc,
477         (struct usb_descriptor_header *) &gs_call_mgmt_descriptor,
478         (struct usb_descriptor_header *) &gs_acm_descriptor,
479         (struct usb_descriptor_header *) &gs_union_desc,
480         (struct usb_descriptor_header *) &gs_fullspeed_notify_desc,
481         (struct usb_descriptor_header *) &gs_data_interface_desc,
482         (struct usb_descriptor_header *) &gs_fullspeed_in_desc,
483         (struct usb_descriptor_header *) &gs_fullspeed_out_desc,
484         NULL,
485 };
486
487 #ifdef CONFIG_USB_GADGET_DUALSPEED
488 static struct usb_endpoint_descriptor gs_highspeed_notify_desc = {
489         .bLength =              USB_DT_ENDPOINT_SIZE,
490         .bDescriptorType =      USB_DT_ENDPOINT,
491         .bEndpointAddress =     USB_DIR_IN,
492         .bmAttributes =         USB_ENDPOINT_XFER_INT,
493         .wMaxPacketSize =       __constant_cpu_to_le16(GS_NOTIFY_MAXPACKET),
494         .bInterval =            GS_LOG2_NOTIFY_INTERVAL+4,
495 };
496
497 static struct usb_endpoint_descriptor gs_highspeed_in_desc = {
498         .bLength =              USB_DT_ENDPOINT_SIZE,
499         .bDescriptorType =      USB_DT_ENDPOINT,
500         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
501         .wMaxPacketSize =       __constant_cpu_to_le16(512),
502 };
503
504 static struct usb_endpoint_descriptor gs_highspeed_out_desc = {
505         .bLength =              USB_DT_ENDPOINT_SIZE,
506         .bDescriptorType =      USB_DT_ENDPOINT,
507         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
508         .wMaxPacketSize =       __constant_cpu_to_le16(512),
509 };
510
511 static struct usb_qualifier_descriptor gs_qualifier_desc = {
512         .bLength =              sizeof(struct usb_qualifier_descriptor),
513         .bDescriptorType =      USB_DT_DEVICE_QUALIFIER,
514         .bcdUSB =               __constant_cpu_to_le16 (0x0200),
515         /* assumes ep0 uses the same value for both speeds ... */
516         .bNumConfigurations =   GS_NUM_CONFIGS,
517 };
518
519 static const struct usb_descriptor_header *gs_bulk_highspeed_function[] = {
520         (struct usb_descriptor_header *) &gs_otg_descriptor,
521         (struct usb_descriptor_header *) &gs_bulk_interface_desc,
522         (struct usb_descriptor_header *) &gs_highspeed_in_desc,
523         (struct usb_descriptor_header *) &gs_highspeed_out_desc,
524         NULL,
525 };
526
527 static const struct usb_descriptor_header *gs_acm_highspeed_function[] = {
528         (struct usb_descriptor_header *) &gs_otg_descriptor,
529         (struct usb_descriptor_header *) &gs_control_interface_desc,
530         (struct usb_descriptor_header *) &gs_header_desc,
531         (struct usb_descriptor_header *) &gs_call_mgmt_descriptor,
532         (struct usb_descriptor_header *) &gs_acm_descriptor,
533         (struct usb_descriptor_header *) &gs_union_desc,
534         (struct usb_descriptor_header *) &gs_highspeed_notify_desc,
535         (struct usb_descriptor_header *) &gs_data_interface_desc,
536         (struct usb_descriptor_header *) &gs_highspeed_in_desc,
537         (struct usb_descriptor_header *) &gs_highspeed_out_desc,
538         NULL,
539 };
540
541 #endif /* CONFIG_USB_GADGET_DUALSPEED */
542
543
544 /* Module */
545 MODULE_DESCRIPTION(GS_LONG_NAME);
546 MODULE_AUTHOR("Al Borchers");
547 MODULE_LICENSE("GPL");
548
549 #ifdef GS_DEBUG
550 module_param(debug, int, S_IRUGO|S_IWUSR);
551 MODULE_PARM_DESC(debug, "Enable debugging, 0=off, 1=on");
552 #endif
553
554 module_param(read_q_size, uint, S_IRUGO);
555 MODULE_PARM_DESC(read_q_size, "Read request queue size, default=32");
556
557 module_param(write_q_size, uint, S_IRUGO);
558 MODULE_PARM_DESC(write_q_size, "Write request queue size, default=32");
559
560 module_param(write_buf_size, uint, S_IRUGO);
561 MODULE_PARM_DESC(write_buf_size, "Write buffer size, default=8192");
562
563 module_param(use_acm, uint, S_IRUGO);
564 MODULE_PARM_DESC(use_acm, "Use CDC ACM, 0=no, 1=yes, default=no");
565
566 module_init(gs_module_init);
567 module_exit(gs_module_exit);
568
569 /*
570 *  gs_module_init
571 *
572 *  Register as a USB gadget driver and a tty driver.
573 */
574 static int __init gs_module_init(void)
575 {
576         int i;
577         int retval;
578
579         retval = usb_gadget_register_driver(&gs_gadget_driver);
580         if (retval) {
581                 printk(KERN_ERR "gs_module_init: cannot register gadget driver, ret=%d\n", retval);
582                 return retval;
583         }
584
585         gs_tty_driver = alloc_tty_driver(GS_NUM_PORTS);
586         if (!gs_tty_driver)
587                 return -ENOMEM;
588         gs_tty_driver->owner = THIS_MODULE;
589         gs_tty_driver->driver_name = GS_SHORT_NAME;
590         gs_tty_driver->name = "ttygs";
591         gs_tty_driver->devfs_name = "usb/ttygs/";
592         gs_tty_driver->major = GS_MAJOR;
593         gs_tty_driver->minor_start = GS_MINOR_START;
594         gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
595         gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
596         gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_NO_DEVFS;
597         gs_tty_driver->init_termios = tty_std_termios;
598         gs_tty_driver->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
599         tty_set_operations(gs_tty_driver, &gs_tty_ops);
600
601         for (i=0; i < GS_NUM_PORTS; i++)
602                 sema_init(&gs_open_close_sem[i], 1);
603
604         retval = tty_register_driver(gs_tty_driver);
605         if (retval) {
606                 usb_gadget_unregister_driver(&gs_gadget_driver);
607                 put_tty_driver(gs_tty_driver);
608                 printk(KERN_ERR "gs_module_init: cannot register tty driver, ret=%d\n", retval);
609                 return retval;
610         }
611
612         printk(KERN_INFO "gs_module_init: %s %s loaded\n", GS_LONG_NAME, GS_VERSION_STR);
613         return 0;
614 }
615
616 /*
617 * gs_module_exit
618 *
619 * Unregister as a tty driver and a USB gadget driver.
620 */
621 static void __exit gs_module_exit(void)
622 {
623         tty_unregister_driver(gs_tty_driver);
624         put_tty_driver(gs_tty_driver);
625         usb_gadget_unregister_driver(&gs_gadget_driver);
626
627         printk(KERN_INFO "gs_module_exit: %s %s unloaded\n", GS_LONG_NAME, GS_VERSION_STR);
628 }
629
630 /* TTY Driver */
631
632 /*
633  * gs_open
634  */
635 static int gs_open(struct tty_struct *tty, struct file *file)
636 {
637         int port_num;
638         unsigned long flags;
639         struct gs_port *port;
640         struct gs_dev *dev;
641         struct gs_buf *buf;
642         struct semaphore *sem;
643         int ret;
644
645         port_num = tty->index;
646
647         gs_debug("gs_open: (%d,%p,%p)\n", port_num, tty, file);
648
649         if (port_num < 0 || port_num >= GS_NUM_PORTS) {
650                 printk(KERN_ERR "gs_open: (%d,%p,%p) invalid port number\n",
651                         port_num, tty, file);
652                 return -ENODEV;
653         }
654
655         dev = gs_device;
656
657         if (dev == NULL) {
658                 printk(KERN_ERR "gs_open: (%d,%p,%p) NULL device pointer\n",
659                         port_num, tty, file);
660                 return -ENODEV;
661         }
662
663         sem = &gs_open_close_sem[port_num];
664         if (down_interruptible(sem)) {
665                 printk(KERN_ERR
666                 "gs_open: (%d,%p,%p) interrupted waiting for semaphore\n",
667                         port_num, tty, file);
668                 return -ERESTARTSYS;
669         }
670
671         spin_lock_irqsave(&dev->dev_lock, flags);
672
673         if (dev->dev_config == GS_NO_CONFIG_ID) {
674                 printk(KERN_ERR
675                         "gs_open: (%d,%p,%p) device is not connected\n",
676                         port_num, tty, file);
677                 ret = -ENODEV;
678                 goto exit_unlock_dev;
679         }
680
681         port = dev->dev_port[port_num];
682
683         if (port == NULL) {
684                 printk(KERN_ERR "gs_open: (%d,%p,%p) NULL port pointer\n",
685                         port_num, tty, file);
686                 ret = -ENODEV;
687                 goto exit_unlock_dev;
688         }
689
690         spin_lock(&port->port_lock);
691         spin_unlock(&dev->dev_lock);
692
693         if (port->port_dev == NULL) {
694                 printk(KERN_ERR "gs_open: (%d,%p,%p) port disconnected (1)\n",
695                         port_num, tty, file);
696                 ret = -EIO;
697                 goto exit_unlock_port;
698         }
699
700         if (port->port_open_count > 0) {
701                 ++port->port_open_count;
702                 gs_debug("gs_open: (%d,%p,%p) already open\n",
703                         port_num, tty, file);
704                 ret = 0;
705                 goto exit_unlock_port;
706         }
707
708         tty->driver_data = NULL;
709
710         /* mark port as in use, we can drop port lock and sleep if necessary */
711         port->port_in_use = 1;
712
713         /* allocate write buffer on first open */
714         if (port->port_write_buf == NULL) {
715                 spin_unlock_irqrestore(&port->port_lock, flags);
716                 buf = gs_buf_alloc(write_buf_size, GFP_KERNEL);
717                 spin_lock_irqsave(&port->port_lock, flags);
718
719                 /* might have been disconnected while asleep, check */
720                 if (port->port_dev == NULL) {
721                         printk(KERN_ERR
722                                 "gs_open: (%d,%p,%p) port disconnected (2)\n",
723                                 port_num, tty, file);
724                         port->port_in_use = 0;
725                         ret = -EIO;
726                         goto exit_unlock_port;
727                 }
728
729                 if ((port->port_write_buf=buf) == NULL) {
730                         printk(KERN_ERR "gs_open: (%d,%p,%p) cannot allocate port write buffer\n",
731                                 port_num, tty, file);
732                         port->port_in_use = 0;
733                         ret = -ENOMEM;
734                         goto exit_unlock_port;
735                 }
736
737         }
738
739         /* wait for carrier detect (not implemented) */
740
741         /* might have been disconnected while asleep, check */
742         if (port->port_dev == NULL) {
743                 printk(KERN_ERR "gs_open: (%d,%p,%p) port disconnected (3)\n",
744                         port_num, tty, file);
745                 port->port_in_use = 0;
746                 ret = -EIO;
747                 goto exit_unlock_port;
748         }
749
750         tty->driver_data = port;
751         port->port_tty = tty;
752         port->port_open_count = 1;
753         port->port_in_use = 0;
754
755         gs_debug("gs_open: (%d,%p,%p) completed\n", port_num, tty, file);
756
757         ret = 0;
758
759 exit_unlock_port:
760         spin_unlock_irqrestore(&port->port_lock, flags);
761         up(sem);
762         return ret;
763
764 exit_unlock_dev:
765         spin_unlock_irqrestore(&dev->dev_lock, flags);
766         up(sem);
767         return ret;
768
769 }
770
771 /*
772  * gs_close
773  */
774
775 #define GS_WRITE_FINISHED_EVENT_SAFELY(p)                       \
776 ({                                                              \
777         unsigned long flags;                                    \
778         int cond;                                               \
779                                                                 \
780         spin_lock_irqsave(&(p)->port_lock, flags);              \
781         cond = !(p)->port_dev || !gs_buf_data_avail((p)->port_write_buf); \
782         spin_unlock_irqrestore(&(p)->port_lock, flags);         \
783         cond;                                                   \
784 })
785
786 static void gs_close(struct tty_struct *tty, struct file *file)
787 {
788         unsigned long flags;
789         struct gs_port *port = tty->driver_data;
790         struct semaphore *sem;
791
792         if (port == NULL) {
793                 printk(KERN_ERR "gs_close: NULL port pointer\n");
794                 return;
795         }
796
797         gs_debug("gs_close: (%d,%p,%p)\n", port->port_num, tty, file);
798
799         sem = &gs_open_close_sem[port->port_num];
800         down(sem);
801
802         spin_lock_irqsave(&port->port_lock, flags);
803
804         if (port->port_open_count == 0) {
805                 printk(KERN_ERR
806                         "gs_close: (%d,%p,%p) port is already closed\n",
807                         port->port_num, tty, file);
808                 goto exit;
809         }
810
811         if (port->port_open_count > 1) {
812                 --port->port_open_count;
813                 goto exit;
814         }
815
816         /* free disconnected port on final close */
817         if (port->port_dev == NULL) {
818                 kfree(port);
819                 goto exit;
820         }
821
822         /* mark port as closed but in use, we can drop port lock */
823         /* and sleep if necessary */
824         port->port_in_use = 1;
825         port->port_open_count = 0;
826
827         /* wait for write buffer to drain, or */
828         /* at most GS_CLOSE_TIMEOUT seconds */
829         if (gs_buf_data_avail(port->port_write_buf) > 0) {
830                 spin_unlock_irqrestore(&port->port_lock, flags);
831                 wait_event_interruptible_timeout(port->port_write_wait,
832                                         GS_WRITE_FINISHED_EVENT_SAFELY(port),
833                                         GS_CLOSE_TIMEOUT * HZ);
834                 spin_lock_irqsave(&port->port_lock, flags);
835         }
836
837         /* free disconnected port on final close */
838         /* (might have happened during the above sleep) */
839         if (port->port_dev == NULL) {
840                 kfree(port);
841                 goto exit;
842         }
843
844         gs_buf_clear(port->port_write_buf);
845
846         tty->driver_data = NULL;
847         port->port_tty = NULL;
848         port->port_in_use = 0;
849
850         gs_debug("gs_close: (%d,%p,%p) completed\n",
851                 port->port_num, tty, file);
852
853 exit:
854         spin_unlock_irqrestore(&port->port_lock, flags);
855         up(sem);
856 }
857
858 /*
859  * gs_write
860  */
861 static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
862 {
863         unsigned long flags;
864         struct gs_port *port = tty->driver_data;
865         int ret;
866
867         if (port == NULL) {
868                 printk(KERN_ERR "gs_write: NULL port pointer\n");
869                 return -EIO;
870         }
871
872         gs_debug("gs_write: (%d,%p) writing %d bytes\n", port->port_num, tty,
873                 count);
874
875         if (count == 0)
876                 return 0;
877
878         spin_lock_irqsave(&port->port_lock, flags);
879
880         if (port->port_dev == NULL) {
881                 printk(KERN_ERR "gs_write: (%d,%p) port is not connected\n",
882                         port->port_num, tty);
883                 ret = -EIO;
884                 goto exit;
885         }
886
887         if (port->port_open_count == 0) {
888                 printk(KERN_ERR "gs_write: (%d,%p) port is closed\n",
889                         port->port_num, tty);
890                 ret = -EBADF;
891                 goto exit;
892         }
893
894         count = gs_buf_put(port->port_write_buf, buf, count);
895
896         spin_unlock_irqrestore(&port->port_lock, flags);
897
898         gs_send(gs_device);
899
900         gs_debug("gs_write: (%d,%p) wrote %d bytes\n", port->port_num, tty,
901                 count);
902
903         return count;
904
905 exit:
906         spin_unlock_irqrestore(&port->port_lock, flags);
907         return ret;
908 }
909
910 /*
911  * gs_put_char
912  */
913 static void gs_put_char(struct tty_struct *tty, unsigned char ch)
914 {
915         unsigned long flags;
916         struct gs_port *port = tty->driver_data;
917
918         if (port == NULL) {
919                 printk(KERN_ERR "gs_put_char: NULL port pointer\n");
920                 return;
921         }
922
923         gs_debug("gs_put_char: (%d,%p) char=0x%x, called from %p, %p, %p\n", port->port_num, tty, ch, __builtin_return_address(0), __builtin_return_address(1), __builtin_return_address(2));
924
925         spin_lock_irqsave(&port->port_lock, flags);
926
927         if (port->port_dev == NULL) {
928                 printk(KERN_ERR "gs_put_char: (%d,%p) port is not connected\n",
929                         port->port_num, tty);
930                 goto exit;
931         }
932
933         if (port->port_open_count == 0) {
934                 printk(KERN_ERR "gs_put_char: (%d,%p) port is closed\n",
935                         port->port_num, tty);
936                 goto exit;
937         }
938
939         gs_buf_put(port->port_write_buf, &ch, 1);
940
941 exit:
942         spin_unlock_irqrestore(&port->port_lock, flags);
943 }
944
945 /*
946  * gs_flush_chars
947  */
948 static void gs_flush_chars(struct tty_struct *tty)
949 {
950         unsigned long flags;
951         struct gs_port *port = tty->driver_data;
952
953         if (port == NULL) {
954                 printk(KERN_ERR "gs_flush_chars: NULL port pointer\n");
955                 return;
956         }
957
958         gs_debug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
959
960         spin_lock_irqsave(&port->port_lock, flags);
961
962         if (port->port_dev == NULL) {
963                 printk(KERN_ERR
964                         "gs_flush_chars: (%d,%p) port is not connected\n",
965                         port->port_num, tty);
966                 goto exit;
967         }
968
969         if (port->port_open_count == 0) {
970                 printk(KERN_ERR "gs_flush_chars: (%d,%p) port is closed\n",
971                         port->port_num, tty);
972                 goto exit;
973         }
974
975         spin_unlock_irqrestore(&port->port_lock, flags);
976
977         gs_send(gs_device);
978
979         return;
980
981 exit:
982         spin_unlock_irqrestore(&port->port_lock, flags);
983 }
984
985 /*
986  * gs_write_room
987  */
988 static int gs_write_room(struct tty_struct *tty)
989 {
990
991         int room = 0;
992         unsigned long flags;
993         struct gs_port *port = tty->driver_data;
994
995
996         if (port == NULL)
997                 return 0;
998
999         spin_lock_irqsave(&port->port_lock, flags);
1000
1001         if (port->port_dev != NULL && port->port_open_count > 0
1002         && port->port_write_buf != NULL)
1003                 room = gs_buf_space_avail(port->port_write_buf);
1004
1005         spin_unlock_irqrestore(&port->port_lock, flags);
1006
1007         gs_debug("gs_write_room: (%d,%p) room=%d\n",
1008                 port->port_num, tty, room);
1009
1010         return room;
1011 }
1012
1013 /*
1014  * gs_chars_in_buffer
1015  */
1016 static int gs_chars_in_buffer(struct tty_struct *tty)
1017 {
1018         int chars = 0;
1019         unsigned long flags;
1020         struct gs_port *port = tty->driver_data;
1021
1022         if (port == NULL)
1023                 return 0;
1024
1025         spin_lock_irqsave(&port->port_lock, flags);
1026
1027         if (port->port_dev != NULL && port->port_open_count > 0
1028         && port->port_write_buf != NULL)
1029                 chars = gs_buf_data_avail(port->port_write_buf);
1030
1031         spin_unlock_irqrestore(&port->port_lock, flags);
1032
1033         gs_debug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
1034                 port->port_num, tty, chars);
1035
1036         return chars;
1037 }
1038
1039 /*
1040  * gs_throttle
1041  */
1042 static void gs_throttle(struct tty_struct *tty)
1043 {
1044 }
1045
1046 /*
1047  * gs_unthrottle
1048  */
1049 static void gs_unthrottle(struct tty_struct *tty)
1050 {
1051 }
1052
1053 /*
1054  * gs_break
1055  */
1056 static void gs_break(struct tty_struct *tty, int break_state)
1057 {
1058 }
1059
1060 /*
1061  * gs_ioctl
1062  */
1063 static int gs_ioctl(struct tty_struct *tty, struct file *file, unsigned int cmd, unsigned long arg)
1064 {
1065         struct gs_port *port = tty->driver_data;
1066
1067         if (port == NULL) {
1068                 printk(KERN_ERR "gs_ioctl: NULL port pointer\n");
1069                 return -EIO;
1070         }
1071
1072         gs_debug("gs_ioctl: (%d,%p,%p) cmd=0x%4.4x, arg=%lu\n",
1073                 port->port_num, tty, file, cmd, arg);
1074
1075         /* handle ioctls */
1076
1077         /* could not handle ioctl */
1078         return -ENOIOCTLCMD;
1079 }
1080
1081 /*
1082  * gs_set_termios
1083  */
1084 static void gs_set_termios(struct tty_struct *tty, struct termios *old)
1085 {
1086 }
1087
1088 /*
1089 * gs_send
1090 *
1091 * This function finds available write requests, calls
1092 * gs_send_packet to fill these packets with data, and
1093 * continues until either there are no more write requests
1094 * available or no more data to send.  This function is
1095 * run whenever data arrives or write requests are available.
1096 */
1097 static int gs_send(struct gs_dev *dev)
1098 {
1099         int ret,len;
1100         unsigned long flags;
1101         struct usb_ep *ep;
1102         struct usb_request *req;
1103         struct gs_req_entry *req_entry;
1104
1105         if (dev == NULL) {
1106                 printk(KERN_ERR "gs_send: NULL device pointer\n");
1107                 return -ENODEV;
1108         }
1109
1110         spin_lock_irqsave(&dev->dev_lock, flags);
1111
1112         ep = dev->dev_in_ep;
1113
1114         while(!list_empty(&dev->dev_req_list)) {
1115
1116                 req_entry = list_entry(dev->dev_req_list.next,
1117                         struct gs_req_entry, re_entry);
1118
1119                 req = req_entry->re_req;
1120
1121                 len = gs_send_packet(dev, req->buf, ep->maxpacket);
1122
1123                 if (len > 0) {
1124 gs_debug_level(3, "gs_send: len=%d, 0x%2.2x 0x%2.2x 0x%2.2x ...\n", len, *((unsigned char *)req->buf), *((unsigned char *)req->buf+1), *((unsigned char *)req->buf+2));
1125                         list_del(&req_entry->re_entry);
1126                         req->length = len;
1127                         if ((ret=usb_ep_queue(ep, req, GFP_ATOMIC))) {
1128                                 printk(KERN_ERR
1129                                 "gs_send: cannot queue read request, ret=%d\n",
1130                                         ret);
1131                                 break;
1132                         }
1133                 } else {
1134                         break;
1135                 }
1136
1137         }
1138
1139         spin_unlock_irqrestore(&dev->dev_lock, flags);
1140
1141         return 0;
1142 }
1143
1144 /*
1145  * gs_send_packet
1146  *
1147  * If there is data to send, a packet is built in the given
1148  * buffer and the size is returned.  If there is no data to
1149  * send, 0 is returned.  If there is any error a negative
1150  * error number is returned.
1151  *
1152  * Called during USB completion routine, on interrupt time.
1153  *
1154  * We assume that disconnect will not happen until all completion
1155  * routines have completed, so we can assume that the dev_port
1156  * array does not change during the lifetime of this function.
1157  */
1158 static int gs_send_packet(struct gs_dev *dev, char *packet, unsigned int size)
1159 {
1160         unsigned int len;
1161         struct gs_port *port;
1162
1163         /* TEMPORARY -- only port 0 is supported right now */
1164         port = dev->dev_port[0];
1165
1166         if (port == NULL) {
1167                 printk(KERN_ERR
1168                         "gs_send_packet: port=%d, NULL port pointer\n",
1169                         0);
1170                 return -EIO;
1171         }
1172
1173         spin_lock(&port->port_lock);
1174
1175         len = gs_buf_data_avail(port->port_write_buf);
1176         if (len < size)
1177                 size = len;
1178
1179         if (size == 0)
1180                 goto exit;
1181
1182         size = gs_buf_get(port->port_write_buf, packet, size);
1183
1184         if (port->port_tty)
1185                 wake_up_interruptible(&port->port_tty->write_wait);
1186
1187 exit:
1188         spin_unlock(&port->port_lock);
1189         return size;
1190 }
1191
1192 /*
1193  * gs_recv_packet
1194  *
1195  * Called for each USB packet received.  Reads the packet
1196  * header and stuffs the data in the appropriate tty buffer.
1197  * Returns 0 if successful, or a negative error number.
1198  *
1199  * Called during USB completion routine, on interrupt time.
1200  *
1201  * We assume that disconnect will not happen until all completion
1202  * routines have completed, so we can assume that the dev_port
1203  * array does not change during the lifetime of this function.
1204  */
1205 static int gs_recv_packet(struct gs_dev *dev, char *packet, unsigned int size)
1206 {
1207         unsigned int len;
1208         struct gs_port *port;
1209         int ret;
1210         struct tty_struct *tty;
1211
1212         /* TEMPORARY -- only port 0 is supported right now */
1213         port = dev->dev_port[0];
1214
1215         if (port == NULL) {
1216                 printk(KERN_ERR "gs_recv_packet: port=%d, NULL port pointer\n",
1217                         port->port_num);
1218                 return -EIO;
1219         }
1220
1221         spin_lock(&port->port_lock);
1222
1223         if (port->port_open_count == 0) {
1224                 printk(KERN_ERR "gs_recv_packet: port=%d, port is closed\n",
1225                         port->port_num);
1226                 ret = -EIO;
1227                 goto exit;
1228         }
1229
1230
1231         tty = port->port_tty;
1232
1233         if (tty == NULL) {
1234                 printk(KERN_ERR "gs_recv_packet: port=%d, NULL tty pointer\n",
1235                         port->port_num);
1236                 ret = -EIO;
1237                 goto exit;
1238         }
1239
1240         if (port->port_tty->magic != TTY_MAGIC) {
1241                 printk(KERN_ERR "gs_recv_packet: port=%d, bad tty magic\n",
1242                         port->port_num);
1243                 ret = -EIO;
1244                 goto exit;
1245         }
1246
1247         len = tty_buffer_request_room(tty, size);
1248         if (len > 0) {
1249                 tty_insert_flip_string(tty, packet, len);
1250                 tty_flip_buffer_push(port->port_tty);
1251                 wake_up_interruptible(&port->port_tty->read_wait);
1252         }
1253         ret = 0;
1254 exit:
1255         spin_unlock(&port->port_lock);
1256         return ret;
1257 }
1258
1259 /*
1260 * gs_read_complete
1261 */
1262 static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
1263 {
1264         int ret;
1265         struct gs_dev *dev = ep->driver_data;
1266
1267         if (dev == NULL) {
1268                 printk(KERN_ERR "gs_read_complete: NULL device pointer\n");
1269                 return;
1270         }
1271
1272         switch(req->status) {
1273         case 0:
1274                 /* normal completion */
1275                 gs_recv_packet(dev, req->buf, req->actual);
1276 requeue:
1277                 req->length = ep->maxpacket;
1278                 if ((ret=usb_ep_queue(ep, req, GFP_ATOMIC))) {
1279                         printk(KERN_ERR
1280                         "gs_read_complete: cannot queue read request, ret=%d\n",
1281                                 ret);
1282                 }
1283                 break;
1284
1285         case -ESHUTDOWN:
1286                 /* disconnect */
1287                 gs_debug("gs_read_complete: shutdown\n");
1288                 gs_free_req(ep, req);
1289                 break;
1290
1291         default:
1292                 /* unexpected */
1293                 printk(KERN_ERR
1294                 "gs_read_complete: unexpected status error, status=%d\n",
1295                         req->status);
1296                 goto requeue;
1297                 break;
1298         }
1299 }
1300
1301 /*
1302 * gs_write_complete
1303 */
1304 static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
1305 {
1306         struct gs_dev *dev = ep->driver_data;
1307         struct gs_req_entry *gs_req = req->context;
1308
1309         if (dev == NULL) {
1310                 printk(KERN_ERR "gs_write_complete: NULL device pointer\n");
1311                 return;
1312         }
1313
1314         switch(req->status) {
1315         case 0:
1316                 /* normal completion */
1317 requeue:
1318                 if (gs_req == NULL) {
1319                         printk(KERN_ERR
1320                                 "gs_write_complete: NULL request pointer\n");
1321                         return;
1322                 }
1323
1324                 spin_lock(&dev->dev_lock);
1325                 list_add(&gs_req->re_entry, &dev->dev_req_list);
1326                 spin_unlock(&dev->dev_lock);
1327
1328                 gs_send(dev);
1329
1330                 break;
1331
1332         case -ESHUTDOWN:
1333                 /* disconnect */
1334                 gs_debug("gs_write_complete: shutdown\n");
1335                 gs_free_req(ep, req);
1336                 break;
1337
1338         default:
1339                 printk(KERN_ERR
1340                 "gs_write_complete: unexpected status error, status=%d\n",
1341                         req->status);
1342                 goto requeue;
1343                 break;
1344         }
1345 }
1346
1347 /* Gadget Driver */
1348
1349 /*
1350  * gs_bind
1351  *
1352  * Called on module load.  Allocates and initializes the device
1353  * structure and a control request.
1354  */
1355 static int __init gs_bind(struct usb_gadget *gadget)
1356 {
1357         int ret;
1358         struct usb_ep *ep;
1359         struct gs_dev *dev;
1360         int gcnum;
1361
1362         /* Some controllers can't support CDC ACM:
1363          * - sh doesn't support multiple interfaces or configs;
1364          * - sa1100 doesn't have a third interrupt endpoint
1365          */
1366         if (gadget_is_sh(gadget) || gadget_is_sa1100(gadget))
1367                 use_acm = 0;
1368
1369         gcnum = usb_gadget_controller_number(gadget);
1370         if (gcnum >= 0)
1371                 gs_device_desc.bcdDevice =
1372                                 cpu_to_le16(GS_VERSION_NUM | gcnum);
1373         else {
1374                 printk(KERN_WARNING "gs_bind: controller '%s' not recognized\n",
1375                         gadget->name);
1376                 /* unrecognized, but safe unless bulk is REALLY quirky */
1377                 gs_device_desc.bcdDevice =
1378                         __constant_cpu_to_le16(GS_VERSION_NUM|0x0099);
1379         }
1380
1381         usb_ep_autoconfig_reset(gadget);
1382
1383         ep = usb_ep_autoconfig(gadget, &gs_fullspeed_in_desc);
1384         if (!ep)
1385                 goto autoconf_fail;
1386         EP_IN_NAME = ep->name;
1387         ep->driver_data = ep;   /* claim the endpoint */
1388
1389         ep = usb_ep_autoconfig(gadget, &gs_fullspeed_out_desc);
1390         if (!ep)
1391                 goto autoconf_fail;
1392         EP_OUT_NAME = ep->name;
1393         ep->driver_data = ep;   /* claim the endpoint */
1394
1395         if (use_acm) {
1396                 ep = usb_ep_autoconfig(gadget, &gs_fullspeed_notify_desc);
1397                 if (!ep) {
1398                         printk(KERN_ERR "gs_bind: cannot run ACM on %s\n", gadget->name);
1399                         goto autoconf_fail;
1400                 }
1401                 gs_device_desc.idProduct = __constant_cpu_to_le16(
1402                                                 GS_CDC_PRODUCT_ID),
1403                 EP_NOTIFY_NAME = ep->name;
1404                 ep->driver_data = ep;   /* claim the endpoint */
1405         }
1406
1407         gs_device_desc.bDeviceClass = use_acm
1408                 ? USB_CLASS_COMM : USB_CLASS_VENDOR_SPEC;
1409         gs_device_desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1410
1411 #ifdef CONFIG_USB_GADGET_DUALSPEED
1412         gs_qualifier_desc.bDeviceClass = use_acm
1413                 ? USB_CLASS_COMM : USB_CLASS_VENDOR_SPEC;
1414         /* assume ep0 uses the same packet size for both speeds */
1415         gs_qualifier_desc.bMaxPacketSize0 = gs_device_desc.bMaxPacketSize0;
1416         /* assume endpoints are dual-speed */
1417         gs_highspeed_notify_desc.bEndpointAddress =
1418                 gs_fullspeed_notify_desc.bEndpointAddress;
1419         gs_highspeed_in_desc.bEndpointAddress =
1420                 gs_fullspeed_in_desc.bEndpointAddress;
1421         gs_highspeed_out_desc.bEndpointAddress =
1422                 gs_fullspeed_out_desc.bEndpointAddress;
1423 #endif /* CONFIG_USB_GADGET_DUALSPEED */
1424
1425         usb_gadget_set_selfpowered(gadget);
1426
1427         if (gadget->is_otg) {
1428                 gs_otg_descriptor.bmAttributes |= USB_OTG_HNP,
1429                 gs_bulk_config_desc.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
1430                 gs_acm_config_desc.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
1431         }
1432
1433         gs_device = dev = kmalloc(sizeof(struct gs_dev), GFP_KERNEL);
1434         if (dev == NULL)
1435                 return -ENOMEM;
1436
1437         snprintf(manufacturer, sizeof(manufacturer), "%s %s with %s",
1438                 system_utsname.sysname, system_utsname.release,
1439                 gadget->name);
1440
1441         memset(dev, 0, sizeof(struct gs_dev));
1442         dev->dev_gadget = gadget;
1443         spin_lock_init(&dev->dev_lock);
1444         INIT_LIST_HEAD(&dev->dev_req_list);
1445         set_gadget_data(gadget, dev);
1446
1447         if ((ret=gs_alloc_ports(dev, GFP_KERNEL)) != 0) {
1448                 printk(KERN_ERR "gs_bind: cannot allocate ports\n");
1449                 gs_unbind(gadget);
1450                 return ret;
1451         }
1452
1453         /* preallocate control response and buffer */
1454         dev->dev_ctrl_req = gs_alloc_req(gadget->ep0, GS_MAX_DESC_LEN,
1455                 GFP_KERNEL);
1456         if (dev->dev_ctrl_req == NULL) {
1457                 gs_unbind(gadget);
1458                 return -ENOMEM;
1459         }
1460         dev->dev_ctrl_req->complete = gs_setup_complete;
1461
1462         gadget->ep0->driver_data = dev;
1463
1464         printk(KERN_INFO "gs_bind: %s %s bound\n",
1465                 GS_LONG_NAME, GS_VERSION_STR);
1466
1467         return 0;
1468
1469 autoconf_fail:
1470         printk(KERN_ERR "gs_bind: cannot autoconfigure on %s\n", gadget->name);
1471         return -ENODEV;
1472 }
1473
1474 /*
1475  * gs_unbind
1476  *
1477  * Called on module unload.  Frees the control request and device
1478  * structure.
1479  */
1480 static void __exit gs_unbind(struct usb_gadget *gadget)
1481 {
1482         struct gs_dev *dev = get_gadget_data(gadget);
1483
1484         gs_device = NULL;
1485
1486         /* read/write requests already freed, only control request remains */
1487         if (dev != NULL) {
1488                 if (dev->dev_ctrl_req != NULL) {
1489                         gs_free_req(gadget->ep0, dev->dev_ctrl_req);
1490                         dev->dev_ctrl_req = NULL;
1491                 }
1492                 gs_free_ports(dev);
1493                 kfree(dev);
1494                 set_gadget_data(gadget, NULL);
1495         }
1496
1497         printk(KERN_INFO "gs_unbind: %s %s unbound\n", GS_LONG_NAME,
1498                 GS_VERSION_STR);
1499 }
1500
1501 /*
1502  * gs_setup
1503  *
1504  * Implements all the control endpoint functionality that's not
1505  * handled in hardware or the hardware driver.
1506  *
1507  * Returns the size of the data sent to the host, or a negative
1508  * error number.
1509  */
1510 static int gs_setup(struct usb_gadget *gadget,
1511         const struct usb_ctrlrequest *ctrl)
1512 {
1513         int ret = -EOPNOTSUPP;
1514         struct gs_dev *dev = get_gadget_data(gadget);
1515         struct usb_request *req = dev->dev_ctrl_req;
1516         u16 wIndex = le16_to_cpu(ctrl->wIndex);
1517         u16 wValue = le16_to_cpu(ctrl->wValue);
1518         u16 wLength = le16_to_cpu(ctrl->wLength);
1519
1520         switch (ctrl->bRequestType & USB_TYPE_MASK) {
1521         case USB_TYPE_STANDARD:
1522                 ret = gs_setup_standard(gadget,ctrl);
1523                 break;
1524
1525         case USB_TYPE_CLASS:
1526                 ret = gs_setup_class(gadget,ctrl);
1527                 break;
1528
1529         default:
1530                 printk(KERN_ERR "gs_setup: unknown request, type=%02x, request=%02x, value=%04x, index=%04x, length=%d\n",
1531                         ctrl->bRequestType, ctrl->bRequest,
1532                         wValue, wIndex, wLength);
1533                 break;
1534         }
1535
1536         /* respond with data transfer before status phase? */
1537         if (ret >= 0) {
1538                 req->length = ret;
1539                 req->zero = ret < wLength
1540                                 && (ret % gadget->ep0->maxpacket) == 0;
1541                 ret = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1542                 if (ret < 0) {
1543                         printk(KERN_ERR "gs_setup: cannot queue response, ret=%d\n",
1544                                 ret);
1545                         req->status = 0;
1546                         gs_setup_complete(gadget->ep0, req);
1547                 }
1548         }
1549
1550         /* device either stalls (ret < 0) or reports success */
1551         return ret;
1552 }
1553
1554 static int gs_setup_standard(struct usb_gadget *gadget,
1555         const struct usb_ctrlrequest *ctrl)
1556 {
1557         int ret = -EOPNOTSUPP;
1558         struct gs_dev *dev = get_gadget_data(gadget);
1559         struct usb_request *req = dev->dev_ctrl_req;
1560         u16 wIndex = le16_to_cpu(ctrl->wIndex);
1561         u16 wValue = le16_to_cpu(ctrl->wValue);
1562         u16 wLength = le16_to_cpu(ctrl->wLength);
1563
1564         switch (ctrl->bRequest) {
1565         case USB_REQ_GET_DESCRIPTOR:
1566                 if (ctrl->bRequestType != USB_DIR_IN)
1567                         break;
1568
1569                 switch (wValue >> 8) {
1570                 case USB_DT_DEVICE:
1571                         ret = min(wLength,
1572                                 (u16)sizeof(struct usb_device_descriptor));
1573                         memcpy(req->buf, &gs_device_desc, ret);
1574                         break;
1575
1576 #ifdef CONFIG_USB_GADGET_DUALSPEED
1577                 case USB_DT_DEVICE_QUALIFIER:
1578                         if (!gadget->is_dualspeed)
1579                                 break;
1580                         ret = min(wLength,
1581                                 (u16)sizeof(struct usb_qualifier_descriptor));
1582                         memcpy(req->buf, &gs_qualifier_desc, ret);
1583                         break;
1584
1585                 case USB_DT_OTHER_SPEED_CONFIG:
1586                         if (!gadget->is_dualspeed)
1587                                 break;
1588                         /* fall through */
1589 #endif /* CONFIG_USB_GADGET_DUALSPEED */
1590                 case USB_DT_CONFIG:
1591                         ret = gs_build_config_buf(req->buf, gadget->speed,
1592                                 wValue >> 8, wValue & 0xff,
1593                                 gadget->is_otg);
1594                         if (ret >= 0)
1595                                 ret = min(wLength, (u16)ret);
1596                         break;
1597
1598                 case USB_DT_STRING:
1599                         /* wIndex == language code. */
1600                         ret = usb_gadget_get_string(&gs_string_table,
1601                                 wValue & 0xff, req->buf);
1602                         if (ret >= 0)
1603                                 ret = min(wLength, (u16)ret);
1604                         break;
1605                 }
1606                 break;
1607
1608         case USB_REQ_SET_CONFIGURATION:
1609                 if (ctrl->bRequestType != 0)
1610                         break;
1611                 spin_lock(&dev->dev_lock);
1612                 ret = gs_set_config(dev, wValue);
1613                 spin_unlock(&dev->dev_lock);
1614                 break;
1615
1616         case USB_REQ_GET_CONFIGURATION:
1617                 if (ctrl->bRequestType != USB_DIR_IN)
1618                         break;
1619                 *(u8 *)req->buf = dev->dev_config;
1620                 ret = min(wLength, (u16)1);
1621                 break;
1622
1623         case USB_REQ_SET_INTERFACE:
1624                 if (ctrl->bRequestType != USB_RECIP_INTERFACE
1625                                 || !dev->dev_config
1626                                 || wIndex >= GS_MAX_NUM_INTERFACES)
1627                         break;
1628                 if (dev->dev_config == GS_BULK_CONFIG_ID
1629                                 && wIndex != GS_BULK_INTERFACE_ID)
1630                         break;
1631                 /* no alternate interface settings */
1632                 if (wValue != 0)
1633                         break;
1634                 spin_lock(&dev->dev_lock);
1635                 /* PXA hardware partially handles SET_INTERFACE;
1636                  * we need to kluge around that interference.  */
1637                 if (gadget_is_pxa(gadget)) {
1638                         ret = gs_set_config(dev, use_acm ?
1639                                 GS_ACM_CONFIG_ID : GS_BULK_CONFIG_ID);
1640                         goto set_interface_done;
1641                 }
1642                 if (dev->dev_config != GS_BULK_CONFIG_ID
1643                                 && wIndex == GS_CONTROL_INTERFACE_ID) {
1644                         if (dev->dev_notify_ep) {
1645                                 usb_ep_disable(dev->dev_notify_ep);
1646                                 usb_ep_enable(dev->dev_notify_ep, dev->dev_notify_ep_desc);
1647                         }
1648                 } else {
1649                         usb_ep_disable(dev->dev_in_ep);
1650                         usb_ep_disable(dev->dev_out_ep);
1651                         usb_ep_enable(dev->dev_in_ep, dev->dev_in_ep_desc);
1652                         usb_ep_enable(dev->dev_out_ep, dev->dev_out_ep_desc);
1653                 }
1654                 ret = 0;
1655 set_interface_done:
1656                 spin_unlock(&dev->dev_lock);
1657                 break;
1658
1659         case USB_REQ_GET_INTERFACE:
1660                 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE)
1661                 || dev->dev_config == GS_NO_CONFIG_ID)
1662                         break;
1663                 if (wIndex >= GS_MAX_NUM_INTERFACES
1664                                 || (dev->dev_config == GS_BULK_CONFIG_ID
1665                                 && wIndex != GS_BULK_INTERFACE_ID)) {
1666                         ret = -EDOM;
1667                         break;
1668                 }
1669                 /* no alternate interface settings */
1670                 *(u8 *)req->buf = 0;
1671                 ret = min(wLength, (u16)1);
1672                 break;
1673
1674         default:
1675                 printk(KERN_ERR "gs_setup: unknown standard request, type=%02x, request=%02x, value=%04x, index=%04x, length=%d\n",
1676                         ctrl->bRequestType, ctrl->bRequest,
1677                         wValue, wIndex, wLength);
1678                 break;
1679         }
1680
1681         return ret;
1682 }
1683
1684 static int gs_setup_class(struct usb_gadget *gadget,
1685         const struct usb_ctrlrequest *ctrl)
1686 {
1687         int ret = -EOPNOTSUPP;
1688         struct gs_dev *dev = get_gadget_data(gadget);
1689         struct gs_port *port = dev->dev_port[0];        /* ACM only has one port */
1690         struct usb_request *req = dev->dev_ctrl_req;
1691         u16 wIndex = le16_to_cpu(ctrl->wIndex);
1692         u16 wValue = le16_to_cpu(ctrl->wValue);
1693         u16 wLength = le16_to_cpu(ctrl->wLength);
1694
1695         switch (ctrl->bRequest) {
1696         case USB_CDC_REQ_SET_LINE_CODING:
1697                 ret = min(wLength,
1698                         (u16)sizeof(struct usb_cdc_line_coding));
1699                 if (port) {
1700                         spin_lock(&port->port_lock);
1701                         memcpy(&port->port_line_coding, req->buf, ret);
1702                         spin_unlock(&port->port_lock);
1703                 }
1704                 break;
1705
1706         case USB_CDC_REQ_GET_LINE_CODING:
1707                 port = dev->dev_port[0];        /* ACM only has one port */
1708                 ret = min(wLength,
1709                         (u16)sizeof(struct usb_cdc_line_coding));
1710                 if (port) {
1711                         spin_lock(&port->port_lock);
1712                         memcpy(req->buf, &port->port_line_coding, ret);
1713                         spin_unlock(&port->port_lock);
1714                 }
1715                 break;
1716
1717         case USB_CDC_REQ_SET_CONTROL_LINE_STATE:
1718                 ret = 0;
1719                 break;
1720
1721         default:
1722                 printk(KERN_ERR "gs_setup: unknown class request, type=%02x, request=%02x, value=%04x, index=%04x, length=%d\n",
1723                         ctrl->bRequestType, ctrl->bRequest,
1724                         wValue, wIndex, wLength);
1725                 break;
1726         }
1727
1728         return ret;
1729 }
1730
1731 /*
1732  * gs_setup_complete
1733  */
1734 static void gs_setup_complete(struct usb_ep *ep, struct usb_request *req)
1735 {
1736         if (req->status || req->actual != req->length) {
1737                 printk(KERN_ERR "gs_setup_complete: status error, status=%d, actual=%d, length=%d\n",
1738                         req->status, req->actual, req->length);
1739         }
1740 }
1741
1742 /*
1743  * gs_disconnect
1744  *
1745  * Called when the device is disconnected.  Frees the closed
1746  * ports and disconnects open ports.  Open ports will be freed
1747  * on close.  Then reallocates the ports for the next connection.
1748  */
1749 static void gs_disconnect(struct usb_gadget *gadget)
1750 {
1751         unsigned long flags;
1752         struct gs_dev *dev = get_gadget_data(gadget);
1753
1754         spin_lock_irqsave(&dev->dev_lock, flags);
1755
1756         gs_reset_config(dev);
1757
1758         /* free closed ports and disconnect open ports */
1759         /* (open ports will be freed when closed) */
1760         gs_free_ports(dev);
1761
1762         /* re-allocate ports for the next connection */
1763         if (gs_alloc_ports(dev, GFP_ATOMIC) != 0)
1764                 printk(KERN_ERR "gs_disconnect: cannot re-allocate ports\n");
1765
1766         spin_unlock_irqrestore(&dev->dev_lock, flags);
1767
1768         printk(KERN_INFO "gs_disconnect: %s disconnected\n", GS_LONG_NAME);
1769 }
1770
1771 /*
1772  * gs_set_config
1773  *
1774  * Configures the device by enabling device specific
1775  * optimizations, setting up the endpoints, allocating
1776  * read and write requests and queuing read requests.
1777  *
1778  * The device lock must be held when calling this function.
1779  */
1780 static int gs_set_config(struct gs_dev *dev, unsigned config)
1781 {
1782         int i;
1783         int ret = 0;
1784         struct usb_gadget *gadget = dev->dev_gadget;
1785         struct usb_ep *ep;
1786         struct usb_endpoint_descriptor *ep_desc;
1787         struct usb_request *req;
1788         struct gs_req_entry *req_entry;
1789
1790         if (dev == NULL) {
1791                 printk(KERN_ERR "gs_set_config: NULL device pointer\n");
1792                 return 0;
1793         }
1794
1795         if (config == dev->dev_config)
1796                 return 0;
1797
1798         gs_reset_config(dev);
1799
1800         switch (config) {
1801         case GS_NO_CONFIG_ID:
1802                 return 0;
1803         case GS_BULK_CONFIG_ID:
1804                 if (use_acm)
1805                         return -EINVAL;
1806                 /* device specific optimizations */
1807                 if (gadget_is_net2280(gadget))
1808                         net2280_set_fifo_mode(gadget, 1);
1809                 break;
1810         case GS_ACM_CONFIG_ID:
1811                 if (!use_acm)
1812                         return -EINVAL;
1813                 /* device specific optimizations */
1814                 if (gadget_is_net2280(gadget))
1815                         net2280_set_fifo_mode(gadget, 1);
1816                 break;
1817         default:
1818                 return -EINVAL;
1819         }
1820
1821         dev->dev_config = config;
1822
1823         gadget_for_each_ep(ep, gadget) {
1824
1825                 if (EP_NOTIFY_NAME
1826                 && strcmp(ep->name, EP_NOTIFY_NAME) == 0) {
1827                         ep_desc = GS_SPEED_SELECT(
1828                                 gadget->speed == USB_SPEED_HIGH,
1829                                 &gs_highspeed_notify_desc,
1830                                 &gs_fullspeed_notify_desc);
1831                         ret = usb_ep_enable(ep,ep_desc);
1832                         if (ret == 0) {
1833                                 ep->driver_data = dev;
1834                                 dev->dev_notify_ep = ep;
1835                                 dev->dev_notify_ep_desc = ep_desc;
1836                         } else {
1837                                 printk(KERN_ERR "gs_set_config: cannot enable notify endpoint %s, ret=%d\n",
1838                                         ep->name, ret);
1839                                 goto exit_reset_config;
1840                         }
1841                 }
1842
1843                 else if (strcmp(ep->name, EP_IN_NAME) == 0) {
1844                         ep_desc = GS_SPEED_SELECT(
1845                                 gadget->speed == USB_SPEED_HIGH,
1846                                 &gs_highspeed_in_desc,
1847                                 &gs_fullspeed_in_desc);
1848                         ret = usb_ep_enable(ep,ep_desc);
1849                         if (ret == 0) {
1850                                 ep->driver_data = dev;
1851                                 dev->dev_in_ep = ep;
1852                                 dev->dev_in_ep_desc = ep_desc;
1853                         } else {
1854                                 printk(KERN_ERR "gs_set_config: cannot enable in endpoint %s, ret=%d\n",
1855                                         ep->name, ret);
1856                                 goto exit_reset_config;
1857                         }
1858                 }
1859
1860                 else if (strcmp(ep->name, EP_OUT_NAME) == 0) {
1861                         ep_desc = GS_SPEED_SELECT(
1862                                 gadget->speed == USB_SPEED_HIGH,
1863                                 &gs_highspeed_out_desc,
1864                                 &gs_fullspeed_out_desc);
1865                         ret = usb_ep_enable(ep,ep_desc);
1866                         if (ret == 0) {
1867                                 ep->driver_data = dev;
1868                                 dev->dev_out_ep = ep;
1869                                 dev->dev_out_ep_desc = ep_desc;
1870                         } else {
1871                                 printk(KERN_ERR "gs_set_config: cannot enable out endpoint %s, ret=%d\n",
1872                                         ep->name, ret);
1873                                 goto exit_reset_config;
1874                         }
1875                 }
1876
1877         }
1878
1879         if (dev->dev_in_ep == NULL || dev->dev_out_ep == NULL
1880         || (config != GS_BULK_CONFIG_ID && dev->dev_notify_ep == NULL)) {
1881                 printk(KERN_ERR "gs_set_config: cannot find endpoints\n");
1882                 ret = -ENODEV;
1883                 goto exit_reset_config;
1884         }
1885
1886         /* allocate and queue read requests */
1887         ep = dev->dev_out_ep;
1888         for (i=0; i<read_q_size && ret == 0; i++) {
1889                 if ((req=gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC))) {
1890                         req->complete = gs_read_complete;
1891                         if ((ret=usb_ep_queue(ep, req, GFP_ATOMIC))) {
1892                                 printk(KERN_ERR "gs_set_config: cannot queue read request, ret=%d\n",
1893                                         ret);
1894                         }
1895                 } else {
1896                         printk(KERN_ERR "gs_set_config: cannot allocate read requests\n");
1897                         ret = -ENOMEM;
1898                         goto exit_reset_config;
1899                 }
1900         }
1901
1902         /* allocate write requests, and put on free list */
1903         ep = dev->dev_in_ep;
1904         for (i=0; i<write_q_size; i++) {
1905                 if ((req_entry=gs_alloc_req_entry(ep, ep->maxpacket, GFP_ATOMIC))) {
1906                         req_entry->re_req->complete = gs_write_complete;
1907                         list_add(&req_entry->re_entry, &dev->dev_req_list);
1908                 } else {
1909                         printk(KERN_ERR "gs_set_config: cannot allocate write requests\n");
1910                         ret = -ENOMEM;
1911                         goto exit_reset_config;
1912                 }
1913         }
1914
1915         printk(KERN_INFO "gs_set_config: %s configured, %s speed %s config\n",
1916                 GS_LONG_NAME,
1917                 gadget->speed == USB_SPEED_HIGH ? "high" : "full",
1918                 config == GS_BULK_CONFIG_ID ? "BULK" : "CDC-ACM");
1919
1920         return 0;
1921
1922 exit_reset_config:
1923         gs_reset_config(dev);
1924         return ret;
1925 }
1926
1927 /*
1928  * gs_reset_config
1929  *
1930  * Mark the device as not configured, disable all endpoints,
1931  * which forces completion of pending I/O and frees queued
1932  * requests, and free the remaining write requests on the
1933  * free list.
1934  *
1935  * The device lock must be held when calling this function.
1936  */
1937 static void gs_reset_config(struct gs_dev *dev)
1938 {
1939         struct gs_req_entry *req_entry;
1940
1941         if (dev == NULL) {
1942                 printk(KERN_ERR "gs_reset_config: NULL device pointer\n");
1943                 return;
1944         }
1945
1946         if (dev->dev_config == GS_NO_CONFIG_ID)
1947                 return;
1948
1949         dev->dev_config = GS_NO_CONFIG_ID;
1950
1951         /* free write requests on the free list */
1952         while(!list_empty(&dev->dev_req_list)) {
1953                 req_entry = list_entry(dev->dev_req_list.next,
1954                         struct gs_req_entry, re_entry);
1955                 list_del(&req_entry->re_entry);
1956                 gs_free_req_entry(dev->dev_in_ep, req_entry);
1957         }
1958
1959         /* disable endpoints, forcing completion of pending i/o; */
1960         /* completion handlers free their requests in this case */
1961         if (dev->dev_notify_ep) {
1962                 usb_ep_disable(dev->dev_notify_ep);
1963                 dev->dev_notify_ep = NULL;
1964         }
1965         if (dev->dev_in_ep) {
1966                 usb_ep_disable(dev->dev_in_ep);
1967                 dev->dev_in_ep = NULL;
1968         }
1969         if (dev->dev_out_ep) {
1970                 usb_ep_disable(dev->dev_out_ep);
1971                 dev->dev_out_ep = NULL;
1972         }
1973 }
1974
1975 /*
1976  * gs_build_config_buf
1977  *
1978  * Builds the config descriptors in the given buffer and returns the
1979  * length, or a negative error number.
1980  */
1981 static int gs_build_config_buf(u8 *buf, enum usb_device_speed speed,
1982         u8 type, unsigned int index, int is_otg)
1983 {
1984         int len;
1985         int high_speed;
1986         const struct usb_config_descriptor *config_desc;
1987         const struct usb_descriptor_header **function;
1988
1989         if (index >= gs_device_desc.bNumConfigurations)
1990                 return -EINVAL;
1991
1992         /* other speed switches high and full speed */
1993         high_speed = (speed == USB_SPEED_HIGH);
1994         if (type == USB_DT_OTHER_SPEED_CONFIG)
1995                 high_speed = !high_speed;
1996
1997         if (use_acm) {
1998                 config_desc = &gs_acm_config_desc;
1999                 function = GS_SPEED_SELECT(high_speed,
2000                         gs_acm_highspeed_function,
2001                         gs_acm_fullspeed_function);
2002         } else {
2003                 config_desc = &gs_bulk_config_desc;
2004                 function = GS_SPEED_SELECT(high_speed,
2005                         gs_bulk_highspeed_function,
2006                         gs_bulk_fullspeed_function);
2007         }
2008
2009         /* for now, don't advertise srp-only devices */
2010         if (!is_otg)
2011                 function++;
2012
2013         len = usb_gadget_config_buf(config_desc, buf, GS_MAX_DESC_LEN, function);
2014         if (len < 0)
2015                 return len;
2016
2017         ((struct usb_config_descriptor *)buf)->bDescriptorType = type;
2018
2019         return len;
2020 }
2021
2022 /*
2023  * gs_alloc_req
2024  *
2025  * Allocate a usb_request and its buffer.  Returns a pointer to the
2026  * usb_request or NULL if there is an error.
2027  */
2028 static struct usb_request *
2029 gs_alloc_req(struct usb_ep *ep, unsigned int len, gfp_t kmalloc_flags)
2030 {
2031         struct usb_request *req;
2032
2033         if (ep == NULL)
2034                 return NULL;
2035
2036         req = usb_ep_alloc_request(ep, kmalloc_flags);
2037
2038         if (req != NULL) {
2039                 req->length = len;
2040                 req->buf = kmalloc(len, kmalloc_flags);
2041                 if (req->buf == NULL) {
2042                         usb_ep_free_request(ep, req);
2043                         return NULL;
2044                 }
2045         }
2046
2047         return req;
2048 }
2049
2050 /*
2051  * gs_free_req
2052  *
2053  * Free a usb_request and its buffer.
2054  */
2055 static void gs_free_req(struct usb_ep *ep, struct usb_request *req)
2056 {
2057         if (ep != NULL && req != NULL) {
2058                 kfree(req->buf);
2059                 usb_ep_free_request(ep, req);
2060         }
2061 }
2062
2063 /*
2064  * gs_alloc_req_entry
2065  *
2066  * Allocates a request and its buffer, using the given
2067  * endpoint, buffer len, and kmalloc flags.
2068  */
2069 static struct gs_req_entry *
2070 gs_alloc_req_entry(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
2071 {
2072         struct gs_req_entry     *req;
2073
2074         req = kmalloc(sizeof(struct gs_req_entry), kmalloc_flags);
2075         if (req == NULL)
2076                 return NULL;
2077
2078         req->re_req = gs_alloc_req(ep, len, kmalloc_flags);
2079         if (req->re_req == NULL) {
2080                 kfree(req);
2081                 return NULL;
2082         }
2083
2084         req->re_req->context = req;
2085
2086         return req;
2087 }
2088
2089 /*
2090  * gs_free_req_entry
2091  *
2092  * Frees a request and its buffer.
2093  */
2094 static void gs_free_req_entry(struct usb_ep *ep, struct gs_req_entry *req)
2095 {
2096         if (ep != NULL && req != NULL) {
2097                 if (req->re_req != NULL)
2098                         gs_free_req(ep, req->re_req);
2099                 kfree(req);
2100         }
2101 }
2102
2103 /*
2104  * gs_alloc_ports
2105  *
2106  * Allocate all ports and set the gs_dev struct to point to them.
2107  * Return 0 if successful, or a negative error number.
2108  *
2109  * The device lock is normally held when calling this function.
2110  */
2111 static int gs_alloc_ports(struct gs_dev *dev, gfp_t kmalloc_flags)
2112 {
2113         int i;
2114         struct gs_port *port;
2115
2116         if (dev == NULL)
2117                 return -EIO;
2118
2119         for (i=0; i<GS_NUM_PORTS; i++) {
2120                 if ((port=kzalloc(sizeof(struct gs_port), kmalloc_flags)) == NULL)
2121                         return -ENOMEM;
2122
2123                 port->port_dev = dev;
2124                 port->port_num = i;
2125                 port->port_line_coding.dwDTERate = cpu_to_le32(GS_DEFAULT_DTE_RATE);
2126                 port->port_line_coding.bCharFormat = GS_DEFAULT_CHAR_FORMAT;
2127                 port->port_line_coding.bParityType = GS_DEFAULT_PARITY;
2128                 port->port_line_coding.bDataBits = GS_DEFAULT_DATA_BITS;
2129                 spin_lock_init(&port->port_lock);
2130                 init_waitqueue_head(&port->port_write_wait);
2131
2132                 dev->dev_port[i] = port;
2133         }
2134
2135         return 0;
2136 }
2137
2138 /*
2139  * gs_free_ports
2140  *
2141  * Free all closed ports.  Open ports are disconnected by
2142  * freeing their write buffers, setting their device pointers
2143  * and the pointers to them in the device to NULL.  These
2144  * ports will be freed when closed.
2145  *
2146  * The device lock is normally held when calling this function.
2147  */
2148 static void gs_free_ports(struct gs_dev *dev)
2149 {
2150         int i;
2151         unsigned long flags;
2152         struct gs_port *port;
2153
2154         if (dev == NULL)
2155                 return;
2156
2157         for (i=0; i<GS_NUM_PORTS; i++) {
2158                 if ((port=dev->dev_port[i]) != NULL) {
2159                         dev->dev_port[i] = NULL;
2160
2161                         spin_lock_irqsave(&port->port_lock, flags);
2162
2163                         if (port->port_write_buf != NULL) {
2164                                 gs_buf_free(port->port_write_buf);
2165                                 port->port_write_buf = NULL;
2166                         }
2167
2168                         if (port->port_open_count > 0 || port->port_in_use) {
2169                                 port->port_dev = NULL;
2170                                 wake_up_interruptible(&port->port_write_wait);
2171                                 if (port->port_tty) {
2172                                         wake_up_interruptible(&port->port_tty->read_wait);
2173                                         wake_up_interruptible(&port->port_tty->write_wait);
2174                                 }
2175                                 spin_unlock_irqrestore(&port->port_lock, flags);
2176                         } else {
2177                                 spin_unlock_irqrestore(&port->port_lock, flags);
2178                                 kfree(port);
2179                         }
2180
2181                 }
2182         }
2183 }
2184
2185 /* Circular Buffer */
2186
2187 /*
2188  * gs_buf_alloc
2189  *
2190  * Allocate a circular buffer and all associated memory.
2191  */
2192 static struct gs_buf *gs_buf_alloc(unsigned int size, gfp_t kmalloc_flags)
2193 {
2194         struct gs_buf *gb;
2195
2196         if (size == 0)
2197                 return NULL;
2198
2199         gb = (struct gs_buf *)kmalloc(sizeof(struct gs_buf), kmalloc_flags);
2200         if (gb == NULL)
2201                 return NULL;
2202
2203         gb->buf_buf = kmalloc(size, kmalloc_flags);
2204         if (gb->buf_buf == NULL) {
2205                 kfree(gb);
2206                 return NULL;
2207         }
2208
2209         gb->buf_size = size;
2210         gb->buf_get = gb->buf_put = gb->buf_buf;
2211
2212         return gb;
2213 }
2214
2215 /*
2216  * gs_buf_free
2217  *
2218  * Free the buffer and all associated memory.
2219  */
2220 void gs_buf_free(struct gs_buf *gb)
2221 {
2222         if (gb) {
2223                 kfree(gb->buf_buf);
2224                 kfree(gb);
2225         }
2226 }
2227
2228 /*
2229  * gs_buf_clear
2230  *
2231  * Clear out all data in the circular buffer.
2232  */
2233 void gs_buf_clear(struct gs_buf *gb)
2234 {
2235         if (gb != NULL)
2236                 gb->buf_get = gb->buf_put;
2237                 /* equivalent to a get of all data available */
2238 }
2239
2240 /*
2241  * gs_buf_data_avail
2242  *
2243  * Return the number of bytes of data available in the circular
2244  * buffer.
2245  */
2246 unsigned int gs_buf_data_avail(struct gs_buf *gb)
2247 {
2248         if (gb != NULL)
2249                 return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
2250         else
2251                 return 0;
2252 }
2253
2254 /*
2255  * gs_buf_space_avail
2256  *
2257  * Return the number of bytes of space available in the circular
2258  * buffer.
2259  */
2260 unsigned int gs_buf_space_avail(struct gs_buf *gb)
2261 {
2262         if (gb != NULL)
2263                 return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
2264         else
2265                 return 0;
2266 }
2267
2268 /*
2269  * gs_buf_put
2270  *
2271  * Copy data data from a user buffer and put it into the circular buffer.
2272  * Restrict to the amount of space available.
2273  *
2274  * Return the number of bytes copied.
2275  */
2276 unsigned int gs_buf_put(struct gs_buf *gb, const char *buf, unsigned int count)
2277 {
2278         unsigned int len;
2279
2280         if (gb == NULL)
2281                 return 0;
2282
2283         len  = gs_buf_space_avail(gb);
2284         if (count > len)
2285                 count = len;
2286
2287         if (count == 0)
2288                 return 0;
2289
2290         len = gb->buf_buf + gb->buf_size - gb->buf_put;
2291         if (count > len) {
2292                 memcpy(gb->buf_put, buf, len);
2293                 memcpy(gb->buf_buf, buf+len, count - len);
2294                 gb->buf_put = gb->buf_buf + count - len;
2295         } else {
2296                 memcpy(gb->buf_put, buf, count);
2297                 if (count < len)
2298                         gb->buf_put += count;
2299                 else /* count == len */
2300                         gb->buf_put = gb->buf_buf;
2301         }
2302
2303         return count;
2304 }
2305
2306 /*
2307  * gs_buf_get
2308  *
2309  * Get data from the circular buffer and copy to the given buffer.
2310  * Restrict to the amount of data available.
2311  *
2312  * Return the number of bytes copied.
2313  */
2314 unsigned int gs_buf_get(struct gs_buf *gb, char *buf, unsigned int count)
2315 {
2316         unsigned int len;
2317
2318         if (gb == NULL)
2319                 return 0;
2320
2321         len = gs_buf_data_avail(gb);
2322         if (count > len)
2323                 count = len;
2324
2325         if (count == 0)
2326                 return 0;
2327
2328         len = gb->buf_buf + gb->buf_size - gb->buf_get;
2329         if (count > len) {
2330                 memcpy(buf, gb->buf_get, len);
2331                 memcpy(buf+len, gb->buf_buf, count - len);
2332                 gb->buf_get = gb->buf_buf + count - len;
2333         } else {
2334                 memcpy(buf, gb->buf_get, count);
2335                 if (count < len)
2336                         gb->buf_get += count;
2337                 else /* count == len */
2338                         gb->buf_get = gb->buf_buf;
2339         }
2340
2341         return count;
2342 }