1/******************************************************************************
2 *
3 * Driver for Option High Speed Mobile Devices.
4 *
5 *  Copyright (C) 2008 Option International
6 *                     Filip Aben <f.aben@option.com>
7 *                     Denis Joseph Barrow <d.barow@option.com>
8 *                     Jan Dumon <j.dumon@option.com>
9 *  Copyright (C) 2007 Andrew Bird (Sphere Systems Ltd)
10 *  			<ajb@spheresystems.co.uk>
11 *  Copyright (C) 2008 Greg Kroah-Hartman <gregkh@suse.de>
12 *  Copyright (C) 2008 Novell, Inc.
13 *
14 *  This program is free software; you can redistribute it and/or modify
15 *  it under the terms of the GNU General Public License version 2 as
16 *  published by the Free Software Foundation.
17 *
18 *  This program is distributed in the hope that it will be useful,
19 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
20 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 *  GNU General Public License for more details.
22 *
23 *  You should have received a copy of the GNU General Public License
24 *  along with this program; if not, write to the Free Software
25 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
26 *  USA
27 *
28 *
29 *****************************************************************************/
30
31/******************************************************************************
32 *
33 * Description of the device:
34 *
35 * Interface 0:	Contains the IP network interface on the bulk end points.
36 *		The multiplexed serial ports are using the interrupt and
37 *		control endpoints.
38 *		Interrupt contains a bitmap telling which multiplexed
39 *		serialport needs servicing.
40 *
41 * Interface 1:	Diagnostics port, uses bulk only, do not submit urbs until the
42 *		port is opened, as this have a huge impact on the network port
43 *		throughput.
44 *
45 * Interface 2:	Standard modem interface - circuit switched interface, this
46 *		can be used to make a standard ppp connection however it
47 *              should not be used in conjunction with the IP network interface
48 *              enabled for USB performance reasons i.e. if using this set
49 *              ideally disable_net=1.
50 *
51 *****************************************************************************/
52
53#include <linux/sched.h>
54#include <linux/slab.h>
55#include <linux/init.h>
56#include <linux/delay.h>
57#include <linux/netdevice.h>
58#include <linux/module.h>
59#include <linux/ethtool.h>
60#include <linux/usb.h>
61#include <linux/timer.h>
62#include <linux/tty.h>
63#include <linux/tty_driver.h>
64#include <linux/tty_flip.h>
65#include <linux/kmod.h>
66#include <linux/rfkill.h>
67#include <linux/ip.h>
68#include <linux/uaccess.h>
69#include <linux/usb/cdc.h>
70#include <net/arp.h>
71#include <asm/byteorder.h>
72#include <linux/serial_core.h>
73#include <linux/serial.h>
74
75
76#define MOD_AUTHOR			"Option Wireless"
77#define MOD_DESCRIPTION			"USB High Speed Option driver"
78#define MOD_LICENSE			"GPL"
79
80#define HSO_MAX_NET_DEVICES		10
81#define HSO__MAX_MTU			2048
82#define DEFAULT_MTU			1500
83#define DEFAULT_MRU			1500
84
85#define CTRL_URB_RX_SIZE		1024
86#define CTRL_URB_TX_SIZE		64
87
88#define BULK_URB_RX_SIZE		4096
89#define BULK_URB_TX_SIZE		8192
90
91#define MUX_BULK_RX_BUF_SIZE		HSO__MAX_MTU
92#define MUX_BULK_TX_BUF_SIZE		HSO__MAX_MTU
93#define MUX_BULK_RX_BUF_COUNT		4
94#define USB_TYPE_OPTION_VENDOR		0x20
95
96/* These definitions are used with the struct hso_net flags element */
97/* - use *_bit operations on it. (bit indices not values.) */
98#define HSO_NET_RUNNING			0
99
100#define	HSO_NET_TX_TIMEOUT		(HZ*10)
101
102#define HSO_SERIAL_MAGIC		0x48534f31
103
104/* Number of ttys to handle */
105#define HSO_SERIAL_TTY_MINORS		256
106
107#define MAX_RX_URBS			2
108
109static inline struct hso_serial *get_serial_by_tty(struct tty_struct *tty)
110{
111	if (tty)
112		return tty->driver_data;
113	return NULL;
114}
115
116/*****************************************************************************/
117/* Debugging functions                                                       */
118/*****************************************************************************/
119#define D__(lvl_, fmt, arg...)				\
120	do {						\
121		printk(lvl_ "[%d:%s]: " fmt "\n",	\
122		       __LINE__, __func__, ## arg);	\
123	} while (0)
124
125#define D_(lvl, args...)				\
126	do {						\
127		if (lvl & debug)			\
128			D__(KERN_INFO, args);		\
129	} while (0)
130
131#define D1(args...)	D_(0x01, ##args)
132#define D2(args...)	D_(0x02, ##args)
133#define D3(args...)	D_(0x04, ##args)
134#define D4(args...)	D_(0x08, ##args)
135#define D5(args...)	D_(0x10, ##args)
136
137/*****************************************************************************/
138/* Enumerators                                                               */
139/*****************************************************************************/
140enum pkt_parse_state {
141	WAIT_IP,
142	WAIT_DATA,
143	WAIT_SYNC
144};
145
146/*****************************************************************************/
147/* Structs                                                                   */
148/*****************************************************************************/
149
150struct hso_shared_int {
151	struct usb_endpoint_descriptor *intr_endp;
152	void *shared_intr_buf;
153	struct urb *shared_intr_urb;
154	struct usb_device *usb;
155	int use_count;
156	int ref_count;
157	struct mutex shared_int_lock;
158};
159
160struct hso_net {
161	struct hso_device *parent;
162	struct net_device *net;
163	struct rfkill *rfkill;
164
165	struct usb_endpoint_descriptor *in_endp;
166	struct usb_endpoint_descriptor *out_endp;
167
168	struct urb *mux_bulk_rx_urb_pool[MUX_BULK_RX_BUF_COUNT];
169	struct urb *mux_bulk_tx_urb;
170	void *mux_bulk_rx_buf_pool[MUX_BULK_RX_BUF_COUNT];
171	void *mux_bulk_tx_buf;
172
173	struct sk_buff *skb_rx_buf;
174	struct sk_buff *skb_tx_buf;
175
176	enum pkt_parse_state rx_parse_state;
177	spinlock_t net_lock;
178
179	unsigned short rx_buf_size;
180	unsigned short rx_buf_missing;
181	struct iphdr rx_ip_hdr;
182
183	unsigned long flags;
184};
185
186enum rx_ctrl_state{
187	RX_IDLE,
188	RX_SENT,
189	RX_PENDING
190};
191
192#define BM_REQUEST_TYPE (0xa1)
193#define B_NOTIFICATION  (0x20)
194#define W_VALUE         (0x0)
195#define W_INDEX         (0x2)
196#define W_LENGTH        (0x2)
197
198#define B_OVERRUN       (0x1<<6)
199#define B_PARITY        (0x1<<5)
200#define B_FRAMING       (0x1<<4)
201#define B_RING_SIGNAL   (0x1<<3)
202#define B_BREAK         (0x1<<2)
203#define B_TX_CARRIER    (0x1<<1)
204#define B_RX_CARRIER    (0x1<<0)
205
206struct hso_serial_state_notification {
207	u8 bmRequestType;
208	u8 bNotification;
209	u16 wValue;
210	u16 wIndex;
211	u16 wLength;
212	u16 UART_state_bitmap;
213} __packed;
214
215struct hso_tiocmget {
216	struct mutex mutex;
217	wait_queue_head_t waitq;
218	int    intr_completed;
219	struct usb_endpoint_descriptor *endp;
220	struct urb *urb;
221	struct hso_serial_state_notification serial_state_notification;
222	u16    prev_UART_state_bitmap;
223	struct uart_icount icount;
224};
225
226
227struct hso_serial {
228	struct hso_device *parent;
229	int magic;
230	u8 minor;
231
232	struct hso_shared_int *shared_int;
233
234	/* rx/tx urb could be either a bulk urb or a control urb depending
235	   on which serial port it is used on. */
236	struct urb *rx_urb[MAX_RX_URBS];
237	u8 num_rx_urbs;
238	u8 *rx_data[MAX_RX_URBS];
239	u16 rx_data_length;	/* should contain allocated length */
240
241	struct urb *tx_urb;
242	u8 *tx_data;
243	u8 *tx_buffer;
244	u16 tx_data_length;	/* should contain allocated length */
245	u16 tx_data_count;
246	u16 tx_buffer_count;
247	struct usb_ctrlrequest ctrl_req_tx;
248	struct usb_ctrlrequest ctrl_req_rx;
249
250	struct usb_endpoint_descriptor *in_endp;
251	struct usb_endpoint_descriptor *out_endp;
252
253	enum rx_ctrl_state rx_state;
254	u8 rts_state;
255	u8 dtr_state;
256	unsigned tx_urb_used:1;
257
258	/* from usb_serial_port */
259	struct tty_struct *tty;
260	int open_count;
261	spinlock_t serial_lock;
262
263	int (*write_data) (struct hso_serial *serial);
264	struct hso_tiocmget  *tiocmget;
265	/* Hacks required to get flow control
266	 * working on the serial receive buffers
267	 * so as not to drop characters on the floor.
268	 */
269	int  curr_rx_urb_idx;
270	u16  curr_rx_urb_offset;
271	u8   rx_urb_filled[MAX_RX_URBS];
272	struct tasklet_struct unthrottle_tasklet;
273	struct work_struct    retry_unthrottle_workqueue;
274};
275
276struct hso_device {
277	union {
278		struct hso_serial *dev_serial;
279		struct hso_net *dev_net;
280	} port_data;
281
282	u32 port_spec;
283
284	u8 is_active;
285	u8 usb_gone;
286	struct work_struct async_get_intf;
287	struct work_struct async_put_intf;
288	struct work_struct reset_device;
289
290	struct usb_device *usb;
291	struct usb_interface *interface;
292
293	struct device *dev;
294	struct kref ref;
295	struct mutex mutex;
296};
297
298/* Type of interface */
299#define HSO_INTF_MASK		0xFF00
300#define	HSO_INTF_MUX		0x0100
301#define	HSO_INTF_BULK   	0x0200
302
303/* Type of port */
304#define HSO_PORT_MASK		0xFF
305#define HSO_PORT_NO_PORT	0x0
306#define	HSO_PORT_CONTROL	0x1
307#define	HSO_PORT_APP		0x2
308#define	HSO_PORT_GPS		0x3
309#define	HSO_PORT_PCSC		0x4
310#define	HSO_PORT_APP2		0x5
311#define HSO_PORT_GPS_CONTROL	0x6
312#define HSO_PORT_MSD		0x7
313#define HSO_PORT_VOICE		0x8
314#define HSO_PORT_DIAG2		0x9
315#define	HSO_PORT_DIAG		0x10
316#define	HSO_PORT_MODEM		0x11
317#define	HSO_PORT_NETWORK	0x12
318
319/* Additional device info */
320#define HSO_INFO_MASK		0xFF000000
321#define HSO_INFO_CRC_BUG	0x01000000
322
323/*****************************************************************************/
324/* Prototypes                                                                */
325/*****************************************************************************/
326/* Serial driver functions */
327static int hso_serial_tiocmset(struct tty_struct *tty,
328			       unsigned int set, unsigned int clear);
329static void ctrl_callback(struct urb *urb);
330static int put_rxbuf_data(struct urb *urb, struct hso_serial *serial);
331static void hso_kick_transmit(struct hso_serial *serial);
332/* Helper functions */
333static int hso_mux_submit_intr_urb(struct hso_shared_int *mux_int,
334				   struct usb_device *usb, gfp_t gfp);
335static void handle_usb_error(int status, const char *function,
336			     struct hso_device *hso_dev);
337static struct usb_endpoint_descriptor *hso_get_ep(struct usb_interface *intf,
338						  int type, int dir);
339static int hso_get_mux_ports(struct usb_interface *intf, unsigned char *ports);
340static void hso_free_interface(struct usb_interface *intf);
341static int hso_start_serial_device(struct hso_device *hso_dev, gfp_t flags);
342static int hso_stop_serial_device(struct hso_device *hso_dev);
343static int hso_start_net_device(struct hso_device *hso_dev);
344static void hso_free_shared_int(struct hso_shared_int *shared_int);
345static int hso_stop_net_device(struct hso_device *hso_dev);
346static void hso_serial_ref_free(struct kref *ref);
347static void hso_std_serial_read_bulk_callback(struct urb *urb);
348static int hso_mux_serial_read(struct hso_serial *serial);
349static void async_get_intf(struct work_struct *data);
350static void async_put_intf(struct work_struct *data);
351static int hso_put_activity(struct hso_device *hso_dev);
352static int hso_get_activity(struct hso_device *hso_dev);
353static void tiocmget_intr_callback(struct urb *urb);
354static void reset_device(struct work_struct *data);
355/*****************************************************************************/
356/* Helping functions                                                         */
357/*****************************************************************************/
358
359/* #define DEBUG */
360
361static inline struct hso_net *dev2net(struct hso_device *hso_dev)
362{
363	return hso_dev->port_data.dev_net;
364}
365
366static inline struct hso_serial *dev2ser(struct hso_device *hso_dev)
367{
368	return hso_dev->port_data.dev_serial;
369}
370
371/* Debugging functions */
372#ifdef DEBUG
373static void dbg_dump(int line_count, const char *func_name, unsigned char *buf,
374		     unsigned int len)
375{
376	static char name[255];
377
378	sprintf(name, "hso[%d:%s]", line_count, func_name);
379	print_hex_dump_bytes(name, DUMP_PREFIX_NONE, buf, len);
380}
381
382#define DUMP(buf_, len_)	\
383	dbg_dump(__LINE__, __func__, (unsigned char *)buf_, len_)
384
385#define DUMP1(buf_, len_)			\
386	do {					\
387		if (0x01 & debug)		\
388			DUMP(buf_, len_);	\
389	} while (0)
390#else
391#define DUMP(buf_, len_)
392#define DUMP1(buf_, len_)
393#endif
394
395/* module parameters */
396static int debug;
397static int tty_major;
398static int disable_net;
399
400/* driver info */
401static const char driver_name[] = "hso";
402static const char tty_filename[] = "ttyHS";
403static const char *version = __FILE__ ": " MOD_AUTHOR;
404/* the usb driver itself (registered in hso_init) */
405static struct usb_driver hso_driver;
406/* serial structures */
407static struct tty_driver *tty_drv;
408static struct hso_device *serial_table[HSO_SERIAL_TTY_MINORS];
409static struct hso_device *network_table[HSO_MAX_NET_DEVICES];
410static spinlock_t serial_table_lock;
411
412static const s32 default_port_spec[] = {
413	HSO_INTF_MUX | HSO_PORT_NETWORK,
414	HSO_INTF_BULK | HSO_PORT_DIAG,
415	HSO_INTF_BULK | HSO_PORT_MODEM,
416	0
417};
418
419static const s32 icon321_port_spec[] = {
420	HSO_INTF_MUX | HSO_PORT_NETWORK,
421	HSO_INTF_BULK | HSO_PORT_DIAG2,
422	HSO_INTF_BULK | HSO_PORT_MODEM,
423	HSO_INTF_BULK | HSO_PORT_DIAG,
424	0
425};
426
427#define default_port_device(vendor, product)	\
428	USB_DEVICE(vendor, product),	\
429		.driver_info = (kernel_ulong_t)default_port_spec
430
431#define icon321_port_device(vendor, product)	\
432	USB_DEVICE(vendor, product),	\
433		.driver_info = (kernel_ulong_t)icon321_port_spec
434
435/* list of devices we support */
436static const struct usb_device_id hso_ids[] = {
437	{default_port_device(0x0af0, 0x6711)},
438	{default_port_device(0x0af0, 0x6731)},
439	{default_port_device(0x0af0, 0x6751)},
440	{default_port_device(0x0af0, 0x6771)},
441	{default_port_device(0x0af0, 0x6791)},
442	{default_port_device(0x0af0, 0x6811)},
443	{default_port_device(0x0af0, 0x6911)},
444	{default_port_device(0x0af0, 0x6951)},
445	{default_port_device(0x0af0, 0x6971)},
446	{default_port_device(0x0af0, 0x7011)},
447	{default_port_device(0x0af0, 0x7031)},
448	{default_port_device(0x0af0, 0x7051)},
449	{default_port_device(0x0af0, 0x7071)},
450	{default_port_device(0x0af0, 0x7111)},
451	{default_port_device(0x0af0, 0x7211)},
452	{default_port_device(0x0af0, 0x7251)},
453	{default_port_device(0x0af0, 0x7271)},
454	{default_port_device(0x0af0, 0x7311)},
455	{default_port_device(0x0af0, 0xc031)},	/* Icon-Edge */
456	{icon321_port_device(0x0af0, 0xd013)},	/* Module HSxPA */
457	{icon321_port_device(0x0af0, 0xd031)},	/* Icon-321 */
458	{icon321_port_device(0x0af0, 0xd033)},	/* Icon-322 */
459	{USB_DEVICE(0x0af0, 0x7301)},		/* GE40x */
460	{USB_DEVICE(0x0af0, 0x7361)},		/* GE40x */
461	{USB_DEVICE(0x0af0, 0x7381)},		/* GE40x */
462	{USB_DEVICE(0x0af0, 0x7401)},		/* GI 0401 */
463	{USB_DEVICE(0x0af0, 0x7501)},		/* GTM 382 */
464	{USB_DEVICE(0x0af0, 0x7601)},		/* GE40x */
465	{USB_DEVICE(0x0af0, 0x7701)},
466	{USB_DEVICE(0x0af0, 0x7706)},
467	{USB_DEVICE(0x0af0, 0x7801)},
468	{USB_DEVICE(0x0af0, 0x7901)},
469	{USB_DEVICE(0x0af0, 0x7A01)},
470	{USB_DEVICE(0x0af0, 0x7A05)},
471	{USB_DEVICE(0x0af0, 0x8200)},
472	{USB_DEVICE(0x0af0, 0x8201)},
473	{USB_DEVICE(0x0af0, 0x8300)},
474	{USB_DEVICE(0x0af0, 0x8302)},
475	{USB_DEVICE(0x0af0, 0x8304)},
476	{USB_DEVICE(0x0af0, 0x8400)},
477	{USB_DEVICE(0x0af0, 0x8600)},
478	{USB_DEVICE(0x0af0, 0x8800)},
479	{USB_DEVICE(0x0af0, 0x8900)},
480	{USB_DEVICE(0x0af0, 0x9000)},
481	{USB_DEVICE(0x0af0, 0xd035)},
482	{USB_DEVICE(0x0af0, 0xd055)},
483	{USB_DEVICE(0x0af0, 0xd155)},
484	{USB_DEVICE(0x0af0, 0xd255)},
485	{USB_DEVICE(0x0af0, 0xd057)},
486	{USB_DEVICE(0x0af0, 0xd157)},
487	{USB_DEVICE(0x0af0, 0xd257)},
488	{USB_DEVICE(0x0af0, 0xd357)},
489	{USB_DEVICE(0x0af0, 0xd058)},
490	{USB_DEVICE(0x0af0, 0xc100)},
491	{}
492};
493MODULE_DEVICE_TABLE(usb, hso_ids);
494
495/* Sysfs attribute */
496static ssize_t hso_sysfs_show_porttype(struct device *dev,
497				       struct device_attribute *attr,
498				       char *buf)
499{
500	struct hso_device *hso_dev = dev_get_drvdata(dev);
501	char *port_name;
502
503	if (!hso_dev)
504		return 0;
505
506	switch (hso_dev->port_spec & HSO_PORT_MASK) {
507	case HSO_PORT_CONTROL:
508		port_name = "Control";
509		break;
510	case HSO_PORT_APP:
511		port_name = "Application";
512		break;
513	case HSO_PORT_APP2:
514		port_name = "Application2";
515		break;
516	case HSO_PORT_GPS:
517		port_name = "GPS";
518		break;
519	case HSO_PORT_GPS_CONTROL:
520		port_name = "GPS Control";
521		break;
522	case HSO_PORT_PCSC:
523		port_name = "PCSC";
524		break;
525	case HSO_PORT_DIAG:
526		port_name = "Diagnostic";
527		break;
528	case HSO_PORT_DIAG2:
529		port_name = "Diagnostic2";
530		break;
531	case HSO_PORT_MODEM:
532		port_name = "Modem";
533		break;
534	case HSO_PORT_NETWORK:
535		port_name = "Network";
536		break;
537	default:
538		port_name = "Unknown";
539		break;
540	}
541
542	return sprintf(buf, "%s\n", port_name);
543}
544static DEVICE_ATTR(hsotype, S_IRUGO, hso_sysfs_show_porttype, NULL);
545
546static int hso_urb_to_index(struct hso_serial *serial, struct urb *urb)
547{
548	int idx;
549
550	for (idx = 0; idx < serial->num_rx_urbs; idx++)
551		if (serial->rx_urb[idx] == urb)
552			return idx;
553	dev_err(serial->parent->dev, "hso_urb_to_index failed\n");
554	return -1;
555}
556
557/* converts mux value to a port spec value */
558static u32 hso_mux_to_port(int mux)
559{
560	u32 result;
561
562	switch (mux) {
563	case 0x1:
564		result = HSO_PORT_CONTROL;
565		break;
566	case 0x2:
567		result = HSO_PORT_APP;
568		break;
569	case 0x4:
570		result = HSO_PORT_PCSC;
571		break;
572	case 0x8:
573		result = HSO_PORT_GPS;
574		break;
575	case 0x10:
576		result = HSO_PORT_APP2;
577		break;
578	default:
579		result = HSO_PORT_NO_PORT;
580	}
581	return result;
582}
583
584/* converts port spec value to a mux value */
585static u32 hso_port_to_mux(int port)
586{
587	u32 result;
588
589	switch (port & HSO_PORT_MASK) {
590	case HSO_PORT_CONTROL:
591		result = 0x0;
592		break;
593	case HSO_PORT_APP:
594		result = 0x1;
595		break;
596	case HSO_PORT_PCSC:
597		result = 0x2;
598		break;
599	case HSO_PORT_GPS:
600		result = 0x3;
601		break;
602	case HSO_PORT_APP2:
603		result = 0x4;
604		break;
605	default:
606		result = 0x0;
607	}
608	return result;
609}
610
611static struct hso_serial *get_serial_by_shared_int_and_type(
612					struct hso_shared_int *shared_int,
613					int mux)
614{
615	int i, port;
616
617	port = hso_mux_to_port(mux);
618
619	for (i = 0; i < HSO_SERIAL_TTY_MINORS; i++) {
620		if (serial_table[i] &&
621		    (dev2ser(serial_table[i])->shared_int == shared_int) &&
622		    ((serial_table[i]->port_spec & HSO_PORT_MASK) == port)) {
623			return dev2ser(serial_table[i]);
624		}
625	}
626
627	return NULL;
628}
629
630static struct hso_serial *get_serial_by_index(unsigned index)
631{
632	struct hso_serial *serial = NULL;
633	unsigned long flags;
634
635	spin_lock_irqsave(&serial_table_lock, flags);
636	if (serial_table[index])
637		serial = dev2ser(serial_table[index]);
638	spin_unlock_irqrestore(&serial_table_lock, flags);
639
640	return serial;
641}
642
643static int get_free_serial_index(void)
644{
645	int index;
646	unsigned long flags;
647
648	spin_lock_irqsave(&serial_table_lock, flags);
649	for (index = 0; index < HSO_SERIAL_TTY_MINORS; index++) {
650		if (serial_table[index] == NULL) {
651			spin_unlock_irqrestore(&serial_table_lock, flags);
652			return index;
653		}
654	}
655	spin_unlock_irqrestore(&serial_table_lock, flags);
656
657	printk(KERN_ERR "%s: no free serial devices in table\n", __func__);
658	return -1;
659}
660
661static void set_serial_by_index(unsigned index, struct hso_serial *serial)
662{
663	unsigned long flags;
664
665	spin_lock_irqsave(&serial_table_lock, flags);
666	if (serial)
667		serial_table[index] = serial->parent;
668	else
669		serial_table[index] = NULL;
670	spin_unlock_irqrestore(&serial_table_lock, flags);
671}
672
673static void handle_usb_error(int status, const char *function,
674			     struct hso_device *hso_dev)
675{
676	char *explanation;
677
678	switch (status) {
679	case -ENODEV:
680		explanation = "no device";
681		break;
682	case -ENOENT:
683		explanation = "endpoint not enabled";
684		break;
685	case -EPIPE:
686		explanation = "endpoint stalled";
687		break;
688	case -ENOSPC:
689		explanation = "not enough bandwidth";
690		break;
691	case -ESHUTDOWN:
692		explanation = "device disabled";
693		break;
694	case -EHOSTUNREACH:
695		explanation = "device suspended";
696		break;
697	case -EINVAL:
698	case -EAGAIN:
699	case -EFBIG:
700	case -EMSGSIZE:
701		explanation = "internal error";
702		break;
703	case -EILSEQ:
704	case -EPROTO:
705	case -ETIME:
706	case -ETIMEDOUT:
707		explanation = "protocol error";
708		if (hso_dev)
709			schedule_work(&hso_dev->reset_device);
710		break;
711	default:
712		explanation = "unknown status";
713		break;
714	}
715
716	/* log a meaningful explanation of an USB status */
717	D1("%s: received USB status - %s (%d)", function, explanation, status);
718}
719
720/* Network interface functions */
721
722/* called when net interface is brought up by ifconfig */
723static int hso_net_open(struct net_device *net)
724{
725	struct hso_net *odev = netdev_priv(net);
726	unsigned long flags = 0;
727
728	if (!odev) {
729		dev_err(&net->dev, "No net device !\n");
730		return -ENODEV;
731	}
732
733	odev->skb_tx_buf = NULL;
734
735	/* setup environment */
736	spin_lock_irqsave(&odev->net_lock, flags);
737	odev->rx_parse_state = WAIT_IP;
738	odev->rx_buf_size = 0;
739	odev->rx_buf_missing = sizeof(struct iphdr);
740	spin_unlock_irqrestore(&odev->net_lock, flags);
741
742	/* We are up and running. */
743	set_bit(HSO_NET_RUNNING, &odev->flags);
744	hso_start_net_device(odev->parent);
745
746	/* Tell the kernel we are ready to start receiving from it */
747	netif_start_queue(net);
748
749	return 0;
750}
751
752/* called when interface is brought down by ifconfig */
753static int hso_net_close(struct net_device *net)
754{
755	struct hso_net *odev = netdev_priv(net);
756
757	/* we don't need the queue anymore */
758	netif_stop_queue(net);
759	/* no longer running */
760	clear_bit(HSO_NET_RUNNING, &odev->flags);
761
762	hso_stop_net_device(odev->parent);
763
764	/* done */
765	return 0;
766}
767
768/* USB tells is xmit done, we should start the netqueue again */
769static void write_bulk_callback(struct urb *urb)
770{
771	struct hso_net *odev = urb->context;
772	int status = urb->status;
773
774	/* Sanity check */
775	if (!odev || !test_bit(HSO_NET_RUNNING, &odev->flags)) {
776		dev_err(&urb->dev->dev, "%s: device not running\n", __func__);
777		return;
778	}
779
780	/* Do we still have a valid kernel network device? */
781	if (!netif_device_present(odev->net)) {
782		dev_err(&urb->dev->dev, "%s: net device not present\n",
783			__func__);
784		return;
785	}
786
787	/* log status, but don't act on it, we don't need to resubmit anything
788	 * anyhow */
789	if (status)
790		handle_usb_error(status, __func__, odev->parent);
791
792	hso_put_activity(odev->parent);
793
794	/* Tell the network interface we are ready for another frame */
795	netif_wake_queue(odev->net);
796}
797
798/* called by kernel when we need to transmit a packet */
799static netdev_tx_t hso_net_start_xmit(struct sk_buff *skb,
800					    struct net_device *net)
801{
802	struct hso_net *odev = netdev_priv(net);
803	int result;
804
805	/* Tell the kernel, "No more frames 'til we are done with this one." */
806	netif_stop_queue(net);
807	if (hso_get_activity(odev->parent) == -EAGAIN) {
808		odev->skb_tx_buf = skb;
809		return NETDEV_TX_OK;
810	}
811
812	/* log if asked */
813	DUMP1(skb->data, skb->len);
814	/* Copy it from kernel memory to OUR memory */
815	memcpy(odev->mux_bulk_tx_buf, skb->data, skb->len);
816	D1("len: %d/%d", skb->len, MUX_BULK_TX_BUF_SIZE);
817
818	/* Fill in the URB for shipping it out. */
819	usb_fill_bulk_urb(odev->mux_bulk_tx_urb,
820			  odev->parent->usb,
821			  usb_sndbulkpipe(odev->parent->usb,
822					  odev->out_endp->
823					  bEndpointAddress & 0x7F),
824			  odev->mux_bulk_tx_buf, skb->len, write_bulk_callback,
825			  odev);
826
827	/* Deal with the Zero Length packet problem, I hope */
828	odev->mux_bulk_tx_urb->transfer_flags |= URB_ZERO_PACKET;
829
830	/* Send the URB on its merry way. */
831	result = usb_submit_urb(odev->mux_bulk_tx_urb, GFP_ATOMIC);
832	if (result) {
833		dev_warn(&odev->parent->interface->dev,
834			"failed mux_bulk_tx_urb %d\n", result);
835		net->stats.tx_errors++;
836		netif_start_queue(net);
837	} else {
838		net->stats.tx_packets++;
839		net->stats.tx_bytes += skb->len;
840	}
841	dev_kfree_skb(skb);
842	/* we're done */
843	return NETDEV_TX_OK;
844}
845
846static const struct ethtool_ops ops = {
847	.get_link = ethtool_op_get_link
848};
849
850/* called when a packet did not ack after watchdogtimeout */
851static void hso_net_tx_timeout(struct net_device *net)
852{
853	struct hso_net *odev = netdev_priv(net);
854
855	if (!odev)
856		return;
857
858	/* Tell syslog we are hosed. */
859	dev_warn(&net->dev, "Tx timed out.\n");
860
861	/* Tear the waiting frame off the list */
862	if (odev->mux_bulk_tx_urb &&
863	    (odev->mux_bulk_tx_urb->status == -EINPROGRESS))
864		usb_unlink_urb(odev->mux_bulk_tx_urb);
865
866	/* Update statistics */
867	net->stats.tx_errors++;
868}
869
870/* make a real packet from the received USB buffer */
871static void packetizeRx(struct hso_net *odev, unsigned char *ip_pkt,
872			unsigned int count, unsigned char is_eop)
873{
874	unsigned short temp_bytes;
875	unsigned short buffer_offset = 0;
876	unsigned short frame_len;
877	unsigned char *tmp_rx_buf;
878
879	/* log if needed */
880	D1("Rx %d bytes", count);
881	DUMP(ip_pkt, min(128, (int)count));
882
883	while (count) {
884		switch (odev->rx_parse_state) {
885		case WAIT_IP:
886			/* waiting for IP header. */
887			/* wanted bytes - size of ip header */
888			temp_bytes =
889			    (count <
890			     odev->rx_buf_missing) ? count : odev->
891			    rx_buf_missing;
892
893			memcpy(((unsigned char *)(&odev->rx_ip_hdr)) +
894			       odev->rx_buf_size, ip_pkt + buffer_offset,
895			       temp_bytes);
896
897			odev->rx_buf_size += temp_bytes;
898			buffer_offset += temp_bytes;
899			odev->rx_buf_missing -= temp_bytes;
900			count -= temp_bytes;
901
902			if (!odev->rx_buf_missing) {
903				/* header is complete allocate an sk_buffer and
904				 * continue to WAIT_DATA */
905				frame_len = ntohs(odev->rx_ip_hdr.tot_len);
906
907				if ((frame_len > DEFAULT_MRU) ||
908				    (frame_len < sizeof(struct iphdr))) {
909					dev_err(&odev->net->dev,
910						"Invalid frame (%d) length\n",
911						frame_len);
912					odev->rx_parse_state = WAIT_SYNC;
913					continue;
914				}
915				/* Allocate an sk_buff */
916				odev->skb_rx_buf = netdev_alloc_skb(odev->net,
917								    frame_len);
918				if (!odev->skb_rx_buf) {
919					/* We got no receive buffer. */
920					D1("could not allocate memory");
921					odev->rx_parse_state = WAIT_SYNC;
922					return;
923				}
924
925				/* Copy what we got so far. make room for iphdr
926				 * after tail. */
927				tmp_rx_buf =
928				    skb_put(odev->skb_rx_buf,
929					    sizeof(struct iphdr));
930				memcpy(tmp_rx_buf, (char *)&(odev->rx_ip_hdr),
931				       sizeof(struct iphdr));
932
933				/* ETH_HLEN */
934				odev->rx_buf_size = sizeof(struct iphdr);
935
936				/* Filip actually use .tot_len */
937				odev->rx_buf_missing =
938				    frame_len - sizeof(struct iphdr);
939				odev->rx_parse_state = WAIT_DATA;
940			}
941			break;
942
943		case WAIT_DATA:
944			temp_bytes = (count < odev->rx_buf_missing)
945					? count : odev->rx_buf_missing;
946
947			/* Copy the rest of the bytes that are left in the
948			 * buffer into the waiting sk_buf. */
949			/* Make room for temp_bytes after tail. */
950			tmp_rx_buf = skb_put(odev->skb_rx_buf, temp_bytes);
951			memcpy(tmp_rx_buf, ip_pkt + buffer_offset, temp_bytes);
952
953			odev->rx_buf_missing -= temp_bytes;
954			count -= temp_bytes;
955			buffer_offset += temp_bytes;
956			odev->rx_buf_size += temp_bytes;
957			if (!odev->rx_buf_missing) {
958				/* Packet is complete. Inject into stack. */
959				/* We have IP packet here */
960				odev->skb_rx_buf->protocol = cpu_to_be16(ETH_P_IP);
961				skb_reset_mac_header(odev->skb_rx_buf);
962
963				/* Ship it off to the kernel */
964				netif_rx(odev->skb_rx_buf);
965				/* No longer our buffer. */
966				odev->skb_rx_buf = NULL;
967
968				/* update out statistics */
969				odev->net->stats.rx_packets++;
970
971				odev->net->stats.rx_bytes += odev->rx_buf_size;
972
973				odev->rx_buf_size = 0;
974				odev->rx_buf_missing = sizeof(struct iphdr);
975				odev->rx_parse_state = WAIT_IP;
976			}
977			break;
978
979		case WAIT_SYNC:
980			D1(" W_S");
981			count = 0;
982			break;
983		default:
984			D1(" ");
985			count--;
986			break;
987		}
988	}
989
990	/* Recovery mechanism for WAIT_SYNC state. */
991	if (is_eop) {
992		if (odev->rx_parse_state == WAIT_SYNC) {
993			odev->rx_parse_state = WAIT_IP;
994			odev->rx_buf_size = 0;
995			odev->rx_buf_missing = sizeof(struct iphdr);
996		}
997	}
998}
999
1000static void fix_crc_bug(struct urb *urb, __le16 max_packet_size)
1001{
1002	static const u8 crc_check[4] = { 0xDE, 0xAD, 0xBE, 0xEF };
1003	u32 rest = urb->actual_length % le16_to_cpu(max_packet_size);
1004
1005	if (((rest == 5) || (rest == 6)) &&
1006	    !memcmp(((u8 *)urb->transfer_buffer) + urb->actual_length - 4,
1007		    crc_check, 4)) {
1008		urb->actual_length -= 4;
1009	}
1010}
1011
1012/* Moving data from usb to kernel (in interrupt state) */
1013static void read_bulk_callback(struct urb *urb)
1014{
1015	struct hso_net *odev = urb->context;
1016	struct net_device *net;
1017	int result;
1018	int status = urb->status;
1019
1020	/* is al ok?  (Filip: Who's Al ?) */
1021	if (status) {
1022		handle_usb_error(status, __func__, odev->parent);
1023		return;
1024	}
1025
1026	/* Sanity check */
1027	if (!odev || !test_bit(HSO_NET_RUNNING, &odev->flags)) {
1028		D1("BULK IN callback but driver is not active!");
1029		return;
1030	}
1031	usb_mark_last_busy(urb->dev);
1032
1033	net = odev->net;
1034
1035	if (!netif_device_present(net)) {
1036		/* Somebody killed our network interface... */
1037		return;
1038	}
1039
1040	if (odev->parent->port_spec & HSO_INFO_CRC_BUG)
1041		fix_crc_bug(urb, odev->in_endp->wMaxPacketSize);
1042
1043	/* do we even have a packet? */
1044	if (urb->actual_length) {
1045		/* Handle the IP stream, add header and push it onto network
1046		 * stack if the packet is complete. */
1047		spin_lock(&odev->net_lock);
1048		packetizeRx(odev, urb->transfer_buffer, urb->actual_length,
1049			    (urb->transfer_buffer_length >
1050			     urb->actual_length) ? 1 : 0);
1051		spin_unlock(&odev->net_lock);
1052	}
1053
1054	/* We are done with this URB, resubmit it. Prep the USB to wait for
1055	 * another frame. Reuse same as received. */
1056	usb_fill_bulk_urb(urb,
1057			  odev->parent->usb,
1058			  usb_rcvbulkpipe(odev->parent->usb,
1059					  odev->in_endp->
1060					  bEndpointAddress & 0x7F),
1061			  urb->transfer_buffer, MUX_BULK_RX_BUF_SIZE,
1062			  read_bulk_callback, odev);
1063
1064	/* Give this to the USB subsystem so it can tell us when more data
1065	 * arrives. */
1066	result = usb_submit_urb(urb, GFP_ATOMIC);
1067	if (result)
1068		dev_warn(&odev->parent->interface->dev,
1069			 "%s failed submit mux_bulk_rx_urb %d\n", __func__,
1070			 result);
1071}
1072
1073/* Serial driver functions */
1074
1075static void hso_init_termios(struct ktermios *termios)
1076{
1077	/*
1078	 * The default requirements for this device are:
1079	 */
1080	termios->c_iflag &=
1081		~(IGNBRK	/* disable ignore break */
1082		| BRKINT	/* disable break causes interrupt */
1083		| PARMRK	/* disable mark parity errors */
1084		| ISTRIP	/* disable clear high bit of input characters */
1085		| INLCR		/* disable translate NL to CR */
1086		| IGNCR		/* disable ignore CR */
1087		| ICRNL		/* disable translate CR to NL */
1088		| IXON);	/* disable enable XON/XOFF flow control */
1089
1090	/* disable postprocess output characters */
1091	termios->c_oflag &= ~OPOST;
1092
1093	termios->c_lflag &=
1094		~(ECHO		/* disable echo input characters */
1095		| ECHONL	/* disable echo new line */
1096		| ICANON	/* disable erase, kill, werase, and rprnt
1097				   special characters */
1098		| ISIG		/* disable interrupt, quit, and suspend special
1099				   characters */
1100		| IEXTEN);	/* disable non-POSIX special characters */
1101
1102	termios->c_cflag &=
1103		~(CSIZE		/* no size */
1104		| PARENB	/* disable parity bit */
1105		| CBAUD		/* clear current baud rate */
1106		| CBAUDEX);	/* clear current buad rate */
1107
1108	termios->c_cflag |= CS8;	/* character size 8 bits */
1109
1110	/* baud rate 115200 */
1111	tty_termios_encode_baud_rate(termios, 115200, 115200);
1112}
1113
1114static void _hso_serial_set_termios(struct tty_struct *tty,
1115				    struct ktermios *old)
1116{
1117	struct hso_serial *serial = get_serial_by_tty(tty);
1118	struct ktermios *termios;
1119
1120	if (!serial) {
1121		printk(KERN_ERR "%s: no tty structures", __func__);
1122		return;
1123	}
1124
1125	D4("port %d", serial->minor);
1126
1127	/*
1128	 *	Fix up unsupported bits
1129	 */
1130	termios = tty->termios;
1131	termios->c_iflag &= ~IXON; /* disable enable XON/XOFF flow control */
1132
1133	termios->c_cflag &=
1134		~(CSIZE		/* no size */
1135		| PARENB	/* disable parity bit */
1136		| CBAUD		/* clear current baud rate */
1137		| CBAUDEX);	/* clear current buad rate */
1138
1139	termios->c_cflag |= CS8;	/* character size 8 bits */
1140
1141	/* baud rate 115200 */
1142	tty_encode_baud_rate(tty, 115200, 115200);
1143}
1144
1145static void hso_resubmit_rx_bulk_urb(struct hso_serial *serial, struct urb *urb)
1146{
1147	int result;
1148	/* We are done with this URB, resubmit it. Prep the USB to wait for
1149	 * another frame */
1150	usb_fill_bulk_urb(urb, serial->parent->usb,
1151			  usb_rcvbulkpipe(serial->parent->usb,
1152					  serial->in_endp->
1153					  bEndpointAddress & 0x7F),
1154			  urb->transfer_buffer, serial->rx_data_length,
1155			  hso_std_serial_read_bulk_callback, serial);
1156	/* Give this to the USB subsystem so it can tell us when more data
1157	 * arrives. */
1158	result = usb_submit_urb(urb, GFP_ATOMIC);
1159	if (result) {
1160		dev_err(&urb->dev->dev, "%s failed submit serial rx_urb %d\n",
1161			__func__, result);
1162	}
1163}
1164
1165
1166
1167
1168static void put_rxbuf_data_and_resubmit_bulk_urb(struct hso_serial *serial)
1169{
1170	int count;
1171	struct urb *curr_urb;
1172
1173	while (serial->rx_urb_filled[serial->curr_rx_urb_idx]) {
1174		curr_urb = serial->rx_urb[serial->curr_rx_urb_idx];
1175		count = put_rxbuf_data(curr_urb, serial);
1176		if (count == -1)
1177			return;
1178		if (count == 0) {
1179			serial->curr_rx_urb_idx++;
1180			if (serial->curr_rx_urb_idx >= serial->num_rx_urbs)
1181				serial->curr_rx_urb_idx = 0;
1182			hso_resubmit_rx_bulk_urb(serial, curr_urb);
1183		}
1184	}
1185}
1186
1187static void put_rxbuf_data_and_resubmit_ctrl_urb(struct hso_serial *serial)
1188{
1189	int count = 0;
1190	struct urb *urb;
1191
1192	urb = serial->rx_urb[0];
1193	if (serial->open_count > 0) {
1194		count = put_rxbuf_data(urb, serial);
1195		if (count == -1)
1196			return;
1197	}
1198	/* Re issue a read as long as we receive data. */
1199
1200	if (count == 0 && ((urb->actual_length != 0) ||
1201			   (serial->rx_state == RX_PENDING))) {
1202		serial->rx_state = RX_SENT;
1203		hso_mux_serial_read(serial);
1204	} else
1205		serial->rx_state = RX_IDLE;
1206}
1207
1208
1209/* read callback for Diag and CS port */
1210static void hso_std_serial_read_bulk_callback(struct urb *urb)
1211{
1212	struct hso_serial *serial = urb->context;
1213	int status = urb->status;
1214
1215	/* sanity check */
1216	if (!serial) {
1217		D1("serial == NULL");
1218		return;
1219	} else if (status) {
1220		handle_usb_error(status, __func__, serial->parent);
1221		return;
1222	}
1223
1224	D4("\n--- Got serial_read_bulk callback %02x ---", status);
1225	D1("Actual length = %d\n", urb->actual_length);
1226	DUMP1(urb->transfer_buffer, urb->actual_length);
1227
1228	/* Anyone listening? */
1229	if (serial->open_count == 0)
1230		return;
1231
1232	if (status == 0) {
1233		if (serial->parent->port_spec & HSO_INFO_CRC_BUG)
1234			fix_crc_bug(urb, serial->in_endp->wMaxPacketSize);
1235		/* Valid data, handle RX data */
1236		spin_lock(&serial->serial_lock);
1237		serial->rx_urb_filled[hso_urb_to_index(serial, urb)] = 1;
1238		put_rxbuf_data_and_resubmit_bulk_urb(serial);
1239		spin_unlock(&serial->serial_lock);
1240	} else if (status == -ENOENT || status == -ECONNRESET) {
1241		/* Unlinked - check for throttled port. */
1242		D2("Port %d, successfully unlinked urb", serial->minor);
1243		spin_lock(&serial->serial_lock);
1244		serial->rx_urb_filled[hso_urb_to_index(serial, urb)] = 0;
1245		hso_resubmit_rx_bulk_urb(serial, urb);
1246		spin_unlock(&serial->serial_lock);
1247	} else {
1248		D2("Port %d, status = %d for read urb", serial->minor, status);
1249		return;
1250	}
1251}
1252
1253/*
1254 * This needs to be a tasklet otherwise we will
1255 * end up recursively calling this function.
1256 */
1257static void hso_unthrottle_tasklet(struct hso_serial *serial)
1258{
1259	unsigned long flags;
1260
1261	spin_lock_irqsave(&serial->serial_lock, flags);
1262	if ((serial->parent->port_spec & HSO_INTF_MUX))
1263		put_rxbuf_data_and_resubmit_ctrl_urb(serial);
1264	else
1265		put_rxbuf_data_and_resubmit_bulk_urb(serial);
1266	spin_unlock_irqrestore(&serial->serial_lock, flags);
1267}
1268
1269static	void hso_unthrottle(struct tty_struct *tty)
1270{
1271	struct hso_serial *serial = get_serial_by_tty(tty);
1272
1273	tasklet_hi_schedule(&serial->unthrottle_tasklet);
1274}
1275
1276static void hso_unthrottle_workfunc(struct work_struct *work)
1277{
1278	struct hso_serial *serial =
1279	    container_of(work, struct hso_serial,
1280			 retry_unthrottle_workqueue);
1281	hso_unthrottle_tasklet(serial);
1282}
1283
1284/* open the requested serial port */
1285static int hso_serial_open(struct tty_struct *tty, struct file *filp)
1286{
1287	struct hso_serial *serial = get_serial_by_index(tty->index);
1288	int result;
1289
1290	/* sanity check */
1291	if (serial == NULL || serial->magic != HSO_SERIAL_MAGIC) {
1292		WARN_ON(1);
1293		tty->driver_data = NULL;
1294		D1("Failed to open port");
1295		return -ENODEV;
1296	}
1297
1298	mutex_lock(&serial->parent->mutex);
1299	result = usb_autopm_get_interface(serial->parent->interface);
1300	if (result < 0)
1301		goto err_out;
1302
1303	D1("Opening %d", serial->minor);
1304	kref_get(&serial->parent->ref);
1305
1306	/* setup */
1307	spin_lock_irq(&serial->serial_lock);
1308	tty->driver_data = serial;
1309	tty_kref_put(serial->tty);
1310	serial->tty = tty_kref_get(tty);
1311	spin_unlock_irq(&serial->serial_lock);
1312
1313	/* check for port already opened, if not set the termios */
1314	serial->open_count++;
1315	if (serial->open_count == 1) {
1316		serial->rx_state = RX_IDLE;
1317		/* Force default termio settings */
1318		_hso_serial_set_termios(tty, NULL);
1319		tasklet_init(&serial->unthrottle_tasklet,
1320			     (void (*)(unsigned long))hso_unthrottle_tasklet,
1321			     (unsigned long)serial);
1322		INIT_WORK(&serial->retry_unthrottle_workqueue,
1323			  hso_unthrottle_workfunc);
1324		result = hso_start_serial_device(serial->parent, GFP_KERNEL);
1325		if (result) {
1326			hso_stop_serial_device(serial->parent);
1327			serial->open_count--;
1328			kref_put(&serial->parent->ref, hso_serial_ref_free);
1329		}
1330	} else {
1331		D1("Port was already open");
1332	}
1333
1334	usb_autopm_put_interface(serial->parent->interface);
1335
1336	/* done */
1337	if (result)
1338		hso_serial_tiocmset(tty, TIOCM_RTS | TIOCM_DTR, 0);
1339err_out:
1340	mutex_unlock(&serial->parent->mutex);
1341	return result;
1342}
1343
1344/* close the requested serial port */
1345static void hso_serial_close(struct tty_struct *tty, struct file *filp)
1346{
1347	struct hso_serial *serial = tty->driver_data;
1348	u8 usb_gone;
1349
1350	D1("Closing serial port");
1351
1352	/* Open failed, no close cleanup required */
1353	if (serial == NULL)
1354		return;
1355
1356	mutex_lock(&serial->parent->mutex);
1357	usb_gone = serial->parent->usb_gone;
1358
1359	if (!usb_gone)
1360		usb_autopm_get_interface(serial->parent->interface);
1361
1362	/* reset the rts and dtr */
1363	/* do the actual close */
1364	serial->open_count--;
1365
1366	if (serial->open_count <= 0) {
1367		serial->open_count = 0;
1368		spin_lock_irq(&serial->serial_lock);
1369		if (serial->tty == tty) {
1370			serial->tty->driver_data = NULL;
1371			serial->tty = NULL;
1372			tty_kref_put(tty);
1373		}
1374		spin_unlock_irq(&serial->serial_lock);
1375		if (!usb_gone)
1376			hso_stop_serial_device(serial->parent);
1377		tasklet_kill(&serial->unthrottle_tasklet);
1378		cancel_work_sync(&serial->retry_unthrottle_workqueue);
1379	}
1380
1381	if (!usb_gone)
1382		usb_autopm_put_interface(serial->parent->interface);
1383
1384	mutex_unlock(&serial->parent->mutex);
1385
1386	kref_put(&serial->parent->ref, hso_serial_ref_free);
1387}
1388
1389/* close the requested serial port */
1390static int hso_serial_write(struct tty_struct *tty, const unsigned char *buf,
1391			    int count)
1392{
1393	struct hso_serial *serial = get_serial_by_tty(tty);
1394	int space, tx_bytes;
1395	unsigned long flags;
1396
1397	/* sanity check */
1398	if (serial == NULL) {
1399		printk(KERN_ERR "%s: serial is NULL\n", __func__);
1400		return -ENODEV;
1401	}
1402
1403	spin_lock_irqsave(&serial->serial_lock, flags);
1404
1405	space = serial->tx_data_length - serial->tx_buffer_count;
1406	tx_bytes = (count < space) ? count : space;
1407
1408	if (!tx_bytes)
1409		goto out;
1410
1411	memcpy(serial->tx_buffer + serial->tx_buffer_count, buf, tx_bytes);
1412	serial->tx_buffer_count += tx_bytes;
1413
1414out:
1415	spin_unlock_irqrestore(&serial->serial_lock, flags);
1416
1417	hso_kick_transmit(serial);
1418	/* done */
1419	return tx_bytes;
1420}
1421
1422/* how much room is there for writing */
1423static int hso_serial_write_room(struct tty_struct *tty)
1424{
1425	struct hso_serial *serial = get_serial_by_tty(tty);
1426	int room;
1427	unsigned long flags;
1428
1429	spin_lock_irqsave(&serial->serial_lock, flags);
1430	room = serial->tx_data_length - serial->tx_buffer_count;
1431	spin_unlock_irqrestore(&serial->serial_lock, flags);
1432
1433	/* return free room */
1434	return room;
1435}
1436
1437/* setup the term */
1438static void hso_serial_set_termios(struct tty_struct *tty, struct ktermios *old)
1439{
1440	struct hso_serial *serial = get_serial_by_tty(tty);
1441	unsigned long flags;
1442
1443	if (old)
1444		D5("Termios called with: cflags new[%d] - old[%d]",
1445		   tty->termios->c_cflag, old->c_cflag);
1446
1447	/* the actual setup */
1448	spin_lock_irqsave(&serial->serial_lock, flags);
1449	if (serial->open_count)
1450		_hso_serial_set_termios(tty, old);
1451	else
1452		tty->termios = old;
1453	spin_unlock_irqrestore(&serial->serial_lock, flags);
1454
1455	/* done */
1456}
1457
1458/* how many characters in the buffer */
1459static int hso_serial_chars_in_buffer(struct tty_struct *tty)
1460{
1461	struct hso_serial *serial = get_serial_by_tty(tty);
1462	int chars;
1463	unsigned long flags;
1464
1465	/* sanity check */
1466	if (serial == NULL)
1467		return 0;
1468
1469	spin_lock_irqsave(&serial->serial_lock, flags);
1470	chars = serial->tx_buffer_count;
1471	spin_unlock_irqrestore(&serial->serial_lock, flags);
1472
1473	return chars;
1474}
1475static int tiocmget_submit_urb(struct hso_serial *serial,
1476			       struct hso_tiocmget *tiocmget,
1477			       struct usb_device *usb)
1478{
1479	int result;
1480
1481	if (serial->parent->usb_gone)
1482		return -ENODEV;
1483	usb_fill_int_urb(tiocmget->urb, usb,
1484			 usb_rcvintpipe(usb,
1485					tiocmget->endp->
1486					bEndpointAddress & 0x7F),
1487			 &tiocmget->serial_state_notification,
1488			 sizeof(struct hso_serial_state_notification),
1489			 tiocmget_intr_callback, serial,
1490			 tiocmget->endp->bInterval);
1491	result = usb_submit_urb(tiocmget->urb, GFP_ATOMIC);
1492	if (result) {
1493		dev_warn(&usb->dev, "%s usb_submit_urb failed %d\n", __func__,
1494			 result);
1495	}
1496	return result;
1497
1498}
1499
1500static void tiocmget_intr_callback(struct urb *urb)
1501{
1502	struct hso_serial *serial = urb->context;
1503	struct hso_tiocmget *tiocmget;
1504	int status = urb->status;
1505	u16 UART_state_bitmap, prev_UART_state_bitmap;
1506	struct uart_icount *icount;
1507	struct hso_serial_state_notification *serial_state_notification;
1508	struct usb_device *usb;
1509
1510	/* Sanity checks */
1511	if (!serial)
1512		return;
1513	if (status) {
1514		handle_usb_error(status, __func__, serial->parent);
1515		return;
1516	}
1517	tiocmget = serial->tiocmget;
1518	if (!tiocmget)
1519		return;
1520	usb = serial->parent->usb;
1521	serial_state_notification = &tiocmget->serial_state_notification;
1522	if (serial_state_notification->bmRequestType != BM_REQUEST_TYPE ||
1523	    serial_state_notification->bNotification != B_NOTIFICATION ||
1524	    le16_to_cpu(serial_state_notification->wValue) != W_VALUE ||
1525	    le16_to_cpu(serial_state_notification->wIndex) != W_INDEX ||
1526	    le16_to_cpu(serial_state_notification->wLength) != W_LENGTH) {
1527		dev_warn(&usb->dev,
1528			 "hso received invalid serial state notification\n");
1529		DUMP(serial_state_notification,
1530		     sizeof(struct hso_serial_state_notification));
1531	} else {
1532
1533		UART_state_bitmap = le16_to_cpu(serial_state_notification->
1534						UART_state_bitmap);
1535		prev_UART_state_bitmap = tiocmget->prev_UART_state_bitmap;
1536		icount = &tiocmget->icount;
1537		spin_lock(&serial->serial_lock);
1538		if ((UART_state_bitmap & B_OVERRUN) !=
1539		   (prev_UART_state_bitmap & B_OVERRUN))
1540			icount->parity++;
1541		if ((UART_state_bitmap & B_PARITY) !=
1542		   (prev_UART_state_bitmap & B_PARITY))
1543			icount->parity++;
1544		if ((UART_state_bitmap & B_FRAMING) !=
1545		   (prev_UART_state_bitmap & B_FRAMING))
1546			icount->frame++;
1547		if ((UART_state_bitmap & B_RING_SIGNAL) &&
1548		   !(prev_UART_state_bitmap & B_RING_SIGNAL))
1549			icount->rng++;
1550		if ((UART_state_bitmap & B_BREAK) !=
1551		   (prev_UART_state_bitmap & B_BREAK))
1552			icount->brk++;
1553		if ((UART_state_bitmap & B_TX_CARRIER) !=
1554		   (prev_UART_state_bitmap & B_TX_CARRIER))
1555			icount->dsr++;
1556		if ((UART_state_bitmap & B_RX_CARRIER) !=
1557		   (prev_UART_state_bitmap & B_RX_CARRIER))
1558			icount->dcd++;
1559		tiocmget->prev_UART_state_bitmap = UART_state_bitmap;
1560		spin_unlock(&serial->serial_lock);
1561		tiocmget->intr_completed = 1;
1562		wake_up_interruptible(&tiocmget->waitq);
1563	}
1564	memset(serial_state_notification, 0,
1565	       sizeof(struct hso_serial_state_notification));
1566	tiocmget_submit_urb(serial,
1567			    tiocmget,
1568			    serial->parent->usb);
1569}
1570
1571/*
1572 * next few functions largely stolen from drivers/serial/serial_core.c
1573 */
1574/* Wait for any of the 4 modem inputs (DCD,RI,DSR,CTS) to change
1575 * - mask passed in arg for lines of interest
1576 *   (use |'ed TIOCM_RNG/DSR/CD/CTS for masking)
1577 * Caller should use TIOCGICOUNT to see which one it was
1578 */
1579static int
1580hso_wait_modem_status(struct hso_serial *serial, unsigned long arg)
1581{
1582	DECLARE_WAITQUEUE(wait, current);
1583	struct uart_icount cprev, cnow;
1584	struct hso_tiocmget  *tiocmget;
1585	int ret;
1586
1587	tiocmget = serial->tiocmget;
1588	if (!tiocmget)
1589		return -ENOENT;
1590	/*
1591	 * note the counters on entry
1592	 */
1593	spin_lock_irq(&serial->serial_lock);
1594	memcpy(&cprev, &tiocmget->icount, sizeof(struct uart_icount));
1595	spin_unlock_irq(&serial->serial_lock);
1596	add_wait_queue(&tiocmget->waitq, &wait);
1597	for (;;) {
1598		spin_lock_irq(&serial->serial_lock);
1599		memcpy(&cnow, &tiocmget->icount, sizeof(struct uart_icount));
1600		spin_unlock_irq(&serial->serial_lock);
1601		set_current_state(TASK_INTERRUPTIBLE);
1602		if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
1603		    ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
1604		    ((arg & TIOCM_CD)  && (cnow.dcd != cprev.dcd))) {
1605			ret = 0;
1606			break;
1607		}
1608		schedule();
1609		/* see if a signal did it */
1610		if (signal_pending(current)) {
1611			ret = -ERESTARTSYS;
1612			break;
1613		}
1614		cprev = cnow;
1615	}
1616	current->state = TASK_RUNNING;
1617	remove_wait_queue(&tiocmget->waitq, &wait);
1618
1619	return ret;
1620}
1621
1622/*
1623 * Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
1624 * Return: write counters to the user passed counter struct
1625 * NB: both 1->0 and 0->1 transitions are counted except for
1626 *     RI where only 0->1 is counted.
1627 */
1628static int hso_get_count(struct tty_struct *tty,
1629		  struct serial_icounter_struct *icount)
1630{
1631	struct uart_icount cnow;
1632	struct hso_serial *serial = get_serial_by_tty(tty);
1633	struct hso_tiocmget  *tiocmget = serial->tiocmget;
1634
1635	memset(icount, 0, sizeof(struct serial_icounter_struct));
1636
1637	if (!tiocmget)
1638		 return -ENOENT;
1639	spin_lock_irq(&serial->serial_lock);
1640	memcpy(&cnow, &tiocmget->icount, sizeof(struct uart_icount));
1641	spin_unlock_irq(&serial->serial_lock);
1642
1643	icount->cts         = cnow.cts;
1644	icount->dsr         = cnow.dsr;
1645	icount->rng         = cnow.rng;
1646	icount->dcd         = cnow.dcd;
1647	icount->rx          = cnow.rx;
1648	icount->tx          = cnow.tx;
1649	icount->frame       = cnow.frame;
1650	icount->overrun     = cnow.overrun;
1651	icount->parity      = cnow.parity;
1652	icount->brk         = cnow.brk;
1653	icount->buf_overrun = cnow.buf_overrun;
1654
1655	return 0;
1656}
1657
1658
1659static int hso_serial_tiocmget(struct tty_struct *tty)
1660{
1661	int retval;
1662	struct hso_serial *serial = get_serial_by_tty(tty);
1663	struct hso_tiocmget  *tiocmget;
1664	u16 UART_state_bitmap;
1665
1666	/* sanity check */
1667	if (!serial) {
1668		D1("no tty structures");
1669		return -EINVAL;
1670	}
1671	spin_lock_irq(&serial->serial_lock);
1672	retval = ((serial->rts_state) ? TIOCM_RTS : 0) |
1673	    ((serial->dtr_state) ? TIOCM_DTR : 0);
1674	tiocmget = serial->tiocmget;
1675	if (tiocmget) {
1676
1677		UART_state_bitmap = le16_to_cpu(
1678			tiocmget->prev_UART_state_bitmap);
1679		if (UART_state_bitmap & B_RING_SIGNAL)
1680			retval |=  TIOCM_RNG;
1681		if (UART_state_bitmap & B_RX_CARRIER)
1682			retval |=  TIOCM_CD;
1683		if (UART_state_bitmap & B_TX_CARRIER)
1684			retval |=  TIOCM_DSR;
1685	}
1686	spin_unlock_irq(&serial->serial_lock);
1687	return retval;
1688}
1689
1690static int hso_serial_tiocmset(struct tty_struct *tty,
1691			       unsigned int set, unsigned int clear)
1692{
1693	int val = 0;
1694	unsigned long flags;
1695	int if_num;
1696	struct hso_serial *serial = get_serial_by_tty(tty);
1697
1698	/* sanity check */
1699	if (!serial) {
1700		D1("no tty structures");
1701		return -EINVAL;
1702	}
1703
1704	if ((serial->parent->port_spec & HSO_PORT_MASK) != HSO_PORT_MODEM)
1705		return -EINVAL;
1706
1707	if_num = serial->parent->interface->altsetting->desc.bInterfaceNumber;
1708
1709	spin_lock_irqsave(&serial->serial_lock, flags);
1710	if (set & TIOCM_RTS)
1711		serial->rts_state = 1;
1712	if (set & TIOCM_DTR)
1713		serial->dtr_state = 1;
1714
1715	if (clear & TIOCM_RTS)
1716		serial->rts_state = 0;
1717	if (clear & TIOCM_DTR)
1718		serial->dtr_state = 0;
1719
1720	if (serial->dtr_state)
1721		val |= 0x01;
1722	if (serial->rts_state)
1723		val |= 0x02;
1724
1725	spin_unlock_irqrestore(&serial->serial_lock, flags);
1726
1727	return usb_control_msg(serial->parent->usb,
1728			       usb_rcvctrlpipe(serial->parent->usb, 0), 0x22,
1729			       0x21, val, if_num, NULL, 0,
1730			       USB_CTRL_SET_TIMEOUT);
1731}
1732
1733static int hso_serial_ioctl(struct tty_struct *tty,
1734			    unsigned int cmd, unsigned long arg)
1735{
1736	struct hso_serial *serial =  get_serial_by_tty(tty);
1737	int ret = 0;
1738	D4("IOCTL cmd: %d, arg: %ld", cmd, arg);
1739
1740	if (!serial)
1741		return -ENODEV;
1742	switch (cmd) {
1743	case TIOCMIWAIT:
1744		ret = hso_wait_modem_status(serial, arg);
1745		break;
1746	default:
1747		ret = -ENOIOCTLCMD;
1748		break;
1749	}
1750	return ret;
1751}
1752
1753
1754/* starts a transmit */
1755static void hso_kick_transmit(struct hso_serial *serial)
1756{
1757	u8 *temp;
1758	unsigned long flags;
1759	int res;
1760
1761	spin_lock_irqsave(&serial->serial_lock, flags);
1762	if (!serial->tx_buffer_count)
1763		goto out;
1764
1765	if (serial->tx_urb_used)
1766		goto out;
1767
1768	/* Wakeup USB interface if necessary */
1769	if (hso_get_activity(serial->parent) == -EAGAIN)
1770		goto out;
1771
1772	/* Switch pointers around to avoid memcpy */
1773	temp = serial->tx_buffer;
1774	serial->tx_buffer = serial->tx_data;
1775	serial->tx_data = temp;
1776	serial->tx_data_count = serial->tx_buffer_count;
1777	serial->tx_buffer_count = 0;
1778
1779	/* If temp is set, it means we switched buffers */
1780	if (temp && serial->write_data) {
1781		res = serial->write_data(serial);
1782		if (res >= 0)
1783			serial->tx_urb_used = 1;
1784	}
1785out:
1786	spin_unlock_irqrestore(&serial->serial_lock, flags);
1787}
1788
1789/* make a request (for reading and writing data to muxed serial port) */
1790static int mux_device_request(struct hso_serial *serial, u8 type, u16 port,
1791			      struct urb *ctrl_urb,
1792			      struct usb_ctrlrequest *ctrl_req,
1793			      u8 *ctrl_urb_data, u32 size)
1794{
1795	int result;
1796	int pipe;
1797
1798	/* Sanity check */
1799	if (!serial || !ctrl_urb || !ctrl_req) {
1800		printk(KERN_ERR "%s: Wrong arguments\n", __func__);
1801		return -EINVAL;
1802	}
1803
1804	/* initialize */
1805	ctrl_req->wValue = 0;
1806	ctrl_req->wIndex = cpu_to_le16(hso_port_to_mux(port));
1807	ctrl_req->wLength = cpu_to_le16(size);
1808
1809	if (type == USB_CDC_GET_ENCAPSULATED_RESPONSE) {
1810		/* Reading command */
1811		ctrl_req->bRequestType = USB_DIR_IN |
1812					 USB_TYPE_OPTION_VENDOR |
1813					 USB_RECIP_INTERFACE;
1814		ctrl_req->bRequest = USB_CDC_GET_ENCAPSULATED_RESPONSE;
1815		pipe = usb_rcvctrlpipe(serial->parent->usb, 0);
1816	} else {
1817		/* Writing command */
1818		ctrl_req->bRequestType = USB_DIR_OUT |
1819					 USB_TYPE_OPTION_VENDOR |
1820					 USB_RECIP_INTERFACE;
1821		ctrl_req->bRequest = USB_CDC_SEND_ENCAPSULATED_COMMAND;
1822		pipe = usb_sndctrlpipe(serial->parent->usb, 0);
1823	}
1824	/* syslog */
1825	D2("%s command (%02x) len: %d, port: %d",
1826	   type == USB_CDC_GET_ENCAPSULATED_RESPONSE ? "Read" : "Write",
1827	   ctrl_req->bRequestType, ctrl_req->wLength, port);
1828
1829	/* Load ctrl urb */
1830	ctrl_urb->transfer_flags = 0;
1831	usb_fill_control_urb(ctrl_urb,
1832			     serial->parent->usb,
1833			     pipe,
1834			     (u8 *) ctrl_req,
1835			     ctrl_urb_data, size, ctrl_callback, serial);
1836	/* Send it on merry way */
1837	result = usb_submit_urb(ctrl_urb, GFP_ATOMIC);
1838	if (result) {
1839		dev_err(&ctrl_urb->dev->dev,
1840			"%s failed submit ctrl_urb %d type %d\n", __func__,
1841			result, type);
1842		return result;
1843	}
1844
1845	/* done */
1846	return size;
1847}
1848
1849/* called by intr_callback when read occurs */
1850static int hso_mux_serial_read(struct hso_serial *serial)
1851{
1852	if (!serial)
1853		return -EINVAL;
1854
1855	/* clean data */
1856	memset(serial->rx_data[0], 0, CTRL_URB_RX_SIZE);
1857	/* make the request */
1858
1859	if (serial->num_rx_urbs != 1) {
1860		dev_err(&serial->parent->interface->dev,
1861			"ERROR: mux'd reads with multiple buffers "
1862			"not possible\n");
1863		return 0;
1864	}
1865	return mux_device_request(serial,
1866				  USB_CDC_GET_ENCAPSULATED_RESPONSE,
1867				  serial->parent->port_spec & HSO_PORT_MASK,
1868				  serial->rx_urb[0],
1869				  &serial->ctrl_req_rx,
1870				  serial->rx_data[0], serial->rx_data_length);
1871}
1872
1873/* used for muxed serial port callback (muxed serial read) */
1874static void intr_callback(struct urb *urb)
1875{
1876	struct hso_shared_int *shared_int = urb->context;
1877	struct hso_serial *serial;
1878	unsigned char *port_req;
1879	int status = urb->status;
1880	int i;
1881
1882	usb_mark_last_busy(urb->dev);
1883
1884	/* sanity check */
1885	if (!shared_int)
1886		return;
1887
1888	/* status check */
1889	if (status) {
1890		handle_usb_error(status, __func__, NULL);
1891		return;
1892	}
1893	D4("\n--- Got intr callback 0x%02X ---", status);
1894
1895	/* what request? */
1896	port_req = urb->transfer_buffer;
1897	D4(" port_req = 0x%.2X\n", *port_req);
1898	/* loop over all muxed ports to find the one sending this */
1899	for (i = 0; i < 8; i++) {
1900		/* max 8 channels on MUX */
1901		if (*port_req & (1 << i)) {
1902			serial = get_serial_by_shared_int_and_type(shared_int,
1903								   (1 << i));
1904			if (serial != NULL) {
1905				D1("Pending read interrupt on port %d\n", i);
1906				spin_lock(&serial->serial_lock);
1907				if (serial->rx_state == RX_IDLE &&
1908					serial->open_count > 0) {
1909					/* Setup and send a ctrl req read on
1910					 * port i */
1911					if (!serial->rx_urb_filled[0]) {
1912						serial->rx_state = RX_SENT;
1913						hso_mux_serial_read(serial);
1914					} else
1915						serial->rx_state = RX_PENDING;
1916				} else {
1917					D1("Already a read pending on "
1918					   "port %d or port not open\n", i);
1919				}
1920				spin_unlock(&serial->serial_lock);
1921			}
1922		}
1923	}
1924	/* Resubmit interrupt urb */
1925	hso_mux_submit_intr_urb(shared_int, urb->dev, GFP_ATOMIC);
1926}
1927
1928/* called for writing to muxed serial port */
1929static int hso_mux_serial_write_data(struct hso_serial *serial)
1930{
1931	if (NULL == serial)
1932		return -EINVAL;
1933
1934	return mux_device_request(serial,
1935				  USB_CDC_SEND_ENCAPSULATED_COMMAND,
1936				  serial->parent->port_spec & HSO_PORT_MASK,
1937				  serial->tx_urb,
1938				  &serial->ctrl_req_tx,
1939				  serial->tx_data, serial->tx_data_count);
1940}
1941
1942/* write callback for Diag and CS port */
1943static void hso_std_serial_write_bulk_callback(struct urb *urb)
1944{
1945	struct hso_serial *serial = urb->context;
1946	int status = urb->status;
1947	struct tty_struct *tty;
1948
1949	/* sanity check */
1950	if (!serial) {
1951		D1("serial == NULL");
1952		return;
1953	}
1954
1955	spin_lock(&serial->serial_lock);
1956	serial->tx_urb_used = 0;
1957	tty = tty_kref_get(serial->tty);
1958	spin_unlock(&serial->serial_lock);
1959	if (status) {
1960		handle_usb_error(status, __func__, serial->parent);
1961		tty_kref_put(tty);
1962		return;
1963	}
1964	hso_put_activity(serial->parent);
1965	if (tty) {
1966		tty_wakeup(tty);
1967		tty_kref_put(tty);
1968	}
1969	hso_kick_transmit(serial);
1970
1971	D1(" ");
1972}
1973
1974/* called for writing diag or CS serial port */
1975static int hso_std_serial_write_data(struct hso_serial *serial)
1976{
1977	int count = serial->tx_data_count;
1978	int result;
1979
1980	usb_fill_bulk_urb(serial->tx_urb,
1981			  serial->parent->usb,
1982			  usb_sndbulkpipe(serial->parent->usb,
1983					  serial->out_endp->
1984					  bEndpointAddress & 0x7F),
1985			  serial->tx_data, serial->tx_data_count,
1986			  hso_std_serial_write_bulk_callback, serial);
1987
1988	result = usb_submit_urb(serial->tx_urb, GFP_ATOMIC);
1989	if (result) {
1990		dev_warn(&serial->parent->usb->dev,
1991			 "Failed to submit urb - res %d\n", result);
1992		return result;
1993	}
1994
1995	return count;
1996}
1997
1998/* callback after read or write on muxed serial port */
1999static void ctrl_callback(struct urb *urb)
2000{
2001	struct hso_serial *serial = urb->context;
2002	struct usb_ctrlrequest *req;
2003	int status = urb->status;
2004	struct tty_struct *tty;
2005
2006	/* sanity check */
2007	if (!serial)
2008		return;
2009
2010	spin_lock(&serial->serial_lock);
2011	serial->tx_urb_used = 0;
2012	tty = tty_kref_get(serial->tty);
2013	spin_unlock(&serial->serial_lock);
2014	if (status) {
2015		handle_usb_error(status, __func__, serial->parent);
2016		tty_kref_put(tty);
2017		return;
2018	}
2019
2020	/* what request? */
2021	req = (struct usb_ctrlrequest *)(urb->setup_packet);
2022	D4("\n--- Got muxed ctrl callback 0x%02X ---", status);
2023	D4("Actual length of urb = %d\n", urb->actual_length);
2024	DUMP1(urb->transfer_buffer, urb->actual_length);
2025
2026	if (req->bRequestType ==
2027	    (USB_DIR_IN | USB_TYPE_OPTION_VENDOR | USB_RECIP_INTERFACE)) {
2028		/* response to a read command */
2029		serial->rx_urb_filled[0] = 1;
2030		spin_lock(&serial->serial_lock);
2031		put_rxbuf_data_and_resubmit_ctrl_urb(serial);
2032		spin_unlock(&serial->serial_lock);
2033	} else {
2034		hso_put_activity(serial->parent);
2035		if (tty)
2036			tty_wakeup(tty);
2037		/* response to a write command */
2038		hso_kick_transmit(serial);
2039	}
2040	tty_kref_put(tty);
2041}
2042
2043/* handle RX data for serial port */
2044static int put_rxbuf_data(struct urb *urb, struct hso_serial *serial)
2045{
2046	struct tty_struct *tty;
2047	int write_length_remaining = 0;
2048	int curr_write_len;
2049
2050	/* Sanity check */
2051	if (urb == NULL || serial == NULL) {
2052		D1("serial = NULL");
2053		return -2;
2054	}
2055
2056	/* All callers to put_rxbuf_data hold serial_lock */
2057	tty = tty_kref_get(serial->tty);
2058
2059	/* Push data to tty */
2060	if (tty) {
2061		write_length_remaining = urb->actual_length -
2062			serial->curr_rx_urb_offset;
2063		D1("data to push to tty");
2064		while (write_length_remaining) {
2065			if (test_bit(TTY_THROTTLED, &tty->flags)) {
2066				tty_kref_put(tty);
2067				return -1;
2068			}
2069			curr_write_len =  tty_insert_flip_string
2070				(tty, urb->transfer_buffer +
2071				 serial->curr_rx_urb_offset,
2072				 write_length_remaining);
2073			serial->curr_rx_urb_offset += curr_write_len;
2074			write_length_remaining -= curr_write_len;
2075			tty_flip_buffer_push(tty);
2076		}
2077	}
2078	if (write_length_remaining == 0) {
2079		serial->curr_rx_urb_offset = 0;
2080		serial->rx_urb_filled[hso_urb_to_index(serial, urb)] = 0;
2081	}
2082	tty_kref_put(tty);
2083	return write_length_remaining;
2084}
2085
2086
2087/* Base driver functions */
2088
2089static void hso_log_port(struct hso_device *hso_dev)
2090{
2091	char *port_type;
2092	char port_dev[20];
2093
2094	switch (hso_dev->port_spec & HSO_PORT_MASK) {
2095	case HSO_PORT_CONTROL:
2096		port_type = "Control";
2097		break;
2098	case HSO_PORT_APP:
2099		port_type = "Application";
2100		break;
2101	case HSO_PORT_GPS:
2102		port_type = "GPS";
2103		break;
2104	case HSO_PORT_GPS_CONTROL:
2105		port_type = "GPS control";
2106		break;
2107	case HSO_PORT_APP2:
2108		port_type = "Application2";
2109		break;
2110	case HSO_PORT_PCSC:
2111		port_type = "PCSC";
2112		break;
2113	case HSO_PORT_DIAG:
2114		port_type = "Diagnostic";
2115		break;
2116	case HSO_PORT_DIAG2:
2117		port_type = "Diagnostic2";
2118		break;
2119	case HSO_PORT_MODEM:
2120		port_type = "Modem";
2121		break;
2122	case HSO_PORT_NETWORK:
2123		port_type = "Network";
2124		break;
2125	default:
2126		port_type = "Unknown";
2127		break;
2128	}
2129	if ((hso_dev->port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) {
2130		sprintf(port_dev, "%s", dev2net(hso_dev)->net->name);
2131	} else
2132		sprintf(port_dev, "/dev/%s%d", tty_filename,
2133			dev2ser(hso_dev)->minor);
2134
2135	dev_dbg(&hso_dev->interface->dev, "HSO: Found %s port %s\n",
2136		port_type, port_dev);
2137}
2138
2139static int hso_start_net_device(struct hso_device *hso_dev)
2140{
2141	int i, result = 0;
2142	struct hso_net *hso_net = dev2net(hso_dev);
2143
2144	if (!hso_net)
2145		return -ENODEV;
2146
2147	/* send URBs for all read buffers */
2148	for (i = 0; i < MUX_BULK_RX_BUF_COUNT; i++) {
2149
2150		/* Prep a receive URB */
2151		usb_fill_bulk_urb(hso_net->mux_bulk_rx_urb_pool[i],
2152				  hso_dev->usb,
2153				  usb_rcvbulkpipe(hso_dev->usb,
2154						  hso_net->in_endp->
2155						  bEndpointAddress & 0x7F),
2156				  hso_net->mux_bulk_rx_buf_pool[i],
2157				  MUX_BULK_RX_BUF_SIZE, read_bulk_callback,
2158				  hso_net);
2159
2160		/* Put it out there so the device can send us stuff */
2161		result = usb_submit_urb(hso_net->mux_bulk_rx_urb_pool[i],
2162					GFP_NOIO);
2163		if (result)
2164			dev_warn(&hso_dev->usb->dev,
2165				"%s failed mux_bulk_rx_urb[%d] %d\n", __func__,
2166				i, result);
2167	}
2168
2169	return result;
2170}
2171
2172static int hso_stop_net_device(struct hso_device *hso_dev)
2173{
2174	int i;
2175	struct hso_net *hso_net = dev2net(hso_dev);
2176
2177	if (!hso_net)
2178		return -ENODEV;
2179
2180	for (i = 0; i < MUX_BULK_RX_BUF_COUNT; i++) {
2181		if (hso_net->mux_bulk_rx_urb_pool[i])
2182			usb_kill_urb(hso_net->mux_bulk_rx_urb_pool[i]);
2183
2184	}
2185	if (hso_net->mux_bulk_tx_urb)
2186		usb_kill_urb(hso_net->mux_bulk_tx_urb);
2187
2188	return 0;
2189}
2190
2191static int hso_start_serial_device(struct hso_device *hso_dev, gfp_t flags)
2192{
2193	int i, result = 0;
2194	struct hso_serial *serial = dev2ser(hso_dev);
2195
2196	if (!serial)
2197		return -ENODEV;
2198
2199	/* If it is not the MUX port fill in and submit a bulk urb (already
2200	 * allocated in hso_serial_start) */
2201	if (!(serial->parent->port_spec & HSO_INTF_MUX)) {
2202		for (i = 0; i < serial->num_rx_urbs; i++) {
2203			usb_fill_bulk_urb(serial->rx_urb[i],
2204					  serial->parent->usb,
2205					  usb_rcvbulkpipe(serial->parent->usb,
2206							  serial->in_endp->
2207							  bEndpointAddress &
2208							  0x7F),
2209					  serial->rx_data[i],
2210					  serial->rx_data_length,
2211					  hso_std_serial_read_bulk_callback,
2212					  serial);
2213			result = usb_submit_urb(serial->rx_urb[i], flags);
2214			if (result) {
2215				dev_warn(&serial->parent->usb->dev,
2216					 "Failed to submit urb - res %d\n",
2217					 result);
2218				break;
2219			}
2220		}
2221	} else {
2222		mutex_lock(&serial->shared_int->shared_int_lock);
2223		if (!serial->shared_int->use_count) {
2224			result =
2225			    hso_mux_submit_intr_urb(serial->shared_int,
2226						    hso_dev->usb, flags);
2227		}
2228		serial->shared_int->use_count++;
2229		mutex_unlock(&serial->shared_int->shared_int_lock);
2230	}
2231	if (serial->tiocmget)
2232		tiocmget_submit_urb(serial,
2233				    serial->tiocmget,
2234				    serial->parent->usb);
2235	return result;
2236}
2237
2238static int hso_stop_serial_device(struct hso_device *hso_dev)
2239{
2240	int i;
2241	struct hso_serial *serial = dev2ser(hso_dev);
2242	struct hso_tiocmget  *tiocmget;
2243
2244	if (!serial)
2245		return -ENODEV;
2246
2247	for (i = 0; i < serial->num_rx_urbs; i++) {
2248		if (serial->rx_urb[i]) {
2249				usb_kill_urb(serial->rx_urb[i]);
2250				serial->rx_urb_filled[i] = 0;
2251		}
2252	}
2253	serial->curr_rx_urb_idx = 0;
2254	serial->curr_rx_urb_offset = 0;
2255
2256	if (serial->tx_urb)
2257		usb_kill_urb(serial->tx_urb);
2258
2259	if (serial->shared_int) {
2260		mutex_lock(&serial->shared_int->shared_int_lock);
2261		if (serial->shared_int->use_count &&
2262		    (--serial->shared_int->use_count == 0)) {
2263			struct urb *urb;
2264
2265			urb = serial->shared_int->shared_intr_urb;
2266			if (urb)
2267				usb_kill_urb(urb);
2268		}
2269		mutex_unlock(&serial->shared_int->shared_int_lock);
2270	}
2271	tiocmget = serial->tiocmget;
2272	if (tiocmget) {
2273		wake_up_interruptible(&tiocmget->waitq);
2274		usb_kill_urb(tiocmget->urb);
2275	}
2276
2277	return 0;
2278}
2279
2280static void hso_serial_common_free(struct hso_serial *serial)
2281{
2282	int i;
2283
2284	if (serial->parent->dev)
2285		device_remove_file(serial->parent->dev, &dev_attr_hsotype);
2286
2287	tty_unregister_device(tty_drv, serial->minor);
2288
2289	for (i = 0; i < serial->num_rx_urbs; i++) {
2290		/* unlink and free RX URB */
2291		usb_free_urb(serial->rx_urb[i]);
2292		/* free the RX buffer */
2293		kfree(serial->rx_data[i]);
2294	}
2295
2296	/* unlink and free TX URB */
2297	usb_free_urb(serial->tx_urb);
2298	kfree(serial->tx_data);
2299}
2300
2301static int hso_serial_common_create(struct hso_serial *serial, int num_urbs,
2302				    int rx_size, int tx_size)
2303{
2304	struct device *dev;
2305	int minor;
2306	int i;
2307
2308	minor = get_free_serial_index();
2309	if (minor < 0)
2310		goto exit;
2311
2312	/* register our minor number */
2313	serial->parent->dev = tty_register_device(tty_drv, minor,
2314					&serial->parent->interface->dev);
2315	dev = serial->parent->dev;
2316	dev_set_drvdata(dev, serial->parent);
2317	i = device_create_file(dev, &dev_attr_hsotype);
2318
2319	/* fill in specific data for later use */
2320	serial->minor = minor;
2321	serial->magic = HSO_SERIAL_MAGIC;
2322	spin_lock_init(&serial->serial_lock);
2323	serial->num_rx_urbs = num_urbs;
2324
2325	/* RX, allocate urb and initialize */
2326
2327	/* prepare our RX buffer */
2328	serial->rx_data_length = rx_size;
2329	for (i = 0; i < serial->num_rx_urbs; i++) {
2330		serial->rx_urb[i] = usb_alloc_urb(0, GFP_KERNEL);
2331		if (!serial->rx_urb[i]) {
2332			dev_err(dev, "Could not allocate urb?\n");
2333			goto exit;
2334		}
2335		serial->rx_urb[i]->transfer_buffer = NULL;
2336		serial->rx_urb[i]->transfer_buffer_length = 0;
2337		serial->rx_data[i] = kzalloc(serial->rx_data_length,
2338					     GFP_KERNEL);
2339		if (!serial->rx_data[i]) {
2340			dev_err(dev, "%s - Out of memory\n", __func__);
2341			goto exit;
2342		}
2343	}
2344
2345	/* TX, allocate urb and initialize */
2346	serial->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
2347	if (!serial->tx_urb) {
2348		dev_err(dev, "Could not allocate urb?\n");
2349		goto exit;
2350	}
2351	serial->tx_urb->transfer_buffer = NULL;
2352	serial->tx_urb->transfer_buffer_length = 0;
2353	/* prepare our TX buffer */
2354	serial->tx_data_count = 0;
2355	serial->tx_buffer_count = 0;
2356	serial->tx_data_length = tx_size;
2357	serial->tx_data = kzalloc(serial->tx_data_length, GFP_KERNEL);
2358	if (!serial->tx_data) {
2359		dev_err(dev, "%s - Out of memory\n", __func__);
2360		goto exit;
2361	}
2362	serial->tx_buffer = kzalloc(serial->tx_data_length, GFP_KERNEL);
2363	if (!serial->tx_buffer) {
2364		dev_err(dev, "%s - Out of memory\n", __func__);
2365		goto exit;
2366	}
2367
2368	return 0;
2369exit:
2370	hso_serial_common_free(serial);
2371	return -1;
2372}
2373
2374/* Creates a general hso device */
2375static struct hso_device *hso_create_device(struct usb_interface *intf,
2376					    int port_spec)
2377{
2378	struct hso_device *hso_dev;
2379
2380	hso_dev = kzalloc(sizeof(*hso_dev), GFP_ATOMIC);
2381	if (!hso_dev)
2382		return NULL;
2383
2384	hso_dev->port_spec = port_spec;
2385	hso_dev->usb = interface_to_usbdev(intf);
2386	hso_dev->interface = intf;
2387	kref_init(&hso_dev->ref);
2388	mutex_init(&hso_dev->mutex);
2389
2390	INIT_WORK(&hso_dev->async_get_intf, async_get_intf);
2391	INIT_WORK(&hso_dev->async_put_intf, async_put_intf);
2392	INIT_WORK(&hso_dev->reset_device, reset_device);
2393
2394	return hso_dev;
2395}
2396
2397/* Removes a network device in the network device table */
2398static int remove_net_device(struct hso_device *hso_dev)
2399{
2400	int i;
2401
2402	for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
2403		if (network_table[i] == hso_dev) {
2404			network_table[i] = NULL;
2405			break;
2406		}
2407	}
2408	if (i == HSO_MAX_NET_DEVICES)
2409		return -1;
2410	return 0;
2411}
2412
2413/* Frees our network device */
2414static void hso_free_net_device(struct hso_device *hso_dev)
2415{
2416	int i;
2417	struct hso_net *hso_net = dev2net(hso_dev);
2418
2419	if (!hso_net)
2420		return;
2421
2422	remove_net_device(hso_net->parent);
2423
2424	if (hso_net->net)
2425		unregister_netdev(hso_net->net);
2426
2427	/* start freeing */
2428	for (i = 0; i < MUX_BULK_RX_BUF_COUNT; i++) {
2429		usb_free_urb(hso_net->mux_bulk_rx_urb_pool[i]);
2430		kfree(hso_net->mux_bulk_rx_buf_pool[i]);
2431		hso_net->mux_bulk_rx_buf_pool[i] = NULL;
2432	}
2433	usb_free_urb(hso_net->mux_bulk_tx_urb);
2434	kfree(hso_net->mux_bulk_tx_buf);
2435	hso_net->mux_bulk_tx_buf = NULL;
2436
2437	if (hso_net->net)
2438		free_netdev(hso_net->net);
2439
2440	kfree(hso_dev);
2441}
2442
2443static const struct net_device_ops hso_netdev_ops = {
2444	.ndo_open	= hso_net_open,
2445	.ndo_stop	= hso_net_close,
2446	.ndo_start_xmit = hso_net_start_xmit,
2447	.ndo_tx_timeout = hso_net_tx_timeout,
2448};
2449
2450/* initialize the network interface */
2451static void hso_net_init(struct net_device *net)
2452{
2453	struct hso_net *hso_net = netdev_priv(net);
2454
2455	D1("sizeof hso_net is %d", (int)sizeof(*hso_net));
2456
2457	/* fill in the other fields */
2458	net->netdev_ops = &hso_netdev_ops;
2459	net->watchdog_timeo = HSO_NET_TX_TIMEOUT;
2460	net->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
2461	net->type = ARPHRD_NONE;
2462	net->mtu = DEFAULT_MTU - 14;
2463	net->tx_queue_len = 10;
2464	SET_ETHTOOL_OPS(net, &ops);
2465
2466	/* and initialize the semaphore */
2467	spin_lock_init(&hso_net->net_lock);
2468}
2469
2470/* Adds a network device in the network device table */
2471static int add_net_device(struct hso_device *hso_dev)
2472{
2473	int i;
2474
2475	for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
2476		if (network_table[i] == NULL) {
2477			network_table[i] = hso_dev;
2478			break;
2479		}
2480	}
2481	if (i == HSO_MAX_NET_DEVICES)
2482		return -1;
2483	return 0;
2484}
2485
2486static int hso_rfkill_set_block(void *data, bool blocked)
2487{
2488	struct hso_device *hso_dev = data;
2489	int enabled = !blocked;
2490	int rv;
2491
2492	mutex_lock(&hso_dev->mutex);
2493	if (hso_dev->usb_gone)
2494		rv = 0;
2495	else
2496		rv = usb_control_msg(hso_dev->usb, usb_rcvctrlpipe(hso_dev->usb, 0),
2497				       enabled ? 0x82 : 0x81, 0x40, 0, 0, NULL, 0,
2498				       USB_CTRL_SET_TIMEOUT);
2499	mutex_unlock(&hso_dev->mutex);
2500	return rv;
2501}
2502
2503static const struct rfkill_ops hso_rfkill_ops = {
2504	.set_block = hso_rfkill_set_block,
2505};
2506
2507/* Creates and sets up everything for rfkill */
2508static void hso_create_rfkill(struct hso_device *hso_dev,
2509			     struct usb_interface *interface)
2510{
2511	struct hso_net *hso_net = dev2net(hso_dev);
2512	struct device *dev = &hso_net->net->dev;
2513	char *rfkn;
2514
2515	rfkn = kzalloc(20, GFP_KERNEL);
2516	if (!rfkn)
2517		dev_err(dev, "%s - Out of memory\n", __func__);
2518
2519	snprintf(rfkn, 20, "hso-%d",
2520		 interface->altsetting->desc.bInterfaceNumber);
2521
2522	hso_net->rfkill = rfkill_alloc(rfkn,
2523				       &interface_to_usbdev(interface)->dev,
2524				       RFKILL_TYPE_WWAN,
2525				       &hso_rfkill_ops, hso_dev);
2526	if (!hso_net->rfkill) {
2527		dev_err(dev, "%s - Out of memory\n", __func__);
2528		kfree(rfkn);
2529		return;
2530	}
2531	if (rfkill_register(hso_net->rfkill) < 0) {
2532		rfkill_destroy(hso_net->rfkill);
2533		kfree(rfkn);
2534		hso_net->rfkill = NULL;
2535		dev_err(dev, "%s - Failed to register rfkill\n", __func__);
2536		return;
2537	}
2538}
2539
2540static struct device_type hso_type = {
2541	.name	= "wwan",
2542};
2543
2544/* Creates our network device */
2545static struct hso_device *hso_create_net_device(struct usb_interface *interface,
2546						int port_spec)
2547{
2548	int result, i;
2549	struct net_device *net;
2550	struct hso_net *hso_net;
2551	struct hso_device *hso_dev;
2552
2553	hso_dev = hso_create_device(interface, port_spec);
2554	if (!hso_dev)
2555		return NULL;
2556
2557	/* allocate our network device, then we can put in our private data */
2558	/* call hso_net_init to do the basic initialization */
2559	net = alloc_netdev(sizeof(struct hso_net), "hso%d", hso_net_init);
2560	if (!net) {
2561		dev_err(&interface->dev, "Unable to create ethernet device\n");
2562		goto exit;
2563	}
2564
2565	hso_net = netdev_priv(net);
2566
2567	hso_dev->port_data.dev_net = hso_net;
2568	hso_net->net = net;
2569	hso_net->parent = hso_dev;
2570
2571	hso_net->in_endp = hso_get_ep(interface, USB_ENDPOINT_XFER_BULK,
2572				      USB_DIR_IN);
2573	if (!hso_net->in_endp) {
2574		dev_err(&interface->dev, "Can't find BULK IN endpoint\n");
2575		goto exit;
2576	}
2577	hso_net->out_endp = hso_get_ep(interface, USB_ENDPOINT_XFER_BULK,
2578				       USB_DIR_OUT);
2579	if (!hso_net->out_endp) {
2580		dev_err(&interface->dev, "Can't find BULK OUT endpoint\n");
2581		goto exit;
2582	}
2583	SET_NETDEV_DEV(net, &interface->dev);
2584	SET_NETDEV_DEVTYPE(net, &hso_type);
2585
2586	/* registering our net device */
2587	result = register_netdev(net);
2588	if (result) {
2589		dev_err(&interface->dev, "Failed to register device\n");
2590		goto exit;
2591	}
2592
2593	/* start allocating */
2594	for (i = 0; i < MUX_BULK_RX_BUF_COUNT; i++) {
2595		hso_net->mux_bulk_rx_urb_pool[i] = usb_alloc_urb(0, GFP_KERNEL);
2596		if (!hso_net->mux_bulk_rx_urb_pool[i]) {
2597			dev_err(&interface->dev, "Could not allocate rx urb\n");
2598			goto exit;
2599		}
2600		hso_net->mux_bulk_rx_buf_pool[i] = kzalloc(MUX_BULK_RX_BUF_SIZE,
2601							   GFP_KERNEL);
2602		if (!hso_net->mux_bulk_rx_buf_pool[i]) {
2603			dev_err(&interface->dev, "Could not allocate rx buf\n");
2604			goto exit;
2605		}
2606	}
2607	hso_net->mux_bulk_tx_urb = usb_alloc_urb(0, GFP_KERNEL);
2608	if (!hso_net->mux_bulk_tx_urb) {
2609		dev_err(&interface->dev, "Could not allocate tx urb\n");
2610		goto exit;
2611	}
2612	hso_net->mux_bulk_tx_buf = kzalloc(MUX_BULK_TX_BUF_SIZE, GFP_KERNEL);
2613	if (!hso_net->mux_bulk_tx_buf) {
2614		dev_err(&interface->dev, "Could not allocate tx buf\n");
2615		goto exit;
2616	}
2617
2618	add_net_device(hso_dev);
2619
2620	hso_log_port(hso_dev);
2621
2622	hso_create_rfkill(hso_dev, interface);
2623
2624	return hso_dev;
2625exit:
2626	hso_free_net_device(hso_dev);
2627	return NULL;
2628}
2629
2630static void hso_free_tiomget(struct hso_serial *serial)
2631{
2632	struct hso_tiocmget *tiocmget;
2633	if (!serial)
2634		return;
2635	tiocmget = serial->tiocmget;
2636	if (tiocmget) {
2637		usb_free_urb(tiocmget->urb);
2638		tiocmget->urb = NULL;
2639		serial->tiocmget = NULL;
2640		kfree(tiocmget);
2641	}
2642}
2643
2644/* Frees an AT channel ( goes for both mux and non-mux ) */
2645static void hso_free_serial_device(struct hso_device *hso_dev)
2646{
2647	struct hso_serial *serial = dev2ser(hso_dev);
2648
2649	if (!serial)
2650		return;
2651	set_serial_by_index(serial->minor, NULL);
2652
2653	hso_serial_common_free(serial);
2654
2655	if (serial->shared_int) {
2656		mutex_lock(&serial->shared_int->shared_int_lock);
2657		if (--serial->shared_int->ref_count == 0)
2658			hso_free_shared_int(serial->shared_int);
2659		else
2660			mutex_unlock(&serial->shared_int->shared_int_lock);
2661	}
2662	hso_free_tiomget(serial);
2663	kfree(serial);
2664	kfree(hso_dev);
2665}
2666
2667/* Creates a bulk AT channel */
2668static struct hso_device *hso_create_bulk_serial_device(
2669			struct usb_interface *interface, int port)
2670{
2671	struct hso_device *hso_dev;
2672	struct hso_serial *serial;
2673	int num_urbs;
2674	struct hso_tiocmget *tiocmget;
2675
2676	hso_dev = hso_create_device(interface, port);
2677	if (!hso_dev)
2678		return NULL;
2679
2680	serial = kzalloc(sizeof(*serial), GFP_KERNEL);
2681	if (!serial)
2682		goto exit;
2683
2684	serial->parent = hso_dev;
2685	hso_dev->port_data.dev_serial = serial;
2686
2687	if ((port & HSO_PORT_MASK) == HSO_PORT_MODEM) {
2688		num_urbs = 2;
2689		serial->tiocmget = kzalloc(sizeof(struct hso_tiocmget),
2690					   GFP_KERNEL);
2691		/* it isn't going to break our heart if serial->tiocmget
2692		 *  allocation fails don't bother checking this.
2693		 */
2694		if (serial->tiocmget) {
2695			tiocmget = serial->tiocmget;
2696			tiocmget->urb = usb_alloc_urb(0, GFP_KERNEL);
2697			if (tiocmget->urb) {
2698				mutex_init(&tiocmget->mutex);
2699				init_waitqueue_head(&tiocmget->waitq);
2700				tiocmget->endp = hso_get_ep(
2701					interface,
2702					USB_ENDPOINT_XFER_INT,
2703					USB_DIR_IN);
2704			} else
2705				hso_free_tiomget(serial);
2706		}
2707	}
2708	else
2709		num_urbs = 1;
2710
2711	if (hso_serial_common_create(serial, num_urbs, BULK_URB_RX_SIZE,
2712				     BULK_URB_TX_SIZE))
2713		goto exit;
2714
2715	serial->in_endp = hso_get_ep(interface, USB_ENDPOINT_XFER_BULK,
2716				     USB_DIR_IN);
2717	if (!serial->in_endp) {
2718		dev_err(&interface->dev, "Failed to find BULK IN ep\n");
2719		goto exit2;
2720	}
2721
2722	if (!
2723	    (serial->out_endp =
2724	     hso_get_ep(interface, USB_ENDPOINT_XFER_BULK, USB_DIR_OUT))) {
2725		dev_err(&interface->dev, "Failed to find BULK IN ep\n");
2726		goto exit2;
2727	}
2728
2729	serial->write_data = hso_std_serial_write_data;
2730
2731	/* and record this serial */
2732	set_serial_by_index(serial->minor, serial);
2733
2734	/* setup the proc dirs and files if needed */
2735	hso_log_port(hso_dev);
2736
2737	/* done, return it */
2738	return hso_dev;
2739
2740exit2:
2741	hso_serial_common_free(serial);
2742exit:
2743	hso_free_tiomget(serial);
2744	kfree(serial);
2745	kfree(hso_dev);
2746	return NULL;
2747}
2748
2749/* Creates a multiplexed AT channel */
2750static
2751struct hso_device *hso_create_mux_serial_device(struct usb_interface *interface,
2752						int port,
2753						struct hso_shared_int *mux)
2754{
2755	struct hso_device *hso_dev;
2756	struct hso_serial *serial;
2757	int port_spec;
2758
2759	port_spec = HSO_INTF_MUX;
2760	port_spec &= ~HSO_PORT_MASK;
2761
2762	port_spec |= hso_mux_to_port(port);
2763	if ((port_spec & HSO_PORT_MASK) == HSO_PORT_NO_PORT)
2764		return NULL;
2765
2766	hso_dev = hso_create_device(interface, port_spec);
2767	if (!hso_dev)
2768		return NULL;
2769
2770	serial = kzalloc(sizeof(*serial), GFP_KERNEL);
2771	if (!serial)
2772		goto exit;
2773
2774	hso_dev->port_data.dev_serial = serial;
2775	serial->parent = hso_dev;
2776
2777	if (hso_serial_common_create
2778	    (serial, 1, CTRL_URB_RX_SIZE, CTRL_URB_TX_SIZE))
2779		goto exit;
2780
2781	serial->tx_data_length--;
2782	serial->write_data = hso_mux_serial_write_data;
2783
2784	serial->shared_int = mux;
2785	mutex_lock(&serial->shared_int->shared_int_lock);
2786	serial->shared_int->ref_count++;
2787	mutex_unlock(&serial->shared_int->shared_int_lock);
2788
2789	/* and record this serial */
2790	set_serial_by_index(serial->minor, serial);
2791
2792	/* setup the proc dirs and files if needed */
2793	hso_log_port(hso_dev);
2794
2795	/* done, return it */
2796	return hso_dev;
2797
2798exit:
2799	if (serial) {
2800		tty_unregister_device(tty_drv, serial->minor);
2801		kfree(serial);
2802	}
2803	if (hso_dev)
2804		kfree(hso_dev);
2805	return NULL;
2806
2807}
2808
2809static void hso_free_shared_int(struct hso_shared_int *mux)
2810{
2811	usb_free_urb(mux->shared_intr_urb);
2812	kfree(mux->shared_intr_buf);
2813	mutex_unlock(&mux->shared_int_lock);
2814	kfree(mux);
2815}
2816
2817static
2818struct hso_shared_int *hso_create_shared_int(struct usb_interface *interface)
2819{
2820	struct hso_shared_int *mux = kzalloc(sizeof(*mux), GFP_KERNEL);
2821
2822	if (!mux)
2823		return NULL;
2824
2825	mux->intr_endp = hso_get_ep(interface, USB_ENDPOINT_XFER_INT,
2826				    USB_DIR_IN);
2827	if (!mux->intr_endp) {
2828		dev_err(&interface->dev, "Can't find INT IN endpoint\n");
2829		goto exit;
2830	}
2831
2832	mux->shared_intr_urb = usb_alloc_urb(0, GFP_KERNEL);
2833	if (!mux->shared_intr_urb) {
2834		dev_err(&interface->dev, "Could not allocate intr urb?\n");
2835		goto exit;
2836	}
2837	mux->shared_intr_buf =
2838		kzalloc(le16_to_cpu(mux->intr_endp->wMaxPacketSize),
2839			GFP_KERNEL);
2840	if (!mux->shared_intr_buf) {
2841		dev_err(&interface->dev, "Could not allocate intr buf?\n");
2842		goto exit;
2843	}
2844
2845	mutex_init(&mux->shared_int_lock);
2846
2847	return mux;
2848
2849exit:
2850	kfree(mux->shared_intr_buf);
2851	usb_free_urb(mux->shared_intr_urb);
2852	kfree(mux);
2853	return NULL;
2854}
2855
2856/* Gets the port spec for a certain interface */
2857static int hso_get_config_data(struct usb_interface *interface)
2858{
2859	struct usb_device *usbdev = interface_to_usbdev(interface);
2860	u8 config_data[17];
2861	u32 if_num = interface->altsetting->desc.bInterfaceNumber;
2862	s32 result;
2863
2864	if (usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0),
2865			    0x86, 0xC0, 0, 0, config_data, 17,
2866			    USB_CTRL_SET_TIMEOUT) != 0x11) {
2867		return -EIO;
2868	}
2869
2870	switch (config_data[if_num]) {
2871	case 0x0:
2872		result = 0;
2873		break;
2874	case 0x1:
2875		result = HSO_PORT_DIAG;
2876		break;
2877	case 0x2:
2878		result = HSO_PORT_GPS;
2879		break;
2880	case 0x3:
2881		result = HSO_PORT_GPS_CONTROL;
2882		break;
2883	case 0x4:
2884		result = HSO_PORT_APP;
2885		break;
2886	case 0x5:
2887		result = HSO_PORT_APP2;
2888		break;
2889	case 0x6:
2890		result = HSO_PORT_CONTROL;
2891		break;
2892	case 0x7:
2893		result = HSO_PORT_NETWORK;
2894		break;
2895	case 0x8:
2896		result = HSO_PORT_MODEM;
2897		break;
2898	case 0x9:
2899		result = HSO_PORT_MSD;
2900		break;
2901	case 0xa:
2902		result = HSO_PORT_PCSC;
2903		break;
2904	case 0xb:
2905		result = HSO_PORT_VOICE;
2906		break;
2907	default:
2908		result = 0;
2909	}
2910
2911	if (result)
2912		result |= HSO_INTF_BULK;
2913
2914	if (config_data[16] & 0x1)
2915		result |= HSO_INFO_CRC_BUG;
2916
2917	return result;
2918}
2919
2920/* called once for each interface upon device insertion */
2921static int hso_probe(struct usb_interface *interface,
2922		     const struct usb_device_id *id)
2923{
2924	int mux, i, if_num, port_spec;
2925	unsigned char port_mask;
2926	struct hso_device *hso_dev = NULL;
2927	struct hso_shared_int *shared_int;
2928	struct hso_device *tmp_dev = NULL;
2929
2930	if_num = interface->altsetting->desc.bInterfaceNumber;
2931
2932	/* Get the interface/port specification from either driver_info or from
2933	 * the device itself */
2934	if (id->driver_info)
2935		port_spec = ((u32 *)(id->driver_info))[if_num];
2936	else
2937		port_spec = hso_get_config_data(interface);
2938
2939	if (interface->cur_altsetting->desc.bInterfaceClass != 0xFF) {
2940		dev_err(&interface->dev, "Not our interface\n");
2941		return -ENODEV;
2942	}
2943	/* Check if we need to switch to alt interfaces prior to port
2944	 * configuration */
2945	if (interface->num_altsetting > 1)
2946		usb_set_interface(interface_to_usbdev(interface), if_num, 1);
2947	interface->needs_remote_wakeup = 1;
2948
2949	/* Allocate new hso device(s) */
2950	switch (port_spec & HSO_INTF_MASK) {
2951	case HSO_INTF_MUX:
2952		if ((port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) {
2953			/* Create the network device */
2954			if (!disable_net) {
2955				hso_dev = hso_create_net_device(interface,
2956								port_spec);
2957				if (!hso_dev)
2958					goto exit;
2959				tmp_dev = hso_dev;
2960			}
2961		}
2962
2963		if (hso_get_mux_ports(interface, &port_mask))
2964			/* TODO: de-allocate everything */
2965			goto exit;
2966
2967		shared_int = hso_create_shared_int(interface);
2968		if (!shared_int)
2969			goto exit;
2970
2971		for (i = 1, mux = 0; i < 0x100; i = i << 1, mux++) {
2972			if (port_mask & i) {
2973				hso_dev = hso_create_mux_serial_device(
2974						interface, i, shared_int);
2975				if (!hso_dev)
2976					goto exit;
2977			}
2978		}
2979
2980		if (tmp_dev)
2981			hso_dev = tmp_dev;
2982		break;
2983
2984	case HSO_INTF_BULK:
2985		/* It's a regular bulk interface */
2986		if ((port_spec & HSO_PORT_MASK) == HSO_PORT_NETWORK) {
2987			if (!disable_net)
2988				hso_dev =
2989				    hso_create_net_device(interface, port_spec);
2990		} else {
2991			hso_dev =
2992			    hso_create_bulk_serial_device(interface, port_spec);
2993		}
2994		if (!hso_dev)
2995			goto exit;
2996		break;
2997	default:
2998		goto exit;
2999	}
3000
3001	/* save our data pointer in this device */
3002	usb_set_intfdata(interface, hso_dev);
3003
3004	/* done */
3005	return 0;
3006exit:
3007	hso_free_interface(interface);
3008	return -ENODEV;
3009}
3010
3011/* device removed, cleaning up */
3012static void hso_disconnect(struct usb_interface *interface)
3013{
3014	hso_free_interface(interface);
3015
3016	/* remove reference of our private data */
3017	usb_set_intfdata(interface, NULL);
3018}
3019
3020static void async_get_intf(struct work_struct *data)
3021{
3022	struct hso_device *hso_dev =
3023	    container_of(data, struct hso_device, async_get_intf);
3024	usb_autopm_get_interface(hso_dev->interface);
3025}
3026
3027static void async_put_intf(struct work_struct *data)
3028{
3029	struct hso_device *hso_dev =
3030	    container_of(data, struct hso_device, async_put_intf);
3031	usb_autopm_put_interface(hso_dev->interface);
3032}
3033
3034static int hso_get_activity(struct hso_device *hso_dev)
3035{
3036	if (hso_dev->usb->state == USB_STATE_SUSPENDED) {
3037		if (!hso_dev->is_active) {
3038			hso_dev->is_active = 1;
3039			schedule_work(&hso_dev->async_get_intf);
3040		}
3041	}
3042
3043	if (hso_dev->usb->state != USB_STATE_CONFIGURED)
3044		return -EAGAIN;
3045
3046	usb_mark_last_busy(hso_dev->usb);
3047
3048	return 0;
3049}
3050
3051static int hso_put_activity(struct hso_device *hso_dev)
3052{
3053	if (hso_dev->usb->state != USB_STATE_SUSPENDED) {
3054		if (hso_dev->is_active) {
3055			hso_dev->is_active = 0;
3056			schedule_work(&hso_dev->async_put_intf);
3057			return -EAGAIN;
3058		}
3059	}
3060	hso_dev->is_active = 0;
3061	return 0;
3062}
3063
3064/* called by kernel when we need to suspend device */
3065static int hso_suspend(struct usb_interface *iface, pm_message_t message)
3066{
3067	int i, result;
3068
3069	/* Stop all serial ports */
3070	for (i = 0; i < HSO_SERIAL_TTY_MINORS; i++) {
3071		if (serial_table[i] && (serial_table[i]->interface == iface)) {
3072			result = hso_stop_serial_device(serial_table[i]);
3073			if (result)
3074				goto out;
3075		}
3076	}
3077
3078	/* Stop all network ports */
3079	for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
3080		if (network_table[i] &&
3081		    (network_table[i]->interface == iface)) {
3082			result = hso_stop_net_device(network_table[i]);
3083			if (result)
3084				goto out;
3085		}
3086	}
3087
3088out:
3089	return 0;
3090}
3091
3092/* called by kernel when we need to resume device */
3093static int hso_resume(struct usb_interface *iface)
3094{
3095	int i, result = 0;
3096	struct hso_net *hso_net;
3097
3098	/* Start all serial ports */
3099	for (i = 0; i < HSO_SERIAL_TTY_MINORS; i++) {
3100		if (serial_table[i] && (serial_table[i]->interface == iface)) {
3101			if (dev2ser(serial_table[i])->open_count) {
3102				result =
3103				    hso_start_serial_device(serial_table[i], GFP_NOIO);
3104				hso_kick_transmit(dev2ser(serial_table[i]));
3105				if (result)
3106					goto out;
3107			}
3108		}
3109	}
3110
3111	/* Start all network ports */
3112	for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
3113		if (network_table[i] &&
3114		    (network_table[i]->interface == iface)) {
3115			hso_net = dev2net(network_table[i]);
3116			if (hso_net->flags & IFF_UP) {
3117				/* First transmit any lingering data,
3118				   then restart the device. */
3119				if (hso_net->skb_tx_buf) {
3120					dev_dbg(&iface->dev,
3121						"Transmitting"
3122						" lingering data\n");
3123					hso_net_start_xmit(hso_net->skb_tx_buf,
3124							   hso_net->net);
3125					hso_net->skb_tx_buf = NULL;
3126				}
3127				result = hso_start_net_device(network_table[i]);
3128				if (result)
3129					goto out;
3130			}
3131		}
3132	}
3133
3134out:
3135	return result;
3136}
3137
3138static void reset_device(struct work_struct *data)
3139{
3140	struct hso_device *hso_dev =
3141	    container_of(data, struct hso_device, reset_device);
3142	struct usb_device *usb = hso_dev->usb;
3143	int result;
3144
3145	if (hso_dev->usb_gone) {
3146		D1("No reset during disconnect\n");
3147	} else {
3148		result = usb_lock_device_for_reset(usb, hso_dev->interface);
3149		if (result < 0)
3150			D1("unable to lock device for reset: %d\n", result);
3151		else {
3152			usb_reset_device(usb);
3153			usb_unlock_device(usb);
3154		}
3155	}
3156}
3157
3158static void hso_serial_ref_free(struct kref *ref)
3159{
3160	struct hso_device *hso_dev = container_of(ref, struct hso_device, ref);
3161
3162	hso_free_serial_device(hso_dev);
3163}
3164
3165static void hso_free_interface(struct usb_interface *interface)
3166{
3167	struct hso_serial *hso_dev;
3168	struct tty_struct *tty;
3169	int i;
3170
3171	for (i = 0; i < HSO_SERIAL_TTY_MINORS; i++) {
3172		if (serial_table[i] &&
3173		    (serial_table[i]->interface == interface)) {
3174			hso_dev = dev2ser(serial_table[i]);
3175			spin_lock_irq(&hso_dev->serial_lock);
3176			tty = tty_kref_get(hso_dev->tty);
3177			spin_unlock_irq(&hso_dev->serial_lock);
3178			if (tty)
3179				tty_hangup(tty);
3180			mutex_lock(&hso_dev->parent->mutex);
3181			tty_kref_put(tty);
3182			hso_dev->parent->usb_gone = 1;
3183			mutex_unlock(&hso_dev->parent->mutex);
3184			kref_put(&serial_table[i]->ref, hso_serial_ref_free);
3185		}
3186	}
3187
3188	for (i = 0; i < HSO_MAX_NET_DEVICES; i++) {
3189		if (network_table[i] &&
3190		    (network_table[i]->interface == interface)) {
3191			struct rfkill *rfk = dev2net(network_table[i])->rfkill;
3192			/* hso_stop_net_device doesn't stop the net queue since
3193			 * traffic needs to start it again when suspended */
3194			netif_stop_queue(dev2net(network_table[i])->net);
3195			hso_stop_net_device(network_table[i]);
3196			cancel_work_sync(&network_table[i]->async_put_intf);
3197			cancel_work_sync(&network_table[i]->async_get_intf);
3198			if (rfk) {
3199				rfkill_unregister(rfk);
3200				rfkill_destroy(rfk);
3201			}
3202			hso_free_net_device(network_table[i]);
3203		}
3204	}
3205}
3206
3207/* Helper functions */
3208
3209/* Get the endpoint ! */
3210static struct usb_endpoint_descriptor *hso_get_ep(struct usb_interface *intf,
3211						  int type, int dir)
3212{
3213	int i;
3214	struct usb_host_interface *iface = intf->cur_altsetting;
3215	struct usb_endpoint_descriptor *endp;
3216
3217	for (i = 0; i < iface->desc.bNumEndpoints; i++) {
3218		endp = &iface->endpoint[i].desc;
3219		if (((endp->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == dir) &&
3220		    (usb_endpoint_type(endp) == type))
3221			return endp;
3222	}
3223
3224	return NULL;
3225}
3226
3227/* Get the byte that describes which ports are enabled */
3228static int hso_get_mux_ports(struct usb_interface *intf, unsigned char *ports)
3229{
3230	int i;
3231	struct usb_host_interface *iface = intf->cur_altsetting;
3232
3233	if (iface->extralen == 3) {
3234		*ports = iface->extra[2];
3235		return 0;
3236	}
3237
3238	for (i = 0; i < iface->desc.bNumEndpoints; i++) {
3239		if (iface->endpoint[i].extralen == 3) {
3240			*ports = iface->endpoint[i].extra[2];
3241			return 0;
3242		}
3243	}
3244
3245	return -1;
3246}
3247
3248/* interrupt urb needs to be submitted, used for serial read of muxed port */
3249static int hso_mux_submit_intr_urb(struct hso_shared_int *shared_int,
3250				   struct usb_device *usb, gfp_t gfp)
3251{
3252	int result;
3253
3254	usb_fill_int_urb(shared_int->shared_intr_urb, usb,
3255			 usb_rcvintpipe(usb,
3256				shared_int->intr_endp->bEndpointAddress & 0x7F),
3257			 shared_int->shared_intr_buf,
3258			 1,
3259			 intr_callback, shared_int,
3260			 shared_int->intr_endp->bInterval);
3261
3262	result = usb_submit_urb(shared_int->shared_intr_urb, gfp);
3263	if (result)
3264		dev_warn(&usb->dev, "%s failed mux_intr_urb %d\n", __func__,
3265			result);
3266
3267	return result;
3268}
3269
3270/* operations setup of the serial interface */
3271static const struct tty_operations hso_serial_ops = {
3272	.open = hso_serial_open,
3273	.close = hso_serial_close,
3274	.write = hso_serial_write,
3275	.write_room = hso_serial_write_room,
3276	.ioctl = hso_serial_ioctl,
3277	.set_termios = hso_serial_set_termios,
3278	.chars_in_buffer = hso_serial_chars_in_buffer,
3279	.tiocmget = hso_serial_tiocmget,
3280	.tiocmset = hso_serial_tiocmset,
3281	.get_icount = hso_get_count,
3282	.unthrottle = hso_unthrottle
3283};
3284
3285static struct usb_driver hso_driver = {
3286	.name = driver_name,
3287	.probe = hso_probe,
3288	.disconnect = hso_disconnect,
3289	.id_table = hso_ids,
3290	.suspend = hso_suspend,
3291	.resume = hso_resume,
3292	.reset_resume = hso_resume,
3293	.supports_autosuspend = 1,
3294};
3295
3296static int __init hso_init(void)
3297{
3298	int i;
3299	int result;
3300
3301	/* put it in the log */
3302	printk(KERN_INFO "hso: %s\n", version);
3303
3304	/* Initialise the serial table semaphore and table */
3305	spin_lock_init(&serial_table_lock);
3306	for (i = 0; i < HSO_SERIAL_TTY_MINORS; i++)
3307		serial_table[i] = NULL;
3308
3309	/* allocate our driver using the proper amount of supported minors */
3310	tty_drv = alloc_tty_driver(HSO_SERIAL_TTY_MINORS);
3311	if (!tty_drv)
3312		return -ENOMEM;
3313
3314	/* fill in all needed values */
3315	tty_drv->magic = TTY_DRIVER_MAGIC;
3316	tty_drv->driver_name = driver_name;
3317	tty_drv->name = tty_filename;
3318
3319	/* if major number is provided as parameter, use that one */
3320	if (tty_major)
3321		tty_drv->major = tty_major;
3322
3323	tty_drv->minor_start = 0;
3324	tty_drv->type = TTY_DRIVER_TYPE_SERIAL;
3325	tty_drv->subtype = SERIAL_TYPE_NORMAL;
3326	tty_drv->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
3327	tty_drv->init_termios = tty_std_termios;
3328	hso_init_termios(&tty_drv->init_termios);
3329	tty_set_operations(tty_drv, &hso_serial_ops);
3330
3331	/* register the tty driver */
3332	result = tty_register_driver(tty_drv);
3333	if (result) {
3334		printk(KERN_ERR "%s - tty_register_driver failed(%d)\n",
3335			__func__, result);
3336		return result;
3337	}
3338
3339	/* register this module as an usb driver */
3340	result = usb_register(&hso_driver);
3341	if (result) {
3342		printk(KERN_ERR "Could not register hso driver? error: %d\n",
3343			result);
3344		/* cleanup serial interface */
3345		tty_unregister_driver(tty_drv);
3346		return result;
3347	}
3348
3349	/* done */
3350	return 0;
3351}
3352
3353static void __exit hso_exit(void)
3354{
3355	printk(KERN_INFO "hso: unloaded\n");
3356
3357	tty_unregister_driver(tty_drv);
3358	/* deregister the usb driver */
3359	usb_deregister(&hso_driver);
3360}
3361
3362/* Module definitions */
3363module_init(hso_init);
3364module_exit(hso_exit);
3365
3366MODULE_AUTHOR(MOD_AUTHOR);
3367MODULE_DESCRIPTION(MOD_DESCRIPTION);
3368MODULE_LICENSE(MOD_LICENSE);
3369
3370/* change the debug level (eg: insmod hso.ko debug=0x04) */
3371MODULE_PARM_DESC(debug, "Level of debug [0x01 | 0x02 | 0x04 | 0x08 | 0x10]");
3372module_param(debug, int, S_IRUGO | S_IWUSR);
3373
3374/* set the major tty number (eg: insmod hso.ko tty_major=245) */
3375MODULE_PARM_DESC(tty_major, "Set the major tty number");
3376module_param(tty_major, int, S_IRUGO | S_IWUSR);
3377
3378/* disable network interface (eg: insmod hso.ko disable_net=1) */
3379MODULE_PARM_DESC(disable_net, "Disable the network interface");
3380module_param(disable_net, int, S_IRUGO | S_IWUSR);
3381