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