summaryrefslogtreecommitdiffstats
path: root/private/ntos/afd/init.c
blob: 95b5ff5794eb60faa871549d343013a6ca28ebdb (plain) (blame)
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
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    init.c

Abstract:

    This module performs initialization for the AFD device driver.

Author:

    David Treadwell (davidtr)    21-Feb-1992

Revision History:

--*/

#include "afdp.h"

#define REGISTRY_PARAMETERS         L"Parameters"
#define REGISTRY_AFD_INFORMATION    L"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\Afd"
#define REGISTRY_IRP_STACK_SIZE     L"IrpStackSize"
#define REGISTRY_PRIORITY_BOOST     L"PriorityBoost"
#define REGISTRY_IGNORE_PUSH_BIT    L"IgnorePushBitOnReceives"
#define REGISTRY_NO_RAW_SECURITY    L"DisableRawSecurity"
#define REGISTRY_MAX_ACTIVE_TRANSMIT_FILE_COUNT L"MaxActiveTransmitFileCount"
#define REGISTRY_ENABLE_DYNAMIC_BACKLOG L"EnableDynamicBacklog"

#if DBG
#define REGISTRY_DEBUG_FLAGS        L"DebugFlags"
#define REGISTRY_BREAK_ON_STARTUP   L"BreakOnStartup"
#define REGISTRY_ENABLE_UNLOAD      L"EnableUnload"
#define REGISTRY_USE_PRIVATE_ASSERT L"UsePrivateAssert"
#endif

#if AFD_PERF_DBG
#define REGISTRY_DISABLE_FAST_IO    L"DisableFastIO"
#define REGISTRY_DISABLE_CONN_REUSE L"DisableConnectionReuse"
#endif

//
// A list of longwords that are configured by the registry.
//

struct _AfdConfigInfo {
    PWCHAR RegistryValueName;
    PULONG Variable;
} AfdConfigInfo[] = {
    { L"LargeBufferSize", &AfdLargeBufferSize },
    { L"LargeBufferListDepth", &AfdLargeBufferListDepth },
    { L"MediumBufferSize", &AfdMediumBufferSize },
    { L"MediumBufferListDepth", &AfdMediumBufferListDepth },
    { L"SmallBufferSize", &AfdSmallBufferSize },
    { L"SmallBufferListDepth", &AfdSmallBufferListDepth },
    { L"FastSendDatagramThreshold", &AfdFastSendDatagramThreshold },
    { L"StandardAddressLength", &AfdStandardAddressLength },
    { L"DefaultReceiveWindow", &AfdReceiveWindowSize },
    { L"DefaultSendWindow", &AfdSendWindowSize },
    { L"BufferMultiplier", &AfdBufferMultiplier },
    { L"TransmitIoLength", &AfdTransmitIoLength },
    { L"MaxFastTransmit", &AfdMaxFastTransmit },
    { L"MaxFastCopyTransmit", &AfdMaxFastCopyTransmit },
    { L"MinimumDynamicBacklog", &AfdMinimumDynamicBacklog },
    { L"MaximumDynamicBacklog", &AfdMaximumDynamicBacklog },
    { L"DynamicBacklogGrowthDelta", &AfdDynamicBacklogGrowthDelta }
};

#define AFD_CONFIG_VAR_COUNT (sizeof(AfdConfigInfo) / sizeof(AfdConfigInfo[0]))

PSECURITY_DESCRIPTOR AfdRawSecurityDescriptor = NULL;

#if DBG
BOOLEAN AfdEnableUnload = FALSE;
#endif

ULONG
AfdReadSingleParameter(
    IN HANDLE ParametersHandle,
    IN PWCHAR ValueName,
    IN LONG DefaultValue
    );

NTSTATUS
AfdOpenRegistry(
    IN PUNICODE_STRING BaseName,
    OUT PHANDLE ParametersHandle
    );

VOID
AfdReadRegistry (
    VOID
    );

#if DBG
VOID
AfdUnload (
    IN PDRIVER_OBJECT DriverObject
    );
#endif

NTSTATUS
DriverEntry (
    IN PDRIVER_OBJECT DriverObject,
    IN PUNICODE_STRING RegistryPath
    );

NTSTATUS
AfdCreateRawSecurityDescriptor(
    VOID
    );

NTSTATUS
AfdBuildDeviceAcl(
    OUT PACL *DeviceAcl
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text( INIT, DriverEntry )
#pragma alloc_text( INIT, AfdReadSingleParameter )
#pragma alloc_text( INIT, AfdOpenRegistry )
#pragma alloc_text( INIT, AfdReadRegistry )
#pragma alloc_text( INIT, AfdCreateRawSecurityDescriptor )
#pragma alloc_text( INIT, AfdBuildDeviceAcl )
#if DBG
#pragma alloc_text( PAGE, AfdUnload )
#endif
#endif


NTSTATUS
DriverEntry (
    IN PDRIVER_OBJECT DriverObject,
    IN PUNICODE_STRING RegistryPath
    )

/*++

Routine Description:

    This is the initialization routine for the AFD device driver.

Arguments:

    DriverObject - Pointer to driver object created by the system.

Return Value:

    The function value is the final status from the initialization operation.

--*/

{
    NTSTATUS status;
    UNICODE_STRING deviceName;
    CLONG i;
    BOOLEAN success;

    PAGED_CODE( );

    //
    // Create the device object.  (IoCreateDevice zeroes the memory
    // occupied by the object.)
    //
    // !!! Apply an ACL to the device object.
    //

    RtlInitUnicodeString( &deviceName, AFD_DEVICE_NAME );

    status = IoCreateDevice(
                 DriverObject,                   // DriverObject
                 0,                              // DeviceExtension
                 &deviceName,                    // DeviceName
                 FILE_DEVICE_NAMED_PIPE,         // DeviceType
                 0,                              // DeviceCharacteristics
                 FALSE,                          // Exclusive
                 &AfdDeviceObject                // DeviceObject
                 );


    if ( !NT_SUCCESS(status) ) {
        KdPrint(( "AFD DriverEntry: unable to create device object: %X\n", status ));
        return status;
    }

    //
    // Create the security descriptor used for raw socket access checks.
    //
    status = AfdCreateRawSecurityDescriptor();

    if (!NT_SUCCESS(status)) {
        IoDeleteDevice(AfdDeviceObject);
        return status;
    }

    AfdDeviceObject->Flags |= DO_DIRECT_IO;

    //
    // Initialize the driver object for this file system driver.
    //

    for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++) {
        DriverObject->MajorFunction[i] = AfdDispatch;
    }

    DriverObject->FastIoDispatch = &AfdFastIoDispatch;
    DriverObject->DriverUnload = NULL;

    //
    // Initialize global data.
    //

    success = AfdInitializeData( );
    if ( !success ) {
        IoDeleteDevice(AfdDeviceObject);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // Initialize group ID manager.
    //

    success = AfdInitializeGroup();
    if ( !success ) {
        IoDeleteDevice(AfdDeviceObject);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // Read registry information.
    //

    AfdReadRegistry( );

#if DBG
    if( AfdEnableUnload ) {
        KdPrint(( "AFD: DriverUnload enabled\n" ));
        DriverObject->DriverUnload = AfdUnload;
    }
#endif

    //
    // Initialize the lookaside lists.
    //

    AfdLookasideLists = AFD_ALLOCATE_POOL(
                            NonPagedPool,
                            sizeof(*AfdLookasideLists),
                            AFD_LOOKASIDE_LISTS_POOL_TAG
                            );

    if( AfdLookasideLists == NULL ) {
        IoDeleteDevice(AfdDeviceObject);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    // Initialize the work queue item lookaside list.
    //

    ExInitializeNPagedLookasideList(
        &AfdLookasideLists->WorkQueueList,
#if DBG
        AfdAllocateWorkItemPool,
        AfdFreeWorkItemPool,
#else
        NULL,
        NULL,
#endif
        NonPagedPoolMustSucceed,
        sizeof( AFD_WORK_ITEM ),
        AFD_WORK_ITEM_POOL_TAG,
        12
        );

    //
    // Initialize the AFD buffer lookaside lists.  These must be
    // initialized *after* the registry data has been read.
    //

    ExInitializeNPagedLookasideList(
        &AfdLookasideLists->LargeBufferList,
        AfdAllocateBuffer,
#if DBG
        AfdFreeBufferPool,
#else
        NULL,
#endif
        0,
        AfdLargeBufferSize,
        AFD_DATA_BUFFER_POOL_TAG,
        (USHORT)AfdLargeBufferListDepth
        );

    ExInitializeNPagedLookasideList(
        &AfdLookasideLists->MediumBufferList,
        AfdAllocateBuffer,
#if DBG
        AfdFreeBufferPool,
#else
        NULL,
#endif
        0,
        AfdMediumBufferSize,
        AFD_DATA_BUFFER_POOL_TAG,
        (USHORT)AfdMediumBufferListDepth
        );

    ExInitializeNPagedLookasideList(
        &AfdLookasideLists->SmallBufferList,
        AfdAllocateBuffer,
#if DBG
        AfdFreeBufferPool,
#else
        NULL,
#endif
        0,
        AfdSmallBufferSize,
        AFD_DATA_BUFFER_POOL_TAG,
        (USHORT)AfdSmallBufferListDepth
        );

    //
    // Initialize our device object.
    //

    AfdDeviceObject->StackSize = AfdIrpStackSize;

    //
    // Remember a pointer to the system process.  We'll use this pointer
    // for KeAttachProcess() calls so that we can open handles in the
    // context of the system process.
    //

    AfdSystemProcess = (PKPROCESS)IoGetCurrentProcess();

    //
    // Tell MM that it can page all of AFD it is desires.  We will reset
    // to normal paging of AFD code as soon as an AFD endpoint is
    // opened.
    //

    AfdLoaded = FALSE;

    MmPageEntireDriver( DriverEntry );

    return (status);

} // DriverEntry


#if DBG
VOID
AfdUnload (
    IN PDRIVER_OBJECT DriverObject
    )
{

    PLIST_ENTRY listEntry;
    PAFD_TRANSPORT_INFO transportInfo;

    UNREFERENCED_PARAMETER( DriverObject );

    PAGED_CODE( );

    KdPrint(( "AfdUnload called.\n" ));

    //
    // Kill the transport info list.
    //

    while( !IsListEmpty( &AfdTransportInfoListHead ) ) {

        listEntry = RemoveHeadList( &AfdTransportInfoListHead );

        transportInfo = CONTAINING_RECORD(
                            listEntry,
                            AFD_TRANSPORT_INFO,
                            TransportInfoListEntry
                            );

        AFD_FREE_POOL(
            transportInfo,
            AFD_TRANSPORT_INFO_POOL_TAG
            );

    }

    //
    // Kill the resource that protects the executive worker thread queue.
    //

    if( AfdResource != NULL ) {

        ExDeleteResource( AfdResource );

        AFD_FREE_POOL(
            AfdResource,
            AFD_RESOURCE_POOL_TAG
            );

    }

    //
    // Destroy the lookaside lists.
    //

    if( AfdLookasideLists != NULL ) {

        ExDeleteNPagedLookasideList( &AfdLookasideLists->WorkQueueList );
        ExDeleteNPagedLookasideList( &AfdLookasideLists->LargeBufferList );
        ExDeleteNPagedLookasideList( &AfdLookasideLists->MediumBufferList );
        ExDeleteNPagedLookasideList( &AfdLookasideLists->SmallBufferList );

        AFD_FREE_POOL(
            AfdLookasideLists,
            AFD_LOOKASIDE_LISTS_POOL_TAG
            );

    }

    //
    // Terminate the group ID manager.
    //

    AfdTerminateGroup();

    //
    // Delete our device object.
    //

    IoDeleteDevice( AfdDeviceObject );

} // AfdUnload
#endif


VOID
AfdReadRegistry (
    VOID
    )

/*++

Routine Description:

    Reads the AFD section of the registry.  Any values listed in the
    registry override defaults.

Arguments:

    None.

Return Value:

    None -- if anything fails, the default value is used.

--*/
{
    HANDLE parametersHandle;
    NTSTATUS status;
    ULONG stackSize;
    ULONG priorityBoost;
    UNICODE_STRING registryPath;
    CLONG i;

    PAGED_CODE( );

    RtlInitUnicodeString( &registryPath, REGISTRY_AFD_INFORMATION );

    status = AfdOpenRegistry( &registryPath, &parametersHandle );

    if (status != STATUS_SUCCESS) {
        return;
    }

#if DBG
    //
    // Read the debug flags from the registry.
    //

    AfdDebug = AfdReadSingleParameter(
                   parametersHandle,
                   REGISTRY_DEBUG_FLAGS,
                   AfdDebug
                   );

    //
    // Force a breakpoint if so requested.
    //

    if( AfdReadSingleParameter(
            parametersHandle,
            REGISTRY_BREAK_ON_STARTUP,
            0 ) != 0 ) {
        DbgBreakPoint();
    }

    //
    // Enable driver unload if requested.
    //

    AfdEnableUnload = AfdReadSingleParameter(
                          parametersHandle,
                          REGISTRY_ENABLE_UNLOAD,
                          (LONG)AfdEnableUnload
                          ) != 0;

    //
    // Enable private assert function if requested.
    //

    AfdUsePrivateAssert = AfdReadSingleParameter(
                              parametersHandle,
                              REGISTRY_USE_PRIVATE_ASSERT,
                              (LONG)AfdUsePrivateAssert
                              ) != 0;
#endif

#if AFD_PERF_DBG
    //
    // Read a flag from the registry that allows us to disable Fast IO.
    //

    AfdDisableFastIo = AfdReadSingleParameter(
                           parametersHandle,
                           REGISTRY_DISABLE_FAST_IO,
                           (LONG)AfdDisableFastIo
                           ) != 0;

    if( AfdDisableFastIo ) {

        KdPrint(( "AFD: Fast IO disabled\n" ));

    }

    //
    // Read a flag from the registry that allows us to disable connection
    // reuse.
    //

    AfdDisableConnectionReuse = AfdReadSingleParameter(
                                    parametersHandle,
                                    REGISTRY_DISABLE_CONN_REUSE,
                                    (LONG)AfdDisableConnectionReuse
                                    ) != 0;

    if( AfdDisableConnectionReuse ) {

        KdPrint(( "AFD: Connection Reuse disabled\n" ));

    }
#endif

    //
    // Read the stack size and priority boost values from the registry.
    //

    stackSize = AfdReadSingleParameter(
                    parametersHandle,
                    REGISTRY_IRP_STACK_SIZE,
                    (ULONG)AfdIrpStackSize
                    );

    if ( stackSize > 255 ) {
        stackSize = 255;
    }

    AfdIrpStackSize = (CCHAR)stackSize;

    priorityBoost = AfdReadSingleParameter(
                        parametersHandle,
                        REGISTRY_PRIORITY_BOOST,
                        (ULONG)AfdPriorityBoost
                        );

    if ( priorityBoost > 16 ) {
        priorityBoost = AFD_DEFAULT_PRIORITY_BOOST;
    }

    AfdPriorityBoost = (CCHAR)priorityBoost;

    //
    // Read other config variables from the registry.
    //

    for ( i = 0; i < AFD_CONFIG_VAR_COUNT; i++ ) {

        *AfdConfigInfo[i].Variable =
            AfdReadSingleParameter(
                parametersHandle,
                AfdConfigInfo[i].RegistryValueName,
                *AfdConfigInfo[i].Variable
                );
    }

    AfdIgnorePushBitOnReceives = AfdReadSingleParameter(
                                     parametersHandle,
                                     REGISTRY_IGNORE_PUSH_BIT,
                                     (LONG)AfdIgnorePushBitOnReceives
                                     ) != 0;

    AfdDisableRawSecurity = AfdReadSingleParameter(
                                parametersHandle,
                                REGISTRY_NO_RAW_SECURITY,
                                (LONG)AfdDisableRawSecurity
                                ) != 0;

    if( MmIsThisAnNtAsSystem() ) {

        //
        // On the NT Server product, make the maximum active TransmitFile
        // count configurable. This value is fixed (not configurable) on
        // the NT Workstation product.
        //

        AfdMaxActiveTransmitFileCount = AfdReadSingleParameter(
                                            parametersHandle,
                                            REGISTRY_MAX_ACTIVE_TRANSMIT_FILE_COUNT,
                                            (LONG)AfdMaxActiveTransmitFileCount
                                            );

        //
        // Dynamic backlog is only possible on NT Server.
        //

        AfdEnableDynamicBacklog = AfdReadSingleParameter(
                                         parametersHandle,
                                         REGISTRY_ENABLE_DYNAMIC_BACKLOG,
                                         (LONG)AfdEnableDynamicBacklog
                                         ) != 0;

    } else {

        AfdEnableDynamicBacklog = FALSE;

    }

    ZwClose( parametersHandle );

    return;

} // AfdReadRegistry


NTSTATUS
AfdOpenRegistry(
    IN PUNICODE_STRING BaseName,
    OUT PHANDLE ParametersHandle
    )

/*++

Routine Description:

    This routine is called by AFD to open the registry. If the registry
    tree exists, then it opens it and returns an error. If not, it
    creates the appropriate keys in the registry, opens it, and
    returns STATUS_SUCCESS.

Arguments:

    BaseName - Where in the registry to start looking for the information.

    LinkageHandle - Returns the handle used to read linkage information.

    ParametersHandle - Returns the handle used to read other
        parameters.

Return Value:

    The status of the request.

--*/
{

    HANDLE configHandle;
    NTSTATUS status;
    PWSTR parametersString = REGISTRY_PARAMETERS;
    UNICODE_STRING parametersKeyName;
    OBJECT_ATTRIBUTES objectAttributes;
    ULONG disposition;

    PAGED_CODE( );

    //
    // Open the registry for the initial string.
    //

    InitializeObjectAttributes(
        &objectAttributes,
        BaseName,                   // name
        OBJ_CASE_INSENSITIVE,       // attributes
        NULL,                       // root
        NULL                        // security descriptor
        );

    status = ZwCreateKey(
                 &configHandle,
                 KEY_WRITE,
                 &objectAttributes,
                 0,                 // title index
                 NULL,              // class
                 0,                 // create options
                 &disposition       // disposition
                 );

    if (!NT_SUCCESS(status)) {
        return STATUS_UNSUCCESSFUL;
    }

    //
    // Now open the parameters key.
    //

    RtlInitUnicodeString (&parametersKeyName, parametersString);

    InitializeObjectAttributes(
        &objectAttributes,
        &parametersKeyName,         // name
        OBJ_CASE_INSENSITIVE,       // attributes
        configHandle,               // root
        NULL                        // security descriptor
        );

    status = ZwOpenKey(
                 ParametersHandle,
                 KEY_READ,
                 &objectAttributes
                 );
    if (!NT_SUCCESS(status)) {

        ZwClose( configHandle );
        return status;
    }

    //
    // All keys successfully opened or created.
    //

    ZwClose( configHandle );
    return STATUS_SUCCESS;

} // AfdOpenRegistry


ULONG
AfdReadSingleParameter(
    IN HANDLE ParametersHandle,
    IN PWCHAR ValueName,
    IN LONG DefaultValue
    )

/*++

Routine Description:

    This routine is called by AFD to read a single parameter
    from the registry. If the parameter is found it is stored
    in Data.

Arguments:

    ParametersHandle - A pointer to the open registry.

    ValueName - The name of the value to search for.

    DefaultValue - The default value.

Return Value:

    The value to use; will be the default if the value is not
    found or is not in the correct range.

--*/

{
    static ULONG informationBuffer[32];   // declare ULONG to get it aligned
    PKEY_VALUE_FULL_INFORMATION information =
        (PKEY_VALUE_FULL_INFORMATION)informationBuffer;
    UNICODE_STRING valueKeyName;
    ULONG informationLength;
    LONG returnValue;
    NTSTATUS status;

    PAGED_CODE( );

    RtlInitUnicodeString( &valueKeyName, ValueName );

    status = ZwQueryValueKey(
                 ParametersHandle,
                 &valueKeyName,
                 KeyValueFullInformation,
                 (PVOID)information,
                 sizeof (informationBuffer),
                 &informationLength
                 );

    if ((status == STATUS_SUCCESS) && (information->DataLength == sizeof(ULONG))) {

        RtlMoveMemory(
            (PVOID)&returnValue,
            ((PUCHAR)information) + information->DataOffset,
            sizeof(ULONG)
            );

        if (returnValue < 0) {

            returnValue = DefaultValue;

        }

    } else {

        returnValue = DefaultValue;
    }

    return returnValue;

} // AfdReadSingleParameter


NTSTATUS
AfdBuildDeviceAcl(
    OUT PACL *DeviceAcl
    )

/*++

Routine Description:

    This routine builds an ACL which gives Administrators and LocalSystem
    principals full access. All other principals have no access.

Arguments:

    DeviceAcl - Output pointer to the new ACL.

Return Value:

    STATUS_SUCCESS or an appropriate error code.

--*/

{
    PGENERIC_MAPPING GenericMapping;
    PSID AdminsSid;
    PSID SystemSid;
    ULONG AclLength;
    NTSTATUS Status;
    ACCESS_MASK AccessMask = GENERIC_ALL;
    PACL NewAcl;

    //
    // Enable access to all the globally defined SIDs
    //

    GenericMapping = IoGetFileObjectGenericMapping();

    RtlMapGenericMask( &AccessMask, GenericMapping );

    SeEnableAccessToExports();

    AdminsSid = SeExports->SeAliasAdminsSid;
    SystemSid = SeExports->SeLocalSystemSid;

    AclLength = sizeof( ACL )                    +
                2 * sizeof( ACCESS_ALLOWED_ACE ) +
                RtlLengthSid( AdminsSid )         +
                RtlLengthSid( SystemSid )         -
                2 * sizeof( ULONG );

    NewAcl = AFD_ALLOCATE_POOL(
                 PagedPool,
                 AclLength,
                 AFD_SECURITY_POOL_TAG
                 );

    if (NewAcl == NULL) {
        return( STATUS_INSUFFICIENT_RESOURCES );
    }

    Status = RtlCreateAcl (NewAcl, AclLength, ACL_REVISION );

    if (!NT_SUCCESS( Status )) {
        AFD_FREE_POOL(
            NewAcl,
            AFD_SECURITY_POOL_TAG
            );
        return( Status );
    }

    Status = RtlAddAccessAllowedAce (
                 NewAcl,
                 ACL_REVISION2,
                 AccessMask,
                 AdminsSid
                 );

    ASSERT( NT_SUCCESS( Status ));

    Status = RtlAddAccessAllowedAce (
                 NewAcl,
                 ACL_REVISION2,
                 AccessMask,
                 SystemSid
                 );

    ASSERT( NT_SUCCESS( Status ));

    *DeviceAcl = NewAcl;

    return( STATUS_SUCCESS );

} // AfdBuildDeviceAcl


NTSTATUS
AfdCreateRawSecurityDescriptor(
    VOID
    )

/*++

Routine Description:

    This routine creates a security descriptor which gives access
    only to Administrtors and LocalSystem. This descriptor is used
    to access check raw endpoint opens.

Arguments:

    None.

Return Value:

    STATUS_SUCCESS or an appropriate error code.

--*/

{
    PACL                  rawAcl;
    NTSTATUS              status;
    BOOLEAN               memoryAllocated = FALSE;
    PSECURITY_DESCRIPTOR  afdSecurityDescriptor;
    ULONG                 afdSecurityDescriptorLength;
    CHAR                  buffer[SECURITY_DESCRIPTOR_MIN_LENGTH];
    PSECURITY_DESCRIPTOR  localSecurityDescriptor =
                             (PSECURITY_DESCRIPTOR) &buffer;
    SECURITY_INFORMATION  securityInformation = DACL_SECURITY_INFORMATION;


    //
    // Get a pointer to the security descriptor from the AFD device object.
    //
    status = ObGetObjectSecurity(
                 AfdDeviceObject,
                 &afdSecurityDescriptor,
                 &memoryAllocated
                 );

    if (!NT_SUCCESS(status)) {
        KdPrint((
            "AFD: Unable to get security descriptor, error: %x\n",
            status
            ));
        ASSERT(memoryAllocated == FALSE);
        return(status);
    }

    //
    // Build a local security descriptor with an ACL giving only
    // administrators and system access.
    //
    status = AfdBuildDeviceAcl(&rawAcl);

    if (!NT_SUCCESS(status)) {
        KdPrint(("AFD: Unable to create Raw ACL, error: %x\n", status));
        goto error_exit;
    }

    (VOID) RtlCreateSecurityDescriptor(
                localSecurityDescriptor,
                SECURITY_DESCRIPTOR_REVISION
                );

    (VOID) RtlSetDaclSecurityDescriptor(
                localSecurityDescriptor,
                TRUE,
                rawAcl,
                FALSE
                );

    //
    // Make a copy of the AFD descriptor. This copy will be the raw descriptor.
    //
    afdSecurityDescriptorLength = RtlLengthSecurityDescriptor(
                                      afdSecurityDescriptor
                                      );

    AfdRawSecurityDescriptor = AFD_ALLOCATE_POOL(
                                   PagedPool,
                                   afdSecurityDescriptorLength,
                                   AFD_SECURITY_POOL_TAG
                                   );

    if (AfdRawSecurityDescriptor == NULL) {
        KdPrint(("AFD: couldn't allocate security descriptor\n"));
        goto error_exit;
    }

    RtlMoveMemory(
        AfdRawSecurityDescriptor,
        afdSecurityDescriptor,
        afdSecurityDescriptorLength
        );

    //
    // Now apply the local descriptor to the raw descriptor.
    //
    status = SeSetSecurityDescriptorInfo(
                 NULL,
                 &securityInformation,
                 localSecurityDescriptor,
                 &AfdRawSecurityDescriptor,
                 PagedPool,
                 IoGetFileObjectGenericMapping()
                 );

    if (!NT_SUCCESS(status)) {
        KdPrint(("AFD: SeSetSecurity failed, %lx\n", status));
        AFD_FREE_POOL(
            AfdRawSecurityDescriptor,
            AFD_SECURITY_POOL_TAG
            );
        AFD_FREE_POOL(
            rawAcl,
            AFD_SECURITY_POOL_TAG
            );
        AfdRawSecurityDescriptor = NULL;
        goto error_exit;
    }

    status = STATUS_SUCCESS;

error_exit:

    ObReleaseObjectSecurity(
        afdSecurityDescriptor,
        memoryAllocated
        );

    return(status);
}