blob: e1e25168a2b6f8249e8b9faf3df82063c7130c20 [file] [log] [blame]
Austin Schuh20b2b082019-09-11 20:42:56 -07001#include "aos/ipc_lib/lockless_queue.h"
2
3#include <inttypes.h>
4#include <signal.h>
5#include <unistd.h>
6#include <wait.h>
7#include <chrono>
8#include <memory>
9#include <random>
10#include <thread>
11
12#include "aos/event.h"
13#include "aos/events/epoll.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070014#include "aos/ipc_lib/aos_sync.h"
15#include "aos/ipc_lib/queue_racer.h"
16#include "aos/ipc_lib/signalfd.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070017#include "aos/realtime.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070018#include "gflags/gflags.h"
19#include "gtest/gtest.h"
20
21DEFINE_int32(min_iterations, 100,
22 "Minimum number of stress test iterations to run");
23DEFINE_int32(duration, 5, "Number of seconds to test for");
24DEFINE_int32(print_rate, 60, "Number of seconds between status prints");
25
26// The roboRIO can only handle 10 threads before exploding. Set the default for
27// ARM to 10.
28DEFINE_int32(thread_count,
29#if defined(__ARM_EABI__)
30 10,
31#else
32 100,
33#endif
34 "Number of threads to race");
35
36namespace aos {
37namespace ipc_lib {
38namespace testing {
39
40namespace chrono = ::std::chrono;
41
42class LocklessQueueTest : public ::testing::Test {
43 public:
44 LocklessQueueTest() {
Austin Schuh20b2b082019-09-11 20:42:56 -070045 config_.num_watchers = 10;
46 config_.num_senders = 100;
Brian Silverman177567e2020-08-12 19:51:33 -070047 config_.num_pinners = 5;
Austin Schuh20b2b082019-09-11 20:42:56 -070048 config_.queue_size = 10000;
49 // Exercise the alignment code. This would throw off alignment.
50 config_.message_data_size = 101;
51
52 // Since our backing store is an array of uint64_t for alignment purposes,
53 // normalize by the size.
54 memory_.resize(LocklessQueueMemorySize(config_) / sizeof(uint64_t));
55
56 Reset();
57 }
58
Brian Silvermanfc0d2e82020-08-12 19:58:35 -070059 LocklessQueue queue() {
60 return LocklessQueue(reinterpret_cast<LocklessQueueMemory *>(&(memory_[0])),
61 reinterpret_cast<LocklessQueueMemory *>(&(memory_[0])),
62 config_);
Austin Schuh20b2b082019-09-11 20:42:56 -070063 }
64
Brian Silvermanfc0d2e82020-08-12 19:58:35 -070065 void Reset() { memset(&memory_[0], 0, LocklessQueueMemorySize(config_)); }
Austin Schuh20b2b082019-09-11 20:42:56 -070066
67 // Runs until the signal is received.
68 void RunUntilWakeup(Event *ready, int priority) {
Austin Schuh20b2b082019-09-11 20:42:56 -070069 internal::EPoll epoll;
70 SignalFd signalfd({kWakeupSignal});
71
72 epoll.OnReadable(signalfd.fd(), [&signalfd, &epoll]() {
73 signalfd_siginfo result = signalfd.Read();
74
75 fprintf(stderr, "Got signal: %d\n", result.ssi_signo);
76 epoll.Quit();
77 });
78
Brian Silvermanfc0d2e82020-08-12 19:58:35 -070079 {
80 // Register to be woken up *after* the signalfd is catching the signals.
81 LocklessQueueWatcher watcher =
82 LocklessQueueWatcher::Make(queue(), priority).value();
Austin Schuh20b2b082019-09-11 20:42:56 -070083
Brian Silvermanfc0d2e82020-08-12 19:58:35 -070084 // And signal we are now ready.
85 ready->Set();
Austin Schuh20b2b082019-09-11 20:42:56 -070086
Brian Silvermanfc0d2e82020-08-12 19:58:35 -070087 epoll.Run();
Austin Schuh20b2b082019-09-11 20:42:56 -070088
Brian Silvermanfc0d2e82020-08-12 19:58:35 -070089 // Cleanup, ensuring the watcher is destroyed before the signalfd.
90 }
Austin Schuh20b2b082019-09-11 20:42:56 -070091 epoll.DeleteFd(signalfd.fd());
92 }
93
94 // Use a type with enough alignment that we are guarenteed that everything
95 // will be aligned properly on the target platform.
96 ::std::vector<uint64_t> memory_;
97
98 LocklessQueueConfiguration config_;
99};
100
101typedef LocklessQueueTest LocklessQueueDeathTest;
102
103// Tests that wakeup doesn't do anything if nothing was registered.
104TEST_F(LocklessQueueTest, NoWatcherWakeup) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700105 LocklessQueueWakeUpper wake_upper(queue());
Austin Schuh20b2b082019-09-11 20:42:56 -0700106
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700107 EXPECT_EQ(wake_upper.Wakeup(7), 0);
Austin Schuh20b2b082019-09-11 20:42:56 -0700108}
109
110// Tests that wakeup doesn't do anything if a wakeup was registered and then
111// unregistered.
112TEST_F(LocklessQueueTest, UnregisteredWatcherWakeup) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700113 LocklessQueueWakeUpper wake_upper(queue());
Austin Schuh20b2b082019-09-11 20:42:56 -0700114
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700115 { LocklessQueueWatcher::Make(queue(), 5).value(); }
Austin Schuh20b2b082019-09-11 20:42:56 -0700116
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700117 EXPECT_EQ(wake_upper.Wakeup(7), 0);
Austin Schuh20b2b082019-09-11 20:42:56 -0700118}
119
120// Tests that wakeup doesn't do anything if the thread dies.
121TEST_F(LocklessQueueTest, DiedWatcherWakeup) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700122 LocklessQueueWakeUpper wake_upper(queue());
Austin Schuh20b2b082019-09-11 20:42:56 -0700123
124 ::std::thread([this]() {
125 // Use placement new so the destructor doesn't get run.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700126 ::std::aligned_storage<sizeof(LocklessQueueWatcher),
127 alignof(LocklessQueueWatcher)>::type data;
128 new (&data)
129 LocklessQueueWatcher(LocklessQueueWatcher::Make(queue(), 5).value());
130 })
131 .join();
Austin Schuh20b2b082019-09-11 20:42:56 -0700132
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700133 EXPECT_EQ(wake_upper.Wakeup(7), 0);
Austin Schuh20b2b082019-09-11 20:42:56 -0700134}
135
136struct WatcherState {
137 ::std::thread t;
138 Event ready;
139};
140
141// Tests that too many watchers fails like expected.
142TEST_F(LocklessQueueTest, TooManyWatchers) {
143 // This is going to be a barrel of monkeys.
144 // We need to spin up a bunch of watchers. But, they all need to be in
145 // different threads so they have different tids.
146 ::std::vector<WatcherState> queues;
147 // Reserve num_watchers WatcherState objects so the pointer value doesn't
148 // change out from under us below.
149 queues.reserve(config_.num_watchers);
150
151 // Event used to trigger all the threads to unregister.
152 Event cleanup;
153
154 // Start all the threads.
155 for (size_t i = 0; i < config_.num_watchers; ++i) {
156 queues.emplace_back();
157
158 WatcherState *s = &queues.back();
159 queues.back().t = ::std::thread([this, &cleanup, s]() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700160 LocklessQueueWatcher q = LocklessQueueWatcher::Make(queue(), 0).value();
Austin Schuh20b2b082019-09-11 20:42:56 -0700161
162 // Signal that this thread is ready.
163 s->ready.Set();
164
165 // And wait until we are asked to shut down.
166 cleanup.Wait();
Austin Schuh20b2b082019-09-11 20:42:56 -0700167 });
168 }
169
170 // Wait until all the threads are actually going.
171 for (WatcherState &w : queues) {
172 w.ready.Wait();
173 }
174
175 // Now try to allocate another one. This will fail.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700176 EXPECT_FALSE(LocklessQueueWatcher::Make(queue(), 0));
Austin Schuh20b2b082019-09-11 20:42:56 -0700177
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700178 // Trigger the threads to cleanup their resources, and wait until they are
Austin Schuh20b2b082019-09-11 20:42:56 -0700179 // done.
180 cleanup.Set();
181 for (WatcherState &w : queues) {
182 w.t.join();
183 }
184
185 // We should now be able to allocate a wakeup.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700186 EXPECT_TRUE(LocklessQueueWatcher::Make(queue(), 0));
Austin Schuh20b2b082019-09-11 20:42:56 -0700187}
188
189// Tests that too many watchers dies like expected.
Austin Schuhe516ab02020-05-06 21:37:04 -0700190TEST_F(LocklessQueueTest, TooManySenders) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700191 ::std::vector<LocklessQueueSender> senders;
Austin Schuhe516ab02020-05-06 21:37:04 -0700192 for (size_t i = 0; i < config_.num_senders; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700193 senders.emplace_back(LocklessQueueSender::Make(queue()).value());
Austin Schuhe516ab02020-05-06 21:37:04 -0700194 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700195 EXPECT_FALSE(LocklessQueueSender::Make(queue()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700196}
197
198// Now, start 2 threads and have them receive the signals.
199TEST_F(LocklessQueueTest, WakeUpThreads) {
200 // Confirm that the wakeup signal is in range.
201 EXPECT_LE(kWakeupSignal, SIGRTMAX);
202 EXPECT_GE(kWakeupSignal, SIGRTMIN);
203
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700204 LocklessQueueWakeUpper wake_upper(queue());
Austin Schuh20b2b082019-09-11 20:42:56 -0700205
206 // Event used to make sure the thread is ready before the test starts.
207 Event ready1;
208 Event ready2;
209
210 // Start the thread.
211 ::std::thread t1([this, &ready1]() { RunUntilWakeup(&ready1, 5); });
212 ::std::thread t2([this, &ready2]() { RunUntilWakeup(&ready2, 4); });
213
214 ready1.Wait();
215 ready2.Wait();
216
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700217 EXPECT_EQ(wake_upper.Wakeup(3), 2);
Austin Schuh20b2b082019-09-11 20:42:56 -0700218
219 t1.join();
220 t2.join();
221
222 // Clean up afterwords. We are pretending to be RT when we are really not.
223 // So we will be PI boosted up.
224 UnsetCurrentThreadRealtimePriority();
225}
226
227// Do a simple send test.
228TEST_F(LocklessQueueTest, Send) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700229 LocklessQueueSender sender = LocklessQueueSender::Make(queue()).value();
230 LocklessQueueReader reader(queue());
Austin Schuh20b2b082019-09-11 20:42:56 -0700231
232 // Send enough messages to wrap.
233 for (int i = 0; i < 20000; ++i) {
234 // Confirm that the queue index makes sense given the number of sends.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700235 EXPECT_EQ(reader.LatestIndex().index(),
236 i == 0 ? QueueIndex::Invalid().index() : i - 1);
Austin Schuh20b2b082019-09-11 20:42:56 -0700237
238 // Send a trivial piece of data.
239 char data[100];
240 size_t s = snprintf(data, sizeof(data), "foobar%d", i);
241 sender.Send(data, s);
242
243 // Confirm that the queue index still makes sense. This is easier since the
244 // empty case has been handled.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700245 EXPECT_EQ(reader.LatestIndex().index(), i);
Austin Schuh20b2b082019-09-11 20:42:56 -0700246
247 // Read a result from 5 in the past.
248 ::aos::monotonic_clock::time_point monotonic_sent_time;
249 ::aos::realtime_clock::time_point realtime_sent_time;
Austin Schuhad154822019-12-27 15:45:13 -0800250 ::aos::monotonic_clock::time_point monotonic_remote_time;
251 ::aos::realtime_clock::time_point realtime_remote_time;
252 uint32_t remote_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -0700253 char read_data[1024];
254 size_t length;
255
256 QueueIndex index = QueueIndex::Zero(config_.queue_size);
257 if (i - 5 < 0) {
258 index = index.DecrementBy(5 - i);
259 } else {
260 index = index.IncrementBy(i - 5);
261 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700262 LocklessQueueReader::Result read_result =
263 reader.Read(index.index(), &monotonic_sent_time, &realtime_sent_time,
264 &monotonic_remote_time, &realtime_remote_time,
265 &remote_queue_index, &length, &(read_data[0]));
Austin Schuh20b2b082019-09-11 20:42:56 -0700266
267 // This should either return GOOD, or TOO_OLD if it is before the start of
268 // the queue.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700269 if (read_result != LocklessQueueReader::Result::GOOD) {
270 EXPECT_EQ(read_result, LocklessQueueReader::Result::TOO_OLD);
Austin Schuh20b2b082019-09-11 20:42:56 -0700271 }
272 }
273}
274
275// Races a bunch of sending threads to see if it all works.
276TEST_F(LocklessQueueTest, SendRace) {
277 const size_t kNumMessages = 10000 / FLAGS_thread_count;
278
279 ::std::mt19937 generator(0);
280 ::std::uniform_int_distribution<> write_wrap_count_distribution(0, 10);
281 ::std::bernoulli_distribution race_reads_distribution;
282 ::std::bernoulli_distribution wrap_writes_distribution;
283
284 const chrono::seconds print_frequency(FLAGS_print_rate);
285
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700286 QueueRacer racer(queue(), FLAGS_thread_count, kNumMessages);
287 const monotonic_clock::time_point start_time = monotonic_clock::now();
Austin Schuh20b2b082019-09-11 20:42:56 -0700288 const monotonic_clock::time_point end_time =
289 start_time + chrono::seconds(FLAGS_duration);
290
291 monotonic_clock::time_point monotonic_now = start_time;
292 monotonic_clock::time_point next_print_time = start_time + print_frequency;
293 uint64_t messages = 0;
294 for (int i = 0; i < FLAGS_min_iterations || monotonic_now < end_time; ++i) {
295 bool race_reads = race_reads_distribution(generator);
296 int write_wrap_count = write_wrap_count_distribution(generator);
297 if (!wrap_writes_distribution(generator)) {
298 write_wrap_count = 0;
299 }
300 EXPECT_NO_FATAL_FAILURE(racer.RunIteration(race_reads, write_wrap_count))
301 << ": Running with race_reads: " << race_reads
302 << ", and write_wrap_count " << write_wrap_count << " and on iteration "
303 << i;
304
305 messages += racer.CurrentIndex();
306
307 monotonic_now = monotonic_clock::now();
308 if (monotonic_now > next_print_time) {
309 double elapsed_seconds = chrono::duration_cast<chrono::duration<double>>(
310 monotonic_now - start_time)
311 .count();
312 printf("Finished iteration %d, %f iterations/sec, %f messages/second\n",
313 i, i / elapsed_seconds,
314 static_cast<double>(messages) / elapsed_seconds);
315 next_print_time = monotonic_now + print_frequency;
316 }
317 }
318}
319
320// Send enough messages to wrap the 32 bit send counter.
321TEST_F(LocklessQueueTest, WrappedSend) {
322 uint64_t kNumMessages = 0x100010000ul;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700323 QueueRacer racer(queue(), 1, kNumMessages);
Austin Schuh20b2b082019-09-11 20:42:56 -0700324
325 const monotonic_clock::time_point start_time = monotonic_clock::now();
326 EXPECT_NO_FATAL_FAILURE(racer.RunIteration(false, 0));
327 const monotonic_clock::time_point monotonic_now = monotonic_clock::now();
328 double elapsed_seconds = chrono::duration_cast<chrono::duration<double>>(
329 monotonic_now - start_time)
330 .count();
331 printf("Took %f seconds to write %" PRIu64 " messages, %f messages/s\n",
332 elapsed_seconds, kNumMessages,
333 static_cast<double>(kNumMessages) / elapsed_seconds);
334}
335
336} // namespace testing
337} // namespace ipc_lib
338} // namespace aos