Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft changes to the io_uring prototype #208

Draft
wants to merge 49 commits into
base: main
Choose a base branch
from
Draft
Changes from 1 commit
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
15794f5
ioring pitch: first steps
oxy Jul 19, 2023
6338029
stage 2: IORequest enum
oxy Aug 1, 2023
996e940
initial AsyncFileDescriptor work
oxy Aug 1, 2023
1f821a8
AsyncSequence draft implementation
oxy Aug 8, 2023
0762f57
migrate CSystem to systemLibrary
oxy Aug 10, 2023
d099546
fix access control
oxy Aug 11, 2023
b584504
fix off-by-one in IORequest.openat
oxy Aug 11, 2023
b596783
implement closing
oxy Aug 11, 2023
6b4084c
introduce IORing unit tests
oxy Aug 11, 2023
baab9b2
Starting to move to noncopyable structs, and away from swift-atomics
Catfish-Man Oct 24, 2024
6029936
One more noncopyable struct
Catfish-Man Oct 24, 2024
10c070a
WIP, more ~Copyable adoption
Catfish-Man Oct 28, 2024
32966f9
It builds again! With some horrible hacks
Catfish-Man Oct 28, 2024
822e481
Adopt isolation parameters
Catfish-Man Oct 28, 2024
fcb0b69
Merge branch 'main' into david/ioring
Catfish-Man Oct 29, 2024
6f793cf
Merge branch 'main' into david/ioring
Catfish-Man Oct 29, 2024
a9f92a6
Delete stray Package.resolved changes
Catfish-Man Oct 29, 2024
1a3e37d
Fix mismerge
Catfish-Man Oct 29, 2024
f369347
Fix mismerge
Catfish-Man Oct 29, 2024
ef94a37
Refactoring, and give up on resources being noncopyable structs
Catfish-Man Dec 5, 2024
7ea32ae
More refactoring, and working timeout support on ManagedIORing
Catfish-Man Dec 11, 2024
55fd6e7
Add support for timeout-on-wait to IORing, don't have tests yet
Catfish-Man Dec 12, 2024
e5fdf9e
Remove managed abstractions for now
Catfish-Man Feb 6, 2025
fdbceca
Eliminate internal locking and add multiple consume support
Catfish-Man Feb 6, 2025
7107a57
Fix import visibility
Catfish-Man Feb 11, 2025
02481e0
More import fixes
Catfish-Man Feb 11, 2025
bb03f0f
Redesign registered resources API
Catfish-Man Feb 11, 2025
a396967
More registration tweaks
Catfish-Man Feb 11, 2025
d4ca412
Some renaming, and implement linked requests
Catfish-Man Feb 11, 2025
5bfed03
Switch to static methods for constructing requests
Catfish-Man Feb 11, 2025
74366c3
Improve submit API
Catfish-Man Feb 12, 2025
7f6e673
Adjust registered resources API
Catfish-Man Feb 12, 2025
0c6ef16
Fix type
Catfish-Man Feb 12, 2025
a22e5f6
Add a version of registerBuffers that isn't varargs
Catfish-Man Feb 13, 2025
6983196
Add unlinkAt support
Catfish-Man Feb 13, 2025
5ba1377
Dubious approach to this, but I want to try it out a bit
Catfish-Man Feb 13, 2025
0064649
Turn on single issuer as an experiment
Catfish-Man Feb 14, 2025
901f4c8
Revert "Turn on single issuer as an experiment"
Catfish-Man Feb 14, 2025
283e8d6
Reapply "Turn on single issuer as an experiment"
Catfish-Man Feb 14, 2025
d895f2a
Revert "Reapply "Turn on single issuer as an experiment""
Catfish-Man Feb 14, 2025
f3b8cc4
Actually consume events we waited for
Catfish-Man Feb 28, 2025
d338de1
Only get one completion if we asked for one completion
Catfish-Man Feb 28, 2025
5e24673
Switch from unsafe pointers to FilePaths, using hacks
Catfish-Man Mar 3, 2025
49dd797
Add a combined "submit and consume" operation
Catfish-Man Mar 3, 2025
91155fd
Plumb error handling through completion consumers
Catfish-Man Mar 3, 2025
9ad16c0
Plumb through userData
Catfish-Man Mar 3, 2025
880ec90
Add a pointer convenience for getting the user data
Catfish-Man Mar 3, 2025
48455a9
Fix plumbing
Catfish-Man Mar 3, 2025
72c316b
Make completions noncopyable again
Catfish-Man Mar 3, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
It builds again! With some horrible hacks
Catfish-Man committed Oct 28, 2024
commit 32966f975d8d4285059c29eaccd1cee46c56b84f
117 changes: 75 additions & 42 deletions Sources/System/AsyncFileDescriptor.swift
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
@_implementationOnly import CSystem


public final class AsyncFileDescriptor {
public struct AsyncFileDescriptor: ~Copyable {
@usableFromInline var open: Bool = true
@usableFromInline let fileSlot: IORingFileSlot
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally this should be a borrow of the file slot, but that's hard to express right now

@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()
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a hack, this should also be an actual 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) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

more "should be a borrow"

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,67 +57,99 @@ 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()
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

more hacks

let res = await ring.submitAndWait(
.readUnregistered(
file: .registered(file),
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 or error? TBD
@inlinable @inline(__always) @_unsafeInheritExecutor
public func read(
into buffer: borrowing IORingBuffer, //TODO: should be inout?
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think inout is right here. We want to loan the buffer to the kernel to read into basically… right?

atAbsoluteOffset offset: UInt64 = UInt64.max
) async throws -> UInt32 {
let res = await ring.submitAndWait(
.read(
file: .registered(self.fileSlot.borrow()),
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

borrow hacks

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?
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we express this? Need to go look over the relevant S-E proposals again

// deinit {
// if self.open {
// TODO: close or error? TBD
// }
// }
}

extension AsyncFileDescriptor: AsyncSequence {
public class AsyncFileDescriptorSequence: AsyncSequence {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is only here because ~Copyable structs can't conform to AsyncSequence rn

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
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

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: 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? {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For some reason changing this to take an isolation parameter makes it not compile

if _fastPath(currentByte != lastByte) {
// SAFETY: both pointers should be non-nil if they're not equal
let byte = currentByte.unsafelyUnwrapped.load(as: UInt8.self)
1 change: 1 addition & 0 deletions Sources/System/IOCompletion.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
@_implementationOnly import CSystem

//TODO: should be ~Copyable, but requires UnsafeContinuation add ~Copyable support
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another workaround for missing features

public struct IOCompletion {
let rawValue: io_uring_cqe
}
58 changes: 27 additions & 31 deletions Sources/System/IORequest.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import struct CSystem.io_uring_sqe

public enum IORequest: ~Copyable {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unclear to me how we want to structure this. An enum is… kinda elegant, but I haven't figured out how to express "this enum's associated values are all borrows scoped to some other thing's lifetime" yet.

case nop // nothing here
case nop // nothing here
case openat(
atDirectory: FileDescriptor,
path: UnsafePointer<CChar>,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

path should probably be a FilePath?

@@ -12,21 +12,26 @@ public enum IORequest: ~Copyable {
)
case read(
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the registered/unregistered cases used to be combined, I split 'em up to make the borrows work. Unclear that that's what we want long term

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 {
22 changes: 15 additions & 7 deletions Sources/System/IORing.swift
Original file line number Diff line number Diff line change
@@ -51,7 +51,7 @@ internal class ResourceManager<T>: @unchecked Sendable {

struct Resources {
let resourceList: UnsafeMutableBufferPointer<T>
var freeList: [Int]
var freeList: [Int] //TODO: bitvector?
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I bet we can be really efficient here if it matters

}

let mutex: Mutex<Resources>
@@ -90,23 +90,33 @@ public struct IOResource<T>: ~Copyable {
@usableFromInline let resource: T
@usableFromInline let index: Int
let manager: ResourceManager<T>
let isBorrow: Bool //TODO: this is a workaround for lifetime issues and should be removed

internal init(
resource: T,
index: Int,
manager: ResourceManager<T>
manager: ResourceManager<T>,
isBorrow: Bool = false
) {
self.resource = resource
self.index = index
self.manager = manager
self.isBorrow = isBorrow
}

func withResource() {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?


}

//TODO: this is a workaround for lifetime issues and should be removed
@usableFromInline func borrow() -> IOResource<T> {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is awful, but it unblocks me for now

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 {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this need to be Sendable? I found it surprising that SQRing and CQRing are protected by Mutex. If I was writing a single threaded program, I wouldn't want that overhead.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, we decided to change that

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)
}
}

4 changes: 2 additions & 2 deletions Sources/System/ManagedIORing.swift
Original file line number Diff line number Diff line change
@@ -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()
}

}
2 changes: 1 addition & 1 deletion Sources/System/RawIORequest.swift
Original file line number Diff line number Diff line change
@@ -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() {
2 changes: 1 addition & 1 deletion Tests/SystemTests/AsyncFileDescriptorTests.swift
Original file line number Diff line number Diff line change
@@ -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")
}
}
4 changes: 2 additions & 2 deletions Tests/SystemTests/IORequestTests.swift
Original file line number Diff line number Diff line change
@@ -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] = {