-
Notifications
You must be signed in to change notification settings - Fork 680
Expand file tree
/
Copy pathlibrary.c
More file actions
3159 lines (2690 loc) · 93.6 KB
/
Copy pathlibrary.c
File metadata and controls
3159 lines (2690 loc) · 93.6 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 (c) Microsoft Corporation.
Licensed under the MIT License.
Abstract:
General library functions
--*/
#include "precomp.h"
#ifdef QUIC_CLOG
#include "library.c.clog.h"
#endif
QUIC_LIBRARY MsQuicLib = { 0 };
QUIC_TRACE_RUNDOWN_CALLBACK QuicTraceRundown;
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicLibApplyLoadBalancingSetting(
void
);
_IRQL_requires_max_(DISPATCH_LEVEL)
void
QuicLibraryEvaluateSendRetryState(
void
);
CXPLAT_THREAD_CALLBACK(RegistrationCleanupWorker, Context);
CXPLAT_DATAPATH_FEATURES
QuicLibraryGetDatapathFeatures(
void
)
{
CXPLAT_SOCKET_FLAGS SocketFlags = CXPLAT_SOCKET_FLAG_NONE;
if (MsQuicLib.Settings.XdpEnabled) {
SocketFlags |= CXPLAT_SOCKET_FLAG_XDP;
}
CXPLAT_DBG_ASSERT(MsQuicLib.Datapath != NULL);
return CxPlatDataPathGetSupportedFeatures(MsQuicLib.Datapath, SocketFlags);
}
//
// Initializes all global variables if not already done.
//
_IRQL_requires_max_(PASSIVE_LEVEL)
void
MsQuicLibraryLoad(
void
)
{
if (InterlockedIncrement16(&MsQuicLib.LoadRefCount) == 1) {
//
// Load the library.
//
CxPlatSystemLoad();
CxPlatLockInitialize(&MsQuicLib.Lock);
CxPlatDispatchLockInitialize(&MsQuicLib.DatapathLock);
#if DEBUG
QuicLibraryInitializeDbg();
#endif
CxPlatListInitializeHead(&MsQuicLib.Registrations);
CxPlatListInitializeHead(&MsQuicLib.Bindings);
QuicTraceRundownCallback = QuicTraceRundown;
MsQuicLib.Loaded = TRUE;
MsQuicLib.Version[0] = VER_MAJOR;
MsQuicLib.Version[1] = VER_MINOR;
MsQuicLib.Version[2] = VER_PATCH;
MsQuicLib.Version[3] = VER_BUILD_ID;
MsQuicLib.GitHash = VER_GIT_HASH_STR;
}
}
//
// Uninitializes global variables if necessary.
//
_IRQL_requires_max_(PASSIVE_LEVEL)
void
MsQuicLibraryUnload(
void
)
{
CXPLAT_FRE_ASSERT(MsQuicLib.Loaded);
if (InterlockedDecrement16(&MsQuicLib.LoadRefCount) == 0) {
QUIC_LIB_VERIFY(MsQuicLib.OpenRefCount == 0);
QUIC_LIB_VERIFY(!MsQuicLib.InUse);
MsQuicLib.Loaded = FALSE;
#if DEBUG
QuicLibraryUninitializeDbg();
#endif
CxPlatDispatchLockUninitialize(&MsQuicLib.DatapathLock);
CxPlatLockUninitialize(&MsQuicLib.Lock);
CxPlatSystemUnload();
}
}
void
MsQuicCalculatePartitionMask(
void
)
{
CXPLAT_DBG_ASSERT(MsQuicLib.PartitionCount != 0);
CXPLAT_DBG_ASSERT(MsQuicLib.PartitionCount != 0xFFFF);
uint16_t PartitionCount = MsQuicLib.PartitionCount;
//
// The following operations set all bits following the higest bit to one.
//
PartitionCount |= (PartitionCount >> 1);
PartitionCount |= (PartitionCount >> 2);
PartitionCount |= (PartitionCount >> 4);
PartitionCount |= (PartitionCount >> 8);
MsQuicLib.PartitionMask = PartitionCount;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
MsQuicLibraryFreePartitions(
void
)
{
if (MsQuicLib.Partitions) {
for (uint16_t i = 0; i < MsQuicLib.PartitionCount; ++i) {
QuicPartitionUninitialize(&MsQuicLib.Partitions[i]);
}
CXPLAT_FREE(MsQuicLib.Partitions, QUIC_POOL_PERPROC);
MsQuicLib.Partitions = NULL;
}
}
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
QuicLibraryInitializePartitions(
void
)
{
CXPLAT_DBG_ASSERT(MsQuicLib.Partitions == NULL);
MsQuicLib.PartitionCount = (uint16_t)CxPlatProcCount();
CXPLAT_FRE_ASSERT(MsQuicLib.PartitionCount > 0);
uint16_t* ProcessorList = NULL;
#ifndef _KERNEL_MODE
if (MsQuicLib.WorkerPool != NULL) {
MsQuicLib.CustomPartitions = TRUE;
MsQuicLib.PartitionCount = (uint16_t)CxPlatWorkerPoolGetCount(MsQuicLib.WorkerPool);
} else if (
#else
if (
#endif
MsQuicLib.ExecutionConfig &&
MsQuicLib.ExecutionConfig->ProcessorCount &&
MsQuicLib.ExecutionConfig->ProcessorCount != MsQuicLib.PartitionCount) {
//
// The app has specified a non-default custom set of processors to
// create partitions one.
//
MsQuicLib.CustomPartitions = TRUE;
MsQuicLib.PartitionCount = (uint16_t)MsQuicLib.ExecutionConfig->ProcessorCount;
ProcessorList = MsQuicLib.ExecutionConfig->ProcessorList;
} else {
MsQuicLib.CustomPartitions = FALSE;
uint32_t MaxPartitionCount = QUIC_MAX_PARTITION_COUNT;
if (MsQuicLib.Storage != NULL) {
uint32_t MaxPartitionCountLen = sizeof(MaxPartitionCount);
CxPlatStorageReadValue(
MsQuicLib.Storage,
QUIC_SETTING_MAX_PARTITION_COUNT,
(uint8_t*)&MaxPartitionCount,
&MaxPartitionCountLen);
if (MaxPartitionCount == 0) {
MaxPartitionCount = QUIC_MAX_PARTITION_COUNT;
}
}
if (MsQuicLib.PartitionCount > MaxPartitionCount) {
MsQuicLib.PartitionCount = (uint16_t)MaxPartitionCount;
}
}
CXPLAT_FRE_ASSERT(MsQuicLib.PartitionCount > 0);
MsQuicCalculatePartitionMask();
const size_t PartitionsSize = MsQuicLib.PartitionCount * sizeof(QUIC_PARTITION);
MsQuicLib.Partitions = CXPLAT_ALLOC_NONPAGED(PartitionsSize, QUIC_POOL_PERPROC);
if (MsQuicLib.Partitions == NULL) {
QuicTraceEvent(
AllocFailure,
"Allocation of '%s' failed. (%llu bytes)",
"Library Partitions",
PartitionsSize);
return QUIC_STATUS_OUT_OF_MEMORY;
}
CxPlatZeroMemory(MsQuicLib.Partitions, PartitionsSize);
uint8_t ResetHashKey[20];
CxPlatRandom(sizeof(ResetHashKey), ResetHashKey);
uint8_t RetrySecret[CXPLAT_AEAD_AES_256_GCM_SIZE];
CxPlatRandom(sizeof(RetrySecret), RetrySecret);
QUIC_STATELESS_RETRY_CONFIG RetryConfig;
RetryConfig.SecretLength = sizeof(RetrySecret);
RetryConfig.Secret = RetrySecret;
RetryConfig.RotationMs = QUIC_STATELESS_RETRY_KEY_LIFETIME_MS;
RetryConfig.Algorithm = QUIC_AEAD_ALGORITHM_AES_256_GCM;
QUIC_STATUS Status = QuicLibrarySetRetryKeyConfig(&RetryConfig);
CXPLAT_FRE_ASSERT(QUIC_SUCCEEDED(Status));
CxPlatSecureZeroMemory(RetrySecret, sizeof(RetrySecret));
uint16_t i;
for (i = 0; i < MsQuicLib.PartitionCount; ++i) {
Status =
QuicPartitionInitialize(
&MsQuicLib.Partitions[i],
i,
#ifndef _KERNEL_MODE
ProcessorList ? ProcessorList[i] :
(MsQuicLib.CustomPartitions ?
(uint16_t)CxPlatWorkerPoolGetIdealProcessor(MsQuicLib.WorkerPool, i) :
i),
#else
ProcessorList ? ProcessorList[i] : i,
#endif
CXPLAT_HASH_SHA256,
ResetHashKey,
sizeof(ResetHashKey));
if (QUIC_FAILED(Status)) {
goto Error;
}
}
CxPlatSecureZeroMemory(ResetHashKey, sizeof(ResetHashKey));
return QUIC_STATUS_SUCCESS;
Error:
CxPlatSecureZeroMemory(ResetHashKey, sizeof(ResetHashKey));
for (uint16_t j = 0; j < i; ++j) {
QuicPartitionUninitialize(&MsQuicLib.Partitions[j]);
}
CXPLAT_FREE(MsQuicLib.Partitions, QUIC_POOL_PERPROC);
MsQuicLib.Partitions = NULL;
return Status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicLibrarySumPerfCounters(
_Out_writes_bytes_(BufferLength) uint8_t* Buffer,
_In_ uint32_t BufferLength
)
{
if (MsQuicLib.Partitions == NULL) {
CxPlatZeroMemory(Buffer, BufferLength);
return;
}
CXPLAT_DBG_ASSERT(BufferLength == (BufferLength / sizeof(uint64_t) * sizeof(uint64_t)));
CXPLAT_DBG_ASSERT(BufferLength <= sizeof(MsQuicLib.Partitions[0].PerfCounters));
const uint32_t CountersPerBuffer = BufferLength / sizeof(int64_t);
int64_t* const Counters = (int64_t*)Buffer;
memcpy(Buffer, MsQuicLib.Partitions[0].PerfCounters, BufferLength);
for (uint32_t ProcIndex = 1; ProcIndex < MsQuicLib.PartitionCount; ++ProcIndex) {
for (uint32_t CounterIndex = 0; CounterIndex < CountersPerBuffer; ++CounterIndex) {
Counters[CounterIndex] += MsQuicLib.Partitions[ProcIndex].PerfCounters[CounterIndex];
}
}
//
// Zero any counters that are still negative after summation.
//
for (uint32_t CounterIndex = 0; CounterIndex < CountersPerBuffer; ++CounterIndex) {
if (Counters[CounterIndex] < 0) {
Counters[CounterIndex] = 0;
}
}
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicLibrarySumPerfCountersExternal(
_Out_writes_bytes_(BufferLength) uint8_t* Buffer,
_In_ uint32_t BufferLength
)
{
CxPlatLockAcquire(&MsQuicLib.Lock);
if (MsQuicLib.OpenRefCount == 0) {
CxPlatZeroMemory(Buffer, BufferLength);
} else {
QuicLibrarySumPerfCounters(Buffer, BufferLength);
}
CxPlatLockRelease(&MsQuicLib.Lock);
}
_IRQL_requires_max_(DISPATCH_LEVEL)
void
QuicPerfCounterSnapShot(
_In_ uint64_t TimeDiffUs
)
{
UNREFERENCED_PARAMETER(TimeDiffUs); // Only used in asserts below.
int64_t PerfCounterSamples[QUIC_PERF_COUNTER_MAX];
QuicLibrarySumPerfCounters(
(uint8_t*)PerfCounterSamples,
sizeof(PerfCounterSamples));
QuicTraceEvent(
PerfCountersRundown,
"[ lib] Perf counters Rundown, Counters=%!CID!",
CASTED_CLOG_BYTEARRAY16(sizeof(PerfCounterSamples), PerfCounterSamples));
// Ensure a perf counter stays below a given max Hz/frequency.
#define QUIC_COUNTER_LIMIT_HZ(TYPE, LIMIT_PER_SECOND) \
CXPLAT_TEL_ASSERT( \
((1000 * 1000 * (PerfCounterSamples[TYPE] - MsQuicLib.PerfCounterSamples[TYPE])) / TimeDiffUs) < LIMIT_PER_SECOND)
// Ensures a perf counter doesn't consistently (both samples) go above a give max value.
#define QUIC_COUNTER_CAP(TYPE, MAX_LIMIT) \
CXPLAT_TEL_ASSERT( \
PerfCounterSamples[TYPE] < MAX_LIMIT && \
MsQuicLib.PerfCounterSamples[TYPE] < MAX_LIMIT)
#ifndef DEBUG // Only in release mode
//
// Some heuristics to ensure that bad things aren't happening. TODO - these
// values should be configurable dynamically, somehow.
//
QUIC_COUNTER_LIMIT_HZ(QUIC_PERF_COUNTER_CONN_HANDSHAKE_FAIL, 1000000); // Don't have 1 million failed handshakes per second
QUIC_COUNTER_CAP(QUIC_PERF_COUNTER_CONN_QUEUE_DEPTH, 100000); // Don't maintain huge queue depths
#endif
CxPlatCopyMemory(
MsQuicLib.PerfCounterSamples,
PerfCounterSamples,
sizeof(PerfCounterSamples));
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
QuicLibraryLoadRetryConfig(
_In_ CXPLAT_STORAGE* Storage
)
{
QUIC_STATELESS_RETRY_CONFIG RetryConfig = { 0 };
uint8_t Secret[CXPLAT_AEAD_MAX_SIZE] = { 0 };
uint32_t SecretLength = sizeof(Secret);
uint32_t KeyRotationMs;
uint32_t RotationLength = sizeof(KeyRotationMs);
uint32_t KeyAlgorithm;
uint32_t AlgLength = sizeof(KeyAlgorithm);
BOOLEAN SettingChanged = FALSE;
BOOLEAN SecretChanged = FALSE;
BOOLEAN AlgorithmChanged = FALSE;
//
// Initialize RetryConfig with current settings. Secret is set to a
// sentinel value that won't get copied when only RotationMs changes.
//
CxPlatDispatchRwLockAcquireShared(&MsQuicLib.StatelessRetry.Lock, PrevIrql);
RetryConfig.Algorithm = (QUIC_AEAD_ALGORITHM_TYPE)MsQuicLib.StatelessRetry.AeadAlgorithm;
RetryConfig.RotationMs = MsQuicLib.StatelessRetry.KeyRotationMs;
RetryConfig.SecretLength = MsQuicLib.StatelessRetry.SecretLength;
RetryConfig.Secret = MsQuicLib.StatelessRetry.BaseSecret;
CxPlatDispatchRwLockReleaseShared(&MsQuicLib.StatelessRetry.Lock, PrevIrql);
if (QUIC_SUCCEEDED(
CxPlatStorageReadValue(
Storage,
QUIC_SETTING_RETRY_KEY_ROTATION_MS,
(uint8_t*)&KeyRotationMs,
&RotationLength))) {
RetryConfig.RotationMs = KeyRotationMs;
SettingChanged = TRUE;
}
if (QUIC_SUCCEEDED(
CxPlatStorageReadValue(
Storage,
QUIC_SETTING_RETRY_KEY_ALGORITHM,
(uint8_t*)&KeyAlgorithm,
&AlgLength))) {
AlgorithmChanged = TRUE;
}
if (QUIC_SUCCEEDED(
CxPlatStorageReadValue(
Storage,
QUIC_SETTING_RETRY_KEY_SECRET,
Secret,
&SecretLength))) {
SecretChanged = TRUE;
}
if (SecretChanged && AlgorithmChanged) {
//
// Both secret and algorithm must be present in the registry for
// either to take effect.
// We expect admins to delete the existing values when changing
// algorithm or secret, to prevent split state. See Settings.md.
//
RetryConfig.Algorithm = KeyAlgorithm;
RetryConfig.Secret = Secret;
RetryConfig.SecretLength = SecretLength;
SettingChanged = TRUE;
}
if (SettingChanged) {
QuicLibrarySetRetryKeyConfig(&RetryConfig);
}
CxPlatSecureZeroMemory(&Secret, sizeof(Secret));
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
MsQuicLibraryOnSettingsChanged(
_In_ BOOLEAN UpdateRegistrations
)
{
if (!MsQuicLib.InUse) {
//
// Load balancing settings can only change before the library is
// officially "in use", otherwise existing connections would be
// destroyed.
//
QuicLibApplyLoadBalancingSetting();
}
MsQuicLib.HandshakeMemoryLimit =
(MsQuicLib.Settings.RetryMemoryLimit * CxPlatTotalMemory) / UINT16_MAX;
QuicLibraryEvaluateSendRetryState();
if (UpdateRegistrations) {
CxPlatLockAcquire(&MsQuicLib.Lock);
for (CXPLAT_LIST_ENTRY* Link = MsQuicLib.Registrations.Flink;
Link != &MsQuicLib.Registrations;
Link = Link->Flink) {
QuicRegistrationSettingsChanged(
CXPLAT_CONTAINING_RECORD(Link, QUIC_REGISTRATION, Link));
}
CxPlatLockRelease(&MsQuicLib.Lock);
}
}
_IRQL_requires_max_(PASSIVE_LEVEL)
_Function_class_(CXPLAT_STORAGE_CHANGE_CALLBACK)
void
MsQuicLibraryReadSettings(
_In_opt_ void* Context
)
{
QuicSettingsSetDefault(&MsQuicLib.Settings);
if (MsQuicLib.Storage != NULL) {
QuicSettingsLoad(&MsQuicLib.Settings, MsQuicLib.Storage);
QuicLibraryLoadRetryConfig(MsQuicLib.Storage);
}
QuicTraceLogInfo(
LibrarySettingsUpdated,
"[ lib] Settings %p Updated",
&MsQuicLib.Settings);
QuicSettingsDump(&MsQuicLib.Settings);
MsQuicLibraryOnSettingsChanged(Context != NULL);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
MsQuicLibraryInitialize(
void
)
{
QUIC_STATUS Status = QUIC_STATUS_SUCCESS;
BOOLEAN PlatformInitialized = FALSE;
Status = CxPlatInitialize();
if (QUIC_FAILED(Status)) {
goto Error; // Cannot log anything if platform failed to initialize.
}
CXPLAT_DBG_ASSERT(US_TO_MS(CxPlatGetTimerResolution()) + 1 <= UINT8_MAX);
MsQuicLib.TimerResolutionMs = (uint8_t)US_TO_MS(CxPlatGetTimerResolution()) + 1;
MsQuicLib.PerfCounterSamplesTime = CxPlatTimeUs64();
CxPlatZeroMemory(MsQuicLib.PerfCounterSamples, sizeof(MsQuicLib.PerfCounterSamples));
CxPlatRandom(sizeof(MsQuicLib.ToeplitzHash.HashKey), MsQuicLib.ToeplitzHash.HashKey);
MsQuicLib.ToeplitzHash.InputSize = CXPLAT_TOEPLITZ_INPUT_SIZE_QUIC;
CxPlatToeplitzHashInitialize(&MsQuicLib.ToeplitzHash);
CxPlatDispatchRwLockInitialize(&MsQuicLib.StatelessRetry.Lock);
CxPlatZeroMemory(&MsQuicLib.Settings, sizeof(MsQuicLib.Settings));
CxPlatLockInitialize(&MsQuicLib.RegistrationCloseCleanupLock);
CxPlatEventInitialize(&MsQuicLib.RegistrationCloseCleanupEvent, FALSE, FALSE);
MsQuicLib.RegistrationCloseCleanupShutdown = FALSE;
CxPlatListInitializeHead(&MsQuicLib.RegistrationCloseCleanupList);
CxPlatRundownInitialize(&MsQuicLib.RegistrationCloseCleanupRundown);
PlatformInitialized = TRUE;
Status =
CxPlatStorageOpen(
NULL,
MsQuicLibraryReadSettings,
(void*)TRUE, // Non-null indicates registrations should be updated
CXPLAT_STORAGE_OPEN_FLAG_READ,
&MsQuicLib.Storage);
if (QUIC_FAILED(Status)) {
QuicTraceLogWarning(
LibraryStorageOpenFailed,
"[ lib] Failed to open global settings, 0x%x",
Status);
// Non-fatal, as the process may not have access
}
MsQuicLibraryReadSettings(NULL); // NULL means don't update registrations.
CXPLAT_THREAD_CONFIG ThreadConfig = {
0,
0,
"RegistrationCleanupWorker",
RegistrationCleanupWorker,
NULL,
};
Status = CxPlatThreadCreate(&ThreadConfig, &MsQuicLib.RegistrationCloseCleanupWorker);
if (QUIC_FAILED(Status)) {
goto Error;
}
uint32_t CompatibilityListByteLength = 0;
QuicVersionNegotiationExtGenerateCompatibleVersionsList(
QUIC_VERSION_LATEST,
DefaultSupportedVersionsList,
ARRAYSIZE(DefaultSupportedVersionsList),
NULL,
&CompatibilityListByteLength);
MsQuicLib.DefaultCompatibilityList =
CXPLAT_ALLOC_NONPAGED(CompatibilityListByteLength, QUIC_POOL_DEFAULT_COMPAT_VER_LIST);
if (MsQuicLib.DefaultCompatibilityList == NULL) {
QuicTraceEvent(
AllocFailure,
"Allocation of '%s' failed. (%llu bytes)", "default compatibility list",
CompatibilityListByteLength);
Status = QUIC_STATUS_OUT_OF_MEMORY;
goto Error;
}
MsQuicLib.DefaultCompatibilityListLength = CompatibilityListByteLength / sizeof(uint32_t);
if (QUIC_FAILED(
QuicVersionNegotiationExtGenerateCompatibleVersionsList(
QUIC_VERSION_LATEST,
DefaultSupportedVersionsList,
ARRAYSIZE(DefaultSupportedVersionsList),
(uint8_t*)MsQuicLib.DefaultCompatibilityList,
&CompatibilityListByteLength))) {
goto Error;
}
QuicTraceEvent(
LibraryInitializedV3,
"[ lib] Initialized");
QuicTraceEvent(
LibraryVersion,
"[ lib] Version %u.%u.%u.%u",
MsQuicLib.Version[0],
MsQuicLib.Version[1],
MsQuicLib.Version[2],
MsQuicLib.Version[3]);
#ifdef CxPlatVerifierEnabled
uint32_t Flags;
MsQuicLib.IsVerifying = CxPlatVerifierEnabled(Flags);
if (MsQuicLib.IsVerifying) {
#ifdef CxPlatVerifierEnabledByAddr
QuicTraceLogInfo(
LibraryVerifierEnabledPerRegistration,
"[ lib] Verifing enabled, per-registration!");
#else
QuicTraceLogInfo(
LibraryVerifierEnabled,
"[ lib] Verifing enabled for all!");
#endif
}
#endif
Error:
if (QUIC_FAILED(Status)) {
if (MsQuicLib.RegistrationCloseCleanupWorker) {
MsQuicLib.RegistrationCloseCleanupShutdown = TRUE;
CxPlatEventSet(MsQuicLib.RegistrationCloseCleanupEvent);
CxPlatThreadWait(&MsQuicLib.RegistrationCloseCleanupWorker);
CxPlatThreadDelete(&MsQuicLib.RegistrationCloseCleanupWorker);
MsQuicLib.RegistrationCloseCleanupWorker = 0;
}
if (MsQuicLib.Storage != NULL) {
CxPlatStorageClose(MsQuicLib.Storage);
MsQuicLib.Storage = NULL;
}
if (MsQuicLib.DefaultCompatibilityList != NULL) {
CXPLAT_FREE(MsQuicLib.DefaultCompatibilityList, QUIC_POOL_DEFAULT_COMPAT_VER_LIST);
MsQuicLib.DefaultCompatibilityList = NULL;
}
if (PlatformInitialized) {
CxPlatRundownUninitialize(&MsQuicLib.RegistrationCloseCleanupRundown);
CxPlatEventUninitialize(MsQuicLib.RegistrationCloseCleanupEvent);
CxPlatLockUninitialize(&MsQuicLib.RegistrationCloseCleanupLock);
CxPlatDispatchRwLockUninitialize(&MsQuicLib.StatelessRetry.Lock);
CxPlatUninitialize();
}
}
return Status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
MsQuicLibraryLazyUninitialize(
void
)
{
#if DEBUG
CXPLAT_DATAPATH* CleanUpDatapath = NULL;
#endif
//
// The library's stateless registration may still have half-opened
// connections that need to be cleaned up before all the bindings and
// sockets can be cleaned up. Kick off a clean up of those connections.
//
if (MsQuicLib.StatelessRegistration != NULL) {
//
// Best effort to clean up existing connections.
//
MsQuicRegistrationShutdown(
(HQUIC)MsQuicLib.StatelessRegistration,
QUIC_CONNECTION_SHUTDOWN_FLAG_SILENT,
0);
}
//
// Clean up the stateless registration that might have any leftovers.
//
if (MsQuicLib.StatelessRegistration != NULL) {
MsQuicRegistrationClose(
(HQUIC)MsQuicLib.StatelessRegistration);
MsQuicLib.StatelessRegistration = NULL;
}
//
// If you hit this assert, MsQuic API is trying to be unloaded without
// first closing all registrations.
//
CXPLAT_TEL_ASSERT(CxPlatListIsEmpty(&MsQuicLib.Registrations));
//
// Clean up the data path, which will start the final clean up of the
// socket layer. This is generally async and doesn't block until the
// call to CxPlatUninitialize below.
//
if (MsQuicLib.Datapath != NULL) {
#if DEBUG
CleanUpDatapath = MsQuicLib.Datapath;
UNREFERENCED_PARAMETER(CleanUpDatapath);
#endif
CxPlatDataPathUninitialize(MsQuicLib.Datapath);
MsQuicLib.Datapath = NULL;
}
#if DEBUG
//
// If you hit this assert, MsQuic API is trying to be unloaded without
// first cleaning up all connections.
//
CXPLAT_TEL_ASSERT(MsQuicLib.ConnectionCount == 0);
#endif
#if DEBUG
uint64_t PerfCounters[QUIC_PERF_COUNTER_MAX];
QuicLibrarySumPerfCounters((uint8_t*)PerfCounters, sizeof(PerfCounters));
//
// All active/current counters should be zero by cleanup.
//
CXPLAT_DBG_ASSERT(PerfCounters[QUIC_PERF_COUNTER_CONN_ACTIVE] == 0);
CXPLAT_DBG_ASSERT(PerfCounters[QUIC_PERF_COUNTER_CONN_CONNECTED] == 0);
CXPLAT_DBG_ASSERT(PerfCounters[QUIC_PERF_COUNTER_STRM_ACTIVE] == 0);
CXPLAT_DBG_ASSERT(PerfCounters[QUIC_PERF_COUNTER_CONN_QUEUE_DEPTH] == 0);
CXPLAT_DBG_ASSERT(PerfCounters[QUIC_PERF_COUNTER_CONN_OPER_QUEUE_DEPTH] == 0);
CXPLAT_DBG_ASSERT(PerfCounters[QUIC_PERF_COUNTER_WORK_OPER_QUEUE_DEPTH] == 0);
#endif
//
// If you hit this assert, MsQuic API is trying to be unloaded without
// first being cleaned up all listeners and connections.
//
CXPLAT_TEL_ASSERT(CxPlatListIsEmpty(&MsQuicLib.Bindings));
MsQuicLibraryFreePartitions();
MsQuicLib.LazyInitComplete = FALSE;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
MsQuicLibraryUninitialize(
void
)
{
QuicTraceEvent(
LibraryUninitialized,
"[ lib] Uninitialized");
MsQuicLibraryLazyUninitialize();
if (MsQuicLib.Storage != NULL) {
CxPlatStorageClose(MsQuicLib.Storage);
MsQuicLib.Storage = NULL;
}
QuicSettingsCleanup(&MsQuicLib.Settings);
CXPLAT_FREE(MsQuicLib.DefaultCompatibilityList, QUIC_POOL_DEFAULT_COMPAT_VER_LIST);
MsQuicLib.DefaultCompatibilityList = NULL;
CxPlatDispatchRwLockUninitialize(&MsQuicLib.StatelessRetry.Lock);
CxPlatRundownReleaseAndWait(&MsQuicLib.RegistrationCloseCleanupRundown);
MsQuicLib.RegistrationCloseCleanupShutdown = TRUE;
CxPlatEventSet(MsQuicLib.RegistrationCloseCleanupEvent);
CxPlatThreadWait(&MsQuicLib.RegistrationCloseCleanupWorker);
CxPlatThreadDelete(&MsQuicLib.RegistrationCloseCleanupWorker);
MsQuicLib.RegistrationCloseCleanupWorker = 0;
CxPlatEventUninitialize(MsQuicLib.RegistrationCloseCleanupEvent);
CxPlatLockUninitialize(&MsQuicLib.RegistrationCloseCleanupLock);
if (MsQuicLib.ExecutionConfig != NULL) {
CXPLAT_FREE(MsQuicLib.ExecutionConfig, QUIC_POOL_EXECUTION_CONFIG);
MsQuicLib.ExecutionConfig = NULL;
}
if (MsQuicLib.XdpMapConfigs != NULL) {
CXPLAT_FREE(MsQuicLib.XdpMapConfigs, QUIC_POOL_XDP_MAP_CONFIG);
MsQuicLib.XdpMapConfigs = NULL;
MsQuicLib.XdpMapConfigCount = 0;
}
#ifndef _KERNEL_MODE
CxPlatWorkerPoolDelete(MsQuicLib.WorkerPool, CXPLAT_WORKER_POOL_REF_LIBRARY);
MsQuicLib.WorkerPool = NULL;
#endif
CxPlatUninitialize();
}
CXPLAT_THREAD_CALLBACK(RegistrationCleanupWorker, Context)
{
UNREFERENCED_PARAMETER(Context);
while (!MsQuicLib.RegistrationCloseCleanupShutdown) {
CxPlatEventWaitForever(MsQuicLib.RegistrationCloseCleanupEvent);
CxPlatLockAcquire(&MsQuicLib.RegistrationCloseCleanupLock);
while (!CxPlatListIsEmpty(&MsQuicLib.RegistrationCloseCleanupList)) {
CXPLAT_LIST_ENTRY* Entry =
CxPlatListRemoveHead(&MsQuicLib.RegistrationCloseCleanupList);
QUIC_REGISTRATION* Registration =
CXPLAT_CONTAINING_RECORD(Entry, QUIC_REGISTRATION, CloseCleanupEntry);
CxPlatLockRelease(&MsQuicLib.RegistrationCloseCleanupLock);
CxPlatThreadWait(&Registration->CloseThread);
CxPlatThreadDelete(&Registration->CloseThread);
#if DEBUG
QuicLibraryUntrackDbgObject(
QUIC_DBG_OBJECT_TYPE_REGISTRATION, &Registration->DbgObjectLink);
#endif
CXPLAT_FREE(Registration, QUIC_POOL_REGISTRATION);
CxPlatRundownRelease(&MsQuicLib.RegistrationCloseCleanupRundown);
CxPlatLockAcquire(&MsQuicLib.RegistrationCloseCleanupLock);
}
CxPlatLockRelease(&MsQuicLib.RegistrationCloseCleanupLock);
}
CXPLAT_THREAD_RETURN(QUIC_STATUS_SUCCESS);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
MsQuicAddRef(
void
)
{
//
// If you hit this assert, you are trying to call MsQuic API without
// actually loading/starting the library/driver.
//
CXPLAT_TEL_ASSERT(MsQuicLib.Loaded);
if (!MsQuicLib.Loaded) {
return QUIC_STATUS_INVALID_STATE;
}
QUIC_STATUS Status = QUIC_STATUS_SUCCESS;
CxPlatLockAcquire(&MsQuicLib.Lock);
//
// Increment global ref count, and if this is the first ref, initialize all
// the global library state.
//
if (++MsQuicLib.OpenRefCount == 1) {
Status = MsQuicLibraryInitialize();
if (QUIC_FAILED(Status)) {
MsQuicLib.OpenRefCount--;
goto Error;
}
}
QuicTraceEvent(
LibraryAddRef,
"[ lib] AddRef");
Error:
CxPlatLockRelease(&MsQuicLib.Lock);
return Status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
void
MsQuicRelease(
void
)
{
CxPlatLockAcquire(&MsQuicLib.Lock);
//
// Decrement global ref count and uninitialize the library if this is the
// last ref.
//
CXPLAT_FRE_ASSERT(MsQuicLib.OpenRefCount > 0);
QuicTraceEvent(
LibraryRelease,
"[ lib] Release");
if (--MsQuicLib.OpenRefCount == 0) {
MsQuicLibraryUninitialize();
}
CxPlatLockRelease(&MsQuicLib.Lock);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_STATUS
QuicLibraryLazyInitialize(
BOOLEAN AcquireLock
)
{
const CXPLAT_UDP_DATAPATH_CALLBACKS DatapathCallbacks = {
QuicBindingReceive,
QuicBindingUnreachable,
};
QUIC_STATUS Status = QUIC_STATUS_SUCCESS;
BOOLEAN CreatedWorkerPool = FALSE;
if (AcquireLock) {
CxPlatLockAcquire(&MsQuicLib.Lock);
}
if (MsQuicLib.LazyInitComplete) {
goto Exit;
}
CXPLAT_DBG_ASSERT(MsQuicLib.Partitions == NULL);
CXPLAT_DBG_ASSERT(MsQuicLib.Datapath == NULL);
Status = QuicLibraryInitializePartitions();
if (QUIC_FAILED(Status)) {
goto Exit;
}
#ifndef _KERNEL_MODE
if (MsQuicLib.WorkerPool == NULL) {
MsQuicLib.WorkerPool = CxPlatWorkerPoolCreate(MsQuicLib.ExecutionConfig, CXPLAT_WORKER_POOL_REF_LIBRARY);
if (!MsQuicLib.WorkerPool) {
Status = QUIC_STATUS_OUT_OF_MEMORY;
MsQuicLibraryFreePartitions();
goto Exit;
}
CreatedWorkerPool = TRUE;
}
#endif
CXPLAT_DATAPATH_INIT_CONFIG InitConfig = {0};
InitConfig.EnableDscpOnRecv = MsQuicLib.EnableDscpOnRecv;
InitConfig.XdpMapConfigs = MsQuicLib.XdpMapConfigs;
InitConfig.XdpMapConfigCount = MsQuicLib.XdpMapConfigCount;
Status =
CxPlatDataPathInitialize(
sizeof(QUIC_RX_PACKET),
&DatapathCallbacks,
NULL, // TcpCallbacks
MsQuicLib.WorkerPool,
&InitConfig,
&MsQuicLib.Datapath);
if (QUIC_SUCCEEDED(Status)) {
QuicTraceEvent(
DataPathInitialized,
"[data] Initialized, DatapathFeatures=%u",
QuicLibraryGetDatapathFeatures());
if (MsQuicLib.ExecutionConfig &&
MsQuicLib.ExecutionConfig->PollingIdleTimeoutUs != 0) {
CxPlatDataPathUpdatePollingIdleTimeout(
MsQuicLib.Datapath,
MsQuicLib.ExecutionConfig->PollingIdleTimeoutUs);
}
} else {
MsQuicLibraryFreePartitions();
#ifndef _KERNEL_MODE
if (CreatedWorkerPool) {
CxPlatWorkerPoolDelete(MsQuicLib.WorkerPool, CXPLAT_WORKER_POOL_REF_LIBRARY);
MsQuicLib.WorkerPool = NULL;
}
#endif
goto Exit;
}
CXPLAT_DBG_ASSERT(MsQuicLib.Partitions != NULL);
CXPLAT_DBG_ASSERT(MsQuicLib.Datapath != NULL);
MsQuicLib.LazyInitComplete = TRUE;
Exit:
if (AcquireLock) {
CxPlatLockRelease(&MsQuicLib.Lock);
}
return Status;
}
_IRQL_requires_max_(DISPATCH_LEVEL)
void
QUIC_API
MsQuicSetContext(
_In_ _Pre_defensive_ HQUIC Handle,
_In_opt_ void* Context
)
{
if (Handle != NULL) {
Handle->ClientContext = Context;
}
}
_IRQL_requires_max_(DISPATCH_LEVEL)
void*
QUIC_API
MsQuicGetContext(
_In_ _Pre_defensive_ HQUIC Handle
)
{
return Handle == NULL ? NULL : Handle->ClientContext;
}
#pragma warning(disable:28023) // The function being assigned or passed should have a _Function_class_ annotation
_IRQL_requires_max_(DISPATCH_LEVEL)
void
QUIC_API
MsQuicSetCallbackHandler(
_In_ _Pre_defensive_ HQUIC Handle,
_In_ void* Handler,
_In_opt_ void* Context
)
{
if (Handle == NULL) {
return;
}