VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.git] / drivers / usb / misc / auerswald.c
1 /*****************************************************************************/
2 /*
3  *      auerswald.c  --  Auerswald PBX/System Telephone usb driver.
4  *
5  *      Copyright (C) 2001  Wolfgang Mües (wolfgang@iksw-muees.de)
6  *
7  *      Very much code of this driver is borrowed from dabusb.c (Deti Fliegl)
8  *      and from the USB Skeleton driver (Greg Kroah-Hartman). Thank you.
9  *
10  *      This program is free software; you can redistribute it and/or modify
11  *      it under the terms of the GNU General Public License as published by
12  *      the Free Software Foundation; either version 2 of the License, or
13  *      (at your option) any later version.
14  *
15  *      This program is distributed in the hope that it will be useful,
16  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *      GNU General Public License for more details.
19  *
20  *      You should have received a copy of the GNU General Public License
21  *      along with this program; if not, write to the Free Software
22  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24  /*****************************************************************************/
25
26 /* Standard Linux module include files */
27 #include <asm/uaccess.h>
28 #include <asm/byteorder.h>
29 #include <linux/slab.h>
30 #include <linux/module.h>
31 #include <linux/init.h>
32 #undef DEBUG            /* include debug macros until it's done */
33 #include <linux/usb.h>
34
35 /*-------------------------------------------------------------------*/
36 /* Debug support                                                     */
37 #ifdef DEBUG
38 #define dump( adr, len) \
39 do {                    \
40         unsigned int u; \
41         printk (KERN_DEBUG); \
42         for (u = 0; u < len; u++) \
43                 printk (" %02X", adr[u] & 0xFF); \
44         printk ("\n"); \
45 } while (0)
46 #else
47 #define dump( adr, len)
48 #endif
49
50 /*-------------------------------------------------------------------*/
51 /* Version Information */
52 #define DRIVER_VERSION "0.9.11"
53 #define DRIVER_AUTHOR  "Wolfgang Mües <wolfgang@iksw-muees.de>"
54 #define DRIVER_DESC    "Auerswald PBX/System Telephone usb driver"
55
56 /*-------------------------------------------------------------------*/
57 /* Private declarations for Auerswald USB driver                     */
58
59 /* Auerswald Vendor ID */
60 #define ID_AUERSWALD    0x09BF
61
62 #define AUER_MINOR_BASE 112     /* auerswald driver minor number */
63
64 /* we can have up to this number of device plugged in at once */
65 #define AUER_MAX_DEVICES 16
66
67
68 /* Number of read buffers for each device */
69 #define AU_RBUFFERS     10
70
71 /* Number of chain elements for each control chain */
72 #define AUCH_ELEMENTS   20
73
74 /* Number of retries in communication */
75 #define AU_RETRIES      10
76
77 /*-------------------------------------------------------------------*/
78 /* vendor specific protocol                                          */
79 /* Header Byte */
80 #define AUH_INDIRMASK   0x80    /* mask for direct/indirect bit */
81 #define AUH_DIRECT      0x00    /* data is for USB device */
82 #define AUH_INDIRECT    0x80    /* USB device is relay */
83
84 #define AUH_SPLITMASK   0x40    /* mask for split bit */
85 #define AUH_UNSPLIT     0x00    /* data block is full-size */
86 #define AUH_SPLIT       0x40    /* data block is part of a larger one,
87                                    split-byte follows */
88
89 #define AUH_TYPEMASK    0x3F    /* mask for type of data transfer */
90 #define AUH_TYPESIZE    0x40    /* different types */
91 #define AUH_DCHANNEL    0x00    /* D channel data */
92 #define AUH_B1CHANNEL   0x01    /* B1 channel transparent */
93 #define AUH_B2CHANNEL   0x02    /* B2 channel transparent */
94 /*                0x03..0x0F       reserved for driver internal use */
95 #define AUH_COMMAND     0x10    /* Command channel */
96 #define AUH_BPROT       0x11    /* Configuration block protocol */
97 #define AUH_DPROTANA    0x12    /* D channel protocol analyzer */
98 #define AUH_TAPI        0x13    /* telephone api data (ATD) */
99 /*                0x14..0x3F       reserved for other protocols */
100 #define AUH_UNASSIGNED  0xFF    /* if char device has no assigned service */
101 #define AUH_FIRSTUSERCH 0x11    /* first channel which is available for driver users */
102
103 #define AUH_SIZE        1       /* Size of Header Byte */
104
105 /* Split Byte. Only present if split bit in header byte set.*/
106 #define AUS_STARTMASK   0x80    /* mask for first block of splitted frame */
107 #define AUS_FIRST       0x80    /* first block */
108 #define AUS_FOLLOW      0x00    /* following block */
109
110 #define AUS_ENDMASK     0x40    /* mask for last block of splitted frame */
111 #define AUS_END         0x40    /* last block */
112 #define AUS_NOEND       0x00    /* not the last block */
113
114 #define AUS_LENMASK     0x3F    /* mask for block length information */
115
116 /* Request types */
117 #define AUT_RREQ        (USB_DIR_IN  | USB_TYPE_VENDOR | USB_RECIP_OTHER)   /* Read Request */
118 #define AUT_WREQ        (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_OTHER)   /* Write Request */
119
120 /* Vendor Requests */
121 #define AUV_GETINFO     0x00    /* GetDeviceInfo */
122 #define AUV_WBLOCK      0x01    /* Write Block */
123 #define AUV_RBLOCK      0x02    /* Read Block */
124 #define AUV_CHANNELCTL  0x03    /* Channel Control */
125 #define AUV_DUMMY       0x04    /* Dummy Out for retry */
126
127 /* Device Info Types */
128 #define AUDI_NUMBCH     0x0000  /* Number of supported B channels */
129 #define AUDI_OUTFSIZE   0x0001  /* Size of OUT B channel fifos */
130 #define AUDI_MBCTRANS   0x0002  /* max. Blocklength of control transfer */
131
132 /* Interrupt endpoint definitions */
133 #define AU_IRQENDP      1       /* Endpoint number */
134 #define AU_IRQCMDID     16      /* Command-block ID */
135 #define AU_BLOCKRDY     0       /* Command: Block data ready on ctl endpoint */
136 #define AU_IRQMINSIZE   5       /* Nr. of bytes decoded in this driver */
137
138 /* Device String Descriptors */
139 #define AUSI_VENDOR     1       /* "Auerswald GmbH & Co. KG" */
140 #define AUSI_DEVICE     2       /* Name of the Device */
141 #define AUSI_SERIALNR   3       /* Serial Number */
142 #define AUSI_MSN        4       /* "MSN ..." (first) Multiple Subscriber Number */
143
144 #define AUSI_DLEN       100     /* Max. Length of Device Description */
145
146 #define AUV_RETRY       0x101   /* First Firmware version which can do control retries */
147
148 /*-------------------------------------------------------------------*/
149 /* External data structures / Interface                              */
150 typedef struct
151 {
152         char __user *buf;       /* return buffer for string contents */
153         unsigned int bsize;     /* size of return buffer */
154 } audevinfo_t,*paudevinfo_t;
155
156 /* IO controls */
157 #define IOCTL_AU_SLEN     _IOR( 'U', 0xF0, int)         /* return the max. string descriptor length */
158 #define IOCTL_AU_DEVINFO  _IOWR('U', 0xF1, audevinfo_t) /* get name of a specific device */
159 #define IOCTL_AU_SERVREQ  _IOW( 'U', 0xF2, int)         /* request a service channel */
160 #define IOCTL_AU_BUFLEN   _IOR( 'U', 0xF3, int)         /* return the max. buffer length for the device */
161 #define IOCTL_AU_RXAVAIL  _IOR( 'U', 0xF4, int)         /* return != 0 if Receive Data available */
162 #define IOCTL_AU_CONNECT  _IOR( 'U', 0xF5, int)         /* return != 0 if connected to a service channel */
163 #define IOCTL_AU_TXREADY  _IOR( 'U', 0xF6, int)         /* return != 0 if Transmitt channel ready to send */
164 /*                              'U'  0xF7..0xFF reseved */
165
166 /*-------------------------------------------------------------------*/
167 /* Internal data structures                                          */
168
169 /* ..................................................................*/
170 /* urb chain element */
171 struct  auerchain;                      /* forward for circular reference */
172 typedef struct
173 {
174         struct auerchain *chain;        /* pointer to the chain to which this element belongs */
175         struct urb * urbp;                   /* pointer to attached urb */
176         void *context;                  /* saved URB context */
177         usb_complete_t complete;        /* saved URB completion function */
178         struct list_head list;          /* to include element into a list */
179 } auerchainelement_t,*pauerchainelement_t;
180
181 /* urb chain */
182 typedef struct auerchain
183 {
184         pauerchainelement_t active;     /* element which is submitted to urb */
185         spinlock_t lock;                /* protection agains interrupts */
186         struct list_head waiting_list;  /* list of waiting elements */
187         struct list_head free_list;     /* list of available elements */
188 } auerchain_t,*pauerchain_t;
189
190 /* urb blocking completion helper struct */
191 typedef struct
192 {
193         wait_queue_head_t wqh;          /* wait for completion */
194         unsigned int done;              /* completion flag */
195 } auerchain_chs_t,*pauerchain_chs_t;
196
197 /* ...................................................................*/
198 /* buffer element */
199 struct  auerbufctl;                     /* forward */
200 typedef struct
201 {
202         char *bufp;                     /* reference to allocated data buffer */
203         unsigned int len;               /* number of characters in data buffer */
204         unsigned int retries;           /* for urb retries */
205         struct usb_ctrlrequest *dr;     /* for setup data in control messages */
206         struct urb * urbp;                   /* USB urb */
207         struct auerbufctl *list;        /* pointer to list */
208         struct list_head buff_list;     /* reference to next buffer in list */
209 } auerbuf_t,*pauerbuf_t;
210
211 /* buffer list control block */
212 typedef struct auerbufctl
213 {
214         spinlock_t lock;                /* protection in interrupt */
215         struct list_head free_buff_list;/* free buffers */
216         struct list_head rec_buff_list; /* buffers with receive data */
217 } auerbufctl_t,*pauerbufctl_t;
218
219 /* ...................................................................*/
220 /* service context */
221 struct  auerscon;                       /* forward */
222 typedef void (*auer_dispatch_t)(struct auerscon*, pauerbuf_t);
223 typedef void (*auer_disconn_t) (struct auerscon*);
224 typedef struct auerscon
225 {
226         unsigned int id;                /* protocol service id AUH_xxxx */
227         auer_dispatch_t dispatch;       /* dispatch read buffer */
228         auer_disconn_t disconnect;      /* disconnect from device, wake up all char readers */
229 } auerscon_t,*pauerscon_t;
230
231 /* ...................................................................*/
232 /* USB device context */
233 typedef struct
234 {
235         struct semaphore        mutex;              /* protection in user context */
236         char                    name[20];           /* name of the /dev/usb entry */
237         unsigned int            dtindex;            /* index in the device table */
238         struct usb_device *     usbdev;             /* USB device handle */
239         int                     open_count;         /* count the number of open character channels */
240         char                    dev_desc[AUSI_DLEN];/* for storing a textual description */
241         unsigned int            maxControlLength;   /* max. Length of control paket (without header) */
242         struct urb *            inturbp;            /* interrupt urb */
243         char *                  intbufp;            /* data buffer for interrupt urb */
244         unsigned int            irqsize;            /* size of interrupt endpoint 1 */
245         struct auerchain        controlchain;       /* for chaining of control messages */
246         auerbufctl_t            bufctl;             /* Buffer control for control transfers */
247         pauerscon_t             services[AUH_TYPESIZE];/* context pointers for each service */
248         unsigned int            version;            /* Version of the device */
249         wait_queue_head_t       bufferwait;         /* wait for a control buffer */
250 } auerswald_t,*pauerswald_t;
251
252 /* ................................................................... */
253 /* character device context */
254 typedef struct
255 {
256         struct semaphore mutex;         /* protection in user context */
257         pauerswald_t auerdev;           /* context pointer of assigned device */
258         auerbufctl_t bufctl;            /* controls the buffer chain */
259         auerscon_t scontext;            /* service context */
260         wait_queue_head_t readwait;     /* for synchronous reading */
261         struct semaphore readmutex;     /* protection against multiple reads */
262         pauerbuf_t readbuf;             /* buffer held for partial reading */
263         unsigned int readoffset;        /* current offset in readbuf */
264         unsigned int removed;           /* is != 0 if device is removed */
265 } auerchar_t,*pauerchar_t;
266
267
268 /*-------------------------------------------------------------------*/
269 /* Forwards */
270 static void auerswald_ctrlread_complete (struct urb * urb, struct pt_regs *regs);
271 static void auerswald_removeservice (pauerswald_t cp, pauerscon_t scp);
272 extern struct usb_driver auerswald_driver;
273
274
275 /*-------------------------------------------------------------------*/
276 /* USB chain helper functions                                        */
277 /* --------------------------                                        */
278
279 /* completion function for chained urbs */
280 static void auerchain_complete (struct urb * urb, struct pt_regs *regs)
281 {
282         unsigned long flags;
283         int result;
284
285         /* get pointer to element and to chain */
286         pauerchainelement_t acep = (pauerchainelement_t) urb->context;
287         pauerchain_t         acp = acep->chain;
288
289         /* restore original entries in urb */
290         urb->context  = acep->context;
291         urb->complete = acep->complete;
292
293         dbg ("auerchain_complete called");
294
295         /* call original completion function
296            NOTE: this function may lead to more urbs submitted into the chain.
297                  (no chain lock at calling complete()!)
298                  acp->active != NULL is protecting us against recursion.*/
299         urb->complete (urb, regs);
300
301         /* detach element from chain data structure */
302         spin_lock_irqsave (&acp->lock, flags);
303         if (acp->active != acep) /* paranoia debug check */
304                 dbg ("auerchain_complete: completion on non-active element called!");
305         else
306                 acp->active = NULL;
307
308         /* add the used chain element to the list of free elements */
309         list_add_tail (&acep->list, &acp->free_list);
310         acep = NULL;
311
312         /* is there a new element waiting in the chain? */
313         if (!acp->active && !list_empty (&acp->waiting_list)) {
314                 /* yes: get the entry */
315                 struct list_head *tmp = acp->waiting_list.next;
316                 list_del (tmp);
317                 acep = list_entry (tmp, auerchainelement_t, list);
318                 acp->active = acep;
319         }
320         spin_unlock_irqrestore (&acp->lock, flags);
321
322         /* submit the new urb */
323         if (acep) {
324                 urb    = acep->urbp;
325                 dbg ("auerchain_complete: submitting next urb from chain");
326                 urb->status = 0;        /* needed! */
327                 result = usb_submit_urb(urb, GFP_ATOMIC);
328
329                 /* check for submit errors */
330                 if (result) {
331                         urb->status = result;
332                         dbg("auerchain_complete: usb_submit_urb with error code %d", result);
333                         /* and do error handling via *this* completion function (recursive) */
334                         auerchain_complete( urb, NULL);
335                 }
336         } else {
337                 /* simple return without submitting a new urb.
338                    The empty chain is detected with acp->active == NULL. */
339         };
340 }
341
342
343 /* submit function for chained urbs
344    this function may be called from completion context or from user space!
345    early = 1 -> submit in front of chain
346 */
347 static int auerchain_submit_urb_list (pauerchain_t acp, struct urb * urb, int early)
348 {
349         int result;
350         unsigned long flags;
351         pauerchainelement_t acep = NULL;
352
353         dbg ("auerchain_submit_urb called");
354
355         /* try to get a chain element */
356         spin_lock_irqsave (&acp->lock, flags);
357         if (!list_empty (&acp->free_list)) {
358                 /* yes: get the entry */
359                 struct list_head *tmp = acp->free_list.next;
360                 list_del (tmp);
361                 acep = list_entry (tmp, auerchainelement_t, list);
362         }
363         spin_unlock_irqrestore (&acp->lock, flags);
364
365         /* if no chain element available: return with error */
366         if (!acep) {
367                 return -ENOMEM;
368         }
369
370         /* fill in the new chain element values */
371         acep->chain    = acp;
372         acep->context  = urb->context;
373         acep->complete = urb->complete;
374         acep->urbp     = urb;
375         INIT_LIST_HEAD (&acep->list);
376
377         /* modify urb */
378         urb->context   = acep;
379         urb->complete  = auerchain_complete;
380         urb->status    = -EINPROGRESS;    /* usb_submit_urb does this, too */
381
382         /* add element to chain - or start it immediately */
383         spin_lock_irqsave (&acp->lock, flags);
384         if (acp->active) {
385                 /* there is traffic in the chain, simple add element to chain */
386                 if (early) {
387                         dbg ("adding new urb to head of chain");
388                         list_add (&acep->list, &acp->waiting_list);
389                 } else {
390                         dbg ("adding new urb to end of chain");
391                         list_add_tail (&acep->list, &acp->waiting_list);
392                 }
393                 acep = NULL;
394         } else {
395                 /* the chain is empty. Prepare restart */
396                 acp->active = acep;
397         }
398         /* Spin has to be removed before usb_submit_urb! */
399         spin_unlock_irqrestore (&acp->lock, flags);
400
401         /* Submit urb if immediate restart */
402         if (acep) {
403                 dbg("submitting urb immediate");
404                 urb->status = 0;        /* needed! */
405                 result = usb_submit_urb(urb, GFP_ATOMIC);
406                 /* check for submit errors */
407                 if (result) {
408                         urb->status = result;
409                         dbg("auerchain_submit_urb: usb_submit_urb with error code %d", result);
410                         /* and do error handling via completion function */
411                         auerchain_complete( urb, NULL);
412                 }
413         }
414
415         return 0;
416 }
417
418 /* submit function for chained urbs
419    this function may be called from completion context or from user space!
420 */
421 static int auerchain_submit_urb (pauerchain_t acp, struct urb * urb)
422 {
423         return auerchain_submit_urb_list (acp, urb, 0);
424 }
425
426 /* cancel an urb which is submitted to the chain
427    the result is 0 if the urb is cancelled, or -EINPROGRESS if
428    URB_ASYNC_UNLINK is set and the function is successfully started.
429 */
430 static int auerchain_unlink_urb (pauerchain_t acp, struct urb * urb)
431 {
432         unsigned long flags;
433         struct urb * urbp;
434         pauerchainelement_t acep;
435         struct list_head *tmp;
436
437         dbg ("auerchain_unlink_urb called");
438
439         /* search the chain of waiting elements */
440         spin_lock_irqsave (&acp->lock, flags);
441         list_for_each (tmp, &acp->waiting_list) {
442                 acep = list_entry (tmp, auerchainelement_t, list);
443                 if (acep->urbp == urb) {
444                         list_del (tmp);
445                         urb->context = acep->context;
446                         urb->complete = acep->complete;
447                         list_add_tail (&acep->list, &acp->free_list);
448                         spin_unlock_irqrestore (&acp->lock, flags);
449                         dbg ("unlink waiting urb");
450                         urb->status = -ENOENT;
451                         urb->complete (urb, NULL);
452                         return 0;
453                 }
454         }
455         /* not found. */
456         spin_unlock_irqrestore (&acp->lock, flags);
457
458         /* get the active urb */
459         acep = acp->active;
460         if (acep) {
461                 urbp = acep->urbp;
462
463                 /* check if we have to cancel the active urb */
464                 if (urbp == urb) {
465                         /* note that there is a race condition between the check above
466                            and the unlink() call because of no lock. This race is harmless,
467                            because the usb module will detect the unlink() after completion.
468                            We can't use the acp->lock here because the completion function
469                            wants to grab it.
470                         */
471                         dbg ("unlink active urb");
472                         return usb_unlink_urb (urbp);
473                 }
474         }
475
476         /* not found anyway
477            ... is some kind of success
478         */
479         dbg ("urb to unlink not found in chain");
480         return 0;
481 }
482
483 /* cancel all urbs which are in the chain.
484    this function must not be called from interrupt or completion handler.
485 */
486 static void auerchain_unlink_all (pauerchain_t acp)
487 {
488         unsigned long flags;
489         struct urb * urbp;
490         pauerchainelement_t acep;
491
492         dbg ("auerchain_unlink_all called");
493
494         /* clear the chain of waiting elements */
495         spin_lock_irqsave (&acp->lock, flags);
496         while (!list_empty (&acp->waiting_list)) {
497                 /* get the next entry */
498                 struct list_head *tmp = acp->waiting_list.next;
499                 list_del (tmp);
500                 acep = list_entry (tmp, auerchainelement_t, list);
501                 urbp = acep->urbp;
502                 urbp->context = acep->context;
503                 urbp->complete = acep->complete;
504                 list_add_tail (&acep->list, &acp->free_list);
505                 spin_unlock_irqrestore (&acp->lock, flags);
506                 dbg ("unlink waiting urb");
507                 urbp->status = -ENOENT;
508                 urbp->complete (urbp, NULL);
509                 spin_lock_irqsave (&acp->lock, flags);
510         }
511         spin_unlock_irqrestore (&acp->lock, flags);
512
513         /* clear the active urb */
514         acep = acp->active;
515         if (acep) {
516                 urbp = acep->urbp;
517                 urbp->transfer_flags &= ~URB_ASYNC_UNLINK;
518                 dbg ("unlink active urb");
519                 usb_unlink_urb (urbp);
520         }
521 }
522
523
524 /* free the chain.
525    this function must not be called from interrupt or completion handler.
526 */
527 static void auerchain_free (pauerchain_t acp)
528 {
529         unsigned long flags;
530         pauerchainelement_t acep;
531
532         dbg ("auerchain_free called");
533
534         /* first, cancel all pending urbs */
535         auerchain_unlink_all (acp);
536
537         /* free the elements */
538         spin_lock_irqsave (&acp->lock, flags);
539         while (!list_empty (&acp->free_list)) {
540                 /* get the next entry */
541                 struct list_head *tmp = acp->free_list.next;
542                 list_del (tmp);
543                 spin_unlock_irqrestore (&acp->lock, flags);
544                 acep = list_entry (tmp, auerchainelement_t, list);
545                 kfree (acep);
546                 spin_lock_irqsave (&acp->lock, flags);
547         }
548         spin_unlock_irqrestore (&acp->lock, flags);
549 }
550
551
552 /* Init the chain control structure */
553 static void auerchain_init (pauerchain_t acp)
554 {
555         /* init the chain data structure */
556         acp->active = NULL;
557         spin_lock_init (&acp->lock);
558         INIT_LIST_HEAD (&acp->waiting_list);
559         INIT_LIST_HEAD (&acp->free_list);
560 }
561
562 /* setup a chain.
563    It is assumed that there is no concurrency while setting up the chain
564    requirement: auerchain_init()
565 */
566 static int auerchain_setup (pauerchain_t acp, unsigned int numElements)
567 {
568         pauerchainelement_t acep;
569
570         dbg ("auerchain_setup called with %d elements", numElements);
571
572         /* fill the list of free elements */
573         for (;numElements; numElements--) {
574                 acep = (pauerchainelement_t) kmalloc (sizeof (auerchainelement_t), GFP_KERNEL);
575                 if (!acep)
576                         goto ac_fail;
577                 memset (acep, 0, sizeof (auerchainelement_t));
578                 INIT_LIST_HEAD (&acep->list);
579                 list_add_tail (&acep->list, &acp->free_list);
580         }
581         return 0;
582
583 ac_fail:/* free the elements */
584         while (!list_empty (&acp->free_list)) {
585                 /* get the next entry */
586                 struct list_head *tmp = acp->free_list.next;
587                 list_del (tmp);
588                 acep = list_entry (tmp, auerchainelement_t, list);
589                 kfree (acep);
590         }
591         return -ENOMEM;
592 }
593
594
595 /* completion handler for synchronous chained URBs */
596 static void auerchain_blocking_completion (struct urb *urb, struct pt_regs *regs)
597 {
598         pauerchain_chs_t pchs = (pauerchain_chs_t)urb->context;
599         pchs->done = 1;
600         wmb();
601         wake_up (&pchs->wqh);
602 }
603
604
605 /* Starts chained urb and waits for completion or timeout */
606 static int auerchain_start_wait_urb (pauerchain_t acp, struct urb *urb, int timeout, int* actual_length)
607 {
608         DECLARE_WAITQUEUE (wait, current);
609         auerchain_chs_t chs;
610         int status;
611
612         dbg ("auerchain_start_wait_urb called");
613         init_waitqueue_head (&chs.wqh);
614         chs.done = 0;
615
616         set_current_state (TASK_UNINTERRUPTIBLE);
617         add_wait_queue (&chs.wqh, &wait);
618         urb->context = &chs;
619         status = auerchain_submit_urb (acp, urb);
620         if (status) {
621                 /* something went wrong */
622                 set_current_state (TASK_RUNNING);
623                 remove_wait_queue (&chs.wqh, &wait);
624                 return status;
625         }
626
627         while (timeout && !chs.done)
628         {
629                 timeout = schedule_timeout (timeout);
630                 set_current_state(TASK_UNINTERRUPTIBLE);
631                 rmb();
632         }
633
634         set_current_state (TASK_RUNNING);
635         remove_wait_queue (&chs.wqh, &wait);
636
637         if (!timeout && !chs.done) {
638                 if (urb->status != -EINPROGRESS) {      /* No callback?!! */
639                         dbg ("auerchain_start_wait_urb: raced timeout");
640                         status = urb->status;
641                 } else {
642                         dbg ("auerchain_start_wait_urb: timeout");
643                         auerchain_unlink_urb (acp, urb);  /* remove urb safely */
644                         status = -ETIMEDOUT;
645                 }
646         } else
647                 status = urb->status;
648
649         if (actual_length)
650                 *actual_length = urb->actual_length;
651
652         return status;
653 }
654
655
656 /* auerchain_control_msg - Builds a control urb, sends it off and waits for completion
657    acp: pointer to the auerchain
658    dev: pointer to the usb device to send the message to
659    pipe: endpoint "pipe" to send the message to
660    request: USB message request value
661    requesttype: USB message request type value
662    value: USB message value
663    index: USB message index value
664    data: pointer to the data to send
665    size: length in bytes of the data to send
666    timeout: time to wait for the message to complete before timing out (if 0 the wait is forever)
667
668    This function sends a simple control message to a specified endpoint
669    and waits for the message to complete, or timeout.
670
671    If successful, it returns the transferred length, otherwise a negative error number.
672
673    Don't use this function from within an interrupt context, like a
674    bottom half handler.  If you need an asynchronous message, or need to send
675    a message from within interrupt context, use auerchain_submit_urb()
676 */
677 static int auerchain_control_msg (pauerchain_t acp, struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
678                                   __u16 value, __u16 index, void *data, __u16 size, int timeout)
679 {
680         int ret;
681         struct usb_ctrlrequest *dr;
682         struct urb *urb;
683         int length;
684
685         dbg ("auerchain_control_msg");
686         dr = kmalloc (sizeof (struct usb_ctrlrequest), GFP_KERNEL);
687         if (!dr)
688                 return -ENOMEM;
689         urb = usb_alloc_urb (0, GFP_KERNEL);
690         if (!urb) {
691                 kfree (dr);
692                 return -ENOMEM;
693         }
694
695         dr->bRequestType = requesttype;
696         dr->bRequest = request;
697         dr->wValue  = cpu_to_le16 (value);
698         dr->wIndex  = cpu_to_le16 (index);
699         dr->wLength = cpu_to_le16 (size);
700
701         usb_fill_control_urb (urb, dev, pipe, (unsigned char*)dr, data, size,    /* build urb */
702                           auerchain_blocking_completion, NULL);
703         ret = auerchain_start_wait_urb (acp, urb, timeout, &length);
704
705         usb_free_urb (urb);
706         kfree (dr);
707
708         if (ret < 0)
709                 return ret;
710         else
711                 return length;
712 }
713
714
715 /*-------------------------------------------------------------------*/
716 /* Buffer List helper functions                                      */
717
718 /* free a single auerbuf */
719 static void auerbuf_free (pauerbuf_t bp)
720 {
721         if (bp->bufp) {
722                 kfree (bp->bufp);
723         }
724         if (bp->dr) {
725                 kfree (bp->dr);
726         }
727         if (bp->urbp) {
728                 usb_free_urb (bp->urbp);
729         }
730         kfree (bp);
731 }
732
733 /* free the buffers from an auerbuf list */
734 static void auerbuf_free_list (struct list_head *q)
735 {
736         struct list_head *tmp;
737         struct list_head *p;
738         pauerbuf_t bp;
739
740         dbg ("auerbuf_free_list");
741         for (p = q->next; p != q;) {
742                 bp = list_entry (p, auerbuf_t, buff_list);
743                 tmp = p->next;
744                 list_del (p);
745                 p = tmp;
746                 auerbuf_free (bp);
747         }
748 }
749
750 /* init the members of a list control block */
751 static void auerbuf_init (pauerbufctl_t bcp)
752 {
753         dbg ("auerbuf_init");
754         spin_lock_init (&bcp->lock);
755         INIT_LIST_HEAD (&bcp->free_buff_list);
756         INIT_LIST_HEAD (&bcp->rec_buff_list);
757 }
758
759 /* free all buffers from an auerbuf chain */
760 static void auerbuf_free_buffers (pauerbufctl_t bcp)
761 {
762         unsigned long flags;
763         dbg ("auerbuf_free_buffers");
764
765         spin_lock_irqsave (&bcp->lock, flags);
766
767         auerbuf_free_list (&bcp->free_buff_list);
768         auerbuf_free_list (&bcp->rec_buff_list);
769
770         spin_unlock_irqrestore (&bcp->lock, flags);
771 }
772
773 /* setup a list of buffers */
774 /* requirement: auerbuf_init() */
775 static int auerbuf_setup (pauerbufctl_t bcp, unsigned int numElements, unsigned int bufsize)
776 {
777         pauerbuf_t bep = NULL;
778
779         dbg ("auerbuf_setup called with %d elements of %d bytes", numElements, bufsize);
780
781         /* fill the list of free elements */
782         for (;numElements; numElements--) {
783                 bep = (pauerbuf_t) kmalloc (sizeof (auerbuf_t), GFP_KERNEL);
784                 if (!bep)
785                         goto bl_fail;
786                 memset (bep, 0, sizeof (auerbuf_t));
787                 bep->list = bcp;
788                 INIT_LIST_HEAD (&bep->buff_list);
789                 bep->bufp = (char *) kmalloc (bufsize, GFP_KERNEL);
790                 if (!bep->bufp)
791                         goto bl_fail;
792                 bep->dr = (struct usb_ctrlrequest *) kmalloc (sizeof (struct usb_ctrlrequest), GFP_KERNEL);
793                 if (!bep->dr)
794                         goto bl_fail;
795                 bep->urbp = usb_alloc_urb (0, GFP_KERNEL);
796                 if (!bep->urbp)
797                         goto bl_fail;
798                 list_add_tail (&bep->buff_list, &bcp->free_buff_list);
799         }
800         return 0;
801
802 bl_fail:/* not enough memory. Free allocated elements */
803         dbg ("auerbuf_setup: no more memory");
804         kfree(bep);
805         auerbuf_free_buffers (bcp);
806         return -ENOMEM;
807 }
808
809 /* insert a used buffer into the free list */
810 static void auerbuf_releasebuf( pauerbuf_t bp)
811 {
812         unsigned long flags;
813         pauerbufctl_t bcp = bp->list;
814         bp->retries = 0;
815
816         dbg ("auerbuf_releasebuf called");
817         spin_lock_irqsave (&bcp->lock, flags);
818         list_add_tail (&bp->buff_list, &bcp->free_buff_list);
819         spin_unlock_irqrestore (&bcp->lock, flags);
820 }
821
822
823 /*-------------------------------------------------------------------*/
824 /* Completion handlers */
825
826 /* Values of urb->status or results of usb_submit_urb():
827 0               Initial, OK
828 -EINPROGRESS    during submission until end
829 -ENOENT         if urb is unlinked
830 -ETIMEDOUT      Transfer timed out, NAK
831 -ENOMEM         Memory Overflow
832 -ENODEV         Specified USB-device or bus doesn't exist
833 -ENXIO          URB already queued
834 -EINVAL         a) Invalid transfer type specified (or not supported)
835                 b) Invalid interrupt interval (0n256)
836 -EAGAIN         a) Specified ISO start frame too early
837                 b) (using ISO-ASAP) Too much scheduled for the future wait some time and try again.
838 -EFBIG          Too much ISO frames requested (currently uhci900)
839 -EPIPE          Specified pipe-handle/Endpoint is already stalled
840 -EMSGSIZE       Endpoint message size is zero, do interface/alternate setting
841 -EPROTO         a) Bitstuff error
842                 b) Unknown USB error
843 -EILSEQ         CRC mismatch
844 -ENOSR          Buffer error
845 -EREMOTEIO      Short packet detected
846 -EXDEV          ISO transfer only partially completed look at individual frame status for details
847 -EINVAL         ISO madness, if this happens: Log off and go home
848 -EOVERFLOW      babble
849 */
850
851 /* check if a status code allows a retry */
852 static int auerswald_status_retry (int status)
853 {
854         switch (status) {
855         case 0:
856         case -ETIMEDOUT:
857         case -EOVERFLOW:
858         case -EAGAIN:
859         case -EPIPE:
860         case -EPROTO:
861         case -EILSEQ:
862         case -ENOSR:
863         case -EREMOTEIO:
864                 return 1; /* do a retry */
865         }
866         return 0;       /* no retry possible */
867 }
868
869 /* Completion of asynchronous write block */
870 static void auerchar_ctrlwrite_complete (struct urb * urb, struct pt_regs *regs)
871 {
872         pauerbuf_t bp = (pauerbuf_t) urb->context;
873         pauerswald_t cp = ((pauerswald_t)((char *)(bp->list)-(unsigned long)(&((pauerswald_t)0)->bufctl)));
874         dbg ("auerchar_ctrlwrite_complete called");
875
876         /* reuse the buffer */
877         auerbuf_releasebuf (bp);
878         /* Wake up all processes waiting for a buffer */
879         wake_up (&cp->bufferwait);
880 }
881
882 /* Completion handler for dummy retry packet */
883 static void auerswald_ctrlread_wretcomplete (struct urb * urb, struct pt_regs *regs)
884 {
885         pauerbuf_t bp = (pauerbuf_t) urb->context;
886         pauerswald_t cp;
887         int ret;
888         dbg ("auerswald_ctrlread_wretcomplete called");
889         dbg ("complete with status: %d", urb->status);
890         cp = ((pauerswald_t)((char *)(bp->list)-(unsigned long)(&((pauerswald_t)0)->bufctl)));
891
892         /* check if it is possible to advance */
893         if (!auerswald_status_retry (urb->status) || !cp->usbdev) {
894                 /* reuse the buffer */
895                 err ("control dummy: transmission error %d, can not retry", urb->status);
896                 auerbuf_releasebuf (bp);
897                 /* Wake up all processes waiting for a buffer */
898                 wake_up (&cp->bufferwait);
899                 return;
900         }
901
902         /* fill the control message */
903         bp->dr->bRequestType = AUT_RREQ;
904         bp->dr->bRequest     = AUV_RBLOCK;
905         bp->dr->wLength      = bp->dr->wValue;  /* temporary stored */
906         bp->dr->wValue       = cpu_to_le16 (1); /* Retry Flag */
907         /* bp->dr->index    = channel id;          remains */
908         usb_fill_control_urb (bp->urbp, cp->usbdev, usb_rcvctrlpipe (cp->usbdev, 0),
909                           (unsigned char*)bp->dr, bp->bufp, le16_to_cpu (bp->dr->wLength),
910                           auerswald_ctrlread_complete,bp);
911
912         /* submit the control msg as next paket */
913         ret = auerchain_submit_urb_list (&cp->controlchain, bp->urbp, 1);
914         if (ret) {
915                 dbg ("auerswald_ctrlread_complete: nonzero result of auerchain_submit_urb_list %d", ret);
916                 bp->urbp->status = ret;
917                 auerswald_ctrlread_complete (bp->urbp, NULL);
918         }
919 }
920
921 /* completion handler for receiving of control messages */
922 static void auerswald_ctrlread_complete (struct urb * urb, struct pt_regs *regs)
923 {
924         unsigned int  serviceid;
925         pauerswald_t  cp;
926         pauerscon_t   scp;
927         pauerbuf_t    bp  = (pauerbuf_t) urb->context;
928         int ret;
929         dbg ("auerswald_ctrlread_complete called");
930
931         cp = ((pauerswald_t)((char *)(bp->list)-(unsigned long)(&((pauerswald_t)0)->bufctl)));
932
933         /* check if there is valid data in this urb */
934         if (urb->status) {
935                 dbg ("complete with non-zero status: %d", urb->status);
936                 /* should we do a retry? */
937                 if (!auerswald_status_retry (urb->status)
938                  || !cp->usbdev
939                  || (cp->version < AUV_RETRY)
940                  || (bp->retries >= AU_RETRIES)) {
941                         /* reuse the buffer */
942                         err ("control read: transmission error %d, can not retry", urb->status);
943                         auerbuf_releasebuf (bp);
944                         /* Wake up all processes waiting for a buffer */
945                         wake_up (&cp->bufferwait);
946                         return;
947                 }
948                 bp->retries++;
949                 dbg ("Retry count = %d", bp->retries);
950                 /* send a long dummy control-write-message to allow device firmware to react */
951                 bp->dr->bRequestType = AUT_WREQ;
952                 bp->dr->bRequest     = AUV_DUMMY;
953                 bp->dr->wValue       = bp->dr->wLength; /* temporary storage */
954                 // bp->dr->wIndex    channel ID remains
955                 bp->dr->wLength      = cpu_to_le16 (32); /* >= 8 bytes */
956                 usb_fill_control_urb (bp->urbp, cp->usbdev, usb_sndctrlpipe (cp->usbdev, 0),
957                         (unsigned char*)bp->dr, bp->bufp, 32,
958                         auerswald_ctrlread_wretcomplete,bp);
959
960                 /* submit the control msg as next paket */
961                 ret = auerchain_submit_urb_list (&cp->controlchain, bp->urbp, 1);
962                 if (ret) {
963                         dbg ("auerswald_ctrlread_complete: nonzero result of auerchain_submit_urb_list %d", ret);
964                         bp->urbp->status = ret;
965                         auerswald_ctrlread_wretcomplete (bp->urbp, regs);
966                 }
967                 return;
968         }
969
970         /* get the actual bytecount (incl. headerbyte) */
971         bp->len = urb->actual_length;
972         serviceid = bp->bufp[0] & AUH_TYPEMASK;
973         dbg ("Paket with serviceid %d and %d bytes received", serviceid, bp->len);
974
975         /* dispatch the paket */
976         scp = cp->services[serviceid];
977         if (scp) {
978                 /* look, Ma, a listener! */
979                 scp->dispatch (scp, bp);
980         }
981
982         /* release the paket */
983         auerbuf_releasebuf (bp);
984         /* Wake up all processes waiting for a buffer */
985         wake_up (&cp->bufferwait);
986 }
987
988 /*-------------------------------------------------------------------*/
989 /* Handling of Interrupt Endpoint                                    */
990 /* This interrupt Endpoint is used to inform the host about waiting
991    messages from the USB device.
992 */
993 /* int completion handler. */
994 static void auerswald_int_complete (struct urb * urb, struct pt_regs *regs)
995 {
996         unsigned long flags;
997         unsigned  int channelid;
998         unsigned  int bytecount;
999         int ret;
1000         pauerbuf_t   bp = NULL;
1001         pauerswald_t cp = (pauerswald_t) urb->context;
1002
1003         dbg ("%s called", __FUNCTION__);
1004
1005         switch (urb->status) {
1006         case 0:
1007                 /* success */
1008                 break;
1009         case -ECONNRESET:
1010         case -ENOENT:
1011         case -ESHUTDOWN:
1012                 /* this urb is terminated, clean up */
1013                 dbg("%s - urb shutting down with status: %d", __FUNCTION__, urb->status);
1014                 return;
1015         default:
1016                 dbg("%s - nonzero urb status received: %d", __FUNCTION__, urb->status);
1017                 goto exit;
1018         }
1019
1020         /* check if all needed data was received */
1021         if (urb->actual_length < AU_IRQMINSIZE) {
1022                 dbg ("invalid data length received: %d bytes", urb->actual_length);
1023                 goto exit;
1024         }
1025
1026         /* check the command code */
1027         if (cp->intbufp[0] != AU_IRQCMDID) {
1028                 dbg ("invalid command received: %d", cp->intbufp[0]);
1029                 goto exit;
1030         }
1031
1032         /* check the command type */
1033         if (cp->intbufp[1] != AU_BLOCKRDY) {
1034                 dbg ("invalid command type received: %d", cp->intbufp[1]);
1035                 goto exit;
1036         }
1037
1038         /* now extract the information */
1039         channelid = cp->intbufp[2];
1040         bytecount = le16_to_cpup (&cp->intbufp[3]);
1041
1042         /* check the channel id */
1043         if (channelid >= AUH_TYPESIZE) {
1044                 dbg ("invalid channel id received: %d", channelid);
1045                 goto exit;
1046         }
1047
1048         /* check the byte count */
1049         if (bytecount > (cp->maxControlLength+AUH_SIZE)) {
1050                 dbg ("invalid byte count received: %d", bytecount);
1051                 goto exit;
1052         }
1053         dbg ("Service Channel = %d", channelid);
1054         dbg ("Byte Count = %d", bytecount);
1055
1056         /* get a buffer for the next data paket */
1057         spin_lock_irqsave (&cp->bufctl.lock, flags);
1058         if (!list_empty (&cp->bufctl.free_buff_list)) {
1059                 /* yes: get the entry */
1060                 struct list_head *tmp = cp->bufctl.free_buff_list.next;
1061                 list_del (tmp);
1062                 bp = list_entry (tmp, auerbuf_t, buff_list);
1063         }
1064         spin_unlock_irqrestore (&cp->bufctl.lock, flags);
1065
1066         /* if no buffer available: skip it */
1067         if (!bp) {
1068                 dbg ("auerswald_int_complete: no data buffer available");
1069                 /* can we do something more?
1070                    This is a big problem: if this int packet is ignored, the
1071                    device will wait forever and not signal any more data.
1072                    The only real solution is: having enough buffers!
1073                    Or perhaps temporary disabling the int endpoint?
1074                 */
1075                 goto exit;
1076         }
1077
1078         /* fill the control message */
1079         bp->dr->bRequestType = AUT_RREQ;
1080         bp->dr->bRequest     = AUV_RBLOCK;
1081         bp->dr->wValue       = cpu_to_le16 (0);
1082         bp->dr->wIndex       = cpu_to_le16 (channelid | AUH_DIRECT | AUH_UNSPLIT);
1083         bp->dr->wLength      = cpu_to_le16 (bytecount);
1084         usb_fill_control_urb (bp->urbp, cp->usbdev, usb_rcvctrlpipe (cp->usbdev, 0),
1085                           (unsigned char*)bp->dr, bp->bufp, bytecount,
1086                           auerswald_ctrlread_complete,bp);
1087
1088         /* submit the control msg */
1089         ret = auerchain_submit_urb (&cp->controlchain, bp->urbp);
1090         if (ret) {
1091                 dbg ("auerswald_int_complete: nonzero result of auerchain_submit_urb %d", ret);
1092                 bp->urbp->status = ret;
1093                 auerswald_ctrlread_complete( bp->urbp, NULL);
1094                 /* here applies the same problem as above: device locking! */
1095         }
1096 exit:
1097         ret = usb_submit_urb (urb, GFP_ATOMIC);
1098         if (ret)
1099                 err ("%s - usb_submit_urb failed with result %d",
1100                      __FUNCTION__, ret);
1101 }
1102
1103 /* int memory deallocation
1104    NOTE: no mutex please!
1105 */
1106 static void auerswald_int_free (pauerswald_t cp)
1107 {
1108         if (cp->inturbp) {
1109                 usb_free_urb (cp->inturbp);
1110                 cp->inturbp = NULL;
1111         }
1112         if (cp->intbufp) {
1113                 kfree (cp->intbufp);
1114                 cp->intbufp = NULL;
1115         }
1116 }
1117
1118 /* This function is called to activate the interrupt
1119    endpoint. This function returns 0 if successful or an error code.
1120    NOTE: no mutex please!
1121 */
1122 static int auerswald_int_open (pauerswald_t cp)
1123 {
1124         int ret;
1125         struct usb_endpoint_descriptor *ep;
1126         int irqsize;
1127         dbg ("auerswald_int_open");
1128
1129         ep = usb_epnum_to_ep_desc (cp->usbdev, USB_DIR_IN | AU_IRQENDP);
1130         if (!ep) {
1131                 ret = -EFAULT;
1132                 goto intoend;
1133         }
1134         irqsize = ep->wMaxPacketSize;
1135         cp->irqsize = irqsize;
1136
1137         /* allocate the urb and data buffer */
1138         if (!cp->inturbp) {
1139                 cp->inturbp = usb_alloc_urb (0, GFP_KERNEL);
1140                 if (!cp->inturbp) {
1141                         ret = -ENOMEM;
1142                         goto intoend;
1143                 }
1144         }
1145         if (!cp->intbufp) {
1146                 cp->intbufp = (char *) kmalloc (irqsize, GFP_KERNEL);
1147                 if (!cp->intbufp) {
1148                         ret = -ENOMEM;
1149                         goto intoend;
1150                 }
1151         }
1152         /* setup urb */
1153         usb_fill_int_urb (cp->inturbp, cp->usbdev, usb_rcvintpipe (cp->usbdev,AU_IRQENDP), cp->intbufp, irqsize, auerswald_int_complete, cp, ep->bInterval);
1154         /* start the urb */
1155         cp->inturbp->status = 0;        /* needed! */
1156         ret = usb_submit_urb (cp->inturbp, GFP_KERNEL);
1157
1158 intoend:
1159         if (ret < 0) {
1160                 /* activation of interrupt endpoint has failed. Now clean up. */
1161                 dbg ("auerswald_int_open: activation of int endpoint failed");
1162
1163                 /* deallocate memory */
1164                 auerswald_int_free (cp);
1165         }
1166         return ret;
1167 }
1168
1169 /* This function is called to deactivate the interrupt
1170    endpoint. This function returns 0 if successful or an error code.
1171    NOTE: no mutex please!
1172 */
1173 static int auerswald_int_release (pauerswald_t cp)
1174 {
1175         int ret = 0;
1176         dbg ("auerswald_int_release");
1177
1178         /* stop the int endpoint */
1179         if (cp->inturbp) {
1180                 ret = usb_unlink_urb (cp->inturbp);
1181                 if (ret)
1182                         dbg ("nonzero int unlink result received: %d", ret);
1183         }
1184
1185         /* deallocate memory */
1186         auerswald_int_free (cp);
1187
1188         return ret;
1189 }
1190
1191 /* --------------------------------------------------------------------- */
1192 /* Helper functions                                                      */
1193
1194 /* wake up waiting readers */
1195 static void auerchar_disconnect (pauerscon_t scp)
1196 {
1197         pauerchar_t ccp = ((pauerchar_t)((char *)(scp)-(unsigned long)(&((pauerchar_t)0)->scontext)));
1198         dbg ("auerchar_disconnect called");
1199         ccp->removed = 1;
1200         wake_up (&ccp->readwait);
1201 }
1202
1203
1204 /* dispatch a read paket to a waiting character device */
1205 static void auerchar_ctrlread_dispatch (pauerscon_t scp, pauerbuf_t bp)
1206 {
1207         unsigned long flags;
1208         pauerchar_t ccp;
1209         pauerbuf_t newbp = NULL;
1210         char * charp;
1211         dbg ("auerchar_ctrlread_dispatch called");
1212         ccp = ((pauerchar_t)((char *)(scp)-(unsigned long)(&((pauerchar_t)0)->scontext)));
1213
1214         /* get a read buffer from character device context */
1215         spin_lock_irqsave (&ccp->bufctl.lock, flags);
1216         if (!list_empty (&ccp->bufctl.free_buff_list)) {
1217                 /* yes: get the entry */
1218                 struct list_head *tmp = ccp->bufctl.free_buff_list.next;
1219                 list_del (tmp);
1220                 newbp = list_entry (tmp, auerbuf_t, buff_list);
1221         }
1222         spin_unlock_irqrestore (&ccp->bufctl.lock, flags);
1223
1224         if (!newbp) {
1225                 dbg ("No read buffer available, discard paket!");
1226                 return;     /* no buffer, no dispatch */
1227         }
1228
1229         /* copy information to new buffer element
1230            (all buffers have the same length) */
1231         charp = newbp->bufp;
1232         newbp->bufp = bp->bufp;
1233         bp->bufp = charp;
1234         newbp->len = bp->len;
1235
1236         /* insert new buffer in read list */
1237         spin_lock_irqsave (&ccp->bufctl.lock, flags);
1238         list_add_tail (&newbp->buff_list, &ccp->bufctl.rec_buff_list);
1239         spin_unlock_irqrestore (&ccp->bufctl.lock, flags);
1240         dbg ("read buffer appended to rec_list");
1241
1242         /* wake up pending synchronous reads */
1243         wake_up (&ccp->readwait);
1244 }
1245
1246
1247 /* Delete an auerswald driver context */
1248 static void auerswald_delete( pauerswald_t cp)
1249 {
1250         dbg( "auerswald_delete");
1251         if (cp == NULL)
1252                 return;
1253
1254         /* Wake up all processes waiting for a buffer */
1255         wake_up (&cp->bufferwait);
1256
1257         /* Cleaning up */
1258         auerswald_int_release (cp);
1259         auerchain_free (&cp->controlchain);
1260         auerbuf_free_buffers (&cp->bufctl);
1261
1262         /* release the memory */
1263         kfree( cp);
1264 }
1265
1266
1267 /* Delete an auerswald character context */
1268 static void auerchar_delete( pauerchar_t ccp)
1269 {
1270         dbg ("auerchar_delete");
1271         if (ccp == NULL)
1272                 return;
1273
1274         /* wake up pending synchronous reads */
1275         ccp->removed = 1;
1276         wake_up (&ccp->readwait);
1277
1278         /* remove the read buffer */
1279         if (ccp->readbuf) {
1280                 auerbuf_releasebuf (ccp->readbuf);
1281                 ccp->readbuf = NULL;
1282         }
1283
1284         /* remove the character buffers */
1285         auerbuf_free_buffers (&ccp->bufctl);
1286
1287         /* release the memory */
1288         kfree( ccp);
1289 }
1290
1291
1292 /* add a new service to the device
1293    scp->id must be set!
1294    return: 0 if OK, else error code
1295 */
1296 static int auerswald_addservice (pauerswald_t cp, pauerscon_t scp)
1297 {
1298         int ret;
1299
1300         /* is the device available? */
1301         if (!cp->usbdev) {
1302                 dbg ("usbdev == NULL");
1303                 return -EIO;    /*no: can not add a service, sorry*/
1304         }
1305
1306         /* is the service available? */
1307         if (cp->services[scp->id]) {
1308                 dbg ("service is busy");
1309                 return -EBUSY;
1310         }
1311
1312         /* device is available, service is free */
1313         cp->services[scp->id] = scp;
1314
1315         /* register service in device */
1316         ret = auerchain_control_msg(
1317                 &cp->controlchain,                      /* pointer to control chain */
1318                 cp->usbdev,                             /* pointer to device */
1319                 usb_sndctrlpipe (cp->usbdev, 0),        /* pipe to control endpoint */
1320                 AUV_CHANNELCTL,                         /* USB message request value */
1321                 AUT_WREQ,                               /* USB message request type value */
1322                 0x01,              /* open                 USB message value */
1323                 scp->id,                                /* USB message index value */
1324                 NULL,                                   /* pointer to the data to send */
1325                 0,                                      /* length in bytes of the data to send */
1326                 HZ * 2);                                /* time to wait for the message to complete before timing out */
1327         if (ret < 0) {
1328                 dbg ("auerswald_addservice: auerchain_control_msg returned error code %d", ret);
1329                 /* undo above actions */
1330                 cp->services[scp->id] = NULL;
1331                 return ret;
1332         }
1333
1334         dbg ("auerswald_addservice: channel open OK");
1335         return 0;
1336 }
1337
1338
1339 /* remove a service from the the device
1340    scp->id must be set! */
1341 static void auerswald_removeservice (pauerswald_t cp, pauerscon_t scp)
1342 {
1343         dbg ("auerswald_removeservice called");
1344
1345         /* check if we have a service allocated */
1346         if (scp->id == AUH_UNASSIGNED)
1347                 return;
1348
1349         /* If there is a device: close the channel */
1350         if (cp->usbdev) {
1351                 /* Close the service channel inside the device */
1352                 int ret = auerchain_control_msg(
1353                 &cp->controlchain,                      /* pointer to control chain */
1354                 cp->usbdev,                             /* pointer to device */
1355                 usb_sndctrlpipe (cp->usbdev, 0),        /* pipe to control endpoint */
1356                 AUV_CHANNELCTL,                         /* USB message request value */
1357                 AUT_WREQ,                               /* USB message request type value */
1358                 0x00,              // close             /* USB message value */
1359                 scp->id,                                /* USB message index value */
1360                 NULL,                                   /* pointer to the data to send */
1361                 0,                                      /* length in bytes of the data to send */
1362                 HZ * 2);                                /* time to wait for the message to complete before timing out */
1363                 if (ret < 0) {
1364                         dbg ("auerswald_removeservice: auerchain_control_msg returned error code %d", ret);
1365                 }
1366                 else {
1367                         dbg ("auerswald_removeservice: channel close OK");
1368                 }
1369         }
1370
1371         /* remove the service from the device */
1372         cp->services[scp->id] = NULL;
1373         scp->id = AUH_UNASSIGNED;
1374 }
1375
1376
1377 /* --------------------------------------------------------------------- */
1378 /* Char device functions                                                 */
1379
1380 /* Open a new character device */
1381 static int auerchar_open (struct inode *inode, struct file *file)
1382 {
1383         int dtindex = iminor(inode);
1384         pauerswald_t cp = NULL;
1385         pauerchar_t ccp = NULL;
1386         struct usb_interface *intf;
1387         int ret;
1388
1389         /* minor number in range? */
1390         if (dtindex < 0) {
1391                 return -ENODEV;
1392         }
1393         intf = usb_find_interface(&auerswald_driver, dtindex);
1394         if (!intf) {
1395                 return -ENODEV;
1396         }
1397
1398         /* usb device available? */
1399         cp = usb_get_intfdata (intf);
1400         if (cp == NULL) {
1401                 return -ENODEV;
1402         }
1403         if (down_interruptible (&cp->mutex)) {
1404                 return -ERESTARTSYS;
1405         }
1406
1407         /* we have access to the device. Now lets allocate memory */
1408         ccp = (pauerchar_t) kmalloc(sizeof(auerchar_t), GFP_KERNEL);
1409         if (ccp == NULL) {
1410                 err ("out of memory");
1411                 ret = -ENOMEM;
1412                 goto ofail;
1413         }
1414
1415         /* Initialize device descriptor */
1416         memset( ccp, 0, sizeof(auerchar_t));
1417         init_MUTEX( &ccp->mutex);
1418         init_MUTEX( &ccp->readmutex);
1419         auerbuf_init (&ccp->bufctl);
1420         ccp->scontext.id = AUH_UNASSIGNED;
1421         ccp->scontext.dispatch = auerchar_ctrlread_dispatch;
1422         ccp->scontext.disconnect = auerchar_disconnect;
1423         init_waitqueue_head (&ccp->readwait);
1424
1425         ret = auerbuf_setup (&ccp->bufctl, AU_RBUFFERS, cp->maxControlLength+AUH_SIZE);
1426         if (ret) {
1427                 goto ofail;
1428         }
1429
1430         cp->open_count++;
1431         ccp->auerdev = cp;
1432         dbg("open %s as /dev/%s", cp->dev_desc, cp->name);
1433         up (&cp->mutex);
1434
1435         /* file IO stuff */
1436         file->f_pos = 0;
1437         file->private_data = ccp;
1438         return nonseekable_open(inode, file);
1439
1440         /* Error exit */
1441 ofail:  up (&cp->mutex);
1442         auerchar_delete (ccp);
1443         return ret;
1444 }
1445
1446
1447 /* IOCTL functions */
1448 static int auerchar_ioctl (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
1449 {
1450         pauerchar_t ccp = (pauerchar_t) file->private_data;
1451         int ret = 0;
1452         audevinfo_t devinfo;
1453         pauerswald_t cp = NULL;
1454         unsigned int u;
1455         unsigned int __user *user_arg = (unsigned int __user *)arg;
1456
1457         dbg ("ioctl");
1458
1459         /* get the mutexes */
1460         if (down_interruptible (&ccp->mutex)) {
1461                 return -ERESTARTSYS;
1462         }
1463         cp = ccp->auerdev;
1464         if (!cp) {
1465                 up (&ccp->mutex);
1466                 return -ENODEV;
1467         }
1468         if (down_interruptible (&cp->mutex)) {
1469                 up(&ccp->mutex);
1470                 return -ERESTARTSYS;
1471         }
1472
1473         /* Check for removal */
1474         if (!cp->usbdev) {
1475                 up(&cp->mutex);
1476                 up(&ccp->mutex);
1477                 return -ENODEV;
1478         }
1479
1480         switch (cmd) {
1481
1482         /* return != 0 if Transmitt channel ready to send */
1483         case IOCTL_AU_TXREADY:
1484                 dbg ("IOCTL_AU_TXREADY");
1485                 u   = ccp->auerdev
1486                    && (ccp->scontext.id != AUH_UNASSIGNED)
1487                    && !list_empty (&cp->bufctl.free_buff_list);
1488                 ret = put_user (u, user_arg);
1489                 break;
1490
1491         /* return != 0 if connected to a service channel */
1492         case IOCTL_AU_CONNECT:
1493                 dbg ("IOCTL_AU_CONNECT");
1494                 u = (ccp->scontext.id != AUH_UNASSIGNED);
1495                 ret = put_user (u, user_arg);
1496                 break;
1497
1498         /* return != 0 if Receive Data available */
1499         case IOCTL_AU_RXAVAIL:
1500                 dbg ("IOCTL_AU_RXAVAIL");
1501                 if (ccp->scontext.id == AUH_UNASSIGNED) {
1502                         ret = -EIO;
1503                         break;
1504                 }
1505                 u = 0;  /* no data */
1506                 if (ccp->readbuf) {
1507                         int restlen = ccp->readbuf->len - ccp->readoffset;
1508                         if (restlen > 0)
1509                                 u = 1;
1510                 }
1511                 if (!u) {
1512                         if (!list_empty (&ccp->bufctl.rec_buff_list)) {
1513                                 u = 1;
1514                         }
1515                 }
1516                 ret = put_user (u, user_arg);
1517                 break;
1518
1519         /* return the max. buffer length for the device */
1520         case IOCTL_AU_BUFLEN:
1521                 dbg ("IOCTL_AU_BUFLEN");
1522                 u = cp->maxControlLength;
1523                 ret = put_user (u, user_arg);
1524                 break;
1525
1526         /* requesting a service channel */
1527         case IOCTL_AU_SERVREQ:
1528                 dbg ("IOCTL_AU_SERVREQ");
1529                 /* requesting a service means: release the previous one first */
1530                 auerswald_removeservice (cp, &ccp->scontext);
1531                 /* get the channel number */
1532                 ret = get_user (u, user_arg);
1533                 if (ret) {
1534                         break;
1535                 }
1536                 if ((u < AUH_FIRSTUSERCH) || (u >= AUH_TYPESIZE)) {
1537                         ret = -EIO;
1538                         break;
1539                 }
1540                 dbg ("auerchar service request parameters are ok");
1541                 ccp->scontext.id = u;
1542
1543                 /* request the service now */
1544                 ret = auerswald_addservice (cp, &ccp->scontext);
1545                 if (ret) {
1546                         /* no: revert service entry */
1547                         ccp->scontext.id = AUH_UNASSIGNED;
1548                 }
1549                 break;
1550
1551         /* get a string descriptor for the device */
1552         case IOCTL_AU_DEVINFO:
1553                 dbg ("IOCTL_AU_DEVINFO");
1554                 if (copy_from_user (&devinfo, (void __user *) arg, sizeof (audevinfo_t))) {
1555                         ret = -EFAULT;
1556                         break;
1557                 }
1558                 u = strlen(cp->dev_desc)+1;
1559                 if (u > devinfo.bsize) {
1560                         u = devinfo.bsize;
1561                 }
1562                 ret = copy_to_user(devinfo.buf, cp->dev_desc, u) ? -EFAULT : 0;
1563                 break;
1564
1565         /* get the max. string descriptor length */
1566         case IOCTL_AU_SLEN:
1567                 dbg ("IOCTL_AU_SLEN");
1568                 u = AUSI_DLEN;
1569                 ret = put_user (u, user_arg);
1570                 break;
1571
1572         default:
1573                 dbg ("IOCTL_AU_UNKNOWN");
1574                 ret = -ENOIOCTLCMD;
1575                 break;
1576         }
1577         /* release the mutexes */
1578         up(&cp->mutex);
1579         up(&ccp->mutex);
1580         return ret;
1581 }
1582
1583 /* Read data from the device */
1584 static ssize_t auerchar_read (struct file *file, char __user *buf, size_t count, loff_t * ppos)
1585 {
1586         unsigned long flags;
1587         pauerchar_t ccp = (pauerchar_t) file->private_data;
1588         pauerbuf_t   bp = NULL;
1589         wait_queue_t wait;
1590
1591         dbg ("auerchar_read");
1592
1593         /* Error checking */
1594         if (!ccp)
1595                 return -EIO;
1596         if (*ppos)
1597                 return -ESPIPE;
1598         if (count == 0)
1599                 return 0;
1600
1601         /* get the mutex */
1602         if (down_interruptible (&ccp->mutex))
1603                 return -ERESTARTSYS;
1604
1605         /* Can we expect to read something? */
1606         if (ccp->scontext.id == AUH_UNASSIGNED) {
1607                 up (&ccp->mutex);
1608                 return -EIO;
1609         }
1610
1611         /* only one reader per device allowed */
1612         if (down_interruptible (&ccp->readmutex)) {
1613                 up (&ccp->mutex);
1614                 return -ERESTARTSYS;
1615         }
1616
1617         /* read data from readbuf, if available */
1618 doreadbuf:
1619         bp = ccp->readbuf;
1620         if (bp) {
1621                 /* read the maximum bytes */
1622                 int restlen = bp->len - ccp->readoffset;
1623                 if (restlen < 0)
1624                         restlen = 0;
1625                 if (count > restlen)
1626                         count = restlen;
1627                 if (count) {
1628                         if (copy_to_user (buf, bp->bufp+ccp->readoffset, count)) {
1629                                 dbg ("auerswald_read: copy_to_user failed");
1630                                 up (&ccp->readmutex);
1631                                 up (&ccp->mutex);
1632                                 return -EFAULT;
1633                         }
1634                 }
1635                 /* advance the read offset */
1636                 ccp->readoffset += count;
1637                 restlen -= count;
1638                 // reuse the read buffer
1639                 if (restlen <= 0) {
1640                         auerbuf_releasebuf (bp);
1641                         ccp->readbuf = NULL;
1642                 }
1643                 /* return with number of bytes read */
1644                 if (count) {
1645                         up (&ccp->readmutex);
1646                         up (&ccp->mutex);
1647                         return count;
1648                 }
1649         }
1650
1651         /* a read buffer is not available. Try to get the next data block. */
1652 doreadlist:
1653         /* Preparing for sleep */
1654         init_waitqueue_entry (&wait, current);
1655         set_current_state (TASK_INTERRUPTIBLE);
1656         add_wait_queue (&ccp->readwait, &wait);
1657
1658         bp = NULL;
1659         spin_lock_irqsave (&ccp->bufctl.lock, flags);
1660         if (!list_empty (&ccp->bufctl.rec_buff_list)) {
1661                 /* yes: get the entry */
1662                 struct list_head *tmp = ccp->bufctl.rec_buff_list.next;
1663                 list_del (tmp);
1664                 bp = list_entry (tmp, auerbuf_t, buff_list);
1665         }
1666         spin_unlock_irqrestore (&ccp->bufctl.lock, flags);
1667
1668         /* have we got data? */
1669         if (bp) {
1670                 ccp->readbuf = bp;
1671                 ccp->readoffset = AUH_SIZE; /* for headerbyte */
1672                 set_current_state (TASK_RUNNING);
1673                 remove_wait_queue (&ccp->readwait, &wait);
1674                 goto doreadbuf;           /* now we can read! */
1675         }
1676
1677         /* no data available. Should we wait? */
1678         if (file->f_flags & O_NONBLOCK) {
1679                 dbg ("No read buffer available, returning -EAGAIN");
1680                 set_current_state (TASK_RUNNING);
1681                 remove_wait_queue (&ccp->readwait, &wait);
1682                 up (&ccp->readmutex);
1683                 up (&ccp->mutex);
1684                 return -EAGAIN;  /* nonblocking, no data available */
1685         }
1686
1687         /* yes, we should wait! */
1688         up (&ccp->mutex); /* allow other operations while we wait */
1689         schedule();
1690         remove_wait_queue (&ccp->readwait, &wait);
1691         if (signal_pending (current)) {
1692                 /* waked up by a signal */
1693                 up (&ccp->readmutex);
1694                 return -ERESTARTSYS;
1695         }
1696
1697         /* Anything left to read? */
1698         if ((ccp->scontext.id == AUH_UNASSIGNED) || ccp->removed) {
1699                 up (&ccp->readmutex);
1700                 return -EIO;
1701         }
1702
1703         if (down_interruptible (&ccp->mutex)) {
1704                 up (&ccp->readmutex);
1705                 return -ERESTARTSYS;
1706         }
1707
1708         /* try to read the incoming data again */
1709         goto doreadlist;
1710 }
1711
1712
1713 /* Write a data block into the right service channel of the device */
1714 static ssize_t auerchar_write (struct file *file, const char __user *buf, size_t len, loff_t *ppos)
1715 {
1716         pauerchar_t ccp = (pauerchar_t) file->private_data;
1717         pauerswald_t cp = NULL;
1718         pauerbuf_t bp;
1719         unsigned long flags;
1720         int ret;
1721         wait_queue_t wait;
1722
1723         dbg ("auerchar_write %d bytes", len);
1724
1725         /* Error checking */
1726         if (!ccp)
1727                 return -EIO;
1728         if (*ppos)
1729                 return -ESPIPE;
1730         if (len == 0)
1731                 return 0;
1732
1733 write_again:
1734         /* get the mutex */
1735         if (down_interruptible (&ccp->mutex))
1736                 return -ERESTARTSYS;
1737
1738         /* Can we expect to write something? */
1739         if (ccp->scontext.id == AUH_UNASSIGNED) {
1740                 up (&ccp->mutex);
1741                 return -EIO;
1742         }
1743
1744         cp = ccp->auerdev;
1745         if (!cp) {
1746                 up (&ccp->mutex);
1747                 return -ERESTARTSYS;
1748         }
1749         if (down_interruptible (&cp->mutex)) {
1750                 up (&ccp->mutex);
1751                 return -ERESTARTSYS;
1752         }
1753         if (!cp->usbdev) {
1754                 up (&cp->mutex);
1755                 up (&ccp->mutex);
1756                 return -EIO;
1757         }
1758         /* Prepare for sleep */
1759         init_waitqueue_entry (&wait, current);
1760         set_current_state (TASK_INTERRUPTIBLE);
1761         add_wait_queue (&cp->bufferwait, &wait);
1762
1763         /* Try to get a buffer from the device pool.
1764            We can't use a buffer from ccp->bufctl because the write
1765            command will last beond a release() */
1766         bp = NULL;
1767         spin_lock_irqsave (&cp->bufctl.lock, flags);
1768         if (!list_empty (&cp->bufctl.free_buff_list)) {
1769                 /* yes: get the entry */
1770                 struct list_head *tmp = cp->bufctl.free_buff_list.next;
1771                 list_del (tmp);
1772                 bp = list_entry (tmp, auerbuf_t, buff_list);
1773         }
1774         spin_unlock_irqrestore (&cp->bufctl.lock, flags);
1775
1776         /* are there any buffers left? */
1777         if (!bp) {
1778                 up (&cp->mutex);
1779                 up (&ccp->mutex);
1780
1781                 /* NONBLOCK: don't wait */
1782                 if (file->f_flags & O_NONBLOCK) {
1783                         set_current_state (TASK_RUNNING);
1784                         remove_wait_queue (&cp->bufferwait, &wait);
1785                         return -EAGAIN;
1786                 }
1787
1788                 /* BLOCKING: wait */
1789                 schedule();
1790                 remove_wait_queue (&cp->bufferwait, &wait);
1791                 if (signal_pending (current)) {
1792                         /* waked up by a signal */
1793                         return -ERESTARTSYS;
1794                 }
1795                 goto write_again;
1796         } else {
1797                 set_current_state (TASK_RUNNING);
1798                 remove_wait_queue (&cp->bufferwait, &wait);
1799         }
1800
1801         /* protect against too big write requests */
1802         if (len > cp->maxControlLength)
1803                 len = cp->maxControlLength;
1804
1805         /* Fill the buffer */
1806         if (copy_from_user ( bp->bufp+AUH_SIZE, buf, len)) {
1807                 dbg ("copy_from_user failed");
1808                 auerbuf_releasebuf (bp);
1809                 /* Wake up all processes waiting for a buffer */
1810                 wake_up (&cp->bufferwait);
1811                 up (&cp->mutex);
1812                 up (&ccp->mutex);
1813                 return -EFAULT;
1814         }
1815
1816         /* set the header byte */
1817         *(bp->bufp) = ccp->scontext.id | AUH_DIRECT | AUH_UNSPLIT;
1818
1819         /* Set the transfer Parameters */
1820         bp->len = len+AUH_SIZE;
1821         bp->dr->bRequestType = AUT_WREQ;
1822         bp->dr->bRequest     = AUV_WBLOCK;
1823         bp->dr->wValue       = cpu_to_le16 (0);
1824         bp->dr->wIndex       = cpu_to_le16 (ccp->scontext.id | AUH_DIRECT | AUH_UNSPLIT);
1825         bp->dr->wLength      = cpu_to_le16 (len+AUH_SIZE);
1826         usb_fill_control_urb (bp->urbp, cp->usbdev, usb_sndctrlpipe (cp->usbdev, 0),
1827                    (unsigned char*)bp->dr, bp->bufp, len+AUH_SIZE,
1828                     auerchar_ctrlwrite_complete, bp);
1829         /* up we go */
1830         ret = auerchain_submit_urb (&cp->controlchain, bp->urbp);
1831         up (&cp->mutex);
1832         if (ret) {
1833                 dbg ("auerchar_write: nonzero result of auerchain_submit_urb %d", ret);
1834                 auerbuf_releasebuf (bp);
1835                 /* Wake up all processes waiting for a buffer */
1836                 wake_up (&cp->bufferwait);
1837                 up (&ccp->mutex);
1838                 return -EIO;
1839         }
1840         else {
1841                 dbg ("auerchar_write: Write OK");
1842                 up (&ccp->mutex);
1843                 return len;
1844         }
1845 }
1846
1847
1848 /* Close a character device */
1849 static int auerchar_release (struct inode *inode, struct file *file)
1850 {
1851         pauerchar_t ccp = (pauerchar_t) file->private_data;
1852         pauerswald_t cp;
1853         dbg("release");
1854
1855         /* get the mutexes */
1856         if (down_interruptible (&ccp->mutex)) {
1857                 return -ERESTARTSYS;
1858         }
1859         cp = ccp->auerdev;
1860         if (cp) {
1861                 if (down_interruptible (&cp->mutex)) {
1862                         up (&ccp->mutex);
1863                         return -ERESTARTSYS;
1864                 }
1865                 /* remove an open service */
1866                 auerswald_removeservice (cp, &ccp->scontext);
1867                 /* detach from device */
1868                 if ((--cp->open_count <= 0) && (cp->usbdev == NULL)) {
1869                         /* usb device waits for removal */
1870                         up (&cp->mutex);
1871                         auerswald_delete (cp);
1872                 } else {
1873                         up (&cp->mutex);
1874                 }
1875                 cp = NULL;
1876                 ccp->auerdev = NULL;
1877         }
1878         up (&ccp->mutex);
1879         auerchar_delete (ccp);
1880
1881         return 0;
1882 }
1883
1884
1885 /*----------------------------------------------------------------------*/
1886 /* File operation structure                                             */
1887 static struct file_operations auerswald_fops =
1888 {
1889         .owner =        THIS_MODULE,
1890         .llseek =       no_llseek,
1891         .read =         auerchar_read,
1892         .write =        auerchar_write,
1893         .ioctl =        auerchar_ioctl,
1894         .open =         auerchar_open,
1895         .release =      auerchar_release,
1896 };
1897
1898 static struct usb_class_driver auerswald_class = {
1899         .name =         "usb/auer%d",
1900         .fops =         &auerswald_fops,
1901         .mode =         S_IFCHR | S_IRUGO | S_IWUGO,
1902         .minor_base =   AUER_MINOR_BASE,
1903 };
1904
1905
1906 /* --------------------------------------------------------------------- */
1907 /* Special USB driver functions                                          */
1908
1909 /* Probe if this driver wants to serve an USB device
1910
1911    This entry point is called whenever a new device is attached to the bus.
1912    Then the device driver has to create a new instance of its internal data
1913    structures for the new device.
1914
1915    The  dev argument specifies the device context, which contains pointers
1916    to all USB descriptors. The  interface argument specifies the interface
1917    number. If a USB driver wants to bind itself to a particular device and
1918    interface it has to return a pointer. This pointer normally references
1919    the device driver's context structure.
1920
1921    Probing normally is done by checking the vendor and product identifications
1922    or the class and subclass definitions. If they match the interface number
1923    is compared with the ones supported by the driver. When probing is done
1924    class based it might be necessary to parse some more USB descriptors because
1925    the device properties can differ in a wide range.
1926 */
1927 static int auerswald_probe (struct usb_interface *intf,
1928                             const struct usb_device_id *id)
1929 {
1930         struct usb_device *usbdev = interface_to_usbdev(intf);
1931         pauerswald_t cp = NULL;
1932         unsigned int u = 0;
1933         char *pbuf;
1934         int ret;
1935
1936         dbg ("probe: vendor id 0x%x, device id 0x%x",
1937              usbdev->descriptor.idVendor, usbdev->descriptor.idProduct);
1938
1939         /* See if the device offered us matches that we can accept */
1940         if (usbdev->descriptor.idVendor != ID_AUERSWALD)
1941                 return -ENODEV;
1942
1943         /* we use only the first -and only- interface */
1944         if (intf->altsetting->desc.bInterfaceNumber != 0)
1945                 return -ENODEV;
1946
1947         /* allocate memory for our device and initialize it */
1948         cp = kmalloc (sizeof(auerswald_t), GFP_KERNEL);
1949         if (cp == NULL) {
1950                 err ("out of memory");
1951                 goto pfail;
1952         }
1953
1954         /* Initialize device descriptor */
1955         memset (cp, 0, sizeof(auerswald_t));
1956         init_MUTEX (&cp->mutex);
1957         cp->usbdev = usbdev;
1958         auerchain_init (&cp->controlchain);
1959         auerbuf_init (&cp->bufctl);
1960         init_waitqueue_head (&cp->bufferwait);
1961
1962         ret = usb_register_dev(intf, &auerswald_class);
1963         if (ret) {
1964                 err ("Not able to get a minor for this device.");
1965                 goto pfail;
1966         }
1967
1968         /* Give the device a name */
1969         sprintf (cp->name, "usb/auer%d", intf->minor);
1970
1971         /* Store the index */
1972         cp->dtindex = intf->minor;
1973
1974         /* Get the usb version of the device */
1975         cp->version = cp->usbdev->descriptor.bcdDevice;
1976         dbg ("Version is %X", cp->version);
1977
1978         /* allow some time to settle the device */
1979         set_current_state(TASK_UNINTERRUPTIBLE);
1980         schedule_timeout(HZ/3);
1981
1982         /* Try to get a suitable textual description of the device */
1983         /* Device name:*/
1984         ret = usb_string( cp->usbdev, AUSI_DEVICE, cp->dev_desc, AUSI_DLEN-1);
1985         if (ret >= 0) {
1986                 u += ret;
1987                 /* Append Serial Number */
1988                 memcpy(&cp->dev_desc[u], ",Ser# ", 6);
1989                 u += 6;
1990                 ret = usb_string( cp->usbdev, AUSI_SERIALNR, &cp->dev_desc[u], AUSI_DLEN-u-1);
1991                 if (ret >= 0) {
1992                         u += ret;
1993                         /* Append subscriber number */
1994                         memcpy(&cp->dev_desc[u], ", ", 2);
1995                         u += 2;
1996                         ret = usb_string( cp->usbdev, AUSI_MSN, &cp->dev_desc[u], AUSI_DLEN-u-1);
1997                         if (ret >= 0) {
1998                                 u += ret;
1999                         }
2000                 }
2001         }
2002         cp->dev_desc[u] = '\0';
2003         info("device is a %s", cp->dev_desc);
2004
2005         /* get the maximum allowed control transfer length */
2006         pbuf = (char *) kmalloc (2, GFP_KERNEL);    /* use an allocated buffer because of urb target */
2007         if (!pbuf) {
2008                 err( "out of memory");
2009                 goto pfail;
2010         }
2011         ret = usb_control_msg(cp->usbdev,           /* pointer to device */
2012                 usb_rcvctrlpipe( cp->usbdev, 0 ),   /* pipe to control endpoint */
2013                 AUV_GETINFO,                        /* USB message request value */
2014                 AUT_RREQ,                           /* USB message request type value */
2015                 0,                                  /* USB message value */
2016                 AUDI_MBCTRANS,                      /* USB message index value */
2017                 pbuf,                               /* pointer to the receive buffer */
2018                 2,                                  /* length of the buffer */
2019                 HZ * 2);                            /* time to wait for the message to complete before timing out */
2020         if (ret == 2) {
2021                 cp->maxControlLength = le16_to_cpup(pbuf);
2022                 kfree(pbuf);
2023                 dbg("setup: max. allowed control transfersize is %d bytes", cp->maxControlLength);
2024         } else {
2025                 kfree(pbuf);
2026                 err("setup: getting max. allowed control transfer length failed with error %d", ret);
2027                 goto pfail;
2028         }
2029
2030         /* allocate a chain for the control messages */
2031         if (auerchain_setup (&cp->controlchain, AUCH_ELEMENTS)) {
2032                 err ("out of memory");
2033                 goto pfail;
2034         }
2035
2036         /* allocate buffers for control messages */
2037         if (auerbuf_setup (&cp->bufctl, AU_RBUFFERS, cp->maxControlLength+AUH_SIZE)) {
2038                 err ("out of memory");
2039                 goto pfail;
2040         }
2041
2042         /* start the interrupt endpoint */
2043         if (auerswald_int_open (cp)) {
2044                 err ("int endpoint failed");
2045                 goto pfail;
2046         }
2047
2048         /* all OK */
2049         usb_set_intfdata (intf, cp);
2050         return 0;
2051
2052         /* Error exit: clean up the memory */
2053 pfail:  auerswald_delete (cp);
2054         return -EIO;
2055 }
2056
2057
2058 /* Disconnect driver from a served device
2059
2060    This function is called whenever a device which was served by this driver
2061    is disconnected.
2062
2063    The argument  dev specifies the device context and the  driver_context
2064    returns a pointer to the previously registered  driver_context of the
2065    probe function. After returning from the disconnect function the USB
2066    framework completely deallocates all data structures associated with
2067    this device. So especially the usb_device structure must not be used
2068    any longer by the usb driver.
2069 */
2070 static void auerswald_disconnect (struct usb_interface *intf)
2071 {
2072         pauerswald_t cp = usb_get_intfdata (intf);
2073         unsigned int u;
2074
2075         usb_set_intfdata (intf, NULL);
2076         if (!cp)
2077                 return;
2078
2079         down (&cp->mutex);
2080         info ("device /dev/%s now disconnecting", cp->name);
2081
2082         /* give back our USB minor number */
2083         usb_deregister_dev(intf, &auerswald_class);
2084
2085         /* Stop the interrupt endpoint */
2086         auerswald_int_release (cp);
2087
2088         /* remove the control chain allocated in auerswald_probe
2089            This has the benefit of
2090            a) all pending (a)synchronous urbs are unlinked
2091            b) all buffers dealing with urbs are reclaimed
2092         */
2093         auerchain_free (&cp->controlchain);
2094
2095         if (cp->open_count == 0) {
2096                 /* nobody is using this device. So we can clean up now */
2097                 up (&cp->mutex);/* up() is possible here because no other task
2098                                    can open the device (see above). I don't want
2099                                    to kfree() a locked mutex. */
2100                 auerswald_delete (cp);
2101         } else {
2102                 /* device is used. Remove the pointer to the
2103                    usb device (it's not valid any more). The last
2104                    release() will do the clean up */
2105                 cp->usbdev = NULL;
2106                 up (&cp->mutex);
2107                 /* Terminate waiting writers */
2108                 wake_up (&cp->bufferwait);
2109                 /* Inform all waiting readers */
2110                 for ( u = 0; u < AUH_TYPESIZE; u++) {
2111                         pauerscon_t scp = cp->services[u];
2112                         if (scp)
2113                                 scp->disconnect( scp);
2114                 }
2115         }
2116 }
2117
2118 /* Descriptor for the devices which are served by this driver.
2119    NOTE: this struct is parsed by the usbmanager install scripts.
2120          Don't change without caution!
2121 */
2122 static struct usb_device_id auerswald_ids [] = {
2123         { USB_DEVICE (ID_AUERSWALD, 0x00C0) },          /* COMpact 2104 USB */
2124         { USB_DEVICE (ID_AUERSWALD, 0x00DB) },          /* COMpact 4410/2206 USB */
2125         { USB_DEVICE (ID_AUERSWALD, 0x00F1) },          /* Comfort 2000 System Telephone */
2126         { USB_DEVICE (ID_AUERSWALD, 0x00F2) },          /* Comfort 1200 System Telephone */
2127         { }                                             /* Terminating entry */
2128 };
2129
2130 /* Standard module device table */
2131 MODULE_DEVICE_TABLE (usb, auerswald_ids);
2132
2133 /* Standard usb driver struct */
2134 static struct usb_driver auerswald_driver = {
2135         .owner =        THIS_MODULE,
2136         .name =         "auerswald",
2137         .probe =        auerswald_probe,
2138         .disconnect =   auerswald_disconnect,
2139         .id_table =     auerswald_ids,
2140 };
2141
2142
2143 /* --------------------------------------------------------------------- */
2144 /* Module loading/unloading                                              */
2145
2146 /* Driver initialisation. Called after module loading.
2147    NOTE: there is no concurrency at _init
2148 */
2149 static int __init auerswald_init (void)
2150 {
2151         int result;
2152         dbg ("init");
2153
2154         /* register driver at the USB subsystem */
2155         result = usb_register (&auerswald_driver);
2156         if (result < 0) {
2157                 err ("driver could not be registered");
2158                 return -1;
2159         }
2160         return 0;
2161 }
2162
2163 /* Driver deinit. Called before module removal.
2164    NOTE: there is no concurrency at _cleanup
2165 */
2166 static void __exit auerswald_cleanup (void)
2167 {
2168         dbg ("cleanup");
2169         usb_deregister (&auerswald_driver);
2170 }
2171
2172 /* --------------------------------------------------------------------- */
2173 /* Linux device driver module description                                */
2174
2175 MODULE_AUTHOR (DRIVER_AUTHOR);
2176 MODULE_DESCRIPTION (DRIVER_DESC);
2177 MODULE_LICENSE ("GPL");
2178
2179 module_init (auerswald_init);
2180 module_exit (auerswald_cleanup);
2181
2182 /* --------------------------------------------------------------------- */
2183