Debian Codegraph @

src/core/lib/iomgr/tcp_posix.cc

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #include <grpc/impl/codegen/grpc_types.h>
22
•23 #include "absl/base/thread_annotations.h"
24 #include "absl/status/status.h"
25 #include "absl/strings/str_cat.h"
26 #include "absl/strings/string_view.h"
27 #include "absl/types/optional.h"
28
29 #include "src/core/lib/gprpp/global_config_generic.h"
30 #include "src/core/lib/iomgr/exec_ctx.h"
31 #include "src/core/lib/iomgr/port.h"
32
33 #ifdef GRPC_POSIX_SOCKET_TCP
34
35 #include <errno.h>
36 #include <limits.h>
37 #include <netinet/in.h>
38 #include <netinet/tcp.h>
39 #include <stdbool.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <sys/socket.h>
44 #include <sys/types.h>
45 #include <unistd.h>
46
47 #include <algorithm>
48 #include <unordered_map>
49
50 #include <grpc/slice.h>
51 #include <grpc/support/alloc.h>
52 #include <grpc/support/log.h>
53 #include <grpc/support/string_util.h>
54 #include <grpc/support/sync.h>
55 #include <grpc/support/time.h>
56
57 #include "src/core/lib/address_utils/sockaddr_utils.h"
58 #include "src/core/lib/debug/event_log.h"
59 #include "src/core/lib/debug/stats.h"
60 #include "src/core/lib/debug/stats_data.h"
61 #include "src/core/lib/debug/trace.h"
62 #include "src/core/lib/experiments/experiments.h"
63 #include "src/core/lib/gpr/string.h"
64 #include "src/core/lib/gpr/useful.h"
65 #include "src/core/lib/gprpp/strerror.h"
66 #include "src/core/lib/gprpp/sync.h"
67 #include "src/core/lib/iomgr/buffer_list.h"
68 #include "src/core/lib/iomgr/ev_posix.h"
69 #include "src/core/lib/iomgr/executor.h"
70 #include "src/core/lib/iomgr/socket_utils_posix.h"
71 #include "src/core/lib/iomgr/tcp_posix.h"
72 #include "src/core/lib/resource_quota/api.h"
73 #include "src/core/lib/resource_quota/memory_quota.h"
74 #include "src/core/lib/resource_quota/trace.h"
75 #include "src/core/lib/slice/slice_internal.h"
76 #include "src/core/lib/slice/slice_string_helpers.h"
77
78 #ifndef SOL_TCP
79 #define SOL_TCP IPPROTO_TCP
80 #endif
81
82 #ifndef TCP_INQ
83 #define TCP_INQ 36
84 #define TCP_CM_INQ TCP_INQ
85 #endif
86
87 #ifdef GRPC_HAVE_MSG_NOSIGNAL
88 #define SENDMSG_FLAGS MSG_NOSIGNAL
89 #else
90 #define SENDMSG_FLAGS 0
91 #endif
92
93 // TCP zero copy sendmsg flag.
94 // NB: We define this here as a fallback in case we're using an older set of
95 // library headers that has not defined MSG_ZEROCOPY. Since this constant is
96 // part of the kernel, we are guaranteed it will never change/disagree so
97 // defining it here is safe.
98 #ifndef MSG_ZEROCOPY
99 #define MSG_ZEROCOPY 0x4000000
100 #endif
101
102 #ifdef GRPC_MSG_IOVLEN_TYPE
103 typedef GRPC_MSG_IOVLEN_TYPE msg_iovlen_type;
104 #else
105 typedef size_t msg_iovlen_type;
106 #endif
107
108 extern grpc_core::TraceFlag grpc_tcp_trace;
109
110 namespace grpc_core {
111
112 class TcpZerocopySendRecord {
113 public:
114 TcpZerocopySendRecord() { grpc_slice_buffer_init(&buf_); }
115
116 ~TcpZerocopySendRecord() {
117 AssertEmpty();
118 grpc_slice_buffer_destroy(&buf_);
119 }
120
121 // Given the slices that we wish to send, and the current offset into the
122 // slice buffer (indicating which have already been sent), populate an iovec
123 // array that will be used for a zerocopy enabled sendmsg().
124 msg_iovlen_type PopulateIovs(size_t* unwind_slice_idx,
125 size_t* unwind_byte_idx, size_t* sending_length,
126 iovec* iov);
127
128 // A sendmsg() may not be able to send the bytes that we requested at this
129 // time, returning EAGAIN (possibly due to backpressure). In this case,
130 // unwind the offset into the slice buffer so we retry sending these bytes.
131 void UnwindIfThrottled(size_t unwind_slice_idx, size_t unwind_byte_idx) {
132 out_offset_.byte_idx = unwind_byte_idx;
133 out_offset_.slice_idx = unwind_slice_idx;
134 }
135
136 // Update the offset into the slice buffer based on how much we wanted to sent
137 // vs. what sendmsg() actually sent (which may be lower, possibly due to
138 // backpressure).
139 void UpdateOffsetForBytesSent(size_t sending_length, size_t actually_sent);
140
141 // Indicates whether all underlying data has been sent or not.
142 bool AllSlicesSent() { return out_offset_.slice_idx == buf_.count; }
143
144 // Reset this structure for a new tcp_write() with zerocopy.
145 void PrepareForSends(grpc_slice_buffer* slices_to_send) {
146 AssertEmpty();
147 out_offset_.slice_idx = 0;
148 out_offset_.byte_idx = 0;
149 grpc_slice_buffer_swap(slices_to_send, &buf_);
150 Ref();
151 }
152
153 // References: 1 reference per sendmsg(), and 1 for the tcp_write().
154 void Ref() { ref_.fetch_add(1, std::memory_order_relaxed); }
155
156 // Unref: called when we get an error queue notification for a sendmsg(), if a
157 // sendmsg() failed or when tcp_write() is done.
158 bool Unref() {
159 const intptr_t prior = ref_.fetch_sub(1, std::memory_order_acq_rel);
160 GPR_DEBUG_ASSERT(prior > 0);
161 if (prior == 1) {
162 AllSendsComplete();
163 return true;
164 }
165 return false;
166 }
167
168 private:
169 struct OutgoingOffset {
170 size_t slice_idx = 0;
171 size_t byte_idx = 0;
172 };
173
174 void AssertEmpty() {
175 GPR_DEBUG_ASSERT(buf_.count == 0);
176 GPR_DEBUG_ASSERT(buf_.length == 0);
177 GPR_DEBUG_ASSERT(ref_.load(std::memory_order_relaxed) == 0);
178 }
179
180 // When all sendmsg() calls associated with this tcp_write() have been
181 // completed (ie. we have received the notifications for each sequence number
182 // for each sendmsg()) and all reference counts have been dropped, drop our
183 // reference to the underlying data since we no longer need it.
184 void AllSendsComplete() {
185 GPR_DEBUG_ASSERT(ref_.load(std::memory_order_relaxed) == 0);
186 grpc_slice_buffer_reset_and_unref(&buf_);
187 }
188
189 grpc_slice_buffer buf_;
190 std::atomic<intptr_t> ref_{0};
191 OutgoingOffset out_offset_;
192 };
193
194 class TcpZerocopySendCtx {
195 public:
196 static constexpr int kDefaultMaxSends = 4;
197 static constexpr size_t kDefaultSendBytesThreshold = 16 * 1024; // 16KB
198
199 explicit TcpZerocopySendCtx(
200 int max_sends = kDefaultMaxSends,
201 size_t send_bytes_threshold = kDefaultSendBytesThreshold)
202 : max_sends_(max_sends),
203 free_send_records_size_(max_sends),
204 threshold_bytes_(send_bytes_threshold) {
205 send_records_ = static_cast<TcpZerocopySendRecord*>(
206 gpr_malloc(max_sends * sizeof(*send_records_)));
207 free_send_records_ = static_cast<TcpZerocopySendRecord**>(
208 gpr_malloc(max_sends * sizeof(*free_send_records_)));
209 if (send_records_ == nullptr || free_send_records_ == nullptr) {
210 gpr_free(send_records_);
211 gpr_free(free_send_records_);
212 gpr_log(GPR_INFO, "Disabling TCP TX zerocopy due to memory pressure.\n");
213 memory_limited_ = true;
214 } else {
215 for (int idx = 0; idx < max_sends_; ++idx) {
216 new (send_records_ + idx) TcpZerocopySendRecord();
217 free_send_records_[idx] = send_records_ + idx;
218 }
219 }
220 }
221
222 ~TcpZerocopySendCtx() {
223 if (send_records_ != nullptr) {
224 for (int idx = 0; idx < max_sends_; ++idx) {
225 send_records_[idx].~TcpZerocopySendRecord();
226 }
227 }
228 gpr_free(send_records_);
229 gpr_free(free_send_records_);
230 }
231
232 // True if we were unable to allocate the various bookkeeping structures at
233 // transport initialization time. If memory limited, we do not zerocopy.
234 bool memory_limited() const { return memory_limited_; }
235
236 // TCP send zerocopy maintains an implicit sequence number for every
237 // successful sendmsg() with zerocopy enabled; the kernel later gives us an
238 // error queue notification with this sequence number indicating that the
239 // underlying data buffers that we sent can now be released. Once that
240 // notification is received, we can release the buffers associated with this
241 // zerocopy send record. Here, we associate the sequence number with the data
242 // buffers that were sent with the corresponding call to sendmsg().
243 void NoteSend(TcpZerocopySendRecord* record) {
244 record->Ref();
245 {
246 MutexLock guard(&lock_);
247 is_in_write_ = true;
248 AssociateSeqWithSendRecordLocked(last_send_, record);
249 }
250 ++last_send_;
251 }
252
253 // If sendmsg() actually failed, though, we need to revert the sequence number
254 // that we speculatively bumped before calling sendmsg(). Note that we bump
255 // this sequence number and perform relevant bookkeeping (see: NoteSend())
256 // *before* calling sendmsg() since, if we called it *after* sendmsg(), then
257 // there is a possible race with the release notification which could occur on
258 // another thread before we do the necessary bookkeeping. Hence, calling
259 // NoteSend() *before* sendmsg() and implementing an undo function is needed.
260 void UndoSend() {
261 --last_send_;
262 if (ReleaseSendRecord(last_send_)->Unref()) {
263 // We should still be holding the ref taken by tcp_write().
264 GPR_DEBUG_ASSERT(0);
265 }
266 }
267
268 // Simply associate this send record (and the underlying sent data buffers)
269 // with the implicit sequence number for this zerocopy sendmsg().
270 void AssociateSeqWithSendRecordLocked(uint32_t seq,
271 TcpZerocopySendRecord* record) {
272 ctx_lookup_.emplace(seq, record);
273 }
274
275 // Get a send record for a send that we wish to do with zerocopy.
276 TcpZerocopySendRecord* GetSendRecord() {
277 MutexLock guard(&lock_);
278 return TryGetSendRecordLocked();
279 }
280
281 // A given send record corresponds to a single tcp_write() with zerocopy
282 // enabled. This can result in several sendmsg() calls to flush all of the
283 // data to wire. Each sendmsg() takes a reference on the
284 // TcpZerocopySendRecord, and corresponds to a single sequence number.
285 // ReleaseSendRecord releases a reference on TcpZerocopySendRecord for a
286 // single sequence number. This is called either when we receive the relevant
287 // error queue notification (saying that we can discard the underlying
288 // buffers for this sendmsg()) is received from the kernel - or, in case
289 // sendmsg() was unsuccessful to begin with.
290 TcpZerocopySendRecord* ReleaseSendRecord(uint32_t seq) {
291 MutexLock guard(&lock_);
292 return ReleaseSendRecordLocked(seq);
293 }
294
295 // After all the references to a TcpZerocopySendRecord are released, we can
296 // add it back to the pool (of size max_sends_). Note that we can only have
297 // max_sends_ tcp_write() instances with zerocopy enabled in flight at the
298 // same time.
299 void PutSendRecord(TcpZerocopySendRecord* record) {
300 GPR_DEBUG_ASSERT(record >= send_records_ &&
301 record < send_records_ + max_sends_);
302 MutexLock guard(&lock_);
303 PutSendRecordLocked(record);
304 }
305
306 // Indicate that we are disposing of this zerocopy context. This indicator
307 // will prevent new zerocopy writes from being issued.
308 void Shutdown() { shutdown_.store(true, std::memory_order_release); }
309
310 // Indicates that there are no inflight tcp_write() instances with zerocopy
311 // enabled.
312 bool AllSendRecordsEmpty() {
313 MutexLock guard(&lock_);
314 return free_send_records_size_ == max_sends_;
315 }
316
317 bool enabled() const { return enabled_; }
318
319 void set_enabled(bool enabled) {
320 GPR_DEBUG_ASSERT(!enabled || !memory_limited());
321 enabled_ = enabled;
322 }
323
324 // Only use zerocopy if we are sending at least this many bytes. The
325 // additional overhead of reading the error queue for notifications means that
326 // zerocopy is not useful for small transfers.
327 size_t threshold_bytes() const { return threshold_bytes_; }
328
329 // Expected to be called by handler reading messages from the err queue.
330 // It is used to indicate that some OMem meory is now available. It returns
331 // true to tell the caller to mark the file descriptor as immediately
332 // writable.
333 //
334 // If a write is currently in progress on the socket (ie. we have issued a
335 // sendmsg() and are about to check its return value) then we set omem state
336 // to CHECK to make the sending thread know that some tcp_omem was
337 // concurrently freed even if sendmsg() returns ENOBUFS. In this case, since
338 // there is already an active send thread, we do not need to mark the
339 // socket writeable, so we return false.
340 //
341 // If there was no write in progress on the socket, and the socket was not
342 // marked as FULL, then we need not mark the socket writeable now that some
343 // tcp_omem memory is freed since it was not considered as blocked on
344 // tcp_omem to begin with. So in this case, return false.
345 //
346 // But, if a write was not in progress and the omem state was FULL, then we
347 // need to mark the socket writeable since it is no longer blocked by
348 // tcp_omem. In this case, return true.
349 //
350 // Please refer to the STATE TRANSITION DIAGRAM below for more details.
351 //
352 bool UpdateZeroCopyOMemStateAfterFree() {
353 MutexLock guard(&lock_);
354 if (is_in_write_) {
355 zcopy_enobuf_state_ = OMemState::CHECK;
356 return false;
357 }
358 GPR_DEBUG_ASSERT(zcopy_enobuf_state_ != OMemState::CHECK);
359 if (zcopy_enobuf_state_ == OMemState::FULL) {
360 // A previous sendmsg attempt was blocked by ENOBUFS. Return true to
361 // mark the fd as writable so the next write attempt could be made.
362 zcopy_enobuf_state_ = OMemState::OPEN;
363 return true;
364 } else if (zcopy_enobuf_state_ == OMemState::OPEN) {
365 // No need to mark the fd as writable because the previous write
366 // attempt did not encounter ENOBUFS.
367 return false;
368 } else {
369 // This state should never be reached because it implies that the previous
370 // state was CHECK and is_in_write is false. This means that after the
371 // previous sendmsg returned and set is_in_write to false, it did
372 // not update the z-copy change from CHECK to OPEN.
373 GPR_ASSERT(false && "OMem state error!");
374 }
375 }
376
377 // Expected to be called by the thread calling sendmsg after the syscall
378 // invocation. is complete. If an ENOBUF is seen, it checks if the error
379 // handler (Tx0cp completions) has already run and free'ed up some OMem. It
380 // returns true indicating that the write can be attempted again immediately.
381 // If ENOBUFS was seen but no Tx0cp completions have been received between the
382 // sendmsg() and us taking this lock, then tcp_omem is still full from our
383 // point of view. Therefore, we do not signal that the socket is writeable
384 // with respect to the availability of tcp_omem. Therefore the function
385 // returns false. This indicates that another write should not be attempted
386 // immediately and the calling thread should wait until the socket is writable
387 // again. If ENOBUFS was not seen, then again return false because the next
388 // write should be attempted only when the socket is writable again.
389 //
390 // Please refer to the STATE TRANSITION DIAGRAM below for more details.
391 //
392 bool UpdateZeroCopyOMemStateAfterSend(bool seen_enobuf) {
393 MutexLock guard(&lock_);
394 is_in_write_ = false;
395 if (seen_enobuf) {
396 if (zcopy_enobuf_state_ == OMemState::CHECK) {
397 zcopy_enobuf_state_ = OMemState::OPEN;
398 return true;
399 } else {
400 zcopy_enobuf_state_ = OMemState::FULL;
401 }
402 } else if (zcopy_enobuf_state_ != OMemState::OPEN) {
403 zcopy_enobuf_state_ = OMemState::OPEN;
404 }
405 return false;
406 }
407
408 private:
409 // STATE TRANSITION DIAGRAM
410 //
411 // sendmsg succeeds Tx-zero copy succeeds and there is no active sendmsg
412 // ----<<--+ +------<<-------------------------------------+
413 // | | | |
414 // | | v sendmsg returns ENOBUFS |
415 // +-----> OPEN ------------->>-------------------------> FULL
416 // ^ |
417 // | |
418 // | sendmsg completes |
419 // +----<<---------- CHECK <-------<<-------------+
420 // Tx-zero copy succeeds and there is
421 // an active sendmsg
422 //
423 enum class OMemState : int8_t {
424 OPEN, // Everything is clear and omem is not full.
425 FULL, // The last sendmsg() has returned with an errno of ENOBUFS.
426 CHECK, // Error queue is read while is_in_write_ was true, so we should
427 // check this state after the sendmsg.
428 };
429
430 TcpZerocopySendRecord* ReleaseSendRecordLocked(uint32_t seq) {
431 auto iter = ctx_lookup_.find(seq);
432 GPR_DEBUG_ASSERT(iter != ctx_lookup_.end());
433 TcpZerocopySendRecord* record = iter->second;
434 ctx_lookup_.erase(iter);
435 return record;
436 }
437
438 TcpZerocopySendRecord* TryGetSendRecordLocked() {
439 if (shutdown_.load(std::memory_order_acquire)) {
440 return nullptr;
441 }
442 if (free_send_records_size_ == 0) {
443 return nullptr;
444 }
445 free_send_records_size_--;
446 return free_send_records_[free_send_records_size_];
447 }
448
449 void PutSendRecordLocked(TcpZerocopySendRecord* record) {
450 GPR_DEBUG_ASSERT(free_send_records_size_ < max_sends_);
451 free_send_records_[free_send_records_size_] = record;
452 free_send_records_size_++;
453 }
454
455 TcpZerocopySendRecord* send_records_;
456 TcpZerocopySendRecord** free_send_records_;
457 int max_sends_;
458 int free_send_records_size_;
459 Mutex lock_;
460 uint32_t last_send_ = 0;
461 std::atomic<bool> shutdown_{false};
462 bool enabled_ = false;
463 size_t threshold_bytes_ = kDefaultSendBytesThreshold;
464 std::unordered_map<uint32_t, TcpZerocopySendRecord*> ctx_lookup_;
465 bool memory_limited_ = false;
466 bool is_in_write_ = false;
467 OMemState zcopy_enobuf_state_;
468 };
469
470 } // namespace grpc_core
471
472 using grpc_core::TcpZerocopySendCtx;
473 using grpc_core::TcpZerocopySendRecord;
474
475 namespace {
476
477 struct grpc_tcp {
478 explicit grpc_tcp(const grpc_core::PosixTcpOptions& tcp_options)
479 : min_read_chunk_size(tcp_options.tcp_min_read_chunk_size),
480 max_read_chunk_size(tcp_options.tcp_max_read_chunk_size),
481 tcp_zerocopy_send_ctx(
482 tcp_options.tcp_tx_zerocopy_max_simultaneous_sends,
483 tcp_options.tcp_tx_zerocopy_send_bytes_threshold) {}
484 grpc_endpoint base;
485 grpc_fd* em_fd;
486 int fd;
487 /* Used by the endpoint read function to distinguish the very first read call
488 * from the rest */
489 bool is_first_read;
490 bool has_posted_reclaimer ABSL_GUARDED_BY(read_mu) = false;
491 double target_length;
492 double bytes_read_this_round;
493 grpc_core::RefCount refcount;
494 gpr_atm shutdown_count;
495
496 int min_read_chunk_size;
497 int max_read_chunk_size;
498 int set_rcvlowat = 0;
499
500 /* garbage after the last read */
501 grpc_slice_buffer last_read_buffer;
502
503 grpc_core::Mutex read_mu;
504 grpc_slice_buffer* incoming_buffer ABSL_GUARDED_BY(read_mu) = nullptr;
505 int inq; /* bytes pending on the socket from the last read. */
506 bool inq_capable; /* cache whether kernel supports inq */
507
508 grpc_slice_buffer* outgoing_buffer;
509 /* byte within outgoing_buffer->slices[0] to write next */
510 size_t outgoing_byte_idx;
511
512 grpc_closure* read_cb;
513 grpc_closure* write_cb;
514 grpc_closure* release_fd_cb;
515 int* release_fd;
516
517 grpc_closure read_done_closure;
518 grpc_closure write_done_closure;
519 grpc_closure error_closure;
520
521 std::string peer_string;
522 std::string local_address;
523
524 grpc_core::MemoryOwner memory_owner;
525 grpc_core::MemoryAllocator::Reservation self_reservation;
526
527 grpc_core::TracedBufferList tb_list; /* List of traced buffers */
528
529 /* grpc_endpoint_write takes an argument which if non-null means that the
530 * transport layer wants the TCP layer to collect timestamps for this write.
531 * This arg is forwarded to the timestamps callback function when the ACK
532 * timestamp is received from the kernel. This arg is a (void *) which allows
533 * users of this API to pass in a pointer to any kind of structure. This
534 * structure could actually be a tag or any book-keeping object that the user
535 * can use to distinguish between different traced writes. The only
536 * requirement from the TCP endpoint layer is that this arg should be non-null
537 * if the user wants timestamps for the write. */
538 void* outgoing_buffer_arg;
539 /* A counter which starts at 0. It is initialized the first time the socket
540 * options for collecting timestamps are set, and is incremented with each
541 * byte sent. */
542 int bytes_counter;
543 bool socket_ts_enabled; /* True if timestamping options are set on the socket
544 */
545 bool ts_capable; /* Cache whether we can set timestamping options */
546 gpr_atm stop_error_notification; /* Set to 1 if we do not want to be notified
547 on errors anymore */
548 TcpZerocopySendCtx tcp_zerocopy_send_ctx;
549 TcpZerocopySendRecord* current_zerocopy_send = nullptr;
550
551 int min_progress_size; /* A hint from upper layers specifying the minimum
552 number of bytes that need to be read to make
553 meaningful progress */
554 };
555
556 struct backup_poller {
557 gpr_mu* pollset_mu;
558 grpc_closure run_poller;
559 };
560
561 } // namespace
562
563 static void ZerocopyDisableAndWaitForRemaining(grpc_tcp* tcp);
564
565 #define BACKUP_POLLER_POLLSET(b) ((grpc_pollset*)((b) + 1))
566
567 static grpc_core::Mutex* g_backup_poller_mu = nullptr;
568 static int g_uncovered_notifications_pending
569 ABSL_GUARDED_BY(g_backup_poller_mu);
570 static backup_poller* g_backup_poller ABSL_GUARDED_BY(g_backup_poller_mu);
571
572 static void tcp_handle_read(void* arg /* grpc_tcp */, grpc_error_handle error);
573 static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error_handle error);
574 static void tcp_drop_uncovered_then_handle_write(void* arg /* grpc_tcp */,
575 grpc_error_handle error);
576
577 static void done_poller(void* bp, grpc_error_handle /*error_ignored*/) {
578 backup_poller* p = static_cast<backup_poller*>(bp);
579 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
580 gpr_log(GPR_INFO, "BACKUP_POLLER:%p destroy", p);
581 }
582 grpc_pollset_destroy(BACKUP_POLLER_POLLSET(p));
583 gpr_free(p);
584 }
585
586 static void run_poller(void* bp, grpc_error_handle /*error_ignored*/) {
587 backup_poller* p = static_cast<backup_poller*>(bp);
588 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
589 gpr_log(GPR_INFO, "BACKUP_POLLER:%p run", p);
590 }
591 gpr_mu_lock(p->pollset_mu);
592 grpc_core::Timestamp deadline =
593 grpc_core::Timestamp::Now() + grpc_core::Duration::Seconds(10);
594 GRPC_LOG_IF_ERROR(
595 "backup_poller:pollset_work",
596 grpc_pollset_work(BACKUP_POLLER_POLLSET(p), nullptr, deadline));
597 gpr_mu_unlock(p->pollset_mu);
598 g_backup_poller_mu->Lock();
599 /* last "uncovered" notification is the ref that keeps us polling */
600 if (g_uncovered_notifications_pending == 1) {
601 GPR_ASSERT(g_backup_poller == p);
602 g_backup_poller = nullptr;
603 g_uncovered_notifications_pending = 0;
604 g_backup_poller_mu->Unlock();
605 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
606 gpr_log(GPR_INFO, "BACKUP_POLLER:%p shutdown", p);
607 }
608 grpc_pollset_shutdown(BACKUP_POLLER_POLLSET(p),
609 GRPC_CLOSURE_INIT(&p->run_poller, done_poller, p,
610 grpc_schedule_on_exec_ctx));
611 } else {
612 g_backup_poller_mu->Unlock();
613 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
614 gpr_log(GPR_INFO, "BACKUP_POLLER:%p reschedule", p);
615 }
616 grpc_core::Executor::Run(&p->run_poller, absl::OkStatus(),
617 grpc_core::ExecutorType::DEFAULT,
618 grpc_core::ExecutorJobType::LONG);
619 }
620 }
621
622 static void drop_uncovered(grpc_tcp* /*tcp*/) {
623 int old_count;
624 backup_poller* p;
625 g_backup_poller_mu->Lock();
626 p = g_backup_poller;
627 old_count = g_uncovered_notifications_pending--;
628 g_backup_poller_mu->Unlock();
629 GPR_ASSERT(old_count > 1);
630 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
631 gpr_log(GPR_INFO, "BACKUP_POLLER:%p uncover cnt %d->%d", p, old_count,
632 old_count - 1);
633 }
634 }
635
636 // gRPC API considers a Write operation to be done the moment it clears ‘flow
637 // control’ i.e., not necessarily sent on the wire. This means that the
638 // application MIGHT not call `grpc_completion_queue_next/pluck` in a timely
639 // manner when its `Write()` API is acked.
640 //
641 // We need to ensure that the fd is 'covered' (i.e being monitored by some
642 // polling thread and progress is made) and hence add it to a backup poller here
643 static void cover_self(grpc_tcp* tcp) {
644 backup_poller* p;
645 g_backup_poller_mu->Lock();
646 int old_count = 0;
647 if (g_uncovered_notifications_pending == 0) {
648 g_uncovered_notifications_pending = 2;
649 p = static_cast<backup_poller*>(
650 gpr_zalloc(sizeof(*p) + grpc_pollset_size()));
651 g_backup_poller = p;
652 grpc_pollset_init(BACKUP_POLLER_POLLSET(p), &p->pollset_mu);
653 g_backup_poller_mu->Unlock();
654 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
655 gpr_log(GPR_INFO, "BACKUP_POLLER:%p create", p);
656 }
657 grpc_core::Executor::Run(
658 GRPC_CLOSURE_INIT(&p->run_poller, run_poller, p, nullptr),
659 absl::OkStatus(), grpc_core::ExecutorType::DEFAULT,
660 grpc_core::ExecutorJobType::LONG);
661 } else {
662 old_count = g_uncovered_notifications_pending++;
663 p = g_backup_poller;
664 g_backup_poller_mu->Unlock();
665 }
666 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
667 gpr_log(GPR_INFO, "BACKUP_POLLER:%p add %p cnt %d->%d", p, tcp,
668 old_count - 1, old_count);
669 }
670 grpc_pollset_add_fd(BACKUP_POLLER_POLLSET(p), tcp->em_fd);
671 }
672
673 static void notify_on_read(grpc_tcp* tcp) {
674 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
675 gpr_log(GPR_INFO, "TCP:%p notify_on_read", tcp);
676 }
677 grpc_fd_notify_on_read(tcp->em_fd, &tcp->read_done_closure);
678 }
679
680 static void notify_on_write(grpc_tcp* tcp) {
681 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
682 gpr_log(GPR_INFO, "TCP:%p notify_on_write", tcp);
683 }
684 if (!grpc_event_engine_run_in_background()) {
685 cover_self(tcp);
686 }
687 grpc_fd_notify_on_write(tcp->em_fd, &tcp->write_done_closure);
688 }
689
690 static void tcp_drop_uncovered_then_handle_write(void* arg,
691 grpc_error_handle error) {
692 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
693 gpr_log(GPR_INFO, "TCP:%p got_write: %s", arg,
694 grpc_core::StatusToString(error).c_str());
695 }
696 drop_uncovered(static_cast<grpc_tcp*>(arg));
697 tcp_handle_write(arg, error);
698 }
699
700 static void add_to_estimate(grpc_tcp* tcp, size_t bytes) {
701 tcp->bytes_read_this_round += static_cast<double>(bytes);
702 }
703
704 static void finish_estimate(grpc_tcp* tcp) {
705 /* If we read >80% of the target buffer in one read loop, increase the size
706 of the target buffer to either the amount read, or twice its previous
707 value */
708 if (tcp->bytes_read_this_round > tcp->target_length * 0.8) {
709 tcp->target_length =
710 std::max(2 * tcp->target_length, tcp->bytes_read_this_round);
711 } else {
712 tcp->target_length =
713 0.99 * tcp->target_length + 0.01 * tcp->bytes_read_this_round;
714 }
715 tcp->bytes_read_this_round = 0;
716 }
717
718 static grpc_error_handle tcp_annotate_error(grpc_error_handle src_error,
719 grpc_tcp* tcp) {
720 return grpc_error_set_str(
721 grpc_error_set_int(
722 grpc_error_set_int(src_error, grpc_core::StatusIntProperty::kFd,
723 tcp->fd),
724 /* All tcp errors are marked with UNAVAILABLE so that application may
725 * choose to retry. */
726 grpc_core::StatusIntProperty::kRpcStatus, GRPC_STATUS_UNAVAILABLE),
727 grpc_core::StatusStrProperty::kTargetAddress, tcp->peer_string);
728 }
729
730 static void tcp_handle_read(void* arg /* grpc_tcp */, grpc_error_handle error);
731 static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error_handle error);
732
733 static void tcp_shutdown(grpc_endpoint* ep, grpc_error_handle why) {
734 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
735 ZerocopyDisableAndWaitForRemaining(tcp);
736 grpc_fd_shutdown(tcp->em_fd, why);
737 }
738
739 static void tcp_free(grpc_tcp* tcp) {
740 grpc_fd_orphan(tcp->em_fd, tcp->release_fd_cb, tcp->release_fd,
741 "tcp_unref_orphan");
742 grpc_slice_buffer_destroy(&tcp->last_read_buffer);
743 tcp->tb_list.Shutdown(tcp->outgoing_buffer_arg,
744 GRPC_ERROR_CREATE("endpoint destroyed"));
745 tcp->outgoing_buffer_arg = nullptr;
746 delete tcp;
747 }
748
749 #ifndef NDEBUG
750 #define TCP_UNREF(tcp, reason) tcp_unref((tcp), (reason), DEBUG_LOCATION)
751 #define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), DEBUG_LOCATION)
752 static void tcp_unref(grpc_tcp* tcp, const char* reason,
753 const grpc_core::DebugLocation& debug_location) {
754 if (GPR_UNLIKELY(tcp->refcount.Unref(debug_location, reason))) {
755 tcp_free(tcp);
756 }
757 }
758
759 static void tcp_ref(grpc_tcp* tcp, const char* reason,
760 const grpc_core::DebugLocation& debug_location) {
761 tcp->refcount.Ref(debug_location, reason);
762 }
763 #else
764 #define TCP_UNREF(tcp, reason) tcp_unref((tcp))
765 #define TCP_REF(tcp, reason) tcp_ref((tcp))
766 static void tcp_unref(grpc_tcp* tcp) {
767 if (GPR_UNLIKELY(tcp->refcount.Unref())) {
768 tcp_free(tcp);
769 }
770 }
771
772 static void tcp_ref(grpc_tcp* tcp) { tcp->refcount.Ref(); }
773 #endif
774
775 static void tcp_destroy(grpc_endpoint* ep) {
776 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
777 grpc_slice_buffer_reset_and_unref(&tcp->last_read_buffer);
778 if (grpc_event_engine_can_track_errors()) {
779 ZerocopyDisableAndWaitForRemaining(tcp);
780 gpr_atm_no_barrier_store(&tcp->stop_error_notification, true);
781 grpc_fd_set_error(tcp->em_fd);
782 }
783 TCP_UNREF(tcp, "destroy");
784 }
785
786 static void perform_reclamation(grpc_tcp* tcp)
787 ABSL_LOCKS_EXCLUDED(tcp->read_mu) {
788 if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) {
789 gpr_log(GPR_INFO, "TCP: benign reclamation to free memory");
790 }
791 tcp->read_mu.Lock();
792 if (tcp->incoming_buffer != nullptr) {
793 grpc_slice_buffer_reset_and_unref(tcp->incoming_buffer);
794 }
795 tcp->has_posted_reclaimer = false;
796 tcp->read_mu.Unlock();
797 }
798
799 static void maybe_post_reclaimer(grpc_tcp* tcp)
800 ABSL_EXCLUSIVE_LOCKS_REQUIRED(tcp->read_mu) {
801 if (!tcp->has_posted_reclaimer) {
802 tcp->has_posted_reclaimer = true;
803 tcp->memory_owner.PostReclaimer(
804 grpc_core::ReclamationPass::kBenign,
805 [tcp](absl::optional<grpc_core::ReclamationSweep> sweep) {
806 if (!sweep.has_value()) return;
807 perform_reclamation(tcp);
808 });
809 }
810 }
811
812 static void tcp_trace_read(grpc_tcp* tcp, grpc_error_handle error)
813 ABSL_EXCLUSIVE_LOCKS_REQUIRED(tcp->read_mu) {
814 grpc_closure* cb = tcp->read_cb;
815 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
816 gpr_log(GPR_INFO, "TCP:%p call_cb %p %p:%p", tcp, cb, cb->cb, cb->cb_arg);
817 size_t i;
818 gpr_log(GPR_INFO, "READ %p (peer=%s) error=%s", tcp,
819 tcp->peer_string.c_str(), grpc_core::StatusToString(error).c_str());
820 if (gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) {
821 for (i = 0; i < tcp->incoming_buffer->count; i++) {
822 char* dump = grpc_dump_slice(tcp->incoming_buffer->slices[i],
823 GPR_DUMP_HEX | GPR_DUMP_ASCII);
824 gpr_log(GPR_DEBUG, "READ DATA: %s", dump);
825 gpr_free(dump);
826 }
827 }
828 }
829 }
830
831 static void update_rcvlowat(grpc_tcp* tcp)
832 ABSL_EXCLUSIVE_LOCKS_REQUIRED(tcp->read_mu) {
833 if (!grpc_core::IsTcpRcvLowatEnabled()) return;
834
835 // TODO(ctiller): Check if supported by OS.
836 // TODO(ctiller): Allow some adjustments instead of hardcoding things.
837
838 static constexpr int kRcvLowatMax = 16 * 1024 * 1024;
839 static constexpr int kRcvLowatThreshold = 16 * 1024;
840
841 int remaining = std::min(static_cast<int>(tcp->incoming_buffer->length),
842 tcp->min_progress_size);
843 remaining = std::min(remaining, kRcvLowatMax);
844
845 // Setting SO_RCVLOWAT for small quantities does not save on CPU.
846 if (remaining < kRcvLowatThreshold) {
847 remaining = 0;
848 }
849
850 // If zerocopy is off, wake shortly before the full RPC is here. More can
851 // show up partway through recvmsg() since it takes a while to copy data.
852 // So an early wakeup aids latency.
853 if (!tcp->tcp_zerocopy_send_ctx.enabled() && remaining > 0) {
854 remaining -= kRcvLowatThreshold;
855 }
856
857 // We still do not know the RPC size. Do not set SO_RCVLOWAT.
858 if (tcp->set_rcvlowat <= 1 && remaining <= 1) return;
859
860 // Previous value is still valid. No change needed in SO_RCVLOWAT.
861 if (tcp->set_rcvlowat == remaining) {
862 return;
863 }
864 if (setsockopt(tcp->fd, SOL_SOCKET, SO_RCVLOWAT, &remaining,
865 sizeof(remaining)) != 0) {
866 gpr_log(GPR_ERROR, "%s",
867 absl::StrCat("Cannot set SO_RCVLOWAT on fd=", tcp->fd,
868 " err=", grpc_core::StrError(errno).c_str())
869 .c_str());
870 return;
871 }
872 tcp->set_rcvlowat = remaining;
873 }
874
875 /* Returns true if data available to read or error other than EAGAIN. */
876 #define MAX_READ_IOVEC 64
877 static bool tcp_do_read(grpc_tcp* tcp, grpc_error_handle* error)
878 ABSL_EXCLUSIVE_LOCKS_REQUIRED(tcp->read_mu) {
879 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
880 gpr_log(GPR_INFO, "TCP:%p do_read", tcp);
881 }
882 struct msghdr msg;
883 struct iovec iov[MAX_READ_IOVEC];
884 ssize_t read_bytes;
885 size_t total_read_bytes = 0;
886 size_t iov_len =
887 std::min<size_t>(MAX_READ_IOVEC, tcp->incoming_buffer->count);
888 #ifdef GRPC_LINUX_ERRQUEUE
889 constexpr size_t cmsg_alloc_space =
890 CMSG_SPACE(sizeof(grpc_core::scm_timestamping)) + CMSG_SPACE(sizeof(int));
891 #else
892 constexpr size_t cmsg_alloc_space = 24 /* CMSG_SPACE(sizeof(int)) */;
893 #endif /* GRPC_LINUX_ERRQUEUE */
894 char cmsgbuf[cmsg_alloc_space];
895 for (size_t i = 0; i < iov_len; i++) {
896 iov[i].iov_base = GRPC_SLICE_START_PTR(tcp->incoming_buffer->slices[i]);
897 iov[i].iov_len = GRPC_SLICE_LENGTH(tcp->incoming_buffer->slices[i]);
898 }
899
900 GPR_ASSERT(tcp->incoming_buffer->length != 0);
901 GPR_DEBUG_ASSERT(tcp->min_progress_size > 0);
902
903 do {
904 /* Assume there is something on the queue. If we receive TCP_INQ from
905 * kernel, we will update this value, otherwise, we have to assume there is
906 * always something to read until we get EAGAIN. */
907 tcp->inq = 1;
908
909 msg.msg_name = nullptr;
910 msg.msg_namelen = 0;
911 msg.msg_iov = iov;
912 msg.msg_iovlen = static_cast<msg_iovlen_type>(iov_len);
913 if (tcp->inq_capable) {
914 msg.msg_control = cmsgbuf;
915 msg.msg_controllen = sizeof(cmsgbuf);
916 } else {
917 msg.msg_control = nullptr;
918 msg.msg_controllen = 0;
919 }
920 msg.msg_flags = 0;
921
922 grpc_core::global_stats().IncrementTcpReadOffer(
923 tcp->incoming_buffer->length);
924 grpc_core::global_stats().IncrementTcpReadOfferIovSize(
925 tcp->incoming_buffer->count);
926
927 do {
928 grpc_core::global_stats().IncrementSyscallRead();
929 read_bytes = recvmsg(tcp->fd, &msg, 0);
930 } while (read_bytes < 0 && errno == EINTR);
931
932 if (read_bytes < 0 && errno == EAGAIN) {
933 /* NB: After calling call_read_cb a parallel call of the read handler may
934 * be running. */
935 if (total_read_bytes > 0) {
936 break;
937 }
938 finish_estimate(tcp);
939 tcp->inq = 0;
940 return false;
941 }
942
943 /* We have read something in previous reads. We need to deliver those
944 * bytes to the upper layer. */
945 if (read_bytes <= 0 && total_read_bytes >= 1) {
946 tcp->inq = 1;
947 break;
948 }
949
950 if (read_bytes <= 0) {
951 /* 0 read size ==> end of stream */
952 grpc_slice_buffer_reset_and_unref(tcp->incoming_buffer);
953 if (read_bytes == 0) {
954 *error = tcp_annotate_error(absl::InternalError("Socket closed"), tcp);
955 } else {
956 *error =
957 tcp_annotate_error(absl::InternalError(absl::StrCat(
958 "recvmsg:", grpc_core::StrError(errno))),
959 tcp);
960 }
961 return true;
962 }
963
964 grpc_core::global_stats().IncrementTcpReadSize(read_bytes);
965 add_to_estimate(tcp, static_cast<size_t>(read_bytes));
966 GPR_DEBUG_ASSERT((size_t)read_bytes <=
967 tcp->incoming_buffer->length - total_read_bytes);
968
969 #ifdef GRPC_HAVE_TCP_INQ
970 if (tcp->inq_capable) {
971 GPR_DEBUG_ASSERT(!(msg.msg_flags & MSG_CTRUNC));
972 struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
973 for (; cmsg != nullptr; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
974 if (cmsg->cmsg_level == SOL_TCP && cmsg->cmsg_type == TCP_CM_INQ &&
975 cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
976 tcp->inq = *reinterpret_cast<int*>(CMSG_DATA(cmsg));
977 break;
978 }
979 }
980 }
981 #endif /* GRPC_HAVE_TCP_INQ */
982
983 total_read_bytes += read_bytes;
984 if (tcp->inq == 0 || total_read_bytes == tcp->incoming_buffer->length) {
985 break;
986 }
987
988 /* We had a partial read, and still have space to read more data.
989 * So, adjust IOVs and try to read more. */
990 size_t remaining = read_bytes;
991 size_t j = 0;
992 for (size_t i = 0; i < iov_len; i++) {
993 if (remaining >= iov[i].iov_len) {
994 remaining -= iov[i].iov_len;
995 continue;
996 }
997 if (remaining > 0) {
998 iov[j].iov_base = static_cast<char*>(iov[i].iov_base) + remaining;
999 iov[j].iov_len = iov[i].iov_len - remaining;
1000 remaining = 0;
1001 } else {
1002 iov[j].iov_base = iov[i].iov_base;
1003 iov[j].iov_len = iov[i].iov_len;
1004 }
1005 ++j;
1006 }
1007 iov_len = j;
1008 } while (true);
1009
1010 if (tcp->inq == 0) {
1011 finish_estimate(tcp);
1012 }
1013
1014 GPR_DEBUG_ASSERT(total_read_bytes > 0);
1015 *error = absl::OkStatus();
1016 if (grpc_core::IsTcpFrameSizeTuningEnabled()) {
1017 // Update min progress size based on the total number of bytes read in
1018 // this round.
1019 tcp->min_progress_size -= total_read_bytes;
1020 if (tcp->min_progress_size > 0) {
1021 // There is still some bytes left to be read before we can signal
1022 // the read as complete. Append the bytes read so far into
1023 // last_read_buffer which serves as a staging buffer. Return false
1024 // to indicate tcp_handle_read needs to be scheduled again.
1025 grpc_slice_buffer_move_first(tcp->incoming_buffer, total_read_bytes,
1026 &tcp->last_read_buffer);
1027 return false;
1028 } else {
1029 // The required number of bytes have been read. Append the bytes
1030 // read in this round into last_read_buffer. Then swap last_read_buffer
1031 // and incoming_buffer. Now incoming buffer contains all the bytes
1032 // read since the start of the last tcp_read operation. last_read_buffer
1033 // would contain any spare space left in the incoming buffer. This
1034 // space will be used in the next tcp_read operation.
1035 tcp->min_progress_size = 1;
1036 grpc_slice_buffer_move_first(tcp->incoming_buffer, total_read_bytes,
1037 &tcp->last_read_buffer);
1038 grpc_slice_buffer_swap(&tcp->last_read_buffer, tcp->incoming_buffer);
1039 return true;
1040 }
1041 }
1042 if (total_read_bytes < tcp->incoming_buffer->length) {
1043 grpc_slice_buffer_trim_end(tcp->incoming_buffer,
1044 tcp->incoming_buffer->length - total_read_bytes,
1045 &tcp->last_read_buffer);
1046 }
1047 return true;
1048 }
1049
1050 static void maybe_make_read_slices(grpc_tcp* tcp)
1051 ABSL_EXCLUSIVE_LOCKS_REQUIRED(tcp->read_mu) {
1052 if (grpc_core::IsTcpReadChunksEnabled()) {
1053 static const int kBigAlloc = 64 * 1024;
1054 static const int kSmallAlloc = 8 * 1024;
1055 if (tcp->incoming_buffer->length <
1056 static_cast<size_t>(tcp->min_progress_size)) {
1057 size_t allocate_length = tcp->min_progress_size;
1058 const size_t target_length = static_cast<size_t>(tcp->target_length);
1059 // If memory pressure is low and we think there will be more than
1060 // min_progress_size bytes to read, allocate a bit more.
1061 const bool low_memory_pressure =
1062 tcp->memory_owner.GetPressureInfo().pressure_control_value < 0.8;
1063 if (low_memory_pressure && target_length > allocate_length) {
1064 allocate_length = target_length;
1065 }
1066 int extra_wanted =
1067 allocate_length - static_cast<int>(tcp->incoming_buffer->length);
1068 if (extra_wanted >=
1069 (low_memory_pressure ? kSmallAlloc * 3 / 2 : kBigAlloc)) {
1070 while (extra_wanted > 0) {
1071 extra_wanted -= kBigAlloc;
1072 grpc_slice_buffer_add_indexed(tcp->incoming_buffer,
1073 tcp->memory_owner.MakeSlice(kBigAlloc));
1074 grpc_core::global_stats().IncrementTcpReadAlloc64k();
1075 }
1076 } else {
1077 while (extra_wanted > 0) {
1078 extra_wanted -= kSmallAlloc;
1079 grpc_slice_buffer_add_indexed(
1080 tcp->incoming_buffer, tcp->memory_owner.MakeSlice(kSmallAlloc));
1081 grpc_core::global_stats().IncrementTcpReadAlloc8k();
1082 }
1083 }
1084 maybe_post_reclaimer(tcp);
1085 }
1086 } else {
1087 if (tcp->incoming_buffer->length <
1088 static_cast<size_t>(tcp->min_progress_size) &&
1089 tcp->incoming_buffer->count < MAX_READ_IOVEC) {
1090 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1091 gpr_log(GPR_INFO,
1092 "TCP:%p alloc_slices; min_chunk=%d max_chunk=%d target=%lf "
1093 "buf_len=%" PRIdPTR,
1094 tcp, tcp->min_read_chunk_size, tcp->max_read_chunk_size,
1095 tcp->target_length, tcp->incoming_buffer->length);
1096 }
1097 int target_length = std::max(static_cast<int>(tcp->target_length),
1098 tcp->min_progress_size);
1099 int extra_wanted =
1100 target_length - static_cast<int>(tcp->incoming_buffer->length);
1101 int min_read_chunk_size =
1102 std::max(tcp->min_read_chunk_size, tcp->min_progress_size);
1103 int max_read_chunk_size =
1104 std::max(tcp->max_read_chunk_size, tcp->min_progress_size);
1105 grpc_slice slice = tcp->memory_owner.MakeSlice(grpc_core::MemoryRequest(
1106 min_read_chunk_size,
1107 grpc_core::Clamp(extra_wanted, min_read_chunk_size,
1108 max_read_chunk_size)));
1109 grpc_slice_buffer_add_indexed(tcp->incoming_buffer, slice);
1110 maybe_post_reclaimer(tcp);
1111 }
1112 }
1113 }
1114
1115 static void tcp_handle_read(void* arg /* grpc_tcp */, grpc_error_handle error) {
1116 grpc_tcp* tcp = static_cast<grpc_tcp*>(arg);
1117 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1118 gpr_log(GPR_INFO, "TCP:%p got_read: %s", tcp,
1119 grpc_core::StatusToString(error).c_str());
1120 }
1121 tcp->read_mu.Lock();
1122 grpc_error_handle tcp_read_error;
1123 if (GPR_LIKELY(error.ok())) {
1124 maybe_make_read_slices(tcp);
1125 if (!tcp_do_read(tcp, &tcp_read_error)) {
1126 /* We've consumed the edge, request a new one */
1127 update_rcvlowat(tcp);
1128 tcp->read_mu.Unlock();
1129 notify_on_read(tcp);
1130 return;
1131 }
1132 tcp_trace_read(tcp, tcp_read_error);
1133 } else {
1134 tcp_read_error = error;
1135 grpc_slice_buffer_reset_and_unref(tcp->incoming_buffer);
1136 grpc_slice_buffer_reset_and_unref(&tcp->last_read_buffer);
1137 }
1138 grpc_closure* cb = tcp->read_cb;
1139 tcp->read_cb = nullptr;
1140 tcp->incoming_buffer = nullptr;
1141 tcp->read_mu.Unlock();
1142 grpc_core::Closure::Run(DEBUG_LOCATION, cb, tcp_read_error);
1143 TCP_UNREF(tcp, "read");
1144 }
1145
1146 static void tcp_read(grpc_endpoint* ep, grpc_slice_buffer* incoming_buffer,
1147 grpc_closure* cb, bool urgent, int min_progress_size) {
1148 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
1149 GPR_ASSERT(tcp->read_cb == nullptr);
1150 tcp->read_cb = cb;
1151 tcp->read_mu.Lock();
1152 tcp->incoming_buffer = incoming_buffer;
1153 tcp->min_progress_size =
1154 grpc_core::IsTcpFrameSizeTuningEnabled() ? min_progress_size : 1;
1155 grpc_slice_buffer_reset_and_unref(incoming_buffer);
1156 grpc_slice_buffer_swap(incoming_buffer, &tcp->last_read_buffer);
1157 TCP_REF(tcp, "read");
1158 if (tcp->is_first_read) {
1159 update_rcvlowat(tcp);
1160 tcp->read_mu.Unlock();
1161 /* Endpoint read called for the very first time. Register read callback with
1162 * the polling engine */
1163 tcp->is_first_read = false;
1164 notify_on_read(tcp);
1165 } else if (!urgent && tcp->inq == 0) {
1166 update_rcvlowat(tcp);
1167 tcp->read_mu.Unlock();
1168 /* Upper layer asked to read more but we know there is no pending data
1169 * to read from previous reads. So, wait for POLLIN.
1170 */
1171 notify_on_read(tcp);
1172 } else {
1173 tcp->read_mu.Unlock();
1174 /* Not the first time. We may or may not have more bytes available. In any
1175 * case call tcp->read_done_closure (i.e tcp_handle_read()) which does the
1176 * right thing (i.e calls tcp_do_read() which either reads the available
1177 * bytes or calls notify_on_read() to be notified when new bytes become
1178 * available */
1179 grpc_core::Closure::Run(DEBUG_LOCATION, &tcp->read_done_closure,
1180 absl::OkStatus());
1181 }
1182 }
1183
1184 /* A wrapper around sendmsg. It sends \a msg over \a fd and returns the number
1185 * of bytes sent. */
1186 ssize_t tcp_send(int fd, const struct msghdr* msg, int* saved_errno,
1187 int additional_flags = 0) {
1188 ssize_t sent_length;
1189 do {
1190 /* TODO(klempner): Cork if this is a partial write */
1191 grpc_core::global_stats().IncrementSyscallWrite();
1192 sent_length = sendmsg(fd, msg, SENDMSG_FLAGS | additional_flags);
1193 } while (sent_length < 0 && (*saved_errno = errno) == EINTR);
1194 return sent_length;
1195 }
1196
1197 /** This is to be called if outgoing_buffer_arg is not null. On linux platforms,
1198 * this will call sendmsg with socket options set to collect timestamps inside
1199 * the kernel. On return, sent_length is set to the return value of the sendmsg
1200 * call. Returns false if setting the socket options failed. This is not
1201 * implemented for non-linux platforms currently, and crashes out.
1202 */
1203 static bool tcp_write_with_timestamps(grpc_tcp* tcp, struct msghdr* msg,
1204 size_t sending_length,
1205 ssize_t* sent_length, int* saved_errno,
1206 int additional_flags = 0);
1207
1208 /** The callback function to be invoked when we get an error on the socket. */
1209 static void tcp_handle_error(void* arg /* grpc_tcp */, grpc_error_handle error);
1210
1211 static TcpZerocopySendRecord* tcp_get_send_zerocopy_record(
1212 grpc_tcp* tcp, grpc_slice_buffer* buf);
1213
1214 #ifdef GRPC_LINUX_ERRQUEUE
1215 static bool process_errors(grpc_tcp* tcp);
1216
1217 static TcpZerocopySendRecord* tcp_get_send_zerocopy_record(
1218 grpc_tcp* tcp, grpc_slice_buffer* buf) {
1219 TcpZerocopySendRecord* zerocopy_send_record = nullptr;
1220 const bool use_zerocopy =
1221 tcp->tcp_zerocopy_send_ctx.enabled() &&
1222 tcp->tcp_zerocopy_send_ctx.threshold_bytes() < buf->length;
1223 if (use_zerocopy) {
1224 zerocopy_send_record = tcp->tcp_zerocopy_send_ctx.GetSendRecord();
1225 if (zerocopy_send_record == nullptr) {
1226 process_errors(tcp);
1227 zerocopy_send_record = tcp->tcp_zerocopy_send_ctx.GetSendRecord();
1228 }
1229 if (zerocopy_send_record != nullptr) {
1230 zerocopy_send_record->PrepareForSends(buf);
1231 GPR_DEBUG_ASSERT(buf->count == 0);
1232 GPR_DEBUG_ASSERT(buf->length == 0);
1233 tcp->outgoing_byte_idx = 0;
1234 tcp->outgoing_buffer = nullptr;
1235 }
1236 }
1237 return zerocopy_send_record;
1238 }
1239
1240 static void ZerocopyDisableAndWaitForRemaining(grpc_tcp* tcp) {
1241 tcp->tcp_zerocopy_send_ctx.Shutdown();
1242 while (!tcp->tcp_zerocopy_send_ctx.AllSendRecordsEmpty()) {
1243 process_errors(tcp);
1244 }
1245 }
1246
1247 static bool tcp_write_with_timestamps(grpc_tcp* tcp, struct msghdr* msg,
1248 size_t sending_length,
1249 ssize_t* sent_length, int* saved_errno,
1250 int additional_flags) {
1251 if (!tcp->socket_ts_enabled) {
1252 uint32_t opt = grpc_core::kTimestampingSocketOptions;
1253 if (setsockopt(tcp->fd, SOL_SOCKET, SO_TIMESTAMPING,
1254 static_cast<void*>(&opt), sizeof(opt)) != 0) {
1255 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1256 gpr_log(GPR_ERROR, "Failed to set timestamping options on the socket.");
1257 }
1258 return false;
1259 }
1260 tcp->bytes_counter = -1;
1261 tcp->socket_ts_enabled = true;
1262 }
1263 /* Set control message to indicate that you want timestamps. */
1264 union {
1265 char cmsg_buf[CMSG_SPACE(sizeof(uint32_t))];
1266 struct cmsghdr align;
1267 } u;
1268 cmsghdr* cmsg = reinterpret_cast<cmsghdr*>(u.cmsg_buf);
1269 cmsg->cmsg_level = SOL_SOCKET;
1270 cmsg->cmsg_type = SO_TIMESTAMPING;
1271 cmsg->cmsg_len = CMSG_LEN(sizeof(uint32_t));
1272 *reinterpret_cast<int*>(CMSG_DATA(cmsg)) =
1273 grpc_core::kTimestampingRecordingOptions;
1274 msg->msg_control = u.cmsg_buf;
1275 msg->msg_controllen = CMSG_SPACE(sizeof(uint32_t));
1276
1277 /* If there was an error on sendmsg the logic in tcp_flush will handle it. */
1278 ssize_t length = tcp_send(tcp->fd, msg, saved_errno, additional_flags);
1279 *sent_length = length;
1280 /* Only save timestamps if all the bytes were taken by sendmsg. */
1281 if (sending_length == static_cast<size_t>(length)) {
1282 tcp->tb_list.AddNewEntry(static_cast<uint32_t>(tcp->bytes_counter + length),
1283 tcp->fd, tcp->outgoing_buffer_arg);
1284 tcp->outgoing_buffer_arg = nullptr;
1285 }
1286 return true;
1287 }
1288
1289 static void UnrefMaybePutZerocopySendRecord(grpc_tcp* tcp,
1290 TcpZerocopySendRecord* record,
1291 uint32_t seq, const char* tag);
1292 // Reads \a cmsg to process zerocopy control messages.
1293 static void process_zerocopy(grpc_tcp* tcp, struct cmsghdr* cmsg) {
1294 GPR_DEBUG_ASSERT(cmsg);
1295 auto serr = reinterpret_cast<struct sock_extended_err*>(CMSG_DATA(cmsg));
1296 GPR_DEBUG_ASSERT(serr->ee_errno == 0);
1297 GPR_DEBUG_ASSERT(serr->ee_origin == SO_EE_ORIGIN_ZEROCOPY);
1298 const uint32_t lo = serr->ee_info;
1299 const uint32_t hi = serr->ee_data;
1300 for (uint32_t seq = lo; seq <= hi; ++seq) {
1301 // TODO(arjunroy): It's likely that lo and hi refer to zerocopy sequence
1302 // numbers that are generated by a single call to grpc_endpoint_write; ie.
1303 // we can batch the unref operation. So, check if record is the same for
1304 // both; if so, batch the unref/put.
1305 TcpZerocopySendRecord* record =
1306 tcp->tcp_zerocopy_send_ctx.ReleaseSendRecord(seq);
1307 GPR_DEBUG_ASSERT(record);
1308 UnrefMaybePutZerocopySendRecord(tcp, record, seq, "CALLBACK RCVD");
1309 }
1310 if (tcp->tcp_zerocopy_send_ctx.UpdateZeroCopyOMemStateAfterFree()) {
1311 grpc_fd_set_writable(tcp->em_fd);
1312 }
1313 }
1314
1315 // Whether the cmsg received from error queue is of the IPv4 or IPv6 levels.
1316 static bool CmsgIsIpLevel(const cmsghdr& cmsg) {
1317 return (cmsg.cmsg_level == SOL_IPV6 && cmsg.cmsg_type == IPV6_RECVERR) ||
1318 (cmsg.cmsg_level == SOL_IP && cmsg.cmsg_type == IP_RECVERR);
1319 }
1320
1321 static bool CmsgIsZeroCopy(const cmsghdr& cmsg) {
1322 if (!CmsgIsIpLevel(cmsg)) {
1323 return false;
1324 }
1325 auto serr = reinterpret_cast<const sock_extended_err*> CMSG_DATA(&cmsg);
1326 return serr->ee_errno == 0 && serr->ee_origin == SO_EE_ORIGIN_ZEROCOPY;
1327 }
1328
1329 /** Reads \a cmsg to derive timestamps from the control messages. If a valid
1330 * timestamp is found, the traced buffer list is updated with this timestamp.
1331 * The caller of this function should be looping on the control messages found
1332 * in \a msg. \a cmsg should point to the control message that the caller wants
1333 * processed.
1334 * On return, a pointer to a control message is returned. On the next iteration,
1335 * CMSG_NXTHDR(msg, ret_val) should be passed as \a cmsg. */
1336 struct cmsghdr* process_timestamp(grpc_tcp* tcp, msghdr* msg,
1337 struct cmsghdr* cmsg) {
1338 auto next_cmsg = CMSG_NXTHDR(msg, cmsg);
1339 cmsghdr* opt_stats = nullptr;
1340 if (next_cmsg == nullptr) {
1341 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1342 gpr_log(GPR_ERROR, "Received timestamp without extended error");
1343 }
1344 return cmsg;
1345 }
1346
1347 /* Check if next_cmsg is an OPT_STATS msg */
1348 if (next_cmsg->cmsg_level == SOL_SOCKET &&
1349 next_cmsg->cmsg_type == SCM_TIMESTAMPING_OPT_STATS) {
1350 opt_stats = next_cmsg;
1351 next_cmsg = CMSG_NXTHDR(msg, opt_stats);
1352 if (next_cmsg == nullptr) {
1353 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1354 gpr_log(GPR_ERROR, "Received timestamp without extended error");
1355 }
1356 return opt_stats;
1357 }
1358 }
1359
1360 if (!(next_cmsg->cmsg_level == SOL_IP || next_cmsg->cmsg_level == SOL_IPV6) ||
1361 !(next_cmsg->cmsg_type == IP_RECVERR ||
1362 next_cmsg->cmsg_type == IPV6_RECVERR)) {
1363 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1364 gpr_log(GPR_ERROR, "Unexpected control message");
1365 }
1366 return cmsg;
1367 }
1368
1369 auto tss =
1370 reinterpret_cast<struct grpc_core::scm_timestamping*>(CMSG_DATA(cmsg));
1371 auto serr = reinterpret_cast<struct sock_extended_err*>(CMSG_DATA(next_cmsg));
1372 if (serr->ee_errno != ENOMSG ||
1373 serr->ee_origin != SO_EE_ORIGIN_TIMESTAMPING) {
1374 gpr_log(GPR_ERROR, "Unexpected control message");
1375 return cmsg;
1376 }
1377 tcp->tb_list.ProcessTimestamp(serr, opt_stats, tss);
1378 return next_cmsg;
1379 }
1380
1381 /** For linux platforms, reads the socket's error queue and processes error
1382 * messages from the queue.
1383 */
1384 static bool process_errors(grpc_tcp* tcp) {
1385 bool processed_err = false;
1386 struct iovec iov;
1387 iov.iov_base = nullptr;
1388 iov.iov_len = 0;
1389 struct msghdr msg;
1390 msg.msg_name = nullptr;
1391 msg.msg_namelen = 0;
1392 msg.msg_iov = &iov;
1393 msg.msg_iovlen = 0;
1394 msg.msg_flags = 0;
1395 /* Allocate enough space so we don't need to keep increasing this as size
1396 * of OPT_STATS increase */
1397 constexpr size_t cmsg_alloc_space =
1398 CMSG_SPACE(sizeof(grpc_core::scm_timestamping)) +
1399 CMSG_SPACE(sizeof(sock_extended_err) + sizeof(sockaddr_in)) +
1400 CMSG_SPACE(32 * NLA_ALIGN(NLA_HDRLEN + sizeof(uint64_t)));
1401 /* Allocate aligned space for cmsgs received along with timestamps */
1402 union {
1403 char rbuf[cmsg_alloc_space];
1404 struct cmsghdr align;
1405 } aligned_buf;
1406 msg.msg_control = aligned_buf.rbuf;
1407 int r, saved_errno;
1408 while (true) {
1409 msg.msg_controllen = sizeof(aligned_buf.rbuf);
1410 do {
1411 r = recvmsg(tcp->fd, &msg, MSG_ERRQUEUE);
1412 saved_errno = errno;
1413 } while (r < 0 && saved_errno == EINTR);
1414
1415 if (r == -1 && saved_errno == EAGAIN) {
1416 return processed_err; /* No more errors to process */
1417 }
1418 if (r == -1) {
1419 return processed_err;
1420 }
1421 if (GPR_UNLIKELY((msg.msg_flags & MSG_CTRUNC) != 0)) {
1422 gpr_log(GPR_ERROR, "Error message was truncated.");
1423 }
1424
1425 if (msg.msg_controllen == 0) {
1426 /* There was no control message found. It was probably spurious. */
1427 return processed_err;
1428 }
1429 bool seen = false;
1430 for (auto cmsg = CMSG_FIRSTHDR(&msg); cmsg && cmsg->cmsg_len;
1431 cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1432 if (CmsgIsZeroCopy(*cmsg)) {
1433 process_zerocopy(tcp, cmsg);
1434 seen = true;
1435 processed_err = true;
1436 } else if (cmsg->cmsg_level == SOL_SOCKET &&
1437 cmsg->cmsg_type == SCM_TIMESTAMPING) {
1438 cmsg = process_timestamp(tcp, &msg, cmsg);
1439 seen = true;
1440 processed_err = true;
1441 } else {
1442 /* Got a control message that is not a timestamp or zerocopy. Don't know
1443 * how to handle this. */
1444 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1445 gpr_log(GPR_INFO,
1446 "unknown control message cmsg_level:%d cmsg_type:%d",
1447 cmsg->cmsg_level, cmsg->cmsg_type);
1448 }
1449 return processed_err;
1450 }
1451 }
1452 if (!seen) {
1453 return processed_err;
1454 }
1455 }
1456 }
1457
1458 static void tcp_handle_error(void* arg /* grpc_tcp */,
1459 grpc_error_handle error) {
1460 grpc_tcp* tcp = static_cast<grpc_tcp*>(arg);
1461 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1462 gpr_log(GPR_INFO, "TCP:%p got_error: %s", tcp,
1463 grpc_core::StatusToString(error).c_str());
1464 }
1465
1466 if (!error.ok() ||
1467 static_cast<bool>(gpr_atm_acq_load(&tcp->stop_error_notification))) {
1468 /* We aren't going to register to hear on error anymore, so it is safe to
1469 * unref. */
1470 TCP_UNREF(tcp, "error-tracking");
1471 return;
1472 }
1473
1474 /* We are still interested in collecting timestamps, so let's try reading
1475 * them. */
1476 bool processed = process_errors(tcp);
1477 /* This might not a timestamps error. Set the read and write closures to be
1478 * ready. */
1479 if (!processed) {
1480 grpc_fd_set_readable(tcp->em_fd);
1481 grpc_fd_set_writable(tcp->em_fd);
1482 }
1483 grpc_fd_notify_on_error(tcp->em_fd, &tcp->error_closure);
1484 }
1485
1486 #else /* GRPC_LINUX_ERRQUEUE */
1487 static TcpZerocopySendRecord* tcp_get_send_zerocopy_record(
1488 grpc_tcp* /*tcp*/, grpc_slice_buffer* /*buf*/) {
1489 return nullptr;
1490 }
1491
1492 static void ZerocopyDisableAndWaitForRemaining(grpc_tcp* /*tcp*/) {}
1493
1494 static bool tcp_write_with_timestamps(grpc_tcp* /*tcp*/, struct msghdr* /*msg*/,
1495 size_t /*sending_length*/,
1496 ssize_t* /*sent_length*/,
1497 int* /* saved_errno */,
1498 int /*additional_flags*/) {
1499 gpr_log(GPR_ERROR, "Write with timestamps not supported for this platform");
1500 GPR_ASSERT(0);
1501 return false;
1502 }
1503
1504 static void tcp_handle_error(void* /*arg*/ /* grpc_tcp */,
1505 grpc_error_handle /*error*/) {
1506 gpr_log(GPR_ERROR, "Error handling is not supported for this platform");
1507 GPR_ASSERT(0);
1508 }
1509 #endif /* GRPC_LINUX_ERRQUEUE */
1510
1511 /* If outgoing_buffer_arg is filled, shuts down the list early, so that any
1512 * release operations needed can be performed on the arg */
1513 void tcp_shutdown_buffer_list(grpc_tcp* tcp) {
1514 if (tcp->outgoing_buffer_arg) {
1515 tcp->tb_list.Shutdown(tcp->outgoing_buffer_arg,
1516 GRPC_ERROR_CREATE("TracedBuffer list shutdown"));
1517 tcp->outgoing_buffer_arg = nullptr;
1518 }
1519 }
1520
1521 #if defined(IOV_MAX) && IOV_MAX < 260
1522 #define MAX_WRITE_IOVEC IOV_MAX
1523 #else
1524 #define MAX_WRITE_IOVEC 260
1525 #endif
1526 msg_iovlen_type TcpZerocopySendRecord::PopulateIovs(size_t* unwind_slice_idx,
1527 size_t* unwind_byte_idx,
1528 size_t* sending_length,
1529 iovec* iov) {
1530 msg_iovlen_type iov_size;
1531 *unwind_slice_idx = out_offset_.slice_idx;
1532 *unwind_byte_idx = out_offset_.byte_idx;
1533 for (iov_size = 0;
1534 out_offset_.slice_idx != buf_.count && iov_size != MAX_WRITE_IOVEC;
1535 iov_size++) {
1536 iov[iov_size].iov_base =
1537 GRPC_SLICE_START_PTR(buf_.slices[out_offset_.slice_idx]) +
1538 out_offset_.byte_idx;
1539 iov[iov_size].iov_len =
1540 GRPC_SLICE_LENGTH(buf_.slices[out_offset_.slice_idx]) -
1541 out_offset_.byte_idx;
1542 *sending_length += iov[iov_size].iov_len;
1543 ++(out_offset_.slice_idx);
1544 out_offset_.byte_idx = 0;
1545 }
1546 GPR_DEBUG_ASSERT(iov_size > 0);
1547 return iov_size;
1548 }
1549
1550 void TcpZerocopySendRecord::UpdateOffsetForBytesSent(size_t sending_length,
1551 size_t actually_sent) {
1552 size_t trailing = sending_length - actually_sent;
1553 while (trailing > 0) {
1554 size_t slice_length;
1555 out_offset_.slice_idx--;
1556 slice_length = GRPC_SLICE_LENGTH(buf_.slices[out_offset_.slice_idx]);
1557 if (slice_length > trailing) {
1558 out_offset_.byte_idx = slice_length - trailing;
1559 break;
1560 } else {
1561 trailing -= slice_length;
1562 }
1563 }
1564 }
1565
1566 // returns true if done, false if pending; if returning true, *error is set
1567 static bool do_tcp_flush_zerocopy(grpc_tcp* tcp, TcpZerocopySendRecord* record,
1568 grpc_error_handle* error) {
1569 msg_iovlen_type iov_size;
1570 ssize_t sent_length = 0;
1571 size_t sending_length;
1572 size_t unwind_slice_idx;
1573 size_t unwind_byte_idx;
1574 bool tried_sending_message;
1575 int saved_errno;
1576 msghdr msg;
1577 // iov consumes a large space. Keep it as the last item on the stack to
1578 // improve locality. After all, we expect only the first elements of it being
1579 // populated in most cases.
1580 iovec iov[MAX_WRITE_IOVEC];
1581 while (true) {
1582 sending_length = 0;
1583 iov_size = record->PopulateIovs(&unwind_slice_idx, &unwind_byte_idx,
1584 &sending_length, iov);
1585 msg.msg_name = nullptr;
1586 msg.msg_namelen = 0;
1587 msg.msg_iov = iov;
1588 msg.msg_iovlen = iov_size;
1589 msg.msg_flags = 0;
1590 tried_sending_message = false;
1591 // Before calling sendmsg (with or without timestamps): we
1592 // take a single ref on the zerocopy send record.
1593 tcp->tcp_zerocopy_send_ctx.NoteSend(record);
1594 saved_errno = 0;
1595 if (tcp->outgoing_buffer_arg != nullptr) {
1596 if (!tcp->ts_capable ||
1597 !tcp_write_with_timestamps(tcp, &msg, sending_length, &sent_length,
1598 &saved_errno, MSG_ZEROCOPY)) {
1599 /* We could not set socket options to collect Fathom timestamps.
1600 * Fallback on writing without timestamps. */
1601 tcp->ts_capable = false;
1602 tcp_shutdown_buffer_list(tcp);
1603 } else {
1604 tried_sending_message = true;
1605 }
1606 }
1607 if (!tried_sending_message) {
1608 msg.msg_control = nullptr;
1609 msg.msg_controllen = 0;
1610 grpc_core::global_stats().IncrementTcpWriteSize(sending_length);
1611 grpc_core::global_stats().IncrementTcpWriteIovSize(iov_size);
1612 sent_length = tcp_send(tcp->fd, &msg, &saved_errno, MSG_ZEROCOPY);
1613 }
1614 if (tcp->tcp_zerocopy_send_ctx.UpdateZeroCopyOMemStateAfterSend(
1615 saved_errno == ENOBUFS)) {
1616 grpc_fd_set_writable(tcp->em_fd);
1617 }
1618 if (sent_length < 0) {
1619 // If this particular send failed, drop ref taken earlier in this method.
1620 tcp->tcp_zerocopy_send_ctx.UndoSend();
1621 if (saved_errno == EAGAIN || saved_errno == ENOBUFS) {
1622 record->UnwindIfThrottled(unwind_slice_idx, unwind_byte_idx);
1623 return false;
1624 } else if (saved_errno == EPIPE) {
1625 *error = tcp_annotate_error(GRPC_OS_ERROR(saved_errno, "sendmsg"), tcp);
1626 tcp_shutdown_buffer_list(tcp);
1627 return true;
1628 } else {
1629 *error = tcp_annotate_error(GRPC_OS_ERROR(saved_errno, "sendmsg"), tcp);
1630 tcp_shutdown_buffer_list(tcp);
1631 return true;
1632 }
1633 }
1634 grpc_core::EventLog::Append("tcp-write-outstanding", -sent_length);
1635 tcp->bytes_counter += sent_length;
1636 record->UpdateOffsetForBytesSent(sending_length,
1637 static_cast<size_t>(sent_length));
1638 if (record->AllSlicesSent()) {
1639 *error = absl::OkStatus();
1640 return true;
1641 }
1642 }
1643 }
1644
1645 static void UnrefMaybePutZerocopySendRecord(grpc_tcp* tcp,
1646 TcpZerocopySendRecord* record,
1647 uint32_t /*seq*/,
1648 const char* /*tag*/) {
1649 if (record->Unref()) {
1650 tcp->tcp_zerocopy_send_ctx.PutSendRecord(record);
1651 }
1652 }
1653
1654 static bool tcp_flush_zerocopy(grpc_tcp* tcp, TcpZerocopySendRecord* record,
1655 grpc_error_handle* error) {
1656 bool done = do_tcp_flush_zerocopy(tcp, record, error);
1657 if (done) {
1658 // Either we encountered an error, or we successfully sent all the bytes.
1659 // In either case, we're done with this record.
1660 UnrefMaybePutZerocopySendRecord(tcp, record, 0, "flush_done");
1661 }
1662 return done;
1663 }
1664
1665 static bool tcp_flush(grpc_tcp* tcp, grpc_error_handle* error) {
1666 struct msghdr msg;
1667 struct iovec iov[MAX_WRITE_IOVEC];
1668 msg_iovlen_type iov_size;
1669 ssize_t sent_length = 0;
1670 size_t sending_length;
1671 size_t trailing;
1672 size_t unwind_slice_idx;
1673 size_t unwind_byte_idx;
1674 int saved_errno;
1675
1676 // We always start at zero, because we eagerly unref and trim the slice
1677 // buffer as we write
1678 size_t outgoing_slice_idx = 0;
1679
1680 while (true) {
1681 sending_length = 0;
1682 unwind_slice_idx = outgoing_slice_idx;
1683 unwind_byte_idx = tcp->outgoing_byte_idx;
1684 for (iov_size = 0; outgoing_slice_idx != tcp->outgoing_buffer->count &&
1685 iov_size != MAX_WRITE_IOVEC;
1686 iov_size++) {
1687 iov[iov_size].iov_base =
1688 GRPC_SLICE_START_PTR(
1689 tcp->outgoing_buffer->slices[outgoing_slice_idx]) +
1690 tcp->outgoing_byte_idx;
1691 iov[iov_size].iov_len =
1692 GRPC_SLICE_LENGTH(tcp->outgoing_buffer->slices[outgoing_slice_idx]) -
1693 tcp->outgoing_byte_idx;
1694 sending_length += iov[iov_size].iov_len;
1695 outgoing_slice_idx++;
1696 tcp->outgoing_byte_idx = 0;
1697 }
1698 GPR_ASSERT(iov_size > 0);
1699
1700 msg.msg_name = nullptr;
1701 msg.msg_namelen = 0;
1702 msg.msg_iov = iov;
1703 msg.msg_iovlen = iov_size;
1704 msg.msg_flags = 0;
1705 bool tried_sending_message = false;
1706 saved_errno = 0;
1707 if (tcp->outgoing_buffer_arg != nullptr) {
1708 if (!tcp->ts_capable ||
1709 !tcp_write_with_timestamps(tcp, &msg, sending_length, &sent_length,
1710 &saved_errno)) {
1711 /* We could not set socket options to collect Fathom timestamps.
1712 * Fallback on writing without timestamps. */
1713 tcp->ts_capable = false;
1714 tcp_shutdown_buffer_list(tcp);
1715 } else {
1716 tried_sending_message = true;
1717 }
1718 }
1719 if (!tried_sending_message) {
1720 msg.msg_control = nullptr;
1721 msg.msg_controllen = 0;
1722
1723 grpc_core::global_stats().IncrementTcpWriteSize(sending_length);
1724 grpc_core::global_stats().IncrementTcpWriteIovSize(iov_size);
1725
1726 sent_length = tcp_send(tcp->fd, &msg, &saved_errno);
1727 }
1728
1729 if (sent_length < 0) {
1730 if (saved_errno == EAGAIN || saved_errno == ENOBUFS) {
1731 tcp->outgoing_byte_idx = unwind_byte_idx;
1732 // unref all and forget about all slices that have been written to this
1733 // point
1734 for (size_t idx = 0; idx < unwind_slice_idx; ++idx) {
1735 grpc_slice_buffer_remove_first(tcp->outgoing_buffer);
1736 }
1737 return false;
1738 } else if (saved_errno == EPIPE) {
1739 *error = tcp_annotate_error(GRPC_OS_ERROR(saved_errno, "sendmsg"), tcp);
1740 grpc_slice_buffer_reset_and_unref(tcp->outgoing_buffer);
1741 tcp_shutdown_buffer_list(tcp);
1742 return true;
1743 } else {
1744 *error = tcp_annotate_error(GRPC_OS_ERROR(saved_errno, "sendmsg"), tcp);
1745 grpc_slice_buffer_reset_and_unref(tcp->outgoing_buffer);
1746 tcp_shutdown_buffer_list(tcp);
1747 return true;
1748 }
1749 }
1750
1751 GPR_ASSERT(tcp->outgoing_byte_idx == 0);
1752 grpc_core::EventLog::Append("tcp-write-outstanding", -sent_length);
1753 tcp->bytes_counter += sent_length;
1754 trailing = sending_length - static_cast<size_t>(sent_length);
1755 while (trailing > 0) {
1756 size_t slice_length;
1757
1758 outgoing_slice_idx--;
1759 slice_length =
1760 GRPC_SLICE_LENGTH(tcp->outgoing_buffer->slices[outgoing_slice_idx]);
1761 if (slice_length > trailing) {
1762 tcp->outgoing_byte_idx = slice_length - trailing;
1763 break;
1764 } else {
1765 trailing -= slice_length;
1766 }
1767 }
1768 if (outgoing_slice_idx == tcp->outgoing_buffer->count) {
1769 *error = absl::OkStatus();
1770 grpc_slice_buffer_reset_and_unref(tcp->outgoing_buffer);
1771 return true;
1772 }
1773 }
1774 }
1775
1776 static void tcp_handle_write(void* arg /* grpc_tcp */,
1777 grpc_error_handle error) {
1778 grpc_tcp* tcp = static_cast<grpc_tcp*>(arg);
1779 grpc_closure* cb;
1780
1781 if (!error.ok()) {
1782 cb = tcp->write_cb;
1783 tcp->write_cb = nullptr;
1784 if (tcp->current_zerocopy_send != nullptr) {
1785 UnrefMaybePutZerocopySendRecord(tcp, tcp->current_zerocopy_send, 0,
1786 "handle_write_err");
1787 tcp->current_zerocopy_send = nullptr;
1788 }
1789 grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
1790 TCP_UNREF(tcp, "write");
1791 return;
1792 }
1793 bool flush_result =
1794 tcp->current_zerocopy_send != nullptr
1795 ? tcp_flush_zerocopy(tcp, tcp->current_zerocopy_send, &error)
1796 : tcp_flush(tcp, &error);
1797 if (!flush_result) {
1798 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1799 gpr_log(GPR_INFO, "write: delayed");
1800 }
1801 notify_on_write(tcp);
1802 // tcp_flush does not populate error if it has returned false.
1803 GPR_DEBUG_ASSERT(error.ok());
1804 } else {
1805 cb = tcp->write_cb;
1806 tcp->write_cb = nullptr;
1807 tcp->current_zerocopy_send = nullptr;
1808 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1809 gpr_log(GPR_INFO, "write: %s", grpc_core::StatusToString(error).c_str());
1810 }
1811 // No need to take a ref on error since tcp_flush provides a ref.
1812 grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
1813 TCP_UNREF(tcp, "write");
1814 }
1815 }
1816
1817 static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf,
1818 grpc_closure* cb, void* arg, int /*max_frame_size*/) {
1819 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
1820 grpc_error_handle error;
1821 TcpZerocopySendRecord* zerocopy_send_record = nullptr;
1822
1823 grpc_core::EventLog::Append("tcp-write-outstanding", buf->length);
1824
1825 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1826 size_t i;
1827
1828 for (i = 0; i < buf->count; i++) {
1829 gpr_log(GPR_INFO, "WRITE %p (peer=%s)", tcp, tcp->peer_string.c_str());
1830 if (gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) {
1831 char* data =
1832 grpc_dump_slice(buf->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII);
1833 gpr_log(GPR_DEBUG, "WRITE DATA: %s", data);
1834 gpr_free(data);
1835 }
1836 }
1837 }
1838
1839 GPR_ASSERT(tcp->write_cb == nullptr);
1840 GPR_DEBUG_ASSERT(tcp->current_zerocopy_send == nullptr);
1841
1842 if (buf->length == 0) {
1843 grpc_core::Closure::Run(
1844 DEBUG_LOCATION, cb,
1845 grpc_fd_is_shutdown(tcp->em_fd)
1846 ? tcp_annotate_error(GRPC_ERROR_CREATE("EOF"), tcp)
1847 : absl::OkStatus());
1848 tcp_shutdown_buffer_list(tcp);
1849 return;
1850 }
1851
1852 zerocopy_send_record = tcp_get_send_zerocopy_record(tcp, buf);
1853 if (zerocopy_send_record == nullptr) {
1854 // Either not enough bytes, or couldn't allocate a zerocopy context.
1855 tcp->outgoing_buffer = buf;
1856 tcp->outgoing_byte_idx = 0;
1857 }
1858 tcp->outgoing_buffer_arg = arg;
1859 if (arg) {
1860 GPR_ASSERT(grpc_event_engine_can_track_errors());
1861 }
1862
1863 bool flush_result =
1864 zerocopy_send_record != nullptr
1865 ? tcp_flush_zerocopy(tcp, zerocopy_send_record, &error)
1866 : tcp_flush(tcp, &error);
1867 if (!flush_result) {
1868 TCP_REF(tcp, "write");
1869 tcp->write_cb = cb;
1870 tcp->current_zerocopy_send = zerocopy_send_record;
1871 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1872 gpr_log(GPR_INFO, "write: delayed");
1873 }
1874 notify_on_write(tcp);
1875 } else {
1876 if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) {
1877 gpr_log(GPR_INFO, "write: %s", grpc_core::StatusToString(error).c_str());
1878 }
1879 grpc_core::Closure::Run(DEBUG_LOCATION, cb, error);
1880 }
1881 }
1882
1883 static void tcp_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
1884 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
1885 grpc_pollset_add_fd(pollset, tcp->em_fd);
1886 }
1887
1888 static void tcp_add_to_pollset_set(grpc_endpoint* ep,
1889 grpc_pollset_set* pollset_set) {
1890 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
1891 grpc_pollset_set_add_fd(pollset_set, tcp->em_fd);
1892 }
1893
1894 static void tcp_delete_from_pollset_set(grpc_endpoint* ep,
1895 grpc_pollset_set* pollset_set) {
1896 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
1897 grpc_pollset_set_del_fd(pollset_set, tcp->em_fd);
1898 }
1899
1900 static absl::string_view tcp_get_peer(grpc_endpoint* ep) {
1901 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
1902 return tcp->peer_string;
1903 }
1904
1905 static absl::string_view tcp_get_local_address(grpc_endpoint* ep) {
1906 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
1907 return tcp->local_address;
1908 }
1909
1910 static int tcp_get_fd(grpc_endpoint* ep) {
1911 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
1912 return tcp->fd;
1913 }
1914
1915 static bool tcp_can_track_err(grpc_endpoint* ep) {
1916 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
1917 if (!grpc_event_engine_can_track_errors()) {
1918 return false;
1919 }
1920 struct sockaddr addr;
1921 socklen_t len = sizeof(addr);
1922 if (getsockname(tcp->fd, &addr, &len) < 0) {
1923 return false;
1924 }
1925 return addr.sa_family == AF_INET || addr.sa_family == AF_INET6;
1926 }
1927
1928 static const grpc_endpoint_vtable vtable = {tcp_read,
1929 tcp_write,
1930 tcp_add_to_pollset,
1931 tcp_add_to_pollset_set,
1932 tcp_delete_from_pollset_set,
1933 tcp_shutdown,
1934 tcp_destroy,
1935 tcp_get_peer,
1936 tcp_get_local_address,
1937 tcp_get_fd,
1938 tcp_can_track_err};
1939
1940 grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd,
1941 const grpc_core::PosixTcpOptions& options,
1942 absl::string_view peer_string) {
1943 grpc_tcp* tcp = new grpc_tcp(options);
1944 tcp->base.vtable = &vtable;
1945 tcp->peer_string = std::string(peer_string);
1946 tcp->fd = grpc_fd_wrapped_fd(em_fd);
1947 GPR_ASSERT(options.resource_quota != nullptr);
1948 tcp->memory_owner =
1949 options.resource_quota->memory_quota()->CreateMemoryOwner(peer_string);
1950 tcp->self_reservation = tcp->memory_owner.MakeReservation(sizeof(grpc_tcp));
1951 grpc_resolved_address resolved_local_addr;
1952 memset(&resolved_local_addr, 0, sizeof(resolved_local_addr));
1953 resolved_local_addr.len = sizeof(resolved_local_addr.addr);
1954 absl::StatusOr<std::string> addr_uri;
1955 if (getsockname(tcp->fd,
1956 reinterpret_cast<sockaddr*>(resolved_local_addr.addr),
1957 &resolved_local_addr.len) < 0 ||
1958 !(addr_uri = grpc_sockaddr_to_uri(&resolved_local_addr)).ok()) {
1959 tcp->local_address = "";
1960 } else {
1961 tcp->local_address = addr_uri.value();
1962 }
1963 tcp->read_cb = nullptr;
1964 tcp->write_cb = nullptr;
1965 tcp->current_zerocopy_send = nullptr;
1966 tcp->release_fd_cb = nullptr;
1967 tcp->release_fd = nullptr;
1968 tcp->target_length = static_cast<double>(options.tcp_read_chunk_size);
1969 tcp->bytes_read_this_round = 0;
1970 /* Will be set to false by the very first endpoint read function */
1971 tcp->is_first_read = true;
1972 tcp->bytes_counter = -1;
1973 tcp->socket_ts_enabled = false;
1974 tcp->ts_capable = true;
1975 tcp->outgoing_buffer_arg = nullptr;
1976 tcp->min_progress_size = 1;
1977 if (options.tcp_tx_zero_copy_enabled &&
1978 !tcp->tcp_zerocopy_send_ctx.memory_limited()) {
1979 #ifdef GRPC_LINUX_ERRQUEUE
1980 const int enable = 1;
1981 auto err =
1982 setsockopt(tcp->fd, SOL_SOCKET, SO_ZEROCOPY, &enable, sizeof(enable));
1983 if (err == 0) {
1984 tcp->tcp_zerocopy_send_ctx.set_enabled(true);
1985 } else {
1986 gpr_log(GPR_ERROR, "Failed to set zerocopy options on the socket.");
1987 }
1988 #endif
1989 }
1990 /* paired with unref in grpc_tcp_destroy */
1991 new (&tcp->refcount) grpc_core::RefCount(
1992 1, GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace) ? "tcp" : nullptr);
1993 gpr_atm_no_barrier_store(&tcp->shutdown_count, 0);
1994 tcp->em_fd = em_fd;
1995 grpc_slice_buffer_init(&tcp->last_read_buffer);
1996 GRPC_CLOSURE_INIT(&tcp->read_done_closure, tcp_handle_read, tcp,
1997 grpc_schedule_on_exec_ctx);
1998 if (grpc_event_engine_run_in_background()) {
1999 // If there is a polling engine always running in the background, there is
2000 // no need to run the backup poller.
2001 GRPC_CLOSURE_INIT(&tcp->write_done_closure, tcp_handle_write, tcp,
2002 grpc_schedule_on_exec_ctx);
2003 } else {
2004 GRPC_CLOSURE_INIT(&tcp->write_done_closure,
2005 tcp_drop_uncovered_then_handle_write, tcp,
2006 grpc_schedule_on_exec_ctx);
2007 }
2008 /* Always assume there is something on the queue to read. */
2009 tcp->inq = 1;
2010 #ifdef GRPC_HAVE_TCP_INQ
2011 int one = 1;
2012 if (setsockopt(tcp->fd, SOL_TCP, TCP_INQ, &one, sizeof(one)) == 0) {
2013 tcp->inq_capable = true;
2014 } else {
2015 gpr_log(GPR_DEBUG, "cannot set inq fd=%d errno=%d", tcp->fd, errno);
2016 tcp->inq_capable = false;
2017 }
2018 #else
2019 tcp->inq_capable = false;
2020 #endif /* GRPC_HAVE_TCP_INQ */
2021 /* Start being notified on errors if event engine can track errors. */
2022 if (grpc_event_engine_can_track_errors()) {
2023 /* Grab a ref to tcp so that we can safely access the tcp struct when
2024 * processing errors. We unref when we no longer want to track errors
2025 * separately. */
2026 TCP_REF(tcp, "error-tracking");
2027 gpr_atm_rel_store(&tcp->stop_error_notification, 0);
2028 GRPC_CLOSURE_INIT(&tcp->error_closure, tcp_handle_error, tcp,
2029 grpc_schedule_on_exec_ctx);
2030 grpc_fd_notify_on_error(tcp->em_fd, &tcp->error_closure);
2031 }
2032
2033 return &tcp->base;
2034 }
2035
2036 int grpc_tcp_fd(grpc_endpoint* ep) {
2037 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
2038 GPR_ASSERT(ep->vtable == &vtable);
2039 return grpc_fd_wrapped_fd(tcp->em_fd);
2040 }
2041
2042 void grpc_tcp_destroy_and_release_fd(grpc_endpoint* ep, int* fd,
2043 grpc_closure* done) {
2044 grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep);
2045 GPR_ASSERT(ep->vtable == &vtable);
2046 tcp->release_fd = fd;
2047 tcp->release_fd_cb = done;
2048 grpc_slice_buffer_reset_and_unref(&tcp->last_read_buffer);
2049 if (grpc_event_engine_can_track_errors()) {
2050 /* Stop errors notification. */
2051 ZerocopyDisableAndWaitForRemaining(tcp);
2052 gpr_atm_no_barrier_store(&tcp->stop_error_notification, true);
2053 grpc_fd_set_error(tcp->em_fd);
2054 }
2055 TCP_UNREF(tcp, "destroy");
2056 }
2057
2058 void grpc_tcp_posix_init() { g_backup_poller_mu = new grpc_core::Mutex; }
2059
2060 void grpc_tcp_posix_shutdown() {
2061 delete g_backup_poller_mu;
2062 g_backup_poller_mu = nullptr;
2063 }
2064
2065 #endif /* GRPC_POSIX_SOCKET_TCP */