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