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