1/*
2 * USB driver for Gigaset 307x base via direct USB connection.
3 *
4 * Copyright (c) 2001 by Hansjoerg Lipp <hjlipp@web.de>,
5 *                       Tilman Schmidt <tilman@imap.cc>,
6 *                       Stefan Eilers.
7 *
8 * =====================================================================
9 *	This program is free software; you can redistribute it and/or
10 *	modify it under the terms of the GNU General Public License as
11 *	published by the Free Software Foundation; either version 2 of
12 *	the License, or (at your option) any later version.
13 * =====================================================================
14 */
15
16#include "gigaset.h"
17
18#include <linux/errno.h>
19#include <linux/init.h>
20#include <linux/slab.h>
21#include <linux/timer.h>
22#include <linux/usb.h>
23#include <linux/module.h>
24#include <linux/moduleparam.h>
25
26/* Version Information */
27#define DRIVER_AUTHOR "Tilman Schmidt <tilman@imap.cc>, Hansjoerg Lipp <hjlipp@web.de>, Stefan Eilers"
28#define DRIVER_DESC "USB Driver for Gigaset 307x"
29
30
31/* Module parameters */
32
33static int startmode = SM_ISDN;
34static int cidmode = 1;
35
36module_param(startmode, int, S_IRUGO);
37module_param(cidmode, int, S_IRUGO);
38MODULE_PARM_DESC(startmode, "start in isdn4linux mode");
39MODULE_PARM_DESC(cidmode, "Call-ID mode");
40
41#define GIGASET_MINORS     1
42#define GIGASET_MINOR      16
43#define GIGASET_MODULENAME "bas_gigaset"
44#define GIGASET_DEVNAME    "ttyGB"
45
46/* length limit according to Siemens 3070usb-protokoll.doc ch. 2.1 */
47#define IF_WRITEBUF 264
48
49/* Values for the Gigaset 307x */
50#define USB_GIGA_VENDOR_ID      0x0681
51#define USB_3070_PRODUCT_ID     0x0001
52#define USB_3075_PRODUCT_ID     0x0002
53#define USB_SX303_PRODUCT_ID    0x0021
54#define USB_SX353_PRODUCT_ID    0x0022
55
56/* table of devices that work with this driver */
57static const struct usb_device_id gigaset_table [] = {
58	{ USB_DEVICE(USB_GIGA_VENDOR_ID, USB_3070_PRODUCT_ID) },
59	{ USB_DEVICE(USB_GIGA_VENDOR_ID, USB_3075_PRODUCT_ID) },
60	{ USB_DEVICE(USB_GIGA_VENDOR_ID, USB_SX303_PRODUCT_ID) },
61	{ USB_DEVICE(USB_GIGA_VENDOR_ID, USB_SX353_PRODUCT_ID) },
62	{ } /* Terminating entry */
63};
64
65MODULE_DEVICE_TABLE(usb, gigaset_table);
66
67/*======================= local function prototypes ==========================*/
68
69/* function called if a new device belonging to this driver is connected */
70static int gigaset_probe(struct usb_interface *interface,
71			 const struct usb_device_id *id);
72
73/* Function will be called if the device is unplugged */
74static void gigaset_disconnect(struct usb_interface *interface);
75
76static int atread_submit(struct cardstate *, int);
77static void stopurbs(struct bas_bc_state *);
78static int req_submit(struct bc_state *, int, int, int);
79static int atwrite_submit(struct cardstate *, unsigned char *, int);
80static int start_cbsend(struct cardstate *);
81
82/*============================================================================*/
83
84struct bas_cardstate {
85	struct usb_device	*udev;		/* USB device pointer */
86	struct usb_interface	*interface;	/* interface for this device */
87	unsigned char		minor;		/* starting minor number */
88
89	struct urb		*urb_ctrl;	/* control pipe default URB */
90	struct usb_ctrlrequest	dr_ctrl;
91	struct timer_list	timer_ctrl;	/* control request timeout */
92	int			retry_ctrl;
93
94	struct timer_list	timer_atrdy;	/* AT command ready timeout */
95	struct urb		*urb_cmd_out;	/* for sending AT commands */
96	struct usb_ctrlrequest	dr_cmd_out;
97	int			retry_cmd_out;
98
99	struct urb		*urb_cmd_in;	/* for receiving AT replies */
100	struct usb_ctrlrequest	dr_cmd_in;
101	struct timer_list	timer_cmd_in;	/* receive request timeout */
102	unsigned char		*rcvbuf;	/* AT reply receive buffer */
103
104	struct urb		*urb_int_in;	/* URB for interrupt pipe */
105	unsigned char		int_in_buf[3];
106
107	spinlock_t		lock;		/* locks all following */
108	atomic_t		basstate;	/* bitmap (BS_*) */
109	int			pending;	/* uncompleted base request */
110	int			rcvbuf_size;	/* size of AT receive buffer */
111						/* 0: no receive in progress */
112	int			retry_cmd_in;	/* receive req retry count */
113};
114
115/* status of direct USB connection to 307x base (bits in basstate) */
116#define BS_ATOPEN	0x001	/* AT channel open */
117#define BS_B1OPEN	0x002	/* B channel 1 open */
118#define BS_B2OPEN	0x004	/* B channel 2 open */
119#define BS_ATREADY	0x008	/* base ready for AT command */
120#define BS_INIT		0x010	/* base has signalled INIT_OK */
121#define BS_ATTIMER	0x020	/* waiting for HD_READY_SEND_ATDATA */
122#define BS_ATRDPEND	0x040	/* urb_cmd_in in use */
123#define BS_ATWRPEND	0x080	/* urb_cmd_out in use */
124
125
126static struct gigaset_driver *driver = NULL;
127static struct cardstate *cardstate = NULL;
128
129/* usb specific object needed to register this driver with the usb subsystem */
130static struct usb_driver gigaset_usb_driver = {
131	.name =         GIGASET_MODULENAME,
132	.probe =        gigaset_probe,
133	.disconnect =   gigaset_disconnect,
134	.id_table =     gigaset_table,
135};
136
137/* get message text for usb_submit_urb return code
138 */
139static char *get_usb_rcmsg(int rc)
140{
141	static char unkmsg[28];
142
143	switch (rc) {
144	case 0:
145		return "success";
146	case -ENOMEM:
147		return "out of memory";
148	case -ENODEV:
149		return "device not present";
150	case -ENOENT:
151		return "endpoint not present";
152	case -ENXIO:
153		return "URB type not supported";
154	case -EINVAL:
155		return "invalid argument";
156	case -EAGAIN:
157		return "start frame too early or too much scheduled";
158	case -EFBIG:
159		return "too many isochronous frames requested";
160	case -EPIPE:
161		return "endpoint stalled";
162	case -EMSGSIZE:
163		return "invalid packet size";
164	case -ENOSPC:
165		return "would overcommit USB bandwidth";
166	case -ESHUTDOWN:
167		return "device shut down";
168	case -EPERM:
169		return "reject flag set";
170	case -EHOSTUNREACH:
171		return "device suspended";
172	default:
173		snprintf(unkmsg, sizeof(unkmsg), "unknown error %d", rc);
174		return unkmsg;
175	}
176}
177
178/* get message text for USB status code
179 */
180static char *get_usb_statmsg(int status)
181{
182	static char unkmsg[28];
183
184	switch (status) {
185	case 0:
186		return "success";
187	case -ENOENT:
188		return "unlinked (sync)";
189	case -EINPROGRESS:
190		return "pending";
191	case -EPROTO:
192		return "bit stuffing error, timeout, or unknown USB error";
193	case -EILSEQ:
194		return "CRC mismatch, timeout, or unknown USB error";
195	case -ETIME:
196		return "timed out";
197	case -EPIPE:
198		return "endpoint stalled";
199	case -ECOMM:
200		return "IN buffer overrun";
201	case -ENOSR:
202		return "OUT buffer underrun";
203	case -EOVERFLOW:
204		return "too much data";
205	case -EREMOTEIO:
206		return "short packet detected";
207	case -ENODEV:
208		return "device removed";
209	case -EXDEV:
210		return "partial isochronous transfer";
211	case -EINVAL:
212		return "invalid argument";
213	case -ECONNRESET:
214		return "unlinked (async)";
215	case -ESHUTDOWN:
216		return "device shut down";
217	default:
218		snprintf(unkmsg, sizeof(unkmsg), "unknown status %d", status);
219		return unkmsg;
220	}
221}
222
223/* usb_pipetype_str
224 * retrieve string representation of USB pipe type
225 */
226static inline char *usb_pipetype_str(int pipe)
227{
228	if (usb_pipeisoc(pipe))
229		return "Isoc";
230	if (usb_pipeint(pipe))
231		return "Int";
232	if (usb_pipecontrol(pipe))
233		return "Ctrl";
234	if (usb_pipebulk(pipe))
235		return "Bulk";
236	return "?";
237}
238
239/* dump_urb
240 * write content of URB to syslog for debugging
241 */
242static inline void dump_urb(enum debuglevel level, const char *tag,
243			    struct urb *urb)
244{
245#ifdef CONFIG_GIGASET_DEBUG
246	int i;
247	gig_dbg(level, "%s urb(0x%08lx)->{", tag, (unsigned long) urb);
248	if (urb) {
249		gig_dbg(level,
250			"  dev=0x%08lx, pipe=%s:EP%d/DV%d:%s, "
251			"status=%d, hcpriv=0x%08lx, transfer_flags=0x%x,",
252			(unsigned long) urb->dev,
253			usb_pipetype_str(urb->pipe),
254			usb_pipeendpoint(urb->pipe), usb_pipedevice(urb->pipe),
255			usb_pipein(urb->pipe) ? "in" : "out",
256			urb->status, (unsigned long) urb->hcpriv,
257			urb->transfer_flags);
258		gig_dbg(level,
259			"  transfer_buffer=0x%08lx[%d], actual_length=%d, "
260			"setup_packet=0x%08lx,",
261			(unsigned long) urb->transfer_buffer,
262			urb->transfer_buffer_length, urb->actual_length,
263			(unsigned long) urb->setup_packet);
264		gig_dbg(level,
265			"  start_frame=%d, number_of_packets=%d, interval=%d, "
266			"error_count=%d,",
267			urb->start_frame, urb->number_of_packets, urb->interval,
268			urb->error_count);
269		gig_dbg(level,
270			"  context=0x%08lx, complete=0x%08lx, "
271			"iso_frame_desc[]={",
272			(unsigned long) urb->context,
273			(unsigned long) urb->complete);
274		for (i = 0; i < urb->number_of_packets; i++) {
275			struct usb_iso_packet_descriptor *pifd
276				= &urb->iso_frame_desc[i];
277			gig_dbg(level,
278				"    {offset=%u, length=%u, actual_length=%u, "
279				"status=%u}",
280				pifd->offset, pifd->length, pifd->actual_length,
281				pifd->status);
282		}
283	}
284	gig_dbg(level, "}}");
285#endif
286}
287
288/* read/set modem control bits etc. (m10x only) */
289static int gigaset_set_modem_ctrl(struct cardstate *cs, unsigned old_state,
290				  unsigned new_state)
291{
292	return -EINVAL;
293}
294
295static int gigaset_baud_rate(struct cardstate *cs, unsigned cflag)
296{
297	return -EINVAL;
298}
299
300static int gigaset_set_line_ctrl(struct cardstate *cs, unsigned cflag)
301{
302	return -EINVAL;
303}
304
305/* error_hangup
306 * hang up any existing connection because of an unrecoverable error
307 * This function may be called from any context and takes care of scheduling
308 * the necessary actions for execution outside of interrupt context.
309 * cs->lock must not be held.
310 * argument:
311 *	B channel control structure
312 */
313static inline void error_hangup(struct bc_state *bcs)
314{
315	struct cardstate *cs = bcs->cs;
316
317	gig_dbg(DEBUG_ANY, "%s: scheduling HUP for channel %d",
318		__func__, bcs->channel);
319
320	if (!gigaset_add_event(cs, &bcs->at_state, EV_HUP, NULL, 0, NULL))
321		dev_err(cs->dev, "event queue full\n");
322
323	gigaset_schedule_event(cs);
324}
325
326/* error_reset
327 * reset Gigaset device because of an unrecoverable error
328 * This function may be called from any context, and takes care of
329 * scheduling the necessary actions for execution outside of interrupt context.
330 * cs->lock must not be held.
331 * argument:
332 *	controller state structure
333 */
334static inline void error_reset(struct cardstate *cs)
335{
336	/* close AT command channel to recover (ignore errors) */
337	req_submit(cs->bcs, HD_CLOSE_ATCHANNEL, 0, BAS_TIMEOUT);
338
339	dev_err(cs->dev,
340	    "unrecoverable error - please disconnect Gigaset base to reset\n");
341}
342
343/* check_pending
344 * check for completion of pending control request
345 * parameter:
346 *	ucs	hardware specific controller state structure
347 */
348static void check_pending(struct bas_cardstate *ucs)
349{
350	unsigned long flags;
351
352	spin_lock_irqsave(&ucs->lock, flags);
353	switch (ucs->pending) {
354	case 0:
355		break;
356	case HD_OPEN_ATCHANNEL:
357		if (atomic_read(&ucs->basstate) & BS_ATOPEN)
358			ucs->pending = 0;
359		break;
360	case HD_OPEN_B1CHANNEL:
361		if (atomic_read(&ucs->basstate) & BS_B1OPEN)
362			ucs->pending = 0;
363		break;
364	case HD_OPEN_B2CHANNEL:
365		if (atomic_read(&ucs->basstate) & BS_B2OPEN)
366			ucs->pending = 0;
367		break;
368	case HD_CLOSE_ATCHANNEL:
369		if (!(atomic_read(&ucs->basstate) & BS_ATOPEN))
370			ucs->pending = 0;
371		break;
372	case HD_CLOSE_B1CHANNEL:
373		if (!(atomic_read(&ucs->basstate) & BS_B1OPEN))
374			ucs->pending = 0;
375		break;
376	case HD_CLOSE_B2CHANNEL:
377		if (!(atomic_read(&ucs->basstate) & BS_B2OPEN))
378			ucs->pending = 0;
379		break;
380	case HD_DEVICE_INIT_ACK:		/* no reply expected */
381		ucs->pending = 0;
382		break;
383	/* HD_READ_ATMESSAGE, HD_WRITE_ATMESSAGE, HD_RESET_INTERRUPTPIPE
384	 * are handled separately and should never end up here
385	 */
386	default:
387		dev_warn(&ucs->interface->dev,
388			 "unknown pending request 0x%02x cleared\n",
389			 ucs->pending);
390		ucs->pending = 0;
391	}
392
393	if (!ucs->pending)
394		del_timer(&ucs->timer_ctrl);
395
396	spin_unlock_irqrestore(&ucs->lock, flags);
397}
398
399/* cmd_in_timeout
400 * timeout routine for command input request
401 * argument:
402 *	controller state structure
403 */
404static void cmd_in_timeout(unsigned long data)
405{
406	struct cardstate *cs = (struct cardstate *) data;
407	struct bas_cardstate *ucs = cs->hw.bas;
408	int rc;
409
410	if (!ucs->rcvbuf_size) {
411		gig_dbg(DEBUG_USBREQ, "%s: no receive in progress", __func__);
412		return;
413	}
414
415	if (ucs->retry_cmd_in++ < BAS_RETRY) {
416		dev_notice(cs->dev, "control read: timeout, retry %d\n",
417			   ucs->retry_cmd_in);
418		rc = atread_submit(cs, BAS_TIMEOUT);
419		if (rc >= 0 || rc == -ENODEV)
420			/* resubmitted or disconnected */
421			/* - bypass regular exit block */
422			return;
423	} else {
424		dev_err(cs->dev,
425			"control read: timeout, giving up after %d tries\n",
426			ucs->retry_cmd_in);
427	}
428	kfree(ucs->rcvbuf);
429	ucs->rcvbuf = NULL;
430	ucs->rcvbuf_size = 0;
431	error_reset(cs);
432}
433
434/* set/clear bits in base connection state, return previous state
435 */
436inline static int update_basstate(struct bas_cardstate *ucs,
437				  int set, int clear)
438{
439	unsigned long flags;
440	int state;
441
442	spin_lock_irqsave(&ucs->lock, flags);
443	state = atomic_read(&ucs->basstate);
444	atomic_set(&ucs->basstate, (state & ~clear) | set);
445	spin_unlock_irqrestore(&ucs->lock, flags);
446	return state;
447}
448
449/* read_ctrl_callback
450 * USB completion handler for control pipe input
451 * called by the USB subsystem in interrupt context
452 * parameter:
453 *	urb	USB request block
454 *		urb->context = inbuf structure for controller state
455 */
456static void read_ctrl_callback(struct urb *urb)
457{
458	struct inbuf_t *inbuf = urb->context;
459	struct cardstate *cs = inbuf->cs;
460	struct bas_cardstate *ucs = cs->hw.bas;
461	int have_data = 0;
462	unsigned numbytes;
463	int rc;
464
465	update_basstate(ucs, 0, BS_ATRDPEND);
466
467	if (!ucs->rcvbuf_size) {
468		dev_warn(cs->dev, "%s: no receive in progress\n", __func__);
469		return;
470	}
471
472	del_timer(&ucs->timer_cmd_in);
473
474	switch (urb->status) {
475	case 0:				/* normal completion */
476		numbytes = urb->actual_length;
477		if (unlikely(numbytes != ucs->rcvbuf_size)) {
478			dev_warn(cs->dev,
479			       "control read: received %d chars, expected %d\n",
480				 numbytes, ucs->rcvbuf_size);
481			if (numbytes > ucs->rcvbuf_size)
482				numbytes = ucs->rcvbuf_size;
483		}
484
485		/* copy received bytes to inbuf */
486		have_data = gigaset_fill_inbuf(inbuf, ucs->rcvbuf, numbytes);
487
488		if (unlikely(numbytes < ucs->rcvbuf_size)) {
489			/* incomplete - resubmit for remaining bytes */
490			ucs->rcvbuf_size -= numbytes;
491			ucs->retry_cmd_in = 0;
492			rc = atread_submit(cs, BAS_TIMEOUT);
493			if (rc >= 0 || rc == -ENODEV)
494				/* resubmitted or disconnected */
495				/* - bypass regular exit block */
496				return;
497			error_reset(cs);
498		}
499		break;
500
501	case -ENOENT:			/* cancelled */
502	case -ECONNRESET:		/* cancelled (async) */
503	case -EINPROGRESS:		/* pending */
504	case -ENODEV:			/* device removed */
505	case -ESHUTDOWN:		/* device shut down */
506		/* no action necessary */
507		gig_dbg(DEBUG_USBREQ, "%s: %s",
508			__func__, get_usb_statmsg(urb->status));
509		break;
510
511	default:			/* severe trouble */
512		dev_warn(cs->dev, "control read: %s\n",
513			 get_usb_statmsg(urb->status));
514		if (ucs->retry_cmd_in++ < BAS_RETRY) {
515			dev_notice(cs->dev, "control read: retry %d\n",
516				   ucs->retry_cmd_in);
517			rc = atread_submit(cs, BAS_TIMEOUT);
518			if (rc >= 0 || rc == -ENODEV)
519				/* resubmitted or disconnected */
520				/* - bypass regular exit block */
521				return;
522		} else {
523			dev_err(cs->dev,
524				"control read: giving up after %d tries\n",
525				ucs->retry_cmd_in);
526		}
527		error_reset(cs);
528	}
529
530	kfree(ucs->rcvbuf);
531	ucs->rcvbuf = NULL;
532	ucs->rcvbuf_size = 0;
533	if (have_data) {
534		gig_dbg(DEBUG_INTR, "%s-->BH", __func__);
535		gigaset_schedule_event(cs);
536	}
537}
538
539/* atread_submit
540 * submit an HD_READ_ATMESSAGE command URB and optionally start a timeout
541 * parameters:
542 *	cs	controller state structure
543 *	timeout	timeout in 1/10 sec., 0: none
544 * return value:
545 *	0 on success
546 *	-EBUSY if another request is pending
547 *	any URB submission error code
548 */
549static int atread_submit(struct cardstate *cs, int timeout)
550{
551	struct bas_cardstate *ucs = cs->hw.bas;
552	int ret;
553
554	gig_dbg(DEBUG_USBREQ, "-------> HD_READ_ATMESSAGE (%d)",
555		ucs->rcvbuf_size);
556
557	if (update_basstate(ucs, BS_ATRDPEND, 0) & BS_ATRDPEND) {
558		dev_err(cs->dev,
559			"could not submit HD_READ_ATMESSAGE: URB busy\n");
560		return -EBUSY;
561	}
562
563	ucs->dr_cmd_in.bRequestType = IN_VENDOR_REQ;
564	ucs->dr_cmd_in.bRequest = HD_READ_ATMESSAGE;
565	ucs->dr_cmd_in.wValue = 0;
566	ucs->dr_cmd_in.wIndex = 0;
567	ucs->dr_cmd_in.wLength = cpu_to_le16(ucs->rcvbuf_size);
568	usb_fill_control_urb(ucs->urb_cmd_in, ucs->udev,
569			     usb_rcvctrlpipe(ucs->udev, 0),
570			     (unsigned char*) & ucs->dr_cmd_in,
571			     ucs->rcvbuf, ucs->rcvbuf_size,
572			     read_ctrl_callback, cs->inbuf);
573
574	if ((ret = usb_submit_urb(ucs->urb_cmd_in, GFP_ATOMIC)) != 0) {
575		update_basstate(ucs, 0, BS_ATRDPEND);
576		dev_err(cs->dev, "could not submit HD_READ_ATMESSAGE: %s\n",
577			get_usb_rcmsg(ret));
578		return ret;
579	}
580
581	if (timeout > 0) {
582		gig_dbg(DEBUG_USBREQ, "setting timeout of %d/10 secs", timeout);
583		ucs->timer_cmd_in.expires = jiffies + timeout * HZ / 10;
584		ucs->timer_cmd_in.data = (unsigned long) cs;
585		ucs->timer_cmd_in.function = cmd_in_timeout;
586		add_timer(&ucs->timer_cmd_in);
587	}
588	return 0;
589}
590
591/* read_int_callback
592 * USB completion handler for interrupt pipe input
593 * called by the USB subsystem in interrupt context
594 * parameter:
595 *	urb	USB request block
596 *		urb->context = controller state structure
597 */
598static void read_int_callback(struct urb *urb)
599{
600	struct cardstate *cs = urb->context;
601	struct bas_cardstate *ucs = cs->hw.bas;
602	struct bc_state *bcs;
603	unsigned long flags;
604	int rc;
605	unsigned l;
606	int channel;
607
608	switch (urb->status) {
609	case 0:			/* success */
610		break;
611	case -ENOENT:			/* cancelled */
612	case -ECONNRESET:		/* cancelled (async) */
613	case -EINPROGRESS:		/* pending */
614		/* ignore silently */
615		gig_dbg(DEBUG_USBREQ, "%s: %s",
616			__func__, get_usb_statmsg(urb->status));
617		return;
618	case -ENODEV:			/* device removed */
619	case -ESHUTDOWN:		/* device shut down */
620		gig_dbg(DEBUG_USBREQ, "%s: device disconnected", __func__);
621		return;
622	default:		/* severe trouble */
623		dev_warn(cs->dev, "interrupt read: %s\n",
624			 get_usb_statmsg(urb->status));
625		goto resubmit;
626	}
627
628	/* drop incomplete packets even if the missing bytes wouldn't matter */
629	if (unlikely(urb->actual_length < 3)) {
630		dev_warn(cs->dev, "incomplete interrupt packet (%d bytes)\n",
631			 urb->actual_length);
632		goto resubmit;
633	}
634
635	l = (unsigned) ucs->int_in_buf[1] +
636	    (((unsigned) ucs->int_in_buf[2]) << 8);
637
638	gig_dbg(DEBUG_USBREQ, "<-------%d: 0x%02x (%u [0x%02x 0x%02x])",
639		urb->actual_length, (int)ucs->int_in_buf[0], l,
640		(int)ucs->int_in_buf[1], (int)ucs->int_in_buf[2]);
641
642	channel = 0;
643
644	switch (ucs->int_in_buf[0]) {
645	case HD_DEVICE_INIT_OK:
646		update_basstate(ucs, BS_INIT, 0);
647		break;
648
649	case HD_READY_SEND_ATDATA:
650		del_timer(&ucs->timer_atrdy);
651		update_basstate(ucs, BS_ATREADY, BS_ATTIMER);
652		start_cbsend(cs);
653		break;
654
655	case HD_OPEN_B2CHANNEL_ACK:
656		++channel;
657	case HD_OPEN_B1CHANNEL_ACK:
658		bcs = cs->bcs + channel;
659		update_basstate(ucs, BS_B1OPEN << channel, 0);
660		gigaset_bchannel_up(bcs);
661		break;
662
663	case HD_OPEN_ATCHANNEL_ACK:
664		update_basstate(ucs, BS_ATOPEN, 0);
665		start_cbsend(cs);
666		break;
667
668	case HD_CLOSE_B2CHANNEL_ACK:
669		++channel;
670	case HD_CLOSE_B1CHANNEL_ACK:
671		bcs = cs->bcs + channel;
672		update_basstate(ucs, 0, BS_B1OPEN << channel);
673		stopurbs(bcs->hw.bas);
674		gigaset_bchannel_down(bcs);
675		break;
676
677	case HD_CLOSE_ATCHANNEL_ACK:
678		update_basstate(ucs, 0, BS_ATOPEN);
679		break;
680
681	case HD_B2_FLOW_CONTROL:
682		++channel;
683	case HD_B1_FLOW_CONTROL:
684		bcs = cs->bcs + channel;
685		atomic_add((l - BAS_NORMFRAME) * BAS_CORRFRAMES,
686			   &bcs->hw.bas->corrbytes);
687		gig_dbg(DEBUG_ISO,
688			"Flow control (channel %d, sub %d): 0x%02x => %d",
689			channel, bcs->hw.bas->numsub, l,
690			atomic_read(&bcs->hw.bas->corrbytes));
691		break;
692
693	case HD_RECEIVEATDATA_ACK:	/* AT response ready to be received */
694		if (!l) {
695			dev_warn(cs->dev,
696				"HD_RECEIVEATDATA_ACK with length 0 ignored\n");
697			break;
698		}
699		spin_lock_irqsave(&cs->lock, flags);
700		if (ucs->rcvbuf_size) {
701			/* throw away previous buffer - we have no queue */
702			dev_err(cs->dev,
703				"receive AT data overrun, %d bytes lost\n",
704				ucs->rcvbuf_size);
705			kfree(ucs->rcvbuf);
706			ucs->rcvbuf_size = 0;
707		}
708		if ((ucs->rcvbuf = kmalloc(l, GFP_ATOMIC)) == NULL) {
709			spin_unlock_irqrestore(&cs->lock, flags);
710			dev_err(cs->dev, "out of memory receiving AT data\n");
711			error_reset(cs);
712			break;
713		}
714		ucs->rcvbuf_size = l;
715		ucs->retry_cmd_in = 0;
716		if ((rc = atread_submit(cs, BAS_TIMEOUT)) < 0) {
717			kfree(ucs->rcvbuf);
718			ucs->rcvbuf = NULL;
719			ucs->rcvbuf_size = 0;
720			if (rc != -ENODEV) {
721				spin_unlock_irqrestore(&cs->lock, flags);
722				error_reset(cs);
723				break;
724			}
725		}
726		spin_unlock_irqrestore(&cs->lock, flags);
727		break;
728
729	case HD_RESET_INTERRUPT_PIPE_ACK:
730		gig_dbg(DEBUG_USBREQ, "HD_RESET_INTERRUPT_PIPE_ACK");
731		break;
732
733	case HD_SUSPEND_END:
734		gig_dbg(DEBUG_USBREQ, "HD_SUSPEND_END");
735		break;
736
737	default:
738		dev_warn(cs->dev,
739			 "unknown Gigaset signal 0x%02x (%u) ignored\n",
740			 (int) ucs->int_in_buf[0], l);
741	}
742
743	check_pending(ucs);
744
745resubmit:
746	rc = usb_submit_urb(urb, GFP_ATOMIC);
747	if (unlikely(rc != 0 && rc != -ENODEV)) {
748		dev_err(cs->dev, "could not resubmit interrupt URB: %s\n",
749			get_usb_rcmsg(rc));
750		error_reset(cs);
751	}
752}
753
754/* read_iso_callback
755 * USB completion handler for B channel isochronous input
756 * called by the USB subsystem in interrupt context
757 * parameter:
758 *	urb	USB request block of completed request
759 *		urb->context = bc_state structure
760 */
761static void read_iso_callback(struct urb *urb)
762{
763	struct bc_state *bcs;
764	struct bas_bc_state *ubc;
765	unsigned long flags;
766	int i, rc;
767
768	/* status codes not worth bothering the tasklet with */
769	if (unlikely(urb->status == -ENOENT ||
770		     urb->status == -ECONNRESET ||
771		     urb->status == -EINPROGRESS ||
772		     urb->status == -ENODEV ||
773		     urb->status == -ESHUTDOWN)) {
774		gig_dbg(DEBUG_ISO, "%s: %s",
775			__func__, get_usb_statmsg(urb->status));
776		return;
777	}
778
779	bcs = urb->context;
780	ubc = bcs->hw.bas;
781
782	spin_lock_irqsave(&ubc->isoinlock, flags);
783	if (likely(ubc->isoindone == NULL)) {
784		/* pass URB to tasklet */
785		ubc->isoindone = urb;
786		tasklet_schedule(&ubc->rcvd_tasklet);
787	} else {
788		/* tasklet still busy, drop data and resubmit URB */
789		ubc->loststatus = urb->status;
790		for (i = 0; i < BAS_NUMFRAMES; i++) {
791			ubc->isoinlost += urb->iso_frame_desc[i].actual_length;
792			if (unlikely(urb->iso_frame_desc[i].status != 0 &&
793				     urb->iso_frame_desc[i].status !=
794								-EINPROGRESS))
795				ubc->loststatus = urb->iso_frame_desc[i].status;
796			urb->iso_frame_desc[i].status = 0;
797			urb->iso_frame_desc[i].actual_length = 0;
798		}
799		if (likely(atomic_read(&ubc->running))) {
800			/* urb->dev is clobbered by USB subsystem */
801			urb->dev = bcs->cs->hw.bas->udev;
802			urb->transfer_flags = URB_ISO_ASAP;
803			urb->number_of_packets = BAS_NUMFRAMES;
804			gig_dbg(DEBUG_ISO, "%s: isoc read overrun/resubmit",
805				__func__);
806			rc = usb_submit_urb(urb, GFP_ATOMIC);
807			if (unlikely(rc != 0 && rc != -ENODEV)) {
808				dev_err(bcs->cs->dev,
809					"could not resubmit isochronous read "
810					"URB: %s\n", get_usb_rcmsg(rc));
811				dump_urb(DEBUG_ISO, "isoc read", urb);
812				error_hangup(bcs);
813			}
814		}
815	}
816	spin_unlock_irqrestore(&ubc->isoinlock, flags);
817}
818
819/* write_iso_callback
820 * USB completion handler for B channel isochronous output
821 * called by the USB subsystem in interrupt context
822 * parameter:
823 *	urb	USB request block of completed request
824 *		urb->context = isow_urbctx_t structure
825 */
826static void write_iso_callback(struct urb *urb)
827{
828	struct isow_urbctx_t *ucx;
829	struct bas_bc_state *ubc;
830	unsigned long flags;
831
832	/* status codes not worth bothering the tasklet with */
833	if (unlikely(urb->status == -ENOENT ||
834		     urb->status == -ECONNRESET ||
835		     urb->status == -EINPROGRESS ||
836		     urb->status == -ENODEV ||
837		     urb->status == -ESHUTDOWN)) {
838		gig_dbg(DEBUG_ISO, "%s: %s",
839			__func__, get_usb_statmsg(urb->status));
840		return;
841	}
842
843	/* pass URB context to tasklet */
844	ucx = urb->context;
845	ubc = ucx->bcs->hw.bas;
846
847	spin_lock_irqsave(&ubc->isooutlock, flags);
848	ubc->isooutovfl = ubc->isooutdone;
849	ubc->isooutdone = ucx;
850	spin_unlock_irqrestore(&ubc->isooutlock, flags);
851	tasklet_schedule(&ubc->sent_tasklet);
852}
853
854/* starturbs
855 * prepare and submit USB request blocks for isochronous input and output
856 * argument:
857 *	B channel control structure
858 * return value:
859 *	0 on success
860 *	< 0 on error (no URBs submitted)
861 */
862static int starturbs(struct bc_state *bcs)
863{
864	struct bas_bc_state *ubc = bcs->hw.bas;
865	struct urb *urb;
866	int j, k;
867	int rc;
868
869	/* initialize L2 reception */
870	if (bcs->proto2 == ISDN_PROTO_L2_HDLC)
871		bcs->inputstate |= INS_flag_hunt;
872
873	/* submit all isochronous input URBs */
874	atomic_set(&ubc->running, 1);
875	for (k = 0; k < BAS_INURBS; k++) {
876		urb = ubc->isoinurbs[k];
877		if (!urb) {
878			rc = -EFAULT;
879			goto error;
880		}
881
882		urb->dev = bcs->cs->hw.bas->udev;
883		urb->pipe = usb_rcvisocpipe(urb->dev, 3 + 2 * bcs->channel);
884		urb->transfer_flags = URB_ISO_ASAP;
885		urb->transfer_buffer = ubc->isoinbuf + k * BAS_INBUFSIZE;
886		urb->transfer_buffer_length = BAS_INBUFSIZE;
887		urb->number_of_packets = BAS_NUMFRAMES;
888		urb->interval = BAS_FRAMETIME;
889		urb->complete = read_iso_callback;
890		urb->context = bcs;
891		for (j = 0; j < BAS_NUMFRAMES; j++) {
892			urb->iso_frame_desc[j].offset = j * BAS_MAXFRAME;
893			urb->iso_frame_desc[j].length = BAS_MAXFRAME;
894			urb->iso_frame_desc[j].status = 0;
895			urb->iso_frame_desc[j].actual_length = 0;
896		}
897
898		dump_urb(DEBUG_ISO, "Initial isoc read", urb);
899		if ((rc = usb_submit_urb(urb, GFP_ATOMIC)) != 0)
900			goto error;
901	}
902
903	/* initialize L2 transmission */
904	gigaset_isowbuf_init(ubc->isooutbuf, PPP_FLAG);
905
906	/* set up isochronous output URBs for flag idling */
907	for (k = 0; k < BAS_OUTURBS; ++k) {
908		urb = ubc->isoouturbs[k].urb;
909		if (!urb) {
910			rc = -EFAULT;
911			goto error;
912		}
913		urb->dev = bcs->cs->hw.bas->udev;
914		urb->pipe = usb_sndisocpipe(urb->dev, 4 + 2 * bcs->channel);
915		urb->transfer_flags = URB_ISO_ASAP;
916		urb->transfer_buffer = ubc->isooutbuf->data;
917		urb->transfer_buffer_length = sizeof(ubc->isooutbuf->data);
918		urb->number_of_packets = BAS_NUMFRAMES;
919		urb->interval = BAS_FRAMETIME;
920		urb->complete = write_iso_callback;
921		urb->context = &ubc->isoouturbs[k];
922		for (j = 0; j < BAS_NUMFRAMES; ++j) {
923			urb->iso_frame_desc[j].offset = BAS_OUTBUFSIZE;
924			urb->iso_frame_desc[j].length = BAS_NORMFRAME;
925			urb->iso_frame_desc[j].status = 0;
926			urb->iso_frame_desc[j].actual_length = 0;
927		}
928		ubc->isoouturbs[k].limit = -1;
929	}
930
931	/* submit two URBs, keep third one */
932	for (k = 0; k < 2; ++k) {
933		dump_urb(DEBUG_ISO, "Initial isoc write", urb);
934		rc = usb_submit_urb(ubc->isoouturbs[k].urb, GFP_ATOMIC);
935		if (rc != 0)
936			goto error;
937	}
938	dump_urb(DEBUG_ISO, "Initial isoc write (free)", urb);
939	ubc->isooutfree = &ubc->isoouturbs[2];
940	ubc->isooutdone = ubc->isooutovfl = NULL;
941	return 0;
942 error:
943	stopurbs(ubc);
944	return rc;
945}
946
947/* stopurbs
948 * cancel the USB request blocks for isochronous input and output
949 * errors are silently ignored
950 * argument:
951 *	B channel control structure
952 */
953static void stopurbs(struct bas_bc_state *ubc)
954{
955	int k, rc;
956
957	atomic_set(&ubc->running, 0);
958
959	for (k = 0; k < BAS_INURBS; ++k) {
960		rc = usb_unlink_urb(ubc->isoinurbs[k]);
961		gig_dbg(DEBUG_ISO,
962			"%s: isoc input URB %d unlinked, result = %s",
963			__func__, k, get_usb_rcmsg(rc));
964	}
965
966	for (k = 0; k < BAS_OUTURBS; ++k) {
967		rc = usb_unlink_urb(ubc->isoouturbs[k].urb);
968		gig_dbg(DEBUG_ISO,
969			"%s: isoc output URB %d unlinked, result = %s",
970			__func__, k, get_usb_rcmsg(rc));
971	}
972}
973
974/* Isochronous Write - Bottom Half */
975/* =============================== */
976
977/* submit_iso_write_urb
978 * fill and submit the next isochronous write URB
979 * parameters:
980 *	ucx	context structure containing URB
981 * return value:
982 *	number of frames submitted in URB
983 *	0 if URB not submitted because no data available (isooutbuf busy)
984 *	error code < 0 on error
985 */
986static int submit_iso_write_urb(struct isow_urbctx_t *ucx)
987{
988	struct urb *urb = ucx->urb;
989	struct bas_bc_state *ubc = ucx->bcs->hw.bas;
990	struct usb_iso_packet_descriptor *ifd;
991	int corrbytes, nframe, rc;
992
993	/* urb->dev is clobbered by USB subsystem */
994	urb->dev = ucx->bcs->cs->hw.bas->udev;
995	urb->transfer_flags = URB_ISO_ASAP;
996	urb->transfer_buffer = ubc->isooutbuf->data;
997	urb->transfer_buffer_length = sizeof(ubc->isooutbuf->data);
998
999	for (nframe = 0; nframe < BAS_NUMFRAMES; nframe++) {
1000		ifd = &urb->iso_frame_desc[nframe];
1001
1002		/* compute frame length according to flow control */
1003		ifd->length = BAS_NORMFRAME;
1004		if ((corrbytes = atomic_read(&ubc->corrbytes)) != 0) {
1005			gig_dbg(DEBUG_ISO, "%s: corrbytes=%d",
1006				__func__, corrbytes);
1007			if (corrbytes > BAS_HIGHFRAME - BAS_NORMFRAME)
1008				corrbytes = BAS_HIGHFRAME - BAS_NORMFRAME;
1009			else if (corrbytes < BAS_LOWFRAME - BAS_NORMFRAME)
1010				corrbytes = BAS_LOWFRAME - BAS_NORMFRAME;
1011			ifd->length += corrbytes;
1012			atomic_add(-corrbytes, &ubc->corrbytes);
1013		}
1014
1015		/* retrieve block of data to send */
1016		ifd->offset = gigaset_isowbuf_getbytes(ubc->isooutbuf,
1017						       ifd->length);
1018		if (ifd->offset < 0) {
1019			if (ifd->offset == -EBUSY) {
1020				gig_dbg(DEBUG_ISO,
1021					"%s: buffer busy at frame %d",
1022					__func__, nframe);
1023				/* tasklet will be restarted from
1024				   gigaset_send_skb() */
1025			} else {
1026				dev_err(ucx->bcs->cs->dev,
1027					"%s: buffer error %d at frame %d\n",
1028					__func__, ifd->offset, nframe);
1029				return ifd->offset;
1030			}
1031			break;
1032		}
1033		ucx->limit = atomic_read(&ubc->isooutbuf->nextread);
1034		ifd->status = 0;
1035		ifd->actual_length = 0;
1036	}
1037	if (unlikely(nframe == 0))
1038		return 0;	/* no data to send */
1039	urb->number_of_packets = nframe;
1040
1041	rc = usb_submit_urb(urb, GFP_ATOMIC);
1042	if (unlikely(rc)) {
1043		if (rc == -ENODEV)
1044			/* device removed - give up silently */
1045			gig_dbg(DEBUG_ISO, "%s: disconnected", __func__);
1046		else
1047			dev_err(ucx->bcs->cs->dev,
1048				"could not submit isochronous write URB: %s\n",
1049				get_usb_rcmsg(rc));
1050		return rc;
1051	}
1052	++ubc->numsub;
1053	return nframe;
1054}
1055
1056/* write_iso_tasklet
1057 * tasklet scheduled when an isochronous output URB from the Gigaset device
1058 * has completed
1059 * parameter:
1060 *	data	B channel state structure
1061 */
1062static void write_iso_tasklet(unsigned long data)
1063{
1064	struct bc_state *bcs = (struct bc_state *) data;
1065	struct bas_bc_state *ubc = bcs->hw.bas;
1066	struct cardstate *cs = bcs->cs;
1067	struct isow_urbctx_t *done, *next, *ovfl;
1068	struct urb *urb;
1069	struct usb_iso_packet_descriptor *ifd;
1070	int offset;
1071	unsigned long flags;
1072	int i;
1073	struct sk_buff *skb;
1074	int len;
1075	int rc;
1076
1077	/* loop while completed URBs arrive in time */
1078	for (;;) {
1079		if (unlikely(!(atomic_read(&ubc->running)))) {
1080			gig_dbg(DEBUG_ISO, "%s: not running", __func__);
1081			return;
1082		}
1083
1084		/* retrieve completed URBs */
1085		spin_lock_irqsave(&ubc->isooutlock, flags);
1086		done = ubc->isooutdone;
1087		ubc->isooutdone = NULL;
1088		ovfl = ubc->isooutovfl;
1089		ubc->isooutovfl = NULL;
1090		spin_unlock_irqrestore(&ubc->isooutlock, flags);
1091		if (ovfl) {
1092			dev_err(cs->dev, "isochronous write buffer underrun\n");
1093			error_hangup(bcs);
1094			break;
1095		}
1096		if (!done)
1097			break;
1098
1099		/* submit free URB if available */
1100		spin_lock_irqsave(&ubc->isooutlock, flags);
1101		next = ubc->isooutfree;
1102		ubc->isooutfree = NULL;
1103		spin_unlock_irqrestore(&ubc->isooutlock, flags);
1104		if (next) {
1105			rc = submit_iso_write_urb(next);
1106			if (unlikely(rc <= 0 && rc != -ENODEV)) {
1107				/* could not submit URB, put it back */
1108				spin_lock_irqsave(&ubc->isooutlock, flags);
1109				if (ubc->isooutfree == NULL) {
1110					ubc->isooutfree = next;
1111					next = NULL;
1112				}
1113				spin_unlock_irqrestore(&ubc->isooutlock, flags);
1114				if (next) {
1115					/* couldn't put it back */
1116					dev_err(cs->dev,
1117					      "losing isochronous write URB\n");
1118					error_hangup(bcs);
1119				}
1120			}
1121		}
1122
1123		/* process completed URB */
1124		urb = done->urb;
1125		switch (urb->status) {
1126		case -EXDEV:			/* partial completion */
1127			gig_dbg(DEBUG_ISO, "%s: URB partially completed",
1128				__func__);
1129			/* fall through - what's the difference anyway? */
1130		case 0:				/* normal completion */
1131			/* inspect individual frames
1132			 * assumptions (for lack of documentation):
1133			 * - actual_length bytes of first frame in error are
1134			 *   successfully sent
1135			 * - all following frames are not sent at all
1136			 */
1137			offset = done->limit;	/* default (no error) */
1138			for (i = 0; i < BAS_NUMFRAMES; i++) {
1139				ifd = &urb->iso_frame_desc[i];
1140				if (ifd->status ||
1141				    ifd->actual_length != ifd->length) {
1142					dev_warn(cs->dev,
1143					     "isochronous write: frame %d: %s, "
1144					     "only %d of %d bytes sent\n",
1145					     i, get_usb_statmsg(ifd->status),
1146					     ifd->actual_length, ifd->length);
1147					offset = (ifd->offset +
1148						  ifd->actual_length)
1149						 % BAS_OUTBUFSIZE;
1150					break;
1151				}
1152			}
1153#ifdef CONFIG_GIGASET_DEBUG
1154			/* check assumption on remaining frames */
1155			for (; i < BAS_NUMFRAMES; i++) {
1156				ifd = &urb->iso_frame_desc[i];
1157				if (ifd->status != -EINPROGRESS
1158				    || ifd->actual_length != 0) {
1159					dev_warn(cs->dev,
1160					     "isochronous write: frame %d: %s, "
1161					     "%d of %d bytes sent\n",
1162					     i, get_usb_statmsg(ifd->status),
1163					     ifd->actual_length, ifd->length);
1164					offset = (ifd->offset +
1165						  ifd->actual_length)
1166						 % BAS_OUTBUFSIZE;
1167					break;
1168				}
1169			}
1170#endif
1171			break;
1172		case -EPIPE:			/* stall - probably underrun */
1173			dev_err(cs->dev, "isochronous write stalled\n");
1174			error_hangup(bcs);
1175			break;
1176		default:			/* severe trouble */
1177			dev_warn(cs->dev, "isochronous write: %s\n",
1178				 get_usb_statmsg(urb->status));
1179		}
1180
1181		/* mark the write buffer area covered by this URB as free */
1182		if (done->limit >= 0)
1183			atomic_set(&ubc->isooutbuf->read, done->limit);
1184
1185		/* mark URB as free */
1186		spin_lock_irqsave(&ubc->isooutlock, flags);
1187		next = ubc->isooutfree;
1188		ubc->isooutfree = done;
1189		spin_unlock_irqrestore(&ubc->isooutlock, flags);
1190		if (next) {
1191			/* only one URB still active - resubmit one */
1192			rc = submit_iso_write_urb(next);
1193			if (unlikely(rc <= 0 && rc != -ENODEV)) {
1194				/* couldn't submit */
1195				error_hangup(bcs);
1196			}
1197		}
1198	}
1199
1200	/* process queued SKBs */
1201	while ((skb = skb_dequeue(&bcs->squeue))) {
1202		/* copy to output buffer, doing L2 encapsulation */
1203		len = skb->len;
1204		if (gigaset_isoc_buildframe(bcs, skb->data, len) == -EAGAIN) {
1205			/* insufficient buffer space, push back onto queue */
1206			skb_queue_head(&bcs->squeue, skb);
1207			gig_dbg(DEBUG_ISO, "%s: skb requeued, qlen=%d",
1208				__func__, skb_queue_len(&bcs->squeue));
1209			break;
1210		}
1211		skb_pull(skb, len);
1212		gigaset_skb_sent(bcs, skb);
1213		dev_kfree_skb_any(skb);
1214	}
1215}
1216
1217/* Isochronous Read - Bottom Half */
1218/* ============================== */
1219
1220/* read_iso_tasklet
1221 * tasklet scheduled when an isochronous input URB from the Gigaset device
1222 * has completed
1223 * parameter:
1224 *	data	B channel state structure
1225 */
1226static void read_iso_tasklet(unsigned long data)
1227{
1228	struct bc_state *bcs = (struct bc_state *) data;
1229	struct bas_bc_state *ubc = bcs->hw.bas;
1230	struct cardstate *cs = bcs->cs;
1231	struct urb *urb;
1232	char *rcvbuf;
1233	unsigned long flags;
1234	int totleft, numbytes, offset, frame, rc;
1235
1236	/* loop while more completed URBs arrive in the meantime */
1237	for (;;) {
1238		/* retrieve URB */
1239		spin_lock_irqsave(&ubc->isoinlock, flags);
1240		if (!(urb = ubc->isoindone)) {
1241			spin_unlock_irqrestore(&ubc->isoinlock, flags);
1242			return;
1243		}
1244		ubc->isoindone = NULL;
1245		if (unlikely(ubc->loststatus != -EINPROGRESS)) {
1246			dev_warn(cs->dev,
1247				 "isochronous read overrun, "
1248				 "dropped URB with status: %s, %d bytes lost\n",
1249				 get_usb_statmsg(ubc->loststatus),
1250				 ubc->isoinlost);
1251			ubc->loststatus = -EINPROGRESS;
1252		}
1253		spin_unlock_irqrestore(&ubc->isoinlock, flags);
1254
1255		if (unlikely(!(atomic_read(&ubc->running)))) {
1256			gig_dbg(DEBUG_ISO,
1257				"%s: channel not running, "
1258				"dropped URB with status: %s",
1259				__func__, get_usb_statmsg(urb->status));
1260			return;
1261		}
1262
1263		switch (urb->status) {
1264		case 0:				/* normal completion */
1265			break;
1266		case -EXDEV:			/* inspect individual frames
1267						   (we do that anyway) */
1268			gig_dbg(DEBUG_ISO, "%s: URB partially completed",
1269				__func__);
1270			break;
1271		case -ENOENT:
1272		case -ECONNRESET:
1273		case -EINPROGRESS:
1274			gig_dbg(DEBUG_ISO, "%s: %s",
1275				__func__, get_usb_statmsg(urb->status));
1276			continue;		/* -> skip */
1277		case -EPIPE:
1278			dev_err(cs->dev, "isochronous read stalled\n");
1279			error_hangup(bcs);
1280			continue;		/* -> skip */
1281		default:			/* severe trouble */
1282			dev_warn(cs->dev, "isochronous read: %s\n",
1283				 get_usb_statmsg(urb->status));
1284			goto error;
1285		}
1286
1287		rcvbuf = urb->transfer_buffer;
1288		totleft = urb->actual_length;
1289		for (frame = 0; totleft > 0 && frame < BAS_NUMFRAMES; frame++) {
1290			if (unlikely(urb->iso_frame_desc[frame].status)) {
1291				dev_warn(cs->dev,
1292					 "isochronous read: frame %d: %s\n",
1293					 frame,
1294					 get_usb_statmsg(
1295					    urb->iso_frame_desc[frame].status));
1296				break;
1297			}
1298			numbytes = urb->iso_frame_desc[frame].actual_length;
1299			if (unlikely(numbytes > BAS_MAXFRAME)) {
1300				dev_warn(cs->dev,
1301					 "isochronous read: frame %d: "
1302					 "numbytes (%d) > BAS_MAXFRAME\n",
1303					 frame, numbytes);
1304				break;
1305			}
1306			if (unlikely(numbytes > totleft)) {
1307				dev_warn(cs->dev,
1308					 "isochronous read: frame %d: "
1309					 "numbytes (%d) > totleft (%d)\n",
1310					 frame, numbytes, totleft);
1311				break;
1312			}
1313			offset = urb->iso_frame_desc[frame].offset;
1314			if (unlikely(offset + numbytes > BAS_INBUFSIZE)) {
1315				dev_warn(cs->dev,
1316					 "isochronous read: frame %d: "
1317					 "offset (%d) + numbytes (%d) "
1318					 "> BAS_INBUFSIZE\n",
1319					 frame, offset, numbytes);
1320				break;
1321			}
1322			gigaset_isoc_receive(rcvbuf + offset, numbytes, bcs);
1323			totleft -= numbytes;
1324		}
1325		if (unlikely(totleft > 0))
1326			dev_warn(cs->dev,
1327				 "isochronous read: %d data bytes missing\n",
1328				 totleft);
1329
1330	error:
1331		/* URB processed, resubmit */
1332		for (frame = 0; frame < BAS_NUMFRAMES; frame++) {
1333			urb->iso_frame_desc[frame].status = 0;
1334			urb->iso_frame_desc[frame].actual_length = 0;
1335		}
1336		/* urb->dev is clobbered by USB subsystem */
1337		urb->dev = bcs->cs->hw.bas->udev;
1338		urb->transfer_flags = URB_ISO_ASAP;
1339		urb->number_of_packets = BAS_NUMFRAMES;
1340		rc = usb_submit_urb(urb, GFP_ATOMIC);
1341		if (unlikely(rc != 0 && rc != -ENODEV)) {
1342			dev_err(cs->dev,
1343				"could not resubmit isochronous read URB: %s\n",
1344				get_usb_rcmsg(rc));
1345			dump_urb(DEBUG_ISO, "resubmit iso read", urb);
1346			error_hangup(bcs);
1347		}
1348	}
1349}
1350
1351/* Channel Operations */
1352/* ================== */
1353
1354/* req_timeout
1355 * timeout routine for control output request
1356 * argument:
1357 *	B channel control structure
1358 */
1359static void req_timeout(unsigned long data)
1360{
1361	struct bc_state *bcs = (struct bc_state *) data;
1362	struct bas_cardstate *ucs = bcs->cs->hw.bas;
1363	int pending;
1364	unsigned long flags;
1365
1366	check_pending(ucs);
1367
1368	spin_lock_irqsave(&ucs->lock, flags);
1369	pending = ucs->pending;
1370	ucs->pending = 0;
1371	spin_unlock_irqrestore(&ucs->lock, flags);
1372
1373	switch (pending) {
1374	case 0:					/* no pending request */
1375		gig_dbg(DEBUG_USBREQ, "%s: no request pending", __func__);
1376		break;
1377
1378	case HD_OPEN_ATCHANNEL:
1379		dev_err(bcs->cs->dev, "timeout opening AT channel\n");
1380		error_reset(bcs->cs);
1381		break;
1382
1383	case HD_OPEN_B2CHANNEL:
1384	case HD_OPEN_B1CHANNEL:
1385		dev_err(bcs->cs->dev, "timeout opening channel %d\n",
1386			bcs->channel + 1);
1387		error_hangup(bcs);
1388		break;
1389
1390	case HD_CLOSE_ATCHANNEL:
1391		dev_err(bcs->cs->dev, "timeout closing AT channel\n");
1392		break;
1393
1394	case HD_CLOSE_B2CHANNEL:
1395	case HD_CLOSE_B1CHANNEL:
1396		dev_err(bcs->cs->dev, "timeout closing channel %d\n",
1397			bcs->channel + 1);
1398		error_reset(bcs->cs);
1399		break;
1400
1401	default:
1402		dev_warn(bcs->cs->dev, "request 0x%02x timed out, clearing\n",
1403			 pending);
1404	}
1405}
1406
1407/* write_ctrl_callback
1408 * USB completion handler for control pipe output
1409 * called by the USB subsystem in interrupt context
1410 * parameter:
1411 *	urb	USB request block of completed request
1412 *		urb->context = hardware specific controller state structure
1413 */
1414static void write_ctrl_callback(struct urb *urb)
1415{
1416	struct bas_cardstate *ucs = urb->context;
1417	int rc;
1418	unsigned long flags;
1419
1420	/* check status */
1421	switch (urb->status) {
1422	case 0:					/* normal completion */
1423		spin_lock_irqsave(&ucs->lock, flags);
1424		switch (ucs->pending) {
1425		case HD_DEVICE_INIT_ACK:	/* no reply expected */
1426			del_timer(&ucs->timer_ctrl);
1427			ucs->pending = 0;
1428			break;
1429		}
1430		spin_unlock_irqrestore(&ucs->lock, flags);
1431		return;
1432
1433	case -ENOENT:			/* cancelled */
1434	case -ECONNRESET:		/* cancelled (async) */
1435	case -EINPROGRESS:		/* pending */
1436	case -ENODEV:			/* device removed */
1437	case -ESHUTDOWN:		/* device shut down */
1438		/* ignore silently */
1439		gig_dbg(DEBUG_USBREQ, "%s: %s",
1440			__func__, get_usb_statmsg(urb->status));
1441		break;
1442
1443	default:				/* any failure */
1444		if (++ucs->retry_ctrl > BAS_RETRY) {
1445			dev_err(&ucs->interface->dev,
1446				"control request 0x%02x failed: %s\n",
1447				ucs->dr_ctrl.bRequest,
1448				get_usb_statmsg(urb->status));
1449			break;		/* give up */
1450		}
1451		dev_notice(&ucs->interface->dev,
1452			   "control request 0x%02x: %s, retry %d\n",
1453			   ucs->dr_ctrl.bRequest, get_usb_statmsg(urb->status),
1454			   ucs->retry_ctrl);
1455		/* urb->dev is clobbered by USB subsystem */
1456		urb->dev = ucs->udev;
1457		rc = usb_submit_urb(urb, GFP_ATOMIC);
1458		if (unlikely(rc)) {
1459			dev_err(&ucs->interface->dev,
1460				"could not resubmit request 0x%02x: %s\n",
1461				ucs->dr_ctrl.bRequest, get_usb_rcmsg(rc));
1462			break;
1463		}
1464		/* resubmitted */
1465		return;
1466	}
1467
1468	/* failed, clear pending request */
1469	spin_lock_irqsave(&ucs->lock, flags);
1470	del_timer(&ucs->timer_ctrl);
1471	ucs->pending = 0;
1472	spin_unlock_irqrestore(&ucs->lock, flags);
1473}
1474
1475/* req_submit
1476 * submit a control output request without message buffer to the Gigaset base
1477 * and optionally start a timeout
1478 * parameters:
1479 *	bcs	B channel control structure
1480 *	req	control request code (HD_*)
1481 *	val	control request parameter value (set to 0 if unused)
1482 *	timeout	timeout in seconds (0: no timeout)
1483 * return value:
1484 *	0 on success
1485 *	-EBUSY if another request is pending
1486 *	any URB submission error code
1487 */
1488static int req_submit(struct bc_state *bcs, int req, int val, int timeout)
1489{
1490	struct bas_cardstate *ucs = bcs->cs->hw.bas;
1491	int ret;
1492	unsigned long flags;
1493
1494	gig_dbg(DEBUG_USBREQ, "-------> 0x%02x (%d)", req, val);
1495
1496	spin_lock_irqsave(&ucs->lock, flags);
1497	if (ucs->pending) {
1498		spin_unlock_irqrestore(&ucs->lock, flags);
1499		dev_err(bcs->cs->dev,
1500			"submission of request 0x%02x failed: "
1501			"request 0x%02x still pending\n",
1502			req, ucs->pending);
1503		return -EBUSY;
1504	}
1505
1506	ucs->dr_ctrl.bRequestType = OUT_VENDOR_REQ;
1507	ucs->dr_ctrl.bRequest = req;
1508	ucs->dr_ctrl.wValue = cpu_to_le16(val);
1509	ucs->dr_ctrl.wIndex = 0;
1510	ucs->dr_ctrl.wLength = 0;
1511	usb_fill_control_urb(ucs->urb_ctrl, ucs->udev,
1512			     usb_sndctrlpipe(ucs->udev, 0),
1513			     (unsigned char*) &ucs->dr_ctrl, NULL, 0,
1514			     write_ctrl_callback, ucs);
1515	ucs->retry_ctrl = 0;
1516	ret = usb_submit_urb(ucs->urb_ctrl, GFP_ATOMIC);
1517	if (unlikely(ret)) {
1518		dev_err(bcs->cs->dev, "could not submit request 0x%02x: %s\n",
1519			req, get_usb_rcmsg(ret));
1520		spin_unlock_irqrestore(&ucs->lock, flags);
1521		return ret;
1522	}
1523	ucs->pending = req;
1524
1525	if (timeout > 0) {
1526		gig_dbg(DEBUG_USBREQ, "setting timeout of %d/10 secs", timeout);
1527		ucs->timer_ctrl.expires = jiffies + timeout * HZ / 10;
1528		ucs->timer_ctrl.data = (unsigned long) bcs;
1529		ucs->timer_ctrl.function = req_timeout;
1530		add_timer(&ucs->timer_ctrl);
1531	}
1532
1533	spin_unlock_irqrestore(&ucs->lock, flags);
1534	return 0;
1535}
1536
1537/* gigaset_init_bchannel
1538 * called by common.c to connect a B channel
1539 * initialize isochronous I/O and tell the Gigaset base to open the channel
1540 * argument:
1541 *	B channel control structure
1542 * return value:
1543 *	0 on success, error code < 0 on error
1544 */
1545static int gigaset_init_bchannel(struct bc_state *bcs)
1546{
1547	int req, ret;
1548	unsigned long flags;
1549
1550	spin_lock_irqsave(&bcs->cs->lock, flags);
1551	if (unlikely(!bcs->cs->connected)) {
1552		gig_dbg(DEBUG_USBREQ, "%s: not connected", __func__);
1553		spin_unlock_irqrestore(&bcs->cs->lock, flags);
1554		return -ENODEV;
1555	}
1556
1557	if ((ret = starturbs(bcs)) < 0) {
1558		dev_err(bcs->cs->dev,
1559			"could not start isochronous I/O for channel B%d: %s\n",
1560			bcs->channel + 1,
1561			ret == -EFAULT ? "null URB" : get_usb_rcmsg(ret));
1562		if (ret != -ENODEV)
1563			error_hangup(bcs);
1564		spin_unlock_irqrestore(&bcs->cs->lock, flags);
1565		return ret;
1566	}
1567
1568	req = bcs->channel ? HD_OPEN_B2CHANNEL : HD_OPEN_B1CHANNEL;
1569	if ((ret = req_submit(bcs, req, 0, BAS_TIMEOUT)) < 0) {
1570		dev_err(bcs->cs->dev, "could not open channel B%d\n",
1571			bcs->channel + 1);
1572		stopurbs(bcs->hw.bas);
1573		if (ret != -ENODEV)
1574			error_hangup(bcs);
1575	}
1576
1577	spin_unlock_irqrestore(&bcs->cs->lock, flags);
1578	return ret;
1579}
1580
1581/* gigaset_close_bchannel
1582 * called by common.c to disconnect a B channel
1583 * tell the Gigaset base to close the channel
1584 * stopping isochronous I/O and LL notification will be done when the
1585 * acknowledgement for the close arrives
1586 * argument:
1587 *	B channel control structure
1588 * return value:
1589 *	0 on success, error code < 0 on error
1590 */
1591static int gigaset_close_bchannel(struct bc_state *bcs)
1592{
1593	int req, ret;
1594	unsigned long flags;
1595
1596	spin_lock_irqsave(&bcs->cs->lock, flags);
1597	if (unlikely(!bcs->cs->connected)) {
1598		spin_unlock_irqrestore(&bcs->cs->lock, flags);
1599		gig_dbg(DEBUG_USBREQ, "%s: not connected", __func__);
1600		return -ENODEV;
1601	}
1602
1603	if (!(atomic_read(&bcs->cs->hw.bas->basstate) &
1604	      (bcs->channel ? BS_B2OPEN : BS_B1OPEN))) {
1605		/* channel not running: just signal common.c */
1606		spin_unlock_irqrestore(&bcs->cs->lock, flags);
1607		gigaset_bchannel_down(bcs);
1608		return 0;
1609	}
1610
1611	/* channel running: tell device to close it */
1612	req = bcs->channel ? HD_CLOSE_B2CHANNEL : HD_CLOSE_B1CHANNEL;
1613	if ((ret = req_submit(bcs, req, 0, BAS_TIMEOUT)) < 0)
1614		dev_err(bcs->cs->dev, "closing channel B%d failed\n",
1615			bcs->channel + 1);
1616
1617	spin_unlock_irqrestore(&bcs->cs->lock, flags);
1618	return ret;
1619}
1620
1621/* Device Operations */
1622/* ================= */
1623
1624/* complete_cb
1625 * unqueue first command buffer from queue, waking any sleepers
1626 * must be called with cs->cmdlock held
1627 * parameter:
1628 *	cs	controller state structure
1629 */
1630static void complete_cb(struct cardstate *cs)
1631{
1632	struct cmdbuf_t *cb = cs->cmdbuf;
1633
1634	/* unqueue completed buffer */
1635	cs->cmdbytes -= cs->curlen;
1636	gig_dbg(DEBUG_TRANSCMD|DEBUG_LOCKCMD,
1637		"write_command: sent %u bytes, %u left",
1638		cs->curlen, cs->cmdbytes);
1639	if ((cs->cmdbuf = cb->next) != NULL) {
1640		cs->cmdbuf->prev = NULL;
1641		cs->curlen = cs->cmdbuf->len;
1642	} else {
1643		cs->lastcmdbuf = NULL;
1644		cs->curlen = 0;
1645	}
1646
1647	if (cb->wake_tasklet)
1648		tasklet_schedule(cb->wake_tasklet);
1649
1650	kfree(cb);
1651}
1652
1653/* write_command_callback
1654 * USB completion handler for AT command transmission
1655 * called by the USB subsystem in interrupt context
1656 * parameter:
1657 *	urb	USB request block of completed request
1658 *		urb->context = controller state structure
1659 */
1660static void write_command_callback(struct urb *urb)
1661{
1662	struct cardstate *cs = urb->context;
1663	struct bas_cardstate *ucs = cs->hw.bas;
1664	unsigned long flags;
1665
1666	update_basstate(ucs, 0, BS_ATWRPEND);
1667
1668	/* check status */
1669	switch (urb->status) {
1670	case 0:					/* normal completion */
1671		break;
1672	case -ENOENT:			/* cancelled */
1673	case -ECONNRESET:		/* cancelled (async) */
1674	case -EINPROGRESS:		/* pending */
1675	case -ENODEV:			/* device removed */
1676	case -ESHUTDOWN:		/* device shut down */
1677		/* ignore silently */
1678		gig_dbg(DEBUG_USBREQ, "%s: %s",
1679			__func__, get_usb_statmsg(urb->status));
1680		return;
1681	default:				/* any failure */
1682		if (++ucs->retry_cmd_out > BAS_RETRY) {
1683			dev_warn(cs->dev,
1684				 "command write: %s, "
1685				 "giving up after %d retries\n",
1686				 get_usb_statmsg(urb->status),
1687				 ucs->retry_cmd_out);
1688			break;
1689		}
1690		if (cs->cmdbuf == NULL) {
1691			dev_warn(cs->dev,
1692				 "command write: %s, "
1693				 "cannot retry - cmdbuf gone\n",
1694				 get_usb_statmsg(urb->status));
1695			break;
1696		}
1697		dev_notice(cs->dev, "command write: %s, retry %d\n",
1698			   get_usb_statmsg(urb->status), ucs->retry_cmd_out);
1699		if (atwrite_submit(cs, cs->cmdbuf->buf, cs->cmdbuf->len) >= 0)
1700			/* resubmitted - bypass regular exit block */
1701			return;
1702		/* command send failed, assume base still waiting */
1703		update_basstate(ucs, BS_ATREADY, 0);
1704	}
1705
1706	spin_lock_irqsave(&cs->cmdlock, flags);
1707	if (cs->cmdbuf != NULL)
1708		complete_cb(cs);
1709	spin_unlock_irqrestore(&cs->cmdlock, flags);
1710}
1711
1712/* atrdy_timeout
1713 * timeout routine for AT command transmission
1714 * argument:
1715 *	controller state structure
1716 */
1717static void atrdy_timeout(unsigned long data)
1718{
1719	struct cardstate *cs = (struct cardstate *) data;
1720	struct bas_cardstate *ucs = cs->hw.bas;
1721
1722	dev_warn(cs->dev, "timeout waiting for HD_READY_SEND_ATDATA\n");
1723
1724	/* fake the missing signal - what else can I do? */
1725	update_basstate(ucs, BS_ATREADY, BS_ATTIMER);
1726	start_cbsend(cs);
1727}
1728
1729/* atwrite_submit
1730 * submit an HD_WRITE_ATMESSAGE command URB
1731 * parameters:
1732 *	cs	controller state structure
1733 *	buf	buffer containing command to send
1734 *	len	length of command to send
1735 * return value:
1736 *	0 on success
1737 *	-EBUSY if another request is pending
1738 *	any URB submission error code
1739 */
1740static int atwrite_submit(struct cardstate *cs, unsigned char *buf, int len)
1741{
1742	struct bas_cardstate *ucs = cs->hw.bas;
1743	int rc;
1744
1745	gig_dbg(DEBUG_USBREQ, "-------> HD_WRITE_ATMESSAGE (%d)", len);
1746
1747	if (update_basstate(ucs, BS_ATWRPEND, 0) & BS_ATWRPEND) {
1748		dev_err(cs->dev,
1749			"could not submit HD_WRITE_ATMESSAGE: URB busy\n");
1750		return -EBUSY;
1751	}
1752
1753	ucs->dr_cmd_out.bRequestType = OUT_VENDOR_REQ;
1754	ucs->dr_cmd_out.bRequest = HD_WRITE_ATMESSAGE;
1755	ucs->dr_cmd_out.wValue = 0;
1756	ucs->dr_cmd_out.wIndex = 0;
1757	ucs->dr_cmd_out.wLength = cpu_to_le16(len);
1758	usb_fill_control_urb(ucs->urb_cmd_out, ucs->udev,
1759			     usb_sndctrlpipe(ucs->udev, 0),
1760			     (unsigned char*) &ucs->dr_cmd_out, buf, len,
1761			     write_command_callback, cs);
1762	rc = usb_submit_urb(ucs->urb_cmd_out, GFP_ATOMIC);
1763	if (unlikely(rc)) {
1764		update_basstate(ucs, 0, BS_ATWRPEND);
1765		dev_err(cs->dev, "could not submit HD_WRITE_ATMESSAGE: %s\n",
1766			get_usb_rcmsg(rc));
1767		return rc;
1768	}
1769
1770	/* submitted successfully, start timeout if necessary */
1771	if (!(update_basstate(ucs, BS_ATTIMER, BS_ATREADY) & BS_ATTIMER)) {
1772		gig_dbg(DEBUG_OUTPUT, "setting ATREADY timeout of %d/10 secs",
1773			ATRDY_TIMEOUT);
1774		ucs->timer_atrdy.expires = jiffies + ATRDY_TIMEOUT * HZ / 10;
1775		ucs->timer_atrdy.data = (unsigned long) cs;
1776		ucs->timer_atrdy.function = atrdy_timeout;
1777		add_timer(&ucs->timer_atrdy);
1778	}
1779	return 0;
1780}
1781
1782/* start_cbsend
1783 * start transmission of AT command queue if necessary
1784 * parameter:
1785 *	cs		controller state structure
1786 * return value:
1787 *	0 on success
1788 *	error code < 0 on error
1789 */
1790static int start_cbsend(struct cardstate *cs)
1791{
1792	struct cmdbuf_t *cb;
1793	struct bas_cardstate *ucs = cs->hw.bas;
1794	unsigned long flags;
1795	int rc;
1796	int retval = 0;
1797
1798	/* check if AT channel is open */
1799	if (!(atomic_read(&ucs->basstate) & BS_ATOPEN)) {
1800		gig_dbg(DEBUG_TRANSCMD|DEBUG_LOCKCMD, "AT channel not open");
1801		rc = req_submit(cs->bcs, HD_OPEN_ATCHANNEL, 0, BAS_TIMEOUT);
1802		if (rc < 0) {
1803			/* flush command queue */
1804			spin_lock_irqsave(&cs->cmdlock, flags);
1805			while (cs->cmdbuf != NULL)
1806				complete_cb(cs);
1807			spin_unlock_irqrestore(&cs->cmdlock, flags);
1808		}
1809		return rc;
1810	}
1811
1812	/* try to send first command in queue */
1813	spin_lock_irqsave(&cs->cmdlock, flags);
1814
1815	while ((cb = cs->cmdbuf) != NULL &&
1816	       atomic_read(&ucs->basstate) & BS_ATREADY) {
1817		ucs->retry_cmd_out = 0;
1818		rc = atwrite_submit(cs, cb->buf, cb->len);
1819		if (unlikely(rc)) {
1820			retval = rc;
1821			complete_cb(cs);
1822		}
1823	}
1824
1825	spin_unlock_irqrestore(&cs->cmdlock, flags);
1826	return retval;
1827}
1828
1829/* gigaset_write_cmd
1830 * This function is called by the device independent part of the driver
1831 * to transmit an AT command string to the Gigaset device.
1832 * It encapsulates the device specific method for transmission over the
1833 * direct USB connection to the base.
1834 * The command string is added to the queue of commands to send, and
1835 * USB transmission is started if necessary.
1836 * parameters:
1837 *	cs		controller state structure
1838 *	buf		command string to send
1839 *	len		number of bytes to send (max. IF_WRITEBUF)
1840 *	wake_tasklet	tasklet to run when transmission is completed
1841 *			(NULL if none)
1842 * return value:
1843 *	number of bytes queued on success
1844 *	error code < 0 on error
1845 */
1846static int gigaset_write_cmd(struct cardstate *cs,
1847			     const unsigned char *buf, int len,
1848			     struct tasklet_struct *wake_tasklet)
1849{
1850	struct cmdbuf_t *cb;
1851	unsigned long flags;
1852	int rc;
1853
1854	gigaset_dbg_buffer(atomic_read(&cs->mstate) != MS_LOCKED ?
1855			     DEBUG_TRANSCMD : DEBUG_LOCKCMD,
1856			   "CMD Transmit", len, buf);
1857
1858	if (len <= 0) {
1859		/* nothing to do */
1860		rc = 0;
1861		goto notqueued;
1862	}
1863
1864	if (len > IF_WRITEBUF)
1865		len = IF_WRITEBUF;
1866	if (!(cb = kmalloc(sizeof(struct cmdbuf_t) + len, GFP_ATOMIC))) {
1867		dev_err(cs->dev, "%s: out of memory\n", __func__);
1868		rc = -ENOMEM;
1869		goto notqueued;
1870	}
1871
1872	memcpy(cb->buf, buf, len);
1873	cb->len = len;
1874	cb->offset = 0;
1875	cb->next = NULL;
1876	cb->wake_tasklet = wake_tasklet;
1877
1878	spin_lock_irqsave(&cs->cmdlock, flags);
1879	cb->prev = cs->lastcmdbuf;
1880	if (cs->lastcmdbuf)
1881		cs->lastcmdbuf->next = cb;
1882	else {
1883		cs->cmdbuf = cb;
1884		cs->curlen = len;
1885	}
1886	cs->cmdbytes += len;
1887	cs->lastcmdbuf = cb;
1888	spin_unlock_irqrestore(&cs->cmdlock, flags);
1889
1890	spin_lock_irqsave(&cs->lock, flags);
1891	if (unlikely(!cs->connected)) {
1892		spin_unlock_irqrestore(&cs->lock, flags);
1893		gig_dbg(DEBUG_USBREQ, "%s: not connected", __func__);
1894		/* flush command queue */
1895		spin_lock_irqsave(&cs->cmdlock, flags);
1896		while (cs->cmdbuf != NULL)
1897			complete_cb(cs);
1898		spin_unlock_irqrestore(&cs->cmdlock, flags);
1899		return -ENODEV;
1900	}
1901	rc = start_cbsend(cs);
1902	spin_unlock_irqrestore(&cs->lock, flags);
1903	return rc < 0 ? rc : len;
1904
1905notqueued:			/* request handled without queuing */
1906	if (wake_tasklet)
1907		tasklet_schedule(wake_tasklet);
1908	return rc;
1909}
1910
1911/* gigaset_write_room
1912 * tty_driver.write_room interface routine
1913 * return number of characters the driver will accept to be written via
1914 * gigaset_write_cmd
1915 * parameter:
1916 *	controller state structure
1917 * return value:
1918 *	number of characters
1919 */
1920static int gigaset_write_room(struct cardstate *cs)
1921{
1922	return IF_WRITEBUF;
1923}
1924
1925/* gigaset_chars_in_buffer
1926 * tty_driver.chars_in_buffer interface routine
1927 * return number of characters waiting to be sent
1928 * parameter:
1929 *	controller state structure
1930 * return value:
1931 *	number of characters
1932 */
1933static int gigaset_chars_in_buffer(struct cardstate *cs)
1934{
1935	unsigned long flags;
1936	unsigned bytes;
1937
1938	spin_lock_irqsave(&cs->cmdlock, flags);
1939	bytes = cs->cmdbytes;
1940	spin_unlock_irqrestore(&cs->cmdlock, flags);
1941
1942	return bytes;
1943}
1944
1945/* gigaset_brkchars
1946 * implementation of ioctl(GIGASET_BRKCHARS)
1947 * parameter:
1948 *	controller state structure
1949 * return value:
1950 *	-EINVAL (unimplemented function)
1951 */
1952static int gigaset_brkchars(struct cardstate *cs, const unsigned char buf[6])
1953{
1954	return -EINVAL;
1955}
1956
1957
1958/* Device Initialization/Shutdown */
1959/* ============================== */
1960
1961/* Free hardware dependent part of the B channel structure
1962 * parameter:
1963 *	bcs	B channel structure
1964 * return value:
1965 *	!=0 on success
1966 */
1967static int gigaset_freebcshw(struct bc_state *bcs)
1968{
1969	struct bas_bc_state *ubc = bcs->hw.bas;
1970	int i;
1971
1972	if (!ubc)
1973		return 0;
1974
1975	/* kill URBs and tasklets before freeing - better safe than sorry */
1976	atomic_set(&ubc->running, 0);
1977	gig_dbg(DEBUG_INIT, "%s: killing iso URBs", __func__);
1978	for (i = 0; i < BAS_OUTURBS; ++i) {
1979		usb_kill_urb(ubc->isoouturbs[i].urb);
1980		usb_free_urb(ubc->isoouturbs[i].urb);
1981	}
1982	for (i = 0; i < BAS_INURBS; ++i) {
1983		usb_kill_urb(ubc->isoinurbs[i]);
1984		usb_free_urb(ubc->isoinurbs[i]);
1985	}
1986	tasklet_kill(&ubc->sent_tasklet);
1987	tasklet_kill(&ubc->rcvd_tasklet);
1988	kfree(ubc->isooutbuf);
1989	kfree(ubc);
1990	bcs->hw.bas = NULL;
1991	return 1;
1992}
1993
1994/* Initialize hardware dependent part of the B channel structure
1995 * parameter:
1996 *	bcs	B channel structure
1997 * return value:
1998 *	!=0 on success
1999 */
2000static int gigaset_initbcshw(struct bc_state *bcs)
2001{
2002	int i;
2003	struct bas_bc_state *ubc;
2004
2005	bcs->hw.bas = ubc = kmalloc(sizeof(struct bas_bc_state), GFP_KERNEL);
2006	if (!ubc) {
2007		err("could not allocate bas_bc_state");
2008		return 0;
2009	}
2010
2011	atomic_set(&ubc->running, 0);
2012	atomic_set(&ubc->corrbytes, 0);
2013	spin_lock_init(&ubc->isooutlock);
2014	for (i = 0; i < BAS_OUTURBS; ++i) {
2015		ubc->isoouturbs[i].urb = NULL;
2016		ubc->isoouturbs[i].bcs = bcs;
2017	}
2018	ubc->isooutdone = ubc->isooutfree = ubc->isooutovfl = NULL;
2019	ubc->numsub = 0;
2020	if (!(ubc->isooutbuf = kmalloc(sizeof(struct isowbuf_t), GFP_KERNEL))) {
2021		err("could not allocate isochronous output buffer");
2022		kfree(ubc);
2023		bcs->hw.bas = NULL;
2024		return 0;
2025	}
2026	tasklet_init(&ubc->sent_tasklet,
2027		     &write_iso_tasklet, (unsigned long) bcs);
2028
2029	spin_lock_init(&ubc->isoinlock);
2030	for (i = 0; i < BAS_INURBS; ++i)
2031		ubc->isoinurbs[i] = NULL;
2032	ubc->isoindone = NULL;
2033	ubc->loststatus = -EINPROGRESS;
2034	ubc->isoinlost = 0;
2035	ubc->seqlen = 0;
2036	ubc->inbyte = 0;
2037	ubc->inbits = 0;
2038	ubc->goodbytes = 0;
2039	ubc->alignerrs = 0;
2040	ubc->fcserrs = 0;
2041	ubc->frameerrs = 0;
2042	ubc->giants = 0;
2043	ubc->runts = 0;
2044	ubc->aborts = 0;
2045	ubc->shared0s = 0;
2046	ubc->stolen0s = 0;
2047	tasklet_init(&ubc->rcvd_tasklet,
2048		     &read_iso_tasklet, (unsigned long) bcs);
2049	return 1;
2050}
2051
2052static void gigaset_reinitbcshw(struct bc_state *bcs)
2053{
2054	struct bas_bc_state *ubc = bcs->hw.bas;
2055
2056	atomic_set(&bcs->hw.bas->running, 0);
2057	atomic_set(&bcs->hw.bas->corrbytes, 0);
2058	bcs->hw.bas->numsub = 0;
2059	spin_lock_init(&ubc->isooutlock);
2060	spin_lock_init(&ubc->isoinlock);
2061	ubc->loststatus = -EINPROGRESS;
2062}
2063
2064static void gigaset_freecshw(struct cardstate *cs)
2065{
2066	/* timers, URBs and rcvbuf are disposed of in disconnect */
2067	kfree(cs->hw.bas);
2068	cs->hw.bas = NULL;
2069}
2070
2071static int gigaset_initcshw(struct cardstate *cs)
2072{
2073	struct bas_cardstate *ucs;
2074
2075	cs->hw.bas = ucs = kmalloc(sizeof *ucs, GFP_KERNEL);
2076	if (!ucs)
2077		return 0;
2078
2079	ucs->urb_cmd_in = NULL;
2080	ucs->urb_cmd_out = NULL;
2081	ucs->rcvbuf = NULL;
2082	ucs->rcvbuf_size = 0;
2083
2084	spin_lock_init(&ucs->lock);
2085	ucs->pending = 0;
2086
2087	atomic_set(&ucs->basstate, 0);
2088	init_timer(&ucs->timer_ctrl);
2089	init_timer(&ucs->timer_atrdy);
2090	init_timer(&ucs->timer_cmd_in);
2091
2092	return 1;
2093}
2094
2095/* freeurbs
2096 * unlink and deallocate all URBs unconditionally
2097 * caller must make sure that no commands are still in progress
2098 * parameter:
2099 *	cs	controller state structure
2100 */
2101static void freeurbs(struct cardstate *cs)
2102{
2103	struct bas_cardstate *ucs = cs->hw.bas;
2104	struct bas_bc_state *ubc;
2105	int i, j;
2106
2107	gig_dbg(DEBUG_INIT, "%s: killing URBs", __func__);
2108	for (j = 0; j < 2; ++j) {
2109		ubc = cs->bcs[j].hw.bas;
2110		for (i = 0; i < BAS_OUTURBS; ++i) {
2111			usb_kill_urb(ubc->isoouturbs[i].urb);
2112			usb_free_urb(ubc->isoouturbs[i].urb);
2113			ubc->isoouturbs[i].urb = NULL;
2114		}
2115		for (i = 0; i < BAS_INURBS; ++i) {
2116			usb_kill_urb(ubc->isoinurbs[i]);
2117			usb_free_urb(ubc->isoinurbs[i]);
2118			ubc->isoinurbs[i] = NULL;
2119		}
2120	}
2121	usb_kill_urb(ucs->urb_int_in);
2122	usb_free_urb(ucs->urb_int_in);
2123	ucs->urb_int_in = NULL;
2124	usb_kill_urb(ucs->urb_cmd_out);
2125	usb_free_urb(ucs->urb_cmd_out);
2126	ucs->urb_cmd_out = NULL;
2127	usb_kill_urb(ucs->urb_cmd_in);
2128	usb_free_urb(ucs->urb_cmd_in);
2129	ucs->urb_cmd_in = NULL;
2130	usb_kill_urb(ucs->urb_ctrl);
2131	usb_free_urb(ucs->urb_ctrl);
2132	ucs->urb_ctrl = NULL;
2133}
2134
2135/* gigaset_probe
2136 * This function is called when a new USB device is connected.
2137 * It checks whether the new device is handled by this driver.
2138 */
2139static int gigaset_probe(struct usb_interface *interface,
2140			 const struct usb_device_id *id)
2141{
2142	struct usb_host_interface *hostif;
2143	struct usb_device *udev = interface_to_usbdev(interface);
2144	struct cardstate *cs = NULL;
2145	struct bas_cardstate *ucs = NULL;
2146	struct bas_bc_state *ubc;
2147	struct usb_endpoint_descriptor *endpoint;
2148	int i, j;
2149	int rc;
2150
2151	gig_dbg(DEBUG_ANY,
2152		"%s: Check if device matches .. (Vendor: 0x%x, Product: 0x%x)",
2153		__func__, le16_to_cpu(udev->descriptor.idVendor),
2154		le16_to_cpu(udev->descriptor.idProduct));
2155
2156	/* set required alternate setting */
2157	hostif = interface->cur_altsetting;
2158	if (hostif->desc.bAlternateSetting != 3) {
2159		gig_dbg(DEBUG_ANY,
2160			"%s: wrong alternate setting %d - trying to switch",
2161			__func__, hostif->desc.bAlternateSetting);
2162		if (usb_set_interface(udev, hostif->desc.bInterfaceNumber, 3) < 0) {
2163			dev_warn(&udev->dev, "usb_set_interface failed, "
2164				 "device %d interface %d altsetting %d\n",
2165				 udev->devnum, hostif->desc.bInterfaceNumber,
2166				 hostif->desc.bAlternateSetting);
2167			return -ENODEV;
2168		}
2169		hostif = interface->cur_altsetting;
2170	}
2171
2172	/* Reject application specific interfaces
2173	 */
2174	if (hostif->desc.bInterfaceClass != 255) {
2175		dev_warn(&udev->dev, "%s: bInterfaceClass == %d\n",
2176			 __func__, hostif->desc.bInterfaceClass);
2177		return -ENODEV;
2178	}
2179
2180	dev_info(&udev->dev,
2181		 "%s: Device matched (Vendor: 0x%x, Product: 0x%x)\n",
2182		 __func__, le16_to_cpu(udev->descriptor.idVendor),
2183		 le16_to_cpu(udev->descriptor.idProduct));
2184
2185	cs = gigaset_getunassignedcs(driver);
2186	if (!cs) {
2187		dev_err(&udev->dev, "no free cardstate\n");
2188		return -ENODEV;
2189	}
2190	ucs = cs->hw.bas;
2191
2192	/* save off device structure ptrs for later use */
2193	usb_get_dev(udev);
2194	ucs->udev = udev;
2195	ucs->interface = interface;
2196	cs->dev = &interface->dev;
2197
2198	/* allocate URBs:
2199	 * - one for the interrupt pipe
2200	 * - three for the different uses of the default control pipe
2201	 * - three for each isochronous pipe
2202	 */
2203	if (!(ucs->urb_int_in = usb_alloc_urb(0, GFP_KERNEL)) ||
2204	    !(ucs->urb_cmd_in = usb_alloc_urb(0, GFP_KERNEL)) ||
2205	    !(ucs->urb_cmd_out = usb_alloc_urb(0, GFP_KERNEL)) ||
2206	    !(ucs->urb_ctrl = usb_alloc_urb(0, GFP_KERNEL)))
2207		goto allocerr;
2208
2209	for (j = 0; j < 2; ++j) {
2210		ubc = cs->bcs[j].hw.bas;
2211		for (i = 0; i < BAS_OUTURBS; ++i)
2212			if (!(ubc->isoouturbs[i].urb =
2213			      usb_alloc_urb(BAS_NUMFRAMES, GFP_KERNEL)))
2214				goto allocerr;
2215		for (i = 0; i < BAS_INURBS; ++i)
2216			if (!(ubc->isoinurbs[i] =
2217			      usb_alloc_urb(BAS_NUMFRAMES, GFP_KERNEL)))
2218				goto allocerr;
2219	}
2220
2221	ucs->rcvbuf = NULL;
2222	ucs->rcvbuf_size = 0;
2223
2224	/* Fill the interrupt urb and send it to the core */
2225	endpoint = &hostif->endpoint[0].desc;
2226	usb_fill_int_urb(ucs->urb_int_in, udev,
2227			 usb_rcvintpipe(udev,
2228					(endpoint->bEndpointAddress) & 0x0f),
2229			 ucs->int_in_buf, 3, read_int_callback, cs,
2230			 endpoint->bInterval);
2231	if ((rc = usb_submit_urb(ucs->urb_int_in, GFP_KERNEL)) != 0) {
2232		dev_err(cs->dev, "could not submit interrupt URB: %s\n",
2233			get_usb_rcmsg(rc));
2234		goto error;
2235	}
2236
2237	/* tell the device that the driver is ready */
2238	if ((rc = req_submit(cs->bcs, HD_DEVICE_INIT_ACK, 0, 0)) != 0)
2239		goto error;
2240
2241	/* tell common part that the device is ready */
2242	if (startmode == SM_LOCKED)
2243		atomic_set(&cs->mstate, MS_LOCKED);
2244
2245	/* save address of controller structure */
2246	usb_set_intfdata(interface, cs);
2247
2248	if (!gigaset_start(cs))
2249		goto error;
2250
2251	return 0;
2252
2253allocerr:
2254	dev_err(cs->dev, "could not allocate URBs\n");
2255error:
2256	freeurbs(cs);
2257	usb_set_intfdata(interface, NULL);
2258	gigaset_unassign(cs);
2259	return -ENODEV;
2260}
2261
2262/* gigaset_disconnect
2263 * This function is called when the Gigaset base is unplugged.
2264 */
2265static void gigaset_disconnect(struct usb_interface *interface)
2266{
2267	struct cardstate *cs;
2268	struct bas_cardstate *ucs;
2269	int j;
2270
2271	cs = usb_get_intfdata(interface);
2272
2273	ucs = cs->hw.bas;
2274
2275	dev_info(cs->dev, "disconnecting Gigaset base\n");
2276
2277	/* mark base as not ready, all channels disconnected */
2278	atomic_set(&ucs->basstate, 0);
2279
2280	/* tell LL all channels are down */
2281	for (j = 0; j < 2; ++j)
2282		gigaset_bchannel_down(cs->bcs + j);
2283
2284	/* stop driver (common part) */
2285	gigaset_stop(cs);
2286
2287	/* stop timers and URBs, free ressources */
2288	del_timer_sync(&ucs->timer_ctrl);
2289	del_timer_sync(&ucs->timer_atrdy);
2290	del_timer_sync(&ucs->timer_cmd_in);
2291	freeurbs(cs);
2292	usb_set_intfdata(interface, NULL);
2293	kfree(ucs->rcvbuf);
2294	ucs->rcvbuf = NULL;
2295	ucs->rcvbuf_size = 0;
2296	usb_put_dev(ucs->udev);
2297	ucs->interface = NULL;
2298	ucs->udev = NULL;
2299	cs->dev = NULL;
2300	gigaset_unassign(cs);
2301}
2302
2303static const struct gigaset_ops gigops = {
2304	gigaset_write_cmd,
2305	gigaset_write_room,
2306	gigaset_chars_in_buffer,
2307	gigaset_brkchars,
2308	gigaset_init_bchannel,
2309	gigaset_close_bchannel,
2310	gigaset_initbcshw,
2311	gigaset_freebcshw,
2312	gigaset_reinitbcshw,
2313	gigaset_initcshw,
2314	gigaset_freecshw,
2315	gigaset_set_modem_ctrl,
2316	gigaset_baud_rate,
2317	gigaset_set_line_ctrl,
2318	gigaset_isoc_send_skb,
2319	gigaset_isoc_input,
2320};
2321
2322/* bas_gigaset_init
2323 * This function is called after the kernel module is loaded.
2324 */
2325static int __init bas_gigaset_init(void)
2326{
2327	int result;
2328
2329	/* allocate memory for our driver state and intialize it */
2330	if ((driver = gigaset_initdriver(GIGASET_MINOR, GIGASET_MINORS,
2331				       GIGASET_MODULENAME, GIGASET_DEVNAME,
2332				       &gigops, THIS_MODULE)) == NULL)
2333		goto error;
2334
2335	/* allocate memory for our device state and intialize it */
2336	cardstate = gigaset_initcs(driver, 2, 0, 0, cidmode,
2337				   GIGASET_MODULENAME);
2338	if (!cardstate)
2339		goto error;
2340
2341	/* register this driver with the USB subsystem */
2342	result = usb_register(&gigaset_usb_driver);
2343	if (result < 0) {
2344		err("usb_register failed (error %d)", -result);
2345		goto error;
2346	}
2347
2348	info(DRIVER_AUTHOR);
2349	info(DRIVER_DESC);
2350	return 0;
2351
2352error:	if (cardstate)
2353		gigaset_freecs(cardstate);
2354	cardstate = NULL;
2355	if (driver)
2356		gigaset_freedriver(driver);
2357	driver = NULL;
2358	return -1;
2359}
2360
2361/* bas_gigaset_exit
2362 * This function is called before the kernel module is unloaded.
2363 */
2364static void __exit bas_gigaset_exit(void)
2365{
2366	struct bas_cardstate *ucs = cardstate->hw.bas;
2367
2368	gigaset_blockdriver(driver); /* => probe will fail
2369				      * => no gigaset_start any more
2370				      */
2371
2372	gigaset_shutdown(cardstate);
2373	/* from now on, no isdn callback should be possible */
2374
2375	/* close all still open channels */
2376	if (atomic_read(&ucs->basstate) & BS_B1OPEN) {
2377		gig_dbg(DEBUG_INIT, "closing B1 channel");
2378		usb_control_msg(ucs->udev, usb_sndctrlpipe(ucs->udev, 0),
2379				HD_CLOSE_B1CHANNEL, OUT_VENDOR_REQ, 0, 0,
2380				NULL, 0, BAS_TIMEOUT);
2381	}
2382	if (atomic_read(&ucs->basstate) & BS_B2OPEN) {
2383		gig_dbg(DEBUG_INIT, "closing B2 channel");
2384		usb_control_msg(ucs->udev, usb_sndctrlpipe(ucs->udev, 0),
2385				HD_CLOSE_B2CHANNEL, OUT_VENDOR_REQ, 0, 0,
2386				NULL, 0, BAS_TIMEOUT);
2387	}
2388	if (atomic_read(&ucs->basstate) & BS_ATOPEN) {
2389		gig_dbg(DEBUG_INIT, "closing AT channel");
2390		usb_control_msg(ucs->udev, usb_sndctrlpipe(ucs->udev, 0),
2391				HD_CLOSE_ATCHANNEL, OUT_VENDOR_REQ, 0, 0,
2392				NULL, 0, BAS_TIMEOUT);
2393	}
2394	atomic_set(&ucs->basstate, 0);
2395
2396	/* deregister this driver with the USB subsystem */
2397	usb_deregister(&gigaset_usb_driver);
2398	/* this will call the disconnect-callback */
2399	/* from now on, no disconnect/probe callback should be running */
2400
2401	gigaset_freecs(cardstate);
2402	cardstate = NULL;
2403	gigaset_freedriver(driver);
2404	driver = NULL;
2405}
2406
2407
2408module_init(bas_gigaset_init);
2409module_exit(bas_gigaset_exit);
2410
2411MODULE_AUTHOR(DRIVER_AUTHOR);
2412MODULE_DESCRIPTION(DRIVER_DESC);
2413MODULE_LICENSE("GPL");
2414