aboutsummaryrefslogblamecommitdiffstats
path: root/drivers/staging/meilhaus/me4600_ao.c
blob: eb472692a7c5645914f37de08b8041295e3b6223 (plain) (tree)
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
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
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
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
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
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
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







































                                                                          

                          

















                            
                                                                      



                                                                                
                                                                   

                                                               
                                                                



                                                                        
                                                           



                                                                             
                                                                     

                                                        
                                                                    

                                                                   
                                                                    





















                                                                                                           
                                                                  



                                                                       
                                                                








                                                                               
                                                              





                                                                         
                                                               





                                                                         
                                                                
                                                         
                                                                      
                                                
                                                                   



                                                                         
                                                                    




                                                                               
                                                               




                                                                              
                                                                





                                                                           
                                                              




                                                              
                                                               





                                                                         
                                                        

                                                                     
                                                                               



                                                   
                                                                    



                                                  
                                                                            



                                                 
                                                                            



                                                   
                                                                


                                           
                                                                  


            
                                                                  








































































                                                                                                           
                                                                











































































































































































                                                                                                               
                                                              


















































































                                                                                                                                       
                                                               
























































































































































































































































































































































































































































                                                                                                                                                                                                                                               
                                                                
                                                         
                                                                      
                                                
                                                                   






























                                                                                
                                                                












































































































































































































































































































                                                                                                                             
                                                                    















































































                                                                                                        
                                                               



















































































































































































































































































































































































































































                                                                                                                                                                                               
                                                                
































































































                                                                                                                                          
                                                              







































































































                                                                                                       
                                                               






























































































































































































































                                                                                                                                                                                                          
                                                       
















                                                                                
                                                                       










































































































































































































                                                                                                                                                                                   

                                                                          




























































































































































































                                                                                   

                                                       












                                                                         
                                                               



















































                                                                                                                        
                                                                               































































                                                                                                                                                               
                                                                    




































































                                                                                                                                                               
                                                                            
























































                                                                                                                                                               
                                                                            






























                                                                                           
                                                                 








                                        

                                                                               
                                                                

















































































































































































































































































































                                                                                                                                                                    
                                                               





                                 
                                                                  








































                                                                                
                                                                













































































































































































































































































                                                                                                 
      







                                                                     
                                                              



































                                                                        
                                                               


















































































































































                                                                                                          
      





                          
                                                                
                                                         
                                                                      
                                                
                                                                   



















































































































































































































































































































                                                                                    
      







                                                                     
                                                                    













































































                                                                                  
                                                             













                                                                           
                                                               











































































































































































































































































































































































































































































































































                                                                                                                                                                    
      





                          
                                                                























































                                                                                       
      





                          
                                                              








































                                                                                
      





                          
                                                               




















































































































































































































































































































































































































































































































































                                                                                                              
      





                          
                                                       























































































































































































































                                                                                                                              

                                                                          
































































































































































                                                                                
                                                                      

































                                                                               
                                                                   
















                                                              
                                                                






















                                                                       
                                                           
































                                                                              
                                                                     











                                                       
                                                                    













                                                                               
                                                                               













































                                                                               
/**
 * @file me4600_ao.c
 *
 * @brief ME-4000 analog output subdevice instance.
 * @note Copyright (C) 2007 Meilhaus Electronic GmbH (support@meilhaus.de)
 * @author Guenter Gebhardt
 * @author Krzysztof Gantzke	(k.gantzke@meilhaus.de)
 */

/*
 * Copyright (C) 2007 Meilhaus Electronic GmbH (support@meilhaus.de)
 *
 * This file 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#ifndef __KERNEL__
#  define __KERNEL__
#endif

///Common part. (For normal and Bosch builds.)

/* Includes
 */

#include <linux/module.h>

#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <linux/types.h>
#include <linux/version.h>
#include <linux/interrupt.h>
#include <linux/delay.h>

#include "medefines.h"
#include "meinternal.h"
#include "meerror.h"

#include "medebug.h"
#include "meids.h"
#include "me4600_reg.h"
#include "me4600_ao_reg.h"
#include "me4600_ao.h"

/* Defines
 */

static int me4600_ao_query_range_by_min_max(me_subdevice_t *subdevice,
					    int unit,
					    int *min,
					    int *max, int *maxdata, int *range);

static int me4600_ao_query_number_ranges(me_subdevice_t *subdevice,
					 int unit, int *count);

static int me4600_ao_query_range_info(me_subdevice_t *subdevice,
				      int range,
				      int *unit,
				      int *min, int *max, int *maxdata);

static int me4600_ao_query_timer(me_subdevice_t *subdevice,
				 int timer,
				 int *base_frequency,
				 long long *min_ticks, long long *max_ticks);

static int me4600_ao_query_number_channels(me_subdevice_t *subdevice,
					   int *number);

static int me4600_ao_query_subdevice_type(me_subdevice_t *subdevice,
					  int *type, int *subtype);

static int me4600_ao_query_subdevice_caps(me_subdevice_t *subdevice,
					  int *caps);

static int me4600_ao_query_subdevice_caps_args(struct me_subdevice *subdevice,
					       int cap, int *args, int count);

#ifndef BOSCH
/// @note NORMAL BUILD
/// @author Krzysztof Gantzke   (k.gantzke@meilhaus.de)
/* Includes
 */

# include <linux/workqueue.h>

/* Defines
 */

/** Remove subdevice.
*/
static void me4600_ao_destructor(struct me_subdevice *subdevice);

/** Reset subdevice. Stop all actions. Reset registry. Disable FIFO. Set output to 0V and status to 'none'.
*/
static int me4600_ao_io_reset_subdevice(me_subdevice_t *subdevice,
					struct file *filep, int flags);

/** Set output as single
*/
static int me4600_ao_io_single_config(me_subdevice_t *subdevice,
				      struct file *filep,
				      int channel,
				      int single_config,
				      int ref,
				      int trig_chan,
				      int trig_type, int trig_edge, int flags);

/** Pass to user actual value of output.
*/
static int me4600_ao_io_single_read(me_subdevice_t *subdevice,
				    struct file *filep,
				    int channel,
				    int *value, int time_out, int flags);

/** Write to output requed value.
*/
static int me4600_ao_io_single_write(me_subdevice_t *subdevice,
				     struct file *filep,
				     int channel,
				     int value, int time_out, int flags);

/** Set output as streamed device.
*/
static int me4600_ao_io_stream_config(me_subdevice_t *subdevice,
				      struct file *filep,
				      meIOStreamConfig_t *config_list,
				      int count,
				      meIOStreamTrigger_t *trigger,
				      int fifo_irq_threshold, int flags);

/** Wait for / Check empty space in buffer.
*/
static int me4600_ao_io_stream_new_values(me_subdevice_t *subdevice,
					  struct file *filep,
					  int time_out, int *count, int flags);

/** Start streaming.
*/
static int me4600_ao_io_stream_start(me_subdevice_t *subdevice,
				     struct file *filep,
				     int start_mode, int time_out, int flags);

/** Check actual state. / Wait for end.
*/
static int me4600_ao_io_stream_status(me_subdevice_t *subdevice,
				      struct file *filep,
				      int wait,
				      int *status, int *values, int flags);

/** Stop streaming.
*/
static int me4600_ao_io_stream_stop(me_subdevice_t *subdevice,
				    struct file *filep,
				    int stop_mode, int flags);

/** Write datas to buffor.
*/
static int me4600_ao_io_stream_write(me_subdevice_t *subdevice,
				     struct file *filep,
				     int write_mode,
				     int *values, int *count, int flags);

/** Interrupt handler. Copy from buffer to FIFO.
*/
static irqreturn_t me4600_ao_isr(int irq, void *dev_id);
/** Copy data from circular buffer to fifo (fast) in wraparound mode.
*/
inline int ao_write_data_wraparound(me4600_ao_subdevice_t *instance, int count,
				    int start_pos);

/** Copy data from circular buffer to fifo (fast).
*/
inline int ao_write_data(me4600_ao_subdevice_t *instance, int count,
			 int start_pos);

/** Copy data from circular buffer to fifo (slow).
*/
inline int ao_write_data_pooling(me4600_ao_subdevice_t *instance, int count,
				 int start_pos);

/** Copy data from user space to circular buffer.
*/
inline int ao_get_data_from_user(me4600_ao_subdevice_t *instance, int count,
				 int *user_values);

/** Stop presentation. Preserve FIFOs.
*/
inline int ao_stop_immediately(me4600_ao_subdevice_t *instance);

/** Task for asynchronical state verifying.
*/
static void me4600_ao_work_control_task(struct work_struct *work);
/* Functions
 */

static int me4600_ao_io_reset_subdevice(me_subdevice_t *subdevice,
					struct file *filep, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	uint32_t tmp;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (flags) {
		PERROR("Invalid flag specified.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	ME_SUBDEVICE_ENTER;

	instance->status = ao_status_none;
	instance->ao_control_task_flag = 0;
	cancel_delayed_work(&instance->ao_control_task);
	instance->timeout.delay = 0;
	instance->timeout.start_time = jiffies;

	//Stop state machine.
	err = ao_stop_immediately(instance);

	//Remove from synchronous start.
	spin_lock(instance->preload_reg_lock);
	tmp = inl(instance->preload_reg);
	tmp &=
	    ~((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->
	      ao_idx);
	outl(tmp, instance->preload_reg);
	PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->preload_reg - instance->reg_base, tmp);
	*instance->preload_flags &=
	    ~((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->
	      ao_idx);
	spin_unlock(instance->preload_reg_lock);

	//Set single mode, dissable FIFO, dissable external trigger, set output to analog, block interrupt.
	outl(ME4600_AO_MODE_SINGLE | ME4600_AO_CTRL_BIT_STOP |
	     ME4600_AO_CTRL_BIT_IMMEDIATE_STOP | ME4600_AO_CTRL_BIT_RESET_IRQ,
	     instance->ctrl_reg);
	PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->ctrl_reg - instance->reg_base,
		   ME4600_AO_MODE_SINGLE | ME4600_AO_CTRL_BIT_STOP |
		   ME4600_AO_CTRL_BIT_IMMEDIATE_STOP |
		   ME4600_AO_CTRL_BIT_RESET_IRQ);

	//Set output to 0V
	outl(0x8000, instance->single_reg);
	PDEBUG_REG("single_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->single_reg - instance->reg_base, 0x8000);

	instance->circ_buf.head = 0;
	instance->circ_buf.tail = 0;
	instance->preloaded_count = 0;
	instance->data_count = 0;
	instance->single_value = 0x8000;
	instance->single_value_in_fifo = 0x8000;

	//Set status to signal that device is unconfigured.
	instance->status = ao_status_none;

	//Signal reset if user is on wait.
	wake_up_interruptible_all(&instance->wait_queue);

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_single_config(me_subdevice_t *subdevice,
				      struct file *filep,
				      int channel,
				      int single_config,
				      int ref,
				      int trig_chan,
				      int trig_type, int trig_edge, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	uint32_t ctrl;
	uint32_t sync;
	unsigned long cpu_flags;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	// Checking parameters
	if (flags) {
		PERROR
		    ("Invalid flag specified. Must be ME_IO_SINGLE_CONFIG_NO_FLAGS.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	switch (trig_type) {
	case ME_TRIG_TYPE_SW:
		if (trig_edge != ME_TRIG_EDGE_NONE) {
			PERROR
			    ("Invalid trigger edge. Software trigger has not edge.\n");
			return ME_ERRNO_INVALID_TRIG_EDGE;
		}
		break;

	case ME_TRIG_TYPE_EXT_DIGITAL:
		switch (trig_edge) {
		case ME_TRIG_EDGE_ANY:
		case ME_TRIG_EDGE_RISING:
		case ME_TRIG_EDGE_FALLING:
			break;

		default:
			PERROR("Invalid trigger edge.\n");
			return ME_ERRNO_INVALID_TRIG_EDGE;
		}
		break;

	default:
		PERROR
		    ("Invalid trigger type. Trigger must be software or digital.\n");
		return ME_ERRNO_INVALID_TRIG_TYPE;
	}

	if ((trig_chan != ME_TRIG_CHAN_DEFAULT)
	    && (trig_chan != ME_TRIG_CHAN_SYNCHRONOUS)) {
		PERROR("Invalid trigger channel specified.\n");
		return ME_ERRNO_INVALID_TRIG_CHAN;
	}

	if (ref != ME_REF_AO_GROUND) {
		PERROR
		    ("Invalid reference. Analog outputs have to have got REF_AO_GROUND.\n");
		return ME_ERRNO_INVALID_REF;
	}

	if (single_config != 0) {
		PERROR
		    ("Invalid single config specified. Only one range for anlog outputs is available.\n");
		return ME_ERRNO_INVALID_SINGLE_CONFIG;
	}

	if (channel != 0) {
		PERROR
		    ("Invalid channel number specified. Analog output have only one channel.\n");
		return ME_ERRNO_INVALID_CHANNEL;
	}

	ME_SUBDEVICE_ENTER;

	//Subdevice running in stream mode!
	if ((instance->status >= ao_status_stream_run_wait)
	    && (instance->status < ao_status_stream_end)) {
		PERROR("Subdevice is busy.\n");
		ME_SUBDEVICE_EXIT;

		return ME_ERRNO_SUBDEVICE_BUSY;
	}
/// @note For single all calls (config and write) are erasing previous state!

	instance->status = ao_status_none;

	// Correct single mirrors
	instance->single_value_in_fifo = instance->single_value;

	//Stop device
	err = ao_stop_immediately(instance);
	if (err) {
		PERROR_CRITICAL("FSM IS BUSY!\n");
		ME_SUBDEVICE_EXIT;

		return ME_ERRNO_SUBDEVICE_BUSY;
	}
	// Set control register.
	spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
	// Set stop bit. Stop streaming mode.
	ctrl = inl(instance->ctrl_reg);
	//Reset all bits.
	ctrl = ME4600_AO_CTRL_BIT_IMMEDIATE_STOP | ME4600_AO_CTRL_BIT_STOP;

	if (trig_type == ME_TRIG_TYPE_EXT_DIGITAL) {
		PINFO("External digital trigger.\n");

		if (trig_edge == ME_TRIG_EDGE_ANY) {
//                              ctrl |= ME4600_AO_CTRL_BIT_EX_TRIG_EDGE | ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH;
			instance->ctrl_trg =
			    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE |
			    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH;
		} else if (trig_edge == ME_TRIG_EDGE_FALLING) {
//                              ctrl |= ME4600_AO_CTRL_BIT_EX_TRIG_EDGE;
			instance->ctrl_trg = ME4600_AO_CTRL_BIT_EX_TRIG_EDGE;
		} else if (trig_edge == ME_TRIG_EDGE_RISING) {
			instance->ctrl_trg = 0x0;
		}
	} else if (trig_type == ME_TRIG_TYPE_SW) {
		PDEBUG("Software trigger\n");
		instance->ctrl_trg = 0x0;
	}

	outl(ctrl, instance->ctrl_reg);
	PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->ctrl_reg - instance->reg_base, ctrl);
	spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

	// Set preload/synchronization register.
	spin_lock(instance->preload_reg_lock);
	if (trig_type == ME_TRIG_TYPE_SW) {
		*instance->preload_flags &=
		    ~(ME4600_AO_SYNC_EXT_TRIG << instance->ao_idx);
	} else			//if (trig_type == ME_TRIG_TYPE_EXT_DIGITAL)
	{
		*instance->preload_flags |=
		    ME4600_AO_SYNC_EXT_TRIG << instance->ao_idx;
	}

	if (trig_chan == ME_TRIG_CHAN_DEFAULT) {
		*instance->preload_flags &=
		    ~(ME4600_AO_SYNC_HOLD << instance->ao_idx);
	} else			//if (trig_chan == ME_TRIG_CHAN_SYNCHRONOUS)
	{
		*instance->preload_flags |=
		    ME4600_AO_SYNC_HOLD << instance->ao_idx;
	}

	//Reset hardware register
	sync = inl(instance->preload_reg);
	PDEBUG_REG("preload_reg inl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->preload_reg - instance->reg_base, sync);
	sync &= ~(ME4600_AO_SYNC_EXT_TRIG << instance->ao_idx);
	sync |= ME4600_AO_SYNC_HOLD << instance->ao_idx;

	//Output configured in default (safe) mode.
	outl(sync, instance->preload_reg);
	PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->preload_reg - instance->reg_base, sync);
	spin_unlock(instance->preload_reg_lock);

	instance->status = ao_status_single_configured;

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_single_read(me_subdevice_t *subdevice,
				    struct file *filep,
				    int channel,
				    int *value, int time_out, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;

	unsigned long j;
	unsigned long delay = 0;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (flags & ~ME_IO_SINGLE_NONBLOCKING) {
		PERROR("Invalid flag specified. %d\n", flags);
		return ME_ERRNO_INVALID_FLAGS;
	}

	if (time_out < 0) {
		PERROR("Invalid timeout specified.\n");
		return ME_ERRNO_INVALID_TIMEOUT;
	}

	if (channel != 0) {
		PERROR("Invalid channel number specified.\n");
		return ME_ERRNO_INVALID_CHANNEL;
	}

	if ((instance->status >= ao_status_stream_configured)
	    && (instance->status <= ao_status_stream_end)) {
		PERROR("Subdevice not configured to work in single mode!\n");
		return ME_ERRNO_PREVIOUS_CONFIG;
	}

	ME_SUBDEVICE_ENTER;
	if ((!flags) && (instance->status == ao_status_single_run_wait)) {	//Blocking mode. Wait for trigger.
		if (time_out) {
			delay = (time_out * HZ) / 1000;
			if (delay == 0)
				delay = 1;
		}

		j = jiffies;

		//Only runing process will interrupt this call. Events are signaled when status change. This procedure has own timeout.
		wait_event_interruptible_timeout(instance->wait_queue,
						 (instance->status !=
						  ao_status_single_run_wait),
						 (delay) ? delay +
						 1 : LONG_MAX);

		if (instance->status == ao_status_none) {
			PDEBUG("Single canceled.\n");
			err = ME_ERRNO_CANCELLED;
		}

		if (signal_pending(current)) {
			PERROR("Wait on start of state machine interrupted.\n");
			instance->status = ao_status_none;
			ao_stop_immediately(instance);
			err = ME_ERRNO_SIGNAL;
		}

		if ((delay) && ((jiffies - j) >= delay)) {

			PDEBUG("Timeout reached.\n");
			err = ME_ERRNO_TIMEOUT;
		}

		*value =
		    (!err) ? instance->single_value_in_fifo : instance->
		    single_value;
	} else {		//Non-blocking mode
		//Read value
		*value = instance->single_value;
	}

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_single_write(me_subdevice_t *subdevice,
				     struct file *filep,
				     int channel,
				     int value, int time_out, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	unsigned long cpu_flags;
	unsigned long j;
	unsigned long delay = 0x0;

	//Registry handling variables.
	uint32_t sync_mask;
	uint32_t mode;
	uint32_t tmp;
	uint32_t ctrl;
	uint32_t status;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (flags &
	    ~(ME_IO_SINGLE_TYPE_TRIG_SYNCHRONOUS |
	      ME_IO_SINGLE_TYPE_WRITE_NONBLOCKING)) {
		PERROR("Invalid flag specified.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	if (time_out < 0) {
		PERROR("Invalid timeout specified.\n");
		return ME_ERRNO_INVALID_TIMEOUT;
	}

	if (value & ~ME4600_AO_MAX_DATA) {
		PERROR("Invalid value provided.\n");
		return ME_ERRNO_VALUE_OUT_OF_RANGE;
	}

	if (channel != 0) {
		PERROR("Invalid channel number specified.\n");
		return ME_ERRNO_INVALID_CHANNEL;
	}

	if ((instance->status == ao_status_none)
	    || (instance->status > ao_status_single_end)) {
		PERROR("Subdevice not configured to work in single mode!\n");
		return ME_ERRNO_PREVIOUS_CONFIG;
	}

	ME_SUBDEVICE_ENTER;

/// @note For single all calls (config and write) are erasing previous state!

	//Cancel control task
	PDEBUG("Cancel control task. idx=%d\n", instance->ao_idx);
	instance->ao_control_task_flag = 0;
	cancel_delayed_work(&instance->ao_control_task);

	// Correct single mirrors
	instance->single_value_in_fifo = instance->single_value;

	//Stop device
	err = ao_stop_immediately(instance);
	if (err) {
		PERROR_CRITICAL("FSM IS BUSY!\n");
		ME_SUBDEVICE_EXIT;

		return ME_ERRNO_SUBDEVICE_BUSY;
	}

	if (time_out) {
		delay = (time_out * HZ) / 1000;

		if (delay == 0)
			delay = 1;
	}

	spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);

	instance->single_value_in_fifo = value;

	ctrl = inl(instance->ctrl_reg);

	if (!instance->fifo) {	//No FIFO
		//Set the single mode.
		ctrl &= ~ME4600_AO_CTRL_MODE_MASK;

		//Write value
		PDEBUG("Write value\n");
		outl(value, instance->single_reg);
		PDEBUG_REG("single_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->single_reg - instance->reg_base, value);
	} else {		// mix-mode
		//Set speed
		outl(ME4600_AO_MIN_CHAN_TICKS - 1, instance->timer_reg);
		PDEBUG_REG("timer_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->timer_reg - instance->reg_base,
			   (int)ME4600_AO_MIN_CHAN_TICKS);
		instance->hardware_stop_delay = HZ / 10;	//100ms

		status = inl(instance->status_reg);

		//Set the continous mode.
		ctrl &= ~ME4600_AO_CTRL_MODE_MASK;
		ctrl |= ME4600_AO_MODE_CONTINUOUS;

		//Prepare FIFO
		if (!(ctrl & ME4600_AO_CTRL_BIT_ENABLE_FIFO)) {	//FIFO wasn't enabeled. Do it.
			PINFO("Enableing FIFO.\n");
			ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			ctrl |=
			    ME4600_AO_CTRL_BIT_ENABLE_FIFO |
			    ME4600_AO_CTRL_BIT_RESET_IRQ;
		} else {	//Check if FIFO is empty
			if (status & ME4600_AO_STATUS_BIT_EF) {	//FIFO not empty
				PINFO("Reseting FIFO.\n");
				ctrl &=
				    ~(ME4600_AO_CTRL_BIT_ENABLE_FIFO |
				      ME4600_AO_CTRL_BIT_ENABLE_IRQ);
				ctrl |= ME4600_AO_CTRL_BIT_RESET_IRQ;
				outl(ctrl, instance->ctrl_reg);
				PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
					   instance->reg_base,
					   instance->ctrl_reg -
					   instance->reg_base, ctrl);

				ctrl |=
				    ME4600_AO_CTRL_BIT_ENABLE_FIFO |
				    ME4600_AO_CTRL_BIT_RESET_IRQ;
			} else {	//FIFO empty, only interrupt needs to be disabled!
				ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
				ctrl |= ME4600_AO_CTRL_BIT_RESET_IRQ;
			}
		}

		outl(ctrl, instance->ctrl_reg);
		PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->ctrl_reg - instance->reg_base, ctrl);

		//Write output - 1 value to FIFO
		if (instance->ao_idx & 0x1) {
			outl(value <<= 16, instance->fifo_reg);
			PDEBUG_REG("fifo_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->fifo_reg - instance->reg_base,
				   value <<= 16);
		} else {
			outl(value, instance->fifo_reg);
			PDEBUG_REG("fifo_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->fifo_reg - instance->reg_base,
				   value);
		}
	}

	mode = *instance->preload_flags >> instance->ao_idx;
	mode &= (ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG);

	PINFO("Triggering mode: 0x%x\n", mode);

	spin_lock(instance->preload_reg_lock);
	sync_mask = inl(instance->preload_reg);
	PDEBUG_REG("preload_reg inl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->preload_reg - instance->reg_base, sync_mask);
	switch (mode) {
	case 0:		//Individual software
		ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;

		if (!instance->fifo) {	// No FIFO - In this case resetting 'ME4600_AO_SYNC_HOLD' will trigger output.
			if ((sync_mask & ((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->ao_idx)) != ME4600_AO_SYNC_HOLD) {	//Now we can set correct mode. This is exception. It is set to synchronous and triggered later.
				sync_mask &=
				    ~(ME4600_AO_SYNC_EXT_TRIG << instance->
				      ao_idx);
				sync_mask |=
				    ME4600_AO_SYNC_HOLD << instance->ao_idx;

				outl(sync_mask, instance->preload_reg);
				PDEBUG_REG
				    ("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				     instance->reg_base,
				     instance->preload_reg - instance->reg_base,
				     sync_mask);
			}
		} else {	// FIFO
			if ((sync_mask & ((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->ao_idx)) != 0x0) {	//Now we can set correct mode.
				sync_mask &=
				    ~((ME4600_AO_SYNC_EXT_TRIG |
				       ME4600_AO_SYNC_HOLD) << instance->
				      ao_idx);

				outl(sync_mask, instance->preload_reg);
				PDEBUG_REG
				    ("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				     instance->reg_base,
				     instance->preload_reg - instance->reg_base,
				     sync_mask);
			}
		}
		instance->single_value = value;
		break;

	case ME4600_AO_SYNC_EXT_TRIG:	//Individual hardware
		ctrl |= ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;

		if (!instance->fifo) {	// No FIFO - In this case resetting 'ME4600_AO_SYNC_HOLD' will trigger output.
			if ((sync_mask & ((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->ao_idx)) != ME4600_AO_SYNC_HOLD) {	//Now we can set correct mode
				sync_mask &=
				    ~(ME4600_AO_SYNC_EXT_TRIG << instance->
				      ao_idx);
				sync_mask |=
				    ME4600_AO_SYNC_HOLD << instance->ao_idx;

				outl(sync_mask, instance->preload_reg);
				PDEBUG_REG
				    ("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				     instance->reg_base,
				     instance->preload_reg - instance->reg_base,
				     sync_mask);
			}
		} else {	// FIFO
			if ((sync_mask & ((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->ao_idx)) != 0x0) {	//Now we can set correct mode.
				sync_mask &=
				    ~((ME4600_AO_SYNC_EXT_TRIG |
				       ME4600_AO_SYNC_HOLD) << instance->
				      ao_idx);

				outl(sync_mask, instance->preload_reg);
				PDEBUG_REG
				    ("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				     instance->reg_base,
				     instance->preload_reg - instance->reg_base,
				     sync_mask);
			}
		}
		break;

	case ME4600_AO_SYNC_HOLD:	//Synchronous software
		ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;

//                                      if((sync_mask & ((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->ao_idx)) != ME4600_AO_SYNC_HOLD)
		if ((sync_mask & ((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->ao_idx)) != (ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG)) {	//Now we can set correct mode
			sync_mask |=
			    ME4600_AO_SYNC_EXT_TRIG << instance->ao_idx;
//                                              sync_mask &= ~(ME4600_AO_SYNC_EXT_TRIG << instance->ao_idx);
			sync_mask |= ME4600_AO_SYNC_HOLD << instance->ao_idx;

			outl(sync_mask, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   sync_mask);
		}
		break;

	case (ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG):	//Synchronous hardware
		ctrl |= ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;
		if ((sync_mask & ((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->ao_idx)) != (ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG)) {	//Now we can set correct mode
			sync_mask |=
			    (ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) <<
			    instance->ao_idx;

			outl(sync_mask, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   sync_mask);
		}
		break;
	}
//              spin_unlock(instance->preload_reg_lock);        // Moved down.

	//Activate ISM (remove 'stop' bits)
	ctrl &=
	    ~(ME4600_AO_CTRL_BIT_EX_TRIG_EDGE |
	      ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH);
	ctrl |= instance->ctrl_trg;
	ctrl &= ~(ME4600_AO_CTRL_BIT_STOP | ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);
	outl(ctrl, instance->ctrl_reg);
	PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->ctrl_reg - instance->reg_base, ctrl);
	spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

/// @note When flag 'ME_IO_SINGLE_TYPE_TRIG_SYNCHRONOUS' is set than output is triggered. ALWAYS!

	if (!instance->fifo) {	//No FIFO
		if (flags & ME_IO_SINGLE_TYPE_TRIG_SYNCHRONOUS) {	//Fired all software synchronous outputs.
			tmp = ~(*instance->preload_flags | 0xFFFF0000);
			PINFO
			    ("Fired all software synchronous outputs. mask:0x%08x\n",
			     tmp);
			tmp |= sync_mask & 0xFFFF0000;
			// Add this channel to list
			tmp &= ~(ME4600_AO_SYNC_HOLD << instance->ao_idx);

			//Fire
			PINFO("Software trigger.\n");
			outl(tmp, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   tmp);

			//Restore save settings
			outl(sync_mask, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   sync_mask);
		} else if (!mode) {	// Add this channel to list
			outl(sync_mask &
			     ~(ME4600_AO_SYNC_HOLD << instance->ao_idx),
			     instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   sync_mask & ~(ME4600_AO_SYNC_HOLD <<
						 instance->ao_idx));

			//Fire
			PINFO("Software trigger.\n");

			//Restore save settings
			outl(sync_mask, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   sync_mask);
		}

	} else {		// mix-mode - begin
		if (flags & ME_IO_SINGLE_TYPE_TRIG_SYNCHRONOUS) {	//Trigger outputs
			//Add channel to start list
			outl(sync_mask |
			     (ME4600_AO_SYNC_HOLD << instance->ao_idx),
			     instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   sync_mask | (ME4600_AO_SYNC_HOLD <<
						instance->ao_idx));

			//Fire
			PINFO
			    ("Fired all software synchronous outputs by software trigger.\n");
			outl(0x8000, instance->single_reg);
			PDEBUG_REG("single_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->single_reg - instance->reg_base,
				   0x8000);

			//Restore save settings
			outl(sync_mask, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   sync_mask);
		} else if (!mode) {	//Trigger outputs
/*			//Remove channel from start list //<== Unnecessary. Removed.
			outl(sync_mask & ~(ME4600_AO_SYNC_HOLD << instance->ao_idx), instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base, instance->preload_reg - instance->reg_base, tmp);
*/
			//Fire
			PINFO("Software trigger.\n");
			outl(0x8000, instance->single_reg);
			PDEBUG_REG("single_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->single_reg - instance->reg_base,
				   0x8000);

/*			//Restore save settings //<== Unnecessary. Removed.
			outl(sync_mask, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base, instance->preload_reg - instance->reg_base, sync_mask);
*/
		}
	}
	spin_unlock(instance->preload_reg_lock);

	j = jiffies;
	instance->status = ao_status_single_run_wait;

	instance->timeout.delay = delay;
	instance->timeout.start_time = j;
	instance->ao_control_task_flag = 1;
	queue_delayed_work(instance->me4600_workqueue,
			   &instance->ao_control_task, 1);

	if (!(flags & ME_IO_SINGLE_TYPE_WRITE_NONBLOCKING)) {

		//Only runing process will interrupt this call. Events are signaled when status change. Extra timeout add for safe reason.
		wait_event_interruptible_timeout(instance->wait_queue,
						 (instance->status !=
						  ao_status_single_run_wait),
						 (delay) ? delay +
						 1 : LONG_MAX);

		if (((!delay) || ((jiffies - j) <= delay))
		    && (instance->status != ao_status_single_end)) {
			PDEBUG("Single canceled.\n");
			err = ME_ERRNO_CANCELLED;
		}

		if (signal_pending(current)) {
			PERROR("Wait on start of state machine interrupted.\n");
			instance->ao_control_task_flag = 0;
			cancel_delayed_work(&instance->ao_control_task);
			ao_stop_immediately(instance);
			instance->status = ao_status_none;
			err = ME_ERRNO_SIGNAL;
		}

		if ((delay) && ((jiffies - j) >= delay)) {
			if (instance->status == ao_status_single_end) {
				PDEBUG("Timeout reached.\n");
			} else {
				if ((jiffies - j) > delay) {
					PERROR
					    ("Timeout reached. Not handled by control task!\n");
				} else {
					PERROR
					    ("Timeout reached. Signal come but status is strange: %d\n",
					     instance->status);
				}

				ao_stop_immediately(instance);
			}

			instance->ao_control_task_flag = 0;
			cancel_delayed_work(&instance->ao_control_task);
			instance->status = ao_status_single_end;
			err = ME_ERRNO_TIMEOUT;
		}
	}

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_config(me_subdevice_t *subdevice,
				      struct file *filep,
				      meIOStreamConfig_t *config_list,
				      int count,
				      meIOStreamTrigger_t *trigger,
				      int fifo_irq_threshold, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	uint32_t ctrl;
	unsigned long cpu_flags;
	uint64_t conv_ticks;
	unsigned int conv_start_ticks_low = trigger->iConvStartTicksLow;
	unsigned int conv_start_ticks_high = trigger->iConvStartTicksHigh;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	conv_ticks =
	    (uint64_t) conv_start_ticks_low +
	    ((uint64_t) conv_start_ticks_high << 32);

	if (flags &
	    ~(ME_IO_STREAM_CONFIG_HARDWARE_ONLY | ME_IO_STREAM_CONFIG_WRAPAROUND
	      | ME_IO_STREAM_CONFIG_BIT_PATTERN)) {
		PERROR("Invalid flags.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	if (flags & ME_IO_STREAM_CONFIG_HARDWARE_ONLY) {
		if (!(flags & ME_IO_STREAM_CONFIG_WRAPAROUND)) {
			PERROR
			    ("Hardware ME_IO_STREAM_CONFIG_HARDWARE_ONLY has to be with ME_IO_STREAM_CONFIG_WRAPAROUND.\n");
			return ME_ERRNO_INVALID_FLAGS;
		}

		if ((trigger->iAcqStopTrigType != ME_TRIG_TYPE_NONE)
		    || (trigger->iScanStopTrigType != ME_TRIG_TYPE_NONE)) {
			PERROR
			    ("Hardware wraparound mode must be in infinite mode.\n");
			return ME_ERRNO_INVALID_FLAGS;
		}
	}

	if (count != 1) {
		PERROR("Only 1 entry in config list acceptable.\n");
		return ME_ERRNO_INVALID_CONFIG_LIST_COUNT;
	}

	if (config_list[0].iChannel != 0) {
		PERROR("Invalid channel number specified.\n");
		return ME_ERRNO_INVALID_CHANNEL;
	}

	if (config_list[0].iStreamConfig != 0) {
		PERROR("Only one range available.\n");
		return ME_ERRNO_INVALID_STREAM_CONFIG;
	}

	if (config_list[0].iRef != ME_REF_AO_GROUND) {
		PERROR("Output is referenced to ground.\n");
		return ME_ERRNO_INVALID_REF;
	}

	if ((trigger->iAcqStartTicksLow != 0)
	    || (trigger->iAcqStartTicksHigh != 0)) {
		PERROR
		    ("Invalid acquisition start trigger argument specified.\n");
		return ME_ERRNO_INVALID_ACQ_START_ARG;
	}

	if (config_list[0].iFlags) {
		PERROR("Invalid config list flag.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	switch (trigger->iAcqStartTrigType) {
	case ME_TRIG_TYPE_SW:
		if (trigger->iAcqStartTrigEdge != ME_TRIG_EDGE_NONE) {
			PERROR
			    ("Invalid acquisition start trigger edge specified.\n");
			return ME_ERRNO_INVALID_ACQ_START_TRIG_EDGE;
		}
		break;

	case ME_TRIG_TYPE_EXT_DIGITAL:
		switch (trigger->iAcqStartTrigEdge) {
		case ME_TRIG_EDGE_ANY:
		case ME_TRIG_EDGE_RISING:
		case ME_TRIG_EDGE_FALLING:
			break;

		default:
			PERROR
			    ("Invalid acquisition start trigger edge specified.\n");
			return ME_ERRNO_INVALID_ACQ_START_TRIG_EDGE;
		}
		break;

	default:
		PERROR("Invalid acquisition start trigger type specified.\n");
		return ME_ERRNO_INVALID_ACQ_START_TRIG_TYPE;
	}

	if (trigger->iScanStartTrigType != ME_TRIG_TYPE_FOLLOW) {
		PERROR("Invalid scan start trigger type specified.\n");
		return ME_ERRNO_INVALID_SCAN_START_TRIG_TYPE;
	}

	if (trigger->iConvStartTrigType != ME_TRIG_TYPE_TIMER) {
		PERROR("Invalid conv start trigger type specified.\n");
		return ME_ERRNO_INVALID_CONV_START_TRIG_TYPE;
	}

	if ((conv_ticks < ME4600_AO_MIN_CHAN_TICKS)
	    || (conv_ticks > ME4600_AO_MAX_CHAN_TICKS)) {
		PERROR("Invalid conv start trigger argument specified.\n");
		return ME_ERRNO_INVALID_CONV_START_ARG;
	}

	if (trigger->iAcqStartTicksLow || trigger->iAcqStartTicksHigh) {
		PERROR("Invalid acq start trigger argument specified.\n");
		return ME_ERRNO_INVALID_ACQ_START_ARG;
	}

	if (trigger->iScanStartTicksLow || trigger->iScanStartTicksHigh) {
		PERROR("Invalid scan start trigger argument specified.\n");
		return ME_ERRNO_INVALID_SCAN_START_ARG;
	}

	switch (trigger->iScanStopTrigType) {
	case ME_TRIG_TYPE_NONE:
		if (trigger->iScanStopCount != 0) {
			PERROR("Invalid scan stop count specified.\n");
			return ME_ERRNO_INVALID_SCAN_STOP_ARG;
		}
		break;

	case ME_TRIG_TYPE_COUNT:
		if (flags & ME_IO_STREAM_CONFIG_WRAPAROUND) {
			if (trigger->iScanStopCount <= 0) {
				PERROR("Invalid scan stop count specified.\n");
				return ME_ERRNO_INVALID_SCAN_STOP_ARG;
			}
		} else {
			PERROR("The continous mode has not 'scan' contects.\n");
			return ME_ERRNO_INVALID_ACQ_STOP_TRIG_TYPE;
		}
		break;

	default:
		PERROR("Invalid scan stop trigger type specified.\n");
		return ME_ERRNO_INVALID_SCAN_STOP_TRIG_TYPE;
	}

	switch (trigger->iAcqStopTrigType) {
	case ME_TRIG_TYPE_NONE:
		if (trigger->iAcqStopCount != 0) {
			PERROR("Invalid acq stop count specified.\n");
			return ME_ERRNO_INVALID_ACQ_STOP_ARG;
		}
		break;

	case ME_TRIG_TYPE_COUNT:
		if (trigger->iScanStopTrigType != ME_TRIG_TYPE_NONE) {
			PERROR("Invalid acq stop trigger type specified.\n");
			return ME_ERRNO_INVALID_ACQ_STOP_TRIG_TYPE;
		}

		if (flags & ME_IO_STREAM_CONFIG_WRAPAROUND) {
			if (trigger->iAcqStopCount <= 0) {
				PERROR
				    ("The continous mode has not 'scan' contects.\n");
				return ME_ERRNO_INVALID_ACQ_STOP_ARG;
			}
		}
		break;

	default:
		PERROR("Invalid acq stop trigger type specified.\n");
		return ME_ERRNO_INVALID_ACQ_STOP_TRIG_TYPE;
	}

	switch (trigger->iAcqStartTrigChan) {
	case ME_TRIG_CHAN_DEFAULT:
	case ME_TRIG_CHAN_SYNCHRONOUS:
		break;

	default:
		PERROR("Invalid acq start trigger channel specified.\n");
		return ME_ERRNO_INVALID_ACQ_START_TRIG_CHAN;
	}

	ME_SUBDEVICE_ENTER;

	if ((flags & ME_IO_STREAM_CONFIG_BIT_PATTERN) && !instance->bitpattern) {
		PERROR("This subdevice not support output redirection.\n");
		ME_SUBDEVICE_EXIT;
		return ME_ERRNO_INVALID_FLAGS;
	}
	//Stop device

	//Cancel control task
	PDEBUG("Cancel control task. idx=%d\n", instance->ao_idx);
	instance->ao_control_task_flag = 0;
	cancel_delayed_work(&instance->ao_control_task);

	//Check if state machine is stopped.
	err = ao_stop_immediately(instance);
	if (err) {
		PERROR_CRITICAL("FSM IS BUSY!\n");
		ME_SUBDEVICE_EXIT;

		return ME_ERRNO_SUBDEVICE_BUSY;
	}

	spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
	//Reset control register. Block all actions. Disable IRQ. Disable FIFO.
	ctrl =
	    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP | ME4600_AO_CTRL_BIT_STOP |
	    ME4600_AO_CTRL_BIT_RESET_IRQ;
	outl(ctrl, instance->ctrl_reg);
	PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->ctrl_reg - instance->reg_base, ctrl);

	//This is paranoic, but to be sure.
	instance->preloaded_count = 0;
	instance->data_count = 0;
	instance->circ_buf.head = 0;
	instance->circ_buf.tail = 0;

	/* Set mode. */
	if (flags & ME_IO_STREAM_CONFIG_WRAPAROUND) {	//Wraparound
		if (flags & ME_IO_STREAM_CONFIG_HARDWARE_ONLY) {	//Hardware wraparound
			PINFO("Hardware wraparound.\n");
			ctrl |= ME4600_AO_MODE_WRAPAROUND;
			instance->mode = ME4600_AO_HW_WRAP_MODE;
		} else {	//Software wraparound
			PINFO("Software wraparound.\n");
			ctrl |= ME4600_AO_MODE_CONTINUOUS;
			instance->mode = ME4600_AO_SW_WRAP_MODE;
		}
	} else {		//Continous
		PINFO("Continous.\n");
		ctrl |= ME4600_AO_MODE_CONTINUOUS;
		instance->mode = ME4600_AO_CONTINOUS;
	}

	//Set the trigger edge.
	if (trigger->iAcqStartTrigType == ME_TRIG_TYPE_EXT_DIGITAL) {	//Set the trigger type and edge for external trigger.
		PINFO("External digital trigger.\n");
		instance->start_mode = ME4600_AO_EXT_TRIG;
/*
			ctrl |= ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;
*/
		switch (trigger->iAcqStartTrigEdge) {
		case ME_TRIG_EDGE_RISING:
			PINFO("Set the trigger edge: rising.\n");
			instance->ctrl_trg = 0x0;
			break;

		case ME_TRIG_EDGE_FALLING:
			PINFO("Set the trigger edge: falling.\n");
//                                      ctrl |= ME4600_AO_CTRL_BIT_EX_TRIG_EDGE;
			instance->ctrl_trg = ME4600_AO_CTRL_BIT_EX_TRIG_EDGE;
			break;

		case ME_TRIG_EDGE_ANY:
			PINFO("Set the trigger edge: both edges.\n");
//                                      ctrl |= ME4600_AO_CTRL_BIT_EX_TRIG_EDGE | ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH;
			instance->ctrl_trg =
			    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE |
			    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH;
			break;
		}
	} else {
		PINFO("Internal software trigger.\n");
		instance->start_mode = 0;
	}

	//Set the stop mode and value.
	if (trigger->iAcqStopTrigType == ME_TRIG_TYPE_COUNT) {	//Amount of data
		instance->stop_mode = ME4600_AO_ACQ_STOP_MODE;
		instance->stop_count = trigger->iAcqStopCount;
	} else if (trigger->iScanStopTrigType == ME_TRIG_TYPE_COUNT) {	//Amount of 'scans'
		instance->stop_mode = ME4600_AO_SCAN_STOP_MODE;
		instance->stop_count = trigger->iScanStopCount;
	} else {		//Infinite
		instance->stop_mode = ME4600_AO_INF_STOP_MODE;
		instance->stop_count = 0;
	}

	PINFO("Stop count: %d.\n", instance->stop_count);

	if (trigger->iAcqStartTrigChan == ME_TRIG_CHAN_SYNCHRONOUS) {	//Synchronous start
		instance->start_mode |= ME4600_AO_SYNC_HOLD;
		if (trigger->iAcqStartTrigType == ME_TRIG_TYPE_EXT_DIGITAL) {	//Externaly triggered
			PINFO("Synchronous start. Externaly trigger active.\n");
			instance->start_mode |= ME4600_AO_SYNC_EXT_TRIG;
		}
#ifdef MEDEBUG_INFO
		else {
			PINFO
			    ("Synchronous start. Externaly trigger dissabled.\n");
		}
#endif

	}
	//Set speed
	outl(conv_ticks - 2, instance->timer_reg);
	PDEBUG_REG("timer_reg outl(0x%lX+0x%lX)=0x%llx\n", instance->reg_base,
		   instance->timer_reg - instance->reg_base, conv_ticks - 2);
	instance->hardware_stop_delay = (int)(conv_ticks * HZ) / ME4600_AO_BASE_FREQUENCY;	//<== MUST be with cast!

	//Conect outputs to analog or digital port.
	if (flags & ME_IO_STREAM_CONFIG_BIT_PATTERN) {
		ctrl |= ME4600_AO_CTRL_BIT_ENABLE_DO;
	}
	// Write the control word
	outl(ctrl, instance->ctrl_reg);
	PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->ctrl_reg - instance->reg_base, ctrl);

	//Set status.
	instance->status = ao_status_stream_configured;
	spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_new_values(me_subdevice_t *subdevice,
					  struct file *filep,
					  int time_out, int *count, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	long t = 0;
	long j;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	if (flags) {
		PERROR("Invalid flag specified.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	if (!instance->circ_buf.buf) {
		PERROR("Circular buffer not exists.\n");
		return ME_ERRNO_INTERNAL;
	}

	if (time_out < 0) {
		PERROR("Invalid time_out specified.\n");
		return ME_ERRNO_INVALID_TIMEOUT;
	}

	ME_SUBDEVICE_ENTER;

	if (me_circ_buf_space(&instance->circ_buf)) {	//The buffer is NOT full.
		*count = me_circ_buf_space(&instance->circ_buf);
	} else {		//The buffer is full.
		if (time_out) {
			t = (time_out * HZ) / 1000;

			if (t == 0)
				t = 1;
		} else {	//Max time.
			t = LONG_MAX;
		}

		*count = 0;

		j = jiffies;

		//Only runing process will interrupt this call. Interrupts are when FIFO HF is signaled.
		wait_event_interruptible_timeout(instance->wait_queue,
						 ((me_circ_buf_space
						   (&instance->circ_buf))
						  || !(inl(instance->status_reg)
						       &
						       ME4600_AO_STATUS_BIT_FSM)),
						 t);

		if (!(inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM)) {
			PERROR("AO subdevice is not running.\n");
			err = ME_ERRNO_SUBDEVICE_NOT_RUNNING;
		} else if (signal_pending(current)) {
			PERROR("Wait on values interrupted from signal.\n");
			instance->status = ao_status_none;
			ao_stop_immediately(instance);
			err = ME_ERRNO_SIGNAL;
		} else if ((jiffies - j) >= t) {
			PERROR("Wait on values timed out.\n");
			err = ME_ERRNO_TIMEOUT;
		} else {	//Uff... all is good. Inform user about empty space.
			*count = me_circ_buf_space(&instance->circ_buf);
		}
	}

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_start(me_subdevice_t *subdevice,
				     struct file *filep,
				     int start_mode, int time_out, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	unsigned long cpu_flags = 0;
	uint32_t status;
	uint32_t ctrl;
	uint32_t synch;
	int count = 0;
	int circ_buffer_count;

	unsigned long ref;
	unsigned long delay = 0;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	if (flags & ~ME_IO_STREAM_START_TYPE_TRIG_SYNCHRONOUS) {
		PERROR("Invalid flags.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	if (time_out < 0) {
		PERROR("Invalid timeout specified.\n");
		return ME_ERRNO_INVALID_TIMEOUT;
	}

	if ((start_mode != ME_START_MODE_BLOCKING)
	    && (start_mode != ME_START_MODE_NONBLOCKING)) {
		PERROR("Invalid start mode specified.\n");
		return ME_ERRNO_INVALID_START_MODE;
	}

	if (time_out) {
		delay = (time_out * HZ) / 1000;
		if (delay == 0)
			delay = 1;
	}

	switch (instance->status) {	//Checking actual mode.
	case ao_status_stream_configured:
	case ao_status_stream_end:
		//Correct modes!
		break;

		//The device is in wrong mode.
	case ao_status_none:
	case ao_status_single_configured:
	case ao_status_single_run_wait:
	case ao_status_single_run:
	case ao_status_single_end_wait:
		PERROR
		    ("Subdevice must be preinitialize correctly for streaming.\n");
		return ME_ERRNO_PREVIOUS_CONFIG;

	case ao_status_stream_fifo_error:
	case ao_status_stream_buffer_error:
	case ao_status_stream_error:
		PDEBUG("Before restart broke stream 'STOP' must be caled.\n");
		return ME_STATUS_ERROR;

	case ao_status_stream_run_wait:
	case ao_status_stream_run:
	case ao_status_stream_end_wait:
		PDEBUG("Stream is already working.\n");
		return ME_ERRNO_SUBDEVICE_BUSY;

	default:
		instance->status = ao_status_stream_error;
		PERROR_CRITICAL("Status is in wrong state!\n");
		return ME_ERRNO_INTERNAL;

	}

	ME_SUBDEVICE_ENTER;

	if (instance->mode == ME4600_AO_CONTINOUS) {	//Continous
		instance->circ_buf.tail += instance->preloaded_count;
		instance->circ_buf.tail &= instance->circ_buf.mask;
	}
	circ_buffer_count = me_circ_buf_values(&instance->circ_buf);

	if (!circ_buffer_count && !instance->preloaded_count) {	//No values in buffer
		ME_SUBDEVICE_EXIT;
		PERROR("No values in buffer!\n");
		return ME_ERRNO_LACK_OF_RESOURCES;
	}

	//Cancel control task
	PDEBUG("Cancel control task. idx=%d\n", instance->ao_idx);
	instance->ao_control_task_flag = 0;
	cancel_delayed_work(&instance->ao_control_task);

	//Stop device
	err = ao_stop_immediately(instance);
	if (err) {
		PERROR_CRITICAL("FSM IS BUSY!\n");
		ME_SUBDEVICE_EXIT;

		return ME_ERRNO_SUBDEVICE_BUSY;
	}
	//Set values for single_read()
	instance->single_value = ME4600_AO_MAX_DATA + 1;
	instance->single_value_in_fifo = ME4600_AO_MAX_DATA + 1;

	//Setting stop points
	if (instance->stop_mode == ME4600_AO_SCAN_STOP_MODE) {
		instance->stop_data_count =
		    instance->stop_count * circ_buffer_count;
	} else {
		instance->stop_data_count = instance->stop_count;
	}

	if ((instance->stop_data_count != 0)
	    && (instance->stop_data_count < circ_buffer_count)) {
		PERROR("More data in buffer than previously set limit!\n");
	}

	spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
	ctrl = inl(instance->ctrl_reg);
	//Check FIFO
	if (!(ctrl & ME4600_AO_CTRL_BIT_ENABLE_FIFO)) {	//FIFO wasn't enabeled. Do it. <= This should be done by user call with ME_WRITE_MODE_PRELOAD
		PINFO("Enableing FIFO.\n");
		ctrl |=
		    ME4600_AO_CTRL_BIT_ENABLE_FIFO |
		    ME4600_AO_CTRL_BIT_RESET_IRQ;

		instance->preloaded_count = 0;
		instance->data_count = 0;
	} else {		//Block IRQ
		ctrl |= ME4600_AO_CTRL_BIT_RESET_IRQ;
	}
	outl(ctrl, instance->ctrl_reg);
	PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->ctrl_reg - instance->reg_base,
		   ctrl | ME4600_AO_CTRL_BIT_RESET_IRQ);

	//Fill FIFO <= Generaly this should be done by user pre-load call but this is second place to do it.
	status = inl(instance->status_reg);
	if (!(status & ME4600_AO_STATUS_BIT_EF)) {	//FIFO empty
		if (instance->stop_data_count == 0) {
			count = ME4600_AO_FIFO_COUNT;
		} else {
			count =
			    (ME4600_AO_FIFO_COUNT <
			     instance->
			     stop_data_count) ? ME4600_AO_FIFO_COUNT :
			    instance->stop_data_count;
		}

		//Copy data
		count =
		    ao_write_data(instance, count, instance->preloaded_count);

		if (count < 0) {	//This should never happend!
			PERROR_CRITICAL("COPY FINISH WITH ERROR!\n");
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
			ME_SUBDEVICE_EXIT;
			return ME_ERRNO_INTERNAL;
		}
	}
	//Set pre-load features.
	spin_lock(instance->preload_reg_lock);
	synch = inl(instance->preload_reg);
	synch &=
	    ~((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) << instance->
	      ao_idx);
	synch |=
	    (instance->start_mode & ~ME4600_AO_EXT_TRIG) << instance->ao_idx;
	outl(synch, instance->preload_reg);
	PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->preload_reg - instance->reg_base, synch);
	spin_unlock(instance->preload_reg_lock);

	//Default count is '0'
	if (instance->mode == ME4600_AO_CONTINOUS) {	//Continous
		instance->preloaded_count = 0;
		instance->circ_buf.tail += count;
		instance->circ_buf.tail &= instance->circ_buf.mask;
	} else {		//Wraparound
		instance->preloaded_count += count;
		instance->data_count += count;

		//Special case: Infinite wraparound with less than FIFO datas always should runs in hardware mode.
		if ((instance->stop_mode == ME4600_AO_INF_STOP_MODE)
		    && (circ_buffer_count <= ME4600_AO_FIFO_COUNT)) {	//Change to hardware wraparound
			PDEBUG
			    ("Changeing mode from software wraparound to hardware wraparound.\n");
			//Copy all data
			count =
			    ao_write_data(instance, circ_buffer_count,
					  instance->preloaded_count);
			ctrl &= ~ME4600_AO_CTRL_MODE_MASK;
			ctrl |= ME4600_AO_MODE_WRAPAROUND;
		}

		if (instance->preloaded_count == me_circ_buf_values(&instance->circ_buf)) {	//Reset position indicator.
			instance->preloaded_count = 0;
		} else if (instance->preloaded_count > me_circ_buf_values(&instance->circ_buf)) {	//This should never happend!
			PERROR_CRITICAL
			    ("PRELOADED MORE VALUES THAN ARE IN BUFFER!\n");
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
			ME_SUBDEVICE_EXIT;
			return ME_ERRNO_INTERNAL;
		}
	}

	//Set status to 'wait for start'
	instance->status = ao_status_stream_run_wait;

	status = inl(instance->status_reg);
	//Start state machine and interrupts
	ctrl &= ~(ME4600_AO_CTRL_BIT_STOP | ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);
	if (instance->start_mode == ME4600_AO_EXT_TRIG) {	// External trigger.
		PINFO("External trigger.\n");
		ctrl |= ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;
	}
	if (!(status & ME4600_AO_STATUS_BIT_HF)) {	//More than half!
		if ((ctrl & ME4600_AO_CTRL_MODE_MASK) == ME4600_AO_MODE_CONTINUOUS) {	//Enable IRQ only when hardware_continous is set and FIFO is more than half
			ctrl &= ~ME4600_AO_CTRL_BIT_RESET_IRQ;
			ctrl |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
		}
	}
	outl(ctrl, instance->ctrl_reg);
	PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->ctrl_reg - instance->reg_base, ctrl);
	spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

	//Trigger output
	if (flags & ME_IO_SINGLE_TYPE_TRIG_SYNCHRONOUS) {	//Trigger outputs
		spin_lock(instance->preload_reg_lock);
		synch = inl(instance->preload_reg);
		//Add channel to start list
		outl(synch | (ME4600_AO_SYNC_HOLD << instance->ao_idx),
		     instance->preload_reg);
		PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->preload_reg - instance->reg_base,
			   synch | (ME4600_AO_SYNC_HOLD << instance->ao_idx));

		//Fire
		PINFO
		    ("Fired all software synchronous outputs by software trigger.\n");
		outl(0x8000, instance->single_reg);
		PDEBUG_REG("single_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->single_reg - instance->reg_base, 0x8000);

		//Restore save settings
		outl(synch, instance->preload_reg);
		PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->preload_reg - instance->reg_base, synch);
		spin_unlock(instance->preload_reg_lock);
	} else if (!instance->start_mode) {	//Trigger outputs
/*
		//Remove channel from start list.	// <== Unnecessary. Removed.
		spin_lock(instance->preload_reg_lock);
			synch = inl(instance->preload_reg);
			outl(synch & ~(ME4600_AO_SYNC_HOLD << instance->ao_idx), instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base, instance->preload_reg - instance->reg_base, synch & ~(ME4600_AO_SYNC_HOLD << instance->ao_idx));
*/
		//Fire
		PINFO("Software trigger.\n");
		outl(0x8000, instance->single_reg);
		PDEBUG_REG("single_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->single_reg - instance->reg_base, 0x8000);

/*
			//Restore save settings.	// <== Unnecessary. Removed.
			outl(synch, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base, instance->preload_reg - instance->reg_base, synch);
		spin_unlock(instance->preload_reg_lock);
*/
	}
	// Set control task's timeout
	ref = jiffies;
	instance->timeout.delay = delay;
	instance->timeout.start_time = ref;

	if (status & ME4600_AO_STATUS_BIT_HF) {	//Less than half but not empty!
		PINFO("Less than half.\n");
		if (instance->stop_data_count != 0) {
			count = ME4600_AO_FIFO_COUNT / 2;
		} else {
			count =
			    ((ME4600_AO_FIFO_COUNT / 2) <
			     instance->stop_data_count) ? ME4600_AO_FIFO_COUNT /
			    2 : instance->stop_data_count;
		}

		//Copy data
		count =
		    ao_write_data(instance, count, instance->preloaded_count);

		if (count < 0) {	//This should never happend!
			PERROR_CRITICAL("COPY FINISH WITH ERROR!\n");
			ME_SUBDEVICE_EXIT;
			return ME_ERRNO_INTERNAL;
		}

		if (instance->mode == ME4600_AO_CONTINOUS) {	//Continous
			instance->circ_buf.tail += count;
			instance->circ_buf.tail &= instance->circ_buf.mask;
		} else {	//Wraparound
			instance->data_count += count;
			instance->preloaded_count += count;

			if (instance->preloaded_count == me_circ_buf_values(&instance->circ_buf)) {	//Reset position indicator.
				instance->preloaded_count = 0;
			} else if (instance->preloaded_count > me_circ_buf_values(&instance->circ_buf)) {	//This should never happend!
				PERROR_CRITICAL
				    ("PRELOADED MORE VALUES THAN ARE IN BUFFER!\n");
				ME_SUBDEVICE_EXIT;
				return ME_ERRNO_INTERNAL;
			}
		}

		status = inl(instance->status_reg);
		if (!(status & ME4600_AO_STATUS_BIT_HF)) {	//More than half!
			spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
			ctrl = inl(instance->ctrl_reg);
			ctrl &= ~ME4600_AO_CTRL_BIT_RESET_IRQ;
			ctrl |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			outl(ctrl, instance->ctrl_reg);
			PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->ctrl_reg - instance->reg_base,
				   ctrl);
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
		}
	}
	//Special case: Limited wraparound with less than HALF FIFO datas need work around to generate first interrupt.
	if ((instance->stop_mode != ME4600_AO_INF_STOP_MODE)
	    && (instance->mode == ME4600_AO_SW_WRAP_MODE)
	    && (circ_buffer_count <= (ME4600_AO_FIFO_COUNT / 2))) {	//Put more data to FIFO
		PINFO("Limited wraparound with less than HALF FIFO datas.\n");
		if (instance->preloaded_count) {	//This should never happend!
			PERROR_CRITICAL
			    ("ERROR WHEN LOADING VALUES FOR WRAPAROUND!\n");
			ME_SUBDEVICE_EXIT;
			return ME_ERRNO_INTERNAL;
		}

		while (instance->stop_data_count > instance->data_count) {	//Maximum data not set jet.
			//Copy to buffer
			if (circ_buffer_count != ao_write_data(instance, circ_buffer_count, 0)) {	//This should never happend!
				PERROR_CRITICAL
				    ("ERROR WHEN LOADING VALUES FOR WRAPAROUND!\n");
				ME_SUBDEVICE_EXIT;
				return ME_ERRNO_INTERNAL;
			}
			instance->data_count += circ_buffer_count;

			if (!((status = inl(instance->status_reg)) & ME4600_AO_STATUS_BIT_HF)) {	//FIFO is more than half. Enable IRQ and end copy.
				spin_lock_irqsave(&instance->subdevice_lock,
						  cpu_flags);
				ctrl = inl(instance->ctrl_reg);
				ctrl &= ~ME4600_AO_CTRL_BIT_RESET_IRQ;
				ctrl |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
				outl(ctrl, instance->ctrl_reg);
				PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
					   instance->reg_base,
					   instance->ctrl_reg -
					   instance->reg_base, ctrl);
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				break;
			}
		}
	}
	// Schedule control task.
	instance->ao_control_task_flag = 1;
	queue_delayed_work(instance->me4600_workqueue,
			   &instance->ao_control_task, 1);

	if (start_mode == ME_START_MODE_BLOCKING) {	//Wait for start.
		//Only runing process will interrupt this call. Events are signaled when status change. Extra timeout add for safe reason.
		wait_event_interruptible_timeout(instance->wait_queue,
						 (instance->status !=
						  ao_status_stream_run_wait),
						 (delay) ? delay +
						 1 : LONG_MAX);

		if ((instance->status != ao_status_stream_run)
		    && (instance->status != ao_status_stream_end)) {
			PDEBUG("Starting stream canceled. %d\n",
			       instance->status);
			err = ME_ERRNO_CANCELLED;
		}

		if (signal_pending(current)) {
			PERROR("Wait on start of state machine interrupted.\n");
			instance->status = ao_status_none;
			ao_stop_immediately(instance);
			err = ME_ERRNO_SIGNAL;
		} else if ((delay) && ((jiffies - ref) >= delay)) {
			if (instance->status != ao_status_stream_run) {
				if (instance->status == ao_status_stream_end) {
					PDEBUG("Timeout reached.\n");
				} else {
					if ((jiffies - ref) > delay) {
						PERROR
						    ("Timeout reached. Not handled by control task!\n");
					} else {
						PERROR
						    ("Timeout reached. Signal come but status is strange: %d\n",
						     instance->status);
					}
					ao_stop_immediately(instance);
				}

				instance->ao_control_task_flag = 0;
				cancel_delayed_work(&instance->ao_control_task);
				instance->status = ao_status_stream_end;
				err = ME_ERRNO_TIMEOUT;
			}
		}
	}

	ME_SUBDEVICE_EXIT;
	return err;
}

static int me4600_ao_io_stream_status(me_subdevice_t *subdevice,
				      struct file *filep,
				      int wait,
				      int *status, int *values, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	if (flags) {
		PERROR("Invalid flag specified.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	if ((wait != ME_WAIT_NONE) && (wait != ME_WAIT_IDLE)) {
		PERROR("Invalid wait argument specified.\n");
		*status = ME_STATUS_INVALID;
		return ME_ERRNO_INVALID_WAIT;
	}

	ME_SUBDEVICE_ENTER;

	switch (instance->status) {
	case ao_status_single_configured:
	case ao_status_single_end:
	case ao_status_stream_configured:
	case ao_status_stream_end:
	case ao_status_stream_fifo_error:
	case ao_status_stream_buffer_error:
	case ao_status_stream_error:
		*status = ME_STATUS_IDLE;
		break;

	case ao_status_single_run_wait:
	case ao_status_single_run:
	case ao_status_single_end_wait:
	case ao_status_stream_run_wait:
	case ao_status_stream_run:
	case ao_status_stream_end_wait:
		*status = ME_STATUS_BUSY;
		break;

	case ao_status_none:
	default:
		*status =
		    (inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM) ?
		    ME_STATUS_BUSY : ME_STATUS_IDLE;
		break;
	}

	if ((wait == ME_WAIT_IDLE) && (*status == ME_STATUS_BUSY)) {
		//Only runing process will interrupt this call. Events are signaled when status change. Extra timeout add for safe reason.
		wait_event_interruptible_timeout(instance->wait_queue,
						 ((instance->status !=
						   ao_status_single_run_wait)
						  && (instance->status !=
						      ao_status_single_run)
						  && (instance->status !=
						      ao_status_single_end_wait)
						  && (instance->status !=
						      ao_status_stream_run_wait)
						  && (instance->status !=
						      ao_status_stream_run)
						  && (instance->status !=
						      ao_status_stream_end_wait)),
						 LONG_MAX);

		if (instance->status != ao_status_stream_end) {
			PDEBUG("Wait for IDLE canceled. %d\n",
			       instance->status);
			err = ME_ERRNO_CANCELLED;
		}

		if (signal_pending(current)) {
			PERROR("Wait for IDLE interrupted.\n");
			instance->status = ao_status_none;
			ao_stop_immediately(instance);
			err = ME_ERRNO_SIGNAL;
		}

		*status = ME_STATUS_IDLE;
	}

	*values = me_circ_buf_space(&instance->circ_buf);

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_stop(me_subdevice_t *subdevice,
				    struct file *filep,
				    int stop_mode, int flags)
{				// Stop work and empty buffer and FIFO
	int err = ME_ERRNO_SUCCESS;
	me4600_ao_subdevice_t *instance;
	unsigned long cpu_flags;
	volatile uint32_t ctrl;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (flags & ~ME_IO_STREAM_STOP_PRESERVE_BUFFERS) {
		PERROR("Invalid flag specified.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	if ((stop_mode != ME_STOP_MODE_IMMEDIATE)
	    && (stop_mode != ME_STOP_MODE_LAST_VALUE)) {
		PERROR("Invalid stop mode specified.\n");
		return ME_ERRNO_INVALID_STOP_MODE;
	}

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	if (instance->status < ao_status_stream_configured) {
		//There is nothing to stop!
		PERROR("Subdevice not in streaming mode. %d\n",
		       instance->status);
		return ME_ERRNO_PREVIOUS_CONFIG;
	}

	ME_SUBDEVICE_ENTER;

	//Mark as stopping. => Software stop.
	instance->status = ao_status_stream_end_wait;

	if (stop_mode == ME_STOP_MODE_IMMEDIATE) {	//Stopped now!
		err = ao_stop_immediately(instance);
	} else if (stop_mode == ME_STOP_MODE_LAST_VALUE) {
		ctrl = inl(instance->ctrl_reg) & ME4600_AO_CTRL_MODE_MASK;
		if (ctrl == ME4600_AO_MODE_WRAPAROUND) {	//Hardware wraparound => Hardware stop.
			spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
			ctrl = inl(instance->ctrl_reg);
			ctrl |=
			    ME4600_AO_CTRL_BIT_STOP |
			    ME4600_AO_CTRL_BIT_RESET_IRQ;
			ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			outl(ctrl, instance->ctrl_reg);
			PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->ctrl_reg - instance->reg_base,
				   ctrl);
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
		}
		//Only runing process will interrupt this call. Events are signaled when status change.
		wait_event_interruptible_timeout(instance->wait_queue,
						 (instance->status !=
						  ao_status_stream_end_wait),
						 LONG_MAX);

		if (instance->status != ao_status_stream_end) {
			PDEBUG("Stopping stream canceled.\n");
			err = ME_ERRNO_CANCELLED;
		}

		if (signal_pending(current)) {
			PERROR("Stopping stream interrupted.\n");
			instance->status = ao_status_none;
			ao_stop_immediately(instance);
			err = ME_ERRNO_SIGNAL;
		}
	}

	spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
	ctrl = inl(instance->ctrl_reg);
	ctrl |=
	    ME4600_AO_CTRL_BIT_STOP | ME4600_AO_CTRL_BIT_IMMEDIATE_STOP |
	    ME4600_AO_CTRL_BIT_RESET_IRQ;
	ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
	if (!flags) {		//Reset FIFO
		ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_FIFO;
	}
	outl(ctrl, instance->ctrl_reg);
	PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->ctrl_reg - instance->reg_base, ctrl);
	spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

	if (!flags) {		//Reset software buffer
		instance->circ_buf.head = 0;
		instance->circ_buf.tail = 0;
		instance->preloaded_count = 0;
		instance->data_count = 0;
	}

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_write(me_subdevice_t *subdevice,
				     struct file *filep,
				     int write_mode,
				     int *values, int *count, int flags)
{
	int err = ME_ERRNO_SUCCESS;
	me4600_ao_subdevice_t *instance;
	unsigned long cpu_flags = 0;
	uint32_t reg_copy;

	int copied_from_user = 0;
	int left_to_copy_from_user = *count;

	int copied_values;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	//Checking arguments
	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	if (flags) {
		PERROR("Invalid flag specified.\n");
		return ME_ERRNO_INVALID_FLAGS;
	}

	if (*count <= 0) {
		PERROR("Invalid count of values specified.\n");
		return ME_ERRNO_INVALID_VALUE_COUNT;
	}

	if (values == NULL) {
		PERROR("Invalid address of values specified.\n");
		return ME_ERRNO_INVALID_POINTER;
	}

	if ((instance->status == ao_status_none) || (instance->status == ao_status_single_configured)) {	//The device is in single mode.
		PERROR
		    ("Subdevice must be preinitialize correctly for streaming.\n");
		return ME_ERRNO_PREVIOUS_CONFIG;
	}
/// @note If no 'pre-load' is used. stream_start() will move data to FIFO.
	switch (write_mode) {
	case ME_WRITE_MODE_PRELOAD:

		//Device must be stopped.
		if ((instance->status != ao_status_stream_configured)
		    && (instance->status != ao_status_stream_end)) {
			PERROR
			    ("Subdevice mustn't be runing when 'pre-load' mode is used.\n");
			return ME_ERRNO_PREVIOUS_CONFIG;
		}
		break;
	case ME_WRITE_MODE_NONBLOCKING:
	case ME_WRITE_MODE_BLOCKING:
		/// @note In blocking mode: When device is not runing and there is not enought space call will blocked up!
		/// @note Some other thread must empty buffer by starting engine.
		break;

	default:
		PERROR("Invalid write mode specified.\n");
		return ME_ERRNO_INVALID_WRITE_MODE;
	}

	if (instance->mode & ME4600_AO_WRAP_MODE) {	//Wraparound mode. Device must be stopped.
		if ((instance->status != ao_status_stream_configured)
		    && (instance->status != ao_status_stream_end)) {
			PERROR
			    ("Subdevice mustn't be runing when 'pre-load' mode is used.\n");
			return ME_ERRNO_INVALID_WRITE_MODE;
		}
	}

	if ((instance->mode == ME4600_AO_HW_WRAP_MODE) && (write_mode != ME_WRITE_MODE_PRELOAD)) {	// hardware wrap_around mode.
		//This is transparent for user.
		PDEBUG("Changing write_mode to ME_WRITE_MODE_PRELOAD.\n");
		write_mode = ME_WRITE_MODE_PRELOAD;
	}

	ME_SUBDEVICE_ENTER;

	if (write_mode == ME_WRITE_MODE_PRELOAD) {	//Init enviroment - preload
		spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
		reg_copy = inl(instance->ctrl_reg);
		//Check FIFO
		if (!(reg_copy & ME4600_AO_CTRL_BIT_ENABLE_FIFO)) {	//FIFO not active. Enable it.
			reg_copy |= ME4600_AO_CTRL_BIT_ENABLE_FIFO;
			outl(reg_copy, instance->ctrl_reg);
			PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->ctrl_reg - instance->reg_base,
				   reg_copy);
			instance->preloaded_count = 0;
		}
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
	}

	while (1) {
		//Copy to buffer. This step is common for all modes.
		copied_from_user =
		    ao_get_data_from_user(instance, left_to_copy_from_user,
					  values + (*count -
						    left_to_copy_from_user));
		left_to_copy_from_user -= copied_from_user;

		reg_copy = inl(instance->status_reg);
		if ((instance->status == ao_status_stream_run) && !(reg_copy & ME4600_AO_STATUS_BIT_FSM)) {	//BROKEN PIPE! The state machine is stoped but logical status show that should be working.
			PERROR("Broken pipe in write.\n");
			err = ME_ERRNO_SUBDEVICE_NOT_RUNNING;
			break;
		}

		if ((instance->status == ao_status_stream_run) && (instance->mode == ME4600_AO_CONTINOUS) && (reg_copy & ME4600_AO_STATUS_BIT_HF)) {	//Continous mode runing and data are below half!

			// Block interrupts.
			spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
			reg_copy = inl(instance->ctrl_reg);
			//reg_copy &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			reg_copy |= ME4600_AO_CTRL_BIT_RESET_IRQ;
			outl(reg_copy, instance->ctrl_reg);
			PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->ctrl_reg - instance->reg_base,
				   reg_copy);
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			//Fast copy
			copied_values =
			    ao_write_data(instance, ME4600_AO_FIFO_COUNT / 2,
					  0);
			if (copied_values > 0) {
				instance->circ_buf.tail += copied_values;
				instance->circ_buf.tail &=
				    instance->circ_buf.mask;
				continue;
			}
			// Activate interrupts.
			spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
			reg_copy = inl(instance->ctrl_reg);
			//reg_copy |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			reg_copy &= ~ME4600_AO_CTRL_BIT_RESET_IRQ;
			outl(reg_copy, instance->ctrl_reg);
			PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->ctrl_reg - instance->reg_base,
				   reg_copy);
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			if (copied_values == 0) {	//This was checked and never should happend!
				PERROR_CRITICAL("COPING FINISH WITH 0!\n");
			}

			if (copied_values < 0) {	//This was checked and never should happend!
				PERROR_CRITICAL
				    ("COPING FINISH WITH AN ERROR!\n");
				instance->status = ao_status_stream_fifo_error;
				err = ME_ERRNO_FIFO_BUFFER_OVERFLOW;
				break;
			}
		}

		if (!left_to_copy_from_user) {	//All datas were copied.
			break;
		} else {	//Not all datas were copied.
			if (instance->mode & ME4600_AO_WRAP_MODE) {	//Error too much datas! Wraparound is limited in size!
				PERROR
				    ("Too much data for wraparound mode!  Exceeded size of %ld.\n",
				     ME4600_AO_CIRC_BUF_COUNT - 1);
				err = ME_ERRNO_RING_BUFFER_OVERFLOW;
				break;
			}

			if (write_mode != ME_WRITE_MODE_BLOCKING) {	//Non blocking calls
				break;
			}

			wait_event_interruptible(instance->wait_queue,
						 me_circ_buf_space(&instance->
								   circ_buf));

			if (signal_pending(current)) {
				PERROR("Writing interrupted by signal.\n");
				instance->status = ao_status_none;
				ao_stop_immediately(instance);
				err = ME_ERRNO_SIGNAL;
				break;
			}

			if (instance->status == ao_status_none) {	//Reset
				PERROR("Writing interrupted by reset.\n");
				err = ME_ERRNO_CANCELLED;
				break;
			}
		}
	}

	if (write_mode == ME_WRITE_MODE_PRELOAD) {	//Copy data to FIFO - preload
		copied_values =
		    ao_write_data_pooling(instance, ME4600_AO_FIFO_COUNT,
					  instance->preloaded_count);
		instance->preloaded_count += copied_values;
		instance->data_count += copied_values;

		if ((instance->mode == ME4600_AO_HW_WRAP_MODE)
		    && (me_circ_buf_values(&instance->circ_buf) >
			ME4600_AO_FIFO_COUNT)) {
			PERROR
			    ("Too much data for hardware wraparound mode! Exceeded size of %d.\n",
			     ME4600_AO_FIFO_COUNT);
			err = ME_ERRNO_FIFO_BUFFER_OVERFLOW;
		}
	}

	*count = *count - left_to_copy_from_user;
	ME_SUBDEVICE_EXIT;

	return err;
}
static irqreturn_t me4600_ao_isr(int irq, void *dev_id)
{
	me4600_ao_subdevice_t *instance = dev_id;
	uint32_t irq_status;
	uint32_t ctrl;
	uint32_t status;
	int count = 0;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (irq != instance->irq) {
		PERROR("Incorrect interrupt num: %d.\n", irq);
		return IRQ_NONE;
	}

	irq_status = inl(instance->irq_status_reg);
	if (!(irq_status & (ME4600_IRQ_STATUS_BIT_AO_HF << instance->ao_idx))) {
		PINFO("%ld Shared interrupt. %s(): ID=%d: status_reg=0x%04X\n",
		      jiffies, __func__, instance->ao_idx, irq_status);
		return IRQ_NONE;
	}

	if (!instance->circ_buf.buf) {
		instance->status = ao_status_stream_error;
		PERROR_CRITICAL("CIRCULAR BUFFER NOT EXISTS!\n");
		//Block interrupts. Stop machine.
		ctrl = inl(instance->ctrl_reg);
		ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
		ctrl |=
		    ME4600_AO_CTRL_BIT_RESET_IRQ |
		    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP | ME4600_AO_CTRL_BIT_STOP;
		outl(ctrl, instance->ctrl_reg);
		PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->ctrl_reg - instance->reg_base, ctrl);

		//Inform user
		wake_up_interruptible_all(&instance->wait_queue);
		return IRQ_HANDLED;
	}

	status = inl(instance->status_reg);
	if (!(status & ME4600_AO_STATUS_BIT_FSM)) {	//Too late. Not working! END? BROKEN PIPE?
		PDEBUG("Interrupt come but ISM is not working!\n");
		//Block interrupts. Stop machine.
		ctrl = inl(instance->ctrl_reg);
		ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
		ctrl |=
		    ME4600_AO_CTRL_BIT_RESET_IRQ | ME4600_AO_CTRL_BIT_STOP |
		    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
		outl(ctrl, instance->ctrl_reg);
		PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->ctrl_reg - instance->reg_base, ctrl);

		return IRQ_HANDLED;
	}
	//General procedure. Process more datas.

#ifdef MEDEBUG_DEBUG
	if (!me_circ_buf_values(&instance->circ_buf)) {	//Buffer is empty!
		PDEBUG("Circular buffer empty!\n");
	}
#endif

	//Check FIFO
	if (status & ME4600_AO_STATUS_BIT_HF) {	//OK less than half

		//Block interrupts
		ctrl = inl(instance->ctrl_reg);
		ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
		ctrl |= ME4600_AO_CTRL_BIT_RESET_IRQ;
		outl(ctrl, instance->ctrl_reg);
		PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->ctrl_reg - instance->reg_base, ctrl);

		do {
			//Calculate how many should be copied.
			count =
			    (instance->stop_data_count) ? instance->
			    stop_data_count -
			    instance->data_count : ME4600_AO_FIFO_COUNT / 2;
			if (ME4600_AO_FIFO_COUNT / 2 < count) {
				count = ME4600_AO_FIFO_COUNT / 2;
			}
			//Copy data
			if (instance->mode == ME4600_AO_CONTINOUS) {	//Continous
				count = ao_write_data(instance, count, 0);
				if (count > 0) {
					instance->circ_buf.tail += count;
					instance->circ_buf.tail &=
					    instance->circ_buf.mask;
					instance->data_count += count;

					if ((instance->status == ao_status_stream_end_wait) && !me_circ_buf_values(&instance->circ_buf)) {	//Stoping. Whole buffer was copied.
						break;
					}
				}
			} else if ((instance->mode == ME4600_AO_SW_WRAP_MODE) && ((ctrl & ME4600_AO_CTRL_MODE_MASK) == ME4600_AO_MODE_CONTINUOUS)) {	//Wraparound (software)
				if (instance->status == ao_status_stream_end_wait) {	//We stoping => Copy to the end of the buffer.
					count =
					    ao_write_data(instance, count, 0);
				} else {	//Copy in wraparound mode.
					count =
					    ao_write_data_wraparound(instance,
								     count,
								     instance->
								     preloaded_count);
				}

				if (count > 0) {
					instance->data_count += count;
					instance->preloaded_count += count;
					instance->preloaded_count %=
					    me_circ_buf_values(&instance->
							       circ_buf);

					if ((instance->status == ao_status_stream_end_wait) && !instance->preloaded_count) {	//Stoping. Whole buffer was copied.
						break;
					}
				}
			}

			if ((count <= 0) || (instance->stop_data_count && (instance->stop_data_count <= instance->data_count))) {	//End of work.
				break;
			}
		}		//Repeat if still is under half fifo
		while ((status =
			inl(instance->status_reg)) & ME4600_AO_STATUS_BIT_HF);

		//Unblock interrupts
		ctrl = inl(instance->ctrl_reg);
		if (count >= 0) {	//Copy was successful.
			if (instance->stop_data_count && (instance->stop_data_count <= instance->data_count)) {	//Finishing work. No more interrupts.
				PDEBUG("Finishing work. Interrupt disabled.\n");
				instance->status = ao_status_stream_end_wait;
			} else if (count > 0) {	//Normal work. Enable interrupt.
				PDEBUG("Normal work. Enable interrupt.\n");
				ctrl &= ~ME4600_AO_CTRL_BIT_RESET_IRQ;
				ctrl |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			} else {	//Normal work but there are no more data in buffer. Interrupt active but blocked. stream_write() will unblock it.
				PDEBUG
				    ("No data in software buffer. Interrupt blocked.\n");
				ctrl |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			}
		} else {	//Error during copy.
			instance->status = ao_status_stream_fifo_error;
		}

		outl(ctrl, instance->ctrl_reg);
		PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->ctrl_reg - instance->reg_base, ctrl);
	} else {		//?? more than half
		PDEBUG
		    ("Interrupt come but FIFO more than half full! Reset interrupt.\n");
		//Reset pending interrupt
		ctrl = inl(instance->ctrl_reg);
		ctrl |= ME4600_AO_CTRL_BIT_RESET_IRQ;
		outl(ctrl, instance->ctrl_reg);
		PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->ctrl_reg - instance->reg_base, ctrl);
		ctrl &= ~ME4600_AO_CTRL_BIT_RESET_IRQ;
		outl(ctrl, instance->ctrl_reg);
		PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->ctrl_reg - instance->reg_base, ctrl);
	}

	PINFO("ISR: Buffer count: %d.(T:%d H:%d)\n",
	      me_circ_buf_values(&instance->circ_buf), instance->circ_buf.tail,
	      instance->circ_buf.head);
	PINFO("ISR: Stop count: %d.\n", instance->stop_count);
	PINFO("ISR: Stop data count: %d.\n", instance->stop_data_count);
	PINFO("ISR: Data count: %d.\n", instance->data_count);

	//Inform user
	wake_up_interruptible_all(&instance->wait_queue);

	return IRQ_HANDLED;
}

static void me4600_ao_destructor(struct me_subdevice *subdevice)
{
	me4600_ao_subdevice_t *instance;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	instance->ao_control_task_flag = 0;

	// Reset subdevice to asure clean exit.
	me4600_ao_io_reset_subdevice(subdevice, NULL,
				     ME_IO_RESET_SUBDEVICE_NO_FLAGS);

	// Remove any tasks from work queue. This is paranoic because it was done allready in reset().
	if (!cancel_delayed_work(&instance->ao_control_task)) {	//Wait 2 ticks to be sure that control task is removed from queue.
		set_current_state(TASK_INTERRUPTIBLE);
		schedule_timeout(2);
	}

	if (instance->fifo) {
		if (instance->irq) {
			free_irq(instance->irq, instance);
			instance->irq = 0;
		}

		if (instance->circ_buf.buf) {
			free_pages((unsigned long)instance->circ_buf.buf,
				   ME4600_AO_CIRC_BUF_SIZE_ORDER);
		}
		instance->circ_buf.buf = NULL;
	}

	me_subdevice_deinit(&instance->base);
	kfree(instance);
}

me4600_ao_subdevice_t *me4600_ao_constructor(uint32_t reg_base,
					     spinlock_t *preload_reg_lock,
					     uint32_t *preload_flags,
					     int ao_idx,
					     int fifo,
					     int irq,
					     struct workqueue_struct *me4600_wq)
{
	me4600_ao_subdevice_t *subdevice;
	int err;

	PDEBUG("executed. idx=%d\n", ao_idx);

	// Allocate memory for subdevice instance.
	subdevice = kmalloc(sizeof(me4600_ao_subdevice_t), GFP_KERNEL);

	if (!subdevice) {
		PERROR("Cannot get memory for subdevice instance.\n");
		return NULL;
	}

	memset(subdevice, 0, sizeof(me4600_ao_subdevice_t));

	// Initialize subdevice base class.
	err = me_subdevice_init(&subdevice->base);

	if (err) {
		PERROR("Cannot initialize subdevice base class instance.\n");
		kfree(subdevice);
		return NULL;
	}
	// Initialize spin locks.
	spin_lock_init(&subdevice->subdevice_lock);

	subdevice->preload_reg_lock = preload_reg_lock;
	subdevice->preload_flags = preload_flags;

	// Store analog output index.
	subdevice->ao_idx = ao_idx;

	// Store if analog output has fifo.
	subdevice->fifo = (ao_idx < fifo) ? 1 : 0;

	if (subdevice->fifo) {	// Allocate and initialize circular buffer.
		subdevice->circ_buf.mask = ME4600_AO_CIRC_BUF_COUNT - 1;

		subdevice->circ_buf.buf =
		    (void *)__get_free_pages(GFP_KERNEL,
					     ME4600_AO_CIRC_BUF_SIZE_ORDER);
		PDEBUG("circ_buf = %p size=%ld\n", subdevice->circ_buf.buf,
		       ME4600_AO_CIRC_BUF_SIZE);

		if (!subdevice->circ_buf.buf) {
			PERROR
			    ("Cannot initialize subdevice base class instance.\n");
			kfree(subdevice);
			return NULL;
		}

		memset(subdevice->circ_buf.buf, 0, ME4600_AO_CIRC_BUF_SIZE);
	} else {		// No FIFO.
		subdevice->circ_buf.mask = 0;
		subdevice->circ_buf.buf = NULL;
	}

	subdevice->circ_buf.head = 0;
	subdevice->circ_buf.tail = 0;

	subdevice->status = ao_status_none;
	subdevice->ao_control_task_flag = 0;
	subdevice->timeout.delay = 0;
	subdevice->timeout.start_time = jiffies;

	// Initialize wait queue.
	init_waitqueue_head(&subdevice->wait_queue);

	// Initialize single value to 0V.
	subdevice->single_value = 0x8000;
	subdevice->single_value_in_fifo = 0x8000;

	// Register interrupt service routine.
	if (subdevice->fifo) {
		subdevice->irq = irq;
		if (request_irq(subdevice->irq, me4600_ao_isr,
#ifdef IRQF_DISABLED
				IRQF_DISABLED | IRQF_SHARED,
#else
				SA_INTERRUPT | SA_SHIRQ,
#endif
				ME4600_NAME, subdevice)) {
			PERROR("Cannot get interrupt line.\n");
			PDEBUG("free circ_buf = %p size=%d",
			       subdevice->circ_buf.buf,
			       PAGE_SHIFT << ME4600_AO_CIRC_BUF_SIZE_ORDER);
			free_pages((unsigned long)subdevice->circ_buf.buf,
				   ME4600_AO_CIRC_BUF_SIZE_ORDER);
			me_subdevice_deinit((me_subdevice_t *) subdevice);
			kfree(subdevice);
			return NULL;
		}
		PINFO("Registered irq=%d.\n", subdevice->irq);
	} else {
		subdevice->irq = 0;
	}

	// Initialize registers.
	subdevice->irq_status_reg = reg_base + ME4600_IRQ_STATUS_REG;
	subdevice->preload_reg = reg_base + ME4600_AO_SYNC_REG;
	if (ao_idx == 0) {
		subdevice->ctrl_reg = reg_base + ME4600_AO_00_CTRL_REG;
		subdevice->status_reg = reg_base + ME4600_AO_00_STATUS_REG;
		subdevice->fifo_reg = reg_base + ME4600_AO_00_FIFO_REG;
		subdevice->single_reg = reg_base + ME4600_AO_00_SINGLE_REG;
		subdevice->timer_reg = reg_base + ME4600_AO_00_TIMER_REG;
		subdevice->reg_base = reg_base;
		subdevice->bitpattern = 0;
	} else if (ao_idx == 1) {
		subdevice->ctrl_reg = reg_base + ME4600_AO_01_CTRL_REG;
		subdevice->status_reg = reg_base + ME4600_AO_01_STATUS_REG;
		subdevice->fifo_reg = reg_base + ME4600_AO_01_FIFO_REG;
		subdevice->single_reg = reg_base + ME4600_AO_01_SINGLE_REG;
		subdevice->timer_reg = reg_base + ME4600_AO_01_TIMER_REG;
		subdevice->reg_base = reg_base;
		subdevice->bitpattern = 0;
	} else if (ao_idx == 2) {
		subdevice->ctrl_reg = reg_base + ME4600_AO_02_CTRL_REG;
		subdevice->status_reg = reg_base + ME4600_AO_02_STATUS_REG;
		subdevice->fifo_reg = reg_base + ME4600_AO_02_FIFO_REG;
		subdevice->single_reg = reg_base + ME4600_AO_02_SINGLE_REG;
		subdevice->timer_reg = reg_base + ME4600_AO_02_TIMER_REG;
		subdevice->reg_base = reg_base;
		subdevice->bitpattern = 0;
	} else if (ao_idx == 3) {
		subdevice->ctrl_reg = reg_base + ME4600_AO_03_CTRL_REG;
		subdevice->status_reg = reg_base + ME4600_AO_03_STATUS_REG;
		subdevice->fifo_reg = reg_base + ME4600_AO_03_FIFO_REG;
		subdevice->single_reg = reg_base + ME4600_AO_03_SINGLE_REG;
		subdevice->timer_reg = reg_base + ME4600_AO_03_TIMER_REG;
		subdevice->reg_base = reg_base;
		subdevice->bitpattern = 1;
	} else {
		PERROR_CRITICAL("WRONG SUBDEVICE idx=%d!", ao_idx);
		me_subdevice_deinit((me_subdevice_t *) subdevice);
		if (subdevice->fifo) {
			free_pages((unsigned long)subdevice->circ_buf.buf,
				   ME4600_AO_CIRC_BUF_SIZE_ORDER);
		}
		subdevice->circ_buf.buf = NULL;
		kfree(subdevice);
		return NULL;
	}

	// Override base class methods.
	subdevice->base.me_subdevice_destructor = me4600_ao_destructor;
	subdevice->base.me_subdevice_io_reset_subdevice =
	    me4600_ao_io_reset_subdevice;
	subdevice->base.me_subdevice_io_single_config =
	    me4600_ao_io_single_config;
	subdevice->base.me_subdevice_io_single_read = me4600_ao_io_single_read;
	subdevice->base.me_subdevice_io_single_write =
	    me4600_ao_io_single_write;
	subdevice->base.me_subdevice_io_stream_config =
	    me4600_ao_io_stream_config;
	subdevice->base.me_subdevice_io_stream_new_values =
	    me4600_ao_io_stream_new_values;
	subdevice->base.me_subdevice_io_stream_write =
	    me4600_ao_io_stream_write;
	subdevice->base.me_subdevice_io_stream_start =
	    me4600_ao_io_stream_start;
	subdevice->base.me_subdevice_io_stream_status =
	    me4600_ao_io_stream_status;
	subdevice->base.me_subdevice_io_stream_stop = me4600_ao_io_stream_stop;
	subdevice->base.me_subdevice_query_number_channels =
	    me4600_ao_query_number_channels;
	subdevice->base.me_subdevice_query_subdevice_type =
	    me4600_ao_query_subdevice_type;
	subdevice->base.me_subdevice_query_subdevice_caps =
	    me4600_ao_query_subdevice_caps;
	subdevice->base.me_subdevice_query_subdevice_caps_args =
	    me4600_ao_query_subdevice_caps_args;
	subdevice->base.me_subdevice_query_range_by_min_max =
	    me4600_ao_query_range_by_min_max;
	subdevice->base.me_subdevice_query_number_ranges =
	    me4600_ao_query_number_ranges;
	subdevice->base.me_subdevice_query_range_info =
	    me4600_ao_query_range_info;
	subdevice->base.me_subdevice_query_timer = me4600_ao_query_timer;

	// Prepare work queue
	subdevice->me4600_workqueue = me4600_wq;

/* workqueue API changed in kernel 2.6.20 */
	INIT_DELAYED_WORK(&subdevice->ao_control_task,
			  me4600_ao_work_control_task);

	if (subdevice->fifo) {	// Set speed for single operations.
		outl(ME4600_AO_MIN_CHAN_TICKS - 1, subdevice->timer_reg);
		subdevice->hardware_stop_delay = HZ / 10;	//100ms
	}

	return subdevice;
}

/** @brief Stop presentation. Preserve FIFOs.
*
* @param instance The subdevice instance (pointer).
*/
inline int ao_stop_immediately(me4600_ao_subdevice_t *instance)
{
	unsigned long cpu_flags;
	uint32_t ctrl;
	int timeout;
	int i;

	timeout =
	    (instance->hardware_stop_delay >
	     (HZ / 10)) ? instance->hardware_stop_delay : HZ / 10;
	for (i = 0; i <= timeout; i++) {
		spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
		// Stop all actions. No conditions! Block interrupts. Leave FIFO untouched!
		ctrl = inl(instance->ctrl_reg);
		ctrl |=
		    ME4600_AO_CTRL_BIT_STOP | ME4600_AO_CTRL_BIT_IMMEDIATE_STOP
		    | ME4600_AO_CTRL_BIT_RESET_IRQ;
		ctrl &=
		    ~(ME4600_AO_CTRL_BIT_ENABLE_IRQ |
		      ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG);
		outl(ctrl, instance->ctrl_reg);
		PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->ctrl_reg - instance->reg_base, ctrl);
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

		if (!(inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM)) {	// Exit.
			break;
		}
		//Still working!
		set_current_state(TASK_INTERRUPTIBLE);
		schedule_timeout(1);
	}

	if (i > timeout) {
		PERROR_CRITICAL("FSM IS BUSY!\n");
		return ME_ERRNO_INTERNAL;
	}
	return ME_ERRNO_SUCCESS;
}

/** @brief Copy data from circular buffer to fifo (fast) in wraparound.
* @note This is time critical function. Checking is done at begining and end only.
* @note The is not reasonable way to check how many walues was in FIFO at begining. The count must be managed externaly.
*
* @param instance The subdevice instance (pointer).
* @param count Maximum number of copied data.
* @param start_pos Position of the firs value in buffer.
*
* @return On success: Number of copied data.
* @return On error/success: 0.	No datas were copied => no data in buffer.
* @return On error: -ME_ERRNO_FIFO_BUFFER_OVERFLOW.
*/
inline int ao_write_data_wraparound(me4600_ao_subdevice_t *instance, int count,
				    int start_pos)
{				/// @note This is time critical function!
	uint32_t status;
	uint32_t value;
	int pos =
	    (instance->circ_buf.tail + start_pos) & instance->circ_buf.mask;
	int local_count = count;
	int i = 1;

	if (count <= 0) {	//Wrong count!
		return 0;
	}

	while (i < local_count) {
		//Get value from buffer
		value = *(instance->circ_buf.buf + pos);
		//Prepare it
		if (instance->ao_idx & 0x1) {
			value <<= 16;
		}
		//Put value to FIFO
		outl(value, instance->fifo_reg);
		//PDEBUG_REG("idx=%d fifo_reg outl(0x%lX+0x%lX)=0x%x\n", instance->ao_idx, instance->reg_base, instance->fifo_reg - instance->reg_base, value);

		pos++;
		pos &= instance->circ_buf.mask;
		if (pos == instance->circ_buf.head) {
			pos = instance->circ_buf.tail;
		}
		i++;
	}

	status = inl(instance->status_reg);
	if (!(status & ME4600_AO_STATUS_BIT_FF)) {	//FIFO is full before all datas were copied!
		PERROR("FIFO was full before all datas were copied! idx=%d\n",
		       instance->ao_idx);
		return -ME_ERRNO_FIFO_BUFFER_OVERFLOW;
	} else {		//Add last value
		value = *(instance->circ_buf.buf + pos);
		if (instance->ao_idx & 0x1) {
			value <<= 16;
		}
		//Put value to FIFO
		outl(value, instance->fifo_reg);
		//PDEBUG_REG("idx=%d fifo_reg outl(0x%lX+0x%lX)=0x%x\n", instance->ao_idx, instance->reg_base, instance->fifo_reg - instance->reg_base, value);
	}

	PINFO("WRAPAROUND LOADED %d values. idx=%d\n", local_count,
	      instance->ao_idx);
	return local_count;
}

/** @brief Copy data from software buffer to fifo (fast).
* @note This is time critical function. Checking is done at begining and end only.
* @note The is not reasonable way to check how many walues was in FIFO at begining. The count must be managed externaly.
*
* @param instance The subdevice instance (pointer).
* @param count Maximum number of copied data.
* @param start_pos Position of the firs value in buffer.
*
* @return On success: Number of copied data.
* @return On error/success: 0.	No datas were copied => no data in buffer.
* @return On error: -ME_ERRNO_FIFO_BUFFER_OVERFLOW.
*/
inline int ao_write_data(me4600_ao_subdevice_t *instance, int count,
			 int start_pos)
{				/// @note This is time critical function!
	uint32_t status;
	uint32_t value;
	int pos =
	    (instance->circ_buf.tail + start_pos) & instance->circ_buf.mask;
	int local_count = count;
	int max_count;
	int i = 1;

	if (count <= 0) {	//Wrong count!
		return 0;
	}

	max_count = me_circ_buf_values(&instance->circ_buf) - start_pos;
	if (max_count <= 0) {	//No data to copy!
		return 0;
	}

	if (max_count < count) {
		local_count = max_count;
	}

	while (i < local_count) {
		//Get value from buffer
		value = *(instance->circ_buf.buf + pos);
		//Prepare it
		if (instance->ao_idx & 0x1) {
			value <<= 16;
		}
		//Put value to FIFO
		outl(value, instance->fifo_reg);
		//PDEBUG_REG("idx=%d fifo_reg outl(0x%lX+0x%lX)=0x%x\n", instance->ao_idx, instance->reg_base, instance->fifo_reg - instance->reg_base, value);

		pos++;
		pos &= instance->circ_buf.mask;
		i++;
	}

	status = inl(instance->status_reg);
	if (!(status & ME4600_AO_STATUS_BIT_FF)) {	//FIFO is full before all datas were copied!
		PERROR("FIFO was full before all datas were copied! idx=%d\n",
		       instance->ao_idx);
		return -ME_ERRNO_FIFO_BUFFER_OVERFLOW;
	} else {		//Add last value
		value = *(instance->circ_buf.buf + pos);
		if (instance->ao_idx & 0x1) {
			value <<= 16;
		}
		//Put value to FIFO
		outl(value, instance->fifo_reg);
		//PDEBUG_REG("idx=%d fifo_reg outl(0x%lX+0x%lX)=0x%x\n", instance->ao_idx, instance->reg_base, instance->fifo_reg - instance->reg_base, value);
	}

	PINFO("FAST LOADED %d values. idx=%d\n", local_count, instance->ao_idx);
	return local_count;
}

/** @brief Copy data from software buffer to fifo (slow).
* @note This is slow function that copy all data from buffer to FIFO with full control.
*
* @param instance The subdevice instance (pointer).
* @param count Maximum number of copied data.
* @param start_pos Position of the firs value in buffer.
*
* @return On success: Number of copied values.
* @return On error/success: 0.	FIFO was full at begining.
* @return On error: -ME_ERRNO_RING_BUFFER_UNDEFFLOW.
*/
inline int ao_write_data_pooling(me4600_ao_subdevice_t *instance, int count,
				 int start_pos)
{				/// @note This is slow function!
	uint32_t status;
	uint32_t value;
	int pos =
	    (instance->circ_buf.tail + start_pos) & instance->circ_buf.mask;
	int local_count = count;
	int i;
	int max_count;

	if (count <= 0) {	//Wrong count!
		PERROR("SLOW LOADED: Wrong count! idx=%d\n", instance->ao_idx);
		return 0;
	}

	max_count = me_circ_buf_values(&instance->circ_buf) - start_pos;
	if (max_count <= 0) {	//No data to copy!
		PERROR("SLOW LOADED: No data to copy! idx=%d\n",
		       instance->ao_idx);
		return 0;
	}

	if (max_count < count) {
		local_count = max_count;
	}

	for (i = 0; i < local_count; i++) {
		status = inl(instance->status_reg);
		if (!(status & ME4600_AO_STATUS_BIT_FF)) {	//FIFO is full!
			return i;
		}
		//Get value from buffer
		value = *(instance->circ_buf.buf + pos);
		//Prepare it
		if (instance->ao_idx & 0x1) {
			value <<= 16;
		}
		//Put value to FIFO
		outl(value, instance->fifo_reg);
		//PDEBUG_REG("idx=%d fifo_reg outl(0x%lX+0x%lX)=0x%x\n", instance->ao_idx, instance->reg_base, instance->fifo_reg - instance->reg_base, value);

		pos++;
		pos &= instance->circ_buf.mask;
	}

	PINFO("SLOW LOADED %d values. idx=%d\n", local_count, instance->ao_idx);
	return local_count;
}

/** @brief Copy data from user space to circular buffer.
* @param instance The subdevice instance (pointer).
* @param count Number of datas in user space.
* @param user_values Buffer's pointer.
*
* @return On success: Number of copied values.
* @return On error: -ME_ERRNO_INTERNAL.
*/
inline int ao_get_data_from_user(me4600_ao_subdevice_t *instance, int count,
				 int *user_values)
{
	int i, err;
	int empty_space;
	int copied;
	int value;

	empty_space = me_circ_buf_space(&instance->circ_buf);
	//We have only this space free.
	copied = (count < empty_space) ? count : empty_space;
	for (i = 0; i < copied; i++) {	//Copy from user to buffer
		if ((err = get_user(value, (int *)(user_values + i)))) {
			PERROR
			    ("BUFFER LOADED: get_user(0x%p) return an error: %d. idx=%d\n",
			     user_values + i, err, instance->ao_idx);
			return -ME_ERRNO_INTERNAL;
		}
		/// @note The analog output in me4600 series has size of 16 bits.
		*(instance->circ_buf.buf + instance->circ_buf.head) =
		    (uint16_t) value;
		instance->circ_buf.head++;
		instance->circ_buf.head &= instance->circ_buf.mask;
	}

	PINFO("BUFFER LOADED %d values. idx=%d\n", copied, instance->ao_idx);
	return copied;
}

/** @brief Checking actual hardware and logical state.
* @param instance The subdevice instance (pointer).
*/
static void me4600_ao_work_control_task(struct work_struct *work)
{
	me4600_ao_subdevice_t *instance;
	unsigned long cpu_flags = 0;
	uint32_t status;
	uint32_t ctrl;
	uint32_t synch;
	int reschedule = 0;
	int signaling = 0;

	instance =
	    container_of((void *)work, me4600_ao_subdevice_t, ao_control_task);
	PINFO("<%s: %ld> executed. idx=%d\n", __func__, jiffies,
	      instance->ao_idx);

	status = inl(instance->status_reg);
	PDEBUG_REG("status_reg inl(0x%lX+0x%lX)=0x%x\n", instance->reg_base,
		   instance->status_reg - instance->reg_base, status);

	switch (instance->status) {	// Checking actual mode.

		// Not configured for work.
	case ao_status_none:
		break;

		//This are stable modes. No need to do anything. (?)
	case ao_status_single_configured:
	case ao_status_stream_configured:
	case ao_status_stream_fifo_error:
	case ao_status_stream_buffer_error:
	case ao_status_stream_error:
		PERROR("Shouldn't be running!.\n");
		break;

	case ao_status_stream_end:
		if (!instance->fifo) {
			PERROR_CRITICAL
			    ("Streaming on single device! This feature is not implemented in this version!\n");
			instance->status = ao_status_stream_error;
			// Signal the end.
			signaling = 1;
			break;
		}
	case ao_status_single_end:
		if (status & ME4600_AO_STATUS_BIT_FSM) {	// State machine is working but the status is set to end. Force stop.

			// Wait for stop.
			reschedule = 1;
		}

		spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
		// Stop all actions. No conditions! Block interrupts and trigger. Leave FIFO untouched!
		ctrl = inl(instance->ctrl_reg);
		ctrl |=
		    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP | ME4600_AO_CTRL_BIT_STOP
		    | ME4600_AO_CTRL_BIT_RESET_IRQ;
		ctrl &=
		    ~(ME4600_AO_CTRL_BIT_ENABLE_IRQ |
		      ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG);
		ctrl &=
		    ~(ME4600_AO_CTRL_BIT_EX_TRIG_EDGE |
		      ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH);
		outl(ctrl, instance->ctrl_reg);
		PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
			   instance->reg_base,
			   instance->ctrl_reg - instance->reg_base, ctrl);
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
		break;

		// Single modes
	case ao_status_single_run_wait:
	case ao_status_single_run:
	case ao_status_single_end_wait:

		if (!(status & ME4600_AO_STATUS_BIT_FSM)) {	// State machine is not working.
			if (((instance->fifo)
			     && (!(status & ME4600_AO_STATUS_BIT_EF)))
			    || (!(instance->fifo))) {	// Single is in end state.
				PDEBUG("Single call has been complited.\n");

				// Set correct value for single_read();
				instance->single_value =
				    instance->single_value_in_fifo;

				// Set status as 'ao_status_single_end'
				instance->status = ao_status_single_end;

				// Signal the end.
				signaling = 1;
				// Wait for stop ISM.
				reschedule = 1;

				break;
			}
		}
		// Check timeout.
		if ((instance->timeout.delay) && ((jiffies - instance->timeout.start_time) >= instance->timeout.delay)) {	// Timeout
			PDEBUG("Timeout reached.\n");
			// Stop all actions. No conditions! Block interrupts and trigger. Leave FIFO untouched!
			spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
			ctrl = inl(instance->ctrl_reg);
			ctrl |=
			    ME4600_AO_CTRL_BIT_STOP |
			    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP |
			    ME4600_AO_CTRL_BIT_RESET_IRQ;
			ctrl &=
			    ~(ME4600_AO_CTRL_BIT_ENABLE_IRQ |
			      ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG);
			/// Fix for timeout error.
			ctrl &=
			    ~(ME4600_AO_CTRL_BIT_EX_TRIG_EDGE |
			      ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH);
			if (instance->fifo) {	//Disabling FIFO
				ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_FIFO;
			}
			outl(ctrl, instance->ctrl_reg);
			PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->ctrl_reg - instance->reg_base,
				   ctrl);
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			spin_lock(instance->preload_reg_lock);
			//Remove from synchronous start. Block triggering from this output.
			synch = inl(instance->preload_reg);
			synch &=
			    ~((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) <<
			      instance->ao_idx);
			if (!(instance->fifo)) {	// No FIFO - set to single safe mode
				synch |=
				    ME4600_AO_SYNC_HOLD << instance->ao_idx;
			}
			outl(synch, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   synch);
			spin_unlock(instance->preload_reg_lock);

			if (!(instance->fifo)) {	// No FIFO
				// Restore old settings.
				PDEBUG("Write old value back to register.\n");
				outl(instance->single_value,
				     instance->single_reg);
				PDEBUG_REG
				    ("single_reg outl(0x%lX+0x%lX)=0x%x\n",
				     instance->reg_base,
				     instance->single_reg - instance->reg_base,
				     instance->single_value);
			}
			// Set correct value for single_read();
			instance->single_value_in_fifo = instance->single_value;

			instance->status = ao_status_single_end;

			// Signal the end.
			signaling = 1;
		}
		// Wait for stop.
		reschedule = 1;
		break;

		// Stream modes
	case ao_status_stream_run_wait:
		if (!instance->fifo) {
			PERROR_CRITICAL
			    ("Streaming on single device! This feature is not implemented in this version!\n");
			instance->status = ao_status_stream_error;
			// Signal the end.
			signaling = 1;
			break;
		}

		if (status & ME4600_AO_STATUS_BIT_FSM) {	// State machine is working. Waiting for start finish.
			instance->status = ao_status_stream_run;

			// Signal end of this step
			signaling = 1;
		} else {	// State machine is not working.
			if (!(status & ME4600_AO_STATUS_BIT_EF)) {	// FIFO is empty. Procedure has started and finish already!
				instance->status = ao_status_stream_end;

				// Signal the end.
				signaling = 1;
				// Wait for stop.
				reschedule = 1;
				break;
			}
		}

		// Check timeout.
		if ((instance->timeout.delay) && ((jiffies - instance->timeout.start_time) >= instance->timeout.delay)) {	// Timeout
			PDEBUG("Timeout reached.\n");
			// Stop all actions. No conditions! Block interrupts. Leave FIFO untouched!
			spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
			ctrl = inl(instance->ctrl_reg);
			ctrl |=
			    ME4600_AO_CTRL_BIT_STOP |
			    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP |
			    ME4600_AO_CTRL_BIT_RESET_IRQ;
			ctrl &=
			    ~(ME4600_AO_CTRL_BIT_ENABLE_IRQ |
			      ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG);
			outl(ctrl, instance->ctrl_reg);
			PDEBUG_REG("ctrl_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->ctrl_reg - instance->reg_base,
				   ctrl);
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
			spin_lock(instance->preload_reg_lock);
			//Remove from synchronous start. Block triggering from this output.
			synch = inl(instance->preload_reg);
			synch &=
			    ~((ME4600_AO_SYNC_HOLD | ME4600_AO_SYNC_EXT_TRIG) <<
			      instance->ao_idx);
			outl(synch, instance->preload_reg);
			PDEBUG_REG("preload_reg outl(0x%lX+0x%lX)=0x%x\n",
				   instance->reg_base,
				   instance->preload_reg - instance->reg_base,
				   synch);
			spin_unlock(instance->preload_reg_lock);

			instance->status = ao_status_stream_end;

			// Signal the end.
			signaling = 1;
		}
		// Wait for stop.
		reschedule = 1;
		break;

	case ao_status_stream_run:
		if (!instance->fifo) {
			PERROR_CRITICAL
			    ("Streaming on single device! This feature is not implemented in this version!\n");
			instance->status = ao_status_stream_error;
			// Signal the end.
			signaling = 1;
			break;
		}

		if (!(status & ME4600_AO_STATUS_BIT_FSM)) {	// State machine is not working. This is an error.
			// BROKEN PIPE!
			if (!(status & ME4600_AO_STATUS_BIT_EF)) {	// FIFO is empty.
				if (me_circ_buf_values(&instance->circ_buf)) {	// Software buffer is not empty.
					if (instance->stop_data_count && (instance->stop_data_count <= instance->data_count)) {	//Finishing work. Requed data shown.
						PDEBUG
						    ("ISM stoped. No data in FIFO. Buffer is not empty.\n");
						instance->status =
						    ao_status_stream_end;
					} else {
						PERROR
						    ("Output stream has been broken. ISM stoped. No data in FIFO. Buffer is not empty.\n");
						instance->status =
						    ao_status_stream_buffer_error;
					}
				} else {	// Software buffer is empty.
					PDEBUG
					    ("ISM stoped. No data in FIFO. Buffer is empty.\n");
					instance->status = ao_status_stream_end;
				}
			} else {	// There are still datas in FIFO.
				if (me_circ_buf_values(&instance->circ_buf)) {	// Software buffer is not empty.
					PERROR
					    ("Output stream has been broken. ISM stoped but some data in FIFO and buffer.\n");
				} else {	// Software buffer is empty.
					PERROR
					    ("Output stream has been broken. ISM stoped but some data in FIFO. Buffer is empty.\n");
				}
				instance->status = ao_status_stream_fifo_error;

			}

			// Signal the failure.
			signaling = 1;
			break;
		}
		// Wait for stop.
		reschedule = 1;
		break;

	case ao_status_stream_end_wait:
		if (!instance->fifo) {
			PERROR_CRITICAL
			    ("Streaming on single device! This feature is not implemented in this version!\n");
			instance->status = ao_status_stream_error;
			// Signal the end.
			signaling = 1;
			break;
		}

		if (!(status & ME4600_AO_STATUS_BIT_FSM)) {	// State machine is not working. Waiting for stop finish.
			instance->status = ao_status_stream_end;
			signaling = 1;
		}
		// State machine is working.
		reschedule = 1;
		break;

	default:
		PERROR_CRITICAL("Status is in wrong state (%d)!\n",
				instance->status);
		instance->status = ao_status_stream_error;
		// Signal the end.
		signaling = 1;
		break;

	}

	if (signaling) {	//Signal it.
		wake_up_interruptible_all(&instance->wait_queue);
	}

	if (instance->ao_control_task_flag && reschedule) {	// Reschedule task
		queue_delayed_work(instance->me4600_workqueue,
				   &instance->ao_control_task, 1);
	} else {
		PINFO("<%s> Ending control task.\n", __func__);
	}

}
#else
/// @note SPECIAL BUILD FOR BOSCH
/// @author Guenter Gebhardt
static int me4600_ao_io_reset_subdevice(me_subdevice_t *subdevice,
					struct file *filep, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	uint32_t tmp;
	unsigned long status;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	ME_SUBDEVICE_ENTER spin_lock_irqsave(&instance->subdevice_lock, status);
	spin_lock(instance->preload_reg_lock);
	tmp = inl(instance->preload_reg);
	tmp &= ~(0x10001 << instance->ao_idx);
	outl(tmp, instance->preload_reg);
	*instance->preload_flags &= ~(0x1 << instance->ao_idx);
	spin_unlock(instance->preload_reg_lock);

	tmp = inl(instance->ctrl_reg);
	tmp |= ME4600_AO_CTRL_BIT_STOP | ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
	outl(tmp, instance->ctrl_reg);

	while (inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM) ;

	outl(ME4600_AO_CTRL_BIT_STOP | ME4600_AO_CTRL_BIT_IMMEDIATE_STOP,
	     instance->ctrl_reg);

	outl(0x8000, instance->single_reg);

	instance->single_value = 0x8000;
	instance->circ_buf.head = 0;
	instance->circ_buf.tail = 0;

	spin_unlock_irqrestore(&instance->subdevice_lock, status);

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_single_config(me_subdevice_t *subdevice,
				      struct file *filep,
				      int channel,
				      int single_config,
				      int ref,
				      int trig_chan,
				      int trig_type, int trig_edge, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	uint32_t tmp;
	unsigned long cpu_flags;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	ME_SUBDEVICE_ENTER
	    spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);

	if (inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM) {
		PERROR("Subdevice is busy.\n");
		err = ME_ERRNO_SUBDEVICE_BUSY;
		goto ERROR;
	}

	if (channel == 0) {
		if (single_config == 0) {
			if (ref == ME_REF_AO_GROUND) {
				if (trig_chan == ME_TRIG_CHAN_DEFAULT) {
					if (trig_type == ME_TRIG_TYPE_SW) {
						tmp = inl(instance->ctrl_reg);
						tmp |=
						    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
						outl(tmp, instance->ctrl_reg);
						tmp =
						    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
						outl(tmp, instance->ctrl_reg);

						spin_lock(instance->
							  preload_reg_lock);
						tmp =
						    inl(instance->preload_reg);
						tmp &=
						    ~(0x10001 << instance->
						      ao_idx);
						outl(tmp,
						     instance->preload_reg);
						*instance->preload_flags &=
						    ~(0x1 << instance->ao_idx);
						spin_unlock(instance->
							    preload_reg_lock);
					} else if (trig_type ==
						   ME_TRIG_TYPE_EXT_DIGITAL) {
						if (trig_edge ==
						    ME_TRIG_EDGE_RISING) {
							tmp =
							    inl(instance->
								ctrl_reg);
							tmp |=
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
							outl(tmp,
							     instance->
							     ctrl_reg);
							tmp =
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP
							    |
							    ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;
							outl(tmp,
							     instance->
							     ctrl_reg);
						} else if (trig_edge ==
							   ME_TRIG_EDGE_FALLING)
						{
							tmp =
							    inl(instance->
								ctrl_reg);
							tmp |=
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
							outl(tmp,
							     instance->
							     ctrl_reg);
							tmp =
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP
							    |
							    ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG
							    |
							    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE;
							outl(tmp,
							     instance->
							     ctrl_reg);
						} else if (trig_edge ==
							   ME_TRIG_EDGE_ANY) {
							tmp =
							    inl(instance->
								ctrl_reg);
							tmp |=
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
							outl(tmp,
							     instance->
							     ctrl_reg);
							tmp =
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP
							    |
							    ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG
							    |
							    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE
							    |
							    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH;
							outl(tmp,
							     instance->
							     ctrl_reg);
						} else {
							PERROR
							    ("Invalid trigger edge.\n");
							err =
							    ME_ERRNO_INVALID_TRIG_EDGE;
							goto ERROR;
						}

						spin_lock(instance->
							  preload_reg_lock);

						tmp =
						    inl(instance->preload_reg);
						tmp &=
						    ~(0x10001 << instance->
						      ao_idx);
						tmp |= 0x1 << instance->ao_idx;
						outl(tmp,
						     instance->preload_reg);
						*instance->preload_flags &=
						    ~(0x1 << instance->ao_idx);
						spin_unlock(instance->
							    preload_reg_lock);
					} else {
						PERROR
						    ("Invalid trigger type.\n");
						err =
						    ME_ERRNO_INVALID_TRIG_TYPE;
						goto ERROR;
					}
				} else if (trig_chan ==
					   ME_TRIG_CHAN_SYNCHRONOUS) {
					if (trig_type == ME_TRIG_TYPE_SW) {
						tmp = inl(instance->ctrl_reg);
						tmp |=
						    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
						outl(tmp, instance->ctrl_reg);
						tmp =
						    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
						outl(tmp, instance->ctrl_reg);

						spin_lock(instance->
							  preload_reg_lock);
						tmp =
						    inl(instance->preload_reg);
						tmp &=
						    ~(0x10001 << instance->
						      ao_idx);
						tmp |= 0x1 << instance->ao_idx;
						outl(tmp,
						     instance->preload_reg);
						*instance->preload_flags |=
						    0x1 << instance->ao_idx;
						spin_unlock(instance->
							    preload_reg_lock);
					} else if (trig_type ==
						   ME_TRIG_TYPE_EXT_DIGITAL) {
						if (trig_edge ==
						    ME_TRIG_EDGE_RISING) {
							tmp =
							    inl(instance->
								ctrl_reg);
							tmp |=
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
							outl(tmp,
							     instance->
							     ctrl_reg);
							tmp =
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
							outl(tmp,
							     instance->
							     ctrl_reg);
						} else if (trig_edge ==
							   ME_TRIG_EDGE_FALLING)
						{
							tmp =
							    inl(instance->
								ctrl_reg);
							tmp |=
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
							outl(tmp,
							     instance->
							     ctrl_reg);
							tmp =
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP
							    |
							    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE;
							outl(tmp,
							     instance->
							     ctrl_reg);
						} else if (trig_edge ==
							   ME_TRIG_EDGE_ANY) {
							tmp =
							    inl(instance->
								ctrl_reg);
							tmp |=
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
							outl(tmp,
							     instance->
							     ctrl_reg);
							tmp =
							    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP
							    |
							    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE
							    |
							    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH;
							outl(tmp,
							     instance->
							     ctrl_reg);
						} else {
							PERROR
							    ("Invalid trigger edge.\n");
							err =
							    ME_ERRNO_INVALID_TRIG_EDGE;
							goto ERROR;
						}

						spin_lock(instance->
							  preload_reg_lock);

						tmp =
						    inl(instance->preload_reg);
						tmp |=
						    0x10001 << instance->ao_idx;
						outl(tmp,
						     instance->preload_reg);
						*instance->preload_flags &=
						    ~(0x1 << instance->ao_idx);
						spin_unlock(instance->
							    preload_reg_lock);
					} else {
						PERROR
						    ("Invalid trigger type.\n");
						err =
						    ME_ERRNO_INVALID_TRIG_TYPE;
						goto ERROR;
					}
				} else {
					PERROR
					    ("Invalid trigger channel specified.\n");
					err = ME_ERRNO_INVALID_REF;
					goto ERROR;
				}
			} else {
				PERROR("Invalid analog reference specified.\n");
				err = ME_ERRNO_INVALID_REF;
				goto ERROR;
			}
		} else {
			PERROR("Invalid single config specified.\n");
			err = ME_ERRNO_INVALID_SINGLE_CONFIG;
			goto ERROR;
		}
	} else {
		PERROR("Invalid channel number specified.\n");
		err = ME_ERRNO_INVALID_CHANNEL;
		goto ERROR;
	}

ERROR:

	spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_single_read(me_subdevice_t *subdevice,
				    struct file *filep,
				    int channel,
				    int *value, int time_out, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	unsigned long tmp;
	unsigned long cpu_flags;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	if (channel != 0) {
		PERROR("Invalid channel number specified.\n");
		return ME_ERRNO_INVALID_CHANNEL;
	}

	ME_SUBDEVICE_ENTER
	    spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
	tmp = inl(instance->ctrl_reg);

	if (tmp & 0x3) {
		PERROR("Not in single mode.\n");
		err = ME_ERRNO_PREVIOUS_CONFIG;
	} else {
		*value = instance->single_value;
	}

	spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_single_write(me_subdevice_t *subdevice,
				     struct file *filep,
				     int channel,
				     int value, int time_out, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	unsigned long mask = 0;
	unsigned long tmp;
	unsigned long cpu_flags;
	int i;
	wait_queue_head_t queue;
	unsigned long j;
	unsigned long delay = 0;

	PDEBUG("executed.\n");

	init_waitqueue_head(&queue);

	instance = (me4600_ao_subdevice_t *) subdevice;

	if (channel != 0) {
		PERROR("Invalid channel number specified.\n");
		return ME_ERRNO_INVALID_CHANNEL;
	}

	if (time_out < 0) {
		PERROR("Invalid timeout specified.\n");
		return ME_ERRNO_INVALID_TIMEOUT;
	}

	if (time_out) {
		delay = (time_out * HZ) / 1000;

		if (delay == 0)
			delay = 1;
	}

	ME_SUBDEVICE_ENTER
	    spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);

	tmp = inl(instance->ctrl_reg);

	if (tmp & 0x3) {
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
		PERROR("Not in single mode.\n");
		err = ME_ERRNO_PREVIOUS_CONFIG;
		goto ERROR;
	}

	if (tmp & ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG) {
		outl(value, instance->single_reg);
		instance->single_value = value;
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

		if (!(flags & ME_IO_SINGLE_TYPE_WRITE_NONBLOCKING)) {
			j = jiffies;

			while (inl(instance->status_reg) &
			       ME4600_AO_STATUS_BIT_FSM) {
				interruptible_sleep_on_timeout(&queue, 1);

				if (signal_pending(current)) {
					PERROR
					    ("Wait on external trigger interrupted by signal.\n");
					err = ME_ERRNO_SIGNAL;
					goto ERROR;
				}

				if (delay && ((jiffies - j) > delay)) {
					PERROR("Timeout reached.\n");
					err = ME_ERRNO_TIMEOUT;
					goto ERROR;
				}
			}
		}
	} else if ((inl(instance->preload_reg) & (0x10001 << instance->ao_idx))
		   == (0x10001 << instance->ao_idx)) {
		if (flags & ME_IO_SINGLE_TYPE_TRIG_SYNCHRONOUS) {
			tmp |= ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;
			outl(tmp, instance->ctrl_reg);
			outl(value, instance->single_reg);
			instance->single_value = value;
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			if (!(flags & ME_IO_SINGLE_TYPE_WRITE_NONBLOCKING)) {
				j = jiffies;

				while (inl(instance->status_reg) &
				       ME4600_AO_STATUS_BIT_FSM) {
					interruptible_sleep_on_timeout(&queue,
								       1);

					if (signal_pending(current)) {
						PERROR
						    ("Wait on external trigger interrupted by signal.\n");
						err = ME_ERRNO_SIGNAL;
						goto ERROR;
					}

					if (delay && ((jiffies - j) > delay)) {
						PERROR("Timeout reached.\n");
						err = ME_ERRNO_TIMEOUT;
						goto ERROR;
					}
				}
			}
		} else {
			outl(value, instance->single_reg);
			instance->single_value = value;
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
		}
	} else if ((inl(instance->preload_reg) & (0x10001 << instance->ao_idx))
		   == (0x1 << instance->ao_idx)) {
		outl(value, instance->single_reg);
		instance->single_value = value;

		PDEBUG("Synchronous SW, flags = 0x%X.\n", flags);

		if (flags & ME_IO_SINGLE_TYPE_TRIG_SYNCHRONOUS) {
			PDEBUG("Trigger synchronous SW.\n");
			spin_lock(instance->preload_reg_lock);
			tmp = inl(instance->preload_reg);

			for (i = 0; i < ME4600_AO_MAX_SUBDEVICES; i++) {
				if ((*instance->preload_flags & (0x1 << i))) {
					if ((tmp & (0x10001 << i)) ==
					    (0x1 << i)) {
						mask |= 0x1 << i;
					}
				}
			}

			tmp &= ~(mask);

			outl(tmp, instance->preload_reg);
			spin_unlock(instance->preload_reg_lock);
		}

		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
	} else {
		outl(value, instance->single_reg);
		instance->single_value = value;
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
	}

ERROR:

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_config(me_subdevice_t *subdevice,
				      struct file *filep,
				      meIOStreamConfig_t *config_list,
				      int count,
				      meIOStreamTrigger_t *trigger,
				      int fifo_irq_threshold, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	unsigned long ctrl;
	unsigned long tmp;
	unsigned long cpu_flags;
	uint64_t conv_ticks;
	unsigned int conv_start_ticks_low = trigger->iConvStartTicksLow;
	unsigned int conv_start_ticks_high = trigger->iConvStartTicksHigh;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	conv_ticks =
	    (uint64_t) conv_start_ticks_low +
	    ((uint64_t) conv_start_ticks_high << 32);

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	ME_SUBDEVICE_ENTER
	    spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);

	if ((inl(instance->status_reg)) & ME4600_AO_STATUS_BIT_FSM) {
		PERROR("Subdevice is busy.\n");
		err = ME_ERRNO_SUBDEVICE_BUSY;
		goto ERROR;
	}

	ctrl = inl(instance->ctrl_reg);
	ctrl |= ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
	outl(ctrl, instance->ctrl_reg);
	ctrl = ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
	outl(ctrl, instance->ctrl_reg);

	if (count != 1) {
		PERROR("Invalid stream configuration list count specified.\n");
		err = ME_ERRNO_INVALID_CONFIG_LIST_COUNT;
		goto ERROR;
	}

	if (config_list[0].iChannel != 0) {
		PERROR("Invalid channel number specified.\n");
		err = ME_ERRNO_INVALID_CHANNEL;
		goto ERROR;
	}

	if (config_list[0].iStreamConfig != 0) {
		PERROR("Invalid stream config specified.\n");
		err = ME_ERRNO_INVALID_STREAM_CONFIG;
		goto ERROR;
	}

	if (config_list[0].iRef != ME_REF_AO_GROUND) {
		PERROR("Invalid analog reference.\n");
		err = ME_ERRNO_INVALID_REF;
		goto ERROR;
	}

	if ((trigger->iAcqStartTicksLow != 0)
	    || (trigger->iAcqStartTicksHigh != 0)) {
		PERROR
		    ("Invalid acquisition start trigger argument specified.\n");
		err = ME_ERRNO_INVALID_ACQ_START_ARG;
		goto ERROR;
	}

	switch (trigger->iAcqStartTrigType) {

	case ME_TRIG_TYPE_SW:
		break;

	case ME_TRIG_TYPE_EXT_DIGITAL:
		ctrl |= ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;

		switch (trigger->iAcqStartTrigEdge) {

		case ME_TRIG_EDGE_RISING:
			break;

		case ME_TRIG_EDGE_FALLING:
			ctrl |= ME4600_AO_CTRL_BIT_EX_TRIG_EDGE;

			break;

		case ME_TRIG_EDGE_ANY:
			ctrl |=
			    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE |
			    ME4600_AO_CTRL_BIT_EX_TRIG_EDGE_BOTH;

			break;

		default:
			PERROR
			    ("Invalid acquisition start trigger edge specified.\n");

			err = ME_ERRNO_INVALID_ACQ_START_TRIG_EDGE;

			goto ERROR;

			break;
		}

		break;

	default:
		PERROR("Invalid acquisition start trigger type specified.\n");

		err = ME_ERRNO_INVALID_ACQ_START_TRIG_TYPE;

		goto ERROR;

		break;
	}

	switch (trigger->iScanStartTrigType) {

	case ME_TRIG_TYPE_FOLLOW:
		break;

	default:
		PERROR("Invalid scan start trigger type specified.\n");

		err = ME_ERRNO_INVALID_SCAN_START_TRIG_TYPE;

		goto ERROR;

		break;
	}

	switch (trigger->iConvStartTrigType) {

	case ME_TRIG_TYPE_TIMER:
		if ((conv_ticks < ME4600_AO_MIN_CHAN_TICKS)
		    || (conv_ticks > ME4600_AO_MAX_CHAN_TICKS)) {
			PERROR
			    ("Invalid conv start trigger argument specified.\n");
			err = ME_ERRNO_INVALID_CONV_START_ARG;
			goto ERROR;
		}

		break;

	default:
		PERROR("Invalid conv start trigger type specified.\n");

		err = ME_ERRNO_INVALID_CONV_START_TRIG_TYPE;

		goto ERROR;

		break;
	}

	/* Preset to hardware wraparound mode */
	instance->flags &= ~(ME4600_AO_FLAGS_SW_WRAP_MODE_MASK);

	switch (trigger->iScanStopTrigType) {

	case ME_TRIG_TYPE_NONE:
		if (flags & ME_IO_STREAM_CONFIG_WRAPAROUND) {
			/* Set flags to indicate usage of software mode. */
			instance->flags |= ME4600_AO_FLAGS_SW_WRAP_MODE_INF;
			instance->wrap_count = 0;
			instance->wrap_remaining = 0;
		}

		break;

	case ME_TRIG_TYPE_COUNT:
		if (flags & ME_IO_STREAM_CONFIG_WRAPAROUND) {
			if (trigger->iScanStopCount <= 0) {
				PERROR("Invalid scan stop count specified.\n");
				err = ME_ERRNO_INVALID_SCAN_STOP_ARG;
				goto ERROR;
			}

			/* Set flags to indicate usage of software mode. */
			instance->flags |= ME4600_AO_FLAGS_SW_WRAP_MODE_FIN;
			instance->wrap_count = trigger->iScanStopCount;
			instance->wrap_remaining = trigger->iScanStopCount;
		} else {
			PERROR("Invalid scan stop trigger type specified.\n");
			err = ME_ERRNO_INVALID_ACQ_STOP_TRIG_TYPE;
			goto ERROR;
		}

		break;

	default:
		PERROR("Invalid scan stop trigger type specified.\n");

		err = ME_ERRNO_INVALID_SCAN_STOP_TRIG_TYPE;

		goto ERROR;

		break;
	}

	switch (trigger->iAcqStopTrigType) {

	case ME_TRIG_TYPE_NONE:
		break;

	case ME_TRIG_TYPE_COUNT:
		if (trigger->iScanStopTrigType != ME_TRIG_TYPE_NONE) {
			PERROR("Invalid acq stop trigger type specified.\n");
			err = ME_ERRNO_INVALID_ACQ_STOP_TRIG_TYPE;
			goto ERROR;
		}

		if (flags & ME_IO_STREAM_CONFIG_WRAPAROUND) {
			if (trigger->iAcqStopCount <= 0) {
				PERROR("Invalid acq stop count specified.\n");
				err = ME_ERRNO_INVALID_ACQ_STOP_ARG;
				goto ERROR;
			}

			/* Set flags to indicate usage of software mode. */
			instance->flags |= ME4600_AO_FLAGS_SW_WRAP_MODE_FIN;
			instance->wrap_count = trigger->iAcqStopCount;
			instance->wrap_remaining = trigger->iAcqStopCount;
		} else {
			PERROR("Invalid acp stop trigger type specified.\n");
			err = ME_ERRNO_INVALID_ACQ_STOP_TRIG_TYPE;
			goto ERROR;
		}

		break;

	default:
		PERROR("Invalid acq stop trigger type specified.\n");
		err = ME_ERRNO_INVALID_ACQ_STOP_TRIG_TYPE;
		goto ERROR;
		break;
	}

	switch (trigger->iAcqStartTrigChan) {

	case ME_TRIG_CHAN_DEFAULT:
		spin_lock(instance->preload_reg_lock);
		tmp = inl(instance->preload_reg);
		tmp &= ~(0x10001 << instance->ao_idx);
		outl(tmp, instance->preload_reg);
		spin_unlock(instance->preload_reg_lock);

		break;

	case ME_TRIG_CHAN_SYNCHRONOUS:
		if (trigger->iAcqStartTrigType == ME_TRIG_TYPE_SW) {
			spin_lock(instance->preload_reg_lock);
			tmp = inl(instance->preload_reg);
			tmp &= ~(0x10001 << instance->ao_idx);
			outl(tmp, instance->preload_reg);
			tmp |= 0x1 << instance->ao_idx;
			outl(tmp, instance->preload_reg);
			spin_unlock(instance->preload_reg_lock);
		} else {
			ctrl &= ~(ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG);
			spin_lock(instance->preload_reg_lock);
			tmp = inl(instance->preload_reg);
			tmp &= ~(0x10001 << instance->ao_idx);
			outl(tmp, instance->preload_reg);
			tmp |= 0x10000 << instance->ao_idx;
			outl(tmp, instance->preload_reg);
			spin_unlock(instance->preload_reg_lock);
		}

		break;

	default:
		PERROR("Invalid acq start trigger channel specified.\n");
		err = ME_ERRNO_INVALID_ACQ_START_TRIG_CHAN;
		goto ERROR;

		break;
	}

	outl(conv_ticks - 2, instance->timer_reg);

	if (flags & ME_IO_STREAM_CONFIG_BIT_PATTERN) {
		if (instance->ao_idx == 3) {
			ctrl |= ME4600_AO_CTRL_BIT_ENABLE_DO;
		} else {
			err = ME_ERRNO_INVALID_FLAGS;
			goto ERROR;
		}
	} else {
		if (instance->ao_idx == 3) {
			ctrl &= ~ME4600_AO_CTRL_BIT_ENABLE_DO;
		}
	}

	/* Set hardware mode. */
	if (flags & ME_IO_STREAM_CONFIG_WRAPAROUND) {
		ctrl |= ME4600_AO_CTRL_BIT_MODE_0;
	} else {
		ctrl |= ME4600_AO_CTRL_BIT_MODE_1;
	}

	PDEBUG("Preload word = 0x%X.\n", inl(instance->preload_reg));

	PDEBUG("Ctrl word = 0x%lX.\n", ctrl);
	outl(ctrl, instance->ctrl_reg);	// Write the control word

ERROR:

	spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_new_values(me_subdevice_t *subdevice,
					  struct file *filep,
					  int time_out, int *count, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	long t = 0;
	long j;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	if (time_out < 0) {
		PERROR("Invalid time_out specified.\n");
		return ME_ERRNO_INVALID_TIMEOUT;
	}

	if (time_out) {
		t = (time_out * HZ) / 1000;

		if (t == 0)
			t = 1;
	}

	*count = 0;

	ME_SUBDEVICE_ENTER;

	if (t) {
		j = jiffies;
		wait_event_interruptible_timeout(instance->wait_queue,
						 ((me_circ_buf_space
						   (&instance->circ_buf))
						  || !(inl(instance->status_reg)
						       &
						       ME4600_AO_STATUS_BIT_FSM)),
						 t);

		if (!(inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM)) {
			PERROR("AO subdevice is not running.\n");
			err = ME_ERRNO_SUBDEVICE_NOT_RUNNING;
		} else if (signal_pending(current)) {
			PERROR("Wait on values interrupted from signal.\n");
			err = ME_ERRNO_SIGNAL;
		} else if ((jiffies - j) >= t) {
			PERROR("Wait on values timed out.\n");
			err = ME_ERRNO_TIMEOUT;
		} else {
			*count = me_circ_buf_space(&instance->circ_buf);
		}
	} else {
		wait_event_interruptible(instance->wait_queue,
					 ((me_circ_buf_space
					   (&instance->circ_buf))
					  || !(inl(instance->status_reg) &
					       ME4600_AO_STATUS_BIT_FSM)));

		if (!(inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM)) {
			PERROR("AO subdevice is not running.\n");
			err = ME_ERRNO_SUBDEVICE_NOT_RUNNING;
		} else if (signal_pending(current)) {
			PERROR("Wait on values interrupted from signal.\n");
			err = ME_ERRNO_SIGNAL;
		} else {
			*count = me_circ_buf_space(&instance->circ_buf);
		}
	}

	ME_SUBDEVICE_EXIT;

	return err;
}

static void stop_immediately(me4600_ao_subdevice_t *instance)
{
	unsigned long cpu_flags;
	uint32_t tmp;

	spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
	tmp = inl(instance->ctrl_reg);
	tmp |= ME4600_AO_CTRL_BIT_STOP | ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
	outl(tmp, instance->ctrl_reg);

	while (inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM) ;

	spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
}

static int me4600_ao_io_stream_start(me_subdevice_t *subdevice,
				     struct file *filep,
				     int start_mode, int time_out, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	unsigned long cpu_flags = 0;
	unsigned long ref;
	unsigned long tmp;
	unsigned long delay = 0;
	wait_queue_head_t queue;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	init_waitqueue_head(&queue);

	if (time_out < 0) {
		PERROR("Invalid timeout specified.\n");
		return ME_ERRNO_INVALID_TIMEOUT;
	}

	if (time_out) {
		delay = (time_out * HZ) / 1000;

		if (delay == 0)
			delay = 1;
	}

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	ME_SUBDEVICE_ENTER
	    spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);

	tmp = inl(instance->ctrl_reg);

	switch (tmp & (ME4600_AO_CTRL_MASK_MODE)) {

	case 0:		// Single mode
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
		PERROR("Subdevice is configured in single mode.\n");
		err = ME_ERRNO_PREVIOUS_CONFIG;
		goto ERROR;

	case 1:		// Wraparound mode
		if (tmp & ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG) {	// Normal wraparound with external trigger

			if ((inl(instance->status_reg) &
			     ME4600_AO_STATUS_BIT_FSM)) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR("Conversion is already running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			tmp &=
			    ~(ME4600_AO_CTRL_BIT_ENABLE_IRQ |
			      ME4600_AO_CTRL_BIT_STOP |
			      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);

			outl(tmp, instance->ctrl_reg);
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			if (start_mode == ME_START_MODE_BLOCKING) {
				init_waitqueue_head(&queue);

				if (delay) {
					ref = jiffies;

					while (!
					       (inl(instance->status_reg) &
						ME4600_AO_STATUS_BIT_FSM)) {
						interruptible_sleep_on_timeout
						    (&queue, 1);

						if (signal_pending(current)) {
							PERROR
							    ("Wait on start of state machine interrupted.\n");
							stop_immediately
							    (instance);
							err = ME_ERRNO_SIGNAL;
							goto ERROR;
						}

						if (((jiffies - ref) >= delay)) {
							PERROR
							    ("Timeout reached.\n");
							stop_immediately
							    (instance);
							err = ME_ERRNO_TIMEOUT;
							goto ERROR;
						}
					}
				} else {
					while (!
					       (inl(instance->status_reg) &
						ME4600_AO_STATUS_BIT_FSM)) {
						interruptible_sleep_on_timeout
						    (&queue, 1);

						if (signal_pending(current)) {
							PERROR
							    ("Wait on start of state machine interrupted.\n");
							stop_immediately
							    (instance);
							err = ME_ERRNO_SIGNAL;
							goto ERROR;
						}
					}
				}
			} else if (start_mode == ME_START_MODE_NONBLOCKING) {
			} else {
				PERROR("Invalid start mode specified.\n");
				err = ME_ERRNO_INVALID_START_MODE;
				goto ERROR;
			}
		} else if ((inl(instance->preload_reg) & (0x10001 << instance->ao_idx)) == (0x10000 << instance->ao_idx)) {	// Synchronous with external trigger

			if ((inl(instance->status_reg) &
			     ME4600_AO_STATUS_BIT_FSM)) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR("Conversion is already running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			if (flags & ME_IO_STREAM_START_TYPE_TRIG_SYNCHRONOUS) {
				tmp |= ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG;
				tmp &=
				    ~(ME4600_AO_CTRL_BIT_ENABLE_IRQ |
				      ME4600_AO_CTRL_BIT_STOP |
				      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);
				outl(tmp, instance->ctrl_reg);
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);

				if (start_mode == ME_START_MODE_BLOCKING) {
					init_waitqueue_head(&queue);

					if (delay) {
						ref = jiffies;

						while (!
						       (inl
							(instance->
							 status_reg) &
							ME4600_AO_STATUS_BIT_FSM))
						{
							interruptible_sleep_on_timeout
							    (&queue, 1);

							if (signal_pending
							    (current)) {
								PERROR
								    ("Wait on start of state machine interrupted.\n");
								stop_immediately
								    (instance);
								err =
								    ME_ERRNO_SIGNAL;
								goto ERROR;
							}

							if (((jiffies - ref) >=
							     delay)) {
								PERROR
								    ("Timeout reached.\n");
								stop_immediately
								    (instance);
								err =
								    ME_ERRNO_TIMEOUT;
								goto ERROR;
							}
						}
					} else {
						while (!
						       (inl
							(instance->
							 status_reg) &
							ME4600_AO_STATUS_BIT_FSM))
						{
							interruptible_sleep_on_timeout
							    (&queue, 1);

							if (signal_pending
							    (current)) {
								PERROR
								    ("Wait on start of state machine interrupted.\n");
								stop_immediately
								    (instance);
								err =
								    ME_ERRNO_SIGNAL;
								goto ERROR;
							}
						}
					}
				} else if (start_mode ==
					   ME_START_MODE_NONBLOCKING) {
				} else {
					PERROR
					    ("Invalid start mode specified.\n");
					err = ME_ERRNO_INVALID_START_MODE;
					goto ERROR;
				}
			} else {
				tmp &=
				    ~(ME4600_AO_CTRL_BIT_ENABLE_IRQ |
				      ME4600_AO_CTRL_BIT_STOP |
				      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);
				outl(tmp, instance->ctrl_reg);
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
			}
		} else if ((inl(instance->preload_reg) & (0x10001 << instance->ao_idx)) == (0x1 << instance->ao_idx)) {	// Synchronous wraparound with sw trigger

			if ((inl(instance->status_reg) &
			     ME4600_AO_STATUS_BIT_FSM)) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR("Conversion is already running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			tmp &=
			    ~(ME4600_AO_CTRL_BIT_ENABLE_IRQ |
			      ME4600_AO_CTRL_BIT_STOP |
			      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);

			outl(tmp, instance->ctrl_reg);

			if (flags & ME_IO_STREAM_START_TYPE_TRIG_SYNCHRONOUS) {
				outl(0x8000, instance->single_reg);
				instance->single_value = 0x8000;
			}

			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
		} else {	// Software start

			if ((inl(instance->status_reg) &
			     ME4600_AO_STATUS_BIT_FSM)) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR("Conversion is already running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			tmp &=
			    ~(ME4600_AO_CTRL_BIT_ENABLE_IRQ |
			      ME4600_AO_CTRL_BIT_STOP |
			      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);

			outl(tmp, instance->ctrl_reg);

			outl(0x8000, instance->single_reg);
			instance->single_value = 0x8000;

			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
		}

		break;

	case 2:		// Continuous mode
		if (tmp & ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG) {	// Externally triggered

			if ((inl(instance->status_reg) &
			     ME4600_AO_STATUS_BIT_FSM)) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR("Conversion is already running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			tmp &=
			    ~(ME4600_AO_CTRL_BIT_STOP |
			      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);
			tmp |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			outl(tmp, instance->ctrl_reg);
			instance->wrap_remaining = instance->wrap_count;
			instance->circ_buf.tail = 0;
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			if (start_mode == ME_START_MODE_BLOCKING) {
				init_waitqueue_head(&queue);

				if (delay) {
					ref = jiffies;

					while (!
					       (inl(instance->status_reg) &
						ME4600_AO_STATUS_BIT_FSM)) {
						interruptible_sleep_on_timeout
						    (&queue, 1);

						if (signal_pending(current)) {
							PERROR
							    ("Wait on start of state machine interrupted.\n");
							stop_immediately
							    (instance);
							err = ME_ERRNO_SIGNAL;
							goto ERROR;
						}

						if (((jiffies - ref) >= delay)) {
							PERROR
							    ("Timeout reached.\n");
							stop_immediately
							    (instance);
							err = ME_ERRNO_TIMEOUT;
							goto ERROR;
						}
					}
				} else {
					while (!
					       (inl(instance->status_reg) &
						ME4600_AO_STATUS_BIT_FSM)) {
						interruptible_sleep_on_timeout
						    (&queue, 1);

						if (signal_pending(current)) {
							PERROR
							    ("Wait on start of state machine interrupted.\n");
							stop_immediately
							    (instance);
							err = ME_ERRNO_SIGNAL;
							goto ERROR;
						}
					}
				}
			} else if (start_mode == ME_START_MODE_NONBLOCKING) {
				/* Do nothing */
			} else {
				PERROR("Invalid start mode specified.\n");
				stop_immediately(instance);
				err = ME_ERRNO_INVALID_START_MODE;
				goto ERROR;
			}
		} else if ((inl(instance->preload_reg) & (0x10001 << instance->ao_idx)) == (0x10000 << instance->ao_idx)) {	// Synchronous with external trigger

			if ((inl(instance->status_reg) &
			     ME4600_AO_STATUS_BIT_FSM)) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR("Conversion is already running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			if (flags & ME_IO_STREAM_START_TYPE_TRIG_SYNCHRONOUS) {
				tmp |=
				    ME4600_AO_CTRL_BIT_ENABLE_EX_TRIG |
				    ME4600_AO_CTRL_BIT_ENABLE_IRQ;
				tmp &=
				    ~(ME4600_AO_CTRL_BIT_STOP |
				      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);
				outl(tmp, instance->ctrl_reg);
				instance->wrap_remaining = instance->wrap_count;
				instance->circ_buf.tail = 0;

				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);

				if (start_mode == ME_START_MODE_BLOCKING) {
					init_waitqueue_head(&queue);

					if (delay) {
						ref = jiffies;

						while (!
						       (inl
							(instance->
							 status_reg) &
							ME4600_AO_STATUS_BIT_FSM))
						{
							interruptible_sleep_on_timeout
							    (&queue, 1);

							if (signal_pending
							    (current)) {
								PERROR
								    ("Wait on start of state machine interrupted.\n");
								stop_immediately
								    (instance);
								err =
								    ME_ERRNO_SIGNAL;
								goto ERROR;
							}

							if (((jiffies - ref) >=
							     delay)) {
								PERROR
								    ("Timeout reached.\n");
								stop_immediately
								    (instance);
								err =
								    ME_ERRNO_TIMEOUT;
								goto ERROR;
							}
						}
					} else {
						while (!
						       (inl
							(instance->
							 status_reg) &
							ME4600_AO_STATUS_BIT_FSM))
						{
							interruptible_sleep_on_timeout
							    (&queue, 1);

							if (signal_pending
							    (current)) {
								PERROR
								    ("Wait on start of state machine interrupted.\n");
								stop_immediately
								    (instance);
								err =
								    ME_ERRNO_SIGNAL;
								goto ERROR;
							}
						}
					}
				} else if (start_mode ==
					   ME_START_MODE_NONBLOCKING) {
				} else {
					PERROR
					    ("Invalid start mode specified.\n");
					stop_immediately(instance);
					err = ME_ERRNO_INVALID_START_MODE;
					goto ERROR;
				}
			} else {
				tmp |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
				tmp &=
				    ~(ME4600_AO_CTRL_BIT_STOP |
				      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);
				outl(tmp, instance->ctrl_reg);
				instance->wrap_remaining = instance->wrap_count;
				instance->circ_buf.tail = 0;
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
			}
		} else if ((inl(instance->preload_reg) & (0x10001 << instance->ao_idx)) == (0x1 << instance->ao_idx)) {	// Synchronous wraparound with sw trigger

			if ((inl(instance->status_reg) &
			     ME4600_AO_STATUS_BIT_FSM)) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR("Conversion is already running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			tmp &=
			    ~(ME4600_AO_CTRL_BIT_STOP |
			      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);
			tmp |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			instance->wrap_remaining = instance->wrap_count;
			instance->circ_buf.tail = 0;
			PDEBUG("CTRL Reg = 0x%X.\n", inl(instance->ctrl_reg));
			outl(tmp, instance->ctrl_reg);

			if (flags & ME_IO_STREAM_START_TYPE_TRIG_SYNCHRONOUS) {
				outl(0x8000, instance->single_reg);
				instance->single_value = 0x8000;
			}

			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
		} else {	// Software start

			if ((inl(instance->status_reg) &
			     ME4600_AO_STATUS_BIT_FSM)) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR("Conversion is already running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			tmp &=
			    ~(ME4600_AO_CTRL_BIT_STOP |
			      ME4600_AO_CTRL_BIT_IMMEDIATE_STOP);

			tmp |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			outl(tmp, instance->ctrl_reg);
			outl(0x8000, instance->single_reg);
			instance->single_value = 0x8000;
			instance->wrap_remaining = instance->wrap_count;
			instance->circ_buf.tail = 0;
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
		}

		break;

	default:
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
		PERROR("Invalid mode configured.\n");
		err = ME_ERRNO_INTERNAL;
		goto ERROR;
	}

ERROR:

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_status(me_subdevice_t *subdevice,
				      struct file *filep,
				      int wait,
				      int *status, int *values, int flags)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;
	wait_queue_head_t queue;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	init_waitqueue_head(&queue);

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	ME_SUBDEVICE_ENTER;

	if (wait == ME_WAIT_NONE) {
		*status =
		    (inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM) ?
		    ME_STATUS_BUSY : ME_STATUS_IDLE;
		*values = me_circ_buf_space(&instance->circ_buf);
	} else if (wait == ME_WAIT_IDLE) {
		while (inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM) {
			interruptible_sleep_on_timeout(&queue, 1);

			if (instance->flags & ME4600_AO_FLAGS_BROKEN_PIPE) {
				PERROR("Output stream was interrupted.\n");
				*status = ME_STATUS_ERROR;
				err = ME_ERRNO_SUCCESS;
				goto ERROR;
			}

			if (signal_pending(current)) {
				PERROR
				    ("Wait on state machine interrupted by signal.\n");
				*status = ME_STATUS_INVALID;
				err = ME_ERRNO_SIGNAL;
				goto ERROR;
			}
		}

		*status = ME_STATUS_IDLE;

		*values = me_circ_buf_space(&instance->circ_buf);
	} else {
		PERROR("Invalid wait argument specified.\n");
		*status = ME_STATUS_INVALID;
		err = ME_ERRNO_INVALID_WAIT;
		goto ERROR;
	}

ERROR:

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_stop(me_subdevice_t *subdevice,
				    struct file *filep,
				    int stop_mode, int flags)
{
	int err = ME_ERRNO_SUCCESS;
	me4600_ao_subdevice_t *instance;
	unsigned long cpu_flags;
	unsigned long tmp;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	ME_SUBDEVICE_ENTER;

	if (stop_mode == ME_STOP_MODE_IMMEDIATE) {
		spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
		tmp = inl(instance->ctrl_reg);
		tmp |=
		    ME4600_AO_CTRL_BIT_STOP | ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
		outl(tmp, instance->ctrl_reg);

		while (inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM) ;

		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
	} else if (stop_mode == ME_STOP_MODE_LAST_VALUE) {
		spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);
		tmp = inl(instance->ctrl_reg);
		tmp |= ME4600_AO_CTRL_BIT_STOP;
		outl(tmp, instance->ctrl_reg);
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
	} else {
		PERROR("Invalid stop mode specified.\n");
		err = ME_ERRNO_INVALID_STOP_MODE;
		goto ERROR;
	}

ERROR:

	ME_SUBDEVICE_EXIT;

	return err;
}

static int me4600_ao_io_stream_write(me_subdevice_t *subdevice,
				     struct file *filep,
				     int write_mode,
				     int *values, int *count, int flags)
{
	int err = ME_ERRNO_SUCCESS;
	me4600_ao_subdevice_t *instance;
	unsigned long tmp;
	int i;
	int value;
	int cnt = *count;
	int c;
	int k;
	int ret = 0;
	unsigned long cpu_flags = 0;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	if (!instance->fifo) {
		PERROR("Not a streaming ao.\n");
		return ME_ERRNO_NOT_SUPPORTED;
	}

	ME_SUBDEVICE_ENTER;

	if (*count <= 0) {
		PERROR("Invalid count of values specified.\n");
		err = ME_ERRNO_INVALID_VALUE_COUNT;
		goto ERROR;
	}

	spin_lock_irqsave(&instance->subdevice_lock, cpu_flags);

	tmp = inl(instance->ctrl_reg);

	switch (tmp & 0x3) {

	case 1:		// Wraparound mode
		if (instance->bosch_fw) {	// Bosch firmware
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			if (cnt != 7) {
				PERROR
				    ("Invalid count of values specified. 7 expected.\n");
				err = ME_ERRNO_INVALID_VALUE_COUNT;
				goto ERROR;
			}

			for (i = 0; i < 7; i++) {
				if (get_user(value, values)) {
					PERROR
					    ("Can't copy value from user space.\n");
					err = ME_ERRNO_INTERNAL;
					goto ERROR;
				}

				if (i == 0) {
					/* Maximum voltage */
					value <<= 16;
					value |=
					    inl(instance->reg_base +
						0xD4) & 0xFFFF;
					outl(value, instance->reg_base + 0xD4);
				} else if (i == 1) {
					/* Minimum voltage */
					value &= 0xFFFF;
					value |=
					    inl(instance->reg_base +
						0xD4) & 0xFFFF0000;
					outl(value, instance->reg_base + 0xD4);
				} else if (i == 2) {
					/* Delta up */
					value <<= 16;
					value |=
					    inl(instance->reg_base +
						0xD8) & 0xFFFF;
					outl(value, instance->reg_base + 0xD8);
				} else if (i == 3) {
					/* Delta down */
					value &= 0xFFFF;
					value |=
					    inl(instance->reg_base +
						0xD8) & 0xFFFF0000;
					outl(value, instance->reg_base + 0xD8);
				} else if (i == 4) {
					/* Start value */
					outl(value, instance->reg_base + 0xDC);
				} else if (i == 5) {
					/* Invert */
					if (value) {
						value = inl(instance->ctrl_reg);
						value |= 0x100;
						outl(value, instance->ctrl_reg);
					} else {
						value = inl(instance->ctrl_reg);
						value &= ~0x100;
						outl(value, instance->ctrl_reg);
					}
				} else if (i == 6) {
					/* Timer for positive ramp */
					outl(value, instance->reg_base + 0xE0);
				}

				values++;
			}
		} else {	// Normal firmware
			PDEBUG("Write for wraparound mode.\n");

			if (inl(instance->status_reg) &
			    ME4600_AO_STATUS_BIT_FSM) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR
				    ("There is already a conversion running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			tmp |= ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
			tmp &= ~ME4600_AO_CTRL_BIT_ENABLE_FIFO;
			outl(tmp, instance->ctrl_reg);
			tmp |= ME4600_AO_CTRL_BIT_ENABLE_FIFO;

			if ((*count > ME4600_AO_FIFO_COUNT) ||
			    ((instance->
			      flags & ME4600_AO_FLAGS_SW_WRAP_MODE_MASK) ==
			     ME4600_AO_FLAGS_SW_WRAP_MODE_FIN)) {
				tmp &=
				    ~(ME4600_AO_CTRL_BIT_MODE_0 |
				      ME4600_AO_CTRL_BIT_MODE_1);
				tmp |= ME4600_AO_CTRL_BIT_MODE_1;
			}

			outl(tmp, instance->ctrl_reg);
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			if ((*count <= ME4600_AO_FIFO_COUNT) &&
			    ((instance->
			      flags & ME4600_AO_FLAGS_SW_WRAP_MODE_MASK) ==
			     ME4600_AO_FLAGS_SW_WRAP_MODE_INF)) {
				for (i = 0; i < *count; i++) {
					if (get_user(value, values + i)) {
						PERROR
						    ("Cannot copy value from user space.\n");
						err = ME_ERRNO_INTERNAL;
						goto ERROR;
					}

					if (instance->ao_idx & 0x1)
						value <<= 16;

					outl(value, instance->fifo_reg);
				}
			} else if ((*count <= ME4600_AO_CIRC_BUF_COUNT) &&
				   ((instance->
				     flags & ME4600_AO_FLAGS_SW_WRAP_MODE_MASK)
				    == ME4600_AO_FLAGS_SW_WRAP_MODE_INF)) {
				for (i = 0; i < *count; i++) {
					if (get_user(value, values + i)) {
						PERROR
						    ("Cannot copy value from user space.\n");
						err = ME_ERRNO_INTERNAL;
						goto ERROR;
					}

					instance->circ_buf.buf[i] = value;	/* Used to hold the values. */
				}

				instance->circ_buf.tail = 0;	/* Used as the current read position. */
				instance->circ_buf.head = *count;	/* Used as the buffer size. */

				/* Preload the FIFO. */

				for (i = 0; i < ME4600_AO_FIFO_COUNT;
				     i++, instance->circ_buf.tail++) {
					if (instance->circ_buf.tail >=
					    instance->circ_buf.head)
						instance->circ_buf.tail = 0;

					if (instance->ao_idx & 0x1)
						outl(instance->circ_buf.
						     buf[instance->circ_buf.
							 tail] << 16,
						     instance->fifo_reg);
					else
						outl(instance->circ_buf.
						     buf[instance->circ_buf.
							 tail],
						     instance->fifo_reg);
				}
			} else if ((*count <= ME4600_AO_CIRC_BUF_COUNT) &&
				   ((instance->
				     flags & ME4600_AO_FLAGS_SW_WRAP_MODE_MASK)
				    == ME4600_AO_FLAGS_SW_WRAP_MODE_FIN)) {
				unsigned int preload_count;

				for (i = 0; i < *count; i++) {
					if (get_user(value, values + i)) {
						PERROR
						    ("Cannot copy value from user space.\n");
						err = ME_ERRNO_INTERNAL;
						goto ERROR;
					}

					instance->circ_buf.buf[i] = value;	/* Used to hold the values. */
				}

				instance->circ_buf.tail = 0;	/* Used as the current read position. */
				instance->circ_buf.head = *count;	/* Used as the buffer size. */

				/* Try to preload the whole FIFO. */
				preload_count = ME4600_AO_FIFO_COUNT;

				if (preload_count > instance->wrap_count)
					preload_count = instance->wrap_count;

				/* Preload the FIFO. */
				for (i = 0; i < preload_count;
				     i++, instance->circ_buf.tail++) {
					if (instance->circ_buf.tail >=
					    instance->circ_buf.head)
						instance->circ_buf.tail = 0;

					if (instance->ao_idx & 0x1)
						outl(instance->circ_buf.
						     buf[instance->circ_buf.
							 tail] << 16,
						     instance->fifo_reg);
					else
						outl(instance->circ_buf.
						     buf[instance->circ_buf.
							 tail],
						     instance->fifo_reg);
				}

				instance->wrap_remaining =
				    instance->wrap_count - preload_count;
			} else {
				PERROR("To many values written.\n");
				err = ME_ERRNO_INVALID_VALUE_COUNT;
				goto ERROR;
			}
		}

		break;

	case 2:		// Continuous mode
		/* Check if in SW wrapround mode */
		if (instance->flags & ME4600_AO_FLAGS_SW_WRAP_MODE_MASK) {
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);
			PERROR("Subdevice is configured SW wrapround mode.\n");
			err = ME_ERRNO_PREVIOUS_CONFIG;
			goto ERROR;
		}

		switch (write_mode) {

		case ME_WRITE_MODE_BLOCKING:
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			PDEBUG("Write for blocking continuous mode.\n");

			while (cnt > 0) {
				wait_event_interruptible(instance->wait_queue,
							 (c =
							  me_circ_buf_space_to_end
							  (&instance->
							   circ_buf)));

				if (instance->
				    flags & ME4600_AO_FLAGS_BROKEN_PIPE) {
					PERROR
					    ("Broken pipe in blocking write.\n");
					err = ME_ERRNO_SUBDEVICE_NOT_RUNNING;
					goto ERROR;
				} else if (signal_pending(current)) {
					PERROR
					    ("Wait for free buffer interrupted from signal.\n");
					err = ME_ERRNO_SIGNAL;
					goto ERROR;
				}

				PDEBUG("Space to end = %d.\n", c);

				/* Only able to write size of free buffer or size of count */

				if (cnt < c)
					c = cnt;
				k = sizeof(int) * c;
				k -= copy_from_user(instance->circ_buf.buf +
						    instance->circ_buf.head,
						    values, k);
				c = k / sizeof(int);

				PDEBUG("Copy %d values from user space.\n", c);

				if (!c) {
					PERROR
					    ("Cannot copy values from user space.\n");
					err = ME_ERRNO_INTERNAL;
					goto ERROR;
				}

				instance->circ_buf.head =
				    (instance->circ_buf.head +
				     c) & (instance->circ_buf.mask);

				values += c;
				cnt -= c;
				ret += c;

				/* Values are now available so enable interrupts */
				spin_lock_irqsave(&instance->subdevice_lock,
						  cpu_flags);

				if (me_circ_buf_space(&instance->circ_buf)) {
					tmp = inl(instance->ctrl_reg);
					tmp |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
					outl(tmp, instance->ctrl_reg);
				}

				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
			}

			*count = ret;

			break;

		case ME_WRITE_MODE_NONBLOCKING:
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			PDEBUG("Write for non blocking continuous mode.\n");

			while (cnt > 0) {
				if (instance->
				    flags & ME4600_AO_FLAGS_BROKEN_PIPE) {
					PERROR
					    ("ME4600:Broken pipe in nonblocking write.\n");
					err = ME_ERRNO_SUBDEVICE_NOT_RUNNING;
					goto ERROR;
				}

				c = me_circ_buf_space_to_end(&instance->
							     circ_buf);

				if (!c) {
					PDEBUG
					    ("Returning from nonblocking write.\n");
					break;
				}

				PDEBUG("Space to end = %d.\n", c);

				/* Only able to write size of free buffer or size of count */

				if (cnt < c)
					c = cnt;
				k = sizeof(int) * c;
				k -= copy_from_user(instance->circ_buf.buf +
						    instance->circ_buf.head,
						    values, k);
				c = k / sizeof(int);

				PDEBUG("Copy %d values from user space.\n", c);

				if (!c) {
					PERROR
					    ("Cannot copy values from user space.\n");
					err = ME_ERRNO_INTERNAL;
					goto ERROR;
				}

				instance->circ_buf.head =
				    (instance->circ_buf.head +
				     c) & (instance->circ_buf.mask);

				values += c;
				cnt -= c;
				ret += c;

				/* Values are now available so enable interrupts */
				spin_lock_irqsave(&instance->subdevice_lock,
						  cpu_flags);

				if (me_circ_buf_space(&instance->circ_buf)) {
					tmp = inl(instance->ctrl_reg);
					tmp |= ME4600_AO_CTRL_BIT_ENABLE_IRQ;
					outl(tmp, instance->ctrl_reg);
				}

				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
			}

			*count = ret;

			break;

		case ME_WRITE_MODE_PRELOAD:
			PDEBUG("Write for preload continuous mode.\n");

			if ((inl(instance->status_reg) &
			     ME4600_AO_STATUS_BIT_FSM)) {
				spin_unlock_irqrestore(&instance->
						       subdevice_lock,
						       cpu_flags);
				PERROR
				    ("Can't Preload DAC FIFO while conversion is running.\n");
				err = ME_ERRNO_SUBDEVICE_BUSY;
				goto ERROR;
			}

			tmp = inl(instance->ctrl_reg);

			tmp |=
			    ME4600_AO_CTRL_BIT_STOP |
			    ME4600_AO_CTRL_BIT_IMMEDIATE_STOP;
			outl(tmp, instance->ctrl_reg);
			tmp &=
			    ~(ME4600_AO_CTRL_BIT_ENABLE_FIFO |
			      ME4600_AO_CTRL_BIT_ENABLE_IRQ);
			outl(tmp, instance->ctrl_reg);
			tmp |= ME4600_AO_CTRL_BIT_ENABLE_FIFO;
			outl(tmp, instance->ctrl_reg);

			instance->circ_buf.head = 0;
			instance->circ_buf.tail = 0;
			instance->flags &= ~ME4600_AO_FLAGS_BROKEN_PIPE;

			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			c = ME4600_AO_FIFO_COUNT;

			if (cnt < c)
				c = cnt;

			for (i = 0; i < c; i++) {
				if (get_user(value, values)) {
					PERROR
					    ("Can't copy value from user space.\n");
					err = ME_ERRNO_INTERNAL;
					goto ERROR;
				}

				if (instance->ao_idx & 0x1)
					value <<= 16;

				outl(value, instance->fifo_reg);

				values++;
			}

			cnt -= c;

			ret += c;

			PDEBUG("Wrote %d values to fifo.\n", c);

			while (1) {
				c = me_circ_buf_space_to_end(&instance->
							     circ_buf);

				if (c == 0)
					break;

				if (cnt < c)
					c = cnt;

				if (c <= 0)
					break;

				k = sizeof(int) * c;

				k -= copy_from_user(instance->circ_buf.buf +
						    instance->circ_buf.head,
						    values, k);

				c = k / sizeof(int);

				PDEBUG("Wrote %d values to circular buffer.\n",
				       c);

				if (!c) {
					PERROR
					    ("Can't copy values from user space.\n");
					err = ME_ERRNO_INTERNAL;
					goto ERROR;
				}

				instance->circ_buf.head =
				    (instance->circ_buf.head +
				     c) & (instance->circ_buf.mask);

				values += c;
				cnt -= c;
				ret += c;
			}

			*count = ret;

			break;

		default:
			spin_unlock_irqrestore(&instance->subdevice_lock,
					       cpu_flags);

			PERROR("Invalid write mode specified.\n");

			err = ME_ERRNO_INVALID_WRITE_MODE;

			goto ERROR;
		}

		break;

	default:		// Single mode of invalid
		spin_unlock_irqrestore(&instance->subdevice_lock, cpu_flags);
		PERROR("Subdevice is configured in single mode.\n");
		err = ME_ERRNO_PREVIOUS_CONFIG;
		goto ERROR;
	}

ERROR:

	ME_SUBDEVICE_EXIT;

	return err;
}

static irqreturn_t me4600_ao_isr(int irq, void *dev_id)
{
	unsigned long tmp;
	int value;
	me4600_ao_subdevice_t *instance = dev_id;
	int i;
	int c = 0;
	int c1 = 0;

	if (irq != instance->irq) {
		PDEBUG("Incorrect interrupt num: %d.\n", irq);
		return IRQ_NONE;
	}

	if (!((0x1 << (instance->ao_idx + 3)) & inl(instance->irq_status_reg))) {
		return IRQ_NONE;
	}

	PDEBUG("executed.\n");

	tmp = inl(instance->status_reg);

	if (!(tmp & ME4600_AO_STATUS_BIT_EF) &&
	    (tmp & ME4600_AO_STATUS_BIT_HF) &&
	    (tmp & ME4600_AO_STATUS_BIT_HF)) {
		c = ME4600_AO_FIFO_COUNT;
		PDEBUG("Fifo empty.\n");
	} else if ((tmp & ME4600_AO_STATUS_BIT_EF) &&
		   (tmp & ME4600_AO_STATUS_BIT_HF) &&
		   (tmp & ME4600_AO_STATUS_BIT_HF)) {
		c = ME4600_AO_FIFO_COUNT / 2;
		PDEBUG("Fifo under half full.\n");
	} else {
		c = 0;
		PDEBUG("Fifo full.\n");
	}

	PDEBUG("Try to write 0x%04X values.\n", c);

	if ((instance->flags & ME4600_AO_FLAGS_SW_WRAP_MODE_MASK) ==
	    ME4600_AO_FLAGS_SW_WRAP_MODE_INF) {
		while (c) {
			c1 = c;

			if (c1 > (instance->circ_buf.head - instance->circ_buf.tail))	/* Only up to the end of the buffer */
				c1 = (instance->circ_buf.head -
				      instance->circ_buf.tail);

			/* Write the values to the FIFO */
			for (i = 0; i < c1; i++, instance->circ_buf.tail++, c--) {
				if (instance->ao_idx & 0x1)
					outl(instance->circ_buf.
					     buf[instance->circ_buf.tail] << 16,
					     instance->fifo_reg);
				else
					outl(instance->circ_buf.
					     buf[instance->circ_buf.tail],
					     instance->fifo_reg);
			}

			if (instance->circ_buf.tail >= instance->circ_buf.head)	/* Start from beginning */
				instance->circ_buf.tail = 0;
		}

		spin_lock(&instance->subdevice_lock);

		tmp = inl(instance->ctrl_reg);
		tmp |= ME4600_AO_CTRL_BIT_RESET_IRQ;
		outl(tmp, instance->ctrl_reg);
		tmp &= ~ME4600_AO_CTRL_BIT_RESET_IRQ;
		outl(tmp, instance->ctrl_reg);

		if (!(inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM)) {
			PERROR("Broken pipe.\n");
			instance->flags |= ME4600_AO_FLAGS_BROKEN_PIPE;
			tmp &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			outl(tmp, instance->ctrl_reg);
		}

		spin_unlock(&instance->subdevice_lock);
	} else if ((instance->flags & ME4600_AO_FLAGS_SW_WRAP_MODE_MASK) ==
		   ME4600_AO_FLAGS_SW_WRAP_MODE_FIN) {
		while (c && instance->wrap_remaining) {
			c1 = c;

			if (c1 > (instance->circ_buf.head - instance->circ_buf.tail))	/* Only up to the end of the buffer */
				c1 = (instance->circ_buf.head -
				      instance->circ_buf.tail);

			if (c1 > instance->wrap_remaining)	/* Only up to count of user defined number of values */
				c1 = instance->wrap_remaining;

			/* Write the values to the FIFO */
			for (i = 0; i < c1;
			     i++, instance->circ_buf.tail++, c--,
			     instance->wrap_remaining--) {
				if (instance->ao_idx & 0x1)
					outl(instance->circ_buf.
					     buf[instance->circ_buf.tail] << 16,
					     instance->fifo_reg);
				else
					outl(instance->circ_buf.
					     buf[instance->circ_buf.tail],
					     instance->fifo_reg);
			}

			if (instance->circ_buf.tail >= instance->circ_buf.head)	/* Start from beginning */
				instance->circ_buf.tail = 0;
		}

		spin_lock(&instance->subdevice_lock);

		tmp = inl(instance->ctrl_reg);

		if (!instance->wrap_remaining) {
			PDEBUG("Finite SW wraparound done.\n");
			tmp &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
		}

		tmp |= ME4600_AO_CTRL_BIT_RESET_IRQ;

		outl(tmp, instance->ctrl_reg);
		tmp &= ~ME4600_AO_CTRL_BIT_RESET_IRQ;
		outl(tmp, instance->ctrl_reg);

		if (!(inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM)) {
			PERROR("Broken pipe.\n");
			instance->flags |= ME4600_AO_FLAGS_BROKEN_PIPE;
			tmp &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			outl(tmp, instance->ctrl_reg);
		}

		spin_unlock(&instance->subdevice_lock);

	} else {		/* Regular continuous mode */

		while (1) {
			c1 = me_circ_buf_values_to_end(&instance->circ_buf);
			PDEBUG("Values to end = %d.\n", c1);

			if (c1 > c)
				c1 = c;

			if (c1 <= 0) {
				PDEBUG("Work done or buffer empty.\n");
				break;
			}

			if (instance->ao_idx & 0x1) {
				for (i = 0; i < c1; i++) {
					value =
					    *(instance->circ_buf.buf +
					      instance->circ_buf.tail +
					      i) << 16;
					outl(value, instance->fifo_reg);
				}
			} else
				outsl(instance->fifo_reg,
				      instance->circ_buf.buf +
				      instance->circ_buf.tail, c1);

			instance->circ_buf.tail =
			    (instance->circ_buf.tail +
			     c1) & (instance->circ_buf.mask);

			PDEBUG("%d values wrote to port 0x%04X.\n", c1,
			       instance->fifo_reg);

			c -= c1;
		}

		spin_lock(&instance->subdevice_lock);

		tmp = inl(instance->ctrl_reg);

		if (!me_circ_buf_values(&instance->circ_buf)) {
			PDEBUG
			    ("Disable Interrupt because no values left in buffer.\n");
			tmp &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
		}

		tmp |= ME4600_AO_CTRL_BIT_RESET_IRQ;

		outl(tmp, instance->ctrl_reg);
		tmp &= ~ME4600_AO_CTRL_BIT_RESET_IRQ;
		outl(tmp, instance->ctrl_reg);

		if (!(inl(instance->status_reg) & ME4600_AO_STATUS_BIT_FSM)) {
			PDEBUG("Broken pipe in me4600_ao_isr.\n");
			instance->flags |= ME4600_AO_FLAGS_BROKEN_PIPE;
			tmp &= ~ME4600_AO_CTRL_BIT_ENABLE_IRQ;
			outl(tmp, instance->ctrl_reg);
		}

		spin_unlock(&instance->subdevice_lock);

		wake_up_interruptible(&instance->wait_queue);
	}

	return IRQ_HANDLED;
}

static void me4600_ao_destructor(struct me_subdevice *subdevice)
{
	me4600_ao_subdevice_t *instance;

	PDEBUG("executed.\n");

	instance = (me4600_ao_subdevice_t *) subdevice;

	free_irq(instance->irq, instance);
	kfree(instance->circ_buf.buf);
	me_subdevice_deinit(&instance->base);
	kfree(instance);
}

me4600_ao_subdevice_t *me4600_ao_constructor(uint32_t reg_base,
					     spinlock_t *preload_reg_lock,
					     uint32_t *preload_flags,
					     int ao_idx, int fifo, int irq)
{
	me4600_ao_subdevice_t *subdevice;
	int err;

	PDEBUG("executed.\n");

	/* Allocate memory for subdevice instance */
	subdevice = kmalloc(sizeof(me4600_ao_subdevice_t), GFP_KERNEL);

	if (!subdevice) {
		PERROR("Cannot get memory for subdevice instance.\n");
		return NULL;
	}

	memset(subdevice, 0, sizeof(me4600_ao_subdevice_t));

	/* Initialize subdevice base class */
	err = me_subdevice_init(&subdevice->base);

	if (err) {
		PERROR("Cannot initialize subdevice base class instance.\n");
		kfree(subdevice);
		return NULL;
	}
	// Initialize spin locks.
	spin_lock_init(&subdevice->subdevice_lock);

	subdevice->preload_reg_lock = preload_reg_lock;
	subdevice->preload_flags = preload_flags;

	/* Allocate and initialize circular buffer */
	subdevice->circ_buf.mask = ME4600_AO_CIRC_BUF_COUNT - 1;
	subdevice->circ_buf.buf = kmalloc(ME4600_AO_CIRC_BUF_SIZE, GFP_KERNEL);

	if (!subdevice->circ_buf.buf) {
		PERROR("Cannot initialize subdevice base class instance.\n");
		me_subdevice_deinit((me_subdevice_t *) subdevice);
		kfree(subdevice);
		return NULL;
	}

	memset(subdevice->circ_buf.buf, 0, ME4600_AO_CIRC_BUF_SIZE);

	subdevice->circ_buf.head = 0;
	subdevice->circ_buf.tail = 0;

	/* Initialize wait queue */
	init_waitqueue_head(&subdevice->wait_queue);

	/* Initialize single value to 0V */
	subdevice->single_value = 0x8000;

	/* Store analog output index */
	subdevice->ao_idx = ao_idx;

	/* Store if analog output has fifo */
	subdevice->fifo = fifo;

	/* Initialize registers */

	if (ao_idx == 0) {
		subdevice->ctrl_reg = reg_base + ME4600_AO_00_CTRL_REG;
		subdevice->status_reg = reg_base + ME4600_AO_00_STATUS_REG;
		subdevice->fifo_reg = reg_base + ME4600_AO_00_FIFO_REG;
		subdevice->single_reg = reg_base + ME4600_AO_00_SINGLE_REG;
		subdevice->timer_reg = reg_base + ME4600_AO_00_TIMER_REG;
		subdevice->reg_base = reg_base;

		if (inl(subdevice->reg_base + ME4600_AO_BOSCH_REG) == 0x20000) {
			PINFO("Bosch firmware in use for channel 0.\n");
			subdevice->bosch_fw = 1;
		} else {
			subdevice->bosch_fw = 0;
		}
	} else if (ao_idx == 1) {
		subdevice->ctrl_reg = reg_base + ME4600_AO_01_CTRL_REG;
		subdevice->status_reg = reg_base + ME4600_AO_01_STATUS_REG;
		subdevice->fifo_reg = reg_base + ME4600_AO_01_FIFO_REG;
		subdevice->single_reg = reg_base + ME4600_AO_01_SINGLE_REG;
		subdevice->timer_reg = reg_base + ME4600_AO_01_TIMER_REG;
		subdevice->reg_base = reg_base;
		subdevice->bosch_fw = 0;
	} else if (ao_idx == 2) {
		subdevice->ctrl_reg = reg_base + ME4600_AO_02_CTRL_REG;
		subdevice->status_reg = reg_base + ME4600_AO_02_STATUS_REG;
		subdevice->fifo_reg = reg_base + ME4600_AO_02_FIFO_REG;
		subdevice->single_reg = reg_base + ME4600_AO_02_SINGLE_REG;
		subdevice->timer_reg = reg_base + ME4600_AO_02_TIMER_REG;
		subdevice->reg_base = reg_base;
		subdevice->bosch_fw = 0;
	} else {
		subdevice->ctrl_reg = reg_base + ME4600_AO_03_CTRL_REG;
		subdevice->status_reg = reg_base + ME4600_AO_03_STATUS_REG;
		subdevice->fifo_reg = reg_base + ME4600_AO_03_FIFO_REG;
		subdevice->single_reg = reg_base + ME4600_AO_03_SINGLE_REG;
		subdevice->timer_reg = reg_base + ME4600_AO_03_TIMER_REG;
		subdevice->reg_base = reg_base;
		subdevice->bosch_fw = 0;
	}

	subdevice->irq_status_reg = reg_base + ME4600_IRQ_STATUS_REG;
	subdevice->preload_reg = reg_base + ME4600_AO_LOADSETREG_XX;

	/* Register interrupt service routine */
	subdevice->irq = irq;

	if (request_irq
	    (subdevice->irq, me4600_ao_isr, SA_INTERRUPT | SA_SHIRQ,
	     ME4600_NAME, subdevice)) {
		PERROR("Cannot get interrupt line.\n");
		me_subdevice_deinit((me_subdevice_t *) subdevice);
		kfree(subdevice->circ_buf.buf);
		kfree(subdevice);
		return NULL;
	}

	/* Override base class methods. */
	subdevice->base.me_subdevice_destructor = me4600_ao_destructor;
	subdevice->base.me_subdevice_io_reset_subdevice =
	    me4600_ao_io_reset_subdevice;
	subdevice->base.me_subdevice_io_single_config =
	    me4600_ao_io_single_config;
	subdevice->base.me_subdevice_io_single_read = me4600_ao_io_single_read;
	subdevice->base.me_subdevice_io_single_write =
	    me4600_ao_io_single_write;
	subdevice->base.me_subdevice_io_stream_config =
	    me4600_ao_io_stream_config;
	subdevice->base.me_subdevice_io_stream_new_values =
	    me4600_ao_io_stream_new_values;
	subdevice->base.me_subdevice_io_stream_write =
	    me4600_ao_io_stream_write;
	subdevice->base.me_subdevice_io_stream_start =
	    me4600_ao_io_stream_start;
	subdevice->base.me_subdevice_io_stream_status =
	    me4600_ao_io_stream_status;
	subdevice->base.me_subdevice_io_stream_stop = me4600_ao_io_stream_stop;
	subdevice->base.me_subdevice_query_number_channels =
	    me4600_ao_query_number_channels;
	subdevice->base.me_subdevice_query_subdevice_type =
	    me4600_ao_query_subdevice_type;
	subdevice->base.me_subdevice_query_subdevice_caps =
	    me4600_ao_query_subdevice_caps;
	subdevice->base.me_subdevice_query_subdevice_caps_args =
	    me4600_ao_query_subdevice_caps_args;
	subdevice->base.me_subdevice_query_range_by_min_max =
	    me4600_ao_query_range_by_min_max;
	subdevice->base.me_subdevice_query_number_ranges =
	    me4600_ao_query_number_ranges;
	subdevice->base.me_subdevice_query_range_info =
	    me4600_ao_query_range_info;
	subdevice->base.me_subdevice_query_timer = me4600_ao_query_timer;

	return subdevice;
}

#endif // BOSCH

/* Common functions
*/

static int me4600_ao_query_range_by_min_max(me_subdevice_t *subdevice,
					    int unit,
					    int *min,
					    int *max, int *maxdata, int *range)
{
	me4600_ao_subdevice_t *instance;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if ((*max - *min) < 0) {
		PERROR("Invalid minimum and maximum values specified.\n");
		return ME_ERRNO_INVALID_MIN_MAX;
	}

	if ((unit == ME_UNIT_VOLT) || (unit == ME_UNIT_ANY)) {
		if ((*max <= (ME4600_AO_MAX_RANGE + 1000))
		    && (*min >= ME4600_AO_MIN_RANGE)) {
			*min = ME4600_AO_MIN_RANGE;
			*max = ME4600_AO_MAX_RANGE;
			*maxdata = ME4600_AO_MAX_DATA;
			*range = 0;
		} else {
			PERROR("No matching range available.\n");
			return ME_ERRNO_NO_RANGE;
		}
	} else {
		PERROR("Invalid physical unit specified.\n");
		return ME_ERRNO_INVALID_UNIT;
	}

	return ME_ERRNO_SUCCESS;
}

static int me4600_ao_query_number_ranges(me_subdevice_t *subdevice,
					 int unit, int *count)
{
	me4600_ao_subdevice_t *instance;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if ((unit == ME_UNIT_VOLT) || (unit == ME_UNIT_ANY)) {
		*count = 1;
	} else {
		*count = 0;
	}

	return ME_ERRNO_SUCCESS;
}

static int me4600_ao_query_range_info(me_subdevice_t *subdevice,
				      int range,
				      int *unit,
				      int *min, int *max, int *maxdata)
{
	me4600_ao_subdevice_t *instance;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (range == 0) {
		*unit = ME_UNIT_VOLT;
		*min = ME4600_AO_MIN_RANGE;
		*max = ME4600_AO_MAX_RANGE;
		*maxdata = ME4600_AO_MAX_DATA;
	} else {
		PERROR("Invalid range number specified.\n");
		return ME_ERRNO_INVALID_RANGE;
	}

	return ME_ERRNO_SUCCESS;
}

static int me4600_ao_query_timer(me_subdevice_t *subdevice,
				 int timer,
				 int *base_frequency,
				 long long *min_ticks, long long *max_ticks)
{
	me4600_ao_subdevice_t *instance;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if ((timer != ME_TIMER_ACQ_START) && (timer != ME_TIMER_CONV_START)) {
		PERROR("Invalid timer specified.\n");
		return ME_ERRNO_INVALID_TIMER;
	}

	if (instance->fifo) {	//Streaming device.
		*base_frequency = ME4600_AO_BASE_FREQUENCY;
		if (timer == ME_TIMER_ACQ_START) {
			*min_ticks = ME4600_AO_MIN_ACQ_TICKS;
			*max_ticks = ME4600_AO_MAX_ACQ_TICKS;
		} else if (timer == ME_TIMER_CONV_START) {
			*min_ticks = ME4600_AO_MIN_CHAN_TICKS;
			*max_ticks = ME4600_AO_MAX_CHAN_TICKS;
		}
	} else {		//Not streaming device!
		*base_frequency = 0;
		*min_ticks = 0;
		*max_ticks = 0;
	}

	return ME_ERRNO_SUCCESS;
}

static int me4600_ao_query_number_channels(me_subdevice_t *subdevice,
					   int *number)
{
	me4600_ao_subdevice_t *instance;
	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	*number = 1;

	return ME_ERRNO_SUCCESS;
}

static int me4600_ao_query_subdevice_type(me_subdevice_t *subdevice,
					  int *type, int *subtype)
{
	me4600_ao_subdevice_t *instance;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	*type = ME_TYPE_AO;
	*subtype = (instance->fifo) ? ME_SUBTYPE_STREAMING : ME_SUBTYPE_SINGLE;

	return ME_ERRNO_SUCCESS;
}

static int me4600_ao_query_subdevice_caps(me_subdevice_t *subdevice, int *caps)
{
	me4600_ao_subdevice_t *instance;
	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	*caps =
	    ME_CAPS_AO_TRIG_SYNCHRONOUS | ((instance->fifo) ? ME_CAPS_AO_FIFO :
					   ME_CAPS_NONE);

	return ME_ERRNO_SUCCESS;
}

static int me4600_ao_query_subdevice_caps_args(struct me_subdevice *subdevice,
					       int cap, int *args, int count)
{
	me4600_ao_subdevice_t *instance;
	int err = ME_ERRNO_SUCCESS;

	instance = (me4600_ao_subdevice_t *) subdevice;

	PDEBUG("executed. idx=%d\n", instance->ao_idx);

	if (count != 1) {
		PERROR("Invalid capability argument count.\n");
		return ME_ERRNO_INVALID_CAP_ARG_COUNT;
	}

	switch (cap) {
	case ME_CAP_AI_FIFO_SIZE:
		args[0] = (instance->fifo) ? ME4600_AO_FIFO_COUNT : 0;
		break;

	case ME_CAP_AI_BUFFER_SIZE:
		args[0] =
		    (instance->circ_buf.buf) ? ME4600_AO_CIRC_BUF_COUNT : 0;
		break;

	default:
		PERROR("Invalid capability.\n");
		err = ME_ERRNO_INVALID_CAP;
		args[0] = 0;
	}

	return err;
}