blob: c8f7e5f3e77450288c88607ac8dde74d713ca008 [file] [log] [blame]
Patrick Williams74187662022-08-26 19:28:24 -05001#include <systemd/sd-bus.h>
2
3#include <sdbusplus/async/context.hpp>
4
Patrick Williams73e278b2022-09-16 08:31:36 -05005#include <chrono>
6
Patrick Williams74187662022-08-26 19:28:24 -05007namespace sdbusplus::async
8{
9
Patrick Williams73e278b2022-09-16 08:31:36 -050010context::context(bus_t&& b) : bus(std::move(b))
11{
12 dbus_source = event_loop.add_io(bus.get_fd(), EPOLLIN, dbus_event_handle,
13 this);
14}
15
Patrick Williams74187662022-08-26 19:28:24 -050016namespace details
17{
18
19/* The sd_bus_wait/process completion event.
20 *
21 * The wait/process handshake is modelled as a Sender with the the worker
22 * task `co_await`ing Senders over and over. This class is the completion
23 * handling for the Sender (to get it back to the Receiver, ie. the worker).
24 */
25struct wait_process_completion : bus::details::bus_friend
26{
27 explicit wait_process_completion(context& ctx) : ctx(ctx) {}
28 virtual ~wait_process_completion() = default;
29
30 // Called by the `caller` to indicate the Sender is completed.
31 virtual void complete() noexcept = 0;
Patrick Williams73e278b2022-09-16 08:31:36 -050032 // Called by the `caller` to indicate the Sender should be stopped.
33 virtual void stop() noexcept = 0;
Patrick Williams74187662022-08-26 19:28:24 -050034
35 // Arm the completion event.
36 void arm() noexcept;
37
38 // Data to share with the worker.
39 context& ctx;
Patrick Williams435eb1b2022-09-16 16:22:07 -050040 event_t::time_resolution timeout{};
Patrick Williams74187662022-08-26 19:28:24 -050041
Patrick Williams97c31c82023-05-25 11:04:46 -050042 // TODO: It seems like we should be able to do a normal `task<>` here
43 // but spawn on it compile fails.
44 static exec::basic_task<void, exec::__task::__raw_task_context<void>>
45 loop(context& ctx);
Patrick Williams74187662022-08-26 19:28:24 -050046 static void wait_once(context& ctx);
47};
48
49/* The completion template based on receiver type.
50 *
51 * The type of the receivers (typically the co_awaiter) is only known by
52 * a template, so we need a sub-class of completion to hold the receiver.
53 */
54template <execution::receiver R>
55struct wait_process_operation : public wait_process_completion
56{
57 wait_process_operation(context& ctx, R r) :
58 wait_process_completion(ctx), receiver(std::move(r))
59 {}
60
61 wait_process_operation(wait_process_operation&&) = delete;
62
63 void complete() noexcept override final
64 {
65 execution::set_value(std::move(this->receiver));
66 }
67
Patrick Williams73e278b2022-09-16 08:31:36 -050068 void stop() noexcept override final
69 {
70 // Stop can be called when the context is shutting down,
71 // so treat it as if the receiver completed.
72 execution::set_value(std::move(this->receiver));
73 }
74
Patrick Williams74187662022-08-26 19:28:24 -050075 friend void tag_invoke(execution::start_t,
76 wait_process_operation& self) noexcept
77 {
78 self.arm();
79 }
80
81 R receiver;
82};
83
84/* The sender for the wait/process event. */
85struct wait_process_sender
86{
Ed Tanousb8be5992023-01-04 15:56:20 -080087 explicit wait_process_sender(context& ctx) : ctx(ctx) {}
Patrick Williams74187662022-08-26 19:28:24 -050088
89 friend auto tag_invoke(execution::get_completion_signatures_t,
90 const wait_process_sender&, auto)
91 -> execution::completion_signatures<execution::set_value_t()>;
92
93 template <execution::receiver R>
94 friend auto tag_invoke(execution::connect_t, wait_process_sender&& self,
95 R r) -> wait_process_operation<R>
96 {
97 // Create the completion for the wait.
98 return {self.ctx, std::move(r)};
99 }
100
101 private:
102 context& ctx;
103};
104
Patrick Williams97c31c82023-05-25 11:04:46 -0500105exec::basic_task<void, exec::__task::__raw_task_context<void>>
106 wait_process_completion::loop(context& ctx)
Patrick Williams74187662022-08-26 19:28:24 -0500107{
Patrick Williams78e436f2022-09-21 10:06:20 -0500108 while (!ctx.final_stop.stop_requested())
Patrick Williams74187662022-08-26 19:28:24 -0500109 {
110 // Handle the next sdbus event.
111 co_await wait_process_sender(ctx);
112
113 // Completion likely happened on the context 'caller' thread, so
114 // we need to switch to the worker thread.
115 co_await execution::schedule(ctx.loop.get_scheduler());
116 }
Patrick Williams10483c92022-09-23 11:33:39 -0500117
118 {
119 std::lock_guard lock{ctx.lock};
120 ctx.wait_process_stopped = true;
121 }
Patrick Williams74187662022-08-26 19:28:24 -0500122}
123
124} // namespace details
125
126context::~context() noexcept(false)
127{
128 if (worker_thread.joinable())
129 {
130 throw std::logic_error(
131 "sdbusplus::async::context destructed without completion.");
132 }
133}
134
Patrick Williams3c242ba2022-09-23 09:51:55 -0500135void context::run()
Patrick Williams74187662022-08-26 19:28:24 -0500136{
Patrick Williams10483c92022-09-23 11:33:39 -0500137 // Run the primary portion of the run-loop.
138 caller_run();
Patrick Williams74187662022-08-26 19:28:24 -0500139
Patrick Williams5d16a8e2023-05-25 12:13:24 -0500140 // This should be final_stop...
Patrick Williams10483c92022-09-23 11:33:39 -0500141
142 // We need to wait for the pending wait process and stop it.
143 wait_for_wait_process_stopped();
Patrick Williams4cfc2842022-09-22 09:53:33 -0500144
Patrick Williams78e436f2022-09-21 10:06:20 -0500145 // Wait for all the internal tasks to complete.
Patrick Williams97c31c82023-05-25 11:04:46 -0500146 stdexec::sync_wait(internal_tasks.on_empty());
Patrick Williamsc5b5ff52022-09-21 08:34:22 -0500147
Patrick Williams10483c92022-09-23 11:33:39 -0500148 // Finish up the loop and join the thread.
149 // (There shouldn't be anything going on by this point anyhow.)
Patrick Williams74187662022-08-26 19:28:24 -0500150 loop.finish();
151 if (worker_thread.joinable())
152 {
153 worker_thread.join();
154 }
155}
156
Patrick Williams3c242ba2022-09-23 09:51:55 -0500157void context::worker_run()
Patrick Williams74187662022-08-26 19:28:24 -0500158{
Patrick Williams3c242ba2022-09-23 09:51:55 -0500159 // Start the sdbus 'wait/process' loop; treat it as an internal task.
Patrick Williams97c31c82023-05-25 11:04:46 -0500160 internal_tasks.spawn(details::wait_process_completion::loop(*this));
Patrick Williams74187662022-08-26 19:28:24 -0500161
162 // Run the execution::run_loop to handle all the tasks.
163 loop.run();
164}
165
Patrick Williams5d16a8e2023-05-25 12:13:24 -0500166void context::spawn_complete()
Patrick Williams10483c92022-09-23 11:33:39 -0500167{
168 {
169 std::lock_guard l{lock};
170 spawn_watcher_running = false;
Patrick Williams10483c92022-09-23 11:33:39 -0500171 }
172
173 if (stop_requested())
174 {
175 final_stop.request_stop();
176 }
177
178 caller_wait.notify_one();
179 event_loop.break_run();
180}
181
182void context::check_stop_requested()
183{
184 if (stop_requested())
185 {
186 throw std::logic_error(
187 "sdbusplus::async::context spawn called while already stopped.");
188 }
189}
190
191void context::spawn_watcher()
192{
193 {
194 std::lock_guard l{lock};
195 if (spawn_watcher_running)
196 {
197 return;
198 }
199
200 spawn_watcher_running = true;
201 }
202
203 // Spawn the watch for completion / exceptions.
Patrick Williams97c31c82023-05-25 11:04:46 -0500204 internal_tasks.spawn(pending_tasks.on_empty() |
205 execution::then([this]() { spawn_complete(); }));
Patrick Williams10483c92022-09-23 11:33:39 -0500206}
207
208void context::caller_run()
209{
210 // We are able to run the loop until the context is requested to stop or
211 // we get an exception.
212 auto keep_running = [this]() {
213 std::lock_guard l{lock};
Patrick Williams5d16a8e2023-05-25 12:13:24 -0500214 return !final_stop.stop_requested();
Patrick Williams10483c92022-09-23 11:33:39 -0500215 };
216
217 // If we are suppose to keep running, start the run loop.
218 if (keep_running())
219 {
220 // Start up the worker thread.
221 if (!worker_thread.joinable())
222 {
223 worker_thread = std::thread{[this]() { worker_run(); }};
224 }
225 else
226 {
Patrick Williams5d16a8e2023-05-25 12:13:24 -0500227 // We've already been running and there might a completion pending.
228 // Spawn a new watcher that checks for these.
Patrick Williams10483c92022-09-23 11:33:39 -0500229 spawn_watcher();
230 }
231
232 while (keep_running())
233 {
234 // Handle waiting on all the sd-events.
235 details::wait_process_completion::wait_once(*this);
236 }
237 }
238 else
239 {
Patrick Williams5d16a8e2023-05-25 12:13:24 -0500240 // There might be pending completions still, so spawn a watcher for
241 // them.
Patrick Williams10483c92022-09-23 11:33:39 -0500242 spawn_watcher();
243 }
244}
245
246void context::wait_for_wait_process_stopped()
247{
248 auto worker = std::exchange(pending, nullptr);
249 while (worker == nullptr)
250 {
251 std::lock_guard l{lock};
252 if (wait_process_stopped)
253 {
254 break;
255 }
256
257 worker = std::exchange(staged, nullptr);
258 if (!worker)
259 {
260 std::this_thread::yield();
261 }
262 }
263 if (worker)
264 {
265 worker->stop();
266 wait_process_stopped = true;
267 }
268}
269
Patrick Williams74187662022-08-26 19:28:24 -0500270void details::wait_process_completion::arm() noexcept
271{
272 // Call process. True indicates something was handled and we do not
273 // need to `wait`, because there might be yet another pending operation
274 // to process, so immediately signal the operation as complete.
275 if (ctx.get_bus().process_discard())
276 {
277 this->complete();
278 return;
279 }
280
Patrick Williams73e278b2022-09-16 08:31:36 -0500281 // We need to call wait now, get the current timeout and stage ourselves
282 // as the next completion.
Patrick Williams74187662022-08-26 19:28:24 -0500283
284 // Get the bus' timeout.
Patrick Williams73e278b2022-09-16 08:31:36 -0500285 uint64_t to_usec = 0;
286 sd_bus_get_timeout(get_busp(ctx.get_bus()), &to_usec);
Patrick Williams74187662022-08-26 19:28:24 -0500287
Patrick Williams73e278b2022-09-16 08:31:36 -0500288 if (to_usec == UINT64_MAX)
Patrick Williams74187662022-08-26 19:28:24 -0500289 {
290 // sd_bus_get_timeout returns UINT64_MAX to indicate 'wait forever'.
Patrick Williams73e278b2022-09-16 08:31:36 -0500291 // Turn this into -1 for sd-event.
292 timeout = std::chrono::microseconds{-1};
Patrick Williams74187662022-08-26 19:28:24 -0500293 }
294 else
295 {
Patrick Williams73e278b2022-09-16 08:31:36 -0500296 timeout = std::chrono::microseconds(to_usec);
Patrick Williams74187662022-08-26 19:28:24 -0500297 }
298
299 // Assign ourselves as the pending completion and release the caller.
300 std::lock_guard lock{ctx.lock};
Patrick Williams73e278b2022-09-16 08:31:36 -0500301 ctx.staged = this;
Patrick Williams74187662022-08-26 19:28:24 -0500302 ctx.caller_wait.notify_one();
303}
304
305void details::wait_process_completion::wait_once(context& ctx)
306{
Patrick Williams74187662022-08-26 19:28:24 -0500307 // Scope for lock.
308 {
309 std::unique_lock lock{ctx.lock};
310
311 // If there isn't a completion waiting already, wait on the condition
312 // variable for one to show up (we can't call `poll` yet because we
313 // don't have the required parameters).
Patrick Williams73e278b2022-09-16 08:31:36 -0500314 ctx.caller_wait.wait(lock, [&] {
315 return (ctx.pending != nullptr) || (ctx.staged != nullptr) ||
Patrick Williams5d16a8e2023-05-25 12:13:24 -0500316 ctx.final_stop.stop_requested();
Patrick Williams73e278b2022-09-16 08:31:36 -0500317 });
Patrick Williams74187662022-08-26 19:28:24 -0500318
Patrick Williams73e278b2022-09-16 08:31:36 -0500319 // Save the waiter as pending.
320 if (ctx.pending == nullptr)
321 {
322 ctx.pending = std::exchange(ctx.staged, nullptr);
323 }
Patrick Williams74187662022-08-26 19:28:24 -0500324 }
325
Patrick Williams73e278b2022-09-16 08:31:36 -0500326 // Run the event loop to process one request.
Patrick Williams10483c92022-09-23 11:33:39 -0500327 // If the context has been requested to be stopped, skip the event loop.
328 if (!ctx.final_stop.stop_requested() && ctx.pending)
Patrick Williams73e278b2022-09-16 08:31:36 -0500329 {
Patrick Williams10483c92022-09-23 11:33:39 -0500330 ctx.event_loop.run_one(ctx.pending->timeout);
Patrick Williams73e278b2022-09-16 08:31:36 -0500331 }
332}
333
334int context::dbus_event_handle(sd_event_source*, int, uint32_t, void* data)
335{
336 auto self = static_cast<context*>(data);
337
Patrick Williams10483c92022-09-23 11:33:39 -0500338 auto pending = std::exchange(self->pending, nullptr);
Patrick Williams73e278b2022-09-16 08:31:36 -0500339 if (pending != nullptr)
340 {
Patrick Williams10483c92022-09-23 11:33:39 -0500341 pending->complete();
Patrick Williams73e278b2022-09-16 08:31:36 -0500342 }
343
344 return 0;
Patrick Williams74187662022-08-26 19:28:24 -0500345}
346
347} // namespace sdbusplus::async