From ab11b74b391d650cc8aa2530157a68d559b7ee7c Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Mon, 8 Dec 2025 11:32:06 +0100 Subject: [PATCH 01/34] [IO_URING] Add support for `pollAdd` operation To observe events on file descriptors IO_URING supports the `pollAdd` operation. This is useful when you want to observe a file descriptor becoming ready to read or write This PR adds a new `IORing.Request.PollEvents` option set to model the poll masks. Furthermore, it adds a new `static func pollAdd` to the `IORing.Request`. We can now use IO_URING to poll for events on file descriptors. --- Sources/CSystem/include/io_uring.h | 2 + Sources/System/IORing/IORequest.swift | 80 ++++++++++++++++++++++++++ Sources/System/IORing/PollEvents.swift | 59 +++++++++++++++++++ Tests/SystemTests/IORingTests.swift | 60 ++++++++++++++++++- 4 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 Sources/System/IORing/PollEvents.swift diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index defc284..b422315 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -135,6 +135,8 @@ typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe; #define IORING_FEAT_RW_ATTR (1U << 16) #define IORING_FEAT_NO_IOWAIT (1U << 17) +#define IORING_POLL_ADD_MULTI (1U << 0) + #if !defined(_ASM_GENERIC_INT_LL64_H) && !defined(_ASM_GENERIC_INT_L64_H) && !defined(_UAPI_ASM_GENERIC_INT_LL64_H) && !defined(_UAPI_ASM_GENERIC_INT_L64_H) typedef uint8_t __u8; typedef uint16_t __u16; diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 4a388c4..100ce7b 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -23,6 +23,12 @@ internal enum IORequestCore { intoSlot: IORing.RegisteredFile, context: UInt64 = 0 ) + case pollAdd( + file: FileDescriptor, + pollEvents: IORing.Request.PollEvents, + isMultiShot: Bool = true, + context: UInt64 = 0 + ) case read( file: FileDescriptor, buffer: IORing.RegisteredBuffer, @@ -187,6 +193,72 @@ extension IORing.Request { .init(core: .nop) } + /// Adds a poll operation to monitor a file descriptor for specific I/O events. + /// + /// This method creates an io_uring poll operation that monitors the specified file descriptor + /// for I/O readiness events. The operation completes when any of the requested events become + /// active on the file descriptor, such as data becoming available for reading or the descriptor + /// becoming ready for writing. + /// + /// Poll operations are useful for implementing efficient I/O multiplexing, allowing you to + /// monitor multiple file descriptors concurrently within a single io_uring instance. When used + /// with multishot mode, a single poll operation can deliver multiple completion events without + /// needing to be resubmitted. + /// + /// ## Multishot Behavior + /// + /// When `isMultiShot` is `true`, the poll operation automatically rearms after each completion + /// event, continuing to monitor the file descriptor for subsequent events. This reduces + /// submission overhead for long-lived monitoring operations. The operation continues until + /// explicitly cancelled or the file descriptor is closed. + /// + /// When `isMultiShot` is `false`, the poll operation completes once after the first matching + /// event occurs, requiring resubmission to continue monitoring. + /// + /// ## Example Usage + /// + /// ```swift + /// // Monitor a socket for incoming connections + /// let pollRequest = IORing.Request.pollAdd( + /// listenSocket, + /// pollEvents: .pollin, + /// isMultiShot: true, + /// context: 1 + /// ) + /// try ring.submit(pollRequest) + /// + /// // Process completions + /// for completion in try ring.completions() { + /// if completion.context == 1 { + /// // Handle incoming connection + /// } + /// } + /// ``` + /// + /// - Parameters: + /// - file: The file descriptor to monitor for I/O events. + /// - pollEvents: The I/O events to monitor on the file descriptor. + /// - isMultiShot: If `true`, the poll operation automatically rearms after each event, + /// continuing to monitor the file descriptor. If `false`, the operation completes after + /// the first matching event. Defaults to `false`. + /// - context: An application-specific value passed through to the completion event, + /// allowing you to identify which operation completed. Defaults to `0`. + /// + /// - Returns: An I/O ring request that monitors the file descriptor for the specified events. + /// + /// ## See Also + /// + /// - ``PollEvents``: The events that can be monitored. + /// - ``IORing/Request/cancel(_:matching:)``: Cancelling poll operations. + @inlinable public static func pollAdd( + _ file: FileDescriptor, + pollEvents: PollEvents, + isMultiShot: Bool = false, + context: UInt64 = 0 + ) -> IORing.Request { + .init(core: .pollAdd(file: file, pollEvents: pollEvents, context: context)) + } + @inlinable public static func read( _ file: IORing.RegisteredFile, into buffer: IORing.RegisteredBuffer, @@ -477,6 +549,14 @@ extension IORing.Request { case .cancel(let flags): request.operation = .asyncCancel request.cancel_flags = flags + case .pollAdd(let file, let pollEvents, let isMultiShot, let context): + request.operation = .pollAdd + request.fileDescriptor = file + request.rawValue.user_data = context + if isMultiShot { + request.rawValue.len = IORING_POLL_ADD_MULTI + } + request.rawValue.poll32_events = pollEvents.rawValue } return request diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift new file mode 100644 index 0000000..ea8b829 --- /dev/null +++ b/Sources/System/IORing/PollEvents.swift @@ -0,0 +1,59 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2020 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information + */ + +#if compiler(>=6.2) && $Lifetimes +#if os(Linux) +extension IORing.Request { + /// A set of I/O events that can be monitored on a file descriptor. + /// + /// `PollEvents` represents the event mask used with io_uring poll operations to specify + /// which I/O conditions to monitor on a file descriptor. These events correspond to the + /// standard Posix poll events defined in the kernel's `poll.h` header. + /// + /// Use `PollEvents` with ``IORing/Request/pollAdd(_:pollEvents:isMultiShot:context:)`` + /// to register interest in specific I/O events. The poll operation completes when any of + /// the specified events become active on the file descriptor. + /// + /// ## Usage + /// + /// ```swift + /// // Monitor a socket for incoming data + /// let request = IORing.Request.pollAdd( + /// socketFD, + /// pollEvents: .pollin, + /// isMultiShot: true + /// ) + /// ``` + public struct PollEvents: OptionSet, Hashable, Codable { + public var rawValue: UInt32 + + @inlinable + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + /// An event indicating data is available for reading. + /// + /// This event becomes active when data arrives on the file descriptor and can be read + /// without blocking. For sockets, this includes when a new connection is available on + /// a listening socket. Corresponds to the Posix `POLLIN` event flag. + @inlinable + public static var pollIn: PollEvents { PollEvents(rawValue: 0x0001) } + + /// An event indicating the file descriptor is ready for writing. + /// + /// This event becomes active when writing to the file descriptor will not block. For + /// sockets, this indicates that send buffer space is available. Corresponds to the + /// Posix `POLLOUT` event flag. + @inlinable + public static var pollOut: PollEvents { PollEvents(rawValue: 0x0004) } + } +} +#endif +#endif diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 97bf86c..012a70d 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -177,7 +177,7 @@ final class IORingTests: XCTestCase { let bytesRead = try nonRingFD.read(into: rawBuffer) XCTAssert(bytesRead == 13) let result2 = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!) - XCTAssertEqual(result2, "Hello, World!") + XCTAssertEqual(result2, "Hello, World!") try cleanUpHelloWorldFile(parent) efdBuf.deallocate() rawBuffer.deallocate() @@ -310,6 +310,64 @@ final class IORingTests: XCTestCase { XCTAssertEqual(error, Errno(rawValue: EBADFD)) } } + + func testPollAddPollIn() throws { + guard uringEnabled else { try XCTSkip("System does not support IOring") } + var ring = try IORing(queueDepth: 32, flags: []) + + // Test POLLIN: Create an eventfd to monitor for read readiness + let testEventFD = FileDescriptor(rawValue: eventfd(0, 0)) + defer { + // Clean up + try! testEventFD.close() + } + let pollInContext: UInt64 = 42 + + // Submit a pollAdd request to monitor for POLLIN events (data available for reading) + let enqueued = try ring.submit(linkedRequests: + .pollAdd(testEventFD, pollEvents: .pollin, isMultiShot: false, context: pollInContext)) + XCTAssert(enqueued) + + // Write to the eventfd to trigger the POLLIN event + var value: UInt64 = 1 + withUnsafeBytes(of: &value) { bufferPtr in + _ = try? testEventFD.write(bufferPtr) + } + + // Consume the completion from the poll operation + let completion = try ring.blockingConsumeCompletion() + XCTAssertEqual(completion.context, pollInContext) + XCTAssertGreaterThan(completion.result, 0) // Poll should return mask of ready events + } + + func testPollAddPollOut() throws { + guard uringEnabled else { try XCTSkip("System does not support IOring") } + var ring = try IORing(queueDepth: 32, flags: []) + + // Test POLLOUT: Create a pipe to monitor for write readiness + var pipeFDs: [Int32] = [0, 0] + let pipeResult = pipe(&pipeFDs) + XCTAssertEqual(pipeResult, 0) + let writeFD = FileDescriptor(rawValue: pipeFDs[1]) + let readFD = FileDescriptor(rawValue: pipeFDs[0]) + defer { + // Clean up + try! writeFD.close() + try! readFD.close() + } + let pollOutContext: UInt64 = 43 + + // Submit a pollAdd request to monitor for POLLOUT events (ready for writing) + // Pipes are typically ready for writing when empty + let enqueuedOut = try ring.submit(linkedRequests: + .pollAdd(writeFD, pollEvents: .pollout, isMultiShot: false, context: pollOutContext)) + XCTAssert(enqueuedOut) + + // Consume the completion from the poll operation + let completionOut = try ring.blockingConsumeCompletion() + XCTAssertEqual(completionOut.context, pollOutContext) + XCTAssertGreaterThan(completionOut.result, 0) // Poll should return mask of ready events + } } #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes From e4b352c650b714042aaf2a0007e5683716445cff Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 13 Jan 2026 13:02:23 -0800 Subject: [PATCH 02/34] [test] fix spelling error --- Tests/SystemTests/IORingTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 012a70d..8bbd3d2 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -325,7 +325,7 @@ final class IORingTests: XCTestCase { // Submit a pollAdd request to monitor for POLLIN events (data available for reading) let enqueued = try ring.submit(linkedRequests: - .pollAdd(testEventFD, pollEvents: .pollin, isMultiShot: false, context: pollInContext)) + .pollAdd(testEventFD, pollEvents: .pollIn, isMultiShot: false, context: pollInContext)) XCTAssert(enqueued) // Write to the eventfd to trigger the POLLIN event @@ -360,7 +360,7 @@ final class IORingTests: XCTestCase { // Submit a pollAdd request to monitor for POLLOUT events (ready for writing) // Pipes are typically ready for writing when empty let enqueuedOut = try ring.submit(linkedRequests: - .pollAdd(writeFD, pollEvents: .pollout, isMultiShot: false, context: pollOutContext)) + .pollAdd(writeFD, pollEvents: .pollOut, isMultiShot: false, context: pollOutContext)) XCTAssert(enqueuedOut) // Consume the completion from the poll operation From e775d1bf59d24370a2879034fa5b64e3d68bbdec Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Wed, 14 Jan 2026 16:06:27 +0100 Subject: [PATCH 03/34] Apply suggestion from @MarSe32m Co-authored-by: Martin --- Sources/System/IORing/IORequest.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 100ce7b..6a99591 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -256,7 +256,7 @@ extension IORing.Request { isMultiShot: Bool = false, context: UInt64 = 0 ) -> IORing.Request { - .init(core: .pollAdd(file: file, pollEvents: pollEvents, context: context)) + .init(core: .pollAdd(file: file, pollEvents: pollEvents, isMultiShot: isMultiShot, context: context)) } @inlinable public static func read( From 2a069e401bb43761c914c85a8ceb4bd3f08354b1 Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Wed, 14 Jan 2026 23:03:46 +0100 Subject: [PATCH 04/34] Update Sources/System/IORing/IORequest.swift --- Sources/System/IORing/IORequest.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 6a99591..6aedac7 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -196,8 +196,8 @@ extension IORing.Request { /// Adds a poll operation to monitor a file descriptor for specific I/O events. /// /// This method creates an io_uring poll operation that monitors the specified file descriptor - /// for I/O readiness events. The operation completes when any of the requested events become - /// active on the file descriptor, such as data becoming available for reading or the descriptor + /// for I/O readiness events. The operation completes when any of the requested events + /// occur on the file descriptor, such as data becoming available for reading or the descriptor /// becoming ready for writing. /// /// Poll operations are useful for implementing efficient I/O multiplexing, allowing you to From dd5313284d3e030aede35cc040f9e27b442103ab Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 27 Jul 2026 14:55:39 -0700 Subject: [PATCH 05/34] [cmake] add new file to configuration --- Sources/System/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/CMakeLists.txt b/Sources/System/CMakeLists.txt index a904eb1..d41e7ac 100644 --- a/Sources/System/CMakeLists.txt +++ b/Sources/System/CMakeLists.txt @@ -49,6 +49,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL Linux) IORing/IORequest.swift IORing/IORing.swift IORing/IORing+Util.swift + IORing/PollEvents.swift IORing/RawIORequest.swift) endif() target_sources(SystemPackage PRIVATE From 27b4a4a03a4f5c4a922023c6ffeaf3b21da6e0be Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 27 Jul 2026 15:10:58 -0700 Subject: [PATCH 06/34] Use XCTSkipIf to guard IORing tests --- Tests/SystemTests/IORingTests.swift | 34 +++++++++++++++-------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 8bbd3d2..c4ad1da 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -25,6 +25,8 @@ let uringEnabled: Bool = { } }() +let failureMessage = "Runtime environment does not support IORing." + func isUringEnabled() throws -> Bool { // Even if the kernel supports io_uring, the SystemPackage build may have // been compiled against older kernel headers that lack features it needs @@ -83,12 +85,12 @@ final class IORingTests: XCTestCase { } func testInit() throws { - guard uringEnabled else { return } + try XCTSkipIf(!uringEnabled, failureMessage) _ = try IORing(queueDepth: 32, flags: []) } func testNop() throws { - guard uringEnabled else { return } + try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 32, flags: []) _ = try ring.submit(linkedRequests: .nop()) let completion = try ring.blockingConsumeCompletion() @@ -124,7 +126,7 @@ final class IORingTests: XCTestCase { } func testUndersizedSubmissionQueue() throws { - guard uringEnabled else { return } + try XCTSkipIf(!uringEnabled, failureMessage) var ring: IORing = try IORing(queueDepth: 1) let enqueued = ring.prepare(linkedRequests: .nop(), .nop()) XCTAssertFalse(enqueued) @@ -132,7 +134,7 @@ final class IORingTests: XCTestCase { // Exercises opening, reading, closing, registered files, registered buffers, and eventfd func testOpenReadAndWriteFixedFile() throws { - guard uringEnabled else { return } + try XCTSkipIf(!uringEnabled, failureMessage) let (parent, path) = try makeHelloWorldFile() let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer]) @@ -189,7 +191,7 @@ final class IORingTests: XCTestCase { // dangling pointer. Here we deliberately let the FilePath go out of scope // between prepare and submit, then churn the heap to make UAFs observable. func testPathBufferLifetimeAcrossPrepareSubmit() throws { - guard uringEnabled else { return } + try XCTSkipIf(!uringEnabled, failureMessage) let (parent, _) = try makeHelloWorldFile() var ring = try IORing(queueDepth: 6) @@ -223,7 +225,7 @@ final class IORingTests: XCTestCase { } func testPathBufferLifetimeAcrossLinkedRequests() throws { - guard uringEnabled else { return } + try XCTSkipIf(!uringEnabled, failureMessage) let (parent, _) = try makeHelloWorldFile() let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer]) @@ -260,12 +262,12 @@ final class IORingTests: XCTestCase { // Timeout test for `blockingConsumeCompletion(timeout:)`: func testBlockingConsumeCompletionWithTimeoutOnIdleRing() throws { - guard uringEnabled else { return } + try XCTSkipIf(!uringEnabled, failureMessage) let ring = try IORing(queueDepth: 4, flags: []) - guard ring.supportedFeatures.contains(.extendedArguments) else { - // Kernel < 5.11: timeouts in io_uring_enter aren't supported. - return - } + try XCTSkipIf( + !ring.supportedFeatures.contains(.extendedArguments), + "Kernel < 5.11: timeouts in io_uring_enter aren't supported." + ) let clock = ContinuousClock() let start = clock.now @@ -285,7 +287,7 @@ final class IORingTests: XCTestCase { } func testRegisterEventFDTwiceThrows() throws { - guard uringEnabled else { return } + try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 4) let efd = FileDescriptor(rawValue: eventfd(0, Int32(EFD_SEMAPHORE))) defer { try? efd.close() } @@ -300,10 +302,10 @@ final class IORingTests: XCTestCase { } func testSubmitOnDisabledRingThrows() throws { - guard uringEnabled else { return } + try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 4, flags: [.startDisabled]) - do throws(Errno) { + do throws(Errno) { _ = try ring.submit(linkedRequests: .nop()) XCTFail("expected submit on a disabled ring to throw") } catch { @@ -312,7 +314,7 @@ final class IORingTests: XCTestCase { } func testPollAddPollIn() throws { - guard uringEnabled else { try XCTSkip("System does not support IOring") } + try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 32, flags: []) // Test POLLIN: Create an eventfd to monitor for read readiness @@ -341,7 +343,7 @@ final class IORingTests: XCTestCase { } func testPollAddPollOut() throws { - guard uringEnabled else { try XCTSkip("System does not support IOring") } + try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 32, flags: []) // Test POLLOUT: Create a pipe to monitor for write readiness From 6baba54adb8884d626e2df7c65316c35102f5ba9 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 27 Jul 2026 17:38:31 -0700 Subject: [PATCH 07/34] Reflow or improve some doc-comments --- Sources/System/IORing/IORequest.swift | 124 +++++++++++++++++-------- Sources/System/IORing/PollEvents.swift | 29 +++--- 2 files changed, 99 insertions(+), 54 deletions(-) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 6aedac7..ac0c2e1 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -194,41 +194,55 @@ extension IORing.Request { } /// Adds a poll operation to monitor a file descriptor for specific I/O events. + /// Adds a poll operation to monitor a file descriptor for specific I/O + /// events. /// - /// This method creates an io_uring poll operation that monitors the specified file descriptor - /// for I/O readiness events. The operation completes when any of the requested events - /// occur on the file descriptor, such as data becoming available for reading or the descriptor - /// becoming ready for writing. + /// This method creates an io_uring poll operation that monitors the + /// specified file descriptor for I/O readiness events. The operation + /// completes when any of the requested events occur on the file + /// descriptor, such as data becoming available for reading or the + /// descriptor becoming ready for writing. /// - /// Poll operations are useful for implementing efficient I/O multiplexing, allowing you to - /// monitor multiple file descriptors concurrently within a single io_uring instance. When used - /// with multishot mode, a single poll operation can deliver multiple completion events without - /// needing to be resubmitted. + /// Poll operations are useful for implementing efficient I/O + /// multiplexing, allowing you to monitor multiple file descriptors + /// concurrently within a single io_uring instance. When used with + /// multishot mode, a single poll operation can deliver multiple + /// completion events without needing to be resubmitted. /// /// ## Multishot Behavior /// - /// When `isMultiShot` is `true`, the poll operation automatically rearms after each completion - /// event, continuing to monitor the file descriptor for subsequent events. This reduces - /// submission overhead for long-lived monitoring operations. The operation continues until - /// explicitly cancelled or the file descriptor is closed. + /// When `isMultiShot` is `true`, the poll operation automatically rearms + /// after each completion event, continuing to monitor the file descriptor + /// for subsequent events. This reduces submission overhead for long-lived + /// monitoring operations. The operation continues until explicitly + /// cancelled or the file descriptor is closed. /// - /// When `isMultiShot` is `false`, the poll operation completes once after the first matching - /// event occurs, requiring resubmission to continue monitoring. + /// When `isMultiShot` is `false`, the poll operation completes once after + /// the first matching event occurs, requiring resubmission to continue + /// monitoring. /// /// ## Example Usage /// /// ```swift /// // Monitor a socket for incoming connections + /// var ring = try IORing(queueDepth: 32) /// let pollRequest = IORing.Request.pollAdd( /// listenSocket, - /// pollEvents: .pollin, + /// pollEvents: .pollIn, /// isMultiShot: true, /// context: 1 /// ) - /// try ring.submit(pollRequest) + /// guard try ring.submit(linkedRequests: pollRequest) else { + /// // The submission queue was full; retry or drain completions first. + /// return + /// } /// - /// // Process completions - /// for completion in try ring.completions() { + /// // Process completions. A multishot poll stays armed while its + /// // completions contain `.moreCompletions`. + /// var armed = true + /// while armed { + /// let completion = try ring.blockingConsumeCompletion() + /// armed = completion.flags.contains(.moreCompletions) /// if completion.context == 1 { /// // Handle incoming connection /// } @@ -238,13 +252,16 @@ extension IORing.Request { /// - Parameters: /// - file: The file descriptor to monitor for I/O events. /// - pollEvents: The I/O events to monitor on the file descriptor. - /// - isMultiShot: If `true`, the poll operation automatically rearms after each event, - /// continuing to monitor the file descriptor. If `false`, the operation completes after - /// the first matching event. Defaults to `false`. - /// - context: An application-specific value passed through to the completion event, - /// allowing you to identify which operation completed. Defaults to `0`. + /// - isMultiShot: If `true`, the poll operation automatically rearms + /// after each event, continuing to monitor the file descriptor. If + /// `false`, the operation completes after the first matching event. + /// Defaults to `false`. + /// - context: An application-specific value passed through to the + /// completion event, allowing you to identify which operation + /// completed. Defaults to `0`. /// - /// - Returns: An I/O ring request that monitors the file descriptor for the specified events. + /// - Returns: An I/O ring request that monitors the file descriptor for + /// the specified events. /// /// ## See Also /// @@ -388,24 +405,49 @@ extension IORing.Request { // Cancel - /* - * ASYNC_CANCEL flags. - * - * IORING_ASYNC_CANCEL_ALL Cancel all requests that match the given key - * IORING_ASYNC_CANCEL_FD Key off 'fd' for cancellation rather than the - * request 'user_data' - * IORING_ASYNC_CANCEL_ANY Match any request - * IORING_ASYNC_CANCEL_FD_FIXED 'fd' passed in is a fixed descriptor - * IORING_ASYNC_CANCEL_USERDATA Match on user_data, default for no other key - * IORING_ASYNC_CANCEL_OP Match request based on opcode - */ + /// Cancel every request matching the given key, rather than only the + /// first one found. + /// + /// Corresponds to `IORING_ASYNC_CANCEL_ALL`. + @_alwaysEmitIntoClient + internal static var SWIFT_IORING_ASYNC_CANCEL_ALL: UInt32 { 1 << 0 } -@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_ALL: UInt32 { 1 << 0 } -@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_FD: UInt32 { 1 << 1 } -@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_ANY: UInt32 { 1 << 2 } -@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { 1 << 3 } -@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_USERDATA: UInt32 { 1 << 4 } -@inlinable internal static var SWIFT_IORING_ASYNC_CANCEL_OP: UInt32 { 1 << 5 } + /// Match requests on `sqe->fd`, rather than on their `user_data`. + /// + /// Corresponds to `IORING_ASYNC_CANCEL_FD`. Cannot be combined with + /// ``SWIFT_IORING_ASYNC_CANCEL_ANY``. + @_alwaysEmitIntoClient + internal static var SWIFT_IORING_ASYNC_CANCEL_FD: UInt32 { 1 << 1 } + + /// Match any request, disregarding every other key. + /// + /// Corresponds to `IORING_ASYNC_CANCEL_ANY`. Cannot be combined with + /// ``SWIFT_IORING_ASYNC_CANCEL_FD`` or ``SWIFT_IORING_ASYNC_CANCEL_OP``. + @_alwaysEmitIntoClient + internal static var SWIFT_IORING_ASYNC_CANCEL_ANY: UInt32 { 1 << 2 } + + /// The descriptor to match against is a registered file, so `sqe->fd` + /// carries a slot index rather than a file descriptor. + /// + /// Corresponds to `IORING_ASYNC_CANCEL_FD_FIXED`, and accompanies + /// ``SWIFT_IORING_ASYNC_CANCEL_FD``. + @_alwaysEmitIntoClient + internal static var SWIFT_IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { 1 << 3 } + + /// Match requests on their `user_data`. This is the default when no other + /// key is given. + /// + /// Corresponds to `IORING_ASYNC_CANCEL_USERDATA`. + @_alwaysEmitIntoClient + internal static var SWIFT_IORING_ASYNC_CANCEL_USERDATA: UInt32 { 1 << 4 } + + /// Match requests by operation. Note that the opcode to match is read + /// from `sqe->len`. + /// + /// Corresponds to `IORING_ASYNC_CANCEL_OP`. Cannot be combined with + /// ``SWIFT_IORING_ASYNC_CANCEL_ANY``. + @_alwaysEmitIntoClient + internal static var SWIFT_IORING_ASYNC_CANCEL_OP: UInt32 { 1 << 5 } public enum CancellationMatch { case all diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index ea8b829..e24f816 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -12,13 +12,15 @@ extension IORing.Request { /// A set of I/O events that can be monitored on a file descriptor. /// - /// `PollEvents` represents the event mask used with io_uring poll operations to specify - /// which I/O conditions to monitor on a file descriptor. These events correspond to the - /// standard Posix poll events defined in the kernel's `poll.h` header. + /// `PollEvents` represents the event mask used with io_uring poll + /// operations to specify which I/O conditions to monitor on a file + /// descriptor. These events correspond to the standard Posix poll events + /// defined in the kernel's `poll.h` header. /// - /// Use `PollEvents` with ``IORing/Request/pollAdd(_:pollEvents:isMultiShot:context:)`` - /// to register interest in specific I/O events. The poll operation completes when any of - /// the specified events become active on the file descriptor. + /// Use `PollEvents` with + /// ``IORing/Request/pollAdd(_:pollEvents:isMultiShot:context:)`` to + /// register interest in specific I/O events. The poll operation completes + /// when any of the specified events become active on the file descriptor. /// /// ## Usage /// @@ -26,7 +28,7 @@ extension IORing.Request { /// // Monitor a socket for incoming data /// let request = IORing.Request.pollAdd( /// socketFD, - /// pollEvents: .pollin, + /// pollEvents: .pollIn, /// isMultiShot: true /// ) /// ``` @@ -40,17 +42,18 @@ extension IORing.Request { /// An event indicating data is available for reading. /// - /// This event becomes active when data arrives on the file descriptor and can be read - /// without blocking. For sockets, this includes when a new connection is available on - /// a listening socket. Corresponds to the Posix `POLLIN` event flag. + /// This event becomes active when data arrives on the file descriptor + /// and can be read without blocking. For sockets, this includes when + /// a new connection is available on a listening socket. Corresponds + /// to the Posix `POLLIN` event flag. @inlinable public static var pollIn: PollEvents { PollEvents(rawValue: 0x0001) } /// An event indicating the file descriptor is ready for writing. /// - /// This event becomes active when writing to the file descriptor will not block. For - /// sockets, this indicates that send buffer space is available. Corresponds to the - /// Posix `POLLOUT` event flag. + /// This event becomes active when writing to the file descriptor will + /// not block. For sockets, this indicates that send buffer space is + /// available. Corresponds to the Posix `POLLOUT` event flag. @inlinable public static var pollOut: PollEvents { PollEvents(rawValue: 0x0004) } } From 5b7e24a6b1b02f627de3a24480eeb59e1275de7d Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 27 Jul 2026 17:39:14 -0700 Subject: [PATCH 08/34] Define a constant in Swift rather than in C --- Sources/CSystem/include/io_uring.h | 2 -- Sources/System/IORing/IORequest.swift | 15 +++++++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index b422315..defc284 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -135,8 +135,6 @@ typedef struct __SWIFT_IORING_SQE_FALLBACK_STRUCT swift_io_uring_sqe; #define IORING_FEAT_RW_ATTR (1U << 16) #define IORING_FEAT_NO_IOWAIT (1U << 17) -#define IORING_POLL_ADD_MULTI (1U << 0) - #if !defined(_ASM_GENERIC_INT_LL64_H) && !defined(_ASM_GENERIC_INT_L64_H) && !defined(_UAPI_ASM_GENERIC_INT_LL64_H) && !defined(_UAPI_ASM_GENERIC_INT_L64_H) typedef uint8_t __u8; typedef uint16_t __u16; diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index ac0c2e1..72ddcac 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -193,7 +193,18 @@ extension IORing.Request { .init(core: .nop) } - /// Adds a poll operation to monitor a file descriptor for specific I/O events. + // Poll + + /// Multishot poll: the poll handler continues to report CQEs on behalf + /// of the same SQE, each flagged with + /// ``IORing/Completion/Flags/moreCompletions``. + /// + /// Corresponds to `IORING_POLL_ADD_MULTI`. Note that since + /// `sqe->poll_events` is the event space, the command flags for + /// `POLL_ADD` are stored in `sqe->len`. + @_alwaysEmitIntoClient + internal static var SWIFT_IORING_POLL_ADD_MULTI: UInt32 { 1 << 0 } + /// Adds a poll operation to monitor a file descriptor for specific I/O /// events. /// @@ -596,7 +607,7 @@ extension IORing.Request { request.fileDescriptor = file request.rawValue.user_data = context if isMultiShot { - request.rawValue.len = IORING_POLL_ADD_MULTI + request.rawValue.len = Self.SWIFT_IORING_POLL_ADD_MULTI } request.rawValue.poll32_events = pollEvents.rawValue } From 75c85d47e7cff5bdc7c5f654a76459bccace5fcc Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 27 Jul 2026 18:33:21 -0700 Subject: [PATCH 09/34] Account for big-endian architectures for poll event encoding --- Sources/System/IORing/IORequest.swift | 2 +- Sources/System/IORing/RawIORequest.swift | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 72ddcac..dfe2dba 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -609,7 +609,7 @@ extension IORing.Request { if isMultiShot { request.rawValue.len = Self.SWIFT_IORING_POLL_ADD_MULTI } - request.rawValue.poll32_events = pollEvents.rawValue + request.pollEvents = pollEvents } return request diff --git a/Sources/System/IORing/RawIORequest.swift b/Sources/System/IORing/RawIORequest.swift index 1de6013..507fc0d 100644 --- a/Sources/System/IORing/RawIORequest.swift +++ b/Sources/System/IORing/RawIORequest.swift @@ -75,6 +75,27 @@ extension RawIORequest { set { rawValue.addr = newValue } } + /// The poll event mask, stored in `sqe->poll32_events`. + /// + /// Big-endian kernels swap the halfwords of this field before reading it. + /// Equivalent to liburing's `__io_uring_prep_poll_mask`. + @_alwaysEmitIntoClient var pollEvents: IORing.Request.PollEvents { + get { .init(rawValue: _applyPollMask(rawValue.poll32_events)) } + set { rawValue.poll32_events = _applyPollMask(newValue.rawValue) } + } + + /// Converts a poll event mask between its in-memory and `sqe` encodings. + /// + /// This is a halfword rotate (`swahw32` from ``), which keeps + /// the byte order within each half. + @_alwaysEmitIntoClient func _applyPollMask(_ mask: UInt32) -> UInt32 { + #if _endian(big) + return (mask &<< 16) | (mask &>> 16) + #else + return mask + #endif + } + @inlinable public var flags: Flags { get { Flags(rawValue: rawValue.flags) } set { rawValue.flags = newValue.rawValue } From 2e81d9414205b30ecfc705e54e745630d68f7e9e Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 27 Jul 2026 18:58:49 -0700 Subject: [PATCH 10/34] Add a test similar to the example in the pollAdd doc-comment --- Tests/SystemTests/IORingTests.swift | 113 ++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index c4ad1da..8759e22 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -370,6 +370,119 @@ final class IORingTests: XCTestCase { XCTAssertEqual(completionOut.context, pollOutContext) XCTAssertGreaterThan(completionOut.result, 0) // Poll should return mask of ready events } + + // Similar to the multishot example in the documentation for + // `pollAdd(_:pollEvents:isMultiShot:context:)`: arm a multishot poll, + // then consume completions for as long as they carry `.moreCompletions`. + func testPollAddMultiShotRearmsAcrossEvents() throws { + try XCTSkipIf(!uringEnabled, failureMessage) + var ring = try IORing(queueDepth: 32, flags: []) + + // Every wait below has a timeout, so that a poll that fails to fire + // causes a test failure. + try XCTSkipIf( + !ring.supportedFeatures.contains(.extendedArguments), + "Kernel < 5.11: timeouts in io_uring_enter aren't supported." + ) + + var pipeFDs: [Int32] = [0, 0] + XCTAssertEqual(pipe(&pipeFDs), 0) + let readFD = FileDescriptor(rawValue: pipeFDs[0]) + let writeFD = FileDescriptor(rawValue: pipeFDs[1]) + defer { + try? readFD.close() + try? writeFD.close() + } + + func writeByte() throws { + var byte: UInt8 = 1 + try withUnsafeBytes(of: &byte) { + try XCTAssertEqual(writeFD.write($0), 1) + } + } + + func readByte() throws { + var scratch: UInt8 = 0 + try withUnsafeMutableBytes(of: &scratch) { + try XCTAssertEqual(readFD.read(into: $0), 1) + } + } + + let context: UInt64 = 44 + let pollIn = Int32(IORing.Request.PollEvents.pollIn.rawValue) + + let pollRequest = IORing.Request.pollAdd( + readFD, pollEvents: .pollIn, isMultiShot: true, context: context + ) + let enqueued = try ring.submit(linkedRequests: pollRequest) + XCTAssert(enqueued) + + try writeByte() + let first = try ring.blockingConsumeCompletion(timeout: .seconds(1)) + // Kernels before 5.13 reject IORING_POLL_ADD_MULTI + try XCTSkipIf( + first.result == -EINVAL, + "Kernel < 5.13: multishot poll is unsupported." + ) + XCTAssertEqual(first.context, context) + XCTAssertNotEqual( + first.result & pollIn, 0, "expected POLLIN in the result mask" + ) + XCTAssert(first.flags.contains(.moreCompletions)) + + // Drain the pipe, then any extra completions. + try readByte() + while ring.tryConsumeCompletion() != nil {} + + try writeByte() + // This written byte will only be reported by a re-armed poll. + let second = try ring.blockingConsumeCompletion(timeout: .seconds(1)) + XCTAssertEqual(second.context, context) + XCTAssertNotEqual( + second.result & pollIn, 0, "expected POLLIN in the result mask" + ) + + // Drain again + try readByte() + while ring.tryConsumeCompletion() != nil {} + + // Cancel to end the multishot poll. + try XCTAssert( + ring.submit(linkedRequests: .cancel(.all, matchingContext: context)) + ) + var terminal: (result: Int32, flags: IORing.Completion.Flags)? = nil + var observed: [(context: UInt64, result: Int32, flags: UInt32)] = [] + // The cancel posts a completion of its own under a different context, + // and the two may land a moment apart, so retry briefly rather than + // draining exactly once. + for _ in 0..<100 where terminal == nil { + while let completion = ring.tryConsumeCompletion() { + observed.append( + ( + completion.context, + completion.result, + completion.flags.rawValue + ) + ) + if completion.context == context { + terminal = (completion.result, completion.flags) + } + } + if terminal == nil { usleep(1000) } + } + XCTAssertNotNil( + terminal, + "no terminal completion for the cancelled poll; " + + "completions seen: \(observed)" + ) + if let terminal { + XCTAssertEqual(terminal.result, -ECANCELED) + XCTAssertFalse( + terminal.flags.contains(.moreCompletions), + "poll kept its armed state after being cancelled" + ) + } + } } #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes From bed8e2886096518866e2cd75ffdd868836804294 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 27 Jul 2026 19:28:02 -0700 Subject: [PATCH 11/34] Clean up permissively --- Tests/SystemTests/IORingTests.swift | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 8759e22..8b97e7f 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -320,8 +320,7 @@ final class IORingTests: XCTestCase { // Test POLLIN: Create an eventfd to monitor for read readiness let testEventFD = FileDescriptor(rawValue: eventfd(0, 0)) defer { - // Clean up - try! testEventFD.close() + try? testEventFD.close() } let pollInContext: UInt64 = 42 @@ -353,9 +352,8 @@ final class IORingTests: XCTestCase { let writeFD = FileDescriptor(rawValue: pipeFDs[1]) let readFD = FileDescriptor(rawValue: pipeFDs[0]) defer { - // Clean up - try! writeFD.close() - try! readFD.close() + try? writeFD.close() + try? readFD.close() } let pollOutContext: UInt64 = 43 From 0ecb080d5cea42fed8d4cf32fe5823b08d8d6266 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 27 Jul 2026 19:28:43 -0700 Subject: [PATCH 12/34] Test ready events in a better way --- Tests/SystemTests/IORingTests.swift | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 8b97e7f..83e856c 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -338,7 +338,10 @@ final class IORingTests: XCTestCase { // Consume the completion from the poll operation let completion = try ring.blockingConsumeCompletion() XCTAssertEqual(completion.context, pollInContext) - XCTAssertGreaterThan(completion.result, 0) // Poll should return mask of ready events + let pollIn = Int32(IORing.Request.PollEvents.pollIn.rawValue) + XCTAssertNotEqual( + completion.result & pollIn, 0, "expected POLLIN in the result mask" + ) } func testPollAddPollOut() throws { @@ -366,7 +369,11 @@ final class IORingTests: XCTestCase { // Consume the completion from the poll operation let completionOut = try ring.blockingConsumeCompletion() XCTAssertEqual(completionOut.context, pollOutContext) - XCTAssertGreaterThan(completionOut.result, 0) // Poll should return mask of ready events + let pollOut = Int32(IORing.Request.PollEvents.pollOut.rawValue) + XCTAssertNotEqual( + completionOut.result & pollOut, 0, + "expected POLLOUT in the result mask" + ) } // Similar to the multishot example in the documentation for From bd49600d622d577592a144724a593654d5a70392 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Mon, 27 Jul 2026 19:36:12 -0700 Subject: [PATCH 13/34] Prevent tests from hanging in the wrong conditions --- Tests/SystemTests/IORingTests.swift | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 83e856c..d363948 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -317,6 +317,12 @@ final class IORingTests: XCTestCase { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 32, flags: []) + // We use the timeout feature below. + try XCTSkipIf( + !ring.supportedFeatures.contains(.extendedArguments), + "Kernel < 5.11: timeouts in io_uring_enter aren't supported." + ) + // Test POLLIN: Create an eventfd to monitor for read readiness let testEventFD = FileDescriptor(rawValue: eventfd(0, 0)) defer { @@ -336,7 +342,9 @@ final class IORingTests: XCTestCase { } // Consume the completion from the poll operation - let completion = try ring.blockingConsumeCompletion() + let completion = try ring.blockingConsumeCompletion( + timeout: .seconds(1) + ) XCTAssertEqual(completion.context, pollInContext) let pollIn = Int32(IORing.Request.PollEvents.pollIn.rawValue) XCTAssertNotEqual( @@ -348,6 +356,12 @@ final class IORingTests: XCTestCase { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 32, flags: []) + // We use the timeout feature below. + try XCTSkipIf( + !ring.supportedFeatures.contains(.extendedArguments), + "Kernel < 5.11: timeouts in io_uring_enter aren't supported." + ) + // Test POLLOUT: Create a pipe to monitor for write readiness var pipeFDs: [Int32] = [0, 0] let pipeResult = pipe(&pipeFDs) @@ -367,7 +381,9 @@ final class IORingTests: XCTestCase { XCTAssert(enqueuedOut) // Consume the completion from the poll operation - let completionOut = try ring.blockingConsumeCompletion() + let completionOut = try ring.blockingConsumeCompletion( + timeout: .seconds(1) + ) XCTAssertEqual(completionOut.context, pollOutContext) let pollOut = Int32(IORing.Request.PollEvents.pollOut.rawValue) XCTAssertNotEqual( From 980a71f20c0891f983288942a6376a3da6848406 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 28 Jul 2026 13:57:16 -0700 Subject: [PATCH 14/34] Add test to show that `PollEvents` has too few values --- Tests/SystemTests/IORingTests.swift | 41 +++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index d363948..f9cedca 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -504,6 +504,47 @@ final class IORingTests: XCTestCase { ) } } + + func testUnexpectedPollValue() throws { + try XCTSkipIf(!uringEnabled, failureMessage) + var ring = try IORing(queueDepth: 8) + let (readFD, writeFD) = try FileDescriptor.pipe() + defer { + try? readFD.close() + try? writeFD.close() + } + + try XCTSkipIf( + !ring.supportedFeatures.contains(.extendedArguments), + "Kernel < 5.11: timeouts in io_uring_enter aren't supported." + ) + + let request = IORing.Request.pollAdd( + readFD, pollEvents: .pollIn, isMultiShot: false, context: 97 + ) + let success = try ring.submit(linkedRequests: request) + XCTAssertEqual(success, true) + try writeFD.close() + + let dt = Duration.seconds(1) + let completion = try ring.blockingConsumeCompletion(timeout: dt) + + let values = [ // This should be caseIterable. + IORing.Request.PollEvents.pollIn.rawValue, + IORing.Request.PollEvents.pollOut.rawValue + ] + + for value in values { + if completion.result & Int32(value) != 0 { + // success! + return + } + } + + let pollValue = completion.result & 0x10 + XCTAssertEqual(pollValue, 0x10) + XCTFail("Unexpected poll event: 0x\(String(pollValue, radix: 16))") + } } #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes From a2ca84e281eb56370197e23d52192159e54d510d Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 28 Jul 2026 14:37:14 -0700 Subject: [PATCH 15/34] Round out `PollEvents` --- Sources/System/IORing/PollEvents.swift | 62 +++++++++++++++++++++++--- Tests/SystemTests/IORingTests.swift | 18 +++----- 2 files changed, 62 insertions(+), 18 deletions(-) diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index e24f816..d832597 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -14,7 +14,7 @@ extension IORing.Request { /// /// `PollEvents` represents the event mask used with io_uring poll /// operations to specify which I/O conditions to monitor on a file - /// descriptor. These events correspond to the standard Posix poll events + /// descriptor. These events correspond to the standard POSIX poll events /// defined in the kernel's `poll.h` header. /// /// Use `PollEvents` with @@ -32,7 +32,7 @@ extension IORing.Request { /// isMultiShot: true /// ) /// ``` - public struct PollEvents: OptionSet, Hashable, Codable { + public struct PollEvents: OptionSet, Hashable, Codable, CaseIterable { public var rawValue: UInt32 @inlinable @@ -40,22 +40,72 @@ extension IORing.Request { self.rawValue = rawValue } + @usableFromInline + init(_ event: Event) { + self.rawValue = event.rawValue + } + + @usableFromInline + enum Event: UInt32, RawRepresentable, Hashable, CaseIterable { + case pollIn = 0x0001 + case pollOut = 0x0004 + case pollErr = 0x0008 + case pollHup = 0x0010 + case pollNval = 0x0020 + } + + public static var allCases: [PollEvents] { + Event.allCases.map(PollEvents.init(_:)) + } + /// An event indicating data is available for reading. /// /// This event becomes active when data arrives on the file descriptor /// and can be read without blocking. For sockets, this includes when /// a new connection is available on a listening socket. Corresponds - /// to the Posix `POLLIN` event flag. + /// to the POSIX `POLLIN` event flag. @inlinable - public static var pollIn: PollEvents { PollEvents(rawValue: 0x0001) } + public static var pollIn: PollEvents { PollEvents(.pollIn) } /// An event indicating the file descriptor is ready for writing. /// /// This event becomes active when writing to the file descriptor will /// not block. For sockets, this indicates that send buffer space is - /// available. Corresponds to the Posix `POLLOUT` event flag. + /// available. Corresponds to the POSIX `POLLOUT` event flag. @inlinable - public static var pollOut: PollEvents { PollEvents(rawValue: 0x0004) } + public static var pollOut: PollEvents { PollEvents(.pollOut) } + + /// An event indicating an error condition on the file descriptor. + /// + /// The kernel reports this event whether or not it was requested, so + /// it can appear in a completion's result mask even when the poll + /// asked only for ``pollIn`` or ``pollOut``. Requesting it explicitly + /// has no effect. Corresponds to the POSIX `POLLERR` event flag. + @_alwaysEmitIntoClient + public static var pollErr: PollEvents { PollEvents(.pollErr) } + + /// An event indicating the peer closed its end of the channel. + /// + /// For a pipe this means the writing end was closed; for a socket, that + /// the connection was shut down. A descriptor reporting this event will + /// never become readable again, so treating it as "not ready yet" and + /// polling again will not make progress. + /// + /// The kernel reports this event whether or not it was requested, and + /// requesting it explicitly has no effect. Corresponds to the POSIX + /// `POLLHUP` event flag. + @_alwaysEmitIntoClient + public static var pollHup: PollEvents { PollEvents(.pollHup) } + + /// An event indicating the file descriptor is not open. + /// + /// This usually means the descriptor was closed, or was never valid. + /// + /// The kernel reports this event whether or not it was requested, and + /// requesting it explicitly has no effect. Corresponds to the POSIX + /// `POLLNVAL` event flag. + @_alwaysEmitIntoClient + public static var pollNval: PollEvents { PollEvents(.pollNval) } } } #endif diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index f9cedca..ab974b9 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -505,7 +505,7 @@ final class IORingTests: XCTestCase { } } - func testUnexpectedPollValue() throws { + func testPollHangup() throws { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 8) let (readFD, writeFD) = try FileDescriptor.pipe() @@ -529,21 +529,15 @@ final class IORingTests: XCTestCase { let dt = Duration.seconds(1) let completion = try ring.blockingConsumeCompletion(timeout: dt) - let values = [ // This should be caseIterable. - IORing.Request.PollEvents.pollIn.rawValue, - IORing.Request.PollEvents.pollOut.rawValue - ] - - for value in values { - if completion.result & Int32(value) != 0 { - // success! + for event in IORing.Request.PollEvents.allCases { + if completion.result & Int32(event.rawValue) != 0 { + XCTAssertEqual(event, .pollHup) return } } - let pollValue = completion.result & 0x10 - XCTAssertEqual(pollValue, 0x10) - XCTFail("Unexpected poll event: 0x\(String(pollValue, radix: 16))") + let unexpected = completion.result + XCTFail("Unexpected poll event: 0x\(String(unexpected, radix: 16))") } } #endif // os(Linux) From 4df226b09887be1629aff65eec63f86363ee9942 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 28 Jul 2026 14:49:03 -0700 Subject: [PATCH 16/34] Fix copyright notices --- Sources/System/IORing/IOCompletion.swift | 9 +++++++++ Sources/System/IORing/IORequest.swift | 9 +++++++++ Sources/System/IORing/IORing.swift | 9 +++++++++ Sources/System/IORing/PollEvents.swift | 2 +- Sources/System/IORing/RawIORequest.swift | 9 +++++++++ 5 files changed, 37 insertions(+), 1 deletion(-) diff --git a/Sources/System/IORing/IOCompletion.swift b/Sources/System/IORing/IOCompletion.swift index d9e6905..7ad858c 100644 --- a/Sources/System/IORing/IOCompletion.swift +++ b/Sources/System/IORing/IOCompletion.swift @@ -1,3 +1,12 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2023 - 2025 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + #if compiler(>=6.2) && $Lifetimes #if os(Linux) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index dfe2dba..8cec4e1 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -1,3 +1,12 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + #if compiler(>=6.2) && $Lifetimes #if os(Linux) diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 27d27a0..bd6087d 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -1,3 +1,12 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + #if compiler(>=6.2) && $Lifetimes #if os(Linux) diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index d832597..59f78ac 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 Apple Inc. and the Swift System project authors + Copyright (c) 2026 Apple Inc. and the Swift System project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information diff --git a/Sources/System/IORing/RawIORequest.swift b/Sources/System/IORing/RawIORequest.swift index 507fc0d..ab4eb56 100644 --- a/Sources/System/IORing/RawIORequest.swift +++ b/Sources/System/IORing/RawIORequest.swift @@ -1,3 +1,12 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2023 - 2026 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + #if compiler(>=6.2) && $Lifetimes #if os(Linux) From a6d4c153b7e09d70e6a5c102299e08445e226a4c Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 28 Jul 2026 15:19:02 -0700 Subject: [PATCH 17/34] Add test to demonstrate a POLLERR result --- Tests/SystemTests/IORingTests.swift | 38 +++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index ab974b9..cc6b8d1 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -539,6 +539,44 @@ final class IORingTests: XCTestCase { let unexpected = completion.result XCTFail("Unexpected poll event: 0x\(String(unexpected, radix: 16))") } + + func testPollError() throws { + try XCTSkipIf(!uringEnabled, failureMessage) + var ring = try IORing(queueDepth: 8) + let (readFD, writeFD) = try FileDescriptor.pipe(options: .nonBlocking) + defer { + try? readFD.close() + try? writeFD.close() + } + + try XCTSkipIf( + !ring.supportedFeatures.contains(.extendedArguments), + "Kernel < 5.11: timeouts in io_uring_enter aren't supported." + ) + + let chunk = [UInt8](repeating: 0, count: 4096) + chunk.withUnsafeBytes { + // Fill the pipe by writing until an operation fails + while let written = try? writeFD.write($0), written > 0 {} + } + + let request = IORing.Request.pollAdd( + writeFD, pollEvents: .pollOut, isMultiShot: false, context: 98 + ) + let success = try ring.submit(linkedRequests: request) + XCTAssertEqual(success, true) + try readFD.close() + + let dt = Duration.seconds(1) + let completion = try ring.blockingConsumeCompletion(timeout: dt) + XCTAssertEqual(completion.context, 98) + + let pollErr = IORing.Request.PollEvents.pollErr.rawValue + let result = completion.result & Int32(pollErr) + if result != pollErr { + XCTFail("expected POLLERR, got 0x\(String(result, radix: 16))") + } + } } #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes From d4373e36f6c35d831d3f3e5f2496484ba3f3d937 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 28 Jul 2026 16:20:56 -0700 Subject: [PATCH 18/34] Clarify .pollNval and add test reading from an invalid descriptor --- Sources/System/IORing/IOCompletion.swift | 7 ++++++ Sources/System/IORing/PollEvents.swift | 10 ++++++-- Tests/SystemTests/IORingTests.swift | 32 ++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/Sources/System/IORing/IOCompletion.swift b/Sources/System/IORing/IOCompletion.swift index 7ad858c..8a1bc71 100644 --- a/Sources/System/IORing/IOCompletion.swift +++ b/Sources/System/IORing/IOCompletion.swift @@ -54,6 +54,13 @@ public extension IORing.Completion { } } + /// The result of the completed operation. + /// + /// A non-negative value is the operation's success result: a byte count + /// for a read or a write, an event mask for a poll, and so on. + /// + /// A negative value is an `errno` code multiplied by -1. Recover the error + /// by negating it again: `Errno(rawValue: -completion.result)`. @inlinable var result: Int32 { get { rawValue.res diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index 59f78ac..b9b77e3 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -97,9 +97,15 @@ extension IORing.Request { @_alwaysEmitIntoClient public static var pollHup: PollEvents { PollEvents(.pollHup) } - /// An event indicating the file descriptor is not open. + /// An event indicating that the object a descriptor refers to is no + /// longer valid. /// - /// This usually means the descriptor was closed, or was never valid. + /// This arises when the descriptor itself resolves, but the thing it + /// refers to has since become invalid. For example, the disconnection + /// of a sound device could cause this event. + /// + /// Note that a descriptor which simply does not resolve would + /// return the EBADF error code (Errno.badFileDescriptor). /// /// The kernel reports this event whether or not it was requested, and /// requesting it explicitly has no effect. Corresponds to the POSIX diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index cc6b8d1..961af17 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -577,6 +577,38 @@ final class IORingTests: XCTestCase { XCTFail("expected POLLERR, got 0x\(String(result, radix: 16))") } } + + // A completion's `result` is two things in one field: a non-negative + // value is an event mask, and a negative value is a negated errno. The + // sign is the only thing distinguishing them, so it has to be checked + // before the value is treated as anything else. + func testPollAddOnInvalidDescriptor() throws { + try XCTSkipIf(!uringEnabled, failureMessage) + var ring = try IORing(queueDepth: 8) + + let request = IORing.Request.pollAdd( + FileDescriptor(rawValue: -1), pollEvents: .pollIn, + isMultiShot: false, context: 99 + ) + let success = try ring.submit(linkedRequests: request) + XCTAssertEqual(success, true) + + guard let completion = ring.tryConsumeCompletion() else { + XCTFail("expected a completion for the failed poll") + return + } + XCTAssertEqual(completion.context, 99) + + // A negative value for `result` marks the completion a a failure. + XCTAssertLessThan(completion.result, 0, "expected a failure") + // The negative value is the error code multiplied by -1. + XCTAssertEqual(Errno(rawValue: -completion.result), .badFileDescriptor) + + // A negative result may look like another result code. + // Checking for the error must happen first. + let pollNval = Int32(IORing.Request.PollEvents.pollNval.rawValue) + XCTAssertNotEqual(completion.result & pollNval, 0) + } } #endif // os(Linux) #endif // compiler(>=6.2) && $Lifetimes From 6e3259aec35aae30f61ff641fea63331d72ce913 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Tue, 28 Jul 2026 16:51:19 -0700 Subject: [PATCH 19/34] Better explain a skip condition --- Tests/SystemTests/IORingTests.swift | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 961af17..e3b45b5 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -317,7 +317,7 @@ final class IORingTests: XCTestCase { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 32, flags: []) - // We use the timeout feature below. + // This test case requires timeout support try XCTSkipIf( !ring.supportedFeatures.contains(.extendedArguments), "Kernel < 5.11: timeouts in io_uring_enter aren't supported." @@ -356,7 +356,7 @@ final class IORingTests: XCTestCase { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 32, flags: []) - // We use the timeout feature below. + // This test case requires timeout support try XCTSkipIf( !ring.supportedFeatures.contains(.extendedArguments), "Kernel < 5.11: timeouts in io_uring_enter aren't supported." @@ -399,8 +399,7 @@ final class IORingTests: XCTestCase { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 32, flags: []) - // Every wait below has a timeout, so that a poll that fails to fire - // causes a test failure. + // This test case requires timeout support try XCTSkipIf( !ring.supportedFeatures.contains(.extendedArguments), "Kernel < 5.11: timeouts in io_uring_enter aren't supported." @@ -514,6 +513,7 @@ final class IORingTests: XCTestCase { try? writeFD.close() } + // This test case requires timeout support try XCTSkipIf( !ring.supportedFeatures.contains(.extendedArguments), "Kernel < 5.11: timeouts in io_uring_enter aren't supported." @@ -549,6 +549,7 @@ final class IORingTests: XCTestCase { try? writeFD.close() } + // This test case requires timeout support try XCTSkipIf( !ring.supportedFeatures.contains(.extendedArguments), "Kernel < 5.11: timeouts in io_uring_enter aren't supported." From 27bc5e7e8d7dede686422b06c25bb4f49e327e50 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 7 Aug 2026 14:40:11 -0700 Subject: [PATCH 20/34] =?UTF-8?q?Enable=20=E2=80=9CMemberImportVisibility?= =?UTF-8?q?=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Package.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Package.swift b/Package.swift index e6dbeae..7d5471a 100644 --- a/Package.swift +++ b/Package.swift @@ -81,6 +81,7 @@ let swiftSettings = swiftSettingsAvailability + swiftSettingsCI + [ .define("SYSTEM_PACKAGE"), .define("ENABLE_MOCKING", .when(configuration: .debug)), .enableExperimentalFeature("Lifetimes"), + .enableUpcomingFeature("MemberImportVisibility"), ] let cSettings: [CSetting] = [ From c5c1a835d61e5c85ca12caa8c28fabf66592ceb6 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 7 Aug 2026 15:42:10 -0700 Subject: [PATCH 21/34] Explicitly import CSystem for wasi --- Sources/System/FilePath/FilePathTempPosix.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/FilePath/FilePathTempPosix.swift b/Sources/System/FilePath/FilePathTempPosix.swift index 2ac7098..9e44836 100644 --- a/Sources/System/FilePath/FilePathTempPosix.swift +++ b/Sources/System/FilePath/FilePathTempPosix.swift @@ -18,6 +18,7 @@ import Glibc import CSystem import Musl #elseif canImport(WASILibc) +import CSystem import WASILibc #elseif canImport(Android) import CSystem From 79b7490ae91cdc10e994ef434512d50e1f131979 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Fri, 7 Aug 2026 15:43:00 -0700 Subject: [PATCH 22/34] =?UTF-8?q?Hoist=20=E2=80=9Cimport=20CSystem?= =?UTF-8?q?=E2=80=9D=20above=20the=20platform-specific=20imports?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/System/FilePath/FilePathTempPosix.swift | 5 +---- Sources/System/Internals/Constants.swift | 3 +-- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/Sources/System/FilePath/FilePathTempPosix.swift b/Sources/System/FilePath/FilePathTempPosix.swift index 9e44836..942b211 100644 --- a/Sources/System/FilePath/FilePathTempPosix.swift +++ b/Sources/System/FilePath/FilePathTempPosix.swift @@ -9,19 +9,16 @@ #if !os(Windows) +import CSystem #if SYSTEM_PACKAGE_DARWIN import Darwin #elseif canImport(Glibc) -import CSystem import Glibc #elseif canImport(Musl) -import CSystem import Musl #elseif canImport(WASILibc) -import CSystem import WASILibc #elseif canImport(Android) -import CSystem import Android #else #error("Unsupported Platform") diff --git a/Sources/System/Internals/Constants.swift b/Sources/System/Internals/Constants.swift index 656e2c3..7a2ad9a 100644 --- a/Sources/System/Internals/Constants.swift +++ b/Sources/System/Internals/Constants.swift @@ -11,6 +11,7 @@ // they can be used anywhere without imports and without confusion to // unavailable local decls. +import CSystem #if SYSTEM_PACKAGE_DARWIN import Darwin #elseif os(Windows) @@ -27,8 +28,6 @@ import Android #error("Unsupported Platform") #endif -import CSystem - // MARK: errno #if SYSTEM_PACKAGE_DARWIN @_alwaysEmitIntoClient From 241fedcbbded89495e8a9bd40757e8cca8c64509 Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Tue, 22 Sep 2026 10:07:05 +0200 Subject: [PATCH 23/34] Address review feedback --- Sources/System/IORing/IORequest.swift | 14 +++--- Sources/System/IORing/PollEvents.swift | 57 +++++++++++++++++------- Sources/System/IORing/RawIORequest.swift | 6 +-- Tests/SystemTests/IORingTests.swift | 55 +++++++++++++---------- 4 files changed, 82 insertions(+), 50 deletions(-) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 8cec4e1..4de9eaa 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -34,7 +34,7 @@ internal enum IORequestCore { ) case pollAdd( file: FileDescriptor, - pollEvents: IORing.Request.PollEvents, + events: IORing.Request.PollEvents, isMultiShot: Bool = true, context: UInt64 = 0 ) @@ -248,7 +248,7 @@ extension IORing.Request { /// var ring = try IORing(queueDepth: 32) /// let pollRequest = IORing.Request.pollAdd( /// listenSocket, - /// pollEvents: .pollIn, + /// events: .readable, /// isMultiShot: true, /// context: 1 /// ) @@ -271,7 +271,7 @@ extension IORing.Request { /// /// - Parameters: /// - file: The file descriptor to monitor for I/O events. - /// - pollEvents: The I/O events to monitor on the file descriptor. + /// - events: The I/O events to monitor on the file descriptor. /// - isMultiShot: If `true`, the poll operation automatically rearms /// after each event, continuing to monitor the file descriptor. If /// `false`, the operation completes after the first matching event. @@ -289,11 +289,11 @@ extension IORing.Request { /// - ``IORing/Request/cancel(_:matching:)``: Cancelling poll operations. @inlinable public static func pollAdd( _ file: FileDescriptor, - pollEvents: PollEvents, + events: PollEvents, isMultiShot: Bool = false, context: UInt64 = 0 ) -> IORing.Request { - .init(core: .pollAdd(file: file, pollEvents: pollEvents, isMultiShot: isMultiShot, context: context)) + .init(core: .pollAdd(file: file, events: events, isMultiShot: isMultiShot, context: context)) } @inlinable public static func read( @@ -611,14 +611,14 @@ extension IORing.Request { case .cancel(let flags): request.operation = .asyncCancel request.cancel_flags = flags - case .pollAdd(let file, let pollEvents, let isMultiShot, let context): + case .pollAdd(let file, let events, let isMultiShot, let context): request.operation = .pollAdd request.fileDescriptor = file request.rawValue.user_data = context if isMultiShot { request.rawValue.len = Self.SWIFT_IORING_POLL_ADD_MULTI } - request.pollEvents = pollEvents + request.pollEvents = events } return request diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index b9b77e3..bbbc3ec 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -18,7 +18,7 @@ extension IORing.Request { /// defined in the kernel's `poll.h` header. /// /// Use `PollEvents` with - /// ``IORing/Request/pollAdd(_:pollEvents:isMultiShot:context:)`` to + /// ``IORing/Request/pollAdd(_:events:isMultiShot:context:)`` to /// register interest in specific I/O events. The poll operation completes /// when any of the specified events become active on the file descriptor. /// @@ -28,12 +28,12 @@ extension IORing.Request { /// // Monitor a socket for incoming data /// let request = IORing.Request.pollAdd( /// socketFD, - /// pollEvents: .pollIn, + /// events: .readable, /// isMultiShot: true /// ) /// ``` - public struct PollEvents: OptionSet, Hashable, Codable, CaseIterable { - public var rawValue: UInt32 + public struct PollEvents: OptionSet, Hashable, Codable { + public let rawValue: UInt32 @inlinable public init(rawValue: UInt32) { @@ -47,14 +47,16 @@ extension IORing.Request { @usableFromInline enum Event: UInt32, RawRepresentable, Hashable, CaseIterable { - case pollIn = 0x0001 - case pollOut = 0x0004 - case pollErr = 0x0008 - case pollHup = 0x0010 - case pollNval = 0x0020 + case readable = 0x0001 + case priorityData = 0x0002 + case writable = 0x0004 + case error = 0x0008 + case hangUp = 0x0010 + case invalidDescriptor = 0x0020 + case peerClosed = 0x2000 } - public static var allCases: [PollEvents] { + public static var allEvents: [PollEvents] { Event.allCases.map(PollEvents.init(_:)) } @@ -65,7 +67,16 @@ extension IORing.Request { /// a new connection is available on a listening socket. Corresponds /// to the POSIX `POLLIN` event flag. @inlinable - public static var pollIn: PollEvents { PollEvents(.pollIn) } + public static var readable: PollEvents { PollEvents(.readable) } + + /// An event indicating out-of-band data is available for reading. + /// + /// For sockets this signals urgent data; it is also used to report + /// exceptional conditions on descriptors that have no other way to + /// signal them, such as a `sysfs` attribute that has changed value. + /// Corresponds to the POSIX `POLLPRI` event flag. + @_alwaysEmitIntoClient + public static var priorityData: PollEvents { PollEvents(.priorityData) } /// An event indicating the file descriptor is ready for writing. /// @@ -73,16 +84,17 @@ extension IORing.Request { /// not block. For sockets, this indicates that send buffer space is /// available. Corresponds to the POSIX `POLLOUT` event flag. @inlinable - public static var pollOut: PollEvents { PollEvents(.pollOut) } + public static var writable: PollEvents { PollEvents(.writable) } /// An event indicating an error condition on the file descriptor. /// /// The kernel reports this event whether or not it was requested, so /// it can appear in a completion's result mask even when the poll - /// asked only for ``pollIn`` or ``pollOut``. Requesting it explicitly - /// has no effect. Corresponds to the POSIX `POLLERR` event flag. + /// asked only for ``readable`` or ``writable``. Requesting it + /// explicitly has no effect. Corresponds to the POSIX `POLLERR` event + /// flag. @_alwaysEmitIntoClient - public static var pollErr: PollEvents { PollEvents(.pollErr) } + public static var error: PollEvents { PollEvents(.error) } /// An event indicating the peer closed its end of the channel. /// @@ -95,7 +107,7 @@ extension IORing.Request { /// requesting it explicitly has no effect. Corresponds to the POSIX /// `POLLHUP` event flag. @_alwaysEmitIntoClient - public static var pollHup: PollEvents { PollEvents(.pollHup) } + public static var hangUp: PollEvents { PollEvents(.hangUp) } /// An event indicating that the object a descriptor refers to is no /// longer valid. @@ -111,7 +123,18 @@ extension IORing.Request { /// requesting it explicitly has no effect. Corresponds to the POSIX /// `POLLNVAL` event flag. @_alwaysEmitIntoClient - public static var pollNval: PollEvents { PollEvents(.pollNval) } + public static var invalidDescriptor: PollEvents { + PollEvents(.invalidDescriptor) + } + + /// An event indicating the peer closed its writing end of a stream + /// socket, or shut it down for writing. + /// + /// Unlike ``hangUp``, this event leaves the connection half-open: data + /// already in flight can still be read, and the local end can still + /// write. Corresponds to the Linux `POLLRDHUP` event flag. + @_alwaysEmitIntoClient + public static var peerClosed: PollEvents { PollEvents(.peerClosed) } } } #endif diff --git a/Sources/System/IORing/RawIORequest.swift b/Sources/System/IORing/RawIORequest.swift index ab4eb56..7bc92ce 100644 --- a/Sources/System/IORing/RawIORequest.swift +++ b/Sources/System/IORing/RawIORequest.swift @@ -89,15 +89,15 @@ extension RawIORequest { /// Big-endian kernels swap the halfwords of this field before reading it. /// Equivalent to liburing's `__io_uring_prep_poll_mask`. @_alwaysEmitIntoClient var pollEvents: IORing.Request.PollEvents { - get { .init(rawValue: _applyPollMask(rawValue.poll32_events)) } - set { rawValue.poll32_events = _applyPollMask(newValue.rawValue) } + get { .init(rawValue: Self._applyPollMask(rawValue.poll32_events)) } + set { rawValue.poll32_events = Self._applyPollMask(newValue.rawValue) } } /// Converts a poll event mask between its in-memory and `sqe` encodings. /// /// This is a halfword rotate (`swahw32` from ``), which keeps /// the byte order within each half. - @_alwaysEmitIntoClient func _applyPollMask(_ mask: UInt32) -> UInt32 { + @_alwaysEmitIntoClient static func _applyPollMask(_ mask: UInt32) -> UInt32 { #if _endian(big) return (mask &<< 16) | (mask &>> 16) #else diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index e3b45b5..8bafe4a 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -332,7 +332,7 @@ final class IORingTests: XCTestCase { // Submit a pollAdd request to monitor for POLLIN events (data available for reading) let enqueued = try ring.submit(linkedRequests: - .pollAdd(testEventFD, pollEvents: .pollIn, isMultiShot: false, context: pollInContext)) + .pollAdd(testEventFD, events: .readable, isMultiShot: false, context: pollInContext)) XCTAssert(enqueued) // Write to the eventfd to trigger the POLLIN event @@ -346,9 +346,9 @@ final class IORingTests: XCTestCase { timeout: .seconds(1) ) XCTAssertEqual(completion.context, pollInContext) - let pollIn = Int32(IORing.Request.PollEvents.pollIn.rawValue) + let readable = Int32(IORing.Request.PollEvents.readable.rawValue) XCTAssertNotEqual( - completion.result & pollIn, 0, "expected POLLIN in the result mask" + completion.result & readable, 0, "expected POLLIN in the result mask" ) } @@ -377,7 +377,7 @@ final class IORingTests: XCTestCase { // Submit a pollAdd request to monitor for POLLOUT events (ready for writing) // Pipes are typically ready for writing when empty let enqueuedOut = try ring.submit(linkedRequests: - .pollAdd(writeFD, pollEvents: .pollOut, isMultiShot: false, context: pollOutContext)) + .pollAdd(writeFD, events: .writable, isMultiShot: false, context: pollOutContext)) XCTAssert(enqueuedOut) // Consume the completion from the poll operation @@ -385,15 +385,15 @@ final class IORingTests: XCTestCase { timeout: .seconds(1) ) XCTAssertEqual(completionOut.context, pollOutContext) - let pollOut = Int32(IORing.Request.PollEvents.pollOut.rawValue) + let writable = Int32(IORing.Request.PollEvents.writable.rawValue) XCTAssertNotEqual( - completionOut.result & pollOut, 0, + completionOut.result & writable, 0, "expected POLLOUT in the result mask" ) } // Similar to the multishot example in the documentation for - // `pollAdd(_:pollEvents:isMultiShot:context:)`: arm a multishot poll, + // `pollAdd(_:events:isMultiShot:context:)`: arm a multishot poll, // then consume completions for as long as they carry `.moreCompletions`. func testPollAddMultiShotRearmsAcrossEvents() throws { try XCTSkipIf(!uringEnabled, failureMessage) @@ -429,10 +429,10 @@ final class IORingTests: XCTestCase { } let context: UInt64 = 44 - let pollIn = Int32(IORing.Request.PollEvents.pollIn.rawValue) + let readable = Int32(IORing.Request.PollEvents.readable.rawValue) let pollRequest = IORing.Request.pollAdd( - readFD, pollEvents: .pollIn, isMultiShot: true, context: context + readFD, events: .readable, isMultiShot: true, context: context ) let enqueued = try ring.submit(linkedRequests: pollRequest) XCTAssert(enqueued) @@ -446,7 +446,7 @@ final class IORingTests: XCTestCase { ) XCTAssertEqual(first.context, context) XCTAssertNotEqual( - first.result & pollIn, 0, "expected POLLIN in the result mask" + first.result & readable, 0, "expected POLLIN in the result mask" ) XCTAssert(first.flags.contains(.moreCompletions)) @@ -459,7 +459,7 @@ final class IORingTests: XCTestCase { let second = try ring.blockingConsumeCompletion(timeout: .seconds(1)) XCTAssertEqual(second.context, context) XCTAssertNotEqual( - second.result & pollIn, 0, "expected POLLIN in the result mask" + second.result & readable, 0, "expected POLLIN in the result mask" ) // Drain again @@ -508,9 +508,13 @@ final class IORingTests: XCTestCase { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 8) let (readFD, writeFD) = try FileDescriptor.pipe() + // The hangup is produced by closing the write end mid-test, so the + // cleanup below must not close it a second time: the descriptor number + // may already have been reused elsewhere in the test process. + var writeEndClosed = false defer { try? readFD.close() - try? writeFD.close() + if !writeEndClosed { try? writeFD.close() } } // This test case requires timeout support @@ -520,18 +524,19 @@ final class IORingTests: XCTestCase { ) let request = IORing.Request.pollAdd( - readFD, pollEvents: .pollIn, isMultiShot: false, context: 97 + readFD, events: .readable, isMultiShot: false, context: 97 ) let success = try ring.submit(linkedRequests: request) XCTAssertEqual(success, true) try writeFD.close() + writeEndClosed = true let dt = Duration.seconds(1) let completion = try ring.blockingConsumeCompletion(timeout: dt) - for event in IORing.Request.PollEvents.allCases { + for event in IORing.Request.PollEvents.allEvents { if completion.result & Int32(event.rawValue) != 0 { - XCTAssertEqual(event, .pollHup) + XCTAssertEqual(event, .hangUp) return } } @@ -544,8 +549,11 @@ final class IORingTests: XCTestCase { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 8) let (readFD, writeFD) = try FileDescriptor.pipe(options: .nonBlocking) + // POLLERR is produced by closing the read end mid-test; see the note in + // `testPollHangup` for why cleanup must not close it twice. + var readEndClosed = false defer { - try? readFD.close() + if !readEndClosed { try? readFD.close() } try? writeFD.close() } @@ -562,19 +570,20 @@ final class IORingTests: XCTestCase { } let request = IORing.Request.pollAdd( - writeFD, pollEvents: .pollOut, isMultiShot: false, context: 98 + writeFD, events: .writable, isMultiShot: false, context: 98 ) let success = try ring.submit(linkedRequests: request) XCTAssertEqual(success, true) try readFD.close() + readEndClosed = true let dt = Duration.seconds(1) let completion = try ring.blockingConsumeCompletion(timeout: dt) XCTAssertEqual(completion.context, 98) - let pollErr = IORing.Request.PollEvents.pollErr.rawValue - let result = completion.result & Int32(pollErr) - if result != pollErr { + let pollError = IORing.Request.PollEvents.error.rawValue + let result = completion.result & Int32(pollError) + if result != pollError { XCTFail("expected POLLERR, got 0x\(String(result, radix: 16))") } } @@ -588,7 +597,7 @@ final class IORingTests: XCTestCase { var ring = try IORing(queueDepth: 8) let request = IORing.Request.pollAdd( - FileDescriptor(rawValue: -1), pollEvents: .pollIn, + FileDescriptor(rawValue: -1), events: .readable, isMultiShot: false, context: 99 ) let success = try ring.submit(linkedRequests: request) @@ -607,8 +616,8 @@ final class IORingTests: XCTestCase { // A negative result may look like another result code. // Checking for the error must happen first. - let pollNval = Int32(IORing.Request.PollEvents.pollNval.rawValue) - XCTAssertNotEqual(completion.result & pollNval, 0) + let invalidDescriptor = Int32(IORing.Request.PollEvents.invalidDescriptor.rawValue) + XCTAssertNotEqual(completion.result & invalidDescriptor, 0) } } #endif // os(Linux) From 3b8124e350115c09228c63ca0e5bd9c13fe38048 Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Tue, 22 Sep 2026 10:18:47 +0200 Subject: [PATCH 24/34] Smaller touch ups --- Sources/System/IORing/IORequest.swift | 15 ++++++--------- Sources/System/IORing/PollEvents.swift | 16 +++++++--------- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 4de9eaa..31b0ba4 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -425,44 +425,41 @@ extension IORing.Request { // Cancel - /// Cancel every request matching the given key, rather than only the - /// first one found. + /// Cancel every request matching the given key. /// /// Corresponds to `IORING_ASYNC_CANCEL_ALL`. @_alwaysEmitIntoClient internal static var SWIFT_IORING_ASYNC_CANCEL_ALL: UInt32 { 1 << 0 } - /// Match requests on `sqe->fd`, rather than on their `user_data`. + /// Cancel any request matching the given file descriptor. /// /// Corresponds to `IORING_ASYNC_CANCEL_FD`. Cannot be combined with /// ``SWIFT_IORING_ASYNC_CANCEL_ANY``. @_alwaysEmitIntoClient internal static var SWIFT_IORING_ASYNC_CANCEL_FD: UInt32 { 1 << 1 } - /// Match any request, disregarding every other key. + /// Cancel any matching request, disregarding every other key. /// /// Corresponds to `IORING_ASYNC_CANCEL_ANY`. Cannot be combined with /// ``SWIFT_IORING_ASYNC_CANCEL_FD`` or ``SWIFT_IORING_ASYNC_CANCEL_OP``. @_alwaysEmitIntoClient internal static var SWIFT_IORING_ASYNC_CANCEL_ANY: UInt32 { 1 << 2 } - /// The descriptor to match against is a registered file, so `sqe->fd` - /// carries a slot index rather than a file descriptor. + /// Cancel any request matching a registered file. /// /// Corresponds to `IORING_ASYNC_CANCEL_FD_FIXED`, and accompanies /// ``SWIFT_IORING_ASYNC_CANCEL_FD``. @_alwaysEmitIntoClient internal static var SWIFT_IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { 1 << 3 } - /// Match requests on their `user_data`. This is the default when no other + /// Cancel requests matching the `user_data`. This is the default when no other /// key is given. /// /// Corresponds to `IORING_ASYNC_CANCEL_USERDATA`. @_alwaysEmitIntoClient internal static var SWIFT_IORING_ASYNC_CANCEL_USERDATA: UInt32 { 1 << 4 } - /// Match requests by operation. Note that the opcode to match is read - /// from `sqe->len`. + /// Cancel requests matching the operation. /// /// Corresponds to `IORING_ASYNC_CANCEL_OP`. Cannot be combined with /// ``SWIFT_IORING_ASYNC_CANCEL_ANY``. diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index bbbc3ec..b5029f3 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -56,6 +56,7 @@ extension IORing.Request { case peerClosed = 0x2000 } + @inlinable public static var allEvents: [PollEvents] { Event.allCases.map(PollEvents.init(_:)) } @@ -75,7 +76,7 @@ extension IORing.Request { /// exceptional conditions on descriptors that have no other way to /// signal them, such as a `sysfs` attribute that has changed value. /// Corresponds to the POSIX `POLLPRI` event flag. - @_alwaysEmitIntoClient + @inlinable public static var priorityData: PollEvents { PollEvents(.priorityData) } /// An event indicating the file descriptor is ready for writing. @@ -93,20 +94,17 @@ extension IORing.Request { /// asked only for ``readable`` or ``writable``. Requesting it /// explicitly has no effect. Corresponds to the POSIX `POLLERR` event /// flag. - @_alwaysEmitIntoClient + @inlinable public static var error: PollEvents { PollEvents(.error) } /// An event indicating the peer closed its end of the channel. /// /// For a pipe this means the writing end was closed; for a socket, that - /// the connection was shut down. A descriptor reporting this event will - /// never become readable again, so treating it as "not ready yet" and - /// polling again will not make progress. + /// the connection was shut down. /// /// The kernel reports this event whether or not it was requested, and /// requesting it explicitly has no effect. Corresponds to the POSIX - /// `POLLHUP` event flag. - @_alwaysEmitIntoClient + /// `POLLHUP` event flag.v public static var hangUp: PollEvents { PollEvents(.hangUp) } /// An event indicating that the object a descriptor refers to is no @@ -122,7 +120,7 @@ extension IORing.Request { /// The kernel reports this event whether or not it was requested, and /// requesting it explicitly has no effect. Corresponds to the POSIX /// `POLLNVAL` event flag. - @_alwaysEmitIntoClient + @inlinable public static var invalidDescriptor: PollEvents { PollEvents(.invalidDescriptor) } @@ -133,7 +131,7 @@ extension IORing.Request { /// Unlike ``hangUp``, this event leaves the connection half-open: data /// already in flight can still be read, and the local end can still /// write. Corresponds to the Linux `POLLRDHUP` event flag. - @_alwaysEmitIntoClient + @inlinable public static var peerClosed: PollEvents { PollEvents(.peerClosed) } } } From dc65a924d94ebfcb7726fb3ed4eef9dbab5d38ea Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Thu, 24 Sep 2026 16:50:32 -0600 Subject: [PATCH 25/34] Doc comment updates --- Sources/System/IORing/IOCompletion.swift | 4 +++- Sources/System/IORing/IORequest.swift | 30 +++++++++++++++++------- Sources/System/IORing/IORing.swift | 8 +++---- Sources/System/IORing/PollEvents.swift | 21 ++++++++++------- 4 files changed, 42 insertions(+), 21 deletions(-) diff --git a/Sources/System/IORing/IOCompletion.swift b/Sources/System/IORing/IOCompletion.swift index 8a1bc71..672606b 100644 --- a/Sources/System/IORing/IOCompletion.swift +++ b/Sources/System/IORing/IOCompletion.swift @@ -60,7 +60,9 @@ public extension IORing.Completion { /// for a read or a write, an event mask for a poll, and so on. /// /// A negative value is an `errno` code multiplied by -1. Recover the error - /// by negating it again: `Errno(rawValue: -completion.result)`. + /// by negating it again: `Errno(rawValue: -completion.result)`. Only + /// ``IORing/tryConsumeCompletion()`` returns completions with a negative + /// result; the blocking methods report the error as an ``Errno`` instead. @inlinable var result: Int32 { get { rawValue.res diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 31b0ba4..c39c14a 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -217,7 +217,7 @@ extension IORing.Request { /// Adds a poll operation to monitor a file descriptor for specific I/O /// events. /// - /// This method creates an io_uring poll operation that monitors the + /// This method creates an `io_uring` poll operation that monitors the /// specified file descriptor for I/O readiness events. The operation /// completes when any of the requested events occur on the file /// descriptor, such as data becoming available for reading or the @@ -225,17 +225,24 @@ extension IORing.Request { /// /// Poll operations are useful for implementing efficient I/O /// multiplexing, allowing you to monitor multiple file descriptors - /// concurrently within a single io_uring instance. When used with + /// concurrently within a single `io_uring` instance. When used with /// multishot mode, a single poll operation can deliver multiple /// completion events without needing to be resubmitted. /// + /// Poll requests on a ring created with + /// ``IORing/SetupFlags/pollCompletions`` fail with + /// ``Errno/invalidArgument``. + /// /// ## Multishot Behavior /// /// When `isMultiShot` is `true`, the poll operation automatically rearms /// after each completion event, continuing to monitor the file descriptor /// for subsequent events. This reduces submission overhead for long-lived - /// monitoring operations. The operation continues until explicitly - /// cancelled or the file descriptor is closed. + /// monitoring operations. The poll stays armed until it's canceled or the + /// kernel ends it; its last completion is the one without + /// ``IORing/Completion/Flags/moreCompletions``. Neither a hangup nor + /// closing the descriptor ends the poll, and the request keeps the file + /// open until the poll ends. /// /// When `isMultiShot` is `false`, the poll operation completes once after /// the first matching event occurs, requiring resubmission to continue @@ -262,13 +269,19 @@ extension IORing.Request { /// var armed = true /// while armed { /// let completion = try ring.blockingConsumeCompletion() - /// armed = completion.flags.contains(.moreCompletions) - /// if completion.context == 1 { - /// // Handle incoming connection + /// guard completion.context == 1 else { + /// // Handle completions for other requests. + /// continue /// } + /// armed = completion.flags.contains(.moreCompletions) + /// // Handle incoming connection /// } /// ``` /// + /// If the poll ends with an error, such as ``Errno/canceled``, + /// ``IORing/blockingConsumeCompletion(timeout:)`` throws that error + /// instead of returning the completion. + /// /// - Parameters: /// - file: The file descriptor to monitor for I/O events. /// - events: The I/O events to monitor on the file descriptor. @@ -286,7 +299,8 @@ extension IORing.Request { /// ## See Also /// /// - ``PollEvents``: The events that can be monitored. - /// - ``IORing/Request/cancel(_:matching:)``: Cancelling poll operations. + /// - ``IORing/Request/cancel(_:matching:)-(_,FileDescriptor)``: + /// Canceling poll operations. @inlinable public static func pollAdd( _ file: FileDescriptor, events: PollEvents, diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index bd6087d..2426048 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -51,8 +51,8 @@ extension UnsafeMutableRawBufferPointer { } /// Owns the FilePaths whose interior pointers have been written into pending -/// SQEs. The kernel copies SQE-referenced data out during io_uring_enter (due to -/// IORING_FEAT_SUBMIT_STABLE), so the paths only need to live across the prepare->submit gap +/// SQEs. The kernel copies SQE-referenced data out during `io_uring_enter` (due to +/// `IORING_FEAT_SUBMIT_STABLE`), so the paths only need to live across the prepare->submit gap /// This is a class purely to avoid making methods calling `pin` mutating, which would be an API break @usableFromInline internal final class PendingPathBuffers { @@ -885,7 +885,7 @@ public struct IORing: ~Copyable { return true } - /// Describes which io_uring features are supported by the kernel this program is running on + /// Describes which `io_uring` features are supported by the kernel this program is running on public struct Features: OptionSet, RawRepresentable, Hashable { public let rawValue: UInt32 @@ -911,7 +911,7 @@ public struct IORing: ~Copyable { @inlinable public static var bundledSendReceive: Features { .init(rawValue: UInt32(1) << 14) } //IORING_FEAT_RECVSEND_BUNDLE } - /// Describes which io_uring features are supported by the kernel this program is running on + /// Describes which `io_uring` features are supported by the kernel this program is running on public var supportedFeatures: Features { return features } diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index b5029f3..593eebb 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -5,14 +5,14 @@ Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information - */ +*/ #if compiler(>=6.2) && $Lifetimes #if os(Linux) extension IORing.Request { /// A set of I/O events that can be monitored on a file descriptor. /// - /// `PollEvents` represents the event mask used with io_uring poll + /// `PollEvents` represents the event mask used with `io_uring` poll /// operations to specify which I/O conditions to monitor on a file /// descriptor. These events correspond to the standard POSIX poll events /// defined in the kernel's `poll.h` header. @@ -104,7 +104,7 @@ extension IORing.Request { /// /// The kernel reports this event whether or not it was requested, and /// requesting it explicitly has no effect. Corresponds to the POSIX - /// `POLLHUP` event flag.v + /// `POLLHUP` event flag. public static var hangUp: PollEvents { PollEvents(.hangUp) } /// An event indicating that the object a descriptor refers to is no @@ -114,8 +114,8 @@ extension IORing.Request { /// refers to has since become invalid. For example, the disconnection /// of a sound device could cause this event. /// - /// Note that a descriptor which simply does not resolve would - /// return the EBADF error code (Errno.badFileDescriptor). + /// A descriptor that doesn't resolve at all would make the request + /// fail with ``Errno/badFileDescriptor`` instead. /// /// The kernel reports this event whether or not it was requested, and /// requesting it explicitly has no effect. Corresponds to the POSIX @@ -128,9 +128,14 @@ extension IORing.Request { /// An event indicating the peer closed its writing end of a stream /// socket, or shut it down for writing. /// - /// Unlike ``hangUp``, this event leaves the connection half-open: data - /// already in flight can still be read, and the local end can still - /// write. Corresponds to the Linux `POLLRDHUP` event flag. + /// Unlike ``hangUp``, this event can arrive while the connection is + /// still half-open: data already in flight can still be read, and the + /// local end can still write. Once both directions are shut down, + /// ``hangUp`` is reported alongside this event. + /// + /// Unlike `poll(2)`, `io_uring` reports this event whether or not it + /// was requested, and requesting it explicitly has no effect. + /// Corresponds to the Linux `POLLRDHUP` event flag. @inlinable public static var peerClosed: PollEvents { PollEvents(.peerClosed) } } From 59b5659a1e679961ed75418aa3a41e5a6e1f7018 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Thu, 24 Sep 2026 16:52:48 -0600 Subject: [PATCH 26/34] Make internal isMultiShot default match public API --- Sources/System/IORing/IORequest.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index c39c14a..a5c4c40 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -35,7 +35,7 @@ internal enum IORequestCore { case pollAdd( file: FileDescriptor, events: IORing.Request.PollEvents, - isMultiShot: Bool = true, + isMultiShot: Bool = false, context: UInt64 = 0 ) case read( From 1c80f27aefeef95e0fb21d80682b809fd13ae772 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Thu, 24 Sep 2026 19:22:07 -0600 Subject: [PATCH 27/34] Remove PollEvents.allEvents and use internal Event enum for testing --- Sources/System/IORing/PollEvents.swift | 5 ----- Tests/SystemTests/IORingTests.swift | 6 +++--- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index 593eebb..e377c57 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -56,11 +56,6 @@ extension IORing.Request { case peerClosed = 0x2000 } - @inlinable - public static var allEvents: [PollEvents] { - Event.allCases.map(PollEvents.init(_:)) - } - /// An event indicating data is available for reading. /// /// This event becomes active when data arrives on the file descriptor diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 8bafe4a..d843015 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -10,9 +10,9 @@ import Musl // for errno #endif #if SYSTEM_PACKAGE -import SystemPackage +@testable import SystemPackage #else -import System +@testable import System #endif // Cache `isUringEnabled()`. The probe is complex and the answer doesn't change @@ -534,7 +534,7 @@ final class IORingTests: XCTestCase { let dt = Duration.seconds(1) let completion = try ring.blockingConsumeCompletion(timeout: dt) - for event in IORing.Request.PollEvents.allEvents { + for event in IORing.Request.PollEvents.Event.allCases { if completion.result & Int32(event.rawValue) != 0 { XCTAssertEqual(event, .hangUp) return From 4699556133afe46dc747afd3c9f1e712820fbaae Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Thu, 24 Sep 2026 19:33:50 -0600 Subject: [PATCH 28/34] Add unavailable/renamed hints for C names --- Sources/System/IORing/PollEvents.swift | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index e377c57..b004bd1 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -65,6 +65,10 @@ extension IORing.Request { @inlinable public static var readable: PollEvents { PollEvents(.readable) } + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "readable") + public static var POLLIN: PollEvents { readable } + /// An event indicating out-of-band data is available for reading. /// /// For sockets this signals urgent data; it is also used to report @@ -74,6 +78,10 @@ extension IORing.Request { @inlinable public static var priorityData: PollEvents { PollEvents(.priorityData) } + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "priorityData") + public static var POLLPRI: PollEvents { priorityData } + /// An event indicating the file descriptor is ready for writing. /// /// This event becomes active when writing to the file descriptor will @@ -82,6 +90,10 @@ extension IORing.Request { @inlinable public static var writable: PollEvents { PollEvents(.writable) } + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "writable") + public static var POLLOUT: PollEvents { writable } + /// An event indicating an error condition on the file descriptor. /// /// The kernel reports this event whether or not it was requested, so @@ -92,6 +104,10 @@ extension IORing.Request { @inlinable public static var error: PollEvents { PollEvents(.error) } + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "error") + public static var POLLERR: PollEvents { error } + /// An event indicating the peer closed its end of the channel. /// /// For a pipe this means the writing end was closed; for a socket, that @@ -102,6 +118,10 @@ extension IORing.Request { /// `POLLHUP` event flag. public static var hangUp: PollEvents { PollEvents(.hangUp) } + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "hangUp") + public static var POLLHUP: PollEvents { hangUp } + /// An event indicating that the object a descriptor refers to is no /// longer valid. /// @@ -120,6 +140,10 @@ extension IORing.Request { PollEvents(.invalidDescriptor) } + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "invalidDescriptor") + public static var POLLNVAL: PollEvents { invalidDescriptor } + /// An event indicating the peer closed its writing end of a stream /// socket, or shut it down for writing. /// @@ -133,6 +157,10 @@ extension IORing.Request { /// Corresponds to the Linux `POLLRDHUP` event flag. @inlinable public static var peerClosed: PollEvents { PollEvents(.peerClosed) } + + @_alwaysEmitIntoClient + @available(*, unavailable, renamed: "peerClosed") + public static var POLLRDHUP: PollEvents { peerClosed } } } #endif From 6843adad5a1ee17b29e194b200aed1014f49d895 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Thu, 24 Sep 2026 16:51:26 -0600 Subject: [PATCH 29/34] Add missing `@inlinable` --- Sources/System/IORing/PollEvents.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/IORing/PollEvents.swift b/Sources/System/IORing/PollEvents.swift index b004bd1..6989a23 100644 --- a/Sources/System/IORing/PollEvents.swift +++ b/Sources/System/IORing/PollEvents.swift @@ -116,6 +116,7 @@ extension IORing.Request { /// The kernel reports this event whether or not it was requested, and /// requesting it explicitly has no effect. Corresponds to the POSIX /// `POLLHUP` event flag. + @inlinable public static var hangUp: PollEvents { PollEvents(.hangUp) } @_alwaysEmitIntoClient From 65f43f5d57bc2d932d39d53f9abcff95bdd91c67 Mon Sep 17 00:00:00 2001 From: "apple-ospo[bot]" <326325757+apple-ospo[bot]@users.noreply.github.com> Date: Fri, 25 Sep 2026 17:42:48 +0000 Subject: [PATCH 30/34] Replace repo-level CODE_OF_CONDUCT file with the inherited org-wide Code of Conduct in .github repo. --- CODE_OF_CONDUCT.md | 38 -------------------------------------- README.md | 2 +- 2 files changed, 1 insertion(+), 39 deletions(-) delete mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 95c80e7..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,38 +0,0 @@ -# Code of Conduct - -To be a truly great community, Swift.org needs to welcome developers from all walks of life, with different backgrounds, and with a wide range of experience. A diverse and friendly community will have more great ideas, more unique perspectives, and produce more great code. We will work diligently to make the Swift community welcoming to everyone. - -To give clarity of what is expected of our members, this code of conduct is based on [contributor-covenant.org](http://contributor-covenant.org). This document is used across many open source communities, and we think it articulates our values well. - -### Contributor Code of Conduct v1.4 - -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language (e.g., prefer non-gendered words like “folks” to “guys”, non-ableist words like “soundness check” to “sanity check”, etc.) -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others’ private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -This Code of Conduct applies within all project spaces managed by Swift.org, including (but not limited to) source code repositories, bug trackers, web sites, documentation, and online forums. It also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a member of the [Swift Core Team](https://swift.org/community/#community-structure) or by flagging the behavior for moderation (e.g., in the Forums), whether you are the target of that behavior or not. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. The site of the disputed behavior is usually not an acceptable place to discuss moderation decisions, and moderators may move or remove any such discussion. - -Project maintainers are held to a higher standard, and project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership. -If you disagree with a moderation action, you can appeal to the Core Team (or individual Core Team members) privately. - -This policy is adapted from the Contributor Code of Conduct [version 1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct/). diff --git a/README.md b/README.md index ea2cba0..bc8db5a 100644 --- a/README.md +++ b/README.md @@ -126,4 +126,4 @@ For example, anything landing on `release/1.6.0` will eventually appear on `rele Like all Swift.org projects, we would like the Swift System project to foster a diverse and friendly community. We expect contributors to adhere to the [Swift.org Code of Conduct](https://swift.org/code-of-conduct/). A copy of this document is [available in this repository][coc]. -[coc]: CODE_OF_CONDUCT.md +[coc]: https://github.com/apple/.github/blob/main/CODE_OF_CONDUCT.md From 74a7b6f61839388b8e1f577210a92a89acb1be4b Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Wed, 30 Sep 2026 15:59:05 -0600 Subject: [PATCH 31/34] Fix missing `done` in IORing.blockingConsumeCompletions --- Sources/System/IORing/IORing.swift | 2 +- Tests/SystemTests/IORingTests.swift | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 2426048..c55f28a 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -584,8 +584,8 @@ public struct IORing: ~Copyable { break } } - try consumer(nil, nil, true) } + try consumer(nil, nil, true) } @inlinable diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index d843015..799e591 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -286,6 +286,17 @@ final class IORingTests: XCTestCase { XCTAssertGreaterThanOrEqual(elapsed, .milliseconds(50)) } + func testBlockingConsumeCompletionsSendsDone() throws { + try XCTSkipIf(!uringEnabled, failureMessage) + var ring = try IORing(queueDepth: 4) + XCTAssertTrue(try ring.submit(linkedRequests: .nop())) + var dones: [Bool] = [] + ring.blockingConsumeCompletions { (completion: consuming IORing.Completion?, error, done) in + dones.append(done) + } + XCTAssertEqual(dones, [false, true]) + } + func testRegisterEventFDTwiceThrows() throws { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 4) From cbf57d457533d4f55b6ca6a7530643e2df9f4b0d Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Mon, 5 Oct 2026 20:58:32 +0200 Subject: [PATCH 32/34] [IO_URING] Keep the completion of failed IORing operations When an operation failed, the blocking consume methods dropped its completion and only reported the `Errno`. The caller could not tell which request failed, since the `context` was lost. This breaks any user that matches completions to requests. This PR makes `blockingConsumeCompletions` pass the completion of a failed operation together with its error. Errors of the ring itself, such as `.timeout`, are still passed without a completion. Additionally, `blockingConsumeCompletion(timeout:)` now returns the completion of a failed operation instead of throwing. It only throws errors of the ring itself. I also added `Completion.error`, which is `nil` on success and the decoded `Errno` otherwise to make it easy to get to the error of a completion. Fixes #364 Fixes #395 --- Sources/System/IORing/IOCompletion.swift | 12 +++++-- Sources/System/IORing/IORequest.swift | 6 ++-- Sources/System/IORing/IORing.swift | 44 ++++++++++++++---------- Tests/SystemTests/IORingTests.swift | 44 ++++++++++++++++++++++++ 4 files changed, 82 insertions(+), 24 deletions(-) diff --git a/Sources/System/IORing/IOCompletion.swift b/Sources/System/IORing/IOCompletion.swift index 672606b..9c7d55d 100644 --- a/Sources/System/IORing/IOCompletion.swift +++ b/Sources/System/IORing/IOCompletion.swift @@ -60,15 +60,21 @@ public extension IORing.Completion { /// for a read or a write, an event mask for a poll, and so on. /// /// A negative value is an `errno` code multiplied by -1. Recover the error - /// by negating it again: `Errno(rawValue: -completion.result)`. Only - /// ``IORing/tryConsumeCompletion()`` returns completions with a negative - /// result; the blocking methods report the error as an ``Errno`` instead. + /// by negating it again: `Errno(rawValue: -completion.result)`, or use + /// ``error``. @inlinable var result: Int32 { get { rawValue.res } } + /// The error of the completed operation, or `nil` if the operation succeeded. + @inlinable var error: Errno? { + get { + rawValue.res < 0 ? Errno(rawValue: -rawValue.res) : nil + } + } + @inlinable var flags: IORing.Completion.Flags { get { Flags(rawValue: rawValue.flags & 0x0000FFFF) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index a5c4c40..cc4a7f0 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -278,9 +278,9 @@ extension IORing.Request { /// } /// ``` /// - /// If the poll ends with an error, such as ``Errno/canceled``, - /// ``IORing/blockingConsumeCompletion(timeout:)`` throws that error - /// instead of returning the completion. + /// If the poll ends with an error, such as ``Errno/canceled``, its last + /// completion carries that error in ``IORing/Completion/error`` and + /// doesn't contain `.moreCompletions`. /// /// - Parameters: /// - file: The file descriptor to monitor for I/O events. diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index c55f28a..38cef62 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -519,11 +519,10 @@ public struct IORing: ~Copyable { var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { count += 1 - if completion.result < 0 { - try consumer(nil, Errno(rawValue: -completion.result), false) - } else { - try consumer(completion, nil, false) - } + // We still return the completion for a failed operation so that the + // caller can tell which request failed through its `context`. + let error = completion.error + try consumer(completion, error, false) if count == maximumCount { try consumer(nil, nil, true) return @@ -575,11 +574,8 @@ public struct IORing: ~Copyable { var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { count += 1 - if completion.result < 0 { - try consumer(nil, Errno(rawValue: -completion.result), false) - } else { - try consumer(completion, nil, false) - } + let error = completion.error + try consumer(completion, error, false) if count == maximumCount { break } @@ -595,17 +591,23 @@ public struct IORing: ~Copyable { var result: Completion? = nil try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { (completion: consuming Completion?, error, done) throws(Errno) in - if let error { - throw error - } if let completion { result = consume completion + } else if let error { + throw error } } return result.take()! } /// Synchronously waits for an operation to complete for up to `timeout` (or forever if not specified) + /// + /// The completion is returned even if its operation failed. Check + /// ``IORing/Completion/error`` to find out whether it did, and + /// ``IORing/Completion/context`` to find out which request it belongs to. + /// + /// - Throws: An error of the ring itself, such as ``Errno/timeout`` when + /// no operation completed within `timeout`. @inlinable public func blockingConsumeCompletion( timeout: Duration? = nil @@ -629,7 +631,17 @@ public struct IORing: ~Copyable { } } - /// Synchronously waits for `minimumCount` or more operations to complete for up to `timeout` (or forever if not specified). For each completed operation found, `consumer` is called to handle processing it + /// Synchronously waits for `minimumCount` or more operations to complete for up to `timeout` + /// (or forever if not specified). For each completed operation found, `consumer` is called to handle + /// processing it. + /// + /// `consumer` receives a completion, an error, and whether consuming is done: + /// - For each completed operation, it receives the completion. If the + /// operation failed, it receives the operation's error alongside the + /// completion. + /// - If the ring itself fails, such as with ``Errno/timeout``, it receives + /// the error without a completion. + /// - Once consuming is done, it is called a final time with `done` set to `true`. @inlinable public func blockingConsumeCompletions( minimumCount: UInt32 = 1, @@ -658,10 +670,6 @@ public struct IORing: ~Copyable { } } - // public func peekNextCompletion() -> IOCompletion { - - // } - /// Takes a completed operation from the ring and returns it, if one is ready. Otherwise, returns nil. @inlinable public func tryConsumeCompletion() -> Completion? { diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 799e591..24fba4f 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -297,6 +297,50 @@ final class IORingTests: XCTestCase { XCTAssertEqual(dones, [false, true]) } + func testBlockingConsumeCompletionsKeepsContextOfFailedCompletion() throws { + try XCTSkipIf(!uringEnabled, failureMessage) + var ring = try IORing(queueDepth: 4) + XCTAssertTrue(try ring.submit( + linkedRequests: .close(FileDescriptor(rawValue: -1), context: 42) + )) + + var received: [(context: UInt64?, error: Errno?, done: Bool)] = [] + ring.blockingConsumeCompletions { (completion: consuming IORing.Completion?, error, done) in + received.append((completion?.context, error, done)) + } + + XCTAssertEqual(received.count, 2) + XCTAssertEqual(received.first?.context, 42) + XCTAssertEqual(received.first?.error, .badFileDescriptor) + XCTAssertEqual(received.first?.done, false) + XCTAssertEqual(received.last?.context, nil) + XCTAssertEqual(received.last?.error, nil) + XCTAssertEqual(received.last?.done, true) + } + + func testBlockingConsumeCompletionReturnsFailedCompletion() throws { + try XCTSkipIf(!uringEnabled, failureMessage) + var ring = try IORing(queueDepth: 4) + XCTAssertTrue(try ring.submit( + linkedRequests: .close(FileDescriptor(rawValue: -1), context: 43) + )) + + let completion = try ring.blockingConsumeCompletion() + XCTAssertEqual(completion.context, 43) + XCTAssertEqual(completion.error, .badFileDescriptor) + XCTAssertEqual(completion.result, -Errno.badFileDescriptor.rawValue) + } + + func testCompletionOfSuccessfulOperationHasNoError() throws { + try XCTSkipIf(!uringEnabled, failureMessage) + var ring = try IORing(queueDepth: 4) + XCTAssertTrue(try ring.submit(linkedRequests: .nop())) + + let completion = try ring.blockingConsumeCompletion() + XCTAssertEqual(completion.result, 0) + XCTAssertNil(completion.error) + } + func testRegisterEventFDTwiceThrows() throws { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 4) From 95ed6aa2a4bd3d765dde19498037a21e71dbc426 Mon Sep 17 00:00:00 2001 From: Franz Busch Date: Tue, 6 Oct 2026 10:21:52 +0200 Subject: [PATCH 33/34] Address review comments --- Sources/System/IORing/IORequest.swift | 4 ++++ Sources/System/IORing/IORing.swift | 8 ++++++++ Tests/SystemTests/IORingTests.swift | 20 ++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index cc4a7f0..544c1ef 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -274,6 +274,10 @@ extension IORing.Request { /// continue /// } /// armed = completion.flags.contains(.moreCompletions) + /// if let error = completion.error { + /// // The poll ended with an error, such as `.canceled`. + /// throw error + /// } /// // Handle incoming connection /// } /// ``` diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 38cef62..473fe43 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -818,6 +818,14 @@ public struct IORing: ~Copyable { } /// Sends all prepared requests to the kernel for processing, and then dequeues at least `minimumCount` completions, waiting up to `timeout` for them to become available. `consumer` is called to process each completed IO operation as it becomes available. + /// + /// `consumer` receives a completion, an error, and whether consuming is done: + /// - For each completed operation, it receives the completion. If the + /// operation failed, it receives the operation's error alongside the + /// completion. + /// - If submitting the requests or waiting for completions fails, such as + /// with ``Errno/timeout``, it receives the error without a completion. + /// - Once consuming is done, it is called a final time with `done` set to `true`. @inlinable public func submitPreparedRequestsAndConsumeCompletions( minimumCount: UInt32 = 1, diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 24fba4f..dffe76b 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -331,6 +331,26 @@ final class IORingTests: XCTestCase { XCTAssertEqual(completion.result, -Errno.badFileDescriptor.rawValue) } + func testSubmitAndConsumeCompletionsKeepsContextOfFailedCompletion() throws { + try XCTSkipIf(!uringEnabled, failureMessage) + var ring = try IORing(queueDepth: 4) + XCTAssertTrue(ring.prepare(request: .close(FileDescriptor(rawValue: -1), context: 44))) + + var received: [(context: UInt64?, error: Errno?, done: Bool)] = [] + ring.submitPreparedRequestsAndConsumeCompletions { + (completion: consuming IORing.Completion?, error, done) in + received.append((completion?.context, error, done)) + } + + XCTAssertEqual(received.count, 2) + XCTAssertEqual(received.first?.context, 44) + XCTAssertEqual(received.first?.error, .badFileDescriptor) + XCTAssertEqual(received.first?.done, false) + XCTAssertEqual(received.last?.context, nil) + XCTAssertEqual(received.last?.error, nil) + XCTAssertEqual(received.last?.done, true) + } + func testCompletionOfSuccessfulOperationHasNoError() throws { try XCTSkipIf(!uringEnabled, failureMessage) var ring = try IORing(queueDepth: 4) From d0f7d75929dc606153589e9987788136f802ad51 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Fri, 16 Oct 2026 17:12:07 -0600 Subject: [PATCH 34/34] Add automerger workflow from release/1.8.x to main --- .github/workflows/automerge_to_main.yml | 20 ++++++++++++++++++++ .github/workflows/pull_request.yml | 2 +- README.md | 2 +- 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/automerge_to_main.yml diff --git a/.github/workflows/automerge_to_main.yml b/.github/workflows/automerge_to_main.yml new file mode 100644 index 0000000..ec295ff --- /dev/null +++ b/.github/workflows/automerge_to_main.yml @@ -0,0 +1,20 @@ +name: Create PR to merge release branch into the main branch +# Changes should land on the earliest release branch they will need to ship on and then be automatically forwarded to main +permissions: + contents: read +on: + schedule: + - cron: '0 9 * * *' + workflow_dispatch: +jobs: + create_merge_pr: + name: Create PR to merge release branch into main branch + uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@0.0.15 + with: + base_branch: main + head_branch: release/1.8.x + pr_message: This PR was automatically opened by a GitHub action. Review the changes included in this PR and determine if they should be included on main. If yes, merge the PR. Otherwise revert changes that should not be included on this branch. + permissions: + contents: write + pull-requests: write + if: (github.event_name == 'schedule' && github.repository == 'apple/swift-system') || (github.event_name != 'schedule') # Ensure that we don't run this on a schedule in a fork diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index ca6fbea..88c5e25 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -5,7 +5,7 @@ permissions: on: pull_request: - types: [opened, reopened, synchronize] + types: [opened, reopened, synchronize, ready_for_review] jobs: tests: diff --git a/README.md b/README.md index bc8db5a..c4c2ad3 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ Changes must land on the branch corresponding to the earliest release that they `release/1.7.0` → `release/1.8.x` → `main` -For example, anything landing on `release/1.6.0` will eventually appear on `release/1.7.0`, then `release/1.8.x` and finally `main` as well. There is no need to file standalone PRs for each release line. (Change propagation currently requires manual work -- it is performed by project maintainers.) +For example, anything landing on `release/1.7.0` will eventually appear on `release/1.8.x` and finally `main` as well. There is no need to file standalone PRs for each release line. (Merges into `main` are performed by the [automerger](.github/workflows/automerge_to_main.yml); propagation between release branches is performed by project maintainers.) ### Code of Conduct