summaryrefslogblamecommitdiffstats
path: root/private/ntos/tdi/tcpip/tcp/dgram.c
blob: c0ada18c576c519b863a54162201164f5900db15 (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





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                    
/********************************************************************/
/**                     Microsoft LAN Manager                      **/
/**               Copyright(c) Microsoft Corp., 1990-1993          **/
/********************************************************************/
/* :ts=4 */

//** DGRAM.C - Common datagram protocol code.
//
//  This file contains the code common to both UDP and Raw IP.
//

#include    "oscfg.h"
#include    "ndis.h"
#include    "cxport.h"
#include    "ip.h"
#include    "tdi.h"
#include    "tdistat.h"
#ifdef VXD
#include    "tdivxd.h"
#endif
#ifdef NT
#include    "tdint.h"
#include    "tdistat.h"
#endif
#include    "queue.h"
#include    "addr.h"
#include    "dgram.h"
#include    "tlcommon.h"
#include    "info.h"

#define NO_TCP_DEFS 1
#include    "tcpdeb.h"

#ifdef NT

#ifdef POOL_TAGGING

#ifdef ExAllocatePool
#undef ExAllocatePool
#endif

#define ExAllocatePool(type, size) ExAllocatePoolWithTag(type, size, 'dPCT')

#ifndef CTEAllocMem
#error "CTEAllocMem is not already defined - will override tagging"
#else
#undef CTEAllocMem
#endif

#define CTEAllocMem(size) ExAllocatePoolWithTag(NonPagedPool, size, 'dPCT')

#endif // POOL_TAGGING

#endif // NT

#define NUM_DG_HEADERS         5

#ifdef	NT
#define	DG_MAX_HDRS			0xffff
#else
#define	DG_MAX_HDRS			100
#endif

ulong		DGCurrentSendFree = 0;
ulong		DGMaxSendFree = DG_MAX_HDRS;

EXTERNAL_LOCK(AddrObjTableLock)

DGSendReq      *DGSendReqFree;
DEFINE_LOCK_STRUCTURE(DGSendReqLock)

#ifndef NT
DGRcvReq       *DGRcvReqFree;
#else
SLIST_HEADER	DGRcvReqFree;
#endif

DEFINE_LOCK_STRUCTURE(DGRcvReqFreeLock)

#ifdef  DEBUG
uint    NumSendReq = 0;
uint    NumRcvReq = 0;
#endif

// Information for maintaining the DG Header structures and
// pending queue.
uint            DGHeaderSize;
PNDIS_BUFFER    DGHeaderList;
Queue           DGHeaderPending;
Queue           DGDelayed;

CTEEvent        DGDelayedEvent;

extern  IPInfo  LocalNetInfo;

typedef struct	DGHdrBPoolEntry {
	struct DGHdrBPoolEntry		*uhe_next;
	NDIS_HANDLE					uhe_handle;
	uchar						*uhe_buffer;
} DGHdrBPoolEntry;

DGHdrBPoolEntry	*DGHdrBPoolList = NULL;

//
// All of the init code can be discarded.
//
#ifdef NT
#ifdef ALLOC_PRAGMA

int InitDG(uint MaxHeaderSize);

#pragma alloc_text(INIT, InitDG)

#endif // ALLOC_PRAGMA
#endif

#ifdef CHICAGO
extern	int			RegisterAddrChangeHndlr(void *Handler, uint Add);
extern	void		AddrChange(IPAddr Addr, IPMask Mask, void *Context,
						uint Added);
#endif



//*	GrowDGHeaderList - Try to grow the DG header list.
//
//	Called when we run out of buffers on the DG header list, and need
//	to grow it. We look to see if we're already at the maximum size, and
//	if not we'll allocate the need structures and free them to the list.
//	This routine must be called with the SendReq lock held.
//
//	Input: Nothing.
//
//	Returns: A pointer to a new DG header buffer if we have one, or NULL.
//
PNDIS_BUFFER
GrowDGHeaderList(void)
{
	DGHdrBPoolEntry        *NewEntry;
	NDIS_STATUS				Status;
	uint					HeaderSize;
	uchar					*DGSendHP;
	uint					i;
	PNDIS_BUFFER			Buffer;
	PNDIS_BUFFER			ReturnBuffer = NULL;
	
	if (DGCurrentSendFree < DGMaxSendFree) {
	
		// Still room to grow the list.	
		NewEntry = CTEAllocMem(sizeof(DGHdrBPoolEntry));
	
		if (NewEntry == NULL) {
			// Couldn't get the memory.
			return NULL;
		}
	
    	NdisAllocateBufferPool(&Status, &NewEntry->uhe_handle,
    		NUM_DG_HEADERS);

    	if (Status != NDIS_STATUS_SUCCESS) {
			// Couldn't get a new set of buffers. Fail.
			CTEFreeMem(NewEntry);
        	return NULL;
		}
    	
    	HeaderSize = DGHeaderSize + LocalNetInfo.ipi_hsize;

    	DGSendHP = CTEAllocMem(HeaderSize * NUM_DG_HEADERS);

    	if (DGSendHP == NULL) {
        	NdisFreeBufferPool(NewEntry->uhe_handle);
			CTEFreeMem(NewEntry);
			return NULL;
    	}
		
		NewEntry->uhe_buffer = DGSendHP;

    	for (i = 0; i < NUM_DG_HEADERS; i++) {
        	NdisAllocateBuffer(&Status, &Buffer, NewEntry->uhe_handle,
            	DGSendHP + (i * HeaderSize), HeaderSize);
        	if (Status != NDIS_STATUS_SUCCESS) {
	        	NdisFreeBufferPool(NewEntry->uhe_handle);
				CTEFreeMem(NewEntry);
            	CTEFreeMem(DGSendHP);
				return NULL;
        	}
			if (i != 0)
        		FreeDGHeader(Buffer);
			else
				ReturnBuffer = Buffer;
    	}
	
		DGCurrentSendFree += NUM_DG_HEADERS;
		NewEntry->uhe_next = DGHdrBPoolList;
		DGHdrBPoolList = NewEntry;
	
	} else {
		// At the limit already.
		ReturnBuffer = NULL;
	}
	
	return ReturnBuffer;
			

}
//* GetDGHeader - Get a DG header buffer.
//
//  The get header buffer routine. Called with the SendReqLock held.
//
//  Input: Nothing.
//
//  Output: A pointer to an NDIS buffer, or NULL.
//
_inline PNDIS_BUFFER
GetDGHeader(void)
{
    PNDIS_BUFFER    NewBuffer;

    NewBuffer = DGHeaderList;
    if (NewBuffer != NULL)
        DGHeaderList = NDIS_BUFFER_LINKAGE(NewBuffer);
	else
		NewBuffer = GrowDGHeaderList();

    return NewBuffer;
}

//* FreeDGHeader - Free a DG header buffer.
//
//  The free header buffer routine. Called with the SendReqLock held.
//
//  Input: Buffer to be freed.
//
//  Output: Nothing.
//
void
FreeDGHeader(PNDIS_BUFFER FreedBuffer)
{
    NDIS_BUFFER_LINKAGE(FreedBuffer) = DGHeaderList;
    DGHeaderList = FreedBuffer;
}

//* PutPendingQ - Put an address object on the pending queue.
//
//  Called when we've experienced a header buffer out of resources condition,
//  and want to queue an AddrObj for later processing. We put the specified
//  address object on the DGHeaderPending queue,  set the OOR flag and clear
//  the 'send request' flag. It is invariant in the system that the send
//  request flag and the OOR flag are not set at the same time.
//
//  This routine assumes that the caller holds the DGSendReqLock and the
//  lock on the particular AddrObj.
//
//  Input:  QueueingAO  - Pointer to address object to be queued.
//
//  Returns: Nothing.
//
void
PutPendingQ(AddrObj *QueueingAO)
{
    CTEStructAssert(QueueingAO, ao);

	if (!AO_OOR(QueueingAO)) {
        CLEAR_AO_REQUEST(QueueingAO, AO_SEND);
        SET_AO_OOR(QueueingAO);

        ENQUEUE(&DGHeaderPending, &QueueingAO->ao_pendq);
	}
}

//* GetDGSendReq   - Get a DG send request.
//
//  Called when someone wants to allocate a DG send request. We assume
//  the send request lock is held when we are called.
//
//  Note: This routine and the corresponding free routine might
//      be good candidates for inlining.
//
//  Input:  Nothing.
//
//  Returns: Pointer to the SendReq, or NULL if none.
//
DGSendReq *
GetDGSendReq()
{
    DGSendReq      *NewReq;


    NewReq = DGSendReqFree;
    if (NewReq != NULL) {
        CTEStructAssert(NewReq, dsr);
        DGSendReqFree = (DGSendReq *)NewReq->dsr_q.q_next;
    } else {
        // Couldn't get a request, grow it. This is one area where we'll try
        // to allocate memory with a lock held. Because of this, we've
        // got to be careful about where we call this routine from.

        NewReq = CTEAllocMem(sizeof(DGSendReq));
        if (NewReq != NULL) {
#ifdef DEBUG
            NewReq->dsr_sig = dsr_signature;
            NumSendReq++;
#endif
        }
    }

    return NewReq;
}

//* FreeDGSendReq  - Free a DG send request.
//
//  Called when someone wants to free a DG send request. It's assumed
//  that the caller holds the SendRequest lock.
//
//  Input:  SendReq     - SendReq to be freed.
//
//  Returns: Nothing.
//
void
FreeDGSendReq(DGSendReq *SendReq)
{
    CTEStructAssert(SendReq, dsr);

    *(DGSendReq **)&SendReq->dsr_q.q_next = DGSendReqFree;
    DGSendReqFree = SendReq;
}

//* GetDGRcvReq - Get a DG receive request.
//
//  Called when we need to get a DG receive request.
//
//  Input:  Nothing.
//
//  Returns: Pointer to new request, or NULL if none.
//
DGRcvReq *
GetDGRcvReq()
{
    DGRcvReq       *NewReq;

#ifdef VXD
    NewReq = DGRcvReqFree;
    if (NewReq != NULL) {
        CTEStructAssert(NewReq, drr);
        DGRcvReqFree = (DGRcvReq *)NewReq->drr_q.q_next;
    } else {
        // Couldn't get a request, grow it.
        NewReq = CTEAllocMem(sizeof(DGRcvReq));
        if (NewReq != NULL) {
#ifdef DEBUG
            NewReq->drr_sig = drr_signature;
            NumRcvReq++;
#endif
        }
    }

#endif // VXD

#ifdef NT
    PSINGLE_LIST_ENTRY   BufferLink;
    Queue               *QueuePtr;

    BufferLink = ExInterlockedPopEntrySList(
                     &DGRcvReqFree,
                     &DGRcvReqFreeLock
                     );

    if (BufferLink != NULL) {
        QueuePtr = STRUCT_OF(Queue, BufferLink, q_next);
        NewReq = STRUCT_OF(DGRcvReq, QueuePtr, drr_q);
        CTEStructAssert(NewReq, drr);
    }
    else {
        // Couldn't get a request, grow it.
        NewReq = CTEAllocMem(sizeof(DGRcvReq));
        if (NewReq != NULL) {
#ifdef DEBUG
            NewReq->drr_sig = drr_signature;
            ExInterlockedAddUlong(&NumRcvReq, 1, &DGRcvReqFreeLock);
#endif
        }
    }

#endif // NT

    return NewReq;
}

//* FreeDGRcvReq   - Free a DG rcv request.
//
//  Called when someone wants to free a DG rcv request.
//
//  Input:  RcvReq      - RcvReq to be freed.
//
//  Returns: Nothing.
//
void
FreeDGRcvReq(DGRcvReq *RcvReq)
{
#ifdef VXD

    CTEStructAssert(RcvReq, drr);

    *(DGRcvReq **)&RcvReq->drr_q.q_next = DGRcvReqFree;
    DGRcvReqFree = RcvReq;

#endif // VXD

#ifdef NT

    PSINGLE_LIST_ENTRY BufferLink;

    CTEStructAssert(RcvReq, drr);

    BufferLink = STRUCT_OF(SINGLE_LIST_ENTRY, &(RcvReq->drr_q.q_next), Next);
    ExInterlockedPushEntrySList(
        &DGRcvReqFree,
        BufferLink,
        &DGRcvReqFreeLock
        );

#endif // NT
}


//* DGDelayedEventProc - Handle a delayed event.
//
//  This is the delayed event handler, used for out-of-resources conditions
//  on AddrObjs. We pull from the delayed queue, and is the addr obj is
//  not already busy we'll send the datagram.
//
//  Input:  Event   - Pointer to the event structure.
//          Context - Nothing.
//
//  Returns: Nothing
//
void
DGDelayedEventProc(CTEEvent *Event, void *Context)
{
    CTELockHandle   HeaderHandle, AOHandle;
    AddrObj         *SendingAO;
    DGSendProc      SendProc;

    CTEGetLock(&DGSendReqLock, &HeaderHandle);
    while (!EMPTYQ(&DGDelayed)) {
        DEQUEUE(&DGDelayed, SendingAO, AddrObj, ao_pendq);
        CTEStructAssert(SendingAO, ao);

        CTEGetLock(&SendingAO->ao_lock, &AOHandle);

        CLEAR_AO_OOR(SendingAO);
        if (!AO_BUSY(SendingAO)) {
            DGSendReq          *SendReq;

            if (!EMPTYQ(&SendingAO->ao_sendq)) {
                DEQUEUE(&SendingAO->ao_sendq, SendReq, DGSendReq, dsr_q);

                CTEStructAssert(SendReq, dsr);
                CTEAssert(SendReq->dsr_header != NULL);

                SendingAO->ao_usecnt++;
                SendProc = SendingAO->ao_dgsend;
                CTEFreeLock(&SendingAO->ao_lock, AOHandle);
                CTEFreeLock(&DGSendReqLock, HeaderHandle);

                (*SendProc)(SendingAO, SendReq);
                DEREF_AO(SendingAO);
                CTEGetLock(&DGSendReqLock, &HeaderHandle);
            } else {
                CTEAssert(FALSE);
                CTEFreeLock(&SendingAO->ao_lock, AOHandle);
            }

        } else {
            SET_AO_REQUEST(SendingAO, AO_SEND);
            CTEFreeLock(&SendingAO->ao_lock, AOHandle);
        }
    }

    CTEFreeLock(&DGSendReqLock, HeaderHandle);

}

//* DGSendComplete - DG send complete handler.
//
//  This is the routine called by IP when a send completes. We
//  take the context passed back as a pointer to a SendRequest
//  structure, and complete the caller's send.
//
//  Input:  Context         - Context we gave on send (really a
//                              SendRequest structure).
//          BufferChain     - Chain of buffers sent.
//
//  Returns: Nothing.
void
DGSendComplete(void *Context, PNDIS_BUFFER BufferChain)
{
    DGSendReq      *FinishedSR = (DGSendReq *)Context;
    CTELockHandle   HeaderHandle, AOHandle;
    CTEReqCmpltRtn  Callback;           // Completion routine.
    PVOID           CallbackContext;    // User context.
    ushort          SentSize;
    AddrObj         *AO;

    CTEStructAssert(FinishedSR, dsr);
    CTEGetLock(&DGSendReqLock, &HeaderHandle);

    Callback = FinishedSR->dsr_rtn;
    CallbackContext = FinishedSR->dsr_context;
    SentSize = FinishedSR->dsr_size;

    // If there's nothing on the header pending queue, just free the
    // header buffer. Otherwise pull from the pending queue,  give him the
    // resource, and schedule an event to deal with him.
    if (EMPTYQ(&DGHeaderPending)) {
        FreeDGHeader(BufferChain);
    } else {
        DEQUEUE(&DGHeaderPending, AO, AddrObj, ao_pendq);
        CTEStructAssert(AO, ao);
        CTEGetLock(&AO->ao_lock, &AOHandle);
        if (!EMPTYQ(&AO->ao_sendq)) {
            DGSendReq      *SendReq;

            PEEKQ(&AO->ao_sendq, SendReq, DGSendReq, dsr_q);
            SendReq->dsr_header = BufferChain;      // Give him this buffer.

            ENQUEUE(&DGDelayed, &AO->ao_pendq);
            CTEFreeLock(&AO->ao_lock, AOHandle);
            CTEScheduleEvent(&DGDelayedEvent, NULL);
        } else {
            // On the pending queue, but no sends!
            DEBUGCHK;
            CLEAR_AO_OOR(AO);
            CTEFreeLock(&AO->ao_lock, AOHandle);
        }

    }

    FreeDGSendReq(FinishedSR);
    CTEFreeLock(&DGSendReqLock, HeaderHandle);
    if (Callback != NULL)
        (*Callback)(CallbackContext, TDI_SUCCESS, (uint)SentSize);

}


#ifdef NT
//
// NT supports cancellation of DG send/receive requests.
//

#define TCP_DEBUG_SEND_DGRAM     0x00000100
#define TCP_DEBUG_RECEIVE_DGRAM  0x00000200

extern ULONG TCPDebug;


VOID
TdiCancelSendDatagram(
    AddrObj  *SrcAO,
	PVOID     Context
	)
{
	CTELockHandle	 lockHandle;
	DGSendReq	    *sendReq = NULL;
	Queue           *qentry;
	BOOLEAN          found = FALSE;


	CTEStructAssert(SrcAO, ao);

	CTEGetLock(&SrcAO->ao_lock, &lockHandle);

	// Search the send list for the specified request.
	for ( qentry = QNEXT(&(SrcAO->ao_sendq));
		  qentry != &(SrcAO->ao_sendq);
		  qentry = QNEXT(qentry)
		) {

        sendReq = STRUCT_OF(DGSendReq, qentry, dsr_q);

    	CTEStructAssert(sendReq, dsr);

		if (sendReq->dsr_context == Context) {
			//
			// Found it. Dequeue
			//
			REMOVEQ(qentry);
			found = TRUE;

            IF_TCPDBG(TCP_DEBUG_SEND_DGRAM) {
				TCPTRACE((
				    "TdiCancelSendDatagram: Dequeued item %lx\n",
				    Context
					));
			}

			break;
		}
	}

	CTEFreeLock(&SrcAO->ao_lock, lockHandle);

	if (found) {
		//
		// Complete the request and free its resources.
		//
	    (*sendReq->dsr_rtn)(sendReq->dsr_context, (uint) TDI_CANCELLED, 0);

		CTEGetLock(&DGSendReqLock, &lockHandle);

	    if (sendReq->dsr_header != NULL) {
		    FreeDGHeader(sendReq->dsr_header);
	    }

		FreeDGSendReq(sendReq);

		CTEFreeLock(&DGSendReqLock, lockHandle);
	}

} // TdiCancelSendDatagram


VOID
TdiCancelReceiveDatagram(
    AddrObj  *SrcAO,
	PVOID     Context
	)
{
	CTELockHandle	 lockHandle;
	DGRcvReq 	    *rcvReq = NULL;
	Queue           *qentry;
	BOOLEAN          found = FALSE;


	CTEStructAssert(SrcAO, ao);

	CTEGetLock(&SrcAO->ao_lock, &lockHandle);

	// Search the send list for the specified request.
	for ( qentry = QNEXT(&(SrcAO->ao_rcvq));
		  qentry != &(SrcAO->ao_rcvq);
		  qentry = QNEXT(qentry)
		) {

        rcvReq = STRUCT_OF(DGRcvReq, qentry, drr_q);

    	CTEStructAssert(rcvReq, drr);

		if (rcvReq->drr_context == Context) {
			//
			// Found it. Dequeue
			//
			REMOVEQ(qentry);
			found = TRUE;

            IF_TCPDBG(TCP_DEBUG_SEND_DGRAM) {
				TCPTRACE((
				    "TdiCancelReceiveDatagram: Dequeued item %lx\n",
				    Context
					));
			}

			break;
		}
	}

	CTEFreeLock(&SrcAO->ao_lock, lockHandle);

	if (found) {
		//
		// Complete the request and free its resources.
		//
	    (*rcvReq->drr_rtn)(rcvReq->drr_context, (uint) TDI_CANCELLED, 0);

		FreeDGRcvReq(rcvReq);
	}

} // TdiCancelReceiveDatagram


#endif // NT


//** TdiSendDatagram - TDI send datagram function.
//
//  This is the user interface to the send datagram function. The
//  caller specified a request structure, a connection info
//  structure  containing the address, and data to be sent.
//  This routine gets a DG Send request structure to manage the
//  send, fills the structure in, and calls DGSend to deal with
//  it.
//
//  Input:  Request         - Pointer to request structure.
//          ConnInfo        - Pointer to ConnInfo structure which points to
//                              remote address.
//          DataSize        - Size in bytes of data to be sent.
//          BytesSent       - Pointer to where to return size sent.
//          Buffer          - Pointer to buffer chain.
//
//  Returns: Status of attempt to send.
//
TDI_STATUS
TdiSendDatagram(PTDI_REQUEST Request, PTDI_CONNECTION_INFORMATION ConnInfo,
    uint DataSize, uint *BytesSent, PNDIS_BUFFER Buffer)
{
    AddrObj         *SrcAO;     // Pointer to AddrObj for src.
    DGSendReq      *SendReq;   // Pointer to send req for this request.
    CTELockHandle   Handle, SRHandle;   // Lock handles for the AO and the
                                // send request.
    TDI_STATUS      ReturnValue;
    DGSendProc      SendProc;

    // First, get a send request. We do this first because of MP issues
    // if we port this to NT. We need to take the SendRequest lock before
    // we take the AddrObj lock, to prevent deadlock and also because
    // GetDGSendReq might yield, and the state of the AddrObj might
    // change on us, so we don't want to yield after we've validated
    // it.

    CTEGetLock(&DGSendReqLock, &SRHandle);
    SendReq = GetDGSendReq();

    // Now get the lock on the AO, and make sure it's valid. We do this
    // to make sure we return the correct error code.

#ifdef VXD
    SrcAO = GetIndexedAO((uint)Request->Handle.AddressHandle);

    if (SrcAO != NULL) {
#else
    SrcAO = Request->Handle.AddressHandle;
#endif

    CTEStructAssert(SrcAO, ao);

    CTEGetLock(&SrcAO->ao_lock, &Handle);

    if (AO_VALID(SrcAO)) {

	    // Make sure the size is reasonable.
        if (DataSize <= SrcAO->ao_maxdgsize)  {
		
            // The AddrObj is valid. Now fill the address into the send request,
            // if we've got one. If this works, we'll continue with the
            // send.

            if (SendReq != NULL) {          // Got a send request.
                if (GetAddress(ConnInfo->RemoteAddress, &SendReq->dsr_addr,
                    &SendReq->dsr_port)) {

                    SendReq->dsr_rtn = Request->RequestNotifyObject;
                    SendReq->dsr_context = Request->RequestContext;
                    SendReq->dsr_buffer = Buffer;
                    SendReq->dsr_size = (ushort)DataSize;

                    // We've filled in the send request. If the AO isn't
                    // already busy, try to get a DG header buffer and send
                    // this. If the AO is busy, or we can't get a buffer, queue
                    // until later. We try to get the header buffer here, as
                    // an optimazation to avoid having to retake the lock.

                    if (!AO_OOR(SrcAO)) {           // AO isn't out of resources
                        if (!AO_BUSY(SrcAO)) {      // or or busy

                            if ((SendReq->dsr_header = GetDGHeader()) != NULL) {
                                REF_AO(SrcAO);      // Lock out exclusive
                                                    // activities.
                                SendProc = SrcAO->ao_dgsend;

                                CTEFreeLock(&SrcAO->ao_lock, Handle);
                                CTEFreeLock(&DGSendReqLock, SRHandle);

                                // Allright, just send it.
                                (*SendProc)(SrcAO, SendReq);

                                // See if any pending requests occured during
                                // the send. If so, call the request handler.
                                DEREF_AO(SrcAO);

                                return TDI_PENDING;
                            } else {
                                // We couldn't get a header buffer. Put this
                                // guy on the pending queue, and then fall
                                // through to the 'queue request' code.
                                PutPendingQ(SrcAO);
                            }
                        } else {
                            // AO is busy, set request for later
                            SET_AO_REQUEST(SrcAO, AO_SEND);
                        }
                    }

                    // AO is busy, or out of resources. Queue the send request
                    // for later.
                    SendReq->dsr_header = NULL;
                    ENQUEUE(&SrcAO->ao_sendq, &SendReq->dsr_q);
                    SendReq = NULL;
                    ReturnValue = TDI_PENDING;
                }
                else {
                    // The remote address was invalid.
                    ReturnValue = TDI_BAD_ADDR;
                }
            }
            else {
                // Send request was null, return no resources.
                ReturnValue = TDI_NO_RESOURCES;
            }
        }
        else {
            // Buffer was too big, return an error.
            ReturnValue = TDI_BUFFER_TOO_BIG;
        }
    }
    else {
        // The addr object is invalid, possibly because it's deleting.
        ReturnValue = TDI_ADDR_INVALID;
    }

    CTEFreeLock(&SrcAO->ao_lock, Handle);

#ifdef VXD
    }
    else {
        ReturnValue = TDI_ADDR_INVALID;
    }
#endif

    if (SendReq != NULL)
        FreeDGSendReq(SendReq);

    CTEFreeLock(&DGSendReqLock, SRHandle);

    return TDI_ADDR_INVALID;
}

//** TdiReceiveDatagram - TDI receive datagram function.
//
//  This is the user interface to the receive datagram function. The
//  caller specifies a request structure, a connection info
//  structure  that acts as a filter on acceptable datagrams, a connection
//  info structure to be filled in, and other parameters. We get a DGRcvReq
//  structure, fill it in, and hang it on the AddrObj, where it will be removed
//  later by incomig datagram handler.
//
//  Input:  Request         - Pointer to request structure.
//          ConnInfo        - Pointer to ConnInfo structure which points to
//                              remote address.
//          ReturnInfo      - Pointer to ConnInfo structure to be filled in.
//          RcvSize         - Total size in bytes receive buffer.
//          BytesRcvd       - Pointer to where to return size received.
//          Buffer          - Pointer to buffer chain.
//
//  Returns: Status of attempt to receive.
//
TDI_STATUS
TdiReceiveDatagram(PTDI_REQUEST Request, PTDI_CONNECTION_INFORMATION ConnInfo,
    PTDI_CONNECTION_INFORMATION ReturnInfo, uint RcvSize, uint *BytesRcvd,
    PNDIS_BUFFER Buffer)
{
    AddrObj        *RcvAO;     // AddrObj that is receiving.
    DGRcvReq       *RcvReq;    // Receive request structure.
    CTELockHandle   AOHandle;
    uchar           AddrValid;

    RcvReq = GetDGRcvReq();

#ifdef VXD
    RcvAO = GetIndexedAO((uint)Request->Handle.AddressHandle);

    if (RcvAO != NULL) {
        CTEStructAssert(RcvAO, ao);

#else
    RcvAO = Request->Handle.AddressHandle;
    CTEStructAssert(RcvAO, ao);
#endif

    CTEGetLock(&RcvAO->ao_lock, &AOHandle);
    if (AO_VALID(RcvAO)) {

        IF_TCPDBG(TCP_DEBUG_RAW) {
            TCPTRACE(("posting receive on AO %lx\n", RcvAO));
        }

        if (RcvReq != NULL) {
            if (ConnInfo != NULL && ConnInfo->RemoteAddressLength != 0)
                AddrValid = GetAddress(ConnInfo->RemoteAddress,
                    &RcvReq->drr_addr, &RcvReq->drr_port);
            else {
                AddrValid = TRUE;
                RcvReq->drr_addr = NULL_IP_ADDR;
                RcvReq->drr_port = 0;
            }

			if (AddrValid) {

                // Everything'd valid. Fill in the receive request and queue it.
                RcvReq->drr_conninfo = ReturnInfo;
                RcvReq->drr_rtn = Request->RequestNotifyObject;
                RcvReq->drr_context = Request->RequestContext;
                RcvReq->drr_buffer = Buffer;
                RcvReq->drr_size = RcvSize;
                ENQUEUE(&RcvAO->ao_rcvq, &RcvReq->drr_q);
                CTEFreeLock(&RcvAO->ao_lock, AOHandle);

                return TDI_PENDING;
            } else {
                // Have an invalid filter address.
                CTEFreeLock(&RcvAO->ao_lock, AOHandle);
                FreeDGRcvReq(RcvReq);
                return TDI_BAD_ADDR;
            }
        } else {
            // Couldn't get a receive request.
            CTEFreeLock(&RcvAO->ao_lock, AOHandle);
            return TDI_NO_RESOURCES;
        }
    } else {
        // The AddrObj isn't valid.
        CTEFreeLock(&RcvAO->ao_lock, AOHandle);
    }

#ifdef VXD
    }
#endif

    // The AddrObj is invalid or non-existent.
    if (RcvReq != NULL)
        FreeDGRcvReq(RcvReq);

    return TDI_ADDR_INVALID;
}


#pragma BEGIN_INIT

//* InitDG - Initialize the DG stuff.
//
//  Called during init time to initalize the DG code. We initialize
//  our locks and request lists.
//
//  Input:  MaxHeaderSize - The maximum size of a datagram transport header,
//                          not including the IP header.
//
//  Returns: True if we succeed, False if we fail.
//
int
InitDG(uint MaxHeaderSize)
{
    PNDIS_BUFFER    Buffer;
	CTELockHandle	Handle;


    DGHeaderSize = MaxHeaderSize;

    CTEInitLock(&DGSendReqLock);
    CTEInitLock(&DGRcvReqFreeLock);

    DGSendReqFree = NULL;

#ifndef NT
    DGRcvReqFree = NULL;
#else
	ExInitializeSListHead(&DGRcvReqFree);
#endif

	
	CTEGetLock(&DGSendReqLock, &Handle);
		
	Buffer = GrowDGHeaderList();
	
	if (Buffer != NULL) {
		FreeDGHeader(Buffer);
		CTEFreeLock(&DGSendReqLock, Handle);
	} else {
		CTEFreeLock(&DGSendReqLock, Handle);
		return FALSE;
	}
			
    INITQ(&DGHeaderPending);
    INITQ(&DGDelayed);

    CTEInitEvent(&DGDelayedEvent, DGDelayedEventProc);

    return TRUE;
}

#pragma END_INIT