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