blob: 8774c733226a256f7143252bb78cab4cf3b45c4f [file] [log] [blame]
Brian Silvermane4d8b282015-12-24 13:44:48 -08001#include "third_party/gflags/include/gflags/gflags.h"
2
Austin Schuhf2a50ba2016-12-24 16:16:26 -08003#include <fcntl.h>
4#include <mqueue.h>
Brian Silvermane4d8b282015-12-24 13:44:48 -08005#include <netinet/in.h>
Brian Silvermanfd788882016-09-10 16:56:20 -04006#include <netinet/tcp.h>
Austin Schuhf2a50ba2016-12-24 16:16:26 -08007#include <pthread.h>
8#include <semaphore.h>
9#include <stdint.h>
10#include <sys/eventfd.h>
Brian Silvermane4d8b282015-12-24 13:44:48 -080011#include <sys/msg.h>
12#include <sys/sem.h>
Austin Schuhf2a50ba2016-12-24 16:16:26 -080013#include <sys/socket.h>
14#include <sys/stat.h>
15#include <sys/types.h>
16#include <sys/un.h>
Brian Silvermane4d8b282015-12-24 13:44:48 -080017
Austin Schuhf2a50ba2016-12-24 16:16:26 -080018#include <atomic>
19#include <chrono>
Brian Silvermane4d8b282015-12-24 13:44:48 -080020#include <memory>
21#include <string>
Austin Schuhf2a50ba2016-12-24 16:16:26 -080022#include <thread>
Brian Silvermane4d8b282015-12-24 13:44:48 -080023
John Park33858a32018-09-28 23:05:48 -070024#include "aos/condition.h"
25#include "aos/event.h"
26#include "aos/logging/implementations.h"
27#include "aos/logging/logging.h"
28#include "aos/mutex/mutex.h"
29#include "aos/time/time.h"
John Park398c74a2018-10-20 21:17:39 -070030#include "aos/init.h"
31#include "aos/ipc_lib/queue.h"
Brian Silvermane4d8b282015-12-24 13:44:48 -080032
33DEFINE_string(method, "", "Which IPC method to use");
34DEFINE_int32(messages, 1000000, "How many messages to send back and forth");
35DEFINE_int32(client_cpu, 0, "CPU to pin client to");
36DEFINE_int32(server_cpu, 0, "CPU to pin server to");
37DEFINE_int32(client_priority, 1,
38 "Realtime priority for client. Negative for don't change");
39DEFINE_int32(server_priority, 1,
40 "Realtime priority for server. Negative for don't change");
41
42namespace aos {
43
Austin Schuhf2a50ba2016-12-24 16:16:26 -080044namespace chrono = ::std::chrono;
45
Brian Silvermane4d8b282015-12-24 13:44:48 -080046// A generic interface for an object which can send some data to another thread
47// and back.
48//
49// One side is called the "server". It should constantly Wait, do something with
50// the result, and then call Pong.
51// The other side is called the "client". It should repeatedly call Ping.
52class PingPongerInterface {
53 public:
54 // A chunk of memory definitely on its own cache line anywhere sane.
55 typedef uint8_t Data[1024] __attribute__((aligned(128)));
56
57 virtual ~PingPongerInterface() {}
58
59 // Returns where the "client" side should write data in preparation to send to
60 // the server.
61 // The result is valid until the next Ping call.
62 virtual Data *PingData() = 0;
63
64 // Sends the data returned from the most recent PingData call to the "server"
65 // side and returns its response.
66 // PingData must be called exactly once before each call of this method.
67 // The result is valid until the next PingData call.
68 virtual const Data *Ping() = 0;
69
70 // Waits for a Ping call and then returns the associated data.
71 // The result is valid until the beginning of the next Pong call.
72 virtual const Data *Wait() = 0;
73
74 // Returns where the "server" side should write data in preparation to send
75 // back to the "client".
76 // The result is valid until the next Pong call.
77 virtual Data *PongData() = 0;
78
79 // Sends data back to an in-progress Ping.
80 // Sends the data returned from the most recent PongData call back to an
81 // in-progress Ping.
82 // PongData must be called exactly once before each call of this method.
83 virtual void Pong() = 0;
84};
85
86// Base class for implementations which simple use a pair of Data objects for
87// all Pings and Pongs.
88class StaticPingPonger : public PingPongerInterface {
89 public:
90 Data *PingData() override { return &ping_data_; }
91 Data *PongData() override { return &pong_data_; }
92
93 private:
94 Data ping_data_, pong_data_;
95};
96
97// Implements ping-pong by sending the data over file descriptors.
98class FDPingPonger : public StaticPingPonger {
99 protected:
100 // Subclasses must override and call Init.
101 FDPingPonger() {}
102
103 // Subclasses must call this in their constructor.
104 // Does not take ownership of any of the file descriptors, any/all of which
105 // may be the same.
106 // {server,client}_read must be open for reading and {server,client}_write
107 // must be open for writing.
108 void Init(int server_read, int server_write, int client_read,
109 int client_write) {
110 server_read_ = server_read;
111 server_write_ = server_write;
112 client_read_ = client_read;
113 client_write_ = client_write;
114 }
115
116 private:
117 const Data *Ping() override {
118 WriteFully(client_write_, *PingData());
119 ReadFully(client_read_, &read_by_client_);
120 return &read_by_client_;
121 }
122
123 const Data *Wait() override {
124 ReadFully(server_read_, &read_by_server_);
125 return &read_by_server_;
126 }
127
128 void Pong() override { WriteFully(server_write_, *PongData()); }
129
130 void ReadFully(int fd, Data *data) {
131 size_t remaining = sizeof(*data);
132 uint8_t *current = &(*data)[0];
133 while (remaining > 0) {
134 const ssize_t result = PCHECK(read(fd, current, remaining));
135 CHECK_LE(static_cast<size_t>(result), remaining);
136 remaining -= result;
137 current += result;
138 }
139 }
140
141 void WriteFully(int fd, const Data &data) {
142 size_t remaining = sizeof(data);
143 const uint8_t *current = &data[0];
144 while (remaining > 0) {
145 const ssize_t result = PCHECK(write(fd, current, remaining));
146 CHECK_LE(static_cast<size_t>(result), remaining);
147 remaining -= result;
148 current += result;
149 }
150 }
151
152 Data read_by_client_, read_by_server_;
153 int server_read_ = -1, server_write_ = -1, client_read_ = -1,
154 client_write_ = -1;
155};
156
157class PipePingPonger : public FDPingPonger {
158 public:
159 PipePingPonger() {
160 PCHECK(pipe(to_server));
161 PCHECK(pipe(from_server));
162 Init(to_server[0], from_server[1], from_server[0], to_server[1]);
163 }
164 ~PipePingPonger() {
165 PCHECK(close(to_server[0]));
166 PCHECK(close(to_server[1]));
167 PCHECK(close(from_server[0]));
168 PCHECK(close(from_server[1]));
169 }
170
171 private:
172 int to_server[2], from_server[2];
173};
174
175class NamedPipePingPonger : public FDPingPonger {
176 public:
177 NamedPipePingPonger() {
178 OpenFifo("/tmp/to_server", &client_write_, &server_read_);
179 OpenFifo("/tmp/from_server", &server_write_, &client_read_);
180
181 Init(server_read_, server_write_, client_read_, client_write_);
182 }
183 ~NamedPipePingPonger() {
184 PCHECK(close(server_read_));
185 PCHECK(close(client_write_));
186 PCHECK(close(client_read_));
187 PCHECK(close(server_write_));
188 }
189
190 private:
191 void OpenFifo(const char *name, int *write, int *read) {
192 {
193 const int ret = unlink(name);
194 if (ret == -1 && errno != ENOENT) {
195 PLOG(FATAL, "unlink(%s)", name);
196 }
197 PCHECK(mkfifo(name, S_IWUSR | S_IRUSR));
198 // Have to open it nonblocking because the other end isn't open yet...
199 *read = PCHECK(open(name, O_RDONLY | O_NONBLOCK));
200 *write = PCHECK(open(name, O_WRONLY));
201 {
202 const int flags = PCHECK(fcntl(*read, F_GETFL));
203 PCHECK(fcntl(*read, F_SETFL, flags & ~O_NONBLOCK));
204 }
205 }
206 }
207
208 int server_read_, server_write_, client_read_, client_write_;
209};
210
211class UnixPingPonger : public FDPingPonger {
212 public:
213 UnixPingPonger(int type) {
214 PCHECK(socketpair(AF_UNIX, type, 0, to_server));
215 PCHECK(socketpair(AF_UNIX, type, 0, from_server));
216 Init(to_server[0], from_server[1], from_server[0], to_server[1]);
217 }
218 ~UnixPingPonger() {
219 PCHECK(close(to_server[0]));
220 PCHECK(close(to_server[1]));
221 PCHECK(close(from_server[0]));
222 PCHECK(close(from_server[1]));
223 }
224
225 private:
226 int to_server[2], from_server[2];
227};
228
229class TCPPingPonger : public FDPingPonger {
230 public:
Brian Silvermanfd788882016-09-10 16:56:20 -0400231 TCPPingPonger(bool nodelay) {
Brian Silvermane4d8b282015-12-24 13:44:48 -0800232 server_ = PCHECK(socket(AF_INET, SOCK_STREAM, 0));
Brian Silvermanfd788882016-09-10 16:56:20 -0400233 if (nodelay) {
234 const int yes = 1;
235 PCHECK(setsockopt(server_, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)));
236 }
Brian Silvermane4d8b282015-12-24 13:44:48 -0800237 {
238 sockaddr_in server_address;
239 memset(&server_address, 0, sizeof(server_address));
240 server_address.sin_family = AF_INET;
241 server_address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
242 PCHECK(bind(server_, reinterpret_cast<sockaddr *>(&server_address),
243 sizeof(server_address)));
244 }
245 PCHECK(listen(server_, 1));
246
247 client_ = PCHECK(socket(AF_INET, SOCK_STREAM, 0));
Brian Silvermanfd788882016-09-10 16:56:20 -0400248 if (nodelay) {
249 const int yes = 1;
250 PCHECK(setsockopt(client_, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)));
251 }
Brian Silvermane4d8b282015-12-24 13:44:48 -0800252 {
253 sockaddr_in client_address;
254 unsigned int length = sizeof(client_address);
255 PCHECK(getsockname(server_, reinterpret_cast<sockaddr *>(&client_address),
256 &length));
257 PCHECK(connect(client_, reinterpret_cast<sockaddr *>(&client_address),
258 length));
259 }
260 server_connection_ = PCHECK(accept(server_, nullptr, 0));
261
262 Init(server_connection_, server_connection_, client_, client_);
263 }
264 ~TCPPingPonger() {
265 PCHECK(close(client_));
266 PCHECK(close(server_connection_));
267 PCHECK(close(server_));
268 }
269
270 private:
271 int server_, client_, server_connection_;
272};
273
274class UDPPingPonger : public FDPingPonger {
275 public:
276 UDPPingPonger() {
277 CreatePair(&server_read_, &client_write_);
278 CreatePair(&client_read_, &server_write_);
279
280 Init(server_read_, server_write_, client_read_, client_write_);
281 }
282 ~UDPPingPonger() {
283 PCHECK(close(server_read_));
284 PCHECK(close(client_write_));
285 PCHECK(close(client_read_));
286 PCHECK(close(server_write_));
287 }
288
289 private:
290 void CreatePair(int *server, int *client) {
291 *server = PCHECK(socket(AF_INET, SOCK_DGRAM, 0));
292 {
293 sockaddr_in server_address;
294 memset(&server_address, 0, sizeof(server_address));
295 server_address.sin_family = AF_INET;
296 server_address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
297 // server_address.sin_port = htons(server_ + 3000);
298 PCHECK(bind(*server, reinterpret_cast<sockaddr *>(&server_address),
299 sizeof(server_address)));
300 }
301 *client = PCHECK(socket(AF_INET, SOCK_DGRAM, 0));
302 {
303 sockaddr_in client_address;
304 unsigned int length = sizeof(client_address);
305 PCHECK(getsockname(*server, reinterpret_cast<sockaddr *>(&client_address),
306 &length));
307 PCHECK(connect(*client, reinterpret_cast<sockaddr *>(&client_address),
308 length));
309 }
310 }
311
312 int server_read_, server_write_, client_read_, client_write_;
313};
314
315// Implements ping-pong without copying the data using a condition variable-like
316// interface.
317class ConditionVariablePingPonger : public StaticPingPonger {
318 protected:
319 // Represents a condition variable bundled with a mutex.
320 //
321 // Wait may return spuriously.
322 class ConditionVariableInterface {
323 public:
324 virtual ~ConditionVariableInterface() {}
325
326 // Locks the mutex.
327 virtual void Lock() = 0;
328
329 // Unlocks the mutex.
330 virtual void Unlock() = 0;
331
332 // Waits on the condition variable.
333 //
334 // The mutex must be locked when this is called.
335 virtual void Wait() = 0;
336
337 // Signals the condition variable.
338 //
339 // The mutex does not have to be locked during this.
340 virtual void Signal() = 0;
341 };
342
343 ConditionVariablePingPonger(
344 ::std::unique_ptr<ConditionVariableInterface> ping,
345 ::std::unique_ptr<ConditionVariableInterface> pong)
346 : ping_(::std::move(ping)), pong_(::std::move(pong)) {}
347
348 private:
349 const Data *Ping() override {
350 ping_->Lock();
351 to_server_ = PingData();
352 ping_->Unlock();
353 ping_->Signal();
354 pong_->Lock();
355 while (from_server_ == nullptr) {
356 pong_->Wait();
357 }
358 const Data *r = from_server_;
359 from_server_ = nullptr;
360 pong_->Unlock();
361 return r;
362 }
363
364 const Data *Wait() override {
365 ping_->Lock();
366 while (to_server_ == nullptr) {
367 ping_->Wait();
368 }
369 const Data *r = to_server_;
370 to_server_ = nullptr;
371 ping_->Unlock();
372 return r;
373 }
374
375 void Pong() override {
376 pong_->Lock();
377 from_server_ = PongData();
378 pong_->Unlock();
379 pong_->Signal();
380 }
381
382 const Data *to_server_ = nullptr, *from_server_ = nullptr;
383 const ::std::unique_ptr<ConditionVariableInterface> ping_, pong_;
384};
385
386// Implements ping-pong without copying the data using a semaphore-like
387// interface.
388class SemaphorePingPonger : public StaticPingPonger {
389 protected:
390 // Represents a semaphore, which need only count to 1.
391 //
392 // The behavior when calling Get/Put in anything other than alternating order
393 // is undefined.
394 //
395 // Wait may NOT return spuriously.
396 class SemaphoreInterface {
397 public:
398 virtual ~SemaphoreInterface() {}
399
400 virtual void Get() = 0;
401 virtual void Put() = 0;
402 };
403
404 SemaphorePingPonger(::std::unique_ptr<SemaphoreInterface> ping,
405 ::std::unique_ptr<SemaphoreInterface> pong)
406 : ping_(::std::move(ping)), pong_(::std::move(pong)) {}
407
408 private:
409 const Data *Ping() override {
410 to_server_ = PingData();
411 ping_->Put();
412 pong_->Get();
413 return from_server_;
414 }
415
416 const Data *Wait() override {
417 ping_->Get();
418 return to_server_;
419 }
420
421 void Pong() override {
422 from_server_ = PongData();
423 pong_->Put();
424 }
425
426 const Data *to_server_ = nullptr, *from_server_ = nullptr;
427 const ::std::unique_ptr<SemaphoreInterface> ping_, pong_;
428};
429
430
431class AOSMutexPingPonger : public ConditionVariablePingPonger {
432 public:
433 AOSMutexPingPonger()
434 : ConditionVariablePingPonger(
435 ::std::unique_ptr<ConditionVariableInterface>(
436 new AOSConditionVariable()),
437 ::std::unique_ptr<ConditionVariableInterface>(
438 new AOSConditionVariable())) {}
439
440 private:
441 class AOSConditionVariable : public ConditionVariableInterface {
442 public:
443 AOSConditionVariable() : condition_(&mutex_) {}
444
445 private:
446 void Lock() override { CHECK(!mutex_.Lock()); }
447 void Unlock() override { mutex_.Unlock(); }
448 void Wait() override { CHECK(!condition_.Wait()); }
449 void Signal() override { condition_.Broadcast(); }
450
451 Mutex mutex_;
452 Condition condition_;
453 };
454};
455
456class AOSEventPingPonger : public SemaphorePingPonger {
457 public:
458 AOSEventPingPonger()
459 : SemaphorePingPonger(
460 ::std::unique_ptr<SemaphoreInterface>(
461 new AOSEventSemaphore()),
462 ::std::unique_ptr<SemaphoreInterface>(
463 new AOSEventSemaphore())) {}
464
465 private:
466 class AOSEventSemaphore : public SemaphoreInterface {
467 private:
468 void Get() override {
469 event_.Wait();
470 event_.Clear();
471 }
472 void Put() override { event_.Set(); }
473
474 Event event_;
475 };
476};
477
478class PthreadMutexPingPonger : public ConditionVariablePingPonger {
479 public:
Brian Silvermanfd788882016-09-10 16:56:20 -0400480 PthreadMutexPingPonger(int pshared, bool pi)
Brian Silvermane4d8b282015-12-24 13:44:48 -0800481 : ConditionVariablePingPonger(
482 ::std::unique_ptr<ConditionVariableInterface>(
Brian Silvermanfd788882016-09-10 16:56:20 -0400483 new PthreadConditionVariable(pshared, pi)),
Brian Silvermane4d8b282015-12-24 13:44:48 -0800484 ::std::unique_ptr<ConditionVariableInterface>(
Brian Silvermanfd788882016-09-10 16:56:20 -0400485 new PthreadConditionVariable(pshared, pi))) {}
Brian Silvermane4d8b282015-12-24 13:44:48 -0800486
487 private:
488 class PthreadConditionVariable : public ConditionVariableInterface {
489 public:
Brian Silvermanfd788882016-09-10 16:56:20 -0400490 PthreadConditionVariable(bool pshared, bool pi) {
491 {
492 pthread_condattr_t cond_attr;
493 PRCHECK(pthread_condattr_init(&cond_attr));
494 if (pshared) {
495 PRCHECK(
496 pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED));
497 }
498 PRCHECK(pthread_cond_init(&condition_, &cond_attr));
499 PRCHECK(pthread_condattr_destroy(&cond_attr));
500 }
501
502 {
503 pthread_mutexattr_t mutex_attr;
504 PRCHECK(pthread_mutexattr_init(&mutex_attr));
505 if (pshared) {
506 PRCHECK(pthread_mutexattr_setpshared(&mutex_attr,
507 PTHREAD_PROCESS_SHARED));
508 }
509 if (pi) {
510 PRCHECK(
511 pthread_mutexattr_setprotocol(&mutex_attr, PTHREAD_PRIO_INHERIT));
512 }
513 PRCHECK(pthread_mutex_init(&mutex_, nullptr));
514 PRCHECK(pthread_mutexattr_destroy(&mutex_attr));
515 }
Brian Silvermane4d8b282015-12-24 13:44:48 -0800516 }
517 ~PthreadConditionVariable() {
518 PRCHECK(pthread_mutex_destroy(&mutex_));
519 PRCHECK(pthread_cond_destroy(&condition_));
520 }
521
522 private:
523 void Lock() override { PRCHECK(pthread_mutex_lock(&mutex_)); }
524 void Unlock() override { PRCHECK(pthread_mutex_unlock(&mutex_)); }
525 void Wait() override { PRCHECK(pthread_cond_wait(&condition_, &mutex_)); }
526 void Signal() override { PRCHECK(pthread_cond_broadcast(&condition_)); }
527
528 pthread_cond_t condition_;
529 pthread_mutex_t mutex_;
530 };
531};
532
533class EventFDPingPonger : public SemaphorePingPonger {
534 public:
535 EventFDPingPonger()
536 : SemaphorePingPonger(
537 ::std::unique_ptr<SemaphoreInterface>(new EventFDSemaphore()),
538 ::std::unique_ptr<SemaphoreInterface>(new EventFDSemaphore())) {}
539
540 private:
541 class EventFDSemaphore : public SemaphoreInterface {
542 public:
543 EventFDSemaphore() : fd_(PCHECK(eventfd(0, 0))) {}
544 ~EventFDSemaphore() { PCHECK(close(fd_)); }
545
546 private:
547 void Get() override {
548 uint64_t value;
549 if (read(fd_, &value, sizeof(value)) != sizeof(value)) {
550 PLOG(FATAL, "reading from eventfd %d failed\n", fd_);
551 }
552 CHECK_EQ(1u, value);
553 }
554 void Put() override {
555 uint64_t value = 1;
556 if (write(fd_, &value, sizeof(value)) != sizeof(value)) {
557 PLOG(FATAL, "writing to eventfd %d failed\n", fd_);
558 }
559 }
560
561 const int fd_;
562 };
563};
564
565class SysvSemaphorePingPonger : public SemaphorePingPonger {
566 public:
567 SysvSemaphorePingPonger()
568 : SemaphorePingPonger(
569 ::std::unique_ptr<SemaphoreInterface>(new SysvSemaphore()),
570 ::std::unique_ptr<SemaphoreInterface>(new SysvSemaphore())) {}
571
572 private:
573 class SysvSemaphore : public SemaphoreInterface {
574 public:
575 SysvSemaphore()
576 : sem_id_(PCHECK(semget(IPC_PRIVATE, 1, 0600))) {}
577
578 private:
579 void Get() override {
580 struct sembuf op;
581 op.sem_num = 0;
582 op.sem_op = -1;
583 op.sem_flg = 0;
584 PCHECK(semop(sem_id_, &op, 1));
585 }
586 void Put() override {
587 struct sembuf op;
588 op.sem_num = 0;
589 op.sem_op = 1;
590 op.sem_flg = 0;
591 PCHECK(semop(sem_id_, &op, 1));
592 }
593
594 const int sem_id_;
595 };
596};
597
598class PosixSemaphorePingPonger : public SemaphorePingPonger {
599 protected:
600 PosixSemaphorePingPonger(sem_t *ping_sem, sem_t *pong_sem)
601 : SemaphorePingPonger(
602 ::std::unique_ptr<SemaphoreInterface>(new PosixSemaphore(ping_sem)),
603 ::std::unique_ptr<SemaphoreInterface>(
604 new PosixSemaphore(pong_sem))) {}
605
606 private:
607 class PosixSemaphore : public SemaphoreInterface {
608 public:
609 PosixSemaphore(sem_t *sem)
610 : sem_(sem) {}
611
612 private:
613 void Get() override { PCHECK(sem_wait(sem_)); }
614 void Put() override { PCHECK(sem_post(sem_)); }
615
616 sem_t *const sem_;
617 };
618};
619
620class SysvQueuePingPonger : public StaticPingPonger {
621 public:
622 SysvQueuePingPonger()
623 : ping_(PCHECK(msgget(IPC_PRIVATE, 0600))),
624 pong_(PCHECK(msgget(IPC_PRIVATE, 0600))) {}
625
626 const Data *Ping() override {
627 {
628 Message to_send;
629 memcpy(&to_send.data, PingData(), sizeof(Data));
630 PCHECK(msgsnd(ping_, &to_send, sizeof(Data), 0));
631 }
632 {
633 Message received;
634 PCHECK(msgrcv(pong_, &received, sizeof(Data), 1, 0));
635 memcpy(&pong_received_, &received.data, sizeof(Data));
636 }
637 return &pong_received_;
638 }
639
640 const Data *Wait() override {
641 {
642 Message received;
643 PCHECK(msgrcv(ping_, &received, sizeof(Data), 1, 0));
644 memcpy(&ping_received_, &received.data, sizeof(Data));
645 }
646 return &ping_received_;
647 }
648
649 virtual void Pong() override {
650 Message to_send;
651 memcpy(&to_send.data, PongData(), sizeof(Data));
652 PCHECK(msgsnd(pong_, &to_send, sizeof(Data), 0));
653 }
654
655 private:
656 struct Message {
657 long mtype = 1;
658 char data[sizeof(Data)];
659 };
660
661 Data ping_received_, pong_received_;
662
663 const int ping_, pong_;
664};
665
666class PosixQueuePingPonger : public StaticPingPonger {
667 public:
668 PosixQueuePingPonger() : ping_(Open("/ping")), pong_(Open("/pong")) {}
669 ~PosixQueuePingPonger() {
670 PCHECK(mq_close(ping_));
671 PCHECK(mq_close(pong_));
672 }
673
674 const Data *Ping() override {
675 PCHECK(mq_send(ping_, static_cast<char *>(static_cast<void *>(PingData())),
676 sizeof(Data), 1));
677 PCHECK(mq_receive(pong_,
678 static_cast<char *>(static_cast<void *>(&pong_received_)),
679 sizeof(Data), nullptr));
680 return &pong_received_;
681 }
682
683 const Data *Wait() override {
684 PCHECK(mq_receive(ping_,
685 static_cast<char *>(static_cast<void *>(&ping_received_)),
686 sizeof(Data), nullptr));
687 return &ping_received_;
688 }
689
690 virtual void Pong() override {
691 PCHECK(mq_send(pong_, static_cast<char *>(static_cast<void *>(PongData())),
692 sizeof(Data), 1));
693 }
694
695 private:
696 mqd_t Open(const char *name) {
697 if (mq_unlink(name) == -1 && errno != ENOENT) {
698 PLOG(FATAL, "mq_unlink(%s) failed", name);
699 }
700 struct mq_attr attr;
701 attr.mq_flags = 0;
702 attr.mq_maxmsg = 1;
703 attr.mq_msgsize = sizeof(Data);
704 attr.mq_curmsgs = 0;
705 const mqd_t r = mq_open(name, O_CREAT | O_RDWR | O_EXCL, 0600, &attr);
706 if (r == reinterpret_cast<mqd_t>(-1)) {
707 PLOG(FATAL, "mq_open(%s, O_CREAT | O_RDWR | O_EXCL) failed", name);
708 }
709 return r;
710 }
711
712 const mqd_t ping_, pong_;
713 Data ping_received_, pong_received_;
714};
715
716class PosixUnnamedSemaphorePingPonger : public PosixSemaphorePingPonger {
717 public:
718 PosixUnnamedSemaphorePingPonger(int pshared)
719 : PosixSemaphorePingPonger(&ping_sem_, &pong_sem_) {
720 PCHECK(sem_init(&ping_sem_, pshared, 0));
721 PCHECK(sem_init(&pong_sem_, pshared, 0));
722 }
723 ~PosixUnnamedSemaphorePingPonger() {
724 PCHECK(sem_destroy(&ping_sem_));
725 PCHECK(sem_destroy(&pong_sem_));
726 }
727
728 private:
729 sem_t ping_sem_, pong_sem_;
730};
731
732class PosixNamedSemaphorePingPonger : public PosixSemaphorePingPonger {
733 public:
734 PosixNamedSemaphorePingPonger()
735 : PosixSemaphorePingPonger(ping_sem_ = Open("/ping"),
736 pong_sem_ = Open("/pong")) {}
737 ~PosixNamedSemaphorePingPonger() {
738 PCHECK(sem_close(ping_sem_));
739 PCHECK(sem_close(pong_sem_));
740 }
741
742 private:
743 sem_t *Open(const char *name) {
744 if (sem_unlink(name) == -1 && errno != ENOENT) {
745 PLOG(FATAL, "shm_unlink(%s) failed", name);
746 }
747 sem_t *const r = sem_open(name, O_CREAT | O_RDWR | O_EXCL, 0600, 0);
748 if (r == SEM_FAILED) {
749 PLOG(FATAL, "sem_open(%s, O_CREAT | O_RDWR | O_EXCL) failed", name);
750 }
751 return r;
752 }
753
754 sem_t *ping_sem_, *pong_sem_;
755};
756
757class AOSQueuePingPonger : public PingPongerInterface {
758 public:
759 AOSQueuePingPonger()
760 : ping_queue_(RawQueue::Fetch("ping", sizeof(Data), 0, 1)),
761 pong_queue_(RawQueue::Fetch("pong", sizeof(Data), 0, 1)) {}
762
763 Data *PingData() override {
764 CHECK_EQ(nullptr, ping_to_send_);
765 ping_to_send_ = static_cast<Data *>(ping_queue_->GetMessage());
766 return ping_to_send_;
767 }
768
769 const Data *Ping() override {
770 CHECK_NE(nullptr, ping_to_send_);
771 CHECK(ping_queue_->WriteMessage(ping_to_send_, RawQueue::kBlock));
772 ping_to_send_ = nullptr;
773 pong_queue_->FreeMessage(pong_received_);
774 pong_received_ =
775 static_cast<const Data *>(pong_queue_->ReadMessage(RawQueue::kBlock));
776 return pong_received_;
777 }
778
779 const Data *Wait() override {
780 ping_queue_->FreeMessage(ping_received_);
781 ping_received_ =
782 static_cast<const Data *>(ping_queue_->ReadMessage(RawQueue::kBlock));
783 return ping_received_;
784 }
785
786 Data *PongData() override {
787 CHECK_EQ(nullptr, pong_to_send_);
788 pong_to_send_ = static_cast<Data *>(pong_queue_->GetMessage());
789 return pong_to_send_;
790 }
791
792 void Pong() override {
793 CHECK_NE(nullptr, pong_to_send_);
794 CHECK(pong_queue_->WriteMessage(pong_to_send_, RawQueue::kBlock));
795 pong_to_send_ = nullptr;
796 }
797
798 private:
799 RawQueue *const ping_queue_;
800 RawQueue *const pong_queue_;
801
802 Data *ping_to_send_ = nullptr, *pong_to_send_ = nullptr;
803 const Data *ping_received_ = nullptr, *pong_received_ = nullptr;
804};
805
806int Main(int /*argc*/, char **argv) {
807 ::std::unique_ptr<PingPongerInterface> ping_ponger;
808 if (FLAGS_method == "pipe") {
809 ping_ponger.reset(new PipePingPonger());
810 } else if (FLAGS_method == "named_pipe") {
811 ping_ponger.reset(new NamedPipePingPonger());
812 } else if (FLAGS_method == "aos_mutex") {
813 ping_ponger.reset(new AOSMutexPingPonger());
814 } else if (FLAGS_method == "aos_event") {
815 ping_ponger.reset(new AOSEventPingPonger());
816 } else if (FLAGS_method == "pthread_mutex") {
Brian Silvermanfd788882016-09-10 16:56:20 -0400817 ping_ponger.reset(new PthreadMutexPingPonger(false, false));
818 } else if (FLAGS_method == "pthread_mutex_pshared") {
819 ping_ponger.reset(new PthreadMutexPingPonger(true, false));
820 } else if (FLAGS_method == "pthread_mutex_pshared_pi") {
821 ping_ponger.reset(new PthreadMutexPingPonger(true, true));
822 } else if (FLAGS_method == "pthread_mutex_pi") {
823 ping_ponger.reset(new PthreadMutexPingPonger(false, true));
Brian Silvermane4d8b282015-12-24 13:44:48 -0800824 } else if (FLAGS_method == "aos_queue") {
825 ping_ponger.reset(new AOSQueuePingPonger());
826 } else if (FLAGS_method == "eventfd") {
827 ping_ponger.reset(new EventFDPingPonger());
828 } else if (FLAGS_method == "sysv_semaphore") {
829 ping_ponger.reset(new SysvSemaphorePingPonger());
830 } else if (FLAGS_method == "sysv_queue") {
831 ping_ponger.reset(new SysvQueuePingPonger());
832 } else if (FLAGS_method == "posix_semaphore_unnamed_shared") {
833 ping_ponger.reset(new PosixUnnamedSemaphorePingPonger(1));
834 } else if (FLAGS_method == "posix_semaphore_unnamed_unshared") {
835 ping_ponger.reset(new PosixUnnamedSemaphorePingPonger(0));
836 } else if (FLAGS_method == "posix_semaphore_named") {
837 ping_ponger.reset(new PosixNamedSemaphorePingPonger());
838 } else if (FLAGS_method == "posix_queue") {
839 ping_ponger.reset(new PosixQueuePingPonger());
840 } else if (FLAGS_method == "unix_stream") {
841 ping_ponger.reset(new UnixPingPonger(SOCK_STREAM));
842 } else if (FLAGS_method == "unix_datagram") {
843 ping_ponger.reset(new UnixPingPonger(SOCK_DGRAM));
844 } else if (FLAGS_method == "unix_seqpacket") {
845 ping_ponger.reset(new UnixPingPonger(SOCK_SEQPACKET));
846 } else if (FLAGS_method == "tcp") {
Brian Silvermanfd788882016-09-10 16:56:20 -0400847 ping_ponger.reset(new TCPPingPonger(false));
848 } else if (FLAGS_method == "tcp_nodelay") {
849 ping_ponger.reset(new TCPPingPonger(true));
Brian Silvermane4d8b282015-12-24 13:44:48 -0800850 } else if (FLAGS_method == "udp") {
851 ping_ponger.reset(new UDPPingPonger());
852 } else {
853 fprintf(stderr, "Unknown IPC method to test '%s'\n", FLAGS_method.c_str());
854 ::gflags::ShowUsageWithFlags(argv[0]);
855 return 1;
856 }
857
Brian Silverman1d42ce22016-09-10 16:55:40 -0400858 ::std::atomic<bool> done{false};
Brian Silvermane4d8b282015-12-24 13:44:48 -0800859
860 ::std::thread server([&ping_ponger, &done]() {
861 if (FLAGS_server_priority > 0) {
862 SetCurrentThreadRealtimePriority(FLAGS_server_priority);
863 }
864 PinCurrentThreadToCPU(FLAGS_server_cpu);
865
866 while (!done) {
867 const PingPongerInterface::Data *data = ping_ponger->Wait();
868 PingPongerInterface::Data *response = ping_ponger->PongData();
869 for (size_t i = 0; i < sizeof(*data); ++i) {
870 (*response)[i] = (*data)[i] + 1;
871 }
872 ping_ponger->Pong();
873 }
874 });
875
876 if (FLAGS_client_priority > 0) {
877 SetCurrentThreadRealtimePriority(FLAGS_client_priority);
878 }
879 PinCurrentThreadToCPU(FLAGS_client_cpu);
880
881 // Warm everything up.
882 for (int i = 0; i < 1000; ++i) {
883 PingPongerInterface::Data *warmup_data = ping_ponger->PingData();
884 memset(*warmup_data, i % 255, sizeof(*warmup_data));
885 ping_ponger->Ping();
886 }
887
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800888 const monotonic_clock::time_point start = monotonic_clock::now();
Brian Silvermane4d8b282015-12-24 13:44:48 -0800889
890 for (int32_t i = 0; i < FLAGS_messages; ++i) {
891 PingPongerInterface::Data *to_send = ping_ponger->PingData();
892 memset(*to_send, i % 123, sizeof(*to_send));
893 const PingPongerInterface::Data *received = ping_ponger->Ping();
894 for (size_t ii = 0; ii < sizeof(*received); ++ii) {
895 CHECK_EQ(((i % 123) + 1) % 255, (*received)[ii]);
896 }
897 }
898
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800899 const monotonic_clock::time_point end = monotonic_clock::now();
Brian Silvermane4d8b282015-12-24 13:44:48 -0800900
Brian Silverman1d42ce22016-09-10 16:55:40 -0400901 // Try to make sure the server thread gets past its check of done so our
902 // Ping() down below doesn't hang. Kind of lame, but doing better would
903 // require complicating the interface to each implementation which isn't worth
904 // it here.
905 ::std::this_thread::sleep_for(::std::chrono::milliseconds(200));
Brian Silvermane4d8b282015-12-24 13:44:48 -0800906 done = true;
907 ping_ponger->PingData();
908 ping_ponger->Ping();
909 server.join();
910
911 LOG(INFO, "Took %f seconds to send %" PRId32 " messages\n",
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800912 chrono::duration_cast<chrono::duration<double>>(end - start).count(),
913 FLAGS_messages);
914 const chrono::nanoseconds per_message = (end - start) / FLAGS_messages;
915 if (per_message >= chrono::seconds(1)) {
Brian Silvermane4d8b282015-12-24 13:44:48 -0800916 LOG(INFO, "More than 1 second per message ?!?\n");
917 } else {
918 LOG(INFO, "That is %" PRId32 " nanoseconds per message\n",
Austin Schuhf2a50ba2016-12-24 16:16:26 -0800919 static_cast<int>(per_message.count()));
Brian Silvermane4d8b282015-12-24 13:44:48 -0800920 }
921
922 return 0;
923}
924
925} // namespace aos
926
927int main(int argc, char **argv) {
928 ::gflags::SetUsageMessage(
929 ::std::string("Compares various forms of IPC. Usage:\n") + argv[0] +
930 " --method=METHOD\n"
931 "METHOD can be one of the following:\n"
932 "\tpipe\n"
933 "\tnamed_pipe\n"
934 "\taos_mutex\n"
935 "\taos_event\n"
936 "\tpthread_mutex\n"
Brian Silvermanfd788882016-09-10 16:56:20 -0400937 "\tpthread_mutex_pshared\n"
938 "\tpthread_mutex_pshared_pi\n"
939 "\tpthread_mutex_pi\n"
Brian Silvermane4d8b282015-12-24 13:44:48 -0800940 "\taos_queue\n"
941 "\teventfd\n"
942 "\tsysv_semaphore\n"
943 "\tsysv_queue\n"
944 "\tposix_semaphore_unnamed_shared\n"
945 "\tposix_semaphore_unnamed_unshared\n"
946 "\tposix_semaphore_named\n"
947 "\tposix_queue\n"
948 "\tunix_stream\n"
949 "\tunix_datagram\n"
950 "\tunix_seqpacket\n"
951 "\ttcp\n"
Brian Silvermanfd788882016-09-10 16:56:20 -0400952 "\ttcp_nodelay\n"
Brian Silvermane4d8b282015-12-24 13:44:48 -0800953 "\tudp\n");
954 ::gflags::ParseCommandLineFlags(&argc, &argv, true);
955
956 ::aos::InitNRT();
957 ::aos::logging::AddImplementation(
958 new ::aos::logging::StreamLogImplementation(stdout));
959
960 return ::aos::Main(argc, argv);
961}