Linux Audio

Check our new training course

Embedded Linux Audio

Check our new training course
with Creative Commons CC-BY-SA
lecture materials

Bootlin logo

Elixir Cross Referencer

Loading...
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  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
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 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
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 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
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
/*
 * Hardware driver for DAQ-STC based boards
 *
 * COMEDI - Linux Control and Measurement Device Interface
 * Copyright (C) 1997-2001 David A. Schleef <ds@schleef.org>
 * Copyright (C) 2002-2006 Frank Mori Hess <fmhess@users.sourceforge.net>
 *
 * 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.
 */

/*
 * This file is meant to be included by another file, e.g.,
 * ni_atmio.c or ni_pcimio.c.
 *
 * Interrupt support originally added by Truxton Fulton <trux@truxton.com>
 *
 * References (ftp://ftp.natinst.com/support/manuals):
 *   340747b.pdf  AT-MIO E series Register Level Programmer Manual
 *   341079b.pdf  PCI E Series RLPM
 *   340934b.pdf  DAQ-STC reference manual
 *
 * 67xx and 611x registers (ftp://ftp.ni.com/support/daq/mhddk/documentation/)
 *   release_ni611x.pdf
 *   release_ni67xx.pdf
 *
 * Other possibly relevant info:
 *   320517c.pdf  User manual (obsolete)
 *   320517f.pdf  User manual (new)
 *   320889a.pdf  delete
 *   320906c.pdf  maximum signal ratings
 *   321066a.pdf  about 16x
 *   321791a.pdf  discontinuation of at-mio-16e-10 rev. c
 *   321808a.pdf  about at-mio-16e-10 rev P
 *   321837a.pdf  discontinuation of at-mio-16de-10 rev d
 *   321838a.pdf  about at-mio-16de-10 rev N
 *
 * ISSUES:
 *   - the interrupt routine needs to be cleaned up
 *
 * 2006-02-07: S-Series PCI-6143: Support has been added but is not
 * fully tested as yet. Terry Barnaby, BEAM Ltd.
 */

#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include "8255.h"
#include "mite.h"

/* A timeout count */
#define NI_TIMEOUT 1000

/* Note: this table must match the ai_gain_* definitions */
static const short ni_gainlkup[][16] = {
	[ai_gain_16] = {0, 1, 2, 3, 4, 5, 6, 7,
			0x100, 0x101, 0x102, 0x103, 0x104, 0x105, 0x106, 0x107},
	[ai_gain_8] = {1, 2, 4, 7, 0x101, 0x102, 0x104, 0x107},
	[ai_gain_14] = {1, 2, 3, 4, 5, 6, 7,
			0x101, 0x102, 0x103, 0x104, 0x105, 0x106, 0x107},
	[ai_gain_4] = {0, 1, 4, 7},
	[ai_gain_611x] = {0x00a, 0x00b, 0x001, 0x002,
			  0x003, 0x004, 0x005, 0x006},
	[ai_gain_622x] = {0, 1, 4, 5},
	[ai_gain_628x] = {1, 2, 3, 4, 5, 6, 7},
	[ai_gain_6143] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
};

static const struct comedi_lrange range_ni_E_ai = {
	16, {
		BIP_RANGE(10),
		BIP_RANGE(5),
		BIP_RANGE(2.5),
		BIP_RANGE(1),
		BIP_RANGE(0.5),
		BIP_RANGE(0.25),
		BIP_RANGE(0.1),
		BIP_RANGE(0.05),
		UNI_RANGE(20),
		UNI_RANGE(10),
		UNI_RANGE(5),
		UNI_RANGE(2),
		UNI_RANGE(1),
		UNI_RANGE(0.5),
		UNI_RANGE(0.2),
		UNI_RANGE(0.1)
	}
};

static const struct comedi_lrange range_ni_E_ai_limited = {
	8, {
		BIP_RANGE(10),
		BIP_RANGE(5),
		BIP_RANGE(1),
		BIP_RANGE(0.1),
		UNI_RANGE(10),
		UNI_RANGE(5),
		UNI_RANGE(1),
		UNI_RANGE(0.1)
	}
};

static const struct comedi_lrange range_ni_E_ai_limited14 = {
	14, {
		BIP_RANGE(10),
		BIP_RANGE(5),
		BIP_RANGE(2),
		BIP_RANGE(1),
		BIP_RANGE(0.5),
		BIP_RANGE(0.2),
		BIP_RANGE(0.1),
		UNI_RANGE(10),
		UNI_RANGE(5),
		UNI_RANGE(2),
		UNI_RANGE(1),
		UNI_RANGE(0.5),
		UNI_RANGE(0.2),
		UNI_RANGE(0.1)
	}
};

static const struct comedi_lrange range_ni_E_ai_bipolar4 = {
	4, {
		BIP_RANGE(10),
		BIP_RANGE(5),
		BIP_RANGE(0.5),
		BIP_RANGE(0.05)
	}
};

static const struct comedi_lrange range_ni_E_ai_611x = {
	8, {
		BIP_RANGE(50),
		BIP_RANGE(20),
		BIP_RANGE(10),
		BIP_RANGE(5),
		BIP_RANGE(2),
		BIP_RANGE(1),
		BIP_RANGE(0.5),
		BIP_RANGE(0.2)
	}
};

static const struct comedi_lrange range_ni_M_ai_622x = {
	4, {
		BIP_RANGE(10),
		BIP_RANGE(5),
		BIP_RANGE(1),
		BIP_RANGE(0.2)
	}
};

static const struct comedi_lrange range_ni_M_ai_628x = {
	7, {
		BIP_RANGE(10),
		BIP_RANGE(5),
		BIP_RANGE(2),
		BIP_RANGE(1),
		BIP_RANGE(0.5),
		BIP_RANGE(0.2),
		BIP_RANGE(0.1)
	}
};

static const struct comedi_lrange range_ni_E_ao_ext = {
	4, {
		BIP_RANGE(10),
		UNI_RANGE(10),
		RANGE_ext(-1, 1),
		RANGE_ext(0, 1)
	}
};

static const struct comedi_lrange *const ni_range_lkup[] = {
	[ai_gain_16] = &range_ni_E_ai,
	[ai_gain_8] = &range_ni_E_ai_limited,
	[ai_gain_14] = &range_ni_E_ai_limited14,
	[ai_gain_4] = &range_ni_E_ai_bipolar4,
	[ai_gain_611x] = &range_ni_E_ai_611x,
	[ai_gain_622x] = &range_ni_M_ai_622x,
	[ai_gain_628x] = &range_ni_M_ai_628x,
	[ai_gain_6143] = &range_bipolar5
};

enum aimodes {
	AIMODE_NONE = 0,
	AIMODE_HALF_FULL = 1,
	AIMODE_SCAN = 2,
	AIMODE_SAMPLE = 3,
};

enum ni_common_subdevices {
	NI_AI_SUBDEV,
	NI_AO_SUBDEV,
	NI_DIO_SUBDEV,
	NI_8255_DIO_SUBDEV,
	NI_UNUSED_SUBDEV,
	NI_CALIBRATION_SUBDEV,
	NI_EEPROM_SUBDEV,
	NI_PFI_DIO_SUBDEV,
	NI_CS5529_CALIBRATION_SUBDEV,
	NI_SERIAL_SUBDEV,
	NI_RTSI_SUBDEV,
	NI_GPCT0_SUBDEV,
	NI_GPCT1_SUBDEV,
	NI_FREQ_OUT_SUBDEV,
	NI_NUM_SUBDEVICES
};

#define NI_GPCT_SUBDEV(x)	(NI_GPCT0_SUBDEV + (x))

enum timebase_nanoseconds {
	TIMEBASE_1_NS = 50,
	TIMEBASE_2_NS = 10000
};

#define SERIAL_DISABLED		0
#define SERIAL_600NS		600
#define SERIAL_1_2US		1200
#define SERIAL_10US			10000

static const int num_adc_stages_611x = 3;

static void ni_writel(struct comedi_device *dev, unsigned int data, int reg)
{
	if (dev->mmio)
		writel(data, dev->mmio + reg);
	else
		outl(data, dev->iobase + reg);
}

static void ni_writew(struct comedi_device *dev, unsigned int data, int reg)
{
	if (dev->mmio)
		writew(data, dev->mmio + reg);
	else
		outw(data, dev->iobase + reg);
}

static void ni_writeb(struct comedi_device *dev, unsigned int data, int reg)
{
	if (dev->mmio)
		writeb(data, dev->mmio + reg);
	else
		outb(data, dev->iobase + reg);
}

static unsigned int ni_readl(struct comedi_device *dev, int reg)
{
	if (dev->mmio)
		return readl(dev->mmio + reg);

	return inl(dev->iobase + reg);
}

static unsigned int ni_readw(struct comedi_device *dev, int reg)
{
	if (dev->mmio)
		return readw(dev->mmio + reg);

	return inw(dev->iobase + reg);
}

static unsigned int ni_readb(struct comedi_device *dev, int reg)
{
	if (dev->mmio)
		return readb(dev->mmio + reg);

	return inb(dev->iobase + reg);
}

/*
 * We automatically take advantage of STC registers that can be
 * read/written directly in the I/O space of the board.
 *
 * The AT-MIO and DAQCard devices map the low 8 STC registers to
 * iobase+reg*2.
 *
 * Most PCIMIO devices also map the low 8 STC registers but the
 * 611x devices map the read registers to iobase+(addr-1)*2.
 * For now non-windowed STC access is disabled if a PCIMIO device
 * is detected (devpriv->mite has been initialized).
 *
 * The M series devices do not used windowed registers for the
 * STC registers. The functions below handle the mapping of the
 * windowed STC registers to the m series register offsets.
 */

struct mio_regmap {
	unsigned int mio_reg;
	int size;
};

static const struct mio_regmap m_series_stc_write_regmap[] = {
	[NISTC_INTA_ACK_REG]		= { 0x104, 2 },
	[NISTC_INTB_ACK_REG]		= { 0x106, 2 },
	[NISTC_AI_CMD2_REG]		= { 0x108, 2 },
	[NISTC_AO_CMD2_REG]		= { 0x10a, 2 },
	[NISTC_G0_CMD_REG]		= { 0x10c, 2 },
	[NISTC_G1_CMD_REG]		= { 0x10e, 2 },
	[NISTC_AI_CMD1_REG]		= { 0x110, 2 },
	[NISTC_AO_CMD1_REG]		= { 0x112, 2 },
	/*
	 * NISTC_DIO_OUT_REG maps to:
	 * { NI_M_DIO_REG, 4 } and { NI_M_SCXI_SER_DO_REG, 1 }
	 */
	[NISTC_DIO_OUT_REG]		= { 0, 0 }, /* DOES NOT MAP CLEANLY */
	[NISTC_DIO_CTRL_REG]		= { 0, 0 }, /* DOES NOT MAP CLEANLY */
	[NISTC_AI_MODE1_REG]		= { 0x118, 2 },
	[NISTC_AI_MODE2_REG]		= { 0x11a, 2 },
	[NISTC_AI_SI_LOADA_REG]		= { 0x11c, 4 },
	[NISTC_AI_SI_LOADB_REG]		= { 0x120, 4 },
	[NISTC_AI_SC_LOADA_REG]		= { 0x124, 4 },
	[NISTC_AI_SC_LOADB_REG]		= { 0x128, 4 },
	[NISTC_AI_SI2_LOADA_REG]	= { 0x12c, 4 },
	[NISTC_AI_SI2_LOADB_REG]	= { 0x130, 4 },
	[NISTC_G0_MODE_REG]		= { 0x134, 2 },
	[NISTC_G1_MODE_REG]		= { 0x136, 2 },
	[NISTC_G0_LOADA_REG]		= { 0x138, 4 },
	[NISTC_G0_LOADB_REG]		= { 0x13c, 4 },
	[NISTC_G1_LOADA_REG]		= { 0x140, 4 },
	[NISTC_G1_LOADB_REG]		= { 0x144, 4 },
	[NISTC_G0_INPUT_SEL_REG]	= { 0x148, 2 },
	[NISTC_G1_INPUT_SEL_REG]	= { 0x14a, 2 },
	[NISTC_AO_MODE1_REG]		= { 0x14c, 2 },
	[NISTC_AO_MODE2_REG]		= { 0x14e, 2 },
	[NISTC_AO_UI_LOADA_REG]		= { 0x150, 4 },
	[NISTC_AO_UI_LOADB_REG]		= { 0x154, 4 },
	[NISTC_AO_BC_LOADA_REG]		= { 0x158, 4 },
	[NISTC_AO_BC_LOADB_REG]		= { 0x15c, 4 },
	[NISTC_AO_UC_LOADA_REG]		= { 0x160, 4 },
	[NISTC_AO_UC_LOADB_REG]		= { 0x164, 4 },
	[NISTC_CLK_FOUT_REG]		= { 0x170, 2 },
	[NISTC_IO_BIDIR_PIN_REG]	= { 0x172, 2 },
	[NISTC_RTSI_TRIG_DIR_REG]	= { 0x174, 2 },
	[NISTC_INT_CTRL_REG]		= { 0x176, 2 },
	[NISTC_AI_OUT_CTRL_REG]		= { 0x178, 2 },
	[NISTC_ATRIG_ETC_REG]		= { 0x17a, 2 },
	[NISTC_AI_START_STOP_REG]	= { 0x17c, 2 },
	[NISTC_AI_TRIG_SEL_REG]		= { 0x17e, 2 },
	[NISTC_AI_DIV_LOADA_REG]	= { 0x180, 4 },
	[NISTC_AO_START_SEL_REG]	= { 0x184, 2 },
	[NISTC_AO_TRIG_SEL_REG]		= { 0x186, 2 },
	[NISTC_G0_AUTOINC_REG]		= { 0x188, 2 },
	[NISTC_G1_AUTOINC_REG]		= { 0x18a, 2 },
	[NISTC_AO_MODE3_REG]		= { 0x18c, 2 },
	[NISTC_RESET_REG]		= { 0x190, 2 },
	[NISTC_INTA_ENA_REG]		= { 0x192, 2 },
	[NISTC_INTA2_ENA_REG]		= { 0, 0 }, /* E-Series only */
	[NISTC_INTB_ENA_REG]		= { 0x196, 2 },
	[NISTC_INTB2_ENA_REG]		= { 0, 0 }, /* E-Series only */
	[NISTC_AI_PERSONAL_REG]		= { 0x19a, 2 },
	[NISTC_AO_PERSONAL_REG]		= { 0x19c, 2 },
	[NISTC_RTSI_TRIGA_OUT_REG]	= { 0x19e, 2 },
	[NISTC_RTSI_TRIGB_OUT_REG]	= { 0x1a0, 2 },
	[NISTC_RTSI_BOARD_REG]		= { 0, 0 }, /* Unknown */
	[NISTC_CFG_MEM_CLR_REG]		= { 0x1a4, 2 },
	[NISTC_ADC_FIFO_CLR_REG]	= { 0x1a6, 2 },
	[NISTC_DAC_FIFO_CLR_REG]	= { 0x1a8, 2 },
	[NISTC_AO_OUT_CTRL_REG]		= { 0x1ac, 2 },
	[NISTC_AI_MODE3_REG]		= { 0x1ae, 2 },
};

static void m_series_stc_write(struct comedi_device *dev,
			       unsigned int data, unsigned int reg)
{
	const struct mio_regmap *regmap;

	if (reg < ARRAY_SIZE(m_series_stc_write_regmap)) {
		regmap = &m_series_stc_write_regmap[reg];
	} else {
		dev_warn(dev->class_dev, "%s: unhandled register=0x%x\n",
			 __func__, reg);
		return;
	}

	switch (regmap->size) {
	case 4:
		ni_writel(dev, data, regmap->mio_reg);
		break;
	case 2:
		ni_writew(dev, data, regmap->mio_reg);
		break;
	default:
		dev_warn(dev->class_dev, "%s: unmapped register=0x%x\n",
			 __func__, reg);
		break;
	}
}

static const struct mio_regmap m_series_stc_read_regmap[] = {
	[NISTC_AI_STATUS1_REG]		= { 0x104, 2 },
	[NISTC_AO_STATUS1_REG]		= { 0x106, 2 },
	[NISTC_G01_STATUS_REG]		= { 0x108, 2 },
	[NISTC_AI_STATUS2_REG]		= { 0, 0 }, /* Unknown */
	[NISTC_AO_STATUS2_REG]		= { 0x10c, 2 },
	[NISTC_DIO_IN_REG]		= { 0, 0 }, /* Unknown */
	[NISTC_G0_HW_SAVE_REG]		= { 0x110, 4 },
	[NISTC_G1_HW_SAVE_REG]		= { 0x114, 4 },
	[NISTC_G0_SAVE_REG]		= { 0x118, 4 },
	[NISTC_G1_SAVE_REG]		= { 0x11c, 4 },
	[NISTC_AO_UI_SAVE_REG]		= { 0x120, 4 },
	[NISTC_AO_BC_SAVE_REG]		= { 0x124, 4 },
	[NISTC_AO_UC_SAVE_REG]		= { 0x128, 4 },
	[NISTC_STATUS1_REG]		= { 0x136, 2 },
	[NISTC_DIO_SERIAL_IN_REG]	= { 0x009, 1 },
	[NISTC_STATUS2_REG]		= { 0x13a, 2 },
	[NISTC_AI_SI_SAVE_REG]		= { 0x180, 4 },
	[NISTC_AI_SC_SAVE_REG]		= { 0x184, 4 },
};

static unsigned int m_series_stc_read(struct comedi_device *dev,
				      unsigned int reg)
{
	const struct mio_regmap *regmap;

	if (reg < ARRAY_SIZE(m_series_stc_read_regmap)) {
		regmap = &m_series_stc_read_regmap[reg];
	} else {
		dev_warn(dev->class_dev, "%s: unhandled register=0x%x\n",
			 __func__, reg);
		return 0;
	}

	switch (regmap->size) {
	case 4:
		return ni_readl(dev, regmap->mio_reg);
	case 2:
		return ni_readw(dev, regmap->mio_reg);
	case 1:
		return ni_readb(dev, regmap->mio_reg);
	default:
		dev_warn(dev->class_dev, "%s: unmapped register=0x%x\n",
			 __func__, reg);
		return 0;
	}
}

static void ni_stc_writew(struct comedi_device *dev,
			  unsigned int data, int reg)
{
	struct ni_private *devpriv = dev->private;
	unsigned long flags;

	if (devpriv->is_m_series) {
		m_series_stc_write(dev, data, reg);
	} else {
		spin_lock_irqsave(&devpriv->window_lock, flags);
		if (!devpriv->mite && reg < 8) {
			ni_writew(dev, data, reg * 2);
		} else {
			ni_writew(dev, reg, NI_E_STC_WINDOW_ADDR_REG);
			ni_writew(dev, data, NI_E_STC_WINDOW_DATA_REG);
		}
		spin_unlock_irqrestore(&devpriv->window_lock, flags);
	}
}

static void ni_stc_writel(struct comedi_device *dev,
			  unsigned int data, int reg)
{
	struct ni_private *devpriv = dev->private;

	if (devpriv->is_m_series) {
		m_series_stc_write(dev, data, reg);
	} else {
		ni_stc_writew(dev, data >> 16, reg);
		ni_stc_writew(dev, data & 0xffff, reg + 1);
	}
}

static unsigned int ni_stc_readw(struct comedi_device *dev, int reg)
{
	struct ni_private *devpriv = dev->private;
	unsigned long flags;
	unsigned int val;

	if (devpriv->is_m_series) {
		val = m_series_stc_read(dev, reg);
	} else {
		spin_lock_irqsave(&devpriv->window_lock, flags);
		if (!devpriv->mite && reg < 8) {
			val = ni_readw(dev, reg * 2);
		} else {
			ni_writew(dev, reg, NI_E_STC_WINDOW_ADDR_REG);
			val = ni_readw(dev, NI_E_STC_WINDOW_DATA_REG);
		}
		spin_unlock_irqrestore(&devpriv->window_lock, flags);
	}
	return val;
}

static unsigned int ni_stc_readl(struct comedi_device *dev, int reg)
{
	struct ni_private *devpriv = dev->private;
	unsigned int val;

	if (devpriv->is_m_series) {
		val = m_series_stc_read(dev, reg);
	} else {
		val = ni_stc_readw(dev, reg) << 16;
		val |= ni_stc_readw(dev, reg + 1);
	}
	return val;
}

static inline void ni_set_bitfield(struct comedi_device *dev, int reg,
				   unsigned int bit_mask,
				   unsigned int bit_values)
{
	struct ni_private *devpriv = dev->private;
	unsigned long flags;

	spin_lock_irqsave(&devpriv->soft_reg_copy_lock, flags);
	switch (reg) {
	case NISTC_INTA_ENA_REG:
		devpriv->int_a_enable_reg &= ~bit_mask;
		devpriv->int_a_enable_reg |= bit_values & bit_mask;
		ni_stc_writew(dev, devpriv->int_a_enable_reg, reg);
		break;
	case NISTC_INTB_ENA_REG:
		devpriv->int_b_enable_reg &= ~bit_mask;
		devpriv->int_b_enable_reg |= bit_values & bit_mask;
		ni_stc_writew(dev, devpriv->int_b_enable_reg, reg);
		break;
	case NISTC_IO_BIDIR_PIN_REG:
		devpriv->io_bidirection_pin_reg &= ~bit_mask;
		devpriv->io_bidirection_pin_reg |= bit_values & bit_mask;
		ni_stc_writew(dev, devpriv->io_bidirection_pin_reg, reg);
		break;
	case NI_E_DMA_AI_AO_SEL_REG:
		devpriv->ai_ao_select_reg &= ~bit_mask;
		devpriv->ai_ao_select_reg |= bit_values & bit_mask;
		ni_writeb(dev, devpriv->ai_ao_select_reg, reg);
		break;
	case NI_E_DMA_G0_G1_SEL_REG:
		devpriv->g0_g1_select_reg &= ~bit_mask;
		devpriv->g0_g1_select_reg |= bit_values & bit_mask;
		ni_writeb(dev, devpriv->g0_g1_select_reg, reg);
		break;
	case NI_M_CDIO_DMA_SEL_REG:
		devpriv->cdio_dma_select_reg &= ~bit_mask;
		devpriv->cdio_dma_select_reg |= bit_values & bit_mask;
		ni_writeb(dev, devpriv->cdio_dma_select_reg, reg);
		break;
	default:
		dev_err(dev->class_dev, "called with invalid register %d\n",
			reg);
		break;
	}
	mmiowb();
	spin_unlock_irqrestore(&devpriv->soft_reg_copy_lock, flags);
}

#ifdef PCIDMA

/* selects the MITE channel to use for DMA */
#define NI_STC_DMA_CHAN_SEL(x)	(((x) < 4) ? BIT(x) :	\
				 ((x) == 4) ? 0x3 :	\
				 ((x) == 5) ? 0x5 : 0x0)

/* DMA channel setup */
static int ni_request_ai_mite_channel(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	struct mite_channel *mite_chan;
	unsigned long flags;
	unsigned int bits;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	mite_chan = mite_request_channel(devpriv->mite, devpriv->ai_mite_ring);
	if (!mite_chan) {
		spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
		dev_err(dev->class_dev,
			"failed to reserve mite dma channel for analog input\n");
		return -EBUSY;
	}
	mite_chan->dir = COMEDI_INPUT;
	devpriv->ai_mite_chan = mite_chan;

	bits = NI_STC_DMA_CHAN_SEL(mite_chan->channel);
	ni_set_bitfield(dev, NI_E_DMA_AI_AO_SEL_REG,
			NI_E_DMA_AI_SEL_MASK, NI_E_DMA_AI_SEL(bits));

	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
	return 0;
}

static int ni_request_ao_mite_channel(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	struct mite_channel *mite_chan;
	unsigned long flags;
	unsigned int bits;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	mite_chan = mite_request_channel(devpriv->mite, devpriv->ao_mite_ring);
	if (!mite_chan) {
		spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
		dev_err(dev->class_dev,
			"failed to reserve mite dma channel for analog outut\n");
		return -EBUSY;
	}
	mite_chan->dir = COMEDI_OUTPUT;
	devpriv->ao_mite_chan = mite_chan;

	bits = NI_STC_DMA_CHAN_SEL(mite_chan->channel);
	ni_set_bitfield(dev, NI_E_DMA_AI_AO_SEL_REG,
			NI_E_DMA_AO_SEL_MASK, NI_E_DMA_AO_SEL(bits));

	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
	return 0;
}

static int ni_request_gpct_mite_channel(struct comedi_device *dev,
					unsigned int gpct_index,
					enum comedi_io_direction direction)
{
	struct ni_private *devpriv = dev->private;
	struct ni_gpct *counter = &devpriv->counter_dev->counters[gpct_index];
	struct mite_channel *mite_chan;
	unsigned long flags;
	unsigned int bits;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	mite_chan = mite_request_channel(devpriv->mite,
					 devpriv->gpct_mite_ring[gpct_index]);
	if (!mite_chan) {
		spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
		dev_err(dev->class_dev,
			"failed to reserve mite dma channel for counter\n");
		return -EBUSY;
	}
	mite_chan->dir = direction;
	ni_tio_set_mite_channel(counter, mite_chan);

	bits = NI_STC_DMA_CHAN_SEL(mite_chan->channel);
	ni_set_bitfield(dev, NI_E_DMA_G0_G1_SEL_REG,
			NI_E_DMA_G0_G1_SEL_MASK(gpct_index),
			NI_E_DMA_G0_G1_SEL(gpct_index, bits));

	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
	return 0;
}

static int ni_request_cdo_mite_channel(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	struct mite_channel *mite_chan;
	unsigned long flags;
	unsigned int bits;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	mite_chan = mite_request_channel(devpriv->mite, devpriv->cdo_mite_ring);
	if (!mite_chan) {
		spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
		dev_err(dev->class_dev,
			"failed to reserve mite dma channel for correlated digital output\n");
		return -EBUSY;
	}
	mite_chan->dir = COMEDI_OUTPUT;
	devpriv->cdo_mite_chan = mite_chan;

	/*
	 * XXX just guessing NI_STC_DMA_CHAN_SEL()
	 * returns the right bits, under the assumption the cdio dma
	 * selection works just like ai/ao/gpct.
	 * Definitely works for dma channels 0 and 1.
	 */
	bits = NI_STC_DMA_CHAN_SEL(mite_chan->channel);
	ni_set_bitfield(dev, NI_M_CDIO_DMA_SEL_REG,
			NI_M_CDIO_DMA_SEL_CDO_MASK,
			NI_M_CDIO_DMA_SEL_CDO(bits));

	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
	return 0;
}
#endif /*  PCIDMA */

static void ni_release_ai_mite_channel(struct comedi_device *dev)
{
#ifdef PCIDMA
	struct ni_private *devpriv = dev->private;
	unsigned long flags;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (devpriv->ai_mite_chan) {
		ni_set_bitfield(dev, NI_E_DMA_AI_AO_SEL_REG,
				NI_E_DMA_AI_SEL_MASK, 0);
		mite_release_channel(devpriv->ai_mite_chan);
		devpriv->ai_mite_chan = NULL;
	}
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
#endif /*  PCIDMA */
}

static void ni_release_ao_mite_channel(struct comedi_device *dev)
{
#ifdef PCIDMA
	struct ni_private *devpriv = dev->private;
	unsigned long flags;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (devpriv->ao_mite_chan) {
		ni_set_bitfield(dev, NI_E_DMA_AI_AO_SEL_REG,
				NI_E_DMA_AO_SEL_MASK, 0);
		mite_release_channel(devpriv->ao_mite_chan);
		devpriv->ao_mite_chan = NULL;
	}
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
#endif /*  PCIDMA */
}

#ifdef PCIDMA
static void ni_release_gpct_mite_channel(struct comedi_device *dev,
					 unsigned int gpct_index)
{
	struct ni_private *devpriv = dev->private;
	unsigned long flags;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (devpriv->counter_dev->counters[gpct_index].mite_chan) {
		struct mite_channel *mite_chan =
		    devpriv->counter_dev->counters[gpct_index].mite_chan;

		ni_set_bitfield(dev, NI_E_DMA_G0_G1_SEL_REG,
				NI_E_DMA_G0_G1_SEL_MASK(gpct_index), 0);
		ni_tio_set_mite_channel(&devpriv->
					counter_dev->counters[gpct_index],
					NULL);
		mite_release_channel(mite_chan);
	}
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
}

static void ni_release_cdo_mite_channel(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	unsigned long flags;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (devpriv->cdo_mite_chan) {
		ni_set_bitfield(dev, NI_M_CDIO_DMA_SEL_REG,
				NI_M_CDIO_DMA_SEL_CDO_MASK, 0);
		mite_release_channel(devpriv->cdo_mite_chan);
		devpriv->cdo_mite_chan = NULL;
	}
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
}

static void ni_e_series_enable_second_irq(struct comedi_device *dev,
					  unsigned int gpct_index, short enable)
{
	struct ni_private *devpriv = dev->private;
	unsigned int val = 0;
	int reg;

	if (devpriv->is_m_series || gpct_index > 1)
		return;

	/*
	 * e-series boards use the second irq signals to generate
	 * dma requests for their counters
	 */
	if (gpct_index == 0) {
		reg = NISTC_INTA2_ENA_REG;
		if (enable)
			val = NISTC_INTA_ENA_G0_GATE;
	} else {
		reg = NISTC_INTB2_ENA_REG;
		if (enable)
			val = NISTC_INTB_ENA_G1_GATE;
	}
	ni_stc_writew(dev, val, reg);
}
#endif /*  PCIDMA */

static void ni_clear_ai_fifo(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	static const int timeout = 10000;
	int i;

	if (devpriv->is_6143) {
		/*  Flush the 6143 data FIFO */
		ni_writel(dev, 0x10, NI6143_AI_FIFO_CTRL_REG);
		ni_writel(dev, 0x00, NI6143_AI_FIFO_CTRL_REG);
		/*  Wait for complete */
		for (i = 0; i < timeout; i++) {
			if (!(ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) & 0x10))
				break;
			udelay(1);
		}
		if (i == timeout)
			dev_err(dev->class_dev, "FIFO flush timeout\n");
	} else {
		ni_stc_writew(dev, 1, NISTC_ADC_FIFO_CLR_REG);
		if (devpriv->is_625x) {
			ni_writeb(dev, 0, NI_M_STATIC_AI_CTRL_REG(0));
			ni_writeb(dev, 1, NI_M_STATIC_AI_CTRL_REG(0));
#if 0
			/*
			 * The NI example code does 3 convert pulses for 625x
			 * boards, But that appears to be wrong in practice.
			 */
			ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
				      NISTC_AI_CMD1_REG);
			ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
				      NISTC_AI_CMD1_REG);
			ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
				      NISTC_AI_CMD1_REG);
#endif
		}
	}
}

static inline void ni_ao_win_outw(struct comedi_device *dev,
				  unsigned int data, int addr)
{
	struct ni_private *devpriv = dev->private;
	unsigned long flags;

	spin_lock_irqsave(&devpriv->window_lock, flags);
	ni_writew(dev, addr, NI611X_AO_WINDOW_ADDR_REG);
	ni_writew(dev, data, NI611X_AO_WINDOW_DATA_REG);
	spin_unlock_irqrestore(&devpriv->window_lock, flags);
}

static inline void ni_ao_win_outl(struct comedi_device *dev,
				  unsigned int data, int addr)
{
	struct ni_private *devpriv = dev->private;
	unsigned long flags;

	spin_lock_irqsave(&devpriv->window_lock, flags);
	ni_writew(dev, addr, NI611X_AO_WINDOW_ADDR_REG);
	ni_writel(dev, data, NI611X_AO_WINDOW_DATA_REG);
	spin_unlock_irqrestore(&devpriv->window_lock, flags);
}

static inline unsigned short ni_ao_win_inw(struct comedi_device *dev, int addr)
{
	struct ni_private *devpriv = dev->private;
	unsigned long flags;
	unsigned short data;

	spin_lock_irqsave(&devpriv->window_lock, flags);
	ni_writew(dev, addr, NI611X_AO_WINDOW_ADDR_REG);
	data = ni_readw(dev, NI611X_AO_WINDOW_DATA_REG);
	spin_unlock_irqrestore(&devpriv->window_lock, flags);
	return data;
}

/*
 * ni_set_bits( ) allows different parts of the ni_mio_common driver to
 * share registers (such as Interrupt_A_Register) without interfering with
 * each other.
 *
 * NOTE: the switch/case statements are optimized out for a constant argument
 * so this is actually quite fast---  If you must wrap another function around
 * this make it inline to avoid a large speed penalty.
 *
 * value should only be 1 or 0.
 */
static inline void ni_set_bits(struct comedi_device *dev, int reg,
			       unsigned int bits, unsigned int value)
{
	unsigned int bit_values;

	if (value)
		bit_values = bits;
	else
		bit_values = 0;
	ni_set_bitfield(dev, reg, bits, bit_values);
}

#ifdef PCIDMA
static void ni_sync_ai_dma(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_subdevice *s = dev->read_subdev;
	unsigned long flags;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (devpriv->ai_mite_chan)
		mite_sync_dma(devpriv->ai_mite_chan, s);
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
}

static int ni_ai_drain_dma(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	int i;
	static const int timeout = 10000;
	unsigned long flags;
	int retval = 0;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (devpriv->ai_mite_chan) {
		for (i = 0; i < timeout; i++) {
			if ((ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
			     NISTC_AI_STATUS1_FIFO_E) &&
			    mite_bytes_in_transit(devpriv->ai_mite_chan) == 0)
				break;
			udelay(5);
		}
		if (i == timeout) {
			dev_err(dev->class_dev, "timed out\n");
			dev_err(dev->class_dev,
				"mite_bytes_in_transit=%i, AI_Status1_Register=0x%x\n",
				mite_bytes_in_transit(devpriv->ai_mite_chan),
				ni_stc_readw(dev, NISTC_AI_STATUS1_REG));
			retval = -1;
		}
	}
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);

	ni_sync_ai_dma(dev);

	return retval;
}

static int ni_ao_wait_for_dma_load(struct comedi_device *dev)
{
	static const int timeout = 10000;
	int i;

	for (i = 0; i < timeout; i++) {
		unsigned short b_status;

		b_status = ni_stc_readw(dev, NISTC_AO_STATUS1_REG);
		if (b_status & NISTC_AO_STATUS1_FIFO_HF)
			break;
		/*
		 * If we poll too often, the pci bus activity seems
		 * to slow the dma transfer down.
		 */
		usleep_range(10, 100);
	}
	if (i == timeout) {
		dev_err(dev->class_dev, "timed out waiting for dma load\n");
		return -EPIPE;
	}
	return 0;
}
#endif /* PCIDMA */

#ifndef PCIDMA

static void ni_ao_fifo_load(struct comedi_device *dev,
			    struct comedi_subdevice *s, int n)
{
	struct ni_private *devpriv = dev->private;
	int i;
	unsigned short d;
	unsigned int packed_data;

	for (i = 0; i < n; i++) {
		comedi_buf_read_samples(s, &d, 1);

		if (devpriv->is_6xxx) {
			packed_data = d & 0xffff;
			/* 6711 only has 16 bit wide ao fifo */
			if (!devpriv->is_6711) {
				comedi_buf_read_samples(s, &d, 1);
				i++;
				packed_data |= (d << 16) & 0xffff0000;
			}
			ni_writel(dev, packed_data, NI611X_AO_FIFO_DATA_REG);
		} else {
			ni_writew(dev, d, NI_E_AO_FIFO_DATA_REG);
		}
	}
}

/*
 *  There's a small problem if the FIFO gets really low and we
 *  don't have the data to fill it.  Basically, if after we fill
 *  the FIFO with all the data available, the FIFO is _still_
 *  less than half full, we never clear the interrupt.  If the
 *  IRQ is in edge mode, we never get another interrupt, because
 *  this one wasn't cleared.  If in level mode, we get flooded
 *  with interrupts that we can't fulfill, because nothing ever
 *  gets put into the buffer.
 *
 *  This kind of situation is recoverable, but it is easier to
 *  just pretend we had a FIFO underrun, since there is a good
 *  chance it will happen anyway.  This is _not_ the case for
 *  RT code, as RT code might purposely be running close to the
 *  metal.  Needs to be fixed eventually.
 */
static int ni_ao_fifo_half_empty(struct comedi_device *dev,
				 struct comedi_subdevice *s)
{
	const struct ni_board_struct *board = dev->board_ptr;
	unsigned int nbytes;
	unsigned int nsamples;

	nbytes = comedi_buf_read_n_available(s);
	if (nbytes == 0) {
		s->async->events |= COMEDI_CB_OVERFLOW;
		return 0;
	}

	nsamples = comedi_bytes_to_samples(s, nbytes);
	if (nsamples > board->ao_fifo_depth / 2)
		nsamples = board->ao_fifo_depth / 2;

	ni_ao_fifo_load(dev, s, nsamples);

	return 1;
}

static int ni_ao_prep_fifo(struct comedi_device *dev,
			   struct comedi_subdevice *s)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;
	unsigned int nbytes;
	unsigned int nsamples;

	/* reset fifo */
	ni_stc_writew(dev, 1, NISTC_DAC_FIFO_CLR_REG);
	if (devpriv->is_6xxx)
		ni_ao_win_outl(dev, 0x6, NI611X_AO_FIFO_OFFSET_LOAD_REG);

	/* load some data */
	nbytes = comedi_buf_read_n_available(s);
	if (nbytes == 0)
		return 0;

	nsamples = comedi_bytes_to_samples(s, nbytes);
	if (nsamples > board->ao_fifo_depth)
		nsamples = board->ao_fifo_depth;

	ni_ao_fifo_load(dev, s, nsamples);

	return nsamples;
}

static void ni_ai_fifo_read(struct comedi_device *dev,
			    struct comedi_subdevice *s, int n)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_async *async = s->async;
	unsigned int dl;
	unsigned short data;
	int i;

	if (devpriv->is_611x) {
		for (i = 0; i < n / 2; i++) {
			dl = ni_readl(dev, NI611X_AI_FIFO_DATA_REG);
			/* This may get the hi/lo data in the wrong order */
			data = (dl >> 16) & 0xffff;
			comedi_buf_write_samples(s, &data, 1);
			data = dl & 0xffff;
			comedi_buf_write_samples(s, &data, 1);
		}
		/* Check if there's a single sample stuck in the FIFO */
		if (n % 2) {
			dl = ni_readl(dev, NI611X_AI_FIFO_DATA_REG);
			data = dl & 0xffff;
			comedi_buf_write_samples(s, &data, 1);
		}
	} else if (devpriv->is_6143) {
		/*
		 * This just reads the FIFO assuming the data is present,
		 * no checks on the FIFO status are performed.
		 */
		for (i = 0; i < n / 2; i++) {
			dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);

			data = (dl >> 16) & 0xffff;
			comedi_buf_write_samples(s, &data, 1);
			data = dl & 0xffff;
			comedi_buf_write_samples(s, &data, 1);
		}
		if (n % 2) {
			/* Assume there is a single sample stuck in the FIFO */
			/* Get stranded sample into FIFO */
			ni_writel(dev, 0x01, NI6143_AI_FIFO_CTRL_REG);
			dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);
			data = (dl >> 16) & 0xffff;
			comedi_buf_write_samples(s, &data, 1);
		}
	} else {
		if (n > ARRAY_SIZE(devpriv->ai_fifo_buffer)) {
			dev_err(dev->class_dev,
				"bug! ai_fifo_buffer too small\n");
			async->events |= COMEDI_CB_ERROR;
			return;
		}
		for (i = 0; i < n; i++) {
			devpriv->ai_fifo_buffer[i] =
			    ni_readw(dev, NI_E_AI_FIFO_DATA_REG);
		}
		comedi_buf_write_samples(s, devpriv->ai_fifo_buffer, n);
	}
}

static void ni_handle_fifo_half_full(struct comedi_device *dev)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct comedi_subdevice *s = dev->read_subdev;
	int n;

	n = board->ai_fifo_depth / 2;

	ni_ai_fifo_read(dev, s, n);
}
#endif

/* Empties the AI fifo */
static void ni_handle_fifo_dregs(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_subdevice *s = dev->read_subdev;
	unsigned int dl;
	unsigned short data;
	int i;

	if (devpriv->is_611x) {
		while ((ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
			NISTC_AI_STATUS1_FIFO_E) == 0) {
			dl = ni_readl(dev, NI611X_AI_FIFO_DATA_REG);

			/* This may get the hi/lo data in the wrong order */
			data = dl >> 16;
			comedi_buf_write_samples(s, &data, 1);
			data = dl & 0xffff;
			comedi_buf_write_samples(s, &data, 1);
		}
	} else if (devpriv->is_6143) {
		i = 0;
		while (ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) & 0x04) {
			dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);

			/* This may get the hi/lo data in the wrong order */
			data = dl >> 16;
			comedi_buf_write_samples(s, &data, 1);
			data = dl & 0xffff;
			comedi_buf_write_samples(s, &data, 1);
			i += 2;
		}
		/*  Check if stranded sample is present */
		if (ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) & 0x01) {
			/* Get stranded sample into FIFO */
			ni_writel(dev, 0x01, NI6143_AI_FIFO_CTRL_REG);
			dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);
			data = (dl >> 16) & 0xffff;
			comedi_buf_write_samples(s, &data, 1);
		}

	} else {
		unsigned short fe;	/* fifo empty */

		fe = ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
		     NISTC_AI_STATUS1_FIFO_E;
		while (fe == 0) {
			for (i = 0;
			     i < ARRAY_SIZE(devpriv->ai_fifo_buffer); i++) {
				fe = ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
				     NISTC_AI_STATUS1_FIFO_E;
				if (fe)
					break;
				devpriv->ai_fifo_buffer[i] =
				    ni_readw(dev, NI_E_AI_FIFO_DATA_REG);
			}
			comedi_buf_write_samples(s, devpriv->ai_fifo_buffer, i);
		}
	}
}

static void get_last_sample_611x(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_subdevice *s = dev->read_subdev;
	unsigned short data;
	unsigned int dl;

	if (!devpriv->is_611x)
		return;

	/* Check if there's a single sample stuck in the FIFO */
	if (ni_readb(dev, NI_E_STATUS_REG) & 0x80) {
		dl = ni_readl(dev, NI611X_AI_FIFO_DATA_REG);
		data = dl & 0xffff;
		comedi_buf_write_samples(s, &data, 1);
	}
}

static void get_last_sample_6143(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_subdevice *s = dev->read_subdev;
	unsigned short data;
	unsigned int dl;

	if (!devpriv->is_6143)
		return;

	/* Check if there's a single sample stuck in the FIFO */
	if (ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) & 0x01) {
		/* Get stranded sample into FIFO */
		ni_writel(dev, 0x01, NI6143_AI_FIFO_CTRL_REG);
		dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);

		/* This may get the hi/lo data in the wrong order */
		data = (dl >> 16) & 0xffff;
		comedi_buf_write_samples(s, &data, 1);
	}
}

static void shutdown_ai_command(struct comedi_device *dev)
{
	struct comedi_subdevice *s = dev->read_subdev;

#ifdef PCIDMA
	ni_ai_drain_dma(dev);
#endif
	ni_handle_fifo_dregs(dev);
	get_last_sample_611x(dev);
	get_last_sample_6143(dev);

	s->async->events |= COMEDI_CB_EOA;
}

static void ni_handle_eos(struct comedi_device *dev, struct comedi_subdevice *s)
{
	struct ni_private *devpriv = dev->private;

	if (devpriv->aimode == AIMODE_SCAN) {
#ifdef PCIDMA
		static const int timeout = 10;
		int i;

		for (i = 0; i < timeout; i++) {
			ni_sync_ai_dma(dev);
			if ((s->async->events & COMEDI_CB_EOS))
				break;
			udelay(1);
		}
#else
		ni_handle_fifo_dregs(dev);
		s->async->events |= COMEDI_CB_EOS;
#endif
	}
	/* handle special case of single scan */
	if (devpriv->ai_cmd2 & NISTC_AI_CMD2_END_ON_EOS)
		shutdown_ai_command(dev);
}

static void handle_gpct_interrupt(struct comedi_device *dev,
				  unsigned short counter_index)
{
#ifdef PCIDMA
	struct ni_private *devpriv = dev->private;
	struct comedi_subdevice *s;

	s = &dev->subdevices[NI_GPCT_SUBDEV(counter_index)];

	ni_tio_handle_interrupt(&devpriv->counter_dev->counters[counter_index],
				s);
	comedi_handle_events(dev, s);
#endif
}

static void ack_a_interrupt(struct comedi_device *dev, unsigned short a_status)
{
	unsigned short ack = 0;

	if (a_status & NISTC_AI_STATUS1_SC_TC)
		ack |= NISTC_INTA_ACK_AI_SC_TC;
	if (a_status & NISTC_AI_STATUS1_START1)
		ack |= NISTC_INTA_ACK_AI_START1;
	if (a_status & NISTC_AI_STATUS1_START)
		ack |= NISTC_INTA_ACK_AI_START;
	if (a_status & NISTC_AI_STATUS1_STOP)
		ack |= NISTC_INTA_ACK_AI_STOP;
	if (ack)
		ni_stc_writew(dev, ack, NISTC_INTA_ACK_REG);
}

static void handle_a_interrupt(struct comedi_device *dev,
			       struct comedi_subdevice *s,
			       unsigned short status)
{
	struct comedi_cmd *cmd = &s->async->cmd;

	/* test for all uncommon interrupt events at the same time */
	if (status & (NISTC_AI_STATUS1_ERR |
		      NISTC_AI_STATUS1_SC_TC | NISTC_AI_STATUS1_START1)) {
		if (status == 0xffff) {
			dev_err(dev->class_dev, "Card removed?\n");
			/*
			 * We probably aren't even running a command now,
			 * so it's a good idea to be careful.
			 */
			if (comedi_is_subdevice_running(s))
				s->async->events |= COMEDI_CB_ERROR;
			return;
		}
		if (status & NISTC_AI_STATUS1_ERR) {
			dev_err(dev->class_dev, "ai error a_status=%04x\n",
				status);

			shutdown_ai_command(dev);

			s->async->events |= COMEDI_CB_ERROR;
			if (status & NISTC_AI_STATUS1_OVER)
				s->async->events |= COMEDI_CB_OVERFLOW;
			return;
		}
		if (status & NISTC_AI_STATUS1_SC_TC) {
			if (cmd->stop_src == TRIG_COUNT)
				shutdown_ai_command(dev);
		}
	}
#ifndef PCIDMA
	if (status & NISTC_AI_STATUS1_FIFO_HF) {
		int i;
		static const int timeout = 10;
		/*
		 * PCMCIA cards (at least 6036) seem to stop producing
		 * interrupts if we fail to get the fifo less than half
		 * full, so loop to be sure.
		 */
		for (i = 0; i < timeout; ++i) {
			ni_handle_fifo_half_full(dev);
			if ((ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
			     NISTC_AI_STATUS1_FIFO_HF) == 0)
				break;
		}
	}
#endif /*  !PCIDMA */

	if (status & NISTC_AI_STATUS1_STOP)
		ni_handle_eos(dev, s);
}

static void ack_b_interrupt(struct comedi_device *dev, unsigned short b_status)
{
	unsigned short ack = 0;

	if (b_status & NISTC_AO_STATUS1_BC_TC)
		ack |= NISTC_INTB_ACK_AO_BC_TC;
	if (b_status & NISTC_AO_STATUS1_OVERRUN)
		ack |= NISTC_INTB_ACK_AO_ERR;
	if (b_status & NISTC_AO_STATUS1_START)
		ack |= NISTC_INTB_ACK_AO_START;
	if (b_status & NISTC_AO_STATUS1_START1)
		ack |= NISTC_INTB_ACK_AO_START1;
	if (b_status & NISTC_AO_STATUS1_UC_TC)
		ack |= NISTC_INTB_ACK_AO_UC_TC;
	if (b_status & NISTC_AO_STATUS1_UI2_TC)
		ack |= NISTC_INTB_ACK_AO_UI2_TC;
	if (b_status & NISTC_AO_STATUS1_UPDATE)
		ack |= NISTC_INTB_ACK_AO_UPDATE;
	if (ack)
		ni_stc_writew(dev, ack, NISTC_INTB_ACK_REG);
}

static void handle_b_interrupt(struct comedi_device *dev,
			       struct comedi_subdevice *s,
			       unsigned short b_status)
{
	if (b_status == 0xffff)
		return;
	if (b_status & NISTC_AO_STATUS1_OVERRUN) {
		dev_err(dev->class_dev,
			"AO FIFO underrun status=0x%04x status2=0x%04x\n",
			b_status, ni_stc_readw(dev, NISTC_AO_STATUS2_REG));
		s->async->events |= COMEDI_CB_OVERFLOW;
	}

	if (s->async->cmd.stop_src != TRIG_NONE &&
	    b_status & NISTC_AO_STATUS1_BC_TC)
		s->async->events |= COMEDI_CB_EOA;

#ifndef PCIDMA
	if (b_status & NISTC_AO_STATUS1_FIFO_REQ) {
		int ret;

		ret = ni_ao_fifo_half_empty(dev, s);
		if (!ret) {
			dev_err(dev->class_dev, "AO buffer underrun\n");
			ni_set_bits(dev, NISTC_INTB_ENA_REG,
				    NISTC_INTB_ENA_AO_FIFO |
				    NISTC_INTB_ENA_AO_ERR, 0);
			s->async->events |= COMEDI_CB_OVERFLOW;
		}
	}
#endif
}

static void ni_ai_munge(struct comedi_device *dev, struct comedi_subdevice *s,
			void *data, unsigned int num_bytes,
			unsigned int chan_index)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_async *async = s->async;
	struct comedi_cmd *cmd = &async->cmd;
	unsigned int nsamples = comedi_bytes_to_samples(s, num_bytes);
	unsigned short *array = data;
	unsigned int *larray = data;
	unsigned int i;
#ifdef PCIDMA
	__le16 *barray = data;
	__le32 *blarray = data;
#endif

	for (i = 0; i < nsamples; i++) {
#ifdef PCIDMA
		if (s->subdev_flags & SDF_LSAMPL)
			larray[i] = le32_to_cpu(blarray[i]);
		else
			array[i] = le16_to_cpu(barray[i]);
#endif
		if (s->subdev_flags & SDF_LSAMPL)
			larray[i] += devpriv->ai_offset[chan_index];
		else
			array[i] += devpriv->ai_offset[chan_index];
		chan_index++;
		chan_index %= cmd->chanlist_len;
	}
}

#ifdef PCIDMA

static int ni_ai_setup_MITE_dma(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_subdevice *s = dev->read_subdev;
	int retval;
	unsigned long flags;

	retval = ni_request_ai_mite_channel(dev);
	if (retval)
		return retval;

	/* write alloc the entire buffer */
	comedi_buf_write_alloc(s, s->async->prealloc_bufsz);

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (!devpriv->ai_mite_chan) {
		spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
		return -EIO;
	}

	if (devpriv->is_611x || devpriv->is_6143)
		mite_prep_dma(devpriv->ai_mite_chan, 32, 16);
	else if (devpriv->is_628x)
		mite_prep_dma(devpriv->ai_mite_chan, 32, 32);
	else
		mite_prep_dma(devpriv->ai_mite_chan, 16, 16);

	/*start the MITE */
	mite_dma_arm(devpriv->ai_mite_chan);
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);

	return 0;
}

static int ni_ao_setup_MITE_dma(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_subdevice *s = dev->write_subdev;
	int retval;
	unsigned long flags;

	retval = ni_request_ao_mite_channel(dev);
	if (retval)
		return retval;

	/* read alloc the entire buffer */
	comedi_buf_read_alloc(s, s->async->prealloc_bufsz);

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (devpriv->ao_mite_chan) {
		if (devpriv->is_611x || devpriv->is_6713) {
			mite_prep_dma(devpriv->ao_mite_chan, 32, 32);
		} else {
			/*
			 * Doing 32 instead of 16 bit wide transfers from
			 * memory makes the mite do 32 bit pci transfers,
			 * doubling pci bandwidth.
			 */
			mite_prep_dma(devpriv->ao_mite_chan, 16, 32);
		}
		mite_dma_arm(devpriv->ao_mite_chan);
	} else {
		retval = -EIO;
	}
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);

	return retval;
}

#endif /*  PCIDMA */

/*
 * used for both cancel ioctl and board initialization
 *
 * this is pretty harsh for a cancel, but it works...
 */
static int ni_ai_reset(struct comedi_device *dev, struct comedi_subdevice *s)
{
	struct ni_private *devpriv = dev->private;
	unsigned int ai_personal;
	unsigned int ai_out_ctrl;

	ni_release_ai_mite_channel(dev);
	/* ai configuration */
	ni_stc_writew(dev, NISTC_RESET_AI_CFG_START | NISTC_RESET_AI,
		      NISTC_RESET_REG);

	ni_set_bits(dev, NISTC_INTA_ENA_REG, NISTC_INTA_ENA_AI_MASK, 0);

	ni_clear_ai_fifo(dev);

	if (!devpriv->is_6143)
		ni_writeb(dev, NI_E_MISC_CMD_EXT_ATRIG, NI_E_MISC_CMD_REG);

	ni_stc_writew(dev, NISTC_AI_CMD1_DISARM, NISTC_AI_CMD1_REG);
	ni_stc_writew(dev, NISTC_AI_MODE1_START_STOP |
			   NISTC_AI_MODE1_RSVD
			    /*| NISTC_AI_MODE1_TRIGGER_ONCE */,
		      NISTC_AI_MODE1_REG);
	ni_stc_writew(dev, 0, NISTC_AI_MODE2_REG);
	/* generate FIFO interrupts on non-empty */
	ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_NE,
		      NISTC_AI_MODE3_REG);

	ai_personal = NISTC_AI_PERSONAL_SHIFTIN_PW |
		      NISTC_AI_PERSONAL_SOC_POLARITY |
		      NISTC_AI_PERSONAL_LOCALMUX_CLK_PW;
	ai_out_ctrl = NISTC_AI_OUT_CTRL_SCAN_IN_PROG_SEL(3) |
		      NISTC_AI_OUT_CTRL_EXTMUX_CLK_SEL(0) |
		      NISTC_AI_OUT_CTRL_LOCALMUX_CLK_SEL(2) |
		      NISTC_AI_OUT_CTRL_SC_TC_SEL(3);
	if (devpriv->is_611x) {
		ai_out_ctrl |= NISTC_AI_OUT_CTRL_CONVERT_HIGH;
	} else if (devpriv->is_6143) {
		ai_out_ctrl |= NISTC_AI_OUT_CTRL_CONVERT_LOW;
	} else {
		ai_personal |= NISTC_AI_PERSONAL_CONVERT_PW;
		if (devpriv->is_622x)
			ai_out_ctrl |= NISTC_AI_OUT_CTRL_CONVERT_HIGH;
		else
			ai_out_ctrl |= NISTC_AI_OUT_CTRL_CONVERT_LOW;
	}
	ni_stc_writew(dev, ai_personal, NISTC_AI_PERSONAL_REG);
	ni_stc_writew(dev, ai_out_ctrl, NISTC_AI_OUT_CTRL_REG);

	/* the following registers should not be changed, because there
	 * are no backup registers in devpriv.  If you want to change
	 * any of these, add a backup register and other appropriate code:
	 *      NISTC_AI_MODE1_REG
	 *      NISTC_AI_MODE3_REG
	 *      NISTC_AI_PERSONAL_REG
	 *      NISTC_AI_OUT_CTRL_REG
	 */

	/* clear interrupts */
	ni_stc_writew(dev, NISTC_INTA_ACK_AI_ALL, NISTC_INTA_ACK_REG);

	ni_stc_writew(dev, NISTC_RESET_AI_CFG_END, NISTC_RESET_REG);

	return 0;
}

static int ni_ai_poll(struct comedi_device *dev, struct comedi_subdevice *s)
{
	unsigned long flags;
	int count;

	/*  lock to avoid race with interrupt handler */
	spin_lock_irqsave(&dev->spinlock, flags);
#ifndef PCIDMA
	ni_handle_fifo_dregs(dev);
#else
	ni_sync_ai_dma(dev);
#endif
	count = comedi_buf_n_bytes_ready(s);
	spin_unlock_irqrestore(&dev->spinlock, flags);

	return count;
}

static void ni_prime_channelgain_list(struct comedi_device *dev)
{
	int i;

	ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE, NISTC_AI_CMD1_REG);
	for (i = 0; i < NI_TIMEOUT; ++i) {
		if (!(ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
		      NISTC_AI_STATUS1_FIFO_E)) {
			ni_stc_writew(dev, 1, NISTC_ADC_FIFO_CLR_REG);
			return;
		}
		udelay(1);
	}
	dev_err(dev->class_dev, "timeout loading channel/gain list\n");
}

static void ni_m_series_load_channelgain_list(struct comedi_device *dev,
					      unsigned int n_chan,
					      unsigned int *list)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;
	unsigned int chan, range, aref;
	unsigned int i;
	unsigned int dither;
	unsigned int range_code;

	ni_stc_writew(dev, 1, NISTC_CFG_MEM_CLR_REG);

	if ((list[0] & CR_ALT_SOURCE)) {
		unsigned int bypass_bits;

		chan = CR_CHAN(list[0]);
		range = CR_RANGE(list[0]);
		range_code = ni_gainlkup[board->gainlkup][range];
		dither = (list[0] & CR_ALT_FILTER) != 0;
		bypass_bits = NI_M_CFG_BYPASS_FIFO |
			      NI_M_CFG_BYPASS_AI_CHAN(chan) |
			      NI_M_CFG_BYPASS_AI_GAIN(range_code) |
			      devpriv->ai_calib_source;
		if (dither)
			bypass_bits |= NI_M_CFG_BYPASS_AI_DITHER;
		/*  don't use 2's complement encoding */
		bypass_bits |= NI_M_CFG_BYPASS_AI_POLARITY;
		ni_writel(dev, bypass_bits, NI_M_CFG_BYPASS_FIFO_REG);
	} else {
		ni_writel(dev, 0, NI_M_CFG_BYPASS_FIFO_REG);
	}
	for (i = 0; i < n_chan; i++) {
		unsigned int config_bits = 0;

		chan = CR_CHAN(list[i]);
		aref = CR_AREF(list[i]);
		range = CR_RANGE(list[i]);
		dither = (list[i] & CR_ALT_FILTER) != 0;

		range_code = ni_gainlkup[board->gainlkup][range];
		devpriv->ai_offset[i] = 0;
		switch (aref) {
		case AREF_DIFF:
			config_bits |= NI_M_AI_CFG_CHAN_TYPE_DIFF;
			break;
		case AREF_COMMON:
			config_bits |= NI_M_AI_CFG_CHAN_TYPE_COMMON;
			break;
		case AREF_GROUND:
			config_bits |= NI_M_AI_CFG_CHAN_TYPE_GROUND;
			break;
		case AREF_OTHER:
			break;
		}
		config_bits |= NI_M_AI_CFG_CHAN_SEL(chan);
		config_bits |= NI_M_AI_CFG_BANK_SEL(chan);
		config_bits |= NI_M_AI_CFG_GAIN(range_code);
		if (i == n_chan - 1)
			config_bits |= NI_M_AI_CFG_LAST_CHAN;
		if (dither)
			config_bits |= NI_M_AI_CFG_DITHER;
		/*  don't use 2's complement encoding */
		config_bits |= NI_M_AI_CFG_POLARITY;
		ni_writew(dev, config_bits, NI_M_AI_CFG_FIFO_DATA_REG);
	}
	ni_prime_channelgain_list(dev);
}

/*
 * Notes on the 6110 and 6111:
 * These boards a slightly different than the rest of the series, since
 * they have multiple A/D converters.
 * From the driver side, the configuration memory is a
 * little different.
 * Configuration Memory Low:
 *   bits 15-9: same
 *   bit 8: unipolar/bipolar (should be 0 for bipolar)
 *   bits 0-3: gain.  This is 4 bits instead of 3 for the other boards
 *       1001 gain=0.1 (+/- 50)
 *       1010 0.2
 *       1011 0.1
 *       0001 1
 *       0010 2
 *       0011 5
 *       0100 10
 *       0101 20
 *       0110 50
 * Configuration Memory High:
 *   bits 12-14: Channel Type
 *       001 for differential
 *       000 for calibration
 *   bit 11: coupling  (this is not currently handled)
 *       1 AC coupling
 *       0 DC coupling
 *   bits 0-2: channel
 *       valid channels are 0-3
 */
static void ni_load_channelgain_list(struct comedi_device *dev,
				     struct comedi_subdevice *s,
				     unsigned int n_chan, unsigned int *list)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;
	unsigned int offset = (s->maxdata + 1) >> 1;
	unsigned int chan, range, aref;
	unsigned int i;
	unsigned int hi, lo;
	unsigned int dither;

	if (devpriv->is_m_series) {
		ni_m_series_load_channelgain_list(dev, n_chan, list);
		return;
	}
	if (n_chan == 1 && !devpriv->is_611x && !devpriv->is_6143) {
		if (devpriv->changain_state &&
		    devpriv->changain_spec == list[0]) {
			/*  ready to go. */
			return;
		}
		devpriv->changain_state = 1;
		devpriv->changain_spec = list[0];
	} else {
		devpriv->changain_state = 0;
	}

	ni_stc_writew(dev, 1, NISTC_CFG_MEM_CLR_REG);

	/*  Set up Calibration mode if required */
	if (devpriv->is_6143) {
		if ((list[0] & CR_ALT_SOURCE) &&
		    !devpriv->ai_calib_source_enabled) {
			/*  Strobe Relay enable bit */
			ni_writew(dev, devpriv->ai_calib_source |
				       NI6143_CALIB_CHAN_RELAY_ON,
				  NI6143_CALIB_CHAN_REG);
			ni_writew(dev, devpriv->ai_calib_source,
				  NI6143_CALIB_CHAN_REG);
			devpriv->ai_calib_source_enabled = 1;
			/* Allow relays to change */
			msleep_interruptible(100);
		} else if (!(list[0] & CR_ALT_SOURCE) &&
			   devpriv->ai_calib_source_enabled) {
			/*  Strobe Relay disable bit */
			ni_writew(dev, devpriv->ai_calib_source |
				       NI6143_CALIB_CHAN_RELAY_OFF,
				  NI6143_CALIB_CHAN_REG);
			ni_writew(dev, devpriv->ai_calib_source,
				  NI6143_CALIB_CHAN_REG);
			devpriv->ai_calib_source_enabled = 0;
			/* Allow relays to change */
			msleep_interruptible(100);
		}
	}

	for (i = 0; i < n_chan; i++) {
		if (!devpriv->is_6143 && (list[i] & CR_ALT_SOURCE))
			chan = devpriv->ai_calib_source;
		else
			chan = CR_CHAN(list[i]);
		aref = CR_AREF(list[i]);
		range = CR_RANGE(list[i]);
		dither = (list[i] & CR_ALT_FILTER) != 0;

		/* fix the external/internal range differences */
		range = ni_gainlkup[board->gainlkup][range];
		if (devpriv->is_611x)
			devpriv->ai_offset[i] = offset;
		else
			devpriv->ai_offset[i] = (range & 0x100) ? 0 : offset;

		hi = 0;
		if ((list[i] & CR_ALT_SOURCE)) {
			if (devpriv->is_611x)
				ni_writew(dev, CR_CHAN(list[i]) & 0x0003,
					  NI611X_CALIB_CHAN_SEL_REG);
		} else {
			if (devpriv->is_611x)
				aref = AREF_DIFF;
			else if (devpriv->is_6143)
				aref = AREF_OTHER;
			switch (aref) {
			case AREF_DIFF:
				hi |= NI_E_AI_CFG_HI_TYPE_DIFF;
				break;
			case AREF_COMMON:
				hi |= NI_E_AI_CFG_HI_TYPE_COMMON;
				break;
			case AREF_GROUND:
				hi |= NI_E_AI_CFG_HI_TYPE_GROUND;
				break;
			case AREF_OTHER:
				break;
			}
		}
		hi |= NI_E_AI_CFG_HI_CHAN(chan);

		ni_writew(dev, hi, NI_E_AI_CFG_HI_REG);

		if (!devpriv->is_6143) {
			lo = NI_E_AI_CFG_LO_GAIN(range);

			if (i == n_chan - 1)
				lo |= NI_E_AI_CFG_LO_LAST_CHAN;
			if (dither)
				lo |= NI_E_AI_CFG_LO_DITHER;

			ni_writew(dev, lo, NI_E_AI_CFG_LO_REG);
		}
	}

	/* prime the channel/gain list */
	if (!devpriv->is_611x && !devpriv->is_6143)
		ni_prime_channelgain_list(dev);
}

static int ni_ai_insn_read(struct comedi_device *dev,
			   struct comedi_subdevice *s,
			   struct comedi_insn *insn,
			   unsigned int *data)
{
	struct ni_private *devpriv = dev->private;
	unsigned int mask = s->maxdata;
	int i, n;
	unsigned int signbits;
	unsigned int d;
	unsigned long dl;

	ni_load_channelgain_list(dev, s, 1, &insn->chanspec);

	ni_clear_ai_fifo(dev);

	signbits = devpriv->ai_offset[0];
	if (devpriv->is_611x) {
		for (n = 0; n < num_adc_stages_611x; n++) {
			ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
				      NISTC_AI_CMD1_REG);
			udelay(1);
		}
		for (n = 0; n < insn->n; n++) {
			ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
				      NISTC_AI_CMD1_REG);
			/* The 611x has screwy 32-bit FIFOs. */
			d = 0;
			for (i = 0; i < NI_TIMEOUT; i++) {
				if (ni_readb(dev, NI_E_STATUS_REG) & 0x80) {
					d = ni_readl(dev,
						     NI611X_AI_FIFO_DATA_REG);
					d >>= 16;
					d &= 0xffff;
					break;
				}
				if (!(ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
				      NISTC_AI_STATUS1_FIFO_E)) {
					d = ni_readl(dev,
						     NI611X_AI_FIFO_DATA_REG);
					d &= 0xffff;
					break;
				}
			}
			if (i == NI_TIMEOUT) {
				dev_err(dev->class_dev, "timeout\n");
				return -ETIME;
			}
			d += signbits;
			data[n] = d & 0xffff;
		}
	} else if (devpriv->is_6143) {
		for (n = 0; n < insn->n; n++) {
			ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
				      NISTC_AI_CMD1_REG);

			/*
			 * The 6143 has 32-bit FIFOs. You need to strobe a
			 * bit to move a single 16bit stranded sample into
			 * the FIFO.
			 */
			dl = 0;
			for (i = 0; i < NI_TIMEOUT; i++) {
				if (ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) &
				    0x01) {
					/* Get stranded sample into FIFO */
					ni_writel(dev, 0x01,
						  NI6143_AI_FIFO_CTRL_REG);
					dl = ni_readl(dev,
						      NI6143_AI_FIFO_DATA_REG);
					break;
				}
			}
			if (i == NI_TIMEOUT) {
				dev_err(dev->class_dev, "timeout\n");
				return -ETIME;
			}
			data[n] = (((dl >> 16) & 0xFFFF) + signbits) & 0xFFFF;
		}
	} else {
		for (n = 0; n < insn->n; n++) {
			ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
				      NISTC_AI_CMD1_REG);
			for (i = 0; i < NI_TIMEOUT; i++) {
				if (!(ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
				      NISTC_AI_STATUS1_FIFO_E))
					break;
			}
			if (i == NI_TIMEOUT) {
				dev_err(dev->class_dev, "timeout\n");
				return -ETIME;
			}
			if (devpriv->is_m_series) {
				dl = ni_readl(dev, NI_M_AI_FIFO_DATA_REG);
				dl &= mask;
				data[n] = dl;
			} else {
				d = ni_readw(dev, NI_E_AI_FIFO_DATA_REG);
				d += signbits;
				data[n] = d & 0xffff;
			}
		}
	}
	return insn->n;
}

static int ni_ns_to_timer(const struct comedi_device *dev,
			  unsigned int nanosec, unsigned int flags)
{
	struct ni_private *devpriv = dev->private;
	int divider;

	switch (flags & CMDF_ROUND_MASK) {
	case CMDF_ROUND_NEAREST:
	default:
		divider = DIV_ROUND_CLOSEST(nanosec, devpriv->clock_ns);
		break;
	case CMDF_ROUND_DOWN:
		divider = (nanosec) / devpriv->clock_ns;
		break;
	case CMDF_ROUND_UP:
		divider = DIV_ROUND_UP(nanosec, devpriv->clock_ns);
		break;
	}
	return divider - 1;
}

static unsigned int ni_timer_to_ns(const struct comedi_device *dev, int timer)
{
	struct ni_private *devpriv = dev->private;

	return devpriv->clock_ns * (timer + 1);
}

static void ni_cmd_set_mite_transfer(struct mite_ring *ring,
				     struct comedi_subdevice *sdev,
				     const struct comedi_cmd *cmd,
				     unsigned int max_count) {
#ifdef PCIDMA
	unsigned int nbytes = max_count;

	if (cmd->stop_arg > 0 && cmd->stop_arg < max_count)
		nbytes = cmd->stop_arg;
	nbytes *= comedi_bytes_per_scan(sdev);

	if (nbytes > sdev->async->prealloc_bufsz) {
		if (cmd->stop_arg > 0)
			dev_err(sdev->device->class_dev,
				"ni_cmd_set_mite_transfer: tried exact data transfer limits greater than buffer size\n");

		/*
		 * we can only transfer up to the size of the buffer.  In this
		 * case, the user is expected to continue to write into the
		 * comedi buffer (already implemented as a ring buffer).
		 */
		nbytes = sdev->async->prealloc_bufsz;
	}

	mite_init_ring_descriptors(ring, sdev, nbytes);
#else
	dev_err(sdev->device->class_dev,
		"ni_cmd_set_mite_transfer: exact data transfer limits not implemented yet without DMA\n");
#endif
}

static unsigned int ni_min_ai_scan_period_ns(struct comedi_device *dev,
					     unsigned int num_channels)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;

	/* simultaneously-sampled inputs */
	if (devpriv->is_611x || devpriv->is_6143)
		return board->ai_speed;

	/* multiplexed inputs */
	return board->ai_speed * num_channels;
}

static int ni_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
			 struct comedi_cmd *cmd)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;
	int err = 0;
	unsigned int tmp;
	unsigned int sources;

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

	err |= comedi_check_trigger_src(&cmd->start_src,
					TRIG_NOW | TRIG_INT | TRIG_EXT);
	err |= comedi_check_trigger_src(&cmd->scan_begin_src,
					TRIG_TIMER | TRIG_EXT);

	sources = TRIG_TIMER | TRIG_EXT;
	if (devpriv->is_611x || devpriv->is_6143)
		sources |= TRIG_NOW;
	err |= comedi_check_trigger_src(&cmd->convert_src, sources);

	err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
	err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);

	if (err)
		return 1;

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

	err |= comedi_check_trigger_is_unique(cmd->start_src);
	err |= comedi_check_trigger_is_unique(cmd->scan_begin_src);
	err |= comedi_check_trigger_is_unique(cmd->convert_src);
	err |= comedi_check_trigger_is_unique(cmd->stop_src);

	/* Step 2b : and mutually compatible */

	if (err)
		return 2;

	/* Step 3: check if arguments are trivially valid */

	switch (cmd->start_src) {
	case TRIG_NOW:
	case TRIG_INT:
		err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0);
		break;
	case TRIG_EXT:
		tmp = CR_CHAN(cmd->start_arg);

		if (tmp > 16)
			tmp = 16;
		tmp |= (cmd->start_arg & (CR_INVERT | CR_EDGE));
		err |= comedi_check_trigger_arg_is(&cmd->start_arg, tmp);
		break;
	}

	if (cmd->scan_begin_src == TRIG_TIMER) {
		err |= comedi_check_trigger_arg_min(&cmd->scan_begin_arg,
			ni_min_ai_scan_period_ns(dev, cmd->chanlist_len));
		err |= comedi_check_trigger_arg_max(&cmd->scan_begin_arg,
						    devpriv->clock_ns *
						    0xffffff);
	} else if (cmd->scan_begin_src == TRIG_EXT) {
		/* external trigger */
		unsigned int tmp = CR_CHAN(cmd->scan_begin_arg);

		if (tmp > 16)
			tmp = 16;
		tmp |= (cmd->scan_begin_arg & (CR_INVERT | CR_EDGE));
		err |= comedi_check_trigger_arg_is(&cmd->scan_begin_arg, tmp);
	} else {		/* TRIG_OTHER */
		err |= comedi_check_trigger_arg_is(&cmd->scan_begin_arg, 0);
	}

	if (cmd->convert_src == TRIG_TIMER) {
		if (devpriv->is_611x || devpriv->is_6143) {
			err |= comedi_check_trigger_arg_is(&cmd->convert_arg,
							   0);
		} else {
			err |= comedi_check_trigger_arg_min(&cmd->convert_arg,
							    board->ai_speed);
			err |= comedi_check_trigger_arg_max(&cmd->convert_arg,
							    devpriv->clock_ns *
							    0xffff);
		}
	} else if (cmd->convert_src == TRIG_EXT) {
		/* external trigger */
		unsigned int tmp = CR_CHAN(cmd->convert_arg);

		if (tmp > 16)
			tmp = 16;
		tmp |= (cmd->convert_arg & (CR_ALT_FILTER | CR_INVERT));
		err |= comedi_check_trigger_arg_is(&cmd->convert_arg, tmp);
	} else if (cmd->convert_src == TRIG_NOW) {
		err |= comedi_check_trigger_arg_is(&cmd->convert_arg, 0);
	}

	err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg,
					   cmd->chanlist_len);

	if (cmd->stop_src == TRIG_COUNT) {
		unsigned int max_count = 0x01000000;

		if (devpriv->is_611x)
			max_count -= num_adc_stages_611x;
		err |= comedi_check_trigger_arg_max(&cmd->stop_arg, max_count);
		err |= comedi_check_trigger_arg_min(&cmd->stop_arg, 1);
	} else {
		/* TRIG_NONE */
		err |= comedi_check_trigger_arg_is(&cmd->stop_arg, 0);
	}

	if (err)
		return 3;

	/* step 4: fix up any arguments */

	if (cmd->scan_begin_src == TRIG_TIMER) {
		tmp = cmd->scan_begin_arg;
		cmd->scan_begin_arg =
		    ni_timer_to_ns(dev, ni_ns_to_timer(dev,
						       cmd->scan_begin_arg,
						       cmd->flags));
		if (tmp != cmd->scan_begin_arg)
			err++;
	}
	if (cmd->convert_src == TRIG_TIMER) {
		if (!devpriv->is_611x && !devpriv->is_6143) {
			tmp = cmd->convert_arg;
			cmd->convert_arg =
			    ni_timer_to_ns(dev, ni_ns_to_timer(dev,
							       cmd->convert_arg,
							       cmd->flags));
			if (tmp != cmd->convert_arg)
				err++;
			if (cmd->scan_begin_src == TRIG_TIMER &&
			    cmd->scan_begin_arg <
			    cmd->convert_arg * cmd->scan_end_arg) {
				cmd->scan_begin_arg =
				    cmd->convert_arg * cmd->scan_end_arg;
				err++;
			}
		}
	}

	if (err)
		return 4;

	return 0;
}

static int ni_ai_inttrig(struct comedi_device *dev,
			 struct comedi_subdevice *s,
			 unsigned int trig_num)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_cmd *cmd = &s->async->cmd;

	if (trig_num != cmd->start_arg)
		return -EINVAL;

	ni_stc_writew(dev, NISTC_AI_CMD2_START1_PULSE | devpriv->ai_cmd2,
		      NISTC_AI_CMD2_REG);
	s->async->inttrig = NULL;

	return 1;
}

static int ni_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
	struct ni_private *devpriv = dev->private;
	const struct comedi_cmd *cmd = &s->async->cmd;
	int timer;
	int mode1 = 0;		/* mode1 is needed for both stop and convert */
	int mode2 = 0;
	int start_stop_select = 0;
	unsigned int stop_count;
	int interrupt_a_enable = 0;
	unsigned int ai_trig;

	if (dev->irq == 0) {
		dev_err(dev->class_dev, "cannot run command without an irq\n");
		return -EIO;
	}
	ni_clear_ai_fifo(dev);

	ni_load_channelgain_list(dev, s, cmd->chanlist_len, cmd->chanlist);

	/* start configuration */
	ni_stc_writew(dev, NISTC_RESET_AI_CFG_START, NISTC_RESET_REG);

	/*
	 * Disable analog triggering for now, since it interferes
	 * with the use of pfi0.
	 */
	devpriv->an_trig_etc_reg &= ~NISTC_ATRIG_ETC_ENA;
	ni_stc_writew(dev, devpriv->an_trig_etc_reg, NISTC_ATRIG_ETC_REG);

	ai_trig = NISTC_AI_TRIG_START2_SEL(0) | NISTC_AI_TRIG_START1_SYNC;
	switch (cmd->start_src) {
	case TRIG_INT:
	case TRIG_NOW:
		ai_trig |= NISTC_AI_TRIG_START1_EDGE |
			   NISTC_AI_TRIG_START1_SEL(0);
		break;
	case TRIG_EXT:
		ai_trig |= NISTC_AI_TRIG_START1_SEL(CR_CHAN(cmd->start_arg) +
						    1);

		if (cmd->start_arg & CR_INVERT)
			ai_trig |= NISTC_AI_TRIG_START1_POLARITY;
		if (cmd->start_arg & CR_EDGE)
			ai_trig |= NISTC_AI_TRIG_START1_EDGE;
		break;
	}
	ni_stc_writew(dev, ai_trig, NISTC_AI_TRIG_SEL_REG);

	mode2 &= ~NISTC_AI_MODE2_PRE_TRIGGER;
	mode2 &= ~NISTC_AI_MODE2_SC_INIT_LOAD_SRC;
	mode2 &= ~NISTC_AI_MODE2_SC_RELOAD_MODE;
	ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);

	if (cmd->chanlist_len == 1 || devpriv->is_611x || devpriv->is_6143) {
		/* logic low */
		start_stop_select |= NISTC_AI_STOP_POLARITY |
				     NISTC_AI_STOP_SEL(31) |
				     NISTC_AI_STOP_SYNC;
	} else {
		/*  ai configuration memory */
		start_stop_select |= NISTC_AI_STOP_SEL(19);
	}
	ni_stc_writew(dev, start_stop_select, NISTC_AI_START_STOP_REG);

	devpriv->ai_cmd2 = 0;
	switch (cmd->stop_src) {
	case TRIG_COUNT:
		stop_count = cmd->stop_arg - 1;

		if (devpriv->is_611x) {
			/*  have to take 3 stage adc pipeline into account */
			stop_count += num_adc_stages_611x;
		}
		/* stage number of scans */
		ni_stc_writel(dev, stop_count, NISTC_AI_SC_LOADA_REG);

		mode1 |= NISTC_AI_MODE1_START_STOP |
			 NISTC_AI_MODE1_RSVD |
			 NISTC_AI_MODE1_TRIGGER_ONCE;
		ni_stc_writew(dev, mode1, NISTC_AI_MODE1_REG);
		/* load SC (Scan Count) */
		ni_stc_writew(dev, NISTC_AI_CMD1_SC_LOAD, NISTC_AI_CMD1_REG);

		if (stop_count == 0) {
			devpriv->ai_cmd2 |= NISTC_AI_CMD2_END_ON_EOS;
			interrupt_a_enable |= NISTC_INTA_ENA_AI_STOP;
			/*
			 * This is required to get the last sample for
			 * chanlist_len > 1, not sure why.
			 */
			if (cmd->chanlist_len > 1)
				start_stop_select |= NISTC_AI_STOP_POLARITY |
						     NISTC_AI_STOP_EDGE;
		}
		break;
	case TRIG_NONE:
		/* stage number of scans */
		ni_stc_writel(dev, 0, NISTC_AI_SC_LOADA_REG);

		mode1 |= NISTC_AI_MODE1_START_STOP |
			 NISTC_AI_MODE1_RSVD |
			 NISTC_AI_MODE1_CONTINUOUS;
		ni_stc_writew(dev, mode1, NISTC_AI_MODE1_REG);

		/* load SC (Scan Count) */
		ni_stc_writew(dev, NISTC_AI_CMD1_SC_LOAD, NISTC_AI_CMD1_REG);
		break;
	}

	switch (cmd->scan_begin_src) {
	case TRIG_TIMER:
		/*
		 * stop bits for non 611x boards
		 * NISTC_AI_MODE3_SI_TRIG_DELAY=0
		 * NISTC_AI_MODE2_PRE_TRIGGER=0
		 * NISTC_AI_START_STOP_REG:
		 * NISTC_AI_START_POLARITY=0	(?) rising edge
		 * NISTC_AI_START_EDGE=1	edge triggered
		 * NISTC_AI_START_SYNC=1	(?)
		 * NISTC_AI_START_SEL=0		SI_TC
		 * NISTC_AI_STOP_POLARITY=0	rising edge
		 * NISTC_AI_STOP_EDGE=0		level
		 * NISTC_AI_STOP_SYNC=1
		 * NISTC_AI_STOP_SEL=19		external pin (configuration mem)
		 */
		start_stop_select |= NISTC_AI_START_EDGE | NISTC_AI_START_SYNC;
		ni_stc_writew(dev, start_stop_select, NISTC_AI_START_STOP_REG);

		mode2 &= ~NISTC_AI_MODE2_SI_INIT_LOAD_SRC;	/* A */
		mode2 |= NISTC_AI_MODE2_SI_RELOAD_MODE(0);
		/* mode2 |= NISTC_AI_MODE2_SC_RELOAD_MODE; */
		ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);

		/* load SI */
		timer = ni_ns_to_timer(dev, cmd->scan_begin_arg,
				       CMDF_ROUND_NEAREST);
		ni_stc_writel(dev, timer, NISTC_AI_SI_LOADA_REG);
		ni_stc_writew(dev, NISTC_AI_CMD1_SI_LOAD, NISTC_AI_CMD1_REG);
		break;
	case TRIG_EXT:
		if (cmd->scan_begin_arg & CR_EDGE)
			start_stop_select |= NISTC_AI_START_EDGE;
		if (cmd->scan_begin_arg & CR_INVERT)	/* falling edge */
			start_stop_select |= NISTC_AI_START_POLARITY;
		if (cmd->scan_begin_src != cmd->convert_src ||
		    (cmd->scan_begin_arg & ~CR_EDGE) !=
		    (cmd->convert_arg & ~CR_EDGE))
			start_stop_select |= NISTC_AI_START_SYNC;
		start_stop_select |=
		    NISTC_AI_START_SEL(1 + CR_CHAN(cmd->scan_begin_arg));
		ni_stc_writew(dev, start_stop_select, NISTC_AI_START_STOP_REG);
		break;
	}

	switch (cmd->convert_src) {
	case TRIG_TIMER:
	case TRIG_NOW:
		if (cmd->convert_arg == 0 || cmd->convert_src == TRIG_NOW)
			timer = 1;
		else
			timer = ni_ns_to_timer(dev, cmd->convert_arg,
					       CMDF_ROUND_NEAREST);
		/* 0,0 does not work */
		ni_stc_writew(dev, 1, NISTC_AI_SI2_LOADA_REG);
		ni_stc_writew(dev, timer, NISTC_AI_SI2_LOADB_REG);

		mode2 &= ~NISTC_AI_MODE2_SI2_INIT_LOAD_SRC;	/* A */
		mode2 |= NISTC_AI_MODE2_SI2_RELOAD_MODE;	/* alternate */
		ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);

		ni_stc_writew(dev, NISTC_AI_CMD1_SI2_LOAD, NISTC_AI_CMD1_REG);

		mode2 |= NISTC_AI_MODE2_SI2_INIT_LOAD_SRC;	/* B */
		mode2 |= NISTC_AI_MODE2_SI2_RELOAD_MODE;	/* alternate */
		ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);
		break;
	case TRIG_EXT:
		mode1 |= NISTC_AI_MODE1_CONVERT_SRC(1 +
						    CR_CHAN(cmd->convert_arg));
		if ((cmd->convert_arg & CR_INVERT) == 0)
			mode1 |= NISTC_AI_MODE1_CONVERT_POLARITY;
		ni_stc_writew(dev, mode1, NISTC_AI_MODE1_REG);

		mode2 |= NISTC_AI_MODE2_SC_GATE_ENA |
			 NISTC_AI_MODE2_START_STOP_GATE_ENA;
		ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);

		break;
	}

	if (dev->irq) {
		/* interrupt on FIFO, errors, SC_TC */
		interrupt_a_enable |= NISTC_INTA_ENA_AI_ERR |
				      NISTC_INTA_ENA_AI_SC_TC;

#ifndef PCIDMA
		interrupt_a_enable |= NISTC_INTA_ENA_AI_FIFO;
#endif

		if ((cmd->flags & CMDF_WAKE_EOS) ||
		    (devpriv->ai_cmd2 & NISTC_AI_CMD2_END_ON_EOS)) {
			/* wake on end-of-scan */
			devpriv->aimode = AIMODE_SCAN;
		} else {
			devpriv->aimode = AIMODE_HALF_FULL;
		}

		switch (devpriv->aimode) {
		case AIMODE_HALF_FULL:
			/* FIFO interrupts and DMA requests on half-full */
#ifdef PCIDMA
			ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_HF_E,
				      NISTC_AI_MODE3_REG);
#else
			ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_HF,
				      NISTC_AI_MODE3_REG);
#endif
			break;
		case AIMODE_SAMPLE:
			/*generate FIFO interrupts on non-empty */
			ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_NE,
				      NISTC_AI_MODE3_REG);
			break;
		case AIMODE_SCAN:
#ifdef PCIDMA
			ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_NE,
				      NISTC_AI_MODE3_REG);
#else
			ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_HF,
				      NISTC_AI_MODE3_REG);
#endif
			interrupt_a_enable |= NISTC_INTA_ENA_AI_STOP;
			break;
		default:
			break;
		}

		/* clear interrupts */
		ni_stc_writew(dev, NISTC_INTA_ACK_AI_ALL, NISTC_INTA_ACK_REG);

		ni_set_bits(dev, NISTC_INTA_ENA_REG, interrupt_a_enable, 1);
	} else {
		/* interrupt on nothing */
		ni_set_bits(dev, NISTC_INTA_ENA_REG, ~0, 0);

		/* XXX start polling if necessary */
	}

	/* end configuration */
	ni_stc_writew(dev, NISTC_RESET_AI_CFG_END, NISTC_RESET_REG);

	switch (cmd->scan_begin_src) {
	case TRIG_TIMER:
		ni_stc_writew(dev, NISTC_AI_CMD1_SI2_ARM |
				   NISTC_AI_CMD1_SI_ARM |
				   NISTC_AI_CMD1_DIV_ARM |
				   NISTC_AI_CMD1_SC_ARM,
			      NISTC_AI_CMD1_REG);
		break;
	case TRIG_EXT:
		ni_stc_writew(dev, NISTC_AI_CMD1_SI2_ARM |
				   NISTC_AI_CMD1_SI_ARM |	/* XXX ? */
				   NISTC_AI_CMD1_DIV_ARM |
				   NISTC_AI_CMD1_SC_ARM,
			      NISTC_AI_CMD1_REG);
		break;
	}

#ifdef PCIDMA
	{
		int retval = ni_ai_setup_MITE_dma(dev);

		if (retval)
			return retval;
	}
#endif

	if (cmd->start_src == TRIG_NOW) {
		ni_stc_writew(dev, NISTC_AI_CMD2_START1_PULSE |
				   devpriv->ai_cmd2,
			      NISTC_AI_CMD2_REG);
		s->async->inttrig = NULL;
	} else if (cmd->start_src == TRIG_EXT) {
		s->async->inttrig = NULL;
	} else {	/* TRIG_INT */
		s->async->inttrig = ni_ai_inttrig;
	}

	return 0;
}

static int ni_ai_insn_config(struct comedi_device *dev,
			     struct comedi_subdevice *s,
			     struct comedi_insn *insn, unsigned int *data)
{
	struct ni_private *devpriv = dev->private;

	if (insn->n < 1)
		return -EINVAL;

	switch (data[0]) {
	case INSN_CONFIG_ALT_SOURCE:
		if (devpriv->is_m_series) {
			if (data[1] & ~NI_M_CFG_BYPASS_AI_CAL_MASK)
				return -EINVAL;
			devpriv->ai_calib_source = data[1];
		} else if (devpriv->is_6143) {
			unsigned int calib_source;

			calib_source = data[1] & 0xf;

			devpriv->ai_calib_source = calib_source;
			ni_writew(dev, calib_source, NI6143_CALIB_CHAN_REG);
		} else {
			unsigned int calib_source;
			unsigned int calib_source_adjust;

			calib_source = data[1] & 0xf;
			calib_source_adjust = (data[1] >> 4) & 0xff;

			if (calib_source >= 8)
				return -EINVAL;
			devpriv->ai_calib_source = calib_source;
			if (devpriv->is_611x) {
				ni_writeb(dev, calib_source_adjust,
					  NI611X_CAL_GAIN_SEL_REG);
			}
		}
		return 2;
	default:
		break;
	}

	return -EINVAL;
}

static void ni_ao_munge(struct comedi_device *dev, struct comedi_subdevice *s,
			void *data, unsigned int num_bytes,
			unsigned int chan_index)
{
	struct comedi_cmd *cmd = &s->async->cmd;
	unsigned int nsamples = comedi_bytes_to_samples(s, num_bytes);
	unsigned short *array = data;
	unsigned int i;
#ifdef PCIDMA
	__le16 buf, *barray = data;
#endif

	for (i = 0; i < nsamples; i++) {
		unsigned int range = CR_RANGE(cmd->chanlist[chan_index]);
		unsigned short val = array[i];

		/*
		 * Munge data from unsigned to two's complement for
		 * bipolar ranges.
		 */
		if (comedi_range_is_bipolar(s, range))
			val = comedi_offset_munge(s, val);
#ifdef PCIDMA
		buf = cpu_to_le16(val);
		barray[i] = buf;
#else
		array[i] = val;
#endif
		chan_index++;
		chan_index %= cmd->chanlist_len;
	}
}

static int ni_m_series_ao_config_chanlist(struct comedi_device *dev,
					  struct comedi_subdevice *s,
					  unsigned int chanspec[],
					  unsigned int n_chans, int timed)
{
	struct ni_private *devpriv = dev->private;
	unsigned int range;
	unsigned int chan;
	unsigned int conf;
	int i;
	int invert = 0;

	if (timed) {
		for (i = 0; i < s->n_chan; ++i) {
			devpriv->ao_conf[i] &= ~NI_M_AO_CFG_BANK_UPDATE_TIMED;
			ni_writeb(dev, devpriv->ao_conf[i],
				  NI_M_AO_CFG_BANK_REG(i));
			ni_writeb(dev, 0xf, NI_M_AO_WAVEFORM_ORDER_REG(i));
		}
	}
	for (i = 0; i < n_chans; i++) {
		const struct comedi_krange *krange;

		chan = CR_CHAN(chanspec[i]);
		range = CR_RANGE(chanspec[i]);
		krange = s->range_table->range + range;
		invert = 0;
		conf = 0;
		switch (krange->max - krange->min) {
		case 20000000:
			conf |= NI_M_AO_CFG_BANK_REF_INT_10V;
			ni_writeb(dev, 0, NI_M_AO_REF_ATTENUATION_REG(chan));
			break;
		case 10000000:
			conf |= NI_M_AO_CFG_BANK_REF_INT_5V;
			ni_writeb(dev, 0, NI_M_AO_REF_ATTENUATION_REG(chan));
			break;
		case 4000000:
			conf |= NI_M_AO_CFG_BANK_REF_INT_10V;
			ni_writeb(dev, NI_M_AO_REF_ATTENUATION_X5,
				  NI_M_AO_REF_ATTENUATION_REG(chan));
			break;
		case 2000000:
			conf |= NI_M_AO_CFG_BANK_REF_INT_5V;
			ni_writeb(dev, NI_M_AO_REF_ATTENUATION_X5,
				  NI_M_AO_REF_ATTENUATION_REG(chan));
			break;
		default:
			dev_err(dev->class_dev,
				"bug! unhandled ao reference voltage\n");
			break;
		}
		switch (krange->max + krange->min) {
		case 0:
			conf |= NI_M_AO_CFG_BANK_OFFSET_0V;
			break;
		case 10000000:
			conf |= NI_M_AO_CFG_BANK_OFFSET_5V;
			break;
		default:
			dev_err(dev->class_dev,
				"bug! unhandled ao offset voltage\n");
			break;
		}
		if (timed)
			conf |= NI_M_AO_CFG_BANK_UPDATE_TIMED;
		ni_writeb(dev, conf, NI_M_AO_CFG_BANK_REG(chan));
		devpriv->ao_conf[chan] = conf;
		ni_writeb(dev, i, NI_M_AO_WAVEFORM_ORDER_REG(chan));
	}
	return invert;
}

static int ni_old_ao_config_chanlist(struct comedi_device *dev,
				     struct comedi_subdevice *s,
				     unsigned int chanspec[],
				     unsigned int n_chans)
{
	struct ni_private *devpriv = dev->private;
	unsigned int range;
	unsigned int chan;
	unsigned int conf;
	int i;
	int invert = 0;

	for (i = 0; i < n_chans; i++) {
		chan = CR_CHAN(chanspec[i]);
		range = CR_RANGE(chanspec[i]);
		conf = NI_E_AO_DACSEL(chan);

		if (comedi_range_is_bipolar(s, range)) {
			conf |= NI_E_AO_CFG_BIP;
			invert = (s->maxdata + 1) >> 1;
		} else {
			invert = 0;
		}
		if (comedi_range_is_external(s, range))
			conf |= NI_E_AO_EXT_REF;

		/* not all boards can deglitch, but this shouldn't hurt */
		if (chanspec[i] & CR_DEGLITCH)
			conf |= NI_E_AO_DEGLITCH;

		/* analog reference */
		/* AREF_OTHER connects AO ground to AI ground, i think */
		if (CR_AREF(chanspec[i]) == AREF_OTHER)
			conf |= NI_E_AO_GROUND_REF;

		ni_writew(dev, conf, NI_E_AO_CFG_REG);
		devpriv->ao_conf[chan] = conf;
	}
	return invert;
}

static int ni_ao_config_chanlist(struct comedi_device *dev,
				 struct comedi_subdevice *s,
				 unsigned int chanspec[], unsigned int n_chans,
				 int timed)
{
	struct ni_private *devpriv = dev->private;

	if (devpriv->is_m_series)
		return ni_m_series_ao_config_chanlist(dev, s, chanspec, n_chans,
						      timed);
	else
		return ni_old_ao_config_chanlist(dev, s, chanspec, n_chans);
}

static int ni_ao_insn_write(struct comedi_device *dev,
			    struct comedi_subdevice *s,
			    struct comedi_insn *insn,
			    unsigned int *data)
{
	struct ni_private *devpriv = dev->private;
	unsigned int chan = CR_CHAN(insn->chanspec);
	unsigned int range = CR_RANGE(insn->chanspec);
	int reg;
	int i;

	if (devpriv->is_6xxx) {
		ni_ao_win_outw(dev, 1 << chan, NI671X_AO_IMMEDIATE_REG);

		reg = NI671X_DAC_DIRECT_DATA_REG(chan);
	} else if (devpriv->is_m_series) {
		reg = NI_M_DAC_DIRECT_DATA_REG(chan);
	} else {
		reg = NI_E_DAC_DIRECT_DATA_REG(chan);
	}

	ni_ao_config_chanlist(dev, s, &insn->chanspec, 1, 0);

	for (i = 0; i < insn->n; i++) {
		unsigned int val = data[i];

		s->readback[chan] = val;

		if (devpriv->is_6xxx) {
			/*
			 * 6xxx boards have bipolar outputs, munge the
			 * unsigned comedi values to 2's complement
			 */
			val = comedi_offset_munge(s, val);

			ni_ao_win_outw(dev, val, reg);
		} else if (devpriv->is_m_series) {
			/*
			 * M-series boards use offset binary values for
			 * bipolar and uinpolar outputs
			 */
			ni_writew(dev, val, reg);
		} else {
			/*
			 * Non-M series boards need two's complement values
			 * for bipolar ranges.
			 */
			if (comedi_range_is_bipolar(s, range))
				val = comedi_offset_munge(s, val);

			ni_writew(dev, val, reg);
		}
	}

	return insn->n;
}

static int ni_ao_insn_config(struct comedi_device *dev,
			     struct comedi_subdevice *s,
			     struct comedi_insn *insn, unsigned int *data)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;
	unsigned int nbytes;

	switch (data[0]) {
	case INSN_CONFIG_GET_HARDWARE_BUFFER_SIZE:
		switch (data[1]) {
		case COMEDI_OUTPUT:
			nbytes = comedi_samples_to_bytes(s,
							 board->ao_fifo_depth);
			data[2] = 1 + nbytes;
			if (devpriv->mite)
				data[2] += devpriv->mite->fifo_size;
			break;
		case COMEDI_INPUT:
			data[2] = 0;
			break;
		default:
			return -EINVAL;
		}
		return 0;
	default:
		break;
	}

	return -EINVAL;
}

static int ni_ao_inttrig(struct comedi_device *dev,
			 struct comedi_subdevice *s,
			 unsigned int trig_num)
{
	struct ni_private *devpriv = dev->private;
	struct comedi_cmd *cmd = &s->async->cmd;
	int ret;
	int interrupt_b_bits;
	int i;
	static const int timeout = 1000;

	/*
	 * Require trig_num == cmd->start_arg when cmd->start_src == TRIG_INT.
	 * For backwards compatibility, also allow trig_num == 0 when
	 * cmd->start_src != TRIG_INT (i.e. when cmd->start_src == TRIG_EXT);
	 * in that case, the internal trigger is being used as a pre-trigger
	 * before the external trigger.
	 */
	if (!(trig_num == cmd->start_arg ||
	      (trig_num == 0 && cmd->start_src != TRIG_INT)))
		return -EINVAL;

	/*
	 * Null trig at beginning prevent ao start trigger from executing more
	 * than once per command (and doing things like trying to allocate the
	 * ao dma channel multiple times).
	 */
	s->async->inttrig = NULL;

	ni_set_bits(dev, NISTC_INTB_ENA_REG,
		    NISTC_INTB_ENA_AO_FIFO | NISTC_INTB_ENA_AO_ERR, 0);
	interrupt_b_bits = NISTC_INTB_ENA_AO_ERR;
#ifdef PCIDMA
	ni_stc_writew(dev, 1, NISTC_DAC_FIFO_CLR_REG);
	if (devpriv->is_6xxx)
		ni_ao_win_outl(dev, 0x6, NI611X_AO_FIFO_OFFSET_LOAD_REG);
	ret = ni_ao_setup_MITE_dma(dev);
	if (ret)
		return ret;
	ret = ni_ao_wait_for_dma_load(dev);
	if (ret < 0)
		return ret;
#else
	ret = ni_ao_prep_fifo(dev, s);
	if (ret == 0)
		return -EPIPE;

	interrupt_b_bits |= NISTC_INTB_ENA_AO_FIFO;
#endif

	ni_stc_writew(dev, devpriv->ao_mode3 | NISTC_AO_MODE3_NOT_AN_UPDATE,
		      NISTC_AO_MODE3_REG);
	ni_stc_writew(dev, devpriv->ao_mode3, NISTC_AO_MODE3_REG);
	/* wait for DACs to be loaded */
	for (i = 0; i < timeout; i++) {
		udelay(1);
		if ((ni_stc_readw(dev, NISTC_STATUS2_REG) &
		     NISTC_STATUS2_AO_TMRDACWRS_IN_PROGRESS) == 0)
			break;
	}
	if (i == timeout) {
		dev_err(dev->class_dev,
			"timed out waiting for AO_TMRDACWRs_In_Progress_St to clear\n");
		return -EIO;
	}
	/*
	 * stc manual says we are need to clear error interrupt after
	 * AO_TMRDACWRs_In_Progress_St clears
	 */
	ni_stc_writew(dev, NISTC_INTB_ACK_AO_ERR, NISTC_INTB_ACK_REG);

	ni_set_bits(dev, NISTC_INTB_ENA_REG, interrupt_b_bits, 1);

	ni_stc_writew(dev, NISTC_AO_CMD1_UI_ARM |
			   NISTC_AO_CMD1_UC_ARM |
			   NISTC_AO_CMD1_BC_ARM |
			   devpriv->ao_cmd1,
		      NISTC_AO_CMD1_REG);

	ni_stc_writew(dev, NISTC_AO_CMD2_START1_PULSE | devpriv->ao_cmd2,
		      NISTC_AO_CMD2_REG);

	return 0;
}

/*
 * begin ni_ao_cmd.
 * Organized similar to NI-STC and MHDDK examples.
 * ni_ao_cmd is broken out into configuration sub-routines for clarity.
 */

static void ni_ao_cmd_personalize(struct comedi_device *dev,
				  const struct comedi_cmd *cmd)
{
	const struct ni_board_struct *board = dev->board_ptr;
	unsigned int bits;

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);

	bits =
	  /* fast CPU interface--only eseries */
	  /* ((slow CPU interface) ? 0 : AO_Fast_CPU) | */
	  NISTC_AO_PERSONAL_BC_SRC_SEL  |
	  0 /* (use_original_pulse ? 0 : NISTC_AO_PERSONAL_UPDATE_TIMEBASE) */ |
	  /*
	   * FIXME:  start setting following bit when appropriate.  Need to
	   * determine whether board is E4 or E1.
	   * FROM MHHDK:
	   * if board is E4 or E1
	   *   Set bit "NISTC_AO_PERSONAL_UPDATE_PW" to 0
	   * else
	   *   set it to 1
	   */
	  NISTC_AO_PERSONAL_UPDATE_PW   |
	  /* FIXME:  when should we set following bit to zero? */
	  NISTC_AO_PERSONAL_TMRDACWR_PW |
	  (board->ao_fifo_depth ?
	    NISTC_AO_PERSONAL_FIFO_ENA : NISTC_AO_PERSONAL_DMA_PIO_CTRL)
	  ;
#if 0
	/*
	 * FIXME:
	 * add something like ".has_individual_dacs = 0" to ni_board_struct
	 * since, as F Hess pointed out, not all in m series have singles.  not
	 * sure if e-series all have duals...
	 */

	/*
	 * F Hess: windows driver does not set NISTC_AO_PERSONAL_NUM_DAC bit for
	 * 6281, verified with bus analyzer.
	 */
	if (devpriv->is_m_series)
		bits |= NISTC_AO_PERSONAL_NUM_DAC;
#endif
	ni_stc_writew(dev, bits, NISTC_AO_PERSONAL_REG);

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
}

static void ni_ao_cmd_set_trigger(struct comedi_device *dev,
				  const struct comedi_cmd *cmd)
{
	struct ni_private *devpriv = dev->private;
	unsigned int trigsel;

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);

	/* sync */
	if (cmd->stop_src == TRIG_NONE) {
		devpriv->ao_mode1 |= NISTC_AO_MODE1_CONTINUOUS;
		devpriv->ao_mode1 &= ~NISTC_AO_MODE1_TRIGGER_ONCE;
	} else {
		devpriv->ao_mode1 &= ~NISTC_AO_MODE1_CONTINUOUS;
		devpriv->ao_mode1 |= NISTC_AO_MODE1_TRIGGER_ONCE;
	}
	ni_stc_writew(dev, devpriv->ao_mode1, NISTC_AO_MODE1_REG);

	if (cmd->start_src == TRIG_INT) {
		trigsel = NISTC_AO_TRIG_START1_EDGE |
			  NISTC_AO_TRIG_START1_SYNC;
	} else { /* TRIG_EXT */
		trigsel = NISTC_AO_TRIG_START1_SEL(CR_CHAN(cmd->start_arg) + 1);
		/* 0=active high, 1=active low. see daq-stc 3-24 (p186) */
		if (cmd->start_arg & CR_INVERT)
			trigsel |= NISTC_AO_TRIG_START1_POLARITY;
		/* 0=edge detection disabled, 1=enabled */
		if (cmd->start_arg & CR_EDGE)
			trigsel |= NISTC_AO_TRIG_START1_EDGE;
	}
	ni_stc_writew(dev, trigsel, NISTC_AO_TRIG_SEL_REG);

	/* AO_Delayed_START1 = 0, we do not support delayed start...yet */

	/* sync */
	/* select DA_START1 as PFI6/AO_START1 when configured as an output */
	devpriv->ao_mode3 &= ~NISTC_AO_MODE3_TRIG_LEN;
	ni_stc_writew(dev, devpriv->ao_mode3, NISTC_AO_MODE3_REG);

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
}

static void ni_ao_cmd_set_counters(struct comedi_device *dev,
				   const struct comedi_cmd *cmd)
{
	struct ni_private *devpriv = dev->private;
	/* Not supporting 'waveform staging' or 'local buffer with pauses' */

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);
	/*
	 * This relies on ao_mode1/(Trigger_Once | Continuous) being set in
	 * set_trigger above.  It is unclear whether we really need to re-write
	 * this register with these values.  The mhddk examples for e-series
	 * show writing this in both places, but the examples for m-series show
	 * a single write in the set_counters function (here).
	 */
	ni_stc_writew(dev, devpriv->ao_mode1, NISTC_AO_MODE1_REG);

	/* sync (upload number of buffer iterations -1) */
	/* indicate that we want to use BC_Load_A_Register as the source */
	devpriv->ao_mode2 &= ~NISTC_AO_MODE2_BC_INIT_LOAD_SRC;
	ni_stc_writew(dev, devpriv->ao_mode2, NISTC_AO_MODE2_REG);

	/*
	 * if the BC_TC interrupt is still issued in spite of UC, BC, UI
	 * ignoring BC_TC, then we will need to find a way to ignore that
	 * interrupt in continuous mode.
	 */
	ni_stc_writel(dev, 0, NISTC_AO_BC_LOADA_REG); /* iter once */

	/* sync (issue command to load number of buffer iterations -1) */
	ni_stc_writew(dev, NISTC_AO_CMD1_BC_LOAD, NISTC_AO_CMD1_REG);

	/* sync (upload number of updates in buffer) */
	/* indicate that we want to use UC_Load_A_Register as the source */
	devpriv->ao_mode2 &= ~NISTC_AO_MODE2_UC_INIT_LOAD_SRC;
	ni_stc_writew(dev, devpriv->ao_mode2, NISTC_AO_MODE2_REG);

	/*
	 * if a user specifies '0', this automatically assumes the entire 24bit
	 * address space is available for the (multiple iterations of single
	 * buffer) MISB.  Otherwise, stop_arg specifies the MISB length that
	 * will be used, regardless of whether we are in continuous mode or not.
	 * In continuous mode, the output will just iterate indefinitely over
	 * the MISB.
	 */
	{
		unsigned int stop_arg = cmd->stop_arg > 0 ?
			(cmd->stop_arg & 0xffffff) : 0xffffff;

		if (devpriv->is_m_series) {
			/*
			 * this is how the NI example code does it for m-series
			 * boards, verified correct with 6259
			 */
			ni_stc_writel(dev, stop_arg - 1, NISTC_AO_UC_LOADA_REG);

			/* sync (issue cmd to load number of updates in MISB) */
			ni_stc_writew(dev, NISTC_AO_CMD1_UC_LOAD,
				      NISTC_AO_CMD1_REG);
		} else {
			ni_stc_writel(dev, stop_arg, NISTC_AO_UC_LOADA_REG);

			/* sync (issue cmd to load number of updates in MISB) */
			ni_stc_writew(dev, NISTC_AO_CMD1_UC_LOAD,
				      NISTC_AO_CMD1_REG);

			/*
			 * sync (upload number of updates-1 in MISB)
			 * --eseries only?
			 */
			ni_stc_writel(dev, stop_arg - 1, NISTC_AO_UC_LOADA_REG);
		}
	}

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
}

static void ni_ao_cmd_set_update(struct comedi_device *dev,
				 const struct comedi_cmd *cmd)
{
	struct ni_private *devpriv = dev->private;

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);

	/*
	 * zero out these bit fields to be set below. Does an ao-reset do this
	 * automatically?
	 */
	devpriv->ao_mode1 &= ~(
	  NISTC_AO_MODE1_UI_SRC_MASK         |
	  NISTC_AO_MODE1_UI_SRC_POLARITY     |
	  NISTC_AO_MODE1_UPDATE_SRC_MASK     |
	  NISTC_AO_MODE1_UPDATE_SRC_POLARITY
	);

	if (cmd->scan_begin_src == TRIG_TIMER) {
		unsigned int trigvar;

		devpriv->ao_cmd2  &= ~NISTC_AO_CMD2_BC_GATE_ENA;

		/*
		 * NOTE: there are several other ways of configuring internal
		 * updates, but we'll only support one for now:  using
		 * AO_IN_TIMEBASE, w/o waveform staging, w/o a delay between
		 * START1 and first update, and also w/o local buffer mode w/
		 * pauses.
		 */

		/*
		 * This is already done above:
		 * devpriv->ao_mode1 &= ~(
		 *   // set UPDATE_Source to UI_TC:
		 *   NISTC_AO_MODE1_UPDATE_SRC_MASK |
		 *   // set UPDATE_Source_Polarity to rising (required?)
		 *   NISTC_AO_MODE1_UPDATE_SRC_POLARITY |
		 *   // set UI_Source to AO_IN_TIMEBASE1:
		 *   NISTC_AO_MODE1_UI_SRC_MASK     |
		 *   // set UI_Source_Polarity to rising (required?)
		 *   NISTC_AO_MODE1_UI_SRC_POLARITY
		 * );
		 */

		/*
		 * TODO:  use ao_ui_clock_source to allow all possible signals
		 * to be routed to UI_Source_Select.  See tSTC.h for
		 * eseries/ni67xx and tMSeries.h for mseries.
		 */

		trigvar = ni_ns_to_timer(dev, cmd->scan_begin_arg,
					 CMDF_ROUND_NEAREST);

		/*
		 * Wait N TB3 ticks after the start trigger before
		 * clocking (N must be >=2).
		 */
		/* following line: 2-1 per STC */
		ni_stc_writel(dev, 1, NISTC_AO_UI_LOADA_REG);
		ni_stc_writew(dev, NISTC_AO_CMD1_UI_LOAD, NISTC_AO_CMD1_REG);
		ni_stc_writel(dev, trigvar, NISTC_AO_UI_LOADA_REG);
	} else { /* TRIG_EXT */
		/* FIXME:  assert scan_begin_arg != 0, ret failure otherwise */
		devpriv->ao_cmd2  |= NISTC_AO_CMD2_BC_GATE_ENA;
		devpriv->ao_mode1 |= NISTC_AO_MODE1_UPDATE_SRC(
					CR_CHAN(cmd->scan_begin_arg));
		if (cmd->scan_begin_arg & CR_INVERT)
			devpriv->ao_mode1 |= NISTC_AO_MODE1_UPDATE_SRC_POLARITY;
	}

	ni_stc_writew(dev, devpriv->ao_cmd2, NISTC_AO_CMD2_REG);
	ni_stc_writew(dev, devpriv->ao_mode1, NISTC_AO_MODE1_REG);
	devpriv->ao_mode2 &= ~(NISTC_AO_MODE2_UI_RELOAD_MODE(3) |
			       NISTC_AO_MODE2_UI_INIT_LOAD_SRC);
	ni_stc_writew(dev, devpriv->ao_mode2, NISTC_AO_MODE2_REG);

	/* Configure DAQ-STC for Timed update mode */
	devpriv->ao_cmd1 |= NISTC_AO_CMD1_DAC1_UPDATE_MODE |
			    NISTC_AO_CMD1_DAC0_UPDATE_MODE;
	/* We are not using UPDATE2-->don't have to set DACx_Source_Select */
	ni_stc_writew(dev, devpriv->ao_cmd1, NISTC_AO_CMD1_REG);

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
}

static void ni_ao_cmd_set_channels(struct comedi_device *dev,
				   struct comedi_subdevice *s)
{
	struct ni_private *devpriv = dev->private;
	const struct comedi_cmd *cmd = &s->async->cmd;
	unsigned int bits = 0;

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);

	if (devpriv->is_6xxx) {
		unsigned int i;

		bits = 0;
		for (i = 0; i < cmd->chanlist_len; ++i) {
			int chan = CR_CHAN(cmd->chanlist[i]);

			bits |= 1 << chan;
			ni_ao_win_outw(dev, chan, NI611X_AO_WAVEFORM_GEN_REG);
		}
		ni_ao_win_outw(dev, bits, NI611X_AO_TIMED_REG);
	}

	ni_ao_config_chanlist(dev, s, cmd->chanlist, cmd->chanlist_len, 1);

	if (cmd->scan_end_arg > 1) {
		devpriv->ao_mode1 |= NISTC_AO_MODE1_MULTI_CHAN;
		bits = NISTC_AO_OUT_CTRL_CHANS(cmd->scan_end_arg - 1)
				 | NISTC_AO_OUT_CTRL_UPDATE_SEL_HIGHZ;

	} else {
		devpriv->ao_mode1 &= ~NISTC_AO_MODE1_MULTI_CHAN;
		bits = NISTC_AO_OUT_CTRL_UPDATE_SEL_HIGHZ;
		if (devpriv->is_m_series | devpriv->is_6xxx)
			bits |= NISTC_AO_OUT_CTRL_CHANS(0);
		else
			bits |= NISTC_AO_OUT_CTRL_CHANS(
					CR_CHAN(cmd->chanlist[0]));
	}

	ni_stc_writew(dev, devpriv->ao_mode1, NISTC_AO_MODE1_REG);
	ni_stc_writew(dev, bits,              NISTC_AO_OUT_CTRL_REG);

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
}

static void ni_ao_cmd_set_stop_conditions(struct comedi_device *dev,
					  const struct comedi_cmd *cmd)
{
	struct ni_private *devpriv = dev->private;

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);

	devpriv->ao_mode3 |= NISTC_AO_MODE3_STOP_ON_OVERRUN_ERR;
	ni_stc_writew(dev, devpriv->ao_mode3, NISTC_AO_MODE3_REG);

	/*
	 * Since we are not supporting waveform staging, we ignore these errors:
	 * NISTC_AO_MODE3_STOP_ON_BC_TC_ERR,
	 * NISTC_AO_MODE3_STOP_ON_BC_TC_TRIG_ERR
	 */

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
}

static void ni_ao_cmd_set_fifo_mode(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);

	devpriv->ao_mode2 &= ~NISTC_AO_MODE2_FIFO_MODE_MASK;
#ifdef PCIDMA
	devpriv->ao_mode2 |= NISTC_AO_MODE2_FIFO_MODE_HF_F;
#else
	devpriv->ao_mode2 |= NISTC_AO_MODE2_FIFO_MODE_HF;
#endif
	/* NOTE:  this is where use_onboard_memory=True would be implemented */
	devpriv->ao_mode2 &= ~NISTC_AO_MODE2_FIFO_REXMIT_ENA;
	ni_stc_writew(dev, devpriv->ao_mode2, NISTC_AO_MODE2_REG);

	/* enable sending of ao fifo requests (dma request) */
	ni_stc_writew(dev, NISTC_AO_START_AOFREQ_ENA, NISTC_AO_START_SEL_REG);

	ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);

	/* we are not supporting boards with virtual fifos */
}

static void ni_ao_cmd_set_interrupts(struct comedi_device *dev,
				     struct comedi_subdevice *s)
{
	if (s->async->cmd.stop_src == TRIG_COUNT)
		ni_set_bits(dev, NISTC_INTB_ENA_REG,
			    NISTC_INTB_ENA_AO_BC_TC, 1);

	s->async->inttrig = ni_ao_inttrig;
}

static int ni_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
	struct ni_private *devpriv = dev->private;
	const struct comedi_cmd *cmd = &s->async->cmd;

	if (dev->irq == 0) {
		dev_err(dev->class_dev, "cannot run command without an irq");
		return -EIO;
	}

	/* ni_ao_reset should have already been done */
	ni_ao_cmd_personalize(dev, cmd);
	/* clearing fifo and preload happens elsewhere */

	ni_ao_cmd_set_trigger(dev, cmd);
	ni_ao_cmd_set_counters(dev, cmd);
	ni_ao_cmd_set_update(dev, cmd);
	ni_ao_cmd_set_channels(dev, s);
	ni_ao_cmd_set_stop_conditions(dev, cmd);
	ni_ao_cmd_set_fifo_mode(dev);
	ni_cmd_set_mite_transfer(devpriv->ao_mite_ring, s, cmd, 0x00ffffff);
	ni_ao_cmd_set_interrupts(dev, s);

	/*
	 * arm(ing) and star(ting) happen in ni_ao_inttrig, which _must_ be
	 * called for ao commands since 1) TRIG_NOW is not supported and 2) DMA
	 * must be setup and initially written to before arm/start happen.
	 */
	return 0;
}

/* end ni_ao_cmd */

static int ni_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
			 struct comedi_cmd *cmd)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;
	int err = 0;
	unsigned int tmp;

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

	err |= comedi_check_trigger_src(&cmd->start_src, TRIG_INT | TRIG_EXT);
	err |= comedi_check_trigger_src(&cmd->scan_begin_src,
					TRIG_TIMER | TRIG_EXT);
	err |= comedi_check_trigger_src(&cmd->convert_src, TRIG_NOW);
	err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
	err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);

	if (err)
		return 1;

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

	err |= comedi_check_trigger_is_unique(cmd->start_src);
	err |= comedi_check_trigger_is_unique(cmd->scan_begin_src);
	err |= comedi_check_trigger_is_unique(cmd->stop_src);

	/* Step 2b : and mutually compatible */

	if (err)
		return 2;

	/* Step 3: check if arguments are trivially valid */

	switch (cmd->start_src) {
	case TRIG_INT:
		err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0);
		break;
	case TRIG_EXT:
		tmp = CR_CHAN(cmd->start_arg);

		if (tmp > 18)
			tmp = 18;
		tmp |= (cmd->start_arg & (CR_INVERT | CR_EDGE));
		err |= comedi_check_trigger_arg_is(&cmd->start_arg, tmp);
		break;
	}

	if (cmd->scan_begin_src == TRIG_TIMER) {
		err |= comedi_check_trigger_arg_min(&cmd->scan_begin_arg,
						    board->ao_speed);
		err |= comedi_check_trigger_arg_max(&cmd->scan_begin_arg,
						    devpriv->clock_ns *
						    0xffffff);
	}

	err |= comedi_check_trigger_arg_is(&cmd->convert_arg, 0);
	err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg,
					   cmd->chanlist_len);
	err |= comedi_check_trigger_arg_max(&cmd->stop_arg, 0x00ffffff);

	if (err)
		return 3;

	/* step 4: fix up any arguments */
	if (cmd->scan_begin_src == TRIG_TIMER) {
		tmp = cmd->scan_begin_arg;
		cmd->scan_begin_arg =
		    ni_timer_to_ns(dev, ni_ns_to_timer(dev,
						       cmd->scan_begin_arg,
						       cmd->flags));
		if (tmp != cmd->scan_begin_arg)
			err++;
	}
	if (err)
		return 4;

	return 0;
}

static int ni_ao_reset(struct comedi_device *dev, struct comedi_subdevice *s)
{
	/* See 3.6.1.2 "Resetting", of DAQ-STC Technical Reference Manual */

	/*
	 * In the following, the "--sync" comments are meant to denote
	 * asynchronous boundaries for setting the registers as described in the
	 * DAQ-STC mostly in the order also described in the DAQ-STC.
	 */

	struct ni_private *devpriv = dev->private;

	ni_release_ao_mite_channel(dev);

	/* --sync (reset AO) */
	if (devpriv->is_m_series)
		/* following example in mhddk for m-series */
		ni_stc_writew(dev, NISTC_RESET_AO, NISTC_RESET_REG);

	/*--sync (start config) */
	ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);

	/*--sync (Disarm) */
	ni_stc_writew(dev, NISTC_AO_CMD1_DISARM, NISTC_AO_CMD1_REG);

	/*
	 * --sync
	 * (clear bunch of registers--mseries mhddk examples do not include
	 * this)
	 */
	devpriv->ao_cmd1  = 0;
	devpriv->ao_cmd2  = 0;
	devpriv->ao_mode1 = 0;
	devpriv->ao_mode2 = 0;
	if (devpriv->is_m_series)
		devpriv->ao_mode3 = NISTC_AO_MODE3_LAST_GATE_DISABLE;
	else
		devpriv->ao_mode3 = 0;

	ni_stc_writew(dev, 0, NISTC_AO_PERSONAL_REG);
	ni_stc_writew(dev, 0, NISTC_AO_CMD1_REG);
	ni_stc_writew(dev, 0, NISTC_AO_CMD2_REG);
	ni_stc_writew(dev, 0, NISTC_AO_MODE1_REG);
	ni_stc_writew(dev, 0, NISTC_AO_MODE2_REG);
	ni_stc_writew(dev, 0, NISTC_AO_OUT_CTRL_REG);
	ni_stc_writew(dev, devpriv->ao_mode3, NISTC_AO_MODE3_REG);
	ni_stc_writew(dev, 0, NISTC_AO_START_SEL_REG);
	ni_stc_writew(dev, 0, NISTC_AO_TRIG_SEL_REG);

	/*--sync (disable interrupts) */
	ni_set_bits(dev, NISTC_INTB_ENA_REG, ~0, 0);

	/*--sync (ack) */
	ni_stc_writew(dev, NISTC_AO_PERSONAL_BC_SRC_SEL, NISTC_AO_PERSONAL_REG);
	ni_stc_writew(dev, NISTC_INTB_ACK_AO_ALL, NISTC_INTB_ACK_REG);

	/*--not in DAQ-STC.  which doc? */
	if (devpriv->is_6xxx) {
		ni_ao_win_outw(dev, (1u << s->n_chan) - 1u,
			       NI671X_AO_IMMEDIATE_REG);
		ni_ao_win_outw(dev, NI611X_AO_MISC_CLEAR_WG,
			       NI611X_AO_MISC_REG);
	}
	ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
	/*--end */

	return 0;
}

/* digital io */

static int ni_dio_insn_config(struct comedi_device *dev,
			      struct comedi_subdevice *s,
			      struct comedi_insn *insn,
			      unsigned int *data)
{
	struct ni_private *devpriv = dev->private;
	int ret;

	ret = comedi_dio_insn_config(dev, s, insn, data, 0);
	if (ret)
		return ret;

	devpriv->dio_control &= ~NISTC_DIO_CTRL_DIR_MASK;
	devpriv->dio_control |= NISTC_DIO_CTRL_DIR(s->io_bits);
	ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);

	return insn->n;
}

static int ni_dio_insn_bits(struct comedi_device *dev,
			    struct comedi_subdevice *s,
			    struct comedi_insn *insn,
			    unsigned int *data)
{
	struct ni_private *devpriv = dev->private;

	/* Make sure we're not using the serial part of the dio */
	if ((data[0] & (NISTC_DIO_SDIN | NISTC_DIO_SDOUT)) &&
	    devpriv->serial_interval_ns)
		return -EBUSY;

	if (comedi_dio_update_state(s, data)) {
		devpriv->dio_output &= ~NISTC_DIO_OUT_PARALLEL_MASK;
		devpriv->dio_output |= NISTC_DIO_OUT_PARALLEL(s->state);
		ni_stc_writew(dev, devpriv->dio_output, NISTC_DIO_OUT_REG);
	}

	data[1] = ni_stc_readw(dev, NISTC_DIO_IN_REG);

	return insn->n;
}

#ifdef PCIDMA
static int ni_m_series_dio_insn_config(struct comedi_device *dev,
				       struct comedi_subdevice *s,
				       struct comedi_insn *insn,
				       unsigned int *data)
{
	int ret;

	ret = comedi_dio_insn_config(dev, s, insn, data, 0);
	if (ret)
		return ret;

	ni_writel(dev, s->io_bits, NI_M_DIO_DIR_REG);

	return insn->n;
}

static int ni_m_series_dio_insn_bits(struct comedi_device *dev,
				     struct comedi_subdevice *s,
				     struct comedi_insn *insn,
				     unsigned int *data)
{
	if (comedi_dio_update_state(s, data))
		ni_writel(dev, s->state, NI_M_DIO_REG);

	data[1] = ni_readl(dev, NI_M_DIO_REG);

	return insn->n;
}

static int ni_cdio_check_chanlist(struct comedi_device *dev,
				  struct comedi_subdevice *s,
				  struct comedi_cmd *cmd)
{
	int i;

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

		if (chan != i)
			return -EINVAL;
	}

	return 0;
}

static int ni_cdio_cmdtest(struct comedi_device *dev,
			   struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
	int err = 0;
	int tmp;

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

	err |= comedi_check_trigger_src(&cmd->start_src, TRIG_INT);
	err |= comedi_check_trigger_src(&cmd->scan_begin_src, TRIG_EXT);
	err |= comedi_check_trigger_src(&cmd->convert_src, TRIG_NOW);
	err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
	err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_NONE);

	if (err)
		return 1;

	/* Step 2a : make sure trigger sources are unique */
	/* Step 2b : and mutually compatible */

	/* Step 3: check if arguments are trivially valid */

	err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0);

	tmp = cmd->scan_begin_arg;
	tmp &= CR_PACK_FLAGS(NI_M_CDO_MODE_SAMPLE_SRC_MASK, 0, 0, CR_INVERT);
	if (tmp != cmd->scan_begin_arg)
		err |= -EINVAL;

	err |= comedi_check_trigger_arg_is(&cmd->convert_arg, 0);
	err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg,
					   cmd->chanlist_len);
	err |= comedi_check_trigger_arg_max(&cmd->stop_arg,
					    s->async->prealloc_bufsz /
					    comedi_bytes_per_scan(s));

	if (err)
		return 3;

	/* Step 4: fix up any arguments */

	/* Step 5: check channel list if it exists */

	if (cmd->chanlist && cmd->chanlist_len > 0)
		err |= ni_cdio_check_chanlist(dev, s, cmd);

	if (err)
		return 5;

	return 0;
}

static int ni_cdo_inttrig(struct comedi_device *dev,
			  struct comedi_subdevice *s,
			  unsigned int trig_num)
{
	struct comedi_cmd *cmd = &s->async->cmd;
	const unsigned int timeout = 1000;
	int retval = 0;
	unsigned int i;
	struct ni_private *devpriv = dev->private;
	unsigned long flags;

	if (trig_num != cmd->start_arg)
		return -EINVAL;

	s->async->inttrig = NULL;

	/* read alloc the entire buffer */
	comedi_buf_read_alloc(s, s->async->prealloc_bufsz);

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (devpriv->cdo_mite_chan) {
		mite_prep_dma(devpriv->cdo_mite_chan, 32, 32);
		mite_dma_arm(devpriv->cdo_mite_chan);
	} else {
		dev_err(dev->class_dev, "BUG: no cdo mite channel?\n");
		retval = -EIO;
	}
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
	if (retval < 0)
		return retval;

	/*
	 * XXX not sure what interrupt C group does
	 * wait for dma to fill output fifo
	 * ni_writeb(dev, NI_M_INTC_ENA, NI_M_INTC_ENA_REG);
	 */
	for (i = 0; i < timeout; ++i) {
		if (ni_readl(dev, NI_M_CDIO_STATUS_REG) &
		    NI_M_CDIO_STATUS_CDO_FIFO_FULL)
			break;
		usleep_range(10, 100);
	}
	if (i == timeout) {
		dev_err(dev->class_dev, "dma failed to fill cdo fifo!\n");
		s->cancel(dev, s);
		return -EIO;
	}
	ni_writel(dev, NI_M_CDO_CMD_ARM |
		       NI_M_CDO_CMD_ERR_INT_ENA_SET |
		       NI_M_CDO_CMD_F_E_INT_ENA_SET,
		  NI_M_CDIO_CMD_REG);
	return retval;
}

static int ni_cdio_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
	struct ni_private *devpriv = dev->private;
	const struct comedi_cmd *cmd = &s->async->cmd;
	unsigned int cdo_mode_bits;
	int retval;

	ni_writel(dev, NI_M_CDO_CMD_RESET, NI_M_CDIO_CMD_REG);
	cdo_mode_bits = NI_M_CDO_MODE_FIFO_MODE |
			NI_M_CDO_MODE_HALT_ON_ERROR |
			NI_M_CDO_MODE_SAMPLE_SRC(CR_CHAN(cmd->scan_begin_arg));
	if (cmd->scan_begin_arg & CR_INVERT)
		cdo_mode_bits |= NI_M_CDO_MODE_POLARITY;
	ni_writel(dev, cdo_mode_bits, NI_M_CDO_MODE_REG);
	if (s->io_bits) {
		ni_writel(dev, s->state, NI_M_CDO_FIFO_DATA_REG);
		ni_writel(dev, NI_M_CDO_CMD_SW_UPDATE, NI_M_CDIO_CMD_REG);
		ni_writel(dev, s->io_bits, NI_M_CDO_MASK_ENA_REG);
	} else {
		dev_err(dev->class_dev,
			"attempted to run digital output command with no lines configured as outputs\n");
		return -EIO;
	}
	retval = ni_request_cdo_mite_channel(dev);
	if (retval < 0)
		return retval;

	ni_cmd_set_mite_transfer(devpriv->cdo_mite_ring, s, cmd,
				 s->async->prealloc_bufsz /
				 comedi_bytes_per_scan(s));

	s->async->inttrig = ni_cdo_inttrig;

	return 0;
}

static int ni_cdio_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
	ni_writel(dev, NI_M_CDO_CMD_DISARM |
		       NI_M_CDO_CMD_ERR_INT_ENA_CLR |
		       NI_M_CDO_CMD_F_E_INT_ENA_CLR |
		       NI_M_CDO_CMD_F_REQ_INT_ENA_CLR,
		  NI_M_CDIO_CMD_REG);
	/*
	 * XXX not sure what interrupt C group does
	 * ni_writeb(dev, 0, NI_M_INTC_ENA_REG);
	 */
	ni_writel(dev, 0, NI_M_CDO_MASK_ENA_REG);
	ni_release_cdo_mite_channel(dev);
	return 0;
}

static void handle_cdio_interrupt(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;
	unsigned int cdio_status;
	struct comedi_subdevice *s = &dev->subdevices[NI_DIO_SUBDEV];
	unsigned long flags;

	spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
	if (devpriv->cdo_mite_chan)
		mite_ack_linkc(devpriv->cdo_mite_chan, s, true);
	spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);

	cdio_status = ni_readl(dev, NI_M_CDIO_STATUS_REG);
	if (cdio_status & NI_M_CDIO_STATUS_CDO_ERROR) {
		/* XXX just guessing this is needed and does something useful */
		ni_writel(dev, NI_M_CDO_CMD_ERR_INT_CONFIRM,
			  NI_M_CDIO_CMD_REG);
		s->async->events |= COMEDI_CB_OVERFLOW;
	}
	if (cdio_status & NI_M_CDIO_STATUS_CDO_FIFO_EMPTY) {
		ni_writel(dev, NI_M_CDO_CMD_F_E_INT_ENA_CLR,
			  NI_M_CDIO_CMD_REG);
		/* s->async->events |= COMEDI_CB_EOA; */
	}
	comedi_handle_events(dev, s);
}
#endif /*  PCIDMA */

static int ni_serial_hw_readwrite8(struct comedi_device *dev,
				   struct comedi_subdevice *s,
				   unsigned char data_out,
				   unsigned char *data_in)
{
	struct ni_private *devpriv = dev->private;
	unsigned int status1;
	int err = 0, count = 20;

	devpriv->dio_output &= ~NISTC_DIO_OUT_SERIAL_MASK;
	devpriv->dio_output |= NISTC_DIO_OUT_SERIAL(data_out);
	ni_stc_writew(dev, devpriv->dio_output, NISTC_DIO_OUT_REG);

	status1 = ni_stc_readw(dev, NISTC_STATUS1_REG);
	if (status1 & NISTC_STATUS1_SERIO_IN_PROG) {
		err = -EBUSY;
		goto error;
	}

	devpriv->dio_control |= NISTC_DIO_CTRL_HW_SER_START;
	ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
	devpriv->dio_control &= ~NISTC_DIO_CTRL_HW_SER_START;

	/* Wait until STC says we're done, but don't loop infinitely. */
	while ((status1 = ni_stc_readw(dev, NISTC_STATUS1_REG)) &
	       NISTC_STATUS1_SERIO_IN_PROG) {
		/* Delay one bit per loop */
		udelay((devpriv->serial_interval_ns + 999) / 1000);
		if (--count < 0) {
			dev_err(dev->class_dev,
				"SPI serial I/O didn't finish in time!\n");
			err = -ETIME;
			goto error;
		}
	}

	/*
	 * Delay for last bit. This delay is absolutely necessary, because
	 * NISTC_STATUS1_SERIO_IN_PROG goes high one bit too early.
	 */
	udelay((devpriv->serial_interval_ns + 999) / 1000);

	if (data_in)
		*data_in = ni_stc_readw(dev, NISTC_DIO_SERIAL_IN_REG);

error:
	ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);

	return err;
}

static int ni_serial_sw_readwrite8(struct comedi_device *dev,
				   struct comedi_subdevice *s,
				   unsigned char data_out,
				   unsigned char *data_in)
{
	struct ni_private *devpriv = dev->private;
	unsigned char mask, input = 0;

	/* Wait for one bit before transfer */
	udelay((devpriv->serial_interval_ns + 999) / 1000);

	for (mask = 0x80; mask; mask >>= 1) {
		/*
		 * Output current bit; note that we cannot touch s->state
		 * because it is a per-subdevice field, and serial is
		 * a separate subdevice from DIO.
		 */
		devpriv->dio_output &= ~NISTC_DIO_SDOUT;
		if (data_out & mask)
			devpriv->dio_output |= NISTC_DIO_SDOUT;
		ni_stc_writew(dev, devpriv->dio_output, NISTC_DIO_OUT_REG);

		/*
		 * Assert SDCLK (active low, inverted), wait for half of
		 * the delay, deassert SDCLK, and wait for the other half.
		 */
		devpriv->dio_control |= NISTC_DIO_SDCLK;
		ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);

		udelay((devpriv->serial_interval_ns + 999) / 2000);

		devpriv->dio_control &= ~NISTC_DIO_SDCLK;
		ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);

		udelay((devpriv->serial_interval_ns + 999) / 2000);

		/* Input current bit */
		if (ni_stc_readw(dev, NISTC_DIO_IN_REG) & NISTC_DIO_SDIN)
			input |= mask;
	}

	if (data_in)
		*data_in = input;

	return 0;
}

static int ni_serial_insn_config(struct comedi_device *dev,
				 struct comedi_subdevice *s,
				 struct comedi_insn *insn,
				 unsigned int *data)
{
	struct ni_private *devpriv = dev->private;
	unsigned int clk_fout = devpriv->clock_and_fout;
	int err = insn->n;
	unsigned char byte_out, byte_in = 0;

	if (insn->n != 2)
		return -EINVAL;

	switch (data[0]) {
	case INSN_CONFIG_SERIAL_CLOCK:
		devpriv->serial_hw_mode = 1;
		devpriv->dio_control |= NISTC_DIO_CTRL_HW_SER_ENA;

		if (data[1] == SERIAL_DISABLED) {
			devpriv->serial_hw_mode = 0;
			devpriv->dio_control &= ~(NISTC_DIO_CTRL_HW_SER_ENA |
						  NISTC_DIO_SDCLK);
			data[1] = SERIAL_DISABLED;
			devpriv->serial_interval_ns = data[1];
		} else if (data[1] <= SERIAL_600NS) {
			/*
			 * Warning: this clock speed is too fast to reliably
			 * control SCXI.
			 */
			devpriv->dio_control &= ~NISTC_DIO_CTRL_HW_SER_TIMEBASE;
			clk_fout |= NISTC_CLK_FOUT_SLOW_TIMEBASE;
			clk_fout &= ~NISTC_CLK_FOUT_DIO_SER_OUT_DIV2;
			data[1] = SERIAL_600NS;
			devpriv->serial_interval_ns = data[1];
		} else if (data[1] <= SERIAL_1_2US) {
			devpriv->dio_control &= ~NISTC_DIO_CTRL_HW_SER_TIMEBASE;
			clk_fout |= NISTC_CLK_FOUT_SLOW_TIMEBASE |
				    NISTC_CLK_FOUT_DIO_SER_OUT_DIV2;
			data[1] = SERIAL_1_2US;
			devpriv->serial_interval_ns = data[1];
		} else if (data[1] <= SERIAL_10US) {
			devpriv->dio_control |= NISTC_DIO_CTRL_HW_SER_TIMEBASE;
			clk_fout |= NISTC_CLK_FOUT_SLOW_TIMEBASE |
				    NISTC_CLK_FOUT_DIO_SER_OUT_DIV2;
			/*
			 * Note: NISTC_CLK_FOUT_DIO_SER_OUT_DIV2 only affects
			 * 600ns/1.2us. If you turn divide_by_2 off with the
			 * slow clock, you will still get 10us, except then
			 * all your delays are wrong.
			 */
			data[1] = SERIAL_10US;
			devpriv->serial_interval_ns = data[1];
		} else {
			devpriv->dio_control &= ~(NISTC_DIO_CTRL_HW_SER_ENA |
						  NISTC_DIO_SDCLK);
			devpriv->serial_hw_mode = 0;
			data[1] = (data[1] / 1000) * 1000;
			devpriv->serial_interval_ns = data[1];
		}
		devpriv->clock_and_fout = clk_fout;

		ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
		ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);
		return 1;

	case INSN_CONFIG_BIDIRECTIONAL_DATA:

		if (devpriv->serial_interval_ns == 0)
			return -EINVAL;

		byte_out = data[1] & 0xFF;

		if (devpriv->serial_hw_mode) {
			err = ni_serial_hw_readwrite8(dev, s, byte_out,
						      &byte_in);
		} else if (devpriv->serial_interval_ns > 0) {
			err = ni_serial_sw_readwrite8(dev, s, byte_out,
						      &byte_in);
		} else {
			dev_err(dev->class_dev, "serial disabled!\n");
			return -EINVAL;
		}
		if (err < 0)
			return err;
		data[1] = byte_in & 0xFF;
		return insn->n;

		break;
	default:
		return -EINVAL;
	}
}

static void init_ao_67xx(struct comedi_device *dev, struct comedi_subdevice *s)
{
	int i;

	for (i = 0; i < s->n_chan; i++) {
		ni_ao_win_outw(dev, NI_E_AO_DACSEL(i) | 0x0,
			       NI67XX_AO_CFG2_REG);
	}
	ni_ao_win_outw(dev, 0x0, NI67XX_AO_SP_UPDATES_REG);
}

static const struct mio_regmap ni_gpct_to_stc_regmap[] = {
	[NITIO_G0_AUTO_INC]	= { NISTC_G0_AUTOINC_REG, 2 },
	[NITIO_G1_AUTO_INC]	= { NISTC_G1_AUTOINC_REG, 2 },
	[NITIO_G0_CMD]		= { NISTC_G0_CMD_REG, 2 },
	[NITIO_G1_CMD]		= { NISTC_G1_CMD_REG, 2 },
	[NITIO_G0_HW_SAVE]	= { NISTC_G0_HW_SAVE_REG, 4 },
	[NITIO_G1_HW_SAVE]	= { NISTC_G1_HW_SAVE_REG, 4 },
	[NITIO_G0_SW_SAVE]	= { NISTC_G0_SAVE_REG, 4 },
	[NITIO_G1_SW_SAVE]	= { NISTC_G1_SAVE_REG, 4 },
	[NITIO_G0_MODE]		= { NISTC_G0_MODE_REG, 2 },
	[NITIO_G1_MODE]		= { NISTC_G1_MODE_REG, 2 },
	[NITIO_G0_LOADA]	= { NISTC_G0_LOADA_REG, 4 },
	[NITIO_G1_LOADA]	= { NISTC_G1_LOADA_REG, 4 },
	[NITIO_G0_LOADB]	= { NISTC_G0_LOADB_REG, 4 },
	[NITIO_G1_LOADB]	= { NISTC_G1_LOADB_REG, 4 },
	[NITIO_G0_INPUT_SEL]	= { NISTC_G0_INPUT_SEL_REG, 2 },
	[NITIO_G1_INPUT_SEL]	= { NISTC_G1_INPUT_SEL_REG, 2 },
	[NITIO_G0_CNT_MODE]	= { 0x1b0, 2 },	/* M-Series only */
	[NITIO_G1_CNT_MODE]	= { 0x1b2, 2 },	/* M-Series only */
	[NITIO_G0_GATE2]	= { 0x1b4, 2 },	/* M-Series only */
	[NITIO_G1_GATE2]	= { 0x1b6, 2 },	/* M-Series only */
	[NITIO_G01_STATUS]	= { NISTC_G01_STATUS_REG, 2 },
	[NITIO_G01_RESET]	= { NISTC_RESET_REG, 2 },
	[NITIO_G01_STATUS1]	= { NISTC_STATUS1_REG, 2 },
	[NITIO_G01_STATUS2]	= { NISTC_STATUS2_REG, 2 },
	[NITIO_G0_DMA_CFG]	= { 0x1b8, 2 },	/* M-Series only */
	[NITIO_G1_DMA_CFG]	= { 0x1ba, 2 },	/* M-Series only */
	[NITIO_G0_DMA_STATUS]	= { 0x1b8, 2 },	/* M-Series only */
	[NITIO_G1_DMA_STATUS]	= { 0x1ba, 2 },	/* M-Series only */
	[NITIO_G0_ABZ]		= { 0x1c0, 2 },	/* M-Series only */
	[NITIO_G1_ABZ]		= { 0x1c2, 2 },	/* M-Series only */
	[NITIO_G0_INT_ACK]	= { NISTC_INTA_ACK_REG, 2 },
	[NITIO_G1_INT_ACK]	= { NISTC_INTB_ACK_REG, 2 },
	[NITIO_G0_STATUS]	= { NISTC_AI_STATUS1_REG, 2 },
	[NITIO_G1_STATUS]	= { NISTC_AO_STATUS1_REG, 2 },
	[NITIO_G0_INT_ENA]	= { NISTC_INTA_ENA_REG, 2 },
	[NITIO_G1_INT_ENA]	= { NISTC_INTB_ENA_REG, 2 },
};

static unsigned int ni_gpct_to_stc_register(struct comedi_device *dev,
					    enum ni_gpct_register reg)
{
	const struct mio_regmap *regmap;

	if (reg < ARRAY_SIZE(ni_gpct_to_stc_regmap)) {
		regmap = &ni_gpct_to_stc_regmap[reg];
	} else {
		dev_warn(dev->class_dev, "%s: unhandled register=0x%x\n",
			 __func__, reg);
		return 0;
	}

	return regmap->mio_reg;
}

static void ni_gpct_write_register(struct ni_gpct *counter, unsigned int bits,
				   enum ni_gpct_register reg)
{
	struct comedi_device *dev = counter->counter_dev->dev;
	unsigned int stc_register = ni_gpct_to_stc_register(dev, reg);

	if (stc_register == 0)
		return;

	switch (reg) {
		/* m-series only registers */
	case NITIO_G0_CNT_MODE:
	case NITIO_G1_CNT_MODE:
	case NITIO_G0_GATE2:
	case NITIO_G1_GATE2:
	case NITIO_G0_DMA_CFG:
	case NITIO_G1_DMA_CFG:
	case NITIO_G0_ABZ:
	case NITIO_G1_ABZ:
		ni_writew(dev, bits, stc_register);
		break;

		/* 32 bit registers */
	case NITIO_G0_LOADA:
	case NITIO_G1_LOADA:
	case NITIO_G0_LOADB:
	case NITIO_G1_LOADB:
		ni_stc_writel(dev, bits, stc_register);
		break;

		/* 16 bit registers */
	case NITIO_G0_INT_ENA:
		ni_set_bitfield(dev, stc_register,
				NISTC_INTA_ENA_G0_GATE | NISTC_INTA_ENA_G0_TC,
				bits);
		break;
	case NITIO_G1_INT_ENA:
		ni_set_bitfield(dev, stc_register,
				NISTC_INTB_ENA_G1_GATE | NISTC_INTB_ENA_G1_TC,
				bits);
		break;
	default:
		ni_stc_writew(dev, bits, stc_register);
	}
}

static unsigned int ni_gpct_read_register(struct ni_gpct *counter,
					  enum ni_gpct_register reg)
{
	struct comedi_device *dev = counter->counter_dev->dev;
	unsigned int stc_register = ni_gpct_to_stc_register(dev, reg);

	if (stc_register == 0)
		return 0;

	switch (reg) {
		/* m-series only registers */
	case NITIO_G0_DMA_STATUS:
	case NITIO_G1_DMA_STATUS:
		return ni_readw(dev, stc_register);

		/* 32 bit registers */
	case NITIO_G0_HW_SAVE:
	case NITIO_G1_HW_SAVE:
	case NITIO_G0_SW_SAVE:
	case NITIO_G1_SW_SAVE:
		return ni_stc_readl(dev, stc_register);

		/* 16 bit registers */
	default:
		return ni_stc_readw(dev, stc_register);
	}
}

static int ni_freq_out_insn_read(struct comedi_device *dev,
				 struct comedi_subdevice *s,
				 struct comedi_insn *insn,
				 unsigned int *data)
{
	struct ni_private *devpriv = dev->private;
	unsigned int val = NISTC_CLK_FOUT_TO_DIVIDER(devpriv->clock_and_fout);
	int i;

	for (i = 0; i < insn->n; i++)
		data[i] = val;

	return insn->n;
}

static int ni_freq_out_insn_write(struct comedi_device *dev,
				  struct comedi_subdevice *s,
				  struct comedi_insn *insn,
				  unsigned int *data)
{
	struct ni_private *devpriv = dev->private;

	if (insn->n) {
		unsigned int val = data[insn->n - 1];

		devpriv->clock_and_fout &= ~NISTC_CLK_FOUT_ENA;
		ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);
		devpriv->clock_and_fout &= ~NISTC_CLK_FOUT_DIVIDER_MASK;

		/* use the last data value to set the fout divider */
		devpriv->clock_and_fout |= NISTC_CLK_FOUT_DIVIDER(val);

		devpriv->clock_and_fout |= NISTC_CLK_FOUT_ENA;
		ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);
	}
	return insn->n;
}

static int ni_freq_out_insn_config(struct comedi_device *dev,
				   struct comedi_subdevice *s,
				   struct comedi_insn *insn,
				   unsigned int *data)
{
	struct ni_private *devpriv = dev->private;

	switch (data[0]) {
	case INSN_CONFIG_SET_CLOCK_SRC:
		switch (data[1]) {
		case NI_FREQ_OUT_TIMEBASE_1_DIV_2_CLOCK_SRC:
			devpriv->clock_and_fout &= ~NISTC_CLK_FOUT_TIMEBASE_SEL;
			break;
		case NI_FREQ_OUT_TIMEBASE_2_CLOCK_SRC:
			devpriv->clock_and_fout |= NISTC_CLK_FOUT_TIMEBASE_SEL;
			break;
		default:
			return -EINVAL;
		}
		ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);
		break;
	case INSN_CONFIG_GET_CLOCK_SRC:
		if (devpriv->clock_and_fout & NISTC_CLK_FOUT_TIMEBASE_SEL) {
			data[1] = NI_FREQ_OUT_TIMEBASE_2_CLOCK_SRC;
			data[2] = TIMEBASE_2_NS;
		} else {
			data[1] = NI_FREQ_OUT_TIMEBASE_1_DIV_2_CLOCK_SRC;
			data[2] = TIMEBASE_1_NS * 2;
		}
		break;
	default:
		return -EINVAL;
	}
	return insn->n;
}

static int ni_8255_callback(struct comedi_device *dev,
			    int dir, int port, int data, unsigned long iobase)
{
	if (dir) {
		ni_writeb(dev, data, iobase + 2 * port);
		return 0;
	}

	return ni_readb(dev, iobase + 2 * port);
}

static int ni_get_pwm_config(struct comedi_device *dev, unsigned int *data)
{
	struct ni_private *devpriv = dev->private;

	data[1] = devpriv->pwm_up_count * devpriv->clock_ns;
	data[2] = devpriv->pwm_down_count * devpriv->clock_ns;
	return 3;
}

static int ni_m_series_pwm_config(struct comedi_device *dev,
				  struct comedi_subdevice *s,
				  struct comedi_insn *insn,
				  unsigned int *data)
{
	struct ni_private *devpriv = dev->private;
	unsigned int up_count, down_count;

	switch (data[0]) {
	case INSN_CONFIG_PWM_OUTPUT:
		switch (data[1]) {
		case CMDF_ROUND_NEAREST:
			up_count = DIV_ROUND_CLOSEST(data[2],
						     devpriv->clock_ns);
			break;
		case CMDF_ROUND_DOWN:
			up_count = data[2] / devpriv->clock_ns;
			break;
		case CMDF_ROUND_UP:
			up_count =
			    DIV_ROUND_UP(data[2], devpriv->clock_ns);
			break;
		default:
			return -EINVAL;
		}
		switch (data[3]) {
		case CMDF_ROUND_NEAREST:
			down_count = DIV_ROUND_CLOSEST(data[4],
						       devpriv->clock_ns);
			break;
		case CMDF_ROUND_DOWN:
			down_count = data[4] / devpriv->clock_ns;
			break;
		case CMDF_ROUND_UP:
			down_count =
			    DIV_ROUND_UP(data[4], devpriv->clock_ns);
			break;
		default:
			return -EINVAL;
		}
		if (up_count * devpriv->clock_ns != data[2] ||
		    down_count * devpriv->clock_ns != data[4]) {
			data[2] = up_count * devpriv->clock_ns;
			data[4] = down_count * devpriv->clock_ns;
			return -EAGAIN;
		}
		ni_writel(dev, NI_M_CAL_PWM_HIGH_TIME(up_count) |
			       NI_M_CAL_PWM_LOW_TIME(down_count),
			  NI_M_CAL_PWM_REG);
		devpriv->pwm_up_count = up_count;
		devpriv->pwm_down_count = down_count;
		return 5;
	case INSN_CONFIG_GET_PWM_OUTPUT:
		return ni_get_pwm_config(dev, data);
	default:
		return -EINVAL;
	}
	return 0;
}

static int ni_6143_pwm_config(struct comedi_device *dev,
			      struct comedi_subdevice *s,
			      struct comedi_insn *insn,
			      unsigned int *data)
{
	struct ni_private *devpriv = dev->private;
	unsigned int up_count, down_count;

	switch (data[0]) {
	case INSN_CONFIG_PWM_OUTPUT:
		switch (data[1]) {
		case CMDF_ROUND_NEAREST:
			up_count = DIV_ROUND_CLOSEST(data[2],
						     devpriv->clock_ns);
			break;
		case CMDF_ROUND_DOWN:
			up_count = data[2] / devpriv->clock_ns;
			break;
		case CMDF_ROUND_UP:
			up_count =
			    DIV_ROUND_UP(data[2], devpriv->clock_ns);
			break;
		default:
			return -EINVAL;
		}
		switch (data[3]) {
		case CMDF_ROUND_NEAREST:
			down_count = DIV_ROUND_CLOSEST(data[4],
						       devpriv->clock_ns);
			break;
		case CMDF_ROUND_DOWN:
			down_count = data[4] / devpriv->clock_ns;
			break;
		case CMDF_ROUND_UP:
			down_count =
			    DIV_ROUND_UP(data[4], devpriv->clock_ns);
			break;
		default:
			return -EINVAL;
		}
		if (up_count * devpriv->clock_ns != data[2] ||
		    down_count * devpriv->clock_ns != data[4]) {
			data[2] = up_count * devpriv->clock_ns;
			data[4] = down_count * devpriv->clock_ns;
			return -EAGAIN;
		}
		ni_writel(dev, up_count, NI6143_CALIB_HI_TIME_REG);
		devpriv->pwm_up_count = up_count;
		ni_writel(dev, down_count, NI6143_CALIB_LO_TIME_REG);
		devpriv->pwm_down_count = down_count;
		return 5;
	case INSN_CONFIG_GET_PWM_OUTPUT:
		return ni_get_pwm_config(dev, data);
	default:
		return -EINVAL;
	}
	return 0;
}

static int pack_mb88341(int addr, int val, int *bitstring)
{
	/*
	 * Fujitsu MB 88341
	 * Note that address bits are reversed.  Thanks to
	 * Ingo Keen for noticing this.
	 *
	 * Note also that the 88341 expects address values from
	 * 1-12, whereas we use channel numbers 0-11.  The NI
	 * docs use 1-12, also, so be careful here.
	 */
	addr++;
	*bitstring = ((addr & 0x1) << 11) |
	    ((addr & 0x2) << 9) |
	    ((addr & 0x4) << 7) | ((addr & 0x8) << 5) | (val & 0xff);
	return 12;
}

static int pack_dac8800(int addr, int val, int *bitstring)
{
	*bitstring = ((addr & 0x7) << 8) | (val & 0xff);
	return 11;
}

static int pack_dac8043(int addr, int val, int *bitstring)
{
	*bitstring = val & 0xfff;
	return 12;
}

static int pack_ad8522(int addr, int val, int *bitstring)
{
	*bitstring = (val & 0xfff) | (addr ? 0xc000 : 0xa000);
	return 16;
}

static int pack_ad8804(int addr, int val, int *bitstring)
{
	*bitstring = ((addr & 0xf) << 8) | (val & 0xff);
	return 12;
}

static int pack_ad8842(int addr, int val, int *bitstring)
{
	*bitstring = ((addr + 1) << 8) | (val & 0xff);
	return 12;
}

struct caldac_struct {
	int n_chans;
	int n_bits;
	int (*packbits)(int, int, int *);
};

static struct caldac_struct caldacs[] = {
	[mb88341] = {12, 8, pack_mb88341},
	[dac8800] = {8, 8, pack_dac8800},
	[dac8043] = {1, 12, pack_dac8043},
	[ad8522] = {2, 12, pack_ad8522},
	[ad8804] = {12, 8, pack_ad8804},
	[ad8842] = {8, 8, pack_ad8842},
	[ad8804_debug] = {16, 8, pack_ad8804},
};

static void ni_write_caldac(struct comedi_device *dev, int addr, int val)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;
	unsigned int loadbit = 0, bits = 0, bit, bitstring = 0;
	unsigned int cmd;
	int i;
	int type;

	if (devpriv->caldacs[addr] == val)
		return;
	devpriv->caldacs[addr] = val;

	for (i = 0; i < 3; i++) {
		type = board->caldac[i];
		if (type == caldac_none)
			break;
		if (addr < caldacs[type].n_chans) {
			bits = caldacs[type].packbits(addr, val, &bitstring);
			loadbit = NI_E_SERIAL_CMD_DAC_LD(i);
			break;
		}
		addr -= caldacs[type].n_chans;
	}

	/* bits will be 0 if there is no caldac for the given addr */
	if (bits == 0)
		return;

	for (bit = 1 << (bits - 1); bit; bit >>= 1) {
		cmd = (bit & bitstring) ? NI_E_SERIAL_CMD_SDATA : 0;
		ni_writeb(dev, cmd, NI_E_SERIAL_CMD_REG);
		udelay(1);
		ni_writeb(dev, NI_E_SERIAL_CMD_SCLK | cmd, NI_E_SERIAL_CMD_REG);
		udelay(1);
	}
	ni_writeb(dev, loadbit, NI_E_SERIAL_CMD_REG);
	udelay(1);
	ni_writeb(dev, 0, NI_E_SERIAL_CMD_REG);
}

static int ni_calib_insn_write(struct comedi_device *dev,
			       struct comedi_subdevice *s,
			       struct comedi_insn *insn,
			       unsigned int *data)
{
	ni_write_caldac(dev, CR_CHAN(insn->chanspec), data[0]);

	return 1;
}

static int ni_calib_insn_read(struct comedi_device *dev,
			      struct comedi_subdevice *s,
			      struct comedi_insn *insn,
			      unsigned int *data)
{
	struct ni_private *devpriv = dev->private;

	data[0] = devpriv->caldacs[CR_CHAN(insn->chanspec)];

	return 1;
}

static void caldac_setup(struct comedi_device *dev, struct comedi_subdevice *s)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;
	int i, j;
	int n_dacs;
	int n_chans = 0;
	int n_bits;
	int diffbits = 0;
	int type;
	int chan;

	type = board->caldac[0];
	if (type == caldac_none)
		return;
	n_bits = caldacs[type].n_bits;
	for (i = 0; i < 3; i++) {
		type = board->caldac[i];
		if (type == caldac_none)
			break;
		if (caldacs[type].n_bits != n_bits)
			diffbits = 1;
		n_chans += caldacs[type].n_chans;
	}
	n_dacs = i;
	s->n_chan = n_chans;

	if (diffbits) {
		unsigned int *maxdata_list = devpriv->caldac_maxdata_list;

		if (n_chans > MAX_N_CALDACS)
			dev_err(dev->class_dev,
				"BUG! MAX_N_CALDACS too small\n");
		s->maxdata_list = maxdata_list;
		chan = 0;
		for (i = 0; i < n_dacs; i++) {
			type = board->caldac[i];
			for (j = 0; j < caldacs[type].n_chans; j++) {
				maxdata_list[chan] =
				    (1 << caldacs[type].n_bits) - 1;
				chan++;
			}
		}

		for (chan = 0; chan < s->n_chan; chan++)
			ni_write_caldac(dev, i, s->maxdata_list[i] / 2);
	} else {
		type = board->caldac[0];
		s->maxdata = (1 << caldacs[type].n_bits) - 1;

		for (chan = 0; chan < s->n_chan; chan++)
			ni_write_caldac(dev, i, s->maxdata / 2);
	}
}

static int ni_read_eeprom(struct comedi_device *dev, int addr)
{
	unsigned int cmd = NI_E_SERIAL_CMD_EEPROM_CS;
	int bit;
	int bitstring;

	bitstring = 0x0300 | ((addr & 0x100) << 3) | (addr & 0xff);
	ni_writeb(dev, cmd, NI_E_SERIAL_CMD_REG);
	for (bit = 0x8000; bit; bit >>= 1) {
		if (bit & bitstring)
			cmd |= NI_E_SERIAL_CMD_SDATA;
		else
			cmd &= ~NI_E_SERIAL_CMD_SDATA;

		ni_writeb(dev, cmd, NI_E_SERIAL_CMD_REG);
		ni_writeb(dev, NI_E_SERIAL_CMD_SCLK | cmd, NI_E_SERIAL_CMD_REG);
	}
	cmd = NI_E_SERIAL_CMD_EEPROM_CS;
	bitstring = 0;
	for (bit = 0x80; bit; bit >>= 1) {
		ni_writeb(dev, cmd, NI_E_SERIAL_CMD_REG);
		ni_writeb(dev, NI_E_SERIAL_CMD_SCLK | cmd, NI_E_SERIAL_CMD_REG);
		if (ni_readb(dev, NI_E_STATUS_REG) & NI_E_STATUS_PROMOUT)
			bitstring |= bit;
	}
	ni_writeb(dev, 0, NI_E_SERIAL_CMD_REG);

	return bitstring;
}

static int ni_eeprom_insn_read(struct comedi_device *dev,
			       struct comedi_subdevice *s,
			       struct comedi_insn *insn,
			       unsigned int *data)
{
	data[0] = ni_read_eeprom(dev, CR_CHAN(insn->chanspec));

	return 1;
}

static int ni_m_series_eeprom_insn_read(struct comedi_device *dev,
					struct comedi_subdevice *s,
					struct comedi_insn *insn,
					unsigned int *data)
{
	struct ni_private *devpriv = dev->private;

	data[0] = devpriv->eeprom_buffer[CR_CHAN(insn->chanspec)];

	return 1;
}

static unsigned int ni_old_get_pfi_routing(struct comedi_device *dev,
					   unsigned int chan)
{
	/*  pre-m-series boards have fixed signals on pfi pins */
	switch (chan) {
	case 0:
		return NI_PFI_OUTPUT_AI_START1;
	case 1:
		return NI_PFI_OUTPUT_AI_START2;
	case 2:
		return NI_PFI_OUTPUT_AI_CONVERT;
	case 3:
		return NI_PFI_OUTPUT_G_SRC1;
	case 4:
		return NI_PFI_OUTPUT_G_GATE1;
	case 5:
		return NI_PFI_OUTPUT_AO_UPDATE_N;
	case 6:
		return NI_PFI_OUTPUT_AO_START1;
	case 7:
		return NI_PFI_OUTPUT_AI_START_PULSE;
	case 8:
		return NI_PFI_OUTPUT_G_SRC0;
	case 9:
		return NI_PFI_OUTPUT_G_GATE0;
	default:
		dev_err(dev->class_dev, "bug, unhandled case in switch.\n");
		break;
	}
	return 0;
}

static int ni_old_set_pfi_routing(struct comedi_device *dev,
				  unsigned int chan, unsigned int source)
{
	/*  pre-m-series boards have fixed signals on pfi pins */
	if (source != ni_old_get_pfi_routing(dev, chan))
		return -EINVAL;
	return 2;
}

static unsigned int ni_m_series_get_pfi_routing(struct comedi_device *dev,
						unsigned int chan)
{
	struct ni_private *devpriv = dev->private;
	const unsigned int array_offset = chan / 3;

	return NI_M_PFI_OUT_SEL_TO_SRC(chan,
				devpriv->pfi_output_select_reg[array_offset]);
}

static int ni_m_series_set_pfi_routing(struct comedi_device *dev,
				       unsigned int chan, unsigned int source)
{
	struct ni_private *devpriv = dev->private;
	unsigned int index = chan / 3;
	unsigned short val = devpriv->pfi_output_select_reg[index];

	if ((source & 0x1f) != source)
		return -EINVAL;

	val &= ~NI_M_PFI_OUT_SEL_MASK(chan);
	val |= NI_M_PFI_OUT_SEL(chan, source);
	ni_writew(dev, val, NI_M_PFI_OUT_SEL_REG(index));
	devpriv->pfi_output_select_reg[index] = val;

	return 2;
}

static unsigned int ni_get_pfi_routing(struct comedi_device *dev,
				       unsigned int chan)
{
	struct ni_private *devpriv = dev->private;

	return (devpriv->is_m_series)
			? ni_m_series_get_pfi_routing(dev, chan)
			: ni_old_get_pfi_routing(dev, chan);
}

static int ni_set_pfi_routing(struct comedi_device *dev,
			      unsigned int chan, unsigned int source)
{
	struct ni_private *devpriv = dev->private;

	return (devpriv->is_m_series)
			? ni_m_series_set_pfi_routing(dev, chan, source)
			: ni_old_set_pfi_routing(dev, chan, source);
}

static int ni_config_filter(struct comedi_device *dev,
			    unsigned int pfi_channel,
			    enum ni_pfi_filter_select filter)
{
	struct ni_private *devpriv = dev->private;
	unsigned int bits;

	if (!devpriv->is_m_series)
		return -ENOTSUPP;

	bits = ni_readl(dev, NI_M_PFI_FILTER_REG);
	bits &= ~NI_M_PFI_FILTER_SEL_MASK(pfi_channel);
	bits |= NI_M_PFI_FILTER_SEL(pfi_channel, filter);
	ni_writel(dev, bits, NI_M_PFI_FILTER_REG);
	return 0;
}

static int ni_pfi_insn_config(struct comedi_device *dev,
			      struct comedi_subdevice *s,
			      struct comedi_insn *insn,
			      unsigned int *data)
{
	struct ni_private *devpriv = dev->private;
	unsigned int chan;

	if (insn->n < 1)
		return -EINVAL;

	chan = CR_CHAN(insn->chanspec);

	switch (data[0]) {
	case COMEDI_OUTPUT:
		ni_set_bits(dev, NISTC_IO_BIDIR_PIN_REG, 1 << chan, 1);
		break;
	case COMEDI_INPUT:
		ni_set_bits(dev, NISTC_IO_BIDIR_PIN_REG, 1 << chan, 0);
		break;
	case INSN_CONFIG_DIO_QUERY:
		data[1] =
		    (devpriv->io_bidirection_pin_reg & (1 << chan)) ?
		    COMEDI_OUTPUT : COMEDI_INPUT;
		return 0;
	case INSN_CONFIG_SET_ROUTING:
		return ni_set_pfi_routing(dev, chan, data[1]);
	case INSN_CONFIG_GET_ROUTING:
		data[1] = ni_get_pfi_routing(dev, chan);
		break;
	case INSN_CONFIG_FILTER:
		return ni_config_filter(dev, chan, data[1]);
	default:
		return -EINVAL;
	}
	return 0;
}

static int ni_pfi_insn_bits(struct comedi_device *dev,
			    struct comedi_subdevice *s,
			    struct comedi_insn *insn,
			    unsigned int *data)
{
	struct ni_private *devpriv = dev->private;

	if (!devpriv->is_m_series)
		return -ENOTSUPP;

	if (comedi_dio_update_state(s, data))
		ni_writew(dev, s->state, NI_M_PFI_DO_REG);

	data[1] = ni_readw(dev, NI_M_PFI_DI_REG);

	return insn->n;
}

static int cs5529_wait_for_idle(struct comedi_device *dev)
{
	unsigned short status;
	const int timeout = HZ;
	int i;

	for (i = 0; i < timeout; i++) {
		status = ni_ao_win_inw(dev, NI67XX_CAL_STATUS_REG);
		if ((status & NI67XX_CAL_STATUS_BUSY) == 0)
			break;
		set_current_state(TASK_INTERRUPTIBLE);
		if (schedule_timeout(1))
			return -EIO;
	}
	if (i == timeout) {
		dev_err(dev->class_dev, "timeout\n");
		return -ETIME;
	}
	return 0;
}

static void cs5529_command(struct comedi_device *dev, unsigned short value)
{
	static const int timeout = 100;
	int i;

	ni_ao_win_outw(dev, value, NI67XX_CAL_CMD_REG);
	/* give time for command to start being serially clocked into cs5529.
	 * this insures that the NI67XX_CAL_STATUS_BUSY bit will get properly
	 * set before we exit this function.
	 */
	for (i = 0; i < timeout; i++) {
		if (ni_ao_win_inw(dev, NI67XX_CAL_STATUS_REG) &
		    NI67XX_CAL_STATUS_BUSY)
			break;
		udelay(1);
	}
	if (i == timeout)
		dev_err(dev->class_dev,
			"possible problem - never saw adc go busy?\n");
}

static int cs5529_do_conversion(struct comedi_device *dev,
				unsigned short *data)
{
	int retval;
	unsigned short status;

	cs5529_command(dev, CS5529_CMD_CB | CS5529_CMD_SINGLE_CONV);
	retval = cs5529_wait_for_idle(dev);
	if (retval) {
		dev_err(dev->class_dev,
			"timeout or signal in cs5529_do_conversion()\n");
		return -ETIME;
	}
	status = ni_ao_win_inw(dev, NI67XX_CAL_STATUS_REG);
	if (status & NI67XX_CAL_STATUS_OSC_DETECT) {
		dev_err(dev->class_dev,
			"cs5529 conversion error, status CSS_OSC_DETECT\n");
		return -EIO;
	}
	if (status & NI67XX_CAL_STATUS_OVERRANGE) {
		dev_err(dev->class_dev,
			"cs5529 conversion error, overrange (ignoring)\n");
	}
	if (data) {
		*data = ni_ao_win_inw(dev, NI67XX_CAL_DATA_REG);
		/* cs5529 returns 16 bit signed data in bipolar mode */
		*data ^= (1 << 15);
	}
	return 0;
}

static int cs5529_ai_insn_read(struct comedi_device *dev,
			       struct comedi_subdevice *s,
			       struct comedi_insn *insn,
			       unsigned int *data)
{
	int n, retval;
	unsigned short sample;
	unsigned int channel_select;
	const unsigned int INTERNAL_REF = 0x1000;

	/*
	 * Set calibration adc source.  Docs lie, reference select bits 8 to 11
	 * do nothing. bit 12 seems to chooses internal reference voltage, bit
	 * 13 causes the adc input to go overrange (maybe reads external
	 * reference?)
	 */
	if (insn->chanspec & CR_ALT_SOURCE)
		channel_select = INTERNAL_REF;
	else
		channel_select = CR_CHAN(insn->chanspec);
	ni_ao_win_outw(dev, channel_select, NI67XX_AO_CAL_CHAN_SEL_REG);

	for (n = 0; n < insn->n; n++) {
		retval = cs5529_do_conversion(dev, &sample);
		if (retval < 0)
			return retval;
		data[n] = sample;
	}
	return insn->n;
}

static void cs5529_config_write(struct comedi_device *dev, unsigned int value,
				unsigned int reg_select_bits)
{
	ni_ao_win_outw(dev, (value >> 16) & 0xff, NI67XX_CAL_CFG_HI_REG);
	ni_ao_win_outw(dev, value & 0xffff, NI67XX_CAL_CFG_LO_REG);
	reg_select_bits &= CS5529_CMD_REG_MASK;
	cs5529_command(dev, CS5529_CMD_CB | reg_select_bits);
	if (cs5529_wait_for_idle(dev))
		dev_err(dev->class_dev,
			"timeout or signal in %s\n", __func__);
}

static int init_cs5529(struct comedi_device *dev)
{
	unsigned int config_bits = CS5529_CFG_PORT_FLAG |
				   CS5529_CFG_WORD_RATE_2180;

#if 1
	/* do self-calibration */
	cs5529_config_write(dev, config_bits | CS5529_CFG_CALIB_BOTH_SELF,
			    CS5529_CFG_REG);
	/* need to force a conversion for calibration to run */
	cs5529_do_conversion(dev, NULL);
#else
	/* force gain calibration to 1 */
	cs5529_config_write(dev, 0x400000, CS5529_GAIN_REG);
	cs5529_config_write(dev, config_bits | CS5529_CFG_CALIB_OFFSET_SELF,
			    CS5529_CFG_REG);
	if (cs5529_wait_for_idle(dev))
		dev_err(dev->class_dev,
			"timeout or signal in %s\n", __func__);
#endif
	return 0;
}

/*
 * Find best multiplier/divider to try and get the PLL running at 80 MHz
 * given an arbitrary frequency input clock.
 */
static int ni_mseries_get_pll_parameters(unsigned int reference_period_ns,
					 unsigned int *freq_divider,
					 unsigned int *freq_multiplier,
					 unsigned int *actual_period_ns)
{
	unsigned int div;
	unsigned int best_div = 1;
	unsigned int mult;
	unsigned int best_mult = 1;
	static const unsigned int pico_per_nano = 1000;
	const unsigned int reference_picosec = reference_period_ns *
					       pico_per_nano;
	/*
	 * m-series wants the phased-locked loop to output 80MHz, which is
	 * divided by 4 to 20 MHz for most timing clocks
	 */
	static const unsigned int target_picosec = 12500;
	int best_period_picosec = 0;

	for (div = 1; div <= NI_M_PLL_MAX_DIVISOR; ++div) {
		for (mult = 1; mult <= NI_M_PLL_MAX_MULTIPLIER; ++mult) {
			unsigned int new_period_ps =
			    (reference_picosec * div) / mult;
			if (abs(new_period_ps - target_picosec) <
			    abs(best_period_picosec - target_picosec)) {
				best_period_picosec = new_period_ps;
				best_div = div;
				best_mult = mult;
			}
		}
	}
	if (best_period_picosec == 0)
		return -EIO;

	*freq_divider = best_div;
	*freq_multiplier = best_mult;
	/* return the actual period (* fudge factor for 80 to 20 MHz) */
	*actual_period_ns = DIV_ROUND_CLOSEST(best_period_picosec * 4,
					      pico_per_nano);
	return 0;
}

static int ni_mseries_set_pll_master_clock(struct comedi_device *dev,
					   unsigned int source,
					   unsigned int period_ns)
{
	struct ni_private *devpriv = dev->private;
	static const unsigned int min_period_ns = 50;
	static const unsigned int max_period_ns = 1000;
	static const unsigned int timeout = 1000;
	unsigned int pll_control_bits;
	unsigned int freq_divider;
	unsigned int freq_multiplier;
	unsigned int rtsi;
	unsigned int i;
	int retval;

	if (source == NI_MIO_PLL_PXI10_CLOCK)
		period_ns = 100;
	/*
	 * These limits are somewhat arbitrary, but NI advertises 1 to 20MHz
	 * range so we'll use that.
	 */
	if (period_ns < min_period_ns || period_ns > max_period_ns) {
		dev_err(dev->class_dev,
			"%s: you must specify an input clock frequency between %i and %i nanosec for the phased-lock loop\n",
			__func__, min_period_ns, max_period_ns);
		return -EINVAL;
	}
	devpriv->rtsi_trig_direction_reg &= ~NISTC_RTSI_TRIG_USE_CLK;
	ni_stc_writew(dev, devpriv->rtsi_trig_direction_reg,
		      NISTC_RTSI_TRIG_DIR_REG);
	pll_control_bits = NI_M_PLL_CTRL_ENA | NI_M_PLL_CTRL_VCO_MODE_75_150MHZ;
	devpriv->clock_and_fout2 |= NI_M_CLK_FOUT2_TIMEBASE1_PLL |
				    NI_M_CLK_FOUT2_TIMEBASE3_PLL;
	devpriv->clock_and_fout2 &= ~NI_M_CLK_FOUT2_PLL_SRC_MASK;
	switch (source) {
	case NI_MIO_PLL_PXI_STAR_TRIGGER_CLOCK:
		devpriv->clock_and_fout2 |= NI_M_CLK_FOUT2_PLL_SRC_STAR;
		break;
	case NI_MIO_PLL_PXI10_CLOCK:
		/* pxi clock is 10MHz */
		devpriv->clock_and_fout2 |= NI_M_CLK_FOUT2_PLL_SRC_PXI10;
		break;
	default:
		for (rtsi = 0; rtsi <= NI_M_MAX_RTSI_CHAN; ++rtsi) {
			if (source == NI_MIO_PLL_RTSI_CLOCK(rtsi)) {
				devpriv->clock_and_fout2 |=
					NI_M_CLK_FOUT2_PLL_SRC_RTSI(rtsi);
				break;
			}
		}
		if (rtsi > NI_M_MAX_RTSI_CHAN)
			return -EINVAL;
		break;
	}
	retval = ni_mseries_get_pll_parameters(period_ns,
					       &freq_divider,
					       &freq_multiplier,
					       &devpriv->clock_ns);
	if (retval < 0) {
		dev_err(dev->class_dev,
			"bug, failed to find pll parameters\n");
		return retval;
	}

	ni_writew(dev, devpriv->clock_and_fout2, NI_M_CLK_FOUT2_REG);
	pll_control_bits |= NI_M_PLL_CTRL_DIVISOR(freq_divider) |
			    NI_M_PLL_CTRL_MULTIPLIER(freq_multiplier);

	ni_writew(dev, pll_control_bits, NI_M_PLL_CTRL_REG);
	devpriv->clock_source = source;
	/* it takes a few hundred microseconds for PLL to lock */
	for (i = 0; i < timeout; ++i) {
		if (ni_readw(dev, NI_M_PLL_STATUS_REG) & NI_M_PLL_STATUS_LOCKED)
			break;
		udelay(1);
	}
	if (i == timeout) {
		dev_err(dev->class_dev,
			"%s: timed out waiting for PLL to lock to reference clock source %i with period %i ns\n",
			__func__, source, period_ns);
		return -ETIMEDOUT;
	}
	return 3;
}

static int ni_set_master_clock(struct comedi_device *dev,
			       unsigned int source, unsigned int period_ns)
{
	struct ni_private *devpriv = dev->private;

	if (source == NI_MIO_INTERNAL_CLOCK) {
		devpriv->rtsi_trig_direction_reg &= ~NISTC_RTSI_TRIG_USE_CLK;
		ni_stc_writew(dev, devpriv->rtsi_trig_direction_reg,
			      NISTC_RTSI_TRIG_DIR_REG);
		devpriv->clock_ns = TIMEBASE_1_NS;
		if (devpriv->is_m_series) {
			devpriv->clock_and_fout2 &=
			    ~(NI_M_CLK_FOUT2_TIMEBASE1_PLL |
			      NI_M_CLK_FOUT2_TIMEBASE3_PLL);
			ni_writew(dev, devpriv->clock_and_fout2,
				  NI_M_CLK_FOUT2_REG);
			ni_writew(dev, 0, NI_M_PLL_CTRL_REG);
		}
		devpriv->clock_source = source;
	} else {
		if (devpriv->is_m_series) {
			return ni_mseries_set_pll_master_clock(dev, source,
							       period_ns);
		} else {
			if (source == NI_MIO_RTSI_CLOCK) {
				devpriv->rtsi_trig_direction_reg |=
				    NISTC_RTSI_TRIG_USE_CLK;
				ni_stc_writew(dev,
					      devpriv->rtsi_trig_direction_reg,
					      NISTC_RTSI_TRIG_DIR_REG);
				if (period_ns == 0) {
					dev_err(dev->class_dev,
						"we don't handle an unspecified clock period correctly yet, returning error\n");
					return -EINVAL;
				}
				devpriv->clock_ns = period_ns;
				devpriv->clock_source = source;
			} else {
				return -EINVAL;
			}
		}
	}
	return 3;
}

static int ni_valid_rtsi_output_source(struct comedi_device *dev,
				       unsigned int chan, unsigned int source)
{
	struct ni_private *devpriv = dev->private;

	if (chan >= NISTC_RTSI_TRIG_NUM_CHAN(devpriv->is_m_series)) {
		if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
			if (source == NI_RTSI_OUTPUT_RTSI_OSC)
				return 1;

			dev_err(dev->class_dev,
				"%s: invalid source for channel=%i, channel %i is always the RTSI clock for pre-m-series boards\n",
				__func__, chan, NISTC_RTSI_TRIG_OLD_CLK_CHAN);
			return 0;
		}
		return 0;
	}
	switch (source) {
	case NI_RTSI_OUTPUT_ADR_START1:
	case NI_RTSI_OUTPUT_ADR_START2:
	case NI_RTSI_OUTPUT_SCLKG:
	case NI_RTSI_OUTPUT_DACUPDN:
	case NI_RTSI_OUTPUT_DA_START1:
	case NI_RTSI_OUTPUT_G_SRC0:
	case NI_RTSI_OUTPUT_G_GATE0:
	case NI_RTSI_OUTPUT_RGOUT0:
	case NI_RTSI_OUTPUT_RTSI_BRD_0:
		return 1;
	case NI_RTSI_OUTPUT_RTSI_OSC:
		return (devpriv->is_m_series) ? 1 : 0;
	default:
		return 0;
	}
}

static int ni_set_rtsi_routing(struct comedi_device *dev,
			       unsigned int chan, unsigned int src)
{
	struct ni_private *devpriv = dev->private;

	if (ni_valid_rtsi_output_source(dev, chan, src) == 0)
		return -EINVAL;
	if (chan < 4) {
		devpriv->rtsi_trig_a_output_reg &= ~NISTC_RTSI_TRIG_MASK(chan);
		devpriv->rtsi_trig_a_output_reg |= NISTC_RTSI_TRIG(chan, src);
		ni_stc_writew(dev, devpriv->rtsi_trig_a_output_reg,
			      NISTC_RTSI_TRIGA_OUT_REG);
	} else if (chan < 8) {
		devpriv->rtsi_trig_b_output_reg &= ~NISTC_RTSI_TRIG_MASK(chan);
		devpriv->rtsi_trig_b_output_reg |= NISTC_RTSI_TRIG(chan, src);
		ni_stc_writew(dev, devpriv->rtsi_trig_b_output_reg,
			      NISTC_RTSI_TRIGB_OUT_REG);
	}
	return 2;
}

static unsigned int ni_get_rtsi_routing(struct comedi_device *dev,
					unsigned int chan)
{
	struct ni_private *devpriv = dev->private;

	if (chan < 4) {
		return NISTC_RTSI_TRIG_TO_SRC(chan,
					      devpriv->rtsi_trig_a_output_reg);
	} else if (chan < NISTC_RTSI_TRIG_NUM_CHAN(devpriv->is_m_series)) {
		return NISTC_RTSI_TRIG_TO_SRC(chan,
					      devpriv->rtsi_trig_b_output_reg);
	} else {
		if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN)
			return NI_RTSI_OUTPUT_RTSI_OSC;
		dev_err(dev->class_dev, "bug! should never get here?\n");
		return 0;
	}
}

static int ni_rtsi_insn_config(struct comedi_device *dev,
			       struct comedi_subdevice *s,
			       struct comedi_insn *insn,
			       unsigned int *data)
{
	struct ni_private *devpriv = dev->private;
	unsigned int chan = CR_CHAN(insn->chanspec);
	unsigned int max_chan = NISTC_RTSI_TRIG_NUM_CHAN(devpriv->is_m_series);

	switch (data[0]) {
	case INSN_CONFIG_DIO_OUTPUT:
		if (chan < max_chan) {
			devpriv->rtsi_trig_direction_reg |=
			    NISTC_RTSI_TRIG_DIR(chan, devpriv->is_m_series);
		} else if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
			devpriv->rtsi_trig_direction_reg |=
			    NISTC_RTSI_TRIG_DRV_CLK;
		}
		ni_stc_writew(dev, devpriv->rtsi_trig_direction_reg,
			      NISTC_RTSI_TRIG_DIR_REG);
		break;
	case INSN_CONFIG_DIO_INPUT:
		if (chan < max_chan) {
			devpriv->rtsi_trig_direction_reg &=
			    ~NISTC_RTSI_TRIG_DIR(chan, devpriv->is_m_series);
		} else if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
			devpriv->rtsi_trig_direction_reg &=
			    ~NISTC_RTSI_TRIG_DRV_CLK;
		}
		ni_stc_writew(dev, devpriv->rtsi_trig_direction_reg,
			      NISTC_RTSI_TRIG_DIR_REG);
		break;
	case INSN_CONFIG_DIO_QUERY:
		if (chan < max_chan) {
			data[1] =
			    (devpriv->rtsi_trig_direction_reg &
			     NISTC_RTSI_TRIG_DIR(chan, devpriv->is_m_series))
				? INSN_CONFIG_DIO_OUTPUT
				: INSN_CONFIG_DIO_INPUT;
		} else if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
			data[1] = (devpriv->rtsi_trig_direction_reg &
				   NISTC_RTSI_TRIG_DRV_CLK)
				  ? INSN_CONFIG_DIO_OUTPUT
				  : INSN_CONFIG_DIO_INPUT;
		}
		return 2;
	case INSN_CONFIG_SET_CLOCK_SRC:
		return ni_set_master_clock(dev, data[1], data[2]);
	case INSN_CONFIG_GET_CLOCK_SRC:
		data[1] = devpriv->clock_source;
		data[2] = devpriv->clock_ns;
		return 3;
	case INSN_CONFIG_SET_ROUTING:
		return ni_set_rtsi_routing(dev, chan, data[1]);
	case INSN_CONFIG_GET_ROUTING:
		data[1] = ni_get_rtsi_routing(dev, chan);
		return 2;
	default:
		return -EINVAL;
	}
	return 1;
}

static int ni_rtsi_insn_bits(struct comedi_device *dev,
			     struct comedi_subdevice *s,
			     struct comedi_insn *insn,
			     unsigned int *data)
{
	data[1] = 0;

	return insn->n;
}

static void ni_rtsi_init(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;

	/*  Initialises the RTSI bus signal switch to a default state */

	/*
	 * Use 10MHz instead of 20MHz for RTSI clock frequency. Appears
	 * to have no effect, at least on pxi-6281, which always uses
	 * 20MHz rtsi clock frequency
	 */
	devpriv->clock_and_fout2 = NI_M_CLK_FOUT2_RTSI_10MHZ;
	/*  Set clock mode to internal */
	if (ni_set_master_clock(dev, NI_MIO_INTERNAL_CLOCK, 0) < 0)
		dev_err(dev->class_dev, "ni_set_master_clock failed, bug?\n");
	/*  default internal lines routing to RTSI bus lines */
	devpriv->rtsi_trig_a_output_reg =
	    NISTC_RTSI_TRIG(0, NI_RTSI_OUTPUT_ADR_START1) |
	    NISTC_RTSI_TRIG(1, NI_RTSI_OUTPUT_ADR_START2) |
	    NISTC_RTSI_TRIG(2, NI_RTSI_OUTPUT_SCLKG) |
	    NISTC_RTSI_TRIG(3, NI_RTSI_OUTPUT_DACUPDN);
	ni_stc_writew(dev, devpriv->rtsi_trig_a_output_reg,
		      NISTC_RTSI_TRIGA_OUT_REG);
	devpriv->rtsi_trig_b_output_reg =
	    NISTC_RTSI_TRIG(4, NI_RTSI_OUTPUT_DA_START1) |
	    NISTC_RTSI_TRIG(5, NI_RTSI_OUTPUT_G_SRC0) |
	    NISTC_RTSI_TRIG(6, NI_RTSI_OUTPUT_G_GATE0);
	if (devpriv->is_m_series)
		devpriv->rtsi_trig_b_output_reg |=
		    NISTC_RTSI_TRIG(7, NI_RTSI_OUTPUT_RTSI_OSC);
	ni_stc_writew(dev, devpriv->rtsi_trig_b_output_reg,
		      NISTC_RTSI_TRIGB_OUT_REG);

	/*
	 * Sets the source and direction of the 4 on board lines
	 * ni_stc_writew(dev, 0, NISTC_RTSI_BOARD_REG);
	 */
}

#ifdef PCIDMA
static int ni_gpct_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
	struct ni_gpct *counter = s->private;
	int retval;

	retval = ni_request_gpct_mite_channel(dev, counter->counter_index,
					      COMEDI_INPUT);
	if (retval) {
		dev_err(dev->class_dev,
			"no dma channel available for use by counter\n");
		return retval;
	}
	ni_tio_acknowledge(counter);
	ni_e_series_enable_second_irq(dev, counter->counter_index, 1);

	return ni_tio_cmd(dev, s);
}

static int ni_gpct_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
	struct ni_gpct *counter = s->private;
	int retval;

	retval = ni_tio_cancel(counter);
	ni_e_series_enable_second_irq(dev, counter->counter_index, 0);
	ni_release_gpct_mite_channel(dev, counter->counter_index);
	return retval;
}
#endif

static irqreturn_t ni_E_interrupt(int irq, void *d)
{
	struct comedi_device *dev = d;
	struct comedi_subdevice *s_ai = dev->read_subdev;
	struct comedi_subdevice *s_ao = dev->write_subdev;
	unsigned short a_status;
	unsigned short b_status;
	unsigned long flags;
#ifdef PCIDMA
	struct ni_private *devpriv = dev->private;
#endif

	if (!dev->attached)
		return IRQ_NONE;
	smp_mb();		/* make sure dev->attached is checked */

	/*  lock to avoid race with comedi_poll */
	spin_lock_irqsave(&dev->spinlock, flags);
	a_status = ni_stc_readw(dev, NISTC_AI_STATUS1_REG);
	b_status = ni_stc_readw(dev, NISTC_AO_STATUS1_REG);
#ifdef PCIDMA
	if (devpriv->mite) {
		unsigned long flags_too;

		spin_lock_irqsave(&devpriv->mite_channel_lock, flags_too);
		if (s_ai && devpriv->ai_mite_chan)
			mite_ack_linkc(devpriv->ai_mite_chan, s_ai, false);
		if (s_ao && devpriv->ao_mite_chan)
			mite_ack_linkc(devpriv->ao_mite_chan, s_ao, false);
		spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags_too);
	}
#endif
	ack_a_interrupt(dev, a_status);
	ack_b_interrupt(dev, b_status);
	if (s_ai) {
		if (a_status & NISTC_AI_STATUS1_INTA)
			handle_a_interrupt(dev, s_ai, a_status);
		/* handle any interrupt or dma events */
		comedi_handle_events(dev, s_ai);
	}
	if (s_ao) {
		if (b_status & NISTC_AO_STATUS1_INTB)
			handle_b_interrupt(dev, s_ao, b_status);
		/* handle any interrupt or dma events */
		comedi_handle_events(dev, s_ao);
	}
	handle_gpct_interrupt(dev, 0);
	handle_gpct_interrupt(dev, 1);
#ifdef PCIDMA
	if (devpriv->is_m_series)
		handle_cdio_interrupt(dev);
#endif

	spin_unlock_irqrestore(&dev->spinlock, flags);
	return IRQ_HANDLED;
}

static int ni_alloc_private(struct comedi_device *dev)
{
	struct ni_private *devpriv;

	devpriv = comedi_alloc_devpriv(dev, sizeof(*devpriv));
	if (!devpriv)
		return -ENOMEM;

	spin_lock_init(&devpriv->window_lock);
	spin_lock_init(&devpriv->soft_reg_copy_lock);
	spin_lock_init(&devpriv->mite_channel_lock);

	return 0;
}

static int ni_E_init(struct comedi_device *dev,
		     unsigned int interrupt_pin, unsigned int irq_polarity)
{
	const struct ni_board_struct *board = dev->board_ptr;
	struct ni_private *devpriv = dev->private;
	struct comedi_subdevice *s;
	int ret;
	int i;

	if (board->n_aochan > MAX_N_AO_CHAN) {
		dev_err(dev->class_dev, "bug! n_aochan > MAX_N_AO_CHAN\n");
		return -EINVAL;
	}

	/* initialize clock dividers */
	devpriv->clock_and_fout = NISTC_CLK_FOUT_SLOW_DIV2 |
				  NISTC_CLK_FOUT_SLOW_TIMEBASE |
				  NISTC_CLK_FOUT_TO_BOARD_DIV2 |
				  NISTC_CLK_FOUT_TO_BOARD;
	if (!devpriv->is_6xxx) {
		/* BEAM is this needed for PCI-6143 ?? */
		devpriv->clock_and_fout |= (NISTC_CLK_FOUT_AI_OUT_DIV2 |
					    NISTC_CLK_FOUT_AO_OUT_DIV2);
	}
	ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);

	ret = comedi_alloc_subdevices(dev, NI_NUM_SUBDEVICES);
	if (ret)
		return ret;

	/* Analog Input subdevice */
	s = &dev->subdevices[NI_AI_SUBDEV];
	if (board->n_adchan) {
		s->type		= COMEDI_SUBD_AI;
		s->subdev_flags	= SDF_READABLE | SDF_DIFF | SDF_DITHER;
		if (!devpriv->is_611x)
			s->subdev_flags	|= SDF_GROUND | SDF_COMMON | SDF_OTHER;
		if (board->ai_maxdata > 0xffff)
			s->subdev_flags	|= SDF_LSAMPL;
		if (devpriv->is_m_series)
			s->subdev_flags	|= SDF_SOFT_CALIBRATED;
		s->n_chan	= board->n_adchan;
		s->maxdata	= board->ai_maxdata;
		s->range_table	= ni_range_lkup[board->gainlkup];
		s->insn_read	= ni_ai_insn_read;
		s->insn_config	= ni_ai_insn_config;
		if (dev->irq) {
			dev->read_subdev = s;
			s->subdev_flags	|= SDF_CMD_READ;
			s->len_chanlist	= 512;
			s->do_cmdtest	= ni_ai_cmdtest;
			s->do_cmd	= ni_ai_cmd;
			s->cancel	= ni_ai_reset;
			s->poll		= ni_ai_poll;
			s->munge	= ni_ai_munge;

			if (devpriv->mite)
				s->async_dma_dir = DMA_FROM_DEVICE;
		}

		/* reset the analog input configuration */
		ni_ai_reset(dev, s);
	} else {
		s->type		= COMEDI_SUBD_UNUSED;
	}

	/* Analog Output subdevice */
	s = &dev->subdevices[NI_AO_SUBDEV];
	if (board->n_aochan) {
		s->type		= COMEDI_SUBD_AO;
		s->subdev_flags	= SDF_WRITABLE | SDF_DEGLITCH | SDF_GROUND;
		if (devpriv->is_m_series)
			s->subdev_flags	|= SDF_SOFT_CALIBRATED;
		s->n_chan	= board->n_aochan;
		s->maxdata	= board->ao_maxdata;
		s->range_table	= board->ao_range_table;
		s->insn_config	= ni_ao_insn_config;
		s->insn_write	= ni_ao_insn_write;

		ret = comedi_alloc_subdev_readback(s);
		if (ret)
			return ret;

		/*
		 * Along with the IRQ we need either a FIFO or DMA for
		 * async command support.
		 */
		if (dev->irq && (board->ao_fifo_depth || devpriv->mite)) {
			dev->write_subdev = s;
			s->subdev_flags	|= SDF_CMD_WRITE;
			s->len_chanlist	= s->n_chan;
			s->do_cmdtest	= ni_ao_cmdtest;
			s->do_cmd	= ni_ao_cmd;
			s->cancel	= ni_ao_reset;
			if (!devpriv->is_m_series)
				s->munge	= ni_ao_munge;

			if (devpriv->mite)
				s->async_dma_dir = DMA_TO_DEVICE;
		}

		if (devpriv->is_67xx)
			init_ao_67xx(dev, s);

		/* reset the analog output configuration */
		ni_ao_reset(dev, s);
	} else {
		s->type		= COMEDI_SUBD_UNUSED;
	}

	/* Digital I/O subdevice */
	s = &dev->subdevices[NI_DIO_SUBDEV];
	s->type		= COMEDI_SUBD_DIO;
	s->subdev_flags	= SDF_WRITABLE | SDF_READABLE;
	s->n_chan	= board->has_32dio_chan ? 32 : 8;
	s->maxdata	= 1;
	s->range_table	= &range_digital;
	if (devpriv->is_m_series) {
#ifdef PCIDMA
		s->subdev_flags	|= SDF_LSAMPL;
		s->insn_bits	= ni_m_series_dio_insn_bits;
		s->insn_config	= ni_m_series_dio_insn_config;
		if (dev->irq) {
			s->subdev_flags	|= SDF_CMD_WRITE /* | SDF_CMD_READ */;
			s->len_chanlist	= s->n_chan;
			s->do_cmdtest	= ni_cdio_cmdtest;
			s->do_cmd	= ni_cdio_cmd;
			s->cancel	= ni_cdio_cancel;

			/* M-series boards use DMA */
			s->async_dma_dir = DMA_BIDIRECTIONAL;
		}

		/* reset DIO and set all channels to inputs */
		ni_writel(dev, NI_M_CDO_CMD_RESET |
			       NI_M_CDI_CMD_RESET,
			  NI_M_CDIO_CMD_REG);
		ni_writel(dev, s->io_bits, NI_M_DIO_DIR_REG);
#endif /* PCIDMA */
	} else {
		s->insn_bits	= ni_dio_insn_bits;
		s->insn_config	= ni_dio_insn_config;

		/* set all channels to inputs */
		devpriv->dio_control = NISTC_DIO_CTRL_DIR(s->io_bits);
		ni_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
	}

	/* 8255 device */
	s = &dev->subdevices[NI_8255_DIO_SUBDEV];
	if (board->has_8255) {
		ret = subdev_8255_init(dev, s, ni_8255_callback,
				       NI_E_8255_BASE);
		if (ret)
			return ret;
	} else {
		s->type = COMEDI_SUBD_UNUSED;
	}

	/* formerly general purpose counter/timer device, but no longer used */
	s = &dev->subdevices[NI_UNUSED_SUBDEV];
	s->type = COMEDI_SUBD_UNUSED;

	/* Calibration subdevice */
	s = &dev->subdevices[NI_CALIBRATION_SUBDEV];
	s->type		= COMEDI_SUBD_CALIB;
	s->subdev_flags	= SDF_INTERNAL;
	s->n_chan	= 1;
	s->maxdata	= 0;
	if (devpriv->is_m_series) {
		/* internal PWM output used for AI nonlinearity calibration */
		s->insn_config	= ni_m_series_pwm_config;

		ni_writel(dev, 0x0, NI_M_CAL_PWM_REG);
	} else if (devpriv->is_6143) {
		/* internal PWM output used for AI nonlinearity calibration */
		s->insn_config	= ni_6143_pwm_config;
	} else {
		s->subdev_flags	|= SDF_WRITABLE;
		s->insn_read	= ni_calib_insn_read;
		s->insn_write	= ni_calib_insn_write;

		/* setup the caldacs and find the real n_chan and maxdata */
		caldac_setup(dev, s);
	}

	/* EEPROM subdevice */
	s = &dev->subdevices[NI_EEPROM_SUBDEV];
	s->type		= COMEDI_SUBD_MEMORY;
	s->subdev_flags	= SDF_READABLE | SDF_INTERNAL;
	s->maxdata	= 0xff;
	if (devpriv->is_m_series) {
		s->n_chan	= M_SERIES_EEPROM_SIZE;
		s->insn_read	= ni_m_series_eeprom_insn_read;
	} else {
		s->n_chan	= 512;
		s->insn_read	= ni_eeprom_insn_read;
	}

	/* Digital I/O (PFI) subdevice */
	s = &dev->subdevices[NI_PFI_DIO_SUBDEV];
	s->type		= COMEDI_SUBD_DIO;
	s->subdev_flags	= SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
	s->maxdata	= 1;
	if (devpriv->is_m_series) {
		s->n_chan	= 16;
		s->insn_bits	= ni_pfi_insn_bits;

		ni_writew(dev, s->state, NI_M_PFI_DO_REG);
		for (i = 0; i < NUM_PFI_OUTPUT_SELECT_REGS; ++i) {
			ni_writew(dev, devpriv->pfi_output_select_reg[i],
				  NI_M_PFI_OUT_SEL_REG(i));
		}
	} else {
		s->n_chan	= 10;
	}
	s->insn_config	= ni_pfi_insn_config;

	ni_set_bits(dev, NISTC_IO_BIDIR_PIN_REG, ~0, 0);

	/* cs5529 calibration adc */
	s = &dev->subdevices[NI_CS5529_CALIBRATION_SUBDEV];
	if (devpriv->is_67xx) {
		s->type = COMEDI_SUBD_AI;
		s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_INTERNAL;
		/*  one channel for each analog output channel */
		s->n_chan = board->n_aochan;
		s->maxdata = (1 << 16) - 1;
		s->range_table = &range_unknown;	/* XXX */
		s->insn_read = cs5529_ai_insn_read;
		s->insn_config = NULL;
		init_cs5529(dev);
	} else {
		s->type = COMEDI_SUBD_UNUSED;
	}

	/* Serial */
	s = &dev->subdevices[NI_SERIAL_SUBDEV];
	s->type = COMEDI_SUBD_SERIAL;
	s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
	s->n_chan = 1;
	s->maxdata = 0xff;
	s->insn_config = ni_serial_insn_config;
	devpriv->serial_interval_ns = 0;
	devpriv->serial_hw_mode = 0;

	/* RTSI */
	s = &dev->subdevices[NI_RTSI_SUBDEV];
	s->type = COMEDI_SUBD_DIO;
	s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
	s->n_chan = 8;
	s->maxdata = 1;
	s->insn_bits = ni_rtsi_insn_bits;
	s->insn_config = ni_rtsi_insn_config;
	ni_rtsi_init(dev);

	/* allocate and initialize the gpct counter device */
	devpriv->counter_dev = ni_gpct_device_construct(dev,
					ni_gpct_write_register,
					ni_gpct_read_register,
					(devpriv->is_m_series)
						? ni_gpct_variant_m_series
						: ni_gpct_variant_e_series,
					NUM_GPCT);
	if (!devpriv->counter_dev)
		return -ENOMEM;

	/* Counter (gpct) subdevices */
	for (i = 0; i < NUM_GPCT; ++i) {
		struct ni_gpct *gpct = &devpriv->counter_dev->counters[i];

		/* setup and initialize the counter */
		gpct->chip_index = 0;
		gpct->counter_index = i;
		ni_tio_init_counter(gpct);

		s = &dev->subdevices[NI_GPCT_SUBDEV(i)];
		s->type		= COMEDI_SUBD_COUNTER;
		s->subdev_flags	= SDF_READABLE | SDF_WRITABLE | SDF_LSAMPL;
		s->n_chan	= 3;
		s->maxdata	= (devpriv->is_m_series) ? 0xffffffff
							 : 0x00ffffff;
		s->insn_read	= ni_tio_insn_read;
		s->insn_write	= ni_tio_insn_write;
		s->insn_config	= ni_tio_insn_config;
#ifdef PCIDMA
		if (dev->irq && devpriv->mite) {
			s->subdev_flags	|= SDF_CMD_READ /* | SDF_CMD_WRITE */;
			s->len_chanlist	= 1;
			s->do_cmdtest	= ni_tio_cmdtest;
			s->do_cmd	= ni_gpct_cmd;
			s->cancel	= ni_gpct_cancel;

			s->async_dma_dir = DMA_BIDIRECTIONAL;
		}
#endif
		s->private	= gpct;
	}

	/* Frequency output subdevice */
	s = &dev->subdevices[NI_FREQ_OUT_SUBDEV];
	s->type		= COMEDI_SUBD_COUNTER;
	s->subdev_flags	= SDF_READABLE | SDF_WRITABLE;
	s->n_chan	= 1;
	s->maxdata	= 0xf;
	s->insn_read	= ni_freq_out_insn_read;
	s->insn_write	= ni_freq_out_insn_write;
	s->insn_config	= ni_freq_out_insn_config;

	if (dev->irq) {
		ni_stc_writew(dev,
			      (irq_polarity ? NISTC_INT_CTRL_INT_POL : 0) |
			      (NISTC_INT_CTRL_3PIN_INT & 0) |
			      NISTC_INT_CTRL_INTA_ENA |
			      NISTC_INT_CTRL_INTB_ENA |
			      NISTC_INT_CTRL_INTA_SEL(interrupt_pin) |
			      NISTC_INT_CTRL_INTB_SEL(interrupt_pin),
			      NISTC_INT_CTRL_REG);
	}

	/* DMA setup */
	ni_writeb(dev, devpriv->ai_ao_select_reg, NI_E_DMA_AI_AO_SEL_REG);
	ni_writeb(dev, devpriv->g0_g1_select_reg, NI_E_DMA_G0_G1_SEL_REG);

	if (devpriv->is_6xxx) {
		ni_writeb(dev, 0, NI611X_MAGIC_REG);
	} else if (devpriv->is_m_series) {
		int channel;

		for (channel = 0; channel < board->n_aochan; ++channel) {
			ni_writeb(dev, 0xf,
				  NI_M_AO_WAVEFORM_ORDER_REG(channel));
			ni_writeb(dev, 0x0,
				  NI_M_AO_REF_ATTENUATION_REG(channel));
		}
		ni_writeb(dev, 0x0, NI_M_AO_CALIB_REG);
	}

	return 0;
}

static void mio_common_detach(struct comedi_device *dev)
{
	struct ni_private *devpriv = dev->private;

	if (devpriv)
		ni_gpct_device_destroy(devpriv->counter_dev);
}