From 15794f5cad319a58a8ed768af3947e2228ced0ce Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Tue, 18 Jul 2023 21:04:39 -0700 Subject: [PATCH 001/102] ioring pitch: first steps --- Package.resolved | 16 ++ Package.swift | 9 +- Sources/CSystem/include/CSystemLinux.h | 1 + Sources/CSystem/include/io_uring.h | 50 ++++ Sources/System/IOCompletion.swift | 50 ++++ Sources/System/IORequest.swift | 140 ++++++++++ Sources/System/IORing.swift | 350 +++++++++++++++++++++++++ Sources/System/IORingBuffer.swift | 0 Sources/System/IORingFileSlot.swift | 8 + Sources/System/Lock.swift | 37 +++ Sources/System/ManagedIORing.swift | 33 +++ 11 files changed, 692 insertions(+), 2 deletions(-) create mode 100644 Package.resolved create mode 100644 Sources/CSystem/include/io_uring.h create mode 100644 Sources/System/IOCompletion.swift create mode 100644 Sources/System/IORequest.swift create mode 100644 Sources/System/IORing.swift create mode 100644 Sources/System/IORingBuffer.swift create mode 100644 Sources/System/IORingFileSlot.swift create mode 100644 Sources/System/Lock.swift create mode 100644 Sources/System/ManagedIORing.swift diff --git a/Package.resolved b/Package.resolved new file mode 100644 index 0000000..b10a983 --- /dev/null +++ b/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "swift-atomics", + "repositoryURL": "https://github.com/apple/swift-atomics", + "state": { + "branch": null, + "revision": "6c89474e62719ddcc1e9614989fff2f68208fe10", + "version": "1.1.0" + } + } + ] + }, + "version": 1 +} diff --git a/Package.swift b/Package.swift index b081a87..60f1a56 100644 --- a/Package.swift +++ b/Package.swift @@ -17,14 +17,19 @@ let package = Package( products: [ .library(name: "SystemPackage", targets: ["SystemPackage"]), ], - dependencies: [], + dependencies: [ + .package(url: "https://github.com/apple/swift-atomics", from: "1.1.0") + ], targets: [ .target( name: "CSystem", dependencies: []), .target( name: "SystemPackage", - dependencies: ["CSystem"], + dependencies: [ + "CSystem", + .product(name: "Atomics", package: "swift-atomics") + ], path: "Sources/System", cSettings: [ .define("_CRT_SECURE_NO_WARNINGS") diff --git a/Sources/CSystem/include/CSystemLinux.h b/Sources/CSystem/include/CSystemLinux.h index b172d65..6489c4f 100644 --- a/Sources/CSystem/include/CSystemLinux.h +++ b/Sources/CSystem/include/CSystemLinux.h @@ -21,5 +21,6 @@ #include #include #include +#include "io_uring.h" #endif diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h new file mode 100644 index 0000000..9e3d9fb --- /dev/null +++ b/Sources/CSystem/include/io_uring.h @@ -0,0 +1,50 @@ +#include +#include +#include + +#include +#include + +#ifdef __alpha__ +/* + * alpha is the only exception, all other architectures + * have common numbers for new system calls. + */ +# ifndef __NR_io_uring_setup +# define __NR_io_uring_setup 535 +# endif +# ifndef __NR_io_uring_enter +# define __NR_io_uring_enter 536 +# endif +# ifndef __NR_io_uring_register +# define __NR_io_uring_register 537 +# endif +#else /* !__alpha__ */ +# ifndef __NR_io_uring_setup +# define __NR_io_uring_setup 425 +# endif +# ifndef __NR_io_uring_enter +# define __NR_io_uring_enter 426 +# endif +# ifndef __NR_io_uring_register +# define __NR_io_uring_register 427 +# endif +#endif + +int io_uring_register(int fd, unsigned int opcode, void *arg, + unsigned int nr_args) +{ + return syscall(__NR_io_uring_register, fd, opcode, arg, nr_args); +} + +int io_uring_setup(unsigned int entries, struct io_uring_params *p) +{ + return syscall(__NR_io_uring_setup, entries, p); +} + +int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete, + unsigned int flags, sigset_t *sig) +{ + return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, + flags, sig, _NSIG / 8); +} diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift new file mode 100644 index 0000000..5e22632 --- /dev/null +++ b/Sources/System/IOCompletion.swift @@ -0,0 +1,50 @@ +@_implementationOnly import CSystem + +public struct IOCompletion { + let rawValue: io_uring_cqe +} + +extension IOCompletion { + public struct Flags: OptionSet, Hashable, Codable { + public let rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + public static let allocatedBuffer = Flags(rawValue: 1 << 0) + public static let moreCompletions = Flags(rawValue: 1 << 1) + public static let socketNotEmpty = Flags(rawValue: 1 << 2) + public static let isNotificationEvent = Flags(rawValue: 1 << 3) + } +} + +extension IOCompletion { + public var userData: UInt64 { + get { + return rawValue.user_data + } + } + + public var result: Int32 { + get { + return rawValue.res + } + } + + public var flags: IOCompletion.Flags { + get { + return Flags(rawValue: rawValue.flags & 0x0000FFFF) + } + } + + public var bufferIndex: UInt16? { + get { + if self.flags.contains(.allocatedBuffer) { + return UInt16(rawValue.flags >> 16) + } else { + return nil + } + } + } +} diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift new file mode 100644 index 0000000..efa03f3 --- /dev/null +++ b/Sources/System/IORequest.swift @@ -0,0 +1,140 @@ +@_implementationOnly import CSystem + +public struct IORequest { + internal var rawValue: io_uring_sqe + + public init() { + self.rawValue = io_uring_sqe() + } +} + +extension IORequest { + public enum Operation: UInt8 { + case nop = 0 + case readv = 1 + case writev = 2 + case fsync = 3 + case readFixed = 4 + case writeFixed = 5 + case pollAdd = 6 + case pollRemove = 7 + case syncFileRange = 8 + case sendMessage = 9 + case receiveMessage = 10 + // ... + case openAt = 18 + case read = 22 + case write = 23 + case openAt2 = 28 + + } + + public struct Flags: OptionSet, Hashable, Codable { + public let rawValue: UInt8 + + public init(rawValue: UInt8) { + self.rawValue = rawValue + } + + public static let fixedFile = Flags(rawValue: 1 << 0) + public static let drainQueue = Flags(rawValue: 1 << 1) + public static let linkRequest = Flags(rawValue: 1 << 2) + public static let hardlinkRequest = Flags(rawValue: 1 << 3) + public static let asynchronous = Flags(rawValue: 1 << 4) + public static let selectBuffer = Flags(rawValue: 1 << 5) + public static let skipSuccess = Flags(rawValue: 1 << 6) + } + + public var operation: Operation { + get { Operation(rawValue: rawValue.opcode)! } + set { rawValue.opcode = newValue.rawValue } + } + + public var flags: Flags { + get { Flags(rawValue: rawValue.flags) } + set { rawValue.flags = newValue.rawValue } + } + + public var fileDescriptor: FileDescriptor { + get { FileDescriptor(rawValue: rawValue.fd) } + set { rawValue.fd = newValue.rawValue } + } + + public var offset: UInt64? { + get { + if (rawValue.off == UInt64.max) { + return nil + } else { + return rawValue.off + } + } + set { + if let val = newValue { + rawValue.off = val + } else { + rawValue.off = UInt64.max + } + } + } + + public var buffer: UnsafeMutableRawBufferPointer { + get { + let ptr = UnsafeMutableRawPointer(bitPattern: UInt(exactly: rawValue.addr)!) + return UnsafeMutableRawBufferPointer(start: ptr, count: Int(rawValue.len)) + } + + set { + // TODO: cleanup? + rawValue.addr = UInt64(Int(bitPattern: newValue.baseAddress!)) + rawValue.len = UInt32(exactly: newValue.count)! + } + } +} + +extension IORequest { + static func nop() -> IORequest { + var req = IORequest() + req.operation = .nop + return req + } + + static func read( + from fileDescriptor: FileDescriptor, + into buffer: UnsafeMutableRawBufferPointer, + at offset: UInt64? = nil + ) -> IORequest { + var req = IORequest.readWrite( + op: Operation.read, + fd: fileDescriptor, + buffer: buffer, + offset: offset + ) + fatalError() + } + + static func read( + fixedFile: Int // TODO: AsyncFileDescriptor + ) -> IORequest { + fatalError() + } + + static func write( + + ) -> IORequest { + fatalError() + } + + internal static func readWrite( + op: Operation, + fd: FileDescriptor, + buffer: UnsafeMutableRawBufferPointer, + offset: UInt64? = nil + ) -> IORequest { + var req = IORequest() + req.operation = op + req.fileDescriptor = fd + req.offset = offset + req.buffer = buffer + return req + } +} \ No newline at end of file diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift new file mode 100644 index 0000000..6945d8c --- /dev/null +++ b/Sources/System/IORing.swift @@ -0,0 +1,350 @@ +@_implementationOnly import CSystem +import Glibc +import Atomics + +// XXX: this *really* shouldn't be here. oh well. +extension UnsafeMutableRawPointer { + func advanced(by offset: UInt32) -> UnsafeMutableRawPointer { + return advanced(by: Int(offset)) + } +} + +// all pointers in this struct reference kernel-visible memory +struct SQRing { + let kernelHead: UnsafeAtomic + let kernelTail: UnsafeAtomic + var userTail: UInt32 + + // from liburing: the kernel should never change these + // might change in the future with resizable rings? + let ringMask: UInt32 + // let ringEntries: UInt32 - absorbed into array.count + + // ring flags bitfield + // currently used by the kernel only in SQPOLL mode to indicate + // when the polling thread needs to be woken up + let flags: UnsafeAtomic + + // ring array + // maps indexes between the actual ring and the submissionQueueEntries list, + // allowing the latter to be used as a kind of freelist with enough work? + // currently, just 1:1 mapping (0.. +} + +struct CQRing { + let kernelHead: UnsafeAtomic + let kernelTail: UnsafeAtomic + + // TODO: determine if this is actually used + var userHead: UInt32 + + let ringMask: UInt32 + + let cqes: UnsafeBufferPointer +} + +// XXX: This should be a non-copyable type (?) +// demo only runs on Swift 5.8.1 +public final class IORing: Sendable { + let ringFlags: UInt32 + let ringDescriptor: Int32 + + var submissionRing: SQRing + var submissionMutex: Mutex + // FEAT: set this eventually + let submissionPolling: Bool = false + + var completionRing: CQRing + var completionMutex: Mutex + + let submissionQueueEntries: UnsafeMutableBufferPointer + + var registeredFiles: UnsafeMutableBufferPointer? + + // kept around for unmap / cleanup + let ringSize: Int + let ringPtr: UnsafeMutableRawPointer + + public init(queueDepth: UInt32) throws { + var params = io_uring_params() + + ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { + return io_uring_setup(queueDepth, $0); + } + + if (params.features & IORING_FEAT_SINGLE_MMAP == 0 + || params.features & IORING_FEAT_NODROP == 0) { + close(ringDescriptor) + // TODO: error handling + fatalError("kernel not new enough") + } + + if (ringDescriptor < 0) { + // TODO: error handling + } + + let submitRingSize = params.sq_off.array + + params.sq_entries * UInt32(MemoryLayout.size) + + let completionRingSize = params.cq_off.cqes + + params.cq_entries * UInt32(MemoryLayout.size) + + ringSize = Int(max(submitRingSize, completionRingSize)) + + ringPtr = mmap( + /* addr: */ nil, + /* len: */ ringSize, + /* prot: */ PROT_READ | PROT_WRITE, + /* flags: */ MAP_SHARED | MAP_POPULATE, + /* fd: */ ringDescriptor, + /* offset: */ __off_t(IORING_OFF_SQ_RING) + ); + + if (ringPtr == MAP_FAILED) { + perror("mmap"); + // TODO: error handling + fatalError() + } + + let kernelHead = UnsafeAtomic(at: + ringPtr.advanced(by: params.sq_off.head) + .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + ) + + submissionRing = SQRing( + kernelHead: UnsafeAtomic( + at: ringPtr.advanced(by: params.sq_off.head) + .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + ), + kernelTail: UnsafeAtomic( + at: ringPtr.advanced(by: params.sq_off.tail) + .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + ), + userTail: 0, // no requests yet + ringMask: ringPtr.advanced(by: params.sq_off.ring_mask) + .assumingMemoryBound(to: UInt32.self).pointee, + flags: UnsafeAtomic( + at: ringPtr.advanced(by: params.sq_off.flags) + .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + ), + array: UnsafeMutableBufferPointer( + start: ringPtr.advanced(by: params.sq_off.array) + .assumingMemoryBound(to: UInt32.self), + count: Int(ringPtr.advanced(by: params.sq_off.ring_entries) + .assumingMemoryBound(to: UInt32.self).pointee) + ) + ) + + // fill submission ring array with 1:1 map to underlying SQEs + for i in 0...size, + /* prot: */ PROT_READ | PROT_WRITE, + /* flags: */ MAP_SHARED | MAP_POPULATE, + /* fd: */ ringDescriptor, + /* offset: */ __off_t(IORING_OFF_SQES) + ); + + if (sqes == MAP_FAILED) { + perror("mmap"); + // TODO: error handling + fatalError() + } + + submissionQueueEntries = UnsafeMutableBufferPointer( + start: sqes!.assumingMemoryBound(to: io_uring_sqe.self), + count: Int(params.sq_entries) + ) + + completionRing = CQRing( + kernelHead: UnsafeAtomic( + at: ringPtr.advanced(by: params.cq_off.head) + .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + ), + kernelTail: UnsafeAtomic( + at: ringPtr.advanced(by: params.cq_off.tail) + .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + ), + userHead: 0, // no completions yet + ringMask: ringPtr.advanced(by: params.cq_off.ring_mask) + .assumingMemoryBound(to: UInt32.self).pointee, + cqes: UnsafeBufferPointer( + start: ringPtr.advanced(by: params.cq_off.cqes) + .assumingMemoryBound(to: io_uring_cqe.self), + count: Int(ringPtr.advanced(by: params.cq_off.ring_entries) + .assumingMemoryBound(to: UInt32.self).pointee) + ) + ) + + self.submissionMutex = Mutex() + self.completionMutex = Mutex() + + self.ringFlags = params.flags + } + + func blockingConsumeCompletion() -> IOCompletion { + self.completionMutex.lock() + defer { self.completionMutex.unlock() } + + if let completion = _tryConsumeCompletion() { + return completion + } else { + _waitForCompletion() + return _tryConsumeCompletion().unsafelyUnwrapped + } + } + + func _waitForCompletion() { + // TODO: error handling + io_uring_enter(ringDescriptor, 0, 1, IORING_ENTER_GETEVENTS, nil) + } + + func tryConsumeCompletion() -> IOCompletion? { + self.completionMutex.lock() + defer { self.completionMutex.unlock() } + return _tryConsumeCompletion() + } + + func _tryConsumeCompletion() -> IOCompletion? { + let tail = completionRing.kernelTail.load(ordering: .acquiring) + var head = completionRing.kernelHead.load(ordering: .relaxed) + + if tail != head { + // 32 byte copy - oh well + let res = completionRing.cqes[Int(head & completionRing.ringMask)] + completionRing.kernelHead.store(head + 1, ordering: .relaxed) + return IOCompletion(rawValue: res) + } + + return nil + } + + + func registerFiles(count: UInt32) { + // TODO: implement + guard self.registeredFiles == nil else { fatalError() } + let fileBuf = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) + fileBuf.initialize(repeating: UInt32.max) + io_uring_register( + self.ringDescriptor, + IORING_REGISTER_FILES, + fileBuf.baseAddress!, + count + ) + // TODO: error handling + self.registeredFiles = fileBuf + } + + func unregisterFiles() { + if self.registeredFiles != nil { + io_uring_register( + self.ringDescriptor, + IORING_UNREGISTER_FILES, + self.registeredFiles!.baseAddress!, + UInt32(self.registeredFiles!.count) + ) + // TODO: error handling + self.registeredFiles!.deallocate() + self.registeredFiles = nil + } + } + + // register a group of buffers + func registerBuffers(bufSize: UInt32, count: UInt32) { + // + + } + + func getBuffer() -> (index: Int, buf: UnsafeRawBufferPointer) { + fatalError() + } + + // TODO: types + func submitRequests() { + self.submissionMutex.lock() + defer { self.submissionMutex.unlock() } + self._submitRequests() + } + + func _submitRequests() { + let flushedEvents = _flushQueue() + + // Ring always needs enter right now; + // TODO: support SQPOLL here + + let ret = io_uring_enter(ringDescriptor, flushedEvents, 0, 0, nil) + // TODO: handle errors + } + + internal func _flushQueue() -> UInt32 { + self.submissionRing.kernelTail.store( + self.submissionRing.userTail, ordering: .relaxed + ) + return self.submissionRing.userTail - + self.submissionRing.kernelHead.load(ordering: .relaxed) + } + + + func writeRequest(_ request: __owned IORequest) -> Bool { + self.submissionMutex.lock() + defer { self.submissionMutex.unlock() } + return _writeRequest(request) + } + + internal func _writeRequest(_ request: __owned IORequest) -> Bool { + if let entry = _getSubmissionEntry() { + entry.pointee = request.rawValue + return true + } + return false + } + + internal func _blockingGetSubmissionEntry() -> UnsafeMutablePointer { + while true { + if let entry = _getSubmissionEntry() { + return entry + } + // TODO: actually block here instead of spinning + } + + } + + internal func _getSubmissionEntry() -> UnsafeMutablePointer? { + let next = self.submissionRing.userTail + 1 + + // FEAT: smp load when SQPOLL in use (not in MVP) + let kernelHead = self.submissionRing.kernelHead.load(ordering: .relaxed) + + // FEAT: 128-bit event support (not in MVP) + if (next - kernelHead <= self.submissionRing.array.count) { + // let sqe = &sq->sqes[(sq->sqe_tail & sq->ring_mask) << shift]; + let sqeIndex = Int( + self.submissionRing.userTail & self.submissionRing.ringMask + ) + + let sqe = self.submissionQueueEntries + .baseAddress.unsafelyUnwrapped + .advanced(by: sqeIndex) + + self.submissionRing.userTail = next; + return sqe + } + return nil + } + + deinit { + munmap(ringPtr, ringSize); + munmap( + UnsafeMutableRawPointer(submissionQueueEntries.baseAddress!), + submissionQueueEntries.count * MemoryLayout.size + ) + close(ringDescriptor) + } +}; + diff --git a/Sources/System/IORingBuffer.swift b/Sources/System/IORingBuffer.swift new file mode 100644 index 0000000..e69de29 diff --git a/Sources/System/IORingFileSlot.swift b/Sources/System/IORingFileSlot.swift new file mode 100644 index 0000000..d0a7c66 --- /dev/null +++ b/Sources/System/IORingFileSlot.swift @@ -0,0 +1,8 @@ +class IORingFileSlot { + + + deinit { + // return file slot + + } +} \ No newline at end of file diff --git a/Sources/System/Lock.swift b/Sources/System/Lock.swift new file mode 100644 index 0000000..c5204ba --- /dev/null +++ b/Sources/System/Lock.swift @@ -0,0 +1,37 @@ +// TODO: write against kernel APIs directly? +import Glibc + +public final class Mutex { + @usableFromInline let mutex: UnsafeMutablePointer + + @inlinable init() { + self.mutex = UnsafeMutablePointer.allocate(capacity: 1) + self.mutex.initialize(to: pthread_mutex_t()) + pthread_mutex_init(self.mutex, nil) + } + + @inlinable deinit { + defer { mutex.deallocate() } + guard pthread_mutex_destroy(mutex) == 0 else { + preconditionFailure("unable to destroy mutex") + } + } + + // XXX: this is because we need to lock the mutex in the context of a submit() function + // and unlock *before* the UnsafeContinuation returns. + // Code looks like: { + // // prepare request + // io_uring_get_sqe() + // io_uring_prep_foo(...) + // return await withUnsafeContinuation { + // sqe->user_data = ...; io_uring_submit(); unlock(); + // } + // } + @inlinable @inline(__always) public func lock() { + pthread_mutex_lock(mutex) + } + + @inlinable @inline(__always) public func unlock() { + pthread_mutex_unlock(mutex) + } +} diff --git a/Sources/System/ManagedIORing.swift b/Sources/System/ManagedIORing.swift new file mode 100644 index 0000000..32c84fa --- /dev/null +++ b/Sources/System/ManagedIORing.swift @@ -0,0 +1,33 @@ +final public class ManagedIORing: @unchecked Sendable { + var internalRing: IORing + + init(queueDepth: UInt32) throws { + self.internalRing = try IORing(queueDepth: queueDepth) + self.startWaiter() + } + + private func startWaiter() { + Task.detached { + while (!Task.isCancelled) { + let cqe = self.internalRing.blockingConsumeCompletion() + + let cont = unsafeBitCast(cqe.userData, to: UnsafeContinuation.self) + cont.resume(returning: cqe) + } + } + } + + @_unsafeInheritExecutor + public func submitAndWait(_ request: __owned IORequest) async -> IOCompletion { + self.internalRing.submissionMutex.lock() + return await withUnsafeContinuation { cont in + let entry = internalRing._blockingGetSubmissionEntry() + entry.pointee = request.rawValue + entry.pointee.user_data = unsafeBitCast(cont, to: UInt64.self) + self.internalRing._submitRequests() + self.internalRing.submissionMutex.unlock() + } + } + + +} \ No newline at end of file From 6338029b74b84b79795a0cc24bcc189883ec083d Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Mon, 31 Jul 2023 22:28:43 -0700 Subject: [PATCH 002/102] stage 2: IORequest enum --- Sources/System/IORequest.swift | 204 +++++++++----------------- Sources/System/IORing.swift | 220 +++++++++++++++++++++------- Sources/System/IORingBuffer.swift | 0 Sources/System/IORingError.swift | 3 + Sources/System/IORingFileSlot.swift | 8 - Sources/System/Lock.swift | 2 +- Sources/System/ManagedIORing.swift | 11 +- Sources/System/RawIORequest.swift | 139 ++++++++++++++++++ 8 files changed, 396 insertions(+), 191 deletions(-) delete mode 100644 Sources/System/IORingBuffer.swift create mode 100644 Sources/System/IORingError.swift delete mode 100644 Sources/System/IORingFileSlot.swift create mode 100644 Sources/System/RawIORequest.swift diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index efa03f3..6b26a4d 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -1,140 +1,82 @@ -@_implementationOnly import CSystem +import struct CSystem.io_uring_sqe -public struct IORequest { - internal var rawValue: io_uring_sqe +public enum IORequest { + case nop // nothing here + case openat( + atDirectory: FileDescriptor, + path: UnsafePointer, + FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil, + intoSlot: IORingFileSlot? = nil + ) + case read( + file: File, + buffer: Buffer, + offset: UInt64 = 0 + ) + case write( + file: File, + buffer: Buffer, + offset: UInt64 = 0 + ) - public init() { - self.rawValue = io_uring_sqe() + public enum Buffer { + case registered(IORingBuffer) + case unregistered(UnsafeMutableRawBufferPointer) + } + + public enum File { + case registered(IORingFileSlot) + case unregistered(FileDescriptor) } } extension IORequest { - public enum Operation: UInt8 { - case nop = 0 - case readv = 1 - case writev = 2 - case fsync = 3 - case readFixed = 4 - case writeFixed = 5 - case pollAdd = 6 - case pollRemove = 7 - case syncFileRange = 8 - case sendMessage = 9 - case receiveMessage = 10 - // ... - case openAt = 18 - case read = 22 - case write = 23 - case openAt2 = 28 - - } - - public struct Flags: OptionSet, Hashable, Codable { - public let rawValue: UInt8 - - public init(rawValue: UInt8) { - self.rawValue = rawValue - } - - public static let fixedFile = Flags(rawValue: 1 << 0) - public static let drainQueue = Flags(rawValue: 1 << 1) - public static let linkRequest = Flags(rawValue: 1 << 2) - public static let hardlinkRequest = Flags(rawValue: 1 << 3) - public static let asynchronous = Flags(rawValue: 1 << 4) - public static let selectBuffer = Flags(rawValue: 1 << 5) - public static let skipSuccess = Flags(rawValue: 1 << 6) - } - - public var operation: Operation { - get { Operation(rawValue: rawValue.opcode)! } - set { rawValue.opcode = newValue.rawValue } - } - - public var flags: Flags { - get { Flags(rawValue: rawValue.flags) } - set { rawValue.flags = newValue.rawValue } - } - - public var fileDescriptor: FileDescriptor { - get { FileDescriptor(rawValue: rawValue.fd) } - set { rawValue.fd = newValue.rawValue } - } - - public var offset: UInt64? { - get { - if (rawValue.off == UInt64.max) { - return nil - } else { - return rawValue.off - } - } - set { - if let val = newValue { - rawValue.off = val - } else { - rawValue.off = UInt64.max - } - } - } - - public var buffer: UnsafeMutableRawBufferPointer { - get { - let ptr = UnsafeMutableRawPointer(bitPattern: UInt(exactly: rawValue.addr)!) - return UnsafeMutableRawBufferPointer(start: ptr, count: Int(rawValue.len)) - } - - set { - // TODO: cleanup? - rawValue.addr = UInt64(Int(bitPattern: newValue.baseAddress!)) - rawValue.len = UInt32(exactly: newValue.count)! + @inlinable @inline(__always) + public func makeRawRequest() -> RawIORequest { + var request = RawIORequest() + switch self { + case .nop: + request.operation = .nop + case .openat(let atDirectory, let path, let mode, let options, let permissions, let slot): + // TODO: use rawValue less + request.operation = .openAt + request.fileDescriptor = atDirectory + request.rawValue.addr = unsafeBitCast(path, to: UInt64.self) + request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) + request.rawValue.len = permissions?.rawValue ?? 0 + request.rawValue.file_index = UInt32(slot?.index ?? 0) + case .read(let file, let buffer, let offset), .write(let file, let buffer, let offset): + if case .read = self { + if case .registered = buffer { + request.operation = .readFixed + } else { + request.operation = .read + } + } else { + if case .registered = buffer { + request.operation = .writeFixed + } else { + request.operation = .write + } + } + switch file { + case .registered(let regFile): + request.rawValue.fd = Int32(exactly: regFile.index)! + request.flags = .fixedFile + case .unregistered(let fd): + request.fileDescriptor = fd + } + switch buffer { + case .registered(let regBuf): + request.buffer = regBuf.unsafeBuffer + request.rawValue.buf_index = UInt16(exactly: regBuf.index)! + case .unregistered(let buf): + request.buffer = buf + } + request.offset = offset } + return request } } - -extension IORequest { - static func nop() -> IORequest { - var req = IORequest() - req.operation = .nop - return req - } - - static func read( - from fileDescriptor: FileDescriptor, - into buffer: UnsafeMutableRawBufferPointer, - at offset: UInt64? = nil - ) -> IORequest { - var req = IORequest.readWrite( - op: Operation.read, - fd: fileDescriptor, - buffer: buffer, - offset: offset - ) - fatalError() - } - - static func read( - fixedFile: Int // TODO: AsyncFileDescriptor - ) -> IORequest { - fatalError() - } - - static func write( - - ) -> IORequest { - fatalError() - } - - internal static func readWrite( - op: Operation, - fd: FileDescriptor, - buffer: UnsafeMutableRawBufferPointer, - offset: UInt64? = nil - ) -> IORequest { - var req = IORequest() - req.operation = op - req.fileDescriptor = fd - req.offset = offset - req.buffer = buffer - return req - } -} \ No newline at end of file diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 6945d8c..0c2f138 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -1,6 +1,8 @@ @_implementationOnly import CSystem -import Glibc -import Atomics +import struct CSystem.io_uring_sqe + +@_implementationOnly import Atomics +import Glibc // needed for mmap // XXX: this *really* shouldn't be here. oh well. extension UnsafeMutableRawPointer { @@ -10,7 +12,7 @@ extension UnsafeMutableRawPointer { } // all pointers in this struct reference kernel-visible memory -struct SQRing { +@usableFromInline struct SQRing { let kernelHead: UnsafeAtomic let kernelTail: UnsafeAtomic var userTail: UInt32 @@ -44,14 +46,90 @@ struct CQRing { let cqes: UnsafeBufferPointer } +internal class ResourceManager: @unchecked Sendable { + typealias Resource = T + let resourceList: UnsafeMutableBufferPointer + var freeList: [Int] + let mutex: Mutex + + init(_ res: UnsafeMutableBufferPointer) { + self.resourceList = res + self.freeList = [Int](resourceList.indices) + self.mutex = Mutex() + } + + func getResource() -> IOResource? { + self.mutex.lock() + defer { self.mutex.unlock() } + if let index = freeList.popLast() { + return IOResource( + rescource: resourceList[index], + index: index, + manager: self + ) + } else { + return nil + } + } + + func releaseResource(index: Int) { + self.mutex.lock() + defer { self.mutex.unlock() } + self.freeList.append(index) + } +} + +public class IOResource { + typealias Resource = T + @usableFromInline let resource: T + @usableFromInline let index: Int + let manager: ResourceManager + + internal init( + rescource: T, + index: Int, + manager: ResourceManager + ) { + self.resource = rescource + self.index = index + self.manager = manager + } + + func withResource() { + + } + + deinit { + self.manager.releaseResource(index: self.index) + } +} + +public typealias IORingFileSlot = IOResource +public typealias IORingBuffer = IOResource + +extension IORingFileSlot { + public var unsafeFileSlot: Int { + return index + } +} +extension IORingBuffer { + public var unsafeBuffer: UnsafeMutableRawBufferPointer { + get { + return .init(start: resource.iov_base, count: resource.iov_len) + } + } +} + + + // XXX: This should be a non-copyable type (?) // demo only runs on Swift 5.8.1 -public final class IORing: Sendable { +public final class IORing: @unchecked Sendable { let ringFlags: UInt32 let ringDescriptor: Int32 - var submissionRing: SQRing - var submissionMutex: Mutex + @usableFromInline var submissionRing: SQRing + @usableFromInline var submissionMutex: Mutex // FEAT: set this eventually let submissionPolling: Bool = false @@ -59,13 +137,14 @@ public final class IORing: Sendable { var completionMutex: Mutex let submissionQueueEntries: UnsafeMutableBufferPointer - - var registeredFiles: UnsafeMutableBufferPointer? // kept around for unmap / cleanup let ringSize: Int let ringPtr: UnsafeMutableRawPointer + var registeredFiles: ResourceManager? + var registeredBuffers: ResourceManager? + public init(queueDepth: UInt32) throws { var params = io_uring_params() @@ -77,7 +156,7 @@ public final class IORing: Sendable { || params.features & IORING_FEAT_NODROP == 0) { close(ringDescriptor) // TODO: error handling - fatalError("kernel not new enough") + throw IORingError.missingRequiredFeatures } if (ringDescriptor < 0) { @@ -104,14 +183,9 @@ public final class IORing: Sendable { if (ringPtr == MAP_FAILED) { perror("mmap"); // TODO: error handling - fatalError() + fatalError("mmap failed in ring setup") } - let kernelHead = UnsafeAtomic(at: - ringPtr.advanced(by: params.sq_off.head) - .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) - ) - submissionRing = SQRing( kernelHead: UnsafeAtomic( at: ringPtr.advanced(by: params.sq_off.head) @@ -154,7 +228,7 @@ public final class IORing: Sendable { if (sqes == MAP_FAILED) { perror("mmap"); // TODO: error handling - fatalError() + fatalError("sqe mmap failed in ring setup") } submissionQueueEntries = UnsafeMutableBufferPointer( @@ -195,16 +269,29 @@ public final class IORing: Sendable { if let completion = _tryConsumeCompletion() { return completion } else { - _waitForCompletion() + while true { + let res = io_uring_enter(ringDescriptor, 0, 1, IORING_ENTER_GETEVENTS, nil) + // error handling: + // EAGAIN / EINTR (try again), + // EBADF / EBADFD / EOPNOTSUPP / ENXIO + // (failure in ring lifetime management, fatal), + // EINVAL (bad constant flag?, fatal), + // EFAULT (bad address for argument from library, fatal) + // EBUSY (not enough space for events; implies events filled + // by kernel between kernelTail load and now) + if res >= 0 || res == -EBUSY { + break + } else if res == -EAGAIN || res == -EINTR { + continue + } + fatalError("fatal error in receiving requests: " + + Errno(rawValue: -res).debugDescription + ) + } return _tryConsumeCompletion().unsafelyUnwrapped } } - func _waitForCompletion() { - // TODO: error handling - io_uring_enter(ringDescriptor, 0, 1, IORING_ENTER_GETEVENTS, nil) - } - func tryConsumeCompletion() -> IOCompletion? { self.completionMutex.lock() defer { self.completionMutex.unlock() } @@ -213,7 +300,7 @@ public final class IORing: Sendable { func _tryConsumeCompletion() -> IOCompletion? { let tail = completionRing.kernelTail.load(ordering: .acquiring) - var head = completionRing.kernelHead.load(ordering: .relaxed) + let head = completionRing.kernelHead.load(ordering: .relaxed) if tail != head { // 32 byte copy - oh well @@ -227,7 +314,6 @@ public final class IORing: Sendable { func registerFiles(count: UInt32) { - // TODO: implement guard self.registeredFiles == nil else { fatalError() } let fileBuf = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) fileBuf.initialize(repeating: UInt32.max) @@ -238,31 +324,43 @@ public final class IORing: Sendable { count ) // TODO: error handling - self.registeredFiles = fileBuf + self.registeredFiles = ResourceManager(fileBuf) } func unregisterFiles() { - if self.registeredFiles != nil { - io_uring_register( - self.ringDescriptor, - IORING_UNREGISTER_FILES, - self.registeredFiles!.baseAddress!, - UInt32(self.registeredFiles!.count) - ) - // TODO: error handling - self.registeredFiles!.deallocate() - self.registeredFiles = nil - } + fatalError("failed to unregister files") + } + + func getFile() -> IORingFileSlot? { + return self.registeredFiles?.getResource() } // register a group of buffers func registerBuffers(bufSize: UInt32, count: UInt32) { - // - + let iovecs = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) + let intBufSize = Int(bufSize) + for i in 0.. (index: Int, buf: UnsafeRawBufferPointer) { - fatalError() + func getBuffer() -> IORingBuffer? { + return self.registeredBuffers?.getResource() + } + + func unregisterBuffers() { + fatalError("failed to unregister buffers: TODO") } // TODO: types @@ -277,9 +375,22 @@ public final class IORing: Sendable { // Ring always needs enter right now; // TODO: support SQPOLL here - - let ret = io_uring_enter(ringDescriptor, flushedEvents, 0, 0, nil) - // TODO: handle errors + while true { + let ret = io_uring_enter(ringDescriptor, flushedEvents, 0, 0, nil) + // error handling: + // EAGAIN / EINTR (try again), + // EBADF / EBADFD / EOPNOTSUPP / ENXIO + // (failure in ring lifetime management, fatal), + // EINVAL (bad constant flag?, fatal), + // EFAULT (bad address for argument from library, fatal) + if ret == -EAGAIN || ret == -EINTR { + continue + } else if ret < 0 { + fatalError("fatal error in submitting requests: " + + Errno(rawValue: -ret).debugDescription + ) + } + } } internal func _flushQueue() -> UInt32 { @@ -291,20 +402,28 @@ public final class IORing: Sendable { } + @inlinable @inline(__always) func writeRequest(_ request: __owned IORequest) -> Bool { self.submissionMutex.lock() defer { self.submissionMutex.unlock() } - return _writeRequest(request) + return _writeRequest(request.makeRawRequest()) } - internal func _writeRequest(_ request: __owned IORequest) -> Bool { - if let entry = _getSubmissionEntry() { - entry.pointee = request.rawValue - return true - } - return false + @inlinable @inline(__always) + func writeAndSubmit(_ request: __owned IORequest) -> Bool { + self.submissionMutex.lock() + defer { self.submissionMutex.unlock() } + return _writeRequest(request.makeRawRequest()) } + @inlinable @inline(__always) + internal func _writeRequest(_ request: __owned RawIORequest) -> Bool { + let entry = _blockingGetSubmissionEntry() + entry.pointee = request.rawValue + return true + } + + @inlinable @inline(__always) internal func _blockingGetSubmissionEntry() -> UnsafeMutablePointer { while true { if let entry = _getSubmissionEntry() { @@ -315,6 +434,7 @@ public final class IORing: Sendable { } + @usableFromInline @inline(__always) internal func _getSubmissionEntry() -> UnsafeMutablePointer? { let next = self.submissionRing.userTail + 1 diff --git a/Sources/System/IORingBuffer.swift b/Sources/System/IORingBuffer.swift deleted file mode 100644 index e69de29..0000000 diff --git a/Sources/System/IORingError.swift b/Sources/System/IORingError.swift new file mode 100644 index 0000000..d87b293 --- /dev/null +++ b/Sources/System/IORingError.swift @@ -0,0 +1,3 @@ +enum IORingError: Error { + case missingRequiredFeatures +} diff --git a/Sources/System/IORingFileSlot.swift b/Sources/System/IORingFileSlot.swift deleted file mode 100644 index d0a7c66..0000000 --- a/Sources/System/IORingFileSlot.swift +++ /dev/null @@ -1,8 +0,0 @@ -class IORingFileSlot { - - - deinit { - // return file slot - - } -} \ No newline at end of file diff --git a/Sources/System/Lock.swift b/Sources/System/Lock.swift index c5204ba..fd20c64 100644 --- a/Sources/System/Lock.swift +++ b/Sources/System/Lock.swift @@ -1,7 +1,7 @@ // TODO: write against kernel APIs directly? import Glibc -public final class Mutex { +@usableFromInline final class Mutex { @usableFromInline let mutex: UnsafeMutablePointer @inlinable init() { diff --git a/Sources/System/ManagedIORing.swift b/Sources/System/ManagedIORing.swift index 32c84fa..580eacc 100644 --- a/Sources/System/ManagedIORing.swift +++ b/Sources/System/ManagedIORing.swift @@ -3,6 +3,8 @@ final public class ManagedIORing: @unchecked Sendable { init(queueDepth: UInt32) throws { self.internalRing = try IORing(queueDepth: queueDepth) + self.internalRing.registerBuffers(bufSize: 655336, count: 4) + self.internalRing.registerFiles(count: 32) self.startWaiter() } @@ -22,12 +24,19 @@ final public class ManagedIORing: @unchecked Sendable { self.internalRing.submissionMutex.lock() return await withUnsafeContinuation { cont in let entry = internalRing._blockingGetSubmissionEntry() - entry.pointee = request.rawValue + entry.pointee = request.makeRawRequest().rawValue entry.pointee.user_data = unsafeBitCast(cont, to: UInt64.self) self.internalRing._submitRequests() self.internalRing.submissionMutex.unlock() } } + internal func getFileSlot() -> IORingFileSlot? { + self.internalRing.getFile() + } + + internal func getBuffer() -> IORingBuffer? { + self.internalRing.getBuffer() + } } \ No newline at end of file diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift new file mode 100644 index 0000000..fa50b43 --- /dev/null +++ b/Sources/System/RawIORequest.swift @@ -0,0 +1,139 @@ +// TODO: investigate @usableFromInline / @_implementationOnly dichotomy +@_implementationOnly import CSystem +import struct CSystem.io_uring_sqe + +public struct RawIORequest { + @usableFromInline var rawValue: io_uring_sqe + + public init() { + self.rawValue = io_uring_sqe() + } +} + +extension RawIORequest { + public enum Operation: UInt8 { + case nop = 0 + case readv = 1 + case writev = 2 + case fsync = 3 + case readFixed = 4 + case writeFixed = 5 + case pollAdd = 6 + case pollRemove = 7 + case syncFileRange = 8 + case sendMessage = 9 + case receiveMessage = 10 + // ... + case openAt = 18 + case read = 22 + case write = 23 + case openAt2 = 28 + + } + + public struct Flags: OptionSet, Hashable, Codable { + public let rawValue: UInt8 + + public init(rawValue: UInt8) { + self.rawValue = rawValue + } + + public static let fixedFile = Flags(rawValue: 1 << 0) + public static let drainQueue = Flags(rawValue: 1 << 1) + public static let linkRequest = Flags(rawValue: 1 << 2) + public static let hardlinkRequest = Flags(rawValue: 1 << 3) + public static let asynchronous = Flags(rawValue: 1 << 4) + public static let selectBuffer = Flags(rawValue: 1 << 5) + public static let skipSuccess = Flags(rawValue: 1 << 6) + } + + public var operation: Operation { + get { Operation(rawValue: rawValue.opcode)! } + set { rawValue.opcode = newValue.rawValue } + } + + public var flags: Flags { + get { Flags(rawValue: rawValue.flags) } + set { rawValue.flags = newValue.rawValue } + } + + public var fileDescriptor: FileDescriptor { + get { FileDescriptor(rawValue: rawValue.fd) } + set { rawValue.fd = newValue.rawValue } + } + + public var offset: UInt64? { + get { + if (rawValue.off == UInt64.max) { + return nil + } else { + return rawValue.off + } + } + set { + if let val = newValue { + rawValue.off = val + } else { + rawValue.off = UInt64.max + } + } + } + + public var buffer: UnsafeMutableRawBufferPointer { + get { + let ptr = UnsafeMutableRawPointer(bitPattern: UInt(exactly: rawValue.addr)!) + return UnsafeMutableRawBufferPointer(start: ptr, count: Int(rawValue.len)) + } + + set { + // TODO: cleanup? + rawValue.addr = UInt64(Int(bitPattern: newValue.baseAddress!)) + rawValue.len = UInt32(exactly: newValue.count)! + } + } + + public enum RequestFlags { + case readWriteFlags(ReadWriteFlags) + // case fsyncFlags(FsyncFlags?) + // poll_events + // poll32_events + // sync_range_flags + // msg_flags + // timeout_flags + // accept_flags + // cancel_flags + case openFlags(FileDescriptor.OpenOptions) + // statx_flags + // fadvise_advice + // splice_flags + } + + public struct ReadWriteFlags: OptionSet, Hashable, Codable { + public var rawValue: UInt32 + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + public static let highPriority = ReadWriteFlags(rawValue: 1 << 0) + + // sync with only data integrity + public static let dataSync = ReadWriteFlags(rawValue: 1 << 1) + + // sync with full data + file integrity + public static let fileSync = ReadWriteFlags(rawValue: 1 << 2) + + // return -EAGAIN if operation blocks + public static let noWait = ReadWriteFlags(rawValue: 1 << 3) + + // append to end of the file + public static let append = ReadWriteFlags(rawValue: 1 << 4) + } +} + +extension RawIORequest { + static func nop() -> RawIORequest { + var req = RawIORequest() + req.operation = .nop + return req + } +} \ No newline at end of file From 996e940942f976f7a2de8751375c21413812ac41 Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Mon, 31 Jul 2023 22:28:54 -0700 Subject: [PATCH 003/102] initial AsyncFileDescriptor work --- Sources/System/AsyncFileDescriptor.swift | 71 ++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Sources/System/AsyncFileDescriptor.swift diff --git a/Sources/System/AsyncFileDescriptor.swift b/Sources/System/AsyncFileDescriptor.swift new file mode 100644 index 0000000..9742781 --- /dev/null +++ b/Sources/System/AsyncFileDescriptor.swift @@ -0,0 +1,71 @@ +@_implementationOnly import CSystem + +public class AsyncFileDescriptor { + var open: Bool = true + @usableFromInline let fileSlot: IORingFileSlot + @usableFromInline let ring: ManagedIORing + + static func openat( + atDirectory: FileDescriptor = FileDescriptor(rawValue: AT_FDCWD), + path: FilePath, + _ mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil, + onRing ring: ManagedIORing + ) async throws -> AsyncFileDescriptor { + // todo; real error type + guard let fileSlot = ring.getFileSlot() else { + throw IORingError.missingRequiredFeatures + } + let cstr = path.withCString { + return $0 // bad + } + let res = await ring.submitAndWait(.openat( + atDirectory: atDirectory, + path: cstr, + mode, + options: options, + permissions: permissions, intoSlot: fileSlot + )) + if res.result < 0 { + throw Errno(rawValue: -res.result) + } + + return AsyncFileDescriptor( + fileSlot, ring: ring + ) + } + + internal init(_ fileSlot: IORingFileSlot, ring: ManagedIORing) { + self.fileSlot = fileSlot + self.ring = ring + } + + func close() async throws { + self.open = false + fatalError() + } + + @inlinable @inline(__always) @_unsafeInheritExecutor + func read( + into buffer: IORequest.Buffer, + atAbsoluteOffset offset: UInt64 = UInt64.max + ) async throws -> UInt32 { + let res = await ring.submitAndWait(.read( + file: .registered(self.fileSlot), + buffer: buffer, + offset: offset + )) + if res.result < 0 { + throw Errno(rawValue: -res.result) + } else { + return UInt32(bitPattern: res.result) + } + } + + deinit { + if (self.open) { + // TODO: close + } + } +} From 1f821a8539af62aab858f356ab9aa21592742ccb Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Tue, 8 Aug 2023 09:44:32 -0700 Subject: [PATCH 004/102] AsyncSequence draft implementation --- Sources/System/AsyncFileDescriptor.swift | 52 ++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/Sources/System/AsyncFileDescriptor.swift b/Sources/System/AsyncFileDescriptor.swift index 9742781..6e39e05 100644 --- a/Sources/System/AsyncFileDescriptor.swift +++ b/Sources/System/AsyncFileDescriptor.swift @@ -69,3 +69,55 @@ public class AsyncFileDescriptor { } } } + +extension AsyncFileDescriptor: AsyncSequence { + public func makeAsyncIterator() -> FileIterator { + return .init(self) + } + + public typealias AsyncIterator = FileIterator + public typealias Element = UInt8 +} + +public struct FileIterator: AsyncIteratorProtocol { + @usableFromInline let file: AsyncFileDescriptor + @usableFromInline var buffer: IORingBuffer + @usableFromInline var done: Bool + + @usableFromInline internal var currentByte: UnsafeRawPointer? + @usableFromInline internal var lastByte: UnsafeRawPointer? + + init(_ file: AsyncFileDescriptor) { + self.file = file + self.buffer = file.ring.getBuffer()! + self.done = false + } + + @inlinable @inline(__always) + public mutating func nextBuffer() async throws { + let buffer = self.buffer + + let bytesRead = try await file.read(into: .registered(buffer)) + if _fastPath(bytesRead != 0) { + let bufPointer = buffer.unsafeBuffer.baseAddress.unsafelyUnwrapped + self.currentByte = UnsafeRawPointer(bufPointer) + self.lastByte = UnsafeRawPointer(bufPointer.advanced(by: Int(bytesRead))) + } else { + self.done = true + } + } + + @inlinable @inline(__always) @_unsafeInheritExecutor + public mutating func next() async throws -> UInt8? { + if _fastPath(currentByte != lastByte) { + // SAFETY: both pointers should be non-nil if they're not equal + let byte = currentByte.unsafelyUnwrapped.load(as: UInt8.self) + currentByte = currentByte.unsafelyUnwrapped + 1 + return byte + } else if done { + return nil + } + try await nextBuffer() + return try await next() + } +} From 0762f57d806df3f5ad9e268d18eddbe4f3cb2594 Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Thu, 10 Aug 2023 16:03:21 -0700 Subject: [PATCH 005/102] migrate CSystem to systemLibrary for some reason, the linker on my linux machine fails to link the tests otherwise. investigate / fix before merging. --- Package.swift | 5 ++--- Sources/CSystem/{include => }/CSystemLinux.h | 0 Sources/CSystem/{include => }/CSystemWindows.h | 0 Sources/CSystem/{include => }/io_uring.h | 5 +++++ Sources/CSystem/{include => }/module.modulemap | 0 Sources/CSystem/shims.c | 18 ------------------ 6 files changed, 7 insertions(+), 21 deletions(-) rename Sources/CSystem/{include => }/CSystemLinux.h (100%) rename Sources/CSystem/{include => }/CSystemWindows.h (100%) rename Sources/CSystem/{include => }/io_uring.h (94%) rename Sources/CSystem/{include => }/module.modulemap (100%) delete mode 100644 Sources/CSystem/shims.c diff --git a/Package.swift b/Package.swift index 60f1a56..1c058ac 100644 --- a/Package.swift +++ b/Package.swift @@ -21,9 +21,8 @@ let package = Package( .package(url: "https://github.com/apple/swift-atomics", from: "1.1.0") ], targets: [ - .target( - name: "CSystem", - dependencies: []), + .systemLibrary( + name: "CSystem"), .target( name: "SystemPackage", dependencies: [ diff --git a/Sources/CSystem/include/CSystemLinux.h b/Sources/CSystem/CSystemLinux.h similarity index 100% rename from Sources/CSystem/include/CSystemLinux.h rename to Sources/CSystem/CSystemLinux.h diff --git a/Sources/CSystem/include/CSystemWindows.h b/Sources/CSystem/CSystemWindows.h similarity index 100% rename from Sources/CSystem/include/CSystemWindows.h rename to Sources/CSystem/CSystemWindows.h diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/io_uring.h similarity index 94% rename from Sources/CSystem/include/io_uring.h rename to Sources/CSystem/io_uring.h index 9e3d9fb..5c05ed8 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/io_uring.h @@ -5,6 +5,9 @@ #include #include +#ifndef SWIFT_IORING_C_WRAPPER +#define SWIFT_IORING_C_WRAPPER + #ifdef __alpha__ /* * alpha is the only exception, all other architectures @@ -48,3 +51,5 @@ int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete, return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, sig, _NSIG / 8); } + +#endif diff --git a/Sources/CSystem/include/module.modulemap b/Sources/CSystem/module.modulemap similarity index 100% rename from Sources/CSystem/include/module.modulemap rename to Sources/CSystem/module.modulemap diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c deleted file mode 100644 index f492a2a..0000000 --- a/Sources/CSystem/shims.c +++ /dev/null @@ -1,18 +0,0 @@ -/* - 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 -*/ - -#ifdef __linux__ - -#include - -#endif - -#if defined(_WIN32) -#include -#endif From d099546787499e97973db394abb3de388e7e5305 Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Fri, 11 Aug 2023 09:06:17 -0700 Subject: [PATCH 006/102] fix access control --- Sources/System/AsyncFileDescriptor.swift | 14 +++++----- Sources/System/IORing.swift | 34 +++++++++--------------- Sources/System/ManagedIORing.swift | 2 +- 3 files changed, 22 insertions(+), 28 deletions(-) diff --git a/Sources/System/AsyncFileDescriptor.swift b/Sources/System/AsyncFileDescriptor.swift index 6e39e05..2143847 100644 --- a/Sources/System/AsyncFileDescriptor.swift +++ b/Sources/System/AsyncFileDescriptor.swift @@ -1,12 +1,13 @@ @_implementationOnly import CSystem -public class AsyncFileDescriptor { - var open: Bool = true + +public final class AsyncFileDescriptor { + @usableFromInline var open: Bool = true @usableFromInline let fileSlot: IORingFileSlot @usableFromInline let ring: ManagedIORing - static func openat( - atDirectory: FileDescriptor = FileDescriptor(rawValue: AT_FDCWD), + public static func openat( + atDirectory: FileDescriptor = FileDescriptor(rawValue: -100), path: FilePath, _ mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), @@ -25,7 +26,8 @@ public class AsyncFileDescriptor { path: cstr, mode, options: options, - permissions: permissions, intoSlot: fileSlot + permissions: permissions, + intoSlot: fileSlot )) if res.result < 0 { throw Errno(rawValue: -res.result) @@ -47,7 +49,7 @@ public class AsyncFileDescriptor { } @inlinable @inline(__always) @_unsafeInheritExecutor - func read( + public func read( into buffer: IORequest.Buffer, atAbsoluteOffset offset: UInt64 = UInt64.max ) async throws -> UInt32 { diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 0c2f138..f91dfc0 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -262,7 +262,7 @@ public final class IORing: @unchecked Sendable { self.ringFlags = params.flags } - func blockingConsumeCompletion() -> IOCompletion { + public func blockingConsumeCompletion() -> IOCompletion { self.completionMutex.lock() defer { self.completionMutex.unlock() } @@ -292,7 +292,7 @@ public final class IORing: @unchecked Sendable { } } - func tryConsumeCompletion() -> IOCompletion? { + public func tryConsumeCompletion() -> IOCompletion? { self.completionMutex.lock() defer { self.completionMutex.unlock() } return _tryConsumeCompletion() @@ -312,8 +312,7 @@ public final class IORing: @unchecked Sendable { return nil } - - func registerFiles(count: UInt32) { + public func registerFiles(count: UInt32) { guard self.registeredFiles == nil else { fatalError() } let fileBuf = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) fileBuf.initialize(repeating: UInt32.max) @@ -327,16 +326,15 @@ public final class IORing: @unchecked Sendable { self.registeredFiles = ResourceManager(fileBuf) } - func unregisterFiles() { + public func unregisterFiles() { fatalError("failed to unregister files") } - func getFile() -> IORingFileSlot? { + public func getFile() -> IORingFileSlot? { return self.registeredFiles?.getResource() } - // register a group of buffers - func registerBuffers(bufSize: UInt32, count: UInt32) { + public func registerBuffers(bufSize: UInt32, count: UInt32) { let iovecs = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) let intBufSize = Int(bufSize) for i in 0.. IORingBuffer? { + public func getBuffer() -> IORingBuffer? { return self.registeredBuffers?.getResource() } - func unregisterBuffers() { + public func unregisterBuffers() { fatalError("failed to unregister buffers: TODO") } - // TODO: types - func submitRequests() { + public func submitRequests() { self.submissionMutex.lock() defer { self.submissionMutex.unlock() } self._submitRequests() } - func _submitRequests() { + internal func _submitRequests() { let flushedEvents = _flushQueue() // Ring always needs enter right now; @@ -389,6 +386,8 @@ public final class IORing: @unchecked Sendable { fatalError("fatal error in submitting requests: " + Errno(rawValue: -ret).debugDescription ) + } else { + break } } } @@ -403,14 +402,7 @@ public final class IORing: @unchecked Sendable { @inlinable @inline(__always) - func writeRequest(_ request: __owned IORequest) -> Bool { - self.submissionMutex.lock() - defer { self.submissionMutex.unlock() } - return _writeRequest(request.makeRawRequest()) - } - - @inlinable @inline(__always) - func writeAndSubmit(_ request: __owned IORequest) -> Bool { + public func writeRequest(_ request: __owned IORequest) -> Bool { self.submissionMutex.lock() defer { self.submissionMutex.unlock() } return _writeRequest(request.makeRawRequest()) diff --git a/Sources/System/ManagedIORing.swift b/Sources/System/ManagedIORing.swift index 580eacc..7f5bec2 100644 --- a/Sources/System/ManagedIORing.swift +++ b/Sources/System/ManagedIORing.swift @@ -1,7 +1,7 @@ final public class ManagedIORing: @unchecked Sendable { var internalRing: IORing - init(queueDepth: UInt32) throws { + public init(queueDepth: UInt32) throws { self.internalRing = try IORing(queueDepth: queueDepth) self.internalRing.registerBuffers(bufSize: 655336, count: 4) self.internalRing.registerFiles(count: 32) From b58450413e04141a7fa4e32b7cb68b3fa90809e1 Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Fri, 11 Aug 2023 09:07:08 -0700 Subject: [PATCH 007/102] fix off-by-one in IORequest.openat --- Sources/System/IORequest.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 6b26a4d..39d7cdb 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -46,7 +46,9 @@ extension IORequest { request.rawValue.addr = unsafeBitCast(path, to: UInt64.self) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 - request.rawValue.file_index = UInt32(slot?.index ?? 0) + if let fileSlot = slot { + request.rawValue.file_index = UInt32(fileSlot.index + 1) + } case .read(let file, let buffer, let offset), .write(let file, let buffer, let offset): if case .read = self { if case .registered = buffer { From b596783bd9a5e9d34f99e06b3624c0bf9e243c7d Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Fri, 11 Aug 2023 09:07:47 -0700 Subject: [PATCH 008/102] implement closing --- Sources/System/AsyncFileDescriptor.swift | 12 +++++++++--- Sources/System/IORequest.swift | 9 +++++++++ Sources/System/RawIORequest.swift | 6 +++++- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/Sources/System/AsyncFileDescriptor.swift b/Sources/System/AsyncFileDescriptor.swift index 2143847..504aec9 100644 --- a/Sources/System/AsyncFileDescriptor.swift +++ b/Sources/System/AsyncFileDescriptor.swift @@ -43,9 +43,15 @@ public final class AsyncFileDescriptor { self.ring = ring } - func close() async throws { + @inlinable @inline(__always) @_unsafeInheritExecutor + public func close() async throws { + let res = await ring.submitAndWait(.close( + .registered(self.fileSlot) + )) + if res.result < 0 { + throw Errno(rawValue: -res.result) + } self.open = false - fatalError() } @inlinable @inline(__always) @_unsafeInheritExecutor @@ -67,7 +73,7 @@ public final class AsyncFileDescriptor { deinit { if (self.open) { - // TODO: close + // TODO: close or error? TBD } } } diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 39d7cdb..9548b3f 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -20,6 +20,7 @@ public enum IORequest { buffer: Buffer, offset: UInt64 = 0 ) + case close(File) public enum Buffer { case registered(IORingBuffer) @@ -78,6 +79,14 @@ extension IORequest { request.buffer = buf } request.offset = offset + case .close(let file): + request.operation = .close + switch file { + case .registered(let regFile): + request.rawValue.file_index = UInt32(regFile.index + 1) + case .unregistered(let normalFile): + request.fileDescriptor = normalFile + } } return request } diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index fa50b43..520cb85 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -25,10 +25,14 @@ extension RawIORequest { case receiveMessage = 10 // ... case openAt = 18 + case close = 19 + case filesUpdate = 20 + case statx = 21 case read = 22 case write = 23 + // ... case openAt2 = 28 - + // ... } public struct Flags: OptionSet, Hashable, Codable { From 6b4084c69f8a691976d7fe4deeaa80e099649356 Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Fri, 11 Aug 2023 09:08:43 -0700 Subject: [PATCH 009/102] introduce IORing unit tests --- Tests/LinuxMain.swift | 8 -- .../AsyncFileDescriptorTests.swift | 40 ++++++ Tests/SystemTests/IORequestTests.swift | 68 +++++++++ Tests/SystemTests/IORingTests.swift | 21 +++ Tests/SystemTests/ManagedIORingTests.swift | 19 +++ Tests/SystemTests/XCTestManifests.swift | 132 ------------------ 6 files changed, 148 insertions(+), 140 deletions(-) delete mode 100644 Tests/LinuxMain.swift create mode 100644 Tests/SystemTests/AsyncFileDescriptorTests.swift create mode 100644 Tests/SystemTests/IORequestTests.swift create mode 100644 Tests/SystemTests/IORingTests.swift create mode 100644 Tests/SystemTests/ManagedIORingTests.swift delete mode 100644 Tests/SystemTests/XCTestManifests.swift diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift deleted file mode 100644 index 695f4e5..0000000 --- a/Tests/LinuxMain.swift +++ /dev/null @@ -1,8 +0,0 @@ -import XCTest - -import SystemTests - -var tests = [XCTestCaseEntry]() -tests += SystemTests.__allTests() - -XCTMain(tests) diff --git a/Tests/SystemTests/AsyncFileDescriptorTests.swift b/Tests/SystemTests/AsyncFileDescriptorTests.swift new file mode 100644 index 0000000..0f1c103 --- /dev/null +++ b/Tests/SystemTests/AsyncFileDescriptorTests.swift @@ -0,0 +1,40 @@ +import XCTest + +#if SYSTEM_PACKAGE +import SystemPackage +#else +import System +#endif + +final class AsyncFileDescriptorTests: XCTestCase { + func testOpen() async throws { + let ring = try ManagedIORing(queueDepth: 32) + let file = try await AsyncFileDescriptor.openat( + path: "/dev/zero", + .readOnly, + onRing: ring + ) + } + + func testOpenClose() async throws { + let ring = try ManagedIORing(queueDepth: 32) + let file = try await AsyncFileDescriptor.openat( + path: "/dev/zero", + .readOnly, + onRing: ring + ) + await try file.close() + } + + func testDevNullEmpty() async throws { + let ring = try ManagedIORing(queueDepth: 32) + let file = try await AsyncFileDescriptor.openat( + path: "/dev/null", + .readOnly, + onRing: ring + ) + for try await _ in file { + XCTFail("/dev/null should be empty") + } + } +} diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift new file mode 100644 index 0000000..a44a607 --- /dev/null +++ b/Tests/SystemTests/IORequestTests.swift @@ -0,0 +1,68 @@ +import XCTest + +#if SYSTEM_PACKAGE +@testable import SystemPackage +#else +import System +#endif + +func requestBytes(_ request: RawIORequest) -> [UInt8] { + return withUnsafePointer(to: request) { + let requestBuf = UnsafeBufferPointer(start: $0, count: 1) + let rawBytes = UnsafeRawBufferPointer(requestBuf) + return .init(rawBytes) + } +} + +// This test suite compares various IORequests bit-for-bit to IORequests +// that were generated with liburing or manually written out, +// which are known to work correctly. +final class IORequestTests: XCTestCase { + func testNop() { + let req = IORequest.nop.makeRawRequest() + let sourceBytes = requestBytes(req) + // convenient property of nop: it's all zeros! + // for some unknown reason, liburing sets the fd field to -1. + // we're not trying to be bug-compatible with it, so 0 *should* work. + XCTAssertEqual(sourceBytes, .init(repeating: 0, count: 64)) + } + + func testOpenatFixedFile() throws { + // TODO: come up with a better way of getting a FileSlot. + let buf = UnsafeMutableBufferPointer.allocate(capacity: 2) + let resmgr = ResourceManager.init(buf) + + let pathPtr = UnsafePointer(bitPattern: 0x414141410badf00d)! + let fileSlot = resmgr.getResource()! + let req = IORequest.openat( + atDirectory: FileDescriptor(rawValue: -100), + path: pathPtr, + .readOnly, + options: [], + permissions: nil, + intoSlot: fileSlot + ) + + let expectedRequest: [UInt8] = { + var bin = [UInt8].init(repeating: 0, count: 64) + bin[0] = 0x12 // opcode for the request + // bin[1] = 0 - no request flags + // bin[2...3] = 0 - padding + bin[4...7] = [0x9c, 0xff, 0xff, 0xff] // -100 in UInt32 - dirfd + // bin[8...15] = 0 - zeroes + withUnsafeBytes(of: pathPtr) { + // path pointer + bin[16...23] = ArraySlice($0) + } + // bin[24...43] = 0 - zeroes + withUnsafeBytes(of: UInt32(fileSlot.index + 1)) { + // file index + 1 - yes, unfortunately + bin[44...47] = ArraySlice($0) + } + return bin + }() + + let actualRequest = requestBytes(req.makeRawRequest()) + XCTAssertEqual(expectedRequest, actualRequest) + } +} diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift new file mode 100644 index 0000000..78baa98 --- /dev/null +++ b/Tests/SystemTests/IORingTests.swift @@ -0,0 +1,21 @@ +import XCTest + +#if SYSTEM_PACKAGE +import SystemPackage +#else +import System +#endif + +final class IORingTests: XCTestCase { + func testInit() throws { + let ring = try IORing(queueDepth: 32) + } + + func testNop() throws { + let ring = try IORing(queueDepth: 32) + ring.writeRequest(.nop) + ring.submitRequests() + let completion = ring.blockingConsumeCompletion() + XCTAssertEqual(completion.result, 0) + } +} diff --git a/Tests/SystemTests/ManagedIORingTests.swift b/Tests/SystemTests/ManagedIORingTests.swift new file mode 100644 index 0000000..e7ad3f5 --- /dev/null +++ b/Tests/SystemTests/ManagedIORingTests.swift @@ -0,0 +1,19 @@ +import XCTest + +#if SYSTEM_PACKAGE +import SystemPackage +#else +import System +#endif + +final class ManagedIORingTests: XCTestCase { + func testInit() throws { + let ring = try ManagedIORing(queueDepth: 32) + } + + func testNop() async throws { + let ring = try ManagedIORing(queueDepth: 32) + let completion = await ring.submitAndWait(.nop) + XCTAssertEqual(completion.result, 0) + } +} diff --git a/Tests/SystemTests/XCTestManifests.swift b/Tests/SystemTests/XCTestManifests.swift deleted file mode 100644 index de99bd8..0000000 --- a/Tests/SystemTests/XCTestManifests.swift +++ /dev/null @@ -1,132 +0,0 @@ -#if !canImport(ObjectiveC) && swift(<5.5) -import XCTest - -extension ErrnoTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__ErrnoTest = [ - ("testConstants", testConstants), - ("testPatternMatching", testPatternMatching), - ] -} - -extension FileDescriptorTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FileDescriptorTest = [ - ("testConstants", testConstants), - ("testStandardDescriptors", testStandardDescriptors), - ] -} - -extension FileOperationsTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FileOperationsTest = [ - ("testAdHocOpen", testAdHocOpen), - ("testAdHocPipe", testAdHocPipe), - ("testGithubIssues", testGithubIssues), - ("testHelpers", testHelpers), - ("testSyscalls", testSyscalls), - ] -} - -extension FilePathComponentsTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePathComponentsTest = [ - ("testAdHocRRC", testAdHocRRC), - ("testCases", testCases), - ("testSeparatorNormalization", testSeparatorNormalization), - ] -} - -extension FilePathParsingTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePathParsingTest = [ - ("testNormalization", testNormalization), - ] -} - -extension FilePathSyntaxTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePathSyntaxTest = [ - ("testAdHocMutations", testAdHocMutations), - ("testFailableStringInitializers", testFailableStringInitializers), - ("testLexicallyRelative", testLexicallyRelative), - ("testPartialWindowsRoots", testPartialWindowsRoots), - ("testPathSyntax", testPathSyntax), - ("testPrefixSuffix", testPrefixSuffix), - ] -} - -extension FilePathTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePathTest = [ - ("testFilePath", testFilePath), - ] -} - -extension FilePermissionsTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FilePermissionsTest = [ - ("testPermissions", testPermissions), - ] -} - -extension MockingTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__MockingTest = [ - ("testMocking", testMocking), - ] -} - -extension SystemCharTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__SystemCharTest = [ - ("testIsLetter", testIsLetter), - ] -} - -extension SystemStringTest { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__SystemStringTest = [ - ("testAdHoc", testAdHoc), - ("testPlatformString", testPlatformString), - ] -} - -public func __allTests() -> [XCTestCaseEntry] { - return [ - testCase(ErrnoTest.__allTests__ErrnoTest), - testCase(FileDescriptorTest.__allTests__FileDescriptorTest), - testCase(FileOperationsTest.__allTests__FileOperationsTest), - testCase(FilePathComponentsTest.__allTests__FilePathComponentsTest), - testCase(FilePathParsingTest.__allTests__FilePathParsingTest), - testCase(FilePathSyntaxTest.__allTests__FilePathSyntaxTest), - testCase(FilePathTest.__allTests__FilePathTest), - testCase(FilePermissionsTest.__allTests__FilePermissionsTest), - testCase(MockingTest.__allTests__MockingTest), - testCase(SystemCharTest.__allTests__SystemCharTest), - testCase(SystemStringTest.__allTests__SystemStringTest), - ] -} -#endif From baab9b26b77bca2622e7f3741ceddc62a51e00fe Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 24 Oct 2024 21:21:07 +0000 Subject: [PATCH 010/102] Starting to move to noncopyable structs, and away from swift-atomics --- Sources/System/IORing.swift | 72 ++++++++++++++--------------- Tests/SystemTests/IORingTests.swift | 2 +- 2 files changed, 37 insertions(+), 37 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index f91dfc0..0ac783a 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -1,7 +1,7 @@ @_implementationOnly import CSystem import struct CSystem.io_uring_sqe -@_implementationOnly import Atomics +@_implementationOnly import Synchronization import Glibc // needed for mmap // XXX: this *really* shouldn't be here. oh well. @@ -12,9 +12,9 @@ extension UnsafeMutableRawPointer { } // all pointers in this struct reference kernel-visible memory -@usableFromInline struct SQRing { - let kernelHead: UnsafeAtomic - let kernelTail: UnsafeAtomic +@usableFromInline struct SQRing: ~Copyable { + let kernelHead: UnsafePointer> + let kernelTail: UnsafePointer> var userTail: UInt32 // from liburing: the kernel should never change these @@ -25,7 +25,7 @@ extension UnsafeMutableRawPointer { // ring flags bitfield // currently used by the kernel only in SQPOLL mode to indicate // when the polling thread needs to be woken up - let flags: UnsafeAtomic + let flags: UnsafePointer> // ring array // maps indexes between the actual ring and the submissionQueueEntries list, @@ -34,9 +34,9 @@ extension UnsafeMutableRawPointer { let array: UnsafeMutableBufferPointer } -struct CQRing { - let kernelHead: UnsafeAtomic - let kernelTail: UnsafeAtomic +struct CQRing: ~Copyable { + let kernelHead: UnsafePointer> + let kernelTail: UnsafePointer> // TODO: determine if this is actually used var userHead: UInt32 @@ -124,7 +124,7 @@ extension IORingBuffer { // XXX: This should be a non-copyable type (?) // demo only runs on Swift 5.8.1 -public final class IORing: @unchecked Sendable { +public struct IORing: @unchecked Sendable, ~Copyable { let ringFlags: UInt32 let ringDescriptor: Int32 @@ -187,20 +187,20 @@ public final class IORing: @unchecked Sendable { } submissionRing = SQRing( - kernelHead: UnsafeAtomic( - at: ringPtr.advanced(by: params.sq_off.head) - .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + kernelHead: UnsafePointer>( + ringPtr.advanced(by: params.sq_off.head) + .assumingMemoryBound(to: Atomic.self) ), - kernelTail: UnsafeAtomic( - at: ringPtr.advanced(by: params.sq_off.tail) - .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + kernelTail: UnsafePointer>( + ringPtr.advanced(by: params.sq_off.tail) + .assumingMemoryBound(to: Atomic.self) ), userTail: 0, // no requests yet ringMask: ringPtr.advanced(by: params.sq_off.ring_mask) .assumingMemoryBound(to: UInt32.self).pointee, - flags: UnsafeAtomic( - at: ringPtr.advanced(by: params.sq_off.flags) - .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + flags: UnsafePointer>( + ringPtr.advanced(by: params.sq_off.flags) + .assumingMemoryBound(to: Atomic.self) ), array: UnsafeMutableBufferPointer( start: ringPtr.advanced(by: params.sq_off.array) @@ -237,13 +237,13 @@ public final class IORing: @unchecked Sendable { ) completionRing = CQRing( - kernelHead: UnsafeAtomic( - at: ringPtr.advanced(by: params.cq_off.head) - .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + kernelHead: UnsafePointer>( + ringPtr.advanced(by: params.cq_off.head) + .assumingMemoryBound(to: Atomic.self) ), - kernelTail: UnsafeAtomic( - at: ringPtr.advanced(by: params.cq_off.tail) - .assumingMemoryBound(to: UInt32.AtomicRepresentation.self) + kernelTail: UnsafePointer>( + ringPtr.advanced(by: params.cq_off.tail) + .assumingMemoryBound(to: Atomic.self) ), userHead: 0, // no completions yet ringMask: ringPtr.advanced(by: params.cq_off.ring_mask) @@ -299,20 +299,20 @@ public final class IORing: @unchecked Sendable { } func _tryConsumeCompletion() -> IOCompletion? { - let tail = completionRing.kernelTail.load(ordering: .acquiring) - let head = completionRing.kernelHead.load(ordering: .relaxed) + let tail = completionRing.kernelTail.pointee.load(ordering: .acquiring) + let head = completionRing.kernelHead.pointee.load(ordering: .relaxed) if tail != head { // 32 byte copy - oh well let res = completionRing.cqes[Int(head & completionRing.ringMask)] - completionRing.kernelHead.store(head + 1, ordering: .relaxed) + completionRing.kernelHead.pointee.store(head + 1, ordering: .relaxed) return IOCompletion(rawValue: res) } return nil } - public func registerFiles(count: UInt32) { + public mutating func registerFiles(count: UInt32) { guard self.registeredFiles == nil else { fatalError() } let fileBuf = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) fileBuf.initialize(repeating: UInt32.max) @@ -334,7 +334,7 @@ public final class IORing: @unchecked Sendable { return self.registeredFiles?.getResource() } - public func registerBuffers(bufSize: UInt32, count: UInt32) { + public mutating func registerBuffers(bufSize: UInt32, count: UInt32) { let iovecs = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) let intBufSize = Int(bufSize) for i in 0.. UInt32 { - self.submissionRing.kernelTail.store( + self.submissionRing.kernelTail.pointee.store( self.submissionRing.userTail, ordering: .relaxed ) return self.submissionRing.userTail - - self.submissionRing.kernelHead.load(ordering: .relaxed) + self.submissionRing.kernelHead.pointee.load(ordering: .relaxed) } @inlinable @inline(__always) - public func writeRequest(_ request: __owned IORequest) -> Bool { + public mutating func writeRequest(_ request: __owned IORequest) -> Bool { self.submissionMutex.lock() defer { self.submissionMutex.unlock() } return _writeRequest(request.makeRawRequest()) } @inlinable @inline(__always) - internal func _writeRequest(_ request: __owned RawIORequest) -> Bool { + internal mutating func _writeRequest(_ request: __owned RawIORequest) -> Bool { let entry = _blockingGetSubmissionEntry() entry.pointee = request.rawValue return true } @inlinable @inline(__always) - internal func _blockingGetSubmissionEntry() -> UnsafeMutablePointer { + internal mutating func _blockingGetSubmissionEntry() -> UnsafeMutablePointer { while true { if let entry = _getSubmissionEntry() { return entry @@ -427,11 +427,11 @@ public final class IORing: @unchecked Sendable { } @usableFromInline @inline(__always) - internal func _getSubmissionEntry() -> UnsafeMutablePointer? { + internal mutating func _getSubmissionEntry() -> UnsafeMutablePointer? { let next = self.submissionRing.userTail + 1 // FEAT: smp load when SQPOLL in use (not in MVP) - let kernelHead = self.submissionRing.kernelHead.load(ordering: .relaxed) + let kernelHead = self.submissionRing.kernelHead.pointee.load(ordering: .relaxed) // FEAT: 128-bit event support (not in MVP) if (next - kernelHead <= self.submissionRing.array.count) { diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 78baa98..4604f50 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -12,7 +12,7 @@ final class IORingTests: XCTestCase { } func testNop() throws { - let ring = try IORing(queueDepth: 32) + var ring = try IORing(queueDepth: 32) ring.writeRequest(.nop) ring.submitRequests() let completion = ring.blockingConsumeCompletion() From 60299362ed85e53915891a562b60d621afc608df Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 24 Oct 2024 21:27:22 +0000 Subject: [PATCH 011/102] One more noncopyable struct --- Sources/System/IORing.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 0ac783a..656e168 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -79,7 +79,7 @@ internal class ResourceManager: @unchecked Sendable { } } -public class IOResource { +public struct IOResource: ~Copyable { typealias Resource = T @usableFromInline let resource: T @usableFromInline let index: Int From 10c070abd648bb66da947c77b5a5c645ef1d53fd Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 28 Oct 2024 20:00:07 +0000 Subject: [PATCH 012/102] WIP, more ~Copyable adoption --- Sources/System/IORequest.swift | 145 ++++--- Sources/System/IORing.swift | 368 +++++++++--------- Sources/System/Lock.swift | 37 -- Sources/System/ManagedIORing.swift | 25 +- .../AsyncFileDescriptorTests.swift | 2 +- 5 files changed, 295 insertions(+), 282 deletions(-) delete mode 100644 Sources/System/Lock.swift diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 9548b3f..2ecd3f4 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -1,9 +1,9 @@ import struct CSystem.io_uring_sqe -public enum IORequest { +public enum IORequest: ~Copyable { case nop // nothing here case openat( - atDirectory: FileDescriptor, + atDirectory: FileDescriptor, path: UnsafePointer, FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), @@ -22,71 +22,106 @@ public enum IORequest { ) case close(File) - public enum Buffer { + public enum Buffer: ~Copyable { case registered(IORingBuffer) case unregistered(UnsafeMutableRawBufferPointer) } - public enum File { + public enum File: ~Copyable { case registered(IORingFileSlot) case unregistered(FileDescriptor) } } +@inlinable @inline(__always) +internal func makeRawRequest_readWrite_registered( + file: consuming IORequest.File, + buffer: consuming IORingBuffer, + offset: UInt64, + request: consuming RawIORequest +) -> RawIORequest { + switch file { + case .registered(let regFile): + request.rawValue.fd = Int32(exactly: regFile.index)! + request.flags = .fixedFile + case .unregistered(let fd): + request.fileDescriptor = fd + } + request.buffer = buffer.unsafeBuffer + request.rawValue.buf_index = UInt16(exactly: buffer.index)! + request.offset = offset + return request +} + +@inlinable @inline(__always) +internal func makeRawRequest_readWrite_unregistered( + file: consuming IORequest.File, + buffer: UnsafeMutableRawBufferPointer, + offset: UInt64, + request: consuming RawIORequest +) -> RawIORequest { + switch file { + case .registered(let regFile): + request.rawValue.fd = Int32(exactly: regFile.index)! + request.flags = .fixedFile + case .unregistered(let fd): + request.fileDescriptor = fd + } + request.buffer = buffer + request.offset = offset + return request +} + extension IORequest { @inlinable @inline(__always) - public func makeRawRequest() -> RawIORequest { + public consuming func makeRawRequest() -> RawIORequest { var request = RawIORequest() - switch self { - case .nop: - request.operation = .nop - case .openat(let atDirectory, let path, let mode, let options, let permissions, let slot): - // TODO: use rawValue less - request.operation = .openAt - request.fileDescriptor = atDirectory - request.rawValue.addr = unsafeBitCast(path, to: UInt64.self) - request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) - request.rawValue.len = permissions?.rawValue ?? 0 - if let fileSlot = slot { - request.rawValue.file_index = UInt32(fileSlot.index + 1) - } - case .read(let file, let buffer, let offset), .write(let file, let buffer, let offset): - if case .read = self { - if case .registered = buffer { - request.operation = .readFixed - } else { - request.operation = .read - } - } else { - if case .registered = buffer { - request.operation = .writeFixed - } else { - request.operation = .write - } - } - switch file { - case .registered(let regFile): - request.rawValue.fd = Int32(exactly: regFile.index)! - request.flags = .fixedFile - case .unregistered(let fd): - request.fileDescriptor = fd - } - switch buffer { - case .registered(let regBuf): - request.buffer = regBuf.unsafeBuffer - request.rawValue.buf_index = UInt16(exactly: regBuf.index)! - case .unregistered(let buf): - request.buffer = buf - } - request.offset = offset - case .close(let file): - request.operation = .close - switch file { - case .registered(let regFile): - request.rawValue.file_index = UInt32(regFile.index + 1) - case .unregistered(let normalFile): - request.fileDescriptor = normalFile - } + switch consume self { + case .nop: + request.operation = .nop + case .openat(let atDirectory, let path, let mode, let options, let permissions, let slot): + // TODO: use rawValue less + request.operation = .openAt + request.fileDescriptor = atDirectory + request.rawValue.addr = unsafeBitCast(path, to: UInt64.self) + request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) + request.rawValue.len = permissions?.rawValue ?? 0 + if let fileSlot = slot { + request.rawValue.file_index = UInt32(fileSlot.index + 1) + } + case .write(let file, let buffer, let offset): + switch consume buffer { + case .registered(let buffer): + request.operation = .writeFixed + return makeRawRequest_readWrite_registered( + file: file, buffer: buffer, offset: offset, request: request) + + case .unregistered(let buffer): + request.operation = .write + return makeRawRequest_readWrite_unregistered( + file: file, buffer: buffer, offset: offset, request: request) + } + case .read(let file, let buffer, let offset): + + switch consume buffer { + case .registered(let buffer): + request.operation = .readFixed + return makeRawRequest_readWrite_registered( + file: file, buffer: buffer, offset: offset, request: request) + + case .unregistered(let buffer): + request.operation = .read + return makeRawRequest_readWrite_unregistered( + file: file, buffer: buffer, offset: offset, request: request) + } + case .close(let file): + request.operation = .close + switch file { + case .registered(let regFile): + request.rawValue.file_index = UInt32(regFile.index + 1) + case .unregistered(let normalFile): + request.fileDescriptor = normalFile + } } return request } diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 656e168..3e24408 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -1,8 +1,8 @@ @_implementationOnly import CSystem -import struct CSystem.io_uring_sqe +import Glibc // needed for mmap +import Synchronization -@_implementationOnly import Synchronization -import Glibc // needed for mmap +import struct CSystem.io_uring_sqe // XXX: this *really* shouldn't be here. oh well. extension UnsafeMutableRawPointer { @@ -26,7 +26,7 @@ extension UnsafeMutableRawPointer { // currently used by the kernel only in SQPOLL mode to indicate // when the polling thread needs to be woken up let flags: UnsafePointer> - + // ring array // maps indexes between the actual ring and the submissionQueueEntries list, // allowing the latter to be used as a kind of freelist with enough work? @@ -48,34 +48,40 @@ struct CQRing: ~Copyable { internal class ResourceManager: @unchecked Sendable { typealias Resource = T - let resourceList: UnsafeMutableBufferPointer - var freeList: [Int] - let mutex: Mutex + + struct Resources { + let resourceList: UnsafeMutableBufferPointer + var freeList: [Int] + } + + let mutex: Mutex init(_ res: UnsafeMutableBufferPointer) { - self.resourceList = res - self.freeList = [Int](resourceList.indices) - self.mutex = Mutex() + mutex = Mutex( + Resources( + resourceList: res, + freeList: [Int](res.indices) + )) } func getResource() -> IOResource? { - self.mutex.lock() - defer { self.mutex.unlock() } - if let index = freeList.popLast() { - return IOResource( - rescource: resourceList[index], - index: index, - manager: self - ) - } else { - return nil + mutex.withLock { resources in + if let index = resources.freeList.popLast() { + return IOResource( + resource: resources.resourceList[index], + index: index, + manager: self + ) + } else { + return nil + } } } func releaseResource(index: Int) { - self.mutex.lock() - defer { self.mutex.unlock() } - self.freeList.append(index) + mutex.withLock { resources in + resources.freeList.append(index) + } } } @@ -86,11 +92,11 @@ public struct IOResource: ~Copyable { let manager: ResourceManager internal init( - rescource: T, + resource: T, index: Int, manager: ResourceManager ) { - self.resource = rescource + self.resource = resource self.index = index self.manager = manager } @@ -114,13 +120,89 @@ extension IORingFileSlot { } extension IORingBuffer { public var unsafeBuffer: UnsafeMutableRawBufferPointer { - get { - return .init(start: resource.iov_base, count: resource.iov_len) + return .init(start: resource.iov_base, count: resource.iov_len) + } +} + +@inlinable @inline(__always) +internal func _writeRequest(_ request: __owned RawIORequest, ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer) + -> Bool +{ + let entry = _blockingGetSubmissionEntry(ring: &ring, submissionQueueEntries: submissionQueueEntries) + entry.pointee = request.rawValue + return true +} + +@inlinable @inline(__always) +internal func _blockingGetSubmissionEntry(ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer) -> UnsafeMutablePointer< + io_uring_sqe +> { + while true { + if let entry = _getSubmissionEntry(ring: &ring, submissionQueueEntries: submissionQueueEntries) { + return entry + } + // TODO: actually block here instead of spinning + } + +} + +internal func _submitRequests(ring: inout SQRing, ringDescriptor: Int32) { + let flushedEvents = _flushQueue(ring: &ring) + + // Ring always needs enter right now; + // TODO: support SQPOLL here + while true { + let ret = io_uring_enter(ringDescriptor, flushedEvents, 0, 0, nil) + // error handling: + // EAGAIN / EINTR (try again), + // EBADF / EBADFD / EOPNOTSUPP / ENXIO + // (failure in ring lifetime management, fatal), + // EINVAL (bad constant flag?, fatal), + // EFAULT (bad address for argument from library, fatal) + if ret == -EAGAIN || ret == -EINTR { + continue + } else if ret < 0 { + fatalError( + "fatal error in submitting requests: " + Errno(rawValue: -ret).debugDescription + ) + } else { + break } } } +internal func _flushQueue(ring: inout SQRing) -> UInt32 { + ring.kernelTail.pointee.store( + ring.userTail, ordering: .relaxed + ) + return ring.userTail - ring.kernelHead.pointee.load(ordering: .relaxed) +} +@usableFromInline @inline(__always) +internal func _getSubmissionEntry(ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer) -> UnsafeMutablePointer< + io_uring_sqe +>? { + let next = ring.userTail + 1 + + // FEAT: smp load when SQPOLL in use (not in MVP) + let kernelHead = ring.kernelHead.pointee.load(ordering: .relaxed) + + // FEAT: 128-bit event support (not in MVP) + if next - kernelHead <= ring.array.count { + // let sqe = &sq->sqes[(sq->sqe_tail & sq->ring_mask) << shift]; + let sqeIndex = Int( + ring.userTail & ring.ringMask + ) + + let sqe = submissionQueueEntries + .baseAddress.unsafelyUnwrapped + .advanced(by: sqeIndex) + + ring.userTail = next + return sqe + } + return nil +} // XXX: This should be a non-copyable type (?) // demo only runs on Swift 5.8.1 @@ -128,15 +210,13 @@ public struct IORing: @unchecked Sendable, ~Copyable { let ringFlags: UInt32 let ringDescriptor: Int32 - @usableFromInline var submissionRing: SQRing - @usableFromInline var submissionMutex: Mutex + @usableFromInline let submissionMutex: Mutex // FEAT: set this eventually let submissionPolling: Bool = false - var completionRing: CQRing - var completionMutex: Mutex + let completionMutex: Mutex - let submissionQueueEntries: UnsafeMutableBufferPointer + @usableFromInline let submissionQueueEntries: UnsafeMutableBufferPointer // kept around for unmap / cleanup let ringSize: Int @@ -149,28 +229,31 @@ public struct IORing: @unchecked Sendable, ~Copyable { var params = io_uring_params() ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { - return io_uring_setup(queueDepth, $0); + return io_uring_setup(queueDepth, $0) } - if (params.features & IORING_FEAT_SINGLE_MMAP == 0 - || params.features & IORING_FEAT_NODROP == 0) { + if params.features & IORING_FEAT_SINGLE_MMAP == 0 + || params.features & IORING_FEAT_NODROP == 0 + { close(ringDescriptor) // TODO: error handling throw IORingError.missingRequiredFeatures } - - if (ringDescriptor < 0) { + + if ringDescriptor < 0 { // TODO: error handling } - let submitRingSize = params.sq_off.array + let submitRingSize = + params.sq_off.array + params.sq_entries * UInt32(MemoryLayout.size) - - let completionRingSize = params.cq_off.cqes + + let completionRingSize = + params.cq_off.cqes + params.cq_entries * UInt32(MemoryLayout.size) ringSize = Int(max(submitRingSize, completionRingSize)) - + ringPtr = mmap( /* addr: */ nil, /* len: */ ringSize, @@ -178,35 +261,36 @@ public struct IORing: @unchecked Sendable, ~Copyable { /* flags: */ MAP_SHARED | MAP_POPULATE, /* fd: */ ringDescriptor, /* offset: */ __off_t(IORING_OFF_SQ_RING) - ); + ) - if (ringPtr == MAP_FAILED) { - perror("mmap"); + if ringPtr == MAP_FAILED { + perror("mmap") // TODO: error handling fatalError("mmap failed in ring setup") } - submissionRing = SQRing( + let submissionRing = SQRing( kernelHead: UnsafePointer>( ringPtr.advanced(by: params.sq_off.head) - .assumingMemoryBound(to: Atomic.self) + .assumingMemoryBound(to: Atomic.self) ), kernelTail: UnsafePointer>( ringPtr.advanced(by: params.sq_off.tail) - .assumingMemoryBound(to: Atomic.self) + .assumingMemoryBound(to: Atomic.self) ), - userTail: 0, // no requests yet + userTail: 0, // no requests yet ringMask: ringPtr.advanced(by: params.sq_off.ring_mask) .assumingMemoryBound(to: UInt32.self).pointee, flags: UnsafePointer>( ringPtr.advanced(by: params.sq_off.flags) - .assumingMemoryBound(to: Atomic.self) + .assumingMemoryBound(to: Atomic.self) ), array: UnsafeMutableBufferPointer( start: ringPtr.advanced(by: params.sq_off.array) .assumingMemoryBound(to: UInt32.self), - count: Int(ringPtr.advanced(by: params.sq_off.ring_entries) - .assumingMemoryBound(to: UInt32.self).pointee) + count: Int( + ringPtr.advanced(by: params.sq_off.ring_entries) + .assumingMemoryBound(to: UInt32.self).pointee) ) ) @@ -223,10 +307,10 @@ public struct IORing: @unchecked Sendable, ~Copyable { /* flags: */ MAP_SHARED | MAP_POPULATE, /* fd: */ ringDescriptor, /* offset: */ __off_t(IORING_OFF_SQES) - ); + ) - if (sqes == MAP_FAILED) { - perror("mmap"); + if sqes == MAP_FAILED { + perror("mmap") // TODO: error handling fatalError("sqe mmap failed in ring setup") } @@ -236,76 +320,77 @@ public struct IORing: @unchecked Sendable, ~Copyable { count: Int(params.sq_entries) ) - completionRing = CQRing( + let completionRing = CQRing( kernelHead: UnsafePointer>( ringPtr.advanced(by: params.cq_off.head) - .assumingMemoryBound(to: Atomic.self) + .assumingMemoryBound(to: Atomic.self) ), kernelTail: UnsafePointer>( ringPtr.advanced(by: params.cq_off.tail) - .assumingMemoryBound(to: Atomic.self) + .assumingMemoryBound(to: Atomic.self) ), - userHead: 0, // no completions yet + userHead: 0, // no completions yet ringMask: ringPtr.advanced(by: params.cq_off.ring_mask) .assumingMemoryBound(to: UInt32.self).pointee, cqes: UnsafeBufferPointer( start: ringPtr.advanced(by: params.cq_off.cqes) .assumingMemoryBound(to: io_uring_cqe.self), - count: Int(ringPtr.advanced(by: params.cq_off.ring_entries) - .assumingMemoryBound(to: UInt32.self).pointee) + count: Int( + ringPtr.advanced(by: params.cq_off.ring_entries) + .assumingMemoryBound(to: UInt32.self).pointee) ) ) - self.submissionMutex = Mutex() - self.completionMutex = Mutex() + self.submissionMutex = Mutex(submissionRing) + self.completionMutex = Mutex(completionRing) self.ringFlags = params.flags } public func blockingConsumeCompletion() -> IOCompletion { - self.completionMutex.lock() - defer { self.completionMutex.unlock() } - - if let completion = _tryConsumeCompletion() { - return completion - } else { - while true { - let res = io_uring_enter(ringDescriptor, 0, 1, IORING_ENTER_GETEVENTS, nil) - // error handling: - // EAGAIN / EINTR (try again), - // EBADF / EBADFD / EOPNOTSUPP / ENXIO - // (failure in ring lifetime management, fatal), - // EINVAL (bad constant flag?, fatal), - // EFAULT (bad address for argument from library, fatal) - // EBUSY (not enough space for events; implies events filled - // by kernel between kernelTail load and now) - if res >= 0 || res == -EBUSY { - break - } else if res == -EAGAIN || res == -EINTR { - continue + completionMutex.withLock { ring in + if let completion = _tryConsumeCompletion(ring: &ring) { + return completion + } else { + while true { + let res = io_uring_enter(ringDescriptor, 0, 1, IORING_ENTER_GETEVENTS, nil) + // error handling: + // EAGAIN / EINTR (try again), + // EBADF / EBADFD / EOPNOTSUPP / ENXIO + // (failure in ring lifetime management, fatal), + // EINVAL (bad constant flag?, fatal), + // EFAULT (bad address for argument from library, fatal) + // EBUSY (not enough space for events; implies events filled + // by kernel between kernelTail load and now) + if res >= 0 || res == -EBUSY { + break + } else if res == -EAGAIN || res == -EINTR { + continue + } + fatalError( + "fatal error in receiving requests: " + + Errno(rawValue: -res).debugDescription + ) } - fatalError("fatal error in receiving requests: " + - Errno(rawValue: -res).debugDescription - ) + return _tryConsumeCompletion(ring: &ring).unsafelyUnwrapped } - return _tryConsumeCompletion().unsafelyUnwrapped } } public func tryConsumeCompletion() -> IOCompletion? { - self.completionMutex.lock() - defer { self.completionMutex.unlock() } - return _tryConsumeCompletion() + completionMutex.withLock { ring in + return _tryConsumeCompletion(ring: &ring) + } } - func _tryConsumeCompletion() -> IOCompletion? { - let tail = completionRing.kernelTail.pointee.load(ordering: .acquiring) - let head = completionRing.kernelHead.pointee.load(ordering: .relaxed) - + func _tryConsumeCompletion(ring: inout CQRing) -> IOCompletion? { + let tail = ring.kernelTail.pointee.load(ordering: .acquiring) + let head = ring.kernelHead.pointee.load(ordering: .relaxed) + if tail != head { // 32 byte copy - oh well - let res = completionRing.cqes[Int(head & completionRing.ringMask)] - completionRing.kernelHead.pointee.store(head + 1, ordering: .relaxed) + let res = ring.cqes[Int(head & ring.ringMask)] + ring.kernelHead.pointee.store(head + 1, ordering: .relaxed) return IOCompletion(rawValue: res) } @@ -340,7 +425,8 @@ public struct IORing: @unchecked Sendable, ~Copyable { for i in 0.. UInt32 { - self.submissionRing.kernelTail.pointee.store( - self.submissionRing.userTail, ordering: .relaxed - ) - return self.submissionRing.userTail - - self.submissionRing.kernelHead.pointee.load(ordering: .relaxed) - } - - @inlinable @inline(__always) public mutating func writeRequest(_ request: __owned IORequest) -> Bool { - self.submissionMutex.lock() - defer { self.submissionMutex.unlock() } - return _writeRequest(request.makeRawRequest()) - } - - @inlinable @inline(__always) - internal mutating func _writeRequest(_ request: __owned RawIORequest) -> Bool { - let entry = _blockingGetSubmissionEntry() - entry.pointee = request.rawValue - return true - } - - @inlinable @inline(__always) - internal mutating func _blockingGetSubmissionEntry() -> UnsafeMutablePointer { - while true { - if let entry = _getSubmissionEntry() { - return entry - } - // TODO: actually block here instead of spinning + let raw = request.makeRawRequest() + return submissionMutex.withLock { ring in + return _writeRequest(raw, ring: &ring, submissionQueueEntries: submissionQueueEntries) } - - } - - @usableFromInline @inline(__always) - internal mutating func _getSubmissionEntry() -> UnsafeMutablePointer? { - let next = self.submissionRing.userTail + 1 - - // FEAT: smp load when SQPOLL in use (not in MVP) - let kernelHead = self.submissionRing.kernelHead.pointee.load(ordering: .relaxed) - - // FEAT: 128-bit event support (not in MVP) - if (next - kernelHead <= self.submissionRing.array.count) { - // let sqe = &sq->sqes[(sq->sqe_tail & sq->ring_mask) << shift]; - let sqeIndex = Int( - self.submissionRing.userTail & self.submissionRing.ringMask - ) - - let sqe = self.submissionQueueEntries - .baseAddress.unsafelyUnwrapped - .advanced(by: sqeIndex) - - self.submissionRing.userTail = next; - return sqe - } - return nil } deinit { - munmap(ringPtr, ringSize); + munmap(ringPtr, ringSize) munmap( UnsafeMutableRawPointer(submissionQueueEntries.baseAddress!), submissionQueueEntries.count * MemoryLayout.size ) close(ringDescriptor) } -}; - +} diff --git a/Sources/System/Lock.swift b/Sources/System/Lock.swift deleted file mode 100644 index fd20c64..0000000 --- a/Sources/System/Lock.swift +++ /dev/null @@ -1,37 +0,0 @@ -// TODO: write against kernel APIs directly? -import Glibc - -@usableFromInline final class Mutex { - @usableFromInline let mutex: UnsafeMutablePointer - - @inlinable init() { - self.mutex = UnsafeMutablePointer.allocate(capacity: 1) - self.mutex.initialize(to: pthread_mutex_t()) - pthread_mutex_init(self.mutex, nil) - } - - @inlinable deinit { - defer { mutex.deallocate() } - guard pthread_mutex_destroy(mutex) == 0 else { - preconditionFailure("unable to destroy mutex") - } - } - - // XXX: this is because we need to lock the mutex in the context of a submit() function - // and unlock *before* the UnsafeContinuation returns. - // Code looks like: { - // // prepare request - // io_uring_get_sqe() - // io_uring_prep_foo(...) - // return await withUnsafeContinuation { - // sqe->user_data = ...; io_uring_submit(); unlock(); - // } - // } - @inlinable @inline(__always) public func lock() { - pthread_mutex_lock(mutex) - } - - @inlinable @inline(__always) public func unlock() { - pthread_mutex_unlock(mutex) - } -} diff --git a/Sources/System/ManagedIORing.swift b/Sources/System/ManagedIORing.swift index 7f5bec2..88fb72e 100644 --- a/Sources/System/ManagedIORing.swift +++ b/Sources/System/ManagedIORing.swift @@ -5,15 +5,16 @@ final public class ManagedIORing: @unchecked Sendable { self.internalRing = try IORing(queueDepth: queueDepth) self.internalRing.registerBuffers(bufSize: 655336, count: 4) self.internalRing.registerFiles(count: 32) - self.startWaiter() + self.startWaiter() } private func startWaiter() { Task.detached { - while (!Task.isCancelled) { + while !Task.isCancelled { let cqe = self.internalRing.blockingConsumeCompletion() - let cont = unsafeBitCast(cqe.userData, to: UnsafeContinuation.self) + let cont = unsafeBitCast( + cqe.userData, to: UnsafeContinuation.self) cont.resume(returning: cqe) } } @@ -21,14 +22,18 @@ final public class ManagedIORing: @unchecked Sendable { @_unsafeInheritExecutor public func submitAndWait(_ request: __owned IORequest) async -> IOCompletion { - self.internalRing.submissionMutex.lock() + var consumeOnceWorkaround: IORequest? = request return await withUnsafeContinuation { cont in - let entry = internalRing._blockingGetSubmissionEntry() - entry.pointee = request.makeRawRequest().rawValue - entry.pointee.user_data = unsafeBitCast(cont, to: UInt64.self) - self.internalRing._submitRequests() - self.internalRing.submissionMutex.unlock() + return internalRing.submissionMutex.withLock { ring in + let request = consumeOnceWorkaround.take()! + let entry = _blockingGetSubmissionEntry( + ring: &ring, submissionQueueEntries: internalRing.submissionQueueEntries) + entry.pointee = request.makeRawRequest().rawValue + entry.pointee.user_data = unsafeBitCast(cont, to: UInt64.self) + _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) + } } + } internal func getFileSlot() -> IORingFileSlot? { @@ -39,4 +44,4 @@ final public class ManagedIORing: @unchecked Sendable { self.internalRing.getBuffer() } -} \ No newline at end of file +} diff --git a/Tests/SystemTests/AsyncFileDescriptorTests.swift b/Tests/SystemTests/AsyncFileDescriptorTests.swift index 0f1c103..1baba96 100644 --- a/Tests/SystemTests/AsyncFileDescriptorTests.swift +++ b/Tests/SystemTests/AsyncFileDescriptorTests.swift @@ -23,7 +23,7 @@ final class AsyncFileDescriptorTests: XCTestCase { .readOnly, onRing: ring ) - await try file.close() + try await file.close() } func testDevNullEmpty() async throws { From 32966f975d8d4285059c29eaccd1cee46c56b84f Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 28 Oct 2024 23:43:59 +0000 Subject: [PATCH 013/102] It builds again! With some horrible hacks --- Sources/System/AsyncFileDescriptor.swift | 117 +++++++++++------- Sources/System/IOCompletion.swift | 1 + Sources/System/IORequest.swift | 58 ++++----- Sources/System/IORing.swift | 22 ++-- Sources/System/ManagedIORing.swift | 4 +- Sources/System/RawIORequest.swift | 2 +- .../AsyncFileDescriptorTests.swift | 2 +- Tests/SystemTests/IORequestTests.swift | 4 +- 8 files changed, 124 insertions(+), 86 deletions(-) diff --git a/Sources/System/AsyncFileDescriptor.swift b/Sources/System/AsyncFileDescriptor.swift index 504aec9..a00f41d 100644 --- a/Sources/System/AsyncFileDescriptor.swift +++ b/Sources/System/AsyncFileDescriptor.swift @@ -1,13 +1,12 @@ @_implementationOnly import CSystem - -public final class AsyncFileDescriptor { +public struct AsyncFileDescriptor: ~Copyable { @usableFromInline var open: Bool = true @usableFromInline let fileSlot: IORingFileSlot @usableFromInline let ring: ManagedIORing - + public static func openat( - atDirectory: FileDescriptor = FileDescriptor(rawValue: -100), + atDirectory: FileDescriptor = FileDescriptor(rawValue: -100), path: FilePath, _ mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), @@ -19,35 +18,37 @@ public final class AsyncFileDescriptor { throw IORingError.missingRequiredFeatures } let cstr = path.withCString { - return $0 // bad + return $0 // bad } - let res = await ring.submitAndWait(.openat( - atDirectory: atDirectory, - path: cstr, - mode, - options: options, - permissions: permissions, - intoSlot: fileSlot - )) + let res = await ring.submitAndWait( + .openat( + atDirectory: atDirectory, + path: cstr, + mode, + options: options, + permissions: permissions, + intoSlot: fileSlot.borrow() + )) if res.result < 0 { throw Errno(rawValue: -res.result) } - + return AsyncFileDescriptor( fileSlot, ring: ring ) } - internal init(_ fileSlot: IORingFileSlot, ring: ManagedIORing) { - self.fileSlot = fileSlot + internal init(_ fileSlot: consuming IORingFileSlot, ring: ManagedIORing) { + self.fileSlot = consume fileSlot self.ring = ring } @inlinable @inline(__always) @_unsafeInheritExecutor - public func close() async throws { - let res = await ring.submitAndWait(.close( - .registered(self.fileSlot) - )) + public consuming func close() async throws { + let res = await ring.submitAndWait( + .close( + .registered(self.fileSlot) + )) if res.result < 0 { throw Errno(rawValue: -res.result) } @@ -56,14 +57,16 @@ public final class AsyncFileDescriptor { @inlinable @inline(__always) @_unsafeInheritExecutor public func read( - into buffer: IORequest.Buffer, + into buffer: inout UnsafeMutableRawBufferPointer, atAbsoluteOffset offset: UInt64 = UInt64.max ) async throws -> UInt32 { - let res = await ring.submitAndWait(.read( - file: .registered(self.fileSlot), - buffer: buffer, - offset: offset - )) + let file = fileSlot.borrow() + let res = await ring.submitAndWait( + .readUnregistered( + file: .registered(file), + buffer: buffer, + offset: offset + )) if res.result < 0 { throw Errno(rawValue: -res.result) } else { @@ -71,23 +74,54 @@ public final class AsyncFileDescriptor { } } - deinit { - if (self.open) { - // TODO: close or error? TBD + @inlinable @inline(__always) @_unsafeInheritExecutor + public func read( + into buffer: borrowing IORingBuffer, //TODO: should be inout? + atAbsoluteOffset offset: UInt64 = UInt64.max + ) async throws -> UInt32 { + let res = await ring.submitAndWait( + .read( + file: .registered(self.fileSlot.borrow()), + buffer: buffer.borrow(), + offset: offset + )) + if res.result < 0 { + throw Errno(rawValue: -res.result) + } else { + return UInt32(bitPattern: res.result) } } + + //TODO: temporary workaround until AsyncSequence supports ~Copyable + public consuming func toBytes() -> AsyncFileDescriptorSequence { + AsyncFileDescriptorSequence(self) + } + + //TODO: can we do the linear types thing and error if they don't consume it manually? + // deinit { + // if self.open { + // TODO: close or error? TBD + // } + // } } -extension AsyncFileDescriptor: AsyncSequence { +public class AsyncFileDescriptorSequence: AsyncSequence { + var descriptor: AsyncFileDescriptor? + public func makeAsyncIterator() -> FileIterator { - return .init(self) + return .init(descriptor.take()!) + } + + internal init(_ descriptor: consuming AsyncFileDescriptor) { + self.descriptor = consume descriptor } public typealias AsyncIterator = FileIterator public typealias Element = UInt8 } -public struct FileIterator: AsyncIteratorProtocol { +//TODO: only a class due to ~Copyable limitations +public class FileIterator: AsyncIteratorProtocol { @usableFromInline let file: AsyncFileDescriptor @usableFromInline var buffer: IORingBuffer @usableFromInline var done: Bool @@ -95,28 +129,27 @@ public struct FileIterator: AsyncIteratorProtocol { @usableFromInline internal var currentByte: UnsafeRawPointer? @usableFromInline internal var lastByte: UnsafeRawPointer? - init(_ file: AsyncFileDescriptor) { - self.file = file + init(_ file: consuming AsyncFileDescriptor) { self.buffer = file.ring.getBuffer()! + self.file = file self.done = false } @inlinable @inline(__always) - public mutating func nextBuffer() async throws { - let buffer = self.buffer - - let bytesRead = try await file.read(into: .registered(buffer)) + public func nextBuffer() async throws { + let bytesRead = Int(try await file.read(into: buffer)) if _fastPath(bytesRead != 0) { - let bufPointer = buffer.unsafeBuffer.baseAddress.unsafelyUnwrapped + let unsafeBuffer = buffer.unsafeBuffer + let bufPointer = unsafeBuffer.baseAddress.unsafelyUnwrapped self.currentByte = UnsafeRawPointer(bufPointer) - self.lastByte = UnsafeRawPointer(bufPointer.advanced(by: Int(bytesRead))) + self.lastByte = UnsafeRawPointer(bufPointer.advanced(by: bytesRead)) } else { - self.done = true + done = true } } @inlinable @inline(__always) @_unsafeInheritExecutor - public mutating func next() async throws -> UInt8? { + public func next() async throws -> UInt8? { if _fastPath(currentByte != lastByte) { // SAFETY: both pointers should be non-nil if they're not equal let byte = currentByte.unsafelyUnwrapped.load(as: UInt8.self) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index 5e22632..8bf173c 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -1,5 +1,6 @@ @_implementationOnly import CSystem +//TODO: should be ~Copyable, but requires UnsafeContinuation add ~Copyable support public struct IOCompletion { let rawValue: io_uring_cqe } diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 2ecd3f4..2a47c62 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -1,7 +1,7 @@ import struct CSystem.io_uring_sqe public enum IORequest: ~Copyable { - case nop // nothing here + case nop // nothing here case openat( atDirectory: FileDescriptor, path: UnsafePointer, @@ -12,21 +12,26 @@ public enum IORequest: ~Copyable { ) case read( file: File, - buffer: Buffer, + buffer: IORingBuffer, + offset: UInt64 = 0 + ) + case readUnregistered( + file: File, + buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0 ) case write( file: File, - buffer: Buffer, + buffer: IORingBuffer, + offset: UInt64 = 0 + ) + case writeUnregistered( + file: File, + buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0 ) case close(File) - public enum Buffer: ~Copyable { - case registered(IORingBuffer) - case unregistered(UnsafeMutableRawBufferPointer) - } - public enum File: ~Copyable { case registered(IORingFileSlot) case unregistered(FileDescriptor) @@ -90,30 +95,21 @@ extension IORequest { request.rawValue.file_index = UInt32(fileSlot.index + 1) } case .write(let file, let buffer, let offset): - switch consume buffer { - case .registered(let buffer): - request.operation = .writeFixed - return makeRawRequest_readWrite_registered( - file: file, buffer: buffer, offset: offset, request: request) - - case .unregistered(let buffer): - request.operation = .write - return makeRawRequest_readWrite_unregistered( - file: file, buffer: buffer, offset: offset, request: request) - } + request.operation = .writeFixed + return makeRawRequest_readWrite_registered( + file: file, buffer: buffer, offset: offset, request: request) + case .writeUnregistered(let file, let buffer, let offset): + request.operation = .write + return makeRawRequest_readWrite_unregistered( + file: file, buffer: buffer, offset: offset, request: request) case .read(let file, let buffer, let offset): - - switch consume buffer { - case .registered(let buffer): - request.operation = .readFixed - return makeRawRequest_readWrite_registered( - file: file, buffer: buffer, offset: offset, request: request) - - case .unregistered(let buffer): - request.operation = .read - return makeRawRequest_readWrite_unregistered( - file: file, buffer: buffer, offset: offset, request: request) - } + request.operation = .readFixed + return makeRawRequest_readWrite_registered( + file: file, buffer: buffer, offset: offset, request: request) + case .readUnregistered(let file, let buffer, let offset): + request.operation = .read + return makeRawRequest_readWrite_unregistered( + file: file, buffer: buffer, offset: offset, request: request) case .close(let file): request.operation = .close switch file { diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 3e24408..2f18cb5 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -51,7 +51,7 @@ internal class ResourceManager: @unchecked Sendable { struct Resources { let resourceList: UnsafeMutableBufferPointer - var freeList: [Int] + var freeList: [Int] //TODO: bitvector? } let mutex: Mutex @@ -90,23 +90,33 @@ public struct IOResource: ~Copyable { @usableFromInline let resource: T @usableFromInline let index: Int let manager: ResourceManager + let isBorrow: Bool //TODO: this is a workaround for lifetime issues and should be removed internal init( resource: T, index: Int, - manager: ResourceManager + manager: ResourceManager, + isBorrow: Bool = false ) { self.resource = resource self.index = index self.manager = manager + self.isBorrow = isBorrow } func withResource() { } + //TODO: this is a workaround for lifetime issues and should be removed + @usableFromInline func borrow() -> IOResource { + IOResource(resource: resource, index: index, manager: manager, isBorrow: true) + } + deinit { - self.manager.releaseResource(index: self.index) + if !isBorrow { + manager.releaseResource(index: self.index) + } } } @@ -204,8 +214,6 @@ internal func _getSubmissionEntry(ring: inout SQRing, submissionQueueEntries: Un return nil } -// XXX: This should be a non-copyable type (?) -// demo only runs on Swift 5.8.1 public struct IORing: @unchecked Sendable, ~Copyable { let ringFlags: UInt32 let ringDescriptor: Int32 @@ -455,9 +463,9 @@ public struct IORing: @unchecked Sendable, ~Copyable { @inlinable @inline(__always) public mutating func writeRequest(_ request: __owned IORequest) -> Bool { - let raw = request.makeRawRequest() + var raw: RawIORequest? = request.makeRawRequest() return submissionMutex.withLock { ring in - return _writeRequest(raw, ring: &ring, submissionQueueEntries: submissionQueueEntries) + return _writeRequest(raw.take()!, ring: &ring, submissionQueueEntries: submissionQueueEntries) } } diff --git a/Sources/System/ManagedIORing.swift b/Sources/System/ManagedIORing.swift index 88fb72e..73ea231 100644 --- a/Sources/System/ManagedIORing.swift +++ b/Sources/System/ManagedIORing.swift @@ -37,11 +37,11 @@ final public class ManagedIORing: @unchecked Sendable { } internal func getFileSlot() -> IORingFileSlot? { - self.internalRing.getFile() + internalRing.getFile() } internal func getBuffer() -> IORingBuffer? { - self.internalRing.getBuffer() + internalRing.getBuffer() } } diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 520cb85..52407b0 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -2,7 +2,7 @@ @_implementationOnly import CSystem import struct CSystem.io_uring_sqe -public struct RawIORequest { +public struct RawIORequest: ~Copyable { @usableFromInline var rawValue: io_uring_sqe public init() { diff --git a/Tests/SystemTests/AsyncFileDescriptorTests.swift b/Tests/SystemTests/AsyncFileDescriptorTests.swift index 1baba96..7de2272 100644 --- a/Tests/SystemTests/AsyncFileDescriptorTests.swift +++ b/Tests/SystemTests/AsyncFileDescriptorTests.swift @@ -33,7 +33,7 @@ final class AsyncFileDescriptorTests: XCTestCase { .readOnly, onRing: ring ) - for try await _ in file { + for try await _ in file.toBytes() { XCTFail("/dev/null should be empty") } } diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index a44a607..a1e1453 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -6,7 +6,7 @@ import XCTest import System #endif -func requestBytes(_ request: RawIORequest) -> [UInt8] { +func requestBytes(_ request: consuming RawIORequest) -> [UInt8] { return withUnsafePointer(to: request) { let requestBuf = UnsafeBufferPointer(start: $0, count: 1) let rawBytes = UnsafeRawBufferPointer(requestBuf) @@ -40,7 +40,7 @@ final class IORequestTests: XCTestCase { .readOnly, options: [], permissions: nil, - intoSlot: fileSlot + intoSlot: fileSlot.borrow() ) let expectedRequest: [UInt8] = { From 822e4814d18de785c06fe4edbe31f750c3898f1b Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 28 Oct 2024 23:49:37 +0000 Subject: [PATCH 014/102] Adopt isolation parameters --- Sources/System/AsyncFileDescriptor.swift | 16 +++++++++------- Sources/System/ManagedIORing.swift | 3 +-- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Sources/System/AsyncFileDescriptor.swift b/Sources/System/AsyncFileDescriptor.swift index a00f41d..68d9e33 100644 --- a/Sources/System/AsyncFileDescriptor.swift +++ b/Sources/System/AsyncFileDescriptor.swift @@ -43,8 +43,8 @@ public struct AsyncFileDescriptor: ~Copyable { self.ring = ring } - @inlinable @inline(__always) @_unsafeInheritExecutor - public consuming func close() async throws { + @inlinable @inline(__always) + public consuming func close(isolation actor: isolated (any Actor)? = #isolation) async throws { let res = await ring.submitAndWait( .close( .registered(self.fileSlot) @@ -55,10 +55,11 @@ public struct AsyncFileDescriptor: ~Copyable { self.open = false } - @inlinable @inline(__always) @_unsafeInheritExecutor + @inlinable @inline(__always) public func read( into buffer: inout UnsafeMutableRawBufferPointer, - atAbsoluteOffset offset: UInt64 = UInt64.max + atAbsoluteOffset offset: UInt64 = UInt64.max, + isolation actor: isolated (any Actor)? = #isolation ) async throws -> UInt32 { let file = fileSlot.borrow() let res = await ring.submitAndWait( @@ -74,10 +75,11 @@ public struct AsyncFileDescriptor: ~Copyable { } } - @inlinable @inline(__always) @_unsafeInheritExecutor + @inlinable @inline(__always) public func read( into buffer: borrowing IORingBuffer, //TODO: should be inout? - atAbsoluteOffset offset: UInt64 = UInt64.max + atAbsoluteOffset offset: UInt64 = UInt64.max, + isolation actor: isolated (any Actor)? = #isolation ) async throws -> UInt32 { let res = await ring.submitAndWait( .read( @@ -148,7 +150,7 @@ public class FileIterator: AsyncIteratorProtocol { } } - @inlinable @inline(__always) @_unsafeInheritExecutor + @inlinable @inline(__always) public func next() async throws -> UInt8? { if _fastPath(currentByte != lastByte) { // SAFETY: both pointers should be non-nil if they're not equal diff --git a/Sources/System/ManagedIORing.swift b/Sources/System/ManagedIORing.swift index 73ea231..30ea5ed 100644 --- a/Sources/System/ManagedIORing.swift +++ b/Sources/System/ManagedIORing.swift @@ -20,8 +20,7 @@ final public class ManagedIORing: @unchecked Sendable { } } - @_unsafeInheritExecutor - public func submitAndWait(_ request: __owned IORequest) async -> IOCompletion { + public func submitAndWait(_ request: __owned IORequest, isolation actor: isolated (any Actor)? = #isolation) async -> IOCompletion { var consumeOnceWorkaround: IORequest? = request return await withUnsafeContinuation { cont in return internalRing.submissionMutex.withLock { ring in From a9f92a6e316826c6f80d3963f3207bae4d573818 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 28 Oct 2024 17:23:25 -0700 Subject: [PATCH 015/102] Delete stray Package.resolved changes --- Package.resolved | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 Package.resolved diff --git a/Package.resolved b/Package.resolved deleted file mode 100644 index b10a983..0000000 --- a/Package.resolved +++ /dev/null @@ -1,16 +0,0 @@ -{ - "object": { - "pins": [ - { - "package": "swift-atomics", - "repositoryURL": "https://github.com/apple/swift-atomics", - "state": { - "branch": null, - "revision": "6c89474e62719ddcc1e9614989fff2f68208fe10", - "version": "1.1.0" - } - } - ] - }, - "version": 1 -} From 1a3e37d7919aba47d376200d7c6f998e31aa84ba Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 28 Oct 2024 17:24:46 -0700 Subject: [PATCH 016/102] Fix mismerge --- Sources/CSystem/{ => include}/CSystemLinux.h | 0 Sources/CSystem/{ => include}/CSystemWASI.h | 0 Sources/CSystem/{ => include}/CSystemWindows.h | 0 Sources/CSystem/{ => include}/io_uring.h | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename Sources/CSystem/{ => include}/CSystemLinux.h (100%) rename Sources/CSystem/{ => include}/CSystemWASI.h (100%) rename Sources/CSystem/{ => include}/CSystemWindows.h (100%) rename Sources/CSystem/{ => include}/io_uring.h (100%) diff --git a/Sources/CSystem/CSystemLinux.h b/Sources/CSystem/include/CSystemLinux.h similarity index 100% rename from Sources/CSystem/CSystemLinux.h rename to Sources/CSystem/include/CSystemLinux.h diff --git a/Sources/CSystem/CSystemWASI.h b/Sources/CSystem/include/CSystemWASI.h similarity index 100% rename from Sources/CSystem/CSystemWASI.h rename to Sources/CSystem/include/CSystemWASI.h diff --git a/Sources/CSystem/CSystemWindows.h b/Sources/CSystem/include/CSystemWindows.h similarity index 100% rename from Sources/CSystem/CSystemWindows.h rename to Sources/CSystem/include/CSystemWindows.h diff --git a/Sources/CSystem/io_uring.h b/Sources/CSystem/include/io_uring.h similarity index 100% rename from Sources/CSystem/io_uring.h rename to Sources/CSystem/include/io_uring.h From f369347b73ccbd40740cb905a12b82d09083757e Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 28 Oct 2024 17:25:31 -0700 Subject: [PATCH 017/102] Fix mismerge --- Sources/CSystem/{ => include}/module.modulemap | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Sources/CSystem/{ => include}/module.modulemap (100%) diff --git a/Sources/CSystem/module.modulemap b/Sources/CSystem/include/module.modulemap similarity index 100% rename from Sources/CSystem/module.modulemap rename to Sources/CSystem/include/module.modulemap From ef94a3719363a97cc8b7e6fa30a096a7d74e9f3c Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 5 Dec 2024 03:11:11 +0000 Subject: [PATCH 018/102] Refactoring, and give up on resources being noncopyable structs --- Sources/System/AsyncFileDescriptor.swift | 60 ++-- Sources/System/IOCompletion.swift | 2 +- Sources/System/IORequest.swift | 273 +++++++++++++++--- Sources/System/IORing.swift | 18 +- .../Internals/WindowsSyscallAdapters.swift | 2 +- .../AsyncFileDescriptorTests.swift | 36 ++- Tests/SystemTests/IORequestTests.swift | 14 +- Tests/SystemTests/IORingTests.swift | 4 +- Tests/SystemTests/ManagedIORingTests.swift | 4 +- 9 files changed, 305 insertions(+), 108 deletions(-) diff --git a/Sources/System/AsyncFileDescriptor.swift b/Sources/System/AsyncFileDescriptor.swift index 68d9e33..f8075d6 100644 --- a/Sources/System/AsyncFileDescriptor.swift +++ b/Sources/System/AsyncFileDescriptor.swift @@ -5,29 +5,30 @@ public struct AsyncFileDescriptor: ~Copyable { @usableFromInline let fileSlot: IORingFileSlot @usableFromInline let ring: ManagedIORing - public static func openat( - atDirectory: FileDescriptor = FileDescriptor(rawValue: -100), + public static func open( path: FilePath, - _ mode: FileDescriptor.AccessMode, + in directory: FileDescriptor = FileDescriptor(rawValue: -100), + on ring: ManagedIORing, + mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil, - onRing ring: ManagedIORing + permissions: FilePermissions? = nil ) async throws -> AsyncFileDescriptor { // todo; real error type guard let fileSlot = ring.getFileSlot() else { throw IORingError.missingRequiredFeatures } + //TODO: need an async-friendly withCString let cstr = path.withCString { return $0 // bad } let res = await ring.submitAndWait( - .openat( - atDirectory: atDirectory, - path: cstr, - mode, - options: options, - permissions: permissions, - intoSlot: fileSlot.borrow() + IORequest( + opening: cstr, + in: directory, + into: fileSlot, + mode: mode, + options: options, + permissions: permissions )) if res.result < 0 { throw Errno(rawValue: -res.result) @@ -45,10 +46,7 @@ public struct AsyncFileDescriptor: ~Copyable { @inlinable @inline(__always) public consuming func close(isolation actor: isolated (any Actor)? = #isolation) async throws { - let res = await ring.submitAndWait( - .close( - .registered(self.fileSlot) - )) + let res = await ring.submitAndWait(IORequest(closing: fileSlot)) if res.result < 0 { throw Errno(rawValue: -res.result) } @@ -61,12 +59,11 @@ public struct AsyncFileDescriptor: ~Copyable { atAbsoluteOffset offset: UInt64 = UInt64.max, isolation actor: isolated (any Actor)? = #isolation ) async throws -> UInt32 { - let file = fileSlot.borrow() let res = await ring.submitAndWait( - .readUnregistered( - file: .registered(file), - buffer: buffer, - offset: offset + IORequest( + reading: fileSlot, + into: buffer, + at: offset )) if res.result < 0 { throw Errno(rawValue: -res.result) @@ -77,15 +74,15 @@ public struct AsyncFileDescriptor: ~Copyable { @inlinable @inline(__always) public func read( - into buffer: borrowing IORingBuffer, //TODO: should be inout? + into buffer: IORingBuffer, //TODO: should be inout? atAbsoluteOffset offset: UInt64 = UInt64.max, isolation actor: isolated (any Actor)? = #isolation ) async throws -> UInt32 { let res = await ring.submitAndWait( - .read( - file: .registered(self.fileSlot.borrow()), - buffer: buffer.borrow(), - offset: offset + IORequest( + reading: fileSlot, + into: buffer, + at: offset )) if res.result < 0 { throw Errno(rawValue: -res.result) @@ -100,11 +97,12 @@ public struct AsyncFileDescriptor: ~Copyable { } //TODO: can we do the linear types thing and error if they don't consume it manually? - // deinit { - // if self.open { - // TODO: close or error? TBD - // } - // } + // deinit { + // if self.open { + // close() + // // TODO: close or error? TBD + // } + // } } public class AsyncFileDescriptorSequence: AsyncSequence { diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index 8bf173c..1702f9e 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -21,7 +21,7 @@ extension IOCompletion { } extension IOCompletion { - public var userData: UInt64 { + public var userData: UInt64 { //TODO: naming? get { return rawValue.user_data } diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 2a47c62..0af8717 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -1,57 +1,90 @@ import struct CSystem.io_uring_sqe -public enum IORequest: ~Copyable { +@usableFromInline +internal enum IORequestCore: ~Copyable { case nop // nothing here case openat( + atDirectory: FileDescriptor, + path: UnsafePointer, + FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil + ) + case openatSlot( atDirectory: FileDescriptor, path: UnsafePointer, FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, - intoSlot: IORingFileSlot? = nil + intoSlot: IORingFileSlot ) case read( - file: File, + file: FileDescriptor, buffer: IORingBuffer, offset: UInt64 = 0 ) case readUnregistered( - file: File, + file: FileDescriptor, + buffer: UnsafeMutableRawBufferPointer, + offset: UInt64 = 0 + ) + case readSlot( + file: IORingFileSlot, + buffer: IORingBuffer, + offset: UInt64 = 0 + ) + case readUnregisteredSlot( + file: IORingFileSlot, buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0 ) case write( - file: File, + file: FileDescriptor, buffer: IORingBuffer, offset: UInt64 = 0 ) case writeUnregistered( - file: File, + file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0 ) - case close(File) - - public enum File: ~Copyable { - case registered(IORingFileSlot) - case unregistered(FileDescriptor) - } + case writeSlot( + file: IORingFileSlot, + buffer: IORingBuffer, + offset: UInt64 = 0 + ) + case writeUnregisteredSlot( + file: IORingFileSlot, + buffer: UnsafeMutableRawBufferPointer, + offset: UInt64 = 0 + ) + case close(FileDescriptor) + case closeSlot(IORingFileSlot) } @inlinable @inline(__always) internal func makeRawRequest_readWrite_registered( - file: consuming IORequest.File, - buffer: consuming IORingBuffer, + file: FileDescriptor, + buffer: IORingBuffer, offset: UInt64, request: consuming RawIORequest ) -> RawIORequest { - switch file { - case .registered(let regFile): - request.rawValue.fd = Int32(exactly: regFile.index)! - request.flags = .fixedFile - case .unregistered(let fd): - request.fileDescriptor = fd - } + request.fileDescriptor = file + request.buffer = buffer.unsafeBuffer + request.rawValue.buf_index = UInt16(exactly: buffer.index)! + request.offset = offset + return request +} + +@inlinable @inline(__always) +internal func makeRawRequest_readWrite_registered_slot( + file: IORingFileSlot, + buffer: IORingBuffer, + offset: UInt64, + request: consuming RawIORequest +) -> RawIORequest { + request.rawValue.fd = Int32(exactly: file.index)! + request.flags = .fixedFile request.buffer = buffer.unsafeBuffer request.rawValue.buf_index = UInt16(exactly: buffer.index)! request.offset = offset @@ -60,64 +93,222 @@ internal func makeRawRequest_readWrite_registered( @inlinable @inline(__always) internal func makeRawRequest_readWrite_unregistered( - file: consuming IORequest.File, + file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, offset: UInt64, request: consuming RawIORequest ) -> RawIORequest { - switch file { - case .registered(let regFile): - request.rawValue.fd = Int32(exactly: regFile.index)! - request.flags = .fixedFile - case .unregistered(let fd): - request.fileDescriptor = fd - } + request.fileDescriptor = file request.buffer = buffer request.offset = offset return request } +@inlinable @inline(__always) +internal func makeRawRequest_readWrite_unregistered_slot( + file: IORingFileSlot, + buffer: UnsafeMutableRawBufferPointer, + offset: UInt64, + request: consuming RawIORequest +) -> RawIORequest { + request.rawValue.fd = Int32(exactly: file.index)! + request.flags = .fixedFile + request.buffer = buffer + request.offset = offset + return request +} + +public struct IORequest : ~Copyable { + @usableFromInline var core: IORequestCore + + @inlinable internal consuming func extractCore() -> IORequestCore { + return core + } +} + extension IORequest { + public init() { //TODO: why do we have nop? + core = .nop + } + + public init( + reading file: IORingFileSlot, + into buffer: IORingBuffer, + at offset: UInt64 = 0 + ) { + core = .readSlot(file: file, buffer: buffer, offset: offset) + } + + public init( + reading file: FileDescriptor, + into buffer: IORingBuffer, + at offset: UInt64 = 0 + ) { + core = .read(file: file, buffer: buffer, offset: offset) + } + + public init( + reading file: IORingFileSlot, + into buffer: UnsafeMutableRawBufferPointer, + at offset: UInt64 = 0 + ) { + core = .readUnregisteredSlot(file: file, buffer: buffer, offset: offset) + } + + public init( + reading file: FileDescriptor, + into buffer: UnsafeMutableRawBufferPointer, + at offset: UInt64 = 0 + ) { + core = .readUnregistered(file: file, buffer: buffer, offset: offset) + } + + public init( + writing buffer: IORingBuffer, + into file: IORingFileSlot, + at offset: UInt64 = 0 + ) { + core = .writeSlot(file: file, buffer: buffer, offset: offset) + } + + public init( + writing buffer: IORingBuffer, + into file: FileDescriptor, + at offset: UInt64 = 0 + ) { + core = .write(file: file, buffer: buffer, offset: offset) + } + + public init( + writing buffer: UnsafeMutableRawBufferPointer, + into file: IORingFileSlot, + at offset: UInt64 = 0 + ) { + core = .writeUnregisteredSlot(file: file, buffer: buffer, offset: offset) + } + + public init( + writing buffer: UnsafeMutableRawBufferPointer, + into file: FileDescriptor, + at offset: UInt64 = 0 + ) { + core = .writeUnregistered(file: file, buffer: buffer, offset: offset) + } + + public init( + closing file: FileDescriptor + ) { + core = .close(file) + } + + public init( + closing file: IORingFileSlot + ) { + core = .closeSlot(file) + } + + + public init( + opening path: UnsafePointer, + in directory: FileDescriptor, + into slot: IORingFileSlot, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil + ) { + core = .openatSlot(atDirectory: directory, path: path, mode, options: options, permissions: permissions, intoSlot: slot) + } + + public init( + opening path: UnsafePointer, + in directory: FileDescriptor, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil + ) { + core = .openat(atDirectory: directory, path: path, mode, options: options, permissions: permissions) + } + + + public init( + opening path: FilePath, + in directory: FileDescriptor, + into slot: IORingFileSlot, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil + ) { + fatalError("Implement me") + } + + public init( + opening path: FilePath, + in directory: FileDescriptor, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil + ) { + fatalError("Implement me") + } + @inlinable @inline(__always) public consuming func makeRawRequest() -> RawIORequest { var request = RawIORequest() - switch consume self { + switch extractCore() { case .nop: request.operation = .nop - case .openat(let atDirectory, let path, let mode, let options, let permissions, let slot): + case .openatSlot(let atDirectory, let path, let mode, let options, let permissions, let fileSlot): // TODO: use rawValue less request.operation = .openAt request.fileDescriptor = atDirectory - request.rawValue.addr = unsafeBitCast(path, to: UInt64.self) + request.rawValue.addr = UInt64(UInt(bitPattern: path)) + request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) + request.rawValue.len = permissions?.rawValue ?? 0 + request.rawValue.file_index = UInt32(fileSlot.index + 1) + case .openat(let atDirectory, let path, let mode, let options, let permissions): + request.operation = .openAt + request.fileDescriptor = atDirectory + request.rawValue.addr = UInt64(UInt(bitPattern: path)) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 - if let fileSlot = slot { - request.rawValue.file_index = UInt32(fileSlot.index + 1) - } case .write(let file, let buffer, let offset): request.operation = .writeFixed return makeRawRequest_readWrite_registered( file: file, buffer: buffer, offset: offset, request: request) + case .writeSlot(let file, let buffer, let offset): + request.operation = .writeFixed + return makeRawRequest_readWrite_registered_slot( + file: file, buffer: buffer, offset: offset, request: request) case .writeUnregistered(let file, let buffer, let offset): request.operation = .write return makeRawRequest_readWrite_unregistered( file: file, buffer: buffer, offset: offset, request: request) + case .writeUnregisteredSlot(let file, let buffer, let offset): + request.operation = .write + return makeRawRequest_readWrite_unregistered_slot( + file: file, buffer: buffer, offset: offset, request: request) case .read(let file, let buffer, let offset): request.operation = .readFixed return makeRawRequest_readWrite_registered( file: file, buffer: buffer, offset: offset, request: request) + case .readSlot(let file, let buffer, let offset): + request.operation = .readFixed + return makeRawRequest_readWrite_registered_slot( + file: file, buffer: buffer, offset: offset, request: request) case .readUnregistered(let file, let buffer, let offset): request.operation = .read return makeRawRequest_readWrite_unregistered( file: file, buffer: buffer, offset: offset, request: request) + case .readUnregisteredSlot(let file, let buffer, let offset): + request.operation = .read + return makeRawRequest_readWrite_unregistered_slot( + file: file, buffer: buffer, offset: offset, request: request) case .close(let file): request.operation = .close - switch file { - case .registered(let regFile): - request.rawValue.file_index = UInt32(regFile.index + 1) - case .unregistered(let normalFile): - request.fileDescriptor = normalFile - } + request.fileDescriptor = file + case .closeSlot(let file): + request.operation = .close + request.rawValue.file_index = UInt32(file.index + 1) } return request } diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 2f18cb5..57c2161 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -46,7 +46,7 @@ struct CQRing: ~Copyable { let cqes: UnsafeBufferPointer } -internal class ResourceManager: @unchecked Sendable { +internal final class ResourceManager: @unchecked Sendable { typealias Resource = T struct Resources { @@ -85,38 +85,28 @@ internal class ResourceManager: @unchecked Sendable { } } -public struct IOResource: ~Copyable { +public class IOResource { typealias Resource = T @usableFromInline let resource: T @usableFromInline let index: Int let manager: ResourceManager - let isBorrow: Bool //TODO: this is a workaround for lifetime issues and should be removed internal init( resource: T, index: Int, - manager: ResourceManager, - isBorrow: Bool = false + manager: ResourceManager ) { self.resource = resource self.index = index self.manager = manager - self.isBorrow = isBorrow } func withResource() { } - //TODO: this is a workaround for lifetime issues and should be removed - @usableFromInline func borrow() -> IOResource { - IOResource(resource: resource, index: index, manager: manager, isBorrow: true) - } - deinit { - if !isBorrow { - manager.releaseResource(index: self.index) - } + manager.releaseResource(index: self.index) } } diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index d56d33e..706881e 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -187,7 +187,7 @@ internal func pwrite( internal func pipe( _ fds: UnsafeMutablePointer, bytesReserved: UInt32 = 4096 ) -> CInt { -  return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT); + return _pipe(fds, bytesReserved, _O_BINARY | _O_NOINHERIT); } @inline(__always) diff --git a/Tests/SystemTests/AsyncFileDescriptorTests.swift b/Tests/SystemTests/AsyncFileDescriptorTests.swift index 7de2272..ebd308f 100644 --- a/Tests/SystemTests/AsyncFileDescriptorTests.swift +++ b/Tests/SystemTests/AsyncFileDescriptorTests.swift @@ -9,32 +9,50 @@ import System final class AsyncFileDescriptorTests: XCTestCase { func testOpen() async throws { let ring = try ManagedIORing(queueDepth: 32) - let file = try await AsyncFileDescriptor.openat( + _ = try await AsyncFileDescriptor.open( path: "/dev/zero", - .readOnly, - onRing: ring + on: ring, + mode: .readOnly ) } func testOpenClose() async throws { let ring = try ManagedIORing(queueDepth: 32) - let file = try await AsyncFileDescriptor.openat( + let file = try await AsyncFileDescriptor.open( path: "/dev/zero", - .readOnly, - onRing: ring + on: ring, + mode: .readOnly ) try await file.close() } func testDevNullEmpty() async throws { let ring = try ManagedIORing(queueDepth: 32) - let file = try await AsyncFileDescriptor.openat( + let file = try await AsyncFileDescriptor.open( path: "/dev/null", - .readOnly, - onRing: ring + on: ring, + mode: .readOnly ) for try await _ in file.toBytes() { XCTFail("/dev/null should be empty") } } + + func testRead() async throws { + let ring = try ManagedIORing(queueDepth: 32) + let file = try await AsyncFileDescriptor.open( + path: "/dev/zero", + on: ring, + mode: .readOnly + ) + let bytes = file.toBytes() + var counter = 0 + for try await byte in bytes { + XCTAssert(byte == 0) + counter &+= 1 + if counter > 16384 { + break + } + } + } } diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index a1e1453..78be4cf 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -19,7 +19,7 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] { // which are known to work correctly. final class IORequestTests: XCTestCase { func testNop() { - let req = IORequest.nop.makeRawRequest() + let req = IORequest().makeRawRequest() let sourceBytes = requestBytes(req) // convenient property of nop: it's all zeros! // for some unknown reason, liburing sets the fd field to -1. @@ -34,13 +34,13 @@ final class IORequestTests: XCTestCase { let pathPtr = UnsafePointer(bitPattern: 0x414141410badf00d)! let fileSlot = resmgr.getResource()! - let req = IORequest.openat( - atDirectory: FileDescriptor(rawValue: -100), - path: pathPtr, - .readOnly, + let req = IORequest( + opening: pathPtr, + in: FileDescriptor(rawValue: -100), + into: fileSlot, + mode: .readOnly, options: [], - permissions: nil, - intoSlot: fileSlot.borrow() + permissions: nil ) let expectedRequest: [UInt8] = { diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 4604f50..85846d3 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -8,12 +8,12 @@ import System final class IORingTests: XCTestCase { func testInit() throws { - let ring = try IORing(queueDepth: 32) + _ = try IORing(queueDepth: 32) } func testNop() throws { var ring = try IORing(queueDepth: 32) - ring.writeRequest(.nop) + ring.writeRequest(IORequest()) ring.submitRequests() let completion = ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) diff --git a/Tests/SystemTests/ManagedIORingTests.swift b/Tests/SystemTests/ManagedIORingTests.swift index e7ad3f5..4b8ea28 100644 --- a/Tests/SystemTests/ManagedIORingTests.swift +++ b/Tests/SystemTests/ManagedIORingTests.swift @@ -8,12 +8,12 @@ import System final class ManagedIORingTests: XCTestCase { func testInit() throws { - let ring = try ManagedIORing(queueDepth: 32) + _ = try ManagedIORing(queueDepth: 32) } func testNop() async throws { let ring = try ManagedIORing(queueDepth: 32) - let completion = await ring.submitAndWait(.nop) + let completion = await ring.submitAndWait(IORequest()) XCTAssertEqual(completion.result, 0) } } From 7ea32aefce1f716cb0147f43b64eacf184f1914f Mon Sep 17 00:00:00 2001 From: David Smith Date: Wed, 11 Dec 2024 23:00:50 +0000 Subject: [PATCH 019/102] More refactoring, and working timeout support on ManagedIORing --- Sources/System/AsyncFileDescriptor.swift | 11 ++- Sources/System/IORing.swift | 82 +++++++++++++++++----- Sources/System/IORingError.swift | 5 +- Sources/System/ManagedIORing.swift | 74 ++++++++++++++++--- Sources/System/RawIORequest.swift | 42 ++++++++++- Tests/SystemTests/IORingTests.swift | 2 +- Tests/SystemTests/ManagedIORingTests.swift | 31 +++++++- 7 files changed, 208 insertions(+), 39 deletions(-) diff --git a/Sources/System/AsyncFileDescriptor.swift b/Sources/System/AsyncFileDescriptor.swift index f8075d6..a76d90e 100644 --- a/Sources/System/AsyncFileDescriptor.swift +++ b/Sources/System/AsyncFileDescriptor.swift @@ -21,8 +21,7 @@ public struct AsyncFileDescriptor: ~Copyable { let cstr = path.withCString { return $0 // bad } - let res = await ring.submitAndWait( - IORequest( + let res = try await ring.submit(request: IORequest( opening: cstr, in: directory, into: fileSlot, @@ -46,7 +45,7 @@ public struct AsyncFileDescriptor: ~Copyable { @inlinable @inline(__always) public consuming func close(isolation actor: isolated (any Actor)? = #isolation) async throws { - let res = await ring.submitAndWait(IORequest(closing: fileSlot)) + let res = try await ring.submit(request: IORequest(closing: fileSlot)) if res.result < 0 { throw Errno(rawValue: -res.result) } @@ -59,8 +58,7 @@ public struct AsyncFileDescriptor: ~Copyable { atAbsoluteOffset offset: UInt64 = UInt64.max, isolation actor: isolated (any Actor)? = #isolation ) async throws -> UInt32 { - let res = await ring.submitAndWait( - IORequest( + let res = try await ring.submit(request: IORequest( reading: fileSlot, into: buffer, at: offset @@ -78,8 +76,7 @@ public struct AsyncFileDescriptor: ~Copyable { atAbsoluteOffset offset: UInt64 = UInt64.max, isolation actor: isolated (any Actor)? = #isolation ) async throws -> UInt32 { - let res = await ring.submitAndWait( - IORequest( + let res = try await ring.submit(request: IORequest( reading: fileSlot, into: buffer, at: offset diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 57c2161..00461d1 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -138,7 +138,10 @@ internal func _blockingGetSubmissionEntry(ring: inout SQRing, submissionQueueEnt io_uring_sqe > { while true { - if let entry = _getSubmissionEntry(ring: &ring, submissionQueueEntries: submissionQueueEntries) { + if let entry = _getSubmissionEntry( + ring: &ring, + submissionQueueEntries: submissionQueueEntries + ) { return entry } // TODO: actually block here instead of spinning @@ -146,13 +149,18 @@ internal func _blockingGetSubmissionEntry(ring: inout SQRing, submissionQueueEnt } -internal func _submitRequests(ring: inout SQRing, ringDescriptor: Int32) { - let flushedEvents = _flushQueue(ring: &ring) - - // Ring always needs enter right now; +//TODO: omitting signal mask for now +//Tell the kernel that we've submitted requests and/or are waiting for completions +internal func _enter( + ringDescriptor: Int32, + numEvents: UInt32, + minCompletions: UInt32, + flags: UInt32 +) throws -> Int32 { + // Ring always needs enter right now; // TODO: support SQPOLL here while true { - let ret = io_uring_enter(ringDescriptor, flushedEvents, 0, 0, nil) + let ret = io_uring_enter(ringDescriptor, numEvents, minCompletions, flags, nil) // error handling: // EAGAIN / EINTR (try again), // EBADF / EBADFD / EOPNOTSUPP / ENXIO @@ -160,32 +168,47 @@ internal func _submitRequests(ring: inout SQRing, ringDescriptor: Int32) { // EINVAL (bad constant flag?, fatal), // EFAULT (bad address for argument from library, fatal) if ret == -EAGAIN || ret == -EINTR { + //TODO: should we wait a bit on AGAIN? continue } else if ret < 0 { fatalError( "fatal error in submitting requests: " + Errno(rawValue: -ret).debugDescription ) } else { - break + return ret } } } +internal func _submitRequests(ring: inout SQRing, ringDescriptor: Int32) throws { + let flushedEvents = _flushQueue(ring: &ring) + _ = try _enter(ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0) +} + +internal func _getUnconsumedSubmissionCount(ring: inout SQRing) -> UInt32 { + return ring.userTail - ring.kernelHead.pointee.load(ordering: .acquiring) +} + +internal func _getUnconsumedCompletionCount(ring: inout CQRing) -> UInt32 { + return ring.kernelTail.pointee.load(ordering: .acquiring) - ring.kernelHead.pointee.load(ordering: .acquiring) +} + +//TODO: pretty sure this is supposed to do more than it does internal func _flushQueue(ring: inout SQRing) -> UInt32 { ring.kernelTail.pointee.store( - ring.userTail, ordering: .relaxed + ring.userTail, ordering: .releasing ) - return ring.userTail - ring.kernelHead.pointee.load(ordering: .relaxed) + return _getUnconsumedSubmissionCount(ring: &ring) } @usableFromInline @inline(__always) internal func _getSubmissionEntry(ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer) -> UnsafeMutablePointer< io_uring_sqe >? { - let next = ring.userTail + 1 + let next = ring.userTail &+ 1 //this is expected to wrap // FEAT: smp load when SQPOLL in use (not in MVP) - let kernelHead = ring.kernelHead.pointee.load(ordering: .relaxed) + let kernelHead = ring.kernelHead.pointee.load(ordering: .acquiring) // FEAT: 128-bit event support (not in MVP) if next - kernelHead <= ring.array.count { @@ -383,18 +406,45 @@ public struct IORing: @unchecked Sendable, ~Copyable { func _tryConsumeCompletion(ring: inout CQRing) -> IOCompletion? { let tail = ring.kernelTail.pointee.load(ordering: .acquiring) - let head = ring.kernelHead.pointee.load(ordering: .relaxed) + let head = ring.kernelHead.pointee.load(ordering: .acquiring) if tail != head { // 32 byte copy - oh well let res = ring.cqes[Int(head & ring.ringMask)] - ring.kernelHead.pointee.store(head + 1, ordering: .relaxed) + ring.kernelHead.pointee.store(head &+ 1, ordering: .releasing) return IOCompletion(rawValue: res) } return nil } + internal func handleRegistrationResult(_ result: Int32) throws { + //TODO: error handling + } + + public mutating func registerEventFD(ring: inout IORing, _ descriptor: FileDescriptor) throws { + var rawfd = descriptor.rawValue + let result = withUnsafePointer(to: &rawfd) { fdptr in + return io_uring_register( + ring.ringDescriptor, + IORING_REGISTER_EVENTFD, + UnsafeMutableRawPointer(mutating: fdptr), + 1 + ) + } + try handleRegistrationResult(result) + } + + public mutating func unregisterEventFD(ring: inout IORing) throws { + let result = io_uring_register( + ring.ringDescriptor, + IORING_UNREGISTER_EVENTFD, + nil, + 0 + ) + try handleRegistrationResult(result) + } + public mutating func registerFiles(count: UInt32) { guard self.registeredFiles == nil else { fatalError() } let fileBuf = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) @@ -445,9 +495,9 @@ public struct IORing: @unchecked Sendable, ~Copyable { fatalError("failed to unregister buffers: TODO") } - public func submitRequests() { - submissionMutex.withLock { ring in - _submitRequests(ring: &ring, ringDescriptor: ringDescriptor) + public func submitRequests() throws { + try submissionMutex.withLock { ring in + try _submitRequests(ring: &ring, ringDescriptor: ringDescriptor) } } diff --git a/Sources/System/IORingError.swift b/Sources/System/IORingError.swift index d87b293..fda58bc 100644 --- a/Sources/System/IORingError.swift +++ b/Sources/System/IORingError.swift @@ -1,3 +1,6 @@ -enum IORingError: Error { +//TODO: make this not an enum +public enum IORingError: Error, Equatable { case missingRequiredFeatures + case operationCanceled + case unknown } diff --git a/Sources/System/ManagedIORing.swift b/Sources/System/ManagedIORing.swift index 30ea5ed..99c112d 100644 --- a/Sources/System/ManagedIORing.swift +++ b/Sources/System/ManagedIORing.swift @@ -1,3 +1,16 @@ +fileprivate func handleCompletionError( + _ result: Int32, + for continuation: UnsafeContinuation) { + var error: IORingError = .unknown + switch result { + case -(_ECANCELED): + error = .operationCanceled + default: + error = .unknown + } + continuation.resume(throwing: error) +} + final public class ManagedIORing: @unchecked Sendable { var internalRing: IORing @@ -11,25 +24,64 @@ final public class ManagedIORing: @unchecked Sendable { private func startWaiter() { Task.detached { while !Task.isCancelled { + //TODO: should timeout handling be sunk into IORing? let cqe = self.internalRing.blockingConsumeCompletion() + if cqe.userData == 0 { + continue + } let cont = unsafeBitCast( - cqe.userData, to: UnsafeContinuation.self) - cont.resume(returning: cqe) + cqe.userData, to: UnsafeContinuation.self) + + if cqe.result < 0 { + var err = system_strerror(cqe.result * -1) + let len = system_strlen(err!) + err!.withMemoryRebound(to: UInt8.self, capacity: len) { + let errStr = String(decoding: UnsafeBufferPointer(start: $0, count: len), as: UTF8.self) + print("\(errStr)") + } + handleCompletionError(cqe.result, for: cont) + } else { + cont.resume(returning: cqe) + } } } } - public func submitAndWait(_ request: __owned IORequest, isolation actor: isolated (any Actor)? = #isolation) async -> IOCompletion { + public func submit( + request: __owned IORequest, + timeout: Duration? = nil, + isolation actor: isolated (any Actor)? = #isolation + ) async throws -> IOCompletion { var consumeOnceWorkaround: IORequest? = request - return await withUnsafeContinuation { cont in - return internalRing.submissionMutex.withLock { ring in - let request = consumeOnceWorkaround.take()! - let entry = _blockingGetSubmissionEntry( - ring: &ring, submissionQueueEntries: internalRing.submissionQueueEntries) - entry.pointee = request.makeRawRequest().rawValue - entry.pointee.user_data = unsafeBitCast(cont, to: UInt64.self) - _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) + return try await withUnsafeThrowingContinuation { cont in + do { + try internalRing.submissionMutex.withLock { ring in + let request = consumeOnceWorkaround.take()! + let entry = _blockingGetSubmissionEntry( + ring: &ring, submissionQueueEntries: internalRing.submissionQueueEntries) + entry.pointee = request.makeRawRequest().rawValue + entry.pointee.user_data = unsafeBitCast(cont, to: UInt64.self) + if let timeout { + //TODO: if IORING_FEAT_MIN_TIMEOUT is supported we can do this more efficiently + let timeoutEntry = _blockingGetSubmissionEntry( + ring: &ring, + submissionQueueEntries: internalRing.submissionQueueEntries + ) + try RawIORequest.withTimeoutRequest( + linkedTo: entry, + in: timeoutEntry, + duration: timeout, + flags: .relativeTime + ) { + try _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) + } + } else { + try _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) + } + } + } catch (let e) { + cont.resume(throwing: e) } } diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 52407b0..5a1fd03 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -24,6 +24,8 @@ extension RawIORequest { case sendMessage = 9 case receiveMessage = 10 // ... + case link_timeout = 15 + // ... case openAt = 18 case close = 19 case filesUpdate = 20 @@ -103,7 +105,7 @@ extension RawIORequest { // poll32_events // sync_range_flags // msg_flags - // timeout_flags + case timeoutFlags(TimeOutFlags) // accept_flags // cancel_flags case openFlags(FileDescriptor.OpenOptions) @@ -132,12 +134,48 @@ extension RawIORequest { // append to end of the file public static let append = ReadWriteFlags(rawValue: 1 << 4) } + + public struct TimeOutFlags: OptionSet, Hashable, Codable { + public var rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + public static let relativeTime: RawIORequest.TimeOutFlags = TimeOutFlags(rawValue: 0) + public static let absoluteTime: RawIORequest.TimeOutFlags = TimeOutFlags(rawValue: 1 << 0) + } } extension RawIORequest { static func nop() -> RawIORequest { - var req = RawIORequest() + var req: RawIORequest = RawIORequest() req.operation = .nop return req } + + //TODO: typed errors + static func withTimeoutRequest( + linkedTo opEntry: UnsafeMutablePointer, + in timeoutEntry: UnsafeMutablePointer, + duration: Duration, + flags: TimeOutFlags, + work: () throws -> R) rethrows -> R { + + opEntry.pointee.flags |= Flags.linkRequest.rawValue + opEntry.pointee.off = 1 + var ts = __kernel_timespec( + tv_sec: duration.components.seconds, + tv_nsec: duration.components.attoseconds / 1_000_000_000 + ) + return try withUnsafePointer(to: &ts) { tsPtr in + var req: RawIORequest = RawIORequest() + req.operation = .link_timeout + req.rawValue.timeout_flags = flags.rawValue + req.rawValue.len = 1 + req.rawValue.addr = UInt64(UInt(bitPattern: tsPtr)) + timeoutEntry.pointee = req.rawValue + return try work() + } + } } \ No newline at end of file diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 85846d3..d0102a0 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -14,7 +14,7 @@ final class IORingTests: XCTestCase { func testNop() throws { var ring = try IORing(queueDepth: 32) ring.writeRequest(IORequest()) - ring.submitRequests() + try ring.submitRequests() let completion = ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) } diff --git a/Tests/SystemTests/ManagedIORingTests.swift b/Tests/SystemTests/ManagedIORingTests.swift index 4b8ea28..2432403 100644 --- a/Tests/SystemTests/ManagedIORingTests.swift +++ b/Tests/SystemTests/ManagedIORingTests.swift @@ -13,7 +13,36 @@ final class ManagedIORingTests: XCTestCase { func testNop() async throws { let ring = try ManagedIORing(queueDepth: 32) - let completion = await ring.submitAndWait(IORequest()) + let completion = try await ring.submit(request: IORequest()) XCTAssertEqual(completion.result, 0) } + + func testTimeout() async throws { + let ring = try ManagedIORing(queueDepth: 32) + var pipes: (Int32, Int32) = (0, 0) + withUnsafeMutableBytes(of: &pipes) { ptr in + ptr.withMemoryRebound(to: UInt32.self) { tptr in + let res = pipe(tptr.baseAddress!) + XCTAssertEqual(res, 0) + } + } + let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 128, alignment: 16) + do { + let completion = try await ring.submit( + request: IORequest(reading: FileDescriptor(rawValue: pipes.0), into: buffer), + timeout: .seconds(0.1) + ) + print("\(completion)") + XCTFail("An error should be thrown") + } catch (let e) { + if let err = e as? IORingError { + XCTAssertEqual(err, .operationCanceled) + } else { + XCTFail() + } + buffer.deallocate() + close(pipes.0) + close(pipes.1) + } + } } From 55fd6e7150cb6f48fa0203c1df29746be35b1a00 Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 12 Dec 2024 01:20:24 +0000 Subject: [PATCH 020/102] Add support for timeout-on-wait to IORing, don't have tests yet --- Sources/System/IORing.swift | 37 ++++++++++++++++++++-- Sources/System/ManagedIORing.swift | 33 ++++++++++--------- Tests/SystemTests/IORingTests.swift | 2 +- Tests/SystemTests/ManagedIORingTests.swift | 2 +- 4 files changed, 53 insertions(+), 21 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 00461d1..872d996 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -368,13 +368,26 @@ public struct IORing: @unchecked Sendable, ~Copyable { self.ringFlags = params.flags } - public func blockingConsumeCompletion() -> IOCompletion { + private func _blockingConsumeCompletionGuts( + extraArgs: UnsafeMutablePointer? = nil + ) throws(IORingError) -> IOCompletion { completionMutex.withLock { ring in if let completion = _tryConsumeCompletion(ring: &ring) { return completion } else { while true { - let res = io_uring_enter(ringDescriptor, 0, 1, IORING_ENTER_GETEVENTS, nil) + var sz = 0 + if extraArgs != nil { + sz = MemoryLayout.size + } + let res = io_uring_enter2( + ringDescriptor, + 0, + 1, + IORING_ENTER_GETEVENTS, + extraArgs, + sz + ) // error handling: // EAGAIN / EINTR (try again), // EBADF / EBADFD / EOPNOTSUPP / ENXIO @@ -398,6 +411,26 @@ public struct IORing: @unchecked Sendable, ~Copyable { } } + public func blockingConsumeCompletion(timeout: Duration? = nil) throws -> IOCompletion { + if let timeout { + var ts = __kernel_timespec( + tv_sec: timeout.components.seconds, + tv_nsec: timeout.components.attoseconds / 1_000_000_000 + ) + return try withUnsafePointer(to: &ts) { tsPtr in + var args = io_uring_getevents_arg( + sigmask: 0, + sigmask_sz: 0, + pad: 0, + ts: UInt64(UInt(bitPattern: tsPtr)) + ) + return try _blockingConsumeCompletionGuts(extraArgs: &args) + } + } else { + return try _blockingConsumeCompletionGuts() + } + } + public func tryConsumeCompletion() -> IOCompletion? { completionMutex.withLock { ring in return _tryConsumeCompletion(ring: &ring) diff --git a/Sources/System/ManagedIORing.swift b/Sources/System/ManagedIORing.swift index 99c112d..b6df140 100644 --- a/Sources/System/ManagedIORing.swift +++ b/Sources/System/ManagedIORing.swift @@ -25,7 +25,8 @@ final public class ManagedIORing: @unchecked Sendable { Task.detached { while !Task.isCancelled { //TODO: should timeout handling be sunk into IORing? - let cqe = self.internalRing.blockingConsumeCompletion() + //TODO: sort out the error handling here + let cqe = try! self.internalRing.blockingConsumeCompletion() if cqe.userData == 0 { continue @@ -34,12 +35,6 @@ final public class ManagedIORing: @unchecked Sendable { cqe.userData, to: UnsafeContinuation.self) if cqe.result < 0 { - var err = system_strerror(cqe.result * -1) - let len = system_strlen(err!) - err!.withMemoryRebound(to: UInt8.self, capacity: len) { - let errStr = String(decoding: UnsafeBufferPointer(start: $0, count: len), as: UTF8.self) - print("\(errStr)") - } handleCompletionError(cqe.result, for: cont) } else { cont.resume(returning: cqe) @@ -64,17 +59,21 @@ final public class ManagedIORing: @unchecked Sendable { entry.pointee.user_data = unsafeBitCast(cont, to: UInt64.self) if let timeout { //TODO: if IORING_FEAT_MIN_TIMEOUT is supported we can do this more efficiently - let timeoutEntry = _blockingGetSubmissionEntry( - ring: &ring, - submissionQueueEntries: internalRing.submissionQueueEntries - ) - try RawIORequest.withTimeoutRequest( - linkedTo: entry, - in: timeoutEntry, - duration: timeout, - flags: .relativeTime - ) { + if true { //replace with IORING_FEAT_MIN_TIMEOUT feature check try _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) + } else { + let timeoutEntry = _blockingGetSubmissionEntry( + ring: &ring, + submissionQueueEntries: internalRing.submissionQueueEntries + ) + try RawIORequest.withTimeoutRequest( + linkedTo: entry, + in: timeoutEntry, + duration: timeout, + flags: .relativeTime + ) { + try _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) + } } } else { try _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index d0102a0..2c25e2b 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -15,7 +15,7 @@ final class IORingTests: XCTestCase { var ring = try IORing(queueDepth: 32) ring.writeRequest(IORequest()) try ring.submitRequests() - let completion = ring.blockingConsumeCompletion() + let completion = try ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) } } diff --git a/Tests/SystemTests/ManagedIORingTests.swift b/Tests/SystemTests/ManagedIORingTests.swift index 2432403..a499f6c 100644 --- a/Tests/SystemTests/ManagedIORingTests.swift +++ b/Tests/SystemTests/ManagedIORingTests.swift @@ -17,7 +17,7 @@ final class ManagedIORingTests: XCTestCase { XCTAssertEqual(completion.result, 0) } - func testTimeout() async throws { + func testSubmitTimeout() async throws { let ring = try ManagedIORing(queueDepth: 32) var pipes: (Int32, Int32) = (0, 0) withUnsafeMutableBytes(of: &pipes) { ptr in From e5fdf9ea96ff918aac8d8f1667909c74c1bc3b7c Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 6 Feb 2025 00:41:30 +0000 Subject: [PATCH 021/102] Remove managed abstractions for now --- Sources/System/AsyncFileDescriptor.swift | 161 ------------------ Sources/System/ManagedIORing.swift | 97 ----------- .../AsyncFileDescriptorTests.swift | 58 ------- Tests/SystemTests/ManagedIORingTests.swift | 48 ------ 4 files changed, 364 deletions(-) delete mode 100644 Sources/System/AsyncFileDescriptor.swift delete mode 100644 Sources/System/ManagedIORing.swift delete mode 100644 Tests/SystemTests/AsyncFileDescriptorTests.swift delete mode 100644 Tests/SystemTests/ManagedIORingTests.swift diff --git a/Sources/System/AsyncFileDescriptor.swift b/Sources/System/AsyncFileDescriptor.swift deleted file mode 100644 index a76d90e..0000000 --- a/Sources/System/AsyncFileDescriptor.swift +++ /dev/null @@ -1,161 +0,0 @@ -@_implementationOnly import CSystem - -public struct AsyncFileDescriptor: ~Copyable { - @usableFromInline var open: Bool = true - @usableFromInline let fileSlot: IORingFileSlot - @usableFromInline let ring: ManagedIORing - - public static func open( - path: FilePath, - in directory: FileDescriptor = FileDescriptor(rawValue: -100), - on ring: ManagedIORing, - mode: FileDescriptor.AccessMode, - options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil - ) async throws -> AsyncFileDescriptor { - // todo; real error type - guard let fileSlot = ring.getFileSlot() else { - throw IORingError.missingRequiredFeatures - } - //TODO: need an async-friendly withCString - let cstr = path.withCString { - return $0 // bad - } - let res = try await ring.submit(request: IORequest( - opening: cstr, - in: directory, - into: fileSlot, - mode: mode, - options: options, - permissions: permissions - )) - if res.result < 0 { - throw Errno(rawValue: -res.result) - } - - return AsyncFileDescriptor( - fileSlot, ring: ring - ) - } - - internal init(_ fileSlot: consuming IORingFileSlot, ring: ManagedIORing) { - self.fileSlot = consume fileSlot - self.ring = ring - } - - @inlinable @inline(__always) - public consuming func close(isolation actor: isolated (any Actor)? = #isolation) async throws { - let res = try await ring.submit(request: IORequest(closing: fileSlot)) - if res.result < 0 { - throw Errno(rawValue: -res.result) - } - self.open = false - } - - @inlinable @inline(__always) - public func read( - into buffer: inout UnsafeMutableRawBufferPointer, - atAbsoluteOffset offset: UInt64 = UInt64.max, - isolation actor: isolated (any Actor)? = #isolation - ) async throws -> UInt32 { - let res = try await ring.submit(request: IORequest( - reading: fileSlot, - into: buffer, - at: offset - )) - if res.result < 0 { - throw Errno(rawValue: -res.result) - } else { - return UInt32(bitPattern: res.result) - } - } - - @inlinable @inline(__always) - public func read( - into buffer: IORingBuffer, //TODO: should be inout? - atAbsoluteOffset offset: UInt64 = UInt64.max, - isolation actor: isolated (any Actor)? = #isolation - ) async throws -> UInt32 { - let res = try await ring.submit(request: IORequest( - reading: fileSlot, - into: buffer, - at: offset - )) - if res.result < 0 { - throw Errno(rawValue: -res.result) - } else { - return UInt32(bitPattern: res.result) - } - } - - //TODO: temporary workaround until AsyncSequence supports ~Copyable - public consuming func toBytes() -> AsyncFileDescriptorSequence { - AsyncFileDescriptorSequence(self) - } - - //TODO: can we do the linear types thing and error if they don't consume it manually? - // deinit { - // if self.open { - // close() - // // TODO: close or error? TBD - // } - // } -} - -public class AsyncFileDescriptorSequence: AsyncSequence { - var descriptor: AsyncFileDescriptor? - - public func makeAsyncIterator() -> FileIterator { - return .init(descriptor.take()!) - } - - internal init(_ descriptor: consuming AsyncFileDescriptor) { - self.descriptor = consume descriptor - } - - public typealias AsyncIterator = FileIterator - public typealias Element = UInt8 -} - -//TODO: only a class due to ~Copyable limitations -public class FileIterator: AsyncIteratorProtocol { - @usableFromInline let file: AsyncFileDescriptor - @usableFromInline var buffer: IORingBuffer - @usableFromInline var done: Bool - - @usableFromInline internal var currentByte: UnsafeRawPointer? - @usableFromInline internal var lastByte: UnsafeRawPointer? - - init(_ file: consuming AsyncFileDescriptor) { - self.buffer = file.ring.getBuffer()! - self.file = file - self.done = false - } - - @inlinable @inline(__always) - public func nextBuffer() async throws { - let bytesRead = Int(try await file.read(into: buffer)) - if _fastPath(bytesRead != 0) { - let unsafeBuffer = buffer.unsafeBuffer - let bufPointer = unsafeBuffer.baseAddress.unsafelyUnwrapped - self.currentByte = UnsafeRawPointer(bufPointer) - self.lastByte = UnsafeRawPointer(bufPointer.advanced(by: bytesRead)) - } else { - done = true - } - } - - @inlinable @inline(__always) - public func next() async throws -> UInt8? { - if _fastPath(currentByte != lastByte) { - // SAFETY: both pointers should be non-nil if they're not equal - let byte = currentByte.unsafelyUnwrapped.load(as: UInt8.self) - currentByte = currentByte.unsafelyUnwrapped + 1 - return byte - } else if done { - return nil - } - try await nextBuffer() - return try await next() - } -} diff --git a/Sources/System/ManagedIORing.swift b/Sources/System/ManagedIORing.swift deleted file mode 100644 index b6df140..0000000 --- a/Sources/System/ManagedIORing.swift +++ /dev/null @@ -1,97 +0,0 @@ -fileprivate func handleCompletionError( - _ result: Int32, - for continuation: UnsafeContinuation) { - var error: IORingError = .unknown - switch result { - case -(_ECANCELED): - error = .operationCanceled - default: - error = .unknown - } - continuation.resume(throwing: error) -} - -final public class ManagedIORing: @unchecked Sendable { - var internalRing: IORing - - public init(queueDepth: UInt32) throws { - self.internalRing = try IORing(queueDepth: queueDepth) - self.internalRing.registerBuffers(bufSize: 655336, count: 4) - self.internalRing.registerFiles(count: 32) - self.startWaiter() - } - - private func startWaiter() { - Task.detached { - while !Task.isCancelled { - //TODO: should timeout handling be sunk into IORing? - //TODO: sort out the error handling here - let cqe = try! self.internalRing.blockingConsumeCompletion() - - if cqe.userData == 0 { - continue - } - let cont = unsafeBitCast( - cqe.userData, to: UnsafeContinuation.self) - - if cqe.result < 0 { - handleCompletionError(cqe.result, for: cont) - } else { - cont.resume(returning: cqe) - } - } - } - } - - public func submit( - request: __owned IORequest, - timeout: Duration? = nil, - isolation actor: isolated (any Actor)? = #isolation - ) async throws -> IOCompletion { - var consumeOnceWorkaround: IORequest? = request - return try await withUnsafeThrowingContinuation { cont in - do { - try internalRing.submissionMutex.withLock { ring in - let request = consumeOnceWorkaround.take()! - let entry = _blockingGetSubmissionEntry( - ring: &ring, submissionQueueEntries: internalRing.submissionQueueEntries) - entry.pointee = request.makeRawRequest().rawValue - entry.pointee.user_data = unsafeBitCast(cont, to: UInt64.self) - if let timeout { - //TODO: if IORING_FEAT_MIN_TIMEOUT is supported we can do this more efficiently - if true { //replace with IORING_FEAT_MIN_TIMEOUT feature check - try _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) - } else { - let timeoutEntry = _blockingGetSubmissionEntry( - ring: &ring, - submissionQueueEntries: internalRing.submissionQueueEntries - ) - try RawIORequest.withTimeoutRequest( - linkedTo: entry, - in: timeoutEntry, - duration: timeout, - flags: .relativeTime - ) { - try _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) - } - } - } else { - try _submitRequests(ring: &ring, ringDescriptor: internalRing.ringDescriptor) - } - } - } catch (let e) { - cont.resume(throwing: e) - } - } - - } - - internal func getFileSlot() -> IORingFileSlot? { - internalRing.getFile() - } - - internal func getBuffer() -> IORingBuffer? { - internalRing.getBuffer() - } - -} diff --git a/Tests/SystemTests/AsyncFileDescriptorTests.swift b/Tests/SystemTests/AsyncFileDescriptorTests.swift deleted file mode 100644 index ebd308f..0000000 --- a/Tests/SystemTests/AsyncFileDescriptorTests.swift +++ /dev/null @@ -1,58 +0,0 @@ -import XCTest - -#if SYSTEM_PACKAGE -import SystemPackage -#else -import System -#endif - -final class AsyncFileDescriptorTests: XCTestCase { - func testOpen() async throws { - let ring = try ManagedIORing(queueDepth: 32) - _ = try await AsyncFileDescriptor.open( - path: "/dev/zero", - on: ring, - mode: .readOnly - ) - } - - func testOpenClose() async throws { - let ring = try ManagedIORing(queueDepth: 32) - let file = try await AsyncFileDescriptor.open( - path: "/dev/zero", - on: ring, - mode: .readOnly - ) - try await file.close() - } - - func testDevNullEmpty() async throws { - let ring = try ManagedIORing(queueDepth: 32) - let file = try await AsyncFileDescriptor.open( - path: "/dev/null", - on: ring, - mode: .readOnly - ) - for try await _ in file.toBytes() { - XCTFail("/dev/null should be empty") - } - } - - func testRead() async throws { - let ring = try ManagedIORing(queueDepth: 32) - let file = try await AsyncFileDescriptor.open( - path: "/dev/zero", - on: ring, - mode: .readOnly - ) - let bytes = file.toBytes() - var counter = 0 - for try await byte in bytes { - XCTAssert(byte == 0) - counter &+= 1 - if counter > 16384 { - break - } - } - } -} diff --git a/Tests/SystemTests/ManagedIORingTests.swift b/Tests/SystemTests/ManagedIORingTests.swift deleted file mode 100644 index a499f6c..0000000 --- a/Tests/SystemTests/ManagedIORingTests.swift +++ /dev/null @@ -1,48 +0,0 @@ -import XCTest - -#if SYSTEM_PACKAGE -import SystemPackage -#else -import System -#endif - -final class ManagedIORingTests: XCTestCase { - func testInit() throws { - _ = try ManagedIORing(queueDepth: 32) - } - - func testNop() async throws { - let ring = try ManagedIORing(queueDepth: 32) - let completion = try await ring.submit(request: IORequest()) - XCTAssertEqual(completion.result, 0) - } - - func testSubmitTimeout() async throws { - let ring = try ManagedIORing(queueDepth: 32) - var pipes: (Int32, Int32) = (0, 0) - withUnsafeMutableBytes(of: &pipes) { ptr in - ptr.withMemoryRebound(to: UInt32.self) { tptr in - let res = pipe(tptr.baseAddress!) - XCTAssertEqual(res, 0) - } - } - let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 128, alignment: 16) - do { - let completion = try await ring.submit( - request: IORequest(reading: FileDescriptor(rawValue: pipes.0), into: buffer), - timeout: .seconds(0.1) - ) - print("\(completion)") - XCTFail("An error should be thrown") - } catch (let e) { - if let err = e as? IORingError { - XCTAssertEqual(err, .operationCanceled) - } else { - XCTFail() - } - buffer.deallocate() - close(pipes.0) - close(pipes.1) - } - } -} From fdbcecab0bf531d5f739f5414969599b9be663aa Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 6 Feb 2025 00:42:21 +0000 Subject: [PATCH 022/102] Eliminate internal locking and add multiple consume support --- Sources/CSystem/include/io_uring.h | 10 +- Sources/System/IORing.swift | 223 ++++++++++++++++++----------- 2 files changed, 150 insertions(+), 83 deletions(-) diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index 5c05ed8..5cab757 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -45,11 +45,17 @@ int io_uring_setup(unsigned int entries, struct io_uring_params *p) return syscall(__NR_io_uring_setup, entries, p); } +int io_uring_enter2(int fd, unsigned int to_submit, unsigned int min_complete, + unsigned int flags, void *args, size_t sz) +{ + return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, + flags, args, _NSIG / 8); +} + int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete, unsigned int flags, sigset_t *sig) { - return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, - flags, sig, _NSIG / 8); + return io_uring_enter2(fd, to_submit, min_complete, flags, sig, _NSIG / 8); } #endif diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 872d996..0328538 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -51,7 +51,7 @@ internal final class ResourceManager: @unchecked Sendable { struct Resources { let resourceList: UnsafeMutableBufferPointer - var freeList: [Int] //TODO: bitvector? + var freeList: [Int] //TODO: bitvector? } let mutex: Mutex @@ -125,21 +125,27 @@ extension IORingBuffer { } @inlinable @inline(__always) -internal func _writeRequest(_ request: __owned RawIORequest, ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer) +internal func _writeRequest( + _ request: __owned RawIORequest, ring: inout SQRing, + submissionQueueEntries: UnsafeMutableBufferPointer +) -> Bool { - let entry = _blockingGetSubmissionEntry(ring: &ring, submissionQueueEntries: submissionQueueEntries) + let entry = _blockingGetSubmissionEntry( + ring: &ring, submissionQueueEntries: submissionQueueEntries) entry.pointee = request.rawValue return true } @inlinable @inline(__always) -internal func _blockingGetSubmissionEntry(ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer) -> UnsafeMutablePointer< +internal func _blockingGetSubmissionEntry( + ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer +) -> UnsafeMutablePointer< io_uring_sqe > { while true { if let entry = _getSubmissionEntry( - ring: &ring, + ring: &ring, submissionQueueEntries: submissionQueueEntries ) { return entry @@ -152,12 +158,12 @@ internal func _blockingGetSubmissionEntry(ring: inout SQRing, submissionQueueEnt //TODO: omitting signal mask for now //Tell the kernel that we've submitted requests and/or are waiting for completions internal func _enter( - ringDescriptor: Int32, + ringDescriptor: Int32, numEvents: UInt32, minCompletions: UInt32, flags: UInt32 ) throws -> Int32 { - // Ring always needs enter right now; + // Ring always needs enter right now; // TODO: support SQPOLL here while true { let ret = io_uring_enter(ringDescriptor, numEvents, minCompletions, flags, nil) @@ -180,32 +186,36 @@ internal func _enter( } } -internal func _submitRequests(ring: inout SQRing, ringDescriptor: Int32) throws { - let flushedEvents = _flushQueue(ring: &ring) - _ = try _enter(ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0) +internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws { + let flushedEvents = _flushQueue(ring: ring) + _ = try _enter( + ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0) } -internal func _getUnconsumedSubmissionCount(ring: inout SQRing) -> UInt32 { +internal func _getUnconsumedSubmissionCount(ring: borrowing SQRing) -> UInt32 { return ring.userTail - ring.kernelHead.pointee.load(ordering: .acquiring) } -internal func _getUnconsumedCompletionCount(ring: inout CQRing) -> UInt32 { - return ring.kernelTail.pointee.load(ordering: .acquiring) - ring.kernelHead.pointee.load(ordering: .acquiring) +internal func _getUnconsumedCompletionCount(ring: borrowing CQRing) -> UInt32 { + return ring.kernelTail.pointee.load(ordering: .acquiring) + - ring.kernelHead.pointee.load(ordering: .acquiring) } //TODO: pretty sure this is supposed to do more than it does -internal func _flushQueue(ring: inout SQRing) -> UInt32 { +internal func _flushQueue(ring: borrowing SQRing) -> UInt32 { ring.kernelTail.pointee.store( ring.userTail, ordering: .releasing ) - return _getUnconsumedSubmissionCount(ring: &ring) + return _getUnconsumedSubmissionCount(ring: ring) } @usableFromInline @inline(__always) -internal func _getSubmissionEntry(ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer) -> UnsafeMutablePointer< +internal func _getSubmissionEntry( + ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer +) -> UnsafeMutablePointer< io_uring_sqe >? { - let next = ring.userTail &+ 1 //this is expected to wrap + let next = ring.userTail &+ 1 //this is expected to wrap // FEAT: smp load when SQPOLL in use (not in MVP) let kernelHead = ring.kernelHead.pointee.load(ordering: .acquiring) @@ -227,15 +237,15 @@ internal func _getSubmissionEntry(ring: inout SQRing, submissionQueueEntries: Un return nil } -public struct IORing: @unchecked Sendable, ~Copyable { +public struct IORing: ~Copyable { let ringFlags: UInt32 let ringDescriptor: Int32 - @usableFromInline let submissionMutex: Mutex + @usableFromInline var submissionRing: SQRing // FEAT: set this eventually let submissionPolling: Bool = false - let completionMutex: Mutex + let completionRing: CQRing @usableFromInline let submissionQueueEntries: UnsafeMutableBufferPointer @@ -362,82 +372,136 @@ public struct IORing: @unchecked Sendable, ~Copyable { ) ) - self.submissionMutex = Mutex(submissionRing) - self.completionMutex = Mutex(completionRing) + self.submissionRing = submissionRing + self.completionRing = completionRing self.ringFlags = params.flags } private func _blockingConsumeCompletionGuts( - extraArgs: UnsafeMutablePointer? = nil - ) throws(IORingError) -> IOCompletion { - completionMutex.withLock { ring in - if let completion = _tryConsumeCompletion(ring: &ring) { - return completion - } else { - while true { - var sz = 0 - if extraArgs != nil { - sz = MemoryLayout.size - } - let res = io_uring_enter2( - ringDescriptor, - 0, - 1, - IORING_ENTER_GETEVENTS, - extraArgs, - sz - ) - // error handling: - // EAGAIN / EINTR (try again), - // EBADF / EBADFD / EOPNOTSUPP / ENXIO - // (failure in ring lifetime management, fatal), - // EINVAL (bad constant flag?, fatal), - // EFAULT (bad address for argument from library, fatal) - // EBUSY (not enough space for events; implies events filled - // by kernel between kernelTail load and now) - if res >= 0 || res == -EBUSY { - break - } else if res == -EAGAIN || res == -EINTR { - continue - } - fatalError( - "fatal error in receiving requests: " - + Errno(rawValue: -res).debugDescription - ) + minimumCount: UInt32, + extraArgs: UnsafeMutablePointer? = nil, + consumer: (IOCompletion?, IORingError?, Bool) throws -> Void + ) rethrows { + var count = 0 + while let completion = _tryConsumeCompletion(ring: completionRing) { + count += 1 + try consumer(completion, nil, false) + } + + if count < minimumCount { + while count < minimumCount { + var sz = 0 + if extraArgs != nil { + sz = MemoryLayout.size + } + let res = io_uring_enter2( + ringDescriptor, + 0, + minimumCount, + IORING_ENTER_GETEVENTS, + extraArgs, + sz + ) + // error handling: + // EAGAIN / EINTR (try again), + // EBADF / EBADFD / EOPNOTSUPP / ENXIO + // (failure in ring lifetime management, fatal), + // EINVAL (bad constant flag?, fatal), + // EFAULT (bad address for argument from library, fatal) + // EBUSY (not enough space for events; implies events filled + // by kernel between kernelTail load and now) + if res >= 0 || res == -EBUSY { + break + } else if res == -EAGAIN || res == -EINTR { + continue + } + fatalError( + "fatal error in receiving requests: " + + Errno(rawValue: -res).debugDescription + ) + while let completion = _tryConsumeCompletion(ring: completionRing) { + try consumer(completion, nil, false) } - return _tryConsumeCompletion(ring: &ring).unsafelyUnwrapped } + try consumer(nil, nil, true) } } - public func blockingConsumeCompletion(timeout: Duration? = nil) throws -> IOCompletion { + internal func _blockingConsumeOneCompletion( + extraArgs: UnsafeMutablePointer? = nil + ) throws -> IOCompletion { + var result: IOCompletion? = nil + try _blockingConsumeCompletionGuts(minimumCount: 1, extraArgs: extraArgs) { + (completion, error, done) in + if let error { + throw error + } + if let completion { + result = completion + } + } + return result.unsafelyUnwrapped + } + + public func blockingConsumeCompletion( + timeout: Duration? = nil + ) throws -> IOCompletion { if let timeout { var ts = __kernel_timespec( - tv_sec: timeout.components.seconds, - tv_nsec: timeout.components.attoseconds / 1_000_000_000 + tv_sec: timeout.components.seconds, + tv_nsec: timeout.components.attoseconds / 1_000_000_000 ) return try withUnsafePointer(to: &ts) { tsPtr in var args = io_uring_getevents_arg( - sigmask: 0, - sigmask_sz: 0, - pad: 0, + sigmask: 0, + sigmask_sz: 0, + pad: 0, ts: UInt64(UInt(bitPattern: tsPtr)) ) - return try _blockingConsumeCompletionGuts(extraArgs: &args) + return try _blockingConsumeOneCompletion(extraArgs: &args) } } else { - return try _blockingConsumeCompletionGuts() + return try _blockingConsumeOneCompletion() } } + public func blockingConsumeCompletions( + minimumCount: UInt32 = 1, + timeout: Duration? = nil, + consumer: (IOCompletion?, IORingError?, Bool) throws -> Void + ) throws { + var x = Glibc.stat() + let y = x.st_size + if let timeout { + var ts = __kernel_timespec( + tv_sec: timeout.components.seconds, + tv_nsec: timeout.components.attoseconds / 1_000_000_000 + ) + return try withUnsafePointer(to: &ts) { tsPtr in + var args = io_uring_getevents_arg( + sigmask: 0, + sigmask_sz: 0, + pad: 0, + ts: UInt64(UInt(bitPattern: tsPtr)) + ) + try _blockingConsumeCompletionGuts( + minimumCount: minimumCount, extraArgs: &args, consumer: consumer) + } + } else { + try _blockingConsumeCompletionGuts(minimumCount: minimumCount, consumer: consumer) + } + } + + // public func peekNextCompletion() -> IOCompletion { + + // } + public func tryConsumeCompletion() -> IOCompletion? { - completionMutex.withLock { ring in - return _tryConsumeCompletion(ring: &ring) - } + return _tryConsumeCompletion(ring: completionRing) } - func _tryConsumeCompletion(ring: inout CQRing) -> IOCompletion? { + func _tryConsumeCompletion(ring: borrowing CQRing) -> IOCompletion? { let tail = ring.kernelTail.pointee.load(ordering: .acquiring) let head = ring.kernelHead.pointee.load(ordering: .acquiring) @@ -459,9 +523,9 @@ public struct IORing: @unchecked Sendable, ~Copyable { var rawfd = descriptor.rawValue let result = withUnsafePointer(to: &rawfd) { fdptr in return io_uring_register( - ring.ringDescriptor, + ring.ringDescriptor, IORING_REGISTER_EVENTFD, - UnsafeMutableRawPointer(mutating: fdptr), + UnsafeMutableRawPointer(mutating: fdptr), 1 ) } @@ -470,9 +534,9 @@ public struct IORing: @unchecked Sendable, ~Copyable { public mutating func unregisterEventFD(ring: inout IORing) throws { let result = io_uring_register( - ring.ringDescriptor, + ring.ringDescriptor, IORING_UNREGISTER_EVENTFD, - nil, + nil, 0 ) try handleRegistrationResult(result) @@ -529,17 +593,14 @@ public struct IORing: @unchecked Sendable, ~Copyable { } public func submitRequests() throws { - try submissionMutex.withLock { ring in - try _submitRequests(ring: &ring, ringDescriptor: ringDescriptor) - } + try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } @inlinable @inline(__always) public mutating func writeRequest(_ request: __owned IORequest) -> Bool { var raw: RawIORequest? = request.makeRawRequest() - return submissionMutex.withLock { ring in - return _writeRequest(raw.take()!, ring: &ring, submissionQueueEntries: submissionQueueEntries) - } + return _writeRequest( + raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } deinit { From 7107a570b4ad1a37a0ff86d510bc8159fb18dbb8 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 11 Feb 2025 21:01:49 +0000 Subject: [PATCH 023/102] Fix import visibility --- Sources/System/IORequest.swift | 10 +++++----- Sources/System/IORing.swift | 2 -- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 0af8717..0e1a3b0 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -1,4 +1,4 @@ -import struct CSystem.io_uring_sqe +@_implementationOnly import struct CSystem.io_uring_sqe @usableFromInline internal enum IORequestCore: ~Copyable { @@ -62,7 +62,7 @@ internal enum IORequestCore: ~Copyable { case closeSlot(IORingFileSlot) } -@inlinable @inline(__always) +@inline(__always) internal func makeRawRequest_readWrite_registered( file: FileDescriptor, buffer: IORingBuffer, @@ -76,7 +76,7 @@ internal func makeRawRequest_readWrite_registered( return request } -@inlinable @inline(__always) +@inline(__always) internal func makeRawRequest_readWrite_registered_slot( file: IORingFileSlot, buffer: IORingBuffer, @@ -104,7 +104,7 @@ internal func makeRawRequest_readWrite_unregistered( return request } -@inlinable @inline(__always) +@inline(__always) internal func makeRawRequest_readWrite_unregistered_slot( file: IORingFileSlot, buffer: UnsafeMutableRawBufferPointer, @@ -251,7 +251,7 @@ extension IORequest { fatalError("Implement me") } - @inlinable @inline(__always) + @inline(__always) public consuming func makeRawRequest() -> RawIORequest { var request = RawIORequest() switch extractCore() { diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 0328538..472a69b 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -471,8 +471,6 @@ public struct IORing: ~Copyable { timeout: Duration? = nil, consumer: (IOCompletion?, IORingError?, Bool) throws -> Void ) throws { - var x = Glibc.stat() - let y = x.st_size if let timeout { var ts = __kernel_timespec( tv_sec: timeout.components.seconds, From 02481e0daabc0fb342c175681347efe8f2d44337 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 11 Feb 2025 21:06:16 +0000 Subject: [PATCH 024/102] More import fixes --- Sources/System/IORing.swift | 12 ++++++------ Sources/System/RawIORequest.swift | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 472a69b..6dff66f 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -2,7 +2,7 @@ import Glibc // needed for mmap import Synchronization -import struct CSystem.io_uring_sqe +@_implementationOnly import struct CSystem.io_uring_sqe // XXX: this *really* shouldn't be here. oh well. extension UnsafeMutableRawPointer { @@ -124,7 +124,7 @@ extension IORingBuffer { } } -@inlinable @inline(__always) +@inline(__always) internal func _writeRequest( _ request: __owned RawIORequest, ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer @@ -137,7 +137,7 @@ internal func _writeRequest( return true } -@inlinable @inline(__always) +@inline(__always) internal func _blockingGetSubmissionEntry( ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer ) -> UnsafeMutablePointer< @@ -209,7 +209,7 @@ internal func _flushQueue(ring: borrowing SQRing) -> UInt32 { return _getUnconsumedSubmissionCount(ring: ring) } -@usableFromInline @inline(__always) +@inline(__always) internal func _getSubmissionEntry( ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer ) -> UnsafeMutablePointer< @@ -247,7 +247,7 @@ public struct IORing: ~Copyable { let completionRing: CQRing - @usableFromInline let submissionQueueEntries: UnsafeMutableBufferPointer + let submissionQueueEntries: UnsafeMutableBufferPointer // kept around for unmap / cleanup let ringSize: Int @@ -594,7 +594,7 @@ public struct IORing: ~Copyable { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } - @inlinable @inline(__always) + @inline(__always) public mutating func writeRequest(_ request: __owned IORequest) -> Bool { var raw: RawIORequest? = request.makeRawRequest() return _writeRequest( diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 5a1fd03..5b88499 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -1,9 +1,9 @@ // TODO: investigate @usableFromInline / @_implementationOnly dichotomy @_implementationOnly import CSystem -import struct CSystem.io_uring_sqe +@_implementationOnly import struct CSystem.io_uring_sqe public struct RawIORequest: ~Copyable { - @usableFromInline var rawValue: io_uring_sqe + var rawValue: io_uring_sqe public init() { self.rawValue = io_uring_sqe() From bb03f0fba3c480c3a625c9894b2f5dc32e9885c2 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 11 Feb 2025 22:33:10 +0000 Subject: [PATCH 025/102] Redesign registered resources API --- Sources/System/IORing.swift | 148 ++++++++++--------------- Tests/SystemTests/IORequestTests.swift | 6 +- 2 files changed, 60 insertions(+), 94 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 6dff66f..3305a9b 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -11,6 +11,12 @@ extension UnsafeMutableRawPointer { } } +extension UnsafeMutableRawBufferPointer { + func to_iovec() -> iovec { + iovec(iov_base: baseAddress, iov_len: count) + } +} + // all pointers in this struct reference kernel-visible memory @usableFromInline struct SQRing: ~Copyable { let kernelHead: UnsafePointer> @@ -46,67 +52,17 @@ struct CQRing: ~Copyable { let cqes: UnsafeBufferPointer } -internal final class ResourceManager: @unchecked Sendable { - typealias Resource = T - - struct Resources { - let resourceList: UnsafeMutableBufferPointer - var freeList: [Int] //TODO: bitvector? - } - - let mutex: Mutex - - init(_ res: UnsafeMutableBufferPointer) { - mutex = Mutex( - Resources( - resourceList: res, - freeList: [Int](res.indices) - )) - } - - func getResource() -> IOResource? { - mutex.withLock { resources in - if let index = resources.freeList.popLast() { - return IOResource( - resource: resources.resourceList[index], - index: index, - manager: self - ) - } else { - return nil - } - } - } - - func releaseResource(index: Int) { - mutex.withLock { resources in - resources.freeList.append(index) - } - } -} - -public class IOResource { +public struct IOResource { typealias Resource = T @usableFromInline let resource: T @usableFromInline let index: Int - let manager: ResourceManager internal init( resource: T, - index: Int, - manager: ResourceManager + index: Int ) { self.resource = resource self.index = index - self.manager = manager - } - - func withResource() { - - } - - deinit { - manager.releaseResource(index: self.index) } } @@ -253,8 +209,8 @@ public struct IORing: ~Copyable { let ringSize: Int let ringPtr: UnsafeMutableRawPointer - var registeredFiles: ResourceManager? - var registeredBuffers: ResourceManager? + var _registeredFiles: [UInt32]? + var _registeredBuffers: [iovec]? public init(queueDepth: UInt32) throws { var params = io_uring_params() @@ -517,11 +473,11 @@ public struct IORing: ~Copyable { //TODO: error handling } - public mutating func registerEventFD(ring: inout IORing, _ descriptor: FileDescriptor) throws { + public mutating func registerEventFD(_ descriptor: FileDescriptor) throws { var rawfd = descriptor.rawValue let result = withUnsafePointer(to: &rawfd) { fdptr in return io_uring_register( - ring.ringDescriptor, + ringDescriptor, IORING_REGISTER_EVENTFD, UnsafeMutableRawPointer(mutating: fdptr), 1 @@ -530,9 +486,9 @@ public struct IORing: ~Copyable { try handleRegistrationResult(result) } - public mutating func unregisterEventFD(ring: inout IORing) throws { + public mutating func unregisterEventFD() throws { let result = io_uring_register( - ring.ringDescriptor, + ringDescriptor, IORING_UNREGISTER_EVENTFD, nil, 0 @@ -540,50 +496,64 @@ public struct IORing: ~Copyable { try handleRegistrationResult(result) } - public mutating func registerFiles(count: UInt32) { - guard self.registeredFiles == nil else { fatalError() } - let fileBuf = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) - fileBuf.initialize(repeating: UInt32.max) - io_uring_register( - self.ringDescriptor, - IORING_REGISTER_FILES, - fileBuf.baseAddress!, - count - ) + public mutating func registerFileSlots(count: Int) { + precondition(_registeredFiles == nil) + precondition(count < UInt32.max) + let files = [UInt32](repeating: UInt32.max, count: count) + + let regResult = files.withUnsafeBufferPointer { bPtr in + io_uring_register( + self.ringDescriptor, + IORING_REGISTER_FILES, + UnsafeMutableRawPointer(mutating:bPtr.baseAddress!), + UInt32(truncatingIfNeeded: count) + ) + } + // TODO: error handling - self.registeredFiles = ResourceManager(fileBuf) + _registeredFiles = files } public func unregisterFiles() { fatalError("failed to unregister files") } - public func getFile() -> IORingFileSlot? { - return self.registeredFiles?.getResource() + public var registeredFileSlots: some RandomAccessCollection { + RegisteredResources(resources: _registeredFiles ?? []) } - public mutating func registerBuffers(bufSize: UInt32, count: UInt32) { - let iovecs = UnsafeMutableBufferPointer.allocate(capacity: Int(count)) - let intBufSize = Int(bufSize) - for i in 0.. IORingBuffer? { - return self.registeredBuffers?.getResource() + struct RegisteredResources: RandomAccessCollection { + let resources: [T] + + var startIndex: Int { 0 } + var endIndex: Int { resources.endIndex } + init(resources: [T]) { + self.resources = resources + } + subscript(position: Int) -> IOResource { + IOResource(resource: resources[position], index: position) + } + } + + public var registeredBuffers: some RandomAccessCollection { + RegisteredResources(resources: _registeredBuffers ?? []) } public func unregisterBuffers() { diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 78be4cf..e553a54 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -28,12 +28,8 @@ final class IORequestTests: XCTestCase { } func testOpenatFixedFile() throws { - // TODO: come up with a better way of getting a FileSlot. - let buf = UnsafeMutableBufferPointer.allocate(capacity: 2) - let resmgr = ResourceManager.init(buf) - let pathPtr = UnsafePointer(bitPattern: 0x414141410badf00d)! - let fileSlot = resmgr.getResource()! + let fileSlot: IORingFileSlot = IORingFileSlot(resource: UInt32.max, index: 0) let req = IORequest( opening: pathPtr, in: FileDescriptor(rawValue: -100), From a396967e3a77b780a78b733564137be7a8b4b7dc Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 11 Feb 2025 22:38:01 +0000 Subject: [PATCH 026/102] More registration tweaks --- Sources/System/IORing.swift | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 3305a9b..292303b 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -496,7 +496,7 @@ public struct IORing: ~Copyable { try handleRegistrationResult(result) } - public mutating func registerFileSlots(count: Int) { + public mutating func registerFileSlots(count: Int) -> some RandomAccessCollection { precondition(_registeredFiles == nil) precondition(count < UInt32.max) let files = [UInt32](repeating: UInt32.max, count: count) @@ -512,6 +512,7 @@ public struct IORing: ~Copyable { // TODO: error handling _registeredFiles = files + return registeredFileSlots } public func unregisterFiles() { @@ -522,9 +523,10 @@ public struct IORing: ~Copyable { RegisteredResources(resources: _registeredFiles ?? []) } - public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) { + public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) -> some RandomAccessCollection { precondition(buffers.count < UInt32.max) precondition(_registeredBuffers == nil) + //TODO: check if io_uring has preconditions it needs for the buffers (e.g. alignment) let iovecs = buffers.map { $0.to_iovec() } let regResult = iovecs.withUnsafeBufferPointer { bPtr in io_uring_register( @@ -537,6 +539,7 @@ public struct IORing: ~Copyable { // TODO: error handling _registeredBuffers = iovecs + return registeredBuffers } struct RegisteredResources: RandomAccessCollection { From d4ca4129a033c04efb863827e9178101434c44df Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 11 Feb 2025 23:01:33 +0000 Subject: [PATCH 027/102] Some renaming, and implement linked requests --- Sources/System/IORequest.swift | 4 ++-- Sources/System/IORing.swift | 19 +++++++++++++++++-- Sources/System/RawIORequest.swift | 9 +++++++-- Tests/SystemTests/IORingTests.swift | 2 +- 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 0e1a3b0..f406f5a 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -1,7 +1,7 @@ @_implementationOnly import struct CSystem.io_uring_sqe @usableFromInline -internal enum IORequestCore: ~Copyable { +internal enum IORequestCore { case nop // nothing here case openat( atDirectory: FileDescriptor, @@ -118,7 +118,7 @@ internal func makeRawRequest_readWrite_unregistered_slot( return request } -public struct IORequest : ~Copyable { +public struct IORequest { @usableFromInline var core: IORequestCore @inlinable internal consuming func extractCore() -> IORequestCore { diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 292303b..fab2f8e 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -567,13 +567,28 @@ public struct IORing: ~Copyable { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } - @inline(__always) - public mutating func writeRequest(_ request: __owned IORequest) -> Bool { + public mutating func prepare(request: __owned IORequest) -> Bool { var raw: RawIORequest? = request.makeRawRequest() return _writeRequest( raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } + //@inlinable //TODO: make sure the array allocation gets optimized out... + public mutating func prepare(linkedRequests: IORequest...) { + guard linkedRequests.count > 0 else { + return + } + let last = linkedRequests.last! + for req in linkedRequests.dropLast() { + var raw = req.makeRawRequest() + raw.linkToNextRequest() + _writeRequest( + raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) + } + _writeRequest( + last.makeRawRequest(), ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) + } + deinit { munmap(ringPtr, ringSize) munmap( diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 5b88499..40b7236 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -2,6 +2,7 @@ @_implementationOnly import CSystem @_implementationOnly import struct CSystem.io_uring_sqe +//TODO: make this internal public struct RawIORequest: ~Copyable { var rawValue: io_uring_sqe @@ -11,7 +12,7 @@ public struct RawIORequest: ~Copyable { } extension RawIORequest { - public enum Operation: UInt8 { + enum Operation: UInt8 { case nop = 0 case readv = 1 case writev = 2 @@ -53,7 +54,7 @@ extension RawIORequest { public static let skipSuccess = Flags(rawValue: 1 << 6) } - public var operation: Operation { + var operation: Operation { get { Operation(rawValue: rawValue.opcode)! } set { rawValue.opcode = newValue.rawValue } } @@ -63,6 +64,10 @@ extension RawIORequest { set { rawValue.flags = newValue.rawValue } } + public mutating func linkToNextRequest() { + flags = Flags(rawValue: flags.rawValue | Flags.linkRequest.rawValue) + } + public var fileDescriptor: FileDescriptor { get { FileDescriptor(rawValue: rawValue.fd) } set { rawValue.fd = newValue.rawValue } diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 2c25e2b..4ae12fc 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -13,7 +13,7 @@ final class IORingTests: XCTestCase { func testNop() throws { var ring = try IORing(queueDepth: 32) - ring.writeRequest(IORequest()) + ring.prepare(request: IORequest()) try ring.submitRequests() let completion = try ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) From 5bfed03c971a5440f8c5e8489466352be8c2f298 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 11 Feb 2025 23:27:03 +0000 Subject: [PATCH 028/102] Switch to static methods for constructing requests --- Sources/System/IORequest.swift | 96 +++++++++++--------------- Tests/SystemTests/IORequestTests.swift | 5 +- Tests/SystemTests/IORingTests.swift | 2 +- 3 files changed, 43 insertions(+), 60 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index f406f5a..4cdda76 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -127,127 +127,111 @@ public struct IORequest { } extension IORequest { - public init() { //TODO: why do we have nop? - core = .nop + public static func nop() -> IORequest { + IORequest(core: .nop) } - public init( - reading file: IORingFileSlot, + public static func reading(_ file: IORingFileSlot, into buffer: IORingBuffer, at offset: UInt64 = 0 - ) { - core = .readSlot(file: file, buffer: buffer, offset: offset) + ) -> IORequest { + IORequest(core: .readSlot(file: file, buffer: buffer, offset: offset)) } - public init( - reading file: FileDescriptor, + public static func reading(_ file: FileDescriptor, into buffer: IORingBuffer, at offset: UInt64 = 0 - ) { - core = .read(file: file, buffer: buffer, offset: offset) + ) -> IORequest { + IORequest(core: .read(file: file, buffer: buffer, offset: offset)) } - public init( - reading file: IORingFileSlot, + public static func reading(_ file: IORingFileSlot, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0 - ) { - core = .readUnregisteredSlot(file: file, buffer: buffer, offset: offset) + ) -> IORequest { + IORequest(core: .readUnregisteredSlot(file: file, buffer: buffer, offset: offset)) } - public init( - reading file: FileDescriptor, + public static func reading(_ file: FileDescriptor, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0 - ) { - core = .readUnregistered(file: file, buffer: buffer, offset: offset) + ) -> IORequest { + IORequest(core: .readUnregistered(file: file, buffer: buffer, offset: offset)) } - public init( - writing buffer: IORingBuffer, + public static func writing(_ buffer: IORingBuffer, into file: IORingFileSlot, at offset: UInt64 = 0 - ) { - core = .writeSlot(file: file, buffer: buffer, offset: offset) + ) -> IORequest { + IORequest(core: .writeSlot(file: file, buffer: buffer, offset: offset)) } - public init( - writing buffer: IORingBuffer, + public static func writing(_ buffer: IORingBuffer, into file: FileDescriptor, at offset: UInt64 = 0 - ) { - core = .write(file: file, buffer: buffer, offset: offset) + ) -> IORequest { + IORequest(core: .write(file: file, buffer: buffer, offset: offset)) } - public init( - writing buffer: UnsafeMutableRawBufferPointer, + public static func writing(_ buffer: UnsafeMutableRawBufferPointer, into file: IORingFileSlot, at offset: UInt64 = 0 - ) { - core = .writeUnregisteredSlot(file: file, buffer: buffer, offset: offset) + ) -> IORequest { + IORequest(core: .writeUnregisteredSlot(file: file, buffer: buffer, offset: offset)) } - public init( - writing buffer: UnsafeMutableRawBufferPointer, + public static func writing(_ buffer: UnsafeMutableRawBufferPointer, into file: FileDescriptor, at offset: UInt64 = 0 - ) { - core = .writeUnregistered(file: file, buffer: buffer, offset: offset) + ) -> IORequest { + IORequest(core: .writeUnregistered(file: file, buffer: buffer, offset: offset)) } - public init( - closing file: FileDescriptor - ) { - core = .close(file) + public static func closing(_ file: FileDescriptor) -> IORequest { + IORequest(core: .close(file)) } - public init( - closing file: IORingFileSlot - ) { - core = .closeSlot(file) + public static func closing(_ file: IORingFileSlot) -> IORequest { + IORequest(core: .closeSlot(file)) } - public init( - opening path: UnsafePointer, + public static func opening(_ path: UnsafePointer, in directory: FileDescriptor, into slot: IORingFileSlot, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil - ) { - core = .openatSlot(atDirectory: directory, path: path, mode, options: options, permissions: permissions, intoSlot: slot) + ) -> IORequest { + IORequest(core :.openatSlot(atDirectory: directory, path: path, mode, options: options, permissions: permissions, intoSlot: slot)) } - public init( - opening path: UnsafePointer, + public static func opening(_ path: UnsafePointer, in directory: FileDescriptor, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil - ) { - core = .openat(atDirectory: directory, path: path, mode, options: options, permissions: permissions) + ) -> IORequest { + IORequest(core: .openat(atDirectory: directory, path: path, mode, options: options, permissions: permissions)) } - public init( - opening path: FilePath, + public static func opening(_ path: FilePath, in directory: FileDescriptor, into slot: IORingFileSlot, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil - ) { + ) -> IORequest { fatalError("Implement me") } - public init( - opening path: FilePath, + public static func opening(_ path: FilePath, in directory: FileDescriptor, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil - ) { + ) -> IORequest { fatalError("Implement me") } diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index e553a54..f9f9580 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -19,7 +19,7 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] { // which are known to work correctly. final class IORequestTests: XCTestCase { func testNop() { - let req = IORequest().makeRawRequest() + let req = IORequest.nop().makeRawRequest() let sourceBytes = requestBytes(req) // convenient property of nop: it's all zeros! // for some unknown reason, liburing sets the fd field to -1. @@ -30,8 +30,7 @@ final class IORequestTests: XCTestCase { func testOpenatFixedFile() throws { let pathPtr = UnsafePointer(bitPattern: 0x414141410badf00d)! let fileSlot: IORingFileSlot = IORingFileSlot(resource: UInt32.max, index: 0) - let req = IORequest( - opening: pathPtr, + let req = IORequest.opening(pathPtr, in: FileDescriptor(rawValue: -100), into: fileSlot, mode: .readOnly, diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 4ae12fc..6421e0c 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -13,7 +13,7 @@ final class IORingTests: XCTestCase { func testNop() throws { var ring = try IORing(queueDepth: 32) - ring.prepare(request: IORequest()) + ring.prepare(request: IORequest.nop()) try ring.submitRequests() let completion = try ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) From 74366c33418fafe8268d225f56046590ef01d083 Mon Sep 17 00:00:00 2001 From: David Smith Date: Wed, 12 Feb 2025 20:18:51 +0000 Subject: [PATCH 029/102] Improve submit API --- Sources/System/IORing.swift | 15 ++++++++++++--- Tests/SystemTests/IORingTests.swift | 3 +-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index fab2f8e..e238fab 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -563,7 +563,7 @@ public struct IORing: ~Copyable { fatalError("failed to unregister buffers: TODO") } - public func submitRequests() throws { + public func submitPreparedRequests() throws { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } @@ -573,8 +573,7 @@ public struct IORing: ~Copyable { raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } - //@inlinable //TODO: make sure the array allocation gets optimized out... - public mutating func prepare(linkedRequests: IORequest...) { + mutating func prepare(linkedRequests: some BidirectionalCollection) { guard linkedRequests.count > 0 else { return } @@ -589,6 +588,16 @@ public struct IORing: ~Copyable { last.makeRawRequest(), ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } + //@inlinable //TODO: make sure the array allocation gets optimized out... + public mutating func prepare(linkedRequests: IORequest...) { + prepare(linkedRequests: linkedRequests) + } + + public mutating func submit(linkedRequests: IORequest...) throws { + prepare(linkedRequests: linkedRequests) + try submitPreparedRequests() + } + deinit { munmap(ringPtr, ringSize) munmap( diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 6421e0c..306516b 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -13,8 +13,7 @@ final class IORingTests: XCTestCase { func testNop() throws { var ring = try IORing(queueDepth: 32) - ring.prepare(request: IORequest.nop()) - try ring.submitRequests() + try ring.submit(linkedRequests: IORequest.nop()) let completion = try ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) } From 7f6e673750128d8b9a47934b83e0b0c523921b56 Mon Sep 17 00:00:00 2001 From: David Smith Date: Wed, 12 Feb 2025 23:43:29 +0000 Subject: [PATCH 030/102] Adjust registered resources API --- Sources/System/IORing.swift | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index e238fab..0500be0 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -53,7 +53,7 @@ struct CQRing: ~Copyable { } public struct IOResource { - typealias Resource = T + public typealias Resource = T @usableFromInline let resource: T @usableFromInline let index: Int @@ -496,7 +496,7 @@ public struct IORing: ~Copyable { try handleRegistrationResult(result) } - public mutating func registerFileSlots(count: Int) -> some RandomAccessCollection { + public mutating func registerFileSlots(count: Int) -> RegisteredResources { precondition(_registeredFiles == nil) precondition(count < UInt32.max) let files = [UInt32](repeating: UInt32.max, count: count) @@ -519,11 +519,11 @@ public struct IORing: ~Copyable { fatalError("failed to unregister files") } - public var registeredFileSlots: some RandomAccessCollection { + public var registeredFileSlots: RegisteredResources { RegisteredResources(resources: _registeredFiles ?? []) } - public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) -> some RandomAccessCollection { + public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) -> RegisteredResources { precondition(buffers.count < UInt32.max) precondition(_registeredBuffers == nil) //TODO: check if io_uring has preconditions it needs for the buffers (e.g. alignment) @@ -542,20 +542,23 @@ public struct IORing: ~Copyable { return registeredBuffers } - struct RegisteredResources: RandomAccessCollection { + public struct RegisteredResources: RandomAccessCollection { let resources: [T] - var startIndex: Int { 0 } - var endIndex: Int { resources.endIndex } + public var startIndex: Int { 0 } + public var endIndex: Int { resources.endIndex } init(resources: [T]) { self.resources = resources } - subscript(position: Int) -> IOResource { + public subscript(position: Int) -> IOResource { IOResource(resource: resources[position], index: position) } + public subscript(position: Int16) -> IOResource { + IOResource(resource: resources[Int(position)], index: Int(position)) + } } - public var registeredBuffers: some RandomAccessCollection { + public var registeredBuffers: RegisteredResources { RegisteredResources(resources: _registeredBuffers ?? []) } From 0c6ef16ca91cd82ab78a52a5cac83b113ba8e67d Mon Sep 17 00:00:00 2001 From: David Smith Date: Wed, 12 Feb 2025 23:45:18 +0000 Subject: [PATCH 031/102] Fix type --- Sources/System/IORing.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 0500be0..fb0c20a 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -553,7 +553,7 @@ public struct IORing: ~Copyable { public subscript(position: Int) -> IOResource { IOResource(resource: resources[position], index: position) } - public subscript(position: Int16) -> IOResource { + public subscript(position: UInt16) -> IOResource { IOResource(resource: resources[Int(position)], index: Int(position)) } } From a22e5f685866614a027ff4a394e2af71d4b412c8 Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 13 Feb 2025 22:09:42 +0000 Subject: [PATCH 032/102] Add a version of registerBuffers that isn't varargs --- Sources/System/IORing.swift | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index fb0c20a..b718991 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -496,16 +496,18 @@ public struct IORing: ~Copyable { try handleRegistrationResult(result) } - public mutating func registerFileSlots(count: Int) -> RegisteredResources { + public mutating func registerFileSlots(count: Int) -> RegisteredResources< + IORingFileSlot.Resource + > { precondition(_registeredFiles == nil) precondition(count < UInt32.max) - let files = [UInt32](repeating: UInt32.max, count: count) + let files = [UInt32](repeating: UInt32.max, count: count) let regResult = files.withUnsafeBufferPointer { bPtr in io_uring_register( self.ringDescriptor, IORING_REGISTER_FILES, - UnsafeMutableRawPointer(mutating:bPtr.baseAddress!), + UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), UInt32(truncatingIfNeeded: count) ) } @@ -523,7 +525,9 @@ public struct IORing: ~Copyable { RegisteredResources(resources: _registeredFiles ?? []) } - public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) -> RegisteredResources { + public mutating func registerBuffers(_ buffers: some Collection) + -> RegisteredResources + { precondition(buffers.count < UInt32.max) precondition(_registeredBuffers == nil) //TODO: check if io_uring has preconditions it needs for the buffers (e.g. alignment) @@ -542,6 +546,12 @@ public struct IORing: ~Copyable { return registeredBuffers } + public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) + -> RegisteredResources + { + registerBuffers(buffers) + } + public struct RegisteredResources: RandomAccessCollection { let resources: [T] @@ -588,7 +598,8 @@ public struct IORing: ~Copyable { raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } _writeRequest( - last.makeRawRequest(), ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) + last.makeRawRequest(), ring: &submissionRing, + submissionQueueEntries: submissionQueueEntries) } //@inlinable //TODO: make sure the array allocation gets optimized out... From 6983196ad6f980fde158811e13a828d70b7a93f0 Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 13 Feb 2025 23:31:06 +0000 Subject: [PATCH 033/102] Add unlinkAt support --- Sources/System/IORequest.swift | 14 ++++++++++++++ Sources/System/RawIORequest.swift | 1 + 2 files changed, 15 insertions(+) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 4cdda76..8705f0d 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -60,6 +60,10 @@ internal enum IORequestCore { ) case close(FileDescriptor) case closeSlot(IORingFileSlot) + case unlinkAt( + atDirectory: FileDescriptor, + path: UnsafePointer + ) } @inline(__always) @@ -235,6 +239,12 @@ extension IORequest { fatalError("Implement me") } + public static func unlinking(_ path: UnsafePointer, + in directory: FileDescriptor + ) -> IORequest { + IORequest(core: .unlinkAt(atDirectory: directory, path: path)) + } + @inline(__always) public consuming func makeRawRequest() -> RawIORequest { var request = RawIORequest() @@ -293,6 +303,10 @@ extension IORequest { case .closeSlot(let file): request.operation = .close request.rawValue.file_index = UInt32(file.index + 1) + case .unlinkAt(let atDirectory, let path): + request.operation = .unlinkAt + request.fileDescriptor = atDirectory + request.rawValue.addr = UInt64(UInt(bitPattern: path)) } return request } diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 40b7236..8f1a2b1 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -36,6 +36,7 @@ extension RawIORequest { // ... case openAt2 = 28 // ... + case unlinkAt = 36 } public struct Flags: OptionSet, Hashable, Codable { From 5ba137703c63791b5088ac44ef1ebd2662566d0a Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 13 Feb 2025 23:43:19 +0000 Subject: [PATCH 034/102] Dubious approach to this, but I want to try it out a bit --- Sources/System/RawIORequest.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 8f1a2b1..78f4f6d 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -101,6 +101,7 @@ extension RawIORequest { // TODO: cleanup? rawValue.addr = UInt64(Int(bitPattern: newValue.baseAddress!)) rawValue.len = UInt32(exactly: newValue.count)! + rawValue.user_data = rawValue.addr //TODO: this is kind of a hack, but I need to decide how best to get the buffer out on the other side } } From 006464963162f26a722f600b975a5ad5145e7150 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 14 Feb 2025 18:24:09 +0000 Subject: [PATCH 035/102] Turn on single issuer as an experiment --- Sources/System/IORing.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index b718991..5dd53d3 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -214,6 +214,7 @@ public struct IORing: ~Copyable { public init(queueDepth: UInt32) throws { var params = io_uring_params() + params.flags = IORING_SETUP_SINGLE_ISSUER //TODO make this configurable ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { return io_uring_setup(queueDepth, $0) From 901f4c80c48dd983ae87b115736f0589d6963b73 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 14 Feb 2025 18:25:46 +0000 Subject: [PATCH 036/102] Revert "Turn on single issuer as an experiment" This reverts commit 006464963162f26a722f600b975a5ad5145e7150. --- Sources/System/IORing.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 5dd53d3..b718991 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -214,7 +214,6 @@ public struct IORing: ~Copyable { public init(queueDepth: UInt32) throws { var params = io_uring_params() - params.flags = IORING_SETUP_SINGLE_ISSUER //TODO make this configurable ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { return io_uring_setup(queueDepth, $0) From 283e8d6b7b747f082ed2b7c9bd763229729d9d76 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 14 Feb 2025 18:26:31 +0000 Subject: [PATCH 037/102] Reapply "Turn on single issuer as an experiment" This reverts commit 901f4c80c48dd983ae87b115736f0589d6963b73. --- Sources/System/IORing.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index b718991..5dd53d3 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -214,6 +214,7 @@ public struct IORing: ~Copyable { public init(queueDepth: UInt32) throws { var params = io_uring_params() + params.flags = IORING_SETUP_SINGLE_ISSUER //TODO make this configurable ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { return io_uring_setup(queueDepth, $0) From d895f2a828f6c6c884057f43f0b14aa7fac10aff Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 14 Feb 2025 18:27:17 +0000 Subject: [PATCH 038/102] Revert "Reapply "Turn on single issuer as an experiment"" This reverts commit 283e8d6b7b747f082ed2b7c9bd763229729d9d76. --- Sources/System/IORing.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 5dd53d3..b718991 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -214,7 +214,6 @@ public struct IORing: ~Copyable { public init(queueDepth: UInt32) throws { var params = io_uring_params() - params.flags = IORING_SETUP_SINGLE_ISSUER //TODO make this configurable ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { return io_uring_setup(queueDepth, $0) From f3b8cc473dfb84705aaaa374d8385794ba4a5efe Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 28 Feb 2025 00:45:31 +0000 Subject: [PATCH 039/102] Actually consume events we waited for --- Sources/System/IORing.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index b718991..505f3e0 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -376,9 +376,9 @@ public struct IORing: ~Copyable { "fatal error in receiving requests: " + Errno(rawValue: -res).debugDescription ) - while let completion = _tryConsumeCompletion(ring: completionRing) { - try consumer(completion, nil, false) - } + } + while let completion = _tryConsumeCompletion(ring: completionRing) { + try consumer(completion, nil, false) } try consumer(nil, nil, true) } From d338de147879b044c636992b6fe892a4b90ac8fc Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 28 Feb 2025 00:49:31 +0000 Subject: [PATCH 040/102] Only get one completion if we asked for one completion --- Sources/System/IORing.swift | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 505f3e0..d459422 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -336,6 +336,7 @@ public struct IORing: ~Copyable { private func _blockingConsumeCompletionGuts( minimumCount: UInt32, + maximumCount: UInt32, extraArgs: UnsafeMutablePointer? = nil, consumer: (IOCompletion?, IORingError?, Bool) throws -> Void ) rethrows { @@ -343,6 +344,10 @@ public struct IORing: ~Copyable { while let completion = _tryConsumeCompletion(ring: completionRing) { count += 1 try consumer(completion, nil, false) + if count == maximumCount { + try consumer(nil, nil, true) + return + } } if count < minimumCount { @@ -377,8 +382,13 @@ public struct IORing: ~Copyable { + Errno(rawValue: -res).debugDescription ) } + var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { + count += 1 try consumer(completion, nil, false) + if count == maximumCount { + break + } } try consumer(nil, nil, true) } @@ -388,7 +398,7 @@ public struct IORing: ~Copyable { extraArgs: UnsafeMutablePointer? = nil ) throws -> IOCompletion { var result: IOCompletion? = nil - try _blockingConsumeCompletionGuts(minimumCount: 1, extraArgs: extraArgs) { + try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { (completion, error, done) in if let error { throw error @@ -440,10 +450,10 @@ public struct IORing: ~Copyable { ts: UInt64(UInt(bitPattern: tsPtr)) ) try _blockingConsumeCompletionGuts( - minimumCount: minimumCount, extraArgs: &args, consumer: consumer) + minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args, consumer: consumer) } } else { - try _blockingConsumeCompletionGuts(minimumCount: minimumCount, consumer: consumer) + try _blockingConsumeCompletionGuts(minimumCount: minimumCount, maximumCount: UInt32.max, consumer: consumer) } } From 5e2467325960b37a53b145fab6efc896ce9b1d6f Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 3 Mar 2025 21:53:26 +0000 Subject: [PATCH 041/102] Switch from unsafe pointers to FilePaths, using hacks --- Sources/System/IORequest.swift | 97 +++++++++++++++----------- Sources/System/RawIORequest.swift | 3 +- Tests/SystemTests/IORequestTests.swift | 2 +- 3 files changed, 58 insertions(+), 44 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 8705f0d..e09bd89 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -5,14 +5,14 @@ internal enum IORequestCore { case nop // nothing here case openat( atDirectory: FileDescriptor, - path: UnsafePointer, + path: FilePath, FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil ) case openatSlot( atDirectory: FileDescriptor, - path: UnsafePointer, + path: FilePath, FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, @@ -60,9 +60,9 @@ internal enum IORequestCore { ) case close(FileDescriptor) case closeSlot(IORingFileSlot) - case unlinkAt( + case unlinkAt( atDirectory: FileDescriptor, - path: UnsafePointer + path: FilePath ) } @@ -135,56 +135,64 @@ extension IORequest { IORequest(core: .nop) } - public static func reading(_ file: IORingFileSlot, + public static func reading( + _ file: IORingFileSlot, into buffer: IORingBuffer, at offset: UInt64 = 0 ) -> IORequest { IORequest(core: .readSlot(file: file, buffer: buffer, offset: offset)) } - public static func reading(_ file: FileDescriptor, + public static func reading( + _ file: FileDescriptor, into buffer: IORingBuffer, at offset: UInt64 = 0 ) -> IORequest { IORequest(core: .read(file: file, buffer: buffer, offset: offset)) } - public static func reading(_ file: IORingFileSlot, + public static func reading( + _ file: IORingFileSlot, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0 ) -> IORequest { IORequest(core: .readUnregisteredSlot(file: file, buffer: buffer, offset: offset)) } - public static func reading(_ file: FileDescriptor, + public static func reading( + _ file: FileDescriptor, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0 ) -> IORequest { IORequest(core: .readUnregistered(file: file, buffer: buffer, offset: offset)) } - public static func writing(_ buffer: IORingBuffer, + public static func writing( + _ buffer: IORingBuffer, into file: IORingFileSlot, at offset: UInt64 = 0 ) -> IORequest { IORequest(core: .writeSlot(file: file, buffer: buffer, offset: offset)) } - public static func writing(_ buffer: IORingBuffer, + public static func writing( + _ buffer: IORingBuffer, into file: FileDescriptor, at offset: UInt64 = 0 ) -> IORequest { IORequest(core: .write(file: file, buffer: buffer, offset: offset)) } - public static func writing(_ buffer: UnsafeMutableRawBufferPointer, + public static func writing( + _ buffer: UnsafeMutableRawBufferPointer, into file: IORingFileSlot, at offset: UInt64 = 0 ) -> IORequest { IORequest(core: .writeUnregisteredSlot(file: file, buffer: buffer, offset: offset)) } - public static func writing(_ buffer: UnsafeMutableRawBufferPointer, + public static func writing( + _ buffer: UnsafeMutableRawBufferPointer, into file: FileDescriptor, at offset: UInt64 = 0 ) -> IORequest { @@ -199,47 +207,35 @@ extension IORequest { IORequest(core: .closeSlot(file)) } - - public static func opening(_ path: UnsafePointer, + public static func opening( + _ path: FilePath, in directory: FileDescriptor, into slot: IORingFileSlot, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil ) -> IORequest { - IORequest(core :.openatSlot(atDirectory: directory, path: path, mode, options: options, permissions: permissions, intoSlot: slot)) + IORequest( + core: .openatSlot( + atDirectory: directory, path: path, mode, options: options, + permissions: permissions, intoSlot: slot)) } - public static func opening(_ path: UnsafePointer, + public static func opening( + _ path: FilePath, in directory: FileDescriptor, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil ) -> IORequest { - IORequest(core: .openat(atDirectory: directory, path: path, mode, options: options, permissions: permissions)) + IORequest( + core: .openat( + atDirectory: directory, path: path, mode, options: options, permissions: permissions + )) } - - public static func opening(_ path: FilePath, - in directory: FileDescriptor, - into slot: IORingFileSlot, - mode: FileDescriptor.AccessMode, - options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil - ) -> IORequest { - fatalError("Implement me") - } - - public static func opening(_ path: FilePath, - in directory: FileDescriptor, - mode: FileDescriptor.AccessMode, - options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil - ) -> IORequest { - fatalError("Implement me") - } - - public static func unlinking(_ path: UnsafePointer, + public static func unlinking( + _ path: FilePath, in directory: FileDescriptor ) -> IORequest { IORequest(core: .unlinkAt(atDirectory: directory, path: path)) @@ -251,20 +247,31 @@ extension IORequest { switch extractCore() { case .nop: request.operation = .nop - case .openatSlot(let atDirectory, let path, let mode, let options, let permissions, let fileSlot): + case .openatSlot( + let atDirectory, let path, let mode, let options, let permissions, let fileSlot): // TODO: use rawValue less request.operation = .openAt request.fileDescriptor = atDirectory - request.rawValue.addr = UInt64(UInt(bitPattern: path)) + request.rawValue.addr = UInt64( + UInt( + bitPattern: path.withPlatformString { ptr in + ptr //this is unsavory, but we keep it alive by storing path alongside it in the request + })) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 request.rawValue.file_index = UInt32(fileSlot.index + 1) + request.path = path case .openat(let atDirectory, let path, let mode, let options, let permissions): request.operation = .openAt request.fileDescriptor = atDirectory - request.rawValue.addr = UInt64(UInt(bitPattern: path)) + request.rawValue.addr = UInt64( + UInt( + bitPattern: path.withPlatformString { ptr in + ptr //this is unsavory, but we keep it alive by storing path alongside it in the request + })) request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 + request.path = path case .write(let file, let buffer, let offset): request.operation = .writeFixed return makeRawRequest_readWrite_registered( @@ -306,7 +313,13 @@ extension IORequest { case .unlinkAt(let atDirectory, let path): request.operation = .unlinkAt request.fileDescriptor = atDirectory - request.rawValue.addr = UInt64(UInt(bitPattern: path)) + request.rawValue.addr = UInt64( + UInt( + bitPattern: path.withPlatformString { ptr in + ptr //this is unsavory, but we keep it alive by storing path alongside it in the request + }) + ) + request.path = path } return request } diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 78f4f6d..980771c 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -4,7 +4,8 @@ //TODO: make this internal public struct RawIORequest: ~Copyable { - var rawValue: io_uring_sqe + var rawValue: io_uring_sqe + var path: FilePath? //buffer owner for the path pointer that the sqe may have public init() { self.rawValue = io_uring_sqe() diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index f9f9580..4aaf754 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -30,7 +30,7 @@ final class IORequestTests: XCTestCase { func testOpenatFixedFile() throws { let pathPtr = UnsafePointer(bitPattern: 0x414141410badf00d)! let fileSlot: IORingFileSlot = IORingFileSlot(resource: UInt32.max, index: 0) - let req = IORequest.opening(pathPtr, + let req = IORequest.opening(FilePath(platformString: pathPtr), in: FileDescriptor(rawValue: -100), into: fileSlot, mode: .readOnly, From 49dd7977ca34dc0ea40adcbd031586f4269819bc Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 3 Mar 2025 22:07:28 +0000 Subject: [PATCH 042/102] Add a combined "submit and consume" operation --- Sources/System/IORing.swift | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index d459422..1f223fa 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -450,10 +450,12 @@ public struct IORing: ~Copyable { ts: UInt64(UInt(bitPattern: tsPtr)) ) try _blockingConsumeCompletionGuts( - minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args, consumer: consumer) + minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args, + consumer: consumer) } } else { - try _blockingConsumeCompletionGuts(minimumCount: minimumCount, maximumCount: UInt32.max, consumer: consumer) + try _blockingConsumeCompletionGuts( + minimumCount: minimumCount, maximumCount: UInt32.max, consumer: consumer) } } @@ -590,6 +592,20 @@ public struct IORing: ~Copyable { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } + public func submitPreparedRequestsAndConsumeCompletions( + minimumCount: UInt32 = 1, + timeout: Duration? = nil, + consumer: (IOCompletion?, IORingError?, Bool) throws -> Void + ) throws { + //TODO: optimize this to one uring_enter + try submitPreparedRequests() + try blockingConsumeCompletions( + minimumCount: minimumCount, + timeout: timeout, + consumer: consumer + ) + } + public mutating func prepare(request: __owned IORequest) -> Bool { var raw: RawIORequest? = request.makeRawRequest() return _writeRequest( From 91155fd52772b5cb1cf6980461f4429f3301f0e9 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 3 Mar 2025 22:15:32 +0000 Subject: [PATCH 043/102] Plumb error handling through completion consumers --- Sources/System/IORing.swift | 12 ++++++++++-- Sources/System/IORingError.swift | 6 +++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 1f223fa..4525281 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -343,7 +343,11 @@ public struct IORing: ~Copyable { var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { count += 1 - try consumer(completion, nil, false) + if completion.result < 0 { + try consumer(nil, IORingError(completionResult: completion.result), false) + } else { + try consumer(completion, nil, false) + } if count == maximumCount { try consumer(nil, nil, true) return @@ -385,8 +389,12 @@ public struct IORing: ~Copyable { var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { count += 1 + if completion.result < 0 { + try consumer(nil, IORingError(completionResult: completion.result), false) + } else { try consumer(completion, nil, false) - if count == maximumCount { + } + if count == maximumCount { break } } diff --git a/Sources/System/IORingError.swift b/Sources/System/IORingError.swift index fda58bc..fbd70bc 100644 --- a/Sources/System/IORingError.swift +++ b/Sources/System/IORingError.swift @@ -2,5 +2,9 @@ public enum IORingError: Error, Equatable { case missingRequiredFeatures case operationCanceled - case unknown + case unknown(errorCode: Int) + + internal init(completionResult: Int32) { + self = .unknown(errorCode: Int(completionResult)) //TODO, flesh this out + } } From 9ad16c0aae9f005202eab849f1e6278179453238 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 3 Mar 2025 22:37:51 +0000 Subject: [PATCH 044/102] Plumb through userData --- Sources/System/IORequest.swift | 175 +++++++++++++++++++----------- Sources/System/RawIORequest.swift | 1 - 2 files changed, 114 insertions(+), 62 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index e09bd89..7b60206 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -8,7 +8,8 @@ internal enum IORequestCore { path: FilePath, FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil + permissions: FilePermissions? = nil, + userData: UInt64 = 0 ) case openatSlot( atDirectory: FileDescriptor, @@ -16,53 +17,69 @@ internal enum IORequestCore { FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, - intoSlot: IORingFileSlot + intoSlot: IORingFileSlot, + userData: UInt64 = 0 ) case read( file: FileDescriptor, buffer: IORingBuffer, - offset: UInt64 = 0 + offset: UInt64 = 0, + userData: UInt64 = 0 ) case readUnregistered( file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, - offset: UInt64 = 0 + offset: UInt64 = 0, + userData: UInt64 = 0 ) case readSlot( file: IORingFileSlot, buffer: IORingBuffer, - offset: UInt64 = 0 + offset: UInt64 = 0, + userData: UInt64 = 0 ) case readUnregisteredSlot( file: IORingFileSlot, buffer: UnsafeMutableRawBufferPointer, - offset: UInt64 = 0 + offset: UInt64 = 0, + userData: UInt64 = 0 ) case write( file: FileDescriptor, buffer: IORingBuffer, - offset: UInt64 = 0 + offset: UInt64 = 0, + userData: UInt64 = 0 ) case writeUnregistered( file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, - offset: UInt64 = 0 + offset: UInt64 = 0, + userData: UInt64 = 0 ) case writeSlot( file: IORingFileSlot, buffer: IORingBuffer, - offset: UInt64 = 0 + offset: UInt64 = 0, + userData: UInt64 = 0 ) case writeUnregisteredSlot( file: IORingFileSlot, buffer: UnsafeMutableRawBufferPointer, - offset: UInt64 = 0 + offset: UInt64 = 0, + userData: UInt64 = 0 + ) + case close( + FileDescriptor, + userData: UInt64 = 0 + ) + case closeSlot( + IORingFileSlot, + userData: UInt64 = 0 ) - case close(FileDescriptor) - case closeSlot(IORingFileSlot) case unlinkAt( atDirectory: FileDescriptor, - path: FilePath + path: FilePath, + userData: UInt64 = 0 ) } @@ -71,6 +88,7 @@ internal func makeRawRequest_readWrite_registered( file: FileDescriptor, buffer: IORingBuffer, offset: UInt64, + userData: UInt64 = 0, request: consuming RawIORequest ) -> RawIORequest { request.fileDescriptor = file @@ -85,6 +103,7 @@ internal func makeRawRequest_readWrite_registered_slot( file: IORingFileSlot, buffer: IORingBuffer, offset: UInt64, + userData: UInt64 = 0, request: consuming RawIORequest ) -> RawIORequest { request.rawValue.fd = Int32(exactly: file.index)! @@ -100,6 +119,7 @@ internal func makeRawRequest_readWrite_unregistered( file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, offset: UInt64, + userData: UInt64 = 0, request: consuming RawIORequest ) -> RawIORequest { request.fileDescriptor = file @@ -113,6 +133,7 @@ internal func makeRawRequest_readWrite_unregistered_slot( file: IORingFileSlot, buffer: UnsafeMutableRawBufferPointer, offset: UInt64, + userData: UInt64 = 0, request: consuming RawIORequest ) -> RawIORequest { request.rawValue.fd = Int32(exactly: file.index)! @@ -131,80 +152,101 @@ public struct IORequest { } extension IORequest { - public static func nop() -> IORequest { + public static func nop(userData: UInt64 = 0) -> IORequest { IORequest(core: .nop) } public static func reading( _ file: IORingFileSlot, into buffer: IORingBuffer, - at offset: UInt64 = 0 + at offset: UInt64 = 0, + userData: UInt64 = 0 ) -> IORequest { - IORequest(core: .readSlot(file: file, buffer: buffer, offset: offset)) + IORequest(core: .readSlot(file: file, buffer: buffer, offset: offset, userData: userData)) } public static func reading( _ file: FileDescriptor, into buffer: IORingBuffer, - at offset: UInt64 = 0 + at offset: UInt64 = 0, + userData: UInt64 = 0 ) -> IORequest { - IORequest(core: .read(file: file, buffer: buffer, offset: offset)) + IORequest(core: .read(file: file, buffer: buffer, offset: offset, userData: userData)) } public static func reading( _ file: IORingFileSlot, into buffer: UnsafeMutableRawBufferPointer, - at offset: UInt64 = 0 + at offset: UInt64 = 0, + userData: UInt64 = 0 ) -> IORequest { - IORequest(core: .readUnregisteredSlot(file: file, buffer: buffer, offset: offset)) + IORequest( + core: .readUnregisteredSlot( + file: file, buffer: buffer, offset: offset, userData: userData)) } public static func reading( _ file: FileDescriptor, into buffer: UnsafeMutableRawBufferPointer, - at offset: UInt64 = 0 + at offset: UInt64 = 0, + userData: UInt64 = 0 ) -> IORequest { - IORequest(core: .readUnregistered(file: file, buffer: buffer, offset: offset)) + IORequest( + core: .readUnregistered(file: file, buffer: buffer, offset: offset, userData: userData)) } public static func writing( _ buffer: IORingBuffer, into file: IORingFileSlot, - at offset: UInt64 = 0 + at offset: UInt64 = 0, + userData: UInt64 = 0 ) -> IORequest { - IORequest(core: .writeSlot(file: file, buffer: buffer, offset: offset)) + IORequest(core: .writeSlot(file: file, buffer: buffer, offset: offset, userData: userData)) } public static func writing( _ buffer: IORingBuffer, into file: FileDescriptor, - at offset: UInt64 = 0 + at offset: UInt64 = 0, + userData: UInt64 = 0 ) -> IORequest { - IORequest(core: .write(file: file, buffer: buffer, offset: offset)) + IORequest(core: .write(file: file, buffer: buffer, offset: offset, userData: userData)) } public static func writing( _ buffer: UnsafeMutableRawBufferPointer, into file: IORingFileSlot, - at offset: UInt64 = 0 + at offset: UInt64 = 0, + userData: UInt64 = 0 ) -> IORequest { - IORequest(core: .writeUnregisteredSlot(file: file, buffer: buffer, offset: offset)) + IORequest( + core: .writeUnregisteredSlot( + file: file, buffer: buffer, offset: offset, userData: userData)) } public static func writing( _ buffer: UnsafeMutableRawBufferPointer, into file: FileDescriptor, - at offset: UInt64 = 0 + at offset: UInt64 = 0, + userData: UInt64 = 0 ) -> IORequest { - IORequest(core: .writeUnregistered(file: file, buffer: buffer, offset: offset)) + IORequest( + core: .writeUnregistered(file: file, buffer: buffer, offset: offset, userData: userData) + ) } - public static func closing(_ file: FileDescriptor) -> IORequest { - IORequest(core: .close(file)) + public static func closing( + _ file: FileDescriptor, + userData: UInt64 = 0 + ) -> IORequest { + IORequest(core: .close(file, userData: userData)) } - public static func closing(_ file: IORingFileSlot) -> IORequest { - IORequest(core: .closeSlot(file)) + public static func closing( + _ file: IORingFileSlot, + userData: UInt64 = 0 + ) -> IORequest { + IORequest(core: .closeSlot(file, userData: userData)) } public static func opening( @@ -213,12 +255,13 @@ extension IORequest { into slot: IORingFileSlot, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil + permissions: FilePermissions? = nil, + userData: UInt64 = 0 ) -> IORequest { IORequest( core: .openatSlot( atDirectory: directory, path: path, mode, options: options, - permissions: permissions, intoSlot: slot)) + permissions: permissions, intoSlot: slot, userData: userData)) } public static func opening( @@ -226,19 +269,22 @@ extension IORequest { in directory: FileDescriptor, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil + permissions: FilePermissions? = nil, + userData: UInt64 = 0 ) -> IORequest { IORequest( core: .openat( - atDirectory: directory, path: path, mode, options: options, permissions: permissions + atDirectory: directory, path: path, mode, options: options, + permissions: permissions, userData: userData )) } public static func unlinking( _ path: FilePath, - in directory: FileDescriptor + in directory: FileDescriptor, + userData: UInt64 = 0 ) -> IORequest { - IORequest(core: .unlinkAt(atDirectory: directory, path: path)) + IORequest(core: .unlinkAt(atDirectory: directory, path: path, userData: userData)) } @inline(__always) @@ -248,7 +294,8 @@ extension IORequest { case .nop: request.operation = .nop case .openatSlot( - let atDirectory, let path, let mode, let options, let permissions, let fileSlot): + let atDirectory, let path, let mode, let options, let permissions, let fileSlot, + let userData): // TODO: use rawValue less request.operation = .openAt request.fileDescriptor = atDirectory @@ -261,7 +308,9 @@ extension IORequest { request.rawValue.len = permissions?.rawValue ?? 0 request.rawValue.file_index = UInt32(fileSlot.index + 1) request.path = path - case .openat(let atDirectory, let path, let mode, let options, let permissions): + request.rawValue.user_data = userData + case .openat( + let atDirectory, let path, let mode, let options, let permissions, let userData): request.operation = .openAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( @@ -272,45 +321,48 @@ extension IORequest { request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 request.path = path - case .write(let file, let buffer, let offset): + request.rawValue.user_data = userData + case .write(let file, let buffer, let offset, let userData): request.operation = .writeFixed return makeRawRequest_readWrite_registered( - file: file, buffer: buffer, offset: offset, request: request) - case .writeSlot(let file, let buffer, let offset): + file: file, buffer: buffer, offset: offset, userData: userData, request: request) + case .writeSlot(let file, let buffer, let offset, let userData): request.operation = .writeFixed return makeRawRequest_readWrite_registered_slot( - file: file, buffer: buffer, offset: offset, request: request) - case .writeUnregistered(let file, let buffer, let offset): + file: file, buffer: buffer, offset: offset, userData: userData, request: request) + case .writeUnregistered(let file, let buffer, let offset, let userData): request.operation = .write return makeRawRequest_readWrite_unregistered( - file: file, buffer: buffer, offset: offset, request: request) - case .writeUnregisteredSlot(let file, let buffer, let offset): + file: file, buffer: buffer, offset: offset, userData: userData, request: request) + case .writeUnregisteredSlot(let file, let buffer, let offset, let userData): request.operation = .write return makeRawRequest_readWrite_unregistered_slot( - file: file, buffer: buffer, offset: offset, request: request) - case .read(let file, let buffer, let offset): + file: file, buffer: buffer, offset: offset, userData: userData, request: request) + case .read(let file, let buffer, let offset, let userData): request.operation = .readFixed return makeRawRequest_readWrite_registered( - file: file, buffer: buffer, offset: offset, request: request) - case .readSlot(let file, let buffer, let offset): + file: file, buffer: buffer, offset: offset, userData: userData, request: request) + case .readSlot(let file, let buffer, let offset, let userData): request.operation = .readFixed return makeRawRequest_readWrite_registered_slot( - file: file, buffer: buffer, offset: offset, request: request) - case .readUnregistered(let file, let buffer, let offset): + file: file, buffer: buffer, offset: offset, userData: userData, request: request) + case .readUnregistered(let file, let buffer, let offset, let userData): request.operation = .read return makeRawRequest_readWrite_unregistered( - file: file, buffer: buffer, offset: offset, request: request) - case .readUnregisteredSlot(let file, let buffer, let offset): + file: file, buffer: buffer, offset: offset, userData: userData, request: request) + case .readUnregisteredSlot(let file, let buffer, let offset, let userData): request.operation = .read return makeRawRequest_readWrite_unregistered_slot( - file: file, buffer: buffer, offset: offset, request: request) - case .close(let file): + file: file, buffer: buffer, offset: offset, userData: userData, request: request) + case .close(let file, let userData): request.operation = .close request.fileDescriptor = file - case .closeSlot(let file): + request.rawValue.user_data = userData + case .closeSlot(let file, let userData): request.operation = .close request.rawValue.file_index = UInt32(file.index + 1) - case .unlinkAt(let atDirectory, let path): + request.rawValue.user_data = userData + case .unlinkAt(let atDirectory, let path, let userData): request.operation = .unlinkAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( @@ -320,6 +372,7 @@ extension IORequest { }) ) request.path = path + request.rawValue.user_data = userData } return request } diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 980771c..50c97c6 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -102,7 +102,6 @@ extension RawIORequest { // TODO: cleanup? rawValue.addr = UInt64(Int(bitPattern: newValue.baseAddress!)) rawValue.len = UInt32(exactly: newValue.count)! - rawValue.user_data = rawValue.addr //TODO: this is kind of a hack, but I need to decide how best to get the buffer out on the other side } } From 880ec9086e0517cd8a90e1f58588cfcebdcec487 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 3 Mar 2025 22:51:35 +0000 Subject: [PATCH 045/102] Add a pointer convenience for getting the user data --- Sources/System/IOCompletion.swift | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index 1702f9e..9b41214 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -23,19 +23,25 @@ extension IOCompletion { extension IOCompletion { public var userData: UInt64 { //TODO: naming? get { - return rawValue.user_data + rawValue.user_data + } + } + + public var userPointer: UnsafeRawPointer? { + get { + UnsafeRawPointer(bitPattern: UInt(rawValue.user_data)) } } public var result: Int32 { get { - return rawValue.res + rawValue.res } } public var flags: IOCompletion.Flags { get { - return Flags(rawValue: rawValue.flags & 0x0000FFFF) + Flags(rawValue: rawValue.flags & 0x0000FFFF) } } From 48455a913557acf7e7e5f0b7a209e7b6fa9a2c6a Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 3 Mar 2025 23:04:52 +0000 Subject: [PATCH 046/102] Fix plumbing --- Sources/System/IORequest.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 7b60206..1eed6ed 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -95,6 +95,7 @@ internal func makeRawRequest_readWrite_registered( request.buffer = buffer.unsafeBuffer request.rawValue.buf_index = UInt16(exactly: buffer.index)! request.offset = offset + request.rawValue.user_data = userData return request } @@ -111,10 +112,11 @@ internal func makeRawRequest_readWrite_registered_slot( request.buffer = buffer.unsafeBuffer request.rawValue.buf_index = UInt16(exactly: buffer.index)! request.offset = offset + request.rawValue.user_data = userData return request } -@inlinable @inline(__always) +@inline(__always) internal func makeRawRequest_readWrite_unregistered( file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, @@ -125,6 +127,7 @@ internal func makeRawRequest_readWrite_unregistered( request.fileDescriptor = file request.buffer = buffer request.offset = offset + request.rawValue.user_data = userData return request } @@ -140,6 +143,7 @@ internal func makeRawRequest_readWrite_unregistered_slot( request.flags = .fixedFile request.buffer = buffer request.offset = offset + request.rawValue.user_data = userData return request } From 72c316ba86750e2cd3e223afd8ee698795e4efe0 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 3 Mar 2025 23:59:36 +0000 Subject: [PATCH 047/102] Make completions noncopyable again --- Sources/System/IOCompletion.swift | 3 +-- Sources/System/IORing.swift | 14 +++++++------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index 9b41214..ee81797 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -1,7 +1,6 @@ @_implementationOnly import CSystem -//TODO: should be ~Copyable, but requires UnsafeContinuation add ~Copyable support -public struct IOCompletion { +public struct IOCompletion: ~Copyable { let rawValue: io_uring_cqe } diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 4525281..79840c1 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -338,7 +338,7 @@ public struct IORing: ~Copyable { minimumCount: UInt32, maximumCount: UInt32, extraArgs: UnsafeMutablePointer? = nil, - consumer: (IOCompletion?, IORingError?, Bool) throws -> Void + consumer: (consuming IOCompletion?, IORingError?, Bool) throws -> Void ) rethrows { var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { @@ -407,15 +407,15 @@ public struct IORing: ~Copyable { ) throws -> IOCompletion { var result: IOCompletion? = nil try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { - (completion, error, done) in + (completion: consuming IOCompletion?, error, done) in if let error { throw error } - if let completion { - result = completion + if let completion { + result = consume completion } } - return result.unsafelyUnwrapped + return result.take()! } public func blockingConsumeCompletion( @@ -443,7 +443,7 @@ public struct IORing: ~Copyable { public func blockingConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (IOCompletion?, IORingError?, Bool) throws -> Void + consumer: (consuming IOCompletion?, IORingError?, Bool) throws -> Void ) throws { if let timeout { var ts = __kernel_timespec( @@ -603,7 +603,7 @@ public struct IORing: ~Copyable { public func submitPreparedRequestsAndConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (IOCompletion?, IORingError?, Bool) throws -> Void + consumer: (consuming IOCompletion?, IORingError?, Bool) throws -> Void ) throws { //TODO: optimize this to one uring_enter try submitPreparedRequests() From 7fff872441b6acb03bb8922300c09ef5f2afae2b Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 6 Mar 2025 12:09:57 -0800 Subject: [PATCH 048/102] Add the draft proposal so I can link to it --- NNNN-swift-system-io-uring.md | 434 ++++++++++++++++++++++++++++++++++ 1 file changed, 434 insertions(+) create mode 100644 NNNN-swift-system-io-uring.md diff --git a/NNNN-swift-system-io-uring.md b/NNNN-swift-system-io-uring.md new file mode 100644 index 0000000..9b0eb1d --- /dev/null +++ b/NNNN-swift-system-io-uring.md @@ -0,0 +1,434 @@ +# IORing, a Swift System API for io_uring + +* Proposal: [SE-NNNN](NNNN-filename.md) +* Authors: [Lucy Satheesan](https://github.com/oxy), [David Smith](https://github.com/Catfish-Man/) +* Review Manager: TBD +* Status: **Awaiting implementation** +* Implementation: [apple/swift-system#208](https://github.com/apple/swift-system/pull/208) + +## Introduction + +`io_uring` is Linux's solution to asynchronous and batched syscalls, with a particular focus on IO. We propose a low-level Swift API for it in Swift System that could either be used directly by projects with unusual needs, or via intermediaries like Swift NIO, to address scalability and thread pool starvation issues. + +## Motivation + +Up until recently, the overwhelmingly dominant file IO syscalls on major Unix platforms have been synchronous, e.g. `read(2)`. This design is very simple and proved sufficient for many uses for decades, but is less than ideal for Swift's needs in a few major ways: + +1. Requiring an entire OS thread for each concurrent operation imposes significant memory overhead +2. Requiring a separate syscall for each operation imposes significant CPU/time overhead to switch into and out of kernel mode repeatedly. This has been exacerbated in recent years by mitigations for the Spectre family of security exploits increasing the cost of syscalls. +3. Swift's N:M coroutine-on-thread-pool concurrency model assumes that threads will not be blocked. Each thread waiting for a syscall means a CPU core being left idle. In practice systems like NIO that deal in highly concurrent IO have had to work around this by providing their own thread pools. + +Non-file IO (network, pipes, etc…) has been in a somewhat better place with `epoll` and `kqueue` for asynchronously waiting for readability, but syscall overhead remains a significant issue for highly scalable systems. + +With the introduction of `io_uring` in 2019, Linux now has the kernel level tools to address these three problems directly. However, `io_uring` is quite complex and maps poorly into Swift. We expect that by providing a Swift interface to it, we can enable Swift on Linux servers to scale better and be more efficient than it has been in the past. + +## Proposed solution + +`struct IORing: ~Copyable` provides facilities for + +* Registering and unregistering resources (files and buffers), an `io_uring` specific variation on Unix file descriptors that improves their efficiency +* Registering and unregistering eventfds, which allow asynchronous waiting for completions +* Enqueueing IO requests +* Dequeueing IO completions + +`class IOResource` represents, via its two typealiases `IORingFileSlot` and `IORingBuffer`, registered file descriptors and buffers. Ideally we'd express the lifetimes of these as being dependent on the lifetime of the ring, but so far that's proven intractable, so we use a reference type. We expect that the up-front overhead of this should be negligible for larger operations, and smaller or one-shot operations can use non-registered buffers and file descriptors. + +`struct IORequest: ~Copyable` represents an IO operation that can be enqueued for the kernel to execute. It supports a wide variety of operations matching traditional unix file and socket operations. + +IORequest operations are expressed as overloaded static methods on `IORequest`, e.g. `openat` is spelled + +```swift + public static func opening( + _ path: FilePath, + in directory: FileDescriptor, + into slot: IORingFileSlot, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil, + context: UInt64 = 0 + ) -> IORequest + + public static func opening( + _ path: FilePath, + in directory: FileDescriptor, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil, + context: UInt64 = 0 + ) -> IORequest +``` + +which allows clients to decide whether they want to open the file into a slot on the ring, or have it return a file descriptor via a completion. Similarly, read operations have overloads for "use a buffer from the ring" or "read into this `UnsafeMutableBufferPointer`" + +Multiple `IORequests` can be enqueued on a single `IORing` using the `prepare(…)` family of methods, and then submitted together using `submitPreparedRequests`, allowing for things like "open this file, read its contents, and then close it" to be a single syscall. Conveniences are provided for preparing and submitting requests in one call. + +Since IO operations can execute in parallel or out of order by default, linked chains of operations can be established with `prepare(linkedRequests:…)` and related methods. Separate chains can still execute in parallel, and if an operation early in the chain fails, all subsequent operations will deliver cancellation errors as their completion. + +Already-completed results can be retrieved from the ring using `tryConsumeCompletion`, which never waits but may return nil, or `blockingConsumeCompletion(timeout:)`, which synchronously waits (up to an optional timeout) until an operation completes. There's also a bulk version of `blockingConsumeCompletion`, which may reduce the number of syscalls issued. It takes a closure which will be called repeatedly as completions are available (see Future Directions for potential improvements to this API). + +Since neither polling nor synchronously waiting is optimal in many cases, `IORing` also exposes the ability to register an eventfd (see `man eventfd(2)`), which will become readable when completions are available on the ring. This can then be monitored asynchronously with `epoll`, `kqueue`, or for clients who are linking libdispatch, `DispatchSource`. + +`struct IOCompletion: ~Copyable` represents the result of an IO operation and provides + +* Flags indicating various operation-specific metadata about the now-completed syscall +* The context associated with the operation when it was enqueued, as an `UnsafeRawPointer` or a `UInt64` +* The result of the operation, as an `Int32` with operation-specific meaning +* The error, if one occurred + +Unfortunately the underlying kernel API makes it relatively difficult to determine which `IORequest` led to a given `IOCompletion`, so it's expected that users will need to create this association themselves via the context parameter. + +`IORingError` represents failure of an operation. + +`IORing.Features` describes the supported features of the underlying kernel `IORing` implementation, which can be used to provide graceful reduction in functionality when running on older systems. + +## Detailed design + +```swift +public class IOResource { } +public typealias IORingFileSlot = IOResource +public typealias IORingBuffer = IOResource + +extension IORingBuffer { + public var unsafeBuffer: UnsafeMutableRawBufferPointer +} + +// IORing is intentionally not Sendable, to avoid internal locking overhead +public struct IORing: ~Copyable { + + public init(queueDepth: UInt32) throws(IORingError) + + public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(IORingError) + public mutating func unregisterEventFD(_ descriptor: FileDescriptor) throws(IORingError) + + // An IORing.RegisteredResources is a view into the buffers or files registered with the ring, if any + public struct RegisteredResources: RandomAccessCollection { + public subscript(position: Int) -> IOResource + public subscript(position: UInt16) -> IOResource // This is useful because io_uring likes to use UInt16s as indexes + } + + public mutating func registerFileSlots(count: Int) throws(IORingError) -> RegisteredResources + + public func unregisterFiles() + + public var registeredFileSlots: RegisteredResources + + public mutating func registerBuffers( + _ buffers: some Collection + ) throws(IORingError) -> RegisteredResources + + public mutating func registerBuffers( + _ buffers: UnsafeMutableRawBufferPointer... + ) throws(IORingError) -> RegisteredResources + + public func unregisterBuffers() + + public var registeredBuffers: RegisteredResources + + public func prepare(requests: IORequest...) + public func prepare(linkedRequests: IORequest...) + + public func submitPreparedRequests(timeout: Duration? = nil) throws(IORingError) + public func submit(requests: IORequest..., timeout: Duration? = nil) throws(IORingError) + public func submit(linkedRequests: IORequest..., timeout: Duration? = nil) throws(IORingError) + + public func submitPreparedRequests() throws(IORingError) + public func submitPreparedRequestsAndWait(timeout: Duration? = nil) throws(IORingError) + + public func submitPreparedRequestsAndConsumeCompletions( + minimumCount: UInt32 = 1, + timeout: Duration? = nil, + consumer: (consuming IOCompletion?, IORingError?, Bool) throws(E) -> Void + ) throws(E) + + public func blockingConsumeCompletion( + timeout: Duration? = nil + ) throws(IORingError) -> IOCompletion + + public func blockingConsumeCompletions( + minimumCount: UInt32 = 1, + timeout: Duration? = nil, + consumer: (consuming IOCompletion?, IORingError?, Bool) throws(E) -> Void + ) throws(E) + + public func tryConsumeCompletion() -> IOCompletion? + + public struct Features { + //IORING_FEAT_SINGLE_MMAP is handled internally + public var nonDroppingCompletions: Bool //IORING_FEAT_NODROP + public var stableSubmissions: Bool //IORING_FEAT_SUBMIT_STABLE + public var currentFilePosition: Bool //IORING_FEAT_RW_CUR_POS + public var assumingTaskCredentials: Bool //IORING_FEAT_CUR_PERSONALITY + public var fastPolling: Bool //IORING_FEAT_FAST_POLL + public var epoll32BitFlags: Bool //IORING_FEAT_POLL_32BITS + public var pollNonFixedFiles: Bool //IORING_FEAT_SQPOLL_NONFIXED + public var extendedArguments: Bool //IORING_FEAT_EXT_ARG + public var nativeWorkers: Bool //IORING_FEAT_NATIVE_WORKERS + public var resourceTags: Bool //IORING_FEAT_RSRC_TAGS + public var allowsSkippingSuccessfulCompletions: Bool //IORING_FEAT_CQE_SKIP + public var improvedLinkedFiles: Bool //IORING_FEAT_LINKED_FILE + public var registerRegisteredRings: Bool //IORING_FEAT_REG_REG_RING + public var minimumTimeout: Bool //IORING_FEAT_MIN_TIMEOUT + public var bundledSendReceive: Bool //IORING_FEAT_RECVSEND_BUNDLE + } + public static var supportedFeatures: Features +} + +public struct IORequest: ~Copyable { + public static func nop(context: UInt64 = 0) -> IORequest + + // overloads for each combination of registered vs unregistered buffer/descriptor + // Read + public static func reading( + _ file: IORingFileSlot, + into buffer: IORingBuffer, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> IORequest + + public static func reading( + _ file: FileDescriptor, + into buffer: IORingBuffer, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> IORequest + + public static func reading( + _ file: IORingFileSlot, + into buffer: UnsafeMutableRawBufferPointer, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> IORequest + + public static func reading( + _ file: FileDescriptor, + into buffer: UnsafeMutableRawBufferPointer, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> IORequest + + // Write + public static func writing( + _ buffer: IORingBuffer, + into file: IORingFileSlot, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> IORequest + + public static func writing( + _ buffer: IORingBuffer, + into file: FileDescriptor, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> IORequest + + public static func writing( + _ buffer: UnsafeMutableRawBufferPointer, + into file: IORingFileSlot, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> IORequest + + public static func writing( + _ buffer: UnsafeMutableRawBufferPointer, + into file: FileDescriptor, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> IORequest + + // Close + public static func closing( + _ file: FileDescriptor, + context: UInt64 = 0 + ) -> IORequest + + public static func closing( + _ file: IORingFileSlot, + context: UInt64 = 0 + ) -> IORequest + + // Open At + public static func opening( + _ path: FilePath, + in directory: FileDescriptor, + into slot: IORingFileSlot, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil, + context: UInt64 = 0 + ) -> IORequest + + public static func opening( + _ path: FilePath, + in directory: FileDescriptor, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil, + context: UInt64 = 0 + ) -> IORequest + + public static func unlinking( + _ path: FilePath, + in directory: FileDescriptor, + context: UInt64 = 0 + ) -> IORequest + + // Other operations follow in the same pattern +} + +public struct IOCompletion { + + public struct Flags: OptionSet, Hashable, Codable { + public let rawValue: UInt32 + + public init(rawValue: UInt32) + + public static let moreCompletions: Flags + public static let socketNotEmpty: Flags + public static let isNotificationEvent: Flags + } + + //These are both the same value, but having both eliminates some ugly casts in client code + public var context: UInt64 + public var contextPointer: UnsafeRawPointer + + public var result: Int32 + + public var error: IORingError? // Convenience wrapper over `result` + + public var flags: Flags +} + +public struct IORingError: Error, Equatable { + static var missingRequiredFeatures: IORingError + static var operationCanceled: IORingError + static var timedOut: IORingError + static var resourceRegistrationFailed: IORingError + // Other error values to be filled out as the set of supported operations expands in the future + static var unknown: IORingError(errorCode: Int) +} + +``` + +## Usage Examples + +### Blocking + +```swift +let ring = try IORing(queueDepth: 2) + +//Make space on the ring for our file (this is optional, but improves performance with repeated use) +let file = ring.registerFiles(count: 1)[0] + +var statInfo = Glibc.stat() // System doesn't have an abstraction for stat() right now +// Build our requests to open the file and find out how big it is +ring.prepare(linkedRequests: + .opening(path, + in: parentDirectory, + into: file, + mode: mode, + options: openOptions, + permissions: nil + ), + .readingMetadataOf(file, + into: &statInfo + ) +) +//batch submit 2 syscalls in 1! +try ring.submitPreparedRequestsAndConsumeCompletions(minimumCount: 2) { (completion: consuming IOCompletion?, error, done) in + if let error { + throw error //or other error handling as desired + } +} + +// We could register our buffer with the ring too, but we're only using it once +let buffer = UnsafeMutableRawBufferPointer.allocate(Int(statInfo.st_size)) + +// Build our requests to read the file and close it +ring.prepare(linkedRequests: + .reading(file, + into: buffer + ), + .closing(file) +) + +//batch submit 2 syscalls in 1! +try ring.submitPreparedRequestsAndConsumeCompletions(minimumCount: 2) { (completion: consuming IOCompletion?, error, done) in + if let error { + throw error //or other error handling as desired + } +} + +processBuffer(buffer) +``` + +### Using libdispatch to wait for the read asynchronously + +```swift +//Initial setup as above up through creating buffer, omitted for brevity + +//Make the read request with a context so we can get the buffer out of it in the completion handler +… +.reading(file, into: buffer, context: UInt64(buffer.baseAddress!)) +… + +// Make an eventfd and register it with the ring +let eventfd = eventfd(0, 0) +ring.registerEventFD(eventfd) + +// Make a read source to monitor the eventfd for readability +let readabilityMonitor = DispatchSource.makeReadSource(fileDescriptor: eventfd) +readabilityMonitor.setEventHandler { + let completion = ring.blockingConsumeCompletion() + if let error = completion.error { + //handle failure to read the file + } + processBuffer(completion.contextPointer) +} +readabilityMonitor.activate() + +ring.submitPreparedRequests //note, not "AndConsumeCompletions" this time +``` + +## Source compatibility + +This is an all-new API in Swift System, so has no backwards compatibility implications. Of note, though, this API is only available on Linux. + +## ABI compatibility + +Swift on Linux does not have a stable ABI, and we will likely take advantage of this to evolve IORing as compiler support improves, as described in Future Directions. + +## Implications on adoption + +This feature is intrinsically linked to Linux kernel support, so constrains the deployment target of anything that adopts it to newer kernels. Exactly which features of the evolving io_uring syscall surface area we need is under consideration. + +## Future directions + +* While most Swift users on Darwin are not limited by IO scalability issues, the thread pool considerations still make introducing something similar to this appealing if and when the relevant OS support is available. We should attempt to the best of our ability to not design this in a way that's gratuitously incompatible with non-Linux OSs, although Swift System does not attempt to have an API that's identical on all platforms. +* The set of syscalls covered by `io_uring` has grown significantly and is still growing. We should leave room for supporting additional operations in the future. +* Once same-element requirements and pack counts as integer generic arguments are supported by the compiler, we should consider adding something along the lines of the following to allow preparing, submitting, and waiting for an entire set of operations at once: + +``` +func submitLinkedRequestsAndWait( + _ requests: repeat each Request +) where Request == IORequest + -> InlineArray<(repeat each Request).count, IOCompletion> +``` +* Once mutable borrows are supported, we should consider replacing the closure-taking bulk completion APIs (e.g. `blockingConsumeCompletions(…)`) with ones that return a sequence of completions instead +* We should consider making more types noncopyable as compiler support improves +* liburing has a "peek next completion" operation that doesn't consume it, and then a "mark consumed" operation. We may want to add something similar +* liburing has support for operations allocating their own buffers and returning them via the completion, we may want to support this +* We may want to provide API for asynchronously waiting, rather than just exposing the eventfd to let people roll their own async waits. Doing this really well has *considerable* implications for the concurrency runtime though. +* We should almost certainly expose API for more of the configuration options in `io_uring_setup` +* The API for feature probing is functional but not especially nice. Finding a better way to present that concept would be desirable. + +## Alternatives considered + +* We could use a NIO-style separate thread pool, but we believe `io_uring` is likely a better option for scalability. We may still want to provide a thread-pool backed version as an option, because many Linux systems currently disable `io_uring` due to security concerns. +* We could multiplex all IO onto a single actor as `AsyncBytes` currently does, but this has a number of downsides that make it entirely unsuitable to server usage. Most notably, it eliminates IO parallelism entirely. +* Using POSIX AIO instead of or as well as io_uring would greatly increase our ability to support older kernels and other Unix systems, but it has well-documented performance and usability issues that have prevented its adoption elsewhere, and apply just as much to Swift. +* Earlier versions of this proposal had higher level "managed" abstractions over IORing. These have been removed due to lack of interest from clients, but could be added back later if needed. +* I considered making any or all of `IORingError`, `IOCompletion`, and `IORequest` nested struct declarations inside `IORing`. The main reason I haven't done so is I was a little concerned about the ambiguity of having a type called `Error`. I'd be particularly interested in feedback on this choice. + +## Acknowledgments + +The NIO team, in particular Cory Benfield and Franz Busch, have provided invaluable feedback and direction on this project. From 0e652c4d25adfda3e40e1001357261cfabbc93ef Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 4 Apr 2025 16:42:33 -0700 Subject: [PATCH 049/102] Naming updates, cancellation support, IOResources are structs now, other editorial updates --- NNNN-swift-system-io-uring.md | 117 ++++++++++++++++++++++------------ 1 file changed, 77 insertions(+), 40 deletions(-) diff --git a/NNNN-swift-system-io-uring.md b/NNNN-swift-system-io-uring.md index 9b0eb1d..5c08588 100644 --- a/NNNN-swift-system-io-uring.md +++ b/NNNN-swift-system-io-uring.md @@ -15,7 +15,7 @@ Up until recently, the overwhelmingly dominant file IO syscalls on major Unix platforms have been synchronous, e.g. `read(2)`. This design is very simple and proved sufficient for many uses for decades, but is less than ideal for Swift's needs in a few major ways: 1. Requiring an entire OS thread for each concurrent operation imposes significant memory overhead -2. Requiring a separate syscall for each operation imposes significant CPU/time overhead to switch into and out of kernel mode repeatedly. This has been exacerbated in recent years by mitigations for the Spectre family of security exploits increasing the cost of syscalls. +2. Requiring a separate syscall for each operation imposes significant CPU/time overhead to switch into and out of kernel mode repeatedly. This has been exacerbated in recent years by mitigations for the Meltdown family of security exploits increasing the cost of syscalls. 3. Swift's N:M coroutine-on-thread-pool concurrency model assumes that threads will not be blocked. Each thread waiting for a syscall means a CPU core being left idle. In practice systems like NIO that deal in highly concurrent IO have had to work around this by providing their own thread pools. Non-file IO (network, pipes, etc…) has been in a somewhat better place with `epoll` and `kqueue` for asynchronously waiting for readability, but syscall overhead remains a significant issue for highly scalable systems. @@ -24,6 +24,8 @@ With the introduction of `io_uring` in 2019, Linux now has the kernel level tool ## Proposed solution +We propose a *low level, unopinionated* Swift interface for io_uring on Linux (see Future Directions for discussion of possible more abstract interfaces). + `struct IORing: ~Copyable` provides facilities for * Registering and unregistering resources (files and buffers), an `io_uring` specific variation on Unix file descriptors that improves their efficiency @@ -31,14 +33,14 @@ With the introduction of `io_uring` in 2019, Linux now has the kernel level tool * Enqueueing IO requests * Dequeueing IO completions -`class IOResource` represents, via its two typealiases `IORingFileSlot` and `IORingBuffer`, registered file descriptors and buffers. Ideally we'd express the lifetimes of these as being dependent on the lifetime of the ring, but so far that's proven intractable, so we use a reference type. We expect that the up-front overhead of this should be negligible for larger operations, and smaller or one-shot operations can use non-registered buffers and file descriptors. +`struct IOResource` represents, via its two typealiases `IORingFileSlot` and `IORingBuffer`, registered file descriptors and buffers. `struct IORequest: ~Copyable` represents an IO operation that can be enqueued for the kernel to execute. It supports a wide variety of operations matching traditional unix file and socket operations. IORequest operations are expressed as overloaded static methods on `IORequest`, e.g. `openat` is spelled ```swift - public static func opening( + public static func open( _ path: FilePath, in directory: FileDescriptor, into slot: IORingFileSlot, @@ -48,7 +50,7 @@ IORequest operations are expressed as overloaded static methods on `IORequest`, context: UInt64 = 0 ) -> IORequest - public static func opening( + public static func open( _ path: FilePath, in directory: FileDescriptor, mode: FileDescriptor.AccessMode, @@ -84,7 +86,7 @@ Unfortunately the underlying kernel API makes it relatively difficult to determi ## Detailed design ```swift -public class IOResource { } +public struct IOResource { } public typealias IORingFileSlot = IOResource public typealias IORingBuffer = IOResource @@ -152,23 +154,27 @@ public struct IORing: ~Copyable { public func tryConsumeCompletion() -> IOCompletion? - public struct Features { + public struct Features: OptionSet { + let rawValue: UInt32 + + public init(rawValue: UInt32) + //IORING_FEAT_SINGLE_MMAP is handled internally - public var nonDroppingCompletions: Bool //IORING_FEAT_NODROP - public var stableSubmissions: Bool //IORING_FEAT_SUBMIT_STABLE - public var currentFilePosition: Bool //IORING_FEAT_RW_CUR_POS - public var assumingTaskCredentials: Bool //IORING_FEAT_CUR_PERSONALITY - public var fastPolling: Bool //IORING_FEAT_FAST_POLL - public var epoll32BitFlags: Bool //IORING_FEAT_POLL_32BITS - public var pollNonFixedFiles: Bool //IORING_FEAT_SQPOLL_NONFIXED - public var extendedArguments: Bool //IORING_FEAT_EXT_ARG - public var nativeWorkers: Bool //IORING_FEAT_NATIVE_WORKERS - public var resourceTags: Bool //IORING_FEAT_RSRC_TAGS - public var allowsSkippingSuccessfulCompletions: Bool //IORING_FEAT_CQE_SKIP - public var improvedLinkedFiles: Bool //IORING_FEAT_LINKED_FILE - public var registerRegisteredRings: Bool //IORING_FEAT_REG_REG_RING - public var minimumTimeout: Bool //IORING_FEAT_MIN_TIMEOUT - public var bundledSendReceive: Bool //IORING_FEAT_RECVSEND_BUNDLE + public static let nonDroppingCompletions: Bool //IORING_FEAT_NODROP + public static let stableSubmissions: Bool //IORING_FEAT_SUBMIT_STABLE + public static let currentFilePosition: Bool //IORING_FEAT_RW_CUR_POS + public static let assumingTaskCredentials: Bool //IORING_FEAT_CUR_PERSONALITY + public static let fastPolling: Bool //IORING_FEAT_FAST_POLL + public static let epoll32BitFlags: Bool //IORING_FEAT_POLL_32BITS + public static let pollNonFixedFiles: Bool //IORING_FEAT_SQPOLL_NONFIXED + public static let extendedArguments: Bool //IORING_FEAT_EXT_ARG + public static let nativeWorkers: Bool //IORING_FEAT_NATIVE_WORKERS + public static let resourceTags: Bool //IORING_FEAT_RSRC_TAGS + public static let allowsSkippingSuccessfulCompletions: Bool //IORING_FEAT_CQE_SKIP + public static let improvedLinkedFiles: Bool //IORING_FEAT_LINKED_FILE + public static let registerRegisteredRings: Bool //IORING_FEAT_REG_REG_RING + public static let minimumTimeout: Bool //IORING_FEAT_MIN_TIMEOUT + public static let bundledSendReceive: Bool //IORING_FEAT_RECVSEND_BUNDLE } public static var supportedFeatures: Features } @@ -178,28 +184,28 @@ public struct IORequest: ~Copyable { // overloads for each combination of registered vs unregistered buffer/descriptor // Read - public static func reading( + public static func read( _ file: IORingFileSlot, into buffer: IORingBuffer, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest - public static func reading( + public static func read( _ file: FileDescriptor, into buffer: IORingBuffer, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest - public static func reading( + public static func read( _ file: IORingFileSlot, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest - public static func reading( + public static func read( _ file: FileDescriptor, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, @@ -207,28 +213,28 @@ public struct IORequest: ~Copyable { ) -> IORequest // Write - public static func writing( + public static func write( _ buffer: IORingBuffer, into file: IORingFileSlot, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest - public static func writing( + public static func write( _ buffer: IORingBuffer, into file: FileDescriptor, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest - public static func writing( + public static func write( _ buffer: UnsafeMutableRawBufferPointer, into file: IORingFileSlot, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest - public static func writing( + public static func write( _ buffer: UnsafeMutableRawBufferPointer, into file: FileDescriptor, at offset: UInt64 = 0, @@ -236,18 +242,18 @@ public struct IORequest: ~Copyable { ) -> IORequest // Close - public static func closing( + public static func close( _ file: FileDescriptor, context: UInt64 = 0 ) -> IORequest - public static func closing( + public static func close( _ file: IORingFileSlot, context: UInt64 = 0 ) -> IORequest // Open At - public static func opening( + public static func open( _ path: FilePath, in directory: FileDescriptor, into slot: IORingFileSlot, @@ -257,7 +263,7 @@ public struct IORequest: ~Copyable { context: UInt64 = 0 ) -> IORequest - public static func opening( + public static func open( _ path: FilePath, in directory: FileDescriptor, mode: FileDescriptor.AccessMode, @@ -266,12 +272,42 @@ public struct IORequest: ~Copyable { context: UInt64 = 0 ) -> IORequest - public static func unlinking( + public static func unlink( _ path: FilePath, in directory: FileDescriptor, context: UInt64 = 0 ) -> IORequest + // Cancel + + public enum CancellationMatch { + case all + case first + } + + public static func cancel( + _ matchAll: CancellationMatch, + matchingContext: UInt64, + context: UInt64 + ) -> IORequest + + public static func cancel( + _ matchAll: CancellationMatch, + matchingFileDescriptor: FileDescriptor, + context: UInt64 + ) -> IORequest + + public static func cancel( + _ matchAll: CancellationMatch, + matchingRegisteredFileDescriptorAtIndex: Int, + context: UInt64 + ) -> IORequest + + public static func cancel( + _ matchAll: CancellationMatch, + context: UInt64 + ) -> IORequest + // Other operations follow in the same pattern } @@ -322,14 +358,14 @@ let file = ring.registerFiles(count: 1)[0] var statInfo = Glibc.stat() // System doesn't have an abstraction for stat() right now // Build our requests to open the file and find out how big it is ring.prepare(linkedRequests: - .opening(path, + .open(path, in: parentDirectory, into: file, mode: mode, options: openOptions, permissions: nil ), - .readingMetadataOf(file, + .stat(file, into: &statInfo ) ) @@ -345,10 +381,10 @@ let buffer = UnsafeMutableRawBufferPointer.allocate(Int(statInfo.st_size)) // Build our requests to read the file and close it ring.prepare(linkedRequests: - .reading(file, + .read(file, into: buffer ), - .closing(file) + .close(file) ) //batch submit 2 syscalls in 1! @@ -368,7 +404,7 @@ processBuffer(buffer) //Make the read request with a context so we can get the buffer out of it in the completion handler … -.reading(file, into: buffer, context: UInt64(buffer.baseAddress!)) +.read(file, into: buffer, context: UInt64(buffer.baseAddress!)) … // Make an eventfd and register it with the ring @@ -419,7 +455,7 @@ func submitLinkedRequestsAndWait( * liburing has support for operations allocating their own buffers and returning them via the completion, we may want to support this * We may want to provide API for asynchronously waiting, rather than just exposing the eventfd to let people roll their own async waits. Doing this really well has *considerable* implications for the concurrency runtime though. * We should almost certainly expose API for more of the configuration options in `io_uring_setup` -* The API for feature probing is functional but not especially nice. Finding a better way to present that concept would be desirable. +* Stronger safety guarantees around cancellation and resource lifetimes (e.g. as described in https://without.boats/blog/io-uring/) would be very welcome, but require an API that is much more strongly opinionated about how io_uring is used. A future higher level abstraction focused on the goal of being "an async IO API for Swift" rather than "a Swifty interface to io_uring" seems like a good place for that. ## Alternatives considered @@ -428,6 +464,7 @@ func submitLinkedRequestsAndWait( * Using POSIX AIO instead of or as well as io_uring would greatly increase our ability to support older kernels and other Unix systems, but it has well-documented performance and usability issues that have prevented its adoption elsewhere, and apply just as much to Swift. * Earlier versions of this proposal had higher level "managed" abstractions over IORing. These have been removed due to lack of interest from clients, but could be added back later if needed. * I considered making any or all of `IORingError`, `IOCompletion`, and `IORequest` nested struct declarations inside `IORing`. The main reason I haven't done so is I was a little concerned about the ambiguity of having a type called `Error`. I'd be particularly interested in feedback on this choice. +* IOResource was originally a class in an attempt to manage the lifetime of the resource via language features. Changing to the current model of it being a copyable struct didn't make the lifetime management any less safe (the IORing still owns the actual resource), and reduces overhead. In the future it would be neat if we could express IOResources as being borrowed from the IORing so they can't be used after its lifetime. ## Acknowledgments From b40b09440c5ce0bca9d2633b8d374a156d95e053 Mon Sep 17 00:00:00 2001 From: David Smith Date: Wed, 16 Apr 2025 23:37:50 +0000 Subject: [PATCH 050/102] Revamp error handling --- Sources/System/IORing.swift | 170 +++++++++++++++++++++---------- Sources/System/IORingError.swift | 10 -- 2 files changed, 117 insertions(+), 63 deletions(-) delete mode 100644 Sources/System/IORingError.swift diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 79840c1..3ef9299 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -118,7 +118,7 @@ internal func _enter( numEvents: UInt32, minCompletions: UInt32, flags: UInt32 -) throws -> Int32 { +) throws(IORing.OperationError) -> Int32 { // Ring always needs enter right now; // TODO: support SQPOLL here while true { @@ -133,16 +133,14 @@ internal func _enter( //TODO: should we wait a bit on AGAIN? continue } else if ret < 0 { - fatalError( - "fatal error in submitting requests: " + Errno(rawValue: -ret).debugDescription - ) + throw(IORing.OperationError(result: -ret)) } else { return ret } } } -internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws { +internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws(IORing.OperationError) { let flushedEvents = _flushQueue(ring: ring) _ = try _enter( ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0) @@ -193,7 +191,40 @@ internal func _getSubmissionEntry( return nil } +//TODO: make this not an enum. And maybe split it up? And move it into IORing + public struct IORing: ~Copyable { + + /// Errors in either submitting operations or receiving operation completions + public struct OperationError: Error, Hashable { + private var errorCode: Int + public static var operationCanceled: OperationError { .init(result: ECANCELED) } + + internal init(result: Int32) { + errorCode = Int(result) //TODO, flesh this out + } + } + + public struct SetupError: Error, Hashable { + private var errorCode: Int + + public static var missingRequiredFeatures: SetupError { + .init(setupResult: -1) /* TODO: numeric value */ + } + + internal init(setupResult: Int32) { + errorCode = Int(setupResult) //TODO, flesh this out + } + } + + public struct RegistrationError: Error, Hashable { + private var errorCode: Int + + internal init(registrationResult: Int32) { + errorCode = Int(registrationResult) //TODO, flesh this out + } + } + let ringFlags: UInt32 let ringDescriptor: Int32 @@ -212,7 +243,7 @@ public struct IORing: ~Copyable { var _registeredFiles: [UInt32]? var _registeredBuffers: [iovec]? - public init(queueDepth: UInt32) throws { + public init(queueDepth: UInt32) throws(SetupError) { var params = io_uring_params() ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { @@ -224,7 +255,7 @@ public struct IORing: ~Copyable { { close(ringDescriptor) // TODO: error handling - throw IORingError.missingRequiredFeatures + throw .missingRequiredFeatures } if ringDescriptor < 0 { @@ -334,17 +365,17 @@ public struct IORing: ~Copyable { self.ringFlags = params.flags } - private func _blockingConsumeCompletionGuts( + private func _blockingConsumeCompletionGuts( minimumCount: UInt32, maximumCount: UInt32, extraArgs: UnsafeMutablePointer? = nil, - consumer: (consuming IOCompletion?, IORingError?, Bool) throws -> Void - ) rethrows { + consumer: (consuming IOCompletion?, OperationError?, Bool) throws(Err) -> Void + ) throws(Err) { var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { count += 1 if completion.result < 0 { - try consumer(nil, IORingError(completionResult: completion.result), false) + try consumer(nil, OperationError(result: completion.result), false) } else { try consumer(completion, nil, false) } @@ -389,12 +420,12 @@ public struct IORing: ~Copyable { var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { count += 1 - if completion.result < 0 { - try consumer(nil, IORingError(completionResult: completion.result), false) - } else { - try consumer(completion, nil, false) - } - if count == maximumCount { + if completion.result < 0 { + try consumer(nil, OperationError(result: completion.result), false) + } else { + try consumer(completion, nil, false) + } + if count == maximumCount { break } } @@ -404,14 +435,14 @@ public struct IORing: ~Copyable { internal func _blockingConsumeOneCompletion( extraArgs: UnsafeMutablePointer? = nil - ) throws -> IOCompletion { + ) throws(OperationError) -> IOCompletion { var result: IOCompletion? = nil try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { (completion: consuming IOCompletion?, error, done) in if let error { throw error } - if let completion { + if let completion { result = consume completion } } @@ -420,46 +451,65 @@ public struct IORing: ~Copyable { public func blockingConsumeCompletion( timeout: Duration? = nil - ) throws -> IOCompletion { + ) throws(OperationError) -> IOCompletion { if let timeout { var ts = __kernel_timespec( tv_sec: timeout.components.seconds, tv_nsec: timeout.components.attoseconds / 1_000_000_000 ) - return try withUnsafePointer(to: &ts) { tsPtr in + var err: OperationError? = nil + var result: IOCompletion? = nil + result = try withUnsafePointer(to: &ts) { tsPtr in var args = io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, pad: 0, ts: UInt64(UInt(bitPattern: tsPtr)) ) - return try _blockingConsumeOneCompletion(extraArgs: &args) + do { + return try _blockingConsumeOneCompletion(extraArgs: &args) + } catch (let e) { + err = e as! OperationError + return nil + } } + guard let result else { + throw(err!) + } + return result } else { return try _blockingConsumeOneCompletion() } } - public func blockingConsumeCompletions( + public func blockingConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (consuming IOCompletion?, IORingError?, Bool) throws -> Void - ) throws { + consumer: (consuming IOCompletion?, OperationError?, Bool) throws(Err) -> Void + ) throws(Err) { if let timeout { var ts = __kernel_timespec( tv_sec: timeout.components.seconds, tv_nsec: timeout.components.attoseconds / 1_000_000_000 ) - return try withUnsafePointer(to: &ts) { tsPtr in + var err: Err? = nil + withUnsafePointer(to: &ts) { tsPtr in var args = io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, pad: 0, ts: UInt64(UInt(bitPattern: tsPtr)) ) - try _blockingConsumeCompletionGuts( - minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args, - consumer: consumer) + do { + try _blockingConsumeCompletionGuts( + minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args, + consumer: consumer) + } catch (let e) { + err = e as! Err //TODO: why is `e` coming in as `any Error`? That seems wrong + } + } + if let err { + throw(err) } } else { try _blockingConsumeCompletionGuts( @@ -489,34 +539,35 @@ public struct IORing: ~Copyable { return nil } - internal func handleRegistrationResult(_ result: Int32) throws { - //TODO: error handling - } - - public mutating func registerEventFD(_ descriptor: FileDescriptor) throws { + public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(RegistrationError) { var rawfd = descriptor.rawValue let result = withUnsafePointer(to: &rawfd) { fdptr in - return io_uring_register( + let result = io_uring_register( ringDescriptor, IORING_REGISTER_EVENTFD, UnsafeMutableRawPointer(mutating: fdptr), 1 ) + return result >= 0 ? nil : Errno.current + } + if let result { + throw(RegistrationError(registrationResult: result.rawValue)) } - try handleRegistrationResult(result) } - public mutating func unregisterEventFD() throws { + public mutating func unregisterEventFD() throws(RegistrationError) { let result = io_uring_register( ringDescriptor, IORING_UNREGISTER_EVENTFD, nil, 0 ) - try handleRegistrationResult(result) + if result < 0 { + throw(RegistrationError(registrationResult: result)) + } } - public mutating func registerFileSlots(count: Int) -> RegisteredResources< + public mutating func registerFileSlots(count: Int) throws(RegistrationError) -> RegisteredResources< IORingFileSlot.Resource > { precondition(_registeredFiles == nil) @@ -524,15 +575,19 @@ public struct IORing: ~Copyable { let files = [UInt32](repeating: UInt32.max, count: count) let regResult = files.withUnsafeBufferPointer { bPtr in - io_uring_register( + let result = io_uring_register( self.ringDescriptor, IORING_REGISTER_FILES, UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), UInt32(truncatingIfNeeded: count) ) + return result >= 0 ? nil : Errno.current + } + + guard regResult == nil else { + throw RegistrationError(registrationResult: regResult!.rawValue) } - // TODO: error handling _registeredFiles = files return registeredFileSlots } @@ -545,7 +600,7 @@ public struct IORing: ~Copyable { RegisteredResources(resources: _registeredFiles ?? []) } - public mutating func registerBuffers(_ buffers: some Collection) + public mutating func registerBuffers(_ buffers: some Collection) throws(RegistrationError) -> RegisteredResources { precondition(buffers.count < UInt32.max) @@ -553,12 +608,17 @@ public struct IORing: ~Copyable { //TODO: check if io_uring has preconditions it needs for the buffers (e.g. alignment) let iovecs = buffers.map { $0.to_iovec() } let regResult = iovecs.withUnsafeBufferPointer { bPtr in - io_uring_register( + let result = io_uring_register( self.ringDescriptor, IORING_REGISTER_BUFFERS, UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), UInt32(truncatingIfNeeded: buffers.count) ) + return result >= 0 ? nil : Errno.current + } + + guard regResult == nil else { + throw RegistrationError(registrationResult: regResult!.rawValue) } // TODO: error handling @@ -566,10 +626,10 @@ public struct IORing: ~Copyable { return registeredBuffers } - public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) + public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) throws(RegistrationError) -> RegisteredResources { - registerBuffers(buffers) + try registerBuffers(buffers) } public struct RegisteredResources: RandomAccessCollection { @@ -596,20 +656,24 @@ public struct IORing: ~Copyable { fatalError("failed to unregister buffers: TODO") } - public func submitPreparedRequests() throws { + public func submitPreparedRequests() throws(OperationError) { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } - public func submitPreparedRequestsAndConsumeCompletions( + public func submitPreparedRequestsAndConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (consuming IOCompletion?, IORingError?, Bool) throws -> Void - ) throws { + consumer: (consuming IOCompletion?, OperationError?, Bool) throws(Err) -> Void + ) throws(Err) { //TODO: optimize this to one uring_enter - try submitPreparedRequests() + do { + try submitPreparedRequests() + } catch (let e) { + try consumer(nil, e, true) + } try blockingConsumeCompletions( - minimumCount: minimumCount, - timeout: timeout, + minimumCount: minimumCount, + timeout: timeout, consumer: consumer ) } @@ -641,7 +705,7 @@ public struct IORing: ~Copyable { prepare(linkedRequests: linkedRequests) } - public mutating func submit(linkedRequests: IORequest...) throws { + public mutating func submit(linkedRequests: IORequest...) throws(OperationError) { prepare(linkedRequests: linkedRequests) try submitPreparedRequests() } diff --git a/Sources/System/IORingError.swift b/Sources/System/IORingError.swift deleted file mode 100644 index fbd70bc..0000000 --- a/Sources/System/IORingError.swift +++ /dev/null @@ -1,10 +0,0 @@ -//TODO: make this not an enum -public enum IORingError: Error, Equatable { - case missingRequiredFeatures - case operationCanceled - case unknown(errorCode: Int) - - internal init(completionResult: Int32) { - self = .unknown(errorCode: Int(completionResult)) //TODO, flesh this out - } -} From 2f91217c90d9efc02f4d1bd28a7e2188b774bf77 Mon Sep 17 00:00:00 2001 From: David Smith Date: Wed, 16 Apr 2025 23:44:21 +0000 Subject: [PATCH 051/102] Fix a few things I missed --- Sources/System/IORing.swift | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 3ef9299..e45d48a 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -437,14 +437,18 @@ public struct IORing: ~Copyable { extraArgs: UnsafeMutablePointer? = nil ) throws(OperationError) -> IOCompletion { var result: IOCompletion? = nil - try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { - (completion: consuming IOCompletion?, error, done) in - if let error { - throw error - } - if let completion { - result = consume completion + do { + try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { + (completion: consuming IOCompletion?, error, done) in + if let error { + throw error + } + if let completion { + result = consume completion + } } + } catch (let e) { + throw e as! OperationError //TODO: why is this needed? } return result.take()! } @@ -459,7 +463,7 @@ public struct IORing: ~Copyable { ) var err: OperationError? = nil var result: IOCompletion? = nil - result = try withUnsafePointer(to: &ts) { tsPtr in + result = withUnsafePointer(to: &ts) { tsPtr in var args = io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, @@ -469,7 +473,7 @@ public struct IORing: ~Copyable { do { return try _blockingConsumeOneCompletion(extraArgs: &args) } catch (let e) { - err = e as! OperationError + err = (e as! OperationError) return nil } } @@ -505,7 +509,7 @@ public struct IORing: ~Copyable { minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args, consumer: consumer) } catch (let e) { - err = e as! Err //TODO: why is `e` coming in as `any Error`? That seems wrong + err = (e as! Err) //TODO: why is `e` coming in as `any Error`? That seems wrong } } if let err { @@ -692,10 +696,10 @@ public struct IORing: ~Copyable { for req in linkedRequests.dropLast() { var raw = req.makeRawRequest() raw.linkToNextRequest() - _writeRequest( + _ = _writeRequest( raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } - _writeRequest( + _ = _writeRequest( last.makeRawRequest(), ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } From d4ca203c09c7e541d603436bf2f0d78d600f5309 Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 17 Apr 2025 00:26:13 +0000 Subject: [PATCH 052/102] Most of feature querying and setup flags --- Sources/System/IORing.swift | 56 ++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index e45d48a..ef63ecc 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -243,8 +243,33 @@ public struct IORing: ~Copyable { var _registeredFiles: [UInt32]? var _registeredBuffers: [iovec]? - public init(queueDepth: UInt32) throws(SetupError) { + @frozen + public struct SetupFlags: OptionSet, RawRepresentable { + public var rawValue: UInt32 + + @inlinable public init(rawValue: UInt32) { + self.rawValue = rawValue + } + @inlinable public static var pollCompletions: SetupFlags { .init(rawValue: UInt32(1) << 0) } //IORING_SETUP_IOPOLL + @inlinable public static var pollSubmissions: SetupFlags { .init(rawValue: UInt32(1) << 1) } //IORING_SETUP_SQPOLL + //TODO: figure out how to expose IORING_SETUP_SQ_AFF, IORING_SETUP_CQSIZE, IORING_SETUP_ATTACH_WQ + @inlinable public static var clampMaxEntries: SetupFlags { .init(rawValue: UInt32(1) << 4) } //IORING_SETUP_CLAMP + @inlinable public static var startDisabled: SetupFlags { .init(rawValue: UInt32(1) << 6) } //IORING_SETUP_R_DISABLED + @inlinable public static var continueSubmittingOnError: SetupFlags { .init(rawValue: UInt32(1) << 7) } //IORING_SETUP_SUBMIT_ALL + //TODO: do we want to expose IORING_SETUP_COOP_TASKRUN and IORING_SETUP_TASKRUN_FLAG? + //public static var runTasksCooperatively: SetupFlags { .init(rawValue: UInt32(1) << 8) } //IORING_SETUP_COOP_TASKRUN + //TODO: can we even do different size sqe/cqe? It requires a kernel feature, but how do we convince swift to let the types be different sizes? + internal static var use128ByteSQEs: SetupFlags { .init(rawValue: UInt32(1) << 10) } //IORING_SETUP_SQE128 + internal static var use32ByteCQEs: SetupFlags { .init(rawValue: UInt32(1) << 11) } //IORING_SETUP_CQE32 + @inlinable public static var singleSubmissionThread: SetupFlags { .init(rawValue: UInt32(1) << 12) } //IORING_SETUP_SINGLE_ISSUER + @inlinable public static var deferRunningTasks: SetupFlags { .init(rawValue: UInt32(1) << 13) } //IORING_SETUP_DEFER_TASKRUN + //pretty sure we don't want to expose IORING_SETUP_NO_MMAP or IORING_SETUP_REGISTERED_FD_ONLY currently + //TODO: should IORING_SETUP_NO_SQARRAY be the default? do we need to adapt anything to it? + } + + public init(queueDepth: UInt32, flags: SetupFlags = []) throws(SetupError) { var params = io_uring_params() + params.flags = flags.rawValue ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { return io_uring_setup(queueDepth, $0) @@ -714,6 +739,35 @@ public struct IORing: ~Copyable { try submitPreparedRequests() } + @frozen + public struct Features: OptionSet, RawRepresentable { + public let rawValue: UInt32 + + @inlinable public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + //IORING_FEAT_SINGLE_MMAP is handled internally + @inlinable public static var nonDroppingCompletions: Features { .init(rawValue: UInt32(1) << 1) } //IORING_FEAT_NODROP + @inlinable public static var stableSubmissions: Features { .init(rawValue: UInt32(1) << 2) } //IORING_FEAT_SUBMIT_STABLE + @inlinable public static var currentFilePosition: Features { .init(rawValue: UInt32(1) << 3) } //IORING_FEAT_RW_CUR_POS + @inlinable public static var assumingTaskCredentials: Features { .init(rawValue: UInt32(1) << 4) } //IORING_FEAT_CUR_PERSONALITY + @inlinable public static var fastPolling: Features { .init(rawValue: UInt32(1) << 5) } //IORING_FEAT_FAST_POLL + @inlinable public static var epoll32BitFlags: Features { .init(rawValue: UInt32(1) << 6) } //IORING_FEAT_POLL_32BITS + @inlinable public static var pollNonFixedFiles: Features { .init(rawValue: UInt32(1) << 7) } //IORING_FEAT_SQPOLL_NONFIXED + @inlinable public static var extendedArguments: Features { .init(rawValue: UInt32(1) << 8) } //IORING_FEAT_EXT_ARG + @inlinable public static var nativeWorkers: Features { .init(rawValue: UInt32(1) << 9) } //IORING_FEAT_NATIVE_WORKERS + @inlinable public static var resourceTags: Features { .init(rawValue: UInt32(1) << 10) } //IORING_FEAT_RSRC_TAGS + @inlinable public static var allowsSkippingSuccessfulCompletions: Features { .init(rawValue: UInt32(1) << 11) } //IORING_FEAT_CQE_SKIP + @inlinable public static var improvedLinkedFiles: Features { .init(rawValue: UInt32(1) << 12) } //IORING_FEAT_LINKED_FILE + @inlinable public static var registerRegisteredRings: Features { .init(rawValue: UInt32(1) << 13) } //IORING_FEAT_REG_REG_RING + @inlinable public static var minimumTimeout: Features { .init(rawValue: UInt32(1) << 15) } //IORING_FEAT_MIN_TIMEOUT + @inlinable public static var bundledSendReceive: Features { .init(rawValue: UInt32(1) << 14) } //IORING_FEAT_RECVSEND_BUNDLE + } + public static var supportedFeatures: Features { + fatalError("Implement me") + } + deinit { munmap(ringPtr, ringSize) munmap( From 41f967690797dcb68220d7587215216824dac0fe Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 17 Apr 2025 23:31:01 +0000 Subject: [PATCH 053/102] WIP, crashes the compiler --- Sources/System/IORing.swift | 237 ++++++++++++++++++++---------------- 1 file changed, 130 insertions(+), 107 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index ef63ecc..e72c9e8 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -191,11 +191,113 @@ internal func _getSubmissionEntry( return nil } -//TODO: make this not an enum. And maybe split it up? And move it into IORing +private func setUpRing( + queueDepth: UInt32, flags: IORing.SetupFlags, submissionRing: inout SQRing +) throws(IORing.SetupError) -> + (params: io_uring_params, ringDescriptor: Int32, ringPtr: UnsafeMutableRawPointer, ringSize: Int, sqes: UnsafeMutableRawPointer) { + var params = io_uring_params() + params.flags = flags.rawValue + + var err: Errno? = nil + let ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { + let result = io_uring_setup(queueDepth, $0) + if result < 0 { + err = Errno.current + } + return result + } + + if let err { + throw IORing.SetupError(setupResult: err.rawValue) + } + + if params.features & IORING_FEAT_SINGLE_MMAP == 0 + || params.features & IORING_FEAT_NODROP == 0 + { + close(ringDescriptor) + // TODO: error handling + throw .missingRequiredFeatures + } + + let submitRingSize = + params.sq_off.array + + params.sq_entries * UInt32(MemoryLayout.size) + + let completionRingSize = + params.cq_off.cqes + + params.cq_entries * UInt32(MemoryLayout.size) + + let ringSize = Int(max(submitRingSize, completionRingSize)) + + let ringPtr: UnsafeMutableRawPointer! = mmap( + /* addr: */ nil, + /* len: */ ringSize, + /* prot: */ PROT_READ | PROT_WRITE, + /* flags: */ MAP_SHARED | MAP_POPULATE, + /* fd: */ ringDescriptor, + /* offset: */ __off_t(IORING_OFF_SQ_RING) + ) + + if ringPtr == MAP_FAILED { + perror("mmap") + close(ringDescriptor) + throw .mapFailed + } + + let submissionRing = SQRing( + kernelHead: UnsafePointer>( + ringPtr.advanced(by: params.sq_off.head) + .assumingMemoryBound(to: Atomic.self) + ), + kernelTail: UnsafePointer>( + ringPtr.advanced(by: params.sq_off.tail) + .assumingMemoryBound(to: Atomic.self) + ), + userTail: 0, // no requests yet + ringMask: ringPtr.advanced(by: params.sq_off.ring_mask) + .assumingMemoryBound(to: UInt32.self).pointee, + flags: UnsafePointer>( + ringPtr.advanced(by: params.sq_off.flags) + .assumingMemoryBound(to: Atomic.self) + ), + array: UnsafeMutableBufferPointer( + start: ringPtr.advanced(by: params.sq_off.array) + .assumingMemoryBound(to: UInt32.self), + count: Int( + ringPtr.advanced(by: params.sq_off.ring_entries) + .assumingMemoryBound(to: UInt32.self).pointee) + ) + ) + + // fill submission ring array with 1:1 map to underlying SQEs + for i in 0...size, + /* prot: */ PROT_READ | PROT_WRITE, + /* flags: */ MAP_SHARED | MAP_POPULATE, + /* fd: */ ringDescriptor, + /* offset: */ __off_t(IORING_OFF_SQES) + ) + + if sqes == MAP_FAILED { + perror("mmap") + munmap(ringPtr, ringSize) + close(ringDescriptor) + throw .mapFailed + } + + return (params: params, ringDescriptor: ringDescriptor, ringPtr: ringPtr!, ringSize: ringSize, sqes: sqes!) +} public struct IORing: ~Copyable { /// Errors in either submitting operations or receiving operation completions + @frozen public struct OperationError: Error, Hashable { private var errorCode: Int public static var operationCanceled: OperationError { .init(result: ECANCELED) } @@ -205,6 +307,7 @@ public struct IORing: ~Copyable { } } + @frozen public struct SetupError: Error, Hashable { private var errorCode: Int @@ -212,11 +315,14 @@ public struct IORing: ~Copyable { .init(setupResult: -1) /* TODO: numeric value */ } + public static var mapFailed: SetupError { .init(setupResult: -2) } + internal init(setupResult: Int32) { errorCode = Int(setupResult) //TODO, flesh this out } } + @frozen public struct RegistrationError: Error, Hashable { private var errorCode: Int @@ -228,7 +334,7 @@ public struct IORing: ~Copyable { let ringFlags: UInt32 let ringDescriptor: Int32 - @usableFromInline var submissionRing: SQRing + @usableFromInline var submissionRing: SQRing! // FEAT: set this eventually let submissionPolling: Bool = false @@ -240,8 +346,10 @@ public struct IORing: ~Copyable { let ringSize: Int let ringPtr: UnsafeMutableRawPointer - var _registeredFiles: [UInt32]? - var _registeredBuffers: [iovec]? + var _registeredFiles: [UInt32] = [] + var _registeredBuffers: [iovec] = [] + + var features = Features(rawValue: 0) @frozen public struct SetupFlags: OptionSet, RawRepresentable { @@ -267,103 +375,22 @@ public struct IORing: ~Copyable { //TODO: should IORING_SETUP_NO_SQARRAY be the default? do we need to adapt anything to it? } - public init(queueDepth: UInt32, flags: SetupFlags = []) throws(SetupError) { - var params = io_uring_params() - params.flags = flags.rawValue - - ringDescriptor = withUnsafeMutablePointer(to: ¶ms) { - return io_uring_setup(queueDepth, $0) - } - - if params.features & IORING_FEAT_SINGLE_MMAP == 0 - || params.features & IORING_FEAT_NODROP == 0 - { - close(ringDescriptor) - // TODO: error handling - throw .missingRequiredFeatures - } - - if ringDescriptor < 0 { - // TODO: error handling - } - - let submitRingSize = - params.sq_off.array - + params.sq_entries * UInt32(MemoryLayout.size) - - let completionRingSize = - params.cq_off.cqes - + params.cq_entries * UInt32(MemoryLayout.size) - - ringSize = Int(max(submitRingSize, completionRingSize)) - - ringPtr = mmap( - /* addr: */ nil, - /* len: */ ringSize, - /* prot: */ PROT_READ | PROT_WRITE, - /* flags: */ MAP_SHARED | MAP_POPULATE, - /* fd: */ ringDescriptor, - /* offset: */ __off_t(IORING_OFF_SQ_RING) - ) - - if ringPtr == MAP_FAILED { - perror("mmap") - // TODO: error handling - fatalError("mmap failed in ring setup") - } - - let submissionRing = SQRing( - kernelHead: UnsafePointer>( - ringPtr.advanced(by: params.sq_off.head) - .assumingMemoryBound(to: Atomic.self) - ), - kernelTail: UnsafePointer>( - ringPtr.advanced(by: params.sq_off.tail) - .assumingMemoryBound(to: Atomic.self) - ), - userTail: 0, // no requests yet - ringMask: ringPtr.advanced(by: params.sq_off.ring_mask) - .assumingMemoryBound(to: UInt32.self).pointee, - flags: UnsafePointer>( - ringPtr.advanced(by: params.sq_off.flags) - .assumingMemoryBound(to: Atomic.self) - ), - array: UnsafeMutableBufferPointer( - start: ringPtr.advanced(by: params.sq_off.array) - .assumingMemoryBound(to: UInt32.self), - count: Int( - ringPtr.advanced(by: params.sq_off.ring_entries) - .assumingMemoryBound(to: UInt32.self).pointee) - ) - ) - - // fill submission ring array with 1:1 map to underlying SQEs - for i in 0...size, - /* prot: */ PROT_READ | PROT_WRITE, - /* flags: */ MAP_SHARED | MAP_POPULATE, - /* fd: */ ringDescriptor, - /* offset: */ __off_t(IORING_OFF_SQES) - ) - - if sqes == MAP_FAILED { - perror("mmap") - // TODO: error handling - fatalError("sqe mmap failed in ring setup") - } + public init(queueDepth: UInt32, flags: SetupFlags) throws(SetupError) { + let (params, tmpRingDescriptor, tmpRingPtr, tmpRingSize, sqes) = try setUpRing(queueDepth: queueDepth, flags: flags, submissionRing: &submissionRing) + // All throws need to be before initializing ivars here to avoid + // "error: conditional initialization or destruction of noncopyable types is not supported; + // this variable must be consistently in an initialized or uninitialized state through every code path" + features = Features(rawValue: params.features) + ringDescriptor = tmpRingDescriptor + ringPtr = tmpRingPtr + ringSize = tmpRingSize submissionQueueEntries = UnsafeMutableBufferPointer( - start: sqes!.assumingMemoryBound(to: io_uring_sqe.self), + start: sqes.assumingMemoryBound(to: io_uring_sqe.self), count: Int(params.sq_entries) ) - let completionRing = CQRing( + completionRing = CQRing( kernelHead: UnsafePointer>( ringPtr.advanced(by: params.cq_off.head) .assumingMemoryBound(to: Atomic.self) @@ -383,10 +410,6 @@ public struct IORing: ~Copyable { .assumingMemoryBound(to: UInt32.self).pointee) ) ) - - self.submissionRing = submissionRing - self.completionRing = completionRing - self.ringFlags = params.flags } @@ -599,7 +622,7 @@ public struct IORing: ~Copyable { public mutating func registerFileSlots(count: Int) throws(RegistrationError) -> RegisteredResources< IORingFileSlot.Resource > { - precondition(_registeredFiles == nil) + precondition(_registeredFiles.isEmpty) precondition(count < UInt32.max) let files = [UInt32](repeating: UInt32.max, count: count) @@ -626,14 +649,14 @@ public struct IORing: ~Copyable { } public var registeredFileSlots: RegisteredResources { - RegisteredResources(resources: _registeredFiles ?? []) + RegisteredResources(resources: _registeredFiles) } public mutating func registerBuffers(_ buffers: some Collection) throws(RegistrationError) -> RegisteredResources { precondition(buffers.count < UInt32.max) - precondition(_registeredBuffers == nil) + precondition(_registeredBuffers.isEmpty) //TODO: check if io_uring has preconditions it needs for the buffers (e.g. alignment) let iovecs = buffers.map { $0.to_iovec() } let regResult = iovecs.withUnsafeBufferPointer { bPtr in @@ -678,7 +701,7 @@ public struct IORing: ~Copyable { } public var registeredBuffers: RegisteredResources { - RegisteredResources(resources: _registeredBuffers ?? []) + RegisteredResources(resources: _registeredBuffers) } public func unregisterBuffers() { @@ -740,7 +763,7 @@ public struct IORing: ~Copyable { } @frozen - public struct Features: OptionSet, RawRepresentable { + public struct Features: OptionSet, RawRepresentable, Hashable { public let rawValue: UInt32 @inlinable public init(rawValue: UInt32) { @@ -764,8 +787,8 @@ public struct IORing: ~Copyable { @inlinable public static var minimumTimeout: Features { .init(rawValue: UInt32(1) << 15) } //IORING_FEAT_MIN_TIMEOUT @inlinable public static var bundledSendReceive: Features { .init(rawValue: UInt32(1) << 14) } //IORING_FEAT_RECVSEND_BUNDLE } - public static var supportedFeatures: Features { - fatalError("Implement me") + public var supportedFeatures: Features { + return features } deinit { From 014f8b78eb3b2acf07f98589661acd8fa2e42bd7 Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 17 Apr 2025 23:36:51 +0000 Subject: [PATCH 054/102] Rename userData to context --- Sources/System/IOCompletion.swift | 2 +- Sources/System/IORequest.swift | 148 +++++++++++++++--------------- 2 files changed, 75 insertions(+), 75 deletions(-) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index ee81797..b15f0d4 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -20,7 +20,7 @@ extension IOCompletion { } extension IOCompletion { - public var userData: UInt64 { //TODO: naming? + public var context: UInt64 { get { rawValue.user_data } diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 1eed6ed..c836fd3 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -9,7 +9,7 @@ internal enum IORequestCore { FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, - userData: UInt64 = 0 + context: UInt64 = 0 ) case openatSlot( atDirectory: FileDescriptor, @@ -18,68 +18,68 @@ internal enum IORequestCore { options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, intoSlot: IORingFileSlot, - userData: UInt64 = 0 + context: UInt64 = 0 ) case read( file: FileDescriptor, buffer: IORingBuffer, offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) case readUnregistered( file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) case readSlot( file: IORingFileSlot, buffer: IORingBuffer, offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) case readUnregisteredSlot( file: IORingFileSlot, buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) case write( file: FileDescriptor, buffer: IORingBuffer, offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) case writeUnregistered( file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) case writeSlot( file: IORingFileSlot, buffer: IORingBuffer, offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) case writeUnregisteredSlot( file: IORingFileSlot, buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) case close( FileDescriptor, - userData: UInt64 = 0 + context: UInt64 = 0 ) case closeSlot( IORingFileSlot, - userData: UInt64 = 0 + context: UInt64 = 0 ) case unlinkAt( atDirectory: FileDescriptor, path: FilePath, - userData: UInt64 = 0 + context: UInt64 = 0 ) } @@ -88,14 +88,14 @@ internal func makeRawRequest_readWrite_registered( file: FileDescriptor, buffer: IORingBuffer, offset: UInt64, - userData: UInt64 = 0, + context: UInt64 = 0, request: consuming RawIORequest ) -> RawIORequest { request.fileDescriptor = file request.buffer = buffer.unsafeBuffer request.rawValue.buf_index = UInt16(exactly: buffer.index)! request.offset = offset - request.rawValue.user_data = userData + request.rawValue.user_data = context return request } @@ -104,7 +104,7 @@ internal func makeRawRequest_readWrite_registered_slot( file: IORingFileSlot, buffer: IORingBuffer, offset: UInt64, - userData: UInt64 = 0, + context: UInt64 = 0, request: consuming RawIORequest ) -> RawIORequest { request.rawValue.fd = Int32(exactly: file.index)! @@ -112,7 +112,7 @@ internal func makeRawRequest_readWrite_registered_slot( request.buffer = buffer.unsafeBuffer request.rawValue.buf_index = UInt16(exactly: buffer.index)! request.offset = offset - request.rawValue.user_data = userData + request.rawValue.user_data = context return request } @@ -121,13 +121,13 @@ internal func makeRawRequest_readWrite_unregistered( file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, offset: UInt64, - userData: UInt64 = 0, + context: UInt64 = 0, request: consuming RawIORequest ) -> RawIORequest { request.fileDescriptor = file request.buffer = buffer request.offset = offset - request.rawValue.user_data = userData + request.rawValue.user_data = context return request } @@ -136,14 +136,14 @@ internal func makeRawRequest_readWrite_unregistered_slot( file: IORingFileSlot, buffer: UnsafeMutableRawBufferPointer, offset: UInt64, - userData: UInt64 = 0, + context: UInt64 = 0, request: consuming RawIORequest ) -> RawIORequest { request.rawValue.fd = Int32(exactly: file.index)! request.flags = .fixedFile request.buffer = buffer request.offset = offset - request.rawValue.user_data = userData + request.rawValue.user_data = context return request } @@ -156,7 +156,7 @@ public struct IORequest { } extension IORequest { - public static func nop(userData: UInt64 = 0) -> IORequest { + public static func nop(context: UInt64 = 0) -> IORequest { IORequest(core: .nop) } @@ -164,93 +164,93 @@ extension IORequest { _ file: IORingFileSlot, into buffer: IORingBuffer, at offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { - IORequest(core: .readSlot(file: file, buffer: buffer, offset: offset, userData: userData)) + IORequest(core: .readSlot(file: file, buffer: buffer, offset: offset, context: context)) } public static func reading( _ file: FileDescriptor, into buffer: IORingBuffer, at offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { - IORequest(core: .read(file: file, buffer: buffer, offset: offset, userData: userData)) + IORequest(core: .read(file: file, buffer: buffer, offset: offset, context: context)) } public static func reading( _ file: IORingFileSlot, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { IORequest( core: .readUnregisteredSlot( - file: file, buffer: buffer, offset: offset, userData: userData)) + file: file, buffer: buffer, offset: offset, context: context)) } public static func reading( _ file: FileDescriptor, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { IORequest( - core: .readUnregistered(file: file, buffer: buffer, offset: offset, userData: userData)) + core: .readUnregistered(file: file, buffer: buffer, offset: offset, context: context)) } public static func writing( _ buffer: IORingBuffer, into file: IORingFileSlot, at offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { - IORequest(core: .writeSlot(file: file, buffer: buffer, offset: offset, userData: userData)) + IORequest(core: .writeSlot(file: file, buffer: buffer, offset: offset, context: context)) } public static func writing( _ buffer: IORingBuffer, into file: FileDescriptor, at offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { - IORequest(core: .write(file: file, buffer: buffer, offset: offset, userData: userData)) + IORequest(core: .write(file: file, buffer: buffer, offset: offset, context: context)) } public static func writing( _ buffer: UnsafeMutableRawBufferPointer, into file: IORingFileSlot, at offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { IORequest( core: .writeUnregisteredSlot( - file: file, buffer: buffer, offset: offset, userData: userData)) + file: file, buffer: buffer, offset: offset, context: context)) } public static func writing( _ buffer: UnsafeMutableRawBufferPointer, into file: FileDescriptor, at offset: UInt64 = 0, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { IORequest( - core: .writeUnregistered(file: file, buffer: buffer, offset: offset, userData: userData) + core: .writeUnregistered(file: file, buffer: buffer, offset: offset, context: context) ) } public static func closing( _ file: FileDescriptor, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { - IORequest(core: .close(file, userData: userData)) + IORequest(core: .close(file, context: context)) } public static func closing( _ file: IORingFileSlot, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { - IORequest(core: .closeSlot(file, userData: userData)) + IORequest(core: .closeSlot(file, context: context)) } public static func opening( @@ -260,12 +260,12 @@ extension IORequest { mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { IORequest( core: .openatSlot( atDirectory: directory, path: path, mode, options: options, - permissions: permissions, intoSlot: slot, userData: userData)) + permissions: permissions, intoSlot: slot, context: context)) } public static func opening( @@ -274,21 +274,21 @@ extension IORequest { mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { IORequest( core: .openat( atDirectory: directory, path: path, mode, options: options, - permissions: permissions, userData: userData + permissions: permissions, context: context )) } public static func unlinking( _ path: FilePath, in directory: FileDescriptor, - userData: UInt64 = 0 + context: UInt64 = 0 ) -> IORequest { - IORequest(core: .unlinkAt(atDirectory: directory, path: path, userData: userData)) + IORequest(core: .unlinkAt(atDirectory: directory, path: path, context: context)) } @inline(__always) @@ -299,7 +299,7 @@ extension IORequest { request.operation = .nop case .openatSlot( let atDirectory, let path, let mode, let options, let permissions, let fileSlot, - let userData): + let context): // TODO: use rawValue less request.operation = .openAt request.fileDescriptor = atDirectory @@ -312,9 +312,9 @@ extension IORequest { request.rawValue.len = permissions?.rawValue ?? 0 request.rawValue.file_index = UInt32(fileSlot.index + 1) request.path = path - request.rawValue.user_data = userData + request.rawValue.user_data = context case .openat( - let atDirectory, let path, let mode, let options, let permissions, let userData): + let atDirectory, let path, let mode, let options, let permissions, let context): request.operation = .openAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( @@ -325,48 +325,48 @@ extension IORequest { request.rawValue.open_flags = UInt32(bitPattern: options.rawValue | mode.rawValue) request.rawValue.len = permissions?.rawValue ?? 0 request.path = path - request.rawValue.user_data = userData - case .write(let file, let buffer, let offset, let userData): + request.rawValue.user_data = context + case .write(let file, let buffer, let offset, let context): request.operation = .writeFixed return makeRawRequest_readWrite_registered( - file: file, buffer: buffer, offset: offset, userData: userData, request: request) - case .writeSlot(let file, let buffer, let offset, let userData): + file: file, buffer: buffer, offset: offset, context: context, request: request) + case .writeSlot(let file, let buffer, let offset, let context): request.operation = .writeFixed return makeRawRequest_readWrite_registered_slot( - file: file, buffer: buffer, offset: offset, userData: userData, request: request) - case .writeUnregistered(let file, let buffer, let offset, let userData): + file: file, buffer: buffer, offset: offset, context: context, request: request) + case .writeUnregistered(let file, let buffer, let offset, let context): request.operation = .write return makeRawRequest_readWrite_unregistered( - file: file, buffer: buffer, offset: offset, userData: userData, request: request) - case .writeUnregisteredSlot(let file, let buffer, let offset, let userData): + file: file, buffer: buffer, offset: offset, context: context, request: request) + case .writeUnregisteredSlot(let file, let buffer, let offset, let context): request.operation = .write return makeRawRequest_readWrite_unregistered_slot( - file: file, buffer: buffer, offset: offset, userData: userData, request: request) - case .read(let file, let buffer, let offset, let userData): + file: file, buffer: buffer, offset: offset, context: context, request: request) + case .read(let file, let buffer, let offset, let context): request.operation = .readFixed return makeRawRequest_readWrite_registered( - file: file, buffer: buffer, offset: offset, userData: userData, request: request) - case .readSlot(let file, let buffer, let offset, let userData): + file: file, buffer: buffer, offset: offset, context: context, request: request) + case .readSlot(let file, let buffer, let offset, let context): request.operation = .readFixed return makeRawRequest_readWrite_registered_slot( - file: file, buffer: buffer, offset: offset, userData: userData, request: request) - case .readUnregistered(let file, let buffer, let offset, let userData): + file: file, buffer: buffer, offset: offset, context: context, request: request) + case .readUnregistered(let file, let buffer, let offset, let context): request.operation = .read return makeRawRequest_readWrite_unregistered( - file: file, buffer: buffer, offset: offset, userData: userData, request: request) - case .readUnregisteredSlot(let file, let buffer, let offset, let userData): + file: file, buffer: buffer, offset: offset, context: context, request: request) + case .readUnregisteredSlot(let file, let buffer, let offset, let context): request.operation = .read return makeRawRequest_readWrite_unregistered_slot( - file: file, buffer: buffer, offset: offset, userData: userData, request: request) - case .close(let file, let userData): + file: file, buffer: buffer, offset: offset, context: context, request: request) + case .close(let file, let context): request.operation = .close request.fileDescriptor = file - request.rawValue.user_data = userData - case .closeSlot(let file, let userData): + request.rawValue.user_data = context + case .closeSlot(let file, let context): request.operation = .close request.rawValue.file_index = UInt32(file.index + 1) - request.rawValue.user_data = userData - case .unlinkAt(let atDirectory, let path, let userData): + request.rawValue.user_data = context + case .unlinkAt(let atDirectory, let path, let context): request.operation = .unlinkAt request.fileDescriptor = atDirectory request.rawValue.addr = UInt64( @@ -376,7 +376,7 @@ extension IORequest { }) ) request.path = path - request.rawValue.user_data = userData + request.rawValue.user_data = context } return request } From 261ca250fe3d097247b903e141396dc28ee76c37 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 18 Apr 2025 22:20:09 +0000 Subject: [PATCH 055/102] Centralize on Errno for errors, and work around lifetime compiler crash. There's a second compiler crash still to work around though. --- Sources/System/IORing.swift | 159 ++++++++++++------------------------ 1 file changed, 52 insertions(+), 107 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index e72c9e8..6c994b9 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -118,7 +118,7 @@ internal func _enter( numEvents: UInt32, minCompletions: UInt32, flags: UInt32 -) throws(IORing.OperationError) -> Int32 { +) throws(Errno) -> Int32 { // Ring always needs enter right now; // TODO: support SQPOLL here while true { @@ -133,14 +133,14 @@ internal func _enter( //TODO: should we wait a bit on AGAIN? continue } else if ret < 0 { - throw(IORing.OperationError(result: -ret)) + throw(Errno(rawValue: -ret)) } else { return ret } } } -internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws(IORing.OperationError) { +internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws(Errno) { let flushedEvents = _flushQueue(ring: ring) _ = try _enter( ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0) @@ -193,7 +193,7 @@ internal func _getSubmissionEntry( private func setUpRing( queueDepth: UInt32, flags: IORing.SetupFlags, submissionRing: inout SQRing -) throws(IORing.SetupError) -> +) throws(Errno) -> (params: io_uring_params, ringDescriptor: Int32, ringPtr: UnsafeMutableRawPointer, ringSize: Int, sqes: UnsafeMutableRawPointer) { var params = io_uring_params() params.flags = flags.rawValue @@ -208,7 +208,7 @@ private func setUpRing( } if let err { - throw IORing.SetupError(setupResult: err.rawValue) + throw err } if params.features & IORING_FEAT_SINGLE_MMAP == 0 @@ -216,7 +216,7 @@ private func setUpRing( { close(ringDescriptor) // TODO: error handling - throw .missingRequiredFeatures + throw Errno.invalidArgument } let submitRingSize = @@ -239,9 +239,10 @@ private func setUpRing( ) if ringPtr == MAP_FAILED { + let errno = Errno.current perror("mmap") close(ringDescriptor) - throw .mapFailed + throw errno } let submissionRing = SQRing( @@ -285,52 +286,17 @@ private func setUpRing( ) if sqes == MAP_FAILED { + let errno = Errno.current perror("mmap") munmap(ringPtr, ringSize) close(ringDescriptor) - throw .mapFailed + throw errno } return (params: params, ringDescriptor: ringDescriptor, ringPtr: ringPtr!, ringSize: ringSize, sqes: sqes!) } public struct IORing: ~Copyable { - - /// Errors in either submitting operations or receiving operation completions - @frozen - public struct OperationError: Error, Hashable { - private var errorCode: Int - public static var operationCanceled: OperationError { .init(result: ECANCELED) } - - internal init(result: Int32) { - errorCode = Int(result) //TODO, flesh this out - } - } - - @frozen - public struct SetupError: Error, Hashable { - private var errorCode: Int - - public static var missingRequiredFeatures: SetupError { - .init(setupResult: -1) /* TODO: numeric value */ - } - - public static var mapFailed: SetupError { .init(setupResult: -2) } - - internal init(setupResult: Int32) { - errorCode = Int(setupResult) //TODO, flesh this out - } - } - - @frozen - public struct RegistrationError: Error, Hashable { - private var errorCode: Int - - internal init(registrationResult: Int32) { - errorCode = Int(registrationResult) //TODO, flesh this out - } - } - let ringFlags: UInt32 let ringDescriptor: Int32 @@ -346,8 +312,8 @@ public struct IORing: ~Copyable { let ringSize: Int let ringPtr: UnsafeMutableRawPointer - var _registeredFiles: [UInt32] = [] - var _registeredBuffers: [iovec] = [] + var _registeredFiles: [UInt32] + var _registeredBuffers: [iovec] var features = Features(rawValue: 0) @@ -375,7 +341,7 @@ public struct IORing: ~Copyable { //TODO: should IORING_SETUP_NO_SQARRAY be the default? do we need to adapt anything to it? } - public init(queueDepth: UInt32, flags: SetupFlags) throws(SetupError) { + public init(queueDepth: UInt32, flags: SetupFlags) throws(Errno) { let (params, tmpRingDescriptor, tmpRingPtr, tmpRingSize, sqes) = try setUpRing(queueDepth: queueDepth, flags: flags, submissionRing: &submissionRing) // All throws need to be before initializing ivars here to avoid // "error: conditional initialization or destruction of noncopyable types is not supported; @@ -384,6 +350,8 @@ public struct IORing: ~Copyable { ringDescriptor = tmpRingDescriptor ringPtr = tmpRingPtr ringSize = tmpRingSize + _registeredFiles = [] + _registeredBuffers = [] submissionQueueEntries = UnsafeMutableBufferPointer( start: sqes.assumingMemoryBound(to: io_uring_sqe.self), @@ -417,13 +385,13 @@ public struct IORing: ~Copyable { minimumCount: UInt32, maximumCount: UInt32, extraArgs: UnsafeMutablePointer? = nil, - consumer: (consuming IOCompletion?, OperationError?, Bool) throws(Err) -> Void + consumer: (consuming IOCompletion?, Errno?, Bool) throws(Err) -> Void ) throws(Err) { var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { count += 1 if completion.result < 0 { - try consumer(nil, OperationError(result: completion.result), false) + try consumer(nil, Errno(rawValue: -completion.result), false) } else { try consumer(completion, nil, false) } @@ -469,7 +437,7 @@ public struct IORing: ~Copyable { while let completion = _tryConsumeCompletion(ring: completionRing) { count += 1 if completion.result < 0 { - try consumer(nil, OperationError(result: completion.result), false) + try consumer(nil, Errno(rawValue: -completion.result), false) } else { try consumer(completion, nil, false) } @@ -483,52 +451,37 @@ public struct IORing: ~Copyable { internal func _blockingConsumeOneCompletion( extraArgs: UnsafeMutablePointer? = nil - ) throws(OperationError) -> IOCompletion { + ) throws(Errno) -> IOCompletion { var result: IOCompletion? = nil - do { - try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { - (completion: consuming IOCompletion?, error, done) in - if let error { - throw error - } - if let completion { - result = consume completion - } + try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { + (completion: consuming IOCompletion?, error, done) throws(Errno) in + if let error { + throw error + } + if let completion { + result = consume completion } - } catch (let e) { - throw e as! OperationError //TODO: why is this needed? } return result.take()! } public func blockingConsumeCompletion( timeout: Duration? = nil - ) throws(OperationError) -> IOCompletion { + ) throws(Errno) -> IOCompletion { if let timeout { var ts = __kernel_timespec( tv_sec: timeout.components.seconds, tv_nsec: timeout.components.attoseconds / 1_000_000_000 ) - var err: OperationError? = nil - var result: IOCompletion? = nil - result = withUnsafePointer(to: &ts) { tsPtr in + return try withUnsafePointer(to: &ts) { (tsPtr) throws(Errno) -> IOCompletion in var args = io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, pad: 0, ts: UInt64(UInt(bitPattern: tsPtr)) ) - do { - return try _blockingConsumeOneCompletion(extraArgs: &args) - } catch (let e) { - err = (e as! OperationError) - return nil - } + return try _blockingConsumeOneCompletion(extraArgs: &args) } - guard let result else { - throw(err!) - } - return result } else { return try _blockingConsumeOneCompletion() } @@ -537,31 +490,23 @@ public struct IORing: ~Copyable { public func blockingConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (consuming IOCompletion?, OperationError?, Bool) throws(Err) -> Void + consumer: (consuming IOCompletion?, Errno?, Bool) throws(Err) -> Void ) throws(Err) { if let timeout { var ts = __kernel_timespec( tv_sec: timeout.components.seconds, tv_nsec: timeout.components.attoseconds / 1_000_000_000 ) - var err: Err? = nil - withUnsafePointer(to: &ts) { tsPtr in + try withUnsafePointer(to: &ts) { (tsPtr) throws(Err) in var args = io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, pad: 0, ts: UInt64(UInt(bitPattern: tsPtr)) ) - do { - try _blockingConsumeCompletionGuts( - minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args, - consumer: consumer) - } catch (let e) { - err = (e as! Err) //TODO: why is `e` coming in as `any Error`? That seems wrong - } - } - if let err { - throw(err) + try _blockingConsumeCompletionGuts( + minimumCount: minimumCount, maximumCount: UInt32.max, extraArgs: &args, + consumer: consumer) } } else { try _blockingConsumeCompletionGuts( @@ -591,7 +536,7 @@ public struct IORing: ~Copyable { return nil } - public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(RegistrationError) { + public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) { var rawfd = descriptor.rawValue let result = withUnsafePointer(to: &rawfd) { fdptr in let result = io_uring_register( @@ -600,14 +545,14 @@ public struct IORing: ~Copyable { UnsafeMutableRawPointer(mutating: fdptr), 1 ) - return result >= 0 ? nil : Errno.current + return result >= 0 ? nil : Errno(rawValue: -result) } if let result { - throw(RegistrationError(registrationResult: result.rawValue)) + throw result } } - public mutating func unregisterEventFD() throws(RegistrationError) { + public mutating func unregisterEventFD() throws(Errno) { let result = io_uring_register( ringDescriptor, IORING_UNREGISTER_EVENTFD, @@ -615,11 +560,11 @@ public struct IORing: ~Copyable { 0 ) if result < 0 { - throw(RegistrationError(registrationResult: result)) + throw Errno(rawValue: -result) } } - public mutating func registerFileSlots(count: Int) throws(RegistrationError) -> RegisteredResources< + public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources< IORingFileSlot.Resource > { precondition(_registeredFiles.isEmpty) @@ -633,11 +578,11 @@ public struct IORing: ~Copyable { UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), UInt32(truncatingIfNeeded: count) ) - return result >= 0 ? nil : Errno.current + return result >= 0 ? nil : Errno(rawValue: -result) } - - guard regResult == nil else { - throw RegistrationError(registrationResult: regResult!.rawValue) + + if let regResult { + throw regResult } _registeredFiles = files @@ -652,7 +597,7 @@ public struct IORing: ~Copyable { RegisteredResources(resources: _registeredFiles) } - public mutating func registerBuffers(_ buffers: some Collection) throws(RegistrationError) + public mutating func registerBuffers(_ buffers: some Collection) throws(Errno) -> RegisteredResources { precondition(buffers.count < UInt32.max) @@ -666,11 +611,11 @@ public struct IORing: ~Copyable { UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), UInt32(truncatingIfNeeded: buffers.count) ) - return result >= 0 ? nil : Errno.current + return result >= 0 ? nil : Errno(rawValue: -result) } - guard regResult == nil else { - throw RegistrationError(registrationResult: regResult!.rawValue) + if let regResult { + throw regResult } // TODO: error handling @@ -678,7 +623,7 @@ public struct IORing: ~Copyable { return registeredBuffers } - public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) throws(RegistrationError) + public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) throws(Errno) -> RegisteredResources { try registerBuffers(buffers) @@ -708,14 +653,14 @@ public struct IORing: ~Copyable { fatalError("failed to unregister buffers: TODO") } - public func submitPreparedRequests() throws(OperationError) { + public func submitPreparedRequests() throws(Errno) { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } public func submitPreparedRequestsAndConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (consuming IOCompletion?, OperationError?, Bool) throws(Err) -> Void + consumer: (consuming IOCompletion?, Errno?, Bool) throws(Err) -> Void ) throws(Err) { //TODO: optimize this to one uring_enter do { @@ -757,7 +702,7 @@ public struct IORing: ~Copyable { prepare(linkedRequests: linkedRequests) } - public mutating func submit(linkedRequests: IORequest...) throws(OperationError) { + public mutating func submit(linkedRequests: IORequest...) throws(Errno) { prepare(linkedRequests: linkedRequests) try submitPreparedRequests() } From c029c1bfbd0da1f8672229dc80f39626617c1abb Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 18 Apr 2025 15:22:17 -0700 Subject: [PATCH 056/102] Proposal updates and a minor change to setup flags --- NNNN-swift-system-io-uring.md | 59 ++++++++++++++++++----------------- Sources/System/IORing.swift | 2 +- 2 files changed, 31 insertions(+), 30 deletions(-) diff --git a/NNNN-swift-system-io-uring.md b/NNNN-swift-system-io-uring.md index 5c08588..0d8cf8e 100644 --- a/NNNN-swift-system-io-uring.md +++ b/NNNN-swift-system-io-uring.md @@ -79,8 +79,6 @@ Since neither polling nor synchronously waiting is optimal in many cases, `IORin Unfortunately the underlying kernel API makes it relatively difficult to determine which `IORequest` led to a given `IOCompletion`, so it's expected that users will need to create this association themselves via the context parameter. -`IORingError` represents failure of an operation. - `IORing.Features` describes the supported features of the underlying kernel `IORing` implementation, which can be used to provide graceful reduction in functionality when running on older systems. ## Detailed design @@ -97,10 +95,22 @@ extension IORingBuffer { // IORing is intentionally not Sendable, to avoid internal locking overhead public struct IORing: ~Copyable { - public init(queueDepth: UInt32) throws(IORingError) + public init(queueDepth: UInt32, flags: IORing.SetupFlags) throws(Errno) - public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(IORingError) - public mutating func unregisterEventFD(_ descriptor: FileDescriptor) throws(IORingError) + public struct SetupFlags: OptionSet, RawRepresentable, Hashable { + public var rawValue: UInt32 + public init(rawValue: UInt32) + public static var pollCompletions: SetupFlags //IORING_SETUP_IOPOLL + public static var pollSubmissions: SetupFlags //IORING_SETUP_SQPOLL + public static var clampMaxEntries: SetupFlags //IORING_SETUP_CLAMP + public static var startDisabled: SetupFlags //IORING_SETUP_R_DISABLED + public static var continueSubmittingOnError: SetupFlags //IORING_SETUP_SUBMIT_ALL + public static var singleSubmissionThread: SetupFlags //IORING_SETUP_SINGLE_ISSUER + public static var deferRunningTasks: SetupFlags //IORING_SETUP_DEFER_TASKRUN + } + + public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) + public mutating func unregisterEventFD(_ descriptor: FileDescriptor) throws(Errno) // An IORing.RegisteredResources is a view into the buffers or files registered with the ring, if any public struct RegisteredResources: RandomAccessCollection { @@ -108,7 +118,7 @@ public struct IORing: ~Copyable { public subscript(position: UInt16) -> IOResource // This is useful because io_uring likes to use UInt16s as indexes } - public mutating func registerFileSlots(count: Int) throws(IORingError) -> RegisteredResources + public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources public func unregisterFiles() @@ -116,11 +126,11 @@ public struct IORing: ~Copyable { public mutating func registerBuffers( _ buffers: some Collection - ) throws(IORingError) -> RegisteredResources + ) throws(Errno) -> RegisteredResources public mutating func registerBuffers( _ buffers: UnsafeMutableRawBufferPointer... - ) throws(IORingError) -> RegisteredResources + ) throws(Errno) -> RegisteredResources public func unregisterBuffers() @@ -129,32 +139,32 @@ public struct IORing: ~Copyable { public func prepare(requests: IORequest...) public func prepare(linkedRequests: IORequest...) - public func submitPreparedRequests(timeout: Duration? = nil) throws(IORingError) - public func submit(requests: IORequest..., timeout: Duration? = nil) throws(IORingError) - public func submit(linkedRequests: IORequest..., timeout: Duration? = nil) throws(IORingError) + public func submitPreparedRequests(timeout: Duration? = nil) throws(Errno) + public func submit(requests: IORequest..., timeout: Duration? = nil) throws(Errno) + public func submit(linkedRequests: IORequest..., timeout: Duration? = nil) throws(Errno) - public func submitPreparedRequests() throws(IORingError) - public func submitPreparedRequestsAndWait(timeout: Duration? = nil) throws(IORingError) + public func submitPreparedRequests() throws(Errno) + public func submitPreparedRequestsAndWait(timeout: Duration? = nil) throws(Errno) public func submitPreparedRequestsAndConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (consuming IOCompletion?, IORingError?, Bool) throws(E) -> Void + consumer: (consuming IOCompletion?, Errno?, Bool) throws(E) -> Void ) throws(E) public func blockingConsumeCompletion( timeout: Duration? = nil - ) throws(IORingError) -> IOCompletion + ) throws(Errno) -> IOCompletion public func blockingConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (consuming IOCompletion?, IORingError?, Bool) throws(E) -> Void + consumer: (consuming IOCompletion?, Errno?, Bool) throws(E) -> Void ) throws(E) public func tryConsumeCompletion() -> IOCompletion? - public struct Features: OptionSet { + public struct Features: OptionSet, RawRepresentable, Hashable { let rawValue: UInt32 public init(rawValue: UInt32) @@ -176,7 +186,7 @@ public struct IORing: ~Copyable { public static let minimumTimeout: Bool //IORING_FEAT_MIN_TIMEOUT public static let bundledSendReceive: Bool //IORING_FEAT_RECVSEND_BUNDLE } - public static var supportedFeatures: Features + public var supportedFeatures: Features } public struct IORequest: ~Copyable { @@ -329,19 +339,10 @@ public struct IOCompletion { public var result: Int32 - public var error: IORingError? // Convenience wrapper over `result` + public var error: Errno? // Convenience wrapper over `result` public var flags: Flags } - -public struct IORingError: Error, Equatable { - static var missingRequiredFeatures: IORingError - static var operationCanceled: IORingError - static var timedOut: IORingError - static var resourceRegistrationFailed: IORingError - // Other error values to be filled out as the set of supported operations expands in the future - static var unknown: IORingError(errorCode: Int) -} ``` @@ -463,7 +464,7 @@ func submitLinkedRequestsAndWait( * We could multiplex all IO onto a single actor as `AsyncBytes` currently does, but this has a number of downsides that make it entirely unsuitable to server usage. Most notably, it eliminates IO parallelism entirely. * Using POSIX AIO instead of or as well as io_uring would greatly increase our ability to support older kernels and other Unix systems, but it has well-documented performance and usability issues that have prevented its adoption elsewhere, and apply just as much to Swift. * Earlier versions of this proposal had higher level "managed" abstractions over IORing. These have been removed due to lack of interest from clients, but could be added back later if needed. -* I considered making any or all of `IORingError`, `IOCompletion`, and `IORequest` nested struct declarations inside `IORing`. The main reason I haven't done so is I was a little concerned about the ambiguity of having a type called `Error`. I'd be particularly interested in feedback on this choice. +* I considered having dedicated error types for IORing, but eventually decided throwing Errno was more consistent with other platform APIs * IOResource was originally a class in an attempt to manage the lifetime of the resource via language features. Changing to the current model of it being a copyable struct didn't make the lifetime management any less safe (the IORing still owns the actual resource), and reduces overhead. In the future it would be neat if we could express IOResources as being borrowed from the IORing so they can't be used after its lifetime. ## Acknowledgments diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 6c994b9..81efe12 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -318,7 +318,7 @@ public struct IORing: ~Copyable { var features = Features(rawValue: 0) @frozen - public struct SetupFlags: OptionSet, RawRepresentable { + public struct SetupFlags: OptionSet, RawRepresentable, Hashable { public var rawValue: UInt32 @inlinable public init(rawValue: UInt32) { From 05eac87c08b651d93c644fade578fea4bf13f1cd Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 18 Apr 2025 23:37:50 +0000 Subject: [PATCH 057/102] It compiles again! --- Sources/CSystem/include/io_uring.h | 8 ++++---- Sources/System/IORing.swift | 7 ++++++- Tests/SystemTests/IORingTests.swift | 4 ++-- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index 5cab757..75a07e5 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -34,25 +34,25 @@ # endif #endif -int io_uring_register(int fd, unsigned int opcode, void *arg, +static inline int io_uring_register(int fd, unsigned int opcode, void *arg, unsigned int nr_args) { return syscall(__NR_io_uring_register, fd, opcode, arg, nr_args); } -int io_uring_setup(unsigned int entries, struct io_uring_params *p) +static inline int io_uring_setup(unsigned int entries, struct io_uring_params *p) { return syscall(__NR_io_uring_setup, entries, p); } -int io_uring_enter2(int fd, unsigned int to_submit, unsigned int min_complete, +static inline int io_uring_enter2(int fd, unsigned int to_submit, unsigned int min_complete, unsigned int flags, void *args, size_t sz) { return syscall(__NR_io_uring_enter, fd, to_submit, min_complete, flags, args, _NSIG / 8); } -int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete, +static inline int io_uring_enter(int fd, unsigned int to_submit, unsigned int min_complete, unsigned int flags, sigset_t *sig) { return io_uring_enter2(fd, to_submit, min_complete, flags, sig, _NSIG / 8); diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 81efe12..9b45f56 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -654,7 +654,12 @@ public struct IORing: ~Copyable { } public func submitPreparedRequests() throws(Errno) { - try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) + switch submissionRing { + case .some(let submissionRing): + try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) + case .none: + fatalError() + } } public func submitPreparedRequestsAndConsumeCompletions( diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 306516b..57437e4 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -8,11 +8,11 @@ import System final class IORingTests: XCTestCase { func testInit() throws { - _ = try IORing(queueDepth: 32) + _ = try IORing(queueDepth: 32, flags: []) } func testNop() throws { - var ring = try IORing(queueDepth: 32) + var ring = try IORing(queueDepth: 32, flags: []) try ring.submit(linkedRequests: IORequest.nop()) let completion = try ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) From 7798f0c9577319dab7fe5080c9ed4bc4e856c785 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 21 Apr 2025 23:18:33 +0000 Subject: [PATCH 058/102] Add cancellation support and drop gerunds --- Sources/System/IORequest.swift | 116 ++++++++++++++++++++++--- Sources/System/RawIORequest.swift | 11 +++ Tests/SystemTests/IORequestTests.swift | 2 +- 3 files changed, 115 insertions(+), 14 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index c836fd3..df50521 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -81,6 +81,18 @@ internal enum IORequestCore { path: FilePath, context: UInt64 = 0 ) + case cancel( + flags: UInt32, + targetContext: UInt64 + ) + case cancelFD( + flags: UInt32, + targetFD: FileDescriptor + ) + case cancelFDSlot( + flags: UInt32, + target: IORingFileSlot + ) } @inline(__always) @@ -160,7 +172,7 @@ extension IORequest { IORequest(core: .nop) } - public static func reading( + public static func read( _ file: IORingFileSlot, into buffer: IORingBuffer, at offset: UInt64 = 0, @@ -169,7 +181,7 @@ extension IORequest { IORequest(core: .readSlot(file: file, buffer: buffer, offset: offset, context: context)) } - public static func reading( + public static func read( _ file: FileDescriptor, into buffer: IORingBuffer, at offset: UInt64 = 0, @@ -178,7 +190,7 @@ extension IORequest { IORequest(core: .read(file: file, buffer: buffer, offset: offset, context: context)) } - public static func reading( + public static func read( _ file: IORingFileSlot, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, @@ -189,7 +201,7 @@ extension IORequest { file: file, buffer: buffer, offset: offset, context: context)) } - public static func reading( + public static func read( _ file: FileDescriptor, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, @@ -199,7 +211,7 @@ extension IORequest { core: .readUnregistered(file: file, buffer: buffer, offset: offset, context: context)) } - public static func writing( + public static func write( _ buffer: IORingBuffer, into file: IORingFileSlot, at offset: UInt64 = 0, @@ -208,7 +220,7 @@ extension IORequest { IORequest(core: .writeSlot(file: file, buffer: buffer, offset: offset, context: context)) } - public static func writing( + public static func write( _ buffer: IORingBuffer, into file: FileDescriptor, at offset: UInt64 = 0, @@ -217,7 +229,7 @@ extension IORequest { IORequest(core: .write(file: file, buffer: buffer, offset: offset, context: context)) } - public static func writing( + public static func write( _ buffer: UnsafeMutableRawBufferPointer, into file: IORingFileSlot, at offset: UInt64 = 0, @@ -228,7 +240,7 @@ extension IORequest { file: file, buffer: buffer, offset: offset, context: context)) } - public static func writing( + public static func write( _ buffer: UnsafeMutableRawBufferPointer, into file: FileDescriptor, at offset: UInt64 = 0, @@ -239,21 +251,21 @@ extension IORequest { ) } - public static func closing( + public static func close( _ file: FileDescriptor, context: UInt64 = 0 ) -> IORequest { IORequest(core: .close(file, context: context)) } - public static func closing( + public static func close( _ file: IORingFileSlot, context: UInt64 = 0 ) -> IORequest { IORequest(core: .closeSlot(file, context: context)) } - public static func opening( + public static func open( _ path: FilePath, in directory: FileDescriptor, into slot: IORingFileSlot, @@ -268,7 +280,7 @@ extension IORequest { permissions: permissions, intoSlot: slot, context: context)) } - public static func opening( + public static func open( _ path: FilePath, in directory: FileDescriptor, mode: FileDescriptor.AccessMode, @@ -283,7 +295,7 @@ extension IORequest { )) } - public static func unlinking( + public static func unlink( _ path: FilePath, in directory: FileDescriptor, context: UInt64 = 0 @@ -291,6 +303,71 @@ extension IORequest { IORequest(core: .unlinkAt(atDirectory: directory, path: path, context: context)) } + // Cancel + + /* + * ASYNC_CANCEL flags. + * + * IORING_ASYNC_CANCEL_ALL Cancel all requests that match the given key + * IORING_ASYNC_CANCEL_FD Key off 'fd' for cancelation 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 + */ + //TODO: why aren't these showing up from the header import? + private static var IORING_ASYNC_CANCEL_ALL: UInt32 { (1 as UInt32) << 0 } + private static var IORING_ASYNC_CANCEL_FD: UInt32 { (1 as UInt32) << 1 } + private static var IORING_ASYNC_CANCEL_ANY: UInt32 { (1 as UInt32) << 2 } + private static var IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { (1 as UInt32) << 3 } + private static var IORING_ASYNC_CANCEL_USERDATA: UInt32 { (1 as UInt32) << 4 } + private static var IORING_ASYNC_CANCEL_OP: UInt32 { (1 as UInt32) << 5 } + + + public enum CancellationMatch { + case all + case first + } + + public static func cancel( + _ matchAll: CancellationMatch, + matchingContext: UInt64, + ) -> IORequest { + switch matchAll { + case .all: + IORequest(core: .cancel(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) + case .first: + IORequest(core: .cancel(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) + } + } + + public static func cancel( + _ matchAll: CancellationMatch, + matchingFileDescriptor: FileDescriptor, + ) -> IORequest { + switch matchAll { + case .all: + IORequest(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD, targetFD: matchingFileDescriptor)) + case .first: + IORequest(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD, targetFD: matchingFileDescriptor)) + } + } + + public static func cancel( + _ matchAll: CancellationMatch, + matchingFile: IORingFileSlot, + ) -> IORequest { + switch matchAll { + case .all: + IORequest(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD_FIXED, target: matchingFile)) + case .first: + IORequest(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD_FIXED, target: matchingFile)) + } + } + + //TODO: add support for CANCEL_OP + @inline(__always) public consuming func makeRawRequest() -> RawIORequest { var request = RawIORequest() @@ -377,7 +454,20 @@ extension IORequest { ) request.path = path request.rawValue.user_data = context + case .cancel(let flags, let targetContext): + request.operation = .asyncCancel + request.cancel_flags = flags + request.addr = targetContext + case .cancelFD(let flags, let targetFD): + request.operation = .asyncCancel + request.cancel_flags = flags + request.fileDescriptor = targetFD + case .cancelFDSlot(let flags, let target): + request.operation = .asyncCancel + request.cancel_flags = flags + request.rawValue.fd = Int32(target.index) } + return request } } diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 50c97c6..6190b0d 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -26,6 +26,7 @@ extension RawIORequest { case sendMessage = 9 case receiveMessage = 10 // ... + case asyncCancel = 14 case link_timeout = 15 // ... case openAt = 18 @@ -61,6 +62,16 @@ extension RawIORequest { set { rawValue.opcode = newValue.rawValue } } + var cancel_flags: UInt32 { + get { rawValue.cancel_flags } + set { rawValue.cancel_flags = newValue } + } + + var addr: UInt64 { + get { rawValue.addr } + set { rawValue.addr = newValue } + } + public var flags: Flags { get { Flags(rawValue: rawValue.flags) } set { rawValue.flags = newValue.rawValue } diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 4aaf754..6642293 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -30,7 +30,7 @@ final class IORequestTests: XCTestCase { func testOpenatFixedFile() throws { let pathPtr = UnsafePointer(bitPattern: 0x414141410badf00d)! let fileSlot: IORingFileSlot = IORingFileSlot(resource: UInt32.max, index: 0) - let req = IORequest.opening(FilePath(platformString: pathPtr), + let req = IORequest.open(FilePath(platformString: pathPtr), in: FileDescriptor(rawValue: -100), into: fileSlot, mode: .readOnly, From 9d325b29ceb88760b55a5900d6cb796e5cbc1a20 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 21 Apr 2025 23:23:26 +0000 Subject: [PATCH 059/102] Change IORingFileSlot and IORingBuffer to be nested types in IORing --- Sources/System/IORequest.swift | 52 +++++++++++++------------- Sources/System/IORing.swift | 38 +++++++++---------- Tests/SystemTests/IORequestTests.swift | 2 +- 3 files changed, 46 insertions(+), 46 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index df50521..f89facd 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -17,12 +17,12 @@ internal enum IORequestCore { FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, - intoSlot: IORingFileSlot, + intoSlot: IORing.RegisteredFile, context: UInt64 = 0 ) case read( file: FileDescriptor, - buffer: IORingBuffer, + buffer: IORing.RegisteredBuffer, offset: UInt64 = 0, context: UInt64 = 0 ) @@ -33,20 +33,20 @@ internal enum IORequestCore { context: UInt64 = 0 ) case readSlot( - file: IORingFileSlot, - buffer: IORingBuffer, + file: IORing.RegisteredFile, + buffer: IORing.RegisteredBuffer, offset: UInt64 = 0, context: UInt64 = 0 ) case readUnregisteredSlot( - file: IORingFileSlot, + file: IORing.RegisteredFile, buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0, context: UInt64 = 0 ) case write( file: FileDescriptor, - buffer: IORingBuffer, + buffer: IORing.RegisteredBuffer, offset: UInt64 = 0, context: UInt64 = 0 ) @@ -57,13 +57,13 @@ internal enum IORequestCore { context: UInt64 = 0 ) case writeSlot( - file: IORingFileSlot, - buffer: IORingBuffer, + file: IORing.RegisteredFile, + buffer: IORing.RegisteredBuffer, offset: UInt64 = 0, context: UInt64 = 0 ) case writeUnregisteredSlot( - file: IORingFileSlot, + file: IORing.RegisteredFile, buffer: UnsafeMutableRawBufferPointer, offset: UInt64 = 0, context: UInt64 = 0 @@ -73,7 +73,7 @@ internal enum IORequestCore { context: UInt64 = 0 ) case closeSlot( - IORingFileSlot, + IORing.RegisteredFile, context: UInt64 = 0 ) case unlinkAt( @@ -91,14 +91,14 @@ internal enum IORequestCore { ) case cancelFDSlot( flags: UInt32, - target: IORingFileSlot + target: IORing.RegisteredFile ) } @inline(__always) internal func makeRawRequest_readWrite_registered( file: FileDescriptor, - buffer: IORingBuffer, + buffer: IORing.RegisteredBuffer, offset: UInt64, context: UInt64 = 0, request: consuming RawIORequest @@ -113,8 +113,8 @@ internal func makeRawRequest_readWrite_registered( @inline(__always) internal func makeRawRequest_readWrite_registered_slot( - file: IORingFileSlot, - buffer: IORingBuffer, + file: IORing.RegisteredFile, + buffer: IORing.RegisteredBuffer, offset: UInt64, context: UInt64 = 0, request: consuming RawIORequest @@ -145,7 +145,7 @@ internal func makeRawRequest_readWrite_unregistered( @inline(__always) internal func makeRawRequest_readWrite_unregistered_slot( - file: IORingFileSlot, + file: IORing.RegisteredFile, buffer: UnsafeMutableRawBufferPointer, offset: UInt64, context: UInt64 = 0, @@ -173,8 +173,8 @@ extension IORequest { } public static func read( - _ file: IORingFileSlot, - into buffer: IORingBuffer, + _ file: IORing.RegisteredFile, + into buffer: IORing.RegisteredBuffer, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest { @@ -183,7 +183,7 @@ extension IORequest { public static func read( _ file: FileDescriptor, - into buffer: IORingBuffer, + into buffer: IORing.RegisteredBuffer, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest { @@ -191,7 +191,7 @@ extension IORequest { } public static func read( - _ file: IORingFileSlot, + _ file: IORing.RegisteredFile, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, context: UInt64 = 0 @@ -212,8 +212,8 @@ extension IORequest { } public static func write( - _ buffer: IORingBuffer, - into file: IORingFileSlot, + _ buffer: IORing.RegisteredBuffer, + into file: IORing.RegisteredFile, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest { @@ -221,7 +221,7 @@ extension IORequest { } public static func write( - _ buffer: IORingBuffer, + _ buffer: IORing.RegisteredBuffer, into file: FileDescriptor, at offset: UInt64 = 0, context: UInt64 = 0 @@ -231,7 +231,7 @@ extension IORequest { public static func write( _ buffer: UnsafeMutableRawBufferPointer, - into file: IORingFileSlot, + into file: IORing.RegisteredFile, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest { @@ -259,7 +259,7 @@ extension IORequest { } public static func close( - _ file: IORingFileSlot, + _ file: IORing.RegisteredFile, context: UInt64 = 0 ) -> IORequest { IORequest(core: .closeSlot(file, context: context)) @@ -268,7 +268,7 @@ extension IORequest { public static func open( _ path: FilePath, in directory: FileDescriptor, - into slot: IORingFileSlot, + into slot: IORing.RegisteredFile, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, @@ -356,7 +356,7 @@ extension IORequest { public static func cancel( _ matchAll: CancellationMatch, - matchingFile: IORingFileSlot, + matchingFile: IORing.RegisteredFile, ) -> IORequest { switch matchAll { case .all: diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 9b45f56..89391b0 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -66,20 +66,6 @@ public struct IOResource { } } -public typealias IORingFileSlot = IOResource -public typealias IORingBuffer = IOResource - -extension IORingFileSlot { - public var unsafeFileSlot: Int { - return index - } -} -extension IORingBuffer { - public var unsafeBuffer: UnsafeMutableRawBufferPointer { - return .init(start: resource.iov_base, count: resource.iov_len) - } -} - @inline(__always) internal func _writeRequest( _ request: __owned RawIORequest, ring: inout SQRing, @@ -317,6 +303,9 @@ public struct IORing: ~Copyable { var features = Features(rawValue: 0) + public typealias RegisteredFile = IOResource + public typealias RegisteredBuffer = IOResource + @frozen public struct SetupFlags: OptionSet, RawRepresentable, Hashable { public var rawValue: UInt32 @@ -565,7 +554,7 @@ public struct IORing: ~Copyable { } public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources< - IORingFileSlot.Resource + IORing.RegisteredFile.Resource > { precondition(_registeredFiles.isEmpty) precondition(count < UInt32.max) @@ -593,12 +582,12 @@ public struct IORing: ~Copyable { fatalError("failed to unregister files") } - public var registeredFileSlots: RegisteredResources { + public var registeredFileSlots: RegisteredResources { RegisteredResources(resources: _registeredFiles) } public mutating func registerBuffers(_ buffers: some Collection) throws(Errno) - -> RegisteredResources + -> RegisteredResources { precondition(buffers.count < UInt32.max) precondition(_registeredBuffers.isEmpty) @@ -624,7 +613,7 @@ public struct IORing: ~Copyable { } public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) throws(Errno) - -> RegisteredResources + -> RegisteredResources { try registerBuffers(buffers) } @@ -645,7 +634,7 @@ public struct IORing: ~Copyable { } } - public var registeredBuffers: RegisteredResources { + public var registeredBuffers: RegisteredResources { RegisteredResources(resources: _registeredBuffers) } @@ -750,3 +739,14 @@ public struct IORing: ~Copyable { close(ringDescriptor) } } + +extension IORing.RegisteredFile { + public var unsafeFileSlot: Int { + return index + } +} +extension IORing.RegisteredBuffer { + public var unsafeBuffer: UnsafeMutableRawBufferPointer { + return .init(start: resource.iov_base, count: resource.iov_len) + } +} \ No newline at end of file diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 6642293..9705026 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -29,7 +29,7 @@ final class IORequestTests: XCTestCase { func testOpenatFixedFile() throws { let pathPtr = UnsafePointer(bitPattern: 0x414141410badf00d)! - let fileSlot: IORingFileSlot = IORingFileSlot(resource: UInt32.max, index: 0) + let fileSlot = IORing.RegisteredFile(resource: UInt32.max, index: 0) let req = IORequest.open(FilePath(platformString: pathPtr), in: FileDescriptor(rawValue: -100), into: fileSlot, From ea77ef8a21e45e28c267c68a6f318fe578acae69 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 21 Apr 2025 23:24:09 +0000 Subject: [PATCH 060/102] Minor cleanup --- Sources/System/IORing.swift | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 89391b0..54e3b10 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -553,9 +553,7 @@ public struct IORing: ~Copyable { } } - public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources< - IORing.RegisteredFile.Resource - > { + public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources { precondition(_registeredFiles.isEmpty) precondition(count < UInt32.max) let files = [UInt32](repeating: UInt32.max, count: count) From baa3d625693df48a7882c689350431fa7794e361 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 21 Apr 2025 23:26:14 +0000 Subject: [PATCH 061/102] API tweak --- Sources/System/IORequest.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index f89facd..4be37d3 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -344,7 +344,7 @@ extension IORequest { public static func cancel( _ matchAll: CancellationMatch, - matchingFileDescriptor: FileDescriptor, + matching: FileDescriptor, ) -> IORequest { switch matchAll { case .all: @@ -356,7 +356,7 @@ extension IORequest { public static func cancel( _ matchAll: CancellationMatch, - matchingFile: IORing.RegisteredFile, + matching: IORing.RegisteredFile, ) -> IORequest { switch matchAll { case .all: From 3760dc265ac2ebce5dfa87d030148edc2e7b0d30 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 21 Apr 2025 16:35:08 -0700 Subject: [PATCH 062/102] Nest IOResource, and update proposal to match --- NNNN-swift-system-io-uring.md | 70 ++++++++++++++++------------------- Sources/System/IORing.swift | 34 ++++++++--------- 2 files changed, 48 insertions(+), 56 deletions(-) diff --git a/NNNN-swift-system-io-uring.md b/NNNN-swift-system-io-uring.md index 0d8cf8e..2bd981d 100644 --- a/NNNN-swift-system-io-uring.md +++ b/NNNN-swift-system-io-uring.md @@ -33,7 +33,7 @@ We propose a *low level, unopinionated* Swift interface for io_uring on Linux (s * Enqueueing IO requests * Dequeueing IO completions -`struct IOResource` represents, via its two typealiases `IORingFileSlot` and `IORingBuffer`, registered file descriptors and buffers. +`struct RegisteredResource` represents, via its two typealiases `IORing.RegisteredFile` and `IORing.RegisteredBuffer`, registered file descriptors and buffers. `struct IORequest: ~Copyable` represents an IO operation that can be enqueued for the kernel to execute. It supports a wide variety of operations matching traditional unix file and socket operations. @@ -43,7 +43,7 @@ IORequest operations are expressed as overloaded static methods on `IORequest`, public static func open( _ path: FilePath, in directory: FileDescriptor, - into slot: IORingFileSlot, + into slot: IORing.RegisteredFile, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, @@ -84,14 +84,6 @@ Unfortunately the underlying kernel API makes it relatively difficult to determi ## Detailed design ```swift -public struct IOResource { } -public typealias IORingFileSlot = IOResource -public typealias IORingBuffer = IOResource - -extension IORingBuffer { - public var unsafeBuffer: UnsafeMutableRawBufferPointer -} - // IORing is intentionally not Sendable, to avoid internal locking overhead public struct IORing: ~Copyable { @@ -111,6 +103,10 @@ public struct IORing: ~Copyable { public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) public mutating func unregisterEventFD(_ descriptor: FileDescriptor) throws(Errno) + + public struct RegisteredResource { } + public typealias RegisteredFile = RegisteredResource + public typealias RegisteredBuffer = RegisteredResource // An IORing.RegisteredResources is a view into the buffers or files registered with the ring, if any public struct RegisteredResources: RandomAccessCollection { @@ -118,23 +114,23 @@ public struct IORing: ~Copyable { public subscript(position: UInt16) -> IOResource // This is useful because io_uring likes to use UInt16s as indexes } - public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources + public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources public func unregisterFiles() - public var registeredFileSlots: RegisteredResources + public var registeredFileSlots: RegisteredResources public mutating func registerBuffers( _ buffers: some Collection - ) throws(Errno) -> RegisteredResources + ) throws(Errno) -> RegisteredResources public mutating func registerBuffers( _ buffers: UnsafeMutableRawBufferPointer... - ) throws(Errno) -> RegisteredResources + ) throws(Errno) -> RegisteredResources public func unregisterBuffers() - public var registeredBuffers: RegisteredResources + public var registeredBuffers: RegisteredResources public func prepare(requests: IORequest...) public func prepare(linkedRequests: IORequest...) @@ -189,27 +185,31 @@ public struct IORing: ~Copyable { public var supportedFeatures: Features } +extension IORing.RegisteredBuffer { + public var unsafeBuffer: UnsafeMutableRawBufferPointer +} + public struct IORequest: ~Copyable { public static func nop(context: UInt64 = 0) -> IORequest // overloads for each combination of registered vs unregistered buffer/descriptor // Read public static func read( - _ file: IORingFileSlot, - into buffer: IORingBuffer, + _ file: IORing.RegisteredFile, + into buffer: IORing.RegisteredBuffer, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest public static func read( _ file: FileDescriptor, - into buffer: IORingBuffer, + into buffer: IORing.RegisteredBuffer, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest public static func read( - _ file: IORingFileSlot, + _ file: IORing.RegisteredFile, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, context: UInt64 = 0 @@ -224,14 +224,14 @@ public struct IORequest: ~Copyable { // Write public static func write( - _ buffer: IORingBuffer, - into file: IORingFileSlot, + _ buffer: IORing.RegisteredBuffer, + into file: IORing.RegisteredFile, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest public static func write( - _ buffer: IORingBuffer, + _ buffer: IORing.RegisteredBuffer, into file: FileDescriptor, at offset: UInt64 = 0, context: UInt64 = 0 @@ -239,7 +239,7 @@ public struct IORequest: ~Copyable { public static func write( _ buffer: UnsafeMutableRawBufferPointer, - into file: IORingFileSlot, + into file: IORing.RegisteredFile, at offset: UInt64 = 0, context: UInt64 = 0 ) -> IORequest @@ -258,7 +258,7 @@ public struct IORequest: ~Copyable { ) -> IORequest public static func close( - _ file: IORingFileSlot, + _ file: IORing.RegisteredFile, context: UInt64 = 0 ) -> IORequest @@ -266,7 +266,7 @@ public struct IORequest: ~Copyable { public static func open( _ path: FilePath, in directory: FileDescriptor, - into slot: IORingFileSlot, + into slot: IORing.RegisteredFile, mode: FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, @@ -296,26 +296,18 @@ public struct IORequest: ~Copyable { } public static func cancel( - _ matchAll: CancellationMatch, - matchingContext: UInt64, - context: UInt64 + _ matchAll: CancellationMatch, + matchingContext: UInt64, ) -> IORequest public static func cancel( - _ matchAll: CancellationMatch, - matchingFileDescriptor: FileDescriptor, - context: UInt64 + _ matchAll: CancellationMatch, + matching: FileDescriptor, ) -> IORequest public static func cancel( - _ matchAll: CancellationMatch, - matchingRegisteredFileDescriptorAtIndex: Int, - context: UInt64 - ) -> IORequest - - public static func cancel( - _ matchAll: CancellationMatch, - context: UInt64 + _ matchAll: CancellationMatch, + matching: IORing.RegisteredFile, ) -> IORequest // Other operations follow in the same pattern diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 54e3b10..7d69aa3 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -52,20 +52,6 @@ struct CQRing: ~Copyable { let cqes: UnsafeBufferPointer } -public struct IOResource { - public typealias Resource = T - @usableFromInline let resource: T - @usableFromInline let index: Int - - internal init( - resource: T, - index: Int - ) { - self.resource = resource - self.index = index - } -} - @inline(__always) internal func _writeRequest( _ request: __owned RawIORequest, ring: inout SQRing, @@ -302,9 +288,23 @@ public struct IORing: ~Copyable { var _registeredBuffers: [iovec] var features = Features(rawValue: 0) + + public struct RegisteredResource { + public typealias Resource = T + @usableFromInline let resource: T + @usableFromInline let index: Int - public typealias RegisteredFile = IOResource - public typealias RegisteredBuffer = IOResource + internal init( + resource: T, + index: Int + ) { + self.resource = resource + self.index = index + } + } + + public typealias RegisteredFile = RegisteredResource + public typealias RegisteredBuffer = RegisteredResource @frozen public struct SetupFlags: OptionSet, RawRepresentable, Hashable { @@ -747,4 +747,4 @@ extension IORing.RegisteredBuffer { public var unsafeBuffer: UnsafeMutableRawBufferPointer { return .init(start: resource.iov_base, count: resource.iov_len) } -} \ No newline at end of file +} From a98cd3f2dae5cdd397f71e4cc6d549229a570bf7 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 21 Apr 2025 23:47:00 +0000 Subject: [PATCH 063/102] Build fix and rename IOResource --- Sources/System/IORequest.swift | 8 ++++---- Sources/System/IORing.swift | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 4be37d3..b5d48af 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -348,9 +348,9 @@ extension IORequest { ) -> IORequest { switch matchAll { case .all: - IORequest(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD, targetFD: matchingFileDescriptor)) + IORequest(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD, targetFD: matching)) case .first: - IORequest(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD, targetFD: matchingFileDescriptor)) + IORequest(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD, targetFD: matching)) } } @@ -360,9 +360,9 @@ extension IORequest { ) -> IORequest { switch matchAll { case .all: - IORequest(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD_FIXED, target: matchingFile)) + IORequest(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) case .first: - IORequest(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD_FIXED, target: matchingFile)) + IORequest(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) } } diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 7d69aa3..76f6818 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -624,11 +624,11 @@ public struct IORing: ~Copyable { init(resources: [T]) { self.resources = resources } - public subscript(position: Int) -> IOResource { - IOResource(resource: resources[position], index: position) + public subscript(position: Int) -> RegisteredResource { + RegisteredResource(resource: resources[position], index: position) } - public subscript(position: UInt16) -> IOResource { - IOResource(resource: resources[Int(position)], index: Int(position)) + public subscript(position: UInt16) -> RegisteredResource { + RegisteredResource(resource: resources[Int(position)], index: Int(position)) } } From 344b3b85f8bb0d8014efb27927e639fb2dae5d62 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 21 Apr 2025 16:59:39 -0700 Subject: [PATCH 064/102] Proposal updates --- NNNN-swift-system-io-uring.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NNNN-swift-system-io-uring.md b/NNNN-swift-system-io-uring.md index 2bd981d..978b87b 100644 --- a/NNNN-swift-system-io-uring.md +++ b/NNNN-swift-system-io-uring.md @@ -108,7 +108,7 @@ public struct IORing: ~Copyable { public typealias RegisteredFile = RegisteredResource public typealias RegisteredBuffer = RegisteredResource - // An IORing.RegisteredResources is a view into the buffers or files registered with the ring, if any + // A `RegisteredResources` is a view into the buffers or files registered with the ring, if any public struct RegisteredResources: RandomAccessCollection { public subscript(position: Int) -> IOResource public subscript(position: UInt16) -> IOResource // This is useful because io_uring likes to use UInt16s as indexes @@ -355,7 +355,7 @@ ring.prepare(linkedRequests: in: parentDirectory, into: file, mode: mode, - options: openOptions, + options: openOptions, permissions: nil ), .stat(file, From c47779fac00f63042684364a7011aefc541a187d Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 22 Apr 2025 23:06:48 +0000 Subject: [PATCH 065/102] Try making requests and completions nested types --- Sources/System/IOCompletion.swift | 22 +++--- Sources/System/IORequest.swift | 92 +++++++++++++------------- Sources/System/IORing.swift | 30 ++++----- Tests/SystemTests/IORequestTests.swift | 4 +- Tests/SystemTests/IORingTests.swift | 2 +- 5 files changed, 76 insertions(+), 74 deletions(-) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index b15f0d4..5fa2932 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -1,11 +1,13 @@ @_implementationOnly import CSystem -public struct IOCompletion: ~Copyable { - let rawValue: io_uring_cqe +public extension IORing { + struct Completion: ~Copyable { + let rawValue: io_uring_cqe + } } -extension IOCompletion { - public struct Flags: OptionSet, Hashable, Codable { +public extension IORing.Completion { + struct Flags: OptionSet, Hashable, Codable { public let rawValue: UInt32 public init(rawValue: UInt32) { @@ -19,32 +21,32 @@ extension IOCompletion { } } -extension IOCompletion { - public var context: UInt64 { +public extension IORing.Completion { + var context: UInt64 { get { rawValue.user_data } } - public var userPointer: UnsafeRawPointer? { + var userPointer: UnsafeRawPointer? { get { UnsafeRawPointer(bitPattern: UInt(rawValue.user_data)) } } - public var result: Int32 { + var result: Int32 { get { rawValue.res } } - public var flags: IOCompletion.Flags { + var flags: IORing.Completion.Flags { get { Flags(rawValue: rawValue.flags & 0x0000FFFF) } } - public var bufferIndex: UInt16? { + var bufferIndex: UInt16? { get { if self.flags.contains(.allocatedBuffer) { return UInt16(rawValue.flags >> 16) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index b5d48af..3c4d2a2 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -159,17 +159,21 @@ internal func makeRawRequest_readWrite_unregistered_slot( return request } -public struct IORequest { - @usableFromInline var core: IORequestCore +extension IORing { + public struct Request { + @usableFromInline var core: IORequestCore - @inlinable internal consuming func extractCore() -> IORequestCore { - return core + @inlinable internal consuming func extractCore() -> IORequestCore { + return core + } } } -extension IORequest { - public static func nop(context: UInt64 = 0) -> IORequest { - IORequest(core: .nop) + + +extension IORing.Request { + public static func nop(context: UInt64 = 0) -> IORing.Request { + .init(core: .nop) } public static func read( @@ -177,8 +181,8 @@ extension IORequest { into buffer: IORing.RegisteredBuffer, at offset: UInt64 = 0, context: UInt64 = 0 - ) -> IORequest { - IORequest(core: .readSlot(file: file, buffer: buffer, offset: offset, context: context)) + ) -> IORing.Request { + .init(core: .readSlot(file: file, buffer: buffer, offset: offset, context: context)) } public static func read( @@ -186,8 +190,8 @@ extension IORequest { into buffer: IORing.RegisteredBuffer, at offset: UInt64 = 0, context: UInt64 = 0 - ) -> IORequest { - IORequest(core: .read(file: file, buffer: buffer, offset: offset, context: context)) + ) -> IORing.Request { + .init(core: .read(file: file, buffer: buffer, offset: offset, context: context)) } public static func read( @@ -195,10 +199,8 @@ extension IORequest { into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, context: UInt64 = 0 - ) -> IORequest { - IORequest( - core: .readUnregisteredSlot( - file: file, buffer: buffer, offset: offset, context: context)) + ) -> IORing.Request { + .init(core: .readUnregisteredSlot(file: file, buffer: buffer, offset: offset, context: context)) } public static func read( @@ -206,9 +208,8 @@ extension IORequest { into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, context: UInt64 = 0 - ) -> IORequest { - IORequest( - core: .readUnregistered(file: file, buffer: buffer, offset: offset, context: context)) + ) -> IORing.Request { + .init(core: .readUnregistered(file: file, buffer: buffer, offset: offset, context: context)) } public static func write( @@ -216,8 +217,8 @@ extension IORequest { into file: IORing.RegisteredFile, at offset: UInt64 = 0, context: UInt64 = 0 - ) -> IORequest { - IORequest(core: .writeSlot(file: file, buffer: buffer, offset: offset, context: context)) + ) -> IORing.Request { + .init(core: .writeSlot(file: file, buffer: buffer, offset: offset, context: context)) } public static func write( @@ -225,8 +226,8 @@ extension IORequest { into file: FileDescriptor, at offset: UInt64 = 0, context: UInt64 = 0 - ) -> IORequest { - IORequest(core: .write(file: file, buffer: buffer, offset: offset, context: context)) + ) -> IORing.Request { + .init(core: .write(file: file, buffer: buffer, offset: offset, context: context)) } public static func write( @@ -234,9 +235,8 @@ extension IORequest { into file: IORing.RegisteredFile, at offset: UInt64 = 0, context: UInt64 = 0 - ) -> IORequest { - IORequest( - core: .writeUnregisteredSlot( + ) -> IORing.Request { + .init(core: .writeUnregisteredSlot( file: file, buffer: buffer, offset: offset, context: context)) } @@ -245,8 +245,8 @@ extension IORequest { into file: FileDescriptor, at offset: UInt64 = 0, context: UInt64 = 0 - ) -> IORequest { - IORequest( + ) -> IORing.Request { + .init( core: .writeUnregistered(file: file, buffer: buffer, offset: offset, context: context) ) } @@ -254,15 +254,15 @@ extension IORequest { public static func close( _ file: FileDescriptor, context: UInt64 = 0 - ) -> IORequest { - IORequest(core: .close(file, context: context)) + ) -> IORing.Request { + .init(core: .close(file, context: context)) } public static func close( _ file: IORing.RegisteredFile, context: UInt64 = 0 - ) -> IORequest { - IORequest(core: .closeSlot(file, context: context)) + ) -> IORing.Request { + .init(core: .closeSlot(file, context: context)) } public static func open( @@ -273,8 +273,8 @@ extension IORequest { options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, context: UInt64 = 0 - ) -> IORequest { - IORequest( + ) -> IORing.Request { + .init( core: .openatSlot( atDirectory: directory, path: path, mode, options: options, permissions: permissions, intoSlot: slot, context: context)) @@ -287,8 +287,8 @@ extension IORequest { options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, context: UInt64 = 0 - ) -> IORequest { - IORequest( + ) -> IORing.Request { + .init( core: .openat( atDirectory: directory, path: path, mode, options: options, permissions: permissions, context: context @@ -299,8 +299,8 @@ extension IORequest { _ path: FilePath, in directory: FileDescriptor, context: UInt64 = 0 - ) -> IORequest { - IORequest(core: .unlinkAt(atDirectory: directory, path: path, context: context)) + ) -> IORing.Request { + .init(core: .unlinkAt(atDirectory: directory, path: path, context: context)) } // Cancel @@ -333,36 +333,36 @@ extension IORequest { public static func cancel( _ matchAll: CancellationMatch, matchingContext: UInt64, - ) -> IORequest { + ) -> IORing.Request { switch matchAll { case .all: - IORequest(core: .cancel(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) + .init(core: .cancel(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) case .first: - IORequest(core: .cancel(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) + .init(core: .cancel(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) } } public static func cancel( _ matchAll: CancellationMatch, matching: FileDescriptor, - ) -> IORequest { + ) -> IORing.Request { switch matchAll { case .all: - IORequest(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD, targetFD: matching)) + .init(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD, targetFD: matching)) case .first: - IORequest(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD, targetFD: matching)) + .init(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD, targetFD: matching)) } } public static func cancel( _ matchAll: CancellationMatch, matching: IORing.RegisteredFile, - ) -> IORequest { + ) -> IORing.Request { switch matchAll { case .all: - IORequest(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) + .init(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) case .first: - IORequest(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) + .init(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) } } diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 76f6818..dafedce 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -374,7 +374,7 @@ public struct IORing: ~Copyable { minimumCount: UInt32, maximumCount: UInt32, extraArgs: UnsafeMutablePointer? = nil, - consumer: (consuming IOCompletion?, Errno?, Bool) throws(Err) -> Void + consumer: (consuming IORing.Completion?, Errno?, Bool) throws(Err) -> Void ) throws(Err) { var count = 0 while let completion = _tryConsumeCompletion(ring: completionRing) { @@ -440,10 +440,10 @@ public struct IORing: ~Copyable { internal func _blockingConsumeOneCompletion( extraArgs: UnsafeMutablePointer? = nil - ) throws(Errno) -> IOCompletion { - var result: IOCompletion? = nil + ) throws(Errno) -> Completion { + var result: Completion? = nil try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { - (completion: consuming IOCompletion?, error, done) throws(Errno) in + (completion: consuming Completion?, error, done) throws(Errno) in if let error { throw error } @@ -456,13 +456,13 @@ public struct IORing: ~Copyable { public func blockingConsumeCompletion( timeout: Duration? = nil - ) throws(Errno) -> IOCompletion { + ) throws(Errno) -> Completion { if let timeout { var ts = __kernel_timespec( tv_sec: timeout.components.seconds, tv_nsec: timeout.components.attoseconds / 1_000_000_000 ) - return try withUnsafePointer(to: &ts) { (tsPtr) throws(Errno) -> IOCompletion in + return try withUnsafePointer(to: &ts) { (tsPtr) throws(Errno) -> Completion in var args = io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, @@ -479,7 +479,7 @@ public struct IORing: ~Copyable { public func blockingConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (consuming IOCompletion?, Errno?, Bool) throws(Err) -> Void + consumer: (consuming Completion?, Errno?, Bool) throws(Err) -> Void ) throws(Err) { if let timeout { var ts = __kernel_timespec( @@ -507,11 +507,11 @@ public struct IORing: ~Copyable { // } - public func tryConsumeCompletion() -> IOCompletion? { + public func tryConsumeCompletion() -> Completion? { return _tryConsumeCompletion(ring: completionRing) } - func _tryConsumeCompletion(ring: borrowing CQRing) -> IOCompletion? { + func _tryConsumeCompletion(ring: borrowing CQRing) -> Completion? { let tail = ring.kernelTail.pointee.load(ordering: .acquiring) let head = ring.kernelHead.pointee.load(ordering: .acquiring) @@ -519,7 +519,7 @@ public struct IORing: ~Copyable { // 32 byte copy - oh well let res = ring.cqes[Int(head & ring.ringMask)] ring.kernelHead.pointee.store(head &+ 1, ordering: .releasing) - return IOCompletion(rawValue: res) + return Completion(rawValue: res) } return nil @@ -652,7 +652,7 @@ public struct IORing: ~Copyable { public func submitPreparedRequestsAndConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, - consumer: (consuming IOCompletion?, Errno?, Bool) throws(Err) -> Void + consumer: (consuming Completion?, Errno?, Bool) throws(Err) -> Void ) throws(Err) { //TODO: optimize this to one uring_enter do { @@ -667,13 +667,13 @@ public struct IORing: ~Copyable { ) } - public mutating func prepare(request: __owned IORequest) -> Bool { + public mutating func prepare(request: __owned Request) -> Bool { var raw: RawIORequest? = request.makeRawRequest() return _writeRequest( raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } - mutating func prepare(linkedRequests: some BidirectionalCollection) { + mutating func prepare(linkedRequests: some BidirectionalCollection) { guard linkedRequests.count > 0 else { return } @@ -690,11 +690,11 @@ public struct IORing: ~Copyable { } //@inlinable //TODO: make sure the array allocation gets optimized out... - public mutating func prepare(linkedRequests: IORequest...) { + public mutating func prepare(linkedRequests: Request...) { prepare(linkedRequests: linkedRequests) } - public mutating func submit(linkedRequests: IORequest...) throws(Errno) { + public mutating func submit(linkedRequests: Request...) throws(Errno) { prepare(linkedRequests: linkedRequests) try submitPreparedRequests() } diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 9705026..3d1f72d 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -19,7 +19,7 @@ func requestBytes(_ request: consuming RawIORequest) -> [UInt8] { // which are known to work correctly. final class IORequestTests: XCTestCase { func testNop() { - let req = IORequest.nop().makeRawRequest() + let req = IORing.Request.nop().makeRawRequest() let sourceBytes = requestBytes(req) // convenient property of nop: it's all zeros! // for some unknown reason, liburing sets the fd field to -1. @@ -30,7 +30,7 @@ final class IORequestTests: XCTestCase { func testOpenatFixedFile() throws { let pathPtr = UnsafePointer(bitPattern: 0x414141410badf00d)! let fileSlot = IORing.RegisteredFile(resource: UInt32.max, index: 0) - let req = IORequest.open(FilePath(platformString: pathPtr), + let req = IORing.Request.open(FilePath(platformString: pathPtr), in: FileDescriptor(rawValue: -100), into: fileSlot, mode: .readOnly, diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 57437e4..6c086da 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -13,7 +13,7 @@ final class IORingTests: XCTestCase { func testNop() throws { var ring = try IORing(queueDepth: 32, flags: []) - try ring.submit(linkedRequests: IORequest.nop()) + try ring.submit(linkedRequests: .nop()) let completion = try ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) } From a49ba8a8b3194043d839d691a3229d8cb20a8309 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 22 Apr 2025 23:20:37 +0000 Subject: [PATCH 066/102] Give flags a default value --- Sources/System/IORing.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index dafedce..94c9504 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -330,7 +330,7 @@ public struct IORing: ~Copyable { //TODO: should IORING_SETUP_NO_SQARRAY be the default? do we need to adapt anything to it? } - public init(queueDepth: UInt32, flags: SetupFlags) throws(Errno) { + public init(queueDepth: UInt32, flags: SetupFlags = []) throws(Errno) { let (params, tmpRingDescriptor, tmpRingPtr, tmpRingSize, sqes) = try setUpRing(queueDepth: queueDepth, flags: flags, submissionRing: &submissionRing) // All throws need to be before initializing ivars here to avoid // "error: conditional initialization or destruction of noncopyable types is not supported; From f38d72f310a133490e85f1fa50a64c49bd59b8a8 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 22 Apr 2025 16:30:50 -0700 Subject: [PATCH 067/102] Nested types, some renames, misc other updates --- NNNN-swift-system-io-uring.md | 333 +++++++++++++++++----------------- 1 file changed, 166 insertions(+), 167 deletions(-) diff --git a/NNNN-swift-system-io-uring.md b/NNNN-swift-system-io-uring.md index 978b87b..37f0c5c 100644 --- a/NNNN-swift-system-io-uring.md +++ b/NNNN-swift-system-io-uring.md @@ -28,16 +28,16 @@ We propose a *low level, unopinionated* Swift interface for io_uring on Linux (s `struct IORing: ~Copyable` provides facilities for -* Registering and unregistering resources (files and buffers), an `io_uring` specific variation on Unix file descriptors that improves their efficiency +* Registering and unregistering resources (files and buffers), an `io_uring` specific variation on Unix file IOdescriptors that improves their efficiency * Registering and unregistering eventfds, which allow asynchronous waiting for completions * Enqueueing IO requests * Dequeueing IO completions -`struct RegisteredResource` represents, via its two typealiases `IORing.RegisteredFile` and `IORing.RegisteredBuffer`, registered file descriptors and buffers. +`struct IORing.RegisteredResource` represents, via its two typealiases `IORing.RegisteredFile` and `IORing.RegisteredBuffer`, registered file descriptors and buffers. -`struct IORequest: ~Copyable` represents an IO operation that can be enqueued for the kernel to execute. It supports a wide variety of operations matching traditional unix file and socket operations. +`struct IORing.Request: ~Copyable` represents an IO operation that can be enqueued for the kernel to execute. It supports a wide variety of operations matching traditional unix file and socket operations. -IORequest operations are expressed as overloaded static methods on `IORequest`, e.g. `openat` is spelled +Request operations are expressed as overloaded static methods on `Request`, e.g. `openat` is spelled ```swift public static func open( @@ -48,7 +48,7 @@ IORequest operations are expressed as overloaded static methods on `IORequest`, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, context: UInt64 = 0 - ) -> IORequest + ) -> Request public static func open( _ path: FilePath, @@ -57,12 +57,12 @@ IORequest operations are expressed as overloaded static methods on `IORequest`, options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), permissions: FilePermissions? = nil, context: UInt64 = 0 - ) -> IORequest + ) -> Request ``` which allows clients to decide whether they want to open the file into a slot on the ring, or have it return a file descriptor via a completion. Similarly, read operations have overloads for "use a buffer from the ring" or "read into this `UnsafeMutableBufferPointer`" -Multiple `IORequests` can be enqueued on a single `IORing` using the `prepare(…)` family of methods, and then submitted together using `submitPreparedRequests`, allowing for things like "open this file, read its contents, and then close it" to be a single syscall. Conveniences are provided for preparing and submitting requests in one call. +Multiple `Requests` can be enqueued on a single `IORing` using the `prepare(…)` family of methods, and then submitted together using `submitPreparedRequests`, allowing for things like "open this file, read its contents, and then close it" to be a single syscall. Conveniences are provided for preparing and submitting requests in one call. Since IO operations can execute in parallel or out of order by default, linked chains of operations can be established with `prepare(linkedRequests:…)` and related methods. Separate chains can still execute in parallel, and if an operation early in the chain fails, all subsequent operations will deliver cancellation errors as their completion. @@ -70,14 +70,14 @@ Already-completed results can be retrieved from the ring using `tryConsumeComple Since neither polling nor synchronously waiting is optimal in many cases, `IORing` also exposes the ability to register an eventfd (see `man eventfd(2)`), which will become readable when completions are available on the ring. This can then be monitored asynchronously with `epoll`, `kqueue`, or for clients who are linking libdispatch, `DispatchSource`. -`struct IOCompletion: ~Copyable` represents the result of an IO operation and provides +`struct Completion: ~Copyable` represents the result of an IO operation and provides * Flags indicating various operation-specific metadata about the now-completed syscall * The context associated with the operation when it was enqueued, as an `UnsafeRawPointer` or a `UInt64` * The result of the operation, as an `Int32` with operation-specific meaning * The error, if one occurred -Unfortunately the underlying kernel API makes it relatively difficult to determine which `IORequest` led to a given `IOCompletion`, so it's expected that users will need to create this association themselves via the context parameter. +Unfortunately the underlying kernel API makes it relatively difficult to determine which `Request` led to a given `Completion`, so it's expected that users will need to create this association themselves via the context parameter. `IORing.Features` describes the supported features of the underlying kernel `IORing` implementation, which can be used to provide graceful reduction in functionality when running on older systems. @@ -87,37 +87,35 @@ Unfortunately the underlying kernel API makes it relatively difficult to determi // IORing is intentionally not Sendable, to avoid internal locking overhead public struct IORing: ~Copyable { - public init(queueDepth: UInt32, flags: IORing.SetupFlags) throws(Errno) - - public struct SetupFlags: OptionSet, RawRepresentable, Hashable { - public var rawValue: UInt32 - public init(rawValue: UInt32) - public static var pollCompletions: SetupFlags //IORING_SETUP_IOPOLL - public static var pollSubmissions: SetupFlags //IORING_SETUP_SQPOLL - public static var clampMaxEntries: SetupFlags //IORING_SETUP_CLAMP - public static var startDisabled: SetupFlags //IORING_SETUP_R_DISABLED - public static var continueSubmittingOnError: SetupFlags //IORING_SETUP_SUBMIT_ALL - public static var singleSubmissionThread: SetupFlags //IORING_SETUP_SINGLE_ISSUER - public static var deferRunningTasks: SetupFlags //IORING_SETUP_DEFER_TASKRUN - } - - public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) - public mutating func unregisterEventFD(_ descriptor: FileDescriptor) throws(Errno) + public init(queueDepth: UInt32, flags: IORing.SetupFlags = []) throws(Errno) + + public struct SetupFlags: OptionSet, RawRepresentable, Hashable { + public var rawValue: UInt32 + public init(rawValue: UInt32) + public static var pollCompletions: SetupFlags //IORING_SETUP_IOPOLL + public static var pollSubmissions: SetupFlags //IORING_SETUP_SQPOLL + public static var clampMaxEntries: SetupFlags //IORING_SETUP_CLAMP + public static var startDisabled: SetupFlags //IORING_SETUP_R_DISABLED + public static var continueSubmittingOnError: SetupFlags //IORING_SETUP_SUBMIT_ALL + public static var singleSubmissionThread: SetupFlags //IORING_SETUP_SINGLE_ISSUER + public static var deferRunningTasks: SetupFlags //IORING_SETUP_DEFER_TASKRUN + } + + public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) + public mutating func unregisterEventFD() throws(Errno) public struct RegisteredResource { } public typealias RegisteredFile = RegisteredResource public typealias RegisteredBuffer = RegisteredResource - - // A `RegisteredResources` is a view into the buffers or files registered with the ring, if any - public struct RegisteredResources: RandomAccessCollection { - public subscript(position: Int) -> IOResource - public subscript(position: UInt16) -> IOResource // This is useful because io_uring likes to use UInt16s as indexes - } + + // A `RegisteredResources` is a view into the buffers or files registered with the ring, if any + public struct RegisteredResources: RandomAccessCollection { + public subscript(position: Int) -> RegisteredResource + public subscript(position: UInt16) -> RegisteredResource // This is useful because io_uring likes to use UInt16s as indexes + } public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources - public func unregisterFiles() - public var registeredFileSlots: RegisteredResources public mutating func registerBuffers( @@ -132,33 +130,33 @@ public struct IORing: ~Copyable { public var registeredBuffers: RegisteredResources - public func prepare(requests: IORequest...) - public func prepare(linkedRequests: IORequest...) + public func prepare(requests: Request...) + public func prepare(linkedRequests: Request...) public func submitPreparedRequests(timeout: Duration? = nil) throws(Errno) - public func submit(requests: IORequest..., timeout: Duration? = nil) throws(Errno) - public func submit(linkedRequests: IORequest..., timeout: Duration? = nil) throws(Errno) + public func submit(requests: Request..., timeout: Duration? = nil) throws(Errno) + public func submit(linkedRequests: Request..., timeout: Duration? = nil) throws(Errno) public func submitPreparedRequests() throws(Errno) public func submitPreparedRequestsAndWait(timeout: Duration? = nil) throws(Errno) public func submitPreparedRequestsAndConsumeCompletions( - minimumCount: UInt32 = 1, - timeout: Duration? = nil, - consumer: (consuming IOCompletion?, Errno?, Bool) throws(E) -> Void - ) throws(E) + minimumCount: UInt32 = 1, + timeout: Duration? = nil, + consumer: (consuming Completion?, Errno?, Bool) throws(E) -> Void + ) throws(E) public func blockingConsumeCompletion( - timeout: Duration? = nil - ) throws(Errno) -> IOCompletion + timeout: Duration? = nil + ) throws(Errno) -> Completion public func blockingConsumeCompletions( - minimumCount: UInt32 = 1, - timeout: Duration? = nil, - consumer: (consuming IOCompletion?, Errno?, Bool) throws(E) -> Void + minimumCount: UInt32 = 1, + timeout: Duration? = nil, + consumer: (consuming Completion?, Errno?, Bool) throws(E) -> Void ) throws(E) - public func tryConsumeCompletion() -> IOCompletion? + public func tryConsumeCompletion() -> Completion? public struct Features: OptionSet, RawRepresentable, Hashable { let rawValue: UInt32 @@ -185,155 +183,156 @@ public struct IORing: ~Copyable { public var supportedFeatures: Features } -extension IORing.RegisteredBuffer { - public var unsafeBuffer: UnsafeMutableRawBufferPointer +public extension IORing.RegisteredBuffer { + var unsafeBuffer: UnsafeMutableRawBufferPointer } -public struct IORequest: ~Copyable { - public static func nop(context: UInt64 = 0) -> IORequest - - // overloads for each combination of registered vs unregistered buffer/descriptor - // Read +public extension IORing { + struct Request: ~Copyable { + public static func nop(context: UInt64 = 0) -> Request + + // overloads for each combination of registered vs unregistered buffer/descriptor + // Read public static func read( - _ file: IORing.RegisteredFile, - into buffer: IORing.RegisteredBuffer, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> IORequest - + _ file: IORing.RegisteredFile, + into buffer: IORing.RegisteredBuffer, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> Request + public static func read( - _ file: FileDescriptor, - into buffer: IORing.RegisteredBuffer, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> IORequest - + _ file: FileDescriptor, + into buffer: IORing.RegisteredBuffer, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> Request + public static func read( - _ file: IORing.RegisteredFile, - into buffer: UnsafeMutableRawBufferPointer, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> IORequest - + _ file: IORing.RegisteredFile, + into buffer: UnsafeMutableRawBufferPointer, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> Request + public static func read( - _ file: FileDescriptor, - into buffer: UnsafeMutableRawBufferPointer, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> IORequest - + _ file: FileDescriptor, + into buffer: UnsafeMutableRawBufferPointer, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> Request + // Write public static func write( - _ buffer: IORing.RegisteredBuffer, - into file: IORing.RegisteredFile, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> IORequest - + _ buffer: IORing.RegisteredBuffer, + into file: IORing.RegisteredFile, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> Request + public static func write( - _ buffer: IORing.RegisteredBuffer, - into file: FileDescriptor, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> IORequest - + _ buffer: IORing.RegisteredBuffer, + into file: FileDescriptor, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> Request + public static func write( - _ buffer: UnsafeMutableRawBufferPointer, - into file: IORing.RegisteredFile, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> IORequest - + _ buffer: UnsafeMutableRawBufferPointer, + into file: IORing.RegisteredFile, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> Request + public static func write( - _ buffer: UnsafeMutableRawBufferPointer, - into file: FileDescriptor, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> IORequest - + _ buffer: UnsafeMutableRawBufferPointer, + into file: FileDescriptor, + at offset: UInt64 = 0, + context: UInt64 = 0 + ) -> Request + // Close public static func close( - _ file: FileDescriptor, - context: UInt64 = 0 - ) -> IORequest - + _ file: FileDescriptor, + context: UInt64 = 0 + ) -> Request + public static func close( - _ file: IORing.RegisteredFile, - context: UInt64 = 0 - ) -> IORequest - + _ file: IORing.RegisteredFile, + context: UInt64 = 0 + ) -> Request + // Open At public static func open( - _ path: FilePath, - in directory: FileDescriptor, - into slot: IORing.RegisteredFile, - mode: FileDescriptor.AccessMode, - options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil, - context: UInt64 = 0 - ) -> IORequest - + _ path: FilePath, + in directory: FileDescriptor, + into slot: IORing.RegisteredFile, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil, + context: UInt64 = 0 + ) -> Request + public static func open( - _ path: FilePath, - in directory: FileDescriptor, - mode: FileDescriptor.AccessMode, - options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil, - context: UInt64 = 0 - ) -> IORequest - + _ path: FilePath, + in directory: FileDescriptor, + mode: FileDescriptor.AccessMode, + options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), + permissions: FilePermissions? = nil, + context: UInt64 = 0 + ) -> Request + public static func unlink( - _ path: FilePath, - in directory: FileDescriptor, - context: UInt64 = 0 - ) -> IORequest - + _ path: FilePath, + in directory: FileDescriptor, + context: UInt64 = 0 + ) -> Request + // Cancel - + public enum CancellationMatch { - case all - case first + case all + case first } - + public static func cancel( _ matchAll: CancellationMatch, matchingContext: UInt64, - ) -> IORequest - + ) -> Request + public static func cancel( _ matchAll: CancellationMatch, matching: FileDescriptor, - ) -> IORequest - + ) -> Request + public static func cancel( _ matchAll: CancellationMatch, matching: IORing.RegisteredFile, - ) -> IORequest - + ) -> Request + // Other operations follow in the same pattern -} + } + + struct Completion { + public struct Flags: OptionSet, Hashable, Codable { + public let rawValue: UInt32 -public struct IOCompletion { + public init(rawValue: UInt32) - public struct Flags: OptionSet, Hashable, Codable { - public let rawValue: UInt32 + public static let moreCompletions: Flags + public static let socketNotEmpty: Flags + public static let isNotificationEvent: Flags + } - public init(rawValue: UInt32) - - public static let moreCompletions: Flags - public static let socketNotEmpty: Flags - public static let isNotificationEvent: Flags - } - - //These are both the same value, but having both eliminates some ugly casts in client code - public var context: UInt64 - public var contextPointer: UnsafeRawPointer - - public var result: Int32 - - public var error: Errno? // Convenience wrapper over `result` - - public var flags: Flags + //These are both the same value, but having both eliminates some ugly casts in client code + public var context: UInt64 + public var contextPointer: UnsafeRawPointer + + public var result: Int32 + + public var error: Errno? // Convenience wrapper over `result` + + public var flags: Flags + } } ``` @@ -363,7 +362,7 @@ ring.prepare(linkedRequests: ) ) //batch submit 2 syscalls in 1! -try ring.submitPreparedRequestsAndConsumeCompletions(minimumCount: 2) { (completion: consuming IOCompletion?, error, done) in +try ring.submitPreparedRequestsAndConsumeCompletions(minimumCount: 2) { (completion: consuming Completion?, error, done) in if let error { throw error //or other error handling as desired } @@ -381,7 +380,7 @@ ring.prepare(linkedRequests: ) //batch submit 2 syscalls in 1! -try ring.submitPreparedRequestsAndConsumeCompletions(minimumCount: 2) { (completion: consuming IOCompletion?, error, done) in +try ring.submitPreparedRequestsAndConsumeCompletions(minimumCount: 2) { (completion: consuming Completion?, error, done) in if let error { throw error //or other error handling as desired } @@ -439,8 +438,8 @@ This feature is intrinsically linked to Linux kernel support, so constrains the ``` func submitLinkedRequestsAndWait( _ requests: repeat each Request -) where Request == IORequest - -> InlineArray<(repeat each Request).count, IOCompletion> +) where Request == IORing.Request + -> InlineArray<(repeat each Request).count, IORing.Completion> ``` * Once mutable borrows are supported, we should consider replacing the closure-taking bulk completion APIs (e.g. `blockingConsumeCompletions(…)`) with ones that return a sequence of completions instead * We should consider making more types noncopyable as compiler support improves @@ -457,7 +456,7 @@ func submitLinkedRequestsAndWait( * Using POSIX AIO instead of or as well as io_uring would greatly increase our ability to support older kernels and other Unix systems, but it has well-documented performance and usability issues that have prevented its adoption elsewhere, and apply just as much to Swift. * Earlier versions of this proposal had higher level "managed" abstractions over IORing. These have been removed due to lack of interest from clients, but could be added back later if needed. * I considered having dedicated error types for IORing, but eventually decided throwing Errno was more consistent with other platform APIs -* IOResource was originally a class in an attempt to manage the lifetime of the resource via language features. Changing to the current model of it being a copyable struct didn't make the lifetime management any less safe (the IORing still owns the actual resource), and reduces overhead. In the future it would be neat if we could express IOResources as being borrowed from the IORing so they can't be used after its lifetime. +* RegisteredResource was originally a class in an attempt to manage the lifetime of the resource via language features. Changing to the current model of it being a copyable struct didn't make the lifetime management any less safe (the IORing still owns the actual resource), and reduces overhead. In the future it would be neat if we could express RegisteredResources as being borrowed from the IORing so they can't be used after its lifetime. ## Acknowledgments From 3a649e32a67625a06e183bbe68094056b28c690b Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 24 Apr 2025 16:39:41 -0700 Subject: [PATCH 068/102] Fix type of features, and make it clear that Completion is a nested type --- NNNN-swift-system-io-uring.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/NNNN-swift-system-io-uring.md b/NNNN-swift-system-io-uring.md index 37f0c5c..d103578 100644 --- a/NNNN-swift-system-io-uring.md +++ b/NNNN-swift-system-io-uring.md @@ -70,7 +70,7 @@ Already-completed results can be retrieved from the ring using `tryConsumeComple Since neither polling nor synchronously waiting is optimal in many cases, `IORing` also exposes the ability to register an eventfd (see `man eventfd(2)`), which will become readable when completions are available on the ring. This can then be monitored asynchronously with `epoll`, `kqueue`, or for clients who are linking libdispatch, `DispatchSource`. -`struct Completion: ~Copyable` represents the result of an IO operation and provides +`struct IORing.Completion: ~Copyable` represents the result of an IO operation and provides * Flags indicating various operation-specific metadata about the now-completed syscall * The context associated with the operation when it was enqueued, as an `UnsafeRawPointer` or a `UInt64` @@ -87,7 +87,7 @@ Unfortunately the underlying kernel API makes it relatively difficult to determi // IORing is intentionally not Sendable, to avoid internal locking overhead public struct IORing: ~Copyable { - public init(queueDepth: UInt32, flags: IORing.SetupFlags = []) throws(Errno) + public init(queueDepth: UInt32, flags: IORing.SetupFlags = []) throws(Errno) public struct SetupFlags: OptionSet, RawRepresentable, Hashable { public var rawValue: UInt32 @@ -164,21 +164,21 @@ public struct IORing: ~Copyable { public init(rawValue: UInt32) //IORING_FEAT_SINGLE_MMAP is handled internally - public static let nonDroppingCompletions: Bool //IORING_FEAT_NODROP - public static let stableSubmissions: Bool //IORING_FEAT_SUBMIT_STABLE - public static let currentFilePosition: Bool //IORING_FEAT_RW_CUR_POS - public static let assumingTaskCredentials: Bool //IORING_FEAT_CUR_PERSONALITY - public static let fastPolling: Bool //IORING_FEAT_FAST_POLL - public static let epoll32BitFlags: Bool //IORING_FEAT_POLL_32BITS - public static let pollNonFixedFiles: Bool //IORING_FEAT_SQPOLL_NONFIXED - public static let extendedArguments: Bool //IORING_FEAT_EXT_ARG - public static let nativeWorkers: Bool //IORING_FEAT_NATIVE_WORKERS - public static let resourceTags: Bool //IORING_FEAT_RSRC_TAGS - public static let allowsSkippingSuccessfulCompletions: Bool //IORING_FEAT_CQE_SKIP - public static let improvedLinkedFiles: Bool //IORING_FEAT_LINKED_FILE - public static let registerRegisteredRings: Bool //IORING_FEAT_REG_REG_RING - public static let minimumTimeout: Bool //IORING_FEAT_MIN_TIMEOUT - public static let bundledSendReceive: Bool //IORING_FEAT_RECVSEND_BUNDLE + public static let nonDroppingCompletions: Features //IORING_FEAT_NODROP + public static let stableSubmissions: Features //IORING_FEAT_SUBMIT_STABLE + public static let currentFilePosition: Features //IORING_FEAT_RW_CUR_POS + public static let assumingTaskCredentials: Features //IORING_FEAT_CUR_PERSONALITY + public static let fastPolling: Features //IORING_FEAT_FAST_POLL + public static let epoll32BitFlags: Features //IORING_FEAT_POLL_32BITS + public static let pollNonFixedFiles: Features //IORING_FEAT_SQPOLL_NONFIXED + public static let extendedArguments: Features //IORING_FEAT_EXT_ARG + public static let nativeWorkers: Features //IORING_FEAT_NATIVE_WORKERS + public static let resourceTags: Features //IORING_FEAT_RSRC_TAGS + public static let allowsSkippingSuccessfulCompletions: Features //IORING_FEAT_CQE_SKIP + public static let improvedLinkedFiles: Features //IORING_FEAT_LINKED_FILE + public static let registerRegisteredRings: Features //IORING_FEAT_REG_REG_RING + public static let minimumTimeout: Features //IORING_FEAT_MIN_TIMEOUT + public static let bundledSendReceive: Features //IORING_FEAT_RECVSEND_BUNDLE } public var supportedFeatures: Features } From 7e2f797fb497f820cbbf7a60ec4376fe20a215f5 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 28 Apr 2025 22:30:00 +0000 Subject: [PATCH 069/102] Fix some errors on newer linux systems --- Sources/System/IORing.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 94c9504..b4e633e 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -466,7 +466,7 @@ public struct IORing: ~Copyable { var args = io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, - pad: 0, + min_wait_usec: 0, ts: UInt64(UInt(bitPattern: tsPtr)) ) return try _blockingConsumeOneCompletion(extraArgs: &args) @@ -490,7 +490,7 @@ public struct IORing: ~Copyable { var args = io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, - pad: 0, + min_wait_usec: 0, ts: UInt64(UInt(bitPattern: tsPtr)) ) try _blockingConsumeCompletionGuts( @@ -530,7 +530,7 @@ public struct IORing: ~Copyable { let result = withUnsafePointer(to: &rawfd) { fdptr in let result = io_uring_register( ringDescriptor, - IORING_REGISTER_EVENTFD, + IORING_REGISTER_EVENTFD.rawValue, UnsafeMutableRawPointer(mutating: fdptr), 1 ) @@ -544,7 +544,7 @@ public struct IORing: ~Copyable { public mutating func unregisterEventFD() throws(Errno) { let result = io_uring_register( ringDescriptor, - IORING_UNREGISTER_EVENTFD, + IORING_UNREGISTER_EVENTFD.rawValue, nil, 0 ) @@ -561,7 +561,7 @@ public struct IORing: ~Copyable { let regResult = files.withUnsafeBufferPointer { bPtr in let result = io_uring_register( self.ringDescriptor, - IORING_REGISTER_FILES, + IORING_REGISTER_FILES.rawValue, UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), UInt32(truncatingIfNeeded: count) ) @@ -594,7 +594,7 @@ public struct IORing: ~Copyable { let regResult = iovecs.withUnsafeBufferPointer { bPtr in let result = io_uring_register( self.ringDescriptor, - IORING_REGISTER_BUFFERS, + IORING_REGISTER_BUFFERS.rawValue, UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), UInt32(truncatingIfNeeded: buffers.count) ) From 3d6cba22b69e3adac60528e69f759b2ff76dc166 Mon Sep 17 00:00:00 2001 From: David Smith Date: Mon, 28 Apr 2025 23:03:26 +0000 Subject: [PATCH 070/102] Work around compiler bugs harder --- Sources/System/IORing.swift | 72 +++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 39 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index b4e633e..5f54af9 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -164,7 +164,7 @@ internal func _getSubmissionEntry( } private func setUpRing( - queueDepth: UInt32, flags: IORing.SetupFlags, submissionRing: inout SQRing + queueDepth: UInt32, flags: IORing.SetupFlags ) throws(Errno) -> (params: io_uring_params, ringDescriptor: Int32, ringPtr: UnsafeMutableRawPointer, ringSize: Int, sqes: UnsafeMutableRawPointer) { var params = io_uring_params() @@ -217,36 +217,6 @@ private func setUpRing( throw errno } - let submissionRing = SQRing( - kernelHead: UnsafePointer>( - ringPtr.advanced(by: params.sq_off.head) - .assumingMemoryBound(to: Atomic.self) - ), - kernelTail: UnsafePointer>( - ringPtr.advanced(by: params.sq_off.tail) - .assumingMemoryBound(to: Atomic.self) - ), - userTail: 0, // no requests yet - ringMask: ringPtr.advanced(by: params.sq_off.ring_mask) - .assumingMemoryBound(to: UInt32.self).pointee, - flags: UnsafePointer>( - ringPtr.advanced(by: params.sq_off.flags) - .assumingMemoryBound(to: Atomic.self) - ), - array: UnsafeMutableBufferPointer( - start: ringPtr.advanced(by: params.sq_off.array) - .assumingMemoryBound(to: UInt32.self), - count: Int( - ringPtr.advanced(by: params.sq_off.ring_entries) - .assumingMemoryBound(to: UInt32.self).pointee) - ) - ) - - // fill submission ring array with 1:1 map to underlying SQEs - for i in 0..>( + ringPtr.advanced(by: params.sq_off.head) + .assumingMemoryBound(to: Atomic.self) + ), + kernelTail: UnsafePointer>( + ringPtr.advanced(by: params.sq_off.tail) + .assumingMemoryBound(to: Atomic.self) + ), + userTail: 0, // no requests yet + ringMask: ringPtr.advanced(by: params.sq_off.ring_mask) + .assumingMemoryBound(to: UInt32.self).pointee, + flags: UnsafePointer>( + ringPtr.advanced(by: params.sq_off.flags) + .assumingMemoryBound(to: Atomic.self) + ), + array: UnsafeMutableBufferPointer( + start: ringPtr.advanced(by: params.sq_off.array) + .assumingMemoryBound(to: UInt32.self), + count: Int( + ringPtr.advanced(by: params.sq_off.ring_entries) + .assumingMemoryBound(to: UInt32.self).pointee) + ) + ) + + // fill submission ring array with 1:1 map to underlying SQEs + for i in 0 ..< submissionRing.array.count { + submissionRing.array[i] = UInt32(i) + } submissionQueueEntries = UnsafeMutableBufferPointer( start: sqes.assumingMemoryBound(to: io_uring_sqe.self), @@ -641,12 +640,7 @@ public struct IORing: ~Copyable { } public func submitPreparedRequests() throws(Errno) { - switch submissionRing { - case .some(let submissionRing): - try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) - case .none: - fatalError() - } + try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } public func submitPreparedRequestsAndConsumeCompletions( From f9c2a2b8e78c458c207b7e353ec0e43606d15162 Mon Sep 17 00:00:00 2001 From: David Smith Date: Wed, 18 Jun 2025 23:08:45 +0000 Subject: [PATCH 071/102] Work around io_uring.h in ways that will work on both versions --- Sources/CSystem/include/io_uring.h | 33 ++++++++++++++++++++++++++++++ Sources/System/IORing.swift | 12 +++++------ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index 75a07e5..df1b36a 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -34,6 +34,39 @@ # endif #endif +/* +struct io_uring_getevents_arg { + __u64 sigmask; + __u32 sigmask_sz; + __u32 min_wait_usec; //used to be called `pad`. This compatibility wrapper avoids dealing with that. + __u64 ts; +}; +*/ +struct swift_io_uring_getevents_arg { + __u64 sigmask; + __u32 sigmask_sz; + __u32 min_wait_usec; + __u64 ts; +}; + +//This was #defines in older headers, so we redeclare it to get a consistent import +typedef enum : __u32 { + SWIFT_IORING_REGISTER_BUFFERS = 0, + SWIFT_IORING_UNREGISTER_BUFFERS = 1, + SWIFT_IORING_REGISTER_FILES = 2, + SWIFT_IORING_UNREGISTER_FILES = 3, + SWIFT_IORING_REGISTER_EVENTFD = 4, + SWIFT_IORING_UNREGISTER_EVENTFD = 5, + SWIFT_IORING_REGISTER_FILES_UPDATE = 6, + SWIFT_IORING_REGISTER_EVENTFD_ASYNC = 7, + SWIFT_IORING_REGISTER_PROBE = 8, + SWIFT_IORING_REGISTER_PERSONALITY = 9, + SWIFT_IORING_UNREGISTER_PERSONALITY = 10, + + /* this goes last */ + SWIFT_IORING_REGISTER_LAST +} SWIFT_IORING_REGISTER_OPS; + static inline int io_uring_register(int fd, unsigned int opcode, void *arg, unsigned int nr_args) { diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 5f54af9..ce72aa7 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -372,7 +372,7 @@ public struct IORing: ~Copyable { private func _blockingConsumeCompletionGuts( minimumCount: UInt32, maximumCount: UInt32, - extraArgs: UnsafeMutablePointer? = nil, + extraArgs: UnsafeMutablePointer? = nil, consumer: (consuming IORing.Completion?, Errno?, Bool) throws(Err) -> Void ) throws(Err) { var count = 0 @@ -393,7 +393,7 @@ public struct IORing: ~Copyable { while count < minimumCount { var sz = 0 if extraArgs != nil { - sz = MemoryLayout.size + sz = MemoryLayout.size } let res = io_uring_enter2( ringDescriptor, @@ -438,7 +438,7 @@ public struct IORing: ~Copyable { } internal func _blockingConsumeOneCompletion( - extraArgs: UnsafeMutablePointer? = nil + extraArgs: UnsafeMutablePointer? = nil ) throws(Errno) -> Completion { var result: Completion? = nil try _blockingConsumeCompletionGuts(minimumCount: 1, maximumCount: 1, extraArgs: extraArgs) { @@ -462,7 +462,7 @@ public struct IORing: ~Copyable { tv_nsec: timeout.components.attoseconds / 1_000_000_000 ) return try withUnsafePointer(to: &ts) { (tsPtr) throws(Errno) -> Completion in - var args = io_uring_getevents_arg( + var args = swift_io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, min_wait_usec: 0, @@ -486,7 +486,7 @@ public struct IORing: ~Copyable { tv_nsec: timeout.components.attoseconds / 1_000_000_000 ) try withUnsafePointer(to: &ts) { (tsPtr) throws(Err) in - var args = io_uring_getevents_arg( + var args = swift_io_uring_getevents_arg( sigmask: 0, sigmask_sz: 0, min_wait_usec: 0, @@ -529,7 +529,7 @@ public struct IORing: ~Copyable { let result = withUnsafePointer(to: &rawfd) { fdptr in let result = io_uring_register( ringDescriptor, - IORING_REGISTER_EVENTFD.rawValue, + SWIFT_IORING_REGISTER_EVENTFD.rawValue, UnsafeMutableRawPointer(mutating: fdptr), 1 ) From f91cb6b8de316075a086504e688b81af6aa157dc Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 27 Jun 2025 00:39:35 +0000 Subject: [PATCH 072/102] Improve tests. Not quite working but close --- Tests/SystemTests/IORequestTests.swift | 57 +++++++++++--------------- 1 file changed, 25 insertions(+), 32 deletions(-) diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 3d1f72d..04100e0 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -1,9 +1,9 @@ import XCTest #if SYSTEM_PACKAGE -@testable import SystemPackage + @testable import SystemPackage #else -import System + import System #endif func requestBytes(_ request: consuming RawIORequest) -> [UInt8] { @@ -27,37 +27,30 @@ final class IORequestTests: XCTestCase { XCTAssertEqual(sourceBytes, .init(repeating: 0, count: 64)) } - func testOpenatFixedFile() throws { - let pathPtr = UnsafePointer(bitPattern: 0x414141410badf00d)! - let fileSlot = IORing.RegisteredFile(resource: UInt32.max, index: 0) - let req = IORing.Request.open(FilePath(platformString: pathPtr), - in: FileDescriptor(rawValue: -100), - into: fileSlot, - mode: .readOnly, - options: [], - permissions: nil + func testOpenAndReadFixedFile() throws { + mkdir("/tmp/IORingTests/", 0o777) + let path: FilePath = "/tmp/IORingTests/test.txt" + let fd = try FileDescriptor.open( + path, .readWrite, options: .create, permissions: .ownerReadWrite) + try fd.writeAll("Hello, World!".utf8) + try fd.close() + var ring = try IORing(queueDepth: 3) + let parent = try FileDescriptor.open("/tmp/IORingTests/", .readOnly) + let fileSlot = try ring.registerFileSlots(count: 1)[0] + let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 16) + let buffer = try ring.registerBuffers([rawBuffer])[0] + try ring.submit(linkedRequests: + .open(path, in: parent, into: fileSlot, mode: .readOnly), + .read(fileSlot, into: buffer), + .close(fileSlot) ) + _ = try ring.blockingConsumeCompletion() //open + _ = try ring.blockingConsumeCompletion() //read + _ = try ring.blockingConsumeCompletion() //close - let expectedRequest: [UInt8] = { - var bin = [UInt8].init(repeating: 0, count: 64) - bin[0] = 0x12 // opcode for the request - // bin[1] = 0 - no request flags - // bin[2...3] = 0 - padding - bin[4...7] = [0x9c, 0xff, 0xff, 0xff] // -100 in UInt32 - dirfd - // bin[8...15] = 0 - zeroes - withUnsafeBytes(of: pathPtr) { - // path pointer - bin[16...23] = ArraySlice($0) - } - // bin[24...43] = 0 - zeroes - withUnsafeBytes(of: UInt32(fileSlot.index + 1)) { - // file index + 1 - yes, unfortunately - bin[44...47] = ArraySlice($0) - } - return bin - }() - - let actualRequest = requestBytes(req.makeRawRequest()) - XCTAssertEqual(expectedRequest, actualRequest) + let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!) + XCTAssertEqual(result, "Hello, World!") + + rmdir("/tmp/IORingTests/") } } From 131326c8aedf6e32d9084075cc67cbed0271c538 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 1 Jul 2025 01:02:40 +0000 Subject: [PATCH 073/102] Fix tests --- Tests/SystemTests/IORequestTests.swift | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 04100e0..d22b527 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -7,7 +7,7 @@ import XCTest #endif func requestBytes(_ request: consuming RawIORequest) -> [UInt8] { - return withUnsafePointer(to: request) { + return withUnsafePointer(to: request.rawValue) { let requestBuf = UnsafeBufferPointer(start: $0, count: 1) let rawBytes = UnsafeRawBufferPointer(requestBuf) return .init(rawBytes) @@ -31,26 +31,32 @@ final class IORequestTests: XCTestCase { mkdir("/tmp/IORingTests/", 0o777) let path: FilePath = "/tmp/IORingTests/test.txt" let fd = try FileDescriptor.open( - path, .readWrite, options: .create, permissions: .ownerReadWrite) + path, + .readWrite, + options: .create, + permissions: .ownerReadWrite + ) try fd.writeAll("Hello, World!".utf8) try fd.close() - var ring = try IORing(queueDepth: 3) + var ring = try IORing(queueDepth: 6) let parent = try FileDescriptor.open("/tmp/IORingTests/", .readOnly) let fileSlot = try ring.registerFileSlots(count: 1)[0] - let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 16) + let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) let buffer = try ring.registerBuffers([rawBuffer])[0] + try ring.submit(linkedRequests: .open(path, in: parent, into: fileSlot, mode: .readOnly), .read(fileSlot, into: buffer), - .close(fileSlot) - ) + .close(fileSlot)) _ = try ring.blockingConsumeCompletion() //open _ = try ring.blockingConsumeCompletion() //read _ = try ring.blockingConsumeCompletion() //close + let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!) XCTAssertEqual(result, "Hello, World!") + try parent.close() rmdir("/tmp/IORingTests/") } } From 321a71c2e999932b983516918254bffcfde912ea Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 3 Jul 2025 00:13:29 +0000 Subject: [PATCH 074/102] Expand test coverage --- Tests/SystemTests/IORequestTests.swift | 33 ----------- Tests/SystemTests/IORingTests.swift | 80 ++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 33 deletions(-) diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index d22b527..0e5c972 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -26,37 +26,4 @@ final class IORequestTests: XCTestCase { // we're not trying to be bug-compatible with it, so 0 *should* work. XCTAssertEqual(sourceBytes, .init(repeating: 0, count: 64)) } - - func testOpenAndReadFixedFile() throws { - mkdir("/tmp/IORingTests/", 0o777) - let path: FilePath = "/tmp/IORingTests/test.txt" - let fd = try FileDescriptor.open( - path, - .readWrite, - options: .create, - permissions: .ownerReadWrite - ) - try fd.writeAll("Hello, World!".utf8) - try fd.close() - var ring = try IORing(queueDepth: 6) - let parent = try FileDescriptor.open("/tmp/IORingTests/", .readOnly) - let fileSlot = try ring.registerFileSlots(count: 1)[0] - let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) - let buffer = try ring.registerBuffers([rawBuffer])[0] - - try ring.submit(linkedRequests: - .open(path, in: parent, into: fileSlot, mode: .readOnly), - .read(fileSlot, into: buffer), - .close(fileSlot)) - _ = try ring.blockingConsumeCompletion() //open - _ = try ring.blockingConsumeCompletion() //read - _ = try ring.blockingConsumeCompletion() //close - - - let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!) - XCTAssertEqual(result, "Hello, World!") - - try parent.close() - rmdir("/tmp/IORingTests/") - } } diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 6c086da..8b32b92 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -1,4 +1,5 @@ import XCTest +import CSystem //for eventfd #if SYSTEM_PACKAGE import SystemPackage @@ -17,4 +18,83 @@ final class IORingTests: XCTestCase { let completion = try ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) } + + func makeHelloWorldFile() throws -> (dir: FileDescriptor, file: FilePath) { + mkdir("/tmp/IORingTests/", 0o777) + let path: FilePath = "/tmp/IORingTests/test.txt" + let fd = try FileDescriptor.open( + path, + .readWrite, + options: .create, + permissions: .ownerReadWrite + ) + try fd.writeAll("Hello, World!".utf8) + try fd.close() + let parent = try FileDescriptor.open("/tmp/IORingTests/", .readOnly) + + return (parent, path) + } + + func cleanUpHelloWorldFile(_ parent: FileDescriptor) throws { + try parent.close() + rmdir("/tmp/IORingTests/") + } + + func setupTestRing(depth: Int, fileSlots: Int, buffers: [UnsafeMutableRawBufferPointer]) throws -> IORing { + var ring: IORing = try IORing(queueDepth: 6) + _ = try ring.registerFileSlots(count: 1) + _ = try ring.registerBuffers(buffers) + return ring + } + + // Exercises opening, reading, closing, registered files, registered buffers, and eventfd + func testOpenReadAndWriteFixedFile() throws { + let (parent, path) = try makeHelloWorldFile() + let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) + var ring = try setupTestRing(depth: 3, fileSlots: 1, buffers: [rawBuffer]) + let eventFD = FileDescriptor(rawValue: eventfd(0, Int32(EFD_SEMAPHORE))) + try ring.registerEventFD(eventFD) + + //Part 1: read the file we just created, and make sure the eventfd fires + try ring.submit(linkedRequests: + .open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly), + .read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]), + .close(ring.registeredFileSlots[0])) + let efdBuf = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 0) + _ = try eventFD.read(into: efdBuf) + _ = try ring.blockingConsumeCompletion() //open + _ = try eventFD.read(into: efdBuf) + _ = try ring.blockingConsumeCompletion() //read + _ = try eventFD.read(into: efdBuf) + _ = try ring.blockingConsumeCompletion() //close + let result = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!) + XCTAssertEqual(result, "Hello, World!") + + //Part 2: delete that file, then use the ring to write out a new one + let rmResult = path.withPlatformString { + remove($0) + } + XCTAssertEqual(rmResult, 0) + try ring.submit(linkedRequests: + .open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readWrite, options: .create, permissions: .ownerReadWrite), + .write(ring.registeredBuffers[0], into: ring.registeredFileSlots[0]), + .close(ring.registeredFileSlots[0])) + _ = try eventFD.read(into: efdBuf) + _ = try ring.blockingConsumeCompletion() //open + _ = try eventFD.read(into: efdBuf) + _ = try ring.blockingConsumeCompletion() //write + _ = try eventFD.read(into: efdBuf) + _ = try ring.blockingConsumeCompletion() //close + memset(rawBuffer.baseAddress!, 0, rawBuffer.count) + //Verify using a non-ring IO method that what we wrote matches our expectations + print("about to open") + let nonRingFD = try FileDescriptor.open(path, .readOnly) + let bytesRead = try nonRingFD.read(into: rawBuffer) + XCTAssert(bytesRead == 13) + let result2 = String(cString: rawBuffer.assumingMemoryBound(to: CChar.self).baseAddress!) + XCTAssertEqual(result2, "Hello, World!") + try cleanUpHelloWorldFile(parent) + efdBuf.deallocate() + rawBuffer.deallocate() + } } From 27ccce55db6615e69056424c747b4b330391b0e0 Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 3 Jul 2025 16:04:52 -0700 Subject: [PATCH 075/102] Conditionalize IORing stuff for Linux --- Sources/System/IOCompletion.swift | 2 ++ Sources/System/IORequest.swift | 2 ++ Sources/System/IORing.swift | 2 ++ Sources/System/RawIORequest.swift | 4 +++- 4 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index 5fa2932..ed0feab 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -1,3 +1,4 @@ +#if os(Linux) @_implementationOnly import CSystem public extension IORing { @@ -56,3 +57,4 @@ public extension IORing.Completion { } } } +#endif diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 3c4d2a2..35741bd 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -1,3 +1,4 @@ +#if os(Linux) @_implementationOnly import struct CSystem.io_uring_sqe @usableFromInline @@ -471,3 +472,4 @@ extension IORing.Request { return request } } +#endif diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index ce72aa7..581e795 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -1,3 +1,4 @@ +#if os(Linux) @_implementationOnly import CSystem import Glibc // needed for mmap import Synchronization @@ -742,3 +743,4 @@ extension IORing.RegisteredBuffer { return .init(start: resource.iov_base, count: resource.iov_len) } } +#endif diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 6190b0d..33bea29 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -1,3 +1,4 @@ +#if os(Linux) // TODO: investigate @usableFromInline / @_implementationOnly dichotomy @_implementationOnly import CSystem @_implementationOnly import struct CSystem.io_uring_sqe @@ -196,4 +197,5 @@ extension RawIORequest { return try work() } } -} \ No newline at end of file +} +#endif From 0d4c6fc97147e14c0291d51bab68253b59260e7c Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 3 Jul 2025 16:12:56 -0700 Subject: [PATCH 076/102] Fix Musl --- Sources/System/IORing.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 581e795..0af574d 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -1,6 +1,11 @@ #if os(Linux) @_implementationOnly import CSystem -import Glibc // needed for mmap +// needed for mmap +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#endif import Synchronization @_implementationOnly import struct CSystem.io_uring_sqe From de2d6e2d391368ac3db87b99f1ea9dc2d6e45a3e Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 3 Jul 2025 16:17:51 -0700 Subject: [PATCH 077/102] Conditionalize tests too --- Tests/SystemTests/IORequestTests.swift | 2 ++ Tests/SystemTests/IORingTests.swift | 2 ++ 2 files changed, 4 insertions(+) diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 0e5c972..4d32196 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -1,3 +1,4 @@ +#if os(Linux) import XCTest #if SYSTEM_PACKAGE @@ -27,3 +28,4 @@ final class IORequestTests: XCTestCase { XCTAssertEqual(sourceBytes, .init(repeating: 0, count: 64)) } } +#endif diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 8b32b92..29973c6 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -1,3 +1,4 @@ +#if os(Linux) import XCTest import CSystem //for eventfd @@ -98,3 +99,4 @@ final class IORingTests: XCTestCase { rawBuffer.deallocate() } } +#endif From a6149c215ef7f0b0937fe2ca9091f043ce44f65a Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 4 Jul 2025 00:09:19 +0000 Subject: [PATCH 078/102] Cleanup, implement buffer unregistering, inline almost everything because we're not ABI stable on Linux --- Sources/System/IOCompletion.swift | 19 +++--- Sources/System/IORequest.swift | 81 ++++++++++++------------- Sources/System/IORing.swift | 99 +++++++++++++++++++------------ Sources/System/RawIORequest.swift | 69 ++++++++++----------- 4 files changed, 144 insertions(+), 124 deletions(-) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index ed0feab..4263bd8 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -1,9 +1,12 @@ #if os(Linux) -@_implementationOnly import CSystem +import CSystem public extension IORing { struct Completion: ~Copyable { - let rawValue: io_uring_cqe + @inlinable init(rawValue inRawValue: io_uring_cqe) { + rawValue = inRawValue + } + @usableFromInline let rawValue: io_uring_cqe } } @@ -11,7 +14,7 @@ public extension IORing.Completion { struct Flags: OptionSet, Hashable, Codable { public let rawValue: UInt32 - public init(rawValue: UInt32) { + @inlinable public init(rawValue: UInt32) { self.rawValue = rawValue } @@ -23,31 +26,31 @@ public extension IORing.Completion { } public extension IORing.Completion { - var context: UInt64 { + @inlinable var context: UInt64 { get { rawValue.user_data } } - var userPointer: UnsafeRawPointer? { + @inlinable var userPointer: UnsafeRawPointer? { get { UnsafeRawPointer(bitPattern: UInt(rawValue.user_data)) } } - var result: Int32 { + @inlinable var result: Int32 { get { rawValue.res } } - var flags: IORing.Completion.Flags { + @inlinable var flags: IORing.Completion.Flags { get { Flags(rawValue: rawValue.flags & 0x0000FFFF) } } - var bufferIndex: UInt16? { + @inlinable var bufferIndex: UInt16? { get { if self.flags.contains(.allocatedBuffer) { return UInt16(rawValue.flags >> 16) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 35741bd..8af313a 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -1,5 +1,5 @@ #if os(Linux) -@_implementationOnly import struct CSystem.io_uring_sqe +import CSystem @usableFromInline internal enum IORequestCore { @@ -96,7 +96,7 @@ internal enum IORequestCore { ) } -@inline(__always) +@inline(__always) @inlinable internal func makeRawRequest_readWrite_registered( file: FileDescriptor, buffer: IORing.RegisteredBuffer, @@ -112,7 +112,7 @@ internal func makeRawRequest_readWrite_registered( return request } -@inline(__always) +@inline(__always) @inlinable internal func makeRawRequest_readWrite_registered_slot( file: IORing.RegisteredFile, buffer: IORing.RegisteredBuffer, @@ -129,7 +129,7 @@ internal func makeRawRequest_readWrite_registered_slot( return request } -@inline(__always) +@inline(__always) @inlinable internal func makeRawRequest_readWrite_unregistered( file: FileDescriptor, buffer: UnsafeMutableRawBufferPointer, @@ -144,7 +144,7 @@ internal func makeRawRequest_readWrite_unregistered( return request } -@inline(__always) +@inline(__always) @inlinable internal func makeRawRequest_readWrite_unregistered_slot( file: IORing.RegisteredFile, buffer: UnsafeMutableRawBufferPointer, @@ -164,6 +164,10 @@ extension IORing { public struct Request { @usableFromInline var core: IORequestCore + @inlinable internal init(core inCore: IORequestCore) { + core = inCore + } + @inlinable internal consuming func extractCore() -> IORequestCore { return core } @@ -173,11 +177,11 @@ extension IORing { extension IORing.Request { - public static func nop(context: UInt64 = 0) -> IORing.Request { + @inlinable public static func nop(context: UInt64 = 0) -> IORing.Request { .init(core: .nop) } - public static func read( + @inlinable public static func read( _ file: IORing.RegisteredFile, into buffer: IORing.RegisteredBuffer, at offset: UInt64 = 0, @@ -186,7 +190,7 @@ extension IORing.Request { .init(core: .readSlot(file: file, buffer: buffer, offset: offset, context: context)) } - public static func read( + @inlinable public static func read( _ file: FileDescriptor, into buffer: IORing.RegisteredBuffer, at offset: UInt64 = 0, @@ -195,7 +199,7 @@ extension IORing.Request { .init(core: .read(file: file, buffer: buffer, offset: offset, context: context)) } - public static func read( + @inlinable public static func read( _ file: IORing.RegisteredFile, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, @@ -204,7 +208,7 @@ extension IORing.Request { .init(core: .readUnregisteredSlot(file: file, buffer: buffer, offset: offset, context: context)) } - public static func read( + @inlinable public static func read( _ file: FileDescriptor, into buffer: UnsafeMutableRawBufferPointer, at offset: UInt64 = 0, @@ -213,7 +217,7 @@ extension IORing.Request { .init(core: .readUnregistered(file: file, buffer: buffer, offset: offset, context: context)) } - public static func write( + @inlinable public static func write( _ buffer: IORing.RegisteredBuffer, into file: IORing.RegisteredFile, at offset: UInt64 = 0, @@ -222,7 +226,7 @@ extension IORing.Request { .init(core: .writeSlot(file: file, buffer: buffer, offset: offset, context: context)) } - public static func write( + @inlinable public static func write( _ buffer: IORing.RegisteredBuffer, into file: FileDescriptor, at offset: UInt64 = 0, @@ -231,7 +235,7 @@ extension IORing.Request { .init(core: .write(file: file, buffer: buffer, offset: offset, context: context)) } - public static func write( + @inlinable public static func write( _ buffer: UnsafeMutableRawBufferPointer, into file: IORing.RegisteredFile, at offset: UInt64 = 0, @@ -241,7 +245,7 @@ extension IORing.Request { file: file, buffer: buffer, offset: offset, context: context)) } - public static func write( + @inlinable public static func write( _ buffer: UnsafeMutableRawBufferPointer, into file: FileDescriptor, at offset: UInt64 = 0, @@ -252,21 +256,21 @@ extension IORing.Request { ) } - public static func close( + @inlinable public static func close( _ file: FileDescriptor, context: UInt64 = 0 ) -> IORing.Request { .init(core: .close(file, context: context)) } - public static func close( + @inlinable public static func close( _ file: IORing.RegisteredFile, context: UInt64 = 0 ) -> IORing.Request { .init(core: .closeSlot(file, context: context)) } - public static func open( + @inlinable public static func open( _ path: FilePath, in directory: FileDescriptor, into slot: IORing.RegisteredFile, @@ -281,7 +285,7 @@ extension IORing.Request { permissions: permissions, intoSlot: slot, context: context)) } - public static func open( + @inlinable public static func open( _ path: FilePath, in directory: FileDescriptor, mode: FileDescriptor.AccessMode, @@ -296,7 +300,7 @@ extension IORing.Request { )) } - public static func unlink( + @inlinable public static func unlink( _ path: FilePath, in directory: FileDescriptor, context: UInt64 = 0 @@ -307,31 +311,22 @@ 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 cancelation 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 - */ - //TODO: why aren't these showing up from the header import? - private static var IORING_ASYNC_CANCEL_ALL: UInt32 { (1 as UInt32) << 0 } - private static var IORING_ASYNC_CANCEL_FD: UInt32 { (1 as UInt32) << 1 } - private static var IORING_ASYNC_CANCEL_ANY: UInt32 { (1 as UInt32) << 2 } - private static var IORING_ASYNC_CANCEL_FD_FIXED: UInt32 { (1 as UInt32) << 3 } - private static var IORING_ASYNC_CANCEL_USERDATA: UInt32 { (1 as UInt32) << 4 } - private static var IORING_ASYNC_CANCEL_OP: UInt32 { (1 as UInt32) << 5 } - - + * ASYNC_CANCEL flags. + * + * IORING_ASYNC_CANCEL_ALL Cancel all requests that match the given key + * IORING_ASYNC_CANCEL_FD Key off 'fd' for cancelation 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 + */ public enum CancellationMatch { case all case first } - public static func cancel( + @inlinable public static func cancel( _ matchAll: CancellationMatch, matchingContext: UInt64, ) -> IORing.Request { @@ -343,7 +338,7 @@ extension IORing.Request { } } - public static func cancel( + @inlinable public static func cancel( _ matchAll: CancellationMatch, matching: FileDescriptor, ) -> IORing.Request { @@ -355,7 +350,7 @@ extension IORing.Request { } } - public static func cancel( + @inlinable public static func cancel( _ matchAll: CancellationMatch, matching: IORing.RegisteredFile, ) -> IORing.Request { @@ -369,8 +364,8 @@ extension IORing.Request { //TODO: add support for CANCEL_OP - @inline(__always) - public consuming func makeRawRequest() -> RawIORequest { + @inline(__always) @inlinable + internal consuming func makeRawRequest() -> RawIORequest { var request = RawIORequest() switch extractCore() { case .nop: diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 581e795..6e31a42 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -1,11 +1,8 @@ #if os(Linux) -@_implementationOnly import CSystem +import CSystem import Glibc // needed for mmap import Synchronization -@_implementationOnly import struct CSystem.io_uring_sqe - -// XXX: this *really* shouldn't be here. oh well. extension UnsafeMutableRawPointer { func advanced(by offset: UInt32) -> UnsafeMutableRawPointer { return advanced(by: Int(offset)) @@ -20,40 +17,40 @@ extension UnsafeMutableRawBufferPointer { // all pointers in this struct reference kernel-visible memory @usableFromInline struct SQRing: ~Copyable { - let kernelHead: UnsafePointer> - let kernelTail: UnsafePointer> - var userTail: UInt32 + @usableFromInline let kernelHead: UnsafePointer> + @usableFromInline let kernelTail: UnsafePointer> + @usableFromInline var userTail: UInt32 // from liburing: the kernel should never change these // might change in the future with resizable rings? - let ringMask: UInt32 + @usableFromInline let ringMask: UInt32 // let ringEntries: UInt32 - absorbed into array.count // ring flags bitfield // currently used by the kernel only in SQPOLL mode to indicate // when the polling thread needs to be woken up - let flags: UnsafePointer> + @usableFromInline let flags: UnsafePointer> // ring array // maps indexes between the actual ring and the submissionQueueEntries list, // allowing the latter to be used as a kind of freelist with enough work? // currently, just 1:1 mapping (0.. + @usableFromInline let array: UnsafeMutableBufferPointer } -struct CQRing: ~Copyable { - let kernelHead: UnsafePointer> - let kernelTail: UnsafePointer> +@usableFromInline struct CQRing: ~Copyable { + @usableFromInline let kernelHead: UnsafePointer> + @usableFromInline let kernelTail: UnsafePointer> // TODO: determine if this is actually used var userHead: UInt32 - let ringMask: UInt32 + @usableFromInline let ringMask: UInt32 - let cqes: UnsafeBufferPointer + @usableFromInline let cqes: UnsafeBufferPointer } -@inline(__always) +@inline(__always) @inlinable internal func _writeRequest( _ request: __owned RawIORequest, ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer @@ -66,7 +63,7 @@ internal func _writeRequest( return true } -@inline(__always) +@inline(__always) @inlinable internal func _blockingGetSubmissionEntry( ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer ) -> UnsafeMutablePointer< @@ -86,6 +83,7 @@ internal func _blockingGetSubmissionEntry( //TODO: omitting signal mask for now //Tell the kernel that we've submitted requests and/or are waiting for completions +@inlinable internal func _enter( ringDescriptor: Int32, numEvents: UInt32, @@ -113,22 +111,26 @@ internal func _enter( } } +@inlinable internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws(Errno) { let flushedEvents = _flushQueue(ring: ring) _ = try _enter( ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0) } +@inlinable internal func _getUnconsumedSubmissionCount(ring: borrowing SQRing) -> UInt32 { return ring.userTail - ring.kernelHead.pointee.load(ordering: .acquiring) } +@inlinable internal func _getUnconsumedCompletionCount(ring: borrowing CQRing) -> UInt32 { return ring.kernelTail.pointee.load(ordering: .acquiring) - ring.kernelHead.pointee.load(ordering: .acquiring) } //TODO: pretty sure this is supposed to do more than it does +@inlinable internal func _flushQueue(ring: borrowing SQRing) -> UInt32 { ring.kernelTail.pointee.store( ring.userTail, ordering: .releasing @@ -136,7 +138,7 @@ internal func _flushQueue(ring: borrowing SQRing) -> UInt32 { return _getUnconsumedSubmissionCount(ring: ring) } -@inline(__always) +@inlinable internal func _getSubmissionEntry( ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer ) -> UnsafeMutablePointer< @@ -188,7 +190,6 @@ private func setUpRing( || params.features & IORING_FEAT_NODROP == 0 { close(ringDescriptor) - // TODO: error handling throw Errno.invalidArgument } @@ -241,22 +242,22 @@ private func setUpRing( public struct IORing: ~Copyable { let ringFlags: UInt32 - let ringDescriptor: Int32 + @usableFromInline let ringDescriptor: Int32 @usableFromInline var submissionRing: SQRing // FEAT: set this eventually let submissionPolling: Bool = false - let completionRing: CQRing + @usableFromInline let completionRing: CQRing - let submissionQueueEntries: UnsafeMutableBufferPointer + @usableFromInline let submissionQueueEntries: UnsafeMutableBufferPointer // kept around for unmap / cleanup let ringSize: Int let ringPtr: UnsafeMutableRawPointer - var _registeredFiles: [UInt32] - var _registeredBuffers: [iovec] + @usableFromInline var _registeredFiles: [UInt32] + @usableFromInline var _registeredBuffers: [iovec] var features = Features(rawValue: 0) @@ -265,7 +266,7 @@ public struct IORing: ~Copyable { @usableFromInline let resource: T @usableFromInline let index: Int - internal init( + @inlinable internal init( resource: T, index: Int ) { @@ -277,7 +278,6 @@ public struct IORing: ~Copyable { public typealias RegisteredFile = RegisteredResource public typealias RegisteredBuffer = RegisteredResource - @frozen public struct SetupFlags: OptionSet, RawRepresentable, Hashable { public var rawValue: UInt32 @@ -370,7 +370,8 @@ public struct IORing: ~Copyable { self.ringFlags = params.flags } - private func _blockingConsumeCompletionGuts( + @inlinable + internal func _blockingConsumeCompletionGuts( minimumCount: UInt32, maximumCount: UInt32, extraArgs: UnsafeMutablePointer? = nil, @@ -438,6 +439,7 @@ public struct IORing: ~Copyable { } } + @inlinable internal func _blockingConsumeOneCompletion( extraArgs: UnsafeMutablePointer? = nil ) throws(Errno) -> Completion { @@ -454,6 +456,7 @@ public struct IORing: ~Copyable { return result.take()! } + @inlinable public func blockingConsumeCompletion( timeout: Duration? = nil ) throws(Errno) -> Completion { @@ -476,6 +479,7 @@ public struct IORing: ~Copyable { } } + @inlinable public func blockingConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, @@ -507,10 +511,12 @@ public struct IORing: ~Copyable { // } + @inlinable public func tryConsumeCompletion() -> Completion? { return _tryConsumeCompletion(ring: completionRing) } + @inlinable func _tryConsumeCompletion(ring: borrowing CQRing) -> Completion? { let tail = ring.kernelTail.pointee.load(ordering: .acquiring) let head = ring.kernelHead.pointee.load(ordering: .acquiring) @@ -580,6 +586,7 @@ public struct IORing: ~Copyable { fatalError("failed to unregister files") } + @inlinable public var registeredFileSlots: RegisteredResources { RegisteredResources(resources: _registeredFiles) } @@ -610,6 +617,7 @@ public struct IORing: ~Copyable { return registeredBuffers } + @inlinable public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) throws(Errno) -> RegisteredResources { @@ -617,33 +625,44 @@ public struct IORing: ~Copyable { } public struct RegisteredResources: RandomAccessCollection { - let resources: [T] + @usableFromInline let resources: [T] - public var startIndex: Int { 0 } - public var endIndex: Int { resources.endIndex } - init(resources: [T]) { + @inlinable public var startIndex: Int { 0 } + @inlinable public var endIndex: Int { resources.endIndex } + @inlinable init(resources: [T]) { self.resources = resources } - public subscript(position: Int) -> RegisteredResource { + @inlinable public subscript(position: Int) -> RegisteredResource { RegisteredResource(resource: resources[position], index: position) } - public subscript(position: UInt16) -> RegisteredResource { + @inlinable public subscript(position: UInt16) -> RegisteredResource { RegisteredResource(resource: resources[Int(position)], index: Int(position)) } } + @inlinable public var registeredBuffers: RegisteredResources { RegisteredResources(resources: _registeredBuffers) } - public func unregisterBuffers() { - fatalError("failed to unregister buffers: TODO") + public func unregisterBuffers() throws { + let result = io_uring_register( + self.ringDescriptor, + IORING_UNREGISTER_BUFFERS.rawValue, + nil, + 0 + ) + guard result >= 0 else { + throw Errno(rawValue: -result) + } } + @inlinable public func submitPreparedRequests() throws(Errno) { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } + @inlinable public func submitPreparedRequestsAndConsumeCompletions( minimumCount: UInt32 = 1, timeout: Duration? = nil, @@ -662,12 +681,14 @@ public struct IORing: ~Copyable { ) } + @inlinable public mutating func prepare(request: __owned Request) -> Bool { var raw: RawIORequest? = request.makeRawRequest() return _writeRequest( raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } + @inlinable mutating func prepare(linkedRequests: some BidirectionalCollection) { guard linkedRequests.count > 0 else { return @@ -684,17 +705,17 @@ public struct IORing: ~Copyable { submissionQueueEntries: submissionQueueEntries) } - //@inlinable //TODO: make sure the array allocation gets optimized out... + @inlinable public mutating func prepare(linkedRequests: Request...) { prepare(linkedRequests: linkedRequests) } + @inlinable public mutating func submit(linkedRequests: Request...) throws(Errno) { prepare(linkedRequests: linkedRequests) try submitPreparedRequests() } - @frozen public struct Features: OptionSet, RawRepresentable, Hashable { public let rawValue: UInt32 @@ -734,12 +755,12 @@ public struct IORing: ~Copyable { } extension IORing.RegisteredFile { - public var unsafeFileSlot: Int { + @inlinable public var unsafeFileSlot: Int { return index } } extension IORing.RegisteredBuffer { - public var unsafeBuffer: UnsafeMutableRawBufferPointer { + @inlinable public var unsafeBuffer: UnsafeMutableRawBufferPointer { return .init(start: resource.iov_base, count: resource.iov_len) } } diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 33bea29..e4d0f47 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -1,19 +1,19 @@ #if os(Linux) -// TODO: investigate @usableFromInline / @_implementationOnly dichotomy -@_implementationOnly import CSystem -@_implementationOnly import struct CSystem.io_uring_sqe +import CSystem +import struct CSystem.io_uring_sqe -//TODO: make this internal -public struct RawIORequest: ~Copyable { - var rawValue: io_uring_sqe - var path: FilePath? //buffer owner for the path pointer that the sqe may have +@usableFromInline +internal struct RawIORequest: ~Copyable { + @usableFromInline var rawValue: io_uring_sqe + @usableFromInline var path: FilePath? //buffer owner for the path pointer that the sqe may have - public init() { + @inlinable public init() { self.rawValue = io_uring_sqe() } } extension RawIORequest { + @usableFromInline enum Operation: UInt8 { case nop = 0 case readv = 1 @@ -45,49 +45,49 @@ extension RawIORequest { public struct Flags: OptionSet, Hashable, Codable { public let rawValue: UInt8 - public init(rawValue: UInt8) { + @inlinable public init(rawValue: UInt8) { self.rawValue = rawValue } - public static let fixedFile = Flags(rawValue: 1 << 0) - public static let drainQueue = Flags(rawValue: 1 << 1) - public static let linkRequest = Flags(rawValue: 1 << 2) - public static let hardlinkRequest = Flags(rawValue: 1 << 3) - public static let asynchronous = Flags(rawValue: 1 << 4) - public static let selectBuffer = Flags(rawValue: 1 << 5) - public static let skipSuccess = Flags(rawValue: 1 << 6) + @inlinable public static var fixedFile: RawIORequest.Flags { Flags(rawValue: 1 << 0) } + @inlinable public static var drainQueue: RawIORequest.Flags { Flags(rawValue: 1 << 1) } + @inlinable public static var linkRequest: RawIORequest.Flags { Flags(rawValue: 1 << 2) } + @inlinable public static var hardlinkRequest: RawIORequest.Flags { Flags(rawValue: 1 << 3) } + @inlinable public static var asynchronous: RawIORequest.Flags { Flags(rawValue: 1 << 4) } + @inlinable public static var selectBuffer: RawIORequest.Flags { Flags(rawValue: 1 << 5) } + @inlinable public static var skipSuccess: RawIORequest.Flags { Flags(rawValue: 1 << 6) } } - var operation: Operation { + @inlinable var operation: Operation { get { Operation(rawValue: rawValue.opcode)! } set { rawValue.opcode = newValue.rawValue } } - var cancel_flags: UInt32 { + @inlinable var cancel_flags: UInt32 { get { rawValue.cancel_flags } set { rawValue.cancel_flags = newValue } } - var addr: UInt64 { + @inlinable var addr: UInt64 { get { rawValue.addr } set { rawValue.addr = newValue } } - public var flags: Flags { + @inlinable public var flags: Flags { get { Flags(rawValue: rawValue.flags) } set { rawValue.flags = newValue.rawValue } } - public mutating func linkToNextRequest() { + @inlinable public mutating func linkToNextRequest() { flags = Flags(rawValue: flags.rawValue | Flags.linkRequest.rawValue) } - public var fileDescriptor: FileDescriptor { + @inlinable public var fileDescriptor: FileDescriptor { get { FileDescriptor(rawValue: rawValue.fd) } set { rawValue.fd = newValue.rawValue } } - public var offset: UInt64? { + @inlinable public var offset: UInt64? { get { if (rawValue.off == UInt64.max) { return nil @@ -104,7 +104,7 @@ extension RawIORequest { } } - public var buffer: UnsafeMutableRawBufferPointer { + @inlinable public var buffer: UnsafeMutableRawBufferPointer { get { let ptr = UnsafeMutableRawPointer(bitPattern: UInt(exactly: rawValue.addr)!) return UnsafeMutableRawBufferPointer(start: ptr, count: Int(rawValue.len)) @@ -135,45 +135,46 @@ extension RawIORequest { public struct ReadWriteFlags: OptionSet, Hashable, Codable { public var rawValue: UInt32 - public init(rawValue: UInt32) { + @inlinable public init(rawValue: UInt32) { self.rawValue = rawValue } - public static let highPriority = ReadWriteFlags(rawValue: 1 << 0) + @inlinable public static var highPriority: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 0) } // sync with only data integrity - public static let dataSync = ReadWriteFlags(rawValue: 1 << 1) + @inlinable public static var dataSync: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 1) } // sync with full data + file integrity - public static let fileSync = ReadWriteFlags(rawValue: 1 << 2) + @inlinable public static var fileSync: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 2) } // return -EAGAIN if operation blocks - public static let noWait = ReadWriteFlags(rawValue: 1 << 3) + @inlinable public static var noWait: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 3) } // append to end of the file - public static let append = ReadWriteFlags(rawValue: 1 << 4) + @inlinable public static var append: RawIORequest.ReadWriteFlags { ReadWriteFlags(rawValue: 1 << 4) } } public struct TimeOutFlags: OptionSet, Hashable, Codable { public var rawValue: UInt32 - public init(rawValue: UInt32) { + @inlinable public init(rawValue: UInt32) { self.rawValue = rawValue } - public static let relativeTime: RawIORequest.TimeOutFlags = TimeOutFlags(rawValue: 0) - public static let absoluteTime: RawIORequest.TimeOutFlags = TimeOutFlags(rawValue: 1 << 0) + @inlinable public static var relativeTime: RawIORequest.TimeOutFlags { TimeOutFlags(rawValue: 0) } + @inlinable public static var absoluteTime: RawIORequest.TimeOutFlags { TimeOutFlags(rawValue: 1 << 0) } } } extension RawIORequest { + @inlinable static func nop() -> RawIORequest { var req: RawIORequest = RawIORequest() req.operation = .nop return req } - //TODO: typed errors + @inlinable static func withTimeoutRequest( linkedTo opEntry: UnsafeMutablePointer, in timeoutEntry: UnsafeMutablePointer, From bbe2f1c192eedf9ee1019264fb27173446ac2624 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 8 Jul 2025 00:41:50 +0000 Subject: [PATCH 079/102] Add doc comments, Span/MutableSpan support, unregistering registered fds, variants of submission operations that don't block, address various TODOs --- Package.swift | 1 + Sources/System/IORequest.swift | 2 - Sources/System/IORing.swift | 140 ++++++++++++++++++++++++------ Sources/System/RawIORequest.swift | 2 - 4 files changed, 116 insertions(+), 29 deletions(-) diff --git a/Package.swift b/Package.swift index 14b040e..48b348a 100644 --- a/Package.swift +++ b/Package.swift @@ -22,6 +22,7 @@ let swiftSettings: [SwiftSetting] = [ .when(platforms: [.macOS, .macCatalyst, .iOS, .watchOS, .tvOS, .visionOS])), .define("SYSTEM_PACKAGE"), .define("ENABLE_MOCKING", .when(configuration: .debug)), + .enableExperimentalFeature("Lifetimes"), ] let package = Package( diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 8af313a..1d0638b 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -362,8 +362,6 @@ extension IORing.Request { } } - //TODO: add support for CANCEL_OP - @inline(__always) @inlinable internal consuming func makeRawRequest() -> RawIORequest { var request = RawIORequest() diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 15d9cd7..681ca7e 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -47,25 +47,35 @@ extension UnsafeMutableRawBufferPointer { @usableFromInline let kernelHead: UnsafePointer> @usableFromInline let kernelTail: UnsafePointer> - // TODO: determine if this is actually used - var userHead: UInt32 - @usableFromInline let ringMask: UInt32 @usableFromInline let cqes: UnsafeBufferPointer } +@inline(__always) @inlinable +internal func _tryWriteRequest( + _ request: __owned RawIORequest, ring: inout SQRing, + submissionQueueEntries: UnsafeMutableBufferPointer +) + -> Bool +{ + if let entry = _getSubmissionEntry( + ring: &ring, submissionQueueEntries: submissionQueueEntries) { + entry.pointee = request.rawValue + return true + } + return false +} + @inline(__always) @inlinable internal func _writeRequest( _ request: __owned RawIORequest, ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer ) - -> Bool { let entry = _blockingGetSubmissionEntry( ring: &ring, submissionQueueEntries: submissionQueueEntries) entry.pointee = request.rawValue - return true } @inline(__always) @inlinable @@ -151,8 +161,7 @@ internal func _getSubmissionEntry( >? { let next = ring.userTail &+ 1 //this is expected to wrap - // FEAT: smp load when SQPOLL in use (not in MVP) - let kernelHead = ring.kernelHead.pointee.load(ordering: .acquiring) + let kernelHead: UInt32 = ring.kernelHead.pointee.load(ordering: .acquiring) // FEAT: 128-bit event support (not in MVP) if next - kernelHead <= ring.array.count { @@ -245,6 +254,11 @@ private func setUpRing( return (params: params, ringDescriptor: ringDescriptor, ringPtr: ringPtr!, ringSize: ringSize, sqes: sqes!) } +///IORing provides facilities for +/// * Registering and unregistering resources (files and buffers), an `io_uring` specific variation on Unix file IOdescriptors that improves their efficiency +/// * Registering and unregistering eventfds, which allow asynchronous waiting for completions +/// * Enqueueing IO requests +/// * Dequeueing IO completions public struct IORing: ~Copyable { let ringFlags: UInt32 @usableFromInline let ringDescriptor: Int32 @@ -266,10 +280,11 @@ public struct IORing: ~Copyable { var features = Features(rawValue: 0) + /// RegisteredResource is used via its typealiases, RegisteredFile and RegisteredBuffer. Registering file descriptors and buffers with the IORing allows for more efficient access to them. public struct RegisteredResource { public typealias Resource = T @usableFromInline let resource: T - @usableFromInline let index: Int + public let index: Int @inlinable internal init( resource: T, @@ -283,6 +298,7 @@ public struct IORing: ~Copyable { public typealias RegisteredFile = RegisteredResource public typealias RegisteredBuffer = RegisteredResource + /// SetupFlags represents configuration options to an IORing as it's being created public struct SetupFlags: OptionSet, RawRepresentable, Hashable { public var rawValue: UInt32 @@ -298,14 +314,15 @@ public struct IORing: ~Copyable { //TODO: do we want to expose IORING_SETUP_COOP_TASKRUN and IORING_SETUP_TASKRUN_FLAG? //public static var runTasksCooperatively: SetupFlags { .init(rawValue: UInt32(1) << 8) } //IORING_SETUP_COOP_TASKRUN //TODO: can we even do different size sqe/cqe? It requires a kernel feature, but how do we convince swift to let the types be different sizes? - internal static var use128ByteSQEs: SetupFlags { .init(rawValue: UInt32(1) << 10) } //IORING_SETUP_SQE128 - internal static var use32ByteCQEs: SetupFlags { .init(rawValue: UInt32(1) << 11) } //IORING_SETUP_CQE32 + //internal static var use128ByteSQEs: SetupFlags { .init(rawValue: UInt32(1) << 10) } //IORING_SETUP_SQE128 + //internal static var use32ByteCQEs: SetupFlags { .init(rawValue: UInt32(1) << 11) } //IORING_SETUP_CQE32 @inlinable public static var singleSubmissionThread: SetupFlags { .init(rawValue: UInt32(1) << 12) } //IORING_SETUP_SINGLE_ISSUER @inlinable public static var deferRunningTasks: SetupFlags { .init(rawValue: UInt32(1) << 13) } //IORING_SETUP_DEFER_TASKRUN //pretty sure we don't want to expose IORING_SETUP_NO_MMAP or IORING_SETUP_REGISTERED_FD_ONLY currently //TODO: should IORING_SETUP_NO_SQARRAY be the default? do we need to adapt anything to it? } + /// Initializes an IORing with enough space for `queueDepth` prepared requests and completed operations public init(queueDepth: UInt32, flags: SetupFlags = []) throws(Errno) { let (params, tmpRingDescriptor, tmpRingPtr, tmpRingSize, sqes) = try setUpRing(queueDepth: queueDepth, flags: flags) // All throws need to be before initializing ivars here to avoid @@ -361,7 +378,6 @@ public struct IORing: ~Copyable { ringPtr.advanced(by: params.cq_off.tail) .assumingMemoryBound(to: Atomic.self) ), - userHead: 0, // no completions yet ringMask: ringPtr.advanced(by: params.cq_off.ring_mask) .assumingMemoryBound(to: UInt32.self).pointee, cqes: UnsafeBufferPointer( @@ -461,6 +477,7 @@ public struct IORing: ~Copyable { return result.take()! } + /// Synchronously waits for an operation to complete for up to `timeout` (or forever if not specified) @inlinable public func blockingConsumeCompletion( timeout: Duration? = nil @@ -484,6 +501,7 @@ 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 @inlinable public func blockingConsumeCompletions( minimumCount: UInt32 = 1, @@ -516,6 +534,7 @@ public struct IORing: ~Copyable { // } + /// Takes a completed operation from the ring and returns it, if one is ready. Otherwise, returns nil. @inlinable public func tryConsumeCompletion() -> Completion? { return _tryConsumeCompletion(ring: completionRing) @@ -536,6 +555,7 @@ public struct IORing: ~Copyable { return nil } + /// Registers an event monitoring file descriptor with the ring. The file descriptor becomes readable whenever completions are ready to be dequeued. See `man eventfd(2)` for additional information. public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) { var rawfd = descriptor.rawValue let result = withUnsafePointer(to: &rawfd) { fdptr in @@ -552,6 +572,7 @@ public struct IORing: ~Copyable { } } + /// Removes a registered event file descriptor from the ring public mutating func unregisterEventFD() throws(Errno) { let result = io_uring_register( ringDescriptor, @@ -564,6 +585,7 @@ public struct IORing: ~Copyable { } } + /// Registers `count` files with the ring for later use in IO operations public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources { precondition(_registeredFiles.isEmpty) precondition(count < UInt32.max) @@ -587,21 +609,31 @@ public struct IORing: ~Copyable { return registeredFileSlots } - public func unregisterFiles() { - fatalError("failed to unregister files") + /// Removes registered files from the ring + public func unregisterFiles() throws { + let result = io_uring_register( + ringDescriptor, + IORING_UNREGISTER_FILES.rawValue, + nil, + 0 + ) + if result < 0 { + throw Errno(rawValue: -result) + } } + /// Allows access to registered files by index @inlinable public var registeredFileSlots: RegisteredResources { RegisteredResources(resources: _registeredFiles) } + /// Registers buffers with the ring for later use in IO operations public mutating func registerBuffers(_ buffers: some Collection) throws(Errno) -> RegisteredResources { precondition(buffers.count < UInt32.max) precondition(_registeredBuffers.isEmpty) - //TODO: check if io_uring has preconditions it needs for the buffers (e.g. alignment) let iovecs = buffers.map { $0.to_iovec() } let regResult = iovecs.withUnsafeBufferPointer { bPtr in let result = io_uring_register( @@ -617,11 +649,11 @@ public struct IORing: ~Copyable { throw regResult } - // TODO: error handling _registeredBuffers = iovecs return registeredBuffers } + /// Registers buffers with the ring for later use in IO operations @inlinable public mutating func registerBuffers(_ buffers: UnsafeMutableRawBufferPointer...) throws(Errno) -> RegisteredResources @@ -629,6 +661,7 @@ public struct IORing: ~Copyable { try registerBuffers(buffers) } + /// A view of the registered files or buffers in a ring public struct RegisteredResources: RandomAccessCollection { @usableFromInline let resources: [T] @@ -645,6 +678,7 @@ public struct IORing: ~Copyable { } } + /// Allows access to registered files by index @inlinable public var registeredBuffers: RegisteredResources { RegisteredResources(resources: _registeredBuffers) @@ -662,11 +696,13 @@ public struct IORing: ~Copyable { } } + /// Sends all prepared requests to the kernel for processing. Results will be delivered as completions, which can be dequeued from the ring. @inlinable public func submitPreparedRequests() throws(Errno) { try _submitRequests(ring: submissionRing, ringDescriptor: ringDescriptor) } + /// 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. @inlinable public func submitPreparedRequestsAndConsumeCompletions( minimumCount: UInt32 = 1, @@ -686,13 +722,48 @@ public struct IORing: ~Copyable { ) } + /// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request @inlinable - public mutating func prepare(request: __owned Request) -> Bool { + public mutating func tryPrepare(request: __owned Request) -> Bool { var raw: RawIORequest? = request.makeRawRequest() - return _writeRequest( + return _tryWriteRequest( raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } + /// Attempts to prepare an IO request for submission to the kernel. Blocks if needed until space becomes available to enqueue the request + @inlinable + public mutating func prepare(request: __owned Request) { + var raw: RawIORequest? = request.makeRawRequest() + _writeRequest( + raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) + } + + /// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order. + @inlinable + mutating func tryPrepare(linkedRequests: some BidirectionalCollection) -> Bool { + guard linkedRequests.count > 0 else { + return true + } + let freeSQECount = _getUnconsumedSubmissionCount(ring: submissionRing) + guard freeSQECount >= linkedRequests.count else { + return false + } + let last = linkedRequests.last! + for req in linkedRequests.dropLast() { + var raw = req.makeRawRequest() + raw.linkToNextRequest() + let successfullyAdded = _tryWriteRequest( + raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) + assert(successfullyAdded) + } + let successfullyAdded = _tryWriteRequest( + last.makeRawRequest(), ring: &submissionRing, + submissionQueueEntries: submissionQueueEntries) + assert(successfullyAdded) + return true + } + + /// Prepares a chain of linked IO requests for submission to the kernel. Blocks if needed until space becomes available to enqueue the requests. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order. @inlinable mutating func prepare(linkedRequests: some BidirectionalCollection) { guard linkedRequests.count > 0 else { @@ -702,25 +773,34 @@ public struct IORing: ~Copyable { for req in linkedRequests.dropLast() { var raw = req.makeRawRequest() raw.linkToNextRequest() - _ = _writeRequest( + _writeRequest( raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } - _ = _writeRequest( + _writeRequest( last.makeRawRequest(), ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } + /// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space. + @inlinable + public mutating func tryPrepare(linkedRequests: Request...) -> Bool { + tryPrepare(linkedRequests: linkedRequests) + } + + /// Prepares a sequence of requests for submission to the ring. Blocks if the submission queue doesn't have enough available space. @inlinable public mutating func prepare(linkedRequests: Request...) { prepare(linkedRequests: linkedRequests) } + /// Prepares and submits a sequence of requests to the ring. Blocks if the submission queue doesn't have enough available space. @inlinable public mutating func submit(linkedRequests: Request...) throws(Errno) { prepare(linkedRequests: linkedRequests) try submitPreparedRequests() } + /// 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 @@ -745,6 +825,8 @@ public struct IORing: ~Copyable { @inlinable public static var minimumTimeout: Features { .init(rawValue: UInt32(1) << 15) } //IORING_FEAT_MIN_TIMEOUT @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 public var supportedFeatures: Features { return features } @@ -759,14 +841,22 @@ public struct IORing: ~Copyable { } } -extension IORing.RegisteredFile { - @inlinable public var unsafeFileSlot: Int { - return index - } -} extension IORing.RegisteredBuffer { - @inlinable public var unsafeBuffer: UnsafeMutableRawBufferPointer { + @unsafe @inlinable public var unsafeBuffer: UnsafeMutableRawBufferPointer { return .init(start: resource.iov_base, count: resource.iov_len) } + + @inlinable public var mutableBytes: MutableRawSpan { + @_lifetime(&self) + mutating get { + let span = MutableRawSpan(_unsafeBytes: unsafeBuffer) + return unsafe _overrideLifetime(span, mutating: &self) + } + } + + @inlinable public var bytes: RawSpan { + let span = RawSpan(_unsafeBytes: UnsafeRawBufferPointer(unsafeBuffer)) + return unsafe _overrideLifetime(span, borrowing: self) + } } #endif diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index e4d0f47..3734760 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -1,6 +1,5 @@ #if os(Linux) import CSystem -import struct CSystem.io_uring_sqe @usableFromInline internal struct RawIORequest: ~Copyable { @@ -111,7 +110,6 @@ extension RawIORequest { } set { - // TODO: cleanup? rawValue.addr = UInt64(Int(bitPattern: newValue.baseAddress!)) rawValue.len = UInt32(exactly: newValue.count)! } From 227a38f230f5ad94df7fa1fc72e6b24f1e8b9056 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 8 Jul 2025 22:41:06 +0000 Subject: [PATCH 080/102] Remove blocking enqueue --- Sources/System/IORing.swift | 47 ++++++----------------------- Tests/SystemTests/IORingTests.swift | 8 +++-- 2 files changed, 14 insertions(+), 41 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 681ca7e..64515c3 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -724,23 +724,15 @@ public struct IORing: ~Copyable { /// Attempts to prepare an IO request for submission to the kernel. Returns false if no space is available to enqueue the request @inlinable - public mutating func tryPrepare(request: __owned Request) -> Bool { + public mutating func prepare(request: __owned Request) -> Bool { var raw: RawIORequest? = request.makeRawRequest() return _tryWriteRequest( raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) } - /// Attempts to prepare an IO request for submission to the kernel. Blocks if needed until space becomes available to enqueue the request - @inlinable - public mutating func prepare(request: __owned Request) { - var raw: RawIORequest? = request.makeRawRequest() - _writeRequest( - raw.take()!, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) - } - /// Attempts to prepare a chain of linked IO requests for submission to the kernel. Returns false if not enough space is available to enqueue the request. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order. @inlinable - mutating func tryPrepare(linkedRequests: some BidirectionalCollection) -> Bool { + mutating func prepare(linkedRequests: some BidirectionalCollection) -> Bool { guard linkedRequests.count > 0 else { return true } @@ -763,41 +755,20 @@ public struct IORing: ~Copyable { return true } - /// Prepares a chain of linked IO requests for submission to the kernel. Blocks if needed until space becomes available to enqueue the requests. If any linked operation fails, subsequent operations will be canceled. Linked operations always execute in order. - @inlinable - mutating func prepare(linkedRequests: some BidirectionalCollection) { - guard linkedRequests.count > 0 else { - return - } - let last = linkedRequests.last! - for req in linkedRequests.dropLast() { - var raw = req.makeRawRequest() - raw.linkToNextRequest() - _writeRequest( - raw, ring: &submissionRing, submissionQueueEntries: submissionQueueEntries) - } - _writeRequest( - last.makeRawRequest(), ring: &submissionRing, - submissionQueueEntries: submissionQueueEntries) - } - /// Prepares a sequence of requests for submission to the ring. Returns false if the submission queue doesn't have enough available space. @inlinable - public mutating func tryPrepare(linkedRequests: Request...) -> Bool { - tryPrepare(linkedRequests: linkedRequests) - } - - /// Prepares a sequence of requests for submission to the ring. Blocks if the submission queue doesn't have enough available space. - @inlinable - public mutating func prepare(linkedRequests: Request...) { + public mutating func prepare(linkedRequests: Request...) -> Bool { prepare(linkedRequests: linkedRequests) } - /// Prepares and submits a sequence of requests to the ring. Blocks if the submission queue doesn't have enough available space. + /// Prepares and submits a sequence of requests to the ring. Returns false if the submission queue doesn't have enough available space. @inlinable - public mutating func submit(linkedRequests: Request...) throws(Errno) { - prepare(linkedRequests: linkedRequests) + public mutating func submit(linkedRequests: Request...) throws(Errno) -> Bool { + if !prepare(linkedRequests: linkedRequests) { + return false + } try submitPreparedRequests() + return true } /// Describes which io_uring features are supported by the kernel this program is running on diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 29973c6..1297bf2 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -15,7 +15,7 @@ final class IORingTests: XCTestCase { func testNop() throws { var ring = try IORing(queueDepth: 32, flags: []) - try ring.submit(linkedRequests: .nop()) + _ = try ring.submit(linkedRequests: .nop()) let completion = try ring.blockingConsumeCompletion() XCTAssertEqual(completion.result, 0) } @@ -57,10 +57,11 @@ final class IORingTests: XCTestCase { try ring.registerEventFD(eventFD) //Part 1: read the file we just created, and make sure the eventfd fires - try ring.submit(linkedRequests: + let enqueued = try ring.submit(linkedRequests: .open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readOnly), .read(ring.registeredFileSlots[0], into: ring.registeredBuffers[0]), .close(ring.registeredFileSlots[0])) + XCTAssert(enqueued) let efdBuf = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 0) _ = try eventFD.read(into: efdBuf) _ = try ring.blockingConsumeCompletion() //open @@ -76,10 +77,11 @@ final class IORingTests: XCTestCase { remove($0) } XCTAssertEqual(rmResult, 0) - try ring.submit(linkedRequests: + let enqueued2 = try ring.submit(linkedRequests: .open(path, in: parent, into: ring.registeredFileSlots[0], mode: .readWrite, options: .create, permissions: .ownerReadWrite), .write(ring.registeredBuffers[0], into: ring.registeredFileSlots[0]), .close(ring.registeredFileSlots[0])) + XCTAssert(enqueued2) _ = try eventFD.read(into: efdBuf) _ = try ring.blockingConsumeCompletion() //open _ = try eventFD.read(into: efdBuf) From bc097e91dc7efe4c79324ec970aace5ed7b63ddd Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 8 Jul 2025 22:42:15 +0000 Subject: [PATCH 081/102] Remove more blocking enqueue infrastructure --- Sources/System/IORing.swift | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 64515c3..5c48373 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -67,35 +67,6 @@ internal func _tryWriteRequest( return false } -@inline(__always) @inlinable -internal func _writeRequest( - _ request: __owned RawIORequest, ring: inout SQRing, - submissionQueueEntries: UnsafeMutableBufferPointer -) -{ - let entry = _blockingGetSubmissionEntry( - ring: &ring, submissionQueueEntries: submissionQueueEntries) - entry.pointee = request.rawValue -} - -@inline(__always) @inlinable -internal func _blockingGetSubmissionEntry( - ring: inout SQRing, submissionQueueEntries: UnsafeMutableBufferPointer -) -> UnsafeMutablePointer< - io_uring_sqe -> { - while true { - if let entry = _getSubmissionEntry( - ring: &ring, - submissionQueueEntries: submissionQueueEntries - ) { - return entry - } - // TODO: actually block here instead of spinning - } - -} - //TODO: omitting signal mask for now //Tell the kernel that we've submitted requests and/or are waiting for completions @inlinable From 55e55c197880d5f4422937d59d537e8266560f4a Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 8 Jul 2025 23:15:17 +0000 Subject: [PATCH 082/102] Add test and fix submission queue capacity check --- Sources/System/IORing.swift | 12 ++++++++---- Tests/SystemTests/IORingTests.swift | 10 ++++++++-- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 5c48373..4a28f7c 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -105,23 +105,27 @@ internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) thr } @inlinable -internal func _getUnconsumedSubmissionCount(ring: borrowing SQRing) -> UInt32 { +internal func _getSubmissionQueueCount(ring: borrowing SQRing) -> UInt32 { return ring.userTail - ring.kernelHead.pointee.load(ordering: .acquiring) } +@inlinable +internal func _getRemainingSubmissionQueueCapacity(ring: borrowing SQRing) -> UInt32 { + return UInt32(truncatingIfNeeded: ring.array.count) - _getSubmissionQueueCount(ring: ring) +} + @inlinable internal func _getUnconsumedCompletionCount(ring: borrowing CQRing) -> UInt32 { return ring.kernelTail.pointee.load(ordering: .acquiring) - ring.kernelHead.pointee.load(ordering: .acquiring) } -//TODO: pretty sure this is supposed to do more than it does @inlinable internal func _flushQueue(ring: borrowing SQRing) -> UInt32 { ring.kernelTail.pointee.store( ring.userTail, ordering: .releasing ) - return _getUnconsumedSubmissionCount(ring: ring) + return _getSubmissionQueueCount(ring: ring) } @inlinable @@ -707,7 +711,7 @@ public struct IORing: ~Copyable { guard linkedRequests.count > 0 else { return true } - let freeSQECount = _getUnconsumedSubmissionCount(ring: submissionRing) + let freeSQECount = _getRemainingSubmissionQueueCapacity(ring: submissionRing) guard freeSQECount >= linkedRequests.count else { return false } diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 1297bf2..757866a 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -42,17 +42,23 @@ final class IORingTests: XCTestCase { } func setupTestRing(depth: Int, fileSlots: Int, buffers: [UnsafeMutableRawBufferPointer]) throws -> IORing { - var ring: IORing = try IORing(queueDepth: 6) + var ring: IORing = try IORing(queueDepth: UInt32(depth)) _ = try ring.registerFileSlots(count: 1) _ = try ring.registerBuffers(buffers) return ring } + func testUndersizedSubmissionQueue() throws { + var ring: IORing = try IORing(queueDepth: 1) + let enqueued = ring.prepare(linkedRequests: .nop(), .nop()) + XCTAssertFalse(enqueued) + } + // Exercises opening, reading, closing, registered files, registered buffers, and eventfd func testOpenReadAndWriteFixedFile() throws { let (parent, path) = try makeHelloWorldFile() let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) - var ring = try setupTestRing(depth: 3, fileSlots: 1, buffers: [rawBuffer]) + var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer]) let eventFD = FileDescriptor(rawValue: eventfd(0, Int32(EFD_SEMAPHORE))) try ring.registerEventFD(eventFD) From a6c5a39ca53ec58d4d7cf5ebbd98e32cfcdd1185 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 8 Jul 2025 16:24:20 -0700 Subject: [PATCH 083/102] Remove the proposal doc --- NNNN-swift-system-io-uring.md | 463 ---------------------------------- 1 file changed, 463 deletions(-) delete mode 100644 NNNN-swift-system-io-uring.md diff --git a/NNNN-swift-system-io-uring.md b/NNNN-swift-system-io-uring.md deleted file mode 100644 index d103578..0000000 --- a/NNNN-swift-system-io-uring.md +++ /dev/null @@ -1,463 +0,0 @@ -# IORing, a Swift System API for io_uring - -* Proposal: [SE-NNNN](NNNN-filename.md) -* Authors: [Lucy Satheesan](https://github.com/oxy), [David Smith](https://github.com/Catfish-Man/) -* Review Manager: TBD -* Status: **Awaiting implementation** -* Implementation: [apple/swift-system#208](https://github.com/apple/swift-system/pull/208) - -## Introduction - -`io_uring` is Linux's solution to asynchronous and batched syscalls, with a particular focus on IO. We propose a low-level Swift API for it in Swift System that could either be used directly by projects with unusual needs, or via intermediaries like Swift NIO, to address scalability and thread pool starvation issues. - -## Motivation - -Up until recently, the overwhelmingly dominant file IO syscalls on major Unix platforms have been synchronous, e.g. `read(2)`. This design is very simple and proved sufficient for many uses for decades, but is less than ideal for Swift's needs in a few major ways: - -1. Requiring an entire OS thread for each concurrent operation imposes significant memory overhead -2. Requiring a separate syscall for each operation imposes significant CPU/time overhead to switch into and out of kernel mode repeatedly. This has been exacerbated in recent years by mitigations for the Meltdown family of security exploits increasing the cost of syscalls. -3. Swift's N:M coroutine-on-thread-pool concurrency model assumes that threads will not be blocked. Each thread waiting for a syscall means a CPU core being left idle. In practice systems like NIO that deal in highly concurrent IO have had to work around this by providing their own thread pools. - -Non-file IO (network, pipes, etc…) has been in a somewhat better place with `epoll` and `kqueue` for asynchronously waiting for readability, but syscall overhead remains a significant issue for highly scalable systems. - -With the introduction of `io_uring` in 2019, Linux now has the kernel level tools to address these three problems directly. However, `io_uring` is quite complex and maps poorly into Swift. We expect that by providing a Swift interface to it, we can enable Swift on Linux servers to scale better and be more efficient than it has been in the past. - -## Proposed solution - -We propose a *low level, unopinionated* Swift interface for io_uring on Linux (see Future Directions for discussion of possible more abstract interfaces). - -`struct IORing: ~Copyable` provides facilities for - -* Registering and unregistering resources (files and buffers), an `io_uring` specific variation on Unix file IOdescriptors that improves their efficiency -* Registering and unregistering eventfds, which allow asynchronous waiting for completions -* Enqueueing IO requests -* Dequeueing IO completions - -`struct IORing.RegisteredResource` represents, via its two typealiases `IORing.RegisteredFile` and `IORing.RegisteredBuffer`, registered file descriptors and buffers. - -`struct IORing.Request: ~Copyable` represents an IO operation that can be enqueued for the kernel to execute. It supports a wide variety of operations matching traditional unix file and socket operations. - -Request operations are expressed as overloaded static methods on `Request`, e.g. `openat` is spelled - -```swift - public static func open( - _ path: FilePath, - in directory: FileDescriptor, - into slot: IORing.RegisteredFile, - mode: FileDescriptor.AccessMode, - options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil, - context: UInt64 = 0 - ) -> Request - - public static func open( - _ path: FilePath, - in directory: FileDescriptor, - mode: FileDescriptor.AccessMode, - options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil, - context: UInt64 = 0 - ) -> Request -``` - -which allows clients to decide whether they want to open the file into a slot on the ring, or have it return a file descriptor via a completion. Similarly, read operations have overloads for "use a buffer from the ring" or "read into this `UnsafeMutableBufferPointer`" - -Multiple `Requests` can be enqueued on a single `IORing` using the `prepare(…)` family of methods, and then submitted together using `submitPreparedRequests`, allowing for things like "open this file, read its contents, and then close it" to be a single syscall. Conveniences are provided for preparing and submitting requests in one call. - -Since IO operations can execute in parallel or out of order by default, linked chains of operations can be established with `prepare(linkedRequests:…)` and related methods. Separate chains can still execute in parallel, and if an operation early in the chain fails, all subsequent operations will deliver cancellation errors as their completion. - -Already-completed results can be retrieved from the ring using `tryConsumeCompletion`, which never waits but may return nil, or `blockingConsumeCompletion(timeout:)`, which synchronously waits (up to an optional timeout) until an operation completes. There's also a bulk version of `blockingConsumeCompletion`, which may reduce the number of syscalls issued. It takes a closure which will be called repeatedly as completions are available (see Future Directions for potential improvements to this API). - -Since neither polling nor synchronously waiting is optimal in many cases, `IORing` also exposes the ability to register an eventfd (see `man eventfd(2)`), which will become readable when completions are available on the ring. This can then be monitored asynchronously with `epoll`, `kqueue`, or for clients who are linking libdispatch, `DispatchSource`. - -`struct IORing.Completion: ~Copyable` represents the result of an IO operation and provides - -* Flags indicating various operation-specific metadata about the now-completed syscall -* The context associated with the operation when it was enqueued, as an `UnsafeRawPointer` or a `UInt64` -* The result of the operation, as an `Int32` with operation-specific meaning -* The error, if one occurred - -Unfortunately the underlying kernel API makes it relatively difficult to determine which `Request` led to a given `Completion`, so it's expected that users will need to create this association themselves via the context parameter. - -`IORing.Features` describes the supported features of the underlying kernel `IORing` implementation, which can be used to provide graceful reduction in functionality when running on older systems. - -## Detailed design - -```swift -// IORing is intentionally not Sendable, to avoid internal locking overhead -public struct IORing: ~Copyable { - - public init(queueDepth: UInt32, flags: IORing.SetupFlags = []) throws(Errno) - - public struct SetupFlags: OptionSet, RawRepresentable, Hashable { - public var rawValue: UInt32 - public init(rawValue: UInt32) - public static var pollCompletions: SetupFlags //IORING_SETUP_IOPOLL - public static var pollSubmissions: SetupFlags //IORING_SETUP_SQPOLL - public static var clampMaxEntries: SetupFlags //IORING_SETUP_CLAMP - public static var startDisabled: SetupFlags //IORING_SETUP_R_DISABLED - public static var continueSubmittingOnError: SetupFlags //IORING_SETUP_SUBMIT_ALL - public static var singleSubmissionThread: SetupFlags //IORING_SETUP_SINGLE_ISSUER - public static var deferRunningTasks: SetupFlags //IORING_SETUP_DEFER_TASKRUN - } - - public mutating func registerEventFD(_ descriptor: FileDescriptor) throws(Errno) - public mutating func unregisterEventFD() throws(Errno) - - public struct RegisteredResource { } - public typealias RegisteredFile = RegisteredResource - public typealias RegisteredBuffer = RegisteredResource - - // A `RegisteredResources` is a view into the buffers or files registered with the ring, if any - public struct RegisteredResources: RandomAccessCollection { - public subscript(position: Int) -> RegisteredResource - public subscript(position: UInt16) -> RegisteredResource // This is useful because io_uring likes to use UInt16s as indexes - } - - public mutating func registerFileSlots(count: Int) throws(Errno) -> RegisteredResources - public func unregisterFiles() - public var registeredFileSlots: RegisteredResources - - public mutating func registerBuffers( - _ buffers: some Collection - ) throws(Errno) -> RegisteredResources - - public mutating func registerBuffers( - _ buffers: UnsafeMutableRawBufferPointer... - ) throws(Errno) -> RegisteredResources - - public func unregisterBuffers() - - public var registeredBuffers: RegisteredResources - - public func prepare(requests: Request...) - public func prepare(linkedRequests: Request...) - - public func submitPreparedRequests(timeout: Duration? = nil) throws(Errno) - public func submit(requests: Request..., timeout: Duration? = nil) throws(Errno) - public func submit(linkedRequests: Request..., timeout: Duration? = nil) throws(Errno) - - public func submitPreparedRequests() throws(Errno) - public func submitPreparedRequestsAndWait(timeout: Duration? = nil) throws(Errno) - - public func submitPreparedRequestsAndConsumeCompletions( - minimumCount: UInt32 = 1, - timeout: Duration? = nil, - consumer: (consuming Completion?, Errno?, Bool) throws(E) -> Void - ) throws(E) - - public func blockingConsumeCompletion( - timeout: Duration? = nil - ) throws(Errno) -> Completion - - public func blockingConsumeCompletions( - minimumCount: UInt32 = 1, - timeout: Duration? = nil, - consumer: (consuming Completion?, Errno?, Bool) throws(E) -> Void - ) throws(E) - - public func tryConsumeCompletion() -> Completion? - - public struct Features: OptionSet, RawRepresentable, Hashable { - let rawValue: UInt32 - - public init(rawValue: UInt32) - - //IORING_FEAT_SINGLE_MMAP is handled internally - public static let nonDroppingCompletions: Features //IORING_FEAT_NODROP - public static let stableSubmissions: Features //IORING_FEAT_SUBMIT_STABLE - public static let currentFilePosition: Features //IORING_FEAT_RW_CUR_POS - public static let assumingTaskCredentials: Features //IORING_FEAT_CUR_PERSONALITY - public static let fastPolling: Features //IORING_FEAT_FAST_POLL - public static let epoll32BitFlags: Features //IORING_FEAT_POLL_32BITS - public static let pollNonFixedFiles: Features //IORING_FEAT_SQPOLL_NONFIXED - public static let extendedArguments: Features //IORING_FEAT_EXT_ARG - public static let nativeWorkers: Features //IORING_FEAT_NATIVE_WORKERS - public static let resourceTags: Features //IORING_FEAT_RSRC_TAGS - public static let allowsSkippingSuccessfulCompletions: Features //IORING_FEAT_CQE_SKIP - public static let improvedLinkedFiles: Features //IORING_FEAT_LINKED_FILE - public static let registerRegisteredRings: Features //IORING_FEAT_REG_REG_RING - public static let minimumTimeout: Features //IORING_FEAT_MIN_TIMEOUT - public static let bundledSendReceive: Features //IORING_FEAT_RECVSEND_BUNDLE - } - public var supportedFeatures: Features -} - -public extension IORing.RegisteredBuffer { - var unsafeBuffer: UnsafeMutableRawBufferPointer -} - -public extension IORing { - struct Request: ~Copyable { - public static func nop(context: UInt64 = 0) -> Request - - // overloads for each combination of registered vs unregistered buffer/descriptor - // Read - public static func read( - _ file: IORing.RegisteredFile, - into buffer: IORing.RegisteredBuffer, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> Request - - public static func read( - _ file: FileDescriptor, - into buffer: IORing.RegisteredBuffer, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> Request - - public static func read( - _ file: IORing.RegisteredFile, - into buffer: UnsafeMutableRawBufferPointer, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> Request - - public static func read( - _ file: FileDescriptor, - into buffer: UnsafeMutableRawBufferPointer, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> Request - - // Write - public static func write( - _ buffer: IORing.RegisteredBuffer, - into file: IORing.RegisteredFile, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> Request - - public static func write( - _ buffer: IORing.RegisteredBuffer, - into file: FileDescriptor, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> Request - - public static func write( - _ buffer: UnsafeMutableRawBufferPointer, - into file: IORing.RegisteredFile, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> Request - - public static func write( - _ buffer: UnsafeMutableRawBufferPointer, - into file: FileDescriptor, - at offset: UInt64 = 0, - context: UInt64 = 0 - ) -> Request - - // Close - public static func close( - _ file: FileDescriptor, - context: UInt64 = 0 - ) -> Request - - public static func close( - _ file: IORing.RegisteredFile, - context: UInt64 = 0 - ) -> Request - - // Open At - public static func open( - _ path: FilePath, - in directory: FileDescriptor, - into slot: IORing.RegisteredFile, - mode: FileDescriptor.AccessMode, - options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil, - context: UInt64 = 0 - ) -> Request - - public static func open( - _ path: FilePath, - in directory: FileDescriptor, - mode: FileDescriptor.AccessMode, - options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(), - permissions: FilePermissions? = nil, - context: UInt64 = 0 - ) -> Request - - public static func unlink( - _ path: FilePath, - in directory: FileDescriptor, - context: UInt64 = 0 - ) -> Request - - // Cancel - - public enum CancellationMatch { - case all - case first - } - - public static func cancel( - _ matchAll: CancellationMatch, - matchingContext: UInt64, - ) -> Request - - public static func cancel( - _ matchAll: CancellationMatch, - matching: FileDescriptor, - ) -> Request - - public static func cancel( - _ matchAll: CancellationMatch, - matching: IORing.RegisteredFile, - ) -> Request - - // Other operations follow in the same pattern - } - - struct Completion { - public struct Flags: OptionSet, Hashable, Codable { - public let rawValue: UInt32 - - public init(rawValue: UInt32) - - public static let moreCompletions: Flags - public static let socketNotEmpty: Flags - public static let isNotificationEvent: Flags - } - - //These are both the same value, but having both eliminates some ugly casts in client code - public var context: UInt64 - public var contextPointer: UnsafeRawPointer - - public var result: Int32 - - public var error: Errno? // Convenience wrapper over `result` - - public var flags: Flags - } -} - -``` - -## Usage Examples - -### Blocking - -```swift -let ring = try IORing(queueDepth: 2) - -//Make space on the ring for our file (this is optional, but improves performance with repeated use) -let file = ring.registerFiles(count: 1)[0] - -var statInfo = Glibc.stat() // System doesn't have an abstraction for stat() right now -// Build our requests to open the file and find out how big it is -ring.prepare(linkedRequests: - .open(path, - in: parentDirectory, - into: file, - mode: mode, - options: openOptions, - permissions: nil - ), - .stat(file, - into: &statInfo - ) -) -//batch submit 2 syscalls in 1! -try ring.submitPreparedRequestsAndConsumeCompletions(minimumCount: 2) { (completion: consuming Completion?, error, done) in - if let error { - throw error //or other error handling as desired - } -} - -// We could register our buffer with the ring too, but we're only using it once -let buffer = UnsafeMutableRawBufferPointer.allocate(Int(statInfo.st_size)) - -// Build our requests to read the file and close it -ring.prepare(linkedRequests: - .read(file, - into: buffer - ), - .close(file) -) - -//batch submit 2 syscalls in 1! -try ring.submitPreparedRequestsAndConsumeCompletions(minimumCount: 2) { (completion: consuming Completion?, error, done) in - if let error { - throw error //or other error handling as desired - } -} - -processBuffer(buffer) -``` - -### Using libdispatch to wait for the read asynchronously - -```swift -//Initial setup as above up through creating buffer, omitted for brevity - -//Make the read request with a context so we can get the buffer out of it in the completion handler -… -.read(file, into: buffer, context: UInt64(buffer.baseAddress!)) -… - -// Make an eventfd and register it with the ring -let eventfd = eventfd(0, 0) -ring.registerEventFD(eventfd) - -// Make a read source to monitor the eventfd for readability -let readabilityMonitor = DispatchSource.makeReadSource(fileDescriptor: eventfd) -readabilityMonitor.setEventHandler { - let completion = ring.blockingConsumeCompletion() - if let error = completion.error { - //handle failure to read the file - } - processBuffer(completion.contextPointer) -} -readabilityMonitor.activate() - -ring.submitPreparedRequests //note, not "AndConsumeCompletions" this time -``` - -## Source compatibility - -This is an all-new API in Swift System, so has no backwards compatibility implications. Of note, though, this API is only available on Linux. - -## ABI compatibility - -Swift on Linux does not have a stable ABI, and we will likely take advantage of this to evolve IORing as compiler support improves, as described in Future Directions. - -## Implications on adoption - -This feature is intrinsically linked to Linux kernel support, so constrains the deployment target of anything that adopts it to newer kernels. Exactly which features of the evolving io_uring syscall surface area we need is under consideration. - -## Future directions - -* While most Swift users on Darwin are not limited by IO scalability issues, the thread pool considerations still make introducing something similar to this appealing if and when the relevant OS support is available. We should attempt to the best of our ability to not design this in a way that's gratuitously incompatible with non-Linux OSs, although Swift System does not attempt to have an API that's identical on all platforms. -* The set of syscalls covered by `io_uring` has grown significantly and is still growing. We should leave room for supporting additional operations in the future. -* Once same-element requirements and pack counts as integer generic arguments are supported by the compiler, we should consider adding something along the lines of the following to allow preparing, submitting, and waiting for an entire set of operations at once: - -``` -func submitLinkedRequestsAndWait( - _ requests: repeat each Request -) where Request == IORing.Request - -> InlineArray<(repeat each Request).count, IORing.Completion> -``` -* Once mutable borrows are supported, we should consider replacing the closure-taking bulk completion APIs (e.g. `blockingConsumeCompletions(…)`) with ones that return a sequence of completions instead -* We should consider making more types noncopyable as compiler support improves -* liburing has a "peek next completion" operation that doesn't consume it, and then a "mark consumed" operation. We may want to add something similar -* liburing has support for operations allocating their own buffers and returning them via the completion, we may want to support this -* We may want to provide API for asynchronously waiting, rather than just exposing the eventfd to let people roll their own async waits. Doing this really well has *considerable* implications for the concurrency runtime though. -* We should almost certainly expose API for more of the configuration options in `io_uring_setup` -* Stronger safety guarantees around cancellation and resource lifetimes (e.g. as described in https://without.boats/blog/io-uring/) would be very welcome, but require an API that is much more strongly opinionated about how io_uring is used. A future higher level abstraction focused on the goal of being "an async IO API for Swift" rather than "a Swifty interface to io_uring" seems like a good place for that. - -## Alternatives considered - -* We could use a NIO-style separate thread pool, but we believe `io_uring` is likely a better option for scalability. We may still want to provide a thread-pool backed version as an option, because many Linux systems currently disable `io_uring` due to security concerns. -* We could multiplex all IO onto a single actor as `AsyncBytes` currently does, but this has a number of downsides that make it entirely unsuitable to server usage. Most notably, it eliminates IO parallelism entirely. -* Using POSIX AIO instead of or as well as io_uring would greatly increase our ability to support older kernels and other Unix systems, but it has well-documented performance and usability issues that have prevented its adoption elsewhere, and apply just as much to Swift. -* Earlier versions of this proposal had higher level "managed" abstractions over IORing. These have been removed due to lack of interest from clients, but could be added back later if needed. -* I considered having dedicated error types for IORing, but eventually decided throwing Errno was more consistent with other platform APIs -* RegisteredResource was originally a class in an attempt to manage the lifetime of the resource via language features. Changing to the current model of it being a copyable struct didn't make the lifetime management any less safe (the IORing still owns the actual resource), and reduces overhead. In the future it would be neat if we could express RegisteredResources as being borrowed from the IORing so they can't be used after its lifetime. - -## Acknowledgments - -The NIO team, in particular Cory Benfield and Franz Busch, have provided invaluable feedback and direction on this project. From 528e7485ba5b3293114f93a8be33fe2b11fee9d2 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 8 Jul 2025 16:38:21 -0700 Subject: [PATCH 084/102] Document completion flags and disable ones we don't currently support --- Sources/System/IOCompletion.swift | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index 4263bd8..395e892 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -18,10 +18,15 @@ public extension IORing.Completion { self.rawValue = rawValue } - public static let allocatedBuffer = Flags(rawValue: 1 << 0) - public static let moreCompletions = Flags(rawValue: 1 << 1) - public static let socketNotEmpty = Flags(rawValue: 1 << 2) - public static let isNotificationEvent = Flags(rawValue: 1 << 3) + ///`IORING_CQE_F_BUFFER` Indicates the buffer ID is stored in the upper 16 bits + @inlinable public static var allocatedBuffer: Flags { Flags(rawValue: 1 << 0) } + ///`IORING_CQE_F_MORE` Indicates more completions will be generated from the request that generated this + @inlinable public static var moreCompletions: Flags { Flags(rawValue: 1 << 1) } + //`IORING_CQE_F_SOCK_NONEMPTY`, but currently unused + //@inlinable public static var socketNotEmpty: Flags { Flags(rawValue: 1 << 2) } + //`IORING_CQE_F_NOTIF`, but currently unused + //@inlinable public static var isNotificationEvent: Flags { Flags(rawValue: 1 << 3) } + //IORING_CQE_F_BUF_MORE will eventually be (1U << 4) if we add IOU_PBUF_RING_INC support } } From d6687d2bbb73e8f93980be1f67ec5cafdc185775 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 8 Jul 2025 16:51:24 -0700 Subject: [PATCH 085/102] Add deleted file back --- Sources/CSystem/shims.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Sources/CSystem/shims.c diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c new file mode 100644 index 0000000..f492a2a --- /dev/null +++ b/Sources/CSystem/shims.c @@ -0,0 +1,18 @@ +/* + 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 +*/ + +#ifdef __linux__ + +#include + +#endif + +#if defined(_WIN32) +#include +#endif From d2b78f801bf5dba3f72167e1f5e05e6a5c5edd10 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 8 Jul 2025 23:53:50 +0000 Subject: [PATCH 086/102] Remove unneeded defines --- Sources/CSystem/include/io_uring.h | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index df1b36a..2d081af 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -8,21 +8,6 @@ #ifndef SWIFT_IORING_C_WRAPPER #define SWIFT_IORING_C_WRAPPER -#ifdef __alpha__ -/* - * alpha is the only exception, all other architectures - * have common numbers for new system calls. - */ -# ifndef __NR_io_uring_setup -# define __NR_io_uring_setup 535 -# endif -# ifndef __NR_io_uring_enter -# define __NR_io_uring_enter 536 -# endif -# ifndef __NR_io_uring_register -# define __NR_io_uring_register 537 -# endif -#else /* !__alpha__ */ # ifndef __NR_io_uring_setup # define __NR_io_uring_setup 425 # endif @@ -32,7 +17,6 @@ # ifndef __NR_io_uring_register # define __NR_io_uring_register 427 # endif -#endif /* struct io_uring_getevents_arg { From 8757fae97c67a4a74c49610d8748e691cdac26f2 Mon Sep 17 00:00:00 2001 From: David Smith Date: Tue, 8 Jul 2025 16:57:30 -0700 Subject: [PATCH 087/102] Remove some stray commas the API breakage test complains about --- Sources/System/IORequest.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 1d0638b..f6c1f74 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -328,7 +328,7 @@ extension IORing.Request { @inlinable public static func cancel( _ matchAll: CancellationMatch, - matchingContext: UInt64, + matchingContext: UInt64 ) -> IORing.Request { switch matchAll { case .all: @@ -340,7 +340,7 @@ extension IORing.Request { @inlinable public static func cancel( _ matchAll: CancellationMatch, - matching: FileDescriptor, + matching: FileDescriptor ) -> IORing.Request { switch matchAll { case .all: @@ -352,7 +352,7 @@ extension IORing.Request { @inlinable public static func cancel( _ matchAll: CancellationMatch, - matching: IORing.RegisteredFile, + matching: IORing.RegisteredFile ) -> IORing.Request { switch matchAll { case .all: From 4b70ffe375f6a8891e81081b97ff055b754a610b Mon Sep 17 00:00:00 2001 From: David Smith Date: Wed, 9 Jul 2025 20:53:23 +0000 Subject: [PATCH 088/102] Fix short submits and also fix the registration ops enum, which somehow stopped compiling overnight --- Sources/CSystem/include/io_uring.h | 18 ---------------- Sources/System/IORing.swift | 33 +++++++++++++++++++++++------- 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/Sources/CSystem/include/io_uring.h b/Sources/CSystem/include/io_uring.h index 2d081af..0068f50 100644 --- a/Sources/CSystem/include/io_uring.h +++ b/Sources/CSystem/include/io_uring.h @@ -33,24 +33,6 @@ struct swift_io_uring_getevents_arg { __u64 ts; }; -//This was #defines in older headers, so we redeclare it to get a consistent import -typedef enum : __u32 { - SWIFT_IORING_REGISTER_BUFFERS = 0, - SWIFT_IORING_UNREGISTER_BUFFERS = 1, - SWIFT_IORING_REGISTER_FILES = 2, - SWIFT_IORING_UNREGISTER_FILES = 3, - SWIFT_IORING_REGISTER_EVENTFD = 4, - SWIFT_IORING_UNREGISTER_EVENTFD = 5, - SWIFT_IORING_REGISTER_FILES_UPDATE = 6, - SWIFT_IORING_REGISTER_EVENTFD_ASYNC = 7, - SWIFT_IORING_REGISTER_PROBE = 8, - SWIFT_IORING_REGISTER_PERSONALITY = 9, - SWIFT_IORING_UNREGISTER_PERSONALITY = 10, - - /* this goes last */ - SWIFT_IORING_REGISTER_LAST -} SWIFT_IORING_REGISTER_OPS; - static inline int io_uring_register(int fd, unsigned int opcode, void *arg, unsigned int nr_args) { diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 4a28f7c..5546540 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -8,6 +8,21 @@ import Musl #endif import Synchronization +//This was #defines in older headers, so we redeclare it to get a consistent import +internal enum RegistrationOps: UInt32 { + case registerBuffers = 0 + case unregisterBuffers = 1 + case registerFiles = 2 + case unregisterFiles = 3 + case registerEventFD = 4 + case unregisterEventFD = 5 + case registerFilesUpdate = 6 + case registerEventFDAsync = 7 + case registerProbe = 8 + case registerPersonality = 9 + case unregisterPersonality = 10 +} + extension UnsafeMutableRawPointer { func advanced(by offset: UInt32) -> UnsafeMutableRawPointer { return advanced(by: Int(offset)) @@ -71,6 +86,7 @@ internal func _tryWriteRequest( //Tell the kernel that we've submitted requests and/or are waiting for completions @inlinable internal func _enter( + ring: borrowing SQRing, ringDescriptor: Int32, numEvents: UInt32, minCompletions: UInt32, @@ -91,6 +107,9 @@ internal func _enter( continue } else if ret < 0 { throw(Errno(rawValue: -ret)) + } else if _getSubmissionQueueCount(ring: ring) > 0 { + // See https://github.com/axboe/liburing/issues/309, in some cases not all pending requests are submitted + continue } else { return ret } @@ -101,7 +120,7 @@ internal func _enter( internal func _submitRequests(ring: borrowing SQRing, ringDescriptor: Int32) throws(Errno) { let flushedEvents = _flushQueue(ring: ring) _ = try _enter( - ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0) + ring: ring, ringDescriptor: ringDescriptor, numEvents: flushedEvents, minCompletions: 0, flags: 0) } @inlinable @@ -536,7 +555,7 @@ public struct IORing: ~Copyable { let result = withUnsafePointer(to: &rawfd) { fdptr in let result = io_uring_register( ringDescriptor, - SWIFT_IORING_REGISTER_EVENTFD.rawValue, + RegistrationOps.registerEventFD.rawValue, UnsafeMutableRawPointer(mutating: fdptr), 1 ) @@ -551,7 +570,7 @@ public struct IORing: ~Copyable { public mutating func unregisterEventFD() throws(Errno) { let result = io_uring_register( ringDescriptor, - IORING_UNREGISTER_EVENTFD.rawValue, + RegistrationOps.unregisterEventFD.rawValue, nil, 0 ) @@ -569,7 +588,7 @@ public struct IORing: ~Copyable { let regResult = files.withUnsafeBufferPointer { bPtr in let result = io_uring_register( self.ringDescriptor, - IORING_REGISTER_FILES.rawValue, + RegistrationOps.registerFiles.rawValue, UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), UInt32(truncatingIfNeeded: count) ) @@ -588,7 +607,7 @@ public struct IORing: ~Copyable { public func unregisterFiles() throws { let result = io_uring_register( ringDescriptor, - IORING_UNREGISTER_FILES.rawValue, + RegistrationOps.unregisterFiles.rawValue, nil, 0 ) @@ -613,7 +632,7 @@ public struct IORing: ~Copyable { let regResult = iovecs.withUnsafeBufferPointer { bPtr in let result = io_uring_register( self.ringDescriptor, - IORING_REGISTER_BUFFERS.rawValue, + RegistrationOps.registerBuffers.rawValue, UnsafeMutableRawPointer(mutating: bPtr.baseAddress!), UInt32(truncatingIfNeeded: buffers.count) ) @@ -662,7 +681,7 @@ public struct IORing: ~Copyable { public func unregisterBuffers() throws { let result = io_uring_register( self.ringDescriptor, - IORING_UNREGISTER_BUFFERS.rawValue, + RegistrationOps.unregisterBuffers.rawValue, nil, 0 ) From 329c5f59a25efc5a96468ead91d5a1a073b396e1 Mon Sep 17 00:00:00 2001 From: David Smith Date: Wed, 9 Jul 2025 21:17:42 +0000 Subject: [PATCH 089/102] Conditionalize IORing on compiler >= 6.2 --- Sources/System/IOCompletion.swift | 2 ++ Sources/System/IORequest.swift | 2 ++ Sources/System/IORing.swift | 3 +++ Sources/System/RawIORequest.swift | 3 +++ Tests/SystemTests/IORequestTests.swift | 3 +++ Tests/SystemTests/IORingTests.swift | 3 +++ 6 files changed, 16 insertions(+) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IOCompletion.swift index 395e892..65616e2 100644 --- a/Sources/System/IOCompletion.swift +++ b/Sources/System/IOCompletion.swift @@ -1,4 +1,5 @@ #if os(Linux) +#if compiler(>=6.2) import CSystem public extension IORing { @@ -66,3 +67,4 @@ public extension IORing.Completion { } } #endif +#endif diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index f6c1f74..5d4143d 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -1,4 +1,5 @@ #if os(Linux) +#if compiler(>=6.2) import CSystem @usableFromInline @@ -466,3 +467,4 @@ extension IORing.Request { } } #endif +#endif diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 5546540..cb47e34 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -1,4 +1,6 @@ #if os(Linux) +#if compiler(>=6.2) + import CSystem // needed for mmap #if canImport(Glibc) @@ -825,3 +827,4 @@ extension IORing.RegisteredBuffer { } } #endif +#endif \ No newline at end of file diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 3734760..461bae0 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -1,4 +1,6 @@ #if os(Linux) +#if compiler(>=6.2) + import CSystem @usableFromInline @@ -198,3 +200,4 @@ extension RawIORequest { } } #endif +#endif \ No newline at end of file diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 4d32196..53a0a82 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -1,4 +1,6 @@ #if os(Linux) +#if compiler(>=6.2) + import XCTest #if SYSTEM_PACKAGE @@ -29,3 +31,4 @@ final class IORequestTests: XCTestCase { } } #endif +#endif \ No newline at end of file diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 757866a..7fb899f 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -1,4 +1,6 @@ #if os(Linux) +#if compiler(>=6.2) + import XCTest import CSystem //for eventfd @@ -108,3 +110,4 @@ final class IORingTests: XCTestCase { } } #endif +#endif \ No newline at end of file From a6675d7e5c54d7a9dfdae14451aa48b6d86f819c Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 10 Jul 2025 23:22:11 +0000 Subject: [PATCH 090/102] timespec should be compatible here, let's try it to fix the Ubuntu 22 build --- Sources/System/IORing.swift | 12 ++++++------ Sources/System/RawIORequest.swift | 6 +++--- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index cb47e34..6a281a0 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -479,9 +479,9 @@ public struct IORing: ~Copyable { timeout: Duration? = nil ) throws(Errno) -> Completion { if let timeout { - var ts = __kernel_timespec( - tv_sec: timeout.components.seconds, - tv_nsec: timeout.components.attoseconds / 1_000_000_000 + var ts = timespec( + tv_sec: Int(timeout.components.seconds), + tv_nsec: Int(timeout.components.attoseconds / 1_000_000_000) ) return try withUnsafePointer(to: &ts) { (tsPtr) throws(Errno) -> Completion in var args = swift_io_uring_getevents_arg( @@ -505,9 +505,9 @@ public struct IORing: ~Copyable { consumer: (consuming Completion?, Errno?, Bool) throws(Err) -> Void ) throws(Err) { if let timeout { - var ts = __kernel_timespec( - tv_sec: timeout.components.seconds, - tv_nsec: timeout.components.attoseconds / 1_000_000_000 + var ts = timespec( + tv_sec: Int(timeout.components.seconds), + tv_nsec: Int(timeout.components.attoseconds / 1_000_000_000) ) try withUnsafePointer(to: &ts) { (tsPtr) throws(Err) in var args = swift_io_uring_getevents_arg( diff --git a/Sources/System/RawIORequest.swift b/Sources/System/RawIORequest.swift index 461bae0..b22c1c7 100644 --- a/Sources/System/RawIORequest.swift +++ b/Sources/System/RawIORequest.swift @@ -184,9 +184,9 @@ extension RawIORequest { opEntry.pointee.flags |= Flags.linkRequest.rawValue opEntry.pointee.off = 1 - var ts = __kernel_timespec( - tv_sec: duration.components.seconds, - tv_nsec: duration.components.attoseconds / 1_000_000_000 + var ts = timespec( + tv_sec: Int(duration.components.seconds), + tv_nsec: Int(duration.components.attoseconds / 1_000_000_000) ) return try withUnsafePointer(to: &ts) { tsPtr in var req: RawIORequest = RawIORequest() From d121081c01de1970730f3623e4d42b648e7bf013 Mon Sep 17 00:00:00 2001 From: David Smith Date: Thu, 10 Jul 2025 23:30:42 +0000 Subject: [PATCH 091/102] More Ubuntu 22 workarounds. This should error at runtime rather than not compiling, since we don't have Linux version checks at compile time --- Sources/System/IORequest.swift | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index 5d4143d..b7a0e1a 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -321,7 +321,15 @@ extension IORing.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 - */ + */ + +@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 } + public enum CancellationMatch { case all case first @@ -333,9 +341,9 @@ extension IORing.Request { ) -> IORing.Request { switch matchAll { case .all: - .init(core: .cancel(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) + .init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) case .first: - .init(core: .cancel(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) + .init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ANY | SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) } } @@ -345,9 +353,9 @@ extension IORing.Request { ) -> IORing.Request { switch matchAll { case .all: - .init(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD, targetFD: matching)) + .init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching)) case .first: - .init(core: .cancelFD(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD, targetFD: matching)) + .init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_ANY | SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching)) } } @@ -357,9 +365,9 @@ extension IORing.Request { ) -> IORing.Request { switch matchAll { case .all: - .init(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) + .init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) case .first: - .init(core: .cancelFDSlot(flags: IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) + .init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_ANY | SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) } } From 2f6c4e0f03638880fe92081a52b0bca07f295bf4 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 16:14:36 +0000 Subject: [PATCH 092/102] Add support for non-IORING_FEAT_SINGLE_MMAP kernels --- Sources/System/IORing.swift | 123 ++++++++++++++++++++++++++---------- 1 file changed, 89 insertions(+), 34 deletions(-) diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index 6a281a0..ed451c3 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -179,7 +179,7 @@ internal func _getSubmissionEntry( private func setUpRing( queueDepth: UInt32, flags: IORing.SetupFlags ) throws(Errno) -> - (params: io_uring_params, ringDescriptor: Int32, ringPtr: UnsafeMutableRawPointer, ringSize: Int, sqes: UnsafeMutableRawPointer) { + (params: io_uring_params, ringDescriptor: Int32, ringPtr: UnsafeMutableRawPointer?, ringSize: Int, submissionRingPtr: UnsafeMutableRawPointer?, submissionRingSize: Int, completionRingPtr: UnsafeMutableRawPointer?, completionRingSize: Int, sqes: UnsafeMutableRawPointer) { var params = io_uring_params() params.flags = flags.rawValue @@ -196,8 +196,7 @@ private func setUpRing( throw err } - if params.features & IORING_FEAT_SINGLE_MMAP == 0 - || params.features & IORING_FEAT_NODROP == 0 + if params.features & IORING_FEAT_NODROP == 0 { close(ringDescriptor) throw Errno.invalidArgument @@ -213,20 +212,55 @@ private func setUpRing( let ringSize = Int(max(submitRingSize, completionRingSize)) - let ringPtr: UnsafeMutableRawPointer! = mmap( - /* addr: */ nil, - /* len: */ ringSize, - /* prot: */ PROT_READ | PROT_WRITE, - /* flags: */ MAP_SHARED | MAP_POPULATE, - /* fd: */ ringDescriptor, - /* offset: */ __off_t(IORING_OFF_SQ_RING) - ) + var ringPtr: UnsafeMutableRawPointer! + var sqPtr: UnsafeMutableRawPointer! + var cqPtr: UnsafeMutableRawPointer! - if ringPtr == MAP_FAILED { - let errno = Errno.current - perror("mmap") - close(ringDescriptor) - throw errno + if params.features & IORING_FEAT_SINGLE_MMAP != 0{ + ringPtr = mmap( + /* addr: */ nil, + /* len: */ ringSize, + /* prot: */ PROT_READ | PROT_WRITE, + /* flags: */ MAP_SHARED | MAP_POPULATE, + /* fd: */ ringDescriptor, + /* offset: */ __off_t(IORING_OFF_SQ_RING) + ) + + if ringPtr == MAP_FAILED { + let errno = Errno.current + close(ringDescriptor) + throw errno + } + } else { + sqPtr = mmap( + /* addr: */ nil, + /* len: */ Int(submitRingSize), + /* prot: */ PROT_READ | PROT_WRITE, + /* flags: */ MAP_SHARED | MAP_POPULATE, + /* fd: */ ringDescriptor, + /* offset: */ __off_t(IORING_OFF_SQ_RING) + ) + + if sqPtr == MAP_FAILED { + let errno = Errno.current + close(ringDescriptor) + throw errno + } + + cqPtr = mmap( + /* addr: */ nil, + /* len: */ Int(completionRingSize), + /* prot: */ PROT_READ | PROT_WRITE, + /* flags: */ MAP_SHARED | MAP_POPULATE, + /* fd: */ ringDescriptor, + /* offset: */ __off_t(IORING_OFF_CQ_RING) + ) + + if cqPtr == MAP_FAILED { + let errno: Errno = Errno.current + close(ringDescriptor) + throw errno + } } // map the submission queue @@ -241,13 +275,21 @@ private func setUpRing( if sqes == MAP_FAILED { let errno = Errno.current - perror("mmap") - munmap(ringPtr, ringSize) + if ringPtr != nil { + munmap(ringPtr, ringSize) + } else { + if sqPtr != nil { + munmap(sqPtr, Int(submitRingSize)) + } + if cqPtr != nil { + munmap(cqPtr, Int(completionRingSize)) + } + } close(ringDescriptor) throw errno } - return (params: params, ringDescriptor: ringDescriptor, ringPtr: ringPtr!, ringSize: ringSize, sqes: sqes!) + return (params: params, ringDescriptor: ringDescriptor, ringPtr: ringPtr, ringSize: ringSize, submissionRingPtr: sqPtr, submissionRingSize: Int(submitRingSize), completionRingPtr: cqPtr, completionRingSize: Int(completionRingSize), sqes: sqes!) } ///IORing provides facilities for @@ -267,9 +309,13 @@ public struct IORing: ~Copyable { @usableFromInline let submissionQueueEntries: UnsafeMutableBufferPointer - // kept around for unmap / cleanup + // kept around for unmap / cleanup. TODO: we can save a few words of memory by figuring out how to handle cleanup for non-IORING_FEAT_SINGLE_MMAP better let ringSize: Int - let ringPtr: UnsafeMutableRawPointer + let ringPtr: UnsafeMutableRawPointer? + let submissionRingSize: Int + let submissionRingPtr: UnsafeMutableRawPointer? + let completionRingSize: Int + let completionRingPtr: UnsafeMutableRawPointer? @usableFromInline var _registeredFiles: [UInt32] @usableFromInline var _registeredBuffers: [iovec] @@ -320,7 +366,7 @@ public struct IORing: ~Copyable { /// Initializes an IORing with enough space for `queueDepth` prepared requests and completed operations public init(queueDepth: UInt32, flags: SetupFlags = []) throws(Errno) { - let (params, tmpRingDescriptor, tmpRingPtr, tmpRingSize, sqes) = try setUpRing(queueDepth: queueDepth, flags: flags) + let (params, tmpRingDescriptor, tmpRingPtr, tmpRingSize, tmpSQPtr, tmpSQSize, tmpCQPtr, tmpCQSize, sqes) = try setUpRing(queueDepth: queueDepth, flags: flags) // All throws need to be before initializing ivars here to avoid // "error: conditional initialization or destruction of noncopyable types is not supported; // this variable must be consistently in an initialized or uninitialized state through every code path" @@ -328,29 +374,33 @@ public struct IORing: ~Copyable { ringDescriptor = tmpRingDescriptor ringPtr = tmpRingPtr ringSize = tmpRingSize + submissionRingPtr = tmpSQPtr + submissionRingSize = tmpSQSize + completionRingPtr = tmpCQPtr + completionRingSize = tmpCQSize _registeredFiles = [] _registeredBuffers = [] submissionRing = SQRing( kernelHead: UnsafePointer>( - ringPtr.advanced(by: params.sq_off.head) + (ringPtr ?? submissionRingPtr!).advanced(by: params.sq_off.head) .assumingMemoryBound(to: Atomic.self) ), kernelTail: UnsafePointer>( - ringPtr.advanced(by: params.sq_off.tail) + (ringPtr ?? submissionRingPtr!).advanced(by: params.sq_off.tail) .assumingMemoryBound(to: Atomic.self) ), userTail: 0, // no requests yet - ringMask: ringPtr.advanced(by: params.sq_off.ring_mask) + ringMask: (ringPtr ?? submissionRingPtr!).advanced(by: params.sq_off.ring_mask) .assumingMemoryBound(to: UInt32.self).pointee, flags: UnsafePointer>( - ringPtr.advanced(by: params.sq_off.flags) + (ringPtr ?? submissionRingPtr!).advanced(by: params.sq_off.flags) .assumingMemoryBound(to: Atomic.self) ), array: UnsafeMutableBufferPointer( - start: ringPtr.advanced(by: params.sq_off.array) + start: (ringPtr ?? submissionRingPtr!).advanced(by: params.sq_off.array) .assumingMemoryBound(to: UInt32.self), count: Int( - ringPtr.advanced(by: params.sq_off.ring_entries) + (ringPtr ?? submissionRingPtr!).advanced(by: params.sq_off.ring_entries) .assumingMemoryBound(to: UInt32.self).pointee) ) ) @@ -367,20 +417,20 @@ public struct IORing: ~Copyable { completionRing = CQRing( kernelHead: UnsafePointer>( - ringPtr.advanced(by: params.cq_off.head) + (ringPtr ?? completionRingPtr!).advanced(by: params.cq_off.head) .assumingMemoryBound(to: Atomic.self) ), kernelTail: UnsafePointer>( - ringPtr.advanced(by: params.cq_off.tail) + (ringPtr ?? completionRingPtr!).advanced(by: params.cq_off.tail) .assumingMemoryBound(to: Atomic.self) ), - ringMask: ringPtr.advanced(by: params.cq_off.ring_mask) + ringMask: (ringPtr ?? completionRingPtr!).advanced(by: params.cq_off.ring_mask) .assumingMemoryBound(to: UInt32.self).pointee, cqes: UnsafeBufferPointer( - start: ringPtr.advanced(by: params.cq_off.cqes) + start: (ringPtr ?? completionRingPtr!).advanced(by: params.cq_off.cqes) .assumingMemoryBound(to: io_uring_cqe.self), count: Int( - ringPtr.advanced(by: params.cq_off.ring_entries) + (ringPtr ?? completionRingPtr!).advanced(by: params.cq_off.ring_entries) .assumingMemoryBound(to: UInt32.self).pointee) ) ) @@ -799,7 +849,12 @@ public struct IORing: ~Copyable { } deinit { - munmap(ringPtr, ringSize) + if let ringPtr { + munmap(ringPtr, ringSize) + } else if let submissionRingPtr, let completionRingPtr { + munmap(submissionRingPtr, submissionRingSize) + munmap(completionRingPtr, completionRingSize) + } munmap( UnsafeMutableRawPointer(submissionQueueEntries.baseAddress!), submissionQueueEntries.count * MemoryLayout.size From 779c9ac6285b8d8fd389e6496decf5ee3a480733 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 16:50:58 +0000 Subject: [PATCH 093/102] Fix misuse of _CANCEL_ANY, and add support for non-redicated cancellation --- Sources/System/IORequest.swift | 28 +++++++++++++++++++++++----- Sources/System/IORing.swift | 1 + 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/Sources/System/IORequest.swift b/Sources/System/IORequest.swift index b7a0e1a..275d27b 100644 --- a/Sources/System/IORequest.swift +++ b/Sources/System/IORequest.swift @@ -84,6 +84,9 @@ internal enum IORequestCore { context: UInt64 = 0 ) case cancel( + flags:UInt32 + ) + case cancelContext( flags: UInt32, targetContext: UInt64 ) @@ -95,6 +98,7 @@ internal enum IORequestCore { flags: UInt32, target: IORing.RegisteredFile ) + } @inline(__always) @inlinable @@ -341,9 +345,9 @@ extension IORing.Request { ) -> IORing.Request { switch matchAll { case .all: - .init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) + .init(core: .cancelContext(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) case .first: - .init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ANY | SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) + .init(core: .cancelContext(flags: SWIFT_IORING_ASYNC_CANCEL_USERDATA, targetContext: matchingContext)) } } @@ -355,7 +359,7 @@ extension IORing.Request { case .all: .init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching)) case .first: - .init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_ANY | SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching)) + .init(core: .cancelFD(flags: SWIFT_IORING_ASYNC_CANCEL_FD, targetFD: matching)) } } @@ -367,7 +371,18 @@ extension IORing.Request { case .all: .init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_ALL | SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) case .first: - .init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_ANY | SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) + .init(core: .cancelFDSlot(flags: SWIFT_IORING_ASYNC_CANCEL_FD_FIXED, target: matching)) + } + } + + @inlinable public static func cancel( + _ matchAll: CancellationMatch, + ) -> IORing.Request { + switch matchAll { + case .all: + .init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ALL)) + case .first: + .init(core: .cancel(flags: SWIFT_IORING_ASYNC_CANCEL_ANY)) } } @@ -457,7 +472,7 @@ extension IORing.Request { ) request.path = path request.rawValue.user_data = context - case .cancel(let flags, let targetContext): + case .cancelContext(let flags, let targetContext): request.operation = .asyncCancel request.cancel_flags = flags request.addr = targetContext @@ -469,6 +484,9 @@ extension IORing.Request { request.operation = .asyncCancel request.cancel_flags = flags request.rawValue.fd = Int32(target.index) + case .cancel(let flags): + request.operation = .asyncCancel + request.cancel_flags = flags } return request diff --git a/Sources/System/IORing.swift b/Sources/System/IORing.swift index ed451c3..604f3fd 100644 --- a/Sources/System/IORing.swift +++ b/Sources/System/IORing.swift @@ -378,6 +378,7 @@ public struct IORing: ~Copyable { submissionRingSize = tmpSQSize completionRingPtr = tmpCQPtr completionRingSize = tmpCQSize + _registeredFiles = [] _registeredBuffers = [] submissionRing = SQRing( From 7fc787e6ba4ba3a68b43562dcde165560e7b9855 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 17:00:32 +0000 Subject: [PATCH 094/102] Move IORing files to a subdirectory --- Sources/System/{ => IORing}/IOCompletion.swift | 0 Sources/System/{ => IORing}/IORequest.swift | 0 Sources/System/{ => IORing}/IORing.swift | 0 Sources/System/{ => IORing}/RawIORequest.swift | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename Sources/System/{ => IORing}/IOCompletion.swift (100%) rename Sources/System/{ => IORing}/IORequest.swift (100%) rename Sources/System/{ => IORing}/IORing.swift (100%) rename Sources/System/{ => IORing}/RawIORequest.swift (100%) diff --git a/Sources/System/IOCompletion.swift b/Sources/System/IORing/IOCompletion.swift similarity index 100% rename from Sources/System/IOCompletion.swift rename to Sources/System/IORing/IOCompletion.swift diff --git a/Sources/System/IORequest.swift b/Sources/System/IORing/IORequest.swift similarity index 100% rename from Sources/System/IORequest.swift rename to Sources/System/IORing/IORequest.swift diff --git a/Sources/System/IORing.swift b/Sources/System/IORing/IORing.swift similarity index 100% rename from Sources/System/IORing.swift rename to Sources/System/IORing/IORing.swift diff --git a/Sources/System/RawIORequest.swift b/Sources/System/IORing/RawIORequest.swift similarity index 100% rename from Sources/System/RawIORequest.swift rename to Sources/System/IORing/RawIORequest.swift From f7c05e1fb846fb4748f53d015256f85c8819a7ff Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 18:53:55 +0000 Subject: [PATCH 095/102] Combine platform conditionals --- Sources/System/IORing/IOCompletion.swift | 4 +--- Sources/System/IORing/IORequest.swift | 4 +--- Sources/System/IORing/IORing.swift | 4 +--- Sources/System/IORing/RawIORequest.swift | 4 +--- 4 files changed, 4 insertions(+), 12 deletions(-) diff --git a/Sources/System/IORing/IOCompletion.swift b/Sources/System/IORing/IOCompletion.swift index 65616e2..375abae 100644 --- a/Sources/System/IORing/IOCompletion.swift +++ b/Sources/System/IORing/IOCompletion.swift @@ -1,5 +1,4 @@ -#if os(Linux) -#if compiler(>=6.2) +#if os(Linux) && compiler(>=6.2) import CSystem public extension IORing { @@ -67,4 +66,3 @@ public extension IORing.Completion { } } #endif -#endif diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 275d27b..f7130f2 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -1,5 +1,4 @@ -#if os(Linux) -#if compiler(>=6.2) +#if os(Linux) && compiler(>=6.2) import CSystem @usableFromInline @@ -493,4 +492,3 @@ extension IORing.Request { } } #endif -#endif diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 604f3fd..3b49d5c 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -1,5 +1,4 @@ -#if os(Linux) -#if compiler(>=6.2) +#if os(Linux) && compiler(>=6.2) import CSystem // needed for mmap @@ -883,4 +882,3 @@ extension IORing.RegisteredBuffer { } } #endif -#endif \ No newline at end of file diff --git a/Sources/System/IORing/RawIORequest.swift b/Sources/System/IORing/RawIORequest.swift index b22c1c7..2fc8a99 100644 --- a/Sources/System/IORing/RawIORequest.swift +++ b/Sources/System/IORing/RawIORequest.swift @@ -1,5 +1,4 @@ -#if os(Linux) -#if compiler(>=6.2) +#if os(Linux) && compiler(>=6.2) import CSystem @@ -200,4 +199,3 @@ extension RawIORequest { } } #endif -#endif \ No newline at end of file From a56bcda3c1bd85131f1e36d90ff11ffcdae900e8 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 19:07:04 +0000 Subject: [PATCH 096/102] Un-combine conditionals but flip their order. This should fix the Windows build with older compilers --- Sources/System/IORing/IOCompletion.swift | 5 ++++- Sources/System/IORing/IORequest.swift | 5 ++++- Sources/System/IORing/IORing.swift | 4 +++- Sources/System/IORing/RawIORequest.swift | 4 +++- Tests/SystemTests/IORequestTests.swift | 2 +- Tests/SystemTests/IORingTests.swift | 2 +- 6 files changed, 16 insertions(+), 6 deletions(-) diff --git a/Sources/System/IORing/IOCompletion.swift b/Sources/System/IORing/IOCompletion.swift index 375abae..ce23444 100644 --- a/Sources/System/IORing/IOCompletion.swift +++ b/Sources/System/IORing/IOCompletion.swift @@ -1,4 +1,6 @@ -#if os(Linux) && compiler(>=6.2) +#if compiler(>=6.2) +#if os(Linux) + import CSystem public extension IORing { @@ -66,3 +68,4 @@ public extension IORing.Completion { } } #endif +#endif \ No newline at end of file diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index f7130f2..5ab5ac9 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -1,4 +1,6 @@ -#if os(Linux) && compiler(>=6.2) +#if compiler(>=6.2) +#if os(Linux) + import CSystem @usableFromInline @@ -492,3 +494,4 @@ extension IORing.Request { } } #endif +#endif \ No newline at end of file diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index 3b49d5c..c0fe005 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -1,4 +1,5 @@ -#if os(Linux) && compiler(>=6.2) +#if compiler(>=6.2) +#if os(Linux) import CSystem // needed for mmap @@ -882,3 +883,4 @@ extension IORing.RegisteredBuffer { } } #endif +#endif \ No newline at end of file diff --git a/Sources/System/IORing/RawIORequest.swift b/Sources/System/IORing/RawIORequest.swift index 2fc8a99..332cd91 100644 --- a/Sources/System/IORing/RawIORequest.swift +++ b/Sources/System/IORing/RawIORequest.swift @@ -1,4 +1,5 @@ -#if os(Linux) && compiler(>=6.2) +#if compiler(>=6.2) +#if os(Linux) import CSystem @@ -199,3 +200,4 @@ extension RawIORequest { } } #endif +#endif \ No newline at end of file diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 53a0a82..9a80968 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -1,5 +1,5 @@ -#if os(Linux) #if compiler(>=6.2) +#if os(Linux) import XCTest diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 7fb899f..3a2473c 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -1,5 +1,5 @@ -#if os(Linux) #if compiler(>=6.2) +#if os(Linux) import XCTest import CSystem //for eventfd From 9a046498d07bf9e3c1f087b51373e603a51d2024 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 19:23:24 +0000 Subject: [PATCH 097/102] Try adding newlines to the ends of files to work around a compiler bug --- Sources/System/IORing/IOCompletion.swift | 2 +- Sources/System/IORing/IORequest.swift | 2 +- Sources/System/IORing/IORing.swift | 2 +- Sources/System/IORing/RawIORequest.swift | 2 +- Tests/SystemTests/IORequestTests.swift | 2 +- Tests/SystemTests/IORingTests.swift | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Sources/System/IORing/IOCompletion.swift b/Sources/System/IORing/IOCompletion.swift index ce23444..ea99cc7 100644 --- a/Sources/System/IORing/IOCompletion.swift +++ b/Sources/System/IORing/IOCompletion.swift @@ -68,4 +68,4 @@ public extension IORing.Completion { } } #endif -#endif \ No newline at end of file +#endif diff --git a/Sources/System/IORing/IORequest.swift b/Sources/System/IORing/IORequest.swift index 5ab5ac9..cc91e47 100644 --- a/Sources/System/IORing/IORequest.swift +++ b/Sources/System/IORing/IORequest.swift @@ -494,4 +494,4 @@ extension IORing.Request { } } #endif -#endif \ No newline at end of file +#endif diff --git a/Sources/System/IORing/IORing.swift b/Sources/System/IORing/IORing.swift index c0fe005..c676f78 100644 --- a/Sources/System/IORing/IORing.swift +++ b/Sources/System/IORing/IORing.swift @@ -883,4 +883,4 @@ extension IORing.RegisteredBuffer { } } #endif -#endif \ No newline at end of file +#endif diff --git a/Sources/System/IORing/RawIORequest.swift b/Sources/System/IORing/RawIORequest.swift index 332cd91..dea378f 100644 --- a/Sources/System/IORing/RawIORequest.swift +++ b/Sources/System/IORing/RawIORequest.swift @@ -200,4 +200,4 @@ extension RawIORequest { } } #endif -#endif \ No newline at end of file +#endif diff --git a/Tests/SystemTests/IORequestTests.swift b/Tests/SystemTests/IORequestTests.swift index 9a80968..5072823 100644 --- a/Tests/SystemTests/IORequestTests.swift +++ b/Tests/SystemTests/IORequestTests.swift @@ -31,4 +31,4 @@ final class IORequestTests: XCTestCase { } } #endif -#endif \ No newline at end of file +#endif diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 3a2473c..63e4e78 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -110,4 +110,4 @@ final class IORingTests: XCTestCase { } } #endif -#endif \ No newline at end of file +#endif From b93169b8e28b44664dc7ff93ec79fbca4f7e9e35 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 20:37:23 +0000 Subject: [PATCH 098/102] Work around windows bugs harder --- Package.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 48b348a..cb19f15 100644 --- a/Package.swift +++ b/Package.swift @@ -25,6 +25,12 @@ let swiftSettings: [SwiftSetting] = [ .enableExperimentalFeature("Lifetimes"), ] +#if os(Linux) +let filesToExclude = ["CMakeLists.txt"] +#else +let filesToExclude = ["CMakeLists.txt", "Sources/IORing/", "Tests/SystemTests/IORequestTests.swift", "Tests/SystemTests/IORingTests.swift"] +#endif + let package = Package( name: "swift-system", products: [ @@ -41,7 +47,7 @@ let package = Package( name: "SystemPackage", dependencies: ["CSystem"], path: "Sources/System", - exclude: ["CMakeLists.txt"], + exclude: filesToExclude, cSettings: cSettings, swiftSettings: swiftSettings), .testTarget( From 52d9c99a9476ad19e57b55b94803a8a3534aa8da Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 13:42:49 -0700 Subject: [PATCH 099/102] Fix excludes --- Package.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index cb19f15..a5013fe 100644 --- a/Package.swift +++ b/Package.swift @@ -28,7 +28,13 @@ let swiftSettings: [SwiftSetting] = [ #if os(Linux) let filesToExclude = ["CMakeLists.txt"] #else -let filesToExclude = ["CMakeLists.txt", "Sources/IORing/", "Tests/SystemTests/IORequestTests.swift", "Tests/SystemTests/IORingTests.swift"] +let filesToExclude = ["CMakeLists.txt", "IORing"] +#endif + +#if os(Linux) +let testsToExclude = [] +#else +let testsToExclude = ["IORequestTests.swift", "IORingTests.swift"] #endif let package = Package( @@ -53,6 +59,7 @@ let package = Package( .testTarget( name: "SystemTests", dependencies: ["SystemPackage"], + exclude: testsToExclude, cSettings: cSettings, swiftSettings: swiftSettings), ]) \ No newline at end of file From 33b58a81106df8b6c9fa61caf2313aec2a936f1a Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 13:44:46 -0700 Subject: [PATCH 100/102] Fix excludes harder --- Package.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index a5013fe..9cbfc6e 100644 --- a/Package.swift +++ b/Package.swift @@ -32,7 +32,7 @@ let filesToExclude = ["CMakeLists.txt", "IORing"] #endif #if os(Linux) -let testsToExclude = [] +let testsToExclude:[String] = [] #else let testsToExclude = ["IORequestTests.swift", "IORingTests.swift"] #endif @@ -62,4 +62,4 @@ let package = Package( exclude: testsToExclude, cSettings: cSettings, swiftSettings: swiftSettings), - ]) \ No newline at end of file + ]) From a66176f51829683d280decf7044683364ce5ceb4 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 22:42:35 +0000 Subject: [PATCH 101/102] Only run IORing tests if io_uring support is enabled --- Tests/SystemTests/IORingTests.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 63e4e78..5095f07 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -10,12 +10,25 @@ import SystemPackage import System #endif +func uringEnabled() throws -> Bool { + let procPath = FilePath("/proc/sys/kernel/io_uring_disabled") + let fd = try FileDescriptor.open(procPath, .readOnly) + let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 0) + _ = try fd.read(into: buffer) + if buffer.load(fromByteOffset: 0, as: Int.self) == 0 { + return true + } + return false +} + final class IORingTests: XCTestCase { func testInit() throws { + guard try uringEnabled() else { return } _ = try IORing(queueDepth: 32, flags: []) } func testNop() throws { + guard try uringEnabled() else { return } var ring = try IORing(queueDepth: 32, flags: []) _ = try ring.submit(linkedRequests: .nop()) let completion = try ring.blockingConsumeCompletion() @@ -51,6 +64,7 @@ final class IORingTests: XCTestCase { } func testUndersizedSubmissionQueue() throws { + guard try uringEnabled() else { return } var ring: IORing = try IORing(queueDepth: 1) let enqueued = ring.prepare(linkedRequests: .nop(), .nop()) XCTAssertFalse(enqueued) @@ -58,6 +72,7 @@ final class IORingTests: XCTestCase { // Exercises opening, reading, closing, registered files, registered buffers, and eventfd func testOpenReadAndWriteFixedFile() throws { + guard try uringEnabled() else { return } let (parent, path) = try makeHelloWorldFile() let rawBuffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 13, alignment: 16) var ring = try setupTestRing(depth: 6, fileSlots: 1, buffers: [rawBuffer]) From 08ed962064a04dd002c2175416e0098c180a33e0 Mon Sep 17 00:00:00 2001 From: David Smith Date: Fri, 11 Jul 2025 23:05:26 +0000 Subject: [PATCH 102/102] Don't abort the test if we can't open /proc/sys/kernel/io_uring_disabled --- Tests/SystemTests/IORingTests.swift | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Tests/SystemTests/IORingTests.swift b/Tests/SystemTests/IORingTests.swift index 5095f07..8e0e8fa 100644 --- a/Tests/SystemTests/IORingTests.swift +++ b/Tests/SystemTests/IORingTests.swift @@ -11,12 +11,16 @@ import System #endif func uringEnabled() throws -> Bool { - let procPath = FilePath("/proc/sys/kernel/io_uring_disabled") - let fd = try FileDescriptor.open(procPath, .readOnly) - let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 0) - _ = try fd.read(into: buffer) - if buffer.load(fromByteOffset: 0, as: Int.self) == 0 { - return true + do { + let procPath = FilePath("/proc/sys/kernel/io_uring_disabled") + let fd = try FileDescriptor.open(procPath, .readOnly) + let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 1024, alignment: 0) + _ = try fd.read(into: buffer) + if buffer.load(fromByteOffset: 0, as: Int.self) == 0 { + return true + } + } catch (_) { + return false } return false }