amplc_pci230.c 78.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * comedi/drivers/amplc_pci230.c
 * Driver for Amplicon PCI230 and PCI260 Multifunction I/O boards.
 *
 * Copyright (C) 2001 Allan Willcox <allanwillcox@ozemail.com.au>
 *
 * COMEDI - Linux Control and Measurement Device Interface
 * Copyright (C) 2000 David A. Schleef <ds@schleef.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
20 21

/*
22 23 24 25 26
 * Driver: amplc_pci230
 * Description: Amplicon PCI230, PCI260 Multifunction I/O boards
 * Author: Allan Willcox <allanwillcox@ozemail.com.au>,
 *   Steve D Sharples <steve.sharples@nottingham.ac.uk>,
 *   Ian Abbott <abbotti@mev.co.uk>
27 28
 * Updated: Mon, 01 Sep 2014 10:09:16 +0000
 * Devices: [Amplicon] PCI230 (amplc_pci230), PCI230+, PCI260, PCI260+
29 30 31
 * Status: works
 *
 * Configuration options:
32
 *   none
33
 *
34 35 36 37
 * Manual configuration of PCI cards is not supported; they are configured
 * automatically.
 *
 * The PCI230+ and PCI260+ have the same PCI device IDs as the PCI230 and
38
 * PCI260, but can be distinguished by the size of the PCI regions.  A
39
 * card will be configured as a "+" model if detected as such.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
 *
 * Subdevices:
 *
 *                 PCI230(+)    PCI260(+)
 *                 ---------    ---------
 *   Subdevices       3            1
 *         0          AI           AI
 *         1          AO
 *         2          DIO
 *
 * AI Subdevice:
 *
 *   The AI subdevice has 16 single-ended channels or 8 differential
 *   channels.
 *
 *   The PCI230 and PCI260 cards have 12-bit resolution.  The PCI230+ and
 *   PCI260+ cards have 16-bit resolution.
 *
 *   For differential mode, use inputs 2N and 2N+1 for channel N (e.g. use
 *   inputs 14 and 15 for channel 7).  If the card is physically a PCI230
 *   or PCI260 then it actually uses a "pseudo-differential" mode where the
 *   inputs are sampled a few microseconds apart.  The PCI230+ and PCI260+
 *   use true differential sampling.  Another difference is that if the
 *   card is physically a PCI230 or PCI260, the inverting input is 2N,
 *   whereas for a PCI230+ or PCI260+ the inverting input is 2N+1.  So if a
 *   PCI230 is physically replaced by a PCI230+ (or a PCI260 with a
 *   PCI260+) and differential mode is used, the differential inputs need
 *   to be physically swapped on the connector.
 *
 *   The following input ranges are supported:
 *
 *     0 => [-10, +10] V
 *     1 => [-5, +5] V
 *     2 => [-2.5, +2.5] V
 *     3 => [-1.25, +1.25] V
 *     4 => [0, 10] V
 *     5 => [0, 5] V
 *     6 => [0, 2.5] V
 *
 * AI Commands:
 *
 *   +=========+==============+===========+============+==========+
 *   |start_src|scan_begin_src|convert_src|scan_end_src| stop_src |
 *   +=========+==============+===========+============+==========+
 *   |TRIG_NOW | TRIG_FOLLOW  |TRIG_TIMER | TRIG_COUNT |TRIG_NONE |
 *   |TRIG_INT |              |TRIG_EXT(3)|            |TRIG_COUNT|
 *   |         |              |TRIG_INT   |            |          |
 *   |         |--------------|-----------|            |          |
 *   |         | TRIG_TIMER(1)|TRIG_TIMER |            |          |
 *   |         | TRIG_EXT(2)  |           |            |          |
 *   |         | TRIG_INT     |           |            |          |
 *   +---------+--------------+-----------+------------+----------+
 *
 *   Note 1: If AI command and AO command are used simultaneously, only
 *           one may have scan_begin_src == TRIG_TIMER.
 *
 *   Note 2: For PCI230 and PCI230+, scan_begin_src == TRIG_EXT uses
 *           DIO channel 16 (pin 49) which will need to be configured as
 *           a digital input.  For PCI260+, the EXTTRIG/EXTCONVCLK input
 *           (pin 17) is used instead.  For PCI230, scan_begin_src ==
 *           TRIG_EXT is not supported.  The trigger is a rising edge
 *           on the input.
 *
 *   Note 3: For convert_src == TRIG_EXT, the EXTTRIG/EXTCONVCLK input
 *           (pin 25 on PCI230(+), pin 17 on PCI260(+)) is used.  The
 *           convert_arg value is interpreted as follows:
 *
 *             convert_arg == (CR_EDGE | 0) => rising edge
 *             convert_arg == (CR_EDGE | CR_INVERT | 0) => falling edge
 *             convert_arg == 0 => falling edge (backwards compatibility)
 *             convert_arg == 1 => rising edge (backwards compatibility)
 *
 *   All entries in the channel list must use the same analogue reference.
 *   If the analogue reference is not AREF_DIFF (not differential) each
 *   pair of channel numbers (0 and 1, 2 and 3, etc.) must use the same
 *   input range.  The input ranges used in the sequence must be all
 *   bipolar (ranges 0 to 3) or all unipolar (ranges 4 to 6).  The channel
 *   sequence must consist of 1 or more identical subsequences.  Within the
 *   subsequence, channels must be in ascending order with no repeated
 *   channels.  For example, the following sequences are valid: 0 1 2 3
 *   (single valid subsequence), 0 2 3 5 0 2 3 5 (repeated valid
 *   subsequence), 1 1 1 1 (repeated valid subsequence).  The following
 *   sequences are invalid: 0 3 2 1 (invalid subsequence), 0 2 3 5 0 2 3
 *   (incompletely repeated subsequence).  Some versions of the PCI230+ and
 *   PCI260+ have a bug that requires a subsequence longer than one entry
 *   long to include channel 0.
 *
 * AO Subdevice:
 *
 *   The AO subdevice has 2 channels with 12-bit resolution.
 *   The following output ranges are supported:
 *     0 => [0, 10] V
 *     1 => [-10, +10] V
 *
 * AO Commands:
 *
 *   +=========+==============+===========+============+==========+
 *   |start_src|scan_begin_src|convert_src|scan_end_src| stop_src |
 *   +=========+==============+===========+============+==========+
 *   |TRIG_INT | TRIG_TIMER(1)| TRIG_NOW  | TRIG_COUNT |TRIG_NONE |
 *   |         | TRIG_EXT(2)  |           |            |TRIG_COUNT|
 *   |         | TRIG_INT     |           |            |          |
 *   +---------+--------------+-----------+------------+----------+
 *
 *   Note 1: If AI command and AO command are used simultaneously, only
 *           one may have scan_begin_src == TRIG_TIMER.
 *
 *   Note 2: scan_begin_src == TRIG_EXT is only supported if the card is
 *           configured as a PCI230+ and is only supported on later
 *           versions of the card.  As a card configured as a PCI230+ is
 *           not guaranteed to support external triggering, please consider
 *           this support to be a bonus.  It uses the EXTTRIG/ EXTCONVCLK
 *           input (PCI230+ pin 25).  Triggering will be on the rising edge
 *           unless the CR_INVERT flag is set in scan_begin_arg.
 *
 *   The channels in the channel sequence must be in ascending order with
 *   no repeats.  All entries in the channel sequence must use the same
 *   output range.
 *
 * DIO Subdevice:
 *
 *   The DIO subdevice is a 8255 chip providing 24 DIO channels.  The DIO
 *   channels are configurable as inputs or outputs in four groups:
 *
 *     Port A  - channels  0 to  7
 *     Port B  - channels  8 to 15
 *     Port CL - channels 16 to 19
 *     Port CH - channels 20 to 23
 *
 *   Only mode 0 of the 8255 chip is supported.
 *
 *   Bit 0 of port C (DIO channel 16) is also used as an external scan
 *   trigger input for AI commands on PCI230 and PCI230+, so would need to
 *   be configured as an input to use it for that purpose.
 */

176
/*
177 178 179 180 181
 * Extra triggered scan functionality, interrupt bug-fix added by Steve
 * Sharples.  Support for PCI230+/260+, more triggered scan functionality,
 * and workarounds for (or detection of) various hardware problems added
 * by Ian Abbott.
 */
182

183
#include <linux/module.h>
184
#include <linux/pci.h>
185
#include <linux/delay.h>
186
#include <linux/interrupt.h>
187

188 189
#include "../comedidev.h"

190
#include "comedi_fc.h"
191 192 193
#include "8253.h"
#include "8255.h"

194 195 196
/*
 * PCI230 PCI configuration register information
 */
197 198 199
#define PCI_DEVICE_ID_PCI230 0x0000
#define PCI_DEVICE_ID_PCI260 0x0006

200 201 202
/*
 * PCI230 i/o space 1 registers.
 */
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
#define PCI230_PPI_X_BASE	0x00	/* User PPI (82C55) base */
#define PCI230_PPI_X_A		0x00	/* User PPI (82C55) port A */
#define PCI230_PPI_X_B		0x01	/* User PPI (82C55) port B */
#define PCI230_PPI_X_C		0x02	/* User PPI (82C55) port C */
#define PCI230_PPI_X_CMD	0x03	/* User PPI (82C55) control word */
#define PCI230_Z2_CT_BASE	0x14	/* 82C54 counter/timer base */
#define PCI230_Z2_CT0		0x14	/* 82C54 counter/timer 0 */
#define PCI230_Z2_CT1		0x15	/* 82C54 counter/timer 1 */
#define PCI230_Z2_CT2		0x16	/* 82C54 counter/timer 2 */
#define PCI230_Z2_CTC		0x17	/* 82C54 counter/timer control word */
#define PCI230_ZCLK_SCE		0x1A	/* Group Z Clock Configuration */
#define PCI230_ZGAT_SCE		0x1D	/* Group Z Gate Configuration */
#define PCI230_INT_SCE		0x1E	/* Interrupt source mask (w) */
#define PCI230_INT_STAT		0x1E	/* Interrupt status (r) */

218 219 220
/*
 * PCI230 i/o space 2 registers.
 */
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
#define PCI230_DACCON		0x00	/* DAC control */
#define PCI230_DACOUT1		0x02	/* DAC channel 0 (w) */
#define PCI230_DACOUT2		0x04	/* DAC channel 1 (w) (not FIFO mode) */
#define PCI230_ADCDATA		0x08	/* ADC data (r) */
#define PCI230_ADCSWTRIG	0x08	/* ADC software trigger (w) */
#define PCI230_ADCCON		0x0A	/* ADC control */
#define PCI230_ADCEN		0x0C	/* ADC channel enable bits */
#define PCI230_ADCG		0x0E	/* ADC gain control bits */
/* PCI230+ i/o space 2 additional registers. */
#define PCI230P_ADCTRIG		0x10	/* ADC start acquisition trigger */
#define PCI230P_ADCTH		0x12	/* ADC analog trigger threshold */
#define PCI230P_ADCFFTH		0x14	/* ADC FIFO interrupt threshold */
#define PCI230P_ADCFFLEV	0x16	/* ADC FIFO level (r) */
#define PCI230P_ADCPTSC		0x18	/* ADC pre-trigger sample count (r) */
#define PCI230P_ADCHYST		0x1A	/* ADC analog trigger hysteresys */
#define PCI230P_EXTFUNC		0x1C	/* Extended functions */
#define PCI230P_HWVER		0x1E	/* Hardware version (r) */
/* PCI230+ hardware version 2 onwards. */
#define PCI230P2_DACDATA	0x02	/* DAC data (FIFO mode) (w) */
#define PCI230P2_DACSWTRIG	0x02	/* DAC soft trigger (FIFO mode) (r) */
#define PCI230P2_DACEN		0x06	/* DAC channel enable (FIFO mode) */

243 244 245
/*
 * DACCON read-write values.
 */
246 247 248
#define PCI230_DAC_OR_UNI		(0 << 0) /* Output range unipolar */
#define PCI230_DAC_OR_BIP		(1 << 0) /* Output range bipolar */
#define PCI230_DAC_OR_MASK		(1 << 0)
249 250 251 252
/*
 * The following applies only if DAC FIFO support is enabled in the EXTFUNC
 * register (and only for PCI230+ hardware version 2 onwards).
 */
253
#define PCI230P2_DAC_FIFO_EN		(1 << 8) /* FIFO enable */
254 255 256 257
/*
 * The following apply only if the DAC FIFO is enabled (and only for PCI230+
 * hardware version 2 onwards).
 */
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
#define PCI230P2_DAC_TRIG_NONE		(0 << 2) /* No trigger */
#define PCI230P2_DAC_TRIG_SW		(1 << 2) /* Software trigger trigger */
#define PCI230P2_DAC_TRIG_EXTP		(2 << 2) /* EXTTRIG +ve edge trigger */
#define PCI230P2_DAC_TRIG_EXTN		(3 << 2) /* EXTTRIG -ve edge trigger */
#define PCI230P2_DAC_TRIG_Z2CT0		(4 << 2) /* CT0-OUT +ve edge trigger */
#define PCI230P2_DAC_TRIG_Z2CT1		(5 << 2) /* CT1-OUT +ve edge trigger */
#define PCI230P2_DAC_TRIG_Z2CT2		(6 << 2) /* CT2-OUT +ve edge trigger */
#define PCI230P2_DAC_TRIG_MASK		(7 << 2)
#define PCI230P2_DAC_FIFO_WRAP		(1 << 7) /* FIFO wraparound mode */
#define PCI230P2_DAC_INT_FIFO_EMPTY	(0 << 9) /* FIFO interrupt empty */
#define PCI230P2_DAC_INT_FIFO_NEMPTY	(1 << 9)
#define PCI230P2_DAC_INT_FIFO_NHALF	(2 << 9) /* FIFO intr not half full */
#define PCI230P2_DAC_INT_FIFO_HALF	(3 << 9)
#define PCI230P2_DAC_INT_FIFO_NFULL	(4 << 9) /* FIFO interrupt not full */
#define PCI230P2_DAC_INT_FIFO_FULL	(5 << 9)
#define PCI230P2_DAC_INT_FIFO_MASK	(7 << 9)
274

275 276 277
/*
 * DACCON read-only values.
 */
278
#define PCI230_DAC_BUSY			(1 << 1) /* DAC busy. */
279 280 281 282
/*
 * The following apply only if the DAC FIFO is enabled (and only for PCI230+
 * hardware version 2 onwards).
 */
283 284 285 286
#define PCI230P2_DAC_FIFO_UNDERRUN_LATCHED	(1 << 5) /* Underrun error */
#define PCI230P2_DAC_FIFO_EMPTY		(1 << 13) /* FIFO empty */
#define PCI230P2_DAC_FIFO_FULL		(1 << 14) /* FIFO full */
#define PCI230P2_DAC_FIFO_HALF		(1 << 15) /* FIFO half full */
287

288 289 290 291 292 293 294
/*
 * DACCON write-only, transient values.
 */
/*
 * The following apply only if the DAC FIFO is enabled (and only for PCI230+
 * hardware version 2 onwards).
 */
295 296
#define PCI230P2_DAC_FIFO_UNDERRUN_CLEAR	(1 << 5) /* Clear underrun */
#define PCI230P2_DAC_FIFO_RESET		(1 << 12) /* FIFO reset */
297

298 299 300
/*
 * PCI230+ hardware version 2 DAC FIFO levels.
 */
301 302 303 304 305 306 307 308 309
#define PCI230P2_DAC_FIFOLEVEL_HALF	512
#define PCI230P2_DAC_FIFOLEVEL_FULL	1024
/* Free space in DAC FIFO. */
#define PCI230P2_DAC_FIFOROOM_EMPTY		PCI230P2_DAC_FIFOLEVEL_FULL
#define PCI230P2_DAC_FIFOROOM_ONETOHALF		\
	(PCI230P2_DAC_FIFOLEVEL_FULL - PCI230P2_DAC_FIFOLEVEL_HALF)
#define PCI230P2_DAC_FIFOROOM_HALFTOFULL	1
#define PCI230P2_DAC_FIFOROOM_FULL		0

310 311 312
/*
 * ADCCON read/write values.
 */
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
#define PCI230_ADC_TRIG_NONE		(0 << 0) /* No trigger */
#define PCI230_ADC_TRIG_SW		(1 << 0) /* Software trigger trigger */
#define PCI230_ADC_TRIG_EXTP		(2 << 0) /* EXTTRIG +ve edge trigger */
#define PCI230_ADC_TRIG_EXTN		(3 << 0) /* EXTTRIG -ve edge trigger */
#define PCI230_ADC_TRIG_Z2CT0		(4 << 0) /* CT0-OUT +ve edge trigger */
#define PCI230_ADC_TRIG_Z2CT1		(5 << 0) /* CT1-OUT +ve edge trigger */
#define PCI230_ADC_TRIG_Z2CT2		(6 << 0) /* CT2-OUT +ve edge trigger */
#define PCI230_ADC_TRIG_MASK		(7 << 0)
#define PCI230_ADC_IR_UNI		(0 << 3) /* Input range unipolar */
#define PCI230_ADC_IR_BIP		(1 << 3) /* Input range bipolar */
#define PCI230_ADC_IR_MASK		(1 << 3)
#define PCI230_ADC_IM_SE		(0 << 4) /* Input mode single ended */
#define PCI230_ADC_IM_DIF		(1 << 4) /* Input mode differential */
#define PCI230_ADC_IM_MASK		(1 << 4)
#define PCI230_ADC_FIFO_EN		(1 << 8) /* FIFO enable */
#define PCI230_ADC_INT_FIFO_EMPTY	(0 << 9)
#define PCI230_ADC_INT_FIFO_NEMPTY	(1 << 9) /* FIFO interrupt not empty */
#define PCI230_ADC_INT_FIFO_NHALF	(2 << 9)
#define PCI230_ADC_INT_FIFO_HALF	(3 << 9) /* FIFO interrupt half full */
#define PCI230_ADC_INT_FIFO_NFULL	(4 << 9)
#define PCI230_ADC_INT_FIFO_FULL	(5 << 9) /* FIFO interrupt full */
#define PCI230P_ADC_INT_FIFO_THRESH	(7 << 9) /* FIFO interrupt threshold */
#define PCI230_ADC_INT_FIFO_MASK	(7 << 9)
336

337 338 339
/*
 * ADCCON write-only, transient values.
 */
340 341
#define PCI230_ADC_FIFO_RESET		(1 << 12) /* FIFO reset */
#define PCI230_ADC_GLOB_RESET		(1 << 13) /* Global reset */
342

343 344 345
/*
 * ADCCON read-only values.
 */
346 347 348 349 350
#define PCI230_ADC_BUSY			(1 << 15) /* ADC busy */
#define PCI230_ADC_FIFO_EMPTY		(1 << 12) /* FIFO empty */
#define PCI230_ADC_FIFO_FULL		(1 << 13) /* FIFO full */
#define PCI230_ADC_FIFO_HALF		(1 << 14) /* FIFO half full */
#define PCI230_ADC_FIFO_FULL_LATCHED	(1 << 5)  /* FIFO overrun occurred */
351

352 353 354
/*
 * PCI230 ADC FIFO levels.
 */
355 356 357
#define PCI230_ADC_FIFOLEVEL_HALFFULL	2049	/* Value for FIFO half full */
#define PCI230_ADC_FIFOLEVEL_FULL	4096	/* FIFO size */

358 359 360 361
/*
 * PCI230+ EXTFUNC values.
 */
/* Route EXTTRIG pin to external gate inputs. */
362
#define PCI230P_EXTFUNC_GAT_EXTTRIG	(1 << 0)
363
/* PCI230+ hardware version 2 values. */
364
/* Allow DAC FIFO to be enabled. */
365
#define PCI230P2_EXTFUNC_DACFIFO	(1 << 1)
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

/*
 * Counter/timer clock input configuration sources.
 */
#define CLK_CLK		0	/* reserved (channel-specific clock) */
#define CLK_10MHZ	1	/* internal 10 MHz clock */
#define CLK_1MHZ	2	/* internal 1 MHz clock */
#define CLK_100KHZ	3	/* internal 100 kHz clock */
#define CLK_10KHZ	4	/* internal 10 kHz clock */
#define CLK_1KHZ	5	/* internal 1 kHz clock */
#define CLK_OUTNM1	6	/* output of channel-1 modulo total */
#define CLK_EXT		7	/* external clock */
/* Macro to construct clock input configuration register value. */
#define CLK_CONFIG(chan, src)	((((chan) & 3) << 3) | ((src) & 7))
/* Timebases in ns. */
#define TIMEBASE_10MHZ		100
#define TIMEBASE_1MHZ		1000
#define TIMEBASE_100KHZ		10000
#define TIMEBASE_10KHZ		100000
#define TIMEBASE_1KHZ		1000000

/*
 * Counter/timer gate input configuration sources.
 */
#define GAT_VCC		0	/* VCC (i.e. enabled) */
#define GAT_GND		1	/* GND (i.e. disabled) */
#define GAT_EXT		2	/* external gate input (PPCn on PCI230) */
#define GAT_NOUTNM2	3	/* inverted output of channel-2 modulo total */
/* Macro to construct gate input configuration register value. */
#define GAT_CONFIG(chan, src)	((((chan) & 3) << 3) | ((src) & 7))

/*
 * Summary of CLK_OUTNM1 and GAT_NOUTNM2 connections for PCI230 and PCI260:
 *
 *              Channel's       Channel's
 *              clock input     gate input
 * Channel      CLK_OUTNM1      GAT_NOUTNM2
 * -------      ----------      -----------
 * Z2-CT0       Z2-CT2-OUT      /Z2-CT1-OUT
 * Z2-CT1       Z2-CT0-OUT      /Z2-CT2-OUT
 * Z2-CT2       Z2-CT1-OUT      /Z2-CT0-OUT
 */

409 410 411
/*
 * Interrupt enables/status register values.
 */
412
#define PCI230_INT_DISABLE		0
413 414 415 416
#define PCI230_INT_PPI_C0		(1 << 0)
#define PCI230_INT_PPI_C3		(1 << 1)
#define PCI230_INT_ADC			(1 << 2)
#define PCI230_INT_ZCLK_CT1		(1 << 5)
417
/* For PCI230+ hardware version 2 when DAC FIFO enabled. */
418
#define PCI230P2_INT_DAC		(1 << 4)
419

420 421 422
/*
 * (Potentially) shared resources and their owners
 */
423
enum {
424 425 426
	RES_Z2CT0 = (1U << 0),	/* Z2-CT0 */
	RES_Z2CT1 = (1U << 1),	/* Z2-CT1 */
	RES_Z2CT2 = (1U << 2)	/* Z2-CT2 */
427 428 429 430
};

enum {
	OWNER_AICMD,		/* Owned by AI command */
431 432
	OWNER_AOCMD,		/* Owned by AO command */
	NUM_OWNERS		/* Number of owners */
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
};

/*
 * Handy macros.
 */

/* Combine old and new bits. */
#define COMBINE(old, new, mask)	(((old) & ~(mask)) | ((new) & (mask)))

/* Current CPU.  XXX should this be hard_smp_processor_id()? */
#define THISCPU		smp_processor_id()

/*
 * Board descriptions for the two boards supported.
 */

449
struct pci230_board {
450 451
	const char *name;
	unsigned short id;
452 453 454 455
	unsigned char ai_bits;
	unsigned char ao_bits;
	unsigned char min_hwver; /* Minimum hardware version supported. */
	bool have_dio:1;
456
};
457

458
static const struct pci230_board pci230_boards[] = {
459
	{
460 461 462 463
		.name		= "pci230+",
		.id		= PCI_DEVICE_ID_PCI230,
		.ai_bits	= 16,
		.ao_bits	= 12,
464
		.have_dio	= true,
465 466
		.min_hwver	= 1,
	},
467
	{
468 469 470 471 472
		.name		= "pci260+",
		.id		= PCI_DEVICE_ID_PCI260,
		.ai_bits	= 16,
		.min_hwver	= 1,
	},
473
	{
474 475 476 477
		.name		= "pci230",
		.id		= PCI_DEVICE_ID_PCI230,
		.ai_bits	= 12,
		.ao_bits	= 12,
478
		.have_dio	= true,
479
	},
480
	{
481 482 483 484
		.name		= "pci260",
		.id		= PCI_DEVICE_ID_PCI260,
		.ai_bits	= 12,
	},
485 486 487 488 489 490 491
};

struct pci230_private {
	spinlock_t isr_spinlock;	/* Interrupt spin lock */
	spinlock_t res_spinlock;	/* Shared resources spin lock */
	spinlock_t ai_stop_spinlock;	/* Spin lock for stopping AI command */
	spinlock_t ao_stop_spinlock;	/* Spin lock for stopping AO command */
492
	unsigned long daqio;		/* PCI230's DAQ I/O space */
493 494 495 496 497 498 499 500 501
	unsigned int ai_scan_count;	/* Number of AI scans remaining */
	unsigned int ai_scan_pos;	/* Current position within AI scan */
	unsigned int ao_scan_count;	/* Number of AO scans remaining.  */
	int intr_cpuid;			/* ID of CPU running ISR */
	unsigned short hwver;		/* Hardware version (for '+' models) */
	unsigned short adccon;		/* ADCCON register value */
	unsigned short daccon;		/* DACCON register value */
	unsigned short adcfifothresh;	/* ADC FIFO threshold (PCI230+/260+) */
	unsigned short adcg;		/* ADCG register value */
502
	unsigned char ier;		/* Interrupt enable bits */
503
	unsigned char res_owned[NUM_OWNERS]; /* Owned resources */
504
	bool intr_running:1;		/* Flag set in interrupt routine */
505 506
	bool ai_bipolar:1;		/* Flag AI range is bipolar */
	bool ao_bipolar:1;		/* Flag AO range is bipolar */
507 508
	bool ai_cmd_started:1;		/* Flag AI command started */
	bool ao_cmd_started:1;		/* Flag AO command started */
509 510 511 512 513 514 515 516 517 518 519 520
};

/* PCI230 clock source periods in ns */
static const unsigned int pci230_timebase[8] = {
	[CLK_10MHZ] = TIMEBASE_10MHZ,
	[CLK_1MHZ] = TIMEBASE_1MHZ,
	[CLK_100KHZ] = TIMEBASE_100KHZ,
	[CLK_10KHZ] = TIMEBASE_10KHZ,
	[CLK_1KHZ] = TIMEBASE_1KHZ,
};

/* PCI230 analogue input range table */
521 522 523 524 525 526 527 528 529 530
static const struct comedi_lrange pci230_ai_range = {
	7, {
		BIP_RANGE(10),
		BIP_RANGE(5),
		BIP_RANGE(2.5),
		BIP_RANGE(1.25),
		UNI_RANGE(10),
		UNI_RANGE(5),
		UNI_RANGE(2.5)
	}
531 532 533 534 535 536
};

/* PCI230 analogue gain bits for each input range. */
static const unsigned char pci230_ai_gain[7] = { 0, 1, 2, 3, 1, 2, 3 };

/* PCI230 analogue output range table */
537 538 539 540 541
static const struct comedi_lrange pci230_ao_range = {
	2, {
		UNI_RANGE(10),
		BIP_RANGE(10)
	}
542 543
};

544
static unsigned short pci230_ai_read(struct comedi_device *dev)
545
{
546
	const struct pci230_board *thisboard = dev->board_ptr;
547
	struct pci230_private *devpriv = dev->private;
548
	unsigned short data;
549

550
	/* Read sample. */
551
	data = inw(devpriv->daqio + PCI230_ADCDATA);
552 553 554
	/*
	 * PCI230 is 12 bit - stored in upper bits of 16 bit register
	 * (lower four bits reserved for expansion).  PCI230+ is 16 bit AI.
555
	 *
556 557 558
	 * If a bipolar range was specified, mangle it
	 * (twos complement->straight binary).
	 */
559
	if (devpriv->ai_bipolar)
560 561
		data ^= 0x8000;
	data >>= (16 - thisboard->ai_bits);
562 563 564
	return data;
}

565 566
static unsigned short pci230_ao_mangle_datum(struct comedi_device *dev,
					     unsigned short datum)
567
{
568
	const struct pci230_board *thisboard = dev->board_ptr;
569 570
	struct pci230_private *devpriv = dev->private;

571 572 573 574
	/*
	 * PCI230 is 12 bit - stored in upper bits of 16 bit register (lower
	 * four bits reserved for expansion).  PCI230+ is also 12 bit AO.
	 */
575
	datum <<= (16 - thisboard->ao_bits);
576 577 578 579 580 581
	/*
	 * If a bipolar range was specified, mangle it
	 * (straight binary->twos complement).
	 */
	if (devpriv->ao_bipolar)
		datum ^= 0x8000;
582
	return datum;
583 584
}

585 586
static void pci230_ao_write_nofifo(struct comedi_device *dev,
				   unsigned short datum, unsigned int chan)
587
{
588 589
	struct pci230_private *devpriv = dev->private;

590
	/* Write mangled datum to appropriate DACOUT register. */
591
	outw(pci230_ao_mangle_datum(dev, datum),
592
	     devpriv->daqio + ((chan == 0) ? PCI230_DACOUT1 : PCI230_DACOUT2));
593 594
}

595 596
static void pci230_ao_write_fifo(struct comedi_device *dev,
				 unsigned short datum, unsigned int chan)
597
{
598 599
	struct pci230_private *devpriv = dev->private;

600 601
	/* Write mangled datum to appropriate DACDATA register. */
	outw(pci230_ao_mangle_datum(dev, datum),
602
	     devpriv->daqio + PCI230P2_DACDATA);
603 604
}

605 606
static bool pci230_claim_shared(struct comedi_device *dev,
				unsigned char res_mask, unsigned int owner)
607
{
608
	struct pci230_private *devpriv = dev->private;
609
	unsigned int o;
610 611
	unsigned long irqflags;

612
	spin_lock_irqsave(&devpriv->res_spinlock, irqflags);
613 614 615 616 617 618 619
	for (o = 0; o < NUM_OWNERS; o++) {
		if (o == owner)
			continue;
		if (devpriv->res_owned[o] & res_mask) {
			spin_unlock_irqrestore(&devpriv->res_spinlock,
					       irqflags);
			return false;
620 621
		}
	}
622
	devpriv->res_owned[owner] |= res_mask;
623
	spin_unlock_irqrestore(&devpriv->res_spinlock, irqflags);
624
	return true;
625 626
}

627 628
static void pci230_release_shared(struct comedi_device *dev,
				  unsigned char res_mask, unsigned int owner)
629
{
630
	struct pci230_private *devpriv = dev->private;
631 632
	unsigned long irqflags;

633
	spin_lock_irqsave(&devpriv->res_spinlock, irqflags);
634
	devpriv->res_owned[owner] &= ~res_mask;
635
	spin_unlock_irqrestore(&devpriv->res_spinlock, irqflags);
636 637
}

638 639
static void pci230_release_all_resources(struct comedi_device *dev,
					 unsigned int owner)
640
{
641
	pci230_release_shared(dev, (unsigned char)~0, owner);
642 643
}

644 645
static unsigned int pci230_divide_ns(uint64_t ns, unsigned int timebase,
				     unsigned int flags)
646 647 648 649 650 651
{
	uint64_t div;
	unsigned int rem;

	div = ns;
	rem = do_div(div, timebase);
652
	switch (flags & CMDF_ROUND_MASK) {
653
	default:
654
	case CMDF_ROUND_NEAREST:
655 656
		div += (rem + (timebase / 2)) / timebase;
		break;
657
	case CMDF_ROUND_DOWN:
658
		break;
659
	case CMDF_ROUND_UP:
660 661 662 663 664 665
		div += (rem + timebase - 1) / timebase;
		break;
	}
	return div > UINT_MAX ? UINT_MAX : (unsigned int)div;
}

666 667 668 669
/*
 * Given desired period in ns, returns the required internal clock source
 * and gets the initial count.
 */
670
static unsigned int pci230_choose_clk_count(uint64_t ns, unsigned int *count,
671
					    unsigned int flags)
672 673 674 675
{
	unsigned int clk_src, cnt;

	for (clk_src = CLK_10MHZ;; clk_src++) {
676
		cnt = pci230_divide_ns(ns, pci230_timebase[clk_src], flags);
677
		if (cnt <= 65536 || clk_src == CLK_1KHZ)
678 679 680 681 682 683
			break;
	}
	*count = cnt;
	return clk_src;
}

684
static void pci230_ns_to_single_timer(unsigned int *ns, unsigned int flags)
685 686 687 688
{
	unsigned int count;
	unsigned int clk_src;

689
	clk_src = pci230_choose_clk_count(*ns, &count, flags);
690 691 692 693 694
	*ns = count * pci230_timebase[clk_src];
}

static void pci230_ct_setup_ns_mode(struct comedi_device *dev, unsigned int ct,
				    unsigned int mode, uint64_t ns,
695
				    unsigned int flags)
696 697 698 699 700
{
	unsigned int clk_src;
	unsigned int count;

	/* Set mode. */
701
	i8254_set_mode(dev->iobase + PCI230_Z2_CT_BASE, 0, ct, mode);
702
	/* Determine clock source and count. */
703
	clk_src = pci230_choose_clk_count(ns, &count, flags);
704
	/* Program clock source. */
705
	outb(CLK_CONFIG(ct, clk_src), dev->iobase + PCI230_ZCLK_SCE);
706 707 708 709
	/* Set initial count. */
	if (count >= 65536)
		count = 0;

710
	i8254_write(dev->iobase + PCI230_Z2_CT_BASE, 0, ct, count);
711 712 713 714
}

static void pci230_cancel_ct(struct comedi_device *dev, unsigned int ct)
{
715
	i8254_set_mode(dev->iobase + PCI230_Z2_CT_BASE, 0, ct, I8254_MODE1);
716 717 718
	/* Counter ct, 8254 mode 1, initial count not written. */
}

719 720 721 722 723
static int pci230_ai_eoc(struct comedi_device *dev,
			 struct comedi_subdevice *s,
			 struct comedi_insn *insn,
			 unsigned long context)
{
724
	struct pci230_private *devpriv = dev->private;
725 726
	unsigned int status;

727
	status = inw(devpriv->daqio + PCI230_ADCCON);
728 729 730 731 732
	if ((status & PCI230_ADC_FIFO_EMPTY) == 0)
		return 0;
	return -EBUSY;
}

733 734 735
static int pci230_ai_insn_read(struct comedi_device *dev,
			       struct comedi_subdevice *s,
			       struct comedi_insn *insn, unsigned int *data)
736
{
737
	struct pci230_private *devpriv = dev->private;
738
	unsigned int n;
739 740 741
	unsigned int chan, range, aref;
	unsigned int gainshift;
	unsigned short adccon, adcen;
742
	int ret;
743 744 745 746 747 748 749 750

	/* Unpack channel and range. */
	chan = CR_CHAN(insn->chanspec);
	range = CR_RANGE(insn->chanspec);
	aref = CR_AREF(insn->chanspec);
	if (aref == AREF_DIFF) {
		/* Differential. */
		if (chan >= s->n_chan / 2) {
751 752 753
			dev_dbg(dev->class_dev,
				"%s: differential channel number out of range 0 to %u\n",
				__func__, (s->n_chan / 2) - 1);
754 755 756 757
			return -EINVAL;
		}
	}

758 759
	/*
	 * Use Z2-CT2 as a conversion trigger instead of the built-in
760 761 762 763 764 765
	 * software trigger, as otherwise triggering of differential channels
	 * doesn't work properly for some versions of PCI230/260.  Also set
	 * FIFO mode because the ADC busy bit only works for software triggers.
	 */
	adccon = PCI230_ADC_TRIG_Z2CT2 | PCI230_ADC_FIFO_EN;
	/* Set Z2-CT2 output low to avoid any false triggers. */
766
	i8254_set_mode(dev->iobase + PCI230_Z2_CT_BASE, 0, 2, I8254_MODE0);
767
	devpriv->ai_bipolar = comedi_range_is_bipolar(s, range);
768 769 770 771
	if (aref == AREF_DIFF) {
		/* Differential. */
		gainshift = chan * 2;
		if (devpriv->hwver == 0) {
772 773 774 775
			/*
			 * Original PCI230/260 expects both inputs of the
			 * differential channel to be enabled.
			 */
776 777
			adcen = 3 << gainshift;
		} else {
778 779 780 781
			/*
			 * PCI230+/260+ expects only one input of the
			 * differential channel to be enabled.
			 */
782 783 784 785 786 787 788 789 790
			adcen = 1 << gainshift;
		}
		adccon |= PCI230_ADC_IM_DIF;
	} else {
		/* Single ended. */
		adcen = 1 << chan;
		gainshift = chan & ~1;
		adccon |= PCI230_ADC_IM_SE;
	}
791 792
	devpriv->adcg = (devpriv->adcg & ~(3 << gainshift)) |
			(pci230_ai_gain[range] << gainshift);
793
	if (devpriv->ai_bipolar)
794
		adccon |= PCI230_ADC_IR_BIP;
795
	else
796
		adccon |= PCI230_ADC_IR_UNI;
797

798 799 800 801
	/*
	 * Enable only this channel in the scan list - otherwise by default
	 * we'll get one sample from each channel.
	 */
802
	outw(adcen, devpriv->daqio + PCI230_ADCEN);
803 804

	/* Set gain for channel. */
805
	outw(devpriv->adcg, devpriv->daqio + PCI230_ADCG);
806 807 808

	/* Specify uni/bip, se/diff, conversion source, and reset FIFO. */
	devpriv->adccon = adccon;
809
	outw(adccon | PCI230_ADC_FIFO_RESET, devpriv->daqio + PCI230_ADCCON);
810 811 812

	/* Convert n samples */
	for (n = 0; n < insn->n; n++) {
813 814 815 816
		/*
		 * Trigger conversion by toggling Z2-CT2 output
		 * (finish with output high).
		 */
817 818 819 820
		i8254_set_mode(dev->iobase + PCI230_Z2_CT_BASE, 0,
			       2, I8254_MODE0);
		i8254_set_mode(dev->iobase + PCI230_Z2_CT_BASE, 0,
			       2, I8254_MODE1);
821 822

		/* wait for conversion to end */
823
		ret = comedi_timeout(dev, s, insn, pci230_ai_eoc, 0);
824
		if (ret)
825
			return ret;
826 827 828 829 830 831 832 833 834

		/* read data */
		data[n] = pci230_ai_read(dev);
	}

	/* return the number of samples read/written */
	return n;
}

835 836 837 838
static int pci230_ao_insn_write(struct comedi_device *dev,
				struct comedi_subdevice *s,
				struct comedi_insn *insn,
				unsigned int *data)
839
{
840
	struct pci230_private *devpriv = dev->private;
841 842 843
	unsigned int chan = CR_CHAN(insn->chanspec);
	unsigned int range = CR_RANGE(insn->chanspec);
	unsigned int val = s->readback[chan];
844 845
	int i;

846 847 848 849
	/*
	 * Set range - see analogue output range table; 0 => unipolar 10V,
	 * 1 => bipolar +/-10V range scale
	 */
850
	devpriv->ao_bipolar = comedi_range_is_bipolar(s, range);
851
	outw(range, devpriv->daqio + PCI230_DACCON);
852 853

	for (i = 0; i < insn->n; i++) {
854 855
		val = data[i];
		pci230_ao_write_nofifo(dev, val, chan);
856
	}
857
	s->readback[chan] = val;
858

859
	return insn->n;
860 861
}

862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
static int pci230_ao_check_chanlist(struct comedi_device *dev,
				    struct comedi_subdevice *s,
				    struct comedi_cmd *cmd)
{
	unsigned int prev_chan = CR_CHAN(cmd->chanlist[0]);
	unsigned int range0 = CR_RANGE(cmd->chanlist[0]);
	int i;

	for (i = 1; i < cmd->chanlist_len; i++) {
		unsigned int chan = CR_CHAN(cmd->chanlist[i]);
		unsigned int range = CR_RANGE(cmd->chanlist[i]);

		if (chan < prev_chan) {
			dev_dbg(dev->class_dev,
				"%s: channel numbers must increase\n",
				__func__);
			return -EINVAL;
		}

		if (range != range0) {
			dev_dbg(dev->class_dev,
				"%s: channels must have the same range\n",
				__func__);
			return -EINVAL;
		}

		prev_chan = chan;
	}

	return 0;
}

894 895
static int pci230_ao_cmdtest(struct comedi_device *dev,
			     struct comedi_subdevice *s, struct comedi_cmd *cmd)
896
{
897
	const struct pci230_board *thisboard = dev->board_ptr;
898
	struct pci230_private *devpriv = dev->private;
899 900 901
	int err = 0;
	unsigned int tmp;

902
	/* Step 1 : check if triggers are trivially valid */
903

904
	err |= cfc_check_trigger_src(&cmd->start_src, TRIG_INT);
905

906
	tmp = TRIG_TIMER | TRIG_INT;
907
	if (thisboard->min_hwver > 0 && devpriv->hwver >= 2) {
908 909 910 911 912 913 914 915 916 917 918 919 920 921
		/*
		 * For PCI230+ hardware version 2 onwards, allow external
		 * trigger from EXTTRIG/EXTCONVCLK input (PCI230+ pin 25).
		 *
		 * FIXME: The permitted scan_begin_src values shouldn't depend
		 * on devpriv->hwver (the detected card's actual hardware
		 * version).  They should only depend on thisboard->min_hwver
		 * (the static capabilities of the configured card).  To fix
		 * it, a new card model, e.g. "pci230+2" would have to be
		 * defined with min_hwver set to 2.  It doesn't seem worth it
		 * for this alone.  At the moment, please consider
		 * scan_begin_src==TRIG_EXT support to be a bonus rather than a
		 * guarantee!
		 */
922
		tmp |= TRIG_EXT;
923
	}
924
	err |= cfc_check_trigger_src(&cmd->scan_begin_src, tmp);
925

926 927 928
	err |= cfc_check_trigger_src(&cmd->convert_src, TRIG_NOW);
	err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
	err |= cfc_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
929 930 931 932

	if (err)
		return 1;

933
	/* Step 2a : make sure trigger sources are unique */
934

935 936 937 938
	err |= cfc_check_trigger_is_unique(cmd->scan_begin_src);
	err |= cfc_check_trigger_is_unique(cmd->stop_src);

	/* Step 2b : and mutually compatible */
939 940 941 942

	if (err)
		return 2;

943 944 945
	/* Step 3: check if arguments are trivially valid */

	err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);
946 947

#define MAX_SPEED_AO	8000	/* 8000 ns => 125 kHz */
948 949 950 951
/*
 * Comedi limit due to unsigned int cmd.  Driver limit =
 * 2^16 (16bit * counter) * 1000000ns (1kHz onboard clock) = 65.536s
 */
952 953 954 955
#define MIN_SPEED_AO	4294967295u	/* 4294967295ns = 4.29s */

	switch (cmd->scan_begin_src) {
	case TRIG_TIMER:
956 957 958 959
		err |= cfc_check_trigger_arg_min(&cmd->scan_begin_arg,
						 MAX_SPEED_AO);
		err |= cfc_check_trigger_arg_max(&cmd->scan_begin_arg,
						 MIN_SPEED_AO);
960 961
		break;
	case TRIG_EXT:
962 963 964
		/*
		 * External trigger - for PCI230+ hardware version 2 onwards.
		 */
965
		/* Trigger number must be 0. */
966
		if (cmd->scan_begin_arg & ~CR_FLAGS_MASK) {
967
			cmd->scan_begin_arg = COMBINE(cmd->scan_begin_arg, 0,
968
						      ~CR_FLAGS_MASK);
969
			err |= -EINVAL;
970
		}
971 972 973 974
		/*
		 * The only flags allowed are CR_EDGE and CR_INVERT.
		 * The CR_EDGE flag is ignored.
		 */
975 976 977 978 979
		if (cmd->scan_begin_arg & CR_FLAGS_MASK &
		    ~(CR_EDGE | CR_INVERT)) {
			cmd->scan_begin_arg =
			    COMBINE(cmd->scan_begin_arg, 0,
				    CR_FLAGS_MASK & ~(CR_EDGE | CR_INVERT));
980
			err |= -EINVAL;
981 982 983
		}
		break;
	default:
984
		err |= cfc_check_trigger_arg_is(&cmd->scan_begin_arg, 0);
985 986 987
		break;
	}

988 989
	err |= cfc_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len);

990 991 992
	if (cmd->stop_src == TRIG_COUNT)
		err |= cfc_check_trigger_arg_min(&cmd->stop_arg, 1);
	else	/* TRIG_NONE */
993
		err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
994 995 996 997

	if (err)
		return 3;

998
	/* Step 4: fix up any arguments */
999 1000 1001

	if (cmd->scan_begin_src == TRIG_TIMER) {
		tmp = cmd->scan_begin_arg;
1002
		pci230_ns_to_single_timer(&cmd->scan_begin_arg, cmd->flags);
1003 1004 1005 1006 1007 1008 1009
		if (tmp != cmd->scan_begin_arg)
			err++;
	}

	if (err)
		return 4;

1010 1011 1012
	/* Step 5: check channel list if it exists */
	if (cmd->chanlist && cmd->chanlist_len > 0)
		err |= pci230_ao_check_chanlist(dev, s, cmd);
1013 1014 1015 1016 1017 1018 1019

	if (err)
		return 5;

	return 0;
}

1020 1021 1022 1023 1024 1025
static void pci230_ao_stop(struct comedi_device *dev,
			   struct comedi_subdevice *s)
{
	struct pci230_private *devpriv = dev->private;
	unsigned long irqflags;
	unsigned char intsrc;
1026
	bool started;
1027 1028 1029
	struct comedi_cmd *cmd;

	spin_lock_irqsave(&devpriv->ao_stop_spinlock, irqflags);
1030 1031
	started = devpriv->ao_cmd_started;
	devpriv->ao_cmd_started = false;
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
	spin_unlock_irqrestore(&devpriv->ao_stop_spinlock, irqflags);
	if (!started)
		return;
	cmd = &s->async->cmd;
	if (cmd->scan_begin_src == TRIG_TIMER) {
		/* Stop scan rate generator. */
		pci230_cancel_ct(dev, 1);
	}
	/* Determine interrupt source. */
	if (devpriv->hwver < 2) {
		/* Not using DAC FIFO.  Using CT1 interrupt. */
		intsrc = PCI230_INT_ZCLK_CT1;
	} else {
		/* Using DAC FIFO interrupt. */
		intsrc = PCI230P2_INT_DAC;
	}
1048 1049 1050 1051
	/*
	 * Disable interrupt and wait for interrupt routine to finish running
	 * unless we are called from the interrupt routine.
	 */
1052
	spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
1053
	devpriv->ier &= ~intsrc;
1054 1055 1056 1057
	while (devpriv->intr_running && devpriv->intr_cpuid != THISCPU) {
		spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
		spin_lock_irqsave(&devpriv->isr_spinlock, irqflags);
	}
1058
	outb(devpriv->ier, dev->iobase + PCI230_INT_SCE);
1059 1060
	spin_unlock_irqrestore(&devpriv->isr_spinlock, irqflags);
	if (devpriv->hwver >= 2) {
1061 1062 1063 1064
		/*
		 * Using DAC FIFO.  Reset FIFO, clear underrun error,
		 * disable FIFO.
		 */
1065
		devpriv->daccon &= PCI230_DAC_OR_MASK;
1066 1067
		outw(devpriv->daccon | PCI230P2_DAC_FIFO_RESET |
		     PCI230P2_DAC_FIFO_UNDERRUN_CLEAR,
1068
		     devpriv->daqio + PCI230_DACCON);
1069 1070
	}
	/* Release resources. */
1071
	pci230_release_all_resources(dev, OWNER_AOCMD);
1072 1073 1074 1075 1076 1077
}

static void pci230_handle_ao_nofifo(struct comedi_device *dev,
				    struct comedi_subdevice *s)
{
	struct pci230_private *devpriv = dev->private;
1078
	unsigned short data;
1079 1080 1081 1082
	int i, ret;
	struct comedi_async *async = s->async;
	struct comedi_cmd *cmd = &async->cmd;

1083
	if (cmd->stop_src == TRIG_COUNT && devpriv->ao_scan_count == 0)
1084 1085
		return;
	for (i = 0; i < cmd->chanlist_len; i++) {
1086 1087
		unsigned int chan = CR_CHAN(cmd->chanlist[i]);

1088
		/* Read sample from Comedi's circular buffer. */
1089
		ret = comedi_buf_get(s, &data);
1090 1091 1092 1093
		if (ret == 0) {
			s->async->events |= COMEDI_CB_OVERFLOW;
			return;
		}
1094 1095
		pci230_ao_write_nofifo(dev, data, chan);
		s->readback[chan] = data;
1096 1097
	}
	async->events |= COMEDI_CB_BLOCK | COMEDI_CB_EOS;
1098
	if (cmd->stop_src == TRIG_COUNT) {
1099 1100 1101 1102 1103 1104 1105 1106
		devpriv->ao_scan_count--;
		if (devpriv->ao_scan_count == 0) {
			/* End of acquisition. */
			async->events |= COMEDI_CB_EOA;
		}
	}
}

1107 1108 1109 1110 1111 1112
/*
 * Loads DAC FIFO (if using it) from buffer.
 * Returns false if AO finished due to completion or error, true if still going.
 */
static bool pci230_handle_ao_fifo(struct comedi_device *dev,
				  struct comedi_subdevice *s)
1113 1114 1115 1116 1117 1118 1119 1120 1121
{
	struct pci230_private *devpriv = dev->private;
	struct comedi_async *async = s->async;
	struct comedi_cmd *cmd = &async->cmd;
	unsigned int num_scans;
	unsigned int room;
	unsigned short dacstat;
	unsigned int i, n;
	unsigned int events = 0;
1122
	bool running;
1123 1124

	/* Get DAC FIFO status. */
1125
	dacstat = inw(devpriv->daqio + PCI230_DACCON);
1126
	/* Determine number of scans available in buffer. */
1127
	num_scans = comedi_buf_read_n_available(s) / cfc_bytes_per_scan(s);
1128
	if (cmd->stop_src == TRIG_COUNT) {
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
		/* Fixed number of scans. */
		if (num_scans > devpriv->ao_scan_count)
			num_scans = devpriv->ao_scan_count;
		if (devpriv->ao_scan_count == 0) {
			/* End of acquisition. */
			events |= COMEDI_CB_EOA;
		}
	}
	if (events == 0) {
		/* Check for FIFO underrun. */
1139
		if (dacstat & PCI230P2_DAC_FIFO_UNDERRUN_LATCHED) {
1140
			dev_err(dev->class_dev, "AO FIFO underrun\n");
1141 1142
			events |= COMEDI_CB_OVERFLOW | COMEDI_CB_ERROR;
		}
1143 1144
		/*
		 * Check for buffer underrun if FIFO less than half full
1145
		 * (otherwise there will be loads of "DAC FIFO not half full"
1146 1147
		 * interrupts).
		 */
1148 1149
		if (num_scans == 0 &&
		    (dacstat & PCI230P2_DAC_FIFO_HALF) == 0) {
1150
			dev_err(dev->class_dev, "AO buffer underrun\n");
1151 1152 1153 1154 1155
			events |= COMEDI_CB_OVERFLOW | COMEDI_CB_ERROR;
		}
	}
	if (events == 0) {
		/* Determine how much room is in the FIFO (in samples). */
1156
		if (dacstat & PCI230P2_DAC_FIFO_FULL)
1157
			room = PCI230P2_DAC_FIFOROOM_FULL;
1158
		else if (dacstat & PCI230P2_DAC_FIFO_HALF)
1159
			room = PCI230P2_DAC_FIFOROOM_HALFTOFULL;
1160
		else if (dacstat & PCI230P2_DAC_FIFO_EMPTY)
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
			room = PCI230P2_DAC_FIFOROOM_EMPTY;
		else
			room = PCI230P2_DAC_FIFOROOM_ONETOHALF;
		/* Convert room to number of scans that can be added. */
		room /= cmd->chanlist_len;
		/* Determine number of scans to process. */
		if (num_scans > room)
			num_scans = room;
		/* Process scans. */
		for (n = 0; n < num_scans; n++) {
			for (i = 0; i < cmd->chanlist_len; i++) {
1172
				unsigned int chan = CR_CHAN(cmd->chanlist[i]);
1173
				unsigned short datum;
1174

1175
				comedi_buf_get(s, &datum);
1176 1177
				pci230_ao_write_fifo(dev, datum, chan);
				s->readback[chan] = datum;
1178 1179 1180
			}
		}
		events |= COMEDI_CB_EOS | COMEDI_CB_BLOCK;
1181
		if (cmd->stop_src == TRIG_COUNT) {
1182 1183
			devpriv->ao_scan_count -= num_scans;
			if (devpriv->ao_scan_count == 0) {
1184 1185
				/*
				 * All data for the command has been written
1186
				 * to FIFO.  Set FIFO interrupt trigger level
1187 1188
				 * to 'empty'.
				 */
1189 1190 1191 1192
				devpriv->daccon =
				    (devpriv->daccon &
				     ~PCI230P2_DAC_INT_FIFO_MASK) |
				    PCI230P2_DAC_INT_FIFO_EMPTY;
1193
				outw(devpriv->daccon,
1194
				     devpriv->daqio + PCI230_DACCON);
1195 1196 1197
			}
		}
		/* Check if FIFO underrun occurred while writing to FIFO. */
1198
		dacstat = inw(devpriv->daqio + PCI230_DACCON);
1199
		if (dacstat & PCI230P2_DAC_FIFO_UNDERRUN_LATCHED) {
1200
			dev_err(dev->class_dev, "AO FIFO underrun\n");
1201 1202 1203
			events |= COMEDI_CB_OVERFLOW | COMEDI_CB_ERROR;
		}
	}
1204
	if (events & (COMEDI_CB_EOA | COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW))
1205
		running = false;
1206
	else
1207
		running = true;
1208 1209 1210 1211
	async->events |= events;
	return running;
}

1212
static int pci230_ao_inttrig_scan_begin(struct comedi_device *dev,
1213 1214
					struct comedi_subdevice *s,
					unsigned int trig_num)
1215
{
1216
	struct pci230_private *devpriv = dev->private;
1217 1218
	unsigned long irqflags;

1219
	if (trig_num)
1220 1221
		return -EINVAL;

1222
	spin_lock_irqsave(&devpriv->ao_stop_spinlock, irqflags);
1223 1224 1225 1226 1227 1228 1229 1230 1231
	if (!devpriv->ao_cmd_started) {
		spin_unlock_irqrestore(&devpriv->ao_stop_spinlock, irqflags);
		return 1;
	}
	/* Perform scan. */
	if (devpriv->hwver < 2) {
		/* Not using DAC FIFO. */
		spin_unlock_irqrestore(&devpriv->ao_stop_spinlock, irqflags);
		pci230_handle_ao_nofifo(dev, s);
1232
		comedi_handle_events(dev, s);
1233
	} else {
1234 1235 1236
		/* Using DAC FIFO. */
		/* Read DACSWTRIG register to trigger conversion. */
		inw(devpriv->daqio + PCI230P2_DACSWTRIG);
1237
		spin_unlock_irqrestore(&devpriv->ao_stop_spinlock, irqflags);
1238
	}
1239 1240 1241
	/* Delay.  Should driver be responsible for this? */
	/* XXX TODO: See if DAC busy bit can be used. */
	udelay(8);
1242 1243 1244
	return 1;
}

1245 1246
static void pci230_ao_start(struct comedi_device *dev,
			    struct comedi_subdevice *s)
1247
{
1248
	struct pci230_private *devpriv = dev->private;
1249
	struct comedi_async *async = s->async;
1250
	struct comedi_cmd *cmd = &async->cmd;
1251 1252
	unsigned long irqflags;

1253
	devpriv->ao_cmd_started = true;
1254

1255 1256 1257
	if (devpriv->hwver >= 2) {
		/* Using DAC FIFO. */
		unsigned short scantrig;
1258
		bool run;
1259 1260 1261

		/* Preload FIFO data. */
		run = pci230_handle_ao_fifo(dev, s);
1262
		comedi_handle_events(dev, s);
1263 1264 1265
		if (!run) {
			/* Stopped. */
			return;
1266
		}
1267
		/* Set scan trigger source. */
1268 1269
		switch (cmd->scan_begin_src) {
		case TRIG_TIMER:
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
			scantrig = PCI230P2_DAC_TRIG_Z2CT1;
			break;
		case TRIG_EXT:
			/* Trigger on EXTTRIG/EXTCONVCLK pin. */
			if ((cmd->scan_begin_arg & CR_INVERT) == 0) {
				/* +ve edge */
				scantrig = PCI230P2_DAC_TRIG_EXTP;
			} else {