Skip to content

fix(ubshm): keep the UBRing poller off a released ring - #3780

Open
wwbmmm wants to merge 1 commit into
apache:masterfrom
wwbmmm:oncall/req-20261121-025731-5
Open

wwbmmm wants to merge 1 commit into
apache:masterfrom
wwbmmm:oncall/req-20261121-025731-5

Conversation

@wwbmmm

@wwbmmm wwbmmm commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: N/A

Problem Summary:

The UBRing poller dereferences ep->_ub_ring in PollIn(), but UBShmEndpoint::Reset() destroyed that ring as soon as it had enqueued a fire-and-forget REMOVE op, without waiting for the poller to stop using it. A poller that was inside PollIn() for the same endpoint then read the released UBRing and its shared memory. In addition, PollerRegisterEvent() picked the poller group with bthread_self_tag() on every call, so a MOD/REMOVE issued from a different bthread than the ADD could be delivered to another group, leaving the socket id in the first poller's set forever. IsWritable() also dereferenced _ub_ring unconditionally, so a concurrent reset made it dereference a null (or stale) pointer.

What is changed and the side effects?

Changed:

  • PollerRegisterEvent() records the poller that serves _poller_sid when the event is added and reuses it for every later ADD/MOD/REMOVE, so an endpoint is always added to and removed from the same op queue regardless of the bthread tag.
  • The synthetic poller socket no longer stores the UBShmEndpoint as its SocketUser. It stores a small PollerUser with the id of the owning Socket; the poller resolves the endpoint through Socket::Address() and keeps that Socket referenced while polling, so the endpoint and its transport cannot be released under the poller.
  • The ring is reference counted: AcquireRing()/ReleaseRing() mark it in use (poller, sender, handshake), DeallocateResources() takes it out of the endpoint and marks it closed, and the last user destroys it. The trx is therefore closed only when nobody uses the ring any more; when the poller is the last user, the close (which may wait for the peer to acknowledge) is moved to a helper bthread so polling is never blocked on it. When no user is in flight the ring is closed inline, as before.
  • PollIn()/PollOut() receive the ring that the caller acquired instead of following ep->_ub_ring, and IsWritable()/CutFromIOBufList() borrow the ring the same way, so they never observe a null or replaced pointer and report "not writable"/EPIPE once the endpoint is released.
  • The handshake's UbrMapRemoteShm()/UbrUnlinkLocalShm() calls use the same acquire/release path.

Side effects:

  • Performance effects: the poller takes one additional reference count per poll of an endpoint (a pair of atomics on a cacheline that only the teardown path writes); the number of Socket::Address() calls per poll is the same as before, since PollIn() used to resolve the endpoint's socket itself.
  • Breaking backward compatibility: none. UBShmEndpoint::IsWritable() is no longer const (it now borrows the ring); it is internal to the ubshm transport.

Check List:

  • Please make sure your changes are compilable.
    • cmake -B build -DBUILD_UNIT_TESTS=ON -DDOWNLOAD_GTEST=OFF -DBRPC_SYSTEM_GTEST_SOURCE_DIR=/usr/src/googletest -DWITH_UBRING=ON + make -j6 brpc_ubring_unittest brpc-static : OK
    • default configuration (UBRING off): brpc_ubring_unittest builds and the disabled-path test passes.
  • Tests:
    • make -j6 brpc_ubring_unittest && test/brpc_ubring_unittest: 36/36 pass (also 36/36 with -DWITH_ASAN=ON, no ASAN report; the only leak reported is the pre-existing g_ubring_resource_mutex from GlobalInitialize()).
    • New tests: ring_lifetime_is_bounded_by_its_users (a ring in use is not handed out nor destroyed by Reset(), and its trx is released only after the last user returns it), poller_of_add_serves_later_operations (REMOVE reaches the poller recorded at ADD even when it is not the poller derived from the current bthread tag; Reset() forgets the registration), and poller_survives_endpoint_teardown (a bthread churns create/poll/reset/destroy of endpoints while the UBPolling bthread polls them, waiting for each trx to come back).
    • Not covered by the container: there is no UB hardware/UDK here, so UBRing runs on the built-in IPC shared-memory backend. An end-to-end reproduction with a real ubring session (a client that drops the TCP fd and stops acknowledging the close) still has to be checked manually on UB hardware; the unit tests exercise the same poller/teardown paths with real UBRing/trx objects.

🤖 This PR was automatically created by brpc-oncall

PollIn() dereferences ep->_ub_ring in the polling bthread while Reset()
frees the ring right after enqueueing a fire-and-forget REMOVE op, so the
poller can read the released ring. PollerRegisterEvent() also looks up the
poller group with bthread_self_tag() at REMOVE time, which may be a
different group than the one that saw ADD, leaving a stale socket id in the
first group's set.

- Choose the poller of _poller_sid when the events are added and reuse it
  for MOD/REMOVE.
- Resolve the endpoint from the owning Socket through a SocketUser kept in
  the synthetic poller Socket, and hold that Socket while polling, so the
  endpoint cannot be released under the poller.
- Reference count the ring: DeallocateResources() stops handing it out and
  the last user destroys it. The trx is closed only when nobody uses the
  ring, and the close, which may wait for the peer, does not run in the
  poller when the poller is the last user.
- Pass the acquired ring to PollIn()/PollOut() so they cannot observe a
  replaced _ub_ring, and let IsWritable()/CutFromIOBufList() borrow it the
  same way instead of dereferencing a null or stale pointer.

Tests: ring lifetime across Reset()/release, event routing to the poller
recorded at ADD time, and a stress test that churns endpoints while the
poller polls them.

Copilot AI left a comment

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.

🟡 Changes recommended

Several unresolved moderate and critical findings remain, including leak-prone ownership transfer, blocking cleanup on the poller path, unsafe ring retirement and acquisition races, and untracked shutdown helpers that can access torn-down global resources.

5 open issues
What changed in this PR

This PR hardens UBRing endpoint teardown against concurrent polling, sending, and handshake activity while keeping poller operations associated with the poller selected during registration.

Changes:

  • Adds reference-counted ring acquisition and deferred destruction during teardown.
  • Resolves poller endpoints through retained owning sockets and records stable poller ownership.
  • Adds tests covering ring lifetime, poller routing, and endpoint teardown races.
File Description
test/​brpc_ubring_unittest.cpp Adds tests for ring lifetime bounds, poller operation routing, and endpoint teardown under concurrent polling.
src/​brpc/​ubshm/​ub_endpoint.h Declares ring reference-management APIs, poller ownership metadata, and updated polling interfaces.
src/​brpc/​ubshm/​ub_endpoint.cpp Implements ring lifetime coordination, socket-based poller endpoint resolution, stable poller routing, and safer polling and teardown paths.

Review effort: Lite

Comment on lines +231 to +234
if (bthread_start_background(&tid, &attr, DestroyRingInBthread, ring) != 0) {
PLOG(WARNING) << "Fail to start bthread to destroy the ring";
DestroyRing(ring);
}
Comment on lines +228 to +234
bthread_t tid;
bthread_attr_t attr = BTHREAD_ATTR_NORMAL;
bthread_attr_set_name(&attr, "UBDestroyRing");
if (bthread_start_background(&tid, &attr, DestroyRingInBthread, ring) != 0) {
PLOG(WARNING) << "Fail to start bthread to destroy the ring";
DestroyRing(ring);
}
Comment on lines +237 to +246
bool UBShmEndpoint::AcquireRing(UBRing** ring) {
_ring_ref.fetch_add(1, butil::memory_order_seq_cst);
// The acquire load pairs with the release store in
// AllocateClientResources()/AllocateServerResources(), which publish the
// ring before they hand it out.
if (_ring_closed.load(butil::memory_order_acquire)) {
ReleaseRing();
return false;
}
*ring = _ub_ring.load(butil::memory_order_acquire);
Comment on lines +984 to +985
_ring_retired.store(ring, butil::memory_order_seq_cst);
if (_ring_ref.load(butil::memory_order_seq_cst) != 0) {
Comment on lines +918 to 923
// The poller resolves the endpoint from the owning Socket, see PollerUser.
options.user = new PollerUser(_socket_id);
options.keytable_pool = _socket->_keytable_pool;
if (Socket::Create(options, &_poller_sid) < 0) {
PLOG(WARNING) << "Fail to create socket for UBRing poller";
return -1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants