GNU Linux-libre 4.14.332-gnu1
[releases.git] / drivers / staging / comedi / drivers / s626.c
1 /*
2  * comedi/drivers/s626.c
3  * Sensoray s626 Comedi driver
4  *
5  * COMEDI - Linux Control and Measurement Device Interface
6  * Copyright (C) 2000 David A. Schleef <ds@schleef.org>
7  *
8  * Based on Sensoray Model 626 Linux driver Version 0.2
9  * Copyright (C) 2002-2004 Sensoray Co., Inc.
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  */
21
22 /*
23  * Driver: s626
24  * Description: Sensoray 626 driver
25  * Devices: [Sensoray] 626 (s626)
26  * Authors: Gianluca Palli <gpalli@deis.unibo.it>,
27  * Updated: Fri, 15 Feb 2008 10:28:42 +0000
28  * Status: experimental
29
30  * Configuration options: not applicable, uses PCI auto config
31
32  * INSN_CONFIG instructions:
33  *   analog input:
34  *    none
35  *
36  *   analog output:
37  *    none
38  *
39  *   digital channel:
40  *    s626 has 3 dio subdevices (2,3 and 4) each with 16 i/o channels
41  *    supported configuration options:
42  *    INSN_CONFIG_DIO_QUERY
43  *    COMEDI_INPUT
44  *    COMEDI_OUTPUT
45  *
46  *   encoder:
47  *    Every channel must be configured before reading.
48  *
49  *   Example code
50  *
51  *    insn.insn=INSN_CONFIG;   //configuration instruction
52  *    insn.n=1;                //number of operation (must be 1)
53  *    insn.data=&initialvalue; //initial value loaded into encoder
54  *                             //during configuration
55  *    insn.subdev=5;           //encoder subdevice
56  *    insn.chanspec=CR_PACK(encoder_channel,0,AREF_OTHER); //encoder_channel
57  *                                                         //to configure
58  *
59  *    comedi_do_insn(cf,&insn); //executing configuration
60  */
61
62 #include <linux/module.h>
63 #include <linux/delay.h>
64 #include <linux/interrupt.h>
65 #include <linux/kernel.h>
66 #include <linux/types.h>
67
68 #include "../comedi_pci.h"
69
70 #include "s626.h"
71
72 struct s626_buffer_dma {
73         dma_addr_t physical_base;
74         void *logical_base;
75 };
76
77 /**
78  * struct s626_private - Working data for s626 driver.
79  * @ai_cmd_running: non-zero if ai_cmd is running.
80  * @ai_sample_timer: time between samples in units of the timer.
81  * @ai_convert_count: conversion counter.
82  * @ai_convert_timer: time between conversion in units of the timer.
83  * @counter_int_enabs: counter interrupt enable mask for MISC2 register.
84  * @adc_items: number of items in ADC poll list.
85  * @rps_buf: DMA buffer used to hold ADC (RPS1) program.
86  * @ana_buf:  DMA buffer used to receive ADC data and hold DAC data.
87  * @dac_wbuf: pointer to logical adrs of DMA buffer used to hold DAC data.
88  * @dacpol: image of DAC polarity register.
89  * @trim_setpoint: images of TrimDAC setpoints.
90  * @i2c_adrs: I2C device address for onboard EEPROM (board rev dependent)
91  */
92 struct s626_private {
93         u8 ai_cmd_running;
94         unsigned int ai_sample_timer;
95         int ai_convert_count;
96         unsigned int ai_convert_timer;
97         u16 counter_int_enabs;
98         u8 adc_items;
99         struct s626_buffer_dma rps_buf;
100         struct s626_buffer_dma ana_buf;
101         u32 *dac_wbuf;
102         u16 dacpol;
103         u8 trim_setpoint[12];
104         u32 i2c_adrs;
105 };
106
107 /* Counter overflow/index event flag masks for RDMISC2. */
108 #define S626_INDXMASK(C) (1 << (((C) > 2) ? ((C) * 2 - 1) : ((C) * 2 +  4)))
109 #define S626_OVERMASK(C) (1 << (((C) > 2) ? ((C) * 2 + 5) : ((C) * 2 + 10)))
110
111 /*
112  * Enable/disable a function or test status bit(s) that are accessed
113  * through Main Control Registers 1 or 2.
114  */
115 static void s626_mc_enable(struct comedi_device *dev,
116                            unsigned int cmd, unsigned int reg)
117 {
118         unsigned int val = (cmd << 16) | cmd;
119
120         mmiowb();
121         writel(val, dev->mmio + reg);
122 }
123
124 static void s626_mc_disable(struct comedi_device *dev,
125                             unsigned int cmd, unsigned int reg)
126 {
127         writel(cmd << 16, dev->mmio + reg);
128         mmiowb();
129 }
130
131 static bool s626_mc_test(struct comedi_device *dev,
132                          unsigned int cmd, unsigned int reg)
133 {
134         unsigned int val;
135
136         val = readl(dev->mmio + reg);
137
138         return (val & cmd) ? true : false;
139 }
140
141 #define S626_BUGFIX_STREG(REGADRS)   ((REGADRS) - 4)
142
143 /* Write a time slot control record to TSL2. */
144 #define S626_VECTPORT(VECTNUM)          (S626_P_TSL2 + ((VECTNUM) << 2))
145
146 static const struct comedi_lrange s626_range_table = {
147         2, {
148                 BIP_RANGE(5),
149                 BIP_RANGE(10)
150         }
151 };
152
153 /*
154  * Execute a DEBI transfer.  This must be called from within a critical section.
155  */
156 static void s626_debi_transfer(struct comedi_device *dev)
157 {
158         static const int timeout = 10000;
159         int i;
160
161         /* Initiate upload of shadow RAM to DEBI control register */
162         s626_mc_enable(dev, S626_MC2_UPLD_DEBI, S626_P_MC2);
163
164         /*
165          * Wait for completion of upload from shadow RAM to
166          * DEBI control register.
167          */
168         for (i = 0; i < timeout; i++) {
169                 if (s626_mc_test(dev, S626_MC2_UPLD_DEBI, S626_P_MC2))
170                         break;
171                 udelay(1);
172         }
173         if (i == timeout)
174                 dev_err(dev->class_dev,
175                         "Timeout while uploading to DEBI control register\n");
176
177         /* Wait until DEBI transfer is done */
178         for (i = 0; i < timeout; i++) {
179                 if (!(readl(dev->mmio + S626_P_PSR) & S626_PSR_DEBI_S))
180                         break;
181                 udelay(1);
182         }
183         if (i == timeout)
184                 dev_err(dev->class_dev, "DEBI transfer timeout\n");
185 }
186
187 /*
188  * Read a value from a gate array register.
189  */
190 static u16 s626_debi_read(struct comedi_device *dev, u16 addr)
191 {
192         /* Set up DEBI control register value in shadow RAM */
193         writel(S626_DEBI_CMD_RDWORD | addr, dev->mmio + S626_P_DEBICMD);
194
195         /*  Execute the DEBI transfer. */
196         s626_debi_transfer(dev);
197
198         return readl(dev->mmio + S626_P_DEBIAD);
199 }
200
201 /*
202  * Write a value to a gate array register.
203  */
204 static void s626_debi_write(struct comedi_device *dev, u16 addr,
205                             u16 wdata)
206 {
207         /* Set up DEBI control register value in shadow RAM */
208         writel(S626_DEBI_CMD_WRWORD | addr, dev->mmio + S626_P_DEBICMD);
209         writel(wdata, dev->mmio + S626_P_DEBIAD);
210
211         /*  Execute the DEBI transfer. */
212         s626_debi_transfer(dev);
213 }
214
215 /*
216  * Replace the specified bits in a gate array register.  Imports: mask
217  * specifies bits that are to be preserved, wdata is new value to be
218  * or'd with the masked original.
219  */
220 static void s626_debi_replace(struct comedi_device *dev, unsigned int addr,
221                               unsigned int mask, unsigned int wdata)
222 {
223         unsigned int val;
224
225         addr &= 0xffff;
226         writel(S626_DEBI_CMD_RDWORD | addr, dev->mmio + S626_P_DEBICMD);
227         s626_debi_transfer(dev);
228
229         writel(S626_DEBI_CMD_WRWORD | addr, dev->mmio + S626_P_DEBICMD);
230         val = readl(dev->mmio + S626_P_DEBIAD);
231         val &= mask;
232         val |= wdata;
233         writel(val & 0xffff, dev->mmio + S626_P_DEBIAD);
234         s626_debi_transfer(dev);
235 }
236
237 /* **************  EEPROM ACCESS FUNCTIONS  ************** */
238
239 static int s626_i2c_handshake_eoc(struct comedi_device *dev,
240                                   struct comedi_subdevice *s,
241                                   struct comedi_insn *insn,
242                                   unsigned long context)
243 {
244         bool status;
245
246         status = s626_mc_test(dev, S626_MC2_UPLD_IIC, S626_P_MC2);
247         if (status)
248                 return 0;
249         return -EBUSY;
250 }
251
252 static int s626_i2c_handshake(struct comedi_device *dev, u32 val)
253 {
254         unsigned int ctrl;
255         int ret;
256
257         /* Write I2C command to I2C Transfer Control shadow register */
258         writel(val, dev->mmio + S626_P_I2CCTRL);
259
260         /*
261          * Upload I2C shadow registers into working registers and
262          * wait for upload confirmation.
263          */
264         s626_mc_enable(dev, S626_MC2_UPLD_IIC, S626_P_MC2);
265         ret = comedi_timeout(dev, NULL, NULL, s626_i2c_handshake_eoc, 0);
266         if (ret)
267                 return ret;
268
269         /* Wait until I2C bus transfer is finished or an error occurs */
270         do {
271                 ctrl = readl(dev->mmio + S626_P_I2CCTRL);
272         } while ((ctrl & (S626_I2C_BUSY | S626_I2C_ERR)) == S626_I2C_BUSY);
273
274         /* Return non-zero if I2C error occurred */
275         return ctrl & S626_I2C_ERR;
276 }
277
278 /* Read u8 from EEPROM. */
279 static u8 s626_i2c_read(struct comedi_device *dev, u8 addr)
280 {
281         struct s626_private *devpriv = dev->private;
282
283         /*
284          * Send EEPROM target address:
285          *  Byte2 = I2C command: write to I2C EEPROM device.
286          *  Byte1 = EEPROM internal target address.
287          *  Byte0 = Not sent.
288          */
289         if (s626_i2c_handshake(dev, S626_I2C_B2(S626_I2C_ATTRSTART,
290                                                 devpriv->i2c_adrs) |
291                                     S626_I2C_B1(S626_I2C_ATTRSTOP, addr) |
292                                     S626_I2C_B0(S626_I2C_ATTRNOP, 0)))
293                 /* Abort function and declare error if handshake failed. */
294                 return 0;
295
296         /*
297          * Execute EEPROM read:
298          *  Byte2 = I2C command: read from I2C EEPROM device.
299          *  Byte1 receives uint8_t from EEPROM.
300          *  Byte0 = Not sent.
301          */
302         if (s626_i2c_handshake(dev, S626_I2C_B2(S626_I2C_ATTRSTART,
303                                                 (devpriv->i2c_adrs | 1)) |
304                                     S626_I2C_B1(S626_I2C_ATTRSTOP, 0) |
305                                     S626_I2C_B0(S626_I2C_ATTRNOP, 0)))
306                 /* Abort function and declare error if handshake failed. */
307                 return 0;
308
309         return (readl(dev->mmio + S626_P_I2CCTRL) >> 16) & 0xff;
310 }
311
312 /* ***********  DAC FUNCTIONS *********** */
313
314 /* TrimDac LogicalChan-to-PhysicalChan mapping table. */
315 static const u8 s626_trimchan[] = { 10, 9, 8, 3, 2, 7, 6, 1, 0, 5, 4 };
316
317 /* TrimDac LogicalChan-to-EepromAdrs mapping table. */
318 static const u8 s626_trimadrs[] = {
319         0x40, 0x41, 0x42, 0x50, 0x51, 0x52, 0x53, 0x60, 0x61, 0x62, 0x63
320 };
321
322 enum {
323         s626_send_dac_wait_not_mc1_a2out,
324         s626_send_dac_wait_ssr_af2_out,
325         s626_send_dac_wait_fb_buffer2_msb_00,
326         s626_send_dac_wait_fb_buffer2_msb_ff
327 };
328
329 static int s626_send_dac_eoc(struct comedi_device *dev,
330                              struct comedi_subdevice *s,
331                              struct comedi_insn *insn,
332                              unsigned long context)
333 {
334         unsigned int status;
335
336         switch (context) {
337         case s626_send_dac_wait_not_mc1_a2out:
338                 status = readl(dev->mmio + S626_P_MC1);
339                 if (!(status & S626_MC1_A2OUT))
340                         return 0;
341                 break;
342         case s626_send_dac_wait_ssr_af2_out:
343                 status = readl(dev->mmio + S626_P_SSR);
344                 if (status & S626_SSR_AF2_OUT)
345                         return 0;
346                 break;
347         case s626_send_dac_wait_fb_buffer2_msb_00:
348                 status = readl(dev->mmio + S626_P_FB_BUFFER2);
349                 if (!(status & 0xff000000))
350                         return 0;
351                 break;
352         case s626_send_dac_wait_fb_buffer2_msb_ff:
353                 status = readl(dev->mmio + S626_P_FB_BUFFER2);
354                 if (status & 0xff000000)
355                         return 0;
356                 break;
357         default:
358                 return -EINVAL;
359         }
360         return -EBUSY;
361 }
362
363 /*
364  * Private helper function: Transmit serial data to DAC via Audio
365  * channel 2.  Assumes: (1) TSL2 slot records initialized, and (2)
366  * dacpol contains valid target image.
367  */
368 static int s626_send_dac(struct comedi_device *dev, u32 val)
369 {
370         struct s626_private *devpriv = dev->private;
371         int ret;
372
373         /* START THE SERIAL CLOCK RUNNING ------------- */
374
375         /*
376          * Assert DAC polarity control and enable gating of DAC serial clock
377          * and audio bit stream signals.  At this point in time we must be
378          * assured of being in time slot 0.  If we are not in slot 0, the
379          * serial clock and audio stream signals will be disabled; this is
380          * because the following s626_debi_write statement (which enables
381          * signals to be passed through the gate array) would execute before
382          * the trailing edge of WS1/WS3 (which turns off the signals), thus
383          * causing the signals to be inactive during the DAC write.
384          */
385         s626_debi_write(dev, S626_LP_DACPOL, devpriv->dacpol);
386
387         /* TRANSFER OUTPUT DWORD VALUE INTO A2'S OUTPUT FIFO ---------------- */
388
389         /* Copy DAC setpoint value to DAC's output DMA buffer. */
390         /* writel(val, dev->mmio + (uint32_t)devpriv->dac_wbuf); */
391         *devpriv->dac_wbuf = val;
392
393         /*
394          * Enable the output DMA transfer. This will cause the DMAC to copy
395          * the DAC's data value to A2's output FIFO. The DMA transfer will
396          * then immediately terminate because the protection address is
397          * reached upon transfer of the first DWORD value.
398          */
399         s626_mc_enable(dev, S626_MC1_A2OUT, S626_P_MC1);
400
401         /* While the DMA transfer is executing ... */
402
403         /*
404          * Reset Audio2 output FIFO's underflow flag (along with any
405          * other FIFO underflow/overflow flags). When set, this flag
406          * will indicate that we have emerged from slot 0.
407          */
408         writel(S626_ISR_AFOU, dev->mmio + S626_P_ISR);
409
410         /*
411          * Wait for the DMA transfer to finish so that there will be data
412          * available in the FIFO when time slot 1 tries to transfer a DWORD
413          * from the FIFO to the output buffer register.  We test for DMA
414          * Done by polling the DMAC enable flag; this flag is automatically
415          * cleared when the transfer has finished.
416          */
417         ret = comedi_timeout(dev, NULL, NULL, s626_send_dac_eoc,
418                              s626_send_dac_wait_not_mc1_a2out);
419         if (ret) {
420                 dev_err(dev->class_dev, "DMA transfer timeout\n");
421                 return ret;
422         }
423
424         /* START THE OUTPUT STREAM TO THE TARGET DAC -------------------- */
425
426         /*
427          * FIFO data is now available, so we enable execution of time slots
428          * 1 and higher by clearing the EOS flag in slot 0.  Note that SD3
429          * will be shifted in and stored in FB_BUFFER2 for end-of-slot-list
430          * detection.
431          */
432         writel(S626_XSD2 | S626_RSD3 | S626_SIB_A2,
433                dev->mmio + S626_VECTPORT(0));
434
435         /*
436          * Wait for slot 1 to execute to ensure that the Packet will be
437          * transmitted.  This is detected by polling the Audio2 output FIFO
438          * underflow flag, which will be set when slot 1 execution has
439          * finished transferring the DAC's data DWORD from the output FIFO
440          * to the output buffer register.
441          */
442         ret = comedi_timeout(dev, NULL, NULL, s626_send_dac_eoc,
443                              s626_send_dac_wait_ssr_af2_out);
444         if (ret) {
445                 dev_err(dev->class_dev,
446                         "TSL timeout waiting for slot 1 to execute\n");
447                 return ret;
448         }
449
450         /*
451          * Set up to trap execution at slot 0 when the TSL sequencer cycles
452          * back to slot 0 after executing the EOS in slot 5.  Also,
453          * simultaneously shift out and in the 0x00 that is ALWAYS the value
454          * stored in the last byte to be shifted out of the FIFO's DWORD
455          * buffer register.
456          */
457         writel(S626_XSD2 | S626_XFIFO_2 | S626_RSD2 | S626_SIB_A2 | S626_EOS,
458                dev->mmio + S626_VECTPORT(0));
459
460         /* WAIT FOR THE TRANSACTION TO FINISH ----------------------- */
461
462         /*
463          * Wait for the TSL to finish executing all time slots before
464          * exiting this function.  We must do this so that the next DAC
465          * write doesn't start, thereby enabling clock/chip select signals:
466          *
467          * 1. Before the TSL sequence cycles back to slot 0, which disables
468          *    the clock/cs signal gating and traps slot // list execution.
469          *    we have not yet finished slot 5 then the clock/cs signals are
470          *    still gated and we have not finished transmitting the stream.
471          *
472          * 2. While slots 2-5 are executing due to a late slot 0 trap.  In
473          *    this case, the slot sequence is currently repeating, but with
474          *    clock/cs signals disabled.  We must wait for slot 0 to trap
475          *    execution before setting up the next DAC setpoint DMA transfer
476          *    and enabling the clock/cs signals.  To detect the end of slot 5,
477          *    we test for the FB_BUFFER2 MSB contents to be equal to 0xFF.  If
478          *    the TSL has not yet finished executing slot 5 ...
479          */
480         if (readl(dev->mmio + S626_P_FB_BUFFER2) & 0xff000000) {
481                 /*
482                  * The trap was set on time and we are still executing somewhere
483                  * in slots 2-5, so we now wait for slot 0 to execute and trap
484                  * TSL execution.  This is detected when FB_BUFFER2 MSB changes
485                  * from 0xFF to 0x00, which slot 0 causes to happen by shifting
486                  * out/in on SD2 the 0x00 that is always referenced by slot 5.
487                  */
488                 ret = comedi_timeout(dev, NULL, NULL, s626_send_dac_eoc,
489                                      s626_send_dac_wait_fb_buffer2_msb_00);
490                 if (ret) {
491                         dev_err(dev->class_dev,
492                                 "TSL timeout waiting for slot 0 to execute\n");
493                         return ret;
494                 }
495         }
496         /*
497          * Either (1) we were too late setting the slot 0 trap; the TSL
498          * sequencer restarted slot 0 before we could set the EOS trap flag,
499          * or (2) we were not late and execution is now trapped at slot 0.
500          * In either case, we must now change slot 0 so that it will store
501          * value 0xFF (instead of 0x00) to FB_BUFFER2 next time it executes.
502          * In order to do this, we reprogram slot 0 so that it will shift in
503          * SD3, which is driven only by a pull-up resistor.
504          */
505         writel(S626_RSD3 | S626_SIB_A2 | S626_EOS,
506                dev->mmio + S626_VECTPORT(0));
507
508         /*
509          * Wait for slot 0 to execute, at which time the TSL is setup for
510          * the next DAC write.  This is detected when FB_BUFFER2 MSB changes
511          * from 0x00 to 0xFF.
512          */
513         ret = comedi_timeout(dev, NULL, NULL, s626_send_dac_eoc,
514                              s626_send_dac_wait_fb_buffer2_msb_ff);
515         if (ret) {
516                 dev_err(dev->class_dev,
517                         "TSL timeout waiting for slot 0 to execute\n");
518                 return ret;
519         }
520         return 0;
521 }
522
523 /*
524  * Private helper function: Write setpoint to an application DAC channel.
525  */
526 static int s626_set_dac(struct comedi_device *dev,
527                         u16 chan, int16_t dacdata)
528 {
529         struct s626_private *devpriv = dev->private;
530         u16 signmask;
531         u32 ws_image;
532         u32 val;
533
534         /*
535          * Adjust DAC data polarity and set up Polarity Control Register image.
536          */
537         signmask = 1 << chan;
538         if (dacdata < 0) {
539                 dacdata = -dacdata;
540                 devpriv->dacpol |= signmask;
541         } else {
542                 devpriv->dacpol &= ~signmask;
543         }
544
545         /* Limit DAC setpoint value to valid range. */
546         if ((u16)dacdata > 0x1FFF)
547                 dacdata = 0x1FFF;
548
549         /*
550          * Set up TSL2 records (aka "vectors") for DAC update.  Vectors V2
551          * and V3 transmit the setpoint to the target DAC.  V4 and V5 send
552          * data to a non-existent TrimDac channel just to keep the clock
553          * running after sending data to the target DAC.  This is necessary
554          * to eliminate the clock glitch that would otherwise occur at the
555          * end of the target DAC's serial data stream.  When the sequence
556          * restarts at V0 (after executing V5), the gate array automatically
557          * disables gating for the DAC clock and all DAC chip selects.
558          */
559
560         /* Choose DAC chip select to be asserted */
561         ws_image = (chan & 2) ? S626_WS1 : S626_WS2;
562         /* Slot 2: Transmit high data byte to target DAC */
563         writel(S626_XSD2 | S626_XFIFO_1 | ws_image,
564                dev->mmio + S626_VECTPORT(2));
565         /* Slot 3: Transmit low data byte to target DAC */
566         writel(S626_XSD2 | S626_XFIFO_0 | ws_image,
567                dev->mmio + S626_VECTPORT(3));
568         /* Slot 4: Transmit to non-existent TrimDac channel to keep clock */
569         writel(S626_XSD2 | S626_XFIFO_3 | S626_WS3,
570                dev->mmio + S626_VECTPORT(4));
571         /* Slot 5: running after writing target DAC's low data byte */
572         writel(S626_XSD2 | S626_XFIFO_2 | S626_WS3 | S626_EOS,
573                dev->mmio + S626_VECTPORT(5));
574
575         /*
576          * Construct and transmit target DAC's serial packet:
577          * (A10D DDDD), (DDDD DDDD), (0x0F), (0x00) where A is chan<0>,
578          * and D<12:0> is the DAC setpoint.  Append a WORD value (that writes
579          * to a  non-existent TrimDac channel) that serves to keep the clock
580          * running after the packet has been sent to the target DAC.
581          */
582         val = 0x0F000000;       /* Continue clock after target DAC data
583                                  * (write to non-existent trimdac).
584                                  */
585         val |= 0x00004000;      /* Address the two main dual-DAC devices
586                                  * (TSL's chip select enables target device).
587                                  */
588         val |= ((u32)(chan & 1) << 15); /* Address the DAC channel
589                                          * within the device.
590                                          */
591         val |= (u32)dacdata;    /* Include DAC setpoint data. */
592         return s626_send_dac(dev, val);
593 }
594
595 static int s626_write_trim_dac(struct comedi_device *dev,
596                                u8 logical_chan, u8 dac_data)
597 {
598         struct s626_private *devpriv = dev->private;
599         u32 chan;
600
601         /*
602          * Save the new setpoint in case the application needs to read it back
603          * later.
604          */
605         devpriv->trim_setpoint[logical_chan] = dac_data;
606
607         /* Map logical channel number to physical channel number. */
608         chan = s626_trimchan[logical_chan];
609
610         /*
611          * Set up TSL2 records for TrimDac write operation.  All slots shift
612          * 0xFF in from pulled-up SD3 so that the end of the slot sequence
613          * can be detected.
614          */
615
616         /* Slot 2: Send high uint8_t to target TrimDac */
617         writel(S626_XSD2 | S626_XFIFO_1 | S626_WS3,
618                dev->mmio + S626_VECTPORT(2));
619         /* Slot 3: Send low uint8_t to target TrimDac */
620         writel(S626_XSD2 | S626_XFIFO_0 | S626_WS3,
621                dev->mmio + S626_VECTPORT(3));
622         /* Slot 4: Send NOP high uint8_t to DAC0 to keep clock running */
623         writel(S626_XSD2 | S626_XFIFO_3 | S626_WS1,
624                dev->mmio + S626_VECTPORT(4));
625         /* Slot 5: Send NOP low  uint8_t to DAC0 */
626         writel(S626_XSD2 | S626_XFIFO_2 | S626_WS1 | S626_EOS,
627                dev->mmio + S626_VECTPORT(5));
628
629         /*
630          * Construct and transmit target DAC's serial packet:
631          * (0000 AAAA), (DDDD DDDD), (0x00), (0x00) where A<3:0> is the
632          * DAC channel's address, and D<7:0> is the DAC setpoint.  Append a
633          * WORD value (that writes a channel 0 NOP command to a non-existent
634          * main DAC channel) that serves to keep the clock running after the
635          * packet has been sent to the target DAC.
636          */
637
638         /*
639          * Address the DAC channel within the trimdac device.
640          * Include DAC setpoint data.
641          */
642         return s626_send_dac(dev, (chan << 8) | dac_data);
643 }
644
645 static int s626_load_trim_dacs(struct comedi_device *dev)
646 {
647         u8 i;
648         int ret;
649
650         /* Copy TrimDac setpoint values from EEPROM to TrimDacs. */
651         for (i = 0; i < ARRAY_SIZE(s626_trimchan); i++) {
652                 ret = s626_write_trim_dac(dev, i,
653                                           s626_i2c_read(dev, s626_trimadrs[i]));
654                 if (ret)
655                         return ret;
656         }
657         return 0;
658 }
659
660 /* ******  COUNTER FUNCTIONS  ******* */
661
662 /*
663  * All counter functions address a specific counter by means of the
664  * "Counter" argument, which is a logical counter number.  The Counter
665  * argument may have any of the following legal values: 0=0A, 1=1A,
666  * 2=2A, 3=0B, 4=1B, 5=2B.
667  */
668
669 /*
670  * Return/set a counter pair's latch trigger source.  0: On read
671  * access, 1: A index latches A, 2: B index latches B, 3: A overflow
672  * latches B.
673  */
674 static void s626_set_latch_source(struct comedi_device *dev,
675                                   unsigned int chan, u16 value)
676 {
677         s626_debi_replace(dev, S626_LP_CRB(chan),
678                           ~(S626_CRBMSK_INTCTRL | S626_CRBMSK_LATCHSRC),
679                           S626_SET_CRB_LATCHSRC(value));
680 }
681
682 /*
683  * Write value into counter preload register.
684  */
685 static void s626_preload(struct comedi_device *dev,
686                          unsigned int chan, u32 value)
687 {
688         s626_debi_write(dev, S626_LP_CNTR(chan), value);
689         s626_debi_write(dev, S626_LP_CNTR(chan) + 2, value >> 16);
690 }
691
692 /* ******  PRIVATE COUNTER FUNCTIONS ****** */
693
694 /*
695  * Reset a counter's index and overflow event capture flags.
696  */
697 static void s626_reset_cap_flags(struct comedi_device *dev,
698                                  unsigned int chan)
699 {
700         u16 set;
701
702         set = S626_SET_CRB_INTRESETCMD(1);
703         if (chan < 3)
704                 set |= S626_SET_CRB_INTRESET_A(1);
705         else
706                 set |= S626_SET_CRB_INTRESET_B(1);
707
708         s626_debi_replace(dev, S626_LP_CRB(chan), ~S626_CRBMSK_INTCTRL, set);
709 }
710
711 /*
712  * Set the operating mode for the specified counter.  The setup
713  * parameter is treated as a COUNTER_SETUP data type.  The following
714  * parameters are programmable (all other parms are ignored): ClkMult,
715  * ClkPol, ClkEnab, IndexSrc, IndexPol, LoadSrc.
716  */
717 static void s626_set_mode_a(struct comedi_device *dev,
718                             unsigned int chan, u16 setup,
719                             u16 disable_int_src)
720 {
721         struct s626_private *devpriv = dev->private;
722         u16 cra;
723         u16 crb;
724         unsigned int cntsrc, clkmult, clkpol;
725
726         /* Initialize CRA and CRB images. */
727         /* Preload trigger is passed through. */
728         cra = S626_SET_CRA_LOADSRC_A(S626_GET_STD_LOADSRC(setup));
729         /* IndexSrc is passed through. */
730         cra |= S626_SET_CRA_INDXSRC_A(S626_GET_STD_INDXSRC(setup));
731
732         /* Reset any pending CounterA event captures. */
733         crb = S626_SET_CRB_INTRESETCMD(1) | S626_SET_CRB_INTRESET_A(1);
734         /* Clock enable is passed through. */
735         crb |= S626_SET_CRB_CLKENAB_A(S626_GET_STD_CLKENAB(setup));
736
737         /* Force IntSrc to Disabled if disable_int_src is asserted. */
738         if (!disable_int_src)
739                 cra |= S626_SET_CRA_INTSRC_A(S626_GET_STD_INTSRC(setup));
740
741         /* Populate all mode-dependent attributes of CRA & CRB images. */
742         clkpol = S626_GET_STD_CLKPOL(setup);
743         switch (S626_GET_STD_ENCMODE(setup)) {
744         case S626_ENCMODE_EXTENDER: /* Extender Mode: */
745                 /* Force to Timer mode (Extender valid only for B counters). */
746                 /* Fall through to case S626_ENCMODE_TIMER: */
747         case S626_ENCMODE_TIMER:        /* Timer Mode: */
748                 /* CntSrcA<1> selects system clock */
749                 cntsrc = S626_CNTSRC_SYSCLK;
750                 /* Count direction (CntSrcA<0>) obtained from ClkPol. */
751                 cntsrc |= clkpol;
752                 /* ClkPolA behaves as always-on clock enable. */
753                 clkpol = 1;
754                 /* ClkMult must be 1x. */
755                 clkmult = S626_CLKMULT_1X;
756                 break;
757         default:                /* Counter Mode: */
758                 /* Select ENC_C and ENC_D as clock/direction inputs. */
759                 cntsrc = S626_CNTSRC_ENCODER;
760                 /* Clock polarity is passed through. */
761                 /* Force multiplier to x1 if not legal, else pass through. */
762                 clkmult = S626_GET_STD_CLKMULT(setup);
763                 if (clkmult == S626_CLKMULT_SPECIAL)
764                         clkmult = S626_CLKMULT_1X;
765                 break;
766         }
767         cra |= S626_SET_CRA_CNTSRC_A(cntsrc) | S626_SET_CRA_CLKPOL_A(clkpol) |
768                S626_SET_CRA_CLKMULT_A(clkmult);
769
770         /*
771          * Force positive index polarity if IndxSrc is software-driven only,
772          * otherwise pass it through.
773          */
774         if (S626_GET_STD_INDXSRC(setup) != S626_INDXSRC_SOFT)
775                 cra |= S626_SET_CRA_INDXPOL_A(S626_GET_STD_INDXPOL(setup));
776
777         /*
778          * If IntSrc has been forced to Disabled, update the MISC2 interrupt
779          * enable mask to indicate the counter interrupt is disabled.
780          */
781         if (disable_int_src)
782                 devpriv->counter_int_enabs &= ~(S626_OVERMASK(chan) |
783                                                 S626_INDXMASK(chan));
784
785         /*
786          * While retaining CounterB and LatchSrc configurations, program the
787          * new counter operating mode.
788          */
789         s626_debi_replace(dev, S626_LP_CRA(chan),
790                           S626_CRAMSK_INDXSRC_B | S626_CRAMSK_CNTSRC_B, cra);
791         s626_debi_replace(dev, S626_LP_CRB(chan),
792                           ~(S626_CRBMSK_INTCTRL | S626_CRBMSK_CLKENAB_A), crb);
793 }
794
795 static void s626_set_mode_b(struct comedi_device *dev,
796                             unsigned int chan, u16 setup,
797                             u16 disable_int_src)
798 {
799         struct s626_private *devpriv = dev->private;
800         u16 cra;
801         u16 crb;
802         unsigned int cntsrc, clkmult, clkpol;
803
804         /* Initialize CRA and CRB images. */
805         /* IndexSrc is passed through. */
806         cra = S626_SET_CRA_INDXSRC_B(S626_GET_STD_INDXSRC(setup));
807
808         /* Reset event captures and disable interrupts. */
809         crb = S626_SET_CRB_INTRESETCMD(1) | S626_SET_CRB_INTRESET_B(1);
810         /* Clock enable is passed through. */
811         crb |= S626_SET_CRB_CLKENAB_B(S626_GET_STD_CLKENAB(setup));
812         /* Preload trigger source is passed through. */
813         crb |= S626_SET_CRB_LOADSRC_B(S626_GET_STD_LOADSRC(setup));
814
815         /* Force IntSrc to Disabled if disable_int_src is asserted. */
816         if (!disable_int_src)
817                 crb |= S626_SET_CRB_INTSRC_B(S626_GET_STD_INTSRC(setup));
818
819         /* Populate all mode-dependent attributes of CRA & CRB images. */
820         clkpol = S626_GET_STD_CLKPOL(setup);
821         switch (S626_GET_STD_ENCMODE(setup)) {
822         case S626_ENCMODE_TIMER:        /* Timer Mode: */
823                 /* CntSrcB<1> selects system clock */
824                 cntsrc = S626_CNTSRC_SYSCLK;
825                 /* with direction (CntSrcB<0>) obtained from ClkPol. */
826                 cntsrc |= clkpol;
827                 /* ClkPolB behaves as always-on clock enable. */
828                 clkpol = 1;
829                 /* ClkMultB must be 1x. */
830                 clkmult = S626_CLKMULT_1X;
831                 break;
832         case S626_ENCMODE_EXTENDER:     /* Extender Mode: */
833                 /* CntSrcB source is OverflowA (same as "timer") */
834                 cntsrc = S626_CNTSRC_SYSCLK;
835                 /* with direction obtained from ClkPol. */
836                 cntsrc |= clkpol;
837                 /* ClkPolB controls IndexB -- always set to active. */
838                 clkpol = 1;
839                 /* ClkMultB selects OverflowA as the clock source. */
840                 clkmult = S626_CLKMULT_SPECIAL;
841                 break;
842         default:                /* Counter Mode: */
843                 /* Select ENC_C and ENC_D as clock/direction inputs. */
844                 cntsrc = S626_CNTSRC_ENCODER;
845                 /* ClkPol is passed through. */
846                 /* Force ClkMult to x1 if not legal, otherwise pass through. */
847                 clkmult = S626_GET_STD_CLKMULT(setup);
848                 if (clkmult == S626_CLKMULT_SPECIAL)
849                         clkmult = S626_CLKMULT_1X;
850                 break;
851         }
852         cra |= S626_SET_CRA_CNTSRC_B(cntsrc);
853         crb |= S626_SET_CRB_CLKPOL_B(clkpol) | S626_SET_CRB_CLKMULT_B(clkmult);
854
855         /*
856          * Force positive index polarity if IndxSrc is software-driven only,
857          * otherwise pass it through.
858          */
859         if (S626_GET_STD_INDXSRC(setup) != S626_INDXSRC_SOFT)
860                 crb |= S626_SET_CRB_INDXPOL_B(S626_GET_STD_INDXPOL(setup));
861
862         /*
863          * If IntSrc has been forced to Disabled, update the MISC2 interrupt
864          * enable mask to indicate the counter interrupt is disabled.
865          */
866         if (disable_int_src)
867                 devpriv->counter_int_enabs &= ~(S626_OVERMASK(chan) |
868                                                 S626_INDXMASK(chan));
869
870         /*
871          * While retaining CounterA and LatchSrc configurations, program the
872          * new counter operating mode.
873          */
874         s626_debi_replace(dev, S626_LP_CRA(chan),
875                           ~(S626_CRAMSK_INDXSRC_B | S626_CRAMSK_CNTSRC_B), cra);
876         s626_debi_replace(dev, S626_LP_CRB(chan),
877                           S626_CRBMSK_CLKENAB_A | S626_CRBMSK_LATCHSRC, crb);
878 }
879
880 static void s626_set_mode(struct comedi_device *dev,
881                           unsigned int chan,
882                           u16 setup, u16 disable_int_src)
883 {
884         if (chan < 3)
885                 s626_set_mode_a(dev, chan, setup, disable_int_src);
886         else
887                 s626_set_mode_b(dev, chan, setup, disable_int_src);
888 }
889
890 /*
891  * Return/set a counter's enable.  enab: 0=always enabled, 1=enabled by index.
892  */
893 static void s626_set_enable(struct comedi_device *dev,
894                             unsigned int chan, u16 enab)
895 {
896         unsigned int mask = S626_CRBMSK_INTCTRL;
897         unsigned int set;
898
899         if (chan < 3) {
900                 mask |= S626_CRBMSK_CLKENAB_A;
901                 set = S626_SET_CRB_CLKENAB_A(enab);
902         } else {
903                 mask |= S626_CRBMSK_CLKENAB_B;
904                 set = S626_SET_CRB_CLKENAB_B(enab);
905         }
906         s626_debi_replace(dev, S626_LP_CRB(chan), ~mask, set);
907 }
908
909 /*
910  * Return/set the event that will trigger transfer of the preload
911  * register into the counter.  0=ThisCntr_Index, 1=ThisCntr_Overflow,
912  * 2=OverflowA (B counters only), 3=disabled.
913  */
914 static void s626_set_load_trig(struct comedi_device *dev,
915                                unsigned int chan, u16 trig)
916 {
917         u16 reg;
918         u16 mask;
919         u16 set;
920
921         if (chan < 3) {
922                 reg = S626_LP_CRA(chan);
923                 mask = S626_CRAMSK_LOADSRC_A;
924                 set = S626_SET_CRA_LOADSRC_A(trig);
925         } else {
926                 reg = S626_LP_CRB(chan);
927                 mask = S626_CRBMSK_LOADSRC_B | S626_CRBMSK_INTCTRL;
928                 set = S626_SET_CRB_LOADSRC_B(trig);
929         }
930         s626_debi_replace(dev, reg, ~mask, set);
931 }
932
933 /*
934  * Return/set counter interrupt source and clear any captured
935  * index/overflow events.  int_source: 0=Disabled, 1=OverflowOnly,
936  * 2=IndexOnly, 3=IndexAndOverflow.
937  */
938 static void s626_set_int_src(struct comedi_device *dev,
939                              unsigned int chan, u16 int_source)
940 {
941         struct s626_private *devpriv = dev->private;
942         u16 cra_reg = S626_LP_CRA(chan);
943         u16 crb_reg = S626_LP_CRB(chan);
944
945         if (chan < 3) {
946                 /* Reset any pending counter overflow or index captures */
947                 s626_debi_replace(dev, crb_reg, ~S626_CRBMSK_INTCTRL,
948                                   S626_SET_CRB_INTRESETCMD(1) |
949                                   S626_SET_CRB_INTRESET_A(1));
950
951                 /* Program counter interrupt source */
952                 s626_debi_replace(dev, cra_reg, ~S626_CRAMSK_INTSRC_A,
953                                   S626_SET_CRA_INTSRC_A(int_source));
954         } else {
955                 u16 crb;
956
957                 /* Cache writeable CRB register image */
958                 crb = s626_debi_read(dev, crb_reg);
959                 crb &= ~S626_CRBMSK_INTCTRL;
960
961                 /* Reset any pending counter overflow or index captures */
962                 s626_debi_write(dev, crb_reg,
963                                 crb | S626_SET_CRB_INTRESETCMD(1) |
964                                 S626_SET_CRB_INTRESET_B(1));
965
966                 /* Program counter interrupt source */
967                 s626_debi_write(dev, crb_reg,
968                                 (crb & ~S626_CRBMSK_INTSRC_B) |
969                                 S626_SET_CRB_INTSRC_B(int_source));
970         }
971
972         /* Update MISC2 interrupt enable mask. */
973         devpriv->counter_int_enabs &= ~(S626_OVERMASK(chan) |
974                                         S626_INDXMASK(chan));
975         switch (int_source) {
976         case 0:
977         default:
978                 break;
979         case 1:
980                 devpriv->counter_int_enabs |= S626_OVERMASK(chan);
981                 break;
982         case 2:
983                 devpriv->counter_int_enabs |= S626_INDXMASK(chan);
984                 break;
985         case 3:
986                 devpriv->counter_int_enabs |= (S626_OVERMASK(chan) |
987                                                S626_INDXMASK(chan));
988                 break;
989         }
990 }
991
992 /*
993  * Generate an index pulse.
994  */
995 static void s626_pulse_index(struct comedi_device *dev,
996                              unsigned int chan)
997 {
998         if (chan < 3) {
999                 u16 cra;
1000
1001                 cra = s626_debi_read(dev, S626_LP_CRA(chan));
1002
1003                 /* Pulse index */
1004                 s626_debi_write(dev, S626_LP_CRA(chan),
1005                                 (cra ^ S626_CRAMSK_INDXPOL_A));
1006                 s626_debi_write(dev, S626_LP_CRA(chan), cra);
1007         } else {
1008                 u16 crb;
1009
1010                 crb = s626_debi_read(dev, S626_LP_CRB(chan));
1011                 crb &= ~S626_CRBMSK_INTCTRL;
1012
1013                 /* Pulse index */
1014                 s626_debi_write(dev, S626_LP_CRB(chan),
1015                                 (crb ^ S626_CRBMSK_INDXPOL_B));
1016                 s626_debi_write(dev, S626_LP_CRB(chan), crb);
1017         }
1018 }
1019
1020 static unsigned int s626_ai_reg_to_uint(unsigned int data)
1021 {
1022         return ((data >> 18) & 0x3fff) ^ 0x2000;
1023 }
1024
1025 static int s626_dio_set_irq(struct comedi_device *dev, unsigned int chan)
1026 {
1027         unsigned int group = chan / 16;
1028         unsigned int mask = 1 << (chan - (16 * group));
1029         unsigned int status;
1030
1031         /* set channel to capture positive edge */
1032         status = s626_debi_read(dev, S626_LP_RDEDGSEL(group));
1033         s626_debi_write(dev, S626_LP_WREDGSEL(group), mask | status);
1034
1035         /* enable interrupt on selected channel */
1036         status = s626_debi_read(dev, S626_LP_RDINTSEL(group));
1037         s626_debi_write(dev, S626_LP_WRINTSEL(group), mask | status);
1038
1039         /* enable edge capture write command */
1040         s626_debi_write(dev, S626_LP_MISC1, S626_MISC1_EDCAP);
1041
1042         /* enable edge capture on selected channel */
1043         status = s626_debi_read(dev, S626_LP_RDCAPSEL(group));
1044         s626_debi_write(dev, S626_LP_WRCAPSEL(group), mask | status);
1045
1046         return 0;
1047 }
1048
1049 static int s626_dio_reset_irq(struct comedi_device *dev, unsigned int group,
1050                               unsigned int mask)
1051 {
1052         /* disable edge capture write command */
1053         s626_debi_write(dev, S626_LP_MISC1, S626_MISC1_NOEDCAP);
1054
1055         /* enable edge capture on selected channel */
1056         s626_debi_write(dev, S626_LP_WRCAPSEL(group), mask);
1057
1058         return 0;
1059 }
1060
1061 static int s626_dio_clear_irq(struct comedi_device *dev)
1062 {
1063         unsigned int group;
1064
1065         /* disable edge capture write command */
1066         s626_debi_write(dev, S626_LP_MISC1, S626_MISC1_NOEDCAP);
1067
1068         /* clear all dio pending events and interrupt */
1069         for (group = 0; group < S626_DIO_BANKS; group++)
1070                 s626_debi_write(dev, S626_LP_WRCAPSEL(group), 0xffff);
1071
1072         return 0;
1073 }
1074
1075 static void s626_handle_dio_interrupt(struct comedi_device *dev,
1076                                       u16 irqbit, u8 group)
1077 {
1078         struct s626_private *devpriv = dev->private;
1079         struct comedi_subdevice *s = dev->read_subdev;
1080         struct comedi_cmd *cmd = &s->async->cmd;
1081
1082         s626_dio_reset_irq(dev, group, irqbit);
1083
1084         if (devpriv->ai_cmd_running) {
1085                 /* check if interrupt is an ai acquisition start trigger */
1086                 if ((irqbit >> (cmd->start_arg - (16 * group))) == 1 &&
1087                     cmd->start_src == TRIG_EXT) {
1088                         /* Start executing the RPS program */
1089                         s626_mc_enable(dev, S626_MC1_ERPS1, S626_P_MC1);
1090
1091                         if (cmd->scan_begin_src == TRIG_EXT)
1092                                 s626_dio_set_irq(dev, cmd->scan_begin_arg);
1093                 }
1094                 if ((irqbit >> (cmd->scan_begin_arg - (16 * group))) == 1 &&
1095                     cmd->scan_begin_src == TRIG_EXT) {
1096                         /* Trigger ADC scan loop start */
1097                         s626_mc_enable(dev, S626_MC2_ADC_RPS, S626_P_MC2);
1098
1099                         if (cmd->convert_src == TRIG_EXT) {
1100                                 devpriv->ai_convert_count = cmd->chanlist_len;
1101
1102                                 s626_dio_set_irq(dev, cmd->convert_arg);
1103                         }
1104
1105                         if (cmd->convert_src == TRIG_TIMER) {
1106                                 devpriv->ai_convert_count = cmd->chanlist_len;
1107                                 s626_set_enable(dev, 5, S626_CLKENAB_ALWAYS);
1108                         }
1109                 }
1110                 if ((irqbit >> (cmd->convert_arg - (16 * group))) == 1 &&
1111                     cmd->convert_src == TRIG_EXT) {
1112                         /* Trigger ADC scan loop start */
1113                         s626_mc_enable(dev, S626_MC2_ADC_RPS, S626_P_MC2);
1114
1115                         devpriv->ai_convert_count--;
1116                         if (devpriv->ai_convert_count > 0)
1117                                 s626_dio_set_irq(dev, cmd->convert_arg);
1118                 }
1119         }
1120 }
1121
1122 static void s626_check_dio_interrupts(struct comedi_device *dev)
1123 {
1124         u16 irqbit;
1125         u8 group;
1126
1127         for (group = 0; group < S626_DIO_BANKS; group++) {
1128                 /* read interrupt type */
1129                 irqbit = s626_debi_read(dev, S626_LP_RDCAPFLG(group));
1130
1131                 /* check if interrupt is generated from dio channels */
1132                 if (irqbit) {
1133                         s626_handle_dio_interrupt(dev, irqbit, group);
1134                         return;
1135                 }
1136         }
1137 }
1138
1139 static void s626_check_counter_interrupts(struct comedi_device *dev)
1140 {
1141         struct s626_private *devpriv = dev->private;
1142         struct comedi_subdevice *s = dev->read_subdev;
1143         struct comedi_async *async = s->async;
1144         struct comedi_cmd *cmd = &async->cmd;
1145         u16 irqbit;
1146
1147         /* read interrupt type */
1148         irqbit = s626_debi_read(dev, S626_LP_RDMISC2);
1149
1150         /* check interrupt on counters */
1151         if (irqbit & S626_IRQ_COINT1A) {
1152                 /* clear interrupt capture flag */
1153                 s626_reset_cap_flags(dev, 0);
1154         }
1155         if (irqbit & S626_IRQ_COINT2A) {
1156                 /* clear interrupt capture flag */
1157                 s626_reset_cap_flags(dev, 1);
1158         }
1159         if (irqbit & S626_IRQ_COINT3A) {
1160                 /* clear interrupt capture flag */
1161                 s626_reset_cap_flags(dev, 2);
1162         }
1163         if (irqbit & S626_IRQ_COINT1B) {
1164                 /* clear interrupt capture flag */
1165                 s626_reset_cap_flags(dev, 3);
1166         }
1167         if (irqbit & S626_IRQ_COINT2B) {
1168                 /* clear interrupt capture flag */
1169                 s626_reset_cap_flags(dev, 4);
1170
1171                 if (devpriv->ai_convert_count > 0) {
1172                         devpriv->ai_convert_count--;
1173                         if (devpriv->ai_convert_count == 0)
1174                                 s626_set_enable(dev, 4, S626_CLKENAB_INDEX);
1175
1176                         if (cmd->convert_src == TRIG_TIMER) {
1177                                 /* Trigger ADC scan loop start */
1178                                 s626_mc_enable(dev, S626_MC2_ADC_RPS,
1179                                                S626_P_MC2);
1180                         }
1181                 }
1182         }
1183         if (irqbit & S626_IRQ_COINT3B) {
1184                 /* clear interrupt capture flag */
1185                 s626_reset_cap_flags(dev, 5);
1186
1187                 if (cmd->scan_begin_src == TRIG_TIMER) {
1188                         /* Trigger ADC scan loop start */
1189                         s626_mc_enable(dev, S626_MC2_ADC_RPS, S626_P_MC2);
1190                 }
1191
1192                 if (cmd->convert_src == TRIG_TIMER) {
1193                         devpriv->ai_convert_count = cmd->chanlist_len;
1194                         s626_set_enable(dev, 4, S626_CLKENAB_ALWAYS);
1195                 }
1196         }
1197 }
1198
1199 static bool s626_handle_eos_interrupt(struct comedi_device *dev)
1200 {
1201         struct s626_private *devpriv = dev->private;
1202         struct comedi_subdevice *s = dev->read_subdev;
1203         struct comedi_async *async = s->async;
1204         struct comedi_cmd *cmd = &async->cmd;
1205         /*
1206          * Init ptr to DMA buffer that holds new ADC data.  We skip the
1207          * first uint16_t in the buffer because it contains junk data
1208          * from the final ADC of the previous poll list scan.
1209          */
1210         u32 *readaddr = (u32 *)devpriv->ana_buf.logical_base + 1;
1211         int i;
1212
1213         /* get the data and hand it over to comedi */
1214         for (i = 0; i < cmd->chanlist_len; i++) {
1215                 unsigned short tempdata;
1216
1217                 /*
1218                  * Convert ADC data to 16-bit integer values and copy
1219                  * to application buffer.
1220                  */
1221                 tempdata = s626_ai_reg_to_uint(*readaddr);
1222                 readaddr++;
1223
1224                 comedi_buf_write_samples(s, &tempdata, 1);
1225         }
1226
1227         if (cmd->stop_src == TRIG_COUNT && async->scans_done >= cmd->stop_arg)
1228                 async->events |= COMEDI_CB_EOA;
1229
1230         if (async->events & COMEDI_CB_CANCEL_MASK)
1231                 devpriv->ai_cmd_running = 0;
1232
1233         if (devpriv->ai_cmd_running && cmd->scan_begin_src == TRIG_EXT)
1234                 s626_dio_set_irq(dev, cmd->scan_begin_arg);
1235
1236         comedi_handle_events(dev, s);
1237
1238         return !devpriv->ai_cmd_running;
1239 }
1240
1241 static irqreturn_t s626_irq_handler(int irq, void *d)
1242 {
1243         struct comedi_device *dev = d;
1244         unsigned long flags;
1245         u32 irqtype, irqstatus;
1246
1247         if (!dev->attached)
1248                 return IRQ_NONE;
1249         /* lock to avoid race with comedi_poll */
1250         spin_lock_irqsave(&dev->spinlock, flags);
1251
1252         /* save interrupt enable register state */
1253         irqstatus = readl(dev->mmio + S626_P_IER);
1254
1255         /* read interrupt type */
1256         irqtype = readl(dev->mmio + S626_P_ISR);
1257
1258         /* disable master interrupt */
1259         writel(0, dev->mmio + S626_P_IER);
1260
1261         /* clear interrupt */
1262         writel(irqtype, dev->mmio + S626_P_ISR);
1263
1264         switch (irqtype) {
1265         case S626_IRQ_RPS1:     /* end_of_scan occurs */
1266                 if (s626_handle_eos_interrupt(dev))
1267                         irqstatus = 0;
1268                 break;
1269         case S626_IRQ_GPIO3:    /* check dio and counter interrupt */
1270                 /* s626_dio_clear_irq(dev); */
1271                 s626_check_dio_interrupts(dev);
1272                 s626_check_counter_interrupts(dev);
1273                 break;
1274         }
1275
1276         /* enable interrupt */
1277         writel(irqstatus, dev->mmio + S626_P_IER);
1278
1279         spin_unlock_irqrestore(&dev->spinlock, flags);
1280         return IRQ_HANDLED;
1281 }
1282
1283 /*
1284  * This function builds the RPS program for hardware driven acquisition.
1285  */
1286 static void s626_reset_adc(struct comedi_device *dev, u8 *ppl)
1287 {
1288         struct s626_private *devpriv = dev->private;
1289         struct comedi_subdevice *s = dev->read_subdev;
1290         struct comedi_cmd *cmd = &s->async->cmd;
1291         u32 *rps;
1292         u32 jmp_adrs;
1293         u16 i;
1294         u16 n;
1295         u32 local_ppl;
1296
1297         /* Stop RPS program in case it is currently running */
1298         s626_mc_disable(dev, S626_MC1_ERPS1, S626_P_MC1);
1299
1300         /* Set starting logical address to write RPS commands. */
1301         rps = (u32 *)devpriv->rps_buf.logical_base;
1302
1303         /* Initialize RPS instruction pointer */
1304         writel((u32)devpriv->rps_buf.physical_base,
1305                dev->mmio + S626_P_RPSADDR1);
1306
1307         /* Construct RPS program in rps_buf DMA buffer */
1308         if (cmd->scan_begin_src != TRIG_FOLLOW) {
1309                 /* Wait for Start trigger. */
1310                 *rps++ = S626_RPS_PAUSE | S626_RPS_SIGADC;
1311                 *rps++ = S626_RPS_CLRSIGNAL | S626_RPS_SIGADC;
1312         }
1313
1314         /*
1315          * SAA7146 BUG WORKAROUND Do a dummy DEBI Write.  This is necessary
1316          * because the first RPS DEBI Write following a non-RPS DEBI write
1317          * seems to always fail.  If we don't do this dummy write, the ADC
1318          * gain might not be set to the value required for the first slot in
1319          * the poll list; the ADC gain would instead remain unchanged from
1320          * the previously programmed value.
1321          */
1322         /* Write DEBI Write command and address to shadow RAM. */
1323         *rps++ = S626_RPS_LDREG | (S626_P_DEBICMD >> 2);
1324         *rps++ = S626_DEBI_CMD_WRWORD | S626_LP_GSEL;
1325         *rps++ = S626_RPS_LDREG | (S626_P_DEBIAD >> 2);
1326         /* Write DEBI immediate data  to shadow RAM: */
1327         *rps++ = S626_GSEL_BIPOLAR5V;   /* arbitrary immediate data  value. */
1328         *rps++ = S626_RPS_CLRSIGNAL | S626_RPS_DEBI;
1329         /* Reset "shadow RAM  uploaded" flag. */
1330         /* Invoke shadow RAM upload. */
1331         *rps++ = S626_RPS_UPLOAD | S626_RPS_DEBI;
1332         /* Wait for shadow upload to finish. */
1333         *rps++ = S626_RPS_PAUSE | S626_RPS_DEBI;
1334
1335         /*
1336          * Digitize all slots in the poll list. This is implemented as a
1337          * for loop to limit the slot count to 16 in case the application
1338          * forgot to set the S626_EOPL flag in the final slot.
1339          */
1340         for (devpriv->adc_items = 0; devpriv->adc_items < 16;
1341              devpriv->adc_items++) {
1342                 /*
1343                  * Convert application's poll list item to private board class
1344                  * format.  Each app poll list item is an uint8_t with form
1345                  * (EOPL,x,x,RANGE,CHAN<3:0>), where RANGE code indicates 0 =
1346                  * +-10V, 1 = +-5V, and EOPL = End of Poll List marker.
1347                  */
1348                 local_ppl = (*ppl << 8) | (*ppl & 0x10 ? S626_GSEL_BIPOLAR5V :
1349                                            S626_GSEL_BIPOLAR10V);
1350
1351                 /* Switch ADC analog gain. */
1352                 /* Write DEBI command and address to shadow RAM. */
1353                 *rps++ = S626_RPS_LDREG | (S626_P_DEBICMD >> 2);
1354                 *rps++ = S626_DEBI_CMD_WRWORD | S626_LP_GSEL;
1355                 /* Write DEBI immediate data to shadow RAM. */
1356                 *rps++ = S626_RPS_LDREG | (S626_P_DEBIAD >> 2);
1357                 *rps++ = local_ppl;
1358                 /* Reset "shadow RAM uploaded" flag. */
1359                 *rps++ = S626_RPS_CLRSIGNAL | S626_RPS_DEBI;
1360                 /* Invoke shadow RAM upload. */
1361                 *rps++ = S626_RPS_UPLOAD | S626_RPS_DEBI;
1362                 /* Wait for shadow upload to finish. */
1363                 *rps++ = S626_RPS_PAUSE | S626_RPS_DEBI;
1364                 /* Select ADC analog input channel. */
1365                 *rps++ = S626_RPS_LDREG | (S626_P_DEBICMD >> 2);
1366                 /* Write DEBI command and address to shadow RAM. */
1367                 *rps++ = S626_DEBI_CMD_WRWORD | S626_LP_ISEL;
1368                 *rps++ = S626_RPS_LDREG | (S626_P_DEBIAD >> 2);
1369                 /* Write DEBI immediate data to shadow RAM. */
1370                 *rps++ = local_ppl;
1371                 /* Reset "shadow RAM uploaded" flag. */
1372                 *rps++ = S626_RPS_CLRSIGNAL | S626_RPS_DEBI;
1373                 /* Invoke shadow RAM upload. */
1374                 *rps++ = S626_RPS_UPLOAD | S626_RPS_DEBI;
1375                 /* Wait for shadow upload to finish. */
1376                 *rps++ = S626_RPS_PAUSE | S626_RPS_DEBI;
1377
1378                 /*
1379                  * Delay at least 10 microseconds for analog input settling.
1380                  * Instead of padding with NOPs, we use S626_RPS_JUMP
1381                  * instructions here; this allows us to produce a longer delay
1382                  * than is possible with NOPs because each S626_RPS_JUMP
1383                  * flushes the RPS' instruction prefetch pipeline.
1384                  */
1385                 jmp_adrs =
1386                         (u32)devpriv->rps_buf.physical_base +
1387                         (u32)((unsigned long)rps -
1388                                    (unsigned long)devpriv->
1389                                                   rps_buf.logical_base);
1390                 for (i = 0; i < (10 * S626_RPSCLK_PER_US / 2); i++) {
1391                         jmp_adrs += 8;  /* Repeat to implement time delay: */
1392                         /* Jump to next RPS instruction. */
1393                         *rps++ = S626_RPS_JUMP;
1394                         *rps++ = jmp_adrs;
1395                 }
1396
1397                 if (cmd->convert_src != TRIG_NOW) {
1398                         /* Wait for Start trigger. */
1399                         *rps++ = S626_RPS_PAUSE | S626_RPS_SIGADC;
1400                         *rps++ = S626_RPS_CLRSIGNAL | S626_RPS_SIGADC;
1401                 }
1402                 /* Start ADC by pulsing GPIO1. */
1403                 /* Begin ADC Start pulse. */
1404                 *rps++ = S626_RPS_LDREG | (S626_P_GPIO >> 2);
1405                 *rps++ = S626_GPIO_BASE | S626_GPIO1_LO;
1406                 *rps++ = S626_RPS_NOP;
1407                 /* VERSION 2.03 CHANGE: STRETCH OUT ADC START PULSE. */
1408                 /* End ADC Start pulse. */
1409                 *rps++ = S626_RPS_LDREG | (S626_P_GPIO >> 2);
1410                 *rps++ = S626_GPIO_BASE | S626_GPIO1_HI;
1411                 /*
1412                  * Wait for ADC to complete (GPIO2 is asserted high when ADC not
1413                  * busy) and for data from previous conversion to shift into FB
1414                  * BUFFER 1 register.
1415                  */
1416                 /* Wait for ADC done. */
1417                 *rps++ = S626_RPS_PAUSE | S626_RPS_GPIO2;
1418
1419                 /* Transfer ADC data from FB BUFFER 1 register to DMA buffer. */
1420                 *rps++ = S626_RPS_STREG |
1421                          (S626_BUGFIX_STREG(S626_P_FB_BUFFER1) >> 2);
1422                 *rps++ = (u32)devpriv->ana_buf.physical_base +
1423                          (devpriv->adc_items << 2);
1424
1425                 /*
1426                  * If this slot's EndOfPollList flag is set, all channels have
1427                  * now been processed.
1428                  */
1429                 if (*ppl++ & S626_EOPL) {
1430                         devpriv->adc_items++; /* Adjust poll list item count. */
1431                         break;  /* Exit poll list processing loop. */
1432                 }
1433         }
1434
1435         /*
1436          * VERSION 2.01 CHANGE: DELAY CHANGED FROM 250NS to 2US.  Allow the
1437          * ADC to stabilize for 2 microseconds before starting the final
1438          * (dummy) conversion.  This delay is necessary to allow sufficient
1439          * time between last conversion finished and the start of the dummy
1440          * conversion.  Without this delay, the last conversion's data value
1441          * is sometimes set to the previous conversion's data value.
1442          */
1443         for (n = 0; n < (2 * S626_RPSCLK_PER_US); n++)
1444                 *rps++ = S626_RPS_NOP;
1445
1446         /*
1447          * Start a dummy conversion to cause the data from the last
1448          * conversion of interest to be shifted in.
1449          */
1450         /* Begin ADC Start pulse. */
1451         *rps++ = S626_RPS_LDREG | (S626_P_GPIO >> 2);
1452         *rps++ = S626_GPIO_BASE | S626_GPIO1_LO;
1453         *rps++ = S626_RPS_NOP;
1454         /* VERSION 2.03 CHANGE: STRETCH OUT ADC START PULSE. */
1455         *rps++ = S626_RPS_LDREG | (S626_P_GPIO >> 2); /* End ADC Start pulse. */
1456         *rps++ = S626_GPIO_BASE | S626_GPIO1_HI;
1457
1458         /*
1459          * Wait for the data from the last conversion of interest to arrive
1460          * in FB BUFFER 1 register.
1461          */
1462         *rps++ = S626_RPS_PAUSE | S626_RPS_GPIO2;       /* Wait for ADC done. */
1463
1464         /* Transfer final ADC data from FB BUFFER 1 register to DMA buffer. */
1465         *rps++ = S626_RPS_STREG | (S626_BUGFIX_STREG(S626_P_FB_BUFFER1) >> 2);
1466         *rps++ = (u32)devpriv->ana_buf.physical_base +
1467                  (devpriv->adc_items << 2);
1468
1469         /* Indicate ADC scan loop is finished. */
1470         /* Signal ReadADC() that scan is done. */
1471         /* *rps++= S626_RPS_CLRSIGNAL | S626_RPS_SIGADC; */
1472
1473         /* invoke interrupt */
1474         if (devpriv->ai_cmd_running == 1)
1475                 *rps++ = S626_RPS_IRQ;
1476
1477         /* Restart RPS program at its beginning. */
1478         *rps++ = S626_RPS_JUMP; /* Branch to start of RPS program. */
1479         *rps++ = (u32)devpriv->rps_buf.physical_base;
1480
1481         /* End of RPS program build */
1482 }
1483
1484 static int s626_ai_eoc(struct comedi_device *dev,
1485                        struct comedi_subdevice *s,
1486                        struct comedi_insn *insn,
1487                        unsigned long context)
1488 {
1489         unsigned int status;
1490
1491         status = readl(dev->mmio + S626_P_PSR);
1492         if (status & S626_PSR_GPIO2)
1493                 return 0;
1494         return -EBUSY;
1495 }
1496
1497 static int s626_ai_insn_read(struct comedi_device *dev,
1498                              struct comedi_subdevice *s,
1499                              struct comedi_insn *insn,
1500                              unsigned int *data)
1501 {
1502         u16 chan = CR_CHAN(insn->chanspec);
1503         u16 range = CR_RANGE(insn->chanspec);
1504         u16 adc_spec = 0;
1505         u32 gpio_image;
1506         u32 tmp;
1507         int ret;
1508         int n;
1509
1510         /*
1511          * Convert application's ADC specification into form
1512          *  appropriate for register programming.
1513          */
1514         if (range == 0)
1515                 adc_spec = (chan << 8) | (S626_GSEL_BIPOLAR5V);
1516         else
1517                 adc_spec = (chan << 8) | (S626_GSEL_BIPOLAR10V);
1518
1519         /* Switch ADC analog gain. */
1520         s626_debi_write(dev, S626_LP_GSEL, adc_spec);   /* Set gain. */
1521
1522         /* Select ADC analog input channel. */
1523         s626_debi_write(dev, S626_LP_ISEL, adc_spec);   /* Select channel. */
1524
1525         for (n = 0; n < insn->n; n++) {
1526                 /* Delay 10 microseconds for analog input settling. */
1527                 usleep_range(10, 20);
1528
1529                 /* Start ADC by pulsing GPIO1 low */
1530                 gpio_image = readl(dev->mmio + S626_P_GPIO);
1531                 /* Assert ADC Start command */
1532                 writel(gpio_image & ~S626_GPIO1_HI, dev->mmio + S626_P_GPIO);
1533                 /* and stretch it out */
1534                 writel(gpio_image & ~S626_GPIO1_HI, dev->mmio + S626_P_GPIO);
1535                 writel(gpio_image & ~S626_GPIO1_HI, dev->mmio + S626_P_GPIO);
1536                 /* Negate ADC Start command */
1537                 writel(gpio_image | S626_GPIO1_HI, dev->mmio + S626_P_GPIO);
1538
1539                 /*
1540                  * Wait for ADC to complete (GPIO2 is asserted high when
1541                  * ADC not busy) and for data from previous conversion to
1542                  * shift into FB BUFFER 1 register.
1543                  */
1544
1545                 /* Wait for ADC done */
1546                 ret = comedi_timeout(dev, s, insn, s626_ai_eoc, 0);
1547                 if (ret)
1548                         return ret;
1549
1550                 /* Fetch ADC data */
1551                 if (n != 0) {
1552                         tmp = readl(dev->mmio + S626_P_FB_BUFFER1);
1553                         data[n - 1] = s626_ai_reg_to_uint(tmp);
1554                 }
1555
1556                 /*
1557                  * Allow the ADC to stabilize for 4 microseconds before
1558                  * starting the next (final) conversion.  This delay is
1559                  * necessary to allow sufficient time between last
1560                  * conversion finished and the start of the next
1561                  * conversion.  Without this delay, the last conversion's
1562                  * data value is sometimes set to the previous
1563                  * conversion's data value.
1564                  */
1565                 udelay(4);
1566         }
1567
1568         /*
1569          * Start a dummy conversion to cause the data from the
1570          * previous conversion to be shifted in.
1571          */
1572         gpio_image = readl(dev->mmio + S626_P_GPIO);
1573         /* Assert ADC Start command */
1574         writel(gpio_image & ~S626_GPIO1_HI, dev->mmio + S626_P_GPIO);
1575         /* and stretch it out */
1576         writel(gpio_image & ~S626_GPIO1_HI, dev->mmio + S626_P_GPIO);
1577         writel(gpio_image & ~S626_GPIO1_HI, dev->mmio + S626_P_GPIO);
1578         /* Negate ADC Start command */
1579         writel(gpio_image | S626_GPIO1_HI, dev->mmio + S626_P_GPIO);
1580
1581         /* Wait for the data to arrive in FB BUFFER 1 register. */
1582
1583         /* Wait for ADC done */
1584         ret = comedi_timeout(dev, s, insn, s626_ai_eoc, 0);
1585         if (ret)
1586                 return ret;
1587
1588         /* Fetch ADC data from audio interface's input shift register. */
1589
1590         /* Fetch ADC data */
1591         if (n != 0) {
1592                 tmp = readl(dev->mmio + S626_P_FB_BUFFER1);
1593                 data[n - 1] = s626_ai_reg_to_uint(tmp);
1594         }
1595
1596         return n;
1597 }
1598
1599 static int s626_ai_load_polllist(u8 *ppl, struct comedi_cmd *cmd)
1600 {
1601         int n;
1602
1603         for (n = 0; n < cmd->chanlist_len; n++) {
1604                 if (CR_RANGE(cmd->chanlist[n]) == 0)
1605                         ppl[n] = CR_CHAN(cmd->chanlist[n]) | S626_RANGE_5V;
1606                 else
1607                         ppl[n] = CR_CHAN(cmd->chanlist[n]) | S626_RANGE_10V;
1608         }
1609         if (n != 0)
1610                 ppl[n - 1] |= S626_EOPL;
1611
1612         return n;
1613 }
1614
1615 static int s626_ai_inttrig(struct comedi_device *dev,
1616                            struct comedi_subdevice *s,
1617                            unsigned int trig_num)
1618 {
1619         struct comedi_cmd *cmd = &s->async->cmd;
1620
1621         if (trig_num != cmd->start_arg)
1622                 return -EINVAL;
1623
1624         /* Start executing the RPS program */
1625         s626_mc_enable(dev, S626_MC1_ERPS1, S626_P_MC1);
1626
1627         s->async->inttrig = NULL;
1628
1629         return 1;
1630 }
1631
1632 /*
1633  * This function doesn't require a particular form, this is just what
1634  * happens to be used in some of the drivers.  It should convert ns
1635  * nanoseconds to a counter value suitable for programming the device.
1636  * Also, it should adjust ns so that it cooresponds to the actual time
1637  * that the device will use.
1638  */
1639 static int s626_ns_to_timer(unsigned int *nanosec, unsigned int flags)
1640 {
1641         int divider, base;
1642
1643         base = 500;             /* 2MHz internal clock */
1644
1645         switch (flags & CMDF_ROUND_MASK) {
1646         case CMDF_ROUND_NEAREST:
1647         default:
1648                 divider = DIV_ROUND_CLOSEST(*nanosec, base);
1649                 break;
1650         case CMDF_ROUND_DOWN:
1651                 divider = (*nanosec) / base;
1652                 break;
1653         case CMDF_ROUND_UP:
1654                 divider = DIV_ROUND_UP(*nanosec, base);
1655                 break;
1656         }
1657
1658         *nanosec = base * divider;
1659         return divider - 1;
1660 }
1661
1662 static void s626_timer_load(struct comedi_device *dev,
1663                             unsigned int chan, int tick)
1664 {
1665         u16 setup =
1666                 /* Preload upon index. */
1667                 S626_SET_STD_LOADSRC(S626_LOADSRC_INDX) |
1668                 /* Disable hardware index. */
1669                 S626_SET_STD_INDXSRC(S626_INDXSRC_SOFT) |
1670                 /* Operating mode is Timer. */
1671                 S626_SET_STD_ENCMODE(S626_ENCMODE_TIMER) |
1672                 /* Count direction is Down. */
1673                 S626_SET_STD_CLKPOL(S626_CNTDIR_DOWN) |
1674                 /* Clock multiplier is 1x. */
1675                 S626_SET_STD_CLKMULT(S626_CLKMULT_1X) |
1676                 /* Enabled by index */
1677                 S626_SET_STD_CLKENAB(S626_CLKENAB_INDEX);
1678         u16 value_latchsrc = S626_LATCHSRC_A_INDXA;
1679         /* uint16_t enab = S626_CLKENAB_ALWAYS; */
1680
1681         s626_set_mode(dev, chan, setup, false);
1682
1683         /* Set the preload register */
1684         s626_preload(dev, chan, tick);
1685
1686         /*
1687          * Software index pulse forces the preload register to load
1688          * into the counter
1689          */
1690         s626_set_load_trig(dev, chan, 0);
1691         s626_pulse_index(dev, chan);
1692
1693         /* set reload on counter overflow */
1694         s626_set_load_trig(dev, chan, 1);
1695
1696         /* set interrupt on overflow */
1697         s626_set_int_src(dev, chan, S626_INTSRC_OVER);
1698
1699         s626_set_latch_source(dev, chan, value_latchsrc);
1700         /* s626_set_enable(dev, chan, (uint16_t)(enab != 0)); */
1701 }
1702
1703 /* TO COMPLETE  */
1704 static int s626_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
1705 {
1706         struct s626_private *devpriv = dev->private;
1707         u8 ppl[16];
1708         struct comedi_cmd *cmd = &s->async->cmd;
1709         int tick;
1710
1711         if (devpriv->ai_cmd_running) {
1712                 dev_err(dev->class_dev,
1713                         "s626_ai_cmd: Another ai_cmd is running\n");
1714                 return -EBUSY;
1715         }
1716         /* disable interrupt */
1717         writel(0, dev->mmio + S626_P_IER);
1718
1719         /* clear interrupt request */
1720         writel(S626_IRQ_RPS1 | S626_IRQ_GPIO3, dev->mmio + S626_P_ISR);
1721
1722         /* clear any pending interrupt */
1723         s626_dio_clear_irq(dev);
1724         /* s626_enc_clear_irq(dev); */
1725
1726         /* reset ai_cmd_running flag */
1727         devpriv->ai_cmd_running = 0;
1728
1729         s626_ai_load_polllist(ppl, cmd);
1730         devpriv->ai_cmd_running = 1;
1731         devpriv->ai_convert_count = 0;
1732
1733         switch (cmd->scan_begin_src) {
1734         case TRIG_FOLLOW:
1735                 break;
1736         case TRIG_TIMER:
1737                 /*
1738                  * set a counter to generate adc trigger at scan_begin_arg
1739                  * interval
1740                  */
1741                 tick = s626_ns_to_timer(&cmd->scan_begin_arg, cmd->flags);
1742
1743                 /* load timer value and enable interrupt */
1744                 s626_timer_load(dev, 5, tick);
1745                 s626_set_enable(dev, 5, S626_CLKENAB_ALWAYS);
1746                 break;
1747         case TRIG_EXT:
1748                 /* set the digital line and interrupt for scan trigger */
1749                 if (cmd->start_src != TRIG_EXT)
1750                         s626_dio_set_irq(dev, cmd->scan_begin_arg);
1751                 break;
1752         }
1753
1754         switch (cmd->convert_src) {
1755         case TRIG_NOW:
1756                 break;
1757         case TRIG_TIMER:
1758                 /*
1759                  * set a counter to generate adc trigger at convert_arg
1760                  * interval
1761                  */
1762                 tick = s626_ns_to_timer(&cmd->convert_arg, cmd->flags);
1763
1764                 /* load timer value and enable interrupt */
1765                 s626_timer_load(dev, 4, tick);
1766                 s626_set_enable(dev, 4, S626_CLKENAB_INDEX);
1767                 break;
1768         case TRIG_EXT:
1769                 /* set the digital line and interrupt for convert trigger */
1770                 if (cmd->scan_begin_src != TRIG_EXT &&
1771                     cmd->start_src == TRIG_EXT)
1772                         s626_dio_set_irq(dev, cmd->convert_arg);
1773                 break;
1774         }
1775
1776         s626_reset_adc(dev, ppl);
1777
1778         switch (cmd->start_src) {
1779         case TRIG_NOW:
1780                 /* Trigger ADC scan loop start */
1781                 /* s626_mc_enable(dev, S626_MC2_ADC_RPS, S626_P_MC2); */
1782
1783                 /* Start executing the RPS program */
1784                 s626_mc_enable(dev, S626_MC1_ERPS1, S626_P_MC1);
1785                 s->async->inttrig = NULL;
1786                 break;
1787         case TRIG_EXT:
1788                 /* configure DIO channel for acquisition trigger */
1789                 s626_dio_set_irq(dev, cmd->start_arg);
1790                 s->async->inttrig = NULL;
1791                 break;
1792         case TRIG_INT:
1793                 s->async->inttrig = s626_ai_inttrig;
1794                 break;
1795         }
1796
1797         /* enable interrupt */
1798         writel(S626_IRQ_GPIO3 | S626_IRQ_RPS1, dev->mmio + S626_P_IER);
1799
1800         return 0;
1801 }
1802
1803 static int s626_ai_cmdtest(struct comedi_device *dev,
1804                            struct comedi_subdevice *s, struct comedi_cmd *cmd)
1805 {
1806         int err = 0;
1807         unsigned int arg;
1808
1809         /* Step 1 : check if triggers are trivially valid */
1810
1811         err |= comedi_check_trigger_src(&cmd->start_src,
1812                                         TRIG_NOW | TRIG_INT | TRIG_EXT);
1813         err |= comedi_check_trigger_src(&cmd->scan_begin_src,
1814                                         TRIG_TIMER | TRIG_EXT | TRIG_FOLLOW);
1815         err |= comedi_check_trigger_src(&cmd->convert_src,
1816                                         TRIG_TIMER | TRIG_EXT | TRIG_NOW);
1817         err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
1818         err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
1819
1820         if (err)
1821                 return 1;
1822
1823         /* Step 2a : make sure trigger sources are unique */
1824
1825         err |= comedi_check_trigger_is_unique(cmd->start_src);
1826         err |= comedi_check_trigger_is_unique(cmd->scan_begin_src);
1827         err |= comedi_check_trigger_is_unique(cmd->convert_src);
1828         err |= comedi_check_trigger_is_unique(cmd->stop_src);
1829
1830         /* Step 2b : and mutually compatible */
1831
1832         if (err)
1833                 return 2;
1834
1835         /* Step 3: check if arguments are trivially valid */
1836
1837         switch (cmd->start_src) {
1838         case TRIG_NOW:
1839         case TRIG_INT:
1840                 err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0);
1841                 break;
1842         case TRIG_EXT:
1843                 err |= comedi_check_trigger_arg_max(&cmd->start_arg, 39);
1844                 break;
1845         }
1846
1847         if (cmd->scan_begin_src == TRIG_EXT)
1848                 err |= comedi_check_trigger_arg_max(&cmd->scan_begin_arg, 39);
1849         if (cmd->convert_src == TRIG_EXT)
1850                 err |= comedi_check_trigger_arg_max(&cmd->convert_arg, 39);
1851
1852 #define S626_MAX_SPEED  200000  /* in nanoseconds */
1853 #define S626_MIN_SPEED  2000000000      /* in nanoseconds */
1854
1855         if (cmd->scan_begin_src == TRIG_TIMER) {
1856                 err |= comedi_check_trigger_arg_min(&cmd->scan_begin_arg,
1857                                                     S626_MAX_SPEED);
1858                 err |= comedi_check_trigger_arg_max(&cmd->scan_begin_arg,
1859                                                     S626_MIN_SPEED);
1860         } else {
1861                 /*
1862                  * external trigger
1863                  * should be level/edge, hi/lo specification here
1864                  * should specify multiple external triggers
1865                  * err |= comedi_check_trigger_arg_max(&cmd->scan_begin_arg, 9);
1866                  */
1867         }
1868         if (cmd->convert_src == TRIG_TIMER) {
1869                 err |= comedi_check_trigger_arg_min(&cmd->convert_arg,
1870                                                     S626_MAX_SPEED);
1871                 err |= comedi_check_trigger_arg_max(&cmd->convert_arg,
1872                                                     S626_MIN_SPEED);
1873         } else {
1874                 /*
1875                  * external trigger - see above
1876                  * err |= comedi_check_trigger_arg_max(&cmd->scan_begin_arg, 9);
1877                  */
1878         }
1879
1880         err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg,
1881                                            cmd->chanlist_len);
1882
1883         if (cmd->stop_src == TRIG_COUNT)
1884                 err |= comedi_check_trigger_arg_min(&cmd->stop_arg, 1);
1885         else    /* TRIG_NONE */
1886                 err |= comedi_check_trigger_arg_is(&cmd->stop_arg, 0);
1887
1888         if (err)
1889                 return 3;
1890
1891         /* step 4: fix up any arguments */
1892
1893         if (cmd->scan_begin_src == TRIG_TIMER) {
1894                 arg = cmd->scan_begin_arg;
1895                 s626_ns_to_timer(&arg, cmd->flags);
1896                 err |= comedi_check_trigger_arg_is(&cmd->scan_begin_arg, arg);
1897         }
1898
1899         if (cmd->convert_src == TRIG_TIMER) {
1900                 arg = cmd->convert_arg;
1901                 s626_ns_to_timer(&arg, cmd->flags);
1902                 err |= comedi_check_trigger_arg_is(&cmd->convert_arg, arg);
1903
1904                 if (cmd->scan_begin_src == TRIG_TIMER) {
1905                         arg = cmd->convert_arg * cmd->scan_end_arg;
1906                         err |= comedi_check_trigger_arg_min(&cmd->
1907                                                             scan_begin_arg,
1908                                                             arg);
1909                 }
1910         }
1911
1912         if (err)
1913                 return 4;
1914
1915         return 0;
1916 }
1917
1918 static int s626_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
1919 {
1920         struct s626_private *devpriv = dev->private;
1921
1922         /* Stop RPS program in case it is currently running */
1923         s626_mc_disable(dev, S626_MC1_ERPS1, S626_P_MC1);
1924
1925         /* disable master interrupt */
1926         writel(0, dev->mmio + S626_P_IER);
1927
1928         devpriv->ai_cmd_running = 0;
1929
1930         return 0;
1931 }
1932
1933 static int s626_ao_insn_write(struct comedi_device *dev,
1934                               struct comedi_subdevice *s,
1935                               struct comedi_insn *insn,
1936                               unsigned int *data)
1937 {
1938         unsigned int chan = CR_CHAN(insn->chanspec);
1939         int i;
1940
1941         for (i = 0; i < insn->n; i++) {
1942                 s16 dacdata = (s16)data[i];
1943                 int ret;
1944
1945                 dacdata -= (0x1fff);
1946
1947                 ret = s626_set_dac(dev, chan, dacdata);
1948                 if (ret)
1949                         return ret;
1950
1951                 s->readback[chan] = data[i];
1952         }
1953
1954         return insn->n;
1955 }
1956
1957 /* *************** DIGITAL I/O FUNCTIONS *************** */
1958
1959 /*
1960  * All DIO functions address a group of DIO channels by means of
1961  * "group" argument.  group may be 0, 1 or 2, which correspond to DIO
1962  * ports A, B and C, respectively.
1963  */
1964
1965 static void s626_dio_init(struct comedi_device *dev)
1966 {
1967         u16 group;
1968
1969         /* Prepare to treat writes to WRCapSel as capture disables. */
1970         s626_debi_write(dev, S626_LP_MISC1, S626_MISC1_NOEDCAP);
1971
1972         /* For each group of sixteen channels ... */
1973         for (group = 0; group < S626_DIO_BANKS; group++) {
1974                 /* Disable all interrupts */
1975                 s626_debi_write(dev, S626_LP_WRINTSEL(group), 0);
1976                 /* Disable all event captures */
1977                 s626_debi_write(dev, S626_LP_WRCAPSEL(group), 0xffff);
1978                 /* Init all DIOs to default edge polarity */
1979                 s626_debi_write(dev, S626_LP_WREDGSEL(group), 0);
1980                 /* Program all outputs to inactive state */
1981                 s626_debi_write(dev, S626_LP_WRDOUT(group), 0);
1982         }
1983 }
1984
1985 static int s626_dio_insn_bits(struct comedi_device *dev,
1986                               struct comedi_subdevice *s,
1987                               struct comedi_insn *insn,
1988                               unsigned int *data)
1989 {
1990         unsigned long group = (unsigned long)s->private;
1991
1992         if (comedi_dio_update_state(s, data))
1993                 s626_debi_write(dev, S626_LP_WRDOUT(group), s->state);
1994
1995         data[1] = s626_debi_read(dev, S626_LP_RDDIN(group));
1996
1997         return insn->n;
1998 }
1999
2000 static int s626_dio_insn_config(struct comedi_device *dev,
2001                                 struct comedi_subdevice *s,
2002                                 struct comedi_insn *insn,
2003                                 unsigned int *data)
2004 {
2005         unsigned long group = (unsigned long)s->private;
2006         int ret;
2007
2008         ret = comedi_dio_insn_config(dev, s, insn, data, 0);
2009         if (ret)
2010                 return ret;
2011
2012         s626_debi_write(dev, S626_LP_WRDOUT(group), s->io_bits);
2013
2014         return insn->n;
2015 }
2016
2017 /*
2018  * Now this function initializes the value of the counter (data[0])
2019  * and set the subdevice. To complete with trigger and interrupt
2020  * configuration.
2021  *
2022  * FIXME: data[0] is supposed to be an INSN_CONFIG_xxx constant indicating
2023  * what is being configured, but this function appears to be using data[0]
2024  * as a variable.
2025  */
2026 static int s626_enc_insn_config(struct comedi_device *dev,
2027                                 struct comedi_subdevice *s,
2028                                 struct comedi_insn *insn, unsigned int *data)
2029 {
2030         unsigned int chan = CR_CHAN(insn->chanspec);
2031         u16 setup =
2032                 /* Preload upon index. */
2033                 S626_SET_STD_LOADSRC(S626_LOADSRC_INDX) |
2034                 /* Disable hardware index. */
2035                 S626_SET_STD_INDXSRC(S626_INDXSRC_SOFT) |
2036                 /* Operating mode is Counter. */
2037                 S626_SET_STD_ENCMODE(S626_ENCMODE_COUNTER) |
2038                 /* Active high clock. */
2039                 S626_SET_STD_CLKPOL(S626_CLKPOL_POS) |
2040                 /* Clock multiplier is 1x. */
2041                 S626_SET_STD_CLKMULT(S626_CLKMULT_1X) |
2042                 /* Enabled by index */
2043                 S626_SET_STD_CLKENAB(S626_CLKENAB_INDEX);
2044         /* uint16_t disable_int_src = true; */
2045         /* uint32_t Preloadvalue;              //Counter initial value */
2046         u16 value_latchsrc = S626_LATCHSRC_AB_READ;
2047         u16 enab = S626_CLKENAB_ALWAYS;
2048
2049         /* (data==NULL) ? (Preloadvalue=0) : (Preloadvalue=data[0]); */
2050
2051         s626_set_mode(dev, chan, setup, true);
2052         s626_preload(dev, chan, data[0]);
2053         s626_pulse_index(dev, chan);
2054         s626_set_latch_source(dev, chan, value_latchsrc);
2055         s626_set_enable(dev, chan, (enab != 0));
2056
2057         return insn->n;
2058 }
2059
2060 static int s626_enc_insn_read(struct comedi_device *dev,
2061                               struct comedi_subdevice *s,
2062                               struct comedi_insn *insn,
2063                               unsigned int *data)
2064 {
2065         unsigned int chan = CR_CHAN(insn->chanspec);
2066         u16 cntr_latch_reg = S626_LP_CNTR(chan);
2067         int i;
2068
2069         for (i = 0; i < insn->n; i++) {
2070                 unsigned int val;
2071
2072                 /*
2073                  * Read the counter's output latch LSW/MSW.
2074                  * Latches on LSW read.
2075                  */
2076                 val = s626_debi_read(dev, cntr_latch_reg);
2077                 val |= (s626_debi_read(dev, cntr_latch_reg + 2) << 16);
2078                 data[i] = val;
2079         }
2080
2081         return insn->n;
2082 }
2083
2084 static int s626_enc_insn_write(struct comedi_device *dev,
2085                                struct comedi_subdevice *s,
2086                                struct comedi_insn *insn, unsigned int *data)
2087 {
2088         unsigned int chan = CR_CHAN(insn->chanspec);
2089
2090         /* Set the preload register */
2091         s626_preload(dev, chan, data[0]);
2092
2093         /*
2094          * Software index pulse forces the preload register to load
2095          * into the counter
2096          */
2097         s626_set_load_trig(dev, chan, 0);
2098         s626_pulse_index(dev, chan);
2099         s626_set_load_trig(dev, chan, 2);
2100
2101         return 1;
2102 }
2103
2104 static void s626_write_misc2(struct comedi_device *dev, u16 new_image)
2105 {
2106         s626_debi_write(dev, S626_LP_MISC1, S626_MISC1_WENABLE);
2107         s626_debi_write(dev, S626_LP_WRMISC2, new_image);
2108         s626_debi_write(dev, S626_LP_MISC1, S626_MISC1_WDISABLE);
2109 }
2110
2111 static void s626_counters_init(struct comedi_device *dev)
2112 {
2113         int chan;
2114         u16 setup =
2115                 /* Preload upon index. */
2116                 S626_SET_STD_LOADSRC(S626_LOADSRC_INDX) |
2117                 /* Disable hardware index. */
2118                 S626_SET_STD_INDXSRC(S626_INDXSRC_SOFT) |
2119                 /* Operating mode is counter. */
2120                 S626_SET_STD_ENCMODE(S626_ENCMODE_COUNTER) |
2121                 /* Active high clock. */
2122                 S626_SET_STD_CLKPOL(S626_CLKPOL_POS) |
2123                 /* Clock multiplier is 1x. */
2124                 S626_SET_STD_CLKMULT(S626_CLKMULT_1X) |
2125                 /* Enabled by index */
2126                 S626_SET_STD_CLKENAB(S626_CLKENAB_INDEX);
2127
2128         /*
2129          * Disable all counter interrupts and clear any captured counter events.
2130          */
2131         for (chan = 0; chan < S626_ENCODER_CHANNELS; chan++) {
2132                 s626_set_mode(dev, chan, setup, true);
2133                 s626_set_int_src(dev, chan, 0);
2134                 s626_reset_cap_flags(dev, chan);
2135                 s626_set_enable(dev, chan, S626_CLKENAB_ALWAYS);
2136         }
2137 }
2138
2139 static int s626_allocate_dma_buffers(struct comedi_device *dev)
2140 {
2141         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
2142         struct s626_private *devpriv = dev->private;
2143         void *addr;
2144         dma_addr_t appdma;
2145
2146         addr = pci_alloc_consistent(pcidev, S626_DMABUF_SIZE, &appdma);
2147         if (!addr)
2148                 return -ENOMEM;
2149         devpriv->ana_buf.logical_base = addr;
2150         devpriv->ana_buf.physical_base = appdma;
2151
2152         addr = pci_alloc_consistent(pcidev, S626_DMABUF_SIZE, &appdma);
2153         if (!addr)
2154                 return -ENOMEM;
2155         devpriv->rps_buf.logical_base = addr;
2156         devpriv->rps_buf.physical_base = appdma;
2157
2158         return 0;
2159 }
2160
2161 static void s626_free_dma_buffers(struct comedi_device *dev)
2162 {
2163         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
2164         struct s626_private *devpriv = dev->private;
2165
2166         if (!devpriv)
2167                 return;
2168
2169         if (devpriv->rps_buf.logical_base)
2170                 pci_free_consistent(pcidev, S626_DMABUF_SIZE,
2171                                     devpriv->rps_buf.logical_base,
2172                                     devpriv->rps_buf.physical_base);
2173         if (devpriv->ana_buf.logical_base)
2174                 pci_free_consistent(pcidev, S626_DMABUF_SIZE,
2175                                     devpriv->ana_buf.logical_base,
2176                                     devpriv->ana_buf.physical_base);
2177 }
2178
2179 static int s626_initialize(struct comedi_device *dev)
2180 {
2181         struct s626_private *devpriv = dev->private;
2182         dma_addr_t phys_buf;
2183         u16 chan;
2184         int i;
2185         int ret;
2186
2187         /* Enable DEBI and audio pins, enable I2C interface */
2188         s626_mc_enable(dev, S626_MC1_DEBI | S626_MC1_AUDIO | S626_MC1_I2C,
2189                        S626_P_MC1);
2190
2191         /*
2192          * Configure DEBI operating mode
2193          *
2194          *  Local bus is 16 bits wide
2195          *  Declare DEBI transfer timeout interval
2196          *  Set up byte lane steering
2197          *  Intel-compatible local bus (DEBI never times out)
2198          */
2199         writel(S626_DEBI_CFG_SLAVE16 |
2200                (S626_DEBI_TOUT << S626_DEBI_CFG_TOUT_BIT) | S626_DEBI_SWAP |
2201                S626_DEBI_CFG_INTEL, dev->mmio + S626_P_DEBICFG);
2202
2203         /* Disable MMU paging */
2204         writel(S626_DEBI_PAGE_DISABLE, dev->mmio + S626_P_DEBIPAGE);
2205
2206         /* Init GPIO so that ADC Start* is negated */
2207         writel(S626_GPIO_BASE | S626_GPIO1_HI, dev->mmio + S626_P_GPIO);
2208
2209         /* I2C device address for onboard eeprom (revb) */
2210         devpriv->i2c_adrs = 0xA0;
2211
2212         /*
2213          * Issue an I2C ABORT command to halt any I2C
2214          * operation in progress and reset BUSY flag.
2215          */
2216         writel(S626_I2C_CLKSEL | S626_I2C_ABORT,
2217                dev->mmio + S626_P_I2CSTAT);
2218         s626_mc_enable(dev, S626_MC2_UPLD_IIC, S626_P_MC2);
2219         ret = comedi_timeout(dev, NULL, NULL, s626_i2c_handshake_eoc, 0);
2220         if (ret)
2221                 return ret;
2222
2223         /*
2224          * Per SAA7146 data sheet, write to STATUS
2225          * reg twice to reset all  I2C error flags.
2226          */
2227         for (i = 0; i < 2; i++) {
2228                 writel(S626_I2C_CLKSEL, dev->mmio + S626_P_I2CSTAT);
2229                 s626_mc_enable(dev, S626_MC2_UPLD_IIC, S626_P_MC2);
2230                 ret = comedi_timeout(dev, NULL,
2231                                      NULL, s626_i2c_handshake_eoc, 0);
2232                 if (ret)
2233                         return ret;
2234         }
2235
2236         /*
2237          * Init audio interface functional attributes: set DAC/ADC
2238          * serial clock rates, invert DAC serial clock so that
2239          * DAC data setup times are satisfied, enable DAC serial
2240          * clock out.
2241          */
2242         writel(S626_ACON2_INIT, dev->mmio + S626_P_ACON2);
2243
2244         /*
2245          * Set up TSL1 slot list, which is used to control the
2246          * accumulation of ADC data: S626_RSD1 = shift data in on SD1.
2247          * S626_SIB_A1  = store data uint8_t at next available location
2248          * in FB BUFFER1 register.
2249          */
2250         writel(S626_RSD1 | S626_SIB_A1, dev->mmio + S626_P_TSL1);
2251         writel(S626_RSD1 | S626_SIB_A1 | S626_EOS,
2252                dev->mmio + S626_P_TSL1 + 4);
2253
2254         /* Enable TSL1 slot list so that it executes all the time */
2255         writel(S626_ACON1_ADCSTART, dev->mmio + S626_P_ACON1);
2256
2257         /*
2258          * Initialize RPS registers used for ADC
2259          */
2260
2261         /* Physical start of RPS program */
2262         writel((u32)devpriv->rps_buf.physical_base,
2263                dev->mmio + S626_P_RPSADDR1);
2264         /* RPS program performs no explicit mem writes */
2265         writel(0, dev->mmio + S626_P_RPSPAGE1);
2266         /* Disable RPS timeouts */
2267         writel(0, dev->mmio + S626_P_RPS1_TOUT);
2268
2269 #if 0
2270         /*
2271          * SAA7146 BUG WORKAROUND
2272          *
2273          * Initialize SAA7146 ADC interface to a known state by
2274          * invoking ADCs until FB BUFFER 1 register shows that it
2275          * is correctly receiving ADC data. This is necessary
2276          * because the SAA7146 ADC interface does not start up in
2277          * a defined state after a PCI reset.
2278          */
2279         {
2280                 struct comedi_subdevice *s = dev->read_subdev;
2281                 uint8_t poll_list;
2282                 uint16_t adc_data;
2283                 uint16_t start_val;
2284                 uint16_t index;
2285                 unsigned int data[16];
2286
2287                 /* Create a simple polling list for analog input channel 0 */
2288                 poll_list = S626_EOPL;
2289                 s626_reset_adc(dev, &poll_list);
2290
2291                 /* Get initial ADC value */
2292                 s626_ai_rinsn(dev, s, NULL, data);
2293                 start_val = data[0];
2294
2295                 /*
2296                  * VERSION 2.01 CHANGE: TIMEOUT ADDED TO PREVENT HANGED
2297                  * EXECUTION.
2298                  *
2299                  * Invoke ADCs until the new ADC value differs from the initial
2300                  * value or a timeout occurs.  The timeout protects against the
2301                  * possibility that the driver is restarting and the ADC data is
2302                  * a fixed value resulting from the applied ADC analog input
2303                  * being unusually quiet or at the rail.
2304                  */
2305                 for (index = 0; index < 500; index++) {
2306                         s626_ai_rinsn(dev, s, NULL, data);
2307                         adc_data = data[0];
2308                         if (adc_data != start_val)
2309                                 break;
2310                 }
2311         }
2312 #endif  /* SAA7146 BUG WORKAROUND */
2313
2314         /*
2315          * Initialize the DAC interface
2316          */
2317
2318         /*
2319          * Init Audio2's output DMAC attributes:
2320          *   burst length = 1 DWORD
2321          *   threshold = 1 DWORD.
2322          */
2323         writel(0, dev->mmio + S626_P_PCI_BT_A);
2324
2325         /*
2326          * Init Audio2's output DMA physical addresses.  The protection
2327          * address is set to 1 DWORD past the base address so that a
2328          * single DWORD will be transferred each time a DMA transfer is
2329          * enabled.
2330          */
2331         phys_buf = devpriv->ana_buf.physical_base +
2332                    (S626_DAC_WDMABUF_OS * sizeof(u32));
2333         writel((u32)phys_buf, dev->mmio + S626_P_BASEA2_OUT);
2334         writel((u32)(phys_buf + sizeof(u32)),
2335                dev->mmio + S626_P_PROTA2_OUT);
2336
2337         /*
2338          * Cache Audio2's output DMA buffer logical address.  This is
2339          * where DAC data is buffered for A2 output DMA transfers.
2340          */
2341         devpriv->dac_wbuf = (u32 *)devpriv->ana_buf.logical_base +
2342                             S626_DAC_WDMABUF_OS;
2343
2344         /*
2345          * Audio2's output channels does not use paging.  The
2346          * protection violation handling bit is set so that the
2347          * DMAC will automatically halt and its PCI address pointer
2348          * will be reset when the protection address is reached.
2349          */
2350         writel(8, dev->mmio + S626_P_PAGEA2_OUT);
2351
2352         /*
2353          * Initialize time slot list 2 (TSL2), which is used to control
2354          * the clock generation for and serialization of data to be sent
2355          * to the DAC devices.  Slot 0 is a NOP that is used to trap TSL
2356          * execution; this permits other slots to be safely modified
2357          * without first turning off the TSL sequencer (which is
2358          * apparently impossible to do).  Also, SD3 (which is driven by a
2359          * pull-up resistor) is shifted in and stored to the MSB of
2360          * FB_BUFFER2 to be used as evidence that the slot sequence has
2361          * not yet finished executing.
2362          */
2363
2364         /* Slot 0: Trap TSL execution, shift 0xFF into FB_BUFFER2 */
2365         writel(S626_XSD2 | S626_RSD3 | S626_SIB_A2 | S626_EOS,
2366                dev->mmio + S626_VECTPORT(0));
2367
2368         /*
2369          * Initialize slot 1, which is constant.  Slot 1 causes a
2370          * DWORD to be transferred from audio channel 2's output FIFO
2371          * to the FIFO's output buffer so that it can be serialized
2372          * and sent to the DAC during subsequent slots.  All remaining
2373          * slots are dynamically populated as required by the target
2374          * DAC device.
2375          */
2376
2377         /* Slot 1: Fetch DWORD from Audio2's output FIFO */
2378         writel(S626_LF_A2, dev->mmio + S626_VECTPORT(1));
2379
2380         /* Start DAC's audio interface (TSL2) running */
2381         writel(S626_ACON1_DACSTART, dev->mmio + S626_P_ACON1);
2382
2383         /*
2384          * Init Trim DACs to calibrated values.  Do it twice because the
2385          * SAA7146 audio channel does not always reset properly and
2386          * sometimes causes the first few TrimDAC writes to malfunction.
2387          */
2388         s626_load_trim_dacs(dev);
2389         ret = s626_load_trim_dacs(dev);
2390         if (ret)
2391                 return ret;
2392
2393         /*
2394          * Manually init all gate array hardware in case this is a soft
2395          * reset (we have no way of determining whether this is a warm
2396          * or cold start).  This is necessary because the gate array will
2397          * reset only in response to a PCI hard reset; there is no soft
2398          * reset function.
2399          */
2400
2401         /*
2402          * Init all DAC outputs to 0V and init all DAC setpoint and
2403          * polarity images.
2404          */
2405         for (chan = 0; chan < S626_DAC_CHANNELS; chan++) {
2406                 ret = s626_set_dac(dev, chan, 0);
2407                 if (ret)
2408                         return ret;
2409         }
2410
2411         /* Init counters */
2412         s626_counters_init(dev);
2413
2414         /*
2415          * Without modifying the state of the Battery Backup enab, disable
2416          * the watchdog timer, set DIO channels 0-5 to operate in the
2417          * standard DIO (vs. counter overflow) mode, disable the battery
2418          * charger, and reset the watchdog interval selector to zero.
2419          */
2420         s626_write_misc2(dev, (s626_debi_read(dev, S626_LP_RDMISC2) &
2421                                S626_MISC2_BATT_ENABLE));
2422
2423         /* Initialize the digital I/O subsystem */
2424         s626_dio_init(dev);
2425
2426         return 0;
2427 }
2428
2429 static int s626_auto_attach(struct comedi_device *dev,
2430                             unsigned long context_unused)
2431 {
2432         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
2433         struct s626_private *devpriv;
2434         struct comedi_subdevice *s;
2435         int ret;
2436
2437         devpriv = comedi_alloc_devpriv(dev, sizeof(*devpriv));
2438         if (!devpriv)
2439                 return -ENOMEM;
2440
2441         ret = comedi_pci_enable(dev);
2442         if (ret)
2443                 return ret;
2444
2445         dev->mmio = pci_ioremap_bar(pcidev, 0);
2446         if (!dev->mmio)
2447                 return -ENOMEM;
2448
2449         /* disable master interrupt */
2450         writel(0, dev->mmio + S626_P_IER);
2451
2452         /* soft reset */
2453         writel(S626_MC1_SOFT_RESET, dev->mmio + S626_P_MC1);
2454
2455         /* DMA FIXME DMA// */
2456
2457         ret = s626_allocate_dma_buffers(dev);
2458         if (ret)
2459                 return ret;
2460
2461         if (pcidev->irq) {
2462                 ret = request_irq(pcidev->irq, s626_irq_handler, IRQF_SHARED,
2463                                   dev->board_name, dev);
2464
2465                 if (ret == 0)
2466                         dev->irq = pcidev->irq;
2467         }
2468
2469         ret = comedi_alloc_subdevices(dev, 6);
2470         if (ret)
2471                 return ret;
2472
2473         s = &dev->subdevices[0];
2474         /* analog input subdevice */
2475         s->type         = COMEDI_SUBD_AI;
2476         s->subdev_flags = SDF_READABLE | SDF_DIFF;
2477         s->n_chan       = S626_ADC_CHANNELS;
2478         s->maxdata      = 0x3fff;
2479         s->range_table  = &s626_range_table;
2480         s->len_chanlist = S626_ADC_CHANNELS;
2481         s->insn_read    = s626_ai_insn_read;
2482         if (dev->irq) {
2483                 dev->read_subdev = s;
2484                 s->subdev_flags |= SDF_CMD_READ;
2485                 s->do_cmd       = s626_ai_cmd;
2486                 s->do_cmdtest   = s626_ai_cmdtest;
2487                 s->cancel       = s626_ai_cancel;
2488         }
2489
2490         s = &dev->subdevices[1];
2491         /* analog output subdevice */
2492         s->type         = COMEDI_SUBD_AO;
2493         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
2494         s->n_chan       = S626_DAC_CHANNELS;
2495         s->maxdata      = 0x3fff;
2496         s->range_table  = &range_bipolar10;
2497         s->insn_write   = s626_ao_insn_write;
2498
2499         ret = comedi_alloc_subdev_readback(s);
2500         if (ret)
2501                 return ret;
2502
2503         s = &dev->subdevices[2];
2504         /* digital I/O subdevice */
2505         s->type         = COMEDI_SUBD_DIO;
2506         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
2507         s->n_chan       = 16;
2508         s->maxdata      = 1;
2509         s->io_bits      = 0xffff;
2510         s->private      = (void *)0;    /* DIO group 0 */
2511         s->range_table  = &range_digital;
2512         s->insn_config  = s626_dio_insn_config;
2513         s->insn_bits    = s626_dio_insn_bits;
2514
2515         s = &dev->subdevices[3];
2516         /* digital I/O subdevice */
2517         s->type         = COMEDI_SUBD_DIO;
2518         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
2519         s->n_chan       = 16;
2520         s->maxdata      = 1;
2521         s->io_bits      = 0xffff;
2522         s->private      = (void *)1;    /* DIO group 1 */
2523         s->range_table  = &range_digital;
2524         s->insn_config  = s626_dio_insn_config;
2525         s->insn_bits    = s626_dio_insn_bits;
2526
2527         s = &dev->subdevices[4];
2528         /* digital I/O subdevice */
2529         s->type         = COMEDI_SUBD_DIO;
2530         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
2531         s->n_chan       = 16;
2532         s->maxdata      = 1;
2533         s->io_bits      = 0xffff;
2534         s->private      = (void *)2;    /* DIO group 2 */
2535         s->range_table  = &range_digital;
2536         s->insn_config  = s626_dio_insn_config;
2537         s->insn_bits    = s626_dio_insn_bits;
2538
2539         s = &dev->subdevices[5];
2540         /* encoder (counter) subdevice */
2541         s->type         = COMEDI_SUBD_COUNTER;
2542         s->subdev_flags = SDF_WRITABLE | SDF_READABLE | SDF_LSAMPL;
2543         s->n_chan       = S626_ENCODER_CHANNELS;
2544         s->maxdata      = 0xffffff;
2545         s->range_table  = &range_unknown;
2546         s->insn_config  = s626_enc_insn_config;
2547         s->insn_read    = s626_enc_insn_read;
2548         s->insn_write   = s626_enc_insn_write;
2549
2550         return s626_initialize(dev);
2551 }
2552
2553 static void s626_detach(struct comedi_device *dev)
2554 {
2555         struct s626_private *devpriv = dev->private;
2556
2557         if (devpriv) {
2558                 /* stop ai_command */
2559                 devpriv->ai_cmd_running = 0;
2560
2561                 if (dev->mmio) {
2562                         /* interrupt mask */
2563                         /* Disable master interrupt */
2564                         writel(0, dev->mmio + S626_P_IER);
2565                         /* Clear board's IRQ status flag */
2566                         writel(S626_IRQ_GPIO3 | S626_IRQ_RPS1,
2567                                dev->mmio + S626_P_ISR);
2568
2569                         /* Disable the watchdog timer and battery charger. */
2570                         s626_write_misc2(dev, 0);
2571
2572                         /* Close all interfaces on 7146 device */
2573                         writel(S626_MC1_SHUTDOWN, dev->mmio + S626_P_MC1);
2574                         writel(S626_ACON1_BASE, dev->mmio + S626_P_ACON1);
2575                 }
2576         }
2577         comedi_pci_detach(dev);
2578         s626_free_dma_buffers(dev);
2579 }
2580
2581 static struct comedi_driver s626_driver = {
2582         .driver_name    = "s626",
2583         .module         = THIS_MODULE,
2584         .auto_attach    = s626_auto_attach,
2585         .detach         = s626_detach,
2586 };
2587
2588 static int s626_pci_probe(struct pci_dev *dev,
2589                           const struct pci_device_id *id)
2590 {
2591         return comedi_pci_auto_config(dev, &s626_driver, id->driver_data);
2592 }
2593
2594 /*
2595  * For devices with vendor:device id == 0x1131:0x7146 you must specify
2596  * also subvendor:subdevice ids, because otherwise it will conflict with
2597  * Philips SAA7146 media/dvb based cards.
2598  */
2599 static const struct pci_device_id s626_pci_table[] = {
2600         { PCI_DEVICE_SUB(PCI_VENDOR_ID_PHILIPS, PCI_DEVICE_ID_PHILIPS_SAA7146,
2601                          0x6000, 0x0272) },
2602         { 0 }
2603 };
2604 MODULE_DEVICE_TABLE(pci, s626_pci_table);
2605
2606 static struct pci_driver s626_pci_driver = {
2607         .name           = "s626",
2608         .id_table       = s626_pci_table,
2609         .probe          = s626_pci_probe,
2610         .remove         = comedi_pci_auto_unconfig,
2611 };
2612 module_comedi_pci_driver(s626_driver, s626_pci_driver);
2613
2614 MODULE_AUTHOR("Gianluca Palli <gpalli@deis.unibo.it>");
2615 MODULE_DESCRIPTION("Sensoray 626 Comedi driver module");
2616 MODULE_LICENSE("GPL");