Debian Codegraph @

src/sigwaittest/sigwaittest.c

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