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