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