Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
285 changes: 262 additions & 23 deletions src/brpc/event_dispatcher.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@
// specific language governing permissions and limitations
// under the License.

#include <stdlib.h> // `atexit`
#include <stdlib.h> // `abort`, `atexit`
#include <memory>
#include <mutex>
#include <gflags/gflags.h> // DEFINE_int32
#include "butil/compat.h"
#include "butil/fd_utility.h" // make_close_on_exec
#include "butil/logging.h" // LOG
#include "butil/third_party/murmurhash3/murmurhash3.h"// fmix32
#include "bvar/latency_recorder.h" // bvar::LatencyRecorder
#include "bthread/bthread.h" // bthread_start_background
#include "bthread/countdown_event.h"
#include "bthread/mutex.h"
#include "bthread/task_group.h" // TaskGroup::address_meta
#include "brpc/event_dispatcher.h"

Expand All @@ -32,7 +36,10 @@ DECLARE_int32(event_dispatcher_num);

namespace brpc {
DEFINE_bool(event_dispatcher_edisp_unsched, false,
"Disable event dispatcher schedule");
"Enqueue transport input processing without an urgent bthread switch");
DEFINE_bool(event_dispatcher_use_polling, false,
"Busy poll epoll/kqueue without sleeping. Set before dispatchers "
"start; urgent/background input scheduling remains independent.");

DEFINE_bool(usercode_in_pthread, false,
"Call user's callback in pthreads, use bthreads otherwise");
Expand All @@ -43,46 +50,176 @@ static EventDispatcher* g_edisp = nullptr;
static bvar::LatencyRecorder* g_edisp_read_lantency = nullptr;
static bvar::LatencyRecorder* g_edisp_write_lantency = nullptr;
static pthread_once_t g_edisp_once = PTHREAD_ONCE_INIT;
static int g_edisp_ntags = 0;
static int g_edisp_num = 0;

struct EventDispatcherPollingState {
explicit EventDispatcherPollingState(const PollingCallbacks& cb)
: callbacks(cb) {}
const PollingCallbacks callbacks;
// Assigned under the group lock before installing the callbacks.
uint64_t id = 0;
};

struct EventDispatcherPollingCommand {
explicit EventDispatcherPollingCommand(EventDispatcherPollingState* s)
: state(s), rc(0) {}
EventDispatcherPollingState* state;
int rc;
bthread::CountdownEvent done;
};

struct EventDispatcherPollingGroup {
// Registration may suspend its caller while dispatchers acknowledge. A
// pthread mutex held across this wait could deadlock the worker pool.
bthread::Mutex mutex;
uint64_t next_id = 0;
std::unique_ptr<EventDispatcherPollingState> state;
};
static EventDispatcherPollingGroup* g_polling_groups = nullptr;

bool EventDispatcher::IsDispatcherThread() const {
const bthread_t tid = _tid.load(std::memory_order_acquire);
return tid != INVALID_BTHREAD && bthread_self() == tid;
}

int EventDispatcher::SetPollingCallbacks(EventDispatcherPollingState* state) {
EventDispatcherPollingCommand command(state);
{
BAIDU_SCOPED_LOCK(_polling_command_mutex);
// There is no dispatcher thread to acknowledge commands after it
// finishes or is joined.
if (_polling_finished ||
_tid.load(std::memory_order_acquire) == INVALID_BTHREAD) {
return state ? ESHUTDOWN : 0;
}
if (state && _stop.load(std::memory_order_acquire)) {
return ESHUTDOWN;
}
CHECK(_polling_command.load(std::memory_order_relaxed) == nullptr);
_polling_command.store(&command, std::memory_order_release);
}
// Only polling dispatchers accept commands, so no wakeup syscall is needed.
CHECK_EQ(0, command.done.wait());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If the first dispatcher for the same tag starts successfully but the second fails to start because file descriptors are exhausted or bthread creation fails, this still publishes a command to the second dispatcher. Both its _stop and _polling_finished are false, but no thread can call done.signal(). Registration will wait indefinitely while holding the tag lock.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. A dispatcher that fails to start never reaches FinishPolling(), so checking _stop and _polling_finished alone was not enough.
SetPollingCallbacks() now checks for a valid bthread ID before publishing the command. If the second dispatcher failed to start, registration rolls back the callbacks already installed on the first dispatcher and returns -1 with errno = ESHUTDOWN, without issuing a token. We also made Start() fail if the wakeup pipe cannot be created, so a partially initialized dispatcher cannot accept polling commands.

return command.rc;
}

void EventDispatcher::ReleasePollingCallbacks() {
if (_polling_state) {
if (_polling_state->callbacks.release_fn) {
_polling_state->callbacks.release_fn(_polling_context);
}
_polling_state = nullptr;
_polling_context.user_data = nullptr;
}
}

void EventDispatcher::ProcessPollingCommand() {
// Run() only probes the pointer with a relaxed load. Acquire the command
// published by SetPollingCallbacks() before accessing its contents.
EventDispatcherPollingCommand* command =
_polling_command.exchange(nullptr, std::memory_order_acquire);
if (!command) {
return;
}
ReleasePollingCallbacks();
if (command->state) {
if (_stop.load(std::memory_order_acquire)) {
command->rc = ESHUTDOWN;
} else {
_polling_state = command->state;
_polling_context.tag = bthread_self_tag();
_polling_context.dispatcher_index = _priority_index;
if (_polling_state->callbacks.init_fn) {
command->rc =
_polling_state->callbacks.init_fn(_polling_context);
if (command->rc != 0) {
if (command->rc < 0) {
command->rc = EINVAL;
}
ReleasePollingCallbacks();
}
}
}
}
// signal() may resume the caller, which destroys the stack command.
command->done.signal();
}

void EventDispatcher::RunPollingCallback() {
if (_polling_state && !_stop.load(std::memory_order_acquire)) {
_polling_state->callbacks.poll_fn(_polling_context);
}
}

void EventDispatcher::FinishPolling() {
// Release first: a concurrent unregister must not return while release_fn
// still uses the registration. Then reject/acknowledge pending commands.
ReleasePollingCallbacks();
EventDispatcherPollingCommand* command;
{
BAIDU_SCOPED_LOCK(_polling_command_mutex);
_polling_finished = true;
command = _polling_command.exchange(nullptr, std::memory_order_acquire);
if (command) {
command->rc = command->state ? ESHUTDOWN : 0;
}
}
// Acknowledgement may switch bthreads; never hold a pthread mutex here.
if (command) {
command->done.signal();
}
}

bool EventDispatcherUnsched() {
return FLAGS_event_dispatcher_edisp_unsched;
}

static void StopAndJoinGlobalDispatchers() {
for (int i = 0; i < FLAGS_task_group_ntags; ++i) {
for (int j = 0; j < FLAGS_event_dispatcher_num; ++j) {
g_edisp[i * FLAGS_event_dispatcher_num + j].Stop();
g_edisp[i * FLAGS_event_dispatcher_num + j].Join();
}
for (int i = 0; i < g_edisp_ntags * g_edisp_num; ++i) {
g_edisp[i].Stop();
}
for (int i = 0; i < g_edisp_ntags * g_edisp_num; ++i) {
g_edisp[i].Join();
}
}

void InitializeGlobalDispatchers() {
// These options define array sizes and fd ownership and are startup-only.
g_edisp_ntags = FLAGS_task_group_ntags;
g_edisp_num = FLAGS_event_dispatcher_num;
CHECK_GT(g_edisp_ntags, 0);
CHECK_GT(g_edisp_num, 0);
// A dispatcher may switch bthreads through `bthread_start_urgent()`
// while handling events. Waiting in `epoll_wait`/`kevent` blocks its worker
// pthread. Reserve one extra worker per dispatcher to compensate for that
// blocked capacity and preserve the normal concurrency configured by
// pthread. Busy polling also occupies a worker. Reserve one extra worker
// per dispatcher to preserve the normal concurrency configured by
// `ServerOptions.num_threads` or `-bthread_concurrency`.
// Without reservations, `event_dispatcher_num >= num_threads` can leave
// all workers blocked in dispatcher waits, preventing other work.
for (int i = 0; i < FLAGS_task_group_ntags; ++i) {
bthread_tag_t tag = (BTHREAD_TAG_DEFAULT + i) % FLAGS_task_group_ntags;
int rc = bthread_add_reserved_concurrency_by_tag(
FLAGS_event_dispatcher_num, tag);
CHECK_EQ(0, rc) << "Fail to reserve " << FLAGS_event_dispatcher_num
for (int i = 0; i < g_edisp_ntags; ++i) {
bthread_tag_t tag = (BTHREAD_TAG_DEFAULT + i) % g_edisp_ntags;
int rc = bthread_add_reserved_concurrency_by_tag(g_edisp_num, tag);
CHECK_EQ(0, rc) << "Fail to reserve " << g_edisp_num
<< " workers for event dispatchers of tag=" << tag
<< ": " << berror(rc);
}
g_edisp_read_lantency = new bvar::LatencyRecorder("event_dispatcher_read");
g_edisp_write_lantency = new bvar::LatencyRecorder("event_dispatcher_write");
g_edisp = new EventDispatcher[FLAGS_task_group_ntags * FLAGS_event_dispatcher_num];
for (int i = 0; i < FLAGS_task_group_ntags; ++i) {
for (int j = 0; j < FLAGS_event_dispatcher_num; ++j) {
g_edisp = new EventDispatcher[g_edisp_ntags * g_edisp_num];
g_polling_groups = new EventDispatcherPollingGroup[g_edisp_ntags];
for (int i = 0; i < g_edisp_ntags; ++i) {
for (int j = 0; j < g_edisp_num; ++j) {
bthread_attr_t attr =
FLAGS_usercode_in_pthread ? BTHREAD_ATTR_PTHREAD : BTHREAD_ATTR_NORMAL;
attr.tag = (BTHREAD_TAG_DEFAULT + i) % FLAGS_task_group_ntags;
g_edisp[i * FLAGS_event_dispatcher_num + j].set_priority_index(j);
CHECK_EQ(0, g_edisp[i * FLAGS_event_dispatcher_num + j].Start(&attr));
attr.tag = (BTHREAD_TAG_DEFAULT + i) % g_edisp_ntags;
g_edisp[i * g_edisp_num + j].set_priority_index(j);
if (g_edisp[i * g_edisp_num + j].Start(&attr) != 0) {
// Do not let pthread_once complete with an unusable fd shard.
LOG(FATAL) << "Fail to start global event dispatcher, tag="
<< attr.tag << ", index=" << j;
abort(); // FATAL logging may be configured not to terminate.
}
}
}
// This atexit is will be run before g_task_control.stop() because above
Expand All @@ -92,11 +229,113 @@ void InitializeGlobalDispatchers() {

EventDispatcher& GetGlobalEventDispatcher(int fd, bthread_tag_t tag) {
pthread_once(&g_edisp_once, InitializeGlobalDispatchers);
if (FLAGS_task_group_ntags == 1 && FLAGS_event_dispatcher_num == 1) {
if (g_edisp_ntags == 1 && g_edisp_num == 1) {
return g_edisp[0];
}
int index = butil::fmix32(fd) % FLAGS_event_dispatcher_num;
return g_edisp[tag * FLAGS_event_dispatcher_num + index];
int index = butil::fmix32(fd) % g_edisp_num;
return g_edisp[tag * g_edisp_num + index];
}

static bool IsGlobalDispatcherThread() {
for (int i = 0; i < g_edisp_ntags * g_edisp_num; ++i) {
if (g_edisp[i].IsDispatcherThread()) {
Comment on lines +240 to +241
return true;
}
}
return false;
}

int RegisterPollingCallbacksWithTag(bthread_tag_t tag,
const PollingCallbacks& callbacks,
PollingRegistration* registration) {
if (!registration || !callbacks.poll_fn || tag < 0 ||
tag >= FLAGS_task_group_ntags) {
errno = EINVAL;
return -1;
}
pthread_once(&g_edisp_once, InitializeGlobalDispatchers);
if (IsGlobalDispatcherThread()) {
errno = EDEADLK;
return -1;
}
if (tag >= g_edisp_ntags) {
errno = EINVAL;
return -1;
}
EventDispatcherPollingGroup& group = g_polling_groups[tag];
// If registration unwinds, release the lock before destroying callbacks.
std::unique_ptr<EventDispatcherPollingState> state;
std::unique_lock<bthread::Mutex> lock(group.mutex);
if (group.state) {
errno = EEXIST;
return -1;
}
EventDispatcher* dispatchers = g_edisp + tag * g_edisp_num;
if (!dispatchers[0].use_polling()) {
errno = EPERM;
return -1;
}
// Copying a callable may reenter registration or unregistration.
lock.unlock();
state.reset(new EventDispatcherPollingState(callbacks));
lock.lock();
// Another registration (including a reentrant one) may have won the tag.
if (group.state) {
lock.unlock();
state.reset();
errno = EEXIST;
return -1;
}
state->id = ++group.next_id;
for (int i = 0; i < g_edisp_num; ++i) {
const int rc = dispatchers[i].SetPollingCallbacks(state.get());
if (rc != 0) {
for (int j = 0; j < i; ++j) {
CHECK_EQ(0, dispatchers[j].SetPollingCallbacks(nullptr));
}
// Captured objects may reenter registration when destroyed.
lock.unlock();
state.reset();
errno = rc;
return -1;
}
}
registration->_tag = tag;
registration->_id = state->id;
group.state = std::move(state);
return 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

After dispatcher 0 confirms initialization, it can complete Stop(), Join(), and release_fn before dispatcher 1 initializes. The two dispatchers have therefore never been ready at the same time, yet this still publishes a token and returns 0.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This race is still possible. Registration waits for each dispatcher to acknowledge initialization, but an earlier dispatcher can stop and run release_fn while registration is still waiting for a later one. A successful return therefore means every dispatcher acknowledged installation, not that they were all ready at the same time. The token identifies the registration; it is not a liveness guarantee.
The startup-failure fix does not address this race. To guarantee that all dispatchers are still ready when the token is published, we would need to synchronize the final registration commit with Stop() and event-loop exit, and roll back if shutdown wins. Checking Running() one dispatcher at a time would not close the race.

}

int UnregisterPollingCallbacks(PollingRegistration registration) {
if (!registration._id || registration._tag < 0) {
errno = EINVAL;
return -1;
}
pthread_once(&g_edisp_once, InitializeGlobalDispatchers);
if (IsGlobalDispatcherThread()) {
errno = EDEADLK;
return -1;
}
if (registration._tag >= g_edisp_ntags) {
errno = EINVAL;
return -1;
}
EventDispatcherPollingGroup& group = g_polling_groups[registration._tag];
std::unique_lock<bthread::Mutex> lock(group.mutex);
if (!group.state || group.state->id != registration._id) {
errno = ENOENT;
return -1;
}
EventDispatcher* dispatchers =
g_edisp + registration._tag * g_edisp_num;
for (int i = 0; i < g_edisp_num; ++i) {
CHECK_EQ(0, dispatchers[i].SetPollingCallbacks(nullptr));
}
// Clear the registration under the lock, but destroy the callbacks after
// unlocking: a captured object's destructor may reenter on the same tag.
auto state = std::move(group.state);
lock.unlock();
return 0;
}

int IOEventData::OnCreated(const IOEventDataOptions& options) {
Expand Down
Loading
Loading