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