-
Notifications
You must be signed in to change notification settings - Fork 268
Epoll: Rework epoll type #619
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
dcantah
wants to merge
1
commit into
apple:main
Choose a base branch
from
dcantah:epoll-return-events
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,168 +14,178 @@ | |
| // limitations under the License. | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| #if os(Linux) | ||
| import Foundation | ||
|
|
||
| #if canImport(Musl) | ||
| import Musl | ||
| #elseif canImport(Glibc) | ||
| import Glibc | ||
| #endif | ||
|
|
||
| import Foundation | ||
| import Synchronization | ||
|
|
||
| /// Register file descriptors to receive events via Linux's | ||
| /// epoll syscall surface. | ||
| /// A thin wrapper around the Linux epoll syscall surface. | ||
| public final class Epoll: Sendable { | ||
| public typealias Mask = Int32 | ||
| public typealias Handler = (@Sendable (Mask) -> Void) | ||
| /// A set of epoll event flags. | ||
| public struct Mask: OptionSet, Sendable { | ||
| public let rawValue: UInt32 | ||
|
|
||
| public init(rawValue: UInt32) { | ||
| self.rawValue = rawValue | ||
| } | ||
|
|
||
| public static let input = Mask(rawValue: UInt32(bitPattern: EPOLLIN)) | ||
| public static let output = Mask(rawValue: UInt32(bitPattern: EPOLLOUT)) | ||
|
|
||
| public var isHangup: Bool { | ||
| !self.isDisjoint(with: Mask(rawValue: UInt32(bitPattern: EPOLLHUP | EPOLLERR))) | ||
| } | ||
|
|
||
| public var isRemoteHangup: Bool { | ||
| !self.isDisjoint(with: Mask(rawValue: UInt32(bitPattern: EPOLLRDHUP))) | ||
| } | ||
|
|
||
| public var readyToRead: Bool { | ||
| self.contains(.input) | ||
| } | ||
|
|
||
| public var readyToWrite: Bool { | ||
| self.contains(.output) | ||
| } | ||
| } | ||
|
|
||
| /// An event returned by `wait()`. | ||
| public struct Event: Sendable { | ||
| public let fd: Int32 | ||
| public let mask: Mask | ||
| } | ||
|
|
||
| private let epollFD: Int32 | ||
| private let handlers = SafeMap<Int32, Handler>() | ||
| private let pipe = Pipe() // to wake up a waiting epoll_wait | ||
| private let shutdownReadFD: Int32 | ||
| private let shutdownWriteFD: Int32 | ||
|
|
||
| public init() throws { | ||
| let efd = epoll_create1(EPOLL_CLOEXEC) | ||
| guard efd > 0 else { | ||
| guard efd >= 0 else { | ||
| throw POSIXError.fromErrno() | ||
| } | ||
|
|
||
| var pipeFDs: (Int32, Int32) = (0, 0) | ||
| let pipeResult = withUnsafeMutablePointer(to: &pipeFDs) { ptr in | ||
| ptr.withMemoryRebound(to: Int32.self, capacity: 2) { buf in | ||
| pipe2(buf, O_CLOEXEC | O_NONBLOCK) | ||
| } | ||
| } | ||
| guard pipeResult == 0 else { | ||
| let pipeErrno = POSIXError.fromErrno() | ||
| close(efd) | ||
| throw pipeErrno | ||
| } | ||
|
|
||
| self.epollFD = efd | ||
| try self.add(pipe.fileHandleForReading.fileDescriptor) { _ in } | ||
| self.shutdownReadFD = pipeFDs.0 | ||
| self.shutdownWriteFD = pipeFDs.1 | ||
|
|
||
| // Register the shutdown pipe read end with epoll. | ||
| var event = epoll_event() | ||
| event.events = UInt32(bitPattern: EPOLLIN) | ||
| event.data.fd = self.shutdownReadFD | ||
| let ctlResult = withUnsafeMutablePointer(to: &event) { ptr in | ||
| epoll_ctl(efd, EPOLL_CTL_ADD, self.shutdownReadFD, ptr) | ||
| } | ||
| guard ctlResult == 0 else { | ||
| let ctlErrno = POSIXError.fromErrno() | ||
| close(self.shutdownReadFD) | ||
| close(self.shutdownWriteFD) | ||
| close(efd) | ||
| throw ctlErrno | ||
| } | ||
| } | ||
|
|
||
| public func add( | ||
| _ fd: Int32, | ||
| mask: Int32 = EPOLLIN | EPOLLOUT, // HUP is always added | ||
| handler: @escaping Handler | ||
| ) throws { | ||
| deinit { | ||
| close(epollFD) | ||
| close(shutdownReadFD) | ||
| close(shutdownWriteFD) | ||
| } | ||
|
|
||
| /// Register a file descriptor for edge-triggered monitoring. | ||
| public func add(_ fd: Int32, mask: Mask) throws { | ||
| guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0 else { | ||
| throw POSIXError.fromErrno() | ||
| } | ||
|
|
||
| let events = EPOLLET | UInt32(bitPattern: mask) | ||
| let events = EPOLLET | mask.rawValue | ||
|
|
||
| var event = epoll_event() | ||
| event.events = events | ||
| event.data.fd = fd | ||
|
|
||
| try withUnsafeMutablePointer(to: &event) { ptr in | ||
| while true { | ||
| if epoll_ctl(self.epollFD, EPOLL_CTL_ADD, fd, ptr) == -1 { | ||
| if errno == EAGAIN || errno == EINTR { | ||
| continue | ||
| } | ||
| throw POSIXError.fromErrno() | ||
| } | ||
| break | ||
| if epoll_ctl(self.epollFD, EPOLL_CTL_ADD, fd, ptr) == -1 { | ||
| throw POSIXError.fromErrno() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| self.handlers.set(fd, handler) | ||
| /// Remove a file descriptor from the monitored collection. | ||
| public func delete(_ fd: Int32) throws { | ||
| var event = epoll_event() | ||
| let result = withUnsafeMutablePointer(to: &event) { ptr in | ||
| epoll_ctl(self.epollFD, EPOLL_CTL_DEL, fd, ptr) | ||
| } | ||
| if result != 0 { | ||
| if !acceptableDeletionErrno() { | ||
| throw POSIXError.fromErrno() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Run the main epoll loop. | ||
| /// Wait for events. | ||
| /// | ||
| /// max events to return in a single wait | ||
| /// timeout in ms. | ||
| /// -1 means block forever. | ||
| /// 0 means return immediately if no events. | ||
| public func run(maxEvents: Int = 128, timeout: Int32 = -1) throws { | ||
| /// Returns an array of events ready for processing. Returns an empty array | ||
| /// on shutdown or timeout. | ||
| public func wait(maxEvents: Int = 128, timeout: Int32 = -1) -> [Event] { | ||
| var events: [epoll_event] = .init( | ||
| repeating: epoll_event(), | ||
| count: maxEvents | ||
| ) | ||
|
|
||
| while true { | ||
| let n = epoll_wait(self.epollFD, &events, Int32(events.count), timeout) | ||
| guard n >= 0 else { | ||
| if n < 0 { | ||
| if errno == EINTR || errno == EAGAIN { | ||
| continue // go back to epoll_wait | ||
| continue | ||
| } | ||
| throw POSIXError.fromErrno() | ||
| return [] | ||
| } | ||
|
|
||
| if n == 0 { | ||
| return // if epoll wait times out, then n will be 0 | ||
| return [] | ||
| } | ||
|
|
||
| var result: [Event] = [] | ||
| result.reserveCapacity(Int(n)) | ||
| for i in 0..<Int(n) { | ||
| let fd = events[i].data.fd | ||
| let mask = events[i].events | ||
|
|
||
| if fd == self.pipe.fileHandleForReading.fileDescriptor { | ||
| close(self.epollFD) | ||
| return // this is a shutdown message | ||
| if fd == self.shutdownReadFD { | ||
| return [] | ||
| } | ||
|
|
||
| guard let handler = handlers.get(fd) else { | ||
| continue | ||
| } | ||
| handler(Int32(bitPattern: mask)) | ||
| result.append(Event(fd: fd, mask: Mask(rawValue: events[i].events))) | ||
| } | ||
| return result | ||
| } | ||
| } | ||
|
|
||
| /// Remove the provided fd from the monitored collection. | ||
| public func delete(_ fd: Int32) throws { | ||
| var event = epoll_event() | ||
| let result = withUnsafeMutablePointer(to: &event) { ptr in | ||
| epoll_ctl(self.epollFD, EPOLL_CTL_DEL, fd, ptr) | ||
| } | ||
| if result != 0 { | ||
| if !acceptableDeletionErrno() { | ||
| throw POSIXError.fromErrno() | ||
| } | ||
| } | ||
| self.handlers.del(fd) | ||
| /// Signal the epoll loop to stop waiting. | ||
| public func shutdown() { | ||
| var byte: UInt8 = 0 | ||
| _ = Musl.write(shutdownWriteFD, &byte, 1) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this be not specific to Musl and just be |
||
| } | ||
|
|
||
| // The errno's here are acceptable and can happen if the caller | ||
| // closed the underlying fd before calling delete(). | ||
| private func acceptableDeletionErrno() -> Bool { | ||
| errno == ENOENT || errno == EBADF || errno == EPERM | ||
| } | ||
|
|
||
| /// Shutdown the epoll handler. | ||
| public func shutdown() throws { | ||
| // wakes up epoll_wait and triggers a shutdown | ||
| try self.pipe.fileHandleForWriting.close() | ||
| } | ||
|
|
||
| private final class SafeMap<Key: Hashable & Sendable, Value: Sendable>: Sendable { | ||
| let dict = Mutex<[Key: Value]>([:]) | ||
|
|
||
| func set(_ key: Key, _ value: Value) { | ||
| dict.withLock { @Sendable in | ||
| $0[key] = value | ||
| } | ||
| } | ||
|
|
||
| func get(_ key: Key) -> Value? { | ||
| dict.withLock { @Sendable in | ||
| $0[key] | ||
| } | ||
| } | ||
|
|
||
| func del(_ key: Key) { | ||
| dict.withLock { @Sendable in | ||
| _ = $0.removeValue(forKey: key) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| extension Epoll.Mask { | ||
| public var isHangup: Bool { | ||
| (self & (EPOLLHUP | EPOLLERR)) != 0 | ||
| } | ||
|
|
||
| public var isRhangup: Bool { | ||
| (self & EPOLLRDHUP) != 0 | ||
| } | ||
|
|
||
| public var readyToRead: Bool { | ||
| (self & EPOLLIN) != 0 | ||
| } | ||
|
|
||
| public var readyToWrite: Bool { | ||
| (self & EPOLLOUT) != 0 | ||
| } | ||
| } | ||
|
|
||
| #endif // canImport(Musl) | ||
| #endif // os(Linux) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we want to just return empty if
epoll_wait()happens to error withEBADForEFAULT? What's the reason we don't want to throw error here?