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