From 6338029b74b84b79795a0cc24bcc189883ec083d Mon Sep 17 00:00:00 2001 From: Lucy Satheesan Date: Mon, 31 Jul 2023 22:28:43 -0700 Subject: [PATCH] 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