patch-2_6_7-vs1_9_1_12
[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         /* sometimes needed to get chip out of stuck state */
524         err = usb_reset_device(stir->usbdev);
525         if (err)
526                 goto out;
527
528         /* Reset modulator */
529         err = write_reg(stir, REG_CTRL1, CTRL1_SRESET);
530         if (err)
531                 goto out;
532
533         /* Undocumented magic to tweak the DPLL */
534         err = write_reg(stir, REG_DPLL, 0x15);
535         if (err)
536                 goto out;
537
538         /* Set clock */
539         err = write_reg(stir, REG_PDCLK, stir_modes[i].pdclk);
540         if (err)
541                 goto out;
542
543         mode = MODE_NRESET | MODE_FASTRX;
544         if (isfir(speed))
545                 mode |= MODE_FIR | MODE_FFRSTEN;
546         else
547                 mode |= MODE_SIR;
548
549         if (speed == 2400)
550                 mode |= MODE_2400;
551
552         err = write_reg(stir, REG_MODE, mode);
553         if (err)
554                 goto out;
555
556         /* This resets TEMIC style transceiver if any. */
557         err = write_reg(stir, REG_CTRL1,
558                         CTRL1_SDMODE | (tx_power & 3) << 1);
559         if (err)
560                 goto out;
561
562         err = write_reg(stir, REG_CTRL1, (tx_power & 3) << 1);
563         if (err)
564                 goto out;
565
566         /* Reset sensitivity */
567         err = write_reg(stir, REG_CTRL2, (rx_sensitivity & 7) << 5);
568  out:
569         stir->speed = speed;
570         return err;
571 }
572
573 /*
574  * Called from net/core when new frame is available.
575  */
576 static int stir_hard_xmit(struct sk_buff *skb, struct net_device *netdev)
577 {
578         struct stir_cb *stir = netdev->priv;
579
580         netif_stop_queue(netdev);
581
582         /* the IRDA wrapping routines don't deal with non linear skb */
583         SKB_LINEAR_ASSERT(skb);
584
585         skb = xchg(&stir->tx_pending, skb);
586         wake_up(&stir->thr_wait);
587         
588         /* this should never happen unless stop/wakeup problem */
589         if (unlikely(skb)) {
590                 WARN_ON(1);
591                 dev_kfree_skb(skb);
592         }
593
594         return 0;
595 }
596
597 /*
598  * Wait for the transmit FIFO to have space for next data
599  *
600  * If space < 0 then wait till FIFO completely drains.
601  * FYI: can take up to 13 seconds at 2400baud.
602  */
603 static int fifo_txwait(struct stir_cb *stir, int space)
604 {
605         int err;
606         unsigned long count, status;
607
608         /* Read FIFO status and count */
609         for(;;) {
610                 err = read_reg(stir, REG_FIFOCTL, stir->fifo_status, 
611                                    FIFO_REGS_SIZE);
612                 if (unlikely(err != FIFO_REGS_SIZE)) {
613                         warn("%s: FIFO register read error: %d", 
614                              stir->netdev->name, err);
615
616                         return err;
617                 }
618
619                 status = stir->fifo_status[0];
620                 count = (unsigned)(stir->fifo_status[2] & 0x1f) << 8 
621                         | stir->fifo_status[1];
622
623                 pr_debug("fifo status 0x%lx count %lu\n", status, count);
624
625                 /* error when receive/transmit fifo gets confused */
626                 if (status & FIFOCTL_RXERR) {
627                         stir->stats.rx_fifo_errors++;
628                         stir->stats.rx_errors++;
629                         break;
630                 }
631
632                 if (status & FIFOCTL_TXERR) {
633                         stir->stats.tx_fifo_errors++;
634                         stir->stats.tx_errors++;
635                         break;
636                 }
637
638                 /* is fifo receiving already, or empty */
639                 if (!(status & FIFOCTL_DIR)
640                     || (status & FIFOCTL_EMPTY))
641                         return 0;
642
643                 if (signal_pending(current))
644                         return -EINTR;
645
646                 /* shutting down? */
647                 if (!netif_running(stir->netdev)
648                     || !netif_device_present(stir->netdev))
649                         return -ESHUTDOWN;
650
651                 /* only waiting for some space */
652                 if (space >= 0 && STIR_FIFO_SIZE - 4 > space + count)
653                         return 0;
654
655                 /* estimate transfer time for remaining chars */
656                 msleep((count * 8000) / stir->speed);
657         }
658                         
659         err = write_reg(stir, REG_FIFOCTL, FIFOCTL_CLR);
660         if (err) 
661                 return err;
662         err = write_reg(stir, REG_FIFOCTL, 0);
663         if (err)
664                 return err;
665
666         return 0;
667 }
668
669
670 /* Wait for turnaround delay before starting transmit.  */
671 static void turnaround_delay(const struct stir_cb *stir, long us)
672 {
673         long ticks;
674         struct timeval now;
675
676         if (us <= 0)
677                 return;
678
679         do_gettimeofday(&now);
680         us -= (now.tv_sec - stir->rx_time.tv_sec) * USEC_PER_SEC;
681         us -= now.tv_usec - stir->rx_time.tv_usec;
682         if (us < 10)
683                 return;
684
685         ticks = us / (1000000 / HZ);
686         if (ticks > 0) {
687                 current->state = TASK_INTERRUPTIBLE;
688                 schedule_timeout(1 + ticks);
689         } else
690                 udelay(us);
691 }
692
693 /*
694  * Start receiver by submitting a request to the receive pipe.
695  * If nothing is available it will return after rx_interval.
696  */
697 static int receive_start(struct stir_cb *stir)
698 {
699         /* reset state */
700         stir->receiving = 1;
701
702         stir->rx_buff.in_frame = FALSE;
703         stir->rx_buff.state = OUTSIDE_FRAME;
704
705         stir->rx_urb->status = 0;
706         return usb_submit_urb(stir->rx_urb, GFP_KERNEL);
707 }
708
709 /* Stop all pending receive Urb's */
710 static void receive_stop(struct stir_cb *stir)
711 {
712         stir->receiving = 0;
713         usb_unlink_urb(stir->rx_urb);
714
715         if (stir->rx_buff.in_frame) 
716                 stir->stats.collisions++;
717 }
718 /*
719  * Wrap data in socket buffer and send it.
720  */
721 static void stir_send(struct stir_cb *stir, struct sk_buff *skb)
722 {
723         unsigned wraplen;
724         int first_frame = 0;
725
726         /* if receiving, need to turnaround */
727         if (stir->receiving) {
728                 receive_stop(stir);
729                 turnaround_delay(stir, irda_get_mtt(skb));
730                 first_frame = 1;
731         }
732
733         if (isfir(stir->speed))
734                 wraplen = wrap_fir_skb(skb, stir->io_buf);
735         else
736                 wraplen = wrap_sir_skb(skb, stir->io_buf);
737                 
738         /* check for space available in fifo */
739         if (!first_frame)
740                 fifo_txwait(stir, wraplen);
741
742         stir->stats.tx_packets++;
743         stir->stats.tx_bytes += skb->len;
744         stir->netdev->trans_start = jiffies;
745         pr_debug("send %d (%d)\n", skb->len, wraplen);
746
747         if (usb_bulk_msg(stir->usbdev, usb_sndbulkpipe(stir->usbdev, 1),
748                          stir->io_buf, wraplen,
749                          NULL, msecs_to_jiffies(TRANSMIT_TIMEOUT)))
750                 stir->stats.tx_errors++;
751 }
752
753 /*
754  * Transmit state machine thread
755  */
756 static int stir_transmit_thread(void *arg)
757 {
758         struct stir_cb *stir = arg;
759         struct net_device *dev = stir->netdev;
760         struct sk_buff *skb;
761
762         daemonize("%s", dev->name);
763         allow_signal(SIGTERM);
764
765         while (netif_running(dev)
766                && netif_device_present(dev)
767                && !signal_pending(current))
768         {
769                 /* if suspending, then power off and wait */
770                 if (current->flags & PF_FREEZE) {
771                         if (stir->receiving)
772                                 receive_stop(stir);
773                         else
774                                 fifo_txwait(stir, -1);
775
776                         write_reg(stir, REG_CTRL1, CTRL1_TXPWD|CTRL1_RXPWD);
777
778                         refrigerator(PF_FREEZE);
779
780                         if (change_speed(stir, stir->speed))
781                                 break;
782                 }
783
784                 /* if something to send? */
785                 skb = xchg(&stir->tx_pending, NULL);
786                 if (skb) {
787                         unsigned new_speed = irda_get_next_speed(skb);
788                         netif_wake_queue(dev);
789
790                         if (skb->len > 0)
791                                 stir_send(stir, skb);
792                         dev_kfree_skb(skb);
793
794                         if (stir->speed != new_speed) {
795                                 if (fifo_txwait(stir, -1) ||
796                                     change_speed(stir, new_speed))
797                                         break;
798                         }
799                         continue;
800                 }
801
802                 /* nothing to send? start receiving */
803                 if (!stir->receiving 
804                     && irda_device_txqueue_empty(dev)) {
805                         /* Wait otherwise chip gets confused. */
806                         if (fifo_txwait(stir, -1))
807                                 break;
808
809                         if (unlikely(receive_start(stir))) {
810                                 if (net_ratelimit())
811                                         info("%s: receive usb submit failed",
812                                              stir->netdev->name);
813                                 stir->receiving = 0;
814                                 msleep(10);
815                                 continue;
816                         }
817                 }
818
819                 /* sleep if nothing to send */
820                 wait_event_interruptible(stir->thr_wait, stir->tx_pending);
821         }
822
823         complete_and_exit (&stir->thr_exited, 0);
824 }
825
826
827 /*
828  * USB bulk receive completion callback.
829  * Wakes up every ms (usb round trip) with wrapped 
830  * data.
831  */
832 static void stir_rcv_irq(struct urb *urb, struct pt_regs *regs)
833 {
834         struct stir_cb *stir = urb->context;
835         int err;
836
837         /* in process of stopping, just drop data */
838         if (!netif_running(stir->netdev))
839                 return;
840
841         /* unlink, shutdown, unplug, other nasties */
842         if (urb->status != 0) 
843                 return;
844
845         if (urb->actual_length > 0) {
846                 pr_debug("receive %d\n", urb->actual_length);
847                 unwrap_chars(stir, urb->transfer_buffer,
848                              urb->actual_length);
849                 
850                 stir->netdev->last_rx = jiffies;
851                 do_gettimeofday(&stir->rx_time);
852         }
853
854         /* kernel thread is stopping receiver don't resubmit */
855         if (!stir->receiving)
856                 return;
857
858         /* resubmit existing urb */
859         err = usb_submit_urb(urb, GFP_ATOMIC);
860
861         /* in case of error, the kernel thread will restart us */
862         if (err) {
863                 warn("%s: usb receive submit error: %d",
864                         stir->netdev->name, err);
865                 stir->receiving = 0;
866                 wake_up(&stir->thr_wait);
867         }
868 }
869
870 /*
871  * Function stir_net_open (dev)
872  *
873  *    Network device is taken up. Usually this is done by "ifconfig irda0 up"
874  */
875 static int stir_net_open(struct net_device *netdev)
876 {
877         struct stir_cb *stir = netdev->priv;
878         int err;
879         char hwname[16];
880
881         err = usb_clear_halt(stir->usbdev, usb_sndbulkpipe(stir->usbdev, 1));
882         if (err)
883                 goto err_out1;
884         err = usb_clear_halt(stir->usbdev, usb_rcvbulkpipe(stir->usbdev, 2));
885         if (err)
886                 goto err_out1;
887
888         err = change_speed(stir, 9600);
889         if (err)
890                 goto err_out1;
891
892         err = -ENOMEM;
893
894         /* Initialize for SIR/FIR to copy data directly into skb.  */
895         stir->receiving = 0;
896         stir->rx_buff.truesize = IRDA_SKB_MAX_MTU;
897         stir->rx_buff.skb = dev_alloc_skb(IRDA_SKB_MAX_MTU);
898         if (!stir->rx_buff.skb) 
899                 goto err_out1;
900
901         skb_reserve(stir->rx_buff.skb, 1);
902         stir->rx_buff.head = stir->rx_buff.skb->data;
903         do_gettimeofday(&stir->rx_time);
904
905         stir->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
906         if (!stir->rx_urb) 
907                 goto err_out2;
908
909         stir->io_buf = kmalloc(STIR_FIFO_SIZE, GFP_KERNEL);
910         if (!stir->io_buf)
911                 goto err_out3;
912
913         usb_fill_bulk_urb(stir->rx_urb, stir->usbdev,
914                           usb_rcvbulkpipe(stir->usbdev, 2),
915                           stir->io_buf, STIR_FIFO_SIZE,
916                           stir_rcv_irq, stir);
917
918         stir->fifo_status = kmalloc(FIFO_REGS_SIZE, GFP_KERNEL);
919         if (!stir->fifo_status) 
920                 goto err_out4;
921                 
922         /*
923          * Now that everything should be initialized properly,
924          * Open new IrLAP layer instance to take care of us...
925          * Note : will send immediately a speed change...
926          */
927         sprintf(hwname, "usb#%d", stir->usbdev->devnum);
928         stir->irlap = irlap_open(netdev, &stir->qos, hwname);
929         if (!stir->irlap) {
930                 err("irlap_open failed");
931                 goto err_out5;
932         }
933
934         /** Start kernel thread for transmit.  */
935         stir->thr_pid = kernel_thread(stir_transmit_thread, stir,
936                                       CLONE_FS|CLONE_FILES);
937         if (stir->thr_pid < 0) {
938                 err = stir->thr_pid;
939                 err("unable to start kernel thread");
940                 goto err_out6;
941         }
942
943         netif_start_queue(netdev);
944
945         return 0;
946
947  err_out6:
948         irlap_close(stir->irlap);
949  err_out5:
950         kfree(stir->fifo_status);
951  err_out4:
952         kfree(stir->io_buf);
953  err_out3:
954         usb_free_urb(stir->rx_urb);
955  err_out2:
956         kfree_skb(stir->rx_buff.skb);
957  err_out1:
958         return err;
959 }
960
961 /*
962  * Function stir_net_close (stir)
963  *
964  *    Network device is taken down. Usually this is done by
965  *    "ifconfig irda0 down"
966  */
967 static int stir_net_close(struct net_device *netdev)
968 {
969         struct stir_cb *stir = netdev->priv;
970
971         /* Stop transmit processing */
972         netif_stop_queue(netdev);
973
974         /* Kill transmit thread */
975         kill_proc(stir->thr_pid, SIGTERM, 1);
976         wait_for_completion(&stir->thr_exited);
977         kfree(stir->fifo_status);
978
979         /* Mop up receive urb's */
980         usb_unlink_urb(stir->rx_urb);
981         
982         kfree(stir->io_buf);
983         usb_free_urb(stir->rx_urb);
984         kfree_skb(stir->rx_buff.skb);
985
986         /* Stop and remove instance of IrLAP */
987         if (stir->irlap)
988                 irlap_close(stir->irlap);
989
990         stir->irlap = NULL;
991
992         return 0;
993 }
994
995 /*
996  * IOCTLs : Extra out-of-band network commands...
997  */
998 static int stir_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
999 {
1000         struct if_irda_req *irq = (struct if_irda_req *) rq;
1001         struct stir_cb *stir = dev->priv;
1002         int ret = 0;
1003
1004         switch (cmd) {
1005         case SIOCSBANDWIDTH: /* Set bandwidth */
1006                 if (!capable(CAP_NET_ADMIN))
1007                         return -EPERM;
1008
1009                 /* Check if the device is still there */
1010                 if (netif_device_present(stir->netdev))
1011                         ret = change_speed(stir, irq->ifr_baudrate);
1012                 break;
1013
1014         case SIOCSMEDIABUSY: /* Set media busy */
1015                 if (!capable(CAP_NET_ADMIN))
1016                         return -EPERM;
1017
1018                 /* Check if the IrDA stack is still there */
1019                 if (netif_running(stir->netdev))
1020                         irda_device_set_media_busy(stir->netdev, TRUE);
1021                 break;
1022
1023         case SIOCGRECEIVING:
1024                 /* Only approximately true */
1025                 irq->ifr_receiving = stir->receiving;
1026                 break;
1027
1028         default:
1029                 ret = -EOPNOTSUPP;
1030         }
1031
1032         return ret;
1033 }
1034
1035 /*
1036  * Get device stats (for /proc/net/dev and ifconfig)
1037  */
1038 static struct net_device_stats *stir_net_get_stats(struct net_device *dev)
1039 {
1040         struct stir_cb *stir = dev->priv;
1041         return &stir->stats;
1042 }
1043
1044 /*
1045  * This routine is called by the USB subsystem for each new device
1046  * in the system. We need to check if the device is ours, and in
1047  * this case start handling it.
1048  * Note : it might be worth protecting this function by a global
1049  * spinlock... Or not, because maybe USB already deal with that...
1050  */
1051 static int stir_probe(struct usb_interface *intf,
1052                       const struct usb_device_id *id)
1053 {
1054         struct usb_device *dev = interface_to_usbdev(intf);
1055         struct stir_cb *stir = NULL;
1056         struct net_device *net;
1057         int ret = -ENOMEM;
1058
1059         /* Allocate network device container. */
1060         net = alloc_irdadev(sizeof(*stir));
1061         if(!net)
1062                 goto err_out1;
1063
1064         SET_MODULE_OWNER(net);
1065         SET_NETDEV_DEV(net, &intf->dev);
1066         stir = net->priv;
1067         stir->netdev = net;
1068         stir->usbdev = dev;
1069
1070         ret = usb_reset_configuration(dev);
1071         if (ret != 0) {
1072                 err("usb reset configuration failed");
1073                 goto err_out2;
1074         }
1075
1076         printk(KERN_INFO "SigmaTel STIr4200 IRDA/USB found at address %d, "
1077                 "Vendor: %x, Product: %x\n",
1078                dev->devnum, dev->descriptor.idVendor,
1079                dev->descriptor.idProduct);
1080
1081         /* Initialize QoS for this device */
1082         irda_init_max_qos_capabilies(&stir->qos);
1083
1084         /* That's the Rx capability. */
1085         stir->qos.baud_rate.bits       &= IR_2400 | IR_9600 | IR_19200 |
1086                                          IR_38400 | IR_57600 | IR_115200 |
1087                                          (IR_4000000 << 8);
1088         stir->qos.min_turn_time.bits   &= qos_mtt_bits;
1089         irda_qos_bits_to_value(&stir->qos);
1090
1091         init_completion (&stir->thr_exited);
1092         init_waitqueue_head (&stir->thr_wait);
1093
1094         /* Override the network functions we need to use */
1095         net->hard_start_xmit = stir_hard_xmit;
1096         net->open            = stir_net_open;
1097         net->stop            = stir_net_close;
1098         net->get_stats       = stir_net_get_stats;
1099         net->do_ioctl        = stir_net_ioctl;
1100
1101         ret = register_netdev(net);
1102         if (ret != 0)
1103                 goto err_out2;
1104
1105         MESSAGE("IrDA: Registered SigmaTel device %s\n", net->name);
1106
1107         usb_set_intfdata(intf, stir);
1108
1109         return 0;
1110
1111 err_out2:
1112         free_netdev(net);
1113 err_out1:
1114         return ret;
1115 }
1116
1117 /*
1118  * The current device is removed, the USB layer tell us to shut it down...
1119  */
1120 static void stir_disconnect(struct usb_interface *intf)
1121 {
1122         struct stir_cb *stir = usb_get_intfdata(intf);
1123
1124         if (!stir)
1125                 return;
1126
1127         unregister_netdev(stir->netdev);
1128         free_netdev(stir->netdev);
1129
1130         usb_set_intfdata(intf, NULL);
1131 }
1132
1133
1134 /* Power management suspend, so power off the transmitter/receiver */
1135 static int stir_suspend(struct usb_interface *intf, u32 state)
1136 {
1137         struct stir_cb *stir = usb_get_intfdata(intf);
1138
1139         netif_device_detach(stir->netdev);
1140         return 0;
1141 }
1142
1143 /* Coming out of suspend, so reset hardware */
1144 static int stir_resume(struct usb_interface *intf)
1145 {
1146         struct stir_cb *stir = usb_get_intfdata(intf);
1147
1148         netif_device_attach(stir->netdev);
1149
1150         /* receiver restarted when send thread wakes up */
1151         return 0;
1152 }
1153
1154 /*
1155  * USB device callbacks
1156  */
1157 static struct usb_driver irda_driver = {
1158         .owner          = THIS_MODULE,
1159         .name           = "stir4200",
1160         .probe          = stir_probe,
1161         .disconnect     = stir_disconnect,
1162         .id_table       = dongles,
1163         .suspend        = stir_suspend,
1164         .resume         = stir_resume,
1165 };
1166
1167 /*
1168  * Module insertion
1169  */
1170 static int __init stir_init(void)
1171 {
1172         if (usb_register(&irda_driver) < 0)
1173                 return -1;
1174
1175         MESSAGE("SigmaTel support registered\n");
1176         return 0;
1177 }
1178 module_init(stir_init);
1179
1180 /*
1181  * Module removal
1182  */
1183 static void __exit stir_cleanup(void)
1184 {
1185         /* Deregister the driver and remove all pending instances */
1186         usb_deregister(&irda_driver);
1187 }
1188 module_exit(stir_cleanup);