From 0b65385fad361663125f43d9439dfe0a16521edd Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Mon, 14 Jul 2025 17:15:10 +0100 Subject: [PATCH] improve inEventLoop checks (#3302) ### Motivation: `inEventLoop` is very much in the performance path of SwiftNIO, especially these days with Concurrency, `NIOLoopBound` and friends. Previously, we relied on `pthread_equal(pthread_self(), myPthread)`, however, this could cause a number of issues. 1. Holding onto a `pthread_t` after `.join` is actually illegal (fixed in #3297) 2. Potential ABA issues when `pthread_t` pointer are re-used for new pthreads 3. Fix would require a lock around `myPthread` which makes things (2x slower, even without contention) ### Modifications: - New type `SelectableEventLoopUniqueID` which can be packed into a `UInt` - Attach them into a C thread local ### Result: - Even faster than the old, incorrect version - old: `measuring: el_in_eventloop_100M: 0.257395375, 0.241049208, 0.243188792, 0.259125916, 0.24843225, 0.229690125, 0.244281541, 0.225078834, 0.236395, 0.233305167` - new: `measuring: el_in_eventloop_100M: 0.175561125, 0.187225625, 0.199269375, 0.19740975, 0.1922695, 0.179850958, 0.177612458, 0.17665125, 0.17897475, 0.18038775` - More correct - Groundwork to make #3297 not make things slower --- Package.swift | 8 ++ Sources/CNIOPosix/event_loop_id.c | 19 ++++ Sources/CNIOPosix/include/CNIOPosix.h | 27 ++++++ Sources/NIOCore/ByteBuffer-int.swift | 2 +- Sources/NIOFileSystem/ByteCount.swift | 2 +- Sources/NIOPosix/IntegerBitPacking.swift | 22 +++++ .../MultiThreadedEventLoopGroup.swift | 22 +++-- Sources/NIOPosix/SelectableEventLoop.swift | 89 ++++++++++++++++++- .../NIOWebSocket/WebSocketFrameEncoder.swift | 2 +- Tests/NIOCoreTests/ByteBufferTest.swift | 2 +- Tests/NIOPosixTests/EventLoopTest.swift | 28 ++++++ 11 files changed, 211 insertions(+), 12 deletions(-) create mode 100644 Sources/CNIOPosix/event_loop_id.c create mode 100644 Sources/CNIOPosix/include/CNIOPosix.h diff --git a/Package.swift b/Package.swift index 5fcd0436f..51a8a18be 100644 --- a/Package.swift +++ b/Package.swift @@ -117,6 +117,7 @@ let package = Package( "NIOConcurrencyHelpers", "NIOCore", "_NIODataStructures", + "CNIOPosix", swiftAtomics, ], exclude: includePrivacyManifest ? [] : ["PrivacyInfo.xcprivacy"], @@ -155,6 +156,13 @@ let package = Package( .define("_GNU_SOURCE") ] ), + .target( + name: "CNIOPosix", + dependencies: [], + cSettings: [ + .define("_GNU_SOURCE") + ] + ), .target( name: "CNIOSHA1", dependencies: [] diff --git a/Sources/CNIOPosix/event_loop_id.c b/Sources/CNIOPosix/event_loop_id.c new file mode 100644 index 000000000..e4cf46312 --- /dev/null +++ b/Sources/CNIOPosix/event_loop_id.c @@ -0,0 +1,19 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +#include "include/CNIOPosix.h" + +// Once we support C23, this should become `thread_local`. +// DO NOT TOUCH DIRECTLY, use `c_nio_posix_{get,set}_el_id` +_Thread_local uintptr_t _c_nio_posix_thread_local_el_id; diff --git a/Sources/CNIOPosix/include/CNIOPosix.h b/Sources/CNIOPosix/include/CNIOPosix.h new file mode 100644 index 000000000..3e385523b --- /dev/null +++ b/Sources/CNIOPosix/include/CNIOPosix.h @@ -0,0 +1,27 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +#pragma once + +#include + +extern _Thread_local uintptr_t _c_nio_posix_thread_local_el_id; + +static inline uintptr_t c_nio_posix_get_el_id(void) { + return _c_nio_posix_thread_local_el_id; +} + +static inline void c_nio_posix_set_el_id(uintptr_t id) { + _c_nio_posix_thread_local_el_id = id; +} diff --git a/Sources/NIOCore/ByteBuffer-int.swift b/Sources/NIOCore/ByteBuffer-int.swift index 161eff7e3..6712467ca 100644 --- a/Sources/NIOCore/ByteBuffer-int.swift +++ b/Sources/NIOCore/ByteBuffer-int.swift @@ -180,7 +180,7 @@ extension UInt32 { var n = self - #if arch(arm) || arch(i386) || arch(arm64_32) + #if arch(arm) || arch(i386) || arch(arm64_32) || arch(wasm32) // on 32-bit platforms we can't make use of a whole UInt32.max (as it doesn't fit in an Int) let max = UInt32(Int.max) #else diff --git a/Sources/NIOFileSystem/ByteCount.swift b/Sources/NIOFileSystem/ByteCount.swift index d881a3ed0..d92f1a356 100644 --- a/Sources/NIOFileSystem/ByteCount.swift +++ b/Sources/NIOFileSystem/ByteCount.swift @@ -81,7 +81,7 @@ public struct ByteCount: Hashable, Sendable { extension ByteCount { /// A ``ByteCount`` for the maximum amount of bytes that can be written to `ByteBuffer`. internal static var byteBufferCapacity: ByteCount { - #if arch(arm) || arch(i386) || arch(arm64_32) + #if arch(arm) || arch(i386) || arch(arm64_32) || arch(wasm32) // on 32-bit platforms we can't make use of a whole UInt32.max (as it doesn't fit in an Int) let byteBufferMaxIndex = UInt32(Int.max) #else diff --git a/Sources/NIOPosix/IntegerBitPacking.swift b/Sources/NIOPosix/IntegerBitPacking.swift index 14532e1b9..fd8c135e8 100644 --- a/Sources/NIOPosix/IntegerBitPacking.swift +++ b/Sources/NIOPosix/IntegerBitPacking.swift @@ -106,4 +106,26 @@ extension IntegerBitPacking { let unpacked = _IntegerBitPacking.unpackUU(value, leftType: UInt32.self, rightType: UInt32.self) return (unpacked.0, CInt(truncatingIfNeeded: unpacked.1)) } + + @inlinable + static func packUInt32UInt32(_ left: UInt32, _ right: UInt32) -> UInt64 { + _IntegerBitPacking.packUU(left, right) + } + + @inlinable + static func unpackUInt32UInt32(_ value: UInt64) -> (UInt32, UInt32) { + let unpacked = _IntegerBitPacking.unpackUU(value, leftType: UInt32.self, rightType: UInt32.self) + return (unpacked.0, unpacked.1) + } + + @inlinable + static func packUInt16UInt16(_ left: UInt16, _ right: UInt16) -> UInt32 { + _IntegerBitPacking.packUU(left, right) + } + + @inlinable + static func unpackUInt16UInt16(_ value: UInt32) -> (UInt16, UInt16) { + let unpacked = _IntegerBitPacking.unpackUU(value, leftType: UInt16.self, rightType: UInt16.self) + return (unpacked.0, unpacked.1) + } } diff --git a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift index e6418d891..a4295007f 100644 --- a/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift +++ b/Sources/NIOPosix/MultiThreadedEventLoopGroup.swift @@ -43,8 +43,6 @@ struct NIORegistration: Registration { @available(*, unavailable) extension NIORegistration: Sendable {} -private let nextEventLoopGroupID = ManagedAtomic(0) - /// Called per `NIOThread` that is created for an EventLoop to do custom initialization of the `NIOThread` before the actual `EventLoop` is run on it. typealias ThreadInitializer = (NIOThread) -> Void @@ -79,6 +77,7 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { private static func runTheLoop( thread: NIOThread, + uniqueID: SelectableEventLoopUniqueID, parentGroup: MultiThreadedEventLoopGroup?, // nil iff thread take-over canEventLoopBeShutdownIndividually: Bool, selectorFactory: @escaping () throws -> NIOPosix.Selector, @@ -87,11 +86,16 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { _ callback: @escaping (SelectableEventLoop) -> Void ) { assert(NIOThread.current == thread) + uniqueID.attachToCurrentThread() + defer { + uniqueID.detachFromCurrentThread() + } initializer(thread) do { let loop = SelectableEventLoop( thread: thread, + uniqueID: uniqueID, parentGroup: parentGroup, selector: try selectorFactory(), canBeShutdownIndividually: canEventLoopBeShutdownIndividually, @@ -112,6 +116,7 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { private static func setupThreadAndEventLoop( name: String, + uniqueID: SelectableEventLoopUniqueID, parentGroup: MultiThreadedEventLoopGroup, selectorFactory: @escaping () throws -> NIOPosix.Selector, initializer: @escaping ThreadInitializer, @@ -125,6 +130,7 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { NIOThread.spawnAndRun(name: name, detachThread: false) { t in MultiThreadedEventLoopGroup.runTheLoop( thread: t, + uniqueID: uniqueID, parentGroup: parentGroup, canEventLoopBeShutdownIndividually: false, // part of MTELG selectorFactory: selectorFactory, @@ -270,21 +276,22 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { .init ) { self.threadNamePrefix = threadNamePrefix - let myGroupID = nextEventLoopGroupID.loadThenWrappingIncrement(ordering: .relaxed) - self.myGroupID = myGroupID - var idx = 0 + let firstLoopID = SelectableEventLoopUniqueID.makeNextGroup() + self.myGroupID = firstLoopID.groupID self.canBeShutDown = canBeShutDown self.eventLoops = [] // Just so we're fully initialised and can vend `self` to the `SelectableEventLoop`. + var loopUniqueID = firstLoopID self.eventLoops = threadInitializers.map { initializer in // Maximum name length on linux is 16 by default. let ev = MultiThreadedEventLoopGroup.setupThreadAndEventLoop( - name: "\(threadNamePrefix)\(myGroupID)-#\(idx)", + name: "\(threadNamePrefix)\(loopUniqueID.groupID)-#\(loopUniqueID.loopID)", + uniqueID: loopUniqueID, parentGroup: self, selectorFactory: selectorFactory, initializer: initializer, metricsDelegate: metricsDelegate ) - idx += 1 + loopUniqueID.nextLoop() return ev } } @@ -459,6 +466,7 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup { let callingThread = NIOThread.current MultiThreadedEventLoopGroup.runTheLoop( thread: callingThread, + uniqueID: .makeNextGroup(), parentGroup: nil, canEventLoopBeShutdownIndividually: true, selectorFactory: NIOPosix.Selector.init, diff --git a/Sources/NIOPosix/SelectableEventLoop.swift b/Sources/NIOPosix/SelectableEventLoop.swift index b9d0902ca..9d5c5694c 100644 --- a/Sources/NIOPosix/SelectableEventLoop.swift +++ b/Sources/NIOPosix/SelectableEventLoop.swift @@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import Atomics +import CNIOPosix import DequeModule import Dispatch import NIOConcurrencyHelpers @@ -134,6 +135,8 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { internal var _scheduledTasks = PriorityQueue() @usableFromInline internal var _immediateTasks = Deque() + @usableFromInline + internal let _uniqueID: SelectableEventLoopUniqueID // We only need the ScheduledTask's task closure. However, an `Array<() -> Void>` allocates // for every appended closure. https://bugs.swift.org/browse/SR-15872 @@ -247,12 +250,14 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { internal init( thread: NIOThread, + uniqueID: SelectableEventLoopUniqueID, parentGroup: MultiThreadedEventLoopGroup?, // nil iff thread take-over selector: NIOPosix.Selector, canBeShutdownIndividually: Bool, metricsDelegate: NIOEventLoopMetricsDelegate? ) { self.metricsDelegate = metricsDelegate + self._uniqueID = uniqueID self._parentGroup = parentGroup self._selector = selector self.thread = thread @@ -267,6 +272,8 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { let voidPromise = self.makePromise(of: Void.self) voidPromise.succeed(()) self._succeededVoidFuture = voidPromise.futureResult + preconditionInEventLoop() + precondition(self._uniqueID.matchesCurrentThread) } deinit { @@ -326,7 +333,7 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { /// - see: `EventLoop.inEventLoop` @usableFromInline internal var inEventLoop: Bool { - thread.isCurrent + self._uniqueID.matchesCurrentThread } /// - see: `EventLoop.now` @@ -809,6 +816,7 @@ internal final class SelectableEventLoop: EventLoop, @unchecked Sendable { /// Start processing I/O and tasks for this `SelectableEventLoop`. This method will continue running (and so block) until the `SelectableEventLoop` is closed. internal func run() throws { self.preconditionInEventLoop() + defer { var iterations = 0 var drained = false @@ -1098,3 +1106,82 @@ extension SelectableEventLoop { } } } + +@usableFromInline +struct SelectableEventLoopUniqueID: Sendable { + @usableFromInline + static let _nextGroupID = ManagedAtomic(1) // DO NOT MAKE THIS 0. + + @usableFromInline + var _loopID: UInt32 + + @usableFromInline + let _groupID: UInt32 + + @inlinable + var groupID: Int { + Int(self._groupID) + } + + @inlinable + var loopID: Int { + Int(self._loopID) + } + + @inlinable + init(_loopID: UInt32, groupID: UInt32) { + self._loopID = _loopID + self._groupID = groupID + } + + static func makeNextGroup() -> Self { + let groupID = Self._nextGroupID.loadThenWrappingIncrement(ordering: .relaxed) + + // If we're crashing just below, we created more 2^32 ELGs -- unlikely. + return Self(_loopID: 1, groupID: UInt32(groupID)) + } + + mutating func nextLoop() { + self._loopID += 1 + } + + @inlinable + internal var matchesCurrentThread: Bool { + let threadUniqueID = c_nio_posix_get_el_id() + return threadUniqueID == self.packedEventLoopID + } + + @inlinable + internal var packedEventLoopID: UInt { + #if arch(arm) || arch(i386) || arch(arm64_32) || arch(wasm32) + // 32 bit + // If we're crashing below, we created more than 2^16 (64ki) ELGs which is unsupported. + precondition(self._groupID < UInt32(UInt16.max), "too many event loops created") + precondition(self._loopID < UInt32(UInt16.max), "event loop group with too many event loops created") + let packedID = IntegerBitPacking.packUInt16UInt16( + UInt16(self._groupID), + UInt16(self._loopID) + ) + #else + // 64 bit + let packedID = IntegerBitPacking.packUInt32UInt32(self._groupID, self._loopID) + #endif + assert(MemoryLayout.size == MemoryLayout.size(ofValue: packedID)) + return UInt(packedID) + } + + internal func attachToCurrentThread() { + let existingPackedID = c_nio_posix_get_el_id() + precondition(existingPackedID == 0, "weird, current thread ID \(existingPackedID), expected 0") + + let packedID = self.packedEventLoopID + c_nio_posix_set_el_id(UInt(packedID)) + } + + internal func detachFromCurrentThread() { + let existingPackedID = c_nio_posix_get_el_id() + precondition(existingPackedID == self.packedEventLoopID) + + c_nio_posix_set_el_id(0) + } +} diff --git a/Sources/NIOWebSocket/WebSocketFrameEncoder.swift b/Sources/NIOWebSocket/WebSocketFrameEncoder.swift index 8bac7446d..5d3ca1594 100644 --- a/Sources/NIOWebSocket/WebSocketFrameEncoder.swift +++ b/Sources/NIOWebSocket/WebSocketFrameEncoder.swift @@ -16,7 +16,7 @@ import NIOCore private let maxOneByteSize = 125 private let maxTwoByteSize = Int(UInt16.max) -#if arch(arm) || arch(i386) || arch(arm64_32) +#if arch(arm) || arch(i386) || arch(arm64_32) || arch(wasm32) // on 32-bit platforms we can't put a whole UInt32 in an Int private let maxNIOFrameSize = Int(UInt32.max / 2) #else diff --git a/Tests/NIOCoreTests/ByteBufferTest.swift b/Tests/NIOCoreTests/ByteBufferTest.swift index bd50fe025..73694bbd5 100644 --- a/Tests/NIOCoreTests/ByteBufferTest.swift +++ b/Tests/NIOCoreTests/ByteBufferTest.swift @@ -1409,7 +1409,7 @@ class ByteBufferTest: XCTestCase { } func testAllocationOfReallyBigByteBuffer() throws { - #if arch(arm) || arch(i386) || arch(arm64_32) + #if arch(arm) || arch(i386) || arch(arm64_32) || arch(wasm32) // this test doesn't work on 32-bit platforms because the address space is only 4GB large and we're trying // to make a 4GB ByteBuffer which just won't fit. Even going down to 2GB won't make it better. return diff --git a/Tests/NIOPosixTests/EventLoopTest.swift b/Tests/NIOPosixTests/EventLoopTest.swift index 37b44a596..6321055b0 100644 --- a/Tests/NIOPosixTests/EventLoopTest.swift +++ b/Tests/NIOPosixTests/EventLoopTest.swift @@ -1985,6 +1985,34 @@ final class EventLoopTest: XCTestCase { scheduledTask.cancel() } + + func testInEventLoopABAProblem() { + // Older SwiftNIO versions had a bug here, they held onto `pthread_t`s for ever (which is illegal) and then + // used `pthread_equal(pthread_self(), myPthread)`. `pthread_equal` just compares the pointer values which + // means there's an ABA problem here. This test checks that we don't suffer from that issue now. + let allELs: NIOLockedValueBox<[any EventLoop]> = NIOLockedValueBox([]) + + for _ in 0..<100 { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 4) + defer { + XCTAssertNoThrow(try group.syncShutdownGracefully()) + } + for loop in group.makeIterator() { + try! loop.submit { + allELs.withLockedValue { allELs in + XCTAssertTrue(loop.inEventLoop) + for otherEL in allELs { + XCTAssertFalse( + otherEL.inEventLoop, + "should only be in \(loop) but turns out also in \(otherEL)" + ) + } + allELs.append(loop) + } + }.wait() + } + } + } } private final class EventLoopWithPreSucceededFuture: EventLoop {