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