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