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