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