Debian Codegraph @

src/sched_deadline/deadline_test.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-2.0-only
2
3 /*
4 * Copyright (C) 2016 Red Hat Inc, Steven Rostedt <[email protected]>
5 * Copyright (C) 2019 John Kacur <[email protected]>
6 * Copyright (C) 2019 Clark Williams <[email protected]>
7 */
8
9 /*
10 * deadline_test.c
11 *
12 * This program is used to test the deadline scheduler (SCHED_DEADLINE tasks).
13 * It is broken up into various degrees of complexity that can be set with
14 * options.
15 *
16 * Here are the test cases:
17 *
18 * 1) Simplest - create one deadline task that can migrate across all CPUS.
19 * Look for "simple_test"
20 *
21 */
22 #include <pthread.h>
23 #include <stdarg.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <fcntl.h>
29 #include <sched.h>
30 #include <ctype.h>
31 #include <errno.h>
32
33 #include <sys/syscall.h>
34 #include <sys/types.h>
35 #include <sys/mount.h>
36 #include <sys/mman.h>
37 #include <sys/time.h>
38 #include <sys/stat.h>
39 #include <sys/vfs.h>
40
41 #include <linux/unistd.h>
42 #include <linux/magic.h>
43
44 #include <rt-utils.h>
45 #include <rt-sched.h>
46
47 /**
48 * usage - show the usage of the program and exit.
49 * @error: Exit error code to be used
50 *
51 * This is defined here to show peoplde looking at this code how
52 * to use this program as well.
53 */
54 static void usage(int error)
55 {
56 printf("deadline_test V %1.2f\n", VERSION);
57 printf("Usage:\n"
58 "deadline_test <options>\n"
59 "-b Bind on the last cpu. (shortcut for -c <lastcpu>)\n"
60 "-c CPUSET Comma/hyphen separated list of CPUs to run deadline\n"
61 " tasks on\n"
62 "-h Show this help menu\n"
63 "-i INTV The shortest deadline for the tasks\n"
64 "-p PERCENT The percent of bandwidth to use (1-90%%)\n"
65 "-P PERCENT The percent of runtime for execution completion\n"
66 " (default 100%%)\n"
67 "-r PRIO Add an RT task with given prio to stress system\n"
68 "-s STEP The amount to increase the deadline for each task in us\n"
69 " (default 500us)\n"
70 "-t NUM The number of threads to run as deadline (default 1)\n"
71 );
72 exit(error);
73 }
74
75 #define _STR(x) #x
76 #define STR(x) _STR(x)
77
78 /* Max path for cpuset path names. 1K should be enough */
79 #ifndef MAXPATH
80 #define MAXPATH 1024
81 #endif
82
83 /*
84 * "my_cpuset" is the cpuset that will hold the SCHED_DEADLINE tasks that
85 * want to limit their affinity.
86 *
87 * "my_cpuset_all" is the cpuset that will have the affinity of all the
88 * other CPUs outside the ones for SCHED_DEADLINE threads. It will hold
89 * all other tasks.
90 */
91 #define CPUSET_ALL "my_cpuset_all"
92 #define CPUSET_LOCAL "my_cpuset"
93
94 typedef unsigned long long u64;
95 typedef unsigned int u32;
96 typedef int s32;
97
98 /**
99 * struct sched_data - the descriptor for the threads.
100 *
101 * This is the descriptor that will be passed as the thread data.
102 * It is used as both input to the thread, as well as output to
103 * the main program.
104 *
105 * @runtime_us: The runtime for sched_deadline tasks in microseconds
106 * @deadline_us: The deadline for sched_deadline tasks in microseconds
107 * @loops_per_period: The amount of loops to run for the runtime
108 * @max_time: Recorded max time to complete loops
109 * @min_time: Recorded min time to complete loops
110 * @total_time: The total time of all periods to perform the loops
111 * @nr_periods: The number of periods executed
112 * @prime: Calculating a prime number.
113 * @missed_periods: The number of periods that were missed (started late)
114 * @missed_deadlines: The number of deadlines that were missed (ended late)
115 * @total_adjust: The time in microseconds adjusted for starting early
116 * @nr_adjust: The number of times adjusted for starting early
117 * @last_time: Last runtime of loops (used to calculate runtime to give)
118 * @prio: The priority for SCHED_FIFO threads (uses same descriptor)
119 * @tid: Stores the thread ID of the thread.
120 * @vol: The number of voluntary schedules the thread made
121 * @nonvol: The number of non-voluntary schedules the thread made (preempted)
122 * @migrate: The number of migrations the thread made.
123 * @buff: A string buffer to store data to write to ftrace
124 *
125 */
126 struct sched_data {
127 u64 runtime_us;
128 u64 deadline_us;
129
130 u64 loops_per_period;
131
132 u64 max_time;
133 u64 min_time;
134 u64 total_time;
135 u64 nr_periods;
136
137 u64 prime;
138
139 int missed_periods;
140 int missed_deadlines;
141 u64 total_adjust;
142 u64 nr_adjust;
143
144 u64 last_time;
145
146 int prio;
147 int tid;
148
149 int vol;
150 int nonvol;
151 int migrate;
152
153 char buff[BUFSIZ+1];
154
155 /* Try to keep each sched_data out of cache lines */
156 char padding[256];
157 };
158
159 /* Barrier to synchronize the threads for initialization */
160 static pthread_barrier_t barrier;
161
162 /* cpu_count is the number of detected cpus on the running machine */
163 static int cpu_count;
164
165 /*
166 * cpusetp and cpuset_size is for cpumasks, in case we run on a machine with
167 * more than 64 CPUs.
168 */
169 static cpu_set_t *cpusetp;
170 static int cpuset_size;
171
172 /* Number of threads to create to run deadline scheduler with (default two) */
173 static int nr_threads = 2;
174
175 /**
176 * find_mount - Find if a file system type is already mounted
177 * @mount: The type of files system to find
178 * @debugfs: Where to place the path to the found file system.
179 *
180 * Returns 1 if found and sets @debugfs.
181 * Returns 0 otherwise.
182 */
183 static int find_mount(const char *mount, char *debugfs)
184 {
185 char type[100];
186 FILE *fp;
187
188 if ((fp = fopen("/proc/mounts", "r")) == NULL)
189 return 0;
190
191 while (fscanf(fp, "%*s %"
192 STR(MAXPATH)
193 "s %99s %*s %*d %*d\n",
194 debugfs, type) == 2) {
195 if (strcmp(type, mount) == 0)
196 break;
197 }
198 fclose(fp);
199
200 if (strcmp(type, mount) != 0)
201 return 0;
202 return 1;
203 }
204
205 /**
206 * find_debugfs - Search for where debugfs is found
207 *
208 * Finds where debugfs is mounted and returns the path.
209 * The returned string is static and should not be modified.
210 */
211 static const char *find_debugfs(void)
212 {
213 static int debugfs_found;
214 static char debugfs[MAXPATH+1];
215
216 if (debugfs_found)
217 return debugfs;
218
219 if (!find_mount("debugfs", debugfs))
220 return "";
221
222 debugfs_found = 1;
223
224 return debugfs;
225 }
226
227 /**
228 * my_vsprintf - simplified vsprintf()
229 * @buf: The buffer to write the string to
230 * @size: The allocated size of @buf
231 * @fmmt: The format to parse
232 * @ap: The variable arguments
233 *
234 * Because there's no real way to prevent glibc's vsprintf from
235 * allocating more memory, or doing any type of system call,
236 * This is a simple version of the function that is under
237 * our control, to make sure we stay in userspace when creating
238 * a ftrace_write string, and only do a system call for the
239 * actual ftrace_write.
240 */
241 static int my_vsprintf(char *buf, int size, const char *fmt, va_list ap)
242 {
243 const char *p;
244 char tmp[100];
245 char *s = buf;
246 char *end = buf + size;
247 char *str;
248 long long lng;
249 int l;
250 int i;
251
252 end[-1] = 0;
253
254 for (p = fmt; *p && s < end; p++) {
255 if (*p == '%') {
256 l = 0;
257 again:
258 p++;
259 switch (*p) {
260 case 's':
261 if (l) {
262 fprintf(stderr, "Illegal print format l used with %%s\n");
263 exit(-1);
264 }
265 str = va_arg(ap, char *);
266 l = strlen(str);
267 strncpy(s, str, end - s);
268 s += l;
269 break;
270 case 'l':
271 l++;
272 goto again;
273 case 'd':
274 if (l == 1) {
275 if (sizeof(long) == 8)
276 l = 2;
277 }
278 if (l == 2)
279 lng = va_arg(ap, long long);
280 else if (l > 2) {
281 fprintf(stderr, "Illegal print format l=%d\n", l);
282 exit(-1);
283 } else
284 lng = va_arg(ap, int);
285 i = 0;
286 while (lng > 0) {
287 tmp[i++] = (lng % 10) + '0';
288 lng /= 10;
289 }
290 tmp[i] = 0;
291 l = strlen(tmp);
292 if (!l) {
293 *s++ = '0';
294 } else {
295 while (l)
296 *s++ = tmp[--l];
297 }
298 break;
299 default:
300 fprintf(stderr, "Illegal print format '%c'\n", *p);
301 exit(-1);
302 }
303 continue;
304 }
305 *s++ = *p;
306 }
307
308 return s - buf;
309 }
310
311 /* The ftrace tracing_marker file descriptor to write to ftrace */
312 static int mark_fd;
313
314 /**
315 * ftrace_write - write a string to ftrace tracing_marker
316 * @buf: A BUFSIZ + 1 allocated scratch pad
317 * @fmt: The format of the sting to write
318 * @va_arg: The arguments for @fmt
319 *
320 * If mark_fd is not less than zero, format the input
321 * and write it out to trace_marker (where mark_fd is a file
322 * descriptor of).
323 */
324 static void ftrace_write(char *buf, const char *fmt, ...)
325 {
326 va_list ap;
327 int n;
328 int ret;
329
330 if (mark_fd < 0)
331 return;
332
333 va_start(ap, fmt);
334 n = my_vsprintf(buf, BUFSIZ, fmt, ap);
335 va_end(ap);
336
337 ret = write(mark_fd, buf, n);
338 if (ret < 0)
339 perror("ftrace write failed");
340 }
341
342 /**
343 * setup_ftrace_marker - Check if trace_marker exists and open if it does
344 *
345 * Tests if debugfs is mounted, and if it is, it tests to see if the
346 * trace_marker exists. If it does, it opens trace_marker and sets
347 * mark_fd to the file descriptor. Then ftrace_write() will be able
348 * to write to the ftrace marker, otherwise ftrace_write() becomes
349 * a nop.
350 *
351 * Failure to open the trace_marker file will not stop this application
352 * from executing. Only ftrace writes will not be performed.
353 */
354 static void setup_ftrace_marker(void)
355 {
356 struct stat st;
357 const char *debugfs = find_debugfs();
358 char files[strlen(debugfs) + strlen("/tracing/trace_marker") + 1];
359 int ret;
360
361 if (strlen(debugfs) == 0)
362 return;
363
364 sprintf(files, "%s/tracing/trace_marker", debugfs);
365 ret = stat(files, &st);
366 if (ret >= 0)
367 goto found;
368 /* Do nothing if not mounted */
369 return;
370 found:
371 mark_fd = open(files, O_WRONLY);
372 }
373
374 /*
375 * Return true if file exists
376 */
377 static int check_file_exists(char *path)
378 {
379 int ret;
380 struct stat st;
381
382 ret = !stat(path, &st);
383
384 return ret;
385
386 }
387
388 /*
389 * Return 0 on success
390 */
391
392 static int fill_sched_features(char *path)
393 {
394 int ret;
395 const char *debugfs;
396
397 debugfs = find_debugfs();
398 if (strlen(debugfs) == 0)
399 return -1;
400
401 snprintf(path, MAX_PATH, "%s/sched/features", debugfs);
402 ret = check_file_exists(path);
403 if (ret)
404 return 0;
405
406 snprintf(path, MAX_PATH, "%s/sched_features", debugfs);
407 ret = check_file_exists(path);
408 if (ret)
409 return 0;
410
411 memset(path, 0, MAX_PATH);
412
413 return ret;
414
415 }
416
417 /**
418 * setup_hr_tick - Enable the HRTICK in sched_features (if available)
419 *
420 * SCHED_DEADLINE tasks are based on HZ, which could be as slow as
421 * 100 times a second (10ms). Which is incredibly slow for scheduling.
422 * For SCHED_DEADLINE to have finer resolution, HRTICK feature must be
423 * set. That's located in the debugfs/sched_features directory.
424 *
425 * This will not mount debugfs. If debugfs is not mounted, this simply
426 * will fail.
427 */
428 static int setup_hr_tick(void)
429 {
430 char path[MAX_PATH];
431 char buf[500];
432 static int set = 0;
433 int hrtick_dl = 0;
434 char *p;
435 int ret;
436 int len;
437 int fd;
438
439 if (set)
440 return 1;
441
442 set = 1;
443
444 ret = fill_sched_features(path);
445 if (ret)
446 return 0;
447
448 fd = open(path, O_RDWR);
449 if (fd < 0) {
450 perror(path);
451 return 0;
452 }
453
454 len = sizeof(buf);
455
456 ret = read(fd, buf, len);
457 if (ret < 0) {
458 perror(path);
459 close(fd);
460 return 0;
461 }
462 if (ret >= len)
463 ret = len - 1;
464 buf[ret] = 0;
465
466 ret = 1;
467
468 p = strstr(buf, "HRTICK_DL");
469 if (p && p - 3 >= buf) {
470 hrtick_dl = 1;
471 p -= 3;
472 if (strncmp(p, "NO_HRTICK_DL", 12) == 0) {
473 ret = write(fd, "HRTICK_DL", 9);
474 if (ret != 9)
475 ret = 0;
476 else
477 ret = 1;
478 }
479 }
480
481 /* Backwards compatibility for kernel that only have HRTICK */
482 if (!hrtick_dl) {
483 p = strstr(buf, "HRTICK");
484 if (p && p - 3 >= buf) {
485 p -=3;
486 if (strncmp(p, "NO_HRTICK", 9) == 0) {
487 ret = write(fd, "HRTICK", 6);
488 if (ret != 6)
489 ret = 0;
490 else
491 ret = 1;
492 }
493 }
494 }
495
496
497 close(fd);
498 return ret;
499 }
500
501 /**
502 * mounted - test if a path is mounted via the given mount type
503 * @path: The path to check is mounted
504 * @magic: The magic number of the mount type.
505 *
506 * Returns -1 if the path does not exist.
507 * Returns 0 if it is mounted but not of the given @magic type.
508 * Returns 1 if mounted and the @magic type matches.
509 */
510 static int mounted(const char *path, long magic)
511 {
512 struct statfs st_fs;
513
514 if (statfs(path, &st_fs) < 0)
515 return -1;
516 if ((long)st_fs.f_type != magic)
517 return 0;
518 return 1;
519 }
520
521 #define CGROUP_PATH "/sys/fs/cgroup"
522 #define CPUSET_PATH CGROUP_PATH "/cpuset"
523
524 /**
525 * cgroup_mounted - test if the path /sys/fs/cgroup exists
526 * and is a supported type
527 *
528 * Returns -1 if the path does not exist
529 * Returns 0 if the path exists but is not a cgroup type
530 * Returns 1 if the path exists and supports cgroups
531 */
532 static int cgroup_mounted(void)
533 {
534 int ret;
535
536 ret = mounted(CGROUP_PATH, TMPFS_MAGIC);
537 if (ret == -1)
538 return -1; /* path doesn't exist */
539 if (ret == 1)
540 return 1; /* tmpfs */
541 ret = mounted(CGROUP_PATH, CGROUP_SUPER_MAGIC);
542 if (ret == 1)
543 return 1; /* cgroup v1 */
544 ret = mounted(CGROUP_PATH, CGROUP2_SUPER_MAGIC);
545 if (ret == 1)
546 return 1; /* cgroup v2 */
547 return 0; /* path exists but type is not recognized */
548 }
549
550 /**
551 * open_cpuset - open a file (usually a cpuset file)
552 * @path: The path of the directory the file is in
553 * @name: The name of the file in the path to open.
554 *
555 * Open a file, used to open cpuset files. This function simply is
556 * made to open many files in the same directory.
557 *
558 * Returns the file descriptor of the opened file or less than zero
559 * on error.
560 */
561 static int open_cpuset(const char *path, const char *name)
562 {
563 char buf[MAXPATH];
564 struct stat st;
565 int ret;
566 int fd;
567
568 buf[MAXPATH - 1] = 0;
569 snprintf(buf, MAXPATH - 1, "%s/%s", path, name);
570
571 ret = stat(buf, &st);
572 if (ret < 0)
573 return ret;
574
575 fd = open(buf, O_WRONLY);
576 return fd;
577 }
578
579 /**
580 * mount_cpuset - Inialize the cpuset system
581 *
582 * Looks to see if cgroups are mounted, if it is not, then it mounts
583 * the cgroup_root to /sys/fs/cgroup. Then the directory cpuset exists
584 * and is mounted in that directory. If it is not, it is created and
585 * mounted.
586 *
587 * The toplevel cpuset "cpu_exclusive" flag is set, this allows child
588 * cpusets to set the flag too.
589 *
590 * The toplevel cpuset "load_balance" flag is cleared, letting the
591 * child cpusets take over load balancing.
592 */
593 static int mount_cpuset(void)
594 {
595 struct stat st;
596 int ret;
597 int fd;
598
599 /* Check if cgroups is already mounted. */
600 ret = cgroup_mounted();
601 if (ret < 0) /* /sys/fs/cgroup doesn't exist */
602 return ret;
603
604 if (!ret) /* /sys/fs/cgroup exists, but we don't recognize the type */
605 return -1;
606
607 ret = stat(CPUSET_PATH, &st);
608 if (ret < 0) {
609 ret = mkdir(CPUSET_PATH, 0755);
610 if (ret < 0)
611 return ret;
612 }
613 ret = mounted(CPUSET_PATH, CGROUP_SUPER_MAGIC);
614 if (ret < 0)
615 return ret;
616 if (!ret) {
617 ret = mount("cpuset", CPUSET_PATH, "cgroup", 0, "cpuset");
618 if (ret < 0)
619 return ret;
620 }
621
622 fd = open_cpuset(CPUSET_PATH, "cpuset.cpu_exclusive");
623 if (fd < 0)
624 return fd;
625 ret = write(fd, "1", 2);
626 close(fd);
627
628 fd = open_cpuset(CPUSET_PATH, "cpuset.sched_load_balance");
629 if (fd < 0)
630 return fd;
631 ret = write(fd, "0", 2);
632 if (ret < 0) {
633 close(fd);
634 return ret;
635 }
636 close(fd);
637
638 return 0;
639 }
640
641 /*
642 * CPUSET flags: used for creating cpusets
643 *
644 * CPU_EXCLUSIVE - Set the cpu exclusive flag
645 * MEM_EXCLUSIVE - Set the mem exclusive flag
646 * ALL_TASKS - Move all tasks from the toplevel cpuset to this one
647 * TASKS - Supply a list of thread IDs to move to this cpuset
648 * CLEAR_LOADBALANCE - clear the loadbalance flag
649 * SET_LOADBALANCE - set the loadbalance flag
650 * CLONE_CHILDREN - set the clone_children flag
651 */
652 enum {
653 CPUSET_FL_CPU_EXCLUSIVE = (1 << 0),
654 CPUSET_FL_MEM_EXCLUSIVE = (1 << 1),
655 CPUSET_FL_ALL_TASKS = (1 << 2),
656 CPUSET_FL_TASKS = (1 << 3),
657 CPUSET_FL_CLEAR_LOADBALANCE = (1 << 4),
658 CPUSET_FL_SET_LOADBALANCE = (1 << 5),
659 CPUSET_FL_CLONE_CHILDREN = (1 << 6),
660 };
661
662 /**
663 * make_cpuset - create a cpuset
664 * @name: The name of the cpuset
665 * @cpus: A string list of cpus this set is for e.g. "1,3,4-7"
666 * @mems: The memory nodes to use (usually just "0") (set to NULL to ignore)
667 * @flags: See the CPUSET_FL_* flags above for information
668 * @va_args: An array of tasks to move if TASKS flag is set.
669 *
670 * Creates a cpuset.
671 *
672 * If TASKS is set, then @va_args will be an array of PIDs to move from
673 * the main cpuset, to this cpuset. The last element of the array must
674 * be a zero, to stop the processing of arrays.
675 *
676 * Returns NULL on success, and a string to describe what went wrong on error.
677 */
678 static const char *make_cpuset(const char *name, const char *cpus,
679 const char *mems, unsigned flags, ...)
680 {
681 struct stat st;
682 char path[MAXPATH];
683 char buf[100];
684 va_list ap;
685 int ret;
686 int fd;
687
688 printf("Creating cpuset '%s'\n", name);
689 snprintf(path, MAXPATH - 1, "%s/%s", CPUSET_PATH, name);
690 path[MAXPATH - 1] = 0;
691
692 ret = mount_cpuset();
693 if (ret < 0)
694 return "mount_cpuset";
695
696 /* Only create the new cpuset directory if it does not yet exist */
697 ret = stat(path, &st);
698 if (ret < 0) {
699 ret = mkdir(path, 0755);
700 if (ret < 0)
701 return "mkdir";
702 }
703
704 /* Assign the CPUs */
705 fd = open_cpuset(path, "cpuset.cpus");
706 if (fd < 0)
707 return "cset";
708 ret = write(fd, cpus, strlen(cpus));
709 close(fd);
710 if (ret < 0)
711 return "write cpus";
712
713 /* Assign the "mems" if it exists */
714 if (mems) {
715 fd = open_cpuset(path, "cpuset.mems");
716 if (fd < 0)
717 return "open mems";
718 ret = write(fd, mems, strlen(mems));
719 close(fd);
720 if (ret < 0)
721 return "write mems";
722 }
723
724 if (flags & CPUSET_FL_CPU_EXCLUSIVE) {
725 fd = open_cpuset(path, "cpuset.cpu_exclusive");
726 if (fd < 0)
727 return "open cpu_exclusive";
728 ret = write(fd, "1", 2);
729 close(fd);
730 if (ret < 0)
731 return "write cpu_exclusive";
732 }
733
734 if (flags & (CPUSET_FL_CLEAR_LOADBALANCE | CPUSET_FL_SET_LOADBALANCE)) {
735 fd = open_cpuset(path, "cpuset.sched_load_balance");
736 if (fd < 0)
737 return "open sched_load_balance";
738 if (flags & CPUSET_FL_SET_LOADBALANCE)
739 ret = write(fd, "1", 2);
740 else
741 ret = write(fd, "0", 2);
742 close(fd);
743 if (ret < 0)
744 return "write sched_load_balance";
745 }
746
747 if (flags & CPUSET_FL_CLONE_CHILDREN) {
748 fd = open_cpuset(path, "cgroup.clone_children");
749 if (fd < 0)
750 return "open clone_children";
751 ret = write(fd, "1", 2);
752 close(fd);
753 if (ret < 0)
754 return "write clone_children";
755 }
756
757
758 /* If TASKS flag is set, then an array of tasks is passed it */
759 if (flags & CPUSET_FL_TASKS) {
760 int *pids;
761 int i;
762
763 fd = open_cpuset(path, "tasks");
764 if (fd < 0)
765 return "open tasks";
766
767 va_start(ap, flags);
768
769 ret = 0;
770 pids = va_arg(ap, int *);
771
772 /* The array ends with pids[i] == 0 */
773 for (i = 0; pids[i]; i++) {
774 sprintf(buf, "%d ", pids[i]);
775 ret = write(fd, buf, strlen(buf));
776 if (ret < 0)
777 break;
778 }
779 va_end(ap);
780 close(fd);
781 if (ret < 0) {
782 fprintf(stderr, "Failed on task %d\n", pids[i]);
783 return "write tasks";
784 }
785 }
786
787 /* If ALL_TASKS flag is set, move all tasks from the top level cpuset */
788 if (flags & CPUSET_FL_ALL_TASKS) {
789 FILE *fp;
790 int pid;
791
792 fd = open_cpuset(path, "tasks");
793
794 snprintf(path, MAXPATH - 1, "%s/tasks", CPUSET_PATH);
795 if ((fp = fopen(path, "r")) == NULL) {
796 close(fd);
797 return "opening cpuset tasks";
798 }
799
800 while (fscanf(fp, "%d", &pid) == 1) {
801 sprintf(buf, "%d", pid);
802 ret = write(fd, buf, strlen(buf));
803 /*
804 * Tasks can come and go, and some tasks are kernel
805 * threads that cannot be moved. The only error we care
806 * about is ENOSPC, as that means something went
807 * wrong that we did not expect.
808 */
809 if (ret < 0 && errno == ENOSPC) {
810 fclose(fp);
811 close(fd);
812 return "Can not move tasks";
813 }
814 }
815 fclose(fp);
816 close(fd);
817 }
818
819 return NULL;
820 }
821
822 /**
823 * destroy_cpuset - tear down a cpuset that was created
824 * @name: The name of the cpuset to destroy
825 * @print: If the tasks being moved should be displayed
826 *
827 * Reads the tasks in the cpuset and moves them to the top level cpuset
828 * then destroys the @name cpuset.
829 */
830 static void destroy_cpuset(const char *name, int print)
831 {
832 struct stat st;
833 char path[MAXPATH];
834 char buf[100];
835 FILE *fp;
836 int pid;
837 int ret;
838 int fd;
839 int retry = 0;
840
841 printf("Removing %s\n", name);
842
843 /* Set path to the cpuset name that we will destroy */
844 snprintf(path, MAXPATH - 1, "%s/%s", CPUSET_PATH, name);
845 path[MAXPATH - 1] = 0;
846
847 /* Make sure it exists! */
848 ret = stat(path, &st);
849 if (ret < 0)
850 return;
851
852 again:
853 /*
854 * Append "/tasks" to the cpuset name, to read the tasks that are
855 * in this cpuset, that must be moved before destroying the cpuset.
856 */
857 strncat(path, "/tasks", MAXPATH - 1);
858 if ((fp = fopen(path, "r")) == NULL) {
859 fprintf(stderr, "Failed opening %s\n", path);
860 perror("fopen");
861 return;
862 }
863 /* Set path to the toplevel cpuset tasks file */
864 snprintf(path, MAXPATH - 1, "%s/tasks", CPUSET_PATH);
865 path[MAXPATH - 1] = 0;
866
867 fd = open(path, O_WRONLY);
868 if (fd < 0) {
869 fclose(fp);
870 fprintf(stderr, "Failed opening %s\n", path);
871 perror("open");
872 return;
873 }
874
875 /*
876 * Now fp points to the destroying cpuset tasks file, and
877 * fd is the toplevel cpuset file descriptor. Scan in the
878 * tasks that are in the cpuset that is being destroyed and
879 * write their pids into the toplevel cpuset.
880 */
881 while (fscanf(fp, "%d", &pid) == 1) {
882 sprintf(buf, "%d", pid);
883 if (print)
884 printf("Moving %d out of %s\n", pid, name);
885 ret = write(fd, buf, strlen(buf));
886 if (ret < 0 && errno == ENOSPC) {
887 /*
888 * If we get ENOSPC, then we have a problem, as it
889 * means that the cpuset is full, and we cannot move
890 * the tasks out of it.
891 */
892 fclose(fp);
893 close(fd);
894 fprintf(stderr, "Failed to move %d out of %s\n", pid, name);
895 perror("write");
896 return;
897 }
898 }
899 fclose(fp);
900 close(fd);
901
902 /* Reset the path name back to the cpuset to destroy */
903 snprintf(path, MAXPATH - 1, "%s/%s", CPUSET_PATH, name);
904 path[MAXPATH - 1] = 0;
905
906 /* Sleep a bit to let all tasks migrate out of this cpuset. */
907 sleep(1);
908
909 ret = rmdir(path);
910 if (ret < 0) {
911 /*
912 * Sometimes there appears to be a delay, and tasks don't
913 * always move when you expect them to. Try 5 times, and
914 * give up after that.
915 */
916 if (retry++ < 5)
917 goto again;
918 fprintf(stderr, "Failed to remove %s\n", path);
919 perror("rmdir");
920 }
921 }
922
923 /**
924 * teardown - Called atexit() to reset the system back to normal
925 *
926 * If cpusets were created, this destroys them and puts all tasks
927 * back to the main cgroup.
928 */
929 static void teardown(void)
930 {
931 int fd;
932 int ret;
933
934 fd = open_cpuset(CPUSET_PATH, "cpuset.cpu_exclusive");
935 if (fd >= 0) {
936 ret = write(fd, "0", 2);
937 if (ret < 0)
938 perror("cpuset.cpu_exclusive");
939 close(fd);
940 }
941
942 fd = open_cpuset(CPUSET_PATH, "cpuset.sched_load_balance");
943 if (fd >= 0) {
944 ret = write(fd, "1", 2);
945 if (ret < 0)
946 perror("cpuset.sched_load_balance");
947 close(fd);
948 }
949
950 destroy_cpuset(CPUSET_ALL, 0);
951 destroy_cpuset(CPUSET_LOCAL, 1);
952 }
953
954 /**
955 * bind_cpu - Set the affinity of a thread to a specific CPU.
956 * @cpu: The CPU to bind to.
957 *
958 * Sets the current thread to have an affinity of a single CPU.
959 * Does not work on SCHED_DEADLINE tasks.
960 */
961 static void bind_cpu(int cpu)
962 {
963 int ret;
964
965 CPU_ZERO_S(cpuset_size, cpusetp);
966 CPU_SET_S(cpu, cpuset_size, cpusetp);
967
968 ret = sched_setaffinity(0, cpuset_size, cpusetp);
969 if (ret < 0)
970 perror("sched_setaffinity bind");
971 }
972
973 /**
974 * unbind_cpu - Set the affinity of a task to all CPUs
975 *
976 * Sets the current thread to have an affinity for all CPUs.
977 * Does not work on SCHED_DEADLINE tasks.
978 */
979 static void unbind_cpu(void)
980 {
981 int cpu;
982 int ret;
983
984 for (cpu = 0; cpu < cpu_count; cpu++)
985 CPU_SET_S(cpu, cpuset_size, cpusetp);
986
987 ret = sched_setaffinity(0, cpuset_size, cpusetp);
988 if (ret < 0)
989 perror("sched_setaffinity unbind");
990 }
991
992 /*
993 * Used by set_prio, but can be used for any task not just current.
994 */
995 static int set_thread_prio(pid_t pid, int prio)
996 {
997 struct sched_param sp = { .sched_priority = prio };
998 int policy = SCHED_FIFO;
999
1000 if (!prio)
1001 policy = SCHED_OTHER;
1002
1003 /* set up our priority */
1004 return sched_setscheduler(pid, policy, &sp);
1005 }
1006
1007 /**
1008 * set_prio - Set the SCHED_FIFO priority of a thread
1009 * @prio: The priority to set a thread to
1010 *
1011 * Converts a SCHED_OTHER task into a SCHED_FIFO task and sets
1012 * its priority to @prio. If @prio is zero, then it converts
1013 * a SCHED_FIFO task back to a SCHED_OTHER task.
1014 *
1015 * Returns 0 on success, otherwise it failed.
1016 */
1017 static int set_prio(int prio)
1018 {
1019 return set_thread_prio(0, prio);
1020 }
1021
1022 /* done - set when the test is complete to have all threads stop */
1023 static int done;
1024
1025 /* fail - set during setup if any thread fails to initialize. */
1026 static int fail;
1027
1028 /**
1029 * get_time_us - Git the current clock time in microseconds
1030 *
1031 * Returns the current clock time in microseconds.
1032 */
1033 static u64 get_time_us(void)
1034 {
1035 struct timespec ts;
1036 u64 time;
1037
1038 clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
1039 time = ts.tv_sec * 1000000;
1040 time += ts.tv_nsec / 1000;
1041
1042 return time;
1043 }
1044
1045 /**
1046 * run_loops - execute a number of loops to perform
1047 * @loops: The number of loops to execute.
1048 *
1049 * Calculates prime numbers, because what else should we do?
1050 */
1051 static u64 run_loops(struct sched_data *data, u64 loops)
1052 {
1053 u64 start = get_time_us();
1054 u64 end;
1055 u64 i;
1056 u64 prime;
1057 u64 cnt = 2;
1058 u64 result;
1059
1060 prime = data->prime;
1061
1062 for (i = 0; i < loops; i++) {
1063 if (cnt > prime / 2) {
1064 data->prime = prime;
1065 prime++;
1066 cnt = 2;
1067 }
1068 result = prime / cnt;
1069 if (result * cnt == prime) {
1070 prime++;
1071 cnt = 2;
1072 } else
1073 cnt++;
1074 }
1075
1076 /* Memory barrier */
1077 asm("":::"memory");
1078
1079 end = get_time_us();
1080 return end - start;
1081 }
1082
1083 /* Helper function for read_ctx_switchs */
1084 static int get_value(const char *line)
1085 {
1086 const char *p;
1087
1088 for (p = line; isspace(*p); p++)
1089 ;
1090 if (*p != ':')
1091 return -1;
1092 p++;
1093 for (; isspace(*p); p++)
1094 ;
1095 return atoi(p);
1096 }
1097
1098 /* Helper function for read_ctx_switchs */
1099 static int update_value(const char *line, int *val, const char *name)
1100 {
1101 int ret;
1102
1103 if (strncmp(line, name, strlen(name)) == 0) {
1104 ret = get_value(line + strlen(name));
1105 if (ret < 0)
1106 return 0;
1107 *val = ret;
1108 return 1;
1109 }
1110 return 0;
1111 }
1112
1113 /**
1114 * read_ctx_switches - read the scheduling information of a task
1115 * @vol: Output to place number of voluntary schedules
1116 * @nonvol: Output to place number of non-voluntary schedules (preemption)
1117 * @migrate: Output to place the number of times the task migrated
1118 *
1119 * Reads /proc/<pid>/sched to get the statistics of the thread.
1120 *
1121 * For info only.
1122 */
1123 static int read_ctx_switches(int *vol, int *nonvol, int *migrate)
1124 {
1125 static int vol_once, nonvol_once;
1126 const char *vol_name = "nr_voluntary_switches";
1127 const char *nonvol_name = "nr_involuntary_switches";
1128 const char *migrate_name = "se.nr_migrations";
1129 char file[1024];
1130 char buf[1024];
1131 char *pbuf;
1132 int pid;
1133 size_t *pn;
1134 size_t n;
1135 FILE *fp;
1136 int r;
1137
1138 pid = gettid();
1139 snprintf(file, 1024, "/proc/%d/sched", pid);
1140 fp = fopen(file, "r");
1141 if (!fp) {
1142 snprintf(file, 1024, "/proc/%d/status", pid);
1143 fp = fopen(file, "r");
1144 if (!fp) {
1145 fprintf(stderr, "could not open %s", file);
1146 return -1;
1147 }
1148 vol_name = "voluntary_ctxt_switches";
1149 nonvol_name = "nonvoluntary_ctxt_switches";
1150 }
1151
1152 *vol = *nonvol = *migrate = -1;
1153
1154 n = 1024;
1155 pn = &n;
1156 pbuf = buf;
1157
1158 while ((r = getline(&pbuf, pn, fp)) >= 0) {
1159
1160 if (update_value(buf, vol, vol_name))
1161 continue;
1162
1163 if (update_value(buf, nonvol, nonvol_name))
1164 continue;
1165
1166 if (update_value(buf, migrate, migrate_name))
1167 continue;
1168 }
1169 fclose(fp);
1170
1171 if (!vol_once && *vol == -1) {
1172 vol_once++;
1173 fprintf(stderr, "Warning, could not find voluntary ctx switch count\n");
1174 }
1175 if (!nonvol_once && *nonvol == -1) {
1176 nonvol_once++;
1177 fprintf(stderr, "Warning, could not find nonvoluntary ctx switch count\n");
1178 }
1179
1180 return 0;
1181 }
1182
1183 /**
1184 * do_runtime - Run a loop to simulate a specific task
1185 * @tid: The thread ID
1186 * @data: The sched_data descriptor
1187 * @period: The time of the last period.
1188 *
1189 * Returns the expected next period.
1190 *
1191 * This simulates some task that needs to be completed within the deadline.
1192 *
1193 * Input:
1194 * @data->deadline_us - to calculate next peroid
1195 * @data->loops_per_peroid - to loop this amount of time
1196 *
1197 * Output:
1198 * @data->total_adjust - Time adjusted for starting a period early
1199 * @data->nr_adjusted - Number of times adjusted
1200 * @data->missed_deadlines - Counter of missed deadlines
1201 * @data->missed_periods - Counter of missed periods (started late)
1202 * @data->max_time - Maximum time it took to complete the loops
1203 * @data->min_time - Minimum time it took to complete the loops
1204 * @data->last_time - How much time it took to complete loops this time
1205 * @data->total_time - Total time it took to complete all loops
1206 * @data->nr_periods - Number of periods that were executed.
1207 */
1208 static u64 do_runtime(struct sched_data *data, u64 period)
1209 {
1210 u64 next_period = period + data->deadline_us;
1211 u64 now = get_time_us();
1212 u64 end;
1213 u64 diff;
1214 u64 time;
1215
1216 /*
1217 * next_period is our new deadline. If now is passed that point
1218 * we missed a period.
1219 */
1220 if (now > next_period) {
1221 ftrace_write(data->buff,
1222 "Missed a period start: %lld next: %lld now: %lld\n",
1223 period, next_period, now);
1224 /* See how many periods were missed. */
1225 while (next_period < now) {
1226 next_period += data->deadline_us;
1227 data->missed_periods++;
1228 }
1229 } else if (now < period) {
1230 u64 delta = period - now;
1231 /*
1232 * Currently, there's no way to find when the period actually
1233 * does begin. If the first runtime starts late, due to another
1234 * deadline task with a shorter deadline running, then it is
1235 * possible that the next period comes in quicker than we
1236 * expect it to.
1237 *
1238 * Adjust the period to start at now, and record the shift.
1239 */
1240 ftrace_write(data->buff,
1241 "Adjusting period: now: %lld period: %lld delta:%lld%s\n",
1242 now, period, delta, delta > data->deadline_us / 2 ?
1243 " HUGE ADJUSTMENT" : "");
1244 data->total_adjust += delta;
1245 data->nr_adjust++;
1246 period = now;
1247 next_period = period + data->deadline_us;
1248 }
1249
1250 ftrace_write(data->buff, "start at %lld off=%lld (period=%lld next=%lld)\n",
1251 now, now - period, period, next_period);
1252
1253 /* Run the simulate task (loops) */
1254 time = run_loops(data, data->loops_per_period);
1255
1256 end = get_time_us();
1257
1258 /* Did we make our deadline? */
1259 if (end > next_period) {
1260 ftrace_write(data->buff,
1261 "Failed runtime by %lld\n", end - next_period);
1262 data->missed_deadlines++;
1263 /*
1264 * We missed our deadline, which means we entered the
1265 * next period. Move it forward one, if we moved it too
1266 * much, then the next interation will adjust.
1267 */
1268 next_period += data->deadline_us;
1269 }
1270
1271
1272 diff = end - now;
1273 if (diff > data->max_time)
1274 data->max_time = diff;
1275 if (!data->min_time || diff < data->min_time)
1276 data->min_time = diff;
1277
1278 data->last_time = time;
1279 data->total_time += diff;
1280 data->nr_periods++;
1281 ftrace_write(data->buff,
1282 "end at %lld diff: %lld run loops: %lld us\n", end, diff, time);
1283
1284 return next_period;
1285 }
1286
1287 /**
1288 * run_deadline - Run deadline thread
1289 * @data: sched_data descriptor
1290 *
1291 * This is called by pthread_create() and executes the sched deadline
1292 * task. @data has the following:
1293 *
1294 * Input:
1295 * @data->runtime_us: The amount of requested runtime in microseconds
1296 * @data->deadline_us: The requested deadline in microseconds
1297 * @data->loops_per_period: The number of loops to make during its runtime
1298 *
1299 * Output:
1300 * @data->tid: The thread ID
1301 * @data->vol: The number of times the thread voluntarily scheduled out
1302 * @data->nonvol: The number of times the thread non-voluntarily scheduled out
1303 * @data->migrate: The number of times the thread migrated across CPUs.
1304 */
1305 void *run_deadline(void *data)
1306 {
1307 struct sched_data *sched_data = data;
1308 struct sched_attr attr;
1309 int vol, nonvol, migrate;
1310 long tid = gettid();
1311 void *heap;
1312 u64 period;
1313 int ret;
1314
1315 /*
1316 * The internal glibc vsnprintf() used by ftrace_write()
1317 * may alloc more space to do conversions. Alloc a bunch of
1318 * memory and free it, and hopefully glibc doesn't return that
1319 * back to the system (we did do an mlockall after all).
1320 */
1321 heap = malloc(1000000);
1322 if (!heap) {
1323 perror("malloc");
1324 fail = 1;
1325 pthread_barrier_wait(&barrier);
1326 pthread_exit("Failed to alloc heap");
1327 return NULL;
1328 }
1329 free(heap);
1330
1331 printf("deadline thread %ld\n", tid);
1332
1333 sched_data->tid = tid;
1334 sched_data->prime = 2;
1335
1336 ret = sched_getattr(0, &attr, sizeof(attr), 0);
1337 if (ret < 0) {
1338 fprintf(stderr, "[%ld]", tid);
1339 perror("sched_getattr");
1340 fail = 1;
1341 pthread_barrier_wait(&barrier);
1342 pthread_exit("Failed sched_getattr");
1343 return NULL;
1344 }
1345
1346 pthread_barrier_wait(&barrier);
1347
1348 if (fail)
1349 return NULL;
1350
1351 attr.sched_policy = SCHED_DEADLINE;
1352 attr.sched_runtime = sched_data->runtime_us * 1000;
1353 attr.sched_deadline = sched_data->deadline_us * 1000;
1354
1355 printf("thread[%d] runtime=%lldus deadline=%lldus loops=%lld\n",
1356 gettid(), sched_data->runtime_us,
1357 sched_data->deadline_us, sched_data->loops_per_period);
1358
1359 pthread_barrier_wait(&barrier);
1360
1361 ret = sched_setattr(0, &attr, 0);
1362 if (ret < 0) {
1363 done = 0;
1364 fprintf(stderr, "[%ld]", tid);
1365 perror("sched_setattr");
1366 fail = 1;
1367 pthread_barrier_wait(&barrier);
1368 pthread_exit("Failed sched_setattr");
1369 return NULL;
1370 }
1371
1372 pthread_barrier_wait(&barrier);
1373
1374 if (fail)
1375 return NULL;
1376
1377 sched_yield();
1378 period = get_time_us();
1379
1380 while (!done) {
1381 period = do_runtime(sched_data, period);
1382 sched_yield();
1383 }
1384 ret = sched_getattr(0, &attr, sizeof(attr), 0);
1385 if (ret < 0) {
1386 perror("sched_getattr");
1387 pthread_exit("Failed second sched_getattr");
1388 }
1389
1390 read_ctx_switches(&vol, &nonvol, &migrate);
1391
1392 sched_data->vol = vol;
1393 sched_data->nonvol = nonvol;
1394 sched_data->migrate = migrate;
1395
1396 return NULL;
1397 }
1398
1399 /**
1400 * run_rt_spin - the Real-Time task spinner
1401 * @data: The sched_data descriptor
1402 *
1403 * This function is called as a thread function. It will read @data->prio
1404 * and set its priority base on that parameter. It sets @data->tid to the
1405 * thread ID. Then after waiting through pthread barriers to sync with
1406 * the main thread as well as with sched deadline threads, it will
1407 * run in a tight loop until the global variable "done" is set.
1408 */
1409 void *run_rt_spin(void *data)
1410 {
1411 struct sched_data *sched_data = data;
1412 long tid = gettid();
1413
1414 sched_data->tid = tid;
1415
1416 if (set_prio(sched_data->prio) < 0) {
1417 fail = 1;
1418 pthread_barrier_wait(&barrier);
1419 pthread_exit("Failed setting prio");
1420 return NULL;
1421 }
1422
1423 pthread_barrier_wait(&barrier);
1424
1425 if (fail)
1426 return NULL;
1427
1428 pthread_barrier_wait(&barrier);
1429
1430 if (fail)
1431 return NULL;
1432
1433 pthread_barrier_wait(&barrier);
1434
1435 if (fail)
1436 return NULL;
1437
1438 while (!done)
1439 get_time_us();
1440
1441 return NULL;
1442 }
1443
1444 struct cpu_list {
1445 struct cpu_list *next;
1446 int start_cpu;
1447 int end_cpu;
1448 };
1449
1450 /**
1451 * add_cpus - Add cpus to cpu_list based on the passed in range
1452 * @cpu_list: The cpu list to add to
1453 * @start_cpu: The start of the range to add
1454 * @end_cpu: The end of the range to add.
1455 *
1456 * Adds a sorted unique item into @cpu_list based on @start_cpu and @end_cpu.
1457 * It removes duplicates in @cpu_list, and will even merge lists if a
1458 * new range is entered that will fill a gap. That is, if @cpu_list has
1459 * "1-3" and "6-7", and @start_cpu is 4 and @end_cpu is 5, it will combined
1460 * the two elements into a single list item of "1-7".
1461 */
1462 static void add_cpus(struct cpu_list **cpu_list, int start_cpu, int end_cpu)
1463 {
1464 struct cpu_list *list;
1465
1466 while (*cpu_list && (*cpu_list)->end_cpu + 1 < start_cpu)
1467 cpu_list = &(*cpu_list)->next;
1468
1469 if (!*cpu_list) {
1470 *cpu_list = malloc(sizeof(struct cpu_list));
1471 (*cpu_list)->start_cpu = start_cpu;
1472 (*cpu_list)->end_cpu = end_cpu;
1473 (*cpu_list)->next = NULL;
1474 return;
1475 }
1476
1477 /* Look to concatinate */
1478 if (end_cpu > (*cpu_list)->start_cpu &&
1479 start_cpu <= (*cpu_list)->end_cpu + 1) {
1480 if (start_cpu < (*cpu_list)->start_cpu)
1481 (*cpu_list)->start_cpu = start_cpu;
1482 list = (*cpu_list)->next;
1483 while (list && list->start_cpu <= end_cpu + 1) {
1484 (*cpu_list)->end_cpu = list->end_cpu;
1485 (*cpu_list)->next = list->next;
1486 free(list);
1487 list = (*cpu_list)->next;
1488 }
1489 if ((*cpu_list)->end_cpu < end_cpu)
1490 (*cpu_list)->end_cpu = end_cpu;
1491 return;
1492 }
1493
1494 /* Check for overlaps */
1495 if (end_cpu >= (*cpu_list)->start_cpu - 1) {
1496 (*cpu_list)->start_cpu = start_cpu;
1497 return;
1498 }
1499
1500 list = malloc(sizeof(struct cpu_list));
1501 list->start_cpu = start_cpu;
1502 list->end_cpu = end_cpu;
1503 list->next = (*cpu_list)->next;
1504 (*cpu_list)->next = list;
1505 }
1506
1507 /**
1508 * count_cpus - Return the number of CPUs in a list
1509 * @cpu_list: The list of CPUs to count
1510 *
1511 * Reads the list of CPUs in @cpu_list. It als will free the
1512 * list as it reads it, so this can only be called once on @cpu_list.
1513 * It also checks if the CPUs in @cpu_list are less than cpu_count
1514 * (the number of discovered CPUs).
1515 *
1516 * Returns the number of CPUs in @cpu_list, or -1 if any CPU in
1517 * @cpu_list is greater or equal to cpu_count.
1518 */
1519 static int count_cpus(struct cpu_list *cpu_list)
1520 {
1521 struct cpu_list *list;
1522 int cpus = 0;
1523 int fail = 0;
1524
1525 while (cpu_list) {
1526 list = cpu_list;
1527 cpus += (list->end_cpu - list->start_cpu) + 1;
1528 if (list->end_cpu >= cpu_count)
1529 fail = 1;
1530 cpu_list = list->next;
1531 free(list);
1532 }
1533 return fail ? -1 : cpus;
1534 }
1535
1536 /**
1537 * append_cpus - Append a set of consecutive cpus to a string
1538 * @buf: The string to append to
1539 * @start: The cpu to start at.
1540 * @end: The cpu to end at.
1541 * @comma: The "," or "" to append before the cpu list.
1542 * @total: The total length of buf.
1543 *
1544 * Realloc @buf to include @comma@start-@end.
1545 * Updates @total to the new length of @buf.
1546 */
1547 static char *append_cpus(char *buf, int start, int end,
1548 const char *comma, int *total)
1549 {
1550 int len;
1551
1552 if (start == end) {
1553 len = snprintf(NULL, 0, "%s%d", comma, start);
1554 buf = realloc(buf, *total + len + 1);
1555 buf[*total] = 0;
1556 snprintf(buf + *total, len + 1, "%s%d", comma, start);
1557 } else {
1558 len = snprintf(NULL, 0, "%s%d-%d", comma, start, end);
1559 buf = realloc(buf, *total + len + 1);
1560 buf[*total] = 0;
1561 snprintf(buf + *total, len + 1, "%s%d-%d", comma,
1562 start, end);
1563 }
1564 *total += len;
1565 return buf;
1566 }
1567
1568 /**
1569 * make_new_list - convert cpu_list into a string
1570 * @cpu_list: The list of CPUs to include
1571 * @buf: The pointer to the allocated string to return
1572 *
1573 * Reads @cpu_list which contains a link list of consecutive
1574 * CPUs, and returns the combined list in @buf.
1575 * If cpu_list has "1", "3" and "6-8", buf would return
1576 * "1,3,6-8"
1577 */
1578 static void make_new_list(struct cpu_list *cpu_list, char **buf)
1579 {
1580 char *comma = "";
1581 int total = 0;
1582
1583 while (cpu_list) {
1584 *buf = append_cpus(*buf, cpu_list->start_cpu, cpu_list->end_cpu,
1585 comma, &total);
1586 comma = ",";
1587 cpu_list = cpu_list->next;
1588 }
1589 }
1590
1591 /**
1592 * make_other_cpu_list - parse cpu list and return all other CPUs
1593 * @setcpu: string listing the CPUs to exclude
1594 * @cpus: The buffer to return the list of CPUs not in setcpu.
1595 *
1596 * @setcpu is expected to be compressed by calc_nr_cpus().
1597 *
1598 * Reads @setcpu and uses cpu_count (number of all CPUs), to return
1599 * a list of CPUs not included in @setcpu. For example, if
1600 * @setcpu is "1-5" and cpu_count is 8, then @cpus would contain
1601 * "0,6-7".
1602 */
1603 static void make_other_cpu_list(const char *setcpu, char **cpus)
1604 {
1605 const char *p = setcpu;
1606 const char *comma = "";
1607 int curr_cpu = 0;
1608 int cpu;
1609 int total = 0;
1610
1611 while (*p && curr_cpu < cpu_count) {
1612 cpu = atoi(p);
1613 if (cpu > curr_cpu) {
1614 *cpus = append_cpus(*cpus, curr_cpu, cpu - 1,
1615 comma, &total);
1616 comma = ",";
1617 }
1618 while (isdigit(*p))
1619 p++;
1620 if (*p == '-') {
1621 p++;
1622 cpu = atoi(p);
1623 while (isdigit(*p))
1624 p++;
1625 }
1626 curr_cpu = cpu + 1;
1627 if (*p)
1628 p++;
1629 }
1630
1631 if (curr_cpu < cpu_count) {
1632 *cpus = append_cpus(*cpus, curr_cpu, cpu_count - 1,
1633 comma, &total);
1634 }
1635 }
1636
1637 /**
1638 * calc_nr_cpus - parse cpu list for list of cpus.
1639 * @setcpu: string listing the CPUs to include
1640 * @buf: The buffer to return as a compressed list.
1641 *
1642 * Reads @setcpu and removes duplicates, it also sets @buf to be
1643 * a consolidated list. For example, if @setcpu is "1,2,4,3-5"
1644 * @buf would become "1-5" and 5 would be returned.
1645 *
1646 * Returns the number of cpus listed in @setcpu.
1647 */
1648 static int calc_nr_cpus(const char *setcpu, char **buf)
1649 {
1650 struct cpu_list *cpu_list = NULL;
1651 const char *p;
1652 int end_cpu;
1653 int cpu;
1654
1655 for (p = setcpu; *p; ) {
1656 cpu = atoi(p);
1657 if (cpu < 0 || (!cpu && *p != '0'))
1658 goto err;
1659
1660 while (isdigit(*p))
1661 p++;
1662 if (*p == '-') {
1663 p++;
1664 end_cpu = atoi(p);
1665 if (end_cpu < cpu || (!end_cpu && *p != '0'))
1666 goto err;
1667 while (isdigit(*p))
1668 p++;
1669 } else
1670 end_cpu = cpu;
1671
1672 add_cpus(&cpu_list, cpu, end_cpu);
1673 if (*p == ',')
1674 p++;
1675 }
1676
1677 make_new_list(cpu_list, buf);
1678 return count_cpus(cpu_list);
1679 err:
1680 /* Frees the list */
1681 count_cpus(cpu_list);
1682 return -1;
1683 }
1684
1685 static const char *join_thread(pthread_t *thread)
1686 {
1687 void *result;
1688
1689 pthread_join(*thread, &result);
1690 return result;
1691 }
1692
1693 static void do_sleep(u64 next)
1694 {
1695 struct timespec req;
1696
1697 req.tv_nsec = next * 1000;
1698 req.tv_sec = 0;
1699 while (req.tv_nsec > 1000000000UL) {
1700 req.tv_nsec -= 1000000000UL;
1701 req.tv_sec++;
1702 }
1703 nanosleep(&req, NULL);
1704 }
1705
1706 /**
1707 * calculate_loops_per_ms - calculate the number of loops per ms
1708 * @overhead: Return the overhead of the call around run_loops()
1709 *
1710 * Runs the do_runtime() to see how long it takes. That returns
1711 * how long the loops took (data->last_time), and the overhead can
1712 * be calculated by that diff.
1713 *
1714 * Returns the length of time it took to run for 1000 loops.
1715 */
1716 static u64 calculate_loops_per_ms(u64 *overhead)
1717 {
1718 struct sched_data sd = { };
1719 u64 test_loops = 100000;
1720 u64 loops;
1721 u64 diff;
1722 u64 odiff;
1723 u64 start;
1724 u64 end;
1725
1726 sd.prime = 2;
1727
1728 /* Sleep 1ms to help flush a bit of cache */
1729 do_sleep(1000);
1730
1731 start = run_loops(&sd, test_loops);
1732
1733 sd.deadline_us = start * 2;
1734 sd.runtime_us = start;
1735 sd.loops_per_period = test_loops;
1736
1737 /* Again try to dirty some cache */
1738 do_sleep(1000);
1739
1740 start = get_time_us();
1741 do_runtime(&sd, start + sd.deadline_us);
1742 end = get_time_us();
1743
1744 diff = end - start;
1745
1746 /*
1747 * Based on the time it took to run test_loops, figure
1748 * out how many loops it may take to run for 1000us.
1749 *
1750 * last_time / test_loops = 1000us / loops
1751 * or
1752 * loops = test_loops * 1000us / last_time
1753 */
1754
1755 loops = 1000ULL * test_loops / sd.last_time;
1756
1757 printf("%lld test loops took %lldus total (%lld internal)\n"
1758 "calculated loops for 1000us=%lld\n",
1759 test_loops, diff, sd.last_time, loops);
1760
1761 sd.deadline_us = 2000;
1762 sd.runtime_us = 1000;
1763 sd.loops_per_period = loops;
1764
1765 test_loops = loops;
1766
1767 do_sleep(1000);
1768
1769 start = get_time_us();
1770 do_runtime(&sd, start + sd.deadline_us);
1771 end = get_time_us();
1772
1773 odiff = end - start;
1774
1775 /*
1776 * Use this new calcualtion to recalculate the number of loops
1777 * for 1000us
1778 */
1779 loops = 1000ULL * loops / sd.last_time;
1780
1781 *overhead = odiff - sd.last_time;
1782
1783 printf("%lld test loops took %lldus total (%lld internal)\n"
1784 "New calculated loops for 1000us=%lld\n"
1785 "Diff from last calculation: %lld loops\n",
1786 test_loops, odiff, sd.last_time, loops, loops - test_loops);
1787
1788 return loops;
1789 }
1790
1791 int main(int argc, char **argv)
1792 {
1793 struct sched_data *sched_data;
1794 struct sched_data *sd;
1795 struct sched_data rt_sched_data;
1796 const char *res;
1797 const char *setcpu = NULL;
1798 char *setcpu_buf = NULL;
1799 char *allcpu_buf = NULL;
1800 pthread_t *thread;
1801 pthread_t rt_thread;
1802 unsigned int interval = 1000;
1803 unsigned int step = 500;
1804 u64 loop_time;
1805 u64 loops;
1806 u64 runtime;
1807 u64 overhead;
1808 u64 start_period;
1809 u64 end_period;
1810 int nr_cpus;
1811 int all_cpus = 1;
1812 int run_percent = 100;
1813 int percent = 80;
1814 int rt_task = 0;
1815 int i;
1816 int c;
1817 int ret;
1818
1819 cpu_count = sysconf(_SC_NPROCESSORS_CONF);
1820 if (cpu_count < 1) {
1821 fprintf(stderr, "Can not calculate number of CPUS\n");
1822 exit(-1);
1823 }
1824
1825 while ((c = getopt(argc, argv, "+hbr:c:i:p:P:t:s:")) >= 0) {
1826 switch (c) {
1827 case 'b':
1828 all_cpus = 0;
1829 break;
1830 case 'c':
1831 all_cpus = 0;
1832 setcpu = optarg;
1833 break;
1834 case 'i':
1835 interval = atoi(optarg);
1836 break;
1837 case 'p':
1838 percent = atoi(optarg);
1839 break;
1840 case 'P':
1841 run_percent = atoi(optarg);
1842 break;
1843 case 's':
1844 step = atoi(optarg);
1845 break;
1846 case 't':
1847 nr_threads = atoi(optarg);
1848 break;
1849 case 'r':
1850 rt_task = atoi(optarg);
1851 break;
1852 case 'h':
1853 usage(0);
1854 break;
1855 default:
1856 usage(1);
1857 }
1858 }
1859
1860 if (rt_task < 0 || rt_task > 98) {
1861 fprintf(stderr, "RT task can only be from 1 to 98\n");
1862 exit(-1);
1863 }
1864
1865 if (percent < 1 || percent > 100 || run_percent < 1 || run_percent > 100) {
1866 fprintf(stderr, "Percent must be between 1 and 100\n");
1867 exit(-1);
1868 }
1869
1870 if (nr_threads < 1) {
1871 fprintf(stderr, "The number of threads must be at least 1\n");
1872 exit(-1);
1873 }
1874
1875 if (setcpu) {
1876 nr_cpus = calc_nr_cpus(setcpu, &setcpu_buf);
1877 if (nr_cpus < 0) {
1878 fprintf(stderr, "Invalid cpu input '%s'\n", setcpu);
1879 exit(-1);
1880 }
1881 } else
1882 nr_cpus = 1;
1883
1884 if (all_cpus)
1885 nr_cpus = cpu_count;
1886
1887 if (cpu_count == nr_cpus)
1888 all_cpus = 1;
1889
1890 /* -b has us bind to the last CPU. */
1891 if (!all_cpus && !setcpu) {
1892 setcpu_buf = malloc(12);
1893 if (!setcpu_buf) {
1894 perror("malloc");
1895 exit(-1);
1896 }
1897 sprintf(setcpu_buf, "%d", cpu_count - 1);
1898 setcpu = setcpu_buf;
1899 }
1900
1901 /*
1902 * Now the amount of bandwidth each tasks takes will be
1903 * percent * nr_cpus / nr_threads. Now if nr_threads is
1904 * But the amount of any one thread can not be more than
1905 * 90 of the CPUs.
1906 */
1907 percent = (percent * nr_cpus) / nr_threads;
1908 if (percent > 90)
1909 percent = 90;
1910
1911 cpusetp = CPU_ALLOC(cpu_count);
1912 cpuset_size = CPU_ALLOC_SIZE(cpu_count);
1913 if (!cpusetp) {
1914 perror("allocating cpuset");
1915 exit(-1);
1916 }
1917
1918 setup_ftrace_marker();
1919
1920 thread = calloc(nr_threads, sizeof(*thread));
1921 sched_data = calloc(nr_threads, sizeof(*sched_data));
1922 if (!thread || !sched_data) {
1923 perror("allocating threads");
1924 exit(-1);
1925 }
1926
1927 if (mlockall(MCL_CURRENT|MCL_FUTURE) == -1)
1928 perror("mlockall");
1929
1930 /*
1931 * Run at prio 99 bound to the last CPU, and try to calculate
1932 * the time it takes to run the loops.
1933 */
1934 set_prio(99);
1935 bind_cpu(cpu_count - 1);
1936
1937 loops = calculate_loops_per_ms(&overhead);
1938
1939 printf("Setup:\n");
1940 printf(" percent per task:%d", percent);
1941 if (run_percent < 100)
1942 printf(" run-percent:%d", run_percent);
1943 printf(" nr_cpus:%d", nr_cpus);
1944 if (setcpu)
1945 printf(" (%s)", setcpu);
1946 printf(" loops:%lld overhead:%lldus\n", loops, overhead);
1947
1948 again:
1949 /* Set up the data while sill in SCHED_FIFO */
1950 for (i = 0; i < nr_threads; i++) {
1951 sd = &sched_data[i];
1952 /*
1953 * Interval is the deadline/period
1954 * The runtime is the percentage of that period.
1955 */
1956 runtime = interval * percent / 100;
1957 if (runtime < overhead) {
1958 fprintf(stderr, "Run time too short: %lld us\n",
1959 runtime);
1960 fprintf(stderr, "Read context takes %lld us\n",
1961 overhead);
1962 exit(-1);
1963 }
1964 if (runtime < 2000) {
1965 /*
1966 * If the runtime is less than 2ms, then we better
1967 * have HRTICK enabled.
1968 */
1969 if (!setup_hr_tick()) {
1970 fprintf(stderr, "For less that 2ms run times, you need to\n"
1971 "have HRTICK enabled in debugfs/sched_features\n");
1972 exit(-1);
1973 }
1974 }
1975 sd->runtime_us = runtime;
1976 /* Account for the reading of context switches */
1977 runtime -= overhead;
1978 /*
1979 * loops is # of loops per ms, convert to us and
1980 * take 5% off of it.
1981 * loops * %run_percent / 1000
1982 */
1983 loop_time = runtime * run_percent / 100;
1984 sd->loops_per_period = loop_time * loops / 1000;
1985
1986 sd->deadline_us = interval;
1987
1988 /* Make sure that we can make our deadlines */
1989 start_period = get_time_us();
1990 do_runtime(sd, start_period);
1991 end_period = get_time_us();
1992 if (end_period - start_period > sd->runtime_us) {
1993 printf("Failed to perform task within runtime: Missed by %lld us\n",
1994 end_period - start_period - sd->runtime_us);
1995 overhead += end_period - start_period - sd->runtime_us;
1996 printf("New overhead=%lldus\n", overhead);
1997 goto again;
1998 }
1999
2000 printf(" Tested at %lldus of %lldus\n",
2001 end_period - start_period, sd->runtime_us);
2002
2003 interval += step;
2004 }
2005
2006 set_prio(0);
2007
2008 unbind_cpu();
2009
2010 pthread_barrier_init(&barrier, NULL, nr_threads + 1 + !!rt_task);
2011
2012 for (i = 0; i < nr_threads; i++) {
2013 sd = &sched_data[i];
2014 pthread_create(&thread[i], NULL, run_deadline, sd);
2015 }
2016
2017 if (rt_task) {
2018 /* Make sure we are a higher priority than the spinner */
2019 set_prio(rt_task + 1);
2020
2021 rt_sched_data.prio = rt_task;
2022 pthread_create(&rt_thread, NULL, run_rt_spin, &rt_sched_data);
2023 }
2024
2025 pthread_barrier_wait(&barrier);
2026
2027 if (fail)
2028 exit(-1);
2029
2030 if (!all_cpus) {
2031 int *pids;
2032
2033 atexit(teardown);
2034
2035 make_other_cpu_list(setcpu, &allcpu_buf);
2036
2037 res = make_cpuset(CPUSET_ALL, allcpu_buf, "0",
2038 CPUSET_FL_SET_LOADBALANCE |
2039 CPUSET_FL_CLONE_CHILDREN |
2040 CPUSET_FL_ALL_TASKS);
2041 if (res) {
2042 perror(res);
2043 exit(-1);
2044 }
2045
2046 pids = calloc(nr_threads + !!rt_task + 1, sizeof(int));
2047 if (!pids) {
2048 perror("Allocating pids");
2049 exit(-1);
2050 }
2051
2052 for (i = 0; i < nr_threads; i++)
2053 pids[i] = sched_data[i].tid;
2054 if (rt_task)
2055 pids[i++] = rt_sched_data.tid;
2056
2057 res = make_cpuset(CPUSET_LOCAL, setcpu, "0",
2058 CPUSET_FL_CPU_EXCLUSIVE |
2059 CPUSET_FL_SET_LOADBALANCE |
2060 CPUSET_FL_CLONE_CHILDREN |
2061 CPUSET_FL_TASKS, pids);
2062 free(pids);
2063 if (res) {
2064 perror(res);
2065 fprintf(stderr, "Check if other cpusets exist that conflict\n");
2066 exit(-1);
2067 }
2068
2069 ret = system("cat /sys/fs/cgroup/cpuset/my_cpuset/tasks");
2070 if (ret < 0)
2071 perror("system call failed");
2072 }
2073
2074 pthread_barrier_wait(&barrier);
2075
2076 if (fail)
2077 exit(-1);
2078
2079 pthread_barrier_wait(&barrier);
2080
2081 if (!fail)
2082 sleep(10);
2083
2084 done = 1;
2085 if (rt_task) {
2086 res = join_thread(&rt_thread);
2087 if (res)
2088 printf("RT Thread failed: %s\n", res);
2089 }
2090
2091 for (i = 0; i < nr_threads; i++) {
2092
2093 sd = &sched_data[i];
2094
2095 res = join_thread(&thread[i]);
2096 if (res) {
2097 printf("Thread %d failed: %s\n", i, res);
2098 continue;
2099 }
2100
2101 printf("\n[%d]\n", sd->tid);
2102 printf("missed deadlines = %d\n", sd->missed_deadlines);
2103 printf("missed periods = %d\n", sd->missed_periods);
2104 printf("Total adjustments = %lld us\n", sd->total_adjust);
2105 if (sd->nr_adjust) {
2106 printf("# adjustments = %lld avg: %lld us\n",
2107 sd->nr_adjust, sd->total_adjust / sd->nr_adjust);
2108 }
2109 printf("deadline : %lld us\n", sd->deadline_us);
2110 printf("runtime : %lld us\n", sd->runtime_us);
2111 printf("nr_periods : %lld\n", sd->nr_periods);
2112 printf("max_time: %lldus", sd->max_time);
2113 printf("\tmin_time: %lldus", sd->min_time);
2114 printf("\tavg_time: %lldus\n", sd->total_time / sd->nr_periods);
2115 printf("ctx switches vol:%d nonvol:%d migration:%d\n",
2116 sd->vol, sd->nonvol, sd->migrate);
2117 printf("highest prime: %lld\n", sd->prime);
2118 printf("\n");
2119 }
2120
2121 if (setcpu_buf)
2122 free(setcpu_buf);
2123 free(thread);
2124 free(sched_data);
2125
2126 CPU_FREE(cpusetp);
2127
2128 return 0;
2129 }