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