Copilot commented on code in PR #3780:
URL: https://github.com/apache/brpc/pull/3780#discussion_r4715054502


##########
src/brpc/ubshm/ub_endpoint.cpp:
##########
@@ -193,15 +193,80 @@ UBShmEndpoint::~UBShmEndpoint() {
 }
 
 void UBShmEndpoint::Reset() {
+    // The ring is destroyed by DeallocateResources() or by the poller that
+    // still uses it.
     DeallocateResources();
 
-    delete _ub_ring;
-    _ub_ring = nullptr;
     _poller_sid = INVALID_SOCKET_ID;
+    _poller = nullptr;
     _negotiated_data_format = UBR_DATA_FORMAT_NONE;
     _state = UNINIT;
 }
 
+// `ring' is not used any more, either because the endpoint never handed it to
+// a poller or because its last user just returned it.
+static void DestroyRing(UBRing* ring) {
+    if (ring == nullptr) {
+        return;
+    }
+    ring->UbrTrxClose();
+    delete ring;
+}
+
+static void* DestroyRingInBthread(void* arg) {
+    DestroyRing(static_cast<UBRing*>(arg));
+    return nullptr;
+}
+
+// Closing the trx may wait for the peer to acknowledge the close, which must
+// not happen in the poller or in a callback of the ring: hand the ring to a
+// bthread instead.
+static void DestroyRingLater(UBRing* ring) {
+    if (ring == nullptr) {
+        return;
+    }
+    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);
+    }

Review Comment:
   If `bthread_start_background` fails, this fallback calls `DestroyRing` 
synchronously from the last ring user. When that user is the UBRing poller, 
`UbrTrxClose()` can wait for the peer's acknowledgement, so resource-exhaustion 
can still block the poller—the guarantee in this change only holds when helper 
creation succeeds. Please use a nonblocking/retained cleanup fallback instead 
of closing the ring inline on the poller path.



##########
src/brpc/ubshm/ub_endpoint.cpp:
##########
@@ -193,15 +193,80 @@ UBShmEndpoint::~UBShmEndpoint() {
 }
 
 void UBShmEndpoint::Reset() {
+    // The ring is destroyed by DeallocateResources() or by the poller that
+    // still uses it.
     DeallocateResources();
 
-    delete _ub_ring;
-    _ub_ring = nullptr;
     _poller_sid = INVALID_SOCKET_ID;
+    _poller = nullptr;
     _negotiated_data_format = UBR_DATA_FORMAT_NONE;
     _state = UNINIT;
 }
 
+// `ring' is not used any more, either because the endpoint never handed it to
+// a poller or because its last user just returned it.
+static void DestroyRing(UBRing* ring) {
+    if (ring == nullptr) {
+        return;
+    }
+    ring->UbrTrxClose();
+    delete ring;
+}
+
+static void* DestroyRingInBthread(void* arg) {
+    DestroyRing(static_cast<UBRing*>(arg));
+    return nullptr;
+}
+
+// Closing the trx may wait for the peer to acknowledge the close, which must
+// not happen in the poller or in a callback of the ring: hand the ring to a
+// bthread instead.
+static void DestroyRingLater(UBRing* ring) {
+    if (ring == nullptr) {
+        return;
+    }
+    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);
+    }

Review Comment:
   This launches an untracked bthread that can execute `UbrTrxClose()` after 
`GlobalRelease()` has joined the pollers and immediately called 
`UBRingManager::UbrMgrFini()`/`ShmMgrFini()`. `UbrTrxClose()` accesses the trx 
manager and shared-memory state, so shutdown can race this helper and use freed 
global resources. Track and drain these destroy helpers before tearing down the 
UBRing and SHM managers, or otherwise make shutdown wait for them.



##########
src/brpc/ubshm/ub_endpoint.cpp:
##########
@@ -193,15 +193,80 @@ UBShmEndpoint::~UBShmEndpoint() {
 }
 
 void UBShmEndpoint::Reset() {
+    // The ring is destroyed by DeallocateResources() or by the poller that
+    // still uses it.
     DeallocateResources();
 
-    delete _ub_ring;
-    _ub_ring = nullptr;
     _poller_sid = INVALID_SOCKET_ID;
+    _poller = nullptr;
     _negotiated_data_format = UBR_DATA_FORMAT_NONE;
     _state = UNINIT;
 }
 
+// `ring' is not used any more, either because the endpoint never handed it to
+// a poller or because its last user just returned it.
+static void DestroyRing(UBRing* ring) {
+    if (ring == nullptr) {
+        return;
+    }
+    ring->UbrTrxClose();
+    delete ring;
+}
+
+static void* DestroyRingInBthread(void* arg) {
+    DestroyRing(static_cast<UBRing*>(arg));
+    return nullptr;
+}
+
+// Closing the trx may wait for the peer to acknowledge the close, which must
+// not happen in the poller or in a callback of the ring: hand the ring to a
+// bthread instead.
+static void DestroyRingLater(UBRing* ring) {
+    if (ring == nullptr) {
+        return;
+    }
+    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);
+    }
+}
+
+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);

Review Comment:
   The refcount increment is not a safe pin against `DeallocateResources()`: 
that method can observe zero users, retire and destroy the ring, while this 
thread's non-sequential `load(_ring_closed)` still observes the old `false` 
value. It can then load the old `_ub_ring` pointer and return a ring that has 
already been destroyed. The closed-state check and refcount transition need one 
atomic protocol (for example, a CAS/state lock) that prevents an acquire from 
succeeding once teardown has begun.



##########
src/brpc/ubshm/ub_endpoint.cpp:
##########
@@ -844,53 +940,62 @@ int UBShmEndpoint::AllocateServerResources(ubring::SHM* 
remote_trx_shm,
         return 0;
     }
 
-    CHECK(_ub_ring == nullptr);
+    CHECK(_ub_ring.load(butil::memory_order_relaxed) == nullptr);
     // TODO: Pooling management
-    _ub_ring = new UBRing();
+    UBRing* ring = new UBRing();
+    _ub_ring.store(ring, butil::memory_order_relaxed);
 
     SocketOptions options;
-    options.user = this;
+    // 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;
     }
-    int ret = _ub_ring->UbrAllocateServerShm(
+    int ret = ring->UbrAllocateServerShm(
         remote_trx_shm, local_trx_shm, format);
     if (ret != 0) {
         return ret;
     }
+    // Publish the ring to the poller before the ADD below reaches it.
+    _ring_closed.store(false, butil::memory_order_release);
     PollerRegisterEvent(PollerSidOp::ADD, EPOLLIN);
     return ret;
 }
 
 void UBShmEndpoint::DeallocateResources() {
-    if (!_ub_ring) {
+    // Take the ring out first so that nobody starts to use it any more.
+    UBRing* ring = _ub_ring.exchange(nullptr, butil::memory_order_seq_cst);
+    if (ring == nullptr) {
         return;
     }
+    // The poller may be inside PollIn() of this endpoint right now, so the
+    // ring is not destroyed here but by its last user.
+    _ring_closed.store(true, butil::memory_order_seq_cst);
     PollerRegisterEvent(PollerSidOp::REMOVE);
-    _ub_ring->UbrTrxClose();
     if (INVALID_SOCKET_ID != _poller_sid) {
         SocketUniquePtr s;
         if (Socket::Address(_poller_sid, &s) == 0) {
-            s->_user = nullptr;
             s->_fd = -1;
             s->SetFailed();
         }
     }
-}
-
-void UBShmEndpoint::PollIn(UBShmEndpoint* ep, uint32_t ep_event) {
-    SocketUniquePtr s;
-    if (Socket::Address(ep->_socket_id, &s) < 0) {
+    _ring_retired.store(ring, butil::memory_order_seq_cst);
+    if (_ring_ref.load(butil::memory_order_seq_cst) != 0) {

Review Comment:
   This assignment can overwrite an older retired ring if the endpoint is reset 
and then allocated again before the previous poller/sender releases its ring. 
The old pointer in `_ring_retired` is then lost, so that ring is never closed 
or deleted (and the shared `_ring_ref` no longer identifies which generation it 
belongs to). Keep teardown state per ring or prevent a new allocation until the 
retired ring has been reclaimed.



##########
src/brpc/ubshm/ub_endpoint.cpp:
##########
@@ -817,21 +909,25 @@ int UBShmEndpoint::AllocateClientResources(ubring::SHM* 
local_trx_shm, const cha
         return 0;
     }
 
-    CHECK(_ub_ring == nullptr);
+    CHECK(_ub_ring.load(butil::memory_order_relaxed) == nullptr);
     // TODO: Pooling management
-    _ub_ring = new UBRing();
+    UBRing* ring = new UBRing();
+    _ub_ring.store(ring, butil::memory_order_relaxed);
 
     SocketOptions options;
-    options.user = this;
+    // 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;

Review Comment:
   `PollerUser` is allocated before `Socket::Create`, but `Socket::OnCreated` 
assigns `_user = options.user` only after several fallible initialization 
steps. If one of those steps fails, `VersionedRefWithId::Create` recycles the 
socket immediately, while `BeforeRecycled()` has no attached user to delete, so 
this raw pointer is leaked. Please make ownership transfer of the poller user 
failure-safe, including failures before `_user` is assigned.
   
   This issue also appears on line 950 of the same file.



-- 
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