0af0b41ba9bc69ead5e57118c27d7d27d27f4edb
[pandora-kernel.git] / drivers / usb / serial / io_edgeport.c
1 /*
2  * Edgeport USB Serial Converter driver
3  *
4  * Copyright (C) 2000 Inside Out Networks, All rights reserved.
5  * Copyright (C) 2001-2002 Greg Kroah-Hartman <greg@kroah.com>
6  *
7  *      This program is free software; you can redistribute it and/or modify
8  *      it under the terms of the GNU General Public License as published by
9  *      the Free Software Foundation; either version 2 of the License, or
10  *      (at your option) any later version.
11  *
12  * Supports the following devices:
13  *      Edgeport/4
14  *      Edgeport/4t
15  *      Edgeport/2
16  *      Edgeport/4i
17  *      Edgeport/2i
18  *      Edgeport/421
19  *      Edgeport/21
20  *      Rapidport/4
21  *      Edgeport/8
22  *      Edgeport/2D8
23  *      Edgeport/4D8
24  *      Edgeport/8i
25  *
26  * For questions or problems with this driver, contact Inside Out
27  * Networks technical support, or Peter Berger <pberger@brimson.com>,
28  * or Al Borchers <alborchers@steinerpoint.com>.
29  *
30  */
31
32 #include <linux/kernel.h>
33 #include <linux/jiffies.h>
34 #include <linux/errno.h>
35 #include <linux/init.h>
36 #include <linux/slab.h>
37 #include <linux/tty.h>
38 #include <linux/tty_driver.h>
39 #include <linux/tty_flip.h>
40 #include <linux/module.h>
41 #include <linux/spinlock.h>
42 #include <linux/serial.h>
43 #include <linux/ioctl.h>
44 #include <linux/wait.h>
45 #include <linux/firmware.h>
46 #include <linux/ihex.h>
47 #include <linux/uaccess.h>
48 #include <linux/usb.h>
49 #include <linux/usb/serial.h>
50 #include "io_edgeport.h"
51 #include "io_ionsp.h"           /* info for the iosp messages */
52 #include "io_16654.h"           /* 16654 UART defines */
53
54 /*
55  * Version Information
56  */
57 #define DRIVER_VERSION "v2.7"
58 #define DRIVER_AUTHOR "Greg Kroah-Hartman <greg@kroah.com> and David Iacovelli"
59 #define DRIVER_DESC "Edgeport USB Serial Driver"
60
61 #define MAX_NAME_LEN            64
62
63 #define CHASE_TIMEOUT           (5*HZ)          /* 5 seconds */
64 #define OPEN_TIMEOUT            (5*HZ)          /* 5 seconds */
65 #define COMMAND_TIMEOUT         (5*HZ)          /* 5 seconds */
66
67 /* receive port state */
68 enum RXSTATE {
69         EXPECT_HDR1 = 0,    /* Expect header byte 1 */
70         EXPECT_HDR2 = 1,    /* Expect header byte 2 */
71         EXPECT_DATA = 2,    /* Expect 'RxBytesRemaining' data */
72         EXPECT_HDR3 = 3,    /* Expect header byte 3 (for status hdrs only) */
73 };
74
75
76 /* Transmit Fifo
77  * This Transmit queue is an extension of the edgeport Rx buffer.
78  * The maximum amount of data buffered in both the edgeport
79  * Rx buffer (maxTxCredits) and this buffer will never exceed maxTxCredits.
80  */
81 struct TxFifo {
82         unsigned int    head;   /* index to head pointer (write) */
83         unsigned int    tail;   /* index to tail pointer (read)  */
84         unsigned int    count;  /* Bytes in queue */
85         unsigned int    size;   /* Max size of queue (equal to Max number of TxCredits) */
86         unsigned char   *fifo;  /* allocated Buffer */
87 };
88
89 /* This structure holds all of the local port information */
90 struct edgeport_port {
91         __u16                   txCredits;              /* our current credits for this port */
92         __u16                   maxTxCredits;           /* the max size of the port */
93
94         struct TxFifo           txfifo;                 /* transmit fifo -- size will be maxTxCredits */
95         struct urb              *write_urb;             /* write URB for this port */
96         bool                    write_in_progress;      /* 'true' while a write URB is outstanding */
97         spinlock_t              ep_lock;
98
99         __u8                    shadowLCR;              /* last LCR value received */
100         __u8                    shadowMCR;              /* last MCR value received */
101         __u8                    shadowMSR;              /* last MSR value received */
102         __u8                    shadowLSR;              /* last LSR value received */
103         __u8                    shadowXonChar;          /* last value set as XON char in Edgeport */
104         __u8                    shadowXoffChar;         /* last value set as XOFF char in Edgeport */
105         __u8                    validDataMask;
106         __u32                   baudRate;
107
108         bool                    open;
109         bool                    openPending;
110         bool                    commandPending;
111         bool                    closePending;
112         bool                    chaseResponsePending;
113
114         wait_queue_head_t       wait_chase;             /* for handling sleeping while waiting for chase to finish */
115         wait_queue_head_t       wait_open;              /* for handling sleeping while waiting for open to finish */
116         wait_queue_head_t       wait_command;           /* for handling sleeping while waiting for command to finish */
117
118         struct async_icount     icount;
119         struct usb_serial_port  *port;                  /* loop back to the owner of this object */
120 };
121
122
123 /* This structure holds all of the individual device information */
124 struct edgeport_serial {
125         char                    name[MAX_NAME_LEN+2];           /* string name of this device */
126
127         struct edge_manuf_descriptor    manuf_descriptor;       /* the manufacturer descriptor */
128         struct edge_boot_descriptor     boot_descriptor;        /* the boot firmware descriptor */
129         struct edgeport_product_info    product_info;           /* Product Info */
130         struct edge_compatibility_descriptor epic_descriptor;   /* Edgeport compatible descriptor */
131         int                     is_epic;                        /* flag if EPiC device or not */
132
133         __u8                    interrupt_in_endpoint;          /* the interrupt endpoint handle */
134         unsigned char           *interrupt_in_buffer;           /* the buffer we use for the interrupt endpoint */
135         struct urb              *interrupt_read_urb;            /* our interrupt urb */
136
137         __u8                    bulk_in_endpoint;               /* the bulk in endpoint handle */
138         unsigned char           *bulk_in_buffer;                /* the buffer we use for the bulk in endpoint */
139         struct urb              *read_urb;                      /* our bulk read urb */
140         bool                    read_in_progress;
141         spinlock_t              es_lock;
142
143         __u8                    bulk_out_endpoint;              /* the bulk out endpoint handle */
144
145         __s16                   rxBytesAvail;                   /* the number of bytes that we need to read from this device */
146
147         enum RXSTATE            rxState;                        /* the current state of the bulk receive processor */
148         __u8                    rxHeader1;                      /* receive header byte 1 */
149         __u8                    rxHeader2;                      /* receive header byte 2 */
150         __u8                    rxHeader3;                      /* receive header byte 3 */
151         __u8                    rxPort;                         /* the port that we are currently receiving data for */
152         __u8                    rxStatusCode;                   /* the receive status code */
153         __u8                    rxStatusParam;                  /* the receive status paramater */
154         __s16                   rxBytesRemaining;               /* the number of port bytes left to read */
155         struct usb_serial       *serial;                        /* loop back to the owner of this object */
156 };
157
158 /* baud rate information */
159 struct divisor_table_entry {
160         __u32   BaudRate;
161         __u16  Divisor;
162 };
163
164 /*
165  * Define table of divisors for Rev A EdgePort/4 hardware
166  * These assume a 3.6864MHz crystal, the standard /16, and
167  * MCR.7 = 0.
168  */
169
170 static const struct divisor_table_entry divisor_table[] = {
171         {   50,         4608},
172         {   75,         3072},
173         {   110,        2095},  /* 2094.545455 => 230450   => .0217 % over */
174         {   134,        1713},  /* 1713.011152 => 230398.5 => .00065% under */
175         {   150,        1536},
176         {   300,        768},
177         {   600,        384},
178         {   1200,       192},
179         {   1800,       128},
180         {   2400,       96},
181         {   4800,       48},
182         {   7200,       32},
183         {   9600,       24},
184         {   14400,      16},
185         {   19200,      12},
186         {   38400,      6},
187         {   57600,      4},
188         {   115200,     2},
189         {   230400,     1},
190 };
191
192 /* local variables */
193 static int debug;
194
195 static atomic_t CmdUrbs;        /* Number of outstanding Command Write Urbs */
196
197
198 /* local function prototypes */
199
200 /* function prototypes for all URB callbacks */
201 static void edge_interrupt_callback(struct urb *urb);
202 static void edge_bulk_in_callback(struct urb *urb);
203 static void edge_bulk_out_data_callback(struct urb *urb);
204 static void edge_bulk_out_cmd_callback(struct urb *urb);
205
206 /* function prototypes for the usbserial callbacks */
207 static int edge_open(struct tty_struct *tty, struct usb_serial_port *port);
208 static void edge_close(struct usb_serial_port *port);
209 static int edge_write(struct tty_struct *tty, struct usb_serial_port *port,
210                                         const unsigned char *buf, int count);
211 static int edge_write_room(struct tty_struct *tty);
212 static int edge_chars_in_buffer(struct tty_struct *tty);
213 static void edge_throttle(struct tty_struct *tty);
214 static void edge_unthrottle(struct tty_struct *tty);
215 static void edge_set_termios(struct tty_struct *tty,
216                                         struct usb_serial_port *port,
217                                         struct ktermios *old_termios);
218 static int  edge_ioctl(struct tty_struct *tty,
219                                         unsigned int cmd, unsigned long arg);
220 static void edge_break(struct tty_struct *tty, int break_state);
221 static int  edge_tiocmget(struct tty_struct *tty);
222 static int  edge_tiocmset(struct tty_struct *tty,
223                                         unsigned int set, unsigned int clear);
224 static int  edge_get_icount(struct tty_struct *tty,
225                                 struct serial_icounter_struct *icount);
226 static int  edge_startup(struct usb_serial *serial);
227 static void edge_disconnect(struct usb_serial *serial);
228 static void edge_release(struct usb_serial *serial);
229
230 #include "io_tables.h"  /* all of the devices that this driver supports */
231
232 /* function prototypes for all of our local functions */
233
234 static void  process_rcvd_data(struct edgeport_serial *edge_serial,
235                                 unsigned char *buffer, __u16 bufferLength);
236 static void process_rcvd_status(struct edgeport_serial *edge_serial,
237                                 __u8 byte2, __u8 byte3);
238 static void edge_tty_recv(struct device *dev, struct tty_struct *tty,
239                                 unsigned char *data, int length);
240 static void handle_new_msr(struct edgeport_port *edge_port, __u8 newMsr);
241 static void handle_new_lsr(struct edgeport_port *edge_port, __u8 lsrData,
242                                 __u8 lsr, __u8 data);
243 static int  send_iosp_ext_cmd(struct edgeport_port *edge_port, __u8 command,
244                                 __u8 param);
245 static int  calc_baud_rate_divisor(int baud_rate, int *divisor);
246 static int  send_cmd_write_baud_rate(struct edgeport_port *edge_port,
247                                 int baudRate);
248 static void change_port_settings(struct tty_struct *tty,
249                                 struct edgeport_port *edge_port,
250                                 struct ktermios *old_termios);
251 static int  send_cmd_write_uart_register(struct edgeport_port *edge_port,
252                                 __u8 regNum, __u8 regValue);
253 static int  write_cmd_usb(struct edgeport_port *edge_port,
254                                 unsigned char *buffer, int writeLength);
255 static void send_more_port_data(struct edgeport_serial *edge_serial,
256                                 struct edgeport_port *edge_port);
257
258 static int sram_write(struct usb_serial *serial, __u16 extAddr, __u16 addr,
259                                         __u16 length, const __u8 *data);
260 static int rom_read(struct usb_serial *serial, __u16 extAddr, __u16 addr,
261                                                 __u16 length, __u8 *data);
262 static int rom_write(struct usb_serial *serial, __u16 extAddr, __u16 addr,
263                                         __u16 length, const __u8 *data);
264 static void get_manufacturing_desc(struct edgeport_serial *edge_serial);
265 static void get_boot_desc(struct edgeport_serial *edge_serial);
266 static void load_application_firmware(struct edgeport_serial *edge_serial);
267
268 static void unicode_to_ascii(char *string, int buflen,
269                                 __le16 *unicode, int unicode_size);
270
271
272 /* ************************************************************************ */
273 /* ************************************************************************ */
274 /* ************************************************************************ */
275 /* ************************************************************************ */
276
277 /************************************************************************
278  *                                                                      *
279  * update_edgeport_E2PROM()     Compare current versions of             *
280  *                              Boot ROM and Manufacture                *
281  *                              Descriptors with versions               *
282  *                              embedded in this driver                 *
283  *                                                                      *
284  ************************************************************************/
285 static void update_edgeport_E2PROM(struct edgeport_serial *edge_serial)
286 {
287         __u32 BootCurVer;
288         __u32 BootNewVer;
289         __u8 BootMajorVersion;
290         __u8 BootMinorVersion;
291         __u16 BootBuildNumber;
292         __u32 Bootaddr;
293         const struct ihex_binrec *rec;
294         const struct firmware *fw;
295         const char *fw_name;
296         int response;
297
298         switch (edge_serial->product_info.iDownloadFile) {
299         case EDGE_DOWNLOAD_FILE_I930:
300                 fw_name = "edgeport/boot.fw";
301                 break;
302         case EDGE_DOWNLOAD_FILE_80251:
303                 fw_name = "edgeport/boot2.fw";
304                 break;
305         default:
306                 return;
307         }
308
309         response = request_ihex_firmware(&fw, fw_name,
310                                          &edge_serial->serial->dev->dev);
311         if (response) {
312                 printk(KERN_ERR "Failed to load image \"%s\" err %d\n",
313                        fw_name, response);
314                 return;
315         }
316
317         rec = (const struct ihex_binrec *)fw->data;
318         BootMajorVersion = rec->data[0];
319         BootMinorVersion = rec->data[1];
320         BootBuildNumber = (rec->data[2] << 8) | rec->data[3];
321
322         /* Check Boot Image Version */
323         BootCurVer = (edge_serial->boot_descriptor.MajorVersion << 24) +
324                      (edge_serial->boot_descriptor.MinorVersion << 16) +
325                       le16_to_cpu(edge_serial->boot_descriptor.BuildNumber);
326
327         BootNewVer = (BootMajorVersion << 24) +
328                      (BootMinorVersion << 16) +
329                       BootBuildNumber;
330
331         dbg("Current Boot Image version %d.%d.%d",
332             edge_serial->boot_descriptor.MajorVersion,
333             edge_serial->boot_descriptor.MinorVersion,
334             le16_to_cpu(edge_serial->boot_descriptor.BuildNumber));
335
336
337         if (BootNewVer > BootCurVer) {
338                 dbg("**Update Boot Image from %d.%d.%d to %d.%d.%d",
339                     edge_serial->boot_descriptor.MajorVersion,
340                     edge_serial->boot_descriptor.MinorVersion,
341                     le16_to_cpu(edge_serial->boot_descriptor.BuildNumber),
342                     BootMajorVersion, BootMinorVersion, BootBuildNumber);
343
344                 dbg("Downloading new Boot Image");
345
346                 for (rec = ihex_next_binrec(rec); rec;
347                      rec = ihex_next_binrec(rec)) {
348                         Bootaddr = be32_to_cpu(rec->addr);
349                         response = rom_write(edge_serial->serial,
350                                              Bootaddr >> 16,
351                                              Bootaddr & 0xFFFF,
352                                              be16_to_cpu(rec->len),
353                                              &rec->data[0]);
354                         if (response < 0) {
355                                 dev_err(&edge_serial->serial->dev->dev,
356                                         "rom_write failed (%x, %x, %d)\n",
357                                         Bootaddr >> 16, Bootaddr & 0xFFFF,
358                                         be16_to_cpu(rec->len));
359                                 break;
360                         }
361                 }
362         } else {
363                 dbg("Boot Image -- already up to date");
364         }
365         release_firmware(fw);
366 }
367
368 #if 0
369 /************************************************************************
370  *
371  *  Get string descriptor from device
372  *
373  ************************************************************************/
374 static int get_string_desc(struct usb_device *dev, int Id,
375                                 struct usb_string_descriptor **pRetDesc)
376 {
377         struct usb_string_descriptor StringDesc;
378         struct usb_string_descriptor *pStringDesc;
379
380         dbg("%s - USB String ID = %d", __func__, Id);
381
382         if (!usb_get_descriptor(dev, USB_DT_STRING, Id, &StringDesc,
383                                                 sizeof(StringDesc)))
384                 return 0;
385
386         pStringDesc = kmalloc(StringDesc.bLength, GFP_KERNEL);
387         if (!pStringDesc)
388                 return -1;
389
390         if (!usb_get_descriptor(dev, USB_DT_STRING, Id, pStringDesc,
391                                                         StringDesc.bLength)) {
392                 kfree(pStringDesc);
393                 return -1;
394         }
395
396         *pRetDesc = pStringDesc;
397         return 0;
398 }
399 #endif
400
401 static void dump_product_info(struct edgeport_product_info *product_info)
402 {
403         /* Dump Product Info structure */
404         dbg("**Product Information:");
405         dbg("  ProductId             %x", product_info->ProductId);
406         dbg("  NumPorts              %d", product_info->NumPorts);
407         dbg("  ProdInfoVer           %d", product_info->ProdInfoVer);
408         dbg("  IsServer              %d", product_info->IsServer);
409         dbg("  IsRS232               %d", product_info->IsRS232);
410         dbg("  IsRS422               %d", product_info->IsRS422);
411         dbg("  IsRS485               %d", product_info->IsRS485);
412         dbg("  RomSize               %d", product_info->RomSize);
413         dbg("  RamSize               %d", product_info->RamSize);
414         dbg("  CpuRev                %x", product_info->CpuRev);
415         dbg("  BoardRev              %x", product_info->BoardRev);
416         dbg("  BootMajorVersion      %d.%d.%d", product_info->BootMajorVersion,
417             product_info->BootMinorVersion,
418             le16_to_cpu(product_info->BootBuildNumber));
419         dbg("  FirmwareMajorVersion  %d.%d.%d",
420                         product_info->FirmwareMajorVersion,
421                         product_info->FirmwareMinorVersion,
422                         le16_to_cpu(product_info->FirmwareBuildNumber));
423         dbg("  ManufactureDescDate   %d/%d/%d",
424                         product_info->ManufactureDescDate[0],
425                         product_info->ManufactureDescDate[1],
426                         product_info->ManufactureDescDate[2]+1900);
427         dbg("  iDownloadFile         0x%x", product_info->iDownloadFile);
428         dbg("  EpicVer               %d", product_info->EpicVer);
429 }
430
431 static void get_product_info(struct edgeport_serial *edge_serial)
432 {
433         struct edgeport_product_info *product_info = &edge_serial->product_info;
434
435         memset(product_info, 0, sizeof(struct edgeport_product_info));
436
437         product_info->ProductId = (__u16)(le16_to_cpu(edge_serial->serial->dev->descriptor.idProduct) & ~ION_DEVICE_ID_80251_NETCHIP);
438         product_info->NumPorts = edge_serial->manuf_descriptor.NumPorts;
439         product_info->ProdInfoVer = 0;
440
441         product_info->RomSize = edge_serial->manuf_descriptor.RomSize;
442         product_info->RamSize = edge_serial->manuf_descriptor.RamSize;
443         product_info->CpuRev = edge_serial->manuf_descriptor.CpuRev;
444         product_info->BoardRev = edge_serial->manuf_descriptor.BoardRev;
445
446         product_info->BootMajorVersion =
447                                 edge_serial->boot_descriptor.MajorVersion;
448         product_info->BootMinorVersion =
449                                 edge_serial->boot_descriptor.MinorVersion;
450         product_info->BootBuildNumber =
451                                 edge_serial->boot_descriptor.BuildNumber;
452
453         memcpy(product_info->ManufactureDescDate,
454                         edge_serial->manuf_descriptor.DescDate,
455                         sizeof(edge_serial->manuf_descriptor.DescDate));
456
457         /* check if this is 2nd generation hardware */
458         if (le16_to_cpu(edge_serial->serial->dev->descriptor.idProduct)
459                                             & ION_DEVICE_ID_80251_NETCHIP)
460                 product_info->iDownloadFile = EDGE_DOWNLOAD_FILE_80251;
461         else
462                 product_info->iDownloadFile = EDGE_DOWNLOAD_FILE_I930;
463  
464         /* Determine Product type and set appropriate flags */
465         switch (DEVICE_ID_FROM_USB_PRODUCT_ID(product_info->ProductId)) {
466         case ION_DEVICE_ID_EDGEPORT_COMPATIBLE:
467         case ION_DEVICE_ID_EDGEPORT_4T:
468         case ION_DEVICE_ID_EDGEPORT_4:
469         case ION_DEVICE_ID_EDGEPORT_2:
470         case ION_DEVICE_ID_EDGEPORT_8_DUAL_CPU:
471         case ION_DEVICE_ID_EDGEPORT_8:
472         case ION_DEVICE_ID_EDGEPORT_421:
473         case ION_DEVICE_ID_EDGEPORT_21:
474         case ION_DEVICE_ID_EDGEPORT_2_DIN:
475         case ION_DEVICE_ID_EDGEPORT_4_DIN:
476         case ION_DEVICE_ID_EDGEPORT_16_DUAL_CPU:
477                 product_info->IsRS232 = 1;
478                 break;
479
480         case ION_DEVICE_ID_EDGEPORT_2I: /* Edgeport/2 RS422/RS485 */
481                 product_info->IsRS422 = 1;
482                 product_info->IsRS485 = 1;
483                 break;
484
485         case ION_DEVICE_ID_EDGEPORT_8I: /* Edgeport/4 RS422 */
486         case ION_DEVICE_ID_EDGEPORT_4I: /* Edgeport/4 RS422 */
487                 product_info->IsRS422 = 1;
488                 break;
489         }
490
491         dump_product_info(product_info);
492 }
493
494 static int get_epic_descriptor(struct edgeport_serial *ep)
495 {
496         int result;
497         struct usb_serial *serial = ep->serial;
498         struct edgeport_product_info *product_info = &ep->product_info;
499         struct edge_compatibility_descriptor *epic = &ep->epic_descriptor;
500         struct edge_compatibility_bits *bits;
501
502         ep->is_epic = 0;
503         result = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
504                                  USB_REQUEST_ION_GET_EPIC_DESC,
505                                  0xC0, 0x00, 0x00,
506                                  &ep->epic_descriptor,
507                                  sizeof(struct edge_compatibility_descriptor),
508                                  300);
509
510         dbg("%s result = %d", __func__, result);
511
512         if (result > 0) {
513                 ep->is_epic = 1;
514                 memset(product_info, 0, sizeof(struct edgeport_product_info));
515
516                 product_info->NumPorts = epic->NumPorts;
517                 product_info->ProdInfoVer = 0;
518                 product_info->FirmwareMajorVersion = epic->MajorVersion;
519                 product_info->FirmwareMinorVersion = epic->MinorVersion;
520                 product_info->FirmwareBuildNumber = epic->BuildNumber;
521                 product_info->iDownloadFile = epic->iDownloadFile;
522                 product_info->EpicVer = epic->EpicVer;
523                 product_info->Epic = epic->Supports;
524                 product_info->ProductId = ION_DEVICE_ID_EDGEPORT_COMPATIBLE;
525                 dump_product_info(product_info);
526
527                 bits = &ep->epic_descriptor.Supports;
528                 dbg("**EPIC descriptor:");
529                 dbg("  VendEnableSuspend: %s", bits->VendEnableSuspend  ? "TRUE": "FALSE");
530                 dbg("  IOSPOpen         : %s", bits->IOSPOpen           ? "TRUE": "FALSE");
531                 dbg("  IOSPClose        : %s", bits->IOSPClose          ? "TRUE": "FALSE");
532                 dbg("  IOSPChase        : %s", bits->IOSPChase          ? "TRUE": "FALSE");
533                 dbg("  IOSPSetRxFlow    : %s", bits->IOSPSetRxFlow      ? "TRUE": "FALSE");
534                 dbg("  IOSPSetTxFlow    : %s", bits->IOSPSetTxFlow      ? "TRUE": "FALSE");
535                 dbg("  IOSPSetXChar     : %s", bits->IOSPSetXChar       ? "TRUE": "FALSE");
536                 dbg("  IOSPRxCheck      : %s", bits->IOSPRxCheck        ? "TRUE": "FALSE");
537                 dbg("  IOSPSetClrBreak  : %s", bits->IOSPSetClrBreak    ? "TRUE": "FALSE");
538                 dbg("  IOSPWriteMCR     : %s", bits->IOSPWriteMCR       ? "TRUE": "FALSE");
539                 dbg("  IOSPWriteLCR     : %s", bits->IOSPWriteLCR       ? "TRUE": "FALSE");
540                 dbg("  IOSPSetBaudRate  : %s", bits->IOSPSetBaudRate    ? "TRUE": "FALSE");
541                 dbg("  TrueEdgeport     : %s", bits->TrueEdgeport       ? "TRUE": "FALSE");
542         }
543
544         return result;
545 }
546
547
548 /************************************************************************/
549 /************************************************************************/
550 /*            U S B  C A L L B A C K   F U N C T I O N S                */
551 /*            U S B  C A L L B A C K   F U N C T I O N S                */
552 /************************************************************************/
553 /************************************************************************/
554
555 /*****************************************************************************
556  * edge_interrupt_callback
557  *      this is the callback function for when we have received data on the
558  *      interrupt endpoint.
559  *****************************************************************************/
560 static void edge_interrupt_callback(struct urb *urb)
561 {
562         struct edgeport_serial  *edge_serial = urb->context;
563         struct edgeport_port *edge_port;
564         struct usb_serial_port *port;
565         struct tty_struct *tty;
566         unsigned char *data = urb->transfer_buffer;
567         int length = urb->actual_length;
568         int bytes_avail;
569         int position;
570         int txCredits;
571         int portNumber;
572         int result;
573         int status = urb->status;
574
575         dbg("%s", __func__);
576
577         switch (status) {
578         case 0:
579                 /* success */
580                 break;
581         case -ECONNRESET:
582         case -ENOENT:
583         case -ESHUTDOWN:
584                 /* this urb is terminated, clean up */
585                 dbg("%s - urb shutting down with status: %d",
586                                                 __func__, status);
587                 return;
588         default:
589                 dbg("%s - nonzero urb status received: %d", __func__, status);
590                 goto exit;
591         }
592
593         /* process this interrupt-read even if there are no ports open */
594         if (length) {
595                 usb_serial_debug_data(debug, &edge_serial->serial->dev->dev,
596                                                 __func__, length, data);
597
598                 if (length > 1) {
599                         bytes_avail = data[0] | (data[1] << 8);
600                         if (bytes_avail) {
601                                 spin_lock(&edge_serial->es_lock);
602                                 edge_serial->rxBytesAvail += bytes_avail;
603                                 dbg("%s - bytes_avail=%d, rxBytesAvail=%d, read_in_progress=%d", __func__, bytes_avail, edge_serial->rxBytesAvail, edge_serial->read_in_progress);
604
605                                 if (edge_serial->rxBytesAvail > 0 &&
606                                     !edge_serial->read_in_progress) {
607                                         dbg("%s - posting a read", __func__);
608                                         edge_serial->read_in_progress = true;
609
610                                         /* we have pending bytes on the
611                                            bulk in pipe, send a request */
612                                         edge_serial->read_urb->dev = edge_serial->serial->dev;
613                                         result = usb_submit_urb(edge_serial->read_urb, GFP_ATOMIC);
614                                         if (result) {
615                                                 dev_err(&edge_serial->serial->dev->dev, "%s - usb_submit_urb(read bulk) failed with result = %d\n", __func__, result);
616                                                 edge_serial->read_in_progress = false;
617                                         }
618                                 }
619                                 spin_unlock(&edge_serial->es_lock);
620                         }
621                 }
622                 /* grab the txcredits for the ports if available */
623                 position = 2;
624                 portNumber = 0;
625                 while ((position < length) &&
626                                 (portNumber < edge_serial->serial->num_ports)) {
627                         txCredits = data[position] | (data[position+1] << 8);
628                         if (txCredits) {
629                                 port = edge_serial->serial->port[portNumber];
630                                 edge_port = usb_get_serial_port_data(port);
631                                 if (edge_port->open) {
632                                         spin_lock(&edge_port->ep_lock);
633                                         edge_port->txCredits += txCredits;
634                                         spin_unlock(&edge_port->ep_lock);
635                                         dbg("%s - txcredits for port%d = %d",
636                                                         __func__, portNumber,
637                                                         edge_port->txCredits);
638
639                                         /* tell the tty driver that something
640                                            has changed */
641                                         tty = tty_port_tty_get(
642                                                 &edge_port->port->port);
643                                         if (tty) {
644                                                 tty_wakeup(tty);
645                                                 tty_kref_put(tty);
646                                         }
647                                         /* Since we have more credit, check
648                                            if more data can be sent */
649                                         send_more_port_data(edge_serial,
650                                                                 edge_port);
651                                 }
652                         }
653                         position += 2;
654                         ++portNumber;
655                 }
656         }
657
658 exit:
659         result = usb_submit_urb(urb, GFP_ATOMIC);
660         if (result)
661                 dev_err(&urb->dev->dev,
662                         "%s - Error %d submitting control urb\n",
663                                                 __func__, result);
664 }
665
666
667 /*****************************************************************************
668  * edge_bulk_in_callback
669  *      this is the callback function for when we have received data on the
670  *      bulk in endpoint.
671  *****************************************************************************/
672 static void edge_bulk_in_callback(struct urb *urb)
673 {
674         struct edgeport_serial  *edge_serial = urb->context;
675         unsigned char           *data = urb->transfer_buffer;
676         int                     retval;
677         __u16                   raw_data_length;
678         int status = urb->status;
679
680         dbg("%s", __func__);
681
682         if (status) {
683                 dbg("%s - nonzero read bulk status received: %d",
684                     __func__, status);
685                 edge_serial->read_in_progress = false;
686                 return;
687         }
688
689         if (urb->actual_length == 0) {
690                 dbg("%s - read bulk callback with no data", __func__);
691                 edge_serial->read_in_progress = false;
692                 return;
693         }
694
695         raw_data_length = urb->actual_length;
696
697         usb_serial_debug_data(debug, &edge_serial->serial->dev->dev,
698                                         __func__, raw_data_length, data);
699
700         spin_lock(&edge_serial->es_lock);
701
702         /* decrement our rxBytes available by the number that we just got */
703         edge_serial->rxBytesAvail -= raw_data_length;
704
705         dbg("%s - Received = %d, rxBytesAvail %d", __func__,
706                                 raw_data_length, edge_serial->rxBytesAvail);
707
708         process_rcvd_data(edge_serial, data, urb->actual_length);
709
710         /* check to see if there's any more data for us to read */
711         if (edge_serial->rxBytesAvail > 0) {
712                 dbg("%s - posting a read", __func__);
713                 edge_serial->read_urb->dev = edge_serial->serial->dev;
714                 retval = usb_submit_urb(edge_serial->read_urb, GFP_ATOMIC);
715                 if (retval) {
716                         dev_err(&urb->dev->dev,
717                                 "%s - usb_submit_urb(read bulk) failed, "
718                                 "retval = %d\n", __func__, retval);
719                         edge_serial->read_in_progress = false;
720                 }
721         } else {
722                 edge_serial->read_in_progress = false;
723         }
724
725         spin_unlock(&edge_serial->es_lock);
726 }
727
728
729 /*****************************************************************************
730  * edge_bulk_out_data_callback
731  *      this is the callback function for when we have finished sending
732  *      serial data on the bulk out endpoint.
733  *****************************************************************************/
734 static void edge_bulk_out_data_callback(struct urb *urb)
735 {
736         struct edgeport_port *edge_port = urb->context;
737         struct tty_struct *tty;
738         int status = urb->status;
739
740         dbg("%s", __func__);
741
742         if (status) {
743                 dbg("%s - nonzero write bulk status received: %d",
744                     __func__, status);
745         }
746
747         tty = tty_port_tty_get(&edge_port->port->port);
748
749         if (tty && edge_port->open) {
750                 /* let the tty driver wakeup if it has a special
751                    write_wakeup function */
752                 tty_wakeup(tty);
753         }
754         tty_kref_put(tty);
755
756         /* Release the Write URB */
757         edge_port->write_in_progress = false;
758
759         /* Check if more data needs to be sent */
760         send_more_port_data((struct edgeport_serial *)
761                 (usb_get_serial_data(edge_port->port->serial)), edge_port);
762 }
763
764
765 /*****************************************************************************
766  * BulkOutCmdCallback
767  *      this is the callback function for when we have finished sending a
768  *      command on the bulk out endpoint.
769  *****************************************************************************/
770 static void edge_bulk_out_cmd_callback(struct urb *urb)
771 {
772         struct edgeport_port *edge_port = urb->context;
773         struct tty_struct *tty;
774         int status = urb->status;
775
776         dbg("%s", __func__);
777
778         atomic_dec(&CmdUrbs);
779         dbg("%s - FREE URB %p (outstanding %d)", __func__,
780                                         urb, atomic_read(&CmdUrbs));
781
782
783         /* clean up the transfer buffer */
784         kfree(urb->transfer_buffer);
785
786         /* Free the command urb */
787         usb_free_urb(urb);
788
789         if (status) {
790                 dbg("%s - nonzero write bulk status received: %d",
791                                                         __func__, status);
792                 return;
793         }
794
795         /* Get pointer to tty */
796         tty = tty_port_tty_get(&edge_port->port->port);
797
798         /* tell the tty driver that something has changed */
799         if (tty && edge_port->open)
800                 tty_wakeup(tty);
801         tty_kref_put(tty);
802
803         /* we have completed the command */
804         edge_port->commandPending = false;
805         wake_up(&edge_port->wait_command);
806 }
807
808
809 /*****************************************************************************
810  * Driver tty interface functions
811  *****************************************************************************/
812
813 /*****************************************************************************
814  * SerialOpen
815  *      this function is called by the tty driver when a port is opened
816  *      If successful, we return 0
817  *      Otherwise we return a negative error number.
818  *****************************************************************************/
819 static int edge_open(struct tty_struct *tty, struct usb_serial_port *port)
820 {
821         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
822         struct usb_serial *serial;
823         struct edgeport_serial *edge_serial;
824         int response;
825
826         dbg("%s - port %d", __func__, port->number);
827
828         if (edge_port == NULL)
829                 return -ENODEV;
830
831         /* see if we've set up our endpoint info yet (can't set it up
832            in edge_startup as the structures were not set up at that time.) */
833         serial = port->serial;
834         edge_serial = usb_get_serial_data(serial);
835         if (edge_serial == NULL)
836                 return -ENODEV;
837         if (edge_serial->interrupt_in_buffer == NULL) {
838                 struct usb_serial_port *port0 = serial->port[0];
839
840                 /* not set up yet, so do it now */
841                 edge_serial->interrupt_in_buffer =
842                                         port0->interrupt_in_buffer;
843                 edge_serial->interrupt_in_endpoint =
844                                         port0->interrupt_in_endpointAddress;
845                 edge_serial->interrupt_read_urb = port0->interrupt_in_urb;
846                 edge_serial->bulk_in_buffer = port0->bulk_in_buffer;
847                 edge_serial->bulk_in_endpoint =
848                                         port0->bulk_in_endpointAddress;
849                 edge_serial->read_urb = port0->read_urb;
850                 edge_serial->bulk_out_endpoint =
851                                         port0->bulk_out_endpointAddress;
852
853                 /* set up our interrupt urb */
854                 usb_fill_int_urb(edge_serial->interrupt_read_urb,
855                       serial->dev,
856                       usb_rcvintpipe(serial->dev,
857                                 port0->interrupt_in_endpointAddress),
858                       port0->interrupt_in_buffer,
859                       edge_serial->interrupt_read_urb->transfer_buffer_length,
860                       edge_interrupt_callback, edge_serial,
861                       edge_serial->interrupt_read_urb->interval);
862
863                 /* set up our bulk in urb */
864                 usb_fill_bulk_urb(edge_serial->read_urb, serial->dev,
865                         usb_rcvbulkpipe(serial->dev,
866                                 port0->bulk_in_endpointAddress),
867                         port0->bulk_in_buffer,
868                         edge_serial->read_urb->transfer_buffer_length,
869                         edge_bulk_in_callback, edge_serial);
870                 edge_serial->read_in_progress = false;
871
872                 /* start interrupt read for this edgeport
873                  * this interrupt will continue as long
874                  * as the edgeport is connected */
875                 response = usb_submit_urb(edge_serial->interrupt_read_urb,
876                                                                 GFP_KERNEL);
877                 if (response) {
878                         dev_err(&port->dev,
879                                 "%s - Error %d submitting control urb\n",
880                                                         __func__, response);
881                 }
882         }
883
884         /* initialize our wait queues */
885         init_waitqueue_head(&edge_port->wait_open);
886         init_waitqueue_head(&edge_port->wait_chase);
887         init_waitqueue_head(&edge_port->wait_command);
888
889         /* initialize our icount structure */
890         memset(&(edge_port->icount), 0x00, sizeof(edge_port->icount));
891
892         /* initialize our port settings */
893         edge_port->txCredits = 0;       /* Can't send any data yet */
894         /* Must always set this bit to enable ints! */
895         edge_port->shadowMCR = MCR_MASTER_IE;
896         edge_port->chaseResponsePending = false;
897
898         /* send a open port command */
899         edge_port->openPending = true;
900         edge_port->open        = false;
901         response = send_iosp_ext_cmd(edge_port, IOSP_CMD_OPEN_PORT, 0);
902
903         if (response < 0) {
904                 dev_err(&port->dev, "%s - error sending open port command\n",
905                                                                 __func__);
906                 edge_port->openPending = false;
907                 return -ENODEV;
908         }
909
910         /* now wait for the port to be completely opened */
911         wait_event_timeout(edge_port->wait_open, !edge_port->openPending,
912                                                                 OPEN_TIMEOUT);
913
914         if (!edge_port->open) {
915                 /* open timed out */
916                 dbg("%s - open timedout", __func__);
917                 edge_port->openPending = false;
918                 return -ENODEV;
919         }
920
921         /* create the txfifo */
922         edge_port->txfifo.head  = 0;
923         edge_port->txfifo.tail  = 0;
924         edge_port->txfifo.count = 0;
925         edge_port->txfifo.size  = edge_port->maxTxCredits;
926         edge_port->txfifo.fifo  = kmalloc(edge_port->maxTxCredits, GFP_KERNEL);
927
928         if (!edge_port->txfifo.fifo) {
929                 dbg("%s - no memory", __func__);
930                 edge_close(port);
931                 return -ENOMEM;
932         }
933
934         /* Allocate a URB for the write */
935         edge_port->write_urb = usb_alloc_urb(0, GFP_KERNEL);
936         edge_port->write_in_progress = false;
937
938         if (!edge_port->write_urb) {
939                 dbg("%s - no memory", __func__);
940                 edge_close(port);
941                 return -ENOMEM;
942         }
943
944         dbg("%s(%d) - Initialize TX fifo to %d bytes",
945                         __func__, port->number, edge_port->maxTxCredits);
946
947         dbg("%s exited", __func__);
948
949         return 0;
950 }
951
952
953 /************************************************************************
954  *
955  * block_until_chase_response
956  *
957  *      This function will block the close until one of the following:
958  *              1. Response to our Chase comes from Edgeport
959  *              2. A timeout of 10 seconds without activity has expired
960  *                 (1K of Edgeport data @ 2400 baud ==> 4 sec to empty)
961  *
962  ************************************************************************/
963 static void block_until_chase_response(struct edgeport_port *edge_port)
964 {
965         DEFINE_WAIT(wait);
966         __u16 lastCredits;
967         int timeout = 1*HZ;
968         int loop = 10;
969
970         while (1) {
971                 /* Save Last credits */
972                 lastCredits = edge_port->txCredits;
973
974                 /* Did we get our Chase response */
975                 if (!edge_port->chaseResponsePending) {
976                         dbg("%s - Got Chase Response", __func__);
977
978                         /* did we get all of our credit back? */
979                         if (edge_port->txCredits == edge_port->maxTxCredits) {
980                                 dbg("%s - Got all credits", __func__);
981                                 return;
982                         }
983                 }
984
985                 /* Block the thread for a while */
986                 prepare_to_wait(&edge_port->wait_chase, &wait,
987                                                 TASK_UNINTERRUPTIBLE);
988                 schedule_timeout(timeout);
989                 finish_wait(&edge_port->wait_chase, &wait);
990
991                 if (lastCredits == edge_port->txCredits) {
992                         /* No activity.. count down. */
993                         loop--;
994                         if (loop == 0) {
995                                 edge_port->chaseResponsePending = false;
996                                 dbg("%s - Chase TIMEOUT", __func__);
997                                 return;
998                         }
999                 } else {
1000                         /* Reset timeout value back to 10 seconds */
1001                         dbg("%s - Last %d, Current %d", __func__,
1002                                         lastCredits, edge_port->txCredits);
1003                         loop = 10;
1004                 }
1005         }
1006 }
1007
1008
1009 /************************************************************************
1010  *
1011  * block_until_tx_empty
1012  *
1013  *      This function will block the close until one of the following:
1014  *              1. TX count are 0
1015  *              2. The edgeport has stopped
1016  *              3. A timeout of 3 seconds without activity has expired
1017  *
1018  ************************************************************************/
1019 static void block_until_tx_empty(struct edgeport_port *edge_port)
1020 {
1021         DEFINE_WAIT(wait);
1022         struct TxFifo *fifo = &edge_port->txfifo;
1023         __u32 lastCount;
1024         int timeout = HZ/10;
1025         int loop = 30;
1026
1027         while (1) {
1028                 /* Save Last count */
1029                 lastCount = fifo->count;
1030
1031                 /* Is the Edgeport Buffer empty? */
1032                 if (lastCount == 0) {
1033                         dbg("%s - TX Buffer Empty", __func__);
1034                         return;
1035                 }
1036
1037                 /* Block the thread for a while */
1038                 prepare_to_wait(&edge_port->wait_chase, &wait,
1039                                                 TASK_UNINTERRUPTIBLE);
1040                 schedule_timeout(timeout);
1041                 finish_wait(&edge_port->wait_chase, &wait);
1042
1043                 dbg("%s wait", __func__);
1044
1045                 if (lastCount == fifo->count) {
1046                         /* No activity.. count down. */
1047                         loop--;
1048                         if (loop == 0) {
1049                                 dbg("%s - TIMEOUT", __func__);
1050                                 return;
1051                         }
1052                 } else {
1053                         /* Reset timeout value back to seconds */
1054                         loop = 30;
1055                 }
1056         }
1057 }
1058
1059
1060 /*****************************************************************************
1061  * edge_close
1062  *      this function is called by the tty driver when a port is closed
1063  *****************************************************************************/
1064 static void edge_close(struct usb_serial_port *port)
1065 {
1066         struct edgeport_serial *edge_serial;
1067         struct edgeport_port *edge_port;
1068         int status;
1069
1070         dbg("%s - port %d", __func__, port->number);
1071
1072         edge_serial = usb_get_serial_data(port->serial);
1073         edge_port = usb_get_serial_port_data(port);
1074         if (edge_serial == NULL || edge_port == NULL)
1075                 return;
1076
1077         /* block until tx is empty */
1078         block_until_tx_empty(edge_port);
1079
1080         edge_port->closePending = true;
1081
1082         if ((!edge_serial->is_epic) ||
1083             ((edge_serial->is_epic) &&
1084              (edge_serial->epic_descriptor.Supports.IOSPChase))) {
1085                 /* flush and chase */
1086                 edge_port->chaseResponsePending = true;
1087
1088                 dbg("%s - Sending IOSP_CMD_CHASE_PORT", __func__);
1089                 status = send_iosp_ext_cmd(edge_port, IOSP_CMD_CHASE_PORT, 0);
1090                 if (status == 0)
1091                         /* block until chase finished */
1092                         block_until_chase_response(edge_port);
1093                 else
1094                         edge_port->chaseResponsePending = false;
1095         }
1096
1097         if ((!edge_serial->is_epic) ||
1098             ((edge_serial->is_epic) &&
1099              (edge_serial->epic_descriptor.Supports.IOSPClose))) {
1100                /* close the port */
1101                 dbg("%s - Sending IOSP_CMD_CLOSE_PORT", __func__);
1102                 send_iosp_ext_cmd(edge_port, IOSP_CMD_CLOSE_PORT, 0);
1103         }
1104
1105         /* port->close = true; */
1106         edge_port->closePending = false;
1107         edge_port->open = false;
1108         edge_port->openPending = false;
1109
1110         usb_kill_urb(edge_port->write_urb);
1111
1112         if (edge_port->write_urb) {
1113                 /* if this urb had a transfer buffer already
1114                                 (old transfer) free it */
1115                 kfree(edge_port->write_urb->transfer_buffer);
1116                 usb_free_urb(edge_port->write_urb);
1117                 edge_port->write_urb = NULL;
1118         }
1119         kfree(edge_port->txfifo.fifo);
1120         edge_port->txfifo.fifo = NULL;
1121
1122         dbg("%s exited", __func__);
1123 }
1124
1125 /*****************************************************************************
1126  * SerialWrite
1127  *      this function is called by the tty driver when data should be written
1128  *      to the port.
1129  *      If successful, we return the number of bytes written, otherwise we
1130  *      return a negative error number.
1131  *****************************************************************************/
1132 static int edge_write(struct tty_struct *tty, struct usb_serial_port *port,
1133                                         const unsigned char *data, int count)
1134 {
1135         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1136         struct TxFifo *fifo;
1137         int copySize;
1138         int bytesleft;
1139         int firsthalf;
1140         int secondhalf;
1141         unsigned long flags;
1142
1143         dbg("%s - port %d", __func__, port->number);
1144
1145         if (edge_port == NULL)
1146                 return -ENODEV;
1147
1148         /* get a pointer to the Tx fifo */
1149         fifo = &edge_port->txfifo;
1150
1151         spin_lock_irqsave(&edge_port->ep_lock, flags);
1152
1153         /* calculate number of bytes to put in fifo */
1154         copySize = min((unsigned int)count,
1155                                 (edge_port->txCredits - fifo->count));
1156
1157         dbg("%s(%d) of %d byte(s) Fifo room  %d -- will copy %d bytes",
1158                         __func__, port->number, count,
1159                         edge_port->txCredits - fifo->count, copySize);
1160
1161         /* catch writes of 0 bytes which the tty driver likes to give us,
1162            and when txCredits is empty */
1163         if (copySize == 0) {
1164                 dbg("%s - copySize = Zero", __func__);
1165                 goto finish_write;
1166         }
1167
1168         /* queue the data
1169          * since we can never overflow the buffer we do not have to check for a
1170          * full condition
1171          *
1172          * the copy is done is two parts -- first fill to the end of the buffer
1173          * then copy the reset from the start of the buffer
1174          */
1175         bytesleft = fifo->size - fifo->head;
1176         firsthalf = min(bytesleft, copySize);
1177         dbg("%s - copy %d bytes of %d into fifo ", __func__,
1178                                         firsthalf, bytesleft);
1179
1180         /* now copy our data */
1181         memcpy(&fifo->fifo[fifo->head], data, firsthalf);
1182         usb_serial_debug_data(debug, &port->dev, __func__,
1183                                         firsthalf, &fifo->fifo[fifo->head]);
1184
1185         /* update the index and size */
1186         fifo->head  += firsthalf;
1187         fifo->count += firsthalf;
1188
1189         /* wrap the index */
1190         if (fifo->head == fifo->size)
1191                 fifo->head = 0;
1192
1193         secondhalf = copySize-firsthalf;
1194
1195         if (secondhalf) {
1196                 dbg("%s - copy rest of data %d", __func__, secondhalf);
1197                 memcpy(&fifo->fifo[fifo->head], &data[firsthalf], secondhalf);
1198                 usb_serial_debug_data(debug, &port->dev, __func__,
1199                                         secondhalf, &fifo->fifo[fifo->head]);
1200                 /* update the index and size */
1201                 fifo->count += secondhalf;
1202                 fifo->head  += secondhalf;
1203                 /* No need to check for wrap since we can not get to end of
1204                  * the fifo in this part
1205                  */
1206         }
1207
1208 finish_write:
1209         spin_unlock_irqrestore(&edge_port->ep_lock, flags);
1210
1211         send_more_port_data((struct edgeport_serial *)
1212                         usb_get_serial_data(port->serial), edge_port);
1213
1214         dbg("%s wrote %d byte(s) TxCredits %d, Fifo %d", __func__,
1215                                 copySize, edge_port->txCredits, fifo->count);
1216
1217         return copySize;
1218 }
1219
1220
1221 /************************************************************************
1222  *
1223  * send_more_port_data()
1224  *
1225  *      This routine attempts to write additional UART transmit data
1226  *      to a port over the USB bulk pipe. It is called (1) when new
1227  *      data has been written to a port's TxBuffer from higher layers
1228  *      (2) when the peripheral sends us additional TxCredits indicating
1229  *      that it can accept more Tx data for a given port; and (3) when
1230  *      a bulk write completes successfully and we want to see if we
1231  *      can transmit more.
1232  *
1233  ************************************************************************/
1234 static void send_more_port_data(struct edgeport_serial *edge_serial,
1235                                         struct edgeport_port *edge_port)
1236 {
1237         struct TxFifo   *fifo = &edge_port->txfifo;
1238         struct urb      *urb;
1239         unsigned char   *buffer;
1240         int             status;
1241         int             count;
1242         int             bytesleft;
1243         int             firsthalf;
1244         int             secondhalf;
1245         unsigned long   flags;
1246
1247         dbg("%s(%d)", __func__, edge_port->port->number);
1248
1249         spin_lock_irqsave(&edge_port->ep_lock, flags);
1250
1251         if (edge_port->write_in_progress ||
1252             !edge_port->open             ||
1253             (fifo->count == 0)) {
1254                 dbg("%s(%d) EXIT - fifo %d, PendingWrite = %d",
1255                                 __func__, edge_port->port->number,
1256                                 fifo->count, edge_port->write_in_progress);
1257                 goto exit_send;
1258         }
1259
1260         /* since the amount of data in the fifo will always fit into the
1261          * edgeport buffer we do not need to check the write length
1262          *
1263          * Do we have enough credits for this port to make it worthwhile
1264          * to bother queueing a write. If it's too small, say a few bytes,
1265          * it's better to wait for more credits so we can do a larger write.
1266          */
1267         if (edge_port->txCredits < EDGE_FW_GET_TX_CREDITS_SEND_THRESHOLD(edge_port->maxTxCredits, EDGE_FW_BULK_MAX_PACKET_SIZE)) {
1268                 dbg("%s(%d) Not enough credit - fifo %d TxCredit %d",
1269                         __func__, edge_port->port->number, fifo->count,
1270                         edge_port->txCredits);
1271                 goto exit_send;
1272         }
1273
1274         /* lock this write */
1275         edge_port->write_in_progress = true;
1276
1277         /* get a pointer to the write_urb */
1278         urb = edge_port->write_urb;
1279
1280         /* make sure transfer buffer is freed */
1281         kfree(urb->transfer_buffer);
1282         urb->transfer_buffer = NULL;
1283
1284         /* build the data header for the buffer and port that we are about
1285            to send out */
1286         count = fifo->count;
1287         buffer = kmalloc(count+2, GFP_ATOMIC);
1288         if (buffer == NULL) {
1289                 dev_err(&edge_port->port->dev,
1290                                 "%s - no more kernel memory...\n", __func__);
1291                 edge_port->write_in_progress = false;
1292                 goto exit_send;
1293         }
1294         buffer[0] = IOSP_BUILD_DATA_HDR1(edge_port->port->number
1295                                 - edge_port->port->serial->minor, count);
1296         buffer[1] = IOSP_BUILD_DATA_HDR2(edge_port->port->number
1297                                 - edge_port->port->serial->minor, count);
1298
1299         /* now copy our data */
1300         bytesleft =  fifo->size - fifo->tail;
1301         firsthalf = min(bytesleft, count);
1302         memcpy(&buffer[2], &fifo->fifo[fifo->tail], firsthalf);
1303         fifo->tail  += firsthalf;
1304         fifo->count -= firsthalf;
1305         if (fifo->tail == fifo->size)
1306                 fifo->tail = 0;
1307
1308         secondhalf = count-firsthalf;
1309         if (secondhalf) {
1310                 memcpy(&buffer[2+firsthalf], &fifo->fifo[fifo->tail],
1311                                                                 secondhalf);
1312                 fifo->tail  += secondhalf;
1313                 fifo->count -= secondhalf;
1314         }
1315
1316         if (count)
1317                 usb_serial_debug_data(debug, &edge_port->port->dev,
1318                                                 __func__, count, &buffer[2]);
1319
1320         /* fill up the urb with all of our data and submit it */
1321         usb_fill_bulk_urb(urb, edge_serial->serial->dev,
1322                         usb_sndbulkpipe(edge_serial->serial->dev,
1323                                         edge_serial->bulk_out_endpoint),
1324                         buffer, count+2,
1325                         edge_bulk_out_data_callback, edge_port);
1326
1327         /* decrement the number of credits we have by the number we just sent */
1328         edge_port->txCredits -= count;
1329         edge_port->icount.tx += count;
1330
1331         urb->dev = edge_serial->serial->dev;
1332         status = usb_submit_urb(urb, GFP_ATOMIC);
1333         if (status) {
1334                 /* something went wrong */
1335                 dev_err(&edge_port->port->dev,
1336                         "%s - usb_submit_urb(write bulk) failed, status = %d, data lost\n",
1337                                 __func__, status);
1338                 edge_port->write_in_progress = false;
1339
1340                 /* revert the credits as something bad happened. */
1341                 edge_port->txCredits += count;
1342                 edge_port->icount.tx -= count;
1343         }
1344         dbg("%s wrote %d byte(s) TxCredit %d, Fifo %d",
1345                         __func__, count, edge_port->txCredits, fifo->count);
1346
1347 exit_send:
1348         spin_unlock_irqrestore(&edge_port->ep_lock, flags);
1349 }
1350
1351
1352 /*****************************************************************************
1353  * edge_write_room
1354  *      this function is called by the tty driver when it wants to know how
1355  *      many bytes of data we can accept for a specific port. If successful,
1356  *      we return the amount of room that we have for this port (the txCredits)
1357  *      otherwise we return a negative error number.
1358  *****************************************************************************/
1359 static int edge_write_room(struct tty_struct *tty)
1360 {
1361         struct usb_serial_port *port = tty->driver_data;
1362         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1363         int room;
1364         unsigned long flags;
1365
1366         dbg("%s", __func__);
1367
1368         if (edge_port == NULL)
1369                 return 0;
1370         if (edge_port->closePending)
1371                 return 0;
1372
1373         dbg("%s - port %d", __func__, port->number);
1374
1375         if (!edge_port->open) {
1376                 dbg("%s - port not opened", __func__);
1377                 return 0;
1378         }
1379
1380         /* total of both buffers is still txCredit */
1381         spin_lock_irqsave(&edge_port->ep_lock, flags);
1382         room = edge_port->txCredits - edge_port->txfifo.count;
1383         spin_unlock_irqrestore(&edge_port->ep_lock, flags);
1384
1385         dbg("%s - returns %d", __func__, room);
1386         return room;
1387 }
1388
1389
1390 /*****************************************************************************
1391  * edge_chars_in_buffer
1392  *      this function is called by the tty driver when it wants to know how
1393  *      many bytes of data we currently have outstanding in the port (data that
1394  *      has been written, but hasn't made it out the port yet)
1395  *      If successful, we return the number of bytes left to be written in the
1396  *      system,
1397  *      Otherwise we return a negative error number.
1398  *****************************************************************************/
1399 static int edge_chars_in_buffer(struct tty_struct *tty)
1400 {
1401         struct usb_serial_port *port = tty->driver_data;
1402         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1403         int num_chars;
1404         unsigned long flags;
1405
1406         dbg("%s", __func__);
1407
1408         if (edge_port == NULL)
1409                 return 0;
1410         if (edge_port->closePending)
1411                 return 0;
1412
1413         if (!edge_port->open) {
1414                 dbg("%s - port not opened", __func__);
1415                 return 0;
1416         }
1417
1418         spin_lock_irqsave(&edge_port->ep_lock, flags);
1419         num_chars = edge_port->maxTxCredits - edge_port->txCredits +
1420                                                 edge_port->txfifo.count;
1421         spin_unlock_irqrestore(&edge_port->ep_lock, flags);
1422         if (num_chars) {
1423                 dbg("%s(port %d) - returns %d", __func__,
1424                                                 port->number, num_chars);
1425         }
1426
1427         return num_chars;
1428 }
1429
1430
1431 /*****************************************************************************
1432  * SerialThrottle
1433  *      this function is called by the tty driver when it wants to stop the data
1434  *      being read from the port.
1435  *****************************************************************************/
1436 static void edge_throttle(struct tty_struct *tty)
1437 {
1438         struct usb_serial_port *port = tty->driver_data;
1439         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1440         int status;
1441
1442         dbg("%s - port %d", __func__, port->number);
1443
1444         if (edge_port == NULL)
1445                 return;
1446
1447         if (!edge_port->open) {
1448                 dbg("%s - port not opened", __func__);
1449                 return;
1450         }
1451
1452         /* if we are implementing XON/XOFF, send the stop character */
1453         if (I_IXOFF(tty)) {
1454                 unsigned char stop_char = STOP_CHAR(tty);
1455                 status = edge_write(tty, port, &stop_char, 1);
1456                 if (status <= 0)
1457                         return;
1458         }
1459
1460         /* if we are implementing RTS/CTS, toggle that line */
1461         if (tty->termios->c_cflag & CRTSCTS) {
1462                 edge_port->shadowMCR &= ~MCR_RTS;
1463                 status = send_cmd_write_uart_register(edge_port, MCR,
1464                                                         edge_port->shadowMCR);
1465                 if (status != 0)
1466                         return;
1467         }
1468 }
1469
1470
1471 /*****************************************************************************
1472  * edge_unthrottle
1473  *      this function is called by the tty driver when it wants to resume the
1474  *      data being read from the port (called after SerialThrottle is called)
1475  *****************************************************************************/
1476 static void edge_unthrottle(struct tty_struct *tty)
1477 {
1478         struct usb_serial_port *port = tty->driver_data;
1479         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1480         int status;
1481
1482         dbg("%s - port %d", __func__, port->number);
1483
1484         if (edge_port == NULL)
1485                 return;
1486
1487         if (!edge_port->open) {
1488                 dbg("%s - port not opened", __func__);
1489                 return;
1490         }
1491
1492         /* if we are implementing XON/XOFF, send the start character */
1493         if (I_IXOFF(tty)) {
1494                 unsigned char start_char = START_CHAR(tty);
1495                 status = edge_write(tty, port, &start_char, 1);
1496                 if (status <= 0)
1497                         return;
1498         }
1499         /* if we are implementing RTS/CTS, toggle that line */
1500         if (tty->termios->c_cflag & CRTSCTS) {
1501                 edge_port->shadowMCR |= MCR_RTS;
1502                 send_cmd_write_uart_register(edge_port, MCR,
1503                                                 edge_port->shadowMCR);
1504         }
1505 }
1506
1507
1508 /*****************************************************************************
1509  * SerialSetTermios
1510  *      this function is called by the tty driver when it wants to change
1511  * the termios structure
1512  *****************************************************************************/
1513 static void edge_set_termios(struct tty_struct *tty,
1514         struct usb_serial_port *port, struct ktermios *old_termios)
1515 {
1516         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1517         unsigned int cflag;
1518
1519         cflag = tty->termios->c_cflag;
1520         dbg("%s - clfag %08x iflag %08x", __func__,
1521             tty->termios->c_cflag, tty->termios->c_iflag);
1522         dbg("%s - old clfag %08x old iflag %08x", __func__,
1523             old_termios->c_cflag, old_termios->c_iflag);
1524
1525         dbg("%s - port %d", __func__, port->number);
1526
1527         if (edge_port == NULL)
1528                 return;
1529
1530         if (!edge_port->open) {
1531                 dbg("%s - port not opened", __func__);
1532                 return;
1533         }
1534
1535         /* change the port settings to the new ones specified */
1536         change_port_settings(tty, edge_port, old_termios);
1537 }
1538
1539
1540 /*****************************************************************************
1541  * get_lsr_info - get line status register info
1542  *
1543  * Purpose: Let user call ioctl() to get info when the UART physically
1544  *          is emptied.  On bus types like RS485, the transmitter must
1545  *          release the bus after transmitting. This must be done when
1546  *          the transmit shift register is empty, not be done when the
1547  *          transmit holding register is empty.  This functionality
1548  *          allows an RS485 driver to be written in user space.
1549  *****************************************************************************/
1550 static int get_lsr_info(struct edgeport_port *edge_port,
1551                                                 unsigned int __user *value)
1552 {
1553         unsigned int result = 0;
1554         unsigned long flags;
1555
1556         spin_lock_irqsave(&edge_port->ep_lock, flags);
1557         if (edge_port->maxTxCredits == edge_port->txCredits &&
1558             edge_port->txfifo.count == 0) {
1559                 dbg("%s -- Empty", __func__);
1560                 result = TIOCSER_TEMT;
1561         }
1562         spin_unlock_irqrestore(&edge_port->ep_lock, flags);
1563
1564         if (copy_to_user(value, &result, sizeof(int)))
1565                 return -EFAULT;
1566         return 0;
1567 }
1568
1569 static int edge_tiocmset(struct tty_struct *tty,
1570                                         unsigned int set, unsigned int clear)
1571 {
1572         struct usb_serial_port *port = tty->driver_data;
1573         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1574         unsigned int mcr;
1575
1576         dbg("%s - port %d", __func__, port->number);
1577
1578         mcr = edge_port->shadowMCR;
1579         if (set & TIOCM_RTS)
1580                 mcr |= MCR_RTS;
1581         if (set & TIOCM_DTR)
1582                 mcr |= MCR_DTR;
1583         if (set & TIOCM_LOOP)
1584                 mcr |= MCR_LOOPBACK;
1585
1586         if (clear & TIOCM_RTS)
1587                 mcr &= ~MCR_RTS;
1588         if (clear & TIOCM_DTR)
1589                 mcr &= ~MCR_DTR;
1590         if (clear & TIOCM_LOOP)
1591                 mcr &= ~MCR_LOOPBACK;
1592
1593         edge_port->shadowMCR = mcr;
1594
1595         send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR);
1596
1597         return 0;
1598 }
1599
1600 static int edge_tiocmget(struct tty_struct *tty)
1601 {
1602         struct usb_serial_port *port = tty->driver_data;
1603         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1604         unsigned int result = 0;
1605         unsigned int msr;
1606         unsigned int mcr;
1607
1608         dbg("%s - port %d", __func__, port->number);
1609
1610         msr = edge_port->shadowMSR;
1611         mcr = edge_port->shadowMCR;
1612         result = ((mcr & MCR_DTR)       ? TIOCM_DTR: 0)   /* 0x002 */
1613                   | ((mcr & MCR_RTS)    ? TIOCM_RTS: 0)   /* 0x004 */
1614                   | ((msr & EDGEPORT_MSR_CTS)   ? TIOCM_CTS: 0)   /* 0x020 */
1615                   | ((msr & EDGEPORT_MSR_CD)    ? TIOCM_CAR: 0)   /* 0x040 */
1616                   | ((msr & EDGEPORT_MSR_RI)    ? TIOCM_RI:  0)   /* 0x080 */
1617                   | ((msr & EDGEPORT_MSR_DSR)   ? TIOCM_DSR: 0);  /* 0x100 */
1618
1619
1620         dbg("%s -- %x", __func__, result);
1621
1622         return result;
1623 }
1624
1625 static int edge_get_icount(struct tty_struct *tty,
1626                                 struct serial_icounter_struct *icount)
1627 {
1628         struct usb_serial_port *port = tty->driver_data;
1629         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1630         struct async_icount cnow;
1631         cnow = edge_port->icount;
1632
1633         icount->cts = cnow.cts;
1634         icount->dsr = cnow.dsr;
1635         icount->rng = cnow.rng;
1636         icount->dcd = cnow.dcd;
1637         icount->rx = cnow.rx;
1638         icount->tx = cnow.tx;
1639         icount->frame = cnow.frame;
1640         icount->overrun = cnow.overrun;
1641         icount->parity = cnow.parity;
1642         icount->brk = cnow.brk;
1643         icount->buf_overrun = cnow.buf_overrun;
1644
1645         dbg("%s (%d) TIOCGICOUNT RX=%d, TX=%d",
1646                         __func__,  port->number, icount->rx, icount->tx);
1647         return 0;
1648 }
1649
1650 static int get_serial_info(struct edgeport_port *edge_port,
1651                                 struct serial_struct __user *retinfo)
1652 {
1653         struct serial_struct tmp;
1654
1655         if (!retinfo)
1656                 return -EFAULT;
1657
1658         memset(&tmp, 0, sizeof(tmp));
1659
1660         tmp.type                = PORT_16550A;
1661         tmp.line                = edge_port->port->serial->minor;
1662         tmp.port                = edge_port->port->number;
1663         tmp.irq                 = 0;
1664         tmp.flags               = ASYNC_SKIP_TEST | ASYNC_AUTO_IRQ;
1665         tmp.xmit_fifo_size      = edge_port->maxTxCredits;
1666         tmp.baud_base           = 9600;
1667         tmp.close_delay         = 5*HZ;
1668         tmp.closing_wait        = 30*HZ;
1669
1670         if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
1671                 return -EFAULT;
1672         return 0;
1673 }
1674
1675
1676 /*****************************************************************************
1677  * SerialIoctl
1678  *      this function handles any ioctl calls to the driver
1679  *****************************************************************************/
1680 static int edge_ioctl(struct tty_struct *tty,
1681                                         unsigned int cmd, unsigned long arg)
1682 {
1683         struct usb_serial_port *port = tty->driver_data;
1684         DEFINE_WAIT(wait);
1685         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1686         struct async_icount cnow;
1687         struct async_icount cprev;
1688
1689         dbg("%s - port %d, cmd = 0x%x", __func__, port->number, cmd);
1690
1691         switch (cmd) {
1692         case TIOCSERGETLSR:
1693                 dbg("%s (%d) TIOCSERGETLSR", __func__,  port->number);
1694                 return get_lsr_info(edge_port, (unsigned int __user *) arg);
1695
1696         case TIOCGSERIAL:
1697                 dbg("%s (%d) TIOCGSERIAL", __func__,  port->number);
1698                 return get_serial_info(edge_port, (struct serial_struct __user *) arg);
1699
1700         case TIOCMIWAIT:
1701                 dbg("%s (%d) TIOCMIWAIT", __func__,  port->number);
1702                 cprev = edge_port->icount;
1703                 while (1) {
1704                         prepare_to_wait(&port->delta_msr_wait,
1705                                                 &wait, TASK_INTERRUPTIBLE);
1706                         schedule();
1707                         finish_wait(&port->delta_msr_wait, &wait);
1708                         /* see if a signal did it */
1709                         if (signal_pending(current))
1710                                 return -ERESTARTSYS;
1711
1712                         if (port->serial->disconnected)
1713                                 return -EIO;
1714
1715                         cnow = edge_port->icount;
1716                         if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
1717                             cnow.dcd == cprev.dcd && cnow.cts == cprev.cts)
1718                                 return -EIO; /* no change => error */
1719                         if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
1720                             ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
1721                             ((arg & TIOCM_CD)  && (cnow.dcd != cprev.dcd)) ||
1722                             ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {
1723                                 return 0;
1724                         }
1725                         cprev = cnow;
1726                 }
1727                 /* NOTREACHED */
1728                 break;
1729
1730         }
1731         return -ENOIOCTLCMD;
1732 }
1733
1734
1735 /*****************************************************************************
1736  * SerialBreak
1737  *      this function sends a break to the port
1738  *****************************************************************************/
1739 static void edge_break(struct tty_struct *tty, int break_state)
1740 {
1741         struct usb_serial_port *port = tty->driver_data;
1742         struct edgeport_port *edge_port = usb_get_serial_port_data(port);
1743         struct edgeport_serial *edge_serial = usb_get_serial_data(port->serial);
1744         int status;
1745
1746         if ((!edge_serial->is_epic) ||
1747             ((edge_serial->is_epic) &&
1748              (edge_serial->epic_descriptor.Supports.IOSPChase))) {
1749                 /* flush and chase */
1750                 edge_port->chaseResponsePending = true;
1751
1752                 dbg("%s - Sending IOSP_CMD_CHASE_PORT", __func__);
1753                 status = send_iosp_ext_cmd(edge_port, IOSP_CMD_CHASE_PORT, 0);
1754                 if (status == 0) {
1755                         /* block until chase finished */
1756                         block_until_chase_response(edge_port);
1757                 } else {
1758                         edge_port->chaseResponsePending = false;
1759                 }
1760         }
1761
1762         if ((!edge_serial->is_epic) ||
1763             ((edge_serial->is_epic) &&
1764              (edge_serial->epic_descriptor.Supports.IOSPSetClrBreak))) {
1765                 if (break_state == -1) {
1766                         dbg("%s - Sending IOSP_CMD_SET_BREAK", __func__);
1767                         status = send_iosp_ext_cmd(edge_port,
1768                                                 IOSP_CMD_SET_BREAK, 0);
1769                 } else {
1770                         dbg("%s - Sending IOSP_CMD_CLEAR_BREAK", __func__);
1771                         status = send_iosp_ext_cmd(edge_port,
1772                                                 IOSP_CMD_CLEAR_BREAK, 0);
1773                 }
1774                 if (status)
1775                         dbg("%s - error sending break set/clear command.",
1776                                 __func__);
1777         }
1778 }
1779
1780
1781 /*****************************************************************************
1782  * process_rcvd_data
1783  *      this function handles the data received on the bulk in pipe.
1784  *****************************************************************************/
1785 static void process_rcvd_data(struct edgeport_serial *edge_serial,
1786                                 unsigned char *buffer, __u16 bufferLength)
1787 {
1788         struct usb_serial_port *port;
1789         struct edgeport_port *edge_port;
1790         struct tty_struct *tty;
1791         __u16 lastBufferLength;
1792         __u16 rxLen;
1793
1794         dbg("%s", __func__);
1795
1796         lastBufferLength = bufferLength + 1;
1797
1798         while (bufferLength > 0) {
1799                 /* failsafe incase we get a message that we don't understand */
1800                 if (lastBufferLength == bufferLength) {
1801                         dbg("%s - stuck in loop, exiting it.", __func__);
1802                         break;
1803                 }
1804                 lastBufferLength = bufferLength;
1805
1806                 switch (edge_serial->rxState) {
1807                 case EXPECT_HDR1:
1808                         edge_serial->rxHeader1 = *buffer;
1809                         ++buffer;
1810                         --bufferLength;
1811
1812                         if (bufferLength == 0) {
1813                                 edge_serial->rxState = EXPECT_HDR2;
1814                                 break;
1815                         }
1816                         /* otherwise, drop on through */
1817                 case EXPECT_HDR2:
1818                         edge_serial->rxHeader2 = *buffer;
1819                         ++buffer;
1820                         --bufferLength;
1821
1822                         dbg("%s - Hdr1=%02X Hdr2=%02X", __func__,
1823                             edge_serial->rxHeader1, edge_serial->rxHeader2);
1824                         /* Process depending on whether this header is
1825                          * data or status */
1826
1827                         if (IS_CMD_STAT_HDR(edge_serial->rxHeader1)) {
1828                                 /* Decode this status header and go to
1829                                  * EXPECT_HDR1 (if we can process the status
1830                                  * with only 2 bytes), or go to EXPECT_HDR3 to
1831                                  * get the third byte. */
1832                                 edge_serial->rxPort =
1833                                     IOSP_GET_HDR_PORT(edge_serial->rxHeader1);
1834                                 edge_serial->rxStatusCode =
1835                                     IOSP_GET_STATUS_CODE(
1836                                                 edge_serial->rxHeader1);
1837
1838                                 if (!IOSP_STATUS_IS_2BYTE(
1839                                                 edge_serial->rxStatusCode)) {
1840                                         /* This status needs additional bytes.
1841                                          * Save what we have and then wait for
1842                                          * more data.
1843                                          */
1844                                         edge_serial->rxStatusParam
1845                                                 = edge_serial->rxHeader2;
1846                                         edge_serial->rxState = EXPECT_HDR3;
1847                                         break;
1848                                 }
1849                                 /* We have all the header bytes, process the
1850                                    status now */
1851                                 process_rcvd_status(edge_serial,
1852                                                 edge_serial->rxHeader2, 0);
1853                                 edge_serial->rxState = EXPECT_HDR1;
1854                                 break;
1855                         } else {
1856                                 edge_serial->rxPort =
1857                                     IOSP_GET_HDR_PORT(edge_serial->rxHeader1);
1858                                 edge_serial->rxBytesRemaining =
1859                                     IOSP_GET_HDR_DATA_LEN(
1860                                                 edge_serial->rxHeader1,
1861                                                 edge_serial->rxHeader2);
1862                                 dbg("%s - Data for Port %u Len %u",
1863                                                 __func__,
1864                                                 edge_serial->rxPort,
1865                                                 edge_serial->rxBytesRemaining);
1866
1867                                 /* ASSERT(DevExt->RxPort < DevExt->NumPorts);
1868                                  * ASSERT(DevExt->RxBytesRemaining <
1869                                  *              IOSP_MAX_DATA_LENGTH);
1870                                  */
1871
1872                                 if (bufferLength == 0) {
1873                                         edge_serial->rxState = EXPECT_DATA;
1874                                         break;
1875                                 }
1876                                 /* Else, drop through */
1877                         }
1878                 case EXPECT_DATA: /* Expect data */
1879                         if (bufferLength < edge_serial->rxBytesRemaining) {
1880                                 rxLen = bufferLength;
1881                                 /* Expect data to start next buffer */
1882                                 edge_serial->rxState = EXPECT_DATA;
1883                         } else {
1884                                 /* BufLen >= RxBytesRemaining */
1885                                 rxLen = edge_serial->rxBytesRemaining;
1886                                 /* Start another header next time */
1887                                 edge_serial->rxState = EXPECT_HDR1;
1888                         }
1889
1890                         bufferLength -= rxLen;
1891                         edge_serial->rxBytesRemaining -= rxLen;
1892
1893                         /* spit this data back into the tty driver if this
1894                            port is open */
1895                         if (rxLen) {
1896                                 port = edge_serial->serial->port[
1897                                                         edge_serial->rxPort];
1898                                 edge_port = usb_get_serial_port_data(port);
1899                                 if (edge_port->open) {
1900                                         tty = tty_port_tty_get(
1901                                                 &edge_port->port->port);
1902                                         if (tty) {
1903                                                 dbg("%s - Sending %d bytes to TTY for port %d",
1904                                                         __func__, rxLen, edge_serial->rxPort);
1905                                                 edge_tty_recv(&edge_serial->serial->dev->dev, tty, buffer, rxLen);
1906                                                 tty_kref_put(tty);
1907                                         }
1908                                         edge_port->icount.rx += rxLen;
1909                                 }
1910                                 buffer += rxLen;
1911                         }
1912                         break;
1913
1914                 case EXPECT_HDR3:       /* Expect 3rd byte of status header */
1915                         edge_serial->rxHeader3 = *buffer;
1916                         ++buffer;
1917                         --bufferLength;
1918
1919                         /* We have all the header bytes, process the
1920                            status now */
1921                         process_rcvd_status(edge_serial,
1922                                 edge_serial->rxStatusParam,
1923                                 edge_serial->rxHeader3);
1924                         edge_serial->rxState = EXPECT_HDR1;
1925                         break;
1926                 }
1927         }
1928 }
1929
1930
1931 /*****************************************************************************
1932  * process_rcvd_status
1933  *      this function handles the any status messages received on the
1934  *      bulk in pipe.
1935  *****************************************************************************/
1936 static void process_rcvd_status(struct edgeport_serial *edge_serial,
1937                                                 __u8 byte2, __u8 byte3)
1938 {
1939         struct usb_serial_port *port;
1940         struct edgeport_port *edge_port;
1941         struct tty_struct *tty;
1942         __u8 code = edge_serial->rxStatusCode;
1943
1944         /* switch the port pointer to the one being currently talked about */
1945         port = edge_serial->serial->port[edge_serial->rxPort];
1946         edge_port = usb_get_serial_port_data(port);
1947         if (edge_port == NULL) {
1948                 dev_err(&edge_serial->serial->dev->dev,
1949                         "%s - edge_port == NULL for port %d\n",
1950                                         __func__, edge_serial->rxPort);
1951                 return;
1952         }
1953
1954         dbg("%s - port %d", __func__, edge_serial->rxPort);
1955
1956         if (code == IOSP_EXT_STATUS) {
1957                 switch (byte2) {
1958                 case IOSP_EXT_STATUS_CHASE_RSP:
1959                         /* we want to do EXT status regardless of port
1960                          * open/closed */
1961                         dbg("%s - Port %u EXT CHASE_RSP Data = %02x",
1962                                         __func__, edge_serial->rxPort, byte3);
1963                         /* Currently, the only EXT_STATUS is Chase, so process
1964                          * here instead of one more call to one more subroutine
1965                          * If/when more EXT_STATUS, there'll be more work to do
1966                          * Also, we currently clear flag and close the port
1967                          * regardless of content of above's Byte3.
1968                          * We could choose to do something else when Byte3 says
1969                          * Timeout on Chase from Edgeport, like wait longer in
1970                          * block_until_chase_response, but for now we don't.
1971                          */
1972                         edge_port->chaseResponsePending = false;
1973                         wake_up(&edge_port->wait_chase);
1974                         return;
1975
1976                 case IOSP_EXT_STATUS_RX_CHECK_RSP:
1977                         dbg("%s ========== Port %u CHECK_RSP Sequence = %02x =============", __func__, edge_serial->rxPort, byte3);
1978                         /* Port->RxCheckRsp = true; */
1979                         return;
1980                 }
1981         }
1982
1983         if (code == IOSP_STATUS_OPEN_RSP) {
1984                 edge_port->txCredits = GET_TX_BUFFER_SIZE(byte3);
1985                 edge_port->maxTxCredits = edge_port->txCredits;
1986                 dbg("%s - Port %u Open Response Initial MSR = %02x TxBufferSize = %d", __func__, edge_serial->rxPort, byte2, edge_port->txCredits);
1987                 handle_new_msr(edge_port, byte2);
1988
1989                 /* send the current line settings to the port so we are
1990                    in sync with any further termios calls */
1991                 tty = tty_port_tty_get(&edge_port->port->port);
1992                 if (tty) {
1993                         change_port_settings(tty,
1994                                 edge_port, tty->termios);
1995                         tty_kref_put(tty);
1996                 }
1997
1998                 /* we have completed the open */
1999                 edge_port->openPending = false;
2000                 edge_port->open = true;
2001                 wake_up(&edge_port->wait_open);
2002                 return;
2003         }
2004
2005         /* If port is closed, silently discard all rcvd status. We can
2006          * have cases where buffered status is received AFTER the close
2007          * port command is sent to the Edgeport.
2008          */
2009         if (!edge_port->open || edge_port->closePending)
2010                 return;
2011
2012         switch (code) {
2013         /* Not currently sent by Edgeport */
2014         case IOSP_STATUS_LSR:
2015                 dbg("%s - Port %u LSR Status = %02x",
2016                                         __func__, edge_serial->rxPort, byte2);
2017                 handle_new_lsr(edge_port, false, byte2, 0);
2018                 break;
2019
2020         case IOSP_STATUS_LSR_DATA:
2021                 dbg("%s - Port %u LSR Status = %02x, Data = %02x",
2022                                 __func__, edge_serial->rxPort, byte2, byte3);
2023                 /* byte2 is LSR Register */
2024                 /* byte3 is broken data byte */
2025                 handle_new_lsr(edge_port, true, byte2, byte3);
2026                 break;
2027         /*
2028          *      case IOSP_EXT_4_STATUS:
2029          *              dbg("%s - Port %u LSR Status = %02x Data = %02x",
2030          *                      __func__, edge_serial->rxPort, byte2, byte3);
2031          *              break;
2032          */
2033         case IOSP_STATUS_MSR:
2034                 dbg("%s - Port %u MSR Status = %02x",
2035                                         __func__, edge_serial->rxPort, byte2);
2036                 /*
2037                  * Process this new modem status and generate appropriate
2038                  * events, etc, based on the new status. This routine
2039                  * also saves the MSR in Port->ShadowMsr.
2040                  */
2041                 handle_new_msr(edge_port, byte2);
2042                 break;
2043
2044         default:
2045                 dbg("%s - Unrecognized IOSP status code %u", __func__, code);
2046                 break;
2047         }
2048 }
2049
2050
2051 /*****************************************************************************
2052  * edge_tty_recv
2053  *      this function passes data on to the tty flip buffer
2054  *****************************************************************************/
2055 static void edge_tty_recv(struct device *dev, struct tty_struct *tty,
2056                                         unsigned char *data, int length)
2057 {
2058         int cnt;
2059
2060         cnt = tty_insert_flip_string(tty, data, length);
2061         if (cnt < length) {
2062                 dev_err(dev, "%s - dropping data, %d bytes lost\n",
2063                                 __func__, length - cnt);
2064         }
2065         data += cnt;
2066         length -= cnt;
2067
2068         tty_flip_buffer_push(tty);
2069 }
2070
2071
2072 /*****************************************************************************
2073  * handle_new_msr
2074  *      this function handles any change to the msr register for a port.
2075  *****************************************************************************/
2076 static void handle_new_msr(struct edgeport_port *edge_port, __u8 newMsr)
2077 {
2078         struct  async_icount *icount;
2079
2080         dbg("%s %02x", __func__, newMsr);
2081
2082         if (newMsr & (EDGEPORT_MSR_DELTA_CTS | EDGEPORT_MSR_DELTA_DSR |
2083                         EDGEPORT_MSR_DELTA_RI | EDGEPORT_MSR_DELTA_CD)) {
2084                 icount = &edge_port->icount;
2085
2086                 /* update input line counters */
2087                 if (newMsr & EDGEPORT_MSR_DELTA_CTS)
2088                         icount->cts++;
2089                 if (newMsr & EDGEPORT_MSR_DELTA_DSR)
2090                         icount->dsr++;
2091                 if (newMsr & EDGEPORT_MSR_DELTA_CD)
2092                         icount->dcd++;
2093                 if (newMsr & EDGEPORT_MSR_DELTA_RI)
2094                         icount->rng++;
2095                 wake_up_interruptible(&edge_port->port->delta_msr_wait);
2096         }
2097
2098         /* Save the new modem status */
2099         edge_port->shadowMSR = newMsr & 0xf0;
2100 }
2101
2102
2103 /*****************************************************************************
2104  * handle_new_lsr
2105  *      this function handles any change to the lsr register for a port.
2106  *****************************************************************************/
2107 static void handle_new_lsr(struct edgeport_port *edge_port, __u8 lsrData,
2108                                                         __u8 lsr, __u8 data)
2109 {
2110         __u8 newLsr = (__u8) (lsr & (__u8)
2111                 (LSR_OVER_ERR | LSR_PAR_ERR | LSR_FRM_ERR | LSR_BREAK));
2112         struct async_icount *icount;
2113
2114         dbg("%s - %02x", __func__, newLsr);
2115
2116         edge_port->shadowLSR = lsr;
2117
2118         if (newLsr & LSR_BREAK) {
2119                 /*
2120                  * Parity and Framing errors only count if they
2121                  * occur exclusive of a break being
2122                  * received.
2123                  */
2124                 newLsr &= (__u8)(LSR_OVER_ERR | LSR_BREAK);
2125         }
2126
2127         /* Place LSR data byte into Rx buffer */
2128         if (lsrData) {
2129                 struct tty_struct *tty =
2130                                 tty_port_tty_get(&edge_port->port->port);
2131                 if (tty) {
2132                         edge_tty_recv(&edge_port->port->dev, tty, &data, 1);
2133                         tty_kref_put(tty);
2134                 }
2135         }
2136         /* update input line counters */
2137         icount = &edge_port->icount;
2138         if (newLsr & LSR_BREAK)
2139                 icount->brk++;
2140         if (newLsr & LSR_OVER_ERR)
2141                 icount->overrun++;
2142         if (newLsr & LSR_PAR_ERR)
2143                 icount->parity++;
2144         if (newLsr & LSR_FRM_ERR)
2145                 icount->frame++;
2146 }
2147
2148
2149 /****************************************************************************
2150  * sram_write
2151  *      writes a number of bytes to the Edgeport device's sram starting at the
2152  *      given address.
2153  *      If successful returns the number of bytes written, otherwise it returns
2154  *      a negative error number of the problem.
2155  ****************************************************************************/
2156 static int sram_write(struct usb_serial *serial, __u16 extAddr, __u16 addr,
2157                                         __u16 length, const __u8 *data)
2158 {
2159         int result;
2160         __u16 current_length;
2161         unsigned char *transfer_buffer;
2162
2163         dbg("%s - %x, %x, %d", __func__, extAddr, addr, length);
2164
2165         transfer_buffer =  kmalloc(64, GFP_KERNEL);
2166         if (!transfer_buffer) {
2167                 dev_err(&serial->dev->dev, "%s - kmalloc(%d) failed.\n",
2168                                                         __func__, 64);
2169                 return -ENOMEM;
2170         }
2171
2172         /* need to split these writes up into 64 byte chunks */
2173         result = 0;
2174         while (length > 0) {
2175                 if (length > 64)
2176                         current_length = 64;
2177                 else
2178                         current_length = length;
2179
2180 /*              dbg("%s - writing %x, %x, %d", __func__,
2181                                         extAddr, addr, current_length); */
2182                 memcpy(transfer_buffer, data, current_length);
2183                 result = usb_control_msg(serial->dev,
2184                                         usb_sndctrlpipe(serial->dev, 0),
2185                                         USB_REQUEST_ION_WRITE_RAM,
2186                                         0x40, addr, extAddr, transfer_buffer,
2187                                         current_length, 300);
2188                 if (result < 0)
2189                         break;
2190                 length -= current_length;
2191                 addr += current_length;
2192                 data += current_length;
2193         }
2194
2195         kfree(transfer_buffer);
2196         return result;
2197 }
2198
2199
2200 /****************************************************************************
2201  * rom_write
2202  *      writes a number of bytes to the Edgeport device's ROM starting at the
2203  *      given address.
2204  *      If successful returns the number of bytes written, otherwise it returns
2205  *      a negative error number of the problem.
2206  ****************************************************************************/
2207 static int rom_write(struct usb_serial *serial, __u16 extAddr, __u16 addr,
2208                                         __u16 length, const __u8 *data)
2209 {
2210         int result;
2211         __u16 current_length;
2212         unsigned char *transfer_buffer;
2213
2214 /*      dbg("%s - %x, %x, %d", __func__, extAddr, addr, length); */
2215
2216         transfer_buffer =  kmalloc(64, GFP_KERNEL);
2217         if (!transfer_buffer) {
2218                 dev_err(&serial->dev->dev, "%s - kmalloc(%d) failed.\n",
2219                                                                 __func__, 64);
2220                 return -ENOMEM;
2221         }
2222
2223         /* need to split these writes up into 64 byte chunks */
2224         result = 0;
2225         while (length > 0) {
2226                 if (length > 64)
2227                         current_length = 64;
2228                 else
2229                         current_length = length;
2230 /*              dbg("%s - writing %x, %x, %d", __func__,
2231                                         extAddr, addr, current_length); */
2232                 memcpy(transfer_buffer, data, current_length);
2233                 result = usb_control_msg(serial->dev,
2234                                         usb_sndctrlpipe(serial->dev, 0),
2235                                         USB_REQUEST_ION_WRITE_ROM, 0x40,
2236                                         addr, extAddr,
2237                                         transfer_buffer, current_length, 300);
2238                 if (result < 0)
2239                         break;
2240                 length -= current_length;
2241                 addr += current_length;
2242                 data += current_length;
2243         }
2244
2245         kfree(transfer_buffer);
2246         return result;
2247 }
2248
2249
2250 /****************************************************************************
2251  * rom_read
2252  *      reads a number of bytes from the Edgeport device starting at the given
2253  *      address.
2254  *      If successful returns the number of bytes read, otherwise it returns
2255  *      a negative error number of the problem.
2256  ****************************************************************************/
2257 static int rom_read(struct usb_serial *serial, __u16 extAddr,
2258                                         __u16 addr, __u16 length, __u8 *data)
2259 {
2260         int result;
2261         __u16 current_length;
2262         unsigned char *transfer_buffer;
2263
2264         dbg("%s - %x, %x, %d", __func__, extAddr, addr, length);
2265
2266         transfer_buffer =  kmalloc(64, GFP_KERNEL);
2267         if (!transfer_buffer) {
2268                 dev_err(&serial->dev->dev,
2269                         "%s - kmalloc(%d) failed.\n", __func__, 64);
2270                 return -ENOMEM;
2271         }
2272
2273         /* need to split these reads up into 64 byte chunks */
2274         result = 0;
2275         while (length > 0) {
2276                 if (length > 64)
2277                         current_length = 64;
2278                 else
2279                         current_length = length;
2280 /*              dbg("%s - %x, %x, %d", __func__,
2281                                 extAddr, addr, current_length); */
2282                 result = usb_control_msg(serial->dev,
2283                                         usb_rcvctrlpipe(serial->dev, 0),
2284                                         USB_REQUEST_ION_READ_ROM,
2285                                         0xC0, addr, extAddr, transfer_buffer,
2286                                         current_length, 300);
2287                 if (result < 0)
2288                         break;
2289                 memcpy(data, transfer_buffer, current_length);
2290                 length -= current_length;
2291                 addr += current_length;
2292                 data += current_length;
2293         }
2294
2295         kfree(transfer_buffer);
2296         return result;
2297 }
2298
2299
2300 /****************************************************************************
2301  * send_iosp_ext_cmd
2302  *      Is used to send a IOSP message to the Edgeport device
2303  ****************************************************************************/
2304 static int send_iosp_ext_cmd(struct edgeport_port *edge_port,
2305                                                 __u8 command, __u8 param)
2306 {
2307         unsigned char   *buffer;
2308         unsigned char   *currentCommand;
2309         int             length = 0;
2310         int             status = 0;
2311
2312         dbg("%s - %d, %d", __func__, command, param);
2313
2314         buffer = kmalloc(10, GFP_ATOMIC);
2315         if (!buffer) {
2316                 dev_err(&edge_port->port->dev,
2317                                 "%s - kmalloc(%d) failed.\n", __func__, 10);
2318                 return -ENOMEM;
2319         }
2320
2321         currentCommand = buffer;
2322
2323         MAKE_CMD_EXT_CMD(&currentCommand, &length,
2324                 edge_port->port->number - edge_port->port->serial->minor,
2325                 command, param);
2326
2327         status = write_cmd_usb(edge_port, buffer, length);
2328         if (status) {
2329                 /* something bad happened, let's free up the memory */
2330                 kfree(buffer);
2331         }
2332
2333         return status;
2334 }
2335
2336
2337 /*****************************************************************************
2338  * write_cmd_usb
2339  *      this function writes the given buffer out to the bulk write endpoint.
2340  *****************************************************************************/
2341 static int write_cmd_usb(struct edgeport_port *edge_port,
2342                                         unsigned char *buffer, int length)
2343 {
2344         struct edgeport_serial *edge_serial =
2345                                 usb_get_serial_data(edge_port->port->serial);
2346         int status = 0;
2347         struct urb *urb;
2348
2349         usb_serial_debug_data(debug, &edge_port->port->dev,
2350                                                 __func__, length, buffer);
2351
2352         /* Allocate our next urb */
2353         urb = usb_alloc_urb(0, GFP_ATOMIC);
2354         if (!urb)
2355                 return -ENOMEM;
2356
2357         atomic_inc(&CmdUrbs);
2358         dbg("%s - ALLOCATE URB %p (outstanding %d)",
2359                                 __func__, urb, atomic_read(&CmdUrbs));
2360
2361         usb_fill_bulk_urb(urb, edge_serial->serial->dev,
2362                         usb_sndbulkpipe(edge_serial->serial->dev,
2363                                         edge_serial->bulk_out_endpoint),
2364                         buffer, length, edge_bulk_out_cmd_callback, edge_port);
2365
2366         edge_port->commandPending = true;
2367         status = usb_submit_urb(urb, GFP_ATOMIC);
2368
2369         if (status) {
2370                 /* something went wrong */
2371                 dev_err(&edge_port->port->dev,
2372                     "%s - usb_submit_urb(write command) failed, status = %d\n",
2373                                                         __func__, status);
2374                 usb_kill_urb(urb);
2375                 usb_free_urb(urb);
2376                 atomic_dec(&CmdUrbs);
2377                 return status;
2378         }
2379
2380 #if 0
2381         wait_event(&edge_port->wait_command, !edge_port->commandPending);
2382
2383         if (edge_port->commandPending) {
2384                 /* command timed out */
2385                 dbg("%s - command timed out", __func__);
2386                 status = -EINVAL;
2387         }
2388 #endif
2389         return status;
2390 }
2391
2392
2393 /*****************************************************************************
2394  * send_cmd_write_baud_rate
2395  *      this function sends the proper command to change the baud rate of the
2396  *      specified port.
2397  *****************************************************************************/
2398 static int send_cmd_write_baud_rate(struct edgeport_port *edge_port,
2399                                                                 int baudRate)
2400 {
2401         struct edgeport_serial *edge_serial =
2402                                 usb_get_serial_data(edge_port->port->serial);
2403         unsigned char *cmdBuffer;
2404         unsigned char *currCmd;
2405         int cmdLen = 0;
2406         int divisor;
2407         int status;
2408         unsigned char number =
2409                 edge_port->port->number - edge_port->port->serial->minor;
2410
2411         if (edge_serial->is_epic &&
2412             !edge_serial->epic_descriptor.Supports.IOSPSetBaudRate) {
2413                 dbg("SendCmdWriteBaudRate - NOT Setting baud rate for port = %d, baud = %d",
2414                     edge_port->port->number, baudRate);
2415                 return 0;
2416         }
2417
2418         dbg("%s - port = %d, baud = %d", __func__,
2419                                         edge_port->port->number, baudRate);
2420
2421         status = calc_baud_rate_divisor(baudRate, &divisor);
2422         if (status) {
2423                 dev_err(&edge_port->port->dev, "%s - bad baud rate\n",
2424                                                                 __func__);
2425                 return status;
2426         }
2427
2428         /* Alloc memory for the string of commands. */
2429         cmdBuffer =  kmalloc(0x100, GFP_ATOMIC);
2430         if (!cmdBuffer) {
2431                 dev_err(&edge_port->port->dev,
2432                         "%s - kmalloc(%d) failed.\n", __func__, 0x100);
2433                 return -ENOMEM;
2434         }
2435         currCmd = cmdBuffer;
2436
2437         /* Enable access to divisor latch */
2438         MAKE_CMD_WRITE_REG(&currCmd, &cmdLen, number, LCR, LCR_DL_ENABLE);
2439
2440         /* Write the divisor itself */
2441         MAKE_CMD_WRITE_REG(&currCmd, &cmdLen, number, DLL, LOW8(divisor));
2442         MAKE_CMD_WRITE_REG(&currCmd, &cmdLen, number, DLM, HIGH8(divisor));
2443
2444         /* Restore original value to disable access to divisor latch */
2445         MAKE_CMD_WRITE_REG(&currCmd, &cmdLen, number, LCR,
2446                                                 edge_port->shadowLCR);
2447
2448         status = write_cmd_usb(edge_port, cmdBuffer, cmdLen);
2449         if (status) {
2450                 /* something bad happened, let's free up the memory */
2451                 kfree(cmdBuffer);
2452         }
2453
2454         return status;
2455 }
2456
2457
2458 /*****************************************************************************
2459  * calc_baud_rate_divisor
2460  *      this function calculates the proper baud rate divisor for the specified
2461  *      baud rate.
2462  *****************************************************************************/
2463 static int calc_baud_rate_divisor(int baudrate, int *divisor)
2464 {
2465         int i;
2466         __u16 custom;
2467
2468
2469         dbg("%s - %d", __func__, baudrate);
2470
2471         for (i = 0; i < ARRAY_SIZE(divisor_table); i++) {
2472                 if (divisor_table[i].BaudRate == baudrate) {
2473                         *divisor = divisor_table[i].Divisor;
2474                         return 0;
2475                 }
2476         }
2477
2478         /* We have tried all of the standard baud rates
2479          * lets try to calculate the divisor for this baud rate
2480          * Make sure the baud rate is reasonable */
2481         if (baudrate > 50 && baudrate < 230400) {
2482                 /* get divisor */
2483                 custom = (__u16)((230400L + baudrate/2) / baudrate);
2484
2485                 *divisor = custom;
2486
2487                 dbg("%s - Baud %d = %d", __func__, baudrate, custom);
2488                 return 0;
2489         }
2490
2491         return -1;
2492 }
2493
2494
2495 /*****************************************************************************
2496  * send_cmd_write_uart_register
2497  *  this function builds up a uart register message and sends to the device.
2498  *****************************************************************************/
2499 static int send_cmd_write_uart_register(struct edgeport_port *edge_port,
2500                                                 __u8 regNum, __u8 regValue)
2501 {
2502         struct edgeport_serial *edge_serial =
2503                                 usb_get_serial_data(edge_port->port->serial);
2504         unsigned char *cmdBuffer;
2505         unsigned char *currCmd;
2506         unsigned long cmdLen = 0;
2507         int status;
2508
2509         dbg("%s - write to %s register 0x%02x",
2510                         (regNum == MCR) ? "MCR" : "LCR", __func__, regValue);
2511
2512         if (edge_serial->is_epic &&
2513             !edge_serial->epic_descriptor.Supports.IOSPWriteMCR &&
2514             regNum == MCR) {
2515                 dbg("SendCmdWriteUartReg - Not writing to MCR Register");
2516                 return 0;
2517         }
2518
2519         if (edge_serial->is_epic &&
2520             !edge_serial->epic_descriptor.Supports.IOSPWriteLCR &&
2521             regNum == LCR) {
2522                 dbg("SendCmdWriteUartReg - Not writing to LCR Register");
2523                 return 0;
2524         }
2525
2526         /* Alloc memory for the string of commands. */
2527         cmdBuffer = kmalloc(0x10, GFP_ATOMIC);
2528         if (cmdBuffer == NULL)
2529                 return -ENOMEM;
2530
2531         currCmd = cmdBuffer;
2532
2533         /* Build a cmd in the buffer to write the given register */
2534         MAKE_CMD_WRITE_REG(&currCmd, &cmdLen,
2535                 edge_port->port->number - edge_port->port->serial->minor,
2536                 regNum, regValue);
2537
2538         status = write_cmd_usb(edge_port, cmdBuffer, cmdLen);
2539         if (status) {
2540                 /* something bad happened, let's free up the memory */
2541                 kfree(cmdBuffer);
2542         }
2543
2544         return status;
2545 }
2546
2547
2548 /*****************************************************************************
2549  * change_port_settings
2550  *      This routine is called to set the UART on the device to match the
2551  *      specified new settings.
2552  *****************************************************************************/
2553
2554 static void change_port_settings(struct tty_struct *tty,
2555         struct edgeport_port *edge_port, struct ktermios *old_termios)
2556 {
2557         struct edgeport_serial *edge_serial =
2558                         usb_get_serial_data(edge_port->port->serial);
2559         int baud;
2560         unsigned cflag;
2561         __u8 mask = 0xff;
2562         __u8 lData;
2563         __u8 lParity;
2564         __u8 lStop;
2565         __u8 rxFlow;
2566         __u8 txFlow;
2567         int status;
2568
2569         dbg("%s - port %d", __func__, edge_port->port->number);
2570
2571         if (!edge_port->open &&
2572             !edge_port->openPending) {
2573                 dbg("%s - port not opened", __func__);
2574                 return;
2575         }
2576
2577         cflag = tty->termios->c_cflag;
2578
2579         switch (cflag & CSIZE) {
2580         case CS5:
2581                 lData = LCR_BITS_5; mask = 0x1f;
2582                 dbg("%s - data bits = 5", __func__);
2583                 break;
2584         case CS6:
2585                 lData = LCR_BITS_6; mask = 0x3f;
2586                 dbg("%s - data bits = 6", __func__);
2587                 break;
2588         case CS7:
2589                 lData = LCR_BITS_7; mask = 0x7f;
2590                 dbg("%s - data bits = 7", __func__);
2591                 break;
2592         default:
2593         case CS8:
2594                 lData = LCR_BITS_8;
2595                 dbg("%s - data bits = 8", __func__);
2596                 break;
2597         }
2598
2599         lParity = LCR_PAR_NONE;
2600         if (cflag & PARENB) {
2601                 if (cflag & CMSPAR) {
2602                         if (cflag & PARODD) {
2603                                 lParity = LCR_PAR_MARK;
2604                                 dbg("%s - parity = mark", __func__);
2605                         } else {
2606                                 lParity = LCR_PAR_SPACE;
2607                                 dbg("%s - parity = space", __func__);
2608                         }
2609                 } else if (cflag & PARODD) {
2610                         lParity = LCR_PAR_ODD;
2611                         dbg("%s - parity = odd", __func__);
2612                 } else {
2613                         lParity = LCR_PAR_EVEN;
2614                         dbg("%s - parity = even", __func__);
2615                 }
2616         } else {
2617                 dbg("%s - parity = none", __func__);
2618         }
2619
2620         if (cflag & CSTOPB) {
2621                 lStop = LCR_STOP_2;
2622                 dbg("%s - stop bits = 2", __func__);
2623         } else {
2624                 lStop = LCR_STOP_1;
2625                 dbg("%s - stop bits = 1", __func__);
2626         }
2627
2628         /* figure out the flow control settings */
2629         rxFlow = txFlow = 0x00;
2630         if (cflag & CRTSCTS) {
2631                 rxFlow |= IOSP_RX_FLOW_RTS;
2632                 txFlow |= IOSP_TX_FLOW_CTS;
2633                 dbg("%s - RTS/CTS is enabled", __func__);
2634         } else {
2635                 dbg("%s - RTS/CTS is disabled", __func__);
2636         }
2637
2638         /* if we are implementing XON/XOFF, set the start and stop character
2639            in the device */
2640         if (I_IXOFF(tty) || I_IXON(tty)) {
2641                 unsigned char stop_char  = STOP_CHAR(tty);
2642                 unsigned char start_char = START_CHAR(tty);
2643
2644                 if ((!edge_serial->is_epic) ||
2645                     ((edge_serial->is_epic) &&
2646                      (edge_serial->epic_descriptor.Supports.IOSPSetXChar))) {
2647                         send_iosp_ext_cmd(edge_port,
2648                                         IOSP_CMD_SET_XON_CHAR, start_char);
2649                         send_iosp_ext_cmd(edge_port,
2650                                         IOSP_CMD_SET_XOFF_CHAR, stop_char);
2651                 }
2652
2653                 /* if we are implementing INBOUND XON/XOFF */
2654                 if (I_IXOFF(tty)) {
2655                         rxFlow |= IOSP_RX_FLOW_XON_XOFF;
2656                         dbg("%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x",
2657                                         __func__, start_char, stop_char);
2658                 } else {
2659                         dbg("%s - INBOUND XON/XOFF is disabled", __func__);
2660                 }
2661
2662                 /* if we are implementing OUTBOUND XON/XOFF */
2663                 if (I_IXON(tty)) {
2664                         txFlow |= IOSP_TX_FLOW_XON_XOFF;
2665                         dbg("%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x",
2666                                         __func__, start_char, stop_char);
2667                 } else {
2668                         dbg("%s - OUTBOUND XON/XOFF is disabled", __func__);
2669                 }
2670         }
2671
2672         /* Set flow control to the configured value */
2673         if ((!edge_serial->is_epic) ||
2674             ((edge_serial->is_epic) &&
2675              (edge_serial->epic_descriptor.Supports.IOSPSetRxFlow)))
2676                 send_iosp_ext_cmd(edge_port, IOSP_CMD_SET_RX_FLOW, rxFlow);
2677         if ((!edge_serial->is_epic) ||
2678             ((edge_serial->is_epic) &&
2679              (edge_serial->epic_descriptor.Supports.IOSPSetTxFlow)))
2680                 send_iosp_ext_cmd(edge_port, IOSP_CMD_SET_TX_FLOW, txFlow);
2681
2682
2683         edge_port->shadowLCR &= ~(LCR_BITS_MASK | LCR_STOP_MASK | LCR_PAR_MASK);
2684         edge_port->shadowLCR |= (lData | lParity | lStop);
2685
2686         edge_port->validDataMask = mask;
2687
2688         /* Send the updated LCR value to the EdgePort */
2689         status = send_cmd_write_uart_register(edge_port, LCR,
2690                                                         edge_port->shadowLCR);
2691         if (status != 0)
2692                 return;
2693
2694         /* set up the MCR register and send it to the EdgePort */
2695         edge_port->shadowMCR = MCR_MASTER_IE;
2696         if (cflag & CBAUD)
2697                 edge_port->shadowMCR |= (MCR_DTR | MCR_RTS);
2698
2699         status = send_cmd_write_uart_register(edge_port, MCR,
2700                                                 edge_port->shadowMCR);
2701         if (status != 0)
2702                 return;
2703
2704         /* Determine divisor based on baud rate */
2705         baud = tty_get_baud_rate(tty);
2706         if (!baud) {
2707                 /* pick a default, any default... */
2708                 baud = 9600;
2709         }
2710
2711         dbg("%s - baud rate = %d", __func__, baud);
2712         status = send_cmd_write_baud_rate(edge_port, baud);
2713         if (status == -1) {
2714                 /* Speed change was not possible - put back the old speed */
2715                 baud = tty_termios_baud_rate(old_termios);
2716                 tty_encode_baud_rate(tty, baud, baud);
2717         }
2718 }
2719
2720
2721 /****************************************************************************
2722  * unicode_to_ascii
2723  *      Turns a string from Unicode into ASCII.
2724  *      Doesn't do a good job with any characters that are outside the normal
2725  *      ASCII range, but it's only for debugging...
2726  *      NOTE: expects the unicode in LE format
2727  ****************************************************************************/
2728 static void unicode_to_ascii(char *string, int buflen,
2729                                         __le16 *unicode, int unicode_size)
2730 {
2731         int i;
2732
2733         if (buflen <= 0)        /* never happens, but... */
2734                 return;
2735         --buflen;               /* space for nul */
2736
2737         for (i = 0; i < unicode_size; i++) {
2738                 if (i >= buflen)
2739                         break;
2740                 string[i] = (char)(le16_to_cpu(unicode[i]));
2741         }
2742         string[i] = 0x00;
2743 }
2744
2745
2746 /****************************************************************************
2747  * get_manufacturing_desc
2748  *      reads in the manufacturing descriptor and stores it into the serial
2749  *      structure.
2750  ****************************************************************************/
2751 static void get_manufacturing_desc(struct edgeport_serial *edge_serial)
2752 {
2753         int response;
2754
2755         dbg("getting manufacturer descriptor");
2756
2757         response = rom_read(edge_serial->serial,
2758                                 (EDGE_MANUF_DESC_ADDR & 0xffff0000) >> 16,
2759                                 (__u16)(EDGE_MANUF_DESC_ADDR & 0x0000ffff),
2760                                 EDGE_MANUF_DESC_LEN,
2761                                 (__u8 *)(&edge_serial->manuf_descriptor));
2762
2763         if (response < 1)
2764                 dev_err(&edge_serial->serial->dev->dev,
2765                         "error in getting manufacturer descriptor\n");
2766         else {
2767                 char string[30];
2768                 dbg("**Manufacturer Descriptor");
2769                 dbg("  RomSize:        %dK",
2770                         edge_serial->manuf_descriptor.RomSize);
2771                 dbg("  RamSize:        %dK",
2772                         edge_serial->manuf_descriptor.RamSize);
2773                 dbg("  CpuRev:         %d",
2774                         edge_serial->manuf_descriptor.CpuRev);
2775                 dbg("  BoardRev:       %d",
2776                         edge_serial->manuf_descriptor.BoardRev);
2777                 dbg("  NumPorts:       %d",
2778                         edge_serial->manuf_descriptor.NumPorts);
2779                 dbg("  DescDate:       %d/%d/%d",
2780                         edge_serial->manuf_descriptor.DescDate[0],
2781                         edge_serial->manuf_descriptor.DescDate[1],
2782                         edge_serial->manuf_descriptor.DescDate[2]+1900);
2783                 unicode_to_ascii(string, sizeof(string),
2784                         edge_serial->manuf_descriptor.SerialNumber,
2785                         edge_serial->manuf_descriptor.SerNumLength/2);
2786                 dbg("  SerialNumber: %s", string);
2787                 unicode_to_ascii(string, sizeof(string),
2788                         edge_serial->manuf_descriptor.AssemblyNumber,
2789                         edge_serial->manuf_descriptor.AssemblyNumLength/2);
2790                 dbg("  AssemblyNumber: %s", string);
2791                 unicode_to_ascii(string, sizeof(string),
2792                     edge_serial->manuf_descriptor.OemAssyNumber,
2793                     edge_serial->manuf_descriptor.OemAssyNumLength/2);
2794                 dbg("  OemAssyNumber:  %s", string);
2795                 dbg("  UartType:       %d",
2796                         edge_serial->manuf_descriptor.UartType);
2797                 dbg("  IonPid:         %d",
2798                         edge_serial->manuf_descriptor.IonPid);
2799                 dbg("  IonConfig:      %d",
2800                         edge_serial->manuf_descriptor.IonConfig);
2801         }
2802 }
2803
2804
2805 /****************************************************************************
2806  * get_boot_desc
2807  *      reads in the bootloader descriptor and stores it into the serial
2808  *      structure.
2809  ****************************************************************************/
2810 static void get_boot_desc(struct edgeport_serial *edge_serial)
2811 {
2812         int response;
2813
2814         dbg("getting boot descriptor");
2815
2816         response = rom_read(edge_serial->serial,
2817                                 (EDGE_BOOT_DESC_ADDR & 0xffff0000) >> 16,
2818                                 (__u16)(EDGE_BOOT_DESC_ADDR & 0x0000ffff),
2819                                 EDGE_BOOT_DESC_LEN,
2820                                 (__u8 *)(&edge_serial->boot_descriptor));
2821
2822         if (response < 1)
2823                 dev_err(&edge_serial->serial->dev->dev,
2824                                 "error in getting boot descriptor\n");
2825         else {
2826                 dbg("**Boot Descriptor:");
2827                 dbg("  BootCodeLength: %d",
2828                     le16_to_cpu(edge_serial->boot_descriptor.BootCodeLength));
2829                 dbg("  MajorVersion:   %d",
2830                         edge_serial->boot_descriptor.MajorVersion);
2831                 dbg("  MinorVersion:   %d",
2832                         edge_serial->boot_descriptor.MinorVersion);
2833                 dbg("  BuildNumber:    %d",
2834                         le16_to_cpu(edge_serial->boot_descriptor.BuildNumber));
2835                 dbg("  Capabilities:   0x%x",
2836                       le16_to_cpu(edge_serial->boot_descriptor.Capabilities));
2837                 dbg("  UConfig0:       %d",
2838                         edge_serial->boot_descriptor.UConfig0);
2839                 dbg("  UConfig1:       %d",
2840                         edge_serial->boot_descriptor.UConfig1);
2841         }
2842 }
2843
2844
2845 /****************************************************************************
2846  * load_application_firmware
2847  *      This is called to load the application firmware to the device
2848  ****************************************************************************/
2849 static void load_application_firmware(struct edgeport_serial *edge_serial)
2850 {
2851         const struct ihex_binrec *rec;
2852         const struct firmware *fw;
2853         const char *fw_name;
2854         const char *fw_info;
2855         int response;
2856         __u32 Operaddr;
2857         __u16 build;
2858
2859         switch (edge_serial->product_info.iDownloadFile) {
2860                 case EDGE_DOWNLOAD_FILE_I930:
2861                         fw_info = "downloading firmware version (930)";
2862                         fw_name = "edgeport/down.fw";
2863                         break;
2864
2865                 case EDGE_DOWNLOAD_FILE_80251:
2866                         fw_info = "downloading firmware version (80251)";
2867                         fw_name = "edgeport/down2.fw";
2868                         break;
2869
2870                 case EDGE_DOWNLOAD_FILE_NONE:
2871                         dbg("No download file specified, skipping download");
2872                         return;
2873
2874                 default:
2875                         return;
2876         }
2877
2878         response = request_ihex_firmware(&fw, fw_name,
2879                                     &edge_serial->serial->dev->dev);
2880         if (response) {
2881                 printk(KERN_ERR "Failed to load image \"%s\" err %d\n",
2882                        fw_name, response);
2883                 return;
2884         }
2885
2886         rec = (const struct ihex_binrec *)fw->data;
2887         build = (rec->data[2] << 8) | rec->data[3];
2888
2889         dbg("%s %d.%d.%d", fw_info, rec->data[0], rec->data[1], build);
2890
2891         edge_serial->product_info.FirmwareMajorVersion = rec->data[0];
2892         edge_serial->product_info.FirmwareMinorVersion = rec->data[1];
2893         edge_serial->product_info.FirmwareBuildNumber = cpu_to_le16(build);
2894
2895         for (rec = ihex_next_binrec(rec); rec;
2896              rec = ihex_next_binrec(rec)) {
2897                 Operaddr = be32_to_cpu(rec->addr);
2898                 response = sram_write(edge_serial->serial,