chenBright commented on code in PR #3750:
URL: https://github.com/apache/brpc/pull/3750#discussion_r4694203408


##########
src/brpc/rdma/rdma_endpoint.cpp:
##########
@@ -2012,34 +2063,85 @@ int RdmaEndpoint::PollingModeInitialize(bthread_tag_t 
tag,
 
         return nullptr;
     };
-    for (int i = 0; i < FLAGS_rdma_poller_num; ++i) {
-        auto args = new FnArgs{&pollers[i], &running};
+    int creation_error = 0;
+    for (size_t i = 0; i < pollers.size(); ++i) {
+        std::unique_ptr<FnArgs> args(
+            new (std::nothrow) FnArgs{&pollers[i], &group});
+        if (!args) {
+            creation_error = ENOMEM;
+            break;
+        }
         auto attr = FLAGS_rdma_disable_bthread ? BTHREAD_ATTR_PTHREAD
                                                : BTHREAD_ATTR_NORMAL;
         attr.tag = tag;
         bthread_attr_set_name(&attr, "RdmaPolling");
         pollers[i].callback = callback;
         pollers[i].init_fn = init_fn;
         pollers[i].release_fn = release_fn;
-        auto rc = bthread_start_background(&pollers[i].tid, &attr, fn, args);
+#if defined(UNIT_TEST)
+        if (g_before_rdma_poller_start_for_test) {
+            g_before_rdma_poller_start_for_test();
+        }
+        const int rc = g_start_rdma_poller_for_test(
+#else
+        const int rc = bthread_start_background(
+#endif
+            &pollers[i].tid, &attr, fn, args.get());
         if (rc != 0) {
-            LOG(ERROR) << "Fail to start rdma polling bthread";
-            return -1;
+            pollers[i].tid = INVALID_BTHREAD;
+            creation_error = rc;
+            break;
+        }
+        args.release();
+    }
+    if (creation_error != 0) {
+        group.state = PollerGroup::FAILED;
+        group.error = creation_error;
+        group.startup_result->store(PollerGroup::ABORTED,
+                                    butil::memory_order_release);
+        bthread::butex_wake_all(group.startup_result);
+        for (auto& poller : pollers) {
+            if (poller.tid != INVALID_BTHREAD) {
+                bthread_join(poller.tid, nullptr);
+                poller.tid = INVALID_BTHREAD;
+            }
         }
+        LOG(ERROR) << "Fail to start rdma polling bthread: "
+                   << berror(creation_error);
+        errno = creation_error;
+        return -1;
     }
+    running.store(true, std::memory_order_relaxed);
+    group.state = PollerGroup::STARTED;
+    group.startup_result->store(PollerGroup::SUCCEEDED,
+                                butil::memory_order_release);
+    bthread::butex_wake_all(group.startup_result);
     return 0;

Review Comment:
   `butex_wake_all` may directly run a poller via `TaskGroup::exchange` on a 
regular bthread with the same tag. The initializer still holds the lifecycle 
lock at this point; if all workers for that tag enter the polling loop, which 
does not yield by default, the initializer cannot resume, and external cleanup 
cannot acquire the lock to stop them. This needs a wake-all method that does 
not switch away from the caller.



##########
test/brpc_rdma_unittest.cpp:
##########
@@ -3569,6 +3577,277 @@ TEST(RdmaInlineDataTest, should_post_inline) {
     EXPECT_FALSE(rdma::ShouldPostInline(true, 1, 0));
 }
 
+// Poller lifecycle tests do not need any RDMA queues or hardware.
+static std::atomic<int> g_poller_start_count{0};
+static int g_poller_fail_at = -1;
+
+static int StartRdmaPollerForTest(bthread_t* tid, const bthread_attr_t* attr,
+                                 void* (*fn)(void*), void* arg) {
+    if (g_poller_start_count.fetch_add(1) == g_poller_fail_at) {
+        return EAGAIN;
+    }
+    return bthread_start_background(tid, attr, fn, arg);
+}
+
+class RdmaPollingTest : public ::testing::TestWithParam<int> {
+protected:
+    void SetUp() override {
+        _saved_use_polling = rdma::FLAGS_rdma_use_polling;
+        _saved_poller_num = rdma::FLAGS_rdma_poller_num;
+        _saved_poller_yield = rdma::FLAGS_rdma_poller_yield;
+        _saved_disable_bthread = rdma::FLAGS_rdma_disable_bthread;
+        _saved_start_poller = rdma::g_start_rdma_poller_for_test;
+        rdma::FLAGS_rdma_use_polling = true;
+        rdma::FLAGS_rdma_poller_num = 3;
+        rdma::FLAGS_rdma_poller_yield = true;
+        _saved_groups.swap(rdma::RdmaEndpoint::_poller_groups);
+        ResetGroups();
+    }
+
+    void TearDown() override {
+        rdma::RdmaEndpoint::PollingModeRelease(BTHREAD_TAG_DEFAULT);
+        rdma::g_start_rdma_poller_for_test = _saved_start_poller;
+        rdma::g_before_rdma_poller_start_for_test = nullptr;
+        _saved_groups.swap(rdma::RdmaEndpoint::_poller_groups);
+        rdma::FLAGS_rdma_use_polling = _saved_use_polling;
+        rdma::FLAGS_rdma_poller_num = _saved_poller_num;
+        rdma::FLAGS_rdma_poller_yield = _saved_poller_yield;
+        rdma::FLAGS_rdma_disable_bthread = _saved_disable_bthread;
+    }
+
+    void ResetGroups() {
+        std::vector<rdma::RdmaEndpoint::PollerGroup> fresh(1);
+        rdma::RdmaEndpoint::_poller_groups.swap(fresh);
+        g_poller_start_count = 0;
+        g_poller_fail_at = -1;
+        _initialized = 0;
+        _released = 0;
+        _callbacks = 0;
+        rdma::g_start_rdma_poller_for_test = StartRdmaPollerForTest;
+        rdma::g_before_rdma_poller_start_for_test = nullptr;
+    }
+
+    int Initialize(const std::function<void()>& init_fn = nullptr) {
+        auto callback = [this] { _callbacks.fetch_add(1); };
+        auto release_fn = [this] { _released.fetch_add(1); };
+        return rdma::RdmaEndpoint::PollingModeInitialize(
+            BTHREAD_TAG_DEFAULT, callback, init_fn, release_fn);
+    }
+
+    void ExpectStopped() {
+        const auto& group =
+            rdma::RdmaEndpoint::_poller_groups[BTHREAD_TAG_DEFAULT];
+        EXPECT_FALSE(group.running.load());
+        for (const auto& poller : group.pollers) {
+            EXPECT_EQ(INVALID_BTHREAD, poller.tid);
+        }
+    }
+
+    std::atomic<int> _initialized{0};
+    std::atomic<int> _released{0};
+    std::atomic<int> _callbacks{0};
+
+private:
+    bool _saved_use_polling;
+    int _saved_poller_num;
+    bool _saved_poller_yield;
+    bool _saved_disable_bthread;
+    decltype(&bthread_start_background) _saved_start_poller;
+    std::vector<rdma::RdmaEndpoint::PollerGroup> _saved_groups;
+};
+
+TEST_P(RdmaPollingTest, failed_creation_is_permanent) {
+    for (bool disable_bthread : {false, true}) {
+        SCOPED_TRACE(disable_bthread);
+        ResetGroups();
+        rdma::FLAGS_rdma_disable_bthread = disable_bthread;
+        g_poller_fail_at = GetParam();
+        auto init_fn = [this] { _initialized.fetch_add(1); };
+        EXPECT_EQ(-1, Initialize(init_fn));
+        EXPECT_EQ(EAGAIN, errno);
+        EXPECT_EQ(GetParam() + 1, g_poller_start_count.load());
+        ExpectStopped();
+        EXPECT_EQ(0, _initialized.load());
+        EXPECT_EQ(0, _released.load());
+        EXPECT_EQ(0, _callbacks.load());
+        EXPECT_EQ(rdma::RdmaEndpoint::PollerGroup::ABORTED,
+                  
rdma::RdmaEndpoint::_poller_groups[0].startup_result->load());
+
+        g_poller_fail_at = -1;
+        EXPECT_EQ(-1, Initialize(init_fn));
+        EXPECT_EQ(EAGAIN, errno);
+        rdma::RdmaEndpoint::PollingModeRelease(BTHREAD_TAG_DEFAULT);
+        EXPECT_EQ(-1, Initialize(init_fn));
+        EXPECT_EQ(EAGAIN, errno);
+        EXPECT_EQ(GetParam() + 1, g_poller_start_count.load());
+    }
+}
+
+class RdmaPollingConcurrencyTest : public RdmaPollingTest {};
+
+TEST_F(RdmaPollingConcurrencyTest, initialize_waits_for_rollback_result) {
+    for (bool disable_bthread : {false, true}) {
+        SCOPED_TRACE(disable_bthread);
+        ResetGroups();
+        rdma::FLAGS_rdma_disable_bthread = disable_bthread;
+        auto init_fn = [this] { _initialized.fetch_add(1); };
+        g_poller_fail_at = 1;
+        bthread::CountdownEvent creation_paused;
+        bthread::CountdownEvent resume_creation;
+        std::atomic<int> before_start_calls{0};
+        rdma::g_before_rdma_poller_start_for_test = [&] {
+            if (before_start_calls.fetch_add(1) == 0) {
+                creation_paused.signal();
+                resume_creation.wait();
+            }
+        };
+        int rc = 0;
+        int competing_rc = 0;
+        int competing_errno = 0;
+        std::thread initializer([&] { rc = Initialize(init_fn); });
+        EXPECT_EQ(0, creation_paused.timed_wait(butil::seconds_from_now(5)));
+        auto& group = rdma::RdmaEndpoint::_poller_groups[0];
+        std::thread competing_initializer([&] {
+            competing_rc = Initialize(init_fn);
+            competing_errno = errno;
+        });
+        // The competing call must wait for rollback instead of returning
+        // success while its poller is about to be stopped.
+        ASSERT_FALSE(group.lifecycle_mutex.try_lock());
+        resume_creation.signal();
+        initializer.join();
+        competing_initializer.join();
+        EXPECT_EQ(-1, rc);
+        EXPECT_EQ(-1, competing_rc);
+        EXPECT_EQ(EAGAIN, competing_errno);
+        EXPECT_EQ(-1, Initialize());
+        EXPECT_EQ(EAGAIN, errno);
+        ExpectStopped();
+        EXPECT_EQ(0, _initialized.load());
+        EXPECT_EQ(0, _released.load());
+    }
+}
+
+TEST_F(RdmaPollingConcurrencyTest, release_waits_before_first_poller_created) {
+    for (bool disable_bthread : {false, true}) {
+        SCOPED_TRACE(disable_bthread);
+        ResetGroups();
+        rdma::FLAGS_rdma_disable_bthread = disable_bthread;
+        auto init_fn = [this] { _initialized.fetch_add(1); };
+        bthread::CountdownEvent creation_paused;
+        bthread::CountdownEvent resume_creation;
+        rdma::g_before_rdma_poller_start_for_test = [&] {
+            creation_paused.signal();
+            resume_creation.wait();
+        };
+        int rc = -1;
+        std::thread initializer([&] { rc = Initialize(init_fn); });
+        EXPECT_EQ(0, creation_paused.timed_wait(butil::seconds_from_now(5)));
+        auto& group = rdma::RdmaEndpoint::_poller_groups[0];
+        bthread::CountdownEvent releasing;
+        std::thread releaser([&] {
+            releasing.signal();
+            rdma::RdmaEndpoint::PollingModeRelease(BTHREAD_TAG_DEFAULT);
+        });
+        releasing.wait();
+        // Final shutdown waits behind creation even if no tid exists yet.
+        ASSERT_FALSE(group.lifecycle_mutex.try_lock());
+        resume_creation.signal();
+        initializer.join();
+        releaser.join();
+        EXPECT_EQ(0, rc);
+        ExpectStopped();
+        EXPECT_EQ(3, _initialized.load());
+        EXPECT_EQ(3, _released.load());
+        EXPECT_EQ(-1, Initialize());
+        EXPECT_EQ(ESHUTDOWN, errno);
+    }
+}
+
+TEST_F(RdmaPollingConcurrencyTest, failed_batch_skips_callbacks) {
+    rdma::FLAGS_rdma_disable_bthread = true;
+    bthread::CountdownEvent poller_entered;
+    bthread::CountdownEvent release_callback;
+    g_poller_fail_at = 1;
+    std::thread initializer([&] {
+        EXPECT_EQ(-1, Initialize([&] {
+            poller_entered.signal();
+            release_callback.wait();
+        }));
+    });
+    EXPECT_EQ(ETIMEDOUT,
+              poller_entered.timed_wait(butil::milliseconds_from_now(100)));
+    release_callback.signal();
+    initializer.join();
+    ExpectStopped();
+    EXPECT_EQ(0, _released.load());
+}
+
+TEST_P(RdmaPollingTest, successful_batch_starts_once_and_releases_finally) {
+    auto init_fn = [this] { _initialized.fetch_add(1); };
+    ASSERT_EQ(0, Initialize(init_fn));
+    ASSERT_TRUE(WaitUntil([this] { return _initialized.load() == 3; }));
+    EXPECT_EQ(3, _initialized.load());
+    EXPECT_EQ(0, Initialize(init_fn));
+    EXPECT_EQ(3, g_poller_start_count.load());
+    rdma::RdmaEndpoint::PollingModeRelease(BTHREAD_TAG_DEFAULT);
+    ExpectStopped();
+    EXPECT_EQ(3, _released.load());
+    EXPECT_EQ(-1, Initialize(init_fn));
+    EXPECT_EQ(ESHUTDOWN, errno);
+    EXPECT_EQ(3, g_poller_start_count.load());
+}
+
+TEST_P(RdmaPollingTest, callbacks_can_wait_for_each_other) {
+    bthread::CountdownEvent all_initialized(1);
+    std::atomic<int> arrived{0};
+    ASSERT_EQ(0, Initialize([&] {
+        if (arrived.fetch_add(1) == 2) {
+            all_initialized.signal();
+        }
+        all_initialized.wait();

Review Comment:
   All three pollers enter `all_initialized.wait()` here, and the current 
`CountdownEvent::wait()` writes to the same non-atomic `_wait_was_invoked`. 
Consider using a barrier that supports multiple waiters, such as an arrival 
count protected by `bthread::Mutex` and a condition variable, to prevent a data 
race in the test itself.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to