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