| 1 |
// Copyright 2022 gRPC Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
#ifndef GRPC_CORE_LIB_EVENT_ENGINE_POSIX_ENGINE_POSIX_ENDPOINT_H |
| 16 |
#define GRPC_CORE_LIB_EVENT_ENGINE_POSIX_ENGINE_POSIX_ENDPOINT_H |
| 17 |
|
| 18 |
#include <grpc/support/port_platform.h> |
| 19 |
|
| 20 |
// IWYU pragma: no_include <bits/types/struct_iovec.h> |
| 21 |
|
| 22 |
#include <atomic> |
| 23 |
#include <cstdint> |
| 24 |
#include <memory> |
| 25 |
#include <new> |
| 26 |
#include <utility> |
| 27 |
|
| 28 |
#include "absl/base/thread_annotations.h" |
| 29 |
#include "absl/container/flat_hash_map.h" |
| 30 |
#include "absl/functional/any_invocable.h" |
| 31 |
#include "absl/hash/hash.h" |
| 32 |
#include "absl/meta/type_traits.h" |
| 33 |
#include "absl/status/status.h" |
| 34 |
|
| 35 |
#include <grpc/event_engine/event_engine.h> |
| 36 |
#include <grpc/event_engine/memory_allocator.h> |
| 37 |
#include <grpc/event_engine/slice_buffer.h> |
| 38 |
#include <grpc/support/alloc.h> |
| 39 |
#include <grpc/support/log.h> |
| 40 |
|
| 41 |
#include "src/core/lib/event_engine/posix_engine/event_poller.h" |
| 42 |
#include "src/core/lib/event_engine/posix_engine/posix_engine_closure.h" |
| 43 |
#include "src/core/lib/event_engine/posix_engine/tcp_socket_utils.h" |
| 44 |
#include "src/core/lib/event_engine/posix_engine/traced_buffer_list.h" |
| 45 |
#include "src/core/lib/gprpp/ref_counted.h" |
| 46 |
#include "src/core/lib/gprpp/sync.h" |
| 47 |
#include "src/core/lib/iomgr/port.h" |
| 48 |
#include "src/core/lib/resource_quota/memory_quota.h" |
| 49 |
|
| 50 |
#ifdef GRPC_POSIX_SOCKET_TCP |
| 51 |
|
| 52 |
#include <sys/socket.h> // IWYU pragma: keep |
| 53 |
#include <sys/types.h> // IWYU pragma: keep |
| 54 |
|
| 55 |
#ifdef GRPC_MSG_IOVLEN_TYPE |
| 56 |
typedef GRPC_MSG_IOVLEN_TYPE msg_iovlen_type; |
| 57 |
#else |
| 58 |
typedef size_t msg_iovlen_type; |
| 59 |
#endif |
| 60 |
|
| 61 |
#endif // GRPC_POSIX_SOCKET_TCP |
| 62 |
|
| 63 |
namespace grpc_event_engine { |
| 64 |
namespace posix_engine { |
| 65 |
|
| 66 |
#ifdef GRPC_POSIX_SOCKET_TCP |
| 67 |
|
| 68 |
class TcpZerocopySendRecord { |
| 69 |
public: |
| 70 |
TcpZerocopySendRecord() { buf_.Clear(); }; |
| 71 |
|
| 72 |
~TcpZerocopySendRecord() { DebugAssertEmpty(); } |
| 73 |
|
| 74 |
// TcpZerocopySendRecord contains a slice buffer holding the slices to be |
| 75 |
// sent. Given the slices that we wish to send, and the current offset into |
| 76 |
// the slice buffer (indicating which have already been sent), populate an |
| 77 |
// iovec array that will be used for a zerocopy enabled sendmsg(). |
| 78 |
// unwind_slice_idx - input/output parameter. It indicates the index of last |
| 79 |
// slice whose contents were partially sent in the previous sendmsg. After |
| 80 |
// this function returns, it gets updated to to a new offset |
| 81 |
// depending on the number of bytes which are decided to be sent in the |
| 82 |
// current sendmsg. |
| 83 |
// unwind_byte_idx - input/output parameter. It indicates the byte offset |
| 84 |
// within the last slice whose contents were partially sent in the previous |
| 85 |
// sendmsg. After this function returns, it gets updated to a new offset |
| 86 |
// depending on the number of bytes which are decided to be sent in the |
| 87 |
// current sendmsg. |
| 88 |
// sending_length - total number of bytes to be sent in the current sendmsg. |
| 89 |
// iov - An iovec array containing the bytes to be sent in the current |
| 90 |
// sendmsg. |
| 91 |
// Returns: the number of entries in the iovec array. |
| 92 |
// |
| 93 |
msg_iovlen_type PopulateIovs(size_t* unwind_slice_idx, |
| 94 |
size_t* unwind_byte_idx, size_t* sending_length, |
| 95 |
iovec* iov); |
| 96 |
|
| 97 |
// A sendmsg() may not be able to send the bytes that we requested at this |
| 98 |
// time, returning EAGAIN (possibly due to backpressure). In this case, |
| 99 |
// unwind the offset into the slice buffer so we retry sending these bytes. |
| 100 |
void UnwindIfThrottled(size_t unwind_slice_idx, size_t unwind_byte_idx) { |
| 101 |
out_offset_.byte_idx = unwind_byte_idx; |
| 102 |
out_offset_.slice_idx = unwind_slice_idx; |
| 103 |
} |
| 104 |
|
| 105 |
// Update the offset into the slice buffer based on how much we wanted to sent |
| 106 |
// vs. what sendmsg() actually sent (which may be lower, possibly due to |
| 107 |
// backpressure). |
| 108 |
void UpdateOffsetForBytesSent(size_t sending_length, size_t actually_sent); |
| 109 |
|
| 110 |
// Indicates whether all underlying data has been sent or not. |
| 111 |
bool AllSlicesSent() { return out_offset_.slice_idx == buf_.Count(); } |
| 112 |
|
| 113 |
// Reset this structure for a new tcp_write() with zerocopy. |
| 114 |
void PrepareForSends( |
| 115 |
grpc_event_engine::experimental::SliceBuffer& slices_to_send) { |
| 116 |
DebugAssertEmpty(); |
| 117 |
out_offset_.slice_idx = 0; |
| 118 |
out_offset_.byte_idx = 0; |
| 119 |
buf_.Swap(slices_to_send); |
| 120 |
Ref(); |
| 121 |
} |
| 122 |
|
| 123 |
// References: 1 reference per sendmsg(), and 1 for the tcp_write(). |
| 124 |
void Ref() { ref_.fetch_add(1, std::memory_order_relaxed); } |
| 125 |
|
| 126 |
// Unref: called when we get an error queue notification for a sendmsg(), if a |
| 127 |
// sendmsg() failed or when tcp_write() is done. |
| 128 |
bool Unref() { |
| 129 |
const intptr_t prior = ref_.fetch_sub(1, std::memory_order_acq_rel); |
| 130 |
GPR_DEBUG_ASSERT(prior > 0); |
| 131 |
if (prior == 1) { |
| 132 |
AllSendsComplete(); |
| 133 |
return true; |
| 134 |
} |
| 135 |
return false; |
| 136 |
} |
| 137 |
|
| 138 |
private: |
| 139 |
struct OutgoingOffset { |
| 140 |
size_t slice_idx = 0; |
| 141 |
size_t byte_idx = 0; |
| 142 |
}; |
| 143 |
|
| 144 |
void DebugAssertEmpty() { |
| 145 |
GPR_DEBUG_ASSERT(buf_.Count() == 0); |
| 146 |
GPR_DEBUG_ASSERT(buf_.Length() == 0); |
| 147 |
GPR_DEBUG_ASSERT(ref_.load(std::memory_order_relaxed) == 0); |
| 148 |
} |
| 149 |
|
| 150 |
// When all sendmsg() calls associated with this tcp_write() have been |
| 151 |
// completed (ie. we have received the notifications for each sequence number |
| 152 |
// for each sendmsg()) and all reference counts have been dropped, drop our |
| 153 |
// reference to the underlying data since we no longer need it. |
| 154 |
void AllSendsComplete() { |
| 155 |
GPR_DEBUG_ASSERT(ref_.load(std::memory_order_relaxed) == 0); |
| 156 |
buf_.Clear(); |
| 157 |
} |
| 158 |
|
| 159 |
grpc_event_engine::experimental::SliceBuffer buf_; |
| 160 |
std::atomic<intptr_t> ref_{0}; |
| 161 |
OutgoingOffset out_offset_; |
| 162 |
}; |
| 163 |
|
| 164 |
class TcpZerocopySendCtx { |
| 165 |
public: |
| 166 |
static constexpr int kDefaultMaxSends = 4; |
| 167 |
static constexpr size_t kDefaultSendBytesThreshold = 16 * 1024; // 16KB |
| 168 |
|
| 169 |
explicit TcpZerocopySendCtx( |
| 170 |
bool zerocopy_enabled, int max_sends = kDefaultMaxSends, |
| 171 |
size_t send_bytes_threshold = kDefaultSendBytesThreshold) |
| 172 |
: max_sends_(max_sends), |
| 173 |
free_send_records_size_(max_sends), |
| 174 |
threshold_bytes_(send_bytes_threshold) { |
| 175 |
send_records_ = static_cast<TcpZerocopySendRecord*>( |
| 176 |
gpr_malloc(max_sends * sizeof(*send_records_))); |
| 177 |
free_send_records_ = static_cast<TcpZerocopySendRecord**>( |
| 178 |
gpr_malloc(max_sends * sizeof(*free_send_records_))); |
| 179 |
if (send_records_ == nullptr || free_send_records_ == nullptr) { |
| 180 |
gpr_free(send_records_); |
| 181 |
gpr_free(free_send_records_); |
| 182 |
gpr_log(GPR_INFO, "Disabling TCP TX zerocopy due to memory pressure.\n"); |
| 183 |
memory_limited_ = true; |
| 184 |
enabled_ = false; |
| 185 |
} else { |
| 186 |
for (int idx = 0; idx < max_sends_; ++idx) { |
| 187 |
new (send_records_ + idx) TcpZerocopySendRecord(); |
| 188 |
free_send_records_[idx] = send_records_ + idx; |
| 189 |
} |
| 190 |
enabled_ = zerocopy_enabled; |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
~TcpZerocopySendCtx() { |
| 195 |
if (send_records_ != nullptr) { |
| 196 |
for (int idx = 0; idx < max_sends_; ++idx) { |
| 197 |
send_records_[idx].~TcpZerocopySendRecord(); |
| 198 |
} |
| 199 |
} |
| 200 |
gpr_free(send_records_); |
| 201 |
gpr_free(free_send_records_); |
| 202 |
} |
| 203 |
|
| 204 |
// True if we were unable to allocate the various bookkeeping structures at |
| 205 |
// transport initialization time. If memory limited, we do not zerocopy. |
| 206 |
bool MemoryLimited() const { return memory_limited_; } |
| 207 |
|
| 208 |
// TCP send zerocopy maintains an implicit sequence number for every |
| 209 |
// successful sendmsg() with zerocopy enabled; the kernel later gives us an |
| 210 |
// error queue notification with this sequence number indicating that the |
| 211 |
// underlying data buffers that we sent can now be released. Once that |
| 212 |
// notification is received, we can release the buffers associated with this |
| 213 |
// zerocopy send record. Here, we associate the sequence number with the data |
| 214 |
// buffers that were sent with the corresponding call to sendmsg(). |
| 215 |
void NoteSend(TcpZerocopySendRecord* record) { |
| 216 |
record->Ref(); |
| 217 |
{ |
| 218 |
grpc_core::MutexLock lock(&mu_); |
| 219 |
is_in_write_ = true; |
| 220 |
AssociateSeqWithSendRecordLocked(last_send_, record); |
| 221 |
} |
| 222 |
++last_send_; |
| 223 |
} |
| 224 |
|
| 225 |
// If sendmsg() actually failed, though, we need to revert the sequence number |
| 226 |
// that we speculatively bumped before calling sendmsg(). Note that we bump |
| 227 |
// this sequence number and perform relevant bookkeeping (see: NoteSend()) |
| 228 |
// *before* calling sendmsg() since, if we called it *after* sendmsg(), then |
| 229 |
// there is a possible race with the release notification which could occur on |
| 230 |
// another thread before we do the necessary bookkeeping. Hence, calling |
| 231 |
// NoteSend() *before* sendmsg() and implementing an undo function is needed. |
| 232 |
void UndoSend() { |
| 233 |
--last_send_; |
| 234 |
if (ReleaseSendRecord(last_send_)->Unref()) { |
| 235 |
// We should still be holding the ref taken by tcp_write(). |
| 236 |
GPR_DEBUG_ASSERT(0); |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
// Simply associate this send record (and the underlying sent data buffers) |
| 241 |
// with the implicit sequence number for this zerocopy sendmsg(). |
| 242 |
void AssociateSeqWithSendRecordLocked(uint32_t seq, |
| 243 |
TcpZerocopySendRecord* record) |
| 244 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { |
| 245 |
ctx_lookup_.emplace(seq, record); |
| 246 |
} |
| 247 |
|
| 248 |
// Get a send record for a send that we wish to do with zerocopy. |
| 249 |
TcpZerocopySendRecord* GetSendRecord() { |
| 250 |
grpc_core::MutexLock lock(&mu_); |
| 251 |
return TryGetSendRecordLocked(); |
| 252 |
} |
| 253 |
|
| 254 |
// A given send record corresponds to a single tcp_write() with zerocopy |
| 255 |
// enabled. This can result in several sendmsg() calls to flush all of the |
| 256 |
// data to wire. Each sendmsg() takes a reference on the |
| 257 |
// TcpZerocopySendRecord, and corresponds to a single sequence number. |
| 258 |
// ReleaseSendRecord releases a reference on TcpZerocopySendRecord for a |
| 259 |
// single sequence number. This is called either when we receive the relevant |
| 260 |
// error queue notification (saying that we can discard the underlying |
| 261 |
// buffers for this sendmsg()) is received from the kernel - or, in case |
| 262 |
// sendmsg() was unsuccessful to begin with. |
| 263 |
TcpZerocopySendRecord* ReleaseSendRecord(uint32_t seq) { |
| 264 |
grpc_core::MutexLock lock(&mu_); |
| 265 |
return ReleaseSendRecordLocked(seq); |
| 266 |
} |
| 267 |
|
| 268 |
// After all the references to a TcpZerocopySendRecord are released, we can |
| 269 |
// add it back to the pool (of size max_sends_). Note that we can only have |
| 270 |
// max_sends_ tcp_write() instances with zerocopy enabled in flight at the |
| 271 |
// same time. |
| 272 |
void PutSendRecord(TcpZerocopySendRecord* record) { |
| 273 |
grpc_core::MutexLock lock(&mu_); |
| 274 |
GPR_DEBUG_ASSERT(record >= send_records_ && |
| 275 |
record < send_records_ + max_sends_); |
| 276 |
PutSendRecordLocked(record); |
| 277 |
} |
| 278 |
|
| 279 |
// Indicate that we are disposing of this zerocopy context. This indicator |
| 280 |
// will prevent new zerocopy writes from being issued. |
| 281 |
void Shutdown() { shutdown_.store(true, std::memory_order_release); } |
| 282 |
|
| 283 |
// Indicates that there are no inflight tcp_write() instances with zerocopy |
| 284 |
// enabled. |
| 285 |
bool AllSendRecordsEmpty() { |
| 286 |
grpc_core::MutexLock lock(&mu_); |
| 287 |
return free_send_records_size_ == max_sends_; |
| 288 |
} |
| 289 |
|
| 290 |
bool Enabled() const { return enabled_; } |
| 291 |
|
| 292 |
// Only use zerocopy if we are sending at least this many bytes. The |
| 293 |
// additional overhead of reading the error queue for notifications means that |
| 294 |
// zerocopy is not useful for small transfers. |
| 295 |
size_t ThresholdBytes() const { return threshold_bytes_; } |
| 296 |
|
| 297 |
// Expected to be called by handler reading messages from the err queue. |
| 298 |
// It is used to indicate that some optmem memory is now available. It returns |
| 299 |
// true to tell the caller to mark the file descriptor as immediately |
| 300 |
// writable. |
| 301 |
// |
| 302 |
// OptMem (controlled by the kernel option optmem_max) refers to the memory |
| 303 |
// allocated to the cmsg list maintained by the kernel that contains "extra" |
| 304 |
// packet information like SCM_RIGHTS or IP_TTL. Increasing this option allows |
| 305 |
// the kernel to allocate more memory as needed for more control messages that |
| 306 |
// need to be sent for each socket connected. |
| 307 |
// |
| 308 |
// If a write is currently in progress on the socket (ie. we have issued a |
| 309 |
// sendmsg() and are about to check its return value) then we set omem state |
| 310 |
// to CHECK to make the sending thread know that some tcp_omem was |
| 311 |
// concurrently freed even if sendmsg() returns ENOBUFS. In this case, since |
| 312 |
// there is already an active send thread, we do not need to mark the |
| 313 |
// socket writeable, so we return false. |
| 314 |
// |
| 315 |
// If there was no write in progress on the socket, and the socket was not |
| 316 |
// marked as FULL, then we need not mark the socket writeable now that some |
| 317 |
// tcp_omem memory is freed since it was not considered as blocked on |
| 318 |
// tcp_omem to begin with. So in this case, return false. |
| 319 |
// |
| 320 |
// But, if a write was not in progress and the omem state was FULL, then we |
| 321 |
// need to mark the socket writeable since it is no longer blocked by |
| 322 |
// tcp_omem. In this case, return true. |
| 323 |
// |
| 324 |
// Please refer to the STATE TRANSITION DIAGRAM below for more details. |
| 325 |
// |
| 326 |
bool UpdateZeroCopyOptMemStateAfterFree() { |
| 327 |
grpc_core::MutexLock lock(&mu_); |
| 328 |
if (is_in_write_) { |
| 329 |
zcopy_enobuf_state_ = OptMemState::kCheck; |
| 330 |
return false; |
| 331 |
} |
| 332 |
GPR_DEBUG_ASSERT(zcopy_enobuf_state_ != OptMemState::kCheck); |
| 333 |
if (zcopy_enobuf_state_ == OptMemState::kFull) { |
| 334 |
// A previous sendmsg attempt was blocked by ENOBUFS. Return true to |
| 335 |
// mark the fd as writable so the next write attempt could be made. |
| 336 |
zcopy_enobuf_state_ = OptMemState::kOpen; |
| 337 |
return true; |
| 338 |
} else if (zcopy_enobuf_state_ == OptMemState::kOpen) { |
| 339 |
// No need to mark the fd as writable because the previous write |
| 340 |
// attempt did not encounter ENOBUFS. |
| 341 |
return false; |
| 342 |
} else { |
| 343 |
// This state should never be reached because it implies that the previous |
| 344 |
// state was CHECK and is_in_write is false. This means that after the |
| 345 |
// previous sendmsg returned and set is_in_write to false, it did |
| 346 |
// not update the z-copy change from CHECK to OPEN. |
| 347 |
GPR_ASSERT(false && "OMem state error!"); |
| 348 |
} |
| 349 |
} |
| 350 |
|
| 351 |
// Expected to be called by the thread calling sendmsg after the syscall |
| 352 |
// invocation. is complete. If an ENOBUF is seen, it checks if the error |
| 353 |
// handler (Tx0cp completions) has already run and free'ed up some OMem. It |
| 354 |
// returns true indicating that the write can be attempted again immediately. |
| 355 |
// If ENOBUFS was seen but no Tx0cp completions have been received between the |
| 356 |
// sendmsg() and us taking this lock, then tcp_omem is still full from our |
| 357 |
// point of view. Therefore, we do not signal that the socket is writeable |
| 358 |
// with respect to the availability of tcp_omem. Therefore the function |
| 359 |
// returns false. This indicates that another write should not be attempted |
| 360 |
// immediately and the calling thread should wait until the socket is writable |
| 361 |
// again. If ENOBUFS was not seen, then again return false because the next |
| 362 |
// write should be attempted only when the socket is writable again. |
| 363 |
// |
| 364 |
// Please refer to the STATE TRANSITION DIAGRAM below for more details. |
| 365 |
// |
| 366 |
bool UpdateZeroCopyOptMemStateAfterSend(bool seen_enobuf, bool& constrained) { |
| 367 |
grpc_core::MutexLock lock(&mu_); |
| 368 |
is_in_write_ = false; |
| 369 |
constrained = false; |
| 370 |
if (seen_enobuf) { |
| 371 |
if (ctx_lookup_.size() == 1) { |
| 372 |
// There is no un-acked z-copy record. Set constrained to true to |
| 373 |
// indicate that we are re-source constrained because we're seeing |
| 374 |
// ENOBUFS even for the first record. This indicates that either |
| 375 |
// the process does not have hard memlock ulimit or RLIMIT_MEMLOCK |
| 376 |
// configured correctly. |
| 377 |
constrained = true; |
| 378 |
} |
| 379 |
if (zcopy_enobuf_state_ == OptMemState::kCheck) { |
| 380 |
zcopy_enobuf_state_ = OptMemState::kOpen; |
| 381 |
return true; |
| 382 |
} else { |
| 383 |
zcopy_enobuf_state_ = OptMemState::kFull; |
| 384 |
} |
| 385 |
} else if (zcopy_enobuf_state_ != OptMemState::kOpen) { |
| 386 |
zcopy_enobuf_state_ = OptMemState::kOpen; |
| 387 |
} |
| 388 |
return false; |
| 389 |
} |
| 390 |
|
| 391 |
private: |
| 392 |
// STATE TRANSITION DIAGRAM |
| 393 |
// |
| 394 |
// sendmsg succeeds Tx-zero copy succeeds and there is no active sendmsg |
| 395 |
// ----<<--+ +------<<-------------------------------------+ |
| 396 |
// | | | | |
| 397 |
// | | v sendmsg returns ENOBUFS | |
| 398 |
// +-----> OPEN ------------->>-------------------------> FULL |
| 399 |
// ^ | |
| 400 |
// | | |
| 401 |
// | sendmsg completes | |
| 402 |
// +----<<---------- CHECK <-------<<-------------+ |
| 403 |
// Tx-zero copy succeeds and there is |
| 404 |
// an active sendmsg |
| 405 |
// |
| 406 |
// OptMem (controlled by the kernel option optmem_max) refers to the memory |
| 407 |
// allocated to the cmsg list maintained by the kernel that contains "extra" |
| 408 |
// packet information like SCM_RIGHTS or IP_TTL. Increasing this option allows |
| 409 |
// the kernel to allocate more memory as needed for more control messages that |
| 410 |
// need to be sent for each socket connected. Each tx zero copy sendmsg has |
| 411 |
// a corresponding entry added into the Optmem queue. The entry is popped |
| 412 |
// from the Optmem queue when the zero copy send is complete. |
| 413 |
enum class OptMemState : int8_t { |
| 414 |
kOpen, // Everything is clear and omem is not full. |
| 415 |
kFull, // The last sendmsg() has returned with an errno of ENOBUFS. |
| 416 |
kCheck, // Error queue is read while is_in_write_ was true, so we should |
| 417 |
// check this state after the sendmsg. |
| 418 |
}; |
| 419 |
|
| 420 |
TcpZerocopySendRecord* ReleaseSendRecordLocked(uint32_t seq) |
| 421 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { |
| 422 |
auto iter = ctx_lookup_.find(seq); |
| 423 |
GPR_DEBUG_ASSERT(iter != ctx_lookup_.end()); |
| 424 |
TcpZerocopySendRecord* record = iter->second; |
| 425 |
ctx_lookup_.erase(iter); |
| 426 |
return record; |
| 427 |
} |
| 428 |
|
| 429 |
TcpZerocopySendRecord* TryGetSendRecordLocked() |
| 430 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { |
| 431 |
if (shutdown_.load(std::memory_order_acquire)) { |
| 432 |
return nullptr; |
| 433 |
} |
| 434 |
if (free_send_records_size_ == 0) { |
| 435 |
return nullptr; |
| 436 |
} |
| 437 |
free_send_records_size_--; |
| 438 |
return free_send_records_[free_send_records_size_]; |
| 439 |
} |
| 440 |
|
| 441 |
void PutSendRecordLocked(TcpZerocopySendRecord* record) |
| 442 |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { |
| 443 |
GPR_DEBUG_ASSERT(free_send_records_size_ < max_sends_); |
| 444 |
free_send_records_[free_send_records_size_] = record; |
| 445 |
free_send_records_size_++; |
| 446 |
} |
| 447 |
|
| 448 |
TcpZerocopySendRecord* send_records_ ABSL_GUARDED_BY(mu_); |
| 449 |
TcpZerocopySendRecord** free_send_records_ ABSL_GUARDED_BY(mu_); |
| 450 |
int max_sends_; |
| 451 |
int free_send_records_size_ ABSL_GUARDED_BY(mu_); |
| 452 |
grpc_core::Mutex mu_; |
| 453 |
uint32_t last_send_ = 0; |
| 454 |
std::atomic<bool> shutdown_{false}; |
| 455 |
bool enabled_ = false; |
| 456 |
size_t threshold_bytes_ = kDefaultSendBytesThreshold; |
| 457 |
absl::flat_hash_map<uint32_t, TcpZerocopySendRecord*> ctx_lookup_ |
| 458 |
ABSL_GUARDED_BY(mu_); |
| 459 |
bool memory_limited_ = false; |
| 460 |
bool is_in_write_ ABSL_GUARDED_BY(mu_) = false; |
| 461 |
OptMemState zcopy_enobuf_state_ ABSL_GUARDED_BY(mu_) = OptMemState::kOpen; |
| 462 |
}; |
| 463 |
|
| 464 |
class PosixEndpointImpl : public grpc_core::RefCounted<PosixEndpointImpl> { |
| 465 |
public: |
| 466 |
PosixEndpointImpl( |
| 467 |
EventHandle* handle, PosixEngineClosure* on_done, |
| 468 |
std::shared_ptr<grpc_event_engine::experimental::EventEngine> engine, |
| 469 |
grpc_event_engine::experimental::MemoryAllocator&& allocator, |
| 470 |
const PosixTcpOptions& options); |
| 471 |
~PosixEndpointImpl() override; |
| 472 |
void Read( |
| 473 |
absl::AnyInvocable<void(absl::Status)> on_read, |
| 474 |
grpc_event_engine::experimental::SliceBuffer* buffer, |
| 475 |
const grpc_event_engine::experimental::EventEngine::Endpoint::ReadArgs* |
| 476 |
args); |
| 477 |
void Write( |
| 478 |
absl::AnyInvocable<void(absl::Status)> on_writable, |
| 479 |
grpc_event_engine::experimental::SliceBuffer* data, |
| 480 |
const grpc_event_engine::experimental::EventEngine::Endpoint::WriteArgs* |
| 481 |
args); |
| 482 |
const grpc_event_engine::experimental::EventEngine::ResolvedAddress& |
| 483 |
GetPeerAddress() const { |
| 484 |
return peer_address_; |
| 485 |
} |
| 486 |
const grpc_event_engine::experimental::EventEngine::ResolvedAddress& |
| 487 |
GetLocalAddress() const { |
| 488 |
return local_address_; |
| 489 |
} |
| 490 |
|
| 491 |
void MaybeShutdown(absl::Status why); |
| 492 |
|
| 493 |
private: |
| 494 |
void UpdateRcvLowat() ABSL_EXCLUSIVE_LOCKS_REQUIRED(read_mu_); |
| 495 |
void HandleWrite(absl::Status status); |
| 496 |
void HandleError(absl::Status status); |
| 497 |
void HandleRead(absl::Status status); |
| 498 |
void MaybeMakeReadSlices() ABSL_EXCLUSIVE_LOCKS_REQUIRED(read_mu_); |
| 499 |
bool TcpDoRead(absl::Status& status) ABSL_EXCLUSIVE_LOCKS_REQUIRED(read_mu_); |
| 500 |
void FinishEstimate(); |
| 501 |
void AddToEstimate(size_t bytes); |
| 502 |
void MaybePostReclaimer() ABSL_EXCLUSIVE_LOCKS_REQUIRED(read_mu_); |
| 503 |
void PerformReclamation() ABSL_LOCKS_EXCLUDED(read_mu_); |
| 504 |
// Zero copy related helper methods. |
| 505 |
TcpZerocopySendRecord* TcpGetSendZerocopyRecord( |
| 506 |
grpc_event_engine::experimental::SliceBuffer& buf); |
| 507 |
bool DoFlushZerocopy(TcpZerocopySendRecord* record, absl::Status& status); |
| 508 |
bool TcpFlushZerocopy(TcpZerocopySendRecord* record, absl::Status& status); |
| 509 |
bool TcpFlush(absl::Status& status); |
| 510 |
void TcpShutdownTracedBufferList(); |
| 511 |
void UnrefMaybePutZerocopySendRecord(TcpZerocopySendRecord* record); |
| 512 |
void ZerocopyDisableAndWaitForRemaining(); |
| 513 |
bool WriteWithTimestamps(struct msghdr* msg, size_t sending_length, |
| 514 |
ssize_t* sent_length, int* saved_errno, |
| 515 |
int additional_flags); |
| 516 |
#ifdef GRPC_LINUX_ERRQUEUE |
| 517 |
bool ProcessErrors(); |
| 518 |
// Reads a cmsg to process zerocopy control messages. |
| 519 |
void ProcessZerocopy(struct cmsghdr* cmsg); |
| 520 |
// Reads a cmsg to derive timestamps from the control messages. |
| 521 |
struct cmsghdr* ProcessTimestamp(msghdr* msg, struct cmsghdr* cmsg); |
| 522 |
#endif // GRPC_LINUX_ERRQUEUE |
| 523 |
grpc_core::Mutex read_mu_; |
| 524 |
PosixSocketWrapper sock_; |
| 525 |
int fd_; |
| 526 |
bool is_first_read_ = true; |
| 527 |
bool has_posted_reclaimer_ ABSL_GUARDED_BY(read_mu_) = false; |
| 528 |
double target_length_; |
| 529 |
int min_read_chunk_size_; |
| 530 |
int max_read_chunk_size_; |
| 531 |
int set_rcvlowat_ = 0; |
| 532 |
double bytes_read_this_round_ = 0; |
| 533 |
std::atomic<int> ref_count_{1}; |
| 534 |
|
| 535 |
// garbage after the last read. |
| 536 |
grpc_event_engine::experimental::SliceBuffer last_read_buffer_; |
| 537 |
|
| 538 |
grpc_event_engine::experimental::SliceBuffer* incoming_buffer_ |
| 539 |
ABSL_GUARDED_BY(read_mu_) = nullptr; |
| 540 |
// bytes pending on the socket from the last read. |
| 541 |
int inq_ = 1; |
| 542 |
// cache whether kernel supports inq. |
| 543 |
bool inq_capable_ = false; |
| 544 |
|
| 545 |
grpc_event_engine::experimental::SliceBuffer* outgoing_buffer_ = nullptr; |
| 546 |
// byte within outgoing_buffer's slices[0] to write next. |
| 547 |
size_t outgoing_byte_idx_ = 0; |
| 548 |
|
| 549 |
PosixEngineClosure* on_read_ = nullptr; |
| 550 |
PosixEngineClosure* on_write_ = nullptr; |
| 551 |
PosixEngineClosure* on_error_ = nullptr; |
| 552 |
PosixEngineClosure* on_done_ = nullptr; |
| 553 |
absl::AnyInvocable<void(absl::Status)> read_cb_ ABSL_GUARDED_BY(read_mu_); |
| 554 |
absl::AnyInvocable<void(absl::Status)> write_cb_; |
| 555 |
|
| 556 |
grpc_event_engine::experimental::EventEngine::ResolvedAddress peer_address_; |
| 557 |
grpc_event_engine::experimental::EventEngine::ResolvedAddress local_address_; |
| 558 |
|
| 559 |
grpc_core::MemoryOwner memory_owner_; |
| 560 |
grpc_core::MemoryAllocator::Reservation self_reservation_; |
| 561 |
|
| 562 |
void* outgoing_buffer_arg_ = nullptr; |
| 563 |
|
| 564 |
// A counter which starts at 0. It is initialized the first time the socket |
| 565 |
// options for collecting timestamps are set, and is incremented with each |
| 566 |
// byte sent. |
| 567 |
int bytes_counter_ = -1; |
| 568 |
// True if timestamping options are set on the socket. |
| 569 |
#ifdef GRPC_LINUX_ERRQUEUE |
| 570 |
bool socket_ts_enabled_ = false; |
| 571 |
#endif // GRPC_LINUX_ERRQUEUE |
| 572 |
// Cache whether we can set timestamping options |
| 573 |
bool ts_capable_ = true; |
| 574 |
// Set to 1 if we do not want to be notified on errors anymore. |
| 575 |
std::atomic<bool> stop_error_notification_{false}; |
| 576 |
std::unique_ptr<TcpZerocopySendCtx> tcp_zerocopy_send_ctx_; |
| 577 |
TcpZerocopySendRecord* current_zerocopy_send_ = nullptr; |
| 578 |
// A hint from upper layers specifying the minimum number of bytes that need |
| 579 |
// to be read to make meaningful progress. |
| 580 |
int min_progress_size_ = 1; |
| 581 |
TracedBufferList traced_buffers_; |
| 582 |
// The handle is owned by the PosixEndpointImpl object. |
| 583 |
EventHandle* handle_; |
| 584 |
PosixEventPoller* poller_; |
| 585 |
std::shared_ptr<grpc_event_engine::experimental::EventEngine> engine_; |
| 586 |
}; |
| 587 |
|
| 588 |
class PosixEndpoint |
| 589 |
: public grpc_event_engine::experimental::EventEngine::Endpoint { |
| 590 |
public: |
| 591 |
PosixEndpoint( |
| 592 |
EventHandle* handle, PosixEngineClosure* on_shutdown, |
| 593 |
std::shared_ptr<grpc_event_engine::experimental::EventEngine> engine, |
| 594 |
grpc_event_engine::experimental::MemoryAllocator&& allocator, |
| 595 |
const PosixTcpOptions& options) |
| 596 |
: impl_(new PosixEndpointImpl(handle, on_shutdown, std::move(engine), |
| 597 |
std::move(allocator), options)) {} |
| 598 |
|
| 599 |
void Read( |
| 600 |
absl::AnyInvocable<void(absl::Status)> on_read, |
| 601 |
grpc_event_engine::experimental::SliceBuffer* buffer, |
| 602 |
const grpc_event_engine::experimental::EventEngine::Endpoint::ReadArgs* |
| 603 |
args) override { |
| 604 |
impl_->Read(std::move(on_read), buffer, args); |
| 605 |
} |
| 606 |
|
| 607 |
void Write( |
| 608 |
absl::AnyInvocable<void(absl::Status)> on_writable, |
| 609 |
grpc_event_engine::experimental::SliceBuffer* data, |
| 610 |
const grpc_event_engine::experimental::EventEngine::Endpoint::WriteArgs* |
| 611 |
args) override { |
| 612 |
impl_->Write(std::move(on_writable), data, args); |
| 613 |
} |
| 614 |
|
| 615 |
const grpc_event_engine::experimental::EventEngine::ResolvedAddress& |
| 616 |
GetPeerAddress() const override { |
| 617 |
return impl_->GetPeerAddress(); |
| 618 |
} |
| 619 |
const grpc_event_engine::experimental::EventEngine::ResolvedAddress& |
| 620 |
GetLocalAddress() const override { |
| 621 |
return impl_->GetLocalAddress(); |
| 622 |
} |
| 623 |
|
| 624 |
~PosixEndpoint() override { |
| 625 |
impl_->MaybeShutdown(absl::InternalError("Endpoint closing")); |
| 626 |
} |
| 627 |
|
| 628 |
private: |
| 629 |
PosixEndpointImpl* impl_; |
| 630 |
}; |
| 631 |
|
| 632 |
#else // GRPC_POSIX_SOCKET_TCP |
| 633 |
|
| 634 |
class PosixEndpoint |
| 635 |
: public grpc_event_engine::experimental::EventEngine::Endpoint { |
| 636 |
public: |
| 637 |
PosixEndpoint() = default; |
| 638 |
|
| 639 |
void Read(absl::AnyInvocable<void(absl::Status)> /*on_read*/, |
| 640 |
grpc_event_engine::experimental::SliceBuffer* /*buffer*/, |
| 641 |
const grpc_event_engine::experimental::EventEngine::Endpoint:: |
| 642 |
ReadArgs* /*args*/) override { |
| 643 |
GPR_ASSERT(false && "PosixEndpoint::Read not supported on this platform"); |
| 644 |
} |
| 645 |
|
| 646 |
void Write(absl::AnyInvocable<void(absl::Status)> /*on_writable*/, |
| 647 |
grpc_event_engine::experimental::SliceBuffer* /*data*/, |
| 648 |
const grpc_event_engine::experimental::EventEngine::Endpoint:: |
| 649 |
WriteArgs* /*args*/) override { |
| 650 |
GPR_ASSERT(false && "PosixEndpoint::Write not supported on this platform"); |
| 651 |
} |
| 652 |
|
| 653 |
const grpc_event_engine::experimental::EventEngine::ResolvedAddress& |
| 654 |
GetPeerAddress() const override { |
| 655 |
GPR_ASSERT(false && |
| 656 |
"PosixEndpoint::GetPeerAddress not supported on this platform"); |
| 657 |
} |
| 658 |
const grpc_event_engine::experimental::EventEngine::ResolvedAddress& |
| 659 |
GetLocalAddress() const override { |
| 660 |
GPR_ASSERT(false && |
| 661 |
"PosixEndpoint::GetLocalAddress not supported on this platform"); |
| 662 |
} |
| 663 |
|
| 664 |
~PosixEndpoint() override = default; |
| 665 |
}; |
| 666 |
|
| 667 |
#endif // GRPC_POSIX_SOCKET_TCP |
| 668 |
|
| 669 |
// Create a PosixEndpoint. |
| 670 |
// A shared_ptr of the EventEngine is passed to the endpoint to ensure that |
| 671 |
// the event engine is alive for the lifetime of the endpoint. The ownership |
| 672 |
// of the EventHandle is transferred to the endpoint. |
| 673 |
std::unique_ptr<PosixEndpoint> CreatePosixEndpoint( |
| 674 |
EventHandle* handle, PosixEngineClosure* on_shutdown, |
| 675 |
std::shared_ptr<EventEngine> engine, |
| 676 |
grpc_event_engine::experimental::MemoryAllocator&& allocator, |
| 677 |
const PosixTcpOptions& options); |
| 678 |
|
| 679 |
} // namespace posix_engine |
| 680 |
} // namespace grpc_event_engine |
| 681 |
|
| 682 |
#endif // GRPC_CORE_LIB_EVENT_ENGINE_POSIX_ENGINE_POSIX_ENDPOINT_H |