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