File: SelectorUring.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (361 lines) | stat: -rw-r--r-- 17,654 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

#if SWIFTNIO_USE_IO_URING
#if os(Linux) || os(Android)

/// Represents the `poll` filters/events we might use from io_uring:
///
///  - `hangup` corresponds to `POLLHUP`
///  - `readHangup` corresponds to `POLLRDHUP`
///  - `input` corresponds to `POLLIN`
///  - `output` corresponds to `POLLOUT`
///  - `error` corresponds to `POLLERR`
private struct URingFilterSet: OptionSet, Equatable {
    typealias RawValue = UInt8

    let rawValue: RawValue

    static let _none = URingFilterSet([])
    static let hangup = URingFilterSet(rawValue: 1 << 0)
    static let readHangup = URingFilterSet(rawValue: 1 << 1)
    static let input = URingFilterSet(rawValue: 1 << 2)
    static let output = URingFilterSet(rawValue: 1 << 3)
    static let error = URingFilterSet(rawValue: 1 << 4)

    init(rawValue: RawValue) {
        self.rawValue = rawValue
    }
}

extension URingFilterSet {
    /// Convert NIO's `SelectorEventSet` set to a `URingFilterSet`
    init(selectorEventSet: SelectorEventSet) {
        var thing: URingFilterSet = [.error, .hangup]
        if selectorEventSet.contains(.read) {
            thing.formUnion(.input)
        }
        if selectorEventSet.contains(.write) {
            thing.formUnion(.output)
        }
        if selectorEventSet.contains(.readEOF) {
            thing.formUnion(.readHangup)
        }
        self = thing
    }
}

extension SelectorEventSet {
    var uringEventSet: UInt32 {
        assert(self != ._none)
        // POLLERR | POLLHUP is always set unconditionally anyway but it's easier to understand if we explicitly ask.
        var filter: UInt32 = URing.POLLERR | URing.POLLHUP
        let uringFilters = URingFilterSet(selectorEventSet: self)
        if uringFilters.contains(.input) {
            filter |= URing.POLLIN
        }
        if uringFilters.contains(.output) {
            filter |= URing.POLLOUT
        }
        if uringFilters.contains(.readHangup) {
            filter |= URing.POLLRDHUP
        }
        assert(filter & URing.POLLHUP != 0) // both of these are reported
        assert(filter & URing.POLLERR != 0) // always and can't be masked.
        return filter
    }

    fileprivate init(uringEvent: UInt32) {
        var selectorEventSet: SelectorEventSet = ._none
        if uringEvent & URing.POLLIN != 0 {
            selectorEventSet.formUnion(.read)
        }
        if uringEvent & URing.POLLOUT != 0 {
            selectorEventSet.formUnion(.write)
        }
        if uringEvent & URing.POLLRDHUP != 0 {
            selectorEventSet.formUnion(.readEOF)
        }
        if uringEvent & URing.POLLHUP != 0 || uringEvent & URing.POLLERR != 0 {
            selectorEventSet.formUnion(.reset)
        }
        self = selectorEventSet
    }
}

extension Selector: _SelectorBackendProtocol {
    internal func _debugPrint(_ s: @autoclosure () -> String) {
        #if SWIFTNIO_IO_URING_DEBUG_SELECTOR
        print("S [\(NIOThread.current)] " + s())
        #endif
    }

    func initialiseState0() throws {
        try ring.io_uring_queue_init()
        self.selectorFD = ring.fd

        // eventfd are always singleshot and re-register each time around
        // as certain use cases of nio seems to generate superfluous wakeups.
        // (at least its tested for that in some of the performance tests
        // e.g. future_whenallsucceed_100k_deferred_off_loop, future_whenallcomplete_100k_deferred_off_loop
        // ) - if using normal ET multishots, we would get 100k events to handle basically.
        // so using single shot for wakeups makes those tests run 30-35% faster approx.

        self.eventFD = try EventFd.eventfd(initval: 0, flags: Int32(EventFd.EFD_CLOEXEC | EventFd.EFD_NONBLOCK))

        ring.io_uring_prep_poll_add(fileDescriptor: self.eventFD,
                                    pollMask: URing.POLLIN,
                                    registrationID:SelectorRegistrationID(rawValue: 0),
                                    multishot:false) // wakeups

        self.lifecycleState = .open
        _debugPrint("URingSelector up and running fd [\(self.selectorFD)] wakeups on event_fd [\(self.eventFD)]")
    }

    func deinitAssertions0() {
        assert(self.eventFD == -1, "self.eventFD == \(self.eventFD) on deinitAssertions0 deinit, forgot close?")
    }

    func register0<S: Selectable>(selectable: S,
                                  fileDescriptor: CInt,
                                  interested: SelectorEventSet,
                                  registrationID: SelectorRegistrationID) throws {
        _debugPrint("register interested \(interested) uringEventSet [\(interested.uringEventSet)] registrationID[\(registrationID)]")
        self.deferredReregistrationsPending = true
        ring.io_uring_prep_poll_add(fileDescriptor: fileDescriptor,
                                    pollMask: interested.uringEventSet,
                                    registrationID: registrationID,
                                    submitNow: !deferReregistrations,
                                    multishot: multishot)
    }

    func reregister0<S: Selectable>(selectable: S,
                                    fileDescriptor: CInt,
                                    oldInterested: SelectorEventSet,
                                    newInterested: SelectorEventSet,
                                    registrationID: SelectorRegistrationID) throws {
        _debugPrint("Re-register old \(oldInterested) new \(newInterested) uringEventSet [\(oldInterested.uringEventSet)] reg.uringEventSet [\(newInterested.uringEventSet)]")

        self.deferredReregistrationsPending = true
        if multishot {
            ring.io_uring_poll_update(fileDescriptor: fileDescriptor,
                                      newPollmask: newInterested.uringEventSet,
                                      oldPollmask: oldInterested.uringEventSet,
                                      registrationID: registrationID,
                                      submitNow: !deferReregistrations,
                                      multishot: true)
        } else {
            ring.io_uring_prep_poll_remove(fileDescriptor: fileDescriptor,
                                           pollMask: oldInterested.uringEventSet,
                                           registrationID: registrationID,
                                           submitNow:!deferReregistrations,
                                           link: true) // next event linked will cancel if this event fails

            ring.io_uring_prep_poll_add(fileDescriptor: fileDescriptor,
                                        pollMask: newInterested.uringEventSet,
                                        registrationID: registrationID,
                                        submitNow: !deferReregistrations,
                                        multishot: false)
        }
    }

    func deregister0<S: Selectable>(selectable: S, fileDescriptor: CInt, oldInterested: SelectorEventSet, registrationID: SelectorRegistrationID) throws {
        _debugPrint("deregister interested \(selectable) reg.interested.uringEventSet [\(oldInterested.uringEventSet)]")

        self.deferredReregistrationsPending = true
        ring.io_uring_prep_poll_remove(fileDescriptor: fileDescriptor,
                                       pollMask: oldInterested.uringEventSet,
                                       registrationID: registrationID,
                                       submitNow:!deferReregistrations)
    }

    private func shouldRefreshPollForEvent(selectorEvent:SelectorEventSet) -> Bool {
        if selectorEvent.contains(.read) {
            // as we don't do exhaustive reads, we need to prod the kernel for
            // new events, would be even better if we knew if we had read all there is
            return true
        }
        // If the event is fully handled, we can return false to avoid reregistration for multishot polls.
        return false
    }

    /// Apply the given `SelectorStrategy` and execute `body` once it's complete (which may produce `SelectorEvent`s to handle).
    ///
    /// - parameters:
    ///     - strategy: The `SelectorStrategy` to apply
    ///     - body: The function to execute for each `SelectorEvent` that was produced.
    func whenReady0(strategy: SelectorStrategy, onLoopBegin loopStart: () -> Void, _ body: (SelectorEvent<R>) throws -> Void) throws -> Void {
        assert(self.myThread == NIOThread.current)
        guard self.lifecycleState == .open else {
            throw IOError(errnoCode: EBADF, reason: "can't call whenReady for selector as it's \(self.lifecycleState).")
        }

        var ready: Int = 0

        // flush reregisteration of pending modifications if needed (nop in SQPOLL mode)
        // basically this elides all reregistrations and deregistrations into a single
        // syscall instead of one for each. Future improvement would be to also merge
        // the pending pollmasks (now each change will be queued, but we could also
        // merge the masks for reregistrations) - but the most important thing is to
        // only trap into the kernel once for the set of changes, so needs to be measured.
        if deferReregistrations && self.deferredReregistrationsPending {
            self.deferredReregistrationsPending = false
            ring.io_uring_flush()
        }

        switch strategy {
        case .now:
            _debugPrint("whenReady.now")
            ready = Int(ring.io_uring_peek_batch_cqe(events: events, maxevents: UInt32(eventsCapacity), multishot:multishot))
        case .blockUntilTimeout(let timeAmount):
            _debugPrint("whenReady.blockUntilTimeout")
            ready = try Int(ring.io_uring_wait_cqe_timeout(events: events, maxevents: UInt32(eventsCapacity), timeout:timeAmount, multishot:multishot))
        case .block:
            _debugPrint("whenReady.block")
            ready = Int(ring.io_uring_peek_batch_cqe(events: events, maxevents: UInt32(eventsCapacity), multishot:multishot)) // first try to consume any existing

            if (ready <= 0)   // otherwise block (only single supported, but we will use batch peek cqe next run around...
            {
                ready = try ring.io_uring_wait_cqe(events: events, maxevents: UInt32(eventsCapacity), multishot:multishot)
            }
        }

        loopStart()

        for i in 0..<ready {
            let event = events[i]

            switch event.fd {
            case self.eventFD: // we don't run these as multishots to avoid tons of events when many wakeups are done
                    _debugPrint("wakeup successful for event.fd [\(event.fd)]")
                    var val = EventFd.eventfd_t()
                    ring.io_uring_prep_poll_add(fileDescriptor: self.eventFD,
                                                pollMask: URing.POLLIN,
                                                registrationID: SelectorRegistrationID(rawValue: 0),
                                                submitNow: false,
                                                multishot: false)
                    do {
                        _ = try EventFd.eventfd_read(fd: self.eventFD, value: &val) // consume wakeup event
                        _debugPrint("read val [\(val)] from event.fd [\(event.fd)]")
                    } catch  {
                    }
            default:
                if let registration = registrations[Int(event.fd)] {

                    _debugPrint("We found a registration for event.fd [\(event.fd)]") // \(registration)

                    // The io_uring backend only has 16 bits available for the registration id
                    guard event.registrationID == UInt16(truncatingIfNeeded:registration.registrationID.rawValue) else {
                        _debugPrint("The event.registrationID [\(event.registrationID)] !=  registration.selectableregistrationID [\(registration.registrationID)], skipping to next event")
                        continue
                    }

                    var selectorEvent = SelectorEventSet(uringEvent: event.pollMask)

                    _debugPrint("selectorEvent [\(selectorEvent)] registration.interested [\(registration.interested)]")

                    // we only want what the user is currently registered for & what we got
                    selectorEvent = selectorEvent.intersection(registration.interested)

                    _debugPrint("intersection [\(selectorEvent)]")

                    if selectorEvent.contains(.readEOF) {
                       _debugPrint("selectorEvent.contains(.readEOF) [\(selectorEvent.contains(.readEOF))]")
                    }

                    if multishot == false { // must be before guard, otherwise lost wake
                        ring.io_uring_prep_poll_add(fileDescriptor: event.fd,
                                                    pollMask: registration.interested.uringEventSet,
                                                    registrationID: registration.registrationID,
                                                    submitNow: false,
                                                    multishot: false)

                        if event.pollCancelled {
                            _debugPrint("Received event.pollCancelled")
                        }
                    }

                    guard selectorEvent != ._none else {
                        _debugPrint("selectorEvent != ._none / [\(selectorEvent)] [\(registration.interested)] [\(SelectorEventSet(uringEvent: event.pollMask))] [\(event.pollMask)] [\(event.fd)]")
                        continue
                    }

                    // This is only needed due to the edge triggered nature of liburing, possibly
                    // we can get away with only updating (force triggering an event if available) for
                    // partial reads (where we currently give up after N iterations)
                    if multishot && self.shouldRefreshPollForEvent(selectorEvent:selectorEvent) { // can be after guard as it is multishot
                        ring.io_uring_poll_update(fileDescriptor: event.fd,
                                                  newPollmask: registration.interested.uringEventSet,
                                                  oldPollmask: registration.interested.uringEventSet,
                                                  registrationID: registration.registrationID,
                                                  submitNow: false)
                    }

                    _debugPrint("running body [\(NIOThread.current)] \(selectorEvent) \(SelectorEventSet(uringEvent: event.pollMask))")

                    try body((SelectorEvent(io: selectorEvent, registration: registration)))

               } else { // remove any polling if we don't have a registration for it
                    _debugPrint("We had no registration for event.fd [\(event.fd)] event.pollMask [\(event.pollMask)] event.registrationID [\(event.registrationID)], it should be deregistered already")
                    if multishot == false {
                        ring.io_uring_prep_poll_remove(fileDescriptor: event.fd,
                                                       pollMask: event.pollMask,
                                                       registrationID: SelectorRegistrationID(rawValue: UInt32(event.registrationID)),
                                                       submitNow: false)
                    }
                }
            }
        }

        self.deferredReregistrationsPending = false // none pending as we will flush here
        ring.io_uring_flush() // flush reregisteration of the polls if needed (nop in SQPOLL mode)
        growEventArrayIfNeeded(ready: ready)
    }

    /// Close the `Selector`.
    ///
    /// After closing the `Selector` it's no longer possible to use it.
    public func close0() throws {
        self.externalSelectorFDLock.withLock {
            // We try! all of the closes because close can only fail in the following ways:
            // - EINTR, which we eat in Posix.close
            // - EIO, which can only happen for on-disk files
            // - EBADF, which can't happen here because we would crash as EBADF is marked unacceptable
            // Therefore, we assert here that close will always succeed and if not, that's a NIO bug we need to know
            // about.

            ring.io_uring_queue_exit() // This closes the ring selector fd for us
            self.selectorFD = -1

            try! Posix.close(descriptor: self.eventFD)
            self.eventFD = -1
        }
        return
    }

    /* attention, this may (will!) be called from outside the event loop, ie. can't access mutable shared state (such as `self.open`) */
    func wakeup0() throws {
        assert(NIOThread.current != self.myThread)
        try self.externalSelectorFDLock.withLock {
                guard self.eventFD >= 0 else {
                    throw EventLoopError.shutdown
                }
                _ = try EventFd.eventfd_write(fd: self.eventFD, value: 1)
        }
    }
}

#endif

#endif