-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP2Pwin32.cpp
More file actions
7572 lines (7005 loc) · 276 KB
/
Copy pathP2Pwin32.cpp
File metadata and controls
7572 lines (7005 loc) · 276 KB
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
// Copyright © 2004-2013, 2026 Ivyware Pty Ltd, Khrustal & Mann
// MELBOURNE, VICTORIA, AUSTRALIA, 3000
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
#include "stdafx.h"
#include "Kernel32_Ext.h"
#include "P2PeerMsg.h"
#include "P2PeerCon.h"
#include "P2Pwin32.h"
#include "P2PeerExplorer.h"
///////////////////////////////////////////////////////////////////////
// Private P2Peer definitions
// NOTES: Used for P2PeerCon and P2PeerMsg object pumping and
// support
//
static
std::atomic<DWORD> s_cP2Pmsg = 0; // live P2Pmsg count; ++/-- and capacity-check reads happen
// on pump threads and posters under different locks - atomic
// to fix the TSan-reported race (Risk #3). Approximate reads
// (the > MAX capacity guard) are fine.
// THE bound on live P2Pmsg's, and the only one. Note the scope: s_cP2Pmsg is
// a PROCESS-WIDE count of live P2Pmsg's across every pump, not the depth of the
// pump being posted to, so this bounds the process's message budget and the
// diagnostic's "pump is full" is the older, narrower reading of it.
// NOTES: const, not "effectively const" - it was a mutable static that nothing
// ever assigned, which is what let the figure and the diagnostic drift
// apart in the first place. The compiler now holds that open.
static
const DWORD s_cP2PmsgMAX = 50000;
// ONE bound, ONE rendering. Every capacity diagnostic renders s_cP2PmsgMAX
// through this format rather than naming a figure of its own.
// NOTES: This is Stage 0 step 2. Seven sites tested the depth
// and all seven printed "10000 entries" while the bound was 50000 - the
// literal outlived the constant, and a message nobody could trust is how
// an operator learns to disregard the queue diagnostic entirely.
// : Numeric-only, so the format stays NARROW at the sites that were narrow
// - rule 3 of p2p_diag_wideformat_sweep.md. %lu (and the unsigned long
// cast at every site) rather than %u because DWORD is unsigned long on
// Windows and uint32_t on Linux, and because Platform's p2p_fix_wformat
// rewrites %s but passes %lu through untouched on the wide path.
#define P2PMSG_QUEFULL_FMT "P2Pmsg pump is full, %lu entries"
#define P2PMSG_WIDEN_(s) L##s
#define P2PMSG_WIDEN(s) P2PMSG_WIDEN_(s)
#define P2PMSG_QUEFULL_FMT_W P2PMSG_WIDEN(P2PMSG_QUEFULL_FMT)
///////////////////////////////////////////////////////////////////////
// Backpressure on the P2Pmsg budget
// NOTES: Stage 4 step 12. The bound above is a CLIFF: a
// peer may send as fast as it likes right up to it, and the failure at
// it is an exception raised on whichever thread happens to post the
// message that crosses it - which is nearly never the thread, or the
// connection, responsible for the pressure. An operator sees a
// QUEFULL out of a send path and learns nothing about who caused it
// : These two marks make the same budget a SLOPE. At or above the HIGH
// mark a connection stops asking its transport for more (refer
// P2PeerCon::HoldRecvForBackpressure); at or below the LOW mark it
// starts again. The gap between them is hysteresis and is the whole
// reason there are two numbers: a single mark makes a connection
// resume the instant the budget dips one message below it, and it is
// then immediately re-throttled, which is a spin rather than a brake
// : ALWAYS ON, unlike the accept bounds, and the default marks are
// fractions of the existing ceiling rather than new numbers. An
// opt-in backpressure default would leave the cliff standing for every
// deployment that did not know to ask, which is the whole complaint
// the step makes. Nothing in the suite comes within an order of
// magnitude of 37500 live messages, so turning it on by default
// changes no measurable behaviour - which is what makes it defensible
// : SETTABLE, unlike s_cP2PmsgMAX, and for a different reason than
// configurability for its own sake: a deployment that wants to feel
// backpressure earlier than three quarters of the process budget has
// no other way to ask, and a TEST cannot manufacture 37500 live
// messages cheaply enough to be a gate. The ceiling stays const
// : Atomic for the same reason s_cP2Pmsg is - read on pump threads and
// written on whichever thread configured the hub
static
std::atomic<DWORD> s_cP2PmsgHIGH ( s_cP2PmsgMAX * 3 / 4 ); // 37500
static
std::atomic<DWORD> s_cP2PmsgLOW ( s_cP2PmsgMAX / 2 ); // 25000
// Cumulative count of holds applied, process-wide and never reset.
// NOTES: The step asks for the decision to be VISIBLE IN A COUNTER, and this
// is the one that answers "is this happening at all" without a hub, a
// snapshot or a connection in hand. Per-connection attribution is
// P2PeerCon::GetRecvThrottleCount(), and the hub's own figure is the
// Throttled field of its snapshot
static
std::atomic<DWORD> s_cP2PmsgHeld ( 0 );
//
// Sets the backpressure marks on the P2Pmsg budget
// NOTES: Throws rather than clamping. A caller that named two numbers and
// got them the wrong way round has a bug, and silently swapping them
// would hide it behind behaviour that looks almost right
// : dwHigh must stay BELOW the ceiling, not merely at or under it. A
// held connection arms a poll timer, a timer IS a P2Pmsg, and a mark
// at the ceiling would make the act of applying backpressure throw the
// QUEFULL it exists to prevent
//
// Parameters: DWORD dwHigh
// Live-message count at which connections stop reading
//
// DWORD dwLow
// Live-message count at which they start again
void
SetP2PmsgBudgetMarks ( DWORD dwHigh, DWORD dwLow )
{
if ( dwHigh == 0 || dwLow == 0 || dwLow >= dwHigh || dwHigh >= s_cP2PmsgMAX )
EVERR->MODULE
->AFP(dwHigh)->AFP(dwLow)
->Message("Backpressure marks must satisfy 0 < low < high < %lu"
, (unsigned long)s_cP2PmsgMAX )
->Advice ("Refer SetP2PmsgBudgetMarks()" )
->Throw ( );
s_cP2PmsgHIGH = dwHigh;
s_cP2PmsgLOW = dwLow;
}
DWORD GetP2PmsgBudgetHigh ( ) { return s_cP2PmsgHIGH; }
DWORD GetP2PmsgBudgetLow ( ) { return s_cP2PmsgLOW; }
DWORD GetP2PmsgBudgetMax ( ) { return s_cP2PmsgMAX; }
//
// Is the budget under pressure, and has it recovered?
// NOTES: Deliberately NOT the negation of each other - between the two marks
// both are false, which is the hysteresis band: a connection already
// holding keeps holding, and one already reading keeps reading
bool P2PmsgBudgetPressed ( ) { return s_cP2Pmsg >= s_cP2PmsgHIGH; }
bool P2PmsgBudgetRelieved ( ) { return s_cP2Pmsg <= s_cP2PmsgLOW; }
DWORD GetP2PmsgHeldCount ( ) { return s_cP2PmsgHeld; }
void BumpP2PmsgHeldCount ( ) { s_cP2PmsgHeld++; }
typedef struct
{
// OWNS its address; it used to be a borrowed P2PaddrSTR (F-S5-2).
// A P2Pmsg is QUEUED and dispatched on another thread, so a pointer
// stored here outlives whatever produced it. Both suppliers are unsafe:
// P2PeerExpump::PostP2PeerCon passed a LOCAL P2Paddr (destroyed at its
// return, while the queue entry still pointed into its CString), and
// GetSource() below returns c_wstr(), which off Win32 is a slot in a
// 16-slot THREAD-LOCAL ring belonging to the posting thread.
// Owning it makes every assignment a copy and ends the class of defect
// rather than the one instance ASan happened to catch.
CString strP2Paddr; // Identifies P2PeerCon object
// from which P2Pmsg originated
P2Pmsg_t nMsg; // Message identification
P2PmsgCN nCode;
P2Peerio *pPeerio;
P2PeerCon *pCon;
P2PeerMsg *pMsg;
P2Pevent *pEvent;
void *pTarget;
P3PmsgItem *pP3PmsgItem;
//P3PmsgNode *pP3PmsgNode;
void *pExtra; // Extra information
DWORD nHubThreadID;
HANDLE hEventHub;
bool bNotify;
__int64 iPitime;
UINT iPitimeID;
WPARAM wParam;
LPARAM lParam;
DWORD dwUserKey;
} P2Pmsg;
P2Pmsg*
P2PmsgFactory ( )
{
// Manufacture
// new P2Pmsg() and NOT ZeroMemory: strP2Paddr is a CString now, and a
// bulk wipe over a constructed std::wstring loses its heap pointer.
// Value-initialisation zeroes every POD member first and then runs the
// implicit default constructor, so the scalars keep the guarantee the
// ZeroMemory gave them.
P2Pmsg *pP2Pmsg = new P2Pmsg();
s_cP2Pmsg++;
return pP2Pmsg;
}
bool
VerifyP2Pmsg ( P2Pmsg *pP2Pmsg )
{
// Addressing
ASSERT ( !pP2Pmsg ||
AfxIsValidAddress(pP2Pmsg,sizeof(P2Pmsg),true) );
ASSERT ( !pP2Pmsg ||
!pP2Pmsg->pCon ||
AfxIsValidAddress(pP2Pmsg->pCon,sizeof(P2PeerCon),true) );
// P2PeerMsg
if ( pP2Pmsg &&
pP2Pmsg->pMsg )
pP2Pmsg -> pMsg -> AssertValid ( );
// P2PeerCon
if ( pP2Pmsg &&
pP2Pmsg->pCon )
pP2Pmsg -> pCon -> AssertValid ( );
// P2PeerTarget
P2PeerTarget *pTarget = reinterpret_cast<P2PeerTarget*>(pP2Pmsg->pTarget);
if ( pP2Pmsg ) {
ASSERT(pTarget);
((P2PeerTarget*)pP2Pmsg->pTarget)->P2PeerTarget::AssertValid();
}
// Done
return true;
}
// P2Pmsg context
// NOTES: Exchanged privately between static functions in the
// P2PeerAPI
// : In addition some helpful thread context management
// definitions
typedef struct
{
HWND hWnd; // Destination
UINT nWM_APP; // WM_APP domain message
DWORD nThreadID; // Thread identifier
P2PeerTarget *pTarget; // Implementation target
P2PeerCon *pCon;
P2PeerMsg *pMsg;
} P2Pmsg_Context;
typedef P2PSafePtr<P2Pmsg_Context> P2Pmsg_ContextSP;
//
// P2PmsgHub handle
typedef struct P2PmsgHub
{
HANDLE hFile;
HANDLE hIOCP;
//P2PeerCon_e eP2PeerCon;
P2PeerCon *pConThis;
P2PeerCon *pConThat;
OVERLAPPEDcon *pOVERLAPPEDrecv;
char *pBufferRecv;
DWORD nBytesRecv;
OVERLAPPEDcon *pOVERLAPPEDsend;
char *pBufferSend;
DWORD nBytesSend;
OVERLAPPEDcon *pOVERLAPPEDaccept;
UINT_PTR uCompletionKey;
P2PmsgHub *hThat;
} P2PmsgHub;
typedef P2PSafePtr<P2PeerCon> P2PeerConSP;
///////////////////////////////////////////////////////////////////////
// SafeCon
// NOTES: Optimised for and targeted to P2PeerCon life cycle
// management. Internal private operations
/*class SafeCon
{
// Constructors and destructor
public:
SafeCon ( P2PeerCon *pCon )
{
m_pCon = pCon;
m_cRef = 0;
m_bDestroy = false;
m_pCon -> m_hP2PmsgCon = (HANDLE)this;
}
virtual
~SafeCon ( ) { delete m_pCon; };
// Life cycle management
public:
UINT
AddRef ( ) { return ++m_cRef; }
UINT
Release ( )
{
int cRef = --m_cRef;
ASSERT(cRef>=0);
if ( m_cRef <= 0 && m_bDestroy )
delete this;
return cRef;
}
UINT
Destroy ( ) { m_bDestroy = true; return m_cRef; }
bool
PostDestroyState ( ) { return m_bDestroy && m_cRef <= 0; }
// Operators
public:
operator P2PeerCon* ( ) { return m_pCon; }
// Attributes
protected:
P2PeerCon *m_pCon;
int m_cRef;
bool m_bDestroy;
};
#define SafeConPtr(pCon) ((SafeCon*)pCon->m_hP2PmsgCon)*/
///////////////////////////////////////////////////////////////////////
// P2PmsgPump
// NOTES: Manages FIFO lists of P2Pmsg objects. Strict P2Pmsg
// ordering must be maintained
static
CRITICAL_SECTION s_oCSectionP2Pmsg;
static
bool s_bCSectionP2Pmsg = false;
static
UINT s_uPitimeID = 0;
static
bool m_bP2PmsgExplorer_Pump = false;
class P2PmsgHubMgr;
class P2PmsgPump;
static CMap<DWORD_PTR, DWORD_PTR, P2PmsgPump*, P2PmsgPump*> s_ThreadID_P2PmsgPump;
static CRITICAL_SECTION s_oCSectionP2PmsgPump;
CMap<DWORD_PTR,DWORD_PTR,P2PmsgHubID,P2PmsgHubID> s_P2PmsgCon_HubID;
CMap<DWORD_PTR,DWORD_PTR,P2PmsgHubID,P2PmsgHubID> s_P2PexpCon_HubID;
P2Pmsg* ReleaseP2Pmsg ( P2Pmsg *pP2Pmsg ); // Fwd decl: defined below, used by ~P2PmsgPump()
class P2PmsgPump
{
// Constructors and destructor
public:
P2PmsgPump ( )
{
m_pQuePrev = 0;
m_pQueNext = 0;
m_hQueEvent = 0;
m_bOwnQueEvent = false; // F-S5-4: set by whoever creates it
m_bWakePosted = false; // W2: no wake outstanding at construction
m_nThreadId = GetCurrentThreadId();
m_nHubID = 0;
m_nPumpID = GetCurrentThreadId();
m_pP2Pmsg = 0;
m_hIOCP = 0;
m_pOVERLAPPED = 0;
m_hP2PmsgHubListen = 0;
m_nPitimeID = 0;
m_pP2Pmsg = 0;
m_oP2Paddr = L"";
m_bListen = 0;
m_pTarget = 0;
m_pContext = 0;
m_bRedirect = false;
m_bRepump = false;
m_nID = 0;
m_wProps = 0;
m_bP2Pexplorer = false;
m_dwExpumpMask = 0;
m_pP2PmsgHubMgr = 0;
s_ThreadID_P2PmsgPump.SetAt( m_nThreadId, this );
InitializeCriticalSection ( &m_oCSection );
};
~P2PmsgPump ( )
{
/*if ( m_pQuePrev )
m_pQuePrev->m_pQueNext = m_pQueNext;
if ( m_pQueNext )
m_pQueNext->m_pQuePrev = m_pQuePrev;
// Optimisation
if ( s_pQueLast == this )
{
if ( m_pQueNext )
s_pQueLast = m_pQueNext;
else if ( m_pQuePrev )
s_pQueLast = m_pQuePrev;
else
s_pQueLast = 0;
}*/
// Garbage
if ( m_pContext )
delete m_pContext;
// Drain any P2Pmsg's still queued at teardown
// NOTES: Undispatched messages (e.g. CN_P2PeerSnc sink notifications
// with pCon==0, which FlushP2Pmsg() deliberately re-queues)
// would otherwise leak - along with their pP3PmsgItem - when
// the pump is destroyed. These are owned by the pump and were
// never dispatched, so releasing them here cannot double-free.
while ( m_oCListP2Pmsg.GetCount() )
ReleaseP2Pmsg ( m_oCListP2Pmsg.RemoveHead() );
while ( m_oCListP2PmsgPit.GetCount() )
ReleaseP2Pmsg ( m_oCListP2PmsgPit.RemoveHead() );
// Resources
DeleteCriticalSection ( &m_oCSection );
if ( m_hIOCP )
CloseHandle ( m_hIOCP );
// F-S5-4. The queue event was created here and was never closed
// anywhere - CreateP2Pexpump() and CreateP2PmsgPump() both make one
// and only m_hIOCP two lines up was ever given back. On Windows
// that is a kernel handle per pump for the life of the process; on
// Linux the shim's HANDLE is a heap object plus an eventfd, which
// is what LSan reports. Ownership-gated - see m_bOwnQueEvent.
if ( m_bOwnQueEvent && m_hQueEvent )
CloseHandle ( m_hQueEvent );
if ( m_pOVERLAPPED )
delete m_pOVERLAPPED;
s_ThreadID_P2PmsgPump.RemoveKey ( m_nThreadId );
};
void
Verify ( )
{
POSITION pos;
pos = m_oCListP2PmsgPit.GetHeadPosition();
while ( pos )
VerifyP2Pmsg ( m_oCListP2PmsgPit.GetNext(pos) );
pos = m_oCListP2Pmsg.GetHeadPosition();
while ( pos )
VerifyP2Pmsg ( m_oCListP2Pmsg.GetNext(pos) );
}
// Patterns
public:
static P2PmsgPump*
GetHead ( )
{
while ( s_pQueLast &&
s_pQueLast->m_pQuePrev )
s_pQueLast = s_pQueLast->m_pQuePrev;
return s_pQueLast;
}
static P2PmsgPump*
GetP2PmsgPump ( P2PumpID nPumpID = 0 )
{
// Introduce locals
if ( nPumpID == 0 )
nPumpID = GetCurrentThreadId ( );
P2PmsgPump *pP2PmsgPump = 0;
// Implementation
s_ThreadID_P2PmsgPump.Lookup ( nPumpID, pP2PmsgPump );
return pP2PmsgPump;
};
static P2PmsgPump*
GetP2PmsgHub ( P2Paddr oP2Paddr )
{
// To be sure, to be sure
if ( !s_pQueLast ||
oP2Paddr.IsNull() )
return 0;
// Reset to first in list
P2PmsgPump *pP2PmsgPump = s_pQueLast;
while ( pP2PmsgPump->m_pQuePrev )
pP2PmsgPump = pP2PmsgPump->m_pQuePrev;
// Search
while ( pP2PmsgPump )
{
if ( pP2PmsgPump->m_hP2PmsgHubListen &&
pP2PmsgPump->m_pTarget->GetP2PaddrHub() == oP2Paddr )
return pP2PmsgPump;
pP2PmsgPump = pP2PmsgPump -> m_pQueNext;
}
// Not found
return pP2PmsgPump;
};
static P2PmsgPump*
Factory ( HANDLE hEventPump, P2PeerTarget *pTarget )
{
P2PsafeCS oSafeCS = s_oCSectionP2PmsgPump;
P2PmsgPump *pQue = new P2PmsgPump ( );
pQue -> m_pTarget = pTarget;
pQue -> m_hQueEvent = hEventPump;
pQue -> m_nThreadId = GetCurrentThreadId();
// Backwards positioning
while ( s_pQueLast &&
s_pQueLast->m_pQuePrev &&
s_pQueLast->m_nThreadId > pQue->m_nThreadId )
s_pQueLast = s_pQueLast->m_pQuePrev;
// Forewards positioning
while ( s_pQueLast &&
s_pQueLast->m_pQueNext &&
s_pQueLast->m_nThreadId < pQue->m_nThreadId )
s_pQueLast = s_pQueLast->m_pQueNext;
// Linkage
if ( !s_pQueLast )
s_pQueLast = pQue;
// Linkage
else if ( pQue->m_nThreadId < s_pQueLast->m_nThreadId )
{
pQue -> m_pQueNext = s_pQueLast;
pQue -> m_pQuePrev = s_pQueLast->m_pQuePrev;
s_pQueLast-> m_pQuePrev = pQue;
if ( pQue->m_pQuePrev )
pQue -> m_pQuePrev -> m_pQueNext = pQue;
if(pQue&&pQue->m_pQuePrev)
ASSERT(pQue->m_nThreadId>pQue->m_pQuePrev->m_nThreadId);
if(pQue&&pQue->m_pQueNext)
ASSERT(pQue->m_nThreadId<pQue->m_pQueNext->m_nThreadId);
}
// Linkage
else if ( pQue->m_nThreadId > s_pQueLast->m_nThreadId )
{
pQue -> m_pQuePrev = s_pQueLast;
pQue -> m_pQueNext = s_pQueLast->m_pQueNext;
s_pQueLast-> m_pQueNext = pQue;
if ( pQue->m_pQueNext )
pQue -> m_pQueNext -> m_pQuePrev = pQue;
if(pQue&&pQue->m_pQuePrev)
ASSERT(pQue->m_nThreadId>pQue->m_pQuePrev->m_nThreadId);
if(pQue&&pQue->m_pQueNext)
ASSERT(pQue->m_nThreadId<pQue->m_pQueNext->m_nThreadId);
}
else
pQue=pQue;
// Tidy up, and
return pQue;
};
// Operations
public:
P2Pmsg*
GetP2Pmsg ( )
{ if ( m_oCListP2Pmsg.GetCount() )
return m_pP2Pmsg = m_oCListP2Pmsg.RemoveHead();
return m_pP2Pmsg = 0;
};
UINT
PutP2Pmsg ( P2Pmsg *pP2Pmsg, bool bPrepend )
{
ASSERT(VerifyP2Pmsg(pP2Pmsg));
auto *pTarget = reinterpret_cast<P2PeerTarget *>(pP2Pmsg->pTarget);
pTarget->P2PeerTarget::AssertValid();
auto *pTarget2 = (P2PeerTarget *)pP2Pmsg->pTarget;
pTarget2->P2PeerTarget::AssertValid();
if ( pP2Pmsg ) // Skip NULL pointers
{
VerifyP2Pmsg ( pP2Pmsg );
if ( pP2Pmsg->pTarget == nullptr )
pP2Pmsg -> pTarget = m_pTarget;
if ( bPrepend )
m_oCListP2Pmsg.AddHead ( pP2Pmsg );
else
m_oCListP2Pmsg.AddTail ( pP2Pmsg );
if ( !pP2Pmsg->nHubThreadID )
pP2Pmsg->nHubThreadID = m_nThreadId;
if ( !pP2Pmsg->hEventHub )
pP2Pmsg->hEventHub = m_hQueEvent;
}
// Wake the pump only when the producer is a DIFFERENT thread. When
// this pump posts to its own FIFO (e.g. the recv path parsing an
// inbound frame and re-posting it as a P2Pmsg), the pump is already
// running and will pick the message up on its next loop iteration -
// so the PostQueuedCompletionStatus + the spurious key=0 completion
// it drains are pure per-message overhead on the hot path. Passing
// m_nThreadId (was the ~0 sentinel, which never matched and defeated
// the same-thread guard in Wakeup()) restores that elision.
//
// W2 (p2p_PumpPerf.md) - wake coalescing: only signal the pump on the
// FIRST post since it last drained to empty. While m_bWakePosted is
// TRUE the pump either is running or has an outstanding completion, so
// it will pick this message up on a subsequent GetP2Pmsg() without a
// fresh wake. The pump clears m_bWakePosted the moment it observes an
// empty FIFO (see PumpP2Pmsg), and this producer holds m_oCSection, so
// any post that races the pump's drain-to-empty re-arms the wake.
if ( !m_bWakePosted )
{
m_bWakePosted = true;
Wakeup ( m_nThreadId ); // self-elides when producer == pump thread
}
//VerifyP2Pmsg ( pP2Pmsg ); problems because pP2Pmsg may no longer exist
return (UINT)m_oCListP2Pmsg.GetCount();
};
BOOL
Wakeup ( DWORD nP2PumpID )
{
if ( nP2PumpID == GetCurrentThreadId() )
return TRUE;
if ( m_hIOCP )
PostQueuedCompletionStatus( m_hIOCP, 0, 0, m_pOVERLAPPED );
else if ( m_hQueEvent )
return SetEvent ( m_hQueEvent );
return FALSE;
}
// Timers
public:
UINT
MakeTimerID ( )
{
TOP: UINT uiPitimerID = m_nThreadId*0x100+m_nPitimeID++;
POSITION pos = m_oCListP2PmsgPit.GetHeadPosition();
while ( pos )
{
P2Pmsg *pP2Pmsg = m_oCListP2PmsgPit.GetNext(pos);
if ( pP2Pmsg->iPitimeID == uiPitimerID )
goto TOP;
}
s_uPitimeID++;
return uiPitimerID;
}
UINT
SetTimer ( P2Pmsg *pP2Pmsg )
{
pP2Pmsg -> iPitimeID = MakeTimerID();
POSITION pos = m_oCListP2PmsgPit.GetTailPosition();
while ( pos )
{
if ( m_oCListP2PmsgPit.GetPrev(pos)->iPitime
<= pP2Pmsg->iPitime )
{
m_oCListP2PmsgPit.InsertAfter ( pos, pP2Pmsg );
return pP2Pmsg->iPitimeID;
}
};
m_oCListP2PmsgPit.AddHead ( pP2Pmsg );
return pP2Pmsg->iPitimeID;
}
P2Pmsg*
KillTimer ( UINT uPitimerID )
{
P2Pmsg *pP2Pmsg = 0;
POSITION pos = m_oCListP2PmsgPit.GetHeadPosition();
POSITION posKill;
while ( pos )
{
posKill = pos;
pP2Pmsg = m_oCListP2PmsgPit.GetNext(pos);
if ( pP2Pmsg->iPitimeID != uPitimerID )
continue;
m_oCListP2PmsgPit.RemoveAt ( posKill );
return pP2Pmsg; // Killed
}
return 0; // Not located
}
__int64
PollTimer ( )
{
if ( m_oCListP2PmsgPit.IsEmpty() )
return 0xFFFFFFFF;
return m_oCListP2PmsgPit.GetHead()->iPitime - _time64(0)*1000;
}
P2Pmsg*
GetTimer ( )
{
return m_oCListP2PmsgPit.RemoveHead();
}
// Properties
public:
UINT
GetCount ( )
{ return (UINT)m_oCListP2Pmsg.GetCount(); };
BOOL
IsPitEmpty ( )
{ return m_oCListP2PmsgPit.IsEmpty(); };
BOOL
IsQueEmpty ( )
{ return m_oCListP2Pmsg.IsEmpty(); };
// Signal-queue accessors (TSan Risk #3): m_oCListP2PsigID is written by
// SignalP2PmsgHub / SignalP2PmsgPump on ANY thread under m_oCSection, so the pump
// thread's own reads/pops must take the same lock (they raced under TSan otherwise).
UINT
SigCount ( )
{ P2PsafeCS oSafeCS = m_oCSection; return (UINT)m_oCListP2PsigID.GetCount(); }
P2PsigID
SigPop ( )
{ P2PsafeCS oSafeCS = m_oCSection;
return m_oCListP2PsigID.GetCount() > 0 ? m_oCListP2PsigID.RemoveHead() : 0; }
// Attributes
public:
CRITICAL_SECTION m_oCSection;
HANDLE m_hIOCP;
P2PmsgHubID m_nHubID;
P2PumpID m_nID;
P2PumpID m_nPumpID;
P2Paddr m_oP2Paddr;
DWORD m_wProps;
CStringADDR m_csName;
CStringADDR m_strFunc;
P2PmsgHub *m_hP2PmsgHubListen;
bool m_bListen;
// W2 (p2p_PumpPerf.md) - wake coalescing. TRUE once a cross-thread
// producer has signalled this pump and it has not yet drained its FIFO
// to empty; suppresses redundant PostQueuedCompletionStatus/SetEvent
// wakes (and the spurious key==0 completions the pump would drain) for
// the 2nd..Nth message of a burst. Guarded by m_oCSection (all
// PutP2Pmsg producers and the pump's empty-observation hold it), so a
// plain bool is race-free. Cleared by the pump the instant it observes
// an empty FIFO (i.e. just before it may park in GetQueuedCompletion
// Status), so any later producer - which must take m_oCSection strictly
// afterwards - always re-arms the wake: no lost-wake window.
bool m_bWakePosted;
OVERLAPPED *m_pOVERLAPPED;
HANDLE m_hQueEvent;
// F-S5-4. TRUE when this pump CREATED m_hQueEvent and must therefore
// close it, FALSE when the handle was handed in from outside and is
// somebody else's to close. The distinction is not decorative: the one
// external supplier is Factory(hEventPump,...) via StartupP2Pmsg(), so
// an unconditional CloseHandle() here would be a double close on a
// handle the caller still owns. m_hIOCP next to it needs no flag
// because the pump is the only thing that ever creates one.
bool m_bOwnQueEvent;
DWORD m_nThreadId;
P2PeerTarget *m_pTarget;
P2PmsgPump *m_pQuePrev;
P2PmsgPump *m_pQueNext;
USHORT m_nPitimeID;
P2Pmsg_Context *m_pContext;
bool m_bRedirect;
bool m_bRepump;
bool m_bP2Pexplorer;
DWORD m_dwExpumpMask;
static
P2PmsgPump *s_pQueLast;
P2PmsgHubMgr *m_pP2PmsgHubMgr;
P2Pmsg *m_pP2Pmsg;
CList<P2Pmsg*> m_oCListP2Pmsg;
CList<P2Pmsg*> m_oCListP2PmsgPit;
CList<P2PsigID> m_oCListP2PsigID;
};
typedef P2PSafePtr<P2PmsgPump> SP2PmsgPump;
P2PmsgPump*
P2PmsgPump::s_pQueLast = 0;
///////////////////////////////////////////////////////////////////////////////
// P2PmsgSink's
// NOTES: Manage the manufacture, translation, dispatch and
// life cycle of internal P2PmsgSinks's
typedef struct
{
P2PmsgSinkID nSinkID; // Sink identification code
P2PsysID nSysID; // Sys identification code
HWND hWnd; // Registered window, or
DWORD nThreadID; // thread, or
P2PumpID nPumpID; // P2Pump, or
P2PeventCBFnc pP2PeventCBFnc; // callback
P2PeerTarget *pTarget; // Nominated P2PeerTarget
DWORD dwCBKey; // Call back key
DWORD dwNotifications; // Registered Notifications.
} P2PmsgSinkReg;
typedef std::list<P2PmsgSinkReg*> P2PmsgSinkReg_list;
typedef std::pair<P2PmsgSinkReg*, P2PmsgSinkReg*> P2PmsgSinkReg_pair;
BOOL
CleanupP2PmsgSink ( P2PmsgHubMgr *pP2PmsgHub );
BOOL
StartupP2PmsgSink ( );
class P2PmsgSink
{
// Constructors and destructor
public:
P2PmsgSink ( UINT nSinkID )
{
m_nSinkID = nSinkID;
InitializeCriticalSection ( &m_oCSection );
};
~P2PmsgSink ( )
{
P2PmsgSinkReg_list::iterator it;
for ( it = m_oP2PmsgSinkReglist.begin(); it != m_oP2PmsgSinkReglist.end(); ++it )
delete (*it);
m_oP2PmsgSinkReglist.clear();
/*if ( m_pQuePrev )
m_pQuePrev->m_pQueNext = m_pQueNext;
if ( m_pQueNext )
m_pQueNext->m_pQuePrev = m_pQuePrev;
// Optimisation
if ( s_pQueLast == this )
{
if ( m_pQueNext )
s_pQueLast = m_pQueNext;
else if ( m_pQuePrev )
s_pQueLast = m_pQuePrev;
else
s_pQueLast = 0;
}*/
// Resources
DeleteCriticalSection ( &m_oCSection );
};
void
Verify ( )
{
}
// Registrations
public:
P2PmsgSinkReg*
RegisterTarget ( P2PeerTarget *pTarget, P2PsysID nP2PsysID )
{
P2PmsgSinkReg *pP2PmsgSinkReg = nullptr;
P2PmsgSinkReg_list::iterator it;
for ( it = m_oP2PmsgSinkReglist.begin(); it != m_oP2PmsgSinkReglist.end(); ++it )
{
pP2PmsgSinkReg = *it;
if ( pP2PmsgSinkReg->pTarget == pTarget &&
pP2PmsgSinkReg->nSysID == nP2PsysID )
return pP2PmsgSinkReg;
}
pP2PmsgSinkReg = new P2PmsgSinkReg;
ZeroMemory ( pP2PmsgSinkReg, sizeof(P2PmsgSinkReg) );
pP2PmsgSinkReg -> pTarget = pTarget;
pP2PmsgSinkReg -> nSysID = nP2PsysID;
m_oP2PmsgSinkReglist.push_back ( pP2PmsgSinkReg );
return pP2PmsgSinkReg;
}
BOOL
CancelTarget ( P2PeerTarget *pTarget, P2PsysID nP2PsysID )
{
int nItems = 0;
P2PmsgSinkReg *pP2PmsgSinkReg = nullptr;
P2PmsgSinkReg_list::iterator it;
for ( it = m_oP2PmsgSinkReglist.begin(); it != m_oP2PmsgSinkReglist.end(); )
{
pP2PmsgSinkReg = *it;
if ( pTarget &&
pP2PmsgSinkReg->pTarget != pTarget )
{ ++it; continue; }
if ( nP2PsysID &&
nP2PsysID != pP2PmsgSinkReg->nSysID )
{ ++it; continue; }
delete pP2PmsgSinkReg;
it = m_oP2PmsgSinkReglist.erase(it);
nItems++;
}
return nItems;
}
// Properties
public:
UINT
GetCount ( )
{ return (UINT)m_oP2PmsgSinkReglist.size(); };
// Attributes
public:
CRITICAL_SECTION m_oCSection;
P2PmsgSinkID m_nSinkID; // Sink identification code
CString m_strSinkname;
P2PmsgSinkReg_list m_oP2PmsgSinkReglist;
//HWND hWnd; // Registered window, or
//DWORD nThreadID; // thread, or
//P2PumpID nPumpID; // P2Pump, or
//P2PeventCBFnc pP2PeventCBFnc; // callback
//P2PeerTarget *pTarget; // Nominated P2PeerTarget
//DWORD dwCBKey; // Call back key
//DWORD dwNotifications; // Registered Notifications.
};
typedef std::map <P2PmsgSinkID, P2PmsgSink*> P2PmsgSinkmap;
typedef std::pair<P2PmsgSinkID, P2PmsgSink*> P2PmsgSinkpair;
//static P2PmsgSinkIDmap s_oP2PmsgSinkIDmap;
static CRITICAL_SECTION s_oCSectionP2PmsgSink;
static bool s_bStartupP2PmsgSink = false;
///////////////////////////////////////////////////////////////////////
// P2PmsgHubMgr
// NOTES: Manages CList of P2PmsgPump's
// : Single P2PmsgHub per Win32 thread context
//
// THE LOCK ORDER FOR THE TWO GLOBAL REGISTRIES, and it is not a preference.
//
// s_oCSectionP2PmsgHub BEFORE s_oCSectionP2PmsgPump
//
// Anything holding both takes them in that order, every time, without
// exception. A hub owns pumps, so the containing registry is the outer lock -
// and ten of the fifteen sites that hold both already read that way, which is
// why this is the order chosen rather than the other one.
//
// Five sites did not, all with the same shape: lock the pump registry, look a
// pump up, read its m_nHubID, then lock the hub registry to find the hub.
// CreateP2Pexpump, CloseP2Pexpump, PostP2PexpCon, EnumP2PexpCon and
// CloseP2PmsgPump. Against CreateP2PmsgHub(), which takes hub then pump, that
// is an AB-BA and TSan called it one - six lock-order-inversion reports across
// p2p_expreg, p2p_hubsnap and p2p_backpressure, 2026-09-17. They are now all
// hub-first. THE LOOKUP DOES NOT NEED TO MOVE and that is the whole trick:
// these locks guard the REGISTRIES, not a hub, so the hub lock can be taken
// before anybody knows which hub is wanted. It costs a little contention and
// nothing else.
//
// Same CLASS as the AB-BA fixed in 4236949 on 2026-07-10, different pair. That
// one was a transport CS against the pump registry, so only Dmx/Pipe/232 could
// trip it; this is the two global registries against each other, which no
// transport can avoid.
//
// A hub's OWN m_oCSection is a third lock and sits under both - several of the
// sites above swap the hub registry out for it once the hub is in hand.
//
static CMap<DWORD,DWORD,P2PmsgHubMgr*,P2PmsgHubMgr*> s_ThreadID_P2PmsgHub;
static CRITICAL_SECTION s_oCSectionP2PmsgHub;
static bool m_bP2PmsgExplorer_Hub = false;
class P2PmsgPumpMgr;
class P2PmsgHubMgr
{
// Constructors and destructor
public:
P2PmsgHubMgr ( )
{
m_hIOCP = 0;
m_pOVERLAPPED = 0;
m_oP2Paddr = L"";
m_pHub = 0;
m_nHubID = GetCurrentThreadId();
m_bP2PmsgExplorer = false;
m_pP2Pexplorer = 0;
m_pP2PmsgSinkmap = 0;
m_nSinksMax = 255;
s_ThreadID_P2PmsgHub.SetAt ( m_nHubID, this );
InitializeCriticalSection ( &m_oCSection );
};
~P2PmsgHubMgr ( )
{
// Resources
if ( m_hIOCP )
CloseHandle ( m_hIOCP );
if ( m_pOVERLAPPED )
delete m_pOVERLAPPED;
CleanupP2PmsgSink ( this );
s_ThreadID_P2PmsgHub.RemoveKey ( m_nHubID );
ASSERT(m_pP2PmsgSinkmap==nullptr);
// Delete the pump object(s) tracked in m_oCListP2PmsgPump (the msg pump, plus
// the explorer pump if one was created). ~P2PmsgPump closes each pump's
// completion port (m_hIOCP) and unregisters it from s_ThreadID_P2PmsgPump;
// m_apP2PmsgPump below owns only the pointer-storage array, not the objects.
// Without this the pump leaked once per hub, taking its Linux io_uring ring
// (an fd + pinned SQ/CQ memory) with it, so a few hundred hub create/destroy
// cycles exhausted RLIMIT_MEMLOCK and the next CreateIoCompletionPort() failed
// with ENOMEM (surfaced by the Phase-5 teardown stress under ASan). No other
// code deletes pumps, so this cannot double-free.
while ( m_oCListP2PmsgPump.GetCount() )
delete m_oCListP2PmsgPump.RemoveHead();
if ( m_apP2PmsgPump )
delete [] m_apP2PmsgPump;
// Match the ctor's InitializeCriticalSection ( &m_oCSection ). ~P2PmsgPump
// already deletes its own m_oCSection; the hub's was leaked every teardown
// (a fixed handle on Windows; on Linux the CRITICAL_SECTION shim's
// recursive_mutex, flagged by the Phase-5 teardown stress under ASan). All
// pump threads are joined by CloseHub before the hub destructs, so nothing
// still holds this section.
DeleteCriticalSection ( &m_oCSection );
//if ( m_pP2PmsgSinkmap )
//{
// P2PmsgSinkmap::iterator it;
// for ( it = m_pP2PmsgSinkmap->begin(); it != m_pP2PmsgSinkmap->end(); )
// delete it -> second;
// delete m_pP2PmsgSinkmap;
//}
};
void
Verify ( )
{
}
// Pumps
public:
P2PmsgPump*
CreateP2PmsgPump ( )
{
P2PmsgPump *pP2PmsgPump = new P2PmsgPump ( );
pP2PmsgPump -> m_bP2Pexplorer = false;
pP2PmsgPump -> m_nHubID = m_nHubID;
pP2PmsgPump -> m_pTarget = dynamic_cast<P2PeerTarget *>(m_pHub);
pP2PmsgPump -> m_pP2PmsgHubMgr = this;
m_oCListP2PmsgPump.AddTail ( pP2PmsgPump );
return pP2PmsgPump;
}
P2PmsgPump*
CreateP2Pexplorer ( )
{
ASSERT(!m_pP2Pexplorer);
m_pP2Pexplorer = new P2PmsgPump ( );
m_pP2Pexplorer -> m_bP2Pexplorer = true;
m_pP2Pexplorer -> m_nHubID = m_nHubID;
m_pP2Pexplorer -> m_pTarget = dynamic_cast<P2PeerTarget *>(m_pHub);
m_pP2Pexplorer -> m_pP2PmsgHubMgr = this;
m_oCListP2PmsgPump.AddTail ( m_pP2Pexplorer );
return m_pP2Pexplorer;
}
P2PmsgSink*
CreateP2PmsgSink ( LPCTNAM lpszSinkname )
{
if ( m_pP2PmsgSinkmap == nullptr )
m_pP2PmsgSinkmap = new P2PmsgSinkmap();
LOP:P2PmsgSinkID nSinkID = (UINT)rand() & (UINT)rand();