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