io_edgeport.c 95.6 KB
Newer Older
Linus Torvalds's avatar
Linus Torvalds committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * Edgeport USB Serial Converter driver
 *
 * Copyright(c) 2000 Inside Out Networks, All rights reserved.
 * Copyright(c) 2001 Greg Kroah-Hartman <greg@kroah.com>
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation; either version 2 of the License, or
 *	(at your option) any later version.
 *
 * Supports the following devices:
 *	Edgeport/4
 *	Edgeport/4t
 *	Edgeport/2
 *	Edgeport/4i
 *	Edgeport/2i
 *	Edgeport/421
 *	Edgeport/21
 *	Rapidport/4
 *	Edgeport/8
 *	Edgeport/2D8
 *	Edgeport/4D8
 *	Edgeport/8i
 *
 * Version history:
Linus Torvalds's avatar
Linus Torvalds committed
27
 * 
Linus Torvalds's avatar
Linus Torvalds committed
28 29 30 31 32 33 34 35
 * 2.2 2001_11_14 greg kroah-hartman
 *	- fixed bug in edge_close that kept the port from being used more
 *	  than once.
 *	- fixed memory leak on device removal.
 *	- fixed potential double free of memory when command urb submitting
 *	  failed.
 *	- other small cleanups when the device is removed
 *	
Linus Torvalds's avatar
Linus Torvalds committed
36 37 38
 * 2.1 2001_07_09 greg kroah-hartman
 *	- added support for TIOCMBIS and TIOCMBIC.
 *
Linus Torvalds's avatar
Linus Torvalds committed
39 40
 *     (04/08/2001) gb
 *	- Identify version on module load.
Linus Torvalds's avatar
Linus Torvalds committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
 *
 * 2.0 2001_03_05 greg kroah-hartman
 *	- reworked entire driver to fit properly in with the other usb-serial
 *	  drivers.  Occasional oopses still happen, but it's a good start.
 *
 * 1.2.3 (02/23/2001) greg kroah-hartman
 *	- changed device table to work properly for 2.4.x final format.
 *	- fixed problem with dropping data at high data rates.
 *
 * 1.2.2 (11/27/2000) greg kroah-hartman
 *	- cleaned up more NTisms.
 *	- Added device table for 2.4.0-test11
 *
 * 1.2.1 (11/08/2000) greg kroah-hartman
 *	- Started to clean up NTisms.
 *	- Fixed problem with dev field of urb for kernels >= 2.4.0-test9
 *
 * 1.2 (10/17/2000) David Iacovelli
 * 	Remove all EPIC code and GPL source
 *  Fix RELEVANT_IFLAG macro to include flow control 
 *  changes port configuration changes.
 *  Fix redefinition of SERIAL_MAGIC
 *  Change all timeout values to 5 seconds
 *  Tried to fix the UHCI multiple urb submission, but failed miserably.
 *  it seems to work fine with OHCI.
 *  ( Greg take a look at the #if 0 at end of WriteCmdUsb() we must 
 *    find a way to work arount this UHCI bug )
 *
 * 1.1 (10/11/2000) David Iacovelli
 *  Fix XON/XOFF flow control to support both IXON and IXOFF
 *
 * 0.9.27 (06/30/2000) David Iacovelli
 *  Added transmit queue and now allocate urb for command writes.
 *
 * 0.9.26 (06/29/2000) David Iacovelli
 *  Add support for 80251 based edgeport
 *
 * 0.9.25 (06/27/2000) David Iacovelli
 *  Do not close the port if it has multiple opens.
 *
 * 0.9.24 (05/26/2000) David Iacovelli
 *  Add IOCTLs to support RXTX and JAVA POS 
 *  and first cut at running BlackBox Demo
 *
 * 0.9.23 (05/24/2000) David Iacovelli
 *  Add IOCTLs to support RXTX and JAVA POS
 *
 * 0.9.22 (05/23/2000) David Iacovelli
 *  fixed bug in enumeration.  If epconfig turns on mapping by
 *  path after a device is already plugged in, we now update
 *  the mapping correctly
 *
 * 0.9.21 (05/16/2000) David Iacovelli
 *  Added BlockUntilChaseResp() to also wait for txcredits
 *  Updated the way we allocate and handle write URBs 
 *	Add debug code to dump buffers
 *
 * 0.9.20 (05/01/2000) David Iacovelli
 *	change driver to use usb/tts/
 *
 * 0.9.19 (05/01/2000) David Iacovelli
 *  Update code to compile if DEBUG is off
 *
 * 0.9.18 (04/28/2000) David Iacovelli
 *  cleanup and test tty_register with devfs
 *
 * 0.9.17 (04/27/2000) greg kroah-hartman
 * 	changed tty_register around to be like the way it
 * 	was before, but now it works properly with devfs.
 *
 * 0.9.16 (04/26/2000) david iacovelli
 *  Fixed bug in GetProductInfo()
 *
 * 0.9.15 (04/25/2000) david iacovelli
 *	Updated enumeration
 *
 * 0.9.14 (04/24/2000) david iacovelli
 *  Removed all config/status IOCTLS and 
 *  converted to using /proc/edgeport
 *  still playing with devfs
 *
 * 0.9.13 (04/24/2000) david iacovelli
 *  Removed configuration based on ttyUSB0
 *  Added support for configuration using /prod/edgeport
 *  first attempt at using devfs (not working yet!)
 *  Added IOCTL to GetProductInfo()
 *  Added support for custom baud rates
 *	Add support for random port numbers
 *
 * 0.9.12 (04/18/2000) david iacovelli
 *	added additional configuration IOCTLs
 *  use ttyUSB0 for configuration
 *
 * 0.9.11 (04/17/2000) greg kroah-hartman
 *	fixed module initialization race conditions.
 *	made all urbs dynamically allocated.
 *	made driver devfs compatible. now it only registers the tty device
 *	when the device is actually plugged in.
 *
 * 0.9.10 (04/13/2000) greg kroah-hartman
 *	added proc interface framework.
 *
 * 0.9.9 (04/13/2000) david iacovelli
 *	added enumeration code and ioctls to configure the device
 *
 * 0.9.8 (04/12/2000) david iacovelli
 *  Change interrupt read start when device is plugged in
 *  and stop when device is removed
 *	process interrupt reads when all ports are closed 
 *  (keep value of rxBytesAvail consistent with the edgeport)
 *  set the USB_BULK_QUEUE flag so that we can shove a bunch 
 *  of urbs at once down the pipe 
 *
 * 0.9.7 (04/10/2000) david iacovelli
 * 	start to add enumeration code.
 *  generate serial number for epic devices
 *  add support for kdb
 *
 * 0.9.6 (03/30/2000) david iacovelli
 *  add IOCTL to get string, manufacture, and boot descriptors
 *
 * 0.9.5 (03/14/2000) greg kroah-hartman
 *	more error checking added to SerialOpen to try to fix UHCI open problem
 *
 * 0.9.4 (03/09/2000) greg kroah-hartman
 *	added more error checking to handle oops when data is hanging
 *	around and tty is abruptly closed.
 *
 * 0.9.3 (03/09/2000) david iacovelli
 *	Add epic support for xon/xoff chars
 *	play with performance
 *
 * 0.9.2 (03/08/2000) greg kroah-hartman
 *	changed most "info" calls to "dbg"
 *	implemented flow control properly in the termios call
 *
 * 0.9.1 (03/08/2000) david iacovelli
 *	added EPIC support
 *	enabled bootloader update
 *
 * 0.9 (03/08/2000) greg kroah-hartman
 *	Release to IO networks.
 *	Integrated changes that David made
 *  made getting urbs for writing SMP safe
 *
 * 0.8 (03/07/2000) greg kroah-hartman
 *	Release to IO networks.
 *	Fixed problems that were seen in code by David.
 *  Now both Edgeport/4 and Edgeport/2 works properly.
 *  Changed most of the functions to use port instead of serial.
 *
 * 0.7 (02/27/2000) greg kroah-hartman
 *	Milestone 3 release.
 *	Release to IO Networks
 *	ioctl for waiting on line change implemented.
 *	ioctl for getting statistics implemented.
 *	multiport support working.
 *	lsr and msr registers are now handled properly.
 *	change break now hooked up and working.
 *	support for all known Edgeport devices.
 *
 * 0.6 (02/22/2000) greg kroah-hartman
 *	Release to IO networks.
 *	CHASE is implemented correctly when port is closed.
 *	SerialOpen now blocks correctly until port is fully opened.
 *
 * 0.5 (02/20/2000) greg kroah-hartman
 *	Release to IO networks.
 *	Known problems:
 *		modem status register changes are not sent on to the user
 *		CHASE is not implemented when the port is closed.
 *
 * 0.4 (02/16/2000) greg kroah-hartman
 *	Second cut at the CeBit demo.
 *	Doesn't leak memory on every write to the port
 *	Still small leaks on startup.
 *	Added support for Edgeport/2 and Edgeport/8
 *
 * 0.3 (02/15/2000) greg kroah-hartman
 *	CeBit demo release.
 *	Force the line settings to 4800, 8, 1, e for the demo.
 *	Warning! This version leaks memory like crazy!
 *
 * 0.2 (01/30/2000) greg kroah-hartman
 *	Milestone 1 release.
 *	Device is found by USB subsystem, enumerated, fimware is downloaded
 *	and the descriptors are printed to the debug log, config is set, and
 *	green light starts to blink. Open port works, and data can be sent
 *	and received at the default settings of the UART. Loopback connector
 *	and debug log confirms this.
 * 
 * 0.1 (01/23/2000) greg kroah-hartman
 *	Initial release to help IO Networks try to set up their test system. 
 *	Edgeport4 is recognized, firmware is downloaded, config is set so 
 *	device blinks green light every 3 sec. Port is bound, but opening,
 *	closing, and sending data do not work properly.
 * 
 */

Linus Torvalds's avatar
Linus Torvalds committed
240
#include <linux/config.h>
Linus Torvalds's avatar
Linus Torvalds committed
241 242 243 244 245 246
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/poll.h>
#include <linux/init.h>
Linus Torvalds's avatar
Linus Torvalds committed
247
#include <linux/slab.h>
Linus Torvalds's avatar
Linus Torvalds committed
248
#include <linux/fcntl.h>
Linus Torvalds's avatar
Linus Torvalds committed
249
#include <linux/tty.h>
Linus Torvalds's avatar
Linus Torvalds committed
250 251 252 253 254 255 256
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/serial.h>
#include <linux/ioctl.h>
#include <linux/proc_fs.h>
Linus Torvalds's avatar
Linus Torvalds committed
257
#include <linux/usb.h>
Linus Torvalds's avatar
Linus Torvalds committed
258 259

#ifdef CONFIG_USB_SERIAL_DEBUG
Linus Torvalds's avatar
Linus Torvalds committed
260
	static int debug = 1;
Linus Torvalds's avatar
Linus Torvalds committed
261
#else
Linus Torvalds's avatar
Linus Torvalds committed
262
	static int debug;
Linus Torvalds's avatar
Linus Torvalds committed
263 264 265 266 267 268 269 270
#endif

#include "usb-serial.h"

#include "io_edgeport.h"
#include "io_ionsp.h"		/* info for the iosp messages */
#include "io_16654.h"		/* 16654 UART defines */

Linus Torvalds's avatar
Linus Torvalds committed
271 272 273
/*
 * Version Information
 */
Linus Torvalds's avatar
Linus Torvalds committed
274
#define DRIVER_VERSION "v2.2"
Linus Torvalds's avatar
Linus Torvalds committed
275 276 277
#define DRIVER_AUTHOR "Greg Kroah-Hartman <greg@kroah.com> and David Iacovelli"
#define DRIVER_DESC "Edgeport USB Serial Driver"

Linus Torvalds's avatar
Linus Torvalds committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
/* First, the latest boot code - for first generation edgeports */
#define IMAGE_ARRAY_NAME	BootCodeImage_GEN1
#define IMAGE_VERSION_NAME	BootCodeImageVersion_GEN1
#include "io_fw_boot.h"		/* the bootloader firmware to download to a device, if it needs it */

/* for second generation edgeports */
#define IMAGE_ARRAY_NAME	BootCodeImage_GEN2
#define IMAGE_VERSION_NAME	BootCodeImageVersion_GEN2
#include "io_fw_boot2.h"	/* the bootloader firmware to download to a device, if it needs it */

/* Then finally the main run-time operational code - for first generation edgeports */
#define IMAGE_ARRAY_NAME	OperationalCodeImage_GEN1
#define IMAGE_VERSION_NAME	OperationalCodeImageVersion_GEN1
#include "io_fw_down.h"		/* Define array OperationalCodeImage[] */

/* for second generation edgeports */
#define IMAGE_ARRAY_NAME	OperationalCodeImage_GEN2
#define IMAGE_VERSION_NAME	OperationalCodeImageVersion_GEN2
#include "io_fw_down2.h"	/* Define array OperationalCodeImage[] */


#define MAX_NAME_LEN		64


#define CHASE_TIMEOUT		(5*HZ)		/* 5 seconds */
#define OPEN_TIMEOUT		(5*HZ)		/* 5 seconds */
#define COMMAND_TIMEOUT		(5*HZ)		/* 5 seconds */

#ifndef SERIAL_MAGIC
	#define SERIAL_MAGIC	0x6702
#endif
#define PORT_MAGIC		0x7301


/* receive port state */
enum RXSTATE {
	EXPECT_HDR1 = 0,	/* Expect header byte 1 */
	EXPECT_HDR2 = 1,	/* Expect header byte 2 */
	EXPECT_DATA = 2,	/* Expect 'RxBytesRemaining' data */
	EXPECT_HDR3 = 3,	/* Expect header byte 3 (for status hdrs only) */
};


/* Transmit Fifo 
 * This Transmit queue is an extension of the edgeport Rx buffer. 
 * The maximum amount of data buffered in both the edgeport 
 * Rx buffer (maxTxCredits) and this buffer will never exceed maxTxCredits.
 */
struct TxFifo {
	unsigned int	head;	/* index to head pointer (write) */
	unsigned int	tail;	/* index to tail pointer (read)  */
	unsigned int	count;	/* Bytes in queue */
	unsigned int	size;	/* Max size of queue (equal to Max number of TxCredits) */
	unsigned char	*fifo;	/* allocated Buffer */
};

/* This structure holds all of the local port information */
struct edgeport_port {
	__u16			txCredits;		/* our current credits for this port */
	__u16			maxTxCredits;		/* the max size of the port */

	struct TxFifo		txfifo;			/* transmit fifo -- size will be maxTxCredits */
	struct urb		*write_urb;		/* write URB for this port */
	char			write_in_progress;	/* TRUE while a write URB is outstanding */

	__u8			shadowLCR;		/* last LCR value received */
	__u8			shadowMCR;		/* last MCR value received */
	__u8			shadowMSR;		/* last MSR value received */
	__u8			shadowLSR;		/* last LSR value received */
	__u8			shadowXonChar;		/* last value set as XON char in Edgeport */
	__u8			shadowXoffChar;		/* last value set as XOFF char in Edgeport */
	__u8			validDataMask;
	__u32			baudRate;

	char			open;
	char			openPending;
	char			commandPending;
	char			closePending;
	char			chaseResponsePending;

	wait_queue_head_t	wait_chase;		/* for handling sleeping while waiting for chase to finish */
	wait_queue_head_t	wait_open;		/* for handling sleeping while waiting for open to finish */
	wait_queue_head_t	wait_command;		/* for handling sleeping while waiting for command to finish */
	wait_queue_head_t	delta_msr_wait;		/* for handling sleeping while waiting for msr change to happen */

	struct async_icount	icount;
	struct usb_serial_port	*port;			/* loop back to the owner of this object */
};


/* This structure holds all of the individual device information */
struct edgeport_serial {
	char			name[MAX_NAME_LEN+1];		/* string name of this device */

372 373
	struct edge_manuf_descriptor	manuf_descriptor;	/* the manufacturer descriptor */
	struct edge_boot_descriptor	boot_descriptor;	/* the boot firmware descriptor */
Linus Torvalds's avatar
Linus Torvalds committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
	struct edgeport_product_info	product_info;		/* Product Info */

	__u8			interrupt_in_endpoint;		/* the interrupt endpoint handle */
	unsigned char *		interrupt_in_buffer;		/* the buffer we use for the interrupt endpoint */
	struct urb *		interrupt_read_urb;		/* our interrupt urb */

	__u8			bulk_in_endpoint;		/* the bulk in endpoint handle */
	unsigned char *		bulk_in_buffer;			/* the buffer we use for the bulk in endpoint */
	struct urb *		read_urb;			/* our bulk read urb */

	__u8			bulk_out_endpoint;		/* the bulk out endpoint handle */

	__s16			rxBytesAvail;			/* the number of bytes that we need to read from this device */

	enum RXSTATE		rxState;			/* the current state of the bulk receive processor */
	__u8			rxHeader1;			/* receive header byte 1 */
	__u8			rxHeader2;			/* receive header byte 2 */
	__u8			rxHeader3;			/* receive header byte 3 */
	__u8			rxPort;				/* the port that we are currently receiving data for */
	__u8			rxStatusCode;			/* the receive status code */
	__u8			rxStatusParam;			/* the receive status paramater */
	__s16			rxBytesRemaining;		/* the number of port bytes left to read */
	struct usb_serial	*serial;			/* loop back to the owner of this object */
};

/* baud rate information */
400
struct divisor_table_entry {
Linus Torvalds's avatar
Linus Torvalds committed
401 402
	__u32   BaudRate;
	__u16  Divisor;
403
};
Linus Torvalds's avatar
Linus Torvalds committed
404 405 406 407 408 409

//
// Define table of divisors for Rev A EdgePort/4 hardware
// These assume a 3.6864MHz crystal, the standard /16, and
// MCR.7 = 0.
//
410
static struct divisor_table_entry divisor_table[] = {
Linus Torvalds's avatar
Linus Torvalds committed
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
	{   75,		3072},  
	{   110,	2095},		/* 2094.545455 => 230450   => .0217 % over */
	{   134,	1713},		/* 1713.011152 => 230398.5 => .00065% under */
	{   150,	1536},
	{   300,	768},
	{   600,	384},
	{   1200,	192},
	{   1800,	128},
	{   2400,	96},
	{   4800,	48},
	{   7200,	32},
	{   9600,	24},
	{   14400,	16},
	{   19200,	12},
	{   38400,	6},
	{   57600,	4},
	{   115200,	2},
	{   230400,	1},
};

/* local variables */
static int	CmdUrbs = 0;							/* Number of outstanding Command Write Urbs */


/* local function prototypes */

/* function prototypes for all URB callbacks */
static void edge_interrupt_callback	(struct urb *urb);
Linus Torvalds's avatar
Linus Torvalds committed
439
static void edge_bulk_in_callback	(struct urb *urb);
Linus Torvalds's avatar
Linus Torvalds committed
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
static void edge_bulk_out_data_callback	(struct urb *urb);
static void edge_bulk_out_cmd_callback	(struct urb *urb);

/* function prototypes for the usbserial callbacks */
static int  edge_open			(struct usb_serial_port *port, struct file *filp);
static void edge_close			(struct usb_serial_port *port, struct file *filp);
static int  edge_write			(struct usb_serial_port *port, int from_user, const unsigned char *buf, int count);
static int  edge_write_room		(struct usb_serial_port *port);
static int  edge_chars_in_buffer	(struct usb_serial_port *port);
static void edge_throttle		(struct usb_serial_port *port);
static void edge_unthrottle		(struct usb_serial_port *port);
static void edge_set_termios		(struct usb_serial_port *port, struct termios *old_termios);
static int  edge_ioctl			(struct usb_serial_port *port, struct file *file, unsigned int cmd, unsigned long arg);
static void edge_break			(struct usb_serial_port *port, int break_state);
static int  edge_startup		(struct usb_serial *serial);
static void edge_shutdown		(struct usb_serial *serial);


#include "io_tables.h"	/* all of the devices that this driver supports */


/* function prototypes for all of our local functions */
static int  process_rcvd_data		(struct edgeport_serial *edge_serial, unsigned char *buffer, __u16 bufferLength);
static void process_rcvd_status		(struct edgeport_serial *edge_serial, __u8 byte2, __u8 byte3);
static void handle_new_msr		(struct edgeport_port *edge_port, __u8 newMsr);
static void handle_new_lsr		(struct edgeport_port *edge_port, __u8 lsrData, __u8 lsr, __u8 data);
static int  send_iosp_ext_cmd		(struct edgeport_port *edge_port, __u8 command, __u8 param);
static int  calc_baud_rate_divisor	(int baud_rate, int *divisor);
static int  send_cmd_write_baud_rate	(struct edgeport_port *edge_port, int baudRate);
static void change_port_settings	(struct edgeport_port *edge_port, struct termios *old_termios);
static int  send_cmd_write_uart_register	(struct edgeport_port *edge_port, __u8 regNum, __u8 regValue);
static int  write_cmd_usb		(struct edgeport_port *edge_port, unsigned char *buffer, int writeLength);
static void send_more_port_data		(struct edgeport_serial *edge_serial, struct edgeport_port *edge_port);

static int  sram_write			(struct usb_serial *serial, __u16 extAddr, __u16 addr, __u16 length, __u8 *data);
static int  rom_read			(struct usb_serial *serial, __u16 extAddr, __u16 addr, __u16 length, __u8 *data);
static int  rom_write			(struct usb_serial *serial, __u16 extAddr, __u16 addr, __u16 length, __u8 *data);
static void get_manufacturing_desc	(struct edgeport_serial *edge_serial);
static void get_boot_desc		(struct edgeport_serial *edge_serial);
static void load_application_firmware	(struct edgeport_serial *edge_serial);


static void unicode_to_ascii		(char *string, short *unicode, int unicode_size);





// ************************************************************************
// ************************************************************************
// ************************************************************************
// ************************************************************************

/************************************************************************
 *									*
Linus Torvalds's avatar
Linus Torvalds committed
495
 * update_edgeport_E2PROM()	Compare current versions of		*
Linus Torvalds's avatar
Linus Torvalds committed
496 497 498 499 500
 *				Boot ROM and Manufacture 		*
 *				Descriptors with versions		*
 *				embedded in this driver			*
 *									*
 ************************************************************************/
Linus Torvalds's avatar
Linus Torvalds committed
501
static void update_edgeport_E2PROM (struct edgeport_serial *edge_serial)
Linus Torvalds's avatar
Linus Torvalds committed
502 503 504 505 506 507 508 509
{
	__u32 BootCurVer;
	__u32 BootNewVer;
	__u8 BootMajorVersion;                  
	__u8 BootMinorVersion;                  
	__u16 BootBuildNumber;
	__u8 *BootImage;      
	__u32 BootSize;
510
	struct edge_firmware_image_record *record;
Linus Torvalds's avatar
Linus Torvalds committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
	unsigned char *firmware;
	int response;


	switch (edge_serial->product_info.iDownloadFile) {
		case EDGE_DOWNLOAD_FILE_I930:
			BootMajorVersion	= BootCodeImageVersion_GEN1.MajorVersion;
			BootMinorVersion	= BootCodeImageVersion_GEN1.MinorVersion;
			BootBuildNumber		= BootCodeImageVersion_GEN1.BuildNumber;
			BootImage		= &BootCodeImage_GEN1[0];
			BootSize		= sizeof( BootCodeImage_GEN1 );
			break;

		case EDGE_DOWNLOAD_FILE_80251:
			BootMajorVersion	= BootCodeImageVersion_GEN2.MajorVersion;
			BootMinorVersion	= BootCodeImageVersion_GEN2.MinorVersion;
			BootBuildNumber		= BootCodeImageVersion_GEN2.BuildNumber;
			BootImage		= &BootCodeImage_GEN2[0];
			BootSize		= sizeof( BootCodeImage_GEN2 );
			break;

		default:
			return;
	}

	// Check Boot Image Version
	BootCurVer = (edge_serial->boot_descriptor.MajorVersion << 24) +
		     (edge_serial->boot_descriptor.MinorVersion << 16) +
		      edge_serial->boot_descriptor.BuildNumber;

	BootNewVer = (BootMajorVersion << 24) +
		     (BootMinorVersion << 16) +
		      BootBuildNumber;

	dbg("Current Boot Image version %d.%d.%d",
	    edge_serial->boot_descriptor.MajorVersion,
	    edge_serial->boot_descriptor.MinorVersion,
	    edge_serial->boot_descriptor.BuildNumber);


	if (BootNewVer > BootCurVer) {
		dbg("**Update Boot Image from %d.%d.%d to %d.%d.%d",
		    edge_serial->boot_descriptor.MajorVersion,
		    edge_serial->boot_descriptor.MinorVersion,
		    edge_serial->boot_descriptor.BuildNumber,
		    BootMajorVersion,
		    BootMinorVersion,
		    BootBuildNumber);


		dbg("Downloading new Boot Image");

		firmware = BootImage;

		for (;;) {
566
			record = (struct edge_firmware_image_record *)firmware;
Linus Torvalds's avatar
Linus Torvalds committed
567 568 569 570 571
			response = rom_write (edge_serial->serial, record->ExtAddr, record->Addr, record->Len, &record->Data[0]);
			if (response < 0) {
				err("sram_write failed (%x, %x, %d)", record->ExtAddr, record->Addr, record->Len);
				break;
			}
572
			firmware += sizeof (struct edge_firmware_image_record) + record->Len;
Linus Torvalds's avatar
Linus Torvalds committed
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
			if (firmware >= &BootImage[BootSize]) {
				break;
			}
		}
	} else {
		dbg("Boot Image -- already up to date");
	}
}


/************************************************************************
 *									*
 *  Get string descriptor from device					*
 *									*
 ************************************************************************/
static int get_string (struct usb_device *dev, int Id, char *string)
{
	struct usb_string_descriptor StringDesc;
	struct usb_string_descriptor *pStringDesc;

	dbg(__FUNCTION__ " - USB String ID = %d", Id );

	if (!usb_get_descriptor(dev, USB_DT_STRING, Id, &StringDesc, sizeof(StringDesc))) {
		return 0;
	}

	pStringDesc = kmalloc (StringDesc.bLength, GFP_KERNEL);

	if (!pStringDesc) {
		return 0;
	}

	if (!usb_get_descriptor(dev, USB_DT_STRING, Id, pStringDesc, StringDesc.bLength )) {
		kfree(pStringDesc);
		return 0;
	}

	unicode_to_ascii(string,  pStringDesc->wData,     pStringDesc->bLength/2-1);

	kfree(pStringDesc);
	return strlen(string);
}


Linus Torvalds's avatar
Linus Torvalds committed
617
#if 0
Linus Torvalds's avatar
Linus Torvalds committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
/************************************************************************
 *
 *  Get string descriptor from device
 *
 ************************************************************************/
static int get_string_desc (struct usb_device *dev, int Id, struct usb_string_descriptor **pRetDesc)
{
	struct usb_string_descriptor StringDesc;
	struct usb_string_descriptor *pStringDesc;

	dbg(__FUNCTION__ " - USB String ID = %d", Id );

	if (!usb_get_descriptor(dev, USB_DT_STRING, Id, &StringDesc, sizeof(StringDesc))) {
		return 0;
	}

	pStringDesc = kmalloc (StringDesc.bLength, GFP_KERNEL);

	if (!pStringDesc) {
		return -1;
	}

	if (!usb_get_descriptor(dev, USB_DT_STRING, Id, pStringDesc, StringDesc.bLength )) {
		kfree(pStringDesc);
		return -1;
	}

	*pRetDesc = pStringDesc;
	return 0;
}
Linus Torvalds's avatar
Linus Torvalds committed
648
#endif
Linus Torvalds's avatar
Linus Torvalds committed
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

static void get_product_info(struct edgeport_serial *edge_serial)
{
	struct edgeport_product_info *product_info = &edge_serial->product_info;

	memset (product_info, 0, sizeof(struct edgeport_product_info));

	product_info->ProductId		= (__u16)(edge_serial->serial->dev->descriptor.idProduct & ~ION_DEVICE_ID_GENERATION_2);
	product_info->NumPorts		= edge_serial->manuf_descriptor.NumPorts;
	product_info->ProdInfoVer	= 0;

	product_info->RomSize		= edge_serial->manuf_descriptor.RomSize;
	product_info->RamSize		= edge_serial->manuf_descriptor.RamSize;
	product_info->CpuRev		= edge_serial->manuf_descriptor.CpuRev;
	product_info->BoardRev		= edge_serial->manuf_descriptor.BoardRev;

	product_info->BootMajorVersion	= edge_serial->boot_descriptor.MajorVersion;
	product_info->BootMinorVersion	= edge_serial->boot_descriptor.MinorVersion;
	product_info->BootBuildNumber	= edge_serial->boot_descriptor.BuildNumber;

	memcpy(product_info->ManufactureDescDate, edge_serial->manuf_descriptor.DescDate, sizeof(edge_serial->manuf_descriptor.DescDate));

	// check if this is 2nd generation hardware
	if (edge_serial->serial->dev->descriptor.idProduct & ION_DEVICE_ID_GENERATION_2) {
		product_info->FirmwareMajorVersion	= OperationalCodeImageVersion_GEN2.MajorVersion;
		product_info->FirmwareMinorVersion	= OperationalCodeImageVersion_GEN2.MinorVersion;
		product_info->FirmwareBuildNumber	= OperationalCodeImageVersion_GEN2.BuildNumber;
		product_info->iDownloadFile		= EDGE_DOWNLOAD_FILE_80251;
	} else {
		product_info->FirmwareMajorVersion	= OperationalCodeImageVersion_GEN1.MajorVersion;
		product_info->FirmwareMinorVersion	= OperationalCodeImageVersion_GEN1.MinorVersion;
		product_info->FirmwareBuildNumber	= OperationalCodeImageVersion_GEN1.BuildNumber;
		product_info->iDownloadFile		= EDGE_DOWNLOAD_FILE_I930;
	}

	// Determine Product type and set appropriate flags
	switch (DEVICE_ID_FROM_USB_PRODUCT_ID(product_info->ProductId)) {
		case ION_DEVICE_ID_EDGEPORT_COMPATIBLE:
		case ION_DEVICE_ID_EDGEPORT_4T:
		case ION_DEVICE_ID_EDGEPORT_4:
		case ION_DEVICE_ID_EDGEPORT_2:
		case ION_DEVICE_ID_EDGEPORT_8_DUAL_CPU:
		case ION_DEVICE_ID_EDGEPORT_8:
		case ION_DEVICE_ID_EDGEPORT_421:
		case ION_DEVICE_ID_EDGEPORT_21:
		case ION_DEVICE_ID_EDGEPORT_2_DIN:
		case ION_DEVICE_ID_EDGEPORT_4_DIN:
		case ION_DEVICE_ID_EDGEPORT_16_DUAL_CPU:
			product_info->IsRS232 = 1;
			break;

		case ION_DEVICE_ID_EDGEPORT_2I:				   // Edgeport/2 RS422/RS485
			product_info->IsRS422 = 1;
			product_info->IsRS485 = 1;
			break;

		case ION_DEVICE_ID_EDGEPORT_8I:				   // Edgeport/4 RS422
		case ION_DEVICE_ID_EDGEPORT_4I:				   // Edgeport/4 RS422
			product_info->IsRS422 = 1;
			break;
	}

	// Dump Product Info structure
	dbg("**Product Information:");
	dbg("  ProductId             %x", product_info->ProductId );
	dbg("  NumPorts              %d", product_info->NumPorts );
	dbg("  ProdInfoVer           %d", product_info->ProdInfoVer );
	dbg("  IsServer              %d", product_info->IsServer);
	dbg("  IsRS232               %d", product_info->IsRS232 );
	dbg("  IsRS422               %d", product_info->IsRS422 );
	dbg("  IsRS485               %d", product_info->IsRS485 );
	dbg("  RomSize               %d", product_info->RomSize );
	dbg("  RamSize               %d", product_info->RamSize );
	dbg("  CpuRev                %x", product_info->CpuRev  );
	dbg("  BoardRev              %x", product_info->BoardRev);
	dbg("  BootMajorVersion      %d.%d.%d", product_info->BootMajorVersion,
	    product_info->BootMinorVersion,
	    product_info->BootBuildNumber);
	dbg("  FirmwareMajorVersion  %d.%d.%d", product_info->FirmwareMajorVersion,
	    product_info->FirmwareMinorVersion,
	    product_info->FirmwareBuildNumber);
	dbg("  ManufactureDescDate   %d/%d/%d", product_info->ManufactureDescDate[0],
	    product_info->ManufactureDescDate[1],
	    product_info->ManufactureDescDate[2]+1900);
	dbg("  iDownloadFile         0x%x",     product_info->iDownloadFile);

}


/************************************************************************/
/************************************************************************/
/*            U S B  C A L L B A C K   F U N C T I O N S                */
/*            U S B  C A L L B A C K   F U N C T I O N S                */
/************************************************************************/
/************************************************************************/

/*****************************************************************************
 * edge_interrupt_callback
 *	this is the callback function for when we have received data on the 
 *	interrupt endpoint.
 *****************************************************************************/
static void edge_interrupt_callback (struct urb *urb)
{
	struct edgeport_serial	*edge_serial = (struct edgeport_serial *)urb->context;
	struct edgeport_port *edge_port;
	struct usb_serial_port *port;
	unsigned char *data = urb->transfer_buffer;
	int length = urb->actual_length;
	int bytes_avail;
	int position;
	int txCredits;
	int portNumber;
	int result;

	dbg(__FUNCTION__);

	if (serial_paranoia_check (edge_serial->serial, __FUNCTION__)) {
		return;
	}

	if (urb->status) {
		dbg(__FUNCTION__" - nonzero control read status received: %d", urb->status);
		return;
	}

	// process this interrupt-read even if there are no ports open
	if (length) {
Linus Torvalds's avatar
Linus Torvalds committed
776
		usb_serial_debug_data (__FILE__, __FUNCTION__, length, data);
Linus Torvalds's avatar
Linus Torvalds committed
777 778 779 780 781 782 783 784 785 786 787 788 789

		if (length > 1) {
			bytes_avail = data[0] | (data[1] << 8);
			if (bytes_avail) {
				edge_serial->rxBytesAvail += bytes_avail;
				dbg(__FUNCTION__" - bytes_avail = %d, rxBytesAvail %d", bytes_avail, edge_serial->rxBytesAvail);

				if ((edge_serial->rxBytesAvail > 0) &&
				    (edge_serial->read_urb->status != -EINPROGRESS)) {
					dbg(" --- Posting a read");

					/* we have pending bytes on the bulk in pipe, send a request */
					edge_serial->read_urb->dev = edge_serial->serial->dev;
790
					result = usb_submit_urb(edge_serial->read_urb, GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
					if (result) {
						dbg(__FUNCTION__" - usb_submit_urb(read bulk) failed with result = %d", result);
					}
				}
			}
		}
		/* grab the txcredits for the ports if available */
		position = 2;
		portNumber = 0;
		while ((position < length) && (portNumber < edge_serial->serial->num_ports)) {
			txCredits = data[position] | (data[position+1] << 8);
			if (txCredits) {
				port = &edge_serial->serial->port[portNumber];
				if (port_paranoia_check (port, __FUNCTION__) == 0) {
					edge_port = (struct edgeport_port *)port->private;
					if (edge_port->open) {
						edge_port->txCredits += txCredits;
						dbg(__FUNCTION__" - txcredits for port%d = %d", portNumber, edge_port->txCredits);

						/* tell the tty driver that something has changed */
						wake_up_interruptible(&edge_port->port->tty->write_wait);

						// Since we have more credit, check if more data can be sent
						send_more_port_data(edge_serial, edge_port);
					}
				}
			}
			position += 2;
			++portNumber;
		}
	}
}


/*****************************************************************************
 * edge_bulk_in_callback
 *	this is the callback function for when we have received data on the 
 *	bulk in endpoint.
 *****************************************************************************/
static void edge_bulk_in_callback (struct urb *urb)
{
	struct edgeport_serial	*edge_serial = (struct edgeport_serial *)urb->context;
	unsigned char		*data = urb->transfer_buffer;
	int			status;
	__u16			raw_data_length;

	dbg(__FUNCTION__);

	if (serial_paranoia_check (edge_serial->serial, __FUNCTION__)) {
		return;
	}

	if (urb->status) {
		dbg(__FUNCTION__" - nonzero read bulk status received: %d", urb->status);
		return;
	}

	if (urb->actual_length) {
		raw_data_length = urb->actual_length;

Linus Torvalds's avatar
Linus Torvalds committed
851
		usb_serial_debug_data (__FILE__, __FUNCTION__, raw_data_length, data);
Linus Torvalds's avatar
Linus Torvalds committed
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866

		/* decrement our rxBytes available by the number that we just got */
		edge_serial->rxBytesAvail -= raw_data_length;

		dbg(__FUNCTION__" - Received = %d, rxBytesAvail %d", raw_data_length, edge_serial->rxBytesAvail);

		process_rcvd_data (edge_serial, data, urb->actual_length);

		/* check to see if there's any more data for us to read */
		if ((edge_serial->rxBytesAvail > 0) &&
		    (edge_serial->read_urb->status != -EINPROGRESS)) {
			dbg(" --- Posting a read");

			/* there is, so resubmit our urb */
			edge_serial->read_urb->dev = edge_serial->serial->dev;
867
			status = usb_submit_urb(edge_serial->read_urb, GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
			if (status) {
				err(__FUNCTION__" - usb_submit_urb(read bulk) failed, status = %d", status);
			}
		}
	}
}


/*****************************************************************************
 * edge_bulk_out_data_callback
 *	this is the callback function for when we have finished sending serial data
 *	on the bulk out endpoint.
 *****************************************************************************/
static void edge_bulk_out_data_callback (struct urb *urb)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)urb->context;
	struct tty_struct *tty;

	dbg(__FUNCTION__);

	if (port_paranoia_check (edge_port->port, __FUNCTION__)) {
		return;
	}

	if (urb->status) {
		dbg(__FUNCTION__" - nonzero write bulk status received: %d", urb->status);
	}

	tty = edge_port->port->tty;

	/* let the tty driver wakeup if it has a special write_wakeup function */
	if ((tty->flags & (1 << TTY_DO_WRITE_WAKEUP)) && tty->ldisc.write_wakeup) {
		(tty->ldisc.write_wakeup)(tty);
	}

	/* tell the tty driver that something has changed */
	wake_up_interruptible(&tty->write_wait);

	// Release the Write URB
	edge_port->write_in_progress = FALSE;

	// Check if more data needs to be sent
	send_more_port_data((struct edgeport_serial *)(edge_port->port->serial->private), edge_port);
}


/*****************************************************************************
 * BulkOutCmdCallback
 *	this is the callback function for when we have finished sending a command
 *	on the bulk out endpoint.
 *****************************************************************************/
static void edge_bulk_out_cmd_callback (struct urb *urb)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)urb->context;
	struct tty_struct *tty;
	int status = urb->status;

	dbg(__FUNCTION__);

	CmdUrbs--;
	dbg(__FUNCTION__" - FREE URB %p (outstanding %d)", urb, CmdUrbs);


Linus Torvalds's avatar
Linus Torvalds committed
931
	/* clean up the transfer buffer */
Linus Torvalds's avatar
Linus Torvalds committed
932 933 934 935 936 937 938 939 940 941 942 943 944
	if (urb->transfer_buffer != NULL) {
		kfree(urb->transfer_buffer);
	}

	// Free the command urb
	usb_unlink_urb (urb);
	usb_free_urb   (urb);

	if (port_paranoia_check (edge_port->port, __FUNCTION__)) {
		return;
	}

	if (status) {
Linus Torvalds's avatar
Linus Torvalds committed
945
		dbg(__FUNCTION__" - nonzero write bulk status received: %d", status);
Linus Torvalds's avatar
Linus Torvalds committed
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
		return;
	}

	/* Get pointer to tty */
	tty = edge_port->port->tty;

	/* tell the tty driver that something has changed */
	wake_up_interruptible(&tty->write_wait);

	/* we have completed the command */
	edge_port->commandPending = FALSE;
	wake_up_interruptible(&edge_port->wait_command);
}


/*****************************************************************************
 * Driver tty interface functions
 *****************************************************************************/

/*****************************************************************************
 * SerialOpen
 *	this function is called by the tty driver when a port is opened
 *	If successful, we return 0
 *	Otherwise we return a negative error number.
 *****************************************************************************/
static int edge_open (struct usb_serial_port *port, struct file * filp)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)port->private;
	struct usb_serial *serial;
	struct edgeport_serial *edge_serial;
	int response;
	int timeout;

	if (port_paranoia_check (port, __FUNCTION__))
		return -ENODEV;
	
	dbg(__FUNCTION__ " - port %d", port->number);

Linus Torvalds's avatar
Linus Torvalds committed
984 985 986
	if (edge_port == NULL)
		return -ENODEV;

Linus Torvalds's avatar
Linus Torvalds committed
987 988
	++port->open_count;
	
Linus Torvalds's avatar
Linus Torvalds committed
989
	if (port->open_count == 1) {
Linus Torvalds's avatar
Linus Torvalds committed
990 991 992 993 994 995 996 997 998
		/* force low_latency on so that our tty_push actually forces the data through, 
		   otherwise it is scheduled, and with high data rates (like with OHCI) data
		   can get lost. */
		port->tty->low_latency = 1;
	
		/* see if we've set up our endpoint info yet (can't set it up in edge_startup
		   as the structures were not set up at that time.) */
		serial = port->serial;
		edge_serial = (struct edgeport_serial *)serial->private;
Linus Torvalds's avatar
Linus Torvalds committed
999 1000 1001 1002
		if (edge_serial == NULL) {
			port->open_count = 0;
			return -ENODEV;
		}
Linus Torvalds's avatar
Linus Torvalds committed
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
		if (edge_serial->interrupt_in_buffer == NULL) {
			struct usb_serial_port *port0 = &serial->port[0];
			
			/* not set up yet, so do it now */
			edge_serial->interrupt_in_buffer = port0->interrupt_in_buffer;
			edge_serial->interrupt_in_endpoint = port0->interrupt_in_endpointAddress;
			edge_serial->interrupt_read_urb = port0->interrupt_in_urb;
			edge_serial->bulk_in_buffer = port0->bulk_in_buffer;
			edge_serial->bulk_in_endpoint = port0->bulk_in_endpointAddress;
			edge_serial->read_urb = port0->read_urb;
			edge_serial->bulk_out_endpoint = port0->bulk_out_endpointAddress;
		
			/* set up our interrupt urb */
Linus Torvalds's avatar
Linus Torvalds committed
1016 1017 1018 1019 1020 1021 1022 1023
			FILL_INT_URB(edge_serial->interrupt_read_urb,
				     serial->dev,
				     usb_rcvintpipe(serial->dev,
					            port0->interrupt_in_endpointAddress),
				     port0->interrupt_in_buffer,
				     edge_serial->interrupt_read_urb->transfer_buffer_length,
				     edge_interrupt_callback, edge_serial,
				     edge_serial->interrupt_read_urb->interval);
Linus Torvalds's avatar
Linus Torvalds committed
1024 1025
			
			/* set up our bulk in urb */
Linus Torvalds's avatar
Linus Torvalds committed
1026 1027 1028 1029
			FILL_BULK_URB(edge_serial->read_urb, serial->dev,
				      usb_rcvbulkpipe(serial->dev, port0->bulk_in_endpointAddress),
				      port0->bulk_in_buffer,
				      edge_serial->read_urb->transfer_buffer_length,
Linus Torvalds's avatar
Linus Torvalds committed
1030
				      edge_bulk_in_callback, edge_serial);
Linus Torvalds's avatar
Linus Torvalds committed
1031

Linus Torvalds's avatar
Linus Torvalds committed
1032 1033
			/* start interrupt read for this edgeport
			 * this interrupt will continue as long as the edgeport is connected */
1034
			response = usb_submit_urb (edge_serial->interrupt_read_urb, GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
			if (response) {
				err(__FUNCTION__" - Error %d submitting control urb", response);
			}
		}
		
		/* initialize our wait queues */
		init_waitqueue_head(&edge_port->wait_open);
		init_waitqueue_head(&edge_port->wait_chase);
		init_waitqueue_head(&edge_port->delta_msr_wait);
		init_waitqueue_head(&edge_port->wait_command);

		/* initialize our icount structure */
		memset (&(edge_port->icount), 0x00, sizeof(edge_port->icount));

		/* initialize our port settings */
		edge_port->txCredits            = 0;			/* Can't send any data yet */
		edge_port->shadowMCR            = MCR_MASTER_IE;	/* Must always set this bit to enable ints! */
		edge_port->chaseResponsePending = FALSE;

		/* send a open port command */
		edge_port->openPending = TRUE;
		edge_port->open        = FALSE;
		response = send_iosp_ext_cmd (edge_port, IOSP_CMD_OPEN_PORT, 0);

		if (response < 0) {
			err(__FUNCTION__" - error sending open port command");
			edge_port->openPending = FALSE;
			port->open_count = 0;
			return -ENODEV;
		}

		/* now wait for the port to be completly opened */
		timeout = OPEN_TIMEOUT;
		while (timeout && edge_port->openPending == TRUE) {
			timeout = interruptible_sleep_on_timeout (&edge_port->wait_open, timeout);
		}

		if (edge_port->open == FALSE) {
			/* open timed out */
			dbg(__FUNCTION__" - open timedout");
			edge_port->openPending = FALSE;
			port->open_count = 0;
			return -ENODEV;
		}

		/* create the txfifo */
		edge_port->txfifo.head	= 0;
		edge_port->txfifo.tail	= 0;
		edge_port->txfifo.count	= 0;
		edge_port->txfifo.size	= edge_port->maxTxCredits;
		edge_port->txfifo.fifo	= kmalloc (edge_port->maxTxCredits, GFP_KERNEL);

		if (!edge_port->txfifo.fifo) {
			dbg(__FUNCTION__" - no memory");
			edge_close (port, filp);
			return -ENOMEM;
		}

		/* Allocate a URB for the write */
		edge_port->write_urb = usb_alloc_urb (0);

		if (!edge_port->write_urb) {
			dbg(__FUNCTION__" - no memory");
			edge_close (port, filp);
			return -ENOMEM;
		}

		dbg(__FUNCTION__"(%d) - Initialize TX fifo to %d bytes", port->number, edge_port->maxTxCredits);
	}

	dbg(__FUNCTION__" exited");

	return 0;
}


/************************************************************************
 *
 * block_until_chase_response
 *
 *	This function will block the close until one of the following:
 *		1. Response to our Chase comes from Edgeport
 *		2. A timout of 10 seconds without activity has expired
 *		   (1K of Edgeport data @ 2400 baud ==> 4 sec to empty)
 *
 ************************************************************************/
static void block_until_chase_response(struct edgeport_port *edge_port)
{
	__u16 lastCredits;
	int timeout = 1*HZ;
	int wait = 10;

	while (1) {
		// Save Last credits
		lastCredits = edge_port->txCredits;

		// Did we get our Chase response
		if (edge_port->chaseResponsePending == FALSE) {
			dbg(__FUNCTION__" - Got Chase Response");

			// did we get all of our credit back?
			if (edge_port->txCredits == edge_port->maxTxCredits ) {
				dbg(__FUNCTION__" - Got all credits");
				return;
			}
		}

		// Block the thread for a while
		interruptible_sleep_on_timeout (&edge_port->wait_chase, timeout);

		if (lastCredits == edge_port->txCredits) {
			// No activity.. count down.
			wait--;
			if (wait == 0) {
				edge_port->chaseResponsePending = FALSE;
				dbg(__FUNCTION__" - Chase TIMEOUT");
				return;
			}
		} else {
			// Reset timout value back to 10 seconds
			dbg(__FUNCTION__" - Last %d, Current %d", lastCredits, edge_port->txCredits);
			wait = 10;
		}
	}
}


/************************************************************************
 *
 * block_until_tx_empty
 *
 *	This function will block the close until one of the following:
 *		1. TX count are 0
 *		2. The edgeport has stopped
 *		3. A timout of 3 seconds without activity has expired
 *
 ************************************************************************/
static void block_until_tx_empty (struct edgeport_port *edge_port)
{
	struct TxFifo *fifo = &edge_port->txfifo;
	__u32 lastCount;
	int timeout = HZ/10;
	int wait = 30;

	while (1) {
		// Save Last count
		lastCount = fifo->count;

		// Is the Edgeport Buffer empty?
		if (lastCount == 0) {
			dbg(__FUNCTION__" - TX Buffer Empty");
			return;
		}

		// Block the thread for a while
		interruptible_sleep_on_timeout (&edge_port->wait_chase, timeout);

		dbg(__FUNCTION__ " wait");

		if (lastCount == fifo->count) {
			// No activity.. count down.
			wait--;
			if (wait == 0) {
				dbg(__FUNCTION__" - TIMEOUT");
				return;
			}
		} else {
			// Reset timout value back to seconds
			wait = 30;
		}
	}
}


/*****************************************************************************
 * edge_close
 *	this function is called by the tty driver when a port is closed
 *****************************************************************************/
static void edge_close (struct usb_serial_port *port, struct file * filp)
{
	struct usb_serial *serial;
	struct edgeport_serial *edge_serial;
	struct edgeport_port *edge_port;
	int status;

	if (port_paranoia_check (port, __FUNCTION__))
		return;
	
	dbg(__FUNCTION__ " - port %d", port->number);
			 
	serial = get_usb_serial (port, __FUNCTION__);
	if (!serial)
		return;
	
	edge_serial = (struct edgeport_serial *)serial->private;
	edge_port = (struct edgeport_port *)port->private;
Linus Torvalds's avatar
Linus Torvalds committed
1231 1232 1233
	if ((edge_serial == NULL) || (edge_port == NULL))
		return;
	
Linus Torvalds's avatar
Linus Torvalds committed
1234 1235 1236
	--port->open_count;

	if (port->open_count <= 0) {
Linus Torvalds's avatar
Linus Torvalds committed
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
		if (serial->dev) {
			// block until tx is empty
			block_until_tx_empty(edge_port);

			edge_port->closePending = TRUE;

			/* flush and chase */
			edge_port->chaseResponsePending = TRUE;

			dbg(__FUNCTION__" - Sending IOSP_CMD_CHASE_PORT");
			status = send_iosp_ext_cmd (edge_port, IOSP_CMD_CHASE_PORT, 0);
			if (status == 0) {
				// block until chase finished
				block_until_chase_response(edge_port);
			} else {
				edge_port->chaseResponsePending = FALSE;
			}

			/* close the port */
			dbg(__FUNCTION__" - Sending IOSP_CMD_CLOSE_PORT");
			send_iosp_ext_cmd (edge_port, IOSP_CMD_CLOSE_PORT, 0);

			//port->close = TRUE;
			edge_port->closePending = FALSE;
			edge_port->open = FALSE;
			edge_port->openPending = FALSE;

			if (edge_port->write_urb) {
				usb_unlink_urb (edge_port->write_urb);
			}
Linus Torvalds's avatar
Linus Torvalds committed
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
		}
	
		if (edge_port->write_urb) {
			/* if this urb had a transfer buffer already (old transfer) free it */
			if (edge_port->write_urb->transfer_buffer != NULL) {
				kfree(edge_port->write_urb->transfer_buffer);
			}
			usb_free_urb   (edge_port->write_urb);
		}
		if (edge_port->txfifo.fifo) {
			kfree(edge_port->txfifo.fifo);
		}
Linus Torvalds's avatar
Linus Torvalds committed
1279
		port->open_count = 0;
Linus Torvalds's avatar
Linus Torvalds committed
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
	}

	dbg(__FUNCTION__" exited");
}   

/*****************************************************************************
 * SerialWrite
 *	this function is called by the tty driver when data should be written to
 *	the port.
 *	If successful, we return the number of bytes written, otherwise we return
 *	a negative error number.
 *****************************************************************************/
static int edge_write (struct usb_serial_port *port, int from_user, const unsigned char *data, int count)
{
        struct edgeport_port *edge_port = (struct edgeport_port *)port->private;
	struct TxFifo *fifo;
	int copySize;
	int bytesleft;
	int firsthalf;
	int secondhalf;

	dbg(__FUNCTION__ " - port %d", port->number);

Linus Torvalds's avatar
Linus Torvalds committed
1303 1304 1305
	if (edge_port == NULL)
		return -ENODEV;

Linus Torvalds's avatar
Linus Torvalds committed
1306 1307 1308 1309
	// get a pointer to the Tx fifo
	fifo = &edge_port->txfifo;

	// calculate number of bytes to put in fifo
Linus Torvalds's avatar
Linus Torvalds committed
1310
	copySize = min ((unsigned int)count, (edge_port->txCredits - fifo->count));
Linus Torvalds's avatar
Linus Torvalds committed
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327

	dbg(__FUNCTION__"(%d) of %d byte(s) Fifo room  %d -- will copy %d bytes", 
	    port->number, count, edge_port->txCredits - fifo->count, copySize);

	/* catch writes of 0 bytes which the tty driver likes to give us, and when txCredits is empty */
	if (copySize == 0) {
		dbg (__FUNCTION__" - copySize = Zero");
		return 0;
	}

	// queue the data	
	// since we can never overflow the buffer we do not have to check for full condition

	// the copy is done is two parts -- first fill to the end of the buffer
	// then copy the reset from the start of the buffer 

	bytesleft = fifo->size - fifo->head;
Linus Torvalds's avatar
Linus Torvalds committed
1328
	firsthalf = min (bytesleft, copySize);
Linus Torvalds's avatar
Linus Torvalds committed
1329 1330 1331 1332
	dbg (__FUNCTION__" - copy %d bytes of %d into fifo ", firsthalf, bytesleft);

	/* now copy our data */
	if (from_user) {
Linus Torvalds's avatar
Linus Torvalds committed
1333 1334
		if (copy_from_user(&fifo->fifo[fifo->head], data, firsthalf))
			return -EFAULT;
Linus Torvalds's avatar
Linus Torvalds committed
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
	} else {
		memcpy(&fifo->fifo[fifo->head], data, firsthalf);
	}  

	// update the index and size
	fifo->head  += firsthalf;
	fifo->count += firsthalf;

	// wrap the index
	if (fifo->head == fifo->size) {
		fifo->head = 0;
	}

	secondhalf = copySize-firsthalf;

	if (secondhalf) {
		dbg (__FUNCTION__" - copy rest of data %d", secondhalf);
		if (from_user) {
Linus Torvalds's avatar
Linus Torvalds committed
1353 1354
			if (copy_from_user(&fifo->fifo[fifo->head], &data[firsthalf], secondhalf))
				return -EFAULT;
Linus Torvalds's avatar
Linus Torvalds committed
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
		} else {
			memcpy(&fifo->fifo[fifo->head], &data[firsthalf], secondhalf);
		}
		// update the index and size
		fifo->count += secondhalf;
		fifo->head  += secondhalf;
		// No need to check for wrap since we can not get to end of fifo in this part
	}

	if (copySize) {
Linus Torvalds's avatar
Linus Torvalds committed
1365
		usb_serial_debug_data (__FILE__, __FUNCTION__, copySize, data);
Linus Torvalds's avatar
Linus Torvalds committed
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
	}

	send_more_port_data((struct edgeport_serial *)port->serial->private, edge_port);

	dbg(__FUNCTION__" wrote %d byte(s) TxCredits %d, Fifo %d", copySize, edge_port->txCredits, fifo->count);

	return copySize;   
}


/************************************************************************
 *
 * send_more_port_data()
 *
 *	This routine attempts to write additional UART transmit data
 *	to a port over the USB bulk pipe. It is called (1) when new
 *	data has been written to a port's TxBuffer from higher layers
 *	(2) when the peripheral sends us additional TxCredits indicating
 *	that it can accept more	Tx data for a given port; and (3) when
 *	a bulk write completes successfully and we want to see if we
 *	can transmit more.
 *
 ************************************************************************/
static void send_more_port_data(struct edgeport_serial *edge_serial, struct edgeport_port *edge_port)
{
	struct TxFifo	*fifo = &edge_port->txfifo;
	struct urb	*urb;
	unsigned char	*buffer;
	int		status;
	int		count;
	int		bytesleft;
	int		firsthalf;
	int		secondhalf;

	dbg(__FUNCTION__"(%d)", edge_port->port->number);

	if (edge_port->write_in_progress ||
	    !edge_port->open             ||
	    (fifo->count == 0)) {
		dbg(__FUNCTION__"(%d) EXIT - fifo %d, PendingWrite = %d", edge_port->port->number, fifo->count, edge_port->write_in_progress);
		return;
	}

	// since the amount of data in the fifo will always fit into the
	// edgeport buffer we do not need to check the write length

	//	Do we have enough credits for this port to make it worthwhile
	//	to bother queueing a write. If it's too small, say a few bytes,
	//	it's better to wait for more credits so we can do a larger
	//	write.
	if (edge_port->txCredits < EDGE_FW_GET_TX_CREDITS_SEND_THRESHOLD(edge_port->maxTxCredits)) {
		dbg(__FUNCTION__"(%d) Not enough credit - fifo %d TxCredit %d", edge_port->port->number, fifo->count, edge_port->txCredits );
		return;
	}

	// lock this write
	edge_port->write_in_progress = TRUE;

	// get a pointer to the write_urb
	urb = edge_port->write_urb;

	/* if this urb had a transfer buffer already (old transfer) free it */
	if (urb->transfer_buffer != NULL) {
		kfree(urb->transfer_buffer);
		urb->transfer_buffer = NULL;
	}

	/* build the data header for the buffer and port that we are about to send out */
	count = fifo->count;
	buffer = kmalloc (count+2, GFP_KERNEL);
	if (buffer == NULL) {
		err(__FUNCTION__" - no more kernel memory...");
		edge_port->write_in_progress = FALSE;
		return;
	}
	buffer[0] = IOSP_BUILD_DATA_HDR1 (edge_port->port->number, count);
	buffer[1] = IOSP_BUILD_DATA_HDR2 (edge_port->port->number, count);

	/* now copy our data */
	bytesleft =  fifo->size - fifo->tail;
Linus Torvalds's avatar
Linus Torvalds committed
1446
	firsthalf = min (bytesleft, count);
Linus Torvalds's avatar
Linus Torvalds committed
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
	memcpy(&buffer[2], &fifo->fifo[fifo->tail], firsthalf);
	fifo->tail  += firsthalf;
	fifo->count -= firsthalf;
	if (fifo->tail == fifo->size) {
		fifo->tail = 0;
	}

	secondhalf = count-firsthalf;
	if (secondhalf) {
		memcpy(&buffer[2+firsthalf], &fifo->fifo[fifo->tail], secondhalf);
		fifo->tail  += secondhalf;
		fifo->count -= secondhalf;
	}

	if (count) {
Linus Torvalds's avatar
Linus Torvalds committed
1462
		usb_serial_debug_data (__FILE__, __FUNCTION__, count, &buffer[2]);
Linus Torvalds's avatar
Linus Torvalds committed
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
	}

	/* fill up the urb with all of our data and submit it */
	FILL_BULK_URB (urb, edge_serial->serial->dev, 
		       usb_sndbulkpipe(edge_serial->serial->dev, edge_serial->bulk_out_endpoint),
		       buffer, count+2, edge_bulk_out_data_callback, edge_port);

	/* set the USB_BULK_QUEUE flag so that we can shove a bunch of urbs at once down the pipe */
	urb->transfer_flags |= USB_QUEUE_BULK;

	urb->dev = edge_serial->serial->dev;
1474
	status = usb_submit_urb(urb, GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
	if (status) {
		/* something went wrong */
		dbg(__FUNCTION__" - usb_submit_urb(write bulk) failed");
		edge_port->write_in_progress = FALSE;
	} else {
		/* decrement the number of credits we have by the number we just sent */
		edge_port->txCredits -= count;
		edge_port->icount.tx += count;
	}
	dbg(__FUNCTION__" wrote %d byte(s) TxCredit %d, Fifo %d", count, edge_port->txCredits, fifo->count);
}


/*****************************************************************************
 * edge_write_room
 *	this function is called by the tty driver when it wants to know how many
 *	bytes of data we can accept for a specific port.
 *	If successful, we return the amount of room that we have for this port
 *	(the txCredits), 
 *	Otherwise we return a negative error number.
 *****************************************************************************/
static int edge_write_room (struct usb_serial_port *port)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)(port->private);
	int room;

	dbg(__FUNCTION__);

Linus Torvalds's avatar
Linus Torvalds committed
1503 1504 1505
	if (edge_port == NULL)
		return -ENODEV;
	if (edge_port->closePending == TRUE)
Linus Torvalds's avatar
Linus Torvalds committed
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
		return -ENODEV;

	dbg(__FUNCTION__" - port %d", port->number);

	if (!edge_port->open) {
		dbg (__FUNCTION__" - port not opened");
		return -EINVAL;
	}

	// total of both buffers is still txCredit
	room = edge_port->txCredits - edge_port->txfifo.count;

	dbg(__FUNCTION__" - returns %d", room);
	return room;
}


/*****************************************************************************
 * edge_chars_in_buffer
 *	this function is called by the tty driver when it wants to know how many
 *	bytes of data we currently have outstanding in the port (data that has
 *	been written, but hasn't made it out the port yet)
 *	If successful, we return the number of bytes left to be written in the 
 *	system, 
 *	Otherwise we return a negative error number.
 *****************************************************************************/
static int edge_chars_in_buffer (struct usb_serial_port *port)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)(port->private);
	int num_chars;

	dbg(__FUNCTION__);

Linus Torvalds's avatar
Linus Torvalds committed
1539 1540 1541 1542 1543
	if (edge_port == NULL)
		return -ENODEV;
	if (edge_port->closePending == TRUE)
		return -ENODEV;

Linus Torvalds's avatar
Linus Torvalds committed
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
	if (!edge_port->open) {
		dbg (__FUNCTION__" - port not opened");
		return -EINVAL;
	}

	num_chars = edge_port->maxTxCredits - edge_port->txCredits + edge_port->txfifo.count;
	if (num_chars) {
		dbg(__FUNCTION__"(port %d) - returns %d", port->number, num_chars);
	}

	return num_chars;
}


/*****************************************************************************
 * SerialThrottle
 *	this function is called by the tty driver when it wants to stop the data
 *	being read from the port.
 *****************************************************************************/
static void edge_throttle (struct usb_serial_port *port)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)(port->private);
	struct tty_struct *tty;
	int status;

	dbg(__FUNCTION__" - port %d", port->number);

Linus Torvalds's avatar
Linus Torvalds committed
1571 1572 1573
	if (edge_port == NULL)
		return;

Linus Torvalds's avatar
Linus Torvalds committed
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
	if (!edge_port->open) {
		dbg (__FUNCTION__" - port not opened");
		return;
	}

	tty = port->tty;

	/* if we are implementing XON/XOFF, send the stop character */
	if (I_IXOFF(tty)) {
		unsigned char stop_char = STOP_CHAR(tty);
		status = edge_write (port, 0, &stop_char, 1);
		if (status <= 0) {
			return;
		}
	}

	/* if we are implementing RTS/CTS, toggle that line */
	if (tty->termios->c_cflag & CRTSCTS) {
		edge_port->shadowMCR &= ~MCR_RTS;
		status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR);
		if (status != 0) {
			return;
		}
	}

	return;
}


/*****************************************************************************
 * edge_unthrottle
 *	this function is called by the tty driver when it wants to resume the data
 *	being read from the port (called after SerialThrottle is called)
 *****************************************************************************/
static void edge_unthrottle (struct usb_serial_port *port)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)(port->private);
	struct tty_struct *tty;
	int status;

	dbg(__FUNCTION__" - port %d", port->number);

Linus Torvalds's avatar
Linus Torvalds committed
1616 1617 1618
	if (edge_port == NULL)
		return;

Linus Torvalds's avatar
Linus Torvalds committed
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
	if (!edge_port->open) {
		dbg (__FUNCTION__" - port not opened");
		return;
	}

	tty = port->tty;

	/* if we are implementing XON/XOFF, send the start character */
	if (I_IXOFF(tty)) {
		unsigned char start_char = START_CHAR(tty);
		status = edge_write (port, 0, &start_char, 1);
		if (status <= 0) {
			return;
		}
	}

	/* if we are implementing RTS/CTS, toggle that line */
	if (tty->termios->c_cflag & CRTSCTS) {
		edge_port->shadowMCR |= MCR_RTS;
		status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR);
		if (status != 0) {
			return;
		}
	}

	return;
}


/*****************************************************************************
 * SerialSetTermios
 *	this function is called by the tty driver when it wants to change the termios structure
 *****************************************************************************/
static void edge_set_termios (struct usb_serial_port *port, struct termios *old_termios)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)(port->private);
	struct tty_struct *tty = port->tty;
	unsigned int cflag = tty->termios->c_cflag;

	dbg(__FUNCTION__" - clfag %08x %08x iflag %08x %08x", 
	    tty->termios->c_cflag,
	    old_termios->c_cflag,
	    RELEVANT_IFLAG(tty->termios->c_iflag),
	    RELEVANT_IFLAG(old_termios->c_iflag)
	   );

	/* check that they really want us to change something */
	if (old_termios) {
		if ((cflag == old_termios->c_cflag) &&
		    (RELEVANT_IFLAG(tty->termios->c_iflag) == RELEVANT_IFLAG(old_termios->c_iflag))) {
			dbg(__FUNCTION__" - nothing to change");
			return;
		}
	}

	dbg(__FUNCTION__" - port %d", port->number);

Linus Torvalds's avatar
Linus Torvalds committed
1676 1677 1678
	if (edge_port == NULL)
		return;

Linus Torvalds's avatar
Linus Torvalds committed
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
	if (!edge_port->open) {
		dbg (__FUNCTION__" - port not opened");
		return;
	}

	/* change the port settings to the new ones specified */
	change_port_settings (edge_port, old_termios);

	return;
}


/*****************************************************************************
 * get_lsr_info - get line status register info
 *
 * Purpose: Let user call ioctl() to get info when the UART physically
 * 	    is emptied.  On bus types like RS485, the transmitter must
 * 	    release the bus after transmitting. This must be done when
 * 	    the transmit shift register is empty, not be done when the
 * 	    transmit holding register is empty.  This functionality
 * 	    allows an RS485 driver to be written in user space. 
 *****************************************************************************/
static int get_lsr_info(struct edgeport_port *edge_port, unsigned int *value)
{
	unsigned int result = 0;

	if (edge_port->maxTxCredits == edge_port->txCredits &&
	    edge_port->txfifo.count == 0) {
		dbg(__FUNCTION__" -- Empty");
		result = TIOCSER_TEMT;
	}

	if (copy_to_user(value, &result, sizeof(int)))
		return -EFAULT;
	return 0;
}

static int get_number_bytes_avail(struct edgeport_port *edge_port, unsigned int *value)
{
	unsigned int result = 0;
	struct tty_struct *tty = edge_port->port->tty;

	result = tty->read_cnt;

	dbg(__FUNCTION__"(%d) = %d",  edge_port->port->number, result);
	if (copy_to_user(value, &result, sizeof(int)))
		return -EFAULT;
	//return 0;
	return -ENOIOCTLCMD;
}

Linus Torvalds's avatar
Linus Torvalds committed
1730
static int set_modem_info(struct edgeport_port *edge_port, unsigned int cmd, unsigned int *value)
Linus Torvalds's avatar
Linus Torvalds committed
1731 1732 1733 1734 1735 1736 1737
{
	unsigned int mcr = edge_port->shadowMCR;
	unsigned int arg;

	if (copy_from_user(&arg, value, sizeof(int)))
		return -EFAULT;

Linus Torvalds's avatar
Linus Torvalds committed
1738 1739 1740 1741 1742 1743 1744 1745 1746
	switch (cmd) {
		case TIOCMBIS:
			if (arg & TIOCM_RTS)
				mcr |= MCR_RTS;
			if (arg & TIOCM_DTR)
				mcr |= MCR_RTS;
			if (arg & TIOCM_LOOP)
				mcr |= MCR_LOOPBACK;
			break;
Linus Torvalds's avatar
Linus Torvalds committed
1747

Linus Torvalds's avatar
Linus Torvalds committed
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
		case TIOCMBIC:
			if (arg & TIOCM_RTS)
				mcr &= ~MCR_RTS;
			if (arg & TIOCM_DTR)
				mcr &= ~MCR_RTS;
			if (arg & TIOCM_LOOP)
				mcr &= ~MCR_LOOPBACK;
			break;

		case TIOCMSET:
			/* turn off the RTS and DTR and LOOPBACK 
			 * and then only turn on what was asked to */
			mcr &=  ~(MCR_RTS | MCR_DTR | MCR_LOOPBACK);
			mcr |= ((arg & TIOCM_RTS) ? MCR_RTS : 0);
			mcr |= ((arg & TIOCM_DTR) ? MCR_DTR : 0);
			mcr |= ((arg & TIOCM_LOOP) ? MCR_LOOPBACK : 0);
			break;
	}
Linus Torvalds's avatar
Linus Torvalds committed
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852

	edge_port->shadowMCR = mcr;

	send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR);

	return 0;
}

static int get_modem_info(struct edgeport_port *edge_port, unsigned int *value)
{
	unsigned int result = 0;
	unsigned int msr = edge_port->shadowMSR;
	unsigned int mcr = edge_port->shadowMCR;

	result = ((mcr & MCR_DTR)	? TIOCM_DTR: 0)	  /* 0x002 */
		  | ((mcr & MCR_RTS)	? TIOCM_RTS: 0)   /* 0x004 */
		  | ((msr & MSR_CTS)	? TIOCM_CTS: 0)   /* 0x020 */
		  | ((msr & MSR_CD)	? TIOCM_CAR: 0)   /* 0x040 */
		  | ((msr & MSR_RI)	? TIOCM_RI:  0)   /* 0x080 */
		  | ((msr & MSR_DSR)	? TIOCM_DSR: 0);  /* 0x100 */


	dbg(__FUNCTION__" -- %x", result);

	if (copy_to_user(value, &result, sizeof(int)))
		return -EFAULT;
	return 0;
}



static int get_serial_info(struct edgeport_port *edge_port, struct serial_struct * retinfo)
{
	struct serial_struct tmp;

	if (!retinfo)
		return -EFAULT;

	memset(&tmp, 0, sizeof(tmp));

	tmp.type		= PORT_16550A;
	tmp.line		= edge_port->port->serial->minor;
	tmp.port		= edge_port->port->number;
	tmp.irq			= 0;
	tmp.flags		= ASYNC_SKIP_TEST | ASYNC_AUTO_IRQ;
	tmp.xmit_fifo_size	= edge_port->maxTxCredits;
	tmp.baud_base		= 9600;
	tmp.close_delay		= 5*HZ;
	tmp.closing_wait	= 30*HZ;
//	tmp.custom_divisor	= state->custom_divisor;
//	tmp.hub6		= state->hub6;
//	tmp.io_type		= state->io_type;


	if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
		return -EFAULT;
	return 0;
}



/*****************************************************************************
 * SerialIoctl
 *	this function handles any ioctl calls to the driver
 *****************************************************************************/
static int edge_ioctl (struct usb_serial_port *port, struct file *file, unsigned int cmd, unsigned long arg)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)(port->private);
	struct async_icount cnow;
	struct async_icount cprev;
	struct serial_icounter_struct icount;


	dbg(__FUNCTION__" - port %d, cmd = 0x%x", port->number, cmd);

	switch (cmd) {
		// return number of bytes available
		case TIOCINQ:
			dbg(__FUNCTION__" (%d) TIOCINQ",  port->number);
			return get_number_bytes_avail(edge_port, (unsigned int *) arg);
			break;

		case TIOCSERGETLSR:
			dbg(__FUNCTION__" (%d) TIOCSERGETLSR",  port->number);
			return get_lsr_info(edge_port, (unsigned int *) arg);
			return 0;

Linus Torvalds's avatar
Linus Torvalds committed
1853 1854 1855 1856 1857
		case TIOCMBIS:
		case TIOCMBIC:
		case TIOCMSET:
			dbg(__FUNCTION__" (%d) TIOCMSET/TIOCMBIC/TIOCMSET",  port->number);
			return set_modem_info(edge_port, cmd, (unsigned int *) arg);
Linus Torvalds's avatar
Linus Torvalds committed
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

		case TIOCMGET:  
			dbg(__FUNCTION__" (%d) TIOCMGET",  port->number);
			return get_modem_info(edge_port, (unsigned int *) arg);

		case TIOCGSERIAL:
			dbg(__FUNCTION__" (%d) TIOCGSERIAL",  port->number);
			return get_serial_info(edge_port, (struct serial_struct *) arg);

		case TIOCSSERIAL:
			dbg(__FUNCTION__" (%d) TIOCSSERIAL",  port->number);
			break;

		case TIOCMIWAIT:
			dbg(__FUNCTION__" (%d) TIOCMIWAIT",  port->number);
			cprev = edge_port->icount;
			while (1) {
				interruptible_sleep_on(&edge_port->delta_msr_wait);
				/* see if a signal did it */
				if (signal_pending(current))
					return -ERESTARTSYS;
Linus Torvalds's avatar
Linus Torvalds committed
1879
				cnow = edge_port->icount;
Linus Torvalds's avatar
Linus Torvalds committed
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
				if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
				    cnow.dcd == cprev.dcd && cnow.cts == cprev.cts)
					return -EIO; /* no change => error */
				if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
				    ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
				    ((arg & TIOCM_CD)  && (cnow.dcd != cprev.dcd)) ||
				    ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts)) ) {
					return 0;
				}
				cprev = cnow;
			}
			/* NOTREACHED */
			break;

		case TIOCGICOUNT:
			cnow = edge_port->icount;
			icount.cts = cnow.cts;
			icount.dsr = cnow.dsr;
			icount.rng = cnow.rng;
			icount.dcd = cnow.dcd;
			icount.rx = cnow.rx;
			icount.tx = cnow.tx;
			icount.frame = cnow.frame;
			icount.overrun = cnow.overrun;
			icount.parity = cnow.parity;
			icount.brk = cnow.brk;
			icount.buf_overrun = cnow.buf_overrun;

			dbg(__FUNCTION__" (%d) TIOCGICOUNT RX=%d, TX=%d",  port->number, icount.rx, icount.tx );
			if (copy_to_user((void *)arg, &icount, sizeof(icount)))
				return -EFAULT;
			return 0;
	}

	return -ENOIOCTLCMD;
}


/*****************************************************************************
 * SerialBreak
 *	this function sends a break to the port
 *****************************************************************************/
static void edge_break (struct usb_serial_port *port, int break_state)
{
	struct edgeport_port *edge_port = (struct edgeport_port *)(port->private);
	int status;

	/* flush and chase */
	edge_port->chaseResponsePending = TRUE;

	dbg(__FUNCTION__" - Sending IOSP_CMD_CHASE_PORT");
	status = send_iosp_ext_cmd (edge_port, IOSP_CMD_CHASE_PORT, 0);
	if (status == 0) {
		// block until chase finished
		block_until_chase_response(edge_port);
	} else {
		edge_port->chaseResponsePending = FALSE;
	}

	if (break_state == -1) {
		dbg(__FUNCTION__" - Sending IOSP_CMD_SET_BREAK");
		status = send_iosp_ext_cmd (edge_port, IOSP_CMD_SET_BREAK, 0);
	} else {
		dbg(__FUNCTION__" - Sending IOSP_CMD_CLEAR_BREAK");
		status = send_iosp_ext_cmd (edge_port, IOSP_CMD_CLEAR_BREAK, 0);
	}
	if (status) {
		dbg(__FUNCTION__" - error sending break set/clear command.");
	}

	return;
}


/*****************************************************************************
 * process_rcvd_data
 *	this function handles the data received on the bulk in pipe.
 *****************************************************************************/
static int process_rcvd_data (struct edgeport_serial *edge_serial, unsigned char * buffer, __u16 bufferLength)
{
	struct usb_serial_port *port;
	struct edgeport_port *edge_port;
	struct tty_struct *tty;
	__u16 lastBufferLength;
	__u16 rxLen;
	int i;

	dbg(__FUNCTION__);

	lastBufferLength = bufferLength + 1;

	while (bufferLength > 0) {
		/* failsafe incase we get a message that we don't understand */
		if (lastBufferLength == bufferLength) {
			dbg(__FUNCTION__" - stuck in loop, exiting it.");
			break;
		}
		lastBufferLength = bufferLength;

		switch (edge_serial->rxState) {
			case EXPECT_HDR1:
				edge_serial->rxHeader1 = *buffer;
				++buffer;
				--bufferLength;

				if (bufferLength == 0) {
					edge_serial->rxState = EXPECT_HDR2;
					break;
				}
				/* otherwise, drop on through */

			case EXPECT_HDR2:
				edge_serial->rxHeader2 = *buffer;
				++buffer;
				--bufferLength;

				dbg(__FUNCTION__" - Hdr1=%02X Hdr2=%02X", edge_serial->rxHeader1, edge_serial->rxHeader2);

				// Process depending on whether this header is
				// data or status

				if (IS_CMD_STAT_HDR(edge_serial->rxHeader1)) {
					// Decode this status header and goto EXPECT_HDR1 (if we
					// can process the status with only 2 bytes), or goto
					// EXPECT_HDR3 to get the third byte.

					edge_serial->rxPort       = IOSP_GET_HDR_PORT(edge_serial->rxHeader1);
					edge_serial->rxStatusCode = IOSP_GET_STATUS_CODE(edge_serial->rxHeader1);

					if (!IOSP_STATUS_IS_2BYTE(edge_serial->rxStatusCode)) {
						// This status needs additional bytes. Save what we have
						// and then wait for more data.
						edge_serial->rxStatusParam = edge_serial->rxHeader2;

						edge_serial->rxState = EXPECT_HDR3;
						break;
					}

					// We have all the header bytes, process the status now
					process_rcvd_status (edge_serial, edge_serial->rxHeader2, 0);

					edge_serial->rxState = EXPECT_HDR1;
					break;
				} else {
					edge_serial->rxPort = IOSP_GET_HDR_PORT(edge_serial->rxHeader1);
					edge_serial->rxBytesRemaining = IOSP_GET_HDR_DATA_LEN(edge_serial->rxHeader1, edge_serial->rxHeader2);

					dbg(__FUNCTION__" - Data for Port %u Len %u", edge_serial->rxPort, edge_serial->rxBytesRemaining);

					//ASSERT( DevExt->RxPort < DevExt->NumPorts );
					//ASSERT( DevExt->RxBytesRemaining < IOSP_MAX_DATA_LENGTH );

					if (bufferLength == 0 ) {
						edge_serial->rxState = EXPECT_DATA;
						break;
					}
					// Else, drop through
				}

			case EXPECT_DATA:	// Expect data

				if (bufferLength < edge_serial->rxBytesRemaining) {
					rxLen = bufferLength;
					edge_serial->rxState = EXPECT_DATA;	// Expect data to start next buffer
				} else {
					// BufLen >= RxBytesRemaining
					rxLen = edge_serial->rxBytesRemaining;
					edge_serial->rxState = EXPECT_HDR1;	// Start another header next time
				}

				bufferLength -= rxLen;
				edge_serial->rxBytesRemaining -= rxLen;

				/* spit this data back into the tty driver if this port is open */
				if (rxLen) {
					port = &edge_serial->serial->port[edge_serial->rxPort];
					if (port_paranoia_check (port, __FUNCTION__) == 0) {
						edge_port = (struct edgeport_port *)port->private;
						if (edge_port->open) {
							tty = edge_port->port->tty;
							if (tty) {
								dbg (__FUNCTION__" - Sending %d bytes to TTY for port %d", rxLen, edge_serial->rxPort);
								for (i = 0; i < rxLen ; ++i) {
									/* if we insert more than TTY_FLIPBUF_SIZE characters, we drop them. */
									if(tty->flip.count >= TTY_FLIPBUF_SIZE) {
										tty_flip_buffer_push(tty);
									}
									/* this doesn't actually push the data through unless tty->low_latency is set */
									tty_insert_flip_char(tty, buffer[i], 0);
								}
								tty_flip_buffer_push(tty);
							}
							edge_port->icount.rx += rxLen;
						}
					}
					buffer += rxLen;
				}

				break;

			case EXPECT_HDR3:			// Expect 3rd byte of status header
				edge_serial->rxHeader3 = *buffer;
				++buffer;
				--bufferLength;

				// We have all the header bytes, process the status now
				process_rcvd_status (edge_serial, edge_serial->rxStatusParam, edge_serial->rxHeader3);
				edge_serial->rxState = EXPECT_HDR1;
				break;

		}
	}

	return 0;
}


/*****************************************************************************
 * process_rcvd_status
 *	this function handles the any status messages received on the bulk in pipe.
 *****************************************************************************/
static void process_rcvd_status (struct edgeport_serial *edge_serial, __u8 byte2, __u8 byte3)
{
	struct usb_serial_port *port;
	struct edgeport_port *edge_port;
	__u8 code = edge_serial->rxStatusCode;

	/* switch the port pointer to the one being currently talked about */
	port = &edge_serial->serial->port[edge_serial->rxPort];
	if (port_paranoia_check (port, __FUNCTION__)) {
		return;
	}
	edge_port = (struct edgeport_port *)port->private;
	if (edge_port == NULL) {
		err (__FUNCTION__ " - edge_port == NULL for port %d", edge_serial->rxPort);
		return;
	}

	dbg(__FUNCTION__" - port %d", edge_serial->rxPort);

	if (code == IOSP_EXT_STATUS) {
		switch (byte2) {
			case IOSP_EXT_STATUS_CHASE_RSP:
				// we want to do EXT status regardless of port open/closed 
				dbg(__FUNCTION__" - Port %u EXT CHASE_RSP Data = %02x", edge_serial->rxPort, byte3 );
				// Currently, the only EXT_STATUS is Chase, so process here instead of one more call
				// to one more subroutine. If/when more EXT_STATUS, there'll be more work to do.
				// Also, we currently clear flag and close the port regardless of content of above's Byte3.
				// We could choose to do something else when Byte3 says Timeout on Chase from Edgeport,
				// like wait longer in block_until_chase_response, but for now we don't. 
				edge_port->chaseResponsePending = FALSE;
				wake_up_interruptible (&edge_port->wait_chase);
				return;

			case IOSP_EXT_STATUS_RX_CHECK_RSP:
				dbg( __FUNCTION__" ========== Port %u CHECK_RSP Sequence = %02x =============\n", edge_serial->rxPort, byte3 );
				//Port->RxCheckRsp = TRUE;
				return;
		}
	}

	if (code == IOSP_STATUS_OPEN_RSP) {
		edge_port->txCredits = GET_TX_BUFFER_SIZE(byte3);
		edge_port->maxTxCredits = edge_port->txCredits;
		dbg (__FUNCTION__" - Port %u Open Response Inital MSR = %02x TxBufferSize = %d", edge_serial->rxPort, byte2, edge_port->txCredits);
		handle_new_msr (edge_port, byte2);

		/* send the current line settings to the port so we are in sync with any further termios calls */
		change_port_settings (edge_port, edge_port->port->tty->termios);

		/* we have completed the open */
		edge_port->openPending = FALSE;
		edge_port->open = TRUE;
		wake_up_interruptible(&edge_port->wait_open);
		return;
	}

	// If port is closed, silently discard all rcvd status. We can
	// have cases where buffered status is received AFTER the close
	// port command is sent to the Edgeport.
	if ((!edge_port->open ) || (edge_port->closePending)) {
		return;
	}

	switch (code) {
		// Not currently sent by Edgeport
		case IOSP_STATUS_LSR:
			dbg(__FUNCTION__" - Port %u LSR Status = %02x", edge_serial->rxPort, byte2);
			handle_new_lsr (edge_port, FALSE, byte2, 0);
			break;

		case IOSP_STATUS_LSR_DATA:
			dbg(__FUNCTION__" - Port %u LSR Status = %02x, Data = %02x", edge_serial->rxPort, byte2, byte3);
			// byte2 is LSR Register
			// byte3 is broken data byte
			handle_new_lsr (edge_port, TRUE, byte2, byte3);
			break;
			//
			//	case IOSP_EXT_4_STATUS:
			//		dbg(__FUNCTION__" - Port %u LSR Status = %02x Data = %02x", edge_serial->rxPort, byte2, byte3);
			//		break;
			//
		case IOSP_STATUS_MSR:
			dbg(__FUNCTION__" - Port %u MSR Status = %02x", edge_serial->rxPort, byte2);

			// Process this new modem status and generate appropriate
			// events, etc, based on the new status. This routine
			// also saves the MSR in Port->ShadowMsr.
			handle_new_msr(edge_port, byte2);
			break;

		default:
			dbg(__FUNCTION__" - Unrecognized IOSP status code %u\n", code);
			break;
	}

	return;
}


/*****************************************************************************
 * handle_new_msr
 *	this function handles any change to the msr register for a port.
 *****************************************************************************/
static void handle_new_msr(struct edgeport_port *edge_port, __u8 newMsr)
{
	struct  async_icount *icount;

	dbg(__FUNCTION__" %02x", newMsr);

	if (newMsr & (MSR_DELTA_CTS | MSR_DELTA_DSR | MSR_DELTA_RI | MSR_DELTA_CD)) {
		icount = &edge_port->icount;

		/* update input line counters */
		if (newMsr & MSR_DELTA_CTS) {
			icount->cts++;
		}
		if (newMsr & MSR_DELTA_DSR) {
			icount->dsr++;
		}
		if (newMsr & MSR_DELTA_CD) {
			icount->dcd++;
		}
		if (newMsr & MSR_DELTA_RI) {
			icount->rng++;
		}
		wake_up_interruptible(&edge_port->delta_msr_wait);
	}

	/* Save the new modem status */
	edge_port->shadowMSR = newMsr & 0xf0;

	return;
}


/*****************************************************************************
 * handle_new_lsr
 *	this function handles any change to the lsr register for a port.
 *****************************************************************************/
static void handle_new_lsr(struct edgeport_port *edge_port, __u8 lsrData, __u8 lsr, __u8 data)
{
	__u8    newLsr = (__u8)(lsr & (__u8)(LSR_OVER_ERR | LSR_PAR_ERR | LSR_FRM_ERR | LSR_BREAK));
	struct  async_icount *icount;

	dbg(__FUNCTION__" - %02x", newLsr);

	edge_port->shadowLSR = lsr;

	if (newLsr & LSR_BREAK) {
		//
		// Parity and Framing errors only count if they
		// occur exclusive of a break being
		// received.
		//
		newLsr &= (__u8)(LSR_OVER_ERR | LSR_BREAK);
	}

	/* Place LSR data byte into Rx buffer */
	if (lsrData) {
		tty_insert_flip_char(edge_port->port->tty, data, 0);
		tty_flip_buffer_push(edge_port->port->tty);
	}

	/* update input line counters */
	icount = &edge_port->icount;
	if (newLsr & LSR_BREAK) {
		icount->brk++;
	}
	if (newLsr & LSR_OVER_ERR) {
		icount->overrun++;
	}
	if (newLsr & LSR_PAR_ERR) {
		icount->parity++;
	}
	if (newLsr & LSR_FRM_ERR) {
		icount->frame++;
	}

	return;
}


/****************************************************************************
 * sram_write
 *	writes a number of bytes to the Edgeport device's sram starting at the 
 *	given address.
 *	If successful returns the number of bytes written, otherwise it returns
 *	a negative error number of the problem.
 ****************************************************************************/
static int sram_write (struct usb_serial *serial, __u16 extAddr, __u16 addr, __u16 length, __u8 *data)
{
	int result;
	__u16 current_length;
	unsigned char *transfer_buffer;

//	dbg (__FUNCTION__" - %x, %x, %d", extAddr, addr, length);

	transfer_buffer =  kmalloc (64, GFP_KERNEL);
	if (!transfer_buffer) {
		err(__FUNCTION__" - kmalloc(%d) failed.\n", 64);
		return -ENOMEM;
	}

	/* need to split these writes up into 64 byte chunks */
	result = 0;
	while (length > 0) {
		if (length > 64) {
			current_length = 64;
		} else {
			current_length = length;
		}
//		dbg (__FUNCTION__" - writing %x, %x, %d", extAddr, addr, current_length);
		memcpy (transfer_buffer, data, current_length);
		result = usb_control_msg (serial->dev, usb_sndctrlpipe(serial->dev, 0), USB_REQUEST_ION_WRITE_RAM, 
					  0x40, addr, extAddr, transfer_buffer, current_length, 300);
		if (result < 0)
			break;
		length -= current_length;
		addr += current_length;
		data += current_length;
	}       

	kfree (transfer_buffer);
	return result;
}


/****************************************************************************
 * rom_write
 *	writes a number of bytes to the Edgeport device's ROM starting at the
 *	given address.
 *	If successful returns the number of bytes written, otherwise it returns
 *	a negative error number of the problem.
 ****************************************************************************/
static int rom_write (struct usb_serial *serial, __u16 extAddr, __u16 addr, __u16 length, __u8 *data)
{
	int result;
	__u16 current_length;
	unsigned char *transfer_buffer;

//	dbg (__FUNCTION__" - %x, %x, %d", extAddr, addr, length);

	transfer_buffer =  kmalloc (64, GFP_KERNEL);
	if (!transfer_buffer) {
		err(__FUNCTION__" - kmalloc(%d) failed.\n", 64);
		return -ENOMEM;
	}

	/* need to split these writes up into 64 byte chunks */
	result = 0;
	while (length > 0) {
		if (length > 64) {
			current_length = 64;
		} else {
			current_length = length;
		}
//		dbg (__FUNCTION__" - writing %x, %x, %d", extAddr, addr, current_length);
		memcpy (transfer_buffer, data, current_length);
		result = usb_control_msg (serial->dev, usb_sndctrlpipe(serial->dev, 0), USB_REQUEST_ION_WRITE_ROM, 
					  0x40, addr, extAddr, transfer_buffer, current_length, 300);
		if (result < 0)
			break;
		length -= current_length;
		addr += current_length;
		data += current_length;
	}       

	kfree (transfer_buffer);
	return result;
}


/****************************************************************************
 * rom_read
 *	reads a number of bytes from the Edgeport device starting at the given
 *	address.
 *	If successful returns the number of bytes read, otherwise it returns
 *	a negative error number of the problem.
 ****************************************************************************/
static int rom_read (struct usb_serial *serial, __u16 extAddr, __u16 addr, __u16 length, __u8 *data)
{
	int result;
	__u16 current_length;
	unsigned char *transfer_buffer;

	dbg (__FUNCTION__" - %x, %x, %d", extAddr, addr, length);

	transfer_buffer =  kmalloc (64, GFP_KERNEL);
	if (!transfer_buffer) {
		err(__FUNCTION__" - kmalloc(%d) failed.\n", 64);
		return -ENOMEM;
	}

	/* need to split these reads up into 64 byte chunks */
	result = 0;
	while (length > 0) {
		if (length > 64) {
			current_length = 64;
		} else {
			current_length = length;
		}
//		dbg (__FUNCTION__" - %x, %x, %d", extAddr, addr, current_length);
		result = usb_control_msg (serial->dev, usb_rcvctrlpipe(serial->dev, 0), USB_REQUEST_ION_READ_ROM, 
					  0xC0, addr, extAddr, transfer_buffer, current_length, 300);
		if (result < 0)
			break;
		memcpy (data, transfer_buffer, current_length);
		length -= current_length;
		addr += current_length;
		data += current_length;
	}       

	kfree (transfer_buffer);
	return result;
}


/****************************************************************************
 * send_iosp_ext_cmd
 *	Is used to send a IOSP message to the Edgeport device
 ****************************************************************************/
static int send_iosp_ext_cmd (struct edgeport_port *edge_port, __u8 command, __u8 param)
{
	unsigned char   *buffer;
	unsigned char   *currentCommand;
	int             length = 0;
	int             status = 0;

	dbg(__FUNCTION__" - %d, %d", command, param);

	buffer =  kmalloc (10, GFP_KERNEL);
	if (!buffer) {
		err(__FUNCTION__" - kmalloc(%d) failed.\n", 10);
		return -ENOMEM;
	}

	currentCommand = buffer;

	MAKE_CMD_EXT_CMD( &currentCommand, &length, edge_port->port->number, command, param);

	status = write_cmd_usb (edge_port, buffer, length);
	if (status) {
		/* something bad happened, let's free up the memory */
		kfree(buffer);
	}

	return status;
}


/*****************************************************************************
 * write_cmd_usb
 *	this function writes the given buffer out to the bulk write endpoint.
 *****************************************************************************/
static int write_cmd_usb (struct edgeport_port *edge_port, unsigned char *buffer, int length)
{
	struct edgeport_serial *edge_serial = (struct edgeport_serial *)edge_port->port->serial->private;
	int status = 0;
Linus Torvalds's avatar
Linus Torvalds committed
2459
	struct urb *urb;
Linus Torvalds's avatar
Linus Torvalds committed
2460 2461
	int timeout;

Linus Torvalds's avatar
Linus Torvalds committed
2462
	usb_serial_debug_data (__FILE__, __FUNCTION__, length, buffer);
Linus Torvalds's avatar
Linus Torvalds committed
2463 2464 2465

	/* Allocate our next urb */
	urb = usb_alloc_urb (0);
Linus Torvalds's avatar
Linus Torvalds committed
2466 2467
	if (!urb)
		return -ENOMEM;
Linus Torvalds's avatar
Linus Torvalds committed
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479

	CmdUrbs++;
	dbg(__FUNCTION__" - ALLOCATE URB %p (outstanding %d)", urb, CmdUrbs);

	FILL_BULK_URB (urb, edge_serial->serial->dev, 
		       usb_sndbulkpipe(edge_serial->serial->dev, edge_serial->bulk_out_endpoint),
		       buffer, length, edge_bulk_out_cmd_callback, edge_port);

	/* set the USB_BULK_QUEUE flag so that we can shove a bunch of urbs at once down the pipe */
	urb->transfer_flags |= USB_QUEUE_BULK;

	edge_port->commandPending = TRUE;
2480
	status = usb_submit_urb(urb, GFP_KERNEL);
Linus Torvalds's avatar
Linus Torvalds committed
2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547

	if (status) {
		/* something went wrong */
		dbg(__FUNCTION__" - usb_submit_urb(write bulk) failed");
		usb_unlink_urb (urb);
		usb_free_urb   (urb);
		return status;
	}

	// wait for command to finish
	timeout = COMMAND_TIMEOUT;
#if 0
	while (timeout && edge_port->commandPending == TRUE) {
		timeout = interruptible_sleep_on_timeout (&edge_port->wait_command, timeout);
	}

	if (edge_port->commandPending == TRUE) {
		/* command timed out */
		dbg(__FUNCTION__" - command timed out");
		status = -EINVAL;
	}
#endif
	return status;
}


/*****************************************************************************
 * send_cmd_write_baud_rate
 *	this function sends the proper command to change the baud rate of the
 *	specified port.
 *****************************************************************************/
static int send_cmd_write_baud_rate (struct edgeport_port *edge_port, int baudRate)
{
	unsigned char *cmdBuffer;
	unsigned char *currCmd;
	int cmdLen = 0;
	int divisor;
	int status;
	unsigned char number = edge_port->port->number;

	dbg(__FUNCTION__" - port = %d, baud = %d", number, baudRate);

	status = calc_baud_rate_divisor (baudRate, &divisor);
	if (status) {
		err(__FUNCTION__" - bad baud rate");
		return status;
	}

	// Alloc memory for the string of commands.
	cmdBuffer =  kmalloc (0x100, GFP_KERNEL);
	if (!cmdBuffer) {
		err(__FUNCTION__" - kmalloc(%d) failed.\n", 0x100);
		return -ENOMEM;
	}
	currCmd = cmdBuffer;

	// Enable access to divisor latch
	MAKE_CMD_WRITE_REG( &currCmd, &cmdLen, number, LCR, LCR_DL_ENABLE );

	// Write the divisor itself
	MAKE_CMD_WRITE_REG( &currCmd, &cmdLen, number, DLL, LOW8 (divisor) );
	MAKE_CMD_WRITE_REG( &currCmd, &cmdLen, number, DLM, HIGH8(divisor) );

	// Restore original value to disable access to divisor latch
	MAKE_CMD_WRITE_REG( &currCmd, &cmdLen, number, LCR, edge_port->shadowLCR);

	status = write_cmd_usb(edge_port, cmdBuffer, cmdLen );
Linus Torvalds's avatar
Linus Torvalds committed
2548 2549 2550 2551
	if (status) {
		/* something bad happened, let's free up the memory */
		kfree (cmdBuffer);
	}
Linus Torvalds's avatar
Linus Torvalds committed
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571

	return status;
}


/*****************************************************************************
 * calc_baud_rate_divisor
 *	this function calculates the proper baud rate divisor for the specified
 *	baud rate.
 *****************************************************************************/
static int calc_baud_rate_divisor (int baudrate, int *divisor)
{
	int i;
	__u16 custom;
	__u16 round1;
	__u16 round;


	dbg(__FUNCTION__" - %d", baudrate);

2572 2573 2574
	for (i = 0; i < NUM_ENTRIES(divisor_table); i++) {
		if ( divisor_table[i].BaudRate == baudrate ) {
			*divisor = divisor_table[i].Divisor;
Linus Torvalds's avatar
Linus Torvalds committed
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
			return 0;
		}
	}

	// We have tried all of the standard baud rates
	// lets try to calculate the divisor for this baud rate
	// Make sure the baud rate is reasonable
	if (baudrate > 75 &&  baudrate < 230400) {
		// get divisor
		custom = (__u16)(230400L  / baudrate);

		// Check for round off
		round1 = (__u16)(2304000L / baudrate);
		round = (__u16)(round1 - (custom * 10));
		if (round > 4) {
			custom++;
		}
		*divisor = custom;

		dbg(__FUNCTION__" - Baud %d = %d\n", baudrate, custom);
		return 0;
	}

	return -1;
}


/*****************************************************************************
 * send_cmd_write_uart_register
 *	this function builds up a uart register message and sends to to the device.
 *****************************************************************************/
static int send_cmd_write_uart_register (struct edgeport_port *edge_port, __u8 regNum, __u8 regValue)
{
	unsigned char *cmdBuffer;
	unsigned char *currCmd;
	unsigned long cmdLen = 0;
	int status;

	dbg (__FUNCTION__" - write to %s register 0x%02x", (regNum == MCR) ? "MCR" : "LCR", regValue);

	// Alloc memory for the string of commands.
	cmdBuffer = kmalloc (0x10, GFP_KERNEL);
	if (cmdBuffer == NULL ) {
		return -ENOMEM;
	}

	currCmd = cmdBuffer;

	// Build a cmd in the buffer to write the given register
	MAKE_CMD_WRITE_REG(&currCmd, &cmdLen, edge_port->port->number, regNum, regValue);

	status = write_cmd_usb(edge_port, cmdBuffer, cmdLen);
Linus Torvalds's avatar
Linus Torvalds committed
2627 2628 2629 2630
	if (status) {
		/* something bad happened, let's free up the memory */
		kfree (cmdBuffer);
	}
Linus Torvalds's avatar
Linus Torvalds committed
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714

	return status;
}


/*****************************************************************************
 * change_port_settings
 *	This routine is called to set the UART on the device to match the specified
 *	new settings.
 *****************************************************************************/
static void change_port_settings (struct edgeport_port *edge_port, struct termios *old_termios)
{
	struct tty_struct *tty;
	int baud;
	unsigned cflag;
	__u8 mask = 0xff;
	__u8 lData;
	__u8 lParity;
	__u8 lStop;
	__u8 rxFlow;
	__u8 txFlow;
	int status;

	dbg(__FUNCTION__" - port %d", edge_port->port->number);

	if ((!edge_port->open) &&
	    (!edge_port->openPending)) {
		dbg(__FUNCTION__" - port not opened");
		return;
	}

	tty = edge_port->port->tty;
	if ((!tty) ||
	    (!tty->termios)) {
		dbg(__FUNCTION__" - no tty structures");
		return;
	}

	cflag = tty->termios->c_cflag;

	switch (cflag & CSIZE) {
		case CS5:   lData = LCR_BITS_5; mask = 0x1f;    dbg(__FUNCTION__" - data bits = 5");   break;
		case CS6:   lData = LCR_BITS_6; mask = 0x3f;    dbg(__FUNCTION__" - data bits = 6");   break;
		case CS7:   lData = LCR_BITS_7; mask = 0x7f;    dbg(__FUNCTION__" - data bits = 7");   break;
		default:
		case CS8:   lData = LCR_BITS_8;                 dbg(__FUNCTION__" - data bits = 8");   break;
	}

	lParity = LCR_PAR_NONE;
	if (cflag & PARENB) {
		if (cflag & PARODD) {
			lParity = LCR_PAR_ODD;
			dbg(__FUNCTION__" - parity = odd");
		} else {
			lParity = LCR_PAR_EVEN;
			dbg(__FUNCTION__" - parity = even");
		}
	} else {
		dbg(__FUNCTION__" - parity = none");
	}

	if (cflag & CSTOPB) {
		lStop = LCR_STOP_2;
		dbg(__FUNCTION__" - stop bits = 2");
	} else {
		lStop = LCR_STOP_1;
		dbg(__FUNCTION__" - stop bits = 1");
	}

	/* figure out the flow control settings */
	rxFlow = txFlow = 0x00;
	if (cflag & CRTSCTS) {
		rxFlow |= IOSP_RX_FLOW_RTS;
		txFlow |= IOSP_TX_FLOW_CTS;
		dbg(__FUNCTION__" - RTS/CTS is enabled");
	} else {
		dbg(__FUNCTION__" - RTS/CTS is disabled");
	}

	/* if we are implementing XON/XOFF, set the start and stop character in the device */
	if (I_IXOFF(tty) || I_IXON(tty)) {
		unsigned char stop_char  = STOP_CHAR(tty);
		unsigned char start_char = START_CHAR(tty);

Linus Torvalds's avatar
Linus Torvalds committed
2715 2716
		send_iosp_ext_cmd (edge_port, IOSP_CMD_SET_XON_CHAR, start_char);
		send_iosp_ext_cmd (edge_port, IOSP_CMD_SET_XOFF_CHAR, stop_char);
Linus Torvalds's avatar
Linus Torvalds committed
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865

		/* if we are implementing INBOUND XON/XOFF */
		if (I_IXOFF(tty)) {
			rxFlow |= IOSP_RX_FLOW_XON_XOFF;
			dbg(__FUNCTION__" - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x", start_char, stop_char);
		} else {
			dbg(__FUNCTION__" - INBOUND XON/XOFF is disabled");
		}

		/* if we are implementing OUTBOUND XON/XOFF */
		if (I_IXON(tty)) {
			txFlow |= IOSP_TX_FLOW_XON_XOFF;
			dbg(__FUNCTION__" - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x", start_char, stop_char);
		} else {
			dbg(__FUNCTION__" - OUTBOUND XON/XOFF is disabled");
		}
	}

	/* Set flow control to the configured value */
	send_iosp_ext_cmd (edge_port, IOSP_CMD_SET_RX_FLOW, rxFlow);
	send_iosp_ext_cmd (edge_port, IOSP_CMD_SET_TX_FLOW, txFlow);


	edge_port->shadowLCR &= ~(LCR_BITS_MASK | LCR_STOP_MASK | LCR_PAR_MASK);
	edge_port->shadowLCR |= (lData | lParity | lStop);

	edge_port->validDataMask = mask;

	/* Send the updated LCR value to the EdgePort */
	status = send_cmd_write_uart_register(edge_port, LCR, edge_port->shadowLCR);
	if (status != 0) {
		return;
	}

	/* set up the MCR register and send it to the EdgePort */
	edge_port->shadowMCR = MCR_MASTER_IE;
	if (cflag & CBAUD) {
		edge_port->shadowMCR |= (MCR_DTR | MCR_RTS);
	}
	status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR);
	if (status != 0) {
		return;
	}

	/* Determine divisor based on baud rate */
	baud = tty_get_baud_rate(tty);
	if (!baud) {
		/* pick a default, any default... */
		baud = 9600;
	}

	dbg(__FUNCTION__ " - baud rate = %d", baud);
	status = send_cmd_write_baud_rate (edge_port, baud);

	return;
}


/****************************************************************************
 * unicode_to_ascii
 *	Turns a string from Unicode into ASCII.
 *	Doesn't do a good job with any characters that are outside the normal
 *	ASCII range, but it's only for debugging...
 ****************************************************************************/
static void unicode_to_ascii (char *string, short *unicode, int unicode_size)
{
	int i;
	for (i = 0; i < unicode_size; ++i) {
		string[i] = (char)(unicode[i]);
	}
	string[unicode_size] = 0x00;
}


/****************************************************************************
 * get_manufacturing_desc
 *	reads in the manufacturing descriptor and stores it into the serial 
 *	structure.
 ****************************************************************************/
static void get_manufacturing_desc (struct edgeport_serial *edge_serial)
{
	int response;

	dbg("getting manufacturer descriptor");

	response = rom_read (edge_serial->serial, (EDGE_MANUF_DESC_ADDR & 0xffff0000) >> 16, 
			    (__u16)(EDGE_MANUF_DESC_ADDR & 0x0000ffff), EDGE_MANUF_DESC_LEN,
			    (__u8 *)(&edge_serial->manuf_descriptor));

	if (response < 1) {
		err("error in getting manufacturer descriptor");
	} else {
		char string[30];
		dbg("**Manufacturer Descriptor");
		dbg("  RomSize:        %dK", edge_serial->manuf_descriptor.RomSize);
		dbg("  RamSize:        %dK", edge_serial->manuf_descriptor.RamSize);
		dbg("  CpuRev:         %d", edge_serial->manuf_descriptor.CpuRev);
		dbg("  BoardRev:       %d", edge_serial->manuf_descriptor.BoardRev);
		dbg("  NumPorts:       %d", edge_serial->manuf_descriptor.NumPorts);
		dbg("  DescDate:       %d/%d/%d", edge_serial->manuf_descriptor.DescDate[0], edge_serial->manuf_descriptor.DescDate[1], edge_serial->manuf_descriptor.DescDate[2]+1900);
		unicode_to_ascii (string, edge_serial->manuf_descriptor.SerialNumber, edge_serial->manuf_descriptor.SerNumLength/2-1);
		dbg("  SerialNumber: %s", string);
		unicode_to_ascii (string, edge_serial->manuf_descriptor.AssemblyNumber, edge_serial->manuf_descriptor.AssemblyNumLength/2-1);
		dbg("  AssemblyNumber: %s", string);
		unicode_to_ascii (string, edge_serial->manuf_descriptor.OemAssyNumber, edge_serial->manuf_descriptor.OemAssyNumLength/2-1);
		dbg("  OemAssyNumber:  %s", string);
		dbg("  UartType:       %d", edge_serial->manuf_descriptor.UartType);
		dbg("  IonPid:         %d", edge_serial->manuf_descriptor.IonPid);
		dbg("  IonConfig:      %d", edge_serial->manuf_descriptor.IonConfig);
	}
}


/****************************************************************************
 * get_boot_desc
 *	reads in the bootloader descriptor and stores it into the serial 
 *	structure.
 ****************************************************************************/
static void get_boot_desc (struct edgeport_serial *edge_serial)
{
	int response;

	dbg("getting boot descriptor");

	response = rom_read (edge_serial->serial, (EDGE_BOOT_DESC_ADDR & 0xffff0000) >> 16, 
			    (__u16)(EDGE_BOOT_DESC_ADDR & 0x0000ffff), EDGE_BOOT_DESC_LEN,
			    (__u8 *)(&edge_serial->boot_descriptor));

	if (response < 1) {
		err("error in getting boot descriptor");
	} else {
		dbg("**Boot Descriptor:");
		dbg("  BootCodeLength: %d", edge_serial->boot_descriptor.BootCodeLength);
		dbg("  MajorVersion:   %d", edge_serial->boot_descriptor.MajorVersion);
		dbg("  MinorVersion:   %d", edge_serial->boot_descriptor.MinorVersion);
		dbg("  BuildNumber:    %d", edge_serial->boot_descriptor.BuildNumber);
		dbg("  Capabilities:   0x%x", edge_serial->boot_descriptor.Capabilities);
		dbg("  UConfig0:       %d", edge_serial->boot_descriptor.UConfig0);
		dbg("  UConfig1:       %d", edge_serial->boot_descriptor.UConfig1);
	}
}


/****************************************************************************
 * load_application_firmware
 *	This is called to load the application firmware to the device
 ****************************************************************************/
static void load_application_firmware (struct edgeport_serial *edge_serial)
{
2866
	struct edge_firmware_image_record *record;
Linus Torvalds's avatar
Linus Torvalds committed
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903
	unsigned char *firmware;
	unsigned char *FirmwareImage;
	int ImageSize;
	int response;


	switch (edge_serial->product_info.iDownloadFile) {
		case EDGE_DOWNLOAD_FILE_I930:
			dbg("downloading firmware version (930) %d.%d.%d", 
			    OperationalCodeImageVersion_GEN1.MajorVersion, 
			    OperationalCodeImageVersion_GEN1.MinorVersion, 
			    OperationalCodeImageVersion_GEN1.BuildNumber);
			firmware = &OperationalCodeImage_GEN1[0];
			FirmwareImage = &OperationalCodeImage_GEN1[0];
			ImageSize = sizeof(OperationalCodeImage_GEN1);
			break;

		case EDGE_DOWNLOAD_FILE_80251:
			dbg("downloading firmware version (80251) %d.%d.%d", 
			    OperationalCodeImageVersion_GEN2.MajorVersion, 
			    OperationalCodeImageVersion_GEN2.MinorVersion, 
			    OperationalCodeImageVersion_GEN2.BuildNumber);
			firmware = &OperationalCodeImage_GEN2[0];
			FirmwareImage = &OperationalCodeImage_GEN2[0];
			ImageSize = sizeof(OperationalCodeImage_GEN2);
			break;

		case EDGE_DOWNLOAD_FILE_NONE:
			dbg     ("No download file specified, skipping download\n");
			return;

		default:
			return;
	}


	for (;;) {
2904
		record = (struct edge_firmware_image_record *)firmware;
Linus Torvalds's avatar
Linus Torvalds committed
2905 2906 2907 2908 2909
		response = sram_write (edge_serial->serial, record->ExtAddr, record->Addr, record->Len, &record->Data[0]);
		if (response < 0) {
			err("sram_write failed (%x, %x, %d)", record->ExtAddr, record->Addr, record->Len);
			break;
		}
2910
		firmware += sizeof (struct edge_firmware_image_record) + record->Len;
Linus Torvalds's avatar
Linus Torvalds committed
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967
		if (firmware >= &FirmwareImage[ImageSize]) {
			break;
		}
	}

	dbg("sending exec_dl_code");
	response = usb_control_msg (edge_serial->serial->dev, 
				    usb_sndctrlpipe(edge_serial->serial->dev, 0), 
				    USB_REQUEST_ION_EXEC_DL_CODE, 
				    0x40, 0x4000, 0x0001, NULL, 0, 3000);

	return;
}




/****************************************************************************
 * edge_startup
 ****************************************************************************/
static int edge_startup (struct usb_serial *serial)
{
	struct edgeport_serial *edge_serial;
	struct edgeport_port *edge_port;
	struct usb_device *dev;
	int i;

	dev = serial->dev;

	/* create our private serial structure */
	edge_serial = kmalloc (sizeof(struct edgeport_serial), GFP_KERNEL);
	if (edge_serial == NULL) {
		err(__FUNCTION__" - Out of memory");
		return -ENOMEM;
	}
	memset (edge_serial, 0, sizeof(struct edgeport_serial));
	edge_serial->serial = serial;
	serial->private = edge_serial;

	/* get the name for the device from the device */
	if ( (i = get_string(dev, dev->descriptor.iManufacturer, &edge_serial->name[0])) != 0) {
		edge_serial->name[i-1] = ' ';
	}

	get_string(dev, dev->descriptor.iProduct, &edge_serial->name[i]);

	info("%s detected", edge_serial->name);

	/* get the manufacturing descriptor for this device */
	get_manufacturing_desc (edge_serial);

	/* get the boot descriptor */
	get_boot_desc (edge_serial);

	get_product_info(edge_serial);

	/* set the number of ports from the manufacturing description */
Linus Torvalds's avatar
Linus Torvalds committed
2968
	/* serial->num_ports = serial->product_info.NumPorts; */
Linus Torvalds's avatar
Linus Torvalds committed
2969
	if (edge_serial->product_info.NumPorts != serial->num_ports) {
Linus Torvalds's avatar
Linus Torvalds committed
2970 2971 2972
		warn(__FUNCTION__ " - Device Reported %d serial ports vs core "
		     "thinking we have %d ports, email greg@kroah.com this info.",
		     edge_serial->product_info.NumPorts, serial->num_ports);
Linus Torvalds's avatar
Linus Torvalds committed
2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
	}

	dbg(__FUNCTION__ " - time 1 %ld", jiffies);

	/* now load the application firmware into this device */
	load_application_firmware (edge_serial);

	dbg(__FUNCTION__ " - time 2 %ld", jiffies);

	/* Check current Edgeport EEPROM and update if necessary */
	update_edgeport_E2PROM (edge_serial);
	
	dbg(__FUNCTION__ " - time 3 %ld", jiffies);

	/* set the configuration to use #1 */
//	dbg("set_configuration 1");
//	usb_set_configuration (dev, 1);

	/* we set up the pointers to the endpoints in the edge_open function, 
	 * as the structures aren't created yet. */

	/* set up our port private structures */
	for (i = 0; i < serial->num_ports; ++i) {
		edge_port = kmalloc (sizeof(struct edgeport_port), GFP_KERNEL);
		if (edge_port == NULL) {
			err(__FUNCTION__" - Out of memory");
			return -ENOMEM;
		}
		memset (edge_port, 0, sizeof(struct edgeport_port));
		edge_port->port = &serial->port[i];
		serial->port[i].private = edge_port;
	}
	
	return 0;
}



/****************************************************************************
Linus Torvalds's avatar
Linus Torvalds committed
3012
 * edge_shutdown
Linus Torvalds's avatar
Linus Torvalds committed
3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025
 *	This function is called whenever the device is removed from the usb bus.
 ****************************************************************************/
static void edge_shutdown (struct usb_serial *serial)
{
	int i;

	dbg (__FUNCTION__);

	/* stop reads and writes on all ports */
	for (i=0; i < serial->num_ports; ++i) {
		while (serial->port[i].open_count > 0) {
			edge_close (&serial->port[i], NULL);
		}
Linus Torvalds's avatar
Linus Torvalds committed
3026 3027
		kfree (serial->port[i].private);
		serial->port[i].private = NULL;
Linus Torvalds's avatar
Linus Torvalds committed
3028
	}
Linus Torvalds's avatar
Linus Torvalds committed
3029 3030
	kfree (serial->private);
	serial->private = NULL;
Linus Torvalds's avatar
Linus Torvalds committed
3031 3032 3033 3034 3035 3036 3037 3038 3039
}


/****************************************************************************
 * edgeport_init
 *	This is called by the module subsystem, or on startup to initialize us
 ****************************************************************************/
int __init edgeport_init(void)
{
Linus Torvalds's avatar
Linus Torvalds committed
3040 3041 3042 3043
	usb_serial_register (&edgeport_1port_device);
	usb_serial_register (&edgeport_2port_device);
	usb_serial_register (&edgeport_4port_device);
	usb_serial_register (&edgeport_8port_device);
Linus Torvalds's avatar
Linus Torvalds committed
3044
	info(DRIVER_DESC " " DRIVER_VERSION);
Linus Torvalds's avatar
Linus Torvalds committed
3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
	return 0;
}



/****************************************************************************
 * edgeport_exit
 *	Called when the driver is about to be unloaded.
 ****************************************************************************/
void __exit edgeport_exit (void)
{
Linus Torvalds's avatar
Linus Torvalds committed
3056 3057 3058 3059
	usb_serial_deregister (&edgeport_1port_device);
	usb_serial_deregister (&edgeport_2port_device);
	usb_serial_deregister (&edgeport_4port_device);
	usb_serial_deregister (&edgeport_8port_device);
Linus Torvalds's avatar
Linus Torvalds committed
3060 3061 3062 3063 3064
}

module_init(edgeport_init);
module_exit(edgeport_exit);

Linus Torvalds's avatar
Linus Torvalds committed
3065 3066 3067
/* Module information */
MODULE_AUTHOR( DRIVER_AUTHOR );
MODULE_DESCRIPTION( DRIVER_DESC );
Linus Torvalds's avatar
Linus Torvalds committed
3068
MODULE_LICENSE("GPL");
Linus Torvalds's avatar
Linus Torvalds committed
3069 3070 3071 3072

MODULE_PARM(debug, "i");
MODULE_PARM_DESC(debug, "Debug enabled or not");