staging: comedi: usbdux: move usbdux_firmware_upload()
[firefly-linux-kernel-4.4.55.git] / drivers / staging / comedi / drivers / usbdux.c
1 /*
2    comedi/drivers/usbdux.c
3    Copyright (C) 2003-2007 Bernd Porr, Bernd.Porr@f2s.com
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14  */
15 /*
16 Driver: usbdux
17 Description: University of Stirling USB DAQ & INCITE Technology Limited
18 Devices: [ITL] USB-DUX (usbdux.o)
19 Author: Bernd Porr <BerndPorr@f2s.com>
20 Updated: 8 Dec 2008
21 Status: Stable
22 Configuration options:
23   You have to upload firmware with the -i option. The
24   firmware is usually installed under /usr/share/usb or
25   /usr/local/share/usb or /lib/firmware.
26
27 Connection scheme for the counter at the digital port:
28   0=/CLK0, 1=UP/DOWN0, 2=RESET0, 4=/CLK1, 5=UP/DOWN1, 6=RESET1.
29   The sampling rate of the counter is approximately 500Hz.
30
31 Please note that under USB2.0 the length of the channel list determines
32 the max sampling rate. If you sample only one channel you get 8kHz
33 sampling rate. If you sample two channels you get 4kHz and so on.
34 */
35 /*
36  * I must give credit here to Chris Baugher who
37  * wrote the driver for AT-MIO-16d. I used some parts of this
38  * driver. I also must give credits to David Brownell
39  * who supported me with the USB development.
40  *
41  * Bernd Porr
42  *
43  *
44  * Revision history:
45  * 0.94: D/A output should work now with any channel list combinations
46  * 0.95: .owner commented out for kernel vers below 2.4.19
47  *       sanity checks in ai/ao_cmd
48  * 0.96: trying to get it working with 2.6, moved all memory alloc to comedi's
49  *       attach final USB IDs
50  *       moved memory allocation completely to the corresponding comedi
51  *       functions firmware upload is by fxload and no longer by comedi (due to
52  *       enumeration)
53  * 0.97: USB IDs received, adjusted table
54  * 0.98: SMP, locking, memory alloc: moved all usb memory alloc
55  *       to the usb subsystem and moved all comedi related memory
56  *       alloc to comedi.
57  *       | kernel | registration | usbdux-usb | usbdux-comedi | comedi |
58  * 0.99: USB 2.0: changed protocol to isochronous transfer
59  *                IRQ transfer is too buggy and too risky in 2.0
60  *                for the high speed ISO transfer is now a working version
61  *                available
62  * 0.99b: Increased the iso transfer buffer for high sp.to 10 buffers. Some VIA
63  *        chipsets miss out IRQs. Deeper buffering is needed.
64  * 1.00: full USB 2.0 support for the A/D converter. Now: max 8kHz sampling
65  *       rate.
66  *       Firmware vers 1.00 is needed for this.
67  *       Two 16 bit up/down/reset counter with a sampling rate of 1kHz
68  *       And loads of cleaning up, in particular streamlining the
69  *       bulk transfers.
70  * 1.1:  moved EP4 transfers to EP1 to make space for a PWM output on EP4
71  * 1.2:  added PWM support via EP4
72  * 2.0:  PWM seems to be stable and is not interfering with the other functions
73  * 2.1:  changed PWM API
74  * 2.2:  added firmware kernel request to fix an udev problem
75  * 2.3:  corrected a bug in bulk timeouts which were far too short
76  * 2.4:  fixed a bug which causes the driver to hang when it ran out of data.
77  *       Thanks to Jan-Matthias Braun and Ian to spot the bug and fix it.
78  *
79  */
80
81 #include <linux/kernel.h>
82 #include <linux/module.h>
83 #include <linux/init.h>
84 #include <linux/slab.h>
85 #include <linux/input.h>
86 #include <linux/usb.h>
87 #include <linux/fcntl.h>
88 #include <linux/compiler.h>
89
90 #include "../comedidev.h"
91
92 #include "comedi_fc.h"
93
94 /* constants for firmware upload and download */
95 #define USBDUX_FIRMWARE         "usbdux_firmware.bin"
96 #define USBDUX_FIRMWARE_MAX_LEN 0x2000
97 #define USBDUX_FIRMWARE_CMD     0xa0
98 #define VENDOR_DIR_IN           0xc0
99 #define VENDOR_DIR_OUT          0x40
100 #define USBDUX_CPU_CS           0xe600
101
102 /* timeout for the USB-transfer in ms */
103 #define BULK_TIMEOUT            1000
104
105 /* 300Hz max frequ under PWM */
106 #define MIN_PWM_PERIOD  ((long)(1E9/300))
107
108 /* Default PWM frequency */
109 #define PWM_DEFAULT_PERIOD ((long)(1E9/100))
110
111 /* Number of channels */
112 #define NUMCHANNELS       8
113
114 /* Size of one A/D value */
115 #define SIZEADIN          ((sizeof(int16_t)))
116
117 /*
118  * Size of the input-buffer IN BYTES
119  * Always multiple of 8 for 8 microframes which is needed in the highspeed mode
120  */
121 #define SIZEINBUF         ((8*SIZEADIN))
122
123 /* 16 bytes. */
124 #define SIZEINSNBUF       16
125
126 /* Number of DA channels */
127 #define NUMOUTCHANNELS    8
128
129 /* size of one value for the D/A converter: channel and value */
130 #define SIZEDAOUT          ((sizeof(int8_t)+sizeof(int16_t)))
131
132 /*
133  * Size of the output-buffer in bytes
134  * Actually only the first 4 triplets are used but for the
135  * high speed mode we need to pad it to 8 (microframes).
136  */
137 #define SIZEOUTBUF         ((8*SIZEDAOUT))
138
139 /*
140  * Size of the buffer for the dux commands: just now max size is determined
141  * by the analogue out + command byte + panic bytes...
142  */
143 #define SIZEOFDUXBUFFER    ((8*SIZEDAOUT+2))
144
145 /* Number of in-URBs which receive the data: min=2 */
146 #define NUMOFINBUFFERSFULL     5
147
148 /* Number of out-URBs which send the data: min=2 */
149 #define NUMOFOUTBUFFERSFULL    5
150
151 /* Number of in-URBs which receive the data: min=5 */
152 /* must have more buffers due to buggy USB ctr */
153 #define NUMOFINBUFFERSHIGH     10
154
155 /* Number of out-URBs which send the data: min=5 */
156 /* must have more buffers due to buggy USB ctr */
157 #define NUMOFOUTBUFFERSHIGH    10
158
159 /* number of retries to get the right dux command */
160 #define RETRIES 10
161
162 static const struct comedi_lrange range_usbdux_ai_range = {
163         4, {
164                 BIP_RANGE(4.096),
165                 BIP_RANGE(4.096 / 2),
166                 UNI_RANGE(4.096),
167                 UNI_RANGE(4.096 / 2)
168         }
169 };
170
171 static const struct comedi_lrange range_usbdux_ao_range = {
172         2, {
173                 BIP_RANGE(4.096),
174                 UNI_RANGE(4.096)
175         }
176 };
177
178 struct usbdux_private {
179         /* actual number of in-buffers */
180         int num_in_buffers;
181         /* actual number of out-buffers */
182         int num_out_buffers;
183         /* ISO-transfer handling: buffers */
184         struct urb **urb_in;
185         struct urb **urb_out;
186         /* pwm-transfer handling */
187         struct urb *urb_pwm;
188         /* PWM period */
189         unsigned int pwm_period;
190         /* PWM internal delay for the GPIF in the FX2 */
191         int8_t pwn_delay;
192         /* size of the PWM buffer which holds the bit pattern */
193         int size_pwm_buf;
194         /* input buffer for the ISO-transfer */
195         int16_t *in_buffer;
196         /* input buffer for single insn */
197         int16_t *insn_buffer;
198         /* output buffer for single DA outputs */
199         int16_t *out_buffer;
200
201         unsigned int high_speed:1;
202         unsigned int ai_cmd_running:1;
203         unsigned int ai_continous:1;
204         unsigned int ao_cmd_running:1;
205         unsigned int ao_continous:1;
206         unsigned int pwm_cmd_running:1;
207
208         /* number of samples to acquire */
209         int ai_sample_count;
210         int ao_sample_count;
211         /* time between samples in units of the timer */
212         unsigned int ai_timer;
213         unsigned int ao_timer;
214         /* counter between aquisitions */
215         unsigned int ai_counter;
216         unsigned int ao_counter;
217         /* interval in frames/uframes */
218         unsigned int ai_interval;
219         /* D/A commands */
220         int8_t *dac_commands;
221         /* commands */
222         int8_t *dux_commands;
223         struct semaphore sem;
224 };
225
226 static void usbduxsub_unlink_inurbs(struct comedi_device *dev)
227 {
228         struct usbdux_private *devpriv = dev->private;
229         int i;
230
231         if (devpriv->urb_in) {
232                 for (i = 0; i < devpriv->num_in_buffers; i++)
233                         usb_kill_urb(devpriv->urb_in[i]);
234         }
235 }
236
237 static void usbdux_ai_stop(struct comedi_device *dev, int do_unlink)
238 {
239         struct usbdux_private *devpriv = dev->private;
240
241         if (do_unlink)
242                 usbduxsub_unlink_inurbs(dev);
243
244         devpriv->ai_cmd_running = 0;
245 }
246
247 static int usbdux_ai_cancel(struct comedi_device *dev,
248                             struct comedi_subdevice *s)
249 {
250         struct usbdux_private *devpriv = dev->private;
251
252         /* prevent other CPUs from submitting new commands just now */
253         down(&devpriv->sem);
254         /* unlink only if the urb really has been submitted */
255         usbdux_ai_stop(dev, devpriv->ai_cmd_running);
256         up(&devpriv->sem);
257
258         return 0;
259 }
260
261 /* analogue IN - interrupt service routine */
262 static void usbduxsub_ai_isoc_irq(struct urb *urb)
263 {
264         struct comedi_device *dev = urb->context;
265         struct comedi_subdevice *s = dev->read_subdev;
266         struct usbdux_private *devpriv = dev->private;
267         int i, err, n;
268
269         /* first we test if something unusual has just happened */
270         switch (urb->status) {
271         case 0:
272                 /* copy the result in the transfer buffer */
273                 memcpy(devpriv->in_buffer, urb->transfer_buffer, SIZEINBUF);
274                 break;
275         case -EILSEQ:
276                 /* error in the ISOchronous data */
277                 /* we don't copy the data into the transfer buffer */
278                 /* and recycle the last data byte */
279                 dev_dbg(dev->class_dev, "CRC error in ISO IN stream\n");
280                 break;
281
282         case -ECONNRESET:
283         case -ENOENT:
284         case -ESHUTDOWN:
285         case -ECONNABORTED:
286                 /* happens after an unlink command */
287                 if (devpriv->ai_cmd_running) {
288                         s->async->events |= COMEDI_CB_EOA;
289                         s->async->events |= COMEDI_CB_ERROR;
290                         comedi_event(dev, s);
291                         /* stop the transfer w/o unlink */
292                         usbdux_ai_stop(dev, 0);
293                 }
294                 return;
295
296         default:
297                 /* a real error on the bus */
298                 /* pass error to comedi if we are really running a command */
299                 if (devpriv->ai_cmd_running) {
300                         dev_err(dev->class_dev,
301                                 "Non-zero urb status received in ai intr context: %d\n",
302                                 urb->status);
303                         s->async->events |= COMEDI_CB_EOA;
304                         s->async->events |= COMEDI_CB_ERROR;
305                         comedi_event(dev, s);
306                         /* don't do an unlink here */
307                         usbdux_ai_stop(dev, 0);
308                 }
309                 return;
310         }
311
312         /*
313          * at this point we are reasonably sure that nothing dodgy has happened
314          * are we running a command?
315          */
316         if (unlikely(!devpriv->ai_cmd_running)) {
317                 /*
318                  * not running a command, do not continue execution if no
319                  * asynchronous command is running in particular not resubmit
320                  */
321                 return;
322         }
323
324         urb->dev = comedi_to_usb_dev(dev);
325
326         /* resubmit the urb */
327         err = usb_submit_urb(urb, GFP_ATOMIC);
328         if (unlikely(err < 0)) {
329                 dev_err(dev->class_dev,
330                         "urb resubmit failed in int-context! err=%d\n", err);
331                 if (err == -EL2NSYNC)
332                         dev_err(dev->class_dev,
333                                 "buggy USB host controller or bug in IRQ handler!\n");
334                 s->async->events |= COMEDI_CB_EOA;
335                 s->async->events |= COMEDI_CB_ERROR;
336                 comedi_event(dev, s);
337                 /* don't do an unlink here */
338                 usbdux_ai_stop(dev, 0);
339                 return;
340         }
341
342         devpriv->ai_counter--;
343         if (likely(devpriv->ai_counter > 0))
344                 return;
345
346         /* timer zero, transfer measurements to comedi */
347         devpriv->ai_counter = devpriv->ai_timer;
348
349         /* test, if we transmit only a fixed number of samples */
350         if (!devpriv->ai_continous) {
351                 /* not continuous, fixed number of samples */
352                 devpriv->ai_sample_count--;
353                 /* all samples received? */
354                 if (devpriv->ai_sample_count < 0) {
355                         /* prevent a resubmit next time */
356                         usbdux_ai_stop(dev, 0);
357                         /* say comedi that the acquistion is over */
358                         s->async->events |= COMEDI_CB_EOA;
359                         comedi_event(dev, s);
360                         return;
361                 }
362         }
363         /* get the data from the USB bus and hand it over to comedi */
364         n = s->async->cmd.chanlist_len;
365         for (i = 0; i < n; i++) {
366                 /* transfer data */
367                 if (CR_RANGE(s->async->cmd.chanlist[i]) <= 1) {
368                         err = comedi_buf_put(s->async,
369                              le16_to_cpu(devpriv->in_buffer[i]) ^ 0x800);
370                 } else {
371                         err = comedi_buf_put(s->async,
372                              le16_to_cpu(devpriv->in_buffer[i]));
373                 }
374                 if (unlikely(err == 0)) {
375                         /* buffer overflow */
376                         usbdux_ai_stop(dev, 0);
377                         return;
378                 }
379         }
380         /* tell comedi that data is there */
381         s->async->events |= COMEDI_CB_BLOCK | COMEDI_CB_EOS;
382         comedi_event(dev, s);
383 }
384
385 static void usbduxsub_unlink_outurbs(struct comedi_device *dev)
386 {
387         struct usbdux_private *devpriv = dev->private;
388         int i;
389
390         if (devpriv->urb_out) {
391                 for (i = 0; i < devpriv->num_out_buffers; i++)
392                         usb_kill_urb(devpriv->urb_out[i]);
393         }
394 }
395
396 static void usbdux_ao_stop(struct comedi_device *dev, int do_unlink)
397 {
398         struct usbdux_private *devpriv = dev->private;
399
400         if (do_unlink)
401                 usbduxsub_unlink_outurbs(dev);
402
403         devpriv->ao_cmd_running = 0;
404 }
405
406 static int usbdux_ao_cancel(struct comedi_device *dev,
407                             struct comedi_subdevice *s)
408 {
409         struct usbdux_private *devpriv = dev->private;
410
411         /* prevent other CPUs from submitting a command just now */
412         down(&devpriv->sem);
413         /* unlink only if it is really running */
414         usbdux_ao_stop(dev, devpriv->ao_cmd_running);
415         up(&devpriv->sem);
416
417         return 0;
418 }
419
420 static void usbduxsub_ao_isoc_irq(struct urb *urb)
421 {
422         struct comedi_device *dev = urb->context;
423         struct comedi_subdevice *s = dev->write_subdev;
424         struct usbdux_private *devpriv = dev->private;
425         int i, ret;
426         int8_t *datap;
427
428         switch (urb->status) {
429         case 0:
430                 /* success */
431                 break;
432
433         case -ECONNRESET:
434         case -ENOENT:
435         case -ESHUTDOWN:
436         case -ECONNABORTED:
437                 /* after an unlink command, unplug, ... etc */
438                 /* no unlink needed here. Already shutting down. */
439                 if (devpriv->ao_cmd_running) {
440                         s->async->events |= COMEDI_CB_EOA;
441                         comedi_event(dev, s);
442                         usbdux_ao_stop(dev, 0);
443                 }
444                 return;
445
446         default:
447                 /* a real error */
448                 if (devpriv->ao_cmd_running) {
449                         dev_err(dev->class_dev,
450                                 "Non-zero urb status received in ao intr context: %d\n",
451                                 urb->status);
452                         s->async->events |= COMEDI_CB_ERROR;
453                         s->async->events |= COMEDI_CB_EOA;
454                         comedi_event(dev, s);
455                         /* we do an unlink if we are in the high speed mode */
456                         usbdux_ao_stop(dev, 0);
457                 }
458                 return;
459         }
460
461         /* are we actually running? */
462         if (!devpriv->ao_cmd_running)
463                 return;
464
465         /* normal operation: executing a command in this subdevice */
466         devpriv->ao_counter--;
467         if ((int)devpriv->ao_counter <= 0) {
468                 /* timer zero */
469                 devpriv->ao_counter = devpriv->ao_timer;
470
471                 /* handle non continous acquisition */
472                 if (!devpriv->ao_continous) {
473                         /* fixed number of samples */
474                         devpriv->ao_sample_count--;
475                         if (devpriv->ao_sample_count < 0) {
476                                 /* all samples transmitted */
477                                 usbdux_ao_stop(dev, 0);
478                                 s->async->events |= COMEDI_CB_EOA;
479                                 comedi_event(dev, s);
480                                 /* no resubmit of the urb */
481                                 return;
482                         }
483                 }
484                 /* transmit data to the USB bus */
485                 ((uint8_t *) (urb->transfer_buffer))[0] =
486                     s->async->cmd.chanlist_len;
487                 for (i = 0; i < s->async->cmd.chanlist_len; i++) {
488                         short temp;
489                         if (i >= NUMOUTCHANNELS)
490                                 break;
491
492                         /* pointer to the DA */
493                         datap =
494                             (&(((int8_t *) urb->transfer_buffer)[i * 3 + 1]));
495                         /* get the data from comedi */
496                         ret = comedi_buf_get(s->async, &temp);
497                         datap[0] = temp;
498                         datap[1] = temp >> 8;
499                         datap[2] = devpriv->dac_commands[i];
500                         if (ret < 0) {
501                                 dev_err(&urb->dev->dev,
502                                         "comedi: buffer underflow\n");
503                                 s->async->events |= COMEDI_CB_EOA;
504                                 s->async->events |= COMEDI_CB_OVERFLOW;
505                         }
506                         /* transmit data to comedi */
507                         s->async->events |= COMEDI_CB_BLOCK;
508                         comedi_event(dev, s);
509                 }
510         }
511         urb->transfer_buffer_length = SIZEOUTBUF;
512         urb->dev = comedi_to_usb_dev(dev);
513         urb->status = 0;
514         if (devpriv->ao_cmd_running) {
515                 if (devpriv->high_speed)
516                         urb->interval = 8;      /* uframes */
517                 else
518                         urb->interval = 1;      /* frames */
519                 urb->number_of_packets = 1;
520                 urb->iso_frame_desc[0].offset = 0;
521                 urb->iso_frame_desc[0].length = SIZEOUTBUF;
522                 urb->iso_frame_desc[0].status = 0;
523                 ret = usb_submit_urb(urb, GFP_ATOMIC);
524                 if (ret < 0) {
525                         dev_err(dev->class_dev,
526                                 "ao urb resubm failed in int-cont. ret=%d",
527                                 ret);
528                         if (ret == EL2NSYNC)
529                                 dev_err(dev->class_dev,
530                                         "buggy USB host controller or bug in IRQ handling!\n");
531
532                         s->async->events |= COMEDI_CB_EOA;
533                         s->async->events |= COMEDI_CB_ERROR;
534                         comedi_event(dev, s);
535                         /* don't do an unlink here */
536                         usbdux_ao_stop(dev, 0);
537                 }
538         }
539 }
540
541 static int usbduxsub_submit_inurbs(struct comedi_device *dev)
542 {
543         struct usb_device *usb = comedi_to_usb_dev(dev);
544         struct usbdux_private *devpriv = dev->private;
545         struct urb *urb;
546         int ret;
547         int i;
548
549         /* Submit all URBs and start the transfer on the bus */
550         for (i = 0; i < devpriv->num_in_buffers; i++) {
551                 urb = devpriv->urb_in[i];
552
553                 /* in case of a resubmission after an unlink... */
554                 urb->interval = devpriv->ai_interval;
555                 urb->context = dev;
556                 urb->dev = usb;
557                 urb->status = 0;
558                 urb->transfer_flags = URB_ISO_ASAP;
559
560                 ret = usb_submit_urb(urb, GFP_ATOMIC);
561                 if (ret)
562                         return ret;
563         }
564         return 0;
565 }
566
567 static int usbduxsub_submit_outurbs(struct comedi_device *dev)
568 {
569         struct usb_device *usb = comedi_to_usb_dev(dev);
570         struct usbdux_private *devpriv = dev->private;
571         struct urb *urb;
572         int ret;
573         int i;
574
575         for (i = 0; i < devpriv->num_out_buffers; i++) {
576                 urb = devpriv->urb_out[i];
577
578                 /* in case of a resubmission after an unlink... */
579                 urb->context = dev;
580                 urb->dev = usb;
581                 urb->status = 0;
582                 urb->transfer_flags = URB_ISO_ASAP;
583
584                 ret = usb_submit_urb(urb, GFP_ATOMIC);
585                 if (ret)
586                         return ret;
587         }
588         return 0;
589 }
590
591 static int usbdux_ai_cmdtest(struct comedi_device *dev,
592                              struct comedi_subdevice *s, struct comedi_cmd *cmd)
593 {
594         struct usbdux_private *this_usbduxsub = dev->private;
595         int err = 0, i;
596         unsigned int tmp_timer;
597
598         /* Step 1 : check if triggers are trivially valid */
599
600         err |= cfc_check_trigger_src(&cmd->start_src, TRIG_NOW | TRIG_INT);
601         err |= cfc_check_trigger_src(&cmd->scan_begin_src, TRIG_TIMER);
602         err |= cfc_check_trigger_src(&cmd->convert_src, TRIG_NOW);
603         err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
604         err |= cfc_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
605
606         if (err)
607                 return 1;
608
609         /* Step 2a : make sure trigger sources are unique */
610
611         err |= cfc_check_trigger_is_unique(cmd->start_src);
612         err |= cfc_check_trigger_is_unique(cmd->stop_src);
613
614         /* Step 2b : and mutually compatible */
615
616         if (err)
617                 return 2;
618
619         /* Step 3: check if arguments are trivially valid */
620
621         err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);
622
623         if (cmd->scan_begin_src == TRIG_FOLLOW) /* internal trigger */
624                 err |= cfc_check_trigger_arg_is(&cmd->scan_begin_arg, 0);
625
626         if (cmd->scan_begin_src == TRIG_TIMER) {
627                 if (this_usbduxsub->high_speed) {
628                         /*
629                          * In high speed mode microframes are possible.
630                          * However, during one microframe we can roughly
631                          * sample one channel. Thus, the more channels
632                          * are in the channel list the more time we need.
633                          */
634                         i = 1;
635                         /* find a power of 2 for the number of channels */
636                         while (i < (cmd->chanlist_len))
637                                 i = i * 2;
638
639                         err |= cfc_check_trigger_arg_min(&cmd->scan_begin_arg,
640                                                          1000000 / 8 * i);
641                         /* now calc the real sampling rate with all the
642                          * rounding errors */
643                         tmp_timer =
644                             ((unsigned int)(cmd->scan_begin_arg / 125000)) *
645                             125000;
646                 } else {
647                         /* full speed */
648                         /* 1kHz scans every USB frame */
649                         err |= cfc_check_trigger_arg_min(&cmd->scan_begin_arg,
650                                                          1000000);
651                         /*
652                          * calc the real sampling rate with the rounding errors
653                          */
654                         tmp_timer = ((unsigned int)(cmd->scan_begin_arg /
655                                                    1000000)) * 1000000;
656                 }
657                 err |= cfc_check_trigger_arg_is(&cmd->scan_begin_arg,
658                                                 tmp_timer);
659         }
660
661         err |= cfc_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len);
662
663         if (cmd->stop_src == TRIG_COUNT) {
664                 /* any count is allowed */
665         } else {
666                 /* TRIG_NONE */
667                 err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
668         }
669
670         if (err)
671                 return 3;
672
673         return 0;
674 }
675
676 /*
677  * creates the ADC command for the MAX1271
678  * range is the range value from comedi
679  */
680 static int8_t create_adc_command(unsigned int chan, int range)
681 {
682         int8_t p = (range <= 1);
683         int8_t r = ((range % 2) == 0);
684         return (chan << 4) | ((p == 1) << 2) | ((r == 1) << 3);
685 }
686
687 /* bulk transfers to usbdux */
688
689 #define SENDADCOMMANDS            0
690 #define SENDDACOMMANDS            1
691 #define SENDDIOCONFIGCOMMAND      2
692 #define SENDDIOBITSCOMMAND        3
693 #define SENDSINGLEAD              4
694 #define READCOUNTERCOMMAND        5
695 #define WRITECOUNTERCOMMAND       6
696 #define SENDPWMON                 7
697 #define SENDPWMOFF                8
698
699 static int send_dux_commands(struct comedi_device *dev, int cmd_type)
700 {
701         struct usb_device *usb = comedi_to_usb_dev(dev);
702         struct usbdux_private *devpriv = dev->private;
703         int nsent;
704
705         devpriv->dux_commands[0] = cmd_type;
706
707         return usb_bulk_msg(usb, usb_sndbulkpipe(usb, 1),
708                             devpriv->dux_commands, SIZEOFDUXBUFFER,
709                             &nsent, BULK_TIMEOUT);
710 }
711
712 static int receive_dux_commands(struct comedi_device *dev, int command)
713 {
714         struct usb_device *usb = comedi_to_usb_dev(dev);
715         struct usbdux_private *devpriv = dev->private;
716         int ret;
717         int nrec;
718         int i;
719
720         for (i = 0; i < RETRIES; i++) {
721                 ret = usb_bulk_msg(usb, usb_rcvbulkpipe(usb, 8),
722                                       devpriv->insn_buffer, SIZEINSNBUF,
723                                       &nrec, BULK_TIMEOUT);
724                 if (ret < 0)
725                         return ret;
726                 if (le16_to_cpu(devpriv->insn_buffer[0]) == command)
727                         return ret;
728         }
729         /* command not received */
730         return -EFAULT;
731 }
732
733 static int usbdux_ai_inttrig(struct comedi_device *dev,
734                              struct comedi_subdevice *s,
735                              unsigned int trignum)
736 {
737         struct usbdux_private *devpriv = dev->private;
738         int ret = -EINVAL;
739
740         down(&devpriv->sem);
741
742         if (trignum != 0)
743                 goto ai_trig_exit;
744
745         if (!devpriv->ai_cmd_running) {
746                 devpriv->ai_cmd_running = 1;
747                 ret = usbduxsub_submit_inurbs(dev);
748                 if (ret < 0) {
749                         devpriv->ai_cmd_running = 0;
750                         goto ai_trig_exit;
751                 }
752                 s->async->inttrig = NULL;
753         } else {
754                 ret = -EBUSY;
755         }
756
757 ai_trig_exit:
758         up(&devpriv->sem);
759         return ret;
760 }
761
762 static int usbdux_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
763 {
764         struct usbdux_private *devpriv = dev->private;
765         struct comedi_cmd *cmd = &s->async->cmd;
766         int len = cmd->chanlist_len;
767         int ret = -EBUSY;
768         int i;
769
770         /* block other CPUs from starting an ai_cmd */
771         down(&devpriv->sem);
772
773         if (devpriv->ai_cmd_running)
774                 goto ai_cmd_exit;
775
776         /* set current channel of the running acquisition to zero */
777         s->async->cur_chan = 0;
778
779         devpriv->dux_commands[1] = len;
780         for (i = 0; i < len; ++i) {
781                 unsigned int chan = CR_CHAN(cmd->chanlist[i]);
782                 unsigned int range = CR_RANGE(cmd->chanlist[i]);
783
784                 if (i >= NUMCHANNELS)
785                         break;
786
787                 devpriv->dux_commands[i + 2] = create_adc_command(chan, range);
788         }
789
790         ret = send_dux_commands(dev, SENDADCOMMANDS);
791         if (ret < 0)
792                 goto ai_cmd_exit;
793
794         if (devpriv->high_speed) {
795                 /*
796                  * every channel gets a time window of 125us. Thus, if we
797                  * sample all 8 channels we need 1ms. If we sample only one
798                  * channel we need only 125us
799                  */
800                 devpriv->ai_interval = 1;
801                 /* find a power of 2 for the interval */
802                 while (devpriv->ai_interval < len)
803                         devpriv->ai_interval *= 2;
804
805                 devpriv->ai_timer = cmd->scan_begin_arg /
806                                     (125000 * devpriv->ai_interval);
807         } else {
808                 /* interval always 1ms */
809                 devpriv->ai_interval = 1;
810                 devpriv->ai_timer = cmd->scan_begin_arg / 1000000;
811         }
812         if (devpriv->ai_timer < 1) {
813                 ret = -EINVAL;
814                 goto ai_cmd_exit;
815         }
816
817         devpriv->ai_counter = devpriv->ai_timer;
818
819         if (cmd->stop_src == TRIG_COUNT) {
820                 /* data arrives as one packet */
821                 devpriv->ai_sample_count = cmd->stop_arg;
822                 devpriv->ai_continous = 0;
823         } else {
824                 /* continous acquisition */
825                 devpriv->ai_continous = 1;
826                 devpriv->ai_sample_count = 0;
827         }
828
829         if (cmd->start_src == TRIG_NOW) {
830                 /* enable this acquisition operation */
831                 devpriv->ai_cmd_running = 1;
832                 ret = usbduxsub_submit_inurbs(dev);
833                 if (ret < 0) {
834                         devpriv->ai_cmd_running = 0;
835                         /* fixme: unlink here?? */
836                         goto ai_cmd_exit;
837                 }
838                 s->async->inttrig = NULL;
839         } else {
840                 /* TRIG_INT */
841                 /* don't enable the acquision operation */
842                 /* wait for an internal signal */
843                 s->async->inttrig = usbdux_ai_inttrig;
844         }
845
846 ai_cmd_exit:
847         up(&devpriv->sem);
848
849         return ret;
850 }
851
852 /* Mode 0 is used to get a single conversion on demand */
853 static int usbdux_ai_insn_read(struct comedi_device *dev,
854                                struct comedi_subdevice *s,
855                                struct comedi_insn *insn,
856                                unsigned int *data)
857 {
858         struct usbdux_private *devpriv = dev->private;
859         unsigned int chan = CR_CHAN(insn->chanspec);
860         unsigned int range = CR_RANGE(insn->chanspec);
861         unsigned int val;
862         int ret = -EBUSY;
863         int i;
864
865         down(&devpriv->sem);
866
867         if (devpriv->ai_cmd_running)
868                 goto ai_read_exit;
869
870         /* set command for the first channel */
871         devpriv->dux_commands[1] = create_adc_command(chan, range);
872
873         /* adc commands */
874         ret = send_dux_commands(dev, SENDSINGLEAD);
875         if (ret < 0)
876                 goto ai_read_exit;
877
878         for (i = 0; i < insn->n; i++) {
879                 ret = receive_dux_commands(dev, SENDSINGLEAD);
880                 if (ret < 0)
881                         goto ai_read_exit;
882
883                 val = le16_to_cpu(devpriv->insn_buffer[1]);
884
885                 /* bipolar data is two's-complement */
886                 if (comedi_range_is_bipolar(s, range))
887                         val ^= ((s->maxdata + 1) >> 1);
888
889                 data[i] = val;
890         }
891
892 ai_read_exit:
893         up(&devpriv->sem);
894
895         return ret ? ret : insn->n;
896 }
897
898 static int usbdux_ao_insn_read(struct comedi_device *dev,
899                                struct comedi_subdevice *s,
900                                struct comedi_insn *insn,
901                                unsigned int *data)
902 {
903         struct usbdux_private *devpriv = dev->private;
904         unsigned int chan = CR_CHAN(insn->chanspec);
905         int i;
906
907         down(&devpriv->sem);
908         for (i = 0; i < insn->n; i++)
909                 data[i] = devpriv->out_buffer[chan];
910         up(&devpriv->sem);
911
912         return insn->n;
913 }
914
915 static int usbdux_ao_insn_write(struct comedi_device *dev,
916                                 struct comedi_subdevice *s,
917                                 struct comedi_insn *insn,
918                                 unsigned int *data)
919 {
920         struct usbdux_private *devpriv = dev->private;
921         unsigned int chan = CR_CHAN(insn->chanspec);
922         unsigned int val = devpriv->out_buffer[chan];
923         int16_t *p = (int16_t *)&devpriv->dux_commands[2];
924         int ret = -EBUSY;
925         int i;
926
927         down(&devpriv->sem);
928
929         if (devpriv->ao_cmd_running)
930                 goto ao_write_exit;
931
932         /* number of channels: 1 */
933         devpriv->dux_commands[1] = 1;
934         /* channel number */
935         devpriv->dux_commands[4] = chan << 6;
936
937         for (i = 0; i < insn->n; i++) {
938                 val = data[i];
939
940                 /* one 16 bit value */
941                 *p = cpu_to_le16(val);
942
943                 ret = send_dux_commands(dev, SENDDACOMMANDS);
944                 if (ret < 0)
945                         goto ao_write_exit;
946         }
947         devpriv->out_buffer[chan] = val;
948
949 ao_write_exit:
950         up(&devpriv->sem);
951
952         return ret ? ret : insn->n;
953 }
954
955 static int usbdux_ao_inttrig(struct comedi_device *dev,
956                              struct comedi_subdevice *s,
957                              unsigned int trignum)
958 {
959         struct usbdux_private *devpriv = dev->private;
960         int ret = -EINVAL;
961
962         down(&devpriv->sem);
963
964         if (trignum != 0)
965                 goto ao_trig_exit;
966
967         if (!devpriv->ao_cmd_running) {
968                 devpriv->ao_cmd_running = 1;
969                 ret = usbduxsub_submit_outurbs(dev);
970                 if (ret < 0) {
971                         devpriv->ao_cmd_running = 0;
972                         goto ao_trig_exit;
973                 }
974                 s->async->inttrig = NULL;
975         } else {
976                 ret = -EBUSY;
977         }
978
979 ao_trig_exit:
980         up(&devpriv->sem);
981         return ret;
982 }
983
984 static int usbdux_ao_cmdtest(struct comedi_device *dev,
985                              struct comedi_subdevice *s, struct comedi_cmd *cmd)
986 {
987         struct usbdux_private *this_usbduxsub = dev->private;
988         int err = 0;
989         unsigned int flags;
990
991         if (!this_usbduxsub)
992                 return -EFAULT;
993
994         /* Step 1 : check if triggers are trivially valid */
995
996         err |= cfc_check_trigger_src(&cmd->start_src, TRIG_NOW | TRIG_INT);
997
998         if (0) {                /* (this_usbduxsub->high_speed) */
999                 /* the sampling rate is set by the coversion rate */
1000                 flags = TRIG_FOLLOW;
1001         } else {
1002                 /* start a new scan (output at once) with a timer */
1003                 flags = TRIG_TIMER;
1004         }
1005         err |= cfc_check_trigger_src(&cmd->scan_begin_src, flags);
1006
1007         if (0) {                /* (this_usbduxsub->high_speed) */
1008                 /*
1009                  * in usb-2.0 only one conversion it transmitted
1010                  * but with 8kHz/n
1011                  */
1012                 flags = TRIG_TIMER;
1013         } else {
1014                 /*
1015                  * all conversion events happen simultaneously with
1016                  * a rate of 1kHz/n
1017                  */
1018                 flags = TRIG_NOW;
1019         }
1020         err |= cfc_check_trigger_src(&cmd->convert_src, flags);
1021
1022         err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
1023         err |= cfc_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
1024
1025         if (err)
1026                 return 1;
1027
1028         /* Step 2a : make sure trigger sources are unique */
1029
1030         err |= cfc_check_trigger_is_unique(cmd->start_src);
1031         err |= cfc_check_trigger_is_unique(cmd->stop_src);
1032
1033         /* Step 2b : and mutually compatible */
1034
1035         if (err)
1036                 return 2;
1037
1038         /* Step 3: check if arguments are trivially valid */
1039
1040         err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);
1041
1042         if (cmd->scan_begin_src == TRIG_FOLLOW) /* internal trigger */
1043                 err |= cfc_check_trigger_arg_is(&cmd->scan_begin_arg, 0);
1044
1045         if (cmd->scan_begin_src == TRIG_TIMER)
1046                 err |= cfc_check_trigger_arg_min(&cmd->scan_begin_arg,
1047                                                  1000000);
1048
1049         /* not used now, is for later use */
1050         if (cmd->convert_src == TRIG_TIMER)
1051                 err |= cfc_check_trigger_arg_min(&cmd->convert_arg, 125000);
1052
1053         err |= cfc_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len);
1054
1055         if (cmd->stop_src == TRIG_COUNT) {
1056                 /* any count is allowed */
1057         } else {
1058                 /* TRIG_NONE */
1059                 err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
1060         }
1061
1062         if (err)
1063                 return 3;
1064
1065         return 0;
1066 }
1067
1068 static int usbdux_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
1069 {
1070         struct usbdux_private *devpriv = dev->private;
1071         struct comedi_cmd *cmd = &s->async->cmd;
1072         int ret = -EBUSY;
1073         int i;
1074
1075         down(&devpriv->sem);
1076
1077         if (devpriv->ao_cmd_running)
1078                 goto ao_cmd_exit;
1079
1080         /* set current channel of the running acquisition to zero */
1081         s->async->cur_chan = 0;
1082
1083         for (i = 0; i < cmd->chanlist_len; ++i) {
1084                 unsigned int chan = CR_CHAN(cmd->chanlist[i]);
1085
1086                 if (i >= NUMOUTCHANNELS)
1087                         break;
1088
1089                 devpriv->dac_commands[i] = chan << 6;
1090         }
1091
1092         /* we count in steps of 1ms (125us) */
1093         /* 125us mode not used yet */
1094         if (0) {                /* (devpriv->high_speed) */
1095                 /* 125us */
1096                 /* timing of the conversion itself: every 125 us */
1097                 devpriv->ao_timer = cmd->convert_arg / 125000;
1098         } else {
1099                 /* 1ms */
1100                 /* timing of the scan: we get all channels at once */
1101                 devpriv->ao_timer = cmd->scan_begin_arg / 1000000;
1102                 if (devpriv->ao_timer < 1) {
1103                         ret = -EINVAL;
1104                         goto ao_cmd_exit;
1105                 }
1106         }
1107
1108         devpriv->ao_counter = devpriv->ao_timer;
1109
1110         if (cmd->stop_src == TRIG_COUNT) {
1111                 /* not continuous */
1112                 /* counter */
1113                 /* high speed also scans everything at once */
1114                 if (0) {        /* (devpriv->high_speed) */
1115                         devpriv->ao_sample_count = cmd->stop_arg *
1116                                                    cmd->scan_end_arg;
1117                 } else {
1118                         /* there's no scan as the scan has been */
1119                         /* perf inside the FX2 */
1120                         /* data arrives as one packet */
1121                         devpriv->ao_sample_count = cmd->stop_arg;
1122                 }
1123                 devpriv->ao_continous = 0;
1124         } else {
1125                 /* continous acquisition */
1126                 devpriv->ao_continous = 1;
1127                 devpriv->ao_sample_count = 0;
1128         }
1129
1130         if (cmd->start_src == TRIG_NOW) {
1131                 /* enable this acquisition operation */
1132                 devpriv->ao_cmd_running = 1;
1133                 ret = usbduxsub_submit_outurbs(dev);
1134                 if (ret < 0) {
1135                         devpriv->ao_cmd_running = 0;
1136                         /* fixme: unlink here?? */
1137                         goto ao_cmd_exit;
1138                 }
1139                 s->async->inttrig = NULL;
1140         } else {
1141                 /* TRIG_INT */
1142                 /* submit the urbs later */
1143                 /* wait for an internal signal */
1144                 s->async->inttrig = usbdux_ao_inttrig;
1145         }
1146
1147 ao_cmd_exit:
1148         up(&devpriv->sem);
1149
1150         return ret;
1151 }
1152
1153 static int usbdux_dio_insn_config(struct comedi_device *dev,
1154                                   struct comedi_subdevice *s,
1155                                   struct comedi_insn *insn,
1156                                   unsigned int *data)
1157 {
1158         unsigned int mask = 1 << CR_CHAN(insn->chanspec);
1159
1160         switch (data[0]) {
1161         case INSN_CONFIG_DIO_OUTPUT:
1162                 s->io_bits |= mask;
1163                 break;
1164         case INSN_CONFIG_DIO_INPUT:
1165                 s->io_bits &= ~mask;
1166                 break;
1167         case INSN_CONFIG_DIO_QUERY:
1168                 data[1] = (s->io_bits & mask) ? COMEDI_OUTPUT : COMEDI_INPUT;
1169                 break;
1170         default:
1171                 return -EINVAL;
1172                 break;
1173         }
1174
1175         /*
1176          * We don't tell the firmware here as it would take 8 frames
1177          * to submit the information. We do it in the insn_bits.
1178          */
1179         return insn->n;
1180 }
1181
1182 static int usbdux_dio_insn_bits(struct comedi_device *dev,
1183                                 struct comedi_subdevice *s,
1184                                 struct comedi_insn *insn,
1185                                 unsigned int *data)
1186 {
1187
1188         struct usbdux_private *devpriv = dev->private;
1189         unsigned int mask = data[0];
1190         unsigned int bits = data[1];
1191         int ret;
1192
1193         down(&devpriv->sem);
1194
1195         s->state &= ~mask;
1196         s->state |= (bits & mask);
1197
1198         devpriv->dux_commands[1] = s->io_bits;
1199         devpriv->dux_commands[2] = s->state;
1200
1201         /*
1202          * This command also tells the firmware to return
1203          * the digital input lines.
1204          */
1205         ret = send_dux_commands(dev, SENDDIOBITSCOMMAND);
1206         if (ret < 0)
1207                 goto dio_exit;
1208         ret = receive_dux_commands(dev, SENDDIOBITSCOMMAND);
1209         if (ret < 0)
1210                 goto dio_exit;
1211
1212         data[1] = le16_to_cpu(devpriv->insn_buffer[1]);
1213
1214 dio_exit:
1215         up(&devpriv->sem);
1216
1217         return ret ? ret : insn->n;
1218 }
1219
1220 static int usbdux_counter_read(struct comedi_device *dev,
1221                                struct comedi_subdevice *s,
1222                                struct comedi_insn *insn,
1223                                unsigned int *data)
1224 {
1225         struct usbdux_private *devpriv = dev->private;
1226         unsigned int chan = CR_CHAN(insn->chanspec);
1227         int ret = 0;
1228         int i;
1229
1230         down(&devpriv->sem);
1231
1232         for (i = 0; i < insn->n; i++) {
1233                 ret = send_dux_commands(dev, READCOUNTERCOMMAND);
1234                 if (ret < 0)
1235                         goto counter_read_exit;
1236                 ret = receive_dux_commands(dev, READCOUNTERCOMMAND);
1237                 if (ret < 0)
1238                         goto counter_read_exit;
1239
1240                 data[i] = le16_to_cpu(devpriv->insn_buffer[chan + 1]);
1241         }
1242
1243 counter_read_exit:
1244         up(&devpriv->sem);
1245
1246         return ret ? ret : insn->n;
1247 }
1248
1249 static int usbdux_counter_write(struct comedi_device *dev,
1250                                 struct comedi_subdevice *s,
1251                                 struct comedi_insn *insn,
1252                                 unsigned int *data)
1253 {
1254         struct usbdux_private *devpriv = dev->private;
1255         unsigned int chan = CR_CHAN(insn->chanspec);
1256         int16_t *p = (int16_t *)&devpriv->dux_commands[2];
1257         int ret = 0;
1258         int i;
1259
1260         down(&devpriv->sem);
1261
1262         devpriv->dux_commands[1] = chan;
1263
1264         for (i = 0; i < insn->n; i++) {
1265                 *p = cpu_to_le16(data[i]);
1266
1267                 ret = send_dux_commands(dev, WRITECOUNTERCOMMAND);
1268                 if (ret < 0)
1269                         break;
1270         }
1271
1272         up(&devpriv->sem);
1273
1274         return ret ? ret : insn->n;
1275 }
1276
1277 static int usbdux_counter_config(struct comedi_device *dev,
1278                                  struct comedi_subdevice *s,
1279                                  struct comedi_insn *insn, unsigned int *data)
1280 {
1281         /* nothing to do so far */
1282         return 2;
1283 }
1284
1285 static void usbduxsub_unlink_pwm_urbs(struct comedi_device *dev)
1286 {
1287         struct usbdux_private *devpriv = dev->private;
1288
1289         usb_kill_urb(devpriv->urb_pwm);
1290 }
1291
1292 static void usbdux_pwm_stop(struct comedi_device *dev, int do_unlink)
1293 {
1294         struct usbdux_private *devpriv = dev->private;
1295
1296         if (do_unlink)
1297                 usbduxsub_unlink_pwm_urbs(dev);
1298
1299         devpriv->pwm_cmd_running = 0;
1300 }
1301
1302 static int usbdux_pwm_cancel(struct comedi_device *dev,
1303                              struct comedi_subdevice *s)
1304 {
1305         struct usbdux_private *devpriv = dev->private;
1306         int ret;
1307
1308         down(&devpriv->sem);
1309         /* unlink only if it is really running */
1310         usbdux_pwm_stop(dev, devpriv->pwm_cmd_running);
1311         ret = send_dux_commands(dev, SENDPWMOFF);
1312         up(&devpriv->sem);
1313
1314         return ret;
1315 }
1316
1317 static void usbduxsub_pwm_irq(struct urb *urb)
1318 {
1319         struct comedi_device *dev = urb->context;
1320         struct usbdux_private *devpriv = dev->private;
1321         int ret;
1322
1323         switch (urb->status) {
1324         case 0:
1325                 /* success */
1326                 break;
1327
1328         case -ECONNRESET:
1329         case -ENOENT:
1330         case -ESHUTDOWN:
1331         case -ECONNABORTED:
1332                 /*
1333                  * after an unlink command, unplug, ... etc
1334                  * no unlink needed here. Already shutting down.
1335                  */
1336                 if (devpriv->pwm_cmd_running)
1337                         usbdux_pwm_stop(dev, 0);
1338
1339                 return;
1340
1341         default:
1342                 /* a real error */
1343                 if (devpriv->pwm_cmd_running) {
1344                         dev_err(dev->class_dev,
1345                                 "Non-zero urb status received in pwm intr context: %d\n",
1346                                 urb->status);
1347                         usbdux_pwm_stop(dev, 0);
1348                 }
1349                 return;
1350         }
1351
1352         /* are we actually running? */
1353         if (!devpriv->pwm_cmd_running)
1354                 return;
1355
1356         urb->transfer_buffer_length = devpriv->size_pwm_buf;
1357         urb->dev = comedi_to_usb_dev(dev);
1358         urb->status = 0;
1359         if (devpriv->pwm_cmd_running) {
1360                 ret = usb_submit_urb(urb, GFP_ATOMIC);
1361                 if (ret < 0) {
1362                         dev_err(dev->class_dev,
1363                                 "pwm urb resubm failed in int-cont. ret=%d",
1364                                 ret);
1365                         if (ret == EL2NSYNC)
1366                                 dev_err(dev->class_dev,
1367                                         "buggy USB host controller or bug in IRQ handling!\n");
1368
1369                         /* don't do an unlink here */
1370                         usbdux_pwm_stop(dev, 0);
1371                 }
1372         }
1373 }
1374
1375 static int usbduxsub_submit_pwm_urbs(struct comedi_device *dev)
1376 {
1377         struct usb_device *usb = comedi_to_usb_dev(dev);
1378         struct usbdux_private *devpriv = dev->private;
1379         struct urb *urb = devpriv->urb_pwm;
1380
1381         /* in case of a resubmission after an unlink... */
1382         usb_fill_bulk_urb(urb, usb, usb_sndbulkpipe(usb, 4),
1383                           urb->transfer_buffer,
1384                           devpriv->size_pwm_buf,
1385                           usbduxsub_pwm_irq,
1386                           dev);
1387
1388         return usb_submit_urb(urb, GFP_ATOMIC);
1389 }
1390
1391 static int usbdux_pwm_period(struct comedi_device *dev,
1392                              struct comedi_subdevice *s, unsigned int period)
1393 {
1394         struct usbdux_private *this_usbduxsub = dev->private;
1395         int fx2delay = 255;
1396
1397         if (period < MIN_PWM_PERIOD) {
1398                 return -EAGAIN;
1399         } else {
1400                 fx2delay = period / ((int)(6 * 512 * (1.0 / 0.033))) - 6;
1401                 if (fx2delay > 255)
1402                         return -EAGAIN;
1403         }
1404         this_usbduxsub->pwn_delay = fx2delay;
1405         this_usbduxsub->pwm_period = period;
1406
1407         return 0;
1408 }
1409
1410 static int usbdux_pwm_start(struct comedi_device *dev,
1411                             struct comedi_subdevice *s)
1412 {
1413         struct usbdux_private *devpriv = dev->private;
1414         int ret = 0;
1415
1416         down(&devpriv->sem);
1417
1418         if (devpriv->pwm_cmd_running)
1419                 goto pwm_start_exit;
1420
1421         devpriv->dux_commands[1] = devpriv->pwn_delay;
1422         ret = send_dux_commands(dev, SENDPWMON);
1423         if (ret < 0)
1424                 goto pwm_start_exit;
1425
1426         /* initialise the buffer */
1427         memset(devpriv->urb_pwm->transfer_buffer, 0, devpriv->size_pwm_buf);
1428
1429         devpriv->pwm_cmd_running = 1;
1430         ret = usbduxsub_submit_pwm_urbs(dev);
1431         if (ret < 0)
1432                 devpriv->pwm_cmd_running = 0;
1433
1434 pwm_start_exit:
1435         up(&devpriv->sem);
1436
1437         return ret;
1438 }
1439
1440 /* generates the bit pattern for PWM with the optional sign bit */
1441 static int usbdux_pwm_pattern(struct comedi_device *dev,
1442                               struct comedi_subdevice *s, int channel,
1443                               unsigned int value, unsigned int sign)
1444 {
1445         struct usbdux_private *this_usbduxsub = dev->private;
1446         int i, szbuf;
1447         char *p_buf;
1448         char pwm_mask;
1449         char sgn_mask;
1450         char c;
1451
1452         if (!this_usbduxsub)
1453                 return -EFAULT;
1454
1455         /* this is the DIO bit which carries the PWM data */
1456         pwm_mask = (1 << channel);
1457         /* this is the DIO bit which carries the optional direction bit */
1458         sgn_mask = (16 << channel);
1459         /* this is the buffer which will be filled with the with bit */
1460         /* pattern for one period */
1461         szbuf = this_usbduxsub->size_pwm_buf;
1462         p_buf = (char *)(this_usbduxsub->urb_pwm->transfer_buffer);
1463         for (i = 0; i < szbuf; i++) {
1464                 c = *p_buf;
1465                 /* reset bits */
1466                 c = c & (~pwm_mask);
1467                 /* set the bit as long as the index is lower than the value */
1468                 if (i < value)
1469                         c = c | pwm_mask;
1470                 /* set the optional sign bit for a relay */
1471                 if (!sign) {
1472                         /* positive value */
1473                         c = c & (~sgn_mask);
1474                 } else {
1475                         /* negative value */
1476                         c = c | sgn_mask;
1477                 }
1478                 *(p_buf++) = c;
1479         }
1480         return 1;
1481 }
1482
1483 static int usbdux_pwm_write(struct comedi_device *dev,
1484                             struct comedi_subdevice *s,
1485                             struct comedi_insn *insn, unsigned int *data)
1486 {
1487         struct usbdux_private *this_usbduxsub = dev->private;
1488
1489         if (!this_usbduxsub)
1490                 return -EFAULT;
1491
1492         if ((insn->n) != 1) {
1493                 /*
1494                  * doesn't make sense to have more than one value here because
1495                  * it would just overwrite the PWM buffer a couple of times
1496                  */
1497                 return -EINVAL;
1498         }
1499
1500         /*
1501          * the sign is set via a special INSN only, this gives us 8 bits for
1502          * normal operation
1503          * relay sign 0 by default
1504          */
1505         return usbdux_pwm_pattern(dev, s, CR_CHAN(insn->chanspec), data[0], 0);
1506 }
1507
1508 static int usbdux_pwm_read(struct comedi_device *x1,
1509                            struct comedi_subdevice *x2, struct comedi_insn *x3,
1510                            unsigned int *x4)
1511 {
1512         /* not needed */
1513         return -EINVAL;
1514 };
1515
1516 /* switches on/off PWM */
1517 static int usbdux_pwm_config(struct comedi_device *dev,
1518                              struct comedi_subdevice *s,
1519                              struct comedi_insn *insn, unsigned int *data)
1520 {
1521         struct usbdux_private *this_usbduxsub = dev->private;
1522         switch (data[0]) {
1523         case INSN_CONFIG_ARM:
1524                 /* switch it on */
1525                 /*
1526                  * if not zero the PWM is limited to a certain time which is
1527                  * not supported here
1528                  */
1529                 if (data[1] != 0)
1530                         return -EINVAL;
1531                 return usbdux_pwm_start(dev, s);
1532         case INSN_CONFIG_DISARM:
1533                 return usbdux_pwm_cancel(dev, s);
1534         case INSN_CONFIG_GET_PWM_STATUS:
1535                 /*
1536                  * to check if the USB transmission has failed or in case PWM
1537                  * was limited to n cycles to check if it has terminated
1538                  */
1539                 data[1] = this_usbduxsub->pwm_cmd_running;
1540                 return 0;
1541         case INSN_CONFIG_PWM_SET_PERIOD:
1542                 return usbdux_pwm_period(dev, s, data[1]);
1543         case INSN_CONFIG_PWM_GET_PERIOD:
1544                 data[1] = this_usbduxsub->pwm_period;
1545                 return 0;
1546         case INSN_CONFIG_PWM_SET_H_BRIDGE:
1547                 /* value in the first byte and the sign in the second for a
1548                    relay */
1549                 return usbdux_pwm_pattern(dev, s,
1550                                           /* the channel number */
1551                                           CR_CHAN(insn->chanspec),
1552                                           /* actual PWM data */
1553                                           data[1],
1554                                           /* just a sign */
1555                                           (data[2] != 0));
1556         case INSN_CONFIG_PWM_GET_H_BRIDGE:
1557                 /* values are not kept in this driver, nothing to return here */
1558                 return -EINVAL;
1559         }
1560         return -EINVAL;
1561 }
1562
1563 static int usbdux_firmware_upload(struct comedi_device *dev,
1564                                   const u8 *data, size_t size,
1565                                   unsigned long context)
1566 {
1567         struct usb_device *usb = comedi_to_usb_dev(dev);
1568         uint8_t *buf;
1569         uint8_t *tmp;
1570         int ret;
1571
1572         if (!data)
1573                 return 0;
1574
1575         if (size > USBDUX_FIRMWARE_MAX_LEN) {
1576                 dev_err(dev->class_dev,
1577                         "usbdux firmware binary it too large for FX2.\n");
1578                 return -ENOMEM;
1579         }
1580
1581         /* we generate a local buffer for the firmware */
1582         buf = kmemdup(data, size, GFP_KERNEL);
1583         if (!buf)
1584                 return -ENOMEM;
1585
1586         /* we need a malloc'ed buffer for usb_control_msg() */
1587         tmp = kmalloc(1, GFP_KERNEL);
1588         if (!tmp) {
1589                 kfree(buf);
1590                 return -ENOMEM;
1591         }
1592
1593         /* stop the current firmware on the device */
1594         *tmp = 1;       /* 7f92 to one */
1595         ret = usb_control_msg(usb, usb_sndctrlpipe(usb, 0),
1596                               USBDUX_FIRMWARE_CMD,
1597                               VENDOR_DIR_OUT,
1598                               USBDUX_CPU_CS, 0x0000,
1599                               tmp, 1,
1600                               BULK_TIMEOUT);
1601         if (ret < 0) {
1602                 dev_err(dev->class_dev, "can not stop firmware\n");
1603                 goto done;
1604         }
1605
1606         /* upload the new firmware to the device */
1607         ret = usb_control_msg(usb, usb_sndctrlpipe(usb, 0),
1608                               USBDUX_FIRMWARE_CMD,
1609                               VENDOR_DIR_OUT,
1610                               0, 0x0000,
1611                               buf, size,
1612                               BULK_TIMEOUT);
1613         if (ret < 0) {
1614                 dev_err(dev->class_dev, "firmware upload failed\n");
1615                 goto done;
1616         }
1617
1618         /* start the new firmware on the device */
1619         *tmp = 0;       /* 7f92 to zero */
1620         ret = usb_control_msg(usb, usb_sndctrlpipe(usb, 0),
1621                               USBDUX_FIRMWARE_CMD,
1622                               VENDOR_DIR_OUT,
1623                               USBDUX_CPU_CS, 0x0000,
1624                               tmp, 1,
1625                               BULK_TIMEOUT);
1626         if (ret < 0)
1627                 dev_err(dev->class_dev, "can not start firmware\n");
1628
1629 done:
1630         kfree(tmp);
1631         kfree(buf);
1632         return ret;
1633 }
1634
1635 static int usbdux_alloc_usb_buffers(struct comedi_device *dev)
1636 {
1637         struct usb_device *usb = comedi_to_usb_dev(dev);
1638         struct usbdux_private *devpriv = dev->private;
1639         struct urb *urb;
1640         int i;
1641
1642         /* create space for the commands of the DA converter */
1643         devpriv->dac_commands = kzalloc(NUMOUTCHANNELS, GFP_KERNEL);
1644         if (!devpriv->dac_commands)
1645                 return -ENOMEM;
1646
1647         /* create space for the commands going to the usb device */
1648         devpriv->dux_commands = kzalloc(SIZEOFDUXBUFFER, GFP_KERNEL);
1649         if (!devpriv->dux_commands)
1650                 return -ENOMEM;
1651
1652         /* create space for the in buffer and set it to zero */
1653         devpriv->in_buffer = kzalloc(SIZEINBUF, GFP_KERNEL);
1654         if (!devpriv->in_buffer)
1655                 return -ENOMEM;
1656
1657         /* create space of the instruction buffer */
1658         devpriv->insn_buffer = kzalloc(SIZEINSNBUF, GFP_KERNEL);
1659         if (!devpriv->insn_buffer)
1660                 return -ENOMEM;
1661
1662         /* create space for the outbuffer */
1663         devpriv->out_buffer = kzalloc(SIZEOUTBUF, GFP_KERNEL);
1664         if (!devpriv->out_buffer)
1665                 return -ENOMEM;
1666
1667         /* in urbs */
1668         devpriv->urb_in = kcalloc(devpriv->num_in_buffers, sizeof(*urb),
1669                                   GFP_KERNEL);
1670         if (!devpriv->urb_in)
1671                 return -ENOMEM;
1672
1673         for (i = 0; i < devpriv->num_in_buffers; i++) {
1674                 /* one frame: 1ms */
1675                 urb = usb_alloc_urb(1, GFP_KERNEL);
1676                 if (!urb)
1677                         return -ENOMEM;
1678                 devpriv->urb_in[i] = urb;
1679
1680                 urb->dev = usb;
1681                 /* will be filled later with a pointer to the comedi-device */
1682                 /* and ONLY then the urb should be submitted */
1683                 urb->context = NULL;
1684                 urb->pipe = usb_rcvisocpipe(usb, 6);
1685                 urb->transfer_flags = URB_ISO_ASAP;
1686                 urb->transfer_buffer = kzalloc(SIZEINBUF, GFP_KERNEL);
1687                 if (!urb->transfer_buffer)
1688                         return -ENOMEM;
1689
1690                 urb->complete = usbduxsub_ai_isoc_irq;
1691                 urb->number_of_packets = 1;
1692                 urb->transfer_buffer_length = SIZEINBUF;
1693                 urb->iso_frame_desc[0].offset = 0;
1694                 urb->iso_frame_desc[0].length = SIZEINBUF;
1695         }
1696
1697         /* out urbs */
1698         devpriv->urb_out = kcalloc(devpriv->num_out_buffers, sizeof(*urb),
1699                                    GFP_KERNEL);
1700         if (!devpriv->urb_out)
1701                 return -ENOMEM;
1702
1703         for (i = 0; i < devpriv->num_out_buffers; i++) {
1704                 /* one frame: 1ms */
1705                 urb = usb_alloc_urb(1, GFP_KERNEL);
1706                 if (!urb)
1707                         return -ENOMEM;
1708                 devpriv->urb_out[i] = urb;
1709
1710                 urb->dev = usb;
1711                 /* will be filled later with a pointer to the comedi-device */
1712                 /* and ONLY then the urb should be submitted */
1713                 urb->context = NULL;
1714                 urb->pipe = usb_sndisocpipe(usb, 2);
1715                 urb->transfer_flags = URB_ISO_ASAP;
1716                 urb->transfer_buffer = kzalloc(SIZEOUTBUF, GFP_KERNEL);
1717                 if (!urb->transfer_buffer)
1718                         return -ENOMEM;
1719
1720                 urb->complete = usbduxsub_ao_isoc_irq;
1721                 urb->number_of_packets = 1;
1722                 urb->transfer_buffer_length = SIZEOUTBUF;
1723                 urb->iso_frame_desc[0].offset = 0;
1724                 urb->iso_frame_desc[0].length = SIZEOUTBUF;
1725                 if (devpriv->high_speed)
1726                         urb->interval = 8;      /* uframes */
1727                 else
1728                         urb->interval = 1;      /* frames */
1729         }
1730
1731         /* pwm */
1732         if (devpriv->size_pwm_buf) {
1733                 urb = usb_alloc_urb(0, GFP_KERNEL);
1734                 if (!urb)
1735                         return -ENOMEM;
1736                 devpriv->urb_pwm = urb;
1737
1738                 /* max bulk ep size in high speed */
1739                 urb->transfer_buffer = kzalloc(devpriv->size_pwm_buf,
1740                                                GFP_KERNEL);
1741                 if (!urb->transfer_buffer)
1742                         return -ENOMEM;
1743         }
1744
1745         return 0;
1746 }
1747
1748 static void usbdux_free_usb_buffers(struct usbdux_private *devpriv)
1749 {
1750         struct urb *urb;
1751         int i;
1752
1753         urb = devpriv->urb_pwm;
1754         if (urb) {
1755                 kfree(urb->transfer_buffer);
1756                 usb_kill_urb(urb);
1757                 usb_free_urb(urb);
1758         }
1759         if (devpriv->urb_out) {
1760                 for (i = 0; i < devpriv->num_out_buffers; i++) {
1761                         urb = devpriv->urb_out[i];
1762                         if (urb) {
1763                                 kfree(urb->transfer_buffer);
1764                                 usb_kill_urb(urb);
1765                                 usb_free_urb(urb);
1766                         }
1767                 }
1768                 kfree(devpriv->urb_out);
1769         }
1770         if (devpriv->urb_in) {
1771                 for (i = 0; i < devpriv->num_in_buffers; i++) {
1772                         urb = devpriv->urb_in[i];
1773                         if (urb) {
1774                                 kfree(urb->transfer_buffer);
1775                                 usb_kill_urb(urb);
1776                                 usb_free_urb(urb);
1777                         }
1778                 }
1779                 kfree(devpriv->urb_in);
1780         }
1781         kfree(devpriv->out_buffer);
1782         kfree(devpriv->insn_buffer);
1783         kfree(devpriv->in_buffer);
1784         kfree(devpriv->dux_commands);
1785         kfree(devpriv->dac_commands);
1786 }
1787
1788 static int usbdux_auto_attach(struct comedi_device *dev,
1789                               unsigned long context_unused)
1790 {
1791         struct usb_interface *intf = comedi_to_usb_interface(dev);
1792         struct usb_device *usb = comedi_to_usb_dev(dev);
1793         struct usbdux_private *devpriv;
1794         struct comedi_subdevice *s;
1795         int ret;
1796
1797         devpriv = comedi_alloc_devpriv(dev, sizeof(*devpriv));
1798         if (!devpriv)
1799                 return -ENOMEM;
1800
1801         sema_init(&devpriv->sem, 1);
1802
1803         usb_set_intfdata(intf, devpriv);
1804
1805         devpriv->high_speed = (usb->speed == USB_SPEED_HIGH);
1806         if (devpriv->high_speed) {
1807                 devpriv->num_in_buffers = NUMOFINBUFFERSHIGH;
1808                 devpriv->num_out_buffers = NUMOFOUTBUFFERSHIGH;
1809                 devpriv->size_pwm_buf = 512;
1810         } else {
1811                 devpriv->num_in_buffers = NUMOFINBUFFERSFULL;
1812                 devpriv->num_out_buffers = NUMOFOUTBUFFERSFULL;
1813         }
1814
1815         ret = usbdux_alloc_usb_buffers(dev);
1816         if (ret)
1817                 return ret;
1818
1819         /* setting to alternate setting 3: enabling iso ep and bulk ep. */
1820         ret = usb_set_interface(usb, intf->altsetting->desc.bInterfaceNumber,
1821                                 3);
1822         if (ret < 0) {
1823                 dev_err(dev->class_dev,
1824                         "could not set alternate setting 3 in high speed\n");
1825                 return ret;
1826         }
1827
1828         ret = comedi_load_firmware(dev, &usb->dev, USBDUX_FIRMWARE,
1829                                    usbdux_firmware_upload, 0);
1830         if (ret < 0)
1831                 return ret;
1832
1833         ret = comedi_alloc_subdevices(dev, (devpriv->high_speed) ? 5 : 4);
1834         if (ret)
1835                 return ret;
1836
1837         /* Analog Input subdevice */
1838         s = &dev->subdevices[0];
1839         dev->read_subdev = s;
1840         s->type         = COMEDI_SUBD_AI;
1841         s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_CMD_READ;
1842         s->n_chan       = 8;
1843         s->maxdata      = 0x0fff;
1844         s->len_chanlist = 8;
1845         s->range_table  = &range_usbdux_ai_range;
1846         s->insn_read    = usbdux_ai_insn_read;
1847         s->do_cmdtest   = usbdux_ai_cmdtest;
1848         s->do_cmd       = usbdux_ai_cmd;
1849         s->cancel       = usbdux_ai_cancel;
1850
1851         /* Analog Output subdevice */
1852         s = &dev->subdevices[1];
1853         dev->write_subdev = s;
1854         s->type         = COMEDI_SUBD_AO;
1855         s->subdev_flags = SDF_WRITABLE | SDF_GROUND | SDF_CMD_WRITE;
1856         s->n_chan       = 4;
1857         s->maxdata      = 0x0fff;
1858         s->len_chanlist = 4;
1859         s->range_table  = &range_usbdux_ao_range;
1860         s->do_cmdtest   = usbdux_ao_cmdtest;
1861         s->do_cmd       = usbdux_ao_cmd;
1862         s->cancel       = usbdux_ao_cancel;
1863         s->insn_read    = usbdux_ao_insn_read;
1864         s->insn_write   = usbdux_ao_insn_write;
1865
1866         /* Digital I/O subdevice */
1867         s = &dev->subdevices[2];
1868         s->type         = COMEDI_SUBD_DIO;
1869         s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
1870         s->n_chan       = 8;
1871         s->maxdata      = 1;
1872         s->range_table  = &range_digital;
1873         s->insn_bits    = usbdux_dio_insn_bits;
1874         s->insn_config  = usbdux_dio_insn_config;
1875
1876         /* Counter subdevice */
1877         s = &dev->subdevices[3];
1878         s->type         = COMEDI_SUBD_COUNTER;
1879         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
1880         s->n_chan       = 4;
1881         s->maxdata      = 0xffff;
1882         s->insn_read    = usbdux_counter_read;
1883         s->insn_write   = usbdux_counter_write;
1884         s->insn_config  = usbdux_counter_config;
1885
1886         if (devpriv->high_speed) {
1887                 /* PWM subdevice */
1888                 s = &dev->subdevices[4];
1889                 s->type         = COMEDI_SUBD_PWM;
1890                 s->subdev_flags = SDF_WRITABLE | SDF_PWM_HBRIDGE;
1891                 s->n_chan       = 8;
1892                 s->maxdata      = devpriv->size_pwm_buf;
1893                 s->insn_write   = usbdux_pwm_write;
1894                 s->insn_read    = usbdux_pwm_read;
1895                 s->insn_config  = usbdux_pwm_config;
1896
1897                 usbdux_pwm_period(dev, s, PWM_DEFAULT_PERIOD);
1898         }
1899
1900         return 0;
1901 }
1902
1903 static void usbdux_detach(struct comedi_device *dev)
1904 {
1905         struct usb_interface *intf = comedi_to_usb_interface(dev);
1906         struct usbdux_private *devpriv = dev->private;
1907
1908         if (devpriv) {
1909                 down(&devpriv->sem);
1910
1911                 usb_set_intfdata(intf, NULL);
1912
1913                 /* stop and unlink any submitted urbs */
1914                 usbdux_pwm_stop(dev, devpriv->pwm_cmd_running);
1915                 usbdux_ao_stop(dev, devpriv->ao_cmd_running);
1916                 usbdux_ai_stop(dev, devpriv->ai_cmd_running);
1917
1918                 usbdux_free_usb_buffers(devpriv);
1919
1920                 up(&devpriv->sem);
1921         }
1922 }
1923
1924 static struct comedi_driver usbdux_driver = {
1925         .driver_name    = "usbdux",
1926         .module         = THIS_MODULE,
1927         .auto_attach    = usbdux_auto_attach,
1928         .detach         = usbdux_detach,
1929 };
1930
1931 static int usbdux_usb_probe(struct usb_interface *intf,
1932                             const struct usb_device_id *id)
1933 {
1934         return comedi_usb_auto_config(intf, &usbdux_driver, 0);
1935 }
1936
1937 static const struct usb_device_id usbdux_usb_table[] = {
1938         { USB_DEVICE(0x13d8, 0x0001) },
1939         { USB_DEVICE(0x13d8, 0x0002) },
1940         { }
1941 };
1942 MODULE_DEVICE_TABLE(usb, usbdux_usb_table);
1943
1944 static struct usb_driver usbdux_usb_driver = {
1945         .name           = "usbdux",
1946         .probe          = usbdux_usb_probe,
1947         .disconnect     = comedi_usb_auto_unconfig,
1948         .id_table       = usbdux_usb_table,
1949 };
1950 module_comedi_usb_driver(usbdux_driver, usbdux_usb_driver);
1951
1952 MODULE_AUTHOR("Bernd Porr, BerndPorr@f2s.com");
1953 MODULE_DESCRIPTION("Stirling/ITL USB-DUX -- Bernd.Porr@f2s.com");
1954 MODULE_LICENSE("GPL");
1955 MODULE_FIRMWARE(USBDUX_FIRMWARE);