Staging: quatech_usb2: implement open functionality
[safe/jmp/linux-2.6] / drivers / staging / quatech_usb2 / quatech_usb2.c
1 /*
2  * Driver for Quatech Inc USB2.0 to serial adaptors. Largely unrelated to the
3  * serqt_usb driver, based on a re-write of the vendor supplied serqt_usb2 code,
4  * which is unrelated to the serqt_usb2 in the staging kernel
5  */
6
7 #include <linux/errno.h>
8 #include <linux/init.h>
9 #include <linux/slab.h>
10 #include <linux/tty.h>
11 #include <linux/tty_driver.h>
12 #include <linux/tty_flip.h>
13 #include <linux/module.h>
14 #include <linux/serial.h>
15 #include <linux/usb.h>
16 #include <linux/usb/serial.h>
17 #include <linux/uaccess.h>
18
19 static int debug;
20
21 /* Version Information */
22 #define DRIVER_VERSION "v2.00"
23 #define DRIVER_AUTHOR "Tim Gobeli, Quatech, Inc"
24 #define DRIVER_DESC "Quatech USB 2.0 to Serial Driver"
25
26 /* vendor and device IDs */
27 #define USB_VENDOR_ID_QUATECH 0x061d    /* Quatech VID */
28 #define QUATECH_SSU2_100 0xC120         /* RS232 single port */
29 #define QUATECH_DSU2_100 0xC140         /* RS232 dual port */
30 #define QUATECH_DSU2_400 0xC150         /* RS232/422/485 dual port */
31 #define QUATECH_QSU2_100 0xC160         /* RS232 four port */
32 #define QUATECH_QSU2_400 0xC170         /* RS232/422/485 four port */
33 #define QUATECH_ESU2_100 0xC1A0         /* RS232 eight port */
34 #define QUATECH_ESU2_400 0xC180         /* RS232/422/485 eight port */
35
36 /* magic numbers go here, when we find out which ones are needed */
37
38 #define QU2BOXPWRON 0x8000              /* magic number to turn FPGA power on */
39 #define QU2BOX232 0x40                  /* RS232 mode on MEI devices */
40 #define QU2BOXSPD9600 0x60              /* set speed to 9600 baud */
41 #define FIFO_DEPTH 1024                 /* size of hardware fifos */
42 /* directions for USB transfers */
43 #define USBD_TRANSFER_DIRECTION_IN    0xc0
44 #define USBD_TRANSFER_DIRECTION_OUT   0x40
45 /* special Quatech command IDs */
46 #define QT_SET_GET_DEVICE               0xc2
47 #define QT_OPEN_CLOSE_CHANNEL           0xca
48 /*#define QT_GET_SET_PREBUF_TRIG_LVL    0xcc
49 #define QT_SET_ATF                      0xcd
50 #define QT_GET_SET_REGISTER             0xc0*/
51 #define QT_GET_SET_UART                 0xc1
52 /*#define QT_HW_FLOW_CONTROL_MASK               0xc5
53 #define QT_SW_FLOW_CONTROL_MASK         0xc6
54 #define QT_SW_FLOW_CONTROL_DISABLE      0xc7
55 #define QT_BREAK_CONTROL                0xc8
56 #define QT_STOP_RECEIVE                 0xe0
57 #define QT_FLUSH_DEVICE                 0xc4*/
58 #define QT_GET_SET_QMCR                 0xe1
59 /* port setting constants */
60 #define  SERIAL_MCR_DTR             0x01
61 #define  SERIAL_MCR_RTS             0x02
62 #define  SERIAL_MCR_LOOP            0x10
63
64 #define  SERIAL_MSR_CTS             0x10
65 #define  SERIAL_MSR_CD              0x80
66 #define  SERIAL_MSR_RI              0x40
67 #define  SERIAL_MSR_DSR             0x20
68 #define  SERIAL_MSR_MASK            0xf0
69
70 #define  SERIAL_8_DATA              0x03
71 #define  SERIAL_7_DATA              0x02
72 #define  SERIAL_6_DATA              0x01
73 #define  SERIAL_5_DATA              0x00
74
75 #define  SERIAL_ODD_PARITY          0X08
76 #define  SERIAL_EVEN_PARITY         0X18
77 #define  SERIAL_TWO_STOPB           0x04
78 #define  SERIAL_ONE_STOPB           0x00
79
80 #define  MAX_BAUD_RATE              921600
81 #define  MAX_BAUD_REMAINDER         4608
82
83 #define SERIAL_LSR_OE       0x02
84 #define SERIAL_LSR_PE       0x04
85 #define SERIAL_LSR_FE       0x08
86 #define SERIAL_LSR_BI       0x10
87
88 /* handy macros for doing escape sequence parsing on data reads */
89 #define THISCHAR        ((unsigned char *)(urb->transfer_buffer))[i]
90 #define NEXTCHAR        ((unsigned char *)(urb->transfer_buffer))[i + 1]
91 #define THIRDCHAR       ((unsigned char *)(urb->transfer_buffer))[i + 2]
92 #define FOURTHCHAR      ((unsigned char *)(urb->transfer_buffer))[i + 3]
93 #define FIFTHCHAR       ((unsigned char *)(urb->transfer_buffer))[i + 4]
94
95 static struct usb_device_id quausb2_id_table[] = {
96         {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_SSU2_100)},
97         {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU2_100)},
98         {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU2_400)},
99         {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU2_100)},
100         {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU2_400)},
101         {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU2_100)},
102         {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU2_400)},
103         {}      /* Terminating entry */
104 };
105
106 MODULE_DEVICE_TABLE(usb, quausb2_id_table);
107
108 /* custom structures we need go here */
109 static struct usb_driver quausb2_usb_driver = {
110         .name = "quatech-usb2-serial",
111         .probe = usb_serial_probe,
112         .disconnect = usb_serial_disconnect,
113         .id_table = quausb2_id_table,
114         .no_dynamic_id = 1,
115 };
116
117 /** structure in which to keep all the messy stuff that this driver needs
118  * alongside the usb_serial_port structure
119  * @param read_urb_busy Flag indicating that port->read_urb is in use
120  * @param close_pending flag indicating that this port is in the process of
121  * being closed.
122  * @param shadowLSR Last received state of the line status register, holds the
123  * value of the line status flags from the port
124  * @param shadowMSR Last received state of the modem status register, holds
125  * the value of the modem status received from the port
126  * @param xmit_pending_bytes Number of bytes waiting to be sent out of
127  * the serial port
128  * @param xmit_fifo_room_bytes free space available in the transmit fifo
129  * for this port on the box
130  * @param rcv_flush Flag indicating that a receive flush has been requested by
131  * the hardware.
132  * @param xmit_flush Flag indicating that a transmit flush has been requested by
133  * the hardware.
134  */
135 struct quatech2_port {
136         int     magic;
137         bool    read_urb_busy;
138         bool    close_pending;
139         __u8    shadowLSR;
140         __u8    shadowMSR;
141         int     xmit_pending_bytes;
142         int     xmit_fifo_room_bytes;
143         char    rcv_flush;
144         char    xmit_flush;
145
146         char    active;         /* someone has this device open */
147         unsigned char           *xfer_to_tty_buffer;
148         wait_queue_head_t       wait;
149         int     open_count;     /* number of times this port has been opened */
150         struct semaphore        sem;    /* locks this structure */
151         __u8    shadowLCR;      /* last LCR value received */
152         __u8    shadowMCR;      /* last MCR value received */
153         char    RxHolding;
154         char    fifo_empty_flag;
155         struct semaphore        pend_xmit_sem;  /* locks this structure */
156         spinlock_t lock;
157 };
158
159 /**
160  * Structure to hold device-wide internal status information
161  * @param ReadBulkStopped The last bulk read attempt ended in tears
162  * @param open_ports The number of serial ports currently in use on the box
163  * @param current_port Pointer to the serial port structure of the port which
164  * the read stream is currently directed to. Escape sequences in the read
165  * stream will change this around as data arrives from different ports on the
166  * box
167  */
168 struct quatech2_dev {
169         bool    ReadBulkStopped;
170         char    open_ports;
171         struct usb_serial_port *current_port;
172 };
173
174 /* structure which holds line and modem status flags */
175 struct qt2_status_data {
176         __u8 line_status;
177         __u8 modem_status;
178 };
179
180 /* Function prototypes */
181 static int qt2_boxpoweron(struct usb_serial *serial);
182 static int qt2_boxsetQMCR(struct usb_serial *serial, __u16 Uart_Number,
183                         __u8 QMCR_Value);
184 static int port_paranoia_check(struct usb_serial_port *port,
185                         const char *function);
186 static int serial_paranoia_check(struct usb_serial *serial,
187                          const char *function);
188 static inline struct quatech2_port *qt2_get_port_private(struct usb_serial_port
189                         *port);
190 static inline void qt2_set_port_private(struct usb_serial_port *port,
191                         struct quatech2_port *data);
192 static inline struct quatech2_dev *qt2_get_dev_private(struct usb_serial
193                         *serial);
194 static inline void qt2_set_dev_private(struct usb_serial *serial,
195                         struct quatech2_dev *data);
196 static int qt2_openboxchannel(struct usb_serial *serial, __u16
197                         Uart_Number, struct qt2_status_data *pDeviceData);
198 static int qt2_closeboxchannel(struct usb_serial *serial, __u16
199                         Uart_Number);
200 static int qt2_conf_uart(struct usb_serial *serial,  unsigned short Uart_Number,
201                          unsigned short divisor, unsigned char LCR);
202 static void qt2_read_bulk_callback(struct urb *urb);
203 static void qt2_process_line_status(struct usb_serial_port *port,
204                               unsigned char LineStatus);
205 static void qt2_process_modem_status(struct usb_serial_port *port,
206                                unsigned char ModemStatus);
207 static void qt2_process_xmit_empty(struct usb_serial_port *port,
208         unsigned char fourth_char, unsigned char fifth_char);
209 static void qt2_process_port_change(struct usb_serial_port *port,
210                               unsigned char New_Current_Port);
211 static void qt2_process_rcv_flush(struct usb_serial_port *port);
212 static void qt2_process_xmit_flush(struct usb_serial_port *port);
213 static void qt2_process_rx_char(struct usb_serial_port *port,
214                                 unsigned char data);
215
216 /* implementation functions, roughly in order of use, are here */
217 static int qt2_calc_num_ports(struct usb_serial *serial)
218 {
219         int num_ports;
220         int flag_as_400;
221         switch (serial->dev->descriptor.idProduct) {
222         case QUATECH_SSU2_100:
223                 num_ports = 1;
224                 break;
225
226         case QUATECH_DSU2_400:
227                 flag_as_400 = true;
228         case QUATECH_DSU2_100:
229                 num_ports = 2;
230         break;
231
232         case QUATECH_QSU2_400:
233                 flag_as_400 = true;
234         case QUATECH_QSU2_100:
235                 num_ports = 4;
236         break;
237
238         case QUATECH_ESU2_400:
239                 flag_as_400 = true;
240         case QUATECH_ESU2_100:
241                 num_ports = 8;
242         break;
243         default:
244         num_ports = 1;
245         break;
246         }
247         return num_ports;
248 }
249
250 static int qt2_attach(struct usb_serial *serial)
251 {
252         struct usb_serial_port *port;
253         struct quatech2_port *qt2_port; /* port-specific private data pointer */
254         struct quatech2_dev  *qt2_dev;  /* dev-specific private data pointer */
255         int i;
256         /* stuff for storing endpoint addresses now */
257         struct usb_endpoint_descriptor *endpoint;
258         struct usb_host_interface *iface_desc;
259         struct usb_serial_port *port0;  /* first port structure on device */
260
261         /* check how many endpoints there are on the device, for
262          * sanity's sake */
263         dbg("%s(): Endpoints: %d bulk in, %d bulk out, %d interrupt in",
264                         __func__, serial->num_bulk_in,
265                         serial->num_bulk_out, serial->num_interrupt_in);
266         if ((serial->num_bulk_in != 1) || (serial->num_bulk_out != 1)) {
267                 dbg("Device has wrong number of bulk endpoints!");
268                 return -ENODEV;
269         }
270         iface_desc = serial->interface->cur_altsetting;
271
272         /* Set up per-device private data, storing extra data alongside
273          * struct usb_serial */
274         qt2_dev = kzalloc(sizeof(*qt2_dev), GFP_KERNEL);
275         if (!qt2_dev) {
276                 dbg("%s: kmalloc for quatech2_dev failed!",
277                     __func__);
278                 return -ENOMEM;
279         }
280         qt2_dev->open_ports = 0;        /* no ports open */
281         qt2_set_dev_private(serial, qt2_dev);   /* store private data */
282
283         /* Now setup per port private data, which replaces all the things
284          * that quatech added to standard kernel structures in their driver */
285         for (i = 0; i < serial->num_ports; i++) {
286                 port = serial->port[i];
287                 qt2_port = kzalloc(sizeof(*qt2_port), GFP_KERNEL);
288                 if (!qt2_port) {
289                         dbg("%s: kmalloc for quatech2_port (%d) failed!.",
290                             __func__, i);
291                         return -ENOMEM;
292                 }
293                 spin_lock_init(&qt2_port->lock);
294                 usb_set_serial_port_data(port, qt2_port);
295         }
296
297         /* gain access to port[0]'s structure because we want to store
298          * device-level stuff in it */
299         if (serial_paranoia_check(serial, __func__))
300                 return -ENODEV;
301         port0 = serial->port[0]; /* get the first port's device structure */
302
303         /* print endpoint addresses so we can check them later
304          * by hand */
305         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
306                 endpoint = &iface_desc->endpoint[i].desc;
307                 if ((endpoint->bEndpointAddress & 0x80) &&
308                         ((endpoint->bmAttributes & 3) == 0x02)) {
309                         /* we found a bulk in endpoint */
310                         dbg("found bulk in at 0x%x",
311                                 endpoint->bEndpointAddress);
312                 }
313
314                 if (((endpoint->bEndpointAddress & 0x80) == 0x00) &&
315                         ((endpoint->bmAttributes & 3) == 0x02)) {
316                         /* we found a bulk out endpoint */
317                         dbg("found bulk out at 0x%x",
318                                 endpoint->bEndpointAddress);
319                 }
320         }       /* end printing endpoint addresses */
321
322         /* switch on power to the hardware */
323         if (qt2_boxpoweron(serial) < 0) {
324                 dbg("qt2_boxpoweron() failed");
325                 goto startup_error;
326         }
327         /* set all ports to RS232 mode */
328         for (i = 0; i < serial->num_ports; ++i) {
329                 if (qt2_boxsetQMCR(serial, i, QU2BOX232) < 0) {
330                         dbg("qt2_boxsetQMCR() on port %d failed",
331                                 i);
332                         goto startup_error;
333                 }
334         }
335
336         return 0;
337
338 startup_error:
339         for (i = 0; i < serial->num_ports; i++) {
340                 port = serial->port[i];
341                 qt2_port = qt2_get_port_private(port);
342                 kfree(qt2_port);
343                 qt2_set_port_private(port, NULL);
344         }
345         qt2_dev = qt2_get_dev_private(serial);
346         kfree(qt2_dev);
347         qt2_set_dev_private(serial, NULL);
348
349         dbg("Exit fail %s\n", __func__);
350         return -EIO;
351 }
352
353 static void qt2_release(struct usb_serial *serial)
354 {
355         struct usb_serial_port *port;
356         struct quatech2_port *qt_port;
357         int i;
358
359         dbg("enterting %s", __func__);
360
361         for (i = 0; i < serial->num_ports; i++) {
362                 port = serial->port[i];
363                 if (!port)
364                         continue;
365
366                 qt_port = usb_get_serial_port_data(port);
367                 kfree(qt_port);
368                 usb_set_serial_port_data(port, NULL);
369         }
370 }
371 /* This function is called once per serial port on the device.
372  * The tty_struct and the usb_serial_port belong to this port,
373  * i.e. there are multiple ones for a multi-port device.
374  * However the usb_serial_port structure has a back-pointer
375  * to the parent usb_serial structure which belongs to the device,
376  * so we can access either the device-wide information or
377  * any other port's information (because there are also forward
378  * pointers) via that pointer.
379  * This is most helpful if the device shares resources (e.g. end
380  * points) between different ports
381  */
382 int qt2_open(struct tty_struct *tty,
383             struct usb_serial_port *port, struct file *filp)
384 {
385         struct usb_serial *serial;      /* device structure */
386         struct usb_serial_port *port0;  /* first port structure on device */
387         struct quatech2_port *port_extra;       /* extra data for this port */
388         struct quatech2_port *port0_extra;      /* extra data for first port */
389         struct quatech2_dev *dev_extra;         /* extra data for the device */
390         struct qt2_status_data ChannelData;
391         unsigned short default_divisor = QU2BOXSPD9600;
392         unsigned char  default_LCR = SERIAL_8_DATA;
393         int status;
394         int result;
395
396         if (port_paranoia_check(port, __func__))
397                 return -ENODEV;
398
399         dbg("%s(): port %d", __func__, port->number);
400
401         serial = port->serial;  /* get the parent device structure */
402         if (serial_paranoia_check(serial, __func__)) {
403                 dbg("usb_serial struct failed sanity check");
404                 return -ENODEV;
405         }
406         dev_extra = qt2_get_dev_private(serial);
407         /* get the device private data */
408         port0 = serial->port[0]; /* get the first port's device structure */
409         if (port_paranoia_check(port, __func__)) {
410                 dbg("port0 usb_serial_port struct failed sanity check");
411                 return -ENODEV;
412         }
413         port_extra = qt2_get_port_private(port);
414         port0_extra = qt2_get_port_private(port0);
415
416         if (port_extra == NULL || port0_extra == NULL) {
417                 dbg("failed to get private data for port and port0");
418                 return -ENODEV;
419         }
420
421         usb_clear_halt(serial->dev, port->write_urb->pipe);
422         usb_clear_halt(serial->dev, port->read_urb->pipe);
423
424         /* FIXME: are these needed?  Does it even do anything useful? */
425         /* get the modem and line status values from the UART */
426         status = qt2_openboxchannel(serial, port->number,
427                         &ChannelData);
428         if (status < 0) {
429                 dbg("qt2_openboxchannel on channel %d failed",
430                     port->number);
431                 return status;
432         }
433         port_extra->shadowLSR = ChannelData.line_status &
434                         (SERIAL_LSR_OE | SERIAL_LSR_PE | SERIAL_LSR_FE |
435                         SERIAL_LSR_BI);
436
437         port_extra->shadowMSR = ChannelData.modem_status &
438                         (SERIAL_MSR_CTS | SERIAL_MSR_DSR | SERIAL_MSR_RI |
439                         SERIAL_MSR_CD);
440
441         port_extra->fifo_empty_flag = true;
442         dbg("qt2_openboxchannel on channel %d completed.",
443             port->number);
444
445         /* Set Baud rate to default and turn off flow control here */
446         status = qt2_conf_uart(serial, port->number, default_divisor,
447                                 default_LCR);
448         if (status < 0) {
449                 dbg("qt2_conf_uart() failed on channel %d",
450                     port->number);
451                 return status;
452         }
453         dbg("qt2_conf_uart() completed on channel %d",
454                 port->number);
455
456         /*
457          * At this point we will need some end points to make further progress.
458          * Handlily, the correct endpoint addresses have been filled out into
459          * the usb_serial_port structure for us by the driver core, so we
460          * already have access to them.
461          * As there is only one bulk in and one bulk out end-point, these are in
462          * port[0]'s structure, and the rest are uninitialised. Handily,
463          * when we do a write to a port, we will use the same endpoint
464          * regardless of the port, with a 5-byte header added on to
465          * tell the box which port it should eventually come out of, so we only
466          * need the one set of endpoints.
467          * Finally we need a bulk in URB to use for background reads from the
468          * device, which will deal with uplink data from the box to host.
469          */
470         dbg("port number is %d", port->number);
471         dbg("serial number is %d", port->serial->minor);
472         dbg("port0 bulk in endpoint is %#.2x", port0->bulk_in_endpointAddress);
473         dbg("port0 bulk out endpoint is %#.2x",
474                 port0->bulk_out_endpointAddress);
475
476         if (dev_extra->open_ports == 0) {
477                 /* this is first port to be opened, so need some URBs */
478                 /* initialise read_urb for bulk in transfers */
479                 usb_fill_bulk_urb(port0->read_urb, serial->dev,
480                         usb_rcvbulkpipe(serial->dev,
481                         port0->bulk_in_endpointAddress),
482                         port0->bulk_in_buffer,
483                         port0->bulk_in_size,
484                         qt2_read_bulk_callback, serial);
485                 dbg("port0 bulk in URB intialised");
486
487                 /* submit URB, i.e. start reading from device (async) */
488                 dev_extra->ReadBulkStopped = false;
489                 port_extra->read_urb_busy = true;
490                 result = usb_submit_urb(port->read_urb, GFP_KERNEL);
491                 if (result) {
492                         dev_err(&port->dev,
493                                  "%s - Error %d submitting bulk in urb\n",
494                                 __func__, result);
495                         port_extra->read_urb_busy = false;
496                 }
497         }
498
499         /* initialize our wait queues */
500         init_waitqueue_head(&port_extra->wait);
501
502         /* remember to store port_extra and port0 back again at end !*/
503         qt2_set_port_private(port, port_extra);
504         qt2_set_port_private(serial->port[0], port0_extra);
505         qt2_set_dev_private(serial, dev_extra);
506
507         dev_extra->open_ports++;        /* one more port opened */
508
509         return 0;
510 }
511
512 /* internal, private helper functions for the driver */
513
514 /* Power up the FPGA in the box to get it working */
515 static int qt2_boxpoweron(struct usb_serial *serial)
516 {
517         int result;
518         __u8  Direcion;
519         unsigned int pipe;
520         Direcion = USBD_TRANSFER_DIRECTION_OUT;
521         pipe = usb_rcvctrlpipe(serial->dev, 0);
522         result = usb_control_msg(serial->dev, pipe, QT_SET_GET_DEVICE,
523                                 Direcion, QU2BOXPWRON, 0x00, NULL, 0x00,
524                                 5000);
525         return result;
526 }
527
528 /*
529  * qt2_boxsetQMCR Issue a QT_GET_SET_QMCR vendor-spcific request on the
530  * default control pipe. If successful return the number of bytes written,
531  * otherwise return a negative error number of the problem.
532  */
533 static int qt2_boxsetQMCR(struct usb_serial *serial, __u16 Uart_Number,
534                           __u8 QMCR_Value)
535 {
536         int result;
537         __u16 PortSettings;
538
539         PortSettings = (__u16)(QMCR_Value);
540
541         dbg("%s(): Port = %d, PortSettings = 0x%x", __func__,
542                         Uart_Number, PortSettings);
543
544         result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
545                                 QT_GET_SET_QMCR, 0x40, PortSettings,
546                                 (__u16)Uart_Number, NULL, 0, 5000);
547         return result;
548 }
549
550 static int port_paranoia_check(struct usb_serial_port *port,
551                                const char *function)
552 {
553         if (!port) {
554                 dbg("%s - port == NULL", function);
555                 return -1;
556         }
557         if (!port->serial) {
558                 dbg("%s - port->serial == NULL\n", function);
559                 return -1;
560         }
561         return 0;
562 }
563
564 static int serial_paranoia_check(struct usb_serial *serial,
565                                  const char *function)
566 {
567         if (!serial) {
568                 dbg("%s - serial == NULL\n", function);
569                 return -1;
570         }
571
572         if (!serial->type) {
573                 dbg("%s - serial->type == NULL!", function);
574                 return -1;
575         }
576
577         return 0;
578 }
579
580 static inline struct quatech2_port *qt2_get_port_private(struct usb_serial_port
581                 *port)
582 {
583         return (struct quatech2_port *)usb_get_serial_port_data(port);
584 }
585
586 static inline void qt2_set_port_private(struct usb_serial_port *port,
587                 struct quatech2_port *data)
588 {
589         usb_set_serial_port_data(port, (void *)data);
590 }
591
592 static inline struct quatech2_dev *qt2_get_dev_private(struct usb_serial
593                 *serial)
594 {
595         return (struct quatech2_dev *)usb_get_serial_data(serial);
596 }
597 static inline void qt2_set_dev_private(struct usb_serial *serial,
598                 struct quatech2_dev *data)
599 {
600         usb_set_serial_data(serial, (void *)data);
601 }
602
603 static int qt2_openboxchannel(struct usb_serial *serial, __u16
604                 Uart_Number, struct qt2_status_data *status)
605 {
606         int result;
607         __u16 length;
608         __u8  Direcion;
609         unsigned int pipe;
610         length = sizeof(struct qt2_status_data);
611         Direcion = USBD_TRANSFER_DIRECTION_IN;
612         pipe = usb_rcvctrlpipe(serial->dev, 0);
613         result = usb_control_msg(serial->dev, pipe, QT_OPEN_CLOSE_CHANNEL,
614                         Direcion, 0x00, Uart_Number, status, length, 5000);
615         return result;
616 }
617 static int qt2_closeboxchannel(struct usb_serial *serial, __u16 Uart_Number)
618 {
619         int result;
620         __u8  direcion;
621         unsigned int pipe;
622         direcion = USBD_TRANSFER_DIRECTION_OUT;
623         pipe = usb_sndctrlpipe(serial->dev, 0);
624         result = usb_control_msg(serial->dev, pipe, QT_OPEN_CLOSE_CHANNEL,
625                   direcion, 0, Uart_Number, NULL, 0, 5000);
626         return result;
627 }
628
629 /* qt2_conf_uart Issue a SET_UART vendor-spcific request on the default
630  * control pipe. If successful sets baud rate divisor and LCR value
631  */
632 static int qt2_conf_uart(struct usb_serial *serial,  unsigned short Uart_Number,
633                       unsigned short divisor, unsigned char LCR)
634 {
635         int result;
636         unsigned short UartNumandLCR;
637
638         UartNumandLCR = (LCR << 8) + Uart_Number;
639
640         result = usb_control_msg(serial->dev, usb_sndctrlpipe(serial->dev, 0),
641                                 QT_GET_SET_UART, 0x40, divisor, UartNumandLCR,
642                                 NULL, 0, 300);
643         return result;
644 }
645
646 /** @brief Callback for asynchronous submission of URBs on bulk in
647  * endpoints
648  *
649  * Registered in qt2_open_port(), used to deal with incomming data
650  * from the box.
651  */
652 static void qt2_read_bulk_callback(struct urb *urb)
653 {
654         /* Get the device pointer (struct usb_serial) back out of the URB */
655         struct usb_serial *serial = urb->context;
656         /* get the extra struct for the device */
657         struct quatech2_dev *dev_extra = qt2_get_dev_private(serial);
658         /* Get first port structure from the device */
659         struct usb_serial_port *port0 = serial->port[0];
660         /* Get the currently active port structure from serial struct */
661         struct usb_serial_port *active = dev_extra->current_port;
662         /* get the extra struct for port 0 */
663         struct quatech2_port *port0_extra = qt2_get_port_private(port0);
664         /* and for the currently active port */
665         struct quatech2_port *active_extra = qt2_get_port_private(active);
666         /* When we finally get to doing some tty stuff, we will need this */
667         struct tty_struct *tty_st;
668         unsigned int RxCount;   /* the length of the data to process */
669         unsigned int i; /* loop counter over the data to process */
670         int result;     /* return value cache variable */
671         bool escapeflag;        /* flag set to true if this loop iteration is
672                                  * parsing an escape sequence, rather than
673                                  * ordinary data */
674
675
676         dbg("%s(): callback running", __func__);
677
678         if (urb->status) {
679                 /* read didn't go well */
680                 dev_extra->ReadBulkStopped = true;
681                 dbg("%s(): nonzero write bulk status received: %d",
682                         __func__, urb->status);
683                 return;
684         }
685
686         /* inline port_sofrint() here */
687         if (port_paranoia_check(port0, __func__) != 0) {
688                 dbg("%s - port_paranoia_check on port0 failed, exiting\n",
689 __func__);
690                 return;
691         }
692         if (port_paranoia_check(active, __func__) != 0) {
693                 dbg("%s - port_paranoia_check on current_port "
694                         "failed, exiting", __func__);
695                 return;
696         }
697
698 /* This single callback function has to do for all the ports on
699  * the device. Data being read up the USB can contain certain
700  * escape sequences which are used to communicate out-of-band
701  * information from the serial port in-band over the USB.
702  * These escapes include sending modem and flow control line
703  * status, and switching the port. The concept of a "Current Port"
704  * is used, which is where data is going until a port change
705  * escape seqence is received. This Current Port is kept between
706  * callbacks so that when this function enters we know which the
707  * currently active port is and can get to work right away without
708  * the box having to send repeat escape sequences (anyway, how
709  * would it know to do so?).
710  */
711
712         if (active_extra->close_pending == true) {
713                 /* We are closing , stop reading */
714                 dbg("%s - (active->close_pending == true", __func__);
715                 if (dev_extra->open_ports <= 0) {
716                         /* If this is the only port left open - stop the
717                          * bulk read */
718                         dev_extra->ReadBulkStopped = true;
719                         dbg("%s - (ReadBulkStopped == true;", __func__);
720                         return;
721                 }
722         }
723
724         /*
725          * RxHolding is asserted by throttle, if we assert it, we're not
726          * receiving any more characters and let the box handle the flow
727          * control
728          */
729         if ((port0_extra->RxHolding == true) &&
730                     (serial->dev->descriptor.idProduct == QUATECH_SSU2_100)) {
731                 /* single port device, input is already stopped, so we don't
732                  * need any more input data */
733                 dev_extra->ReadBulkStopped = true;
734                         return;
735         }
736         /* finally, we are in a situation where we might consider the data
737          * that is contained within the URB, and what to do about it.
738          * This is likely to involved communicating up to the TTY layer, so
739          * we will need to get hold of the tty for the port we are currently
740          * dealing with */
741
742         /* active is a usb_serial_port. It has a member port which is a
743          * tty_port. From this we get a tty_struct pointer which is what we
744          * actually wanted, and keep it on tty_st */
745         tty_st = tty_port_tty_get(&active->port);
746         if (!tty_st) {
747                 dbg("%s - bad tty pointer - exiting", __func__);
748                 return;
749         }
750         dbg("%s(): active port %d, tty_st =0x%p\n", __func__, active->number,
751                 tty_st);
752         RxCount = urb->actual_length;   /* grab length of data handy */
753
754         if (RxCount) {
755                 /* skip all this if no data to process */
756                 for (i = 0; i < RxCount ; ++i) {
757                         /* Look ahead code here -works on several bytes at onc*/
758                         if ((i <= (RxCount - 3)) && (THISCHAR == 0x1b)
759                                 && (NEXTCHAR == 0x1b)) {
760                                 /* we are in an escape sequence, type
761                                  * determined by the 3rd char */
762                                 escapeflag = false;
763                                 switch (THIRDCHAR) {
764                                 case 0x00:
765                                         /* Line status change 4th byte must
766                                          * follow */
767                                         if (i > (RxCount - 4)) {
768                                                 dbg("Illegal escape sequences "
769                                                 "in received data");
770                                                 break;
771                                         }
772                                         qt2_process_line_status(active,
773                                                 FOURTHCHAR);
774                                         i += 3;
775                                         escapeflag = true;
776                                         break;
777                                 case 0x01:
778                                         /* Modem status status change 4th byte
779                                          * must follow */
780                                         if (i > (RxCount - 4)) {
781                                                 dbg("Illegal escape sequences "
782                                                 "in received data");
783                                                 break;
784                                         }
785                                         qt2_process_modem_status(active,
786                                                 FOURTHCHAR);
787                                         i += 3;
788                                         escapeflag = true;
789                                         break;
790                                 case 0x02:
791                                         /* xmit hold empty 4th byte
792                                          * must follow */
793                                         if (i > (RxCount - 4)) {
794                                                 dbg("Illegal escape sequences "
795                                                 "in received data");
796                                                 break;
797                                         }
798                                         qt2_process_xmit_empty(active,
799                                                 FOURTHCHAR,
800                                                         FIFTHCHAR);
801                                         i += 4;
802                                         escapeflag = true;
803                                         break;
804                                 case 0x03:
805                                         /* Port number change 4th byte
806                                          * must follow */
807                                         if (i > (RxCount - 4)) {
808                                                 dbg("Illegal escape sequences "
809                                                 "in received data");
810                                                 break;
811                                         }
812                                         /* Port change. If port open push
813                                          * current data up to tty layer */
814                                         if (dev_extra->open_ports > 0)
815                                                 tty_flip_buffer_push(tty_st);
816
817                                         dbg("Port Change: new port = %d",
818                                                 FOURTHCHAR);
819                                         qt2_process_port_change(active,
820                                                 FOURTHCHAR);
821                                         i += 3;
822                                         escapeflag = true;
823                                         /* having changed port, the pointers for
824                                          * the currently active port are all out
825                                          * of date and need updating */
826                                         active = dev_extra->current_port;
827                                         active_extra =
828                                                 qt2_get_port_private(active);
829                                         tty_st = tty_port_tty_get(
830                                                 &active->port);
831                                         break;
832                                 case 0x04:
833                                         /* Recv flush 3rd byte must
834                                          * follow */
835                                         if (i > (RxCount - 3)) {
836                                                 dbg("Illegal escape sequences "
837                                                         "in received data");
838                                                 break;
839                                         }
840                                         qt2_process_rcv_flush(active);
841                                         i += 2;
842                                         escapeflag = true;
843                                         break;
844                                 case 0x05:
845                                         /* xmit flush 3rd byte must follow */
846                                         if (i > (RxCount - 3)) {
847                                                 dbg("Illegal escape sequences "
848                                                 "in received data");
849                                                 break;
850                                         }
851                                         qt2_process_xmit_flush(active);
852                                         i += 2;
853                                         escapeflag = true;
854                                         break;
855                                 case 0xff:
856                                         dbg("No status sequence");
857                                         qt2_process_rx_char(active, THISCHAR);
858                                         qt2_process_rx_char(active, NEXTCHAR);
859                                         i += 2;
860                                         break;
861                                 default:
862                                         qt2_process_rx_char(active, THISCHAR);
863                                         i += 1;
864                                         break;
865                                 } /*end switch*/
866                                 if (escapeflag == true)
867                                         continue;
868                                 /* if we did an escape char, we don't need
869                                  * to mess around pushing data through the
870                                  * tty layer, and can go round again */
871                         } /*endif*/
872                         if (tty_st && urb->actual_length) {
873                                 tty_buffer_request_room(tty_st, 1);
874                                 tty_insert_flip_string(tty_st,
875                                         &((unsigned char *)(urb->transfer_buffer)
876                                                 )[i],
877                                         1);
878                         }
879                 } /*endfor*/
880                 tty_flip_buffer_push(tty_st);
881         } /*endif*/
882
883         /* at this point we have complete dealing with the data for this
884          * callback. All we have to do now is to start the async read process
885          * back off again. */
886
887         usb_fill_bulk_urb(port0->read_urb, serial->dev,
888                 usb_rcvbulkpipe(serial->dev, port0->bulk_in_endpointAddress),
889                 port0->bulk_in_buffer, port0->bulk_in_size,
890                 qt2_read_bulk_callback, serial);
891         result = usb_submit_urb(port0->read_urb, GFP_ATOMIC);
892         if (result) {
893                 dbg("%s(): failed resubmitting read urb, error %d",
894                         __func__, result);
895         } else {
896                 if (tty_st && RxCount) {
897                         /* if some inbound data was processed, then
898                          * we need to push that through the tty layer
899                          */
900                         tty_flip_buffer_push(tty_st);
901                         tty_schedule_flip(tty_st);
902                 }
903         }
904
905         /* cribbed from serqt_usb2 driver, but not sure which work needs
906          * scheduling - port0 or currently active port? */
907         /* schedule_work(&port->work); */
908
909         return;
910 }
911 static void qt2_process_line_status(struct usb_serial_port *port,
912         unsigned char LineStatus)
913 {
914         /* obtain the private structure for the port */
915         struct quatech2_port *port_extra = qt2_get_port_private(port);
916         port_extra->shadowLSR = LineStatus & (SERIAL_LSR_OE | SERIAL_LSR_PE |
917                 SERIAL_LSR_FE | SERIAL_LSR_BI);
918 }
919 static void qt2_process_modem_status(struct usb_serial_port *port,
920         unsigned char ModemStatus)
921 {
922         /* obtain the private structure for the port */
923         struct quatech2_port *port_extra = qt2_get_port_private(port);
924         port_extra->shadowMSR = ModemStatus;
925         /* ?? */
926         wake_up_interruptible(&port_extra->wait);
927 }
928
929 static void qt2_process_xmit_empty(struct usb_serial_port *port,
930         unsigned char fourth_char, unsigned char fifth_char)
931 {
932         int byte_count;
933         /* obtain the private structure for the port */
934         struct quatech2_port *port_extra = qt2_get_port_private(port);
935
936         byte_count = (int)(fifth_char * 16);
937         byte_count +=  (int)fourth_char;
938         port_extra->xmit_pending_bytes -= (int)byte_count;
939         port_extra->xmit_fifo_room_bytes = FIFO_DEPTH;
940 }
941
942 static void qt2_process_port_change(struct usb_serial_port *port,
943         unsigned char New_Current_Port)
944 {
945         /* obtain the parent usb serial device structure */
946         struct usb_serial *serial = port->serial;
947         /* obtain the private structure for the device */
948         struct quatech2_dev *dev_extra = qt2_get_dev_private(serial);
949         dev_extra->current_port = serial->port[New_Current_Port];
950         /* what should I do with this? commented out in upstream
951          * driver */
952         /*schedule_work(&port->work);*/
953 }
954
955 static void qt2_process_rcv_flush(struct usb_serial_port *port)
956 {
957         /* obtain the private structure for the port */
958         struct quatech2_port *port_extra = qt2_get_port_private(port);
959         port_extra->rcv_flush = true;
960 }
961 static void qt2_process_xmit_flush(struct usb_serial_port *port)
962 {
963         /* obtain the private structure for the port */
964         struct quatech2_port *port_extra = qt2_get_port_private(port);
965         port_extra->xmit_flush = true;
966 }
967
968 static void qt2_process_rx_char(struct usb_serial_port *port,
969         unsigned char data)
970 {
971         /* get the tty_struct for this port */
972         struct tty_struct *tty = tty_port_tty_get(&(port->port));
973         /* get the URB with the data in to push */
974         struct urb *urb = port->serial->port[0]->read_urb;
975
976         if (tty && urb->actual_length) {
977                 tty_buffer_request_room(tty, 1);
978                 tty_insert_flip_string(tty, &data, 1);
979                 /* should this be commented out here? */
980                 /*tty_flip_buffer_push(tty);*/
981         }
982 }
983 /*
984  * last things in file: stuff to register this driver into the generic
985  * USB serial framework.
986  */
987
988 static struct usb_serial_driver quatech2_device = {
989         .driver = {
990                 .owner = THIS_MODULE,
991                 .name = "quatech_usb2",
992         },
993         .description = DRIVER_DESC,
994         .usb_driver = &quausb2_usb_driver,
995         .id_table = quausb2_id_table,
996         .num_ports = 8,
997         .open = qt2_open,
998         /*.close = qt_close,
999         .write = qt_write,
1000         .write_room = qt_write_room,
1001         .chars_in_buffer = qt_chars_in_buffer,
1002         .throttle = qt_throttle,
1003         .unthrottle = qt_unthrottle,*/
1004         .calc_num_ports = qt2_calc_num_ports,
1005         /*.ioctl = qt_ioctl,
1006         .set_termios = qt_set_termios,
1007         .break_ctl = qt_break,
1008         .tiocmget = qt_tiocmget,
1009         .tiocmset = qt_tiocmset,*/
1010         .attach = qt2_attach,
1011         .release = qt2_release,
1012 };
1013
1014 static int __init quausb2_usb_init(void)
1015 {
1016         int retval;
1017
1018         dbg("%s\n", __func__);
1019
1020         /* register with usb-serial */
1021         retval = usb_serial_register(&quatech2_device);
1022
1023         if (retval)
1024                 goto failed_usb_serial_register;
1025
1026         printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
1027                         DRIVER_DESC "\n");
1028
1029         /* register with usb */
1030
1031         retval = usb_register(&quausb2_usb_driver);
1032         if (retval == 0)
1033                 return 0;
1034
1035         /* if we're here, usb_register() failed */
1036         usb_serial_deregister(&quatech2_device);
1037 failed_usb_serial_register:
1038                 return retval;
1039 }
1040
1041
1042
1043 static void __exit quausb2_usb_exit(void)
1044 {
1045         usb_deregister(&quausb2_usb_driver);
1046         usb_serial_deregister(&quatech2_device);
1047 }
1048
1049 module_init(quausb2_usb_init);
1050 module_exit(quausb2_usb_exit);
1051
1052 MODULE_AUTHOR(DRIVER_AUTHOR);
1053 MODULE_DESCRIPTION(DRIVER_DESC);
1054 MODULE_LICENSE("GPL");
1055
1056 module_param(debug, bool, S_IRUGO | S_IWUSR);
1057 MODULE_PARM_DESC(debug, "Debug enabled or not");