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