private void AcceptOn(TSocket tsocket) { try { _acceptSockets.Add(tsocket); lock (_sockets) { _sockets.Add(tsocket.Fd, tsocket); } EPollInterop.EPollControl(_epollFd, EPOLL_CTL_ADD, tsocket.Fd, EPOLLIN, tsocket.Fd); } catch { tsocket.Close(); _acceptSockets.Remove(tsocket); lock (_sockets) { _sockets.Remove(tsocket.Fd); } throw; } }
private void AcceptOn(TSocket tsocket) { try { _acceptSockets.Add(tsocket); lock (_sockets) { _sockets.Add(tsocket.Fd, tsocket); } EPollInterop.EPollControl(_epollFd, EPollOperation.Add, tsocket.Fd, EPollEvents.Readable, EPollData(tsocket.Fd)); } catch { tsocket.Close(); _acceptSockets.Remove(tsocket); lock (_sockets) { _sockets.Remove(tsocket.Fd); } throw; } }
private void Start() { // register pipe EPollInterop.EPollControl(_epollFd, EPollOperation.Add, _pipeEnds.ReadEnd.DangerousGetHandle().ToInt32(), EPollEvents.Readable, EPollData(PipeKey)); // create accept socket { TSocket acceptSocket; SocketFlags flags = SocketFlags.None; if (_transportOptions.DeferSend) { flags |= SocketFlags.DeferSend; } ; if (_transportThread.AcceptThread != null) { flags |= SocketFlags.TypePassFd; int acceptSocketFd = _transportThread.AcceptThread.CreateReceiveSocket(); acceptSocket = new TSocket(this, acceptSocketFd, flags); acceptSocket.ZeroCopyThreshold = LinuxTransportOptions.NoZeroCopy; } else { flags |= SocketFlags.TypeAccept; acceptSocket = CreateAcceptSocket(_transportThread.EndPoint, flags); } // accept connections AcceptOn(acceptSocket); } }
private unsafe void AcceptThreadStart(object state) { try { var socket = _socket; using (socket) { using (EPoll epoll = EPoll.Create()) { int epollFd = epoll.DangerousGetHandle().ToInt32(); const int acceptKey = 0; const int pipeKey = 1; // accept socket epoll.Control(EPollOperation.Add, _socket, EPollEvents.Readable, new EPollData { Int1 = acceptKey, Int2 = acceptKey }); // add pipe epoll.Control(EPollOperation.Add, _pipeEnds.ReadEnd, EPollEvents.Readable, new EPollData { Int1 = pipeKey, Int2 = pipeKey }); const int EventBufferLength = 1; int notPacked = !EPoll.PackedEvents ? 1 : 0; var buffer = stackalloc int[EventBufferLength * (3 + notPacked)]; int * key = &buffer[2]; bool running = true; int nextHandler = 0; var handlers = _handlers; do { int numEvents = EPollInterop.EPollWait(epollFd, buffer, EventBufferLength, timeout: EPoll.TimeoutInfinite).Value; if (numEvents == 1) { if (*key == acceptKey) { var handler = handlers[nextHandler]; nextHandler = (nextHandler + 1) % handlers.Length; socket.TryAcceptAndSendHandleTo(handler); } else { running = false; } } } while (running); } } _stoppedTcs.TrySetResult(null); } catch (Exception e) { _stoppedTcs.SetException(e); } finally { Cleanup(); } }
public static EPoll Create() { EPoll epoll; var result = EPollInterop.EPollCreate(out epoll); result.ThrowOnError(); return(epoll); }
// must be called under tsocket.Gate public void UpdateEPollControl(TSocket tsocket, EPollEvents flags, bool registered) { flags &= EPollEvents.Readable | EPollEvents.Writable | EPollEvents.Error; EPollInterop.EPollControl(_epollFd, registered ? EPollOperation.Modify : EPollOperation.Add, tsocket.Fd, flags | EPollEvents.OneShot, EPollData(tsocket.Fd)); }
// must be called under tsocket.Gate public void UpdateEPollControl(TSocket tsocket, int flags, bool registered) { flags &= EPOLLIN | EPOLLOUT | EPOLLERR; EPollInterop.EPollControl(_epollFd, registered ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, tsocket.Fd, flags | EPOLLONESHOT, tsocket.Fd); }
private unsafe void AcceptThreadStart(object state) { try { var socket = _socket; using (socket) { using (EPoll epoll = EPoll.Create()) { int epollFd = epoll.DangerousGetHandle().ToInt32(); const int acceptKey = 0; const int pipeKey = 1; // accept socket epoll.Control(EPOLL_CTL_ADD, _socket, EPOLLIN, acceptKey); // add pipe epoll.Control(EPOLL_CTL_ADD, _pipeEnds.ReadEnd, EPOLLIN, pipeKey); epoll_event ev; bool running = true; int nextHandler = 0; var handlers = _handlers; do { int numEvents = EPollInterop.EPollWait(epollFd, &ev, 1, timeout: EPoll.TimeoutInfinite).IntValue; if (numEvents == 1) { if (ev.data.fd == acceptKey) { var handler = handlers[nextHandler]; nextHandler = (nextHandler + 1) % handlers.Length; socket.TryAcceptAndSendHandleTo(handler); } else { running = false; } } } while (running); } } _stoppedTcs.TrySetResult(null); } catch (Exception e) { _stoppedTcs.SetException(e); } finally { Cleanup(); } }
static EPoll() { var epollEventSize = EPollInterop.SizeOfEPollEvent(); if (epollEventSize == Marshal.SizeOf <EPollEventPacked>()) { s_packedEvents = true; } else if (epollEventSize == Marshal.SizeOf <EPollEvent>()) { s_packedEvents = false; } else { throw new NotSupportedException(); } }
public PosixResult TryControl(int operation, SafeHandle fd, int events, int data) { return(EPollInterop.EPollControl(this, operation, fd, events, data)); }
public unsafe void Run() { try { Start(); CompleteStateChange(TransportThreadState.Started); } catch (Exception e) { CompleteStateChange(TransportThreadState.Stopped, e); return; } try { int notPacked = !EPoll.PackedEvents ? 1 : 0; var buffer = stackalloc int[EventBufferLength * (3 + notPacked)]; int statReadEvents = 0; int statWriteEvents = 0; int statAcceptEvents = 0; int statAccepts = 0; int statZeroCopySuccess = 0; int statZeroCopyCopied = 0; var acceptableSockets = new List <TSocket>(1); var readableSockets = new List <TSocket>(EventBufferLength); var writableSockets = new List <TSocket>(EventBufferLength); var reregisterEventSockets = new List <TSocket>(EventBufferLength); var zeroCopyCompletions = new List <TSocket>(EventBufferLength); bool pipeReadable = false; bool running = true; do { int numEvents = EPollInterop.EPollWait(_epollFd, buffer, EventBufferLength, timeout: EPoll.TimeoutInfinite).Value; // actions can be scheduled without unblocking epoll SetEpollNotBlocked(); // check events // we don't handle them immediately: // - this ensures we don't mismatch a closed socket with a new socket that have the same fd // ~ To have the same fd, the previous fd must be closed, which means it is removed from the epoll // ~ and won't show up in our next call to epoll.Wait. // ~ The old fd may be present in the buffer still, but lookup won't give a match, since it is removed // ~ from the dictionary before it is closed. If we were accepting already, a new socket could match. // - this also improves cache/cpu locality of the lookup int *ptr = buffer; lock (_sockets) { for (int i = 0; i < numEvents; i++) { // Packed Non-Packed // ------ ------ // 0:Events == Events // 1:Int1 = Key [Padding] // 2:Int2 = Key == Int1 = Key // 3:~~~~~~~~~~ Int2 = Key // ~~~~~~~~~~ EPollEvents events = (EPollEvents)ptr[0]; int key = ptr[2]; ptr += 3 + notPacked; TSocket tsocket; if (_sockets.TryGetValue(key, out tsocket)) { var type = tsocket.Type; if (type == SocketFlags.TypeClient) { lock (tsocket.Gate) { var pendingEventState = tsocket.PendingEventState; // zero copy if ((pendingEventState & EPollEvents.Error & events) != EPollEvents.None) { var copyResult = SocketInterop.CompleteZeroCopy(tsocket.Fd); if (copyResult != PosixResult.EAGAIN) { events &= ~EPollEvents.Error; pendingEventState &= ~EPollEvents.Error; zeroCopyCompletions.Add(tsocket); if (copyResult == SocketInterop.ZeroCopyCopied) { tsocket.ZeroCopyThreshold = LinuxTransportOptions.NoZeroCopy; statZeroCopyCopied++; } else if (copyResult == SocketInterop.ZeroCopySuccess) { statZeroCopySuccess++; } else { Environment.FailFast($"Error occurred while trying to complete zero copy: {copyResult}"); } } } // treat Error as Readable, Writable if ((events & EPollEvents.Error) != EPollEvents.None) { events |= EPollEvents.Readable | EPollEvents.Writable; } events &= pendingEventState & (EPollEvents.Readable | EPollEvents.Writable); // readable if ((events & EPollEvents.Readable) != EPollEvents.None) { readableSockets.Add(tsocket); pendingEventState &= ~EPollEvents.Readable; } // writable if ((events & EPollEvents.Writable) != EPollEvents.None) { writableSockets.Add(tsocket); pendingEventState &= ~EPollEvents.Writable; } // reregister tsocket.PendingEventState = pendingEventState; if ((pendingEventState & (EPollEvents.Readable | EPollEvents.Writable)) != EPollEvents.None) { tsocket.PendingEventState |= TSocket.EventControlPending; reregisterEventSockets.Add(tsocket); } } } else { statAcceptEvents++; acceptableSockets.Add(tsocket); } } else if (key == PipeKey) { pipeReadable = true; } } } // zero copy for (int i = 0; i < zeroCopyCompletions.Count; i++) { zeroCopyCompletions[i].OnZeroCopyCompleted(); } zeroCopyCompletions.Clear(); // handle accepts statAcceptEvents += acceptableSockets.Count; for (int i = 0; i < acceptableSockets.Count; i++) { statAccepts += HandleAccept(acceptableSockets[i]); } acceptableSockets.Clear(); // handle writes statWriteEvents += writableSockets.Count; for (int i = 0; i < writableSockets.Count; i++) { writableSockets[i].OnWritable(stopped: false); } writableSockets.Clear(); // handle reads statReadEvents += readableSockets.Count; if (!_transportOptions.AioReceive) { Span <MemoryHandle> receiveMemoryHandles = MemoryHandles; for (int i = 0; i < readableSockets.Count; i++) { TSocket socket = readableSockets[i]; var receiveResult = socket.Receive(receiveMemoryHandles); socket.OnReceiveFromSocket(receiveResult); } readableSockets.Clear(); } else if (readableSockets.Count > 0) { AioReceive(readableSockets); } // reregister for events for (int i = 0; i < reregisterEventSockets.Count; i++) { var tsocket = reregisterEventSockets[i]; lock (tsocket.Gate) { var pendingEventState = tsocket.PendingEventState & ~TSocket.EventControlPending; tsocket.PendingEventState = pendingEventState; UpdateEPollControl(tsocket, pendingEventState, registered: true); } } reregisterEventSockets.Clear(); // handle pipe if (pipeReadable) { PosixResult result; do { result = _pipeEnds.ReadEnd.TryReadByte(); if (result.Value == PipeStopSockets) { StopSockets(); } else if (result.Value == PipeStopThread) { running = false; } else if (result.Value == PipeCloseAccept) { CloseAccept(); } } while (result); pipeReadable = false; } // scheduled work // note: this may write a byte to the pipe DoScheduledWork(_transportOptions.AioSend); } while (running); _logger.LogDebug($"Stats A/AE:{statAccepts}/{statAcceptEvents} RE:{statReadEvents} WE:{statWriteEvents} ZCS/ZCC:{statZeroCopySuccess}/{statZeroCopyCopied}"); CompleteStateChange(TransportThreadState.Stopped); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Environment.FailFast("TransportThread", ex); } }
public PosixResult TryControl(EPollOperation operation, SafeHandle fd, EPollEvents events, EPollData data) { return(EPollInterop.EPollControl(this, operation, fd, events, data.Long)); }
public unsafe PosixResult TryWait(void *events, int maxEvents, int timeout) { return(EPollInterop.EPollWait(this, events, maxEvents, timeout)); }