summaryrefslogtreecommitdiffstats
path: root/private/ntos/afd/receive.c
blob: 83e9184308d49193836162da9cd5f6a635f6da1a (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
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
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    receive.c

Abstract:

    This module contains the code for passing on receive IRPs to
    TDI providers.

Author:

    David Treadwell (davidtr)    13-Mar-1992

Revision History:

--*/

#include "afdp.h"

NTSTATUS
AfdRestartReceive (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text( PAGEAFD, AfdReceive )
#pragma alloc_text( PAGEAFD, AfdRestartReceive )
#pragma alloc_text( PAGEAFD, AfdReceiveEventHandler )
#pragma alloc_text( PAGEAFD, AfdReceiveExpeditedEventHandler )
#pragma alloc_text( PAGEAFD, AfdQueryReceiveInformation )
#endif


NTSTATUS
AfdReceive (
    IN PIRP Irp,
    IN PIO_STACK_LOCATION IrpSp
    )
{
    NTSTATUS status;
    KIRQL oldIrql;
    PAFD_ENDPOINT endpoint;
    PAFD_CONNECTION connection;
    PTDI_REQUEST_RECEIVE receiveRequest;
    BOOLEAN allocatedReceiveRequest = FALSE;
    BOOLEAN peek;
    LARGE_INTEGER bytesExpected;
    BOOLEAN isDataOnConnection;
    BOOLEAN isExpeditedDataOnConnection;
    PAFD_RECV_INFO recvInfo;
    ULONG recvFlags;
    ULONG afdFlags;
    ULONG recvLength;

    //
    // Make sure that the endpoint is in the correct state.
    //

    endpoint = IrpSp->FileObject->FsContext;
    ASSERT( IS_AFD_ENDPOINT_TYPE( endpoint ) );

    if ( endpoint->State != AfdEndpointStateConnected ) {
        status = STATUS_INVALID_CONNECTION;
        goto complete;
    }

    //
    // If receive has been shut down or the endpoint aborted, fail.
    //

    if ( (endpoint->DisconnectMode & AFD_PARTIAL_DISCONNECT_RECEIVE) ) {
        status = STATUS_PIPE_DISCONNECTED;
        goto complete;
    }

    if ( (endpoint->DisconnectMode & AFD_ABORTIVE_DISCONNECT) ) {
        status = STATUS_LOCAL_DISCONNECT;
        goto complete;
    }

    //
    // If this is an IOCTL_AFD_RECEIVE, then grab the parameters from the
    // supplied AFD_RECV_INFO structure, build an MDL chain describing
    // the WSABUF array, and attach the MDL chain to the IRP.
    //
    // If this is an IRP_MJ_READ IRP, just grab the length from the IRP
    // and set the flags to zero.
    //

    if ( IrpSp->MajorFunction == IRP_MJ_DEVICE_CONTROL ) {

        //
        // Sanity check.
        //

        ASSERT( IrpSp->Parameters.DeviceIoControl.IoControlCode ==
                    IOCTL_AFD_RECEIVE );

        if ( IrpSp->Parameters.DeviceIoControl.InputBufferLength >=
                sizeof(*recvInfo) ) {

            try {

                //
                // Probe the input structure.
                //

                recvInfo = IrpSp->Parameters.DeviceIoControl.Type3InputBuffer;

                if( Irp->RequestorMode != KernelMode ) {

                    ProbeForRead(
                        recvInfo,
                        sizeof(*recvInfo),
                        sizeof(ULONG)
                        );

                }

                //
                // Snag the receive flags.
                //

                recvFlags = recvInfo->TdiFlags;
                afdFlags = recvInfo->AfdFlags;

                //
                // Validate the receive flags & WSABUF parameters.
                // Note that either TDI_RECEIVE_NORMAL or
                // TDI_RECEIVE_EXPEDITED (but not both) must be set
                // in the receive flags.
                //

                if ( ( recvFlags & TDI_RECEIVE_EITHER ) != 0 &&
                     ( recvFlags & TDI_RECEIVE_EITHER ) != TDI_RECEIVE_EITHER &&
                     recvInfo->BufferArray != NULL &&
                     recvInfo->BufferCount > 0 ) {

                    //
                    // Create the MDL chain describing the WSABUF array.
                    //

                    status = AfdAllocateMdlChain(
                                 Irp,
                                 recvInfo->BufferArray,
                                 recvInfo->BufferCount,
                                 IoWriteAccess,
                                 &recvLength
                                 );

                } else {

                    //
                    // Invalid receive flags, BufferArray, or
                    // BufferCount fields.
                    //

                    status = STATUS_INVALID_PARAMETER;

                }

            } except ( EXCEPTION_EXECUTE_HANDLER ) {

                //
                // Exception accessing input structure.
                //

                status = GetExceptionCode();

            }

        } else {

            //
            // Invalid input buffer length.
            //

            status = STATUS_INVALID_PARAMETER;

        }

        if( !NT_SUCCESS(status) ) {

            goto complete;

        }

    } else {

        ASSERT( IrpSp->MajorFunction == IRP_MJ_READ );

        recvFlags = TDI_RECEIVE_NORMAL;
        afdFlags = AFD_OVERLAPPED;
        recvLength = IrpSp->Parameters.Read.Length;

        //
        // Convert this stack location to a proper one for a receive
        // request.
        //

        IrpSp->Parameters.DeviceIoControl.OutputBufferLength =
            IrpSp->Parameters.Read.Length;
        IrpSp->Parameters.DeviceIoControl.InputBufferLength =
            sizeof(*receiveRequest);

    }

    //
    // If this is a datagram endpoint, format up a receive datagram request
    // and pass it on to the TDI provider.
    //

    if ( IS_DGRAM_ENDPOINT(endpoint) ) {
        return AfdReceiveDatagram( Irp, IrpSp, recvFlags, afdFlags );
    }

    //
    // If this is an endpoint on a nonbufferring transport, use another
    // routine to handle the request.
    //

    if ( !endpoint->TdiBufferring ) {
        return AfdBReceive( Irp, IrpSp, recvFlags, afdFlags, recvLength );
    }

    //
    // Allocate a buffer for the receive request structure.
    //

    receiveRequest = AFD_ALLOCATE_POOL(
                         NonPagedPool,
                         sizeof(TDI_REQUEST_RECEIVE),
                         AFD_TDI_POOL_TAG
                         );

    if ( receiveRequest == NULL ) {
        status = STATUS_INSUFFICIENT_RESOURCES;
        goto complete;
    }

    allocatedReceiveRequest = TRUE;

    //
    // Set up the receive request structure.
    //

    RtlZeroMemory(
        receiveRequest,
        sizeof(*receiveRequest)
        );

    receiveRequest->ReceiveFlags = (USHORT)recvFlags;

    connection = endpoint->Common.VcConnecting.Connection;
    ASSERT( connection != NULL );
    ASSERT( connection->Type == AfdBlockTypeConnection );

    //
    // If this endpoint is set up for inline reception of expedited data,
    // change the receive flags to use either normal or expedited data.
    //

    if ( endpoint->InLine ) {
        receiveRequest->ReceiveFlags |= TDI_RECEIVE_EITHER;
    }

    //
    // Determine whether this is a request to just peek at the data.
    //

    peek = (BOOLEAN)( (receiveRequest->ReceiveFlags & TDI_RECEIVE_PEEK) != 0 );

    AfdAcquireSpinLock( &AfdSpinLock, &oldIrql );

    if ( endpoint->NonBlocking ) {
        isDataOnConnection = IS_DATA_ON_CONNECTION( connection );
        isExpeditedDataOnConnection = IS_EXPEDITED_DATA_ON_CONNECTION( connection );
    }

    if ( endpoint->InLine ) {

        //
        // If the endpoint is nonblocking, check whether the receive can
        // be performed immediately.  Note that if the endpoint is set
        // up for inline reception of expedited data we don't fail just
        // yet--there may be expedited data available to be read.
        //

        if ( endpoint->NonBlocking && !( afdFlags & AFD_OVERLAPPED ) ) {

            if ( !isDataOnConnection &&
                     !isExpeditedDataOnConnection &&
                     !connection->AbortIndicated &&
                     !connection->DisconnectIndicated ) {

                IF_DEBUG(RECEIVE) {
                    KdPrint(( "AfdReceive: failing nonblocking IL receive, ind %ld, "
                              "taken %ld, out %ld\n",
                                  connection->Common.Bufferring.ReceiveBytesIndicated.LowPart,
                                  connection->Common.Bufferring.ReceiveBytesTaken.LowPart,
                                  connection->Common.Bufferring.ReceiveBytesOutstanding.LowPart ));
                    KdPrint(( "    EXP ind %ld, taken %ld, out %ld\n",
                                  connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.LowPart,
                                  connection->Common.Bufferring.ReceiveExpeditedBytesTaken.LowPart,
                                  connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.LowPart ));
                }

                AfdReleaseSpinLock( &AfdSpinLock, oldIrql );

                status = STATUS_DEVICE_NOT_READY;
                goto complete;
            }
        }

        //
        // If this is a nonblocking endpoint for a message-oriented
        // transport, limit the number of bytes that can be received to the
        // amount that has been indicated.  This prevents the receive
        // from blocking in the case where only part of a message has been
        // received.
        //

        if ( endpoint->EndpointType != AfdEndpointTypeStream &&
                 endpoint->NonBlocking ) {

            LARGE_INTEGER expBytesExpected;

            bytesExpected.QuadPart =
                connection->Common.Bufferring.ReceiveBytesIndicated.QuadPart -
                    (connection->Common.Bufferring.ReceiveBytesTaken.QuadPart +
                     connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart);
            ASSERT( bytesExpected.HighPart == 0 );

            expBytesExpected.QuadPart =
                connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.QuadPart -
                    (connection->Common.Bufferring.ReceiveExpeditedBytesTaken.QuadPart +
                     connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart);
            ASSERT( expBytesExpected.HighPart == 0 );

            IF_DEBUG(RECEIVE) {
                KdPrint(( "AfdReceive: %lx normal bytes expected, %ld exp bytes expected",
                              bytesExpected.LowPart, expBytesExpected.LowPart ));
            }

            //
            // If expedited data exists on the connection, use the lower
            // count between the available expedited and normal receive
            // data.
            //

            if ( (isExpeditedDataOnConnection &&
                     bytesExpected.LowPart > expBytesExpected.LowPart) ||
                 !isDataOnConnection ) {
                bytesExpected = expBytesExpected;
            }

            //
            // If the request is for more bytes than are available, cut back
            // the number of bytes requested to what we know is actually
            // available.
            //

            if ( recvLength > bytesExpected.LowPart ) {
                recvLength = bytesExpected.LowPart;
            }
        }

        //
        // Increment the count of posted receive bytes outstanding.
        // This count is used for polling and nonblocking receives.
        // Note that we do not increment this count if this is only
        // a PEEK receive, since peeks do not actually take any data
        // they should not affect whether data is available to be read
        // on the endpoint.
        //

        IF_DEBUG(RECEIVE) {
            KdPrint(( "AfdReceive: conn %lx for %ld bytes, ind %ld, "
                      "taken %ld, out %ld %s\n",
                         connection,
                         recvLength,
                         connection->Common.Bufferring.ReceiveBytesIndicated.LowPart,
                         connection->Common.Bufferring.ReceiveBytesTaken.LowPart,
                         connection->Common.Bufferring.ReceiveBytesOutstanding.LowPart,
                         peek ? "PEEK" : "" ));
            KdPrint(( "    EXP ind %ld, taken %ld, out %ld\n",
                         connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.LowPart,
                         connection->Common.Bufferring.ReceiveExpeditedBytesTaken.LowPart,
                         connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.LowPart ));
        }

        if ( !peek ) {

            connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart =
                connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart +
                    recvLength;

            connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart =
                connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart +
                    recvLength;
        }
    }

    if ( !endpoint->InLine &&
             (receiveRequest->ReceiveFlags & TDI_RECEIVE_NORMAL) != 0 ) {

        //
        // If the endpoint is nonblocking, check whether the receive can
        // be performed immediately.
        //

        if ( endpoint->NonBlocking && !( afdFlags & AFD_OVERLAPPED ) ) {

            if ( !isDataOnConnection &&
                     !connection->AbortIndicated &&
                     !connection->DisconnectIndicated ) {

                IF_DEBUG(RECEIVE) {
                    KdPrint(( "AfdReceive: failing nonblocking receive, ind %ld, "
                              "taken %ld, out %ld\n",
                                  connection->Common.Bufferring.ReceiveBytesIndicated.LowPart,
                                  connection->Common.Bufferring.ReceiveBytesTaken.LowPart,
                                  connection->Common.Bufferring.ReceiveBytesOutstanding.LowPart ));
                }

                AfdReleaseSpinLock( &AfdSpinLock, oldIrql );

                status = STATUS_DEVICE_NOT_READY;
                goto complete;
            }
        }

        //
        // If this is a nonblocking endpoint for a message-oriented
        // transport, limit the number of bytes that can be received to the
        // amount that has been indicated.  This prevents the receive
        // from blocking in the case where only part of a message has been
        // received.
        //

        if ( endpoint->EndpointType != AfdEndpointTypeStream &&
                 endpoint->NonBlocking ) {

            bytesExpected.QuadPart =
                connection->Common.Bufferring.ReceiveBytesIndicated.QuadPart -
                    (connection->Common.Bufferring.ReceiveBytesTaken.QuadPart +
                     connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart);

            ASSERT( bytesExpected.HighPart == 0 );

            //
            // If the request is for more bytes than are available, cut back
            // the number of bytes requested to what we know is actually
            // available.
            //

            if ( recvLength > bytesExpected.LowPart ) {
                recvLength = bytesExpected.LowPart;
            }
        }

        //
        // Increment the count of posted receive bytes outstanding.
        // This count is used for polling and nonblocking receives.
        // Note that we do not increment this count if this is only
        // a PEEK receive, since peeks do not actually take any data
        // they should not affect whether data is available to be read
        // on the endpoint.
        //

        IF_DEBUG(RECEIVE) {
            KdPrint(( "AfdReceive: conn %lx for %ld bytes, ind %ld, "
                      "taken %ld, out %ld %s\n",
                         connection,
                         recvLength,
                         connection->Common.Bufferring.ReceiveBytesIndicated.LowPart,
                         connection->Common.Bufferring.ReceiveBytesTaken.LowPart,
                         connection->Common.Bufferring.ReceiveBytesOutstanding.LowPart,
                         peek ? "PEEK" : "" ));
        }

        if ( !peek ) {

            connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart =
                connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart +
                    recvLength;
        }
    }

    if ( !endpoint->InLine &&
             (receiveRequest->ReceiveFlags & TDI_RECEIVE_EXPEDITED) != 0 ) {

        if ( endpoint->NonBlocking && !( afdFlags & AFD_OVERLAPPED ) &&
                 !isExpeditedDataOnConnection &&
                 !connection->AbortIndicated &&
                 !connection->DisconnectIndicated ) {

            IF_DEBUG(RECEIVE) {
                KdPrint(( "AfdReceive: failing nonblocking EXP receive, ind %ld, "
                          "taken %ld, out %ld\n",
                              connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.LowPart,
                              connection->Common.Bufferring.ReceiveExpeditedBytesTaken.LowPart,
                              connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.LowPart ));
            }

            AfdReleaseSpinLock( &AfdSpinLock, oldIrql );

            status = STATUS_DEVICE_NOT_READY;
            goto complete;
        }

        //
        // If this is a nonblocking endpoint for a message-oriented
        // transport, limit the number of bytes that can be received to the
        // amount that has been indicated.  This prevents the receive
        // from blocking in the case where only part of a message has been
        // received.
        //

        if ( endpoint->EndpointType != AfdEndpointTypeStream &&
                 endpoint->NonBlocking &&
                 IS_EXPEDITED_DATA_ON_CONNECTION( connection ) ) {

            bytesExpected.QuadPart =
                connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.QuadPart -
                    (connection->Common.Bufferring.ReceiveExpeditedBytesTaken.QuadPart +
                     connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart);

            ASSERT( bytesExpected.HighPart == 0 );
            ASSERT( bytesExpected.LowPart != 0 );

            //
            // If the request is for more bytes than are available, cut back
            // the number of bytes requested to what we know is actually
            // available.
            //

            if ( recvLength > bytesExpected.LowPart ) {
                recvLength = bytesExpected.LowPart;
            }
        }

        //
        // Increment the count of posted expedited receive bytes
        // outstanding.  This count is used for polling and nonblocking
        // receives.  Note that we do not increment this count if this
        // is only a PEEK receive.
        //

        IF_DEBUG(RECEIVE) {
            KdPrint(( "AfdReceive: conn %lx for %ld bytes, ind %ld, "
                      "taken %ld, out %ld EXP %s\n",
                         connection,
                         recvLength,
                         connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.LowPart,
                         connection->Common.Bufferring.ReceiveExpeditedBytesTaken.LowPart,
                         connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.LowPart,
                         peek ? "PEEK" : "" ));
        }

        if ( !peek ) {

            connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart =
                connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart +
                    recvLength;
        }
    }

    AfdReleaseSpinLock( &AfdSpinLock, oldIrql );

    //
    // Build the TDI receive request.
    //

    TdiBuildReceive(
        Irp,
        connection->DeviceObject,
        connection->FileObject,
        AfdRestartReceive,
        endpoint,
        Irp->MdlAddress,
        receiveRequest->ReceiveFlags,
        recvLength
        );

    //
    // Save a pointer to the receive request structure so that we
    // can free it in our restart routine.
    //

    IrpSp->Parameters.DeviceIoControl.Type3InputBuffer = receiveRequest;
    IrpSp->Parameters.DeviceIoControl.OutputBufferLength = recvLength;


    //
    // Call the transport to actually perform the connect operation.
    //

    return AfdIoCallDriver( endpoint, connection->DeviceObject, Irp );

complete:

    if ( allocatedReceiveRequest ) {
        AFD_FREE_POOL(
            receiveRequest,
            AFD_TDI_POOL_TAG
            );
    }

    Irp->IoStatus.Information = 0;
    Irp->IoStatus.Status = status;
    IoCompleteRequest( Irp, AfdPriorityBoost );

    return status;

} // AfdReceive


NTSTATUS
AfdRestartReceive (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )
{
    PAFD_ENDPOINT endpoint = Context;
    PAFD_CONNECTION connection;
    PIO_STACK_LOCATION irpSp;
    LARGE_INTEGER actualBytes;
    LARGE_INTEGER requestedBytes;
    KIRQL oldIrql1, oldIrql2;
    ULONG receiveFlags;
    ULONG eventMask;
    BOOLEAN expedited;
    PTDI_REQUEST_RECEIVE receiveRequest;

    ASSERT( endpoint->Type == AfdBlockTypeVcConnecting );
    ASSERT( endpoint->Common.VcConnecting.Connection != NULL );
    ASSERT( endpoint->TdiBufferring );

    irpSp = IoGetCurrentIrpStackLocation( Irp );

    actualBytes = RtlConvertUlongToLargeInteger( Irp->IoStatus.Information );
    requestedBytes = RtlConvertUlongToLargeInteger(
                         irpSp->Parameters.DeviceIoControl.OutputBufferLength
                         );

    //
    // Determine whether we received normal or expedited data.
    //

    receiveRequest = irpSp->Parameters.DeviceIoControl.Type3InputBuffer;
    receiveFlags = receiveRequest->ReceiveFlags;

    if ( Irp->IoStatus.Status == STATUS_RECEIVE_EXPEDITED ||
         Irp->IoStatus.Status == STATUS_RECEIVE_PARTIAL_EXPEDITED ) {
        expedited = TRUE;
    } else {
        expedited = FALSE;
    }

    //
    // Free the receive request structure.
    //

    AFD_FREE_POOL(
        receiveRequest,
        AFD_TDI_POOL_TAG
        );

    //
    // If this was a PEEK receive, don't update the counts of received
    // data, just return.
    //

    if ( (receiveFlags & TDI_RECEIVE_PEEK) != 0 ) {

        IF_DEBUG(RECEIVE) {
            KdPrint(( "AfdRestartReceive: IRP %lx, endpoint %lx, conn %lx, "
                      "status %X\n",
                        Irp, endpoint, endpoint->Common.VcConnecting.Connection,
                        Irp->IoStatus.Status ));
            KdPrint(( "    %s data, PEEKed only.\n",
                        expedited ? "expedited" : "normal" ));
        }

        AfdCompleteOutstandingIrp( endpoint, Irp );
        return STATUS_SUCCESS;
    }

    //
    // Update the count of bytes actually received on the connection.
    //

    AfdAcquireSpinLock( &AfdSpinLock, &oldIrql1 );
    AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql2 );

    if( expedited ) {
        eventMask = endpoint->InLine
                        ? (ULONG)~AFD_POLL_RECEIVE
                        : (ULONG)~AFD_POLL_RECEIVE_EXPEDITED;
    } else {
        eventMask = (ULONG)~AFD_POLL_RECEIVE;
    }

    endpoint->EventsActive &= eventMask;

    IF_DEBUG(EVENT_SELECT) {
        KdPrint((
            "AfdReceive: Endp %08lX, Active %08lX\n",
            endpoint,
            endpoint->EventsActive
            ));
    }

    connection = endpoint->Common.VcConnecting.Connection;
    ASSERT( connection->Type == AfdBlockTypeConnection );

    if ( !expedited ) {

        if ( actualBytes.LowPart == 0 ) {
            ASSERT( actualBytes.HighPart == 0 );
            connection->VcZeroByteReceiveIndicated = FALSE;
        } else {
            connection->Common.Bufferring.ReceiveBytesTaken.QuadPart =
                actualBytes.QuadPart +
                connection->Common.Bufferring.ReceiveBytesTaken.QuadPart;
        }

        //
        // If the number taken exceeds the number indicated, then this
        // receive got some unindicated bytes because the receive was
        // posted when the indication arrived.  If this is the case, set
        // the amount indicated equal to the amount received.
        //

        if ( connection->Common.Bufferring.ReceiveBytesTaken.QuadPart >
                 connection->Common.Bufferring.ReceiveBytesIndicated.QuadPart ) {

            connection->Common.Bufferring.ReceiveBytesIndicated =
                connection->Common.Bufferring.ReceiveBytesTaken;
        }

        //
        // Decrement the count of outstanding receive bytes on this connection
        // by the receive size that was requested.
        //

        connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart =
                connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart -
                requestedBytes.QuadPart;

        //
        // If the endpoint is inline, decrement the count of outstanding
        // expedited bytes.
        //

        if ( endpoint->InLine ) {
            connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart =
                connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart -
                requestedBytes.QuadPart;
        }

        if( connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart > 0 ||
            ( endpoint->InLine &&
              connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart > 0 ) ) {

            AfdIndicateEventSelectEvent(
                endpoint,
                AFD_POLL_RECEIVE_BIT,
                STATUS_SUCCESS
                );

        }

        IF_DEBUG(RECEIVE) {
            KdPrint(( "AfdRestartReceive: IRP %lx, endpoint %lx, conn %lx, "
                      "status %X\n",
                        Irp, endpoint, connection,
                        Irp->IoStatus.Status ));
            KdPrint(( "    req. bytes %ld, actual %ld, ind %ld, "
                      " taken %ld, out %ld\n",
                          requestedBytes.LowPart, actualBytes.LowPart,
                          connection->Common.Bufferring.ReceiveBytesIndicated.LowPart,
                          connection->Common.Bufferring.ReceiveBytesTaken.LowPart,
                          connection->Common.Bufferring.ReceiveBytesOutstanding.LowPart
                          ));
        }

    } else {

        connection->Common.Bufferring.ReceiveExpeditedBytesTaken.QuadPart =
            actualBytes.QuadPart +
            connection->Common.Bufferring.ReceiveExpeditedBytesTaken.QuadPart;

        //
        // If the number taken exceeds the number indicated, then this
        // receive got some unindicated bytes because the receive was
        // posted when the indication arrived.  If this is the case, set
        // the amount indicated equal to the amount received.
        //

        if ( connection->Common.Bufferring.ReceiveExpeditedBytesTaken.QuadPart >
                 connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.QuadPart ) {

            connection->Common.Bufferring.ReceiveExpeditedBytesIndicated =
                connection->Common.Bufferring.ReceiveExpeditedBytesTaken;
        }

        //
        // Decrement the count of outstanding receive bytes on this connection
        // by the receive size that was requested.
        //

        ASSERT( connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.LowPart > 0 ||
                    connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.HighPart > 0 ||
                    requestedBytes.LowPart == 0 );

        connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart =
            connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart -
            requestedBytes.QuadPart;

        //
        // If the endpoint is inline, decrement the count of outstanding
        // normal bytes.
        //

        if ( endpoint->InLine ) {

            connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart =
                connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart -
                requestedBytes.QuadPart;

            if( connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart > 0 ||
                connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart > 0 ) {

                AfdIndicateEventSelectEvent(
                    endpoint,
                    AFD_POLL_RECEIVE_BIT,
                    STATUS_SUCCESS
                    );

            }

        } else {

            if( connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart > 0 ) {

                AfdIndicateEventSelectEvent(
                    endpoint,
                    AFD_POLL_RECEIVE_EXPEDITED_BIT,
                    STATUS_SUCCESS
                    );

            }

        }

        IF_DEBUG(RECEIVE) {
            KdPrint(( "AfdRestartReceive: (exp) IRP %lx, endpoint %lx, conn %lx, "
                      "status %X\n",
                        Irp, endpoint, connection,
                        Irp->IoStatus.Status ));
            KdPrint(( "    req. bytes %ld, actual %ld, ind %ld, "
                      " taken %ld, out %ld\n",
                          requestedBytes.LowPart, actualBytes.LowPart,
                          connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.LowPart,
                          connection->Common.Bufferring.ReceiveExpeditedBytesTaken.LowPart,
                          connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.LowPart
                          ));
        }

    }

    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql2 );
    AfdReleaseSpinLock( &AfdSpinLock, oldIrql1 );

    AfdCompleteOutstandingIrp( endpoint, Irp );

    //
    // If pending has be returned for this irp then mark the current
    // stack as pending.
    //

    if ( Irp->PendingReturned ) {
        IoMarkIrpPending(Irp);
    }

    return STATUS_SUCCESS;

} // AfdRestartReceive


NTSTATUS
AfdReceiveEventHandler (
    IN PVOID TdiEventContext,
    IN CONNECTION_CONTEXT ConnectionContext,
    IN ULONG ReceiveFlags,
    IN ULONG BytesIndicated,
    IN ULONG BytesAvailable,
    OUT ULONG *BytesTaken,
    IN PVOID Tsdu,
    OUT PIRP *IoRequestPacket
    )
{
    PAFD_CONNECTION connection;
    PAFD_ENDPOINT endpoint;
    KIRQL oldIrql;

    connection = (PAFD_CONNECTION)ConnectionContext;
    ASSERT( connection != NULL );

    endpoint = connection->Endpoint;
    ASSERT( endpoint != NULL );

    ASSERT( connection->Type == AfdBlockTypeConnection );
    ASSERT( endpoint->Type == AfdBlockTypeVcConnecting ||
            endpoint->Type == AfdBlockTypeVcListening );
    ASSERT( !connection->DisconnectIndicated );
    ASSERT( !connection->AbortIndicated );
    ASSERT( endpoint->TdiBufferring );

    //
    // Bump the count of bytes indicated on the connection to account for
    // the bytes indicated by this event.
    //

    AfdAcquireSpinLock( &AfdSpinLock, &oldIrql );

    if ( BytesAvailable == 0 ) {

        connection->VcZeroByteReceiveIndicated = TRUE;

    } else {

        connection->Common.Bufferring.ReceiveBytesIndicated.QuadPart =
            connection->Common.Bufferring.ReceiveBytesIndicated.QuadPart +
                BytesAvailable;
    }

    IF_DEBUG(RECEIVE) {
        KdPrint(( "AfdReceiveEventHandler: conn %lx, bytes %ld, "
                  "ind %ld, taken %ld, out %ld\n",
                      connection, BytesAvailable,
                      connection->Common.Bufferring.ReceiveBytesIndicated.LowPart,
                      connection->Common.Bufferring.ReceiveBytesTaken.LowPart,
                      connection->Common.Bufferring.ReceiveBytesOutstanding.LowPart ));
    }

    //
    // If the receive side of the endpoint has been shut down, tell the
    // provider that we took all the data and reset the connection.
    // Also, account for these bytes in our count of bytes taken from
    // the transport.
    //

    if ( (endpoint->DisconnectMode & AFD_PARTIAL_DISCONNECT_RECEIVE) != 0 ) {

#if DBG
        DbgPrint( "AfdReceiveEventHandler: receive shutdown, "
                    "%ld bytes, aborting endp %lx\n",
                        BytesAvailable, endpoint );
#endif

        connection->Common.Bufferring.ReceiveBytesTaken.QuadPart =
            connection->Common.Bufferring.ReceiveBytesTaken.QuadPart +
                BytesAvailable;

        AfdReleaseSpinLock( &AfdSpinLock, oldIrql );

        *BytesTaken = BytesAvailable;

        //
        // Abort the connection.  Note that if the abort attempt fails
        // we can't do anything about it.
        //

        (VOID)AfdBeginAbort( connection );

        return STATUS_SUCCESS;

    } else {

        AfdReleaseSpinLock( &AfdSpinLock, oldIrql );

        //
        // Note to the TDI provider that we didn't take any of the data here.
        //
        // !!! needs bufferring for non-bufferring transports!

        *BytesTaken = 0;

        //
        // If there are any outstanding poll IRPs for this endpoint/
        // event, complete them.
        //

        AfdIndicatePollEvent(
            endpoint,
            AFD_POLL_RECEIVE_BIT,
            STATUS_SUCCESS
            );

        return STATUS_DATA_NOT_ACCEPTED;
    }

} // AfdReceiveEventHandler


NTSTATUS
AfdReceiveExpeditedEventHandler (
    IN PVOID TdiEventContext,
    IN CONNECTION_CONTEXT ConnectionContext,
    IN ULONG ReceiveFlags,
    IN ULONG BytesIndicated,
    IN ULONG BytesAvailable,
    OUT ULONG *BytesTaken,
    IN PVOID Tsdu,
    OUT PIRP *IoRequestPacket
    )
{
    PAFD_CONNECTION connection;
    PAFD_ENDPOINT endpoint;
    KIRQL oldIrql;

    connection = (PAFD_CONNECTION)ConnectionContext;
    ASSERT( connection != NULL );

    endpoint = connection->Endpoint;
    ASSERT( endpoint != NULL );

    ASSERT( connection->Type == AfdBlockTypeConnection );

    //
    // Bump the count of bytes indicated on the connection to account for
    // the expedited bytes indicated by this event.
    //

    AfdAcquireSpinLock( &AfdSpinLock, &oldIrql );

    connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.QuadPart =
        connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.QuadPart +
            BytesAvailable;

    IF_DEBUG(RECEIVE) {
        KdPrint(( "AfdReceiveExpeditedEventHandler: conn %lx, bytes %ld, "
                  "ind %ld, taken %ld, out %ld, offset %ld\n",
                      connection, BytesAvailable,
                      connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.LowPart,
                      connection->Common.Bufferring.ReceiveExpeditedBytesTaken.LowPart,
                      connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.LowPart ));
    }

    //
    // If the receive side of the endpoint has been shut down, tell
    // the provider that we took all the data.  Also, account for these
    // bytes in our count of bytes taken from the transport.
    //
    //

    if ( (endpoint->DisconnectMode & AFD_PARTIAL_DISCONNECT_RECEIVE) != 0 ) {

        IF_DEBUG(RECEIVE) {
            KdPrint(( "AfdReceiveExpeditedEventHandler: receive shutdown, "
                      "%ld bytes dropped.\n", BytesAvailable ));
        }

        connection->Common.Bufferring.ReceiveExpeditedBytesTaken.QuadPart =
            connection->Common.Bufferring.ReceiveExpeditedBytesTaken.QuadPart +
                BytesAvailable;

        AfdReleaseSpinLock( &AfdSpinLock, oldIrql );

        *BytesTaken = BytesAvailable;

        //
        // Abort the connection.  Note that if the abort attempt fails
        // we can't do anything about it.
        //

        (VOID)AfdBeginAbort( connection );

    } else {

        AfdReleaseSpinLock( &AfdSpinLock, oldIrql );

        //
        // Note to the TDI provider that we didn't take any of the data here.
        //
        // !!! needs bufferring for non-bufferring transports!

        *BytesTaken = 0;

        //
        // If there are any outstanding poll IRPs for this endpoint/
        // event, complete them.  Indicate this data as normal data if
        // this endpoint is set up for inline reception of expedited
        // data.
        //

        AfdIndicatePollEvent(
            endpoint,
            endpoint->InLine
                ? AFD_POLL_RECEIVE_BIT
                : AFD_POLL_RECEIVE_EXPEDITED_BIT,
            STATUS_SUCCESS
            );
    }

    return STATUS_DATA_NOT_ACCEPTED;

} // AfdReceiveExpeditedEventHandler


NTSTATUS
AfdQueryReceiveInformation (
    IN PIRP Irp,
    IN PIO_STACK_LOCATION IrpSp
    )
{
    PAFD_RECEIVE_INFORMATION receiveInformation;
    PAFD_ENDPOINT endpoint;
    KIRQL oldIrql;
    LARGE_INTEGER result;
    PAFD_CONNECTION connection;

    //
    // Make sure that the output buffer is large enough.
    //

    if ( IrpSp->Parameters.DeviceIoControl.OutputBufferLength <
             sizeof(AFD_RECEIVE_INFORMATION) ) {
        return STATUS_BUFFER_TOO_SMALL;
    }

    //
    // If this endpoint has a connection block, use the connection block's
    // information, else use the information from the endpoint itself.
    //

    endpoint = IrpSp->FileObject->FsContext;
    ASSERT( IS_AFD_ENDPOINT_TYPE( endpoint ) );
    receiveInformation = Irp->AssociatedIrp.SystemBuffer;

    if ( endpoint->TdiBufferring ) {
        AfdAcquireSpinLock( &AfdSpinLock, &oldIrql );
    } else {
        AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );
    }

    connection = AFD_CONNECTION_FROM_ENDPOINT( endpoint );

    if ( connection != NULL ) {

        ASSERT( endpoint->Type == AfdBlockTypeVcConnecting );
        ASSERT( connection->Type == AfdBlockTypeConnection );

        if ( !endpoint->TdiBufferring ) {

            receiveInformation->BytesAvailable =
                connection->VcBufferredReceiveBytes;
            receiveInformation->ExpeditedBytesAvailable =
                connection->VcBufferredExpeditedBytes;

        } else {

            //
            // Determine the number of bytes available to be read.
            //

            result.QuadPart =
                connection->Common.Bufferring.ReceiveBytesIndicated.QuadPart -
                    (connection->Common.Bufferring.ReceiveBytesTaken.QuadPart +
                     connection->Common.Bufferring.ReceiveBytesOutstanding.QuadPart);

            ASSERT( result.HighPart == 0 );

            receiveInformation->BytesAvailable = result.LowPart;

            //
            // Determine the number of expedited bytes available to be read.
            //

            result.QuadPart =
                connection->Common.Bufferring.ReceiveExpeditedBytesIndicated.QuadPart -
                    (connection->Common.Bufferring.ReceiveExpeditedBytesTaken.QuadPart +
                     connection->Common.Bufferring.ReceiveExpeditedBytesOutstanding.QuadPart);

            ASSERT( result.HighPart == 0 );

            receiveInformation->ExpeditedBytesAvailable = result.LowPart;
        }

    } else {

        //
        // Determine the number of bytes available to be read.
        //

        if ( IS_DGRAM_ENDPOINT(endpoint) ) {

            //
            // Return the amount of bytes of datagrams that are
            // bufferred on the endpoint.
            //

            receiveInformation->BytesAvailable = endpoint->BufferredDatagramBytes;

        } else {

            //
            // This is an unconnected endpoint, hence no bytes are
            // available to be read.
            //

            receiveInformation->BytesAvailable = 0;
        }

        //
        // Whether this is a datagram endpoint or just unconnected,
        // there are no expedited bytes available.
        //

        receiveInformation->ExpeditedBytesAvailable = 0;
    }

    if ( endpoint->TdiBufferring ) {
        AfdReleaseSpinLock( &AfdSpinLock, oldIrql );
    } else {
        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );
    }

    Irp->IoStatus.Information = sizeof(AFD_RECEIVE_INFORMATION);

    return STATUS_SUCCESS;

} // AfdQueryReceiveInformation