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