summaryrefslogblamecommitdiffstats
path: root/private/ntos/npfs/datasup.c
blob: 1adbace32f0305cf46a70fdbc8a10d39cfd4c0bf (plain) (tree)
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




















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                       
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    DataSup.c

Abstract:

    This module implements the Named Pipe data queue support routines.

Author:

    Gary Kimura     [GaryKi]    30-Aug-1990

Revision History:

--*/

#include "NpProcs.h"

//
//  The debug trace level
//

#define Dbg                              (DEBUG_TRACE_DATASUP)

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, NpGetNextRealDataQueueEntry)
#pragma alloc_text(PAGE, NpInitializeDataQueue)
#pragma alloc_text(PAGE, NpUninitializeDataQueue)
#endif

//
//  The following macro is used to dump a data queue
//

#define DumpDataQueue(S,P) {                   \
    ULONG NpDumpDataQueue(IN PDATA_QUEUE Ptr); \
    DebugTrace(0,Dbg,S,0);                     \
    DebugTrace(0,Dbg,"", NpDumpDataQueue(P));  \
}

//
//  This is a debugging aid
//

_inline BOOLEAN
NpfsVerifyDataQueue( IN ULONG Line, IN PDATA_QUEUE DataQueue ) {
    PDATA_ENTRY Entry;
    ULONG BytesInQueue = 0;
    ULONG EntriesInQueue = 0;
    for (Entry = DataQueue->FrontOfQueue; Entry != NULL; Entry = Entry->Next) {
        BytesInQueue += Entry->DataSize;
        EntriesInQueue += 1;
        if (Entry->Next == NULL) {
            if (Entry != DataQueue->EndOfQueue) {
                DbgPrint("%d DataQueue does not end corretly %08lx\n", Line, DataQueue );
                DbgBreakPoint();
            }
        }
    }
    if ((DataQueue->EntriesInQueue != EntriesInQueue) ||
        (DataQueue->BytesInQueue != BytesInQueue)) {
        DbgPrint("%d DataQueue is illformed %08lx %x %x\n", Line, DataQueue, BytesInQueue, EntriesInQueue);
        DbgBreakPoint();
        return FALSE;
    }
    return TRUE;
}


VOID
NpCancelDataQueueIrp (
    IN PDEVICE_OBJECT DevictObject,
    IN PIRP Irp
    );


VOID
NpInitializeDataQueue (
    IN PDATA_QUEUE DataQueue,
    IN PEPROCESS Process,
    IN ULONG Quota
    )

/*++

Routine Description:

    This routine initializes a new data queue.  The indicated quota is taken
    from the process and not returned until the data queue is uninitialized.

Arguments:

    DataQueue - Supplies the data queue being initialized

    Process - Supplies a pointer to the process creating the named pipe

    Quota - Supplies the quota to assign to the data queue

Return Value:

    None.

--*/

{
    PAGED_CODE();

    DebugTrace(+1, Dbg, "NpInitializeDataQueue, DataQueue = %08lx\n", DataQueue);

    //
    //  First thing we do is get the process's quota, if we can't get it
    //  then this call will raise status
    //

    ObReferenceObject( Process );
    PsChargePoolQuota( Process, NonPagedPool, Quota );

    //
    //  Now we can initialize the data queue structure
    //

    DataQueue->QueueState     = Empty;
    DataQueue->BytesInQueue   = 0;
    DataQueue->EntriesInQueue = 0;
    DataQueue->Quota          = Quota;
    DataQueue->QuotaUsed      = 0;
    DataQueue->FrontOfQueue   = NULL;
    DataQueue->EndOfQueue     = NULL;
    DataQueue->NextByteOffset = 0;

    //
    //  And return to our caller
    //

    DebugTrace(-1, Dbg, "NpInitializeDataQueue -> VOID\n", 0);

    return;
}


VOID
NpUninitializeDataQueue (
    IN PDATA_QUEUE DataQueue,
    IN PEPROCESS Process
    )

/*++

Routine Description:

    This routine uninitializes a data queue.  The previously debited quota
    is returned to the process.

Arguments:

    DataQueue - Supplies the data queue being uninitialized

    Process - Supplies a pointer to the process who created the named pipe

Return Value:

    None.

--*/

{
    PAGED_CODE();

    DebugTrace(+1, Dbg, "NpUninitializeDataQueue, DataQueue = %08lx\n", DataQueue);

    //
    //  Assert that the queue is empty
    //

    ASSERT( DataQueue->QueueState == Empty );

    //
    //  Return all of our quota back to the process
    //

    PsReturnPoolQuota( Process, NonPagedPool, DataQueue->Quota );
    ObDereferenceObject( Process );

    //
    //  Then for safety sake we'll zero out the data queue structure
    //

    RtlZeroMemory( DataQueue, sizeof(DATA_QUEUE ) );

    //
    //  And return to our caller
    //

    DebugTrace(-1, Dbg, "NpUnininializeDataQueue -> VOID\n", 0);

    return;
}


PDATA_ENTRY
NpAddDataQueueEntry (
    IN PDATA_QUEUE DataQueue,
    IN QUEUE_STATE Who,
    IN DATA_ENTRY_TYPE Type,
    IN ULONG DataSize,
    IN PIRP Irp OPTIONAL,
    IN PVOID DataPointer OPTIONAL
    )

/*++

Routine Description:

    This routine adds a new data entry to the end of the data queue.
    If necessary it will allocate a data entry buffer, or use space in
    the IRP, and possibly complete the indicated IRP.

    The different actions we are perform are based on the type and who
    parameters and quota requirements.

    Type == Internal (i.e, Unbuffered)

        +------+                          - Allocate Data Entry from Irp
        |Irp   |    +----------+
        |      |<---|Unbuffered|          - Reference Irp
        +------+    |InIrp     |
          |         +----------+          - Use system buffer from Irp
          v           |
        +------+      |
        |System|<-----+
        |Buffer|
        +------+

    Type == Buffered && Who == ReadEntries

        +----------+                      - Allocate Data Entry from Irp
        |Irp       |     +-----------+
        |BufferedIo|<----|Buffered   |    - Allocate New System buffer
        |DeallBu...|     |EitherQuota|
        +----------+     +-----------+    - Reference and modify Irp to
          |      |         |                do Buffered I/O, Deallocate
          v      |         v                buffer, and have io completion
        +------+ +------>+------+           copy the buffer (Input operation)
        |User  |         |System|
        |Buffer|         |Buffer|
        +------+         +------+

    Type == Buffered && Who == WriteEntries && PipeQuota Available

        +----------+                      - Allocate Data Entry from Quota
        |Irp       |     +-----------+
        |          |     |Buffered   |    - Allocate New System buffer
        |          |     |PipeQuota  |
        +----------+     +-----------+    - Copy data from User buffer to
          |                |                system buffer
          v                v
        +------+         +------+         - Complete Irp
        |User  |..copy..>|System|
        |Buffer|         |Buffer|
        +------+         +------+

    Type == Buffered && Who == WriteEntries && PipeQuota Not Available

        +----------+                     - Allocate Data Entry from Irp
        |Irp       |     +-----------+
        |BufferedIo|<----|Buffered   |   - Allocate New System buffer
        |DeallBuff |     |UserQuota  |
        +----------+     +-----------+   - Reference and modify Irp to use
          |      |         |               the new system buffer, do Buffered
          v      |         v               I/O, and Deallocate buffer
        +------+ +------>+------+
        |User  |         |System|        - Copy data from User buffer to
        |Buffer|..copy..>|Buffer|          system buffer
        +------+         +------+

    Type == Flush or Close

        +----------+                     - Allocate Data Entry from Irp
        |Irp       |     +-----------+
        |          |<----|Buffered   |   - Reference the Irp
        |          |     |UserQuota  |
        +----------+     +-----------+

Arguments:

    DataQueue - Supplies the Data queue being modified

    Who - Indicates if this is the reader or writer that is adding to the pipe

    Type - Indicates the type of entry to add to the data queue

    DataSize - Indicates the size of the data buffer needed to represent
        this entry

    Irp - Supplies a pointer to the Irp responsible for this entry
        The irp is only optional for buffered write with available pipe quota

    DataPointer - If the Irp is not supplied then this field points to the
        user's write buffer.

Return Value:

    PDATA_ENTRY - Returns a pointer to the newly added data entry

--*/

{
    PDATA_ENTRY DataEntry;
    PIRP IrpToComplete;

    //
    //  The following array indicates storage that needs to be deallocated
    //  on an abnormal unwind.
    //

    PVOID Unwind[2] = { NULL, NULL };

    ASSERT((DataQueue->QueueState == Empty) || (DataQueue->QueueState == Who));

    DebugTrace(+1, Dbg, "NpAddDataQueueEntry, DataQueue = %08lx\n", DataQueue);

    IrpToComplete = NULL;

    try {

        //
        //  Case on the type of operation we are doing
        //

        switch (Type) {

        case Unbuffered:

            ASSERT(ARGUMENT_PRESENT(Irp));

            //
            //  Allocate a data entry from the Irp
            //

            DataEntry = (PDATA_ENTRY)IoGetNextIrpStackLocation( Irp );

            DataEntry->DataEntryType = Unbuffered;
            DataEntry->From          = InIrp;
            DataEntry->Irp           = Irp;
            DataEntry->DataSize      = DataSize;
            DataEntry->DataPointer   = Irp->AssociatedIrp.SystemBuffer;

            DataEntry->SecurityClientContext = NULL;

            ASSERT((DataQueue->QueueState == Empty) || (DataQueue->QueueState == Who));

            break;

        case Buffered:

            //
            //  Check if this is the reader or writer
            //

            if (Who == ReadEntries) {

                ASSERT(ARGUMENT_PRESENT(Irp));

                //
                //  Allocate a data entry from the Irp, and allocate a new
                //  system buffer
                //

                DataEntry = (PDATA_ENTRY)IoGetNextIrpStackLocation( Irp );

                DataEntry->DataEntryType = Buffered;
                DataEntry->Irp           = Irp;
                DataEntry->DataSize      = DataSize;

                if ((DataQueue->Quota - DataQueue->QuotaUsed) >= DataSize) {

                    DataEntry->DataPointer = Unwind[0] = (DataSize != 0 ? FsRtlAllocatePool( NonPagedPool, DataSize ) : NULL);

                    DataQueue->QuotaUsed += DataSize;

                    DataEntry->From = PipeQuota;

                } else {

                    DataEntry->DataPointer = Unwind[1] = (DataSize != 0 ? FsRtlAllocatePoolWithQuota( NonPagedPool, DataSize ) : NULL);

                    DataEntry->From = UserQuota;
                }

                DataEntry->SecurityClientContext = NULL;

                //
                //  Modify the Irp to be buffered I/O, deallocate the buffer, copy
                //  the buffer on completion, and to reference the new system
                //  buffer
                //

                if (DataSize != 0) {

                    Irp->Flags |= IRP_BUFFERED_IO | IRP_DEALLOCATE_BUFFER | IRP_INPUT_OPERATION;
                    Irp->AssociatedIrp.SystemBuffer = DataEntry->DataPointer;
                }

                ASSERT((DataQueue->QueueState == Empty) || (DataQueue->QueueState == Who));

            } else {

                //
                //  This is a writer entry
                //

                //
                //  If there is enough quota left in the pipe then we will
                //  allocate the data entry and data buffer from the pipe quota
                //

                if ((DataQueue->Quota - DataQueue->QuotaUsed) >= sizeof(DATA_ENTRY) + DataSize) {

                    DataEntry = Unwind[0] = FsRtlAllocatePool( NonPagedPool, sizeof(DATA_ENTRY) );

                    DataEntry->DataPointer = Unwind[1] = (DataSize != 0 ? FsRtlAllocatePool( NonPagedPool, DataSize ) : NULL);

                    DataQueue->QuotaUsed += sizeof(DATA_ENTRY) + DataSize;

                    DataEntry->DataEntryType = Buffered;
                    DataEntry->From          = PipeQuota;
                    DataEntry->Irp           = NULL;
                    DataEntry->DataSize      = DataSize;

                    DataEntry->SecurityClientContext = NULL;

                    //
                    //  Safely copy the user buffer to the new system buffer using either
                    //  the irp user buffer is supplied of the data pointer we were given
                    //

                    if (ARGUMENT_PRESENT(Irp)) { DataPointer = Irp->UserBuffer; }

                    try {

                        RtlCopyMemory( DataEntry->DataPointer, DataPointer, DataSize );

                    } except(EXCEPTION_EXECUTE_HANDLER) {

                        ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
                    }

                    IrpToComplete = Irp;

                    ASSERT((DataQueue->QueueState == Empty) || (DataQueue->QueueState == Who));

                } else {

                    ASSERT(ARGUMENT_PRESENT(Irp));

                    //
                    //  There isn't enough pipe quota to do this so we will
                    //  use the user quota
                    //
                    //  Allocate a data entry from the Irp, and allocate a new
                    //  system buffer
                    //

                    DataEntry = (PDATA_ENTRY)IoGetNextIrpStackLocation( Irp );

                    DataEntry->DataEntryType = Buffered;
                    DataEntry->From          = UserQuota;
                    DataEntry->Irp           = Irp;
                    DataEntry->DataSize      = DataSize;

                    DataEntry->SecurityClientContext = NULL;

                    DataEntry->DataPointer = Unwind[0] = (DataSize != 0 ? FsRtlAllocatePoolWithQuota( NonPagedPool, DataSize ) : NULL);

                    //
                    //  Safely copy the user buffer to the new system buffer
                    //

                    try {

                        RtlCopyMemory( DataEntry->DataPointer, Irp->UserBuffer, DataSize );

                    } except(EXCEPTION_EXECUTE_HANDLER) {

                        ExRaiseStatus( STATUS_INVALID_USER_BUFFER );
                    }

                    //
                    //  Modify the Irp to be buffered I/O, deallocate the buffer
                    //  and to reference the new system buffer
                    //

                    if (DataSize != 0) {

                        Irp->Flags |= IRP_BUFFERED_IO | IRP_DEALLOCATE_BUFFER;
                        Irp->AssociatedIrp.SystemBuffer = DataEntry->DataPointer;
                    }

                    ASSERT((DataQueue->QueueState == Empty) || (DataQueue->QueueState == Who));
                }
            }

            break;

        case Flush:
        case Close:

            ASSERT(ARGUMENT_PRESENT(Irp));

            //
            //  Allocate a data entry from the Irp
            //

            DataEntry = (PDATA_ENTRY)IoGetNextIrpStackLocation( Irp );

            DataEntry->DataEntryType = Type;
            DataEntry->From          = InIrp;
            DataEntry->Irp           = Irp;
            DataEntry->DataSize      = 0;
            DataEntry->DataPointer   = NULL;

            DataEntry->SecurityClientContext = NULL;

            ASSERT((DataQueue->QueueState == Empty) || (DataQueue->QueueState == Who));

            break;
        }

        ASSERT((DataQueue->QueueState == Empty) || (DataQueue->QueueState == Who));

        //
        //  Now data entry points to a new data entry to add to the data queue
        //  Check if the queue is empty otherwise we will add this entry to
        //  the end of the queue
        //

        DataEntry->Next = NULL;

        if (DataQueue->QueueState == Empty) {

            DataQueue->QueueState     = Who;
            DataQueue->BytesInQueue   = DataEntry->DataSize;
            DataQueue->EntriesInQueue = 1;
            DataQueue->FrontOfQueue   = DataEntry;
            DataQueue->EndOfQueue     = DataEntry;

        } else {

            ASSERT( DataQueue->QueueState == Who );

            DataQueue->BytesInQueue     += DataEntry->DataSize;
            DataQueue->EntriesInQueue   += 1;
            DataQueue->EndOfQueue->Next  = DataEntry;

            DataQueue->EndOfQueue        = DataEntry;
        }

    } finally {

        //
        //  If this is an abnormal termination then deallocate any storage
        //  that we may have allocated
        //

        if (AbnormalTermination()) {

            if (Unwind[0] != NULL) { ExFreePool( Unwind[0] ); }
            if (Unwind[1] != NULL) { ExFreePool( Unwind[1] ); }

        } else {

            if (IrpToComplete != NULL) {

                NpCompleteRequest( IrpToComplete, STATUS_SUCCESS );

            } else if (ARGUMENT_PRESENT(Irp)) {

                IoAcquireCancelSpinLock( &Irp->CancelIrql );
                Irp->IoStatus.Status = (ULONG)DataQueue;

                if (Irp->Cancel) {

                    //
                    //  Indicate in the first parameter that we're calling the
                    //  cancel routine and not the I/O system.  Therefore
                    //  the routine won't take out the VCB exclusive.
                    //

                    NpCancelDataQueueIrp( ((PVOID)0x1), Irp );

                } else {

                    IoSetCancelRoutine( Irp, NpCancelDataQueueIrp );
                    IoReleaseCancelSpinLock( Irp->CancelIrql );
                }
            }
        }

        DumpDataQueue( "After AddDataQueueEntry\n", DataQueue );
        DebugTrace(-1, Dbg, "NpAddDataQueueEntry -> %08lx\n", DataEntry);
    }

    //
    //  And return to our caller
    //

    return DataEntry;
}


PIRP
NpRemoveDataQueueEntry (
    IN PDATA_QUEUE DataQueue
    )

/*++

Routine Description:

    This routines remove the first entry from the front of the indicated
    data queue, and possibly returns the Irp associated with the entry if
    it wasn't already completed when we did the insert.

    If the data entry we are removing indicates buffered I/O then we also
    need to deallocate the data buffer besides the data entry but only
    if the Irp is null.  Note that the data entry might be stored in an IRP.
    If it is then we are going to return the IRP it is stored in.

Arguments:

    DataQueue - Supplies a pointer to the data queue being modifed

Return Value:

    PIRP - Possibly returns a pointer to an IRP.

--*/

{
    PDATA_ENTRY DataEntry;

    DATA_ENTRY_TYPE DataEntryType;
    FROM From;
    PIRP Irp;
    ULONG DataSize;
    PVOID DataPointer;
    PSECURITY_CLIENT_CONTEXT ClientContext;

    DebugTrace(+1, Dbg, "NpRemoveDataQueueEntry, DataQueue = %08lx\n", DataQueue);

    //
    //  Check if the queue is empty, and if so then we simply return null
    //

    if (DataQueue->QueueState == Empty) {

        Irp = NULL;

    } else {

        //
        //  Reference the front of the data queue, and remove the entry
        //  from the queue itself.
        //

        DataEntry                  = DataQueue->FrontOfQueue;
        DataQueue->FrontOfQueue    = DataEntry->Next;
        DataQueue->BytesInQueue   -= DataEntry->DataSize;
        DataQueue->EntriesInQueue -= 1;

        //
        //  Now if the queue is empty we need to reset the end of queue and
        //  queue state
        //

        if (DataQueue->FrontOfQueue == NULL) {

            DataQueue->EndOfQueue = NULL;
            DataQueue->QueueState = Empty;
        }

        //
        //  Capture some of the fields from the data entry to make our
        //  other references a little easier
        //

        DataEntryType = DataEntry->DataEntryType;
        From          = DataEntry->From;
        Irp           = DataEntry->Irp;
        DataSize      = DataEntry->DataSize;
        DataPointer   = DataEntry->DataPointer;
        ClientContext = DataEntry->SecurityClientContext;

        //
        //  Check if we should delete the client context
        //

        if (ClientContext != NULL) {

            SeDeleteClientSecurity( ClientContext );
            ExFreePool( ClientContext );
        }

        //
        //  Check if we need to deallocate the data buffer, we only need
        //  to deallocate it if it is buffered and the Irp is null
        //

        if (DataEntryType == Buffered) {

            if ((Irp == NULL) && (DataPointer != NULL)) {

                ExFreePool( DataPointer );
            }

            //
            //  Now the preceding call returned the user's quota or it
            //  simply deallocated the buffer.  If it only deallocated
            //  the buffer then we need to credit our quota
            //

            if (From == PipeQuota) {

                DataQueue->QuotaUsed -= DataSize;
            }
        }

        //
        //  Now check if we still have an IRP to return.  If we do then
        //  we know that this data entry is located in the current IRP
        //  stack location and we need to zero out the data entry (skipping
        //  over the spare field), otherwise we got allocated from either
        //  the pipe or user quota, and we need to deallocate it ourselves.
        //
        //  Note that we'll keep the data entry type field intact so that
        //  out caller will know if this is an internal read operation.
        //

        if (Irp != NULL) {

            DataEntry->From        = 0;
            DataEntry->Next        = 0;
            DataEntry->Irp         = 0;
            DataEntry->DataSize    = 0;
            DataEntry->DataPointer = 0;

            DataEntry->SecurityClientContext = NULL;

            IoAcquireCancelSpinLock( &Irp->CancelIrql );
            IoSetCancelRoutine( Irp, NULL );
            IoReleaseCancelSpinLock( Irp->CancelIrql );

        } else {

            if (DataPointer != NULL) {

                ExFreePool( DataEntry );
            }

            //
            //  Now the preceding call returned the user's quota or it
            //  simply deallocated the buffer.  If it only deallocated
            //  the buffer then we need to credit our quota
            //

            if (From == PipeQuota) {

                DataQueue->QuotaUsed -= sizeof(DATA_ENTRY);
            }
        }
    }

    //
    //  In all cases we'll also zero out the next byte offset.
    //

    DataQueue->NextByteOffset = 0;

    //
    //  And return to our caller
    //

    DumpDataQueue( "After RemoveDataQueueEntry\n", DataQueue );
    DebugTrace(-1, Dbg, "NpRemoveDataQueueEntry -> %08lx\n", Irp);

    return Irp;
}


PDATA_ENTRY
NpGetNextRealDataQueueEntry (
    IN PDATA_QUEUE DataQueue
    )

/*++

Routine Description:

    This routine will returns a pointer to the next real data queue entry
    in the indicated data queue.  A real entry is either a read or write
    entry (i.e., buffered or unbuffered).  It will complete (as necessary)
    any flush and close Irps that are in the queue until either the queue
    is empty or a real data queue entry is at the front of the queue.

Arguments:

    DataQueue - Supplies a pointer to the data queue being modified

Return Value:

    PDATA_ENTRY - Returns a pointer to the next data queue entry or NULL
        if there isn't any.

--*/

{
    PDATA_ENTRY DataEntry;
    PIRP Irp;

    PAGED_CODE();

    DebugTrace(+1, Dbg, "NpGetNextRealDataQueueEntry, DataQueue = %08lx\n", DataQueue);

    //
    //  While the next data queue entry at the head of the data queue is not
    //  a real data queue entry we'll dequeue that entry and complete
    //  its corresponding IRP.
    //

    for (DataEntry = NpGetNextDataQueueEntry( DataQueue, NULL);

         (DataEntry != NULL) &&
         ((DataEntry->DataEntryType != Buffered) &&
          (DataEntry->DataEntryType != Unbuffered));

         DataEntry = NpGetNextDataQueueEntry( DataQueue, NULL)) {

        //
        //  We have a non real data queue entry that needs to be removed
        //  and completed.
        //

        Irp = NpRemoveDataQueueEntry( DataQueue );

        if (Irp != NULL) {

            NpCompleteRequest( Irp, STATUS_SUCCESS );
        }
    }

    //
    //  At this point we either have an empty data queue and data entry is
    //  null, or we have a real data queue entry.  In either case it
    //  is time to return to our caller
    //

    DebugTrace(-1, Dbg, "NpGetNextRealDataQueueEntry -> %08lx\n", DataEntry);

    return DataEntry;
}


//
//  Local support routine
//

VOID
NpCancelDataQueueIrp (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp
    )

/*++

Routine Description:

    This routine implements the cancel function for an IRP saved in a
    data queue

Arguments:

    DeviceObject - Generally ignored but the low order bit is a flag indicating
        if we are being called locally (i.e., not from the I/O system) and
        therefore don't need to take out the VCB.

    Irp - Supplies the Irp being cancelled.  A pointer to the data queue
        structure is stored in the information field of the Irp Iosb
        field.

Return Value:

    None.

--*/

{
    PDATA_QUEUE DataQueue;

    PDATA_ENTRY DataEntry;
    PDATA_ENTRY *Previous;

    //
    //  The status field is used to store a pointer to the data queue
    //  containing this irp
    //

    DataQueue = (PDATA_QUEUE)Irp->IoStatus.Status;

    //
    //  We now need to void the cancel routine and release the io cancel spinlock
    //

    IoSetCancelRoutine( Irp, NULL );
    IoReleaseCancelSpinLock( Irp->CancelIrql );

    //
    //  Get exclusive access to the named pipe vcb so we can now do our work
    //  but only if we need to
    //

    if (DeviceObject != (PVOID)0x1) { NpAcquireExclusiveVcb(); }

    try {

        //
        //  Scan through the data queue looking for entries that have Irps
        //  that have been cancelled.  We use previous to point to the pointer to
        //  the data entry we're examining.  We cannot do this in a for loop
        //  because we'll have a tough time setting up ourselves for another iteration
        //  when we remove an entry
        //

        Previous = &DataQueue->FrontOfQueue;
        DataEntry = *Previous;

        while (DataEntry != NULL) {

            //
            //  If the data entry contains an Irp and the irp is cancelled then
            //  we have some work do to
            //

            if ((DataEntry->Irp != NULL) && (DataEntry->Irp->Cancel)) {

                DATA_ENTRY_TYPE DataEntryType;
                FROM From;
                PIRP Irp;
                ULONG DataSize;
                PVOID DataPointer;
                PSECURITY_CLIENT_CONTEXT ClientContext;

                //
                //  First remove this data entry from the queue
                //  Later we will fixup Data entry to the next entry
                //

                *Previous = DataEntry->Next;

                //
                //  If the queue is now empty then we need to fix the queue
                //  state and end of queue pointer
                //

                if (DataQueue->FrontOfQueue == NULL) {

                    DataQueue->EndOfQueue = NULL;
                    DataQueue->QueueState = Empty;

                //
                //  If we removed the last entry in the list then we need to update
                //  the end of the queue
                //

                } else if (DataEntry == DataQueue->EndOfQueue) {

                    DataQueue->EndOfQueue = (PDATA_ENTRY)Previous;
                }

                //
                //  Capture some of the fields from the data entry to make our
                //  other references a little easier
                //

                DataEntryType = DataEntry->DataEntryType;
                From          = DataEntry->From;
                Irp           = DataEntry->Irp;
                DataSize      = DataEntry->DataSize;
                DataPointer   = DataEntry->DataPointer;
                ClientContext = DataEntry->SecurityClientContext;

                //
                //  Check if we should delete the client context
                //

                if (ClientContext != NULL) {

                    SeDeleteClientSecurity( ClientContext );
                    ExFreePool( ClientContext );
                }

                //
                //  Check if we need to return pipe quota for a buffered entry.
                //

                if ((DataEntryType == Buffered) && (From == PipeQuota)) {

                    DataQueue->QuotaUsed -= DataSize;
                }

                //
                //  Update the data queue header information
                //

                DataQueue->BytesInQueue   -= DataSize;
                DataQueue->EntriesInQueue -= 1;

                //
                //  Zero our the data entry
                //

                DataEntry->From        = 0;
                DataEntry->Next        = 0;
                DataEntry->Irp         = 0;
                DataEntry->DataSize    = 0;
                DataEntry->DataPointer = 0;

                DataEntry->SecurityClientContext = NULL;

                //
                //  If what we removed is in the front of the queue then we must
                //  reset the next byte offset
                //

                if (Previous == &DataQueue->FrontOfQueue) {

                    DataQueue->NextByteOffset = 0;
                }

                //
                //  Finally complete the request saying that it has been cancelled.
                //

                NpCompleteRequest( Irp, STATUS_CANCELLED );

                //
                //  And because the data entry is gone we now need to reset
                //  it so we can continue our while loop
                //

                DataEntry = *Previous;

            } else {

                //
                //  Skip over to the next data entry
                //

                Previous = &DataEntry->Next;
                DataEntry = DataEntry->Next;
            }
        }

    } finally {

        if (DeviceObject != (PVOID)0x1) { NpReleaseVcb(); }
    }

    //
    //  And return to our caller
    //

    return;
}