Merge tag 'for-6.1-rc4-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave...
[linux-block.git] / drivers / usb / serial / cypress_m8.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * USB Cypress M8 driver
4  *
5  *      Copyright (C) 2004
6  *          Lonnie Mendez (dignome@gmail.com)
7  *      Copyright (C) 2003,2004
8  *          Neil Whelchel (koyama@firstlight.net)
9  *
10  * See Documentation/usb/usb-serial.rst for more information on using this
11  * driver
12  *
13  * See http://geocities.com/i0xox0i for information on this driver and the
14  * earthmate usb device.
15  */
16
17 /* Thanks to Neil Whelchel for writing the first cypress m8 implementation
18    for linux. */
19 /* Thanks to cypress for providing references for the hid reports. */
20 /* Thanks to Jiang Zhang for providing links and for general help. */
21 /* Code originates and was built up from ftdi_sio, belkin, pl2303 and others.*/
22
23
24 #include <linux/kernel.h>
25 #include <linux/errno.h>
26 #include <linux/slab.h>
27 #include <linux/tty.h>
28 #include <linux/tty_driver.h>
29 #include <linux/tty_flip.h>
30 #include <linux/module.h>
31 #include <linux/moduleparam.h>
32 #include <linux/spinlock.h>
33 #include <linux/usb.h>
34 #include <linux/usb/serial.h>
35 #include <linux/serial.h>
36 #include <linux/kfifo.h>
37 #include <linux/delay.h>
38 #include <linux/uaccess.h>
39 #include <asm/unaligned.h>
40
41 #include "cypress_m8.h"
42
43
44 static bool stats;
45 static int interval;
46 static bool unstable_bauds;
47
48 #define DRIVER_AUTHOR "Lonnie Mendez <dignome@gmail.com>, Neil Whelchel <koyama@firstlight.net>"
49 #define DRIVER_DESC "Cypress USB to Serial Driver"
50
51 /* write buffer size defines */
52 #define CYPRESS_BUF_SIZE        1024
53
54 static const struct usb_device_id id_table_earthmate[] = {
55         { USB_DEVICE(VENDOR_ID_DELORME, PRODUCT_ID_EARTHMATEUSB) },
56         { USB_DEVICE(VENDOR_ID_DELORME, PRODUCT_ID_EARTHMATEUSB_LT20) },
57         { }                                             /* Terminating entry */
58 };
59
60 static const struct usb_device_id id_table_cyphidcomrs232[] = {
61         { USB_DEVICE(VENDOR_ID_CYPRESS, PRODUCT_ID_CYPHIDCOM) },
62         { USB_DEVICE(VENDOR_ID_SAI, PRODUCT_ID_CYPHIDCOM) },
63         { USB_DEVICE(VENDOR_ID_POWERCOM, PRODUCT_ID_UPS) },
64         { USB_DEVICE(VENDOR_ID_FRWD, PRODUCT_ID_CYPHIDCOM_FRWD) },
65         { }                                             /* Terminating entry */
66 };
67
68 static const struct usb_device_id id_table_nokiaca42v2[] = {
69         { USB_DEVICE(VENDOR_ID_DAZZLE, PRODUCT_ID_CA42) },
70         { }                                             /* Terminating entry */
71 };
72
73 static const struct usb_device_id id_table_combined[] = {
74         { USB_DEVICE(VENDOR_ID_DELORME, PRODUCT_ID_EARTHMATEUSB) },
75         { USB_DEVICE(VENDOR_ID_DELORME, PRODUCT_ID_EARTHMATEUSB_LT20) },
76         { USB_DEVICE(VENDOR_ID_CYPRESS, PRODUCT_ID_CYPHIDCOM) },
77         { USB_DEVICE(VENDOR_ID_SAI, PRODUCT_ID_CYPHIDCOM) },
78         { USB_DEVICE(VENDOR_ID_POWERCOM, PRODUCT_ID_UPS) },
79         { USB_DEVICE(VENDOR_ID_FRWD, PRODUCT_ID_CYPHIDCOM_FRWD) },
80         { USB_DEVICE(VENDOR_ID_DAZZLE, PRODUCT_ID_CA42) },
81         { }                                             /* Terminating entry */
82 };
83
84 MODULE_DEVICE_TABLE(usb, id_table_combined);
85
86 enum packet_format {
87         packet_format_1,  /* b0:status, b1:payload count */
88         packet_format_2   /* b0[7:3]:status, b0[2:0]:payload count */
89 };
90
91 struct cypress_private {
92         spinlock_t lock;                   /* private lock */
93         int chiptype;                      /* identifier of device, for quirks/etc */
94         int bytes_in;                      /* used for statistics */
95         int bytes_out;                     /* used for statistics */
96         int cmd_count;                     /* used for statistics */
97         int cmd_ctrl;                      /* always set this to 1 before issuing a command */
98         struct kfifo write_fifo;           /* write fifo */
99         int write_urb_in_use;              /* write urb in use indicator */
100         int write_urb_interval;            /* interval to use for write urb */
101         int read_urb_interval;             /* interval to use for read urb */
102         int comm_is_ok;                    /* true if communication is (still) ok */
103         __u8 line_control;                 /* holds dtr / rts value */
104         __u8 current_status;               /* received from last read - info on dsr,cts,cd,ri,etc */
105         __u8 current_config;               /* stores the current configuration byte */
106         __u8 rx_flags;                     /* throttling - used from whiteheat/ftdi_sio */
107         enum packet_format pkt_fmt;        /* format to use for packet send / receive */
108         int get_cfg_unsafe;                /* If true, the CYPRESS_GET_CONFIG is unsafe */
109         int baud_rate;                     /* stores current baud rate in
110                                               integer form */
111         char prev_status;                  /* used for TIOCMIWAIT */
112 };
113
114 /* function prototypes for the Cypress USB to serial device */
115 static int  cypress_earthmate_port_probe(struct usb_serial_port *port);
116 static int  cypress_hidcom_port_probe(struct usb_serial_port *port);
117 static int  cypress_ca42v2_port_probe(struct usb_serial_port *port);
118 static void cypress_port_remove(struct usb_serial_port *port);
119 static int  cypress_open(struct tty_struct *tty, struct usb_serial_port *port);
120 static void cypress_close(struct usb_serial_port *port);
121 static void cypress_dtr_rts(struct usb_serial_port *port, int on);
122 static int  cypress_write(struct tty_struct *tty, struct usb_serial_port *port,
123                         const unsigned char *buf, int count);
124 static void cypress_send(struct usb_serial_port *port);
125 static unsigned int cypress_write_room(struct tty_struct *tty);
126 static void cypress_earthmate_init_termios(struct tty_struct *tty);
127 static void cypress_set_termios(struct tty_struct *tty,
128                                 struct usb_serial_port *port,
129                                 const struct ktermios *old_termios);
130 static int  cypress_tiocmget(struct tty_struct *tty);
131 static int  cypress_tiocmset(struct tty_struct *tty,
132                         unsigned int set, unsigned int clear);
133 static unsigned int cypress_chars_in_buffer(struct tty_struct *tty);
134 static void cypress_throttle(struct tty_struct *tty);
135 static void cypress_unthrottle(struct tty_struct *tty);
136 static void cypress_set_dead(struct usb_serial_port *port);
137 static void cypress_read_int_callback(struct urb *urb);
138 static void cypress_write_int_callback(struct urb *urb);
139
140 static struct usb_serial_driver cypress_earthmate_device = {
141         .driver = {
142                 .owner =                THIS_MODULE,
143                 .name =                 "earthmate",
144         },
145         .description =                  "DeLorme Earthmate USB",
146         .id_table =                     id_table_earthmate,
147         .num_ports =                    1,
148         .port_probe =                   cypress_earthmate_port_probe,
149         .port_remove =                  cypress_port_remove,
150         .open =                         cypress_open,
151         .close =                        cypress_close,
152         .dtr_rts =                      cypress_dtr_rts,
153         .write =                        cypress_write,
154         .write_room =                   cypress_write_room,
155         .init_termios =                 cypress_earthmate_init_termios,
156         .set_termios =                  cypress_set_termios,
157         .tiocmget =                     cypress_tiocmget,
158         .tiocmset =                     cypress_tiocmset,
159         .tiocmiwait =                   usb_serial_generic_tiocmiwait,
160         .chars_in_buffer =              cypress_chars_in_buffer,
161         .throttle =                     cypress_throttle,
162         .unthrottle =                   cypress_unthrottle,
163         .read_int_callback =            cypress_read_int_callback,
164         .write_int_callback =           cypress_write_int_callback,
165 };
166
167 static struct usb_serial_driver cypress_hidcom_device = {
168         .driver = {
169                 .owner =                THIS_MODULE,
170                 .name =                 "cyphidcom",
171         },
172         .description =                  "HID->COM RS232 Adapter",
173         .id_table =                     id_table_cyphidcomrs232,
174         .num_ports =                    1,
175         .port_probe =                   cypress_hidcom_port_probe,
176         .port_remove =                  cypress_port_remove,
177         .open =                         cypress_open,
178         .close =                        cypress_close,
179         .dtr_rts =                      cypress_dtr_rts,
180         .write =                        cypress_write,
181         .write_room =                   cypress_write_room,
182         .set_termios =                  cypress_set_termios,
183         .tiocmget =                     cypress_tiocmget,
184         .tiocmset =                     cypress_tiocmset,
185         .tiocmiwait =                   usb_serial_generic_tiocmiwait,
186         .chars_in_buffer =              cypress_chars_in_buffer,
187         .throttle =                     cypress_throttle,
188         .unthrottle =                   cypress_unthrottle,
189         .read_int_callback =            cypress_read_int_callback,
190         .write_int_callback =           cypress_write_int_callback,
191 };
192
193 static struct usb_serial_driver cypress_ca42v2_device = {
194         .driver = {
195                 .owner =                THIS_MODULE,
196                 .name =                 "nokiaca42v2",
197         },
198         .description =                  "Nokia CA-42 V2 Adapter",
199         .id_table =                     id_table_nokiaca42v2,
200         .num_ports =                    1,
201         .port_probe =                   cypress_ca42v2_port_probe,
202         .port_remove =                  cypress_port_remove,
203         .open =                         cypress_open,
204         .close =                        cypress_close,
205         .dtr_rts =                      cypress_dtr_rts,
206         .write =                        cypress_write,
207         .write_room =                   cypress_write_room,
208         .set_termios =                  cypress_set_termios,
209         .tiocmget =                     cypress_tiocmget,
210         .tiocmset =                     cypress_tiocmset,
211         .tiocmiwait =                   usb_serial_generic_tiocmiwait,
212         .chars_in_buffer =              cypress_chars_in_buffer,
213         .throttle =                     cypress_throttle,
214         .unthrottle =                   cypress_unthrottle,
215         .read_int_callback =            cypress_read_int_callback,
216         .write_int_callback =           cypress_write_int_callback,
217 };
218
219 static struct usb_serial_driver * const serial_drivers[] = {
220         &cypress_earthmate_device, &cypress_hidcom_device,
221         &cypress_ca42v2_device, NULL
222 };
223
224 /*****************************************************************************
225  * Cypress serial helper functions
226  *****************************************************************************/
227
228 /* FRWD Dongle hidcom needs to skip reset and speed checks */
229 static inline bool is_frwd(struct usb_device *dev)
230 {
231         return ((le16_to_cpu(dev->descriptor.idVendor) == VENDOR_ID_FRWD) &&
232                 (le16_to_cpu(dev->descriptor.idProduct) == PRODUCT_ID_CYPHIDCOM_FRWD));
233 }
234
235 static int analyze_baud_rate(struct usb_serial_port *port, speed_t new_rate)
236 {
237         struct cypress_private *priv;
238         priv = usb_get_serial_port_data(port);
239
240         if (unstable_bauds)
241                 return new_rate;
242
243         /* FRWD Dongle uses 115200 bps */
244         if (is_frwd(port->serial->dev))
245                 return new_rate;
246
247         /*
248          * The general purpose firmware for the Cypress M8 allows for
249          * a maximum speed of 57600bps (I have no idea whether DeLorme
250          * chose to use the general purpose firmware or not), if you
251          * need to modify this speed setting for your own project
252          * please add your own chiptype and modify the code likewise.
253          * The Cypress HID->COM device will work successfully up to
254          * 115200bps (but the actual throughput is around 3kBps).
255          */
256         if (port->serial->dev->speed == USB_SPEED_LOW) {
257                 /*
258                  * Mike Isely <isely@pobox.com> 2-Feb-2008: The
259                  * Cypress app note that describes this mechanism
260                  * states that the low-speed part can't handle more
261                  * than 800 bytes/sec, in which case 4800 baud is the
262                  * safest speed for a part like that.
263                  */
264                 if (new_rate > 4800) {
265                         dev_dbg(&port->dev,
266                                 "%s - failed setting baud rate, device incapable speed %d\n",
267                                 __func__, new_rate);
268                         return -1;
269                 }
270         }
271         switch (priv->chiptype) {
272         case CT_EARTHMATE:
273                 if (new_rate <= 600) {
274                         /* 300 and 600 baud rates are supported under
275                          * the generic firmware, but are not used with
276                          * NMEA and SiRF protocols */
277                         dev_dbg(&port->dev,
278                                 "%s - failed setting baud rate, unsupported speed of %d on Earthmate GPS\n",
279                                 __func__, new_rate);
280                         return -1;
281                 }
282                 break;
283         default:
284                 break;
285         }
286         return new_rate;
287 }
288
289
290 /* This function can either set or retrieve the current serial line settings */
291 static int cypress_serial_control(struct tty_struct *tty,
292         struct usb_serial_port *port, speed_t baud_rate, int data_bits,
293         int stop_bits, int parity_enable, int parity_type, int reset,
294         int cypress_request_type)
295 {
296         int new_baudrate = 0, retval = 0, tries = 0;
297         struct cypress_private *priv;
298         struct device *dev = &port->dev;
299         u8 *feature_buffer;
300         const unsigned int feature_len = 5;
301         unsigned long flags;
302
303         priv = usb_get_serial_port_data(port);
304
305         if (!priv->comm_is_ok)
306                 return -ENODEV;
307
308         feature_buffer = kcalloc(feature_len, sizeof(u8), GFP_KERNEL);
309         if (!feature_buffer)
310                 return -ENOMEM;
311
312         switch (cypress_request_type) {
313         case CYPRESS_SET_CONFIG:
314                 /* 0 means 'Hang up' so doesn't change the true bit rate */
315                 new_baudrate = priv->baud_rate;
316                 if (baud_rate && baud_rate != priv->baud_rate) {
317                         dev_dbg(dev, "%s - baud rate is changing\n", __func__);
318                         retval = analyze_baud_rate(port, baud_rate);
319                         if (retval >= 0) {
320                                 new_baudrate = retval;
321                                 dev_dbg(dev, "%s - New baud rate set to %d\n",
322                                         __func__, new_baudrate);
323                         }
324                 }
325                 dev_dbg(dev, "%s - baud rate is being sent as %d\n", __func__,
326                         new_baudrate);
327
328                 /* fill the feature_buffer with new configuration */
329                 put_unaligned_le32(new_baudrate, feature_buffer);
330                 feature_buffer[4] |= data_bits - 5;   /* assign data bits in 2 bit space ( max 3 ) */
331                 /* 1 bit gap */
332                 feature_buffer[4] |= (stop_bits << 3);   /* assign stop bits in 1 bit space */
333                 feature_buffer[4] |= (parity_enable << 4);   /* assign parity flag in 1 bit space */
334                 feature_buffer[4] |= (parity_type << 5);   /* assign parity type in 1 bit space */
335                 /* 1 bit gap */
336                 feature_buffer[4] |= (reset << 7);   /* assign reset at end of byte, 1 bit space */
337
338                 dev_dbg(dev, "%s - device is being sent this feature report:\n", __func__);
339                 dev_dbg(dev, "%s - %02X - %02X - %02X - %02X - %02X\n", __func__,
340                         feature_buffer[0], feature_buffer[1],
341                         feature_buffer[2], feature_buffer[3],
342                         feature_buffer[4]);
343
344                 do {
345                         retval = usb_control_msg(port->serial->dev,
346                                         usb_sndctrlpipe(port->serial->dev, 0),
347                                         HID_REQ_SET_REPORT,
348                                         USB_DIR_OUT | USB_RECIP_INTERFACE | USB_TYPE_CLASS,
349                                         0x0300, 0, feature_buffer,
350                                         feature_len, 500);
351
352                         if (tries++ >= 3)
353                                 break;
354
355                 } while (retval != feature_len &&
356                          retval != -ENODEV);
357
358                 if (retval != feature_len) {
359                         dev_err(dev, "%s - failed sending serial line settings - %d\n",
360                                 __func__, retval);
361                         cypress_set_dead(port);
362                 } else {
363                         spin_lock_irqsave(&priv->lock, flags);
364                         priv->baud_rate = new_baudrate;
365                         priv->current_config = feature_buffer[4];
366                         spin_unlock_irqrestore(&priv->lock, flags);
367                         /* If we asked for a speed change encode it */
368                         if (baud_rate)
369                                 tty_encode_baud_rate(tty,
370                                         new_baudrate, new_baudrate);
371                 }
372         break;
373         case CYPRESS_GET_CONFIG:
374                 if (priv->get_cfg_unsafe) {
375                         /* Not implemented for this device,
376                            and if we try to do it we're likely
377                            to crash the hardware. */
378                         retval = -ENOTTY;
379                         goto out;
380                 }
381                 dev_dbg(dev, "%s - retrieving serial line settings\n", __func__);
382                 do {
383                         retval = usb_control_msg(port->serial->dev,
384                                         usb_rcvctrlpipe(port->serial->dev, 0),
385                                         HID_REQ_GET_REPORT,
386                                         USB_DIR_IN | USB_RECIP_INTERFACE | USB_TYPE_CLASS,
387                                         0x0300, 0, feature_buffer,
388                                         feature_len, 500);
389
390                         if (tries++ >= 3)
391                                 break;
392                 } while (retval != feature_len
393                                                 && retval != -ENODEV);
394
395                 if (retval != feature_len) {
396                         dev_err(dev, "%s - failed to retrieve serial line settings - %d\n",
397                                 __func__, retval);
398                         cypress_set_dead(port);
399                         goto out;
400                 } else {
401                         spin_lock_irqsave(&priv->lock, flags);
402                         /* store the config in one byte, and later
403                            use bit masks to check values */
404                         priv->current_config = feature_buffer[4];
405                         priv->baud_rate = get_unaligned_le32(feature_buffer);
406                         spin_unlock_irqrestore(&priv->lock, flags);
407                 }
408         }
409         spin_lock_irqsave(&priv->lock, flags);
410         ++priv->cmd_count;
411         spin_unlock_irqrestore(&priv->lock, flags);
412 out:
413         kfree(feature_buffer);
414         return retval;
415 } /* cypress_serial_control */
416
417
418 static void cypress_set_dead(struct usb_serial_port *port)
419 {
420         struct cypress_private *priv = usb_get_serial_port_data(port);
421         unsigned long flags;
422
423         spin_lock_irqsave(&priv->lock, flags);
424         if (!priv->comm_is_ok) {
425                 spin_unlock_irqrestore(&priv->lock, flags);
426                 return;
427         }
428         priv->comm_is_ok = 0;
429         spin_unlock_irqrestore(&priv->lock, flags);
430
431         dev_err(&port->dev, "cypress_m8 suspending failing port %d - "
432                 "interval might be too short\n", port->port_number);
433 }
434
435
436 /*****************************************************************************
437  * Cypress serial driver functions
438  *****************************************************************************/
439
440
441 static int cypress_generic_port_probe(struct usb_serial_port *port)
442 {
443         struct usb_serial *serial = port->serial;
444         struct cypress_private *priv;
445
446         if (!port->interrupt_out_urb || !port->interrupt_in_urb) {
447                 dev_err(&port->dev, "required endpoint is missing\n");
448                 return -ENODEV;
449         }
450
451         priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL);
452         if (!priv)
453                 return -ENOMEM;
454
455         priv->comm_is_ok = !0;
456         spin_lock_init(&priv->lock);
457         if (kfifo_alloc(&priv->write_fifo, CYPRESS_BUF_SIZE, GFP_KERNEL)) {
458                 kfree(priv);
459                 return -ENOMEM;
460         }
461
462         /* Skip reset for FRWD device. It is a workaound:
463            device hangs if it receives SET_CONFIGURE in Configured
464            state. */
465         if (!is_frwd(serial->dev))
466                 usb_reset_configuration(serial->dev);
467
468         priv->cmd_ctrl = 0;
469         priv->line_control = 0;
470         priv->rx_flags = 0;
471         /* Default packet format setting is determined by packet size.
472            Anything with a size larger then 9 must have a separate
473            count field since the 3 bit count field is otherwise too
474            small.  Otherwise we can use the slightly more compact
475            format.  This is in accordance with the cypress_m8 serial
476            converter app note. */
477         if (port->interrupt_out_size > 9)
478                 priv->pkt_fmt = packet_format_1;
479         else
480                 priv->pkt_fmt = packet_format_2;
481
482         if (interval > 0) {
483                 priv->write_urb_interval = interval;
484                 priv->read_urb_interval = interval;
485                 dev_dbg(&port->dev, "%s - read & write intervals forced to %d\n",
486                         __func__, interval);
487         } else {
488                 priv->write_urb_interval = port->interrupt_out_urb->interval;
489                 priv->read_urb_interval = port->interrupt_in_urb->interval;
490                 dev_dbg(&port->dev, "%s - intervals: read=%d write=%d\n",
491                         __func__, priv->read_urb_interval,
492                         priv->write_urb_interval);
493         }
494         usb_set_serial_port_data(port, priv);
495
496         port->port.drain_delay = 256;
497
498         return 0;
499 }
500
501
502 static int cypress_earthmate_port_probe(struct usb_serial_port *port)
503 {
504         struct usb_serial *serial = port->serial;
505         struct cypress_private *priv;
506         int ret;
507
508         ret = cypress_generic_port_probe(port);
509         if (ret) {
510                 dev_dbg(&port->dev, "%s - Failed setting up port\n", __func__);
511                 return ret;
512         }
513
514         priv = usb_get_serial_port_data(port);
515         priv->chiptype = CT_EARTHMATE;
516         /* All Earthmate devices use the separated-count packet
517            format!  Idiotic. */
518         priv->pkt_fmt = packet_format_1;
519         if (serial->dev->descriptor.idProduct !=
520                                 cpu_to_le16(PRODUCT_ID_EARTHMATEUSB)) {
521                 /* The old original USB Earthmate seemed able to
522                    handle GET_CONFIG requests; everything they've
523                    produced since that time crashes if this command is
524                    attempted :-( */
525                 dev_dbg(&port->dev,
526                         "%s - Marking this device as unsafe for GET_CONFIG commands\n",
527                         __func__);
528                 priv->get_cfg_unsafe = !0;
529         }
530
531         return 0;
532 }
533
534 static int cypress_hidcom_port_probe(struct usb_serial_port *port)
535 {
536         struct cypress_private *priv;
537         int ret;
538
539         ret = cypress_generic_port_probe(port);
540         if (ret) {
541                 dev_dbg(&port->dev, "%s - Failed setting up port\n", __func__);
542                 return ret;
543         }
544
545         priv = usb_get_serial_port_data(port);
546         priv->chiptype = CT_CYPHIDCOM;
547
548         return 0;
549 }
550
551 static int cypress_ca42v2_port_probe(struct usb_serial_port *port)
552 {
553         struct cypress_private *priv;
554         int ret;
555
556         ret = cypress_generic_port_probe(port);
557         if (ret) {
558                 dev_dbg(&port->dev, "%s - Failed setting up port\n", __func__);
559                 return ret;
560         }
561
562         priv = usb_get_serial_port_data(port);
563         priv->chiptype = CT_CA42V2;
564
565         return 0;
566 }
567
568 static void cypress_port_remove(struct usb_serial_port *port)
569 {
570         struct cypress_private *priv;
571
572         priv = usb_get_serial_port_data(port);
573
574         kfifo_free(&priv->write_fifo);
575         kfree(priv);
576 }
577
578 static int cypress_open(struct tty_struct *tty, struct usb_serial_port *port)
579 {
580         struct cypress_private *priv = usb_get_serial_port_data(port);
581         struct usb_serial *serial = port->serial;
582         unsigned long flags;
583         int result = 0;
584
585         if (!priv->comm_is_ok)
586                 return -EIO;
587
588         /* clear halts before open */
589         usb_clear_halt(serial->dev, 0x81);
590         usb_clear_halt(serial->dev, 0x02);
591
592         spin_lock_irqsave(&priv->lock, flags);
593         /* reset read/write statistics */
594         priv->bytes_in = 0;
595         priv->bytes_out = 0;
596         priv->cmd_count = 0;
597         priv->rx_flags = 0;
598         spin_unlock_irqrestore(&priv->lock, flags);
599
600         /* Set termios */
601         cypress_send(port);
602
603         if (tty)
604                 cypress_set_termios(tty, port, NULL);
605
606         /* setup the port and start reading from the device */
607         usb_fill_int_urb(port->interrupt_in_urb, serial->dev,
608                 usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress),
609                 port->interrupt_in_urb->transfer_buffer,
610                 port->interrupt_in_urb->transfer_buffer_length,
611                 cypress_read_int_callback, port, priv->read_urb_interval);
612         result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
613
614         if (result) {
615                 dev_err(&port->dev,
616                         "%s - failed submitting read urb, error %d\n",
617                                                         __func__, result);
618                 cypress_set_dead(port);
619         }
620
621         return result;
622 } /* cypress_open */
623
624 static void cypress_dtr_rts(struct usb_serial_port *port, int on)
625 {
626         struct cypress_private *priv = usb_get_serial_port_data(port);
627         /* drop dtr and rts */
628         spin_lock_irq(&priv->lock);
629         if (on == 0)
630                 priv->line_control = 0;
631         else 
632                 priv->line_control = CONTROL_DTR | CONTROL_RTS;
633         priv->cmd_ctrl = 1;
634         spin_unlock_irq(&priv->lock);
635         cypress_write(NULL, port, NULL, 0);
636 }
637
638 static void cypress_close(struct usb_serial_port *port)
639 {
640         struct cypress_private *priv = usb_get_serial_port_data(port);
641         unsigned long flags;
642
643         spin_lock_irqsave(&priv->lock, flags);
644         kfifo_reset_out(&priv->write_fifo);
645         spin_unlock_irqrestore(&priv->lock, flags);
646
647         dev_dbg(&port->dev, "%s - stopping urbs\n", __func__);
648         usb_kill_urb(port->interrupt_in_urb);
649         usb_kill_urb(port->interrupt_out_urb);
650
651         if (stats)
652                 dev_info(&port->dev, "Statistics: %d Bytes In | %d Bytes Out | %d Commands Issued\n",
653                         priv->bytes_in, priv->bytes_out, priv->cmd_count);
654 } /* cypress_close */
655
656
657 static int cypress_write(struct tty_struct *tty, struct usb_serial_port *port,
658                                         const unsigned char *buf, int count)
659 {
660         struct cypress_private *priv = usb_get_serial_port_data(port);
661
662         dev_dbg(&port->dev, "%s - %d bytes\n", __func__, count);
663
664         /* line control commands, which need to be executed immediately,
665            are not put into the buffer for obvious reasons.
666          */
667         if (priv->cmd_ctrl) {
668                 count = 0;
669                 goto finish;
670         }
671
672         if (!count)
673                 return count;
674
675         count = kfifo_in_locked(&priv->write_fifo, buf, count, &priv->lock);
676
677 finish:
678         cypress_send(port);
679
680         return count;
681 } /* cypress_write */
682
683
684 static void cypress_send(struct usb_serial_port *port)
685 {
686         int count = 0, result, offset, actual_size;
687         struct cypress_private *priv = usb_get_serial_port_data(port);
688         struct device *dev = &port->dev;
689         unsigned long flags;
690
691         if (!priv->comm_is_ok)
692                 return;
693
694         dev_dbg(dev, "%s - interrupt out size is %d\n", __func__,
695                 port->interrupt_out_size);
696
697         spin_lock_irqsave(&priv->lock, flags);
698         if (priv->write_urb_in_use) {
699                 dev_dbg(dev, "%s - can't write, urb in use\n", __func__);
700                 spin_unlock_irqrestore(&priv->lock, flags);
701                 return;
702         }
703         spin_unlock_irqrestore(&priv->lock, flags);
704
705         /* clear buffer */
706         memset(port->interrupt_out_urb->transfer_buffer, 0,
707                                                 port->interrupt_out_size);
708
709         spin_lock_irqsave(&priv->lock, flags);
710         switch (priv->pkt_fmt) {
711         default:
712         case packet_format_1:
713                 /* this is for the CY7C64013... */
714                 offset = 2;
715                 port->interrupt_out_buffer[0] = priv->line_control;
716                 break;
717         case packet_format_2:
718                 /* this is for the CY7C63743... */
719                 offset = 1;
720                 port->interrupt_out_buffer[0] = priv->line_control;
721                 break;
722         }
723
724         if (priv->line_control & CONTROL_RESET)
725                 priv->line_control &= ~CONTROL_RESET;
726
727         if (priv->cmd_ctrl) {
728                 priv->cmd_count++;
729                 dev_dbg(dev, "%s - line control command being issued\n", __func__);
730                 spin_unlock_irqrestore(&priv->lock, flags);
731                 goto send;
732         } else
733                 spin_unlock_irqrestore(&priv->lock, flags);
734
735         count = kfifo_out_locked(&priv->write_fifo,
736                                         &port->interrupt_out_buffer[offset],
737                                         port->interrupt_out_size - offset,
738                                         &priv->lock);
739         if (count == 0)
740                 return;
741
742         switch (priv->pkt_fmt) {
743         default:
744         case packet_format_1:
745                 port->interrupt_out_buffer[1] = count;
746                 break;
747         case packet_format_2:
748                 port->interrupt_out_buffer[0] |= count;
749         }
750
751         dev_dbg(dev, "%s - count is %d\n", __func__, count);
752
753 send:
754         spin_lock_irqsave(&priv->lock, flags);
755         priv->write_urb_in_use = 1;
756         spin_unlock_irqrestore(&priv->lock, flags);
757
758         if (priv->cmd_ctrl)
759                 actual_size = 1;
760         else
761                 actual_size = count +
762                               (priv->pkt_fmt == packet_format_1 ? 2 : 1);
763
764         usb_serial_debug_data(dev, __func__, port->interrupt_out_size,
765                               port->interrupt_out_urb->transfer_buffer);
766
767         usb_fill_int_urb(port->interrupt_out_urb, port->serial->dev,
768                 usb_sndintpipe(port->serial->dev, port->interrupt_out_endpointAddress),
769                 port->interrupt_out_buffer, actual_size,
770                 cypress_write_int_callback, port, priv->write_urb_interval);
771         result = usb_submit_urb(port->interrupt_out_urb, GFP_ATOMIC);
772         if (result) {
773                 dev_err_console(port,
774                                 "%s - failed submitting write urb, error %d\n",
775                                                         __func__, result);
776                 priv->write_urb_in_use = 0;
777                 cypress_set_dead(port);
778         }
779
780         spin_lock_irqsave(&priv->lock, flags);
781         if (priv->cmd_ctrl)
782                 priv->cmd_ctrl = 0;
783
784         /* do not count the line control and size bytes */
785         priv->bytes_out += count;
786         spin_unlock_irqrestore(&priv->lock, flags);
787
788         usb_serial_port_softint(port);
789 } /* cypress_send */
790
791
792 /* returns how much space is available in the soft buffer */
793 static unsigned int cypress_write_room(struct tty_struct *tty)
794 {
795         struct usb_serial_port *port = tty->driver_data;
796         struct cypress_private *priv = usb_get_serial_port_data(port);
797         unsigned int room;
798         unsigned long flags;
799
800         spin_lock_irqsave(&priv->lock, flags);
801         room = kfifo_avail(&priv->write_fifo);
802         spin_unlock_irqrestore(&priv->lock, flags);
803
804         dev_dbg(&port->dev, "%s - returns %u\n", __func__, room);
805         return room;
806 }
807
808
809 static int cypress_tiocmget(struct tty_struct *tty)
810 {
811         struct usb_serial_port *port = tty->driver_data;
812         struct cypress_private *priv = usb_get_serial_port_data(port);
813         __u8 status, control;
814         unsigned int result = 0;
815         unsigned long flags;
816
817         spin_lock_irqsave(&priv->lock, flags);
818         control = priv->line_control;
819         status = priv->current_status;
820         spin_unlock_irqrestore(&priv->lock, flags);
821
822         result = ((control & CONTROL_DTR)        ? TIOCM_DTR : 0)
823                 | ((control & CONTROL_RTS)       ? TIOCM_RTS : 0)
824                 | ((status & UART_CTS)        ? TIOCM_CTS : 0)
825                 | ((status & UART_DSR)        ? TIOCM_DSR : 0)
826                 | ((status & UART_RI)         ? TIOCM_RI  : 0)
827                 | ((status & UART_CD)         ? TIOCM_CD  : 0);
828
829         dev_dbg(&port->dev, "%s - result = %x\n", __func__, result);
830
831         return result;
832 }
833
834
835 static int cypress_tiocmset(struct tty_struct *tty,
836                                unsigned int set, unsigned int clear)
837 {
838         struct usb_serial_port *port = tty->driver_data;
839         struct cypress_private *priv = usb_get_serial_port_data(port);
840         unsigned long flags;
841
842         spin_lock_irqsave(&priv->lock, flags);
843         if (set & TIOCM_RTS)
844                 priv->line_control |= CONTROL_RTS;
845         if (set & TIOCM_DTR)
846                 priv->line_control |= CONTROL_DTR;
847         if (clear & TIOCM_RTS)
848                 priv->line_control &= ~CONTROL_RTS;
849         if (clear & TIOCM_DTR)
850                 priv->line_control &= ~CONTROL_DTR;
851         priv->cmd_ctrl = 1;
852         spin_unlock_irqrestore(&priv->lock, flags);
853
854         return cypress_write(tty, port, NULL, 0);
855 }
856
857 static void cypress_earthmate_init_termios(struct tty_struct *tty)
858 {
859         tty_encode_baud_rate(tty, 4800, 4800);
860 }
861
862 static void cypress_set_termios(struct tty_struct *tty,
863                                 struct usb_serial_port *port,
864                                 const struct ktermios *old_termios)
865 {
866         struct cypress_private *priv = usb_get_serial_port_data(port);
867         struct device *dev = &port->dev;
868         int data_bits, stop_bits, parity_type, parity_enable;
869         unsigned int cflag;
870         unsigned long flags;
871         __u8 oldlines;
872         int linechange = 0;
873
874         /* Unsupported features need clearing */
875         tty->termios.c_cflag &= ~(CMSPAR|CRTSCTS);
876
877         cflag = tty->termios.c_cflag;
878
879         /* set number of data bits, parity, stop bits */
880         /* when parity is disabled the parity type bit is ignored */
881
882         /* 1 means 2 stop bits, 0 means 1 stop bit */
883         stop_bits = cflag & CSTOPB ? 1 : 0;
884
885         if (cflag & PARENB) {
886                 parity_enable = 1;
887                 /* 1 means odd parity, 0 means even parity */
888                 parity_type = cflag & PARODD ? 1 : 0;
889         } else
890                 parity_enable = parity_type = 0;
891
892         data_bits = tty_get_char_size(cflag);
893
894         spin_lock_irqsave(&priv->lock, flags);
895         oldlines = priv->line_control;
896         if ((cflag & CBAUD) == B0) {
897                 /* drop dtr and rts */
898                 dev_dbg(dev, "%s - dropping the lines, baud rate 0bps\n", __func__);
899                 priv->line_control &= ~(CONTROL_DTR | CONTROL_RTS);
900         } else
901                 priv->line_control = (CONTROL_DTR | CONTROL_RTS);
902         spin_unlock_irqrestore(&priv->lock, flags);
903
904         dev_dbg(dev, "%s - sending %d stop_bits, %d parity_enable, %d parity_type, %d data_bits (+5)\n",
905                 __func__, stop_bits, parity_enable, parity_type, data_bits);
906
907         cypress_serial_control(tty, port, tty_get_baud_rate(tty),
908                         data_bits, stop_bits,
909                         parity_enable, parity_type,
910                         0, CYPRESS_SET_CONFIG);
911
912         /* we perform a CYPRESS_GET_CONFIG so that the current settings are
913          * filled into the private structure this should confirm that all is
914          * working if it returns what we just set */
915         cypress_serial_control(tty, port, 0, 0, 0, 0, 0, 0, CYPRESS_GET_CONFIG);
916
917         /* Here we can define custom tty settings for devices; the main tty
918          * termios flag base comes from empeg.c */
919
920         spin_lock_irqsave(&priv->lock, flags);
921         if (priv->chiptype == CT_EARTHMATE && priv->baud_rate == 4800) {
922                 dev_dbg(dev, "Using custom termios settings for a baud rate of 4800bps.\n");
923                 /* define custom termios settings for NMEA protocol */
924
925                 tty->termios.c_iflag /* input modes - */
926                         &= ~(IGNBRK  /* disable ignore break */
927                         | BRKINT     /* disable break causes interrupt */
928                         | PARMRK     /* disable mark parity errors */
929                         | ISTRIP     /* disable clear high bit of input char */
930                         | INLCR      /* disable translate NL to CR */
931                         | IGNCR      /* disable ignore CR */
932                         | ICRNL      /* disable translate CR to NL */
933                         | IXON);     /* disable enable XON/XOFF flow control */
934
935                 tty->termios.c_oflag /* output modes */
936                         &= ~OPOST;    /* disable postprocess output char */
937
938                 tty->termios.c_lflag /* line discipline modes */
939                         &= ~(ECHO     /* disable echo input characters */
940                         | ECHONL      /* disable echo new line */
941                         | ICANON      /* disable erase, kill, werase, and rprnt
942                                          special characters */
943                         | ISIG        /* disable interrupt, quit, and suspend
944                                          special characters */
945                         | IEXTEN);    /* disable non-POSIX special characters */
946         } /* CT_CYPHIDCOM: Application should handle this for device */
947
948         linechange = (priv->line_control != oldlines);
949         spin_unlock_irqrestore(&priv->lock, flags);
950
951         /* if necessary, set lines */
952         if (linechange) {
953                 priv->cmd_ctrl = 1;
954                 cypress_write(tty, port, NULL, 0);
955         }
956 } /* cypress_set_termios */
957
958
959 /* returns amount of data still left in soft buffer */
960 static unsigned int cypress_chars_in_buffer(struct tty_struct *tty)
961 {
962         struct usb_serial_port *port = tty->driver_data;
963         struct cypress_private *priv = usb_get_serial_port_data(port);
964         unsigned int chars;
965         unsigned long flags;
966
967         spin_lock_irqsave(&priv->lock, flags);
968         chars = kfifo_len(&priv->write_fifo);
969         spin_unlock_irqrestore(&priv->lock, flags);
970
971         dev_dbg(&port->dev, "%s - returns %u\n", __func__, chars);
972         return chars;
973 }
974
975
976 static void cypress_throttle(struct tty_struct *tty)
977 {
978         struct usb_serial_port *port = tty->driver_data;
979         struct cypress_private *priv = usb_get_serial_port_data(port);
980
981         spin_lock_irq(&priv->lock);
982         priv->rx_flags = THROTTLED;
983         spin_unlock_irq(&priv->lock);
984 }
985
986
987 static void cypress_unthrottle(struct tty_struct *tty)
988 {
989         struct usb_serial_port *port = tty->driver_data;
990         struct cypress_private *priv = usb_get_serial_port_data(port);
991         int actually_throttled, result;
992
993         spin_lock_irq(&priv->lock);
994         actually_throttled = priv->rx_flags & ACTUALLY_THROTTLED;
995         priv->rx_flags = 0;
996         spin_unlock_irq(&priv->lock);
997
998         if (!priv->comm_is_ok)
999                 return;
1000
1001         if (actually_throttled) {
1002                 result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
1003                 if (result) {
1004                         dev_err(&port->dev, "%s - failed submitting read urb, "
1005                                         "error %d\n", __func__, result);
1006                         cypress_set_dead(port);
1007                 }
1008         }
1009 }
1010
1011
1012 static void cypress_read_int_callback(struct urb *urb)
1013 {
1014         struct usb_serial_port *port = urb->context;
1015         struct cypress_private *priv = usb_get_serial_port_data(port);
1016         struct device *dev = &urb->dev->dev;
1017         struct tty_struct *tty;
1018         unsigned char *data = urb->transfer_buffer;
1019         unsigned long flags;
1020         char tty_flag = TTY_NORMAL;
1021         int bytes = 0;
1022         int result;
1023         int i = 0;
1024         int status = urb->status;
1025
1026         switch (status) {
1027         case 0: /* success */
1028                 break;
1029         case -ECONNRESET:
1030         case -ENOENT:
1031         case -ESHUTDOWN:
1032                 /* precursor to disconnect so just go away */
1033                 return;
1034         case -EPIPE:
1035                 /* Can't call usb_clear_halt while in_interrupt */
1036                 fallthrough;
1037         default:
1038                 /* something ugly is going on... */
1039                 dev_err(dev, "%s - unexpected nonzero read status received: %d\n",
1040                         __func__, status);
1041                 cypress_set_dead(port);
1042                 return;
1043         }
1044
1045         spin_lock_irqsave(&priv->lock, flags);
1046         if (priv->rx_flags & THROTTLED) {
1047                 dev_dbg(dev, "%s - now throttling\n", __func__);
1048                 priv->rx_flags |= ACTUALLY_THROTTLED;
1049                 spin_unlock_irqrestore(&priv->lock, flags);
1050                 return;
1051         }
1052         spin_unlock_irqrestore(&priv->lock, flags);
1053
1054         tty = tty_port_tty_get(&port->port);
1055         if (!tty) {
1056                 dev_dbg(dev, "%s - bad tty pointer - exiting\n", __func__);
1057                 return;
1058         }
1059
1060         spin_lock_irqsave(&priv->lock, flags);
1061         result = urb->actual_length;
1062         switch (priv->pkt_fmt) {
1063         default:
1064         case packet_format_1:
1065                 /* This is for the CY7C64013... */
1066                 priv->current_status = data[0] & 0xF8;
1067                 bytes = data[1] + 2;
1068                 i = 2;
1069                 break;
1070         case packet_format_2:
1071                 /* This is for the CY7C63743... */
1072                 priv->current_status = data[0] & 0xF8;
1073                 bytes = (data[0] & 0x07) + 1;
1074                 i = 1;
1075                 break;
1076         }
1077         spin_unlock_irqrestore(&priv->lock, flags);
1078         if (result < bytes) {
1079                 dev_dbg(dev,
1080                         "%s - wrong packet size - received %d bytes but packet said %d bytes\n",
1081                         __func__, result, bytes);
1082                 goto continue_read;
1083         }
1084
1085         usb_serial_debug_data(&port->dev, __func__, urb->actual_length, data);
1086
1087         spin_lock_irqsave(&priv->lock, flags);
1088         /* check to see if status has changed */
1089         if (priv->current_status != priv->prev_status) {
1090                 u8 delta = priv->current_status ^ priv->prev_status;
1091
1092                 if (delta & UART_MSR_MASK) {
1093                         if (delta & UART_CTS)
1094                                 port->icount.cts++;
1095                         if (delta & UART_DSR)
1096                                 port->icount.dsr++;
1097                         if (delta & UART_RI)
1098                                 port->icount.rng++;
1099                         if (delta & UART_CD)
1100                                 port->icount.dcd++;
1101
1102                         wake_up_interruptible(&port->port.delta_msr_wait);
1103                 }
1104
1105                 priv->prev_status = priv->current_status;
1106         }
1107         spin_unlock_irqrestore(&priv->lock, flags);
1108
1109         /* hangup, as defined in acm.c... this might be a bad place for it
1110          * though */
1111         if (tty && !C_CLOCAL(tty) && !(priv->current_status & UART_CD)) {
1112                 dev_dbg(dev, "%s - calling hangup\n", __func__);
1113                 tty_hangup(tty);
1114                 goto continue_read;
1115         }
1116
1117         /* There is one error bit... I'm assuming it is a parity error
1118          * indicator as the generic firmware will set this bit to 1 if a
1119          * parity error occurs.
1120          * I can not find reference to any other error events. */
1121         spin_lock_irqsave(&priv->lock, flags);
1122         if (priv->current_status & CYP_ERROR) {
1123                 spin_unlock_irqrestore(&priv->lock, flags);
1124                 tty_flag = TTY_PARITY;
1125                 dev_dbg(dev, "%s - Parity Error detected\n", __func__);
1126         } else
1127                 spin_unlock_irqrestore(&priv->lock, flags);
1128
1129         /* process read if there is data other than line status */
1130         if (bytes > i) {
1131                 tty_insert_flip_string_fixed_flag(&port->port, data + i,
1132                                 tty_flag, bytes - i);
1133                 tty_flip_buffer_push(&port->port);
1134         }
1135
1136         spin_lock_irqsave(&priv->lock, flags);
1137         /* control and status byte(s) are also counted */
1138         priv->bytes_in += bytes;
1139         spin_unlock_irqrestore(&priv->lock, flags);
1140
1141 continue_read:
1142         tty_kref_put(tty);
1143
1144         /* Continue trying to always read */
1145
1146         if (priv->comm_is_ok) {
1147                 usb_fill_int_urb(port->interrupt_in_urb, port->serial->dev,
1148                                 usb_rcvintpipe(port->serial->dev,
1149                                         port->interrupt_in_endpointAddress),
1150                                 port->interrupt_in_urb->transfer_buffer,
1151                                 port->interrupt_in_urb->transfer_buffer_length,
1152                                 cypress_read_int_callback, port,
1153                                 priv->read_urb_interval);
1154                 result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC);
1155                 if (result && result != -EPERM) {
1156                         dev_err(dev, "%s - failed resubmitting read urb, error %d\n",
1157                                 __func__, result);
1158                         cypress_set_dead(port);
1159                 }
1160         }
1161 } /* cypress_read_int_callback */
1162
1163
1164 static void cypress_write_int_callback(struct urb *urb)
1165 {
1166         struct usb_serial_port *port = urb->context;
1167         struct cypress_private *priv = usb_get_serial_port_data(port);
1168         struct device *dev = &urb->dev->dev;
1169         int status = urb->status;
1170
1171         switch (status) {
1172         case 0:
1173                 /* success */
1174                 break;
1175         case -ECONNRESET:
1176         case -ENOENT:
1177         case -ESHUTDOWN:
1178                 /* this urb is terminated, clean up */
1179                 dev_dbg(dev, "%s - urb shutting down with status: %d\n",
1180                         __func__, status);
1181                 priv->write_urb_in_use = 0;
1182                 return;
1183         case -EPIPE:
1184                 /* Cannot call usb_clear_halt while in_interrupt */
1185                 fallthrough;
1186         default:
1187                 dev_err(dev, "%s - unexpected nonzero write status received: %d\n",
1188                         __func__, status);
1189                 cypress_set_dead(port);
1190                 break;
1191         }
1192         priv->write_urb_in_use = 0;
1193
1194         /* send any buffered data */
1195         cypress_send(port);
1196 }
1197
1198 module_usb_serial_driver(serial_drivers, id_table_combined);
1199
1200 MODULE_AUTHOR(DRIVER_AUTHOR);
1201 MODULE_DESCRIPTION(DRIVER_DESC);
1202 MODULE_LICENSE("GPL");
1203
1204 module_param(stats, bool, 0644);
1205 MODULE_PARM_DESC(stats, "Enable statistics or not");
1206 module_param(interval, int, 0644);
1207 MODULE_PARM_DESC(interval, "Overrides interrupt interval");
1208 module_param(unstable_bauds, bool, 0644);
1209 MODULE_PARM_DESC(unstable_bauds, "Allow unstable baud rates");