summaryrefslogtreecommitdiff
path: root/general/HalExtensionSample/HalExtSampleDma/HalExtSampleDma.c
blob: 3aade31808a543b98831de31c6eb68af741e4a7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
/*++

Copyright (c) 2011 Microsoft Corporation

Module Name:

    HalExtSampleDma.c

Abstract:

    This file implements a HAL Extension Module for the fictitious chDMA
    controller.

Author:

    Cody Hartwig (chartwig) 9-Jun-2011

--*/

//
// --------------------------------------------------------------------Includes
//

#include <nthalext.h>

//
// ---------------------------------------------------------------- Definitions
//

//
// Disable warnings of features used by the standard headers
//
// Disable warning C4214: nonstandard extension used : bit field types other than int
// Disable warning C4201: nonstandard extension used : nameless struct/union
// Disable warning C4115: named type definition in parentheses
// Disable warning C4127: conditional expression is constant
// Disable warning C4200: zero-sized array in struct/union
//

#pragma warning(disable:4214 4201 4115 4127 4200)

//
// Define register set size.
//

#define CH_DMA_REGISTER_SIZE            (0x210)

//
// Define maximums.
//

#define CH_DMA_MAX_REQUEST_LINES        (32)
#define CH_DMA_MAX_CHANNELS             (32)

#define CONFIGURE_ADD_REQ_CONFIG        (0x80000000)

//
// Define register offsets.
//

#define CH_DMA_CONTROL                  (0x00)
#define CH_DMA_STATUS                   (0x04)
#define CH_DMA_INTERRUPT_MASK           (0x08)

#define CH_DMA_CHAN_CONTROL             (0x00)
#define CH_DMA_CHAN_MEM_PTR             (0x04)
#define CH_DMA_CHAN_DEV_PTR             (0x08)
#define CH_DMA_CHAN_STATUS              (0x1c)

//
// Define device-side bus widths.
//

#define CH_DMA_WIDTH_8_BIT              (0)
#define CH_DMA_WIDTH_16_BIT             (1)
#define CH_DMA_WIDTH_32_BIT             (2)

//
// Define transfer burst sizes.
//

#define CH_DMA_BURST_1_WORD             (0)
#define CH_DMA_BURST_2_WORD             (1)
#define CH_DMA_BURST_4_WORD             (2)
#define CH_DMA_BURST_8_WORD             (3)

//
// Define transfer directions.
//

#define CH_DMA_DEVICE_WRITE             (0)
#define CH_DMA_DEVICE_READ              (1)

//
// ------------------------------------------------------ Data Type Definitions
//

#pragma pack(push, 1)

//
// Register Definitions.
//

typedef struct _CH_DMA_CONTROL_REGISTER {
    union {
        struct {
            ULONG ControllerEnable:1;
            ULONG Reserved:31;
        };
        ULONG AsUlong;
    };
} CH_DMA_CONTROL_REGISTER, *PCH_DMA_CONTROL_REGISTER;

typedef struct _CH_DMA_CHAN_CONTROL_REGISTER {
    union {
        struct {
            ULONG ChannelEnable:1;
            ULONG InterruptEnable:1;
            ULONG DeviceWidth:2;
            ULONG BurstSize:2;
            ULONG FlowControl:1;
            ULONG Loop:1;
            ULONG RequestLine:5;
            ULONG ReadFromDevice:1;
            ULONG Reserved:2;
            ULONG Length:16;
        };
        ULONG AsUlong;
    };
} CH_DMA_CHAN_CONTROL_REGISTER, *PCH_DMA_CHAN_CONTROL_REGISTER;

typedef struct _CH_DMA_CHAN_STATUS_REGISTER {
    union {
        struct {
            ULONG Busy:1;
            ULONG Reserved:15;
            ULONG BytesTransferred:16;
        };
        ULONG AsUlong;
    };
} CH_DMA_CHAN_STATUS_REGISTER, *PCH_DMA_CHAN_STATUS_REGISTER;

//
// CSRT resource descriptor types for chDMA.
//

typedef struct _CH_DMA_ADD_REQ_LINE_CONFIG {
    ULONG RequestLine;
    CH_DMA_CHAN_CONTROL_REGISTER Ctrl;
} CH_DMA_ADD_REQ_LINE_CONFIG, *PCH_DMA_ADD_REQ_LINE_CONFIG;

typedef struct _RD_DMA_CONTROLLER {
    CSRT_RESOURCE_DESCRIPTOR_HEADER Header;
    ULONGLONG BasePhysicalAddress;
    ULONG ChannelCount;
    ULONG MinimumRequestLine;
    ULONG MaximumRequestLine;
    ULONG InterruptGsi;
    BOOLEAN CacheCoherent;
    ULONG ReqLineConfigCount;
    CH_DMA_ADD_REQ_LINE_CONFIG ReqLineConfigs[ANYSIZE_ARRAY];
} RD_DMA_CONTROLLER, *PRD_DMA_CONTROLLER;

//
// Resource description matching chDMA controller described in chdmaReadme.txt:
//
// CH_DMA_CHAN_CONTROL_REGISTER UartControl;
// UartControl.AsUlong = 0;
// UartControl.DeviceWidth = CH_DMA_WIDTH_8_BIT;
// UartControl.BurstSize = CH_DMA_BURST_1_WORD;
// UartControl.FlowControl = 1;
//
// CH_DMA_ADD_REQ_LINE_CONFIG UartConfig = {
//      0x15,
//      UartControl
// };
//
// RD_DMA_CONTROLLER DmaDesc = {
//      Header,
//      0x70001000,
//      32,
//      0,
//      31,
//      0x27,
//      FALSE,
//      1,
//      { UartConfig }
// };
//

typedef struct _RD_DMA_CHANNEL {
    CSRT_RESOURCE_DESCRIPTOR_HEADER Header;
    ULONG ChannelNumber;
} RD_DMA_CHANNEL, *PRD_DMA_CHANNEL;

//
// Resource description matching chDMA channel described in chdmaReadme.txt:
//
// RD_DMA_CHANNEL DmaDesc = {
//      Header,
//      0
// };
//

#pragma pack(pop)

//
// Extension Request line to configuration mapping.
//

typedef struct _CH_REQ_LINE_CONFIG {
    BOOLEAN Valid;
    CH_DMA_CHAN_CONTROL_REGISTER Ctrl;
} CH_REQ_LINE_CONFIG, *PCH_REQ_LINE_CONFIG;

typedef struct _CH_REQ_LINE_CONFIG_TABLE {
    CH_REQ_LINE_CONFIG Entries[CH_DMA_MAX_REQUEST_LINES];
} CH_DMA_REQ_LINE_CONFIG_TABLE, *PCH_DMA_REQ_LINE_CONFIG_TABLE;

//
// Define extension internal data for the controller and channel.
//

typedef struct _CH_DMA_CHANNEL {
    BOOLEAN Active;
    BOOLEAN AutoInit;
} CH_DMA_CHANNEL, *PCH_DMA_CHANNEL;

typedef struct _CH_DMA_CONTROLLER {

    //
    // Virtual and physical base addresses of the controller.
    //

    PULONG ControllerBaseVa;
    PHYSICAL_ADDRESS ControllerBasePa;

    ULONG ChannelCount;
    ULONG MinimumRequestLine;
    ULONG MaximumRequestLine;

    //
    // Individual channel extension status.
    //

    CH_DMA_CHANNEL Channels[CH_DMA_MAX_CHANNELS];

    //
    // Request line to configuration mapping.
    //

    CH_DMA_REQ_LINE_CONFIG_TABLE ReqConfig;
} CH_DMA_CONTROLLER, *PCH_DMA_CONTROLLER;

//
// ----------------------------------------------------------------- Prototypes
//

VOID
ChInitializeController (
    __in PVOID ControllerContext
    );

BOOLEAN
ChValidateRequestLineBinding (
    __in PVOID ControllerContext,
    __in PDMA_REQUEST_LINE_BINDING_DESCRIPTION BindingDescription
    );

ULONG
ChQueryMaxFragments (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber,
    __in ULONG MaxFragmentsRequested
    );

VOID
ChProgramChannel (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber,
    __in ULONG RequestLine,
    __in PDMA_SCATTER_GATHER_LIST MemoryAddresses,
    __in PHYSICAL_ADDRESS DeviceAddress,
    __in BOOLEAN WriteToDevice,
    __in BOOLEAN LoopTransfer
    );

BOOLEAN
ChCancelTransfer (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber
    );

NTSTATUS
ChConfigureChannel (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber,
    __in ULONG FunctionNumber,
    __in PVOID Context
    );

VOID
ChFlushChannel (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber
    );

_Success_(return != FALSE)
BOOLEAN
ChHandleInterrupt (
    __in PVOID ControllerContext,
    __out PULONG ChannelNumber,
    __out PDMA_INTERRUPT_TYPE InterruptType
    );

ULONG
ChReadDmaCounter (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber
    );

//
// -------------------------------------------------------------------- Globals
//

DMA_FUNCTION_TABLE ChFunctionTable =
{
    ChInitializeController,
    ChValidateRequestLineBinding,
    ChQueryMaxFragments,
    ChProgramChannel,
    ChConfigureChannel,
    ChFlushChannel,
    ChHandleInterrupt,
    ChReadDmaCounter,
    NULL, /* ReportCommonBuffer */
    ChCancelTransfer
};

//
// ------------------------------------------------------------------- Routines
//

VOID
WriteRegister (
    __in PCH_DMA_CONTROLLER Controller,
    __in ULONG RegisterOffset,
    __in ULONG Value
    )

{

    PULONG Address;

    Address = Controller->ControllerBaseVa;

    //
    // Add register offset.  Register offset is in bytes.  Pointer addition is
    // in ULONGs.
    //

    Address += (RegisterOffset / 4);

    WRITE_REGISTER_ULONG(Address, Value);
}

ULONG
ReadRegister (
    __in PCH_DMA_CONTROLLER Controller,
    __in ULONG RegisterOffset
    )

{

    PULONG Address;

    Address = Controller->ControllerBaseVa;

    //
    // Add register offset.  Register offset is in bytes.  Pointer addition is
    // in ULONGs.
    //

    Address += (RegisterOffset / 4);

    return READ_REGISTER_ULONG(Address);
}

VOID
WriteChannelRegister (
    __in PCH_DMA_CONTROLLER Controller,
    __in ULONG ChannelNumber,
    __in ULONG RegisterOffset,
    __in ULONG Value
    )

{
    PULONG Address;

    Address = Controller->ControllerBaseVa;

    //
    // Add channel base offset.
    // Register offset is in bytes.  Pointer addition is in ULONGs.
    //

    Address += (0x10 / 4);

    //
    // Add channel number offset.
    //

    Address += ((0x10 * ChannelNumber) / 4);

    //
    // Add channel register offset.
    //

    Address += (RegisterOffset / 4);

    WRITE_REGISTER_ULONG(Address, Value);
}

ULONG
ReadChannelRegister (
    __in PCH_DMA_CONTROLLER Controller,
    __in ULONG ChannelNumber,
    __in ULONG RegisterOffset
    )

{

    PULONG Address;

    Address = Controller->ControllerBaseVa;

    //
    // Add channel base offset.
    // Register offset is in bytes.  Pointer addition is in ULONGs.
    //

    Address += (0x10 / 4);

    //
    // Add channel number offset.
    //

    Address += ((0x10 * ChannelNumber) / 4);

    //
    // Add channel register offset.
    //

    Address += (RegisterOffset / 4);

    return READ_REGISTER_ULONG(Address);
}

VOID
ChInitializeController (
    __in PVOID ControllerContext
    )

/*++

Routine Description:

    This routine provides an opportunity for DMA controllers to initialize.

Arguments:

    ControllerContext - Supplies a pointer to the controller's internel data.

Return Value:

    None.

--*/

{

    CH_DMA_CONTROL_REGISTER CtrlRegister;
    PCH_DMA_CONTROLLER Controller;
    ULONG Index;
    ULONG InterruptMask;

    Controller = (PCH_DMA_CONTROLLER)ControllerContext;

    //
    // Map the controller base iff this is the first call to init (and it is
    // therefore not already mapped.)
    //

    if (Controller->ControllerBaseVa == NULL) {
        Controller->ControllerBaseVa =
            (PULONG) HalMapIoSpace(Controller->ControllerBasePa,
                                   PAGE_SIZE,
                                   MmNonCached);

        NT_ASSERT(Controller->ControllerBaseVa != NULL);
    }

    if (Controller->ControllerBaseVa == NULL) {
        return;
    }

    //
    // Initialize each channel.
    //

    for (Index = 0; Index < Controller->ChannelCount; Index += 1) {
        WriteChannelRegister(Controller, Index, CH_DMA_CHAN_CONTROL, 0);
        Controller->Channels[Index].Active = FALSE;
        Controller->Channels[Index].AutoInit = FALSE;
    }

    //
    // Enable the DMA controller.
    //

    CtrlRegister.AsUlong = 0;
    CtrlRegister.ControllerEnable = 1;
    WriteRegister(Controller, CH_DMA_CONTROL, CtrlRegister.AsUlong);

    //
    // Enable all interrupts.
    //

    InterruptMask = (1UL << Controller->ChannelCount) - 1;
    WriteRegister(Controller, CH_DMA_INTERRUPT_MASK, InterruptMask);

    return;
}

BOOLEAN
ChValidateRequestLineBinding (
    __in PVOID ControllerContext,
    __in PDMA_REQUEST_LINE_BINDING_DESCRIPTION BindingDescription
    )

/*++

Routine Description:

    This routine queries a DMA controller extension to test the validity of a
    request line binding.

Arguments:

    ControllerContext - Supplies a pointer to the controller's internal data.

    DeviceDescription - Supplies a pointer to the request information.

Return Value:

    TRUE if the request line binding is valid and supported by the controller.

    FALSE if the binding is invalid.

Environment:

    PASSIVE_LEVEL.

--*/

{

    PCH_DMA_CONTROLLER Controller;

    Controller = (PCH_DMA_CONTROLLER)ControllerContext;
    if (BindingDescription->ChannelNumber > Controller->ChannelCount) {
        return FALSE;
    }

    if ((BindingDescription->RequestLine > Controller->MaximumRequestLine) ||
        (BindingDescription->RequestLine < Controller->MinimumRequestLine)) {

        return FALSE;
    }

    return TRUE;
}

ULONG
ChQueryMaxFragments (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber,
    __in ULONG MaxFragmentsRequested
    )

/*++

Routine Description:

    This routine queries the DMA extension to determine the number of
    scatter gather fragments that the next transfer can support.

Arguments:

    ControllerContext - Supplies a pointer to the controller's internal data.

    ChannelNumber - Supplies the number of the channel to program.

    MaxFragmentsRequested - Supplies a hint to the maximum fragments useful to
        this transfer.

Return Value:

    Number of fragments the next transfer on this channel can support.

--*/

{

    UNREFERENCED_PARAMETER(ControllerContext);
    UNREFERENCED_PARAMETER(ChannelNumber);
    UNREFERENCED_PARAMETER(MaxFragmentsRequested);

    return 1;
}

VOID
ChProgramChannel (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber,
    __in ULONG RequestLine,
    __in PDMA_SCATTER_GATHER_LIST MemoryAddresses,
    __in PHYSICAL_ADDRESS DeviceAddress,
    __in BOOLEAN WriteToDevice,
    __in BOOLEAN LoopTransfer
    )

/*++

Routine Description:

    This routine programs a DMA controller channel for a specific transfer.

Arguments:

    ControllerContext - Supplies a pointer to the controller's internal data.

    ChannelNumber - Supplies the number of the channel to program.

    RequestLine - Supplies the request line number to program.  This request
        line number is system-unique (as provided to the HAL during
        registration) and must be translated by the extension.

    MemoryAddress - Supplies the address to be programmed into the memory
        side of the channel configuration.

    DeviceAddress - Supplies the address to be programmed into the device
        side of the channel configuration.

    WriteToDevice - Supplies the direction of the transfer.

    LoopTransfer - Supplies whether AutoInitialize has been set in the
        adapter making this request.

Return Value:

    None.

--*/

{

    CH_DMA_CHAN_CONTROL_REGISTER Ctrl;
    PCH_DMA_CONTROLLER Controller;
    ULONG DevPtr;
    ULONG MemPtr;

    Controller = (PCH_DMA_CONTROLLER)ControllerContext;
    Controller->Channels[ChannelNumber].Active = TRUE;

    //
    // If this request line exists in the request line config table, use
    // those values.  Otherwise, use the reset values.
    //

    Ctrl.AsUlong = 0;
    if (Controller->ReqConfig.Entries[RequestLine].Valid != 0) {
        Ctrl.AsUlong = Controller->ReqConfig.Entries[RequestLine].Ctrl.AsUlong;
    }

    Ctrl.ChannelEnable = 1;
    Ctrl.InterruptEnable = 1;
    Ctrl.Loop = (LoopTransfer == FALSE) ? 0 : 1;
    Ctrl.ReadFromDevice = (WriteToDevice == FALSE) ? 1 : 0;

    //
    // Request lines numbers reported by BIOS may be offset to make them
    // globally unique.  Request lines on the controller are based at 0.
    //

    Ctrl.RequestLine = RequestLine - Controller->MinimumRequestLine;
    Ctrl.Length = MemoryAddresses->Elements[0].Length;

    DevPtr = DeviceAddress.LowPart;
    MemPtr = MemoryAddresses->Elements[0].Address.LowPart;

    WriteChannelRegister(Controller,
                         ChannelNumber,
                         CH_DMA_CHAN_MEM_PTR,
                         MemPtr);

    WriteChannelRegister(Controller,
                         ChannelNumber,
                         CH_DMA_CHAN_DEV_PTR,
                         DevPtr);

    //
    // Channel control is written last as it will enable the channel.
    //

    WriteChannelRegister(Controller,
                         ChannelNumber,
                         CH_DMA_CHAN_CONTROL,
                         Ctrl.AsUlong);
}

BOOLEAN
ChCancelTransfer (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber
    )

/*++

Routine Description:

    This routine must disable the selected channel.  The channel must not be
    capable of interrupting for this transfer after being cleared in this way.

Arguments:

    ControllerContext - Supplies a pointer to the controller's internal data.

    ChannelNumber - Supplies the channel number.

Return Value:

    FALSE if the channel is already idle or if the channel is already asserting
    an interrupt.  TRUE is the channel is active and no interrupt is asserted.

--*/

{

    PCH_DMA_CONTROLLER Controller;
    ULONG StatusRegister;

    Controller = (PCH_DMA_CONTROLLER)ControllerContext;

    //
    // If the channel is not active (because the interrupt already fired or
    // because the channel was never programmed, return immediately.
    //

    if (Controller->Channels[ChannelNumber].Active == FALSE) {
        return FALSE;
    }

    //
    // Disable the channel.
    //

    WriteChannelRegister(Controller, ChannelNumber, CH_DMA_CHAN_CONTROL, 0);

    //
    // If an interrupt is already pending on the channel, do nothing.  The
    // normal interrupt path will complete it.  If an interrupt is not pending
    // then this was successfully cancelled.  In that case, mark the channel
    // inactive and return TRUE.
    //

    StatusRegister = ReadRegister(Controller, CH_DMA_STATUS);
    if ((StatusRegister & (1UL << ChannelNumber)) != 0) {
        return FALSE;

    } else {
        Controller->Channels[ChannelNumber].Active = FALSE;
        return TRUE;
    }
}

NTSTATUS
AddReqLineConfig (
    __in PCH_DMA_CONTROLLER Controller,
    __in PCH_DMA_ADD_REQ_LINE_CONFIG Config
    )

/*++

Routine Description:

    This routine updates the request line configuration table in the
    extension's internal data for this controller.

Arguments:

    Controller - Supplies a pointer to the internal data for the controller.

    Config - Supplies a pointer to the configuration to modify.

Return Value:

    STATUS_INVALID_PARAMETER if the request line is invalid.
    Else, STATUS_SUCCESS.

--*/

{

    ULONG RequestLine;

    RequestLine = Config->RequestLine;
    if ((RequestLine < Controller->MinimumRequestLine) ||
        (RequestLine > Controller->MaximumRequestLine)) {

        return STATUS_INVALID_PARAMETER;
    }

    Controller->ReqConfig.Entries[RequestLine].Ctrl.AsUlong =
        Config->Ctrl.AsUlong;

    return STATUS_SUCCESS;
}

NTSTATUS
ChConfigureChannel (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber,
    __in ULONG FunctionNumber,
    __in PVOID Context
    )

/*++

Routine Description:

    This routine configures the channel for a DMA extension specific operation.

Arguments:

    ControllerContext - Supplies a pointer to the controller's internal data.

    ChannelNumber - Supplies the channel to configure.

    FunctionNumber - Supplies the ID of the operation to perform.

    Context - Supplies parameters for this operation.

Return Value:

    NTSTATUS code.

--*/

{

    PCH_DMA_CONTROLLER Controller;
    NTSTATUS Status;

    UNREFERENCED_PARAMETER(ChannelNumber);

    Controller = (PCH_DMA_CONTROLLER)ControllerContext;
    switch (FunctionNumber) {
    case CONFIGURE_ADD_REQ_CONFIG:
        Status = AddReqLineConfig(Controller,
                                  (PCH_DMA_ADD_REQ_LINE_CONFIG)Context);

        break;
    default:
        Status = STATUS_NOT_IMPLEMENTED;
    }

    return Status;
}

VOID
ChFlushChannel (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber
    )

/*++

Routine Description:

    This routine flushes a previous transfer from a channel and returns the
    channel to a state ready for the next ProgramChannel call.

Arguments:

    ControllerContext - Supplies a pointer to the controller's internal data.

    ChannelNumber - Supplies the channel to flush.

Return Value:

    None.

--*/

{

    PCH_DMA_CONTROLLER Controller;

    Controller = (PCH_DMA_CONTROLLER)ControllerContext;
    WriteChannelRegister(Controller, ChannelNumber, CH_DMA_CHAN_CONTROL, 0);
}

_Success_(return != FALSE)
BOOLEAN
ChHandleInterrupt (
    __in PVOID ControllerContext,
    __out PULONG ChannelNumber,
    __out PDMA_INTERRUPT_TYPE InterruptType
    )

/*++

Routine Description:

    This routine probes a controller for interrupts, clears any interrupts
    found, fills in channel and interrupt type information.  This routine
    will be called repeatedly until FALSE is returned.

Arguments:

    ControllerContext - Supplies a pointer to the controller's internal data.

    ChannelNumber - Supplies a placeholder for the extension to fill in which
        channel is interrupting.

    InterruptType - Supplies a placeholder for the extension to fill in the
        interrupt type.

Return Value:

    TRUE if an interrupt was found on this controller.

    FALSE otherwise.

--*/

{

    PCH_DMA_CONTROLLER Controller;
    ULONG Index;
    ULONG StatusRegister;

    Controller = (PCH_DMA_CONTROLLER)ControllerContext;
    StatusRegister = ReadRegister(Controller, CH_DMA_STATUS);
    for (Index = 0; Index < Controller->ChannelCount; Index += 1) {
        if ((StatusRegister & (1UL << Index)) != 0) {
            *ChannelNumber = Index;
            *InterruptType = InterruptTypeCompletion;
            WriteRegister(Controller, CH_DMA_STATUS, (1UL << Index));

            //
            // If the channel is not marked as active, then this interrupt
            // is spurious.  Probably this is the result of a transfer being
            // cancelled.
            //

            if (Controller->Channels[Index].Active == FALSE) {
                continue;
            }

            //
            // If the channel is not in autoinitialize mode, is it inactive now.
            // If the channel is in autoinitialize, then it will remain active
            // until it receives a cancel.
            //

            if (Controller->Channels[Index].AutoInit == FALSE) {
                Controller->Channels[Index].Active = FALSE;
            }

            return TRUE;
        }
    }

    return FALSE;
}

ULONG ChReadDmaCounter (
    __in PVOID ControllerContext,
    __in ULONG ChannelNumber
    )

/*++

Routine Description:

    This routine determines how many bytes remain to be transferred on the
    given channel.  If the current transfer is set to loop, this routine
    will return the number of bytes remaining in the current iteration.

Arguments:

    ControllerContext - Supplies a pointer to the controller's internal data.

    ChannelNumber - Supplies the channel number.

Return Value:

    Returns the number of bytes remaining to be transferred on the given
    channel.

--*/

{

    PCH_DMA_CONTROLLER Controller;
    CH_DMA_CHAN_CONTROL_REGISTER Ctrl;
    CH_DMA_CHAN_STATUS_REGISTER StatusReg;

    Controller = (PCH_DMA_CONTROLLER)ControllerContext;
    Ctrl.AsUlong = ReadChannelRegister(Controller,
                                       ChannelNumber,
                                       CH_DMA_CHAN_CONTROL);

    StatusReg.AsUlong = ReadChannelRegister(Controller,
                                            ChannelNumber,
                                            CH_DMA_CHAN_STATUS);

    return (Ctrl.Length - StatusReg.BytesTransferred);
}

NTSTATUS
RegisterDmaController (
    __in ULONG Handle,
    __in PCSRT_RESOURCE_GROUP_HEADER ResourceGroup,
    __in PCSRT_RESOURCE_DESCRIPTOR_HEADER ResourceDescriptor,
    __out PULONG ControllerId
    )

/*++

Routine Description:

    This routine takes a DMA resource descriptor with subtype controller.
    The controller is then registered with the HAL.

Arguments:

    Handle - Supplies handle passed to extension.

    ResourceGroup - Supplies resource group containing this descriptor.

    ResourceDescrpitor - Supplies the resource descriptor.

    ControllerId - Supplies a placeholder for the controller ID returned from
        the HAL after registration.

Return Value:

    NTSTATUS Value.

--*/

{

    PCH_REQ_LINE_CONFIG ConfigEntry;
    PCH_REQ_LINE_CONFIG ConfigTableDst;
    PCH_DMA_ADD_REQ_LINE_CONFIG ConfigTableSrc;
    CH_DMA_CONTROLLER Controller;
    PRD_DMA_CONTROLLER DmaDesc;
    DMA_INITIALIZATION_BLOCK DmaInitBlock;
    ULONG Index;
    ULONG RequestLine;
    NTSTATUS Status;

    RtlZeroMemory(&Controller, sizeof(CH_DMA_CONTROLLER));

    DmaDesc = (PRD_DMA_CONTROLLER)ResourceDescriptor;
    Controller.ControllerBasePa.QuadPart = DmaDesc->BasePhysicalAddress;
    Controller.ChannelCount = DmaDesc->ChannelCount;
    Controller.MinimumRequestLine = DmaDesc->MinimumRequestLine;
    Controller.MaximumRequestLine = DmaDesc->MaximumRequestLine;

    //
    // Build request line configuration mapping table.
    //

    ConfigTableDst = &Controller.ReqConfig.Entries[0];
    ConfigTableSrc = &DmaDesc->ReqLineConfigs[0];

    //
    // Verify the supplied configuration description will fit within
    // the build maximum.
    //

    if (DmaDesc->ReqLineConfigCount >= CH_DMA_MAX_REQUEST_LINES) {
        Status = STATUS_INVALID_PARAMETER_1;
        goto Exit;
    }

    for (Index = 0; Index < DmaDesc->ReqLineConfigCount; Index += 1) {

        RequestLine = ConfigTableSrc[Index].RequestLine;

        //
        // Keep PreFast happy that we're assigning within memory bounds
        //

        if (RequestLine >= CH_DMA_MAX_REQUEST_LINES) {
            Status = STATUS_INVALID_PARAMETER_2;
            goto Exit;
        }

        ConfigEntry = &ConfigTableDst[RequestLine];
        ConfigEntry->Ctrl.AsUlong = ConfigTableSrc[Index].Ctrl.AsUlong;
        ConfigEntry->Valid = TRUE;
    }

    INITIALIZE_DMA_HEADER(&DmaInitBlock);
    DmaInitBlock.ChannelCount = Controller.ChannelCount;
    DmaInitBlock.MinimumTransferUnit = 1;
    DmaInitBlock.MinimumRequestLine = Controller.MinimumRequestLine;
    DmaInitBlock.MaximumRequestLine = Controller.MaximumRequestLine;
    DmaInitBlock.CacheCoherent = DmaDesc->CacheCoherent;
    DmaInitBlock.GeneratesInterrupt = TRUE;
    DmaInitBlock.InternalData = (PVOID)&Controller;
    DmaInitBlock.InternalDataSize = sizeof(CH_DMA_CONTROLLER);
    DmaInitBlock.DmaAddressWidth = 32;
    DmaInitBlock.Gsi = DmaDesc->InterruptGsi;
    DmaInitBlock.InterruptPolarity = InterruptActiveHigh;
    DmaInitBlock.InterruptMode = LevelSensitive;
    DmaInitBlock.Operations = &ChFunctionTable;

    //
    // Register physical address space with the HAL.
    //

    HalRegisterPermanentAddressUsage(Controller.ControllerBasePa,
                                     CH_DMA_REGISTER_SIZE);

    //
    // Register controller.
    //

    Status = RegisterResourceDescriptor(Handle,
                                        ResourceGroup,
                                        ResourceDescriptor,
                                        &DmaInitBlock);

    *ControllerId = DmaInitBlock.ControllerId;

Exit:
    return Status;

}

NTSTATUS
RegisterDmaChannel (
    __in ULONG Handle,
    __in PCSRT_RESOURCE_GROUP_HEADER ResourceGroup,
    __in PCSRT_RESOURCE_DESCRIPTOR_HEADER ResourceDescriptor,
    __in ULONG ControllerId
    )

/*++

Routine Description:

    This routine takes a DMA resource descriptor with subtype channel.
    The channel is then registered with the HAL.

Arguments:

    Handle - Supplies handle passed to extension.

    ResourceGroup - Supplies resource group containing this descriptor.

    ResourceDescrpitor - Supplies the resource descriptor.

    ControllerId - Supplies the controller ID this channel is registered with.

Return Value:

    NTSTATUS Value.

--*/

{

    DMA_CHANNEL_INITIALIZATION_BLOCK DmaChannelInitBlock;
    PRD_DMA_CHANNEL DmaDesc;

    NT_ASSERT(ControllerId != 0);

    DmaDesc = (PRD_DMA_CHANNEL)ResourceDescriptor;
    INITIALIZE_DMA_CHANNEL_HEADER(&DmaChannelInitBlock);
    DmaChannelInitBlock.ControllerId = ControllerId;
    DmaChannelInitBlock.GeneratesInterrupt = FALSE;
    DmaChannelInitBlock.ChannelNumber = DmaDesc->ChannelNumber;
    DmaChannelInitBlock.CommonBufferLength = 0;

    return RegisterResourceDescriptor(Handle,
                                      ResourceGroup,
                                      ResourceDescriptor,
                                      &DmaChannelInitBlock);
}

NTSTATUS
AddResourceGroup (
    __in ULONG Handle,
    __in PCSRT_RESOURCE_GROUP_HEADER ResourceGroup
    )

{

    ULONG ControllerId;
    PCSRT_RESOURCE_DESCRIPTOR_HEADER ResourceDescriptor;

    ResourceDescriptor = NULL;
    ControllerId = 0;
    for (;;) {
        ResourceDescriptor =
            GetNextResourceDescriptor(Handle,
                                      ResourceGroup,
                                      ResourceDescriptor,
                                      CSRT_RD_TYPE_DMA,
                                      CSRT_RD_SUBTYPE_ANY,
                                      CSRT_RD_UID_ANY);

        if (ResourceDescriptor == NULL) {
            break;
        }

        if (ResourceDescriptor->Subtype == CSRT_RD_SUBTYPE_DMA_CONTROLLER) {
            RegisterDmaController(Handle,
                                  ResourceGroup,
                                  ResourceDescriptor,
                                  &ControllerId);

        } else if (ResourceDescriptor->Subtype == CSRT_RD_SUBTYPE_DMA_CHANNEL) {
            RegisterDmaChannel(Handle,
                               ResourceGroup,
                               ResourceDescriptor,
                               ControllerId);
        } else {

            NT_ASSERT(FALSE);
        }
    }

    return STATUS_SUCCESS;
}