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