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