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