• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  * Copyright 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 
19 #include <grpc/support/port_platform.h>
20 
21 #include "src/core/lib/iomgr/combiner.h"
22 
23 #include <assert.h>
24 #include <inttypes.h>
25 #include <string.h>
26 
27 #include <grpc/support/alloc.h>
28 #include <grpc/support/log.h>
29 
30 #include "src/core/lib/debug/stats.h"
31 #include "src/core/lib/gprpp/mpscq.h"
32 #include "src/core/lib/iomgr/executor.h"
33 #include "src/core/lib/iomgr/iomgr.h"
34 #include "src/core/lib/profiling/timers.h"
35 
36 grpc_core::DebugOnlyTraceFlag grpc_combiner_trace(false, "combiner");
37 
38 #define GRPC_COMBINER_TRACE(fn)          \
39   do {                                   \
40     if (grpc_combiner_trace.enabled()) { \
41       fn;                                \
42     }                                    \
43   } while (0)
44 
45 #define STATE_UNORPHANED 1
46 #define STATE_ELEM_COUNT_LOW_BIT 2
47 
48 static void combiner_exec(grpc_core::Combiner* lock, grpc_closure* closure,
49                           grpc_error_handle error);
50 static void combiner_finally_exec(grpc_core::Combiner* lock,
51                                   grpc_closure* closure,
52                                   grpc_error_handle error);
53 
54 static void offload(void* arg, grpc_error_handle error);
55 
grpc_combiner_create(void)56 grpc_core::Combiner* grpc_combiner_create(void) {
57   grpc_core::Combiner* lock = new grpc_core::Combiner();
58   gpr_ref_init(&lock->refs, 1);
59   gpr_atm_no_barrier_store(&lock->state, STATE_UNORPHANED);
60   grpc_closure_list_init(&lock->final_list);
61   GRPC_CLOSURE_INIT(&lock->offload, offload, lock, nullptr);
62   GRPC_COMBINER_TRACE(gpr_log(GPR_INFO, "C:%p create", lock));
63   return lock;
64 }
65 
really_destroy(grpc_core::Combiner * lock)66 static void really_destroy(grpc_core::Combiner* lock) {
67   GRPC_COMBINER_TRACE(gpr_log(GPR_INFO, "C:%p really_destroy", lock));
68   GPR_ASSERT(gpr_atm_no_barrier_load(&lock->state) == 0);
69   delete lock;
70 }
71 
start_destroy(grpc_core::Combiner * lock)72 static void start_destroy(grpc_core::Combiner* lock) {
73   gpr_atm old_state = gpr_atm_full_fetch_add(&lock->state, -STATE_UNORPHANED);
74   GRPC_COMBINER_TRACE(gpr_log(
75       GPR_INFO, "C:%p really_destroy old_state=%" PRIdPTR, lock, old_state));
76   if (old_state == 1) {
77     really_destroy(lock);
78   }
79 }
80 
81 #ifndef NDEBUG
82 #define GRPC_COMBINER_DEBUG_SPAM(op, delta)                                \
83   if (grpc_combiner_trace.enabled()) {                                     \
84     gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG,                            \
85             "C:%p %s %" PRIdPTR " --> %" PRIdPTR " %s", lock, (op),        \
86             gpr_atm_no_barrier_load(&lock->refs.count),                    \
87             gpr_atm_no_barrier_load(&lock->refs.count) + (delta), reason); \
88   }
89 #else
90 #define GRPC_COMBINER_DEBUG_SPAM(op, delta)
91 #endif
92 
grpc_combiner_unref(grpc_core::Combiner * lock GRPC_COMBINER_DEBUG_ARGS)93 void grpc_combiner_unref(grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS) {
94   GRPC_COMBINER_DEBUG_SPAM("UNREF", -1);
95   if (gpr_unref(&lock->refs)) {
96     start_destroy(lock);
97   }
98 }
99 
grpc_combiner_ref(grpc_core::Combiner * lock GRPC_COMBINER_DEBUG_ARGS)100 grpc_core::Combiner* grpc_combiner_ref(
101     grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS) {
102   GRPC_COMBINER_DEBUG_SPAM("  REF", 1);
103   gpr_ref(&lock->refs);
104   return lock;
105 }
106 
push_last_on_exec_ctx(grpc_core::Combiner * lock)107 static void push_last_on_exec_ctx(grpc_core::Combiner* lock) {
108   lock->next_combiner_on_this_exec_ctx = nullptr;
109   if (grpc_core::ExecCtx::Get()->combiner_data()->active_combiner == nullptr) {
110     grpc_core::ExecCtx::Get()->combiner_data()->active_combiner =
111         grpc_core::ExecCtx::Get()->combiner_data()->last_combiner = lock;
112   } else {
113     grpc_core::ExecCtx::Get()
114         ->combiner_data()
115         ->last_combiner->next_combiner_on_this_exec_ctx = lock;
116     grpc_core::ExecCtx::Get()->combiner_data()->last_combiner = lock;
117   }
118 }
119 
push_first_on_exec_ctx(grpc_core::Combiner * lock)120 static void push_first_on_exec_ctx(grpc_core::Combiner* lock) {
121   lock->next_combiner_on_this_exec_ctx =
122       grpc_core::ExecCtx::Get()->combiner_data()->active_combiner;
123   grpc_core::ExecCtx::Get()->combiner_data()->active_combiner = lock;
124   if (lock->next_combiner_on_this_exec_ctx == nullptr) {
125     grpc_core::ExecCtx::Get()->combiner_data()->last_combiner = lock;
126   }
127 }
128 
combiner_exec(grpc_core::Combiner * lock,grpc_closure * cl,grpc_error_handle error)129 static void combiner_exec(grpc_core::Combiner* lock, grpc_closure* cl,
130                           grpc_error_handle error) {
131   GPR_TIMER_SCOPE("combiner.execute", 0);
132   GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_ITEMS();
133   gpr_atm last = gpr_atm_full_fetch_add(&lock->state, STATE_ELEM_COUNT_LOW_BIT);
134   GRPC_COMBINER_TRACE(gpr_log(GPR_INFO,
135                               "C:%p grpc_combiner_execute c=%p last=%" PRIdPTR,
136                               lock, cl, last));
137   if (last == 1) {
138     GRPC_STATS_INC_COMBINER_LOCKS_INITIATED();
139     GPR_TIMER_MARK("combiner.initiated", 0);
140     gpr_atm_no_barrier_store(&lock->initiating_exec_ctx_or_null,
141                              (gpr_atm)grpc_core::ExecCtx::Get());
142     // first element on this list: add it to the list of combiner locks
143     // executing within this exec_ctx
144     push_last_on_exec_ctx(lock);
145   } else {
146     // there may be a race with setting here: if that happens, we may delay
147     // offload for one or two actions, and that's fine
148     gpr_atm initiator =
149         gpr_atm_no_barrier_load(&lock->initiating_exec_ctx_or_null);
150     if (initiator != 0 &&
151         initiator != reinterpret_cast<gpr_atm>(grpc_core::ExecCtx::Get())) {
152       gpr_atm_no_barrier_store(&lock->initiating_exec_ctx_or_null, 0);
153     }
154   }
155   GPR_ASSERT(last & STATE_UNORPHANED);  // ensure lock has not been destroyed
156   assert(cl->cb);
157   cl->error_data.error = error;
158   lock->queue.Push(cl->next_data.mpscq_node.get());
159 }
160 
move_next()161 static void move_next() {
162   grpc_core::ExecCtx::Get()->combiner_data()->active_combiner =
163       grpc_core::ExecCtx::Get()
164           ->combiner_data()
165           ->active_combiner->next_combiner_on_this_exec_ctx;
166   if (grpc_core::ExecCtx::Get()->combiner_data()->active_combiner == nullptr) {
167     grpc_core::ExecCtx::Get()->combiner_data()->last_combiner = nullptr;
168   }
169 }
170 
offload(void * arg,grpc_error_handle)171 static void offload(void* arg, grpc_error_handle /*error*/) {
172   grpc_core::Combiner* lock = static_cast<grpc_core::Combiner*>(arg);
173   push_last_on_exec_ctx(lock);
174 }
175 
queue_offload(grpc_core::Combiner * lock)176 static void queue_offload(grpc_core::Combiner* lock) {
177   GRPC_STATS_INC_COMBINER_LOCKS_OFFLOADED();
178   move_next();
179   GRPC_COMBINER_TRACE(gpr_log(GPR_INFO, "C:%p queue_offload", lock));
180   grpc_core::Executor::Run(&lock->offload, GRPC_ERROR_NONE);
181 }
182 
grpc_combiner_continue_exec_ctx()183 bool grpc_combiner_continue_exec_ctx() {
184   GPR_TIMER_SCOPE("combiner.continue_exec_ctx", 0);
185   grpc_core::Combiner* lock =
186       grpc_core::ExecCtx::Get()->combiner_data()->active_combiner;
187   if (lock == nullptr) {
188     return false;
189   }
190 
191   bool contended =
192       gpr_atm_no_barrier_load(&lock->initiating_exec_ctx_or_null) == 0;
193 
194   GRPC_COMBINER_TRACE(gpr_log(GPR_INFO,
195                               "C:%p grpc_combiner_continue_exec_ctx "
196                               "contended=%d "
197                               "exec_ctx_ready_to_finish=%d "
198                               "time_to_execute_final_list=%d",
199                               lock, contended,
200                               grpc_core::ExecCtx::Get()->IsReadyToFinish(),
201                               lock->time_to_execute_final_list));
202 
203   // offload only if all the following conditions are true:
204   // 1. the combiner is contended and has more than one closure to execute
205   // 2. the current execution context needs to finish as soon as possible
206   // 3. the current thread is not a worker for any background poller
207   // 4. the DEFAULT executor is threaded
208   if (contended && grpc_core::ExecCtx::Get()->IsReadyToFinish() &&
209       !grpc_iomgr_is_any_background_poller_thread() &&
210       grpc_core::Executor::IsThreadedDefault()) {
211     GPR_TIMER_MARK("offload_from_finished_exec_ctx", 0);
212     // this execution context wants to move on: schedule remaining work to be
213     // picked up on the executor
214     queue_offload(lock);
215     return true;
216   }
217 
218   if (!lock->time_to_execute_final_list ||
219       // peek to see if something new has shown up, and execute that with
220       // priority
221       (gpr_atm_acq_load(&lock->state) >> 1) > 1) {
222     grpc_core::MultiProducerSingleConsumerQueue::Node* n = lock->queue.Pop();
223     GRPC_COMBINER_TRACE(
224         gpr_log(GPR_INFO, "C:%p maybe_finish_one n=%p", lock, n));
225     if (n == nullptr) {
226       // queue is in an inconsistent state: use this as a cue that we should
227       // go off and do something else for a while (and come back later)
228       GPR_TIMER_MARK("delay_busy", 0);
229       queue_offload(lock);
230       return true;
231     }
232     GPR_TIMER_SCOPE("combiner.exec1", 0);
233     grpc_closure* cl = reinterpret_cast<grpc_closure*>(n);
234     grpc_error_handle cl_err = cl->error_data.error;
235 #ifndef NDEBUG
236     cl->scheduled = false;
237 #endif
238     cl->cb(cl->cb_arg, cl_err);
239     GRPC_ERROR_UNREF(cl_err);
240   } else {
241     grpc_closure* c = lock->final_list.head;
242     GPR_ASSERT(c != nullptr);
243     grpc_closure_list_init(&lock->final_list);
244     int loops = 0;
245     while (c != nullptr) {
246       GPR_TIMER_SCOPE("combiner.exec_1final", 0);
247       GRPC_COMBINER_TRACE(
248           gpr_log(GPR_INFO, "C:%p execute_final[%d] c=%p", lock, loops, c));
249       grpc_closure* next = c->next_data.next;
250       grpc_error_handle error = c->error_data.error;
251 #ifndef NDEBUG
252       c->scheduled = false;
253 #endif
254       c->cb(c->cb_arg, error);
255       GRPC_ERROR_UNREF(error);
256       c = next;
257     }
258   }
259 
260   GPR_TIMER_MARK("unref", 0);
261   move_next();
262   lock->time_to_execute_final_list = false;
263   gpr_atm old_state =
264       gpr_atm_full_fetch_add(&lock->state, -STATE_ELEM_COUNT_LOW_BIT);
265   GRPC_COMBINER_TRACE(
266       gpr_log(GPR_INFO, "C:%p finish old_state=%" PRIdPTR, lock, old_state));
267 // Define a macro to ease readability of the following switch statement.
268 #define OLD_STATE_WAS(orphaned, elem_count) \
269   (((orphaned) ? 0 : STATE_UNORPHANED) |    \
270    ((elem_count)*STATE_ELEM_COUNT_LOW_BIT))
271   // Depending on what the previous state was, we need to perform different
272   // actions.
273   switch (old_state) {
274     default:
275       // we have multiple queued work items: just continue executing them
276       break;
277     case OLD_STATE_WAS(false, 2):
278     case OLD_STATE_WAS(true, 2):
279       // we're down to one queued item: if it's the final list we should do that
280       if (!grpc_closure_list_empty(lock->final_list)) {
281         lock->time_to_execute_final_list = true;
282       }
283       break;
284     case OLD_STATE_WAS(false, 1):
285       // had one count, one unorphaned --> unlocked unorphaned
286       return true;
287     case OLD_STATE_WAS(true, 1):
288       // and one count, one orphaned --> unlocked and orphaned
289       really_destroy(lock);
290       return true;
291     case OLD_STATE_WAS(false, 0):
292     case OLD_STATE_WAS(true, 0):
293       // these values are illegal - representing an already unlocked or
294       // deleted lock
295       GPR_UNREACHABLE_CODE(return true);
296   }
297   push_first_on_exec_ctx(lock);
298   return true;
299 }
300 
301 static void enqueue_finally(void* closure, grpc_error_handle error);
302 
combiner_finally_exec(grpc_core::Combiner * lock,grpc_closure * closure,grpc_error_handle error)303 static void combiner_finally_exec(grpc_core::Combiner* lock,
304                                   grpc_closure* closure,
305                                   grpc_error_handle error) {
306   GPR_ASSERT(lock != nullptr);
307   GPR_TIMER_SCOPE("combiner.execute_finally", 0);
308   GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS();
309   GRPC_COMBINER_TRACE(gpr_log(
310       GPR_INFO, "C:%p grpc_combiner_execute_finally c=%p; ac=%p", lock, closure,
311       grpc_core::ExecCtx::Get()->combiner_data()->active_combiner));
312   if (grpc_core::ExecCtx::Get()->combiner_data()->active_combiner != lock) {
313     GPR_TIMER_MARK("slowpath", 0);
314     // Using error_data.scratch to store the combiner so that it can be accessed
315     // in enqueue_finally.
316     closure->error_data.scratch = reinterpret_cast<uintptr_t>(lock);
317     lock->Run(GRPC_CLOSURE_CREATE(enqueue_finally, closure, nullptr), error);
318     return;
319   }
320 
321   if (grpc_closure_list_empty(lock->final_list)) {
322     gpr_atm_full_fetch_add(&lock->state, STATE_ELEM_COUNT_LOW_BIT);
323   }
324   grpc_closure_list_append(&lock->final_list, closure, error);
325 }
326 
enqueue_finally(void * closure,grpc_error_handle error)327 static void enqueue_finally(void* closure, grpc_error_handle error) {
328   grpc_closure* cl = static_cast<grpc_closure*>(closure);
329   combiner_finally_exec(
330       reinterpret_cast<grpc_core::Combiner*>(cl->error_data.scratch), cl,
331       GRPC_ERROR_REF(error));
332 }
333 
334 namespace grpc_core {
Run(grpc_closure * closure,grpc_error_handle error)335 void Combiner::Run(grpc_closure* closure, grpc_error_handle error) {
336   combiner_exec(this, closure, error);
337 }
338 
FinallyRun(grpc_closure * closure,grpc_error_handle error)339 void Combiner::FinallyRun(grpc_closure* closure, grpc_error_handle error) {
340   combiner_finally_exec(this, closure, error);
341 }
342 }  // namespace grpc_core
343