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