Debian Codegraph @

src/pmqtest/pmqtest.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * pmqtest.c
4 *
5 * Copyright (C) 2009 Carsten Emde <[email protected]>
6 */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <limits.h>
12 #include <fcntl.h>
13 #include <getopt.h>
14 #include <signal.h>
15 #include <string.h>
16 #include <time.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 #include <sys/mman.h>
21 #include <linux/unistd.h>
22 #include <utmpx.h>
23 #include <mqueue.h>
24 #include <pthread.h>
25 #include <inttypes.h>
26
27 #include "rt-utils.h"
28 #include "rt-get_cpu.h"
29 #include "rt-error.h"
30
31 #define SYNCMQ_NAME "/syncmsg%d"
32 #define TESTMQ_NAME "/testmsg%d"
33 #define MSG_SIZE 8
34
35 char *syncmsg = "Syncing";
36 char *testmsg = "Testing";
37
38 enum {
39 AFFINITY_UNSPECIFIED,
40 AFFINITY_SPECIFIED,
41 AFFINITY_USEALL
42 };
43
44 struct params {
45 int num;
46 int cpu;
47 int priority;
48 int affinity;
49 int sender;
50 int samples;
51 int max_cycles;
52 int tracelimit;
53 int tid;
54 int shutdown;
55 int stopped;
56 struct timespec delay;
57 unsigned int mindiff, maxdiff;
58 double sumdiff;
59 struct timeval sent, received, diff;
60 pthread_t threadid;
61 int timeout;
62 int forcetimeout;
63 int timeoutcount;
64 mqd_t syncmq, testmq;
65 char recvsyncmsg[MSG_SIZE];
66 char recvtestmsg[MSG_SIZE];
67 struct params *neighbor;
68 };
69
70 void *pmqthread(void *param)
71 {
72 int mustgetcpu = 0;
73 struct params *par = param;
74 cpu_set_t mask;
75 int policy = SCHED_FIFO;
76 struct sched_param schedp;
77 struct timespec ts;
78 int ret;
79
80 memset(&schedp, 0, sizeof(schedp));
81 schedp.sched_priority = par->priority;
82 sched_setscheduler(0, policy, &schedp);
83
84 if (par->cpu != -1) {
85 CPU_ZERO(&mask);
86 CPU_SET(par->cpu, &mask);
87 if (sched_setaffinity(0, sizeof(mask), &mask) == -1)
88 fprintf(stderr, "WARNING: Could not set CPU affinity "
89 "to CPU #%d\n", par->cpu);
90 } else
91 mustgetcpu = 1;
92
93 par->tid = gettid();
94
95 while (!par->shutdown) {
96 if (par->sender) {
97
98 /* Optionally force receiver timeout */
99 if (par->forcetimeout) {
100 struct timespec senddelay;
101
102 senddelay.tv_sec = par->forcetimeout;
103 senddelay.tv_nsec = 0;
104 clock_nanosleep(CLOCK_MONOTONIC, 0, &senddelay, NULL);
105 }
106
107 /* Send message: Start of latency measurement ... */
108 gettimeofday(&par->sent, NULL);
109 if (mq_send(par->testmq, testmsg, strlen(testmsg), 1) != 0) {
110 fprintf(stderr, "could not send test message\n");
111 par->shutdown = 1;
112 }
113 par->samples++;
114 if (par->max_cycles && par->samples >= par->max_cycles)
115 par->shutdown = 1;
116 if (mustgetcpu)
117 par->cpu = get_cpu();
118 /* Wait until receiver ready */
119 if (par->timeout) {
120 clock_gettime(CLOCK_REALTIME, &ts);
121 ts.tv_sec += par->timeout;
122
123 if (mq_timedreceive(par->syncmq, par->recvsyncmsg, MSG_SIZE, NULL, &ts)
124 != strlen(syncmsg)) {
125 fprintf(stderr, "could not receive sync message\n");
126 par->shutdown = 1;
127 }
128 }
129 if (mq_receive(par->syncmq, par->recvsyncmsg, MSG_SIZE, NULL) !=
130 strlen(syncmsg)) {
131 perror("could not receive sync message");
132 par->shutdown = 1;
133 }
134 if (!par->shutdown && strcmp(syncmsg, par->recvsyncmsg)) {
135 fprintf(stderr, "ERROR: Sync message mismatch detected\n");
136 fprintf(stderr, " %s != %s\n", syncmsg, par->recvsyncmsg);
137 par->shutdown = 1;
138 }
139 } else {
140 /* Receiver */
141 if (par->timeout) {
142 clock_gettime(CLOCK_REALTIME, &ts);
143 par->timeoutcount = 0;
144 ts.tv_sec += par->timeout;
145 do {
146 if (mq_timedreceive(par->testmq, par->recvtestmsg,
147 MSG_SIZE, NULL, &ts) != strlen(testmsg)) {
148 if (!par->forcetimeout || errno != ETIMEDOUT) {
149 perror("could not receive test message");
150 par->shutdown = 1;
151 break;
152 }
153 if (errno == ETIMEDOUT) {
154 par->timeoutcount++;
155 clock_gettime(CLOCK_REALTIME, &ts);
156 ts.tv_sec += par->timeout;
157 }
158 } else
159 break;
160 } while (1);
161 } else {
162 if (mq_receive(par->testmq, par->recvtestmsg, MSG_SIZE, NULL) !=
163 strlen(testmsg)) {
164 perror("could not receive test message");
165 par->shutdown = 1;
166 }
167 }
168 /* ... Received the message: End of latency measurement */
169 gettimeofday(&par->received, NULL);
170
171 if (!par->shutdown && strcmp(testmsg, par->recvtestmsg)) {
172 fprintf(stderr, "ERROR: Test message mismatch detected\n");
173 fprintf(stderr, " %s != %s\n", testmsg, par->recvtestmsg);
174 par->shutdown = 1;
175 }
176 par->samples++;
177 timersub(&par->received, &par->neighbor->sent,
178 &par->diff);
179
180 if (par->diff.tv_usec < par->mindiff)
181 par->mindiff = par->diff.tv_usec;
182 if (par->diff.tv_usec > par->maxdiff)
183 par->maxdiff = par->diff.tv_usec;
184 par->sumdiff += (double) par->diff.tv_usec;
185 if (par->tracelimit && par->maxdiff > par->tracelimit) {
186 char tracing_enabled_file[MAX_PATH];
187
188 strcpy(tracing_enabled_file, get_tracefs_prefix());
189 strcat(tracing_enabled_file, "tracing_on");
190 int tracing_enabled =
191 open(tracing_enabled_file, O_WRONLY);
192 if (tracing_enabled >= 0) {
193 ret = write(tracing_enabled, "0", 1);
194 if (ret < 0)
195 fatal("Could not write to %s: %s\n",
196 tracing_enabled_file, strerror(errno));
197 close(tracing_enabled);
198 } else
199 fatal("Could not access %s\n", tracing_enabled_file);
200 par->shutdown = 1;
201 par->neighbor->shutdown = 1;
202 }
203
204 if (par->max_cycles && par->samples >= par->max_cycles)
205 par->shutdown = 1;
206 if (mustgetcpu)
207 par->cpu = get_cpu();
208 clock_nanosleep(CLOCK_MONOTONIC, 0, &par->delay, NULL);
209
210 /* Tell receiver that we are ready for the next measurement */
211 if (mq_send(par->syncmq, syncmsg, strlen(syncmsg), 1) != 0) {
212 fprintf(stderr, "could not send sync message\n");
213 par->shutdown = 1;
214 }
215 }
216 }
217 par->stopped = 1;
218 return NULL;
219 }
220
221 static void display_help(int error)
222 {
223 printf("pmqtest V %1.2f\n", VERSION);
224 printf("Usage:\n"
225 "pmqtest <options>\n\n"
226 "Function: test POSIX message queue latency\n\n"
227 "Available options:\n\n"
228 "-a [NUM] --affinity run thread #N on processor #N, if possible\n"
229 " with NUM pin all threads to the processor NUM\n"
230 "-b USEC --breaktrace=USEC send break trace command when latency > USEC\n"
231 "-d DIST --distance=DIST distance of thread intervals in us default=500\n"
232 "-D TIME --duration=TIME specify a length for the test run.\n"
233 " Append 'm', 'h', or 'd' to specify\n"
234 " minutes, hours or days.\n"
235 "-f TO --forcetimeout=TO force timeout of mq_timedreceive(), requires -T\n"
236 "-h --help print this help message\n"
237 "-i INTV --interval=INTV base interval of thread in us default=1000\n"
238 " --json=FILENAME write final results into FILENAME, JSON formatted\n"
239 "-l LOOPS --loops=LOOPS number of loops: default=0(endless)\n"
240 "-p PRIO --prio=PRIO priority\n"
241 "-q --quiet print a summary only on exit\n"
242 "-S --smp SMP testing: options -a -t and same priority\n"
243 " of all threads\n"
244 "-t --threads one thread per available processor\n"
245 "-t [NUM] --threads=NUM number of threads:\n"
246 " without NUM, threads = max_cpus\n"
247 " without -t default = 1\n"
248 "-T TO --timeout=TO use mq_timedreceive() instead of mq_receive()\n"
249 " with timeout TO in seconds\n");
250 exit(error);
251 }
252
253 static int setaffinity = AFFINITY_UNSPECIFIED;
254 static int affinity;
255 static int tracelimit;
256 static int priority;
257 static int num_threads = 1;
258 static int max_cycles;
259 static int duration;
260 static int interval = 1000;
261 static int distance = 500;
262 static int smp;
263 static int sameprio;
264 static int timeout;
265 static int forcetimeout;
266 static int quiet;
267 static char jsonfile[MAX_PATH];
268
269 enum option_value {
270 OPT_AFFINITY=1, OPT_BREAKTRACE, OPT_DISTANCE, OPT_DURATION,
271 OPT_FORCETIMEOUT, OPT_HELP, OPT_INTERVAL, OPT_JSON, OPT_LOOPS,
272 OPT_PRIORITY, OPT_QUIET, OPT_SMP, OPT_THREADS, OPT_TIMEOUT
273 };
274
275 static void process_options(int argc, char *argv[])
276 {
277 int error = 0;
278 int max_cpus = sysconf(_SC_NPROCESSORS_CONF);
279
280 for (;;) {
281 int option_index = 0;
282 /** Options for getopt */
283 static struct option long_options[] = {
284 {"affinity", optional_argument, NULL, OPT_AFFINITY},
285 {"breaktrace", required_argument, NULL, OPT_BREAKTRACE},
286 {"distance", required_argument, NULL, OPT_DISTANCE},
287 {"duration", required_argument, NULL, OPT_DURATION},
288 {"forcetimeout",required_argument, NULL, OPT_FORCETIMEOUT},
289 {"help", no_argument, NULL, OPT_HELP},
290 {"interval", required_argument, NULL, OPT_INTERVAL},
291 {"json", required_argument, NULL, OPT_JSON },
292 {"loops", required_argument, NULL, OPT_LOOPS},
293 {"priority", required_argument, NULL, OPT_PRIORITY},
294 {"quiet", no_argument, NULL, OPT_QUIET},
295 {"smp", no_argument, NULL, OPT_SMP},
296 {"threads", optional_argument, NULL, OPT_THREADS},
297 {"timeout", required_argument, NULL, OPT_TIMEOUT},
298 {NULL, 0, NULL, 0}
299 };
300 int c = getopt_long (argc, argv, "a::b:d:D:f:i:l:p:qSt::T:",
301 long_options, &option_index);
302 if (c == -1)
303 break;
304 switch (c) {
305 case OPT_AFFINITY:
306 case 'a':
307 if (smp) {
308 warn("-a ignored due to --smp\n");
309 break;
310 }
311 if (optarg != NULL) {
312 affinity = atoi(optarg);
313 setaffinity = AFFINITY_SPECIFIED;
314 } else if (optind < argc && atoi(argv[optind])) {
315 affinity = atoi(argv[optind]);
316 setaffinity = AFFINITY_SPECIFIED;
317 } else {
318 setaffinity = AFFINITY_USEALL;
319 }
320 break;
321 case OPT_BREAKTRACE:
322 case 'b':
323 tracelimit = atoi(optarg);
324 break;
325 case OPT_DISTANCE:
326 case 'd':
327 distance = atoi(optarg);
328 break;
329 case OPT_DURATION:
330 case 'D':
331 duration = parse_time_string(optarg);
332 break;
333 case OPT_FORCETIMEOUT:
334 case 'f':
335 forcetimeout = atoi(optarg);
336 break;
337 case OPT_HELP:
338 case '?':
339 case 'h':
340 display_help(0);
341 break;
342 case OPT_INTERVAL:
343 case 'i':
344 interval = atoi(optarg);
345 break;
346 case OPT_JSON:
347 strncpy(jsonfile, optarg, strnlen(optarg, MAX_PATH-1));
348 break;
349 case OPT_LOOPS:
350 case 'l':
351 max_cycles = atoi(optarg);
352 break;
353 case OPT_PRIORITY:
354 case 'p':
355 priority = atoi(optarg);
356 break;
357 case OPT_QUIET:
358 case 'q':
359 quiet = 1;
360 break;
361 case OPT_SMP:
362 case 'S':
363 smp = 1;
364 num_threads = max_cpus;
365 setaffinity = AFFINITY_USEALL;
366 break;
367 case OPT_THREADS:
368 case 't':
369 if (smp) {
370 warn("-t ignored due to --smp\n");
371 break;
372 }
373 if (optarg != NULL)
374 num_threads = atoi(optarg);
375 else if (optind < argc && atoi(argv[optind]))
376 num_threads = atoi(argv[optind]);
377 else
378 num_threads = max_cpus;
379 break;
380 case OPT_TIMEOUT:
381 case 'T':
382 timeout = atoi(optarg);
383 break;
384 default:
385 display_help(1);
386 break;
387 }
388 }
389
390 if (setaffinity == AFFINITY_SPECIFIED) {
391 if (affinity < 0)
392 error = 1;
393 if (affinity >= max_cpus) {
394 fprintf(stderr, "ERROR: CPU #%d not found, only %d CPUs available\n",
395 affinity, max_cpus);
396 error = 1;
397 }
398 }
399
400 if (num_threads < 0)
401 error = 1;
402
403 if (priority < 0 || priority > 99)
404 error = 1;
405
406 if (num_threads < 1)
407 error = 1;
408
409 if (forcetimeout && !timeout)
410 error = 1;
411
412 if (duration < 0)
413 error = 1;
414
415 if (priority && smp)
416 sameprio = 1;
417
418 if (error)
419 display_help(error);
420 }
421
422
423 static int volatile shutdown;
424
425 static void sighand(int sig)
426 {
427 shutdown = 1;
428 }
429
430 static void print_stat(FILE *fp, struct params *receiver, struct params *sender,
431 int verbose, int quiet)
432 {
433 int i;
434
435 if (quiet)
436 return;
437
438 for (i = 0; i < num_threads; i++) {
439 printf("#%1d: ID%d, P%d, CPU%d, I%ld; #%1d: ID%d, P%d, CPU%d, TO %d, Cycles %d\n",
440 i*2, receiver[i].tid, receiver[i].priority, receiver[i].cpu,
441 receiver[i].delay.tv_nsec / 1000,
442 i*2+1, sender[i].tid, sender[i].priority, sender[i].cpu,
443 receiver[i].timeoutcount, sender[i].samples);
444 }
445 for (i = 0; i < num_threads; i++) {
446 printf("#%d -> #%d, Min %4d, Cur %4d, Avg %4d, Max %4d\n",
447 i*2+1, i*2,
448 receiver[i].mindiff, (int) receiver[i].diff.tv_usec,
449 (int) ((receiver[i].sumdiff / receiver[i].samples) + 0.5),
450 receiver[i].maxdiff);
451 }
452 }
453
454 struct params_stats {
455 struct params *receiver;
456 struct params *sender;
457 };
458
459 static void write_stats(FILE *f, void *data)
460 {
461 struct params_stats *ps = data;
462 struct params *s, *r;
463 int i;
464
465 fprintf(f, " \"num_threads\": %d,\n", num_threads);
466 fprintf(f, " \"thread\": {\n");
467 for (i = 0; i < num_threads; i++) {
468 s = &ps->sender[i];
469 r = &ps->receiver[i];
470 fprintf(f, " \"%u\": {\n", i);
471 fprintf(f, " \"sender\": {\n");
472 fprintf(f, " \"cpu\": %d,\n", s->cpu);
473 fprintf(f, " \"priority\": %d,\n", s->priority);
474 fprintf(f, " \"samples\": %d,\n", s->samples);
475 fprintf(f, " \"interval\": %ld\n", r->delay.tv_nsec/1000);
476 fprintf(f, " },\n");
477 fprintf(f, " \"receiver\": {\n");
478 fprintf(f, " \"cpu\": %d,\n", r->cpu);
479 fprintf(f, " \"priority\": %d,\n", r->priority);
480 fprintf(f, " \"timeoutcount\": %d,\n", r->timeoutcount);
481 fprintf(f, " \"min\": %d,\n", r->mindiff);
482 fprintf(f, " \"avg\": %.2f,\n", r->sumdiff/r->samples);
483 fprintf(f, " \"max\": %d\n", r->maxdiff);
484 fprintf(f, " }\n");
485 fprintf(f, " }%s\n", i == num_threads - 1 ? "" : ",");
486 }
487 fprintf(f, " }\n");
488 }
489
490 int main(int argc, char *argv[])
491 {
492 int i;
493 int max_cpus = sysconf(_SC_NPROCESSORS_CONF);
494 struct params *receiver = NULL;
495 struct params *sender = NULL;
496 sigset_t sigset;
497 int oldsamples = INT_MAX;
498 int oldtimeoutcount = INT_MAX;
499 struct timespec maindelay;
500 int oflag = O_CREAT|O_RDWR;
501 struct mq_attr mqstat;
502
503 memset(&mqstat, 0, sizeof(mqstat));
504 mqstat.mq_maxmsg = 1;
505 mqstat.mq_msgsize = 8;
506 mqstat.mq_flags = 0;
507
508 rt_init(argc, argv);
509 process_options(argc, argv);
510
511 if (check_privs())
512 return 1;
513
514 if (mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
515 perror("mlockall");
516 return 1;
517 }
518
519 sigemptyset(&sigset);
520 sigaddset(&sigset, SIGTERM);
521 sigaddset(&sigset, SIGINT);
522 sigaddset(&sigset, SIGALRM);
523 pthread_sigmask(SIG_SETMASK, &sigset, NULL);
524
525 signal(SIGINT, sighand);
526 signal(SIGTERM, sighand);
527 signal(SIGALRM, sighand);
528
529 if (duration)
530 alarm(duration);
531
532 receiver = calloc(num_threads, sizeof(struct params));
533 sender = calloc(num_threads, sizeof(struct params));
534 if (receiver == NULL || sender == NULL)
535 goto nomem;
536
537 for (i = 0; i < num_threads; i++) {
538 char mqname[19];
539
540 sprintf(mqname, SYNCMQ_NAME, i);
541 receiver[i].syncmq = mq_open(mqname, oflag, 0777, &mqstat);
542 if (receiver[i].syncmq == (mqd_t) -1) {
543 fprintf(stderr, "could not open POSIX message queue #1\n");
544 return 1;
545 }
546 sprintf(mqname, TESTMQ_NAME, i);
547 receiver[i].testmq = mq_open(mqname, oflag, 0777, &mqstat);
548 if (receiver[i].testmq == (mqd_t) -1) {
549 fprintf(stderr, "could not open POSIX message queue #2\n");
550 return 1;
551 }
552
553 receiver[i].mindiff = UINT_MAX;
554 receiver[i].maxdiff = 0;
555 receiver[i].sumdiff = 0.0;
556
557 receiver[i].num = i;
558 receiver[i].cpu = i;
559 switch (setaffinity) {
560 case AFFINITY_UNSPECIFIED: receiver[i].cpu = -1; break;
561 case AFFINITY_SPECIFIED: receiver[i].cpu = affinity; break;
562 case AFFINITY_USEALL: receiver[i].cpu = i % max_cpus; break;
563 }
564 receiver[i].priority = priority;
565 receiver[i].tracelimit = tracelimit;
566 if (priority > 1 && !sameprio)
567 priority--;
568 receiver[i].delay.tv_sec = interval / USEC_PER_SEC;
569 receiver[i].delay.tv_nsec = (interval % USEC_PER_SEC) * 1000;
570 interval += distance;
571 receiver[i].max_cycles = max_cycles;
572 receiver[i].sender = 0;
573 receiver[i].neighbor = &sender[i];
574 receiver[i].timeout = timeout;
575 receiver[i].forcetimeout = forcetimeout;
576 pthread_create(&receiver[i].threadid, NULL, pmqthread, &receiver[i]);
577 memcpy(&sender[i], &receiver[i], sizeof(receiver[0]));
578 sender[i].sender = 1;
579 sender[i].neighbor = &receiver[i];
580 pthread_create(&sender[i].threadid, NULL, pmqthread, &sender[i]);
581 }
582
583 maindelay.tv_sec = 0;
584 maindelay.tv_nsec = 50000000; /* 50 ms */
585
586 sigemptyset(&sigset);
587 pthread_sigmask(SIG_SETMASK, &sigset, NULL);
588
589 do {
590 int newsamples = 0, newtimeoutcount = 0;
591 int minsamples = INT_MAX;
592
593 for (i = 0; i < num_threads; i++) {
594 newsamples += receiver[i].samples;
595 newtimeoutcount += receiver[i].timeoutcount;
596 if (receiver[i].samples < minsamples)
597 minsamples = receiver[i].samples;
598 }
599
600 if (minsamples > 1 && (shutdown || newsamples > oldsamples ||
601 newtimeoutcount > oldtimeoutcount)) {
602 print_stat(stdout, receiver, sender, 0, quiet);
603 if (!quiet)
604 printf("\033[%dA", num_threads*2);
605 }
606
607 fflush(NULL);
608
609 oldsamples = 0;
610 oldtimeoutcount = 0;
611 for (i = 0; i < num_threads; i++) {
612 oldsamples += receiver[i].samples;
613 oldtimeoutcount += receiver[i].timeoutcount;
614 }
615
616 nanosleep(&maindelay, NULL);
617
618 for (i = 0; i < num_threads; i++)
619 shutdown |= receiver[i].shutdown | sender[i].shutdown;
620
621 } while (!shutdown);
622
623 if (!quiet)
624 printf("\033[%dB", num_threads*2 + 2);
625 else
626 print_stat(stdout, receiver, sender, 0, 0);
627
628 for (i = 0; i < num_threads; i++) {
629 receiver[i].shutdown = 1;
630 sender[i].shutdown = 1;
631 }
632
633 for (i = 0; i < num_threads; i++) {
634 if (!receiver[i].stopped)
635 pthread_kill(receiver[i].threadid, SIGTERM);
636 if (!sender[i].stopped)
637 pthread_kill(sender[i].threadid, SIGTERM);
638 }
639 nanosleep(&maindelay, NULL);
640 for (i = 0; i < num_threads; i++) {
641 char mqname[19];
642
643 mq_close(receiver[i].syncmq);
644 sprintf(mqname, SYNCMQ_NAME, i);
645 mq_unlink(mqname);
646
647 mq_close(receiver[i].testmq);
648 sprintf(mqname, TESTMQ_NAME, i);
649 mq_unlink(mqname);
650 }
651
652 if (strlen(jsonfile) != 0) {
653 struct params_stats ps = {
654 .receiver = receiver,
655 .sender = sender,
656 };
657 rt_write_json(jsonfile, 0, write_stats, &ps);
658 }
659
660 nomem:
661
662 return 0;
663 }