blob: 6b5b601efeefc606799ff63f68c5e1024f18a895 [file] [log] [blame]
Austin Schuh54cf95f2019-11-29 13:14:18 -08001#include "aos/events/event_loop.h"
2
3#include "aos/configuration.h"
4#include "aos/configuration_generated.h"
Tyler Chatow67ddb032020-01-12 14:30:04 -08005#include "aos/logging/implementations.h"
Austin Schuh070019a2022-12-20 22:23:09 -08006#include "aos/realtime.h"
Austin Schuh54cf95f2019-11-29 13:14:18 -08007#include "glog/logging.h"
8
Austin Schuh39788ff2019-12-01 18:22:57 -08009DEFINE_bool(timing_reports, true, "Publish timing reports.");
10DEFINE_int32(timing_report_ms, 1000,
11 "Period in milliseconds to publish timing reports at.");
12
Austin Schuh54cf95f2019-11-29 13:14:18 -080013namespace aos {
Austin Schuhd54780b2020-10-03 16:26:02 -070014namespace {
15void CheckAlignment(const Channel *channel) {
16 if (channel->max_size() % alignof(flatbuffers::largest_scalar_t) != 0) {
17 LOG(FATAL) << "max_size() (" << channel->max_size()
18 << ") is not a multiple of alignment ("
19 << alignof(flatbuffers::largest_scalar_t) << ") for channel "
20 << configuration::CleanedChannelToString(channel) << ".";
21 }
22}
milind1f1dca32021-07-03 13:50:07 -070023
24std::string_view ErrorToString(const RawSender::Error err) {
25 switch (err) {
26 case RawSender::Error::kOk:
27 return "RawSender::Error::kOk";
28 case RawSender::Error::kMessagesSentTooFast:
29 return "RawSender::Error::kMessagesSentTooFast";
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -070030 case RawSender::Error::kInvalidRedzone:
31 return "RawSender::Error::kInvalidRedzone";
milind1f1dca32021-07-03 13:50:07 -070032 }
33 LOG(FATAL) << "Unknown error given with code " << static_cast<int>(err);
34}
Austin Schuhd54780b2020-10-03 16:26:02 -070035} // namespace
Austin Schuh54cf95f2019-11-29 13:14:18 -080036
milind1f1dca32021-07-03 13:50:07 -070037std::ostream &operator<<(std::ostream &os, const RawSender::Error err) {
38 os << ErrorToString(err);
39 return os;
40}
41
42void RawSender::CheckOk(const RawSender::Error err) {
43 CHECK_EQ(err, Error::kOk) << "Messages were sent too fast on channel: "
44 << configuration::CleanedChannelToString(channel_);
45}
46
Austin Schuh39788ff2019-12-01 18:22:57 -080047RawSender::RawSender(EventLoop *event_loop, const Channel *channel)
48 : event_loop_(event_loop),
49 channel_(channel),
Brian Silverman79ec7fc2020-06-08 20:11:22 -050050 ftrace_prefix_(configuration::StrippedChannelToString(channel)),
Austin Schuh39788ff2019-12-01 18:22:57 -080051 timing_(event_loop_->ChannelIndex(channel)) {
52 event_loop_->NewSender(this);
53}
54
55RawSender::~RawSender() { event_loop_->DeleteSender(this); }
56
milind1f1dca32021-07-03 13:50:07 -070057RawSender::Error RawSender::DoSend(
58 const SharedSpan data, monotonic_clock::time_point monotonic_remote_time,
59 realtime_clock::time_point realtime_remote_time,
60 uint32_t remote_queue_index, const UUID &source_boot_uuid) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -070061 return DoSend(data->data(), data->size(), monotonic_remote_time,
62 realtime_remote_time, remote_queue_index, source_boot_uuid);
63}
64
James Kuszmaul93abac12022-04-14 15:05:10 -070065void RawSender::RecordSendResult(const Error error, size_t message_size) {
66 switch (error) {
67 case Error::kOk: {
68 if (timing_.sender) {
69 timing_.size.Add(message_size);
70 timing_.sender->mutate_count(timing_.sender->count() + 1);
71 }
72 break;
73 }
74 case Error::kMessagesSentTooFast:
75 timing_.IncrementError(timing::SendError::MESSAGE_SENT_TOO_FAST);
76 break;
77 case Error::kInvalidRedzone:
78 timing_.IncrementError(timing::SendError::INVALID_REDZONE);
79 break;
80 }
81}
82
Austin Schuh39788ff2019-12-01 18:22:57 -080083RawFetcher::RawFetcher(EventLoop *event_loop, const Channel *channel)
84 : event_loop_(event_loop),
85 channel_(channel),
Brian Silverman79ec7fc2020-06-08 20:11:22 -050086 ftrace_prefix_(configuration::StrippedChannelToString(channel)),
Austin Schuh39788ff2019-12-01 18:22:57 -080087 timing_(event_loop_->ChannelIndex(channel)) {
Austin Schuhad154822019-12-27 15:45:13 -080088 context_.monotonic_event_time = monotonic_clock::min_time;
89 context_.monotonic_remote_time = monotonic_clock::min_time;
90 context_.realtime_event_time = realtime_clock::min_time;
91 context_.realtime_remote_time = realtime_clock::min_time;
Austin Schuh39788ff2019-12-01 18:22:57 -080092 context_.queue_index = 0xffffffff;
Austin Schuh0debde12022-08-17 16:25:17 -070093 context_.remote_queue_index = 0xffffffffu;
Austin Schuh39788ff2019-12-01 18:22:57 -080094 context_.size = 0;
95 context_.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -070096 context_.buffer_index = -1;
Austin Schuh39788ff2019-12-01 18:22:57 -080097 event_loop_->NewFetcher(this);
98}
99
100RawFetcher::~RawFetcher() { event_loop_->DeleteFetcher(this); }
101
102TimerHandler::TimerHandler(EventLoop *event_loop, std::function<void()> fn)
103 : event_loop_(event_loop), fn_(std::move(fn)) {}
104
105TimerHandler::~TimerHandler() {}
106
107PhasedLoopHandler::PhasedLoopHandler(EventLoop *event_loop,
108 std::function<void(int)> fn,
109 const monotonic_clock::duration interval,
110 const monotonic_clock::duration offset)
111 : event_loop_(event_loop),
112 fn_(std::move(fn)),
113 phased_loop_(interval, event_loop_->monotonic_now(), offset) {
114 event_loop_->OnRun([this]() {
115 const monotonic_clock::time_point monotonic_now =
116 event_loop_->monotonic_now();
117 phased_loop_.Reset(monotonic_now);
118 Reschedule(
119 [this](monotonic_clock::time_point sleep_time) {
120 Schedule(sleep_time);
121 },
122 monotonic_now);
Milind Upadhyay42589bb2021-05-19 20:05:16 -0700123 // Reschedule here will count cycles elapsed before now, and then the
124 // reschedule before running the handler will count the time that elapsed
125 // then. So clear the count here.
Austin Schuh39788ff2019-12-01 18:22:57 -0800126 cycles_elapsed_ = 0;
127 });
128}
129
130PhasedLoopHandler::~PhasedLoopHandler() {}
131
Austin Schuh83c7f702021-01-19 22:36:29 -0800132EventLoop::EventLoop(const Configuration *configuration)
133 : timing_report_(flatbuffers::DetachedBuffer()),
Austin Schuh56196432020-10-24 20:15:21 -0700134 configuration_(configuration) {}
Tyler Chatow67ddb032020-01-12 14:30:04 -0800135
Austin Schuh39788ff2019-12-01 18:22:57 -0800136EventLoop::~EventLoop() {
Brian Silvermanbf889922021-11-10 12:41:57 -0800137 if (!senders_.empty()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700138 for (const RawSender *sender : senders_) {
139 LOG(ERROR) << " Sender "
140 << configuration::StrippedChannelToString(sender->channel())
141 << " still open";
142 }
143 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800144 CHECK_EQ(senders_.size(), 0u) << ": Not all senders destroyed";
Austin Schuh7d87b672019-12-01 20:23:49 -0800145 CHECK_EQ(events_.size(), 0u) << ": Not all events unregistered";
Austin Schuh39788ff2019-12-01 18:22:57 -0800146}
147
Brian Silvermanbf889922021-11-10 12:41:57 -0800148void EventLoop::SkipTimingReport() {
149 skip_timing_report_ = true;
150 timing_report_ = flatbuffers::DetachedBuffer();
151
152 for (size_t i = 0; i < timers_.size(); ++i) {
153 timers_[i]->timing_.set_timing_report(nullptr);
154 }
155
156 for (size_t i = 0; i < phased_loops_.size(); ++i) {
157 phased_loops_[i]->timing_.set_timing_report(nullptr);
158 }
159
160 for (size_t i = 0; i < watchers_.size(); ++i) {
161 watchers_[i]->set_timing_report(nullptr);
162 }
163
164 for (size_t i = 0; i < senders_.size(); ++i) {
165 senders_[i]->timing_.set_timing_report(nullptr);
166 }
167
168 for (size_t i = 0; i < fetchers_.size(); ++i) {
169 fetchers_[i]->timing_.set_timing_report(nullptr);
170 }
171}
172
Austin Schuh39788ff2019-12-01 18:22:57 -0800173int EventLoop::ChannelIndex(const Channel *channel) {
Austin Schuhc9e10ec2020-01-26 16:08:28 -0800174 return configuration::ChannelIndex(configuration_, channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800175}
176
Brian Silverman5120afb2020-01-31 17:44:35 -0800177WatcherState *EventLoop::GetWatcherState(const Channel *channel) {
178 const int channel_index = ChannelIndex(channel);
179 for (const std::unique_ptr<WatcherState> &watcher : watchers_) {
180 if (watcher->channel_index() == channel_index) {
181 return watcher.get();
182 }
183 }
184 LOG(FATAL) << "No watcher found for channel";
185}
186
Austin Schuh39788ff2019-12-01 18:22:57 -0800187void EventLoop::NewSender(RawSender *sender) {
188 senders_.emplace_back(sender);
189 UpdateTimingReport();
190}
191void EventLoop::DeleteSender(RawSender *sender) {
192 CHECK(!is_running());
193 auto s = std::find(senders_.begin(), senders_.end(), sender);
194 CHECK(s != senders_.end()) << ": Sender not in senders list";
195 senders_.erase(s);
196 UpdateTimingReport();
197}
198
199TimerHandler *EventLoop::NewTimer(std::unique_ptr<TimerHandler> timer) {
200 timers_.emplace_back(std::move(timer));
201 UpdateTimingReport();
202 return timers_.back().get();
203}
204
205PhasedLoopHandler *EventLoop::NewPhasedLoop(
206 std::unique_ptr<PhasedLoopHandler> phased_loop) {
207 phased_loops_.emplace_back(std::move(phased_loop));
208 UpdateTimingReport();
209 return phased_loops_.back().get();
210}
211
212void EventLoop::NewFetcher(RawFetcher *fetcher) {
Austin Schuhd54780b2020-10-03 16:26:02 -0700213 CheckAlignment(fetcher->channel());
214
Austin Schuh39788ff2019-12-01 18:22:57 -0800215 fetchers_.emplace_back(fetcher);
216 UpdateTimingReport();
217}
218
219void EventLoop::DeleteFetcher(RawFetcher *fetcher) {
220 CHECK(!is_running());
221 auto f = std::find(fetchers_.begin(), fetchers_.end(), fetcher);
222 CHECK(f != fetchers_.end()) << ": Fetcher not in fetchers list";
223 fetchers_.erase(f);
224 UpdateTimingReport();
225}
226
227WatcherState *EventLoop::NewWatcher(std::unique_ptr<WatcherState> watcher) {
228 watchers_.emplace_back(std::move(watcher));
229
230 UpdateTimingReport();
231
232 return watchers_.back().get();
233}
234
Brian Silverman0fc69932020-01-24 21:54:02 -0800235void EventLoop::TakeWatcher(const Channel *channel) {
236 CHECK(!is_running()) << ": Cannot add new objects while running.";
237 ChannelIndex(channel);
238
Austin Schuhd54780b2020-10-03 16:26:02 -0700239 CheckAlignment(channel);
240
Brian Silverman0fc69932020-01-24 21:54:02 -0800241 CHECK(taken_senders_.find(channel) == taken_senders_.end())
Austin Schuh8072f922020-02-16 21:51:47 -0800242 << ": " << configuration::CleanedChannelToString(channel)
243 << " is already being used.";
Brian Silverman0fc69932020-01-24 21:54:02 -0800244
245 auto result = taken_watchers_.insert(channel);
Austin Schuh8072f922020-02-16 21:51:47 -0800246 CHECK(result.second) << ": " << configuration::CleanedChannelToString(channel)
Brian Silverman0fc69932020-01-24 21:54:02 -0800247 << " is already being used.";
248
249 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
Austin Schuh8072f922020-02-16 21:51:47 -0800250 LOG(FATAL) << ": " << configuration::CleanedChannelToString(channel)
Brian Silverman0fc69932020-01-24 21:54:02 -0800251 << " is not able to be watched on this node. Check your "
252 "configuration.";
253 }
254}
255
256void EventLoop::TakeSender(const Channel *channel) {
257 CHECK(!is_running()) << ": Cannot add new objects while running.";
258 ChannelIndex(channel);
259
Austin Schuhd54780b2020-10-03 16:26:02 -0700260 CheckAlignment(channel);
261
Brian Silverman0fc69932020-01-24 21:54:02 -0800262 CHECK(taken_watchers_.find(channel) == taken_watchers_.end())
Austin Schuh8072f922020-02-16 21:51:47 -0800263 << ": Channel " << configuration::CleanedChannelToString(channel)
264 << " is already being used.";
Brian Silverman0fc69932020-01-24 21:54:02 -0800265
266 // We don't care if this is a duplicate.
267 taken_senders_.insert(channel);
268}
269
Austin Schuh39788ff2019-12-01 18:22:57 -0800270void EventLoop::SendTimingReport() {
Brian Silvermance418d02021-11-03 11:25:52 -0700271 if (!timing_report_sender_) {
272 // Timing reports are disabled, so nothing for us to do.
273 return;
274 }
275
Austin Schuh39788ff2019-12-01 18:22:57 -0800276 // We need to do a fancy dance here to get all the accounting to work right.
277 // We want to copy the memory here, but then send after resetting. Otherwise
278 // the send for the timing report won't be counted in the timing report.
279 //
280 // Also, flatbuffers build from the back end. So place this at the back end
281 // of the buffer. We only have to care because we are using this in a very
282 // raw fashion.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800283 CHECK_LE(timing_report_.span().size(), timing_report_sender_->size())
Austin Schuh39788ff2019-12-01 18:22:57 -0800284 << ": Timing report bigger than the sender size.";
Austin Schuhadd6eb32020-11-09 21:24:26 -0800285 std::copy(timing_report_.span().data(),
286 timing_report_.span().data() + timing_report_.span().size(),
Austin Schuh39788ff2019-12-01 18:22:57 -0800287 reinterpret_cast<uint8_t *>(timing_report_sender_->data()) +
Austin Schuhadd6eb32020-11-09 21:24:26 -0800288 timing_report_sender_->size() - timing_report_.span().size());
Austin Schuh39788ff2019-12-01 18:22:57 -0800289
290 for (const std::unique_ptr<TimerHandler> &timer : timers_) {
291 timer->timing_.ResetTimingReport();
292 }
293 for (const std::unique_ptr<WatcherState> &watcher : watchers_) {
294 watcher->ResetReport();
295 }
296 for (const std::unique_ptr<PhasedLoopHandler> &phased_loop : phased_loops_) {
297 phased_loop->timing_.ResetTimingReport();
298 }
299 for (RawSender *sender : senders_) {
300 sender->timing_.ResetTimingReport();
301 }
302 for (RawFetcher *fetcher : fetchers_) {
303 fetcher->timing_.ResetTimingReport();
304 }
milind1f1dca32021-07-03 13:50:07 -0700305 // TODO(milind): If we fail to send, we don't want to reset the timing report.
306 // We would need to move the reset after the send, and then find the correct
307 // timing report and set the reports with it instead of letting the sender do
308 // this. If we failed to send, we wouldn't reset or set the reports, so they
309 // can accumalate until the next send.
310 timing_report_failure_counter_.Count(
311 timing_report_sender_->Send(timing_report_.span().size()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800312}
313
314void EventLoop::UpdateTimingReport() {
Brian Silvermanbf889922021-11-10 12:41:57 -0800315 if (skip_timing_report_) {
316 return;
317 }
318
Austin Schuh39788ff2019-12-01 18:22:57 -0800319 // We need to support senders and fetchers changing while we are setting up
320 // the event loop. Otherwise we can't fetch or send until the loop runs. This
321 // means that on each change, we need to redo all this work. This makes setup
322 // more expensive, but not by all that much on a modern processor.
323
324 // Now, build up a report with everything pre-filled out.
325 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800326 fbb.ForceDefaults(true);
Austin Schuh39788ff2019-12-01 18:22:57 -0800327
328 // Pre-fill in the defaults for timers.
329 std::vector<flatbuffers::Offset<timing::Timer>> timer_offsets;
330 for (const std::unique_ptr<TimerHandler> &timer : timers_) {
331 flatbuffers::Offset<timing::Statistic> wakeup_latency_offset =
332 timing::CreateStatistic(fbb);
333 flatbuffers::Offset<timing::Statistic> handler_time_offset =
334 timing::CreateStatistic(fbb);
335 flatbuffers::Offset<flatbuffers::String> name_offset;
336 if (timer->name().size() != 0) {
337 name_offset = fbb.CreateString(timer->name());
338 }
339
340 timing::Timer::Builder timer_builder(fbb);
341
342 if (timer->name().size() != 0) {
343 timer_builder.add_name(name_offset);
344 }
345 timer_builder.add_wakeup_latency(wakeup_latency_offset);
346 timer_builder.add_handler_time(handler_time_offset);
347 timer_builder.add_count(0);
348 timer_offsets.emplace_back(timer_builder.Finish());
349 }
350
351 // Pre-fill in the defaults for phased_loops.
352 std::vector<flatbuffers::Offset<timing::Timer>> phased_loop_offsets;
353 for (const std::unique_ptr<PhasedLoopHandler> &phased_loop : phased_loops_) {
354 flatbuffers::Offset<timing::Statistic> wakeup_latency_offset =
355 timing::CreateStatistic(fbb);
356 flatbuffers::Offset<timing::Statistic> handler_time_offset =
357 timing::CreateStatistic(fbb);
358 flatbuffers::Offset<flatbuffers::String> name_offset;
359 if (phased_loop->name().size() != 0) {
360 name_offset = fbb.CreateString(phased_loop->name());
361 }
362
363 timing::Timer::Builder timer_builder(fbb);
364
365 if (phased_loop->name().size() != 0) {
366 timer_builder.add_name(name_offset);
367 }
368 timer_builder.add_wakeup_latency(wakeup_latency_offset);
369 timer_builder.add_handler_time(handler_time_offset);
370 timer_builder.add_count(0);
371 phased_loop_offsets.emplace_back(timer_builder.Finish());
372 }
373
374 // Pre-fill in the defaults for watchers.
375 std::vector<flatbuffers::Offset<timing::Watcher>> watcher_offsets;
376 for (const std::unique_ptr<WatcherState> &watcher : watchers_) {
377 flatbuffers::Offset<timing::Statistic> wakeup_latency_offset =
378 timing::CreateStatistic(fbb);
379 flatbuffers::Offset<timing::Statistic> handler_time_offset =
380 timing::CreateStatistic(fbb);
381
382 timing::Watcher::Builder watcher_builder(fbb);
383
384 watcher_builder.add_channel_index(watcher->channel_index());
385 watcher_builder.add_wakeup_latency(wakeup_latency_offset);
386 watcher_builder.add_handler_time(handler_time_offset);
387 watcher_builder.add_count(0);
388 watcher_offsets.emplace_back(watcher_builder.Finish());
389 }
390
391 // Pre-fill in the defaults for senders.
392 std::vector<flatbuffers::Offset<timing::Sender>> sender_offsets;
James Kuszmaulcc94ed42022-08-24 11:36:17 -0700393 for (RawSender *sender : senders_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800394 flatbuffers::Offset<timing::Statistic> size_offset =
395 timing::CreateStatistic(fbb);
396
James Kuszmaul78514332022-04-06 15:08:34 -0700397 const flatbuffers::Offset<
398 flatbuffers::Vector<flatbuffers::Offset<timing::SendErrorCount>>>
James Kuszmaulcc94ed42022-08-24 11:36:17 -0700399 error_counts_offset = sender->timing_.error_counter.Initialize(&fbb);
James Kuszmaul78514332022-04-06 15:08:34 -0700400
Austin Schuh39788ff2019-12-01 18:22:57 -0800401 timing::Sender::Builder sender_builder(fbb);
402
403 sender_builder.add_channel_index(sender->timing_.channel_index);
404 sender_builder.add_size(size_offset);
James Kuszmaul78514332022-04-06 15:08:34 -0700405 sender_builder.add_error_counts(error_counts_offset);
Austin Schuh39788ff2019-12-01 18:22:57 -0800406 sender_builder.add_count(0);
407 sender_offsets.emplace_back(sender_builder.Finish());
408 }
409
410 // Pre-fill in the defaults for fetchers.
411 std::vector<flatbuffers::Offset<timing::Fetcher>> fetcher_offsets;
412 for (RawFetcher *fetcher : fetchers_) {
413 flatbuffers::Offset<timing::Statistic> latency_offset =
414 timing::CreateStatistic(fbb);
415
416 timing::Fetcher::Builder fetcher_builder(fbb);
417
418 fetcher_builder.add_channel_index(fetcher->timing_.channel_index);
419 fetcher_builder.add_count(0);
420 fetcher_builder.add_latency(latency_offset);
421 fetcher_offsets.emplace_back(fetcher_builder.Finish());
422 }
423
424 // Then build the final report.
425 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Timer>>>
426 timers_offset;
427 if (timer_offsets.size() > 0) {
428 timers_offset = fbb.CreateVector(timer_offsets);
429 }
430
431 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Timer>>>
432 phased_loops_offset;
433 if (phased_loop_offsets.size() > 0) {
434 phased_loops_offset = fbb.CreateVector(phased_loop_offsets);
435 }
436
437 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Watcher>>>
438 watchers_offset;
439 if (watcher_offsets.size() > 0) {
440 watchers_offset = fbb.CreateVector(watcher_offsets);
441 }
442
443 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Sender>>>
444 senders_offset;
445 if (sender_offsets.size() > 0) {
446 senders_offset = fbb.CreateVector(sender_offsets);
447 }
448
449 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<timing::Fetcher>>>
450 fetchers_offset;
451 if (fetcher_offsets.size() > 0) {
452 fetchers_offset = fbb.CreateVector(fetcher_offsets);
453 }
454
455 flatbuffers::Offset<flatbuffers::String> name_offset =
456 fbb.CreateString(name());
457
458 timing::Report::Builder report_builder(fbb);
459 report_builder.add_name(name_offset);
460 report_builder.add_pid(GetTid());
461 if (timer_offsets.size() > 0) {
462 report_builder.add_timers(timers_offset);
463 }
464 if (phased_loop_offsets.size() > 0) {
465 report_builder.add_phased_loops(phased_loops_offset);
466 }
467 if (watcher_offsets.size() > 0) {
468 report_builder.add_watchers(watchers_offset);
469 }
470 if (sender_offsets.size() > 0) {
471 report_builder.add_senders(senders_offset);
472 }
473 if (fetcher_offsets.size() > 0) {
474 report_builder.add_fetchers(fetchers_offset);
475 }
milind1f1dca32021-07-03 13:50:07 -0700476 report_builder.add_send_failures(timing_report_failure_counter_.failures());
Austin Schuh39788ff2019-12-01 18:22:57 -0800477 fbb.Finish(report_builder.Finish());
478
479 timing_report_ = FlatbufferDetachedBuffer<timing::Report>(fbb.Release());
480
481 // Now that the pointers are stable, pass them to the timers and watchers to
482 // be updated.
483 for (size_t i = 0; i < timers_.size(); ++i) {
484 timers_[i]->timing_.set_timing_report(
485 timing_report_.mutable_message()->mutable_timers()->GetMutableObject(
486 i));
487 }
488
489 for (size_t i = 0; i < phased_loops_.size(); ++i) {
490 phased_loops_[i]->timing_.set_timing_report(
491 timing_report_.mutable_message()
492 ->mutable_phased_loops()
493 ->GetMutableObject(i));
494 }
495
496 for (size_t i = 0; i < watchers_.size(); ++i) {
497 watchers_[i]->set_timing_report(
498 timing_report_.mutable_message()->mutable_watchers()->GetMutableObject(
499 i));
500 }
501
502 for (size_t i = 0; i < senders_.size(); ++i) {
503 senders_[i]->timing_.set_timing_report(
504 timing_report_.mutable_message()->mutable_senders()->GetMutableObject(
505 i));
506 }
507
508 for (size_t i = 0; i < fetchers_.size(); ++i) {
509 fetchers_[i]->timing_.set_timing_report(
510 timing_report_.mutable_message()->mutable_fetchers()->GetMutableObject(
511 i));
512 }
513}
514
515void EventLoop::MaybeScheduleTimingReports() {
516 if (FLAGS_timing_reports && !skip_timing_report_) {
517 CHECK(!timing_report_sender_) << ": Timing reports already scheduled.";
518 // Make a raw sender for the report.
519 const Channel *channel = configuration::GetChannel(
520 configuration(), "/aos", timing::Report::GetFullyQualifiedName(),
Austin Schuhbca6cf02019-12-22 17:28:34 -0800521 name(), node());
Austin Schuh196a4452020-03-15 23:12:03 -0700522 CHECK(channel != nullptr) << ": Failed to look up {\"name\": \"/aos\", "
523 "\"type\": \"aos.timing.Report\"} on node "
524 << FlatbufferToJson(node());
Austin Schuhbca6cf02019-12-22 17:28:34 -0800525
526 // Since we are using a RawSender, validity isn't checked. So check it
527 // ourselves.
Austin Schuhca4828c2019-12-28 14:21:35 -0800528 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
529 LOG(FATAL) << "Channel { \"name\": \"/aos"
530 << channel->name()->string_view() << "\", \"type\": \""
531 << channel->type()->string_view()
532 << "\" } is not able to be sent on this node. Check your "
533 "configuration.";
Austin Schuhbca6cf02019-12-22 17:28:34 -0800534 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800535 CHECK(channel != nullptr) << ": Channel { \"name\": \"/aos\", \"type\": \""
536 << timing::Report::GetFullyQualifiedName()
537 << "\" } not found in config.";
538 timing_report_sender_ = MakeRawSender(channel);
539
540 // Register a handler which sends the report out by copying the raw data
541 // from the prebuilt and subsequently modified report.
542 TimerHandler *timing_reports_timer =
543 AddTimer([this]() { SendTimingReport(); });
544
545 // Set it up to send once per second.
546 timing_reports_timer->set_name("timing_reports");
547 OnRun([this, timing_reports_timer]() {
548 timing_reports_timer->Setup(
549 monotonic_now() + std::chrono::milliseconds(FLAGS_timing_report_ms),
550 std::chrono::milliseconds(FLAGS_timing_report_ms));
551 });
552
553 UpdateTimingReport();
554 }
555}
556
Austin Schuh7d87b672019-12-01 20:23:49 -0800557void EventLoop::ReserveEvents() {
558 events_.reserve(timers_.size() + phased_loops_.size() + watchers_.size());
559}
560
561namespace {
562bool CompareEvents(const EventLoopEvent *first, const EventLoopEvent *second) {
Brian Silvermanbd405c02020-06-23 16:25:23 -0700563 if (first->event_time() > second->event_time()) {
564 return true;
565 }
566 if (first->event_time() < second->event_time()) {
567 return false;
568 }
569 return first->generation() > second->generation();
Austin Schuh7d87b672019-12-01 20:23:49 -0800570}
571} // namespace
572
573void EventLoop::AddEvent(EventLoopEvent *event) {
574 DCHECK(std::find(events_.begin(), events_.end(), event) == events_.end());
Brian Silvermanbd405c02020-06-23 16:25:23 -0700575 DCHECK(event->generation() == 0);
576 event->set_generation(++event_generation_);
Austin Schuh7d87b672019-12-01 20:23:49 -0800577 events_.push_back(event);
578 std::push_heap(events_.begin(), events_.end(), CompareEvents);
579}
580
581void EventLoop::RemoveEvent(EventLoopEvent *event) {
582 auto e = std::find(events_.begin(), events_.end(), event);
583 if (e != events_.end()) {
Brian Silvermanbd405c02020-06-23 16:25:23 -0700584 DCHECK(event->generation() != 0);
Austin Schuh7d87b672019-12-01 20:23:49 -0800585 events_.erase(e);
586 std::make_heap(events_.begin(), events_.end(), CompareEvents);
587 event->Invalidate();
588 }
589}
590
591EventLoopEvent *EventLoop::PopEvent() {
592 EventLoopEvent *result = events_.front();
593 std::pop_heap(events_.begin(), events_.end(), CompareEvents);
594 events_.pop_back();
595 result->Invalidate();
596 return result;
597}
598
Austin Schuh0debde12022-08-17 16:25:17 -0700599void EventLoop::ClearContext() {
600 context_.monotonic_event_time = monotonic_clock::min_time;
601 context_.monotonic_remote_time = monotonic_clock::min_time;
602 context_.realtime_event_time = realtime_clock::min_time;
603 context_.realtime_remote_time = realtime_clock::min_time;
604 context_.queue_index = 0xffffffffu;
605 context_.remote_queue_index = 0xffffffffu;
606 context_.size = 0u;
607 context_.data = nullptr;
608 context_.buffer_index = -1;
609 context_.source_boot_uuid = boot_uuid();
610}
611
Austin Schuha9012be2021-07-21 15:19:11 -0700612void EventLoop::SetTimerContext(
613 monotonic_clock::time_point monotonic_event_time) {
614 context_.monotonic_event_time = monotonic_event_time;
615 context_.monotonic_remote_time = monotonic_clock::min_time;
616 context_.realtime_event_time = realtime_clock::min_time;
617 context_.realtime_remote_time = realtime_clock::min_time;
618 context_.queue_index = 0xffffffffu;
Austin Schuh0debde12022-08-17 16:25:17 -0700619 context_.remote_queue_index = 0xffffffffu;
Austin Schuha9012be2021-07-21 15:19:11 -0700620 context_.size = 0u;
621 context_.data = nullptr;
622 context_.buffer_index = -1;
623 context_.source_boot_uuid = boot_uuid();
624}
625
Austin Schuh070019a2022-12-20 22:23:09 -0800626cpu_set_t EventLoop::DefaultAffinity() { return aos::DefaultAffinity(); }
627
Austin Schuh39788ff2019-12-01 18:22:57 -0800628void WatcherState::set_timing_report(timing::Watcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800629 watcher_ = watcher;
Brian Silvermanbf889922021-11-10 12:41:57 -0800630 if (!watcher) {
631 wakeup_latency_.set_statistic(nullptr);
632 handler_time_.set_statistic(nullptr);
633 } else {
634 wakeup_latency_.set_statistic(watcher->mutable_wakeup_latency());
635 handler_time_.set_statistic(watcher->mutable_handler_time());
636 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800637}
638
639void WatcherState::ResetReport() {
Brian Silvermanbf889922021-11-10 12:41:57 -0800640 if (!watcher_) {
641 return;
642 }
643
Austin Schuh39788ff2019-12-01 18:22:57 -0800644 wakeup_latency_.Reset();
645 handler_time_.Reset();
646 watcher_->mutate_count(0);
Austin Schuh54cf95f2019-11-29 13:14:18 -0800647}
648
649} // namespace aos