Debian Codegraph @

src/core/lib/surface/completion_queue.cc

raw
1 /*
2 *
3 * Copyright 2015-2016 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 #include <grpc/support/port_platform.h>
19
20 #include "src/core/lib/surface/completion_queue.h"
21
22 #include <inttypes.h>
23 #include <stdio.h>
24
25 #include <algorithm>
26 #include <atomic>
27 #include <new>
28 #include <string>
29 #include <utility>
30 #include <vector>
31
32 #include "absl/status/status.h"
33 #include "absl/strings/str_format.h"
34 #include "absl/strings/str_join.h"
35
36 #include <grpc/grpc.h>
37 #include <grpc/impl/codegen/gpr_types.h>
38 #include <grpc/support/alloc.h>
39 #include <grpc/support/atm.h>
40 #include <grpc/support/log.h>
41 #include <grpc/support/sync.h>
42
43 #include "src/core/lib/debug/stats.h"
44 #include "src/core/lib/debug/stats_data.h"
45 #include "src/core/lib/gpr/spinlock.h"
46 #include "src/core/lib/gprpp/atomic_utils.h"
47 #include "src/core/lib/gprpp/debug_location.h"
48 #include "src/core/lib/gprpp/ref_counted.h"
49 #include "src/core/lib/gprpp/status_helper.h"
50 #include "src/core/lib/gprpp/time.h"
51 #include "src/core/lib/iomgr/closure.h"
52 #include "src/core/lib/iomgr/exec_ctx.h"
53 #include "src/core/lib/iomgr/executor.h"
54 #include "src/core/lib/iomgr/iomgr.h"
55 #include "src/core/lib/iomgr/pollset.h"
56 #include "src/core/lib/surface/api_trace.h"
57 #include "src/core/lib/surface/event_string.h"
58
59 grpc_core::TraceFlag grpc_trace_operation_failures(false, "op_failure");
60 grpc_core::DebugOnlyTraceFlag grpc_trace_pending_tags(false, "pending_tags");
61 grpc_core::DebugOnlyTraceFlag grpc_trace_cq_refcount(false, "cq_refcount");
62
63 namespace {
64
65 // Specifies a cq thread local cache.
66 // The first event that occurs on a thread
67 // with a cq cache will go into that cache, and
68 // will only be returned on the thread that initialized the cache.
69 // NOTE: Only one event will ever be cached.
70 thread_local grpc_cq_completion* g_cached_event;
71 thread_local grpc_completion_queue* g_cached_cq;
72
73 struct plucker {
74 grpc_pollset_worker** worker;
75 void* tag;
76 };
77 struct cq_poller_vtable {
78 bool can_get_pollset;
79 bool can_listen;
80 size_t (*size)(void);
81 void (*init)(grpc_pollset* pollset, gpr_mu** mu);
82 grpc_error_handle (*kick)(grpc_pollset* pollset,
83 grpc_pollset_worker* specific_worker);
84 grpc_error_handle (*work)(grpc_pollset* pollset, grpc_pollset_worker** worker,
85 grpc_core::Timestamp deadline);
86 void (*shutdown)(grpc_pollset* pollset, grpc_closure* closure);
87 void (*destroy)(grpc_pollset* pollset);
88 };
89 typedef struct non_polling_worker {
90 gpr_cv cv;
91 bool kicked;
92 struct non_polling_worker* next;
93 struct non_polling_worker* prev;
94 } non_polling_worker;
95
96 struct non_polling_poller {
97 gpr_mu mu;
98 bool kicked_without_poller;
99 non_polling_worker* root;
100 grpc_closure* shutdown;
101 };
102 size_t non_polling_poller_size(void) { return sizeof(non_polling_poller); }
103
104 void non_polling_poller_init(grpc_pollset* pollset, gpr_mu** mu) {
105 non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset);
106 gpr_mu_init(&npp->mu);
107 *mu = &npp->mu;
108 }
109
110 void non_polling_poller_destroy(grpc_pollset* pollset) {
111 non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset);
112 gpr_mu_destroy(&npp->mu);
113 }
114
115 grpc_error_handle non_polling_poller_work(grpc_pollset* pollset,
116 grpc_pollset_worker** worker,
117 grpc_core::Timestamp deadline) {
118 non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset);
119 if (npp->shutdown) return absl::OkStatus();
120 if (npp->kicked_without_poller) {
121 npp->kicked_without_poller = false;
122 return absl::OkStatus();
123 }
124 non_polling_worker w;
125 gpr_cv_init(&w.cv);
126 if (worker != nullptr) *worker = reinterpret_cast<grpc_pollset_worker*>(&w);
127 if (npp->root == nullptr) {
128 npp->root = w.next = w.prev = &w;
129 } else {
130 w.next = npp->root;
131 w.prev = w.next->prev;
132 w.next->prev = w.prev->next = &w;
133 }
134 w.kicked = false;
135 gpr_timespec deadline_ts = deadline.as_timespec(GPR_CLOCK_MONOTONIC);
136 while (!npp->shutdown && !w.kicked &&
137 !gpr_cv_wait(&w.cv, &npp->mu, deadline_ts)) {
138 }
139 grpc_core::ExecCtx::Get()->InvalidateNow();
140 if (&w == npp->root) {
141 npp->root = w.next;
142 if (&w == npp->root) {
143 if (npp->shutdown) {
144 grpc_core::ExecCtx::Run(DEBUG_LOCATION, npp->shutdown,
145 absl::OkStatus());
146 }
147 npp->root = nullptr;
148 }
149 }
150 w.next->prev = w.prev;
151 w.prev->next = w.next;
152 gpr_cv_destroy(&w.cv);
153 if (worker != nullptr) *worker = nullptr;
154 return absl::OkStatus();
155 }
156
157 grpc_error_handle non_polling_poller_kick(
158 grpc_pollset* pollset, grpc_pollset_worker* specific_worker) {
159 non_polling_poller* p = reinterpret_cast<non_polling_poller*>(pollset);
160 if (specific_worker == nullptr) {
161 specific_worker = reinterpret_cast<grpc_pollset_worker*>(p->root);
162 }
163 if (specific_worker != nullptr) {
164 non_polling_worker* w =
165 reinterpret_cast<non_polling_worker*>(specific_worker);
166 if (!w->kicked) {
167 w->kicked = true;
168 gpr_cv_signal(&w->cv);
169 }
170 } else {
171 p->kicked_without_poller = true;
172 }
173 return absl::OkStatus();
174 }
175
176 void non_polling_poller_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
177 non_polling_poller* p = reinterpret_cast<non_polling_poller*>(pollset);
178 GPR_ASSERT(closure != nullptr);
179 p->shutdown = closure;
180 if (p->root == nullptr) {
181 grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, absl::OkStatus());
182 } else {
183 non_polling_worker* w = p->root;
184 do {
185 gpr_cv_signal(&w->cv);
186 w = w->next;
187 } while (w != p->root);
188 }
189 }
190
191 const cq_poller_vtable g_poller_vtable_by_poller_type[] = {
192 /* GRPC_CQ_DEFAULT_POLLING */
193 {true, true, grpc_pollset_size, grpc_pollset_init, grpc_pollset_kick,
194 grpc_pollset_work, grpc_pollset_shutdown, grpc_pollset_destroy},
195 /* GRPC_CQ_NON_LISTENING */
196 {true, false, grpc_pollset_size, grpc_pollset_init, grpc_pollset_kick,
197 grpc_pollset_work, grpc_pollset_shutdown, grpc_pollset_destroy},
198 /* GRPC_CQ_NON_POLLING */
199 {false, false, non_polling_poller_size, non_polling_poller_init,
200 non_polling_poller_kick, non_polling_poller_work,
201 non_polling_poller_shutdown, non_polling_poller_destroy},
202 };
203
204 } // namespace
205
206 struct cq_vtable {
207 grpc_cq_completion_type cq_completion_type;
208 size_t data_size;
209 void (*init)(void* data, grpc_completion_queue_functor* shutdown_callback);
210 void (*shutdown)(grpc_completion_queue* cq);
211 void (*destroy)(void* data);
212 bool (*begin_op)(grpc_completion_queue* cq, void* tag);
213 void (*end_op)(grpc_completion_queue* cq, void* tag, grpc_error_handle error,
214 void (*done)(void* done_arg, grpc_cq_completion* storage),
215 void* done_arg, grpc_cq_completion* storage, bool internal);
216 grpc_event (*next)(grpc_completion_queue* cq, gpr_timespec deadline,
217 void* reserved);
218 grpc_event (*pluck)(grpc_completion_queue* cq, void* tag,
219 gpr_timespec deadline, void* reserved);
220 };
221
222 namespace {
223
224 /* Queue that holds the cq_completion_events. Internally uses
225 * MultiProducerSingleConsumerQueue (a lockfree multiproducer single consumer
226 * queue). It uses a queue_lock to support multiple consumers.
227 * Only used in completion queues whose completion_type is GRPC_CQ_NEXT */
228 class CqEventQueue {
229 public:
230 CqEventQueue() = default;
231 ~CqEventQueue() = default;
232
233 /* Note: The counter is not incremented/decremented atomically with push/pop.
234 * The count is only eventually consistent */
235 intptr_t num_items() const {
236 return num_queue_items_.load(std::memory_order_relaxed);
237 }
238
239 bool Push(grpc_cq_completion* c);
240 grpc_cq_completion* Pop();
241
242 private:
243 /* Spinlock to serialize consumers i.e pop() operations */
244 gpr_spinlock queue_lock_ = GPR_SPINLOCK_INITIALIZER;
245
246 grpc_core::MultiProducerSingleConsumerQueue queue_;
247
248 /* A lazy counter of number of items in the queue. This is NOT atomically
249 incremented/decremented along with push/pop operations and hence is only
250 eventually consistent */
251 std::atomic<intptr_t> num_queue_items_{0};
252 };
253
254 struct cq_next_data {
255 ~cq_next_data() {
256 GPR_ASSERT(queue.num_items() == 0);
257 #ifndef NDEBUG
258 if (pending_events.load(std::memory_order_acquire) != 0) {
259 gpr_log(GPR_ERROR, "Destroying CQ without draining it fully.");
260 }
261 #endif
262 }
263
264 /** Completed events for completion-queues of type GRPC_CQ_NEXT */
265 CqEventQueue queue;
266
267 /** Counter of how many things have ever been queued on this completion queue
268 useful for avoiding locks to check the queue */
269 std::atomic<intptr_t> things_queued_ever{0};
270
271 /** Number of outstanding events (+1 if not shut down)
272 Initial count is dropped by grpc_completion_queue_shutdown */
273 std::atomic<intptr_t> pending_events{1};
274
275 /** 0 initially. 1 once we initiated shutdown */
276 bool shutdown_called = false;
277 };
278
279 struct cq_pluck_data {
280 cq_pluck_data() {
281 completed_tail = &completed_head;
282 completed_head.next = reinterpret_cast<uintptr_t>(completed_tail);
283 }
284
285 ~cq_pluck_data() {
286 GPR_ASSERT(completed_head.next ==
287 reinterpret_cast<uintptr_t>(&completed_head));
288 #ifndef NDEBUG
289 if (pending_events.load(std::memory_order_acquire) != 0) {
290 gpr_log(GPR_ERROR, "Destroying CQ without draining it fully.");
291 }
292 #endif
293 }
294
295 /** Completed events for completion-queues of type GRPC_CQ_PLUCK */
296 grpc_cq_completion completed_head;
297 grpc_cq_completion* completed_tail;
298
299 /** Number of pending events (+1 if we're not shutdown).
300 Initial count is dropped by grpc_completion_queue_shutdown. */
301 std::atomic<intptr_t> pending_events{1};
302
303 /** Counter of how many things have ever been queued on this completion queue
304 useful for avoiding locks to check the queue */
305 std::atomic<intptr_t> things_queued_ever{0};
306
307 /** 0 initially. 1 once we completed shutting */
308 /* TODO: (sreek) This is not needed since (shutdown == 1) if and only if
309 * (pending_events == 0). So consider removing this in future and use
310 * pending_events */
311 std::atomic<bool> shutdown{false};
312
313 /** 0 initially. 1 once we initiated shutdown */
314 bool shutdown_called = false;
315
316 int num_pluckers = 0;
317 plucker pluckers[GRPC_MAX_COMPLETION_QUEUE_PLUCKERS];
318 };
319
320 struct cq_callback_data {
321 explicit cq_callback_data(grpc_completion_queue_functor* shutdown_callback)
322 : shutdown_callback(shutdown_callback) {}
323
324 ~cq_callback_data() {
325 #ifndef NDEBUG
326 if (pending_events.load(std::memory_order_acquire) != 0) {
327 gpr_log(GPR_ERROR, "Destroying CQ without draining it fully.");
328 }
329 #endif
330 }
331
332 /** No actual completed events queue, unlike other types */
333
334 /** Number of pending events (+1 if we're not shutdown).
335 Initial count is dropped by grpc_completion_queue_shutdown. */
336 std::atomic<intptr_t> pending_events{1};
337
338 /** 0 initially. 1 once we initiated shutdown */
339 bool shutdown_called = false;
340
341 /** A callback that gets invoked when the CQ completes shutdown */
342 grpc_completion_queue_functor* shutdown_callback;
343 };
344
345 } // namespace
346
347 /* Completion queue structure */
348 struct grpc_completion_queue {
349 /** Once owning_refs drops to zero, we will destroy the cq */
350 grpc_core::RefCount owning_refs;
351
352 gpr_mu* mu;
353
354 const cq_vtable* vtable;
355 const cq_poller_vtable* poller_vtable;
356
357 #ifndef NDEBUG
358 void** outstanding_tags;
359 size_t outstanding_tag_count;
360 size_t outstanding_tag_capacity;
361 #endif
362
363 grpc_closure pollset_shutdown_done;
364 int num_polls;
365 };
366
367 /* Forward declarations */
368 static void cq_finish_shutdown_next(grpc_completion_queue* cq);
369 static void cq_finish_shutdown_pluck(grpc_completion_queue* cq);
370 static void cq_finish_shutdown_callback(grpc_completion_queue* cq);
371 static void cq_shutdown_next(grpc_completion_queue* cq);
372 static void cq_shutdown_pluck(grpc_completion_queue* cq);
373 static void cq_shutdown_callback(grpc_completion_queue* cq);
374
375 static bool cq_begin_op_for_next(grpc_completion_queue* cq, void* tag);
376 static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* tag);
377 static bool cq_begin_op_for_callback(grpc_completion_queue* cq, void* tag);
378
379 // A cq_end_op function is called when an operation on a given CQ with
380 // a given tag has completed. The storage argument is a reference to the
381 // space reserved for this completion as it is placed into the corresponding
382 // queue. The done argument is a callback that will be invoked when it is
383 // safe to free up that storage. The storage MUST NOT be freed until the
384 // done callback is invoked.
385 static void cq_end_op_for_next(
386 grpc_completion_queue* cq, void* tag, grpc_error_handle error,
387 void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
388 grpc_cq_completion* storage, bool internal);
389
390 static void cq_end_op_for_pluck(
391 grpc_completion_queue* cq, void* tag, grpc_error_handle error,
392 void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
393 grpc_cq_completion* storage, bool internal);
394
395 static void cq_end_op_for_callback(
396 grpc_completion_queue* cq, void* tag, grpc_error_handle error,
397 void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
398 grpc_cq_completion* storage, bool internal);
399
400 static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
401 void* reserved);
402
403 static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
404 gpr_timespec deadline, void* reserved);
405
406 // Note that cq_init_next and cq_init_pluck do not use the shutdown_callback
407 static void cq_init_next(void* data,
408 grpc_completion_queue_functor* shutdown_callback);
409 static void cq_init_pluck(void* data,
410 grpc_completion_queue_functor* shutdown_callback);
411 static void cq_init_callback(void* data,
412 grpc_completion_queue_functor* shutdown_callback);
413 static void cq_destroy_next(void* data);
414 static void cq_destroy_pluck(void* data);
415 static void cq_destroy_callback(void* data);
416
417 /* Completion queue vtables based on the completion-type */
418 static const cq_vtable g_cq_vtable[] = {
419 /* GRPC_CQ_NEXT */
420 {GRPC_CQ_NEXT, sizeof(cq_next_data), cq_init_next, cq_shutdown_next,
421 cq_destroy_next, cq_begin_op_for_next, cq_end_op_for_next, cq_next,
422 nullptr},
423 /* GRPC_CQ_PLUCK */
424 {GRPC_CQ_PLUCK, sizeof(cq_pluck_data), cq_init_pluck, cq_shutdown_pluck,
425 cq_destroy_pluck, cq_begin_op_for_pluck, cq_end_op_for_pluck, nullptr,
426 cq_pluck},
427 /* GRPC_CQ_CALLBACK */
428 {GRPC_CQ_CALLBACK, sizeof(cq_callback_data), cq_init_callback,
429 cq_shutdown_callback, cq_destroy_callback, cq_begin_op_for_callback,
430 cq_end_op_for_callback, nullptr, nullptr},
431 };
432
433 #define DATA_FROM_CQ(cq) ((void*)((cq) + 1))
434 #define POLLSET_FROM_CQ(cq) \
435 ((grpc_pollset*)((cq)->vtable->data_size + (char*)DATA_FROM_CQ(cq)))
436
437 grpc_core::TraceFlag grpc_cq_pluck_trace(false, "queue_pluck");
438
439 #define GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, event) \
440 do { \
441 if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) && \
442 (GRPC_TRACE_FLAG_ENABLED(grpc_cq_pluck_trace) || \
443 (event)->type != GRPC_QUEUE_TIMEOUT)) { \
444 gpr_log(GPR_INFO, "RETURN_EVENT[%p]: %s", cq, \
445 grpc_event_string(event).c_str()); \
446 } \
447 } while (0)
448
449 static void on_pollset_shutdown_done(void* arg, grpc_error_handle error);
450
451 void grpc_completion_queue_thread_local_cache_init(grpc_completion_queue* cq) {
452 if (g_cached_cq == nullptr) {
453 g_cached_event = nullptr;
454 g_cached_cq = cq;
455 }
456 }
457
458 int grpc_completion_queue_thread_local_cache_flush(grpc_completion_queue* cq,
459 void** tag, int* ok) {
460 grpc_cq_completion* storage = g_cached_event;
461 int ret = 0;
462 if (storage != nullptr && g_cached_cq == cq) {
463 *tag = storage->tag;
464 grpc_core::ExecCtx exec_ctx;
465 *ok = (storage->next & static_cast<uintptr_t>(1)) == 1;
466 storage->done(storage->done_arg, storage);
467 ret = 1;
468 cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
469 if (cqd->pending_events.fetch_sub(1, std::memory_order_acq_rel) == 1) {
470 GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
471 gpr_mu_lock(cq->mu);
472 cq_finish_shutdown_next(cq);
473 gpr_mu_unlock(cq->mu);
474 GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
475 }
476 }
477 g_cached_event = nullptr;
478 g_cached_cq = nullptr;
479
480 return ret;
481 }
482
483 bool CqEventQueue::Push(grpc_cq_completion* c) {
484 queue_.Push(
485 reinterpret_cast<grpc_core::MultiProducerSingleConsumerQueue::Node*>(c));
486 return num_queue_items_.fetch_add(1, std::memory_order_relaxed) == 0;
487 }
488
489 grpc_cq_completion* CqEventQueue::Pop() {
490 grpc_cq_completion* c = nullptr;
491
492 if (gpr_spinlock_trylock(&queue_lock_)) {
493 bool is_empty = false;
494 c = reinterpret_cast<grpc_cq_completion*>(queue_.PopAndCheckEnd(&is_empty));
495 gpr_spinlock_unlock(&queue_lock_);
496 }
497
498 if (c) {
499 num_queue_items_.fetch_sub(1, std::memory_order_relaxed);
500 }
501
502 return c;
503 }
504
505 grpc_completion_queue* grpc_completion_queue_create_internal(
506 grpc_cq_completion_type completion_type, grpc_cq_polling_type polling_type,
507 grpc_completion_queue_functor* shutdown_callback) {
508 grpc_completion_queue* cq;
509
510 GRPC_API_TRACE(
511 "grpc_completion_queue_create_internal(completion_type=%d, "
512 "polling_type=%d)",
513 2, (completion_type, polling_type));
514
515 switch (completion_type) {
516 case GRPC_CQ_NEXT:
517 grpc_core::global_stats().IncrementCqNextCreates();
518 break;
519 case GRPC_CQ_PLUCK:
520 grpc_core::global_stats().IncrementCqPluckCreates();
521 break;
522 case GRPC_CQ_CALLBACK:
523 grpc_core::global_stats().IncrementCqCallbackCreates();
524 break;
525 }
526
527 const cq_vtable* vtable = &g_cq_vtable[completion_type];
528 const cq_poller_vtable* poller_vtable =
529 &g_poller_vtable_by_poller_type[polling_type];
530
531 grpc_core::ExecCtx exec_ctx;
532
533 cq = static_cast<grpc_completion_queue*>(
534 gpr_zalloc(sizeof(grpc_completion_queue) + vtable->data_size +
535 poller_vtable->size()));
536
537 cq->vtable = vtable;
538 cq->poller_vtable = poller_vtable;
539
540 /* One for destroy(), one for pollset_shutdown */
541 new (&cq->owning_refs) grpc_core::RefCount(2);
542
543 poller_vtable->init(POLLSET_FROM_CQ(cq), &cq->mu);
544 vtable->init(DATA_FROM_CQ(cq), shutdown_callback);
545
546 GRPC_CLOSURE_INIT(&cq->pollset_shutdown_done, on_pollset_shutdown_done, cq,
547 grpc_schedule_on_exec_ctx);
548 return cq;
549 }
550
551 static void cq_init_next(void* data,
552 grpc_completion_queue_functor* /*shutdown_callback*/) {
553 new (data) cq_next_data();
554 }
555
556 static void cq_destroy_next(void* data) {
557 cq_next_data* cqd = static_cast<cq_next_data*>(data);
558 cqd->~cq_next_data();
559 }
560
561 static void cq_init_pluck(
562 void* data, grpc_completion_queue_functor* /*shutdown_callback*/) {
563 new (data) cq_pluck_data();
564 }
565
566 static void cq_destroy_pluck(void* data) {
567 cq_pluck_data* cqd = static_cast<cq_pluck_data*>(data);
568 cqd->~cq_pluck_data();
569 }
570
571 static void cq_init_callback(void* data,
572 grpc_completion_queue_functor* shutdown_callback) {
573 new (data) cq_callback_data(shutdown_callback);
574 }
575
576 static void cq_destroy_callback(void* data) {
577 cq_callback_data* cqd = static_cast<cq_callback_data*>(data);
578 cqd->~cq_callback_data();
579 }
580
581 grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cq) {
582 return cq->vtable->cq_completion_type;
583 }
584
585 int grpc_get_cq_poll_num(grpc_completion_queue* cq) {
586 int cur_num_polls;
587 gpr_mu_lock(cq->mu);
588 cur_num_polls = cq->num_polls;
589 gpr_mu_unlock(cq->mu);
590 return cur_num_polls;
591 }
592
593 #ifndef NDEBUG
594 void grpc_cq_internal_ref(grpc_completion_queue* cq, const char* reason,
595 const char* file, int line) {
596 grpc_core::DebugLocation debug_location(file, line);
597 #else
598 void grpc_cq_internal_ref(grpc_completion_queue* cq) {
599 grpc_core::DebugLocation debug_location;
600 const char* reason = nullptr;
601 #endif
602 cq->owning_refs.Ref(debug_location, reason);
603 }
604
605 static void on_pollset_shutdown_done(void* arg, grpc_error_handle /*error*/) {
606 grpc_completion_queue* cq = static_cast<grpc_completion_queue*>(arg);
607 GRPC_CQ_INTERNAL_UNREF(cq, "pollset_destroy");
608 }
609
610 #ifndef NDEBUG
611 void grpc_cq_internal_unref(grpc_completion_queue* cq, const char* reason,
612 const char* file, int line) {
613 grpc_core::DebugLocation debug_location(file, line);
614 #else
615 void grpc_cq_internal_unref(grpc_completion_queue* cq) {
616 grpc_core::DebugLocation debug_location;
617 const char* reason = nullptr;
618 #endif
619 if (GPR_UNLIKELY(cq->owning_refs.Unref(debug_location, reason))) {
620 cq->vtable->destroy(DATA_FROM_CQ(cq));
621 cq->poller_vtable->destroy(POLLSET_FROM_CQ(cq));
622 #ifndef NDEBUG
623 gpr_free(cq->outstanding_tags);
624 #endif
625 gpr_free(cq);
626 }
627 }
628
629 #ifndef NDEBUG
630 static void cq_check_tag(grpc_completion_queue* cq, void* tag, bool lock_cq) {
631 int found = 0;
632 if (lock_cq) {
633 gpr_mu_lock(cq->mu);
634 }
635
636 for (int i = 0; i < static_cast<int>(cq->outstanding_tag_count); i++) {
637 if (cq->outstanding_tags[i] == tag) {
638 cq->outstanding_tag_count--;
639 std::swap(cq->outstanding_tags[i],
640 cq->outstanding_tags[cq->outstanding_tag_count]);
641 found = 1;
642 break;
643 }
644 }
645
646 if (lock_cq) {
647 gpr_mu_unlock(cq->mu);
648 }
649
650 GPR_ASSERT(found);
651 }
652 #else
653 static void cq_check_tag(grpc_completion_queue* /*cq*/, void* /*tag*/,
654 bool /*lock_cq*/) {}
655 #endif
656
657 static bool cq_begin_op_for_next(grpc_completion_queue* cq, void* /*tag*/) {
658 cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
659 return grpc_core::IncrementIfNonzero(&cqd->pending_events);
660 }
661
662 static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* /*tag*/) {
663 cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
664 return grpc_core::IncrementIfNonzero(&cqd->pending_events);
665 }
666
667 static bool cq_begin_op_for_callback(grpc_completion_queue* cq, void* /*tag*/) {
668 cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq);
669 return grpc_core::IncrementIfNonzero(&cqd->pending_events);
670 }
671
672 bool grpc_cq_begin_op(grpc_completion_queue* cq, void* tag) {
673 #ifndef NDEBUG
674 gpr_mu_lock(cq->mu);
675 if (cq->outstanding_tag_count == cq->outstanding_tag_capacity) {
676 cq->outstanding_tag_capacity =
677 std::max(size_t(4), 2 * cq->outstanding_tag_capacity);
678 cq->outstanding_tags = static_cast<void**>(gpr_realloc(
679 cq->outstanding_tags,
680 sizeof(*cq->outstanding_tags) * cq->outstanding_tag_capacity));
681 }
682 cq->outstanding_tags[cq->outstanding_tag_count++] = tag;
683 gpr_mu_unlock(cq->mu);
684 #endif
685 return cq->vtable->begin_op(cq, tag);
686 }
687
688 /* Queue a GRPC_OP_COMPLETED operation to a completion queue (with a
689 * completion
690 * type of GRPC_CQ_NEXT) */
691 static void cq_end_op_for_next(
692 grpc_completion_queue* cq, void* tag, grpc_error_handle error,
693 void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
694 grpc_cq_completion* storage, bool /*internal*/) {
695 if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) ||
696 (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) && !error.ok())) {
697 std::string errmsg = grpc_core::StatusToString(error);
698 GRPC_API_TRACE(
699 "cq_end_op_for_next(cq=%p, tag=%p, error=%s, "
700 "done=%p, done_arg=%p, storage=%p)",
701 6, (cq, tag, errmsg.c_str(), done, done_arg, storage));
702 if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) && !error.ok()) {
703 gpr_log(GPR_INFO, "Operation failed: tag=%p, error=%s", tag,
704 errmsg.c_str());
705 }
706 }
707 cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
708 int is_success = (error.ok());
709
710 storage->tag = tag;
711 storage->done = done;
712 storage->done_arg = done_arg;
713 storage->next = static_cast<uintptr_t>(is_success);
714
715 cq_check_tag(cq, tag, true); /* Used in debug builds only */
716
717 if (g_cached_cq == cq && g_cached_event == nullptr) {
718 g_cached_event = storage;
719 } else {
720 /* Add the completion to the queue */
721 bool is_first = cqd->queue.Push(storage);
722 cqd->things_queued_ever.fetch_add(1, std::memory_order_relaxed);
723 /* Since we do not hold the cq lock here, it is important to do an 'acquire'
724 load here (instead of a 'no_barrier' load) to match with the release
725 store
726 (done via pending_events.fetch_sub(1, ACQ_REL)) in cq_shutdown_next
727 */
728 if (cqd->pending_events.load(std::memory_order_acquire) != 1) {
729 /* Only kick if this is the first item queued */
730 if (is_first) {
731 gpr_mu_lock(cq->mu);
732 grpc_error_handle kick_error =
733 cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), nullptr);
734 gpr_mu_unlock(cq->mu);
735
736 if (!kick_error.ok()) {
737 gpr_log(GPR_ERROR, "Kick failed: %s",
738 grpc_core::StatusToString(kick_error).c_str());
739 }
740 }
741 if (cqd->pending_events.fetch_sub(1, std::memory_order_acq_rel) == 1) {
742 GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
743 gpr_mu_lock(cq->mu);
744 cq_finish_shutdown_next(cq);
745 gpr_mu_unlock(cq->mu);
746 GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
747 }
748 } else {
749 GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
750 cqd->pending_events.store(0, std::memory_order_release);
751 gpr_mu_lock(cq->mu);
752 cq_finish_shutdown_next(cq);
753 gpr_mu_unlock(cq->mu);
754 GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
755 }
756 }
757 }
758
759 /* Queue a GRPC_OP_COMPLETED operation to a completion queue (with a
760 * completion
761 * type of GRPC_CQ_PLUCK) */
762 static void cq_end_op_for_pluck(
763 grpc_completion_queue* cq, void* tag, grpc_error_handle error,
764 void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
765 grpc_cq_completion* storage, bool /*internal*/) {
766 cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
767 int is_success = (error.ok());
768
769 if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) ||
770 (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) && !error.ok())) {
771 std::string errmsg = grpc_core::StatusToString(error).c_str();
772 GRPC_API_TRACE(
773 "cq_end_op_for_pluck(cq=%p, tag=%p, error=%s, "
774 "done=%p, done_arg=%p, storage=%p)",
775 6, (cq, tag, errmsg.c_str(), done, done_arg, storage));
776 if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) && !error.ok()) {
777 gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag,
778 errmsg.c_str());
779 }
780 }
781
782 storage->tag = tag;
783 storage->done = done;
784 storage->done_arg = done_arg;
785 storage->next = reinterpret_cast<uintptr_t>(&cqd->completed_head) |
786 static_cast<uintptr_t>(is_success);
787
788 gpr_mu_lock(cq->mu);
789 cq_check_tag(cq, tag, false); /* Used in debug builds only */
790
791 /* Add to the list of completions */
792 cqd->things_queued_ever.fetch_add(1, std::memory_order_relaxed);
793 cqd->completed_tail->next =
794 reinterpret_cast<uintptr_t>(storage) | (1u & cqd->completed_tail->next);
795 cqd->completed_tail = storage;
796
797 if (cqd->pending_events.fetch_sub(1, std::memory_order_acq_rel) == 1) {
798 cq_finish_shutdown_pluck(cq);
799 gpr_mu_unlock(cq->mu);
800 } else {
801 grpc_pollset_worker* pluck_worker = nullptr;
802 for (int i = 0; i < cqd->num_pluckers; i++) {
803 if (cqd->pluckers[i].tag == tag) {
804 pluck_worker = *cqd->pluckers[i].worker;
805 break;
806 }
807 }
808
809 grpc_error_handle kick_error =
810 cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), pluck_worker);
811 gpr_mu_unlock(cq->mu);
812 if (!kick_error.ok()) {
813 gpr_log(GPR_ERROR, "Kick failed: %s",
814 grpc_core::StatusToString(kick_error).c_str());
815 }
816 }
817 }
818
819 static void functor_callback(void* arg, grpc_error_handle error) {
820 auto* functor = static_cast<grpc_completion_queue_functor*>(arg);
821 functor->functor_run(functor, error.ok());
822 }
823
824 /* Complete an event on a completion queue of type GRPC_CQ_CALLBACK */
825 static void cq_end_op_for_callback(
826 grpc_completion_queue* cq, void* tag, grpc_error_handle error,
827 void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg,
828 grpc_cq_completion* storage, bool internal) {
829 cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq);
830
831 if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) ||
832 (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) && !error.ok())) {
833 std::string errmsg = grpc_core::StatusToString(error);
834 GRPC_API_TRACE(
835 "cq_end_op_for_callback(cq=%p, tag=%p, error=%s, "
836 "done=%p, done_arg=%p, storage=%p)",
837 6, (cq, tag, errmsg.c_str(), done, done_arg, storage));
838 if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) && !error.ok()) {
839 gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag,
840 errmsg.c_str());
841 }
842 }
843
844 // The callback-based CQ isn't really a queue at all and thus has no need
845 // for reserved storage. Invoke the done callback right away to release it.
846 done(done_arg, storage);
847
848 cq_check_tag(cq, tag, true); /* Used in debug builds only */
849
850 if (cqd->pending_events.fetch_sub(1, std::memory_order_acq_rel) == 1) {
851 cq_finish_shutdown_callback(cq);
852 }
853
854 // If possible, schedule the callback onto an existing thread-local
855 // ApplicationCallbackExecCtx, which is a work queue. This is possible for:
856 // 1. The callback is internally-generated and there is an ACEC available
857 // 2. The callback is marked inlineable and there is an ACEC available
858 // 3. We are already running in a background poller thread (which always has
859 // an ACEC available at the base of the stack).
860 auto* functor = static_cast<grpc_completion_queue_functor*>(tag);
861 if (((internal || functor->inlineable) &&
862 grpc_core::ApplicationCallbackExecCtx::Available()) ||
863 grpc_iomgr_is_any_background_poller_thread()) {
864 grpc_core::ApplicationCallbackExecCtx::Enqueue(functor, (error.ok()));
865 return;
866 }
867
868 // Schedule the callback on a closure if not internal or triggered
869 // from a background poller thread.
870 grpc_core::Executor::Run(
871 GRPC_CLOSURE_CREATE(functor_callback, functor, nullptr), error);
872 }
873
874 void grpc_cq_end_op(grpc_completion_queue* cq, void* tag,
875 grpc_error_handle error,
876 void (*done)(void* done_arg, grpc_cq_completion* storage),
877 void* done_arg, grpc_cq_completion* storage,
878 bool internal) {
879 cq->vtable->end_op(cq, tag, error, done, done_arg, storage, internal);
880 }
881
882 struct cq_is_finished_arg {
883 gpr_atm last_seen_things_queued_ever;
884 grpc_completion_queue* cq;
885 grpc_core::Timestamp deadline;
886 grpc_cq_completion* stolen_completion;
887 void* tag; /* for pluck */
888 bool first_loop;
889 };
890 class ExecCtxNext : public grpc_core::ExecCtx {
891 public:
892 explicit ExecCtxNext(void* arg)
893 : ExecCtx(0), check_ready_to_finish_arg_(arg) {}
894
895 bool CheckReadyToFinish() override {
896 cq_is_finished_arg* a =
897 static_cast<cq_is_finished_arg*>(check_ready_to_finish_arg_);
898 grpc_completion_queue* cq = a->cq;
899 cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
900 GPR_ASSERT(a->stolen_completion == nullptr);
901
902 intptr_t current_last_seen_things_queued_ever =
903 cqd->things_queued_ever.load(std::memory_order_relaxed);
904
905 if (current_last_seen_things_queued_ever !=
906 a->last_seen_things_queued_ever) {
907 a->last_seen_things_queued_ever =
908 cqd->things_queued_ever.load(std::memory_order_relaxed);
909
910 /* Pop a cq_completion from the queue. Returns NULL if the queue is empty
911 * might return NULL in some cases even if the queue is not empty; but
912 * that
913 * is ok and doesn't affect correctness. Might effect the tail latencies a
914 * bit) */
915 a->stolen_completion = cqd->queue.Pop();
916 if (a->stolen_completion != nullptr) {
917 return true;
918 }
919 }
920 return !a->first_loop && a->deadline < grpc_core::Timestamp::Now();
921 }
922
923 private:
924 void* check_ready_to_finish_arg_;
925 };
926
927 #ifndef NDEBUG
928 static void dump_pending_tags(grpc_completion_queue* cq) {
929 if (!GRPC_TRACE_FLAG_ENABLED(grpc_trace_pending_tags)) return;
930 std::vector<std::string> parts;
931 parts.push_back("PENDING TAGS:");
932 gpr_mu_lock(cq->mu);
933 for (size_t i = 0; i < cq->outstanding_tag_count; i++) {
934 parts.push_back(absl::StrFormat(" %p", cq->outstanding_tags[i]));
935 }
936 gpr_mu_unlock(cq->mu);
937 gpr_log(GPR_DEBUG, "%s", absl::StrJoin(parts, "").c_str());
938 }
939 #else
940 static void dump_pending_tags(grpc_completion_queue* /*cq*/) {}
941 #endif
942
943 static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline,
944 void* reserved) {
945 grpc_event ret;
946 cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
947
948 GRPC_API_TRACE(
949 "grpc_completion_queue_next("
950 "cq=%p, "
951 "deadline=gpr_timespec { tv_sec: %" PRId64
952 ", tv_nsec: %d, clock_type: %d }, "
953 "reserved=%p)",
954 5,
955 (cq, deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type,
956 reserved));
957 GPR_ASSERT(!reserved);
958
959 dump_pending_tags(cq);
960
961 GRPC_CQ_INTERNAL_REF(cq, "next");
962
963 grpc_core::Timestamp deadline_millis =
964 grpc_core::Timestamp::FromTimespecRoundUp(deadline);
965 cq_is_finished_arg is_finished_arg = {
966 cqd->things_queued_ever.load(std::memory_order_relaxed),
967 cq,
968 deadline_millis,
969 nullptr,
970 nullptr,
971 true};
972 ExecCtxNext exec_ctx(&is_finished_arg);
973 for (;;) {
974 grpc_core::Timestamp iteration_deadline = deadline_millis;
975
976 if (is_finished_arg.stolen_completion != nullptr) {
977 grpc_cq_completion* c = is_finished_arg.stolen_completion;
978 is_finished_arg.stolen_completion = nullptr;
979 ret.type = GRPC_OP_COMPLETE;
980 ret.success = c->next & 1u;
981 ret.tag = c->tag;
982 c->done(c->done_arg, c);
983 break;
984 }
985
986 grpc_cq_completion* c = cqd->queue.Pop();
987
988 if (c != nullptr) {
989 ret.type = GRPC_OP_COMPLETE;
990 ret.success = c->next & 1u;
991 ret.tag = c->tag;
992 c->done(c->done_arg, c);
993 break;
994 } else {
995 /* If c == NULL it means either the queue is empty OR in an transient
996 inconsistent state. If it is the latter, we shold do a 0-timeout poll
997 so that the thread comes back quickly from poll to make a second
998 attempt at popping. Not doing this can potentially deadlock this
999 thread forever (if the deadline is infinity) */
1000 if (cqd->queue.num_items() > 0) {
1001 iteration_deadline = grpc_core::Timestamp::ProcessEpoch();
1002 }
1003 }
1004
1005 if (cqd->pending_events.load(std::memory_order_acquire) == 0) {
1006 /* Before returning, check if the queue has any items left over (since
1007 MultiProducerSingleConsumerQueue::Pop() can sometimes return NULL
1008 even if the queue is not empty. If so, keep retrying but do not
1009 return GRPC_QUEUE_SHUTDOWN */
1010 if (cqd->queue.num_items() > 0) {
1011 /* Go to the beginning of the loop. No point doing a poll because
1012 (cq->shutdown == true) is only possible when there is no pending
1013 work (i.e cq->pending_events == 0) and any outstanding completion
1014 events should have already been queued on this cq */
1015 continue;
1016 }
1017
1018 ret.type = GRPC_QUEUE_SHUTDOWN;
1019 ret.success = 0;
1020 break;
1021 }
1022
1023 if (!is_finished_arg.first_loop &&
1024 grpc_core::Timestamp::Now() >= deadline_millis) {
1025 ret.type = GRPC_QUEUE_TIMEOUT;
1026 ret.success = 0;
1027 dump_pending_tags(cq);
1028 break;
1029 }
1030
1031 /* The main polling work happens in grpc_pollset_work */
1032 gpr_mu_lock(cq->mu);
1033 cq->num_polls++;
1034 grpc_error_handle err = cq->poller_vtable->work(
1035 POLLSET_FROM_CQ(cq), nullptr, iteration_deadline);
1036 gpr_mu_unlock(cq->mu);
1037
1038 if (!err.ok()) {
1039 gpr_log(GPR_ERROR, "Completion queue next failed: %s",
1040 grpc_core::StatusToString(err).c_str());
1041 if (err == absl::CancelledError()) {
1042 ret.type = GRPC_QUEUE_SHUTDOWN;
1043 } else {
1044 ret.type = GRPC_QUEUE_TIMEOUT;
1045 }
1046 ret.success = 0;
1047 dump_pending_tags(cq);
1048 break;
1049 }
1050 is_finished_arg.first_loop = false;
1051 }
1052
1053 if (cqd->queue.num_items() > 0 &&
1054 cqd->pending_events.load(std::memory_order_acquire) > 0) {
1055 gpr_mu_lock(cq->mu);
1056 (void)cq->poller_vtable->kick(POLLSET_FROM_CQ(cq), nullptr);
1057 gpr_mu_unlock(cq->mu);
1058 }
1059
1060 GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, &ret);
1061 GRPC_CQ_INTERNAL_UNREF(cq, "next");
1062
1063 GPR_ASSERT(is_finished_arg.stolen_completion == nullptr);
1064
1065 return ret;
1066 }
1067
1068 /* Finishes the completion queue shutdown. This means that there are no more
1069 completion events / tags expected from the completion queue
1070 - Must be called under completion queue lock
1071 - Must be called only once in completion queue's lifetime
1072 - grpc_completion_queue_shutdown() MUST have been called before calling
1073 this function */
1074 static void cq_finish_shutdown_next(grpc_completion_queue* cq) {
1075 cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
1076
1077 GPR_ASSERT(cqd->shutdown_called);
1078 GPR_ASSERT(cqd->pending_events.load(std::memory_order_relaxed) == 0);
1079
1080 cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
1081 }
1082
1083 static void cq_shutdown_next(grpc_completion_queue* cq) {
1084 cq_next_data* cqd = static_cast<cq_next_data*> DATA_FROM_CQ(cq);
1085
1086 /* Need an extra ref for cq here because:
1087 * We call cq_finish_shutdown_next() below, that would call pollset shutdown.
1088 * Pollset shutdown decrements the cq ref count which can potentially destroy
1089 * the cq (if that happens to be the last ref).
1090 * Creating an extra ref here prevents the cq from getting destroyed while
1091 * this function is still active */
1092 GRPC_CQ_INTERNAL_REF(cq, "shutting_down");
1093 gpr_mu_lock(cq->mu);
1094 if (cqd->shutdown_called) {
1095 gpr_mu_unlock(cq->mu);
1096 GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
1097 return;
1098 }
1099 cqd->shutdown_called = true;
1100 /* Doing acq/release fetch_sub here to match with
1101 * cq_begin_op_for_next and cq_end_op_for_next functions which read/write
1102 * on this counter without necessarily holding a lock on cq */
1103 if (cqd->pending_events.fetch_sub(1, std::memory_order_acq_rel) == 1) {
1104 cq_finish_shutdown_next(cq);
1105 }
1106 gpr_mu_unlock(cq->mu);
1107 GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down");
1108 }
1109
1110 grpc_event grpc_completion_queue_next(grpc_completion_queue* cq,
1111 gpr_timespec deadline, void* reserved) {
1112 return cq->vtable->next(cq, deadline, reserved);
1113 }
1114
1115 static int add_plucker(grpc_completion_queue* cq, void* tag,
1116 grpc_pollset_worker** worker) {
1117 cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
1118 if (cqd->num_pluckers == GRPC_MAX_COMPLETION_QUEUE_PLUCKERS) {
1119 return 0;
1120 }
1121 cqd->pluckers[cqd->num_pluckers].tag = tag;
1122 cqd->pluckers[cqd->num_pluckers].worker = worker;
1123 cqd->num_pluckers++;
1124 return 1;
1125 }
1126
1127 static void del_plucker(grpc_completion_queue* cq, void* tag,
1128 grpc_pollset_worker** worker) {
1129 cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
1130 for (int i = 0; i < cqd->num_pluckers; i++) {
1131 if (cqd->pluckers[i].tag == tag && cqd->pluckers[i].worker == worker) {
1132 cqd->num_pluckers--;
1133 std::swap(cqd->pluckers[i], cqd->pluckers[cqd->num_pluckers]);
1134 return;
1135 }
1136 }
1137 GPR_UNREACHABLE_CODE(return);
1138 }
1139
1140 class ExecCtxPluck : public grpc_core::ExecCtx {
1141 public:
1142 explicit ExecCtxPluck(void* arg)
1143 : ExecCtx(0), check_ready_to_finish_arg_(arg) {}
1144
1145 bool CheckReadyToFinish() override {
1146 cq_is_finished_arg* a =
1147 static_cast<cq_is_finished_arg*>(check_ready_to_finish_arg_);
1148 grpc_completion_queue* cq = a->cq;
1149 cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
1150
1151 GPR_ASSERT(a->stolen_completion == nullptr);
1152 gpr_atm current_last_seen_things_queued_ever =
1153 cqd->things_queued_ever.load(std::memory_order_relaxed);
1154 if (current_last_seen_things_queued_ever !=
1155 a->last_seen_things_queued_ever) {
1156 gpr_mu_lock(cq->mu);
1157 a->last_seen_things_queued_ever =
1158 cqd->things_queued_ever.load(std::memory_order_relaxed);
1159 grpc_cq_completion* c;
1160 grpc_cq_completion* prev = &cqd->completed_head;
1161 while ((c = reinterpret_cast<grpc_cq_completion*>(
1162 prev->next & ~static_cast<uintptr_t>(1))) !=
1163 &cqd->completed_head) {
1164 if (c->tag == a->tag) {
1165 prev->next = (prev->next & static_cast<uintptr_t>(1)) |
1166 (c->next & ~static_cast<uintptr_t>(1));
1167 if (c == cqd->completed_tail) {
1168 cqd->completed_tail = prev;
1169 }
1170 gpr_mu_unlock(cq->mu);
1171 a->stolen_completion = c;
1172 return true;
1173 }
1174 prev = c;
1175 }
1176 gpr_mu_unlock(cq->mu);
1177 }
1178 return !a->first_loop && a->deadline < grpc_core::Timestamp::Now();
1179 }
1180
1181 private:
1182 void* check_ready_to_finish_arg_;
1183 };
1184
1185 static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag,
1186 gpr_timespec deadline, void* reserved) {
1187 grpc_event ret;
1188 grpc_cq_completion* c;
1189 grpc_cq_completion* prev;
1190 grpc_pollset_worker* worker = nullptr;
1191 cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
1192
1193 if (GRPC_TRACE_FLAG_ENABLED(grpc_cq_pluck_trace)) {
1194 GRPC_API_TRACE(
1195 "grpc_completion_queue_pluck("
1196 "cq=%p, tag=%p, "
1197 "deadline=gpr_timespec { tv_sec: %" PRId64
1198 ", tv_nsec: %d, clock_type: %d }, "
1199 "reserved=%p)",
1200 6,
1201 (cq, tag, deadline.tv_sec, deadline.tv_nsec, (int)deadline.clock_type,
1202 reserved));
1203 }
1204 GPR_ASSERT(!reserved);
1205
1206 dump_pending_tags(cq);
1207
1208 GRPC_CQ_INTERNAL_REF(cq, "pluck");
1209 gpr_mu_lock(cq->mu);
1210 grpc_core::Timestamp deadline_millis =
1211 grpc_core::Timestamp::FromTimespecRoundUp(deadline);
1212 cq_is_finished_arg is_finished_arg = {
1213 cqd->things_queued_ever.load(std::memory_order_relaxed),
1214 cq,
1215 deadline_millis,
1216 nullptr,
1217 tag,
1218 true};
1219 ExecCtxPluck exec_ctx(&is_finished_arg);
1220 for (;;) {
1221 if (is_finished_arg.stolen_completion != nullptr) {
1222 gpr_mu_unlock(cq->mu);
1223 c = is_finished_arg.stolen_completion;
1224 is_finished_arg.stolen_completion = nullptr;
1225 ret.type = GRPC_OP_COMPLETE;
1226 ret.success = c->next & 1u;
1227 ret.tag = c->tag;
1228 c->done(c->done_arg, c);
1229 break;
1230 }
1231 prev = &cqd->completed_head;
1232 while ((c = reinterpret_cast<grpc_cq_completion*>(
1233 prev->next & ~static_cast<uintptr_t>(1))) !=
1234 &cqd->completed_head) {
1235 if (c->tag == tag) {
1236 prev->next = (prev->next & static_cast<uintptr_t>(1)) |
1237 (c->next & ~static_cast<uintptr_t>(1));
1238 if (c == cqd->completed_tail) {
1239 cqd->completed_tail = prev;
1240 }
1241 gpr_mu_unlock(cq->mu);
1242 ret.type = GRPC_OP_COMPLETE;
1243 ret.success = c->next & 1u;
1244 ret.tag = c->tag;
1245 c->done(c->done_arg, c);
1246 goto done;
1247 }
1248 prev = c;
1249 }
1250 if (cqd->shutdown.load(std::memory_order_relaxed)) {
1251 gpr_mu_unlock(cq->mu);
1252 ret.type = GRPC_QUEUE_SHUTDOWN;
1253 ret.success = 0;
1254 break;
1255 }
1256 if (!add_plucker(cq, tag, &worker)) {
1257 gpr_log(GPR_DEBUG,
1258 "Too many outstanding grpc_completion_queue_pluck calls: maximum "
1259 "is %d",
1260 GRPC_MAX_COMPLETION_QUEUE_PLUCKERS);
1261 gpr_mu_unlock(cq->mu);
1262 /* TODO(ctiller): should we use a different result here */
1263 ret.type = GRPC_QUEUE_TIMEOUT;
1264 ret.success = 0;
1265 dump_pending_tags(cq);
1266 break;
1267 }
1268 if (!is_finished_arg.first_loop &&
1269 grpc_core::Timestamp::Now() >= deadline_millis) {
1270 del_plucker(cq, tag, &worker);
1271 gpr_mu_unlock(cq->mu);
1272 ret.type = GRPC_QUEUE_TIMEOUT;
1273 ret.success = 0;
1274 dump_pending_tags(cq);
1275 break;
1276 }
1277 cq->num_polls++;
1278 grpc_error_handle err =
1279 cq->poller_vtable->work(POLLSET_FROM_CQ(cq), &worker, deadline_millis);
1280 if (!err.ok()) {
1281 del_plucker(cq, tag, &worker);
1282 gpr_mu_unlock(cq->mu);
1283 gpr_log(GPR_ERROR, "Completion queue pluck failed: %s",
1284 grpc_core::StatusToString(err).c_str());
1285 ret.type = GRPC_QUEUE_TIMEOUT;
1286 ret.success = 0;
1287 dump_pending_tags(cq);
1288 break;
1289 }
1290 is_finished_arg.first_loop = false;
1291 del_plucker(cq, tag, &worker);
1292 }
1293 done:
1294 GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, &ret);
1295 GRPC_CQ_INTERNAL_UNREF(cq, "pluck");
1296
1297 GPR_ASSERT(is_finished_arg.stolen_completion == nullptr);
1298
1299 return ret;
1300 }
1301
1302 grpc_event grpc_completion_queue_pluck(grpc_completion_queue* cq, void* tag,
1303 gpr_timespec deadline, void* reserved) {
1304 return cq->vtable->pluck(cq, tag, deadline, reserved);
1305 }
1306
1307 static void cq_finish_shutdown_pluck(grpc_completion_queue* cq) {
1308 cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
1309
1310 GPR_ASSERT(cqd->shutdown_called);
1311 GPR_ASSERT(!cqd->shutdown.load(std::memory_order_relaxed));
1312 cqd->shutdown.store(true, std::memory_order_relaxed);
1313
1314 cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
1315 }
1316
1317 /* NOTE: This function is almost exactly identical to cq_shutdown_next() but
1318 * merging them is a bit tricky and probably not worth it */
1319 static void cq_shutdown_pluck(grpc_completion_queue* cq) {
1320 cq_pluck_data* cqd = static_cast<cq_pluck_data*> DATA_FROM_CQ(cq);
1321
1322 /* Need an extra ref for cq here because:
1323 * We call cq_finish_shutdown_pluck() below, that would call pollset shutdown.
1324 * Pollset shutdown decrements the cq ref count which can potentially destroy
1325 * the cq (if that happens to be the last ref).
1326 * Creating an extra ref here prevents the cq from getting destroyed while
1327 * this function is still active */
1328 GRPC_CQ_INTERNAL_REF(cq, "shutting_down (pluck cq)");
1329 gpr_mu_lock(cq->mu);
1330 if (cqd->shutdown_called) {
1331 gpr_mu_unlock(cq->mu);
1332 GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (pluck cq)");
1333 return;
1334 }
1335 cqd->shutdown_called = true;
1336 if (cqd->pending_events.fetch_sub(1, std::memory_order_acq_rel) == 1) {
1337 cq_finish_shutdown_pluck(cq);
1338 }
1339 gpr_mu_unlock(cq->mu);
1340 GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (pluck cq)");
1341 }
1342
1343 static void cq_finish_shutdown_callback(grpc_completion_queue* cq) {
1344 cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq);
1345 auto* callback = cqd->shutdown_callback;
1346
1347 GPR_ASSERT(cqd->shutdown_called);
1348
1349 cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done);
1350 if (grpc_iomgr_is_any_background_poller_thread()) {
1351 grpc_core::ApplicationCallbackExecCtx::Enqueue(callback, true);
1352 return;
1353 }
1354
1355 // Schedule the callback on a closure if not internal or triggered
1356 // from a background poller thread.
1357 grpc_core::Executor::Run(
1358 GRPC_CLOSURE_CREATE(functor_callback, callback, nullptr),
1359 absl::OkStatus());
1360 }
1361
1362 static void cq_shutdown_callback(grpc_completion_queue* cq) {
1363 cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq);
1364
1365 /* Need an extra ref for cq here because:
1366 * We call cq_finish_shutdown_callback() below, which calls pollset shutdown.
1367 * Pollset shutdown decrements the cq ref count which can potentially destroy
1368 * the cq (if that happens to be the last ref).
1369 * Creating an extra ref here prevents the cq from getting destroyed while
1370 * this function is still active */
1371 GRPC_CQ_INTERNAL_REF(cq, "shutting_down (callback cq)");
1372 gpr_mu_lock(cq->mu);
1373 if (cqd->shutdown_called) {
1374 gpr_mu_unlock(cq->mu);
1375 GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (callback cq)");
1376 return;
1377 }
1378 cqd->shutdown_called = true;
1379 if (cqd->pending_events.fetch_sub(1, std::memory_order_acq_rel) == 1) {
1380 gpr_mu_unlock(cq->mu);
1381 cq_finish_shutdown_callback(cq);
1382 } else {
1383 gpr_mu_unlock(cq->mu);
1384 }
1385 GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (callback cq)");
1386 }
1387
1388 /* Shutdown simply drops a ref that we reserved at creation time; if we drop
1389 to zero here, then enter shutdown mode and wake up any waiters */
1390 void grpc_completion_queue_shutdown(grpc_completion_queue* cq) {
1391 grpc_core::ApplicationCallbackExecCtx callback_exec_ctx;
1392 grpc_core::ExecCtx exec_ctx;
1393 GRPC_API_TRACE("grpc_completion_queue_shutdown(cq=%p)", 1, (cq));
1394 cq->vtable->shutdown(cq);
1395 }
1396
1397 void grpc_completion_queue_destroy(grpc_completion_queue* cq) {
1398 GRPC_API_TRACE("grpc_completion_queue_destroy(cq=%p)", 1, (cq));
1399 grpc_completion_queue_shutdown(cq);
1400
1401 grpc_core::ExecCtx exec_ctx;
1402 GRPC_CQ_INTERNAL_UNREF(cq, "destroy");
1403 }
1404
1405 grpc_pollset* grpc_cq_pollset(grpc_completion_queue* cq) {
1406 return cq->poller_vtable->can_get_pollset ? POLLSET_FROM_CQ(cq) : nullptr;
1407 }
1408
1409 bool grpc_cq_can_listen(grpc_completion_queue* cq) {
1410 return cq->poller_vtable->can_listen;
1411 }