upgrade to linux 2.6.10-1.12_FC2
[linux-2.6.git] / drivers / net / irda / stir4200.c
1 /*****************************************************************************
2 *
3 * Filename:      stir4200.c
4 * Version:       0.4
5 * Description:   Irda SigmaTel USB Dongle
6 * Status:        Experimental
7 * Author:        Stephen Hemminger <shemminger@osdl.org>
8 *
9 *       Based on earlier driver by Paul Stewart <stewart@parc.com>
10 *
11 *       Copyright (C) 2000, Roman Weissgaerber <weissg@vienna.at>
12 *       Copyright (C) 2001, Dag Brattli <dag@brattli.net>
13 *       Copyright (C) 2001, Jean Tourrilhes <jt@hpl.hp.com>
14 *       Copyright (C) 2004, Stephen Hemminger <shemminger@osdl.org>
15 *
16 *       This program is free software; you can redistribute it and/or modify
17 *       it under the terms of the GNU General Public License as published by
18 *       the Free Software Foundation; either version 2 of the License, or
19 *       (at your option) any later version.
20 *
21 *       This program is distributed in the hope that it will be useful,
22 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
23 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 *       GNU General Public License for more details.
25 *
26 *       You should have received a copy of the GNU General Public License
27 *       along with this program; if not, write to the Free Software
28 *       Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 *
30 *****************************************************************************/
31
32 /*
33  * This dongle does no framing, and requires polling to receive the
34  * data.  The STIr4200 has bulk in and out endpoints just like
35  * usr-irda devices, but the data it sends and receives is raw; like
36  * irtty, it needs to call the wrap and unwrap functions to add and
37  * remove SOF/BOF and escape characters to/from the frame.
38  */
39
40 #include <linux/module.h>
41 #include <linux/moduleparam.h>
42
43 #include <linux/kernel.h>
44 #include <linux/types.h>
45 #include <linux/init.h>
46 #include <linux/time.h>
47 #include <linux/skbuff.h>
48 #include <linux/netdevice.h>
49 #include <linux/suspend.h>
50 #include <linux/slab.h>
51 #include <linux/delay.h>
52 #include <linux/usb.h>
53 #include <linux/crc32.h>
54 #include <net/irda/irda.h>
55 #include <net/irda/irlap.h>
56 #include <net/irda/irda_device.h>
57 #include <net/irda/wrapper.h>
58 #include <net/irda/crc.h>
59 #include <asm/byteorder.h>
60 #include <asm/unaligned.h>
61
62 MODULE_AUTHOR("Stephen Hemminger <shemminger@osdl.org>");
63 MODULE_DESCRIPTION("IrDA-USB Dongle Driver for SigmaTel STIr4200");
64 MODULE_LICENSE("GPL");
65
66 static int qos_mtt_bits = 0x07; /* 1 ms or more */
67 module_param(qos_mtt_bits, int, 0);
68 MODULE_PARM_DESC(qos_mtt_bits, "Minimum Turn Time");
69
70 static int rx_sensitivity = 1;  /* FIR 0..4, SIR 0..6 */
71 module_param(rx_sensitivity, int, 0);
72 MODULE_PARM_DESC(rx_sensitivity, "Set Receiver sensitivity (0-6, 0 is most sensitive)");
73
74 static int tx_power = 0;        /* 0 = highest ... 3 = lowest */
75 module_param(tx_power, int, 0);
76 MODULE_PARM_DESC(tx_power, "Set Transmitter power (0-3, 0 is highest power)");
77
78 #define STIR_IRDA_HEADER        4
79 #define CTRL_TIMEOUT            100        /* milliseconds */
80 #define TRANSMIT_TIMEOUT        200        /* milliseconds */
81 #define STIR_FIFO_SIZE          4096
82 #define FIFO_REGS_SIZE          3
83
84 enum FirChars {
85         FIR_CE   = 0x7d,
86         FIR_XBOF = 0x7f,
87         FIR_EOF  = 0x7e,
88 };
89
90 enum StirRequests {
91         REQ_WRITE_REG =         0x00,
92         REQ_READ_REG =          0x01,
93         REQ_READ_ROM =          0x02,
94         REQ_WRITE_SINGLE =      0x03,
95 };
96
97 /* Register offsets */
98 enum StirRegs {
99         REG_RSVD=0,
100         REG_MODE,
101         REG_PDCLK,
102         REG_CTRL1,
103         REG_CTRL2,
104         REG_FIFOCTL,
105         REG_FIFOLSB,
106         REG_FIFOMSB,
107         REG_DPLL,
108         REG_IRDIG,
109         REG_TEST=15,
110 };
111
112 enum StirModeMask {
113         MODE_FIR = 0x80,
114         MODE_SIR = 0x20,
115         MODE_ASK = 0x10,
116         MODE_FASTRX = 0x08,
117         MODE_FFRSTEN = 0x04,
118         MODE_NRESET = 0x02,
119         MODE_2400 = 0x01,
120 };
121
122 enum StirPdclkMask {
123         PDCLK_4000000 = 0x02,
124         PDCLK_115200 = 0x09,
125         PDCLK_57600 = 0x13,
126         PDCLK_38400 = 0x1D,
127         PDCLK_19200 = 0x3B,
128         PDCLK_9600 = 0x77,
129         PDCLK_2400 = 0xDF,
130 };
131
132 enum StirCtrl1Mask {
133         CTRL1_SDMODE = 0x80,
134         CTRL1_RXSLOW = 0x40,
135         CTRL1_TXPWD = 0x10,
136         CTRL1_RXPWD = 0x08,
137         CTRL1_SRESET = 0x01,
138 };
139
140 enum StirCtrl2Mask {
141         CTRL2_SPWIDTH = 0x08,
142         CTRL2_REVID = 0x03,
143 };
144
145 enum StirFifoCtlMask {
146         FIFOCTL_EOF = 0x80,
147         FIFOCTL_UNDER = 0x40,
148         FIFOCTL_OVER = 0x20,
149         FIFOCTL_DIR = 0x10,
150         FIFOCTL_CLR = 0x08,
151         FIFOCTL_EMPTY = 0x04,
152         FIFOCTL_RXERR = 0x02,
153         FIFOCTL_TXERR = 0x01,
154 };
155
156 enum StirDiagMask {
157         IRDIG_RXHIGH = 0x80,
158         IRDIG_RXLOW = 0x40,
159 };
160
161 enum StirTestMask {
162         TEST_PLLDOWN = 0x80,
163         TEST_LOOPIR = 0x40,
164         TEST_LOOPUSB = 0x20,
165         TEST_TSTENA = 0x10,
166         TEST_TSTOSC = 0x0F,
167 };
168
169 struct stir_cb {
170         struct usb_device *usbdev;      /* init: probe_irda */
171         struct net_device *netdev;      /* network layer */
172         struct irlap_cb   *irlap;       /* The link layer we are binded to */
173         struct net_device_stats stats;  /* network statistics */
174         struct qos_info   qos;
175         unsigned          speed;        /* Current speed */
176
177         wait_queue_head_t thr_wait;     /* transmit thread wakeup */
178         struct completion thr_exited;
179         pid_t             thr_pid;
180
181         struct sk_buff    *tx_pending;
182         void              *io_buf;      /* transmit/receive buffer */
183         __u8              *fifo_status;
184
185         iobuff_t          rx_buff;      /* receive unwrap state machine */
186         struct timeval    rx_time;
187         int               receiving;
188         struct urb       *rx_urb;
189 };
190
191
192 /* These are the currently known USB ids */
193 static struct usb_device_id dongles[] = {
194     /* SigmaTel, Inc,  STIr4200 IrDA/USB Bridge */
195     { USB_DEVICE(0x066f, 0x4200) },
196     { }
197 };
198
199 MODULE_DEVICE_TABLE(usb, dongles);
200
201 /* Send control message to set dongle register */
202 static int write_reg(struct stir_cb *stir, __u16 reg, __u8 value)
203 {
204         struct usb_device *dev = stir->usbdev;
205
206         pr_debug("%s: write reg %d = 0x%x\n",
207                  stir->netdev->name, reg, value);
208         return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
209                                REQ_WRITE_SINGLE,
210                                USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_DEVICE,
211                                value, reg, NULL, 0,
212                                msecs_to_jiffies(CTRL_TIMEOUT));
213 }
214
215 /* Send control message to read multiple registers */
216 static inline int read_reg(struct stir_cb *stir, __u16 reg,
217                     __u8 *data, __u16 count)
218 {
219         struct usb_device *dev = stir->usbdev;
220
221         return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
222                                REQ_READ_REG,
223                                USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
224                                0, reg, data, count,
225                                msecs_to_jiffies(CTRL_TIMEOUT));
226 }
227
228 static inline int isfir(u32 speed)
229 {
230         return (speed == 4000000);
231 }
232
233 /*
234  * Prepare a FIR IrDA frame for transmission to the USB dongle.  The
235  * FIR transmit frame is documented in the datasheet.  It consists of
236  * a two byte 0x55 0xAA sequence, two little-endian length bytes, a
237  * sequence of exactly 16 XBOF bytes of 0x7E, two BOF bytes of 0x7E,
238  * then the data escaped as follows:
239  *
240  *    0x7D -> 0x7D 0x5D
241  *    0x7E -> 0x7D 0x5E
242  *    0x7F -> 0x7D 0x5F
243  *
244  * Then, 4 bytes of little endian (stuffed) FCS follow, then two
245  * trailing EOF bytes of 0x7E.
246  */
247 static inline __u8 *stuff_fir(__u8 *p, __u8 c)
248 {
249         switch(c) {
250         case 0x7d:
251         case 0x7e:
252         case 0x7f:
253                 *p++ = 0x7d;
254                 c ^= IRDA_TRANS;
255                 /* fall through */
256         default:
257                 *p++ = c;
258         }
259         return p;
260 }
261
262 /* Take raw data in skb and put it wrapped into buf */
263 static unsigned wrap_fir_skb(const struct sk_buff *skb, __u8 *buf)
264 {
265         __u8 *ptr = buf;
266         __u32 fcs = ~(crc32_le(~0, skb->data, skb->len));
267         __u16 wraplen;
268         int i;
269
270         /* Header */
271         buf[0] = 0x55;
272         buf[1] = 0xAA;
273
274         ptr = buf + STIR_IRDA_HEADER;
275         memset(ptr, 0x7f, 16);
276         ptr += 16;
277
278         /* BOF */
279         *ptr++  = 0x7e;
280         *ptr++  = 0x7e;
281
282         /* Address / Control / Information */
283         for (i = 0; i < skb->len; i++)
284                 ptr = stuff_fir(ptr, skb->data[i]);
285
286         /* FCS */
287         ptr = stuff_fir(ptr, fcs & 0xff);
288         ptr = stuff_fir(ptr, (fcs >> 8) & 0xff);
289         ptr = stuff_fir(ptr, (fcs >> 16) & 0xff);
290         ptr = stuff_fir(ptr, (fcs >> 24) & 0xff);
291
292         /* EOFs */
293         *ptr++ = 0x7e;
294         *ptr++ = 0x7e;
295
296         /* Total length, minus the header */
297         wraplen = (ptr - buf) - STIR_IRDA_HEADER;
298         buf[2] = wraplen & 0xff;
299         buf[3] = (wraplen >> 8) & 0xff;
300
301         return wraplen + STIR_IRDA_HEADER;
302 }
303
304 static unsigned wrap_sir_skb(struct sk_buff *skb, __u8 *buf)
305 {
306         __u16 wraplen;
307
308         wraplen = async_wrap_skb(skb, buf + STIR_IRDA_HEADER,
309                                  STIR_FIFO_SIZE - STIR_IRDA_HEADER);
310         buf[0] = 0x55;
311         buf[1] = 0xAA;
312         buf[2] = wraplen & 0xff;
313         buf[3] = (wraplen >> 8) & 0xff;
314
315         return wraplen + STIR_IRDA_HEADER;
316 }
317
318 /*
319  * Frame is fully formed in the rx_buff so check crc
320  * and pass up to irlap
321  * setup for next receive
322  */
323 static void fir_eof(struct stir_cb *stir)
324 {
325         iobuff_t *rx_buff = &stir->rx_buff;
326         int len = rx_buff->len - 4;
327         struct sk_buff *skb, *nskb;
328         __u32 fcs;
329
330         if (unlikely(len <= 0)) {
331                 pr_debug("%s: short frame len %d\n",
332                          stir->netdev->name, len);
333
334                 ++stir->stats.rx_errors;
335                 ++stir->stats.rx_length_errors;
336                 return;
337         }
338
339         fcs = ~(crc32_le(~0, rx_buff->data, len));
340         if (fcs != le32_to_cpu(get_unaligned((u32 *)(rx_buff->data+len)))) {
341                 pr_debug("crc error calc 0x%x len %d\n", fcs, len);
342                 stir->stats.rx_errors++;
343                 stir->stats.rx_crc_errors++;
344                 return;
345         }
346
347         /* if frame is short then just copy it */
348         if (len < IRDA_RX_COPY_THRESHOLD) {
349                 nskb = dev_alloc_skb(len + 1);
350                 if (unlikely(!nskb)) {
351                         ++stir->stats.rx_dropped;
352                         return;
353                 }
354                 skb_reserve(nskb, 1);
355                 skb = nskb;
356                 memcpy(nskb->data, rx_buff->data, len);
357         } else {
358                 nskb = dev_alloc_skb(rx_buff->truesize);
359                 if (unlikely(!nskb)) {
360                         ++stir->stats.rx_dropped;
361                         return;
362                 }
363                 skb_reserve(nskb, 1);
364                 skb = rx_buff->skb;
365                 rx_buff->skb = nskb;
366                 rx_buff->head = nskb->data;
367         }
368
369         skb_put(skb, len);
370
371         skb->mac.raw  = skb->data;
372         skb->protocol = htons(ETH_P_IRDA);
373         skb->dev = stir->netdev;
374
375         netif_rx(skb);
376
377         stir->stats.rx_packets++;
378         stir->stats.rx_bytes += len;
379
380         rx_buff->data = rx_buff->head;
381         rx_buff->len = 0;
382 }
383
384 /* Unwrap FIR stuffed data and bump it to IrLAP */
385 static void stir_fir_chars(struct stir_cb *stir,
386                             const __u8 *bytes, int len)
387 {
388         iobuff_t *rx_buff = &stir->rx_buff;
389         int     i;
390
391         for (i = 0; i < len; i++) {
392                 __u8    byte = bytes[i];
393
394                 switch(rx_buff->state) {
395                 case OUTSIDE_FRAME:
396                         /* ignore garbage till start of frame */
397                         if (unlikely(byte != FIR_EOF))
398                                 continue;
399                         /* Now receiving frame */
400                         rx_buff->state = BEGIN_FRAME;
401
402                         /* Time to initialize receive buffer */
403                         rx_buff->data = rx_buff->head;
404                         rx_buff->len = 0;
405                         continue;
406
407                 case LINK_ESCAPE:
408                         if (byte == FIR_EOF) {
409                                 pr_debug("%s: got EOF after escape\n",
410                                          stir->netdev->name);
411                                 goto frame_error;
412                         }
413                         rx_buff->state = INSIDE_FRAME;
414                         byte ^= IRDA_TRANS;
415                         break;
416
417                 case BEGIN_FRAME:
418                         /* ignore multiple BOF/EOF */
419                         if (byte == FIR_EOF)
420                                 continue;
421                         rx_buff->state = INSIDE_FRAME;
422                         rx_buff->in_frame = TRUE;
423
424                         /* fall through */
425                 case INSIDE_FRAME:
426                         switch(byte) {
427                         case FIR_CE:
428                                 rx_buff->state = LINK_ESCAPE;
429                                 continue;
430                         case FIR_XBOF:
431                                 /* 0x7f is not used in this framing */
432                                 pr_debug("%s: got XBOF without escape\n",
433                                          stir->netdev->name);
434                                 goto frame_error;
435                         case FIR_EOF:
436                                 rx_buff->state = OUTSIDE_FRAME;
437                                 rx_buff->in_frame = FALSE;
438                                 fir_eof(stir);
439                                 continue;
440                         }
441                         break;
442                 }
443
444                 /* add byte to rx buffer */
445                 if (unlikely(rx_buff->len >= rx_buff->truesize)) {
446                         pr_debug("%s: fir frame exceeds %d\n",
447                                  stir->netdev->name, rx_buff->truesize);
448                         ++stir->stats.rx_over_errors;
449                         goto error_recovery;
450                 }
451
452                 rx_buff->data[rx_buff->len++] = byte;
453                 continue;
454
455         frame_error:
456                 ++stir->stats.rx_frame_errors;
457
458         error_recovery:
459                 ++stir->stats.rx_errors;
460                 rx_buff->state = OUTSIDE_FRAME;
461                 rx_buff->in_frame = FALSE;
462         }
463 }
464
465 /* Unwrap SIR stuffed data and bump it up to IrLAP */
466 static void stir_sir_chars(struct stir_cb *stir,
467                             const __u8 *bytes, int len)
468 {
469         int i;
470
471         for (i = 0; i < len; i++)
472                 async_unwrap_char(stir->netdev, &stir->stats,
473                                   &stir->rx_buff, bytes[i]);
474 }
475
476 static inline void unwrap_chars(struct stir_cb *stir,
477                                 const __u8 *bytes, int length)
478 {
479         if (isfir(stir->speed))
480                 stir_fir_chars(stir, bytes, length);
481         else
482                 stir_sir_chars(stir, bytes, length);
483 }
484
485 /* Mode parameters for each speed */
486 static const struct {
487         unsigned speed;
488         __u8 pdclk;
489 } stir_modes[] = {
490         { 2400,    PDCLK_2400 },
491         { 9600,    PDCLK_9600 },
492         { 19200,   PDCLK_19200 },
493         { 38400,   PDCLK_38400 },
494         { 57600,   PDCLK_57600 },
495         { 115200,  PDCLK_115200 },
496         { 4000000, PDCLK_4000000 },
497 };
498
499
500 /*
501  * Setup chip for speed.
502  *  Called at startup to initialize the chip
503  *  and on speed changes.
504  *
505  * Note: Write multiple registers doesn't appear to work
506  */
507 static int change_speed(struct stir_cb *stir, unsigned speed)
508 {
509         int i, err;
510         __u8 mode;
511
512         for (i = 0; i < ARRAY_SIZE(stir_modes); ++i) {
513                 if (speed == stir_modes[i].speed)
514                         goto found;
515         }
516
517         warn("%s: invalid speed %d", stir->netdev->name, speed);
518         return -EINVAL;
519
520  found:
521         pr_debug("speed change from %d to %d\n", stir->speed, speed);
522
523         /* Reset modulator */
524         err = write_reg(stir, REG_CTRL1, CTRL1_SRESET);
525         if (err)
526                 goto out;
527
528         /* Undocumented magic to tweak the DPLL */
529         err = write_reg(stir, REG_DPLL, 0x15);
530         if (err)
531                 goto out;
532
533         /* Set clock */
534         err = write_reg(stir, REG_PDCLK, stir_modes[i].pdclk);
535         if (err)
536                 goto out;
537
538         mode = MODE_NRESET | MODE_FASTRX;
539         if (isfir(speed))
540                 mode |= MODE_FIR | MODE_FFRSTEN;
541         else
542                 mode |= MODE_SIR;
543
544         if (speed == 2400)
545                 mode |= MODE_2400;
546
547         err = write_reg(stir, REG_MODE, mode);
548         if (err)
549                 goto out;
550
551         /* This resets TEMIC style transceiver if any. */
552         err = write_reg(stir, REG_CTRL1,
553                         CTRL1_SDMODE | (tx_power & 3) << 1);
554         if (err)
555                 goto out;
556
557         err = write_reg(stir, REG_CTRL1, (tx_power & 3) << 1);
558         if (err)
559                 goto out;
560
561         /* Reset sensitivity */
562         err = write_reg(stir, REG_CTRL2, (rx_sensitivity & 7) << 5);
563  out:
564         stir->speed = speed;
565         return err;
566 }
567
568 /*
569  * Called from net/core when new frame is available.
570  */
571 static int stir_hard_xmit(struct sk_buff *skb, struct net_device *netdev)
572 {
573         struct stir_cb *stir = netdev_priv(netdev);
574
575         netif_stop_queue(netdev);
576
577         /* the IRDA wrapping routines don't deal with non linear skb */
578         SKB_LINEAR_ASSERT(skb);
579
580         skb = xchg(&stir->tx_pending, skb);
581         wake_up(&stir->thr_wait);
582         
583         /* this should never happen unless stop/wakeup problem */
584         if (unlikely(skb)) {
585                 WARN_ON(1);
586                 dev_kfree_skb(skb);
587         }
588
589         return 0;
590 }
591
592 /*
593  * Wait for the transmit FIFO to have space for next data
594  *
595  * If space < 0 then wait till FIFO completely drains.
596  * FYI: can take up to 13 seconds at 2400baud.
597  */
598 static int fifo_txwait(struct stir_cb *stir, int space)
599 {
600         int err;
601         unsigned long count, status;
602
603         /* Read FIFO status and count */
604         for(;;) {
605                 err = read_reg(stir, REG_FIFOCTL, stir->fifo_status, 
606                                    FIFO_REGS_SIZE);
607                 if (unlikely(err != FIFO_REGS_SIZE)) {
608                         warn("%s: FIFO register read error: %d", 
609                              stir->netdev->name, err);
610
611                         return err;
612                 }
613
614                 status = stir->fifo_status[0];
615                 count = (unsigned)(stir->fifo_status[2] & 0x1f) << 8 
616                         | stir->fifo_status[1];
617
618                 pr_debug("fifo status 0x%lx count %lu\n", status, count);
619
620                 /* error when receive/transmit fifo gets confused */
621                 if (status & FIFOCTL_RXERR) {
622                         stir->stats.rx_fifo_errors++;
623                         stir->stats.rx_errors++;
624                         break;
625                 }
626
627                 if (status & FIFOCTL_TXERR) {
628                         stir->stats.tx_fifo_errors++;
629                         stir->stats.tx_errors++;
630                         break;
631                 }
632
633                 /* is fifo receiving already, or empty */
634                 if (!(status & FIFOCTL_DIR)
635                     || (status & FIFOCTL_EMPTY))
636                         return 0;
637
638                 if (signal_pending(current))
639                         return -EINTR;
640
641                 /* shutting down? */
642                 if (!netif_running(stir->netdev)
643                     || !netif_device_present(stir->netdev))
644                         return -ESHUTDOWN;
645
646                 /* only waiting for some space */
647                 if (space >= 0 && STIR_FIFO_SIZE - 4 > space + count)
648                         return 0;
649
650                 /* estimate transfer time for remaining chars */
651                 msleep((count * 8000) / stir->speed);
652         }
653                         
654         err = write_reg(stir, REG_FIFOCTL, FIFOCTL_CLR);
655         if (err) 
656                 return err;
657         err = write_reg(stir, REG_FIFOCTL, 0);
658         if (err)
659                 return err;
660
661         return 0;
662 }
663
664
665 /* Wait for turnaround delay before starting transmit.  */
666 static void turnaround_delay(const struct stir_cb *stir, long us)
667 {
668         long ticks;
669         struct timeval now;
670
671         if (us <= 0)
672                 return;
673
674         do_gettimeofday(&now);
675         us -= (now.tv_sec - stir->rx_time.tv_sec) * USEC_PER_SEC;
676         us -= now.tv_usec - stir->rx_time.tv_usec;
677         if (us < 10)
678                 return;
679
680         ticks = us / (1000000 / HZ);
681         if (ticks > 0) {
682                 current->state = TASK_INTERRUPTIBLE;
683                 schedule_timeout(1 + ticks);
684         } else
685                 udelay(us);
686 }
687
688 /*
689  * Start receiver by submitting a request to the receive pipe.
690  * If nothing is available it will return after rx_interval.
691  */
692 static int receive_start(struct stir_cb *stir)
693 {
694         /* reset state */
695         stir->receiving = 1;
696
697         stir->rx_buff.in_frame = FALSE;
698         stir->rx_buff.state = OUTSIDE_FRAME;
699
700         stir->rx_urb->status = 0;
701         return usb_submit_urb(stir->rx_urb, GFP_KERNEL);
702 }
703
704 /* Stop all pending receive Urb's */
705 static void receive_stop(struct stir_cb *stir)
706 {
707         stir->receiving = 0;
708         usb_kill_urb(stir->rx_urb);
709
710         if (stir->rx_buff.in_frame) 
711                 stir->stats.collisions++;
712 }
713 /*
714  * Wrap data in socket buffer and send it.
715  */
716 static void stir_send(struct stir_cb *stir, struct sk_buff *skb)
717 {
718         unsigned wraplen;
719         int first_frame = 0;
720
721         /* if receiving, need to turnaround */
722         if (stir->receiving) {
723                 receive_stop(stir);
724                 turnaround_delay(stir, irda_get_mtt(skb));
725                 first_frame = 1;
726         }
727
728         if (isfir(stir->speed))
729                 wraplen = wrap_fir_skb(skb, stir->io_buf);
730         else
731                 wraplen = wrap_sir_skb(skb, stir->io_buf);
732                 
733         /* check for space available in fifo */
734         if (!first_frame)
735                 fifo_txwait(stir, wraplen);
736
737         stir->stats.tx_packets++;
738         stir->stats.tx_bytes += skb->len;
739         stir->netdev->trans_start = jiffies;
740         pr_debug("send %d (%d)\n", skb->len, wraplen);
741
742         if (usb_bulk_msg(stir->usbdev, usb_sndbulkpipe(stir->usbdev, 1),
743                          stir->io_buf, wraplen,
744                          NULL, msecs_to_jiffies(TRANSMIT_TIMEOUT)))
745                 stir->stats.tx_errors++;
746 }
747
748 /*
749  * Transmit state machine thread
750  */
751 static int stir_transmit_thread(void *arg)
752 {
753         struct stir_cb *stir = arg;
754         struct net_device *dev = stir->netdev;
755         struct sk_buff *skb;
756
757         daemonize("%s", dev->name);
758         allow_signal(SIGTERM);
759
760         while (netif_running(dev)
761                && netif_device_present(dev)
762                && !signal_pending(current))
763         {
764 #ifdef CONFIG_PM
765                 /* if suspending, then power off and wait */
766                 if (unlikely(current->flags & PF_FREEZE)) {
767                         if (stir->receiving)
768                                 receive_stop(stir);
769                         else
770                                 fifo_txwait(stir, -1);
771
772                         write_reg(stir, REG_CTRL1, CTRL1_TXPWD|CTRL1_RXPWD);
773
774                         refrigerator(PF_FREEZE);
775
776                         if (change_speed(stir, stir->speed))
777                                 break;
778                 }
779 #endif
780
781                 /* if something to send? */
782                 skb = xchg(&stir->tx_pending, NULL);
783                 if (skb) {
784                         unsigned new_speed = irda_get_next_speed(skb);
785                         netif_wake_queue(dev);
786
787                         if (skb->len > 0)
788                                 stir_send(stir, skb);
789                         dev_kfree_skb(skb);
790
791                         if (stir->speed != new_speed) {
792                                 if (fifo_txwait(stir, -1) ||
793                                     change_speed(stir, new_speed))
794                                         break;
795                         }
796                         continue;
797                 }
798
799                 /* nothing to send? start receiving */
800                 if (!stir->receiving 
801                     && irda_device_txqueue_empty(dev)) {
802                         /* Wait otherwise chip gets confused. */
803                         if (fifo_txwait(stir, -1))
804                                 break;
805
806                         if (unlikely(receive_start(stir))) {
807                                 if (net_ratelimit())
808                                         info("%s: receive usb submit failed",
809                                              stir->netdev->name);
810                                 stir->receiving = 0;
811                                 msleep(10);
812                                 continue;
813                         }
814                 }
815
816                 /* sleep if nothing to send */
817                 wait_event_interruptible(stir->thr_wait, stir->tx_pending);
818         }
819
820         complete_and_exit (&stir->thr_exited, 0);
821 }
822
823
824 /*
825  * USB bulk receive completion callback.
826  * Wakes up every ms (usb round trip) with wrapped 
827  * data.
828  */
829 static void stir_rcv_irq(struct urb *urb, struct pt_regs *regs)
830 {
831         struct stir_cb *stir = urb->context;
832         int err;
833
834         /* in process of stopping, just drop data */
835         if (!netif_running(stir->netdev))
836                 return;
837
838         /* unlink, shutdown, unplug, other nasties */
839         if (urb->status != 0) 
840                 return;
841
842         if (urb->actual_length > 0) {
843                 pr_debug("receive %d\n", urb->actual_length);
844                 unwrap_chars(stir, urb->transfer_buffer,
845                              urb->actual_length);
846                 
847                 stir->netdev->last_rx = jiffies;
848                 do_gettimeofday(&stir->rx_time);
849         }
850
851         /* kernel thread is stopping receiver don't resubmit */
852         if (!stir->receiving)
853                 return;
854
855         /* resubmit existing urb */
856         err = usb_submit_urb(urb, GFP_ATOMIC);
857
858         /* in case of error, the kernel thread will restart us */
859         if (err) {
860                 warn("%s: usb receive submit error: %d",
861                         stir->netdev->name, err);
862                 stir->receiving = 0;
863                 wake_up(&stir->thr_wait);
864         }
865 }
866
867 /*
868  * Function stir_net_open (dev)
869  *
870  *    Network device is taken up. Usually this is done by "ifconfig irda0 up"
871  */
872 static int stir_net_open(struct net_device *netdev)
873 {
874         struct stir_cb *stir = netdev_priv(netdev);
875         int err;
876         char hwname[16];
877
878         err = usb_clear_halt(stir->usbdev, usb_sndbulkpipe(stir->usbdev, 1));
879         if (err)
880                 goto err_out1;
881         err = usb_clear_halt(stir->usbdev, usb_rcvbulkpipe(stir->usbdev, 2));
882         if (err)
883                 goto err_out1;
884
885         err = change_speed(stir, 9600);
886         if (err)
887                 goto err_out1;
888
889         err = -ENOMEM;
890
891         /* Initialize for SIR/FIR to copy data directly into skb.  */
892         stir->receiving = 0;
893         stir->rx_buff.truesize = IRDA_SKB_MAX_MTU;
894         stir->rx_buff.skb = dev_alloc_skb(IRDA_SKB_MAX_MTU);
895         if (!stir->rx_buff.skb) 
896                 goto err_out1;
897
898         skb_reserve(stir->rx_buff.skb, 1);
899         stir->rx_buff.head = stir->rx_buff.skb->data;
900         do_gettimeofday(&stir->rx_time);
901
902         stir->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
903         if (!stir->rx_urb) 
904                 goto err_out2;
905
906         stir->io_buf = kmalloc(STIR_FIFO_SIZE, GFP_KERNEL);
907         if (!stir->io_buf)
908                 goto err_out3;
909
910         usb_fill_bulk_urb(stir->rx_urb, stir->usbdev,
911                           usb_rcvbulkpipe(stir->usbdev, 2),
912                           stir->io_buf, STIR_FIFO_SIZE,
913                           stir_rcv_irq, stir);
914
915         stir->fifo_status = kmalloc(FIFO_REGS_SIZE, GFP_KERNEL);
916         if (!stir->fifo_status) 
917                 goto err_out4;
918                 
919         /*
920          * Now that everything should be initialized properly,
921          * Open new IrLAP layer instance to take care of us...
922          * Note : will send immediately a speed change...
923          */
924         sprintf(hwname, "usb#%d", stir->usbdev->devnum);
925         stir->irlap = irlap_open(netdev, &stir->qos, hwname);
926         if (!stir->irlap) {
927                 err("stir4200: irlap_open failed");
928                 goto err_out5;
929         }
930
931         /** Start kernel thread for transmit.  */
932         stir->thr_pid = kernel_thread(stir_transmit_thread, stir,
933                                       CLONE_FS|CLONE_FILES);
934         if (stir->thr_pid < 0) {
935                 err = stir->thr_pid;
936                 err("stir4200: unable to start kernel thread");
937                 goto err_out6;
938         }
939
940         netif_start_queue(netdev);
941
942         return 0;
943
944  err_out6:
945         irlap_close(stir->irlap);
946  err_out5:
947         kfree(stir->fifo_status);
948  err_out4:
949         kfree(stir->io_buf);
950  err_out3:
951         usb_free_urb(stir->rx_urb);
952  err_out2:
953         kfree_skb(stir->rx_buff.skb);
954  err_out1:
955         return err;
956 }
957
958 /*
959  * Function stir_net_close (stir)
960  *
961  *    Network device is taken down. Usually this is done by
962  *    "ifconfig irda0 down"
963  */
964 static int stir_net_close(struct net_device *netdev)
965 {
966         struct stir_cb *stir = netdev_priv(netdev);
967
968         /* Stop transmit processing */
969         netif_stop_queue(netdev);
970
971         /* Kill transmit thread */
972         kill_proc(stir->thr_pid, SIGTERM, 1);
973         wait_for_completion(&stir->thr_exited);
974         kfree(stir->fifo_status);
975
976         /* Mop up receive urb's */
977         usb_kill_urb(stir->rx_urb);
978         
979         kfree(stir->io_buf);
980         usb_free_urb(stir->rx_urb);
981         kfree_skb(stir->rx_buff.skb);
982
983         /* Stop and remove instance of IrLAP */
984         if (stir->irlap)
985                 irlap_close(stir->irlap);
986
987         stir->irlap = NULL;
988
989         return 0;
990 }
991
992 /*
993  * IOCTLs : Extra out-of-band network commands...
994  */
995 static int stir_net_ioctl(struct net_device *netdev, struct ifreq *rq, int cmd)
996 {
997         struct if_irda_req *irq = (struct if_irda_req *) rq;
998         struct stir_cb *stir = netdev_priv(netdev);
999         int ret = 0;
1000
1001         switch (cmd) {
1002         case SIOCSBANDWIDTH: /* Set bandwidth */
1003                 if (!capable(CAP_NET_ADMIN))
1004                         return -EPERM;
1005
1006                 /* Check if the device is still there */
1007                 if (netif_device_present(stir->netdev))
1008                         ret = change_speed(stir, irq->ifr_baudrate);
1009                 break;
1010
1011         case SIOCSMEDIABUSY: /* Set media busy */
1012                 if (!capable(CAP_NET_ADMIN))
1013                         return -EPERM;
1014
1015                 /* Check if the IrDA stack is still there */
1016                 if (netif_running(stir->netdev))
1017                         irda_device_set_media_busy(stir->netdev, TRUE);
1018                 break;
1019
1020         case SIOCGRECEIVING:
1021                 /* Only approximately true */
1022                 irq->ifr_receiving = stir->receiving;
1023                 break;
1024
1025         default:
1026                 ret = -EOPNOTSUPP;
1027         }
1028
1029         return ret;
1030 }
1031
1032 /*
1033  * Get device stats (for /proc/net/dev and ifconfig)
1034  */
1035 static struct net_device_stats *stir_net_get_stats(struct net_device *netdev)
1036 {
1037         struct stir_cb *stir = netdev_priv(netdev);
1038         return &stir->stats;
1039 }
1040
1041 /*
1042  * This routine is called by the USB subsystem for each new device
1043  * in the system. We need to check if the device is ours, and in
1044  * this case start handling it.
1045  * Note : it might be worth protecting this function by a global
1046  * spinlock... Or not, because maybe USB already deal with that...
1047  */
1048 static int stir_probe(struct usb_interface *intf,
1049                       const struct usb_device_id *id)
1050 {
1051         struct usb_device *dev = interface_to_usbdev(intf);
1052         struct stir_cb *stir = NULL;
1053         struct net_device *net;
1054         int ret = -ENOMEM;
1055
1056         /* Allocate network device container. */
1057         net = alloc_irdadev(sizeof(*stir));
1058         if(!net)
1059                 goto err_out1;
1060
1061         SET_MODULE_OWNER(net);
1062         SET_NETDEV_DEV(net, &intf->dev);
1063         stir = netdev_priv(net);
1064         stir->netdev = net;
1065         stir->usbdev = dev;
1066
1067         ret = usb_reset_configuration(dev);
1068         if (ret != 0) {
1069                 err("stir4200: usb reset configuration failed");
1070                 goto err_out2;
1071         }
1072
1073         printk(KERN_INFO "SigmaTel STIr4200 IRDA/USB found at address %d, "
1074                 "Vendor: %x, Product: %x\n",
1075                dev->devnum, dev->descriptor.idVendor,
1076                dev->descriptor.idProduct);
1077
1078         /* Initialize QoS for this device */
1079         irda_init_max_qos_capabilies(&stir->qos);
1080
1081         /* That's the Rx capability. */
1082         stir->qos.baud_rate.bits       &= IR_2400 | IR_9600 | IR_19200 |
1083                                          IR_38400 | IR_57600 | IR_115200 |
1084                                          (IR_4000000 << 8);
1085         stir->qos.min_turn_time.bits   &= qos_mtt_bits;
1086         irda_qos_bits_to_value(&stir->qos);
1087
1088         init_completion (&stir->thr_exited);
1089         init_waitqueue_head (&stir->thr_wait);
1090
1091         /* Override the network functions we need to use */
1092         net->hard_start_xmit = stir_hard_xmit;
1093         net->open            = stir_net_open;
1094         net->stop            = stir_net_close;
1095         net->get_stats       = stir_net_get_stats;
1096         net->do_ioctl        = stir_net_ioctl;
1097
1098         ret = register_netdev(net);
1099         if (ret != 0)
1100                 goto err_out2;
1101
1102         info("IrDA: Registered SigmaTel device %s", net->name);
1103
1104         usb_set_intfdata(intf, stir);
1105
1106         return 0;
1107
1108 err_out2:
1109         free_netdev(net);
1110 err_out1:
1111         return ret;
1112 }
1113
1114 /*
1115  * The current device is removed, the USB layer tell us to shut it down...
1116  */
1117 static void stir_disconnect(struct usb_interface *intf)
1118 {
1119         struct stir_cb *stir = usb_get_intfdata(intf);
1120
1121         if (!stir)
1122                 return;
1123
1124         unregister_netdev(stir->netdev);
1125         free_netdev(stir->netdev);
1126
1127         usb_set_intfdata(intf, NULL);
1128 }
1129
1130 #ifdef CONFIG_PM
1131 /* Power management suspend, so power off the transmitter/receiver */
1132 static int stir_suspend(struct usb_interface *intf, u32 state)
1133 {
1134         struct stir_cb *stir = usb_get_intfdata(intf);
1135
1136         netif_device_detach(stir->netdev);
1137         return 0;
1138 }
1139
1140 /* Coming out of suspend, so reset hardware */
1141 static int stir_resume(struct usb_interface *intf)
1142 {
1143         struct stir_cb *stir = usb_get_intfdata(intf);
1144
1145         netif_device_attach(stir->netdev);
1146
1147         /* receiver restarted when send thread wakes up */
1148         return 0;
1149 }
1150 #endif
1151
1152 /*
1153  * USB device callbacks
1154  */
1155 static struct usb_driver irda_driver = {
1156         .owner          = THIS_MODULE,
1157         .name           = "stir4200",
1158         .probe          = stir_probe,
1159         .disconnect     = stir_disconnect,
1160         .id_table       = dongles,
1161 #ifdef CONFIG_PM
1162         .suspend        = stir_suspend,
1163         .resume         = stir_resume,
1164 #endif
1165 };
1166
1167 /*
1168  * Module insertion
1169  */
1170 static int __init stir_init(void)
1171 {
1172         return usb_register(&irda_driver);
1173 }
1174 module_init(stir_init);
1175
1176 /*
1177  * Module removal
1178  */
1179 static void __exit stir_cleanup(void)
1180 {
1181         /* Deregister the driver and remove all pending instances */
1182         usb_deregister(&irda_driver);
1183 }
1184 module_exit(stir_cleanup);