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