1 /*
2  *
3  * Copyright 2017 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/lockfree_event.h"
22 
23 #include <grpc/support/log.h>
24 
25 #include "src/core/lib/debug/trace.h"
26 #include "src/core/lib/iomgr/exec_ctx.h"
27 
28 extern grpc_core::DebugOnlyTraceFlag grpc_polling_trace;
29 
30 /* 'state' holds the to call when the fd is readable or writable respectively.
31    It can contain one of the following values:
32      kClosureReady     : The fd has an I/O event of interest but there is no
33                          closure yet to execute
34 
35      kClosureNotReady : The fd has no I/O event of interest
36 
37      closure ptr       : The closure to be executed when the fd has an I/O
38                          event of interest
39 
40      shutdown_error | kShutdownBit :
41                         'shutdown_error' field ORed with kShutdownBit.
42                          This indicates that the fd is shutdown. Since all
43                          memory allocations are word-aligned, the lower two
44                          bits of the shutdown_error pointer are always 0. So
45                          it is safe to OR these with kShutdownBit
46 
47    Valid state transitions:
48 
49      <closure ptr> <-----3------ kClosureNotReady -----1------->  kClosureReady
50        |  |                         ^   |    ^                         |  |
51        |  |                         |   |    |                         |  |
52        |  +--------------4----------+   6    +---------2---------------+  |
53        |                                |                                 |
54        |                                v                                 |
55        +-----5------->  [shutdown_error | kShutdownBit] <-------7---------+
56 
57     For 1, 4 : See SetReady() function
58     For 2, 3 : See NotifyOn() function
59     For 5,6,7: See SetShutdown() function */
60 
61 namespace grpc_core {
62 
LockfreeEvent()63 LockfreeEvent::LockfreeEvent() { InitEvent(); }
64 
InitEvent()65 void LockfreeEvent::InitEvent() {
66   /* Perform an atomic store to start the state machine.
67 
68      Note carefully that LockfreeEvent *MAY* be used whilst in a destroyed
69      state, while a file descriptor is on a freelist. In such a state it may
70      be SetReady'd, and so we need to perform an atomic operation here to
71      ensure no races */
72   gpr_atm_no_barrier_store(&state_, kClosureNotReady);
73 }
74 
DestroyEvent()75 void LockfreeEvent::DestroyEvent() {
76   gpr_atm curr;
77   do {
78     curr = gpr_atm_no_barrier_load(&state_);
79     if (curr & kShutdownBit) {
80       GRPC_ERROR_UNREF((grpc_error*)(curr & ~kShutdownBit));
81     } else {
82       GPR_ASSERT(curr == kClosureNotReady || curr == kClosureReady);
83     }
84     /* we CAS in a shutdown, no error value here. If this event is interacted
85        with post-deletion (see the note in the constructor) we want the bit
86        pattern to prevent error retention in a deleted object */
87   } while (!gpr_atm_no_barrier_cas(&state_, curr,
88                                    kShutdownBit /* shutdown, no error */));
89 }
90 
NotifyOn(grpc_closure * closure)91 void LockfreeEvent::NotifyOn(grpc_closure* closure) {
92   while (true) {
93     /* This load needs to be an acquire load because this can be a shutdown
94      * error that we might need to reference. Adding acquire semantics makes
95      * sure that the shutdown error has been initialized properly before us
96      * referencing it. */
97     gpr_atm curr = gpr_atm_acq_load(&state_);
98     if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
99       gpr_log(GPR_DEBUG, "LockfreeEvent::NotifyOn: %p curr=%p closure=%p", this,
100               (void*)curr, closure);
101     }
102     switch (curr) {
103       case kClosureNotReady: {
104         /* kClosureNotReady -> <closure>.
105 
106            We're guaranteed by API that there's an acquire barrier before here,
107            so there's no need to double-dip and this can be a release-only.
108 
109            The release itself pairs with the acquire half of a set_ready full
110            barrier. */
111         if (gpr_atm_rel_cas(&state_, kClosureNotReady, (gpr_atm)closure)) {
112           return; /* Successful. Return */
113         }
114 
115         break; /* retry */
116       }
117 
118       case kClosureReady: {
119         /* Change the state to kClosureNotReady. Schedule the closure if
120            successful. If not, the state most likely transitioned to shutdown.
121            We should retry.
122 
123            This can be a no-barrier cas since the state is being transitioned to
124            kClosureNotReady; set_ready and set_shutdown do not schedule any
125            closure when transitioning out of CLOSURE_NO_READY state (i.e there
126            is no other code that needs to 'happen-after' this) */
127         if (gpr_atm_no_barrier_cas(&state_, kClosureReady, kClosureNotReady)) {
128           ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_NONE);
129           return; /* Successful. Return */
130         }
131 
132         break; /* retry */
133       }
134 
135       default: {
136         /* 'curr' is either a closure or the fd is shutdown(in which case 'curr'
137            contains a pointer to the shutdown-error). If the fd is shutdown,
138            schedule the closure with the shutdown error */
139         if ((curr & kShutdownBit) > 0) {
140           grpc_error* shutdown_err = (grpc_error*)(curr & ~kShutdownBit);
141           ExecCtx::Run(DEBUG_LOCATION, closure,
142                        GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
143                            "FD Shutdown", &shutdown_err, 1));
144           return;
145         }
146 
147         /* There is already a closure!. This indicates a bug in the code */
148         gpr_log(GPR_ERROR,
149                 "LockfreeEvent::NotifyOn: notify_on called with a previous "
150                 "callback still pending");
151         abort();
152       }
153     }
154   }
155 
156   GPR_UNREACHABLE_CODE(return );
157 }
158 
SetShutdown(grpc_error * shutdown_err)159 bool LockfreeEvent::SetShutdown(grpc_error* shutdown_err) {
160   gpr_atm new_state = (gpr_atm)shutdown_err | kShutdownBit;
161 
162   while (true) {
163     gpr_atm curr = gpr_atm_no_barrier_load(&state_);
164     if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
165       gpr_log(GPR_DEBUG, "LockfreeEvent::SetShutdown: %p curr=%p err=%s",
166               &state_, (void*)curr, grpc_error_string(shutdown_err));
167     }
168     switch (curr) {
169       case kClosureReady:
170       case kClosureNotReady:
171         /* Need a full barrier here so that the initial load in notify_on
172            doesn't need a barrier */
173         if (gpr_atm_full_cas(&state_, curr, new_state)) {
174           return true; /* early out */
175         }
176         break; /* retry */
177 
178       default: {
179         /* 'curr' is either a closure or the fd is already shutdown */
180 
181         /* If fd is already shutdown, we are done */
182         if ((curr & kShutdownBit) > 0) {
183           GRPC_ERROR_UNREF(shutdown_err);
184           return false;
185         }
186 
187         /* Fd is not shutdown. Schedule the closure and move the state to
188            shutdown state.
189            Needs an acquire to pair with setting the closure (and get a
190            happens-after on that edge), and a release to pair with anything
191            loading the shutdown state. */
192         if (gpr_atm_full_cas(&state_, curr, new_state)) {
193           ExecCtx::Run(DEBUG_LOCATION, (grpc_closure*)curr,
194                        GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING(
195                            "FD Shutdown", &shutdown_err, 1));
196           return true;
197         }
198 
199         /* 'curr' was a closure but now changed to a different state. We will
200           have to retry */
201         break;
202       }
203     }
204   }
205 
206   GPR_UNREACHABLE_CODE(return false);
207 }
208 
SetReady()209 void LockfreeEvent::SetReady() {
210   while (true) {
211     gpr_atm curr = gpr_atm_no_barrier_load(&state_);
212 
213     if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) {
214       gpr_log(GPR_DEBUG, "LockfreeEvent::SetReady: %p curr=%p", &state_,
215               (void*)curr);
216     }
217 
218     switch (curr) {
219       case kClosureReady: {
220         /* Already ready. We are done here */
221         return;
222       }
223 
224       case kClosureNotReady: {
225         /* No barrier required as we're transitioning to a state that does not
226            involve a closure */
227         if (gpr_atm_no_barrier_cas(&state_, kClosureNotReady, kClosureReady)) {
228           return; /* early out */
229         }
230         break; /* retry */
231       }
232 
233       default: {
234         /* 'curr' is either a closure or the fd is shutdown */
235         if ((curr & kShutdownBit) > 0) {
236           /* The fd is shutdown. Do nothing */
237           return;
238         }
239         /* Full cas: acquire pairs with this cas' release in the event of a
240            spurious set_ready; release pairs with this or the acquire in
241            notify_on (or set_shutdown) */
242         else if (gpr_atm_full_cas(&state_, curr, kClosureNotReady)) {
243           ExecCtx::Run(DEBUG_LOCATION, (grpc_closure*)curr, GRPC_ERROR_NONE);
244           return;
245         }
246         /* else the state changed again (only possible by either a racing
247            set_ready or set_shutdown functions. In both these cases, the closure
248            would have been scheduled for execution. So we are done here */
249         return;
250       }
251     }
252   }
253 }
254 
255 }  // namespace grpc_core
256