-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathSocketAsyncContext.Unix.cs
More file actions
2331 lines (1947 loc) · 98.9 KB
/
Copy pathSocketAsyncContext.Unix.cs
File metadata and controls
2331 lines (1947 loc) · 98.9 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Sockets
{
// Note on asynchronous behavior here:
// The asynchronous socket operations here generally do the following:
// (1) If the operation queue is Ready (queue is empty), try to perform the operation immediately, non-blocking.
// If this completes (i.e. does not return EWOULDBLOCK), then we return the results immediately
// for both success (SocketError.Success) or failure.
// No callback will happen; callers are expected to handle these synchronous completions themselves.
// (2) If EWOULDBLOCK is returned, or the queue is not empty, then we enqueue an operation to the
// appropriate queue and return SocketError.IOPending.
// Enqueuing itself may fail because the socket is closed before the operation can be enqueued;
// in this case, we return SocketError.OperationAborted (which matches what Winsock would return in this case).
// (3) When we receive an epoll notification for the socket, we post a work item to the threadpool
// to perform the I/O and invoke the callback with the I/O result.
// Synchronous operations generally do the same, except that instead of returning IOPending,
// they block on an event handle until the operation is processed by the queue.
// See comments on OperationQueue below for more details of how the queue coordination works.
internal sealed partial class SocketAsyncContext
{
// Cached operation instances for operations commonly repeated on the same socket instance,
// e.g. async accepts, sends/receives with single and multiple buffers. More can be
// added in the future if necessary, at the expense of extra fields here. With a larger
// refactoring, these could also potentially be moved to SocketAsyncEventArgs, which
// would be more invasive but which would allow them to be reused across socket instances
// and also eliminate the interlocked necessary to rent the instances.
private AcceptOperation? _cachedAcceptOperation;
private BufferMemoryReceiveOperation? _cachedBufferMemoryReceiveOperation;
private BufferListReceiveOperation? _cachedBufferListReceiveOperation;
private BufferMemorySendOperation? _cachedBufferMemorySendOperation;
private BufferListSendOperation? _cachedBufferListSendOperation;
private void ReturnOperation(AcceptOperation operation)
{
operation.Reset();
operation.Callback = null;
operation.SocketAddress = default;
Volatile.Write(ref _cachedAcceptOperation, operation); // benign race condition
}
private void ReturnOperation(BufferMemoryReceiveOperation operation)
{
operation.Reset();
operation.Buffer = default;
operation.Callback = null;
operation.SocketAddress = default;
Volatile.Write(ref _cachedBufferMemoryReceiveOperation, operation); // benign race condition
}
private void ReturnOperation(BufferListReceiveOperation operation)
{
operation.Reset();
operation.Buffers = null;
operation.Callback = null;
operation.SocketAddress = default;
Volatile.Write(ref _cachedBufferListReceiveOperation, operation); // benign race condition
}
private void ReturnOperation(BufferMemorySendOperation operation)
{
operation.Reset();
operation.Buffer = default;
operation.Callback = null;
operation.SocketAddress = default;
Volatile.Write(ref _cachedBufferMemorySendOperation, operation); // benign race condition
}
private void ReturnOperation(BufferListSendOperation operation)
{
operation.Reset();
operation.Buffers = null;
operation.Callback = null;
operation.SocketAddress = default;
Volatile.Write(ref _cachedBufferListSendOperation, operation); // benign race condition
}
private AcceptOperation RentAcceptOperation() =>
Interlocked.Exchange(ref _cachedAcceptOperation, null) ??
new AcceptOperation(this);
private BufferMemoryReceiveOperation RentBufferMemoryReceiveOperation() =>
Interlocked.Exchange(ref _cachedBufferMemoryReceiveOperation, null) ??
new BufferMemoryReceiveOperation(this);
private BufferListReceiveOperation RentBufferListReceiveOperation() =>
Interlocked.Exchange(ref _cachedBufferListReceiveOperation, null) ??
new BufferListReceiveOperation(this);
private BufferMemorySendOperation RentBufferMemorySendOperation() =>
Interlocked.Exchange(ref _cachedBufferMemorySendOperation, null) ??
new BufferMemorySendOperation(this);
private BufferListSendOperation RentBufferListSendOperation() =>
Interlocked.Exchange(ref _cachedBufferListSendOperation, null) ??
new BufferListSendOperation(this);
private abstract class AsyncOperation : IThreadPoolWorkItem
{
private enum State
{
Waiting = 0,
Running,
RunningWithPendingCancellation,
Complete,
Canceled
}
private volatile AsyncOperation.State _state;
#if DEBUG
private bool _callbackQueued; // When true, the callback has been queued.
#endif
public readonly SocketAsyncContext AssociatedContext;
public AsyncOperation Next = null!; // initialized by helper called from ctor
public SocketError ErrorCode;
public Memory<byte> SocketAddress;
public CancellationTokenRegistration CancellationRegistration;
public ManualResetEventSlim? Event { get; set; }
public AsyncOperation(SocketAsyncContext context)
{
AssociatedContext = context;
Reset();
}
public void Reset()
{
_state = State.Waiting;
Event = null;
Next = this;
#if DEBUG
_callbackQueued = false;
#endif
}
public OperationResult TryComplete(SocketAsyncContext context)
{
TraceWithContext(context, "Enter");
// Set state to Running, unless we've been canceled
State oldState = Interlocked.CompareExchange(ref _state, State.Running, State.Waiting);
if (oldState == State.Canceled)
{
TraceWithContext(context, "Exit, Previously canceled");
return OperationResult.Cancelled;
}
Debug.Assert(oldState == State.Waiting, $"Unexpected operation state: {(State)oldState}");
// Try to perform the IO
if (DoTryComplete(context))
{
Debug.Assert(_state is State.Running or State.RunningWithPendingCancellation, "Unexpected operation state");
_state = State.Complete;
TraceWithContext(context, "Exit, Completed");
return OperationResult.Completed;
}
// Set state back to Waiting, unless we were canceled, in which case we have to process cancellation now
State newState;
while (true)
{
State state = _state;
Debug.Assert(state is State.Running or State.RunningWithPendingCancellation, $"Unexpected operation state: {(State)state}");
newState = (state == State.Running ? State.Waiting : State.Canceled);
if (state == Interlocked.CompareExchange(ref _state, newState, state))
{
break;
}
// Race to update the state. Loop and try again.
}
if (newState == State.Canceled)
{
ProcessCancellation();
TraceWithContext(context, "Exit, Newly cancelled");
return OperationResult.Cancelled;
}
TraceWithContext(context, "Exit, Pending");
return OperationResult.Pending;
}
public bool TryCancel()
{
Trace("Enter");
// Note we could be cancelling because of socket close. Regardless, we don't need the registration anymore.
CancellationRegistration.Dispose();
State newState;
while (true)
{
State state = _state;
if (state is State.Complete or State.Canceled or State.RunningWithPendingCancellation)
{
return false;
}
newState = (state == State.Waiting ? State.Canceled : State.RunningWithPendingCancellation);
if (state == Interlocked.CompareExchange(ref _state, newState, state))
{
break;
}
// Race to update the state. Loop and try again.
}
if (newState == State.RunningWithPendingCancellation)
{
// TryComplete will either succeed, or it will see the pending cancellation and deal with it.
return false;
}
ProcessCancellation();
// Note, we leave the operation in the OperationQueue.
// When we get around to processing it, we'll see it's cancelled and skip it.
return true;
}
public void ProcessCancellation()
{
Trace("Enter");
Debug.Assert(_state == State.Canceled);
ErrorCode = SocketError.OperationAborted;
ManualResetEventSlim? e = Event;
if (e != null)
{
e.Set();
}
else
{
#if DEBUG
Debug.Assert(!Interlocked.Exchange(ref _callbackQueued, true), $"Unexpected _callbackQueued: {_callbackQueued}");
#endif
// We've marked the operation as canceled, and so should invoke the callback, but
// we can't pool the object, as ProcessQueue may still have a reference to it, due to
// using a pattern whereby it takes the lock to grab an item, but then releases the lock
// to do further processing on the item that's still in the list.
ThreadPool.UnsafeQueueUserWorkItem(o => ((AsyncOperation)o!).InvokeCallback(allowPooling: false), this);
}
}
public void Dispatch()
{
ManualResetEventSlim? e = Event;
if (e != null)
{
// Sync operation. Signal waiting thread to continue processing.
e.Set();
}
else
{
// Async operation.
Schedule();
}
}
public void Schedule()
{
Debug.Assert(Event == null);
// Async operation. Process the IO on the threadpool.
ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: false);
}
public void Process() => ((IThreadPoolWorkItem)this).Execute();
void IThreadPoolWorkItem.Execute()
{
// ReadOperation and WriteOperation, the only two types derived from
// AsyncOperation, implement IThreadPoolWorkItem.Execute to call
// ProcessAsyncOperation(this) on the appropriate receive or send queue.
// However, this base class needs to be able to queue them without
// additional allocation, so it also implements the interface in order
// to pass the compiler's static checking for the interface, but then
// when the runtime queries for the interface, it'll use the derived
// type's interface implementation. We could instead just make this
// an abstract and have the derived types override it, but that adds
// "Execute" as a public method, which could easily be misunderstood.
// We could also add an abstract method that the base interface implementation
// invokes, but that adds an extra virtual dispatch.
Debug.Fail("Expected derived type to implement IThreadPoolWorkItem");
throw new InvalidOperationException();
}
// Called when op is not in the queue yet, so can't be otherwise executing
public void DoAbort()
{
ErrorCode = SocketError.OperationAborted;
}
protected abstract bool DoTryComplete(SocketAsyncContext context);
public abstract void InvokeCallback(bool allowPooling);
[Conditional("SOCKETASYNCCONTEXT_TRACE")]
public void Trace(string message, [CallerMemberName] string? memberName = null)
{
OutputTrace($"{IdOf(this)}.{memberName}: {message}");
}
[Conditional("SOCKETASYNCCONTEXT_TRACE")]
public void TraceWithContext(SocketAsyncContext context, string message, [CallerMemberName] string? memberName = null)
{
OutputTrace($"{IdOf(context)}, {IdOf(this)}.{memberName}: {message}");
}
}
// These two abstract classes differentiate the operations that go in the
// read queue vs the ones that go in the write queue.
private abstract class ReadOperation : AsyncOperation, IThreadPoolWorkItem
{
public ReadOperation(SocketAsyncContext context) : base(context) { }
void IThreadPoolWorkItem.Execute() => AssociatedContext.ProcessAsyncReadOperation(this);
}
private abstract class WriteOperation : AsyncOperation, IThreadPoolWorkItem
{
public WriteOperation(SocketAsyncContext context) : base(context) { }
void IThreadPoolWorkItem.Execute() => AssociatedContext.ProcessAsyncWriteOperation(this);
}
private abstract class SendOperation : WriteOperation
{
public SocketFlags Flags;
public int BytesTransferred;
public int Offset;
public int Count;
public SendOperation(SocketAsyncContext context) : base(context) { }
public Action<int, Memory<byte>, SocketFlags, SocketError>? Callback { get; set; }
public override void InvokeCallback(bool allowPooling) =>
Callback!(BytesTransferred, SocketAddress, SocketFlags.None, ErrorCode);
}
private class BufferMemorySendOperation : SendOperation
{
public Memory<byte> Buffer;
public BufferMemorySendOperation(SocketAsyncContext context) : base(context) { }
protected override bool DoTryComplete(SocketAsyncContext context)
{
int bufferIndex = 0;
return SocketPal.TryCompleteSendTo(context._socket, Buffer.Span, null, ref bufferIndex, ref Offset, ref Count, Flags, SocketAddress.Span, ref BytesTransferred, out ErrorCode);
}
public override void InvokeCallback(bool allowPooling)
{
var cb = Callback!;
int bt = BytesTransferred;
Memory<byte> sa = SocketAddress;
SocketError ec = ErrorCode;
if (allowPooling)
{
AssociatedContext.ReturnOperation(this);
}
cb(bt, sa, SocketFlags.None, ec);
}
}
private sealed class BufferListSendOperation : SendOperation
{
public IList<ArraySegment<byte>>? Buffers;
public int BufferIndex;
public BufferListSendOperation(SocketAsyncContext context) : base(context) { }
protected override bool DoTryComplete(SocketAsyncContext context)
{
return SocketPal.TryCompleteSendTo(context._socket, default(ReadOnlySpan<byte>), Buffers, ref BufferIndex, ref Offset, ref Count, Flags, SocketAddress.Span, ref BytesTransferred, out ErrorCode);
}
public override void InvokeCallback(bool allowPooling)
{
var cb = Callback!;
int bt = BytesTransferred;
Memory<byte> sa = SocketAddress;
SocketError ec = ErrorCode;
if (allowPooling)
{
AssociatedContext.ReturnOperation(this);
}
cb(bt, sa, SocketFlags.None, ec);
}
}
private sealed unsafe class BufferPtrSendOperation : SendOperation
{
public byte* BufferPtr;
public BufferPtrSendOperation(SocketAsyncContext context) : base(context) { }
protected override bool DoTryComplete(SocketAsyncContext context)
{
int bufferIndex = 0;
int bufferLength = Offset + Count; // TryCompleteSendTo expects the entire buffer, which it then indexes into with the ref Offset and ref Count arguments
return SocketPal.TryCompleteSendTo(context._socket, new ReadOnlySpan<byte>(BufferPtr, bufferLength), null, ref bufferIndex, ref Offset, ref Count, Flags, SocketAddress.Span, ref BytesTransferred, out ErrorCode);
}
}
private abstract class ReceiveOperation : ReadOperation
{
public SocketFlags Flags;
public SocketFlags ReceivedFlags;
public int BytesTransferred;
public ReceiveOperation(SocketAsyncContext context) : base(context) { }
public Action<int, Memory<byte>, SocketFlags, SocketError>? Callback { get; set; }
public override void InvokeCallback(bool allowPooling) =>
Callback!(BytesTransferred, SocketAddress, ReceivedFlags, ErrorCode);
}
private sealed class BufferMemoryReceiveOperation : ReceiveOperation
{
public Memory<byte> Buffer;
public bool SetReceivedFlags;
public BufferMemoryReceiveOperation(SocketAsyncContext context) : base(context) { }
protected override bool DoTryComplete(SocketAsyncContext context)
{
// Zero byte read is performed to know when data is available.
// We don't have to call receive, our caller is interested in the event.
if (Buffer.Length == 0 && Flags == SocketFlags.None && SocketAddress.Length == 0)
{
BytesTransferred = 0;
ReceivedFlags = SocketFlags.None;
ErrorCode = SocketError.Success;
return true;
}
else
{
if (!SetReceivedFlags)
{
Debug.Assert(SocketAddress.Length == 0);
ReceivedFlags = SocketFlags.None;
return SocketPal.TryCompleteReceive(context._socket, Buffer.Span, Flags, out BytesTransferred, out ErrorCode);
}
else
{
bool completed = SocketPal.TryCompleteReceiveFrom(context._socket, Buffer.Span, null, Flags, SocketAddress.Span, out int socketAddressLen, out BytesTransferred, out ReceivedFlags, out ErrorCode);
if (completed && ErrorCode == SocketError.Success)
{
SocketAddress = SocketAddress.Slice(0, socketAddressLen);
}
return completed;
}
}
}
public override void InvokeCallback(bool allowPooling)
{
var cb = Callback!;
int bt = BytesTransferred;
Memory<byte> sa = SocketAddress;
SocketFlags rf = ReceivedFlags;
SocketError ec = ErrorCode;
if (allowPooling)
{
AssociatedContext.ReturnOperation(this);
}
cb(bt, sa, rf, ec);
}
}
private sealed class BufferListReceiveOperation : ReceiveOperation
{
public IList<ArraySegment<byte>>? Buffers;
public BufferListReceiveOperation(SocketAsyncContext context) : base(context) { }
protected override bool DoTryComplete(SocketAsyncContext context)
{
bool completed = SocketPal.TryCompleteReceiveFrom(context._socket, default(Span<byte>), Buffers, Flags, SocketAddress.Span, out int socketAddressLen, out BytesTransferred, out ReceivedFlags, out ErrorCode);
if (completed && ErrorCode == SocketError.Success)
{
SocketAddress = SocketAddress.Slice(0, socketAddressLen);
}
return completed;
}
public override void InvokeCallback(bool allowPooling)
{
var cb = Callback!;
int bt = BytesTransferred;
Memory<byte> sa = SocketAddress;
SocketFlags rf = ReceivedFlags;
SocketError ec = ErrorCode;
if (allowPooling)
{
AssociatedContext.ReturnOperation(this);
}
cb(bt, sa, rf, ec);
}
}
private sealed unsafe class BufferPtrReceiveOperation : ReceiveOperation
{
public byte* BufferPtr;
public int Length;
public BufferPtrReceiveOperation(SocketAsyncContext context) : base(context) { }
protected override bool DoTryComplete(SocketAsyncContext context)
{
bool completed = SocketPal.TryCompleteReceiveFrom(context._socket, new Span<byte>(BufferPtr, Length), null, Flags, SocketAddress.Span, out int socketAddressLen, out BytesTransferred, out ReceivedFlags, out ErrorCode);
if (completed && ErrorCode == SocketError.Success)
{
SocketAddress = SocketAddress.Slice(0, socketAddressLen);
}
return completed;
}
}
private sealed class ReceiveMessageFromOperation : ReadOperation
{
public Memory<byte> Buffer;
public SocketFlags Flags;
public int BytesTransferred;
public SocketFlags ReceivedFlags;
public IList<ArraySegment<byte>>? Buffers;
public bool IsIPv4;
public bool IsIPv6;
public IPPacketInformation IPPacketInformation;
public ReceiveMessageFromOperation(SocketAsyncContext context) : base(context) { }
public Action<int, Memory<byte>, SocketFlags, IPPacketInformation, SocketError>? Callback { get; set; }
protected override bool DoTryComplete(SocketAsyncContext context)
{
bool completed = SocketPal.TryCompleteReceiveMessageFrom(context._socket, Buffer.Span, Buffers, Flags, SocketAddress, out int socketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode);
if (completed && ErrorCode == SocketError.Success)
{
SocketAddress = SocketAddress.Slice(0, socketAddressLen);
}
return completed;
}
public override void InvokeCallback(bool allowPooling) =>
Callback!(BytesTransferred, SocketAddress, ReceivedFlags, IPPacketInformation, ErrorCode);
}
private sealed unsafe class BufferPtrReceiveMessageFromOperation : ReadOperation
{
public byte* BufferPtr;
public int Length;
public SocketFlags Flags;
public int BytesTransferred;
public SocketFlags ReceivedFlags;
public bool IsIPv4;
public bool IsIPv6;
public IPPacketInformation IPPacketInformation;
public BufferPtrReceiveMessageFromOperation(SocketAsyncContext context) : base(context) { }
public Action<int, Memory<byte>, SocketFlags, IPPacketInformation, SocketError>? Callback { get; set; }
protected override bool DoTryComplete(SocketAsyncContext context)
{
bool completed = SocketPal.TryCompleteReceiveMessageFrom(context._socket, new Span<byte>(BufferPtr, Length), null, Flags, SocketAddress!, out int socketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode);
if (completed && ErrorCode == SocketError.Success)
{
SocketAddress = SocketAddress.Slice(0, socketAddressLen);
}
return completed;
}
public override void InvokeCallback(bool allowPooling) =>
Callback!(BytesTransferred, SocketAddress, ReceivedFlags, IPPacketInformation, ErrorCode);
}
private sealed class AcceptOperation : ReadOperation
{
public IntPtr AcceptedFileDescriptor;
public AcceptOperation(SocketAsyncContext context) : base(context) { }
public Action<IntPtr, Memory<byte>, SocketError>? Callback { get; set; }
protected override bool DoTryComplete(SocketAsyncContext context)
{
bool completed = SocketPal.TryCompleteAccept(context._socket, SocketAddress, out int socketAddressLen, out AcceptedFileDescriptor, out ErrorCode);
Debug.Assert(ErrorCode == SocketError.Success || AcceptedFileDescriptor == (IntPtr)(-1), $"Unexpected values: ErrorCode={ErrorCode}, AcceptedFileDescriptor={AcceptedFileDescriptor}");
if (ErrorCode == SocketError.Success)
{
SocketAddress = SocketAddress.Slice(0, socketAddressLen);
}
return completed;
}
public override void InvokeCallback(bool allowPooling)
{
var cb = Callback!;
IntPtr fd = AcceptedFileDescriptor;
Memory<byte> sa = SocketAddress;
SocketError ec = ErrorCode;
if (allowPooling)
{
AssociatedContext.ReturnOperation(this);
}
cb(fd, sa, ec);
}
}
private sealed class ConnectOperation : BufferMemorySendOperation
{
public ConnectOperation(SocketAsyncContext context) : base(context) { }
protected override bool DoTryComplete(SocketAsyncContext context)
{
bool result = SocketPal.TryCompleteConnect(context._socket, out ErrorCode);
context._socket.RegisterConnectResult(ErrorCode);
if (result && ErrorCode == SocketError.Success && Buffer.Length > 0)
{
SocketError error = context.SendToAsync(Buffer, 0, Buffer.Length, SocketFlags.None, Memory<byte>.Empty, ref BytesTransferred, Callback!, default);
if (error != SocketError.Success && error != SocketError.IOPending)
{
context._socket.RegisterConnectResult(ErrorCode);
}
}
return result;
}
public override void InvokeCallback(bool allowPooling)
{
var cb = Callback!;
int bt = BytesTransferred;
Memory<byte> sa = SocketAddress;
SocketError ec = ErrorCode;
Memory<byte> buffer = Buffer;
if (buffer.Length == 0 || ec != SocketError.Success)
{
AssociatedContext._socket.SetBlocking();
// Invoke callback only when we are completely done.
// In case data were provided for Connect we may or may not send them all.
// If we did not we will need follow-up with Send operation
cb(bt, sa, SocketFlags.None, ec);
}
}
}
private sealed class SendFileOperation : WriteOperation
{
public SafeFileHandle FileHandle = null!; // always set when constructed
public long Offset;
public long Count;
public long BytesTransferred;
public SendFileOperation(SocketAsyncContext context) : base(context) { }
public Action<long, SocketError>? Callback { get; set; }
public override void InvokeCallback(bool allowPooling) =>
Callback!(BytesTransferred, ErrorCode);
protected override bool DoTryComplete(SocketAsyncContext context) =>
SocketPal.TryCompleteSendFile(context._socket, FileHandle, ref Offset, ref Count, ref BytesTransferred, out ErrorCode);
}
// In debug builds, this struct guards against:
// (1) Unexpected lock reentrancy, which should never happen
// (2) Deadlock, by setting a reasonably large timeout
private readonly struct LockToken : IDisposable
{
private readonly object _lockObject;
public LockToken(object lockObject)
{
Debug.Assert(lockObject != null);
_lockObject = lockObject;
Debug.Assert(!Monitor.IsEntered(_lockObject));
#if DEBUG
bool success = Monitor.TryEnter(_lockObject, 10000);
Debug.Assert(success, "Timed out waiting for queue lock");
#else
Monitor.Enter(_lockObject);
#endif
}
public void Dispose()
{
Debug.Assert(Monitor.IsEntered(_lockObject));
Monitor.Exit(_lockObject);
}
}
public enum OperationResult
{
Pending = 0,
Completed = 1,
Cancelled = 2
}
private struct OperationQueue<TOperation>
where TOperation : AsyncOperation
{
// Quick overview:
//
// When attempting to perform an IO operation, the caller first checks IsReady,
// and if true, attempts to perform the operation itself.
// If this returns EWOULDBLOCK, or if the queue was not ready, then the operation
// is enqueued by calling StartAsyncOperation and the state becomes Waiting.
// When an epoll notification is received, we check if the state is Waiting,
// and if so, change the state to Processing and enqueue a workitem to the threadpool
// to try to perform the enqueued operations.
// If an operation is successfully performed, we remove it from the queue,
// enqueue another threadpool workitem to process the next item in the queue (if any),
// and call the user's completion callback.
// If we successfully process all enqueued operations, then the state becomes Ready;
// otherwise, the state becomes Waiting and we wait for another epoll notification.
private enum QueueState : int
{
Ready = 0, // Indicates that data MAY be available on the socket.
// Queue must be empty.
Waiting = 1, // Indicates that data is definitely not available on the socket.
// Queue must not be empty.
Processing = 2, // Indicates that a thread pool item has been scheduled (and may
// be executing) to process the IO operations in the queue.
// Queue must not be empty.
Stopped = 3, // Indicates that the queue has been stopped because the
// socket has been closed.
// Queue must be empty.
}
// These fields define the queue state.
private QueueState _state; // See above
private bool _isNextOperationSynchronous;
private int _sequenceNumber; // This sequence number is updated when we receive an epoll notification.
// It allows us to detect when a new epoll notification has arrived
// since the last time we checked the state of the queue.
// If this happens, we MUST retry the operation, otherwise we risk
// "losing" the notification and causing the operation to pend indefinitely.
private AsyncOperation? _tail; // Queue of pending IO operations to process when data becomes available.
// The _queueLock is used to ensure atomic access to the queue state above.
// The lock is only ever held briefly, to read and/or update queue state, and
// never around any external call, e.g. OS call or user code invocation.
private object _queueLock;
private LockToken Lock() => new LockToken(_queueLock);
public bool IsNextOperationSynchronous_Speculative => _isNextOperationSynchronous;
public void Init()
{
Debug.Assert(_queueLock == null);
_queueLock = new object();
_state = QueueState.Ready;
_sequenceNumber = 0;
}
// IsReady returns whether an operation can be executed immediately.
// observedSequenceNumber must be passed to StartAsyncOperation.
public bool IsReady(SocketAsyncContext context, out int observedSequenceNumber)
{
// It is safe to read _state and _sequence without using Lock.
// - The return value is soley based on Volatile.Read of _state.
// - The Volatile.Read of _sequenceNumber ensures we read a value before executing the operation.
// This is needed to retry the operation in StartAsyncOperation in case the _sequenceNumber incremented.
// - Because no Lock is taken, it is possible we observe a sequence number increment before the state
// becomes Ready. When that happens, observedSequenceNumber is decremented, and StartAsyncOperation will
// execute the operation because the sequence number won't match.
Debug.Assert(sizeof(QueueState) == sizeof(int));
QueueState state = (QueueState)Volatile.Read(ref Unsafe.As<QueueState, int>(ref _state));
observedSequenceNumber = Volatile.Read(ref _sequenceNumber);
bool isReady = state == QueueState.Ready || state == QueueState.Stopped;
if (!isReady)
{
observedSequenceNumber--;
}
Trace(context, $"{isReady}");
return isReady;
}
// Return true for pending, false for completed synchronously (including failure and abort)
public bool StartAsyncOperation(SocketAsyncContext context, TOperation operation, int observedSequenceNumber, CancellationToken cancellationToken = default)
{
Trace(context, $"Enter");
if (!context.IsRegistered && !context.TryRegister(out Interop.Error error))
{
HandleFailedRegistration(context, operation, error);
Trace(context, "Leave, not registered");
return false;
}
while (true)
{
bool doAbort = false;
using (Lock())
{
switch (_state)
{
case QueueState.Ready:
if (observedSequenceNumber != _sequenceNumber)
{
// The queue has become ready again since we previously checked it.
// So, we need to retry the operation before we enqueue it.
Debug.Assert(observedSequenceNumber - _sequenceNumber < 10000, "Very large sequence number increase???");
observedSequenceNumber = _sequenceNumber;
break;
}
// Caller tried the operation and got an EWOULDBLOCK, so we need to transition.
_state = QueueState.Waiting;
goto case QueueState.Waiting;
case QueueState.Waiting:
case QueueState.Processing:
// Enqueue the operation.
Debug.Assert(operation.Next == operation, "Expected operation.Next == operation");
if (_tail == null)
{
Debug.Assert(!_isNextOperationSynchronous);
_isNextOperationSynchronous = operation.Event != null;
}
else
{
operation.Next = _tail.Next;
_tail.Next = operation;
}
_tail = operation;
Trace(context, $"Leave, enqueued {IdOf(operation)}");
// Now that the object is enqueued, hook up cancellation.
// Note that it's possible the call to register itself could
// call TryCancel, so we do this after the op is fully enqueued.
if (cancellationToken.CanBeCanceled)
{
operation.CancellationRegistration = cancellationToken.UnsafeRegister(s => ((TOperation)s!).TryCancel(), operation);
}
return true;
case QueueState.Stopped:
Debug.Assert(_tail == null);
doAbort = true;
break;
default:
Environment.FailFast("unexpected queue state");
break;
}
}
if (doAbort)
{
operation.DoAbort();
Trace(context, $"Leave, queue stopped");
return false;
}
// Retry the operation.
if (operation.TryComplete(context) != OperationResult.Pending)
{
Trace(context, $"Leave, retry succeeded");
return false;
}
}
static void HandleFailedRegistration(SocketAsyncContext context, TOperation operation, Interop.Error error)
{
Debug.Assert(error != Interop.Error.SUCCESS);
// macOS: kevent returns EPIPE when adding pipe fd for which the other end is closed.
if (error == Interop.Error.EPIPE)
{
// Because the other end close, we expect the operation to complete when we retry it.
// If it doesn't, we fall through and throw an Exception.
if (operation.TryComplete(context) != OperationResult.Pending)
{
return;
}
}
if (error == Interop.Error.ENOMEM || error == Interop.Error.ENOSPC)
{
throw new OutOfMemoryException();
}
else
{
throw new InternalException(error);
}
}
}
public AsyncOperation? ProcessSyncEventOrGetAsyncEvent(SocketAsyncContext context, bool skipAsyncEvents = false)
{
AsyncOperation op;
using (Lock())
{
Trace(context, $"Enter");
switch (_state)
{
case QueueState.Ready:
Debug.Assert(_tail == null, "State == Ready but queue is not empty!");
_sequenceNumber++;
Trace(context, $"Exit (previously ready)");
return null;
case QueueState.Waiting:
Debug.Assert(_tail != null, "State == Waiting but queue is empty!");
op = _tail.Next;
Debug.Assert(_isNextOperationSynchronous == (op.Event != null));
if (skipAsyncEvents && !_isNextOperationSynchronous)
{
// Return the operation to indicate that the async operation was not processed, without making
// any state changes because async operations are being skipped
return op;
}
_state = QueueState.Processing;
// Break out and release lock
break;
case QueueState.Processing:
Debug.Assert(_tail != null, "State == Processing but queue is empty!");
_sequenceNumber++;
Trace(context, $"Exit (currently processing)");
return null;
case QueueState.Stopped:
Debug.Assert(_tail == null);
Trace(context, $"Exit (stopped)");
return null;
default:
Environment.FailFast("unexpected queue state");
return null;
}
}
ManualResetEventSlim? e = op.Event;
if (e != null)
{
// Sync operation. Signal waiting thread to continue processing.
e.Set();